USE [master]
GO
/****** Object:  Database [MainDB]    Script Date: 2018/9/25 12:40:10 ******/
CREATE DATABASE [MainDB]
 CONTAINMENT = NONE
 ON  PRIMARY 
( NAME = N'MainDB_Primary', FILENAME = N'D:\SqlserverData\MainDB\MainDB.mdf' , SIZE = 15432640KB , MAXSIZE = UNLIMITED, FILEGROWTH = 51200KB ), 
 FILEGROUP [BOthers] 
( NAME = N'MainDB_BOthers', FILENAME = N'D:\SqlserverData\MainDB\MainDB_BOthers.ndf' , SIZE = 9005056KB , MAXSIZE = UNLIMITED, FILEGROWTH = 51200KB ), 
 FILEGROUP [CP] 
( NAME = N'MainDB_CP1', FILENAME = N'D:\SqlserverData\MainDB\MainDB_CP1.ndf' , SIZE = 15281536KB , MAXSIZE = UNLIMITED, FILEGROWTH = 51200KB ),
( NAME = N'MainDB_CP2', FILENAME = N'D:\SqlserverData\MainDB\MainDB_CP2.ndf' , SIZE = 2468864KB , MAXSIZE = UNLIMITED, FILEGROWTH = 10240KB ), 
 FILEGROUP [CV] 
( NAME = N'MainDB_CV1', FILENAME = N'D:\SqlserverData\MainDB\MainDB_CV1.ndf' , SIZE = 36328640KB , MAXSIZE = UNLIMITED, FILEGROWTH = 51200KB ),
( NAME = N'MainDB_CV2', FILENAME = N'D:\SqlserverData\MainDB\MainDB_CV2.ndf' , SIZE = 4676224KB , MAXSIZE = UNLIMITED, FILEGROWTH = 10240KB ), 
 FILEGROUP [Finance] 
( NAME = N'MainDB_Finance', FILENAME = N'D:\SqlserverData\MainDB\MainDB_Finance.ndf' , SIZE = 153664KB , MAXSIZE = UNLIMITED, FILEGROWTH = 10240KB ), 
 FILEGROUP [FOthers] 
( NAME = N'MainDB_FOthers', FILENAME = N'D:\SqlserverData\MainDB\MainDB_FOthers.ndf' , SIZE = 2846080KB , MAXSIZE = UNLIMITED, FILEGROWTH = 10240KB ), 
 FILEGROUP [ftfg_cpMainCatalog] 
( NAME = N'ftrow_cpMainCatalog', FILENAME = N'D:\SqlserverData\MainDB\FtData\ftrow_cpMainCatalog.ndf' , SIZE = 892736KB , MAXSIZE = UNLIMITED, FILEGROWTH = 10%), 
 FILEGROUP [ftfg_cpPublishCatalog] 
( NAME = N'ftrow_cpPublishCatalog', FILENAME = N'D:\SqlserverData\MainDB\FtData\ftrow_cpPublishCatalog.ndf' , SIZE = 1581696KB , MAXSIZE = UNLIMITED, FILEGROWTH = 10%), 
 FILEGROUP [ftfg_cvinfo] 
( NAME = N'ftrow_cvinfo', FILENAME = N'D:\SqlserverData\MainDB\FtData\ftrow_cvinfo.ndf' , SIZE = 1913920KB , MAXSIZE = UNLIMITED, FILEGROWTH = 10%), 
 FILEGROUP [ftfg_cvPublishCatalog] 
( NAME = N'ftrow_cvPublishCatalog', FILENAME = N'D:\SqlserverData\MainDB\FtData\ftrow_cvPublishCatalog.ndf' , SIZE = 737792KB , MAXSIZE = UNLIMITED, FILEGROWTH = 10%), 
 FILEGROUP [ftfg_cvVerifyCatalog] 
( NAME = N'ftrow_cvVerifyCatalog', FILENAME = N'D:\SqlserverData\MainDB\FtData\ftrow_cvVerifyCatalog.ndf' , SIZE = 416384KB , MAXSIZE = UNLIMITED, FILEGROWTH = 10%), 
 FILEGROUP [ftfg_QlrcNews] 
( NAME = N'ftrow_QlrcNews', FILENAME = N'D:\SqlserverData\MainDB\FtData\ftrow_QlrcNews.ndf' , SIZE = 458048KB , MAXSIZE = UNLIMITED, FILEGROWTH = 10%), 
 FILEGROUP [HR] 
( NAME = N'MainDB_HR', FILENAME = N'D:\SqlserverData\MainDB\MainDB_HR.ndf' , SIZE = 2048KB , MAXSIZE = UNLIMITED, FILEGROWTH = 10240KB ), 
 FILEGROUP [Index] 
( NAME = N'MainDB_Index1', FILENAME = N'D:\SqlserverData\MainDB\MainDB_Index1.ndf' , SIZE = 92536768KB , MAXSIZE = UNLIMITED, FILEGROWTH = 51200KB ),
( NAME = N'MainDB_Index2', FILENAME = N'D:\SqlserverData\MainDB\MainDB_Index2.ndf' , SIZE = 9358336KB , MAXSIZE = UNLIMITED, FILEGROWTH = 51200KB ), 
 FILEGROUP [Interaction] 
( NAME = N'MainDB_Interaction', FILENAME = N'D:\SqlserverData\MainDB\MainDB_Interaction.ndf' , SIZE = 1533312KB , MAXSIZE = UNLIMITED, FILEGROWTH = 10240KB ), 
 FILEGROUP [Market] 
( NAME = N'MainDB_Market', FILENAME = N'D:\SqlserverData\MainDB\MainDB_Market.ndf' , SIZE = 3409920KB , MAXSIZE = UNLIMITED, FILEGROWTH = 10240KB ), 
 FILEGROUP [OA] 
( NAME = N'MainDB_OA', FILENAME = N'D:\SqlserverData\MainDB\MainDB_OA.ndf' , SIZE = 3968KB , MAXSIZE = UNLIMITED, FILEGROWTH = 10240KB ), 
 FILEGROUP [Spread1] 
( NAME = N'MainDB_Spread1', FILENAME = N'D:\SqlserverData\MainDB\MainDB_Spread1.ndf' , SIZE = 442496KB , MAXSIZE = UNLIMITED, FILEGROWTH = 51200KB ), 
 FILEGROUP [Spread2] 
( NAME = N'MainDB_Spread2', FILENAME = N'D:\SqlserverData\MainDB\MainDB_Spread2.ndf' , SIZE = 8827776KB , MAXSIZE = UNLIMITED, FILEGROWTH = 51200KB )
 LOG ON 
( NAME = N'MainDB_log', FILENAME = N'D:\SqlserverData\MainDB\MainDB_log.ldf' , SIZE = 77382080KB , MAXSIZE = 2048GB , FILEGROWTH = 51200KB )
 COLLATE Chinese_PRC_CI_AS
GO
ALTER DATABASE [MainDB] SET COMPATIBILITY_LEVEL = 100
GO
IF (1 = FULLTEXTSERVICEPROPERTY('IsFullTextInstalled'))
begin
EXEC [MainDB].[dbo].[sp_fulltext_database] @action = 'enable'
end
GO
ALTER DATABASE [MainDB] SET ANSI_NULL_DEFAULT OFF 
GO
ALTER DATABASE [MainDB] SET ANSI_NULLS OFF 
GO
ALTER DATABASE [MainDB] SET ANSI_PADDING OFF 
GO
ALTER DATABASE [MainDB] SET ANSI_WARNINGS OFF 
GO
ALTER DATABASE [MainDB] SET ARITHABORT OFF 
GO
ALTER DATABASE [MainDB] SET AUTO_CLOSE OFF 
GO
ALTER DATABASE [MainDB] SET AUTO_SHRINK OFF 
GO
ALTER DATABASE [MainDB] SET AUTO_UPDATE_STATISTICS ON 
GO
ALTER DATABASE [MainDB] SET CURSOR_CLOSE_ON_COMMIT OFF 
GO
ALTER DATABASE [MainDB] SET CURSOR_DEFAULT  GLOBAL 
GO
ALTER DATABASE [MainDB] SET CONCAT_NULL_YIELDS_NULL OFF 
GO
ALTER DATABASE [MainDB] SET NUMERIC_ROUNDABORT OFF 
GO
ALTER DATABASE [MainDB] SET QUOTED_IDENTIFIER OFF 
GO
ALTER DATABASE [MainDB] SET RECURSIVE_TRIGGERS OFF 
GO
ALTER DATABASE [MainDB] SET  DISABLE_BROKER 
GO
ALTER DATABASE [MainDB] SET AUTO_UPDATE_STATISTICS_ASYNC OFF 
GO
ALTER DATABASE [MainDB] SET DATE_CORRELATION_OPTIMIZATION OFF 
GO
ALTER DATABASE [MainDB] SET TRUSTWORTHY OFF 
GO
ALTER DATABASE [MainDB] SET ALLOW_SNAPSHOT_ISOLATION OFF 
GO
ALTER DATABASE [MainDB] SET PARAMETERIZATION SIMPLE 
GO
ALTER DATABASE [MainDB] SET READ_COMMITTED_SNAPSHOT OFF 
GO
ALTER DATABASE [MainDB] SET PARTNER TIMEOUT 10 
GO
ALTER DATABASE [MainDB] SET HONOR_BROKER_PRIORITY OFF 
GO
ALTER DATABASE [MainDB] SET RECOVERY FULL 
GO
ALTER DATABASE [MainDB] SET  MULTI_USER 
GO
ALTER DATABASE [MainDB] SET PAGE_VERIFY NONE  
GO
ALTER DATABASE [MainDB] SET DB_CHAINING OFF 
GO
ALTER DATABASE [MainDB] SET FILESTREAM( NON_TRANSACTED_ACCESS = OFF ) 
GO
ALTER DATABASE [MainDB] SET TARGET_RECOVERY_TIME = 0 SECONDS 
GO
ALTER DATABASE [MainDB] SET DELAYED_DURABILITY = DISABLED 
GO
EXEC sys.sp_db_vardecimal_storage_format N'MainDB', N'ON'
GO
ALTER DATABASE [MainDB] SET QUERY_STORE = OFF
GO
USE [MainDB]
GO
ALTER DATABASE SCOPED CONFIGURATION SET MAXDOP = 0;
GO
ALTER DATABASE SCOPED CONFIGURATION FOR SECONDARY SET MAXDOP = PRIMARY;
GO
ALTER DATABASE SCOPED CONFIGURATION SET LEGACY_CARDINALITY_ESTIMATION = OFF;
GO
ALTER DATABASE SCOPED CONFIGURATION FOR SECONDARY SET LEGACY_CARDINALITY_ESTIMATION = PRIMARY;
GO
ALTER DATABASE SCOPED CONFIGURATION SET PARAMETER_SNIFFING = ON;
GO
ALTER DATABASE SCOPED CONFIGURATION FOR SECONDARY SET PARAMETER_SNIFFING = PRIMARY;
GO
ALTER DATABASE SCOPED CONFIGURATION SET QUERY_OPTIMIZER_HOTFIXES = OFF;
GO
ALTER DATABASE SCOPED CONFIGURATION FOR SECONDARY SET QUERY_OPTIMIZER_HOTFIXES = PRIMARY;
GO
USE [MainDB]
GO
/****** Object:  DatabaseRole [MSReplPAL_5_9]    Script Date: 2018/9/25 12:40:10 ******/
CREATE ROLE [MSReplPAL_5_9]
GO
/****** Object:  DatabaseRole [MSReplPAL_5_8]    Script Date: 2018/9/25 12:40:10 ******/
CREATE ROLE [MSReplPAL_5_8]
GO
/****** Object:  DatabaseRole [MSReplPAL_5_3]    Script Date: 2018/9/25 12:40:10 ******/
CREATE ROLE [MSReplPAL_5_3]
GO
/****** Object:  DatabaseRole [MSReplPAL_5_2]    Script Date: 2018/9/25 12:40:10 ******/
CREATE ROLE [MSReplPAL_5_2]
GO
/****** Object:  DatabaseRole [MSReplPAL_14_8]    Script Date: 2018/9/25 12:40:10 ******/
CREATE ROLE [MSReplPAL_14_8]
GO
/****** Object:  DatabaseRole [MSReplPAL_14_7]    Script Date: 2018/9/25 12:40:10 ******/
CREATE ROLE [MSReplPAL_14_7]
GO
/****** Object:  DatabaseRole [MSReplPAL_14_6]    Script Date: 2018/9/25 12:40:10 ******/
CREATE ROLE [MSReplPAL_14_6]
GO
/****** Object:  DatabaseRole [MSReplPAL_14_2]    Script Date: 2018/9/25 12:40:10 ******/
CREATE ROLE [MSReplPAL_14_2]
GO
ALTER ROLE [db_owner] ADD MEMBER [udjjqnfoekdafea]
GO
ALTER ROLE [db_owner] ADD MEMBER [qqwsswrfvbhhhyj]
GO
/****** Object:  Schema [MSReplPAL_5_2]    Script Date: 2018/9/25 12:40:10 ******/
CREATE SCHEMA [MSReplPAL_5_2]
GO
/****** Object:  Schema [MSReplPAL_5_3]    Script Date: 2018/9/25 12:40:10 ******/
CREATE SCHEMA [MSReplPAL_5_3]
GO
/****** Object:  Schema [MSReplPAL_5_8]    Script Date: 2018/9/25 12:40:10 ******/
CREATE SCHEMA [MSReplPAL_5_8]
GO
/****** Object:  Schema [MSReplPAL_5_9]    Script Date: 2018/9/25 12:40:10 ******/
CREATE SCHEMA [MSReplPAL_5_9]
GO
/****** Object:  FullTextCatalog [cpMainCatalog]    Script Date: 2018/9/25 12:40:11 ******/
CREATE FULLTEXT CATALOG [cpMainCatalog]WITH ACCENT_SENSITIVITY = ON

GO
/****** Object:  FullTextCatalog [cpPublishCatalog]    Script Date: 2018/9/25 12:40:11 ******/
CREATE FULLTEXT CATALOG [cpPublishCatalog]WITH ACCENT_SENSITIVITY = ON

GO
/****** Object:  FullTextCatalog [cvinfo]    Script Date: 2018/9/25 12:40:11 ******/
CREATE FULLTEXT CATALOG [cvinfo]WITH ACCENT_SENSITIVITY = ON

GO
/****** Object:  FullTextCatalog [cvPublishCatalog]    Script Date: 2018/9/25 12:40:11 ******/
CREATE FULLTEXT CATALOG [cvPublishCatalog]WITH ACCENT_SENSITIVITY = ON

GO
/****** Object:  FullTextCatalog [cvVerifyCatalog]    Script Date: 2018/9/25 12:40:11 ******/
CREATE FULLTEXT CATALOG [cvVerifyCatalog]WITH ACCENT_SENSITIVITY = ON

GO
/****** Object:  FullTextCatalog [QlrcNews]    Script Date: 2018/9/25 12:40:11 ******/
CREATE FULLTEXT CATALOG [QlrcNews]WITH ACCENT_SENSITIVITY = ON

GO
/****** Object:  PartitionFunction [ifts_comp_fragment_partition_function_00115387]    Script Date: 2018/9/25 12:40:11 ******/
CREATE PARTITION FUNCTION [ifts_comp_fragment_partition_function_00115387](varbinary(128)) AS RANGE LEFT FOR VALUES (0x5B9E8DF5)
GO
/****** Object:  PartitionFunction [ifts_comp_fragment_partition_function_0ECD7B4C]    Script Date: 2018/9/25 12:40:11 ******/
CREATE PARTITION FUNCTION [ifts_comp_fragment_partition_function_0ECD7B4C](varbinary(128)) AS RANGE LEFT FOR VALUES (0x5C40)
GO
/****** Object:  PartitionFunction [ifts_comp_fragment_partition_function_25E1F6B4]    Script Date: 2018/9/25 12:40:11 ******/
CREATE PARTITION FUNCTION [ifts_comp_fragment_partition_function_25E1F6B4](varbinary(128)) AS RANGE LEFT FOR VALUES (0x5A34)
GO
/****** Object:  PartitionFunction [ifts_comp_fragment_partition_function_272B20A8]    Script Date: 2018/9/25 12:40:11 ******/
CREATE PARTITION FUNCTION [ifts_comp_fragment_partition_function_272B20A8](varbinary(128)) AS RANGE LEFT FOR VALUES (0x51FA56FD, 0x6C347535)
GO
/****** Object:  PartitionFunction [ifts_comp_fragment_partition_function_319397BA]    Script Date: 2018/9/25 12:40:11 ******/
CREATE PARTITION FUNCTION [ifts_comp_fragment_partition_function_319397BA](varbinary(128)) AS RANGE LEFT FOR VALUES (0x5DE54F5C)
GO
/****** Object:  PartitionFunction [ifts_comp_fragment_partition_function_382ABB59]    Script Date: 2018/9/25 12:40:11 ******/
CREATE PARTITION FUNCTION [ifts_comp_fragment_partition_function_382ABB59](varbinary(128)) AS RANGE LEFT FOR VALUES (0x5C0A656C)
GO
/****** Object:  PartitionFunction [ifts_comp_fragment_partition_function_5F74419A]    Script Date: 2018/9/25 12:40:11 ******/
CREATE PARTITION FUNCTION [ifts_comp_fragment_partition_function_5F74419A](varbinary(128)) AS RANGE LEFT FOR VALUES (0x5E26)
GO
/****** Object:  PartitionFunction [ifts_comp_fragment_partition_function_67E4C43B]    Script Date: 2018/9/25 12:40:11 ******/
CREATE PARTITION FUNCTION [ifts_comp_fragment_partition_function_67E4C43B](varbinary(128)) AS RANGE LEFT FOR VALUES (0x5B895FBD)
GO
/****** Object:  PartitionFunction [IsHistory]    Script Date: 2018/9/25 12:40:11 ******/
CREATE PARTITION FUNCTION [IsHistory](bit) AS RANGE RIGHT FOR VALUES (1)
GO
/****** Object:  PartitionScheme [ifts_comp_fragment_data_space_00115387]    Script Date: 2018/9/25 12:40:11 ******/
CREATE PARTITION SCHEME [ifts_comp_fragment_data_space_00115387] AS PARTITION [ifts_comp_fragment_partition_function_00115387] TO ([ftfg_cvPublishCatalog], [ftfg_cvPublishCatalog])
GO
/****** Object:  PartitionScheme [ifts_comp_fragment_data_space_0ECD7B4C]    Script Date: 2018/9/25 12:40:11 ******/
CREATE PARTITION SCHEME [ifts_comp_fragment_data_space_0ECD7B4C] AS PARTITION [ifts_comp_fragment_partition_function_0ECD7B4C] TO ([ftfg_cpPublishCatalog], [ftfg_cpPublishCatalog])
GO
/****** Object:  PartitionScheme [ifts_comp_fragment_data_space_25E1F6B4]    Script Date: 2018/9/25 12:40:11 ******/
CREATE PARTITION SCHEME [ifts_comp_fragment_data_space_25E1F6B4] AS PARTITION [ifts_comp_fragment_partition_function_25E1F6B4] TO ([ftfg_cpMainCatalog], [ftfg_cpMainCatalog])
GO
/****** Object:  PartitionScheme [ifts_comp_fragment_data_space_272B20A8]    Script Date: 2018/9/25 12:40:11 ******/
CREATE PARTITION SCHEME [ifts_comp_fragment_data_space_272B20A8] AS PARTITION [ifts_comp_fragment_partition_function_272B20A8] TO ([ftfg_cpPublishCatalog], [ftfg_cpPublishCatalog], [ftfg_cpPublishCatalog])
GO
/****** Object:  PartitionScheme [ifts_comp_fragment_data_space_319397BA]    Script Date: 2018/9/25 12:40:11 ******/
CREATE PARTITION SCHEME [ifts_comp_fragment_data_space_319397BA] AS PARTITION [ifts_comp_fragment_partition_function_319397BA] TO ([ftfg_cpPublishCatalog], [ftfg_cpPublishCatalog])
GO
/****** Object:  PartitionScheme [ifts_comp_fragment_data_space_382ABB59]    Script Date: 2018/9/25 12:40:11 ******/
CREATE PARTITION SCHEME [ifts_comp_fragment_data_space_382ABB59] AS PARTITION [ifts_comp_fragment_partition_function_382ABB59] TO ([ftfg_cpPublishCatalog], [ftfg_cpPublishCatalog])
GO
/****** Object:  PartitionScheme [ifts_comp_fragment_data_space_5F74419A]    Script Date: 2018/9/25 12:40:11 ******/
CREATE PARTITION SCHEME [ifts_comp_fragment_data_space_5F74419A] AS PARTITION [ifts_comp_fragment_partition_function_5F74419A] TO ([ftfg_cpPublishCatalog], [ftfg_cpPublishCatalog])
GO
/****** Object:  PartitionScheme [ifts_comp_fragment_data_space_67E4C43B]    Script Date: 2018/9/25 12:40:11 ******/
CREATE PARTITION SCHEME [ifts_comp_fragment_data_space_67E4C43B] AS PARTITION [ifts_comp_fragment_partition_function_67E4C43B] TO ([ftfg_cvPublishCatalog], [ftfg_cvPublishCatalog])
GO
/****** Object:  PartitionScheme [ResumeXinxiScheme]    Script Date: 2018/9/25 12:40:11 ******/
CREATE PARTITION SCHEME [ResumeXinxiScheme] AS PARTITION [IsHistory] TO ([Spread1], [Spread2])
GO
/****** Object:  Synonym [dbo].[AppRunLog]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[AppRunLog] FOR [logdb].[dbo].[AppRunLog]
GO
/****** Object:  Synonym [dbo].[BaiduExpiredCpMain]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[BaiduExpiredCpMain] FOR [logdb].[dbo].[BaiduExpiredCpMain]
GO
/****** Object:  Synonym [dbo].[BaiduExpiredJob]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[BaiduExpiredJob] FOR [logdb].[dbo].[BaiduExpiredJob]
GO
/****** Object:  Synonym [dbo].[BaiduMapLog]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[BaiduMapLog] FOR [logdb].[dbo].[BaiduMapLog]
GO
/****** Object:  Synonym [dbo].[BlackWord]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[BlackWord] FOR [MarketDB].[dbo].[BlackWord]
GO
/****** Object:  Synonym [dbo].[bsAskInfoTmp]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[bsAskInfoTmp] FOR [SearchDB].[dbo].[bsAskInfoTmp]
GO
/****** Object:  Synonym [dbo].[bsEmailBatch]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[bsEmailBatch] FOR [logdb].[dbo].[bsEmailBatch]
GO
/****** Object:  Synonym [dbo].[bsEmailBatchDetail]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[bsEmailBatchDetail] FOR [logdb].[dbo].[bsEmailBatchDetail]
GO
/****** Object:  Synonym [dbo].[bsPageClickLog]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[bsPageClickLog] FOR [MarketDB].[dbo].[bsPageClickLog]
GO
/****** Object:  Synonym [dbo].[bsSOLStatus]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[bsSOLStatus] FOR [logDB].[dbo].[bsSOLStatus]
GO
/****** Object:  Synonym [dbo].[bsSOLStatusLog]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[bsSOLStatusLog] FOR [logDB].[dbo].[bsSOLStatusLog]
GO
/****** Object:  Synonym [dbo].[bsSourceCount]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[bsSourceCount] FOR [logdb].[dbo].[bsSourceCount]
GO
/****** Object:  Synonym [dbo].[bsSourcedetail]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[bsSourcedetail] FOR [logdb].[dbo].[bsSourcedetail]
GO
/****** Object:  Synonym [dbo].[bsSourceDetailAll]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[bsSourceDetailAll] FOR [logdb].[dbo].[bsSourceDetailAll]
GO
/****** Object:  Synonym [dbo].[bsSourcedetaillog]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[bsSourcedetaillog] FOR [logdb].[dbo].[bsSourcedetaillog]
GO
/****** Object:  Synonym [dbo].[CampusCollect]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[CampusCollect] FOR [shortdb].[dbo].[CampusCollect]
GO
/****** Object:  Synonym [dbo].[CampusListTmp]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[CampusListTmp] FOR [searchdb].[dbo].[CampusListTmp]
GO
/****** Object:  Synonym [dbo].[ClearLog]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[ClearLog] FOR [logdb].[dbo].[ClearLog]
GO
/****** Object:  Synonym [dbo].[CommonChar]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[CommonChar] FOR [shortdb].[dbo].[CommonChar]
GO
/****** Object:  Synonym [dbo].[CompanyLuckDraw]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[CompanyLuckDraw] FOR [shortdb].[dbo].[CompanyLuckDraw]
GO
/****** Object:  Synonym [dbo].[cpCvPrivi]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[cpCvPrivi] FOR [logdb].[dbo].[cpCvPrivi]
GO
/****** Object:  Synonym [dbo].[cpMainHomepageSnapshot]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[cpMainHomepageSnapshot] FOR [searchdb].[dbo].[cpMainHomepageSnapshot]
GO
/****** Object:  Synonym [dbo].[cpOpenApi]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[cpOpenApi] FOR [logdb].[dbo].[cpOpenApi]
GO
/****** Object:  Synonym [dbo].[cpOpenApiLog]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[cpOpenApiLog] FOR [logdb].[dbo].[cpOpenApiLog]
GO
/****** Object:  Synonym [dbo].[cpSessionTrans]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[cpSessionTrans] FOR [logdb].[dbo].[cpSessionTrans]
GO
/****** Object:  Synonym [dbo].[CrawlQQ]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[CrawlQQ] FOR [MarketDB].[dbo].[SpreadCrawlQQ]
GO
/****** Object:  Synonym [dbo].[dcJobTypeMajorMap]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[dcJobTypeMajorMap] FOR [ShortDB].[dbo].[dcJobTypeMajorMap]
GO
/****** Object:  Synonym [dbo].[DouBanMail]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[DouBanMail] FOR [marketdb].[dbo].[DouBanMail]
GO
/****** Object:  Synonym [dbo].[EncryptCaPassword]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[EncryptCaPassword] FOR [MarketDB].[dbo].[EncryptCaPassword]
GO
/****** Object:  Synonym [dbo].[EncryptPaPassword]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[EncryptPaPassword] FOR [MarketDB].[dbo].[EncryptPaPassword]
GO
/****** Object:  Synonym [dbo].[FileDownLoadLog]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[FileDownLoadLog] FOR [LogDB].[dbo].[FileDownLoadLog]
GO
/****** Object:  Synonym [dbo].[filemonitor]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[filemonitor] FOR [shortdb].[dbo].[filemonitor]
GO
/****** Object:  Synonym [dbo].[fpFixPosition]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[fpFixPosition] FOR [SearchDB].[dbo].[fpFixPosition]
GO
/****** Object:  Synonym [dbo].[highjob]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[highjob] FOR [searchdb].[dbo].[highjob]
GO
/****** Object:  Synonym [dbo].[HpJobNews]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[HpJobNews] FOR [searchdb].[dbo].[HpJobNews]
GO
/****** Object:  Synonym [dbo].[hpJobTypeInfo]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[hpJobTypeInfo] FOR [logdb].[dbo].[hpJobTypeInfo]
GO
/****** Object:  Synonym [dbo].[ImageFileList1]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[ImageFileList1] FOR [shortdb].[dbo].[ImageFileList1]
GO
/****** Object:  Synonym [dbo].[ImageFileList2]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[ImageFileList2] FOR [shortdb].[dbo].[ImageFileList2]
GO
/****** Object:  Synonym [dbo].[infoCpVerifyLog]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[infoCpVerifyLog] FOR [LogDB].[dbo].[infoCpVerifyLog]
GO
/****** Object:  Synonym [dbo].[infoCvVerifyLog]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[infoCvVerifyLog] FOR [LogDB].[dbo].[infoCvVerifyLog]
GO
/****** Object:  Synonym [dbo].[InfoVerifyReport]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[InfoVerifyReport] FOR [ReportDB].[dbo].[InfoVerifyReport]
GO
/****** Object:  Synonym [dbo].[Interview]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[Interview] FOR [dbo].[CommentInterview]
GO
/****** Object:  Synonym [dbo].[IpJobView]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[IpJobView] FOR [ShortDb].[dbo].[IpJobView]
GO
/****** Object:  Synonym [dbo].[IpJobViewRefuse]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[IpJobViewRefuse] FOR [shortdb].[dbo].[IpJobViewRefuse]
GO
/****** Object:  Synonym [dbo].[keywordondeal]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[keywordondeal] FOR [oadb].[dbo].[keywordondeal]
GO
/****** Object:  Synonym [dbo].[LoginOtpInfo]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[LoginOtpInfo] FOR [oadb].[dbo].[LoginOtpInfo]
GO
/****** Object:  Synonym [dbo].[LotteryCompany]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[LotteryCompany] FOR [shortdb].[dbo].[LotteryCompany2016]
GO
/****** Object:  Synonym [dbo].[LotteryCompanyLoginLog]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[LotteryCompanyLoginLog] FOR [shortdb].[dbo].[LotteryCompanyLoginLog]
GO
/****** Object:  Synonym [dbo].[MajorClass]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[MajorClass] FOR [MarketDB].[dbo].[MajorClass]
GO
/****** Object:  Synonym [dbo].[NewJobRelated]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[NewJobRelated] FOR [shortdb].[dbo].[NewJobRelated]
GO
/****** Object:  Synonym [dbo].[NewsAnalysis]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[NewsAnalysis] FOR [logdb].[dbo].[NewsAnalysis]
GO
/****** Object:  Synonym [dbo].[NoSendSms]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[NoSendSms] FOR [MarketDB].[dbo].[NoSendSms]
GO
/****** Object:  Synonym [dbo].[paCvviewCount]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[paCvviewCount] FOR [ShortDB].[dbo].[paCvviewCount]
GO
/****** Object:  Synonym [dbo].[paFromSeoLog]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[paFromSeoLog] FOR [logdb].[dbo].[paFromSeoLog]
GO
/****** Object:  Synonym [dbo].[PageBaiduInclude]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[PageBaiduInclude] FOR [MarketDB].[dbo].[PageBaiduInclude]
GO
/****** Object:  Synonym [dbo].[paLoginRegCount]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[paLoginRegCount] FOR [LogDB].[dbo].[paLoginRegCount]
GO
/****** Object:  Synonym [dbo].[paMapSearchCondition]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[paMapSearchCondition] FOR [LogDB].[dbo].[paMapSearchCondition]
GO
/****** Object:  Synonym [dbo].[paSearchCount_0]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[paSearchCount_0] FOR [SearchDb].[dbo].[paSearchCount_0]
GO
/****** Object:  Synonym [dbo].[paSearchCount_1]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[paSearchCount_1] FOR [SearchDb].[dbo].[paSearchCount_1]
GO
/****** Object:  Synonym [dbo].[paSearchCount_2]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[paSearchCount_2] FOR [SearchDb].[dbo].[paSearchCount_2]
GO
/****** Object:  Synonym [dbo].[paSearchCount_3]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[paSearchCount_3] FOR [SearchDb].[dbo].[paSearchCount_3]
GO
/****** Object:  Synonym [dbo].[paVerifyLog]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[paVerifyLog] FOR [logDB].[dbo].[paVerifyLog]
GO
/****** Object:  Synonym [dbo].[paYourFoodEmail]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[paYourFoodEmail] FOR [shortdb].[dbo].[paYourFoodEmail]
GO
/****** Object:  Synonym [dbo].[PersonReport]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[PersonReport] FOR [ReportDB].[dbo].[PersonReport]
GO
/****** Object:  Synonym [dbo].[PracticeJob]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[PracticeJob] FOR [searchdb].[dbo].[PracticeJob]
GO
/****** Object:  Synonym [dbo].[ProcHighJobInsert]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[ProcHighJobInsert] FOR [searchdb].[dbo].[ProcHighJobInsert]
GO
/****** Object:  Synonym [dbo].[procLog]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[procLog] FOR [logdb].[dbo].[procLog]
GO
/****** Object:  Synonym [dbo].[ProjectErrorLog]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[ProjectErrorLog] FOR [logdb].[dbo].[ProjectErrorLog]
GO
/****** Object:  Synonym [dbo].[QiangHongBao]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[QiangHongBao] FOR [shortdb].[dbo].[QiangHongBao]
GO
/****** Object:  Synonym [dbo].[QlrcNewsTop400]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[QlrcNewsTop400] FOR [searchdb].[dbo].[QlrcNewsTop400]
GO
/****** Object:  Synonym [dbo].[Recruitment]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[Recruitment] FOR [marketdb].[dbo].[Recruitment]
GO
/****** Object:  Synonym [dbo].[RecruitmentDept]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[RecruitmentDept] FOR [marketdb].[dbo].[RmDept]
GO
/****** Object:  Synonym [dbo].[RecruitmentList]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[RecruitmentList] FOR [shortdb].[dbo].[RecruitmentList]
GO
/****** Object:  Synonym [dbo].[RecruitmentPlace]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[RecruitmentPlace] FOR [marketdb].[dbo].[RmPlace]
GO
/****** Object:  Synonym [dbo].[RecruitmentTmp]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[RecruitmentTmp] FOR [SearchDB].[dbo].[RecruitmentTmp]
GO
/****** Object:  Synonym [dbo].[RecruitmentTop9]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[RecruitmentTop9] FOR [searchdb].[dbo].[RecruitmentTop9]
GO
/****** Object:  Synonym [dbo].[RmCp]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[RmCp] FOR [MainDB].[dbo].[recruitmentCpmain]
GO
/****** Object:  Synonym [dbo].[RmDept]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[RmDept] FOR [marketdb].[dbo].[RmDept]
GO
/****** Object:  Synonym [dbo].[RmMain]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[RmMain] FOR [MainDB].[dbo].[Recruitment]
GO
/****** Object:  Synonym [dbo].[RmPa]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[RmPa] FOR [MainDB].[dbo].[recruitmentpamain]
GO
/****** Object:  Synonym [dbo].[RtxNotifyLog]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[RtxNotifyLog] FOR [oaDB].[dbo].[RtxSend]
GO
/****** Object:  Synonym [dbo].[SmsBatchSendLog]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[SmsBatchSendLog] FOR [logdb].[dbo].[SmsBatchSendLog]
GO
/****** Object:  Synonym [dbo].[SmsEmailCount]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[SmsEmailCount] FOR [MarketDB].[dbo].[SmsEmailCount]
GO
/****** Object:  Synonym [dbo].[SmsReceive]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[SmsReceive] FOR [shortdb].[dbo].[SmsReceive]
GO
/****** Object:  Synonym [dbo].[sp_who_lock]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[sp_who_lock] FOR [wutongguodb].[dbo].[sp_who_lock]
GO
/****** Object:  Synonym [dbo].[spFamousCompany]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[spFamousCompany] FOR [MarketDB].[dbo].[spFamousCompany]
GO
/****** Object:  Synonym [dbo].[SpreadKeywordAssign]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[SpreadKeywordAssign] FOR [logdb].[dbo].[SpreadKeywordAssign]
GO
/****** Object:  Synonym [dbo].[SpreadLoginLog]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[SpreadLoginLog] FOR [logdb].[dbo].[SpreadLoginLog]
GO
/****** Object:  Synonym [dbo].[SpreadLoginLogSnap]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[SpreadLoginLogSnap] FOR [logdb].[dbo].[SpreadLoginLogSnap]
GO
/****** Object:  Synonym [dbo].[SpreadRefererLog]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[SpreadRefererLog] FOR [logdb].[dbo].[SpreadRefererLog]
GO
/****** Object:  Synonym [dbo].[synbsAskInfoClickNumber]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[synbsAskInfoClickNumber] FOR [searchdb].[dbo].[bsAskInfoClickNumber]
GO
/****** Object:  Synonym [dbo].[SynRecruitmentPlaceTmp]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[SynRecruitmentPlaceTmp] FOR [SearchDB].[dbo].[RecruitmentPlaceTmp]
GO
/****** Object:  Synonym [dbo].[synUeoLog]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[synUeoLog] FOR [LogDB].[dbo].[ueolog]
GO
/****** Object:  Synonym [dbo].[SynUeoVerificationCode]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[SynUeoVerificationCode] FOR [logdb].[dbo].[UeoVerificationCode]
GO
/****** Object:  Synonym [dbo].[tmpcheckfile]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[tmpcheckfile] FOR [shortdb].[dbo].[tmpcheckfile]
GO
/****** Object:  Synonym [dbo].[TopicZanNum]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[TopicZanNum] FOR [logdb].[dbo].[tmpTopicZanNum]
GO
/****** Object:  Synonym [dbo].[viDoc]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[viDoc] FOR [shortdb].[dbo].[viDoc]
GO
/****** Object:  Synonym [dbo].[viInterview]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[viInterview] FOR [shortdb].[dbo].[viInterview]
GO
/****** Object:  Synonym [dbo].[viInterviewRecord]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[viInterviewRecord] FOR [shortdb].[dbo].[viInterviewRecord]
GO
/****** Object:  Synonym [dbo].[VIPlan]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[VIPlan] FOR [shortdb].[dbo].[VIPlan]
GO
/****** Object:  Synonym [dbo].[VIPlanInviteLog]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[VIPlanInviteLog] FOR [shortdb].[dbo].[VIPlanInviteLog]
GO
/****** Object:  Synonym [dbo].[viRoom]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[viRoom] FOR [shortdb].[dbo].[viRoom]
GO
/****** Object:  Synonym [dbo].[viWaitingHall]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[viWaitingHall] FOR [shortdb].[dbo].[viWaitingHall]
GO
/****** Object:  Synonym [dbo].[webSafePaInfo]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[webSafePaInfo] FOR [shortdb].[dbo].[webSafePaInfo]
GO
/****** Object:  Synonym [dbo].[webSafePaInfoLog]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[webSafePaInfoLog] FOR [shortdb].[dbo].[webSafePaInfoLog]
GO
/****** Object:  Synonym [dbo].[WebVisitLog]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[WebVisitLog] FOR [shortdb].[dbo].[WebVisitLog]
GO
/****** Object:  Synonym [dbo].[WXLocation]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[WXLocation] FOR [marketdb].[dbo].[WXLocation]
GO
/****** Object:  Synonym [dbo].[WXMessage]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[WXMessage] FOR [marketdb].[dbo].[WXMessage]
GO
/****** Object:  Synonym [dbo].[WxMessageLog]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[WxMessageLog] FOR [logdb].[dbo].[WxMessageLog]
GO
/****** Object:  Synonym [dbo].[wxMessagePrevSend]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[wxMessagePrevSend] FOR [shortdb].[dbo].[wxMessagePrevSend]
GO
/****** Object:  Synonym [dbo].[WxMessageSend2]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[WxMessageSend2] FOR [logdb].[dbo].[WxMessageSend2]
GO
/****** Object:  Synonym [dbo].[WxMessageTemplate]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[WxMessageTemplate] FOR [logdb].[dbo].[WxMessageTemplate]
GO
/****** Object:  Synonym [dbo].[WxMessageTemplateDetail]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[WxMessageTemplateDetail] FOR [logdb].[dbo].[WxMessageTemplateDetail]
GO
/****** Object:  Synonym [dbo].[wxPhotoMsg]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[wxPhotoMsg] FOR [shortdb].[dbo].[wxPhotoMsg]
GO
/****** Object:  Synonym [dbo].[wxShare]    Script Date: 2018/9/25 12:40:11 ******/
CREATE SYNONYM [dbo].[wxShare] FOR [shortdb].[dbo].[wxShare]
GO
/****** Object:  UserDefinedFunction [dbo].[_51JobRegionToOurID]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--sean 2013-6-25
CREATE FUNCTION [dbo].[_51JobRegionToOurID]
(
	@51JobRegin VARCHAR(50)
)
RETURNS VARCHAR(6)
AS
BEGIN
	DECLARE @Id VARCHAR(6), @Id2 VARCHAR(6), @Des VARCHAR(20)
	SELECT TOP 1 @id = ID, @Des = DESCRIPTION
	FROM dcRegion WHERE Description LIKE LEFT(@51JobRegin, 2) + '%'
	AND GRADE = 1
	ORDER BY ID
	
	IF @Id IS NULL
		SELECT TOP 1 @id = ID, @Des = DESCRIPTION
		FROM dcRegion WHERE Description LIKE LEFT(@51JobRegin, 2) + '%'
		AND GRADE = 2
		ORDER BY ID
	ELSE
	BEGIN
		SET @Des = REPLACE(@Des, '市', '')
		SET @Des = REPLACE(@Des, '省', '')
		SET @51JobRegin = REPLACE(@51JobRegin, @Des, '')
		SET @51JobRegin = REPLACE(@51JobRegin, '-', '')

		SET @51JobRegin = REPLACE(@51JobRegin, @Des, '')
		SET @51JobRegin = REPLACE(@51JobRegin, '-', '')
		SELECT TOP 1 @id2 = ID
		FROM dcRegion 
		WHERE Description LIKE '%' + LEFT(@51JobRegin, 2) + '%'
		AND ID LIKE @Id + '%'
		ORDER BY Id
	END

	IF @Id2 > ''
		RETURN @ID2
	ELSE
		RETURN @ID
	RETURN ''
END

GO
/****** Object:  UserDefinedFunction [dbo].[AgeToBirth]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--######################################3
--创建：Sean 2011-2-25
--年龄to出生年月，用于简历搜索
--######################################3
CREATE FUNCTION [dbo].[AgeToBirth]
(
	@Age TINYINT
)
RETURNS INT
AS
BEGIN
	DECLARE @Year AS INT
	DECLARE @Month AS INT
	SET @Year = YEAR(GETDATE()) - @Age
	SET @Month = MONTH(GETDATE())
	RETURN @Year * 100 + @Month
END



GO
/****** Object:  UserDefinedFunction [dbo].[BinToINT]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[BinToINT]
(
	@BinaryChar char(10)
)
RETURNS INT
AS  
BEGIN 
    DECLARE @stringLength int,@ReturnValue int,@Index int
    DECLARE @CurrentChar char(1)
    SET @Index = 0
    SET @ReturnValue = 0
    SET @stringLength = LEN(@BinaryChar)
    While @Index<@stringLength
        BEGIN
            SET @Index = @Index + 1
            SET @CurrentChar = SUBSTRING(@BinaryChar,@Index,1)
            IF(@CurrentChar='1' or @CurrentChar='0')
                BEGIN
                    SET @ReturnValue = @ReturnValue + (CAST(@CurrentChar as int) * POWER(2,@stringLength - @Index))
                END
        END
    RETURN @ReturnValue
END

GO
/****** Object:  UserDefinedFunction [dbo].[BirthToAge]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--######################################3
--创建：Sean 2011-2-25
--年龄to出生年月，用于简历搜索
--######################################3
CREATE FUNCTION [dbo].[BirthToAge]
(
	@BirthDay INT
)
RETURNS INT
AS
BEGIN	
	RETURN (CONVERT(VARCHAR(6), GETDATE(), 112) - @BirthDay) / 100
END


GO
/****** Object:  UserDefinedFunction [dbo].[CheckCvPrivi]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--修改：harry 2018-4-18
--修改：对企业个人参加同一场校园招聘会，投递的非开放简历进行显示
CREATE FUNCTION [dbo].[CheckCvPrivi]
(
	@cvMainID INT,
	@cpMainID INT
)
RETURNS BIT
BEGIN
	DECLARE @MemberType TINYINT
	SELECT @MemberType = MemberType 
	FROM cpMain WITH(NOLOCK)
	WHERE ID = @cpMainID
	
	IF @MemberType < 2
		RETURN 0
	
	DECLARE @inActiveLog TINYINT, @inDailyGiftLog TINYINT, @inApplyPassed TINYINT, @paMainID INT
	SELECT @inActiveLog = 0, @inDailyGiftLog = 0, @inApplyPassed = 0
	IF EXISTS(SELECT TOP 1 'X'
		FROM caDailyGiftLog WITH(NOLOCK INDEX(PK_caDailyGiftLog))
		WHERE cpMainID = @cpMainID
		AND cvMainID = @cvMainID
	)
	BEGIN
		SET @inDailyGiftLog = 1
	END


	IF @inDailyGiftLog = 0
	BEGIN
		SELECT @paMainId = paMainId FROM cvMain WITH(NOLOCK) WHERE ID = @cvMainID
		DECLARE @t AS TABLE(ID INT)
		INSERT INTO @t
		SELECT ID FROM cvMain WITH(NOLOCK) WHERE paMainId = @paMainID

		IF EXISTS(SELECT TOP 1 'X'
			FROM caActiveLog WITH(NOLOCK INDEX(IX_caActiveLog_cpMainID))
			WHERE cpMainID = @cpMainID
			AND cvMainID IN(SELECT ID FROM @t)
		)
		BEGIN
			SET @inActiveLog = 1
		END
	END

	IF @inDailyGiftLog = 0 AND @inActiveLog = 0
	BEGIN
		IF EXISTS(SELECT TOP 1 'X'
			FROM ExJobApply a WITH(NOLOCK), Job b 
			WHERE a.JobID = b.ID 
			AND a.IsPassed = 1 
			AND a.cvMainID IN(SELECT ID FROM @t)
			AND b.cpMainID = @cpMainID
		)
		BEGIN
			SET @inApplyPassed = 1
		END
	END

	IF @inActiveLog + @inDailyGiftLog + @inApplyPassed = 0
	BEGIN
		--判断 个人给企业投递了简历,个人与企业都报名参加了同一场招聘会--harry2018-4-18
		IF EXISTS(SELECT TOP 1 'X'
			FROM ExJobApply a WITH(NOLOCK), Job b 
			WHERE a.JobID = b.ID 
			AND a.IsPassed = 0--非开放 
			AND a.cvMainID IN(SELECT ID FROM @t)
			AND b.cpMainID = @cpMainID
		)
		BEGIN
			--是否同时参加了一场校园招聘会
			IF EXISTS( SELECT TOP 1 'x'
				FROM marketdb..rmcompany a, marketdb..rmperson b
				WHERE a.cpMainId =@cpMainID
				AND b.paMainId=@paMainID
				AND a.recruitmentId= b.recruitmentId)
			BEGIN
				RETURN 1
			END
			ELSE
			BEGIN
				RETURN 0
			END
		END
		ELSE
		BEGIN
			RETURN 0
		END
	END
		 
	RETURN 1
END



GO
/****** Object:  UserDefinedFunction [dbo].[CleanAddress]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--######################################3
--创建：Sean 2011-2-25
--年龄to出生年月，用于简历搜索
--######################################3
CREATE FUNCTION [dbo].[CleanAddress]
(
	@Address NVARCHAR(100),
	@dcRegionId VARCHAR(6)
)
RETURNS NVARCHAR(100)
AS
BEGIN
	DECLARE @r VARCHAR(6), @A NVARCHAR(100), @l INT
	SELECT @a = @address
	SELECT @r = Description FROM dcRegion WHERE Id = LEFT(@dcRegionId, 2)
	SET @l = LEN(@r)
	IF(LEFT(@a, @l) = @r)
		SET @a = RIGHT(@a, LEN(@a) - @l)
	BEGIN
		IF RIGHT(LEFT(@a, @l), 1) NOT IN('路', '街', '道')
			IF(LEFT(@a, @l - 1) = LEFT(@r, @l - 1))
				SET @a = RIGHT(@a, LEN(@a) - @l + 1)
	END

	IF(LEN(@dcRegionId) > 2)
	BEGIN
		SELECT @r = Description FROM dcRegion WHERE Id = LEFT(@dcRegionId, 4)
		SET @l = LEN(@r)
		IF(LEFT(@a, @l) = @r)
			SET @a = RIGHT(@a, LEN(@a) - @l)
		ELSE IF(LEFT(@a, @l-1) = LEFT(@r, @l - 1))
			SET @a = RIGHT(@a, LEN(@a) - @l + 1)
	END
	IF(LEN(@dcRegionId) > 4)
	BEGIN
		SELECT @r = Description FROM dcRegion WHERE Id = LEFT(@dcRegionId, 6)
		SET @l = LEN(@r)
		IF(LEFT(@a, @l) = @r)
			SET @a = RIGHT(@a, LEN(@a) - @l)
	END

	RETURN @a
END

GO
/****** Object:  UserDefinedFunction [dbo].[ClearChinese]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE function [dbo].[ClearChinese]
(
	@str VARCHAR(MAX)
)
RETURNS VARCHAR(Max)
AS
BEGIN
	DECLARE @I AS INT, @str1 AS VARCHAR(MAX), @c AS NCHAR(1)
	SELECT @I = 1, @str1 = ''
	WHILE @I <= LEN(@str)
	BEGIN
		SELECT @c = SUBSTRING(@str, @i, 1)
		IF DATALENGTH(@c) = LEN(@c)
			SELECT @str1 = @str1 + @c
		SELECT @I = @I + 1
	END
	RETURN @str1
END

GO
/****** Object:  UserDefinedFunction [dbo].[clearhtml]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create function [dbo].[clearhtml]
(
	@maco varchar(MAX)
)
returns varchar(MAX)  
as  
begin  
    declare @randchar_one nvarchar(200)  
    declare @randchar_two nvarchar(200)  
       if(charindex('<<',@maco)>0)  
              begin  
                     set @randchar_one='D4678B36-B958-4274-B81E-BBA636CFB427';  
                     set @randchar_two='49E374CC-9E1A-4850-897C-27074DE32E7F';  
                     set @maco=replace(@maco,'<<',@randchar_one)  
                     set @maco=replace(@maco,'>>',@randchar_two)  
              end  
    declare @i int  
    while 1 = 1  
    begin  
       set @i=len(@maco)  
       set @maco=replace(@maco, substring(@maco,charindex('<',@maco),  
       charindex('>',@maco)-charindex('<',@maco)+1),space(0))  
       if @i=len( @maco )  
       break  
    end  
   
    set @maco=replace(@maco,' ','')  
    set @maco=replace(@maco,'&nbsp;','')  
    set @maco=ltrim(rtrim(@maco))  
    set @maco=replace(@maco,char(9),'')  
    set @maco=replace(@maco,char(10),'')  
    set @maco=replace(@maco,char(13),'')  
    if(charindex(@randchar_one,@maco)>0)  
    begin  
       set @maco=replace(@maco,'D4678B36-B958-4274-B81E-BBA636CFB427','<<')  
       set @maco=replace(@maco,'49E374CC-9E1A-4850-897C-27074DE32E7F','>>')  
    end  
    return (@maco)  
end  

GO
/****** Object:  UserDefinedFunction [dbo].[ClearHTMLTag]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[ClearHTMLTag]
(
	@Cont VARCHAR(MAX)
)
RETURNS VARCHAR(MAX)
AS
BEGIN
	DECLARE @Txt VARCHAR(MAX), @I INT, @J INT
	SET @Txt = REPLACE(ISNULL(@Cont, ''), '&nbsp;', ' ')
	SELECT @i = CHARINDEX('<', @Txt, 0), @j = CHARINDEX('>', @Txt, 1)

	WHILE @i < @j
	BEGIN
		SELECT @Txt = REPLACE(@Txt, SUBSTRING(@txt, @i, @j - @i + 1), '')
		SELECT @i = CHARINDEX('<', @Txt, 0), @j = CHARINDEX('>', @Txt, 1)
	END

	RETURN @Txt
END

GO
/****** Object:  UserDefinedFunction [dbo].[CompanyNameNoCheck]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--######################################################3
--信息员推广企业是，企业名称免检
--######################################################3
CREATE FUNCTION [dbo].[CompanyNameNoCheck]
(
	@CompanyName NVARCHAR(50)
)
RETURNS BIT
AS
BEGIN
	IF @CompanyName LIKE '%香港%'
		RETURN 1

	IF @CompanyName LIKE '%台湾%'
		RETURN 1

	IF @CompanyName LIKE '%澳门%'
		RETURN 1

	RETURN 0
END




GO
/****** Object:  UserDefinedFunction [dbo].[ComputeCvLevel]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[ComputeCvLevel]
(
	@cvLevel CHAR(10),
	@Pos TINYINT,
	@Val CHAR(1)
)   
RETURNS CHAR(10)
AS
BEGIN
	DECLARE @Level AS CHAR(10)
	SET @Level = LEFT(@cvLevel, @Pos - 1) + @Val + RIGHT(@cvLevel,10 - @Pos)
	--IF LEFT(@cvLevel, 1) <> '1'
	--	SET @Level = '1' + RIGHT(@Level, 9)
	RETURN @Level
END


GO
/****** Object:  UserDefinedFunction [dbo].[ComputeJobValid]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE FUNCTION [dbo].[ComputeJobValid]
(	
	@IsDelete BIT,
	@VerifyResult TINYINT,
	@IssueDate SMALLDATETIME,
	@IssueEnd SMALLDATETIME
)
RETURNS BIT
AS
BEGIN
	IF @IsDelete = 1
		RETURN 0
	
	IF @VerifyResult<>1
		RETURN 0

	IF NOT(@IssueDate<GETDATE() AND @IssueEnd>GETDATE())
		RETURN 0

	RETURN 1
END


GO
/****** Object:  UserDefinedFunction [dbo].[CutWord]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Function [dbo].[CutWord]
(
	@InWord NVARCHAR(20)
)
RETURNS NVARCHAR(20)
AS
BEGIN
	IF CHARINDEX('select', @InWord) > 0
		RETURN ''
	IF CHARINDEX('script', @InWord) > 0
		RETURN ''
	IF CHARINDEX('delete', @InWord) > 0
		RETURN ''
	IF CHARINDEX('update', @InWord) > 0
		RETURN ''
	IF CHARINDEX('drop', @InWord) > 0
		RETURN ''

	IF LEN(@InWord) > 4
		IF EXISTS(SELECT 'x' FROM cpMainPublish WITH(NOLOCK) WHERE Name = @InWord)
			RETURN @InWord

	DECLARE @OutWord NVARCHAR(20), @Word NVARCHAR(20), @Word1 NVARCHAR(20), @Word2 NVARCHAR(20), @Word3 NVARCHAR(20), @Id INT, @WordType INT
	SELECT @OutWord = ' ', @Id = 0

	DECLARE @t AS TABLE(Id INT IDENTITY(1, 1), Word NVARCHAR(20))

	INSERT INTO @t
	SELECT * FROM dbo.FnSplit(@InWord, ' ')
	WHILE EXISTS(SELECT 'x' FROM @t WHERE Id > @Id )
	BEGIN
		SELEcT TOP 1 @Id = Id, @Word = Word FROM @t WHERE Id > @Id ORDER BY Id
		IF EXISTS(SELECT 'x' FROM @t WHERE Id < @Id AND WOrd = @Word)
			CONTINUE
		IF LEN(@Word) < 4
		BEGIN
			SET @OutWord = @OutWord + ' ' + @Word
			CONTINUE
		END

		IF EXISTS(SELECT 'x' FROM WordList WHERE Word = @Word)
			SET @OutWord = @OutWord + ' ' + @Word
		ELSE
		BEGIN
			SET @Word1 = ''
			SELECT TOP 1 @WordType = WordType, @Word1 = Word FROM WordList WHERE CHARINDEX(Word, @Word) = 1 ORDER BY WordType, ID
			IF @Word1 > ''
			BEGIN
				SET @Word2 = RIGHT(@Word, LEN(@Word) - LEN(@Word1))
				IF @WordType = 1
				BEGIN
					SET @WordType = 0
					SELECT TOP 1 @WordType = WordType FROM WordList WHERE Word = @Word2
					IF @WordType = 1
						SET @OutWord = @OutWord + ' ' + @Word
					ELSE
						IF @WordType = 0
						BEGIN
							SELECT TOP 1 @WordType = WordType, @Word3 = Word 
							FROM WordList WHERE CHARINDEX(Word, @Word2) = 1 ORDER BY WordType DESC, ID
							IF @WordType < 2
								SET @OutWord = @OutWord + ' ' + @Word
							ELSE
								SET @OutWord = @OutWord + ' ' + @Word1 + ' ' + @Word3 + ' ' + REPLACE(@Word2, @Word3, '')
						END
						ELSE
							SET @OutWord = @OutWord + ' ' + @Word1 + ' ' + @Word2
				END
				ELSE IF @WordType > 1
				BEGIN
					IF LEN(@Word) - LEN(@Word1) < 2
						SET @OutWord = @OutWord + ' ' + @Word
					ELSE
						SET @OutWord = @OutWord + ' ' + @Word1 + ' ' + RIGHT(@Word, LEN(@Word) - LEN(@Word1))
				END
				ELSE
					SET @OutWord = @OutWord + ' ' + @Word
			END
			ELSE
				SET @OutWord = @OutWord + ' ' + @Word
		END
	END

	RETURN LTRIM(@OutWord)
END

GO
/****** Object:  UserDefinedFunction [dbo].[cvMainValid]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[cvMainValid]
(	
	@ID INT
)
RETURNS TINYINT
AS
BEGIN
	DECLARE @cvValid AS TINYINT
	SELECT @cvValid = (
		case [IsCvHidden] 
			when (1) then (0) 
			else 
				case left([cvLevel],(6))+rtrim(CONVERT([char](2),[VerifyResult],(0))) 
					when '1111111' then 
						case left([cvLevelEng],(6))+rtrim(CONVERT([char](2),[VerifyResultEng],(0))) 
							when '1111111' then (2) 
							when '1111011' then (2) 
							else (1) 
						end 
					when '1111011' then 
						case left([cvLevelEng],(6))+rtrim(CONVERT([char](2),[VerifyResultEng],(0))) 
							when '1111111' then (2) 
							when '1111011' then (2) 
							else (1) 
						end 
					else 
						case left([cvLevelEng],(6))+rtrim(CONVERT([char](2),[VerifyResultEng],(0))) 
							when '1111111' then (3) 
							when '1111011' then (3) 
							else (0) 
						end 
				end 
		end)
	FROM cvMain WITH(NOLOCK) WHERE ID=@ID
	RETURN @cvValid
END
GO
/****** Object:  UserDefinedFunction [dbo].[DateTo]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--######################################3
--创建：Richard 2011-4-27
--日期转换
--######################################3
create FUNCTION [dbo].[DateTo]
(
	@d INT
)
RETURNS INT
AS
BEGIN	
	RETURN ((@d) / 60)*100+((@d) % 60)
END


GO
/****** Object:  UserDefinedFunction [dbo].[DateToReportDay]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--######################################3
--创建：Lambo 2013-2-4
--日期转换 将日期转换成天数 2012-1-1为1
--######################################3
CREATE FUNCTION [dbo].[DateToReportDay]
(
	@d SMALLDATETIME
)
RETURNS INT
AS
BEGIN	
	RETURN DATEDIFF(DAY,'2012-1-1',@d)
END
GO
/****** Object:  UserDefinedFunction [dbo].[DeCrypt]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--######################################################3
--实现用户名解密的函数
--######################################################3
CREATE FUNCTION [dbo].[DeCrypt]
(
	@strEncrypted VARCHAR(50)
)
RETURNS VARCHAR(50)
AS
BEGIN
	IF @strEncrypted IS NULL
		RETURN ''
	SET @strEncrypted = LTRIM(RTRIM(@strEncrypted))
	DECLARE @GKey AS CHAR(69)
	DECLARE @I AS INT
	DECLARE @iC AS INT
	DECLARE @iK AS INT
	DECLARE @iD AS INT
	DECLARE @strDecrypted AS VARCHAR(50)

	SET @strDecrypted = ''
	SET @I = 1
	SET @GKey = Char(1) + Char(3) + Char(2) + Char(4) + Char(2) + Char(4) + Char(1) + Char(3) + Char(2) + Char(4) + Char(1) + Char(3) + Char(2) + Char(4) + Char(3) + Char(1) + Char(4) + Char(2) + Char(3) + Char(1) + Char(2) + Char(2) + Char(4) + Char(1) + Char(4) + Char(1) + Char(4) + Char(3) + Char(2) + Char(3) + Char(2) + Char(4) + Char(1) + Char(4) + Char(2) + Char(3) + Char(4) + Char(1) + Char(3) + Char(1) + Char(4) + Char(2) + Char(4) + Char(4) + Char(2) + Char(3) + Char(1) + Char(3) + Char(2) + Char(4) + Char(3) + Char(1) + Char(4) + Char(2) + Char(4) + Char(1) + Char(3) + Char(2) + Char(4) + Char(1) + Char(3) + Char(2) + Char(4) + Char(3) + Char(1) + Char(4) + Char(1) + Char(3) + Char(4)
	
	WHILE @I <= LEN(@strEncrypted)
	BEGIN
		SET @iC = ASCII(SUBSTRING(@strEncrypted, @I, 1))
		SET @iK = ASCII(SUBSTRING(@GKey, @I, 1))
		SET @iD = @iK ^ @iC
		SET @strDecrypted = @strDecrypted + CHAR(@iD)
		SET @I = @I + 1
	END
	RETURN @strDecrypted
END

GO
/****** Object:  UserDefinedFunction [dbo].[ExistUserName]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--######################################3
--创建：Sean 2010-12-2
--推广时企业用户名是否可用
--######################################3
CREATE FUNCTION [dbo].[ExistUserName]
(
	@UserName VARCHAR(50)
)
RETURNS BIT
AS
BEGIN
	IF EXISTS(SELECT 'x' FROM caMain WITH(NOLOCK) WHERE UserNameLower = @UserName)
		RETURN 1
		
	IF EXISTS(SELECT 'x' FROM Company_xinxi WITH(NOLOCK) WHERE UserNameLower = @UserName)
		RETURN 1

	RETURN 0
END



GO
/****** Object:  UserDefinedFunction [dbo].[f_add]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE function [dbo].[f_add](@date datetime,@i int)
returns datetime
as
begin
  declare @rt datetime
  set @rt=@date
  while @i>0
  begin
    set @rt=dateadd(d,1,@rt)
    if datepart(w,@rt) in(1,7) set @rt=dateadd(d,1,@rt)  --7为周六,1为周日
    if datepart(w,@rt) in(1,7) set @rt=dateadd(d,1,@rt)  --7为周六,1为周日
    set @i=@i-1
  end
  return @rt
end

GO
/****** Object:  UserDefinedFunction [dbo].[f_Convert]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[f_Convert]
(
	@str NVARCHAR(4000), 		--要转换的字符串
	@flag bit					--转换标志, 0转换成半角, 1转换成全角
)
RETURNS nvarchar(4000)
AS
BEGIN
    DECLARE @pat nvarchar(8), @step int, @i int, @spc int
    IF @flag  =  0
        SELECT @pat = N'%[！-～]%', @step = -65248, 
            @str = REPLACE(@str, N'　', N' ')
    ELSE
        SELECT @pat = N'%[!-~]%', @step = 65248, 
            @str = REPLACE(@str, N' ', N'　')
    SET @i = PATINDEX(@pat COLLATE LATIN1_GENERAL_BIN, @str)
    WHILE @i > 0
		SELECT @str = REPLACE(@str,
			SUBSTRING(@str, @i, 1), 
            NCHAR(UNICODE(SUBSTRING(@str, @i, 1))+@step)), 
			@i = PATINDEX(@pat COLLATE LATIN1_GENERAL_BIN, @str)

    RETURN(@str)
END
GO
/****** Object:  UserDefinedFunction [dbo].[fn_MorThan100PaLoginLog]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[fn_MorThan100PaLoginLog]
(
	@caMainId INT
)
RETURNS @Temp TABLE(Id INT)
AS
BEGIN
	DECLARE @ID AS INT
	SELECT TOP 100 @ID = ID FROM caLoginLog WHERE caMainId = @caMainId ORDER BY ID DESC
	INSERT @Temp
	SELECT ID FROM caLoginLog WHERE ID < @ID AND caMainId = @caMainId
	RETURN
END

GO
/****** Object:  UserDefinedFunction [dbo].[FnctManageruserSuperior]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create  function   [dbo].[FnctManageruserSuperior](@sender int,@receiver int)   
  returns   int   
  as   
  begin   
declare @superior int,@r1 int,@r2 int,@r3 int,@s1 int,@s2 int,@s3 int


select @s1=superior from manageruser with(nolock) where id=@sender
select @r1=superior from manageruser with(nolock) where id=@receiver

select @s2=superior from manageruser with(nolock) where id=@s1
select @r2=superior from manageruser with(nolock) where id=@r1

select @s3=superior from manageruser with(nolock) where id=@s2
select @r3=superior from manageruser with(nolock) where id=@r2

if @s1=@r1
  set @superior=@s1
else if @s1=@r2
  set @superior=@s1
else if @s2=@r1
  set @superior=@r1
else if @s1=@r3
  set @superior=@s1
else if @r1=@s3
  set @superior=@r1
else if @r2=@s2
  set @superior=@s2
else if @r2=@s3
  set @superior=@r2
else if @s2=@r3
  set @superior=@s2
else if @r3=@s3
  set @superior=@s3
else
  set @superior=1
    return   @superior  
  end 

GO
/****** Object:  UserDefinedFunction [dbo].[fnRanString]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE function [dbo].[fnRanString]
(
	@Length int
)
returns varchar(100)  
begin  
	DECLARE @RandomID varchar(32), @counter smallint, @RandomNumber float, @ValidCharactersLength int,
		@RandomNumberInt tinyint, @CurrentCharacter varchar(1), @ValidCharacters varchar(255)

	SET @ValidCharacters = 'abcdefghijklmnopqrstuvwxyz0123456789'
	SET @ValidCharactersLength = len(@ValidCharacters)
	SELECT @CurrentCharacter = '', @RandomNumber = 0, @RandomNumberInt = 0, @RandomID = '', @counter = 1
	WHILE @counter < (@Length + 1)  
	BEGIN  
		select @RandomNumber = re from v_rand  
		SET @RandomNumberInt = Convert(tinyint, ((@ValidCharactersLength -1) * @RandomNumber + 1));  
		SELECT @CurrentCharacter = SUBSTRING(@ValidCharacters, @RandomNumberInt, 1);  
		SET @counter = @counter + 1;  
		SET @RandomID = @RandomID + @CurrentCharacter;  
	END  

	Return @RandomID;  
end  

GO
/****** Object:  UserDefinedFunction [dbo].[fnSplit]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--######################################################3  --实现split功能 的函数  --######################################################3  
CREATE FUNCTION [dbo].[fnSplit]  
(   
	@StrSource VARCHAR(MAX),   
	@StrSeprate VARCHAR(10)
)  
RETURNS @Temp TABLE(a VARCHAR(max))  
AS  
BEGIN   
	DECLARE @i INT
	SET @StrSource = RTRIM(LTRIM(@StrSource))
	SET @i = CHARINDEX(@StrSeprate, @StrSource)
	WHILE @i > =1
	BEGIN    
		IF LEFT(@StrSource, @i - 1) > '' 
			INSERT @temp VALUES(LEFT(@StrSource, @i - 1))
	
		SET @StrSource = SUBSTRING(@StrSource, @i + 1, LEN(@StrSource) - @i)
		SET @i = CHARINDEX(@StrSeprate, @StrSource)
	END   
	IF @StrSource <> ''    
	INSERT @Temp VALUES(@StrSource)   
	RETURN   
END    

GO
/****** Object:  UserDefinedFunction [dbo].[FormatID]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#############################333
--格式化id，去掉所有不是数字的字符
--#############################333
CREATE FUNCTION [dbo].[FormatID]
(
	@s VARCHAR(MAX)
)
RETURNS VARCHAR(MAX)
AS
BEGIN
	IF @s IS NULL
		RETURN ''
	
	DECLARE @i AS INT
	DECLARE @c AS CHAR(1)
	DECLARE @R AS VARCHAR(MAX)
	SET @R = ''

	SET @i = 0
	WHILE @i < LEN(@s)
	BEGIN
		IF SUBSTRING(@s, @i + 1, 1) IN ('1', '2', '3', '4', '5', '6', '7', '8', '9', '0')
		SET @R = @R + SUBSTRING(@s, @i + 1, 1)
		SET @i = @i +1
	END
	RETURN @R
END


GO
/****** Object:  UserDefinedFunction [dbo].[FormatIDS]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#############################333
--格式化id，去掉所有不是数字和，的字符
--#############################333
create FUNCTION [dbo].[FormatIDS]
(
	@s VARCHAR(MAX)
)
RETURNS VARCHAR(MAX)
AS
BEGIN
	IF @s IS NULL
		RETURN ''
	
	DECLARE @i AS INT
	DECLARE @c AS CHAR(1)
	DECLARE @R AS VARCHAR(MAX)
	SET @R = ''

	SET @i = 0
	WHILE @i < LEN(@s)
	BEGIN
		IF SUBSTRING(@s, @i + 1, 1) IN ('1', '2', '3', '4', '5', '6', '7', '8', '9', '0', ',')
		SET @R = @R + SUBSTRING(@s, @i + 1, 1)
		SET @i = @i +1
	END
	RETURN @R
END


GO
/****** Object:  UserDefinedFunction [dbo].[FormatMobile]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE FUNCTION [dbo].[FormatMobile]
(
	@str AS VARCHAR(MAX)
)
RETURNS VARCHAR(MAX)
AS
BEGIN
	RETURN REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@str, '－', '-'), '０', '0'), '１', '0'), '２', '2'), '３', '3'), '４', '4'), '５', '5'), '６', '6'), '７', '7'), '８', '8'), '９', '9'), '（', '('), '）', ')'), '——', '-'), '—', '-'),'，', ','), '、', ',')	
END
GO
/****** Object:  UserDefinedFunction [dbo].[Full2Half]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[Full2Half]
(
	@str NVARCHAR(4000), --要转换的字符串
	@flag bit              --转换标志,0转换成半角,1转换成全角
)
RETURNS nvarchar(4000)
AS
BEGIN
    DECLARE @pat nvarchar(8), @step int, @i int,@spc int
    IF @flag = 0
        SELECT @pat = N'%[！-～]%', @step = -65248,
            @str = REPLACE(@str, N'　', N' ')
    ELSE
        SELECT @pat = N'%[!-~]%', @step = 65248,
            @str = REPLACE(@str, N' ', N'　')
    SET @i = PATINDEX(@pat COLLATE LATIN1_GENERAL_BIN, @str)
    WHILE @i > 0
        SELECT @str = REPLACE(@str,
                SUBSTRING(@str, @i, 1),
                NCHAR(UNICODE(SUBSTRING(@str, @i, 1)) + @step)),
				@i = PATINDEX(@pat COLLATE LATIN1_GENERAL_BIN, @str)

    RETURN(@str)
END

GO
/****** Object:  UserDefinedFunction [dbo].[fullRegionName]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE FUNCTION [dbo].[fullRegionName]
(
	@Id VARCHAR(6)
)
RETURNS NVARCHAR(20)
BEGIN
 	RETURN (SELECT FullName FROM dcRegion WITH(NOLOCK) WHERE ID = @ID)
END

GO
/****** Object:  UserDefinedFunction [dbo].[Get3JobSecondIds]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[Get3JobSecondIds]
(
	@JobIds AS VARCHAR(MAX)
)
RETURNS @Temp TABLE(Id VARCHAR(12))
AS
BEGIN
	DECLARE @i INT, @Num INT, @StrSource VARCHAR(MAX), @s VARCHAR(50)
	SELECT @StrSource = REPLACE(RTRIM(LTRIM(@JobIds)), '_', '')
	SELECT @i = CHARINDEX(',', @StrSource), @Num = 0, @s = ''

	IF @i = 0
	BEGIN
		IF @StrSource > ''
			INSERT INTO @Temp VALUES(@StrSource)

		RETURN
	END

	WHILE @i >= 1 AND @Num < 3
	BEGIN
		IF LEFT(@StrSource, @i - 1) > '' 
		BEGIN
			INSERT INTO @Temp VALUES(LEFT(@StrSource, @i - 1))
			SELECT @Num = @Num + 1
		END
		SELECT @StrSource = SUBSTRING(@StrSource, @i + 1, LEN(@StrSource) - @i)
		SELECT @i = CHARINDEX(',', @StrSource)
	END

	IF @Num < 3 AND @StrSource <> '' AND @i = 0
		INSERT INTO @Temp VALUES(@StrSource)
	
	IF LEFT(@s, 1) = ','
		INSERT INTO @Temp VALUES(RIGHT(@s, LEN(@s) - 1))

	RETURN
END

GO
/****** Object:  UserDefinedFunction [dbo].[GetBeiSenCvText]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[GetBeiSenCvText]
(
	@cvMainId INT
)
RETURNS NVARCHAR(MAX)
AS
BEGIN
	DECLARE @paName NVARCHAR(10), @Sex NVARCHAR(2), @BirthDay NVARCHAR(20), @LivePlace NVARCHAR(30), @Mobile VARCHAR(20),
		@Email VARCHAR(100), @Career NVARCHAR(30), @WorkYear NVARCHAR(10), @Salary VARCHAR(50), @JobType VARCHAR(100),
		@Industry VARCHAR(100), @WorkPlace VARCHAR(100), @Speciality NVARCHAR(500)

	SELECT @paName = ISNULL(a.Name, ''), @Sex = CASE WHEN Gender = 0 THEN '男' ELSE '女' END, @BirthDay = ISNULL(BirthDay, ''), 
		@LivePlace = ISNULL((SELECT FullName FROM dcRegion WHERE Id = LivePlace), ''), 
		@Mobile = ISNULL(Mobile, ''), @Email = Email,
		@Career = ISNULL((SELECT Description FROM dcCareerStatus WHERE Id = dcCareerStatus), 1),
		@WorkYear =  LTRIM(STR(ISNULL(RelatedWorkYears, 0))) + '年', 
		@Salary = ISNULL((SELECT Description FROM dcSalary WHERE id = dcSalaryId), ''),
		@Speciality = ISNULL(Speciality, '')
	FROM paMain a WITH(NOLOCK), cvMain b WITH(NOLOCK)
	WHERE b.Id = @cvMainId
	AND b.paMainId = a.Id
	
	IF LEN(@BirthDay) = 6
		SET @BirthDay = LEFT(@BirthDay, 4) + '年' + RIGHT(@BirthDay, 2) + '月'

	SELECT @Industry = ISNULL(@Industry, '') + DESCRIPTION + ' '
	FROM dcIndustry a, cvIndustry b
	WHERE a.Id = b.dcIndustryId
	AND b.cvMainId = @cvMainID

	SELECT @WorkPlace = ISNULL(@WorkPlace, '') + DESCRIPTION + ' '
	FROM dcRegion a, cvJobPlace b
	WHERE a.Id = b.dcRegionId
	AND b.cvMainId = @cvMainID 

	SELECT @JobType = ISNULL(@JobType, '') + DESCRIPTION + ' '
	FROM dcJobtype a, cvJobType b
	WHERE a.Id = b.dcJobTypeId
	AND b.cvMainId = @cvMainID

	DECLARE @CvText NVARCHAR(MAX)
		SET @CvText = 
'<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>个人简历</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style>
tr{height:22px;}
td{font-size:10.0pt;padding-left:2px;padding-right:2px}
body{tab-interval:21.0pt}
dd{margin:0; padding:0; float:left; clear:both;}dl{margin:0; padding:0;}
</style>
</head>
<body>
  <h3>个人信息</h3>
  <table cellpadding="0" cellspacing="0" border="1" width="658" >
    <tr>
      <td><label>姓名：</label><span>' + ISNULL(@paName, '') + '</span></td>
      <td><label>性别：</label><span>' + ISNULL(@Sex, '') + '</span></td>
    </tr>
    <tr>
      <td><label>出生年月：</label><span>' + ISNULL(@BirthDay, '') + '</span></td>
      <td><label>现居住地：</label><span>' + ISNULL(@LivePlace, '') + '</span></td>
    </tr>
    <tr>
      <td><label>手机号：</label><span>' + ISNULL(@Mobile, '') + '</span></td>
      <td><label>电子邮箱：</label><span>' + ISNULL(@Email, '') + '</span></td>
    </tr>
  </table>'
	IF @Salary > '' AND @jobType > ''
		SET @cvText = @cvText + '
  <h3>求职意向</h3>
  <table cellpadding="0" cellspacing="0" border="1" width="658" >
    <tr>
      <td><label>求职状态：</label><span>' + ISNULL(@Career, '') + '</span></td>
      <td><label>相关工作经验：</label><span>' + ISNULL(@WorkYear, '') + '</span></td>
    </tr>
    <tr>
      <td><label>期望月薪：</label><span>' + ISNULL(@Salary, '') + '</span></td>
	  <td><label>期望职位类别：</label><span>' + ISNULL(@jobType, '') + '</span></td>
    </tr>
    <tr>
      <td><label>期望工作地点：</label><span>' + ISNULL(@WorkPlace, '') + '</span></td>
      <td colspan="2"><label>期望从事行业：</label><span>' + ISNULL(@Industry, '') + '</span></td>
    </tr>
  </table>'
	-----------------------------------
	DECLARE @GraduateCollage AS VARCHAR(100), @EduDetail AS NVARCHAR(500), @Graduation AS VARCHAR(20), 
		@Degree VARCHAR(10), @MajorName NVARCHAR(50)
	SELECT TOP 1 @GraduateCollage = ISNULL(GraduateCollage, ''), 
		@EduDetail = ISNULL(LEFT(Details, 500), ''),
		@Graduation = ISNULL(Graduation, ''),
		@Degree = ISNULL((SELECT Description FROM dcEducation WHERE id = Degree), ''),
		@MajorName = ISNULL(MajorName, '')
	FROM cvEducation WHERE cvMainId = @cvMainId ORDER BY Degree DESC, Graduation DESC
	IF LEN(@Graduation) = 6
		SET @Graduation = LEFT(@Graduation, 4) + '年' + RIGHT(@Graduation, 2) + '月'

	SET @cvText = @cvText + '
  <h3>教育背景</h3>
  <table cellpadding="0" cellspacing="0" border="1" width="658" >
    <tr>
      <td><label>学校名称：</label><span>' + ISNULL(@GraduateCollage, '') + '</span></td>
      <td><label>毕业时间：</label><span>' + ISNULL(@Graduation, '') + '</span></td>
    </tr>
    <tr>
      <td><label>学历：</label><span>' + ISNULL(@Degree, '') + '</span></td>
      <td><label>专业：</label><span>' + ISNULL(@MajorName, '') + '</span></td>
    </tr>'
	IF LEN(ISNULL(@EduDetail, '')) > 0
	SET @cvText = @cvText + '
    <tr>
      <td colspan="2"><label>学习经历：</label><span>' + @EduDetail + '</span></td>
    </tr>'
	SET @cvText = @cvText + '
  </table>'
	--------------------------------------------------
	DECLARE @CompanyName AS VARCHAR(100), @companyIndustry AS VARCHAR(50), @CompanyPost AS VARCHAR(50), @BeginDate VARCHAR(10), 
		@EndDate VARCHAR(10), @CompanyDesc NVARCHAR(500)
	SELECT TOP 1 @CompanyName = ISNULL(CompanyName, ''),
		@companyIndustry = ISNULL((SELECT Description FROM dcIndustry WHERE Id = dcIndustryId), ''),
		@CompanyPost = ISNULL(JobName, ''),
		@BeginDate = ISNULL(BeginDate, ''),
		@EndDate = ISNULL(EndDate, ''),
		@CompanyDesc = ISNULL(LEFT(Description, 500), '')
	FROM cvExperience WHERE cvMainId = @cvMainId ORDER BY BeginDate DESC, EndDate DESC
	IF LEN(@BeginDate) = 6 AND LEN(@EndDate) = 6
	BEGIN
		SET @cvText = @cvText + '
  <h3>工作经历</h3>
  <table cellpadding="0" cellspacing="0" border="1" width="658" >
    <tr>
      <td><label>企业名称：</label><span>' + ISNULL(@CompanyName, '') + '</span></td>
      <td><label>所属行业：</label><span>' + ISNULL(@companyIndustry, '') + '</span></td>
    </tr>
    <tr>
      <td><label>岗位名称：</label><span>' + ISNULL(@CompanyPost, '') + '</span></td>
      <td><label>工作时间：</label><span>' + LEFT(@BeginDate, 4) + '年' + RIGHT(@BeginDate, 2) + '月至' + CASE WHEN @EndDate = 999999 THEN '今' ELSE LEFT(@EndDate, 4) + '年' + RIGHT(@EndDate, 2) + '月' END + '</span></td>
    </tr>'
		IF @CompanyDesc > ''
			SET @cvText = @cvText + '
	<tr>
      <td colspan="2"><label>工作描述：</label><span>' + @CompanyDesc + '</span></td>
    </tr>'
		SET @cvText = @cvText + '
  </table>'
	END
	IF @Speciality > ''
		SET @cvTExt = @cvText + '
  <h3>工作能力</h3>
  <table cellpadding="0" cellspacing="0" border="1" width="658" >
    <tr>
      <td colspan="2"><label>工作描述：</label><span>' + @Speciality + '</span></td>
    </tr>
  </table>'
SET @CvText = @CvText + '
</body>
</html>'
	RETURN @cvText
END

GO
/****** Object:  UserDefinedFunction [dbo].[GetBit]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

create FUNCTION [dbo].[GetBit](@val INT, @pos INT)
RETURNS BIT
AS
BEGIN
	RETURN (@Val / POWER(2, @pos - 1)) & 1
END
GO
/****** Object:  UserDefinedFunction [dbo].[GetCaName]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[GetCaName] 
(
	@caMainID INT
)
RETURNS VARCHAR(50)
AS
BEGIN
	DECLARE @Name VARCHAR(20)
	DECLARE @Gender BIT
	DECLARE @IsNameHide BIT
	SELECT @Name = Name, @Gender = Gender, @IsNameHide = IsNameHide
	FROM caMain WHERE ID = @caMainID
	IF @IsNameHide = 1
	BEGIN
		IF @Gender = 1
			SELECT @Name = LEFT(@Name,1) + '女士'
		ELSE
			SELECT @Name = LEFT(@Name,1) + '先生'
	END
	RETURN @Name
END
GO
/****** Object:  UserDefinedFunction [dbo].[GetCaOnlineStatus]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[GetCaOnlineStatus]
(
	@caMainID INT
)
RETURNS BIT
AS
BEGIN
	DECLARE @IsOnline AS BIT
	SELECT @IsOnline = IsOnline FROM caOnline WITH(NOLOCK) WHERE caMainID = @caMainID
--	IF EXISTS(SELECT 'X' FROM caOnline WHERE caMainID = @caMainID AND (DATEDIFF(s, RefreshDate, GETDATE()) < 120))
--		SELECT @IsOnline = 1
	RETURN ISNULL(@IsOnline, 0)
END
GO
/****** Object:  UserDefinedFunction [dbo].[GetChatPrivi]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[GetChatPrivi] 
(
    @cvMainID INT,
    @cpMainID INT
)
RETURNS BIT
AS
BEGIN
    IF EXISTS(
        SELECT TOP 1 'X' FROM ChatOnline WITH(NOLOCK) WHERE caMainID IN(
            SELECT ID FROM caMain WITH(NOLOCK) WHERE cpMainID = @cpMainID
        ) AND cvMainID = @cvMainID AND Initiative = 1
    )
    BEGIN
	IF EXISTS(SELECT TOP 1 'X' FROM cpMain WITH(NOLOCK) WHERE ID = @cpMainID AND MemberType < 2)
		RETURN 0
	ELSE
	        RETURN 1
    END

    RETURN dbo.CheckCvPrivi(@cvMainID, @cpMainID)
END
GO
/****** Object:  UserDefinedFunction [dbo].[GetContactPrivi]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create FUNCTION [dbo].[GetContactPrivi]
(
	@caMainID INT,
	@cvMainID INT
)
RETURNS TINYINT	--0无权限； 1显示手机号，email； 2显示手机号；3、显示手机号、email
AS
BEGIN
	DECLARE @cpMainID AS INT,
		@MemberType AS TINYINT,
		@Valid AS TINYINT,
		@VerifyResult AS TINYINT,
		@VerifyResultEng AS TINYINT,
		@IsPassed AS BIT,
		@IsCvHidden AS BIT

	SELECT @cpMainID = cpMainID FROM caMain WITH(NOLOCK) WHERE ID = @caMainId
	SELECT @MemberType = MemberType FROM cpMain WITH(NOLOCK) WHERE ID = @cpMainID

	SELECT @Valid = Valid, @VerifyResult = VerifyResult, @VerifyResultEng = VerifyResultEng, @IsCvHidden = IsCvHidden
	FROM cvMain WITH(NOLOCK) WHERE ID = @cvMainID

	----有问题
	IF @VerifyResult = 10 OR @VerifyResultEng = 10
		RETURN 0

	----未认证会员
	IF @MemberType IN(0, 1)
		RETURN 0

	----普通会员
	IF @MemberType IN(2, 3)
	BEGIN
		IF EXISTS(SELECT 'x' FROM exJobApply WITH(NOLOCK)
				WHERE cvMainID = @cvMainID AND IsPassed = 1
				AND JobID IN(SELECT ID FROM Job WITH(NOLOCK) WHERE cpMainID = @cpMainID))
			RETURN 1

		IF EXISTS(SELECT 'x' FROM caActiveLog WITH(NOLOCK)
				WHERE cpMainID = @cpMainID
				AND cvMainID = @cvMainID)
			RETURN 1

		IF EXISTS(SELECT 'x' FROM caDailyGiftLog WITH(NOLOCK)
				WHERE cpMainID = @cpMainID
				AND cvMainID = @cvMainID)
			RETURN 1

		RETURN 0
	END

	----正式会员
	IF @MemberType = 10
	BEGIN
		IF EXISTS(SELECT 'x' FROM exJobApply WITH(NOLOCK)
				WHERE cvMainID = @cvMainID AND IsPassed = 1
				AND JobID IN(SELECT ID FROM Job WITH(NOLOCK) WHERE cpMainID = @cpMainID))
			RETURN 3

		IF @IsCvHidden = 1
			RETURN 0

		RETURN 2		
	END

	----储值会员
	IF @MemberType = 11
	BEGIN
		IF EXISTS(SELECT 'x' FROM caCvQuotaLog WITH(NOLOCK)
				WHERE cvMainID = @cvMainID
				AND cpMainID = @cpMainID)
			RETURN 3

		IF @IsCvHidden = 1
			RETURN 0

		RETURN 2		
	END

	RETURN 0
END

GO
/****** Object:  UserDefinedFunction [dbo].[GetCpIndustry]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[GetCpIndustry]
(
	@cpMainID INT
)
RETURNS VARCHAR(MAX)
AS
BEGIN
	DECLARE @strIndustry NVARCHAR(100)
	SET @strIndustry = ''
	SELECT @strIndustry = @strIndustry + RTRIM(LTRIM(b.Description)) + '，' FROM cpIndustry a WITH(NOLOCK),dcIndustry b  WITH(NOLOCK) WHERE a.dcIndustryID=b.ID AND a.cpMainID=@cpMainID
	IF LEN(@strIndustry) > 0
		SET @strIndustry = LEFT(@strIndustry,LEN(@strIndustry)-1)
	RETURN @strIndustry
END

GO
/****** Object:  UserDefinedFunction [dbo].[GetCpIndustryId]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[GetCpIndustryId]
(
	@cpMainID INT
)
RETURNS VARCHAR(MAX)
AS
BEGIN
	DECLARE @strIndustry NVARCHAR(100)
	SET @strIndustry = ''
	SELECT @strIndustry = @strIndustry + RTRIM(LTRIM(dcIndustryID)) + ',' FROM cpIndustry WITH(NOLOCK)
	WHERE cpMainID = @cpMainID
	IF LEN(@strIndustry) > 0
		SET @strIndustry = LEFT(@strIndustry, LEN(@strIndustry)-1)
	RETURN @strIndustry
END

GO
/****** Object:  UserDefinedFunction [dbo].[GetCpLogo]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[GetCpLogo]
(
	@cpMainID INT
)
RETURNS VARCHAR(MAX)
AS
BEGIN
	DECLARE @strLogoPath NVARCHAR(1000)
	SELECT @strLogoPath = ISNULL(LogoFile, '')
	FROM cpMain WITH(NOLOCK)
	WHERE ID = @cpMainID

	RETURN @strLogoPath
END
GO
/****** Object:  UserDefinedFunction [dbo].[GetCvJobType]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[GetCvJobType]
(
	@cvMainID INT
)
RETURNS VARCHAR(MAX)
AS
BEGIN
	DECLARE @strJobType NVARCHAR(100)
	SET @strJobType = ''
	SELECT @strJobType = @strJobType + RTRIM(LTRIM(b.Description)) + '，' FROM cvJobType a,dcJobType b WHERE a.dcJobTypeID=b.ID AND a.cvMainID=@cvMainID
	IF LEN(@strJobType) > 0
		SET @strJobType = LEFT(@strJobType,LEN(@strJobType)-1)
	RETURN @strJobType
END

GO
/****** Object:  UserDefinedFunction [dbo].[GetCvMatch]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--######################################3
--创建：Lambo 20120329	
--计算简历和职位的匹配度
--######################################3
CREATE FUNCTION [dbo].[GetCvMatch]
(
	@cvMainID INT,
	@JobID INT
)
RETURNS VARCHAR(MAX)
AS
BEGIN	
	DECLARE @JobTypeMatch AS DECIMAL(18,2)	--职位类别的匹配度
	DECLARE @RegionMatch AS DECIMAL(18,2)		--办公室地点的匹配度
	DECLARE @ExperienceMatch AS DECIMAL(18,2) --相关工作经验的匹配度
	DECLARE @SalaryMatch AS DECIMAL(18,2)		--月薪的匹配度
	DECLARE @EducationMatch AS DECIMAL(18,2)	--学历的匹配度
	DECLARE @IndustryMatch AS DECIMAL(18,2)	--行业的匹配度
	DECLARE @AgeMatch AS DECIMAL(18,2)		--年龄的匹配度

	SET @JobTypeMatch = 0 
	SET @RegionMatch = 0 
	SET @ExperienceMatch = 0 
	SET @SalaryMatch = 0 
	SET @EducationMatch = 0 
	SET @IndustryMatch = 0 
	SET @AgeMatch = 0 
	
	DECLARE @JobTypeID AS INT			--职位的主要职位类别
	DECLARE @dcRegionID AS INT			--办公室地点
	DECLARE @cpIndustry AS VARCHAR(100)	--企业所属行业
	DECLARE @MinExperience INT			--相关工作经验
	DECLARE	@dcSalaryID INT				--最低月薪
	DECLARE @dcEducationID AS INT		--学历要求
	DECLARE @MinAge AS INT				--最小年龄	
	DECLARE @MaxAge AS INT				--最大年龄
	SELECT 
		@JobTypeID=dcJobTypeID,
		@dcRegionID = dcRegionID,
		@MinExperience = MinExperience,
		@dcSalaryID = dcSalaryID,
		@dcEducationID = dcEducationID,
		@MinAge = MinAge,
		@MaxAge = MaxAge,
		@cpIndustry = ','+STUFF((SELECT ','+LTRIM(a.dcIndustryid)+',c'+LTRIM(b.CateGoryId) FROM cpIndustry a,dcIndustryCategory b WHERE a.dcIndustryid = b.dcIndustryid AND cpMainid = JOB.cpMainID FOR XML PATH('')),1,1,'')+','
	FROM JOB WITH(NOLOCK)
	WHERE ID = @JobID

	DECLARE @cvJobType AS INT	--期望职位类别
	DECLARE @cvJobPlace AS VARCHAR(100)	--期望工作地点
	DECLARE @cvIndustry AS VARCHAR(100)	--期望从事行业
	DECLARE @cvRelatedWorkYears AS INT	--个人工作经验			
	DECLARE @cvDcSalaryID AS INT		--期望月薪
	DECLARE @IsNegotiable AS BIT		--是否面议
	DECLARE @Degree AS INT				--个人学历
	DECLARE @Age AS INT					--个人年龄

	DECLARE @INTTemp AS INT		--临时变量
	DECLARE @INTTemp2 AS INT

	--匹配职位类别
	SELECT @JobTypeMatch = ISNULL(MAX(
		CASE 
			WHEN dcJobTypeID=@JobTypeID OR @JobTypeID LIKE LTRIM(dcJobTypeID)+'%'  THEN 1 
			WHEN LEFT(LTRIM(@JobTypeID),2) = LEFT(dcJobTypeID,2) THEN 0.5
		END),'0') 
	FROM  cvJobType WITH(NOLOCK) WHERE cvMainID=@cvMainID
/*
	IF @JobTypeMatch <> 1 
		SELECT @JobTypeMatch = ISNULL(Max(a.Coefficient)/10.0,@JobTypeMatch) 
		FROM dcJobTypeSimilar a WITH(NOLOCK) ,cvJobType b WITH(NOLOCK) 
		WHERE b.cvMainID=@cvMainID
		AND (
				(
				a.dcJobTypeID = @JobTypeID
				AND a.SimilarId = b.dcJobTypeID
				)
			OR 
				(
				SimilarId = @JobTypeID 
				AND a.dcJobTypeID = b.dcJobTypeID
				) 
			)
*/
	--匹配工作地点	
	IF EXISTS( SELECT top 1 'x' FROM cvJobPlace WITH(NOLOCK) 
				WHERE cvMainID = @cvMainID 
				AND (
					dcRegionID = @dcRegionID 
					OR 
					(
						@dcRegionID LIKE ''+LTRIM(dcRegionID)+'%' AND (LEN(dcRegionID)=4 Or LEN(dcRegionID)=2)
					)
				)
			 )
		SET @RegionMatch = 1

	--循环匹配行业	
	DECLARE @iIndex AS INT
	SET @iIndex = 0
	DECLARE #Industry CURSOR FOR 
		SELECT a.dcIndustryID,b.CategoryID 
		FROM  cvIndustry a WITH(NOLOCK) ,dcIndustryCategory b WITH(NOLOCK) 
		WHERE a.dcIndustryid = b.dcIndustryid 
		AND  cvMainID=@cvMainID 
		ORDER BY a.dcIndustryID
	OPEN #Industry
	FETCH NEXT FROM  #Industry INTO @INTTemp,@INTTemp2
	WHILE @@FETCH_STATUS = 0 AND @IndustryMatch<>1
	BEGIN 
		SET @iIndex = @iIndex + 1
		IF CHARINDEX(','+LTRIM(@INTTemp)+',',LTRIM(@cpIndustry))>0
			SET @IndustryMatch=1
		ELSE IF CHARINDEX(',c'+LTRIM(@INTTemp2)+',',LTRIM(@cpIndustry))>0
			SET @IndustryMatch=0.5
		FETCH NEXT FROM  #Industry INTO @INTTemp,@INTTemp2
	END
	CLOSE #Industry
	DEALLOCATE #Industry
	IF @iIndex = 0
		SET @IndustryMatch = 1

	--取简历数据
	SELECT
		@Degree = Degree,
		@cvRelatedWorkYears = ISNULL(RelatedWorkYears,0),
		@cvDcSalaryID = dcSalaryID,
		@IsNegotiable = IsNegotiable,
		@Age = dbo.BirthToAge(b.Birthday)
	From cvMain a WITH(NOLOCK), paMain b WITH(NOLOCK)
	WHERE a.id=@cvMainID 
	AND a.paMainID = b.ID

	--匹配工作经验
	IF @MinExperience = 0
		SET @ExperienceMatch = 1
	ELSE IF @MinExperience = 1
	BEGIN
		IF @cvRelatedWorkYears<1
			SET @ExperienceMatch = 	0.5
		ELSE IF @cvRelatedWorkYears>2
			SET @ExperienceMatch = 	1 + (@cvRelatedWorkYears-2) * -0.1
		ELSE
			SET @ExperienceMatch = 1	
	END	
	ELSE IF @MinExperience = 2
	BEGIN
		IF @cvRelatedWorkYears<3
		BEGIN
			IF @cvRelatedWorkYears >=1 AND @cvRelatedWorkYears <=2
				SET @ExperienceMatch = 	0.5
		END
		ELSE IF @cvRelatedWorkYears>5
			SET @ExperienceMatch = 	1 + (@cvRelatedWorkYears-2) * -0.1
		ELSE
			SET @ExperienceMatch = 1	
	END
	ELSE IF @MinExperience = 3
	BEGIN
		IF @cvRelatedWorkYears<6
		BEGIN
			IF @cvRelatedWorkYears >=3 AND @cvRelatedWorkYears <=5
				SET @ExperienceMatch = 	0.5
		END
		ELSE IF @cvRelatedWorkYears>10
			SET @ExperienceMatch = 	1 + (@cvRelatedWorkYears-2) * -0.1
		ELSE
			SET @ExperienceMatch = 1	
	END
	ELSE IF @MinExperience = 4
	BEGIN
		IF @cvRelatedWorkYears<10
		BEGIn
			IF @cvRelatedWorkYears >=6 AND @cvRelatedWorkYears <=10
				SET @ExperienceMatch = 	0.5
		END
		ELSE
			SET @ExperienceMatch = 1	
	END
	ELSE IF @MinExperience = 5
		SET @ExperienceMatch = 1 +(ISNULL(@cvRelatedWorkYears,0) * -0.1)
	ELSE
		SET @ExperienceMatch = 1	

	--匹配月薪
	IF @dcSalaryID = @cvDcSalaryID OR @dcSalaryID = 100 OR @IsNegotiable = 1
		SET @SalaryMatch = 1
	ELSE IF @dcSalaryID - @cvDcSalaryID = 1 OR @dcSalaryID - @cvDcSalaryID = -1 
		SET @SalaryMatch = 0.5
		
	--匹配学历	
	IF @Degree = @dcEducationID 
		SET @EducationMatch = 1
	ELSE IF @Degree - @dcEducationID = 1
		SET @EducationMatch = 0.8
	ELSE IF @Degree - @dcEducationID = 2
		SET @EducationMatch = 0.5
		
	--匹配年龄
	IF (@MinAge = 99 AND @MaxAge = 99) OR (@MinAge = 0 AND @MaxAge = 0)
		SET @AgeMatch = 1
	ELSE IF @Age < @MinAge
	BEGIN
		IF @MinAge - @Age = 1
			SET @AgeMatch = 0.8
		ELSE IF @MinAge-@Age = 2
			SET @AgeMatch = 0.5
	end
	ELSE IF @Age > @MaxAge
	BEGIN
		IF @Age - @MaxAge = 1
			SET @AgeMatch = 0.8
		ELSE IF @Age - @MaxAge = 2
			SET @AgeMatch = 0.5
	END
	ELSE
		SET @AgeMatch = 1
	RETURN CONVERT(INT,(@JobTypeMatch+@RegionMatch+@ExperienceMatch+@SalaryMatch+@EducationMatch+@IndustryMatch+@AgeMatch)/7*100)
END

GO
/****** Object:  UserDefinedFunction [dbo].[GetJobFullRegionName]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[GetJobFullRegionName]
(
	@JobID INT
)
RETURNS NVARCHAR(100)
AS
BEGIN
	DECLARE @strRegionID NVARCHAR(100)
	SET @strRegionID = ''
	
	SELECT @strRegionID = @strRegionID + RTRIM(LTRIM(b.fullname)) + ','
	FROM JobRegion a WITH(NOLOCK), 
		dcRegion b WITH(NOLOCK)
	WHERE a.JobID = @JobID
	AND a.dcRegionID = b.ID

	IF LEN(@strRegionID) > 0 
		SET @strRegionID = LEFT(@strRegionID, LEN(@strRegionID) - 1)
	
	RETURN @strRegionID
END


GO
/****** Object:  UserDefinedFunction [dbo].[GetJobIds]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[GetJobIds]
(
	@cpMainID INT
)
RETURNS VARCHAR(MAX)
AS
BEGIN
	DECLARE @ids AS VARCHAR(MAX)
	SET @ids = ''
	SELECT TOP 10 @ids = @ids + 
		CASE LEN(@ids) WHEN 0 THEN '' ELSE ',' END +
		--ISNULL((SELECT IsFollow FROM MarketDb..PageBaiduInclude WHERE PageType = 2 AND PageId = SecondID), '') +
		LTRIM(STR(ID))
	FROM Job WITH(NOLOCK)
	WHERE cpMainId = @cpMainId
	AND Valid = 1
	ORDER BY DisplayNo, CONVERT(VARCHAR(4), dcJobtypeId)
	
	RETURN @ids
END


GO
/****** Object:  UserDefinedFunction [dbo].[GetJobIdsNew]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[GetJobIdsNew]
(
	@cpMainID INT
)
RETURNS VARCHAR(MAX)
AS
BEGIN
	DECLARE @ids AS VARCHAR(MAX)
	SET @ids = ''
	SELECT TOP 20 @ids = @ids + CASE LEN(@ids) WHEN 0 THEN '' ELSE ',' END +
		--(SELECT IsFollow FROM MarketDb..PageBaiduInclude WHERE PageType = 2 AND PageId = ID) + 
		LTRIM(STR(ID))
	FROM Job WITH(NOLOCK)
	WHERE cpMainId = @cpMainId
	AND Valid = 1
	ORDER BY DisplayNo, CONVERT(VARCHAR(4), dcJobtypeId)
	
	RETURN @ids
END

GO
/****** Object:  UserDefinedFunction [dbo].[GetJobIdsOld]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create FUNCTION [dbo].[GetJobIdsOld]
(
	@cpMainID INT
)
RETURNS VARCHAR(MAX)
AS
BEGIN
	DECLARE @ids AS VARCHAR(MAX)
	SET @ids = ''
	SELECT TOP 20 @ids = @ids + CASE LEN(@ids) WHEN 0 THEN '' ELSE ',' END + LTRIM(STR(ID))
	FROM Job WITH(NOLOCK)
	WHERE cpMainId = @cpMainId
	AND Valid = 1
	ORDER BY DisplayNo, CONVERT(VARCHAR(4), dcJobtypeId)
	
	RETURN @ids
END





GO
/****** Object:  UserDefinedFunction [dbo].[GetJobNames]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[GetJobNames]
(
	@cpMainID INT
)
RETURNS VARCHAR(MAX)
AS
BEGIN
	DECLARE @ids AS VARCHAR(MAX)
	SET @ids = ''
	SELECT TOP 10 @ids = @ids + CASE LEN(@ids) WHEN 0 THEN '' ELSE ',' END + REPLACE(Name, ',', '，')
	FROM Job WITH(NOLOCK)
	WHERE cpMainId = @cpMainId
	AND Valid = 1
	ORDER BY DisplayNo, CONVERT(VARCHAR(4), dcJobtypeId), ID
	
	RETURN @ids
END





GO
/****** Object:  UserDefinedFunction [dbo].[GetJobSecondIds]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[GetJobSecondIds]
(
	@cpMainID INT
)
RETURNS VARCHAR(MAX)
AS
BEGIN
	DECLARE @ids AS VARCHAR(MAX)
	SET @ids = ''
	SELECT TOP 10 @ids = @ids + 
		CASE LEN(@ids) WHEN 0 THEN '' ELSE ',' END +
		--ISNULL((SELECT '_' FROM MarketDb..PageBaiduInclude WITH(NOLOCK) WHERE PageType = 2 AND PageId = SecondID AND IsFollow = 'n'), '') + 
		SecondId
	FROM Job WITH(NOLOCK)
	WHERE cpMainId = @cpMainId
	AND Valid = 1
	ORDER BY DisplayNo, CONVERT(VARCHAR(4), dcJobtypeId), ID
	
	RETURN @ids
END

GO
/****** Object:  UserDefinedFunction [dbo].[GetLotteryGiftType]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--lucifer 2018-2-1
CREATE FUNCTION [dbo].[GetLotteryGiftType]
(
	@IsAgent TINYINT,
	@GiftNo INT,
	@IsVip TINYINT
)
RETURNS TINYINT
AS
BEGIN
	--奖品类型：1、50职位并发  2、50份简历 3、记事本（100份简历） 4、*200份简历 5、2周六分之一图片 6、2周知名企业 7、2周职位置顶  8、100次职位刷新（2周职位自动刷新）  9、2周六分之二 10、蓝皮书（Vip会员—季度） 11、满1000-50优惠券 12、电热水壶 99、没中奖
	DECLARE @GiftType TINYINT
	IF @IsAgent = 0
	BEGIN
		IF @IsVip = 0
		BEGIN
			IF @GiftNo BETWEEN 1 AND 50			--六分之一广告 5%概率
				SET @GiftType = 5
			ELSE IF @GiftNo BETWEEN 51 AND 100		--2周知名企业 5%概率
				SET @GiftType = 6
			ELSE IF @GiftNo BETWEEN 101 AND 120		--两周职位置顶 2%概率
				SET @GiftType = 7
			ELSE IF @GiftNo BETWEEN 121 AND 170		--100次职位刷新 5%概率
				SET @GiftType = 8
			ELSE IF @GiftNo BETWEEN 171 AND 200		--六分之二广告 3%概率
				SET @GiftType = 9
			ELSE						--满1000-50优惠券 80%概率
				SET @GiftType = 11
		END
		ELSE
		BEGIN
			IF @GiftNo BETWEEN 1 AND 200 			--职位并发 20%概率
				SET @GiftType = 1
			ELSE IF @GiftNo BETWEEN 201 AND 400		--50份简历 20%概率
				SET @GiftType = 2
			ELSE IF @GiftNo BETWEEN 401 AND 450		--六分之一广告 5%概率
				SET @GiftType = 5
			ELSE IF @GiftNo BETWEEN 451 AND 600		--2周知名企业 15%概率
				SET @GiftType = 6
			ELSE IF @GiftNo BETWEEN 601 AND 650		--两周职位置顶 5%概率
				SET @GiftType = 7
			ELSE IF @GiftNo BETWEEN 651 AND 850 		--100次职位刷新 20%概率
				SET @GiftType = 8
			ELSE IF @GiftNo BETWEEN 851 AND 900		--六分之二广告 5%概率
				SET @GiftType = 9
			ELSE						--满1000-50优惠券 10%概率
				SET @GiftType = 11
		END
	END
	ELSE
	BEGIN
		IF @GiftNo BETWEEN 1 AND 300 			--职位并发 30%概率
			SET @GiftType = 1
		ELSE IF @GiftNo BETWEEN 301 AND 500		--50份简历 20%概率
			SET @GiftType = 2
		ELSE 						--100次自动刷新 50%概率
			SET @GiftType = 8
	END
	RETURN @GiftType
END

GO
/****** Object:  UserDefinedFunction [dbo].[GetMemberTypeWithRealName]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--######################################3
--创建：Sean 2010-11-16
--判断企业用户类型
--######################################3
CREATE FUNCTION [dbo].[GetMemberTypeWithRealName]
(
	@ID INT
)
RETURNS TINYINT
AS
BEGIN
	DECLARE @HasLicence AS BIT, @BalanceDate AS SMALLDATETIME, @UnlimitedDate AS SMALLDATETIME,
		@Address AS VARCHAR(100), @Name AS NVARCHAR(6), @Gender AS BIT,
		@MemberType AS TINYINT, @IsDelete AS BIT, @Mobile VARCHAR(100), @RealName TINYINT

	SELECT @HasLicence = ISNULL(HasLicence, 0),
		@BalanceDate = ISNULL(BalanceDate, '1900-1-1'),
		@UnlimitedDate = ISNULL(UnlimitedDate, '1900-1-1'),
		@Address = ISNULL(Address, ''),
		@IsDelete = IsDelete, @RealName = RealName
	FROM cpMain WITH(NOLOCK)
	WHERE ID = @ID
 
	SELECT @Name = Name, @Gender = Gender, @Mobile = ISNULL(Mobile, ISNULL(TelePhone, '')) FROM caMain WITH(NOLOCK)
	WHERE cpMainID = @ID AND AccountType = 1
  
	----企业资料不完整,=0
	IF ISNULL(@Address, '') = '' OR @IsDelete = 1 OR ISNULL(@Name, '') = '' OR @Gender IS NULL OR @Mobile = ''
		SET @MemberType = 0
	----已经上传营业执照,只能是普通会员：2、无限制：10、储值：11、vip：3之一
	ELSE IF @HasLicence = 0
		SET @MemberType = 1
	----检查订单
	ELSE IF EXISTS(SELECT 'x' FROM caOrder WITH(NOLOCK)
			WHERE cpMainID = @ID AND OrderType = 8
			AND BeginDate <= GETDATE() AND EndDate > DATEADD(MINUTE, -4, GETDATE())
			AND IsDeleted = 0
			)
	BEGIN
		IF @RealName = 1
			SET @MemberType = 31
		ELSE
		SET @MemberType = 3
	END
	ELSE
	BEGIN
		IF @RealName = 1
			SET @MemberType = 21
		ELSE
			SET @MemberType = 2
	END

	RETURN @MemberType
END














GO
/****** Object:  UserDefinedFunction [dbo].[GetNextMSSchedule]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

create function [dbo].[GetNextMSSchedule]
(
	@msScheduleId AS INT
)
RETURNS SMALLDATETIME
AS
BEGIN
	DECLARE @FreqType AS TINYINT,
		@FreqINTerval AS TINYINT,
		@FreqSubdayType AS TINYINT,
		@FreqSubdayInterval AS SMALLINT,
		@ActiveStartDate AS VARCHAR(8),
		@ActiveEndDate AS VARCHAR(8),
		@ActiveStartTime AS VARCHAR(4),
		@ActiveEndTime AS VARCHAR(4),
		@StartDate AS SMALLDATETIME,
		@EndDate AS SMALLDATETIME,
		@NextRunTime AS SMALLDATETIME,
		@PlanTime AS SMALLDATETIME,
		@I AS INT,
		@II AS INT,
		@Exceeding AS INT,
		@IsOk AS INT,
		@Now AS SMALLDATETIME
	--获取计划任务数据
	SELECT @FreqType = FreqType, 
		@FreqInterval = FreqInterval,
		@FreqSubdayType = FreqSubdayType,
		@FreqSubdayInterval = FreqSubdayInterval,
		@ActiveStartDate = CONVERT(VARCHAR(8), ActiveStartDate),
		@ActiveEndDate = CONVERT(VARCHAR(8), ActiveEndDate),
		@ActiveStartTime = CONVERT(VARCHAR(4), ActiveStartTime),
		@ActiveEndTime = CONVERT(VARCHAR(4), ActiveEndTime),
		@IsOk = 0,
		@Now = CONVERT(VARCHAR(16), GETDATE(),120)
	FROM MainDb..msSchedule WITH(NOLOCK)
	WHERE ID = @msScheduleId

	--计算开始时间和结束时间
	SELECT @StartDate = dbo.MergeDate(@ActiveStartDate, @ActiveStartTime),
		@EndDate = dbo.MergeDate(@ActiveEndDate, @ActiveEndTime)

	IF @EndDate <= @Now		--如果结束时间<当前，直接退出
	BEGIN
		SELECT @NextRunTime = NULL
	END
	ELSE IF @FreqType = 1			--执行一次
	BEGIN
		--如果开始时间>当前，则返回开始时间，否则返回null
		IF @StartDate > @Now
			SELECT @NextRunTime = @StartDate
		ELSE
			SELECT @NextRunTime = NULL
	END
	ELSE IF @FreqType = 4			--每日执行
	BEGIN
		IF @StartDate > @Now	--如果开始时间>当前，下一次=开始时间
			SELECT @PlanTime = @StartDate
		ELSE
		BEGIN
			--计算从今天起再过几天（@Exceeding）是下次执行日期
			SELECT @Exceeding = DATEDIFF(DAY, @StartDate, @Now) % @FreqInterval
			IF(@Exceeding > 0)
				SELECT @Exceeding = @FreqInterval - @Exceeding

			--得出自今日-点期最近一次执行日期
			SELECT @PlanTime = dbo.MergeDate(@Now + @Exceeding, @ActiveStartTime)
			IF @PlanTime > @Now
				SELECT @NextRunTime = @PlanTime, @IsOk = 1
			ELSE
			BEGIN
				--下次执行日期<当前
				--如果间隔内循环 分钟
				IF @FreqSubdayType >= 4
				BEGIN
					IF @FreqSubdayType = 8
						SELECT @FreqSubdayInterval = @FreqSubdayInterval * 60
					--计算到下次执行，间隔多少分钟
					SELECT @Exceeding = DATEDIFF(MINUTE, @PlanTime, @Now) % @FreqSubdayInterval
					IF(@Exceeding > 0)
						SELECT @Exceeding = @FreqSubdayInterval - @Exceeding

					SELECT @NextRunTime = DATEADD(MINUTE, @Exceeding, @Now)
					IF @NextRunTime <= @Now	--如果是当前一分钟，则+1分钟
						SELECT @NextRunTime = DATEADD(MINUTE, @FreqSubdayInterval, @NextRunTime)
					IF @NextRunTime < CONVERT(VARCHAR(10), @Now + 1, 120)
						SELECT @IsOk = 1
				END
				IF(@IsOk = 0)	--间隔内不循环或者本日无法循环，则到下一执行日期
					SET @NextRunTime = @PlanTime + @FreqInterval
			END
		END
	END
	ELSE IF @FreqType = 8	--按周间隔，周、月都是执行一次
	BEGIN
		DECLARE @w AS INT, @TodayPower AS INT
		SELECT @w = DATEPART(W, @Now)	--1周日，2 周一，。。。7周六
		SELECT @TodayPower = POWER(2, @w - 1), @i = 8, @Exceeding = 7

		IF (@FreqInterval & @TodayPower = @TodayPower)	--今日是执行日期
		BEGIN
			SELECT @PlanTime = dbo.MergeDate(@Now, @ActiveStartTime)
			IF @PlanTime > @Now		--执行时间
				SELECT @NextRunTime = @PlanTime, @IsOk = 1
		END

		IF(@IsOk = 0)	--本日不执行，或者本日时间已过，则到下一执行日期
		BEGIN
			WHILE @I < 15
			BEGIN
				IF (@FreqInterval & POWER(2, @I - 8) = POWER(2, @I - 8))
				BEGIN
					SELECT @II = (@i - @w) % 7
					IF(@Exceeding > @II AND @II > 0)
						SET @Exceeding = @II
				END
				SET @i = @i + 1
			END
			SELECT @NextRunTime = dbo.MergeDate(@Now, @ActiveStartTime) + @Exceeding, @IsOk = 1
		END
	END
	ELSE IF @FreqType = 16	--按月间隔，周、月都是执行一次
	BEGIN
		SELECT @Exceeding = DATEDIFF(MONTH, @StartDate, @Now) / @FreqInterval, @I = 1
		SELECT @PlanTime = DATEADD(MONTH, @Exceeding * @FreqInterval, @StartDate)
		WHILE @PlanTime < @Now
		BEGIN
			SELECT @PlanTime = DATEADD(MONTH, @FreqInterval, @PlanTime)
			SELECT @I = @I + 1	
		END
		SET @NextRunTime = @PlanTime
	END
	RETURN @NextRunTime
END



GO
/****** Object:  UserDefinedFunction [dbo].[GetNextSchedule]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create function [dbo].[GetNextSchedule]
(
	@schScheduleId AS INT
)
RETURNS SMALLDATETIME
AS
BEGIN
	DECLARE @FreqType AS TINYINT,
		@FreqINTerval AS TINYINT,
		@FreqSubdayType AS TINYINT,
		@FreqSubdayInterval AS SMALLINT,
		@ActiveStartDate AS VARCHAR(8),
		@ActiveEndDate AS VARCHAR(8),
		@ActiveStartTime AS VARCHAR(4),
		@ActiveEndTime AS VARCHAR(4),
		@StartDate AS SMALLDATETIME,
		@EndDate AS SMALLDATETIME,
		@NextRunTime AS SMALLDATETIME,
		@PlanTime AS SMALLDATETIME,
		@I AS INT,
		@II AS INT,
		@Exceeding AS INT,
		@IsOk AS INT,
		@Now AS SMALLDATETIME
	--获取计划任务数据
	SELECT @FreqType = FreqType, 
		@FreqInterval = FreqInterval,
		@FreqSubdayType = FreqSubdayType,
		@FreqSubdayInterval = FreqSubdayInterval,
		@ActiveStartDate = CONVERT(VARCHAR(8), ActiveStartDate),
		@ActiveEndDate = CONVERT(VARCHAR(8), ActiveEndDate),
		@ActiveStartTime = CONVERT(VARCHAR(4), ActiveStartTime),
		@ActiveEndTime = CONVERT(VARCHAR(4), ActiveEndTime),
		@IsOk = 0,
		@Now = CONVERT(VARCHAR(16), GETDATE(),120)
	FROM MainDb..schSchedule WITH(NOLOCK)
	WHERE ID = @schScheduleId

	--计算开始时间和结束时间
	SELECT @StartDate = dbo.MergeDate(@ActiveStartDate, @ActiveStartTime),
		@EndDate = dbo.MergeDate(@ActiveEndDate, @ActiveEndTime)

	IF @EndDate <= @Now		--如果结束时间<当前，直接退出
	BEGIN
		SELECT @NextRunTime = NULL
	END
	ELSE IF @FreqType = 1			--执行一次
	BEGIN
		--如果开始时间>当前，则返回开始时间，否则返回null
		IF @StartDate > @Now
			SELECT @NextRunTime = @StartDate
		ELSE
			SELECT @NextRunTime = NULL
	END
	ELSE IF @FreqType = 4			--每日执行
	BEGIN
		IF @StartDate > @Now	--如果开始时间>当前，下一次=开始时间
			SELECT @PlanTime = @StartDate
		ELSE
		BEGIN
			--计算从今天起再过几天（@Exceeding）是下次执行日期
			SELECT @Exceeding = DATEDIFF(DAY, @StartDate, @Now) % @FreqInterval
			IF(@Exceeding > 0)
				SELECT @Exceeding = @FreqInterval - @Exceeding

			--得出自今日-点期最近一次执行日期
			SELECT @PlanTime = dbo.MergeDate(@Now + @Exceeding, @ActiveStartTime)
			IF @PlanTime > @Now
				SELECT @NextRunTime = @PlanTime, @IsOk = 1
			ELSE
			BEGIN
				--下次执行日期<当前
				--如果间隔内循环 分钟
				IF @FreqSubdayType >= 4
				BEGIN
					IF @FreqSubdayType = 8
						SELECT @FreqSubdayInterval = @FreqSubdayInterval * 60
					--计算到下次执行，间隔多少分钟
					SELECT @Exceeding = DATEDIFF(MINUTE, @PlanTime, @Now) % @FreqSubdayInterval
					IF(@Exceeding > 0)
						SELECT @Exceeding = @FreqSubdayInterval - @Exceeding

					SELECT @NextRunTime = DATEADD(MINUTE, @Exceeding, @Now)
					IF @NextRunTime <= @Now	--如果是当前一分钟，则+1分钟
						SELECT @NextRunTime = DATEADD(MINUTE, @FreqSubdayInterval, @NextRunTime)
					IF @NextRunTime < CONVERT(VARCHAR(10), @Now + 1, 120)
						SELECT @IsOk = 1
				END
				IF(@IsOk = 0)	--间隔内不循环或者本日无法循环，则到下一执行日期
					SET @NextRunTime = @PlanTime + @FreqInterval
			END
		END
	END
	ELSE IF @FreqType = 8	--按周间隔，周、月都是执行一次
	BEGIN
		DECLARE @w AS INT, @TodayPower AS INT
		SELECT @w = DATEPART(W, @Now)	--1周日，2 周一，。。。7周六
		SELECT @TodayPower = POWER(2, @w - 1), @i = 8, @Exceeding = 7

		IF (@FreqInterval & @TodayPower = @TodayPower)	--今日是执行日期
		BEGIN
			SELECT @PlanTime = dbo.MergeDate(@Now, @ActiveStartTime)
			IF @PlanTime > @Now		--执行时间
				SELECT @NextRunTime = @PlanTime, @IsOk = 1
		END

		IF(@IsOk = 0)	--本日不执行，或者本日时间已过，则到下一执行日期
		BEGIN
			WHILE @I < 15
			BEGIN
				IF (@FreqInterval & POWER(2, @I - 8) = POWER(2, @I - 8))
				BEGIN
					SELECT @II = (@i - @w) % 7
					IF(@Exceeding > @II AND @II > 0)
						SET @Exceeding = @II
				END
				SET @i = @i + 1
			END
			SELECT @NextRunTime = dbo.MergeDate(@Now, @ActiveStartTime) + @Exceeding, @IsOk = 1
		END
	END
	ELSE IF @FreqType = 16	--按月间隔，周、月都是执行一次
	BEGIN
		SELECT @Exceeding = DATEDIFF(MONTH, @StartDate, @Now) / @FreqInterval, @I = 1
		SELECT @PlanTime = DATEADD(MONTH, @Exceeding * @FreqInterval, @StartDate)
		WHILE @PlanTime < @Now
		BEGIN
			SELECT @PlanTime = DATEADD(MONTH, @FreqInterval, @PlanTime)
			SELECT @I = @I + 1	
		END
		SET @NextRunTime = @PlanTime
	END
	RETURN @NextRunTime
END

GO
/****** Object:  UserDefinedFunction [dbo].[GetNumber]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[GetNumber]
(
	@Text NVARCHAR(100)
)
RETURNS INT
AS
BEGIN
	DECLARE @I INT, @chr NCHAR(1), @Id VARCHAR(10)
	SELECT @i = 0, @Id = ''
	WHILE @i < LEN(@Text)
	BEGIN
		SET @i = @i + 1
		SET @chr = SUBSTRING(@Text, @i, 1)
		IF @Chr IN('0', '1', '2', '3', '4', '5', '6', '7', '8', '9')
			SET @Id = @Id + @Chr
		ELSE
			IF LEN(@Id) > 0
				BREAK 
	END

	IF LEN(@Id) > 0
		SET @i = CONVERT(INT, @Id)
	ELSE
		SET @i = 0

	RETURN @i
END

GO
/****** Object:  UserDefinedFunction [dbo].[GetOldManagerUserName]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE function [dbo].[GetOldManagerUserName]
(
	@ManagerUserId INT,
	@Date DATETIME
)
RETURNS NVARCHAR(10)
AS
BEGIN
	DECLARE @N AS NVARCHAR(10)
	SELECT TOP 1 @n = a.Name
	FROM OaDb..WorkUser a, Oadb..Contract b
	WHERE a.ManagerUserId = @ManagerUserId
	AND a.Id = b.WorkUserId
	AND @Date BETWEEN b.BeginDate AND b.RealEndDate
	--ORDER BY ISNULL(AnnualDate, AddDate + 365) DESC

	IF ISNULL(@N, '') = ''
		SELECT @n = Name FROM MainDb..ManagerUser WHERE Id = @ManagerUSerId

	RETURN @n
END
GO
/****** Object:  UserDefinedFunction [dbo].[GetPaName]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--#########################################################33
--Lambo 20110221
--Lucifer 20180425
--#########################################################33
CREATE FUNCTION [dbo].[GetPaName] 
(
	@cvMainID INT,
	@cpMainID INT
)
RETURNS NVARCHAR(20)
AS
BEGIN
	DECLARE @ReturnName NVARCHAR(20),
		@cpMemeberType INT,
		@Name NVARCHAR(20),
		@JobName NVARCHAR(50),
		@IsNameHiden BIT,
		@Gender BIT,
		@showType INT,
		@SecondId VARCHAR(10)

	SELECT TOP 1 @Name = b.Name,
		@Gender = b.Gender,
		@JobName = a.JobName,
		@IsNameHiden = a.IsNameHidden ,
		@SecondId = a.SecondId
	FROM cvMain a WITH(NOLOCK)
	INNER JOIN paMain b WITH(NOLOCK) ON a.paMainID = b.ID
	WHERE a.ID = @cvMainID

	SET @showType = dbo.GetChatPrivi(@cvMainID, @cpMainID)
	IF @showType = 0
	BEGIN
		SET @ReturnName = ISNULL(@JobName, @SecondId)
	END
	ELSE
	BEGIN
		IF EXISTS (SELECT 'x' FROM ExJobApply a WITH(NOLOCK),Job b 
			WHERE a.JobID = b.ID 
			AND a.cvMainID = @cvMainID
			AND b.cpMainID = @cpMainID
		)
			SET @ReturnName = @Name
		ELSE
		BEGIN
			IF @IsNameHiden = 1
			BEGIN
				IF @Gender = 1 
					SET @ReturnName = LEFT(@Name, 1) + '女士/小姐'
				ELSE
					SET @ReturnName = LEFT(@Name, 1) + '先生'
			END
			ELSE
				SET @ReturnName = @Name
		END
	END
	RETURN @ReturnName
END


GO
/****** Object:  UserDefinedFunction [dbo].[GetPaOnlineStatus]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[GetPaOnlineStatus]
(
	@paMainID INT
)
RETURNS BIT
AS
BEGIN
	DECLARE @IsOnline AS BIT
	SELECT @IsOnline = IsOnline FROM paOnline With(NOLOCK) WHERE paMainID = @paMainID

	RETURN ISNULL(@IsOnline, 0)
END

GO
/****** Object:  UserDefinedFunction [dbo].[GetPaPhotoByCpView]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[GetPaPhotoByCpView]
(
	@cvMainID INT,
	@cpMainID INT
)
RETURNS VARCHAR(50)
AS
BEGIN
	DECLARE @PhotoPath VARCHAR(50)
	
	DECLARE @MemberType TINYINT
	
	SELECT @MemberType = MemberType 
	FROM cpMain WITH(NOLOCK)
	WHERE id = @cpMainID
	
	IF @MemberType < 2
		RETURN ''
	
	DECLARE @isInActiveLog INT, @isInDailyGiftLog INT, @isApplyCount INT, @paMainID INT

	SELECT @isInActiveLog = 0, @isInDailyGiftLog = 0, @isApplyCount = 0

	IF EXISTS(SELECT TOP 1 'x'
		FROM cpCvPrivi WITH(NOLOCK)
		WHERE cpMainID = @cpMainID
		AND cvMainID = @cvMainID)
		SET @isInDailyGiftLog = 1

--sean modify at 2018-3-6
--	IF @isInDailyGiftLog = 0
--		IF EXISTS(SELECT TOP 1 'x'
--			FROM caDailyGiftLog WITH(NOLOCK INDEX(PK_caDailyGiftLog))
--			WHERE cpMainID = @cpMainID
--			AND cvMainID = @cvMainID)
--			SET @isInDailyGiftLog = 1
--
--	IF @isInDailyGiftLog = 0
--	BEGIN
--		DECLARE @t AS TABLE(ID INT)
--		INSERT INTO @t
--		SELECT ID FROM cvMain WITH(NOLOCK) WHERE paMainId = @paMainID
--
--		IF EXISTS(SELECT TOP 1 'x'
--			FROM caActiveLog WITH(NOLOCK INDEX(IX_caActiveLog_cpMainID))
--			WHERE cpMainID = @cpMainID
--			AND cvMainID IN(SELECT ID FROM @t))
--			SET @isInActiveLog = 1
--		
--		IF @isInActiveLog = 0
--			IF EXISTS(SELECT TOP 1 'x'
--				FROM ExJobApply a WITH(NOLOCK), Job b 
--				WHERE a.JobID = b.ID 
--				AND a.IsPassed = 1 
--				AND a.cvMainID IN(SELECT ID FROM @t)
--				AND b.cpMainID = @cpMainID)
--				SET @isApplyCount = 1
--	END

	IF @isInActiveLog + @isInDailyGiftLog + @isApplyCount = 0 
		RETURN ''

	SELECT @paMainId = paMainId FROM cvMain WITH(NOLOCK) WHERE ID = @cvMainID

	SELECT @PhotoPath = PhotoProcessed 
	FROM paPhoto a WITH(NOLOCK INDEX(IX_paPhoto_paMainId)) 
	WHERE paMainID = @paMainId
	
	RETURN @PhotoPath
END

GO
/****** Object:  UserDefinedFunction [dbo].[GetPersonName]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#########################################################33
--Lucifer 20131202
--Lucifer 20180425
--#########################################################33
CREATE FUNCTION [dbo].[GetPersonName] 
(
	@cvMainID INT,
	@cpMainID INT
)
RETURNS VARCHAR(50)
AS
BEGIN
	RETURN dbo.GetPaName(@cvMainID, @cpMainID)
	--DECLARE @ReturnName NVARCHAR(20)
	--DECLARE @cpMemeberType INT
	--DECLARE @Name NVARCHAR(20)
	--DECLARE @JobName NVARCHAR(20)
	--DECLARE @IsNameHiden BIT
	--DECLARE @Gender BIT
	--DECLARE @showType INT
	--DECLARE @showDownload INT

	--SELECT TOP 1 @Name = b.Name,
	--	@Gender = b.Gender,
	--	@JobName = a.JobName,
	--	@IsNameHiden = a.IsNameHidden 
	--FROM cvMain a WITH(NOLOCK)
	--INNER JOIN paMain b WITH(NOLOCK) ON a.paMainID = b.ID
	--WHERE a.ID = @cvMainID

	--SELECT @cpMemeberType = MemberType FROM cpMain WITH(NOLOCK) WHERE ID = @cpMainID

	--SET @showType = 1		--0姓名；1职位, 2不隐藏姓名
	--SET @showDownload = 0
	--IF EXISTS (
	--	SELECT 'x' FROM ExJobApply a WITH(NOLOCK),Job b 
	--	WHERE a.JobID = b.ID 
	--	AND a.cvMainID = @cvMainID
	--	AND b.cpMainID = @cpMainID
	--)	
	--	SET @showType = 2
	--ELSE IF @cpMemeberType IN(10, 11)
	--BEGIN
	--	IF EXISTS(
	--		SELECT 'x' FROM CaCvQuotaLog WITH(NOLOCK)
	--		WHERE cpMainID = @cpMainID
	--		AND cvMainID = @cvMainID
	--	)
	--		SET @showType = 0
	--	ELSE
	--	BEGIN
	--		IF @cpMemeberType = 11
	--			IF EXISTS(
	--				SELECT 'x' FROM caBalanceLog WITH(NOLOCK)
	--				WHERE cpMainID = @cpMainID
	--				AND cvMainID = @cvMainID
	--				AND CONVERT(VARCHAR(100), AddDate, 23) = CONVERT(VARCHAR(100), GETDATE(), 23)
	--			) 
	--				SET @showType = 0
	--	END
	--END
	--ELSE
	--BEGIN
	--	DECLARE @isInActiveLog INT
	--	DECLARE @isInDailyGiftLog INT
	--	----日赠送中有下载
	--	SELECT @isInDailyGiftLog = COUNT(1) FROM caDailyGiftLog WITH(NOLOCK)
	--	WHERE cpMainID = @cpMainID
	--	AND cvMainID = @cvMainID

	--	IF @isInDailyGiftLog > 0
	--	BEGIN
	--		SET @showType = 0
	--		SET @showDownload = 1
	--	END
	--	ELSE
	--	BEGIN
	--		----简历下载中有下载
	--		SELECT @isInActiveLog = COUNT(1) FROM caActiveLog WITH(NOLOCK)
	--		WHERE cpMainID = @cpMainID
	--		AND cvMainID = @cvMainID

	--		If @isInActiveLog>0
	--		BEGIN
	--			SET @showType = 0
	--			SET @showDownload = 1
	--		END
	--		ELSE
	--		BEGIN
	--			----申请职位是的新状态是pass
	--			IF EXISTS (
	--				SELECT 'x' FROM ExJobApply a WITH(NOLOCK),Job b WITH(NOLOCK)
	--				WHERE a.JobID = b.ID 
	--				AND a.IsPassed = 1 
	--				AND a.cvMainID = @cvMainID
	--				AND b.cpMainID = @cpMainID
	--			)
	--				SET @showType = 0
	--		END
	--	END
	--END

	--IF @showType = 0	--姓名
	--BEGIN
	--	SET @ReturnName = @Name
	--	IF @IsNameHiden = 1 
	--		IF @Gender = 1 
	--			SET @ReturnName = LEFT(@ReturnName, 1) + '女士/小姐'
	--		ELSE
	--			SET @ReturnName = LEFT(@ReturnName, 1) + '先生'
	--END
	--ELSE IF @showType = 2	--姓名
	--	SET @ReturnName = @Name
	--ELSE
	--	SET @ReturnName = ISNULL(@JobName, LTRIM(STR(@cvMainID)))

	--IF @showDownload > 0
	--	SET @ReturnName = '$$##' + @ReturnName

	--RETURN @ReturnName
END
GO
/****** Object:  UserDefinedFunction [dbo].[GetPrivi]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[GetPrivi]
(
	@ManagerUserID AS SMALLINT,
	@DataSourceID INT,
	@Pos INT
)
RETURNS CHAR(1)
AS
BEGIN
	DECLARE @RoleID AS INT, @Privi AS VARCHAR(20)
	SELECT @RoleID = RoleID FROM ManagerUser WITH(NOLOCK) WHERE ID = @ManagerUserID

	SELECT @Privi = Privi
	FROM Role_DataSource WITH(NOLOCK)
	WHERE RoleID = @RoleID
	AND DataSourceID = @DataSourceID
	
	IF LEN(ISNULL(@Privi, '')) = 0
		RETURN 'x'

	RETURN SUBSTRING(@Privi, @Pos, 1)
END

GO
/****** Object:  UserDefinedFunction [dbo].[GetPyFirst]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[GetPyFirst](
  @str NVARCHAR(100)
)
RETURNS  NVARCHAR(4000)  
AS
BEGIN  
	DECLARE @intLen INT
	DECLARE @strRet NVARCHAR(4000)  
	DECLARE @temp  NVARCHAR(100)  
	SET @intLen = LEN(@str)  
	SET @strRet = ''  
	WHILE @intLen > 0  
	BEGIN
		SET @temp = ''  
		SELECT @temp = CASE    
		WHEN SUBSTRING(@str,@intLen,1)  >=  '帀' THEN 'Z'  
		WHEN SUBSTRING(@str,@intLen,1)  >=  '丫' THEN 'Y'  
		WHEN SUBSTRING(@str,@intLen,1)  >=  '夕' THEN 'X'  
		WHEN SUBSTRING(@str,@intLen,1)  >=  '屲' THEN 'W'  
		WHEN SUBSTRING(@str,@intLen,1)  >=  '他' THEN 'T'  
		WHEN SUBSTRING(@str,@intLen,1)  >=  '仨' THEN 'S'  
		WHEN SUBSTRING(@str,@intLen,1)  >=  '呥' THEN 'R'  
		WHEN SUBSTRING(@str,@intLen,1)  >=  '七' THEN 'Q'  
		WHEN SUBSTRING(@str,@intLen,1)  >=  '妑' THEN 'P'  
		WHEN SUBSTRING(@str,@intLen,1)  >=  '噢' THEN 'O'  
		WHEN SUBSTRING(@str,@intLen,1)  >=  '拏' THEN 'N'  
		WHEN SUBSTRING(@str,@intLen,1)  >=  '嘸' THEN 'M'  
		WHEN SUBSTRING(@str,@intLen,1)  >=  '垃' THEN 'L'  
		WHEN SUBSTRING(@str,@intLen,1)  >=  '咔' THEN 'K'  
		WHEN SUBSTRING(@str,@intLen,1)  >=  '丌' THEN   'J'  
		WHEN SUBSTRING(@str,@intLen,1)  >=  '铪' THEN 'H'  
		WHEN SUBSTRING(@str,@intLen,1)  >=  '旮' THEN 'G'  
		WHEN SUBSTRING(@str,@intLen,1)  >=  '发' THEN 'F'  
		WHEN SUBSTRING(@str,@intLen,1)  >=  '妸' THEN 'E'  
		WHEN SUBSTRING(@str,@intLen,1)  >=  '咑' THEN 'D'  
		WHEN SUBSTRING(@str,@intLen,1)  >=  '嚓' THEN 'C'  
		WHEN SUBSTRING(@str,@intLen,1)  >=  '八' THEN 'B'  
		WHEN SUBSTRING(@str,@intLen,1)  >=  '吖' THEN 'A'  
		ELSE RTRIM(LTRIM(SUBSTRING(@str,@intLen,1)))  
		END 
		--对于汉字特殊字符，不生成拼音码  
		IF ASCII(@temp) > 127
			SET @temp = ''
		--对于英文中小括号，不生成拼音码  
		IF @temp = '(' OR @temp = ')'
			SET @temp = ''
		SELECT @strRet = @temp + @strRet
		SET @intLen = @intLen - 1
	END
	RETURN LOWER(@strRet)  
END
GO
/****** Object:  UserDefinedFunction [dbo].[GetRegionAll]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE function [dbo].[GetRegionAll]
(
	@ID VARCHAR(6)
)
RETURNS NVARCHAR(20)
AS 
BEGIN
	RETURN (SELECT FullName FROM dcREgion WITH(NOLOCK) WHERE ID = @ID)
END

GO
/****** Object:  UserDefinedFunction [dbo].[GetThreeJobIds]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[GetThreeJobIds]
(
	@JobIds AS VARCHAR(MAX)
)
RETURNS @Temp TABLE(Id INT)
AS
BEGIN
	DECLARE @i INT, @Num INT, @StrSource VARCHAR(MAX), @s VARCHAR(50)
	SELECT @StrSource = REPLACE(RTRIM(LTRIM(@JobIds)), 'N', '')
	SELECT @i = CHARINDEX(',', @StrSource), @Num = 0, @s = ''

	IF @i = 0
	BEGIN
		IF @StrSource > ''
			INSERT INTO @Temp VALUES(@StrSource)

		RETURN
	END

	WHILE @i >= 1 AND @Num < 3
	BEGIN
		IF LEFT(@StrSource, @i - 1) > '' 
		BEGIN
			INSERT INTO @Temp VALUES(LEFT(@StrSource, @i - 1))
			SELECT @Num = @Num + 1
		END
		SELECT @StrSource = SUBSTRING(@StrSource, @i + 1, LEN(@StrSource) - @i)
		SELECT @i = CHARINDEX(',', @StrSource)
	END

	IF @Num < 3 AND @StrSource <> '' AND @i = 0
		INSERT INTO @Temp VALUES(@StrSource)
	
	IF LEFT(@s, 1) = ','
		INSERT INTO @Temp VALUES(RIGHT(@s, LEN(@s) - 1))

	RETURN
END

GO
/****** Object:  UserDefinedFunction [dbo].[GetThreeJobIdsold]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create FUNCTION [dbo].[GetThreeJobIdsold]
(
	@JobIds AS VARCHAR(MAX)
)
RETURNS @Temp TABLE(Id INT)
AS
BEGIN
	DECLARE @i INT, @Num INT, @StrSource VARCHAR(MAX), @s VARCHAR(50)
	SELECT @StrSource = RTRIM(LTRIM(@JobIds))
	SELECT @i = CHARINDEX(',', @StrSource), @Num = 0, @s = ''

	IF @i = 0
	BEGIN
		IF @StrSource > ''
			INSERT INTO @Temp VALUES(@StrSource)

		RETURN
	END

	WHILE @i >= 1 AND @Num < 3
	BEGIN
		IF LEFT(@StrSource, @i - 1) > '' 
		BEGIN
			INSERT INTO @Temp VALUES(LEFT(@StrSource, @i - 1))
			SELECT @Num = @Num + 1
		END
		SELECT @StrSource = SUBSTRING(@StrSource, @i + 1, LEN(@StrSource) - @i)
		SELECT @i = CHARINDEX(',', @StrSource)
	END

	IF @Num < 3 AND @StrSource <> '' AND @i = 0
		INSERT INTO @Temp VALUES(@StrSource)
	
	IF LEFT(@s, 1) = ','
		INSERT INTO @Temp VALUES(RIGHT(@s, LEN(@s) - 1))

	RETURN
END

GO
/****** Object:  UserDefinedFunction [dbo].[GetTop5JobIDs]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create FUNCTION [dbo].[GetTop5JobIDs]
(
	@JobIds AS VARCHAR(MAX)
)
RETURNS VARCHAR(MAX)
AS
BEGIN
	DECLARE @i INT, @Num INT, @StrSource VARCHAR(MAX), @s VARCHAR(50)
	SELECT @StrSource = RTRIM(LTRIM(@JobIds))
	SELECT @i = CHARINDEX(',', @StrSource), @Num = 0, @s = ''

	IF @i = 0
		RETURN @StrSource

	WHILE @i >= 1 AND @Num < 5
	BEGIN
		IF LEFT(@StrSource, @i - 1) > '' 
			SELECT @s = @s + ',' + LEFT(@StrSource, @i - 1), @Num = @Num + 1

		SELECT @StrSource = SUBSTRING(@StrSource, @i + 1, LEN(@StrSource) - @i)
		SELECT @i = CHARINDEX(',', @StrSource)
	END

	IF @Num < 5 AND @StrSource <> '' AND @i = 0
		SELECT @s = @s + ',' + @StrSource
	
	IF LEFT(@s, 1) = ','
		SELECT @s = RIGHT(@s, LEN(@s) - 1)
	RETURN @s
END


GO
/****** Object:  UserDefinedFunction [dbo].[HaveChinese]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Function [dbo].[HaveChinese]
(
	@Str varchar(4000)
)
RETURNS BIT
AS
BEGIN
	DECLARE @IsHave BIT
	IF @Str LIKE N'%[吖-咗]%' COLLATE Chinese_PRC_CI_AS
	BEGIN
		SET @IsHave = 1
	END
	ELSE
	BEGIN
		SET @IsHave = 0
	END
	RETURN @IsHave
END

GO
/****** Object:  UserDefinedFunction [dbo].[HtmlPos]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[HtmlPos]
(
	@s VARCHAR(MAX)
)
RETURNS INT
AS
BEGIN
	DECLARE @t AS TABLE(P INT)
	
	INSERT @t SELECT CHARINDEX('<p', @s)
	INSERT @t SELECT CHARINDEX('<strong', @s)
	INSERT @t SELECT CHARINDEX('<div', @s)
	INSERT @t SELECT CHARINDEX('<font', @s)
	INSERT @t SELECT CHARINDEX('<span', @s)
	INSERT @t SELECT CHARINDEX('<b', @s)
	INSERT @t SELECT CHARINDEX('</', @s)

	RETURN ISNULL((SELECT MIN(p) FROM @t WHERE p > 0), 0)
END
GO
/****** Object:  UserDefinedFunction [dbo].[Int2Bin]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create FUNCTION [dbo].[Int2Bin](@i int)
returns varchar(31)
as
begin
    declare @s varchar(31);
    set @s=''
    while (@i>0)
        select @s=cast(@i%2 as varchar)+@s, @i=@i/2
 
    return(@s)
end

GO
/****** Object:  UserDefinedFunction [dbo].[IpPlace]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Function [dbo].[IpPlace]
(
	@Str varchar(31)
)
RETURNS NVARCHAR(100)
AS
BEGIN
	DECLARE @A1 VARCHAR(3), @A2 VARCHAR(3), @A3 VARCHAR(3), @A4 VARCHAR(3)
	DECLARE @b1 BIGINT, @b2 INT, @B3 INT, @B4 INT
	SELECT @A1 = SUBSTRING(@Str, 1, CHARINDEX('.', @Str)), @Str = SUBSTRING(@Str, CHARINDEX('.', @Str) + 1, LEN(@Str))
	SELECT @A2 = SUBSTRING(@Str, 1, CHARINDEX('.', @Str)), @Str = SUBSTRING(@Str, CHARINDEX('.', @Str) + 1, LEN(@Str))
	SELECT @A3 = SUBSTRING(@Str, 1, CHARINDEX('.', @Str)), @Str = SUBSTRING(@Str, CHARINDEX('.', @Str) + 1, LEN(@Str))
	SELECT @A4 = @str

	SELECT @B1 = CONVERT(INT, REPLACE(@A1, '.', '')),
		@B2 = CONVERT(INT, REPLACE(@A2, '.', '')),
		@B3 = CONVERT(INT, REPLACE(@A3, '.', '')),
		@B4 = CONVERT(INT, REPLACE(@A4, '.', ''))

	SELECT @B1 = @B1 * 256*256*256 + @B2 * 256*256 + @b3 * 256 + @b4

	RETURN (SELECT TOP 1 City + ' ' + Provider FROM dcIpPlace WITH(NOLOCK) WHERE @B1 BETWEEN IpStart AND IpEnd)
END


GO
/****** Object:  UserDefinedFunction [dbo].[IpPlaceToInt]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Function [dbo].[IpPlaceToInt]
(
	@Str varchar(31)
)
RETURNS BIGINT
AS
BEGIN
	IF @Str NOT LIKE '%.%.%.%'
		RETURN 0

	DECLARE @A1 VARCHAR(3), @A2 VARCHAR(3), @A3 VARCHAR(3), @A4 VARCHAR(3)
	DECLARE @b1 BIGINT, @b2 INT, @B3 INT, @B4 INT
	SELECT @A1 = SUBSTRING(@Str, 1, CHARINDEX('.', @Str)), @Str = SUBSTRING(@Str, CHARINDEX('.', @Str) + 1, LEN(@Str))
	SELECT @A2 = SUBSTRING(@Str, 1, CHARINDEX('.', @Str)), @Str = SUBSTRING(@Str, CHARINDEX('.', @Str) + 1, LEN(@Str))
	SELECT @A3 = SUBSTRING(@Str, 1, CHARINDEX('.', @Str)), @Str = SUBSTRING(@Str, CHARINDEX('.', @Str) + 1, LEN(@Str))
	SELECT @A4 = @str

	SELECT @B1 = CONVERT(INT, REPLACE(@A1, '.', '')),
		@B2 = CONVERT(INT, REPLACE(@A2, '.', '')),
		@B3 = CONVERT(INT, REPLACE(@A3, '.', '')),
		@B4 = CONVERT(INT, REPLACE(@A4, '.', ''))

	RETURN @B1 * 256*256*256 + @B2 * 256*256 + @b3 * 256 + @b4
END


GO
/****** Object:  UserDefinedFunction [dbo].[IsAccount]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--######################################################3
--检查是否有效账号
--######################################################3
CREATE FUNCTION [dbo].[IsAccount]
(
	@str VARCHAR(50)
)
RETURNS BIT
AS
BEGIN
	DECLARE @ok AS BIT
	SET @ok = 1

	IF @str IS NULL
		SET @ok = 0
	
	IF @ok = 1
	BEGIN
		SET @str = LOWER(LTRIM(RTRIM(@str)))
		IF (LEN(@str) > 50) OR (LEN(@str) < 6)
			SET @ok = 0
	END
	IF @str LIKE '% %'
		RETURN 0

	IF @ok = 1
	BEGIN
		DECLARE @I AS INT
		DECLARE @ValidChars AS VARCHAR(39)
		SET @ValidChars = 'abcdefghijklmnopqrstuvwxyz0123456789-_.'

		SET @I = 1
		WHILE @I <= LEN(@str)
		BEGIN
			IF CHARINDEX(SUBSTRING(@str, @I, 1), @ValidChars) > 0
				SET @I = @I + 1
			ELSE
			BEGIN
				SET @ok = 0
				SET @I = 100
			END
		END
	END
	RETURN @ok
END




GO
/****** Object:  UserDefinedFunction [dbo].[IsChinese]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--######################################################3
--检查是否汉字
--######################################################3
CREATE FUNCTION [dbo].[IsChinese]
(
	@str VARCHAR(MAX)
)
RETURNS BIT
AS
BEGIN
	DECLARE @ok AS BIT
	SET @ok = 1

	IF ISNULL(@str, '') = ''
		SET @ok = 0

	IF @ok = 1
	BEGIN
		DECLARE @I AS INT

		SET @I = 1
		WHILE @I <= LEN(@str)
		BEGIN
			IF dbo.HaveChinese(SUBSTRING(@str, @I, 1)) = 1
				SET @I = @I + 1
			ELSE
			BEGIN
				SET @ok = 0
				SET @I = LEN(@str) + 1
			END
		END
	END

	RETURN @ok
END


GO
/****** Object:  UserDefinedFunction [dbo].[IsEmail]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--######################################################3
--检查是否有效邮箱
--######################################################3
CREATE FUNCTION [dbo].[IsEmail]
(
	@str VARCHAR(100)
)
RETURNS BIT
AS
BEGIN
	DECLARE @ok AS BIT
	SET @ok = 1

	IF @str IS NULL
		SET @ok = 0
	
	IF @ok = 1
	BEGIN
		SET @str = LOWER(LTRIM(RTRIM(@str)))
		IF LEN(@str) > 50 OR LEN(@str) < 6
			SET @ok = 0
	END

	IF @Str LIKE '% %'
		RETURN 0

	IF @ok = 1
	BEGIN
		DECLARE @t AS TABLE(ID INT IDENTITY(1, 1), S VARCHAR(50))
		INSERT INTO @t (s)
		SELECT * FROM dbo.fnSplit(@str, '@')

		IF(SELECT COUNT(1) FROM @t) <> 2
			SET @ok = 0
		ELSE
		BEGIN
			DECLARE @str1 AS VARCHAR(50)
			SELECT @str1 = S FROM @t WHERE ID = 1
			IF dbo.IsEmailText(@str1, 1) = 0
				SET @ok = 0
			ELSE
			BEGIN
				SELECT @str1 = S FROM @t WHERE ID = 2
				IF dbo.IsEmailText(@str1, 2) = 0
					SET @ok = 0
			END
		END
	END
	RETURN @ok
END


GO
/****** Object:  UserDefinedFunction [dbo].[IsEmailText]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--######################################################3
--检查是否有效邮箱文本,@前后的一部分
--######################################################3
CREATE FUNCTION [dbo].[IsEmailText]
(
	@str VARCHAR(50),
	@Pos INT		--1@前，2@后
)
RETURNS BIT
AS
BEGIN
	DECLARE @ok AS BIT
	SET @ok = 1

	IF @str IS NULL
		SET @ok = 0

	
	IF @ok = 1
	BEGIN
		SET @str = LOWER(LTRIM(RTRIM(@str)))
		IF (LEN(@str) > 45) OR (LEN(@str) < 1)
			SET @ok = 0
	END

	IF @ok = 1
	BEGIN
		IF @Pos = 1 AND (LEFT(@str, 1) IN ('.', '-', '_') OR RIGHT(@str, 1) IN ('.', '-', '_'))
			SET @ok = 0
		IF @Pos = 2 AND (LEFT(@str, 1) = ('.') OR RIGHT(@str, 1) IN ('.', '-', '_'))
			SET @ok = 0
		IF CHARINDEX('..', @str) > 0
			SET @ok = 0
	END

	IF @ok = 1
		IF @pos = 2
			IF CHARINDEX('.', @str) = 0
				SET @ok = 0
			ELSE
			BEGIN
				DECLARE @t AS TABLE(ID INT IDENTITY(1, 1), S VARCHAR(50))
				INSERT INTO @t(S) SELECT * FROM dbo.fnSplit(@str, '.')
				DECLARE @s AS VARCHAR(50)
				SELECT TOP 1 @s = S FROM @t ORDER BY ID DESC
				IF LEN(@s) < 2 OR LEN(@s) > 4
					SET @ok = 0
			END
	IF @ok = 1
	BEGIN
		DECLARE @I AS INT, @ValidChars AS VARCHAR(39)
		SET @ValidChars = 'abcdefghijklmnopqrstuvwxyz0123456789-_.'

		SET @I = 1
		WHILE @I <= LEN(@str)
		BEGIN
			IF CHARINDEX(SUBSTRING(@str, @I, 1) collate Chinese_PRC_CI_AS_KS_WS, @ValidChars) > 0
				SET @I = @I + 1
			ELSE
			BEGIN
				SET @ok = 0
				SET @I = 100
			END
		END
	END
	
	RETURN @ok
END
GO
/****** Object:  UserDefinedFunction [dbo].[IsEnglish]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--######################################################3
--检查是否English
--######################################################3
CREATE FUNCTION [dbo].[IsEnglish]
(
	@str VARCHAR(MAX)
)
RETURNS BIT
AS
BEGIN
	DECLARE @ok AS BIT
	SET @ok = 1

	IF @str IS NULL
		SET @ok = 0

	IF @ok = 1
	BEGIN
		DECLARE @I AS INT
		DECLARE @ValidChars AS VARCHAR(39)
		SET @ValidChars = 'abcdefghijklmnopqrstuvwxyz'

		SET @I = 1
		WHILE @I <= LEN(@str)
		BEGIN
			IF CHARINDEX(SUBSTRING(@str, @I, 1), @ValidChars) > 0
				SET @I = @I + 1
			ELSE
			BEGIN
				SET @ok = 0
				SET @I = LEN(@str) + 1
			END
		END
	END

	RETURN @ok
END

GO
/****** Object:  UserDefinedFunction [dbo].[IsFullWidth]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--######################################################3
--检查是否全角
--######################################################3
CREATE FUNCTION [dbo].[IsFullWidth]
(
	@str VARCHAR(MAX)
)
RETURNS BIT
AS
BEGIN
	DECLARE @ok AS BIT
	IF DATALENGTH(@str) = LEN(@str) * 2
		SET @ok = 1
	ELSE
		SET @ok = 0

	IF LEN(ISNULL(@str, '')) = 0
		SET @ok = 0

	RETURN @ok
END

GO
/****** Object:  UserDefinedFunction [dbo].[IsINT]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--######################################################3
--检查是否INT
--######################################################3
CREATE FUNCTION [dbo].[IsINT]
(
	@str VARCHAR(MAX)
)
RETURNS BIT
AS
BEGIN
	DECLARE @ok AS BIT
	SET @ok = 1

	IF @str IS NULL
		SET @ok = 0

	IF @ok = 1
	BEGIN
		DECLARE @I AS INT
		DECLARE @ValidChars AS VARCHAR(39)
		SET @ValidChars = '0123456789'

		SET @I = 1
		WHILE @I <= LEN(@str)
		BEGIN
			IF CHARINDEX(SUBSTRING(@str, @I, 1), @ValidChars) > 0
				SET @I = @I + 1
			ELSE
			BEGIN
				SET @ok = 0
				SET @I = LEN(@str) + 1
			END
		END
	END

	RETURN @ok
END




GO
/****** Object:  UserDefinedFunction [dbo].[IsJobApplyFilter]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[IsJobApplyFilter]
(
	@JobID INT,
	@cvMainID INT
)
RETURNS BIT
AS
BEGIN
	--获取职位的过滤条件
	DECLARE @FilterMaxDegree AS TINYINT
	DECLARE @FilterMinDegree AS TINYINT
	DECLARE @FilterMaxWorkYear AS TINYINT
	DECLARE @FilterMinWorkYear AS TINYINT
	DECLARE @FilterMaxAge AS TINYINT
	DECLARE @FilterMinAge AS TINYINT
	DECLARE @FilterGender AS VARCHAR(1)
	DECLARE @FilterJobRegion AS VARCHAR(6)
	DECLARE @FilterCvMainID AS VARCHAR(200)
	DECLARE @cpMainID AS INT
	SELECT 
		@FilterMaxDegree = FilterMaxDegree,
		@FilterMinDegree = FilterMinDegree,
		@FilterMaxWorkYear = FilterMaxWorkYear,
		@FilterMinWorkYear = FilterMinWorkYear,
		@FilterMaxAge = FilterMaxAge,
		@FilterMinAge = FilterMinAge,
		@FilterGender = FilterGender,
		@FilterJobRegion = FilterJobRegion,
		@FilterCvMainID = FilterCvMainID,
		@cpMainID = cpMainID
	FROM Job WITH(NOLOCK)
	WHERE ID = @JobID

	--获取简历的相关条件
	DECLARE	@Gender AS BIT
	DECLARE	@Age AS TINYINT
	DECLARE @LivePlace AS VARCHAR(6)
	DECLARE	@RelatedWorkYears AS TINYINT
	DECLARE @Degree AS TINYINT
	SELECT 
		@LivePlace = b.LivePlace,
		@Gender = b.Gender,
		@Age = dbo.BirthToAge(b.birthday),
		@RelatedWorkYears = a.RelatedWorkYears,
		@Degree = a.Degree
	FROM cvMain a,paMain b WHERE a.ID=@cvMainID AND a.paMainID=b.ID
	
	--判断性别
	IF LEN(@Gender) <> 0 AND LEN(@FilterGender) <> 0
	BEGIN
		IF @Gender <> @FilterGender
			RETURN 1
	END
	--判断年龄
	IF LEN(@Age) <> 0
	BEGIN
		IF LEN(@FilterMaxAge) <> 0 AND @FilterMaxAge <> 99
		BEGIN
			IF @Age > @FilterMaxAge
			BEGIN
				RETURN 1
			END
		END
		IF LEN(@FilterMinAge) <> 0 AND @FilterMinAge <> 99
		BEGIN
			IF @Age < @FilterMinAge
			BEGIN
				RETURN 1
			END
		END
	END
	--判断工作年限
	IF LEN(@RelatedWorkYears) <> 0
	BEGIN
		IF LEN(@FilterMaxWorkYear) <> 0 AND @FilterMaxWorkYear <> 0
			IF @RelatedWorkYears > @FilterMaxWorkYear
				RETURN 1

		IF LEN(@FilterMinWorkYear) <> 0 AND @FilterMinWorkYear <> 0
			IF @RelatedWorkYears < @FilterMinWorkYear
				RETURN 1
	END
	--判断学历
	IF LEN(@Degree) <> 0
	BEGIN
		IF LEN(@FilterMaxDegree) <> 0 AND @FilterMaxDegree <> 0
			IF @Degree > @FilterMaxDegree
				RETURN 1

		IF LEN(@FilterMinDegree) <> 0 AND @FilterMinDegree <> 0
			IF @Degree < @FilterMinDegree
				RETURN 1
	END
	--判断地区
	IF LEN(@LivePlace) <> 0 AND LEN(@FilterJobRegion) <> 0 AND @FilterJobRegion <> 0
	BEGIN
		IF LEN(@LivePlace) >= LEN(@FilterJobRegion)
		BEGIN
			IF SUBSTRING(@LivePlace,1,LEN(@FilterJobRegion)) <> @FilterJobRegion
				RETURN 1
		END
		ELSE
		BEGIN
			IF SUBSTRING(@FilterJobRegion,1,LEN(@LivePlace)) <> @LivePlace
				RETURN 1
		END
	END
	--判断是否在过滤简历表中
	IF EXISTS(SELECT 'X' FROM cpCvShield WITH(NOLOCK) WHERE cpMainID = @cpMainID and cvMainID=@cvMainID)
		RETURN 1

	RETURN 0
END
GO
/****** Object:  UserDefinedFunction [dbo].[ISJobApplyPassed]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--######################################3
--创建：Sean 2010-11-16
--判断是否Vip会员
--######################################3
CREATE FUNCTION [dbo].[ISJobApplyPassed]
(
	@JobID INT,
	@cvMainID INT
)
RETURNS BIT
AS
BEGIN
	DECLARE @cpMainID AS INT
	DECLARE @IsOpen AS BIT
	DECLARE @MemberType AS SMALLDATETIME
	DECLARE @Valid AS INT

	SELECT @IsOpen = IsOpen FROM cvMain WITH(NOLOCK) WHERE ID = @cvMainID
	SELECT @cpMainID = a.ID,
		@MemberType = a.MemberType,
		@Valid = a.Valid
	FROM cpMain a WITH(NOLOCK)
	INNER JOIN Job b WITH(NOLOCK)
	ON a.ID = b.cpMainID
	WHERE b.ID = @JobID

	IF @Valid = 0				------企业信息无效，返回0
		RETURN 0

	IF @MemberType >= 10		------储值会员或无限制会员，不享受套餐vip
		RETURN 0

	IF (@IsOpen = 1 AND @MemberType = 2) OR @MemberType = 3	------开放简历，只要申请，企业就可以查看
		RETURN 1
	RETURN 0
END




GO
/****** Object:  UserDefinedFunction [dbo].[IsMobile]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--######################################################3
--检查是否mobile
--######################################################3
CREATE FUNCTION [dbo].[IsMobile]
(
	@str VARCHAR(MAX)
)
RETURNS BIT
AS
BEGIN
	DECLARE @ok AS BIT
	SET @ok = 1

	IF @str IS NULL
		RETURN 0

	IF LEN(@str) <> 11
		RETURN 0

	IF LEFT(@str, 2) NOT IN ('13', '14', '15', '16', '17', '18', '19')
		RETURN 0

	--IF CHARINDEX('@', @str) > 0
	--	RETURN 0

	DECLARE @I AS INT
	DECLARE @ValidChars AS VARCHAR(39)
	SET @ValidChars = '0123456789'

	SET @I = 1
	WHILE @I <= LEN(@str)
	BEGIN
		IF CHARINDEX(SUBSTRING(@str, @I, 1), @ValidChars) > 0
			SET @I = @I + 1
		ELSE
			RETURN 0
	END

	RETURN @ok
END
GO
/****** Object:  UserDefinedFunction [dbo].[IsNumeric]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--######################################################3
--检查是否Numeric
--######################################################3
CREATE FUNCTION [dbo].[IsNumeric]
(
	@str VARCHAR(MAX)
)
RETURNS BIT
AS
BEGIN
	DECLARE @ok AS BIT
	SET @ok = 1

	IF @str IS NULL
		SET @ok = 0

	DECLARE @s AS VARCHAR(MAX)
	SET @s = REPLACE(@str, '.', '')
	IF LEN(@s) < LEN(@str) - 1
		SET @ok = 0

	IF @ok = 1
	BEGIN
		DECLARE @I AS INT
		DECLARE @ValidChars AS VARCHAR(39)
		SET @ValidChars = '0123456789'

		SET @I = 1
		WHILE @I <= LEN(@s)
		BEGIN
			IF CHARINDEX(SUBSTRING(@s, @I, 1), @ValidChars) > 0
				SET @I = @I + 1
			ELSE
			BEGIN
				SET @ok = 0
				SET @I = LEN(@s) + 1
			END
		END
	END

	RETURN @ok
END

GO
/****** Object:  UserDefinedFunction [dbo].[IsPassword]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--######################################################3
----检查是否有效密码 = 检查是否有效账号(tmp)
--######################################################3
CREATE FUNCTION [dbo].[IsPassword]
(
	@str VARCHAR(60)
)
RETURNS BIT
AS
BEGIN
	IF LEN(ISNULL(@Str, '')) <> 60
		RETURN 0
	RETURN 1
/*
	DECLARE @ok AS BIT
	SET @ok = 1

	IF @str IS NULL
		SET @ok = 0
	
	IF @ok = 1
	BEGIN
		SET @str = LOWER(LTRIM(RTRIM(@str)))
		IF (LEN(@str) > 50) OR (LEN(@str) < 6)
			SET @ok = 0
	END

	IF @ok = 1
	BEGIN
		DECLARE @I AS INT
		DECLARE @ValidChars AS VARCHAR(39)
		SET @ValidChars = 'abcdefghijklmnopqrstuvwxyz0123456789-_.'

		SET @I = 1
		WHILE @I <= LEN(@str)
		BEGIN
			IF CHARINDEX(SUBSTRING(@str, @I, 1), @ValidChars) > 0
				SET @I = @I + 1
			ELSE
			BEGIN
				SET @ok = 0
				SET @I = 100
			END
		END
	END
	RETURN @ok
*/
END




GO
/****** Object:  UserDefinedFunction [dbo].[IsSafeSQL]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#############################333
--安全的sql语句用于exec
--Sean 2013-8-23
--#############################333
CREATE FUNCTION [dbo].[IsSafeSQL]
(
	@inputText VARCHAR(MAX)
)
RETURNS INT
AS
BEGIN
	IF @inputText IS NULL
		RETURN 1

	DECLARE @sText VARCHAR(Max)
	SET @SText = @inputText
	SET @sText = REPLACE(@sText, '--','——')
	SET @sText = REPLACE(@sText, 'delete ','delete&nbsp;')
	SET @sText = REPLACE(@sText, 'update ','update&nbsp;')
	SET @sText = REPLACE(@sText, 'create ','create&nbsp;')
	SET @sText = REPLACE(@sText, 'drop ','drop&nbsp;')
	SET @sText = REPLACE(@sText, 'insert ','insert&nbsp;')
	SET @sText = REPLACE(@sText, 'chr(','chr(&nbsp;')
	SET @sText = REPLACE(@sText, 'master ','master&nbsp;')
	SET @sText = REPLACE(@sText, 'net user','net&nbsp;user')
	SET @sText = REPLACE(@sText, 'declare ','declare&nbsp;')
	SET @sText = REPLACE(@sText, 'char(','char(&nbsp;')
	SET @sText = REPLACE(@sText, 'mid(','mid(&nbsp;')
	SET @sText = REPLACE(@sText, 'count ','count&nbsp;')
	SET @sText = REPLACE(@sText, 'xp_cmdshell','xp_cmdshell&nbsp;')
	SET @sText = REPLACE(@sText, 'exec ','exec&nbsp;')
	SET @sText = REPLACE(@sText, 'truncate ','truncate&nbsp;')
	SET @sText = REPLACE(@sText, 'ascii(','ascii(&nbsp;')
	SET @sText = REPLACE(@sText, 'substring(','substring(&nbsp;')
	SET @sText = REPLACE(@sText, 'localgroup ','localgroup&nbsp;')
	SET @sText = REPLACE(@sText, 'administrators ','administrators&nbsp;')
	SET @sText = REPLACE(@sText, 'dbcc ','dbcc&nbsp;')
	SET @sText = REPLACE(@sText, 'checkdb(','checkdb(&nbsp;')
	SET @sText = REPLACE(@sText, 'sp_addsrvrolemember','p_addsrvrolemember&nbsp;')
	SET @sText = REPLACE(@sText, 'wscript.shell','wscript.shell&nbsp;')

	IF @SText = @inputText
		RETURN 1
	ELSE
		RETURN 0

	RETURN 0
END






GO
/****** Object:  UserDefinedFunction [dbo].[JobApplyName]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[JobApplyName]
(	
	@IsNameHidden BIT,
	@paName VARCHAR(12),
	@Gender BIT
)
RETURNS VARCHAR(50)
AS
BEGIN
	IF @IsNameHidden = 0
		RETURN @paName

	SET @paName = LEFT(@paName, 1)
	IF @Gender = 0
		RETURN @paName + '先生'

	RETURN @paName + '女士/小姐'
END


GO
/****** Object:  UserDefinedFunction [dbo].[JobValid]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[JobValid]
(	
	@IsDelete BIT,
	@VerifyResult TINYINT,
	@IssueDate SMALLDATETIME,
	@IssueEnd SMALLDATETIME
)
RETURNS BIT
AS
BEGIN
	IF @IsDelete = 1
		RETURN 0
	
	IF @VerifyResult<>1
		RETURN 0

	IF @IssueDate<GETDATE() AND @IssueEnd>GETDATE()
		RETURN 1

	RETURN 0
END


GO
/****** Object:  UserDefinedFunction [dbo].[LowerUSer]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--######################################################3
--实现split功能 的函数
--######################################################3
CREATE FUNCTION [dbo].[LowerUSer]
(
	@ID INT,
	@Privi CHAR(1)
)
RETURNS @T TABLE(ID SMALLINT)
AS
BEGIN
	DECLARE @deptID AS INT
	IF @Privi IN('0', 'x')
		RETURN

	IF @Privi = 1
		INSERT INTO @T VALUES(@ID)
	ELSE
		SELECT @deptID = DeptId FROM Manageruser WITH(NOLOCK) WHERE ID = @ID
		IF @Privi = 2
			INSERT INTO @T 
			SELECT ID FROM ManagerUser WITH(NOLOCK)
			WHERE DeptID = @deptID
			AND Status < 3

		IF @Privi = 3
			INSERT INTO @T
			SELECT ID FROM ManagerUser WITH(NOLOCK)
			WHERE Status < 3
			AND (DeptID = @deptID
				OR DeptID IN(SELECT ID FROM Dept WITH(NOLOCK) WHERE Superior = @DeptId)
				)

		IF @Privi = 4
			INSERT INTO @T
			SELECT ID FROM ManagerUser WITH(NOLOCK)
			WHERE Status < 3

		IF @Privi = 5
			INSERT INTO @T
			SELECT ID FROM ManagerUser WITH(NOLOCK)
			WHERE Status < 3
			UNION
			SELECT 0

	RETURN
		
END


GO
/****** Object:  UserDefinedFunction [dbo].[LowerUserAll]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--######################################################3
--获得所有的下属员工（包括status>=3的）
--######################################################3
CREATE FUNCTION [dbo].[LowerUserAll]
(
	@ID INT,
	@Privi CHAR(1)
)
RETURNS @T TABLE(ID SMALLINT)
AS
BEGIN
	DECLARE @deptID AS INT
	IF @Privi IN('0', 'x')
		RETURN

	IF @Privi = 1
		INSERT INTO @T VALUES(@ID)
	ELSE
		SELECT @deptID = DeptId FROM Manageruser WITH(NOLOCK) WHERE ID = @ID
		IF @Privi = 2
			INSERT INTO @T 
			SELECT ID FROM ManagerUser WITH(NOLOCK)
			WHERE DeptID = @deptID			

		IF @Privi = 3
			INSERT INTO @T
			SELECT ID FROM ManagerUser WITH(NOLOCK)
			WHERE DeptID = @deptID OR DeptID IN(SELECT ID FROM Dept WITH(NOLOCK) WHERE Superior = @DeptId)

		IF @Privi = 4
			INSERT INTO @T
			SELECT ID FROM ManagerUser WITH(NOLOCK)

		IF @Privi = 5
			INSERT INTO @T
			SELECT ID FROM ManagerUser WITH(NOLOCK)			
			UNION
			SELECT 0
	RETURN
		
END

GO
/****** Object:  UserDefinedFunction [dbo].[MapBarRegionName]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE FUNCTION [dbo].[MapBarRegionName]
(
	@Id VARCHAR(6)
)
RETURNS NVARCHAR(20)
BEGIN
	RETURN (SELECT MapBarName FROM dcREgion WITH(NOLOCK) WHERE ID = @ID)
END

GO
/****** Object:  UserDefinedFunction [dbo].[MemberType]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--######################################3
--创建：Sean 2010-11-16
--判断企业用户类型
--######################################3
CREATE FUNCTION [dbo].[MemberType]
(
	@ID INT
)
RETURNS TINYINT
AS
BEGIN
	DECLARE @HasLicence AS BIT, @BalanceDate AS SMALLDATETIME, @UnlimitedDate AS SMALLDATETIME,
		@Address AS VARCHAR(100), @Name AS NVARCHAR(6), @Gender AS BIT,
		@MemberType AS TINYINT, @IsDelete AS BIT, @Mobile VARCHAR(100)

	SELECT @HasLicence = ISNULL(HasLicence, 0),
		@BalanceDate = ISNULL(BalanceDate, '1900-1-1'),
		@UnlimitedDate = ISNULL(UnlimitedDate, '1900-1-1'),
		@Address = ISNULL(Address, ''),
		@IsDelete = IsDelete
	FROM cpMain WITH(NOLOCK)
	WHERE ID = @ID
 
	SELECT @Name = Name, @Gender = Gender, @Mobile = ISNULL(Mobile, ISNULL(TelePhone, '')) FROM caMain WITH(NOLOCK)
	WHERE cpMainID = @ID AND AccountType = 1
  
	----企业资料不完整,=0
	IF ISNULL(@Address, '') = '' OR @IsDelete = 1 OR ISNULL(@Name, '') = '' OR @Gender IS NULL OR @Mobile = ''
		SET @MemberType = 0

	----已经上传营业执照,只能是普通会员：2、无限制：10、储值：11、vip：3之一
	ELSE IF @HasLicence = 0
		SET @MemberType = 1

	--无限制
	--ELSE IF @UnlimitedDate >= CONVERT(SMALLDATETIME, GETDATE())
	--	SET @MemberType = 10

	--储值
	--ELSE IF @BalanceDate >= CONVERT(SMALLDATETIME, GETDATE())
	--	SET @MemberType = 11

	----检查订单
	ELSE IF EXISTS(SELECT 'x' FROM caOrder WITH(NOLOCK)
			WHERE cpMainID = @ID AND OrderType = 8
			AND BeginDate <= GETDATE() AND ENDDATE > DATEADD(MINUTE, -4, GETDATE())
			AND IsDeleted = 0
			)
		SET @MemberType = 3
	ELSE
		SET @MemberType = 2

	RETURN @MemberType
END














GO
/****** Object:  UserDefinedFunction [dbo].[MemberType1]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--######################################3
--创建：Sean 2010-11-16
--判断企业用户类型
--######################################3
CREATE FUNCTION [dbo].[MemberType1]
(
	@ID INT
)
RETURNS TINYINT
AS
BEGIN
	DECLARE @HasLicence AS BIT
	DECLARE @BalanceDate AS SMALLDATETIME
	DECLARE @Balance AS INT
	DECLARE @UnlimitedDate AS SMALLDATETIME
	DECLARE @Address AS VARCHAR(100)
	DECLARE @Name AS NVARCHAR(6)
	DECLARE @MemberType AS TINYINT
	DECLARE @IsDelete AS BIT
	SELECT @HasLicence = ISNULL(HasLicence, 0),
		@BalanceDate = ISNULL(BalanceDate, '1900-1-1'),
		@Balance = ISNULL(Balance, 0),
		@UnlimitedDate = ISNULL(UnlimitedDate, '1900-1-1'),
		@Address = ISNULL(Address, ''),
		@IsDelete = IsDelete
	FROM cpMain WITH(NOLOCK)
	WHERE ID = @ID
	
	SELECT @Name = Name FROM caMain WITH(NOLOCK)
	WHERE cpMainID = @ID AND AccountType = 1

	----企业资料不完整，=0
	IF ISNULL(@Address, '') = '' OR @IsDelete = 1
	BEGIN
		SET @MemberType = 0
		GOTO ret
	END
	IF @HasLicence = 0
	BEGIN
		SET @MemberType = 1
		GOTO ret
	END
	----已经上传营业执照，只能是普通会员：2、无限制：10、储值：11、vip：3之一
	IF @HasLicence = 1
	BEGIN
		--无限制
		IF @UnlimitedDate > GETDATE()
		BEGIN
			SET @MemberType = 10
			GOTO ret
		END
		--储值
		IF @BalanceDate > GETDATE() AND @Balance > 0
		BEGIN
			SET @MemberType = 11
			GOTO ret
		END
		----检查订单
		IF EXISTS(SELECT 'x' FROM caOrder WITH(NOLOCK)
				WHERE cpMainID = @ID AND OrderType = 8
				AND BEGINDATE<GETDATE() AND ENDDATE > GETDATE())

			SET @MemberType = 3
		ELSE
			SET @MemberType = 2
			GOTO ret
	END
ret:
	RETURN @MemberType
END
GO
/****** Object:  UserDefinedFunction [dbo].[MergeDate]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create function [dbo].[MergeDate]
(
	@D SMALLDATETIME,
	@t INT
)
RETURNS SMALLDATETIME
AS
BEGIN
	DECLARE @c AS VARCHAR(30)
	SET @c = CONVERT(VARCHAR(10), @d, 120) + ' '
	IF @t < 10
		SET @c = @c + '00:0' + LTRIM(STR(@t))
	ELSE IF @t < 100
		SET @c = @c + '00:' + LTRIM(STR(@t))
	ELSE IF @t < 1000
		SET @c = @c + '0' + LEFT(@t, 1) + ':' + RIGHT(@t, 2)
	ELSE
		SET @c = @c + LEFT(@t, 2) + ':' + RIGHT(@t, 2)

	RETURN CONVERT(SMALLDATETIME, @c)
END

GO
/****** Object:  UserDefinedFunction [dbo].[MtNo2RtxId]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE FUNCTION [dbo].[MtNo2RtxId]
(
	@MtNo TINYINT
)
RETURNS INT
AS
BEGIN
	IF @MtNo = 1
		RETURN 1003
	ELSE IF @MtNo = 2
		RETURN 1002
	ELSE IF @MtNo = 3
		RETURN 1004
	ELSE IF @MtNo = 8
		RETURN 1005
	ELSE IF @MtNo = 9
		RETURN 1006

	RETURN 0
END



GO
/****** Object:  UserDefinedFunction [dbo].[MySplit]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Function [dbo].[MySplit](
	@s VARCHAR(MAX),
	@l INT
)
RETURNS @Temp TABLE(Id INT, ts VARCHAR(4000))
AS
BEGIN
	DECLARE @I INT
	SET @i = 0
	WHILE @i * @l < LEN(@s)
	BEGIN
		INSERT INTO @Temp
		SELECT @i + 1, SUBSTRING(@s, @i * @l + 1, @l)

		SET @i = @i + 1
	END
	
	RETURN
END

GO
/****** Object:  UserDefinedFunction [dbo].[photoPath]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[photoPath](@id INT,@fileType INT)
RETURNS varchar(50)
AS
BEGIN 
    DECLARE @result VARCHAR(50)
    DECLARE @path VARCHAR(50),@i INT,@photo VARCHAR(20)
    SET @i = 1
    IF @filetype <=3
    BEGIN
        SET @path = CONVERT(VARCHAR(50),((@id / 100000) + 1) * 100000)
        SET @photo = @path
        WHILE @i<=(9-LEN(@photo))
        BEGIN
            SET @path = '0' + @path
            SET @i = @i + 1
        END
    END
    ELSE
    BEGIN
        SET @path = CONVERT(VARCHAR(50),((@id / 10000) + 1) * 10000)
        SET @photo = @path
        WHILE @i<=(6-LEN(@photo))
        BEGIN
            SET @path = '0' + @path
            SET @i = @i + 1
        END
    END
    SET @path = 'L' + @path
SET @result = @path
RETURN @result
END

GO
/****** Object:  UserDefinedFunction [dbo].[RemoveBR]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[RemoveBR]
(
	@Str VARCHAR(MAX)
)
RETURNS VARCHAR(MAX)
AS
BEGIN
	RETURN REPLACE(REPLACE(@str, '<br>', ''), '&nbsp;', ' ')
END
GO
/****** Object:  UserDefinedFunction [dbo].[RemoveNullChars]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[RemoveNullChars] 
( 
	@string NVARCHAR(MAX) 
) 
RETURNS NVARCHAR(MAX) 
WITH RETURNS NULL ON NULL INPUT 
AS 
BEGIN 
	DECLARE @Result NVARCHAR(MAX) 
	SET @Result = ''
	DECLARE @counter INT 
	SET @counter = 0 
	WHILE (@counter <= LEN(@string)) 
	BEGIN 
		IF UNICODE(SUBSTRING(@string, @counter,1)) <> 0 
			SET @Result = @Result + SUBSTRING(@string, @counter, 1) 
		SET @counter = @counter + 1 
	END 
	RETURN @Result 
END
GO
/****** Object:  UserDefinedFunction [dbo].[ReplyInterval]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE  function   [dbo].[ReplyInterval](@adddate smalldatetime,@replydate smalldatetime)   
  returns   int   
  as   
  begin   
  declare   @result   int   
    if @replydate is null set @replydate=getdate()
    if datepart(w,@adddate)=1
       set @result=datediff(n,cast(cast(year(@adddate+1) as varchar)+'-'+cast(month(@adddate+1) as varchar)+'-'+cast(day(@adddate+1) as varchar)+' 8:30' as smalldatetime),@replydate) 
    else if datepart(w,@adddate)=7 
            and @adddate>cast(cast(year(@adddate) as varchar)+'-'+cast(month(@adddate) as varchar)+'-'+cast(day(@adddate) as varchar)+' 17:30' as smalldatetime) 
            and @adddate<=cast(cast(year(@adddate) as varchar)+'-'+cast(month(@adddate) as varchar)+'-'+cast(day(@adddate) as varchar)+' 23:59' as smalldatetime)
        set @result=datediff(n,cast(cast(year(@adddate+2) as varchar)+'-'+cast(month(@adddate+2) as varchar)+'-'+cast(day(@adddate+2) as varchar)+' 8:30' as smalldatetime),@replydate) 
    else if @adddate>=cast(cast(year(@adddate) as varchar)+'-'+cast(month(@adddate) as varchar)+'-'+cast(day(@adddate) as varchar)+' 0:0' as smalldatetime) 
       and @adddate<cast(cast(year(@adddate) as varchar)+'-'+cast(month(@adddate) as varchar)+'-'+cast(day(@adddate) as varchar)+' 8:30' as smalldatetime)
       --没上班之前的
       set @result=datediff(n,cast(cast(year(@adddate) as varchar)+'-'+cast(month(@adddate) as varchar)+'-'+cast(day(@adddate) as varchar)+' 8:30' as smalldatetime),@replydate)
    else if @adddate>cast(cast(year(@adddate) as varchar)+'-'+cast(month(@adddate) as varchar)+'-'+cast(day(@adddate) as varchar)+' 17:30' as smalldatetime) 
            and @adddate<=cast(cast(year(@adddate) as varchar)+'-'+cast(month(@adddate) as varchar)+'-'+cast(day(@adddate) as varchar)+' 23:59' as smalldatetime) --没上班之前的
       set @result=datediff(n,cast(cast(year(@adddate+1) as varchar)+'-'+cast(month(@adddate+1) as varchar)+'-'+cast(day(@adddate+1) as varchar)+' 8:30' as smalldatetime),@replydate)
    else if @adddate>cast(cast(year(@adddate) as varchar)+'-'+cast(month(@adddate) as varchar)+'-'+cast(day(@adddate) as varchar)+' 10:00' as smalldatetime) 
            and @adddate<=cast(cast(year(@adddate) as varchar)+'-'+cast(month(@adddate) as varchar)+'-'+cast(day(@adddate) as varchar)+' 12:00' as smalldatetime) --10:00-12:00
       set @result=datediff(n,@adddate,@replydate)-60
    else if @adddate>cast(cast(year(@adddate) as varchar)+'-'+cast(month(@adddate) as varchar)+'-'+cast(day(@adddate) as varchar)+' 12:00' as smalldatetime) 
            and @adddate<=cast(cast(year(@adddate) as varchar)+'-'+cast(month(@adddate) as varchar)+'-'+cast(day(@adddate) as varchar)+' 13:00' as smalldatetime) --12:00-13:00
       set @result=datediff(n,cast(cast(year(@adddate) as varchar)+'-'+cast(month(@adddate) as varchar)+'-'+cast(day(@adddate) as varchar)+' 13:00' as smalldatetime),@replydate)
    else
       set @result=datediff(n,@adddate,@replydate)
    return   @result   
  end

GO
/****** Object:  UserDefinedFunction [dbo].[ReportDayToDate]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


--######################################3
--创建：Lambo 2013-2-4
--日期转换 取多少天之前的天数  2012-1-1为1
--######################################3
CREATE FUNCTION [dbo].[ReportDayToDate]
(
	@d int
)
RETURNS INT
AS
BEGIN	
	RETURN DATEDIFF(DAY,'2012-1-1',GETDATE()-@d)
END
GO
/****** Object:  UserDefinedFunction [dbo].[SafeSQL]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#############################333
--安全的sql语句用于exec
--#############################333
CREATE FUNCTION [dbo].[SafeSQL]
(
	@sText VARCHAR(MAX)
)
RETURNS VARCHAR(MAX)
AS
BEGIN
	IF @sText IS NULL
		RETURN ''

--	SET @sText = REPLACE(@sText, 'and ','and&nbsp;')
--	SET @sText = REPLACE(@sText, 'or ','or&nbsp;')
--	SET @sText = REPLACE(@sText, 'exists','exists&nbsp;')	
--	SET @sText = REPLACE(@sText, 'union ','union&nbsp;')
--	SET @sText = REPLACE(@sText, '<','＜')
--	SET @sText = REPLACE(@sText, '>','＞')
--	SET @sText = REPLACE(@sText, 'from ','from&nbsp;')
--	SET @sText = REPLACE(@sText, 'select ','select&nbsp;')
	SET @sText = REPLACE(@sText, '','')
	SET @sText = REPLACE(@sText, 'script','scripｔ')
	SET @sText = REPLACE(@sText, 'src','srｃ')
	SET @sText = REPLACE(@sText, 'iframe','ｉframe')
	SET @sText = REPLACE(@sText, '--','——')
	SET @sText = REPLACE(@sText, 'delete ','delete&nbsp;')
	SET @sText = REPLACE(@sText, 'update ','update&nbsp;')
	SET @sText = REPLACE(@sText, 'delete	','delete&nbsp;')
	SET @sText = REPLACE(@sText, 'update	','update&nbsp;')
	SET @sText = REPLACE(@sText, 'delete
','delete&nbsp;')
	SET @sText = REPLACE(@sText, 'update
','update&nbsp;')
	SET @sText = REPLACE(@sText, 'create','create&nbsp;')
	SET @sText = REPLACE(@sText, 'drop','drop&nbsp;')
	SET @sText = REPLACE(@sText, 'insert','insert&nbsp;')
	SET @sText = REPLACE(@sText, 'chr(','chr(&nbsp;')
	SET @sText = REPLACE(@sText, 'master','master&nbsp;')
	SET @sText = REPLACE(@sText, 'net user','net&nbsp;user')
	SET @sText = REPLACE(@sText, 'declare','declare&nbsp;')
	SET @sText = REPLACE(@sText, 'char(','char(&nbsp;')
	SET @sText = REPLACE(@sText, 'mid(','mid(&nbsp;')
	SET @sText = REPLACE(@sText, 'xp_cmdshell','xp_cmdshell&nbsp;')
	SET @sText = REPLACE(@sText, 'exec','exec&nbsp;')
	SET @sText = REPLACE(@sText, 'truncate','truncate&nbsp;')
	SET @sText = REPLACE(@sText, 'ascii(','ascii(&nbsp;')
	SET @sText = REPLACE(@sText, 'substring(','substring(&nbsp;')
	SET @sText = REPLACE(@sText, 'localgroup ','localgroup&nbsp;')
	SET @sText = REPLACE(@sText, 'administrators ','administrators&nbsp;')
	SET @sText = REPLACE(@sText, 'dbcc','dbcc&nbsp;')
	SET @sText = REPLACE(@sText, 'checkdb(','checkdb(&nbsp;')
	SET @sText = REPLACE(@sText, 'sp_addsrvrolemember','p_addsrvrolemember&nbsp;')
	SET @sText = REPLACE(@sText, 'wscript.shell','wscript.shell&nbsp;')

	RETURN @sText
END

GO
/****** Object:  UserDefinedFunction [dbo].[SafeSQLBack]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#############################333
--安全的sql语句用于exec
--#############################333
CREATE FUNCTION [dbo].[SafeSQLBack]
(
	@sText VARCHAR(MAX)
)
RETURNS VARCHAR(MAX)
AS
BEGIN
	IF @sText IS NULL
		RETURN ''

--	SET @sText = REPLACE(@sText, 'and ','and&nbsp;')
--	SET @sText = REPLACE(@sText, 'or ','or&nbsp;')
--	SET @sText = REPLACE(@sText, 'from ','from&nbsp;')
--	SET @sText = REPLACE(@sText, 'exists','exists&nbsp;')	
--	SET @sText = REPLACE(@sText, 'select ','select&nbsp;')
--	SET @sText = REPLACE(@sText, 'union ','union&nbsp;')
--	SET @sText = REPLACE(@sText, '<','＜')
--	SET @sText = REPLACE(@sText, '>','＞')
	SET @sText = REPLACE(@sText, '','')
	SET @sText = REPLACE(@sText, 'script','scripｔ')
	SET @sText = REPLACE(@sText, 'src','srｃ')
	SET @sText = REPLACE(@sText, 'iframe','ｉframe')
	SET @sText = REPLACE(@sText, '--','——')
	SET @sText = REPLACE(@sText, 'delete ','delete&nbsp;')
	SET @sText = REPLACE(@sText, 'update ','update&nbsp;')
	SET @sText = REPLACE(@sText, 'delete	','delete&nbsp;')
	SET @sText = REPLACE(@sText, 'update	','update&nbsp;')
	SET @sText = REPLACE(@sText, 'delete
','delete&nbsp;')
	SET @sText = REPLACE(@sText, 'update
','update&nbsp;')
	SET @sText = REPLACE(@sText, 'create ','create&nbsp;')
	SET @sText = REPLACE(@sText, 'drop ','drop&nbsp;')
	SET @sText = REPLACE(@sText, 'insert ','insert&nbsp;')
	SET @sText = REPLACE(@sText, 'chr(','chr(&nbsp;')
	SET @sText = REPLACE(@sText, 'master ','master&nbsp;')
	SET @sText = REPLACE(@sText, 'net user','net&nbsp;user')
	SET @sText = REPLACE(@sText, 'declare ','declare&nbsp;')
	SET @sText = REPLACE(@sText, 'char(','char(&nbsp;')
	SET @sText = REPLACE(@sText, 'mid(','mid(&nbsp;')
	--SET @sText = REPLACE(@sText, 'count ','count&nbsp;')
	SET @sText = REPLACE(@sText, 'xp_cmdshell','xp_cmdshell&nbsp;')
	SET @sText = REPLACE(@sText, 'exec ','exec&nbsp;')
	SET @sText = REPLACE(@sText, 'truncate ','truncate&nbsp;')
	SET @sText = REPLACE(@sText, 'ascii(','ascii(&nbsp;')
	SET @sText = REPLACE(@sText, 'substring(','substring(&nbsp;')
	SET @sText = REPLACE(@sText, 'localgroup ','localgroup&nbsp;')
	SET @sText = REPLACE(@sText, 'administrators ','administrators&nbsp;')
	SET @sText = REPLACE(@sText, 'dbcc ','dbcc&nbsp;')
	SET @sText = REPLACE(@sText, 'checkdb(','checkdb(&nbsp;')
	SET @sText = REPLACE(@sText, 'sp_addsrvrolemember','p_addsrvrolemember&nbsp;')
	SET @sText = REPLACE(@sText, 'wscript.shell','wscript.shell&nbsp;')

	RETURN @sText
END

GO
/****** Object:  UserDefinedFunction [dbo].[ScheduleRunTime]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Function [dbo].[ScheduleRunTime]
(
	@RunDate INT,
	@RunTime INT
)
RETURNS DATETIME
AS
BEGIN
	DECLARE @time AS VARCHAR(30)
	SET @Time = LTRIM(STR(@RunTime / 10000)) + ':' 
	SET @RunTime = @RunTime % 10000
	SET @Time = @Time + LTRIM(STR(@RunTime / 100)) + ':00'
	RETURN CONVERT(DATETIME, LTRIM(STR(@RunDate)) + ' ' + @Time)
END
GO
/****** Object:  UserDefinedFunction [dbo].[schGetCaCvExChange]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[schGetCaCvExChange]
(
	@caMainID INT,
	@DateType TINYINT
)
RETURNS VARCHAR(MAX)
AS
BEGIN
	DECLARE @JobID INT,@JobName NVARCHAR(50),@Count INT,@StartTime VARCHAR(20),
		@EndTime VARCHAR(20),@Today VARCHAR(10),@Content VARCHAR(MAX)

	SET @Content = ''
	IF @DateType = 1
	BEGIN
		IF DATEPART(HOUR,GETDATE()) > 0 AND DATEPART(HOUR,GETDATE()) < 9
		BEGIN
			SET @StartTime = CONVERT(VARCHAR(10),DATEADD(DAY,-1,GETDATE()),120) + ' 00:00:00'
			SET @EndTime = CONVERT(VARCHAR(10),DATEADD(DAY,-1,GETDATE()),120) + ' 23:59:59'
			SET @Today = CONVERT(VARCHAR(10),DATEADD(DAY,-1,GETDATE()),120)
		END
		ELSE
		BEGIN
			SET @StartTime = CONVERT(VARCHAR(10),GETDATE(),120) + ' 00:00:00'
			SET @EndTime = CONVERT(VARCHAR(10),GETDATE(),120) + ' 23:59:59'
			SET @Today = CONVERT(VARCHAR(10),GETDATE(),120)
		END
	END
	ELSE
	BEGIN
		SET @StartTime = CONVERT(VARCHAR(10),DATEADD(ww,-1,GETDATE()),120) + ' 00:00:00'
		SET @EndTime = CONVERT(VARCHAR(10),GETDATE(),120) + ' 23:59:59'
		SET @Today = CONVERT(VARCHAR(10),DATEADD(ww,-1,GETDATE()),120)
	END

	SELECT @Count=COUNT(1) FROM exMessageP2C WITH(NOLOCK) WHERE caMainID=@caMainID AND AddDate>CONVERT(SMALLDATETIME,@StartTime) And AddDate<CONVERT(SMALLDATETIME,@EndTime)
	IF @Count > 0
		SET @Content = @Content + '<br>&nbsp;&nbsp;您总共收到了' + CONVERT(VARCHAR,@Count) + '条求职者发来的新留言；'
	
	DECLARE curJob CURSOR FOR SELECT TOP 10 ID,Name FROM Job WITH(NOLOCK) WHERE Valid=1 AND caMainID=@caMainID
	OPEN curJob
	FETCH NEXT FROM curJob INTO @JobID,@JobName
	IF @@FETCH_STATUS >= 0
	BEGIN
		WHILE @@FETCH_STATUS = 0
		BEGIN
			SELECT @Count=COUNT(1) FROM exJobApply a WITH(NOLOCK),cvMain b WITH(NOLOCK)
				WHERE a.cvMainID=b.ID AND b.VerifyResult=1 AND a.JobID=@JobID
				AND a.AddDate<CONVERT(SMALLDATETIME,@EndTime) AND a.AddDate>CONVERT(SMALLDATETIME,@StartTime)
			IF @Count > 0
				SET @Content = @Content + '<br>&nbsp;&nbsp;有' + CONVERT(VARCHAR,@Count) + '个求职者给[' + @JobName + ']投递了简历；'

			FETCH NEXT FROM curJob INTO @JobID,@JobName
		END
	END
	CLOSE curJob 
	DEALLOCATE curJob
	IF LEN(@Content) > 0
	BEGIN
		IF @DateType = 1
			SET @Content = '在' + @Today + '的24小时内：' + @Content
		ELSE
			SET @Content = '在' + CONVERT(VARCHAR(10),@StartTime) + '至' + CONVERT(VARCHAR(10),@EndTime) + '的一周内：' + @Content
	END
	RETURN @Content
END
GO
/****** Object:  UserDefinedFunction [dbo].[schGetOrderDesc]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[schGetOrderDesc]
(
	@ServiceType SMALLINT,
	@OrderType SMALLINT,
	@Paid NUMERIC(18,2),
	@TimeTitle VARCHAR(500),
	@ActiveQuota INT,
	@JobNumber INT,
	@UserNumber INT,
	@PayMethod SMALLINT,
	@Receiver VARCHAR(200),
	@Account VARCHAR(200),
	@BankName VARCHAR(200),
	@NeedInvoice BIT,
	@OrderID INT
)
RETURNS VARCHAR(MAX)
AS
BEGIN
	DECLARE @tmp@ServiceType NVARCHAR(20)
	DECLARE @strOrderDesc NVARCHAR(500)
	SET @strOrderDesc = ''
	SET @tmp@ServiceType = ''
	If @ServiceType = 100 
		SET @tmp@ServiceType = '一周'

	If @ServiceType = 1 
		SET @tmp@ServiceType = '一个月'

	If @ServiceType = 2 
		SET @tmp@ServiceType = '一个季度'

	If @ServiceType = 3 
		SET @tmp@ServiceType = '半年'

	If @ServiceType = 4 
		SET @tmp@ServiceType = '一年'

	If @OrderType = 1
		SET @strOrderDesc = @strOrderDesc + '&nbsp;&nbsp;您的订单内容为申请' + @tmp@ServiceType + '正式会员，费用为' + convert(varchar(10),@Paid) + '元，'

	If @OrderType = 2
		SET @strOrderDesc = @strOrderDesc + '&nbsp;&nbsp;您的订单内容为申请储值会员，加值金额为' + convert(varchar(10),@Paid) + '元，'

	If @OrderType = 4
		SET @strOrderDesc = @strOrderDesc + '&nbsp;&nbsp;您的订单内容为申请广告位，费用为' + convert(varchar(10),@Paid) + '元，'

	If @OrderType = 7
		SET @strOrderDesc = @strOrderDesc + '&nbsp;&nbsp;您的订单内容为首页知名企业招聘，费用为' + convert(varchar(10),@Paid) + '元，'

	If @OrderType = 8
		SET @strOrderDesc = @strOrderDesc + '&nbsp;&nbsp;您的订单内容为申请' + @TimeTitle + 'VIP套餐服务，费用为' + convert(varchar(10),@Paid) + '元，'

	If @OrderType = 9
		SET @strOrderDesc = @strOrderDesc + '&nbsp;&nbsp;您的订单内容为购买' + LTRIM(STR(@ActiveQuota)) + '个简历下载数，费用为' + convert(varchar(10),@Paid) + '元，'

	If @OrderType = 10
		SET @strOrderDesc = @strOrderDesc + '&nbsp;&nbsp;您的订单内容为购买' + LTRIM(STR(@JobNumber)) + '个职位并发数，费用为' + convert(varchar(10),@Paid) + '元，'

	If @OrderType = 11
		SET @strOrderDesc = @strOrderDesc + '&nbsp;&nbsp;您的订单内容为购买' + LTRIM(STR(@UserNumber)) + '个用户数，费用为' + convert(varchar(10),@Paid) + '元，'

	SET @strOrderDesc = @strOrderDesc + '为方便您能够及时开通服务，现将付款流程发送给您，如下：<br>'

	If @PayMethod = 1
	Begin
		SET @strOrderDesc = @strOrderDesc + '1、对公汇款<br>'
		SET @strOrderDesc = @strOrderDesc + '&nbsp;收款人：' + @Receiver + '<br>'
		SET @strOrderDesc = @strOrderDesc + '&nbsp;开户银行：' + @BankName + '<br>'
		SET @strOrderDesc = @strOrderDesc + '&nbsp;帐号：' + @Account + '<br>' 
		SET @strOrderDesc = @strOrderDesc + '&nbsp;汇款用途：会员服务费，订单号' + LTRIM(STR(@OrderID)) + '<br>'   
		SET @strOrderDesc = @strOrderDesc + '2、将银行电汇回单传真至：010-65800851 或者 021-61916451<br>'
		SET @strOrderDesc = @strOrderDesc + dbo.schGetPayDesc(@OrderType,'在银行电汇回单传真、营业执照齐全后',@NeedInvoice)
	End

	If @PayMethod = 2
	BEGIN
		SET @strOrderDesc = @strOrderDesc + '1、邮局汇款<br>'
		SET @strOrderDesc = @strOrderDesc + '&nbsp;收款人：' + @Receiver + '<br>'
		SET @strOrderDesc = @strOrderDesc + '&nbsp;通信地址：' + @BankName + '<br>'
		SET @strOrderDesc = @strOrderDesc + '&nbsp;邮政编码：' + @Account + '<br>'    
		SET @strOrderDesc = @strOrderDesc + '&nbsp;附言：订单号' + LTRIM(STR(@OrderID)) + '<br>'  
		SET @strOrderDesc = @strOrderDesc + '2、在邮政汇款收据上，标上订单号，并传真至：010-65800851 或者 021-61916451<br>'
		SET @strOrderDesc = @strOrderDesc + dbo.schGetPayDesc(@OrderType,'在邮政汇款收据传真、营业执照齐全后',@NeedInvoice)
	End

	If @PayMethod = 6
	BEGIN
		SET @strOrderDesc = @strOrderDesc + '请前来付费：<br>'
		SET @strOrderDesc = @strOrderDesc + '&nbsp;' + @Receiver + '<br>'
		SET @strOrderDesc = @strOrderDesc + '&nbsp;地址：' + @BankName + '<br>'
	End

	If @PayMethod = 7
	BEGIN
		SET @strOrderDesc = @strOrderDesc + '1、工商银行<br>'
		SET @strOrderDesc = @strOrderDesc + '&nbsp;收款人全称：' + @Receiver + '<br>'
		SET @strOrderDesc = @strOrderDesc + '&nbsp;帐号：' + @Account + '<br>' 
		SET @strOrderDesc = @strOrderDesc + '&nbsp;开户银行：' + @BankName + '<br>' 
		SET @strOrderDesc = @strOrderDesc + '2、汇款成功后，请立即打电话或者发邮件通知我们订单号以及汇款金额。<br>'
		SET @strOrderDesc = @strOrderDesc + dbo.schGetPayDesc(@OrderType,'在营业执照齐全，并确认收到汇款后',@NeedInvoice)
	End

	If @PayMethod = 9
	BEGIN
		SET @strOrderDesc = @strOrderDesc + '1、招商银行<br>'
		SET @strOrderDesc = @strOrderDesc + '&nbsp;收款人全称：' + @Receiver + '<br>'
		SET @strOrderDesc = @strOrderDesc + '&nbsp;帐号：' + @Account + '<br>' 
		SET @strOrderDesc = @strOrderDesc + '&nbsp;开户银行：' + @BankName + '<br>' 
		SET @strOrderDesc = @strOrderDesc + '2、汇款成功后，请立即打电话或者发邮件通知我们订单号以及汇款金额。<br>'
		SET @strOrderDesc = @strOrderDesc + dbo.schGetPayDesc(@OrderType,'在营业执照齐全，并确认收到汇款后',@NeedInvoice)
	End

	If @PayMethod = 10
	BEGIN
		SET @strOrderDesc = @strOrderDesc + '1、农业银行<br>'
		SET @strOrderDesc = @strOrderDesc + '&nbsp;收款人全称：' + @Receiver + '<br>'
		SET @strOrderDesc = @strOrderDesc + '&nbsp;帐号：' + @Account + '<br>' 
		SET @strOrderDesc = @strOrderDesc + '&nbsp;开户银行：' + @BankName + '<br>' 
		SET @strOrderDesc = @strOrderDesc + '2、汇款成功后，请立即打电话或者发邮件通知我们订单号以及汇款金额。<br>'
		SET @strOrderDesc = @strOrderDesc + dbo.schGetPayDesc(@OrderType,'在营业执照齐全，并确认收到汇款后',@NeedInvoice)
	End

	If @PayMethod = 19
	BEGIN
		SET @strOrderDesc = @strOrderDesc + '1、支付宝支付（支持全国银行卡，网上付款，自动开通）<br>'
		SET @strOrderDesc = @strOrderDesc + '&nbsp;请到网站在线支付，'
		If @OrderType = 1 Or @OrderType = 2 Or @OrderType = 5 Or @OrderType = 8 Or @OrderType = 9 Or @OrderType = 10 Or @OrderType = 11
			SET @strOrderDesc = @strOrderDesc + '支付完成后，自动开通。' + '<br>'

		If @OrderType = 4
			SET @strOrderDesc = @strOrderDesc + '支付完成后，工作日10分钟之内我们电话与您联系广告制作与播放。' + '<br>'

		If @OrderType = 7
			SET @strOrderDesc = @strOrderDesc + '4、确认收到汇款后，工作日10分钟之内您的单位名称出现在“首页知名企业招聘”。' + '<br>'

		If @NeedInvoice = 1
			SET @strOrderDesc = @strOrderDesc + '汇款到帐后您可以索取发票，在三个工作日内，将您的发票挂号信寄出。<br>'

	End

	If @PayMethod = 12
	BEGIN
		SET @strOrderDesc = @strOrderDesc + '1、建设银行<br>'
		SET @strOrderDesc = @strOrderDesc + '&nbsp;收款人全称：' + @Receiver + '<br>'
		SET @strOrderDesc = @strOrderDesc + '&nbsp;帐号：' + @Account + '<br>' 
		SET @strOrderDesc = @strOrderDesc + '&nbsp;开户银行：' + @BankName + '<br>' 
		SET @strOrderDesc = @strOrderDesc + '2、汇款成功后，请立即打电话或者发邮件通知我们订单号以及汇款金额。<br>'
		SET @strOrderDesc = @strOrderDesc + dbo.schGetPayDesc(@OrderType,'在营业执照齐全，并确认收到汇款后',@NeedInvoice)
	End

	If @PayMethod = 13
	BEGIN
		SET @strOrderDesc = @strOrderDesc + '1、中国银行<br>'
		SET @strOrderDesc = @strOrderDesc + '&nbsp;收款人全称：' + @Receiver + '<br>'
		SET @strOrderDesc = @strOrderDesc + '&nbsp;帐号：' + @Account + '<br>' 
		SET @strOrderDesc = @strOrderDesc + '&nbsp;开户银行：' + @BankName + '<br>' 
		SET @strOrderDesc = @strOrderDesc + '2、汇款成功后，请立即打电话或者发邮件通知我们订单号以及汇款金额。<br>'
		SET @strOrderDesc = @strOrderDesc + dbo.schGetPayDesc(@OrderType,'在营业执照齐全，并确认收到汇款后',@NeedInvoice)
	End

	If @PayMethod = 14
	BEGIN
		SET @strOrderDesc = @strOrderDesc + '1、交通银行<br>'
		SET @strOrderDesc = @strOrderDesc + '&nbsp;收款人全称：' + @Receiver + '<br>'
		SET @strOrderDesc = @strOrderDesc + '&nbsp;帐号：' + @Account + '<br>' 
		SET @strOrderDesc = @strOrderDesc + '&nbsp;开户银行：' + @BankName + '<br>' 
		SET @strOrderDesc = @strOrderDesc + '2、汇款成功后，请立即打电话或者发邮件通知我们订单号以及汇款金额。<br>'
		SET @strOrderDesc = @strOrderDesc + dbo.schGetPayDesc(@OrderType,'在营业执照齐全，并确认收到汇款后',@NeedInvoice)
	End
	
	If @PayMethod = 17
	BEGIN
		SET @strOrderDesc = @strOrderDesc + '1、转帐支票<br>'
		SET @strOrderDesc = @strOrderDesc + '&nbsp;收款人：' + @Receiver + '<br>'
		SET @strOrderDesc = @strOrderDesc + '&nbsp;开户银行：' + @BankName + '<br>'
		SET @strOrderDesc = @strOrderDesc + '&nbsp;帐号：' + @Account + '<br>' 
		SET @strOrderDesc = @strOrderDesc + '&nbsp;汇款用途：会员服务费，订单号' + LTRIM(STR(@OrderID)) + '<br>'   
		SET @strOrderDesc = @strOrderDesc + '2、您可以将支票快递给我们，也可以将支票亲自送过来。<br>'
		SET @strOrderDesc = @strOrderDesc + dbo.schGetPayDesc(@OrderType,'在收到转帐支票、营业执照齐全后',@NeedInvoice)
	End
	
	If @PayMethod = 18
	BEGIN
		SET @strOrderDesc = @strOrderDesc + '1、同城转帐<br>'
		SET @strOrderDesc = @strOrderDesc + '&nbsp;收款人：' + @Receiver + '<br>'
		SET @strOrderDesc = @strOrderDesc + '&nbsp;开户银行：' + @BankName + '<br>'
		SET @strOrderDesc = @strOrderDesc + '&nbsp;帐号：' + @Account + '<br>' 
		SET @strOrderDesc = @strOrderDesc + '&nbsp;汇款用途：会员服务费，订单号' + LTRIM(STR(@OrderID)) + '<br>'   
		SET @strOrderDesc = @strOrderDesc + '2、将同城转帐回单传真至：010-65800851 或者 021-61916451<br>'
		SET @strOrderDesc = @strOrderDesc + dbo.schGetPayDesc(@OrderType,'在同城转帐回单传真、营业执照齐全后',@NeedInvoice)
	End
	
	If @PayMethod = 20
	BEGIN
		SET @strOrderDesc = @strOrderDesc + '1、邮政储蓄银行<br>'
		SET @strOrderDesc = @strOrderDesc + '&nbsp;收款人全称：' + @Receiver + '<br>'
		SET @strOrderDesc = @strOrderDesc + '&nbsp;帐号：' + @Account + '<br>' 
		SET @strOrderDesc = @strOrderDesc + '&nbsp;开户银行：' + @BankName + '<br>' 
		SET @strOrderDesc = @strOrderDesc + '2、汇款成功后，请立即打电话或者发邮件通知我们订单号以及汇款金额。<br>'
		SET @strOrderDesc = @strOrderDesc + dbo.schGetPayDesc(@OrderType,'在营业执照齐全，并确认收到汇款后',@NeedInvoice)
	End
	RETURN @strOrderDesc
END

GO
/****** Object:  UserDefinedFunction [dbo].[schGetPayDesc]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[schGetPayDesc]
(
	@OrderType TINYINT,
	@strDesc NVARCHAR(200),
	@NeedInvoice BIT
)
RETURNS VARCHAR(MAX)
AS
BEGIN
	DECLARE @PayDesc NVARCHAR(500)
	SET @PayDesc = '3、如果贵单位还没有通过营业执照审核，请先上传营业执照，或者传真到 010-65800851 或者 021-61916451<br>'
	If @OrderType = 1 Or @OrderType = 2 Or @OrderType = 8 Or @OrderType = 9 Or @OrderType = 10 Or @OrderType = 11
		SET @PayDesc = @PayDesc + '4、' + @strDesc + '，工作日10分钟之内开通，并通过E-mail通知。<br>'

	If @OrderType = 4
		SET @PayDesc = @PayDesc + '4、' + @strDesc + '，工作日10分钟之内我们电话与您联系广告制作与播放。<br>'

	If @OrderType = 7
		SET @PayDesc = @PayDesc + '4、确认收到汇款后，工作日10分钟之内您的单位名称出现在“首页知名企业招聘”。<br>'

	If @NeedInvoice = 1
		SET @PayDesc = @PayDesc + '5、汇款到帐后您可以索取发票，在三个工作日内，将您的发票挂号信寄出。<br>'

	RETURN @PayDesc
END

GO
/****** Object:  UserDefinedFunction [dbo].[SHA1]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create FUNCTION [dbo].[SHA1]
(
	@Str VARCHAR(40)
)
RETURNS VARCHAR(40)
AS
BEGIN	
	RETURN RIGHT(SYS.fn_VarBinToHexStr(hashbytes('SHA1', LOWER(@Str))), 40)
END



GO
/****** Object:  UserDefinedFunction [dbo].[ShowContact]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[ShowContact]
(
	@cvMainID INT,
	@cpMainID INT
)
RETURNS BIT
AS
BEGIN
	DECLARE @cpMemeberType INT
	SELECT @cpMemeberType = MemberType FROM cpMain WITH(NOLOCK) WHERE ID = @cpMainID
	IF @cpMemeberType IN(3, 10)
		RETURN 1
	ELSE IF @cpMemeberType = 11
	BEGIN

		BEGIN
			IF EXISTS(
				SELECT 'x' FROM caBalanceLog WITH(NOLOCK)
				WHERE cpMainID = @cpMainID
				AND cvMainID = @cvMainID
				AND CONVERT(VARCHAR(100), AddDate, 23) = CONVERT(VARCHAR(100), GETDATE(), 23)
			) OR EXISTS(
				SELECT 'x' FROM CaCvQuotaLog WITH(NOLOCK)
				WHERE cpMainID = @cpMainID
				AND cvMainID = @cvMainID
			)
				RETURN 1
		END
	END
	ELSE
	BEGIN
		DECLARE @isInActiveLog INT
		DECLARE @isInDailyGiftLog INT
		SELECT @isInDailyGiftLog = count(1) FROM caDailyGiftLog WITH(NOLOCK)
			WHERE cpMainID = @cpMainID
			AND cvMainID = @cvMainID
		IF @isInDailyGiftLog > 0 
			RETURN 1
		SELECT @isInActiveLog = count(1) FROM caActiveLog WITH(NOLOCK)
			WHERE cpMainID = @cpMainID
			AND cvMainID = @cvMainID
		If @isInActiveLog > 0  
			RETURN 1
		IF EXISTS (
			SELECT 'x' FROM ExJobApply a WITH(NOLOCK),Job b 
			WHERE a.JobID = b.ID 
			AND a.IsPassed = 1 
			AND a.cvMainID = @cvMainID
			AND b.cpMainID = @cpMainID
		)
		RETURN 1
	END
	RETURN 0
END

GO
/****** Object:  UserDefinedFunction [dbo].[ShowContactByExcel]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[ShowContactByExcel]
(
	@cvMainID INT,
	@cpMainID INT
)
RETURNS BIT
AS
BEGIN
	DECLARE @cpMemeberType INT
	SELECT @cpMemeberType = MemberType FROM cpMain WITH(NOLOCK) WHERE ID = @cpMainID
	IF @cpMemeberType = 10 Or @cpMemeberType = 11
	BEGIN
		IF @cpMemeberType = 10
			RETURN 1
		ELSE
		BEGIN
			IF EXISTS(
				SELECT 'x' FROM caBalanceLog WITH(NOLOCK)
				WHERE cpMainID = @cpMainID
				AND cvMainID = @cvMainID
				AND CONVERT(VARCHAR(100), AddDate, 23) = CONVERT(VARCHAR(100), GETDATE(), 23)
			)
				RETURN 1
		END
	END
	ELSE
	BEGIN
		DECLARE @isInActiveLog INT
		DECLARE @isInDailyGiftLog INT
		SELECT @isInDailyGiftLog = count(1) FROM caDailyGiftLog WITH(NOLOCK)
			WHERE cpMainID = @cpMainID
			AND cvMainID = @cvMainID
		IF @isInDailyGiftLog > 0 
			RETURN 1
		SELECT @isInActiveLog = count(1) FROM caActiveLog WITH(NOLOCK)
			WHERE cpMainID = @cpMainID
			AND cvMainID = @cvMainID
		If @isInActiveLog > 0  
			RETURN 1
		IF EXISTS (
			SELECT 'x' FROM cvMain
			WHERE ID = @cvMainID
			AND IsOpen = 1
		)
		RETURN 1
	END
	RETURN 0
END

GO
/****** Object:  UserDefinedFunction [dbo].[Split]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--######################################################3
--实现split功能 的函数
--######################################################3
create FUNCTION [dbo].[Split]
(
	@StrSource VARCHAR(8000),
	@StrSeprate VARCHAR(10)
)
RETURNS @Temp TABLE(a VARCHAR(100))
AS
BEGIN
	DECLARE @i INT
	SET @StrSource=RTRIM(LTRIM(@StrSource))
	SET @i=CHARINDEX(@StrSeprate, @StrSource)
	WHILE @i>=1
	BEGIN
		IF LEFT(@StrSource,@i-1) > '' 
		INSERT @temp VALUES(LEFT(@StrSource, @i - 1))
		SET @StrSource = SUBSTRING(@StrSource, @i + 1, LEN(@StrSource) - @i)
		SET @i = CHARINDEX(@StrSeprate, @StrSource)
	END
	IF @StrSource <> ''
		INSERT @Temp VALUES(@StrSource)
	RETURN 
END


GO
/****** Object:  UserDefinedFunction [dbo].[Split2]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--######################################################3  --实现split功能 的函数  --######################################################3  
CREATE FUNCTION [dbo].[Split2]
(   
	@StrSource VARCHAR(MAX),   
	@StrSeprate VARCHAR(10)
)  
RETURNS @Temp TABLE(Id Int IDENTITY(1, 1), msg VARCHAR(MAX))  
AS  
BEGIN   
	DECLARE @i INT
	SET @StrSource = RTRIM(LTRIM(@StrSource))
	SET @i = CHARINDEX(@StrSeprate, @StrSource)
	WHILE @i > =1
	BEGIN    
		IF LEFT(@StrSource, @i - 1) > '' 
			INSERT @temp VALUES(LEFT(@StrSource, @i - 1))
	
		SET @StrSource = SUBSTRING(@StrSource, @i + LEN(@StrSeprate), LEN(@StrSource) - @i - LEN(@StrSeprate) + 1)
		SET @i = CHARINDEX(@StrSeprate, @StrSource)
	END   
	IF @StrSource <> ''    
	INSERT @Temp VALUES(@StrSource)   
	RETURN   
END    

GO
/****** Object:  UserDefinedFunction [dbo].[SplitTop]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--######################################################3
--实现split功能 的函数
--######################################################3
CREATE FUNCTION [dbo].[SplitTop]
(
	@StrSource VARCHAR(8000),
	@Top INT
)
RETURNS @Temp TABLE(ID VARCHAR(100))
AS
BEGIN
	DECLARE @i INT
	SET @StrSource = RTRIM(LTRIM(@StrSource))
	SET @i = CHARINDEX(',', @StrSource)
	WHILE @i > =1 AND @Top > 0
	BEGIN
		IF LEFT(@StrSource,@i-1) > '' 
		INSERT @temp VALUES(LEFT(@StrSource, @i - 1))
		SELECT @StrSource = SUBSTRING(@StrSource, @i + 1, LEN(@StrSource) - @i), 
			@i = CHARINDEX(',', @StrSource),
			@Top = @Top - 1
	END
	RETURN 
END

GO
/****** Object:  UserDefinedFunction [dbo].[StripHTML]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[StripHTML]   
(
	@HTMLText VARCHAR(MAX)
)
RETURNS VARCHAR(MAX)   
AS   
BEGIN   
	DECLARE @Start INT   
	DECLARE @End INT   
	DECLARE @Length INT  
	SET @HTMLText = REPLACE(@HTMLText, '&amp;nbsp;', ' ')
	SET @HTMLText = REPLACE(@HTMLText, '&nbsp;', ' ')
	--SET @HTMLText = REPLACE(LTRIM(RTRIM(@HTMLText)), '  ', '&nbsp; &nbsp; ')
	SET @HTMLText = REPLACE(@HTMLText, '<br>'+Char(13)+Char(10), Char(13)+Char(10))
	SET @HTMLText = REPLACE(@HTMLText, '<br >'+Char(13)+Char(10), Char(13)+Char(10))
	SET @HTMLText = REPLACE(@HTMLText, '<br />'+Char(13)+Char(10), Char(13)+Char(10))
	--SET @HTMLText = REPLACE(@HTMLText, '</p>'+Char(13)+Char(10), '')
	--SET @HTMLText = REPLACE(@HTMLText, '</div>'+Char(13)+Char(10), '')

	SET @HTMLText = REPLACE(@HTMLText, '<br>'+Char(13), Char(13)+Char(10))
	SET @HTMLText = REPLACE(@HTMLText, '<br >'+Char(13), Char(13)+Char(10))
	SET @HTMLText = REPLACE(@HTMLText, '<br />'+Char(13), Char(13)+Char(10))

	SET @HTMLText = REPLACE(@HTMLText, '<br>'+Char(10), Char(13)+Char(10))
	SET @HTMLText = REPLACE(@HTMLText, '<br >'+Char(10), Char(13)+Char(10))
	SET @HTMLText = REPLACE(@HTMLText, '<br />'+Char(10), Char(13)+Char(10))
	--SET @HTMLText = REPLACE(@HTMLText, '</p>'+Char(10), '')
	--SET @HTMLText = REPLACE(@HTMLText, '</div>'+Char(10), '')

	SET @HTMLText = REPLACE(@HTMLText, '<br>', Char(13)+Char(10))
	SET @HTMLText = REPLACE(@HTMLText, '<br >', Char(13)+Char(10))
	SET @HTMLText = REPLACE(@HTMLText, '<br />', Char(13)+Char(10))
	--SET @HTMLText = REPLACE(@HTMLText, '</p>', '')
	--SET @HTMLText = REPLACE(@HTMLText, '</div>', '')
/*
	SET @Start = dbo.HtmlPos(@HTMLText)   
	SET @End = CHARINDEX('>', @HTMLText, @Start)   
	SET @Length = (@End - @Start) + 1 
	WHILE @Start > 0 AND @End > 0 AND @Length > 0   
	BEGIN   
		SET @HTMLText = STUFF(@HTMLText, @Start, @Length, '')   
		SET @Start = dbo.HtmlPos(@HTMLText)   
		SET @End = CHARINDEX('>', @HTMLText, @Start)   
		SET @Length = (@End - @Start) + 1   
	END
	SET @HTMLText = REPLACE(@HTMLText, '<', '&lt;')
	SET @HTMLText = REPLACE(@HTMLText, '>', '&gt;')
*/
	RETURN RTRIM(@HTMLText)
END

GO
/****** Object:  UserDefinedFunction [dbo].[TextTrim]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--#############################333
--文本框前导4个空格
--#############################333
CREATE FUNCTION [dbo].[TextTrim]
(
	@sText VARCHAR(MAX)
)
RETURNS VARCHAR(MAX)
AS
BEGIN
	IF LTRIM(@sText) = ''
		RETURN NULL

	SET @sText = REPLACE(RTRIM(@sText), '&nbsp;', ' ')
	IF LEFT(@sText , 4) = '    '
		SET @sText = '    ' + LTRIM(@sText)

	RETURN @sText
END




GO
/****** Object:  UserDefinedFunction [dbo].[TheMonth]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[TheMonth]
(
	@CountDate INT
)
RETURNS INT   
AS
BEGIN
	DECLARE @Result INT
    IF CAST(RIGHT(STR(@CountDate), 2) AS INT) >= 26
    BEGIN
      DECLARE @dd SMALLDATETIME
      SET @dd = DATEADD(m, 1, LEFT(LTRIM(RTRIM(STR(@CountDate))),4) + '-' + RIGHT(LEFT(LTRIM(RTRIM(STR(@CountDate))),6),2)+'-1 00:00')
      SET @Result=YEAR(@dd)*100+MONTH(@dd)
    END
    ELSE
    BEGIN
      SET @Result=@CountDate/100
    END
    RETURN @Result   
END


GO
/****** Object:  UserDefinedFunction [dbo].[ToJianPin]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[ToJianPin](@Words NVARCHAR(2000))  
RETURNS VARCHAR(8000)  
AS 
BEGIN  
    DECLARE @Word nchar(1)  
    DECLARE @PinYin VARCHAR(8000)  
    DECLARE @Index int 
    DECLARE @WordLenth int 
    DECLARE @Unicode int 
    SET @Index = 1  
    SET @Words = LTRIM(RTRIM(@Words))  
    SET @WordLenth = LEN(@Words)  
    WHILE (@Index <= @WordLenth) --循环取字符 
    BEGIN  
    SET @Word = SUBSTRING(@Words, @Index, 1)  
    SET @Unicode = UNICODE(@Word)
    SET @PinYin = ISNULL(@PinYin,'')+   
    (
		CASE WHEN UNICODE(@Word) BETWEEN 19968 AND 19968+20901 THEN   
		(
			SELECT TOP 1 PinYin FROM 
			(  
				SELECT 'a' AS PinYin, '驁' AS Word  
				UNION ALL SELECT 'b', '簿'
				UNION ALL SELECT 'c', '錯'
				UNION ALL SELECT 'd', '鵽'
				UNION ALL SELECT 'e', '樲'
				UNION ALL SELECT 'f', '猤'
				UNION ALL SELECT 'g', '腂'
				UNION ALL SELECT 'h', '夻'
				UNION ALL SELECT 'j', '攈'
				UNION ALL SELECT 'k', '穒'
				UNION ALL SELECT 'l', '鱳'
				UNION ALL SELECT 'm', '旀'
				UNION ALL SELECT 'n', '桛'
				UNION ALL SELECT 'o', '漚'
				UNION ALL SELECT 'p', '曝'
				UNION ALL SELECT 'q', '囕'
				UNION ALL SELECT 'r', '鶸'
				UNION ALL SELECT 's', '蜶'
				UNION ALL SELECT 't', '籜'
				UNION ALL SELECT 'w', '鶩'
				UNION ALL SELECT 'x', '鑂'
				UNION ALL SELECT 'y', '韻'
				UNION ALL SELECT 'z', '咗'
			) Temp   
			WHERE Word >= @Word COLLATE Chinese_PRC_CS_AS_KS_WS   
			ORDER BY Word COLLATE Chinese_PRC_CS_AS_KS_WS ASC
		) 
		ELSE @Word END
	)
	SET @Index = @Index + 1  
    END
    RETURN @PinYin  
END  

GO
/****** Object:  UserDefinedFunction [dbo].[ToPinYin]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create FUNCTION [dbo].[ToPinYin](@Words NVARCHAR(2000))  
RETURNS VARCHAR(8000)  
AS 
BEGIN  
    DECLARE @Word nchar(1)  
    DECLARE @PinYin VARCHAR(8000)  
    DECLARE @Index int 
    DECLARE @WordLenth int 
    DECLARE @Unicode int 
    SET @Index = 1  
    SET @Words = LTRIM(RTRIM(@Words))  
    SET @WordLenth = LEN(@Words)  
    WHILE (@Index <= @WordLenth) --循环取字符 
    BEGIN  
    SET @Word = SUBSTRING(@Words, @Index, 1)  
    SET @Unicode = UNICODE(@Word)
    SET @PinYin = ISNULL(@PinYin,'')+   
    (
		CASE WHEN UNICODE(@Word) BETWEEN 19968 AND 19968+20901 THEN   
		(
			SELECT TOP 1 PinYin FROM 
			(  
				SELECT 'a' AS PinYin,N'厑' AS Word  
				UNION ALL SELECT 'ai',N'靉' 
				UNION ALL SELECT 'an',N'黯' 
				UNION ALL SELECT 'ang',N'醠' 
				UNION ALL SELECT 'ao',N'驁' 
				UNION ALL SELECT 'ba',N'欛' 
				UNION ALL SELECT 'bai',N'瓸'
				UNION ALL SELECT 'ban',N'瓣' 
				UNION ALL SELECT 'bang',N'鎊' 
				UNION ALL SELECT 'bao',N'鑤' 
				UNION ALL SELECT 'bei',N'鐾' 
				UNION ALL SELECT 'ben',N'輽' 
				UNION ALL SELECT 'beng',N'鏰' 
				UNION ALL SELECT 'bi',N'鼊' 
				UNION ALL SELECT 'bian',N'變' 
				UNION ALL SELECT 'biao',N'鰾' 
				UNION ALL SELECT 'bie',N'彆' 
				UNION ALL SELECT 'bin',N'鬢' 
				UNION ALL SELECT 'bing',N'靐' 
				UNION ALL SELECT 'bo',N'蔔' 
				UNION ALL SELECT 'bu',N'簿' 
				UNION ALL SELECT 'ca',N'囃' 
				UNION ALL SELECT 'cai',N'乲'
				UNION ALL SELECT 'can',N'爘' 
				UNION ALL SELECT 'cang',N'賶' 
				UNION ALL SELECT 'cao',N'鼜' 
				UNION ALL SELECT 'ce',N'簎' 
				UNION ALL SELECT 'cen',N'笒' 
				UNION ALL SELECT 'ceng',N'乽' --硛硳岾猠乽 
				UNION ALL SELECT 'cha',N'詫' 
				UNION ALL SELECT 'chai',N'囆' 
				UNION ALL SELECT 'chan',N'顫' 
				UNION ALL SELECT 'chang',N'韔' 
				UNION ALL SELECT 'chao',N'觘' 
				UNION ALL SELECT 'che',N'爡' 
				UNION ALL SELECT 'chen',N'讖' 
				UNION ALL SELECT 'cheng',N'秤' 
				UNION ALL SELECT 'chi',N'鷘' 
				UNION ALL SELECT 'chong',N'銃' 
				UNION ALL SELECT 'chou',N'殠' 
				UNION ALL SELECT 'chu',N'矗' 
				UNION ALL SELECT 'chuai',N'踹' 
				UNION ALL SELECT 'chuan',N'鶨' 
				UNION ALL SELECT 'chuang',N'愴' 
				UNION ALL SELECT 'chui',N'顀' 
				UNION ALL SELECT 'chun',N'蠢' 
				UNION ALL SELECT 'chuo',N'縒' 
				UNION ALL SELECT 'ci',N'嗭' --賜嗭 
				UNION ALL SELECT 'cong',N'謥' 
				UNION ALL SELECT 'cou',N'輳' 
				UNION ALL SELECT 'cu',N'顣' 
				UNION ALL SELECT 'cuan',N'爨' 
				UNION ALL SELECT 'cui',N'臎' 
				UNION ALL SELECT 'cun',N'籿' 
				UNION ALL SELECT 'cuo',N'錯' 
				UNION ALL SELECT 'da',N'橽' 
				UNION ALL SELECT 'dai',N'靆' 
				UNION ALL SELECT 'dan',N'饏' 
				UNION ALL SELECT 'dang',N'闣' 
				UNION ALL SELECT 'dao',N'纛' 
				UNION ALL SELECT 'de',N'的' 
				UNION ALL SELECT 'den',N'扽' 
				UNION ALL SELECT 'deng',N'鐙' 
				UNION ALL SELECT 'di',N'螮' 
				UNION ALL SELECT 'dia',N'嗲' 
				UNION ALL SELECT 'dian',N'驔' 
				UNION ALL SELECT 'diao',N'鑃' 
				UNION ALL SELECT 'die',N'嚸' --眰嚸 
				UNION ALL SELECT 'ding',N'顁' 
				UNION ALL SELECT 'diu',N'銩' 
				UNION ALL SELECT 'dong',N'霘' 
				UNION ALL SELECT 'dou',N'鬭' 
				UNION ALL SELECT 'du',N'蠹' 
				UNION ALL SELECT 'duan',N'叾' --籪叾 
				UNION ALL SELECT 'dui',N'譵' 
				UNION ALL SELECT 'dun',N'踲' 
				UNION ALL SELECT 'duo',N'鵽' 
				UNION ALL SELECT 'e',N'鱷' 
				UNION ALL SELECT 'en',N'摁' 
				UNION ALL SELECT 'eng',N'鞥' 
				UNION ALL SELECT 'er',N'樲' 
				UNION ALL SELECT 'fa',N'髮' 
				UNION ALL SELECT 'fan',N'瀪' 
				UNION ALL SELECT 'fang',N'放' 
				UNION ALL SELECT 'fei',N'靅' 
				UNION ALL SELECT 'fen',N'鱝' 
				UNION ALL SELECT 'feng',N'覅' 
				UNION ALL SELECT 'fo',N'梻' 
				UNION ALL SELECT 'fou',N'鴀' 
				UNION ALL SELECT 'fu',N'猤' --鰒猤 
				UNION ALL SELECT 'ga',N'魀' 
				UNION ALL SELECT 'gai',N'瓂' 
				UNION ALL SELECT 'gan',N'灨' 
				UNION ALL SELECT 'gang',N'戇' 
				UNION ALL SELECT 'gao',N'鋯' 
				UNION ALL SELECT 'ge',N'獦' 
				UNION ALL SELECT 'gei',N'給' 
				UNION ALL SELECT 'gen',N'搄' 
				UNION ALL SELECT 'geng',N'堩' --亙堩啹喼嗰 
				UNION ALL SELECT 'gong',N'兣' --熕贑兝兣 
				UNION ALL SELECT 'gou',N'購' 
				UNION ALL SELECT 'gu',N'顧' 
				UNION ALL SELECT 'gua',N'詿' 
				UNION ALL SELECT 'guai',N'恠' 
				UNION ALL SELECT 'guan',N'鱹' 
				UNION ALL SELECT 'guang',N'撗' 
				UNION ALL SELECT 'gui',N'鱥' 
				UNION ALL SELECT 'gun',N'謴' 
				UNION ALL SELECT 'guo',N'腂' 
				UNION ALL SELECT 'ha',N'哈' 
				UNION ALL SELECT 'hai',N'饚' 
				UNION ALL SELECT 'han',N'鶾' 
				UNION ALL SELECT 'hang',N'沆' 
				UNION ALL SELECT 'hao',N'兞' 
				UNION ALL SELECT 'he',N'靏' 
				UNION ALL SELECT 'hei',N'嬒' 
				UNION ALL SELECT 'hen',N'恨' 
				UNION ALL SELECT 'heng',N'堼' --堼囍 
				UNION ALL SELECT 'hong',N'鬨' 
				UNION ALL SELECT 'hou',N'鱟' 
				UNION ALL SELECT 'hu',N'鸌' 
				UNION ALL SELECT 'hua',N'蘳' 
				UNION ALL SELECT 'huai',N'蘾' 
				UNION ALL SELECT 'huan',N'鰀' 
				UNION ALL SELECT 'huang',N'鎤' 
				UNION ALL SELECT 'hui',N'顪' 
				UNION ALL SELECT 'hun',N'諢' 
				UNION ALL SELECT 'huo',N'夻' 
				UNION ALL SELECT 'ji',N'驥' 
				UNION ALL SELECT 'jia',N'嗧' 
				UNION ALL SELECT 'jian',N'鑳' 
				UNION ALL SELECT 'jiang',N'謽' 
				UNION ALL SELECT 'jiao',N'釂' 
				UNION ALL SELECT 'jie',N'繲' 
				UNION ALL SELECT 'jin',N'齽' 
				UNION ALL SELECT 'jing',N'竸' 
				UNION ALL SELECT 'jiong',N'蘔' 
				UNION ALL SELECT 'jiu',N'欍' 
				UNION ALL SELECT 'ju',N'爠' 
				UNION ALL SELECT 'juan',N'羂' 
				UNION ALL SELECT 'jue',N'钁' 
				UNION ALL SELECT 'jun',N'攈' 
				UNION ALL SELECT 'ka',N'鉲' 
				UNION ALL SELECT 'kai',N'乫' --鎎乫 
				UNION ALL SELECT 'kan',N'矙' 
				UNION ALL SELECT 'kang',N'閌' 
				UNION ALL SELECT 'kao',N'鯌' 
				UNION ALL SELECT 'ke',N'騍' 
				UNION ALL SELECT 'ken',N'褃' 
				UNION ALL SELECT 'keng',N'鏗' --巪乬唟厼怾 
				UNION ALL SELECT 'kong',N'廤' 
				UNION ALL SELECT 'kou',N'鷇' 
				UNION ALL SELECT 'ku',N'嚳' 
				UNION ALL SELECT 'kua',N'骻' 
				UNION ALL SELECT 'kuai',N'鱠' 
				UNION ALL SELECT 'kuan',N'窾' 
				UNION ALL SELECT 'kuang',N'鑛' 
				UNION ALL SELECT 'kui',N'鑎' 
				UNION ALL SELECT 'kun',N'睏' 
				UNION ALL SELECT 'kuo',N'穒' 
				UNION ALL SELECT 'la',N'鞡' 
				UNION ALL SELECT 'lai',N'籟' 
				UNION ALL SELECT 'lan',N'糷' 
				UNION ALL SELECT 'lang',N'唥' 
				UNION ALL SELECT 'lao',N'軂' 
				UNION ALL SELECT 'le',N'餎' 
				UNION ALL SELECT 'lei',N'脷' --嘞脷 
				UNION ALL SELECT 'leng',N'睖' 
				UNION ALL SELECT 'li',N'瓈' 
				UNION ALL SELECT 'lia',N'倆' 
				UNION ALL SELECT 'lian',N'纞' 
				UNION ALL SELECT 'liang',N'鍄' 
				UNION ALL SELECT 'liao',N'瞭' 
				UNION ALL SELECT 'lie',N'鱲' 
				UNION ALL SELECT 'lin',N'轥' --轥拎 
				UNION ALL SELECT 'ling',N'炩' 
				UNION ALL SELECT 'liu',N'咯' --瓼甅囖咯 
				UNION ALL SELECT 'long',N'贚' 
				UNION ALL SELECT 'lou',N'鏤' 
				UNION ALL SELECT 'lu',N'氇' 
				UNION ALL SELECT 'lv',N'鑢' 
				UNION ALL SELECT 'luan',N'亂' 
				UNION ALL SELECT 'lue',N'擽' 
				UNION ALL SELECT 'lun',N'論' 
				UNION ALL SELECT 'luo',N'鱳' 
				UNION ALL SELECT 'ma',N'嘛' 
				UNION ALL SELECT 'mai',N'霢' 
				UNION ALL SELECT 'man',N'蘰' 
				UNION ALL SELECT 'mang',N'蠎' 
				UNION ALL SELECT 'mao',N'唜' 
				UNION ALL SELECT 'me',N'癦' --癦呅 
				UNION ALL SELECT 'mei',N'嚜' 
				UNION ALL SELECT 'men',N'們' 
				UNION ALL SELECT 'meng',N'霥' --霿踎 
				UNION ALL SELECT 'mi',N'羃' 
				UNION ALL SELECT 'mian',N'麵' 
				UNION ALL SELECT 'miao',N'廟' 
				UNION ALL SELECT 'mie',N'鱴' --鱴瓱 
				UNION ALL SELECT 'min',N'鰵' 
				UNION ALL SELECT 'ming',N'詺' 
				UNION ALL SELECT 'miu',N'謬' 
				UNION ALL SELECT 'mo',N'耱' --耱乮 
				UNION ALL SELECT 'mou',N'麰' --麰蟱 
				UNION ALL SELECT 'mu',N'旀' 
				UNION ALL SELECT 'na',N'魶' 
				UNION ALL SELECT 'nai',N'錼' 
				UNION ALL SELECT 'nan',N'婻' 
				UNION ALL SELECT 'nang',N'齉' 
				UNION ALL SELECT 'nao',N'臑' 
				UNION ALL SELECT 'ne',N'呢' 
				UNION ALL SELECT 'nei',N'内' --嫩焾 
				UNION ALL SELECT 'nen',N'嫩' 
				UNION ALL SELECT 'neng',N'能' --莻嗯鈪銰啱 
				UNION ALL SELECT 'ni',N'嬺' 
				UNION ALL SELECT 'nian',N'艌' 
				UNION ALL SELECT 'niang',N'釀' 
				UNION ALL SELECT 'niao',N'脲' 
				UNION ALL SELECT 'nie',N'钀' 
				UNION ALL SELECT 'nin',N'拰' 
				UNION ALL SELECT 'ning',N'濘' 
				UNION ALL SELECT 'niu',N'靵' 
				UNION ALL SELECT 'nong',N'齈' 
				UNION ALL SELECT 'nou',N'譳' 
				UNION ALL SELECT 'nu',N'搙' 
				UNION ALL SELECT 'nv',N'衄' 
				UNION ALL SELECT 'nue',N'瘧' 
				UNION ALL SELECT 'nuan',N'燶' --硸黁燶郍 
				UNION ALL SELECT 'nuo',N'桛' 
				UNION ALL SELECT 'o',N'鞰' --毮夞乯鞰 
				UNION ALL SELECT 'ou',N'漚' 
				UNION ALL SELECT 'pa',N'袙' 
				UNION ALL SELECT 'pai',N'磗' --鎃磗 
				UNION ALL SELECT 'pan',N'鑻' 
				UNION ALL SELECT 'pang',N'胖' 
				UNION ALL SELECT 'pao',N'礮' 
				UNION ALL SELECT 'pei',N'轡' 
				UNION ALL SELECT 'pen',N'喯' 
				UNION ALL SELECT 'peng',N'喸' --浌巼闏乶喸 
				UNION ALL SELECT 'pi',N'鸊' 
				UNION ALL SELECT 'pian',N'騙' 
				UNION ALL SELECT 'piao',N'慓' 
				UNION ALL SELECT 'pie',N'嫳' 
				UNION ALL SELECT 'pin',N'聘' 
				UNION ALL SELECT 'ping',N'蘋' 
				UNION ALL SELECT 'po',N'魄' 
				UNION ALL SELECT 'pou',N'哛' --兺哛 
				UNION ALL SELECT 'pu',N'曝' 
				UNION ALL SELECT 'qi',N'蟿' 
				UNION ALL SELECT 'qia',N'髂' 
				UNION ALL SELECT 'qian',N'縴' 
				UNION ALL SELECT 'qiang',N'瓩' --羻兛瓩 
				UNION ALL SELECT 'qiao',N'躈' 
				UNION ALL SELECT 'qie',N'籡' 
				UNION ALL SELECT 'qin',N'藽' 
				UNION ALL SELECT 'qing',N'櫦' 
				UNION ALL SELECT 'qiong',N'瓗' 
				UNION ALL SELECT 'qiu',N'糗' 
				UNION ALL SELECT 'qu',N'覻' 
				UNION ALL SELECT 'quan',N'勸' 
				UNION ALL SELECT 'que',N'礭' 
				UNION ALL SELECT 'qun',N'囕' 
				UNION ALL SELECT 'ran',N'橪' 
				UNION ALL SELECT 'rang',N'讓' 
				UNION ALL SELECT 'rao',N'繞' 
				UNION ALL SELECT 're',N'熱' 
				UNION ALL SELECT 'ren',N'餁' 
				UNION ALL SELECT 'reng',N'陾' 
				UNION ALL SELECT 'ri',N'馹' 
				UNION ALL SELECT 'rong',N'穃' 
				UNION ALL SELECT 'rou',N'嶿' 
				UNION ALL SELECT 'ru',N'擩' 
				UNION ALL SELECT 'ruan',N'礝' 
				UNION ALL SELECT 'rui',N'壡' 
				UNION ALL SELECT 'run',N'橍' --橍挼 
				UNION ALL SELECT 'ruo',N'鶸' 
				UNION ALL SELECT 'sa',N'栍' --櫒栍 
				UNION ALL SELECT 'sai',N'虄' --簺虄 
				UNION ALL SELECT 'san',N'閐' 
				UNION ALL SELECT 'sang',N'喪' 
				UNION ALL SELECT 'sao',N'髞' 
				UNION ALL SELECT 'se',N'飋' --裇聓 
				UNION ALL SELECT 'sen',N'篸' 
				UNION ALL SELECT 'seng',N'縇' --閪縇 
				UNION ALL SELECT 'sha',N'霎' 
				UNION ALL SELECT 'shai',N'曬' 
				UNION ALL SELECT 'shan',N'鱔' 
				UNION ALL SELECT 'shang',N'緔' 
				UNION ALL SELECT 'shao',N'潲' 
				UNION ALL SELECT 'she',N'欇' 
				UNION ALL SELECT 'shen',N'瘮' 
				UNION ALL SELECT 'sheng',N'賸' 
				UNION ALL SELECT 'shi',N'瓧' --鰘齛兙瓧 
				UNION ALL SELECT 'shou',N'鏉' 
				UNION ALL SELECT 'shu',N'虪' 
				UNION ALL SELECT 'shua',N'誜' 
				UNION ALL SELECT 'shuai',N'卛' 
				UNION ALL SELECT 'shuan',N'腨' 
				UNION ALL SELECT 'shuang',N'灀' 
				UNION ALL SELECT 'shui',N'睡' 
				UNION ALL SELECT 'shun',N'鬊' 
				UNION ALL SELECT 'shuo',N'鑠' 
				UNION ALL SELECT 'si',N'乺' --瀃螦乺 
				UNION ALL SELECT 'song',N'鎹' 
				UNION ALL SELECT 'sou',N'瘶' 
				UNION ALL SELECT 'su',N'鷫' 
				UNION ALL SELECT 'suan',N'算' 
				UNION ALL SELECT 'sui',N'鐩' 
				UNION ALL SELECT 'sun',N'潠' 
				UNION ALL SELECT 'suo',N'蜶' 
				UNION ALL SELECT 'ta',N'襨' --躢襨 
				UNION ALL SELECT 'tai',N'燤' 
				UNION ALL SELECT 'tan',N'賧' 
				UNION ALL SELECT 'tang',N'燙' 
				UNION ALL SELECT 'tao',N'畓' --討畓 
				UNION ALL SELECT 'te',N'蟘' 
				UNION ALL SELECT 'teng',N'朰' --霯唞朰 
				UNION ALL SELECT 'ti',N'趯' 
				UNION ALL SELECT 'tian',N'舚' 
				UNION ALL SELECT 'tiao',N'糶' 
				UNION ALL SELECT 'tie',N'餮' 
				UNION ALL SELECT 'ting',N'乭' --濎乭 
				UNION ALL SELECT 'tong',N'憅' 
				UNION ALL SELECT 'tou',N'透' 
				UNION ALL SELECT 'tu',N'鵵' 
				UNION ALL SELECT 'tuan',N'褖' 
				UNION ALL SELECT 'tui',N'駾' 
				UNION ALL SELECT 'tun',N'坉' 
				UNION ALL SELECT 'tuo',N'籜' 
				UNION ALL SELECT 'wa',N'韤' 
				UNION ALL SELECT 'wai',N'顡' 
				UNION ALL SELECT 'wan',N'贎' 
				UNION ALL SELECT 'wang',N'朢' 
				UNION ALL SELECT 'wei',N'躛' 
				UNION ALL SELECT 'wen',N'璺' 
				UNION ALL SELECT 'weng',N'齆' 
				UNION ALL SELECT 'wo',N'齷' 
				UNION ALL SELECT 'wu',N'鶩' 
				UNION ALL SELECT 'xi',N'衋' 
				UNION ALL SELECT 'xia',N'鏬' 
				UNION ALL SELECT 'xian',N'鼸' 
				UNION ALL SELECT 'xiang',N'鱌' 
				UNION ALL SELECT 'xiao',N'斆' 
				UNION ALL SELECT 'xie',N'躞' 
				UNION ALL SELECT 'xin',N'釁' 
				UNION ALL SELECT 'xing',N'臖' 
				UNION ALL SELECT 'xiong',N'敻' 
				UNION ALL SELECT 'xiu',N'齅' 
				UNION ALL SELECT 'xu',N'蓿' 
				UNION ALL SELECT 'xuan',N'贙' 
				UNION ALL SELECT 'xue',N'瀥' 
				UNION ALL SELECT 'xun',N'鑂' 
				UNION ALL SELECT 'ya',N'齾' 
				UNION ALL SELECT 'yan',N'灩' 
				UNION ALL SELECT 'yang',N'樣' 
				UNION ALL SELECT 'yao',N'鑰' 
				UNION ALL SELECT 'ye',N'岃' --鸈膶岃 
				UNION ALL SELECT 'yi',N'齸' 
				UNION ALL SELECT 'yin',N'檼' 
				UNION ALL SELECT 'ying',N'譍' 
				UNION ALL SELECT 'yo',N'喲' 
				UNION ALL SELECT 'yong',N'醟' 
				UNION ALL SELECT 'you',N'鼬' 
				UNION ALL SELECT 'yu',N'爩' 
				UNION ALL SELECT 'yuan',N'願' 
				UNION ALL SELECT 'yue',N'鸙' 
				UNION ALL SELECT 'yun',N'韻' 
				UNION ALL SELECT 'za',N'雥' 
				UNION ALL SELECT 'zai',N'縡' 
				UNION ALL SELECT 'zan',N'饡' 
				UNION ALL SELECT 'zang',N'臟' 
				UNION ALL SELECT 'zao',N'竈' 
				UNION ALL SELECT 'ze',N'稄' 
				UNION ALL SELECT 'zei',N'鱡' 
				UNION ALL SELECT 'zen',N'囎' 
				UNION ALL SELECT 'zeng',N'贈' 
				UNION ALL SELECT 'zha',N'醡' 
				UNION ALL SELECT 'zhai',N'瘵' 
				UNION ALL SELECT 'zhan',N'驏' 
				UNION ALL SELECT 'zhang',N'瞕' 
				UNION ALL SELECT 'zhao',N'羄' 
				UNION ALL SELECT 'zhe',N'鷓' 
				UNION ALL SELECT 'zhen',N'黮' 
				UNION ALL SELECT 'zheng',N'證' 
				UNION ALL SELECT 'zhi',N'豒' 
				UNION ALL SELECT 'zhong',N'諥' 
				UNION ALL SELECT 'zhou',N'驟' 
				UNION ALL SELECT 'zhu',N'鑄' 
				UNION ALL SELECT 'zhua',N'爪' 
				UNION ALL SELECT 'zhuai',N'跩' 
				UNION ALL SELECT 'zhuan',N'籑' 
				UNION ALL SELECT 'zhuang',N'戅' 
				UNION ALL SELECT 'zhui',N'鑆' 
				UNION ALL SELECT 'zhun',N'稕' 
				UNION ALL SELECT 'zhuo',N'籱' 
				UNION ALL SELECT 'zi',N'漬' 
				UNION ALL SELECT 'zong',N'縱' 
				UNION ALL SELECT 'zou',N'媰' 
				UNION ALL SELECT 'zu',N'謯' 
				UNION ALL SELECT 'zuan',N'攥' 
				UNION ALL SELECT 'zui',N'欈' 
				UNION ALL SELECT 'zun',N'銌' 
				UNION ALL SELECT 'zuo',N'咗'
			) Temp   
			WHERE Word >= @Word COLLATE Chinese_PRC_CS_AS_KS_WS   
			ORDER BY Word COLLATE Chinese_PRC_CS_AS_KS_WS ASC
		) 
		ELSE @Word END
	)
	SET @Index = @Index + 1  
    END
    RETURN @PinYin  
END  

GO
/****** Object:  UserDefinedFunction [dbo].[TransAreaNo]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--######################################################3
--实现功能 的函数 将037155611698 转换为 0371-155611698
--######################################################3
CREATE FUNCTION [dbo].[TransAreaNo]
(
	@TelephoneNo VARCHAR(50)
)

RETURNS VARCHAR(50)

AS
BEGIN

    DECLARE @Temp VARCHAR(50)

    set @TelephoneNo=right(@TelephoneNo,len(@TelephoneNo)-1)

    select @Temp=areano from dctelarea with(nolock)
    where areano like left(@TelephoneNo,len(areano))

    set @TelephoneNo=right(@TelephoneNo,len(@TelephoneNo)-len(@Temp))

	RETURN '0'+@Temp+'-'+@TelephoneNo
END


GO
/****** Object:  UserDefinedFunction [dbo].[Trim]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#############################333
--Trim函数
--#############################333
create FUNCTION [dbo].[Trim]
(
	@sText VARCHAR(MAX)
)
RETURNS VARCHAR(MAX)
AS
BEGIN
	RETURN LTRIM(RTRIM(@sText))
END




GO
/****** Object:  UserDefinedFunction [dbo].[TrimNULL]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#############################333
--Trim函数, 如果=‘’，则为null
--#############################333
CREATE FUNCTION [dbo].[TrimNULL]
(
	@sText VARCHAR(MAX)
)
RETURNS VARCHAR(MAX)
AS
BEGIN
	SET @sText = LTRIM(RTRIM(@sText))
	IF LEN(@sText) = 0
		SET @sText = NULL
	RETURN @sText
END





GO
/****** Object:  UserDefinedFunction [dbo].[TruncJobIDs]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[TruncJobIDs]
(
	@JobIds AS VARCHAR(MAX)
)
RETURNS VARCHAR(MAX)
AS
BEGIN
	DECLARE @i INT, @Num INT, @StrSource VARCHAR(MAX), @s VARCHAR(50)
	SELECT @StrSource = RTRIM(LTRIM(@JobIds))
	SELECT @i = CHARINDEX(',', @StrSource), @Num = 0, @s = ''

	IF @i = 0
		RETURN @StrSource

	WHILE @i >= 1 AND @Num < 3
	BEGIN
		IF LEFT(@StrSource, @i - 1) > '' 
			SELECT @s = @s + ',' + LEFT(@StrSource, @i - 1), @Num = @Num + 1

		SELECT @StrSource = SUBSTRING(@StrSource, @i + 1, LEN(@StrSource) - @i)
		SELECT @i = CHARINDEX(',', @StrSource)
	END

	IF @Num < 3 AND @StrSource <> '' AND @i = 0
		SELECT @s = @s + ',' + @StrSource
	
	IF LEFT(@s, 1) = ','
		SELECT @s = RIGHT(@s, LEN(@s) - 1)
	RETURN @s
END


GO
/****** Object:  UserDefinedFunction [dbo].[v2018_CheckHasCompleteCv]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--####################################################
--添加人：Peter
--添加时间：2018-8-23
--描述：检查个人是否有可以申请职位的家里
--####################################################
CREATE FUNCTION [dbo].[v2018_CheckHasCompleteCv](@PaMainID INT)
RETURNS BIT 
AS
BEGIN
	IF EXISTS(
		SELECT * 
		FROM cvMain WITH(NOLOCK) 
		WHERE paMainID = @PaMainID
			AND (
				(cvLevel LIKE '111__1%' AND VerifyResult = 1) OR
				(cvLevelEng LIKE '111__1%' AND VerifyResultEng = 1)
			)
	)
	BEGIN
		RETURN 1
	END
	ELSE
	BEGIN
		RETURN 0
	END
	RETURN 0
END



GO
/****** Object:  UserDefinedFunction [dbo].[v2018_SafeParam]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#######################################
--添加人：Lucifer
--添加时间：2018-7-27
--用途：过滤不安全的SQL语法
--#######################################
CREATE FUNCTION [dbo].[v2018_SafeParam]
(
	@sText VARCHAR(MAX)
)
RETURNS VARCHAR(MAX)
AS
BEGIN
	IF @sText IS NULL
		RETURN ''

--	SET @sText = REPLACE(@sText, 'and ','and&nbsp;')
--	SET @sText = REPLACE(@sText, 'or ','or&nbsp;')
--	SET @sText = REPLACE(@sText, 'exists','exists&nbsp;')	
--	SET @sText = REPLACE(@sText, 'union ','union&nbsp;')
--	SET @sText = REPLACE(@sText, '<','＜')
--	SET @sText = REPLACE(@sText, '>','＞')
--	SET @sText = REPLACE(@sText, 'from ','from&nbsp;')
--	SET @sText = REPLACE(@sText, 'select ','select&nbsp;')
	SET @sText = REPLACE(@sText, '','')
	SET @sText = REPLACE(@sText, 'script','scripｔ')
	SET @sText = REPLACE(@sText, 'src','srｃ')
	SET @sText = REPLACE(@sText, 'iframe','ｉframe')
	SET @sText = REPLACE(@sText, '--','——')
	SET @sText = REPLACE(@sText, 'delete ','delete&nbsp;')
	SET @sText = REPLACE(@sText, 'update ','update&nbsp;')
	SET @sText = REPLACE(@sText, 'delete	','delete&nbsp;')
	SET @sText = REPLACE(@sText, 'update	','update&nbsp;')
	SET @sText = REPLACE(@sText, 'delete
','delete&nbsp;')
	SET @sText = REPLACE(@sText, 'update
','update&nbsp;')
	SET @sText = REPLACE(@sText, 'create','create&nbsp;')
	SET @sText = REPLACE(@sText, 'drop','drop&nbsp;')
	SET @sText = REPLACE(@sText, 'insert','insert&nbsp;')
	SET @sText = REPLACE(@sText, 'chr(','chr(&nbsp;')
	SET @sText = REPLACE(@sText, 'master','master&nbsp;')
	SET @sText = REPLACE(@sText, 'net user','net&nbsp;user')
	SET @sText = REPLACE(@sText, 'declare','declare&nbsp;')
	SET @sText = REPLACE(@sText, 'char(','char(&nbsp;')
	SET @sText = REPLACE(@sText, 'mid(','mid(&nbsp;')
	SET @sText = REPLACE(@sText, 'xp_cmdshell','xp_cmdshell&nbsp;')
	SET @sText = REPLACE(@sText, 'exec','exec&nbsp;')
	SET @sText = REPLACE(@sText, 'truncate','truncate&nbsp;')
	SET @sText = REPLACE(@sText, 'ascii(','ascii(&nbsp;')
	SET @sText = REPLACE(@sText, 'substring(','substring(&nbsp;')
	SET @sText = REPLACE(@sText, 'localgroup ','localgroup&nbsp;')
	SET @sText = REPLACE(@sText, 'administrators ','administrators&nbsp;')
	SET @sText = REPLACE(@sText, 'dbcc','dbcc&nbsp;')
	SET @sText = REPLACE(@sText, 'checkdb(','checkdb(&nbsp;')
	SET @sText = REPLACE(@sText, 'sp_addsrvrolemember','p_addsrvrolemember&nbsp;')
	SET @sText = REPLACE(@sText, 'wscript.shell','wscript.shell&nbsp;')

	RETURN @sText
END
GO
/****** Object:  UserDefinedFunction [dbo].[v2018_SetIntNull]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--######################################################3
--选填的空值，需要改成Null
--######################################################3
CREATE FUNCTION [dbo].[v2018_SetIntNull]
(
	@str INT
)
RETURNS INT
AS
BEGIN
	IF @str = 0
		SET @str = NULL

	RETURN @str
END


GO
/****** Object:  UserDefinedFunction [dbo].[v2018_SetVarcharNull]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--######################################################3
--选填的空值，需要改成Null
--######################################################3
CREATE FUNCTION [dbo].[v2018_SetVarcharNull]
(
	@Str VARCHAR(MAX)
)
RETURNS VARCHAR(MAX)
AS
BEGIN
	SET @Str = dbo.v2018_SafeParam(@Str)
	IF LEN(ISNULL(@Str, '')) = 0
		SET @Str = NULL

	RETURN @Str
END
GO
/****** Object:  UserDefinedFunction [dbo].[VipJobNumber]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


--######################################3
--创建：Sean 2011-01-25
--贵宾会员的职位数量
--######################################3
CREATE FUNCTION [dbo].[VipJobNumber]
(
	@ID INT
)
RETURNS INT
AS
BEGIN
	DECLARE @Number AS INT, @Sn INT
	SELECT @Number = SUM(JobNumber) FROM caOrder WITH(NOLOCK)
	WHERE cpMainID = @ID
	AND BeginDate <= GETDATE() AND EndDate >= CONVERT(SMALLDATETIME, GETDATE())
	AND OpenDate IS NOT NULL

	SET @Sn = 5
	IF EXISTS(SELECT 'x' FROM cpMain WITH(NOLOCK) WHERE Id = @Id AND RealName = 1)
		SET @Sn = 10
	
	RETURN ISNULL(@Number, 0) + @Sn
END




GO
/****** Object:  UserDefinedFunction [dbo].[VipUserNumber]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


--######################################3
--创建：Sean 2011-01-25
--贵宾会员的用户数量
--######################################3
CREATE FUNCTION [dbo].[VipUserNumber]
(
	@ID INT
)
RETURNS INT
AS
BEGIN
	DECLARE @Number AS INT
	SELECT @Number = SUM(UserNumber) FROM caOrder WITH(NOLOCK)
	WHERE cpMainID = @ID
	AND BeginDate <= GETDATE() AND EndDate >= CONVERT(SMALLDATETIME, GETDATE())
	AND OpenDate IS NOT NULL
	RETURN ISNULL(@Number, 0) + 1
END







GO
/****** Object:  UserDefinedFunction [dbo].[WorkDateAdd]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE  Function [dbo].[WorkDateAdd]
(
	@Date DATETIME,
	@Hours DECIMAL(9, 2)
)
RETURNS DATETIME
AS
BEGIN
	----检查输入参数是否正确
	IF ISNULL(@Hours, 0) = 0 
		RETURN @Date
	IF @Date IS NULL
		RETURN NULL

	DECLARE @Minutes AS INT, @s AS VARCHAR(8), @StartDate AS DATETIME, @CostMinute AS INT
	----获取第一个工作日
	IF NOT EXISTS(SELECT 'x' FROM OaDb..WorkDate WITH(NOLOCK) WHERE WorkDate = CONVERT(VARCHAR(8), @Date, 112) AND WorkType = 1)
	BEGIN
		SELECT TOP 1 @S = a.WorkDate
		FROM OaDb..WorkDate a WITH(NOLOCK) 
		WHERE a.WorkDate > CONVERT(VARCHAR(8), @Date, 112) 
		AND WorkType = 1 
		ORDER BY a.WorkDate
	
		SET @StartDate = @S
	END
	ELSE
		SET @StartDate = CONVERT(DATETIME, CONVERT(VARCHAR(10), @Date, 120))

	----如果当天是工作日，则计算是已运行的工作时间
	IF CONVERT(VARCHAR(8), @Date, 112) = CONVERT(VARCHAR(8), @StartDate, 112)
	BEGIN
		SET @Minutes = DATEPART(HOUR, @Date) * 100 + DATEPART(MINUTE, @Date)
		
		IF @Minutes < 830
			SELECT @CostMinute = 0
		ELSE IF @Minutes < 1201
			SELECT @CostMinute = DATEDIFF(MINUTE, dbo.MergeDate(@Date, 830), @Date)
		ELSE IF @Minutes < 1300
			SELECT @CostMinute = 210
		ELSE IF @Minutes < 1731
			SELECT @CostMinute = DATEDIFF(MINUTE, dbo.MergeDate(@Date, 1300), @Date) + 210
		ELSE		
			SELECT @CostMinute = 480
	END
	ELSE
		SET @CostMinute = 0
	
	SET @Minutes = @Hours * 60 + @CostMinute	----从第一个工作日开始,需要工作的分钟数

	DECLARE @DayInterval AS INT,	--除8等于天数
		@MinuteLast AS INT,
		@ExpireDate AS DATETIME,
		@TempDate AS DATETIME

	SET @DayInterval = @Minutes / 480
	SELECT @MinuteLast = @Minutes - @DayInterval * 480
	SET @DayInterval = @DayInterval + 1

	DECLARE @t AS TABLE(
		ID INT IDENTITY(1,1) NOT NULL,
		WorkDate VARCHAR(8)
	)
	----函数中无法使用临时表和(),所以只有使用表变量
	INSERT INTO @t(WorkDate)
	SELECT TOP (@DayInterval) WorkDate
	FROM OaDb..WorkDate WITH(NOLOCK) 
	WHERE WorkType = 1
	AND WorkDate >= CONVERT(VARCHAR(8), @StartDate, 112)
	ORDER BY WorkDate

	SELECT TOP 1 @S = WorkDate FROM @t ORDER BY ID DESC

	SET @ExpireDate = @S
	IF @MinuteLast > 210
		SET @MinuteLast = @MinuteLast + 60

	SET @ExpireDate = DATEADD(MINUTE, @MinuteLast, dbo.MergeDate(@ExpireDate, 830)) 

	RETURN @ExpireDate
END

GO
/****** Object:  UserDefinedFunction [dbo].[ZhaopinRegionToOurID]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--sean 2013-6-25
CREATE FUNCTION [dbo].[ZhaopinRegionToOurID]
(
	@ZhaopinRegin VARCHAR(50)
)
RETURNS VARCHAR(6)
AS
BEGIN
	DECLARE @Id VARCHAR(6), @Id2 VARCHAR(6), @Des VARCHAR(20)
	SELECT TOP 1 @id = ID, @Des = DESCRIPTION
	FROM dcRegion WHERE Description LIKE LEFT(@ZhaopinRegin, 2) + '%'
	AND GRADE = 1
	ORDER BY ID
	
	SET @Des = REPLACE(@Des, '市', '')
	SET @Des = REPLACE(@Des, '省', '')
	SET @ZhaopinRegin = REPLACE(@ZhaopinRegin, @Des, '')
	
	SELECT TOP 1 @id2 = ID
	FROM dcRegion 
	WHERE Description LIKE '%' + RIGHT(@ZhaopinRegin, 2) + '%'
	AND ID LIKE @Id + '%'
	ORDER BY Id

	IF @Id2 > ''
		RETURN @ID2
	ELSE
		RETURN @ID
	RETURN ''
END

GO
/****** Object:  Table [dbo].[ManagerUser]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ManagerUser](
	[id] [smallint] NOT NULL,
	[UserName] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Password] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[name] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[name_eng] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[OpenName] [tinyint] NULL,
	[superior] [smallint] NULL,
	[title] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[roleid] [int] NOT NULL,
	[deptid] [int] NOT NULL,
	[adddate] [smalldatetime] NOT NULL,
	[logincount] [int] NOT NULL,
	[lastlogindate] [smalldatetime] NULL,
	[type] [smallint] NULL,
	[email] [nvarchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[photo] [nvarchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[introduce] [nvarchar](200) COLLATE Chinese_PRC_CI_AS NULL,
	[status] [smallint] NOT NULL,
	[loginstatus] [smallint] NULL,
	[localrate] [numeric](18, 2) NULL,
	[kpi_manager] [tinyint] NULL,
	[km] [smallint] NULL,
	[km_score] [smallint] NULL,
	[ie] [smallint] NULL,
	[mobile] [varchar](11) COLLATE Chinese_PRC_CI_AS NULL,
	[cookies] [varchar](16) COLLATE Chinese_PRC_CI_AS NULL,
	[rtxstatus] [tinyint] NULL,
	[ec] [smallint] NULL,
	[consultantnum_up] [int] NOT NULL,
	[consultantnum] [int] NOT NULL,
	[consultantnum_noyingye] [int] NOT NULL,
	[consultantnum_up_new] [int] NULL,
	[consultantnum_new] [int] NULL,
	[HRKpiPostId] [int] NULL,
	[HRKpiPostGrade] [tinyint] NULL,
	[consultantnum_quota] [int] NULL,
	[consultantnum_release] [int] NULL,
	[consultantnum_release_lastmonth] [int] NULL,
	[office] [tinyint] NULL,
	[rtxTime] [datetime] NOT NULL,
	[SOLStatus] [tinyint] NULL,
	[SOLTime] [datetime] NULL,
	[LoginIp] [varchar](15) COLLATE Chinese_PRC_CI_AS NULL,
	[ActiveTime] [smalldatetime] NULL,
	[CompanyQQ] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL,
	[SalesLevel] [smallint] NULL,
	[WeiXinNo] [varchar](30) COLLATE Chinese_PRC_CI_AS NULL,
 CONSTRAINT [PK_manageruser] PRIMARY KEY CLUSTERED 
(
	[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 50) ON [PRIMARY]
) ON [PRIMARY]

GO
/****** Object:  View [dbo].[viewBsAskUSer]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE VIEW [dbo].[viewBsAskUSer]
AS
SELECT     id, name
FROM         dbo.ManagerUser
WHERE     (id BETWEEN 160 AND 199)

GO
/****** Object:  Table [dbo].[dcSubSite]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[dcSubSite](
	[ID] [smallint] NOT NULL,
	[ProvinceID] [tinyint] NOT NULL,
	[SubSiteName] [nvarchar](20) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[SubSIteCity] [nvarchar](10) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[SubSiteUrl] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[EmailSite] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[Title] [nvarchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[MetaAuthor] [nvarchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[MetaDescription] [nvarchar](300) COLLATE Chinese_PRC_CI_AS NULL,
	[Keywords] [nvarchar](200) COLLATE Chinese_PRC_CI_AS NULL,
	[SeoBottom] [nvarchar](500) COLLATE Chinese_PRC_CI_AS NULL,
	[pr] [tinyint] NULL,
	[SearchRegionID] [smallint] NULL,
	[T1] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL,
	[T2] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL,
	[T3] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL,
	[T4] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL,
	[T5] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL,
	[T6] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL,
	[T7] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL,
	[SubGroup_Out] [smallint] NULL,
	[InternalIp] [varchar](15) COLLATE Chinese_PRC_CI_AS NULL,
	[EmailTester] [smallint] NULL,
	[MinInfoAmount] [tinyint] NULL,
	[MaxInfoAmount] [decimal](4, 1) NULL,
	[EmailUser] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL,
	[EmailTitle_Company] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[EmailTitle_Person] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[EmailProfile] [varchar](30) COLLATE Chinese_PRC_CI_AS NULL,
	[IsMainSite] [bit] NULL,
	[MainSIteID] [smallint] NULL,
	[SecondSiteName] [nvarchar](20) COLLATE Chinese_PRC_CI_AS NULL,
	[IsSecond] [tinyint] NULL,
	[PinYin] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL,
	[SecondSite] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
 CONSTRAINT [PK_dcSubSite] PRIMARY KEY CLUSTERED 
(
	[ID] 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].[version]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE VIEW [dbo].[version]
AS
SELECT     ID AS ph_id, ID, ProvinceID AS province_id, SubSiteName AS websitename, SubSIteCity AS VersionName, SubSiteUrl AS VersionDomain, Title, 
                      MetaAuthor AS Meta_Author, MetaDescription AS Meta_Description, SeoBottom AS Bottom, Keywords, pr, SearchRegionID, SubGroup_Out, T1, T2, T3, T4, T5, T6, 
                      T7
FROM         dbo.dcSubSite

GO
/****** Object:  Table [dbo].[Link]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Link](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[Text] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[Link] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL,
	[AnnounceDate] [smalldatetime] NOT NULL,
	[VersionId] [int] NOT NULL,
	[Power] [int] NOT NULL,
	[Type] [smallint] NULL,
	[Filename] [varchar](1000) COLLATE Chinese_PRC_CI_AS NULL,
	[Valid] [smallint] NOT NULL,
	[LinkMan] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[Telephone] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[Email] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[PowerAll] [int] NOT NULL,
	[Vision] [smallint] NOT NULL,
	[Our] [bit] NOT NULL,
	[Pr] [tinyint] NULL,
	[OutLink] [int] NULL,
	[LinkPage] [varchar](500) COLLATE Chinese_PRC_CI_AS NULL,
	[Authority] [tinyint] NULL,
	[Correlation] [tinyint] NULL,
	[Score] [numeric](5, 3) NOT NULL,
	[Orderby] [smallint] NOT NULL,
	[NoFollow] [bit] NOT NULL,
	[Deleted] [smallint] NOT NULL,
	[DeleteDate] [smalldatetime] NULL,
	[Baidu] [smallint] NULL,
	[BaiduDate] [smalldatetime] NULL,
	[LinkOur] [smallint] NULL,
	[ErrorNum] [smallint] NOT NULL,
	[BaiduRank] [int] NULL,
	[ManagerUserId] [smallint] NULL,
	[Method] [smallint] NULL,
	[BaiduIncluded] [int] NULL,
	[CheckVersionId] [int] NULL,
	[Category] [int] NULL,
	[deleteman] [smallint] NULL,
	[SnapshotDate] [smalldatetime] NULL,
	[OurKeyWord] [nvarchar](10) COLLATE Chinese_PRC_CI_AS NULL,
	[BaiduSort] [tinyint] NULL,
	[IsNoFollow] [bit] NULL,
	[BaiduWeight] [tinyint] NULL,
 CONSTRAINT [PK_Link] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Market]
) ON [Market]

GO
/****** Object:  View [dbo].[viewLinkAbnormalAll]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE VIEW [dbo].[viewLinkAbnormalAll]
AS
SELECT     LEFT(b.ID, 2) AS ProvinceID, b.VersionDomain, b.VersionName, a.VersionId, a.Text, a.Link, a.LinkPage, a.Baidu, a.LinkOur, a.Id, a.Pr, a.OutLink, 
                      a.BaiduRank, a.BaiduIncluded, a.BaiduDate, a.Deleted, a.Method
FROM         dbo.Link AS a INNER JOIN
                      dbo.version AS b ON a.VersionId = b.ID AND a.Valid = 1 AND a.Deleted = 0 AND a.Type = 1 AND a.Method = 1
WHERE     (a.BaiduIncluded = 0) OR
                      (a.LinkOur < 1) OR
                      (a.LinkOur > 2) OR
                      (a.LinkOur < 1) OR
                      (a.LinkOur > 2) OR
                      (a.OutLink = 0) OR
                      (ISNULL(a.SnapshotDate, '2000-1-1') < '2000-1-2')

GO
/****** Object:  View [dbo].[viewLinkAbnormal]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE VIEW [dbo].[viewLinkAbnormal]
AS
SELECT     LEFT(b.ID, 2) AS ProvinceID, b.VersionDomain, b.VersionName, a.VersionId, a.Text, a.Link, a.LinkPage, a.Baidu, a.LinkOur, a.Id, a.Pr, a.OutLink, 
                      a.BaiduRank, a.BaiduIncluded, a.BaiduDate, a.Deleted, a.Method
FROM         dbo.Link AS a INNER JOIN
                      dbo.version AS b ON a.VersionId = b.ID AND a.Valid = 1 AND a.Deleted = 0 AND a.Type = 1 AND a.Method = 1
WHERE     (a.BaiduIncluded = 0) OR
                      (a.LinkOur < 1) OR
                      (a.LinkOur > 2) OR
                      (a.LinkOur < 1) OR
                      (a.LinkOur > 2) OR
                      (a.OutLink = 0)

GO
/****** Object:  Table [dbo].[caOrder]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[caOrder](
	[ID] [int] IDENTITY(1,1) NOT FOR REPLICATION NOT NULL,
	[cpMainID] [int] NOT NULL,
	[ProvinceID] [smallint] NOT NULL,
	[OrderStatus] [tinyint] NOT NULL,
	[dcFeeDetailID] [int] NULL,
	[ServiceType] [tinyint] NULL,
	[PlaceWeek] [tinyint] NULL,
	[PayMethod] [tinyint] NOT NULL,
	[OrderType] [tinyint] NOT NULL,
	[Accounts] [numeric](18, 2) NOT NULL,
	[Paid] [numeric](18, 2) NOT NULL,
	[Balance] [int] NULL,
	[ActiveQuota] [smallint] NULL,
	[RemainQuota] [smallint] NULL,
	[UserNumber] [tinyint] NULL,
	[JobNumber] [smallint] NULL,
	[MainOrderID] [int] NULL,
	[LinkMan] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Telephone] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[LinkRemark] [nvarchar](1000) COLLATE Chinese_PRC_CI_AS NULL,
	[NeedInvoice] [bit] NULL,
	[MailAddress] [nvarchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[InvoiceTitle] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[Recipient] [nvarchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[Zip] [char](6) COLLATE Chinese_PRC_CI_AS NULL,
	[PostTelephone] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[FaxFile] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[CompanyName] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[RemittanceFile] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL,
	[RemittanceDate] [smalldatetime] NULL,
	[ReceiveMan] [smallint] NULL,
	[ReceiveDate] [smalldatetime] NULL,
	[SmsMobileNumber] [tinyint] NOT NULL,
	[InvoiceMonth] [char](6) COLLATE Chinese_PRC_CI_AS NULL,
	[InvoiceCompany] [smallint] NULL,
	[InvoiceConfirmDate] [smalldatetime] NULL,
	[InvoiceConfirmMan] [smallint] NULL,
	[InvoiceAskDate] [smalldatetime] NULL,
	[ContractFile] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[Manageruserid] [smallint] NULL,
	[IsDeleted] [bit] NULL,
	[DeletedMan] [smallint] NULL,
	[DeletedDate] [smalldatetime] NULL,
	[OpenMan] [smallint] NULL,
	[OpenDate] [smalldatetime] NULL,
	[BeginDate] [smalldatetime] NULL,
	[EndDate] [smalldatetime] NULL,
	[AddDate] [smalldatetime] NOT NULL,
	[IsBackSubmit] [bit] NOT NULL,
	[Tariff] [varchar](30) COLLATE Chinese_PRC_CI_AS NULL,
	[RegisterAddress] [nvarchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[RegisterTel] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[BankName] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[BankAccount] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[InvoiceReConfirmDate] [smalldatetime] NULL,
	[InvoiceReConfirmMan] [smallint] NULL,
	[PaidCoin] [int] NULL,
	[PaidPoint] [int] NULL,
	[CancelReason] [nvarchar](70) COLLATE Chinese_PRC_CI_AS NULL,
	[GivePoint] [int] NULL,
	[SmsQuota] [int] NULL,
	[RemainSmsQuota] [int] NULL,
	[jobRefreshQuota] [int] NULL,
	[remainJobRefreshQuota] [int] NULL,
	[isCvAllocate] [bit] NULL,
	[invoiceconfirmFile] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL,
	[isdocopen] [tinyint] NULL,
	[AssessReportQuota] [int] NULL,
	[RemainAssessReportQuota] [int] NULL,
 CONSTRAINT [PK_caOrder] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [CP]
) ON [CP]

GO
/****** Object:  Table [dbo].[cpMain]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[cpMain](
	[ID] [int] IDENTITY(1,1) NOT FOR REPLICATION NOT NULL,
	[dcProvinceID] [tinyint] NOT NULL,
	[RegDate] [smalldatetime] NOT NULL,
	[RegisterIP] [varchar](39) COLLATE Chinese_PRC_CI_AS NULL,
	[RegisterMode] [tinyint] NOT NULL,
	[AddMan] [smallint] NULL,
	[IsDefaultPassword] [bit] NOT NULL,
	[Name] [varchar](100) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[ShortName] [varchar](40) COLLATE Chinese_PRC_CI_AS NULL,
	[dcCompanyKindID] [smallint] NULL,
	[dcCompanySizeID] [tinyint] NULL,
	[dcRegionID] [varchar](6) COLLATE Chinese_PRC_CI_AS NULL,
	[Address] [nvarchar](60) COLLATE Chinese_PRC_CI_AS NULL,
	[Zip] [char](6) COLLATE Chinese_PRC_CI_AS NULL,
	[MapBarID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[HomePage] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[Brief] [varchar](6000) COLLATE Chinese_PRC_CI_AS NULL,
	[HasLicence] [bit] NOT NULL,
	[HasLogo] [bit] NOT NULL,
	[HasVisual] [bit] NOT NULL,
	[ConsultantID] [smallint] NULL,
	[ConsultantDate] [smalldatetime] NULL,
	[DailyGiftQuota] [tinyint] NOT NULL,
	[UnlimitedDate] [smalldatetime] NOT NULL,
	[BalanceDate] [smalldatetime] NOT NULL,
	[Balance] [smallint] NOT NULL,
	[ResumeQuota] [smallint] NOT NULL,
	[MaxUserNumber] [tinyint] NOT NULL,
	[MaxJobNumber] [smallint] NULL,
	[Quality] [tinyint] NULL,
	[SendFeeCount] [tinyint] NULL,
	[IsAgent] [bit] NOT NULL,
	[IsLimitLogin] [tinyint] NOT NULL,
	[Islock] [bit] NOT NULL,
	[IsDelete] [bit] NOT NULL,
	[MemberType] [tinyint] NOT NULL,
	[Description] [nvarchar](500) COLLATE Chinese_PRC_CI_AS NULL,
	[VerifyResult] [tinyint] NOT NULL,
	[BlockCount] [smallint] NOT NULL,
	[VerifyCount] [int] NOT NULL,
	[LoginCount] [int] NOT NULL,
	[JobNumber] [smallint] NOT NULL,
	[ViewNumber] [int] NOT NULL,
	[RefreshDate] [smalldatetime] NULL,
	[LastModifyDate] [smalldatetime] NULL,
	[RegCapital] [int] NULL,
	[dcSubSiteID] [smallint] NULL,
	[LastLoginDate] [smalldatetime] NULL,
	[LastLoginIP] [varchar](31) COLLATE Chinese_PRC_CI_AS NULL,
	[Valid]  AS (case when isnull([Address],'')='' OR [IsDelete]=(1) OR [IsLimitLogin]=(9) OR [VerifyResult]=(10) OR [VerifyCount]=(0) then (0) else (1) end) PERSISTED NOT NULL,
	[PerfectDate] [smalldatetime] NULL,
	[Lng] [decimal](8, 5) NULL,
	[Lat] [decimal](8, 5) NULL,
	[SecondId] [varchar](10) COLLATE Chinese_PRC_CI_AS NULL,
	[IsProtect] [bit] NULL,
	[RemainPoint] [int] NULL,
	[RemainCoin] [int] NULL,
	[RegisterSourceId] [int] NULL,
	[MemberDate] [smalldatetime] NULL,
	[ReplyRate] [decimal](18, 3) NULL,
	[H5Mode] [tinyint] NULL,
	[RealName] [tinyint] NULL,
	[CommentNumber] [smallint] NULL,
	[InterViewNumber] [smallint] NULL,
	[LogoFile] [varchar](90) COLLATE Chinese_PRC_CI_AS NULL,
	[AutoReplyConfirm] [smalldatetime] NULL,
	[SocialCreditCode] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[RealNameLimit] [nvarchar](200) COLLATE Chinese_PRC_CI_AS NULL,
 CONSTRAINT [PK_cpMain] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [CP]
) ON [CP]

GO
/****** Object:  View [dbo].[vCpmain]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--修改;harry 2017-6-6 增加短信剩余量RemainSmsQuota,SmsQuota配额
--修改;harry 2017-10-23 增加职位刷新数配额
--修改：harry 2018-9-21 增加人才测评
CREATE VIEW [dbo].[vCpmain]
AS
SELECT ID, HasLicence, MemberType,
	(SELECT MAX(EndDate) AS Expr1
	FROM dbo.caOrder WITH (NOLOCK)
	WHERE (cpMainID = dbo.cpMain.ID) AND (OrderType = 8) AND (OpenDate IS NOT NULL) AND (EndDate > GETDATE()) AND (IsDeleted = 0)) 
	AS VipDate,
	(SELECT ISNULL(SUM(ActiveQuota), 0) AS Expr1
	FROM dbo.caOrder AS caOrder_2 WITH (NOLOCK)
	WHERE (cpMainID = dbo.cpMain.ID) AND (OrderType IN (8, 9, 10, 11)) AND (OpenDate IS NOT NULL) AND (BeginDate < GETDATE()) AND 
	(EndDate > GETDATE()) AND (IsDeleted = 0)) AS ActiveQuota,
	(SELECT ISNULL(SUM(RemainQuota), 0) AS Expr1
	FROM dbo.caOrder AS caOrder_1 WITH (NOLOCK)
	WHERE (cpMainID = dbo.cpMain.ID) AND (OrderType IN (8, 9, 10, 11)) AND (OpenDate IS NOT NULL) AND (BeginDate < GETDATE()) AND 
	(EndDate > GETDATE()) AND (IsDeleted = 0)) AS RemainQuota, 
	(SELECT ISNULL(SUM(RemainSmsQuota), 0) AS Expr1
	FROM dbo.caOrder AS caOrder_3 WITH (NOLOCK)
	WHERE (cpMainID = dbo.cpMain.ID) AND (OrderType IN (8,14)) AND (OpenDate IS NOT NULL) AND (BeginDate < GETDATE()) AND 
	(EndDate > GETDATE()) AND (IsDeleted = 0)) AS RemainSmsQuota,
	(SELECT ISNULL(SUM(SmsQuota), 0) AS Expr1
	FROM dbo.caOrder AS caOrder_4 WITH (NOLOCK)
	WHERE (cpMainID = dbo.cpMain.ID) AND (OrderType IN (8,14)) AND (OpenDate IS NOT NULL) AND (BeginDate < GETDATE()) AND 
	(EndDate > GETDATE()) AND (IsDeleted = 0)) AS SmsQuota,
	(SELECT ISNULL(SUM(remainJobRefreshQuota), 0) AS Expr1
	FROM dbo.caOrder AS caOrder_5 WITH (NOLOCK)
	WHERE (cpMainID = dbo.cpMain.ID) AND (OrderType IN (8,15)) AND (OpenDate IS NOT NULL) AND (BeginDate < GETDATE()) AND 
	(EndDate > GETDATE()) AND (IsDeleted = 0)) AS remainJobRefreshQuota,
	(SELECT ISNULL(SUM(jobRefreshQuota), 0) AS Expr1
	FROM dbo.caOrder AS caOrder_6 WITH (NOLOCK)
	WHERE (cpMainID = dbo.cpMain.ID) AND (OrderType IN (8,15)) AND (OpenDate IS NOT NULL) AND (BeginDate < GETDATE()) AND 
	(EndDate > GETDATE()) AND (IsDeleted = 0)) AS jobRefreshQuota,
	(SELECT ISNULL(SUM(AssessReportQuota), 0) AS Expr1
	FROM dbo.caOrder AS caOrder_7 WITH (NOLOCK)
	WHERE (cpMainID = dbo.cpMain.ID) AND (OrderType IN (8,25)) AND (OpenDate IS NOT NULL) AND (BeginDate < GETDATE()) AND 
	(EndDate > GETDATE()) AND (IsDeleted = 0)) AS AssessReportQuota,
	(SELECT ISNULL(SUM(RemainAssessReportQuota), 0) AS Expr1
	FROM dbo.caOrder AS caOrder_8 WITH (NOLOCK)
	WHERE (cpMainID = dbo.cpMain.ID) AND (OrderType IN (8,25)) AND (OpenDate IS NOT NULL) AND (BeginDate < GETDATE()) AND 
	(EndDate > GETDATE()) AND (IsDeleted = 0)) AS RemainAssessReportQuota,
	MaxJobNumber, MaxUserNumber, UnlimitedDate, Balance, BalanceDate, ResumeQuota, IsAgent
FROM dbo.cpMain WITH (NOLOCK)
WHERE (IsDelete = 0) AND (IsLimitLogin < 9)

GO
/****** Object:  Table [dbo].[paMain]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[paMain](
	[ID] [int] IDENTITY(1,1) NOT FOR REPLICATION NOT NULL,
	[UserName] [varchar](50) COLLATE Chinese_PRC_CS_AS NOT NULL,
	[UserNameLower]  AS (CONVERT([varchar](50),[UserName] collate CHINESE_PRC_CI_AS,(0))) PERSISTED,
	[Password] [varchar](60) COLLATE Chinese_PRC_CI_AS NULL,
	[IsDefaultPassword] [bit] NOT NULL,
	[dcProvinceID] [tinyint] NOT NULL,
	[RegisterIP] [varchar](31) COLLATE Chinese_PRC_CI_AS NULL,
	[RegisterMode] [tinyint] NOT NULL,
	[AddMan] [smallint] NULL,
	[Name] [nvarchar](6) COLLATE Chinese_PRC_CI_AS NULL,
	[NameEng] [varchar](30) COLLATE Chinese_PRC_CI_AS NULL,
	[Email] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Gender] [bit] NULL,
	[BirthDay] [int] NULL,
	[LivePlace] [varchar](6) COLLATE Chinese_PRC_CI_AS NULL,
	[AccountPlace] [varchar](6) COLLATE Chinese_PRC_CI_AS NULL,
	[GrowPlace] [varchar](6) COLLATE Chinese_PRC_CI_AS NULL,
	[Mobile] [varchar](13) COLLATE Chinese_PRC_CI_AS NULL,
	[OnlineContact] [tinyint] NULL,
	[OnlineContactNo] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[Homepage] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL,
	[Marriage] [tinyint] NULL,
	[Nation] [tinyint] NULL,
	[Height] [tinyint] NULL,
	[dcCareerStatus] [tinyint] NULL,
	[HasPhoto] [tinyint] NULL,
	[HideConditions] [nvarchar](500) COLLATE Chinese_PRC_CI_AS NULL,
	[BlockCount] [int] NOT NULL,
	[VerifyCount] [int] NOT NULL,
	[LastLoginDate] [datetime] NULL,
	[TotalLoginNum] [int] NOT NULL,
	[LastModifyDate] [smalldatetime] NULL,
	[AddDate] [smalldatetime] NOT NULL,
	[dcSubSiteID] [smallint] NULL,
	[MobileRegion] [varchar](6) COLLATE Chinese_PRC_CI_AS NULL,
	[IsReceiveSms] [bit] NULL,
	[PerfectDate] [smalldatetime] NULL,
	[PlainPassword] [varchar](40) COLLATE Chinese_PRC_CI_AS NULL,
	[MobileVerifyDate] [smalldatetime] NULL,
	[EmailVerifyDate] [smalldatetime] NULL,
	[RegisterFrom] [tinyint] NULL,
	[SpreadDate] [smalldatetime] NULL,
	[RegisterType] [tinyint] NULL,
	[IsAppNotice] [bit] NULL,
	[IsEmailNotice] [bit] NULL,
	[IsWeixinNotice] [bit] NULL,
	[IsAppJobFinder] [bit] NULL,
	[IsEmailJobFinder] [bit] NULL,
	[IsWeiXinJobFinder] [bit] NULL,
	[IsUseYourFood] [bit] NULL,
	[dcMapPlaceID] [int] NULL,
 CONSTRAINT [PK_paMain] PRIMARY KEY NONCLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [CV],
 CONSTRAINT [IX_paMain_Username] UNIQUE NONCLUSTERED 
(
	[UserName] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
) ON [CV]

GO
/****** Object:  Table [dbo].[Job]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Job](
	[ID] [int] IDENTITY(1,1) NOT FOR REPLICATION NOT NULL,
	[cpMainID] [int] NOT NULL,
	[caMainID] [int] NOT NULL,
	[Name] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[dcJobTypeID] [smallint] NOT NULL,
	[dcJobTypeIDMinor] [smallint] NULL,
	[NeedNumber] [tinyint] NULL,
	[dcSalaryID] [tinyint] NOT NULL,
	[EmployType] [tinyint] NOT NULL,
	[dcRegionID] [varchar](6) COLLATE Chinese_PRC_CI_AS NULL,
	[MapBarID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[Responsibility] [varchar](max) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Demand] [varchar](max) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[dcEducationID] [tinyint] NOT NULL,
	[MinExperience] [tinyint] NOT NULL,
	[MinAge] [tinyint] NULL,
	[MaxAge] [tinyint] NULL,
	[EMailSendFreq] [tinyint] NOT NULL,
	[EMailSendNumber] [tinyint] NULL,
	[LastEmailDate] [smalldatetime] NULL,
	[DisplayNo] [smallint] NOT NULL,
	[IssueDate] [smalldatetime] NULL,
	[IssueEnd] [smalldatetime] NULL,
	[IsDelete] [bit] NOT NULL,
	[ApplyNumber] [int] NOT NULL,
	[ViewNumber] [int] NOT NULL,
	[AddDate] [smalldatetime] NOT NULL,
	[RefreshDate] [smalldatetime] NULL,
	[LastModifyDate] [smalldatetime] NOT NULL,
	[Valid] [bit] NOT NULL,
	[Lng] [decimal](8, 5) NULL,
	[Lat] [decimal](8, 5) NULL,
	[FilterMaxDegree] [tinyint] NULL,
	[FilterMinDegree] [tinyint] NULL,
	[FilterMaxWorkYear] [tinyint] NULL,
	[FilterMinWorkYear] [tinyint] NULL,
	[FilterMaxAge] [tinyint] NULL,
	[FilterMinAge] [tinyint] NULL,
	[FilterGender] [varchar](1) COLLATE Chinese_PRC_CI_AS NULL,
	[FilterJobRegion] [varchar](6) COLLATE Chinese_PRC_CI_AS NULL,
	[FilterCvMainID] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL,
	[ForwardEmail] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[Promotion] [nvarchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[Welfare1] [bit] NULL,
	[Welfare2] [bit] NULL,
	[Welfare3] [bit] NULL,
	[Welfare4] [bit] NULL,
	[Welfare5] [bit] NULL,
	[Welfare6] [bit] NULL,
	[Welfare7] [bit] NULL,
	[Welfare8] [bit] NULL,
	[Welfare9] [bit] NULL,
	[Welfare10] [bit] NULL,
	[Welfare11] [bit] NULL,
	[Welfare12] [bit] NULL,
	[Welfare13] [bit] NULL,
	[Welfare14] [bit] NULL,
	[Welfare15] [bit] NULL,
	[Welfare16] [bit] NULL,
	[Welfare17] [bit] NULL,
	[Welfare18] [bit] NULL,
	[SecondId] [varchar](12) COLLATE Chinese_PRC_CI_AS NULL,
	[dcSalaryIdMax] [tinyint] NULL,
	[Negotiable] [bit] NULL,
	[Welfare19] [bit] NULL,
 CONSTRAINT [PK_Job] PRIMARY KEY NONCLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [CP]
) ON [CP] TEXTIMAGE_ON [CP]

GO
/****** Object:  Index [IX_Job_cpMainID]    Script Date: 2018/9/25 12:40:11 ******/
CREATE CLUSTERED INDEX [IX_Job_cpMainID] ON [dbo].[Job]
(
	[cpMainID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [CP]
GO
/****** Object:  Table [dbo].[exJobApply]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[exJobApply](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[JobID] [int] NOT NULL,
	[cvMainID] [int] NOT NULL,
	[ApplyMessage] [nvarchar](2000) COLLATE Chinese_PRC_CI_AS NULL,
	[AddDate] [smalldatetime] NOT NULL,
	[CompanyDeleted] [bit] NOT NULL,
	[CompanyDeleteDate] [smalldatetime] NULL,
	[PersonDeleted] [bit] NOT NULL,
	[Reply] [tinyint] NOT NULL,
	[ReplyDate] [smalldatetime] NULL,
	[IsPassed] [bit] NOT NULL,
	[IsTempInsert] [bit] NULL,
	[RecruitmentId] [int] NULL,
	[IsFilter] [bit] NULL,
	[isMatched] [bit] NULL,
	[ViewDate] [smalldatetime] NULL,
	[RemindDate] [datetime] NULL,
	[IsDeleted] [bit] NULL,
	[ReplyReason] [nvarchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[CpRemindViewDate] [datetime] NULL,
	[CheckMan] [smallint] NULL,
	[CheckDate] [smalldatetime] NULL,
 CONSTRAINT [PK_exJobApply] PRIMARY KEY NONCLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Interaction]
) ON [Interaction]

GO
/****** Object:  Table [dbo].[cvMain]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[cvMain](
	[ID] [int] IDENTITY(1,1) NOT FOR REPLICATION NOT NULL,
	[paMainID] [int] NOT NULL,
	[Name] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[Degree] [tinyint] NULL,
	[dcMajorID] [smallint] NULL,
	[LastJobTypeID] [smallint] NULL,
	[LastIndustryID] [smallint] NULL,
	[JobName] [nvarchar](20) COLLATE Chinese_PRC_CI_AS NULL,
	[SubNodeNum] [tinyint] NULL,
	[RelatedWorkYears] [tinyint] NULL,
	[EmployType] [tinyint] NULL,
	[dcSalaryID] [tinyint] NULL,
	[IsNegotiable] [bit] NOT NULL,
	[Speciality] [varchar](max) COLLATE Chinese_PRC_CI_AS NULL,
	[SpecialityEng] [varchar](max) COLLATE Chinese_PRC_CI_AS NULL,
	[Attachment] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[WordFilename] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[cvType] [tinyint] NOT NULL,
	[IsNameHidden] [bit] NOT NULL,
	[IscvHidden] [bit] NOT NULL,
	[isOpen] [bit] NOT NULL,
	[cvLevel] [char](10) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[cvLevelEng] [char](10) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[VerifyResult] [tinyint] NOT NULL,
	[VerifyResultEng] [tinyint] NOT NULL,
	[Valid] [tinyint] NULL,
	[ViewNumber] [int] NOT NULL,
	[RefreshDate] [smalldatetime] NOT NULL,
	[IsVerified] [int] NULL,
	[SecondId] [varchar](10) COLLATE Chinese_PRC_CI_AS NULL,
 CONSTRAINT [PK_cvMain] PRIMARY KEY NONCLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [CV]
) ON [CV] TEXTIMAGE_ON [CV]

GO
/****** Object:  Index [IX_cvMain_paMainID]    Script Date: 2018/9/25 12:40:11 ******/
CREATE CLUSTERED INDEX [IX_cvMain_paMainID] ON [dbo].[cvMain]
(
	[paMainID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [CV]
GO
/****** Object:  Table [dbo].[caMain]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[caMain](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[RegDate] [smalldatetime] NOT NULL,
	[cpMainID] [int] NOT NULL,
	[AccountType] [tinyint] NOT NULL,
	[UserName] [varchar](50) COLLATE Chinese_PRC_CS_AS NOT NULL,
	[UserNameLower]  AS (CONVERT([varchar](50),[UserName] collate CHINESE_PRC_CI_AS,0)) PERSISTED,
	[Password] [varchar](60) COLLATE Chinese_PRC_CI_AS NULL,
	[Name] [nvarchar](6) COLLATE Chinese_PRC_CI_AS NULL,
	[Gender] [bit] NULL,
	[Title] [nvarchar](20) COLLATE Chinese_PRC_CI_AS NULL,
	[Dept] [nvarchar](20) COLLATE Chinese_PRC_CI_AS NULL,
	[Telephone] [varchar](25) COLLATE Chinese_PRC_CI_AS NULL,
	[Mobile] [varchar](11) COLLATE Chinese_PRC_CI_AS NULL,
	[Fax] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL,
	[EMail] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[IsPhoneHide] [bit] NOT NULL,
	[IsNameHide] [bit] NOT NULL,
	[IsMobileHide] [bit] NOT NULL,
	[EmailSentType] [tinyint] NOT NULL,
	[IsPause] [bit] NOT NULL,
	[IsDelete] [bit] NOT NULL,
	[LastModifyDate] [smalldatetime] NOT NULL,
	[IsReceiveSms] [bit] NOT NULL,
	[qq] [varchar](13) COLLATE Chinese_PRC_CI_AS NULL,
	[SecondPassword] [varchar](60) COLLATE Chinese_PRC_CI_AS NULL,
	[wechat] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL,
	[IsShowEmailContact] [bit] NULL,
	[MobileVerifyDate] [smalldatetime] NULL,
	[qqaddMan] [int] NULL,
	[wechataddMan] [int] NULL,
 CONSTRAINT [PK_caMain] PRIMARY KEY NONCLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [CP]
) ON [CV]

GO
/****** Object:  Index [IX_caMain_cpMainID]    Script Date: 2018/9/25 12:40:11 ******/
CREATE CLUSTERED INDEX [IX_caMain_cpMainID] ON [dbo].[caMain]
(
	[cpMainID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [CV]
GO
/****** Object:  View [dbo].[viewExJobApply]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE VIEW [dbo].[viewExJobApply]
AS
SELECT     dbo.exJobApply.ID, dbo.exJobApply.JobID, dbo.exJobApply.cvMainID, dbo.cvMain.Name, dbo.paMain.Name AS paName, 
                      dbo.exJobApply.ApplyMessage, dbo.cvMain.RefreshDate, dbo.exJobApply.AddDate, dbo.exJobApply.CompanyDeleted, 
                      dbo.exJobApply.CompanyDeleteDate, dbo.exJobApply.PersonDeleted, dbo.exJobApply.Reply, dbo.caMain.cpMainID, dbo.caMain.Name AS caName, 
                      dbo.Job.Name AS jobName, dbo.Job.dcRegionID, dbo.caMain.Title, dbo.caMain.Dept, dbo.caMain.Telephone, dbo.caMain.Mobile, dbo.caMain.Fax, 
                      dbo.caMain.EMail, dbo.caMain.IsPhoneHide, dbo.caMain.IsNameHide, dbo.caMain.IsMobileHide, dbo.Job.dcJobTypeID, dbo.Job.dcJobTypeIDMinor, 
                      dbo.Job.NeedNumber, dbo.Job.dcSalaryID, dbo.Job.EmployType, dbo.Job.dcEducationID, dbo.paMain.Gender, dbo.paMain.BirthDay, 
                      dbo.paMain.LivePlace, dbo.cvMain.paMainID, dbo.cvMain.VerifyResult, dbo.exJobApply.ReplyDate
FROM         dbo.exJobApply INNER JOIN
                      dbo.cvMain ON dbo.exJobApply.cvMainID = dbo.cvMain.ID INNER JOIN
                      dbo.paMain ON dbo.cvMain.paMainID = dbo.paMain.ID INNER JOIN
                      dbo.Job ON dbo.exJobApply.JobID = dbo.Job.ID INNER JOIN
                      dbo.caMain ON dbo.Job.caMainID = dbo.caMain.ID

GO
/****** Object:  Table [dbo].[cvJobPlace]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[cvJobPlace](
	[cvMainID] [int] NOT NULL,
	[dcRegionID] [varchar](6) COLLATE Chinese_PRC_CI_AS NOT NULL,
 CONSTRAINT [PK_cvJobPlace] PRIMARY KEY CLUSTERED 
(
	[cvMainID] ASC,
	[dcRegionID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [CV]
) ON [CV]

GO
/****** Object:  View [dbo].[viewPaJobPlace]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE VIEW [dbo].[viewPaJobPlace]
AS
SELECT     dbo.paMain.ID, LEFT(dbo.cvJobPlace.dcRegionID, 2) AS dcProvinceID
FROM         dbo.paMain WITH (NOLOCK) INNER JOIN
                      dbo.cvMain WITH (NOLOCK) ON dbo.paMain.ID = dbo.cvMain.paMainID INNER JOIN
                      dbo.cvJobPlace WITH (NOLOCK) ON dbo.cvMain.ID = dbo.cvJobPlace.cvMainID


GO
/****** Object:  View [dbo].[viewJob]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE VIEW [dbo].[viewJob]
AS
SELECT     dbo.Job.ID, dbo.Job.cpMainID, dbo.Job.caMainID, dbo.Job.Name, dbo.Job.dcJobTypeID, dbo.Job.dcJobTypeIDMinor, dbo.Job.NeedNumber, 
                      dbo.Job.dcSalaryID, dbo.Job.EmployType, dbo.Job.dcRegionID, dbo.Job.MapBarID, dbo.Job.Responsibility, dbo.Job.Demand, dbo.Job.dcEducationID, 
                      dbo.Job.MinExperience, dbo.Job.MinAge, dbo.Job.MaxAge, dbo.Job.EMailSendNumber, dbo.Job.EMailSendFreq, dbo.Job.DisplayNo, 
                      dbo.Job.IssueDate, dbo.Job.IssueEnd, dbo.Job.IsDelete, dbo.Job.ViewNumber, 
                      dbo.Job.AddDate, dbo.Job.RefreshDate, dbo.Job.LastModifyDate, dbo.cpMain.Name AS cpName
FROM         dbo.Job INNER JOIN
                      dbo.cpMain ON dbo.Job.cpMainID = dbo.cpMain.ID


GO
/****** Object:  Table [dbo].[paLoginLog]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[paLoginLog](
	[ID] [int] IDENTITY(1,1) NOT FOR REPLICATION NOT NULL,
	[paMainID] [int] NOT NULL,
	[LoginIP] [varchar](39) COLLATE Chinese_PRC_CI_AS NULL,
	[AddDate] [smalldatetime] NOT NULL,
	[Browser] [varchar](500) COLLATE Chinese_PRC_CI_AS NULL,
	[LoginFrom] [tinyint] NULL
) ON [CV]

GO
/****** Object:  View [dbo].[ViewPaLoginlog1]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE VIEW [dbo].[ViewPaLoginlog1]
AS
SELECT     ID, paMainID, LoginIP, AddDate
FROM         dbo.paLoginLog
WHERE     (AddDate > GETDATE() - 1)

GO
/****** Object:  Table [dbo].[Dept]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Dept](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[DeptName] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Grade] [smallint] NOT NULL,
	[Superior] [int] NOT NULL,
	[Valid] [bit] NOT NULL,
	[FullNumber] [tinyint] NULL,
	[Place] [int] NULL,
 CONSTRAINT [PK_dept] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 50) ON [PRIMARY],
 CONSTRAINT [IX_dept_unique] UNIQUE NONCLUSTERED 
(
	[DeptName] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 50) ON [Index]
) ON [PRIMARY]

GO
/****** Object:  View [dbo].[ViewDept]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--update dept set grade=3, superior=4 where id=9
--update dept set grade=1, superior=0 where id=9
CREATE View [dbo].[ViewDept]
AS
SELECT * ,
	CASE 
	WHEN Grade = 1 THEN	Id * 10000
	WHEN Grade = 2 THEN Superior * 10000 + ID
	WHEN Grade = 3 THEN (SELECT Superior * 10000 FROM Dept a WITH(NOLOCK) WHERE a.Id = Dept.Superior) + Superior * 100 + Id
	END
	OrderNo
FROM Dept WITH(NOLOCK)
WHERE Valid = 1


GO
/****** Object:  Table [dbo].[dcJobType]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[dcJobType](
	[ID] [smallint] NOT NULL,
	[ParentID] [smallint] NULL,
	[grade] [tinyint] NOT NULL,
	[Description] [nvarchar](25) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[DescriptionEng] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[ParentID2] [smallint] NULL,
	[ParentID3] [smallint] NULL,
	[OrderNo] [smallint] NOT NULL,
	[Abbreviation] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
 CONSTRAINT [PK_dcJobType] PRIMARY KEY CLUSTERED 
(
	[ID] 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].[viewJobType]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create view [dbo].[viewJobType]
as 
	select * from dcJobtype where id>0
	
GO
/****** Object:  View [dbo].[viewLinkSnapDate]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create view [dbo].[viewLinkSnapDate]
as
SELECT     LEFT(b.ID, 2) AS ProvinceID, b.VersionDomain, b.VersionName, a.VersionId, a.Text, a.Link, a.LinkPage, a.Baidu, a.LinkOur, a.Id, a.Pr, a.OutLink, 
                      a.BaiduRank, a.BaiduIncluded, a.BaiduDate, a.Deleted, a.Method
FROM         dbo.Link AS a INNER JOIN
                      dbo.version AS b ON a.VersionId = b.ID AND a.Valid = 1 AND a.Deleted = 0 AND a.Type = 1 AND a.Method = 1
WHERE     (ISNULL(a.SnapshotDate, '2000-1-1') < '2000-1-2')
GO
/****** Object:  View [dbo].[viewLinkKeyword]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create view [dbo].[viewLinkKeyword]
as
SELECT     LEFT(b.ID, 2) AS ProvinceID, b.VersionDomain, b.VersionName, a.VersionId, a.Text, a.Link, a.LinkPage, a.Baidu, a.LinkOur, a.Id, a.Pr, a.OutLink, 
                      a.BaiduRank, a.BaiduIncluded, a.BaiduDate, a.Deleted, a.Method
FROM         dbo.Link AS a INNER JOIN
                      dbo.version AS b ON a.VersionId = b.ID AND a.Valid = 1 AND a.Deleted = 0 AND a.Type = 1 AND a.Method = 1
WHERE     IsNUll(Ourkeyword, '')=''
GO
/****** Object:  View [dbo].[viewLink]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE VIEW [dbo].[viewLink]
AS
SELECT     LEFT(b.ID, 2) AS ProvinceID, b.VersionDomain, b.VersionName, a.VersionId, a.Text, a.Link, a.LinkPage, a.Baidu, a.LinkOur, a.Id, a.Pr, a.OutLink, 
                      a.BaiduRank, a.BaiduIncluded, a.BaiduDate, a.Deleted, a.Method, a.SnapshotDate, a.OurKeyWord, a.CheckVersionId, a.AnnounceDate
FROM         dbo.Link AS a INNER JOIN
                      dbo.version AS b ON a.VersionId = b.ID AND a.Method = 1 AND a.Deleted < 2

GO
/****** Object:  View [dbo].[ViewSubSite]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create view [dbo].[ViewSubSite]
AS
SELECT id, SubSiteName
FROM dcSubSite
UNION
SELECT 90, '梧桐果'
GO
/****** Object:  Table [dbo].[dcProvince]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[dcProvince](
	[ID] [tinyint] NOT NULL,
	[ProvinceName] [nvarchar](10) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[WebsiteName] [nvarchar](10) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[ProvinceDomain] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[SouthNorth] [tinyint] NOT NULL,
	[AssignConsultant] [tinyint] NULL,
	[AdRemarks] [nvarchar](500) COLLATE Chinese_PRC_CI_AS NULL,
 CONSTRAINT [PK_dcProvince] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 50) ON [PRIMARY]
) ON [PRIMARY]

GO
/****** Object:  View [dbo].[province]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE VIEW [dbo].[province]
AS
SELECT     a.ID, a.ProvinceName AS Province, 'www.' + a.ProvinceDomain AS site, a.WebsiteName AS Website, a.ProvinceDomain AS domain, a.SouthNorth, a.AssignConsultant, 
                      a.AdRemarks, b.EmailSite, b.EmailSite AS email_site, b.MinInfoAmount AS info_lowlimit, b.MaxInfoAmount AS info_uplimit, b.EmailTester AS emailtestman, 
                      b.InternalIp AS smtp, b.EmailUser AS Email_User
FROM         dbo.dcProvince AS a LEFT OUTER JOIN
                      dbo.dcSubSite AS b ON a.ID = b.ID

GO
/****** Object:  Table [dbo].[caCvQuotaLog]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[caCvQuotaLog](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[cpMainID] [int] NOT NULL,
	[caMainID] [int] NOT NULL,
	[cvMainID] [int] NOT NULL,
	[AddDate] [smalldatetime] NOT NULL,
 CONSTRAINT [PK_caCvQuotaLog] PRIMARY KEY CLUSTERED 
(
	[cpMainID] ASC,
	[cvMainID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [CP]
) ON [CP]

GO
/****** Object:  Table [dbo].[caCvQuotaLog_Tmp]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[caCvQuotaLog_Tmp](
	[ID] [int] NOT NULL,
	[cpMainID] [int] NOT NULL,
	[caMainID] [int] NOT NULL,
	[cvMainID] [int] NOT NULL,
	[AddDate] [smalldatetime] NOT NULL
) ON [PRIMARY]

GO
/****** Object:  View [dbo].[ViewCaCvQuotaLog]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE VIEW [dbo].[ViewCaCvQuotaLog]
AS
SELECT * FROM CaCvQuotaLog
UNION
SELECT * FROM CaCvQuotaLog_Tmp
GO
/****** Object:  View [dbo].[ViewCpMain6M]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE view [dbo].[ViewCpMain6M]
AS
SELECT * FROM cpMain WHERE RefreshDate > CONVERT(VARCHAR(10), GETDATE()- 183, 120)
GO
/****** Object:  Table [dbo].[JobPublish]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[JobPublish](
	[ID] [int] NOT NULL,
	[cpMainID] [int] NOT NULL,
	[caMainId] [int] NOT NULL,
	[Name] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[dcJobTypeID] [smallint] NOT NULL,
	[dcJobTypeIDMinor] [smallint] NULL,
	[NeedNumber] [tinyint] NULL,
	[dcSalaryID] [tinyint] NOT NULL,
	[EmployType] [tinyint] NOT NULL,
	[dcRegionID] [varchar](6) COLLATE Chinese_PRC_CI_AS NULL,
	[Responsibility] [nvarchar](max) COLLATE Chinese_PRC_CI_AS NULL,
	[Demand] [nvarchar](max) COLLATE Chinese_PRC_CI_AS NULL,
	[dcEducationID] [tinyint] NOT NULL,
	[MinExperience] [tinyint] NOT NULL,
	[MinAge] [tinyint] NULL,
	[MaxAge] [tinyint] NULL,
	[IssueDate] [smalldatetime] NULL,
	[IssueEnd] [smalldatetime] NULL,
	[IsDelete] [bit] NOT NULL,
	[AddDate] [smalldatetime] NOT NULL,
	[RefreshDate] [smalldatetime] NULL,
	[LastModifyDate] [smalldatetime] NOT NULL,
	[Valid] [bit] NOT NULL,
	[Lng] [decimal](8, 5) NULL,
	[Lat] [decimal](8, 5) NULL,
	[SecondId] [varchar](12) COLLATE Chinese_PRC_CI_AS NULL,
	[Welfare1] [bit] NULL,
	[Welfare2] [bit] NULL,
	[Welfare3] [bit] NULL,
	[Welfare4] [bit] NULL,
	[Welfare5] [bit] NULL,
	[Welfare6] [bit] NULL,
	[Welfare7] [bit] NULL,
	[Welfare8] [bit] NULL,
	[Welfare9] [bit] NULL,
	[Welfare10] [bit] NULL,
	[Welfare11] [bit] NULL,
	[Welfare12] [bit] NULL,
	[Welfare13] [bit] NULL,
	[Welfare14] [bit] NULL,
	[Welfare15] [bit] NULL,
	[Welfare16] [bit] NULL,
	[Welfare17] [bit] NULL,
	[Welfare18] [bit] NULL,
	[dcSalaryIdMax] [tinyint] NULL,
	[Welfare19] [bit] NULL,
	[Salary] [int] NULL,
	[SycDate] [datetime] NULL,
 CONSTRAINT [PK_JobPublish] PRIMARY KEY NONCLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [CP]
) ON [CP] TEXTIMAGE_ON [CP]

GO
/****** Object:  Index [IX_JobPublish_cpMainID]    Script Date: 2018/9/25 12:40:11 ******/
CREATE CLUSTERED INDEX [IX_JobPublish_cpMainID] ON [dbo].[JobPublish]
(
	[cpMainID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [CP]
GO
/****** Object:  Table [dbo].[cpMainPublish]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[cpMainPublish](
	[ID] [int] NOT NULL,
	[Name] [nvarchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[ShortName] [varchar](40) COLLATE Chinese_PRC_CI_AS NULL,
	[dcCompanyKindID] [smallint] NULL,
	[dcCompanySizeID] [tinyint] NULL,
	[dcRegionID] [varchar](6) COLLATE Chinese_PRC_CI_AS NULL,
	[Brief] [nvarchar](max) COLLATE Chinese_PRC_CI_AS NULL,
	[HasLicence] [bit] NOT NULL,
	[UnlimitedDate] [smalldatetime] NOT NULL,
	[BalanceDate] [smalldatetime] NOT NULL,
	[Balance] [smallint] NOT NULL,
	[MemberType] [tinyint] NOT NULL,
	[RefreshDate] [smalldatetime] NULL,
	[LastModifyDate] [smalldatetime] NULL,
	[LastLoginDate] [smalldatetime] NULL,
	[Valid] [tinyint] NULL,
	[Lng] [decimal](8, 5) NULL,
	[Lat] [decimal](8, 5) NULL,
	[IsRefreshed] [bit] NOT NULL,
	[SecondId] [varchar](10) COLLATE Chinese_PRC_CI_AS NULL,
	[HasEnvironment] [bit] NULL,
	[dcProvinceId] [tinyint] NULL,
	[ReplyRate] [decimal](8, 3) NULL,
	[RealName] [tinyint] NULL,
	[LogoFile] [varchar](90) COLLATE Chinese_PRC_CI_AS NULL,
	[AvgSalary] [int] NULL,
 CONSTRAINT [PK_cpMainPublish] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [CP]
) ON [CP] TEXTIMAGE_ON [CP]

GO
/****** Object:  View [dbo].[cpMainJob]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE VIEW [dbo].[cpMainJob]
WITH SCHEMABINDING 
AS
SELECT     dbo.JobPublish.Name AS jobname, dbo.JobPublish.ID AS jobid, dbo.JobPublish.Demand, dbo.JobPublish.Responsibility, dbo.cpMainPublish.ID AS cpmainid, 
                      dbo.cpMainPublish.Name AS cpname, dbo.cpMainPublish.Brief
FROM         dbo.JobPublish INNER JOIN
                      dbo.cpMainPublish ON dbo.JobPublish.cpMainID = dbo.cpMainPublish.ID
WHERE     (dbo.JobPublish.Valid = 1) AND (dbo.cpMainPublish.Valid = 1)
GO
SET ARITHABORT ON
SET CONCAT_NULL_YIELDS_NULL ON
SET QUOTED_IDENTIFIER ON
SET ANSI_NULLS ON
SET ANSI_PADDING ON
SET ANSI_WARNINGS ON
SET NUMERIC_ROUNDABORT OFF

GO
/****** Object:  Index [IX_cpMainJob_JobId]    Script Date: 2018/9/25 12:40:11 ******/
CREATE UNIQUE CLUSTERED INDEX [IX_cpMainJob_JobId] ON [dbo].[cpMainJob]
(
	[jobid] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = ON, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
/****** Object:  View [dbo].[RecruitMeeting]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE VIEW [dbo].[RecruitMeeting]
AS
SELECT ID, LEFT(CityId, 2) Province_Id, EndDate EndTime, 2 TYPE, 0 Status, 0 ORDERBY, AddDate FROM Recruitment
GO
/****** Object:  View [dbo].[v_rand]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create view [dbo].[v_rand]  
as  
select Rand() as re  
GO
/****** Object:  Table [dbo].[_caorderCharType]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[_caorderCharType](
	[id] [int] NOT NULL,
	[adddate] [smalldatetime] NOT NULL,
	[begindate] [smalldatetime] NULL,
	[enddate] [smalldatetime] NULL,
	[paid] [numeric](18, 2) NOT NULL,
	[detailname] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[timetitle] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[cpmainid] [int] NOT NULL,
	[Name] [varchar](100) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[ConsultantId] [smallint] NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[_dcMajorKeyword20180117]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[_dcMajorKeyword20180117](
	[MajorName] [nvarchar](20) COLLATE Chinese_PRC_CI_AS NULL,
	[dcMajorId] [int] NULL,
	[PinYin] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[JianPin] [varchar](30) COLLATE Chinese_PRC_CI_AS NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[_FnBankDaybook0329]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[_FnBankDaybook0329](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[Concern] [smallint] NOT NULL,
	[TsctDate] [datetime] NOT NULL,
	[Debit] [numeric](18, 2) NULL,
	[Credit] [numeric](18, 2) NULL,
	[Balance] [numeric](18, 2) NOT NULL,
	[OppositeCompany] [nvarchar](500) COLLATE Chinese_PRC_CI_AS NULL,
	[OppositeAccount] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[OppositeBank] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[Purpose] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[Summary] [nvarchar](200) COLLATE Chinese_PRC_CI_AS NULL,
	[CertificateNo] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL,
	[ApplyNo] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL,
	[AddMan] [int] NOT NULL,
	[AddManName] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[AddDate] [datetime] NOT NULL,
	[RelationNo] [varchar](12) COLLATE Chinese_PRC_CI_AS NULL,
	[Remarks] [nvarchar](200) COLLATE Chinese_PRC_CI_AS NULL,
	[ReceIptDate] [datetime] NULL,
	[ReceIptMan] [int] NULL,
	[ReceIptManName] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[RelationDate] [datetime] NULL,
	[RelationMan] [int] NULL,
	[RelationManName] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[RelationNo2] [varchar](12) COLLATE Chinese_PRC_CI_AS NULL,
	[Attach1] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[BKYearMonth] [char](6) COLLATE Chinese_PRC_CI_AS NULL,
	[VoucherNo] [smallint] NULL,
	[BkMan] [int] NULL,
	[BkManname] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[BKDate] [datetime] NULL,
	[IsSales] [tinyint] NULL,
	[RelationNo3] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[RelationNo4] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[RelationNo5] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[RelationNo6] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[RelationType] [tinyint] NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[_FnBankDaybook0330]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[_FnBankDaybook0330](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[Concern] [smallint] NOT NULL,
	[TsctDate] [datetime] NOT NULL,
	[Debit] [numeric](18, 2) NULL,
	[Credit] [numeric](18, 2) NULL,
	[Balance] [numeric](18, 2) NOT NULL,
	[OppositeCompany] [nvarchar](500) COLLATE Chinese_PRC_CI_AS NULL,
	[OppositeAccount] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[OppositeBank] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[Purpose] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[Summary] [nvarchar](200) COLLATE Chinese_PRC_CI_AS NULL,
	[CertificateNo] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL,
	[ApplyNo] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL,
	[AddMan] [int] NOT NULL,
	[AddManName] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[AddDate] [datetime] NOT NULL,
	[RelationNo] [varchar](12) COLLATE Chinese_PRC_CI_AS NULL,
	[Remarks] [nvarchar](200) COLLATE Chinese_PRC_CI_AS NULL,
	[ReceIptDate] [datetime] NULL,
	[ReceIptMan] [int] NULL,
	[ReceIptManName] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[RelationDate] [datetime] NULL,
	[RelationMan] [int] NULL,
	[RelationManName] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[RelationNo2] [varchar](12) COLLATE Chinese_PRC_CI_AS NULL,
	[Attach1] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[BKYearMonth] [char](6) COLLATE Chinese_PRC_CI_AS NULL,
	[VoucherNo] [smallint] NULL,
	[BkMan] [int] NULL,
	[BkManname] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[BKDate] [datetime] NULL,
	[IsSales] [tinyint] NULL,
	[RelationNo3] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[RelationNo4] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[RelationNo5] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[RelationNo6] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[RelationType] [tinyint] NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[a0]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[a0](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[v] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[a1]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[a1](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[paMainId] [int] NULL,
	[adddate] [datetime] NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[a2]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[a2](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[username] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL,
	[crdate] [datetime] NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[AdverProject]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[AdverProject](
	[Id] [int] IDENTITY(1,1) NOT FOR REPLICATION NOT NULL,
	[Type] [smallint] NOT NULL,
	[Province_Id] [int] NOT NULL,
	[ImageFile] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[ImageFileSmall] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[BOrder] [smallint] NULL,
	[Url] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL,
	[Width] [smallint] NULL,
	[Height] [smallint] NULL,
	[ScrollBar] [bit] NULL,
	[LeftMargin] [smallint] NULL,
	[TopMargin] [smallint] NULL,
	[ClickCount] [int] NOT NULL,
	[CloseButton] [bit] NULL,
	[FollowScreen] [bit] NULL,
	[CloseButtonPosition] [smallint] NULL,
	[BeginTime] [smalldatetime] NOT NULL,
	[EndTime] [smalldatetime] NOT NULL,
	[Valid] [smallint] NOT NULL,
	[Remarks] [nvarchar](200) COLLATE Chinese_PRC_CI_AS NULL,
	[Loop] [smallint] NULL,
	[CompanyId] [int] NULL,
	[Orderby] [smallint] NULL,
	[Description] [nvarchar](200) COLLATE Chinese_PRC_CI_AS NULL,
	[CaOrderID] [int] NULL,
	[AddDate] [smalldatetime] NULL,
	[AddMan] [int] NULL,
	[InNews] [bit] NULL,
	[IsSelf] [bit] NULL,
 CONSTRAINT [PK_AdverProject] PRIMARY KEY NONCLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Market]
) ON [Market]

GO
/****** Object:  Table [dbo].[AdverProject_ErrorLog]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[AdverProject_ErrorLog](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[ErrorLog] [nvarchar](2000) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[AddDate] [smalldatetime] NOT NULL,
 CONSTRAINT [PK_adverproject_ErrorLog] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Market]
) ON [Market]

GO
/****** Object:  Table [dbo].[Agent_Black]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Agent_Black](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[agent] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[description] [nvarchar](500) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[adddate] [smalldatetime] NOT NULL,
	[remarks] [nvarchar](500) COLLATE Chinese_PRC_CI_AS NULL,
 CONSTRAINT [PK_agent_black] PRIMARY KEY CLUSTERED 
(
	[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [FOthers]
) ON [FOthers]

GO
/****** Object:  Table [dbo].[Agent_White]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Agent_White](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[Agent] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Description] [nvarchar](500) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[AddDate] [smalldatetime] NOT NULL,
	[Remarks] [nvarchar](500) COLLATE Chinese_PRC_CI_AS NULL,
 CONSTRAINT [PK_agent_White] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [FOthers]
) ON [FOthers]

GO
/****** Object:  Table [dbo].[AgentIp]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[AgentIp](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[Ip] [varchar](17) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Location] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[AddMan] [smallint] NOT NULL,
	[AddDate] [smalldatetime] NOT NULL,
	[Port] [smallint] NOT NULL,
	[Type] [tinyint] NOT NULL,
 CONSTRAINT [PK_AgentIp] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Market]
) ON [Market]

GO
/****** Object:  Table [dbo].[AGroup_ManagerUser]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[AGroup_ManagerUser](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[Group_Id] [int] NOT NULL,
	[ManagerUser_Id] [smallint] NOT NULL,
	[DescrIption] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[orderby] [smallint] NOT NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[AGroup_Province]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[AGroup_Province](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[Group_Id] [int] NOT NULL,
	[Province_Id] [tinyint] NOT NULL,
	[DescrIption] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[Orderby] [smallint] NOT NULL,
	[QQ_Limit] [smallint] NULL,
	[Sms_limit] [int] NULL,
	[cpSms_limit] [int] NULL,
	[IsSet] [bit] NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[AGroupM]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[AGroupM](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[GroupName] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[DescrIption] [nvarchar](200) COLLATE Chinese_PRC_CI_AS NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[AlipayJobPushLog]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[AlipayJobPushLog](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[JobId] [int] NOT NULL,
	[PushStatus] [tinyint] NULL,
	[PushTime] [smalldatetime] NULL,
 CONSTRAINT [PK_AlipayJobPushLog] PRIMARY KEY CLUSTERED 
(
	[id] 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].[Answer]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Answer](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[Answer] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL,
	[Assist] [nvarchar](200) COLLATE Chinese_PRC_CI_AS NULL,
	[QuestionId] [int] NOT NULL,
	[ManId] [int] NOT NULL,
 CONSTRAINT [PK_answer] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers],
 CONSTRAINT [IX_answer_unique] UNIQUE NONCLUSTERED 
(
	[QuestionId] ASC,
	[ManId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
) ON [BOthers]

GO
/****** Object:  Table [dbo].[ass_consultant]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ass_consultant](
	[consultantid] [smallint] NULL,
	[dcgroup] [smallint] NULL,
	[yearmonth] [varchar](6) COLLATE Chinese_PRC_CI_AS NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[ass_cpmain]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ass_cpmain](
	[id] [int] NOT NULL,
	[a_type] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[consultantid] [smallint] NULL,
	[dcProvinceID] [tinyint] NULL,
	[consultantDate] [smalldatetime] NULL,
	[lastlogindate] [smalldatetime] NULL,
	[consultantidNew] [smallint] NULL,
	[consultantidNewDate] [datetime] NULL,
	[OrderProcessed] [bit] NULL,
	[name] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[yearmonth] [varchar](6) COLLATE Chinese_PRC_CI_AS NULL,
	[addman] [smallint] NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[ass_cpmain_cnt]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ass_cpmain_cnt](
	[consultantid] [smallint] NULL,
	[dcprovinceid] [tinyint] NULL,
	[a_type] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[cnt] [int] NULL,
	[yearmonth] [varchar](6) COLLATE Chinese_PRC_CI_AS NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[ass_cpMain_cnt_All]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ass_cpMain_cnt_All](
	[dcProvinceID] [smallint] NULL,
	[a_type] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[cntAll] [int] NULL,
	[consultantNum] [int] NULL,
	[CntAllAverage] [int] NULL,
	[processed] [bit] NULL,
	[processdate] [datetime] NULL,
	[yearmonth] [varchar](6) COLLATE Chinese_PRC_CI_AS NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[ass_cpmain_tmp]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ass_cpmain_tmp](
	[id] [int] NOT NULL,
	[a_type] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[consultantid] [smallint] NULL,
	[dcProvinceID] [tinyint] NULL,
	[consultantDate] [smalldatetime] NULL,
	[lastlogindate] [smalldatetime] NULL,
	[consultantidNew] [smallint] NULL,
	[consultantidNewDate] [datetime] NULL,
	[OrderProcessed] [bit] NULL,
	[name] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[addman] [smallint] NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[ass_cpmain20180526]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ass_cpmain20180526](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[consultantid] [smallint] NULL,
	[consultantdate] [smalldatetime] NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[ass_group_province]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ass_group_province](
	[dcgroupid] [smallint] NULL,
	[dcprovinceid] [smallint] NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[ass_noAssign]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ass_noAssign](
	[consultantid] [smallint] NOT NULL,
	[yearmonth] [varchar](6) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[companyname] [varchar](100) COLLATE Chinese_PRC_CI_AS NOT NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[ass_noAssign_old]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ass_noAssign_old](
	[consultantid] [smallint] NULL,
	[cpMainID] [int] NULL,
	[yearmonth] [varchar](6) COLLATE Chinese_PRC_CI_AS NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[assessCpInvite]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[assessCpInvite](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[CaMainID] [int] NOT NULL,
	[PaMainID] [int] NOT NULL,
	[AssessTypeID] [int] NOT NULL,
	[Email] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[Mobile] [varchar](11) COLLATE Chinese_PRC_CI_AS NULL,
	[Status] [tinyint] NOT NULL,
	[EndDate] [smalldatetime] NOT NULL,
	[AddDate] [smalldatetime] NOT NULL,
 CONSTRAINT [PK_assessCpInvite] PRIMARY KEY CLUSTERED 
(
	[ID] 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].[assessDimension]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[assessDimension](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[Name] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[ShortName] [nvarchar](10) COLLATE Chinese_PRC_CI_AS NULL,
	[AssessDimensionGroupID] [int] NOT NULL,
	[AddMan] [int] NULL,
	[AddDate] [smalldatetime] NOT NULL,
 CONSTRAINT [PK_assessOptionsDimension] PRIMARY KEY CLUSTERED 
(
	[ID] 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].[assessDimensionGroup]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[assessDimensionGroup](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[Name] [nvarchar](20) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[AssessTypeID] [int] NOT NULL,
	[AddMan] [int] NOT NULL,
	[AddDate] [smalldatetime] NOT NULL,
	[ShortName] [varchar](5) COLLATE Chinese_PRC_CI_AS NULL,
 CONSTRAINT [PK_assessDimensionGroup] PRIMARY KEY CLUSTERED 
(
	[ID] 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].[assessOptions]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[assessOptions](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[AssessQuestionID] [int] NOT NULL,
	[Options] [nvarchar](500) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[AssessDimensionID] [int] NULL,
	[Score] [int] NULL,
	[SortNo] [tinyint] NULL,
	[AddMan] [int] NULL,
	[AddDate] [smalldatetime] NOT NULL,
 CONSTRAINT [PK_assessAnswer] PRIMARY KEY CLUSTERED 
(
	[ID] 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].[assessQuestion]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[assessQuestion](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[AssessThemeID] [int] NOT NULL,
	[Question] [nvarchar](max) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[AttachmentFile] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[SortNo] [tinyint] NOT NULL,
	[QuestionType] [tinyint] NULL,
	[OptionsSort] [tinyint] NULL,
	[AssessDimensionGroupID] [int] NULL,
	[AddMan] [int] NULL,
	[AddDate] [smalldatetime] NOT NULL,
	[OptionsShowMode] [tinyint] NULL,
 CONSTRAINT [PK_assessQuestion] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

GO
/****** Object:  Table [dbo].[assessTestAnswer]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[assessTestAnswer](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[AssessTestLogID] [int] NOT NULL,
	[AssessQuestionID] [int] NOT NULL,
	[AssessOptionsID] [int] NULL,
	[AddDate] [smalldatetime] NOT NULL,
	[AnswerDate] [smalldatetime] NULL,
	[Choice] [varchar](5) COLLATE Chinese_PRC_CI_AS NULL,
 CONSTRAINT [PK_assessTestAnswer] PRIMARY KEY CLUSTERED 
(
	[ID] 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].[assessTestLog]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[assessTestLog](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[PaMainID] [int] NOT NULL,
	[AssessTypeID] [int] NOT NULL,
	[AssessCpInviteID] [int] NULL,
	[BeginTime] [datetime] NULL,
	[EndTime] [smalldatetime] NULL,
	[TextResult] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[ScoreResult] [int] NULL,
	[RemainSeconds] [int] NULL,
	[LeaveTimes] [int] NULL,
	[IsOpen] [bit] NULL,
	[Status] [tinyint] NULL,
	[AddDate] [smalldatetime] NULL,
 CONSTRAINT [PK_assessTestLog] PRIMARY KEY CLUSTERED 
(
	[ID] 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].[assessTheme]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[assessTheme](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[AssessTypeID] [int] NOT NULL,
	[Title] [nvarchar](100) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Summary] [nvarchar](1000) COLLATE Chinese_PRC_CI_AS NULL,
	[Material] [nvarchar](max) COLLATE Chinese_PRC_CI_AS NULL,
	[Notice] [nvarchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[AssessThemeTypeID] [int] NOT NULL,
	[SortNo] [tinyint] NULL,
	[SortType] [tinyint] NULL,
	[AddMan] [int] NULL,
	[AddDate] [smalldatetime] NOT NULL,
	[CountPerPage] [tinyint] NULL,
	[QuestionCount] [tinyint] NULL,
 CONSTRAINT [PK_assessTheme] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

GO
/****** Object:  Table [dbo].[assessThemeType]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[assessThemeType](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[Name] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[DefaultTitle] [nvarchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[DefaultSummary] [nvarchar](1000) COLLATE Chinese_PRC_CI_AS NULL,
	[DefaultNotice] [nvarchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[Summary] [nvarchar](500) COLLATE Chinese_PRC_CI_AS NULL,
	[AddMan] [int] NULL,
	[AddDate] [smalldatetime] NOT NULL,
 CONSTRAINT [PK_assessThemeType] PRIMARY KEY CLUSTERED 
(
	[ID] 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].[assessType]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[assessType](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[Name] [nvarchar](100) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[ImgUrl] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[NeedTime] [int] NULL,
	[ReTestDay] [int] NOT NULL,
	[Summary] [nvarchar](1000) COLLATE Chinese_PRC_CI_AS NULL,
	[Notice] [nvarchar](max) COLLATE Chinese_PRC_CI_AS NULL,
	[UseCount] [int] NOT NULL,
	[SortNo] [tinyint] NULL,
	[ResultType] [tinyint] NULL,
	[AddMan] [int] NULL,
	[AddDate] [smalldatetime] NOT NULL,
 CONSTRAINT [PK_assessType] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

GO
/****** Object:  Table [dbo].[assessTypeResult]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[assessTypeResult](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[AssessTypeID] [int] NOT NULL,
	[Title] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[MinScore] [int] NULL,
	[MaxScore] [int] NULL,
	[TextResult] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[AttachmentFile] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[AddMan] [int] NULL,
	[AddDate] [smalldatetime] NULL,
	[ReportHtml] [nvarchar](max) COLLATE Chinese_PRC_CI_AS NULL,
 CONSTRAINT [PK_assessTypeResult] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

GO
/****** Object:  Table [dbo].[Atc_Account]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Atc_Account](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[username] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[password] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[AddMan] [smallint] NOT NULL,
	[AddDate] [smalldatetime] NOT NULL,
	[Description] [nvarchar](max) COLLATE Chinese_PRC_CI_AS NULL,
	[Atc_Resource_Id] [int] NOT NULL,
	[Hypocorism] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[ip] [varchar](15) COLLATE Chinese_PRC_CI_AS NULL,
 CONSTRAINT [PK_Atc_Account] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Market]
) ON [Market] TEXTIMAGE_ON [Market]

GO
/****** Object:  Table [dbo].[Atc_Article]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Atc_Article](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[Atc_NewsPoint_Id] [int] NOT NULL,
	[Title] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Description] [nvarchar](max) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Addman] [smallint] NOT NULL,
	[Adddate] [smalldatetime] NOT NULL,
	[grade] [smallint] NOT NULL,
	[status] [smallint] NOT NULL,
	[type] [smallint] NOT NULL,
	[imagefile] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[attachment] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
 CONSTRAINT [PK_Atc_Article] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Market]
) ON [Market] TEXTIMAGE_ON [Market]

GO
/****** Object:  Table [dbo].[Atc_NewsPoint]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Atc_NewsPoint](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[Atc_Project_Id] [int] NOT NULL,
	[NewsPoint] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Description] [nvarchar](max) COLLATE Chinese_PRC_CI_AS NULL,
	[AddDate] [smalldatetime] NOT NULL,
	[AddMan] [smallint] NULL,
 CONSTRAINT [PK_Act_NewsPoint] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Market]
) ON [Market] TEXTIMAGE_ON [Market]

GO
/****** Object:  Table [dbo].[Atc_Project]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Atc_Project](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[Project] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Background] [nvarchar](max) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Addman] [smallint] NOT NULL,
	[adddate] [smalldatetime] NOT NULL,
	[Expect] [nvarchar](max) COLLATE Chinese_PRC_CI_AS NOT NULL,
 CONSTRAINT [PK_Atc_Topic] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers]
) ON [BOthers] TEXTIMAGE_ON [BOthers]

GO
/****** Object:  Table [dbo].[Atc_Resource]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Atc_Resource](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[ResourceName] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[HomePage] [varchar](1000) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[LoginPage] [varchar](1000) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[RegisterPage] [varchar](1000) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Description] [nvarchar](200) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Addman] [smallint] NOT NULL,
	[AddDate] [smalldatetime] NOT NULL,
	[grade] [smallint] NOT NULL,
 CONSTRAINT [PK_Atc_Resource] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Market]
) ON [Market]

GO
/****** Object:  Table [dbo].[Atc_Topic]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Atc_Topic](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[Url] [varchar](2000) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[AddDate] [smalldatetime] NOT NULL,
	[Atc_Article_Id] [int] NOT NULL,
	[Atc_Account_Id] [int] NOT NULL,
	[UrlList] [varchar](2000) COLLATE Chinese_PRC_CI_AS NULL,
	[ClickNum] [int] NOT NULL,
	[status] [smallint] NOT NULL,
	[Block] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[Remarks] [nvarchar](500) COLLATE Chinese_PRC_CI_AS NULL,
	[Ip] [varchar](15) COLLATE Chinese_PRC_CI_AS NULL,
 CONSTRAINT [PK_Atc_Topic_1] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Market]
) ON [Market]

GO
/****** Object:  Table [dbo].[Atc_Topic_ClickNum]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Atc_Topic_ClickNum](
	[Atc_Topic_Id] [int] NOT NULL,
	[MonthDay] [int] NOT NULL,
	[ClickNum] [int] NOT NULL
) ON [Market]

GO
/****** Object:  Table [dbo].[Atc_TopicFollow]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Atc_TopicFollow](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[Atc_Topic_Id] [int] NOT NULL,
	[Atc_Account_Id] [int] NOT NULL,
	[AddDate] [smalldatetime] NOT NULL,
	[Description] [nvarchar](max) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[ip] [varchar](15) COLLATE Chinese_PRC_CI_AS NULL,
	[remarks] [nvarchar](500) COLLATE Chinese_PRC_CI_AS NULL,
 CONSTRAINT [PK_Atc_TopicFollow] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Market]
) ON [Market] TEXTIMAGE_ON [Market]

GO
/****** Object:  Table [dbo].[b_company]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[b_company](
	[id] [int] NULL,
	[companyname] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[email] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[addman] [int] NULL,
	[deleted] [tinyint] NULL
) ON [BOthers]

GO
/****** Object:  Table [dbo].[b_resume]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[b_resume](
	[id] [int] NOT NULL,
	[email] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[deleted] [tinyint] NULL,
	[province] [int] NULL,
	[addman] [int] NULL
) ON [BOthers]

GO
/****** Object:  Table [dbo].[BackData]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[BackData](
	[ID] [int] IDENTITY(1,1) NOT FOR REPLICATION NOT NULL,
	[ManagerID] [smallint] NOT NULL,
	[CountDate] [int] NOT NULL,
	[Resume_Pass] [int] NOT NULL,
	[Resume_Delete] [int] NOT NULL,
	[Resume_NoPass] [int] NOT NULL,
	[Resume_Modify] [int] NOT NULL,
	[Photo_Pass] [int] NOT NULL,
	[Photo_Modify] [int] NOT NULL,
	[Photo_Delete] [int] NOT NULL,
	[Appendix_Modify] [int] NOT NULL,
	[Appendix_Delete] [int] NOT NULL,
	[CompanyLogo_Pass] [int] NOT NULL,
	[CompanyLogo_Delete] [int] NOT NULL,
	[High_Resume_Pass] [int] NOT NULL,
	[High_Resume_NoPass] [int] NOT NULL,
	[Black] [int] NOT NULL,
	[CompanyDelete] [int] NOT NULL,
	[CompanyVisual_Pass] [int] NOT NULL,
	[CompanyVisual_Delete] [int] NOT NULL,
	[Company_Modify] [int] NOT NULL,
	[Contact_NoCvCount] [int] NULL,
	[Contact_NoApplyCount] [int] NULL,
	[Contact_Count] [int] NULL,
	[Contact_CvCount] [int] NULL,
	[Contact_ApplyCount] [int] NULL,
 CONSTRAINT [PK_BackData] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers]
) ON [BOthers]

GO
/****** Object:  Table [dbo].[bakmsEmailTemplete]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[bakmsEmailTemplete](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[msSqlID] [int] NOT NULL,
	[Name] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Title] [varchar](100) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[MailBody] [varchar](max) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[SubMailBody] [varchar](max) COLLATE Chinese_PRC_CI_AS NULL,
	[NoDataBody] [varchar](max) COLLATE Chinese_PRC_CI_AS NULL,
	[Status] [tinyint] NULL,
	[AddMan] [smallint] NOT NULL,
	[AddDate] [smalldatetime] NOT NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

GO
/****** Object:  Table [dbo].[bakmsEmailTempleteLog]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[bakmsEmailTempleteLog](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[msEmailTempleteId] [int] NULL,
	[msSqlID] [int] NOT NULL,
	[Name] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Title] [varchar](100) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[MailBody] [varchar](max) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[SubMailBody] [varchar](max) COLLATE Chinese_PRC_CI_AS NULL,
	[NoDataBody] [varchar](max) COLLATE Chinese_PRC_CI_AS NULL,
	[Status] [tinyint] NULL,
	[AddMan] [smallint] NOT NULL,
	[AddDate] [smalldatetime] NOT NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

GO
/****** Object:  Table [dbo].[bakmsEmailTitle]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[bakmsEmailTitle](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[msBodyTempleteId] [int] NULL,
	[Title] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[GoToServer] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[dcProvinceId] [tinyint] NOT NULL,
	[AddMan] [smallint] NOT NULL,
	[AddDate] [smalldatetime] NOT NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[bakmsEmailType]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[bakmsEmailType](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[Name] [nvarchar](100) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[msEmailTempleteId] [int] NOT NULL,
	[msSqlId] [int] NOT NULL,
	[AllowedSite] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL,
	[BannedSite] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL,
	[ProvinceIds] [varchar](200) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Sender] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Host] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[ParamValue] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL,
	[Status] [tinyint] NULL,
	[IsPause] [bit] NOT NULL,
	[VerifyMan] [smallint] NULL,
	[VerifyDate] [smalldatetime] NULL,
	[VerifyMessage] [varchar](500) COLLATE Chinese_PRC_CI_AS NULL,
	[AddMan] [smallint] NOT NULL,
	[AddDate] [smalldatetime] NOT NULL,
	[ViewMan] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[emailno] [int] NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[bakmsEmailTypeEdit]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[bakmsEmailTypeEdit](
	[ID] [int] NOT NULL,
	[Name] [nvarchar](100) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[msEmailTempleteId] [int] NOT NULL,
	[msSqlId] [int] NOT NULL,
	[AllowedSite] [varchar](200) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[BannedSite] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL,
	[ProvinceIds] [varchar](200) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Sender] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Host] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[ParamValue] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL,
	[Status] [tinyint] NULL,
	[IsPause] [bit] NULL,
	[VerifyMan] [smallint] NULL,
	[VerifyDate] [smalldatetime] NULL,
	[VerifyMessage] [varchar](500) COLLATE Chinese_PRC_CI_AS NULL,
	[AddMan] [smallint] NOT NULL,
	[AddDate] [smalldatetime] NULL,
	[emailno] [int] NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[bakmsProcess]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[bakmsProcess](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[msEmailTypeId] [int] NOT NULL,
	[dcSubSiteId] [smallint] NOT NULL,
	[Sender] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Host] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[msScheduleId] [int] NOT NULL,
	[MaxRunMinute] [smallint] NOT NULL,
	[SendInterval] [int] NULL,
	[NextRunTime] [smalldatetime] NULL,
	[RunStatus] [tinyint] NULL,
	[SendNumber] [int] NULL,
	[ccMail] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[ccRate] [smallint] NULL,
	[AddMan] [smallint] NOT NULL,
	[AddDate] [smalldatetime] NOT NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[bakmsProcessEdit]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[bakmsProcessEdit](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[msEmailTypeId] [int] NOT NULL,
	[dcSubSiteId] [smallint] NOT NULL,
	[Sender] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Host] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[msScheduleId] [int] NOT NULL,
	[MaxRunMinute] [smallint] NOT NULL,
	[SendInterval] [tinyint] NULL,
	[NextRunTime] [smalldatetime] NULL,
	[RunStatus] [tinyint] NULL,
	[SendNumber] [int] NULL,
	[ccMail] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[ccRate] [smallint] NULL,
	[AddMan] [smallint] NOT NULL,
	[AddDate] [smalldatetime] NOT NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[bakmsProcessLog]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[bakmsProcessLog](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[msProcessId] [int] NOT NULL,
	[BeginTime] [datetime] NOT NULL,
	[EndTime] [datetime] NULL,
	[EndStatus] [int] NOT NULL,
	[SendNumber] [int] NOT NULL,
	[SuccessNumber] [int] NOT NULL,
	[FailNumber] [int] NOT NULL,
	[Remark] [nvarchar](max) COLLATE Chinese_PRC_CI_AS NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

GO
/****** Object:  Table [dbo].[bakmsSchedule]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[bakmsSchedule](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[Name] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Enabled] [bit] NOT NULL,
	[FreqType] [tinyint] NOT NULL,
	[FreqInterval] [smallint] NULL,
	[FreqSubdayType] [tinyint] NULL,
	[FreqSubdayInterval] [smallint] NULL,
	[ActiveStartDate] [int] NOT NULL,
	[ActiveEndDate] [int] NOT NULL,
	[ActiveStartTime] [smallint] NOT NULL,
	[ActiveEndTime] [smallint] NOT NULL,
	[AddMan] [smallint] NULL,
	[AddDate] [smalldatetime] NOT NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[bakmsSql]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[bakmsSql](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[Name] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Sql] [varchar](max) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[ParamIn] [varchar](500) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[ParamOut] [varchar](500) COLLATE Chinese_PRC_CI_AS NULL,
	[SubSql] [varchar](max) COLLATE Chinese_PRC_CI_AS NULL,
	[SubParam] [varchar](500) COLLATE Chinese_PRC_CI_AS NULL,
	[Relation] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[AfterSendSql] [varchar](max) COLLATE Chinese_PRC_CI_AS NULL,
	[FinishedSql] [varchar](max) COLLATE Chinese_PRC_CI_AS NULL,
	[Remark] [nvarchar](500) COLLATE Chinese_PRC_CI_AS NULL,
	[ManagerUserId] [smallint] NOT NULL,
	[Status] [tinyint] NULL,
	[AddMan] [smallint] NOT NULL,
	[AddDate] [smalldatetime] NOT NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

GO
/****** Object:  Table [dbo].[bakrecruitment]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[bakrecruitment](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[RecruitmentDeptId] [int] NOT NULL,
	[RecruitmentName] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Brief] [varchar](max) COLLATE Chinese_PRC_CI_AS NULL,
	[BeginDate] [smalldatetime] NOT NULL,
	[EndDate] [smalldatetime] NOT NULL,
	[CityID] [varchar](4) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[RecruitmentPlaceId] [int] NOT NULL,
	[LinkMan] [nvarchar](10) COLLATE Chinese_PRC_CI_AS NULL,
	[Mobile] [varchar](11) COLLATE Chinese_PRC_CI_AS NULL,
	[Telephone] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL,
	[Fax] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL,
	[Email] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[qq] [varchar](10) COLLATE Chinese_PRC_CI_AS NULL,
	[OrderBy] [int] NOT NULL,
	[IsPause] [tinyint] NOT NULL,
	[PauseReason] [nvarchar](200) COLLATE Chinese_PRC_CI_AS NULL,
	[IsSchool] [bit] NOT NULL,
	[ViewNumber] [int] NOT NULL,
	[CompanyViewNumber] [int] NOT NULL,
	[PersonViewNumber] [int] NOT NULL,
	[InnerOrderBy] [smallint] NULL,
	[IsCompanyTop] [bit] NOT NULL,
	[IsPersonalTop] [bit] NOT NULL,
	[ManagerUserID] [smallint] NULL,
	[ModifyDate] [smalldatetime] NOT NULL,
	[AddDate] [smalldatetime] NULL,
	[MainID] [int] NULL,
	[RandNumber] [varchar](40) COLLATE Chinese_PRC_CI_AS NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

GO
/****** Object:  Table [dbo].[bakrecruitmentdept]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[bakrecruitmentdept](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[dcProvinceID] [smallint] NOT NULL,
	[Username] [varchar](20) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Password] [varchar](20) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[DeptName] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[LinkMan] [nvarchar](10) COLLATE Chinese_PRC_CI_AS NULL,
	[Mobile] [varchar](11) COLLATE Chinese_PRC_CI_AS NULL,
	[TelePhone] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL,
	[Fax] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL,
	[Email] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[qq] [varchar](10) COLLATE Chinese_PRC_CI_AS NULL,
	[LinkAddress] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[Brief] [nvarchar](max) COLLATE Chinese_PRC_CI_AS NULL,
	[CertFile] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[UpLoadTime] [smalldatetime] NULL,
	[VerifyMan] [smallint] NULL,
	[VerifyDate] [smalldatetime] NULL,
	[VerifyInfo] [nvarchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[CreditRating] [tinyint] NULL,
	[ModifyDate] [smalldatetime] NOT NULL,
	[RegDate] [smalldatetime] NOT NULL,
	[IsPause] [bit] NULL,
	[Description] [nvarchar](100) COLLATE Chinese_PRC_CI_AS NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

GO
/****** Object:  Table [dbo].[bakrecruitmentplace]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[bakrecruitmentplace](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[PlaceName] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Address] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[BusLine] [nvarchar](300) COLLATE Chinese_PRC_CI_AS NULL,
	[MapBarID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[VerifyMan] [smallint] NULL,
	[VerifyDate] [smalldatetime] NULL,
	[AddDate] [smalldatetime] NOT NULL,
	[dcRegionID] [varchar](6) COLLATE Chinese_PRC_CI_AS NULL,
	[MapBarId2] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[Lng] [decimal](8, 5) NULL,
	[Lat] [decimal](8, 5) NULL,
	[IsCreditRating] [bit] NULL,
	[IsCampus] [bit] NULL,
	[isBreak] [int] NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[BeiSenAds]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[BeiSenAds](
	[Id] [int] NOT NULL,
	[TenantId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[JobAdId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[JobAdName] [nvarchar](500) COLLATE Chinese_PRC_CI_AS NULL,
	[JobType] [nvarchar](500) COLLATE Chinese_PRC_CI_AS NULL,
	[LocID] [nvarchar](500) COLLATE Chinese_PRC_CI_AS NULL,
	[Salary] [nvarchar](500) COLLATE Chinese_PRC_CI_AS NULL,
	[Degree] [nvarchar](500) COLLATE Chinese_PRC_CI_AS NULL,
	[YearsofWorking] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[EndTime] [datetime] NULL,
	[Email] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[Status] [nvarchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[CreateDate] [datetime] NULL,
	[ModifiedDate] [datetime] NULL,
	[Adddate] [smalldatetime] NULL,
	[LastGetDate] [smalldatetime] NULL,
	[JobId] [int] NULL,
	[LinkMan] [smallint] NULL,
	[LinkDate] [smalldatetime] NULL,
 CONSTRAINT [PK_BeiSenAds] PRIMARY KEY CLUSTERED 
(
	[Id] 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].[BeiSenCompany]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[BeiSenCompany](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[TenantId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[Name] [nvarchar](500) COLLATE Chinese_PRC_CI_AS NULL,
	[Domain] [nvarchar](500) COLLATE Chinese_PRC_CI_AS NULL,
	[Abbreviation] [nvarchar](500) COLLATE Chinese_PRC_CI_AS NULL,
	[Address] [nvarchar](500) COLLATE Chinese_PRC_CI_AS NULL,
	[PostalCode] [nvarchar](500) COLLATE Chinese_PRC_CI_AS NULL,
	[EmailHost] [nvarchar](500) COLLATE Chinese_PRC_CI_AS NULL,
	[Logo] [varchar](500) COLLATE Chinese_PRC_CI_AS NULL,
	[AddDate] [smalldatetime] NULL,
	[cpMainId] [int] NULL,
	[LinkMan] [smallint] NULL,
	[LinkDate] [smalldatetime] NULL,
 CONSTRAINT [PK_BeiSenCompany] PRIMARY KEY CLUSTERED 
(
	[Id] 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].[BeisenJobApply]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[BeisenJobApply](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[ExJobApplyID] [int] NOT NULL,
	[JobId] [int] NULL,
	[cvMainId] [int] NULL,
	[BeiSenResumeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[BeiSenResumeSyncId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[BeiSenHasApply] [tinyint] NULL,
	[BeiSenProcess] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[BeiSenProcessNew] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[LastGetDate] [datetime] NULL,
	[cvText] [varchar](max) COLLATE Chinese_PRC_CI_AS NULL,
 CONSTRAINT [PK_BeisenJobApply] PRIMARY KEY CLUSTERED 
(
	[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [FOthers]
) ON [FOthers] TEXTIMAGE_ON [FOthers]

GO
/****** Object:  Table [dbo].[BestEmployer]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[BestEmployer](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[cpMainID] [int] NOT NULL,
	[CompanyName] [varchar](100) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[AddDate] [smalldatetime] NOT NULL,
 CONSTRAINT [PK_BestEmployer] PRIMARY KEY CLUSTERED 
(
	[ID] 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].[BestEmployerVote]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[BestEmployerVote](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[BestEmployerID] [int] NOT NULL,
	[OpenID] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[AddDate] [smalldatetime] NOT NULL,
 CONSTRAINT [PK_BestEmployerVote] PRIMARY KEY CLUSTERED 
(
	[ID] 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].[bsAskClickLog]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[bsAskClickLog](
	[CountMonth] [varchar](6) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[bsAskInfoID] [int] NOT NULL,
	[ClickNumber] [int] NOT NULL,
	[Increase] [int] NOT NULL,
 CONSTRAINT [PK_bsAskClickLog] PRIMARY KEY CLUSTERED 
(
	[bsAskInfoID] ASC,
	[CountMonth] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Market]
) ON [Market]

GO
/****** Object:  Table [dbo].[bsASKInfo]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[bsASKInfo](
	[ID] [int] IDENTITY(1,1) NOT FOR REPLICATION NOT NULL,
	[Title] [varchar](300) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Url] [varchar](200) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[ClassID] [int] NULL,
	[Question] [nvarchar](max) COLLATE Chinese_PRC_CI_AS NULL,
	[Answer] [nvarchar](max) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[TypeID] [int] NOT NULL,
	[Mark] [nvarchar](30) COLLATE Chinese_PRC_CI_AS NULL,
	[UserName] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL,
	[AddUserID] [smallint] NULL,
	[AddDate] [datetime] NOT NULL,
	[Comment] [nvarchar](500) COLLATE Chinese_PRC_CI_AS NULL,
	[SolveDate] [datetime] NOT NULL,
	[IsOnline] [bit] NOT NULL,
	[UpdateDate] [datetime] NULL,
	[ProvinceIds] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[GetWay] [bit] NULL,
	[ReferUrl] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL,
	[ClickNumber] [int] NULL,
 CONSTRAINT [PK_bsASKInfo] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Market]
) ON [Market] TEXTIMAGE_ON [Market]

GO
/****** Object:  Table [dbo].[bsAskInfoDayReport]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[bsAskInfoDayReport](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[CountDate] [varchar](8) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[bsAskInfoId] [int] NOT NULL,
	[VisitNumber] [int] NULL,
 CONSTRAINT [PK_bsAskInfoDayReport] PRIMARY KEY NONCLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [FOthers]

GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_BsAskInfoDayReport_CountDate]    Script Date: 2018/9/25 12:40:11 ******/
CREATE CLUSTERED INDEX [IX_BsAskInfoDayReport_CountDate] ON [dbo].[bsAskInfoDayReport]
(
	[CountDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [FOthers]
GO
/****** Object:  Table [dbo].[bsASKSiteClass]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[bsASKSiteClass](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[Weburl] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL,
	[ClassName] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[ClassUrl] [varchar](200) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[classStartID] [int] NULL,
	[classStopID] [int] NULL,
	[Encoding] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[startHtml] [nvarchar](1000) COLLATE Chinese_PRC_CI_AS NULL,
	[EndHtml] [nvarchar](1000) COLLATE Chinese_PRC_CI_AS NULL,
	[linkStart] [nvarchar](1000) COLLATE Chinese_PRC_CI_AS NULL,
	[linkEnd] [nvarchar](1000) COLLATE Chinese_PRC_CI_AS NULL,
	[TitleStart] [nvarchar](1000) COLLATE Chinese_PRC_CI_AS NULL,
	[TitleEnd] [nvarchar](1000) COLLATE Chinese_PRC_CI_AS NULL,
	[QuestionStart] [nvarchar](1000) COLLATE Chinese_PRC_CI_AS NULL,
	[QuestionEnd] [nvarchar](1000) COLLATE Chinese_PRC_CI_AS NULL,
	[AnswerStart] [nvarchar](1000) COLLATE Chinese_PRC_CI_AS NULL,
	[AnswerEnd] [nvarchar](1000) COLLATE Chinese_PRC_CI_AS NULL,
	[SolveDateStart] [nvarchar](1000) COLLATE Chinese_PRC_CI_AS NULL,
	[SolveDateEnd] [nvarchar](1000) COLLATE Chinese_PRC_CI_AS NULL,
	[AnswerStart2] [nvarchar](1000) COLLATE Chinese_PRC_CI_AS NULL,
	[AnswerEnd2] [nvarchar](1000) COLLATE Chinese_PRC_CI_AS NULL,
	[SolveDateStart2] [nvarchar](1000) COLLATE Chinese_PRC_CI_AS NULL,
	[SolveDateEnd2] [nvarchar](1000) COLLATE Chinese_PRC_CI_AS NULL,
	[PageGrow] [int] NULL,
 CONSTRAINT [PK_bsASKSiteClass] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Market]
) ON [Market]

GO
/****** Object:  Table [dbo].[bsASKTagInfo]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[bsASKTagInfo](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[TagName] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Url] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL,
 CONSTRAINT [PK_bsASKTagInfo] PRIMARY KEY CLUSTERED 
(
	[ID] 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].[bsASKTypeSet]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[bsASKTypeSet](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[TypeName] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[OrderNo] [smallint] NULL,
 CONSTRAINT [PK_bsASKTypeSet] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Market]
) ON [Market]

GO
/****** Object:  Table [dbo].[bsBackLogin]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[bsBackLogin](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[UniqueID] [varchar](40) COLLATE Chinese_PRC_CI_AS NULL,
	[funType] [int] NULL,
	[ManagerUserid] [smallint] NOT NULL,
	[AddDate] [smalldatetime] NOT NULL,
	[Url] [varchar](150) COLLATE Chinese_PRC_CI_AS NULL,
	[OpenType] [tinyint] NULL,
 CONSTRAINT [PK_bsAskLogin] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers]
) ON [BOthers]

GO
/****** Object:  Table [dbo].[bsConsultantFreeOrder]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[bsConsultantFreeOrder](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[ConsultantId] [smallint] NOT NULL,
	[OpenDate] [smalldatetime] NOT NULL,
	[OrderID] [int] NOT NULL,
 CONSTRAINT [PK_bsConsultantFreeOrder] PRIMARY KEY CLUSTERED 
(
	[id] 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].[bsConsultantFreeOrderSet]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[bsConsultantFreeOrderSet](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[ConsultantId] [smallint] NOT NULL,
	[Number] [int] NOT NULL,
	[type] [tinyint] NULL,
 CONSTRAINT [PK_bsConsultantFreeOrderSet] PRIMARY KEY CLUSTERED 
(
	[id] 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].[bsConsultantList]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[bsConsultantList](
	[cpMainID] [int] NOT NULL,
	[VipType] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[ServiceEndDate] [datetime] NULL,
	[RemainQuotaSum] [int] NULL,
	[VipMonth] [int] NULL,
	[caOrderLastOpenDate] [smalldatetime] NULL,
	[ContactLastCloseDate] [smalldatetime] NULL,
	[LicenceVerifyDate] [smalldatetime] NULL,
	[caCvQuotaCount] [int] NULL,
	[bsCpStatusAddDate] [smalldatetime] NULL,
	[LastContactDate] [smalldatetime] NULL,
	[caActiveCount] [int] NULL,
	[caFeePageViewAddDate] [smalldatetime] NULL,
	[JobViewNumber] [int] NULL,
	[ContactLastCloseID] [int] NULL,
	[LastContactID] [int] NULL,
	[ContactLastCloseAddDate] [datetime] NULL,
	[LastContactAddDate] [datetime] NULL,
	[NotOpen1] [int] NULL,
	[NotOpen2] [int] NULL,
	[NotOpen3] [int] NULL,
	[NotOpen7] [int] NULL,
	[NotOpen14] [int] NULL,
	[NotOpen30] [int] NULL,
	[CvViewNumber] [int] NULL,
 CONSTRAINT [PK_bsConsultantList] PRIMARY KEY CLUSTERED 
(
	[cpMainID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers]
) ON [BOthers]

GO
/****** Object:  Table [dbo].[bsCpBackLogin]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[bsCpBackLogin](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[UnqueID] [varchar](20) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[cpMainID] [int] NOT NULL,
	[caMainID] [int] NOT NULL,
	[ManagerUserID] [smallint] NOT NULL,
	[AddDate] [smalldatetime] NOT NULL,
	[HasLogin] [bit] NOT NULL,
 CONSTRAINT [PK_bsCpBackLogin] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers]
) ON [BOthers]

GO
/****** Object:  Table [dbo].[bsCpBackLogin0317]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[bsCpBackLogin0317](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[UnqueID] [varchar](20) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[cpMainID] [int] NOT NULL,
	[caMainID] [int] NOT NULL,
	[ManagerUserID] [smallint] NOT NULL,
	[AddDate] [smalldatetime] NOT NULL,
	[HasLogin] [bit] NOT NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[bsCpBackLoginLog]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[bsCpBackLoginLog](
	[ID] [int] NOT NULL,
	[UnqueID] [varchar](20) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[cpMainID] [int] NOT NULL,
	[caMainID] [int] NOT NULL,
	[ManagerUserID] [smallint] NOT NULL,
	[AddDate] [smalldatetime] NULL,
	[HasLogin] [bit] NOT NULL
) ON [BOthers]

GO
/****** Object:  Table [dbo].[bsCpModify]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[bsCpModify](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[cpMainID] [int] NOT NULL,
	[caMainID] [int] NOT NULL,
	[SubID] [int] NULL,
	[Location] [char](4) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[AddDate] [smalldatetime] NOT NULL,
	[ColValue] [nvarchar](max) COLLATE Chinese_PRC_CI_AS NULL,
	[VerifyInfo] [nvarchar](500) COLLATE Chinese_PRC_CI_AS NULL,
	[FilterWord] [nvarchar](20) COLLATE Chinese_PRC_CI_AS NULL,
 CONSTRAINT [PK_bsCpModify] PRIMARY KEY NONCLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers]
) ON [BOthers] TEXTIMAGE_ON [BOthers]

GO
/****** Object:  Index [IX_bsCpModify_cpMainID]    Script Date: 2018/9/25 12:40:11 ******/
CREATE CLUSTERED INDEX [IX_bsCpModify_cpMainID] ON [dbo].[bsCpModify]
(
	[cpMainID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers]
GO
/****** Object:  Table [dbo].[bsCpStatus]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[bsCpStatus](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[cpMainID] [int] NOT NULL,
	[caMainID] [int] NULL,
	[StatusID] [tinyint] NOT NULL,
	[ApplyInfo] [nvarchar](200) COLLATE Chinese_PRC_CI_AS NULL,
	[AddDate] [smalldatetime] NOT NULL,
	[HasPassed] [bit] NULL,
	[VerifyMan] [nchar](10) COLLATE Chinese_PRC_CI_AS NULL,
	[VerifyInfo] [nvarchar](500) COLLATE Chinese_PRC_CI_AS NULL,
	[VerifyDate] [smalldatetime] NULL,
 CONSTRAINT [PK_bsCpStatus] PRIMARY KEY NONCLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers]
) ON [BOthers]

GO
/****** Object:  Index [IX_bsCpStatus_cpMainID]    Script Date: 2018/9/25 12:40:11 ******/
CREATE CLUSTERED INDEX [IX_bsCpStatus_cpMainID] ON [dbo].[bsCpStatus]
(
	[cpMainID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers]
GO
/****** Object:  Table [dbo].[bsCpVerify]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[bsCpVerify](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[cpMainID] [int] NOT NULL,
	[VerifyMan] [smallint] NOT NULL,
	[VerifyDate] [smalldatetime] NOT NULL,
	[VerifyResult] [tinyint] NOT NULL,
	[VerifyInfo] [nvarchar](200) COLLATE Chinese_PRC_CI_AS NULL,
 CONSTRAINT [PK_bsCpVerify] PRIMARY KEY NONCLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers]
) ON [BOthers]

GO
/****** Object:  Index [IX_bsCpVerify_cpMainID]    Script Date: 2018/9/25 12:40:11 ******/
CREATE CLUSTERED INDEX [IX_bsCpVerify_cpMainID] ON [dbo].[bsCpVerify]
(
	[cpMainID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers]
GO
/****** Object:  Table [dbo].[bsCpVerifyLog]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[bsCpVerifyLog](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[bsCpVerifyID] [int] NULL,
	[SubID] [int] NULL,
	[Location] [char](4) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[AddDate] [smalldatetime] NULL,
	[OldValue] [nvarchar](max) COLLATE Chinese_PRC_CI_AS NULL,
	[VerifyResult] [bit] NOT NULL,
	[VerifyInfo] [nvarchar](500) COLLATE Chinese_PRC_CI_AS NULL,
 CONSTRAINT [PK_bsCpVerifyLog] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers]
) ON [BOthers] TEXTIMAGE_ON [PRIMARY]

GO
/****** Object:  Table [dbo].[bsCvModify]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[bsCvModify](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[paMainID] [int] NOT NULL,
	[cvMainID] [int] NULL,
	[SubID] [int] NULL,
	[Location] [char](4) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[AddDate] [smalldatetime] NULL,
	[ColValue] [nvarchar](max) COLLATE Chinese_PRC_CI_AS NULL,
	[VerifyInfo] [nvarchar](200) COLLATE Chinese_PRC_CI_AS NULL,
 CONSTRAINT [PK_bsCvModify] PRIMARY KEY NONCLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers]
) ON [BOthers] TEXTIMAGE_ON [BOthers]

GO
/****** Object:  Index [IX_bsCvModify_paMainID]    Script Date: 2018/9/25 12:40:11 ******/
CREATE CLUSTERED INDEX [IX_bsCvModify_paMainID] ON [dbo].[bsCvModify]
(
	[paMainID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers]
GO
/****** Object:  Table [dbo].[bsCvReview]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[bsCvReview](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[cvMainID] [int] NOT NULL,
	[VerifyMan] [smallint] NOT NULL,
	[VerifyInfo] [nvarchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[AddDate] [smalldatetime] NOT NULL,
 CONSTRAINT [PK_bsCvReview] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers]
) ON [BOthers]

GO
/****** Object:  Table [dbo].[bsCvVerify]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[bsCvVerify](
	[ID] [int] IDENTITY(1,1) NOT FOR REPLICATION NOT NULL,
	[cvMainID] [int] NOT NULL,
	[VerifyMan] [smallint] NOT NULL,
	[VerifyDate] [smalldatetime] NOT NULL,
	[VerifyResult] [tinyint] NOT NULL,
	[VerifyInfo] [nvarchar](200) COLLATE Chinese_PRC_CI_AS NOT NULL,
 CONSTRAINT [PK_bsCvVerify] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers]
) ON [BOthers]

GO
/****** Object:  Table [dbo].[bsCvVerifyLog]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[bsCvVerifyLog](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[bsCvVerifyID] [int] NULL,
	[cvMainID] [int] NULL,
	[SubID] [int] NULL,
	[Location] [char](4) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[AddDate] [smalldatetime] NULL,
	[OldValue] [varchar](max) COLLATE Chinese_PRC_CI_AS NULL,
	[VerifyResult] [bit] NOT NULL,
	[VerifyInfo] [nvarchar](500) COLLATE Chinese_PRC_CI_AS NULL,
 CONSTRAINT [PK_bsCvVerifyLog] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers]
) ON [BOthers] TEXTIMAGE_ON [BOthers]

GO
/****** Object:  Table [dbo].[bsDeadCompany]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[bsDeadCompany](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[cpMainID] [int] NULL,
	[ContactDate] [smalldatetime] NULL,
	[ContactMan] [int] NULL,
	[ContactResult] [int] NULL,
	[DeadDate] [smalldatetime] NULL,
	[ActiveDate] [smalldatetime] NULL,
	[ReMark] [nvarchar](500) COLLATE Chinese_PRC_CI_AS NULL,
	[AddDate] [smalldatetime] NULL,
 CONSTRAINT [PK_bsDeadCompnay] PRIMARY KEY CLUSTERED 
(
	[ID] 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].[bsDeleteFile]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[bsDeleteFile](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[FileType] [tinyint] NULL,
	[FileID] [int] NOT NULL,
	[FileName] [varchar](200) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[FilePath] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[IsDelete] [bit] NOT NULL,
	[DeleteDate] [smalldatetime] NULL,
	[AddDate] [smalldatetime] NOT NULL,
 CONSTRAINT [PK_bsDeleteFile] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers]
) ON [BOthers]

GO
/****** Object:  Table [dbo].[bsForeign]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[bsForeign](
	[ID] [int] NOT NULL,
	[CompanyName] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[LinkMan] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[TelePhone] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[Mobile] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[LoginIp] [varchar](31) COLLATE Chinese_PRC_CI_AS NULL,
	[LoginDate] [smalldatetime] NULL,
	[IpAddress] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[CompanyAddress] [nvarchar](100) COLLATE Chinese_PRC_CI_AS NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[bsJobProblem]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[bsJobProblem](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[cpMainID] [int] NOT NULL,
	[Reason] [nvarchar](200) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[AddDate] [smalldatetime] NOT NULL,
	[AddMan] [smallint] NULL,
 CONSTRAINT [PK_bsJobProblem] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers]
) ON [BOthers]

GO
/****** Object:  Table [dbo].[bsManagerMac]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[bsManagerMac](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[ManagerUserID] [varchar](3) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Mac] [varchar](20) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Remark] [nvarchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[AddDate] [smalldatetime] NULL,
 CONSTRAINT [PK_bsManagerMac] PRIMARY KEY CLUSTERED 
(
	[ManagerUserID] ASC,
	[Mac] 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].[bsManagerUserAction]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[bsManagerUserAction](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[cpMainID] [int] NOT NULL,
	[Action] [varchar](300) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Reason] [varchar](500) COLLATE Chinese_PRC_CI_AS NULL,
	[ManagerUserID] [int] NOT NULL,
	[AddDate] [datetime] NOT NULL,
 CONSTRAINT [PK_bsManagerUserAction] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers]
) ON [BOthers]

GO
/****** Object:  Table [dbo].[bsMobileMessage]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[bsMobileMessage](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[dcProvinceId] [tinyint] NOT NULL,
	[Message] [nvarchar](300) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[BeginDate] [smalldatetime] NOT NULL,
	[EndDate] [smalldatetime] NOT NULL,
	[AddMan] [smallint] NOT NULL,
	[AddDate] [smalldatetime] NOT NULL,
 CONSTRAINT [PK_bsMobileContent] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers]
) ON [BOthers]

GO
/****** Object:  Table [dbo].[bsMobileSpread]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[bsMobileSpread](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[ProvinceId] [tinyint] NOT NULL,
	[MobileNo] [varchar](11) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[SendTime] [tinyint] NOT NULL,
	[HasReturn]  AS (case when [ReturnDate] IS NULL then (0) else (1) end),
	[HasAccount]  AS (case when [AccountDate] IS NULL then (0) else (1) end),
	[ReturnDate] [smalldatetime] NULL,
	[AccountDate] [smalldatetime] NULL,
	[AddMan] [smallint] NOT NULL,
	[AddDate] [smalldatetime] NOT NULL,
	[SendStatus] [tinyint] NULL,
	[UserType] [bit] NULL,
	[Companyname] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[ExportDate] [int] NULL,
	[BatchId] [int] NULL,
	[RelatedID] [int] NULL,
 CONSTRAINT [PK_bsMobileSpread] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers]
) ON [BOthers]

GO
/****** Object:  Table [dbo].[bsPaBackLogin]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[bsPaBackLogin](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[UnqueID] [varchar](20) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[paMainID] [int] NOT NULL,
	[ManagerUserID] [smallint] NOT NULL,
	[AddDate] [smalldatetime] NOT NULL,
	[HasLogin] [bit] NOT NULL,
 CONSTRAINT [PK_bsPaBackLogin] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers]
) ON [BOthers]

GO
/****** Object:  Table [dbo].[bsRtxStatus]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[bsRtxStatus](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[ManagerUserId] [smallint] NOT NULL,
	[CheckDay] [char](8) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[RtxStatus] [tinyint] NOT NULL,
	[PreRtxStatus] [tinyint] NOT NULL,
	[OnlineSecond] [decimal](18, 3) NOT NULL,
	[OfflineSecond] [decimal](18, 3) NOT NULL,
	[LeaveSecond] [decimal](18, 3) NOT NULL,
	[CheckTime] [datetime] NOT NULL,
	[AllOnlineTime] [int] NOT NULL,
 CONSTRAINT [PK_bsRtxStatus] PRIMARY KEY NONCLUSTERED 
(
	[ManagerUserId] ASC,
	[CheckDay] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers]
) ON [BOthers]

GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_bsRtxStatus_CheckDay]    Script Date: 2018/9/25 12:40:11 ******/
CREATE CLUSTERED INDEX [IX_bsRtxStatus_CheckDay] ON [dbo].[bsRtxStatus]
(
	[CheckDay] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers]
GO
/****** Object:  Table [dbo].[bsRtxStatusLog]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[bsRtxStatusLog](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[ManagerUserID] [smallint] NOT NULL,
	[RtxStatus] [tinyint] NOT NULL,
	[LogTime] [datetime] NOT NULL,
 CONSTRAINT [PK_bsRtxStatusLog] PRIMARY KEY NONCLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers]
) ON [BOthers]

GO
/****** Object:  Index [IX_bsRtxStatusLog_ManagerUserID]    Script Date: 2018/9/25 12:40:11 ******/
CREATE CLUSTERED INDEX [IX_bsRtxStatusLog_ManagerUserID] ON [dbo].[bsRtxStatusLog]
(
	[ManagerUserID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers]
GO
/****** Object:  Table [dbo].[bsSourceDetailCountlog]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[bsSourceDetailCountlog](
	[BsSourceDetailId] [int] NULL,
	[Url] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL,
	[AddDate] [datetime] NULL,
	[u] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[bsSourceRefererCount]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[bsSourceRefererCount](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[SubSiteID] [int] NOT NULL,
	[CountDate] [varchar](8) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Referer] [varchar](500) COLLATE Chinese_PRC_CI_AS NULL,
	[HowMany] [int] NULL,
	[TypeID] [tinyint] NULL,
	[SiteType] [tinyint] NULL,
 CONSTRAINT [PK_SourceRefererCount] PRIMARY KEY CLUSTERED 
(
	[ID] 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].[bsSqlLog]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[bsSqlLog](
	[ManagerUserId] [smallint] NOT NULL,
	[sql] [varchar](max) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[adddate] [smalldatetime] NOT NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

GO
/****** Object:  Table [dbo].[BsTableSizeLog]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[BsTableSizeLog](
	[Coutdate] [varchar](8) COLLATE Chinese_PRC_CI_AS NULL,
	[TableName] [sysname] COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Rows] [int] NULL
) ON [BOthers]

GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [PK_bsTableSizeLog]    Script Date: 2018/9/25 12:40:11 ******/
CREATE UNIQUE CLUSTERED INDEX [PK_bsTableSizeLog] ON [dbo].[BsTableSizeLog]
(
	[Coutdate] ASC,
	[TableName] 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 [BOthers]
GO
/****** Object:  Table [dbo].[caActiveLog]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[caActiveLog](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[cpMainID] [int] NOT NULL,
	[caMainID] [int] NOT NULL,
	[cvMainID] [int] NULL,
	[caOrderId] [int] NOT NULL,
	[paName] [nvarchar](6) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[IP] [varchar](39) COLLATE Chinese_PRC_CI_AS NULL,
	[RemainQuota] [smallint] NOT NULL,
	[AddDate] [smalldatetime] NOT NULL,
 CONSTRAINT [PK_caActiveLog] PRIMARY KEY NONCLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [CP]
) ON [CP]

GO
/****** Object:  Index [IX_caActiveLog_cpMainID]    Script Date: 2018/9/25 12:40:11 ******/
CREATE CLUSTERED INDEX [IX_caActiveLog_cpMainID] ON [dbo].[caActiveLog]
(
	[cpMainID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [CP]
GO
/****** Object:  Table [dbo].[caActiveStatus]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[caActiveStatus](
	[caMainId] [int] NOT NULL,
	[IsOnline] [bit] NOT NULL,
	[IsVi] [bit] NOT NULL,
	[ViPlanId] [int] NULL,
	[InterviewDate] [datetime] NULL,
 CONSTRAINT [PK_caActiveStatus] PRIMARY KEY CLUSTERED 
(
	[caMainId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [CP]
) ON [CP]

GO
/****** Object:  Table [dbo].[caBalanceLog]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[caBalanceLog](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[cpMainID] [int] NOT NULL,
	[caMainID] [int] NOT NULL,
	[cvMainID] [int] NULL,
	[IsAgent] [bit] NOT NULL,
	[ReduceMoney] [int] NOT NULL,
	[Balance] [int] NOT NULL,
	[IP] [varchar](31) COLLATE Chinese_PRC_CI_AS NULL,
	[AddDate] [smalldatetime] NOT NULL,
	[BalanceType] [tinyint] NULL,
 CONSTRAINT [PK_caBalanceLog] PRIMARY KEY NONCLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [CP]
) ON [CP]

GO
/****** Object:  Index [IX_caBalanceLog_cpMainID]    Script Date: 2018/9/25 12:40:11 ******/
CREATE CLUSTERED INDEX [IX_caBalanceLog_cpMainID] ON [dbo].[caBalanceLog]
(
	[cpMainID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [CP]
GO
/****** Object:  Table [dbo].[caContact]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[caContact](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[caMainID] [int] NOT NULL,
	[cpMainID] [int] NOT NULL,
	[Telephone] [varchar](25) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Name] [nvarchar](6) COLLATE Chinese_PRC_CI_AS NULL,
	[AddDate] [smalldatetime] NOT NULL,
	[ReplyDate] [smalldatetime] NULL,
 CONSTRAINT [PK_caContact] PRIMARY KEY CLUSTERED 
(
	[ID] 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].[CaCvApplyDeleted]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[CaCvApplyDeleted](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[JobId] [int] NOT NULL,
	[JobName] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[CvMainId] [int] NOT NULL,
	[ApplyDate] [smalldatetime] NOT NULL,
	[Adddate] [smalldatetime] NOT NULL,
	[Reply] [tinyint] NULL,
	[cvDeleted] [bit] NULL,
	[jobDeleted] [bit] NULL,
 CONSTRAINT [PK_CaCvApplyDeleted] PRIMARY KEY NONCLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [CP]

GO
/****** Object:  Index [IX_caCvApplyDeleted_Jobid]    Script Date: 2018/9/25 12:40:11 ******/
CREATE CLUSTERED INDEX [IX_caCvApplyDeleted_Jobid] ON [dbo].[CaCvApplyDeleted]
(
	[JobId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [CP]
GO
/****** Object:  Table [dbo].[caCvFinder]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[caCvFinder](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[caMainID] [int] NOT NULL,
	[Name] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[dcJobTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[dcRegionID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[dcIndustryID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[dcSalaryID] [int] NULL,
	[IsNegotiable] [bit] NULL,
	[dcJobTypeIDOld] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[dcIndustryIDOld] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[IncludeOld] [bit] NULL,
	[MinExperience] [tinyint] NULL,
	[KeyWord] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[SubNodeNum] [tinyint] NULL,
	[Education] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[Standard] [bit] NULL,
	[EducationName] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL,
	[dcMajorID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[Graduation] [int] NULL,
	[LanguageType] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[Gender] [tinyint] NULL,
	[MinAge] [tinyint] NULL,
	[MaxAge] [tinyint] NULL,
	[LivePlace] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[AccountPlace] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[SortType] [tinyint] NULL,
	[cvMainID] [int] NULL,
	[IsExpand] [bit] NULL,
	[AddDate] [smalldatetime] NULL,
	[MobilePlace] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[MinHeight] [tinyint] NULL,
	[MaxHeight] [tinyint] NULL,
	[EmployType] [tinyint] NULL,
	[EmailSent] [smallint] NULL,
	[EmailEndDate] [smalldatetime] NULL,
	[LastEmailDate] [smalldatetime] NULL,
	[EmailNumber] [tinyint] NULL,
	[Email] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
 CONSTRAINT [PK_caCvFinder] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [CP]
) ON [CP]

GO
/****** Object:  Table [dbo].[caCvIntention]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[caCvIntention](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[caMainID] [int] NOT NULL,
	[JobId] [int] NOT NULL,
	[cvMainID] [int] NOT NULL,
	[Reply] [tinyint] NULL,
	[ReplyDate] [smalldatetime] NULL,
	[PersonDeleted] [bit] NULL,
	[CompanyDeleted] [bit] NULL,
	[AddDate] [smalldatetime] NULL,
PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [CP]
) ON [CP]

GO
/****** Object:  Table [dbo].[caCvRemark]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[caCvRemark](
	[ID] [int] IDENTITY(1,1) NOT FOR REPLICATION NOT NULL,
	[caMainID] [int] NOT NULL,
	[Remark] [varchar](200) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[AddDate] [smalldatetime] NOT NULL,
	[cvMainID] [int] NOT NULL,
 CONSTRAINT [PK_caCvRemark] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [CP]
) ON [CP]

GO
/****** Object:  Table [dbo].[caCvviewCntLog]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[caCvviewCntLog](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[camainId] [int] NULL,
	[cpMainId] [int] NULL,
	[cvViewCnt] [int] NULL,
	[downLoadCvViewCnt] [int] NULL,
	[exjobapplyViewCnt] [int] NULL,
	[adddate] [smalldatetime] NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[caCvViewLog]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[caCvViewLog](
	[cvMainID] [int] NOT NULL,
	[caMainID] [int] NOT NULL,
	[AddDate] [smalldatetime] NOT NULL,
 CONSTRAINT [PK_caCvViewLog] PRIMARY KEY NONCLUSTERED 
(
	[cvMainID] ASC,
	[caMainID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [CP]
) ON [CP]

GO
/****** Object:  Index [IX_caCvViewLog_cvMainID]    Script Date: 2018/9/25 12:40:11 ******/
CREATE CLUSTERED INDEX [IX_caCvViewLog_cvMainID] ON [dbo].[caCvViewLog]
(
	[cvMainID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [CP]
GO
/****** Object:  Table [dbo].[caDailyGiftLog]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[caDailyGiftLog](
	[ConsumeDate] [varchar](8) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[cpMainID] [int] NOT NULL,
	[caMainID] [int] NOT NULL,
	[cvMainID] [int] NOT NULL,
	[paName] [nvarchar](6) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[IP] [varchar](31) COLLATE Chinese_PRC_CI_AS NULL,
	[AddDate] [smalldatetime] NOT NULL,
	[Type] [int] NULL,
 CONSTRAINT [PK_caDailyGiftLog] PRIMARY KEY NONCLUSTERED 
(
	[cpMainID] ASC,
	[cvMainID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [CP]
) ON [CP]

GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_caDailyGiftLog_ConsumeDate]    Script Date: 2018/9/25 12:40:11 ******/
CREATE CLUSTERED INDEX [IX_caDailyGiftLog_ConsumeDate] ON [dbo].[caDailyGiftLog]
(
	[ConsumeDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [CP]
GO
/****** Object:  Table [dbo].[caFavorate]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[caFavorate](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[caMainID] [int] NOT NULL,
	[JobId] [int] NOT NULL,
	[cvMainID] [int] NOT NULL,
	[caFavorateMarkID] [int] NULL,
	[AddDate] [smalldatetime] NOT NULL,
 CONSTRAINT [PK_caFavorate] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [CP]
) ON [CP]

GO
/****** Object:  Table [dbo].[caFavorateMark]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[caFavorateMark](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[caMainID] [int] NOT NULL,
	[Mark] [varchar](20) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[AddDate] [smalldatetime] NOT NULL,
 CONSTRAINT [PK_caFavorateMark] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [CP]
) ON [CP]

GO
/****** Object:  Table [dbo].[caFeedback]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[caFeedback](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[caMainID] [int] NOT NULL,
	[dcProvinceID] [tinyint] NOT NULL,
	[IP] [varchar](39) COLLATE Chinese_PRC_CI_AS NULL,
	[Name] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Telephone] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[Email] [varchar](100) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Message] [nvarchar](2000) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[AddDate] [smalldatetime] NOT NULL,
	[IsReply] [bit] NOT NULL,
	[ReplyMessage] [nvarchar](2000) COLLATE Chinese_PRC_CI_AS NULL,
	[ReplyDate] [smalldatetime] NULL,
	[ReplyMan] [int] NULL,
	[ViewDate] [smalldatetime] NULL,
	[HomePage] [bit] NULL,
 CONSTRAINT [PK_caFeedback] PRIMARY KEY NONCLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [CP]
) ON [CP]

GO
/****** Object:  Index [IX_caFeedback_caMainID]    Script Date: 2018/9/25 12:40:11 ******/
CREATE CLUSTERED INDEX [IX_caFeedback_caMainID] ON [dbo].[caFeedback]
(
	[caMainID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [CP]
GO
/****** Object:  Table [dbo].[caFeePageViewLog]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[caFeePageViewLog](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[caMainID] [int] NOT NULL,
	[FeePageID] [tinyint] NOT NULL,
	[AddDate] [smalldatetime] NOT NULL,
 CONSTRAINT [PK_caFeePageViewLog] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [CP]
) ON [CP]

GO
/****** Object:  Table [dbo].[caGetPasswordLog]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[caGetPasswordLog](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[caMainID] [int] NOT NULL,
	[UserNameIn] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[EmailIn] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[VerifyCode] [char](4) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[IP] [varchar](39) COLLATE Chinese_PRC_CI_AS NULL,
	[UserName] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Email] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[AddDate] [smalldatetime] NOT NULL,
	[Mobile] [varchar](13) COLLATE Chinese_PRC_CI_AS NULL,
	[UniqueId] [varchar](40) COLLATE Chinese_PRC_CI_AS NULL,
	[ActivateCode] [varchar](6) COLLATE Chinese_PRC_CI_AS NULL,
	[AskNo] [varchar](40) COLLATE Chinese_PRC_CI_AS NULL,
	[IsReset] [bit] NULL,
 CONSTRAINT [PK_caGetPasswordLog] PRIMARY KEY NONCLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [CP]
) ON [CP]

GO
/****** Object:  Table [dbo].[caGetSecondPasswordLog]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[caGetSecondPasswordLog](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[caMainID] [int] NOT NULL,
	[ActivateCode] [varchar](6) COLLATE Chinese_PRC_CI_AS NULL,
	[UniqueId] [varchar](40) COLLATE Chinese_PRC_CI_AS NULL,
	[IsReset] [bit] NULL,
	[IP] [varchar](39) COLLATE Chinese_PRC_CI_AS NULL,
	[AddDate] [smalldatetime] NOT NULL,
 CONSTRAINT [PK_caGetSecondPasswordLog] PRIMARY KEY NONCLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [CP]
) ON [CP]

GO
/****** Object:  Table [dbo].[caInterviewTemplate]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[caInterviewTemplate](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[caMainID] [int] NOT NULL,
	[Title] [varchar](20) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[InterviewDate] [varchar](100) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[InterViewPlace] [nvarchar](100) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[LinkMan] [nvarchar](6) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Telephone] [varchar](20) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Remark] [varchar](1000) COLLATE Chinese_PRC_CI_AS NULL,
	[AddDate] [smalldatetime] NOT NULL,
 CONSTRAINT [PK_caInterviewTemplate] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [CP]
) ON [CP]

GO
/****** Object:  Table [dbo].[CaIosBind]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[CaIosBind](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[caMainID] [int] NOT NULL,
	[UniqueID] [varchar](100) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Adddate] [smalldatetime] NOT NULL,
	[ClientType] [tinyint] NULL,
 CONSTRAINT [PK_CaIosBind] PRIMARY KEY CLUSTERED 
(
	[id] 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].[caJobCvMatch]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[caJobCvMatch](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[JobID] [int] NOT NULL,
	[MatchCvMainID] [int] NOT NULL,
	[DataSource] [tinyint] NULL,
	[PushDate] [datetime] NULL,
	[AddDate] [datetime] NULL,
	[WxPushDate] [smalldatetime] NULL,
 CONSTRAINT [PK_caJobCvMatch] PRIMARY KEY NONCLUSTERED 
(
	[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [Index]

GO
/****** Object:  Index [IX_caJobcvMatch_JobId]    Script Date: 2018/9/25 12:40:11 ******/
CREATE CLUSTERED INDEX [IX_caJobcvMatch_JobId] ON [dbo].[caJobCvMatch]
(
	[JobID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Table [dbo].[caJobResumePre]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[caJobResumePre](
	[ResumeID] [int] NOT NULL,
	[Name] [nvarchar](6) COLLATE Chinese_PRC_CI_AS NULL,
	[Sex] [bit] NULL,
	[Age] [int] NULL,
	[BirthDay] [int] NULL,
	[EduLevel] [tinyint] NULL,
	[Experience] [tinyint] NULL,
	[JobType] [varchar](max) COLLATE Chinese_PRC_CI_AS NULL,
	[AtPlace] [varchar](6) COLLATE Chinese_PRC_CI_AS NULL,
	[AtPlaceDesc] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[AddDate] [smalldatetime] NOT NULL,
	[LastLoginDate] [smalldatetime] NULL,
	[paMainId] [int] NULL,
	[SecondId] [varchar](10) COLLATE Chinese_PRC_CI_AS NULL
) ON [CP] TEXTIMAGE_ON [PRIMARY]

GO
/****** Object:  Index [PK_caJobResumePre]    Script Date: 2018/9/25 12:40:11 ******/
CREATE CLUSTERED INDEX [PK_caJobResumePre] ON [dbo].[caJobResumePre]
(
	[ResumeID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = OFF) ON [CP]
GO
/****** Object:  Table [dbo].[caJobResumePreJobType]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[caJobResumePreJobType](
	[cvMainID] [int] NOT NULL,
	[dcJobTypeID] [smallint] NOT NULL
) ON [CP]

GO
/****** Object:  Index [PK_caJobResumePreJobType]    Script Date: 2018/9/25 12:40:11 ******/
CREATE CLUSTERED INDEX [PK_caJobResumePreJobType] ON [dbo].[caJobResumePreJobType]
(
	[cvMainID] ASC,
	[dcJobTypeID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = OFF) ON [CP]
GO
/****** Object:  Table [dbo].[caLoginLog]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[caLoginLog](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[caMainID] [int] NOT NULL,
	[cpMainName] [varchar](100) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[caMainName] [nvarchar](20) COLLATE Chinese_PRC_CI_AS NULL,
	[LoginIP] [varchar](39) COLLATE Chinese_PRC_CI_AS NULL,
	[LoginCookies] [varchar](16) COLLATE Chinese_PRC_CI_AS NULL,
	[AddDate] [smalldatetime] NOT NULL,
	[Browser] [varchar](500) COLLATE Chinese_PRC_CI_AS NULL,
	[LoginFrom] [tinyint] NULL,
 CONSTRAINT [PK_caLoginLog] PRIMARY KEY NONCLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [CP]
) ON [CP]

GO
/****** Object:  Index [IX_caLoginLog_caMainID]    Script Date: 2018/9/25 12:40:11 ******/
CREATE CLUSTERED INDEX [IX_caLoginLog_caMainID] ON [dbo].[caLoginLog]
(
	[caMainID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [CP]
GO
/****** Object:  Table [dbo].[CampusRecruitold]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[CampusRecruitold](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[Title] [nvarchar](100) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[CompanyName] [nvarchar](100) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[CompanyKind] [nvarchar](100) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[WorkPlace] [nvarchar](100) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Homepage] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL,
	[Content] [nvarchar](max) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[type] [bit] NOT NULL,
	[ClickNumber] [int] NOT NULL,
	[AllClickNumber] [int] NOT NULL,
	[RefreshDate] [smalldatetime] NOT NULL,
	[AddMan] [int] NOT NULL,
	[AddDate] [smalldatetime] NOT NULL,
	[Appendix] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[AppendixName] [nvarchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[EndDate] [smalldatetime] NULL,
 CONSTRAINT [PK_CampusRecruit] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

GO
/****** Object:  Table [dbo].[CaOnline]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[CaOnline](
	[CaMainID] [int] NOT NULL,
	[IsOnline] [bit] NOT NULL,
	[IsVi] [bit] NOT NULL,
	[ViPlanId] [int] NULL,
	[InterviewDate] [smalldatetime] NULL,
	[RefreshDate] [datetime] NULL,
 CONSTRAINT [PK_CaOnline] PRIMARY KEY CLUSTERED 
(
	[CaMainID] 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].[caOperationLog]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[caOperationLog](
	[ID] [bigint] IDENTITY(1,1) NOT NULL,
	[caMainID] [int] NOT NULL,
	[Operation] [tinyint] NOT NULL,
	[Details] [nvarchar](200) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[IP] [varchar](39) COLLATE Chinese_PRC_CI_AS NULL,
	[AddDate] [smalldatetime] NOT NULL,
 CONSTRAINT [PK_caOperationLog] PRIMARY KEY NONCLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [CP]
) ON [CP]

GO
/****** Object:  Index [IX_caOperationLog_caMainID]    Script Date: 2018/9/25 12:40:11 ******/
CREATE CLUSTERED INDEX [IX_caOperationLog_caMainID] ON [dbo].[caOperationLog]
(
	[caMainID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [CP]
GO
/****** Object:  Table [dbo].[caorder_20180526]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[caorder_20180526](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[manageruserid] [smallint] NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[caOrderRemarks]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[caOrderRemarks](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[OrderId] [int] NOT NULL,
	[Remarks] [nvarchar](200) COLLATE Chinese_PRC_CI_AS NULL,
	[ManagerId] [smallint] NOT NULL,
	[AddDate] [smalldatetime] NOT NULL,
 CONSTRAINT [PK_caOrderRemarks] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [CP]
) ON [CP]

GO
/****** Object:  Table [dbo].[caPageViewLog]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[caPageViewLog](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[caMainID] [int] NOT NULL,
	[ApplyCvDate] [smalldatetime] NULL,
	[RecommendCvDate] [smalldatetime] NULL,
	[InterviewReplyDate] [smalldatetime] NULL,
	[ApplyCvCount] [int] NULL,
	[RecommendCvCount] [int] NULL,
	[InterviewReplyCount] [int] NULL,
	[ChatCount] [int] NULL,
	[AddDate] [smalldatetime] NOT NULL,
 CONSTRAINT [PK_caPageViewLog] PRIMARY KEY CLUSTERED 
(
	[ID] 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].[caPlainPassword]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[caPlainPassword](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[CaMainID] [int] NOT NULL,
	[PlainPassword] [varchar](40) COLLATE Chinese_PRC_CI_AS NOT NULL,
 CONSTRAINT [PK_caPlainPassowrd] PRIMARY KEY CLUSTERED 
(
	[ID] 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].[caPlaint]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[caPlaint](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[caMainID] [int] NOT NULL,
	[cvMainID] [int] NOT NULL,
	[Plaint] [varchar](1000) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[LinkMan] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[Telephone] [varchar](25) COLLATE Chinese_PRC_CI_AS NULL,
	[AddDate] [smalldatetime] NOT NULL,
	[ReplyType] [tinyint] NOT NULL,
	[ReplyMan] [smallint] NULL,
	[IsViewed] [bit] NOT NULL,
	[ProcessMessage] [varchar](500) COLLATE Chinese_PRC_CI_AS NULL,
	[ProcessDate] [smalldatetime] NULL,
 CONSTRAINT [PK_caPlaint] PRIMARY KEY NONCLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [CP]
) ON [CP]

GO
/****** Object:  Index [IX_caPlaint_caMainID]    Script Date: 2018/9/25 12:40:11 ******/
CREATE CLUSTERED INDEX [IX_caPlaint_caMainID] ON [dbo].[caPlaint]
(
	[caMainID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [CP]
GO
/****** Object:  Table [dbo].[caPushSet]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[caPushSet](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[caMainID] [int] NOT NULL,
	[PushFrequency] [tinyint] NOT NULL,
	[PushNo] [tinyint] NULL,
	[LastPushdate] [smalldatetime] NULL,
 CONSTRAINT [PK_caPushSet] PRIMARY KEY CLUSTERED 
(
	[id] 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].[caSmsLog]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[caSmsLog](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[caOrderId] [int] NOT NULL,
	[cvMainId] [int] NOT NULL,
	[Mobile] [varchar](11) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[MsgType] [tinyint] NOT NULL,
	[RelationId] [int] NOT NULL,
	[SmsMessageLogId] [int] NOT NULL,
	[SendStatus] [int] NULL,
	[SendDate] [datetime] NULL,
	[Msg] [nvarchar](210) COLLATE Chinese_PRC_CI_AS NULL,
	[AddDate] [datetime] NOT NULL,
	[caMainId] [int] NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[caVerifyLog]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[caVerifyLog](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[CaMainID] [int] NOT NULL,
	[Mobile] [varchar](11) COLLATE Chinese_PRC_CI_AS NULL,
	[VerifyCode] [varchar](6) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[VerifyDate] [smalldatetime] NULL,
	[AddDate] [smalldatetime] NOT NULL,
	[ip] [varchar](31) COLLATE Chinese_PRC_CI_AS NULL,
 CONSTRAINT [PK_caVerifyLog] PRIMARY KEY CLUSTERED 
(
	[ID] 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].[Certificate_UnReal]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Certificate_UnReal](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[CompanyName] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[CompanyId] [int] NULL,
	[CertfileName] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[AddMan] [smallint] NULL,
	[AddDate] [smalldatetime] NOT NULL,
	[Description] [nvarchar](500) COLLATE Chinese_PRC_CI_AS NULL,
 CONSTRAINT [PK_Certificate_UnReal] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers]
) ON [BOthers]

GO
/****** Object:  Table [dbo].[ChatLogTemp]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ChatLogTemp](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[AddDate] [datetime] NULL,
	[SqlText] [varchar](max) COLLATE Chinese_PRC_CI_AS NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

GO
/****** Object:  Table [dbo].[ChatOnline]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ChatOnline](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[cvMainID] [int] NOT NULL,
	[caMainID] [int] NOT NULL,
	[ManageruserID] [int] NOT NULL,
	[Initiative] [tinyint] NULL,
	[StartDate] [smalldatetime] NOT NULL,
	[EndDate] [smalldatetime] NULL,
	[Valid] [bit] NULL,
	[CheckMan] [smallint] NULL,
	[CheckDate] [smalldatetime] NULL,
	[Evaluate] [smallint] NULL,
	[AddDate] [smalldatetime] NOT NULL,
	[EndType] [tinyint] NULL,
	[ClientType] [tinyint] NULL,
	[caUnViewed] [tinyint] NULL,
	[paUnViewed] [tinyint] NULL,
 CONSTRAINT [PK_ChatOnline] PRIMARY KEY CLUSTERED 
(
	[ID] 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].[ChatOnlineDel]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ChatOnlineDel](
	[ID] [int] NOT NULL,
	[cvMainID] [int] NOT NULL,
	[caMainID] [int] NOT NULL,
	[ManageruserID] [int] NOT NULL,
	[Initiative] [tinyint] NULL,
	[StartDate] [smalldatetime] NOT NULL,
	[EndDate] [smalldatetime] NULL,
	[Valid] [bit] NULL,
	[CheckMan] [smallint] NULL,
	[CheckDate] [smalldatetime] NULL,
	[Evaluate] [smallint] NULL,
	[AddDate] [smalldatetime] NOT NULL,
	[EndType] [tinyint] NULL,
	[ClientType] [tinyint] NULL,
	[caUnViewed] [tinyint] NULL,
	[paUnViewed] [tinyint] NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[ChatOnlineExchange]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ChatOnlineExchange](
	[UserID] [int] NOT NULL,
	[UserType] [tinyint] NOT NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[ChatOnlineLog]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ChatOnlineLog](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[ChatOnlineID] [int] NOT NULL,
	[SenderType] [tinyint] NOT NULL,
	[IsViewed] [bit] NOT NULL,
	[Message] [varchar](max) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[AddDate] [smalldatetime] NOT NULL,
	[CheckUserID] [int] NULL,
	[CheckResult] [bit] NULL,
	[MessageType] [tinyint] NULL,
 CONSTRAINT [PK_ChatOnlineLog] PRIMARY KEY NONCLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [FOthers] TEXTIMAGE_ON [PRIMARY]

GO
/****** Object:  Index [IX_ChatOnlineLog_ChatOnlineId]    Script Date: 2018/9/25 12:40:11 ******/
CREATE CLUSTERED INDEX [IX_ChatOnlineLog_ChatOnlineId] ON [dbo].[ChatOnlineLog]
(
	[ChatOnlineID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [FOthers]
GO
/****** Object:  Table [dbo].[ChatOnlineLogDel]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ChatOnlineLogDel](
	[ID] [int] NOT NULL,
	[ChatOnlineID] [int] NOT NULL,
	[SenderType] [tinyint] NOT NULL,
	[IsViewed] [bit] NOT NULL,
	[Message] [varchar](max) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[AddDate] [smalldatetime] NOT NULL,
	[CheckUserID] [int] NULL,
	[CheckResult] [bit] NULL,
	[MessageType] [tinyint] NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

GO
/****** Object:  Table [dbo].[chatOnlineTest]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[chatOnlineTest](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[AddDate] [datetime] NULL,
	[dcProvinceID] [smallint] NULL,
PRIMARY KEY CLUSTERED 
(
	[ID] 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].[ChatService]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ChatService](
	[ManageruserID] [smallint] NULL,
	[Name] [nvarchar](20) COLLATE Chinese_PRC_CI_AS NULL,
	[NameEng] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL,
	[IsOnline] [bit] NULL,
	[ChatCount] [int] NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[choutest]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[choutest](
	[id] [int] NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[Cold_Consultant_Assign]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Cold_Consultant_Assign](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[Province_Id] [tinyint] NOT NULL,
	[ManagerUserId] [smallint] NOT NULL,
	[Power] [int] NOT NULL,
	[Current_Power] [int] NOT NULL,
	[Status] [smallint] NOT NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[ColdContact]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ColdContact](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[CustomerID] [int] NOT NULL,
	[Title] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[BeginTime] [datetime] NULL,
	[Description] [nvarchar](500) COLLATE Chinese_PRC_CI_AS NULL,
	[TelePhone] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[LinkMan] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[AddMan] [int] NULL,
	[AddDate] [datetime] NULL,
	[NextContactTime] [datetime] NULL,
	[HasNotify] [bit] NULL,
 CONSTRAINT [PK_ColdContact] PRIMARY KEY CLUSTERED 
(
	[ID] 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].[ColdCustomer]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ColdCustomer](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[CompanyName] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[CpMainID] [int] NULL,
	[ProvinceID] [tinyint] NULL,
	[Email] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[Phone] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[SourceLink] [varchar](1000) COLLATE Chinese_PRC_CI_AS NULL,
	[RegType] [tinyint] NULL,
	[RegUserName] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[RegPassWord] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[IsNameRepeat] [bit] NULL,
	[IsEmailRepeat] [bit] NULL,
	[IsMobilerepeat] [bit] NULL,
	[IsAgree] [bit] NULL,
	[DisAgreeReason] [nvarchar](500) COLLATE Chinese_PRC_CI_AS NULL,
	[RegisterDate] [smalldatetime] NULL,
	[LastLoginDate] [smalldatetime] NULL,
	[LicenceDate] [smalldatetime] NULL,
	[PayDate] [smalldatetime] NULL,
	[PayFee] [decimal](7, 2) NULL,
	[Status] [tinyint] NULL,
	[IsValid] [bit] NULL,
	[CheckMan] [int] NULL,
	[CheckReason] [nvarchar](500) COLLATE Chinese_PRC_CI_AS NULL,
	[CheckDate] [smalldatetime] NULL,
	[AddWorkUserID] [smallint] NULL,
	[AddDate] [smalldatetime] NULL,
	[AddMan] [smallint] NULL,
	[LinkMan] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[CpMainIDOld] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[PhotoFile] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[qq] [varchar](15) COLLATE Chinese_PRC_CI_AS NULL,
	[cpIndustry] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[dcCompanySizeID] [int] NULL,
	[dcCompanyKindID] [int] NULL,
	[dcRegionID] [varchar](6) COLLATE Chinese_PRC_CI_AS NULL,
	[Address] [varchar](120) COLLATE Chinese_PRC_CI_AS NULL,
	[Brief] [varchar](6000) COLLATE Chinese_PRC_CI_AS NULL,
	[OtherContact] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[AllocateLogID] [int] NULL,
 CONSTRAINT [PK_ColdCustomer] PRIMARY KEY CLUSTERED 
(
	[ID] 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].[COldCustomer0327]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[COldCustomer0327](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[companyName] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[AddMan] [smallint] NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[ColdCustomerAllocateLog]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ColdCustomerAllocateLog](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[ManagerUserId] [int] NOT NULL,
	[SourceType] [int] NOT NULL,
	[ALLocater] [int] NOT NULL,
	[AllocateNumber] [int] NOT NULL,
	[AddDate] [datetime] NOT NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[coldCustomerRelease]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[coldCustomerRelease](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[custormerId] [int] NULL,
	[consultantid] [int] NULL,
	[allotman] [int] NULL,
	[AddDate] [smalldatetime] NULL,
 CONSTRAINT [PK_coldCustomerRelease] PRIMARY KEY CLUSTERED 
(
	[id] 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].[ColdCustomerTry]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ColdCustomerTry](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[CpmainID] [int] NULL,
	[CompanyName] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL,
	[AddDate] [datetime] NULL,
 CONSTRAINT [PK_ColdCustomerTry] PRIMARY KEY CLUSTERED 
(
	[ID] 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].[CommentInterview]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[CommentInterview](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[CpmainID] [int] NOT NULL,
	[PaMainID] [int] NOT NULL,
	[IP] [varchar](15) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[SessionID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[JobName] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[InterviewDate] [varchar](6) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[InterViewResult] [tinyint] NOT NULL,
	[SalaryMonth] [int] NULL,
	[InterViewExperience] [nvarchar](max) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[InterviewFeeling] [nvarchar](max) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Title] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[AddDate] [smalldatetime] NULL,
	[VerifyMan] [int] NULL,
	[VerifyDate] [smalldatetime] NULL,
	[InterviewType] [int] NULL,
	[ReplyDate] [smalldatetime] NULL,
	[ReplyContent] [nvarchar](max) COLLATE Chinese_PRC_CI_AS NULL,
	[ReplyVerifyMan] [int] NULL,
	[ReplyVerifyDate] [smalldatetime] NULL,
	[ReplyVerifyResult] [tinyint] NULL,
	[PraiseCount] [int] NULL,
	[LoginPraiseCount] [int] NULL,
	[IsDirect] [bit] NULL,
 CONSTRAINT [PK_Interview] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

GO
/****** Object:  Table [dbo].[CommentPraise]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[CommentPraise](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[CommentID] [int] NOT NULL,
	[CommentType] [int] NOT NULL,
	[PamainID] [int] NOT NULL,
	[AddDate] [smalldatetime] NULL,
 CONSTRAINT [PK_CommentPraise] PRIMARY KEY CLUSTERED 
(
	[ID] 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].[Comments]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Comments](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[CpMainID] [int] NOT NULL,
	[PaMainID] [int] NOT NULL,
	[IP] [varchar](15) COLLATE Chinese_PRC_CI_AS NULL,
	[SessionID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[Relation] [tinyint] NOT NULL,
	[GradeStar] [tinyint] NOT NULL,
	[Remark1] [nvarchar](max) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Remark2] [nvarchar](max) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Remark3] [nvarchar](max) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Title] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Position] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[WorkRegionID] [varchar](6) COLLATE Chinese_PRC_CI_AS NULL,
	[EntryDate] [varchar](6) COLLATE Chinese_PRC_CI_AS NULL,
	[QuitDate] [varchar](6) COLLATE Chinese_PRC_CI_AS NULL,
	[AddDate] [smalldatetime] NOT NULL,
	[CommentType] [tinyint] NULL,
	[VerifyMan] [int] NULL,
	[VerifyDate] [smalldatetime] NULL,
	[ReplyDate] [smalldatetime] NULL,
	[ReplyContent] [nvarchar](max) COLLATE Chinese_PRC_CI_AS NULL,
	[ReplyVerifyMan] [int] NULL,
	[ReplyVerifyDate] [smalldatetime] NULL,
	[PraiseCount] [int] NULL,
	[LoginPraiseCount] [int] NULL,
	[ReplyVerifyResult] [int] NULL,
	[IsDirect] [bit] NULL,
 CONSTRAINT [PK_Comments] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

GO
/****** Object:  Table [dbo].[Company_Black]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Company_Black](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[CompanyName] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[managerid] [smallint] NOT NULL,
	[addeddate] [smalldatetime] NOT NULL,
	[email] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[refusecount] [int] NOT NULL,
	[reason] [nvarchar](500) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[mobile] [varchar](11) COLLATE Chinese_PRC_CI_AS NULL
) ON [BOthers]

GO
/****** Object:  Index [PK_Company_Black]    Script Date: 2018/9/25 12:40:11 ******/
CREATE UNIQUE CLUSTERED INDEX [PK_Company_Black] ON [dbo].[Company_Black]
(
	[Id] 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 [BOthers]
GO
/****** Object:  Table [dbo].[Company_deleted]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Company_deleted](
	[Id] [int] NOT NULL,
	[Username] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Password] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Companyname] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[LinkMan] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[Telephone] [varchar](25) COLLATE Chinese_PRC_CI_AS NULL,
	[Email] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Province_Id] [int] NOT NULL,
	[HandleMan] [smallint] NOT NULL,
	[AddDate] [smalldatetime] NOT NULL,
	[Remarks] [nvarchar](1000) COLLATE Chinese_PRC_CI_AS NULL,
	[ManagerUserId] [smallint] NULL,
	[SecondId] [varchar](10) COLLATE Chinese_PRC_CI_AS NULL,
 CONSTRAINT [PK_Company_deleted] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers]
) ON [BOthers]

GO
/****** Object:  Table [dbo].[Company_Month]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Company_Month](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[CompanyId] [int] NOT NULL,
	[YearMonth] [char](6) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[ValidDate] [smalldatetime] NOT NULL,
 CONSTRAINT [PK_Company_Month] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers]
) ON [BOthers]

GO
/****** Object:  Table [dbo].[Company_Xinxi]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Company_Xinxi](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[UserName] [varchar](50) COLLATE Chinese_PRC_CS_AS NULL,
	[PassWord] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Email] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[RegDate] [smalldatetime] NOT NULL,
	[AddMan] [smallint] NOT NULL,
	[Province_Id] [int] NOT NULL,
	[CompanyName] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[IsHistory] [bit] NOT NULL,
	[UserNameLower]  AS (CONVERT([varchar](50),[UserName] collate CHINESE_PRC_CI_AS,(0))) PERSISTED,
 CONSTRAINT [PK_company_xinxi] PRIMARY KEY CLUSTERED 
(
	[IsHistory] ASC,
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [ResumeXinxiScheme]([IsHistory])
) ON [ResumeXinxiScheme]([IsHistory])

GO
/****** Object:  Table [dbo].[CompanyAssignLog]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[CompanyAssignLog](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[ConsultantId_Old] [int] NULL,
	[ConsultantId_New] [int] NULL,
	[AddMan] [smallint] NOT NULL,
	[AddDate] [smalldatetime] NOT NULL,
	[CompanyId] [int] NOT NULL
) ON [BOthers]

GO
/****** Object:  Table [dbo].[CompanyInform]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[CompanyInform](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[Object] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Title] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Content] [nvarchar](max) COLLATE Chinese_PRC_CI_AS NULL,
	[AddDate] [smalldatetime] NOT NULL,
	[Status] [bit] NOT NULL,
	[Type] [smallint] NOT NULL,
	[Link] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[Province] [varchar](100) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[EndDate] [smalldatetime] NULL,
	[at1] [bit] NULL,
	[at2] [bit] NULL,
	[at3] [bit] NULL,
 CONSTRAINT [PK_Companyinform] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers]
) ON [BOthers] TEXTIMAGE_ON [PRIMARY]

GO
/****** Object:  Table [dbo].[CompanyNotify]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[CompanyNotify](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[CompanyId] [int] NOT NULL,
	[AddDate] [smalldatetime] NOT NULL,
	[Type] [smallint] NOT NULL,
	[Content] [nvarchar](300) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[EndDate] [smalldatetime] NULL,
	[Received] [bit] NOT NULL,
	[ManagerUserId] [smallint] NULL,
	[CompanyName] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
 CONSTRAINT [PK_CompanyNotify] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [CP]
) ON [CP]

GO
/****** Object:  Table [dbo].[Consultant_assign]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Consultant_assign](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[Province_Id] [tinyint] NOT NULL,
	[ManagerUserId] [smallint] NOT NULL,
	[Power] [int] NOT NULL,
	[Current_Power] [int] NOT NULL,
	[Status] [smallint] NOT NULL,
 CONSTRAINT [PK_Consultant_assign] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers],
 CONSTRAINT [IX_Consultant_assign] UNIQUE NONCLUSTERED 
(
	[Province_Id] ASC,
	[ManagerUserId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
) ON [BOthers]

GO
/****** Object:  Table [dbo].[Consultant_Factor]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Consultant_Factor](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[YearMonth] [int] NOT NULL,
	[Factor_wuxianzhi] [smallint] NOT NULL,
	[Factor_chuzhi] [smallint] NOT NULL,
	[factor_vip] [smallint] NOT NULL,
	[Factor_noContinue] [smallint] NOT NULL,
	[Factor_New] [smallint] NOT NULL,
	[Factor_active_first] [smallint] NOT NULL,
	[Factor_passive_first] [smallint] NOT NULL,
	[Factor_dead_first] [smallint] NOT NULL,
	[Factor_active_Second] [smallint] NULL,
	[Factor_passive_Second] [smallint] NULL,
	[Factor_dead_Second] [smallint] NULL,
	[Sn] [tinyint] NOT NULL,
 CONSTRAINT [PK_Consultant_Factor] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers]
) ON [BOthers]

GO
/****** Object:  Table [dbo].[Consultant_ManagerUser_Month]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Consultant_ManagerUser_Month](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[YearMonth] [int] NOT NULL,
	[ConsultantId] [smallint] NOT NULL,
	[obj_sales_first] [int] NULL,
	[real_sales_first] [numeric](18, 2) NULL,
	[obj_sales_Second] [int] NULL,
	[real_sales_Second] [numeric](18, 2) NULL,
	[DescrIption] [nvarchar](2000) COLLATE Chinese_PRC_CI_AS NULL,
	[obj_sales_new] [int] NULL,
	[real_sales_new] [numeric](18, 2) NULL,
	[customer_num] [int] NULL,
	[ordernum_first] [int] NULL,
	[ordernum_Second] [int] NULL,
	[ordernum_new] [int] NULL,
	[obj_sales] [int] NULL,
	[real_sales] [numeric](18, 2) NULL,
	[Remarks] [nvarchar](200) COLLATE Chinese_PRC_CI_AS NULL,
	[name] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[name_eng] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[status] [smallint] NULL,
	[deptid] [int] NULL,
 CONSTRAINT [PK_Consultant_ManagerUser_Month] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers],
 CONSTRAINT [IX_Consultant_ManagerUser_Month_unique] UNIQUE NONCLUSTERED 
(
	[YearMonth] ASC,
	[ConsultantId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
) ON [BOthers]

GO
/****** Object:  Table [dbo].[Contact]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Contact](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[Title] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[CompanyId] [int] NULL,
	[DescrIption] [nvarchar](500) COLLATE Chinese_PRC_CI_AS NULL,
	[begintime] [smalldatetime] NULL,
	[status] [smallint] NULL,
	[addDate] [smalldatetime] NOT NULL,
	[ManagerUserId] [smallint] NOT NULL,
	[Creator] [int] NOT NULL,
	[Quality] [smallint] NULL,
	[CloseDate] [smalldatetime] NULL,
	[CompanyType] [smallint] NULL,
	[LinkMan] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[Telephone] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[Label] [char](10) COLLATE Chinese_PRC_CI_AS NULL,
 CONSTRAINT [PK_Contact] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers]
) ON [BOthers]

GO
/****** Object:  Table [dbo].[Coorperation]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Coorperation](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[FileName] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Url] [varchar](200) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[AddDate] [smalldatetime] NULL,
	[Title] [varchar](30) COLLATE Chinese_PRC_CI_AS NULL,
PRIMARY KEY CLUSTERED 
(
	[ID] 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].[counter]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[counter](
	[countDate] [int] NOT NULL,
	[versionId] [smallint] NOT NULL,
	[viewnumber] [int] NOT NULL,
	[spIderviewnumber] [int] NOT NULL,
 CONSTRAINT [IX_counter_unique] UNIQUE CLUSTERED 
(
	[countDate] ASC,
	[versionId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
) ON [Index]

GO
/****** Object:  Table [dbo].[counter_Month]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[counter_Month](
	[countMonth] [int] NOT NULL,
	[versionId] [smallint] NOT NULL,
	[viewnumber] [int] NOT NULL,
	[spIderviewnumber] [int] NOT NULL
) ON [BOthers]

GO
/****** Object:  Table [dbo].[Counter1109]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Counter1109](
	[countDate] [int] NOT NULL,
	[versionId] [smallint] NOT NULL,
	[viewnumber] [int] NOT NULL,
	[spIderviewnumber] [int] NOT NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[CounterSpider]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[CounterSpider](
	[VersionId] [smallint] NOT NULL,
	[AddDate] [datetime] NOT NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[cpAttachment]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[cpAttachment](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[cpMainID] [int] NOT NULL,
	[FileName] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[AddMan] [smallint] NOT NULL,
	[AddDate] [smalldatetime] NOT NULL,
PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [CP]
) ON [CP]

GO
/****** Object:  Table [dbo].[cpCertification]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[cpCertification](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[cpMainID] [int] NOT NULL,
	[CompanyName] [varchar](100) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Mobile] [varchar](11) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[MemberType] [tinyint] NOT NULL,
	[CerType] [tinyint] NULL,
	[CerStatus] [tinyint] NULL,
	[AddDate] [smalldatetime] NOT NULL,
	[CerDate] [smalldatetime] NULL,
 CONSTRAINT [PK_cpCertification] PRIMARY KEY CLUSTERED 
(
	[ID] 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].[cpCheckLog]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[cpCheckLog](
	[cpMainId] [int] NULL,
	[CheckDate] [datetime] NULL,
	[FilterWord] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[cpCoin]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[cpCoin](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[cpMainID] [int] NOT NULL,
	[caOrderID] [int] NOT NULL,
	[Coin] [int] NOT NULL,
	[IsCancel] [bit] NULL,
	[Balance] [int] NULL,
	[AddDate] [datetime] NULL,
 CONSTRAINT [PK_cpCoin] PRIMARY KEY CLUSTERED 
(
	[ID] 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].[cpCompanyEmail]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[cpCompanyEmail](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[cpCertificationID] [int] NOT NULL,
	[Email] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[VerifyCode] [varchar](6) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[CheckResult] [tinyint] NULL,
	[CheckMan] [smallint] NULL,
	[CheckDate] [smalldatetime] NULL,
	[AddDate] [smalldatetime] NOT NULL,
	[CheckMessage] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
 CONSTRAINT [PK_cpCompanyEmail] PRIMARY KEY CLUSTERED 
(
	[ID] 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].[cpCorporationAccount]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[cpCorporationAccount](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[cpCertificationID] [int] NOT NULL,
	[CertificationType] [tinyint] NULL,
	[FnBankDayBookID] [int] NULL,
	[CheckMan] [smallint] NULL,
	[CheckDate] [smalldatetime] NULL,
	[AddDate] [smalldatetime] NOT NULL,
	[HasChecked] [bit] NULL,
 CONSTRAINT [PK_cpCorporationAccount] PRIMARY KEY CLUSTERED 
(
	[ID] 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].[cpCvShield]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[cpCvShield](
	[cpMainID] [int] NULL,
	[cvMainId] [int] NULL
) ON [CP]

GO
/****** Object:  Table [dbo].[cpImage]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[cpImage](
	[ID] [int] IDENTITY(1,1) NOT FOR REPLICATION NOT NULL,
	[cpMainID] [int] NOT NULL,
	[ImgType] [tinyint] NOT NULL,
	[ImgFile] [varchar](500) COLLATE Chinese_PRC_CI_AS NULL,
	[AddDate] [smalldatetime] NOT NULL,
	[HasPassed] [bit] NULL,
	[CheckMan] [smallint] NULL,
	[CheckDate] [smalldatetime] NULL,
	[CheckMessage] [nvarchar](500) COLLATE Chinese_PRC_CI_AS NULL,
	[OrderNo] [tinyint] NULL,
	[Description] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[ClickNumber] [int] NULL,
	[VideoId] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
 CONSTRAINT [PK_cpImage] PRIMARY KEY NONCLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [CP]
) ON [CP]

GO
/****** Object:  Index [IX_cpImage_cpMainID]    Script Date: 2018/9/25 12:40:11 ******/
CREATE CLUSTERED INDEX [IX_cpImage_cpMainID] ON [dbo].[cpImage]
(
	[cpMainID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [CP]
GO
/****** Object:  Table [dbo].[cpImage_before]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[cpImage_before](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[cpMainID] [int] NOT NULL,
	[fileUrl] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[AddDate] [smalldatetime] NOT NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[CpIndexPage]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[CpIndexPage](
	[caMainId] [int] NULL,
	[ID] [int] NULL,
	[type] [int] NULL,
	[ICount] [int] NULL,
	[Title] [nvarchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[Link] [nvarchar](200) COLLATE Chinese_PRC_CI_AS NULL,
	[ContentText] [nvarchar](max) COLLATE Chinese_PRC_CI_AS NULL,
	[AddDate] [smalldatetime] NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

GO
/****** Object:  Table [dbo].[cpIndustry]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[cpIndustry](
	[cpMainID] [int] NOT NULL,
	[dcIndustryID] [smallint] NOT NULL,
 CONSTRAINT [PK_cpIndustry] PRIMARY KEY NONCLUSTERED 
(
	[cpMainID] ASC,
	[dcIndustryID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [CP]
) ON [CP]

GO
/****** Object:  Table [dbo].[cpLicence]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[cpLicence](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[cpMainID] [int] NOT NULL,
	[ImgFile] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[FileSource] [tinyint] NOT NULL,
	[Ip] [varchar](39) COLLATE Chinese_PRC_CI_AS NULL,
	[AddDate] [smalldatetime] NOT NULL,
	[HasPassed] [bit] NULL,
	[CheckMan] [smallint] NULL,
	[CheckDate] [smalldatetime] NULL,
	[CheckMessage] [nvarchar](500) COLLATE Chinese_PRC_CI_AS NULL,
	[cpCertificationID] [int] NULL,
 CONSTRAINT [PK_cpLicence] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [CP]
) ON [CP]

GO
/****** Object:  Table [dbo].[cplicence1107]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[cplicence1107](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[cpMainID] [int] NOT NULL,
	[ImgFile] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[FileSource] [tinyint] NOT NULL,
	[Ip] [varchar](39) COLLATE Chinese_PRC_CI_AS NULL,
	[AddDate] [smalldatetime] NOT NULL,
	[HasPassed] [bit] NULL,
	[CheckMan] [smallint] NULL,
	[CheckDate] [smalldatetime] NULL,
	[CheckMessage] [nvarchar](500) COLLATE Chinese_PRC_CI_AS NULL,
	[cpCertificationID] [int] NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[cpLicenceChangeLog]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[cpLicenceChangeLog](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[cpMainID] [int] NOT NULL,
	[NameOld] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[NameNew] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[FilenameOld] [varchar](100) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[FilenameNew] [varchar](100) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[ManagerUserID] [smallint] NOT NULL,
	[AddDate] [smalldatetime] NOT NULL,
 CONSTRAINT [PK_cpLicenceChangLog] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [CP]
) ON [CP]

GO
/****** Object:  Table [dbo].[cpLicenceLog]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[cpLicenceLog](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[cpMainID] [int] NOT NULL,
	[Description] [varchar](500) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[AddDate] [smalldatetime] NOT NULL,
	[CheckMan] [smallint] NULL,
	[OldFileName] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL,
	[FileSource] [tinyint] NULL,
 CONSTRAINT [PK_cpLicenceLog] PRIMARY KEY NONCLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [CP]
) ON [CP]

GO
/****** Object:  Index [IX_cpLicenceLog_cpMainID]    Script Date: 2018/9/25 12:40:11 ******/
CREATE CLUSTERED INDEX [IX_cpLicenceLog_cpMainID] ON [dbo].[cpLicenceLog]
(
	[cpMainID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [CP]
GO
/****** Object:  Table [dbo].[cpMainBalance]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[cpMainBalance](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[dcProvinceId] [tinyint] NOT NULL,
	[RegDate] [smalldatetime] NOT NULL,
	[RegisterIp] [varchar](39) COLLATE Chinese_PRC_CI_AS NULL,
	[RegisterMode] [tinyint] NOT NULL,
	[Name] [varchar](100) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Address] [nvarchar](60) COLLATE Chinese_PRC_CI_AS NULL,
	[MemberType] [tinyint] NOT NULL,
	[UnlimitedDate] [smalldatetime] NOT NULL,
	[BalanceDate] [smalldatetime] NOT NULL,
	[Balance] [smallint] NOT NULL,
	[ConsultantId] [smallint] NULL,
	[ResumeQuota] [smallint] NOT NULL,
	[LastLoginDate] [smalldatetime] NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[cpMainLimited]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[cpMainLimited](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[CompanyName] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[loginIp] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[LoginCookies] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[AddDate] [smalldatetime] NOT NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[cpmainLng]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[cpmainLng](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[lng] [decimal](8, 5) NULL,
	[lat] [decimal](8, 5) NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[cpMainRelease]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[cpMainRelease](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[cpMainId] [int] NULL,
	[consultantid] [int] NULL,
	[allotman] [int] NULL,
	[AddDate] [smalldatetime] NULL,
 CONSTRAINT [PK_cpMainRelease] PRIMARY KEY CLUSTERED 
(
	[id] 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].[cpMainVip]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[cpMainVip](
	[cpMainId] [int] NOT NULL,
 CONSTRAINT [PK_cpMainVip] PRIMARY KEY CLUSTERED 
(
	[cpMainId] 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].[cpPersonalAccount]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[cpPersonalAccount](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[cpCertificationID] [int] NOT NULL,
	[Name] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[IDCard] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[BankNo] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[FnBankDaybookID] [int] NULL,
	[CheckResult] [tinyint] NULL,
	[CheckMan] [smallint] NULL,
	[CheckDate] [smalldatetime] NULL,
	[AddDate] [smalldatetime] NOT NULL,
 CONSTRAINT [PK_cpPersonalAccount] PRIMARY KEY CLUSTERED 
(
	[ID] 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].[cpPoint]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[cpPoint](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[cpMainID] [int] NOT NULL,
	[ChangeID] [tinyint] NOT NULL,
	[Point] [int] NULL,
	[relativeID] [int] NULL,
	[LastModifyDate] [datetime] NULL,
	[Remark] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
 CONSTRAINT [PK_cpPoint] PRIMARY KEY NONCLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [CP]

GO
/****** Object:  Index [IX_cpPoint_cpMainId]    Script Date: 2018/9/25 12:40:11 ******/
CREATE CLUSTERED INDEX [IX_cpPoint_cpMainId] ON [dbo].[cpPoint]
(
	[cpMainID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [CP]
GO
/****** Object:  Table [dbo].[cpPointCount]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[cpPointCount](
	[CountDate] [smalldatetime] NULL,
	[cpMainId] [int] NULL,
	[TodayPoint] [int] NULL,
	[AllPoint] [int] NULL
) ON [FOthers]

GO
/****** Object:  Index [IX_cpPointCount_cpMainId]    Script Date: 2018/9/25 12:40:11 ******/
CREATE CLUSTERED INDEX [IX_cpPointCount_cpMainId] ON [dbo].[cpPointCount]
(
	[cpMainId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [FOthers]
GO
/****** Object:  Table [dbo].[cpProductBulletin]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[cpProductBulletin](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[ImageFile] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[ProductTitle] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[ProductText] [nvarchar](1000) COLLATE Chinese_PRC_CI_AS NULL,
	[BeginDate] [smalldatetime] NULL,
	[EndDate] [smalldatetime] NULL,
	[AddMan] [smallint] NULL,
	[AddDAte] [smalldatetime] NULL,
 CONSTRAINT [PK_cpProductBulletin] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [CP]
) ON [CP]

GO
/****** Object:  Table [dbo].[CpRealNameLog]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[CpRealNameLog](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[CpMainID] [int] NOT NULL,
	[CertificationType] [tinyint] NOT NULL,
	[FnBankDaybookID] [int] NULL,
	[AddDate] [datetime] NOT NULL,
	[CheckMan] [smallint] NOT NULL,
 CONSTRAINT [PK_CpRealNameLog] PRIMARY KEY CLUSTERED 
(
	[id] 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].[cpRefreshLog]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[cpRefreshLog](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[cpMainId] [int] NOT NULL,
	[RefreshDate] [smalldatetime] NULL,
 CONSTRAINT [PK_cpRefreshLog] PRIMARY KEY NONCLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [CP]

GO
/****** Object:  Index [IX_cpRefreshLog_cpMainId]    Script Date: 2018/9/25 12:40:11 ******/
CREATE CLUSTERED INDEX [IX_cpRefreshLog_cpMainId] ON [dbo].[cpRefreshLog]
(
	[cpMainId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [CP]
GO
/****** Object:  Table [dbo].[cpRemark]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[cpRemark](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[CpMainId] [int] NULL,
	[Description] [varchar](1000) COLLATE Chinese_PRC_CI_AS NULL,
	[AddMan] [int] NULL,
	[AddDate] [smalldatetime] NULL,
PRIMARY KEY CLUSTERED 
(
	[ID] 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].[cpSession]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[cpSession](
	[SessionID] [varchar](30) COLLATE Chinese_PRC_CI_AS NULL,
	[caMainID] [int] NOT NULL,
	[RefreshDate] [datetime] NOT NULL,
	[IP] [varchar](39) COLLATE Chinese_PRC_CI_AS NULL,
	[AddDate] [smalldatetime] NOT NULL,
	[Cookies] [varchar](16) COLLATE Chinese_PRC_CI_AS NULL,
 CONSTRAINT [PK_cpSession] PRIMARY KEY CLUSTERED 
(
	[caMainID] 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].[Customer_Assign]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Customer_Assign](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[Province_Id] [tinyint] NOT NULL,
	[ManagerUserId] [smallint] NOT NULL,
	[Power] [int] NOT NULL,
	[Current_Power] [int] NOT NULL,
	[Status] [smallint] NOT NULL,
	[Type] [smallint] NOT NULL,
 CONSTRAINT [PK_customer_assign] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers],
 CONSTRAINT [IX_customer_assign] UNIQUE NONCLUSTERED 
(
	[Province_Id] ASC,
	[ManagerUserId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
) ON [BOthers]

GO
/****** Object:  Table [dbo].[Customer_Target]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Customer_Target](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[Companyname] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[LinkMan] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Telephone] [varchar](30) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Email] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[addDate] [smalldatetime] NOT NULL,
	[Status] [smallint] NOT NULL,
	[ManagerUserId] [smallint] NOT NULL,
	[Remark] [nvarchar](200) COLLATE Chinese_PRC_CI_AS NULL,
	[source] [varchar](500) COLLATE Chinese_PRC_CI_AS NULL,
 CONSTRAINT [PK_customer_target] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers]
) ON [BOthers]

GO
/****** Object:  Table [dbo].[cvAppendix]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[cvAppendix](
	[ID] [int] IDENTITY(1,1) NOT FOR REPLICATION NOT NULL,
	[cvMainID] [int] NOT NULL,
	[dcAppendixID] [smallint] NULL,
	[Name] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL,
	[NameEng] [varchar](250) COLLATE Chinese_PRC_CI_AS NULL,
	[Description] [nvarchar](200) COLLATE Chinese_PRC_CI_AS NULL,
	[DescriptionEng] [varchar](1000) COLLATE Chinese_PRC_CI_AS NULL,
	[AccessDate] [smallint] NULL,
	[Filename] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
 CONSTRAINT [PK_cvAppendix] PRIMARY KEY NONCLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [CV]
) ON [CV]

GO
/****** Object:  Index [IX_cvAppendix_cvMainID]    Script Date: 2018/9/25 12:40:11 ******/
CREATE CLUSTERED INDEX [IX_cvAppendix_cvMainID] ON [dbo].[cvAppendix]
(
	[cvMainID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [CV]
GO
/****** Object:  Table [dbo].[cvAppendixPublish]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[cvAppendixPublish](
	[ID] [int] NOT NULL,
	[cvMainID] [int] NOT NULL,
	[Name] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL,
	[Description] [nvarchar](200) COLLATE Chinese_PRC_CI_AS NULL,
 CONSTRAINT [PK_cvAppendixPublish] PRIMARY KEY NONCLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [CV]
) ON [CV]

GO
/****** Object:  Index [IX_cvAppendixPublish_cvMainID]    Script Date: 2018/9/25 12:40:11 ******/
CREATE CLUSTERED INDEX [IX_cvAppendixPublish_cvMainID] ON [dbo].[cvAppendixPublish]
(
	[cvMainID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [CV]
GO
/****** Object:  Table [dbo].[cvAttachment]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[cvAttachment](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[cvMainID] [int] NOT NULL,
	[FilePath] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[FileName] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[VerifyResult] [tinyint] NULL,
	[VerifyMan] [int] NULL,
	[VerifyDate] [smalldatetime] NULL,
	[AddDate] [smalldatetime] NOT NULL,
 CONSTRAINT [PK_cvAttachment] PRIMARY KEY CLUSTERED 
(
	[id] 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].[cvDownDoc]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[cvDownDoc](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[Name] [nvarchar](100) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[imgName] [varchar](100) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[FileName] [varchar](100) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[ViewCount] [int] NULL,
	[DownCount] [int] NULL,
	[addMan] [int] NOT NULL,
	[addDate] [smalldatetime] NOT NULL,
	[fileType] [int] NULL,
	[LogoType] [tinyint] NULL,
	[IsBeta] [bit] NULL,
PRIMARY KEY CLUSTERED 
(
	[Id] 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].[cvEducation]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[cvEducation](
	[ID] [int] IDENTITY(1,1) NOT FOR REPLICATION NOT NULL,
	[cvMainID] [int] NOT NULL,
	[GraduateCollage] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[GraduateCollageEng] [varchar](250) COLLATE Chinese_PRC_CI_AS NULL,
	[Graduation] [int] NOT NULL,
	[dcMajorID] [smallint] NOT NULL,
	[MajorName] [nvarchar](20) COLLATE Chinese_PRC_CI_AS NULL,
	[MajorNameEng] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[Degree] [tinyint] NOT NULL,
	[EduType] [tinyint] NOT NULL,
	[Details] [varchar](max) COLLATE Chinese_PRC_CI_AS NULL,
	[DetailsEng] [varchar](max) COLLATE Chinese_PRC_CI_AS NULL,
 CONSTRAINT [PK_cvEducation] PRIMARY KEY NONCLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [CV]
) ON [CV] TEXTIMAGE_ON [CV]

GO
/****** Object:  Index [IX_cvEducation_cvMainID]    Script Date: 2018/9/25 12:40:11 ******/
CREATE CLUSTERED INDEX [IX_cvEducation_cvMainID] ON [dbo].[cvEducation]
(
	[cvMainID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [CV]
GO
/****** Object:  Table [dbo].[cvEducationPublish]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[cvEducationPublish](
	[ID] [int] NOT NULL,
	[cvMainID] [int] NOT NULL,
	[GraduateCollage] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[GraduateCollageEng] [varchar](250) COLLATE Chinese_PRC_CI_AS NULL,
	[Graduation] [int] NOT NULL,
	[dcMajorID] [smallint] NOT NULL,
	[MajorName] [nvarchar](20) COLLATE Chinese_PRC_CI_AS NULL,
	[MajorNameEng] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[Degree] [tinyint] NOT NULL,
	[EduType] [tinyint] NOT NULL,
	[Details] [nvarchar](max) COLLATE Chinese_PRC_CI_AS NULL,
 CONSTRAINT [PK_cvEducationPublish] PRIMARY KEY NONCLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [CV]
) ON [CV] TEXTIMAGE_ON [CV]

GO
/****** Object:  Index [IX_cvEducationPublish_cvMainID]    Script Date: 2018/9/25 12:40:11 ******/
CREATE CLUSTERED INDEX [IX_cvEducationPublish_cvMainID] ON [dbo].[cvEducationPublish]
(
	[cvMainID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [CV]
GO
/****** Object:  Table [dbo].[cvExperience]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[cvExperience](
	[ID] [int] IDENTITY(1,1) NOT FOR REPLICATION NOT NULL,
	[cvMainID] [int] NOT NULL,
	[CompanyName] [nvarchar](30) COLLATE Chinese_PRC_CI_AS NULL,
	[CompanyNameEng] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[dcIndustryID] [smallint] NOT NULL,
	[dcCompanySizeID] [tinyint] NULL,
	[dcJobtypeID] [smallint] NOT NULL,
	[JobName] [nvarchar](20) COLLATE Chinese_PRC_CI_AS NULL,
	[JobNameEng] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[BeginDate] [int] NOT NULL,
	[EndDate] [int] NOT NULL,
	[SubNodeNum] [tinyint] NOT NULL,
	[Description] [varchar](max) COLLATE Chinese_PRC_CI_AS NULL,
	[DescriptionEng] [varchar](max) COLLATE Chinese_PRC_CI_AS NULL,
	[dcCompanyKindID] [smallint] NULL,
	[WorkPlace] [varchar](6) COLLATE Chinese_PRC_CI_AS NULL,
	[Dept] [nvarchar](20) COLLATE Chinese_PRC_CI_AS NULL,
	[DeptEng] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[UpperPost] [nvarchar](20) COLLATE Chinese_PRC_CI_AS NULL,
	[UpperPostEng] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[dcLeaveResonID] [tinyint] NULL,
 CONSTRAINT [PK_cvExperience] PRIMARY KEY NONCLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [CV]
) ON [CV] TEXTIMAGE_ON [CV]

GO
/****** Object:  Index [IX_cvExperience_cvMainID]    Script Date: 2018/9/25 12:40:11 ******/
CREATE CLUSTERED INDEX [IX_cvExperience_cvMainID] ON [dbo].[cvExperience]
(
	[cvMainID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [CV]
GO
/****** Object:  Table [dbo].[cvExperiencePublish]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[cvExperiencePublish](
	[ID] [int] NOT NULL,
	[cvMainID] [int] NOT NULL,
	[CompanyName] [nvarchar](30) COLLATE Chinese_PRC_CI_AS NULL,
	[dcIndustryID] [smallint] NOT NULL,
	[dcJobtypeID] [smallint] NOT NULL,
	[JobName] [nvarchar](20) COLLATE Chinese_PRC_CI_AS NULL,
	[SubNodeNum] [tinyint] NOT NULL,
	[Description] [nvarchar](max) COLLATE Chinese_PRC_CI_AS NULL,
 CONSTRAINT [PK_cvExperiencePublish] PRIMARY KEY NONCLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [CV]
) ON [CV] TEXTIMAGE_ON [CV]

GO
/****** Object:  Index [IX_cvExperiencePublish_cvMainID]    Script Date: 2018/9/25 12:40:11 ******/
CREATE CLUSTERED INDEX [IX_cvExperiencePublish_cvMainID] ON [dbo].[cvExperiencePublish]
(
	[cvMainID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [CV]
GO
/****** Object:  Table [dbo].[cvIndustry]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[cvIndustry](
	[cvMainID] [int] NOT NULL,
	[dcIndustryID] [smallint] NOT NULL,
 CONSTRAINT [PK_cvIndustry] PRIMARY KEY CLUSTERED 
(
	[cvMainID] ASC,
	[dcIndustryID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [CV]
) ON [CV]

GO
/****** Object:  Table [dbo].[cvIndustryPublish]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[cvIndustryPublish](
	[cvMainID] [int] NOT NULL,
	[dcIndustryID] [smallint] NOT NULL,
 CONSTRAINT [PK_cvIndustryPublish] PRIMARY KEY CLUSTERED 
(
	[cvMainID] ASC,
	[dcIndustryID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [CV]
) ON [CV]

GO
/****** Object:  Table [dbo].[cvInfo]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[cvInfo](
	[cvMainId] [int] NOT NULL,
	[JobName] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[Speciality] [varchar](max) COLLATE Chinese_PRC_CI_AS NULL,
	[EduInfo] [varchar](max) COLLATE Chinese_PRC_CI_AS NULL,
	[ExpInfo] [varchar](max) COLLATE Chinese_PRC_CI_AS NULL,
	[ProjectInfo] [varchar](max) COLLATE Chinese_PRC_CI_AS NULL,
	[TrainInfo] [varchar](max) COLLATE Chinese_PRC_CI_AS NULL,
	[ModifyDate] [smalldatetime] NULL,
 CONSTRAINT [PK_cvInfo] PRIMARY KEY CLUSTERED 
(
	[cvMainId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

GO
/****** Object:  Table [dbo].[cvJobPlacePublish]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[cvJobPlacePublish](
	[cvMainID] [int] NOT NULL,
	[dcRegionID] [varchar](6) COLLATE Chinese_PRC_CI_AS NOT NULL,
 CONSTRAINT [PK_cvJobPlacePublish] PRIMARY KEY CLUSTERED 
(
	[cvMainID] ASC,
	[dcRegionID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [CV]
) ON [CV]

GO
/****** Object:  Table [dbo].[cvJobType]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[cvJobType](
	[cvMainID] [int] NOT NULL,
	[dcJobTypeID] [smallint] NOT NULL,
 CONSTRAINT [PK_cvJobType] PRIMARY KEY CLUSTERED 
(
	[cvMainID] ASC,
	[dcJobTypeID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [CV]
) ON [CV]

GO
/****** Object:  Table [dbo].[cvJobTypePublish]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[cvJobTypePublish](
	[cvMainID] [int] NOT NULL,
	[dcJobTypeID] [smallint] NOT NULL,
 CONSTRAINT [PK_cvJobTypePublish] PRIMARY KEY CLUSTERED 
(
	[cvMainID] ASC,
	[dcJobTypeID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [CV]
) ON [CV]

GO
/****** Object:  Table [dbo].[cvLanguage]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[cvLanguage](
	[ID] [int] IDENTITY(1,1) NOT FOR REPLICATION NOT NULL,
	[cvMainID] [int] NOT NULL,
	[LanguageType] [tinyint] NOT NULL,
	[Mastery] [tinyint] NOT NULL,
	[ReadWrite] [tinyint] NULL,
	[Spoken] [tinyint] NULL,
	[Score] [nvarchar](30) COLLATE Chinese_PRC_CI_AS NULL,
	[ScoreEng] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
 CONSTRAINT [PK_cvLanguage] PRIMARY KEY NONCLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [CV]
) ON [CV]

GO
/****** Object:  Index [IX_cvLanguage_cvMainID]    Script Date: 2018/9/25 12:40:11 ******/
CREATE CLUSTERED INDEX [IX_cvLanguage_cvMainID] ON [dbo].[cvLanguage]
(
	[cvMainID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [CV]
GO
/****** Object:  Table [dbo].[cvLanguagePublish]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[cvLanguagePublish](
	[ID] [int] NOT NULL,
	[cvMainID] [int] NOT NULL,
	[LanguageType] [tinyint] NOT NULL,
 CONSTRAINT [PK_cvLanguagePublish] PRIMARY KEY NONCLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [CV]
) ON [CV]

GO
/****** Object:  Index [IX_cvLanguagePublish_cvMainID]    Script Date: 2018/9/25 12:40:11 ******/
CREATE CLUSTERED INDEX [IX_cvLanguagePublish_cvMainID] ON [dbo].[cvLanguagePublish]
(
	[cvMainID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [CV]
GO
/****** Object:  Table [dbo].[cvMainDel]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[cvMainDel](
	[ID] [int] NOT NULL,
	[paMainID] [int] NOT NULL,
	[Name] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[Degree] [tinyint] NULL,
	[dcMajorID] [smallint] NULL,
	[LastJobTypeID] [smallint] NULL,
	[LastIndustryID] [smallint] NULL,
	[JobName] [nvarchar](20) COLLATE Chinese_PRC_CI_AS NULL,
	[SubNodeNum] [tinyint] NULL,
	[RelatedWorkYears] [tinyint] NULL,
	[EmployType] [tinyint] NULL,
	[dcSalaryID] [tinyint] NULL,
	[IsNegotiable] [bit] NOT NULL,
	[Speciality] [varchar](max) COLLATE Chinese_PRC_CI_AS NULL,
	[SpecialityEng] [varchar](max) COLLATE Chinese_PRC_CI_AS NULL,
	[Attachment] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[WordFilename] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[cvType] [tinyint] NOT NULL,
	[IsNameHidden] [bit] NOT NULL,
	[IscvHidden] [bit] NOT NULL,
	[isOpen] [bit] NOT NULL,
	[cvLevel] [char](10) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[cvLevelEng] [char](10) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[VerifyResult] [tinyint] NOT NULL,
	[VerifyResultEng] [tinyint] NOT NULL,
	[Valid] [tinyint] NULL,
	[ViewNumber] [int] NOT NULL,
	[RefreshDate] [smalldatetime] NOT NULL,
	[IsVerified] [int] NULL,
	[SecondId] [varchar](10) COLLATE Chinese_PRC_CI_AS NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

GO
/****** Object:  Table [dbo].[cvMainPublish]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[cvMainPublish](
	[ID] [int] NOT NULL,
	[paMainID] [int] NOT NULL,
	[Degree] [tinyint] NULL,
	[dcMajorID] [smallint] NULL,
	[LastJobTypeID] [smallint] NULL,
	[LastIndustryID] [smallint] NULL,
	[JobName] [nvarchar](20) COLLATE Chinese_PRC_CI_AS NULL,
	[SubNodeNum] [tinyint] NULL,
	[RelatedWorkYears] [tinyint] NULL,
	[dcSalaryID] [tinyint] NULL,
	[IsNegotiable] [bit] NOT NULL,
	[Speciality] [nvarchar](max) COLLATE Chinese_PRC_CI_AS NULL,
	[SpecialityEng] [varchar](max) COLLATE Chinese_PRC_CI_AS NULL,
	[Attachment] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[Valid] [tinyint] NULL,
	[RefreshDate] [smalldatetime] NOT NULL,
	[EmployType] [tinyint] NULL,
	[SecondId] [varchar](10) COLLATE Chinese_PRC_CI_AS NULL,
 CONSTRAINT [PK_cvMainPublish] PRIMARY KEY NONCLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [CV]
) ON [CV] TEXTIMAGE_ON [CV]

GO
/****** Object:  Table [dbo].[cvProject]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[cvProject](
	[ID] [int] IDENTITY(1,1) NOT FOR REPLICATION NOT NULL,
	[cvMainID] [int] NOT NULL,
	[Name] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[NameEng] [varchar](250) COLLATE Chinese_PRC_CI_AS NULL,
	[StartDate] [int] NOT NULL,
	[EndDate] [int] NOT NULL,
	[Description] [nvarchar](1000) COLLATE Chinese_PRC_CI_AS NULL,
	[DescriptionEng] [varchar](max) COLLATE Chinese_PRC_CI_AS NULL,
	[Responsibilities] [nvarchar](200) COLLATE Chinese_PRC_CI_AS NULL,
	[ResponsibilitiesEng] [varchar](1000) COLLATE Chinese_PRC_CI_AS NULL,
 CONSTRAINT [PK_cvProject] PRIMARY KEY NONCLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [CV]
) ON [CV] TEXTIMAGE_ON [CV]

GO
/****** Object:  Index [IX_cvProject_cvMainID]    Script Date: 2018/9/25 12:40:11 ******/
CREATE CLUSTERED INDEX [IX_cvProject_cvMainID] ON [dbo].[cvProject]
(
	[cvMainID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [CV]
GO
/****** Object:  Table [dbo].[cvProjectPublish]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[cvProjectPublish](
	[ID] [int] NOT NULL,
	[cvMainID] [int] NOT NULL,
	[Name] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[Description] [nvarchar](1000) COLLATE Chinese_PRC_CI_AS NULL,
	[Responsibilities] [nvarchar](200) COLLATE Chinese_PRC_CI_AS NULL,
 CONSTRAINT [PK_cvProjectPublish] PRIMARY KEY NONCLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [CV]
) ON [CV]

GO
/****** Object:  Index [IX_cvProjectPublish_cvMainID]    Script Date: 2018/9/25 12:40:11 ******/
CREATE CLUSTERED INDEX [IX_cvProjectPublish_cvMainID] ON [dbo].[cvProjectPublish]
(
	[cvMainID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [CV]
GO
/****** Object:  Table [dbo].[CvSimilarCompare]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[CvSimilarCompare](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[CvMainID] [int] NOT NULL,
	[SimilarJobID] [int] NOT NULL,
	[JobNum] [int] NOT NULL,
	[AddDate] [datetime] NOT NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[cvTags]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[cvTags](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[cvMainID] [int] NOT NULL,
	[Tags] [nvarchar](30) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[AddDate] [datetime] NOT NULL,
	[VerifyDate] [smalldatetime] NULL,
 CONSTRAINT [PK_CvTags] PRIMARY KEY CLUSTERED 
(
	[id] 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].[cvTraining]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[cvTraining](
	[ID] [int] IDENTITY(1,1) NOT FOR REPLICATION NOT NULL,
	[cvMainID] [int] NOT NULL,
	[StartDate] [int] NOT NULL,
	[TimeLength] [tinyint] NOT NULL,
	[TimeUnit] [tinyint] NOT NULL,
	[Institution] [nvarchar](30) COLLATE Chinese_PRC_CI_AS NULL,
	[InstitutionEng] [varchar](150) COLLATE Chinese_PRC_CI_AS NULL,
	[Course] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[CourseEng] [varchar](250) COLLATE Chinese_PRC_CI_AS NULL,
	[City] [nvarchar](10) COLLATE Chinese_PRC_CI_AS NULL,
	[CityEng] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[Certificate] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[CertificateEng] [varchar](250) COLLATE Chinese_PRC_CI_AS NULL,
	[Details] [nvarchar](500) COLLATE Chinese_PRC_CI_AS NULL,
	[DetailsEng] [varchar](2500) COLLATE Chinese_PRC_CI_AS NULL,
 CONSTRAINT [PK_cvTraining] PRIMARY KEY NONCLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [CV]
) ON [CV]

GO
/****** Object:  Index [IX_cvTraining_cvMainID]    Script Date: 2018/9/25 12:40:11 ******/
CREATE CLUSTERED INDEX [IX_cvTraining_cvMainID] ON [dbo].[cvTraining]
(
	[cvMainID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [CV]
GO
/****** Object:  Table [dbo].[cvTrainingPublish]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[cvTrainingPublish](
	[ID] [int] NOT NULL,
	[cvMainID] [int] NOT NULL,
	[Institution] [nvarchar](30) COLLATE Chinese_PRC_CI_AS NULL,
	[Course] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[Certificate] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[Details] [nvarchar](500) COLLATE Chinese_PRC_CI_AS NULL,
 CONSTRAINT [PK_cvTrainingPublish] PRIMARY KEY NONCLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [CV]
) ON [CV]

GO
/****** Object:  Index [IX_cvTrainingPublish_cvMainID]    Script Date: 2018/9/25 12:40:11 ******/
CREATE CLUSTERED INDEX [IX_cvTrainingPublish_cvMainID] ON [dbo].[cvTrainingPublish]
(
	[cvMainID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [CV]
GO
/****** Object:  Table [dbo].[cvVoiceJobType]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[cvVoiceJobType](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[cvVoiceID] [int] NOT NULL,
	[dcJobTypeID] [smallint] NOT NULL,
 CONSTRAINT [PK_cvVoiceJobType] PRIMARY KEY CLUSTERED 
(
	[ID] 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].[cvVoiceText]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[cvVoiceText](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[voiceText] [nvarchar](100) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[AddDate] [smalldatetime] NOT NULL,
	[MatchDate] [smalldatetime] NULL,
 CONSTRAINT [PK_cvVoiceText] PRIMARY KEY CLUSTERED 
(
	[ID] 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].[DataSource]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[DataSource](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[DataSourceName] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Privi] [char](20) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Remark] [nvarchar](200) COLLATE Chinese_PRC_CI_AS NOT NULL,
 CONSTRAINT [PK_DataSource] PRIMARY KEY CLUSTERED 
(
	[Id] 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].[Datereport]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Datereport](
	[CountDate] [int] NOT NULL,
	[CompanyRegNum] [int] NOT NULL,
	[PersonRegNum] [int] NOT NULL,
	[NewJobNum] [int] NOT NULL,
	[DeleteJobNum] [int] NOT NULL,
	[Province_Id] [smallint] NOT NULL,
	[CompanyRegNum_Our] [int] NOT NULL,
	[PersonRegNum_Our] [int] NOT NULL,
	[ValidCompany] [int] NOT NULL,
	[ValidResume] [int] NOT NULL,
	[CompanyloginNum_Net] [int] NOT NULL,
	[PersonloginNum_Net] [int] NOT NULL,
	[DeleteCompanyNum] [int] NOT NULL,
	[CompanyPassed] [int] NOT NULL
) ON [BOthers]

GO
/****** Object:  Index [IX_Datereport_unique]    Script Date: 2018/9/25 12:40:11 ******/
CREATE CLUSTERED INDEX [IX_Datereport_unique] ON [dbo].[Datereport]
(
	[CountDate] ASC,
	[Province_Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers]
GO
/****** Object:  Table [dbo].[dcAlipayDic]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[dcAlipayDic](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[alipayId] [varchar](30) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[alipayDescription] [nvarchar](100) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[alipayParentId] [varchar](30) COLLATE Chinese_PRC_CI_AS NULL,
	[alipayLevel] [int] NULL,
	[qlrcId] [varchar](6) COLLATE Chinese_PRC_CI_AS NULL,
	[DataType] [tinyint] NULL,
 CONSTRAINT [PK_dcAlipayDic] PRIMARY KEY CLUSTERED 
(
	[id] 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].[dcAlipayDicConvert]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[dcAlipayDicConvert](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[qlrcId] [varchar](6) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[dcAlipayDicId] [int] NULL,
	[DataType] [tinyint] NULL,
 CONSTRAINT [PK_dcAlipayDicConvert] PRIMARY KEY CLUSTERED 
(
	[id] 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].[dcAppendix]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[dcAppendix](
	[ID] [smallint] NOT NULL,
	[Description] [varchar](200) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[DescriptionEng] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[Category] [tinyint] NOT NULL,
	[OrderNo] [smallint] NULL,
 CONSTRAINT [PK_dcAppendix] PRIMARY KEY CLUSTERED 
(
	[ID] 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].[dcAutoEmail]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[dcAutoEmail](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[Email] [varchar](30) COLLATE Chinese_PRC_CI_AS NULL,
 CONSTRAINT [PK_dcAutoEmail] PRIMARY KEY CLUSTERED 
(
	[id] 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].[dcBusinessCircle]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[dcBusinessCircle](
	[Id] [int] NOT NULL,
	[dcRegionId] [varchar](6) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Name] [nvarchar](10) COLLATE Chinese_PRC_CI_AS NOT NULL,
 CONSTRAINT [PK_dcBusinessCircle] PRIMARY KEY CLUSTERED 
(
	[Id] 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].[dcCareerStatus]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[dcCareerStatus](
	[ID] [tinyint] NOT NULL,
	[Description] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[DescriptionEng] [varchar](100) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[OrderNo] [tinyint] NOT NULL,
 CONSTRAINT [PK_dcCareerStatus] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 50) ON [PRIMARY]
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[dcChinese]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[dcChinese](
	[chs] [varchar](1000) COLLATE Chinese_PRC_CI_AS NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[dcCollege]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[dcCollege](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[COLNAME] [varchar](150) COLLATE Chinese_PRC_CI_AS NULL,
	[Pinyin] [varchar](150) COLLATE Chinese_PRC_CI_AS NULL,
	[Jianpin] [varchar](150) COLLATE Chinese_PRC_CI_AS NULL,
 CONSTRAINT [PK_dcCollege] PRIMARY KEY CLUSTERED 
(
	[ID] 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].[dcCompanyKind]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[dcCompanyKind](
	[ID] [smallint] NOT NULL,
	[Description] [nvarchar](10) COLLATE Chinese_PRC_CI_AS NULL,
	[DescriptionEng] [varchar](100) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[OrderNo] [tinyint] NOT NULL,
 CONSTRAINT [PK_dcCompanyKind] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 50) ON [PRIMARY]
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[dcCompanySize]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[dcCompanySize](
	[ID] [tinyint] NOT NULL,
	[Description] [nvarchar](20) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[DescriptionEng] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[ORderNo] [tinyint] NOT NULL,
 CONSTRAINT [PK_dcCompanySize] PRIMARY KEY CLUSTERED 
(
	[ID] 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].[dcCpMainIdTemp]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[dcCpMainIdTemp](
	[cpMainId] [int] NOT NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[dcCvConvertMap]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[dcCvConvertMap](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[WebName] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Type] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Description] [nvarchar](max) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[OurID] [int] NOT NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

GO
/****** Object:  Table [dbo].[dcCvOpenSet]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[dcCvOpenSet](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[dcProvinceId] [tinyint] NULL,
	[dcEducation] [tinyint] NULL,
	[Age] [tinyint] NULL,
 CONSTRAINT [PK_dcCvOpenSet] PRIMARY KEY CLUSTERED 
(
	[Id] 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].[dcEducation]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[dcEducation](
	[ID] [tinyint] NOT NULL,
	[Description] [nvarchar](10) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[DescriptionEng] [varchar](20) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[OrderNo] [tinyint] NOT NULL,
 CONSTRAINT [PK_dcEducation] PRIMARY KEY CLUSTERED 
(
	[ID] 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].[dcEduType]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[dcEduType](
	[ID] [tinyint] NOT NULL,
	[Description] [nvarchar](10) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[DescriptionEng] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[OrderNo] [tinyint] NOT NULL,
 CONSTRAINT [PK_dcEducationType] PRIMARY KEY CLUSTERED 
(
	[ID] 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].[dcEmailType]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[dcEmailType](
	[ID] [tinyint] IDENTITY(22,1) NOT NULL,
	[EmailType] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
 CONSTRAINT [PK_dcEmailType] PRIMARY KEY CLUSTERED 
(
	[ID] 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].[dcFee]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[dcFee](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[dcProvinceID] [tinyint] NOT NULL,
	[Name] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[StartDate] [smalldatetime] NOT NULL,
	[EndDate] [smalldatetime] NOT NULL,
	[Type] [tinyint] NOT NULL,
	[Price] [decimal](9, 2) NULL,
	[Remark] [nvarchar](500) COLLATE Chinese_PRC_CI_AS NULL,
	[AddDate] [smalldatetime] NOT NULL,
	[ManagerUserId] [smallint] NOT NULL,
	[CoinRation] [decimal](4, 2) NULL,
	[NeedPoint] [int] NULL,
 CONSTRAINT [PK_dcFee_1] PRIMARY KEY CLUSTERED 
(
	[ID] 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].[dcFeeDetail]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[dcFeeDetail](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[dcFeeID] [int] NOT NULL,
	[Name] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[MinValue] [smallint] NOT NULL,
	[MaxValue] [smallint] NULL,
	[Price] [decimal](9, 2) NULL,
	[Remark] [nvarchar](500) COLLATE Chinese_PRC_CI_AS NULL,
	[NeedPoint] [int] NULL,
 CONSTRAINT [PK_dcFeeDetail] PRIMARY KEY CLUSTERED 
(
	[ID] 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].[dcFeeStandard]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[dcFeeStandard](
	[dcProvinceID] [tinyint] NOT NULL,
	[PriceJob] [decimal](18, 0) NOT NULL,
	[PriceUser] [decimal](18, 0) NOT NULL,
	[PriceResume] [decimal](18, 0) NOT NULL,
	[MinJobNumber] [tinyint] NULL,
	[MinUserNumber] [tinyint] NULL,
	[MinResumeNumber] [tinyint] NULL,
	[PriceMonth] [decimal](18, 0) NOT NULL,
	[PriceAd1] [decimal](18, 0) NOT NULL,
	[PriceAd2] [decimal](18, 0) NOT NULL,
	[PriceAd3] [decimal](18, 0) NOT NULL,
	[PriceAd6] [decimal](18, 0) NOT NULL,
	[PriceAd22] [decimal](18, 0) NOT NULL,
	[PriceFixed] [decimal](18, 0) NOT NULL,
	[PriceCv] [int] NOT NULL,
	[PriceTop] [decimal](18, 0) NULL,
	[PriceRefresh] [int] NULL,
	[NeedPoint] [smallint] NULL,
	[PriceSms] [decimal](9, 2) NULL,
	[PriceJobRefreshNumber] [int] NULL,
	[PriceAssessReport] [decimal](18, 0) NULL,
 CONSTRAINT [PK_dcFeeStandard_1] PRIMARY KEY CLUSTERED 
(
	[dcProvinceID] 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].[dcFilterWord]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[dcFilterWord](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[Word] [nvarchar](20) COLLATE Chinese_PRC_CI_AS NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[dcIndustry]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[dcIndustry](
	[ID] [smallint] NOT NULL,
	[Description] [nvarchar](25) COLLATE Chinese_PRC_CI_AS NULL,
	[DescriptionEng] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[OrderNo] [smallint] NULL,
	[Category] [tinyint] NULL,
	[PinYin] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
 CONSTRAINT [PK_dcIndustry] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 50) ON [PRIMARY]
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[dcIndustryCategory]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[dcIndustryCategory](
	[CateGoryId] [tinyint] NOT NULL,
	[dcIndustryId] [smallint] NOT NULL,
 CONSTRAINT [PK_dcIndustryCategory] PRIMARY KEY CLUSTERED 
(
	[CateGoryId] ASC,
	[dcIndustryId] 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].[dcIndustryLogo]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[dcIndustryLogo](
	[FamilyId] [tinyint] NULL,
	[FamilyName] [nvarchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[dcIndustryId] [tinyint] NULL,
	[IndustryName] [nvarchar](20) COLLATE Chinese_PRC_CI_AS NULL,
	[LogoFile] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[dcIPPlace]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[dcIPPlace](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[IPStart] [bigint] NOT NULL,
	[IPEnd] [bigint] NOT NULL,
	[City] [varchar](300) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Provider] [varchar](300) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[International] [tinyint] NULL,
	[dcSubSiteId] [varchar](6) COLLATE Chinese_PRC_CI_AS NULL,
 CONSTRAINT [PK_dcIPPlace] PRIMARY KEY CLUSTERED 
(
	[ID] 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].[dcIpPlaceCity]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[dcIpPlaceCity](
	[City] [nvarchar](20) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[dcSubSiteID] [varchar](6) COLLATE Chinese_PRC_CI_AS NULL,
 CONSTRAINT [PK_dcIpPlaceCity] PRIMARY KEY CLUSTERED 
(
	[City] 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].[dcJobName]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[dcJobName](
	[Name] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[dcJobTypeId] [smallint] NOT NULL,
	[Cnt] [int] NULL,
 CONSTRAINT [PK_dcJobName] PRIMARY KEY CLUSTERED 
(
	[Name] ASC,
	[dcJobTypeId] 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].[dcJobTypeCategory]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[dcJobTypeCategory](
	[Id] [int] NOT NULL,
	[Description] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[DescriptionEng] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
 CONSTRAINT [PK_dcJobTypeCategory] PRIMARY KEY CLUSTERED 
(
	[Id] 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].[dcJobTypeHot]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[dcJobTypeHot](
	[ID] [smallint] IDENTITY(1,1) NOT NULL,
	[JobName] [nvarchar](10) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[dcJobTypeId] [varchar](200) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[pinyin] [varchar](100) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[OrderNo] [int] NULL,
 CONSTRAINT [PK_dcJobTypeHot] PRIMARY KEY CLUSTERED 
(
	[ID] 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].[dcJobTypeHotNumber]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[dcJobTypeHotNumber](
	[dcProvinceId] [int] NULL,
	[dcJobTypeHotID] [int] NOT NULL,
	[JobNumber] [int] NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[dcJobTypeMap]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[dcJobTypeMap](
	[CategoryId] [int] NOT NULL,
	[JobTypeId] [smallint] NOT NULL,
	[Grade] [tinyint] NULL,
	[JobNumber] [int] NULL,
	[OrderBy] [tinyint] NULL,
 CONSTRAINT [PK_dcJobTypeMap] PRIMARY KEY CLUSTERED 
(
	[CategoryId] ASC,
	[JobTypeId] 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].[dcJobTypeSimilar]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[dcJobTypeSimilar](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[dcJobTypeId] [smallint] NOT NULL,
	[SimilarId] [smallint] NOT NULL,
	[Coefficient] [tinyint] NOT NULL,
 CONSTRAINT [PK_dcJobTypeSimilar] PRIMARY KEY CLUSTERED 
(
	[ID] 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].[dcJobTypeTemplate]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[dcJobTypeTemplate](
	[dcJobTypeID] [int] NOT NULL,
	[Responsibility] [nvarchar](500) COLLATE Chinese_PRC_CI_AS NULL,
	[Demand] [nvarchar](500) COLLATE Chinese_PRC_CI_AS NULL,
	[Promotion] [nvarchar](500) COLLATE Chinese_PRC_CI_AS NULL,
 CONSTRAINT [PK_dcJobTypetTmplate] PRIMARY KEY CLUSTERED 
(
	[dcJobTypeID] 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].[dcJobTypeTop6]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[dcJobTypeTop6](
	[Id] [smallint] NOT NULL,
	[Id2] [varchar](4) COLLATE Chinese_PRC_CI_AS NULL,
	[Description] [nvarchar](25) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[RowNo] [int] NOT NULL
) ON [PRIMARY]

GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_dcJobTypeTop6_Id2]    Script Date: 2018/9/25 12:40:11 ******/
CREATE CLUSTERED INDEX [IX_dcJobTypeTop6_Id2] ON [dbo].[dcJobTypeTop6]
(
	[Id2] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[dcLanguage]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[dcLanguage](
	[ID] [tinyint] NOT NULL,
	[Description] [nvarchar](10) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[DescriptionEng] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[OrderNo] [tinyint] NOT NULL,
 CONSTRAINT [PK_dcLanguage] PRIMARY KEY CLUSTERED 
(
	[ID] 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].[dcLeaveReson]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[dcLeaveReson](
	[ID] [tinyint] NOT NULL,
	[Description] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[DescriptionEng] [varchar](130) COLLATE Chinese_PRC_CI_AS NULL,
	[OrderNo] [tinyint] NULL,
 CONSTRAINT [PK_dcLeaveType] PRIMARY KEY CLUSTERED 
(
	[ID] 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].[dcLimitCookies]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[dcLimitCookies](
	[LoginCookies] [varchar](16) COLLATE Chinese_PRC_CI_AS NULL,
	[LimitType] [tinyint] NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[dcLimitIp]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[dcLimitIp](
	[loginip] [varchar](39) COLLATE Chinese_PRC_CI_AS NULL,
	[LimitType] [tinyint] NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[dcLinkManager]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[dcLinkManager](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[SubSiteId] [int] NOT NULL,
	[GroupId] [int] NULL,
	[ManagerUserId] [smallint] NULL,
 CONSTRAINT [PK_dcLinkManager] PRIMARY KEY CLUSTERED 
(
	[id] 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].[dcLowerNumber]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[dcLowerNumber](
	[ID] [tinyint] NOT NULL,
	[Description] [nvarchar](10) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[DescriptionEng] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[OrderNo] [tinyint] NOT NULL,
 CONSTRAINT [PK_dcLowerNumber] PRIMARY KEY CLUSTERED 
(
	[ID] 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].[dcMajor]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[dcMajor](
	[ID] [smallint] NOT NULL,
	[MajorCategoryID] [tinyint] NOT NULL,
	[Description] [nvarchar](20) COLLATE Chinese_PRC_CI_AS NULL,
	[DescriptionEng] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[OrderNo] [smallint] NOT NULL,
 CONSTRAINT [PK_dcMajor] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 50) ON [PRIMARY]
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[dcMajor1125]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[dcMajor1125](
	[ID] [smallint] NOT NULL,
	[MajorCategoryID] [tinyint] NOT NULL,
	[Description] [nchar](20) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[DescriptionEng] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[OrderNo] [smallint] NOT NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[dcMajor20170516]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[dcMajor20170516](
	[ID] [smallint] NOT NULL,
	[MajorCategoryID] [tinyint] NOT NULL,
	[Description] [nchar](20) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[DescriptionEng] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[OrderNo] [smallint] NOT NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[dcMajorCategory]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[dcMajorCategory](
	[ID] [tinyint] NOT NULL,
	[Description] [nvarchar](20) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[DescriptionEng] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[OrderNo] [tinyint] NOT NULL,
 CONSTRAINT [PK_dcMajorCategory] PRIMARY KEY CLUSTERED 
(
	[ID] 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].[dcMajorCategory20170515]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[dcMajorCategory20170515](
	[ID] [tinyint] NOT NULL,
	[Description] [nvarchar](20) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[DescriptionEng] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[OrderNo] [tinyint] NOT NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[dcMajorKeyword]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[dcMajorKeyword](
	[MajorName] [nvarchar](20) COLLATE Chinese_PRC_CI_AS NULL,
	[dcMajorId] [int] NULL,
	[PinYin] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[JianPin] [varchar](30) COLLATE Chinese_PRC_CI_AS NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[dcMapLine]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[dcMapLine](
	[ID] [int] IDENTITY(1,1) NOT FOR REPLICATION NOT NULL,
	[dcRegionId] [varchar](6) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Name] [nvarchar](20) COLLATE Chinese_PRC_CI_AS NULL,
	[OrderNo] [int] NOT NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[dcMapPlace]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[dcMapPlace](
	[ID] [int] IDENTITY(1,1) NOT FOR REPLICATION NOT NULL,
	[dcRegionID] [varchar](6) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Name] [nvarchar](20) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[OrderNo] [int] NOT NULL,
	[Lng] [decimal](8, 5) NULL,
	[Lat] [decimal](8, 5) NULL,
	[IsHot] [bit] NULL,
 CONSTRAINT [PK_dcMapPlace] PRIMARY KEY NONCLUSTERED 
(
	[ID] 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 ON

GO
/****** Object:  Index [ix_dcMapPlace_dcRegionID]    Script Date: 2018/9/25 12:40:11 ******/
CREATE CLUSTERED INDEX [ix_dcMapPlace_dcRegionID] ON [dbo].[dcMapPlace]
(
	[dcRegionID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[dcMapStation]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[dcMapStation](
	[ID] [int] IDENTITY(1,1) NOT FOR REPLICATION NOT NULL,
	[dcMapLineId] [int] NOT NULL,
	[Name] [nvarchar](20) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[OrderNo] [int] NOT NULL,
	[Lng] [decimal](8, 5) NULL,
	[Lat] [decimal](8, 5) NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[dcMobileArea]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[dcMobileArea](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[Num] [varchar](7) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[City] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[CardType] [nvarchar](20) COLLATE Chinese_PRC_CI_AS NULL,
	[dcRegionId] [varchar](6) COLLATE Chinese_PRC_CI_AS NULL,
 CONSTRAINT [PK_dcMobileArea] PRIMARY KEY CLUSTERED 
(
	[ID] 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].[dcMobileCard]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[dcMobileCard](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[Cardno] [varchar](11) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[SetType] [tinyint] NOT NULL,
	[Portno] [tinyint] NOT NULL,
	[BeginDate] [datetime] NOT NULL,
	[EndDate] [datetime] NOT NULL,
 CONSTRAINT [PK_MobileCard] PRIMARY KEY CLUSTERED 
(
	[id] 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].[dcMsgType]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[dcMsgType](
	[id] [int] NULL,
	[MsgType] [nvarchar](100) COLLATE Chinese_PRC_CI_AS NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[dcNation]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[dcNation](
	[ID] [tinyint] IDENTITY(1,1) NOT NULL,
	[Description] [nvarchar](10) COLLATE Chinese_PRC_CI_AS NULL,
	[DescriptionEng] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL,
	[OrderNo] [tinyint] NULL,
 CONSTRAINT [PK_dcNation] PRIMARY KEY CLUSTERED 
(
	[ID] 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].[dcNewsType]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[dcNewsType](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[Category] [tinyint] NOT NULL,
	[NewsType] [nvarchar](20) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[OrderNo] [int] NOT NULL,
 CONSTRAINT [PK_dcNewsType] PRIMARY KEY CLUSTERED 
(
	[Id] 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].[dcOnlineContact]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[dcOnlineContact](
	[ID] [tinyint] NOT NULL,
	[Description] [varchar](20) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[DescriptionEng] [varchar](20) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[OrderNo] [tinyint] NOT NULL,
 CONSTRAINT [PK_dcOnlineContact] PRIMARY KEY CLUSTERED 
(
	[ID] 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].[dcOnlineContactHistory]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[dcOnlineContactHistory](
	[ID] [tinyint] NOT NULL,
	[Description] [varchar](20) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[DescriptionEng] [varchar](20) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[OrderNo] [tinyint] NOT NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[dcOthers]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[dcOthers](
	[ID] [int] NOT NULL,
	[Category] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[DetailID] [tinyint] NOT NULL,
	[Description] [nvarchar](10) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[DescriptionEng] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[OrderNo] [tinyint] NOT NULL,
	[Number] [smallint] NULL,
 CONSTRAINT [PK_dcOthers] PRIMARY KEY CLUSTERED 
(
	[ID] ASC,
	[DetailID] 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].[dcPassword]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[dcPassword](
	[id] [int] NULL,
	[PwdText] [varchar](6) COLLATE Chinese_PRC_CI_AS NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[dcPayMethod]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[dcPayMethod](
	[PayMethodID] [tinyint] NOT NULL,
	[Name] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[OrderBy] [tinyint] NULL,
	[Homepage] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL,
	[FrontShow] [bit] NULL,
 CONSTRAINT [PK_dcPayMethodRemark] PRIMARY KEY CLUSTERED 
(
	[PayMethodID] 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].[dcPayMethodProvince]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[dcPayMethodProvince](
	[dcProvinceID] [int] NOT NULL,
	[PayMethodID] [tinyint] NOT NULL,
	[Receiver] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[Account] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[BankName] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[JointNo] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL,
 CONSTRAINT [PK_dcPayMethod] PRIMARY KEY CLUSTERED 
(
	[dcProvinceID] ASC,
	[PayMethodID] 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].[dcProvinceNear]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[dcProvinceNear](
	[dcProvinceID] [tinyint] NOT NULL,
	[NearProvinceId] [tinyint] NOT NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[dcRegion]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[dcRegion](
	[ID] [varchar](6) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Grade] [tinyint] NOT NULL,
	[ParentID] [varchar](6) COLLATE Chinese_PRC_CI_AS NULL,
	[Description] [nvarchar](20) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[DescriptionEng] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[OrderNo] [int] NULL,
	[FullName] [nvarchar](20) COLLATE Chinese_PRC_CI_AS NULL,
	[MapBarName] [nvarchar](20) COLLATE Chinese_PRC_CI_AS NULL,
	[Lng] [decimal](8, 5) NULL,
	[Lat] [decimal](8, 5) NULL,
	[Abbr] [nvarchar](10) COLLATE Chinese_PRC_CI_AS NULL,
	[PinYin] [varchar](30) COLLATE Chinese_PRC_CI_AS NULL,
	[TQPinYin] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL,
 CONSTRAINT [PK_dcRegion] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 50) ON [PRIMARY]
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[dcRegionTDK]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[dcRegionTDK](
	[id] [varchar](6) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Title] [nvarchar](500) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Description] [nvarchar](500) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Keyword] [nvarchar](500) COLLATE Chinese_PRC_CI_AS NOT NULL,
 CONSTRAINT [PK_dcRegionTDK] PRIMARY KEY CLUSTERED 
(
	[id] 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].[dcRunParameter]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[dcRunParameter](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[Name] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Description] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Value] [varchar](1000) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[System] [int] NOT NULL,
 CONSTRAINT [PK_dcRunParameter] PRIMARY KEY CLUSTERED 
(
	[Id] 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].[dcSalary]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[dcSalary](
	[ID] [tinyint] NOT NULL,
	[Description] [nvarchar](20) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[DescriptionEng] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[OrderNo] [smallint] NOT NULL,
	[Salary] [int] NULL,
	[DescriptionCp] [nvarchar](10) COLLATE Chinese_PRC_CI_AS NULL,
 CONSTRAINT [PK_dcSalary] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 50) ON [PRIMARY]
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[dcSalary2]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[dcSalary2](
	[ID] [tinyint] NOT NULL,
	[Description] [nvarchar](20) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[DescriptionEng] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[OrderNo] [smallint] NOT NULL,
	[Salary] [int] NULL,
	[DescriptionCp] [nvarchar](10) COLLATE Chinese_PRC_CI_AS NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[dcSmsNo]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[dcSmsNo](
	[Id] [int] NULL,
	[Description] [nvarchar](200) COLLATE Chinese_PRC_CI_AS NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[dcSystemData]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[dcSystemData](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[Name] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Value] [decimal](18, 2) NOT NULL,
 CONSTRAINT [PK_dcSystemData] PRIMARY KEY CLUSTERED 
(
	[Id] 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].[dcTelArea]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[dcTelArea](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[AreaNo] [int] NULL,
	[City] [nvarchar](9) COLLATE Chinese_PRC_CI_AS NULL,
	[Province] [nvarchar](8) COLLATE Chinese_PRC_CI_AS NULL,
 CONSTRAINT [PK_dcTelArea] PRIMARY KEY CLUSTERED 
(
	[ID] 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].[dcVip]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[dcVip](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[dcProvinceID] [tinyint] NOT NULL,
	[name] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[startDate] [smalldatetime] NOT NULL,
	[endDate] [smalldatetime] NOT NULL,
	[PriceJob] [decimal](18, 0) NOT NULL,
	[PriceUser] [decimal](18, 0) NOT NULL,
	[PriceResume] [decimal](18, 0) NOT NULL,
	[MinJobNumber] [tinyint] NULL,
	[MinUserNumber] [tinyint] NULL,
	[MinResumeNumber] [tinyint] NULL,
	[PriceMonth] [float] NOT NULL,
	[Remark] [nvarchar](500) COLLATE Chinese_PRC_CI_AS NULL,
	[addDate] [smalldatetime] NOT NULL,
	[ManagerUserID] [smallint] NOT NULL,
	[NeedPoint] [int] NULL,
	[CoinRation] [decimal](4, 2) NULL,
	[PriceSms] [decimal](5, 2) NULL,
	[MinSmsNumber] [int] NULL,
	[priceJobrefreshNumber] [int] NULL,
	[MinJobrefreshNumber] [int] NULL,
	[PriceAssessReport] [decimal](18, 0) NULL,
 CONSTRAINT [PK_dcVip] PRIMARY KEY CLUSTERED 
(
	[ID] 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].[dcVipDetail]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[dcVipDetail](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[dcVipID] [int] NOT NULL,
	[DetailName] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[TimeTitle] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Month] [tinyint] NOT NULL,
	[JobNumber] [int] NOT NULL,
	[UserNumber] [int] NOT NULL,
	[ResumeNumber] [int] NOT NULL,
	[Price] [decimal](18, 0) NOT NULL,
	[Remark] [nvarchar](500) COLLATE Chinese_PRC_CI_AS NULL,
	[ISRecommend] [bit] NULL,
	[IsShowFront] [tinyint] NULL,
	[Discount] [tinyint] NULL,
	[NeedPoint] [int] NULL,
	[GivePoint] [int] NULL,
	[SmsNumber] [int] NULL,
	[JobRefreshNumber] [int] NULL,
	[AssessReportNumber] [int] NULL,
 CONSTRAINT [PK_dcVipDetails] PRIMARY KEY CLUSTERED 
(
	[ID] 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].[dcVipTryOut]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[dcVipTryOut](
	[ID] [int] NOT NULL,
	[dcVipID] [int] NOT NULL,
	[DetailName] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[TimeTitle] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Month] [tinyint] NOT NULL,
	[JobNumber] [int] NOT NULL,
	[UserNumber] [int] NOT NULL,
	[ResumeNumber] [int] NOT NULL,
	[Price] [decimal](18, 0) NOT NULL,
	[Remark] [nvarchar](500) COLLATE Chinese_PRC_CI_AS NULL,
	[ISRecommend] [bit] NULL,
	[IsShowFront] [tinyint] NULL,
	[Discount] [tinyint] NULL,
	[NeedPoint] [int] NULL,
	[PriceJOb] [decimal](18, 0) NOT NULL,
	[PriceUser] [decimal](18, 0) NOT NULL,
	[PriceResume] [decimal](18, 0) NOT NULL,
	[PriceMonth] [float] NOT NULL,
	[Name] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[SmsNumber] [smallint] NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[dcWxToken]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[dcWxToken](
	[dcProvinceId] [tinyint] NULL,
	[Token] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL,
	[AddDate] [datetime] NULL,
	[jsapi_ticket] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL,
	[jsapi_ticket_AddDate] [smalldatetime] NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[dcZip]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[dcZip](
	[Zip] [varchar](6) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Province] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[City] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
 CONSTRAINT [PK_dcZip] PRIMARY KEY CLUSTERED 
(
	[Zip] 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].[dwnclass1]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[dwnclass1](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[title] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[dir] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[adddate] [smalldatetime] NOT NULL,
	[danwei] [bit] NOT NULL,
	[geren] [bit] NOT NULL,
	[power] [smallint] NOT NULL,
 CONSTRAINT [PK_dwnclass1] PRIMARY KEY CLUSTERED 
(
	[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [FOthers]
) ON [FOthers]

GO
/****** Object:  Table [dbo].[dwnclass2]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[dwnclass2](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[title] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[dir] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[adddate] [smalldatetime] NOT NULL,
	[class1id] [int] NOT NULL,
	[danwei] [bit] NOT NULL,
	[geren] [bit] NOT NULL,
	[power] [smallint] NOT NULL,
 CONSTRAINT [PK_dwnclass2] PRIMARY KEY CLUSTERED 
(
	[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [FOthers]
) ON [FOthers]

GO
/****** Object:  Table [dbo].[dwndoc]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[dwndoc](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[name] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[lgg] [smallint] NOT NULL,
	[adddate] [smalldatetime] NOT NULL,
	[filetype] [smallint] NOT NULL,
	[description] [nvarchar](500) COLLATE Chinese_PRC_CI_AS NULL,
	[authtype] [smallint] NOT NULL,
	[dwnnum] [int] NOT NULL,
	[classid] [int] NOT NULL,
	[filename] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[power] [smallint] NOT NULL,
	[geren] [bit] NOT NULL,
	[danwei] [bit] NOT NULL,
	[updatedate] [smalldatetime] NOT NULL,
	[HtmlContent] [nvarchar](max) COLLATE Chinese_PRC_CI_AS NULL,
 CONSTRAINT [PK_dwndoc] PRIMARY KEY CLUSTERED 
(
	[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [FOthers]
) ON [FOthers] TEXTIMAGE_ON [FOthers]

GO
/****** Object:  Table [dbo].[Email_SentTest]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Email_SentTest](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[email] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[manageruserid] [int] NOT NULL,
	[adddate] [smalldatetime] NOT NULL,
	[emailtype] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[cc_email] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
 CONSTRAINT [PK_email_senttest] PRIMARY KEY CLUSTERED 
(
	[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers]
) ON [BOthers]

GO
/****** Object:  Table [dbo].[Email_SentTest_Log]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Email_SentTest_Log](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[email_senttest_id] [int] NOT NULL,
	[host] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[subject] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[body] [nvarchar](1000) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[fromemail] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[fromname] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[adddate] [smalldatetime] NOT NULL,
	[status] [smallint] NOT NULL,
	[remarks] [nvarchar](500) COLLATE Chinese_PRC_CI_AS NULL,
	[province_id] [tinyint] NULL,
	[type] [smallint] NULL,
	[code] [varchar](6) COLLATE Chinese_PRC_CI_AS NULL,
 CONSTRAINT [PK_email_senttest_log] PRIMARY KEY CLUSTERED 
(
	[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers]
) ON [BOthers]

GO
/****** Object:  Table [dbo].[EmailBody]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[EmailBody](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[EmailBody] [nvarchar](max) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[EmailKey] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[province_id] [tinyint] NULL,
	[schSqlID] [smallint] NOT NULL,
	[AddDate] [smalldatetime] NOT NULL,
 CONSTRAINT [PK_EmailBody] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers]
) ON [BOthers] TEXTIMAGE_ON [BOthers]

GO
/****** Object:  Table [dbo].[EmailCheck]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[EmailCheck](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[testdate] [char](8) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[planhour] [smallint] NOT NULL,
	[sendtime] [smalldatetime] NULL,
	[replylong] [smallint] NULL,
	[manageruserid] [int] NOT NULL,
	[planminute] [smallint] NULL,
	[remarks] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL
) ON [BOthers]

GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_Emailcheck_TestDate]    Script Date: 2018/9/25 12:40:11 ******/
CREATE CLUSTERED INDEX [IX_Emailcheck_TestDate] ON [dbo].[EmailCheck]
(
	[testdate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers]
GO
/****** Object:  Table [dbo].[EmailCompany]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[EmailCompany](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[CompanyId] [int] NOT NULL,
	[Title] [varchar](300) COLLATE Chinese_PRC_CI_AS NULL,
	[Detail] [nvarchar](max) COLLATE Chinese_PRC_CI_AS NULL,
	[AddDate] [smalldatetime] NOT NULL,
	[Type] [smallint] NOT NULL,
	[Email] [varchar](100) COLLATE Chinese_PRC_CI_AS NOT NULL,
 CONSTRAINT [PK_EmailCompany] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers]
) ON [BOthers] TEXTIMAGE_ON [PRIMARY]

GO
/****** Object:  Table [dbo].[EmailDomain]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[EmailDomain](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[EmailDomain] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[EmailKey] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[province_id] [tinyint] NOT NULL,
	[adddate] [smalldatetime] NULL,
 CONSTRAINT [PK_EmailDomain] PRIMARY KEY CLUSTERED 
(
	[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers]
) ON [BOthers]

GO
/****** Object:  Table [dbo].[EmailTitleold]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[EmailTitleold](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[EmailTitle] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[EmailKey] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[province_id] [tinyint] NOT NULL,
	[adddate] [smalldatetime] NOT NULL,
	[EmailTitle_person] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
 CONSTRAINT [PK_EmailTitle] PRIMARY KEY CLUSTERED 
(
	[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers]
) ON [BOthers]

GO
/****** Object:  Table [dbo].[EmailType]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[EmailType](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[EmailType] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
 CONSTRAINT [PK_EmailType] PRIMARY KEY CLUSTERED 
(
	[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers]
) ON [BOthers]

GO
/****** Object:  Table [dbo].[EmailUser]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[EmailUser](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[EmailUser] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[EmailKey] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[province_id] [int] NOT NULL,
	[adddate] [smalldatetime] NULL,
 CONSTRAINT [PK_EmailUser] PRIMARY KEY CLUSTERED 
(
	[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers]
) ON [BOthers]

GO
/****** Object:  Table [dbo].[ErrorLog]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ErrorLog](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[ErrorMessage] [nvarchar](max) COLLATE Chinese_PRC_CI_AS NULL,
	[ErrorNumber] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[ErrorLine] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[AddDate] [datetime] NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

GO
/****** Object:  Table [dbo].[exImage]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[exImage](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[OutID] [int] NOT NULL,
	[OutType] [tinyint] NOT NULL,
	[UniqueID] [varchar](20) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[AddDate] [smalldatetime] NOT NULL,
 CONSTRAINT [PK_exImage] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Interaction]
) ON [Interaction]

GO
/****** Object:  Table [dbo].[exInterview]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[exInterview](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[JobID] [int] NOT NULL,
	[cvMainID] [int] NOT NULL,
	[InterviewDate] [nvarchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[InterViewPlace] [nvarchar](100) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[LinkMan] [nvarchar](25) COLLATE Chinese_PRC_CI_AS NULL,
	[Telephone] [varchar](25) COLLATE Chinese_PRC_CI_AS NULL,
	[Remark] [varchar](1000) COLLATE Chinese_PRC_CI_AS NULL,
	[AddDate] [smalldatetime] NOT NULL,
	[Reply] [tinyint] NOT NULL,
	[ReplyMessage] [varchar](500) COLLATE Chinese_PRC_CI_AS NULL,
	[Replydate] [smalldatetime] NULL,
	[CompanyDeleted] [bit] NOT NULL,
	[CompanyDeleteDate] [smalldatetime] NULL,
	[PersonDeleted] [bit] NOT NULL,
	[PersonDeleteDate] [smalldatetime] NULL,
	[ViewDate] [smalldatetime] NULL,
	[Result] [bit] NULL,
	[ResultDate] [smalldatetime] NULL,
	[CheckMan] [smallint] NULL,
	[CheckDate] [smalldatetime] NULL,
	[SmsNumber] [tinyint] NULL,
	[CpResultViewDate] [datetime] NULL,
 CONSTRAINT [PK_exInterview] PRIMARY KEY NONCLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Interaction]
) ON [Interaction]

GO
/****** Object:  Index [IX_exInterview_cvMainID]    Script Date: 2018/9/25 12:40:11 ******/
CREATE CLUSTERED INDEX [IX_exInterview_cvMainID] ON [dbo].[exInterview]
(
	[cvMainID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Interaction]
GO
/****** Object:  Table [dbo].[exJobApplyMonthTemp]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[exJobApplyMonthTemp](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[JobId] [int] NOT NULL,
	[CvMainID] [int] NOT NULL,
 CONSTRAINT [PK_exJobApplyMothTemp] PRIMARY KEY CLUSTERED 
(
	[id] 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].[exMessageC2P]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[exMessageC2P](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[caMainID] [int] NOT NULL,
	[cvMainID] [int] NOT NULL,
	[Message] [varchar](500) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[AddDate] [smalldatetime] NOT NULL,
	[IsViewed] [bit] NOT NULL,
	[IsReply] [bit] NOT NULL,
	[CompanyDeleted] [bit] NOT NULL,
	[PersonDeleted] [bit] NOT NULL,
	[CheckMan] [smallint] NULL,
	[CheckDate] [smalldatetime] NULL,
 CONSTRAINT [PK_exMessageC2P] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Interaction]
) ON [Interaction]

GO
/****** Object:  Table [dbo].[exMessageP2C]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[exMessageP2C](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[caMainID] [int] NOT NULL,
	[cvMainID] [int] NOT NULL,
	[Message] [varchar](200) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[AddDate] [smalldatetime] NOT NULL,
	[IsViewed] [bit] NOT NULL,
	[IsReply] [bit] NOT NULL,
	[CompanyDeleted] [bit] NOT NULL,
	[PersonDeleted] [bit] NOT NULL,
	[CheckMan] [smallint] NULL,
	[CheckDate] [smalldatetime] NULL,
 CONSTRAINT [PK_exMessageP2C] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Interaction]
) ON [Interaction]

GO
/****** Object:  Table [dbo].[ExtendLink]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ExtendLink](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[CpMainID] [int] NOT NULL,
	[AddDate] [smalldatetime] NOT NULL,
	[Keyword] [nvarchar](20) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[KeywordUrl] [varchar](300) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[CustomLink] [varchar](300) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[RunStatus] [tinyint] NULL,
	[LinkStatus] [tinyint] NOT NULL,
	[ShowType] [tinyint] NOT NULL,
	[ShowDay] [tinyint] NOT NULL,
	[IDs] [int] NULL,
	[BlackReason] [nvarchar](200) COLLATE Chinese_PRC_CI_AS NULL,
	[NextRunDate] [smalldatetime] NOT NULL,
	[LinkStatusPre] [tinyint] NULL,
	[BlackReasonPre] [nvarchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[ManagerUserID] [int] NULL,
 CONSTRAINT [PK_ExtendLink] PRIMARY KEY NONCLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [Index]

GO
/****** Object:  Index [IX_ExtendLink_cpMainId]    Script Date: 2018/9/25 12:40:11 ******/
CREATE CLUSTERED INDEX [IX_ExtendLink_cpMainId] ON [dbo].[ExtendLink]
(
	[CpMainID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Table [dbo].[ExtendLinkCheckLog]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ExtendLinkCheckLog](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[ExtendLinkID] [int] NOT NULL,
	[CpMainID] [int] NOT NULL,
	[CheckMan] [smallint] NOT NULL,
	[CheckResult] [tinyint] NOT NULL,
	[CheckDate] [smalldatetime] NOT NULL,
	[Note] [nvarchar](1000) COLLATE Chinese_PRC_CI_AS NULL,
 CONSTRAINT [PK_ExtendLinkCheckLog] PRIMARY KEY NONCLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [FOthers]

GO
/****** Object:  Index [IX_ExtendLinkCheckLog_cpMainId]    Script Date: 2018/9/25 12:40:11 ******/
CREATE CLUSTERED INDEX [IX_ExtendLinkCheckLog_cpMainId] ON [dbo].[ExtendLinkCheckLog]
(
	[CpMainID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [FOthers]
GO
/****** Object:  Table [dbo].[ExtendLinkRunLog]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ExtendLinkRunLog](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[CpMainID] [int] NOT NULL,
	[ShowType] [tinyint] NOT NULL,
	[BeginDate] [smalldatetime] NOT NULL,
	[EndDate] [smalldatetime] NOT NULL,
	[IDs] [int] NULL,
 CONSTRAINT [PK_ExtendLinkRunLog] PRIMARY KEY NONCLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [FOthers]

GO
/****** Object:  Index [IX_ExtendLinkRunLog_CpMainId]    Script Date: 2018/9/25 12:40:11 ******/
CREATE CLUSTERED INDEX [IX_ExtendLinkRunLog_CpMainId] ON [dbo].[ExtendLinkRunLog]
(
	[CpMainID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [FOthers]
GO
/****** Object:  Table [dbo].[Faq]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Faq](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[Question] [nvarchar](200) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Answer] [nvarchar](1000) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Power] [smallint] NOT NULL,
	[ClickNum] [int] NOT NULL,
	[Type] [smallint] NOT NULL,
	[AddDate] [smalldatetime] NOT NULL,
	[ModifyDate] [smalldatetime] NOT NULL,
	[CategoryID] [smallint] NULL,
 CONSTRAINT [PK_faq] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers]
) ON [BOthers]

GO
/****** Object:  Table [dbo].[FaxReceive]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[FaxReceive](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[ManagerUserId] [int] NULL,
	[CompanyId] [int] NULL,
	[FileName] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[FaxNumber] [varchar](20) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[ReceiveDate] [datetime] NULL,
	[AddDate] [datetime] NOT NULL,
	[isSuccess] [bit] NOT NULL,
	[SortTime] [datetime] NULL,
	[SortMan] [int] NULL,
	[Price] [decimal](18, 2) NULL,
	[IsDone] [bit] NULL,
	[DoneDate] [smalldatetime] NULL,
	[passage] [tinyint] NULL,
	[PageNumber] [smallint] NULL,
	[CompanyMemo] [nvarchar](10) COLLATE Chinese_PRC_CI_AS NULL,
	[SortMinute] [smallint] NULL,
 CONSTRAINT [PK_FaxReceive] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers]
) ON [BOthers]

GO
/****** Object:  Table [dbo].[FaxSend]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[FaxSend](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[CompanyId] [int] NOT NULL,
	[ManagerUserId] [int] NOT NULL,
	[FileName] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL,
	[FaxNumber] [varchar](20) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[JobNumber] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[AddDate] [datetime] NOT NULL,
	[SendSuccess] [smallint] NULL,
	[Passage] [tinyint] NOT NULL,
	[Price] [decimal](18, 2) NULL,
	[PageNumber] [smallint] NULL,
 CONSTRAINT [PK_FaxSend] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers]
) ON [BOthers]

GO
/****** Object:  Table [dbo].[Feedback_NoReg]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Feedback_NoReg](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[Content] [nvarchar](2000) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[AddDate] [smalldatetime] NOT NULL,
	[Name] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Ip] [varchar](20) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Telephone] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[Email] [varchar](100) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Province_Id] [tinyint] NOT NULL,
	[Reply] [bit] NOT NULL,
	[Reply_Date] [smalldatetime] NULL,
	[Reply_Man] [int] NULL,
 CONSTRAINT [PK_feedback_noreg] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [FOthers]
) ON [FOthers]

GO
/****** Object:  Table [dbo].[FeeLog]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[FeeLog](
	[Company_Id] [int] NOT NULL,
	[Occur_Date] [smalldatetime] NOT NULL,
	[Money] [numeric](18, 0) NULL
) ON [FOthers]

GO
/****** Object:  Index [IX_Feelog_occur_Date]    Script Date: 2018/9/25 12:40:11 ******/
CREATE CLUSTERED INDEX [IX_Feelog_occur_Date] ON [dbo].[FeeLog]
(
	[Occur_Date] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [FOthers]
GO
/****** Object:  Table [dbo].[FlowChart]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[FlowChart](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[Title] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[DescrIption] [nvarchar](1000) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[addDate] [smalldatetime] NOT NULL,
	[Type] [smallint] NOT NULL,
	[ManagerUserId] [smallint] NOT NULL,
	[attachment1] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[privi] [varchar](500) COLLATE Chinese_PRC_CI_AS NULL,
	[attachment2] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
 CONSTRAINT [PK_FlowChart] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers]
) ON [BOthers]

GO
/****** Object:  Table [dbo].[FnBankCheck]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[FnBankCheck](
	[Id] [varchar](12) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Kind] [smallint] NOT NULL,
	[AddDate] [datetime] NOT NULL,
	[AddMan] [smallint] NOT NULL,
	[AddManName] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Concern] [smallint] NOT NULL,
	[Status] [smallint] NOT NULL,
	[Receiver] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[ReceiverBank] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[ReceiverAccount] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[Purpose] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[Remarks] [nvarchar](1000) COLLATE Chinese_PRC_CI_AS NULL,
	[Hander] [int] NULL,
	[HanderName] [nvarchar](10) COLLATE Chinese_PRC_CI_AS NULL,
	[Drawer] [int] NULL,
	[DrawerMan] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[DrawDate] [datetime] NULL,
	[Authorizer] [int] NULL,
	[AuthorizerName] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[AuthorizeDate] [datetime] NULL,
	[Attach1] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[PayDate] [datetime] NULL,
	[CancelDate] [datetime] NULL,
	[InValidDate] [datetime] NULL,
	[PayMan] [int] NULL,
	[PayManName] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[CancelMan] [int] NULL,
	[CancelManName] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[InValidMan] [int] NULL,
	[InValidManName] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[money] [numeric](18, 2) NULL,
	[ManagerReason] [nvarchar](200) COLLATE Chinese_PRC_CI_AS NULL,
	[CheckOverDate] [datetime] NULL,
	[CheckOverMan] [int] NULL,
	[CheckOverManName] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[KeyNumber] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[Attach2] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[InValidReason] [nvarchar](200) COLLATE Chinese_PRC_CI_AS NULL,
	[ACRemarks] [nvarchar](200) COLLATE Chinese_PRC_CI_AS NULL,
	[Attach3] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[Attach4] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
 CONSTRAINT [PK_FnBankCheck] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Finance]
) ON [Finance]

GO
/****** Object:  Table [dbo].[FnBankDaybook]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[FnBankDaybook](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[Concern] [smallint] NOT NULL,
	[TsctDate] [datetime] NOT NULL,
	[Debit] [numeric](18, 2) NULL,
	[Credit] [numeric](18, 2) NULL,
	[Balance] [numeric](18, 2) NOT NULL,
	[OppositeCompany] [nvarchar](500) COLLATE Chinese_PRC_CI_AS NULL,
	[OppositeAccount] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[OppositeBank] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[Purpose] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[Summary] [nvarchar](200) COLLATE Chinese_PRC_CI_AS NULL,
	[CertificateNo] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL,
	[ApplyNo] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL,
	[AddMan] [int] NOT NULL,
	[AddManName] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[AddDate] [datetime] NOT NULL,
	[RelationNo] [varchar](12) COLLATE Chinese_PRC_CI_AS NULL,
	[Remarks] [nvarchar](200) COLLATE Chinese_PRC_CI_AS NULL,
	[ReceIptDate] [datetime] NULL,
	[ReceIptMan] [int] NULL,
	[ReceIptManName] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[RelationDate] [datetime] NULL,
	[RelationMan] [int] NULL,
	[RelationManName] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[RelationNo2] [varchar](12) COLLATE Chinese_PRC_CI_AS NULL,
	[Attach1] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[BKYearMonth] [char](6) COLLATE Chinese_PRC_CI_AS NULL,
	[VoucherNo] [smallint] NULL,
	[BkMan] [int] NULL,
	[BkManname] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[BKDate] [datetime] NULL,
	[IsSales] [tinyint] NULL,
	[RelationNo3] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[RelationNo4] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[RelationNo5] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[RelationNo6] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[RelationType] [tinyint] NULL,
 CONSTRAINT [PK_FnBankDaybook] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Finance]
) ON [Finance]

GO
/****** Object:  Table [dbo].[FnBankDaybook0105]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[FnBankDaybook0105](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[Concern] [smallint] NOT NULL,
	[TsctDate] [datetime] NOT NULL,
	[Debit] [numeric](18, 2) NULL,
	[Credit] [numeric](18, 2) NULL,
	[Balance] [numeric](18, 2) NOT NULL,
	[OppositeCompany] [nvarchar](500) COLLATE Chinese_PRC_CI_AS NULL,
	[OppositeAccount] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[OppositeBank] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[Purpose] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[Summary] [nvarchar](200) COLLATE Chinese_PRC_CI_AS NULL,
	[CertificateNo] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL,
	[ApplyNo] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL,
	[AddMan] [int] NOT NULL,
	[AddManName] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[AddDate] [datetime] NOT NULL,
	[RelationNo] [varchar](12) COLLATE Chinese_PRC_CI_AS NULL,
	[Remarks] [nvarchar](200) COLLATE Chinese_PRC_CI_AS NULL,
	[ReceIptDate] [datetime] NULL,
	[ReceIptMan] [int] NULL,
	[ReceIptManName] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[RelationDate] [datetime] NULL,
	[RelationMan] [int] NULL,
	[RelationManName] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[RelationNo2] [varchar](12) COLLATE Chinese_PRC_CI_AS NULL,
	[Attach1] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[BKYearMonth] [char](6) COLLATE Chinese_PRC_CI_AS NULL,
	[VoucherNo] [smallint] NULL,
	[BkMan] [int] NULL,
	[BkManname] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[BKDate] [datetime] NULL,
	[IsSales] [tinyint] NULL,
	[RelationNo3] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[RelationNo4] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[RelationNo5] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[RelationNo6] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[RelationType] [tinyint] NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[FnBankDaybook0428]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[FnBankDaybook0428](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[Concern] [smallint] NOT NULL,
	[TsctDate] [datetime] NOT NULL,
	[Debit] [numeric](18, 2) NULL,
	[Credit] [numeric](18, 2) NULL,
	[Balance] [numeric](18, 2) NOT NULL,
	[OppositeCompany] [nvarchar](500) COLLATE Chinese_PRC_CI_AS NULL,
	[OppositeAccount] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[OppositeBank] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[Purpose] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[Summary] [nvarchar](200) COLLATE Chinese_PRC_CI_AS NULL,
	[CertificateNo] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL,
	[ApplyNo] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL,
	[AddMan] [int] NOT NULL,
	[AddManName] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[AddDate] [datetime] NOT NULL,
	[RelationNo] [varchar](12) COLLATE Chinese_PRC_CI_AS NULL,
	[Remarks] [nvarchar](200) COLLATE Chinese_PRC_CI_AS NULL,
	[ReceIptDate] [datetime] NULL,
	[ReceIptMan] [int] NULL,
	[ReceIptManName] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[RelationDate] [datetime] NULL,
	[RelationMan] [int] NULL,
	[RelationManName] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[RelationNo2] [varchar](12) COLLATE Chinese_PRC_CI_AS NULL,
	[Attach1] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[BKYearMonth] [char](6) COLLATE Chinese_PRC_CI_AS NULL,
	[VoucherNo] [smallint] NULL,
	[BkMan] [int] NULL,
	[BkManname] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[BKDate] [datetime] NULL,
	[IsSales] [tinyint] NULL,
	[RelationNo3] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[RelationNo4] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[RelationNo5] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[RelationNo6] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[RelationType] [tinyint] NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[FnBankDaybook49923]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[FnBankDaybook49923](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[Concern] [smallint] NOT NULL,
	[TsctDate] [datetime] NOT NULL,
	[Debit] [numeric](18, 2) NULL,
	[Credit] [numeric](18, 2) NULL,
	[Balance] [numeric](18, 2) NOT NULL,
	[OppositeCompany] [nvarchar](500) COLLATE Chinese_PRC_CI_AS NULL,
	[OppositeAccount] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[OppositeBank] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[Purpose] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[Summary] [nvarchar](200) COLLATE Chinese_PRC_CI_AS NULL,
	[CertificateNo] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL,
	[ApplyNo] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL,
	[AddMan] [int] NOT NULL,
	[AddManName] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[AddDate] [datetime] NOT NULL,
	[RelationNo] [varchar](12) COLLATE Chinese_PRC_CI_AS NULL,
	[Remarks] [nvarchar](200) COLLATE Chinese_PRC_CI_AS NULL,
	[ReceIptDate] [datetime] NULL,
	[ReceIptMan] [int] NULL,
	[ReceIptManName] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[RelationDate] [datetime] NULL,
	[RelationMan] [int] NULL,
	[RelationManName] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[RelationNo2] [varchar](12) COLLATE Chinese_PRC_CI_AS NULL,
	[Attach1] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[BKYearMonth] [char](6) COLLATE Chinese_PRC_CI_AS NULL,
	[VoucherNo] [smallint] NULL,
	[BkMan] [int] NULL,
	[BkManname] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[BKDate] [datetime] NULL,
	[IsSales] [tinyint] NULL,
	[RelationNo3] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[RelationNo4] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[RelationNo5] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[RelationNo6] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[RelationType] [tinyint] NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[FnCash]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[FnCash](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[kind] [smallint] NOT NULL,
	[handleMan] [smallint] NULL,
	[handleManname] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[status] [smallint] NOT NULL,
	[Authorizer] [int] NULL,
	[AuthorizerName] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[AuthorizeDate] [smalldatetime] NULL,
	[Drawer] [int] NULL,
	[DrawerMan] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[AddDate] [datetime] NOT NULL,
	[Concern] [smallint] NOT NULL,
	[attach1] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[debit] [numeric](18, 2) NULL,
	[credit] [numeric](18, 2) NULL,
	[balance] [numeric](18, 2) NULL,
	[PayDate] [datetime] NULL,
	[PayMan] [int] NULL,
	[PayManName] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[Remarks] [nvarchar](2000) COLLATE Chinese_PRC_CI_AS NULL,
	[CancelDate] [datetime] NULL,
	[CancelMan] [int] NULL,
	[CancelManName] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[InValidMan] [int] NULL,
	[InValidManname] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[InValidDate] [datetime] NULL,
	[Accountant] [int] NULL,
	[AccountantName] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[AccountantDate] [datetime] NULL,
	[SerialNumber] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[ManagerReason] [nvarchar](200) COLLATE Chinese_PRC_CI_AS NULL,
	[AccountantReason] [nvarchar](200) COLLATE Chinese_PRC_CI_AS NULL,
	[BKYearMonth] [char](6) COLLATE Chinese_PRC_CI_AS NULL,
	[VoucherNo] [smallint] NULL,
	[BkMan] [int] NULL,
	[BkManname] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[BKDate] [datetime] NULL,
	[ACRemarks] [nvarchar](200) COLLATE Chinese_PRC_CI_AS NULL,
	[Category] [tinyint] NULL,
	[Attach2] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
 CONSTRAINT [PK_FnCash] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Finance]
) ON [Finance]

GO
/****** Object:  Table [dbo].[FnInvoice]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[FnInvoice](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[No] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[AddDate] [datetime] NULL,
	[AddMan] [int] NULL,
	[AddManName] [nvarchar](10) COLLATE Chinese_PRC_CI_AS NULL,
	[Concern] [smallint] NULL,
	[OrderId] [int] NULL,
	[Money] [numeric](18, 2) NULL,
	[MakeoutDate] [datetime] NULL,
	[MakeoutMan] [int] NULL,
	[MakeoutManName] [nvarchar](10) COLLATE Chinese_PRC_CI_AS NULL,
	[Status] [smallint] NULL,
	[InValidDate] [datetime] NULL,
	[InValidMan] [int] NULL,
	[InValidManName] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[InvoiceMonth] [char](6) COLLATE Chinese_PRC_CI_AS NULL,
	[Remarks] [nvarchar](200) COLLATE Chinese_PRC_CI_AS NULL,
	[InValidReason] [nvarchar](200) COLLATE Chinese_PRC_CI_AS NULL,
	[Head] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[ReturnFnInvoiceId] [int] NULL,
	[FnInvoiceType] [tinyint] NULL,
	[WtgOrderId] [int] NULL,
 CONSTRAINT [PK_FnInvoice] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Finance]
) ON [Finance]

GO
/****** Object:  Table [dbo].[FnLetter]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[FnLetter](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[PostNumber] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[PostTelephone] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[PostAddress] [nvarchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[Recipient] [nvarchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[FnInvoiceID] [int] NOT NULL,
	[Zip] [char](6) COLLATE Chinese_PRC_CI_AS NULL,
	[Postman] [int] NULL,
	[PostmanName] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[Remarks] [nvarchar](200) COLLATE Chinese_PRC_CI_AS NULL,
	[Status] [smallint] NOT NULL,
	[PostDate] [datetime] NULL,
	[ReturnReason] [nvarchar](200) COLLATE Chinese_PRC_CI_AS NULL,
	[Companyname] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[ReturnDate] [datetime] NULL,
	[ReturnMan] [int] NULL,
	[ReturnManName] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[ReceivedManName] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[ReceivedDate] [datetime] NULL,
	[InvalidDate] [datetime] NULL,
	[InvalidMan] [int] NULL,
	[InvalidManName] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[Fee] [numeric](18, 2) NULL,
 CONSTRAINT [PK_FnLetter] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Finance]
) ON [Finance]

GO
/****** Object:  Table [dbo].[FnPICDaybook]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[FnPICDaybook](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[Concern] [smallint] NOT NULL,
	[TsctDate] [datetime] NOT NULL,
	[Debit] [numeric](18, 2) NULL,
	[Credit] [numeric](18, 2) NULL,
	[Balance] [numeric](18, 2) NULL,
	[Opposite] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[OppositeAccount] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[OppositeBank] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[AddMan] [int] NOT NULL,
	[AddManName] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[AddDate] [datetime] NOT NULL,
	[RelationNo] [int] NULL,
	[Remarks] [nvarchar](200) COLLATE Chinese_PRC_CI_AS NULL,
	[RelationDate] [datetime] NULL,
	[RelationMan] [int] NULL,
	[RelationManName] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[Paymethod] [smallint] NOT NULL,
	[Tsctplace] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[Summary] [nvarchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[RelationNo2] [int] NULL,
	[RelationNo3] [int] NULL,
	[RelationNo4] [int] NULL,
	[RelationNo5] [int] NULL,
	[RelationType] [tinyint] NULL,
 CONSTRAINT [PK_FnPICDaybook] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Finance]
) ON [Finance]

GO
/****** Object:  Table [dbo].[fpCommonSearch]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[fpCommonSearch](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[dcProvinceID] [smallint] NOT NULL,
	[SearchText] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[SearchValue] [varchar](max) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[SearchType] [tinyint] NOT NULL,
	[Sequence] [tinyint] NOT NULL,
	[AddMan] [smallint] NULL,
	[AddDate] [smalldatetime] NOT NULL,
 CONSTRAINT [PK_fpCommonSearch] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [FOthers]
) ON [FOthers] TEXTIMAGE_ON [PRIMARY]

GO
/****** Object:  Table [dbo].[fpFixPositionOld]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[fpFixPositionOld](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[cpMainID] [int] NULL,
	[Name] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[JobID] [varchar](max) COLLATE Chinese_PRC_CI_AS NULL,
	[JobName] [nvarchar](max) COLLATE Chinese_PRC_CI_AS NULL,
	[Paid] [numeric](18, 2) NULL,
	[OpenDate] [smalldatetime] NULL,
	[NewXId] [int] NULL,
	[ThreeIds] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[AddDate] [datetime] NULL,
	[dcProvinceId] [tinyint] NULL,
	[dcRegionID] [varchar](6) COLLATE Chinese_PRC_CI_AS NULL,
	[dcSubSiteID] [smallint] NULL,
	[caOrderId] [int] NULL,
	[dcIndustryId] [int] NULL,
	[IndustryCategory] [tinyint] NULL,
	[NoFollow] [varchar](1) COLLATE Chinese_PRC_CI_AS NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

GO
/****** Object:  Table [dbo].[fpHomepageImage]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[fpHomepageImage](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[dcProvinceID] [smallint] NULL,
	[ImageType] [tinyint] NULL,
	[ImageFile] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[Alt] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[AddMan] [smallint] NULL,
	[AddDate] [smalldatetime] NULL,
	[Url] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[title] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
 CONSTRAINT [PK_fpHomepageImage] PRIMARY KEY NONCLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [FOthers]
) ON [FOthers]

GO
/****** Object:  Table [dbo].[FriendLinkBlack]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[FriendLinkBlack](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[Url] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL,
	[WebsiteName] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[AddDate] [smalldatetime] NOT NULL,
	[AddMan] [int] NOT NULL,
	[Remarks] [nvarchar](500) COLLATE Chinese_PRC_CI_AS NULL,
 CONSTRAINT [PK_FriendLinkBlack] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Market]
) ON [Market]

GO
/****** Object:  Table [dbo].[ftpFileUpDate]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ftpFileUpDate](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[FileDir] [varchar](500) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Oper] [int] NOT NULL,
	[SynServer] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[FileBody] [image] NULL,
	[AddDate] [datetime] NULL,
	[isFolder] [char](1) COLLATE Chinese_PRC_CI_AS NULL,
 CONSTRAINT [PK_ftpFileUpate] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers],
 CONSTRAINT [uniqueindex] UNIQUE NONCLUSTERED 
(
	[FileDir] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
) ON [BOthers] TEXTIMAGE_ON [BOthers]

GO
/****** Object:  Table [dbo].[group_ManagerUser]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[group_ManagerUser](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[Group_Id] [int] NOT NULL,
	[ManagerUser_Id] [smallint] NOT NULL,
	[DescrIption] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[orderby] [smallint] NOT NULL,
 CONSTRAINT [PK_group_ManagerUser] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers]
) ON [BOthers]

GO
/****** Object:  Table [dbo].[group_province]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[group_province](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[Group_Id] [int] NOT NULL,
	[Province_Id] [tinyint] NOT NULL,
	[DescrIption] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[Orderby] [smallint] NOT NULL,
	[QQ_Limit] [smallint] NULL,
	[Sms_limit] [int] NULL,
	[cpSms_limit] [int] NULL,
	[IsSet] [bit] NULL,
	[bigsmall] [tinyint] NULL,
 CONSTRAINT [PK_group_province] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers]
) ON [BOthers]

GO
/****** Object:  Table [dbo].[GroupM]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[GroupM](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[GroupName] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[DescrIption] [nvarchar](200) COLLATE Chinese_PRC_CI_AS NULL,
 CONSTRAINT [PK_group] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers]
) ON [BOthers]

GO
/****** Object:  Table [dbo].[HomepageSeoLog]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[HomepageSeoLog](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[versionId] [int] NOT NULL,
	[title_old] [nvarchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[title_new] [nvarchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[meta_author_old] [nvarchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[meta_author_new] [nvarchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[meta_DescrIption_old] [nvarchar](300) COLLATE Chinese_PRC_CI_AS NULL,
	[meta_DescrIption_new] [nvarchar](300) COLLATE Chinese_PRC_CI_AS NULL,
	[meta_keywords_old] [nvarchar](200) COLLATE Chinese_PRC_CI_AS NULL,
	[meta_keywords_new] [nvarchar](200) COLLATE Chinese_PRC_CI_AS NULL,
	[t1_old] [nvarchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[t1_new] [nvarchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[t2_old] [nvarchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[t2_new] [nvarchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[t3_old] [nvarchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[t3_new] [nvarchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[t4_old] [nvarchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[t4_new] [nvarchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[t5_old] [nvarchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[t5_new] [nvarchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[t6_old] [nvarchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[t6_new] [nvarchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[t7_old] [nvarchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[t7_new] [nvarchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[bottom_old] [nvarchar](500) COLLATE Chinese_PRC_CI_AS NULL,
	[bottom_new] [nvarchar](500) COLLATE Chinese_PRC_CI_AS NULL,
	[addDate] [smalldatetime] NOT NULL,
 CONSTRAINT [PK_HomepageSeoLog] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [FOthers]
) ON [FOthers]

GO
/****** Object:  Table [dbo].[hpHighSalaryCompany]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[hpHighSalaryCompany](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[dcRegionID] [varchar](6) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[JobID] [int] NOT NULL,
	[JobSecondID] [varchar](20) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[JobName] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[CpMainID] [int] NOT NULL,
	[CpSecondID] [varchar](20) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[CpName] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[LogoUrl] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL,
	[dcSalaryID] [tinyint] NOT NULL,
	[RefreshDate] [datetime] NULL,
	[AddDate] [datetime] NOT NULL,
	[RowNo] [int] NOT NULL,
 CONSTRAINT [PK_hpHighSalaryCompany] PRIMARY KEY CLUSTERED 
(
	[id] 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].[hpHighSalaryCompanyNew]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[hpHighSalaryCompanyNew](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[dcRegionID] [varchar](6) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[JobID] [int] NOT NULL,
	[JobSecondID] [varchar](20) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[JobName] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[CpMainID] [int] NOT NULL,
	[CpSecondID] [varchar](20) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[CpName] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[LogoUrl] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL,
	[dcSalaryID] [tinyint] NOT NULL,
	[RefreshDate] [datetime] NULL,
	[AddDate] [datetime] NOT NULL,
	[RowNo] [int] NOT NULL,
 CONSTRAINT [PK_hpHighSalaryCompanyNew] PRIMARY KEY CLUSTERED 
(
	[id] 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].[hpHighSalaryJob]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[hpHighSalaryJob](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[dcRegionID] [varchar](6) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[JobID] [int] NOT NULL,
	[JobSecondID] [varchar](20) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[JobName] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[CpMainID] [int] NOT NULL,
	[CpSecondID] [varchar](20) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[CpName] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[LogoUrl] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL,
	[dcSalaryID] [tinyint] NOT NULL,
	[JobRefreshDate] [datetime] NULL,
	[AddDate] [datetime] NOT NULL,
 CONSTRAINT [PK_hpHighSalaryJob] PRIMARY KEY CLUSTERED 
(
	[id] 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].[hpHighSalaryJobNew]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[hpHighSalaryJobNew](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[dcRegionID] [varchar](6) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[JobID] [int] NOT NULL,
	[JobSecondID] [varchar](20) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[JobName] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[CpMainID] [int] NOT NULL,
	[CpSecondID] [varchar](20) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[CpName] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[LogoUrl] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL,
	[dcSalaryID] [tinyint] NOT NULL,
	[JobRefreshDate] [datetime] NULL,
	[AddDate] [datetime] NOT NULL,
 CONSTRAINT [PK_hpHighSalaryJobNew] PRIMARY KEY CLUSTERED 
(
	[id] 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].[hpJobTypeCpLogo]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[hpJobTypeCpLogo](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[dcRegionID] [varchar](6) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[dcJobTypeID] [smallint] NOT NULL,
	[CpMainID] [int] NULL,
	[CpSecondID] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL,
	[LogoUrl] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[AddDate] [datetime] NULL,
 CONSTRAINT [PK_hpJobTypeCpLogo] PRIMARY KEY CLUSTERED 
(
	[id] 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].[hpNewsSet]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[hpNewsSet](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[dcProvinceID] [smallint] NOT NULL,
	[Section] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[AddDate] [smalldatetime] NOT NULL,
 CONSTRAINT [PK_hpNewsSet] PRIMARY KEY CLUSTERED 
(
	[ID] 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].[HRKpiPost]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[HRKpiPost](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[KpiPostname] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Breadth] [int] NOT NULL,
	[Beginning] [int] NOT NULL,
 CONSTRAINT [PK_HRKpiPost] PRIMARY KEY CLUSTERED 
(
	[Id] 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].[info_coeffi]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[info_coeffi](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[BeginDate] [int] NOT NULL,
	[Coefficient] [numeric](18, 2) NOT NULL,
	[Province_Id] [tinyint] NOT NULL,
 CONSTRAINT [PK_info_coeffi] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers]
) ON [BOthers]

GO
/****** Object:  Table [dbo].[info_Datereport]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[info_Datereport](
	[CountDate] [int] NOT NULL,
	[Province_Id] [smallint] NOT NULL,
	[InfoManager_Id] [smallint] NOT NULL,
	[Companyregnum_Our] [int] NOT NULL,
	[Personregnum_Our] [int] NOT NULL,
	[ValidCompany] [int] NOT NULL,
	[ValidResume] [int] NOT NULL,
	[Homepage] [int] NOT NULL,
	[RealCompany] [int] NOT NULL,
	[RealResume] [int] NOT NULL,
	[AllResume] [int] NOT NULL,
	[PersonRegNum_Our_QQ] [int] NOT NULL,
	[MobileNum] [int] NOT NULL,
	[MobileReturn] [int] NOT NULL,
	[MobileAccount] [int] NOT NULL,
	[cpMobileNum] [smallint] NOT NULL,
	[cpMobileRetNum] [smallint] NOT NULL,
	[cpMobileAccountNum] [smallint] NOT NULL,
	[PersonalActivationCount] [int] NOT NULL,
	[CompanyActivationCount] [int] NOT NULL,
 CONSTRAINT [IX_info_Datereport_unique] UNIQUE CLUSTERED 
(
	[CountDate] ASC,
	[Province_Id] ASC,
	[InfoManager_Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
) ON [Index]

GO
/****** Object:  Table [dbo].[infoachieve]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[infoachieve](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[YearMonth] [int] NOT NULL,
	[InfoManager_Id] [smallint] NOT NULL,
	[RealCompany] [int] NULL,
	[RealResume] [int] NULL,
	[Award] [numeric](10, 2) NULL,
	[Homepage] [int] NULL,
	[Real_Company] [int] NULL,
	[Real_Resume] [int] NULL,
	[Add_Company] [int] NULL,
	[Add_Resume] [int] NULL,
	[AllResume] [int] NULL,
	[Salary] [numeric](18, 2) NULL,
	[Salary_Control] [numeric](18, 2) NULL,
	[LocalRate] [numeric](18, 2) NULL,
	[MobileNum] [int] NULL,
	[MobileReturn] [int] NULL,
	[cpMobileNum] [int] NULL,
	[cpMobileRetNum] [int] NULL,
	[paRepeatRate] [decimal](9, 4) NULL,
	[cpRepeatRate] [decimal](9, 4) NULL,
	[paRepeatNum] [int] NULL,
	[cpRepeatNum] [int] NULL,
	[paMobileNumSum] [int] NULL,
	[cpMobileNumSum] [int] NULL,
 CONSTRAINT [PK_infoachieve] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers],
 CONSTRAINT [IX_infoachieve_unique] UNIQUE NONCLUSTERED 
(
	[YearMonth] ASC,
	[InfoManager_Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
) ON [BOthers]

GO
/****** Object:  Table [dbo].[infoEmailAnalyze]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[infoEmailAnalyze](
	[YearMonth] [int] NOT NULL,
	[InfoManager_Id] [smallint] NOT NULL,
	[EmailType_Id] [int] NOT NULL,
	[AddCompany] [numeric](5, 2) NOT NULL,
	[AddResume] [numeric](5, 2) NOT NULL,
	[RealCompany] [numeric](5, 2) NOT NULL,
	[RealResume] [numeric](5, 2) NULL
) ON [BOthers]

GO
/****** Object:  Table [dbo].[infolog]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[infolog](
	[infoManager_Id] [int] NOT NULL,
	[Ip] [varchar](15) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[addDate] [smalldatetime] NOT NULL,
	[referer] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[paMainId] [int] NULL
) ON [Market]

GO
/****** Object:  Table [dbo].[innerer]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[innerer](
	[Referer] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL,
	[VersionId] [int] NULL,
	[LoginDate] [smalldatetime] NOT NULL,
	[Ip] [varchar](15) COLLATE Chinese_PRC_CI_AS NULL,
	[Keywords] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[Province_Id] [int] NULL,
	[Innerpage] [smallint] NULL
) ON [Market]

GO
/****** Object:  Table [dbo].[Innerer_Count_Detail]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Innerer_Count_Detail](
	[Innerer_CountId] [int] NULL,
	[Innerpage] [smallint] NULL,
	[Page_Count] [int] NULL
) ON [Market]

GO
/****** Object:  Table [dbo].[innerer_count_keywords]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[innerer_count_keywords](
	[Referer_count_Id] [int] NOT NULL,
	[Keywords] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[HowMany] [smallint] NOT NULL
) ON [Market]

GO
/****** Object:  Table [dbo].[Innerer_Count0331]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Innerer_Count0331](
	[CountDate] [int] NOT NULL,
	[Province_Id] [smallint] NOT NULL,
	[HowMany] [int] NOT NULL,
	[Referer] [varchar](500) COLLATE Chinese_PRC_CI_AS NULL,
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[InnerPage] [varchar](500) COLLATE Chinese_PRC_CI_AS NULL,
	[JobPage] [int] NULL,
	[CompanyPage] [int] NULL,
	[NewsPage] [int] NULL,
	[RecruitmentPage] [int] NULL,
	[JobHelpPage] [int] NULL,
	[JobMapPage] [int] NULL,
	[OtherPage] [int] NULL,
	[partTimePage] [int] NULL,
	[SchoolPage] [int] NULL,
	[MajorPage] [int] NULL,
	[JobNamePage] [int] NULL,
	[CountyPage] [int] NULL,
	[RegionSearch] [int] NULL,
	[NewJob] [int] NULL,
	[paDownLoad] [int] NULL,
	[sSearch] [int] NULL,
	[VersionId] [smallint] NULL,
 CONSTRAINT [PK_innerer_count] PRIMARY KEY NONCLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Market],
 CONSTRAINT [IX_innerer_count_unique] UNIQUE CLUSTERED 
(
	[CountDate] ASC,
	[Province_Id] ASC,
	[Referer] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
) ON [Index]

GO
/****** Object:  Table [dbo].[innerer_count1]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[innerer_count1](
	[CountDate] [int] NOT NULL,
	[Province_Id] [smallint] NOT NULL,
	[HowMany] [int] NOT NULL,
	[Referer] [varchar](200) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[InnerPage] [varchar](500) COLLATE Chinese_PRC_CI_AS NULL,
	[JobPage] [int] NULL,
	[CompanyPage] [int] NULL,
	[NewsPage] [int] NULL,
	[RecruitmentPage] [int] NULL,
	[JobHelpPage] [int] NULL,
	[JobMapPage] [int] NULL,
	[OtherPage] [int] NULL,
	[partTimePage] [int] NULL,
	[SchoolPage] [int] NULL,
	[MajorPage] [int] NULL,
	[JobNamePage] [int] NULL,
	[CountyPage] [int] NULL,
	[RegionSearch] [int] NULL,
	[NewJob] [int] NULL,
	[paDownLoad] [int] NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[innerer_countNew]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[innerer_countNew](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[CountDate] [int] NOT NULL,
	[Province_Id] [smallint] NOT NULL,
	[HowMany] [int] NOT NULL,
	[Referer] [varchar](200) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[VersionId] [int] NULL,
 CONSTRAINT [PK_innerer_countNew] PRIMARY KEY NONCLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [Market]

GO
/****** Object:  Index [IX_innerer_countNew_CountDate]    Script Date: 2018/9/25 12:40:11 ******/
CREATE CLUSTERED INDEX [IX_innerer_countNew_CountDate] ON [dbo].[innerer_countNew]
(
	[CountDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Market]
GO
/****** Object:  Table [dbo].[innerer_YearMonth]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[innerer_YearMonth](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[YearMonth] [int] NOT NULL,
	[item_name] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[province_Id] [smallint] NULL,
	[howMany] [int] NOT NULL,
 CONSTRAINT [PK_innerer_YearMonth] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Market]
) ON [Market]

GO
/****** Object:  Table [dbo].[Innerer2]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Innerer2](
	[Referer] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL,
	[VersionId] [int] NULL,
	[LoginDate] [smalldatetime] NOT NULL,
	[Ip] [varchar](15) COLLATE Chinese_PRC_CI_AS NULL,
	[Keywords] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[Province_Id] [int] NULL,
	[Innerpage] [smallint] NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[innernews]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[innernews](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[Title] [nvarchar](60) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Content] [varchar](max) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[AnnounceDate] [smalldatetime] NOT NULL,
	[Author] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[AddMan] [smallint] NULL,
 CONSTRAINT [PK_innernews] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Market]
) ON [Market] TEXTIMAGE_ON [Market]

GO
/****** Object:  Table [dbo].[inResult]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[inResult](
	[v_oId] [varchar](1000) COLLATE Chinese_PRC_CI_AS NULL,
	[v_viRement] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[v_count] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[v_mac] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[addDate] [smalldatetime] NOT NULL
) ON [BOthers]

GO
/****** Object:  Index [IX_inResult_addDate]    Script Date: 2018/9/25 12:40:11 ******/
CREATE CLUSTERED INDEX [IX_inResult_addDate] ON [dbo].[inResult]
(
	[addDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers]
GO
/****** Object:  Table [dbo].[Institution]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Institution](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[Title] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[DescrIption] [nvarchar](1000) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[AddDate] [smalldatetime] NOT NULL,
	[Type] [smallint] NOT NULL,
	[ManagerUserId] [smallint] NOT NULL,
	[Attachment] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[Privi] [varchar](500) COLLATE Chinese_PRC_CI_AS NULL,
 CONSTRAINT [PK_Institution] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers]
) ON [BOthers]

GO
/****** Object:  Table [dbo].[Insurance]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Insurance](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[WorkUserID] [int] NOT NULL,
	[ManagerUserID] [smallint] NOT NULL,
	[InsuranceMonth] [varchar](6) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[InsuranceBasic] [decimal](18, 2) NULL,
	[MedicalCareBasic] [decimal](18, 2) NULL,
	[AccumulationBasic] [decimal](18, 2) NULL,
	[CompanyBigMedical] [decimal](18, 2) NULL,
	[SelfBigMedical] [decimal](18, 2) NULL,
	[CompanyPensionPercent] [decimal](18, 4) NULL,
	[SelfPensionPercent] [decimal](18, 4) NULL,
	[SelfPension] [decimal](18, 2) NULL,
	[CompanyUnemployPercent] [decimal](18, 4) NULL,
	[SelfUnemployPercent] [decimal](18, 4) NULL,
	[SelfUnemploy] [decimal](18, 2) NULL,
	[CompanyInjuryPercent] [decimal](18, 4) NULL,
	[CompanyInjury] [decimal](18, 2) NULL,
	[CompanyMedicalCarePercent] [decimal](18, 4) NULL,
	[SelfMedicalCarePercent] [decimal](18, 4) NULL,
	[SelfMedicalCare] [decimal](18, 2) NULL,
	[CompanyBirthPercent] [decimal](18, 4) NULL,
	[CompanyPalceMedicalPercent] [decimal](18, 4) NULL,
	[CompanyAccumulationPercent] [decimal](18, 4) NULL,
	[CompanyAccumulation] [decimal](18, 2) NULL,
	[SelfAccumulationPercent] [decimal](18, 4) NULL,
	[SelfAccumulation] [decimal](18, 2) NULL,
	[Remark] [nvarchar](500) COLLATE Chinese_PRC_CI_AS NULL,
	[CityNum] [int] NULL,
	[AccountType] [int] NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[Investigation]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Investigation](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[Title] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Description] [nvarchar](500) COLLATE Chinese_PRC_CI_AS NULL,
	[AddDate] [smalldatetime] NOT NULL,
	[EndDate] [smalldatetime] NOT NULL,
	[AddMan] [smallint] NOT NULL,
	[Parti] [varchar](1200) COLLATE Chinese_PRC_CI_AS NULL,
 CONSTRAINT [PK_Investigation] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers]
) ON [BOthers]

GO
/****** Object:  Table [dbo].[Ip_Black]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Ip_Black](
	[id] [int] IDENTITY(1,1) NOT FOR REPLICATION NOT NULL,
	[ip] [varchar](20) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[description] [nvarchar](500) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[adddate] [smalldatetime] NOT NULL,
	[type] [tinyint] NOT NULL,
	[remarks] [nvarchar](500) COLLATE Chinese_PRC_CI_AS NULL,
 CONSTRAINT [PK_ip_black] PRIMARY KEY NONCLUSTERED 
(
	[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [FOthers],
 CONSTRAINT [IX_ip_black_ip] UNIQUE CLUSTERED 
(
	[ip] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [FOthers]
) ON [FOthers]

GO
/****** Object:  Table [dbo].[Ip_White]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Ip_White](
	[id] [int] IDENTITY(1,1) NOT FOR REPLICATION NOT NULL,
	[ip] [varchar](20) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[description] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[adddate] [smalldatetime] NOT NULL,
	[visitnum] [int] NOT NULL,
	[visitnum_thismonth] [bigint] NOT NULL,
	[visitnum_lastmonth] [bigint] NOT NULL,
	[remarks] [nvarchar](500) COLLATE Chinese_PRC_CI_AS NULL,
	[visitnum_lastlastmonth] [bigint] NULL,
	[Kind] [tinyint] NULL,
 CONSTRAINT [PK_ip_white] PRIMARY KEY NONCLUSTERED 
(
	[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [FOthers],
 CONSTRAINT [IX_ip_white_ip] UNIQUE CLUSTERED 
(
	[ip] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [FOthers]
) ON [FOthers]

GO
/****** Object:  Table [dbo].[IpLog]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[IpLog](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[ip] [varchar](17) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[http_user_agent] [varchar](500) COLLATE Chinese_PRC_CI_AS NULL,
	[adddate] [smalldatetime] NOT NULL,
	[type] [smallint] NOT NULL,
	[path_info] [varchar](500) COLLATE Chinese_PRC_CI_AS NOT NULL
) ON [FOthers]

GO
/****** Object:  Table [dbo].[IpLog_Daily]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[IpLog_Daily](
	[monthday] [char](8) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[ip] [varchar](17) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[http_user_agent] [varchar](500) COLLATE Chinese_PRC_CI_AS NULL,
	[type] [smallint] NOT NULL,
	[path_info] [varchar](500) COLLATE Chinese_PRC_CI_AS NULL,
	[count] [int] NOT NULL
) ON [FOthers]

GO
/****** Object:  Table [dbo].[IpReport]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[IpReport](
	[id] [smallint] NOT NULL,
	[address] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[ip] [varchar](17) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[refresh] [smalldatetime] NOT NULL
) ON [FOthers]

GO
/****** Object:  Table [dbo].[IpVisitAll]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[IpVisitAll](
	[Ip] [varchar](31) COLLATE Chinese_PRC_CI_AS NULL
) ON [FOthers]

GO
/****** Object:  Table [dbo].[ivgt_answer]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ivgt_answer](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[Title] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Power] [smallint] NOT NULL,
	[ClickNum] [int] NOT NULL,
	[QuestionId] [int] NOT NULL,
	[showType] [smallint] NOT NULL,
 CONSTRAINT [PK_ivgt_answer] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [FOthers],
 CONSTRAINT [IX_ivgt_answer_onlyone] UNIQUE NONCLUSTERED 
(
	[QuestionId] ASC,
	[Power] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
) ON [FOthers]

GO
/****** Object:  Table [dbo].[Ivgt_AnswerLog]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Ivgt_AnswerLog](
	[Ip] [varchar](15) COLLATE Chinese_PRC_CI_AS NULL,
	[AddDate] [smalldatetime] NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[ivgt_answerText]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ivgt_answerText](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[answerId] [int] NOT NULL,
	[answerText] [nvarchar](300) COLLATE Chinese_PRC_CI_AS NULL,
 CONSTRAINT [PK_ivgt_answerText] PRIMARY KEY CLUSTERED 
(
	[ID] 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].[ivgt_investigation]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ivgt_investigation](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[Title] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[DescrIption] [varchar](max) COLLATE Chinese_PRC_CI_AS NULL,
	[Province] [varchar](100) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[AddDate] [smalldatetime] NOT NULL,
	[EndDate] [smalldatetime] NOT NULL,
	[Type] [smallint] NOT NULL,
	[ClickNum] [int] NOT NULL,
	[ReportUrl] [varchar](500) COLLATE Chinese_PRC_CI_AS NULL,
	[ReportTitle] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[ReportType] [tinyint] NULL,
	[AnswerAfterLogin] [smallint] NOT NULL,
	[SeeAnswer] [smallint] NOT NULL,
	[HomepageSee] [smallint] NOT NULL,
	[exLink] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
 CONSTRAINT [PK_ivgt_investigation] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [FOthers]
) ON [FOthers] TEXTIMAGE_ON [FOthers]

GO
/****** Object:  Table [dbo].[ivgt_question]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ivgt_question](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[Title] [nvarchar](150) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Type] [smallint] NOT NULL,
	[Power] [smallint] NOT NULL,
	[InvestId] [int] NOT NULL,
 CONSTRAINT [PK_ivgt_question] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [FOthers]
) ON [FOthers]

GO
/****** Object:  Table [dbo].[ivrDayReport]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ivrDayReport](
	[CountDate] [varchar](8) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[DeptId] [tinyint] NULL,
	[ManagerUserId] [smallint] NOT NULL,
	[Name] [nvarchar](6) COLLATE Chinese_PRC_CI_AS NULL,
	[IsCheck] [bit] NOT NULL,
	[RealNumber] [smallint] NULL,
	[RealMinute] [smallint] NULL,
	[RealWorkTime] [decimal](9, 2) NOT NULL,
	[ConvertNumber]  AS (case when [realworktime]>(0) then CONVERT([int],([realnumber]*(8))/[realworktime],(0)) else (0) end),
	[ConvertMinute]  AS (case when [realworktime]>(0) then CONVERT([int],([realMinute]*(8))/[realworktime],(0)) else (0) end),
	[Remark] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[Status] [tinyint] NOT NULL,
	[ManagerStatus] [tinyint] NULL,
	[Coefficient]  AS (case when [realworktime]>(0) AND ([ManagerUserId]>=(761) AND [ManagerUserId]<=(769)) then CONVERT([decimal](9,3),CONVERT([int],([Realnumber]*(8.0))/[realworktime],(0))/(160.0)+CONVERT([int],([realminute]*(8.0))/[realworktime],(0))/(200.0),(0)) when [realworktime]>(0) AND ([ManagerUserId]=(887) OR [ManagerUserId]=(885) OR [ManagerUserId]=(882) OR [ManagerUserId]=(881) OR [ManagerUserId]=(888) OR [ManagerUserId]=(889) OR [ManagerUserId]=(890) OR [ManagerUserId]=(891) OR [ManagerUserId]=(892)) then CONVERT([decimal](9,3),CONVERT([int],([Realnumber]*(8.0))/[realworktime],(0))/(160.0)+CONVERT([int],([realminute]*(8.0))/[realworktime],(0))/(200.0),(0)) when [realworktime]>(0) AND NOT ([ManagerUserId]>=(761) AND [ManagerUserId]<=(769)) then CONVERT([decimal](9,3),CONVERT([int],([Realnumber]*(8.0))/[realworktime],(0))/(100.0)+CONVERT([int],([realminute]*(8.0))/[realworktime],(0))/(260.0),(0)) else (0) end),
 CONSTRAINT [PK_ivrDayReport] PRIMARY KEY NONCLUSTERED 
(
	[CountDate] ASC,
	[ManagerUserId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers]
) ON [BOthers]

GO
/****** Object:  Table [dbo].[IvrList]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[IvrList](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[CallNo] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[CalledNo] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[CallType] [varchar](10) COLLATE Chinese_PRC_CI_AS NULL,
	[RecordFile] [varchar](500) COLLATE Chinese_PRC_CI_AS NULL,
	[Ring] [datetime] NULL,
	[Begintime] [datetime] NULL,
	[Endtime] [datetime] NULL,
	[Agent] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[State] [varchar](10) COLLATE Chinese_PRC_CI_AS NULL,
	[CallState] [varchar](30) COLLATE Chinese_PRC_CI_AS NULL,
	[ActionId] [varchar](1000) COLLATE Chinese_PRC_CI_AS NULL,
	[AddDate] [datetime] NULL,
	[Ivrkey] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[CallsheetId] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[Exten] [varchar](10) COLLATE Chinese_PRC_CI_AS NULL,
	[Remarks] [nvarchar](1000) COLLATE Chinese_PRC_CI_AS NULL,
	[caMainId] [int] NULL,
	[cpAccountId] [int] NULL,
	[cpLinkManId] [int] NULL,
	[FileServer] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
 CONSTRAINT [PK_IvrList] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers]
) ON [BOthers]

GO
/****** Object:  Table [dbo].[Ivrlist_Day]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Ivrlist_Day](
	[countDate] [int] NOT NULL,
	[ManagerUserId] [smallint] NOT NULL,
	[name] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[CallinNum_all] [smallint] NOT NULL,
	[CallinInterval_all] [int] NOT NULL,
	[CallinNum_up30] [smallint] NOT NULL,
	[CallinInterval_up30] [int] NOT NULL,
	[CallinNum_up60] [smallint] NOT NULL,
	[CallinInterval_up60] [int] NOT NULL,
	[CallinNum_up180] [smallint] NOT NULL,
	[CallinInterval_up180] [int] NOT NULL,
	[CallinNum_up600] [smallint] NOT NULL,
	[CallinInterval_up600] [int] NOT NULL,
	[status] [tinyint] NOT NULL,
	[CalloutNum_all] [smallint] NOT NULL,
	[CalloutInterval_all] [int] NOT NULL,
	[CalloutNum_up30] [smallint] NOT NULL,
	[CalloutInterval_up30] [int] NOT NULL,
	[CalloutNum_up60] [smallint] NOT NULL,
	[CalloutInterval_up60] [int] NOT NULL,
	[CalloutNum_up180] [smallint] NOT NULL,
	[CalloutInterval_up180] [int] NOT NULL,
	[CalloutNum_up600] [smallint] NOT NULL,
	[CalloutInterval_up600] [int] NOT NULL,
	[Callin_notdeal] [smallint] NOT NULL,
	[Callin_leak] [smallint] NOT NULL,
	[Callout_notdeal] [smallint] NOT NULL,
	[Callout_leak] [smallint] NOT NULL,
	[Callin_queueleak] [smallint] NULL,
	[Callin_blacklist] [smallint] NULL,
	[Callin_voicemail] [smallint] NULL,
	[Callout_queueleak] [smallint] NULL,
	[Callout_blacklist] [smallint] NULL,
	[Callout_voicemail] [smallint] NULL,
	[selective] [bit] NULL,
	[WorkTime] [float] NULL,
	[WorkTimeStatus] [tinyint] NULL,
	[CallinNum_up40] [int] NULL,
	[CallinInterval_up40] [int] NULL,
	[CalloutNum_up40] [int] NULL,
	[CalloutInterval_up40] [int] NULL,
 CONSTRAINT [IX_Ivrlist_Day_unique] UNIQUE NONCLUSTERED 
(
	[countDate] ASC,
	[ManagerUserId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
) ON [BOthers]

GO
/****** Object:  Table [dbo].[ivrlistRequest]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ivrlistRequest](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[CallNo] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[CalledNo] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[Exten] [varchar](10) COLLATE Chinese_PRC_CI_AS NULL,
	[para] [varchar](max) COLLATE Chinese_PRC_CI_AS NULL,
	[AddDate] [datetime] NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

GO
/****** Object:  Table [dbo].[JobCheckLog]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[JobCheckLog](
	[cpMainId] [int] NULL,
	[CheckDate] [datetime] NULL,
	[FilterWord] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[JobDeleted]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[JobDeleted](
	[JobId] [int] NOT NULL,
	[DeleteDate] [smalldatetime] NOT NULL,
	[HasIssued] [bit] NOT NULL,
	[caMainID] [int] NULL,
	[cpMainID] [int] NULL,
	[JobName] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[IssueDate] [smalldatetime] NULL,
	[IssueEnd] [smalldatetime] NULL,
	[SecondId] [varchar](12) COLLATE Chinese_PRC_CI_AS NULL,
	[ProvinceID] [tinyint] NULL,
 CONSTRAINT [PK_JobDeleted] PRIMARY KEY CLUSTERED 
(
	[JobId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [CP]
) ON [CP]

GO
/****** Object:  Table [dbo].[jobLng]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[jobLng](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[lng] [decimal](8, 5) NULL,
	[lat] [decimal](8, 5) NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[jobRefreshLog]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[jobRefreshLog](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[jobRefreshSetId] [int] NULL,
	[orderId] [int] NULL,
	[jobId] [int] NOT NULL,
	[jobInfo] [nvarchar](200) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[refreshType] [tinyint] NOT NULL,
	[preRefreshDateTime] [smalldatetime] NULL,
	[runDateTime] [datetime] NULL,
	[operateMan] [int] NOT NULL,
	[cpMainId] [int] NOT NULL,
 CONSTRAINT [PK_jobRefreshLog] PRIMARY KEY CLUSTERED 
(
	[id] 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].[JobRefreshLog_temp]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[JobRefreshLog_temp](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[orderId] [int] NULL,
	[jobRefreshSetId] [int] NULL,
	[jobId] [int] NOT NULL,
	[jobInfo] [nvarchar](200) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[refreshType] [tinyint] NOT NULL,
	[preRefreshDateTime] [smalldatetime] NULL,
	[runDateTime] [datetime] NULL,
	[operateMan] [int] NOT NULL,
	[cpMainId] [int] NOT NULL,
	[addDate] [datetime] NULL,
 CONSTRAINT [PK_JobRefreshLog_temp] PRIMARY KEY CLUSTERED 
(
	[id] 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].[jobRefreshOldCompany]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[jobRefreshOldCompany](
	[cpMainId] [int] NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[jobRefreshSet]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[jobRefreshSet](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[beginDate] [smalldatetime] NOT NULL,
	[endDate] [smalldatetime] NOT NULL,
	[refreshType] [tinyint] NOT NULL,
	[weekDays] [char](13) COLLATE Chinese_PRC_CI_AS NULL,
	[hours] [varchar](100) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[minute] [tinyint] NOT NULL,
	[jobId] [int] NOT NULL,
	[caMainId] [int] NOT NULL,
	[runState] [tinyint] NOT NULL,
	[addDate] [smalldatetime] NOT NULL,
 CONSTRAINT [PK_jobRefreshSet] PRIMARY KEY CLUSTERED 
(
	[id] 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].[JobSimilar]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[JobSimilar](
	[ID] [varchar](12) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[dcJobTypeID] [varchar](4) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[dcRegionID] [varchar](6) COLLATE Chinese_PRC_CI_AS NULL,
	[NeedNumber] [tinyint] NULL,
	[JobName] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[cpMainID] [varchar](10) COLLATE Chinese_PRC_CI_AS NULL,
	[cpName] [varchar](100) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[SubSiteUrl] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[LastLoginDate] [smalldatetime] NULL,
	[dcSalaryId] [smallint] NULL,
	[dcSalaryIdMax] [smallint] NULL,
 CONSTRAINT [PK_JobSimilar] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [CP]
) ON [CP]

GO
/****** Object:  Table [dbo].[JobSimilarCompare]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[JobSimilarCompare](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[JobID] [int] NOT NULL,
	[SimilarJobID] [int] NOT NULL,
	[JobCount] [int] NOT NULL,
	[Pecentage] [float] NOT NULL,
	[AddDate] [datetime] NOT NULL,
 CONSTRAINT [PK_JobLimiteCompare] PRIMARY KEY CLUSTERED 
(
	[id] 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].[JobSubScription]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[JobSubScription](
	[paJobFinderID] [int] NOT NULL,
	[JobId] [int] NOT NULL,
	[AddDate] [smalldatetime] NOT NULL
) ON [FOthers]

GO
/****** Object:  Index [IX_JobSubScription_PaJobFinderId]    Script Date: 2018/9/25 12:40:11 ******/
CREATE CLUSTERED INDEX [IX_JobSubScription_PaJobFinderId] ON [dbo].[JobSubScription]
(
	[paJobFinderID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [FOthers]
GO
/****** Object:  Table [dbo].[jobTags]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[jobTags](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[JobID] [int] NOT NULL,
	[Tags] [nvarchar](10) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[VerifyDate] [smalldatetime] NULL,
	[AddDate] [smalldatetime] NULL,
 CONSTRAINT [PK_jobTags] PRIMARY KEY CLUSTERED 
(
	[id] 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].[JobTemp]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[JobTemp](
	[ID] [int] NOT NULL,
	[cpMainID] [int] NOT NULL,
	[caMainID] [int] NOT NULL,
	[JobName] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[dcJobTypeID] [smallint] NOT NULL,
	[dcJobTypeIDMinor] [smallint] NULL,
	[NeedNumber] [tinyint] NULL,
	[dcSalaryID] [tinyint] NOT NULL,
	[EmployType] [tinyint] NOT NULL,
	[dcRegionID] [varchar](6) COLLATE Chinese_PRC_CI_AS NULL,
	[Responsibility] [nvarchar](max) COLLATE Chinese_PRC_CI_AS NULL,
	[Demand] [nvarchar](max) COLLATE Chinese_PRC_CI_AS NULL,
	[dcEducationID] [tinyint] NOT NULL,
	[MinExperience] [tinyint] NOT NULL,
	[MinAge] [tinyint] NULL,
	[MaxAge] [tinyint] NULL,
	[IssueDate] [smalldatetime] NULL,
	[IssueEND] [smalldatetime] NULL,
	[IsDelete] [bit] NOT NULL,
	[AddDate] [smalldatetime] NOT NULL,
	[RefreshDate] [smalldatetime] NULL,
	[LastModifyDate] [smalldatetime] NOT NULL,
	[cpName] [nvarchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[dcCompanySizeID] [tinyint] NULL,
	[HasLicence] [bit] NOT NULL,
	[UnLimitedDate] [smalldatetime] NOT NULL,
	[BalanceDate] [smalldatetime] NOT NULL,
	[Balance] [smallint] NOT NULL,
	[MemberType] [tinyint] NOT NULL,
	[EnJobID] [varchar](12) COLLATE Chinese_PRC_CI_AS NULL,
	[EnCpMainID] [varchar](10) COLLATE Chinese_PRC_CI_AS NULL,
	[Welfare1] [bit] NULL,
	[Welfare2] [bit] NULL,
	[Welfare3] [bit] NULL,
	[Welfare4] [bit] NULL,
	[Welfare5] [bit] NULL,
	[Welfare6] [bit] NULL,
	[Welfare7] [bit] NULL,
	[Welfare8] [bit] NULL,
	[Welfare9] [bit] NULL,
	[Welfare10] [bit] NULL,
	[Welfare11] [bit] NULL,
	[Welfare12] [bit] NULL,
	[Welfare13] [bit] NULL,
	[Welfare14] [bit] NULL,
	[Welfare15] [bit] NULL,
	[Welfare16] [bit] NULL,
	[Welfare17] [bit] NULL,
	[Welfare18] [bit] NULL,
	[IsOnline] [bit] NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

GO
/****** Object:  Table [dbo].[JobTemplate]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[JobTemplate](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[cpMainId] [int] NOT NULL,
	[caMainId] [int] NOT NULL,
	[Name] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[dcJobTypeId] [smallint] NULL,
	[dcJobTypeIdMinor] [int] NULL,
	[NeedNumber] [smallint] NULL,
	[dcSalaryId] [tinyint] NULL,
	[EmployType] [tinyint] NULL,
	[dcRegionId] [varchar](6) COLLATE Chinese_PRC_CI_AS NULL,
	[MapBarId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[Responsibility] [varchar](max) COLLATE Chinese_PRC_CI_AS NULL,
	[DeMand] [varchar](max) COLLATE Chinese_PRC_CI_AS NULL,
	[dcEducationId] [tinyint] NULL,
	[MinExperience] [tinyint] NULL,
	[MinAge] [tinyint] NULL,
	[MaxAge] [tinyint] NULL,
	[EMailSendFreq] [tinyint] NOT NULL,
	[EMailSendNumber] [tinyint] NULL,
	[AddDate] [smalldatetime] NOT NULL,
	[LastModifyDate] [smalldatetime] NOT NULL,
	[Lng] [decimal](8, 5) NULL,
	[Lat] [decimal](8, 5) NULL,
	[Promotion] [nvarchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[Welfare1] [bit] NULL,
	[Welfare2] [bit] NULL,
	[Welfare3] [bit] NULL,
	[Welfare4] [bit] NULL,
	[Welfare5] [bit] NULL,
	[Welfare6] [bit] NULL,
	[Welfare7] [bit] NULL,
	[Welfare8] [bit] NULL,
	[Welfare9] [bit] NULL,
	[Welfare10] [bit] NULL,
	[Welfare11] [bit] NULL,
	[Welfare12] [bit] NULL,
	[Welfare13] [bit] NULL,
	[Welfare14] [bit] NULL,
	[Welfare15] [bit] NULL,
	[Welfare16] [bit] NULL,
	[Welfare17] [bit] NULL,
	[Welfare18] [bit] NULL,
	[jobTags] [nvarchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[Negotiable] [bit] NULL,
	[dcSalaryIdMax] [tinyint] NULL,
	[Welfare19] [bit] NULL,
 CONSTRAINT [PK_JobTemplate] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [CP]
) ON [CP] TEXTIMAGE_ON [CP]

GO
/****** Object:  Table [dbo].[JobTypeTmp]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[JobTypeTmp](
	[ID] [smallint] NOT NULL,
	[ParentID] [smallint] NULL,
	[grade] [tinyint] NOT NULL,
	[Description] [nvarchar](25) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[DescriptionEng] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[ParentID2] [smallint] NULL,
	[ParentID3] [smallint] NULL,
	[OrderNo] [smallint] NOT NULL,
	[newId] [int] NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[jpi0807]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[jpi0807](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[YearMonth] [int] NOT NULL,
	[ManagerUserId] [smallint] NOT NULL,
	[Name] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[IE_Target] [numeric](8, 2) NULL,
	[IE] [numeric](8, 2) NULL,
	[LP_Completed] [smallint] NULL,
	[LP_NotCompleted] [smallint] NULL,
	[OC_Self] [smallint] NULL,
	[OC_Higher] [smallint] NULL,
	[KM_Received] [smallint] NULL,
	[KM_Received_Subordinate] [smallint] NULL,
	[KM_Sent] [smallint] NULL,
	[KM_Target] [smallint] NULL,
	[KM_Sent_Subordinate] [smallint] NULL,
	[KM_Target_Subordinate] [smallint] NULL,
	[KM] [numeric](8, 2) NULL,
	[EC_Self] [smallint] NULL,
	[EC_Subordinate] [smallint] NULL,
	[EC] [numeric](8, 2) NULL,
	[SA_Self] [numeric](8, 2) NULL,
	[SA_Higher] [numeric](8, 2) NULL,
	[KPI] [numeric](8, 2) NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[KeyWord2JobType]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[KeyWord2JobType](
	[id] [int] IDENTITY(1,1) NOT FOR REPLICATION NOT NULL,
	[crDate] [datetime] NOT NULL,
	[KeyWord] [nvarchar](20) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[dcJobTypeIds] [varchar](24) COLLATE Chinese_PRC_CI_AS NOT NULL,
 CONSTRAINT [PK_KeyWord2JobType_1] PRIMARY KEY CLUSTERED 
(
	[KeyWord] 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].[KeyWordProcessLog]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[KeyWordProcessLog](
	[id] [int] IDENTITY(1,1) NOT FOR REPLICATION NOT NULL,
	[crDate] [datetime] NULL,
	[Keyword] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[Operator] [int] NULL,
	[OperDate] [datetime] NULL,
	[dcjobTypeIds] [varchar](30) COLLATE Chinese_PRC_CI_AS NULL,
 CONSTRAINT [PK_KeyWordProcessLog] PRIMARY KEY CLUSTERED 
(
	[id] 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].[knowledge]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[knowledge](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[title] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[DescrIption] [nvarchar](1000) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[addDate] [smalldatetime] NOT NULL,
	[Type] [smallint] NOT NULL,
	[ManagerUserId] [smallint] NOT NULL,
	[attachment] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
 CONSTRAINT [PK_knowledge] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers]
) ON [BOthers]

GO
/****** Object:  Table [dbo].[KPI]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[KPI](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[YearMonth] [int] NOT NULL,
	[ManagerUserId] [smallint] NOT NULL,
	[Name] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[IE_Target] [numeric](8, 2) NULL,
	[IE] [numeric](8, 2) NULL,
	[LP_Completed] [smallint] NULL,
	[LP_NotCompleted] [smallint] NULL,
	[OC_Self] [smallint] NULL,
	[OC_Higher] [smallint] NULL,
	[KM_Received] [smallint] NULL,
	[KM_Received_Subordinate] [smallint] NULL,
	[KM_Sent] [smallint] NULL,
	[KM_Target] [smallint] NULL,
	[KM_Sent_Subordinate] [smallint] NULL,
	[KM_Target_Subordinate] [smallint] NULL,
	[KM] [numeric](8, 2) NULL,
	[EC_Self] [smallint] NULL,
	[EC_Subordinate] [smallint] NULL,
	[EC] [numeric](8, 2) NULL,
	[SA_Self] [numeric](8, 2) NULL,
	[SA_Higher] [numeric](8, 2) NULL,
	[KPI] [numeric](8, 2) NULL,
 CONSTRAINT [PK_KPI] PRIMARY KEY CLUSTERED 
(
	[Id] 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].[KPI_EC]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[KPI_EC](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[AddDate] [smalldatetime] NOT NULL,
	[Sender] [smallint] NOT NULL,
	[Receiver] [smallint] NOT NULL,
	[DescrIption] [nvarchar](1000) COLLATE Chinese_PRC_CI_AS NOT NULL,
 CONSTRAINT [PK_KPI_EC] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers]
) ON [BOthers]

GO
/****** Object:  Table [dbo].[KPI_IE]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[KPI_IE](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[AddDate] [smalldatetime] NOT NULL,
	[Sender] [smallint] NOT NULL,
	[Receiver] [smallint] NOT NULL,
	[Present] [nvarchar](max) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[improvement] [nvarchar](max) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[effect] [nvarchar](max) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[feasible] [nvarchar](max) COLLATE Chinese_PRC_CI_AS NULL,
	[ApplyMeasure] [nvarchar](max) COLLATE Chinese_PRC_CI_AS NULL,
	[cooperation] [nvarchar](max) COLLATE Chinese_PRC_CI_AS NULL,
	[reply_Date] [smalldatetime] NULL,
	[status] [tinyint] NOT NULL,
	[receiver_higher] [smalldatetime] NULL,
	[sender_higher] [smalldatetime] NULL,
	[referee_reply] [nvarchar](max) COLLATE Chinese_PRC_CI_AS NULL,
	[referee_Date] [smalldatetime] NULL,
	[CompleteDate] [smalldatetime] NULL,
	[expectCompleteDate] [smalldatetime] NULL,
	[title] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[attachment] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[Type] [smallint] NULL,
	[stockDate] [smalldatetime] NULL,
	[createDate] [smalldatetime] NOT NULL,
	[TransferLog] [nvarchar](1000) COLLATE Chinese_PRC_CI_AS NULL,
	[TransferContent] [nvarchar](1000) COLLATE Chinese_PRC_CI_AS NULL,
	[kind] [smallint] NULL,
	[refereer] [int] NULL,
	[BugMan] [smallint] NULL,
	[BugMonth] [tinyint] NULL,
	[IsAccept] [tinyint] NULL,
	[CheckMan] [int] NULL,
	[CheckDate] [smalldatetime] NULL,
	[CheckOpinion] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL,
	[CheckScore] [tinyint] NULL,
	[OldSender] [nvarchar](20) COLLATE Chinese_PRC_CI_AS NULL,
	[OldReceiver] [nvarchar](20) COLLATE Chinese_PRC_CI_AS NULL,
 CONSTRAINT [PK_KPI_IE] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers]
) ON [BOthers] TEXTIMAGE_ON [PRIMARY]

GO
/****** Object:  Table [dbo].[Kpi_IeToSales]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Kpi_IeToSales](
	[id] [int] NOT NULL,
	[title] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[present] [nvarchar](max) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[improvement] [nvarchar](max) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[effect] [nvarchar](max) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[feasible] [nvarchar](max) COLLATE Chinese_PRC_CI_AS NULL,
	[ApplyMeasure] [nvarchar](max) COLLATE Chinese_PRC_CI_AS NULL,
 CONSTRAINT [PK_Kpi_IeToSales] PRIMARY KEY CLUSTERED 
(
	[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

GO
/****** Object:  Table [dbo].[KPI_KM]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[KPI_KM](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[AddDate] [smalldatetime] NOT NULL,
	[Sender] [smallint] NOT NULL,
	[Receiver] [smallint] NOT NULL,
	[DescrIption] [nvarchar](1000) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Reply] [nvarchar](1000) COLLATE Chinese_PRC_CI_AS NULL,
	[Reply_Date] [smalldatetime] NULL,
	[Status] [tinyint] NOT NULL,
	[Receiver_higher] [smalldatetime] NULL,
	[Sender_higher] [smalldatetime] NULL,
	[Referee_reply] [nvarchar](1000) COLLATE Chinese_PRC_CI_AS NULL,
	[Referee_Date] [smalldatetime] NULL,
	[Attachment] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[Check_Date] [smalldatetime] NULL,
 CONSTRAINT [PK_KPI_KM] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers]
) ON [BOthers]

GO
/****** Object:  Table [dbo].[KPI_LP]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[KPI_LP](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[AddDate] [smalldatetime] NOT NULL,
	[Sender] [smallint] NOT NULL,
	[Receiver] [smallint] NOT NULL,
	[Liaison] [nvarchar](1000) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Reply_Date] [smalldatetime] NULL,
	[Status] [tinyint] NOT NULL,
	[Receiver_higher] [smalldatetime] NULL,
	[Sender_higher] [smalldatetime] NULL,
	[ExpectCompleteDate] [smalldatetime] NULL,
	[CompleteDate] [smalldatetime] NULL,
	[Attachment] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[Reason] [nvarchar](1000) COLLATE Chinese_PRC_CI_AS NULL,
	[Attachment_Over] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[CheckComment] [nvarchar](1000) COLLATE Chinese_PRC_CI_AS NULL,
 CONSTRAINT [PK_KPI_LP] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers]
) ON [BOthers]

GO
/****** Object:  Table [dbo].[KPI_OC]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[KPI_OC](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[YearMonth] [int] NOT NULL,
	[ManagerUserId] [smallint] NOT NULL,
	[Workplan] [nvarchar](200) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Standard] [nvarchar](200) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Obj_self] [nvarchar](200) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Obj_higher] [nvarchar](200) COLLATE Chinese_PRC_CI_AS NULL,
	[Score] [tinyint] NULL,
	[Kpi_power] [tinyint] NULL,
	[Achieve_self] [nvarchar](200) COLLATE Chinese_PRC_CI_AS NULL,
	[Acc_self] [tinyint] NULL,
	[acc_higher] [tinyint] NULL,
	[Achieve_higher] [nvarchar](200) COLLATE Chinese_PRC_CI_AS NULL,
	[No] [tinyint] NOT NULL,
	[Status] [tinyint] NULL,
	[Self_Attachment] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[Last_Date] [smalldatetime] NULL,
 CONSTRAINT [PK_KPI_OC] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers]
) ON [BOthers]

GO
/****** Object:  Table [dbo].[KPI_SA]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[KPI_SA](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[YearMonth] [int] NOT NULL,
	[ManagerUserId] [smallint] NOT NULL,
	[a1_s] [tinyint] NULL,
	[a1_h] [tinyint] NULL,
	[a1_key_s] [nvarchar](500) COLLATE Chinese_PRC_CI_AS NULL,
	[a1_key_h] [nvarchar](500) COLLATE Chinese_PRC_CI_AS NULL,
	[a2_s] [tinyint] NULL,
	[a2_h] [tinyint] NULL,
	[a2_key_s] [nvarchar](500) COLLATE Chinese_PRC_CI_AS NULL,
	[a2_key_h] [nvarchar](500) COLLATE Chinese_PRC_CI_AS NULL,
	[b1_s] [tinyint] NULL,
	[b1_h] [tinyint] NULL,
	[b1_key_s] [nvarchar](500) COLLATE Chinese_PRC_CI_AS NULL,
	[b1_key_h] [nvarchar](500) COLLATE Chinese_PRC_CI_AS NULL,
	[c1_s] [tinyint] NULL,
	[c1_h] [tinyint] NULL,
	[c1_key_s] [nvarchar](500) COLLATE Chinese_PRC_CI_AS NULL,
	[c1_key_h] [nvarchar](500) COLLATE Chinese_PRC_CI_AS NULL,
	[d1_s] [tinyint] NULL,
	[d1_h] [tinyint] NULL,
	[d1_key_s] [nvarchar](500) COLLATE Chinese_PRC_CI_AS NULL,
	[d1_key_h] [nvarchar](500) COLLATE Chinese_PRC_CI_AS NULL,
	[e1_s] [tinyint] NULL,
	[e1_h] [tinyint] NULL,
	[e1_key_s] [nvarchar](500) COLLATE Chinese_PRC_CI_AS NULL,
	[e1_key_h] [nvarchar](500) COLLATE Chinese_PRC_CI_AS NULL,
	[Status] [tinyint] NULL,
 CONSTRAINT [PK_KPI_SA] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers]
) ON [BOthers]

GO
/****** Object:  Table [dbo].[Kpi2016202]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Kpi2016202](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[YearMonth] [int] NOT NULL,
	[ManagerUserId] [smallint] NOT NULL,
	[Name] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[IE_Target] [numeric](8, 2) NULL,
	[IE] [numeric](8, 2) NULL,
	[LP_Completed] [smallint] NULL,
	[LP_NotCompleted] [smallint] NULL,
	[OC_Self] [smallint] NULL,
	[OC_Higher] [smallint] NULL,
	[KM_Received] [smallint] NULL,
	[KM_Received_Subordinate] [smallint] NULL,
	[KM_Sent] [smallint] NULL,
	[KM_Target] [smallint] NULL,
	[KM_Sent_Subordinate] [smallint] NULL,
	[KM_Target_Subordinate] [smallint] NULL,
	[KM] [numeric](8, 2) NULL,
	[EC_Self] [smallint] NULL,
	[EC_Subordinate] [smallint] NULL,
	[EC] [numeric](8, 2) NULL,
	[SA_Self] [numeric](8, 2) NULL,
	[SA_Higher] [numeric](8, 2) NULL,
	[KPI] [numeric](8, 2) NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[kpi201704]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[kpi201704](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[YearMonth] [int] NOT NULL,
	[ManagerUserId] [smallint] NOT NULL,
	[Name] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[IE_Target] [numeric](8, 2) NULL,
	[IE] [numeric](8, 2) NULL,
	[LP_Completed] [smallint] NULL,
	[LP_NotCompleted] [smallint] NULL,
	[OC_Self] [smallint] NULL,
	[OC_Higher] [smallint] NULL,
	[KM_Received] [smallint] NULL,
	[KM_Received_Subordinate] [smallint] NULL,
	[KM_Sent] [smallint] NULL,
	[KM_Target] [smallint] NULL,
	[KM_Sent_Subordinate] [smallint] NULL,
	[KM_Target_Subordinate] [smallint] NULL,
	[KM] [numeric](8, 2) NULL,
	[EC_Self] [smallint] NULL,
	[EC_Subordinate] [smallint] NULL,
	[EC] [numeric](8, 2) NULL,
	[SA_Self] [numeric](8, 2) NULL,
	[SA_Higher] [numeric](8, 2) NULL,
	[KPI] [numeric](8, 2) NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[link_count]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[link_count](
	[LinkId] [int] NOT NULL,
	[YearMonth] [int] NOT NULL,
	[Power] [int] NOT NULL
) ON [Market]

GO
/****** Object:  Table [dbo].[link_score]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[link_score](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[CountDate] [smalldatetime] NOT NULL,
	[VersionId] [int] NOT NULL,
	[Score] [numeric](6, 3) NOT NULL,
	[Num] [int] NOT NULL,
 CONSTRAINT [PK_link_score] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Market]
) ON [Market]

GO
/****** Object:  Table [dbo].[linkclick]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[linkclick](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[Link_Id] [int] NOT NULL,
	[Ip] [varchar](15) COLLATE Chinese_PRC_CI_AS NULL,
	[LoginDate] [smalldatetime] NOT NULL,
 CONSTRAINT [PK_linkclick] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Market]
) ON [Market]

GO
/****** Object:  Table [dbo].[LinkNocheck]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[LinkNocheck](
	[Link] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[LogSize]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[LogSize](
	[DbName] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[LogSize] [decimal](8, 2) NOT NULL,
	[LogUsed] [decimal](5, 2) NOT NULL,
	[Status] [int] NULL,
	[AddDate] [smalldatetime] NOT NULL
) ON [BOthers]

GO
/****** Object:  Table [dbo].[ManagerLog]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ManagerLog](
	[ManagerId] [smallint] NOT NULL,
	[LoginDate] [smalldatetime] NOT NULL,
	[Ip] [varchar](15) COLLATE Chinese_PRC_CI_AS NULL,
	[Cookies] [varchar](16) COLLATE Chinese_PRC_CI_AS NULL,
	[Mac] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL,
	[InternalIp] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL,
	[ComputerName] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL
) ON [BOthers]

GO
/****** Object:  Index [IX_ManagerLog_LoginDate]    Script Date: 2018/9/25 12:40:11 ******/
CREATE CLUSTERED INDEX [IX_ManagerLog_LoginDate] ON [dbo].[ManagerLog]
(
	[LoginDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers]
GO
/****** Object:  Table [dbo].[ManagerLogSnap]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ManagerLogSnap](
	[ManagerId] [smallint] NOT NULL,
	[LoginDate] [datetime] NOT NULL,
	[Ip] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[manageruser0806]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[manageruser0806](
	[id] [smallint] NOT NULL,
	[UserName] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Password] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[name] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[name_eng] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[OpenName] [tinyint] NULL,
	[superior] [smallint] NULL,
	[title] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[roleid] [int] NOT NULL,
	[deptid] [int] NOT NULL,
	[adddate] [smalldatetime] NOT NULL,
	[logincount] [int] NOT NULL,
	[lastlogindate] [smalldatetime] NULL,
	[type] [smallint] NULL,
	[email] [nvarchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[photo] [nvarchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[introduce] [nvarchar](200) COLLATE Chinese_PRC_CI_AS NULL,
	[status] [smallint] NOT NULL,
	[loginstatus] [smallint] NULL,
	[localrate] [numeric](18, 2) NULL,
	[kpi_manager] [tinyint] NULL,
	[km] [smallint] NULL,
	[km_score] [smallint] NULL,
	[ie] [smallint] NULL,
	[mobile] [varchar](11) COLLATE Chinese_PRC_CI_AS NULL,
	[cookies] [varchar](16) COLLATE Chinese_PRC_CI_AS NULL,
	[rtxstatus] [tinyint] NULL,
	[ec] [smallint] NULL,
	[consultantnum_up] [int] NOT NULL,
	[consultantnum] [int] NOT NULL,
	[consultantnum_noyingye] [int] NOT NULL,
	[consultantnum_up_new] [int] NULL,
	[consultantnum_new] [int] NULL,
	[HRKpiPostId] [int] NULL,
	[HRKpiPostGrade] [tinyint] NULL,
	[consultantnum_quota] [int] NULL,
	[consultantnum_release] [int] NULL,
	[consultantnum_release_lastmonth] [int] NULL,
	[office] [tinyint] NULL,
	[rtxTime] [datetime] NOT NULL,
	[SOLStatus] [tinyint] NULL,
	[SOLTime] [datetime] NULL,
	[LoginIp] [varchar](15) COLLATE Chinese_PRC_CI_AS NULL,
	[ActiveTime] [smalldatetime] NULL,
	[CompanyQQ] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL,
	[SalesLevel] [smallint] NULL,
	[WeiXinNo] [varchar](30) COLLATE Chinese_PRC_CI_AS NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[manageruser0806_1]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[manageruser0806_1](
	[id] [smallint] NOT NULL,
	[UserName] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Password] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[name] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[name_eng] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[OpenName] [tinyint] NULL,
	[superior] [smallint] NULL,
	[title] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[roleid] [int] NOT NULL,
	[deptid] [int] NOT NULL,
	[adddate] [smalldatetime] NOT NULL,
	[logincount] [int] NOT NULL,
	[lastlogindate] [smalldatetime] NULL,
	[type] [smallint] NULL,
	[email] [nvarchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[photo] [nvarchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[introduce] [nvarchar](200) COLLATE Chinese_PRC_CI_AS NULL,
	[status] [smallint] NOT NULL,
	[loginstatus] [smallint] NULL,
	[localrate] [numeric](18, 2) NULL,
	[kpi_manager] [tinyint] NULL,
	[km] [smallint] NULL,
	[km_score] [smallint] NULL,
	[ie] [smallint] NULL,
	[mobile] [varchar](11) COLLATE Chinese_PRC_CI_AS NULL,
	[cookies] [varchar](16) COLLATE Chinese_PRC_CI_AS NULL,
	[rtxstatus] [tinyint] NULL,
	[ec] [smallint] NULL,
	[consultantnum_up] [int] NOT NULL,
	[consultantnum] [int] NOT NULL,
	[consultantnum_noyingye] [int] NOT NULL,
	[consultantnum_up_new] [int] NULL,
	[consultantnum_new] [int] NULL,
	[HRKpiPostId] [int] NULL,
	[HRKpiPostGrade] [tinyint] NULL,
	[consultantnum_quota] [int] NULL,
	[consultantnum_release] [int] NULL,
	[consultantnum_release_lastmonth] [int] NULL,
	[office] [tinyint] NULL,
	[rtxTime] [datetime] NOT NULL,
	[SOLStatus] [tinyint] NULL,
	[SOLTime] [datetime] NULL,
	[LoginIp] [varchar](15) COLLATE Chinese_PRC_CI_AS NULL,
	[ActiveTime] [smalldatetime] NULL,
	[CompanyQQ] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL,
	[SalesLevel] [smallint] NULL,
	[WeiXinNo] [varchar](30) COLLATE Chinese_PRC_CI_AS NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[ManagerUserChange]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ManagerUserChange](
	[OldManagerUSerId] [smallint] NULL,
	[NewManagerUserId] [smallint] NULL,
	[AddDate] [smalldatetime] NULL,
	[step] [tinyint] NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[ManagerUserCompanyLog]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ManagerUserCompanyLog](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[CompanyId] [int] NOT NULL,
	[ManagerUserId] [smallint] NOT NULL,
	[AddDate] [datetime] NOT NULL,
	[Cookies] [varchar](16) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Ip] [varchar](30) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Source] [tinyint] NOT NULL,
 CONSTRAINT [PK_ManagerUserCompanyLog] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers]
) ON [BOthers]

GO
/****** Object:  Table [dbo].[mblFeedBack]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[mblFeedBack](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[Content] [nvarchar](200) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Version] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[AddDate] [smalldatetime] NULL,
	[paMainID] [int] NULL,
	[Name] [nvarchar](6) COLLATE Chinese_PRC_CI_AS NULL,
	[Mobile] [varchar](13) COLLATE Chinese_PRC_CI_AS NULL,
	[Email] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[ContactMan] [smallint] NULL,
	[ContactDate] [smalldatetime] NULL,
PRIMARY KEY CLUSTERED 
(
	[ID] 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].[mblSql]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[mblSql](
	[SQL] [varchar](500) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Version] [smallint] NOT NULL,
	[AddDate] [smalldatetime] NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[mblVersion]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[mblVersion](
	[Version] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[DownloadURL] [varchar](200) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[AddDate] [smalldatetime] NOT NULL,
	[IsMust] [bit] NULL,
	[Description] [nvarchar](500) COLLATE Chinese_PRC_CI_AS NULL,
	[DownloadCount] [int] NULL,
	[AppType] [tinyint] NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[MobileCerIPVisitLog]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[MobileCerIPVisitLog](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[IP] [varchar](31) COLLATE Chinese_PRC_CI_AS NULL,
	[AddDate] [datetime] NULL,
	[ClientType] [smallint] NULL,
PRIMARY KEY CLUSTERED 
(
	[ID] 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].[msEmailPrevSend]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[msEmailPrevSend](
	[ID] [int] IDENTITY(1,1) NOT FOR REPLICATION NOT NULL,
	[cpMainId] [int] NULL,
	[paMainId] [int] NULL,
	[EmailNo] [tinyint] NOT NULL,
	[EmailTitle] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[JasonData] [nvarchar](max) COLLATE Chinese_PRC_CI_AS NULL,
	[Email] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[dcSubsiteId] [smallint] NOT NULL,
	[IsSend] [tinyint] NOT NULL,
	[AddDate] [datetime] NOT NULL,
	[SendDate] [datetime] NULL,
	[EmailBody] [varchar](max) COLLATE Chinese_PRC_CI_AS NULL,
	[JsonData] [varchar](max) COLLATE Chinese_PRC_CI_AS NULL,
	[ErrorNumber] [tinyint] NULL,
 CONSTRAINT [PK_msEmailPrevSend] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers]
) ON [BOthers] TEXTIMAGE_ON [BOthers]

GO
/****** Object:  Table [dbo].[msemailprevsend1206]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[msemailprevsend1206](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[cpMainId] [int] NULL,
	[paMainId] [int] NULL,
	[EmailNo] [tinyint] NOT NULL,
	[EmailTitle] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[JasonData] [nvarchar](max) COLLATE Chinese_PRC_CI_AS NULL,
	[Email] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[dcSubsiteId] [smallint] NOT NULL,
	[IsSend] [tinyint] NOT NULL,
	[AddDate] [datetime] NOT NULL,
	[SendDate] [datetime] NULL,
	[EmailBody] [varchar](max) COLLATE Chinese_PRC_CI_AS NULL,
	[JsonData] [varchar](max) COLLATE Chinese_PRC_CI_AS NULL,
	[ErrorNumber] [tinyint] NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

GO
/****** Object:  Table [dbo].[msEmailSend]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[msEmailSend](
	[ID] [int] IDENTITY(1,1) NOT FOR REPLICATION NOT NULL,
	[msProcessLogId] [int] NOT NULL,
	[msEmailTypeId] [int] NOT NULL,
	[Host] [varchar](30) COLLATE Chinese_PRC_CI_AS NULL,
	[UserName] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[Email] [varchar](max) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Title] [nvarchar](80) COLLATE Chinese_PRC_CI_AS NULL,
	[EmailBody] [nvarchar](max) COLLATE Chinese_PRC_CI_AS NULL,
	[Status] [bit] NOT NULL,
	[AddDate] [datetime] NOT NULL,
 CONSTRAINT [PK_msEmailSend] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers]
) ON [BOthers] TEXTIMAGE_ON [BOthers]

GO
/****** Object:  Table [dbo].[msEmailTemplete]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[msEmailTemplete](
	[ID] [int] IDENTITY(1,1) NOT FOR REPLICATION NOT NULL,
	[msSqlID] [int] NOT NULL,
	[Name] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Title] [varchar](100) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[MailBody] [varchar](max) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[SubMailBody] [varchar](max) COLLATE Chinese_PRC_CI_AS NULL,
	[NoDataBody] [varchar](max) COLLATE Chinese_PRC_CI_AS NULL,
	[Status] [tinyint] NULL,
	[AddMan] [smallint] NOT NULL,
	[AddDate] [smalldatetime] NOT NULL,
 CONSTRAINT [PK_msBodyTemplete] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers]
) ON [BOthers] TEXTIMAGE_ON [BOthers]

GO
/****** Object:  Table [dbo].[msEmailTempleteEdit]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[msEmailTempleteEdit](
	[ID] [int] NOT NULL,
	[msSqlID] [int] NOT NULL,
	[Name] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Title] [varchar](100) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[MailBody] [varchar](max) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[SubMailBody] [varchar](max) COLLATE Chinese_PRC_CI_AS NULL,
	[NoDataBody] [varchar](max) COLLATE Chinese_PRC_CI_AS NULL,
	[Status] [tinyint] NULL,
	[AddMan] [smallint] NOT NULL,
	[AddDate] [smalldatetime] NOT NULL,
 CONSTRAINT [PK_msEmailTemplete] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers]
) ON [BOthers] TEXTIMAGE_ON [BOthers]

GO
/****** Object:  Table [dbo].[msEmailTempleteLog]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[msEmailTempleteLog](
	[ID] [int] IDENTITY(1,1) NOT FOR REPLICATION NOT NULL,
	[msEmailTempleteId] [int] NULL,
	[msSqlID] [int] NOT NULL,
	[Name] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Title] [varchar](100) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[MailBody] [varchar](max) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[SubMailBody] [varchar](max) COLLATE Chinese_PRC_CI_AS NULL,
	[NoDataBody] [varchar](max) COLLATE Chinese_PRC_CI_AS NULL,
	[Status] [tinyint] NULL,
	[AddMan] [smallint] NOT NULL,
	[AddDate] [smalldatetime] NOT NULL,
 CONSTRAINT [PK_msEmailTempleteLo] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers]
) ON [BOthers] TEXTIMAGE_ON [BOthers]

GO
/****** Object:  Table [dbo].[msEmailTitle]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[msEmailTitle](
	[Id] [int] IDENTITY(1,1) NOT FOR REPLICATION NOT NULL,
	[msBodyTempleteId] [int] NULL,
	[Title] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[GoToServer] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[dcProvinceId] [tinyint] NOT NULL,
	[AddMan] [smallint] NOT NULL,
	[AddDate] [smalldatetime] NOT NULL,
 CONSTRAINT [PK_msEmailTitle] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers]
) ON [BOthers]

GO
/****** Object:  Table [dbo].[msEmailType]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[msEmailType](
	[ID] [int] IDENTITY(1,1) NOT FOR REPLICATION NOT NULL,
	[Name] [nvarchar](100) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[msEmailTempleteId] [int] NOT NULL,
	[msSqlId] [int] NOT NULL,
	[AllowedSite] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL,
	[BannedSite] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL,
	[ProvinceIds] [varchar](200) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Sender] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Host] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[ParamValue] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL,
	[Status] [tinyint] NULL,
	[IsPause] [bit] NOT NULL,
	[VerifyMan] [smallint] NULL,
	[VerifyDate] [smalldatetime] NULL,
	[VerifyMessage] [varchar](500) COLLATE Chinese_PRC_CI_AS NULL,
	[AddMan] [smallint] NOT NULL,
	[AddDate] [smalldatetime] NOT NULL,
	[ViewMan] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[emailno] [int] NULL,
 CONSTRAINT [PK_msEmailMain] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers]
) ON [BOthers]

GO
/****** Object:  Table [dbo].[msemailtype1023]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[msemailtype1023](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[Name] [nvarchar](100) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[msEmailTempleteId] [int] NOT NULL,
	[msSqlId] [int] NOT NULL,
	[AllowedSite] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL,
	[BannedSite] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL,
	[ProvinceIds] [varchar](200) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Sender] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Host] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[ParamValue] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL,
	[Status] [tinyint] NULL,
	[IsPause] [bit] NOT NULL,
	[VerifyMan] [smallint] NULL,
	[VerifyDate] [smalldatetime] NULL,
	[VerifyMessage] [varchar](500) COLLATE Chinese_PRC_CI_AS NULL,
	[AddMan] [smallint] NOT NULL,
	[AddDate] [smalldatetime] NOT NULL,
	[ViewMan] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[emailno] [int] NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[msEmailTypeEdit]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[msEmailTypeEdit](
	[ID] [int] NOT NULL,
	[Name] [nvarchar](100) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[msEmailTempleteId] [int] NOT NULL,
	[msSqlId] [int] NOT NULL,
	[AllowedSite] [varchar](200) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[BannedSite] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL,
	[ProvinceIds] [varchar](200) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Sender] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Host] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[ParamValue] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL,
	[Status] [tinyint] NULL,
	[IsPause] [bit] NULL,
	[VerifyMan] [smallint] NULL,
	[VerifyDate] [smalldatetime] NULL,
	[VerifyMessage] [varchar](500) COLLATE Chinese_PRC_CI_AS NULL,
	[AddMan] [smallint] NOT NULL,
	[AddDate] [smalldatetime] NULL,
	[emailno] [int] NULL,
 CONSTRAINT [PK_msEmailType] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers]
) ON [BOthers]

GO
/****** Object:  Table [dbo].[msProcess]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[msProcess](
	[ID] [int] IDENTITY(1,1) NOT FOR REPLICATION NOT NULL,
	[msEmailTypeId] [int] NOT NULL,
	[dcSubSiteId] [smallint] NOT NULL,
	[Sender] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Host] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[msScheduleId] [int] NOT NULL,
	[MaxRunMinute] [smallint] NOT NULL,
	[SendInterval] [int] NULL,
	[NextRunTime] [smalldatetime] NULL,
	[RunStatus] [tinyint] NULL,
	[SendNumber] [int] NULL,
	[ccMail] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[ccRate] [smallint] NULL,
	[AddMan] [smallint] NOT NULL,
	[AddDate] [smalldatetime] NOT NULL,
 CONSTRAINT [PK_msProcess] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers]
) ON [BOthers]

GO
/****** Object:  Table [dbo].[msProcess0103]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[msProcess0103](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[msEmailTypeId] [int] NOT NULL,
	[dcSubSiteId] [smallint] NOT NULL,
	[Sender] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Host] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[msScheduleId] [int] NOT NULL,
	[MaxRunMinute] [smallint] NOT NULL,
	[SendInterval] [int] NULL,
	[NextRunTime] [smalldatetime] NULL,
	[RunStatus] [tinyint] NULL,
	[SendNumber] [int] NULL,
	[ccMail] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[ccRate] [smallint] NULL,
	[AddMan] [smallint] NOT NULL,
	[AddDate] [smalldatetime] NOT NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[msprocess1023]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[msprocess1023](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[msEmailTypeId] [int] NOT NULL,
	[dcSubSiteId] [smallint] NOT NULL,
	[Sender] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Host] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[msScheduleId] [int] NOT NULL,
	[MaxRunMinute] [smallint] NOT NULL,
	[SendInterval] [int] NULL,
	[NextRunTime] [smalldatetime] NULL,
	[RunStatus] [tinyint] NULL,
	[SendNumber] [int] NULL,
	[ccMail] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[ccRate] [smallint] NULL,
	[AddMan] [smallint] NOT NULL,
	[AddDate] [smalldatetime] NOT NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[msProcessEdit]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[msProcessEdit](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[msEmailTypeId] [int] NOT NULL,
	[dcSubSiteId] [smallint] NOT NULL,
	[Sender] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Host] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[msScheduleId] [int] NOT NULL,
	[MaxRunMinute] [smallint] NOT NULL,
	[SendInterval] [tinyint] NULL,
	[NextRunTime] [smalldatetime] NULL,
	[RunStatus] [tinyint] NULL,
	[SendNumber] [int] NULL,
	[ccMail] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[ccRate] [smallint] NULL,
	[AddMan] [smallint] NOT NULL,
	[AddDate] [smalldatetime] NOT NULL,
 CONSTRAINT [PK_msProcessEdit] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers]
) ON [BOthers]

GO
/****** Object:  Table [dbo].[msProcessLog]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[msProcessLog](
	[ID] [int] IDENTITY(1,1) NOT FOR REPLICATION NOT NULL,
	[msProcessId] [int] NOT NULL,
	[BeginTime] [datetime] NOT NULL,
	[EndTime] [datetime] NULL,
	[EndStatus] [int] NOT NULL,
	[SendNumber] [int] NOT NULL,
	[SuccessNumber] [int] NOT NULL,
	[FailNumber] [int] NOT NULL,
	[Remark] [nvarchar](max) COLLATE Chinese_PRC_CI_AS NULL,
 CONSTRAINT [PK_msProcessLog] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers]
) ON [BOthers] TEXTIMAGE_ON [BOthers]

GO
/****** Object:  Table [dbo].[msSchedule]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[msSchedule](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[Name] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Enabled] [bit] NOT NULL,
	[FreqType] [tinyint] NOT NULL,
	[FreqInterval] [smallint] NULL,
	[FreqSubdayType] [tinyint] NULL,
	[FreqSubdayInterval] [smallint] NULL,
	[ActiveStartDate] [int] NOT NULL,
	[ActiveEndDate] [int] NOT NULL,
	[ActiveStartTime] [smallint] NOT NULL,
	[ActiveEndTime] [smallint] NOT NULL,
	[AddMan] [smallint] NULL,
	[AddDate] [smalldatetime] NOT NULL,
 CONSTRAINT [PK_mcSchedule] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers]
) ON [BOthers]

GO
/****** Object:  Table [dbo].[msSql]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[msSql](
	[ID] [int] IDENTITY(1,1) NOT FOR REPLICATION NOT NULL,
	[Name] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Sql] [varchar](max) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[ParamIn] [varchar](500) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[ParamOut] [varchar](500) COLLATE Chinese_PRC_CI_AS NULL,
	[SubSql] [varchar](max) COLLATE Chinese_PRC_CI_AS NULL,
	[SubParam] [varchar](500) COLLATE Chinese_PRC_CI_AS NULL,
	[Relation] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[AfterSendSql] [varchar](max) COLLATE Chinese_PRC_CI_AS NULL,
	[FinishedSql] [varchar](max) COLLATE Chinese_PRC_CI_AS NULL,
	[Remark] [nvarchar](500) COLLATE Chinese_PRC_CI_AS NULL,
	[ManagerUserId] [smallint] NOT NULL,
	[Status] [tinyint] NULL,
	[AddMan] [smallint] NOT NULL,
	[AddDate] [smalldatetime] NOT NULL,
 CONSTRAINT [PK_msSqlTemplete] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers]
) ON [BOthers] TEXTIMAGE_ON [BOthers]

GO
/****** Object:  Table [dbo].[MT]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[MT](
	[Id] [smallint] IDENTITY(1,1) NOT NULL,
	[MTname] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Valid] [bit] NULL,
 CONSTRAINT [PK_meeting_room] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers]
) ON [BOthers]

GO
/****** Object:  Table [dbo].[MT_plan]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[MT_plan](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[Begintime] [smalldatetime] NOT NULL,
	[Endtime] [smalldatetime] NOT NULL,
	[AddMan] [smallint] NOT NULL,
	[Title] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[AddDate] [smalldatetime] NOT NULL,
	[Mt_Id] [smallint] NOT NULL,
	[Parti] [varchar](1200) COLLATE Chinese_PRC_CI_AS NULL,
 CONSTRAINT [PK_MT_plan] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers]
) ON [BOthers]

GO
/****** Object:  Table [dbo].[nhLottery]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[nhLottery](
	[LotteryType] [tinyint] NULL,
	[Region] [tinyint] NULL,
	[Mobile] [char](13) COLLATE Chinese_PRC_CI_AS NULL,
	[ManagerUserID] [smallint] NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[nhSms]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[nhSms](
	[ID] [int] IDENTITY(1,1) NOT FOR REPLICATION NOT NULL,
	[ManagerUserID] [smallint] NOT NULL,
	[Mobile] [varchar](11) COLLATE Chinese_PRC_CI_AS NULL,
	[Msg] [nvarchar](160) COLLATE Chinese_PRC_CI_AS NULL,
	[IsShowBj] [tinyint] NOT NULL,
	[IsShowSh] [tinyint] NOT NULL,
	[IsShowSd] [tinyint] NOT NULL,
	[AddDate] [datetime] NULL,
 CONSTRAINT [PK_nhSms] PRIMARY KEY CLUSTERED 
(
	[ID] 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].[NoRecommend]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[NoRecommend](
	[cpMainId] [int] NULL,
	[AddDate] [smalldatetime] NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[NoShowOldJob]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[NoShowOldJob](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[cpMainId] [int] NULL,
	[AddDate] [datetime] NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[NV]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[NV](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[Name] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
 CONSTRAINT [PK_NV] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers]
) ON [BOthers]

GO
/****** Object:  Table [dbo].[NVDocument]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[NVDocument](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[Title] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[DescrIption] [nvarchar](1000) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[AddDate] [smalldatetime] NOT NULL,
	[Type] [smallint] NOT NULL,
	[ManagerUserId] [int] NOT NULL,
	[Attachment] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[Privi] [varchar](500) COLLATE Chinese_PRC_CI_AS NULL,
	[NVId] [int] NULL,
	[Coding] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
 CONSTRAINT [PK_NVDocument] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers]
) ON [BOthers]

GO
/****** Object:  Table [dbo].[oa_addRess]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[oa_addRess](
	[Id] [int] NOT NULL,
	[mobile] [varchar](13) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[email] [varchar](30) COLLATE Chinese_PRC_CI_AS NOT NULL,
 CONSTRAINT [PK_oa_addRess] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [OA]
) ON [OA]

GO
/****** Object:  Table [dbo].[oa_Contract]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[oa_Contract](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[UserId] [nchar](10) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[entryDate] [smalldatetime] NULL,
	[PositiveDate] [smalldatetime] NULL,
	[maturityDate] [smalldatetime] NULL,
	[period] [int] NULL,
	[AnnualDate] [smalldatetime] NULL,
	[editor] [int] NULL,
	[editDate] [smalldatetime] NULL,
	[notRemind1] [tinyint] NULL,
	[notRemind2] [tinyint] NULL,
	[notRemind3] [tinyint] NULL,
	[notRemind4] [tinyint] NULL,
	[notRemind5] [tinyint] NULL,
	[RemindDate1] [smalldatetime] NULL,
	[RemindDate2] [smalldatetime] NULL,
	[RemindDate3] [smalldatetime] NULL,
	[RemindDate4] [smalldatetime] NULL,
	[RemindDate5] [smalldatetime] NULL,
	[notRemind6] [int] NULL,
	[RemindDate6] [datetime] NULL,
 CONSTRAINT [PK_Contract] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [OA]
) ON [OA]

GO
/****** Object:  Table [dbo].[oa_flow]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[oa_flow](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[funId] [int] NOT NULL,
	[funName] [nchar](10) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Aspectname] [nchar](10) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[UserId] [int] NOT NULL,
	[arrivaltime] [smalldatetime] NOT NULL,
	[viewtime] [smalldatetime] NULL,
	[sendtime] [smalldatetime] NULL,
	[Agree] [tinyint] NOT NULL,
	[opinion] [nvarchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[worker] [int] NULL,
	[sender] [int] NULL,
	[DescrIption] [nvarchar](100) COLLATE Chinese_PRC_CI_AS NULL,
 CONSTRAINT [PK_oa_flow] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [OA]
) ON [OA]

GO
/****** Object:  Table [dbo].[office]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[office](
	[Id] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[officename] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Ip] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[lastDate] [smalldatetime] NULL,
 CONSTRAINT [PK_office] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers]
) ON [BOthers]

GO
/****** Object:  Table [dbo].[onlinepayResult]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[onlinepayResult](
	[v_oId] [varchar](64) COLLATE Chinese_PRC_CI_AS NULL,
	[v_pmode] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[v_pstatus] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[v_pstring] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[v_md5info] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL,
	[v_amount] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[v_moneyType] [varchar](5) COLLATE Chinese_PRC_CI_AS NULL,
	[v_md5money] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL,
	[addDate] [smalldatetime] NOT NULL
) ON [BOthers]

GO
/****** Object:  Index [IX_onlinepayResult_addDate]    Script Date: 2018/9/25 12:40:11 ******/
CREATE CLUSTERED INDEX [IX_onlinepayResult_addDate] ON [dbo].[onlinepayResult]
(
	[addDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers]
GO
/****** Object:  Table [dbo].[OrderAnalysis]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[OrderAnalysis](
	[ID] [int] NOT NULL,
	[OrderId] [int] NOT NULL,
	[cpMainid] [int] NOT NULL,
	[ProvinceId] [int] NOT NULL,
	[paid] [numeric](18, 2) NOT NULL,
	[opendate] [smalldatetime] NULL,
	[begindate] [smalldatetime] NULL,
	[enddate] [smalldatetime] NULL,
	[Paid2] [numeric](18, 2) NULL,
	[OpenDate2] [smalldatetime] NULL,
	[BeginDate2] [smalldatetime] NULL,
	[EndDate2] [smalldatetime] NULL,
	[NextId] [int] NULL,
	[DiffDay] [int] NULL,
	[DiffMonth] [int] NULL,
	[Interval] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[IntervalRemark] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[CountDate] [varchar](10) COLLATE Chinese_PRC_CI_AS NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[OutLink]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[OutLink](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[OutUrl] [varchar](500) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[ManagerUserId] [smallint] NOT NULL,
	[AddDate] [smalldatetime] NOT NULL,
	[Site] [varchar](150) COLLATE Chinese_PRC_CI_AS NULL,
	[Yst_ClickNum] [int] NOT NULL,
	[Mth_ClickNum] [int] NOT NULL,
	[Status] [tinyint] NOT NULL,
	[CheckDate] [smalldatetime] NULL,
	[Remarks] [nvarchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[Keywords] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[Errornum] [smallint] NOT NULL,
	[Username] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[Password] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[OutLinkResources_Id] [int] NULL,
	[Ip] [varchar](17) COLLATE Chinese_PRC_CI_AS NULL,
	[Copy] [tinyint] NOT NULL,
 CONSTRAINT [PK_OutLink] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Market]
) ON [Market]

GO
/****** Object:  Table [dbo].[outlink_count]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[outlink_count](
	[outlinkId] [int] NOT NULL,
	[YearMonth] [int] NOT NULL,
	[power] [int] NOT NULL
) ON [Market]

GO
/****** Object:  Table [dbo].[OutlinkResources]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[OutlinkResources](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[Kind] [tinyint] NOT NULL,
	[Name] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[RegUrl] [varchar](500) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[AddMan] [int] NOT NULL,
	[AddDate] [smalldatetime] NOT NULL,
	[Remarks] [varchar](500) COLLATE Chinese_PRC_CI_AS NULL,
	[Status] [tinyint] NOT NULL,
	[LoginUrl] [varchar](500) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[GroupId] [smallint] NULL,
	[Example] [varchar](500) COLLATE Chinese_PRC_CI_AS NULL,
	[SecretQuestion] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[SecretAnswer] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
 CONSTRAINT [PK_OutlinkResources] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Market]
) ON [Market]

GO
/****** Object:  Table [dbo].[OverTime]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[OverTime](
	[ManagerUserid] [smallint] NULL,
	[WordDate] [varchar](8) COLLATE Chinese_PRC_CI_AS NULL,
	[LoginCountAfter1755] [smallint] NULL,
	[LoginCountBefore1755] [smallint] NULL,
	[RTXonlineAfter1755] [smallint] NULL,
	[RTXonlineBeforer1755] [smallint] NULL,
	[AttendanceCheckOut] [datetime] NULL,
	[WorkType] [tinyint] NULL,
	[AttendanceCheckIn] [datetime] NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[overtime_old]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[overtime_old](
	[ManagerUserid] [smallint] NULL,
	[WordDate] [varchar](8) COLLATE Chinese_PRC_CI_AS NULL,
	[LoginCountAfter1755] [smallint] NULL,
	[LoginCountBefore1755] [smallint] NULL,
	[RTXonlineAfter1755] [smallint] NULL,
	[RTXonlineBeforer1755] [smallint] NULL,
	[AttendanceCheckOut] [datetime] NULL,
	[WorkType] [tinyint] NULL,
	[AttendanceCheckIn] [datetime] NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[overtime2016]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[overtime2016](
	[ManagerUserid] [smallint] NULL,
	[WordDate] [varchar](8) COLLATE Chinese_PRC_CI_AS NULL,
	[LoginCountAfter1755] [smallint] NULL,
	[LoginCountBefore1755] [smallint] NULL,
	[RTXonlineAfter1755] [smallint] NULL,
	[RTXonlineBeforer1755] [smallint] NULL,
	[AttendanceCheckOut] [datetime] NULL,
	[WorkType] [tinyint] NULL,
	[AttendanceCheckIn] [datetime] NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[overtime2017]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[overtime2017](
	[ManagerUserid] [smallint] NULL,
	[WordDate] [varchar](8) COLLATE Chinese_PRC_CI_AS NULL,
	[LoginCountAfter1755] [smallint] NULL,
	[LoginCountBefore1755] [smallint] NULL,
	[RTXonlineAfter1755] [smallint] NULL,
	[RTXonlineBeforer1755] [smallint] NULL,
	[AttendanceCheckOut] [datetime] NULL,
	[WorkType] [tinyint] NULL,
	[AttendanceCheckIn] [datetime] NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[OvertimeDept]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[OvertimeDept](
	[deptid] [int] NULL,
	[deptname] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[yearmonth] [varchar](6) COLLATE Chinese_PRC_CI_AS NULL,
	[checkIn] [int] NULL,
	[checkOut] [int] NULL,
	[logindaysAfter18] [numeric](18, 2) NULL,
	[logindaysWeekend] [numeric](18, 2) NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[OvertimeDept_old]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[OvertimeDept_old](
	[deptid] [int] NULL,
	[deptname] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[yearmonth] [varchar](6) COLLATE Chinese_PRC_CI_AS NULL,
	[checkIn] [int] NULL,
	[checkOut] [int] NULL,
	[logindaysAfter18] [numeric](18, 2) NULL,
	[logindaysWeekend] [numeric](18, 2) NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[OvertimeDept2016]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[OvertimeDept2016](
	[deptid] [int] NULL,
	[deptname] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[yearmonth] [varchar](6) COLLATE Chinese_PRC_CI_AS NULL,
	[checkIn] [int] NULL,
	[checkOut] [int] NULL,
	[logindaysAfter18] [numeric](18, 2) NULL,
	[logindaysWeekend] [numeric](18, 2) NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[OvertimeDept2017]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[OvertimeDept2017](
	[deptid] [int] NULL,
	[deptname] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[yearmonth] [varchar](6) COLLATE Chinese_PRC_CI_AS NULL,
	[checkIn] [int] NULL,
	[checkOut] [int] NULL,
	[logindaysAfter18] [numeric](18, 2) NULL,
	[logindaysWeekend] [numeric](18, 2) NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[PaAttention]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[PaAttention](
	[ID] [int] IDENTITY(1,1) NOT FOR REPLICATION NOT NULL,
	[PaMainID] [int] NOT NULL,
	[AttentionType] [tinyint] NOT NULL,
	[AttentionID] [int] NOT NULL,
	[AddDate] [smalldatetime] NOT NULL,
	[ViewDate] [smalldatetime] NULL,
 CONSTRAINT [PK_PaAttention] PRIMARY KEY NONCLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [CP]

GO
/****** Object:  Table [dbo].[paContact]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[paContact](
	[paMainId] [int] NULL,
	[ContactMan] [smallint] NULL,
	[ContactDate] [smalldatetime] NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[paCoverLetter]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[paCoverLetter](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[paMainID] [int] NOT NULL,
	[IsDefault] [bit] NOT NULL,
	[Title] [nvarchar](20) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[MainText] [varchar](max) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[AddDate] [smalldatetime] NOT NULL,
 CONSTRAINT [PK_paCoverLetter] PRIMARY KEY NONCLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [CV]
) ON [CV] TEXTIMAGE_ON [CV]

GO
/****** Object:  Index [IX_paCoverLetter_paMainID]    Script Date: 2018/9/25 12:40:11 ******/
CREATE CLUSTERED INDEX [IX_paCoverLetter_paMainID] ON [dbo].[paCoverLetter]
(
	[paMainID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [CV]
GO
/****** Object:  Table [dbo].[paCvAlipayRelation]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[paCvAlipayRelation](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[cvMainID] [int] NOT NULL,
	[alipayResumeID] [varchar](30) COLLATE Chinese_PRC_CI_AS NULL,
	[AddDate] [smalldatetime] NOT NULL,
 CONSTRAINT [PK_paCvAlipayRelation] PRIMARY KEY CLUSTERED 
(
	[id] 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].[paCvImportLog]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[paCvImportLog](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[cvMainID] [int] NULL,
	[cvFrom] [nvarchar](20) COLLATE Chinese_PRC_CI_AS NULL,
	[isSuccess] [bit] NULL,
	[Adddate] [datetime] NULL,
 CONSTRAINT [PK_paCvImportLog] PRIMARY KEY CLUSTERED 
(
	[id] 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].[paFavorate]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[paFavorate](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[paMainID] [int] NOT NULL,
	[JobID] [int] NOT NULL,
	[AddDate] [smalldatetime] NOT NULL,
	[Remark] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL,
 CONSTRAINT [PK_paFavorate] PRIMARY KEY NONCLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [CV]
) ON [CV]

GO
/****** Object:  Index [IX_paFavorate_paMainID]    Script Date: 2018/9/25 12:40:11 ******/
CREATE CLUSTERED INDEX [IX_paFavorate_paMainID] ON [dbo].[paFavorate]
(
	[paMainID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [CV]
GO
/****** Object:  Table [dbo].[paFeedback]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[paFeedback](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[paMainID] [int] NOT NULL,
	[dcProvinceID] [tinyint] NOT NULL,
	[IP] [varchar](39) COLLATE Chinese_PRC_CI_AS NULL,
	[Name] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Telephone] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[Email] [varchar](100) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Message] [nvarchar](2000) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[AddDate] [smalldatetime] NOT NULL,
	[IsReply] [bit] NOT NULL,
	[ReplyMessage] [nvarchar](2000) COLLATE Chinese_PRC_CI_AS NULL,
	[ReplyDate] [smalldatetime] NULL,
	[ReplyMan] [smallint] NULL,
	[ViewDate] [smalldatetime] NULL,
	[JobId] [int] NULL,
 CONSTRAINT [PK_paFeedback] PRIMARY KEY NONCLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [CV]
) ON [CV]

GO
/****** Object:  Index [IX_paFeedback_paMainID]    Script Date: 2018/9/25 12:40:11 ******/
CREATE CLUSTERED INDEX [IX_paFeedback_paMainID] ON [dbo].[paFeedback]
(
	[paMainID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [CV]
GO
/****** Object:  Table [dbo].[paGetPasswordLog]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[paGetPasswordLog](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[paMainID] [int] NOT NULL,
	[UserNameIn] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[EmailIn] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[VerifyCode] [char](4) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[IP] [varchar](39) COLLATE Chinese_PRC_CI_AS NULL,
	[UserName] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Email] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[AddDate] [smalldatetime] NOT NULL,
	[Mobile] [varchar](11) COLLATE Chinese_PRC_CI_AS NULL,
	[UniqueId] [varchar](40) COLLATE Chinese_PRC_CI_AS NULL,
	[ActivateCode] [varchar](6) COLLATE Chinese_PRC_CI_AS NULL,
	[AskNo] [varchar](40) COLLATE Chinese_PRC_CI_AS NULL,
	[IsReset] [bit] NULL,
 CONSTRAINT [PK_paGetPasswordLog] PRIMARY KEY NONCLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [CV]
) ON [CV]

GO
/****** Object:  Index [IX_paGetPasswordLog_paMainID]    Script Date: 2018/9/25 12:40:11 ******/
CREATE CLUSTERED INDEX [IX_paGetPasswordLog_paMainID] ON [dbo].[paGetPasswordLog]
(
	[paMainID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [CV]
GO
/****** Object:  Table [dbo].[paInfoEmailVerifyLog]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[paInfoEmailVerifyLog](
	[paMainID] [int] NOT NULL,
	[Email] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[AddMan] [smallint] NOT NULL,
	[CountDate] [varchar](8) COLLATE Chinese_PRC_CI_AS NOT NULL,
 CONSTRAINT [PK_paInfoEmailVerifyLog] PRIMARY KEY CLUSTERED 
(
	[paMainID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [CV]
) ON [CV]

GO
/****** Object:  Table [dbo].[PaIosBind]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[PaIosBind](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[PaMainID] [int] NOT NULL,
	[UniqueID] [varchar](100) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Adddate] [smalldatetime] NOT NULL,
	[ClientType] [tinyint] NULL,
 CONSTRAINT [PK_PaIosBind] PRIMARY KEY CLUSTERED 
(
	[id] 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].[paJobClickCount]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[paJobClickCount](
	[Ip] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[Cnt] [int] NULL,
	[IsSpider] [bit] NULL,
	[CanView] [bit] NULL,
	[AddDate] [smalldatetime] NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[paJobClickLog]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[paJobClickLog](
	[JobID] [int] NOT NULL,
	[paMainID] [int] NULL,
	[IP] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[AddDate] [datetime] NULL
) ON [CV]

GO
/****** Object:  Table [dbo].[paJobCompare]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[paJobCompare](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[BatchNo] [smallint] NOT NULL,
	[LastRecommenedNo] [tinyint] NOT NULL,
	[PaMainID] [int] NOT NULL,
	[CompareJobID] [int] NOT NULL,
	[ApplyDate] [datetime] NULL,
	[PushDate] [datetime] NULL,
	[AddDate] [datetime] NOT NULL,
	[Source] [varchar](15) COLLATE Chinese_PRC_CI_AS NULL,
 CONSTRAINT [PK_paJobCompare] PRIMARY KEY NONCLUSTERED 
(
	[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [CV]

GO
/****** Object:  Index [IX_paJobCompare_paMainId]    Script Date: 2018/9/25 12:40:11 ******/
CREATE CLUSTERED INDEX [IX_paJobCompare_paMainId] ON [dbo].[paJobCompare]
(
	[PaMainID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [CV]
GO
/****** Object:  Table [dbo].[paJobCompareIndex]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[paJobCompareIndex](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[paMainId] [int] NULL,
	[RunDate] [datetime] NULL,
	[RunStatus] [tinyint] NOT NULL,
	[ADDdATE] [datetime] NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[paJobFinder]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[paJobFinder](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[paMainID] [int] NOT NULL,
	[Name] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[dcJobTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[dcIndustryID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[dcRegionID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[KeyType] [tinyint] NULL,
	[KeyWord] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[Education] [tinyint] NULL,
	[EmployType] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[MinExperience] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[Salary] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[AddDate] [smalldatetime] NOT NULL,
	[EmailSent] [smallint] NOT NULL,
	[EmailEndDate] [smalldatetime] NULL,
	[LastEmailDate] [smalldatetime] NULL,
	[EmailNumber] [tinyint] NULL,
	[Email] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[IsNegotiable] [bit] NULL,
	[dcCompanySizeID] [tinyint] NULL,
 CONSTRAINT [PK_paJobFinder] PRIMARY KEY NONCLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [CV]
) ON [CV]

GO
/****** Object:  Index [IX_paJobFinder_paMainID]    Script Date: 2018/9/25 12:40:11 ******/
CREATE CLUSTERED INDEX [IX_paJobFinder_paMainID] ON [dbo].[paJobFinder]
(
	[paMainID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [CV]
GO
/****** Object:  Table [dbo].[paJobPlanFeedBack]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[paJobPlanFeedBack](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[Name] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Mobile] [varchar](15) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[OnlineContactNo] [varchar](20) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Message] [varchar](1000) COLLATE Chinese_PRC_CI_AS NULL,
	[AddDate] [smalldatetime] NULL,
	[ReplyDate] [smalldatetime] NULL,
	[ReplyMan] [int] NULL,
 CONSTRAINT [PK_paJobPlanFeedback] PRIMARY KEY CLUSTERED 
(
	[ID] 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].[paJobViewLog]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[paJobViewLog](
	[JobID] [int] NOT NULL,
	[paMainID] [int] NOT NULL,
	[AddDate] [smalldatetime] NOT NULL,
 CONSTRAINT [PK_paJobViewLog] PRIMARY KEY CLUSTERED 
(
	[paMainID] ASC,
	[JobID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [CV]
) ON [CV]

GO
/****** Object:  Table [dbo].[paLoginContact]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[paLoginContact](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[paMainID] [int] NOT NULL,
	[Openid] [varchar](100) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[ContactType] [tinyint] NOT NULL,
	[LoginType] [tinyint] NOT NULL,
	[AddDate] [smalldatetime] NOT NULL,
 CONSTRAINT [PK_paLoginContact] PRIMARY KEY CLUSTERED 
(
	[ID] 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].[paLoginLogDel]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[paLoginLogDel](
	[ID] [int] NOT NULL,
	[paMainID] [int] NOT NULL,
	[LoginIP] [varchar](39) COLLATE Chinese_PRC_CI_AS NULL,
	[AddDate] [smalldatetime] NOT NULL,
	[Browser] [varchar](500) COLLATE Chinese_PRC_CI_AS NULL,
	[LoginFrom] [tinyint] NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[pamain0720]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[pamain0720](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[registerfrom] [tinyint] NULL,
	[registertype] [tinyint] NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[pamain0722]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[pamain0722](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[UserName] [varchar](50) COLLATE Chinese_PRC_CS_AS NOT NULL,
	[UserNameLower] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[Password] [varchar](60) COLLATE Chinese_PRC_CI_AS NULL,
	[IsDefaultPassword] [bit] NOT NULL,
	[dcProvinceID] [tinyint] NOT NULL,
	[RegisterIP] [varchar](31) COLLATE Chinese_PRC_CI_AS NULL,
	[RegisterMode] [tinyint] NOT NULL,
	[AddMan] [smallint] NULL,
	[Name] [nvarchar](6) COLLATE Chinese_PRC_CI_AS NULL,
	[NameEng] [varchar](30) COLLATE Chinese_PRC_CI_AS NULL,
	[Email] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Gender] [bit] NULL,
	[BirthDay] [int] NULL,
	[LivePlace] [varchar](6) COLLATE Chinese_PRC_CI_AS NULL,
	[AccountPlace] [varchar](6) COLLATE Chinese_PRC_CI_AS NULL,
	[GrowPlace] [varchar](6) COLLATE Chinese_PRC_CI_AS NULL,
	[Mobile] [varchar](13) COLLATE Chinese_PRC_CI_AS NULL,
	[OnlineContact] [tinyint] NULL,
	[OnlineContactNo] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[Homepage] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL,
	[Marriage] [tinyint] NULL,
	[Nation] [tinyint] NULL,
	[Height] [tinyint] NULL,
	[dcCareerStatus] [tinyint] NULL,
	[HasPhoto] [tinyint] NULL,
	[HideConditions] [nvarchar](500) COLLATE Chinese_PRC_CI_AS NULL,
	[BlockCount] [int] NOT NULL,
	[VerifyCount] [int] NOT NULL,
	[LastLoginDate] [datetime] NULL,
	[TotalLoginNum] [int] NOT NULL,
	[LastModifyDate] [smalldatetime] NULL,
	[AddDate] [smalldatetime] NOT NULL,
	[dcSubSiteID] [smallint] NULL,
	[MobileRegion] [varchar](6) COLLATE Chinese_PRC_CI_AS NULL,
	[IsReceiveSms] [bit] NULL,
	[PerfectDate] [smalldatetime] NULL,
	[PlainPassword] [varchar](40) COLLATE Chinese_PRC_CI_AS NULL,
	[MobileVerifyDate] [smalldatetime] NULL,
	[EmailVerifyDate] [smalldatetime] NULL,
	[RegisterFrom] [tinyint] NULL,
	[SpreadDate] [smalldatetime] NULL,
	[RegisterType] [tinyint] NULL,
	[IsAppNotice] [bit] NULL,
	[IsEmailNotice] [bit] NULL,
	[IsWeixinNotice] [bit] NULL,
	[IsAppJobFinder] [bit] NULL,
	[IsEmailJobFinder] [bit] NULL,
	[IsWeiXinJobFinder] [bit] NULL,
	[IsUseYourFood] [bit] NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[PaMainDateReport]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[PaMainDateReport](
	[paMainId] [int] NULL,
	[ActType] [int] NULL,
	[AddDate] [datetime] NULL
) ON [Market]

GO
/****** Object:  Index [IX_paMainDateReport_paMainId]    Script Date: 2018/9/25 12:40:11 ******/
CREATE CLUSTERED INDEX [IX_paMainDateReport_paMainId] ON [dbo].[PaMainDateReport]
(
	[paMainId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Market]
GO
/****** Object:  Table [dbo].[paMainDel]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[paMainDel](
	[ID] [int] NOT NULL,
	[UserName] [varchar](50) COLLATE Chinese_PRC_CS_AS NOT NULL,
	[UserNameLower] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[Password] [varchar](60) COLLATE Chinese_PRC_CI_AS NULL,
	[IsDefaultPassword] [bit] NOT NULL,
	[dcProvinceID] [tinyint] NOT NULL,
	[RegisterIP] [varchar](31) COLLATE Chinese_PRC_CI_AS NULL,
	[RegisterMode] [tinyint] NOT NULL,
	[AddMan] [smallint] NULL,
	[Name] [nvarchar](6) COLLATE Chinese_PRC_CI_AS NULL,
	[NameEng] [varchar](30) COLLATE Chinese_PRC_CI_AS NULL,
	[Email] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Gender] [bit] NULL,
	[BirthDay] [int] NULL,
	[LivePlace] [varchar](6) COLLATE Chinese_PRC_CI_AS NULL,
	[AccountPlace] [varchar](6) COLLATE Chinese_PRC_CI_AS NULL,
	[GrowPlace] [varchar](6) COLLATE Chinese_PRC_CI_AS NULL,
	[Mobile] [varchar](13) COLLATE Chinese_PRC_CI_AS NULL,
	[OnlineContact] [tinyint] NULL,
	[OnlineContactNo] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[Homepage] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL,
	[Marriage] [tinyint] NULL,
	[Nation] [tinyint] NULL,
	[Height] [tinyint] NULL,
	[dcCareerStatus] [tinyint] NULL,
	[HasPhoto] [tinyint] NULL,
	[HideConditions] [nvarchar](500) COLLATE Chinese_PRC_CI_AS NULL,
	[BlockCount] [int] NOT NULL,
	[VerifyCount] [int] NOT NULL,
	[LastLoginDate] [datetime] NULL,
	[TotalLoginNum] [int] NOT NULL,
	[LastModifyDate] [smalldatetime] NULL,
	[AddDate] [smalldatetime] NOT NULL,
	[dcSubSiteID] [smallint] NULL,
	[MobileRegion] [varchar](6) COLLATE Chinese_PRC_CI_AS NULL,
	[IsReceiveSms] [bit] NULL,
	[PerfectDate] [smalldatetime] NULL,
	[PlainPassword] [varchar](40) COLLATE Chinese_PRC_CI_AS NULL,
	[MobileVerifyDate] [smalldatetime] NULL,
	[EmailVerifyDate] [smalldatetime] NULL,
	[RegisterFrom] [tinyint] NULL,
	[SpreadDate] [smalldatetime] NULL,
	[RegisterType] [tinyint] NULL,
	[IsAppNotice] [bit] NULL,
	[IsEmailNotice] [bit] NULL,
	[IsWeixinNotice] [bit] NULL,
	[IsAppJobFinder] [bit] NULL,
	[IsEmailJobFinder] [bit] NULL,
	[IsWeiXinJobFinder] [bit] NULL,
	[IsUseYourFood] [bit] NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[PaMainDeleted]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[PaMainDeleted](
	[id] [int] NOT NULL,
	[UsernameLower] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[Password] [varchar](60) COLLATE Chinese_PRC_CI_AS NULL,
	[AddDate] [smalldatetime] NOT NULL,
	[Mobile] [varchar](13) COLLATE Chinese_PRC_CI_AS NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[paMainPublish]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[paMainPublish](
	[ID] [int] NOT NULL,
	[Gender] [bit] NULL,
	[BirthDay] [int] NULL,
	[LivePlace] [varchar](6) COLLATE Chinese_PRC_CI_AS NULL,
	[AccountPlace] [varchar](6) COLLATE Chinese_PRC_CI_AS NULL,
	[GrowPlace] [varchar](6) COLLATE Chinese_PRC_CI_AS NULL,
	[Height] [tinyint] NULL,
	[HasPhoto] [tinyint] NULL,
	[LastLoginDate] [datetime] NULL,
	[LastModifyDate] [smalldatetime] NULL,
	[MobileRegion] [varchar](6) COLLATE Chinese_PRC_CI_AS NULL,
 CONSTRAINT [PK_paMainPublishPublsh] PRIMARY KEY NONCLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [CV]
) ON [CV]

GO
/****** Object:  Table [dbo].[paMainTemp]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[paMainTemp](
	[id] [int] NOT NULL,
	[UsernameLower] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[Password] [varchar](60) COLLATE Chinese_PRC_CI_AS NULL,
	[AddDate] [smalldatetime] NOT NULL,
 CONSTRAINT [PK_paMainTemp] PRIMARY KEY CLUSTERED 
(
	[id] 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].[paMobileFollowUp]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[paMobileFollowUp](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[Mobile] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[SessionId] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[PaMainId] [int] NULL,
	[ContactDate] [smalldatetime] NULL,
	[ContactMan] [int] NULL,
	[AddDate] [smalldatetime] NULL,
PRIMARY KEY CLUSTERED 
(
	[ID] 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].[paNotify]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[paNotify](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[paMainID] [int] NOT NULL,
	[Message] [nvarchar](300) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[NotifyType] [tinyint] NOT NULL,
	[EndDate] [smalldatetime] NULL,
	[IsViewed] [bit] NOT NULL,
	[ManagerUserID] [smallint] NULL,
	[AddDate] [smalldatetime] NOT NULL,
 CONSTRAINT [PK_paNotify] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [CV]
) ON [CV]

GO
/****** Object:  Table [dbo].[PaOnline]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[PaOnline](
	[paMainID] [int] NOT NULL,
	[IsOnline] [bit] NOT NULL,
	[RefreshDate] [datetime] NOT NULL,
 CONSTRAINT [PK_PaOnline] PRIMARY KEY CLUSTERED 
(
	[paMainID] 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].[paOperationLog]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[paOperationLog](
	[ID] [bigint] IDENTITY(1,1) NOT NULL,
	[paMainID] [int] NOT NULL,
	[Operation] [tinyint] NOT NULL,
	[Details] [nvarchar](100) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[IP] [varchar](39) COLLATE Chinese_PRC_CI_AS NULL,
	[AddDate] [smalldatetime] NOT NULL,
 CONSTRAINT [PK_paOperationLog] PRIMARY KEY NONCLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [CV]
) ON [CV]

GO
/****** Object:  Index [IX_paOperationLog_paMainID]    Script Date: 2018/9/25 12:40:11 ******/
CREATE CLUSTERED INDEX [IX_paOperationLog_paMainID] ON [dbo].[paOperationLog]
(
	[paMainID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [CV]
GO
/****** Object:  Table [dbo].[paPageViewLog]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[paPageViewLog](
	[paMainId] [int] NOT NULL,
	[InterviewDate] [datetime] NULL,
	[IntentionDate] [datetime] NULL,
	[ViewLogDate] [datetime] NULL,
	[AttentionDate] [datetime] NULL,
	[YourFoodDate] [datetime] NULL,
	[ApplyReplyDate] [datetime] NULL,
	[AddDate] [datetime] NULL,
	[MyAttentionCount] [int] NULL,
	[CvViewLogCount] [int] NULL,
	[YourFoodCount] [int] NULL,
	[JobAppliedCount] [int] NULL,
	[InterviewCount] [int] NULL,
	[CpInvitationCount] [int] NULL,
	[ChatCount] [int] NULL,
 CONSTRAINT [PK_paPageViewLog] PRIMARY KEY CLUSTERED 
(
	[paMainId] 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].[paPhoto]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[paPhoto](
	[paMainID] [int] NOT NULL,
	[PhotoProcessed] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[AddDate] [smalldatetime] NOT NULL,
	[CheckMan] [smallint] NULL,
	[CheckDate] [smalldatetime] NULL,
	[CheckMessage] [nvarchar](500) COLLATE Chinese_PRC_CI_AS NULL,
	[Photo] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[OneKeyBlock] [bit] NULL,
 CONSTRAINT [PK_paPhoto] PRIMARY KEY CLUSTERED 
(
	[paMainID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [CV]
) ON [CV]

GO
/****** Object:  Table [dbo].[paPhoto_before]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[paPhoto_before](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[paMainID] [int] NOT NULL,
	[fileUrl] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[AddDate] [smalldatetime] NOT NULL,
 CONSTRAINT [PK_paPhoto_before] PRIMARY KEY CLUSTERED 
(
	[id] 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].[paPlaint]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[paPlaint](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[paMainID] [int] NOT NULL,
	[caMainID] [int] NOT NULL,
	[JobID] [int] NULL,
	[Plaint] [varchar](1000) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[AddDate] [smalldatetime] NOT NULL,
	[ReplyType] [tinyint] NOT NULL,
	[ReplyMan] [smallint] NULL,
	[IsViewed] [bit] NOT NULL,
	[ProcessMessage] [varchar](500) COLLATE Chinese_PRC_CI_AS NULL,
	[ProcessDate] [smalldatetime] NULL,
	[Name] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[Telephone] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[Email] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[IP] [varchar](39) COLLATE Chinese_PRC_CI_AS NULL,
 CONSTRAINT [PK_paPlaint] PRIMARY KEY NONCLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [CV]
) ON [CV]

GO
/****** Object:  Index [IX_paPlaint_paMainID]    Script Date: 2018/9/25 12:40:11 ******/
CREATE CLUSTERED INDEX [IX_paPlaint_paMainID] ON [dbo].[paPlaint]
(
	[paMainID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [CV]
GO
/****** Object:  Table [dbo].[paPushLog]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[paPushLog](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[paMainID] [int] NOT NULL,
	[PushMessage] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[PushType] [tinyint] NOT NULL,
	[DetailID] [int] NULL,
	[iOSPushDate] [smalldatetime] NULL,
	[AnroidPushDate] [smalldatetime] NULL,
	[AddDate] [smalldatetime] NOT NULL,
	[PushDate] [smalldatetime] NULL,
 CONSTRAINT [PK_paPushLog] PRIMARY KEY CLUSTERED 
(
	[ID] 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].[paReferer]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[paReferer](
	[PaMainId] [int] NOT NULL,
	[Referer] [varchar](500) COLLATE Chinese_PRC_CI_AS NULL,
	[AddDate] [datetime] NULL,
 CONSTRAINT [PK_paReferer_1] PRIMARY KEY CLUSTERED 
(
	[PaMainId] 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].[PaRemindLog]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[PaRemindLog](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[PaMainID] [int] NULL,
	[ContentText] [nvarchar](100) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[RemindDate] [smalldatetime] NULL,
	[RemindStatus] [tinyint] NOT NULL,
	[AddDate] [smalldatetime] NOT NULL,
	[RemainID] [int] NULL,
	[RemainType] [tinyint] NOT NULL,
	[IosRemindDate] [smalldatetime] NULL,
	[AndroidRemindDate] [smalldatetime] NULL,
	[WxRemindDate] [smalldatetime] NULL,
 CONSTRAINT [PK_PaRemindLog] PRIMARY KEY CLUSTERED 
(
	[id] 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].[paSearchKeyword]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[paSearchKeyword](
	[id] [int] NOT NULL,
	[keyword] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[AddDate] [smalldatetime] NOT NULL,
	[HasSubmit] [tinyint] NULL,
 CONSTRAINT [PK_paSearchKeyword] PRIMARY KEY CLUSTERED 
(
	[keyword] 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].[paTagsMain]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[paTagsMain](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[Tag] [nvarchar](30) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[dcJobTypeID] [smallint] NOT NULL,
	[TagType] [smallint] NOT NULL,
	[UseCount] [int] NOT NULL,
	[VerifyDate] [smalldatetime] NULL,
	[AddDate] [smalldatetime] NULL,
 CONSTRAINT [PK_paTagsMain] PRIMARY KEY CLUSTERED 
(
	[id] 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].[paYourFood]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[paYourFood](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[paMainId] [int] NOT NULL,
	[cvMainId] [int] NOT NULL,
	[JobId] [int] NOT NULL,
	[AddDate] [smalldatetime] NULL
) ON [CV]

GO
/****** Object:  Index [IX_paYourFood_INDEX]    Script Date: 2018/9/25 12:40:11 ******/
CREATE CLUSTERED INDEX [IX_paYourFood_INDEX] ON [dbo].[paYourFood]
(
	[paMainId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [CV]
GO
/****** Object:  Table [dbo].[paYourFoodIndex]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[paYourFoodIndex](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[paMainId] [int] NULL,
	[cvMainId] [int] NULL,
	[LastLoginDate] [datetime] NULL,
	[Age] [int] NULL,
	[dcSalaryID] [int] NULL,
	[EmployType] [int] NULL,
	[Degree] [int] NULL,
	[RelatedWorkYears] [int] NULL,
	[HasRun] [bit] NULL,
	[AddDate] [smalldatetime] NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[paYourFoodWeiXin]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[paYourFoodWeiXin](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[paMainId] [int] NULL,
	[cvMainId] [int] NULL,
	[cpMainId] [int] NULL,
	[caMainId] [int] NULL,
	[JobDesc] [nvarchar](500) COLLATE Chinese_PRC_CI_AS NULL,
	[HasSend] [bit] NULL,
	[AddDate] [datetime] NULL,
	[BatchNo] [smallint] NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[Person_Black]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Person_Black](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[ManagerID] [smallint] NOT NULL,
	[AddedDate] [smalldatetime] NOT NULL,
	[Email] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[RefuseCount] [int] NOT NULL,
	[Reason] [nvarchar](500) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Mobile] [varchar](11) COLLATE Chinese_PRC_CI_AS NULL,
 CONSTRAINT [PK_Person_Black] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [CV]
) ON [CV]

GO
/****** Object:  Table [dbo].[person_black_bak]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[person_black_bak](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[ManagerID] [smallint] NOT NULL,
	[AddedDate] [smalldatetime] NOT NULL,
	[Email] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[RefuseCount] [int] NOT NULL,
	[Reason] [nvarchar](500) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Mobile] [varchar](11) COLLATE Chinese_PRC_CI_AS NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[picture]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[picture](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[Attachment] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Type] [smallint] NOT NULL,
	[AddDate] [smalldatetime] NOT NULL,
	[ManagerUserId] [smallint] NOT NULL,
	[Title] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
 CONSTRAINT [PK_picture] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers]
) ON [BOthers]

GO
/****** Object:  Table [dbo].[post2yahoo]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[post2yahoo](
	[Id] [int] NOT NULL,
	[yahooId] [int] NULL
) ON [BOthers]

GO
/****** Object:  Table [dbo].[Pr_Alex]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Pr_Alex](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[Province_Id] [tinyint] NOT NULL,
	[YearMonthDay] [int] NOT NULL,
	[Pr] [smallint] NOT NULL,
	[Alex] [int] NOT NULL,
	[Baidu] [int] NOT NULL,
	[Google] [int] NOT NULL,
	[Sogou] [int] NOT NULL,
	[AddDate] [smalldatetime] NOT NULL,
	[OutLink] [int] NOT NULL,
	[SitePos] [tinyint] NULL,
	[Soso] [int] NULL,
 CONSTRAINT [PK_pr_alex] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers]
) ON [BOthers]

GO
/****** Object:  Table [dbo].[PrecoldCustomer]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[PrecoldCustomer](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[SourceType] [int] NOT NULL,
	[State] [tinyint] NOT NULL,
	[CompanyName] [varchar](200) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[LinkMan] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[Phone] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[Email] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[SourceLink] [varchar](500) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Address] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL,
	[QQ] [char](15) COLLATE Chinese_PRC_CI_AS NULL,
	[AddDate] [datetime] NOT NULL,
	[ColdCustomerAllocateLogID] [int] NULL,
	[Tel] [varchar](13) COLLATE Chinese_PRC_CI_AS NULL,
	[IsSpread] [bit] NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[QlrcNews]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[QlrcNews](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[NewsType] [int] NOT NULL,
	[Title] [nvarchar](60) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Content] [varchar](max) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[AnnounceDate] [smalldatetime] NOT NULL,
	[Author] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[ViewNumber] [int] NOT NULL,
	[VersionId] [int] NOT NULL,
	[Type] [smallint] NOT NULL,
	[RefReshDate] [smalldatetime] NOT NULL,
	[ViewNumber_All] [int] NULL,
	[Label] [nvarchar](200) COLLATE Chinese_PRC_CI_AS NULL,
	[AddMan] [smallint] NULL,
	[DetailType] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[Appendix] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[AppendixName] [nvarchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[kindID] [int] NULL,
	[SmallImg] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
 CONSTRAINT [PK_QlrcNews] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Market]
) ON [Market] TEXTIMAGE_ON [Market]

GO
/****** Object:  Table [dbo].[QlrcNewsTop5]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[QlrcNewsTop5](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[NewsType] [int] NOT NULL,
	[Title] [nvarchar](60) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Content] [varchar](max) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[AnnounceDate] [smalldatetime] NOT NULL,
	[Author] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[ViewNumber] [int] NOT NULL,
	[VersionId] [int] NOT NULL,
	[Type] [smallint] NOT NULL,
	[RefReshDate] [smalldatetime] NOT NULL,
	[ViewNumber_All] [int] NULL,
	[Label] [nvarchar](200) COLLATE Chinese_PRC_CI_AS NULL,
	[AddMan] [smallint] NULL,
	[DetailType] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[Appendix] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[AppendixName] [nvarchar](100) COLLATE Chinese_PRC_CI_AS NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

GO
/****** Object:  Table [dbo].[qlrcNewsVersionidLog]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[qlrcNewsVersionidLog](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[versionid] [int] NOT NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[qryJobApplyMonth]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[qryJobApplyMonth](
	[cpMainID] [int] NOT NULL,
	[NotOpenNumber] [int] NULL,
	[AllNumber] [int] NULL,
 CONSTRAINT [PK_qryJobApplyMonth] PRIMARY KEY CLUSTERED 
(
	[cpMainID] 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].[Question]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Question](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[Title] [nvarchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[Type] [smallint] NOT NULL,
	[AnswerNum] [smallint] NULL,
	[Options] [nvarchar](1000) COLLATE Chinese_PRC_CI_AS NULL,
	[Prompt] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[Power] [smallint] NOT NULL,
	[InvestId] [int] NOT NULL,
 CONSTRAINT [PK_Question] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers]
) ON [BOthers]

GO
/****** Object:  Table [dbo].[QuotaLog]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[QuotaLog](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[QuotaType] [smallint] NOT NULL,
	[CaOrderId] [int] NOT NULL,
	[CaMainId] [int] NOT NULL,
	[Quota] [int] NULL,
	[RemainQuota] [int] NULL,
	[AddDate] [smalldatetime] NOT NULL,
	[cpMainId] [int] NOT NULL,
 CONSTRAINT [PK_QuotaLog] PRIMARY KEY CLUSTERED 
(
	[Id] 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].[Recruitment20130719]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Recruitment20130719](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[RecruitmentDeptId] [int] NOT NULL,
	[RecruitmentName] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Brief] [varchar](max) COLLATE Chinese_PRC_CI_AS NULL,
	[BeginDate] [smalldatetime] NOT NULL,
	[EndDate] [smalldatetime] NOT NULL,
	[CityID] [varchar](4) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[RecruitmentPlaceId] [int] NOT NULL,
	[LinkMan] [nvarchar](10) COLLATE Chinese_PRC_CI_AS NULL,
	[Mobile] [varchar](11) COLLATE Chinese_PRC_CI_AS NULL,
	[Telephone] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL,
	[Fax] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL,
	[Email] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[qq] [varchar](10) COLLATE Chinese_PRC_CI_AS NULL,
	[OrderBy] [int] NOT NULL,
	[IsPause] [tinyint] NOT NULL,
	[PauseReason] [nvarchar](200) COLLATE Chinese_PRC_CI_AS NULL,
	[IsSchool] [bit] NOT NULL,
	[ViewNumber] [int] NOT NULL,
	[CompanyViewNumber] [int] NOT NULL,
	[PersonViewNumber] [int] NOT NULL,
	[InnerOrderBy] [smallint] NULL,
	[IsCompanyTop] [bit] NOT NULL,
	[IsPersonalTop] [bit] NOT NULL,
	[ManagerUserID] [smallint] NULL,
	[ModifyDate] [smalldatetime] NOT NULL,
	[AddDate] [smalldatetime] NULL,
	[MainID] [int] NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

GO
/****** Object:  Table [dbo].[RecruitmentCpMain]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[RecruitmentCpMain](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[RecruitmentID] [int] NOT NULL,
	[cpMainId] [int] NOT NULL,
	[AddDate] [smalldatetime] NOT NULL,
 CONSTRAINT [PK_RecruitmentCpMain] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Market]
) ON [Market]

GO
/****** Object:  Table [dbo].[RecruitmentImage]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[RecruitmentImage](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[RecruitmentID] [int] NOT NULL,
	[FileUrl] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Title] [nvarchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[OrderNo] [smallint] NOT NULL,
	[AddDate] [smalldatetime] NOT NULL,
	[AddMan] [smallint] NOT NULL,
 CONSTRAINT [PK_RecruitmentImage] PRIMARY KEY CLUSTERED 
(
	[ID] 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].[RecruitmentPaMain]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[RecruitmentPaMain](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[RecruitmentID] [int] NOT NULL,
	[paMainId] [int] NOT NULL,
	[AddDate] [smalldatetime] NOT NULL,
 CONSTRAINT [PK_RecruitmentPaMain] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Market]
) ON [Market]

GO
/****** Object:  Table [dbo].[referer]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[referer](
	[Referer] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL,
	[VersionId] [int] NULL,
	[LoginDate] [smalldatetime] NOT NULL,
	[Ip] [varchar](15) COLLATE Chinese_PRC_CI_AS NULL,
	[Keywords] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[Province_Id] [smallint] NULL,
	[SessionId] [varchar](30) COLLATE Chinese_PRC_CI_AS NULL
) ON [Market]

GO
/****** Object:  Table [dbo].[referer_count]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[referer_count](
	[CountDate] [int] NOT NULL,
	[Province_Id] [smallint] NOT NULL,
	[HowMany] [int] NOT NULL,
	[Referer] [varchar](200) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Id] [int] IDENTITY(1,1) NOT NULL,
 CONSTRAINT [PK_referer_count] PRIMARY KEY NONCLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Market],
 CONSTRAINT [IX_referer_count_unique] UNIQUE CLUSTERED 
(
	[CountDate] ASC,
	[Province_Id] ASC,
	[Referer] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
) ON [Index]

GO
/****** Object:  Table [dbo].[Referer_Count_Keywords]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Referer_Count_Keywords](
	[Referer_Count_Id] [int] NOT NULL,
	[Keywords] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[HowMany] [smallint] NOT NULL
) ON [Market]

GO
/****** Object:  Table [dbo].[Referer_Item]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Referer_Item](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[Item_Name] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
 CONSTRAINT [PK_referer_item] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Market]
) ON [Market]

GO
/****** Object:  Table [dbo].[Referer_Item_Keywords]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Referer_Item_Keywords](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[Item_Id] [int] NOT NULL,
	[Keywords] [varchar](500) COLLATE Chinese_PRC_CI_AS NOT NULL,
 CONSTRAINT [PK_referer_item_keywords] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Market]
) ON [Market]

GO
/****** Object:  Table [dbo].[Referer_YearMonth]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Referer_YearMonth](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[YearMonth] [int] NOT NULL,
	[Item_Name] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Province_Id] [smallint] NULL,
	[HowMany] [int] NOT NULL,
 CONSTRAINT [PK_referer_YearMonth] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Market]
) ON [Market]

GO
/****** Object:  Table [dbo].[Referer_YearMonth20140902]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Referer_YearMonth20140902](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[YearMonth] [int] NOT NULL,
	[Item_Name] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Province_Id] [smallint] NULL,
	[HowMany] [int] NOT NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[Referer2]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Referer2](
	[Referer] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL,
	[VersionId] [int] NULL,
	[LoginDate] [smalldatetime] NOT NULL,
	[Ip] [varchar](15) COLLATE Chinese_PRC_CI_AS NULL,
	[Keywords] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[Province_Id] [smallint] NULL,
	[SessionId] [varchar](30) COLLATE Chinese_PRC_CI_AS NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[RefuseIp]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[RefuseIp](
	[Ip] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[VisitNumber] [int] NULL,
	[ReleaseTime] [smalldatetime] NULL,
	[AddDate] [datetime] NULL,
	[IsForever] [bit] NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[Resume_analysis]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Resume_analysis](
	[Resume_num] [int] NULL,
	[addDate] [smalldatetime] NULL
) ON [FOthers]

GO
/****** Object:  Table [dbo].[Resume_analysis_1]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Resume_analysis_1](
	[Id] [char](4) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Description] [nchar](25) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Resume_num] [int] NOT NULL
) ON [FOthers]

GO
/****** Object:  Table [dbo].[Resume_analysis_2]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Resume_analysis_2](
	[Id] [int] NOT NULL,
	[edulevel] [nvarchar](10) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Resume_num] [int] NOT NULL
) ON [FOthers]

GO
/****** Object:  Table [dbo].[Resume_analysis_3]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Resume_analysis_3](
	[Id] [int] NOT NULL,
	[agelevel] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Resume_num] [int] NOT NULL
) ON [FOthers]

GO
/****** Object:  Table [dbo].[Resume_analysis_4]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Resume_analysis_4](
	[Id] [int] NOT NULL,
	[experience] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Resume_num] [int] NOT NULL
) ON [FOthers]

GO
/****** Object:  Table [dbo].[Resume_analysis_5]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Resume_analysis_5](
	[Id] [int] NOT NULL,
	[sex] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Resume_num] [int] NOT NULL
) ON [FOthers]

GO
/****** Object:  Table [dbo].[Resume_analysis_6]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Resume_analysis_6](
	[Id] [int] NOT NULL,
	[DescrIption] [nchar](20) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Resume_num] [int] NOT NULL
) ON [FOthers]

GO
/****** Object:  Table [dbo].[Resume_analysis_7]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Resume_analysis_7](
	[Id] [int] NOT NULL,
	[salary] [nvarchar](20) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Resume_num] [int] NOT NULL
) ON [FOthers]

GO
/****** Object:  Table [dbo].[resume_analysis_8]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[resume_analysis_8](
	[Id] [int] NOT NULL,
	[salary] [nvarchar](20) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Resume_num] [int] NOT NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[Resume_Xinxi]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Resume_Xinxi](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[UserName] [varchar](50) COLLATE Chinese_PRC_CS_AS NULL,
	[PassWord] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Email] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[RegDate] [smalldatetime] NOT NULL,
	[AddMan] [smallint] NOT NULL,
	[Province_Id] [int] NOT NULL,
	[Name] [nvarchar](20) COLLATE Chinese_PRC_CI_AS NULL,
	[IsHistory] [bit] NOT NULL,
	[UserNameLower]  AS (CONVERT([varchar](50),[UserName] collate CHINESE_PRC_CI_AS,(0))) PERSISTED,
 CONSTRAINT [PK_Resume_Xinxi] PRIMARY KEY NONCLUSTERED 
(
	[Id] ASC,
	[IsHistory] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [ResumeXinxiScheme]([IsHistory])
) ON [ResumeXinxiScheme]([IsHistory])

GO
/****** Object:  Table [dbo].[Resumeinform]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Resumeinform](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[title] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[Content] [nvarchar](500) COLLATE Chinese_PRC_CI_AS NULL,
	[addDate] [smalldatetime] NOT NULL,
	[status] [bit] NOT NULL,
	[Type] [smallint] NOT NULL,
	[link] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[province] [varchar](100) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[endDate] [smalldatetime] NULL,
 CONSTRAINT [PK_Resumeinform] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [FOthers]
) ON [FOthers]

GO
/****** Object:  Table [dbo].[ResumeSubScription]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ResumeSubScription](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[ResumeId] [int] NOT NULL,
	[JobId] [int] NOT NULL,
	[AddDate] [smalldatetime] NOT NULL,
 CONSTRAINT [PK_ResumesubscrIption] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [FOthers]
) ON [FOthers]

GO
/****** Object:  Table [dbo].[RmCompanyCv]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[RmCompanyCv](
	[cvMainID] [int] NULL,
	[cpMainId] [int] NULL
) ON [PRIMARY]

GO
/****** Object:  Index [IX_RmCompanyCv_cpMainID]    Script Date: 2018/9/25 12:40:11 ******/
CREATE CLUSTERED INDEX [IX_RmCompanyCv_cpMainID] ON [dbo].[RmCompanyCv]
(
	[cpMainId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[Role]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Role](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[rolename] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[province] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL,
	[grade] [tinyint] NULL,
 CONSTRAINT [PK_role] PRIMARY KEY CLUSTERED 
(
	[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 50) ON [PRIMARY],
 CONSTRAINT [IX_role_unique] UNIQUE NONCLUSTERED 
(
	[rolename] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 50) ON [Index]
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[Role_DataSource]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Role_DataSource](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[RoleId] [int] NOT NULL,
	[DataSourceId] [int] NOT NULL,
	[Privi] [char](20) COLLATE Chinese_PRC_CI_AS NOT NULL,
 CONSTRAINT [PK_Role_DataSource] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 50) ON [PRIMARY]
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[rtx_event]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[rtx_event](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[ErrorTime] [datetime] NOT NULL,
	[Msg] [varchar](1000) COLLATE Chinese_PRC_CI_AS NULL,
	[Filename] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL
) ON [BOthers]

GO
/****** Object:  Table [dbo].[rtx_log]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[rtx_log](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[Addresser] [varchar](20) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Recipient] [varchar](1000) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[AddDate] [datetime] NOT NULL,
	[Rtx_Content] [varchar](max) COLLATE Chinese_PRC_CI_AS NOT NULL,
 CONSTRAINT [PK_rtx_log] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers]
) ON [BOthers] TEXTIMAGE_ON [BOthers]

GO
/****** Object:  Table [dbo].[Sales_Factor]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Sales_Factor](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[YearMonth] [int] NOT NULL,
	[Factor_1] [int] NOT NULL,
	[Factor_2] [int] NOT NULL,
	[Factor_3] [int] NOT NULL,
	[Factor_4] [int] NOT NULL,
	[Factor_5] [int] NOT NULL,
 CONSTRAINT [PK_Sales_Factor] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers]
) ON [BOthers]

GO
/****** Object:  Table [dbo].[Sales_factor_farmer]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Sales_factor_farmer](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[YearMonth] [int] NOT NULL,
	[factor_1] [int] NOT NULL,
	[factor_2] [int] NOT NULL,
	[factor_3] [int] NOT NULL,
	[factor_4] [int] NOT NULL,
	[factor_5] [int] NOT NULL,
	[factor_6] [int] NOT NULL,
	[factor_7] [int] NOT NULL,
	[factor_chuzhi] [int] NOT NULL,
 CONSTRAINT [PK_Sales_factor_farmer] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers]
) ON [BOthers]

GO
/****** Object:  Table [dbo].[sales_ManagerUser_Month]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[sales_ManagerUser_Month](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[YearMonth] [int] NOT NULL,
	[ManagerUserId] [smallint] NOT NULL,
	[Obj_Sales] [int] NULL,
	[Real_Sales] [int] NULL,
	[DescrIption] [nvarchar](2000) COLLATE Chinese_PRC_CI_AS NULL,
 CONSTRAINT [PK_sales_ManagerUser_Month] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers],
 CONSTRAINT [IX_sales_ManagerUser_Month_unique] UNIQUE NONCLUSTERED 
(
	[YearMonth] ASC,
	[ManagerUserId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
) ON [BOthers]

GO
/****** Object:  Table [dbo].[sales_workDate]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[sales_workDate](
	[workDate] [int] NOT NULL,
	[status] [smallint] NOT NULL,
 CONSTRAINT [PK_sales_workDate] PRIMARY KEY CLUSTERED 
(
	[workDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers]
) ON [BOthers]

GO
/****** Object:  Table [dbo].[schMailPrev]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[schMailPrev](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[MailType] [tinyint] NOT NULL,
	[dcProvinceID] [smallint] NOT NULL,
	[AccountID] [int] NOT NULL,
	[AccountName] [varchar](100) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[UserName] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[SubID] [int] NULL,
	[Title] [varchar](200) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[EmailNumber] [tinyint] NOT NULL,
	[emailsite] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Email] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[SubSiteName] [nvarchar](20) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[MailBody] [nvarchar](max) COLLATE Chinese_PRC_CI_AS NULL,
	[HasSend] [bit] NOT NULL,
	[AddDate] [smalldatetime] NOT NULL,
	[MaxAge] [int] NULL,
	[MinAge] [int] NULL,
	[dcJobTypeID] [smallint] NULL,
	[dcRegionID] [varchar](6) COLLATE Chinese_PRC_CI_AS NULL,
	[JobName] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[RefreshDate] [datetime] NULL,
 CONSTRAINT [PK_schMailPrev] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

GO
/****** Object:  Table [dbo].[schMailPrev3]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[schMailPrev3](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[MailType] [tinyint] NOT NULL,
	[dcProvinceID] [smallint] NOT NULL,
	[AccountID] [int] NOT NULL,
	[AccountName] [varchar](100) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[UserName] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[SubID] [int] NULL,
	[Title] [varchar](200) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[EmailNumber] [tinyint] NOT NULL,
	[emailsite] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Email] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[SubSiteName] [nvarchar](20) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[MailBody] [nvarchar](max) COLLATE Chinese_PRC_CI_AS NULL,
	[HasSend] [bit] NOT NULL,
	[AddDate] [smalldatetime] NOT NULL,
	[MaxAge] [int] NULL,
	[MinAge] [int] NULL,
	[dcJobTypeID] [smallint] NULL,
	[dcRegionID] [varchar](6) COLLATE Chinese_PRC_CI_AS NULL,
	[JobName] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[RefreshDate] [datetime] NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

GO
/****** Object:  Table [dbo].[schMailPrevJobResume]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[schMailPrevJobResume](
	[schMailPrevId] [int] NOT NULL,
	[ResumeId] [int] NOT NULL,
	[JobId] [int] NOT NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[SearchCountLog]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[SearchCountLog](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[SearchCount] [int] NULL,
	[AddDate] [smalldatetime] NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[SearchIp]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[SearchIp](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[Ip] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[Source] [varchar](10) COLLATE Chinese_PRC_CI_AS NULL,
	[AddDate] [datetime] NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[SearchJobRefresh]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[SearchJobRefresh](
	[CpMainID] [int] NOT NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[SearchJobTop]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[SearchJobTop](
	[CpMainID] [int] NOT NULL,
	[JobID] [int] NOT NULL,
	[OpenDate] [datetime] NULL,
	[OrderType] [tinyint] NULL,
	[JobName] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
 CONSTRAINT [PK_SearchJobTop] PRIMARY KEY CLUSTERED 
(
	[JobID] 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].[searchkeywords]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[searchkeywords](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[keywords] [nvarchar](20) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[province_Id] [int] NOT NULL,
	[power] [smallint] NOT NULL,
	[Competition] [smalldatetime] NULL,
	[tuneDate] [smalldatetime] NULL,
	[version_Id] [int] NOT NULL,
	[CompetitionPrice] [numeric](5, 2) NULL,
	[Competition_sogou] [smalldatetime] NULL,
	[Competition_soso] [smalldatetime] NULL,
	[CompetitionPrice_sogou] [numeric](5, 2) NULL,
	[CompetitionPrice_soso] [numeric](5, 2) NULL,
 CONSTRAINT [PK_searchkeywords] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Market]
) ON [Market]

GO
/****** Object:  Table [dbo].[SearchKeywordsPower]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[SearchKeywordsPower](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[searchkeywords_Id] [int] NOT NULL,
	[YearMonthDay] [int] NOT NULL,
	[power] [smallint] NULL,
	[engine] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[addDate] [smalldatetime] NULL,
	[Ip] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL,
	[cookies] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
 CONSTRAINT [PK_SearchKeywordsPower] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Market]
) ON [Market]

GO
/****** Object:  Table [dbo].[SearchKeywordsPower0520]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[SearchKeywordsPower0520](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[searchkeywords_Id] [int] NOT NULL,
	[YearMonthDay] [int] NOT NULL,
	[power] [smallint] NULL,
	[engine] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[addDate] [smalldatetime] NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[SeatStatus]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[SeatStatus](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[StatusType] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL,
	[state] [tinyint] NULL,
	[Agent] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[Statustime] [datetime] NULL,
	[Exten] [varchar](10) COLLATE Chinese_PRC_CI_AS NULL,
	[ExtenType] [varchar](10) COLLATE Chinese_PRC_CI_AS NULL,
	[str] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL,
	[BusyType] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
 CONSTRAINT [PK_SeatStatus] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers]
) ON [BOthers]

GO
/****** Object:  Table [dbo].[SeatStatusCount]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[SeatStatusCount](
	[CountDate] [varchar](8) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Exten] [varchar](10) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[PRestatus] [tinyint] NOT NULL,
	[PreTime] [datetime] NOT NULL,
	[LoginSeCond] [int] NOT NULL,
	[LogoutSeCond] [int] NOT NULL,
	[BusySeCond] [int] NOT NULL,
	[IdleSeCond] [int] NOT NULL,
 CONSTRAINT [PK_SeatStatusCount] PRIMARY KEY NONCLUSTERED 
(
	[CountDate] ASC,
	[Exten] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers]
) ON [BOthers]

GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_SeatStatusCount_CountDate]    Script Date: 2018/9/25 12:40:11 ******/
CREATE CLUSTERED INDEX [IX_SeatStatusCount_CountDate] ON [dbo].[SeatStatusCount]
(
	[CountDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers]
GO
/****** Object:  Table [dbo].[Seconderer]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Seconderer](
	[Referer] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL,
	[VersionId] [int] NULL,
	[LoginDate] [smalldatetime] NOT NULL,
	[Ip] [varchar](15) COLLATE Chinese_PRC_CI_AS NULL,
	[Keywords] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[Province_Id] [smallint] NULL,
	[SessionId] [varchar](30) COLLATE Chinese_PRC_CI_AS NULL
) ON [Market]

GO
/****** Object:  Table [dbo].[Seconderer_Count]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Seconderer_Count](
	[CountDate] [int] NOT NULL,
	[Province_Id] [smallint] NOT NULL,
	[HowMany] [int] NOT NULL,
	[Referer] [varchar](200) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[VersionId] [int] NULL,
 CONSTRAINT [PK_seConderer_count] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Market]
) ON [Market]

GO
/****** Object:  Table [dbo].[Seconderer_Count_Keywords]    Script Date: 2018/9/25 12:40:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Seconderer_Count_Keywords](
	[Referer_Count_Id] [int] NOT NULL,
	[Keywords] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[HowMany] [smallint] NOT NULL
) ON [Market]

GO
/****** Object:  Table [dbo].[Seconderer_YearMonth]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Seconderer_YearMonth](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[YearMonth] [int] NOT NULL,
	[Item_Name] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Province_Id] [smallint] NULL,
	[HowMany] [int] NOT NULL,
 CONSTRAINT [PK_seConderer_YearMonth] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Market]
) ON [Market]

GO
/****** Object:  Table [dbo].[Seconderer2]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Seconderer2](
	[Referer] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL,
	[VersionId] [int] NULL,
	[LoginDate] [smalldatetime] NOT NULL,
	[Ip] [varchar](15) COLLATE Chinese_PRC_CI_AS NULL,
	[Keywords] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[Province_Id] [smallint] NULL,
	[SessionId] [varchar](30) COLLATE Chinese_PRC_CI_AS NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[SendResume_recruit]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[SendResume_recruit](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[ResumeId] [int] NOT NULL,
	[RecruitId] [int] NOT NULL,
	[AddDate] [smalldatetime] NOT NULL,
 CONSTRAINT [PK_sendResume_recruit] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [FOthers]
) ON [FOthers]

GO
/****** Object:  Table [dbo].[Servi_Account]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Servi_Account](
	[RtxId] [int] NOT NULL,
	[Status] [tinyint] NOT NULL,
	[CompanyId] [int] NOT NULL,
 CONSTRAINT [PK_servi_account] PRIMARY KEY CLUSTERED 
(
	[RtxId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers]
) ON [BOthers]

GO
/****** Object:  Table [dbo].[servi_log]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[servi_log](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[ProcessId] [int] NOT NULL,
	[Sender] [tinyint] NOT NULL,
	[Message] [varchar](max) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[CrDate] [datetime] NOT NULL,
 CONSTRAINT [PK_servi_log] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers]
) ON [BOthers] TEXTIMAGE_ON [BOthers]

GO
/****** Object:  Table [dbo].[servi_process]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[servi_process](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[RtxId] [int] NOT NULL,
	[VersionDomain] [varchar](30) COLLATE Chinese_PRC_CI_AS NULL,
	[CompanyId] [int] NOT NULL,
	[Province_Id] [tinyint] NOT NULL,
	[Companyname] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Province] [nvarchar](10) COLLATE Chinese_PRC_CI_AS NULL,
	[ValidDate] [varchar](30) COLLATE Chinese_PRC_CI_AS NULL,
	[Balance] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL,
	[Channel] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[ManagerUserId] [varchar](10) COLLATE Chinese_PRC_CI_AS NULL,
	[ManagerrtxId] [smallint] NULL,
	[Manager_User] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL,
	[StartDate] [smalldatetime] NOT NULL,
	[RefReshDate] [datetime] NOT NULL,
	[EndDate] [smalldatetime] NULL,
	[Lastrow] [int] NOT NULL,
	[Satisfaction] [tinyint] NOT NULL,
	[Remark] [nvarchar](500) COLLATE Chinese_PRC_CI_AS NULL,
	[Idlecount] [smallint] NOT NULL,
	[IsActive] [bit] NULL,
 CONSTRAINT [PK_servi_summary] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers]
) ON [BOthers]

GO
/****** Object:  Table [dbo].[Servi_User]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Servi_User](
	[Id] [smallint] NOT NULL,
	[Name] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Name_Eng] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Superior] [smallint] NOT NULL,
	[DeptId] [smallint] NOT NULL,
	[DisplayNo] [tinyint] NOT NULL,
	[AddDate] [smalldatetime] NOT NULL,
	[LetterNumber] [int] NULL,
 CONSTRAINT [PK_Servi_User] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers]
) ON [BOthers]

GO
/****** Object:  Table [dbo].[ServiceRunLog]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ServiceRunLog](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[ServiceId] [tinyint] NOT NULL,
	[RunRows] [int] NULL,
	[RunId] [int] NULL,
	[ObjectNo] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[RunStatus] [int] NULL,
	[RunMessage] [nvarchar](200) COLLATE Chinese_PRC_CI_AS NULL,
	[AddDate] [datetime] NULL,
 CONSTRAINT [PK_ServiceRunLog] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers]
) ON [BOthers]

GO
/****** Object:  Table [dbo].[smsBatchSend]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[smsBatchSend](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[Mobile] [varchar](max) COLLATE Chinese_PRC_CI_AS NULL,
	[Msg] [nvarchar](300) COLLATE Chinese_PRC_CI_AS NULL,
	[SendDate] [datetime] NULL,
	[SendStatus] [int] NULL,
	[AddDate] [smalldatetime] NULL
) ON [BOthers] TEXTIMAGE_ON [BOthers]

GO
/****** Object:  Table [dbo].[SmsMessageLog]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[SmsMessageLog](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[SendMan] [smallint] NOT NULL,
	[ManagerUserId] [smallint] NULL,
	[paMainId] [int] NULL,
	[caMainId] [int] NULL,
	[Mobile] [varchar](20) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Msg] [nvarchar](210) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[IsCat] [bit] NOT NULL,
	[AddDate] [datetime] NOT NULL,
	[PortNo] [tinyint] NULL,
	[SendDate] [datetime] NULL,
	[SendStatus] [int] NULL,
	[SmsType] [tinyint] NOT NULL,
	[MsgType] [tinyint] NOT NULL,
 CONSTRAINT [PK_SmsMessageLog] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers]
) ON [BOthers]

GO
/****** Object:  Table [dbo].[SmsWatch]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[SmsWatch](
	[ID] [int] NOT NULL,
	[CpMainID] [int] NULL,
	[CaMainID] [int] NULL,
	[SmsType] [tinyint] NULL,
	[Msg] [nvarchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[Mobile] [varchar](11) COLLATE Chinese_PRC_CI_AS NULL,
	[LastLoginTime] [int] NULL,
	[exMessageP2CCount] [int] NULL,
	[exInterviewCount] [int] NULL,
	[exJobApplyCount] [int] NULL,
	[cacvIntentionCount] [int] NULL,
	[LastDate] [datetime] NULL,
	[LastLoginDate] [smalldatetime] NULL,
	[IsSend] [bit] NULL,
	[WatchDate] [varchar](8) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[MsgType] [tinyint] NULL
) ON [BOthers]

GO
/****** Object:  Table [dbo].[SmsWatchLog]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[SmsWatchLog](
	[WatchDate] [smalldatetime] NOT NULL,
	[SendDate] [varchar](10) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[LoginNumber] [int] NULL,
	[AllNumBer] [int] NULL,
	[LoginNumberSend] [int] NULL,
	[AllNumBerSend] [int] NULL,
	[LoginNumberNotSend] [int] NULL,
	[AllNumBerNotSend] [int] NULL,
	[MsgType] [tinyint] NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[SOLLog]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[SOLLog](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[ProcessID] [int] NOT NULL,
	[Sender] [tinyint] NOT NULL,
	[IsViewed] [bit] NOT NULL,
	[Message] [varchar](5000) COLLATE Chinese_PRC_CI_AS NULL,
	[AddDate] [datetime] NOT NULL,
 CONSTRAINT [PK_SOLLog] PRIMARY KEY CLUSTERED 
(
	[ID] 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].[SOLProcess]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[SOLProcess](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[caMainID] [int] NOT NULL,
	[CompanyName] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[caName] [nvarchar](6) COLLATE Chinese_PRC_CI_AS NULL,
	[StartDate] [smalldatetime] NOT NULL,
	[EndDate] [smalldatetime] NULL,
	[IsActive] [bit] NOT NULL,
	[ManagerUserId] [smallint] NOT NULL,
	[Evaluate] [smallint] NULL,
	[Remark] [nvarchar](500) COLLATE Chinese_PRC_CI_AS NULL,
	[OfflineType] [tinyint] NOT NULL,
	[AddDate] [smalldatetime] NOT NULL,
 CONSTRAINT [PK_SOLProcess] PRIMARY KEY CLUSTERED 
(
	[ID] 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].[SOLService]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[SOLService](
	[ID] [int] NOT NULL,
	[Name] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[NameEng] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Superior] [smallint] NOT NULL,
	[DeptID] [smallint] NOT NULL,
	[DisplayNo] [tinyint] NOT NULL,
	[LetterNumber] [int] NULL,
	[AddDate] [smalldatetime] NOT NULL,
 CONSTRAINT [PK_SOLService] PRIMARY KEY CLUSTERED 
(
	[ID] 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].[Sow]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Sow](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[Title] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[DescrIption] [nvarchar](1000) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[AddDate] [smalldatetime] NOT NULL,
	[ManagerUserId] [smallint] NOT NULL,
	[Attachment] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[Privi] [varchar](500) COLLATE Chinese_PRC_CI_AS NULL,
 CONSTRAINT [PK_Sow] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers]
) ON [BOthers]

GO
/****** Object:  Table [dbo].[SpreadCallLog]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[SpreadCallLog](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[Filename] [varchar](100) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[FileMD5] [varchar](200) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[PhoneNo] [varchar](20) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[TimeLength] [smallint] NOT NULL,
	[AddMan] [smallint] NOT NULL,
	[AddDate] [smalldatetime] NOT NULL,
 CONSTRAINT [PK_SpreadCallLog] PRIMARY KEY CLUSTERED 
(
	[ID] 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].[Standard]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Standard](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[Title] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[DescrIption] [nvarchar](1000) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[AddDate] [smalldatetime] NOT NULL,
	[Type] [smallint] NOT NULL,
	[ManagerUserId] [smallint] NOT NULL,
	[Attachment] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[Privi] [varchar](500) COLLATE Chinese_PRC_CI_AS NULL,
 CONSTRAINT [PK_Standard] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers]
) ON [BOthers]

GO
/****** Object:  Table [dbo].[SurName]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[SurName](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[surname] [nvarchar](10) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[name] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
 CONSTRAINT [PK_surname] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers],
 CONSTRAINT [IX_surname_surname] UNIQUE NONCLUSTERED 
(
	[surname] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
) ON [BOthers]

GO
/****** Object:  Table [dbo].[TableSpaceInfo]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TableSpaceInfo](
	[NAMEINFO] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[ROWSINFO] [int] NULL,
	[RESERVED] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL,
	[DATAINFO] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL,
	[INDEX_SIZE] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL,
	[UNUSED] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL,
	[AddDate] [smalldatetime] NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[telephonebill_Day]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[telephonebill_Day](
	[countDate] [int] NOT NULL,
	[ManagerUserId] [int] NOT NULL,
	[name] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[telephone_num_all] [smallint] NOT NULL,
	[telephone_interval_all] [int] NOT NULL,
	[telephone_num_up60] [smallint] NOT NULL,
	[telephone_interval_up60] [int] NOT NULL,
	[status] [tinyint] NULL,
 CONSTRAINT [IX_telephonebill_Day_unique] UNIQUE NONCLUSTERED 
(
	[countDate] ASC,
	[ManagerUserId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
) ON [BOthers]

GO
/****** Object:  Table [dbo].[tmp_BlackWord]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tmp_BlackWord](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[BlackWord] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[tmp_jobPublishLog]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tmp_jobPublishLog](
	[id] [int] NULL,
	[cpMainId] [int] NULL,
	[InsertDate] [smalldatetime] NULL,
	[Deletedate] [smalldatetime] NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[Tmp_limitip]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Tmp_limitip](
	[LastLoginIp] [varchar](31) COLLATE Chinese_PRC_CI_AS NULL,
	[Cnt] [int] NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[tmp_limitip2]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tmp_limitip2](
	[ip] [varchar](31) COLLATE Chinese_PRC_CI_AS NULL,
	[cnt] [int] NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[tmp_limitmobile]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tmp_limitmobile](
	[mobile] [varchar](20) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[cnt] [int] NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[tmp0]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tmp0](
	[cvmainid] [int] NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[tmp1]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tmp1](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[ICP_CODE] [varchar](14) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[USER_ID] [varchar](60) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[USER_NAME] [varchar](60) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[IP_ADDR] [varchar](30) COLLATE Chinese_PRC_CI_AS NULL,
	[BIND_EMAIL] [varchar](64) COLLATE Chinese_PRC_CI_AS NULL,
	[BIND_TEL] [varchar](30) COLLATE Chinese_PRC_CI_AS NULL,
	[REAL_NAME] [varchar](60) COLLATE Chinese_PRC_CI_AS NULL,
	[SEX] [varchar](60) COLLATE Chinese_PRC_CI_AS NULL,
	[BIRTHDAY] [varchar](14) COLLATE Chinese_PRC_CI_AS NULL,
	[RESUME_ID] [varchar](30) COLLATE Chinese_PRC_CI_AS NULL,
	[LIVE_CITY] [varchar](60) COLLATE Chinese_PRC_CI_AS NULL,
	[JOB_CITY] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[JOB_POST] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[GRADUATE_SCHOOL] [varchar](128) COLLATE Chinese_PRC_CI_AS NULL,
	[GRADUATE_TIME] [int] NULL,
	[QUALIFICATION] [varchar](30) COLLATE Chinese_PRC_CI_AS NULL,
	[MAJOR] [varchar](128) COLLATE Chinese_PRC_CI_AS NULL,
	[LAST_COMPANY] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL,
	[AddDate] [datetime] NOT NULL,
	[HasSubmit] [bit] NOT NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[tmp1Log]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tmp1Log](
	[ICP_CODE] [varchar](14) COLLATE Chinese_PRC_CI_AS NULL,
	[DATA_TYPE] [varchar](10) COLLATE Chinese_PRC_CI_AS NULL,
	[USER_ID] [varchar](60) COLLATE Chinese_PRC_CI_AS NULL,
	[USER_NAME] [varchar](60) COLLATE Chinese_PRC_CI_AS NULL,
	[USER_PASSWORD] [varchar](128) COLLATE Chinese_PRC_CI_AS NULL,
	[STATUS] [varchar](32) COLLATE Chinese_PRC_CI_AS NULL,
	[CREATE_TIME] [varchar](14) COLLATE Chinese_PRC_CI_AS NULL,
	[IP_ADDR] [varchar](30) COLLATE Chinese_PRC_CI_AS NULL,
	[MAC_ADDR] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[MOBILE_IMEI] [varchar](30) COLLATE Chinese_PRC_CI_AS NULL,
	[BIND_EMAIL] [varchar](64) COLLATE Chinese_PRC_CI_AS NULL,
	[BIND_TEL] [varchar](30) COLLATE Chinese_PRC_CI_AS NULL,
	[CONTACT_TEL] [varchar](30) COLLATE Chinese_PRC_CI_AS NULL,
	[REAL_NAME] [varchar](60) COLLATE Chinese_PRC_CI_AS NULL,
	[SEX] [varchar](60) COLLATE Chinese_PRC_CI_AS NULL,
	[BIRTHDAY] [varchar](14) COLLATE Chinese_PRC_CI_AS NULL,
	[CERTIFICATE_CODE] [varchar](60) COLLATE Chinese_PRC_CI_AS NULL,
	[PHOTO_FILE] [varchar](120) COLLATE Chinese_PRC_CI_AS NULL,
	[RESUME_ID] [varchar](30) COLLATE Chinese_PRC_CI_AS NULL,
	[REGISTER_CITY] [varchar](60) COLLATE Chinese_PRC_CI_AS NULL,
	[DWELL_CITY] [varchar](60) COLLATE Chinese_PRC_CI_AS NULL,
	[RESIDENCE] [varchar](60) COLLATE Chinese_PRC_CI_AS NULL,
	[LIVE_CITY] [varchar](60) COLLATE Chinese_PRC_CI_AS NULL,
	[JOB_CITY] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[JOB_POST] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[BLACKLIST] [varchar](128) COLLATE Chinese_PRC_CI_AS NULL,
	[GRADUATE_SCHOOL] [varchar](128) COLLATE Chinese_PRC_CI_AS NULL,
	[GRADUATE_TIME] [int] NULL,
	[QUALIFICATION] [varchar](30) COLLATE Chinese_PRC_CI_AS NULL,
	[MAJOR] [varchar](128) COLLATE Chinese_PRC_CI_AS NULL,
	[LAST_COMPANY] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL,
	[IPInt] [bigint] NULL,
	[AddDate] [datetime] NULL,
	[ip1] [int] NULL,
	[ip2] [int] NULL,
	[ip3] [int] NULL,
	[ip4] [int] NULL,
	[PhotoPath] [varchar](9) COLLATE Chinese_PRC_CI_AS NULL,
	[PhotoId] [int] NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[TmpID]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TmpID](
	[ID] [int] NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[tmpPaBaiduJson]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tmpPaBaiduJson](
	[paMainID] [int] NOT NULL,
	[Json] [varchar](max) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Adddate] [smalldatetime] NOT NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

GO
/****** Object:  Table [dbo].[tmpResume_Xinxi_Check]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tmpResume_Xinxi_Check](
	[email] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[addman] [smallint] NULL,
	[province_id] [int] NULL,
	[regdate] [datetime] NULL,
	[paMainId] [int] NULL,
	[DeleteDate] [datetime] NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[tmpWsLog]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tmpWsLog](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[ip] [varchar](15) COLLATE Chinese_PRC_CI_AS NULL,
	[pageID] [int] NULL,
	[AddDate] [datetime] NULL,
	[EndDate] [datetime] NULL,
	[para] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[ToolRunLog]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ToolRunLog](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[ToolType] [tinyint] NOT NULL,
	[RunServer] [tinyint] NULL,
	[BeginTime] [datetime] NOT NULL,
	[EndTime] [datetime] NULL,
	[RunTime] [int] NULL,
	[RunStatus] [tinyint] NULL,
	[RunMessage] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL,
	[AddDate] [smalldatetime] NOT NULL,
 CONSTRAINT [PK_ToolRunLog] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers]
) ON [BOthers]

GO
/****** Object:  Table [dbo].[Topics]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Topics](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[Title] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Description] [nvarchar](250) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[FileName] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Url] [varchar](100) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[type] [tinyint] NOT NULL,
	[EmailClick] [int] NOT NULL,
	[ClickNumber] [int] NOT NULL,
	[AddDate] [smalldatetime] NOT NULL,
 CONSTRAINT [PK_Topics] PRIMARY KEY CLUSTERED 
(
	[ID] 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].[tpiCompany]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tpiCompany](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[tpiListId] [int] NULL,
	[cpMainId] [int] NULL,
	[tpiCompanyId] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[Status] [tinyint] NULL,
	[AddDate] [datetime] NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[tpiList]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tpiList](
	[Id] [int] NULL,
	[ThirdPartyName] [nvarchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[Programmer] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL,
	[AddDate] [datetime] NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[Url]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Url](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[DescrIption] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[url] [varchar](200) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[allclick] [int] NOT NULL,
	[toDayclick] [int] NOT NULL,
	[beginDate] [smalldatetime] NOT NULL,
	[province_Id] [int] NOT NULL,
	[Type] [tinyint] NULL,
	[allResume] [int] NOT NULL,
	[toDayResume] [int] NOT NULL,
	[allCompany] [int] NOT NULL,
	[toDayCompany] [int] NOT NULL,
	[status] [smallint] NOT NULL,
	[Ip_repeat] [smallint] NOT NULL,
	[yestoDayclick] [int] NULL,
	[yestoDayResume] [int] NULL,
	[yestoDayCompany] [int] NULL,
	[AddMan] [int] NULL,
 CONSTRAINT [PK_url] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Market]
) ON [Market]

GO
/****** Object:  Table [dbo].[url_click_log]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[url_click_log](
	[url_Id] [int] NOT NULL,
	[Ip] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[addDate] [smalldatetime] NOT NULL
) ON [Market]

GO
/****** Object:  Index [IX_url_click_log_addDate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE CLUSTERED INDEX [IX_url_click_log_addDate] ON [dbo].[url_click_log]
(
	[addDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Market]
GO
/****** Object:  Table [dbo].[url_Month]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[url_Month](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[url_Id] [int] NOT NULL,
	[Month] [int] NOT NULL,
	[click] [int] NOT NULL,
	[Resume] [int] NOT NULL,
	[Company] [int] NOT NULL,
 CONSTRAINT [PK_url_Month] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Market],
 CONSTRAINT [IX_url_Month_weiyi] UNIQUE NONCLUSTERED 
(
	[Month] ASC,
	[url_Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
) ON [Market]

GO
/****** Object:  Table [dbo].[UrlAccount]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[UrlAccount](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[UrlID] [int] NOT NULL,
	[paMainID] [int] NULL,
	[cpMainID] [int] NULL,
	[AddDate] [smalldatetime] NOT NULL,
 CONSTRAINT [PK_UrlAccount] PRIMARY KEY CLUSTERED 
(
	[ID] 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].[VersionPrLog]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[VersionPrLog](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[VersionId] [int] NOT NULL,
	[Pr] [tinyint] NOT NULL,
	[AddDate] [varchar](10) COLLATE Chinese_PRC_CI_AS NOT NULL,
 CONSTRAINT [PK_VersionPrLog] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Market]
) ON [Market]

GO
/****** Object:  Table [dbo].[Video]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Video](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[CompanyId] [int] NOT NULL,
	[vIdeono] [char](10) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[seetime] [datetime] NOT NULL
) ON [FOthers]

GO
/****** Object:  Table [dbo].[WapCounter]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[WapCounter](
	[countDate] [int] NOT NULL,
	[versionId] [smallint] NOT NULL,
	[viewnumber] [int] NOT NULL,
	[spIderviewnumber] [int] NOT NULL,
 CONSTRAINT [IX_WapCounter_unique] UNIQUE CLUSTERED 
(
	[countDate] ASC,
	[versionId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [FOthers]
) ON [FOthers]

GO
/****** Object:  Table [dbo].[WebSiteMonitor]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[WebSiteMonitor](
	[ID] [smallint] NOT NULL,
	[SubSiteName] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[SubSiteUrl] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[Interval] [smallint] NULL,
	[LogTime] [datetime] NULL,
	[RtxNumber] [tinyint] NOT NULL,
 CONSTRAINT [PK_WebSiteMonitor] PRIMARY KEY CLUSTERED 
(
	[ID] 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].[WebSiteMonitorBadLog021]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[WebSiteMonitorBadLog021](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[ProvinceId] [int] NOT NULL,
	[LogTime] [datetime] NOT NULL,
	[FileContent] [nvarchar](max) COLLATE Chinese_PRC_CI_AS NULL,
 CONSTRAINT [PK_WebSiteMonitorBadLog] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

GO
/****** Object:  Table [dbo].[WebSiteMonitorLog]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[WebSiteMonitorLog](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[ProvinceID] [int] NOT NULL,
	[SiteStatus] [tinyint] NULL,
	[AddDate] [datetime] NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[WebSiteMonitorLog1021]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[WebSiteMonitorLog1021](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[ProvinceID] [int] NOT NULL,
	[SiteStatus] [tinyint] NULL,
	[AddDate] [datetime] NULL,
 CONSTRAINT [PK_WebSiteMonitorLog] PRIMARY KEY CLUSTERED 
(
	[ID] 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].[WordList]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[WordList](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[Word] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[WordType] [tinyint] NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[workDate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[workDate](
	[workDate] [int] NOT NULL,
	[Type] [smallint] NULL,
	[IsPaid] [bit] NOT NULL,
 CONSTRAINT [PK_workDate] PRIMARY KEY CLUSTERED 
(
	[workDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers]
) ON [BOthers]

GO
/****** Object:  Table [dbo].[workDate_province_ManagerUser]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[workDate_province_ManagerUser](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[WorkDate] [int] NOT NULL,
	[Province_Id] [tinyint] NOT NULL,
	[ManagerUser_Id] [smallint] NOT NULL,
 CONSTRAINT [PK_workDate_province_ManagerUser] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers]
) ON [BOthers]

GO
/****** Object:  Table [dbo].[WxAttention]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[WxAttention](
	[WxServiceNoID] [int] NULL,
	[OpenID] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[UpdateDate] [smalldatetime] NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[wxChatOnlineTemp]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[wxChatOnlineTemp](
	[ChatOnineId] [int] NULL,
	[paMainId] [int] NULL,
	[cvMainid] [int] NULL,
	[caMainId] [int] NULL,
	[IsSend] [bit] NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[WxFans]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[WxFans](
	[ID] [int] IDENTITY(1,1) NOT FOR REPLICATION NOT NULL,
	[OpenID] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[PaMainID] [int] NULL,
	[AttentionDate] [smalldatetime] NULL,
	[AttentionCancelDate] [smalldatetime] NULL,
	[LastReceiveDate] [smalldatetime] NULL,
	[LastSendMessage] [varchar](500) COLLATE Chinese_PRC_CI_AS NULL,
	[Status] [smallint] NULL,
	[WxServiceNoID] [int] NULL,
	[caMainId] [int] NULL,
	[caBindCancelDate] [smalldatetime] NULL,
	[unionid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
 CONSTRAINT [PK_WxUser] PRIMARY KEY CLUSTERED 
(
	[ID] 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].[WxMax]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[WxMax](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[TableName] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[MaxID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[UpdateDate] [datetime] NULL,
 CONSTRAINT [PK_WxMax] PRIMARY KEY CLUSTERED 
(
	[ID] 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].[WxMessageReceive]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[WxMessageReceive](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[WxFansID] [int] NOT NULL,
	[AddDate] [smalldatetime] NULL,
	[Message] [varchar](500) COLLATE Chinese_PRC_CI_AS NULL,
	[LogType] [smallint] NULL,
 CONSTRAINT [PK_WxUserLog] PRIMARY KEY CLUSTERED 
(
	[ID] 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].[WxMessageSend]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[WxMessageSend](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[WxFansID] [int] NOT NULL,
	[Message] [varchar](1000) COLLATE Chinese_PRC_CI_AS NULL,
	[SendDate] [smalldatetime] NULL,
	[Status] [smallint] NULL,
	[MessageType] [smallint] NULL,
	[WxTemplatenoID] [int] NULL,
	[Remark] [nvarchar](200) COLLATE Chinese_PRC_CI_AS NULL,
	[CpMainID] [int] NULL,
	[AddDate] [smalldatetime] NULL,
 CONSTRAINT [PK_WxMessageSend] PRIMARY KEY CLUSTERED 
(
	[ID] 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].[WXQrImage]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[WXQrImage](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[Ticket] [varchar](150) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[PageType] [tinyint] NOT NULL,
	[Status] [tinyint] NOT NULL,
	[AddDate] [datetime] NOT NULL,
	[paMainId] [int] NULL,
	[ip] [varchar](31) COLLATE Chinese_PRC_CI_AS NULL,
	[OpenID] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
 CONSTRAINT [PK__WXScene__3CAC54C0] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [CP]
) ON [CP]

GO
/****** Object:  Table [dbo].[WxServiceNo]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[WxServiceNo](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[Name] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[AppID] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[AppSecret] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[UserName] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Password] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[ProvinceID] [int] NOT NULL,
	[AddDate] [smalldatetime] NULL,
	[Status] [smallint] NULL,
 CONSTRAINT [PK_WxServiceNo] PRIMARY KEY CLUSTERED 
(
	[ID] 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].[wxSmallPrograminfo]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[wxSmallPrograminfo](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[thirdSessionId] [varchar](200) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[openId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[sessionId] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[unionId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[addDate] [smalldatetime] NULL,
	[pamainid] [int] NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[WxTemplate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[WxTemplate](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[Title] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[TemplateTitle] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Detail] [varchar](1000) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Url] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL,
	[Type] [smallint] NULL,
	[Remark] [nvarchar](500) COLLATE Chinese_PRC_CI_AS NULL,
	[AddDate] [smalldatetime] NULL,
	[Status] [smallint] NULL,
 CONSTRAINT [PK_WxTemplate] PRIMARY KEY CLUSTERED 
(
	[ID] 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].[WxTemplate0103]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[WxTemplate0103](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[Title] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[TemplateTitle] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Detail] [varchar](1000) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[Url] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL,
	[Type] [smallint] NULL,
	[Remark] [nvarchar](500) COLLATE Chinese_PRC_CI_AS NULL,
	[AddDate] [smalldatetime] NULL,
	[Status] [smallint] NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[WxTemplateNo]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[WxTemplateNo](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[No] [varchar](100) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[WxTemplateId] [int] NOT NULL,
	[WxServiceNoID] [int] NOT NULL,
 CONSTRAINT [PK_WxTemplateNo] PRIMARY KEY CLUSTERED 
(
	[ID] 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].[WxTemplatePara]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[WxTemplatePara](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[WxTemplateID] [int] NOT NULL,
	[ParaName] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[ParaValue] [varchar](500) COLLATE Chinese_PRC_CI_AS NULL,
	[ParaColor] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
 CONSTRAINT [PK_WxTemplatePara] PRIMARY KEY CLUSTERED 
(
	[ID] 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].[WxTemplatePara0103]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[WxTemplatePara0103](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[WxTemplateID] [int] NOT NULL,
	[ParaName] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[ParaValue] [varchar](500) COLLATE Chinese_PRC_CI_AS NULL,
	[ParaColor] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[yingyelog]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[yingyelog](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[ManagerUserId] [smallint] NOT NULL,
	[countDate] [int] NOT NULL,
	[province_Id] [tinyint] NOT NULL,
	[faxpassed] [int] NOT NULL,
	[faxnotpassed] [int] NOT NULL,
	[uploadpassed] [int] NOT NULL,
	[uploadnotpassed] [int] NOT NULL,
	[transferpassed] [int] NOT NULL,
	[transfernotpassed] [int] NOT NULL,
 CONSTRAINT [PK_yingyelog] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [BOthers]
) ON [BOthers]

GO
/****** Object:  Table [dbo].[zhifubao20170223]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[zhifubao20170223](
	[tsctdate] [datetime] NOT NULL,
	[a] [varchar](10) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[b] [varchar](12) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[oppositeaccount] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
	[tsctplace] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[debit] [numeric](18, 2) NULL,
	[credit] [numeric](18, 2) NULL,
	[d] [varchar](8) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[e] [int] NOT NULL,
	[balance] [numeric](18, 2) NULL,
	[id] [int] IDENTITY(1,1) NOT NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[ZmxyTransaction]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ZmxyTransaction](
	[ID] [varchar](32) COLLATE Chinese_PRC_CI_AS NOT NULL,
	[AddDate] [smalldatetime] NOT NULL,
	[cpMainID] [int] NULL,
	[cpCertificationID] [int] NULL,
 CONSTRAINT [PK_ZmxyTransaction] PRIMARY KEY CLUSTERED 
(
	[ID] 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:  Index [IX_adverproject_begintime]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_adverproject_begintime] ON [dbo].[AdverProject]
(
	[BeginTime] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_adverproject_complex1]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_adverproject_complex1] ON [dbo].[AdverProject]
(
	[Type] ASC,
	[BeginTime] ASC,
	[EndTime] ASC,
	[Valid] ASC,
	[Province_Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_adverproject_endtime]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_adverproject_endtime] ON [dbo].[AdverProject]
(
	[EndTime] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_adverproject_province_id]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_adverproject_province_id] ON [dbo].[AdverProject]
(
	[Province_Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_adverproject_ErrorLog_addDate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_adverproject_ErrorLog_addDate] ON [dbo].[AdverProject_ErrorLog]
(
	[AddDate] DESC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_Agent_Black_Agent]    Script Date: 2018/9/25 12:40:12 ******/
CREATE UNIQUE NONCLUSTERED INDEX [IX_Agent_Black_Agent] ON [dbo].[Agent_Black]
(
	[agent] 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 = OFF) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_Agent_White_Agent]    Script Date: 2018/9/25 12:40:12 ******/
CREATE UNIQUE NONCLUSTERED INDEX [IX_Agent_White_Agent] ON [dbo].[Agent_White]
(
	[Agent] 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 = OFF) ON [Index]
GO
/****** Object:  Index [IX_AgentIp_Type]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_AgentIp_Type] ON [dbo].[AgentIp]
(
	[Type] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_answer_ansewer]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_answer_ansewer] ON [dbo].[Answer]
(
	[Answer] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_answer_manid]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_answer_manid] ON [dbo].[Answer]
(
	[ManId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_answer_questionid]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_answer_questionid] ON [dbo].[Answer]
(
	[QuestionId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_ass_consultant]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_ass_consultant] ON [dbo].[ass_consultant]
(
	[yearmonth] ASC,
	[dcgroup] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = 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_ass_consultant_id]    Script Date: 2018/9/25 12:40:12 ******/
CREATE UNIQUE NONCLUSTERED INDEX [IX_ass_consultant_id] ON [dbo].[ass_consultant]
(
	[consultantid] ASC,
	[yearmonth] 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_ass_cpmain]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_ass_cpmain] ON [dbo].[ass_cpmain]
(
	[yearmonth] ASC,
	[dcProvinceID] ASC,
	[consultantid] ASC,
	[consultantidNew] ASC,
	[a_type] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
/****** Object:  Index [IX_ass_cpmain_consultantid]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_ass_cpmain_consultantid] ON [dbo].[ass_cpmain]
(
	[consultantid] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
/****** Object:  Index [IX_ass_cpmain_consultantidNew]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_ass_cpmain_consultantidNew] ON [dbo].[ass_cpmain]
(
	[consultantidNew] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
/****** Object:  Index [IX_ass_cpmain_dcprovinceid]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_ass_cpmain_dcprovinceid] ON [dbo].[ass_cpmain]
(
	[dcProvinceID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
/****** Object:  Index [IX_ass_cpmain_id]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_ass_cpmain_id] ON [dbo].[ass_cpmain]
(
	[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = 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_ass_cpmain_name]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_ass_cpmain_name] ON [dbo].[ass_cpmain]
(
	[name] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = 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_ass_cpmain_unique]    Script Date: 2018/9/25 12:40:12 ******/
CREATE UNIQUE NONCLUSTERED INDEX [IX_ass_cpmain_unique] ON [dbo].[ass_cpmain]
(
	[id] ASC,
	[yearmonth] 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 [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_ass_cpMain_cnt_All]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_ass_cpMain_cnt_All] ON [dbo].[ass_cpMain_cnt_All]
(
	[yearmonth] ASC,
	[dcProvinceID] ASC,
	[a_type] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
/****** Object:  Index [IX_ass_group_province]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_ass_group_province] ON [dbo].[ass_group_province]
(
	[dcprovinceid] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
/****** Object:  Index [IX_ass_group_province_1]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_ass_group_province_1] ON [dbo].[ass_group_province]
(
	[dcgroupid] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = 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_ass_noAssign_id]    Script Date: 2018/9/25 12:40:12 ******/
CREATE UNIQUE NONCLUSTERED INDEX [IX_ass_noAssign_id] ON [dbo].[ass_noAssign]
(
	[consultantid] ASC,
	[yearmonth] ASC,
	[companyname] 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_ass_noAssign_id]    Script Date: 2018/9/25 12:40:12 ******/
CREATE UNIQUE NONCLUSTERED INDEX [IX_ass_noAssign_id] ON [dbo].[ass_noAssign_old]
(
	[cpMainID] ASC,
	[yearmonth] 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
/****** Object:  Index [IX_Atc_Account_addDate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_Atc_Account_addDate] ON [dbo].[Atc_Account]
(
	[AddMan] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_Atc_Account_addman]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_Atc_Account_addman] ON [dbo].[Atc_Account]
(
	[AddMan] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_Atc_Account_Atc_Resource_Id]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_Atc_Account_Atc_Resource_Id] ON [dbo].[Atc_Account]
(
	[Atc_Resource_Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_Atc_Account_Complex]    Script Date: 2018/9/25 12:40:12 ******/
CREATE UNIQUE NONCLUSTERED INDEX [IX_Atc_Account_Complex] ON [dbo].[Atc_Account]
(
	[Atc_Resource_Id] ASC,
	[username] 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 [Index]
GO
/****** Object:  Index [IX_Atc_Article_addDate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_Atc_Article_addDate] ON [dbo].[Atc_Article]
(
	[Adddate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_Atc_Article_addMan]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_Atc_Article_addMan] ON [dbo].[Atc_Article]
(
	[Addman] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_Atc_Article_Atc_NewsPoint_Id]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_Atc_Article_Atc_NewsPoint_Id] ON [dbo].[Atc_Article]
(
	[Atc_NewsPoint_Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_Atc_NewsPoint_addDate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_Atc_NewsPoint_addDate] ON [dbo].[Atc_NewsPoint]
(
	[AddDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_Atc_NewsPoint_addMan]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_Atc_NewsPoint_addMan] ON [dbo].[Atc_NewsPoint]
(
	[AddMan] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_Atc_NewsPoint_Atc_Project_Id]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_Atc_NewsPoint_Atc_Project_Id] ON [dbo].[Atc_NewsPoint]
(
	[Atc_Project_Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_Atc_Project_addMan]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_Atc_Project_addMan] ON [dbo].[Atc_Project]
(
	[Addman] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_Atc_Resource]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_Atc_Resource] ON [dbo].[Atc_Resource]
(
	[ResourceName] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_Atc_Resource_addMan]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_Atc_Resource_addMan] ON [dbo].[Atc_Resource]
(
	[Addman] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_Atc_Topic]    Script Date: 2018/9/25 12:40:12 ******/
CREATE UNIQUE NONCLUSTERED INDEX [IX_Atc_Topic] ON [dbo].[Atc_Topic]
(
	[Atc_Account_Id] ASC,
	[Atc_Article_Id] 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 [Index]
GO
/****** Object:  Index [IX_Atc_Topic_complex1]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_Atc_Topic_complex1] ON [dbo].[Atc_Topic]
(
	[status] ASC,
	[AddDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_Atc_Topic_ClickNum_Atc_Topic_Id]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_Atc_Topic_ClickNum_Atc_Topic_Id] ON [dbo].[Atc_Topic_ClickNum]
(
	[Atc_Topic_Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_Atc_Topic_ClickNum_MonthDay]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_Atc_Topic_ClickNum_MonthDay] ON [dbo].[Atc_Topic_ClickNum]
(
	[MonthDay] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_Atc_Topic_ClickNum_unique]    Script Date: 2018/9/25 12:40:12 ******/
CREATE UNIQUE NONCLUSTERED INDEX [IX_Atc_Topic_ClickNum_unique] ON [dbo].[Atc_Topic_ClickNum]
(
	[Atc_Topic_Id] ASC,
	[MonthDay] 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 [Index]
GO
/****** Object:  Index [IX_backdata_countdate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_backdata_countdate] ON [dbo].[BackData]
(
	[CountDate] DESC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_backdata_managerid]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_backdata_managerid] ON [dbo].[BackData]
(
	[ManagerID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_BsAskInfo_Complex]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_BsAskInfo_Complex] ON [dbo].[bsASKInfo]
(
	[AddDate] ASC,
	[IsOnline] ASC,
	[ProvinceIds] ASC,
	[ClickNumber] ASC
)
INCLUDE ( 	[ID]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_bsAskInfo_Complex2]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_bsAskInfo_Complex2] ON [dbo].[bsASKInfo]
(
	[Title] ASC,
	[SolveDate] ASC,
	[UpdateDate] ASC,
	[ProvinceIds] ASC
)
INCLUDE ( 	[ID]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_BsAskInfo_Complex3]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_BsAskInfo_Complex3] ON [dbo].[bsASKInfo]
(
	[TypeID] ASC,
	[IsOnline] ASC,
	[ProvinceIds] ASC,
	[UpdateDate] ASC
)
INCLUDE ( 	[ID]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_bsAskInfoDayreport_Complex]    Script Date: 2018/9/25 12:40:12 ******/
CREATE UNIQUE NONCLUSTERED INDEX [IX_bsAskInfoDayreport_Complex] ON [dbo].[bsAskInfoDayReport]
(
	[CountDate] ASC,
	[bsAskInfoId] 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 [Index]
GO
/****** Object:  Index [IX_bsCpBackLogin_AddDate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_bsCpBackLogin_AddDate] ON [dbo].[bsCpBackLogin]
(
	[AddDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_bsCpBackLogin_caMainID]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_bsCpBackLogin_caMainID] ON [dbo].[bsCpBackLogin]
(
	[caMainID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_bsCpBackLogin_UnqueID]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_bsCpBackLogin_UnqueID] ON [dbo].[bsCpBackLogin]
(
	[UnqueID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_bsCpModify_AddDate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_bsCpModify_AddDate] ON [dbo].[bsCpModify]
(
	[AddDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_bsCpStatus_caMainID]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_bsCpStatus_caMainID] ON [dbo].[bsCpStatus]
(
	[cpMainID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_bsCpStatus_VerifyDate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_bsCpStatus_VerifyDate] ON [dbo].[bsCpStatus]
(
	[VerifyDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_bsCpStatus_VerifyMan]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_bsCpStatus_VerifyMan] ON [dbo].[bsCpStatus]
(
	[VerifyMan] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_bsCpVerify_VerifyDate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_bsCpVerify_VerifyDate] ON [dbo].[bsCpVerify]
(
	[VerifyDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_bsCpVerify_VerifyMan]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_bsCpVerify_VerifyMan] ON [dbo].[bsCpVerify]
(
	[VerifyMan] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_bsCpVerifyLog_bsCpVerifyID]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_bsCpVerifyLog_bsCpVerifyID] ON [dbo].[bsCpVerifyLog]
(
	[bsCpVerifyID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_bsCvModify_cvMainID]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_bsCvModify_cvMainID] ON [dbo].[bsCvModify]
(
	[cvMainID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_bsCvModify_SubID]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_bsCvModify_SubID] ON [dbo].[bsCvModify]
(
	[SubID] ASC,
	[Location] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_bsCvReview_paMainID]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_bsCvReview_paMainID] ON [dbo].[bsCvReview]
(
	[cvMainID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_bsCvReview_VerifyMan]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_bsCvReview_VerifyMan] ON [dbo].[bsCvReview]
(
	[VerifyMan] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_bsCvVerify_cvMainID]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_bsCvVerify_cvMainID] ON [dbo].[bsCvVerify]
(
	[cvMainID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_bsCvVerify_VerifyDate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_bsCvVerify_VerifyDate] ON [dbo].[bsCvVerify]
(
	[VerifyDate] DESC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_bsCvVerifyLog_addDate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_bsCvVerifyLog_addDate] ON [dbo].[bsCvVerifyLog]
(
	[AddDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_bsCvVerifyLog_bsCvVerifyID]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_bsCvVerifyLog_bsCvVerifyID] ON [dbo].[bsCvVerifyLog]
(
	[bsCvVerifyID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_bsCvVerifyLog_cvMain]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_bsCvVerifyLog_cvMain] ON [dbo].[bsCvVerifyLog]
(
	[cvMainID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_bsDeadCompany_CpMainId]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_bsDeadCompany_CpMainId] ON [dbo].[bsDeadCompany]
(
	[cpMainID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_bsDeleteFile_Complex]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_bsDeleteFile_Complex] ON [dbo].[bsDeleteFile]
(
	[FileType] ASC,
	[AddDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_bsDeleteFile_Deleted]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_bsDeleteFile_Deleted] ON [dbo].[bsDeleteFile]
(
	[IsDelete] ASC,
	[DeleteDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_bsManagerUserAction_AddDate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_bsManagerUserAction_AddDate] ON [dbo].[bsManagerUserAction]
(
	[AddDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_bsManagerUserAction_ManagerUSerId]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_bsManagerUserAction_ManagerUSerId] ON [dbo].[bsManagerUserAction]
(
	[ManagerUserID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_bsMobileSpread_AccountDate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_bsMobileSpread_AccountDate] ON [dbo].[bsMobileSpread]
(
	[AccountDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_bsMobileSpread_AddDate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_bsMobileSpread_AddDate] ON [dbo].[bsMobileSpread]
(
	[AddDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_bsMobileSpread_AddMan]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_bsMobileSpread_AddMan] ON [dbo].[bsMobileSpread]
(
	[AddMan] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_bsMobileSpread_MobileNo]    Script Date: 2018/9/25 12:40:12 ******/
CREATE UNIQUE NONCLUSTERED INDEX [IX_bsMobileSpread_MobileNo] ON [dbo].[bsMobileSpread]
(
	[MobileNo] ASC,
	[UserType] 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 [Index]
GO
/****** Object:  Index [Ix_bsMobileSpread_ProvinceId]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [Ix_bsMobileSpread_ProvinceId] ON [dbo].[bsMobileSpread]
(
	[ProvinceId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_bsMobileSpread_ReturnDate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_bsMobileSpread_ReturnDate] ON [dbo].[bsMobileSpread]
(
	[ReturnDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_bsPaBackLogin_AddDate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_bsPaBackLogin_AddDate] ON [dbo].[bsPaBackLogin]
(
	[AddDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_bsPaBackLogin_ManagerUserID]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_bsPaBackLogin_ManagerUserID] ON [dbo].[bsPaBackLogin]
(
	[ManagerUserID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_bsPaBackLogin_paMainID]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_bsPaBackLogin_paMainID] ON [dbo].[bsPaBackLogin]
(
	[paMainID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_bsRtxStatus_Complex]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_bsRtxStatus_Complex] ON [dbo].[bsRtxStatus]
(
	[ManagerUserId] ASC,
	[CheckDay] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_caActiveLog_AddDate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_caActiveLog_AddDate] ON [dbo].[caActiveLog]
(
	[AddDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_caActiveLog_caMainID]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_caActiveLog_caMainID] ON [dbo].[caActiveLog]
(
	[caMainID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_caActiveLog_caOrderId]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_caActiveLog_caOrderId] ON [dbo].[caActiveLog]
(
	[caOrderId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_caActiveLog_Select]    Script Date: 2018/9/25 12:40:12 ******/
CREATE UNIQUE NONCLUSTERED INDEX [IX_caActiveLog_Select] ON [dbo].[caActiveLog]
(
	[cpMainID] ASC,
	[cvMainID] 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 [Index]
GO
/****** Object:  Index [IX_caActiveLog_Unique]    Script Date: 2018/9/25 12:40:12 ******/
CREATE UNIQUE NONCLUSTERED INDEX [IX_caActiveLog_Unique] ON [dbo].[caActiveLog]
(
	[cpMainID] ASC,
	[caOrderId] ASC,
	[RemainQuota] 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 [Index]
GO
/****** Object:  Index [IX_caBalanceLog_AddDate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_caBalanceLog_AddDate] ON [dbo].[caBalanceLog]
(
	[AddDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_caBalanceLog_caMainID]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_caBalanceLog_caMainID] ON [dbo].[caBalanceLog]
(
	[caMainID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_caBalanceLog_cvMainID]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_caBalanceLog_cvMainID] ON [dbo].[caBalanceLog]
(
	[cvMainID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_caCvFinder_caMainID]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_caCvFinder_caMainID] ON [dbo].[caCvFinder]
(
	[caMainID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_caCvIntention_AddDate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_caCvIntention_AddDate] ON [dbo].[caCvIntention]
(
	[AddDate] DESC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_caCvIntention_caMainID]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_caCvIntention_caMainID] ON [dbo].[caCvIntention]
(
	[caMainID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_caCvIntention_cvMainId]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_caCvIntention_cvMainId] ON [dbo].[caCvIntention]
(
	[cvMainID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_caCvIntention_JobId]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_caCvIntention_JobId] ON [dbo].[caCvIntention]
(
	[JobId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_cacvIntention_ReplyDate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_cacvIntention_ReplyDate] ON [dbo].[caCvIntention]
(
	[JobId] ASC,
	[Reply] ASC,
	[ReplyDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_caCvQuotaLog_caMainID]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_caCvQuotaLog_caMainID] ON [dbo].[caCvQuotaLog]
(
	[caMainID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_cacvQuotaLog_cpMainID]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_cacvQuotaLog_cpMainID] ON [dbo].[caCvQuotaLog]
(
	[cpMainID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_caCvRemark_caMainID]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_caCvRemark_caMainID] ON [dbo].[caCvRemark]
(
	[caMainID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_caCvRemark_cvMainID]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_caCvRemark_cvMainID] ON [dbo].[caCvRemark]
(
	[cvMainID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_caCvViewLog_AddDate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_caCvViewLog_AddDate] ON [dbo].[caCvViewLog]
(
	[AddDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_CaCvViewLog_caMainId]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_CaCvViewLog_caMainId] ON [dbo].[caCvViewLog]
(
	[caMainID] ASC,
	[AddDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_caDailyGiftLog_caMainId]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_caDailyGiftLog_caMainId] ON [dbo].[caDailyGiftLog]
(
	[caMainID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_caFavorate_caMainID]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_caFavorate_caMainID] ON [dbo].[caFavorate]
(
	[caMainID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_caFavorate_JobId]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_caFavorate_JobId] ON [dbo].[caFavorate]
(
	[JobId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_caFavorateMark_caMainID]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_caFavorateMark_caMainID] ON [dbo].[caFavorateMark]
(
	[caMainID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_caFeedback_AddDate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_caFeedback_AddDate] ON [dbo].[caFeedback]
(
	[AddDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_caFeedback_Complex]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_caFeedback_Complex] ON [dbo].[caFeedback]
(
	[dcProvinceID] ASC,
	[AddDate] ASC,
	[IsReply] ASC,
	[ReplyDate] ASC,
	[ReplyMan] ASC,
	[ViewDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_caFeedback_dcProvinceID]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_caFeedback_dcProvinceID] ON [dbo].[caFeedback]
(
	[dcProvinceID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_caFeedback_Homepage]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_caFeedback_Homepage] ON [dbo].[caFeedback]
(
	[HomePage] ASC,
	[AddDate] ASC,
	[dcProvinceID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_caGetPasswordLog_AddDate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_caGetPasswordLog_AddDate] ON [dbo].[caGetPasswordLog]
(
	[AddDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_caGetPasswordLog_caMainID]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_caGetPasswordLog_caMainID] ON [dbo].[caGetPasswordLog]
(
	[caMainID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_caGetPasswordLog_Email]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_caGetPasswordLog_Email] ON [dbo].[caGetPasswordLog]
(
	[Email] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_caGetPasswordLog_IP]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_caGetPasswordLog_IP] ON [dbo].[caGetPasswordLog]
(
	[IP] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_caGetPasswordLog_UserName]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_caGetPasswordLog_UserName] ON [dbo].[caGetPasswordLog]
(
	[UserName] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_caInterviewTemplate_caMainID]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_caInterviewTemplate_caMainID] ON [dbo].[caInterviewTemplate]
(
	[caMainID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_caJobCvMatch_Complex]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_caJobCvMatch_Complex] ON [dbo].[caJobCvMatch]
(
	[JobID] ASC,
	[MatchCvMainID] ASC,
	[AddDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = 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_caJobResumePre_Complex]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_caJobResumePre_Complex] ON [dbo].[caJobResumePre]
(
	[AtPlace] ASC,
	[BirthDay] ASC,
	[ResumeID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = OFF) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_caLogin_LoginCookies]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_caLogin_LoginCookies] ON [dbo].[caLoginLog]
(
	[LoginCookies] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = OFF) ON [Index]
GO
/****** Object:  Index [IX_caLoginLog_AddDate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_caLoginLog_AddDate] ON [dbo].[caLoginLog]
(
	[AddDate] ASC
)
INCLUDE ( 	[caMainID]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_caLoginLog_Complex]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_caLoginLog_Complex] ON [dbo].[caLoginLog]
(
	[AddDate] DESC,
	[caMainID] ASC,
	[LoginCookies] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = OFF) ON [Index]
GO
/****** Object:  Index [IX_camain_AccountType]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_camain_AccountType] ON [dbo].[caMain]
(
	[AccountType] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_caMain_Email]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_caMain_Email] ON [dbo].[caMain]
(
	[EMail] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_camain_EmailSentType]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_camain_EmailSentType] ON [dbo].[caMain]
(
	[EmailSentType] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_camain_Gender]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_camain_Gender] ON [dbo].[caMain]
(
	[Gender] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_camain_IsDelete]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_camain_IsDelete] ON [dbo].[caMain]
(
	[IsDelete] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_camain_IsPause]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_camain_IsPause] ON [dbo].[caMain]
(
	[IsPause] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_camain_LastModifyDate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_camain_LastModifyDate] ON [dbo].[caMain]
(
	[LastModifyDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_caMain_Mobile]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_caMain_Mobile] ON [dbo].[caMain]
(
	[Mobile] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_camain_Name]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_camain_Name] ON [dbo].[caMain]
(
	[Name] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_camain_RegDate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_camain_RegDate] ON [dbo].[caMain]
(
	[RegDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_caMain_UserName]    Script Date: 2018/9/25 12:40:12 ******/
CREATE UNIQUE NONCLUSTERED INDEX [IX_caMain_UserName] ON [dbo].[caMain]
(
	[UserName] 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 [Index]
GO
SET ARITHABORT ON
SET CONCAT_NULL_YIELDS_NULL ON
SET QUOTED_IDENTIFIER ON
SET ANSI_NULLS ON
SET ANSI_PADDING ON
SET ANSI_WARNINGS ON
SET NUMERIC_ROUNDABORT OFF

GO
/****** Object:  Index [IX_caMain_UserNameLower]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_caMain_UserNameLower] ON [dbo].[caMain]
(
	[UserNameLower] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_CaMainID_TelePhone]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_CaMainID_TelePhone] ON [dbo].[caMain]
(
	[Telephone] ASC
)
INCLUDE ( 	[ID]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_caOnline_Refreshdate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_caOnline_Refreshdate] ON [dbo].[CaOnline]
(
	[RefreshDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_caOperationLog_AddDate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_caOperationLog_AddDate] ON [dbo].[caOperationLog]
(
	[AddDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_caOrder_adddate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_caOrder_adddate] ON [dbo].[caOrder]
(
	[AddDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [Ix_CaOrder_BalanceOrderType]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [Ix_CaOrder_BalanceOrderType] ON [dbo].[caOrder]
(
	[OrderType] ASC,
	[Balance] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_caOrder_companyname]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_caOrder_companyname] ON [dbo].[caOrder]
(
	[CompanyName] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [Ix_caOrder_Complex1]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [Ix_caOrder_Complex1] ON [dbo].[caOrder]
(
	[OrderType] ASC,
	[BeginDate] ASC,
	[EndDate] ASC,
	[cpMainID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_caOrder_Complex2]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_caOrder_Complex2] ON [dbo].[caOrder]
(
	[cpMainID] ASC,
	[BeginDate] DESC,
	[EndDate] DESC,
	[OrderType] ASC,
	[OpenDate] DESC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_caOrder_cpMainId]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_caOrder_cpMainId] ON [dbo].[caOrder]
(
	[cpMainID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_caOrder_enddate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_caOrder_enddate] ON [dbo].[caOrder]
(
	[EndDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_CaOrder_MainOrderID]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_CaOrder_MainOrderID] ON [dbo].[caOrder]
(
	[MainOrderID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_caOrder_manageruserid]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_caOrder_manageruserid] ON [dbo].[caOrder]
(
	[Manageruserid] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_caOrder_opendate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_caOrder_opendate] ON [dbo].[caOrder]
(
	[OpenDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_caOrder_ProvinceId]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_caOrder_ProvinceId] ON [dbo].[caOrder]
(
	[ProvinceID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_caOrderRemarks_adddate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_caOrderRemarks_adddate] ON [dbo].[caOrderRemarks]
(
	[AddDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_caOrderRemarks_managerid]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_caOrderRemarks_managerid] ON [dbo].[caOrderRemarks]
(
	[ManagerId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_caOrderRemarks_orderid]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_caOrderRemarks_orderid] ON [dbo].[caOrderRemarks]
(
	[OrderId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_caPlaint_AddDate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_caPlaint_AddDate] ON [dbo].[caPlaint]
(
	[AddDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_caPlaint_cvMainId]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_caPlaint_cvMainId] ON [dbo].[caPlaint]
(
	[cvMainID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_caPlaint_ProcessDate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_caPlaint_ProcessDate] ON [dbo].[caPlaint]
(
	[ProcessDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_caSmsLog_CaOrderId]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_caSmsLog_CaOrderId] ON [dbo].[caSmsLog]
(
	[caOrderId] ASC
)
INCLUDE ( 	[caMainId]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_CaSmsLog_Complex1]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_CaSmsLog_Complex1] ON [dbo].[caSmsLog]
(
	[MsgType] ASC,
	[RelationId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_CaSmsLog_SmsMessageLogId]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_CaSmsLog_SmsMessageLogId] ON [dbo].[caSmsLog]
(
	[SmsMessageLogId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_caVerifyLog_Mobile]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_caVerifyLog_Mobile] ON [dbo].[caVerifyLog]
(
	[Mobile] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [Ix_ChatOnline_caMainId]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [Ix_ChatOnline_caMainId] ON [dbo].[ChatOnline]
(
	[caMainID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_ChatOnline_Complex]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_ChatOnline_Complex] ON [dbo].[ChatOnline]
(
	[cvMainID] ASC,
	[caMainID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
/****** Object:  Index [Ix_ChatOnline_cvMainId]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [Ix_ChatOnline_cvMainId] ON [dbo].[ChatOnline]
(
	[cvMainID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_ColdCustomer_AddMan]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_ColdCustomer_AddMan] ON [dbo].[ColdCustomer]
(
	[AddMan] ASC,
	[AddDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
/****** Object:  Index [IX_ColdCustomer_cpMainId]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_ColdCustomer_cpMainId] ON [dbo].[ColdCustomer]
(
	[CpMainID] ASC
)
INCLUDE ( 	[ID]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_Comments_Complex]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_Comments_Complex] ON [dbo].[Comments]
(
	[CpMainID] ASC,
	[CommentType] ASC,
	[VerifyDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_company_black_companyname]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_company_black_companyname] ON [dbo].[Company_Black]
(
	[CompanyName] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_company_black_email]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_company_black_email] ON [dbo].[Company_Black]
(
	[email] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_company_black_mobile]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_company_black_mobile] ON [dbo].[Company_Black]
(
	[mobile] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [Ix_Company_Month_YearMonth]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [Ix_Company_Month_YearMonth] ON [dbo].[Company_Month]
(
	[YearMonth] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_company_xinxi]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_company_xinxi] ON [dbo].[Company_Xinxi]
(
	[RegDate] DESC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_company_xinxi_addman]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_company_xinxi_addman] ON [dbo].[Company_Xinxi]
(
	[AddMan] ASC,
	[RegDate] ASC,
	[Email] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_company_xinxi_companyname]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_company_xinxi_companyname] ON [dbo].[Company_Xinxi]
(
	[CompanyName] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_Company_Xinxi_email]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_Company_Xinxi_email] ON [dbo].[Company_Xinxi]
(
	[Email] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_Company_Xinxi_IsHistory]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_Company_Xinxi_IsHistory] ON [dbo].[Company_Xinxi]
(
	[IsHistory] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_company_xinxi_province_id]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_company_xinxi_province_id] ON [dbo].[Company_Xinxi]
(
	[Province_Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_Company_Xinxi_regdate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_Company_Xinxi_regdate] ON [dbo].[Company_Xinxi]
(
	[RegDate] ASC,
	[IsHistory] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_Company_XInxi_Username]    Script Date: 2018/9/25 12:40:12 ******/
CREATE UNIQUE NONCLUSTERED INDEX [IX_Company_XInxi_Username] ON [dbo].[Company_Xinxi]
(
	[UserName] 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 [Index]
GO
SET ARITHABORT ON
SET CONCAT_NULL_YIELDS_NULL ON
SET QUOTED_IDENTIFIER ON
SET ANSI_NULLS ON
SET ANSI_PADDING ON
SET ANSI_WARNINGS ON
SET NUMERIC_ROUNDABORT OFF

GO
/****** Object:  Index [IX_Company_Xinxi_UserNameLower]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_Company_Xinxi_UserNameLower] ON [dbo].[Company_Xinxi]
(
	[UserNameLower] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_Companyinform_adDate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_Companyinform_adDate] ON [dbo].[CompanyInform]
(
	[AddDate] DESC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_companynotify_companyid]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_companynotify_companyid] ON [dbo].[CompanyNotify]
(
	[CompanyId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_companynotify_enddate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_companynotify_enddate] ON [dbo].[CompanyNotify]
(
	[EndDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_Consultant_Factor_only]    Script Date: 2018/9/25 12:40:12 ******/
CREATE UNIQUE NONCLUSTERED INDEX [IX_Consultant_Factor_only] ON [dbo].[Consultant_Factor]
(
	[YearMonth] ASC,
	[Sn] 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 [Index]
GO
/****** Object:  Index [IX_Contact_addDate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_Contact_addDate] ON [dbo].[Contact]
(
	[addDate] DESC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_Contact_begintime]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_Contact_begintime] ON [dbo].[Contact]
(
	[begintime] DESC,
	[ManagerUserId] ASC,
	[status] ASC,
	[Quality] ASC,
	[CompanyId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_Contact_begintime2]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_Contact_begintime2] ON [dbo].[Contact]
(
	[begintime] ASC,
	[addDate] ASC
)
INCLUDE ( 	[Id]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_Contact_CompanyId]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_Contact_CompanyId] ON [dbo].[Contact]
(
	[CompanyId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_Contact_Complex]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_Contact_Complex] ON [dbo].[Contact]
(
	[CloseDate] ASC,
	[CompanyId] ASC,
	[begintime] ASC,
	[status] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = OFF) ON [Index]
GO
/****** Object:  Index [IX_Contact_ManagerUserId]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_Contact_ManagerUserId] ON [dbo].[Contact]
(
	[ManagerUserId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_Contact_quality]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_Contact_quality] ON [dbo].[Contact]
(
	[Quality] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_Contact_stauts]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_Contact_stauts] ON [dbo].[Contact]
(
	[status] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_counter_Month_unique]    Script Date: 2018/9/25 12:40:12 ******/
CREATE UNIQUE NONCLUSTERED INDEX [IX_counter_Month_unique] ON [dbo].[counter_Month]
(
	[countMonth] ASC,
	[versionId] 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 [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [Ix_cpCertification_Complex]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [Ix_cpCertification_Complex] ON [dbo].[cpCertification]
(
	[cpMainID] ASC,
	[CompanyName] ASC,
	[CerStatus] ASC,
	[CerDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
/****** Object:  Index [Ix_cpCertification_cpMainId]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [Ix_cpCertification_cpMainId] ON [dbo].[cpCertification]
(
	[cpMainID] ASC
)
INCLUDE ( 	[ID]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [Ix_cpCompanyEmail_cpCertificationID]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [Ix_cpCompanyEmail_cpCertificationID] ON [dbo].[cpCompanyEmail]
(
	[cpCertificationID] ASC
)
INCLUDE ( 	[ID]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [Ix_cpCorporationAccount_cpCertificationID]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [Ix_cpCorporationAccount_cpCertificationID] ON [dbo].[cpCorporationAccount]
(
	[cpCertificationID] ASC
)
INCLUDE ( 	[ID]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_cpImage_AddDate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_cpImage_AddDate] ON [dbo].[cpImage]
(
	[AddDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_cpImage_CheckMan]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_cpImage_CheckMan] ON [dbo].[cpImage]
(
	[CheckMan] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_cpImage_ImgType]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_cpImage_ImgType] ON [dbo].[cpImage]
(
	[ImgType] ASC,
	[cpMainID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = OFF) ON [Index]
GO
/****** Object:  Index [IX_CpIndexPage_caMainID]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_CpIndexPage_caMainID] ON [dbo].[CpIndexPage]
(
	[caMainId] ASC,
	[AddDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_cpLicence_AddDate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_cpLicence_AddDate] ON [dbo].[cpLicence]
(
	[AddDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_cpLicence_CheckDate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_cpLicence_CheckDate] ON [dbo].[cpLicence]
(
	[CheckDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_cpLicence_CheckMan]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_cpLicence_CheckMan] ON [dbo].[cpLicence]
(
	[CheckMan] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_cpLicence_Complex]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_cpLicence_Complex] ON [dbo].[cpLicence]
(
	[CheckDate] ASC,
	[HasPassed] ASC,
	[cpMainID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = OFF) ON [Index]
GO
/****** Object:  Index [Ix_cpLicence_cpCertificationID]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [Ix_cpLicence_cpCertificationID] ON [dbo].[cpLicence]
(
	[cpCertificationID] ASC
)
INCLUDE ( 	[ID]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_cpLicence_cpMainID]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_cpLicence_cpMainID] ON [dbo].[cpLicence]
(
	[cpMainID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_cpLicenceChangeLog_AddDate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_cpLicenceChangeLog_AddDate] ON [dbo].[cpLicenceChangeLog]
(
	[AddDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_cpLicenceChangeLog_cpMainID]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_cpLicenceChangeLog_cpMainID] ON [dbo].[cpLicenceChangeLog]
(
	[cpMainID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_cpLicenceChangeLog_ManagerUserID]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_cpLicenceChangeLog_ManagerUserID] ON [dbo].[cpLicenceChangeLog]
(
	[ManagerUserID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_cpLicenceLog_AddDate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_cpLicenceLog_AddDate] ON [dbo].[cpLicenceLog]
(
	[AddDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_cpMain_Address]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_cpMain_Address] ON [dbo].[cpMain]
(
	[Address] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = OFF) ON [Index]
GO
SET ARITHABORT ON
SET CONCAT_NULL_YIELDS_NULL ON
SET QUOTED_IDENTIFIER ON
SET ANSI_NULLS ON
SET ANSI_PADDING ON
SET ANSI_WARNINGS ON
SET NUMERIC_ROUNDABORT OFF

GO
/****** Object:  Index [IX_cpMain_Complex1]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_cpMain_Complex1] ON [dbo].[cpMain]
(
	[Balance] ASC,
	[BalanceDate] ASC,
	[HasLicence] ASC,
	[Valid] ASC,
	[JobNumber] ASC,
	[RefreshDate] ASC,
	[UnlimitedDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_cpMain_Complex2]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_cpMain_Complex2] ON [dbo].[cpMain]
(
	[AddMan] ASC,
	[HasLicence] ASC,
	[RegisterMode] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ARITHABORT ON
SET CONCAT_NULL_YIELDS_NULL ON
SET QUOTED_IDENTIFIER ON
SET ANSI_NULLS ON
SET ANSI_PADDING ON
SET ANSI_WARNINGS ON
SET NUMERIC_ROUNDABORT OFF

GO
/****** Object:  Index [IX_cpMain_Complex3]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_cpMain_Complex3] ON [dbo].[cpMain]
(
	[Valid] ASC,
	[MemberType] ASC,
	[JobNumber] ASC,
	[RefreshDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_cpMain_Consultant]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_cpMain_Consultant] ON [dbo].[cpMain]
(
	[ConsultantID] ASC,
	[ConsultantDate] DESC,
	[MemberType] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = OFF) ON [Index]
GO
SET ARITHABORT ON
SET CONCAT_NULL_YIELDS_NULL ON
SET QUOTED_IDENTIFIER ON
SET ANSI_NULLS ON
SET ANSI_PADDING ON
SET ANSI_WARNINGS ON
SET NUMERIC_ROUNDABORT OFF

GO
/****** Object:  Index [IX_cpMain_dcCompanySizeID]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_cpMain_dcCompanySizeID] ON [dbo].[cpMain]
(
	[dcCompanySizeID] ASC,
	[Valid] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_cpmain_dcProvinceID]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_cpmain_dcProvinceID] ON [dbo].[cpMain]
(
	[dcProvinceID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_cpmain_dcRegionID]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_cpmain_dcRegionID] ON [dbo].[cpMain]
(
	[dcRegionID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_cpMain_DcSubSiteID]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_cpMain_DcSubSiteID] ON [dbo].[cpMain]
(
	[dcSubSiteID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ARITHABORT ON
SET CONCAT_NULL_YIELDS_NULL ON
SET QUOTED_IDENTIFIER ON
SET ANSI_NULLS ON
SET ANSI_PADDING ON
SET ANSI_WARNINGS ON
SET NUMERIC_ROUNDABORT OFF

GO
/****** Object:  Index [IX_cpMain_Homepage]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_cpMain_Homepage] ON [dbo].[cpMain]
(
	[RefreshDate] DESC,
	[dcRegionID] ASC,
	[MemberType] ASC,
	[JobNumber] ASC,
	[Valid] ASC,
	[dcProvinceID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ARITHABORT ON
SET CONCAT_NULL_YIELDS_NULL ON
SET QUOTED_IDENTIFIER ON
SET ANSI_NULLS ON
SET ANSI_PADDING ON
SET ANSI_WARNINGS ON
SET NUMERIC_ROUNDABORT OFF

GO
/****** Object:  Index [IX_cpMain_HomepageFix]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_cpMain_HomepageFix] ON [dbo].[cpMain]
(
	[dcProvinceID] ASC,
	[Valid] ASC,
	[JobNumber] ASC,
	[dcRegionID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = OFF) ON [Index]
GO
/****** Object:  Index [IX_cpMain_IsDelete]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_cpMain_IsDelete] ON [dbo].[cpMain]
(
	[IsDelete] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_cpMain_LastLoginDate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_cpMain_LastLoginDate] ON [dbo].[cpMain]
(
	[LastLoginDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = OFF) ON [PRIMARY]
GO
/****** Object:  Index [IX_cpMain_LastModifyDate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_cpMain_LastModifyDate] ON [dbo].[cpMain]
(
	[LastModifyDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ARITHABORT ON
SET CONCAT_NULL_YIELDS_NULL ON
SET QUOTED_IDENTIFIER ON
SET ANSI_NULLS ON
SET ANSI_PADDING ON
SET ANSI_WARNINGS ON
SET NUMERIC_ROUNDABORT OFF

GO
/****** Object:  Index [IX_cpMain_MemberType]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_cpMain_MemberType] ON [dbo].[cpMain]
(
	[MemberType] ASC,
	[Valid] ASC
)
INCLUDE ( 	[ID]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_cpmain_Name]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_cpmain_Name] ON [dbo].[cpMain]
(
	[Name] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_cpMain_Privi]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_cpMain_Privi] ON [dbo].[cpMain]
(
	[UnlimitedDate] ASC,
	[BalanceDate] ASC,
	[Balance] ASC,
	[MemberType] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_cpMain_Quality]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_cpMain_Quality] ON [dbo].[cpMain]
(
	[Quality] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = OFF) ON [Index]
GO
/****** Object:  Index [IX_cpMain_RefreshDate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_cpMain_RefreshDate] ON [dbo].[cpMain]
(
	[RefreshDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_cpMain_RegCapital]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_cpMain_RegCapital] ON [dbo].[cpMain]
(
	[RegCapital] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = OFF) ON [Index]
GO
/****** Object:  Index [IX_cpmain_RegDate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_cpmain_RegDate] ON [dbo].[cpMain]
(
	[RegDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_cpMain_RegisterIP]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_cpMain_RegisterIP] ON [dbo].[cpMain]
(
	[RegisterIP] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = OFF) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_cpMain_SecondId]    Script Date: 2018/9/25 12:40:12 ******/
CREATE UNIQUE NONCLUSTERED INDEX [IX_cpMain_SecondId] ON [dbo].[cpMain]
(
	[SecondId] 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 = OFF) ON [Index]
GO
SET ARITHABORT ON
SET CONCAT_NULL_YIELDS_NULL ON
SET QUOTED_IDENTIFIER ON
SET ANSI_NULLS ON
SET ANSI_PADDING ON
SET ANSI_WARNINGS ON
SET NUMERIC_ROUNDABORT OFF

GO
/****** Object:  Index [IX_cpMain_Valid]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_cpMain_Valid] ON [dbo].[cpMain]
(
	[Valid] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_cpMainPublish_DcSubSiteID]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_cpMainPublish_DcSubSiteID] ON [dbo].[cpMain]
(
	[dcSubSiteID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_cpMsin_ConsultantSearch]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_cpMsin_ConsultantSearch] ON [dbo].[cpMain]
(
	[ID] ASC,
	[HasLicence] ASC,
	[ConsultantID] ASC,
	[ConsultantDate] ASC,
	[IsAgent] ASC,
	[IsLimitLogin] ASC,
	[Islock] ASC,
	[IsDelete] ASC,
	[MemberType] ASC,
	[JobNumber] ASC,
	[RefreshDate] ASC,
	[LastLoginDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_cpMainPublish_Complex1]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_cpMainPublish_Complex1] ON [dbo].[cpMainPublish]
(
	[Balance] ASC,
	[BalanceDate] ASC,
	[HasLicence] ASC,
	[Valid] ASC,
	[RefreshDate] ASC,
	[UnlimitedDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_cpMainPublish_Complex3]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_cpMainPublish_Complex3] ON [dbo].[cpMainPublish]
(
	[Valid] ASC,
	[MemberType] ASC,
	[RefreshDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_cpMainPublish_dcCompanySizeID]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_cpMainPublish_dcCompanySizeID] ON [dbo].[cpMainPublish]
(
	[dcCompanySizeID] ASC,
	[Valid] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_cpmainPublish_dcProvinceId]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_cpmainPublish_dcProvinceId] ON [dbo].[cpMainPublish]
(
	[dcProvinceId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_cpmainPublish_dcRegionID]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_cpmainPublish_dcRegionID] ON [dbo].[cpMainPublish]
(
	[dcRegionID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_cpMainPublish_HasEnvironment]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_cpMainPublish_HasEnvironment] ON [dbo].[cpMainPublish]
(
	[HasEnvironment] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
/****** Object:  Index [IX_cpMainPublish_IsRefreshed]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_cpMainPublish_IsRefreshed] ON [dbo].[cpMainPublish]
(
	[IsRefreshed] ASC,
	[RefreshDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_cpMainPublish_LastLoginDate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_cpMainPublish_LastLoginDate] ON [dbo].[cpMainPublish]
(
	[LastLoginDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = OFF) ON [PRIMARY]
GO
/****** Object:  Index [IX_cpMainPublish_MemberType]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_cpMainPublish_MemberType] ON [dbo].[cpMainPublish]
(
	[MemberType] ASC,
	[Valid] ASC
)
INCLUDE ( 	[ID]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_cpmainPublish_Name]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_cpmainPublish_Name] ON [dbo].[cpMainPublish]
(
	[Name] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_cpMainPublish_Privi]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_cpMainPublish_Privi] ON [dbo].[cpMainPublish]
(
	[UnlimitedDate] ASC,
	[BalanceDate] ASC,
	[Balance] ASC,
	[MemberType] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_cpMainPublish_RefreshDate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_cpMainPublish_RefreshDate] ON [dbo].[cpMainPublish]
(
	[RefreshDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_cpMainPublish_Valid]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_cpMainPublish_Valid] ON [dbo].[cpMainPublish]
(
	[Valid] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [Ix_cpPersonalAccount_cpCertificationID]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [Ix_cpPersonalAccount_cpCertificationID] ON [dbo].[cpPersonalAccount]
(
	[cpCertificationID] ASC
)
INCLUDE ( 	[ID]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [ix_cppointcount_c2]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [ix_cppointcount_c2] ON [dbo].[cpPointCount]
(
	[CountDate] ASC,
	[TodayPoint] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
/****** Object:  Index [IX_cpPointCount_Complex]    Script Date: 2018/9/25 12:40:12 ******/
CREATE UNIQUE NONCLUSTERED INDEX [IX_cpPointCount_Complex] ON [dbo].[cpPointCount]
(
	[CountDate] ASC,
	[cpMainId] 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 [Index]
GO
/****** Object:  Index [IX_cpProductBulletin_Date]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_cpProductBulletin_Date] ON [dbo].[cpProductBulletin]
(
	[BeginDate] ASC,
	[EndDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_CpRealNameLog_cpMainId]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_CpRealNameLog_cpMainId] ON [dbo].[CpRealNameLog]
(
	[CpMainID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_cpSession_AddDate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_cpSession_AddDate] ON [dbo].[cpSession]
(
	[AddDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_cpSession_caMainID]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_cpSession_caMainID] ON [dbo].[cpSession]
(
	[caMainID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_cpSession_CheckDate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_cpSession_CheckDate] ON [dbo].[cpSession]
(
	[RefreshDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_customer_assign_ManagerUserId]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_customer_assign_ManagerUserId] ON [dbo].[Customer_Assign]
(
	[ManagerUserId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_customer_assign_province_Id]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_customer_assign_province_Id] ON [dbo].[Customer_Assign]
(
	[Province_Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_customer_target_adDate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_customer_target_adDate] ON [dbo].[Customer_Target]
(
	[addDate] DESC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_customer_target_Companyname]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_customer_target_Companyname] ON [dbo].[Customer_Target]
(
	[Companyname] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_customer_target_email]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_customer_target_email] ON [dbo].[Customer_Target]
(
	[Email] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_cvAppendix_dcAppendixID]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_cvAppendix_dcAppendixID] ON [dbo].[cvAppendix]
(
	[dcAppendixID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_cvAttachment_cvMainId]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_cvAttachment_cvMainId] ON [dbo].[cvAttachment]
(
	[cvMainID] ASC
)
INCLUDE ( 	[id]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_cveducation_Complex]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_cveducation_Complex] ON [dbo].[cvEducation]
(
	[Degree] ASC,
	[dcMajorID] ASC,
	[EduType] ASC,
	[GraduateCollage] ASC,
	[Graduation] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_cveducationPublish_Complex]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_cveducationPublish_Complex] ON [dbo].[cvEducationPublish]
(
	[Degree] ASC,
	[dcMajorID] ASC,
	[EduType] ASC,
	[GraduateCollage] ASC,
	[Graduation] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_cvExperience_Complex]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_cvExperience_Complex] ON [dbo].[cvExperience]
(
	[dcJobtypeID] ASC,
	[dcIndustryID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_cvExperience_dcJobType]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_cvExperience_dcJobType] ON [dbo].[cvExperience]
(
	[dcJobtypeID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_cvExperiencePublish_Complex]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_cvExperiencePublish_Complex] ON [dbo].[cvExperiencePublish]
(
	[dcJobtypeID] ASC,
	[dcIndustryID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_cvExperiencePublish_dcJobType]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_cvExperiencePublish_dcJobType] ON [dbo].[cvExperiencePublish]
(
	[dcJobtypeID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_cvIndustry_dcIndustryID]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_cvIndustry_dcIndustryID] ON [dbo].[cvIndustry]
(
	[dcIndustryID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = OFF) ON [Index]
GO
/****** Object:  Index [IX_cvIndustryPublish_dcIndustryID]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_cvIndustryPublish_dcIndustryID] ON [dbo].[cvIndustryPublish]
(
	[dcIndustryID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = OFF) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_CvInfo_JobName]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_CvInfo_JobName] ON [dbo].[cvInfo]
(
	[JobName] ASC
)
INCLUDE ( 	[cvMainId]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_cvJobPlace_DcRegionID]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_cvJobPlace_DcRegionID] ON [dbo].[cvJobPlace]
(
	[dcRegionID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = OFF) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_cvJobPlacePublish_DcRegionID]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_cvJobPlacePublish_DcRegionID] ON [dbo].[cvJobPlacePublish]
(
	[dcRegionID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = OFF) ON [Index]
GO
/****** Object:  Index [IX_cvJobType_dcJobTypeID]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_cvJobType_dcJobTypeID] ON [dbo].[cvJobType]
(
	[dcJobTypeID] ASC,
	[cvMainID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = OFF) ON [Index]
GO
/****** Object:  Index [IX_cvJobTypePublish_dcJobTypeID]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_cvJobTypePublish_dcJobTypeID] ON [dbo].[cvJobTypePublish]
(
	[dcJobTypeID] ASC,
	[cvMainID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = OFF) ON [Index]
GO
/****** Object:  Index [IX_cvlanguage_LanguageType]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_cvlanguage_LanguageType] ON [dbo].[cvLanguage]
(
	[LanguageType] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_cvLanguage_Unique]    Script Date: 2018/9/25 12:40:12 ******/
CREATE UNIQUE NONCLUSTERED INDEX [IX_cvLanguage_Unique] ON [dbo].[cvLanguage]
(
	[cvMainID] ASC,
	[LanguageType] 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 [Index]
GO
/****** Object:  Index [IX_cvlanguagePublish_LanguageType]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_cvlanguagePublish_LanguageType] ON [dbo].[cvLanguagePublish]
(
	[LanguageType] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_cvLanguagePublish_Unique]    Script Date: 2018/9/25 12:40:12 ******/
CREATE UNIQUE NONCLUSTERED INDEX [IX_cvLanguagePublish_Unique] ON [dbo].[cvLanguagePublish]
(
	[cvMainID] ASC,
	[LanguageType] 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 [Index]
GO
/****** Object:  Index [IX_cvMain_Complex1]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_cvMain_Complex1] ON [dbo].[cvMain]
(
	[Valid] ASC,
	[RefreshDate] DESC,
	[LastJobTypeID] ASC,
	[LastIndustryID] ASC,
	[RelatedWorkYears] ASC,
	[dcSalaryID] ASC,
	[IsNegotiable] ASC,
	[Degree] ASC,
	[EmployType] ASC,
	[SubNodeNum] ASC,
	[paMainID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_cvMain_Complex2]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_cvMain_Complex2] ON [dbo].[cvMain]
(
	[cvLevel] ASC,
	[cvLevelEng] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_cvMain_Complex3]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_cvMain_Complex3] ON [dbo].[cvMain]
(
	[IscvHidden] ASC,
	[cvLevel] ASC,
	[cvLevelEng] ASC,
	[VerifyResult] ASC,
	[VerifyResultEng] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_cvMain_IsOpen]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_cvMain_IsOpen] ON [dbo].[cvMain]
(
	[isOpen] ASC,
	[Degree] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_cvMain_OpenSet]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_cvMain_OpenSet] ON [dbo].[cvMain]
(
	[Valid] ASC,
	[isOpen] ASC,
	[Degree] ASC,
	[paMainID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_cvmain_RefreshDate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_cvmain_RefreshDate] ON [dbo].[cvMain]
(
	[RefreshDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_CvMain_SecondId]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_CvMain_SecondId] ON [dbo].[cvMain]
(
	[SecondId] ASC
)
INCLUDE ( 	[ID]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_cvMain_VerifyResult]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_cvMain_VerifyResult] ON [dbo].[cvMain]
(
	[VerifyResult] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_cvMainPublish_Complex1]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_cvMainPublish_Complex1] ON [dbo].[cvMainPublish]
(
	[Valid] ASC,
	[RefreshDate] DESC,
	[LastJobTypeID] ASC,
	[LastIndustryID] ASC,
	[RelatedWorkYears] ASC,
	[dcSalaryID] ASC,
	[IsNegotiable] ASC,
	[Degree] ASC,
	[SubNodeNum] ASC,
	[EmployType] ASC,
	[paMainID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_cvmainPublish_RefreshDate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_cvmainPublish_RefreshDate] ON [dbo].[cvMainPublish]
(
	[RefreshDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_cvMainPublish_SecondId]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_cvMainPublish_SecondId] ON [dbo].[cvMainPublish]
(
	[SecondId] ASC
)
INCLUDE ( 	[ID],
	[paMainID]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_Datereport_countDate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_Datereport_countDate] ON [dbo].[Datereport]
(
	[CountDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_Datereport_Province_Id]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_Datereport_Province_Id] ON [dbo].[Datereport]
(
	[Province_Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_dcAutoEmail_Email]    Script Date: 2018/9/25 12:40:12 ******/
CREATE UNIQUE NONCLUSTERED INDEX [IX_dcAutoEmail_Email] ON [dbo].[dcAutoEmail]
(
	[Email] 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 [Index]
GO
/****** Object:  Index [IX_dcIpPlace_IpStart]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_dcIpPlace_IpStart] ON [dbo].[dcIPPlace]
(
	[IPStart] DESC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_dcJobName_Name]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_dcJobName_Name] ON [dbo].[dcJobName]
(
	[Name] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
/****** Object:  Index [IX_dcJobType_ParentID]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_dcJobType_ParentID] ON [dbo].[dcJobType]
(
	[ParentID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_dcJobType_ParentID2]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_dcJobType_ParentID2] ON [dbo].[dcJobType]
(
	[ParentID2] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_dcJobType_ParentID3]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_dcJobType_ParentID3] ON [dbo].[dcJobType]
(
	[ParentID3] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_dcJobTypeSimilar_dcJobTypeId]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_dcJobTypeSimilar_dcJobTypeId] ON [dbo].[dcJobTypeSimilar]
(
	[dcJobTypeId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_dcMajorKeyword_Complex]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_dcMajorKeyword_Complex] ON [dbo].[dcMajorKeyword]
(
	[MajorName] ASC,
	[PinYin] ASC,
	[JianPin] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_dcMobileArea_Num]    Script Date: 2018/9/25 12:40:12 ******/
CREATE UNIQUE NONCLUSTERED INDEX [IX_dcMobileArea_Num] ON [dbo].[dcMobileArea]
(
	[Num] 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 [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_dcRegion_Unique]    Script Date: 2018/9/25 12:40:12 ******/
CREATE UNIQUE NONCLUSTERED INDEX [IX_dcRegion_Unique] ON [dbo].[dcRegion]
(
	[ParentID] ASC,
	[Description] 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 [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [Ix_dcSubSite_SubSiteUrl]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [Ix_dcSubSite_SubSiteUrl] ON [dbo].[dcSubSite]
(
	[SubSiteUrl] ASC,
	[ProvinceID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = OFF) ON [Index]
GO
/****** Object:  Index [IX_dcTelArea_AreaNo]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_dcTelArea_AreaNo] ON [dbo].[dcTelArea]
(
	[AreaNo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_dcVip_Complex]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_dcVip_Complex] ON [dbo].[dcVip]
(
	[dcProvinceID] ASC,
	[startDate] ASC,
	[endDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_dcFeeDetail_dcFeeID]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_dcFeeDetail_dcFeeID] ON [dbo].[dcVipDetail]
(
	[dcVipID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = OFF) ON [Index]
GO
/****** Object:  Index [IX_dwndoc_classid]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_dwndoc_classid] ON [dbo].[dwndoc]
(
	[classid] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_email_senttest_email]    Script Date: 2018/9/25 12:40:12 ******/
CREATE UNIQUE NONCLUSTERED INDEX [IX_email_senttest_email] ON [dbo].[Email_SentTest]
(
	[email] 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 [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_email_senttest_type]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_email_senttest_type] ON [dbo].[Email_SentTest]
(
	[emailtype] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_email_senttest_log_2]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_email_senttest_log_2] ON [dbo].[Email_SentTest_Log]
(
	[adddate] ASC,
	[type] ASC,
	[email_senttest_id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_email_senttest_log_adddate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_email_senttest_log_adddate] ON [dbo].[Email_SentTest_Log]
(
	[adddate] ASC,
	[email_senttest_id] ASC,
	[status] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_Emailcheck_ManagerUserID]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_Emailcheck_ManagerUserID] ON [dbo].[EmailCheck]
(
	[manageruserid] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_EmailCompany_AddDate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_EmailCompany_AddDate] ON [dbo].[EmailCompany]
(
	[AddDate] DESC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_EmailCompany_CompanyId]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_EmailCompany_CompanyId] ON [dbo].[EmailCompany]
(
	[CompanyId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_EmailDomain_only]    Script Date: 2018/9/25 12:40:12 ******/
CREATE UNIQUE NONCLUSTERED INDEX [IX_EmailDomain_only] ON [dbo].[EmailDomain]
(
	[EmailKey] ASC,
	[province_id] 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 [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_EmailType_email]    Script Date: 2018/9/25 12:40:12 ******/
CREATE UNIQUE NONCLUSTERED INDEX [IX_EmailType_email] ON [dbo].[EmailType]
(
	[EmailType] 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 [Index]
GO
/****** Object:  Index [IX_exInterview_AddDate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_exInterview_AddDate] ON [dbo].[exInterview]
(
	[AddDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_exInterview_JobID]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_exInterview_JobID] ON [dbo].[exInterview]
(
	[JobID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_exInterView_ReplyDate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_exInterView_ReplyDate] ON [dbo].[exInterview]
(
	[JobID] ASC,
	[Reply] ASC,
	[Replydate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_exInterview_ViewDate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_exInterview_ViewDate] ON [dbo].[exInterview]
(
	[ViewDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_exJobApply_AddDate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_exJobApply_AddDate] ON [dbo].[exJobApply]
(
	[AddDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_exJobApply_Complex]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_exJobApply_Complex] ON [dbo].[exJobApply]
(
	[AddDate] ASC,
	[JobID] ASC,
	[cvMainID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = OFF) ON [Index]
GO
/****** Object:  Index [IX_exJobApply_cvMainID]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_exJobApply_cvMainID] ON [dbo].[exJobApply]
(
	[cvMainID] ASC,
	[CompanyDeleted] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_ExJobApply_Date]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_ExJobApply_Date] ON [dbo].[exJobApply]
(
	[AddDate] ASC,
	[ReplyDate] ASC,
	[ViewDate] ASC
)
INCLUDE ( 	[JobID],
	[cvMainID]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
/****** Object:  Index [IX_exJobApply_JobId]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_exJobApply_JobId] ON [dbo].[exJobApply]
(
	[JobID] ASC,
	[AddDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = OFF) ON [Index]
GO
/****** Object:  Index [IX_exJobApply_JobID_CvMainID]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_exJobApply_JobID_CvMainID] ON [dbo].[exJobApply]
(
	[JobID] ASC,
	[cvMainID] ASC,
	[CompanyDeleted] ASC,
	[PersonDeleted] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_exJobApply_Reply]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_exJobApply_Reply] ON [dbo].[exJobApply]
(
	[Reply] ASC
)
INCLUDE ( 	[JobID]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = OFF) ON [Index]
GO
/****** Object:  Index [IX_ExJobApply_ReplyDate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_ExJobApply_ReplyDate] ON [dbo].[exJobApply]
(
	[ReplyDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_exJobApplyMonthTemp_CvMainId]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_exJobApplyMonthTemp_CvMainId] ON [dbo].[exJobApplyMonthTemp]
(
	[CvMainID] ASC
)
INCLUDE ( 	[id]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_exJobApplyMonthTemp_JobId]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_exJobApplyMonthTemp_JobId] ON [dbo].[exJobApplyMonthTemp]
(
	[JobId] ASC
)
INCLUDE ( 	[id]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_exMessageC2P_AddDate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_exMessageC2P_AddDate] ON [dbo].[exMessageC2P]
(
	[AddDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_exMessageC2P_camainID]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_exMessageC2P_camainID] ON [dbo].[exMessageC2P]
(
	[caMainID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_exMessageC2P_cvMainID]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_exMessageC2P_cvMainID] ON [dbo].[exMessageC2P]
(
	[cvMainID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_exMessageP2C_caMainID]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_exMessageP2C_caMainID] ON [dbo].[exMessageP2C]
(
	[caMainID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_exMessageP2C_cvMainID]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_exMessageP2C_cvMainID] ON [dbo].[exMessageP2C]
(
	[cvMainID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_ExtendLink_RunStatus]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_ExtendLink_RunStatus] ON [dbo].[ExtendLink]
(
	[RunStatus] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_ExtendLinkCheckLog_ExtendLinbkId]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_ExtendLinkCheckLog_ExtendLinbkId] ON [dbo].[ExtendLinkCheckLog]
(
	[ExtendLinkID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_FaxReceive_ManagerUserId]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_FaxReceive_ManagerUserId] ON [dbo].[FaxReceive]
(
	[ManagerUserId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_FaxReceive_RecievedDate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_FaxReceive_RecievedDate] ON [dbo].[FaxReceive]
(
	[ReceiveDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_FaxSend_AddDate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_FaxSend_AddDate] ON [dbo].[FaxSend]
(
	[AddDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_FaxSend_CompanyId]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_FaxSend_CompanyId] ON [dbo].[FaxSend]
(
	[CompanyId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_FaxSend_ManagerUserId]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_FaxSend_ManagerUserId] ON [dbo].[FaxSend]
(
	[ManagerUserId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_feedback_noreg_addDate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_feedback_noreg_addDate] ON [dbo].[Feedback_NoReg]
(
	[AddDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_feedback_noreg_province_Id]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_feedback_noreg_province_Id] ON [dbo].[Feedback_NoReg]
(
	[Province_Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_Feelog_CompanyId]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_Feelog_CompanyId] ON [dbo].[FeeLog]
(
	[Company_Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_FnBankDaybook_unique]    Script Date: 2018/9/25 12:40:12 ******/
CREATE UNIQUE NONCLUSTERED INDEX [IX_FnBankDaybook_unique] ON [dbo].[FnBankDaybook]
(
	[TsctDate] ASC,
	[Concern] ASC,
	[Balance] 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 [Index]
GO
/****** Object:  Index [IX_FnInvoice_adddate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_FnInvoice_adddate] ON [dbo].[FnInvoice]
(
	[AddDate] DESC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_FnInvoice_concern]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_FnInvoice_concern] ON [dbo].[FnInvoice]
(
	[Concern] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_FnInvoice_invoicemonth]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_FnInvoice_invoicemonth] ON [dbo].[FnInvoice]
(
	[InvoiceMonth] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_FnInvoice_makeoutdate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_FnInvoice_makeoutdate] ON [dbo].[FnInvoice]
(
	[MakeoutDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_FnInvoice_no]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_FnInvoice_no] ON [dbo].[FnInvoice]
(
	[No] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_FnInvoice_orderid]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_FnInvoice_orderid] ON [dbo].[FnInvoice]
(
	[OrderId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_FnInvoice_status]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_FnInvoice_status] ON [dbo].[FnInvoice]
(
	[Status] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_FnLetter_FnInvoiceID]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_FnLetter_FnInvoiceID] ON [dbo].[FnLetter]
(
	[FnInvoiceID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_FnLetter_postdate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_FnLetter_postdate] ON [dbo].[FnLetter]
(
	[PostDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_FnLetter_status]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_FnLetter_status] ON [dbo].[FnLetter]
(
	[Status] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_FnPICDaybook]    Script Date: 2018/9/25 12:40:12 ******/
CREATE UNIQUE NONCLUSTERED INDEX [IX_FnPICDaybook] ON [dbo].[FnPICDaybook]
(
	[Concern] ASC,
	[TsctDate] ASC,
	[Balance] ASC,
	[Paymethod] 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 [Index]
GO
/****** Object:  Index [IX_fpCommonSearch]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_fpCommonSearch] ON [dbo].[fpCommonSearch]
(
	[dcProvinceID] ASC,
	[SearchType] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = OFF) ON [Index]
GO
/****** Object:  Index [IX_fpFixPosition_AddDate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_fpFixPosition_AddDate] ON [dbo].[fpFixPositionOld]
(
	[AddDate] DESC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = OFF) ON [Index]
GO
/****** Object:  Index [IX_fpFixPosition_dcProvinceID]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_fpFixPosition_dcProvinceID] ON [dbo].[fpFixPositionOld]
(
	[dcProvinceId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = OFF) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_fpFixPosition_dcSubSiteID]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_fpFixPosition_dcSubSiteID] ON [dbo].[fpFixPositionOld]
(
	[dcRegionID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = OFF) ON [Index]
GO
/****** Object:  Index [IX_fpHomePageImage_dcProvinceId]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_fpHomePageImage_dcProvinceId] ON [dbo].[fpHomepageImage]
(
	[dcProvinceID] ASC,
	[ImageType] ASC,
	[AddDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_group_ManagerUser_1]    Script Date: 2018/9/25 12:40:12 ******/
CREATE UNIQUE NONCLUSTERED INDEX [IX_group_ManagerUser_1] ON [dbo].[group_ManagerUser]
(
	[Group_Id] ASC,
	[ManagerUser_Id] 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 [Index]
GO
/****** Object:  Index [IX_group_ManagerUser_group_Id]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_group_ManagerUser_group_Id] ON [dbo].[group_ManagerUser]
(
	[Group_Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_group_ManagerUser_ManagerUser_Id]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_group_ManagerUser_ManagerUser_Id] ON [dbo].[group_ManagerUser]
(
	[ManagerUser_Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_group_province_group_Id]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_group_province_group_Id] ON [dbo].[group_province]
(
	[Group_Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_group_province_province_Id]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_group_province_province_Id] ON [dbo].[group_province]
(
	[Province_Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_hpHighSalaryCompany_Complex]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_hpHighSalaryCompany_Complex] ON [dbo].[hpHighSalaryCompany]
(
	[CpMainID] ASC,
	[RefreshDate] ASC
)
INCLUDE ( 	[id]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_hpHighSalaryJob_dcRegionId]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_hpHighSalaryJob_dcRegionId] ON [dbo].[hpHighSalaryJob]
(
	[dcRegionID] ASC
)
INCLUDE ( 	[id]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_hpJobTypeCpLogo_]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_hpJobTypeCpLogo_] ON [dbo].[hpJobTypeCpLogo]
(
	[dcRegionID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_HRKpiPost_unique]    Script Date: 2018/9/25 12:40:12 ******/
CREATE UNIQUE NONCLUSTERED INDEX [IX_HRKpiPost_unique] ON [dbo].[HRKpiPost]
(
	[KpiPostname] 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 [Index]
GO
/****** Object:  Index [IX_info_Datereport_Complex1]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_info_Datereport_Complex1] ON [dbo].[info_Datereport]
(
	[CountDate] ASC,
	[Province_Id] ASC,
	[InfoManager_Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_info_Datereport_countDate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_info_Datereport_countDate] ON [dbo].[info_Datereport]
(
	[CountDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_info_Datereport_infoManager_Id]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_info_Datereport_infoManager_Id] ON [dbo].[info_Datereport]
(
	[InfoManager_Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_info_Datereport_provinceId]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_info_Datereport_provinceId] ON [dbo].[info_Datereport]
(
	[Province_Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_infoachieve_infoManager_Id]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_infoachieve_infoManager_Id] ON [dbo].[infoachieve]
(
	[InfoManager_Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_infoachieve_YearMonth]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_infoachieve_YearMonth] ON [dbo].[infoachieve]
(
	[YearMonth] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_infoEmailAnalyze_emailType_Id]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_infoEmailAnalyze_emailType_Id] ON [dbo].[infoEmailAnalyze]
(
	[EmailType_Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_infoEmailAnalyze_infoManagerUser_Id]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_infoEmailAnalyze_infoManagerUser_Id] ON [dbo].[infoEmailAnalyze]
(
	[InfoManager_Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_infoEmailAnalyze_weiyi]    Script Date: 2018/9/25 12:40:12 ******/
CREATE UNIQUE NONCLUSTERED INDEX [IX_infoEmailAnalyze_weiyi] ON [dbo].[infoEmailAnalyze]
(
	[YearMonth] ASC,
	[EmailType_Id] ASC,
	[InfoManager_Id] 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 [Index]
GO
/****** Object:  Index [IX_infoEmailAnalyze_YearMonth]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_infoEmailAnalyze_YearMonth] ON [dbo].[infoEmailAnalyze]
(
	[YearMonth] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_infolog_addDate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_infolog_addDate] ON [dbo].[infolog]
(
	[addDate] DESC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_infolog_infoManager_Id]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_infolog_infoManager_Id] ON [dbo].[infolog]
(
	[infoManager_Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_infolog_Ip]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_infolog_Ip] ON [dbo].[infolog]
(
	[Ip] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_innerer_loginDate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_innerer_loginDate] ON [dbo].[innerer]
(
	[LoginDate] DESC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_innerer_versionId]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_innerer_versionId] ON [dbo].[innerer]
(
	[VersionId] ASC,
	[Referer] ASC,
	[Ip] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_innerer_count_keywords_howMany]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_innerer_count_keywords_howMany] ON [dbo].[innerer_count_keywords]
(
	[HowMany] DESC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_innerer_count_keywords_Id]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_innerer_count_keywords_Id] ON [dbo].[innerer_count_keywords]
(
	[Referer_count_Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_innerer_count_keywords_keywords]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_innerer_count_keywords_keywords] ON [dbo].[innerer_count_keywords]
(
	[Keywords] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_innerer_count_countDate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_innerer_count_countDate] ON [dbo].[Innerer_Count0331]
(
	[CountDate] ASC,
	[Referer] ASC,
	[Province_Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_innerer_count_province_Id]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_innerer_count_province_Id] ON [dbo].[Innerer_Count0331]
(
	[Province_Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_innerer_count_referer]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_innerer_count_referer] ON [dbo].[Innerer_Count0331]
(
	[Referer] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_investigation_enddate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_investigation_enddate] ON [dbo].[Investigation]
(
	[EndDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_IpLog_AddDate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_IpLog_AddDate] ON [dbo].[IpLog]
(
	[adddate] DESC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_IpLog_ip]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_IpLog_ip] ON [dbo].[IpLog]
(
	[ip] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_IpLog_Daily_Complex]    Script Date: 2018/9/25 12:40:12 ******/
CREATE UNIQUE NONCLUSTERED INDEX [IX_IpLog_Daily_Complex] ON [dbo].[IpLog_Daily]
(
	[monthday] DESC,
	[ip] ASC,
	[type] 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 [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_IpLog_Daily_Ip]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_IpLog_Daily_Ip] ON [dbo].[IpLog_Daily]
(
	[ip] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_IpLog_Daily_monthday]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_IpLog_Daily_monthday] ON [dbo].[IpLog_Daily]
(
	[monthday] DESC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_IpVistAll_Ip]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_IpVistAll_Ip] ON [dbo].[IpVisitAll]
(
	[Ip] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [FOthers]
GO
/****** Object:  Index [IX_ivgt_answer_questionId]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_ivgt_answer_questionId] ON [dbo].[ivgt_answer]
(
	[QuestionId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_ivgt_question_investId]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_ivgt_question_investId] ON [dbo].[ivgt_question]
(
	[InvestId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_ivgt_question_onlyone]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_ivgt_question_onlyone] ON [dbo].[ivgt_question]
(
	[InvestId] ASC,
	[Power] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_IvrList_addDate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_IvrList_addDate] ON [dbo].[IvrList]
(
	[AddDate] DESC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_IvrList_calledno]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_IvrList_calledno] ON [dbo].[IvrList]
(
	[CalledNo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_IvrList_callno]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_IvrList_callno] ON [dbo].[IvrList]
(
	[CallNo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [ix_ivrlist_callsheetid]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [ix_ivrlist_callsheetid] ON [dbo].[IvrList]
(
	[CallsheetId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_IvrList_callstate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_IvrList_callstate] ON [dbo].[IvrList]
(
	[CallState] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_IvrList_callType]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_IvrList_callType] ON [dbo].[IvrList]
(
	[CallType] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_IvrList_endtime]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_IvrList_endtime] ON [dbo].[IvrList]
(
	[Endtime] DESC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_IvrList_exten]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_IvrList_exten] ON [dbo].[IvrList]
(
	[Exten] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_IvrList_state]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_IvrList_state] ON [dbo].[IvrList]
(
	[State] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_Ivrlist_Day_ManagerUserId]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_Ivrlist_Day_ManagerUserId] ON [dbo].[Ivrlist_Day]
(
	[ManagerUserId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_job_AddDate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_job_AddDate] ON [dbo].[Job]
(
	[AddDate] DESC,
	[cpMainID] ASC,
	[caMainID] ASC,
	[EMailSendFreq] ASC,
	[EMailSendNumber] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_Job_caMainID]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_Job_caMainID] ON [dbo].[Job]
(
	[caMainID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_Job_Complex2]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_Job_Complex2] ON [dbo].[Job]
(
	[Valid] ASC,
	[RefreshDate] DESC,
	[cpMainID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_Job_IssueEnd]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_Job_IssueEnd] ON [dbo].[Job]
(
	[IssueEnd] ASC,
	[ID] ASC
)
INCLUDE ( 	[cpMainID]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
/****** Object:  Index [IX_job_lastemaildate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_job_lastemaildate] ON [dbo].[Job]
(
	[LastEmailDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_job_LastModifyDate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_job_LastModifyDate] ON [dbo].[Job]
(
	[LastModifyDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_job_RefreshDate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_job_RefreshDate] ON [dbo].[Job]
(
	[RefreshDate] DESC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_Job_SecondId]    Script Date: 2018/9/25 12:40:12 ******/
CREATE UNIQUE NONCLUSTERED INDEX [IX_Job_SecondId] ON [dbo].[Job]
(
	[SecondId] 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 = OFF) ON [Index]
GO
/****** Object:  Index [IX_JobDeleted_DeleteDate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_JobDeleted_DeleteDate] ON [dbo].[JobDeleted]
(
	[DeleteDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_JobPublish_caMainId]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_JobPublish_caMainId] ON [dbo].[JobPublish]
(
	[caMainId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_JobPublish_Complex1]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_JobPublish_Complex1] ON [dbo].[JobPublish]
(
	[RefreshDate] ASC,
	[Valid] ASC,
	[dcRegionID] ASC,
	[dcJobTypeID] ASC,
	[dcSalaryID] ASC,
	[MinExperience] ASC,
	[dcEducationID] ASC,
	[EmployType] ASC,
	[Lng] ASC,
	[Lat] ASC,
	[Welfare1] ASC,
	[Welfare2] ASC,
	[Welfare3] ASC,
	[Welfare9] ASC,
	[Welfare10] ASC,
	[Welfare13] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_JobPublish_Complex2]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_JobPublish_Complex2] ON [dbo].[JobPublish]
(
	[Valid] ASC,
	[RefreshDate] DESC,
	[cpMainID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_JobPublish_Complex3]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_JobPublish_Complex3] ON [dbo].[JobPublish]
(
	[Lng] ASC,
	[Lat] ASC,
	[Valid] ASC,
	[dcJobTypeID] ASC,
	[RefreshDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_JobPublish_dcRegionID]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_JobPublish_dcRegionID] ON [dbo].[JobPublish]
(
	[dcRegionID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = OFF) ON [Index]
GO
/****** Object:  Index [IX_jobPublish_LastModifyDate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_jobPublish_LastModifyDate] ON [dbo].[JobPublish]
(
	[LastModifyDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_jobPublish_RefreshDate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_jobPublish_RefreshDate] ON [dbo].[JobPublish]
(
	[RefreshDate] DESC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_JobPublish_SycDate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_JobPublish_SycDate] ON [dbo].[JobPublish]
(
	[SycDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [CP]
GO
/****** Object:  Index [IX_JobPublish_Welfare]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_JobPublish_Welfare] ON [dbo].[JobPublish]
(
	[Welfare7] ASC,
	[Welfare8] ASC,
	[Welfare11] ASC,
	[Welfare12] ASC,
	[Welfare14] ASC,
	[Welfare15] ASC,
	[Welfare16] ASC,
	[Welfare17] ASC,
	[Welfare18] ASC,
	[Welfare4] ASC,
	[Welfare5] ASC,
	[Welfare6] ASC,
	[Welfare19] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_JobRefreshLog_CaOrderId]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_JobRefreshLog_CaOrderId] ON [dbo].[jobRefreshLog]
(
	[orderId] ASC
)
INCLUDE ( 	[id]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_jobRefreshLog_cpMainId]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_jobRefreshLog_cpMainId] ON [dbo].[jobRefreshLog]
(
	[cpMainId] ASC
)
INCLUDE ( 	[id]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_JobRefreshLog_JobId]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_JobRefreshLog_JobId] ON [dbo].[jobRefreshLog]
(
	[jobId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_jobRefreshLog_JobRefreshSetId]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_jobRefreshLog_JobRefreshSetId] ON [dbo].[jobRefreshLog]
(
	[jobRefreshSetId] ASC
)
INCLUDE ( 	[id]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_jobRefreshLog_preRefreshDateTime]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_jobRefreshLog_preRefreshDateTime] ON [dbo].[jobRefreshLog]
(
	[preRefreshDateTime] ASC,
	[runDateTime] ASC
)
INCLUDE ( 	[id]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_JobRefreshLog_temp_Complex1]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_JobRefreshLog_temp_Complex1] ON [dbo].[JobRefreshLog_temp]
(
	[addDate] DESC,
	[cpMainId] ASC
)
INCLUDE ( 	[id]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_JobRefreshLog_temp_jobId]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_JobRefreshLog_temp_jobId] ON [dbo].[JobRefreshLog_temp]
(
	[jobId] ASC
)
INCLUDE ( 	[id]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_JobRefreshLog_temp_JobRefreshSetId]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_JobRefreshLog_temp_JobRefreshSetId] ON [dbo].[JobRefreshLog_temp]
(
	[jobRefreshSetId] ASC
)
INCLUDE ( 	[id]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_jobRefreshOldCompany_cpMainId]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_jobRefreshOldCompany_cpMainId] ON [dbo].[jobRefreshOldCompany]
(
	[cpMainId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_jobRefreshSet_caMainId]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_jobRefreshSet_caMainId] ON [dbo].[jobRefreshSet]
(
	[caMainId] ASC
)
INCLUDE ( 	[id]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_jobRefreshSet_JobId]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_jobRefreshSet_JobId] ON [dbo].[jobRefreshSet]
(
	[jobId] ASC
)
INCLUDE ( 	[id]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_JobSimilar_Complex]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_JobSimilar_Complex] ON [dbo].[JobSimilar]
(
	[dcJobTypeID] ASC,
	[dcRegionID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_JobSubScription_AddDate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_JobSubScription_AddDate] ON [dbo].[JobSubScription]
(
	[AddDate] ASC,
	[paJobFinderID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_jobTags_JobId]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_jobTags_JobId] ON [dbo].[jobTags]
(
	[JobID] ASC
)
INCLUDE ( 	[id]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_JobTemplate_CaMainID]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_JobTemplate_CaMainID] ON [dbo].[JobTemplate]
(
	[caMainId] ASC
)
INCLUDE ( 	[Id]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
/****** Object:  Index [NonClusteredIndex-KeyWordProcessLog-crDate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [NonClusteredIndex-KeyWordProcessLog-crDate] ON [dbo].[KeyWordProcessLog]
(
	[crDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [NonClusteredIndex-KeyWordProcessLog-keyword]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [NonClusteredIndex-KeyWordProcessLog-keyword] ON [dbo].[KeyWordProcessLog]
(
	[Keyword] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [NonClusteredIndex-KeyWordProcessLog-operdate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [NonClusteredIndex-KeyWordProcessLog-operdate] ON [dbo].[KeyWordProcessLog]
(
	[OperDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_knowledge_addDate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_knowledge_addDate] ON [dbo].[knowledge]
(
	[addDate] DESC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_knowledge_ManagerUserId]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_knowledge_ManagerUserId] ON [dbo].[knowledge]
(
	[ManagerUserId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_KPI_unique]    Script Date: 2018/9/25 12:40:12 ******/
CREATE UNIQUE NONCLUSTERED INDEX [IX_KPI_unique] ON [dbo].[KPI]
(
	[ManagerUserId] ASC,
	[YearMonth] 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 [Index]
GO
/****** Object:  Index [[IX_KPI_IE _receiver]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [[IX_KPI_IE _receiver] ON [dbo].[KPI_IE]
(
	[Receiver] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_KPI_IE]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_KPI_IE] ON [dbo].[KPI_IE]
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_KPI_IE_addDate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_KPI_IE_addDate] ON [dbo].[KPI_IE]
(
	[AddDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_KPI_IE_CompleteDate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_KPI_IE_CompleteDate] ON [dbo].[KPI_IE]
(
	[CompleteDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_KPI_IE_expectCompleteDate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_KPI_IE_expectCompleteDate] ON [dbo].[KPI_IE]
(
	[expectCompleteDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_KPI_IE_receiver]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_KPI_IE_receiver] ON [dbo].[KPI_IE]
(
	[Receiver] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_KPI_IE_reply_Date]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_KPI_IE_reply_Date] ON [dbo].[KPI_IE]
(
	[reply_Date] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_KPI_IE_sender]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_KPI_IE_sender] ON [dbo].[KPI_IE]
(
	[Sender] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_KPI_IE_status]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_KPI_IE_status] ON [dbo].[KPI_IE]
(
	[status] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_KPI_addDate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_KPI_addDate] ON [dbo].[KPI_KM]
(
	[AddDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_KPI_KM_reply_Date]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_KPI_KM_reply_Date] ON [dbo].[KPI_KM]
(
	[Reply_Date] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_KPI_KM_sender]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_KPI_KM_sender] ON [dbo].[KPI_KM]
(
	[Sender] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_KPI_KM_status]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_KPI_KM_status] ON [dbo].[KPI_KM]
(
	[Status] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_KPI_receiver]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_KPI_receiver] ON [dbo].[KPI_KM]
(
	[Receiver] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_KPI_LP_receiver]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_KPI_LP_receiver] ON [dbo].[KPI_LP]
(
	[Receiver] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_KPI_LP_sender]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_KPI_LP_sender] ON [dbo].[KPI_LP]
(
	[Sender] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_KPI_LP_status]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_KPI_LP_status] ON [dbo].[KPI_LP]
(
	[Status] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_KPI_OC_ManagerUserId]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_KPI_OC_ManagerUserId] ON [dbo].[KPI_OC]
(
	[ManagerUserId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_KPI_OC_YearMonth]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_KPI_OC_YearMonth] ON [dbo].[KPI_OC]
(
	[YearMonth] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_KPI_SA_ManagerUserId]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_KPI_SA_ManagerUserId] ON [dbo].[KPI_SA]
(
	[ManagerUserId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_KPI_SA_only]    Script Date: 2018/9/25 12:40:12 ******/
CREATE UNIQUE NONCLUSTERED INDEX [IX_KPI_SA_only] ON [dbo].[KPI_SA]
(
	[YearMonth] ASC,
	[ManagerUserId] 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 [Index]
GO
/****** Object:  Index [IX_KPI_SA_YearMonth]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_KPI_SA_YearMonth] ON [dbo].[KPI_SA]
(
	[YearMonth] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_Link_announceDate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_Link_announceDate] ON [dbo].[Link]
(
	[AnnounceDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_Link_friendlist_first]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_Link_friendlist_first] ON [dbo].[Link]
(
	[Power] DESC,
	[PowerAll] DESC,
	[AnnounceDate] DESC,
	[VersionId] ASC,
	[Valid] ASC,
	[Type] ASC,
	[Vision] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_Link_HomePage]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_Link_HomePage] ON [dbo].[Link]
(
	[VersionId] ASC,
	[Type] ASC,
	[Valid] ASC,
	[Orderby] ASC,
	[Deleted] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = OFF) ON [Index]
GO
/****** Object:  Index [IX_Link_power]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_Link_power] ON [dbo].[Link]
(
	[Power] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_Link_powerall]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_Link_powerall] ON [dbo].[Link]
(
	[PowerAll] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_Link_versionId]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_Link_versionId] ON [dbo].[Link]
(
	[VersionId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_link_count]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_link_count] ON [dbo].[link_count]
(
	[LinkId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_link_count_power]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_link_count_power] ON [dbo].[link_count]
(
	[Power] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_link_count_YearMonth]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_link_count_YearMonth] ON [dbo].[link_count]
(
	[YearMonth] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_link_score_countDate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_link_score_countDate] ON [dbo].[link_score]
(
	[CountDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_link_score_versionId]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_link_score_versionId] ON [dbo].[link_score]
(
	[VersionId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_linkclick_linkId]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_linkclick_linkId] ON [dbo].[linkclick]
(
	[Link_Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_linkclick_loginDate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_linkclick_loginDate] ON [dbo].[linkclick]
(
	[LoginDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_ManagerLog_ManagerId]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_ManagerLog_ManagerId] ON [dbo].[ManagerLog]
(
	[ManagerId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_ManagerLogSnap_IP]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_ManagerLogSnap_IP] ON [dbo].[ManagerLogSnap]
(
	[Ip] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = 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_manageruser_unique]    Script Date: 2018/9/25 12:40:12 ******/
CREATE UNIQUE NONCLUSTERED INDEX [IX_manageruser_unique] ON [dbo].[ManagerUser]
(
	[UserName] 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
/****** Object:  Index [IX_ManagerUserCompanyLog_addDate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_ManagerUserCompanyLog_addDate] ON [dbo].[ManagerUserCompanyLog]
(
	[AddDate] DESC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_ManagerUserCompanyLog_CompanyId]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_ManagerUserCompanyLog_CompanyId] ON [dbo].[ManagerUserCompanyLog]
(
	[CompanyId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_ManagerUserCompanyLog_cookies]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_ManagerUserCompanyLog_cookies] ON [dbo].[ManagerUserCompanyLog]
(
	[Cookies] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_ManagerUserCompanyLog_Ip]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_ManagerUserCompanyLog_Ip] ON [dbo].[ManagerUserCompanyLog]
(
	[Ip] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_ManagerUserCompanyLog_ManagerUserId]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_ManagerUserCompanyLog_ManagerUserId] ON [dbo].[ManagerUserCompanyLog]
(
	[ManagerUserId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_msEmailPrevSend_AddDate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_msEmailPrevSend_AddDate] ON [dbo].[msEmailPrevSend]
(
	[AddDate] ASC,
	[IsSend] ASC,
	[dcSubsiteId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_msEmailPrevSend_Email]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_msEmailPrevSend_Email] ON [dbo].[msEmailPrevSend]
(
	[Email] ASC,
	[AddDate] ASC,
	[IsSend] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_msEmailPrevSend_EmailNo]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_msEmailPrevSend_EmailNo] ON [dbo].[msEmailPrevSend]
(
	[EmailNo] ASC,
	[AddDate] ASC,
	[IsSend] ASC,
	[dcSubsiteId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_msEmailPrevSned_Complex]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_msEmailPrevSned_Complex] ON [dbo].[msEmailPrevSend]
(
	[cpMainId] ASC,
	[EmailNo] ASC,
	[Email] ASC,
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_msEmailSend_msEmailTypeId]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_msEmailSend_msEmailTypeId] ON [dbo].[msEmailSend]
(
	[msEmailTypeId] ASC,
	[AddDate] ASC,
	[Status] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_msEmailSend_msProcessLogId]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_msEmailSend_msProcessLogId] ON [dbo].[msEmailSend]
(
	[msProcessLogId] ASC,
	[AddDate] ASC,
	[Status] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [msEmailSend_adddate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [msEmailSend_adddate] ON [dbo].[msEmailSend]
(
	[AddDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_msProcess_Unique]    Script Date: 2018/9/25 12:40:12 ******/
CREATE UNIQUE NONCLUSTERED INDEX [IX_msProcess_Unique] ON [dbo].[msProcess]
(
	[msEmailTypeId] ASC,
	[dcSubSiteId] 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 [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [oa_flow_funname]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [oa_flow_funname] ON [dbo].[oa_flow]
(
	[funName] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [oa_flow_UserId]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [oa_flow_UserId] ON [dbo].[oa_flow]
(
	[UserId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_OutLink_addDate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_OutLink_addDate] ON [dbo].[OutLink]
(
	[AddDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_OutLink_copy]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_OutLink_copy] ON [dbo].[OutLink]
(
	[Copy] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_OutLink_ManagerUserId]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_OutLink_ManagerUserId] ON [dbo].[OutLink]
(
	[ManagerUserId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_OutLink_outurl]    Script Date: 2018/9/25 12:40:12 ******/
CREATE UNIQUE NONCLUSTERED INDEX [IX_OutLink_outurl] ON [dbo].[OutLink]
(
	[OutUrl] ASC,
	[Site] 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 [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_OutLink_site]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_OutLink_site] ON [dbo].[OutLink]
(
	[Site] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_outlink_count_outlinkId]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_outlink_count_outlinkId] ON [dbo].[outlink_count]
(
	[outlinkId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_outlink_count_power]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_outlink_count_power] ON [dbo].[outlink_count]
(
	[power] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_outlink_count_YearMonth]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_outlink_count_YearMonth] ON [dbo].[outlink_count]
(
	[YearMonth] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_paAttention_Complex]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_paAttention_Complex] ON [dbo].[PaAttention]
(
	[AttentionID] ASC
)
INCLUDE ( 	[PaMainID]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [CP]
GO
/****** Object:  Index [IX_paCvAlipayRelation_cvMainId]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_paCvAlipayRelation_cvMainId] ON [dbo].[paCvAlipayRelation]
(
	[cvMainID] ASC,
	[AddDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [X_paCvAlipayRelation_alipayResumeID]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [X_paCvAlipayRelation_alipayResumeID] ON [dbo].[paCvAlipayRelation]
(
	[alipayResumeID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_paFavorate_Unique]    Script Date: 2018/9/25 12:40:12 ******/
CREATE UNIQUE NONCLUSTERED INDEX [IX_paFavorate_Unique] ON [dbo].[paFavorate]
(
	[JobID] ASC,
	[paMainID] 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 [Index]
GO
/****** Object:  Index [IX_paFeedback_Complex1]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_paFeedback_Complex1] ON [dbo].[paFeedback]
(
	[IsReply] ASC,
	[AddDate] ASC,
	[ViewDate] ASC,
	[ReplyDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_paFeedback_ReplyMan]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_paFeedback_ReplyMan] ON [dbo].[paFeedback]
(
	[ReplyMan] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_paGetPasswordLog_AddDate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_paGetPasswordLog_AddDate] ON [dbo].[paGetPasswordLog]
(
	[AddDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_paGetPasswordLog_Email]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_paGetPasswordLog_Email] ON [dbo].[paGetPasswordLog]
(
	[Email] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_paGetPasswordLog_IP]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_paGetPasswordLog_IP] ON [dbo].[paGetPasswordLog]
(
	[IP] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_paGetPasswordLog_Mobile]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_paGetPasswordLog_Mobile] ON [dbo].[paGetPasswordLog]
(
	[Mobile] ASC,
	[AddDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_paGetPasswordLog_Username]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_paGetPasswordLog_Username] ON [dbo].[paGetPasswordLog]
(
	[UserName] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_paInfoEmailVerifyLog_Complex]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_paInfoEmailVerifyLog_Complex] ON [dbo].[paInfoEmailVerifyLog]
(
	[AddMan] ASC,
	[CountDate] ASC,
	[Email] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_paIOSBind_paMainId]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_paIOSBind_paMainId] ON [dbo].[PaIosBind]
(
	[PaMainID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_paJobClickCount_Ip]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_paJobClickCount_Ip] ON [dbo].[paJobClickCount]
(
	[Ip] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_paJobClickLog_Complex]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_paJobClickLog_Complex] ON [dbo].[paJobClickLog]
(
	[JobID] ASC,
	[paMainID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_paJobClickLoh_paMainId]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_paJobClickLoh_paMainId] ON [dbo].[paJobClickLog]
(
	[paMainID] ASC,
	[AddDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_paJobCompareIndex_paMainId]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_paJobCompareIndex_paMainId] ON [dbo].[paJobCompareIndex]
(
	[paMainId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
/****** Object:  Index [IX_paJobViewLog_adddate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_paJobViewLog_adddate] ON [dbo].[paJobViewLog]
(
	[JobID] ASC,
	[AddDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_paLoginContact_OpenId]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_paLoginContact_OpenId] ON [dbo].[paLoginContact]
(
	[Openid] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
/****** Object:  Index [IX_PaLoginContact_PaMainId]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_PaLoginContact_PaMainId] ON [dbo].[paLoginContact]
(
	[paMainID] ASC,
	[ContactType] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_paLoginLog_AddDate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_paLoginLog_AddDate] ON [dbo].[paLoginLog]
(
	[AddDate] ASC,
	[paMainID] ASC,
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_paLoginLog_paMainID]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_paLoginLog_paMainID] ON [dbo].[paLoginLog]
(
	[paMainID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_pamain_AddDate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_pamain_AddDate] ON [dbo].[paMain]
(
	[AddDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_paMain_BirthDay]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_paMain_BirthDay] ON [dbo].[paMain]
(
	[BirthDay] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_paMain_BirthDayLivePlace]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_paMain_BirthDayLivePlace] ON [dbo].[paMain]
(
	[BirthDay] ASC,
	[LivePlace] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_paMain_Complex1]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_paMain_Complex1] ON [dbo].[paMain]
(
	[LivePlace] ASC,
	[AccountPlace] ASC,
	[dcCareerStatus] ASC,
	[LastModifyDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_paMain_dcProvinceID]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_paMain_dcProvinceID] ON [dbo].[paMain]
(
	[dcProvinceID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_pamain_Email]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_pamain_Email] ON [dbo].[paMain]
(
	[Email] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_paMain_HasPhoto]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_paMain_HasPhoto] ON [dbo].[paMain]
(
	[HasPhoto] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_paMain_LastLoginDate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_paMain_LastLoginDate] ON [dbo].[paMain]
(
	[LastLoginDate] ASC
)
INCLUDE ( 	[ID],
	[Gender],
	[BirthDay],
	[AccountPlace]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_pamain_LastModifyDate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_pamain_LastModifyDate] ON [dbo].[paMain]
(
	[LastModifyDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_paMain_LivePlace]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_paMain_LivePlace] ON [dbo].[paMain]
(
	[LivePlace] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_paMain_LocalRate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_paMain_LocalRate] ON [dbo].[paMain]
(
	[LivePlace] ASC,
	[AddMan] ASC,
	[RegisterMode] ASC,
	[AddDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_paMain_Mobile]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_paMain_Mobile] ON [dbo].[paMain]
(
	[Mobile] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [Ix_PaMain_MobileRegion]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [Ix_PaMain_MobileRegion] ON [dbo].[paMain]
(
	[MobileRegion] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_paMain_Name]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_paMain_Name] ON [dbo].[paMain]
(
	[Name] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_pamain_RegisterIp]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_pamain_RegisterIp] ON [dbo].[paMain]
(
	[RegisterIP] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_paMain_TotalLoginNum]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_paMain_TotalLoginNum] ON [dbo].[paMain]
(
	[TotalLoginNum] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ARITHABORT ON
SET CONCAT_NULL_YIELDS_NULL ON
SET QUOTED_IDENTIFIER ON
SET ANSI_NULLS ON
SET ANSI_PADDING ON
SET ANSI_WARNINGS ON
SET NUMERIC_ROUNDABORT OFF

GO
/****** Object:  Index [IX_paMain_UserNameLower]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_paMain_UserNameLower] ON [dbo].[paMain]
(
	[UserNameLower] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_paMainPublish_BirthDay]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_paMainPublish_BirthDay] ON [dbo].[paMainPublish]
(
	[BirthDay] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_paMainPublish_BirthDayLivePlace]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_paMainPublish_BirthDayLivePlace] ON [dbo].[paMainPublish]
(
	[BirthDay] ASC,
	[LivePlace] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_paMainPublish_Complex1]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_paMainPublish_Complex1] ON [dbo].[paMainPublish]
(
	[LivePlace] ASC,
	[AccountPlace] ASC,
	[LastModifyDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_paMainPublish_HasPhoto]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_paMainPublish_HasPhoto] ON [dbo].[paMainPublish]
(
	[HasPhoto] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_paMainPublish_LastLoginDate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_paMainPublish_LastLoginDate] ON [dbo].[paMainPublish]
(
	[LastLoginDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_pamainPublish_LastModifyDate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_pamainPublish_LastModifyDate] ON [dbo].[paMainPublish]
(
	[LastModifyDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_paMainPublish_LivePlace]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_paMainPublish_LivePlace] ON [dbo].[paMainPublish]
(
	[LivePlace] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [Ix_PaMainPublish_MobileRegion]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [Ix_PaMainPublish_MobileRegion] ON [dbo].[paMainPublish]
(
	[MobileRegion] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_paMobileFollowUp_AddDate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_paMobileFollowUp_AddDate] ON [dbo].[paMobileFollowUp]
(
	[AddDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_paMobileFollowUp_Mobie]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_paMobileFollowUp_Mobie] ON [dbo].[paMobileFollowUp]
(
	[Mobile] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_paNotify_AddDate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_paNotify_AddDate] ON [dbo].[paNotify]
(
	[AddDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_paNotify_EndDate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_paNotify_EndDate] ON [dbo].[paNotify]
(
	[EndDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_paNotify_ManagerUserId]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_paNotify_ManagerUserId] ON [dbo].[paNotify]
(
	[ManagerUserID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_paNotify_paMainID]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_paNotify_paMainID] ON [dbo].[paNotify]
(
	[paMainID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_paOnline_RefreshDate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_paOnline_RefreshDate] ON [dbo].[PaOnline]
(
	[RefreshDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_paOperationLog_AddDate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_paOperationLog_AddDate] ON [dbo].[paOperationLog]
(
	[AddDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_paPhoto_AddDate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_paPhoto_AddDate] ON [dbo].[paPhoto]
(
	[AddDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_paPhoto_CheckDate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_paPhoto_CheckDate] ON [dbo].[paPhoto]
(
	[CheckDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = OFF) ON [Index]
GO
/****** Object:  Index [IX_paPhoto_CheckMan]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_paPhoto_CheckMan] ON [dbo].[paPhoto]
(
	[CheckMan] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_paPhoto_paMainId]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_paPhoto_paMainId] ON [dbo].[paPhoto]
(
	[paMainID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_paPlaint_caMainID]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_paPlaint_caMainID] ON [dbo].[paPlaint]
(
	[caMainID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_paPushLog_Complex]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_paPushLog_Complex] ON [dbo].[paPushLog]
(
	[AddDate] ASC,
	[PushDate] ASC,
	[paMainID] ASC
)
INCLUDE ( 	[ID]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_paPushLog_Complex2]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_paPushLog_Complex2] ON [dbo].[paPushLog]
(
	[paMainID] ASC,
	[AddDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_Person_Black_AddedDate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_Person_Black_AddedDate] ON [dbo].[Person_Black]
(
	[AddedDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_Person_Black_Email]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_Person_Black_Email] ON [dbo].[Person_Black]
(
	[Email] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_Person_Black_Mobile]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_Person_Black_Mobile] ON [dbo].[Person_Black]
(
	[Mobile] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_pr_alex_province_Id]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_pr_alex_province_Id] ON [dbo].[Pr_Alex]
(
	[Province_Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_pr_alex_YearMonthDay]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_pr_alex_YearMonthDay] ON [dbo].[Pr_Alex]
(
	[YearMonthDay] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_Qlrcnews_Complex1]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_Qlrcnews_Complex1] ON [dbo].[QlrcNews]
(
	[DetailType] ASC,
	[VersionId] ASC,
	[AnnounceDate] DESC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_QlrcNews_RefreshDate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_QlrcNews_RefreshDate] ON [dbo].[QlrcNews]
(
	[NewsType] ASC,
	[RefReshDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_QlrcNews_Title]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_QlrcNews_Title] ON [dbo].[QlrcNews]
(
	[Title] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_QlrcNewsTop5_Complex1]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_QlrcNewsTop5_Complex1] ON [dbo].[QlrcNewsTop5]
(
	[DetailType] ASC,
	[VersionId] ASC,
	[AnnounceDate] DESC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_qryJobApplyMonth_Complex]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_qryJobApplyMonth_Complex] ON [dbo].[qryJobApplyMonth]
(
	[cpMainID] ASC,
	[NotOpenNumber] ASC,
	[AllNumber] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = OFF) ON [Index]
GO
/****** Object:  Index [IX_question]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_question] ON [dbo].[Question]
(
	[InvestId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_QuotaLog_CaMainId]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_QuotaLog_CaMainId] ON [dbo].[QuotaLog]
(
	[CaMainId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
/****** Object:  Index [IX_QuotaLog_CaOrderId]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_QuotaLog_CaOrderId] ON [dbo].[QuotaLog]
(
	[CaOrderId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
/****** Object:  Index [IX_referer_loginDate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_referer_loginDate] ON [dbo].[referer]
(
	[LoginDate] DESC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Market]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_referer_versionId]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_referer_versionId] ON [dbo].[referer]
(
	[VersionId] ASC,
	[Referer] ASC,
	[Ip] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_referer_count_countDate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_referer_count_countDate] ON [dbo].[referer_count]
(
	[CountDate] ASC,
	[Province_Id] ASC,
	[Referer] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_referer_province_Id]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_referer_province_Id] ON [dbo].[referer_count]
(
	[Province_Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_referer_referer]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_referer_referer] ON [dbo].[referer_count]
(
	[Referer] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_referer_count_keywords_howMany]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_referer_count_keywords_howMany] ON [dbo].[Referer_Count_Keywords]
(
	[HowMany] DESC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_referer_count_keywords_Id]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_referer_count_keywords_Id] ON [dbo].[Referer_Count_Keywords]
(
	[Referer_Count_Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_referer_count_keywords_keywords]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_referer_count_keywords_keywords] ON [dbo].[Referer_Count_Keywords]
(
	[Keywords] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_referer_item_name]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_referer_item_name] ON [dbo].[Referer_Item]
(
	[Item_Name] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_referer_item_keywords_itemId]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_referer_item_keywords_itemId] ON [dbo].[Referer_Item_Keywords]
(
	[Item_Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_Resume_Xinxi_AddMan]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_Resume_Xinxi_AddMan] ON [dbo].[Resume_Xinxi]
(
	[AddMan] ASC,
	[RegDate] ASC,
	[Email] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_Resume_Xinxi_email]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_Resume_Xinxi_email] ON [dbo].[Resume_Xinxi]
(
	[Email] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_Resume_Xinxi_IsHistory]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_Resume_Xinxi_IsHistory] ON [dbo].[Resume_Xinxi]
(
	[IsHistory] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_Resume_Xinxi_Province]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_Resume_Xinxi_Province] ON [dbo].[Resume_Xinxi]
(
	[Province_Id] ASC,
	[RegDate] ASC
)
INCLUDE ( 	[Email]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_Resume_Xinxi_RegDate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_Resume_Xinxi_RegDate] ON [dbo].[Resume_Xinxi]
(
	[RegDate] DESC,
	[IsHistory] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [ResumeXinxiScheme]([IsHistory])
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_resume_Xinxi_Username]    Script Date: 2018/9/25 12:40:12 ******/
CREATE UNIQUE NONCLUSTERED INDEX [IX_resume_Xinxi_Username] ON [dbo].[Resume_Xinxi]
(
	[UserName] 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 [Index]
GO
SET ARITHABORT ON
SET CONCAT_NULL_YIELDS_NULL ON
SET QUOTED_IDENTIFIER ON
SET ANSI_NULLS ON
SET ANSI_PADDING ON
SET ANSI_WARNINGS ON
SET NUMERIC_ROUNDABORT OFF

GO
/****** Object:  Index [IX_Resume_Xinxi_UserNameLower]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_Resume_Xinxi_UserNameLower] ON [dbo].[Resume_Xinxi]
(
	[UserNameLower] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_ResumesubscrIption_addDate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_ResumesubscrIption_addDate] ON [dbo].[ResumeSubScription]
(
	[AddDate] DESC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_ResumesubscrIption_jobId]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_ResumesubscrIption_jobId] ON [dbo].[ResumeSubScription]
(
	[JobId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_ResumesubscrIption_ResumeId]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_ResumesubscrIption_ResumeId] ON [dbo].[ResumeSubScription]
(
	[ResumeId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_rtx_log_addDate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_rtx_log_addDate] ON [dbo].[rtx_log]
(
	[AddDate] DESC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_rtx_log_addResser]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_rtx_log_addResser] ON [dbo].[rtx_log]
(
	[Addresser] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_Sales_Factor_YearMonth]    Script Date: 2018/9/25 12:40:12 ******/
CREATE UNIQUE NONCLUSTERED INDEX [IX_Sales_Factor_YearMonth] ON [dbo].[Sales_Factor]
(
	[YearMonth] 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 [Index]
GO
/****** Object:  Index [IX_Sales_factor_farmer_YearMonth]    Script Date: 2018/9/25 12:40:12 ******/
CREATE UNIQUE NONCLUSTERED INDEX [IX_Sales_factor_farmer_YearMonth] ON [dbo].[Sales_factor_farmer]
(
	[Id] 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 [Index]
GO
/****** Object:  Index [IX_sales_workDate_workDate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE UNIQUE NONCLUSTERED INDEX [IX_sales_workDate_workDate] ON [dbo].[sales_workDate]
(
	[workDate] 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 [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_schMailPrev_Email]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_schMailPrev_Email] ON [dbo].[schMailPrev]
(
	[Email] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
/****** Object:  Index [IX_searchkeywords_competition]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_searchkeywords_competition] ON [dbo].[searchkeywords]
(
	[Competition] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_searchkeywords_power]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_searchkeywords_power] ON [dbo].[searchkeywords]
(
	[power] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_searchkeywords_province_Id]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_searchkeywords_province_Id] ON [dbo].[searchkeywords]
(
	[province_Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_searchkeywords_uniqe]    Script Date: 2018/9/25 12:40:12 ******/
CREATE UNIQUE NONCLUSTERED INDEX [IX_searchkeywords_uniqe] ON [dbo].[searchkeywords]
(
	[keywords] ASC,
	[province_Id] 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 [Index]
GO
/****** Object:  Index [IX_searchkeywords_version_id]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_searchkeywords_version_id] ON [dbo].[searchkeywords]
(
	[version_Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_SearchKeywordsPower_searchkeywords_Id]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_SearchKeywordsPower_searchkeywords_Id] ON [dbo].[SearchKeywordsPower]
(
	[searchkeywords_Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_SearchKeywordsPower_unique]    Script Date: 2018/9/25 12:40:12 ******/
CREATE UNIQUE NONCLUSTERED INDEX [IX_SearchKeywordsPower_unique] ON [dbo].[SearchKeywordsPower]
(
	[engine] ASC,
	[searchkeywords_Id] ASC,
	[YearMonthDay] 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 [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_SearchKeywordsPower_YearMonth]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_SearchKeywordsPower_YearMonth] ON [dbo].[SearchKeywordsPower]
(
	[YearMonthDay] ASC,
	[engine] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_SeatStatus_extent]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_SeatStatus_extent] ON [dbo].[SeatStatus]
(
	[Exten] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_SeatStatus_state]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_SeatStatus_state] ON [dbo].[SeatStatus]
(
	[state] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_SeatStatus_StatusTime]    Script Date: 2018/9/25 12:40:12 ******/
CREATE UNIQUE NONCLUSTERED INDEX [IX_SeatStatus_StatusTime] ON [dbo].[SeatStatus]
(
	[Statustime] ASC,
	[Exten] ASC,
	[state] 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 [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_SeatStatusCount_Exten]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_SeatStatusCount_Exten] ON [dbo].[SeatStatusCount]
(
	[Exten] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_seConderer_loginDate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_seConderer_loginDate] ON [dbo].[Seconderer]
(
	[LoginDate] DESC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_seConderer_versionId]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_seConderer_versionId] ON [dbo].[Seconderer]
(
	[VersionId] ASC,
	[Referer] ASC,
	[Ip] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_seConderer_count_countDate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_seConderer_count_countDate] ON [dbo].[Seconderer_Count]
(
	[CountDate] ASC,
	[Referer] ASC,
	[Province_Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_seConderer_count_province_Id]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_seConderer_count_province_Id] ON [dbo].[Seconderer_Count]
(
	[Province_Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_seConderer_count_referer]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_seConderer_count_referer] ON [dbo].[Seconderer_Count]
(
	[Referer] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_seConderer_count_unique]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_seConderer_count_unique] ON [dbo].[Seconderer_Count]
(
	[CountDate] ASC,
	[Province_Id] ASC,
	[Referer] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_seConderer_count_keywords_howMany]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_seConderer_count_keywords_howMany] ON [dbo].[Seconderer_Count_Keywords]
(
	[HowMany] DESC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_seConderer_count_keywords_Id]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_seConderer_count_keywords_Id] ON [dbo].[Seconderer_Count_Keywords]
(
	[Referer_Count_Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_seConderer_count_keywords_keywords]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_seConderer_count_keywords_keywords] ON [dbo].[Seconderer_Count_Keywords]
(
	[Keywords] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_SmsMessageLog_caMainId]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_SmsMessageLog_caMainId] ON [dbo].[SmsMessageLog]
(
	[caMainId] ASC,
	[SendDate] DESC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_SmsMessageLog_Complex]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_SmsMessageLog_Complex] ON [dbo].[SmsMessageLog]
(
	[AddDate] DESC,
	[SendDate] DESC,
	[IsCat] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_SmsMessageLog_Mobile]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_SmsMessageLog_Mobile] ON [dbo].[SmsMessageLog]
(
	[Mobile] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_SmsMessageLog_paMainId]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_SmsMessageLog_paMainId] ON [dbo].[SmsMessageLog]
(
	[paMainId] ASC,
	[SendDate] DESC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_SmsMessageLog_SendMan]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_SmsMessageLog_SendMan] ON [dbo].[SmsMessageLog]
(
	[SendMan] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_SmsWatch_Complex]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_SmsWatch_Complex] ON [dbo].[SmsWatch]
(
	[SmsType] ASC,
	[IsSend] ASC,
	[WatchDate] ASC,
	[MsgType] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_SmsWatch_WatchDate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_SmsWatch_WatchDate] ON [dbo].[SmsWatch]
(
	[WatchDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_telephonebill_Day_countDate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_telephonebill_Day_countDate] ON [dbo].[telephonebill_Day]
(
	[countDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_telephonebill_Day_ManagerUserId]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_telephonebill_Day_ManagerUserId] ON [dbo].[telephonebill_Day]
(
	[ManagerUserId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_Tmp_BlackWord_BlackWord]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_Tmp_BlackWord_BlackWord] ON [dbo].[tmp_BlackWord]
(
	[BlackWord] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_wordspecial_Word]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_wordspecial_Word] ON [dbo].[WordList]
(
	[Word] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
/****** Object:  Index [IX_workDate_workDate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE UNIQUE NONCLUSTERED INDEX [IX_workDate_workDate] ON [dbo].[workDate]
(
	[workDate] 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 [Index]
GO
/****** Object:  Index [IX_workDate_province_ManagerUser_2]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_workDate_province_ManagerUser_2] ON [dbo].[workDate_province_ManagerUser]
(
	[WorkDate] ASC,
	[ManagerUser_Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_workDate_province_ManagerUser_ManagerUser_Id]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_workDate_province_ManagerUser_ManagerUser_Id] ON [dbo].[workDate_province_ManagerUser]
(
	[ManagerUser_Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_workDate_province_ManagerUser_province_Id]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_workDate_province_ManagerUser_province_Id] ON [dbo].[workDate_province_ManagerUser]
(
	[Province_Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_workDate_province_ManagerUser_workDate]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_workDate_province_ManagerUser_workDate] ON [dbo].[workDate_province_ManagerUser]
(
	[WorkDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_WxFans_CaMainId]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_WxFans_CaMainId] ON [dbo].[WxFans]
(
	[caMainId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_wxFans_OpenId]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_wxFans_OpenId] ON [dbo].[WxFans]
(
	[OpenID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_WxFans_PaMainId]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_WxFans_PaMainId] ON [dbo].[WxFans]
(
	[PaMainID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_WxMessageReceive_Complex1]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_WxMessageReceive_Complex1] ON [dbo].[WxMessageReceive]
(
	[WxFansID] ASC,
	[AddDate] ASC
)
INCLUDE ( 	[ID]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  Index [IX_yingyelog_only]    Script Date: 2018/9/25 12:40:12 ******/
CREATE NONCLUSTERED INDEX [IX_yingyelog_only] ON [dbo].[yingyelog]
(
	[countDate] ASC,
	[ManagerUserId] ASC,
	[province_Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Index]
GO
/****** Object:  FullTextIndex     Script Date: 2018/9/25 12:40:12 ******/
CREATE FULLTEXT INDEX ON [dbo].[bsCvVerifyLog](
[OldValue] LANGUAGE 'Simplified Chinese')
KEY INDEX [PK_bsCvVerifyLog]ON ([cvVerifyCatalog], FILEGROUP [ftfg_cvVerifyCatalog])
WITH (CHANGE_TRACKING = AUTO, STOPLIST = SYSTEM)


GO
/****** Object:  FullTextIndex     Script Date: 2018/9/25 12:40:12 ******/
CREATE FULLTEXT INDEX ON [dbo].[cpMain](
[Brief] LANGUAGE 'Simplified Chinese', 
[Name] LANGUAGE 'Simplified Chinese')
KEY INDEX [PK_cpMain]ON ([cpMainCatalog], FILEGROUP [ftfg_cpMainCatalog])
WITH (CHANGE_TRACKING = AUTO, STOPLIST = SYSTEM)


GO
/****** Object:  FullTextIndex     Script Date: 2018/9/25 12:40:12 ******/
CREATE FULLTEXT INDEX ON [dbo].[cpMainPublish](
[Brief] LANGUAGE 'Simplified Chinese', 
[Name] LANGUAGE 'Simplified Chinese')
KEY INDEX [PK_cpMainPublish]ON ([cpPublishCatalog], FILEGROUP [ftfg_cpPublishCatalog])
WITH (CHANGE_TRACKING = AUTO, STOPLIST = SYSTEM)


GO
/****** Object:  FullTextIndex     Script Date: 2018/9/25 12:40:12 ******/
CREATE FULLTEXT INDEX ON [dbo].[cvAppendixPublish](
[Description] LANGUAGE 'Simplified Chinese', 
[Name] LANGUAGE 'Simplified Chinese')
KEY INDEX [PK_cvAppendixPublish]ON ([cvPublishCatalog], FILEGROUP [ftfg_cvPublishCatalog])
WITH (CHANGE_TRACKING = AUTO, STOPLIST = SYSTEM)


GO
/****** Object:  FullTextIndex     Script Date: 2018/9/25 12:40:12 ******/
CREATE FULLTEXT INDEX ON [dbo].[cvEducationPublish](
[Details] LANGUAGE 'Simplified Chinese', 
[GraduateCollage] LANGUAGE 'Simplified Chinese', 
[MajorName] LANGUAGE 'Simplified Chinese')
KEY INDEX [PK_cvEducationPublish]ON ([cvPublishCatalog], FILEGROUP [ftfg_cvPublishCatalog])
WITH (CHANGE_TRACKING = AUTO, STOPLIST = SYSTEM)


GO
/****** Object:  FullTextIndex     Script Date: 2018/9/25 12:40:12 ******/
CREATE FULLTEXT INDEX ON [dbo].[cvExperiencePublish](
[CompanyName] LANGUAGE 'Simplified Chinese', 
[Description] LANGUAGE 'Simplified Chinese', 
[JobName] LANGUAGE 'Simplified Chinese')
KEY INDEX [PK_cvExperiencePublish]ON ([cvPublishCatalog], FILEGROUP [ftfg_cvPublishCatalog])
WITH (CHANGE_TRACKING = AUTO, STOPLIST = SYSTEM)


GO
/****** Object:  FullTextIndex     Script Date: 2018/9/25 12:40:12 ******/
CREATE FULLTEXT INDEX ON [dbo].[cvInfo](
[EduInfo] LANGUAGE 'Simplified Chinese', 
[ExpInfo] LANGUAGE 'Simplified Chinese', 
[JobName] LANGUAGE 'Simplified Chinese', 
[ProjectInfo] LANGUAGE 'Simplified Chinese', 
[Speciality] LANGUAGE 'Simplified Chinese', 
[TrainInfo] LANGUAGE 'Simplified Chinese')
KEY INDEX [PK_cvInfo]ON ([cvinfo], FILEGROUP [ftfg_cvinfo])
WITH (CHANGE_TRACKING = AUTO, STOPLIST = SYSTEM)


GO
/****** Object:  FullTextIndex     Script Date: 2018/9/25 12:40:12 ******/
CREATE FULLTEXT INDEX ON [dbo].[cvMainPublish](
[JobName] LANGUAGE 'Simplified Chinese', 
[Speciality] LANGUAGE 'Simplified Chinese')
KEY INDEX [PK_cvMainPublish]ON ([cvPublishCatalog], FILEGROUP [ftfg_cvPublishCatalog])
WITH (CHANGE_TRACKING = AUTO, STOPLIST = SYSTEM)


GO
/****** Object:  FullTextIndex     Script Date: 2018/9/25 12:40:12 ******/
CREATE FULLTEXT INDEX ON [dbo].[cvProjectPublish](
[Description] LANGUAGE 'Simplified Chinese', 
[Name] LANGUAGE 'Simplified Chinese', 
[Responsibilities] LANGUAGE 'Simplified Chinese')
KEY INDEX [PK_cvProjectPublish]ON ([cvPublishCatalog], FILEGROUP [ftfg_cvPublishCatalog])
WITH (CHANGE_TRACKING = AUTO, STOPLIST = SYSTEM)


GO
/****** Object:  FullTextIndex     Script Date: 2018/9/25 12:40:12 ******/
CREATE FULLTEXT INDEX ON [dbo].[cvTrainingPublish](
[Certificate] LANGUAGE 'Simplified Chinese', 
[Course] LANGUAGE 'Simplified Chinese', 
[Details] LANGUAGE 'Simplified Chinese', 
[Institution] LANGUAGE 'Simplified Chinese')
KEY INDEX [PK_cvTrainingPublish]ON ([cvPublishCatalog], FILEGROUP [ftfg_cvPublishCatalog])
WITH (CHANGE_TRACKING = AUTO, STOPLIST = SYSTEM)


GO
/****** Object:  FullTextIndex     Script Date: 2018/9/25 12:40:12 ******/
CREATE FULLTEXT INDEX ON [dbo].[JobPublish](
[Demand] LANGUAGE 'Simplified Chinese', 
[Name] LANGUAGE 'Simplified Chinese', 
[Responsibility] LANGUAGE 'Simplified Chinese')
KEY INDEX [PK_JobPublish]ON ([cpPublishCatalog], FILEGROUP [ftfg_cpPublishCatalog])
WITH (CHANGE_TRACKING = AUTO, STOPLIST = SYSTEM)


GO
/****** Object:  FullTextIndex     Script Date: 2018/9/25 12:40:12 ******/
CREATE FULLTEXT INDEX ON [dbo].[QlrcNews](
[Content] LANGUAGE 'Simplified Chinese', 
[Title] LANGUAGE 'Simplified Chinese')
KEY INDEX [PK_QlrcNews]ON ([QlrcNews], FILEGROUP [ftfg_QlrcNews])
WITH (CHANGE_TRACKING = AUTO, STOPLIST = SYSTEM)


GO
/****** Object:  FullTextIndex     Script Date: 2018/9/25 12:40:12 ******/
CREATE FULLTEXT INDEX ON [dbo].[cpMainJob](
[Brief] LANGUAGE 'Simplified Chinese', 
[cpname] LANGUAGE 'Simplified Chinese', 
[Demand] LANGUAGE 'Simplified Chinese', 
[jobname] LANGUAGE 'Simplified Chinese', 
[Responsibility] LANGUAGE 'Simplified Chinese')
KEY INDEX [IX_cpMainJob_JobId]ON ([cpPublishCatalog], FILEGROUP [ftfg_cpPublishCatalog])
WITH (CHANGE_TRACKING = AUTO, STOPLIST = SYSTEM)


GO
ALTER TABLE [dbo].[AdverProject] ADD  CONSTRAINT [DF_AdverProject_ClickCount]  DEFAULT ((0)) FOR [ClickCount]
GO
ALTER TABLE [dbo].[AdverProject] ADD  CONSTRAINT [DF_AdverProject_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[AdverProject] ADD  DEFAULT ((0)) FOR [IsSelf]
GO
ALTER TABLE [dbo].[AdverProject_ErrorLog] ADD  CONSTRAINT [DF_adverproject_ErrorLog_adddate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[Agent_Black] ADD  CONSTRAINT [DF_agent_black_adddate]  DEFAULT (getdate()) FOR [adddate]
GO
ALTER TABLE [dbo].[Agent_White] ADD  CONSTRAINT [DF_agent_White_adddate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[AgentIp] ADD  CONSTRAINT [DF_AgentIp_addDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[AlipayJobPushLog] ADD  CONSTRAINT [DF_AlipayJobPushLog_PushTime]  DEFAULT (getdate()) FOR [PushTime]
GO
ALTER TABLE [dbo].[assessCpInvite] ADD  CONSTRAINT [DF_assessCpInvite_Status]  DEFAULT ((0)) FOR [Status]
GO
ALTER TABLE [dbo].[assessCpInvite] ADD  CONSTRAINT [DF_assessCpInvite_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[assessDimension] ADD  CONSTRAINT [DF_assessOptionsDimension_AddMan]  DEFAULT ((1)) FOR [AddMan]
GO
ALTER TABLE [dbo].[assessDimension] ADD  CONSTRAINT [DF_assessOptionsDimension_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[assessDimensionGroup] ADD  CONSTRAINT [DF_assessDimensionGroup_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[assessOptions] ADD  CONSTRAINT [DF_assessAnswer_Score]  DEFAULT ((0)) FOR [Score]
GO
ALTER TABLE [dbo].[assessOptions] ADD  CONSTRAINT [DF_assessOptions_SortNo]  DEFAULT ((0)) FOR [SortNo]
GO
ALTER TABLE [dbo].[assessOptions] ADD  CONSTRAINT [DF_assessAnswer_AddMan]  DEFAULT ((1)) FOR [AddMan]
GO
ALTER TABLE [dbo].[assessOptions] ADD  CONSTRAINT [DF_assessAnswer_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[assessQuestion] ADD  CONSTRAINT [DF_assessQuestion_SortNo]  DEFAULT ((99)) FOR [SortNo]
GO
ALTER TABLE [dbo].[assessQuestion] ADD  CONSTRAINT [DF_assessQuestion_QuestionType]  DEFAULT ((1)) FOR [QuestionType]
GO
ALTER TABLE [dbo].[assessQuestion] ADD  CONSTRAINT [DF_assessQuestion_AnswerSort]  DEFAULT ((0)) FOR [OptionsSort]
GO
ALTER TABLE [dbo].[assessQuestion] ADD  CONSTRAINT [DF_assessQuestion_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[assessTestAnswer] ADD  CONSTRAINT [DF_assessTestAnswer_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[assessTestLog] ADD  CONSTRAINT [DF_assessTestLog_IsOpen]  DEFAULT ((1)) FOR [IsOpen]
GO
ALTER TABLE [dbo].[assessTestLog] ADD  CONSTRAINT [DF_assessTestLog_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[assessTheme] ADD  CONSTRAINT [DF_assessTheme_SortNo]  DEFAULT ((99)) FOR [SortNo]
GO
ALTER TABLE [dbo].[assessTheme] ADD  CONSTRAINT [DF_assessTheme_SortType]  DEFAULT ((0)) FOR [SortType]
GO
ALTER TABLE [dbo].[assessTheme] ADD  CONSTRAINT [DF_assessTheme_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[assessType] ADD  CONSTRAINT [DF_assessType_ReTestDay]  DEFAULT ((30)) FOR [ReTestDay]
GO
ALTER TABLE [dbo].[assessType] ADD  CONSTRAINT [DF_assessType_UseCount]  DEFAULT ((0)) FOR [UseCount]
GO
ALTER TABLE [dbo].[assessType] ADD  CONSTRAINT [DF_assessType_OrderBy]  DEFAULT ((99)) FOR [SortNo]
GO
ALTER TABLE [dbo].[assessType] ADD  CONSTRAINT [DF_assessType_ResultType]  DEFAULT ((0)) FOR [ResultType]
GO
ALTER TABLE [dbo].[assessType] ADD  CONSTRAINT [DF_assessType_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[assessTypeResult] ADD  CONSTRAINT [DF_assessTypeResult_AddMan]  DEFAULT ((1)) FOR [AddMan]
GO
ALTER TABLE [dbo].[assessTypeResult] ADD  CONSTRAINT [DF_assessTypeResult_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[Atc_Account] ADD  CONSTRAINT [DF_Atc_Account_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[Atc_Article] ADD  CONSTRAINT [DF_Atc_Article_Adddate]  DEFAULT (getdate()) FOR [Adddate]
GO
ALTER TABLE [dbo].[Atc_NewsPoint] ADD  CONSTRAINT [DF_Table_1_Addman]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[Atc_Project] ADD  CONSTRAINT [DF_Atc_Topic_adddate]  DEFAULT (getdate()) FOR [adddate]
GO
ALTER TABLE [dbo].[Atc_Resource] ADD  CONSTRAINT [DF_Table_1_Adddate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[Atc_Topic] ADD  CONSTRAINT [DF_Atc_Topic_AddDate_1]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[Atc_Topic] ADD  CONSTRAINT [DF_Atc_Topic_ClickNum]  DEFAULT ((0)) FOR [ClickNum]
GO
ALTER TABLE [dbo].[Atc_Topic] ADD  CONSTRAINT [DF_Atc_Topic_status]  DEFAULT ((1)) FOR [status]
GO
ALTER TABLE [dbo].[Atc_TopicFollow] ADD  CONSTRAINT [DF_Atc_TopicFollow_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[BackData] ADD  CONSTRAINT [DF_BackData_Resume_Pass]  DEFAULT ((0)) FOR [Resume_Pass]
GO
ALTER TABLE [dbo].[BackData] ADD  CONSTRAINT [DF_BackData_Resume_Delete]  DEFAULT ((0)) FOR [Resume_Delete]
GO
ALTER TABLE [dbo].[BackData] ADD  CONSTRAINT [DF_BackData_Resume_NoPass]  DEFAULT ((0)) FOR [Resume_NoPass]
GO
ALTER TABLE [dbo].[BackData] ADD  CONSTRAINT [DF_BackData_Resume_Modify]  DEFAULT ((0)) FOR [Resume_Modify]
GO
ALTER TABLE [dbo].[BackData] ADD  CONSTRAINT [DF_BackData_Photo_Pass]  DEFAULT ((0)) FOR [Photo_Pass]
GO
ALTER TABLE [dbo].[BackData] ADD  CONSTRAINT [DF_BackData_Photo_Modify]  DEFAULT ((0)) FOR [Photo_Modify]
GO
ALTER TABLE [dbo].[BackData] ADD  CONSTRAINT [DF_BackData_Photo_Delete]  DEFAULT ((0)) FOR [Photo_Delete]
GO
ALTER TABLE [dbo].[BackData] ADD  CONSTRAINT [DF_BackData_Appendix_Modify]  DEFAULT ((0)) FOR [Appendix_Modify]
GO
ALTER TABLE [dbo].[BackData] ADD  CONSTRAINT [DF_BackData_Appendix_Delete]  DEFAULT ((0)) FOR [Appendix_Delete]
GO
ALTER TABLE [dbo].[BackData] ADD  CONSTRAINT [DF_BackData_CompanyLogo_Pass]  DEFAULT ((0)) FOR [CompanyLogo_Pass]
GO
ALTER TABLE [dbo].[BackData] ADD  CONSTRAINT [DF_BackData_CompanyLogo_Delete]  DEFAULT ((0)) FOR [CompanyLogo_Delete]
GO
ALTER TABLE [dbo].[BackData] ADD  CONSTRAINT [DF_BackData_High_Resume_Pass]  DEFAULT ((0)) FOR [High_Resume_Pass]
GO
ALTER TABLE [dbo].[BackData] ADD  CONSTRAINT [DF_BackData_High_Resume_NoPass]  DEFAULT ((0)) FOR [High_Resume_NoPass]
GO
ALTER TABLE [dbo].[BackData] ADD  CONSTRAINT [DF_BackData_Black]  DEFAULT ((0)) FOR [Black]
GO
ALTER TABLE [dbo].[BackData] ADD  CONSTRAINT [DF_BackData_CompanyDelete]  DEFAULT ((0)) FOR [CompanyDelete]
GO
ALTER TABLE [dbo].[BackData] ADD  CONSTRAINT [DF_BackData_CompanyVisual_Pass]  DEFAULT ((0)) FOR [CompanyVisual_Pass]
GO
ALTER TABLE [dbo].[BackData] ADD  CONSTRAINT [DF_BackData_CompanyVisual_Delete]  DEFAULT ((0)) FOR [CompanyVisual_Delete]
GO
ALTER TABLE [dbo].[BackData] ADD  CONSTRAINT [DF_BackData_Company_Modify]  DEFAULT ((0)) FOR [Company_Modify]
GO
ALTER TABLE [dbo].[BeiSenAds] ADD  CONSTRAINT [DF_BeiSenAds_Adddate]  DEFAULT (getdate()) FOR [Adddate]
GO
ALTER TABLE [dbo].[BeiSenAds] ADD  CONSTRAINT [DF_BeiSenAds_LastGetDate]  DEFAULT (getdate()) FOR [LastGetDate]
GO
ALTER TABLE [dbo].[BeiSenCompany] ADD  CONSTRAINT [DF_BeiSenCompany_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[BestEmployer] ADD  CONSTRAINT [DF_BestEmployer_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[BestEmployerVote] ADD  CONSTRAINT [DF_BestEmployerVote_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[bsAskClickLog] ADD  CONSTRAINT [DF_bsAskClickLog_CountDate]  DEFAULT (CONVERT([varchar](6),getdate(),(112))) FOR [CountMonth]
GO
ALTER TABLE [dbo].[bsAskClickLog] ADD  CONSTRAINT [DF_bsAskClickLog_ClickNumber]  DEFAULT ((0)) FOR [ClickNumber]
GO
ALTER TABLE [dbo].[bsAskClickLog] ADD  CONSTRAINT [DF_bsAskClickLog_Increase]  DEFAULT ((0)) FOR [Increase]
GO
ALTER TABLE [dbo].[bsASKInfo] ADD  CONSTRAINT [DF_bsASKInfo_AddUserID]  DEFAULT ((0)) FOR [AddUserID]
GO
ALTER TABLE [dbo].[bsASKInfo] ADD  CONSTRAINT [DF_bsASKInfo_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[bsASKInfo] ADD  CONSTRAINT [DF_bsASKInfo_IsOnline]  DEFAULT ((0)) FOR [IsOnline]
GO
ALTER TABLE [dbo].[bsASKInfo] ADD  CONSTRAINT [DF_bsASKInfo_GetWay]  DEFAULT ((0)) FOR [GetWay]
GO
ALTER TABLE [dbo].[bsASKInfo] ADD  CONSTRAINT [DF_bsASKInfo_ClickNumber]  DEFAULT ((0)) FOR [ClickNumber]
GO
ALTER TABLE [dbo].[bsBackLogin] ADD  CONSTRAINT [DF_bsAskLogin_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[bsCpBackLogin] ADD  CONSTRAINT [DF_bsCpBackLogin_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[bsCpBackLogin] ADD  CONSTRAINT [DF_bsCpBackLogin_HasLogin]  DEFAULT ((0)) FOR [HasLogin]
GO
ALTER TABLE [dbo].[bsCpModify] ADD  CONSTRAINT [DF_bsCpModify_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[bsCpStatus] ADD  CONSTRAINT [DF_bsCpStatus_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[bsCpVerify] ADD  CONSTRAINT [DF_bsCpVerify_VerifyDate]  DEFAULT (getdate()) FOR [VerifyDate]
GO
ALTER TABLE [dbo].[bsCpVerifyLog] ADD  CONSTRAINT [DF_bsCpVerifyLog_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[bsCpVerifyLog] ADD  CONSTRAINT [DF_bsCpVerifyLog_HasPassed]  DEFAULT ((0)) FOR [VerifyResult]
GO
ALTER TABLE [dbo].[bsCvModify] ADD  CONSTRAINT [DF_bsCvModify_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[bsCvReview] ADD  CONSTRAINT [DF_bsCvReview_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[bsCvVerify] ADD  CONSTRAINT [DF_bsCvVerify_VerifyDate]  DEFAULT (getdate()) FOR [VerifyDate]
GO
ALTER TABLE [dbo].[bsCvVerifyLog] ADD  CONSTRAINT [DF_bsCvVerifyLog_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[bsCvVerifyLog] ADD  CONSTRAINT [DF_bsCvVerifyLog_HasPassed]  DEFAULT ((0)) FOR [VerifyResult]
GO
ALTER TABLE [dbo].[bsDeleteFile] ADD  CONSTRAINT [DF_bsDeleteFile_IsDelete]  DEFAULT ((0)) FOR [IsDelete]
GO
ALTER TABLE [dbo].[bsDeleteFile] ADD  CONSTRAINT [DF_bsDeleteFile_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[bsJobProblem] ADD  CONSTRAINT [DF_bsJobProblem_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[bsMobileMessage] ADD  CONSTRAINT [DF_bsMobileContent_dcProvinceId]  DEFAULT ((0)) FOR [dcProvinceId]
GO
ALTER TABLE [dbo].[bsMobileMessage] ADD  CONSTRAINT [DF_bsMobileContent_BeginDate]  DEFAULT (getdate()) FOR [BeginDate]
GO
ALTER TABLE [dbo].[bsMobileMessage] ADD  CONSTRAINT [DF_bsMobileContent_EndDate]  DEFAULT (((2050)-(12))-(31)) FOR [EndDate]
GO
ALTER TABLE [dbo].[bsMobileMessage] ADD  CONSTRAINT [DF_bsMobileContent_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[bsMobileSpread] ADD  CONSTRAINT [DF_bsMobileSpread_SendTime]  DEFAULT ((0)) FOR [SendTime]
GO
ALTER TABLE [dbo].[bsMobileSpread] ADD  CONSTRAINT [DF_bsMobileSpread_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[bsPaBackLogin] ADD  CONSTRAINT [DF_bsPaBackLogin_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[bsPaBackLogin] ADD  CONSTRAINT [DF_bsPaBackLogin_HasLogin]  DEFAULT ((0)) FOR [HasLogin]
GO
ALTER TABLE [dbo].[bsRtxStatus] ADD  CONSTRAINT [DF_bsRtxStatus_CheckDay]  DEFAULT (CONVERT([char](8),getdate(),(112))) FOR [CheckDay]
GO
ALTER TABLE [dbo].[bsRtxStatus] ADD  CONSTRAINT [DF_bsRtxStatus_PreRtxStatus]  DEFAULT ((0)) FOR [PreRtxStatus]
GO
ALTER TABLE [dbo].[bsRtxStatus] ADD  CONSTRAINT [DF_bsRtxStatus_OnlineSecond]  DEFAULT ((0)) FOR [OnlineSecond]
GO
ALTER TABLE [dbo].[bsRtxStatus] ADD  CONSTRAINT [DF_bsRtxStatus_OfflineSecond]  DEFAULT ((0)) FOR [OfflineSecond]
GO
ALTER TABLE [dbo].[bsRtxStatus] ADD  CONSTRAINT [DF_bsRtxStatus_LeaveSecond]  DEFAULT ((0)) FOR [LeaveSecond]
GO
ALTER TABLE [dbo].[bsRtxStatus] ADD  CONSTRAINT [DF_Table_2_LogTime]  DEFAULT (getdate()) FOR [CheckTime]
GO
ALTER TABLE [dbo].[bsRtxStatus] ADD  CONSTRAINT [DF_bsRtxStatus_AllOnlineTime]  DEFAULT ((0)) FOR [AllOnlineTime]
GO
ALTER TABLE [dbo].[bsRtxStatusLog] ADD  CONSTRAINT [DF_bsRtxStatusLog_LogTime]  DEFAULT (getdate()) FOR [LogTime]
GO
ALTER TABLE [dbo].[bsSqlLog] ADD  CONSTRAINT [DF_backstagesql_adddate]  DEFAULT (getdate()) FOR [adddate]
GO
ALTER TABLE [dbo].[caActiveLog] ADD  CONSTRAINT [DF_caActiveLog_paName]  DEFAULT ('') FOR [paName]
GO
ALTER TABLE [dbo].[caActiveLog] ADD  CONSTRAINT [DF_caActiveDownloadLog_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[caActiveStatus] ADD  CONSTRAINT [DF__caActiveS__IsOnl__1BECE178]  DEFAULT ((1)) FOR [IsOnline]
GO
ALTER TABLE [dbo].[caActiveStatus] ADD  CONSTRAINT [DF__caActiveSt__IsVi__1CE105B1]  DEFAULT ((0)) FOR [IsVi]
GO
ALTER TABLE [dbo].[caBalanceLog] ADD  CONSTRAINT [DF_caConsumeLog_IsAgent]  DEFAULT ((0)) FOR [IsAgent]
GO
ALTER TABLE [dbo].[caBalanceLog] ADD  CONSTRAINT [DF_caConsumeLog_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[caContact] ADD  CONSTRAINT [DF_caContact_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[CaCvApplyDeleted] ADD  CONSTRAINT [DF_CaCvApplyDeleted_Adddate]  DEFAULT (getdate()) FOR [Adddate]
GO
ALTER TABLE [dbo].[CaCvApplyDeleted] ADD  DEFAULT ((0)) FOR [cvDeleted]
GO
ALTER TABLE [dbo].[CaCvApplyDeleted] ADD  DEFAULT ((0)) FOR [jobDeleted]
GO
ALTER TABLE [dbo].[caCvFinder] ADD  CONSTRAINT [DF_caCvFinder_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[caCvFinder] ADD  DEFAULT ((0)) FOR [EmailSent]
GO
ALTER TABLE [dbo].[caCvIntention] ADD  DEFAULT ((0)) FOR [PersonDeleted]
GO
ALTER TABLE [dbo].[caCvIntention] ADD  DEFAULT ((0)) FOR [CompanyDeleted]
GO
ALTER TABLE [dbo].[caCvIntention] ADD  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[caCvQuotaLog] ADD  CONSTRAINT [DF_caCvQuotaLog_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[caCvRemark] ADD  CONSTRAINT [DF_caCvRemark_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[caCvViewLog] ADD  CONSTRAINT [DF_caCvViewLog_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[caDailyGiftLog] ADD  CONSTRAINT [DF_caDailyGiftLog_ConsumeDate]  DEFAULT (CONVERT([varchar](8),getdate(),(112))) FOR [ConsumeDate]
GO
ALTER TABLE [dbo].[caDailyGiftLog] ADD  CONSTRAINT [DF_caDailyGiftLog_paName]  DEFAULT ('') FOR [paName]
GO
ALTER TABLE [dbo].[caDailyGiftLog] ADD  CONSTRAINT [DF_caDownloadLog_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[caFavorate] ADD  CONSTRAINT [DF_caFavorate_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[caFavorateMark] ADD  CONSTRAINT [DF_caFavorateMark_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[caFeedback] ADD  CONSTRAINT [DF_caFeedback_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[caFeedback] ADD  CONSTRAINT [DF_caFeedback_IsReply]  DEFAULT ((0)) FOR [IsReply]
GO
ALTER TABLE [dbo].[caFeePageViewLog] ADD  CONSTRAINT [DF_caFeePageViewLog_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[caGetPasswordLog] ADD  CONSTRAINT [DF_caGetPasswordLog_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[caGetSecondPasswordLog] ADD  CONSTRAINT [DF_caGetSecondPasswordLog_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[caInterviewTemplate] ADD  CONSTRAINT [DF_caInterviewTemplate_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[CaIosBind] ADD  CONSTRAINT [DF_CaIosBind_Adddate]  DEFAULT (getdate()) FOR [Adddate]
GO
ALTER TABLE [dbo].[caJobResumePre] ADD  CONSTRAINT [DF_caJobResumePre_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[caLoginLog] ADD  CONSTRAINT [DF_caLoginLog_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[caMain] ADD  CONSTRAINT [DF_caMain_RegDate]  DEFAULT (getdate()) FOR [RegDate]
GO
ALTER TABLE [dbo].[caMain] ADD  CONSTRAINT [DF_caMain_IsManager]  DEFAULT ((2)) FOR [AccountType]
GO
ALTER TABLE [dbo].[caMain] ADD  CONSTRAINT [DF_caMain_IsPhoneHide]  DEFAULT ((1)) FOR [IsPhoneHide]
GO
ALTER TABLE [dbo].[caMain] ADD  CONSTRAINT [DF_caMain_IsNameOpen]  DEFAULT ((0)) FOR [IsNameHide]
GO
ALTER TABLE [dbo].[caMain] ADD  CONSTRAINT [DF_caMain_IsMobileHide]  DEFAULT ((1)) FOR [IsMobileHide]
GO
ALTER TABLE [dbo].[caMain] ADD  CONSTRAINT [DF_caMain_EmailSentType]  DEFAULT ((0)) FOR [EmailSentType]
GO
ALTER TABLE [dbo].[caMain] ADD  CONSTRAINT [DF_caMain_IsPause]  DEFAULT ((0)) FOR [IsPause]
GO
ALTER TABLE [dbo].[caMain] ADD  CONSTRAINT [DF_caMain_IsDelete]  DEFAULT ((0)) FOR [IsDelete]
GO
ALTER TABLE [dbo].[caMain] ADD  CONSTRAINT [DF_caMain_LastModifyDate]  DEFAULT (getdate()) FOR [LastModifyDate]
GO
ALTER TABLE [dbo].[caMain] ADD  CONSTRAINT [DF_caMain_IsReceiveSms]  DEFAULT ((1)) FOR [IsReceiveSms]
GO
ALTER TABLE [dbo].[caMain] ADD  DEFAULT ((0)) FOR [IsShowEmailContact]
GO
ALTER TABLE [dbo].[caMain] ADD  DEFAULT (NULL) FOR [qqaddMan]
GO
ALTER TABLE [dbo].[caMain] ADD  DEFAULT (NULL) FOR [wechataddMan]
GO
ALTER TABLE [dbo].[CampusRecruitold] ADD  CONSTRAINT [DF_CampusRecruit_type]  DEFAULT ((0)) FOR [type]
GO
ALTER TABLE [dbo].[CampusRecruitold] ADD  CONSTRAINT [DF_CampusRecruit_ClickNumber]  DEFAULT ((0)) FOR [ClickNumber]
GO
ALTER TABLE [dbo].[CampusRecruitold] ADD  CONSTRAINT [DF_CampusRecruit_AllClickNumber]  DEFAULT ((0)) FOR [AllClickNumber]
GO
ALTER TABLE [dbo].[CampusRecruitold] ADD  CONSTRAINT [DF_CampusRecruit_RefreshDate]  DEFAULT (getdate()) FOR [RefreshDate]
GO
ALTER TABLE [dbo].[CampusRecruitold] ADD  CONSTRAINT [DF_CampusRecruit_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[CaOnline] ADD  CONSTRAINT [DF_CaOnline_IsVi]  DEFAULT ((0)) FOR [IsVi]
GO
ALTER TABLE [dbo].[caOperationLog] ADD  CONSTRAINT [DF_caOperationLog_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[caOrder] ADD  CONSTRAINT [DF_caOrder_OrderStatus]  DEFAULT ((0)) FOR [OrderStatus]
GO
ALTER TABLE [dbo].[caOrder] ADD  CONSTRAINT [DF_caOrder_SmsMobileNumber]  DEFAULT ((0)) FOR [SmsMobileNumber]
GO
ALTER TABLE [dbo].[caOrder] ADD  CONSTRAINT [DF_caOrder_IsDeleted]  DEFAULT ((0)) FOR [IsDeleted]
GO
ALTER TABLE [dbo].[caOrder] ADD  CONSTRAINT [DF_caOrder_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[caOrder] ADD  CONSTRAINT [DF_caOrder_IsBackSubmit]  DEFAULT ((0)) FOR [IsBackSubmit]
GO
ALTER TABLE [dbo].[caOrder] ADD  DEFAULT ((0)) FOR [isCvAllocate]
GO
ALTER TABLE [dbo].[caOrderRemarks] ADD  CONSTRAINT [DF_caOrderRemarks_adddate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[caPageViewLog] ADD  CONSTRAINT [DF_caPageViewLog_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[caPlaint] ADD  CONSTRAINT [DF_caPlaint_adddate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[caPlaint] ADD  CONSTRAINT [DF_caPlaint_status]  DEFAULT ((0)) FOR [ReplyType]
GO
ALTER TABLE [dbo].[caPlaint] ADD  CONSTRAINT [DF_caPlaint_Viewed]  DEFAULT ((0)) FOR [IsViewed]
GO
ALTER TABLE [dbo].[Certificate_UnReal] ADD  CONSTRAINT [DF_Certificate_UnReal_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[ChatLogTemp] ADD  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[ChatOnline] ADD  CONSTRAINT [DF_ChatOnline_IsCaViewed]  DEFAULT ((1)) FOR [caUnViewed]
GO
ALTER TABLE [dbo].[ChatOnline] ADD  CONSTRAINT [DF_ChatOnline_IsPaViewed]  DEFAULT ((1)) FOR [paUnViewed]
GO
ALTER TABLE [dbo].[ChatOnlineLog] ADD  CONSTRAINT [DF_ChatOnlineLog_IsViewed]  DEFAULT ((0)) FOR [IsViewed]
GO
ALTER TABLE [dbo].[ChatOnlineLog] ADD  CONSTRAINT [DF_ChatOnlineLog_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[ChatOnlineLog] ADD  DEFAULT ((1)) FOR [MessageType]
GO
ALTER TABLE [dbo].[ColdContact] ADD  CONSTRAINT [DF_ColdContact_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[ColdCustomer] ADD  CONSTRAINT [DF_ColdCustomer_IsCustom]  DEFAULT ((0)) FOR [RegType]
GO
ALTER TABLE [dbo].[ColdCustomer] ADD  CONSTRAINT [DF_ColdCustomer_Status]  DEFAULT ((1)) FOR [Status]
GO
ALTER TABLE [dbo].[ColdCustomerAllocateLog] ADD  CONSTRAINT [DF_ColdCustomerAllocateLog_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[coldCustomerRelease] ADD  CONSTRAINT [DF_coldCustomerRelease_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[CommentPraise] ADD  CONSTRAINT [DF_CommentPraise_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[Company_Black] ADD  CONSTRAINT [DF_company_black_addeddate]  DEFAULT (getdate()) FOR [addeddate]
GO
ALTER TABLE [dbo].[Company_Black] ADD  CONSTRAINT [DF_company_black_refusecount]  DEFAULT ((0)) FOR [refusecount]
GO
ALTER TABLE [dbo].[Company_deleted] ADD  CONSTRAINT [DF_Company_deleted_addDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[Company_Xinxi] ADD  CONSTRAINT [DF_company_xinxi_regdate]  DEFAULT (getdate()) FOR [RegDate]
GO
ALTER TABLE [dbo].[Company_Xinxi] ADD  CONSTRAINT [DF_Company_Xinxi_IsHistory]  DEFAULT ((0)) FOR [IsHistory]
GO
ALTER TABLE [dbo].[CompanyAssignLog] ADD  CONSTRAINT [DF_CompanyAssignLog_addDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[CompanyInform] ADD  CONSTRAINT [DF_Companyinform_addDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[CompanyInform] ADD  CONSTRAINT [DF_Companyinform_status]  DEFAULT ((1)) FOR [Status]
GO
ALTER TABLE [dbo].[CompanyInform] ADD  CONSTRAINT [DF_Companyinform_at1]  DEFAULT ((0)) FOR [at1]
GO
ALTER TABLE [dbo].[CompanyInform] ADD  CONSTRAINT [DF_Companyinform_at2]  DEFAULT ((0)) FOR [at2]
GO
ALTER TABLE [dbo].[CompanyInform] ADD  CONSTRAINT [DF_Companyinform_at3]  DEFAULT ((0)) FOR [at3]
GO
ALTER TABLE [dbo].[CompanyNotify] ADD  CONSTRAINT [DF_CompanyNotify_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[CompanyNotify] ADD  CONSTRAINT [DF_CompanyNotify_Received]  DEFAULT ((0)) FOR [Received]
GO
ALTER TABLE [dbo].[Consultant_assign] ADD  CONSTRAINT [DF_Consultant_assign_current_power]  DEFAULT ((0)) FOR [Current_Power]
GO
ALTER TABLE [dbo].[Consultant_assign] ADD  CONSTRAINT [DF_Consultant_assign_status]  DEFAULT ((1)) FOR [Status]
GO
ALTER TABLE [dbo].[Consultant_Factor] ADD  CONSTRAINT [DF_Consultant_Factor_Factor_dead]  DEFAULT ((0)) FOR [Factor_dead_first]
GO
ALTER TABLE [dbo].[Contact] ADD  CONSTRAINT [DF_Contact_addDate]  DEFAULT (getdate()) FOR [addDate]
GO
ALTER TABLE [dbo].[Contact] ADD  CONSTRAINT [DF_Contact_CompanyType]  DEFAULT (NULL) FOR [CompanyType]
GO
ALTER TABLE [dbo].[Coorperation] ADD  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[counter] ADD  CONSTRAINT [DF_counter_viewnumber]  DEFAULT ((0)) FOR [viewnumber]
GO
ALTER TABLE [dbo].[counter] ADD  CONSTRAINT [DF_counter_spIderviewnumber]  DEFAULT ((0)) FOR [spIderviewnumber]
GO
ALTER TABLE [dbo].[cpAttachment] ADD  CONSTRAINT [DF_cpAttachment_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[cpCertification] ADD  CONSTRAINT [DF_cpCertification_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[cpCoin] ADD  CONSTRAINT [DF_cpCoin_IsCancel]  DEFAULT ((0)) FOR [IsCancel]
GO
ALTER TABLE [dbo].[cpCompanyEmail] ADD  CONSTRAINT [DF_cpCompanyEmail_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[cpCorporationAccount] ADD  CONSTRAINT [DF_cpCorporationAccount_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[cpImage] ADD  CONSTRAINT [DF_cpImage_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[cpLicence] ADD  CONSTRAINT [DF_cpLicence_FileSource]  DEFAULT ((0)) FOR [FileSource]
GO
ALTER TABLE [dbo].[cpLicence] ADD  CONSTRAINT [DF_cpLicence_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[cpLicenceChangeLog] ADD  CONSTRAINT [DF_cpLicenceChangLog_adddate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[cpLicenceLog] ADD  CONSTRAINT [DF_cpLicenceLog_adddate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[cpMain] ADD  CONSTRAINT [DF_cpMain_RegDate]  DEFAULT (getdate()) FOR [RegDate]
GO
ALTER TABLE [dbo].[cpMain] ADD  CONSTRAINT [DF_cpMain_RegisterMode]  DEFAULT ((0)) FOR [RegisterMode]
GO
ALTER TABLE [dbo].[cpMain] ADD  CONSTRAINT [DF_cpMain_IsDefaultPassword]  DEFAULT ((0)) FOR [IsDefaultPassword]
GO
ALTER TABLE [dbo].[cpMain] ADD  CONSTRAINT [DF_cpMain_HasLicence]  DEFAULT ((0)) FOR [HasLicence]
GO
ALTER TABLE [dbo].[cpMain] ADD  CONSTRAINT [DF_cpMain_HasLogo]  DEFAULT ((0)) FOR [HasLogo]
GO
ALTER TABLE [dbo].[cpMain] ADD  CONSTRAINT [DF_cpMain_HasVisual]  DEFAULT ((0)) FOR [HasVisual]
GO
ALTER TABLE [dbo].[cpMain] ADD  CONSTRAINT [DF_cpMain_DailyGiftQuota]  DEFAULT ((0)) FOR [DailyGiftQuota]
GO
ALTER TABLE [dbo].[cpMain] ADD  CONSTRAINT [DF_cpMain_UnlimitedDate]  DEFAULT (getdate()-(365)) FOR [UnlimitedDate]
GO
ALTER TABLE [dbo].[cpMain] ADD  CONSTRAINT [DF_cpMain_BalanceDate]  DEFAULT (getdate()-(365)) FOR [BalanceDate]
GO
ALTER TABLE [dbo].[cpMain] ADD  CONSTRAINT [DF_cpMain_Balance]  DEFAULT ((0)) FOR [Balance]
GO
ALTER TABLE [dbo].[cpMain] ADD  CONSTRAINT [DF_cpMain_ResumeQuota]  DEFAULT ((0)) FOR [ResumeQuota]
GO
ALTER TABLE [dbo].[cpMain] ADD  CONSTRAINT [DF_cpMain_MaxUserNumber]  DEFAULT ((1)) FOR [MaxUserNumber]
GO
ALTER TABLE [dbo].[cpMain] ADD  CONSTRAINT [DF_cpMain_MaxJobNumber]  DEFAULT ((0)) FOR [MaxJobNumber]
GO
ALTER TABLE [dbo].[cpMain] ADD  CONSTRAINT [DF_cpMain_IsAgent]  DEFAULT ((0)) FOR [IsAgent]
GO
ALTER TABLE [dbo].[cpMain] ADD  CONSTRAINT [DF_cpMain_IsLimitLogin]  DEFAULT ((0)) FOR [IsLimitLogin]
GO
ALTER TABLE [dbo].[cpMain] ADD  CONSTRAINT [DF_cpMain_IsLock]  DEFAULT ((0)) FOR [Islock]
GO
ALTER TABLE [dbo].[cpMain] ADD  CONSTRAINT [DF_cpMain_IsDelete]  DEFAULT ((0)) FOR [IsDelete]
GO
ALTER TABLE [dbo].[cpMain] ADD  CONSTRAINT [DF_cpMain_MemberType]  DEFAULT ((0)) FOR [MemberType]
GO
ALTER TABLE [dbo].[cpMain] ADD  CONSTRAINT [DF_cpMain_VerifyResult]  DEFAULT ((1)) FOR [VerifyResult]
GO
ALTER TABLE [dbo].[cpMain] ADD  CONSTRAINT [DF_cpMain_BlockNumber]  DEFAULT ((0)) FOR [BlockCount]
GO
ALTER TABLE [dbo].[cpMain] ADD  CONSTRAINT [DF_cpMain_VerifyCount]  DEFAULT ((0)) FOR [VerifyCount]
GO
ALTER TABLE [dbo].[cpMain] ADD  CONSTRAINT [DF_cpMain_LoginCount]  DEFAULT ((0)) FOR [LoginCount]
GO
ALTER TABLE [dbo].[cpMain] ADD  CONSTRAINT [DF_cpMain_JobNumber]  DEFAULT ((0)) FOR [JobNumber]
GO
ALTER TABLE [dbo].[cpMain] ADD  CONSTRAINT [DF_cpMain_ViewNumber]  DEFAULT ((0)) FOR [ViewNumber]
GO
ALTER TABLE [dbo].[cpMain] ADD  CONSTRAINT [DF_cpMain_LastModifyDate]  DEFAULT (getdate()) FOR [LastModifyDate]
GO
ALTER TABLE [dbo].[cpMain] ADD  DEFAULT ((0)) FOR [IsProtect]
GO
ALTER TABLE [dbo].[cpMain] ADD  CONSTRAINT [DF_cpMain_remainpoint]  DEFAULT ((0)) FOR [RemainPoint]
GO
ALTER TABLE [dbo].[cpMain] ADD  DEFAULT ((0)) FOR [RemainCoin]
GO
ALTER TABLE [dbo].[cpMain] ADD  DEFAULT ((0)) FOR [RealName]
GO
ALTER TABLE [dbo].[cpMain] ADD  DEFAULT ((0)) FOR [CommentNumber]
GO
ALTER TABLE [dbo].[cpMain] ADD  DEFAULT ((0)) FOR [InterViewNumber]
GO
ALTER TABLE [dbo].[cpMainLimited] ADD  CONSTRAINT [DF_cpMainLimited_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[cpMainPublish] ADD  CONSTRAINT [DF_cpMainPublish_HasLicence]  DEFAULT ((0)) FOR [HasLicence]
GO
ALTER TABLE [dbo].[cpMainPublish] ADD  CONSTRAINT [DF_cpMainPublish_UnlimitedDate]  DEFAULT (getdate()-(365)) FOR [UnlimitedDate]
GO
ALTER TABLE [dbo].[cpMainPublish] ADD  CONSTRAINT [DF_cpMainPublish_BalanceDate]  DEFAULT (getdate()-(365)) FOR [BalanceDate]
GO
ALTER TABLE [dbo].[cpMainPublish] ADD  CONSTRAINT [DF_cpMainPublish_Balance]  DEFAULT ((0)) FOR [Balance]
GO
ALTER TABLE [dbo].[cpMainPublish] ADD  CONSTRAINT [DF_cpMainPublish_MemberType]  DEFAULT ((0)) FOR [MemberType]
GO
ALTER TABLE [dbo].[cpMainPublish] ADD  CONSTRAINT [DF_cpMainPublish_LastModifyDate]  DEFAULT (getdate()) FOR [LastModifyDate]
GO
ALTER TABLE [dbo].[cpMainPublish] ADD  DEFAULT ((0)) FOR [IsRefreshed]
GO
ALTER TABLE [dbo].[cpMainPublish] ADD  DEFAULT ((0)) FOR [HasEnvironment]
GO
ALTER TABLE [dbo].[cpMainRelease] ADD  CONSTRAINT [DF_cpMainRelease_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[cpPersonalAccount] ADD  CONSTRAINT [DF_cpPersonalAccount_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[CpRealNameLog] ADD  CONSTRAINT [DF_CpRealNameLog_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[CpRealNameLog] ADD  DEFAULT ((0)) FOR [CheckMan]
GO
ALTER TABLE [dbo].[cpRefreshLog] ADD  DEFAULT (getdate()) FOR [RefreshDate]
GO
ALTER TABLE [dbo].[cpRemark] ADD  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[cpSession] ADD  CONSTRAINT [DF_cpSession_CheckDate]  DEFAULT (getdate()) FOR [RefreshDate]
GO
ALTER TABLE [dbo].[cpSession] ADD  CONSTRAINT [DF_Table_1_OnlineTime]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[Customer_Assign] ADD  CONSTRAINT [DF_customer_assign_current_power]  DEFAULT ((0)) FOR [Current_Power]
GO
ALTER TABLE [dbo].[Customer_Assign] ADD  CONSTRAINT [DF_customer_assign_status]  DEFAULT ((1)) FOR [Status]
GO
ALTER TABLE [dbo].[Customer_Target] ADD  CONSTRAINT [DF_customer_target_addDate]  DEFAULT (getdate()) FOR [addDate]
GO
ALTER TABLE [dbo].[Customer_Target] ADD  CONSTRAINT [DF_customer_target_status]  DEFAULT ((0)) FOR [Status]
GO
ALTER TABLE [dbo].[cvAttachment] ADD  CONSTRAINT [DF_cvAttachment_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[cvDownDoc] ADD  DEFAULT ((0)) FOR [ViewCount]
GO
ALTER TABLE [dbo].[cvDownDoc] ADD  DEFAULT ((0)) FOR [DownCount]
GO
ALTER TABLE [dbo].[cvMain] ADD  CONSTRAINT [DF_cvMain_IsNegotiable]  DEFAULT ((0)) FOR [IsNegotiable]
GO
ALTER TABLE [dbo].[cvMain] ADD  CONSTRAINT [DF_cvMain_cvType]  DEFAULT ((0)) FOR [cvType]
GO
ALTER TABLE [dbo].[cvMain] ADD  CONSTRAINT [DF_cvMain_IsNameHidden]  DEFAULT ((0)) FOR [IsNameHidden]
GO
ALTER TABLE [dbo].[cvMain] ADD  CONSTRAINT [DF_cvMain_IsCvHidden]  DEFAULT ((0)) FOR [IscvHidden]
GO
ALTER TABLE [dbo].[cvMain] ADD  CONSTRAINT [DF_cvMain_IsOpen]  DEFAULT ((0)) FOR [isOpen]
GO
ALTER TABLE [dbo].[cvMain] ADD  CONSTRAINT [DF_cvMain_cvLevel]  DEFAULT ('1000000000') FOR [cvLevel]
GO
ALTER TABLE [dbo].[cvMain] ADD  CONSTRAINT [DF_cvMain_cvLevelEng]  DEFAULT ('0000000000') FOR [cvLevelEng]
GO
ALTER TABLE [dbo].[cvMain] ADD  CONSTRAINT [DF_cvMain_VerifyResult]  DEFAULT ((1)) FOR [VerifyResult]
GO
ALTER TABLE [dbo].[cvMain] ADD  CONSTRAINT [DF_cvMain_VerifyResultEng]  DEFAULT ((1)) FOR [VerifyResultEng]
GO
ALTER TABLE [dbo].[cvMain] ADD  CONSTRAINT [DF_cvMain_Valid]  DEFAULT ((0)) FOR [Valid]
GO
ALTER TABLE [dbo].[cvMain] ADD  CONSTRAINT [DF_cvMain_ViewNumber]  DEFAULT ((0)) FOR [ViewNumber]
GO
ALTER TABLE [dbo].[cvMain] ADD  CONSTRAINT [DF_cvMain_RefreshDate]  DEFAULT (getdate()) FOR [RefreshDate]
GO
ALTER TABLE [dbo].[cvMain] ADD  DEFAULT ((0)) FOR [IsVerified]
GO
ALTER TABLE [dbo].[cvMainDel] ADD  DEFAULT ((0)) FOR [IsVerified]
GO
ALTER TABLE [dbo].[cvMainPublish] ADD  CONSTRAINT [DF_cvMainPublish_IsNegotiable]  DEFAULT ((0)) FOR [IsNegotiable]
GO
ALTER TABLE [dbo].[cvMainPublish] ADD  CONSTRAINT [DF_cvMainPublish_Valid]  DEFAULT ((0)) FOR [Valid]
GO
ALTER TABLE [dbo].[cvMainPublish] ADD  CONSTRAINT [DF_cvMainPublish_RefreshDate]  DEFAULT (getdate()) FOR [RefreshDate]
GO
ALTER TABLE [dbo].[CvSimilarCompare] ADD  CONSTRAINT [DF_CvLimiteCompare_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[cvTags] ADD  CONSTRAINT [DF_CvTags_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[cvVoiceText] ADD  CONSTRAINT [DF_cvVoiceText_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[Datereport] ADD  CONSTRAINT [DF_Datereport2_CompanyRegNum]  DEFAULT ((0)) FOR [CompanyRegNum]
GO
ALTER TABLE [dbo].[Datereport] ADD  CONSTRAINT [DF_Datereport2_PersonRegNum]  DEFAULT ((0)) FOR [PersonRegNum]
GO
ALTER TABLE [dbo].[Datereport] ADD  CONSTRAINT [DF_Datereport2_NewJobNum]  DEFAULT ((0)) FOR [NewJobNum]
GO
ALTER TABLE [dbo].[Datereport] ADD  CONSTRAINT [DF_Datereport2_DeleteJobNum]  DEFAULT ((0)) FOR [DeleteJobNum]
GO
ALTER TABLE [dbo].[Datereport] ADD  CONSTRAINT [DF_Datereport2_CompanyRegNum_Our]  DEFAULT ((0)) FOR [CompanyRegNum_Our]
GO
ALTER TABLE [dbo].[Datereport] ADD  CONSTRAINT [DF_Datereport2_PersonRegNum_Our]  DEFAULT ((0)) FOR [PersonRegNum_Our]
GO
ALTER TABLE [dbo].[Datereport] ADD  CONSTRAINT [DF_Datereport2_ValidCompany]  DEFAULT ((0)) FOR [ValidCompany]
GO
ALTER TABLE [dbo].[Datereport] ADD  CONSTRAINT [DF_Datereport2_ValidResume]  DEFAULT ((0)) FOR [ValidResume]
GO
ALTER TABLE [dbo].[Datereport] ADD  CONSTRAINT [DF_Datereport2_CompanyloginNum_Net]  DEFAULT ((0)) FOR [CompanyloginNum_Net]
GO
ALTER TABLE [dbo].[Datereport] ADD  CONSTRAINT [DF_Datereport2_PersonloginNum_Net]  DEFAULT ((0)) FOR [PersonloginNum_Net]
GO
ALTER TABLE [dbo].[Datereport] ADD  CONSTRAINT [DF_Datereport_DeleteCompanyNum]  DEFAULT ((0)) FOR [DeleteCompanyNum]
GO
ALTER TABLE [dbo].[Datereport] ADD  CONSTRAINT [DF_Datereport_CompanyPassed]  DEFAULT ((0)) FOR [CompanyPassed]
GO
ALTER TABLE [dbo].[dcFee] ADD  CONSTRAINT [DF_dcFee_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[dcFeeStandard] ADD  DEFAULT ((0)) FOR [NeedPoint]
GO
ALTER TABLE [dbo].[dcIPPlace] ADD  CONSTRAINT [DF_dcIPPlace_City]  DEFAULT ('') FOR [City]
GO
ALTER TABLE [dbo].[dcIPPlace] ADD  CONSTRAINT [DF_dcIPPlace_Provider]  DEFAULT ('') FOR [Provider]
GO
ALTER TABLE [dbo].[dcJobTypeSimilar] ADD  CONSTRAINT [DF_dcJobTypeSimilar_Coefficient]  DEFAULT ((1)) FOR [Coefficient]
GO
ALTER TABLE [dbo].[dcNewsType] ADD  CONSTRAINT [DF_dcNewsType_OrderNo]  DEFAULT ((0)) FOR [OrderNo]
GO
ALTER TABLE [dbo].[dcPayMethod] ADD  DEFAULT ((0)) FOR [FrontShow]
GO
ALTER TABLE [dbo].[dcRegion] ADD  CONSTRAINT [DF_dcRegion_Grade]  DEFAULT ((1)) FOR [Grade]
GO
ALTER TABLE [dbo].[dcRegionTDK] ADD  CONSTRAINT [DF_dcRegionTDK_Title]  DEFAULT ('') FOR [Title]
GO
ALTER TABLE [dbo].[dcRegionTDK] ADD  CONSTRAINT [DF_dcRegionTDK_DESCRIPTION]  DEFAULT ('') FOR [Description]
GO
ALTER TABLE [dbo].[dcRegionTDK] ADD  CONSTRAINT [DF_dcRegionTDK_Keyword]  DEFAULT ('') FOR [Keyword]
GO
ALTER TABLE [dbo].[dcRunParameter] ADD  CONSTRAINT [DF_dcRunParameter_Description]  DEFAULT ('') FOR [Description]
GO
ALTER TABLE [dbo].[dcRunParameter] ADD  CONSTRAINT [DF_dcRunParameter_System]  DEFAULT ((1)) FOR [System]
GO
ALTER TABLE [dbo].[dcVip] ADD  CONSTRAINT [DF_dcVip_PriceJob]  DEFAULT ((0)) FOR [PriceJob]
GO
ALTER TABLE [dbo].[dcVip] ADD  CONSTRAINT [DF_dcVip_PriceUser]  DEFAULT ((0)) FOR [PriceUser]
GO
ALTER TABLE [dbo].[dcVip] ADD  CONSTRAINT [DF_dcVip_PriceResume]  DEFAULT ((0)) FOR [PriceResume]
GO
ALTER TABLE [dbo].[dcVip] ADD  CONSTRAINT [DF_dcVip_PriceMonth]  DEFAULT ((0)) FOR [PriceMonth]
GO
ALTER TABLE [dbo].[dcVip] ADD  CONSTRAINT [DF_dcVip_addDate]  DEFAULT (getdate()) FOR [addDate]
GO
ALTER TABLE [dbo].[dcVipDetail] ADD  CONSTRAINT [DF__dcVipDeta__IsSho__136CAA10]  DEFAULT ((0)) FOR [IsShowFront]
GO
ALTER TABLE [dbo].[dcVipDetail] ADD  DEFAULT ((0)) FOR [Discount]
GO
ALTER TABLE [dbo].[Dept] ADD  CONSTRAINT [DF_dept_valid]  DEFAULT ((1)) FOR [Valid]
GO
ALTER TABLE [dbo].[dwnclass1] ADD  CONSTRAINT [DF_dwnclass1_adddate]  DEFAULT (getdate()) FOR [adddate]
GO
ALTER TABLE [dbo].[dwnclass1] ADD  CONSTRAINT [DF_dwnclass1_power]  DEFAULT ((0)) FOR [power]
GO
ALTER TABLE [dbo].[dwnclass2] ADD  CONSTRAINT [DF_dwnclass2_adddate]  DEFAULT (getdate()) FOR [adddate]
GO
ALTER TABLE [dbo].[dwnclass2] ADD  CONSTRAINT [DF_dwnclass2_power]  DEFAULT ((0)) FOR [power]
GO
ALTER TABLE [dbo].[dwndoc] ADD  CONSTRAINT [DF_dwndoc_adddate]  DEFAULT (getdate()) FOR [adddate]
GO
ALTER TABLE [dbo].[dwndoc] ADD  CONSTRAINT [DF_dwndoc_dwnnum]  DEFAULT ((0)) FOR [dwnnum]
GO
ALTER TABLE [dbo].[dwndoc] ADD  CONSTRAINT [DF_dwndoc_power]  DEFAULT ((0)) FOR [power]
GO
ALTER TABLE [dbo].[dwndoc] ADD  CONSTRAINT [DF_dwndoc_geren]  DEFAULT ((1)) FOR [geren]
GO
ALTER TABLE [dbo].[dwndoc] ADD  CONSTRAINT [DF_dwndoc_danwei]  DEFAULT ((1)) FOR [danwei]
GO
ALTER TABLE [dbo].[dwndoc] ADD  CONSTRAINT [DF_dwndoc_updatedate]  DEFAULT (getdate()) FOR [updatedate]
GO
ALTER TABLE [dbo].[Email_SentTest] ADD  CONSTRAINT [DF_email_senttest_adddate]  DEFAULT (getdate()) FOR [adddate]
GO
ALTER TABLE [dbo].[Email_SentTest_Log] ADD  CONSTRAINT [DF_email_senttest_log_adddate]  DEFAULT (getdate()) FOR [adddate]
GO
ALTER TABLE [dbo].[Email_SentTest_Log] ADD  CONSTRAINT [DF_email_senttest_log_status]  DEFAULT ((0)) FOR [status]
GO
ALTER TABLE [dbo].[EmailBody] ADD  CONSTRAINT [DF_EmailBody_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[EmailCompany] ADD  CONSTRAINT [DF_EmailJobResume_adddate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[EmailDomain] ADD  CONSTRAINT [DF_EmailDomain_adddate]  DEFAULT (getdate()) FOR [adddate]
GO
ALTER TABLE [dbo].[EmailTitleold] ADD  CONSTRAINT [DF_EmailTitle_adddate]  DEFAULT (getdate()) FOR [adddate]
GO
ALTER TABLE [dbo].[exImage] ADD  CONSTRAINT [DF_exImage_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[exInterview] ADD  CONSTRAINT [DF_exInterview_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[exInterview] ADD  CONSTRAINT [DF_Table_1_Replt]  DEFAULT ((0)) FOR [Reply]
GO
ALTER TABLE [dbo].[exInterview] ADD  CONSTRAINT [DF_exInterview_CompanyDeleted]  DEFAULT ((0)) FOR [CompanyDeleted]
GO
ALTER TABLE [dbo].[exInterview] ADD  CONSTRAINT [DF_exInterview_PersonDeleted]  DEFAULT ((0)) FOR [PersonDeleted]
GO
ALTER TABLE [dbo].[exInterview] ADD  DEFAULT ((0)) FOR [SmsNumber]
GO
ALTER TABLE [dbo].[exJobApply] ADD  CONSTRAINT [DF_exJobApply_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[exJobApply] ADD  CONSTRAINT [DF_exJobApply_CompanyDeleted]  DEFAULT ((0)) FOR [CompanyDeleted]
GO
ALTER TABLE [dbo].[exJobApply] ADD  CONSTRAINT [DF_exJobApply_PersonDeleted]  DEFAULT ((0)) FOR [PersonDeleted]
GO
ALTER TABLE [dbo].[exJobApply] ADD  CONSTRAINT [DF_exJobApply_Reply]  DEFAULT ((0)) FOR [Reply]
GO
ALTER TABLE [dbo].[exJobApply] ADD  CONSTRAINT [DF_exJobApply_ApplyStatus]  DEFAULT ((0)) FOR [IsPassed]
GO
ALTER TABLE [dbo].[exJobApply] ADD  CONSTRAINT [DF_exJobApply_IsTempInsert]  DEFAULT ((0)) FOR [IsTempInsert]
GO
ALTER TABLE [dbo].[exJobApply] ADD  DEFAULT ((0)) FOR [IsDeleted]
GO
ALTER TABLE [dbo].[exMessageC2P] ADD  CONSTRAINT [DF_exMessageC2P_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[exMessageC2P] ADD  CONSTRAINT [DF_exMessageC2P_IsViewed]  DEFAULT ((0)) FOR [IsViewed]
GO
ALTER TABLE [dbo].[exMessageC2P] ADD  CONSTRAINT [DF_exMessageC2P_IsReplay]  DEFAULT ((0)) FOR [IsReply]
GO
ALTER TABLE [dbo].[exMessageC2P] ADD  CONSTRAINT [DF_exMessageC2P_CompanyDeleted]  DEFAULT ((0)) FOR [CompanyDeleted]
GO
ALTER TABLE [dbo].[exMessageC2P] ADD  CONSTRAINT [DF_exMessageC2P_PersonDeleted]  DEFAULT ((0)) FOR [PersonDeleted]
GO
ALTER TABLE [dbo].[exMessageP2C] ADD  CONSTRAINT [DF_exMessageP2C_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[exMessageP2C] ADD  CONSTRAINT [DF_exMessageP2C_IsViewed]  DEFAULT ((0)) FOR [IsViewed]
GO
ALTER TABLE [dbo].[exMessageP2C] ADD  CONSTRAINT [DF_exMessageP2C_IsReplay]  DEFAULT ((0)) FOR [IsReply]
GO
ALTER TABLE [dbo].[exMessageP2C] ADD  CONSTRAINT [DF_exMessageP2C_CompanyDeleted]  DEFAULT ((0)) FOR [CompanyDeleted]
GO
ALTER TABLE [dbo].[exMessageP2C] ADD  CONSTRAINT [DF_exMessageP2C_PersonDeleted]  DEFAULT ((0)) FOR [PersonDeleted]
GO
ALTER TABLE [dbo].[ExtendLink] ADD  CONSTRAINT [DF__ExtendLin__LinkS__10B1044D]  DEFAULT ((0)) FOR [LinkStatusPre]
GO
ALTER TABLE [dbo].[Faq] ADD  CONSTRAINT [DF_faq_clicknum]  DEFAULT ((0)) FOR [ClickNum]
GO
ALTER TABLE [dbo].[Faq] ADD  CONSTRAINT [DF_faq_addDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[Faq] ADD  CONSTRAINT [DF_faq_modifyDate]  DEFAULT (getdate()) FOR [ModifyDate]
GO
ALTER TABLE [dbo].[FaxReceive] ADD  CONSTRAINT [DF_FaxReceive_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[FaxReceive] ADD  CONSTRAINT [DF_FaxReceive_isSuccess]  DEFAULT ((1)) FOR [isSuccess]
GO
ALTER TABLE [dbo].[FaxReceive] ADD  CONSTRAINT [DF__FaxReceiv__IsDon__084E6671]  DEFAULT ((0)) FOR [IsDone]
GO
ALTER TABLE [dbo].[FaxSend] ADD  CONSTRAINT [DF_FaxSend_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[Feedback_NoReg] ADD  CONSTRAINT [DF_feedback_noreg_addDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[Feedback_NoReg] ADD  CONSTRAINT [DF_feedback_noreg_reply]  DEFAULT ((0)) FOR [Reply]
GO
ALTER TABLE [dbo].[FeeLog] ADD  CONSTRAINT [DF_feelog_occur_Date]  DEFAULT (getdate()) FOR [Occur_Date]
GO
ALTER TABLE [dbo].[FlowChart] ADD  CONSTRAINT [DF_FlowChart_addDate]  DEFAULT (getdate()) FOR [addDate]
GO
ALTER TABLE [dbo].[FnBankCheck] ADD  CONSTRAINT [DF_FnBankCheck_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[FnBankCheck] ADD  CONSTRAINT [DF_FnBankCheck_status]  DEFAULT ((1)) FOR [Status]
GO
ALTER TABLE [dbo].[FnBankDaybook] ADD  CONSTRAINT [DF_FnBankDaybook_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[FnCash] ADD  CONSTRAINT [DF_FnCash_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[FnInvoice] ADD  CONSTRAINT [DF_FnInvoice_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[FnInvoice] ADD  CONSTRAINT [DF_FnInvoice_Status]  DEFAULT ((0)) FOR [Status]
GO
ALTER TABLE [dbo].[FnLetter] ADD  CONSTRAINT [DF_FnLetter_PostAddress]  DEFAULT (getdate()) FOR [PostAddress]
GO
ALTER TABLE [dbo].[FnLetter] ADD  CONSTRAINT [DF_FnLetter_Status]  DEFAULT ((1)) FOR [Status]
GO
ALTER TABLE [dbo].[FnPICDaybook] ADD  CONSTRAINT [DF_FnPBankDaybook_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[fpCommonSearch] ADD  CONSTRAINT [DF_fpCommonSearch_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[fpFixPositionOld] ADD  DEFAULT ('N') FOR [NoFollow]
GO
ALTER TABLE [dbo].[FriendLinkBlack] ADD  CONSTRAINT [DF_FriendLinkBlack_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[group_province] ADD  DEFAULT ((0)) FOR [IsSet]
GO
ALTER TABLE [dbo].[HomepageSeoLog] ADD  CONSTRAINT [DF_HomepageSeoLog_addDate]  DEFAULT (getdate()) FOR [addDate]
GO
ALTER TABLE [dbo].[hpHighSalaryCompany] ADD  CONSTRAINT [DF_hpHighSalaryCompany_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[hpHighSalaryCompany] ADD  CONSTRAINT [DF_hpHighSalaryCompany_RowNo]  DEFAULT ((0)) FOR [RowNo]
GO
ALTER TABLE [dbo].[hpHighSalaryCompanyNew] ADD  CONSTRAINT [DF_hpHighSalaryCompanyNew_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[hpHighSalaryCompanyNew] ADD  CONSTRAINT [DF_hpHighSalaryCompanyNew_RowNo]  DEFAULT ((0)) FOR [RowNo]
GO
ALTER TABLE [dbo].[hpHighSalaryJob] ADD  CONSTRAINT [DF_hpHighSalaryJob_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[hpHighSalaryJobNew] ADD  CONSTRAINT [DF_hpHighSalaryJobNew_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[hpJobTypeCpLogo] ADD  CONSTRAINT [DF_hpJobTypeCpLogo_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[hpNewsSet] ADD  CONSTRAINT [DF_hpNewsSet_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[info_Datereport] ADD  CONSTRAINT [DF_info_Datereport1_Companyregnum_Our]  DEFAULT ((0)) FOR [Companyregnum_Our]
GO
ALTER TABLE [dbo].[info_Datereport] ADD  CONSTRAINT [DF_info_Datereport1_personregnum_Our]  DEFAULT ((0)) FOR [Personregnum_Our]
GO
ALTER TABLE [dbo].[info_Datereport] ADD  CONSTRAINT [DF_info_Datereport1_ValidCompany]  DEFAULT ((0)) FOR [ValidCompany]
GO
ALTER TABLE [dbo].[info_Datereport] ADD  CONSTRAINT [DF_info_Datereport1_ValidResume]  DEFAULT ((0)) FOR [ValidResume]
GO
ALTER TABLE [dbo].[info_Datereport] ADD  CONSTRAINT [DF_info_Datereport1_homepage]  DEFAULT ((0)) FOR [Homepage]
GO
ALTER TABLE [dbo].[info_Datereport] ADD  CONSTRAINT [DF_info_Datereport_realCompany]  DEFAULT ((0)) FOR [RealCompany]
GO
ALTER TABLE [dbo].[info_Datereport] ADD  CONSTRAINT [DF_info_Datereport_realResume]  DEFAULT ((0)) FOR [RealResume]
GO
ALTER TABLE [dbo].[info_Datereport] ADD  CONSTRAINT [DF_info_Datereport_allResume]  DEFAULT ((0)) FOR [AllResume]
GO
ALTER TABLE [dbo].[info_Datereport] ADD  CONSTRAINT [DF_info_Datereport_personregnum_Our_qq]  DEFAULT ((0)) FOR [PersonRegNum_Our_QQ]
GO
ALTER TABLE [dbo].[info_Datereport] ADD  CONSTRAINT [DF_info_Datereport_MobileNum]  DEFAULT ((0)) FOR [MobileNum]
GO
ALTER TABLE [dbo].[info_Datereport] ADD  CONSTRAINT [DF_info_Datereport_MobileReturn]  DEFAULT ((0)) FOR [MobileReturn]
GO
ALTER TABLE [dbo].[info_Datereport] ADD  CONSTRAINT [DF_info_Datereport_MobileAccount]  DEFAULT ((0)) FOR [MobileAccount]
GO
ALTER TABLE [dbo].[info_Datereport] ADD  CONSTRAINT [DF_info_Datereport_cpMobileNum]  DEFAULT ((0)) FOR [cpMobileNum]
GO
ALTER TABLE [dbo].[info_Datereport] ADD  CONSTRAINT [DF_info_Datereport_cpMobileRetNum]  DEFAULT ((0)) FOR [cpMobileRetNum]
GO
ALTER TABLE [dbo].[info_Datereport] ADD  CONSTRAINT [DF_info_Datereport_cpMobileAccountNum]  DEFAULT ((0)) FOR [cpMobileAccountNum]
GO
ALTER TABLE [dbo].[info_Datereport] ADD  DEFAULT ((0)) FOR [PersonalActivationCount]
GO
ALTER TABLE [dbo].[info_Datereport] ADD  DEFAULT ((0)) FOR [CompanyActivationCount]
GO
ALTER TABLE [dbo].[infolog] ADD  CONSTRAINT [DF_infolog_addDate]  DEFAULT (getdate()) FOR [addDate]
GO
ALTER TABLE [dbo].[innerer] ADD  CONSTRAINT [DF_innerer_loginDate]  DEFAULT (getdate()) FOR [LoginDate]
GO
ALTER TABLE [dbo].[inResult] ADD  CONSTRAINT [DF_inResult_addDate]  DEFAULT (getdate()) FOR [addDate]
GO
ALTER TABLE [dbo].[Institution] ADD  CONSTRAINT [DF_Institution_addDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[Investigation] ADD  CONSTRAINT [DF_Investigation_adddate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[Ip_Black] ADD  CONSTRAINT [DF_ip_black_adddate]  DEFAULT (getdate()) FOR [adddate]
GO
ALTER TABLE [dbo].[Ip_Black] ADD  CONSTRAINT [DF_ip_black_type]  DEFAULT ((1)) FOR [type]
GO
ALTER TABLE [dbo].[Ip_White] ADD  CONSTRAINT [DF_ip_white_adddate]  DEFAULT (getdate()) FOR [adddate]
GO
ALTER TABLE [dbo].[Ip_White] ADD  CONSTRAINT [DF_ip_white_visitnum]  DEFAULT ((0)) FOR [visitnum]
GO
ALTER TABLE [dbo].[Ip_White] ADD  CONSTRAINT [DF_ip_white_visitnum_thismonth]  DEFAULT ((0)) FOR [visitnum_thismonth]
GO
ALTER TABLE [dbo].[Ip_White] ADD  CONSTRAINT [DF_ip_white_visitnum_lastmonth]  DEFAULT ((0)) FOR [visitnum_lastmonth]
GO
ALTER TABLE [dbo].[IpLog] ADD  CONSTRAINT [DF_iplog_adddate]  DEFAULT (getdate()) FOR [adddate]
GO
ALTER TABLE [dbo].[ivgt_answer] ADD  CONSTRAINT [DF_ivgt_answer_power]  DEFAULT ((1)) FOR [Power]
GO
ALTER TABLE [dbo].[ivgt_answer] ADD  CONSTRAINT [DF_ivgt_answer_clicknum]  DEFAULT ((0)) FOR [ClickNum]
GO
ALTER TABLE [dbo].[ivgt_answer] ADD  CONSTRAINT [DF_ivgt_answer_showType]  DEFAULT ((1)) FOR [showType]
GO
ALTER TABLE [dbo].[ivgt_investigation] ADD  CONSTRAINT [DF_ivgt_investigation_addDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[ivgt_investigation] ADD  CONSTRAINT [DF_ivgt_investigation_clicknum]  DEFAULT ((0)) FOR [ClickNum]
GO
ALTER TABLE [dbo].[ivgt_investigation] ADD  CONSTRAINT [DF_ivgt_investigation_ReportType]  DEFAULT ((1)) FOR [ReportType]
GO
ALTER TABLE [dbo].[ivgt_question] ADD  CONSTRAINT [DF_ivgt_question_power]  DEFAULT ((1)) FOR [Power]
GO
ALTER TABLE [dbo].[ivrDayReport] ADD  CONSTRAINT [DF_ivrDayReport_DeptId]  DEFAULT ((0)) FOR [DeptId]
GO
ALTER TABLE [dbo].[ivrDayReport] ADD  CONSTRAINT [DF_ivrDayReport_IsCheck]  DEFAULT ((1)) FOR [IsCheck]
GO
ALTER TABLE [dbo].[ivrDayReport] ADD  CONSTRAINT [DF_ivrDayReport_Status]  DEFAULT ((0)) FOR [Status]
GO
ALTER TABLE [dbo].[ivrDayReport] ADD  CONSTRAINT [DF_ivrDayReport_ManagerStatus]  DEFAULT ((0)) FOR [ManagerStatus]
GO
ALTER TABLE [dbo].[IvrList] ADD  CONSTRAINT [DF_IvrList_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[Ivrlist_Day] ADD  CONSTRAINT [DF_Ivrlist_Day_WorkTimeStatus]  DEFAULT ((0)) FOR [WorkTimeStatus]
GO
ALTER TABLE [dbo].[Job] ADD  CONSTRAINT [DF_Job_EMailSent]  DEFAULT ((0)) FOR [EMailSendFreq]
GO
ALTER TABLE [dbo].[Job] ADD  CONSTRAINT [DF_Job_DisplayNo]  DEFAULT ((1)) FOR [DisplayNo]
GO
ALTER TABLE [dbo].[Job] ADD  CONSTRAINT [DF_Job_IsDelete]  DEFAULT ((0)) FOR [IsDelete]
GO
ALTER TABLE [dbo].[Job] ADD  CONSTRAINT [DF_Job_ApplyNumber]  DEFAULT ((0)) FOR [ApplyNumber]
GO
ALTER TABLE [dbo].[Job] ADD  CONSTRAINT [DF_Job_ViewNumber]  DEFAULT ((0)) FOR [ViewNumber]
GO
ALTER TABLE [dbo].[Job] ADD  CONSTRAINT [DF_Job_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[Job] ADD  CONSTRAINT [DF_Job_LastModifyDate]  DEFAULT (getdate()) FOR [LastModifyDate]
GO
ALTER TABLE [dbo].[Job] ADD  CONSTRAINT [DF_Job_Valid]  DEFAULT ((0)) FOR [Valid]
GO
ALTER TABLE [dbo].[Job] ADD  DEFAULT ((0)) FOR [Negotiable]
GO
ALTER TABLE [dbo].[JobSimilarCompare] ADD  CONSTRAINT [DF_JobLimiteCompare_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[JobSubScription] ADD  CONSTRAINT [DF_JobSubScrIption_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[jobTags] ADD  CONSTRAINT [DF_jobTags_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[JobTemplate] ADD  CONSTRAINT [DF_JobTemplate_EMailSent]  DEFAULT ((0)) FOR [EMailSendFreq]
GO
ALTER TABLE [dbo].[JobTemplate] ADD  CONSTRAINT [DF_JobTemplate_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[JobTemplate] ADD  CONSTRAINT [DF_JobTemplate_LastModifyDate]  DEFAULT (getdate()) FOR [LastModifyDate]
GO
ALTER TABLE [dbo].[JobTemplate] ADD  DEFAULT ((0)) FOR [Negotiable]
GO
ALTER TABLE [dbo].[knowledge] ADD  CONSTRAINT [DF_knowledge_addDate]  DEFAULT (getdate()) FOR [addDate]
GO
ALTER TABLE [dbo].[KPI_EC] ADD  CONSTRAINT [DF_KPI_EC_addDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[KPI_IE] ADD  CONSTRAINT [DF_KPI_IE_addDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[KPI_IE] ADD  CONSTRAINT [DF_KPI_IE_status]  DEFAULT ((0)) FOR [status]
GO
ALTER TABLE [dbo].[KPI_IE] ADD  CONSTRAINT [DF_KPI_IE_createDate]  DEFAULT (getdate()) FOR [createDate]
GO
ALTER TABLE [dbo].[KPI_IE] ADD  CONSTRAINT [DF__KPI_IE__IsAccept__06295439]  DEFAULT ((0)) FOR [IsAccept]
GO
ALTER TABLE [dbo].[KPI_IE] ADD  CONSTRAINT [DF__KPI_IE__CheckSco__05353000]  DEFAULT ((0)) FOR [CheckScore]
GO
ALTER TABLE [dbo].[KPI_KM] ADD  CONSTRAINT [DF_Table_1_adDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[KPI_KM] ADD  CONSTRAINT [DF_KPI_KM_status]  DEFAULT ((0)) FOR [Status]
GO
ALTER TABLE [dbo].[KPI_LP] ADD  CONSTRAINT [DF_KPI_LP_addDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[KPI_LP] ADD  CONSTRAINT [DF_KPI_LP_status]  DEFAULT ((0)) FOR [Status]
GO
ALTER TABLE [dbo].[KPI_OC] ADD  CONSTRAINT [DF_KPI_OC_status]  DEFAULT ((0)) FOR [Status]
GO
ALTER TABLE [dbo].[KPI_OC] ADD  CONSTRAINT [DF_KPI_OC_Last_Date]  DEFAULT (getdate()) FOR [Last_Date]
GO
ALTER TABLE [dbo].[KPI_SA] ADD  CONSTRAINT [DF_KPI_SA_status]  DEFAULT ((0)) FOR [Status]
GO
ALTER TABLE [dbo].[Link] ADD  CONSTRAINT [DF_Link_AnnounceDate]  DEFAULT (getdate()) FOR [AnnounceDate]
GO
ALTER TABLE [dbo].[Link] ADD  CONSTRAINT [DF_Link_power]  DEFAULT ((0)) FOR [Power]
GO
ALTER TABLE [dbo].[Link] ADD  CONSTRAINT [DF_Link_powerall]  DEFAULT ((0)) FOR [PowerAll]
GO
ALTER TABLE [dbo].[Link] ADD  CONSTRAINT [DF_Link_vision]  DEFAULT ((0)) FOR [Vision]
GO
ALTER TABLE [dbo].[Link] ADD  CONSTRAINT [DF_Link_our]  DEFAULT ((0)) FOR [Our]
GO
ALTER TABLE [dbo].[Link] ADD  CONSTRAINT [DF_Link_score]  DEFAULT ((0)) FOR [Score]
GO
ALTER TABLE [dbo].[Link] ADD  CONSTRAINT [DF_Link_orderby]  DEFAULT ((0)) FOR [Orderby]
GO
ALTER TABLE [dbo].[Link] ADD  CONSTRAINT [DF_Link_deleted]  DEFAULT ((0)) FOR [Deleted]
GO
ALTER TABLE [dbo].[Link] ADD  CONSTRAINT [DF_Link_baIdu]  DEFAULT ((1)) FOR [Baidu]
GO
ALTER TABLE [dbo].[Link] ADD  CONSTRAINT [DF_Link_baIduDate]  DEFAULT (getdate()) FOR [BaiduDate]
GO
ALTER TABLE [dbo].[Link] ADD  CONSTRAINT [DF_Link_linkour]  DEFAULT ((1)) FOR [LinkOur]
GO
ALTER TABLE [dbo].[Link] ADD  CONSTRAINT [DF_Link_errornum]  DEFAULT ((0)) FOR [ErrorNum]
GO
ALTER TABLE [dbo].[Link] ADD  CONSTRAINT [DF_Link_method]  DEFAULT ((1)) FOR [Method]
GO
ALTER TABLE [dbo].[link_count] ADD  CONSTRAINT [DF_link_count_power]  DEFAULT ((0)) FOR [Power]
GO
ALTER TABLE [dbo].[link_score] ADD  CONSTRAINT [DF_link_score_countDate]  DEFAULT (getdate()) FOR [CountDate]
GO
ALTER TABLE [dbo].[link_score] ADD  CONSTRAINT [DF_link_score_num]  DEFAULT ((0)) FOR [Num]
GO
ALTER TABLE [dbo].[linkclick] ADD  CONSTRAINT [DF_linkclick_loginDate]  DEFAULT (getdate()) FOR [LoginDate]
GO
ALTER TABLE [dbo].[LogSize] ADD  CONSTRAINT [DF_LogSize_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[ManagerLog] ADD  CONSTRAINT [DF_ManagerLog_LoginDate]  DEFAULT (getdate()) FOR [LoginDate]
GO
ALTER TABLE [dbo].[ManagerUser] ADD  CONSTRAINT [DF_manageruser_OpenName]  DEFAULT ((0)) FOR [OpenName]
GO
ALTER TABLE [dbo].[ManagerUser] ADD  CONSTRAINT [DF_user_adddate]  DEFAULT (getdate()) FOR [adddate]
GO
ALTER TABLE [dbo].[ManagerUser] ADD  CONSTRAINT [DF_user_logincount]  DEFAULT ((0)) FOR [logincount]
GO
ALTER TABLE [dbo].[ManagerUser] ADD  CONSTRAINT [DF_manageruser_status]  DEFAULT ((1)) FOR [status]
GO
ALTER TABLE [dbo].[ManagerUser] ADD  CONSTRAINT [DF_manageruser_loginstatus]  DEFAULT ((1)) FOR [loginstatus]
GO
ALTER TABLE [dbo].[ManagerUser] ADD  CONSTRAINT [DF_manageruser_RtxStatus]  DEFAULT ((0)) FOR [rtxstatus]
GO
ALTER TABLE [dbo].[ManagerUser] ADD  CONSTRAINT [DF_manageruser_consultantnum_up]  DEFAULT ((0)) FOR [consultantnum_up]
GO
ALTER TABLE [dbo].[ManagerUser] ADD  CONSTRAINT [DF_manageruser_consultantnum]  DEFAULT ((0)) FOR [consultantnum]
GO
ALTER TABLE [dbo].[ManagerUser] ADD  CONSTRAINT [DF_manageruser_consultantnum_noyingye]  DEFAULT ((0)) FOR [consultantnum_noyingye]
GO
ALTER TABLE [dbo].[ManagerUser] ADD  CONSTRAINT [DF_ManagerUser_RtxTime]  DEFAULT (getdate()) FOR [rtxTime]
GO
ALTER TABLE [dbo].[ManagerUser] ADD  DEFAULT ((0)) FOR [SOLStatus]
GO
ALTER TABLE [dbo].[ManagerUser] ADD  DEFAULT (getdate()) FOR [SOLTime]
GO
ALTER TABLE [dbo].[ManagerUserChange] ADD  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[ManagerUserCompanyLog] ADD  CONSTRAINT [DF_ManagerUserCompanyLog_addDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[mblFeedBack] ADD  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[mblVersion] ADD  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[MobileCerIPVisitLog] ADD  DEFAULT ((1)) FOR [ClientType]
GO
ALTER TABLE [dbo].[msEmailPrevSend] ADD  CONSTRAINT [DF_msEmailPrevSend_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[msEmailPrevSend] ADD  DEFAULT ((0)) FOR [ErrorNumber]
GO
ALTER TABLE [dbo].[msEmailSend] ADD  CONSTRAINT [DF_msEmailSend_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[msEmailTemplete] ADD  CONSTRAINT [DF_msBodyTemplete_EmailType]  DEFAULT ((1)) FOR [msSqlID]
GO
ALTER TABLE [dbo].[msEmailTemplete] ADD  CONSTRAINT [DF_msBodyTemplete_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[msEmailTempleteEdit] ADD  CONSTRAINT [DF_msEmailTemplete_EmailType]  DEFAULT ((1)) FOR [msSqlID]
GO
ALTER TABLE [dbo].[msEmailTempleteEdit] ADD  CONSTRAINT [DF_msEmailTemplete_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[msEmailTempleteLog] ADD  CONSTRAINT [DF_msEmailTempleteLo_EmailType]  DEFAULT ((1)) FOR [msSqlID]
GO
ALTER TABLE [dbo].[msEmailTempleteLog] ADD  CONSTRAINT [DF_msEmailTempleteLo_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[msEmailTitle] ADD  CONSTRAINT [DF_msEmailTitle_adddate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[msEmailType] ADD  CONSTRAINT [DF_msEmailType_Sender]  DEFAULT ('Serve@') FOR [Sender]
GO
ALTER TABLE [dbo].[msEmailType] ADD  CONSTRAINT [DF_msEmailType_Host]  DEFAULT ('mail') FOR [Host]
GO
ALTER TABLE [dbo].[msEmailType] ADD  CONSTRAINT [DF_msEmailType_IsPause]  DEFAULT ((0)) FOR [IsPause]
GO
ALTER TABLE [dbo].[msEmailType] ADD  CONSTRAINT [DF_msEmailType_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[msEmailTypeEdit] ADD  CONSTRAINT [DF_msEmailTypeEdit_Sender]  DEFAULT ('Serve@') FOR [Sender]
GO
ALTER TABLE [dbo].[msEmailTypeEdit] ADD  CONSTRAINT [DF_msEmailTypeEdit_Host]  DEFAULT ('mail') FOR [Host]
GO
ALTER TABLE [dbo].[msEmailTypeEdit] ADD  CONSTRAINT [DF_msEmailTypeEdit_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[msProcess] ADD  CONSTRAINT [DF_msProcess_Sender]  DEFAULT ('Serve@') FOR [Sender]
GO
ALTER TABLE [dbo].[msProcess] ADD  CONSTRAINT [DF_msProcess_Host]  DEFAULT ('mail') FOR [Host]
GO
ALTER TABLE [dbo].[msProcess] ADD  CONSTRAINT [DF_msProcess_NextRunTime]  DEFAULT (getdate()) FOR [NextRunTime]
GO
ALTER TABLE [dbo].[msProcess] ADD  CONSTRAINT [DF_msProcess_RunStatus]  DEFAULT ((0)) FOR [RunStatus]
GO
ALTER TABLE [dbo].[msProcess] ADD  CONSTRAINT [DF_msProcess_SendNumber]  DEFAULT ((0)) FOR [SendNumber]
GO
ALTER TABLE [dbo].[msProcess] ADD  CONSTRAINT [DF_msProcess_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[msProcessEdit] ADD  CONSTRAINT [DF_msProcessEdit_Sender]  DEFAULT ('Serve@') FOR [Sender]
GO
ALTER TABLE [dbo].[msProcessEdit] ADD  CONSTRAINT [DF_msProcessEdit_Host]  DEFAULT ('mail') FOR [Host]
GO
ALTER TABLE [dbo].[msProcessEdit] ADD  CONSTRAINT [DF_msProcessEdit_NextRunTime]  DEFAULT (getdate()) FOR [NextRunTime]
GO
ALTER TABLE [dbo].[msProcessEdit] ADD  CONSTRAINT [DF_msProcessEdit_RunStatus]  DEFAULT ((0)) FOR [RunStatus]
GO
ALTER TABLE [dbo].[msProcessEdit] ADD  CONSTRAINT [DF_msProcessEdit_SendNumber]  DEFAULT ((0)) FOR [SendNumber]
GO
ALTER TABLE [dbo].[msProcessEdit] ADD  CONSTRAINT [DF_msProcessEdit_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[msProcessLog] ADD  CONSTRAINT [DF_msProcessLog_SenNumber]  DEFAULT ((0)) FOR [SendNumber]
GO
ALTER TABLE [dbo].[msProcessLog] ADD  CONSTRAINT [DF_msProcessLog_SuccessNumber]  DEFAULT ((0)) FOR [SuccessNumber]
GO
ALTER TABLE [dbo].[msProcessLog] ADD  CONSTRAINT [DF_msProcessLog_FailNumber]  DEFAULT ((0)) FOR [FailNumber]
GO
ALTER TABLE [dbo].[msSchedule] ADD  CONSTRAINT [DF_mcSchedule_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[MT] ADD  DEFAULT ((1)) FOR [Valid]
GO
ALTER TABLE [dbo].[MT_plan] ADD  CONSTRAINT [DF_MT_plan_addDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[nhSms] ADD  CONSTRAINT [DF_nhSms_IsShowBj]  DEFAULT ((0)) FOR [IsShowBj]
GO
ALTER TABLE [dbo].[nhSms] ADD  CONSTRAINT [DF_nhSms_IsShowSh]  DEFAULT ((0)) FOR [IsShowSh]
GO
ALTER TABLE [dbo].[nhSms] ADD  CONSTRAINT [DF__nhSms__IsShow__393D4D3D]  DEFAULT ((0)) FOR [IsShowSd]
GO
ALTER TABLE [dbo].[nhSms] ADD  CONSTRAINT [DF__nhSms__AddDate__3A317176]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[NoRecommend] ADD  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[NVDocument] ADD  CONSTRAINT [DF_NVDocument_addDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[oa_flow] ADD  CONSTRAINT [DF_oa_flows_arrivaltime]  DEFAULT (getdate()) FOR [arrivaltime]
GO
ALTER TABLE [dbo].[oa_flow] ADD  CONSTRAINT [DF_oa_flow_Agree]  DEFAULT ((0)) FOR [Agree]
GO
ALTER TABLE [dbo].[oa_flow] ADD  CONSTRAINT [DF_oa_flow_opinion]  DEFAULT ('') FOR [opinion]
GO
ALTER TABLE [dbo].[onlinepayResult] ADD  CONSTRAINT [DF_onlinepayResult_addDate]  DEFAULT (getdate()) FOR [addDate]
GO
ALTER TABLE [dbo].[OutLink] ADD  CONSTRAINT [DF_OutLink_addDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[OutLink] ADD  CONSTRAINT [DF_OutLink_yst_clicknum]  DEFAULT ((0)) FOR [Yst_ClickNum]
GO
ALTER TABLE [dbo].[OutLink] ADD  CONSTRAINT [DF_OutLink_mth_clicknum]  DEFAULT ((0)) FOR [Mth_ClickNum]
GO
ALTER TABLE [dbo].[OutLink] ADD  CONSTRAINT [DF_OutLink_status]  DEFAULT ((0)) FOR [Status]
GO
ALTER TABLE [dbo].[OutLink] ADD  CONSTRAINT [DF_OutLink_errornum]  DEFAULT ((0)) FOR [Errornum]
GO
ALTER TABLE [dbo].[OutLink] ADD  CONSTRAINT [DF_OutLink_copy]  DEFAULT ((1)) FOR [Copy]
GO
ALTER TABLE [dbo].[outlink_count] ADD  CONSTRAINT [DF_outlink_count_power]  DEFAULT ((0)) FOR [power]
GO
ALTER TABLE [dbo].[OutlinkResources] ADD  CONSTRAINT [DF_OutlinkResources_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[OutlinkResources] ADD  CONSTRAINT [DF_OutlinkResources_Status]  DEFAULT ((1)) FOR [Status]
GO
ALTER TABLE [dbo].[PaAttention] ADD  CONSTRAINT [DF_PaAttention_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[paContact] ADD  DEFAULT (getdate()) FOR [ContactDate]
GO
ALTER TABLE [dbo].[paCoverLetter] ADD  CONSTRAINT [DF_paCoverLetter_IsDefault]  DEFAULT ((0)) FOR [IsDefault]
GO
ALTER TABLE [dbo].[paCoverLetter] ADD  CONSTRAINT [DF_paCoverLetter_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[paCvAlipayRelation] ADD  CONSTRAINT [DF_paCvAlipayRelation_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[paFavorate] ADD  CONSTRAINT [DF_paFavorite_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[paFeedback] ADD  CONSTRAINT [DF_paFeedback_adddate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[paFeedback] ADD  CONSTRAINT [DF_paFeedback_reply]  DEFAULT ((0)) FOR [IsReply]
GO
ALTER TABLE [dbo].[paGetPasswordLog] ADD  CONSTRAINT [DF_paGetPasswordLog_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[paInfoEmailVerifyLog] ADD  CONSTRAINT [DF_paInfoEmailVerifyLog_CountDate]  DEFAULT (CONVERT([varchar](8),getdate(),(112))) FOR [CountDate]
GO
ALTER TABLE [dbo].[PaIosBind] ADD  CONSTRAINT [DF_PaIosBind_Adddate]  DEFAULT (getdate()) FOR [Adddate]
GO
ALTER TABLE [dbo].[paJobClickCount] ADD  CONSTRAINT [DF__paJobClic__IsSpi__6121ECBC]  DEFAULT ((0)) FOR [IsSpider]
GO
ALTER TABLE [dbo].[paJobClickCount] ADD  CONSTRAINT [DF__paJobClic__CanVi__621610F5]  DEFAULT ((0)) FOR [CanView]
GO
ALTER TABLE [dbo].[paJobClickCount] ADD  CONSTRAINT [DF__paJobClic__AddDa__630A352E]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[paJobCompare] ADD  CONSTRAINT [DF_PaJobCompare_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[paJobCompareIndex] ADD  CONSTRAINT [DF_paJobCompareIndex_RunStatus]  DEFAULT ((0)) FOR [RunStatus]
GO
ALTER TABLE [dbo].[paJobCompareIndex] ADD  CONSTRAINT [DF__paJobComp__ADDdA__7BC0D45F]  DEFAULT (getdate()) FOR [ADDdATE]
GO
ALTER TABLE [dbo].[paJobFinder] ADD  CONSTRAINT [DF_paJobFinder_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[paJobFinder] ADD  CONSTRAINT [DF_paJobFinder_emailsent]  DEFAULT ((0)) FOR [EmailSent]
GO
ALTER TABLE [dbo].[paJobPlanFeedBack] ADD  CONSTRAINT [DF_paJobPlanFeedback_addDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[paJobViewLog] ADD  CONSTRAINT [DF_paJobViewLog_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[paLoginLog] ADD  CONSTRAINT [DF_personal_loginlog_logindate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[paMain] ADD  CONSTRAINT [DF_paMain_IsDefaultPassword]  DEFAULT ((0)) FOR [IsDefaultPassword]
GO
ALTER TABLE [dbo].[paMain] ADD  CONSTRAINT [DF_paMain_RegisterMode]  DEFAULT ((0)) FOR [RegisterMode]
GO
ALTER TABLE [dbo].[paMain] ADD  CONSTRAINT [DF_paMain_NotPassedNumber]  DEFAULT ((0)) FOR [BlockCount]
GO
ALTER TABLE [dbo].[paMain] ADD  CONSTRAINT [DF_paMain_VerifyCount]  DEFAULT ((0)) FOR [VerifyCount]
GO
ALTER TABLE [dbo].[paMain] ADD  CONSTRAINT [DF_paMain_LastLoginDate]  DEFAULT (getdate()) FOR [LastLoginDate]
GO
ALTER TABLE [dbo].[paMain] ADD  CONSTRAINT [DF_paMain_TotalLoginNum]  DEFAULT ((0)) FOR [TotalLoginNum]
GO
ALTER TABLE [dbo].[paMain] ADD  CONSTRAINT [DF_paMain_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[paMain] ADD  CONSTRAINT [DF_paMain_IsReceiveSms]  DEFAULT ((1)) FOR [IsReceiveSms]
GO
ALTER TABLE [dbo].[PaMainDateReport] ADD  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[paMainPublish] ADD  CONSTRAINT [DF_paMainPublish_LastLoginDate]  DEFAULT (getdate()) FOR [LastLoginDate]
GO
ALTER TABLE [dbo].[paMainTemp] ADD  CONSTRAINT [DF_paMainTemp_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[paMobileFollowUp] ADD  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[paNotify] ADD  CONSTRAINT [DF_paNotify_IsViewed]  DEFAULT ((0)) FOR [IsViewed]
GO
ALTER TABLE [dbo].[paNotify] ADD  CONSTRAINT [DF_paNotify_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[paOperationLog] ADD  CONSTRAINT [DF_paOperationLog_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[paPageViewLog] ADD  CONSTRAINT [DF_paPageViewLog_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[paPageViewLog] ADD  CONSTRAINT [DF_paPageViewLog_MyAttentionCount]  DEFAULT ((0)) FOR [MyAttentionCount]
GO
ALTER TABLE [dbo].[paPageViewLog] ADD  CONSTRAINT [DF_paPageViewLog_CvViewLogCount]  DEFAULT ((0)) FOR [CvViewLogCount]
GO
ALTER TABLE [dbo].[paPageViewLog] ADD  CONSTRAINT [DF_paPageViewLog_YourFoodCount]  DEFAULT ((0)) FOR [YourFoodCount]
GO
ALTER TABLE [dbo].[paPageViewLog] ADD  CONSTRAINT [DF_paPageViewLog_JobAppliedCount]  DEFAULT ((0)) FOR [JobAppliedCount]
GO
ALTER TABLE [dbo].[paPageViewLog] ADD  CONSTRAINT [DF_paPageViewLog_InterviewCount]  DEFAULT ((0)) FOR [InterviewCount]
GO
ALTER TABLE [dbo].[paPageViewLog] ADD  CONSTRAINT [DF_paPageViewLog_CpInvitationCount]  DEFAULT ((0)) FOR [CpInvitationCount]
GO
ALTER TABLE [dbo].[paPageViewLog] ADD  CONSTRAINT [DF_paPageViewLog_ChatCount]  DEFAULT ((0)) FOR [ChatCount]
GO
ALTER TABLE [dbo].[paPhoto] ADD  CONSTRAINT [DF_paPhoto_adddate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[paPhoto_before] ADD  CONSTRAINT [DF_paPhoto_befor_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[paPlaint] ADD  CONSTRAINT [DF_plaint_adddate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[paPlaint] ADD  CONSTRAINT [DF_plaint_status]  DEFAULT ((0)) FOR [ReplyType]
GO
ALTER TABLE [dbo].[paPlaint] ADD  CONSTRAINT [DF_plaint_Viewed]  DEFAULT ((0)) FOR [IsViewed]
GO
ALTER TABLE [dbo].[paPushLog] ADD  CONSTRAINT [DF_paPushLog_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[paReferer] ADD  CONSTRAINT [DF__paReferer__AddDa__4C46CB67]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[PaRemindLog] ADD  CONSTRAINT [DF_PaRemindLog_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[paSearchKeyword] ADD  CONSTRAINT [DF_paSearchKeyword_HasSubmit]  DEFAULT ((0)) FOR [HasSubmit]
GO
ALTER TABLE [dbo].[paTagsMain] ADD  CONSTRAINT [DF_paTagsMain_UseCount]  DEFAULT ((0)) FOR [UseCount]
GO
ALTER TABLE [dbo].[paYourFoodIndex] ADD  DEFAULT ((0)) FOR [HasRun]
GO
ALTER TABLE [dbo].[paYourFoodWeiXin] ADD  DEFAULT ((0)) FOR [HasSend]
GO
ALTER TABLE [dbo].[paYourFoodWeiXin] ADD  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[Person_Black] ADD  CONSTRAINT [DF_Person_Black_AddedDate]  DEFAULT (getdate()) FOR [AddedDate]
GO
ALTER TABLE [dbo].[Person_Black] ADD  CONSTRAINT [DF_Person_Black_RefuseCount]  DEFAULT ((0)) FOR [RefuseCount]
GO
ALTER TABLE [dbo].[picture] ADD  CONSTRAINT [DF_picture_addDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[Pr_Alex] ADD  CONSTRAINT [DF_pr_alex_YearMonthDay]  DEFAULT ((datepart(year,getdate())*(10000)+datepart(month,getdate())*(100))+datepart(day,getdate())) FOR [YearMonthDay]
GO
ALTER TABLE [dbo].[Pr_Alex] ADD  CONSTRAINT [DF_pr_alex_pr]  DEFAULT ((0)) FOR [Pr]
GO
ALTER TABLE [dbo].[Pr_Alex] ADD  CONSTRAINT [DF_pr_alex_alex]  DEFAULT ((0)) FOR [Alex]
GO
ALTER TABLE [dbo].[Pr_Alex] ADD  CONSTRAINT [DF_pr_alex_baIdu]  DEFAULT ((0)) FOR [Baidu]
GO
ALTER TABLE [dbo].[Pr_Alex] ADD  CONSTRAINT [DF_pr_alex_google]  DEFAULT ((0)) FOR [Google]
GO
ALTER TABLE [dbo].[Pr_Alex] ADD  CONSTRAINT [DF_pr_alex_sogou]  DEFAULT ((0)) FOR [Sogou]
GO
ALTER TABLE [dbo].[Pr_Alex] ADD  CONSTRAINT [DF_pr_alex_addDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[QlrcNews] ADD  CONSTRAINT [DF_QlrcNews_AnnounceDate]  DEFAULT (getdate()) FOR [AnnounceDate]
GO
ALTER TABLE [dbo].[QlrcNews] ADD  CONSTRAINT [DF_QlrcNews_ViewNumber]  DEFAULT ((0)) FOR [ViewNumber]
GO
ALTER TABLE [dbo].[QlrcNews] ADD  CONSTRAINT [DF_QlrcNews_Type]  DEFAULT ((1)) FOR [Type]
GO
ALTER TABLE [dbo].[QlrcNews] ADD  CONSTRAINT [DF_QlrcNews_refReshDate]  DEFAULT (getdate()) FOR [RefReshDate]
GO
ALTER TABLE [dbo].[QlrcNews] ADD  CONSTRAINT [DF_QlrcNews_ViewNumber_All]  DEFAULT ((0)) FOR [ViewNumber_All]
GO
ALTER TABLE [dbo].[Question] ADD  CONSTRAINT [DF_Question_Power]  DEFAULT ((1)) FOR [Power]
GO
ALTER TABLE [dbo].[RecruitmentCpMain] ADD  CONSTRAINT [DF_RecruitmentCpMain_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[RecruitmentImage] ADD  CONSTRAINT [DF_RecruitmentImage_OrderNo]  DEFAULT ((1)) FOR [OrderNo]
GO
ALTER TABLE [dbo].[RecruitmentImage] ADD  CONSTRAINT [DF_RecruitmentImage_addDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[RecruitmentPaMain] ADD  CONSTRAINT [DF_RecruitmentPaMain_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[referer] ADD  CONSTRAINT [DF_referer_loginDate]  DEFAULT (getdate()) FOR [LoginDate]
GO
ALTER TABLE [dbo].[RefuseIp] ADD  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[RefuseIp] ADD  DEFAULT ((0)) FOR [IsForever]
GO
ALTER TABLE [dbo].[Resume_analysis] ADD  CONSTRAINT [DF_Resume_analysis_addDate]  DEFAULT (getdate()) FOR [addDate]
GO
ALTER TABLE [dbo].[Resume_Xinxi] ADD  CONSTRAINT [DF_Resume_Xinxi_RegDate]  DEFAULT (getdate()) FOR [RegDate]
GO
ALTER TABLE [dbo].[Resume_Xinxi] ADD  CONSTRAINT [DF_Resume_Xinxi_IsHistory]  DEFAULT ((0)) FOR [IsHistory]
GO
ALTER TABLE [dbo].[Resumeinform] ADD  CONSTRAINT [DF_Resumeinform_addDate]  DEFAULT (getdate()) FOR [addDate]
GO
ALTER TABLE [dbo].[Resumeinform] ADD  CONSTRAINT [DF_Resumeinform_status]  DEFAULT ((1)) FOR [status]
GO
ALTER TABLE [dbo].[ResumeSubScription] ADD  CONSTRAINT [DF_ResumesubscrIption_addDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[rtx_event] ADD  CONSTRAINT [DF_rtx_event_errortime]  DEFAULT (getdate()) FOR [ErrorTime]
GO
ALTER TABLE [dbo].[Sales_Factor] ADD  CONSTRAINT [DF_Sales_Factor_Factor_1]  DEFAULT ((0)) FOR [Factor_1]
GO
ALTER TABLE [dbo].[Sales_Factor] ADD  CONSTRAINT [DF_Sales_Factor_Factor_2]  DEFAULT ((0)) FOR [Factor_2]
GO
ALTER TABLE [dbo].[Sales_Factor] ADD  CONSTRAINT [DF_Sales_Factor_Factor_3]  DEFAULT ((0)) FOR [Factor_3]
GO
ALTER TABLE [dbo].[Sales_Factor] ADD  CONSTRAINT [DF_Sales_Factor_Factor_4]  DEFAULT ((0)) FOR [Factor_4]
GO
ALTER TABLE [dbo].[Sales_Factor] ADD  CONSTRAINT [DF_Sales_Factor_Factor_5]  DEFAULT ((0)) FOR [Factor_5]
GO
ALTER TABLE [dbo].[schMailPrev] ADD  CONSTRAINT [DF_schMailPrev_HasSend]  DEFAULT ((0)) FOR [HasSend]
GO
ALTER TABLE [dbo].[schMailPrev] ADD  CONSTRAINT [DF_schMailPrev_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[SearchIp] ADD  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[SearchKeywordsPower] ADD  CONSTRAINT [DF_SearchKeywordsPower_addDate]  DEFAULT (getdate()) FOR [addDate]
GO
ALTER TABLE [dbo].[SeatStatusCount] ADD  CONSTRAINT [DF_SeatStatusCount_CountDate]  DEFAULT (CONVERT([varchar](8),getdate(),(112))) FOR [CountDate]
GO
ALTER TABLE [dbo].[SeatStatusCount] ADD  CONSTRAINT [DF_SeatStatusCount_PRestatus]  DEFAULT ((0)) FOR [PRestatus]
GO
ALTER TABLE [dbo].[SeatStatusCount] ADD  CONSTRAINT [DF_SeatStatusCount_PreTime]  DEFAULT (getdate()) FOR [PreTime]
GO
ALTER TABLE [dbo].[SeatStatusCount] ADD  CONSTRAINT [DF_SeatStatusCount_LoginSeCond]  DEFAULT ((0)) FOR [LoginSeCond]
GO
ALTER TABLE [dbo].[SeatStatusCount] ADD  CONSTRAINT [DF_SeatStatusCount_LogoutSeCond]  DEFAULT ((0)) FOR [LogoutSeCond]
GO
ALTER TABLE [dbo].[SeatStatusCount] ADD  CONSTRAINT [DF_SeatStatusCount_BusySeCond]  DEFAULT ((0)) FOR [BusySeCond]
GO
ALTER TABLE [dbo].[SeatStatusCount] ADD  CONSTRAINT [DF_SeatStatusCount_IdleSeCond]  DEFAULT ((0)) FOR [IdleSeCond]
GO
ALTER TABLE [dbo].[Seconderer] ADD  CONSTRAINT [DF_seCondere_loginDate]  DEFAULT (getdate()) FOR [LoginDate]
GO
ALTER TABLE [dbo].[SendResume_recruit] ADD  CONSTRAINT [DF_sendResume_recruit_addDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[Servi_Account] ADD  CONSTRAINT [DF_servi_account_CompanyId]  DEFAULT ((0)) FOR [CompanyId]
GO
ALTER TABLE [dbo].[servi_log] ADD  CONSTRAINT [DF_servi_log_crDate]  DEFAULT (getdate()) FOR [CrDate]
GO
ALTER TABLE [dbo].[servi_process] ADD  CONSTRAINT [DF_servi_summary_startDate]  DEFAULT (getdate()) FOR [StartDate]
GO
ALTER TABLE [dbo].[servi_process] ADD  CONSTRAINT [DF_servi_process_refReshDate]  DEFAULT (getdate()) FOR [RefReshDate]
GO
ALTER TABLE [dbo].[servi_process] ADD  CONSTRAINT [DF_servi_process_lastrow]  DEFAULT ((0)) FOR [Lastrow]
GO
ALTER TABLE [dbo].[servi_process] ADD  CONSTRAINT [DF_servi_summary_Satisfaction]  DEFAULT ((0)) FOR [Satisfaction]
GO
ALTER TABLE [dbo].[servi_process] ADD  CONSTRAINT [DF_servi_process_Idlecount]  DEFAULT ((0)) FOR [Idlecount]
GO
ALTER TABLE [dbo].[servi_process] ADD  DEFAULT ((0)) FOR [IsActive]
GO
ALTER TABLE [dbo].[Servi_User] ADD  CONSTRAINT [DF_Servi_User_DisplayNo]  DEFAULT ((0)) FOR [DisplayNo]
GO
ALTER TABLE [dbo].[Servi_User] ADD  CONSTRAINT [DF_Servi_User_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[ServiceRunLog] ADD  CONSTRAINT [DF_ServiceRunLog_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[smsBatchSend] ADD  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[SmsMessageLog] ADD  CONSTRAINT [DF_SmsCat_IsCat]  DEFAULT ((0)) FOR [IsCat]
GO
ALTER TABLE [dbo].[SmsMessageLog] ADD  CONSTRAINT [DF_SmsCat_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[SmsMessageLog] ADD  CONSTRAINT [DF_SmsCat_SmsType]  DEFAULT ((1)) FOR [SmsType]
GO
ALTER TABLE [dbo].[SmsMessageLog] ADD  CONSTRAINT [DF_SmsCat_MsgType]  DEFAULT ((1)) FOR [MsgType]
GO
ALTER TABLE [dbo].[SmsWatchLog] ADD  CONSTRAINT [DF_SmsWatchLog_WatchDate]  DEFAULT (getdate()) FOR [WatchDate]
GO
ALTER TABLE [dbo].[SOLLog] ADD  CONSTRAINT [DF_SOLLog_IsViewed]  DEFAULT ((1)) FOR [IsViewed]
GO
ALTER TABLE [dbo].[SOLLog] ADD  CONSTRAINT [DF_SOLLog_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[SOLProcess] ADD  CONSTRAINT [DF_SOLProcess_StartDate]  DEFAULT (getdate()) FOR [StartDate]
GO
ALTER TABLE [dbo].[SOLProcess] ADD  CONSTRAINT [DF_SOLProcess_IsActive]  DEFAULT ((1)) FOR [IsActive]
GO
ALTER TABLE [dbo].[SOLProcess] ADD  CONSTRAINT [DF_SOLProcess_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[SOLService] ADD  CONSTRAINT [DF_SOLService_DisplayNo]  DEFAULT ((0)) FOR [DisplayNo]
GO
ALTER TABLE [dbo].[SOLService] ADD  CONSTRAINT [DF_SOLService_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[Sow] ADD  CONSTRAINT [DF_Sow_addDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[Standard] ADD  CONSTRAINT [DF_Standard_addDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[TableSpaceInfo] ADD  CONSTRAINT [DF_TableSpaceInfo_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[tmp1] ADD  CONSTRAINT [DF_tmp1_HasSubmit]  DEFAULT ((0)) FOR [HasSubmit]
GO
ALTER TABLE [dbo].[tmpPaBaiduJson] ADD  CONSTRAINT [DF_tmpPaBaiduJson_Adddate]  DEFAULT (getdate()) FOR [Adddate]
GO
ALTER TABLE [dbo].[tmpWsLog] ADD  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[ToolRunLog] ADD  CONSTRAINT [DF_ToolRunLog_RunServer]  DEFAULT ((1)) FOR [RunServer]
GO
ALTER TABLE [dbo].[ToolRunLog] ADD  CONSTRAINT [DF_ToolRunLog_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[Topics] ADD  CONSTRAINT [DF_Topics_type]  DEFAULT ((1)) FOR [type]
GO
ALTER TABLE [dbo].[Topics] ADD  CONSTRAINT [DF_Topics_EmailClick]  DEFAULT ((0)) FOR [EmailClick]
GO
ALTER TABLE [dbo].[Topics] ADD  CONSTRAINT [DF_Topics_ClickNumber]  DEFAULT ((0)) FOR [ClickNumber]
GO
ALTER TABLE [dbo].[Topics] ADD  CONSTRAINT [DF_Topics_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[Url] ADD  CONSTRAINT [DF_url_allclick]  DEFAULT ((0)) FOR [allclick]
GO
ALTER TABLE [dbo].[Url] ADD  CONSTRAINT [DF_url_toDayclick]  DEFAULT ((0)) FOR [toDayclick]
GO
ALTER TABLE [dbo].[Url] ADD  CONSTRAINT [DF_url_beginDate]  DEFAULT (getdate()) FOR [beginDate]
GO
ALTER TABLE [dbo].[Url] ADD  CONSTRAINT [DF_url_allResume]  DEFAULT ((0)) FOR [allResume]
GO
ALTER TABLE [dbo].[Url] ADD  CONSTRAINT [DF_url_toDayResume]  DEFAULT ((0)) FOR [toDayResume]
GO
ALTER TABLE [dbo].[Url] ADD  CONSTRAINT [DF_url_allCompany]  DEFAULT ((0)) FOR [allCompany]
GO
ALTER TABLE [dbo].[Url] ADD  CONSTRAINT [DF_url_toDayCompany]  DEFAULT ((0)) FOR [toDayCompany]
GO
ALTER TABLE [dbo].[Url] ADD  CONSTRAINT [DF_url_status]  DEFAULT ((1)) FOR [status]
GO
ALTER TABLE [dbo].[Url] ADD  CONSTRAINT [DF_url_Ip_repeat]  DEFAULT ((1)) FOR [Ip_repeat]
GO
ALTER TABLE [dbo].[url_click_log] ADD  CONSTRAINT [DF_url_click_log_Ip]  DEFAULT (getdate()) FOR [Ip]
GO
ALTER TABLE [dbo].[url_click_log] ADD  CONSTRAINT [DF_url_click_log_addDate]  DEFAULT (getdate()) FOR [addDate]
GO
ALTER TABLE [dbo].[UrlAccount] ADD  CONSTRAINT [DF_UrlAccount_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[VersionPrLog] ADD  CONSTRAINT [DF_VersionPrLog_AddDate]  DEFAULT (CONVERT([varchar](10),getdate(),(120))) FOR [AddDate]
GO
ALTER TABLE [dbo].[Video] ADD  CONSTRAINT [DF_vIdeo_seetime]  DEFAULT (getdate()) FOR [seetime]
GO
ALTER TABLE [dbo].[WapCounter] ADD  CONSTRAINT [DF_WapCounter_viewnumber]  DEFAULT ((0)) FOR [viewnumber]
GO
ALTER TABLE [dbo].[WapCounter] ADD  CONSTRAINT [DF_WapCounter_spIderviewnumber]  DEFAULT ((0)) FOR [spIderviewnumber]
GO
ALTER TABLE [dbo].[WebSiteMonitorBadLog021] ADD  CONSTRAINT [DF_WebSiteMonitorBadLog_LogTime]  DEFAULT (getdate()) FOR [LogTime]
GO
ALTER TABLE [dbo].[WebSiteMonitorLog1021] ADD  CONSTRAINT [DF_WebSiteMonitorLog_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[workDate] ADD  CONSTRAINT [DF_workDate_IsPaid]  DEFAULT ((0)) FOR [IsPaid]
GO
ALTER TABLE [dbo].[wxChatOnlineTemp] ADD  DEFAULT ((0)) FOR [IsSend]
GO
ALTER TABLE [dbo].[WXQrImage] ADD  CONSTRAINT [DF_WXQrImage_PageType]  DEFAULT ((1)) FOR [PageType]
GO
ALTER TABLE [dbo].[WXQrImage] ADD  CONSTRAINT [DF_WXQrImage_Status]  DEFAULT ((0)) FOR [Status]
GO
ALTER TABLE [dbo].[WXQrImage] ADD  CONSTRAINT [DF_WXQrImage_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[yingyelog] ADD  CONSTRAINT [DF_yingyelog_faxpassed]  DEFAULT ((0)) FOR [faxpassed]
GO
ALTER TABLE [dbo].[yingyelog] ADD  CONSTRAINT [DF_yingyelog_faxnotpassed]  DEFAULT ((0)) FOR [faxnotpassed]
GO
ALTER TABLE [dbo].[yingyelog] ADD  CONSTRAINT [DF_yingyelog_uploadpassed]  DEFAULT ((0)) FOR [uploadpassed]
GO
ALTER TABLE [dbo].[yingyelog] ADD  CONSTRAINT [DF_yingyelog_uploadnotpassed]  DEFAULT ((0)) FOR [uploadnotpassed]
GO
ALTER TABLE [dbo].[yingyelog] ADD  CONSTRAINT [DF_yingyelog_transferpassed]  DEFAULT ((0)) FOR [transferpassed]
GO
ALTER TABLE [dbo].[yingyelog] ADD  CONSTRAINT [DF_yingyelog_transfernotpassed]  DEFAULT ((0)) FOR [transfernotpassed]
GO
ALTER TABLE [dbo].[ZmxyTransaction] ADD  CONSTRAINT [DF_ZmxyTransaction_AddDate]  DEFAULT (getdate()) FOR [AddDate]
GO
ALTER TABLE [dbo].[AdverProject]  WITH CHECK ADD  CONSTRAINT [FK_AdverProject_cpMain] FOREIGN KEY([CompanyId])
REFERENCES [dbo].[cpMain] ([ID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[AdverProject] CHECK CONSTRAINT [FK_AdverProject_cpMain]
GO
ALTER TABLE [dbo].[AgentIp]  WITH CHECK ADD  CONSTRAINT [FK_AgentIp_ManagerUser] FOREIGN KEY([AddMan])
REFERENCES [dbo].[ManagerUser] ([id])
GO
ALTER TABLE [dbo].[AgentIp] CHECK CONSTRAINT [FK_AgentIp_ManagerUser]
GO
ALTER TABLE [dbo].[Answer]  WITH NOCHECK ADD  CONSTRAINT [FK_answer_question] FOREIGN KEY([QuestionId])
REFERENCES [dbo].[Question] ([Id])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[Answer] CHECK CONSTRAINT [FK_answer_question]
GO
ALTER TABLE [dbo].[assessCpInvite]  WITH CHECK ADD  CONSTRAINT [FK_assessCpInvite_assessType] FOREIGN KEY([AssessTypeID])
REFERENCES [dbo].[assessType] ([ID])
ON UPDATE CASCADE
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[assessCpInvite] CHECK CONSTRAINT [FK_assessCpInvite_assessType]
GO
ALTER TABLE [dbo].[assessCpInvite]  WITH CHECK ADD  CONSTRAINT [FK_assessCpInvite_caMain] FOREIGN KEY([CaMainID])
REFERENCES [dbo].[caMain] ([ID])
ON UPDATE CASCADE
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[assessCpInvite] CHECK CONSTRAINT [FK_assessCpInvite_caMain]
GO
ALTER TABLE [dbo].[assessCpInvite]  WITH CHECK ADD  CONSTRAINT [FK_assessCpInvite_paMain] FOREIGN KEY([PaMainID])
REFERENCES [dbo].[paMain] ([ID])
ON UPDATE CASCADE
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[assessCpInvite] CHECK CONSTRAINT [FK_assessCpInvite_paMain]
GO
ALTER TABLE [dbo].[assessDimension]  WITH CHECK ADD  CONSTRAINT [FK_assessDimension_assessDimension] FOREIGN KEY([AssessDimensionGroupID])
REFERENCES [dbo].[assessDimensionGroup] ([ID])
ON UPDATE CASCADE
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[assessDimension] CHECK CONSTRAINT [FK_assessDimension_assessDimension]
GO
ALTER TABLE [dbo].[assessDimensionGroup]  WITH CHECK ADD  CONSTRAINT [FK_assessDimensionGroup_assessType] FOREIGN KEY([AssessTypeID])
REFERENCES [dbo].[assessType] ([ID])
ON UPDATE CASCADE
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[assessDimensionGroup] CHECK CONSTRAINT [FK_assessDimensionGroup_assessType]
GO
ALTER TABLE [dbo].[assessOptions]  WITH CHECK ADD  CONSTRAINT [FK_assessOptions_assessQuestion] FOREIGN KEY([AssessQuestionID])
REFERENCES [dbo].[assessQuestion] ([ID])
ON UPDATE CASCADE
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[assessOptions] CHECK CONSTRAINT [FK_assessOptions_assessQuestion]
GO
ALTER TABLE [dbo].[assessQuestion]  WITH CHECK ADD  CONSTRAINT [FK_assessQuestion_assessTheme] FOREIGN KEY([AssessThemeID])
REFERENCES [dbo].[assessTheme] ([ID])
ON UPDATE CASCADE
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[assessQuestion] CHECK CONSTRAINT [FK_assessQuestion_assessTheme]
GO
ALTER TABLE [dbo].[assessTestAnswer]  WITH CHECK ADD  CONSTRAINT [FK_assessTestAnswer_assessOptions] FOREIGN KEY([AssessOptionsID])
REFERENCES [dbo].[assessOptions] ([ID])
ON UPDATE CASCADE
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[assessTestAnswer] CHECK CONSTRAINT [FK_assessTestAnswer_assessOptions]
GO
ALTER TABLE [dbo].[assessTestAnswer]  WITH CHECK ADD  CONSTRAINT [FK_assessTestAnswer_assessTestLog] FOREIGN KEY([AssessTestLogID])
REFERENCES [dbo].[assessTestLog] ([ID])
ON UPDATE CASCADE
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[assessTestAnswer] CHECK CONSTRAINT [FK_assessTestAnswer_assessTestLog]
GO
ALTER TABLE [dbo].[assessTestLog]  WITH CHECK ADD  CONSTRAINT [FK_assessTestLog_assessType] FOREIGN KEY([AssessTypeID])
REFERENCES [dbo].[assessType] ([ID])
ON UPDATE CASCADE
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[assessTestLog] CHECK CONSTRAINT [FK_assessTestLog_assessType]
GO
ALTER TABLE [dbo].[assessTestLog]  WITH CHECK ADD  CONSTRAINT [FK_assessTestLog_paMain] FOREIGN KEY([PaMainID])
REFERENCES [dbo].[paMain] ([ID])
ON UPDATE CASCADE
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[assessTestLog] CHECK CONSTRAINT [FK_assessTestLog_paMain]
GO
ALTER TABLE [dbo].[assessTheme]  WITH CHECK ADD  CONSTRAINT [FK_assessTheme_assessThemeType] FOREIGN KEY([AssessThemeTypeID])
REFERENCES [dbo].[assessThemeType] ([ID])
GO
ALTER TABLE [dbo].[assessTheme] CHECK CONSTRAINT [FK_assessTheme_assessThemeType]
GO
ALTER TABLE [dbo].[assessTheme]  WITH CHECK ADD  CONSTRAINT [FK_assessTheme_assessType] FOREIGN KEY([AssessTypeID])
REFERENCES [dbo].[assessType] ([ID])
GO
ALTER TABLE [dbo].[assessTheme] CHECK CONSTRAINT [FK_assessTheme_assessType]
GO
ALTER TABLE [dbo].[assessTypeResult]  WITH CHECK ADD  CONSTRAINT [FK_assessTypeResult_assessType] FOREIGN KEY([AssessTypeID])
REFERENCES [dbo].[assessType] ([ID])
ON UPDATE CASCADE
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[assessTypeResult] CHECK CONSTRAINT [FK_assessTypeResult_assessType]
GO
ALTER TABLE [dbo].[Atc_Account]  WITH CHECK ADD  CONSTRAINT [FK_Atc_Account_Atc_Resource] FOREIGN KEY([Atc_Resource_Id])
REFERENCES [dbo].[Atc_Resource] ([Id])
GO
ALTER TABLE [dbo].[Atc_Account] CHECK CONSTRAINT [FK_Atc_Account_Atc_Resource]
GO
ALTER TABLE [dbo].[Atc_Account]  WITH CHECK ADD  CONSTRAINT [FK_Atc_Account_manageruser] FOREIGN KEY([AddMan])
REFERENCES [dbo].[ManagerUser] ([id])
GO
ALTER TABLE [dbo].[Atc_Account] CHECK CONSTRAINT [FK_Atc_Account_manageruser]
GO
ALTER TABLE [dbo].[Atc_Article]  WITH CHECK ADD  CONSTRAINT [FK_Atc_Article_Atc_NewsPoint] FOREIGN KEY([Atc_NewsPoint_Id])
REFERENCES [dbo].[Atc_NewsPoint] ([Id])
GO
ALTER TABLE [dbo].[Atc_Article] CHECK CONSTRAINT [FK_Atc_Article_Atc_NewsPoint]
GO
ALTER TABLE [dbo].[Atc_Article]  WITH CHECK ADD  CONSTRAINT [FK_Atc_Article_ManagerUser] FOREIGN KEY([Addman])
REFERENCES [dbo].[ManagerUser] ([id])
GO
ALTER TABLE [dbo].[Atc_Article] CHECK CONSTRAINT [FK_Atc_Article_ManagerUser]
GO
ALTER TABLE [dbo].[Atc_NewsPoint]  WITH CHECK ADD  CONSTRAINT [FK_Atc_NewsPoint_Atc_Project] FOREIGN KEY([Atc_Project_Id])
REFERENCES [dbo].[Atc_Project] ([Id])
GO
ALTER TABLE [dbo].[Atc_NewsPoint] CHECK CONSTRAINT [FK_Atc_NewsPoint_Atc_Project]
GO
ALTER TABLE [dbo].[Atc_NewsPoint]  WITH CHECK ADD  CONSTRAINT [FK_Atc_NewsPoint_manageruser] FOREIGN KEY([AddMan])
REFERENCES [dbo].[ManagerUser] ([id])
GO
ALTER TABLE [dbo].[Atc_NewsPoint] CHECK CONSTRAINT [FK_Atc_NewsPoint_manageruser]
GO
ALTER TABLE [dbo].[Atc_Project]  WITH CHECK ADD  CONSTRAINT [FK_Atc_Project_manageruser] FOREIGN KEY([Addman])
REFERENCES [dbo].[ManagerUser] ([id])
GO
ALTER TABLE [dbo].[Atc_Project] CHECK CONSTRAINT [FK_Atc_Project_manageruser]
GO
ALTER TABLE [dbo].[Atc_Resource]  WITH CHECK ADD  CONSTRAINT [FK_Atc_Resource_manageruser] FOREIGN KEY([Addman])
REFERENCES [dbo].[ManagerUser] ([id])
GO
ALTER TABLE [dbo].[Atc_Resource] CHECK CONSTRAINT [FK_Atc_Resource_manageruser]
GO
ALTER TABLE [dbo].[Atc_Topic]  WITH CHECK ADD  CONSTRAINT [FK_Atc_Topic_Atc_Account] FOREIGN KEY([Atc_Account_Id])
REFERENCES [dbo].[Atc_Account] ([Id])
GO
ALTER TABLE [dbo].[Atc_Topic] CHECK CONSTRAINT [FK_Atc_Topic_Atc_Account]
GO
ALTER TABLE [dbo].[Atc_Topic]  WITH CHECK ADD  CONSTRAINT [FK_Atc_Topic_Atc_Article] FOREIGN KEY([Atc_Article_Id])
REFERENCES [dbo].[Atc_Article] ([Id])
GO
ALTER TABLE [dbo].[Atc_Topic] CHECK CONSTRAINT [FK_Atc_Topic_Atc_Article]
GO
ALTER TABLE [dbo].[Atc_Topic_ClickNum]  WITH CHECK ADD  CONSTRAINT [FK_Atc_Topic_ClickNum_Atc_Topic] FOREIGN KEY([Atc_Topic_Id])
REFERENCES [dbo].[Atc_Topic] ([Id])
GO
ALTER TABLE [dbo].[Atc_Topic_ClickNum] CHECK CONSTRAINT [FK_Atc_Topic_ClickNum_Atc_Topic]
GO
ALTER TABLE [dbo].[Atc_TopicFollow]  WITH CHECK ADD  CONSTRAINT [FK_Atc_TopicFollow_Atc_Account] FOREIGN KEY([Atc_Account_Id])
REFERENCES [dbo].[Atc_Account] ([Id])
GO
ALTER TABLE [dbo].[Atc_TopicFollow] CHECK CONSTRAINT [FK_Atc_TopicFollow_Atc_Account]
GO
ALTER TABLE [dbo].[Atc_TopicFollow]  WITH CHECK ADD  CONSTRAINT [FK_Atc_TopicFollow_Atc_Topic] FOREIGN KEY([Atc_Topic_Id])
REFERENCES [dbo].[Atc_Topic] ([Id])
GO
ALTER TABLE [dbo].[Atc_TopicFollow] CHECK CONSTRAINT [FK_Atc_TopicFollow_Atc_Topic]
GO
ALTER TABLE [dbo].[BackData]  WITH CHECK ADD  CONSTRAINT [FK_BackData_Manageruser] FOREIGN KEY([ManagerID])
REFERENCES [dbo].[ManagerUser] ([id])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[BackData] CHECK CONSTRAINT [FK_BackData_Manageruser]
GO
ALTER TABLE [dbo].[BestEmployerVote]  WITH CHECK ADD  CONSTRAINT [FK_BestEmployerVote_BestEmployer] FOREIGN KEY([BestEmployerID])
REFERENCES [dbo].[BestEmployer] ([ID])
GO
ALTER TABLE [dbo].[BestEmployerVote] CHECK CONSTRAINT [FK_BestEmployerVote_BestEmployer]
GO
ALTER TABLE [dbo].[bsCpBackLogin]  WITH CHECK ADD  CONSTRAINT [FK_bsCpBackLogin_caMain] FOREIGN KEY([caMainID])
REFERENCES [dbo].[caMain] ([ID])
ON UPDATE CASCADE
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[bsCpBackLogin] CHECK CONSTRAINT [FK_bsCpBackLogin_caMain]
GO
ALTER TABLE [dbo].[bsCpBackLogin]  WITH CHECK ADD  CONSTRAINT [FK_bsCpBackLogin_manageruser] FOREIGN KEY([ManagerUserID])
REFERENCES [dbo].[ManagerUser] ([id])
GO
ALTER TABLE [dbo].[bsCpBackLogin] CHECK CONSTRAINT [FK_bsCpBackLogin_manageruser]
GO
ALTER TABLE [dbo].[bsCpModify]  WITH CHECK ADD  CONSTRAINT [FK_bsCpModify_caMain] FOREIGN KEY([caMainID])
REFERENCES [dbo].[caMain] ([ID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[bsCpModify] CHECK CONSTRAINT [FK_bsCpModify_caMain]
GO
ALTER TABLE [dbo].[bsCpModify]  WITH CHECK ADD  CONSTRAINT [FK_bsCpModify_cpMain] FOREIGN KEY([cpMainID])
REFERENCES [dbo].[cpMain] ([ID])
GO
ALTER TABLE [dbo].[bsCpModify] CHECK CONSTRAINT [FK_bsCpModify_cpMain]
GO
ALTER TABLE [dbo].[bsCpModify]  WITH CHECK ADD  CONSTRAINT [FK_bsCpModify_Job] FOREIGN KEY([SubID])
REFERENCES [dbo].[Job] ([ID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[bsCpModify] CHECK CONSTRAINT [FK_bsCpModify_Job]
GO
ALTER TABLE [dbo].[bsCpStatus]  WITH CHECK ADD  CONSTRAINT [FK_bsCpStatus_cpMain] FOREIGN KEY([cpMainID])
REFERENCES [dbo].[cpMain] ([ID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[bsCpStatus] CHECK CONSTRAINT [FK_bsCpStatus_cpMain]
GO
ALTER TABLE [dbo].[bsCpVerify]  WITH CHECK ADD  CONSTRAINT [FK_bsCpVerify_cpMain] FOREIGN KEY([cpMainID])
REFERENCES [dbo].[cpMain] ([ID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[bsCpVerify] CHECK CONSTRAINT [FK_bsCpVerify_cpMain]
GO
ALTER TABLE [dbo].[bsCpVerify]  WITH CHECK ADD  CONSTRAINT [FK_bsCpVerify_manageruser] FOREIGN KEY([VerifyMan])
REFERENCES [dbo].[ManagerUser] ([id])
GO
ALTER TABLE [dbo].[bsCpVerify] CHECK CONSTRAINT [FK_bsCpVerify_manageruser]
GO
ALTER TABLE [dbo].[bsCpVerifyLog]  WITH CHECK ADD  CONSTRAINT [FK_bsCpVerifyLog_bsCpVerify] FOREIGN KEY([bsCpVerifyID])
REFERENCES [dbo].[bsCpVerify] ([ID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[bsCpVerifyLog] CHECK CONSTRAINT [FK_bsCpVerifyLog_bsCpVerify]
GO
ALTER TABLE [dbo].[bsCpVerifyLog]  WITH CHECK ADD  CONSTRAINT [FK_bsCpVerifyLog_Job] FOREIGN KEY([SubID])
REFERENCES [dbo].[Job] ([ID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[bsCpVerifyLog] CHECK CONSTRAINT [FK_bsCpVerifyLog_Job]
GO
ALTER TABLE [dbo].[bsCvModify]  WITH CHECK ADD  CONSTRAINT [FK_bsCvModify_cvMain] FOREIGN KEY([cvMainID])
REFERENCES [dbo].[cvMain] ([ID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[bsCvModify] CHECK CONSTRAINT [FK_bsCvModify_cvMain]
GO
ALTER TABLE [dbo].[bsCvReview]  WITH CHECK ADD  CONSTRAINT [FK_bsCvReview_cvMain] FOREIGN KEY([cvMainID])
REFERENCES [dbo].[cvMain] ([ID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[bsCvReview] CHECK CONSTRAINT [FK_bsCvReview_cvMain]
GO
ALTER TABLE [dbo].[bsCvVerify]  WITH CHECK ADD  CONSTRAINT [FK_bsCvVerify_cvMain] FOREIGN KEY([cvMainID])
REFERENCES [dbo].[cvMain] ([ID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[bsCvVerify] CHECK CONSTRAINT [FK_bsCvVerify_cvMain]
GO
ALTER TABLE [dbo].[bsCvVerify]  WITH CHECK ADD  CONSTRAINT [FK_bsCvVerify_manageruser] FOREIGN KEY([VerifyMan])
REFERENCES [dbo].[ManagerUser] ([id])
GO
ALTER TABLE [dbo].[bsCvVerify] CHECK CONSTRAINT [FK_bsCvVerify_manageruser]
GO
ALTER TABLE [dbo].[bsJobProblem]  WITH CHECK ADD  CONSTRAINT [FK_bsJobProblem_cpMain] FOREIGN KEY([cpMainID])
REFERENCES [dbo].[cpMain] ([ID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[bsJobProblem] CHECK CONSTRAINT [FK_bsJobProblem_cpMain]
GO
ALTER TABLE [dbo].[bsPaBackLogin]  WITH CHECK ADD  CONSTRAINT [FK_bsPaBackLogin_manageruser] FOREIGN KEY([ManagerUserID])
REFERENCES [dbo].[ManagerUser] ([id])
GO
ALTER TABLE [dbo].[bsPaBackLogin] CHECK CONSTRAINT [FK_bsPaBackLogin_manageruser]
GO
ALTER TABLE [dbo].[bsPaBackLogin]  WITH CHECK ADD  CONSTRAINT [FK_bsPaBackLogin_paMain] FOREIGN KEY([paMainID])
REFERENCES [dbo].[paMain] ([ID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[bsPaBackLogin] CHECK CONSTRAINT [FK_bsPaBackLogin_paMain]
GO
ALTER TABLE [dbo].[caActiveLog]  WITH CHECK ADD  CONSTRAINT [FK_caActiveLog_caMain] FOREIGN KEY([caMainID])
REFERENCES [dbo].[caMain] ([ID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[caActiveLog] CHECK CONSTRAINT [FK_caActiveLog_caMain]
GO
ALTER TABLE [dbo].[caBalanceLog]  WITH CHECK ADD  CONSTRAINT [FK_caBalanceLog_caMain] FOREIGN KEY([caMainID])
REFERENCES [dbo].[caMain] ([ID])
GO
ALTER TABLE [dbo].[caBalanceLog] CHECK CONSTRAINT [FK_caBalanceLog_caMain]
GO
ALTER TABLE [dbo].[caCvFinder]  WITH CHECK ADD  CONSTRAINT [FK_caCvFinder_caMain] FOREIGN KEY([caMainID])
REFERENCES [dbo].[caMain] ([ID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[caCvFinder] CHECK CONSTRAINT [FK_caCvFinder_caMain]
GO
ALTER TABLE [dbo].[caCvIntention]  WITH CHECK ADD  CONSTRAINT [FK_cacvIntention_cvMain] FOREIGN KEY([cvMainID])
REFERENCES [dbo].[cvMain] ([ID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[caCvIntention] CHECK CONSTRAINT [FK_cacvIntention_cvMain]
GO
ALTER TABLE [dbo].[caCvIntention]  WITH CHECK ADD  CONSTRAINT [FK_cacvIntention_Job] FOREIGN KEY([JobId])
REFERENCES [dbo].[Job] ([ID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[caCvIntention] CHECK CONSTRAINT [FK_cacvIntention_Job]
GO
ALTER TABLE [dbo].[caCvQuotaLog]  WITH CHECK ADD  CONSTRAINT [FK_caCvQuotaLog_caMain] FOREIGN KEY([caMainID])
REFERENCES [dbo].[caMain] ([ID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[caCvQuotaLog] CHECK CONSTRAINT [FK_caCvQuotaLog_caMain]
GO
ALTER TABLE [dbo].[caCvQuotaLog]  WITH CHECK ADD  CONSTRAINT [FK_caCvQuotaLog_cvMain] FOREIGN KEY([cvMainID])
REFERENCES [dbo].[cvMain] ([ID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[caCvQuotaLog] CHECK CONSTRAINT [FK_caCvQuotaLog_cvMain]
GO
ALTER TABLE [dbo].[caCvRemark]  WITH CHECK ADD  CONSTRAINT [FK_caCvRemark_caMain] FOREIGN KEY([caMainID])
REFERENCES [dbo].[caMain] ([ID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[caCvRemark] CHECK CONSTRAINT [FK_caCvRemark_caMain]
GO
ALTER TABLE [dbo].[caCvRemark]  WITH CHECK ADD  CONSTRAINT [FK_caCvRemark_cvMain] FOREIGN KEY([cvMainID])
REFERENCES [dbo].[cvMain] ([ID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[caCvRemark] CHECK CONSTRAINT [FK_caCvRemark_cvMain]
GO
ALTER TABLE [dbo].[caCvViewLog]  WITH CHECK ADD  CONSTRAINT [FK_caCvViewLog_caMain] FOREIGN KEY([caMainID])
REFERENCES [dbo].[caMain] ([ID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[caCvViewLog] CHECK CONSTRAINT [FK_caCvViewLog_caMain]
GO
ALTER TABLE [dbo].[caCvViewLog]  WITH CHECK ADD  CONSTRAINT [FK_caCvViewLog_cvMain] FOREIGN KEY([cvMainID])
REFERENCES [dbo].[cvMain] ([ID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[caCvViewLog] CHECK CONSTRAINT [FK_caCvViewLog_cvMain]
GO
ALTER TABLE [dbo].[caDailyGiftLog]  WITH CHECK ADD  CONSTRAINT [FK_caDailyGiftLog_caMain] FOREIGN KEY([caMainID])
REFERENCES [dbo].[caMain] ([ID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[caDailyGiftLog] CHECK CONSTRAINT [FK_caDailyGiftLog_caMain]
GO
ALTER TABLE [dbo].[caDailyGiftLog]  WITH CHECK ADD  CONSTRAINT [FK_caDailyGiftLog_cvMain] FOREIGN KEY([cvMainID])
REFERENCES [dbo].[cvMain] ([ID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[caDailyGiftLog] CHECK CONSTRAINT [FK_caDailyGiftLog_cvMain]
GO
ALTER TABLE [dbo].[caFavorate]  WITH CHECK ADD  CONSTRAINT [FK_caFavorate_cvMain] FOREIGN KEY([cvMainID])
REFERENCES [dbo].[cvMain] ([ID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[caFavorate] CHECK CONSTRAINT [FK_caFavorate_cvMain]
GO
ALTER TABLE [dbo].[caFavorate]  WITH CHECK ADD  CONSTRAINT [FK_caFavorate_Job] FOREIGN KEY([JobId])
REFERENCES [dbo].[Job] ([ID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[caFavorate] CHECK CONSTRAINT [FK_caFavorate_Job]
GO
ALTER TABLE [dbo].[caFavorateMark]  WITH CHECK ADD  CONSTRAINT [FK_caFavorateMark_caMain] FOREIGN KEY([caMainID])
REFERENCES [dbo].[caMain] ([ID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[caFavorateMark] CHECK CONSTRAINT [FK_caFavorateMark_caMain]
GO
ALTER TABLE [dbo].[caFeedback]  WITH CHECK ADD  CONSTRAINT [FK_caFeedback_caMain] FOREIGN KEY([caMainID])
REFERENCES [dbo].[caMain] ([ID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[caFeedback] CHECK CONSTRAINT [FK_caFeedback_caMain]
GO
ALTER TABLE [dbo].[caInterviewTemplate]  WITH CHECK ADD  CONSTRAINT [FK_caInterviewTemplate_caMain] FOREIGN KEY([caMainID])
REFERENCES [dbo].[caMain] ([ID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[caInterviewTemplate] CHECK CONSTRAINT [FK_caInterviewTemplate_caMain]
GO
ALTER TABLE [dbo].[caLoginLog]  WITH CHECK ADD  CONSTRAINT [FK_caLoginLog_caMain] FOREIGN KEY([caMainID])
REFERENCES [dbo].[caMain] ([ID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[caLoginLog] CHECK CONSTRAINT [FK_caLoginLog_caMain]
GO
ALTER TABLE [dbo].[caMain]  WITH CHECK ADD  CONSTRAINT [FK_caMain_cpMain] FOREIGN KEY([cpMainID])
REFERENCES [dbo].[cpMain] ([ID])
GO
ALTER TABLE [dbo].[caMain] CHECK CONSTRAINT [FK_caMain_cpMain]
GO
ALTER TABLE [dbo].[caOperationLog]  WITH CHECK ADD  CONSTRAINT [FK_caOperationLog_caMain] FOREIGN KEY([caMainID])
REFERENCES [dbo].[caMain] ([ID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[caOperationLog] CHECK CONSTRAINT [FK_caOperationLog_caMain]
GO
ALTER TABLE [dbo].[caOrder]  WITH CHECK ADD  CONSTRAINT [FK_caOrder_dcPayMethod] FOREIGN KEY([PayMethod])
REFERENCES [dbo].[dcPayMethod] ([PayMethodID])
GO
ALTER TABLE [dbo].[caOrder] CHECK CONSTRAINT [FK_caOrder_dcPayMethod]
GO
ALTER TABLE [dbo].[caOrder]  WITH CHECK ADD  CONSTRAINT [FK_caOrder_ManagerUser] FOREIGN KEY([Manageruserid])
REFERENCES [dbo].[ManagerUser] ([id])
GO
ALTER TABLE [dbo].[caOrder] CHECK CONSTRAINT [FK_caOrder_ManagerUser]
GO
ALTER TABLE [dbo].[caOrderRemarks]  WITH CHECK ADD  CONSTRAINT [FK_caOrderRemarks_caOrder] FOREIGN KEY([OrderId])
REFERENCES [dbo].[caOrder] ([ID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[caOrderRemarks] CHECK CONSTRAINT [FK_caOrderRemarks_caOrder]
GO
ALTER TABLE [dbo].[caPlaint]  WITH CHECK ADD  CONSTRAINT [FK_caPlaint_cvMain] FOREIGN KEY([cvMainID])
REFERENCES [dbo].[cvMain] ([ID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[caPlaint] CHECK CONSTRAINT [FK_caPlaint_cvMain]
GO
ALTER TABLE [dbo].[Certificate_UnReal]  WITH CHECK ADD  CONSTRAINT [FK_Certificate_UnReal_Manageruser] FOREIGN KEY([AddMan])
REFERENCES [dbo].[ManagerUser] ([id])
GO
ALTER TABLE [dbo].[Certificate_UnReal] CHECK CONSTRAINT [FK_Certificate_UnReal_Manageruser]
GO
ALTER TABLE [dbo].[ChatOnlineLog]  WITH CHECK ADD  CONSTRAINT [FK_ChatOnlineLog_ChatOnline] FOREIGN KEY([ChatOnlineID])
REFERENCES [dbo].[ChatOnline] ([ID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[ChatOnlineLog] CHECK CONSTRAINT [FK_ChatOnlineLog_ChatOnline]
GO
ALTER TABLE [dbo].[Company_Black]  WITH CHECK ADD  CONSTRAINT [FK_company_black_manageruser] FOREIGN KEY([managerid])
REFERENCES [dbo].[ManagerUser] ([id])
GO
ALTER TABLE [dbo].[Company_Black] CHECK CONSTRAINT [FK_company_black_manageruser]
GO
ALTER TABLE [dbo].[Company_deleted]  WITH CHECK ADD  CONSTRAINT [FK_Company_deleted_ManagerUser] FOREIGN KEY([HandleMan])
REFERENCES [dbo].[ManagerUser] ([id])
GO
ALTER TABLE [dbo].[Company_deleted] CHECK CONSTRAINT [FK_Company_deleted_ManagerUser]
GO
ALTER TABLE [dbo].[Company_Xinxi]  WITH CHECK ADD  CONSTRAINT [FK_company_xinxi_manageruser] FOREIGN KEY([AddMan])
REFERENCES [dbo].[ManagerUser] ([id])
GO
ALTER TABLE [dbo].[Company_Xinxi] CHECK CONSTRAINT [FK_company_xinxi_manageruser]
GO
ALTER TABLE [dbo].[CompanyNotify]  WITH CHECK ADD  CONSTRAINT [FK_CompanyNotify_cpMain] FOREIGN KEY([CompanyId])
REFERENCES [dbo].[cpMain] ([ID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[CompanyNotify] CHECK CONSTRAINT [FK_CompanyNotify_cpMain]
GO
ALTER TABLE [dbo].[CompanyNotify]  WITH CHECK ADD  CONSTRAINT [FK_CompanyNotify_manageruser] FOREIGN KEY([ManagerUserId])
REFERENCES [dbo].[ManagerUser] ([id])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[CompanyNotify] CHECK CONSTRAINT [FK_CompanyNotify_manageruser]
GO
ALTER TABLE [dbo].[Consultant_assign]  WITH CHECK ADD  CONSTRAINT [FK_Consultant_assign_dcProvince] FOREIGN KEY([Province_Id])
REFERENCES [dbo].[dcProvince] ([ID])
GO
ALTER TABLE [dbo].[Consultant_assign] CHECK CONSTRAINT [FK_Consultant_assign_dcProvince]
GO
ALTER TABLE [dbo].[Consultant_assign]  WITH CHECK ADD  CONSTRAINT [FK_Consultant_assign_ManagerUser] FOREIGN KEY([ManagerUserId])
REFERENCES [dbo].[ManagerUser] ([id])
GO
ALTER TABLE [dbo].[Consultant_assign] CHECK CONSTRAINT [FK_Consultant_assign_ManagerUser]
GO
ALTER TABLE [dbo].[Consultant_ManagerUser_Month]  WITH CHECK ADD  CONSTRAINT [FK_Consultant_ManagerUser_Month_ManagerUser] FOREIGN KEY([ConsultantId])
REFERENCES [dbo].[ManagerUser] ([id])
GO
ALTER TABLE [dbo].[Consultant_ManagerUser_Month] CHECK CONSTRAINT [FK_Consultant_ManagerUser_Month_ManagerUser]
GO
ALTER TABLE [dbo].[Contact]  WITH CHECK ADD  CONSTRAINT [FK_Contact_cpMain] FOREIGN KEY([CompanyId])
REFERENCES [dbo].[cpMain] ([ID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[Contact] CHECK CONSTRAINT [FK_Contact_cpMain]
GO
ALTER TABLE [dbo].[Contact]  WITH CHECK ADD  CONSTRAINT [FK_Contact_ManagerUser] FOREIGN KEY([ManagerUserId])
REFERENCES [dbo].[ManagerUser] ([id])
GO
ALTER TABLE [dbo].[Contact] CHECK CONSTRAINT [FK_Contact_ManagerUser]
GO
ALTER TABLE [dbo].[cpCertification]  WITH CHECK ADD  CONSTRAINT [FK_cpCertification_cpMain] FOREIGN KEY([cpMainID])
REFERENCES [dbo].[cpMain] ([ID])
GO
ALTER TABLE [dbo].[cpCertification] CHECK CONSTRAINT [FK_cpCertification_cpMain]
GO
ALTER TABLE [dbo].[cpCompanyEmail]  WITH CHECK ADD  CONSTRAINT [FK_cpCompanyEmail_cpCertification] FOREIGN KEY([cpCertificationID])
REFERENCES [dbo].[cpCertification] ([ID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[cpCompanyEmail] CHECK CONSTRAINT [FK_cpCompanyEmail_cpCertification]
GO
ALTER TABLE [dbo].[cpCorporationAccount]  WITH CHECK ADD  CONSTRAINT [FK_cpCorporationAccount_cpCertification] FOREIGN KEY([cpCertificationID])
REFERENCES [dbo].[cpCertification] ([ID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[cpCorporationAccount] CHECK CONSTRAINT [FK_cpCorporationAccount_cpCertification]
GO
ALTER TABLE [dbo].[cpImage]  WITH CHECK ADD  CONSTRAINT [FK_cpImage_cpMain] FOREIGN KEY([cpMainID])
REFERENCES [dbo].[cpMain] ([ID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[cpImage] CHECK CONSTRAINT [FK_cpImage_cpMain]
GO
ALTER TABLE [dbo].[cpImage]  WITH CHECK ADD  CONSTRAINT [FK_cpImage_manageruser] FOREIGN KEY([CheckMan])
REFERENCES [dbo].[ManagerUser] ([id])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[cpImage] CHECK CONSTRAINT [FK_cpImage_manageruser]
GO
ALTER TABLE [dbo].[cpIndustry]  WITH CHECK ADD  CONSTRAINT [FK_cpIndustry_cpMain] FOREIGN KEY([cpMainID])
REFERENCES [dbo].[cpMain] ([ID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[cpIndustry] CHECK CONSTRAINT [FK_cpIndustry_cpMain]
GO
ALTER TABLE [dbo].[cpIndustry]  WITH CHECK ADD  CONSTRAINT [FK_cpIndustry_dcIndustry] FOREIGN KEY([dcIndustryID])
REFERENCES [dbo].[dcIndustry] ([ID])
GO
ALTER TABLE [dbo].[cpIndustry] CHECK CONSTRAINT [FK_cpIndustry_dcIndustry]
GO
ALTER TABLE [dbo].[cpLicence]  WITH CHECK ADD  CONSTRAINT [FK_cpLicence_cpMain] FOREIGN KEY([cpMainID])
REFERENCES [dbo].[cpMain] ([ID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[cpLicence] CHECK CONSTRAINT [FK_cpLicence_cpMain]
GO
ALTER TABLE [dbo].[cpLicence]  WITH CHECK ADD  CONSTRAINT [FK_cpLicence_manageruser] FOREIGN KEY([CheckMan])
REFERENCES [dbo].[ManagerUser] ([id])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[cpLicence] CHECK CONSTRAINT [FK_cpLicence_manageruser]
GO
ALTER TABLE [dbo].[cpLicenceChangeLog]  WITH CHECK ADD  CONSTRAINT [FK_cpLicenceChangeLog_cpMain] FOREIGN KEY([cpMainID])
REFERENCES [dbo].[cpMain] ([ID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[cpLicenceChangeLog] CHECK CONSTRAINT [FK_cpLicenceChangeLog_cpMain]
GO
ALTER TABLE [dbo].[cpLicenceChangeLog]  WITH CHECK ADD  CONSTRAINT [FK_cpLicenceChangeLog_manageruser] FOREIGN KEY([ManagerUserID])
REFERENCES [dbo].[ManagerUser] ([id])
GO
ALTER TABLE [dbo].[cpLicenceChangeLog] CHECK CONSTRAINT [FK_cpLicenceChangeLog_manageruser]
GO
ALTER TABLE [dbo].[cpLicenceLog]  WITH CHECK ADD  CONSTRAINT [FK_cpLicenceLog_cpMain] FOREIGN KEY([cpMainID])
REFERENCES [dbo].[cpMain] ([ID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[cpLicenceLog] CHECK CONSTRAINT [FK_cpLicenceLog_cpMain]
GO
ALTER TABLE [dbo].[cpLicenceLog]  WITH CHECK ADD  CONSTRAINT [FK_cpLicenceLog_manageruser] FOREIGN KEY([CheckMan])
REFERENCES [dbo].[ManagerUser] ([id])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[cpLicenceLog] CHECK CONSTRAINT [FK_cpLicenceLog_manageruser]
GO
ALTER TABLE [dbo].[cpMain]  WITH CHECK ADD  CONSTRAINT [FK_cpMain_dcCompanyKind] FOREIGN KEY([dcCompanyKindID])
REFERENCES [dbo].[dcCompanyKind] ([ID])
GO
ALTER TABLE [dbo].[cpMain] CHECK CONSTRAINT [FK_cpMain_dcCompanyKind]
GO
ALTER TABLE [dbo].[cpMain]  WITH CHECK ADD  CONSTRAINT [FK_cpMain_dcCompanySize] FOREIGN KEY([dcCompanySizeID])
REFERENCES [dbo].[dcCompanySize] ([ID])
GO
ALTER TABLE [dbo].[cpMain] CHECK CONSTRAINT [FK_cpMain_dcCompanySize]
GO
ALTER TABLE [dbo].[cpMain]  WITH CHECK ADD  CONSTRAINT [FK_cpMain_dcProvince] FOREIGN KEY([dcProvinceID])
REFERENCES [dbo].[dcProvince] ([ID])
GO
ALTER TABLE [dbo].[cpMain] CHECK CONSTRAINT [FK_cpMain_dcProvince]
GO
ALTER TABLE [dbo].[cpMain]  WITH CHECK ADD  CONSTRAINT [FK_cpMain_dcRegion] FOREIGN KEY([dcRegionID])
REFERENCES [dbo].[dcRegion] ([ID])
GO
ALTER TABLE [dbo].[cpMain] CHECK CONSTRAINT [FK_cpMain_dcRegion]
GO
ALTER TABLE [dbo].[cpMain]  WITH CHECK ADD  CONSTRAINT [FK_cpMain_manageruser] FOREIGN KEY([ConsultantID])
REFERENCES [dbo].[ManagerUser] ([id])
ON DELETE SET NULL
GO
ALTER TABLE [dbo].[cpMain] CHECK CONSTRAINT [FK_cpMain_manageruser]
GO
ALTER TABLE [dbo].[cpPersonalAccount]  WITH CHECK ADD  CONSTRAINT [FK_cpPersonalAccount_cpCertification] FOREIGN KEY([cpCertificationID])
REFERENCES [dbo].[cpCertification] ([ID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[cpPersonalAccount] CHECK CONSTRAINT [FK_cpPersonalAccount_cpCertification]
GO
ALTER TABLE [dbo].[cpProductBulletin]  WITH CHECK ADD  CONSTRAINT [FK_cpProductBulletin_manageruser] FOREIGN KEY([AddMan])
REFERENCES [dbo].[ManagerUser] ([id])
GO
ALTER TABLE [dbo].[cpProductBulletin] CHECK CONSTRAINT [FK_cpProductBulletin_manageruser]
GO
ALTER TABLE [dbo].[cpSession]  WITH CHECK ADD  CONSTRAINT [FK_cpSession_caMain] FOREIGN KEY([caMainID])
REFERENCES [dbo].[caMain] ([ID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[cpSession] CHECK CONSTRAINT [FK_cpSession_caMain]
GO
ALTER TABLE [dbo].[Customer_Assign]  WITH CHECK ADD  CONSTRAINT [FK_customer_assign_dcProvince] FOREIGN KEY([Province_Id])
REFERENCES [dbo].[dcProvince] ([ID])
GO
ALTER TABLE [dbo].[Customer_Assign] CHECK CONSTRAINT [FK_customer_assign_dcProvince]
GO
ALTER TABLE [dbo].[Customer_Assign]  WITH CHECK ADD  CONSTRAINT [FK_customer_assign_ManagerUser] FOREIGN KEY([ManagerUserId])
REFERENCES [dbo].[ManagerUser] ([id])
GO
ALTER TABLE [dbo].[Customer_Assign] CHECK CONSTRAINT [FK_customer_assign_ManagerUser]
GO
ALTER TABLE [dbo].[Customer_Target]  WITH CHECK ADD  CONSTRAINT [FK_customer_target_ManagerUser] FOREIGN KEY([ManagerUserId])
REFERENCES [dbo].[ManagerUser] ([id])
GO
ALTER TABLE [dbo].[Customer_Target] CHECK CONSTRAINT [FK_customer_target_ManagerUser]
GO
ALTER TABLE [dbo].[cvAppendix]  WITH CHECK ADD  CONSTRAINT [FK_cvAppendix_cvMain] FOREIGN KEY([cvMainID])
REFERENCES [dbo].[cvMain] ([ID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[cvAppendix] CHECK CONSTRAINT [FK_cvAppendix_cvMain]
GO
ALTER TABLE [dbo].[cvAppendixPublish]  WITH CHECK ADD  CONSTRAINT [FK_cvAppendixPublish_cvMainPublish] FOREIGN KEY([cvMainID])
REFERENCES [dbo].[cvMainPublish] ([ID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[cvAppendixPublish] CHECK CONSTRAINT [FK_cvAppendixPublish_cvMainPublish]
GO
ALTER TABLE [dbo].[cvAttachment]  WITH CHECK ADD  CONSTRAINT [FK_cvAttachment_cvMain] FOREIGN KEY([cvMainID])
REFERENCES [dbo].[cvMain] ([ID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[cvAttachment] CHECK CONSTRAINT [FK_cvAttachment_cvMain]
GO
ALTER TABLE [dbo].[cvEducation]  WITH CHECK ADD  CONSTRAINT [FK_cvEducation_cvMain] FOREIGN KEY([cvMainID])
REFERENCES [dbo].[cvMain] ([ID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[cvEducation] CHECK CONSTRAINT [FK_cvEducation_cvMain]
GO
ALTER TABLE [dbo].[cvEducation]  WITH CHECK ADD  CONSTRAINT [FK_cvEducation_dcMajor] FOREIGN KEY([dcMajorID])
REFERENCES [dbo].[dcMajor] ([ID])
GO
ALTER TABLE [dbo].[cvEducation] CHECK CONSTRAINT [FK_cvEducation_dcMajor]
GO
ALTER TABLE [dbo].[cvEducationPublish]  WITH CHECK ADD  CONSTRAINT [FK_cvEducationPublish_cvMainPublish] FOREIGN KEY([cvMainID])
REFERENCES [dbo].[cvMainPublish] ([ID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[cvEducationPublish] CHECK CONSTRAINT [FK_cvEducationPublish_cvMainPublish]
GO
ALTER TABLE [dbo].[cvEducationPublish]  WITH CHECK ADD  CONSTRAINT [FK_cvEducationPublish_dcMajor] FOREIGN KEY([dcMajorID])
REFERENCES [dbo].[dcMajor] ([ID])
GO
ALTER TABLE [dbo].[cvEducationPublish] CHECK CONSTRAINT [FK_cvEducationPublish_dcMajor]
GO
ALTER TABLE [dbo].[cvExperience]  WITH CHECK ADD  CONSTRAINT [FK_cvExperience_cvMain] FOREIGN KEY([cvMainID])
REFERENCES [dbo].[cvMain] ([ID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[cvExperience] CHECK CONSTRAINT [FK_cvExperience_cvMain]
GO
ALTER TABLE [dbo].[cvExperience]  WITH CHECK ADD  CONSTRAINT [FK_cvExperience_dcCompanyKind] FOREIGN KEY([dcCompanyKindID])
REFERENCES [dbo].[dcCompanyKind] ([ID])
GO
ALTER TABLE [dbo].[cvExperience] CHECK CONSTRAINT [FK_cvExperience_dcCompanyKind]
GO
ALTER TABLE [dbo].[cvExperience]  WITH CHECK ADD  CONSTRAINT [FK_cvExperience_dcCompanySize] FOREIGN KEY([dcCompanySizeID])
REFERENCES [dbo].[dcCompanySize] ([ID])
GO
ALTER TABLE [dbo].[cvExperience] CHECK CONSTRAINT [FK_cvExperience_dcCompanySize]
GO
ALTER TABLE [dbo].[cvExperience]  WITH CHECK ADD  CONSTRAINT [FK_cvExperience_dcIndustry] FOREIGN KEY([dcIndustryID])
REFERENCES [dbo].[dcIndustry] ([ID])
GO
ALTER TABLE [dbo].[cvExperience] CHECK CONSTRAINT [FK_cvExperience_dcIndustry]
GO
ALTER TABLE [dbo].[cvExperience]  WITH CHECK ADD  CONSTRAINT [FK_cvExperience_dcJobType] FOREIGN KEY([dcJobtypeID])
REFERENCES [dbo].[dcJobType] ([ID])
GO
ALTER TABLE [dbo].[cvExperience] CHECK CONSTRAINT [FK_cvExperience_dcJobType]
GO
ALTER TABLE [dbo].[cvExperience]  WITH CHECK ADD  CONSTRAINT [FK_cvExperience_dcLeaveReson] FOREIGN KEY([dcLeaveResonID])
REFERENCES [dbo].[dcLeaveReson] ([ID])
GO
ALTER TABLE [dbo].[cvExperience] CHECK CONSTRAINT [FK_cvExperience_dcLeaveReson]
GO
ALTER TABLE [dbo].[cvExperience]  WITH CHECK ADD  CONSTRAINT [FK_cvExperience_dcLowerNumber] FOREIGN KEY([SubNodeNum])
REFERENCES [dbo].[dcLowerNumber] ([ID])
GO
ALTER TABLE [dbo].[cvExperience] CHECK CONSTRAINT [FK_cvExperience_dcLowerNumber]
GO
ALTER TABLE [dbo].[cvExperience]  WITH CHECK ADD  CONSTRAINT [FK_cvExperience_dcRegion] FOREIGN KEY([WorkPlace])
REFERENCES [dbo].[dcRegion] ([ID])
GO
ALTER TABLE [dbo].[cvExperience] CHECK CONSTRAINT [FK_cvExperience_dcRegion]
GO
ALTER TABLE [dbo].[cvExperiencePublish]  WITH CHECK ADD  CONSTRAINT [FK_cvExperiencePublish_cvMainPublish] FOREIGN KEY([cvMainID])
REFERENCES [dbo].[cvMainPublish] ([ID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[cvExperiencePublish] CHECK CONSTRAINT [FK_cvExperiencePublish_cvMainPublish]
GO
ALTER TABLE [dbo].[cvExperiencePublish]  WITH CHECK ADD  CONSTRAINT [FK_cvExperiencePublish_dcIndustry] FOREIGN KEY([dcIndustryID])
REFERENCES [dbo].[dcIndustry] ([ID])
GO
ALTER TABLE [dbo].[cvExperiencePublish] CHECK CONSTRAINT [FK_cvExperiencePublish_dcIndustry]
GO
ALTER TABLE [dbo].[cvExperiencePublish]  WITH CHECK ADD  CONSTRAINT [FK_cvExperiencePublish_dcJobType] FOREIGN KEY([dcJobtypeID])
REFERENCES [dbo].[dcJobType] ([ID])
GO
ALTER TABLE [dbo].[cvExperiencePublish] CHECK CONSTRAINT [FK_cvExperiencePublish_dcJobType]
GO
ALTER TABLE [dbo].[cvExperiencePublish]  WITH CHECK ADD  CONSTRAINT [FK_cvExperiencePublish_dcLowerNumber] FOREIGN KEY([SubNodeNum])
REFERENCES [dbo].[dcLowerNumber] ([ID])
GO
ALTER TABLE [dbo].[cvExperiencePublish] CHECK CONSTRAINT [FK_cvExperiencePublish_dcLowerNumber]
GO
ALTER TABLE [dbo].[cvIndustry]  WITH CHECK ADD  CONSTRAINT [FK_cvIndustry_cvMain] FOREIGN KEY([cvMainID])
REFERENCES [dbo].[cvMain] ([ID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[cvIndustry] CHECK CONSTRAINT [FK_cvIndustry_cvMain]
GO
ALTER TABLE [dbo].[cvIndustry]  WITH CHECK ADD  CONSTRAINT [FK_cvIndustry_dcIndustry] FOREIGN KEY([dcIndustryID])
REFERENCES [dbo].[dcIndustry] ([ID])
GO
ALTER TABLE [dbo].[cvIndustry] CHECK CONSTRAINT [FK_cvIndustry_dcIndustry]
GO
ALTER TABLE [dbo].[cvIndustryPublish]  WITH CHECK ADD  CONSTRAINT [FK_cvIndustryPublish_cvMainPublish] FOREIGN KEY([cvMainID])
REFERENCES [dbo].[cvMainPublish] ([ID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[cvIndustryPublish] CHECK CONSTRAINT [FK_cvIndustryPublish_cvMainPublish]
GO
ALTER TABLE [dbo].[cvIndustryPublish]  WITH CHECK ADD  CONSTRAINT [FK_cvIndustryPublish_dcIndustry] FOREIGN KEY([dcIndustryID])
REFERENCES [dbo].[dcIndustry] ([ID])
GO
ALTER TABLE [dbo].[cvIndustryPublish] CHECK CONSTRAINT [FK_cvIndustryPublish_dcIndustry]
GO
ALTER TABLE [dbo].[cvJobPlace]  WITH CHECK ADD  CONSTRAINT [FK_cvJobPlace_cvMain] FOREIGN KEY([cvMainID])
REFERENCES [dbo].[cvMain] ([ID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[cvJobPlace] CHECK CONSTRAINT [FK_cvJobPlace_cvMain]
GO
ALTER TABLE [dbo].[cvJobPlace]  WITH CHECK ADD  CONSTRAINT [FK_cvJobPlace_dcRegion] FOREIGN KEY([dcRegionID])
REFERENCES [dbo].[dcRegion] ([ID])
GO
ALTER TABLE [dbo].[cvJobPlace] CHECK CONSTRAINT [FK_cvJobPlace_dcRegion]
GO
ALTER TABLE [dbo].[cvJobPlacePublish]  WITH CHECK ADD  CONSTRAINT [FK_cvJobPlacePublish_cvMainPublish] FOREIGN KEY([cvMainID])
REFERENCES [dbo].[cvMainPublish] ([ID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[cvJobPlacePublish] CHECK CONSTRAINT [FK_cvJobPlacePublish_cvMainPublish]
GO
ALTER TABLE [dbo].[cvJobPlacePublish]  WITH CHECK ADD  CONSTRAINT [FK_cvJobPlacePublish_dcRegion] FOREIGN KEY([dcRegionID])
REFERENCES [dbo].[dcRegion] ([ID])
GO
ALTER TABLE [dbo].[cvJobPlacePublish] CHECK CONSTRAINT [FK_cvJobPlacePublish_dcRegion]
GO
ALTER TABLE [dbo].[cvJobType]  WITH CHECK ADD  CONSTRAINT [FK_cvJobType_cvMain] FOREIGN KEY([cvMainID])
REFERENCES [dbo].[cvMain] ([ID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[cvJobType] CHECK CONSTRAINT [FK_cvJobType_cvMain]
GO
ALTER TABLE [dbo].[cvJobType]  WITH CHECK ADD  CONSTRAINT [FK_cvJobType_dcJobType] FOREIGN KEY([dcJobTypeID])
REFERENCES [dbo].[dcJobType] ([ID])
GO
ALTER TABLE [dbo].[cvJobType] CHECK CONSTRAINT [FK_cvJobType_dcJobType]
GO
ALTER TABLE [dbo].[cvJobTypePublish]  WITH CHECK ADD  CONSTRAINT [FK_cvJobTypePublish_cvMainPublish] FOREIGN KEY([cvMainID])
REFERENCES [dbo].[cvMainPublish] ([ID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[cvJobTypePublish] CHECK CONSTRAINT [FK_cvJobTypePublish_cvMainPublish]
GO
ALTER TABLE [dbo].[cvJobTypePublish]  WITH CHECK ADD  CONSTRAINT [FK_cvJobTypePublish_dcJobType] FOREIGN KEY([dcJobTypeID])
REFERENCES [dbo].[dcJobType] ([ID])
GO
ALTER TABLE [dbo].[cvJobTypePublish] CHECK CONSTRAINT [FK_cvJobTypePublish_dcJobType]
GO
ALTER TABLE [dbo].[cvLanguage]  WITH CHECK ADD  CONSTRAINT [FK_cvLanguage_cvMain] FOREIGN KEY([cvMainID])
REFERENCES [dbo].[cvMain] ([ID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[cvLanguage] CHECK CONSTRAINT [FK_cvLanguage_cvMain]
GO
ALTER TABLE [dbo].[cvLanguagePublish]  WITH CHECK ADD  CONSTRAINT [FK_cvLanguagePublish_cvMainPublish] FOREIGN KEY([cvMainID])
REFERENCES [dbo].[cvMainPublish] ([ID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[cvLanguagePublish] CHECK CONSTRAINT [FK_cvLanguagePublish_cvMainPublish]
GO
ALTER TABLE [dbo].[cvMain]  WITH CHECK ADD  CONSTRAINT [FK_cvMain_paMain] FOREIGN KEY([paMainID])
REFERENCES [dbo].[paMain] ([ID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[cvMain] CHECK CONSTRAINT [FK_cvMain_paMain]
GO
ALTER TABLE [dbo].[cvMainPublish]  WITH CHECK ADD  CONSTRAINT [FK_cvMainPublish_paMainPublish] FOREIGN KEY([paMainID])
REFERENCES [dbo].[paMainPublish] ([ID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[cvMainPublish] CHECK CONSTRAINT [FK_cvMainPublish_paMainPublish]
GO
ALTER TABLE [dbo].[cvProject]  WITH CHECK ADD  CONSTRAINT [FK_cvProject_cvMain] FOREIGN KEY([cvMainID])
REFERENCES [dbo].[cvMain] ([ID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[cvProject] CHECK CONSTRAINT [FK_cvProject_cvMain]
GO
ALTER TABLE [dbo].[cvProjectPublish]  WITH CHECK ADD  CONSTRAINT [FK_cvProjectPublish_cvMainPublish] FOREIGN KEY([cvMainID])
REFERENCES [dbo].[cvMainPublish] ([ID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[cvProjectPublish] CHECK CONSTRAINT [FK_cvProjectPublish_cvMainPublish]
GO
ALTER TABLE [dbo].[cvTraining]  WITH NOCHECK ADD  CONSTRAINT [FK_cvTraining_cvMain] FOREIGN KEY([cvMainID])
REFERENCES [dbo].[cvMain] ([ID])
ON DELETE CASCADE
NOT FOR REPLICATION 
GO
ALTER TABLE [dbo].[cvTraining] CHECK CONSTRAINT [FK_cvTraining_cvMain]
GO
ALTER TABLE [dbo].[cvTrainingPublish]  WITH CHECK ADD  CONSTRAINT [FK_cvTrainingPublish_cvMainPublish] FOREIGN KEY([cvMainID])
REFERENCES [dbo].[cvMainPublish] ([ID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[cvTrainingPublish] CHECK CONSTRAINT [FK_cvTrainingPublish_cvMainPublish]
GO
ALTER TABLE [dbo].[Datereport]  WITH CHECK ADD  CONSTRAINT [FK_Datereport_dcSubSite] FOREIGN KEY([Province_Id])
REFERENCES [dbo].[dcSubSite] ([ID])
GO
ALTER TABLE [dbo].[Datereport] CHECK CONSTRAINT [FK_Datereport_dcSubSite]
GO
ALTER TABLE [dbo].[dcBusinessCircle]  WITH CHECK ADD  CONSTRAINT [FK_dcBusinessCircle_dcRegion] FOREIGN KEY([dcRegionId])
REFERENCES [dbo].[dcRegion] ([ID])
GO
ALTER TABLE [dbo].[dcBusinessCircle] CHECK CONSTRAINT [FK_dcBusinessCircle_dcRegion]
GO
ALTER TABLE [dbo].[dcFeeDetail]  WITH CHECK ADD  CONSTRAINT [FK_dcFeeDetail_dcFee] FOREIGN KEY([dcFeeID])
REFERENCES [dbo].[dcFee] ([ID])
ON UPDATE CASCADE
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[dcFeeDetail] CHECK CONSTRAINT [FK_dcFeeDetail_dcFee]
GO
ALTER TABLE [dbo].[dcIndustryCategory]  WITH CHECK ADD  CONSTRAINT [FK_dcIndustryCategory_dcIndustry] FOREIGN KEY([dcIndustryId])
REFERENCES [dbo].[dcIndustry] ([ID])
GO
ALTER TABLE [dbo].[dcIndustryCategory] CHECK CONSTRAINT [FK_dcIndustryCategory_dcIndustry]
GO
ALTER TABLE [dbo].[dcJobType]  WITH CHECK ADD  CONSTRAINT [FK_dcJobType_dcJobType] FOREIGN KEY([ParentID])
REFERENCES [dbo].[dcJobType] ([ID])
GO
ALTER TABLE [dbo].[dcJobType] CHECK CONSTRAINT [FK_dcJobType_dcJobType]
GO
ALTER TABLE [dbo].[dcMajor]  WITH CHECK ADD  CONSTRAINT [FK_dcMajor_dcMajorCategory] FOREIGN KEY([MajorCategoryID])
REFERENCES [dbo].[dcMajorCategory] ([ID])
GO
ALTER TABLE [dbo].[dcMajor] CHECK CONSTRAINT [FK_dcMajor_dcMajorCategory]
GO
ALTER TABLE [dbo].[dcPayMethodProvince]  WITH CHECK ADD  CONSTRAINT [FK_dcPayMethodProvince_dcPayMethodProvince] FOREIGN KEY([PayMethodID])
REFERENCES [dbo].[dcPayMethod] ([PayMethodID])
GO
ALTER TABLE [dbo].[dcPayMethodProvince] CHECK CONSTRAINT [FK_dcPayMethodProvince_dcPayMethodProvince]
GO
ALTER TABLE [dbo].[dcRegion]  WITH CHECK ADD  CONSTRAINT [FK_dcRegion_dcRegion] FOREIGN KEY([ParentID])
REFERENCES [dbo].[dcRegion] ([ID])
GO
ALTER TABLE [dbo].[dcRegion] CHECK CONSTRAINT [FK_dcRegion_dcRegion]
GO
ALTER TABLE [dbo].[dcVip]  WITH CHECK ADD  CONSTRAINT [FK_ManagerUser_dcVip] FOREIGN KEY([ManagerUserID])
REFERENCES [dbo].[ManagerUser] ([id])
GO
ALTER TABLE [dbo].[dcVip] CHECK CONSTRAINT [FK_ManagerUser_dcVip]
GO
ALTER TABLE [dbo].[dcVipDetail]  WITH CHECK ADD  CONSTRAINT [FK_dcVipDetail_dcVip] FOREIGN KEY([dcVipID])
REFERENCES [dbo].[dcVip] ([ID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[dcVipDetail] CHECK CONSTRAINT [FK_dcVipDetail_dcVip]
GO
ALTER TABLE [dbo].[dwnclass2]  WITH CHECK ADD  CONSTRAINT [FK_dwnclass2_dwnclass1] FOREIGN KEY([class1id])
REFERENCES [dbo].[dwnclass1] ([id])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[dwnclass2] CHECK CONSTRAINT [FK_dwnclass2_dwnclass1]
GO
ALTER TABLE [dbo].[dwndoc]  WITH CHECK ADD  CONSTRAINT [FK_dwndoc_dwnclass2] FOREIGN KEY([classid])
REFERENCES [dbo].[dwnclass2] ([id])
GO
ALTER TABLE [dbo].[dwndoc] CHECK CONSTRAINT [FK_dwndoc_dwnclass2]
GO
ALTER TABLE [dbo].[Email_SentTest_Log]  WITH CHECK ADD  CONSTRAINT [FK_email_senttest_log_email_senttest] FOREIGN KEY([email_senttest_id])
REFERENCES [dbo].[Email_SentTest] ([id])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[Email_SentTest_Log] CHECK CONSTRAINT [FK_email_senttest_log_email_senttest]
GO
ALTER TABLE [dbo].[EmailDomain]  WITH CHECK ADD  CONSTRAINT [FK_EmailDomain_dcProvince] FOREIGN KEY([province_id])
REFERENCES [dbo].[dcProvince] ([ID])
GO
ALTER TABLE [dbo].[EmailDomain] CHECK CONSTRAINT [FK_EmailDomain_dcProvince]
GO
ALTER TABLE [dbo].[EmailTitleold]  WITH CHECK ADD  CONSTRAINT [FK_EmailTitle_dcProvince] FOREIGN KEY([province_id])
REFERENCES [dbo].[dcProvince] ([ID])
GO
ALTER TABLE [dbo].[EmailTitleold] CHECK CONSTRAINT [FK_EmailTitle_dcProvince]
GO
ALTER TABLE [dbo].[exInterview]  WITH CHECK ADD  CONSTRAINT [FK_exInterview_cvMain] FOREIGN KEY([cvMainID])
REFERENCES [dbo].[cvMain] ([ID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[exInterview] CHECK CONSTRAINT [FK_exInterview_cvMain]
GO
ALTER TABLE [dbo].[exInterview]  WITH CHECK ADD  CONSTRAINT [FK_exInterview_Job] FOREIGN KEY([JobID])
REFERENCES [dbo].[Job] ([ID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[exInterview] CHECK CONSTRAINT [FK_exInterview_Job]
GO
ALTER TABLE [dbo].[exJobApply]  WITH CHECK ADD  CONSTRAINT [FK_exJobApply_cvMain] FOREIGN KEY([cvMainID])
REFERENCES [dbo].[cvMain] ([ID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[exJobApply] CHECK CONSTRAINT [FK_exJobApply_cvMain]
GO
ALTER TABLE [dbo].[exMessageC2P]  WITH CHECK ADD  CONSTRAINT [FK_exMessageC2P_caMain] FOREIGN KEY([caMainID])
REFERENCES [dbo].[caMain] ([ID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[exMessageC2P] CHECK CONSTRAINT [FK_exMessageC2P_caMain]
GO
ALTER TABLE [dbo].[exMessageC2P]  WITH CHECK ADD  CONSTRAINT [FK_exMessageC2P_cvMain] FOREIGN KEY([cvMainID])
REFERENCES [dbo].[cvMain] ([ID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[exMessageC2P] CHECK CONSTRAINT [FK_exMessageC2P_cvMain]
GO
ALTER TABLE [dbo].[exMessageP2C]  WITH CHECK ADD  CONSTRAINT [FK_exMessageP2C_caMain] FOREIGN KEY([caMainID])
REFERENCES [dbo].[caMain] ([ID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[exMessageP2C] CHECK CONSTRAINT [FK_exMessageP2C_caMain]
GO
ALTER TABLE [dbo].[exMessageP2C]  WITH CHECK ADD  CONSTRAINT [FK_exMessageP2C_cvMain] FOREIGN KEY([cvMainID])
REFERENCES [dbo].[cvMain] ([ID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[exMessageP2C] CHECK CONSTRAINT [FK_exMessageP2C_cvMain]
GO
ALTER TABLE [dbo].[Feedback_NoReg]  WITH CHECK ADD  CONSTRAINT [FK_feedback_noreg_dcProvince] FOREIGN KEY([Province_Id])
REFERENCES [dbo].[dcProvince] ([ID])
GO
ALTER TABLE [dbo].[Feedback_NoReg] CHECK CONSTRAINT [FK_feedback_noreg_dcProvince]
GO
ALTER TABLE [dbo].[FeeLog]  WITH CHECK ADD  CONSTRAINT [FK_feelog_cpMain] FOREIGN KEY([Company_Id])
REFERENCES [dbo].[cpMain] ([ID])
GO
ALTER TABLE [dbo].[FeeLog] CHECK CONSTRAINT [FK_feelog_cpMain]
GO
ALTER TABLE [dbo].[FlowChart]  WITH CHECK ADD  CONSTRAINT [FK_FlowChart_ManagerUser] FOREIGN KEY([ManagerUserId])
REFERENCES [dbo].[ManagerUser] ([id])
GO
ALTER TABLE [dbo].[FlowChart] CHECK CONSTRAINT [FK_FlowChart_ManagerUser]
GO
ALTER TABLE [dbo].[FnInvoice]  WITH CHECK ADD  CONSTRAINT [FK_FnInvoice_caOrder] FOREIGN KEY([OrderId])
REFERENCES [dbo].[caOrder] ([ID])
GO
ALTER TABLE [dbo].[FnInvoice] CHECK CONSTRAINT [FK_FnInvoice_caOrder]
GO
ALTER TABLE [dbo].[FnLetter]  WITH CHECK ADD  CONSTRAINT [FK_FnLetter_FnInvoice] FOREIGN KEY([FnInvoiceID])
REFERENCES [dbo].[FnInvoice] ([Id])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[FnLetter] CHECK CONSTRAINT [FK_FnLetter_FnInvoice]
GO
ALTER TABLE [dbo].[group_ManagerUser]  WITH CHECK ADD  CONSTRAINT [FK_group_ManagerUser_group_ManagerUser_group_Id] FOREIGN KEY([Group_Id])
REFERENCES [dbo].[GroupM] ([Id])
GO
ALTER TABLE [dbo].[group_ManagerUser] CHECK CONSTRAINT [FK_group_ManagerUser_group_ManagerUser_group_Id]
GO
ALTER TABLE [dbo].[group_ManagerUser]  WITH CHECK ADD  CONSTRAINT [FK_group_ManagerUser_group_ManagerUser_ManagerUser_Id] FOREIGN KEY([ManagerUser_Id])
REFERENCES [dbo].[ManagerUser] ([id])
GO
ALTER TABLE [dbo].[group_ManagerUser] CHECK CONSTRAINT [FK_group_ManagerUser_group_ManagerUser_ManagerUser_Id]
GO
ALTER TABLE [dbo].[group_province]  WITH CHECK ADD  CONSTRAINT [FK_group_province_dcProvince] FOREIGN KEY([Province_Id])
REFERENCES [dbo].[dcProvince] ([ID])
GO
ALTER TABLE [dbo].[group_province] CHECK CONSTRAINT [FK_group_province_dcProvince]
GO
ALTER TABLE [dbo].[group_province]  WITH CHECK ADD  CONSTRAINT [FK_group_province_group_province_group_Id] FOREIGN KEY([Group_Id])
REFERENCES [dbo].[GroupM] ([Id])
GO
ALTER TABLE [dbo].[group_province] CHECK CONSTRAINT [FK_group_province_group_province_group_Id]
GO
ALTER TABLE [dbo].[infoEmailAnalyze]  WITH CHECK ADD  CONSTRAINT [FK_infoEmailAnalyze_EmailType] FOREIGN KEY([EmailType_Id])
REFERENCES [dbo].[EmailType] ([id])
GO
ALTER TABLE [dbo].[infoEmailAnalyze] CHECK CONSTRAINT [FK_infoEmailAnalyze_EmailType]
GO
ALTER TABLE [dbo].[infoEmailAnalyze]  WITH CHECK ADD  CONSTRAINT [FK_infoEmailAnalyze_ManagerUser] FOREIGN KEY([InfoManager_Id])
REFERENCES [dbo].[ManagerUser] ([id])
GO
ALTER TABLE [dbo].[infoEmailAnalyze] CHECK CONSTRAINT [FK_infoEmailAnalyze_ManagerUser]
GO
ALTER TABLE [dbo].[innerer_count_keywords]  WITH CHECK ADD  CONSTRAINT [FK_innerer_count_keywords_innerer_countNew] FOREIGN KEY([Referer_count_Id])
REFERENCES [dbo].[innerer_countNew] ([Id])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[innerer_count_keywords] CHECK CONSTRAINT [FK_innerer_count_keywords_innerer_countNew]
GO
ALTER TABLE [dbo].[Institution]  WITH CHECK ADD  CONSTRAINT [FK_Institution_ManagerUser] FOREIGN KEY([ManagerUserId])
REFERENCES [dbo].[ManagerUser] ([id])
GO
ALTER TABLE [dbo].[Institution] CHECK CONSTRAINT [FK_Institution_ManagerUser]
GO
ALTER TABLE [dbo].[Investigation]  WITH CHECK ADD  CONSTRAINT [FK_Investigation_manageruser] FOREIGN KEY([AddMan])
REFERENCES [dbo].[ManagerUser] ([id])
GO
ALTER TABLE [dbo].[Investigation] CHECK CONSTRAINT [FK_Investigation_manageruser]
GO
ALTER TABLE [dbo].[ivgt_answer]  WITH CHECK ADD  CONSTRAINT [FK_ivgt_answer_ivgt_question] FOREIGN KEY([QuestionId])
REFERENCES [dbo].[ivgt_question] ([Id])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[ivgt_answer] CHECK CONSTRAINT [FK_ivgt_answer_ivgt_question]
GO
ALTER TABLE [dbo].[ivgt_answerText]  WITH CHECK ADD  CONSTRAINT [FK_ivgt_answerText_ivgt_answer] FOREIGN KEY([answerId])
REFERENCES [dbo].[ivgt_answer] ([Id])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[ivgt_answerText] CHECK CONSTRAINT [FK_ivgt_answerText_ivgt_answer]
GO
ALTER TABLE [dbo].[ivgt_question]  WITH CHECK ADD  CONSTRAINT [FK_ivgt_question_ivgt_investigation] FOREIGN KEY([InvestId])
REFERENCES [dbo].[ivgt_investigation] ([Id])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[ivgt_question] CHECK CONSTRAINT [FK_ivgt_question_ivgt_investigation]
GO
ALTER TABLE [dbo].[Job]  WITH CHECK ADD  CONSTRAINT [FK_Job_cpMain] FOREIGN KEY([cpMainID])
REFERENCES [dbo].[cpMain] ([ID])
GO
ALTER TABLE [dbo].[Job] CHECK CONSTRAINT [FK_Job_cpMain]
GO
ALTER TABLE [dbo].[Job]  WITH CHECK ADD  CONSTRAINT [FK_Job_dcJobType] FOREIGN KEY([dcJobTypeID])
REFERENCES [dbo].[dcJobType] ([ID])
GO
ALTER TABLE [dbo].[Job] CHECK CONSTRAINT [FK_Job_dcJobType]
GO
ALTER TABLE [dbo].[JobPublish]  WITH CHECK ADD  CONSTRAINT [FK_JobPublish_cpMainPublish] FOREIGN KEY([cpMainID])
REFERENCES [dbo].[cpMainPublish] ([ID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[JobPublish] CHECK CONSTRAINT [FK_JobPublish_cpMainPublish]
GO
ALTER TABLE [dbo].[JobTemplate]  WITH CHECK ADD  CONSTRAINT [FK_JobTemplate_caMain] FOREIGN KEY([caMainId])
REFERENCES [dbo].[caMain] ([ID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[JobTemplate] CHECK CONSTRAINT [FK_JobTemplate_caMain]
GO
ALTER TABLE [dbo].[JobTemplate]  WITH CHECK ADD  CONSTRAINT [FK_JobTemplate_cpMain] FOREIGN KEY([cpMainId])
REFERENCES [dbo].[cpMain] ([ID])
GO
ALTER TABLE [dbo].[JobTemplate] CHECK CONSTRAINT [FK_JobTemplate_cpMain]
GO
ALTER TABLE [dbo].[JobTemplate]  WITH CHECK ADD  CONSTRAINT [FK_JobTemplate_dcRegion] FOREIGN KEY([dcRegionId])
REFERENCES [dbo].[dcRegion] ([ID])
GO
ALTER TABLE [dbo].[JobTemplate] CHECK CONSTRAINT [FK_JobTemplate_dcRegion]
GO
ALTER TABLE [dbo].[JobTemplate]  WITH CHECK ADD  CONSTRAINT [FK_JobTemplate_dcSalary] FOREIGN KEY([dcSalaryId])
REFERENCES [dbo].[dcSalary] ([ID])
GO
ALTER TABLE [dbo].[JobTemplate] CHECK CONSTRAINT [FK_JobTemplate_dcSalary]
GO
ALTER TABLE [dbo].[knowledge]  WITH CHECK ADD  CONSTRAINT [FK_knowledge_ManagerUser] FOREIGN KEY([ManagerUserId])
REFERENCES [dbo].[ManagerUser] ([id])
GO
ALTER TABLE [dbo].[knowledge] CHECK CONSTRAINT [FK_knowledge_ManagerUser]
GO
ALTER TABLE [dbo].[KPI_EC]  WITH CHECK ADD  CONSTRAINT [FK_KPI_EC_ManagerUser1] FOREIGN KEY([Sender])
REFERENCES [dbo].[ManagerUser] ([id])
GO
ALTER TABLE [dbo].[KPI_EC] CHECK CONSTRAINT [FK_KPI_EC_ManagerUser1]
GO
ALTER TABLE [dbo].[KPI_EC]  WITH CHECK ADD  CONSTRAINT [FK_KPI_EC_ManagerUser2] FOREIGN KEY([Receiver])
REFERENCES [dbo].[ManagerUser] ([id])
GO
ALTER TABLE [dbo].[KPI_EC] CHECK CONSTRAINT [FK_KPI_EC_ManagerUser2]
GO
ALTER TABLE [dbo].[KPI_IE]  WITH CHECK ADD  CONSTRAINT [FK_KPI_IE_ManagerUser1] FOREIGN KEY([Receiver])
REFERENCES [dbo].[ManagerUser] ([id])
GO
ALTER TABLE [dbo].[KPI_IE] CHECK CONSTRAINT [FK_KPI_IE_ManagerUser1]
GO
ALTER TABLE [dbo].[KPI_IE]  WITH CHECK ADD  CONSTRAINT [FK_KPI_IE_ManagerUser2] FOREIGN KEY([Sender])
REFERENCES [dbo].[ManagerUser] ([id])
GO
ALTER TABLE [dbo].[KPI_IE] CHECK CONSTRAINT [FK_KPI_IE_ManagerUser2]
GO
ALTER TABLE [dbo].[KPI_KM]  WITH CHECK ADD  CONSTRAINT [FK_KPI_KM_ManagerUser_receiver] FOREIGN KEY([Receiver])
REFERENCES [dbo].[ManagerUser] ([id])
GO
ALTER TABLE [dbo].[KPI_KM] CHECK CONSTRAINT [FK_KPI_KM_ManagerUser_receiver]
GO
ALTER TABLE [dbo].[KPI_KM]  WITH CHECK ADD  CONSTRAINT [FK_KPI_KM_ManagerUser_sender] FOREIGN KEY([Sender])
REFERENCES [dbo].[ManagerUser] ([id])
GO
ALTER TABLE [dbo].[KPI_KM] CHECK CONSTRAINT [FK_KPI_KM_ManagerUser_sender]
GO
ALTER TABLE [dbo].[KPI_LP]  WITH CHECK ADD  CONSTRAINT [FK_KPI_LP_ManagerUser_receiver] FOREIGN KEY([Receiver])
REFERENCES [dbo].[ManagerUser] ([id])
GO
ALTER TABLE [dbo].[KPI_LP] CHECK CONSTRAINT [FK_KPI_LP_ManagerUser_receiver]
GO
ALTER TABLE [dbo].[KPI_LP]  WITH CHECK ADD  CONSTRAINT [FK_KPI_LP_ManagerUser_sender] FOREIGN KEY([Sender])
REFERENCES [dbo].[ManagerUser] ([id])
GO
ALTER TABLE [dbo].[KPI_LP] CHECK CONSTRAINT [FK_KPI_LP_ManagerUser_sender]
GO
ALTER TABLE [dbo].[KPI_OC]  WITH CHECK ADD  CONSTRAINT [FK_KPI_OC_ManagerUser] FOREIGN KEY([ManagerUserId])
REFERENCES [dbo].[ManagerUser] ([id])
GO
ALTER TABLE [dbo].[KPI_OC] CHECK CONSTRAINT [FK_KPI_OC_ManagerUser]
GO
ALTER TABLE [dbo].[KPI_SA]  WITH CHECK ADD  CONSTRAINT [FK_KPI_SA_ManagerUser] FOREIGN KEY([ManagerUserId])
REFERENCES [dbo].[ManagerUser] ([id])
GO
ALTER TABLE [dbo].[KPI_SA] CHECK CONSTRAINT [FK_KPI_SA_ManagerUser]
GO
ALTER TABLE [dbo].[Link]  WITH CHECK ADD  CONSTRAINT [FK_Link_ManagerUser] FOREIGN KEY([ManagerUserId])
REFERENCES [dbo].[ManagerUser] ([id])
GO
ALTER TABLE [dbo].[Link] CHECK CONSTRAINT [FK_Link_ManagerUser]
GO
ALTER TABLE [dbo].[linkclick]  WITH CHECK ADD  CONSTRAINT [FK_linkclick_link] FOREIGN KEY([Link_Id])
REFERENCES [dbo].[Link] ([Id])
GO
ALTER TABLE [dbo].[linkclick] CHECK CONSTRAINT [FK_linkclick_link]
GO
ALTER TABLE [dbo].[ManagerLog]  WITH CHECK ADD  CONSTRAINT [FK_ManagerLog_Manageruser] FOREIGN KEY([ManagerId])
REFERENCES [dbo].[ManagerUser] ([id])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[ManagerLog] CHECK CONSTRAINT [FK_ManagerLog_Manageruser]
GO
ALTER TABLE [dbo].[ManagerUser]  WITH CHECK ADD  CONSTRAINT [FK_ManagerUser_Dept] FOREIGN KEY([deptid])
REFERENCES [dbo].[Dept] ([Id])
GO
ALTER TABLE [dbo].[ManagerUser] CHECK CONSTRAINT [FK_ManagerUser_Dept]
GO
ALTER TABLE [dbo].[ManagerUser]  WITH CHECK ADD  CONSTRAINT [FK_manageruser_HRKpiPost] FOREIGN KEY([HRKpiPostId])
REFERENCES [dbo].[HRKpiPost] ([Id])
GO
ALTER TABLE [dbo].[ManagerUser] CHECK CONSTRAINT [FK_manageruser_HRKpiPost]
GO
ALTER TABLE [dbo].[ManagerUser]  WITH CHECK ADD  CONSTRAINT [FK_ManagerUser_ManagerUser] FOREIGN KEY([superior])
REFERENCES [dbo].[ManagerUser] ([id])
GO
ALTER TABLE [dbo].[ManagerUser] CHECK CONSTRAINT [FK_ManagerUser_ManagerUser]
GO
ALTER TABLE [dbo].[ManagerUser]  WITH CHECK ADD  CONSTRAINT [FK_ManagerUser_role] FOREIGN KEY([roleid])
REFERENCES [dbo].[Role] ([id])
GO
ALTER TABLE [dbo].[ManagerUser] CHECK CONSTRAINT [FK_ManagerUser_role]
GO
ALTER TABLE [dbo].[msEmailTitle]  WITH CHECK ADD  CONSTRAINT [FK_msEmailTitle_msEmailTemplete] FOREIGN KEY([msBodyTempleteId])
REFERENCES [dbo].[msEmailTemplete] ([ID])
GO
ALTER TABLE [dbo].[msEmailTitle] CHECK CONSTRAINT [FK_msEmailTitle_msEmailTemplete]
GO
ALTER TABLE [dbo].[msEmailType]  WITH CHECK ADD  CONSTRAINT [FK_msEmailType_msEmailTemplete] FOREIGN KEY([msEmailTempleteId])
REFERENCES [dbo].[msEmailTemplete] ([ID])
GO
ALTER TABLE [dbo].[msEmailType] CHECK CONSTRAINT [FK_msEmailType_msEmailTemplete]
GO
ALTER TABLE [dbo].[msEmailType]  WITH CHECK ADD  CONSTRAINT [FK_msEmailType_msSql] FOREIGN KEY([msSqlId])
REFERENCES [dbo].[msSql] ([ID])
GO
ALTER TABLE [dbo].[msEmailType] CHECK CONSTRAINT [FK_msEmailType_msSql]
GO
ALTER TABLE [dbo].[msProcess]  WITH CHECK ADD  CONSTRAINT [FK_msProcess_msEmailType] FOREIGN KEY([msEmailTypeId])
REFERENCES [dbo].[msEmailType] ([ID])
GO
ALTER TABLE [dbo].[msProcess] CHECK CONSTRAINT [FK_msProcess_msEmailType]
GO
ALTER TABLE [dbo].[msProcessEdit]  WITH CHECK ADD  CONSTRAINT [FK_msProcessEdit_msEmailType] FOREIGN KEY([msEmailTypeId])
REFERENCES [dbo].[msEmailType] ([ID])
GO
ALTER TABLE [dbo].[msProcessEdit] CHECK CONSTRAINT [FK_msProcessEdit_msEmailType]
GO
ALTER TABLE [dbo].[msProcessLog]  WITH CHECK ADD  CONSTRAINT [FK_msProcessLog_msProcess] FOREIGN KEY([msProcessId])
REFERENCES [dbo].[msProcess] ([ID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[msProcessLog] CHECK CONSTRAINT [FK_msProcessLog_msProcess]
GO
ALTER TABLE [dbo].[MT_plan]  WITH CHECK ADD  CONSTRAINT [FK_MT_plan_MT] FOREIGN KEY([Mt_Id])
REFERENCES [dbo].[MT] ([Id])
GO
ALTER TABLE [dbo].[MT_plan] CHECK CONSTRAINT [FK_MT_plan_MT]
GO
ALTER TABLE [dbo].[OutLink]  WITH CHECK ADD  CONSTRAINT [FK_OutLink_ManagerUser] FOREIGN KEY([ManagerUserId])
REFERENCES [dbo].[ManagerUser] ([id])
GO
ALTER TABLE [dbo].[OutLink] CHECK CONSTRAINT [FK_OutLink_ManagerUser]
GO
ALTER TABLE [dbo].[OutLink]  WITH CHECK ADD  CONSTRAINT [FK_OutLink_OutlinkResources] FOREIGN KEY([OutLinkResources_Id])
REFERENCES [dbo].[OutlinkResources] ([Id])
GO
ALTER TABLE [dbo].[OutLink] CHECK CONSTRAINT [FK_OutLink_OutlinkResources]
GO
ALTER TABLE [dbo].[outlink_count]  WITH CHECK ADD  CONSTRAINT [FK_outlink_count_outlink] FOREIGN KEY([outlinkId])
REFERENCES [dbo].[OutLink] ([Id])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[outlink_count] CHECK CONSTRAINT [FK_outlink_count_outlink]
GO
ALTER TABLE [dbo].[paCoverLetter]  WITH CHECK ADD  CONSTRAINT [FK_paCoverLetter_paMain] FOREIGN KEY([paMainID])
REFERENCES [dbo].[paMain] ([ID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[paCoverLetter] CHECK CONSTRAINT [FK_paCoverLetter_paMain]
GO
ALTER TABLE [dbo].[paFavorate]  WITH CHECK ADD  CONSTRAINT [FK_paFavorate_Job] FOREIGN KEY([JobID])
REFERENCES [dbo].[Job] ([ID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[paFavorate] CHECK CONSTRAINT [FK_paFavorate_Job]
GO
ALTER TABLE [dbo].[paFavorate]  WITH CHECK ADD  CONSTRAINT [FK_paFavorate_paMain] FOREIGN KEY([paMainID])
REFERENCES [dbo].[paMain] ([ID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[paFavorate] CHECK CONSTRAINT [FK_paFavorate_paMain]
GO
ALTER TABLE [dbo].[paFeedback]  WITH CHECK ADD  CONSTRAINT [FK_paFeedback_manageruser] FOREIGN KEY([ReplyMan])
REFERENCES [dbo].[ManagerUser] ([id])
GO
ALTER TABLE [dbo].[paFeedback] CHECK CONSTRAINT [FK_paFeedback_manageruser]
GO
ALTER TABLE [dbo].[paFeedback]  WITH CHECK ADD  CONSTRAINT [FK_paFeedback_paMain] FOREIGN KEY([paMainID])
REFERENCES [dbo].[paMain] ([ID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[paFeedback] CHECK CONSTRAINT [FK_paFeedback_paMain]
GO
ALTER TABLE [dbo].[paInfoEmailVerifyLog]  WITH CHECK ADD  CONSTRAINT [FK_paInfoEmailVerifyLog_ManagerUser] FOREIGN KEY([AddMan])
REFERENCES [dbo].[ManagerUser] ([id])
GO
ALTER TABLE [dbo].[paInfoEmailVerifyLog] CHECK CONSTRAINT [FK_paInfoEmailVerifyLog_ManagerUser]
GO
ALTER TABLE [dbo].[paInfoEmailVerifyLog]  WITH CHECK ADD  CONSTRAINT [FK_paInfoEmailVerifyLog_paMain] FOREIGN KEY([paMainID])
REFERENCES [dbo].[paMain] ([ID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[paInfoEmailVerifyLog] CHECK CONSTRAINT [FK_paInfoEmailVerifyLog_paMain]
GO
ALTER TABLE [dbo].[paJobClickLog]  WITH CHECK ADD  CONSTRAINT [FK_paJobClickLog_Job] FOREIGN KEY([JobID])
REFERENCES [dbo].[Job] ([ID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[paJobClickLog] CHECK CONSTRAINT [FK_paJobClickLog_Job]
GO
ALTER TABLE [dbo].[paJobFinder]  WITH CHECK ADD  CONSTRAINT [FK_paJobFinder_paMain] FOREIGN KEY([paMainID])
REFERENCES [dbo].[paMain] ([ID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[paJobFinder] CHECK CONSTRAINT [FK_paJobFinder_paMain]
GO
ALTER TABLE [dbo].[paJobViewLog]  WITH CHECK ADD  CONSTRAINT [FK_paJobViewLog_Job] FOREIGN KEY([JobID])
REFERENCES [dbo].[Job] ([ID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[paJobViewLog] CHECK CONSTRAINT [FK_paJobViewLog_Job]
GO
ALTER TABLE [dbo].[paJobViewLog]  WITH CHECK ADD  CONSTRAINT [FK_paJobViewLog_paMain] FOREIGN KEY([paMainID])
REFERENCES [dbo].[paMain] ([ID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[paJobViewLog] CHECK CONSTRAINT [FK_paJobViewLog_paMain]
GO
ALTER TABLE [dbo].[paLoginLog]  WITH CHECK ADD  CONSTRAINT [FK_paLoginLog_paMain] FOREIGN KEY([paMainID])
REFERENCES [dbo].[paMain] ([ID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[paLoginLog] CHECK CONSTRAINT [FK_paLoginLog_paMain]
GO
ALTER TABLE [dbo].[paMain]  WITH CHECK ADD  CONSTRAINT [FK_paMain_dcProvince] FOREIGN KEY([dcProvinceID])
REFERENCES [dbo].[dcProvince] ([ID])
GO
ALTER TABLE [dbo].[paMain] CHECK CONSTRAINT [FK_paMain_dcProvince]
GO
ALTER TABLE [dbo].[paMain]  WITH CHECK ADD  CONSTRAINT [FK_paMain_ManagerUser] FOREIGN KEY([AddMan])
REFERENCES [dbo].[ManagerUser] ([id])
GO
ALTER TABLE [dbo].[paMain] CHECK CONSTRAINT [FK_paMain_ManagerUser]
GO
ALTER TABLE [dbo].[paNotify]  WITH CHECK ADD  CONSTRAINT [FK_paNotify_paMain] FOREIGN KEY([paMainID])
REFERENCES [dbo].[paMain] ([ID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[paNotify] CHECK CONSTRAINT [FK_paNotify_paMain]
GO
ALTER TABLE [dbo].[paOperationLog]  WITH CHECK ADD  CONSTRAINT [FK_paOperationLog_paMain] FOREIGN KEY([paMainID])
REFERENCES [dbo].[paMain] ([ID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[paOperationLog] CHECK CONSTRAINT [FK_paOperationLog_paMain]
GO
ALTER TABLE [dbo].[paPhoto]  WITH CHECK ADD  CONSTRAINT [FK_paPhoto_paMain] FOREIGN KEY([paMainID])
REFERENCES [dbo].[paMain] ([ID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[paPhoto] CHECK CONSTRAINT [FK_paPhoto_paMain]
GO
ALTER TABLE [dbo].[paPlaint]  WITH CHECK ADD  CONSTRAINT [FK_paPlaint_Job] FOREIGN KEY([JobID])
REFERENCES [dbo].[Job] ([ID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[paPlaint] CHECK CONSTRAINT [FK_paPlaint_Job]
GO
ALTER TABLE [dbo].[PaRemindLog]  WITH CHECK ADD  CONSTRAINT [FK_PaRemindLog_PaMain] FOREIGN KEY([PaMainID])
REFERENCES [dbo].[paMain] ([ID])
ON UPDATE CASCADE
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[PaRemindLog] CHECK CONSTRAINT [FK_PaRemindLog_PaMain]
GO
ALTER TABLE [dbo].[Person_Black]  WITH CHECK ADD  CONSTRAINT [FK_Person_Black_manageruser] FOREIGN KEY([ManagerID])
REFERENCES [dbo].[ManagerUser] ([id])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[Person_Black] CHECK CONSTRAINT [FK_Person_Black_manageruser]
GO
ALTER TABLE [dbo].[Question]  WITH NOCHECK ADD  CONSTRAINT [FK_Question_Investigation] FOREIGN KEY([InvestId])
REFERENCES [dbo].[Investigation] ([Id])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[Question] CHECK CONSTRAINT [FK_Question_Investigation]
GO
ALTER TABLE [dbo].[Referer_Count_Keywords]  WITH CHECK ADD  CONSTRAINT [FK_referer_count_keywords_referer_count] FOREIGN KEY([Referer_Count_Id])
REFERENCES [dbo].[referer_count] ([Id])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[Referer_Count_Keywords] CHECK CONSTRAINT [FK_referer_count_keywords_referer_count]
GO
ALTER TABLE [dbo].[Referer_Item_Keywords]  WITH CHECK ADD  CONSTRAINT [FK_referer_item_keywords_referer_item] FOREIGN KEY([Item_Id])
REFERENCES [dbo].[Referer_Item] ([Id])
GO
ALTER TABLE [dbo].[Referer_Item_Keywords] CHECK CONSTRAINT [FK_referer_item_keywords_referer_item]
GO
ALTER TABLE [dbo].[Resume_Xinxi]  WITH CHECK ADD  CONSTRAINT [FK_resume_xinxi_manageruser] FOREIGN KEY([AddMan])
REFERENCES [dbo].[ManagerUser] ([id])
GO
ALTER TABLE [dbo].[Resume_Xinxi] CHECK CONSTRAINT [FK_resume_xinxi_manageruser]
GO
ALTER TABLE [dbo].[Role_DataSource]  WITH CHECK ADD  CONSTRAINT [FK_Role_DataSource_DataSource] FOREIGN KEY([DataSourceId])
REFERENCES [dbo].[DataSource] ([Id])
GO
ALTER TABLE [dbo].[Role_DataSource] CHECK CONSTRAINT [FK_Role_DataSource_DataSource]
GO
ALTER TABLE [dbo].[Role_DataSource]  WITH CHECK ADD  CONSTRAINT [FK_Role_DataSource_Role] FOREIGN KEY([RoleId])
REFERENCES [dbo].[Role] ([id])
GO
ALTER TABLE [dbo].[Role_DataSource] CHECK CONSTRAINT [FK_Role_DataSource_Role]
GO
ALTER TABLE [dbo].[sales_ManagerUser_Month]  WITH CHECK ADD  CONSTRAINT [FK_sales_ManagerUser_Month_ManagerUser] FOREIGN KEY([ManagerUserId])
REFERENCES [dbo].[ManagerUser] ([id])
GO
ALTER TABLE [dbo].[sales_ManagerUser_Month] CHECK CONSTRAINT [FK_sales_ManagerUser_Month_ManagerUser]
GO
ALTER TABLE [dbo].[SearchKeywordsPower]  WITH CHECK ADD  CONSTRAINT [FK_SearchKeywordsPower_searchkeywords] FOREIGN KEY([searchkeywords_Id])
REFERENCES [dbo].[searchkeywords] ([Id])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[SearchKeywordsPower] CHECK CONSTRAINT [FK_SearchKeywordsPower_searchkeywords]
GO
ALTER TABLE [dbo].[servi_log]  WITH CHECK ADD  CONSTRAINT [FK_servi_log_servi_process] FOREIGN KEY([ProcessId])
REFERENCES [dbo].[servi_process] ([Id])
GO
ALTER TABLE [dbo].[servi_log] CHECK CONSTRAINT [FK_servi_log_servi_process]
GO
ALTER TABLE [dbo].[servi_process]  WITH CHECK ADD  CONSTRAINT [FK_servi_process_servi_account] FOREIGN KEY([RtxId])
REFERENCES [dbo].[Servi_Account] ([RtxId])
GO
ALTER TABLE [dbo].[servi_process] CHECK CONSTRAINT [FK_servi_process_servi_account]
GO
ALTER TABLE [dbo].[Sow]  WITH CHECK ADD  CONSTRAINT [FK_Sow_ManagerUser] FOREIGN KEY([ManagerUserId])
REFERENCES [dbo].[ManagerUser] ([id])
GO
ALTER TABLE [dbo].[Sow] CHECK CONSTRAINT [FK_Sow_ManagerUser]
GO
ALTER TABLE [dbo].[Standard]  WITH CHECK ADD  CONSTRAINT [FK_Standard_ManagerUser] FOREIGN KEY([ManagerUserId])
REFERENCES [dbo].[ManagerUser] ([id])
GO
ALTER TABLE [dbo].[Standard] CHECK CONSTRAINT [FK_Standard_ManagerUser]
GO
ALTER TABLE [dbo].[url_click_log]  WITH CHECK ADD  CONSTRAINT [FK_url_click_log_url] FOREIGN KEY([url_Id])
REFERENCES [dbo].[Url] ([Id])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[url_click_log] CHECK CONSTRAINT [FK_url_click_log_url]
GO
ALTER TABLE [dbo].[url_Month]  WITH CHECK ADD  CONSTRAINT [FK_url_Month_url] FOREIGN KEY([url_Id])
REFERENCES [dbo].[Url] ([Id])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[url_Month] CHECK CONSTRAINT [FK_url_Month_url]
GO
ALTER TABLE [dbo].[workDate_province_ManagerUser]  WITH CHECK ADD  CONSTRAINT [FK_workDate_province_manageruser_dcProvince] FOREIGN KEY([Province_Id])
REFERENCES [dbo].[dcProvince] ([ID])
GO
ALTER TABLE [dbo].[workDate_province_ManagerUser] CHECK CONSTRAINT [FK_workDate_province_manageruser_dcProvince]
GO
ALTER TABLE [dbo].[workDate_province_ManagerUser]  WITH CHECK ADD  CONSTRAINT [FK_workDate_province_ManagerUser_manageruser] FOREIGN KEY([ManagerUser_Id])
REFERENCES [dbo].[ManagerUser] ([id])
GO
ALTER TABLE [dbo].[workDate_province_ManagerUser] CHECK CONSTRAINT [FK_workDate_province_ManagerUser_manageruser]
GO
ALTER TABLE [dbo].[workDate_province_ManagerUser]  WITH CHECK ADD  CONSTRAINT [FK_workDate_province_ManagerUser_workDate_province_ManagerUser_workDate] FOREIGN KEY([WorkDate])
REFERENCES [dbo].[workDate] ([workDate])
GO
ALTER TABLE [dbo].[workDate_province_ManagerUser] CHECK CONSTRAINT [FK_workDate_province_ManagerUser_workDate_province_ManagerUser_workDate]
GO
ALTER TABLE [dbo].[yingyelog]  WITH CHECK ADD  CONSTRAINT [FK_yingyelog_ManagerUser] FOREIGN KEY([ManagerUserId])
REFERENCES [dbo].[ManagerUser] ([id])
GO
ALTER TABLE [dbo].[yingyelog] CHECK CONSTRAINT [FK_yingyelog_ManagerUser]
GO
ALTER TABLE [dbo].[caMain]  WITH CHECK ADD  CONSTRAINT [CK_caMain_AccountType] CHECK  (([AccountType]=(2) OR [AccountType]=(1)))
GO
ALTER TABLE [dbo].[caMain] CHECK CONSTRAINT [CK_caMain_AccountType]
GO
ALTER TABLE [dbo].[cpMain]  WITH CHECK ADD  CONSTRAINT [CK_cpMain_DailyGiftQuota] CHECK  (([DailyGiftQuota]>=(2) OR [DailyGiftQuota]=(0)))
GO
ALTER TABLE [dbo].[cpMain] CHECK CONSTRAINT [CK_cpMain_DailyGiftQuota]
GO
ALTER TABLE [dbo].[cpMain]  WITH CHECK ADD  CONSTRAINT [CK_cpMain_MemberType] CHECK  (([MemberType]=(11) OR [MemberType]=(10) OR [MemberType]=(3) OR [MemberType]=(2) OR [MemberType]=(1) OR [MemberType]=(0)))
GO
ALTER TABLE [dbo].[cpMain] CHECK CONSTRAINT [CK_cpMain_MemberType]
GO
ALTER TABLE [dbo].[cpMainPublish]  WITH CHECK ADD  CONSTRAINT [CK_cpMainPublish_MemberType] CHECK  (([MemberType]=(11) OR [MemberType]=(10) OR [MemberType]=(3) OR [MemberType]=(2) OR [MemberType]=(1) OR [MemberType]=(0)))
GO
ALTER TABLE [dbo].[cpMainPublish] CHECK CONSTRAINT [CK_cpMainPublish_MemberType]
GO
ALTER TABLE [dbo].[cvAppendix]  WITH CHECK ADD  CONSTRAINT [CK_cvAppendix_AccessDate] CHECK  (([AccessDate]>(1960) AND [AccessDate]<CONVERT([varchar](4),dateadd(year,(5),getdate()),(112))))
GO
ALTER TABLE [dbo].[cvAppendix] CHECK CONSTRAINT [CK_cvAppendix_AccessDate]
GO
ALTER TABLE [dbo].[cvEducation]  WITH CHECK ADD  CONSTRAINT [CK_cvEducation_Graduation] CHECK  (([Graduation]>(195000) AND right([Graduation],(2))<(13) AND [Graduation]<CONVERT([varchar](6),dateadd(year,(10),getdate()),(112))))
GO
ALTER TABLE [dbo].[cvEducation] CHECK CONSTRAINT [CK_cvEducation_Graduation]
GO
ALTER TABLE [dbo].[cvEducationPublish]  WITH CHECK ADD  CONSTRAINT [CK_cvEducationPublish_Graduation] CHECK  (([Graduation]>(195000) AND right([Graduation],(2))<(13) AND [Graduation]<CONVERT([varchar](6),dateadd(year,(10),getdate()),(112))))
GO
ALTER TABLE [dbo].[cvEducationPublish] CHECK CONSTRAINT [CK_cvEducationPublish_Graduation]
GO
ALTER TABLE [dbo].[cvExperience]  WITH CHECK ADD  CONSTRAINT [CK_cvExperience_BeginDate] CHECK  (([begindate]>(194900) AND [begindate]<CONVERT([varchar](6),getdate()+(500),(112))))
GO
ALTER TABLE [dbo].[cvExperience] CHECK CONSTRAINT [CK_cvExperience_BeginDate]
GO
ALTER TABLE [dbo].[cvExperience]  WITH CHECK ADD  CONSTRAINT [CK_cvExperience_BeginDate_EndDate] CHECK  (([enddate]>=[begindate]))
GO
ALTER TABLE [dbo].[cvExperience] CHECK CONSTRAINT [CK_cvExperience_BeginDate_EndDate]
GO
ALTER TABLE [dbo].[cvExperience]  WITH CHECK ADD  CONSTRAINT [CK_cvExperience_EndDate] CHECK  (([EndDate]>(194900) AND [EndDate]<CONVERT([varchar](6),dateadd(year,(5),getdate()),(112)) OR [EndDate]=(999999)))
GO
ALTER TABLE [dbo].[cvExperience] CHECK CONSTRAINT [CK_cvExperience_EndDate]
GO
ALTER TABLE [dbo].[cvMain]  WITH CHECK ADD  CONSTRAINT [CK_cvMain_Valid] CHECK  (([Valid]=(3) OR [Valid]=(2) OR [Valid]=(1) OR [Valid]=(0)))
GO
ALTER TABLE [dbo].[cvMain] CHECK CONSTRAINT [CK_cvMain_Valid]
GO
ALTER TABLE [dbo].[cvMainPublish]  WITH CHECK ADD  CONSTRAINT [CK_cvMainPublish_Valid] CHECK  (([Valid]=(3) OR [Valid]=(2) OR [Valid]=(1) OR [Valid]=(0)))
GO
ALTER TABLE [dbo].[cvMainPublish] CHECK CONSTRAINT [CK_cvMainPublish_Valid]
GO
ALTER TABLE [dbo].[cvProject]  WITH CHECK ADD  CONSTRAINT [CK_cvProject_EndDate] CHECK  (([enddate]>(196000) AND [enddate]<CONVERT([varchar](6),dateadd(year,(5),getdate()),(112)) OR [enddate]=(999999)))
GO
ALTER TABLE [dbo].[cvProject] CHECK CONSTRAINT [CK_cvProject_EndDate]
GO
ALTER TABLE [dbo].[cvProject]  WITH CHECK ADD  CONSTRAINT [CK_cvProject_StartDate] CHECK  (([startdate]>(196000) AND [startdate]<=CONVERT([varchar](6),getdate(),(112))))
GO
ALTER TABLE [dbo].[cvProject] CHECK CONSTRAINT [CK_cvProject_StartDate]
GO
ALTER TABLE [dbo].[cvProject]  WITH CHECK ADD  CONSTRAINT [CK_cvProject_StartDate_EndDate] CHECK  (([startdate]<=[EndDate]))
GO
ALTER TABLE [dbo].[cvProject] CHECK CONSTRAINT [CK_cvProject_StartDate_EndDate]
GO
ALTER TABLE [dbo].[cvTraining]  WITH CHECK ADD  CONSTRAINT [CK_cvTraing_StartDate] CHECK  (([startdate]>(196000) AND [startdate]<CONVERT([varchar](6),dateadd(year,(5),getdate()),(112))))
GO
ALTER TABLE [dbo].[cvTraining] CHECK CONSTRAINT [CK_cvTraing_StartDate]
GO
ALTER TABLE [dbo].[cvTraining]  WITH CHECK ADD  CONSTRAINT [CK_cvTraing_TimeLength] CHECK  (([TimeLength]>=(1) AND [TimeLength]<=(30)))
GO
ALTER TABLE [dbo].[cvTraining] CHECK CONSTRAINT [CK_cvTraing_TimeLength]
GO
ALTER TABLE [dbo].[cvTraining]  WITH CHECK ADD  CONSTRAINT [CK_cvTraing_TimeUnit] CHECK  (([TimeUnit]=(4) OR [TimeUnit]=(3) OR [TimeUnit]=(2) OR [TimeUnit]=(1)))
GO
ALTER TABLE [dbo].[cvTraining] CHECK CONSTRAINT [CK_cvTraing_TimeUnit]
GO
ALTER TABLE [dbo].[EmailDomain]  WITH CHECK ADD  CONSTRAINT [CK_EmailDomain_province_id] CHECK  (([province_id]<>(0)))
GO
ALTER TABLE [dbo].[EmailDomain] CHECK CONSTRAINT [CK_EmailDomain_province_id]
GO
ALTER TABLE [dbo].[EmailUser]  WITH CHECK ADD  CONSTRAINT [CK_EmailUser_province_id] CHECK  (([province_id]<>(0)))
GO
ALTER TABLE [dbo].[EmailUser] CHECK CONSTRAINT [CK_EmailUser_province_id]
GO
ALTER TABLE [dbo].[Job]  WITH CHECK ADD  CONSTRAINT [CK_Job_IssueDate_IssueEnd] CHECK  (([IssueEnd]>=[IssueDate]))
GO
ALTER TABLE [dbo].[Job] CHECK CONSTRAINT [CK_Job_IssueDate_IssueEnd]
GO
ALTER TABLE [dbo].[KPI_SA]  WITH CHECK ADD  CONSTRAINT [CK_KPI_SA_a1_h] CHECK  (([a1_h]<=(5) AND [a1_h]>=(0)))
GO
ALTER TABLE [dbo].[KPI_SA] CHECK CONSTRAINT [CK_KPI_SA_a1_h]
GO
ALTER TABLE [dbo].[KPI_SA]  WITH CHECK ADD  CONSTRAINT [CK_KPI_SA_a1_s] CHECK  (([a1_s]<=(5) AND [a1_s]>=(0)))
GO
ALTER TABLE [dbo].[KPI_SA] CHECK CONSTRAINT [CK_KPI_SA_a1_s]
GO
ALTER TABLE [dbo].[KPI_SA]  WITH CHECK ADD  CONSTRAINT [CK_KPI_SA_a2_h] CHECK  (([a2_h]<=(5) AND [a2_h]>=(0)))
GO
ALTER TABLE [dbo].[KPI_SA] CHECK CONSTRAINT [CK_KPI_SA_a2_h]
GO
ALTER TABLE [dbo].[KPI_SA]  WITH CHECK ADD  CONSTRAINT [CK_KPI_SA_a2_s] CHECK  (([a2_s]<=(5) AND [a2_s]>=(0)))
GO
ALTER TABLE [dbo].[KPI_SA] CHECK CONSTRAINT [CK_KPI_SA_a2_s]
GO
ALTER TABLE [dbo].[KPI_SA]  WITH CHECK ADD  CONSTRAINT [CK_KPI_SA_b1_h] CHECK  (([b1_h]<=(5) AND [b1_h]>=(0)))
GO
ALTER TABLE [dbo].[KPI_SA] CHECK CONSTRAINT [CK_KPI_SA_b1_h]
GO
ALTER TABLE [dbo].[KPI_SA]  WITH CHECK ADD  CONSTRAINT [CK_KPI_SA_b1_s] CHECK  (([b1_s]<=(5) AND [b1_s]>=(0)))
GO
ALTER TABLE [dbo].[KPI_SA] CHECK CONSTRAINT [CK_KPI_SA_b1_s]
GO
ALTER TABLE [dbo].[KPI_SA]  WITH CHECK ADD  CONSTRAINT [CK_KPI_SA_c1_h] CHECK  (([c1_h]<=(5) AND [c1_h]>=(0)))
GO
ALTER TABLE [dbo].[KPI_SA] CHECK CONSTRAINT [CK_KPI_SA_c1_h]
GO
ALTER TABLE [dbo].[KPI_SA]  WITH CHECK ADD  CONSTRAINT [CK_KPI_SA_c1_s] CHECK  (([c1_s]<=(5) AND [c1_s]>=(0)))
GO
ALTER TABLE [dbo].[KPI_SA] CHECK CONSTRAINT [CK_KPI_SA_c1_s]
GO
ALTER TABLE [dbo].[KPI_SA]  WITH CHECK ADD  CONSTRAINT [CK_KPI_SA_d1_h] CHECK  (([d1_h]<=(5) AND [d1_h]>=(0)))
GO
ALTER TABLE [dbo].[KPI_SA] CHECK CONSTRAINT [CK_KPI_SA_d1_h]
GO
ALTER TABLE [dbo].[KPI_SA]  WITH CHECK ADD  CONSTRAINT [CK_KPI_SA_d1_s] CHECK  (([d1_s]<=(5) AND [d1_s]>=(0)))
GO
ALTER TABLE [dbo].[KPI_SA] CHECK CONSTRAINT [CK_KPI_SA_d1_s]
GO
ALTER TABLE [dbo].[KPI_SA]  WITH CHECK ADD  CONSTRAINT [CK_KPI_SA_e_1] CHECK  (([e1_s]<=(5) AND [e1_s]>=(0)))
GO
ALTER TABLE [dbo].[KPI_SA] CHECK CONSTRAINT [CK_KPI_SA_e_1]
GO
ALTER TABLE [dbo].[KPI_SA]  WITH CHECK ADD  CONSTRAINT [CK_KPI_SA_e1_h] CHECK  (([e1_h]<=(5) AND [e1_h]>=(0)))
GO
ALTER TABLE [dbo].[KPI_SA] CHECK CONSTRAINT [CK_KPI_SA_e1_h]
GO
ALTER TABLE [dbo].[ManagerUser]  WITH CHECK ADD  CONSTRAINT [CK_ManagerUser_ConsultantNum] CHECK  (([consultantnum_release]<=[consultantnum_quota]))
GO
ALTER TABLE [dbo].[ManagerUser] CHECK CONSTRAINT [CK_ManagerUser_ConsultantNum]
GO
ALTER TABLE [dbo].[paMain]  WITH CHECK ADD  CONSTRAINT [CK_paMain_BirthDay] CHECK  (([BirthDay]>=(193001) AND [BirthDay]<CONVERT([varchar](6),dateadd(year,(-12),getdate()),(112))))
GO
ALTER TABLE [dbo].[paMain] CHECK CONSTRAINT [CK_paMain_BirthDay]
GO
ALTER TABLE [dbo].[paMain]  WITH CHECK ADD  CONSTRAINT [CK_paMain_HasPhoto] CHECK  ((isnull([HasPhoto],(0))=(3) OR isnull([HasPhoto],(0))=(2) OR isnull([HasPhoto],(0))=(1) OR isnull([HasPhoto],(0))=(0)))
GO
ALTER TABLE [dbo].[paMain] CHECK CONSTRAINT [CK_paMain_HasPhoto]
GO
ALTER TABLE [dbo].[paMainPublish]  WITH CHECK ADD  CONSTRAINT [CK_paMainPublish_BirthDay] CHECK  (([BirthDay]>=(193001) AND [BirthDay]<CONVERT([varchar](6),dateadd(year,(-12),getdate()),(112))))
GO
ALTER TABLE [dbo].[paMainPublish] CHECK CONSTRAINT [CK_paMainPublish_BirthDay]
GO
/****** Object:  StoredProcedure [dbo].[__bsSchMailPrevJobResumeCreate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[__bsSchMailPrevJobResumeCreate]
AS
return
BEGIN
	SET NOCOUNT ON
	IF ISNULL((SELECT TOP 1 CONVERT(VARCHAR(8), AddDate, 112) FROM schMailPrev), '') <> CONVERT(VARCHAR(8), GETDATE(), 112)
	BEGIN
		TRUNCATE TABLE schMailPrev
		TRUNCATE TABLE schMailPrevJobResume
		INSERT INTO schMailPrev
		SELECT 1,a.dcProvinceID,a.ID,a.name,c.username,b.ID,a.name+'，您的职位['+b.name+']订阅简历',b.emailsendnumber,
			CASE LEN(a.dcsubsiteid) WHEN 2 THEN '' ELSE d.emailsite END,c.email,d.SubSiteName,NULL,0,GETDATE(),
			dbo.AgeToBirth(b.MaxAge), dbo.AgeToBirth(CASE b.MinAge WHEN 99 THEN 16 ELSE b.MinAge END), 
			b.dcJobTypeID, LEFT(b.dcRegionId, 4), b.Name, GETDATE()
		FROM job b WITH(NOLOCK), cpmain a WITH(NOLOCK), camain c WITH(NOLOCK), dcSubSite d WITH(NOLOCK)
		WHERE d.ID=a.dcSubSiteID AND b.cpmainid=a.id AND b.camainid=c.id AND c.cpmainid=a.id 
			AND b.emailsendfreq>0 AND b.valid=1 AND (b.LastEmailDate IS NULL OR datediff(d,b.LastEmailDate,getdate()+1)>=b.emailsendfreq) 
			AND a.islimitlogin<9 AND a.isdelete=0 AND b.emailsendnumber > 0 AND c.email IS NOT NULL AND a.LastLoginDate > GETDATE()-182
		ORDER BY b.adddate DESC
		--sean 2012.1.23 应推广部要求暂停发送qq邮件
		DELETE schMailPrev WHERE Email LIKE '%qq.com'
	END

	--IF DATEADD(Mi, 2, (SELECT MAX(RefreshDate) FROM SchMailPrev)) > GETDATE()
	--	RETURN

	DECLARE @Rows AS INT, @i AS INT, @R AS INT, @Content AS VARCHAR(MAX), @MinID AS INT, @JobId AS INT
	DECLARE @t AS TABLE(ID INT, ResumeID INT, JobId INT)
	SELECT @Rows = COUNT(*), @MinID = MIN(ID), @I=0 FROM schMailPrev WITH(NOLOCK) WHERE MailBody IS NULL

	IF @Rows = 0
		RETURN

	WHILE @i < @Rows
	BEGIN
		SELECT @r = emailnumber from schMailPrev where id = @i + @MinID
		INSERT INTO @t
		SELECT TOP (@r) c.ID,a.ResumeID, c.SubID
		FROM caJobResumePre a WITH(NOLOCK),caJobResumePreJobType b WITH(NOLOCK), schMailPrev c WITH(NOLOCK)
		WHERE a.BirthDay >= c.MaxAge AND a.BirthDay <= c.MinAge
		AND a.AtPlace LIKE c.dcRegionId + '%'
		AND a.ResumeId NOT IN(SELECT ResumeID FROM ResumeSubscription WITH(NOLOCK) WHERE JobID = c.SubID)
		AND a.ResumeID = b.cvMainId 
		AND b.dcJobTypeId =c.DcJobTypeID
		AND c.Id = @i+@MinID
		ORDER BY a.LastLoginDate DESC

		INSERT INTO schMailPrevJobResume
		SELECT * FROM @t

		SET @Content = ''
		SELECT TOP (@r) @Content = @Content +'<tr>'+
		'<td>'+ISNULL(a.Name, '  ')+'[<a href="http://##SiteUrl##/Company/cv/cvview?id=' + CONVERT(VARCHAR, a.ResumeID) + '" target="_blank">' 
		+ CONVERT(VARCHAR, a.ResumeID) 
		+ '</a>]'+'</td>'+
		'<td>'+(CASE ISNULL(a.Sex, 0) WHEN 0 THEN '男' WHEN 1 THEN '女' END)+'</td>'+
		'<td>'+CONVERT(VARCHAR, ISNULL(a.Age, 30))+'</td>'+
		'<td>'+ISNULL(a.JobType, '  ')+'</td>'+
		'<td>'+ISNULL(a.AtPlaceDesc, '  ')+'</td>'+
		+'</tr>'
		FROM caJobResumePre a WITH(NOLOCK), @t c
		WHERE a.ResumeId = c.ResumeId
		ORDER BY a.LastLoginDate DESC
		IF LEN(LTRIM(RTRIM(ISNULL(@Content, '')))) = 0
			UPDATE schMailPrev 
			SET MailBody = '<br>&nbsp;&nbsp;符合[' + JobName + ']招聘职位的简历已经全部发送，暂时没有新的简历出现。您可以登录网站后使用“职位管理”-->“发布中的职位”-->“' + JobName + '”取消订阅，过一周后再重新订阅。<br>&nbsp;&nbsp;',
				RefreshDate = GETDATE()
			WHERE ID = @I+@MinID
		ELSE
			UPDATE schMailPrev 
			SET MailBody = '以下是贵单位为<b>[' + JobName + ']</b>招聘职位订阅的部分简历。<br><table style="font-size:12px"><tr style="FONT-WEIGHT: bold; background-color:#f7b666;"><td>求职者</td><td>性别</td><td>年龄</td><td>求职意向</td><td>所在地</td></tr>' + @Content + 
				'</table>详细情况请登录网站后使用“简历搜索”-->“<a href="http://##SiteUrl##/Company/cvSearch/Search" target="_blank">搜索简历</a>”-->点击“更多搜索条件”-->输入“简历编号”搜索。',
				RefreshDate = GETDATE()
			WHERE ID = @I+@MinID

		UPDATE a
		SET a.MailBody = REPLACE(a.MailBody, '##SiteUrl##', 'www.' + b.ProvinceDomain)
		FROM SchMailPrev a,
			dcProvince b
		WHERE a.dcProvinceId = b.Id
		AND a.Id = @I+@MinID
			
		SELECT @JobId = SubId FROM schMailPrev WITH(NOLOCK) WHERE ID = @I+@MinID
		UPDATE Job SET LastEmailDate = GETDATE() WHERE ID = @JobId
		
		DELETE @t
		SET @i = @i + 1
	END
	DELETE schMailPrev WHERE Email LIKE '%qq.com'
END














GO
/****** Object:  StoredProcedure [dbo].[__procExChangeDataByBdqnInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[__procExChangeDataByBdqnInsert]
AS
BEGIN
	return
	--添加昨天的下载记录到中间表
	INSERT INTO MarketDB..ExchangeActiveLog 
	SELECT cpMainID,cvMainID,AddDate 
	FROM caActiveLog WITH(NOLOCK)
	WHERE cvMainID IN (
		SELECT cvMainID 
		FROM MarketDB..cvImportPrev 
		WHERE OutId > 0
		AND cvMainId > 0
		)
	AND AddDate BETWEEN CONVERT(varchar(10), GETDATE() -1, 120) AND CONVERT(varchar(10), GETDATE(), 120)

	INSERT INTO MarketDB..ExchangeActiveLog
	SELECT cpMainID,cvMainID,AddDate 
	FROM cadailygiftlog WITH(NOLOCK)
	WHERE cvMainID IN (
		SELECT cvMainID 
		FROM MarketDB..cvImportPrev 
		WHERE OutId > 0
		AND cvMainId > 0
	)
	AND AddDate BETWEEN CONVERT(varchar(10), GETDATE() -1, 120) AND CONVERT(varchar(10), GETDATE(), 120)
 
	--将符合条件但不在中间表的职位加入交换数据表中
	INSERT INTO MarketDB..ExchangeData 
	SELECT ID,2,1,1,GETDATE() 
	FROM Job WITH(NOLOCK)
	WHERE dcJobTypeID 
	IN (1122,1413,1414,2215,2217,2313,2316,2317,2410,2412,2414,2613)
	AND ValID = 1 
	AND IssueEnd > GETDATE() 
	AND ID NOT IN (
		SELECT DataID 
		FROM MarketDB..ExchangeData x
		WHERE DataType = 2 AND PartnerType = 1
	)

	--昨天修改的职位，状态改为更新
	Update MarketDB..ExchangeData 
	SET AddDate = GETDATE(),status = 2 
	WHERE datatype = 2 AND DataID IN(
		SELECT ID 
		FROM Job WITH(NOLOCK)
		WHERE dcJobTypeID 
		IN (1122,1413,1414,2215,2217,2313,2316,2317,2410,2412,2414,2613)
		AND ValID = 1 AND IssueEnd > GETDATE() 
		AND LastModifyDate > CONVERT(varchar(10), GETDATE() -1, 120)
	)

	--不符合条件的职位状态改为删除
	Update MarketDB..ExchangeData 
	SET AddDate = GETDATE() ,status = 3 
	WHERE datatype = 2 
	AND DataID NOT IN(		--更改了不符合条件
		SELECT ID 
		FROM Job WITH(NOLOCK)
		WHERE dcJobTypeID 
		IN (1122,1413,1414,2215,2217,2313,2316,2317,2410,2412,2414,2613)
		AND Valid = 1 
		AND IssueEnd > GETDATE()
	)

	--添加公司信息
	INSERT INTO MarketDB..ExchangeData
	SELECT DISTINCT CpMainID,1,1,1,GETDATE() 
	FROM Job
	WHERE ID IN(
		SELECT DataId FROM MarketDB..ExchangeData WITH(NOLOCK)
		WHERE DataType = 2 
		AND PartnerType = 1  
		AND status <> 3
		)
	AND CpMainID NOT IN(
		SELECT DataId FROM MarketDB..ExchangeData WITH(NOLOCK)
		WHERE DataType = 1
		AND PartnerType = 1  
	)

	INSERT INTO MarketDB..ExchangeData
	SELECT DISTINCT CpMainID,1,1,1,GETDATE() 
	FROM MarketDB..ExchangeActiveLog WITH(NOLOCK)
	WHERE CpMainID NOT IN(
		SELECT DataId FROM MarketDB..ExchangeData WITH(NOLOCK)
		WHERE DataType = 1
		AND PartnerType = 1  
		AND status <> 3
	)

	--昨天修改的公司，状态改为更新
	Update MarketDB..ExchangeData 
	SET AddDate = GETDATE(),status = 2 
	WHERE datatype = 1 
	AND DataID IN(
		SELECT ID 
		FROM cpMain WITH(NOLOCK)
		WHERE Valid = 1
		AND LastModifyDate > CONVERT(varchar(10), GETDATE() -1, 120)
		)

	--不存在的企业，状态改为删除
	Update MarketDB..ExchangeData 
	SET AddDate = GETDATE(), status = 3 
	WHERE datatype = 1 
	AND DataID NOT IN(
		SELECT ID
		FROM cpMain WITH(NOLOCK)
		WHERE Valid = 1
		)
END











GO
/****** Object:  StoredProcedure [dbo].[_ProcPaJobCompareInsert0407]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--USE [MainDB]
--GO
--/****** 对象: StoredProcedure [dbo].[ProcPaJobCompareInsert]  脚本日期: 09/13/2016 15:26:30 ******/
--SET ANSI_NULLS ON
--GO
--SET QUOTED_IDENTIFIER ON
--GO
create PROCEDURE [dbo].[_ProcPaJobCompareInsert0407]
AS
SET NOCOUNT ON
IF DATEPART(HOUR, GETDATE()) > 17
	RETURN
BEGIN
	DECLARE @crDate DATETIME
	SELECT @CrDate = Value FROM dcRunParameter WHERE Name = 'exJobApplyMonthTemp create'
	IF @CrDate IS NULL
	BEGIN
		INSERT INTO dcRunParameter SELECT 'exJobApplyMonthTemp create', '', GETDATE() - 1, 1
		SELECT @CrDate = Value FROM dcRunParameter WHERE Name = 'exJobApplyMonthTemp create'
	END
	IF DATEDIFF(MINUTE, @CrDate, GETDATE()) > 480 OR (SELECT COUNT(*) FROM exJobApplyMonthTemp) < 10000
	BEGIN
		TRUNCATE TABLE exJobApplyMonthTemp
		--90天内的数据为样本
		INSERT INTO exJobApplyMonthTemp (JobId, CvMainID)
		SELECT jobID, CvMainID 
		FROM exjobapply WITH(NOLOCK) 
		WHERE addDate > GETDATE() - 30
		AND JobId > 0

		--排除海投
		DELETE FROM exJobApplyMonthTemp 
		WHERE CvMainID IN(
			SELECT CvMainID 
			FROM exJobApplyMonthTemp
			GROUP BY CvMainID
			HAVING COUNT(1) > 41		--if 30 then 26 if 90 then 41
		)

		UPDATE dcRunParameter SET Value = GETDATE() WHERE Name = 'exJobApplyMonthTemp create'
	END

	CREATE TABLE #TNP(paMainId INT)	--Table Need Push
	--一天之内登录过的 也推送
	INSERT INTO #TNP
	SELECT Id
	FROM PaMain WITH(NOLOCK)
	WHERE LastLoginDate > CONVERT(VARCHAR(10), GETDATE() - 1, 120) --一天之内登录的
	AND IsUseYourFood = 1

	--1天之前10天之后登陆的，也要推送
	INSERT INTO #TNP
	SELECT Id
	FROM paMain WITH(NOLOCK)
	WHERE LastLoginDate < GETDATE() - 1			 --一天之前登录的
	AND LastLoginDate >= CONVERT(VARCHAR(10), GETDATE() - 10 ,  120) --10天之内登录的
	AND NOT EXISTS(SELECT 'x' FROM #TNP WHERE PaMainID = PaMain.ID) --确定推送的就不再添加
	AND Id % 2 = DATEPART(DAY, GETDATE()) % 2
	AND IsUseYourFood = 1

	DELETE FROM #TNP WHERE paMainId IN(SELECT DISTINCT paMainId FROM PaJobCompare WITH(NOLOCK) WHERE AddDate > CONVERT(VARCHAR(10), GETDATE() , 120))
	SELECT * INTO #0 FROM #TNP
	DELETE a FROM #0 a, cvMain b WHERE a.paMainId = b.paMainId AND b.Degree > 0 AND b.EmployType > 0 AND RelatedWorkYears > -1
	DELETE #0 WHERE paMainId IN(SELECT paMainId FROM cvMain WHERE Id iN(SELECT cvMainId FROM ExJobApply WHERE AddDate > GETDATE() - 1))
	DELETE #TNP WHERE paMainId IN(SELECT paMainId FROM #0)
	IF EXISTS(SELECT 'x' FROM paJobCompareIndex WHERE AddDate < CONVERT(VARCHAR(10), GETDATE(), 120))
		TRUNCATE TABLE paJobCompareIndex
	DELETE #TNP WHERE paMainId IN(SELECT paMainId FROM paJobCompareIndex)

	INSERT INTO paJobCompareIndex(paMainId)
	SELECT paMainId FROM #Tnp
	DROP TABLE #TNP
	DROP TABLE #0
 	DECLARE @PaMainID INT,  @SQL AS VARCHAR(100)
	WHILE EXISTS(SELECT 'x' FROM paJobCompareIndex WITH(NOLOCK) WHERE RunDate IS NULL)
	BEGIN
		SELECT TOP 1 @PaMainID = PaMainID FROM paJobCompareIndex WITH(NOLOCK) WHERE RunStatus = 0 AND RunDate IS NULL ORDER BY ID
		SET @SQL = 'EXEC ProcPaJobCompareByPaMainIDInsert ' + LTRIM(STR(@PaMainID))
		--PRINT @SQL
		BEGIN TRY
			EXEC(@SQL)
			UPDATE paJobCompareIndex SET RunDate = GETDATE(), RunStatus = 1 WHERE paMainId = @paMainId
		END TRY
		BEGIN CATCH
			UPDATE paJobCompareIndex SET RunDate = GETDATE(), RunStatus = 101 WHERE paMainId = @paMainId
		END CATCH

		IF DATEDIFF(MINUTE, @crDate, GETDATE()) > 45
			RETURN
	END
END

GO
/****** Object:  StoredProcedure [dbo].[_procSOLLogByCaMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.10
--创建人：John
--说明：获取聊天记录
--#####################################################
CREATE PROCEDURE [dbo].[_procSOLLogByCaMainIDSelect]
(
	@caMainID INT
)
AS
BEGIN
	SELECT a.*,b.*,c.Name ManageruserName 
	FROM SOLLog a WITH(NOLOCK),SOLProcess b WITH(NOLOCK),Manageruser c WITH(NOLOCK) 
	WHERE a.ProcessID = b.ID AND b.ManageruserID = c.ID AND b.caMainID = @caMainID ORDER BY a.AddDate
END


GO
/****** Object:  StoredProcedure [dbo].[_procSOLLogByTodaySelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.10
--创建人：John
--说明：刚进入时获取当天的聊天记录
--#####################################################
CREATE PROCEDURE [dbo].[_procSOLLogByTodaySelect]
(
	@caMainID INT
)
AS
BEGIN
	SELECT a.*,b.*,d.cpMainID,e.RegDate,c.OpenName,c.Title,c.Name ManagerName,c.ID ManagerID 
	FROM SOLLog a WITH(NOLOCK),SOLProcess b WITH(NOLOCK),Manageruser c WITH(NOLOCK),caMain d WITH(NOLOCK),cpMain e WITH(NOLOCK) 
	WHERE b.caMainID = d.ID 
		AND d.cpMainID = e.ID 
		AND a.ProcessID = b.ID 
		AND b.ManageruserID = c.ID 
		AND b.caMainID = @caMainID 
		AND ( a.AddDate > CONVERT(VARCHAR(10),GETDATE(),120) OR IsViewed = 0 OR OfflineType = 5 ) 
	ORDER BY a.AddDate
END


GO
/****** Object:  StoredProcedure [dbo].[_procSOLLogIsViewdUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.10
--创建人：John
--说明：未查看标识改为已读
--#####################################################
CREATE PROCEDURE [dbo].[_procSOLLogIsViewdUpdate]
(
	@caMainID INT
)
AS
BEGIN
	UPDATE a SET IsViewed = 1 
	FROM SOLLog a WITH(NOLOCK),SOLProcess b WITH(NOLOCK) 
	WHERE a.ProcessID = b.ID AND b.caMainID = @caMainID AND a.IsViewed = 0
END


GO
/****** Object:  StoredProcedure [dbo].[_procSOLProcessByIsActiveSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.10
--创建人：John
--说明：获取聊天状态
--#####################################################
CREATE PROCEDURE [dbo].[_procSOLProcessByIsActiveSelect]
AS
BEGIN
	SELECT * FROM SolProcess WITH(NOLOCK) WHERE IsActive = 1 AND DATEDIFF(HOUR,StartDate,GETDATE()) >= 1
END


GO
/****** Object:  StoredProcedure [dbo].[_procSOLProcessByRtxSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.10
--创建人：John
--说明：取得发送RTX通知的数据
--#####################################################
CREATE PROCEDURE [dbo].[_procSOLProcessByRtxSelect]
(
	@ID INT
)
AS
BEGIN
	SELECT ManageruserID, CompanyName, b.cpMainID FROM SOLProcess a WITH(NOLOCK),caMain b WHERE a.caMainID = b.ID AND a.ID = @ID
END


GO
/****** Object:  StoredProcedure [dbo].[_procSOLProcessEvaluateUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.10
--创建人：John
--说明：服务评分
--#####################################################
CREATE PROCEDURE [dbo].[_procSOLProcessEvaluateUpdate]
(
	@Score TINYINT,
	@Remark NVARCHAR(500),
	@ProcessID INT
)
AS
BEGIN
	UPDATE SolProcess SET Evaluate = @Score, Remark = @Remark WHERE ID = @ProcessID
END


GO
/****** Object:  StoredProcedure [dbo].[_procSOLProcessIsActiveUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.10
--创建人：John
--说明：重新设置聊天状态为结束
--#####################################################
CREATE PROCEDURE [dbo].[_procSOLProcessIsActiveUpdate]
(
	@ProcessID INT
)
AS
BEGIN
	UPDATE SolProcess SET IsActive = 0, EndDate = GETDATE(), OfflineType = 8 WHERE ID = @ProcessID AND OfflineType NOT IN (5,6)
	UPDATE SolProcess SET IsActive = 0, EndDate = GETDATE() WHERE ID = @ProcessID AND OfflineType IN (5,6)
END


GO
/****** Object:  StoredProcedure [dbo].[_procSOLServiceSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.10
--创建人：John
--说明：获取客服人员列表
--#####################################################
CREATE PROCEDURE [dbo].[_procSOLServiceSelect]
AS
BEGIN
	SELECT a.ID,a.Name,a.NameEng,COUNT(*) cnt,a.DisplayNo,LetterNumber 
	FROM SOLService a WITH(NOLOCK),SOLProcess b WITH(NOLOCK)
	WHERE a.ID = b.ManagerUserID AND b.EndDate IS NULL 
	GROUP BY a.ID,a.Name,a.NameEng,a.DisplayNo,LetterNumber HAVING(COUNT(*)) < 2 
	UNION 
	SELECT a.ID,a.Name,a.NameEng,0 cnt,a.DisplayNo,LetterNumber FROM SOLService a WITH(NOLOCK) 
	WHERE a.ID NOT IN(SELECT ManagerUserID FROM SOLProcess WITH(NOLOCK) WHERE EndDate IS NULL)
	ORDER BY cnt,a.LetterNumber
END


GO
/****** Object:  StoredProcedure [dbo].[_ProcWebSafeJobInfoInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[_ProcWebSafeJobInfoInsert]
AS
BEGIN
	TRUNCATE TABLE ShortDb..WebSafeJobInfoLog

	SELECT a.Id JobId
	INTO #t
	FROM Job a WITH(NOLOCK), cpMain b WITH(NOLOCK)
	WHERE a.cpMainId = b.Id
	AND a.Valid = 1
	AND b.Valid = 1
	AND b.RegDate < GETDATE() - 15	
	
	DELETE #t WHERE JobId IN(SELECT JobId FROM ShortDb..WebSafeJobInfo)
 
	INSERT INTO ShortDb..WebSafeJobInfoLog(ICP_CODE, DATA_TYPE, USER_ID, USER_NAME, USER_PASSWORD, 
		STATUS, AddDate, IP_ADDR, CompanyName, 
		BIND_EMAIL, BIND_TEL, CONTACT_TEL, REAL_NAME, SEX,
		Address, Zip, HomePage, Job_ID, Job_Name, Lng, Lat, IssueEnd, dcCompanyKindID, dcCompanySizeID, dcRegionID,
		dcIndustryId, dcJobTypeID, NeedNumber, dcSalaryID, Job_dcRegionID, dcEducationID, MinExperience, MinAge, MaxAge,
		cpMainId, JobId)
  	SELECT '10000013803693' ICP_CODE, 'RECRUIT' DATA_TYPE, b.SecondID USER_ID, c.UserNameLower USER_NAME, c.Password USER_PASSWORD, 
		'新建' STATUS, b.RegDate AddDate, b.RegisterIp IP_ADDR, b.Name,
		c.Email BIND_EMAIL, c.Mobile BIND_TEL, ISNULL(c.TelePhone, c.Mobile) CONTACT_TEL, c.Name REAL_NAME, CASE WHEN c.Gender = 0 THEN '男' ELSE '女' END SEX,
		b.Address, ISNULL(b.Zip, ''), ISNULL('http://' + b.HomePage, ''), a.SecondId Job_ID, a.Name Job_Name, a.Lng, a.Lat, a.IssueEnd, 
		b.dcCompanyKindID, b.dcCompanySizeID, b.dcRegionID,	'' dcIndustryId, a.dcJobTypeID, a.NeedNumber, a.dcSalaryID, 
		a.dcRegionID Job_dcRegionID, a.dcEducationID, a.MinExperience, a.MinAge, a.MaxAge,
		b.Id, a.Id
  	FROM Job a WITH(NOLOCK), cpMain b WITH(NOLOCK), caMain c WITH(NOLOCK)
	WHERE a.cpMainId = b.Id
	AND c.cpMainId = b.Id
	AND c.AccountType = 1
	AND a.Valid = 1
	AND b.Valid = 1
	AND a.Id IN(SELECT JobId FROM #t)
 
	UPDATE ShortDb..WebSafeJobInfoLog SET CREATE_TIME = REPLACE(REPLACE(REPLACE(CONVERT(VARCHAR(19), GETDATE(), 120), '-', ''), ' ', ''), ':', '')
	UPDATE ShortDb..WebSafeJobInfoLog
	SET Ip_Addr = (SELECT TOP 1 LEFT(LoginIp, 15) FROM MainDb..paLoginLog b WHERE User_Id = b.paMainId ORDER BY ID DESC)
	WHERE Ip_Addr not LIKE '%.%'

	DELETE ShortDb..WebSafeJobInfoLog WHERE Ip_Addr not LIKE '%.%'

	UPDATE a SET a.Job_Region = b.FullName
	FROM ShortDb..WebSafeJobInfoLog a,
		MainDb..dcRegion b
	WHERE a.Job_dcRegionId = b.Id

	UPDATE a SET a.CompanyRegion = b.FullName
	FROM ShortDb..WebSafeJobInfoLog a,
		MainDb..dcRegion b
	WHERE a.dcRegionId = b.Id

	UPDATE a
	SET a.CompanyKind = b.Description
	FROM ShortDb..WebSafeJobInfoLog a, dcCompanyKind b
	WHERE a.dcCompanyKindId = b.Id

	UPDATE a
	SET a.CompanySize = b.Description
	FROM ShortDb..WebSafeJobInfoLog a, dcCompanySize b
	WHERE a.dcCompanySizeId = b.Id

	UPDATE ShortDb..WebSafeJobInfoLog
	SET dcIndustryId = (SELECT TOP 1 dcIndustryId FROM cpIndustry 
		WHERE cpIndustry.cpMainId = ShortDb..WebSafeJobInfoLog.cpMainId)

  	UPDATE a
	SET a.CompanyIndustry = b.Description
	FROM ShortDb..WebSafeJobInfoLog a, dcIndustry b
	WHERE a.dcIndustryId = b.Id

  	UPDATE a
	SET a.Job_Type = b.Description
	FROM ShortDb..WebSafeJobInfoLog a, dcJobType b
	WHERE a.dcJobTypeId = b.Id

	UPDATE a
	SET a.Job_Salary = b.Description
	FROM ShortDb..WebSafeJobInfoLog a, dcSalary b
	WHERE a.dcSalaryId = b.Id

	UPDATE a
	SET a.Job_Education = b.Description
	FROM ShortDb..WebSafeJobInfoLog a, dcEducation b
	WHERE a.dcEducationId = b.Id
	UPDATE ShortDb..WebSafeJobInfoLog SET Job_Education = '' WHERE Job_Education IS NULL

	UPDATE a
	SET a.Job_Experience = b.Description
	FROM ShortDb..WebSafeJobInfoLog a, dcOthers b
	WHERE ISNULL(a.MinExperience, 0) = b.DetailId
	AND b.Category = '职位要求工作经验'
	UPDATE ShortDb..WebSafeJobInfoLog SET Job_Experience = '不限' WHERE Job_Experience IS NULL
	UPDATE ShortDb..WebSafeJobInfoLog SET CompanyKind = '不限' WHERE CompanyKind IS NULL

	UPDATE a
	SET a.Job_NeedNumber = b.Description
	FROM ShortDb..WebSafeJobInfoLog a, dcOthers b
	WHERE ISNULL(a.NeedNumber, 0) = b.DetailId
	AND b.Category = '招聘人数'
	UPDATE ShortDb..WebSafeJobInfoLog SET Job_NeedNumber = '' WHERE Job_NeedNumber IS NULL

	UPDATE ShortDb..WebSafeJobInfoLog SET MinAge = 16 WHERE MinAge > MaxAge AND MinAge < 99
	UPDATE ShortDb..WebSafeJobInfoLog SET Job_Age = '不限' WHERE MinAge = 99 AND MaxAge = 99
	UPDATE ShortDb..WebSafeJobInfoLog
	SET Job_Age = CASE WHEN MinAge > 60 THEN '16' ELSE LTRIM(STR(MinAge)) END + '-' + 
		CASE WHEN MaxAge > 60 THEN '60' ELSE LTRIM(STR(MaxAge)) END + '岁'
	UPDATE ShortDb..WebSafeJobInfoLog SET Job_Age = '' WHERE Job_Age IS NULL
	UPDATE ShortDb..WebSafeJobInfoLog SET CompanyIndustry = '' WHERE CompanyIndustry IS NULL


	UPDATE ShortDb..WebSafeJobInfoLog SET Ip_Addr = LEFT(Ip_Addr, CHARINDEX(',', Ip_Addr) - 1) WHERE Ip_Addr LIKE '%,%'
	UPDATE ShortDb..WebSafeJobInfoLog SET Ip_Addr = '101.41.69.195' WHERE Ip_Addr LIKE '%101.41.69.195%'
	UPDATE ShortDb..WebSafeJobInfoLog SET Ip_Addr = '58.14.0.0' WHERE Ip_Addr LIKE '%58.14.0.0%'
	UPDATE ShortDb..WebSafeJobInfoLog SET Ip_Addr = '117.136.5.11' WHERE Ip_Addr LIKE '辽宁 117.136.5.11'
	UPDATE ShortDb..WebSafeJobInfoLog SET Ip_Addr = REPLACE(Ip_Addr, '#', '') WHERE Ip_Addr LIKE '%#%'
 
	UPDATE ShortDb..WebSafeJobInfoLog SET Ip1 = LEFT(Ip_Addr, CHARINDEX('.', Ip_Addr) - 1) WHERE CHARINDEX('.', Ip_Addr) > 1
	UPDATE ShortDb..WebSafeJobInfoLog SET Ip_Addr = RIGHT(Ip_Addr, LEN(Ip_Addr) - LEN(Ip1) -1) 

	UPDATE ShortDb..WebSafeJobInfoLog SET Ip2 = LEFT(Ip_Addr, CHARINDEX('.', Ip_Addr) - 1) WHERE CHARINDEX('.', Ip_Addr) > 1
	UPDATE ShortDb..WebSafeJobInfoLog SET Ip_Addr = RIGHT(Ip_Addr, LEN(Ip_Addr) - LEN(Ip2) -1) 
	
	UPDATE ShortDb..WebSafeJobInfoLog SET Ip3 = LEFT(Ip_Addr, CHARINDEX('.', Ip_Addr) - 1) WHERE CHARINDEX('.', Ip_Addr) > 1
	UPDATE ShortDb..WebSafeJobInfoLog SET Ip_Addr = RIGHT(Ip_Addr, LEN(Ip_Addr) - LEN(Ip3) -1) 

	UPDATE ShortDb..WebSafeJobInfoLog SET Ip_Addr = '255' WHERE Ip_Addr LIKE '%.%'
	UPDATE ShortDb..WebSafeJobInfoLog SET Ip4 = Ip_Addr
	UPDATE ShortDb..WebSafeJobInfoLog SET IpINT = Ip1
	UPDATE ShortDb..WebSafeJobInfoLog SET Ip_Addr = IpINT * 256 * 256 * 256 + ip2 * 256 * 256 + ip3 * 256 + ip4
	DELETE ShortDb..WebSafeJobInfoLog WHERE Ip1 IS NULL
	UPDATE ShortDb..WebSafeJobInfoLog SET Ip2 = 0 WHERE Ip2 IS NULL
	UPDATE ShortDb..WebSafeJobInfoLog SET Ip3 = 0 WHERE Ip3 IS NULL
	UPDATE ShortDb..WebSafeJobInfoLog SET Ip4 = 0 WHERE Ip4 IS NULL
	UPDATE ShortDb..WebSafeJobInfoLog SET Ip_Addr = IpINT * 256 * 256 * 256 + ip2 * 256 * 256 + ip3 * 256 + ip4
	WHERE Ip_Addr IS NULL
	DELETE ShortDb..WebSafeJobInfoLog WHERE Ip_Addr IS NULL
	DELETE ShortDb..WebSafeJobInfoLog WHERE Ip_Addr = '0'
	
	INSERT INTO ShortDb..WebSafeJobInfo(ICP_CODE, DATA_TYPE, USER_ID, USER_NAME, USER_PASSWORD, STATUS, CREATE_TIME, 
		IP_ADDR, CompanyName, BIND_EMAIL, BIND_TEL, CONTACT_TEL, REAL_NAME, SEX, CompanyKind, CompanySize, CompanyRegion,
		CompanyIndustry, Address, Zip, HomePage, Job_ID, Job_Name, Job_Type, Job_NeedNumber, Job_Salary, 
		Job_Region, Job_Education, Job_Experience, JOB_Age, Lng, Lat, IssueEnd, cpMainId, JobId, HasSubmit, AddDate)
	SELECT ICP_CODE, DATA_TYPE, USER_ID, USER_NAME, USER_PASSWORD, STATUS, CREATE_TIME, 
		IP_ADDR, CompanyName, BIND_EMAIL, BIND_TEL, CONTACT_TEL, REAL_NAME, SEX, CompanyKind, CompanySize, CompanyRegion,
		CompanyIndustry, Address, Zip, HomePage, Job_ID, Job_Name, Job_Type, Job_NeedNumber, Job_Salary, 
		Job_Region, Job_Education, Job_Experience, JOB_Age, Lng, Lat, CONVERT(VARCHAR(10), IssueEnd, 120), cpMainId, JobId, 0, GETDATE()
	FROM ShortDb..WebSafeJobInfoLog

	UPDATE  ShortDb..WebSafeJobInfo SET Lng = '', Lat = '' WHERE lng IS NULL
END

GO
/****** Object:  StoredProcedure [dbo].[agentAddLimitLogin]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[agentAddLimitLogin]
(
	@Key AS VARCHAR(100)
)
AS
--INSERT INTO procLog SELECT 'agentAddLimitLogin', '', GETDATE()
BEGIN
	--sean update at 2015-4-22, update the VerifyInfo text
	--INSERT bsCpStatus(cpMainId, StatusId, VerifyInfo, VerifyMan, VerifyDate)
	--SELECT ID, 9, '由于保险公司被投诉比例上升迅速，我们暂时对保险公司数量进行限制。只有交费企业会员才能正常使用，如需办理交费会员请致电网站客服400-626-5151联系相关事宜，谢谢合作！您的会员编号是' + LTRIM(STR(ID)), 1, GETDATE()
	INSERT bsCpStatus(cpMainId, StatusId, VerifyInfo, VerifyMan, VerifyDate)
	SELECT ID, 9, '您好！您在' + (SELECT TOP 1 WebSiteName FROM dcProvince WHERE Id = dcProvinceId) +
		 '的帐号需要付费使用，详情可致电4006265151联系' + CASE WHEN ConsultantId BETWEEN 600 AND 699 THEN '5' ELSE '6' END + LTRIM(STR(ISNULL(ConsultantId, 0))) + '号顾问，祝您招聘顺利！', 1, GETDATE()
	FROM cpMain WITH(NOLOCK) WHERE HasLicence = 1
	AND Name LIKE '%' + @Key + '%'
	AND IsLimitLogin < 9
	AND MemberType < 3

	IF GETDATE() < '2017-8-26'
		UPDATE cpMain 
		SET IsLimitLogin = 9
		WHERE HasLicence = 1
		AND Name LIKE '%' + @Key + '%'
		AND IsLimitLogin < 9
		AND MemberType < 3
	ELSE
		UPDATE cpMain 
		SET IsLimitLogin = 9,
			RealName = 6
		WHERE HasLicence = 1
		AND Name LIKE '%' + @Key + '%'
		AND IsLimitLogin < 9
		AND MemberType < 3
END

GO
/****** Object:  StoredProcedure [dbo].[BackDataUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[BackDataUpdate]
(
	@ManagerID INT,
	@Pass INT
)
AS
SET NOCOUNT ON
BEGIN TRAN
	DECLARE @ID AS INT
	BEGIN TRY
		SET @ID=0
		SELECT TOP 1 @ID=ID FROM backdata WITH(NOLOCK) WHERE
			ManagerID=@ManagerID AND CountDate=YEAR(GETDATE())*10000+MONTH(GETDATE())*100+DAY(GETDATE())
		IF @ID=0
			INSERT INTO backdata(ManagerID,CountDate) VALUES(
				@ManagerID,YEAR(GETDATE())*10000+MONTH(GETDATE())*100+DAY(GETDATE())
			)
		
		IF @Pass=1	
			UPDATE backdata SET resume_pass=resume_pass + 1 WHERE
				ManagerID=@ManagerID AND CountDate=YEAR(GETDATE())*10000+MONTH(GETDATE())*100+DAY(GETDATE())
		IF @Pass=10
			UPDATE backdata SET resume_nopass=resume_nopass + 1 WHERE
				ManagerID=@ManagerID AND CountDate=YEAR(GETDATE())*10000+MONTH(GETDATE())*100+DAY(GETDATE())
	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH
COMMIT TRAN
RETURN 1
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END














GO
/****** Object:  StoredProcedure [dbo].[bpActivationCpDetailByCountSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--创建人 Andy
--时间 2015-01-23
--按照条件查询企业激活个数
--bpActivationCpDetailByCountSelect 1,1,'','2013-1-31 13:41:00','2013-1-31 13:41:00'
CREATE PROCEDURE [dbo].[bpActivationCpDetailByCountSelect] 
(		
	@AddManOld INT,
	@AddManNew INT,
	@RegDateOld VARCHAR(10),
	@RegDateNewBegin VARCHAR(10),
	@RegDateNewEnd VARCHAR(10)
)
AS
BEGIN		
	DECLARE @SQL VARCHAR(1000)	
	SET @SQL = 'SELECT COUNT(*) allCount FROM LogDb..ActivationCpDetail WHERE 1=1'	
	IF @AddManOld > 0	
		SET @SQL = @SQL + ' And AddManOld = ' + LTRIM(STR(@AddManOld))
	IF @AddManNew > 0	
		SET @SQL = @SQL + ' And AddManNew = ' + LTRIM(STR(@AddManNew))	
	IF LEN(@RegDateOld) > 0
		BEGIN
			DECLARE @RegDateOldBegin DATETIME
			DECLARE @RegDateOldEnd DATETIME
			SET @RegDateOldBegin = CONVERT(DATETIME, @RegDateOld, 120)
			SET @RegDateOldEnd = @RegDateOldBegin + 1			
			SET @SQL = @SQL + ' And RegDateOld BETWEEN ''' + @RegDateOld + ''' AND ''' + CONVERT(VARCHAR(10), @RegDateOldEnd + 1, 120) + ''''
		END
	IF LEN(@RegDateNewBegin) > 0
		SET @SQL = @SQL + ' And RegDateNew >= ''' + CONVERT(VARCHAR(10), @RegDateNewBegin, 120) + ''''		
	IF LEN(@RegDateNewEnd) > 0
		SET @SQL = @SQL + ' And RegDateNew <= ''' + CONVERT(VARCHAR(10), @RegDateNewEnd, 120) + ''''			  

	--PRINT(@SQL)
	EXEC (@SQL)
END


GO
/****** Object:  StoredProcedure [dbo].[bpActivationCpDetailSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--创建人 Andy
--时间 2015-01-23
--按照条件查询企业激活日志
--bpActivationCpDetailSelect 1,1,'2013-1-31 13:41:00','','2013-1-31 13:41:00'
CREATE PROCEDURE [dbo].[bpActivationCpDetailSelect] 
(		
	@AddManOld INT,
	@AddManNew INT,
	@RegDateOld VARCHAR(10),
	@RegDateNewBegin VARCHAR(10),
	@RegDateNewEnd VARCHAR(10)
)
AS
BEGIN		
	DECLARE @SQL VARCHAR(1000)	
	SET @SQL = '
		SELECT a.*,b.Name NameOld, c.Name NameNew 
		FROM LogDb..ActivationCpDetail a  
		JOIN ManagerUser b ON a.addmanold = b.id   
		JOIN ManagerUser c ON a.addmannew = c.id 
		Where 1 = 1'	
	IF @AddManOld > 0	
		SET @SQL = @SQL + ' And AddManOld = ' + LTRIM(STR(@AddManOld))
	IF @AddManNew > 0	
		SET @SQL = @SQL + ' And AddManNew = ' + LTRIM(STR(@AddManNew))	
	IF LEN(@RegDateOld) > 0
		BEGIN
			DECLARE @RegDateOldBegin DATETIME
			DECLARE @RegDateOldEnd DATETIME
			SET @RegDateOldBegin = CONVERT(DATETIME, @RegDateOld, 120)
			SET @RegDateOldEnd = @RegDateOldBegin + 1	
			SET @SQL = @SQL + ' And RegDateOld BETWEEN ''' + @RegDateOld + ''' AND ''' + CONVERT(VARCHAR(10), @RegDateOldEnd + 1, 120) + ''''
		END
	IF LEN(@RegDateNewBegin) > 0
		SET @SQL = @SQL + ' And RegDateNew >= ''' + CONVERT(VARCHAR(10), @RegDateNewBegin, 120) + ''''
	IF LEN(@RegDateNewEnd) > 0
		SET @SQL = @SQL + ' And RegDateNew <= ''' + CONVERT(VARCHAR(10), @RegDateNewEnd, 120) + ''''		
			  
	SET @SQL = @SQL + ' Order By ID DESC'
	--PRINT(@SQL)
	EXEC (@SQL)
END

GO
/****** Object:  StoredProcedure [dbo].[bpActivationCvDetailByCountSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--创建人 Andy
--时间 2015-01-23
--按照条件个人激活的个数
--bpActivationCvDetailByCountSelect 0,0,'2013-1-31','2013-1-31 13:41:00','2013-3-31 13:41:00'
CREATE PROCEDURE [dbo].[bpActivationCvDetailByCountSelect] 
(		
	@AddManOld INT,
	@AddManNew INT,
	@RegDateOld VARCHAR(10),
	@RegDateNewBegin VARCHAR(10),
	@RegDateNewEnd VARCHAR(10)	
)
AS
BEGIN		
	DECLARE @SQL VARCHAR(1000)	
	SET @SQL = '
		SELECT COUNT(*) allCount FROM LogDb..ActivationCvDetail WHERE 1=1 '		
	IF @AddManOld > 0	
		SET @SQL = @SQL + ' And AddManOld = ' + LTRIM(STR(@AddManOld))
	IF @AddManNew > 0	
		SET @SQL = @SQL + ' And AddManNew = ' + LTRIM(STR(@AddManNew))	
	IF LEN(@RegDateOld) > 0
		BEGIN
			DECLARE @RegDateOldBegin DATETIME
			DECLARE @RegDateOldEnd DATETIME
			SET @RegDateOldBegin = CONVERT(DATETIME, @RegDateOld, 120)
			SET @RegDateOldEnd = @RegDateOldBegin + 1			
			SET @SQL = @SQL + ' And RegDateOld BETWEEN ''' + @RegDateOld + ''' AND ''' + CONVERT(VARCHAR(10), @RegDateOldEnd + 1, 120) + ''''
		END		
	IF LEN(@RegDateNewBegin) > 0
		SET @SQL = @SQL + ' And RegDateNew >= ''' + @RegDateNewBegin + ''''		
	IF LEN(@RegDateNewEnd) > 0
		SET @SQL = @SQL + ' And RegDateNew <= ''' + @RegDateNewEnd + ''''			  
	
	--PRINT(@SQL)
	EXEC (@SQL)
END


GO
/****** Object:  StoredProcedure [dbo].[bpActivationCvDetailSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--创建人 Andy
--时间 2015-01-23
--按照条件查询个人激活日志
--bpActivationCvDetailSelect 0,0,'2013-1-31','2013-1-31 13:41:00','2013-3-31 13:41:00'
CREATE PROCEDURE [dbo].[bpActivationCvDetailSelect] 
(		
	@AddManOld INT,
	@AddManNew INT,
	@RegDateOld VARCHAR(10),
	@RegDateNewBegin VARCHAR(10),
	@RegDateNewEnd VARCHAR(10)	
)
AS
BEGIN		
	DECLARE @SQL VARCHAR(1000)	
	SET @SQL = '
		SELECT TOP 2000 a.*, b.Name NameOld, c.Name NameNew 
		FROM LogDb..ActivationCvDetail a  
		JOIN ManagerUser b ON a.addmanold = b.id   
		JOIN ManagerUser c ON a.addmannew = c.id 
		Where 1 = 1 '		
	IF @AddManOld > 0	
		SET @SQL = @SQL + ' And AddManOld = ' + LTRIM(STR(@AddManOld))
	IF @AddManNew > 0	
		SET @SQL = @SQL + ' And AddManNew = ' + LTRIM(STR(@AddManNew))	
	IF LEN(@RegDateOld) > 0
		BEGIN
			DECLARE @RegDateOldBegin DATETIME
			DECLARE @RegDateOldEnd DATETIME
			SET @RegDateOldBegin = CONVERT(DATETIME, @RegDateOld, 120)
			SET @RegDateOldEnd = @RegDateOldBegin + 1			
			SET @SQL = @SQL + ' And RegDateOld BETWEEN ''' + @RegDateOld + ''' AND ''' + CONVERT(VARCHAR(10), @RegDateOldEnd + 1, 120) + ''''
		END				
	IF LEN(@RegDateNewBegin) > 0
		SET @SQL = @SQL + ' And RegDateNew >= ''' + @RegDateNewBegin + ''''		
	IF LEN(@RegDateNewEnd) > 0
		SET @SQL = @SQL + ' And RegDateNew <= ''' + @RegDateNewEnd + ''''
			  
	SET @SQL = @SQL + ' Order By ID DESC'
	--PRINT(@SQL)
	EXEC (@SQL)
END


GO
/****** Object:  StoredProcedure [dbo].[bpActivationLogBySumSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--bpActivationLogBySumSelect 1,'',''
--创建人 Andy
--时间 2015-01-23
--信息员注册信息统计
create PROCEDURE [dbo].[bpActivationLogBySumSelect] 
(		
	@AddMan INT,	
	@CountDateBegin VARCHAR(8),	--格式：20120101
	@CountDateEnd VARCHAR(8)		--格式：20120101
)
AS
BEGIN		
	SET @CountDateBegin = dbo.SafeSql(@CountDateBegin)
	SET @CountDateEnd = dbo.SafeSql(@CountDateEnd)
	
	DECLARE @SQL VARCHAR(1000)	
	SET @SQL = '
			SELECT SUM(CvCount) CvCount, SUM(AllPerson) AllPerson, SUM(CpCount) CpCount, SUM(AllCompany) AllCompany
			FROM LogDb..ActivationLog a 
			JOIN ( 
				SELECT CountDate, InfoManager_Id, SUM(Companyregnum_Our) AllCompany, SUM(Personregnum_Our) AllPerson 
				FROM info_datereport
				GROUP BY CountDate, InfoManager_Id) b 
			ON a.Countdate = b.Countdate AND a.AddMan = b.InfoManager_Id  
			JOIN ManagerUser c 
			ON a.AddMan = c.id 
			WHERE 1 = 1 '		
	IF @AddMan > 0	
		SET @SQL = @SQL + ' And AddMan = ' + LTRIM(STR(@AddMan))		
	IF LEN(@CountDateBegin) > 0
		SET @SQL = @SQL + ' And a.CountDate >= ''' + @CountDateBegin + ''''		
	IF LEN(@CountDateEnd) > 0
		SET @SQL = @SQL + ' And a.CountDate <= ''' + @CountDateEnd + ''''			  
	
	--PRINT(@SQL)
	EXEC (@SQL)
END
GO
/****** Object:  StoredProcedure [dbo].[bpActivationLogSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--bpActivationLogByAddManSelect 0,'20150111','20130131'
--创建人 Andy
--时间 2015-01-23
--信息员注册信息查询
create PROCEDURE [dbo].[bpActivationLogSelect] 
(		
	@AddMan INT,	
	@CountDateBegin VARCHAR(8),	--格式：20120101
	@CountDateEnd VARCHAR(8)		--格式：20120101
)
AS
BEGIN		
	SET @CountDateBegin = dbo.SafeSql(@CountDateBegin)
	SET @CountDateEnd = dbo.SafeSql(@CountDateEnd)
	
	DECLARE @SQL VARCHAR(1000)	
	SET @SQL = '
			SELECT TOP 2000 a.*, b.*, c.name 
			FROM LogDb..ActivationLog a 
			JOIN ( 
				SELECT CountDate, InfoManager_Id, SUM(Companyregnum_Our) AllCompany, SUM(Personregnum_Our) AllPerson 
				FROM info_datereport 
				GROUP BY CountDate, InfoManager_Id) b 
			ON a.Countdate = b.Countdate AND a.AddMan = b.InfoManager_Id  
			JOIN ManagerUser c 
			ON a.Addman=c.id WHERE 1 = 1 '		
	IF @AddMan > 0	
		SET @SQL = @SQL + ' And AddMan = ' + LTRIM(STR(@AddMan))		
	IF LEN(@CountDateBegin) > 0
		SET @SQL = @SQL + ' And a.CountDate >= ''' + @CountDateBegin + ''''		
	IF LEN(@CountDateEnd) > 0
		SET @SQL = @SQL + ' And a.CountDate <= ''' + @CountDateEnd + ''''			  
	SET @SQL = @SQL + ' ORDER BY a.CountDate DESC, Addman ASC'
	--PRINT(@SQL)
	EXEC (@SQL)
END


GO
/****** Object:  StoredProcedure [dbo].[bpAdverprojectByCompany_DeletedSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--###########################
--创建时间：2014.12.10
--创建人：Nick
--说明：删除单位发送通知
--###########################
CREATE PROCEDURE [dbo].[bpAdverprojectByCompany_DeletedSelect]
(
	@cpMainID INT
)
AS
INSERT INTO procLog SELECT 'bpAdverprojectByCompany_DeletedSelect', '', GETDATE()
BEGIN 
	SELECT TOP 10 b.ProvinceName, b.WebSiteName, b.ID, c.HandleMan 
	FROM adverproject a, dcprovince b, Company_Deleted c 
	WHERE a.province_id = b.id 
	AND a.Companyid = c.id 
	AND a.Endtime > GETDATE() 
	AND CompanyId = @cpMainID
END

GO
/****** Object:  StoredProcedure [dbo].[bpAdverProjectSubmitUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Mice 123>
-- Create date: <2014-11-20>
-- Description:	<保存广告计划管理记录>
-- Edit:2014-11-21 Mice 增加参数@innews,@imagefilesmall
--      修改 @pids 为 varchar类型， 传入参数可为（31,32,33,36,83）
--2018-04-16 Carl 修改 增添字段 isSelf
-- =============================================
CREATE PROCEDURE [dbo].[bpAdverProjectSubmitUpdate] 
(
	@id INT,
	@pids varchar(200),
	@type INT,
	@innews INT,
	@begintime VARCHAR(50),
	@endtime VARCHAR(50),
	@width INT,
	@height INT,
	@imagefile VARCHAR(50),
	@imagefilesmall VARCHAR(50),
	@orderby INT,
	@url VARCHAR(200),
	@companyid INT,
	@caorderid INT ,
	@description VARCHAR(200),
	@remarks VARCHAR(200),
	@addman INT,
	@isSelf BIT 
)
AS
INSERT INTO procLog SELECT 'bpAdverProjectSubmitUpdate', '', GETDATE()
BEGIN TRAN
	BEGIN TRY
		DECLARE @result AS INT
		SET @result=0

		IF @companyid > 0
		BEGIN
			IF NOT EXISTS( SELECT 'X' FROM MAINDB..cpmain WITH(NOLOCK)  WHERE ID=@companyid )
			BEGIN
				SET @result = -1 --找不到相关公司ID
				GOTO ERR
			END
		END

		IF @caorderid > 0 
		BEGIN
			IF NOT EXISTS( SELECT 'X' FROM MAINDB..caOrder WITH(NOLOCK)  WHERE ordertype=4 AND opendate IS NULL  AND id= @caorderid )
			BEGIN
				SET @result=-2 --找不到相关订单号，或者订单类型不对，或者订单已经开通
				GOTO ERR
			END
		END
		
		IF Len(@url)=0
			SET @url = NULL
		IF @companyid = 0
			SET @companyid = NULL
		IF @caorderid = 0
			SET  @caorderid = NULL
		IF Len(@description)=0
			SET @description = NULL
		IF @type <> 16
			SET @innews = NULL
		IF @type <> 14
			SET @imagefilesmall = NULL
		IF @width = 0
			SET  @width = NULL
		IF @height = 0
			SET  @height = NULL		

		--保存
		IF @id = 0 --新增保存
		BEGIN
			INSERT INTO  maindb..adverproject ([type],valid, innews, province_id,begintime,endtime,width,height,imagefile,orderby,url,companyid,caorderid,[description],remarks,addman,ImageFileSmall,IsSelf)
			SELECT @type, 1, @innews, a, @begintime,@endtime,@width,@height,@imagefile,@orderby,@url,@companyid,@caorderid,@description,@remarks,@addman,@imagefilesmall,@isSelf FROM dbo.fnsplit(@pids,',')
			
			IF @caorderid IS NOT NULL 
			BEGIN
				--修改订单表的开始时间和结束时间
				UPDATE maindb..caOrder SET OpenDate=GetDate(),OpenMan=@addman, BeginDate=@begintime, EndDate=@endtime WHERE ID=@caorderid
				
				DECLARE @Paid AS INT
				SELECT @Paid = Paid   FROM maindb..caOrder WITH(NOLOCK) WHERE id = @caorderid	
				IF @Paid = 0 --如果金额为0则自动款到账
					UPDATE maindb..caOrder SET ReceiveDate=GetDate(),ReceiveMan = @addman WHERE id = @caorderid	
			END
		END
		ELSE --修改保存
		BEGIN
			UPDATE maindb..adverproject SET begintime=@begintime, endtime=@endtime, imagefile=@imagefile, remarks=@remarks, province_id=@pids,width=@width, height=@height, orderby=@orderby, url=@url, companyid=@companyid, [description]=@description,ImageFileSmall=@imagefilesmall,IsSelf=@isSelf WHERE id=@id
		END
	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH
COMMIT TRAN
RETURN 1
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN @result
END

GO
/****** Object:  StoredProcedure [dbo].[bpAgentIPSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.09.08
--创建人：Nick
--说明：AgentIP
--#####################################################
create PROCEDURE [dbo].[bpAgentIPSelect]
AS
BEGIN
	SELECT * FROM agentip WITH(NOLOCK) ORDER BY adddate DESC
END

GO
/****** Object:  StoredProcedure [dbo].[bpAnswerByIdIndexSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--根据问题id 获取答题人数----------------
--增加人Harry ---------------------------
--增加时间：2015-1-28--------------------
CREATE PROCEDURE [dbo].[bpAnswerByIdIndexSelect]
(
	@id INT, 
	@index INT
)
AS
BEGIN
	SELECT COUNT(1) cnt 
	FROM MainDb..Answer WITH(NOLOCK) 
	WHERE questionid = @id 
	AND EXISTS( 
		SELECT 'x' 
		FROM dbo.fnSplit(answer, ',') 
		WHERE LTRIM(a) = @index
		)
END

GO
/****** Object:  StoredProcedure [dbo].[bpAnswerByIdManIdSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--检查是否完成了问卷调查-----------------
--增加人Harry ---------------------------
--增加时间：2015-1-28--------------------
CREATE PROCEDURE [dbo].[bpAnswerByIdManIdSelect]
(
	@id INT, 
	@manid INT
)
AS
BEGIN 
	SELECT TOP 1 * 
	FROM MainDb..Answer WITH(NOLOCK) 
	WHERE Questionid = @id 
	AND ManId = @manid
END

GO
/****** Object:  StoredProcedure [dbo].[bpAnswerByIdSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--根据问题id 获取答案----------------
--增加人Harry ---------------------------
--增加时间：2015-1-28--------------------
CREATE PROCEDURE [dbo].[bpAnswerByIdSelect]
(
	@id INT
)
AS
BEGIN
	SELECT  a.Assist, b.Id, b.Name 
	FROM MainDb..Answer a WITH(NOLOCK), ManagerUser b WITH(NOLOCK) 
	WHERE a.Manid = b.Id 
	AND LEN(a.Assist)>0 
	AND a.Questionid = @id
END

GO
/****** Object:  StoredProcedure [dbo].[bpAnswerByInvestIdSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


--获取调查的参加人数----------------
--增加人Harry -----------------------
--增加时间：2015-1-28---------------
CREATE PROCEDURE [dbo].[bpAnswerByInvestIdSelect]
(
	@id INT
)
AS
BEGIN
	SELECT TOP 1 COUNT(1) cnt  
	FROM MainDb..Answer a WITH(NOLOCK), MainDb..Question b WITH(NOLOCK) 
	WHERE a.QuestionId = b.Id 
	AND b.InvestId = @id 
	GROUP BY a.QuestionId
END

GO
/****** Object:  StoredProcedure [dbo].[bpAnswerInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--添加调查问卷回答的内容-----------------
--增加人Harry ---------------------------
--增加时间：2015-1-28--------------------
CREATE PROCEDURE [dbo].[bpAnswerInsert]
(
	@answer VARCHAR(20), 
	@assist NVARCHAR(200), 
	@questionid INT, 
	@manid INT
)
AS
BEGIN
	INSERT INTO MainDb..Answer (Answer, Assist, Questionid, Manid) 
	VALUES (@answer, @assist, @questionid, @manid)
END

GO
/****** Object:  StoredProcedure [dbo].[bpBackDataByDaySelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[bpBackDataByDaySelect]
(
	@Day VARCHAR(8)
)
AS
BEGIN
	SELECT *, 
		(SELECT COUNT(ID) 
		FROM bscpstatus 
		WHERE statusID=9 
		AND CONVERT(VARCHAR(10), AddDate, 112) = @Day 
		AND VerifyMan = x.ManagerID
		) limitCount 
	FROM 
		(SELECT managerid, SUM(reSUMe_pass) reSUMe_pass, SUM(reSUMe_delete) reSUMe_delete, 
		SUM(reSUMe_nopass) reSUMe_nopass, SUM(reSUMe_modify) reSUMe_modify, SUM(photo_pass) photo_pass, 
		SUM(photo_modify) photo_modify, SUM(photo_delete) photo_delete, SUM(companylogo_pass) companylogo_pass, 
		SUM(companylogo_delete) companylogo_delete, SUM(companyvisual_pass) companyvisual_pass, 
		SUM(companyvisual_delete) companyvisual_delete, SUM(black) black, SUM(company_modify) company_modify, 
		SUM(companydelete) companydelete,SUM(Contact_NoCvCount) Contact_NoCvCount,SUM(Contact_NoApplyCount) Contact_NoApplyCount,
		SUM(Contact_Count) Contact_Count,SUM(Contact_CvCount) Contact_CvCount,SUM(Contact_ApplyCount) Contact_ApplyCount 
		FROM backdata WITH(NOLOCK)  
		WHERE CONVERT(VARCHAR(10), CountDate, 112) = @Day 
		GROUP BY ManagerID 
		) x 
	ORDER BY ManagerID
END 
GO
/****** Object:  StoredProcedure [dbo].[bpBackDataByManagerUserIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.01.06
--创建人：Nick
--说明：根据根据manageruserid获取backdata
--#####################################################
CREATE PROCEDURE [dbo].[bpBackDataByManagerUserIDSelect]
(
	@ManagerUserID INT,
	@BeginDate VARCHAR(40),
	@EndDate VARCHAR(40)
)
AS
BEGIN
	SELECT *,(
		SELECT COUNT(ID) 
		FROM bscpstatus 
		WHERE statusID=9 
		AND CONVERT(VARCHAR(10),adddate,112)=backdata.countdate 
		AND VerifyMan = backdata.ManagerID
	) limitCount 
	FROM backdata WITH(NOLOCK)  
	WHERE countdate>=@BeginDate 
	AND countdate<=@EndDate 
	AND managerid=@ManagerUserID 
	ORDER BY countdate
END 

GO
/****** Object:  StoredProcedure [dbo].[bpBackDataByMonthSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[bpBackDataByMonthSelect]
(
	@BeginDate VARCHAR(8),
	@EndDate VARCHAR(8)
)
AS
BEGIN
	SELECT *,(
		SELECT COUNT(ID) 
		FROM bscpstatus 
		WHERE statusID=9 
		AND CONVERT(VARCHAR(10),adddate,112)>=@BeginDate 
		AND CONVERT(VARCHAR(10),adddate,112)<=@EndDate 
		AND VerifyMan = x.ManagerID
	) limitCount FROM (
		SELECT managerid,Sum(resume_pass) resume_pass,Sum(resume_delete) resume_delete,Sum(resume_nopass) resume_nopass,
		Sum(resume_modify) resume_modify,Sum(photo_pass) photo_pass,Sum(photo_modify) photo_modify,
		Sum(photo_delete) photo_delete,Sum(companylogo_pass) companylogo_pass,Sum(companylogo_delete) companylogo_delete,
		Sum(companyvisual_pass) companyvisual_pass,Sum(companyvisual_delete) companyvisual_delete,Sum(black) black,
		Sum(company_modify) company_modify,Sum(companydelete) companydelete,SUM(Contact_NoCvCount) Contact_NoCvCount,
		SUM(Contact_NoApplyCount) Contact_NoApplyCount,SUM(Contact_Count) Contact_Count,
		SUM(Contact_CvCount) Contact_CvCount,SUM(Contact_ApplyCount) Contact_ApplyCount 
		FROM backdata WITH(NOLOCK)
		WHERE countdate>=@BeginDate
		AND countdate<=@EndDate
		GROUP BY ManagerID
	) x ORDER BY ManagerID
END 

GO
/****** Object:  StoredProcedure [dbo].[bpBackdataByWeekSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[bpBackdataByWeekSelect]
(
	@week INT
)
AS
INSERT INTO procLog SELECT 'bpBackdataByWeekSelect', '', GETDATE()
BEGIN
    SET DATEFIRST 1
    SELECT managerid, SUM(resume_pass) resume_pass,SUM(resume_delete) resume_delete,
	SUM(resume_nopass) resume_nopass,SUM(resume_modify) resume_modify,SUM(photo_pass) photo_pass,
	SUM(photo_modify) photo_modify,SUM(photo_delete) photo_delete,SUM(companylogo_pass) companylogo_pass,
	SUM(companylogo_delete) companylogo_delete,SUM(companyvisual_pass) companyvisual_pass,
	SUM(companyvisual_delete) companyvisual_delete,SUM(black) black,SUM(company_modify) company_modify,
	SUM(companydelete) companydelete,SUM(Contact_NoCvCount) Contact_NoCvCount,SUM(Contact_NoApplyCount) Contact_NoApplyCount,
	SUM(Contact_Count) Contact_Count,SUM(Contact_CvCount) Contact_CvCount,SUM(Contact_ApplyCount) Contact_ApplyCount 
    FROM backdata with(nolock)   
    WHERE countDate >= CONVERT(varchar(8),dateadd(day,1-datepart(weekday,getdate()-@week*7),getdate()-@week*7),112)
    AND countDate < CONVERT(varchar(8),dateadd(day,1-datepart(weekday,getdate()-(@week-1)*7),getdate()-(@week-1)*7),112)
    GROUP BY managerid 
	ORDER BY managerid
END
GO
/****** Object:  StoredProcedure [dbo].[bpBackDataByYearSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[bpBackDataByYearSelect]
(
	@Year VARCHAR(8)
)
AS
BEGIN
	SELECT *,(
		SELECT COUNT(ID) 
		FROM bscpstatus 
		WHERE statusID=9 
		AND CONVERT(VARCHAR(4),adddate,112)=@Year 
		AND VerifyMan = x.ManagerID
	) limitCount 
	FROM ( 
		SELECT managerid,Sum(resume_pass) resume_pass,Sum(resume_delete) resume_delete,Sum(resume_nopass) resume_nopass,
		Sum(resume_modify) resume_modify,Sum(photo_pass) photo_pass,Sum(photo_modify) photo_modify,
		Sum(photo_delete) photo_delete,Sum(companylogo_pass) companylogo_pass,Sum(companylogo_delete) companylogo_delete,
		Sum(companyvisual_pass) companyvisual_pass,Sum(companyvisual_delete) companyvisual_delete,Sum(black) black,
		Sum(company_modify) company_modify,Sum(companydelete) companydelete,SUM(Contact_NoCvCount) Contact_NoCvCount,
		SUM(Contact_NoApplyCount) Contact_NoApplyCount,SUM(Contact_Count) Contact_Count,SUM(Contact_CvCount) Contact_CvCount,
		SUM(Contact_ApplyCount) Contact_ApplyCount 
		FROM backdata WITH(NOLOCK) 
		WHERE LEFT(countdate,4) = @Year GROUP BY managerid 
	) x ORDER BY managerid
END 

GO
/****** Object:  StoredProcedure [dbo].[bpBackDataUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----------------
--创建日期：2010-9-26
--创建人：lambo
--功能说明：根据列名和用户编号修改今天的操作记录，每次增加1，如果没有则先增加一条
--用于后台记录用户的操作记录
-----------------
CREATE PROCEDURE [dbo].[bpBackDataUpdate]
(
	@ManagerUserID INT,
	@col VARCHAR(50)
)
AS
INSERT INTO procLog SELECT 'bpBackDataUpdate', '', GETDATE()
BEGIN TRAN
	BEGIN TRY
		SET @col = REPLACE(@col, '''', '')
		DECLARE @SQL AS VARCHAR(1000)
		IF NOT EXISTS (SELECT id FROM backdata WITH (NOLOCK) WHERE managerid=@ManagerUserID AND CountDate=YEAR(GETDATE())*10000+MONTH(GETDATE())*100+DAY(GETDATE()))
			INSERT INTO backdata (managerid,countdate) VALUES(@ManagerUserID,YEAR(GETDATE())*10000+MONTH(GETDATE())*100+DAY(GETDATE()))
		SET @SQL = 'UPDATE backdata SET ' + @col + '=' + @col + '+ 1 WHERE managerid=' + LTRIM(STR(@ManagerUserID)) + 
			' AND CountDate=YEAR(GETDATE())*10000+MONTH(GETDATE())*100+DAY(GETDATE())'
		EXEC(@SQL)
	END TRY
	BEGIN CATCH
		GOTO err
	END CATCH
COMMIT TRAN
RETURN 1
err:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END

GO
/****** Object:  StoredProcedure [dbo].[bpBaiduLogCheck]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE  [dbo].[bpBaiduLogCheck]  
AS
INSERT INTO procLog SELECT 'bpBaiduLogCheck', '', GETDATE()
BEGIN
	SELECT TOP 0 * INTO #t FROM BaiduMapLog
	ALTER TABLE #t ADD Id1 INT
	ALTER TABLE #t ADD Id2 INT
	ALTER TABLE #t ADD Id3 INT
	ALTER TABLE #t ADD JobName1 NVARCHAR(100)
	ALTER TABLE #t ADD JobName2 NVARCHAR(100)
	ALTER TABLE #t ADD JobName3 NVARCHAR(100)

	INSERT INTO #t(JobID, Lng, Lat, Status)
	SELECT Id, Lng, Lat, 9
	FROM cpMainPublish WITH(NOLOCK) 
	WHERE Valid = 1 AND Id IN(SELECT cpMainId FROM JobPublish WITH(NOLOCK) WHERE Valid = 1)
	AND Lng > 0
	

	UPDATE a
	SET a.Address = b.Address,
		a.cpMainName = b.Name,
		a.FullName = b.SecondId,
		a.Status = b.dcProvinceID
	FROM #t a, cpMain b
	WHERE a.JobId = b.Id

	UPDATE a
	SET a.JobUrl = b.ProvinceDomain
	FROM #t a, dcProvince b
	WHERE a.Status = b.Id

	UPDATE #t SET cpMainUrl = 'http://www.' + JobUrl + '/personal/cp' + FullName +'.html'

	UPDATE #t SET Status = 9, JobUrl = cpMainUrl, FullName = NULL

	SELECT cpMainId, Id, Name, dcSalaryId, ROW_NUMBER() OVER(PARTITION BY cpMainId ORDER BY CASE dcSalaryId WHEN 100 THEN 5 ELSE dcSalaryId END DESC, IssueDate DESC, ID DESC) RowNo
	INTO #1
	FROM JobPublish WITH(NOLOCK)
	WHERE Valid = 1

	DELETE #1 WHERE cpMainId NOT IN(SELECT JobId FROM #t)
	DELETE #1 WHERE RowNo > 3

	UPDATE a SET a.Id1 = b.Id, a.JobName1 = b.Name, a.dcSalaryId = b.dcSalaryId FROM #t a, #1 b WHERE a.JobId = b.cpMainId AND RowNo = 1
	UPDATE a SET a.Id2 = b.Id, a.JobName2 = b.Name FROM #t a, #1 b WHERE a.JobId = b.cpMainId AND RowNo = 2
	UPDATE a SET a.Id3 = b.Id, a.JobName3 = b.Name FROM #t a, #1 b WHERE a.JobId = b.cpMainId AND RowNo = 3

	DELETE FROM #t WHERE Id1 IS NULL
	UPDATE #t SET JobName = JobName1
	UPDATE #t SET JobName = JobName + ' | ' + JobName2 WHERE JobName2 IS NOT NULL AND LEN(JobName + ' | ' + JobName2) < 50
	UPDATE #t SET JobName = JobName + ' | ' + JobName3 WHERE JobName3 IS NOT NULL AND LEN(JobName + ' | ' + JobName3) < 51
	UPDATE a
	SET a.Salary = b.Description
	FROM #t a, dcSalary b
	WHERE a.dcSalaryId = b.Id
	---------------------------------------

	INSERT INTO BaiduMapLog(JobId, JobName, Address, cpMainName, Lng, Lat, dcSalaryId, Salary, JobUrl, cpMainUrl, [Status])
	SELECT JobId, JobName, Address, cpMainName, Lng, Lat, dcSalaryId, Salary, JobUrl, cpMainUrl,  1
	FROM #t
	WHERE JobID NOT IN(SELECT JobId FROM BaiduMapLog WITH(NOLOCK))

	DELETE BaiduMapLog
	WHERE JobId IN(SELECT ID FROM cpMain WHERE Lat IS NULL OR Lng IS NULL)

	UPDATE BaiduMapLog
	SET Status = 3
	WHERE JobId NOT IN(
		SELECT b.Id
		FROM Job a WITH(NOLOCK), cpMain b WITH(NOLOCK)
		WHERE a.cpMainId = b.Id
		AND a.Valid = 1 
		AND b.Valid = 1)

	UPDATE b SET b.JobName = a.JobName ,b.Status=2 FROM #t a, BaiduMapLog b WHERE a.JobId = b.JobId AND b.Status = 0 AND a.JobName <> b.JobName
	UPDATE b SET b.Address = a.Address ,b.Status=2 FROM #t a, BaiduMapLog b WHERE a.FullName IS NULL AND a.JobId = b.JobId AND b.Status = 0 AND a.Address <> b.Address
	UPDATE b SET b.cpMainName =a.cpMainName, b.Status=2   FROM #t a, BaiduMapLog b WHERE a.FullName IS NULL AND a.JobId = b.JobId AND b.Status = 0 AND a.cpMainName <> b.cpMainName
	UPDATE b SET b.Lng=a.Lng, b.Status=2 FROM #t a, BaiduMapLog b WHERE a.FullName IS NULL AND a.JobId = b.JobId AND b.Status = 0 AND a.Lng <> b.Lng
	UPDATE b SET b.Lat = a.Lat, b.Status=2 FROM #t a, BaiduMapLog b WHERE a.FullName IS NULL AND a.JobId = b.JobId AND b.Status = 0 AND a.Lat <> b.Lat
	UPDATE b SET b.dcSalaryId = a.dcSalaryId, b.Status=2  FROM #t a, BaiduMapLog b WHERE a.FullName IS NULL AND a.JobId = b.JobId AND b.Status = 0 AND a.dcSalaryId <> b.dcSalaryId 
END 

GO
/****** Object:  StoredProcedure [dbo].[bpBaiduLogSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[bpBaiduLogSelect]
AS
RETURN
BEGIN
/*
	UPDATE a SET
		a.Valid = b.Valid,
		a.OperDate = GETDATE()
	FROM LogDB..BaiduMapLog a,Job b
	WHERE a.JobID=b.ID AND a.Valid <> b.Valid

	UPDATE a SET
		a.RefreshDate = CONVERT(VARCHAR,c.LastLoginDate,112),
		a.OperDate = GETDATE()
	FROM LogDB..BaiduMapLog a,Job b,cpMain c
	WHERE a.JobID=b.ID AND b.cpMainID=c.ID AND a.RefreshDate<CONVERT(VARCHAR,c.LastLoginDate,112) AND a.Valid=1

	UPDATE a SET
		a.Lat = b.Lat,
		a.Lng = b.Lng,
		a.OperDate = GETDATE()
	FROM LogDB..BaiduMapLog a,Job b
	WHERE a.JobID=b.ID AND a.Lng<>b.Lng AND b.Lat<>a.Lat AND a.Valid=1

	UPDATE a SET
		a.Name=b.Name,
		a.CoordType=3,
		a.Industry=(SELECT TOP 1 dcIndustryID FROM cpIndustry WITH(NOLOCK) WHERE cpIndustry.cpMainid=b.cpMainID),
		a.Valid=b.Valid,
		a.Description=(SELECT Description FROM dcSalary WITH(NOLOCK) WHERE dcSalary.ID=b.dcSalaryID),
		a.dcJobTypeID=b.dcJobTypeID,
		a.SecondID=b.SecondID,
		a.RefreshDate=CONVERT(VARCHAR(8),b.RefreshDate,112),
		a.cpMainName=c.Name,
		a.cpMainSecondId=c.SecondID,
		a.JobName=b.Name,
		a.cpMainId=c.ID
	FROM Logdb..BaiduMapLog a,Job b,cpMain c
	WHERE a.JobID=b.ID AND b.cpMainID=c.ID AND OperDate>UploadDate
	
	UPDATE a SET
		a.FullName=(SELECT FullName + c.Address FROM dcRegion WITH(NOLOCK) WHERE dcRegion.ID=b.dcRegionID)
	FROM Logdb..BaiduMapLog a,Job b,cpMain c
	WHERE a.JobID=b.ID AND b.cpMainID=c.ID AND OperDate>UploadDate AND LEN(ISNULL(FullName,''))=0

	SELECT TOP 50000 * FROM Logdb..BaiduMapLog WITH(NOLOCK) WHERE OperDate>UploadDate ORDER BY OperDate DESC
*/
print 1
END

GO
/****** Object:  StoredProcedure [dbo].[bpbsAskClickLogByCountMontySelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--bpbsAskClickLogByCountMontySelect '201401'
--创建人 Andy
--时间 2015-01-23
--按月查询求职互助点击量
CREATE PROCEDURE [dbo].[bpbsAskClickLogByCountMontySelect] 
(
	@CountMonth NVARCHAR(6)	
)
AS
BEGIN	
	SELECT b.AddUserID, SUM(a.increase) Cnt
	FROM bsAskClickLog a, bsASKInfo b
	WHERE a.bsAskInfoID = b.ID
	AND a.CountMonth = @Countmonth
	GROUP BY b.AddUserID
	ORDER BY AddUserID
END


GO
/****** Object:  StoredProcedure [dbo].[bpBsAskInfoBySourceSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[bpBsAskInfoBySourceSelect]
AS
SET NOCOUNT ON
BEGIN
	SELECT CountDate, Province_Id, ISNULL(SUM(Page_Count), 0) cnt, southnorth  
	INTO #t
	FROM (SELECT countdate, a.Id as Province_Id, D.Page_Count, southnorth  
		FROM dcProvince a
		LEFT JOIN ( 
			SELECT b.CountDate, c.Page_Count, b.Province_Id 
			From Innerer_CountNew b left join innerer_count_detail c 
			ON c.Innerer_CountId = b.Id  
			WHERE countdate >= CONVERT(VARCHAR(8), GETDATE() - 100, 112)
			AND c.Innerpage=5 
			AND Province_Id < 999  
			AND (LEN(Province_Id)=2 OR LEN(Province_Id)=4 OR Province_Id=0)
			) d ON a.Id  = d.Province_Id
		) E
	GROUP BY CountDate, Province_Id, southnorth 
	ORDER BY CountDate, CASE southnorth WHEN 4 THEN 1 ELSE southnorth END DESC,
		Province_Id

	SELECT DISTINCT CASE southnorth WHEN 4 THEN 1 ELSE southnorth END southnorth, Province_Id 
	INTO #p
	FROM #t
	ORDER BY CASE southnorth WHEN 4 THEN 1 ELSE southnorth END DESC, Province_Id

	DECLARE @temp NVARCHAR(max)
	SELECT @temp=COALESCE(@temp,'')+ '['+  LTRIM(STR(province_id)) +'], '  
	FROM   
	#p  
	set @temp=SUBSTRING(@temp,1,LEN(@temp)-1)  
	--print @temp
	 
	DECLARE @sql NVARCHAR(max)  
	SET @sql='  
	SELECT countdate, ' + @temp + '
	from (select countdate, province_id, cnt from #t) a
	pivot(avg(Cnt)
		for province_id IN('+ @temp+')
	)b ORDER BY CountDATE DESC'  
	--PRINT @sql  
	EXEC(@sql)
END

GO
/****** Object:  StoredProcedure [dbo].[bpbsConsultantFreeOrderInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--添加顾问免费订单记录 Lucifer 2014-12-24
CREATE PROCEDURE [dbo].[bpbsConsultantFreeOrderInsert]
(
	@OrderID INT,
	@ConsultantID SMALLINT
)
AS
INSERT INTO procLog SELECT 'bpbsConsultantFreeOrderInsert', '', GETDATE()
BEGIN
	INSERT INTO MainDb..bsConsultantFreeOrder(ConsultantId,OpenDate,OrderID) SELECT @ConsultantID,GETDATE(),@OrderID
END


GO
/****** Object:  StoredProcedure [dbo].[bpbsConsultantFreeOrderSetSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--查询顾问当月是否还有订单赠送配额 Lucifer 2014-12-24
CREATE PROCEDURE [dbo].[bpbsConsultantFreeOrderSetSelect]
(
	@ConsultantID SMALLINT
)
AS
BEGIN
	SELECT 'X' FROM bsConsultantFreeOrderSet a WHERE (
		SELECT COUNT(*) cnt FROM bsConsultantFreeOrder
		WHERE OpenDate>CONVERT(DATETIME,CONVERT(VARCHAR(8),DATEADD(DAY, -25, GETDATE()),21)+'26') AND
		ConsultantId = a.ConsultantId
	) < a.Number AND [Type]=13 AND ConsultantId = @ConsultantId
END


GO
/****** Object:  StoredProcedure [dbo].[bpbsConsultantFreeOrderSetUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------
--创建日期：2014-12-1
--创建人：harry
--功能说明：newoamvc单位用户管理-->设置顾问开通权限限额分配
--用于设置后台顾问开通权限限额分配
-------------------------------------------------------
CREATE PROCEDURE [dbo].[bpbsConsultantFreeOrderSetUpdate]
(
    @Number INT,
    @DeptId INT
)
AS
SET NOCOUNT ON
BEGIN
    UPDATE bsConsultantFreeOrderSet 
    SET Number = @Number
    WHERE ConsultantId IN(
        SELECT Id 
        FROM Manageruser WITH(NOLOCK)    
        WHERE DeptId = @DeptId)

	INSERT INTO bsConsultantFreeOrderSet
	SELECT ID, @Number, 13 FROM ManagerUser WHERE DeptId = @DeptId AND STATUS < 3 AND ID NOT IN(SELECT ConsultantId FROM bsConsultantFreeOrderSet)

    RETURN 1
END

GO
/****** Object:  StoredProcedure [dbo].[bpBsCpBackLoginByUnqueIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[bpBsCpBackLoginByUnqueIDSelect]
(
	@UID VARCHAR(20)	
)
AS
BEGIN
	DECLARE @CaMainID AS INT
	SELECT @CaMainID = caMainID
	FROM bsCpBackLogin WITH(NOLOCK)
	WHERE UnqueID = @UID
	IF @CaMainID IS NULL
		RETURN 0
	ELSE
		RETURN @CaMainID
END
















GO
/****** Object:  StoredProcedure [dbo].[bpBsCpBackLoginInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[bpBsCpBackLoginInsert]
(
	@cpMainID INT,
	@caMainID INT,
	@ManagerUserID INT,
	@UID VARCHAR(20) OUTPUT
)
AS
BEGIN
	DECLARE @T AS VARCHAR(20)
	SET @T = CONVERT(VARCHAR(20), CONVERT(DECIMAL(18,12),GETDATE()))
	SET @T = RTRIM(CONVERT(VARCHAR(12), @cpMainID)) + '_' + RIGHT(@T,8)
	INSERT INTO BsCpBackLogin (UnqueID,cpMainID,caMainID,ManagerUserID)
	VALUES(@T,@cpMainID,@caMainID,@ManagerUserID)
	SET @UID =  @T
END














GO
/****** Object:  StoredProcedure [dbo].[bpbsCpModifyByFilterWordSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.1.8
--创建人：Nick
--说明：获取包含过滤词的职位
--#####################################################
CREATE PROCEDURE [dbo].[bpbsCpModifyByFilterWordSelect]
AS
BEGIN 
	SELECT a.Id cpMainID, a.IsLimitLogin, a.consultantid, a.haslicence, a.RegDate, a.Name cpName, b.FilterWord, 
	b.AddDate, Left(b.ColValue, 30) colValue 
	FROM cpMain a With(Nolock), bsCpModify b WITH(NOLOCK) 
	WHERE a.Id = b.cpMainId AND b.FilterWord>'' 
	AND b.verifyinfo IS NULL AND b.AddDate > GETDATE() - 2 AND IsLimitLogin < 9 
	ORDER BY b.AddDate
End

GO
/****** Object:  StoredProcedure [dbo].[bpbsCpModifyPassUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[bpbsCpModifyPassUpdate]
(
	@bsCpVerifyID INT,
	@Pass INT
)
AS
BEGIN TRY
	DECLARE @cpMainID AS INT
	SELECT @cpMainID = cpMainID FROM bsCpVerify WITH(NOLOCK) WHERE ID=@bsCpVerifyID
	UPDATE cpMain SET VerifyResult = @Pass WHERE ID = @cpMainID
	
/*		Job全部通过，要么修改 要么删除
	UPDATE Job SET VerifyResult = @Pass WHERE ID IN(
		SELECT DISTINCT SubID FROM bsCpModify WITH(NOLOCK)
		WHERE cpMainID =  @cpMainID
		AND Location Like 'c%'
	)
*/
END TRY
BEGIN CATCH
	GOTO ERR
END CATCH
RETURN 1
ERR:
BEGIN
	RETURN 0
END

GO
/****** Object:  StoredProcedure [dbo].[bpbsCpModifyUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[bpbsCpModifyUpdate]
(
	@ID INT,
	@bsCpVerifyID INT,
	@VerifyInfo NVARCHAR(200)
)
AS
BEGIN TRY
	DECLARE @MaxID AS INT
	IF ISNULL(@VerifyInfo, '') =''
		BEGIN
			INSERT INTO bsCpVerifyLog(bsCpVerifyID,SubID,Location,AddDate,OldValue)
				SELECT @bsCpVerifyID,SubID,Location,AddDate,ColValue FROM bsCpModify WITH(NOLOCK) WHERE ID = @ID
			SET @MaxID = @@IDENTITY
			DELETE FROM bsCpModify WHERE ID = @ID
		END
	ELSE
		BEGIN
			INSERT INTO bsCpVerifyLog(bsCpVerifyID,SubID,Location,AddDate,OldValue,VerifyResult,VerifyInfo)
				SELECT @bsCpVerifyID,SubID,Location,AddDate,ColValue,1,@VerifyInfo FROM bsCpModify WITH(NOLOCK) WHERE ID = @ID
			SET @MaxID = @@IDENTITY
			UPDATE bsCpModify SET VerifyInfo=@VerifyInfo WHERE ID=@ID
		END
END TRY
BEGIN CATCH
	GOTO ERR
END CATCH
RETURN 1
ERR:
BEGIN
	RETURN 0
END














GO
/****** Object:  StoredProcedure [dbo].[bpbsCpStatusByCpMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[bpbsCpStatusByCpMainIDSelect]
(
	@StatusID VARCHAR(20),
	@cpMainID INT
)
AS
BEGIN
	DECLARE @SQL AS VARCHAR(1000)
	SET @StatusID = REPLACE(@StatusID, '''', '')
	SET @SQL = 'SELECT * FROM BsCpStatus WITH(NOLOCK) WHERE cpMainID = ' + RTRIM(CONVERT(CHAR(10), @cpMainID))
	IF LEN(@StatusID) > 0
		SET @SQL = @SQL + '	AND StatusID IN (' + RTRIM(CONVERT(CHAR(10), @StatusID)) + ')'
	SET @SQL = @SQL + '	ORDER BY ID DESC'
	EXEC(@SQL)
END





GO
/****** Object:  StoredProcedure [dbo].[bpBsCpStatusInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-----------------
--创建日期：2010-9-14
--创建人：lambo
--功能说明：增加企业状态操作记录
--用于后台企业用户管理模块
-----------------
CREATE PROCEDURE [dbo].[bpBsCpStatusInsert]
(
	@cpMainID INT,
	@StatusID INT,
	@ApplyInfo VARCHAR(200),
	@VerifyMan INT,
	@VerifyInfo VARCHAR(500)
)
AS
BEGIN TRY
	DECLARE @MaxID AS INT
	INSERT INTO bsCpStatus (cpMainID,ApplyInfo,StatusID,VerifyMan,VerifyInfo,VerifyDate) 
		VALUES(@cpMainID,@ApplyInfo,@StatusID,@VerifyMan,@VerifyInfo,GETDATE())
	SET @MaxID = @@IDENTITY
END TRY
BEGIN CATCH
	GOTO ERR
END CATCH
RETURN @MaxID
ERR:
BEGIN
	RETURN 0
END














GO
/****** Object:  StoredProcedure [dbo].[bpBsCpVerifyBycpMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[bpBsCpVerifyBycpMainIDSelect]
(
	@cpMainID INT
)
AS
BEGIN
	SELECT * FROM BsCpVerify WITH(NOLOCK) WHERE cpMainID=@cpMainID
END














GO
/****** Object:  StoredProcedure [dbo].[bpBsCpVerifyInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--修改Harry
--2018-5-15 
--增加审核记录,用于计算审核延误1
CREATE PROCEDURE [dbo].[bpBsCpVerifyInsert]
(
	@cpMainID INT,
	@VerifyMan INT,
	@VerifyResult TINYINT,
	@VerifyInfo NVARCHAR(200)
)
AS
SET NOCOUNT ON
BEGIN
	INSERT INTO bsCpVerify(cpMainID,VerifyMan,VerifyDate,VerifyResult,VerifyInfo)
	VALUES(@cpMainID,@VerifyMan,GETDATE(),@VerifyResult,@VerifyInfo)
	--harry begin
	DECLARE @VerifyId INT,  @submit DATETIME 
        SELECT TOP 1 @submit=adddate FROM bsCpModify  WHERE cpMainID=@cpMainID ORDER BY adddate DESC 
        IF @submit is NULL 
            SET @submit=GETDATE()
	SELECT @VerifyId=@@IDENTITY
	INSERT INTO logdb..VerifyDelayLog(verifyType, relationId, submitDate, verifyDate, verifyMan)
	SELECT 1,@VerifyId,  @submit, GETDATE(), @VerifyMan
	
	RETURN @VerifyId
END


GO
/****** Object:  StoredProcedure [dbo].[bpbsCpVerifyLogBybsCpVerifyIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[bpbsCpVerifyLogBybsCpVerifyIDSelect]
(
    @bsCpVerifyID INT
)
AS
BEGIN
    SELECT * FROM bsCpVerifyLog WITH(NOLOCK) WHERE bsCpVerifyID = @bsCpVerifyID
END














GO
/****** Object:  StoredProcedure [dbo].[bpBsCpVerifyLogSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[bpBsCpVerifyLogSelect]
(
	@ID INT
)
AS
BEGIN
	SELECT * FROM BsCpVerifyLog WITH(NOLOCK) WHERE ID=@ID
END














GO
/****** Object:  StoredProcedure [dbo].[bpBsCpVerifySelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[bpBsCpVerifySelect]
(
	@cpMainID INT
)
AS
BEGIN
	SELECT Top 1 * FROM BsCpVerify WITH(NOLOCK) WHERE cpMainID=@cpMainID ORDER BY VerifyDate DESC
END














GO
/****** Object:  StoredProcedure [dbo].[bpbsCvModifyByCvMainIDDelete]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.12.26
--创建人：Nick
--说明：删除bsCvModify
--#####################################################
CREATE PROCEDURE [dbo].[bpbsCvModifyByCvMainIDDelete]
(
	@CvMainID INT
)
AS
BEGIN
	DELETE FROM bsCvModify WHERE Location='ac5' And cvMainID = @CvMainID
END 

GO
/****** Object:  StoredProcedure [dbo].[bpBsCvModifyByPaMainIDUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[bpBsCvModifyByPaMainIDUpdate]
(
	@paMainID INT,
	@bsCvVerifyID INT,
	@Pass INT		--100通过，2不通过
)
AS
BEGIN TRAN
	BEGIN TRY
		DECLARE @bCh AS BIT
		DECLARE @bEng AS BIT
		SET @bCh = 0
		SET @bEng = 0
		IF EXISTS(SELECT 'X' FROM bsCvModify WITH(NOLOCK) WHERE paMainID = @paMainID AND SUBSTRING(Location, 2, 1) = 'c')
			SET @bCh = 1
		IF EXISTS(SELECT 'X' FROM bsCvModify WITH(NOLOCK) WHERE paMainID = @paMainID AND SUBSTRING(Location, 2, 1) = 'c')
			SET @bEng = 1

		IF @Pass = 100
			BEGIN
				INSERT INTO bsCvVerifyLog(bsCvVerifyID,SubID,Location,AddDate,OldValue)
					SELECT @bsCvVerifyID,SubID,Location,AddDate,ColValue FROM bsCvModify WITH(NOLOCK) WHERE paMainID = @paMainID

				UPDATE bsCvVerify SET VerifyResult = 100,VerifyInfo='本次审核所有简历审核通过' WHERE ID = @bsCvVerifyID
				IF @bCH = 1
					BEGIN
						UPDATE cvMain SET VerifyResult=100
							WHERE ID IN (SELECT cvMainID FROM bsCvModify WITH(NOLOCK) WHERE paMainID=@paMainID)
					END
				IF @bEng = 1
					BEGIN
						UPDATE cvMain SET VerifyResultEng=100
							WHERE ID IN (SELECT cvMainID FROM bsCvModify WITH(NOLOCK) WHERE paMainID=@paMainID)
					END
				DELETE FROM bsCvModify WHERE paMainID = @paMainID	
			END
		ELSE
			BEGIN
				INSERT INTO bsCvVerifyLog(bsCvVerifyID,SubID,Location,AddDate,OldValue,VerifyResult,VerifyInfo)
					SELECT @bsCvVerifyID,SubID,Location,AddDate,ColValue,1,'本次审核所有简历审核不通过'
					FROM bsCvModify WITH(NOLOCK) WHERE paMainID = @paMainID
				
				UPDATE bsCvModify SET VerifyInfo='本次审核所有简历审核不通过' WHERE paMainID=@paMainID
				UPDATE bsCvVerify SET VerifyResult = 2,VerifyInfo='本次审核所有简历审核不通过' WHERE ID = @bsCvVerifyID
				IF @bCH = 1
					BEGIN
						UPDATE cvMain SET VerifyResult=@Pass
							WHERE ID IN (SELECT cvMainID FROM bsCvModify WITH(NOLOCK) WHERE paMainID=@paMainID)
					END
				IF @bEng = 1
					BEGIN
						UPDATE cvMain SET VerifyResultEng=@Pass
							WHERE ID IN (SELECT cvMainID FROM bsCvModify WITH(NOLOCK) WHERE paMainID=@paMainID)
					END				
			END
	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH
COMMIT TRAN
RETURN 1
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END














GO
/****** Object:  StoredProcedure [dbo].[bpBsCvModifyUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[bpBsCvModifyUpdate]
(
	@ID INT,
	@bsCvVerifyID INT,
	@cvMainID INT,
	@VerifyInfo NVARCHAR(200)
)
AS
BEGIN TRY
	DECLARE @MaxID AS INT
	IF ISNULL(@VerifyInfo, '') =''
		BEGIN
			INSERT INTO bsCvVerifyLog(bsCvVerifyID,cvMainID,SubID,Location,AddDate,OldValue)
				SELECT @bsCvVerifyID,@cvMainID,SubID,Location,AddDate,ColValue FROM bsCvModify WITH(NOLOCK) WHERE ID = @ID
			SET @MaxID = @@IDENTITY
			DELETE FROM bsCvModify WHERE ID = @ID
		END
	ELSE
		BEGIN
			INSERT INTO bsCvVerifyLog(bsCvVerifyID,cvMainID,SubID,Location,AddDate,OldValue,VerifyResult,VerifyInfo)
				SELECT @bsCvVerifyID,@cvMainID,SubID,Location,AddDate,ColValue,1,@VerifyInfo FROM bsCvModify WITH(NOLOCK) WHERE ID = @ID
			SET @MaxID = @@IDENTITY
			UPDATE bsCvModify SET VerifyInfo=@VerifyInfo WHERE ID=@ID
		END
END TRY
BEGIN CATCH
	GOTO ERR
END CATCH
RETURN 1
ERR:
BEGIN
	RETURN 0
END














GO
/****** Object:  StoredProcedure [dbo].[bpbsCvReviewByCvMainIDDelete]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.12.25
--创建人：Nick
--说明：删除bsCvReview
--#####################################################
CREATE PROCEDURE [dbo].[bpbsCvReviewByCvMainIDDelete]
(
	@CvMainID INT
)
AS
BEGIN
	DELETE FROM bsCvReview WHERE cvMainID = @CvMainID
END 

GO
/****** Object:  StoredProcedure [dbo].[bpbsCvReviewByCvMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.12.24
--创建人：Nick
--说明：根据cvmainid获取bsCvReview
--#####################################################
CREATE PROCEDURE [dbo].[bpbsCvReviewByCvMainIDSelect]
(
	@cvMainID INT
)
AS
BEGIN
	SELECT TOP 10 * FROM bsCvReview WHERE cvMainID = @cvMainID
END 


GO
/****** Object:  StoredProcedure [dbo].[bpbsCvReviewInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.12.25
--创建人：Nick
--说明：插入bsCvReview
--#####################################################
CREATE PROCEDURE [dbo].[bpbsCvReviewInsert]
(
	@CvMainID INT,
	@ManagerUserID INT,
	@Reason VARCHAR(500)
)
AS
BEGIN
	INSERT bsCvReview(cvMainID,VerifyMan,VerifyInfo)
	VALUES (@CvMainID,@ManagerUserID,@Reason)
END 

GO
/****** Object:  StoredProcedure [dbo].[bpBsCvVerifyInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--修改Harry
--2017-2-21
--增加审核记录,用于计算审核延误 编号2
CREATE PROCEDURE [dbo].[bpBsCvVerifyInsert]
(
	@cvMainID INT,
	@VerifyMan INT,
	@VerifyResult TINYINT,
	@VerifyInfo NVARCHAR(200)
)
AS
SET NOCOUNT ON
BEGIN
	DECLARE @bsCvVerifyID AS INT
	INSERT INTO bsCvVerify(cvMainID, VerifyMan, VerifyDate, VerifyResult, VerifyInfo)
	VALUES(@cvMainID, @VerifyMan, GETDATE(), @VerifyResult, @VerifyInfo)
	SET @bsCvVerifyID = @@IDENTITY
    
    --插入审核延误记录表
    
	INSERT INTO logdb..VerifyDelayLog(verifyType, relationId, submitDate, verifyDate, verifyMan)
	SELECT 2,@bsCvVerifyID,(SELECT TOP 1 adddate FROM bsCvModify WHERE cvMainID=@cvMainID ORDER BY adddate DESC), GETDATE(), @VerifyMan
	
	--Harry Begin
	IF @VerifyResult = 10
	BEGIN
		DECLARE @wxFansId INT, @paMainId INT
		SELECT @wxFansId = a.id, @paMainId=b.paMainId
		FROM wxFans a WITH(NOLOCK), cvMain b WITH(NOLOCK) 
		WHERE a.paMainId = b.paMainId 
		AND b.Id = @cvMainID 
		AND a.[Status] = 2

		IF @wxFansId > 0
		BEGIN
			--插入到wxMessageSend表中(7. --简历审核未通过)
			INSERT WxMessageSend2(Templatetype, WxFansID, PaMainId, MainTableId, CvMainID, AddDate)
			SELECT 7, @wxFansId, @paMainId, @bsCvVerifyID, @cvMainID, GETDATE()
		END
		--Harry End
	END

	RETURN @bsCvVerifyID
END

GO
/****** Object:  StoredProcedure [dbo].[bpbsCvVerifyLogBybsCvVerifyIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[bpbsCvVerifyLogBybsCvVerifyIDSelect]
(
    @bsCvVerifyID INT
)
AS
BEGIN
    SELECT * FROM bsCvVerifyLog WITH(NOLOCK) WHERE bsCvVerifyID = @bsCvVerifyID
END














GO
/****** Object:  StoredProcedure [dbo].[bpBsCvVerifySelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[bpBsCvVerifySelect]
(
	@ID INT
)
AS
BEGIN
	SELECT * FROM BsCvVerify WITH(NOLOCK) WHERE ID=@ID
END














GO
/****** Object:  StoredProcedure [dbo].[bpBsCvVerifyUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[bpBsCvVerifyUpdate]
(
	@ID INT,
	@VerifyResult TINYINT
)
AS
BEGIN TRY
	UPDATE bsCvVerify SET VerifyResult=@VerifyResult WHERE ID=@ID
	RETURN 1
END TRY
BEGIN CATCH
	RETURN 0
END CATCH














GO
/****** Object:  StoredProcedure [dbo].[bpbsDeadCompanyByStatisticsSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Mice 123>
-- Create date: <2014-12-09>
-- Description:	<死客户汇总查询>
-- Editer : mice 2014-12-15 增加@strPara条件（权限控制）
-- Editer : mice 2014-12-29 修改激活数量ActiveNum的时间依据为激活时间
-- Editer : mice 2014-12-30 修改激活时间和联系时间差在两个月之内的，激活数有效
-- Editer : mice 2014-12-31 需改bug（left out join 为 full out join）
-- =============================================
CREATE PROCEDURE [dbo].[bpbsDeadCompanyByStatisticsSelect] 
(
	@group INT = 0,
	@value INT = NULL,
	@begintime1 VARCHAR(20) = '',
	@endtime1 VARCHAR(20) = '',
	@begintime2 VARCHAR(20) = '',
	@endtime2 VARCHAR(20) = '',
	@strPara VARCHAR(200) = NULL
)
AS
BEGIN
	DECLARE @SQL AS VARCHAR(3000), @COLS AS VARCHAR(1000), @strWhere AS VARCHAR(300), @activeNumWhere AS VARCHAR(300)
	SELECT @COLS = ' COUNT(c.id) AS totalCOUNT, 
		SUM(CASE ISNULL(c.ActiveDate,0) WHEN 0 THEN 1 ELSE 0 END) AS NotActiveNum, 
		SUM(CASE ISNULL(c.ContactResult,0) WHEN 0 THEN 1 ELSE 0 END) AS COUNT0,
		SUM(CASE c.ContactResult WHEN 1 THEN 1 ELSE 0 END) AS COUNT1,
		SUM(CASE c.ContactResult WHEN 2 THEN 1 ELSE 0 END) AS COUNT2,
		SUM(CASE c.ContactResult WHEN 3 THEN 1 ELSE 0 END) AS COUNT3,
		SUM(CASE c.ContactResult WHEN 4 THEN 1 ELSE 0 END) AS COUNT4, 
		SUM(CASE c.ContactResult WHEN 5 THEN 1 ELSE 0 END) AS COUNT5,
		SUM(CASE c.ContactResult WHEN 6 THEN 1 ELSE 0 END) AS COUNT6 ',
		@strWhere = '',
		@activeNumWhere = ''
	
	IF @begintime1 > '' 
	BEGIN
		SET @strWhere = @strWhere + ' AND c.DeadDate > ''' + @begintime1 +''''
		SET @activeNumWhere = @activeNumWhere + ' AND c.DeadDate > ''' + @begintime1 +''''
	END
	IF @endtime1 > ''
	BEGIN
		SET @strWhere = @strWhere + ' AND c.DeadDate < ''' + @endtime1 +''''
		SET @activeNumWhere = @activeNumWhere + ' AND c.DeadDate < ''' + @endtime1 +''''
	END
	IF @begintime2 > ''
	BEGIN
		SET @strWhere = @strWhere + ' AND c.ContactDate > ''' + @begintime2 +''''
		SET @activeNumWhere = @activeNumWhere + ' AND c.ActiveDate > ''' + @begintime2 +''''
	END
	IF @endtime2 > ''
	BEGIN
		SET @strWhere = @strWhere + ' AND C.ContactDate < ''' + @endtime2 +''''
		SET @activeNumWhere = @activeNumWhere + ' AND c.ActiveDate < ''' + @endtime2 +''''
	END
	IF @strPara > ''
	BEGIN
		SET @strWhere = @strWhere + @strPara
		SET @activeNumWhere = @activeNumWhere + @strPara
	END
	IF @value IS NOT NULL AND @VALUE > 0
	BEGIN
		IF @group = 1 -- 按照地区分组查询显示
		BEGIN
			SET @strWhere = @strWhere + ' AND a.dcProvinceID = ' + CONVERT(VARCHAR(10),@value)
			SET @activeNumWhere = @activeNumWhere + ' AND a.dcProvinceID = ' + CONVERT(VARCHAR(10),@value)
		END
		ELSE IF @group = 2 -- 按照招聘顾问工号分组查询显示
		BEGIN
			SET @strWhere = @strWhere + ' AND a.ConsultantID = ' + CONVERT(VARCHAR(10),@value)
			SET @activeNumWhere = @activeNumWhere + ' AND a.ConsultantID = ' + CONVERT(VARCHAR(10),@value)
		END
		ELSE -- 按照部门分组查询显示（默认显示方式）
		BEGIN
			SET @strWhere = @strWhere + ' AND b.deptID = ' + CONVERT(VARCHAR(10),@value)
			SET @activeNumWhere = @activeNumWhere + ' AND b.deptID = ' + CONVERT(VARCHAR(10),@value)
		END	
	END


	IF @group = 1 -- 按照地区分组查询显示
	BEGIN
		SET @SQL = ' SELECT T1.*,T2.* FROM (
			SELECT a.dcProvinceID as groupID,
			( SELECT x.ProvinceName FROM maindb..dcprovince x WITH(NOLOCK) WHERE x.id=a.dcProvinceID) AS groupName, 
			COUNT(1) AS ActiveNum 
			FROM maindb..cpmain a WITH(NOLOCK) , Maindb..bsDeadCompany c WITH(NOLOCK) 
			WHERE a.id = c.cpMainID  AND c.ActiveDate IS NOT NULL 
			AND c.ContactDate IS NOT NULL  AND DATEADD(MONTH,2,c.ContactDate ) >  c.ActiveDate
			' + @activeNumWhere + '
			GROUP BY a.dcProvinceID ) 
			T1 FULL OUTER JOIN (
			SELECT a.dcProvinceID as groupID2 , 
			( SELECT x.ProvinceName FROM maindb..dcprovince x WITH(NOLOCK) WHERE x.id=a.dcProvinceID) AS groupName2, 
			' + @COLS +'
			FROM maindb..cpmain a WITH(NOLOCK) , Maindb..bsDeadCompany c WITH(NOLOCK) 
			WHERE a.id = c.cpMainID
			' + @strWhere + '
			GROUP BY a.dcProvinceID  ) 
			T2 ON T2.groupID2 = T1.groupID 
			ORDER BY T2.groupID2, T1.groupID '

	END
	ELSE IF @group = 2 -- 按照招聘顾问工号分组查询显示
	BEGIN
		SET @SQL = ' SELECT T1.*,T2.* FROM (
			SELECT a.ConsultantID as groupID,
			( SELECT x.name FROM maindb..manageruser x WITH(NOLOCK) WHERE x.id=a.ConsultantID) AS groupName, 
			COUNT(1) AS ActiveNum 
			FROM maindb..cpmain a WITH(NOLOCK) , Maindb..bsDeadCompany c WITH(NOLOCK) 
			WHERE a.id = c.cpMainID  AND c.ActiveDate IS NOT NULL 
			AND c.ContactDate IS NOT NULL  AND DATEADD(MONTH,2,c.ContactDate ) >  c.ActiveDate
			' + @activeNumWhere + '
			GROUP BY a.ConsultantID ) 
			T1 FULL OUTER JOIN (
			SELECT a.ConsultantID as groupID2 , 
			( SELECT x.name FROM maindb..manageruser x WITH(NOLOCK) WHERE x.id=a.ConsultantID) AS groupName2, 
			' + @COLS +'
			FROM maindb..cpmain a WITH(NOLOCK) , Maindb..bsDeadCompany c WITH(NOLOCK) 
			WHERE a.id = c.cpMainID
			' + @strWhere + '
			GROUP BY a.ConsultantID  ) 
			T2 ON T2.groupID2 = T1.groupID 
			ORDER BY T2.groupID2, T1.groupID '
	END
	ELSE -- 按照部门分组查询显示（默认显示方式）
	BEGIN
		SET @SQL = ' SELECT T1.*,T2.* FROM (
			SELECT b.deptID  as groupID,
			( SELECT x.DeptName FROM maindb..dept x WITH(NOLOCK) WHERE x.id=b.deptID ) AS groupName, 
			COUNT(1) AS ActiveNum 
			FROM maindb..cpmain a WITH(NOLOCK), oadb..manageruser b WITH(NOLOCK), Maindb..bsDeadCompany c WITH(NOLOCK) 
			WHERE a.ConsultantID = b.id AND a.id = c.cpMainID  AND c.ActiveDate IS NOT NULL 
			AND c.ContactDate IS NOT NULL  AND DATEADD(MONTH,2,c.ContactDate ) >  c.ActiveDate
			' + @activeNumWhere + '
			GROUP BY b.deptID ) 
			T1 FULL OUTER JOIN (
			SELECT b.deptID  as groupID2 , 
			( SELECT x.DeptName FROM maindb..dept x WITH(NOLOCK) WHERE x.id=b.deptID ) AS groupName2,
			' + @COLS +'
			FROM maindb..cpmain a WITH(NOLOCK), oadb..manageruser b WITH(NOLOCK), Maindb..bsDeadCompany c WITH(NOLOCK)
			WHERE a.ConsultantID = b.id AND a.id = c.cpMainID
			' + @strWhere + '
			GROUP BY b.deptID  ) 
			T2 ON T2.groupID2 = T1.groupID 
			ORDER BY T2.groupID2, T1.groupID '
	END
	--PRINT @Sql
	EXEC(@SQL)
END

GO
/****** Object:  StoredProcedure [dbo].[bpbsDeadCompanyInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Mice 123>
-- Create date: <2014-12-05>
-- Description:	<死客户记录生成>
-- Editer: 修改Mice 2015-2-5 修改时间格式为 2015-02-05
-- =============================================
CREATE PROCEDURE [dbo].[bpbsDeadCompanyInsert]
AS
BEGIN
	SET NOCOUNT ON
	DECLARE @begindate AS VARCHAR(100), @enddate AS VARCHAR(100), @datetime AS VARCHAR(100)
	SELECT @enddate=CONVERT(VARCHAR(100), DATEADD(MONTH,-6,getDate()), 23) ,
		@begindate=CONVERT(VARCHAR(100), DATEADD(MONTH,-7,getDate()), 23),
		@datetime=CONVERT(VARCHAR(100), DATEADD(MONTH,-1,getDate()), 23)

	IF NOT EXISTS(SELECT 'X' FROM Maindb..bsDeadCompany WITH(NOLOCK))	--初次生成遍历所有的
	BEGIN
		INSERT INTO bsDeadCompany(cpMainID,DeadDate,AddDate)
		SELECT a.ID,a.LastLoginDate,getDate()
		FROM Maindb..cpMain a WITH(NOLOCK)
		WHERE MemberType=2 AND ConsultantDate < @datetime AND LastLoginDate < @enddate
		AND (SELECT COUNT(1) FROM caOrder WITH(NOLOCK) WHERE Paid>0 AND EndDate > @datetime 
			AND (OrderType=1 OR OrderType=2 OR OrderType=8) AND cpMainID=a.id) = 0
		ORDER BY LastLoginDate
	END
	ELSE --遍历新增月份的死客户
	BEGIN
		INSERT INTO bsDeadCompany(cpMainID,DeadDate,AddDate)
		SELECT a.ID,a.LastLoginDate,getDate()
		FROM Maindb..cpMain a WITH(NOLOCK)
		WHERE MemberType=2
		AND ConsultantDate < @datetime 
		AND LastLoginDate < @enddate
		AND LastLoginDate > @begindate 
		AND (SELECT COUNT(1) FROM caOrder WITH(NOLOCK) WHERE Paid>0 AND EndDate > @datetime 
			AND (OrderType=1 OR OrderType=2 OR OrderType=8) AND cpMainID=a.id) = 0
		AND a.Id NOT IN(SELECT cpMainId FROM bsDeadCompany WITH(NOLOCK) WHERE ActiveDate IS NULL)
		ORDER BY LastLoginDate
	END
	SET NOCOUNT OFF
END


GO
/****** Object:  StoredProcedure [dbo].[bpbsDeadCompanySelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Mice 123>
-- Create date: <2014-12-09>
-- Description:	<死客户列表查询>
-- 修改： 2014-12-12 mice 添加strWhere 查询条件
-- 修改： 2014-12-24 mice 增加查询条件（企业ID、企业名称）
-- 修改： 2014-12-30 mice 增加查询条件激活时间
--                        修改联系时间、激活时间为二选一查询
-- 修改： 2015-01-13 john 增加如果valid=0则ContactResult=0 OR IS NULL
-- 修改： 2015-01-20 NICK 加入按照联系活动搜索
-- 修改： 2015-03-20 Mice 加入查询条件 NOT (ActiveDate IS NOT NULL and ContactResult IS NULL ) 
-- 修改： 2018-5-9 Harry  加入当前会员状态
-- 修改： 2018-6-11 Harry 查询联系状态是按照联系时间排序
-- =============================================
-- =============================================
CREATE PROCEDURE [dbo].[bpbsDeadCompanySelect]
(
	@deptid INT = NULL,                --部门ID
	@pid INT = NULL,                   --省份ID
	@valid VARCHAR(5) = NULL,          --联系结果
	@active INT = NULL,                --激活状态
	@manageruserid VARCHAR(50) = NULL, --顾问ID
	@begintime1 VARCHAR(50) = NULL,    --截点时间-起始时间
	@endtime1  VARCHAR(50) = NULL,     --截点时间-终止时间
	@itemtime	INT = 0,               --1.激活时间； 0.联系时间
	@begintime2  VARCHAR(50) = NULL,   --激活/联系时间起始时间
	@endtime2  VARCHAR(50) = NULL,     --激活/联系时间终止时间
	@strWhere  VARCHAR(500) = NULL,    --权限控制语句
	@searchItem INT = 0,               --0.企业ID； 1.企业名称
	@searchText VARCHAR(50) = NULL,    --企业ID/名称
	@Page SMALLINT = 1 ,                --页数
	@ContactID INT
)
AS
BEGIN
	CREATE TABLE #T(
		TitleID BIGINT,
		ID int ,
		cpMainID int,
		ContactDate smalldatetime,
		ContactMan int,
		ContactResult int,
		DeadDate smalldatetime,
		ActiveDate smalldatetime,
		ReMark nvarchar(500),
		AddDate smalldatetime,
		cpName nvarchar(500),
		ConsultantID INT,
		RegDate SMALLDATETIME,
		IsLock BIT,
		LastLoginDate SMALLDATETIME,
		Consultantname nvarchar(50),
		ContactManname nvarchar(50),
		ContactDoneDate SMALLDATETIME,
		ContactDoneID INT,
		ContactDoneMan INT,
		ContactDoneAdd SMALLDATETIME,
		ContactNotDoneDate SMALLDATETIME,
		ContactNotDoneID INT,
		ContactNotDoneMan INT,
		ContactNotDoneAdd SMALLDATETIME,
		TotalNum INT,
		HasPaid BIT,
		MemberType INT
	)
	DECLARE @SQL AS VARCHAR(3000)
	SET @SQL = ' INSERT INTO #T 
		( TitleID, id ,cpMainID, ContactDate,ContactMan,ContactResult,DeadDate ,ActiveDate, ReMark, AddDate,
		cpName,ConsultantID ,RegDate, IsLock,LastLoginDate,MemberType)
		SELECT TOP 3000 ROW_NUMBER() OVER ( ORDER BY a.DeadDate DESC ) AS TitleID ,a.id ,a.cpMainID, a.ContactDate,a.ContactMan,a.ContactResult,a.DeadDate ,a.ActiveDate, a.ReMark, a.AddDate,
		b.name AS cpName, b.ConsultantID, b.RegDate, b.IsLock, b.LastLoginDate,b.MemberType
		FROM Maindb..bsDeadCompany a WITH(NOLOCK) , Maindb..cpMain b WITH(NOLOCK) 
		WHERE a.cpMainID=b.id  AND  NOT (ActiveDate IS NOT NULL and ContactResult IS NULL ) '
	IF @strWhere <> ''
	BEGIN
		SET @SQL = @SQL + @strWhere
	END
	IF @pid > 0
		SET @SQL = @SQL + ' AND b.dcProvinceID = ' + CONVERT(VARCHAR(10),@pid)
	IF @valid <> ''
	BEGIN
		IF @valid = '0'
			SET @SQL = @SQL + ' AND (a.ContactResult = 0 OR a.ContactResult IS NULL)'
		ELSE
			SET @SQL = @SQL + ' AND a.ContactResult = ' + @valid
	END
	IF @active = 1
		SET @SQL = @SQL + ' AND a.ActiveDate IS NOT NULL ' 
	ELSE IF @active = 2
		SET @SQL = @SQL + ' AND a.ActiveDate IS NULL ' 
	IF @manageruserid <> ''
	BEGIN
		SET @SQL = @SQL + ' AND b.ConsultantID = ' + @manageruserid
	END
	ELSE
	BEGIN
		IF @deptid > 0
			SET @SQL = @SQL + ' AND b.ConsultantID  IN ( SELECT x.id FROM maindb..manageruser x WITH(NOLOCK) WHERE x.deptid = ' + CONVERT(VARCHAR(10),@deptid) + ' ) '
	END
	IF @begintime1 <> '' 
	BEGIN
		SET @SQL = @SQL + ' AND a.DeadDate > ''' + @begintime1 +''''
	END
	IF @endtime1 <> ''
	BEGIN
		SET @SQL = @SQL + ' AND a.DeadDate < ''' + @endtime1 +''''
	END
	IF @begintime2 <> ''
	BEGIN
		IF @itemtime = 1
			SET @SQL = @SQL + ' AND a.ActiveDate > ''' + @begintime2 +''''
		ELSE
			SET @SQL = @SQL + ' AND a.ContactDate > ''' + @begintime2 +''''
	END

	--加入按照联系活动情况搜索 nick
	IF @ContactID<>0
	BEGIN
		SET @SQL = @SQL + ' AND (SELECT TOP 1 CloseDate FROM MainDB..contact WITH(NOLOCK) WHERE CompanyId = a.cpMainID ORDER BY CloseDate DESC) < ''' + CONVERT(VARCHAR(50),DATEADD (DAY ,-@ContactID, GETDATE()))+''''
	END
		
	IF @endtime2 <> ''
	BEGIN
		IF @itemtime = 1
			SET @SQL = @SQL + ' AND a.ActiveDate < ''' + @endtime2 +''''
		ELSE
			SET @SQL = @SQL + ' AND a.ContactDate < ''' + @endtime2 +''''
	END
		
	IF @searchText <> ''
	BEGIN
		IF @searchItem = 0
		BEGIN
			SET @SQL = @SQL + '  AND a.cpMainID = '+@searchText
		END
		ELSE
		BEGIN
			SET @SQL = @SQL + '  AND b.Name like  ''%' + @searchText + '%'''
		END
	END
        IF @valid>0
        BEGIN
          SET @SQL = @SQL + ' ORDER BY a.ContactDate DESC'
        END
        ELSE
        BEGIN
           SET @SQL = @SQL + ' ORDER BY a.DeadDate DESC'
        END
	

	EXEC(@SQL)

	UPDATE #T SET Consultantname = (SELECT  c.name FROM Maindb..manageruser c WHERE  c.id = #T.ConsultantID ),
		HasPaid = (SELECT TOP 1 ID FROM Maindb..caOrder WHERE Paid>0 AND OpenDate IS NOT NULL AND cpMainID=#T.cpMainID AND IsDeleted = 0),
		ContactManname = (SELECT  c.name FROM Maindb..manageruser c WHERE  c.id = #T.ContactMan ),
		ContactDoneDate = (SELECT top 1 e.BeginTime FROM maindb..contact e WITH(NOLOCK) WHERE e.companyid=#T.cpMainID AND e.status = 2 ORDER BY e.begintime DESC )  ,
		ContactDoneID = (SELECT top 1 e.ID FROM maindb..contact e WITH(NOLOCK) WHERE e.companyid=#T.cpMainID AND e.status = 2 ORDER BY e.begintime DESC )  ,
		ContactDoneMan = (SELECT top 1 e.ManagerUserID FROM maindb..contact e WITH(NOLOCK) WHERE e.companyid=#T.cpMainID AND e.status = 2 ORDER BY e.begintime DESC ) ,
		ContactDoneAdd = (SELECT top 1 e.AddDate FROM maindb..contact e WITH(NOLOCK) WHERE e.companyid=#T.cpMainID AND e.status = 2 ORDER BY e.begintime DESC ) , 
		ContactNotDoneDate = (SELECT top 1 e.BeginTime FROM maindb..contact e WITH(NOLOCK) WHERE e.companyid=#T.cpMainID AND e.status = 1 ORDER BY e.begintime DESC )  ,
		ContactNotDoneID = (SELECT top 1 e.ID FROM maindb..contact e WITH(NOLOCK) WHERE e.companyid=#T.cpMainID AND e.status = 1 ORDER BY e.begintime DESC )  ,
		ContactNotDoneMan = (SELECT top 1 e.ManagerUserID FROM maindb..contact e WITH(NOLOCK) WHERE e.companyid=#T.cpMainID AND e.status = 1 ORDER BY e.begintime DESC ) ,
		ContactNotDoneAdd = (SELECT top 1 e.AddDate FROM maindb..contact e WITH(NOLOCK) WHERE e.companyid=#T.cpMainID AND e.status = 1 ORDER BY e.begintime DESC )
	WHERE TitleID > (@Page-1)*20 AND TitleID <= @Page*20

	UPDATE  #T SET TotalNum=( SELECT COUNT(*) FROM #T ) WHERE TitleID > (@Page-1)*20 AND TitleID <= @Page * 20

	SELECT * FROM #T WITH(NOLOCK) WHERE TitleID > (@Page-1) * 20 AND TitleID <= @Page * 20
	DROP TABLE #T
END


GO
/****** Object:  StoredProcedure [dbo].[bpbsJobProblemByCpMainIDDelete]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.12.18
--创建人：Nick
--说明：限制登陆删除bsJobProblem
--#####################################################
CREATE PROCEDURE [dbo].[bpbsJobProblemByCpMainIDDelete]
(
	@CpmainID INT
)
AS
BEGIN 
	DELETE FROM bsJobProblem WHERE cpMainID = @CpmainID
End


GO
/****** Object:  StoredProcedure [dbo].[bpbsJobProblemByCpMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.1.12
--创建人：Nick
--说明：根据cpmainid获取bsJobProblem
--#####################################################
CREATE PROCEDURE [dbo].[bpbsJobProblemByCpMainIDSelect]
(
	@CpMainID INT
)
AS
BEGIN 
	SELECT TOP 1 Reason,AddMan FROM bsJobProblem 
	WHERE cpMainID=@CpMainID ORDER BY AddDate DESC
End

GO
/****** Object:  StoredProcedure [dbo].[bpbsJobProblemDelete]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.1.8
--创建人：Nick
--说明：限制登陆删除bsJobProblem
--#####################################################
CREATE PROCEDURE [dbo].[bpbsJobProblemDelete]
AS
BEGIN 
	DELETE FROM bsJobProblem 
	WHERE cpMainID IN (
		SELECT ID FROM cpMain WITH(NOLOCK) 
		WHERE ID=bsJobProblem.cpMainID 
		AND (
			SELECT COUNT(1) FROM Job WHERE IsDelete=0 AND cpMainID=cpMain.ID
		)=0
	)
End

GO
/****** Object:  StoredProcedure [dbo].[bpbsJobProblemSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.1.8
--创建人：Nick
--说明：获取bsJobProblem
--#####################################################
CREATE PROCEDURE [dbo].[bpbsJobProblemSelect]
AS
BEGIN 
	SELECT a.cpMainID,c.IsLimitLogin,a.Addman,c.consultantid,c.haslicence,Reason,c.RegDate,c.Name cpName,
	a.Adddate From bsJobProblem a With(Nolock),cpMain c With(Nolock) 
	WHERE a.cpMainID=c.ID
End

GO
/****** Object:  StoredProcedure [dbo].[bpbsManagerUserActionInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-----------------
--创建日期：2010-11-15
--创建人：lambo
--功能说明：增加后台用户对单位的操作记录
--用于后台企业用户管理模块
-----------------
CREATE PROCEDURE [dbo].[bpbsManagerUserActionInsert]
(
	@cpMainID INT,
	@Action VARCHAR(100),
	@Reason VARCHAR(200),
	@ManagerUserID INT
)
AS
BEGIN TRY
	DECLARE @MaxID AS INT
	INSERT INTO bsManagerUserAction (cpMainID,Action,Reason,ManagerUserID,AddDate) 
		VALUES(@cpMainID,@Action,@Reason,@ManagerUserID,GETDATE())
	SET @MaxID = @@IDENTITY
END TRY
BEGIN CATCH
	GOTO ERR
END CATCH
RETURN @MaxID
ERR:
BEGIN
	RETURN 0
END














GO
/****** Object:  StoredProcedure [dbo].[bpbsManagerUserActionSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--获取招聘顾问分配记录-------------------
--添加人Harry -----------------------
--添加时间：2014-12-15---------------
CREATE PROCEDURE [dbo].[bpbsManagerUserActionSelect]
(
	@WHERE VARCHAR(2000)
)
AS 
BEGIN
	DECLARE @SQL AS VARCHAR(2000)
	SET @WHERE = dbo.SafeSql(@WHERE)
	SET	@SQL='
		SELECT top 2000 *,
			(SELECT Name 
			FROM cpMain WITH(NOLOCK) 
			WHERE cpMain.Id = bsManagerUserAction.cpMainID) CompanyName,
			(SELECT regdate 
			FROM cpMain WITH(NOLOCK) 
			WHERE cpMain.Id = bsManagerUserAction.cpMainID) regdate 
		FROM bsManagerUserAction WITH(NOLOCK) 
		WHERE 1=1 '+ @WHERE
	EXEC(@SQL) 
END  


GO
/****** Object:  StoredProcedure [dbo].[bpbsMobileMessageDelete]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--bpbsMobileMessageDelete 100
--#####################################################
--创建时间：2015-01-28
--创建人：Andy
--说明：删除一条短信推广内容
--#####################################################
CREATE PROCEDURE [dbo].[bpbsMobileMessageDelete]
(		
	@ID INT	
)
AS
BEGIN
	DELETE FROM bsMobileMessage WHERE ID = @ID
END
GO
/****** Object:  StoredProcedure [dbo].[bpbsMobileMessageSave]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--bpbsMobileMessageSave 1009,32, '2015-01-01', '2016-01-01', 'TEST1', 119
--#####################################################
--创建时间：2015-01-28
--创建人：Andy
--说明：保存一条短信推广内容
--#####################################################
CREATE PROCEDURE [dbo].[bpbsMobileMessageSave]
(		
	@ID INT, --如果=0，则是insert	
	@ProvinceID INT,
	@BeginTime DATETIME,
	@EndTime DATETIME,
	@Message NVARCHAR(1000),
	@ManagerUserID INT	
)
AS
BEGIN
	IF @ID = 0
		INSERT INTO bsMobileMessage(dcProvinceId, [Message], BeginDate, EndDate, AddMan, AddDate)
		VALUES(@ProvinceID, @Message, @BeginTime, @EndTime, @ManagerUserID, GETDATE())
	ELSE
		UPDATE bsMobileMessage
		SET dcProvinceID = @ProvinceID, [Message] = @Message, BeginDate = @BeginTime, EndDate = @EndTime 
		WHERE ID = @ID
END


GO
/****** Object:  StoredProcedure [dbo].[bpbsMobileMessageSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--bpbsMobileMessageSelect 1,0,'', '2011-01-01'
--创建人 Andy
--时间 2015-01-28
--查询短信推广内容列表
CREATE PROCEDURE [dbo].[bpbsMobileMessageSelect] 
(		
	@ProvinceID INT,	
	@DateType INT,--0:开始时间，1：结束时间，2：添加时间
	@BeginDate VARCHAR(10),	
	@EndDate VARCHAR(10)	
)
AS
BEGIN			
	DECLARE @SQL VARCHAR(1000)	
	SET @SQL = 'SELECT * FROM bsMobileMessage WITH(NOLOCK) WHERE 1 = 1 '		
	
	IF @ProvinceID > 0	
		SET @SQL = @SQL + ' AND dcProvinceID = ' + LTRIM(STR(@ProvinceID))	
	
	IF @DateType = 0
		BEGIN 		
		IF LEN(@BeginDate) > 0
			SET @SQL = @SQL + ' AND BeginDate >= ''' + @BeginDate + ''''
		IF LEN(@EndDate) > 0
			SET @SQL = @SQL + ' AND BeginDate <= ''' + @EndDate + ''''			  
		END
	IF @DateType = 1
		BEGIN 		
		IF LEN(@BeginDate) > 0
			SET @SQL = @SQL + ' AND EndDate >= ''' + @BeginDate + ''''
		IF LEN(@EndDate) > 0
			SET @SQL = @SQL + ' AND EndDate <= ''' + @EndDate + ''''			  
		END
	ELSE IF @DateType = 2
		BEGIN 		
		IF LEN(@BeginDate) > 0
			SET @SQL = @SQL + ' AND AddDate >= ''' + @BeginDate + ''''
		IF LEN(@EndDate) > 0
			SET @SQL = @SQL + ' AND AddDate <= ''' + @EndDate + ''''	  
		END	
		
	SET @SQL = @SQL + ' ORDER BY EndDate DESC, ID DESC '  
	--PRINT(@SQL)
	EXEC (@SQL)
END
GO
/****** Object:  StoredProcedure [dbo].[bpbsMobileSpreadByCountSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2015.2.3
--创建人：Andy
--说明：根据条件获取bsMobileSpread的行数
--#####################################################
--bpbsMobileSpreadByCountSelect 1, '20140101'
CREATE PROCEDURE [dbo].[bpbsMobileSpreadByCountSelect]
(	
	@AddMan INT, --被查询的ID
	@ExportDate VARCHAR(8) --20130805	
)
AS
BEGIN	
	SELECT Count(*) Cnt 
	FROM bsMobileSpread 
	WHERE AddMan = @AddMan AND ExportDate = @ExportDate 
END


GO
/****** Object:  StoredProcedure [dbo].[bpbsMobileSpreadByExportMobileNoSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--bpbsMobileSpreadByExportMobileNoSelect ' ', 119
--创建人 Andy
--时间 2015-01-23
--导出用户信息员短信推广内容手机号
CREATE PROCEDURE [dbo].[bpbsMobileSpreadByExportMobileNoSelect] 
(	
	@Where VARCHAR(1000),
	@AddMan INT
)
AS
BEGIN	
	SET @Where = dbo.SafeSql(@Where)

	--查询共有多少条记录
	DECLARE @Cnt INT
	SELECT @Cnt = Count(*) 
	FROM bsMobileSpread 
	WHERE AddMan = @AddMan AND ExportDate = CONVERT(VARCHAR(10), GETDATE(), 112)

	DECLARE @CntLeave INT
	SET @CntLeave = 100 - @Cnt
	IF @CntLeave < 0
		SET @CntLeave = 100
	ELSE IF @CntLeave > 100
		SET @CntLeave = 100

	--更新日期
	DECLARE @SQL VARCHAR(1000)
	SET @SQL = '
		UPDATE bsMobileSpread 
		SET ExportDate = CONVERT(VARCHAR(8), GETDATE(), 112)' 	
	SET @SQL = @SQL + ' WHERE ID IN(SELECT TOP '+ LTRIM(STR(@Cnt)) + ' ID FROM bsMobileSpread ' 
	SET @SQL = @SQL + @Where + ' )'
	--PRINT(@SQL)
	EXEC (@SQL)	
	
	--查出结果
	SELECT MobileNO
	FROM bsMobileSpread 
	WHERE AddMan = @AddMan AND ExportDate = CONVERT(VARCHAR(10), GETDATE(), 112)
	
END
GO
/****** Object:  StoredProcedure [dbo].[bpbsMobileSpreadByExportSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


--bpbsMobileSpreadByExportSelect 1,1,1,'2010-01-01', '2011-01-01',1,'II'
--创建人 Andy
--时间 2015-01-23
--查询短信推广内容列表,用于导出
CREATE PROCEDURE [dbo].[bpbsMobileSpreadByExportSelect] 
(
	@Cnt INT,		
	@AddMan INT,
	@ProvinceID INT,	
	@BeginDate VARCHAR(10),	
	@EndDate VARCHAR(10),
	@UserType INT,	
	@CompanyName NVARCHAR(50)	
)
AS
BEGIN	
	SET @CompanyName = dbo.SafeSql(@CompanyName)
	SET @EndDate = dbo.SafeSql(@EndDate)	
	SET @BeginDate = dbo.SafeSql(@BeginDate)	
		
	DECLARE @SQL VARCHAR(1000)	
	SET @SQL = 'SELECT TOP ' + LTRIM(STR(@Cnt)) + ' * FROM bsMobileSpread WITH(NOLOCK) '	
	SET @SQL = @SQL + ' WHERE ExportDate IS NULL AND AddMan = ' + LTRIM(STR(@AddMan))	
	
	IF @ProvinceID > 0	
		SET @SQL = @SQL + ' AND ProvinceID = ' + LTRIM(STR(@ProvinceID))	
	IF LEN(@BeginDate) > 0
		SET @SQL = @SQL + ' AND AddDate >= ' + CONVERT(VARCHAR(10), @BeginDate, 120)
	IF LEN(@EndDate) > 0
		SET @SQL = @SQL + ' AND AddDate <= ' + CONVERT(VARCHAR(10), @EndDate, 120)			  	
	SET @SQL = @SQL + ' AND HasReturn = 0 And AddDate < GETDATE() - 16 '
	IF @UserType >= 0
		SET @SQL = @SQL + ' AND UserType = ' + LTRIM(STR(@UserType))	
	IF LEN(@CompanyName) > 0	
		SET @SQL = @SQL + ' AND CompanyName LIKE ''%' + LTRIM(@CompanyName) + '%'''
	
	SET @SQL = @SQL + ' ORDER BY ID DESC' 
	--PRINT(@SQL)
	EXEC (@SQL)
END


GO
/****** Object:  StoredProcedure [dbo].[bpbsMobileSpreadDelete]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--bpbsMobileSpreadDelete 1
--创建人 Andy
--时间 2015-01-23
--删除短信推广内容
CREATE PROCEDURE [dbo].[bpbsMobileSpreadDelete] 
(		
	@ID INT
)
AS
BEGIN	
	Delete FROM bsMobileSpread WHERE Id = @ID
END
GO
/****** Object:  StoredProcedure [dbo].[bpbsMobileSpreadSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--bpbsMobileSpreadSelect 1,1,1,'2010-01-01', '2011-01-01',1,1,1, '中国','13889898989','ORDER BY ID DESC'
--创建人 Andy
--时间 2015-01-23
--查询短信推广内容列表
--修改：2015-01-28，Andy 修改之前用str函数处理@CompanyName参数的bug
CREATE PROCEDURE [dbo].[bpbsMobileSpreadSelect] 
(		
	@AddMan INT,
	@ProvinceID INT,	
	@DateType INT,--1:注册时间，2：返回时间，3：审核时间
	@BeginDate DATETIME,	
	@EndDate DATETIME,
	@HasReturn INT,
	@HasAccount INT,
	@UserType INT,	
	@CompanyName NVARCHAR(50),
	@MobileNo VARCHAR(11),
	@Order VARCHAR(50)	
)
AS
SET NOCOUNT ON
DECLARE @Id INT
SET @Id = @@IDENTITY
BEGIN	
	SET @CompanyName = dbo.SafeSql(@CompanyName)
	SET @MobileNo = dbo.SafeSql(@MobileNo)
	SET @Order = dbo.SafeSql(@Order)
		
	DECLARE @SQL VARCHAR(1000)	
	SET @SQL = 'SELECT TOP 2000 * FROM bsMobileSpread WITH(NOLOCK) WHERE 1 = 1 '		
	IF @AddMan > 0	
		SET @SQL = @SQL + ' AND AddMan = ' + LTRIM(STR(@AddMan))	
	IF @ProvinceID > 0	
		SET @SQL = @SQL + ' AND ProvinceID = ' + LTRIM(STR(@ProvinceID))		
	
	IF @DateType = 1
		BEGIN 		
		IF @BeginDate > '2010-1-1'
			SET @SQL = @SQL + ' AND AddDate >= ' + CONVERT(VARCHAR(10), @BeginDate, 120)
		IF @EndDate > '2010-1-1'
			SET @SQL = @SQL + ' AND AddDate <= ' + CONVERT(VARCHAR(10), @EndDate, 120)			  
		END
	ELSE IF @DateType = 2
		BEGIN 		
		IF @BeginDate > '2010-1-1'
			SET @SQL = @SQL + ' AND ReturnDate >= ' + CONVERT(VARCHAR(10), @BeginDate, 120)
		IF @EndDate > '2010-1-1'
			SET @SQL = @SQL + ' AND ReturnDate <= ' + CONVERT(VARCHAR(10), @EndDate, 120)	  
		END
	ELSE IF @DateType = 3
		BEGIN 		
		IF @BeginDate > '2010-1-1'
			SET @SQL = @SQL + ' AND AccountDate >= ' + CONVERT(VARCHAR(10), @BeginDate, 120)
		IF @EndDate > '2010-1-1'
			SET @SQL = @SQL + ' AND AccountDate <= ' + CONVERT(VARCHAR(10), @EndDate, 120)
		END	
	IF @HasReturn > 0
		SET @SQL = @SQL + ' AND HasReturn = ' + LTRIM(STR(@HasReturn))		
	IF @HasAccount > 0
		SET @SQL = @SQL + ' AND HasAccount = ' + LTRIM(STR(@HasAccount))		
	IF @UserType >= 0
		SET @SQL = @SQL + ' AND UserType = ' + LTRIM(STR(@UserType))	
	IF LEN(@CompanyName) > 0	
		SET @SQL = @SQL + ' AND CompanyName LIKE ''%' + LTRIM(@CompanyName) + '%'''
	IF LEN(@MobileNo) > 0	
		SET @SQL = @SQL + ' AND MobileNo = ' + @MobileNo 	
	IF LEN(@Order) > 0	
		SET @SQL = @SQL + ' ' + @Order 
	--PRINT(@SQL)
	EXEC (@SQL)
END 
GO
/****** Object:  StoredProcedure [dbo].[bpBsPaBackLoginInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--创建人 Lambo
--20101111
--个人后台登陆
CREATE PROCEDURE [dbo].[bpBsPaBackLoginInsert]
(
	@paMainID INT,
	@ManagerUserID INT,
	@UID VARCHAR(20) OUTPUT
)
AS
BEGIN
	DECLARE @T AS VARCHAR(20)
	SET @T = CONVERT(VARCHAR(20), CONVERT(DECIMAL(18,12),GETDATE()))
	SET @T = RTRIM(CONVERT(VARCHAR(12), @paMainID)) + '_' + RIGHT(@T,8)
	INSERT INTO BsPaBackLogin (UnqueID,paMainID,ManagerUserID)
	VALUES(@T,@paMainID,@ManagerUserID)
	SET @UID =  @T
END














GO
/****** Object:  StoredProcedure [dbo].[bpBsPaStatusSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[bpBsPaStatusSelect]
(
	@paMainID INT,
	@cvMainID INT,
	@StatusID INT
)
AS
BEGIN
	DECLARE @SQL AS VARCHAR(1000)
	
	SET @SQL = 'SELECT * FROM BsPaStatus WITH(NOLOCK) WHERE paMainID = ' + RTRIM(CONVERT(CHAR(10), @paMainID))
	IF @cvMainID > 0
		SET @SQL = @SQL + '	AND cvMainID = ' + RTRIM(CONVERT(CHAR(10), @cvMainID))
	IF @StatusID > 0
		SET @SQL = @SQL + '	AND StatusID = ' + RTRIM(CONVERT(CHAR(10), @StatusID))
	SET @SQL = @SQL + '	ORDER BY cvMainID,StatusID'
	EXEC(@SQL)
END




GO
/****** Object:  StoredProcedure [dbo].[bpcaCvViewLogByCpMainIDCountNoOpenSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----------------
--创建日期：20110421
--创建人：lambo
--功能说明：查询某单位一周内浏览的非开放简历数
--用于后台客户界面
-----------------
CREATE PROCEDURE [dbo].[bpcaCvViewLogByCpMainIDCountNoOpenSelect]
(
	@cpMainID INT
)
AS
BEGIN
	DECLARE @ViewCount INT
	SELECT @ViewCount=COUNT(1) FROM caCvViewLog a WITH(index(IX_CaCvViewLog_caMainId) NOLOCK),caMain b WITH(NOLOCK),cvMain c WITH(NOLOCK)
		WHERE a.caMainID = b.ID 
		AND a.CvMainID = c.ID
		AND a.AddDate>GETDATE()-7 
		AND b.cpMainID=@cpMainID
		AND c.IsOpen = 0
	RETURN @ViewCount
END














GO
/****** Object:  StoredProcedure [dbo].[bpcaCvViewLogByCpMainIDCountSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----------------
--创建日期：2010-9-14
--创建人：lambo
--功能说明：查询某单位一周内浏览的简历数
--用于后台企业内容显示页面
-----------------
CREATE PROCEDURE [dbo].[bpcaCvViewLogByCpMainIDCountSelect]
(
	@cpMainID INT
)
AS
BEGIN
	DECLARE @ViewCount INT
	SELECT @ViewCount=COUNT(1) FROM caCvViewLog  a WITH(index(IX_CaCvViewLog_caMainId) NOLOCK),caMain b WITH(NOLOCK)
		WHERE a.caMainID = b.ID 
		AND a.AddDate>GETDATE()-7 
		AND b.cpMainID=@cpMainID
	RETURN @ViewCount
END














GO
/****** Object:  StoredProcedure [dbo].[bpcaCvViewLogDelete]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----------------
--创建日期：2010-9-14
--创建人：lambo
--功能说明：删除一条简历浏览记录记录
--用于后台企业浏览简历记录页面
-----------------
CREATE PROCEDURE [dbo].[bpcaCvViewLogDelete]
(
	@cvMainID INT,
	@caMainID INT
)
AS
BEGIN
	DELETE FROM caCvViewLog WHERE cvMainID=@cvMainID AND caMainID=@caMainID 
END














GO
/****** Object:  StoredProcedure [dbo].[bpCaCvViewLogSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----------------
--创建日期：2010-9-14
--创建人：lambo
--功能说明：根据条件查询企业浏览简历记录
--用于企业浏览简历记录页面
--sean update 2013-1-18
--harry 2018-8-14 增加一天内查看简历数量
-----------------
CREATE PROCEDURE [dbo].[bpCaCvViewLogSelect]
(
	@WHERE VARCHAR(1000)
)
AS
BEGIN
	DECLARE @SQL VARCHAR(2000)
	SET @Where = dbo.SafeSql(@Where)
	SET @SQL = 
	'SELECT TOP 500 b.ID, COUNT(1) cnt, max(b.Refreshdate) r, SPACE(16) Logincookies
	FROM CaCvViewLog a WITH(NOLOCK INDEX(IX_caCvViewLog_AddDate)),
		cpMain b WITH(NOLOCK),
		caMain c WITH(NOLOCK) 
	WHERE a.caMainid = c.ID 
	AND c.cpMainid = b.ID 
	@where
	GROUP BY b.ID
	HAVING Count(1) > 20
	ORDER BY cnt DESC, b.ID'
	SET @Sql = REPLACE(@Sql, '@where', ISNULL(@Where, ''))
	DECLARE @t AS TABLE(
		ID int,
		Cnt int,
		R DATETIME,
		LoginCookie Varchar(16)
	)
	INSERT @t
	EXEC(@SQL)

	UPDATE a
	SET a.Logincookie = b.Logincookies
	FROM @t a, (
		SELECT f.cpMainId, MAX(e.Logincookies) Logincookies
		FROM caLoginlog e with(nolock),
			caMain f with(nolock) 
		WHERE e.caMainID = f.ID 
		AND f.cpMainId IN(SELECT id FROM @t)
		AND e.LoginCookies <> '注册登录'
		GROUP BY f.cpMainID) b
	WHERE a.ID = b.cpMainId

	SELECT * FROM @t
END















GO
/****** Object:  StoredProcedure [dbo].[bpCaFeePageViewLogSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--获取单位点击收费页面记录-----------
--添加人Harry -----------------------
--添加时间：2014-12-15---------------
CREATE PROCEDURE [dbo].[bpCaFeePageViewLogSelect]
(
	@WHERE VARCHAR(2000)
)
AS 
BEGIN 
	DECLARE @SQL AS VARCHAR(2000)
	SET @WHERE=dbo.SafeSql(@WHERE)
	SET	@SQL='
		SELECT TOP 2000 a.*,b.Name caName,c.MemberType,c.Balance, c.Name cpName,c.ID cpMainID,c.ConsultantID ,c.RegDate,c.LastLoginDate 
		FROM caFeePageViewLog a WITH(NOLOCK) 
		INNER JOIN caMain b WITH(NOLOCK) ON a.caMainID = b.ID 
		INNER JOIN cpMain c WITH(NOLOCK) ON b.cpMainID = c.ID 
		WHERE 1 = 1 ' + @WHERE
	--print @sql
	EXEC(@SQL)  
END  


GO
/****** Object:  StoredProcedure [dbo].[bpCaGetPasswordLogBycpMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


--lambo 20110218
--后台，查询企业取回密码日志
CREATE PROCEDURE [dbo].[bpCaGetPasswordLogBycpMainIDSelect]
(
	@cpMainID INT
)
AS
BEGIN
	SELECT a.* ,b.Name caName, c.Name cpName FROM caGetPasswordLog a WITH (NOLOCK)
		INNER JOIN caMain b  WITH (NOLOCK)
		ON a.caMainID = b.ID
		INNER JOIN cpMain c  WITH (NOLOCK)
		ON b.cpMainID = c.ID
		WHERE c.ID = @cpMainID
END














GO
/****** Object:  StoredProcedure [dbo].[bpCaLoginLogByAddDateCpMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----------------
--创建日期：2010-9-14
--创建人：lambo
--功能说明：根据登陆时间和企业编号企业登陆记录
--用于后台企业登陆明显页面
-----------------
CREATE PROCEDURE [dbo].[bpCaLoginLogByAddDateCpMainIDSelect]
(
	@AddDate VARCHAR(20),
	@cpMainID INT
)
AS
BEGIN
	SELECT b.cpMainID,a.cpMainName,a.AddDate,a.LoginIp,a.LoginCookies 
	FROM caloginlog a WITH(NOLOCK),caMain b WITH(NOLOCK)
	WHERE a.caMainID = b.ID
		AND CONVERT(VARCHAR(200),a.AddDate,112)<=@AddDate
		AND b.cpMainID = @cpMainID
	ORDER BY a.AddDate
END














GO
/****** Object:  StoredProcedure [dbo].[bpCaLoginLogByAddDateLoginCookiesSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----------------
--创建日期：2010-9-14
--创建人：lambo
--功能说明：根据登陆时间和机器码查询企业登陆记录
--用于后台非法机器码嫌疑页面
-----------------
CREATE PROCEDURE [dbo].[bpCaLoginLogByAddDateLoginCookiesSelect]
(
	@AddDate VARCHAR(30),
	@LoginCookies VARCHAR(30)
)
AS
BEGIN
	SELECT c.ID,a.cpMainName Name,a.AddDate,a.LoginCookies,a.LoginIP,c.HasLicence,c.dcProvinceID,c.consultantID,c.RegDate,d.HasPassed,d.IP,d.CheckDate,d.ID LicenceID 
	FROM caLoginLog a WITH(NOLOCK) 
		INNER JOIN caMain b WITH(NOLOCK) ON  a.caMainID = b.ID 
		INNER JOIN cpMain c WITH(NOLOCK) ON b.cpMainID = c.ID 
		LEFT JOIN cpLicence d WITH(NOLOCK) ON d.cpMainID = c.ID 
	WHERE a.LoginCookies = @LoginCookies
		AND CONVERT(VARCHAR(20),a.AddDate,112)=CONVERT(VARCHAR(20),@AddDate)
END














GO
/****** Object:  StoredProcedure [dbo].[bpCaLoginLogByAddDateLoginIPSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[bpCaLoginLogByAddDateLoginIPSelect]
(
	@AddDate VARCHAR(8),
	@IP VARCHAR(31),
	@OrderBy VARCHAR(50)
)
AS
BEGIN
	DECLARE @SQL VARCHAR(2000)
	SET @SQL = 'SELECT c.ID,a.cpMainName Name,a.AddDate,a.LoginCookies,a.LoginIP,c.HasLicence,c.dcProvinceID,c.RegDate,c.consultantID,d.HasPassed,d.IP,d.CheckDate,d.ID LicenceID '
	SET @SQL = @SQL + 'FROM caLoginLog a WITH(NOLOCK) '
	SET @SQL = @SQL + 'INNER JOIN caMain b WITH(NOLOCK) ON  a.caMainID = b.ID '
	SET @SQL = @SQL + 'INNER JOIN cpMain c WITH(NOLOCK) ON b.cpMainID = c.ID '
	SET @SQL = @SQL + 'LEFT JOIN cpLicence d WITH(NOLOCK) ON d.cpMainID = c.ID '
	SET @SQL = @SQL + 'WHERE a.LoginIP = ''' + @IP + ''''
	SET @SQL = @SQL + '	AND CONVERT(VARCHAR(8),a.AddDate,112)=''' + @AddDate + ''''
	IF LEN(@OrderBy) > 0
	BEGIN
		SET @OrderBy = dbo.SafeSql(@OrderBy)
		SET @SQL = @SQL + 'ORDER BY ' + @OrderBy
	END
	EXEC(@SQL)
END














GO
/****** Object:  StoredProcedure [dbo].[bpCaLoginLogBycpMainIDOneSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.12.9
--创建人：John
--说明：获取企业用户最新的登录机器码
--#####################################################
CREATE PROCEDURE [dbo].[bpCaLoginLogBycpMainIDOneSelect]
(
	@cpMainID INT
)
AS
BEGIN 
	SELECT TOP 1 LoginIp, LoginCookies
	FROM caLoginLog a, caMain b 
	WHERE a.caMainid = b.id 
	AND cpMainid = @cpMainID 
	ORDER BY a.AddDate DESC
END

GO
/****** Object:  StoredProcedure [dbo].[bpCaLoginLogBycpMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--###########################
--创建时间：2014.12.10
--创建人：Nick
--说明：根据cpMainID获取caloginlog
--###########################
CREATE PROCEDURE [dbo].[bpCaLoginLogBycpMainIDSelect]
(
	@cpMainID INT
)
AS
BEGIN 
	SELECT TOP 1 LoginIp, LoginCookies
	FROM caLoginLog a, caMain b 
	WHERE a.caMainid = b.id 
	AND b.AccountType = 1 
	AND cpMainid = @cpMainID 
	ORDER BY a.AddDate DESC
END


GO
/****** Object:  StoredProcedure [dbo].[bpCaLoginLogByLastLoginIPSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--Lambo 20101113
--查询单位的上次登陆IP
CREATE PROCEDURE [dbo].[bpCaLoginLogByLastLoginIPSelect]
(
    @cpMainID INT
)
AS
BEGIN
    SELECT TOP 2 a.LoginIP  
	FROM caLoginLog a WITH(NOLOCK) ,caMain b WITH(NOLOCK) 
    WHERE a.caMainID = b.ID
	AND b.cpMainID = @cpMainID
	ORDER BY a.ID DESC
END








GO
/****** Object:  StoredProcedure [dbo].[bpCaLoginLogGroupByCookiesSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----------------
--创建日期：2010-9-14
--创建人：lambo
--功能说明：倒序排列某天同一个机器码登录的企业数
--用于后台非法机器码登录嫌疑页面
-----------------
CREATE PROCEDURE [dbo].[bpCaLoginLogGroupByCookiesSelect]
(
	@AddDate VARCHAR(20)
)
AS
BEGIN
	SELECT COUNT(DISTINCT b.cpMainID) cnt,a.loginCookies
	FROM caloginlog a WITH(NOLOCK),caMain b WITH(NOLOCK)
	WHERE a.caMainID = b.ID
	AND CONVERT(VARCHAR(20),a.AddDate,112)=@AddDate
	GROUP BY a.loginCookies HAVING COUNT(DISTINCT b.cpMainID)>1 
	ORDER BY cnt DESC
END














GO
/****** Object:  StoredProcedure [dbo].[bpCaLoginLogGroupByIPAddDateSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[bpCaLoginLogGroupByIPAddDateSelect]
(
	@Day INT
)
AS
BEGIN
	SELECT TOP 500 COUNT(DISTINCT b.cpMainID) cnt,a.loginIP 
	FROM caloginlog a WITH(NOLOCK),caMain b WITH(NOLOCK)
	WHERE a.caMainID = b.ID
	AND a.AddDate > = GETDATE() - @Day
	GROUP BY a.loginIP HAVING COUNT(DISTINCT b.cpMainID)>1
	ORDER BY cnt DESC
END














GO
/****** Object:  StoredProcedure [dbo].[bpCaLoginLogGroupByIPSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----------------
--创建日期：2010-9-14
--创建人：lambo
--功能说明：倒序排列某天同一个IP登录的企业数
--用于后台非法IP登录嫌疑页面
-----------------
CREATE PROCEDURE [dbo].[bpCaLoginLogGroupByIPSelect]
(
	@AddDate VARCHAR(20)
)
AS
BEGIN
	SELECT COUNT(DISTINCT b.cpMainID) cnt,a.loginIP 
	FROM caloginlog a WITH(NOLOCK),caMain b WITH(NOLOCK)
	WHERE a.caMainID = b.ID
	AND CONVERT(VARCHAR(20),a.AddDate,112)=@AddDate
	GROUP BY a.loginIP HAVING COUNT(DISTINCT b.cpMainID)>1
	ORDER BY cnt DESC
END














GO
/****** Object:  StoredProcedure [dbo].[bpCaMainByBeVerifingSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[bpCaMainByBeVerifingSelect]
    @IDS VARCHAR(1000)
AS
BEGIN TRY
	DECLARE @caID Table(ID INT NULL)
	DECLARE @I AS INT
	SET @I= CHARINDEX(',',@IDS)

	WHILE @I >= 1
		BEGIN
			IF LEFT(@IDS, @I - 1) > '' 
				INSERT @caID VALUES(LEFT(@IDS, @I - 1))
			SET @IDS = SUBSTRING(@IDS, @I + 1, LEN(@IDS) - @I)
			SET @I = CHARINDEX(',', @IDS)
		END
	IF @I < 1
	INSERT @caID VALUES(@IDS)

    SELECT
        a.ID,
        RegDate,
        AccountType,
        UserName,
        Name,
        Gender,
        Title,
        Dept,
        TelePhone,
        Mobile,
        Fax,
        EMail,
        IsPause,
        IsDelete,
        LastModifyDate
    FROM caMain a WITH(NOLOCK), @caID b
    WHERE a.ID = b.ID
	AND a.IsDelete = 0
END TRY
BEGIN CATCH
END CATCH














GO
/****** Object:  StoredProcedure [dbo].[bpCaMainByIsPauseUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--Lambo 20101114
--修改个单位非管理员用户的状态
--用于后台单位显示页面

CREATE PROCEDURE [dbo].[bpCaMainByIsPauseUpdate]
(
	@ID INT,
	@maxUserNumber INT,
	@cpMainId INT
)
AS
BEGIN
	BEGIN TRY
		DECLARE @IsPause BIT
		SELECT @IsPause = IsPause FROM caMain WHERE ID = @ID
		IF @IsPause=1
		BEGIN
			DECLARE @UserNum AS INT
			SELECT @UserNum=COUNT(*) FROM caMain 
				WHERE IsDelete=0 AND IsPause=0 AND AccountType<>1 AND cpMainID=@cpMainID
			IF @maxUserNumber<=@UserNum
				GOTO err
		END
		ELSE
		BEGIN
			UPDATE Job Set IssueEnd = GETDATE()-1 WHERE caMainID = @ID AND cpMainID=@cpMainID
		END 
		UPDATE caMain SET IsPause = IsPause-1 WHERE ID=@ID
		RETURN 1
	END TRY
	BEGIN CATCH
		RETURN 0
	END CATCH
END
err:
RETURN -1














GO
/****** Object:  StoredProcedure [dbo].[bpCaMainByIsShowEmailContactUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[bpCaMainByIsShowEmailContactUpdate]
(
	@caMainId INT
)
AS
SET NOCOUNT ON
BEGIN
	UPDATE caMain SET IsShowEmailContact = ISNULL(IsShowEmailContact, 0) - 1 WHERE Id = @caMainId
	DECLARE @Show INT
	SELECT @Show = IsShowEmailContact FROM caMain WITH(NOLOCK) WHERE Id = @caMainId
	SELECT @caMainId caMainId, @Show ShowContact
END

GO
/****** Object:  StoredProcedure [dbo].[bpCaMainByJobIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.1.12
--创建人：Nick
--说明：删除职位获取相关信息
--#####################################################
CREATE PROCEDURE [dbo].[bpCaMainByJobIDSelect]
(
	@JobID VARCHAR(100)
)
AS
BEGIN 
	SELECT a.ID cpmainID,a.Name,b.Email,a.dcSubSiteID,c.Name JobName 
	FROM cpMain a With(Nolock),caMain b With(Nolock),Job c With(Nolock) 
	WHERE c.cpMainID=a.ID 
	AND a.ID=b.cpMainID 
	AND b.AccountType=1 
	AND c.ID IN(SELECT * FROM dbo.fnSplit(@JobID,','))
End

GO
/****** Object:  StoredProcedure [dbo].[bpCaMainDelete]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--lambo 20101115
--后台删除单位非管理员用户
--用于后台单位显示页面
CREATE PROCEDURE [dbo].[bpCaMainDelete]
	@ID INT
AS
BEGIN TRAN
	BEGIN TRY
		UPDATE Job SET IsDelete=1,valid=0 WHERE caMainID = @ID
		DELETE FROM bsCpModify WHERE caMainID = @ID
		UPDATE caMain SET IsDelete=1 WHERE ID=@ID
	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH
COMMIT TRAN
RETURN 1
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END














GO
/****** Object:  StoredProcedure [dbo].[bpCampusBrochureSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Mice 123>
-- Create date: <2014-12-22>
-- Description:	<获取招聘简章列表>
-- 修改： AttachmentName参数的类型为NVARCHAR
-- =============================================
CREATE PROCEDURE [dbo].[bpCampusBrochureSelect]
(
	@Where VARCHAR(500) = '',
	@Page INT = 1
)
AS
BEGIN
	CREATE TABLE #T(
		TitleID BIGINT,
		ID INT ,
		CompanyID INT,
		Title NVARCHAR(100),
		Description NVARCHAR(MAX),
		EndDate SMALLDATETIME,
		[FileName] VARCHAR(100),
		AttachmentName NVARCHAR(100),
		ClickNumber INT,
		AddMan SMALLINT,
		AddDate SMALLDATETIME,
		Source VARCHAR(500),
		SourceName VARCHAR(100),
		OrderBy INT, 
		addManName NVARCHAR(50),
		SubSiteUrl VARCHAR(100),
		SubSiteNames NVARCHAR(300),
		TotalNum INT
	)

	DECLARE @SQL AS VARCHAR(5000)

	SET @SQL = 'INSERT INTO #T
				( TitleID,  ID,CompanyID,Title,Description,EndDate,[FileName],AttachmentName,ClickNumber,AddMan,AddDate,Source,SourceName,OrderBy )
				SELECT ROW_NUMBER() OVER ( ORDER BY a.ID DESC ) AS TitleID , a.ID, a.CompanyID,a.Title,a.Description,a.EndDate,a.FileName,a.AttachmentName,
				a.ClickNumber,a.AddMan, a.AddDate, a.Source, a.SourceName, a.OrderBy
				FROM marketdb..CampusBrochure a WITH(NOLOCK)   
				WHERE 1 = 1   ' 
	IF @Where <> ''
	BEGIN
		SET @Where = dbo.SafeSql(@Where)
		SET @SQL = @SQL + @Where
	END
	SET @SQL = @SQL + '  ORDER BY a.ID DESC '
	EXEC(@SQL)
	UPDATE #T
	SET  addManName = (SELECT TOP 1 [Name] FROM maindb..manageruser y  WITH(NOLOCK)
	WHERE y.id = #T.AddMan), SubSiteUrl = (SELECT TOP 1 y.SubSiteUrl FROM marketdb..CampusBrochureSite x WITH(NOLOCK),maindb..dcSubSite y WITH(NOLOCK) WHERE x.dcSubsiteid = y.id AND CampusBrochure=#T.id),
		SubSiteNames = STUFF((SELECT ','+CONVERT(VARCHAR,y.SubSIteCity) FROM marketdb..CampusBrochureSite x WITH(NOLOCK), maindb..dcSubSite y WITH(NOLOCK)  WHERE x.dcSubsiteid = y.id AND CampusBrochure=#T.ID FOR XML PATH ('')),1,1,'')
	WHERE TitleID > (@Page - 1) * 20
	AND TitleID <= @Page*20

	UPDATE #T
	SET TotalNum = (SELECT COUNT(ID) FROM #T)
	WHERE TitleID > (@Page-1)*20
	AND TitleID <= @Page*20

	SELECT * FROM #T WITH(NOLOCK) WHERE TitleID > (@Page-1)*20 AND TitleID <= @Page*20
	DROP TABLE #T
END


GO
/****** Object:  StoredProcedure [dbo].[bpCaOperationLogSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[bpCaOperationLogSelect]
(
    @cpMainID INT,
	@Operation INT
)
AS
BEGIN
    SELECT a.* FROM caOperationLog a WITH(NOLOCK),caMain b WITH(NOLOCK)
    WHERE a.caMainID = b.ID 
		AND b.cpMainID=@cpMainID
		AND a.Operation =@Operation
	ORDER BY a.ID DESC
END














GO
/****** Object:  StoredProcedure [dbo].[bpcaOrderBy7DayValidSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--根据cpmainid获取有效期>7天的订单
--Lucifer 2014-12-19
CREATE PROCEDURE [dbo].[bpcaOrderBy7DayValidSelect] 
(
	@cpMainID INT
) 
AS 
BEGIN 
	SELECT * FROM maindb..caOrder WITH(NOLOCK)
	WHERE IsDeleted = 0 AND BeginDate<GETDATE() AND EndDate>GETDATE()+7 AND cpMainID=@cpMainID
	AND OrderType = 8
END


GO
/****** Object:  StoredProcedure [dbo].[bpcaOrderByActiveQuotaOpenDateUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--开通简历下载数订单 Lucifer 2014-12-24
CREATE PROCEDURE [dbo].[bpcaOrderByActiveQuotaOpenDateUpdate]
(
	@BeginDate SMALLDATETIME,
	@EndDate SMALLDATETIME,
	@OpenMan SMALLINT,
	@OrderID INT,
	@ActiveQuota INT
)
AS
BEGIN
	UPDATE MainDB..caOrder SET
		BeginDate=@BeginDate,
		EndDate=@EndDate,
		OpenDate=GetDate(),
		OpenMan=@OpenMan,
		ActiveQuota=@ActiveQuota,
		RemainQuota=@ActiveQuota
	WHERE ID=@OrderID
END


GO
/****** Object:  StoredProcedure [dbo].[bpcaOrderByContractUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--更新合同影像 Lucifer 2014-12-9
CREATE PROCEDURE [dbo].[bpcaOrderByContractUpdate]
(
	@ContractFile VARCHAR(50),
	@OrderID INT
)
AS
BEGIN
	UPDATE MainDB..caOrder SET ContractFile=@ContractFile WHERE ID=@OrderID
END


GO
/****** Object:  StoredProcedure [dbo].[bpCaorderByCpMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--创建人 Andy
--时间 2014-12-31
--按照条件查询一个企业的订单
CREATE PROCEDURE [dbo].[bpCaorderByCpMainIDSelect]
(		
	@CpMainID INT,
	@OpenDate VARCHAR(20)	
)
AS
BEGIN	
	SELECT ID,OpenDate,Paid,OrderType,EndDate 
	FROM CaOrder WITH(NOLOCK) 
	WHERE cpMainID=@CpMainID AND Paid>0 AND MainOrderID IS NULL AND OpenDate<@OpenDate
	ORDER BY OpenDate DESC	
END

GO
/****** Object:  StoredProcedure [dbo].[bpCaOrderByCpMainIDValidVipSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.12.9
--创建人：John
--说明：根据公司编号获取会员订单资费明细编号
--修改harry2016-12-21显示续费订单
--#####################################################
CREATE PROCEDURE [dbo].[bpCaOrderByCpMainIDValidVipSelect]
(
	@cpMainID INT
)
AS
BEGIN
	SELECT dcFeeDetailID
	FROM caOrder WITH(NOLOCK) 
	WHERE cpMainid = @cpMainID
	AND EndDate > GETDATE() - 1 
	AND OrderType = 8
	AND OpenDate IS NOT NULL
	AND IsDeleted = 0
END
 
GO
/****** Object:  StoredProcedure [dbo].[bpCaOrderByDeletedSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--###############################
--Andy.Yin 2014-12-2
--###############################
CREATE PROCEDURE [dbo].[bpCaOrderByDeletedSelect]
(
    @BankType INT,
    @OrderType INT,
    @SearchItem INT,
    @SearchOption INT,
    @SearchText NVARCHAR(200),
    @Where VARCHAR(200)    
)
AS
BEGIN
    SET @SearchText = dbo.SafeSQL(@SearchText)
    SET @Where = dbo.SafeSQL(@Where) 
       
    DECLARE @SQL AS VARCHAR(2000)
    SET @SQL = 'SELECT Top 500 OrderType,PayMethod,ServiceType,id,Paid,Accounts,AddDate,OpenDate,RemittanceDate,manageruserid,companyname,cpMainID,DeletedMan,DeletedDate 
    FROM caOrder with(nolock) WHERE IsDeleted=1 '
    
    --付款类型
    IF @BankType<>0
        SET @SQL = @SQL + ' AND PayMethod =' + CAST(@BankType AS NVARCHAR(10))
    --订单类型
    IF @OrderType<>0
        SET @SQL = @SQL + ' AND OrderType =' + CAST(@OrderType AS NVARCHAR(10))        
    --搜索条件
    IF @SearchItem=1        
    BEGIN
        IF @SearchOption=0--等于
            SET @SQL = @SQL + ' AND ID = ''' +  @SearchText + ''''
        ELSE
            SET @SQL = @SQL + ' AND ID LIKE ''%' +  @SearchText + '%'''
    END
    ELSE IF @SearchItem=2 
    BEGIN
        IF @SearchOption=0--等于
            SET @SQL = @SQL + ' AND CompanyName = ''' +  @SearchText+ ''''
        ELSE
            SET @SQL = @SQL + ' AND CompanyName LIKE ''%' +  @SearchText + '%'''
    END
    ELSE IF @SearchItem=3 
    BEGIN
        IF @SearchOption=0--等于
            SET @SQL = @SQL + ' AND cpMainID = ''' +  @SearchText + ''''
        ELSE
            SET @SQL = @SQL + ' AND cpMainID LIKE ''%' +  @SearchText + '%'''
    END
    ELSE IF @SearchItem=4 
    BEGIN
        IF @SearchOption=0--等于
            SET @SQL = @SQL + ' AND manageruserid = ''' +  @SearchText + ''''
        ELSE
            SET @SQL = @SQL + ' AND manageruserid LIKE ''%' +  @SearchText + '%'''
    END
    ELSE IF @SearchItem=5 
    BEGIN
        IF @SearchText='1'
            SET @SQL = @SQL + ' AND OpenDate Is Not Null'
        ELSE IF @SearchText='0'
            SET @SQL = @SQL + ' AND OpenDate Is Null'
    END
    ELSE IF @SearchItem=6 
    BEGIN
        IF @SearchText='1'
            SET @SQL = @SQL + ' AND ReceiveDate Is Not Null'
        ELSE IF @SearchText='0'
            SET @SQL = @SQL + ' AND ReceiveDate Is Null'
    END
    ELSE IF @SearchItem=7 
    BEGIN
        IF @SearchText='1'
            SET @SQL = @SQL + ' AND NeedInvoice=1'
        ELSE IF @SearchText='0'
            SET @SQL = @SQL + ' AND NeedInvoice=0'
    END        
    
    IF LEN(@WHERE)>0
        SET @SQL=@SQL + ' ' + @WHERE
	
	SET @SQL=@SQL + '  Order By DeletedDate Desc'
    PRINT @SQL
    EXEC(@SQL)    
END

GO
/****** Object:  StoredProcedure [dbo].[bpcaOrderByInvoiceUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--修改订单发票信息
--Lucifer 2014-12-19
CREATE PROCEDURE [dbo].[bpcaOrderByInvoiceUpdate] 
(
	@InvoiceAskDate SMALLDATETIME,
	@NeedInvoice BIT,
	@InvoiceConfirmDate SMALLDATETIME,
	@InvoiceConfirmMan SMALLINT,
	@InvoiceTitle NVARCHAR(50),
	@MailAddress NVARCHAR(100),
	@Recipient NVARCHAR(100),
	@zip CHAR(6),
	@PostTelephone VARCHAR(50),
	@Tariff VARCHAR(30),
	@RegisterAddress NVARCHAR(100),
	@RegisterTel VARCHAR(50),
	@BankName NVARCHAR(50),
	@BankAccount NVARCHAR(50),
	@OrderID INT
) 
AS
SET NOCOUNT ON
BEGIN
	IF @InvoiceConfirmDate IS NULL
		UPDATE caOrder SET
			InvoiceAskDate=@InvoiceAskDate,
			NeedInvoice=@NeedInvoice,
			InvoiceTitle=@InvoiceTitle,
			MailAddress=@MailAddress,
			Recipient=@Recipient,
			zip=@zip,
			IsBackSubmit=1,
			PostTelephone=@PostTelephone,
			Tariff=@Tariff,
			RegisterAddress=@RegisterAddress,
			RegisterTel=@RegisterTel,
			BankName=@BankName,
			BankAccount=@BankAccount
		WHERE ID=@OrderID
	ELSE
		UPDATE caOrder SET
			InvoiceAskDate=@InvoiceAskDate,
			NeedInvoice=@NeedInvoice,
			InvoiceConfirmDate=@InvoiceConfirmDate,
			InvoiceConfirmMan=@InvoiceConfirmMan,
			InvoiceTitle=@InvoiceTitle,
			MailAddress=@MailAddress,
			Recipient=@Recipient,
			zip=@zip,
			IsBackSubmit=1,
			PostTelephone=@PostTelephone,
			Tariff=@Tariff,
			RegisterAddress=@RegisterAddress,
			RegisterTel=@RegisterTel,
			BankName=@BankName,
			BankAccount=@BankAccount
		WHERE ID=@OrderID
END


GO
/****** Object:  StoredProcedure [dbo].[bpcaOrderByIsDeleteHasOpenUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--已开通的订单删除 Lucifer 2014-12-9
CREATE PROCEDURE [dbo].[bpcaOrderByIsDeleteHasOpenUpdate]
(
	@OrderID INT,
	@DeletedMan SMALLINT,
	@cpMainID INT,
	@Reason VARCHAR(200)
)
AS
SET NOCOUNT ON
IF NOT EXISTS(SELECT 'x' FROM caOrder WHERE ReceiveDate IS NULL AND ID = @OrderID)
	RETURN
BEGIN TRAN
	DECLARE @UsePoint AS INT, @UseCoin AS INT, @GivePoint INT
	--是否是积分订单
	SELECT @UsePoint = PaidPoint, @GivePoint = GivePoint, @UseCoin = PaidCoin
	FROM caOrder WITH(NOLOCK) 
	WHERE ID = @OrderID

	IF @UsePoint > 0  --积分订单
	BEGIN
		--插入积分记录
		INSERT INTO cpPoint (cpMainID, changeID, point, relativeID, lastModifyDate)
		VALUES(@cpMainID, 16, @UsePoint, @OrderID, GETDATE())
	END

	IF @GivePoint > 0  --积分订单
	BEGIN
		--插入积分记录
		INSERT INTO cpPoint (cpMainID, changeID, point, relativeID, lastModifyDate)
		VALUES(@cpMainID, 24, @GivePoint * -1, @OrderID, GETDATE())
	END

	IF @UseCoin > 0
	BEGIN
		--插入金币记录
		BEGIN
			IF (SELECT COUNT(*) FROM cpCoin WITH(NOLOCK) WHERE caOrderId = @OrderID) = 1
			BEGIN
				DECLARE @Remaincoin INT
				SELECT @Remaincoin = ISNULL(Remaincoin, 0) FROM cpMain WITH(NOLOCK) WHERE Id = @cpMainID

				INSERT INTO cpCoin(cpMainId, caOrderId, Coin, IsCancel, Balance, AddDate)
				SELECT @cpMainId, @OrderID, @UseCoin, 1, @UseCoin + @Remaincoin, GETDATE()
			END
		END
	END

	SET @Reason = dbo.SafeSQL(@Reason)
	UPDATE caOrder SET OpenDate = NULL, IsDeleted=1, DeletedDate=GETDATE(), DeletedMan=@DeletedMan WHERE ReceiveDate IS NULL AND ID = @OrderID
	INSERT INTO caOrderRemarks(ManagerID,Remarks,OrderID) VALUES(@DeletedMan,@Reason,@OrderID)
	EXEC spRedifinePrivilage @cpMainID
COMMIT TRAN
RETURN
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN
END
GO
/****** Object:  StoredProcedure [dbo].[bpcaOrderByIsDeleteUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--未开通订单删除 Lucifer 2014-12-9
--修改：harry 增加积分，金币返还 2015-7-7
CREATE PROCEDURE [dbo].[bpcaOrderByIsDeleteUpdate]
(
	@OrderID INT, 
	@DeletedMan SMALLINT
)
AS
SET NOCOUNT ON
BEGIN TRAN
	IF NOT EXISTS(SELECT 'x' FROM caOrder WHERE OpenDate IS NULL AND ID=@OrderID)
		RETURN

	DECLARE @UsePoint AS INT, @UseCoin AS INT, @cpMainID AS INT, @GivePoint INT

	--是否是积分订单
	SELECT @UsePoint = PaidPoint, @GivePoint = GivePoint, @UseCoin = PaidCoin, @cpMainID = cpMainID 
	FROM caOrder WITH(NOLOCK) 
	WHERE ID = @OrderID

	IF @UsePoint > 0  --积分订单
	BEGIN
		--插入积分记录
		INSERT INTO cpPoint (cpMainID, changeID, point, relativeID, lastModifyDate)
		VALUES(@cpMainID, 16, @UsePoint, @OrderID, GETDATE())
	END

	IF @GivePoint > 0  --积分订单
	BEGIN
		--插入积分记录
		INSERT INTO cpPoint (cpMainID, changeID, point, relativeID, lastModifyDate)
		VALUES(@cpMainID, 24, @GivePoint * -1, @OrderID, GETDATE())
	END

	IF @UseCoin > 0
	BEGIN
		--插入金币记录
		BEGIN
			IF (SELECT COUNT(*) FROM cpCoin WITH(NOLOCK) WHERE caOrderId = @OrderID) = 1
			BEGIN
				DECLARE @Remaincoin INT
				SELECT @Remaincoin = ISNULL(Remaincoin, 0) FROM cpMain WITH(NOLOCK) WHERE Id = @cpMainID

				INSERT INTO cpCoin(cpMainId, caOrderId, Coin, IsCancel, Balance, AddDate)
				SELECT @cpMainId, @OrderID, @UseCoin, 1, @UseCoin + @Remaincoin, GETDATE()
			END
		END
	END
	UPDATE caOrder SET IsDeleted=1, DeletedDate = GETDATE(), DeletedMan=@DeletedMan 
	WHERE OpenDate IS NULL AND ID=@OrderID
COMMIT TRAN
RETURN 1
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END

GO
/****** Object:  StoredProcedure [dbo].[bpcaOrderByJobNumberOpenDateUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--开通职位数订单 Lucifer 2014-12-24
CREATE PROCEDURE [dbo].[bpcaOrderByJobNumberOpenDateUpdate]
(
	@BeginDate SMALLDATETIME,
	@EndDate SMALLDATETIME,
	@OpenMan SMALLINT,
	@OrderID INT,
	@JobNumber INT
)
AS
BEGIN
	UPDATE MainDB..caOrder SET
		BeginDate=@BeginDate,
		EndDate=@EndDate,
		OpenDate=GetDate(),
		OpenMan=@OpenMan,
		JobNumber=@JobNumber
	WHERE ID=@OrderID
END


GO
/****** Object:  StoredProcedure [dbo].[bpcaOrderByJobRefrshQuotaOpenDateUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--开通职位刷新数订单 Harry 2017-6-7
CREATE PROCEDURE [dbo].[bpcaOrderByJobRefrshQuotaOpenDateUpdate]
(
	@BeginDate SMALLDATETIME,
	@EndDate SMALLDATETIME,
	@OpenMan SMALLINT,
	@OrderID INT,
	@SmsNumber INT
)
AS
SET NOCOUNT ON
BEGIN
	UPDATE MainDB..caOrder SET
		BeginDate = @BeginDate,
		EndDate = @EndDate,
		OpenDate = GetDate(),
		OpenMan = @OpenMan,
		jobRefreshQuota = @SmsNumber,
		remainJobRefreshQuota = @SmsNumber 
	WHERE ID=@OrderID
END
SET NOCOUNT OFF
 
GO
/****** Object:  StoredProcedure [dbo].[bpcaOrderByLatestSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--根据企业ID获取最近的正在执行的某类型订单，订单确认用 Lucifer 2014-12-24
CREATE PROCEDURE [dbo].[bpcaOrderByLatestSelect]
(
	@cpMainID INT,
	@OrderType SMALLINT
)
AS
BEGIN
	SELECT Top 1 BeginDate,EndDate FROM caOrder WITH(NOLOCK)
	WHERE cpMainId=@cpMainID AND OrderType=@OrderType AND EndDate>GETDATE() AND OpenDate IS NOT NULL AND IsDeleted=0
	ORDER BY EndDate DESC
END


GO
/****** Object:  StoredProcedure [dbo].[bpCaOrderByOpenDateSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--创建人 Andy
--时间 2014-12-03
--后台按照时间查询没有招聘顾问的订单
CREATE PROCEDURE [dbo].[bpCaOrderByOpenDateSelect]
(   
    @StartTime Datetime, 
    @EndTime Datetime
)
AS
BEGIN
	--有招聘顾问的
	SELECT Paid, DeptId, ManagerUserId 
	FROM caOrder a WITH(NOLOCK), Manageruser b  WITH(NOLOCK)
	WHERE a.manageruserid=b.id AND a.opendate >= @StartTime and a.opendate<=@EndTime	
	--AND a.Paid > 0 AND a.Isdeleted = 0

	--没有招聘顾问的
	SELECT Paid, b.id 
	FROM MainDB..caOrder a WITH(NOLOCK), MainDB..cpMain b WITH(NOLOCK)
	WHERE a.cpMainID=b.id AND a.opendate >= @StartTime AND a.opendate<=@EndTime AND a.manageruserid IS NULL
	--AND a.Paid > 0 AND a.Isdeleted = 0
END

GO
/****** Object:  StoredProcedure [dbo].[bpcaOrderByOpenDateUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--开通订单 Lucifer 2014-12-24
CREATE PROCEDURE [dbo].[bpcaOrderByOpenDateUpdate]
(
	@BeginDate SMALLDATETIME,
	@EndDate SMALLDATETIME,
	@OpenMan SMALLINT,
	@OrderID INT
)
AS
BEGIN
	UPDATE MainDB..caOrder SET
		BeginDate=@BeginDate,
		EndDate=@EndDate,
		OpenDate=GetDate(),
		OpenMan=@OpenMan
	WHERE ID=@OrderID
END


GO
/****** Object:  StoredProcedure [dbo].[bpCaOrderByReceiveDateSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--创建人 Andy
--时间 2014-12-03
--后台按照接收时间查询订单
CREATE PROCEDURE [dbo].[bpCaOrderByReceiveDateSelect]
(   
    @StartTime VARCHAR(20), 
    @EndTime VARCHAR(20),
    @Where VARCHAR(200)
)
AS
BEGIN	
	SET @Where = dbo.SafeSQL(@Where)
	
	DECLARE @SQL AS VARCHAR(2000)
    SET @SQL = 'SELECT a.Id ,b.Id CompanyId,b.Name CompanyName,ReceiveDate,b.RegDate,a.AddDate,a.OpenDate,a.Paid,a.OrderType 
	FROM CaOrder a WITH(NOLOCK),CpMain b WITH(NOLOCK) 
	WHERE a.Paid>0 AND a.cpMainID=b.id
	AND ReceiveDate > ''' + @StartTime + '''
    AND ReceiveDate < ''' + @EndTime + ''''
    IF LEN(@Where) > 0
		SET @SQL = @SQL + @Where
	SET @SQL = @SQL + ' ORDER BY a.OpenDate'
	--PRINT @SQL
    EXEC(@SQL)  
END

GO
/****** Object:  StoredProcedure [dbo].[bpCaOrderByReceiveDateUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--更新订单到账日期和到账人员 Lucifer 2014-12-24
CREATE PROCEDURE [dbo].[bpCaOrderByReceiveDateUpdate]
(
	@OrderID INT,
	@ReceiveMan SMALLINT
)
AS
BEGIN
	UPDATE MainDB..caOrder SET ReceiveDate=GetDate(),ReceiveMan=@ReceiveMan WHERE ID=@OrderID
END


GO
/****** Object:  StoredProcedure [dbo].[bpcaOrderByRemittanceFileUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.12.2
--创建人：Lucifer
--说明：上传汇款凭证更新
--harry 2018-5-19 增加 isdocopen
--#####################################################
CREATE PROCEDURE [dbo].[bpcaOrderByRemittanceFileUpdate]
(
	@OrderID INT,
	@RemittanceFile VARCHAR(100),
        @IsDocOpen INT=0--1 合同图片 0 汇款单图片
)
AS
BEGIN
	DECLARE @CurrentFile AS VARCHAR(100)
	SELECT @CurrentFile = RemittanceFile FROM caOrder WHERE ID = @OrderID
	IF ISNULL(@CurrentFile,'') = ''
		UPDATE caOrder SET RemittanceDate = GETDATE(),RemittanceFile = @RemittanceFile WHERE ID = @OrderID
	ELSE
		UPDATE caOrder SET RemittanceDate = GETDATE(),RemittanceFile = RemittanceFile + '|' + @RemittanceFile WHERE ID = @OrderID
	IF @IsDocOpen=1
		UPDATE caOrder SET IsDocOpen =1 WHERE  ID = @OrderID --合同图片
	IF @IsDocOpen=0
		UPDATE caOrder SET IsDocOpen =2 WHERE  ID = @OrderID AND IsDocOpen =1 --汇款单图片
END

GO
/****** Object:  StoredProcedure [dbo].[bpcaOrderBySmsNumberOpenDateUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--开通短信数订单 Harry 2017-6-7
CREATE PROCEDURE [dbo].[bpcaOrderBySmsNumberOpenDateUpdate]
(
	@BeginDate SMALLDATETIME,
	@EndDate SMALLDATETIME,
	@OpenMan SMALLINT,
	@OrderID INT,
	@SmsNumber INT
)
AS
SET NOCOUNT ON
BEGIN
	UPDATE MainDB..caOrder SET
		BeginDate = @BeginDate,
		EndDate = @EndDate,
		OpenDate = GetDate(),
		OpenMan = @OpenMan,
		SmsQuota = @SmsNumber,
		RemainSmsQuota = @SmsNumber 
	WHERE ID=@OrderID
END
SET NOCOUNT OFF

GO
/****** Object:  StoredProcedure [dbo].[bpcaOrderBySumSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[bpcaOrderBySumSelect]
(
    @cpMainID INT
)
AS
SET NOCOUNT ON
BEGIN
    DECLARE @ActiveQuota INT
    DECLARE @UserNumber INT
    DECLARE @JobNumber INT
    DECLARE @RemainQuota INT
    DECLARE @RemainSmsQuota INT
    DECLARE @VIPDate DATETIME 

    SELECT @ActiveQuota = SUM(ActiveQuota),@UserNumber=SUM(UserNumber),@JobNumber=SUM(JobNumber),@VIPDate=MAX(EndDate),@RemainQuota=SUM(RemainQuota),@RemainSmsQuota=SUM(RemainSmsQuota)
    FROM caOrder WITH(NOLOCK)
    WHERE BeginDate < GETDATE() 
    AND EndDate > GETDATE()
    AND OrderType IN (8,9,10,11,14)
    AND cpMainID = @cpMainID
    AND OpenDate IS NOT NULL
    
    SELECT @ActiveQuota as ActiveQuota ,@UserNumber as UserNumber,@JobNumber as JobNumber,@VIPDate as VIPDate,@RemainQuota as RemainQuota,@RemainSmsQuota as RemainSmsQuota
END
GO
/****** Object:  StoredProcedure [dbo].[bpcaOrderByUserNumberOpenDateUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--开通用户数订单 Lucifer 2014-12-24
CREATE PROCEDURE [dbo].[bpcaOrderByUserNumberOpenDateUpdate]
(
	@BeginDate SMALLDATETIME,
	@EndDate SMALLDATETIME,
	@OpenMan SMALLINT,
	@OrderID INT,
	@UserNumber INT
)
AS
BEGIN
	UPDATE MainDB..caOrder SET
		BeginDate=@BeginDate,
		EndDate=@EndDate,
		OpenDate=GetDate(),
		OpenMan=@OpenMan,
		UserNumber=@UserNumber
	WHERE ID=@OrderID
END


GO
/****** Object:  StoredProcedure [dbo].[bpcaOrderRemarksByOrderIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--根据cpmainid获取订单备注 Lucifer 2014-12-9
CREATE PROCEDURE [dbo].[bpcaOrderRemarksByOrderIDSelect]
(
	@OrderID INT
)
AS
BEGIN
	SELECT * FROM MainDB..caOrderRemarks WITH(NOLOCK) WHERE OrderID=@OrderID
END

GO
/****** Object:  StoredProcedure [dbo].[bpcaOrderSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.12.1
--创建人：Lucifer
--说明：根据条件获取订单列表
--修改：harry 2018-5-21 增加isdocopen
--修改：sunshine 2018-8-15 增加 dcRegionID
--#####################################################
CREATE PROCEDURE [dbo].[bpcaOrderSelect]
(
	@Where VARCHAR(2000), 
	@Order VARCHAR(200)
)
AS
SET NOCOUNT ON
BEGIN
	DECLARE @SQL AS VARCHAR(MAX)
	SELECT @Where = dbo.SafeSql(@Where), @Order = dbo.SafeSql(@Order)
	SET @SQL = '
	Select Top 1000 Balance, ReceiveDate, FaxFile, OrderType, ProvinceID, PayMethod, ID, Paid, dcFeeDetailID, 
		Accounts, AddDate, OpenDate, RemittanceDate, ManageruserID, CompanyName, cpMainID, ServiceType, PlaceWeek, ContractFile, 
		NeedInvoice, InvoiceConfirmDate, OpenMan, InvoiceCompany, InvoiceMonth, PaidCoin, CancelReason, EndDate, BeginDate,
		(Select ConsultantID From cpMain WITH(NOLOCK) Where ID = caOrder.cpMainID) ConsultantID, isdocopen,(Select dcRegionID From cpMain WITH(NOLOCK) Where ID = caOrder.cpMainID) dcRegionID
	From caOrder With(Nolock)
	Where 1=1' + 
	@Where + 
	@Order
	--insert into a2 select @sql, getdate()
	EXEC(@SQL)
END

GO
/****** Object:  StoredProcedure [dbo].[bpcaOrderSUMSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


--Lambo 20101117
--获取企业的购买的简历下载数，职位数，用户数
CREATE PROCEDURE [dbo].[bpcaOrderSUMSelect]
	@cpMainID INT,
	@ActiveQuota INT OUTPUT,
	@UserNumber INT OUTPUT,
	@JobNumber INT OUTPUT,
	@RemainQuota INT OUTPUT,
	@VIPDate DATETIME OUTPUT 
AS
SELECT @ActiveQuota = SUM(ActiveQuota),@UserNumber=SUM(UserNumber),@JobNumber=SUM(JobNumber),@VIPDate=MAX(EndDate),@RemainQuota=SUM(RemainQuota)
FROM caOrder WITH(NOLOCK)
WHERE BeginDate<GETDATE() 
AND EndDate>GETDATE()
AND OrderType IN (8,9,10,11)
AND cpMainID = @cpMainID
AND OpenDate IS NOT NULL














GO
/****** Object:  StoredProcedure [dbo].[bpcaOrderTryInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--添加试用订单
--Lucifer 2014-12-19
--增加短信数harry2017-10-17
CREATE PROCEDURE [dbo].[bpcaOrderTryInsert]
(
	@cpMainID INT,
	@ProvinceID SMALLINT,
	@PayMethod TINYINT,
	@ConsultantID SMALLINT,
	@CompanyName NVARCHAR(50),
	@ManageruserID SMALLINT,
	@LinkMan NVARCHAR(50),
	@Telephone VARCHAR(50),
	@LinkRemark NVARCHAR(1000)
)
AS
SET NOCOUNT ON
BEGIN 
	INSERT INTO maindb..caOrder(
		cpMainID,
		ProvinceID,
		PayMethod,
		OrderType,
		Accounts,
		Paid,
		Manageruserid,
		ActiveQuota,
		RemainQuota,
		JobNumber,
		UserNumber,
		SmsQuota,
		RemainSmsQuota,
		JobRefreshQuota,
		RemainJobRefreshQuota,
		CompanyName,
		NeedInvoice,
		dcFeeDetailID,
		IsBackSubmit,
		BeginDate,
		EndDate,
		OrderStatus,
		OpenDate,
		OpenMan,
		LinkMan,
		Telephone,
		LinkRemark,
		ReceiveDate
	)
	VALUES(
		@cpMainID,
		@ProvinceID,
		@PayMethod,
		8,
		0,
		0,
		@ConsultantID,
		10,
		10,
		5,
		1,
		7,
		7,
		14,
		14,
		@CompanyName,
		0,
		0,
		1,
		GETDATE(),
		GETDATE()+7,
		13,
		GETDATE(),
		@ManageruserID,
		@LinkMan,
		@Telephone,
		@LinkRemark,
		GETDATE()
	)
END

GO
/****** Object:  StoredProcedure [dbo].[bpcaOrderUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 --更新订单信息
--Lucifer 2014-12-19
CREATE PROCEDURE [dbo].[bpcaOrderUpdate] 
(
	@WHERE VARCHAR(MAX),
	@OrderID INT
)
AS 
BEGIN
	DECLARE @SQL VARCHAR(MAX)
	SET @WHERE = dbo.SafeSQL(@WHERE)
	SET @SQL = 'UPDATE caOrder SET ' + @WHERE + ' WHERE ID=' + CONVERT(VARCHAR(20),@OrderID)
	EXEC(@SQL)
END


GO
/****** Object:  StoredProcedure [dbo].[bpcaPlaintSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----------------
--创建日期：2010-9-29
--创建人：lambo
--功能说明：根据条件查询记录
--用于后台客户服务模块，单位投诉个人页面
-----------------
CREATE PROCEDURE [dbo].[bpcaPlaintSelect]
(
	@WHERE VARCHAR(1000)
)
AS
BEGIN
	DECLARE @SQL VARCHAR(2000)
	SET @SQL = 'SELECT TOP 5000 e.mobile,e.email paemail,a.*,b.name caName,d.paMainID paMainID,c.consultantID,c.Name,c.dcProvinceID,c.ID cpMainID,c.regDate'
	SET @SQL = @SQL + ' FROM caPlaint a WITH(NOLOCK) '
	SET @SQL = @SQL + ' LEFT JOIN caMain b WITH(NOLOCK) ON a.caMainID = b.ID '
	SET @SQL = @SQL + ' LEFT JOIN cpMain c WITH(NOLOCK) ON  b.cpMainID = c.ID '
	SET @SQL = @SQL + ' INNER JOIN cvMain d WITH(NOLOCK) ON a.cvMainID = d.ID '
    SET @SQL = @SQL + ' INNER JOIN paMain e WITH(NOLOCK) ON d.paMainID = e.ID '
	SET @SQL = @SQL + ' WHERE  1=1 '
	IF LEN(@WHERE) > 0
	BEGIN
		SET @WHERE = dbo.SafeSql(@Where)
		SET @SQL = @SQL + @WHERE
	END
	SET @SQL = @SQL + ' ORDER BY a.AddDate DESC'
	EXEC(@SQL)
END














GO
/****** Object:  StoredProcedure [dbo].[bpCaPlaintUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----------------
--创建日期：2010-9-26
--创建人：lambo
--功能说明：根据编号修改一条单位投诉个人的记录
--用于后台单位投诉个人页面的处理文件
-----------------
CREATE PROCEDURE [dbo].[bpCaPlaintUpdate]
(
	@ID INT,
	@ReplyType INT,
	@ReplyMan INT,
	@ProcessMessage VARCHAR(500)
)
AS
BEGIN TRY
	UPDATE CaPlaint SET ReplyType=@ReplyType,ReplyMan=@ReplyMan,ProcessMessage=@ProcessMessage,ProcessDate=GETDATE() WHERE ID=@ID
	RETURN 1
END TRY
BEGIN CATCH
	RETURN 0
END CATCH














GO
/****** Object:  StoredProcedure [dbo].[bpCertificate_UnrealByIDDelete]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--###########################
--创建时间：2014.12.15
--创建人：Nick
--说明：删除虚假营业执照
--###########################
CREATE PROCEDURE [dbo].[bpCertificate_UnrealByIDDelete]
(
	@ID INT
)
AS
BEGIN 
	DELETE FROM  certificate_unreal WHERE id = @ID
END


GO
/****** Object:  StoredProcedure [dbo].[bpCertificate_UnrealByIDInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--###########################
--创建时间：2014.12.15
--创建人：Nick
--说明：插入虚假营业执照
--###########################
CREATE PROCEDURE [dbo].[bpCertificate_UnrealByIDInsert]
(
	@CompanyName NVARCHAR(100),
	@CertFileName VARCHAR(100),
	@ManagerUserID INT,
	@Des VARCHAR(MAX)
)
AS
BEGIN 
	INSERT INTO certificate_unreal (Companyname,certfilename,addman,description) 
	VALUES (@CompanyName,@CertFileName,@ManagerUserID,@Des)
END


GO
/****** Object:  StoredProcedure [dbo].[bpCertificate_UnrealByIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--###########################
--创建时间：2014.12.15
--创建人：Nick
--说明：获取虚假营业执照
--###########################
CREATE PROCEDURE [dbo].[bpCertificate_UnrealByIDSelect]
(
	@ID INT
)
AS
BEGIN 
	SELECT certfilename FROM certificate_unreal WITH(NOLOCK) WHERE  id = @ID
END


GO
/****** Object:  StoredProcedure [dbo].[bpCertificate_UnrealSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--###########################
--创建时间：2014.12.15
--创建人：Nick
--说明：获取虚假营业执照案例
--###########################
CREATE PROCEDURE [dbo].[bpCertificate_UnrealSelect]
AS
BEGIN 
	SELECT a.id,a.Companyname,a.certfilename,a.addman,a.AddDate,a.description, b.name
	FROM certificate_unreal a  WITH(NOLOCK) ,ManagerUser b
	WHERE a.AddMan = b.ID
	ORDER BY AddDate DESC
END


GO
/****** Object:  StoredProcedure [dbo].[bpColdCustomerBycpMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--根据企业ID获取冷客户记录
--Lucifer 2014-12-19
CREATE PROCEDURE [dbo].[bpColdCustomerBycpMainIDSelect] 
(
	@cpMainID INT
) 
AS 
BEGIN 
	SELECT * FROM maindb..ColdCustomer WITH(NOLOCK) WHERE IsValid=1 AND cpMainID=@cpMainID
END


GO
/****** Object:  StoredProcedure [dbo].[bpColdCustomerInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[bpColdCustomerInsert]
(
	@CompanyName VARCHAR(100),
	@ProvinceID TINYINT,	
	@Email VARCHAR(100),
	@Phone VARCHAR(50),
	@SourceLink VARCHAR(1000),
	@RegType TINYINT,
	@RegUserName VARCHAR(50),
	@RegPassWord VARCHAR(50),
	@IsNameRepeat BIT,
	@IsEmailRepeat BIT,
	@IsMobilerepeat BIT,
	@IsAgree BIT,
	@DisAgreeReason nvarchar(500),
	@Status TINYINT,
	@IsValid BIT,
	@CheckReason nvarchar(500),
	@CheckDate SMALLDATETIME,
	@AddDate SMALLDATETIME,
	@AddMan SMALLINT,
	@AddWorkUserID SMALLINT,
	@LinkMan VARCHAR(50),
	@CpMainIDOld VARCHAR(100),
	@PhotoFile VARCHAR(50),
	@qq VARCHAR(15),
	@cpIndustry VARCHAR(50),
	@dcCompanyKindID INT,
	@dcCompanySizeID INT,
	@dcRegionID VARCHAR(6),
	@Address VARCHAR(120),
	@Brief VARCHAR(6000),
	@OtherContact VARCHAR(100)	
)
AS
SET NOCOUNT ON
BEGIN
	INSERT INTo MainDB..ColdCustomer 
		(CompanyName, ProvinceID, Email, Phone, SourceLink, RegType,
		RegUserName, RegPassWord, IsNameRepeat, IsEmailRepeat, IsMobilerepeat,
        IsAgree, DisAgreeReason, Status, IsValid, CheckReason, CheckDate,
        AddDate, AddMan, AddWorkUserID, LinkMan, CpMainIDOld, PhotoFile, QQ, cpIndustry, Address,
        Brief, dcCompanySizeID, dcRegionID, dcCompanyKindID, OtherContact)
	SELECT @CompanyName, @ProvinceID, @Email, @Phone, @SourceLink, @RegType,
		@RegUserName, @RegPassWord, @IsNameRepeat, @IsEmailRepeat, @IsMobilerepeat,
        @IsAgree, @DisAgreeReason, @Status, @IsValid, @CheckReason, @CheckDate,
        @AddDate, @AddMan, @AddWorkUserID, @LinkMan, @CpMainIDOld, @PhotoFile, @QQ, @cpIndustry, @Address,
        @Brief, @dcCompanySizeID, @dcRegionID, @dcCompanyKindID, @OtherContact

	SELECT @@IDENTITY
END
GO
/****** Object:  StoredProcedure [dbo].[bpColdCustomerReleaseConsultant]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--alen 2018-4-4
--harry 2018-6-7 修改：分配顾问时间大于2个月的才释放
CREATE PROCEDURE [dbo].[bpColdCustomerReleaseConsultant] 
AS
BEGIN
    SET NOCOUNT ON
	--2个月内未注册的，释放
	UPDATE Maindb..ColdCustomer
	SET AddMan = NULL
	WHERE CpMainID IS NULL
	AND AddDate < DATEADD(m, -2, GETDATE())
	AND AddMan IS NOT NULL

	--已注册，注册2个月内未上传营业执照的，释放
	UPDATE a SET a.AddMan = NULL FROM Maindb..ColdCustomer a, cpMain b
	WHERE a.cpMainID = b.ID AND b.HasLicence = 0 AND a.RegisterDate < DATEADD(m, -2, GETDATE())
        AND b.consultantDate< DATEADD(m, -2, GETDATE())
	AND a.AddMan IS NOT NULL
    SET NOCOUNT OFF

	--企业已删除的，改为未注册状态
	UPDATE ColdCustomer SET
		[Status] = 1,
		cpMainID = NULL,
		RegisterDate = NULL,
		LastLoginDate = NULL,
		LicenceDate = NULL,
		PayDate = NULL,
		PayFee = NULL
	WHERE cpMainID > 0 AND cpMainId NOT IN(SELECT ID FROM cpMain)
END

GO
/****** Object:  StoredProcedure [dbo].[bpColdCustomerTryByCompanyNameSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--根据公司名称获取冷客户VIP试用记录
--Lucifer 2014-12-19
CREATE PROCEDURE [dbo].[bpColdCustomerTryByCompanyNameSelect] 
(
	@CompanyName NVARCHAR(100)
) 
AS 
BEGIN 
	SELECT * FROM maindb..ColdCustomerTry WITH(NOLOCK) WHERE CompanyName=@CompanyName
END


GO
/****** Object:  StoredProcedure [dbo].[bpCommentAndInterviewByStatisticsSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
---修改人Harry,修改点评、面经统计错误
CREATE PROCEDURE [dbo].[bpCommentAndInterviewByStatisticsSelect]
(
	@ManagerUserID SMALLINT,
	@YearMonth VARCHAR(6),
	@DeptID SMALLINT
)
AS
BEGIN
	CREATE TABLE #T
	(
		YearMonth VARCHAR(6),
		WorkUserID SMALLINT,
		paMainID INT,
		GoodComment INT,
		CommonComment INT,
		InvalidComment INT,
		GoodInterview INT,
		CommonInterview INT,
		InvalidInterview INT
	)
	IF LEN(ISNULL(@YearMonth,'')) = 0
	BEGIN
		IF DAY(GETDATE()) > 25
		BEGIN
			INSERT INTO #T(YearMonth,WorkUserID,paMainID) SELECT CONVERT(VARCHAR(6),DATEADD(MONTH,1,GETDATE()),112),WorkUserID,PaMainID FROM oadb..opWorkUserPaMain
			INSERT INTO #T(YearMonth,WorkUserID,paMainID) SELECT CONVERT(VARCHAR(6),GETDATE(),112),WorkUserID,PaMainID FROM oadb..opWorkUserPaMain
			INSERT INTO #T(YearMonth,WorkUserID,paMainID) SELECT CONVERT(VARCHAR(6),DATEADD(MONTH,-1,GETDATE()),112),WorkUserID,PaMainID FROM oadb..opWorkUserPaMain
		END
		ELSE
		BEGIN
			INSERT INTO #T(YearMonth,WorkUserID,paMainID) SELECT CONVERT(VARCHAR(6),GETDATE(),112),WorkUserID,PaMainID FROM oadb..opWorkUserPaMain
			INSERT INTO #T(YearMonth,WorkUserID,paMainID) SELECT CONVERT(VARCHAR(6),DATEADD(MONTH,-1,GETDATE()),112),WorkUserID,PaMainID FROM oadb..opWorkUserPaMain
			INSERT INTO #T(YearMonth,WorkUserID,paMainID) SELECT CONVERT(VARCHAR(6),DATEADD(MONTH,-2,GETDATE()),112),WorkUserID,PaMainID FROM oadb..opWorkUserPaMain
		END
	END
	ELSE
	BEGIN
		INSERT INTO #T(YearMonth,WorkUserID,paMainID) SELECT @YearMonth,WorkUserID,PaMainID FROM oadb..opWorkUserPaMain
	END
	IF @ManagerUserID > 0
	BEGIN
		DELETE FROM #T WHERE WorkUserID NOT IN(SELECT ID FROM oadb..WorkUser WHERE ManageruserID=@ManagerUserID)
	END
	IF @DeptID > 0
	BEGIN
		DELETE FROM #T WHERE WorkUserID NOT IN(SELECT a.ID FROM oadb..WorkUser a,maindb..Manageruser b WHERE a.ManageruserID=b.ID AND b.DeptID=@DeptID)
	END
	--优质评论
	UPDATE a SET a.GoodComment=b.cnt FROM #T a,(
		SELECT paMainID,CONVERT(VARCHAR(6),AddDate,112) YearMonth,COUNT(1) cnt FROM(
			SELECT ROW_NUMBER() OVER(PARTITION BY a.PaMainID, a.CpMainID ORDER BY a.ADDDATE DESC) i,a.paMainID,a.AddDate,a.CommentType 
			FROM Comments a, oadb..opWorkUserPaMain b, oadb..opCommentCompany c
			WHERE a.paMainID=b.paMainID AND a.cpMainID=c.cpMainID AND c.WorkUserID=b.WorkUserID AND a.CommentType=2
		) a
		WHERE i<4
		GROUP BY paMainID,CONVERT(VARCHAR(6),AddDate,112)
	) b
	WHERE a.YearMonth=b.YearMonth AND a.paMainID=b.paMainID
	--一般评论
	UPDATE a SET a.CommonComment=b.cnt FROM #T a,(
		SELECT paMainID,CONVERT(VARCHAR(6),AddDate,112) YearMonth,COUNT(1) cnt FROM(
			SELECT ROW_NUMBER() OVER(PARTITION BY a.PaMainID, a.CpMainID ORDER BY a.ADDDATE DESC) i,a.paMainID,a.AddDate,a.CommentType 
			FROM Comments a, oadb..opWorkUserPaMain b, oadb..opCommentCompany c
			WHERE a.paMainID=b.paMainID AND a.cpMainID=c.cpMainID AND c.WorkUserID=b.WorkUserID AND a.CommentType=1
		) a
		WHERE i<4
		GROUP BY paMainID,CONVERT(VARCHAR(6),AddDate,112)
	) b
	WHERE a.YearMonth=b.YearMonth AND a.paMainID=b.paMainID
	--无效评论
	UPDATE a SET a.InvalidComment=b.cnt FROM #T a,(
		SELECT paMainID,CONVERT(VARCHAR(6),AddDate,112) YearMonth,COUNT(1) cnt FROM(
			SELECT ROW_NUMBER() OVER(PARTITION BY a.PaMainID, a.CpMainID ORDER BY a.ADDDATE DESC) i,a.paMainID,a.AddDate,a.CommentType 
			FROM Comments a, oadb..opWorkUserPaMain b, oadb..opCommentCompany c
			WHERE a.paMainID=b.paMainID AND a.cpMainID=c.cpMainID AND c.WorkUserID=b.WorkUserID AND a.CommentType=3
		) a
		WHERE i<4
		GROUP BY paMainID,CONVERT(VARCHAR(6),AddDate,112)
	) b
	WHERE a.YearMonth=b.YearMonth AND a.paMainID=b.paMainID

	--优质面经
	UPDATE a SET a.GoodInterview=b.cnt FROM #T a,(
		SELECT paMainID,CONVERT(VARCHAR(6),AddDate,112) YearMonth,COUNT(1) cnt FROM(
			SELECT ROW_NUMBER() OVER(PARTITION BY a.PaMainID, a.CpMainID ORDER BY a.ADDDATE DESC) i,a.paMainID,a.AddDate,a.InterviewType 
			FROM Interview a, oadb..opWorkUserPaMain b, oadb..opCommentCompany c
			WHERE a.paMainID=b.paMainID AND a.cpMainID=c.cpMainID AND c.WorkUserID=b.WorkUserID AND a.InterviewType=2
		) a
		WHERE i<4
		GROUP BY paMainID,CONVERT(VARCHAR(6),AddDate,112)
	) b
	WHERE a.YearMonth=b.YearMonth AND a.paMainID=b.paMainID
	--一般面经
	UPDATE a SET a.CommonInterview=b.cnt FROM #T a,(
		SELECT paMainID,CONVERT(VARCHAR(6),AddDate,112) YearMonth,COUNT(1) cnt FROM(
			SELECT ROW_NUMBER() OVER(PARTITION BY a.PaMainID, a.CpMainID ORDER BY a.ADDDATE DESC) i,a.paMainID,a.AddDate,a.InterviewType 
			FROM Interview a, oadb..opWorkUserPaMain b, oadb..opCommentCompany c
			WHERE a.paMainID=b.paMainID AND a.cpMainID=c.cpMainID AND c.WorkUserID=b.WorkUserID AND a.InterviewType=1
		) a
		WHERE i<4
		GROUP BY paMainID,CONVERT(VARCHAR(6),AddDate,112)
	) b
	WHERE a.YearMonth=b.YearMonth AND a.paMainID=b.paMainID
	--无效面经
	UPDATE a SET a.InvalidInterview=b.cnt FROM #T a,(
		SELECT paMainID,CONVERT(VARCHAR(6),AddDate,112) YearMonth,COUNT(1) cnt FROM(
			SELECT ROW_NUMBER() OVER(PARTITION BY a.PaMainID, a.CpMainID ORDER BY a.ADDDATE DESC) i,a.paMainID,a.AddDate,a.InterviewType 
			FROM Interview a, oadb..opWorkUserPaMain b, oadb..opCommentCompany c
			WHERE a.paMainID=b.paMainID AND a.cpMainID=c.cpMainID AND c.WorkUserID=b.WorkUserID AND a.InterviewType=3
		) a
		WHERE i<4
		GROUP BY paMainID,CONVERT(VARCHAR(6),AddDate,112)
	) b
	WHERE a.YearMonth=b.YearMonth AND a.paMainID=b.paMainID
	
	DELETE FROM #T WHERE GoodComment IS NULL
		AND CommonComment IS NULL
		AND InvalidComment IS NULL
		AND GoodInterview IS NULL
		AND CommonInterview IS NULL
		AND InvalidInterview IS NULL
	SELECT * FROM #T
	DROP TABLE #T
END

 
GO
/****** Object:  StoredProcedure [dbo].[bpCommentByStatisticsSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--审核人点评和面经审核工作量统计
--创建人：harry
--创建时间：2015/3/18
CREATE PROCEDURE [dbo].[bpCommentByStatisticsSelect]
(
	@YearMonth VARCHAR(6),
	@BeginDate DateTime,
	@EndDate DateTime
)
AS
BEGIN
	DECLARE @t AS TABLE
	(
		YearMonth VARCHAR(6),
		ManagerUserId SMALLINT,
		UserName VARCHAR(10),
		GoodComment INT,
		CommonComment INT,
		InvalidComment INT,
		GoodInterview INT,
		CommonInterview INT,
		InvalidInterview INT
	)
	INSERT INTO @t(ManagerUserId, UserName, YearMonth)
		SELECT DISTINCT verifyman,name,@YearMonth FROM
		(
			(	
				SELECT DISTINCT a.verifyman, b.Name
				FROM Comments a, managerUser b
				WHERE verifyman  IS NOT NULL 
				AND a.verifyman=b.Id
			) 
			UNION 
			(	
				SELECT DISTINCT a.verifyman, b.Name
				FROM interview a, managerUser b
				WHERE verifyman  IS NOT NULL 
				AND a.verifyman=b.Id
			)
		)E
	
	--优质评论
	UPDATE z SET GoodComment=(
		SELECT COUNT(1)
		FROM comments a
		WHERE a.verifyman = z.ManagerUserId 
		AND a.commenttype=2 
		AND a.verifyDate>@BeginDate 
		AND a.verifyDate<@EndDate 
		GROUP BY a.commenttype, a.verifyman)
	FROM @t z

	--一般评论
	UPDATE z SET CommonComment=(
		SELECT  COUNT(1)
		FROM comments a
		WHERE a.verifyman=z.ManagerUserId  
		AND a.commenttype=1 
		AND a.verifyDate>@BeginDate 
		AND a.verifyDate<@EndDate  
		GROUP BY a.commenttype,a.verifyman)
	FROM @t z

	--无效评论		
	UPDATE z SET InvalidComment=(
		SELECT  COUNT(1)
		FROM comments a
		WHERE a.verifyman=z.ManagerUserId 
		AND a.commenttype=3 
		AND a.verifyDate>@BeginDate 
		AND a.verifyDate<@EndDate  
		GROUP BY a.commenttype,a.verifyman)
	FROM @t z

	--优质面经
	UPDATE z SET GoodInterview=(
		SELECT COUNT(1)
		FROM interview a
		WHERE a.verifyman=z.ManagerUserId 
		AND a.interviewtype=2 
		AND a.verifyDate>@BeginDate 
		AND a.verifyDate<@EndDate 
		GROUP BY a.interviewtype,a.verifyman)
	FROM @t z

	--一般面经		
	UPDATE z SET CommonInterview=(
		SELECT COUNT(1)
		FROM interview a
		WHERE a.verifyman=z.ManagerUserId  
		AND a.interviewtype=1 
		AND a.verifyDate>@BeginDate 
		AND a.verifyDate<@EndDate 
		GROUP BY a.interviewtype,a.verifyman)
	FROM @t z

	--无效面经
	UPDATE z SET InvalidInterview=(
		SELECT COUNT(1)
		FROM interview a
		WHERE a.verifyman=z.ManagerUserId AND  a.interviewtype=3 
		AND a.verifyDate>@BeginDate 
		AND a.verifyDate<@EndDate 
		GROUP BY a.interviewtype,a.verifyman)
	FROM @t z

	SELECT * FROM @t
END

GO
/****** Object:  StoredProcedure [dbo].[bpCommentsByCpMainID_CpLicenceUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--###########################
--创建时间：2014.12.18
--创建人：Nick
--说明：营业执照审核时更新点评 面经信息
--###########################
CREATE PROCEDURE [dbo].[bpCommentsByCpMainID_CpLicenceUpdate]
(
	@cpMainID INT,
	@CompanyNameOld NVARCHAR(50),
	@CompanyNameNew NVARCHAR(50),
	@TypeID INT --1修改执照 2新增执照
)
AS
return
SET NOCOUNT ON
BEGIN 
	IF @TypeID = 1
	BEGIN
		IF @CompanyNameOld<>@CompanyNameNew
		BEGIN
			DELETE FROM Comments WHERE CpmainID = @cpMainID
			DELETE FROM InterView WHERE CpmainID = @cpMainID
			
			--添加营业执照 同步 点评信息
			INSERT INTO Comments 
			SELECT @cpMainID,PaMainID,IP,SessionID,Relation,GradeStar,Remark1,Remark2,Remark3,Title,Position,WorkRegionID,
			EntryDate,QuitDate,AddDate,CommentType,VerifyMan,VerifyDate,ReplyDate,ReplyContent,ReplyVerifyMan,ReplyVerifyDate,
			PraiseCount,LoginPraiseCount,ReplyVerifyResult,0 
			FROM Comments
			WHERE CpMainID IN (
				SELECT TOP 1 CpMainID FROM Comments
				WHERE CpMainID IN (SELECT ID FROM CpMain WHERE Name = @CompanyNameNew AND MemberType > 1)
				AND CpMainID <> @cpMainID
			)
			
			--添加营业执照 同步 面经信息
			INSERT INTO InterView 
			SELECT @cpMainID,PaMainID,IP,SessionID,JobName,InterviewDate,InterViewResult,SalaryMonth,InterViewExperience,
			InterviewFeeling,Title,AddDate,VerifyMan,VerifyDate,InterviewType,ReplyDate,ReplyContent,ReplyVerifyMan,
			ReplyVerifyDate,ReplyVerifyResult,PraiseCount,LoginPraiseCount,0 
			FROM InterView
			WHERE CpMainID IN (
				SELECT TOP 1 CpMainID FROM InterView
				WHERE CpMainID IN (SELECT ID FROM CpMain WHERE Name = @CompanyNameNew AND MemberType > 1)
				AND CpMainID <> @cpMainID
			)
		END
	END
	ELSE
	BEGIN
		--添加营业执照 同步 点评信息
		INSERT INTO Comments 
		SELECT @cpMainID,PaMainID,IP,SessionID,Relation,GradeStar,Remark1,Remark2,Remark3,Title,Position,WorkRegionID,
		EntryDate,QuitDate,AddDate,CommentType,VerifyMan,VerifyDate,ReplyDate,ReplyContent,ReplyVerifyMan,ReplyVerifyDate,
		PraiseCount,LoginPraiseCount,ReplyVerifyResult,0 
		FROM Comments
		WHERE CpMainID IN (
			SELECT TOP 1 CpMainID FROM Comments
			WHERE CpMainID IN (SELECT ID FROM CpMain WHERE Name = @CompanyNameNew AND MemberType > 1)
			AND CpMainID <> @cpMainID
		)
		
		--添加营业执照 同步 面经信息
		INSERT INTO InterView 
		SELECT @cpMainID,PaMainID,IP,SessionID,JobName,InterviewDate,InterViewResult,SalaryMonth,InterViewExperience,
		InterviewFeeling,Title,AddDate,VerifyMan,VerifyDate,InterviewType,ReplyDate,ReplyContent,ReplyVerifyMan,
		ReplyVerifyDate,ReplyVerifyResult,PraiseCount,LoginPraiseCount,0 
		FROM InterView
		WHERE CpMainID IN (
			SELECT TOP 1 CpMainID FROM InterView
			WHERE CpMainID IN (SELECT ID FROM CpMain WHERE Name = @CompanyNameNew AND MemberType > 1)
			AND CpMainID <> @cpMainID
		)
	END
END


GO
/****** Object:  StoredProcedure [dbo].[bpCommentsSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[bpCommentsSelect]
(
	@Where VARCHAR(MAX)
)
AS
BEGIN
	DECLARE @Sql VARCHAR(MAX)
	SET @Sql = 'SELECT TOP 2000 d.Name CompanyName,e.UserName,a.AddDate,a.CommentType,
		d.SecondID,d.dcProvinceID,f.ManageruserID,f.Name ManageruserName,a.VerifyDate 
	FROM Maindb..Comments a,
		oadb..opCommentCompany b,
		oadb..opWorkUserPaMain c,
		MainDB..cpMain d,
		MainDB..paMain e,
		oadb..WorkUser f 
	WHERE a.cpMainID=b.cpMainID 
	AND b.WorkUserID=c.WorkUserID 
	AND a.paMainID=c.paMainID 
	AND d.ID=a.cpMainID 
	AND e.ID=a.paMainID 
	AND f.ID=b.WorkUserID' + @where + 
	' ORDER BY a.AddDate DESC'
	EXEC(@SQL)
END

GO
/****** Object:  StoredProcedure [dbo].[bpCompany_BlackByCompanyNameSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--###########################
--创建时间：2014.12.10
--创建人：Nick
--说明：根据单位名称判断是否在黑名单
--###########################
CREATE PROCEDURE [dbo].[bpCompany_BlackByCompanyNameSelect]
(
	@CompanyName VARCHAR(100)
)
AS
BEGIN 
	SELECT * FROM Company_Black WITH(NOLOCK) 
	WHERE CHARINDEX(lTrim(rTrim(Companyname)), @CompanyName) > 0
END


GO
/****** Object:  StoredProcedure [dbo].[bpCompany_BlackByReasonUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----------------
--创建日期：2010-9-14
--创建人：lambo
--功能说明：根据编号修改企业黑名单的增加原因
--用于企业黑名单页面
-----------------
CREATE PROCEDURE [dbo].[bpCompany_BlackByReasonUpdate]
(
	@ID INT,
	@Reason VARCHAR(500)
)
AS
BEGIN TRY
	UPDATE Company_Black SET Reason=@Reason WHERE ID=@ID
	RETURN 1
END TRY
BEGIN CATCH
	RETURN 0
END CATCH














GO
/****** Object:  StoredProcedure [dbo].[bpCompany_BlackDelete]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----------------
--创建日期：2010-9-14
--创建人：lambo
--功能说明：根据编号删除一条企业黑名单信息
--用于企业黑名单页面
-----------------
CREATE PROCEDURE [dbo].[bpCompany_BlackDelete]
(
	@ID INT
)
AS
BEGIN TRY
	DELETE FROM Company_Black WHERE ID=@ID
	RETURN 1
END TRY
BEGIN CATCH
	RETURN 0
END CATCH














GO
/****** Object:  StoredProcedure [dbo].[bpCompany_BlackInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----------------
--创建日期：2010-9-14
--创建人：lambo
--功能说明：插入一条企业黑名单信息
--用于增加企业黑名单页面
-----------------
CREATE PROCEDURE [dbo].[bpCompany_BlackInsert]
(
	@CompanyName VARCHAR(50),
	@ManagerID INT,
	@Email VARCHAR(50),
	@Reason VARCHAR(500),
	@Mobile VARCHAR(11)
)
AS
BEGIN TRY
	INSERT INTO Company_Black
	(	
		CompanyName,
		ManagerID,
		Email,
		Reason,
		Mobile
	)
	VALUES
	(
		LTRIM(RTRIM(@CompanyName)),
		@ManagerID,
		LTRIM(RTRIM(@Email)),
		@Reason,
		LTRIM(RTRIM(@Mobile))
	)
	RETURN @@IDENTITY
END TRY
BEGIN CATCH
	RETURN 0
END CATCH














GO
/****** Object:  StoredProcedure [dbo].[bpCompany_BlackSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


-----------------
--创建日期：2010-9-14
--创建人：lambo
--功能说明：根据条件查询企业黑名单记录
--用于企业黑名单页面
-----------------
CREATE PROCEDURE [dbo].[bpCompany_BlackSelect]
(
	@WHERE VARCHAR(1000)
)
AS
BEGIN
	DECLARE @SQL VARCHAR(2000)
	SET @SQL = 'SELECT * FROM Company_Black WITH(NOLOCK) WHERE 1=1 '
	IF LEN(@WHERE) > 0
	BEGIN
		SET @WHERE = dbo.SafeSql(@Where)
		SET @SQL = @SQL + @WHERE
	END
	SET @SQL=@SQL + ' ORDER BY AddedDate DESC'
	EXEC(@SQL)
END




GO
/****** Object:  StoredProcedure [dbo].[bpCompany_DeleteedSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-----------------
--创建日期：2011-01-28
--创建人：lambo
--功能说明：根据查询条件查询已删除的企业的信息
--用于删除单位记录页面
-----------------
CREATE PROCEDURE [dbo].[bpCompany_DeleteedSelect]
(
	@WHERE VARCHAR(1000)
)
AS
BEGIN
	BEGIN TRY
		DECLARE @SQL AS VARCHAR(2000)
		SET @SQL='SELECT DISTINCT TOP 200 * FROM Company_Deleted a WITH(NOLOCK)'
		IF LEN(@WHERE) > 0
		BEGIN
			SET @WHERE = dbo.SafeSql(@Where)
			SET @SQL = @SQL + @WHERE
		END
		SET @SQL = @SQL + ' ORDER BY AddDate DESC'
		EXEC(@SQL)
	END TRY
	BEGIN CATCH
	END CATCH
END



GO
/****** Object:  StoredProcedure [dbo].[bpCompany_xinxiDelete]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-----------------
--创建日期：2010-9-14
--创建人：lambo
--功能说明：根据编号删除一条记录
--用于后台临时库查询页面
-----------------
CREATE PROCEDURE [dbo].[bpCompany_xinxiDelete]
(
	@ID INT
)
AS
BEGIN TRY
	DELETE FROM Company_xinxi WHERE ID=@ID
	RETURN 1
END TRY
BEGIN CATCH
	RETURN 0
END CATCH














GO
/****** Object:  StoredProcedure [dbo].[bpCompany_xinxiSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----------------
--创建日期：2010-9-14
--创建人：lambo
--功能说明：根据条件查询临时单位库的数据
--用于临时单位库查询页面
--修改：按照注册时间排序harry
-----------------
CREATE PROCEDURE [dbo].[bpCompany_xinxiSelect]
(
	@count INT,
	@WHERE VARCHAR(1000)
)
AS
BEGIN
	DECLARE @SQL AS VARCHAR(2000)
	SET @SQL='SELECT TOP '+LTRIM(str(@count))+' * FROM company_xinxi '
	IF LEN(@WHERE) > 5
	BEGIN
		SET @WHERE = dbo.SafeSql(@Where)
		SET @SQL = @SQL + ' WHERE ' + RIGHT(@WHERE, LEN(@Where) - 5)
	END
	SET @SQL = @SQL + ' ORDER BY regdate DESC, id DESC'
 	EXEC(@SQL)
END


GO
/****** Object:  StoredProcedure [dbo].[bpCompany_xinxiUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----------------
--创建日期：2010-9-14
--创建人：lambo
--功能说明：根据编号修改单位临时库内的一条记录的邮箱和公司名称
--用于后台临时库查询页面
-----------------
CREATE PROCEDURE [dbo].[bpCompany_xinxiUpdate]
(
	@ID INT,
	@email VARCHAR(50),
	@companyname VARCHAR(50)
)
AS
BEGIN TRY
	UPDATE Company_xinxi SET email=@email,companyname=@companyname WHERE ID=@ID
	RETURN 1
END TRY
BEGIN CATCH
	RETURN 0
END CATCH














GO
/****** Object:  StoredProcedure [dbo].[bpCompanyInformAllSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-----------------
--创建日期：2010-9-14
--创建人：lambo
--功能说明：查询所有的单位分类通知
--用于后台单位分类通知
-----------------
CREATE PROCEDURE [dbo].[bpCompanyInformAllSelect]
AS
BEGIN
	SELECT a.*,b.SubSiteUrl,b.SubSiteCity FROM CompanyInform a WITH(NOLOCK),dcSubSite b WITH(NOLOCK)
	WHERE b.ID=LEFT(a.Province,2)
	ORDER BY AddDate DESC
END














GO
/****** Object:  StoredProcedure [dbo].[bpCompanyInformByStatusUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----------------
--创建日期：2010-9-14
--创建人：lambo
--功能说明：修改单位用户分类通知的状态
--用于单位用户分类通知页面
-----------------
CREATE PROCEDURE [dbo].[bpCompanyInformByStatusUpdate]
	@ID INT
AS
BEGIN TRY
	UPDATE CompanyInform SET Status=Status-1 WHERE ID=@ID
	RETURN 1
END TRY
BEGIN CATCH
	RETURN 0
END CATCH














GO
/****** Object:  StoredProcedure [dbo].[bpCompanyInformDelete]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----------------
--创建日期：2010-9-14
--创建人：lambo
--功能说明：删除一条单位分类通知
--用于后台单位分类通知
-----------------
CREATE PROCEDURE [dbo].[bpCompanyInformDelete]
	@ID INT
AS
BEGIN TRY
	DELETE FROM CompanyInform WHERE ID=@ID
END TRY
BEGIN CATCH
	GOTO ERR
END CATCH
RETURN 1
ERR:
BEGIN
	RETURN 0
END 














GO
/****** Object:  StoredProcedure [dbo].[bpCompanyInformSave]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----------------
--创建日期：2010-9-14
--创建人：lambo
--功能说明：增加或修改单位分类通知，如果@ID>0则是修改，否则是增加
--用于后台增加或修改单位分类通知
--修改：harry2016-8-17 修改content长度
-----------------
CREATE PROCEDURE [dbo].[bpCompanyInformSave]
(
	@ID INT,
    @Object VARCHAR(50),
    @Title VARCHAR(50),
	@Content VARCHAR(MAX),
	@Type INT,
	@Link VARCHAR(100),
	@Province VARCHAR(100),
	@EndDate VARCHAR(20)
)
AS
BEGIN TRAN
	Declare @MaxId AS INT
	BEGIN TRY
		IF @ID>0
			BEGIN
				UPDATE CompanyInform SET
					Object = @Object,
					Title = @Title,
					Content = @Content,
					Type = @Type,
					AddDate = GETDATE(),
					Link = @Link,
					Province = @Province,
					EndDate = @EndDate
				WHERE ID=@ID
				SET @MaxID = @ID
			End
		ELSE
			BEGIN
				INSERT INTO CompanyInform
					(
						Object,Title,Content,Type,
						Province,EndDate,Link
					)
				VALUES
					(
						@Object,@Title,@Content,@Type,
						@Province,@EndDate,@Link
					)
				SET @MaxID = @@IDENTITY
		END
	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH
COMMIT TRAN
RETURN @MaxID
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END
GO
/****** Object:  StoredProcedure [dbo].[bpCompanyInformSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----------------
--创建日期：2010-9-14
--创建人：lambo
--功能说明：根据编号查询一条单位分类通知
--用于后台单位分类通知
-----------------
CREATE PROCEDURE [dbo].[bpCompanyInformSelect]
(
    @ID INT
)
AS
BEGIN
    SELECT * FROM CompanyInform WHERE ID = @ID
END














GO
/****** Object:  StoredProcedure [dbo].[bpCompanyNotifyDelete]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----------------
--创建日期：2010-9-14
--创建人：lambo
--功能说明：根据编号删除一条网站消息
--用于后台单位用户管理网站消息页面
-----------------
CREATE PROCEDURE [dbo].[bpCompanyNotifyDelete]
(
	@ID INT
)
AS
BEGIN TRY
	DELETE FROM CompanyNotify WHERE ID = @ID
END TRY
BEGIN CATCH
	RETURN 0
END CATCH
RETURN 1














GO
/****** Object:  StoredProcedure [dbo].[bpCompanyNotifyInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----------------
--创建日期：2010-9-14
--创建人：lambo
--功能说明：增加一条网站消息
--用于后台单位用户管理网站消息页面
-----------------
CREATE PROCEDURE [dbo].[bpCompanyNotifyInsert]
(
	@CompanyId INT,
	@Type SMALLINT,
	@Content NVARCHAR(600),
	@EndDate VARCHAR(20),
	@ManagerUserID INT,
	@CompanyName VARCHAR(60)
)
AS
BEGIN TRY
	If @Type = 1 
		Set @EndDate = NULL
	INSERT INTO CompanyNotify (CompanyId,[type],[Content],EndDate,ManagerUserID,CompanyName) 
		VALUES(@CompanyId,@Type,@Content,@EndDate,@ManagerUserID,@CompanyName) 
END TRY
BEGIN CATCH
	RETURN 0
END CATCH
RETURN 1














GO
/****** Object:  StoredProcedure [dbo].[bpCompanyNotifySelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[bpCompanyNotifySelect]
(
	@WHERE VARCHAR(1000)
)
AS
BEGIN
	DECLARE @SQL AS VARCHAR(2000)
	SET @SQL='SELECT TOP 300 a.AddDate NotifyAddDate,* FROM CompanyNotify a WITH(NOLOCK) LEFT JOIN Maindb..Manageruser b ON a.ManageruserID=b.ID WHERE 1=1 '
	IF LEN(@WHERE) > 0
	BEGIN
		SET @WHERE = dbo.SafeSql(@Where)
		SET @SQL = @SQL + @WHERE
	END
	SET @SQL = @SQL + ' ORDER BY a.AddDate DESC'
	EXEC(@SQL)
END














GO
/****** Object:  StoredProcedure [dbo].[bpConsultantByRepeatSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--[bpConsultantListSelect] 'And username like ''%aoli%''',12,1
CREATE PROCEDURE [dbo].[bpConsultantByRepeatSelect]
(
	@Where VARCHAR(2000),
	@Page SMALLINT
)
AS
BEGIN
	BEGIN TRY
		SET @WHERE = dbo.SafeSQLBack(@WHERE)
		DECLARE @SQL AS VARCHAR(2000)
		DECLARE @strOrder AS VARCHAR(1000)
		SET @strOrder = ' ORDER BY RegDate DESC'
		
		CREATE TABLE #T(
			TitleID BIGINT,
			ID INT,
			Name NVARCHAR(50),
			HasLicence BIT,
			ziliaodate SMALLDATETIME,
			Quality TINYINT,
			ConsultantID SMALLINT,
			RegDate SMALLDATETIME,
			dcProvinceID TINYINT,
			MemberType TINYINT,
			VerifyResult TINYINT,
			IsAgent BIT,
			LastLoginDate SMALLDATETIME,
			UnlimitedDate SMALLDATETIME,
			Balance SMALLINT,
			BalanceDate SMALLDATETIME,
			IsLimitLogin TINYINT,
			RefreshDate SMALLDATETIME,
			ConsultantDate SMALLDATETIME,
			IsLock BIT,
			ResumeQuota SMALLINT,
			IsDelete BIT,
			JobNumber SMALLINT,
			VerifyMan SMALLINT,
			HasPaid BIT,
			ContactDoneDate SMALLDATETIME,
			ContactDoneMan SMALLINT,
			ContactDoneAdd SMALLDATETIME,
			ContactDoneID INT,
			ContactNotDoneDate SMALLDATETIME,
			ContactNotDoneMan SMALLINT,
			ContactNotDoneAdd SMALLDATETIME,
			ContactNotDoneID INT,
			DownLoadToday SMALLINT,
			JobViewNumber SMALLINT,
			SendResumeNumber SMALLINT,
			SendResumeNumberHigh SMALLINT
		)
		SET @SQL='
			INSERT INTO #T
			(TitleID,ID,Name,HasLicence,Quality,ConsultantID,RegDate,dcProvinceID,MemberType,VerifyResult,
			IsAgent,LastLoginDate,UnlimitedDate,Balance,BalanceDate,IsLimitLogin,RefreshDate,ConsultantDate,IsLock,
			ResumeQuota,IsDelete,JobNumber)
			SELECT ROW_NUMBER() OVER ( ORDER BY b.id DESC, a.ID DESC) AS TitleID,a.ID,a.Name,HasLicence,Quality,	
			ConsultantID,a.RegDate,dcProvinceID,MemberType,VerifyResult,IsAgent,LastLoginDate,UnlimitedDate,Balance,
			BalanceDate,IsLimitLogin,RefreshDate,ConsultantDate,IsLock,ResumeQuota,a.IsDelete,JobNumber
			FROM cpMain a WITH(NOLOCK)
			INNER JOIN (SELECT TOP 500 Name, Max(ID) ID FROM cpMain WITH(NOLOCK) 
				WHERE name <> ''某公司'' ' + @Where + '
				GROUP BY Name HAVING COUNT(*) > 1 
				ORDER BY Max(ID) DESC) b ON a.Name = b.Name
			ORDER BY b.ID DESC'
		EXEC(@SQL)

		UPDATE #T SET ziliaodate = (SELECT TOP 1 CheckDate FROM cpLicence Where cpMainID=#T.ID ORDER BY ID DESC),
			VerifyMan = (Select TOP 1 VerifyMan From bsCpVerify Where bsCpVerify.cpMainID=#T.ID ORDER BY ID DESC),
			HasPaid = (SELECT TOP 1 ID FROM caOrder WHERE Paid>0 AND OpenDate IS NOT NULL AND cpMainID=#T.ID),
			ContactDoneDate = (SELECT top 1 BeginTime FROM contact WITH(NOLOCK) WHERE companyid=#T.ID AND status=2 ORDER BY begintime DESC),
			ContactDoneMan = (SELECT top 1 ManagerUserID FROM contact WITH(NOLOCK) WHERE companyid=#T.ID AND status=2 ORDER BY begintime DESC),
			ContactDoneAdd = (SELECT top 1 AddDate FROM contact WITH(NOLOCK) WHERE companyid=#T.ID AND status=2 ORDER BY begintime DESC),
			ContactDoneID = (SELECT top 1 ID FROM contact WITH(NOLOCK) WHERE companyid=#T.ID AND status=2 ORDER BY begintime DESC),
			ContactNotDoneDate = (SELECT top 1 BeginTime FROM contact WITH(NOLOCK) WHERE companyid=#T.ID AND status=1 ORDER BY begintime DESC),
			ContactNotDoneMan = (SELECT top 1 ManagerUserID FROM contact WITH(NOLOCK) WHERE companyid=#T.ID AND status=1 ORDER BY begintime DESC),
			ContactNotDoneAdd = (SELECT top 1 AddDate FROM contact WITH(NOLOCK) WHERE companyid=#T.ID AND status=1 ORDER BY begintime DESC),
			ContactNotDoneID = (SELECT top 1 ID FROM contact WITH(NOLOCK) WHERE companyid=#T.ID AND status=1 ORDER BY begintime DESC),
			DownLoadToday = (SELECT COUNT(ID) cnt FROM caActiveLog WHERE CONVERT(VARCHAR(10),AddDate,112)=CONVERT(VARCHAR(10),GETDATE(),112) AND cpMainID=#T.ID),
			JobViewNumber = (select COUNT(1) cnt from paJobViewLog a with(nolock),Job b with(nolock) where b.cpMainID=#T.ID and a.JobID=b.ID and b.valid=1 and a.Adddate>getdate()-30)
		WHERE TitleID > (@Page - 1) * 20 AND TitleID <= @Page * 20

		UPDATE a SET SendResumeNumber = AllNumber,
			SendResumeNumberHigh = NotOpenNumber FROM #T a
		INNER JOIN qryJobApplyMonth b ON a.ID=b.cpMainID
		WHERE TitleID > (@Page-1)*20 AND TitleID <= @Page*20
		
		SELECT COUNT(*) FROM #T WITH(NOLOCK)
		SELECT * FROM #T WITH(NOLOCK) WHERE TitleID > (@Page-1)*20 AND TitleID <= @Page*20
		DROP TABLE #T
	END TRY
	BEGIN CATCH
		DROP TABLE #T
	END CATCH
END







GO
/****** Object:  StoredProcedure [dbo].[bpConsultantListSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[bpConsultantListSelect]
(
	@WHERE VARCHAR(1000),
	@ORDER TINYINT,
	@Page SMALLINT
)
AS
SET NOCOUNT ON
BEGIN
	SET @WHERE = dbo.SafeSQLBack(@WHERE)
	DECLARE @SQL AS VARCHAR(2000)
	DECLARE @strOrder AS VARCHAR(1000)
	SET @strOrder = ''
	IF @ORDER = 1
		SET @strOrder = @strOrder + ' ORDER BY ConsultantDate DESC'
	ELSE IF @ORDER = 2
		SET @strOrder = @strOrder + ' ORDER BY LastLoginDate DESC'
	ELSE IF @ORDER = 3
		SET @strOrder = @strOrder + ' ORDER BY (SELECT TOP 1 CerDate FROM MainDB..cpCertification WITH(NOLOCK) WHERE cpMainID = a.ID ORDER BY CerDate DESC) DESC'
	ELSE IF @ORDER = 4
		SET @strOrder = @strOrder + ' ORDER BY RegDate DESC'
	ELSE IF @ORDER = 5
		SET @strOrder = @strOrder + ' ORDER BY JobNumber DESC'
	ELSE IF @ORDER = 6
		SET @strOrder = @strOrder + ' ORDER BY (SELECT COUNT(1) FROM CaCvQuotaLog WITH(NOLOCK) WHERE cpMainID = a.ID) DESC'
	ELSE IF @ORDER = 12
		SET @strOrder = @strOrder + ' ORDER BY (SELECT COUNT(1) FROM CaActiveLog WITH(NOLOCK) WHERE cpMainID = a.ID AND AddDate > CONVERT(VARCHAR(10), GETDATE(), 23)) DESC, LastLoginDate DESC'
	ELSE IF @ORDER = 7
		SET @strOrder = @strOrder + ' ORDER BY (SELECT TOP 1 AddDate FROM bsCpStatus WITH(NOLOCK) WHERE cpMainID = a.ID AND statusID=9 ORDER BY AddDate DESC) DESC'
	ELSE IF @ORDER = 8
		SET @strOrder = @strOrder + ' ORDER BY (Select TOP 1 VerifyDate From bsCpVerify Where cpMainID=a.ID) DESC'
	ELSE IF @ORDER = 9
		SET @strOrder = @strOrder + ' ORDER BY (SELECT TOP 1 begintime FROM contact WITH(NOLOCK) WHERE status=2 AND companyid=a.ID ORDER BY begintime DESC) DESC'
	ELSE IF @ORDER = 10
		SET @strOrder = @strOrder + ' ORDER BY (SELECT TOP 1 begintime FROM contact WITH(NOLOCK) WHERE status=2 AND companyid=a.ID ORDER BY begintime DESC)'
	ELSE IF @ORDER = 14
		SET @strOrder = @strOrder + ' ORDER BY (SELECT TOP 1 EndDate FROM caOrder WITH(NOLOCK) WHERE OrderType=8 AND BeginDate<GetDate() AND EndDate>GETDATE() AND cpMainId = a.Id AND IsDeleted = 0)'
	ELSE IF @ORDER = 15
		SET @strOrder = @strOrder + ' ORDER BY BalanceDate'
	ELSE IF @ORDER = 13
		SET @strOrder = @strOrder + ' ORDER BY Balance'
	ELSE IF @ORDER = 17
		SET @strOrder = @strOrder +  ' ORDER BY d.Id DESC'
	Else IF @ORDER = 0
		SET @strOrder = @strOrder + ' ORDER BY LastLoginDate DESC'
	ELSE IF @ORDER = 19
		SET @strOrder = @strOrder + ' ORDER BY (SELECT TOP 1 EndDate FROM caOrder WITH(NOLOCK) WHERE OrderType=8 AND BeginDate<GetDate() AND EndDate>GETDATE() AND cpMainId = a.Id AND IsDeleted = 0) DESC'
	ELSE IF @ORDER = 20
		SET @strOrder = @strOrder + ' ORDER BY BalanceDate DESC'
	Else IF @ORDER = 16
		SET @strOrder = @strOrder + ' ORDER BY MemberDate'
	Else IF @ORDER = 21
		SET @strOrder = @strOrder + ' ORDER BY MemberDate DESC'
	Else IF @ORDER = 22
		SET @strOrder = @strOrder + ' order by (select top 1  checkdate from cpimage WITH(NOLOCK) where cpmainid=a.id and imgtype=1 and HasPassed=1 ORDER BY checkdate  DESC) desc'
	Else IF @ORDER = 23
		SET @strOrder = @strOrder + ' ORDER BY (SELECT TOP 1 OpenDate FROM caOrder WITH(NOLOCK) WHERE OrderType=8 AND BeginDate<GetDate() AND EndDate>GETDATE() AND cpMainId = a.Id AND IsDeleted = 0) DESC'

	CREATE TABLE #T(
		TitleID BIGINT,
		ID INT,
		Name VARCHAR(100) COLLATE Chinese_PRC_CI_AS,
		HasLicence BIT,
		ziliaodate SMALLDATETIME,
		Quality TINYINT,
		ConsultantID SMALLINT,
		RegDate SMALLDATETIME,
		dcProvinceID TINYINT,
		MemberType TINYINT,
		VerifyResult TINYINT,
		IsAgent BIT,
		LastLoginDate SMALLDATETIME,
		UnlimitedDate SMALLDATETIME,
		Balance SMALLINT,
		BalanceDate SMALLDATETIME,
		IsLimitLogin TINYINT,
		RefreshDate SMALLDATETIME,
		ConsultantDate SMALLDATETIME,
		IsLock BIT,
		ResumeQuota SMALLINT,
		IsDelete BIT,
		JobNumber SMALLINT,
		VerifyMan SMALLINT,
		HasPaid BIT,
		ContactDoneDate SMALLDATETIME,
		ContactDoneMan SMALLINT,
		ContactDoneAdd SMALLDATETIME,
		ContactDoneID INT,
		ContactNotDoneDate SMALLDATETIME,
		ContactNotDoneMan SMALLINT,
		ContactNotDoneAdd SMALLDATETIME,
		ContactNotDoneID INT,
		DownLoadToday SMALLINT,
		JobViewNumber SMALLINT,
		SendResumeNumber SMALLINT,
		SendResumeNumberHigh SMALLINT,
		memberdate smalldatetime,
		RealName TINYINT,
		HasLogo BIT,
		CerMemberType TINYINT,
		CerType TINYINT,
		CerDate SMALLDATETIME,
		
	)
	SET @SQL='
		INSERT INTO #T
		(TitleID,ID,Name,HasLicence,Quality,ConsultantID,RegDate,dcProvinceID,MemberType,VerifyResult,
		IsAgent,LastLoginDate,UnlimitedDate,Balance,BalanceDate,IsLimitLogin,RefreshDate,ConsultantDate,IsLock,
		ResumeQuota,IsDelete,JobNumber,memberdate,RealName,HasLogo)
		SELECT TOP 4000 ROW_NUMBER() OVER (' + @strOrder + ') AS TitleID,a.ID,a.Name,HasLicence,Quality,
		ConsultantID,a.RegDate,dcProvinceID,a.MemberType,VerifyResult,IsAgent,LastLoginDate,UnlimitedDate,Balance,
		BalanceDate,IsLimitLogin,RefreshDate,ConsultantDate,IsLock,ResumeQuota,a.IsDelete,JobNumber, 
		memberdate,a.RealName,a.HasLogo
		FROM cpMain a WITH(NOLOCK)'

	IF @Order = 17
		SET @SQL = @SQL + ' INNER JOIN (SELECT b.cpMainId, MAX(a.Id) Id 
		FROM caFeePageViewLog a, caMain b
		WHERE a.caMainId = b.Id
		GROUP BY b.cpMainId
		) d ON a.ID=d.cpMainID '
	
	SET @SQL = @SQL + '	WHERE 1=1 '

	IF LEN(@WHERE) > 0
		SET @SQL = @SQL + @WHERE
	--print @SQL
	EXEC(@SQL)

	UPDATE #T SET ziliaodate = (SELECT Top 1 CheckDate FROM cpLicence Where cpMainID=#T.ID ORDER BY ID DESC),
		VerifyMan = (Select TOP 1 VerifyMan From bsCpVerify Where bsCpVerify.cpMainID=#T.ID ORDER BY ID DESC),
		HasPaid = (SELECT TOP 1 ID FROM caOrder WHERE Paid>0 AND OpenDate IS NOT NULL AND cpMainID=#T.ID AND IsDeleted = 0),
		ContactDoneDate = (SELECT top 1 BeginTime FROM contact WITH(NOLOCK) WHERE companyid=#T.ID AND status=2 ORDER BY begintime DESC),
		ContactDoneMan = (SELECT top 1 ManagerUserID FROM contact WITH(NOLOCK) WHERE companyid=#T.ID AND status=2 ORDER BY begintime DESC),
		ContactDoneAdd = (SELECT top 1 AddDate FROM contact WITH(NOLOCK) WHERE companyid=#T.ID AND status=2 ORDER BY begintime DESC),
		ContactDoneID = (SELECT top 1 ID FROM contact WITH(NOLOCK) WHERE companyid=#T.ID AND status=2 ORDER BY begintime DESC),
		ContactNotDoneDate = (SELECT top 1 BeginTime FROM contact WITH(NOLOCK) WHERE companyid=#T.ID AND status=1 ORDER BY begintime DESC),
		ContactNotDoneMan = (SELECT top 1 ManagerUserID FROM contact WITH(NOLOCK) WHERE companyid=#T.ID AND status=1 ORDER BY begintime DESC),
		ContactNotDoneAdd = (SELECT top 1 AddDate FROM contact WITH(NOLOCK) WHERE companyid=#T.ID AND status=1 ORDER BY begintime DESC),
		ContactNotDoneID = (SELECT top 1 ID FROM contact WITH(NOLOCK) WHERE companyid=#T.ID AND status=1 ORDER BY begintime DESC),
		DownLoadToday = (SELECT COUNT(ID) cnt FROM caActiveLog WHERE CONVERT(VARCHAR(10),AddDate,112)=CONVERT(VARCHAR(10),GETDATE(),112) AND cpMainID=#T.ID),
		JobViewNumber = (select COUNT(1) cnt from paJobViewLog a with(nolock),Job b with(nolock) where b.cpMainID=#T.ID and a.JobID=b.ID and b.valid=1 and a.Adddate>getdate()-30),
		CerMemberType = (SELECT TOP 1 MemberType FROM cpCertification WITH(NOLOCK) WHERE cpMainID = #T.ID AND CerStatus = 1 ORDER BY CerDate DESC),
		CerType = (SELECT TOP 1 CerType FROM cpCertification WITH(NOLOCK) WHERE cpMainID = #T.ID AND CerStatus = 1 ORDER BY CerDate DESC),
		CerDate = (SELECT TOP 1 CerDate FROM cpCertification WITH(NOLOCK) WHERE cpMainID = #T.ID AND CerStatus = 1 ORDER BY CerDate DESC) 
	WHERE TitleID > (@Page-1)*20 AND TitleID <= @Page*20
        
	UPDATE #T SET ContactDoneMan = (SELECT top 1 a.AddMan FROM ColdContact a,Coldcustomer  b WITH(NOLOCK) WHERE b.id=a.CustomerID AND  b.CpMainID=#T.ID AND isnull(a.beginTime,'')!='' ORDER BY a.BeginTime DESC),
		ContactDoneDate= (SELECT top 1 a.AddDate FROM ColdContact a,Coldcustomer  b WITH(NOLOCK) WHERE b.id=a.CustomerID AND  b.CpMainID=#T.ID  AND isnull(a.beginTime,'')!='' ORDER BY a.BeginTime DESC), 
		ContactDoneAdd = (SELECT top 1 a.AddDate FROM ColdContact a,Coldcustomer  b WITH(NOLOCK) WHERE b.id=a.CustomerID AND  b.CpMainID=#T.ID  AND isnull(a.beginTime,'')!='' ORDER BY a.BeginTime DESC) 
	WHERE ISNULL(ContactDoneDate ,'')='' and  TitleID > (@Page-1)*20 AND TitleID <= @Page*20

	UPDATE #T SET ContactNotDoneMan = (SELECT top 1 a.AddMan FROM ColdContact a,Coldcustomer  b WITH(NOLOCK) WHERE b.id=a.CustomerID AND  b.CpMainID=#T.ID AND isnull(a.beginTime,'')='' ORDER BY a.AddDate DESC),
		ContactNotDoneDate = (SELECT top 1 a.AddDate FROM ColdContact a,Coldcustomer  b WITH(NOLOCK) WHERE b.id=a.CustomerID AND  b.CpMainID=#T.ID  AND isnull(a.beginTime,'')='' ORDER BY a.AddDate  DESC) ,
		ContactNotDoneAdd = (SELECT top 1 a.AddDate FROM ColdContact a,Coldcustomer  b WITH(NOLOCK) WHERE b.id=a.CustomerID AND  b.CpMainID=#T.ID  AND isnull(a.beginTime,'')='' ORDER BY a.AddDate  DESC) 
	WHERE ISNULL(ContactNotDoneDate ,'')=''  and  TitleID > (@Page-1)*20 AND TitleID <= @Page*20

	UPDATE a SET SendResumeNumber = AllNumber,
		SendResumeNumberHigh = NotOpenNumber FROM #T a
	INNER JOIN qryJobApplyMonth b ON a.ID=b.cpMainID
	WHERE TitleID > (@Page-1)*20 AND TitleID <= @Page*20
	
	SELECT COUNT(*) FROM #T WITH(NOLOCK)
	SELECT a.*, b.MemberType UnFinishedMemberType, b.CerType UnFinishedCerType, c.HasPassed, d.CheckResult PersonalCheckResult, e.CheckResult CompanyEmailCheckResult
	FROM #T a WITH(NOLOCK)
		LEFT JOIN cpCertification b WITH(NOLOCK) ON a.ID = b.cpMainID AND b.CerStatus IS NULL
		LEFT JOIN cpLicence c WITH(NOLOCK) ON b.ID = c.cpCertificationID
		LEFT JOIN cpPersonalAccount d WITH(NOLOCK) ON b.ID = d.cpCertificationID
		LEFT JOIN cpCompanyEmail e WITH(NOLOCK) ON b.ID = e.cpCertificationID
	WHERE TitleID > (@Page-1)*20 AND TitleID <= @Page*20
	DROP TABLE #T
END
GO
/****** Object:  StoredProcedure [dbo].[bpcontactByCompanyIdSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--查询企业联系记录-------------------
--添加人Harry -----------------------
--添加时间：2014-12-16---------------
CREATE PROCEDURE [dbo].[bpcontactByCompanyIdSelect]
(
	@CompanyId VARCHAR(20)
)
AS 
BEGIN 
	SELECT TOP 1 Id, Title, Status, Quality, AddDate 
	FROM Contact WITH(NOLOCK INDEX(IX_Contact_CompanyId))
	WHERE CompanyId = @CompanyId
	ORDER BY ID DESC
END


GO
/****** Object:  StoredProcedure [dbo].[bpContactByCountSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--创建人 Andy
--时间 2015-01-12
--按照条件查询后台联系活动的个数
CREATE PROCEDURE [dbo].[bpContactByCountSelect]
(	
	@ManagerUserID INT,
	@Status INT,
	@BeginTime DATETIME
)
AS
BEGIN		
	SELECT COUNT(1) cnt 
	FROM Contact WITH(NOLOCK)
	WHERE ManagerUserID = @ManagerUserID 
	AND Status = @Status 
	AND BeginTime > @BeginTime 
	AND BeginTime < @BeginTime + 1
END
GO
/****** Object:  StoredProcedure [dbo].[bpContactByCpMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--2018-1-25 peter
CREATE PROCEDURE [dbo].[bpContactByCpMainIDSelect]
(
    @companyType INT,
    @companyid INT
)
AS
SET NOCOUNT ON
BEGIN
    IF NOT EXISTS(SELECT 'x' FROM coldcontact WHERE CustomerId IN(SELECT Id FROM ColdCustomer WHERE cpMainId = @companyid))
        SELECT TOP 10 * FROM contact WITH(NOLOCK)
        WHERE companyType = @companyType 
        AND companyID = @companyid
        ORDER BY addDate DESC    
    ELSE
        SELECT TOP 10 * 
        FROM (
            SELECT *
            FROM Contact WITH(NOLOCK)
            WHERE companyID = @companyid
            UNION
            SELECT Id, Title, @CompanyId CompanyId, '冷客户：' + Description Description,
                BeginTime, 2 Status, AddDate, AddMan Manageruserid, AddMan Creator,
                NULL Quality, NULL CloseDate, 1 CompanyType, LinkMan, TelePhone, NULL Label
            FROM coldcontact 
            WHERE CustomerId IN(SELECT Id FROM ColdCustomer WHERE cpMainId = @CompanyId)
        ) a
        ORDER BY addDate DESC    
END
GO
/****** Object:  StoredProcedure [dbo].[bpContactByStatisticSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--创建人 Andy
--时间 2015-01-08
--按照条件统计后台客户联系活动
CREATE PROCEDURE [dbo].[bpContactByStatisticSelect]
(		
	@StartTime DATETIME,
	@EndTime DATETIME,	
	@CurManagerUserID INT,--当前登录用户ID		
	@Privi INT--当前用户的权限
)
AS
BEGIN
	DECLARE @t AS TABLE(ManagerUserID int, Status INT, Cnt INT)
	INSERT INTO @t
	SELECT a.ManagerUserID, a.Status, COUNT(*) Cnt	
	FROM Contact a WITH(NOLOCK)
	WHERE a.CompanyId > 0
	AND a.BeginTime >= @StartTime
	AND a.BeginTime <= @EndTime
	AND a.ManagerUserID IN (SELECT ID FROM dbo.LowerUser(@CurManagerUserID, @Privi)) 		
	GROUP BY a.ManagerUserID, a.Status
 
	SELECT DISTINCT ManagerUserID,
		ISNULL((SELECT Cnt FROM @t WHERE ManagerUserID = a.ManagerUserID AND status = 2), 0) AS Finished, 
		ISNULL((SELECT Cnt FROM @t WHERE ManagerUserID =a .ManagerUserID AND status = 1), 0) AS NotFinished 
	FROM @t a
	ORDER BY a.ManagerUserID
END

GO
/****** Object:  StoredProcedure [dbo].[bpContactInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--创建人 Andy
--时间 2015-01-09
--插入一条后台沟通记录
--@CompanyID，0表示没有companyID
--修改：删除参数CloseDate，根据Status来判断CloseDate
CREATE PROCEDURE [dbo].[bpContactInsert]
(
	@Title NVARCHAR(50),	
	@CompanyID INT,
	@Description NVARCHAR(400),
	@Begintime DATETIME,	
	@Status	INT,
	@ManagerUserId INT,
	@Creator INT,
	@Quality INT,	
	@CompanyType INT,
	@LinkMan INT,
	@Telephone nvarchar(50)	
)
AS
BEGIN	
	INSERT INTO Contact(Title, Companyid, Description, BeginTime, Status, ManagerUserId, Creator, Quality, CloseDate, LinkMan, Telephone) 
	VALUES (@Title,	(CASE WHEN @Companyid = 0 THEN NULL ELSE @Companyid END), @Description, @BeginTime, @Status, @ManagerUserId, @Creator, @Quality, (CASE WHEN @Status = 2 THEN GETDATE() ELSE NULL END), @LinkMan, @Telephone)		
	RETURN 1
END

GO
/****** Object:  StoredProcedure [dbo].[bpContactSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--创建人 Andy
--时间 2015-01-08
--按照条件查询后台客户联系活动
create PROCEDURE [dbo].[bpContactSelect]
(		
	@StartTime DATETIME,
	@EndTime DATETIME,
	@ManagerUserID INT,
	@CompanyID INT,
	@Status INT,--完成状态，1：未完成, 2完成
	@CurManagerUserID INT,--当前登录用户ID		
	@Privi INT--当前用户的权限
)
AS
BEGIN	
	DECLARE @SQL VARCHAR(1000)
	SET @SQL = '
		SELECT a.*, b.Name, c.Name CompanyName
		FROM Contact a WITH(NOLOCK), ManagerUser b WITH(NOLOCK), cpMain c WITH(NOLOCK)
		WHERE a.CompanyId = c.ID AND a.ManagerUserId = b.Id  
		AND a.BeginTime >= ''' + CONVERT(VARCHAR(20),@StartTime, 20) + ''' 
		AND a.BeginTime <= ''' + CONVERT(VARCHAR(20),@EndTime, 20) + ''''
	
	IF @ManagerUserID > 0
		SET @SQL = @SQL + ' AND a.ManagerUserId = ' + LTRIM(STR(@ManagerUserID))	
	IF @CompanyID > 0
		SET @SQL = @SQL + ' AND companyid = ' + LTRIM(STR(@CompanyID))	
	IF @Status = 1 
		SET @SQL = @SQL + ' AND a.Status = 1 '
	ELSE IF @Status = 2
		SET @SQL = @SQL + ' AND a.Status = 2 '		
	--权限
	SET @SQL = @SQL + ' AND a.ManagerUserId IN (
		SELECT ID FROM dbo.LowerUser(' + LTRIM(STR(@CurManagerUserID)) + ', ' + LTRIM(STR(@Privi)) + '))
		ORDER BY BeginTime'
	--PRINT(@SQL)
	EXEC (@SQL)
END
GO
/****** Object:  StoredProcedure [dbo].[bpCpActivationLogByCountDateSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--创建人 Andy
--时间 2015-01-23
--按照条件获取企业登录间隔
CREATE PROCEDURE [dbo].[bpCpActivationLogByCountDateSelect] 
(		
	@BeginDate VARCHAR(8),  --格式20140101
	@EndDate VARCHAR(8)		--格式20140101
)
AS
BEGIN		
	SET @BeginDate = dbo.SafeSql(@BeginDate)
	SET @EndDate = dbo.SafeSql(@EndDate)
	
	DECLARE @SQL VARCHAR(1000)	
	SET @SQL = 'SELECT TOP 2000 * FROM LogDb..CpActivationLog Where 1=1 '		
	
	IF LEN(@BeginDate) > 0
		SET @SQL = @SQL + ' And CountDate >= ''' + @BeginDate + ''''		
	IF LEN(@EndDate) > 0
		SET @SQL = @SQL + ' And CountDate <= ''' + @EndDate + ''''			  
	
	--PRINT(@SQL)
	EXEC (@SQL)
END



GO
/****** Object:  StoredProcedure [dbo].[bpCpActivationLogByStatisticsSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--bpCpActivationLogByStatisticsSelect --'20120101','20150101'
--创建人 Andy
--时间 2015-01-23
--按照条件统计企业登录间隔
CREATE PROCEDURE [dbo].[bpCpActivationLogByStatisticsSelect] 
(		
	@BeginDate VARCHAR(8),  --格式20140101
	@EndDate VARCHAR(8)		--格式20140101
)
AS
BEGIN		
	SET @BeginDate = dbo.SafeSql(@BeginDate)
	SET @EndDate = dbo.SafeSql(@EndDate)
	
	DECLARE @SQL VARCHAR(1000)	
	SET @SQL = 'SELECT SUM(day1) day1, SUM(day2) day2, SUM(day3) day3, SUM(day7) day7, SUM(day15) day15, SUM(day30) day30, SUM(dayOther) dayOther 
		FROM LogDb..CpActivationLog 
		Where 1 = 1'		
	
	IF LEN(@BeginDate) > 0
		SET @SQL = @SQL + ' And CountDate >= ''' + @BeginDate + ''''		
	IF LEN(@EndDate) > 0
		SET @SQL = @SQL + ' And CountDate <= ''' + @EndDate + ''''			  
	
	--PRINT(@SQL)
	EXEC (@SQL)
END


GO
/****** Object:  StoredProcedure [dbo].[bpcpAttachmentByCpMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--根据cpmainid获取单位资料 Lucifer 2014-12-9
CREATE PROCEDURE [dbo].[bpcpAttachmentByCpMainIDSelect]
(
	@cpMainID INT
)
AS
BEGIN
	SELECT TOP 10 * FROM cpAttachment WHERE cpMainID=@cpMainID
END


GO
/****** Object:  StoredProcedure [dbo].[bpcpAttachmentInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--添加单位资料 Lucifer 2014-12-9
CREATE PROCEDURE [dbo].[bpcpAttachmentInsert]
(
	@cpMainID INT,
	@FileName VARCHAR(50),
	@AddMan SMALLINT
)
AS
BEGIN
	INSERT INTO cpAttachment(cpMainID,FileName,AddMan) VALUES(@cpMainID,@FileName,@AddMan)
END


GO
/****** Object:  StoredProcedure [dbo].[bpCpCoinByCaOrderInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--订单积分添加 Lucifer 2014-12-24
CREATE PROCEDURE [dbo].[bpCpCoinByCaOrderInsert]
(
	@OrderID INT,
	@cpMainID INT,
	@OrderType TINYINT
)
AS
SET NOCOUNT ON
BEGIN
	DECLARE @CoinRation NUMERIC(18, 2), @Paid NUMERIC(18, 2), @GivePoint INT
	IF @OrderType = 1
	BEGIN
		SELECT TOP 1 @CoinRation = a.CoinRation, @Paid = c.Paid, @GivePoint = b.GivePoint
		FROM dcVip a, dcVipdetail b, caOrder c
		WHERE c.dcFeeDetailID = b.ID AND b.dcVipID=a.ID AND c.ID = @OrderID
	END
	ELSE
	BEGIN
		SELECT TOP 1 @CoinRation = a.CoinRation, @Paid = c.Paid
		FROM dcFee a,dcFeedetail b,caOrder c
		WHERE c.dcFeeDetailID = b.id AND b.dcFeeID=a.ID AND c.ID = @OrderID
	END
	IF NOT EXISTS(SELECT 'X' FROM cpCoin WHERE caOrderID = @OrderID AND Coin > 0)
	BEGIN
		INSERT INTO cpCoin(cpMainID, caOrderID, Coin, AddDate)
		VALUES(@cpMainID, @OrderID, @CoinRation * @Paid, GETDATE())
	END

	IF @GivePoint > 0
	BEGIN
		INSERT INTO cpPoint (cpMainID, changeID, Point, relativeID, lastModifyDate)
		SELECT @cpMainID, 23, @GivePoint, @OrderID, GETDATE()

		UPDATE caOrder SET GivePoint = @GivePoint WHERE Id = @OrderId
	END
END


GO
/****** Object:  StoredProcedure [dbo].[bpCpCompanyEmailUpdateByVerify]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--企业邮箱审核
CREATE PROCEDURE [dbo].[bpCpCompanyEmailUpdateByVerify]
(
    @cpCompanyEmailID INT,
    @CheckResult INT,
    @CheckMan INT,
	@CheckMessage VARCHAR(100)
)
AS
BEGIN
    DECLARE @cpCertificationID INT
    SELECT TOP 1 @cpCertificationID = cpCertificationID 
    FROM cpCompanyEmail WITH(NOLOCK) 
    WHERE ID = @cpCompanyEmailID
    IF @cpCertificationID IS NULL
        RETURN

    UPDATE cpCompanyEmail 
    SET CheckResult = @CheckResult,CheckMan = @CheckMan,CheckDate = GETDATE(),CheckMessage = @CheckMessage
    WHERE ID = @cpCompanyEmailID
    
    IF @CheckResult = 1
    BEGIN
        UPDATE MainDB..cpCertification 
        SET CerStatus = 1
        WHERE ID = @cpCertificationID
    END
    ELSE
    BEGIN
        INSERT INTO SmsMessageLog (SendMan, caMainId, Mobile, Msg, MsgType, IsCat)
        SELECT TOP 1 @CheckMan, b.ID, a.Mobile, '您的企业邮箱认证未通过，请登录' + d.WebSiteName + '(www.' + d.ProvinceDomain + ')进行查看', 50, 0
        FROM cpCertification a WITH(NOLOCK)
        INNER JOIN caMain b WITH(NOLOCK) ON a.cpMainID = b.cpMainID
        INNER JOIN cpMain c WITH(NOLOCK) ON b.cpMainID = c.ID
        INNER JOIN dcProvince d WITH(NOLOCK) ON c.dcProvinceID = d.ID
        WHERE a.ID = @cpCertificationID AND b.AccountType = 1

		INSERT INTO rtxnotifylog
		SELECT ISNULL(ConsultantID,0),'邮箱审核不通过提醒',Name+'('+LTRIM(STR(ID))+')企业邮箱审核未通过！http://sysback.51rc.com/newoa/company/cp/cpMainInfo?id=' + LTRIM(STR(ID)) + '&code=' + LTRIM(STR(DATEPART(HOUR, RegDate) * 100 + DATEPART(MINUTE, RegDate))),1,0,0,null,getdate()
		FROM cpMain WITH(NOLOCK)
		WHERE ID = (SELECT CpMainID FROM MainDB..cpCertification WITH(NOLOCK) WHERE id = @cpCertificationID)
    END
END
GO
/****** Object:  StoredProcedure [dbo].[bpCpImageByCpIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Mice 123>
-- Create date: <2015-1-19>
-- Description:	<企业图片查询>
-- =============================================
CREATE PROCEDURE [dbo].[bpCpImageByCpIDSelect]
(
	@CpMainID VARCHAR(50),
	@ImgType INT --3企业环境照片
)	

AS
BEGIN
	SELECT TOP 20 a.*, b.Name AS cpName 
	FROM cpImage a, cpMain b
	WHERE a.cpMainID = b.id 
	AND a.cpMainID = @CpMainID
	AND a.ImgType = CONVERT(VARCHAR(2),@ImgType)
END


GO
/****** Object:  StoredProcedure [dbo].[bpcpImageByEnviUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[bpcpImageByEnviUpdate]
(
	@ID INT,
	@cpMainID INT,
	@HasPassed BIT,
	@CheckMan INT,
	@CheckMessage VARCHAR(500),
	@imgType varchar(50)
)
AS
SET NOCOUNT ON
BEGIN
	--插入审核延误记录表 
	INSERT INTO logdb..VerifyDelayLog(verifyType, relationId, submitDate, verifyDate, verifyMan)
	SELECT 6,@ID,(SELECT AddDate FROM cpImage  WHERE cpMainID=@cpMainID AND ID = @ID), GETDATE(), @CheckMan
	
	IF @HasPassed = 1 
	BEGIN
		UPDATE Maindb..cpImage
		SET HasPassed = @HasPassed,
			CheckMan = @CheckMan ,
			Description = @CheckMessage,
			CheckDate = GETDATE()
		WHERE cpMainID=@cpMainID  AND ID=@ID
	END
	ELSE
	BEGIN
		UPDATE Maindb..cpImage
		SET HasPassed = @HasPassed,
			CheckMan = @CheckMan ,
			CheckMessage = @CheckMessage,
			CheckDate = GETDATE()
		WHERE cpMainID=@cpMainID  AND ID=@ID
	END

	if @HasPassed = 1      ---审核通过
	BEGIN
		if @imgType='3'
			INSERT INTO cpPoint(cpMainID, ChangeID, Point, LastModifyDate) VALUES(@cpMainID, 25, 10, GETDATE())
		else if @imgType='4,5'
			INSERT INTO cpPoint(cpMainID, ChangeID, Point, LastModifyDate) VALUES(@cpMainID, 26, 100, GETDATE())
	END
END

GO
/****** Object:  StoredProcedure [dbo].[bpCpImageByFileNameUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Mice 123>
-- Create date: <2015-1-19>
-- Description:	<企业环境照片更新>
---增加审核记录,用于计算审核延误6
-- =============================================
CREATE PROCEDURE [dbo].[bpCpImageByFileNameUpdate]
(
	@ImgID VARCHAR(50),
	@FileName VARCHAR(100),
	@PhotoDesc NVARCHAR(100),
	@ManageruserID INT
)
AS
SET NOCOUNT ON
BEGIN
	UPDATE Maindb..cpImage
	SET ImgFile = @FileName, AddDate = getDate() , 
		HasPassed = 1, CheckMan = @ManageruserID, 
		CheckDate = GETDATE(), CheckMessage = NULL,
		Description = @PhotoDesc
	WHERE ID = @ImgID
	
	  --插入审核延误记录表 
	INSERT INTO logdb..VerifyDelayLog(verifyType, relationId, submitDate, verifyDate, verifyMan)
	SELECT 6,@ImgID,(SELECT AddDate FROM cpImage  WHERE   ID = @ImgID), GETDATE(), @ManageruserID
	
END 

GO
/****** Object:  StoredProcedure [dbo].[bpCpImageByHasVisualSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--###########################
--创建时间：2014.11.27
--创建人：Nick
--说明：获取后台审核形象图
--###########################
CREATE PROCEDURE [dbo].[bpCpImageByHasVisualSelect]
(
	@WHERE VARCHAR(2000),
	@TypeID INT --1等待审核、2最近审核通过 3 最近审核未通过
)
AS
BEGIN 
	DECLARE @SQL VARCHAR(MAX)
	IF @TypeID = 1
	BEGIN
		SET @SQL = '
			SELECT a.ID ImageID,a.AddDate,b.ID,b.Name companyname,b.RegDate 
			FROM cpImage a With(Nolock),cpMain b With(Nolock) 
			WHERE a.cpMainID=b.ID 
			AND a.HasPassed Is Null 
			AND a.AddDate<DateAdd(mi, -40, GetDate()) 
			AND a.ImgType=2 
			AND b.IsDelete=0 
			AND b.IsLimitLogin<>9 
			AND a.adddate < CONVERT(datetime, CONVERT(varchar(100), GETDATE(), 111)+'' 16:51'')
		'+@WHERE + ' Order By a.AddDate'
	END
	ELSE IF @TypeID = 2
	BEGIN
		SET @SQL = '
			SELECT a.ID imageid,a.CheckDate,b.id,b.Name companyname,a.ImgFile,b.RegDate,a.CheckMan 
			FROM cpImage a With(Nolock),cpMain b With(Nolock) 
			WHERE ImgType=2 
			AND a.cpMainID=b.ID 
			AND b.HasVisual=1 
			AND b.Isdelete<>1 
			AND HasPassed=1
		'+@WHERE + ' ORDER BY a.CheckDate DESC'
	END
	ELSE IF @TypeID = 3
	BEGIN
		SET @SQL = '
			SELECT TOP 100 a.ID ImageID,b.ID,b.Name,a.CheckDate,CheckMessage,ImgFile,CheckMan,b.RegDate 
			FROM cpImage a With(Nolock),cpMain b With(Nolock) 
			WHERE a.cpMainID=b.ID 
			AND b.HasVisual=0 
			AND a.ImgType=2 
			AND HasPassed=0 
			AND b.Isdelete<>1
		'+@WHERE + ' Order By a.CheckDate Desc'
	END
	EXEC(@SQL)
END
GO
/****** Object:  StoredProcedure [dbo].[bpCpImageByIDUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--Peter 2014-08-25 修改
--审核通过Logo和形象图  添加积分记录
CREATE PROCEDURE [dbo].[bpCpImageByIDUpdate]
(
	@ID INT,
	@cpMainID INT,
	@ImgType INT,
	@HasPassed BIT,
	@CheckMan INT,
	@CheckMessage VARCHAR(500)
)
AS
BEGIN TRY
	UPDATE cpImage 
	SET HasPassed = @HasPassed,
		CheckMan = @CheckMan ,
		CheckMessage = @CheckMessage,
		CheckDate = GETDATE()
	WHERE cpMainID=@cpMainID AND ImgType = @ImgType AND ID=@ID

	IF @ImgType = 1
	BEGIN
		UPDATE cpMain SET HasLogo = @HasPassed WHERE ID = @cpMainID

		IF @HasPassed = 1
			IF NOT EXISTS (SELECT 'x' FROM cpMain WHERE ID = @cpMainID AND HasLogo = 1) --之前没有审核通过的形象图
				IF NOT EXISTS(SELECT 'x' FROM cpPoint WHERE cpMainID = @cpMainID AND ChangeId = 7 AND Point = 1000)
					INSERT INTO cpPoint(cpMainID, ChangeID, Point, LastModifyDate)	--插入积分记录
					VALUES(@cpMainID, 7, CASE WHEN GETDATE() < '2017-4-26' THEN 1000 ELSE 10 END, GETDATE())
	END			
	ELSE IF @ImgType = 2
	BEGIN
		IF @HasPassed = 1
			IF NOT EXISTS (SELECT 'x' FROM cpMain WHERE ID = @cpMainID AND HasVisual = 1) --之前没有审核通过的形象图
				INSERT INTO cpPoint (cpMainID, ChangeID, Point, LastModifyDate)		--插入积分记录
				VALUES(@cpMainID, 9, 10, GETDATE())

		UPDATE cpMain SET HasVisual = @HasPassed WHERE ID = @cpMainID
		IF EXISTS(SELECT 'X' FROM cpImage WHERE cpMainID=@cpMainID AND HasPassed=1 AND ImgType=@ImgType)
			UPDATE cpMain SET HasVisual = 1 WHERE ID = @cpMainID
	END

	--短信发送
	IF @ImgType = 1
		INSERT SmsMessageLog(SendMan, ManagerUSerId, paMainId, caMainId, Mobile, MsgType, IsCat, Msg)
		SELECT  @CheckMan, NULL, NULL, a.ID, a.Mobile,
			CASE @HasPassed 
				WHEN 1 THEN 2
				ELSE 3 
			END
			,0,
			CASE @HasPassed 
				WHEN 1 THEN
					IsNULL(a.Name,'') + '您好，您在' + c.subsitename + c.EmailSite + '上传的logo已通过审核，祝您招聘顺利'
				ELSE
					IsNULL(a.Name,'') + '您好，您在' + c.subsitename + c.EmailSite + '上传的logo未通过审核，请您及时登录网站修改，以免耽误使用'
			END	
		FROM caMain a WITH(NOLOCK), cpMain b WITH(NOLOCK), dcSubSite c WITH(NOLOCK)
		WHERE a.cpMainID = b.ID
		AND b.dcSubSiteID = c.ID
		AND a.AccountType = 1
		AND a.Mobile > ''
		AND b.ID = @cpMainID
		AND a.IsReceiveSms = 1		
	ELSE
		INSERT SmsMessageLog(SendMan, ManagerUSerId, paMainId, caMainId, Mobile, MsgType, IsCat, Msg)
		SELECT  @CheckMan, NULL, NULL, a.ID, a.Mobile, 
			CASE @HasPassed 
				WHEN 1 THEN 4
				ELSE 5
			END
			 ,0,
			CASE @HasPassed 
				WHEN 1 THEN
					IsNULL(a.Name,'') + '您好，您在' + c.subsitename + c.EmailSite + '上传的形象图已通过审核，祝您招聘顺利'
				ELSE
					IsNULL(a.Name,'') + '您好，您在' + c.subsitename + c.EmailSite + '上传的形象图未通过审核，请您及时登录网站修改，以免耽误使用'
			END
		FROM caMain a WITH(NOLOCK), cpMain b WITH(NOLOCK), dcSubSite c WITH(NOLOCK)
		WHERE a.cpMainID = b.ID
		AND b.dcSubSiteID = c.ID
		AND a.AccountType = 1
		AND a.Mobile > ''
		AND b.ID = @cpMainID
		AND a.IsReceiveSms = 1			
END TRY
BEGIN CATCH
	GOTO ERR
END CATCH
RETURN 1
ERR:
BEGIN
	RETURN 0
END





GO
/****** Object:  StoredProcedure [dbo].[bpCpImageByImgIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Mice 123>
-- Create date: <2015-1-19>
-- Description:	<企业图片查询>
-- =============================================
CREATE PROCEDURE [dbo].[bpCpImageByImgIDSelect]
(
	@ImageID VARCHAR(50)
)	
AS
BEGIN
	SELECT TOP 1 *
	FROM cpImage a, cpMain b
	WHERE a.cpMainID = b.id 
	AND a.id = @ImageID
END


GO
/****** Object:  StoredProcedure [dbo].[bpCpImageByImgTypeInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [dbo].[bpCpImageByImgTypeInsert]
(
	@OperatorID INT,
	@cpMainID INT,
	@ImgType TINYINT,
	@ImgFile VARCHAR(50),
	@Description VARCHAR(100)
)
AS
BEGIN 
	DECLARE @MaxId AS INT, @Desc AS VARCHAR(200)
	DELETE FROM cpImage WHERE cpMainID=@cpMainID AND ImgType=@ImgType AND HasPassed=0
	INSERT INTO cpImage (cpMainID,ImgType,ImgFile,Description)
		VALUES(@cpMainID,@ImgType,@ImgFile,@Description)
	SET @MaxID = @@IDENTITY
	RETURN @MaxID
END

GO
/****** Object:  StoredProcedure [dbo].[bpcpImageByImgTypeSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--获取等待审核的图片
--nick 20141231
CREATE PROCEDURE [dbo].[bpcpImageByImgTypeSelect]
(
	@ImgType INT,
	@WHERE VARCHAR(1000)
)
AS
BEGIN TRY
	DECLARE @SQL AS VARCHAR(2000)
	SET @SQL = 'SELECT top 200 a.AddDate,b.ID,b.Name companyname,b.RegDate 
	FROM cpImage a With(Nolock),cpMain b With(Nolock) 
	WHERE a.cpMainID=b.ID And a.HasPassed Is Null 
	AND a.AddDate<DateAdd(mi, -40, GetDate()) 
	AND b.LastLoginDate > dateAdd(year,-1,getdate()) 
	AND a.ImgType='+CONVERT(VARCHAR(10),@ImgType)+'  
	AND b.IsDelete=0 And b.IsLimitLogin<>9 
	AND a.adddate<convert(datetime, CONVERT(varchar(100), GETDATE(), 111)+'' 16:51'')'+@WHERE
	EXEC(@SQL)
END TRY
BEGIN CATCH
	
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[bpcpImageByReportDaySELECT]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:        
-- Create date: <2015-1-28>
-- Description:    <环境照片审核日报>
-- =============================================
CREATE PROCEDURE [dbo].[bpcpImageByReportDaySELECT]
(
    @BeginDate VARCHAR(10),
    @EndDate VARCHAR(10),
    @VerifyMan INT,
    @ImgType VARCHAR(5)
)
AS
BEGIN
    SELECT @BeginDate = dbo.SafeSql(@BeginDate), @EndDate = dbo.SafeSql(@EndDate)
    DECLARE @SQL AS VARCHAR(5000)
    SET @SQL =' 
        SELECT CheckMan, CONVERT(VARCHAR(8),a.CheckDate,112) datenow ,
            (SELECT [Name] FROM Maindb..Manageruser b WHERE b.id = a.CheckMan ) AS CheckManName ,
            COUNT(0) AS TotalNum,
            SUM( CASE HasPassed WHEN 1 THEN 1 ELSE 0 END ) AS PassNum,
            SUM( CASE HasPassed WHEN 0 THEN 1 ELSE 0 END ) AS NotPassNum
        FROM Maindb..cpImage a
        WHERE a.ImgType IN (' + @ImgType + ') AND a.CheckDate >= ''' + @beginDate + '''
        AND a.CheckDate <= ''' + @EndDate + ''''
    IF @VerifyMan <> ''
    BEGIN
        SET @SQL = @SQL + ' AND a.CheckMan = ' + LTRIM(STR(@VerifyMan))
    END
    SET @SQL = @SQL + ' GROUP BY a.CheckMan, CONVERT(VARCHAR(8),a.CheckDate,112) '
    EXEC(@SQL)
END

GO
/****** Object:  StoredProcedure [dbo].[bpcpImageByReportMonthSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:        
-- Create date: <2015-1-28>
-- Description:    <环境照片审核月报>
-- =============================================
CREATE PROCEDURE [dbo].[bpcpImageByReportMonthSelect]
(
    @BeginDate VARCHAR(10),
    @EndDate VARCHAR(10),
    @VerifyMan INT,
    @ImgType VARCHAR(5)
)
AS
BEGIN
    SELECT @BeginDate = dbo.SafeSql(@BeginDate), @EndDate = dbo.SafeSql(@EndDate)
    DECLARE @SQL AS VARCHAR(5000)
    SET @SQL =' 
        SELECT CheckMan,
            (SELECT [Name] FROM Maindb..Manageruser b WHERE b.id = a.CheckMan ) AS CheckManName ,
            COUNT(1) AS TotalNum,
            SUM( CASE HasPassed WHEN 1 THEN 1 ELSE 0 END ) AS PassNum,
            SUM( CASE HasPassed WHEN 0 THEN 1 ELSE 0 END ) AS NotPassNum
        FROM Maindb..cpImage a
        WHERE a.ImgType IN (' + @ImgType + ') AND a.CheckDate >= ''' + @beginDate + '''
            AND a.CheckDate <= ''' + @EndDate + ''''

    IF @VerifyMan <> ''
    BEGIN
        SET @SQL = @SQL + ' AND a.CheckMan = ' + LTRIM(STR(@VerifyMan))
    END
    SET @SQL = @SQL + ' GROUP BY a.CheckMan '
    EXEC(@SQL)
END
GO
/****** Object:  StoredProcedure [dbo].[bpCpImageByTypeSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[bpCpImageByTypeSelect]
(
	@WHERE VARCHAR(2000),
	@ImgType INT, --3企业环境照片
	@TypeID INT --1等待审核+视频描述、2最近审核通过+上传时间 3 最近审核未通过+上传时间
)
AS
set @where = replace(@where, ' And a.cpMainID = ''0''', '')
BEGIN 
	DECLARE @SQL VARCHAR(MAX), @ImgTypeString VARCHAR(50)
	SET @ImgTypeString = CONVERT(VARCHAR(2),@ImgType)
	IF @ImgType = 4
		SET @ImgTypeString = '4,5,6'
	SET @WHERE = dbo.SafeSql(@WHERE)
	IF @TypeID = 1
	BEGIN
		SET @SQL = '
			SELECT a.ID ImageID,a.Description,a.AddDate,b.ID,b.Name companyname,b.RegDate 
			FROM cpImage a With(Nolock),cpMain b With(Nolock) 
			WHERE a.cpMainID=b.ID 
			AND a.HasPassed Is Null 
			AND a.ImgType IN (' + @ImgTypeString + ')
			AND b.IsDelete=0 
			AND b.IsLimitLogin<>9 
		'+@WHERE + ' Order By a.AddDate'
		--AND a.adddate < CONVERT(datetime, CONVERT(varchar(100), GETDATE(), 111)+'' 16:51'')
	END
	ELSE IF @TypeID = 2
	BEGIN
		SET @SQL = '
			SELECT a.ID imageid,a.Description,a.AddDate,a.CheckDate,b.id,b.Name companyname,a.ImgFile,b.RegDate,a.CheckMan 
			FROM cpImage a With(Nolock),cpMain b With(Nolock) 
			WHERE a.cpMainID=b.ID 
			AND a.ImgType IN (' + @ImgTypeString + ')
			AND b.Isdelete<>1 
			AND HasPassed=1
		'+@WHERE + ' ORDER BY a.CheckDate DESC'
	END
	ELSE IF @TypeID = 3
	BEGIN
		SET @SQL = '
			SELECT TOP 100 a.ID imageid, b.ID,b.Name companyname,a.Description,a.AddDate,a.CheckDate,CheckMessage,ImgFile,CheckMan,b.RegDate 
			FROM cpImage a With(Nolock),cpMain b With(Nolock) 
			WHERE a.cpMainID=b.ID 
			AND a.ImgType IN (' + @ImgTypeString + ')
			AND HasPassed=0 
			AND b.Isdelete<>1
		'+@WHERE + ' Order By a.CheckDate Desc'
	END
	EXEC(@SQL)
END

GO
/****** Object:  StoredProcedure [dbo].[bpCpImageByVerifyInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[bpCpImageByVerifyInsert]
(
@OperatorID INT,
@cpMainID INT,
@ImgType TINYINT,
@ImgFile VARCHAR(50)
)
AS
SET NOCOUNT ON
BEGIN
DECLARE @MaxId AS INT, @Desc AS VARCHAR(200), @SubmitDate DATETIME, @OldImage VARCHAR(100), @IsFront BIT

--插入审核延误记录表
IF @ImgType = 1
BEGIN 
SELECT Top 1 @SubmitDate = AddDate, @OldImage = ImgFile
FROM cpImage 
WHERE cpMainID = @cpMainID AND ImgType = @ImgType 
ORDER by AddDate desc

DELETE FROM cpImage
WHERE cpMainID=@cpMainID AND ImgType=@ImgType

        IF @OldImage LIKE '%processed%'
            SET @IsFront = 1
        ELSE
            SET @IsFront = 0
END 
ELSE
BEGIN
SELECT @SubmitDate = GETDATE()
END 

IF @SubmitDate IS NULL
BEGIN
        SELECT @SubmitDate=GETDATE()
END

INSERT INTO cpImage (cpMainID, ImgType, ImgFile, HasPassed, CheckMan, CheckDate, AddDATE)
VALUES(@cpMainID, @ImgType, @ImgFile, 1, @OperatorID, GETDATE(), @SubmitDate)
SET @MaxID = @@IDENTITY 

--LOGO图
IF @ImgType = 1
BEGIN
IF DATEDIFF(dd, @SubmitDate, GETDATE()) = 0--不是当天的，就不算延迟
BEGIN
            INSERT INTO logdb..VerifyDelayLog(verifyType, relationId, submitDate, verifyDate, verifyMan)
            SELECT 5,@MaxID,@SubmitDate, GETDATE(), @OperatorID 
        END 

        IF @IsFront = 1
            IF NOT EXISTS (SELECT 'x' FROM cpMain WHERE ID = @cpMainID AND HasLogo = 1) --之前没有审核通过的形象图
                IF NOT EXISTS(SELECT 'x' FROM cpPoint WHERE cpMainID = @cpMainID AND ChangeId = 7)
                    INSERT INTO cpPoint(cpMainID, ChangeID, Point, LastModifyDate)    --插入积分记录
                    VALUES(@cpMainID, 7, CASE WHEN GETDATE() < '2017-4-26' THEN 1000 ELSE 50 END, GETDATE())

SET @Desc = '上传LOGO图，文件名:' + @ImgFile

UPDATE cpMain 
SET HasLOGO = 1, logofile=(SELECT TOP 1 'http://down.51rc.com/imagefolder/Logo/' + dbo.photoPath(cpMainID, 5) + '/' + ImgFile ImgFile
FROM cpImage WITH(NOLOCK)
WHERE ImgType = 1 
and cpmainid = @cpMainID
AND HasPassed = 1 
ORDER BY ID DESC)
WHERE ID = @cpMainID 

INSERT INTO bsCpStatus(cpMainID, StatusID) VALUES(@cpMainID, 2)
END

--形象图
IF @ImgType = 2 
BEGIN
SET @Desc = '上传形象图，文件名:' + @ImgFile
IF EXISTS(SELECT 'X' FROM cpMain WITH(NOLOCK) WHERE ID=@cpMainID AND HasVisual IS NULL)
UPDATE cpMain SET HasVisual=0 WHERE ID=@cpMainID 

INSERT INTO bsCpStatus(cpMainID,StatusID) VALUES(@cpMainID,3)
END

RETURN @MaxID
END

GO
/****** Object:  StoredProcedure [dbo].[bpCpImageByVerifySelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[bpCpImageByVerifySelect]
(
	@CheckMan SMALLINT,
	@Type TINYINT,	--10:待审核；1：已经审核；0：审核不通过；20-已经审核
	@ImgType TINYINT,	--1-logo图；2-形象图
	@SubNo TINYINT,	--默认值：0
	@MaxNo TINYINT	--默认值：1
)
AS
BEGIN
	IF @Type = 10
		BEGIN
			IF @MaxNo<1
				SET @MaxNo=1
			IF @SubNo<0 OR @SubNo >= @MaxNo
				SET @SubNo = 0
			SELECT TOP 1000
				a.ID,
                a.cpMainID,
                a.ImgFile,
                a.AddDate,
				b.Name
			FROM cpImage a WITH(NOLOCK),cpMain b WITH(NOLOCK)
			WHERE a.cpMainID=b.ID
			AND a.HasPassed IS NULL
			AND ImgType=@ImgType
			AND (a.cpMainID % @MaxNo) = @SubNo
			AND a.AddDate < DATEADD(HOUR,-1,GETDATE())
			ORDER BY a.AddDate
		END
	IF @Type = 1
		BEGIN
			SELECT TOP 500
				a.ID,
                a.cpMainID,
                a.ImgFile,
                a.AddDate,
				b.Name,
				a.CheckMan,
				a.CheckDate
			FROM cpImage a WITH(NOLOCK),cpMain b WITH(NOLOCK)
			WHERE a.cpMainID=b.ID
			AND a.HasPassed=1
			AND ImgType=@ImgType
			AND CheckMan=@CheckMan
			ORDER BY CheckDate DESC
		END	
	IF @Type = 0
		BEGIN
			SELECT TOP 500
				a.ID,
                a.cpMainID,
                a.ImgFile,
                a.AddDate,
				b.Name,
				a.CheckMan,
				a.CheckDate
			FROM cpImage a WITH(NOLOCK),cpMain b WITH(NOLOCK)
			WHERE a.cpMainID=b.ID
			AND a.HasPassed=0
			AND ImgType=@ImgType
			AND CheckMan=@CheckMan
			ORDER BY CheckDate DESC
		END
	IF @Type = 20
		BEGIN
			SELECT TOP 500
				a.ID,
                a.cpMainID,
                a.ImgFile,
                a.AddDate,
				b.Name,
				a.HasPassed,
				a.CheckMan,
				a.CheckDate
			FROM cpImage a WITH(NOLOCK),cpMain b WITH(NOLOCK)
			WHERE a.cpMainID=b.ID
			AND a.HasPassed IS NOT NULL
			AND ImgType=@ImgType
			AND CheckMan=@CheckMan
			ORDER BY CheckDate DESC
		END	
END














GO
/****** Object:  StoredProcedure [dbo].[bpCpImageInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[bpCpImageInsert]
(
	@OperatorID INT,
	@cpMainID INT,
	@ImgType TINYINT,
	@ImgFile VARCHAR(50)
)
AS
SET NOCOUNT ON
BEGIN TRAN
	DECLARE @MaxId AS INT, @Desc AS VARCHAR(200)
	BEGIN TRY
		DELETE FROM cpImage WHERE cpMainID=@cpMainID AND ImgType=@ImgType AND HasPassed=0
		INSERT INTO cpImage (cpMainID,ImgType,ImgFile) VALUES(@cpMainID,@ImgType,@ImgFile)
		SET @MaxID = @@IDENTITY
		--LOGO图
		IF @ImgType = 1
			BEGIN
				SET @Desc = '上传LOGO图，文件名:' + @ImgFile
				UPDATE cpMain SET HasLogo = 0 WHERE ID = @cpMainID
				IF @OperatorID > 0
					EXEC ccCaOperationLogInsert @OperatorID, 20, @Desc

				INSERT INTO bsCpStatus(cpMainID, StatusID) VALUES(@cpMainID, 2)
			END
		--形象图
		IF @ImgType = 2	
			BEGIN
				SET @Desc = '上传形象图，文件名:' + @ImgFile
				IF EXISTS(SELECT 'X' FROM cpMain WITH(NOLOCK) WHERE ID=@cpMainID AND HasVisual IS NULL)
					UPDATE cpMain SET HasVisual=0 WHERE ID=@cpMainID

				IF @OperatorID > 0
					EXEC ccCaOperationLogInsert @OperatorID, 22, @Desc

				INSERT INTO bsCpStatus(cpMainID,StatusID) VALUES(@cpMainID,3)
			END
	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH
COMMIT TRAN
RETURN @MaxID
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END







GO
/****** Object:  StoredProcedure [dbo].[bpCpImageInsert2]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [dbo].[bpCpImageInsert2]
(
	@OperatorID INT,
	@cpMainID INT,
	@ImgType TINYINT,
	@ImgFile VARCHAR(50)
)
AS
SET NOCOUNT ON
BEGIN
	DECLARE @MaxId AS INT, @Desc AS VARCHAR(200)

	--插入审核延误记录表
	IF @ImgType = 1
	BEGIN
		INSERT INTO logdb..VerifyDelayLog(verifyType, relationId, submitDate, verifyDate, verifyMan)
		SELECT 5,(SELECT Top 1 Id FROM cpImage  WHERE cpMainID=@cpMainID AND ImgType = @ImgType ORDER by AddDate desc),(SELECT Top 1 AddDate FROM cpImage  WHERE cpMainID=@cpMainID AND ImgType = @ImgType ORDER by AddDate desc), GETDATE(), @OperatorID
		
		DELETE FROM cpImage WHERE cpMainID=@cpMainID AND ImgType=@ImgType
	END 
	
	DELETE FROM cpImage WHERE cpMainID=@cpMainID AND ImgType=@ImgType AND HasPassed=0
	
	INSERT INTO cpImage (cpMainID,ImgType,ImgFile,HasPassed,CheckMan,CheckDate)
	VALUES(@cpMainID,@ImgType,@ImgFile,1,@OperatorID,GETDATE())
	SET @MaxID = @@IDENTITY
		
	--LOGO图
	IF @ImgType = 1
	BEGIN
		SET @Desc = '上传LOGO图，文件名:' + @ImgFile
		UPDATE cpMain SET HasLOGO=1 WHERE ID=@cpMainID 
		
		INSERT INTO bsCpStatus(cpMainID, StatusID) VALUES(@cpMainID, 2)
	END

	--形象图
	IF @ImgType = 2	
	BEGIN
		SET @Desc = '上传形象图，文件名:' + @ImgFile
		IF EXISTS(SELECT 'X' FROM cpMain WITH(NOLOCK) WHERE ID=@cpMainID AND HasVisual IS NULL)
			UPDATE cpMain SET HasVisual=0 WHERE ID=@cpMainID 
		 
		INSERT INTO bsCpStatus(cpMainID,StatusID) VALUES(@cpMainID,3)
	END

	RETURN @MaxID
END
 
GO
/****** Object:  StoredProcedure [dbo].[bpCpImageUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


-----------------
--创建日期：2010-9-14
--创建人：lambo
--功能说明：修改cpImage中的logo或形象图的审核信息，同时将cpMain里的logo或形象图的信息也修改
--用于后台logo和形象图审核页面
--修改日期：2014-08-26
--修改人：Peter
--功能说明：添加积分记录
--增加审核记录,用于计算审核延误5
--logo减分改为有过加分记录的，才执行减分
---------------------------
CREATE PROCEDURE [dbo].[bpCpImageUpdate]
(
    @cpMainID INT,
    @ImgType INT,
    @HasPassed BIT,
    @CheckMan INT,
    @CheckMessage VARCHAR(500)
)
AS
SET NOCOUNT ON
BEGIN
    UPDATE cpImage
    SET HasPassed = @HasPassed,
        CheckMan = @CheckMan ,
        CheckMessage = @CheckMessage,
        CheckDate = GETDATE()
    WHERE cpMainID=@cpMainID AND ImgType = @ImgType

    IF @ImgType=1
    BEGIN
        DECLARE @HasOld AS BIT
        IF EXISTS (SELECT 'x' FROM cpMain WHERE ID = @cpMainID AND HasLogo = 1) --之前没有审核通过的形象图
            SET @HasOld = 1
        ELSE
            IF EXISTS(SELECT 'x' FROM cpPoint WHERE cpMainID = @cpMainID AND ChangeId = 7 )
                SET @HasOld = 1                    
            ELSE
                SET @HasOld = 0

        UPDATE cpMain SET HasLogo = @HasPassed WHERE ID = @cpMainID

--插入审核延误记录表
    
        INSERT INTO logdb..VerifyDelayLog(verifyType, relationId, submitDate, verifyDate, verifyMan)
        SELECT 5,(SELECT Id FROM cpImage WHERE cpMainID=@cpMainID AND ImgType = @ImgType),(SELECT AddDate FROM cpImage WHERE cpMainID=@cpMainID AND ImgType = @ImgType), GETDATE(), @CheckMan

        IF @HasPassed = 1
        BEGIN
             IF @HasOld = 0 --之前没有审核通过的形象图
                INSERT INTO cpPoint (cpMainID, ChangeID, Point, LastModifyDate)    --插入积分记录
                VALUES(@cpMainID, 7, CASE WHEN GETDATE() < '2017-4-26' THEN 1000 ELSE 50 END, GETDATE())
            
            UPDATE cpMain SET logofile=(SELECT TOP 1 'http://down.51rc.com/imagefolder/Logo/' + dbo.photoPath(cpMainID, 5) + '/' + ImgFile ImgFile
                FROM cpImage WITH(NOLOCK)
                WHERE ImgType = 1 
                AND cpmainid = @cpMainID 
                ORDER BY ID DESC)
            WHERE id = @cpMainID
        END
	ELSE
        BEGIN
		 IF EXISTS(SELECT 'x' FROM cpPoint WHERE cpMainID = @cpMainID AND ChangeId = 7)--有过加分记录
		 BEGIN
			INSERT INTO cpPoint (cpMainID, ChangeID, Point, LastModifyDate)    --插入积分记录
                	VALUES(@cpMainID, 8, CASE WHEN GETDATE() < '2017-4-26' THEN -1000 ELSE -50 END, GETDATE())
		 END
	END
    END
    ELSE IF @ImgType=2
    BEGIN
        UPDATE cpMain SET HasVisual = @HasPassed WHERE ID = @cpMainID

        IF @HasPassed = 1
            IF NOT EXISTS (SELECT 'x' FROM cpMain WHERE ID = @cpMainID AND HasVisual = 1) --之前没有审核通过的形象图
                INSERT INTO cpPoint (cpMainID,ChangeID,Point,LastModifyDate)        --插入积分记录
                VALUES(@cpMainID,9,10,GETDATE())
    END

    --短信发送
    IF @ImgType = 1
        INSERT SmsMessageLog(SendMan, ManagerUSerId, paMainId, caMainId, Mobile, MsgType, IsCat, Msg)
        SELECT @CheckMan, NULL, NULL, a.ID, a.Mobile,
            CASE @HasPassed 
                WHEN 1 THEN 2
                ELSE 3 
            END
            ,0,
            CASE @HasPassed 
                WHEN 1 THEN
                    IsNULL(a.Name,'') + '您好，您在' + c.subsitename + c.EmailSite + '上传的logo已通过审核，祝您招聘顺利'
                ELSE
                    IsNULL(a.Name,'') + '您好，您在' + c.subsitename + c.EmailSite + '上传的logo未通过审核，请您及时登录网站修改，以免耽误使用'
            END    
        FROM caMain a WITH(NOLOCK), cpMain b WITH(NOLOCK), dcSubSite c WITH(NOLOCK)
        WHERE a.cpMainID = b.ID
        AND b.dcSubSiteID = c.ID
        AND a.AccountType = 1
        AND a.Mobile > ''
        AND b.ID = @cpMainID
        AND a.IsReceiveSms = 1        
    ELSE
        INSERT SmsMessageLog(SendMan, ManagerUSerId, paMainId, caMainId, Mobile, MsgType, IsCat, Msg)
        SELECT @CheckMan, NULL, NULL, a.ID, a.Mobile, 
            CASE @HasPassed 
                WHEN 1 THEN 4
                ELSE 5
            END ,0,
            CASE @HasPassed 
                WHEN 1 THEN
                    IsNULL(a.Name,'') + '您好，您在' + c.subsitename + c.EmailSite + '上传的形象图已通过审核，祝您招聘顺利'
                ELSE
                    IsNULL(a.Name,'') + '您好，您在' + c.subsitename + c.EmailSite + '上传的形象图未通过审核，请您及时登录网站修改，以免耽误使用'
            END
 FROM caMain a WITH(NOLOCK), cpMain b WITH(NOLOCK), dcSubSite c WITH(NOLOCK)
        WHERE a.cpMainID = b.ID
        AND b.dcSubSiteID = c.ID
        AND a.AccountType = 1
        AND a.Mobile > ''
        AND b.ID = @cpMainID
        AND a.IsReceiveSms = 1            
END
RETURN 1
ERR:
BEGIN
    RETURN 0
END
 

GO
/****** Object:  StoredProcedure [dbo].[bpCpLicenceByCheckDateSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--创建人 Andy
--时间 2014-12-31
--按照条件查询企业CpLicence的count，用于统计销售额
CREATE PROCEDURE [dbo].[bpCpLicenceByCheckDateSelect]
(		
	@StartDate DATETIME,
	@EndDate DATETIME,
	@Province INT,
	@Dept INT	
)
AS
BEGIN		
	DECLARE @SQL VARCHAR(1000)
	SET @SQL = '
		SELECT COUNT(1) cnt 
		FROM CpLicence a WITH(NOLOCK),CpMain b WITH(NOLOCK)
		WHERE b.ID=a.cpMainID 
		AND a.CheckDate>'''+ CONVERT(VARCHAR(20),@StartDate, 20)+''' AND a.Checkdate<'''+ CONVERT(VARCHAR(20),@EndDate, 20) +''' AND haslicence=1 '
	
	IF @Province = 2 --北方，不包括山东
		SET @SQL = @SQL + ' AND b.dcProvinceID IN (10,11,12,13,14,20,21,22,70,80,83,84,81,82) '
	ELSE IF @Province = 3 --南方不包括山东
		SET @SQL = @SQL + ' AND b.dcProvinceID IN (30,31,33,34,35,36,40,41,42,60,61,62,63,71,72,64) '
	ELSE IF @Province <> 0
		SET @SQL = @SQL + ' AND b.dcProvinceID = ' + LTRIM(STR(@Province))
	
	IF @Dept > 0
		SET @SQL = @SQL + ' AND b.Consultantid IN (SELECT ID FROM ManagerUser WITH(NOLOCK) WHERE Deptid=' + LTRIM(STR(@Dept)) + ' )' 

	--PRINT(@SQL)
	EXEC (@SQL)
END

GO
/****** Object:  StoredProcedure [dbo].[bpCpLicenceByCpMainIDDelete]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--###########################
--创建时间：2014.12.15
--创建人：Nick
--说明：删除cplicence
--###########################
CREATE PROCEDURE [dbo].[bpCpLicenceByCpMainIDDelete]
(
@cpMainID INT
)
AS
BEGIN
    DECLARE @cpCertificationID AS INT
    
    SELECT @cpCertificationID = cpCertificationID 
    FROM cpLicence WITH(NOLOCK)
    WHERE cpMainID = @cpMainID
    
    IF @cpCertificationID > 0
    BEGIN
        DECLARE @CheckMan INT,@CheckMessage NVARCHAR(500)
        
        SELECT TOP 1 @CheckMan = CheckMan,@CheckMessage = Description
        FROM cpLicenceLog WITH(NOLOCK)
        WHERE cpMainID = @cpMainID
        ORDER BY ID DESC
        
        UPDATE cpLicence SET HasPassed = 0,CheckMan = @CheckMan,CheckMessage = @CheckMessage,CheckDate = GETDATE()
        WHERE cpCertificationID = @cpCertificationID
    END
ELSE
    BEGIN
        DELETE FROM cpLicence WHERE cpMainID = @cpMainID
    END
END
GO
/****** Object:  StoredProcedure [dbo].[bpCpLicenceByCpMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[bpCpLicenceByCpMainIDSelect]
(
	@cpMainID INT
)
AS
BEGIN 
	SELECT TOP 1 * 
	FROM cpLicence With(Nolock) 
	WHERE cpMainID = @cpMainID ORDER BY ID DESC
END

GO
/****** Object:  StoredProcedure [dbo].[bpCpLicenceByCpMainIDSelectbak]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--###########################
--创建时间：2014.12.10
--创建人：Nick
--说明：根据cpMainID获取cpLicence
--###########################
create PROCEDURE [dbo].[bpCpLicenceByCpMainIDSelectbak]
(
	@cpMainID INT
)
AS
BEGIN 
	SELECT CheckDate,ImgFile,IP,FileSource,CheckMan,AddDate 
	FROM cpLicence With(Nolock) 
	WHERE cpMainID = @cpMainID
END

GO
/****** Object:  StoredProcedure [dbo].[bpCpLicenceByNotPassedSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.12.16
--创建人：John
--说明：根据条件查询最近未审核通过营业执照列表
--#####################################################
CREATE PROCEDURE [dbo].[bpCpLicenceByNotPassedSelect]
(
	@WHERE VARCHAR(1000),
	@Num INT
)
AS
BEGIN
	DECLARE @SQL VARCHAR(2000)
	SET @SQL = 'SELECT '
	IF @Num > 0
	BEGIN
		SET @SQL = @SQL + 'TOP '+CONVERT(VARCHAR(20),@Num)+' '
	END
	SET @SQL = @SQL + 'b.CheckMan,a.regdate,a.dcprovinceid,a.consultantid,a.id,a.Name,b.description,a.description description2'
		+',b.adddate,b.OldFileName,b.FileSource FROM cpMain a WITH(NOLOCK),cpLicenceLog b WITH(NOLOCK) WHERE b.cpMainID = a.id'
	IF LEN(@WHERE)>0
		SET @SQL = @SQL + @WHERE
	SET @SQL = @SQL + ' ORDER BY b.AddDate DESC'
	EXEC(@SQL)
END


GO
/****** Object:  StoredProcedure [dbo].[bpCpLicenceByRecentlySelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.12.16
--创建人：John
--说明：根据条件查询最近审核通过营业执照列表
--#####################################################
CREATE PROCEDURE [dbo].[bpCpLicenceByRecentlySelect]
(
	@WHERE VARCHAR(1000)
)
AS
BEGIN
	DECLARE @SQL VARCHAR(2000)
	SET @SQL = '
		SELECT CheckDate,dcProvinceID,a.Name,a.ID,HasLicence,b.ImgFile,a.ConsultantID,a.RegDate,CheckMan,FileSource
		FROM cpMain a WITH(NOLOCK),cpLicence b WITH(NOLOCK)
		WHERE a.ID = b.cpMainID AND HasLicence = 1'
	IF LEN(@WHERE)>0
		SET @SQL = @SQL + @WHERE
	SET @SQL = @SQL + ' ORDER BY b.CheckDate DESC'
	EXEC(@SQL)
END


GO
/****** Object:  StoredProcedure [dbo].[bpCpLicenceByVerifySelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[bpCpLicenceByVerifySelect]
(
	@CheckMan SMALLINT,
	@Type TINYINT,	--10:待审核；1：已经审核；0：审核不通过；20-已经审核
	@SubNo TINYINT,	--默认值：0
	@MaxNo TINYINT	--默认值：1
)
AS
BEGIN
	IF @Type = 10
		BEGIN
			IF @MaxNo<1
				SET @MaxNo=1
			IF @SubNo<0 OR @SubNo >= @MaxNo
				SET @SubNo = 0
			SELECT TOP 1000
				a.ID,
                a.cpMainID,
                a.ImgFile,
                a.AddDate,
				b.Name
			FROM cpLicence a WITH(NOLOCK),cpMain b WITH(NOLOCK)
			WHERE a.cpMainID=b.ID
			AND a.HasPassed IS NULL
			AND (a.cpMainID % @MaxNo) = @SubNo
			AND a.AddDate < DATEADD(HOUR,-1,GETDATE())
			ORDER BY a.AddDate
		END
	IF @Type = 1
		BEGIN
			SELECT TOP 500
				a.ID,
                a.cpMainID,
                a.ImgFile,
                a.AddDate,
				b.Name,
				a.CheckMan,
				a.CheckDate
			FROM cpLicence a WITH(NOLOCK),cpMain b WITH(NOLOCK)
			WHERE a.cpMainID=b.ID
			AND a.HasPassed=1
			AND CheckMan=@CheckMan
			ORDER BY CheckDate DESC
		END	
	IF @Type = 0
		BEGIN
			SELECT TOP 500
				a.ID,
                a.cpMainID,
                a.ImgFile,
                a.AddDate,
				b.Name,
				a.CheckMan,
				a.CheckDate
			FROM cpLicence a WITH(NOLOCK),cpMain b WITH(NOLOCK)
			WHERE a.cpMainID=b.ID
			AND a.HasPassed=0
			AND CheckMan=@CheckMan
			ORDER BY CheckDate DESC
		END
	IF @Type = 20
		BEGIN
			SELECT TOP 500
				a.ID,
                a.cpMainID,
                a.ImgFile,
                a.AddDate,
				b.Name,
				a.HasPassed,
				a.CheckMan,
				a.CheckDate
			FROM cpLicence a WITH(NOLOCK),cpMain b WITH(NOLOCK)
			WHERE a.cpMainID=b.ID
			AND a.HasPassed IS NOT NULL
			AND CheckMan=@CheckMan
			ORDER BY CheckDate DESC
		END	
END














GO
/****** Object:  StoredProcedure [dbo].[bpCpLicenceChangeLogInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--###########################
--创建时间：2014.12.15
--创建人：Nick
--说明：插入cpLicenceChangeLog
--###########################
CREATE PROCEDURE [dbo].[bpCpLicenceChangeLogInsert]
(
	@cpMainID INT,
	@CompanyNameOld NVARCHAR(50),
	@CompanyNameNew NVARCHAR(50),
	@FilenameOld VARCHAR(100),
	@FilenameNew VARCHAR(100),
	@ManagerUserID INT
)
AS
BEGIN 
	INSERT INTO cpLicenceChangeLog(cpMainID,NameOld,NameNew,FilenameOld,FilenameNew,ManagerUserID) 
	VALUES(@cpMainID,@CompanyNameOld,@CompanyNameNew,@FilenameOld,@FilenameNew,@ManagerUserID)
END


GO
/****** Object:  StoredProcedure [dbo].[bpcpLicenceChangeLogSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.12.9
--创建人：Nick
--说明：获取单位更名日志
--#####################################################
CREATE PROCEDURE [dbo].[bpcpLicenceChangeLogSelect]
(
	@CpmainID INT
)
AS
BEGIN 
	DECLARE @WHERE VARCHAR(MAX)
	DECLARE @SQL VARCHAR(MAX)
	IF @CpmainID<>0
	BEGIN
		SET @WHERE = ' And cpMainID= '+CONVERT(VARCHAR(20),@CpmainID)
	END
	ELSE
	BEGIN
		SET @WHERE = ' '
	END
	SET @SQL = '
		SELECT TOP 200 b.id,b.cpMainID,b.NameOld,b.NameNew,b.FileNameOld,b.FileNameNew,b.ManageruserID,b.adddate,
		a.regdate from cpMain a with(nolock),cpLicenceChangeLog b WITH(NOLOCK) 
		WHERE b.cpMainID=a.id '+@WHERE +' ORDER BY b.adddate DESC'
	EXEC(@SQL)
End


GO
/****** Object:  StoredProcedure [dbo].[bpCpLicenceLogByCpMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--###########################
--创建时间：2014.12.10
--创建人：Nick
--说明：根据cpMainID获取cplicencelog
--###########################
CREATE PROCEDURE [dbo].[bpCpLicenceLogByCpMainIDSelect]
(
	@cpMainID INT
)
AS
BEGIN 
	SELECT * FROM cplicencelog 
	WHERE cpMainid = @cpMainID 
	ORDER BY AddDate DESC
END


GO
/****** Object:  StoredProcedure [dbo].[bpCpLicenceLogInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--###########################
--创建时间：2014.12.15
--创建人：Nick
--说明：插入 cpLicenceLog
--###########################
CREATE PROCEDURE [dbo].[bpCpLicenceLogInsert]
(
	@cpMainID INT,
	@Des NVARCHAR(200),
	@CheckMan INT,
	@OldFileName VARCHAR(100),
	@FileSource VARCHAR(100)
)
AS
BEGIN 
	INSERT INTO cpLicenceLog(cpMainID,Description,CheckMan,OldFileName,FileSource) 
	VALUES (@cpMainID,@Des,@CheckMan,@OldFileName,@FileSource)
END


GO
/****** Object:  StoredProcedure [dbo].[bpCpLicenceSave]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--###########################
--创建时间：2014.12.10
--创建人：Nick
--说明：根据cpMainid修改执照
---增加审核记录,用于计算审核延误8
--###########################
CREATE PROCEDURE [dbo].[bpCpLicenceSave]
(
	@CheckMan INT,
	@ImgFile VARCHAR(100),
	@FileSource VARCHAR(200),
	@cpMainID INT,
	@TypeID INT --1 修改执照 2插入执照
)
AS
SET NOCOUNT ON
BEGIN 
	IF @TypeID = 1
	BEGIN
		UPDATE cpLicence SET CheckMan=@CheckMan,CheckDate=GetDate(),
		HasPassed=1,ImgFile=@ImgFile,FileSource=@FileSource 
		WHERE cpMainID = @cpMainID

        DECLARE @cpCertificationID AS INT
        
        SELECT @cpCertificationID = cpCertificationID 
        FROM cpLicence a WITH(NOLOCK), cpCertification b WITH(NOLOCK)
        WHERE a.cpCertificationID = b.ID AND b.cpMainID = @cpMainID AND CerStatus IS NULL
        
        IF @cpCertificationID > 0 
        BEGIN
            BEGIN TRY
                UPDATE MainDB..cpCertification SET CerStatus = 1
                WHERE ID = @cpCertificationID
            END TRY
            BEGIN CATCH
            END CATCH
        END 
        
		--插入审核延误记录表
		IF @FileSource = '1'--只记录用户自己上传的
		BEGIN
			INSERT INTO logdb..VerifyDelayLog(verifyType, relationId, submitDate, verifyDate, verifyMan)
			SELECT 8,(SELECT top 1 id FROM cpLicence WHERE cpMainID = @cpMainID), (SELECT top 1 AddDate FROM cpLicence WHERE cpMainID = @cpMainID), GETDATE(), @CheckMan
		END
	END
	ELSE
	BEGIN
		INSERT INTO cpLicence(cpMainID,ImgFile,CheckMan,CheckDate,HasPassed,FileSource) 
		VALUES(@cpMainID,@ImgFile,@CheckMan,GETDATE(),1,@FileSource)
	END
END
GO
/****** Object:  StoredProcedure [dbo].[bpCpLicenceVerifyUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[bpCpLicenceVerifyUpdate]
(
	@Name VARCHAR(100),
	@Description VARCHAR(MAX),
	@RegCapital INT,
    @ID INT
)
AS
SET NOCOUNT OFF
BEGIN
	UPDATE cpMain SET
		[Description] = @Description,
		RegCapital = @RegCapital
	WHERE ID = @ID

	UPDATE cpCertification SET
		CompanyName = @Name
	WHERE cpMainID = @ID AND CerStatus IS NULL
END
SET NOCOUNT ON
GO
/****** Object:  StoredProcedure [dbo].[bpCpMainByBaiDuFeeSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--bpCpMainByBaiDuFeeSelect 3, 1,2,'2014-01-02','2015-01-02'
--创建人 Andy
--时间 2015-01-23
--查询百度竞价缴费情况
CREATE PROCEDURE [dbo].[bpCpMainByBaiDuFeeSelect] 
(
	@Type INT,
	@MinID INT,
	@MaxID INT,
	@BeginDate VARCHAR(10),
	@EndDate VARCHAR(10)	
)
AS
BEGIN
	IF @Type = 1
		SELECT COUNT(*) FROM cpMain WHERE RegisterSourceId > 0 AND ID BETWEEN @MinID AND @MaxID
	ELSE IF @Type = 2
		SELECT COUNT(DISTINCT b.cpMainID) cnt, ISNULL(SUM(b.paid), 0) paid 
		FROM cpMain a, caOrder b 
		WHERE a.id = b.cpMainid 
		AND a.registersourceid > 0 
		AND a.id BETWEEN @MinID AND @MaxID
	ELSE IF @Type = 3
		SELECT COUNT(DISTINCT b.cpMainID) cnt, ISNULL(SUM(b.paid), 0) paid 
		FROM cpMain a, caOrder b 
		WHERE a.id = b.cpMainid 
		AND a.registersourceid > 0 
		AND b.OpenDate BETWEEN @BeginDate AND @EndDate	
END
GO
/****** Object:  StoredProcedure [dbo].[bpCpMainByBeVerifingSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--[bpCpMainByBeVerifingSelect] 0, 1, ''
-- =============================================
-- 创建日期:2010-4-16
-- 创建人：Sean
-- 功能：显示待审核的企业用户列表
-- 应用于cpMainVerifyListOnWait.asp页面
-- 修改时间：2010-9-14
-- 修改人：Lucifer
-- =============================================
CREATE PROCEDURE [dbo].[bpCpMainByBeVerifingSelect]
(
	@SubNo TINYINT, 	--默认值：0
	@MaxNo TINYINT, 	--默认值：1
	@WHERE VARCHAR(1000)
)	
AS
BEGIN TRY
	IF @MaxNo = 0
		BEGIN
			SET @MaxNo=1
			SET @SubNo=0
		END
	IF @SubNo >= @MaxNo
		SET @SubNo = 0
	CREATE TABLE #Verify(
		ID INT IDENTITY(1, 1) NOT NULL, 
		cpMainID INT NOT NULL, 
		cpName VARCHAR(100) COLLATE Chinese_PRC_CI_AS NOT NULL, 
		LastModifyDate SMALLDATETIME NULL, 
		VerifyResult TINYINT NULL, 
		bsCpVerifyID INT NULL, 
		RegDate SMALLDATETIME NOT NULL, 
		IsAgent BIT NOT NULL
		CONSTRAINT PK_#Verify1 PRIMARY KEY CLUSTERED 
		(
			ID ASC
		)WITH (PAD_INDEX  = OFF, IGNORE_DUP_KEY = OFF)
	)

	INSERT INTO #Verify(cpMainID, cpName, LastModifyDate, RegDate, IsAgent)
	SELECT a.cpMainID, b.Name, Max(a.AddDate), b.RegDate , b.IsAgent 
	FROM bsCpModify a WITH(NOLOCK), cpMain b WITH(NOLOCK)
	WHERE a.cpMainID=b.ID 
	AND a.VerifyInfo IS NULL 
	AND a.cpMainID NOT IN(SELECT cpMainID FROM bsJobProblem WITH(NOLOCK))
	AND a.cpMainID % @MaxNo = @SubNo
	AND b.IsLimitLogin < 9
        AND b.RealName<2--harry:强制实名的企业信息不审核2017-4-11
	GROUP BY a.cpMainID, b.Name, b.RegDate, b.IsAgent 

	UPDATE #Verify SET bsCpVerifyID = (
			SELECT TOP 1 ID FROM bsCpVerify WITH(NOLOCK)
			WHERE #Verify.cpMainID=bsCpVerify.cpMainID
			ORDER BY ID DESC), 
		VerifyResult = (
			SELECT TOP 1 VerifyResult FROM bsCpVerify WITH(NOLOCK)
			WHERE #Verify.cpMainID=bsCpVerify.cpMainID
			ORDER BY ID DESC)

	DECLARE @SQL AS VARCHAR(2000)
	SET @WHERE = dbo.SafeSql(@WHERE)
	SET @SQL = 'SELECT * FROM #Verify WITH(NOLOCK)
		WHERE DATEADD(MI, 40, LastModifyDate) < GETDATE() ' +
		@Where +
		' ORDER BY LastModifyDate ASC'
	EXEC(@SQL)
	DROP TABLE #Verify
END TRY
BEGIN CATCH
	DROP TABLE #Verify
END CATCH


 
GO
/****** Object:  StoredProcedure [dbo].[bpCpMainByBeVerifingSelect1]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[bpCpMainByBeVerifingSelect1]
(
	@VerifyMan SMALLINT,
	@SubNo TINYINT,	--默认值：0
	@MaxNo TINYINT,	--默认值：1
	@WHERE VARCHAR(1000)
)	
AS
BEGIN TRY
	IF @MaxNo = 0
		BEGIN
			SET @MaxNo=1
			SET @SubNo=0
		END
	IF @SubNo >= @MaxNo
		SET @SubNo = 0
	
	CREATE TABLE #Verify(
		ID INT IDENTITY(1,1) NOT NULL,
		VerifyMan SMALLINT NOT NULL,
		cpMainID INT NOT NULL,
		cpName VARCHAR(100) COLLATE Chinese_PRC_CI_AS NOT NULL,
		LastModifyDate SMALLDATETIME NULL,
		VerifyResult TINYINT NULL,
		bsCpVerifyID INT NULL,
	 CONSTRAINT PK_#Verify1 PRIMARY KEY CLUSTERED 
	(
		ID ASC
	)WITH (PAD_INDEX  = OFF, IGNORE_DUP_KEY = OFF)
	)

	INSERT INTO #Verify(VerifyMan,cpMainID,cpName,VerifyResult)
		SELECT @VerifyMan,ID,Name,VerifyResult
		FROM cpMain a WITH(NOLOCK)
		WHERE ID % @MaxNo = @SubNo

	DECLARE @SQL AS VARCHAR(2000)
	SET @WHERE = dbo.SafeSql(@Where)
	SET @SQL = '	SELECT a.*'
	SET @SQL = @sql + ' 	FROM #Verify a WITH(NOLOCK),('
	SET @SQL = @sql + '		SELECT cpMainID,Max(LastModifyDate) Sumdate'
	SET @SQL = @sql + '		FROM #Verify WITH(NOLOCK)'
	SET @SQL = @sql + '		WHERE VerifyMan=' + CONVERT(VARCHAR(10),@VerifyMan)
	SET @SQL = @sql + '		GROUP BY cpMainID'
	SET @SQL = @sql + '	) b'
	SET @SQL = @sql + '	WHERE a.cpMainID=b.cpMainID'
	SET @SQL = @sql + '	AND a.VerifyMan=' + CONVERT(VARCHAR(10),@VerifyMan)
	SET @SQL = @sql + @Where
	SET @SQL = @sql + '	ORDER BY b.Sumdate DESC,cpMainID'
	EXEC(@SQL)
	DROP TABLE #Verify
END TRY
BEGIN CATCH
	DROP TABLE #Verify
END CATCH














GO
/****** Object:  StoredProcedure [dbo].[bpCpMainByColUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[bpCpMainByColUpdate]
(
	@ID INT,
	@ColName VARCHAR(100),
	@ColValue NVARCHAR(Max)
)
AS
BEGIN TRY
	DECLARE @SQL AS VARCHAR(MAX)
	SELECT @ColName = dbo.SafeSQL(@ColName), @ColValue = dbo.SafeSQL(@ColValue)
	SET @SQL = 'UPDATE cpMain SET  ' + REPLACE(@ColName, '''', '') + '= ''' + REPLACE(@ColValue, '''', '''''') +
		''' WHERE ID = ' + CONVERT(VARCHAR(10), @ID)
	EXEC(@SQL)
	RETURN 1
END TRY
BEGIN CATCH
	RETURN 0
END CATCH




GO
/****** Object:  StoredProcedure [dbo].[bpCpMainByConsultantIdSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----------------------
--核算顾问销售业绩
--添加人Harry 
--说明：后台核算顾问业绩
--添加时间：2014-12-22
-----------------------
CREATE PROCEDURE [dbo].[bpCpMainByConsultantIdSelect]
(
	@consultantId INT
)
AS
BEGIN
	DECLARE @t AS TABLE
	(
		CntAll INT,
		CntFactorWuXianZhi INT,
		CntFactorChuZhi INT,
		CntFactorVip INT,
		CntFactorNoContinue INT,
		CntFactorActiveOld INT,
		CntFactorActiveNew INT,
		CntFactorPassiveOld INT,
		CntFactorPassiveNew INT,
		CntFactorDeadOld INT,
		CntFactorDeadNew INT,
		CntFactorNew INT
	)

	INSERT INTO @t 
	VALUES(0,0,0,0,0,0,0,0,0,0,0,0)

	UPDATE @t
	SET	CntAll = (
		SELECT COUNT(1) cnt 
		FROM cpMain WITH(NOLOCK) 
		WHERE ConsultantID=@consultantId 
		)
/*
	UPDATE @t 
	SET	CntFactorWuXianZhi=(
		SELECT COUNT(1) cnt 
		FROM cpMain WITH(NOLOCK) 
		WHERE UnLimitedDate>GETDATE() 
		AND UnLimitedDate<GETDATE()+30 
		AND ConsultantID=@consultantId 
	)

	UPDATE @t
	SET CntFactorChuZhi=(
		SELECT COUNT(1) cnt 
		FROM cpMain WITH(NOLOCK) 
		WHERE (
			(Balance>0 AND Balance<=20 AND BalanceDate>GETDATE()) 
			OR (Balance>0 AND BalanceDate>GETDATE() AND BalanceDate<GETDATE()+30)
			) 
		AND ConsultantID=@consultantId 
	)
*/
	UPDATE @t
	SET CntFactorVip=(
		SELECT COUNT(1) cnt
		FROM cpMain WITH(NOLOCK) 
		WHERE ID IN (
			SELECT cpMainID 
			FROM caOrder WITH(NOLOCK) 
			WHERE OrderType = 8 
			AND BeginDate<GETDATE() 
			AND EndDate<GETDATE()+30 
			AND EndDate>GETDATE() 
			AND paid>0
		) 
		AND ConsultantID=@consultantId
	)
	
	UPDATE @t 
	SET CntFactorNoContinue=(
		SELECT COUNT(1) cnt
		FROM cpMain WITH(NOLOCK) 
		WHERE MemberType=2 
		AND (
			SELECT COUNT(1) 
			FROM caOrder WITH(NOLOCK) 
			WHERE Paid>0 
			AND EndDate>GETDATE()-28 
			AND OrderType=8
			AND cpMainID=cpMain.ID
			)>0 
		AND ConsultantID=@consultantId
	)

	UPDATE @t 
	SET CntFactorActiveOld=(
		SELECT COUNT(1) cnt
		FROM cpMain WITH(NOLOCK) 
		WHERE ConsultantDate<GETDATE()-28 
		AND MemberType=2 
		AND (
			SELECT COUNT(1) 
			FROM caLoginLog with(nolock),caMain with(nolock) 
			WHERE caLoginLog.caMainID=caMain.ID 
			AND caMain.cpMainID=cpMain.id 
			AND caLoginLog.AddDate>GETDATE()-14
			)>0 
		AND (
			SELECT COUNT(1) 
			FROM caOrder WITH(NOLOCK) 
			WHERE Paid>0 AND OpenDate IS NOT NULL AND OrderType=8 AND cpMainID=cpMain.ID
			)>0 
		AND ConsultantID=@consultantId
	)

	UPDATE @t 
	SET CntFactorActiveNew=(
		SELECT COUNT(1) cnt
		FROM cpMain WITH(NOLOCK) 
		WHERE ConsultantDate<GETDATE()-28 
		AND MemberType=2 
		AND (
			SELECT COUNT(1)
			FROM caLoginLog with(nolock),caMain with(nolock)
			WHERE caLoginLog.caMainID=caMain.ID 
			AND caMain.cpMainID=cpMain.id 
			AND caLoginLog.AddDate>GETDATE()-14
			)>0 
		AND (
			SELECT COUNT(1)
			FROM caOrder WITH(NOLOCK) 
			WHERE Paid>0 
			AND OpenDate IS NOT NULL 
			AND OrderType=8
			AND cpMainID=cpMain.ID
		 )=0 
		AND ConsultantID=@consultantId
	)

	UPDATE @t 
	SET CntFactorPassiveOld=(
		SELECT COUNT(1) cnt 
		FROM cpMain WITH(NOLOCK) 
		WHERE ConsultantDate<GETDATE()-28 
		AND MemberType=2 
		AND (
			SELECT COUNT(1) 	
			FROM caLoginLog with(nolock),caMain with(nolock)
			WHERE caLoginLog.caMainID=caMain.ID 
			AND caMain.cpMainID=cpMain.id 
			AND caLoginLog.AddDate>GETDATE()-14
			)=0 
		AND (
			SELECT COUNT(1) 
			FROM caLoginLog with(nolock),caMain with(nolock) 
			WHERE caLoginLog.caMainID=caMain.ID 
			AND caMain.cpMainID=cpMain.id 
			AND caLoginLog.AddDate>GETDATE()-180
			)>0 
		AND (
			SELECT COUNT(1) 
			FROM caOrder WITH(NOLOCK) 
			WHERE Paid>0 
			AND EndDate>GETDATE()-28
			AND OrderType=8
			AND cpMainID=cpMain.ID
			)=0 
		AND (
			SELECT COUNT(1) 
			FROM caOrder WITH(NOLOCK) 
			WHERE Paid>0 
			AND OpenDate IS NOT NULL 
			AND OrderType=8
			AND cpMainID=cpMain.ID
			)>0 
		AND ConsultantID=@consultantId
	)

	UPDATE @t 
	SET	CntFactorPassiveNew=(
		SELECT COUNT(1) cnt
		FROM cpMain WITH(NOLOCK) 
		WHERE ConsultantDate<GETDATE()-28 
		AND MemberType=2 
		AND (
			SELECT COUNT(1)
			FROM caLoginLog with(nolock),caMain with(nolock)
			WHERE caLoginLog.caMainID=caMain.ID 
			AND caMain.cpMainID=cpMain.id 
			AND caLoginLog.AddDate>GETDATE()-14
			)=0 
		AND (
			SELECT COUNT(1)
			FROM caLoginLog with(nolock),caMain with(nolock) 
			WHERE caLoginLog.caMainID=caMain.ID 
			AND caMain.cpMainID=cpMain.id 
			AND caLoginLog.AddDate>GETDATE()-180
			)>0 
		AND (
			SELECT COUNT(1)
			FROM caOrder WITH(NOLOCK) 
			WHERE Paid>0 
			AND EndDate>GETDATE()-28 
			AND OrderType=8
			AND cpMainID=cpMain.ID
			)=0 
		AND (
			SELECT COUNT(1) 
			FROM caOrder WITH(NOLOCK) 
			WHERE Paid>0 
			AND OpenDate IS NOT NULL 
			AND OrderType=8
			AND cpMainID=cpMain.ID
			)=0 
		AND ConsultantID=@consultantId
	)

	UPDATE @t 
	SET	CntFactorDeadOld=(
		SELECT COUNT(1) cnt 
		FROM cpMain WITH(NOLOCK) 
		WHERE ConsultantDate<GETDATE()-28 
		AND MemberType=2 
		AND (
			SELECT COUNT(1) 
			FROM caLoginLog with(nolock),caMain with(nolock) 
			WHERE caLoginLog.caMainID=caMain.ID 
			AND caMain.cpMainID=cpMain.id 
			AND caLoginLog.AddDate>GETDATE()-180
			)=0 
		AND (
			SELECT COUNT(1) 
			FROM caOrder WITH(NOLOCK) 
			WHERE Paid>0 
			AND EndDate>GETDATE()-28 
			AND OrderType=8
			AND cpMainID=cpMain.ID
			)=0 
		AND (
			SELECT COUNT(1) 
			FROM caOrder WITH(NOLOCK) 
			WHERE Paid>0 
			AND OpenDate IS NOT NULL 
			AND OrderType=8
			AND cpMainID=cpMain.ID
			)>0 
		AND ConsultantID=@consultantId
	)

	UPDATE @t
	SET	CntFactorDeadNew=(
		SELECT COUNT(1) cnt
		FROM cpMain WITH(NOLOCK) 
		WHERE ConsultantDate<GETDATE()-28 
		AND MemberType=2 
		AND (
			SELECT COUNT(1) 
			FROM caLoginLog with(nolock),caMain with(nolock) 
			WHERE caLoginLog.caMainID=caMain.ID 
			AND caMain.cpMainID=cpMain.id 
			AND caLoginLog.AddDate>GETDATE()-180
			)=0 
		AND (
			SELECT COUNT(1) 
			FROM caOrder WITH(NOLOCK) 
			WHERE Paid>0 
			AND EndDate>GETDATE()-28 
			AND OrderType=8
			AND cpMainID=cpMain.ID
			)=0 
		AND (
			SELECT COUNT(1) 
			FROM caOrder WITH(NOLOCK) 
			WHERE Paid>0 
			AND OpenDate IS NOT NULL
			AND OrderType=8
			AND cpMainID=cpMain.ID
			)=0 
		AND ConsultantID=@consultantId
	)

	UPDATE @t 
	SET	CntFactorNew=(
		SELECT COUNT(1) cnt 
		FROM cpMain WITH(NOLOCK) 
		WHERE ConsultantDate>GETDATE()-28 
		AND MemberType=2 
		AND ConsultantID=@consultantId
		)

	SELECT * FROM @t
END


GO
/****** Object:  StoredProcedure [dbo].[bpCpMainByConsultantIdUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----------------
--创建日期：2010-9-14
--创建人：lambo
--功能说明：单位编号分配招聘顾问
--用于后台单位查询列表页面
-----------------

CREATE PROCEDURE [dbo].[bpCpMainByConsultantIdUpdate]
(
	@consultantId INT,
	@cpMainID INT
)
AS
	BEGIN TRY
		IF @consultantId=0 
			UPDATE cpMain SET consultantId = null, consultantDate = NULL WHERE ID=@cpMainID
		ELSE
			UPDATE cpMain SET consultantId = @consultantId, consultantDate = GETDATE() WHERE ID=@cpMainID	
	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH
RETURN 1
ERR:
BEGIN
	RETURN 0
END














GO
/****** Object:  StoredProcedure [dbo].[bpCpmainByConsultantUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.12.18
--创建人：Nick
--说明：根据consultantId 修改cpmain
--#####################################################
CREATE PROCEDURE [dbo].[bpCpmainByConsultantUpdate]
(
	@CpmainID INT
)
AS
BEGIN 
	UPDATE cpMain SET consultantId = null, consultantDate = NULL WHERE ID = @CpmainID
End


GO
/****** Object:  StoredProcedure [dbo].[bpCpMainByDailyGiftQuotaUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-----------------
--创建日期：2010-9-14
--创建人：lambo
--功能说明：修改单位的每日增加的简历下载数
--用于后台单位查询列表页面
-----------------

CREATE PROCEDURE [dbo].[bpCpMainByDailyGiftQuotaUpdate]
(
	@cpMainID INT,
	@DailyGiftQuota INT
)
AS
BEGIN
	UPDATE cpMain SET DailyGiftQuota = @DailyGiftQuota WHERE ID=@cpMainID	
	RETURN 1
END

GO
/****** Object:  StoredProcedure [dbo].[bpCpMainBydcProvinceIDUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-----------------
--创建日期：2010-9-14
--创建人：lambo
--功能说明：修改单位所属省份
--用于后台单位显示列表页面
--修改日期：2011-06-22
--修改单位所属省份时，将dcSubsiteID一同修改
-----------------

CREATE PROCEDURE [dbo].[bpCpMainBydcProvinceIDUpdate]
(
	@CpMainID INT,
	@dcProvinceID INT
)
AS
BEGIN TRY
	SET ARITHABORT ON
	UPDATE cpMain SET dcProvinceID = @dcProvinceID,dcSubSiteID=@dcProvinceID  WHERE ID = @CpMainID
END TRY
BEGIN CATCH
	GOTO ERR
END CATCH
RETURN 1
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END














GO
/****** Object:  StoredProcedure [dbo].[bpCpMainByDescriptionUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----------------
--创建日期：2010-9-14
--创建人：lambo
--功能说明：修改单位备注
--用于后台单位显示页面
-----------------

CREATE PROCEDURE [dbo].[bpCpMainByDescriptionUpdate]
(
	@CpMainID INT,
	@Description VARCHAR(300)
)
AS
BEGIN TRY
	UPDATE cpMain SET Description = @Description  WHERE ID = @CpMainID
END TRY
BEGIN CATCH
	GOTO ERR
END CATCH
RETURN 1
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END














GO
/****** Object:  StoredProcedure [dbo].[bpCpMainByEditUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.12.12
--创建人：John
--说明：用于cpEdit页面的操作处理
--#####################################################
CREATE PROCEDURE [dbo].[bpCpMainByEditUpdate]
(
	@sType INT,
	@CpMainID INT,
	@CompanyName VARCHAR(100),
	@ShortName VARCHAR(40),
	@HomePage VARCHAR(100),
	@Address NVARCHAR(60),
	@Brief VARCHAR(6000),
	@LinkMan NVARCHAR(6),
	@LinkManTitle NVARCHAR(20),
	@JobName NVARCHAR(50),
	@Responsibility VARCHAR(MAX),
	@Demand VARCHAR(MAX),
	@JobID INT,
	@IssueDate SMALLDATETIME,
	@IssueEnd SMALLDATETIME
)
AS
BEGIN
	--根据type的值判断操作类型
	--0 修改单位名称
	IF @sType = 0
	BEGIN
		UPDATE cpMain SET [Name] = @CompanyName WHERE ID = @CpMainID
	END
	--1 修改单位简称
	ELSE IF @sType = 1
	BEGIN
		UPDATE cpMain SET shortname = @ShortName WHERE ID = @CpMainID
	END
	--2 修改单位简介
	ELSE IF @sType = 2
	BEGIN
		UPDATE cpMain SET Homepage = @HomePage, Address = @Address, Brief = @Brief WHERE ID = @CpMainID
		UPDATE caMain SET [Name] = @LinkMan, Title = @LinkManTitle WHERE AccountType = 1 AND cpMainID = @CpMainID
	END
	--3 修改职位的岗位说明，岗位职责
	ELSE IF @sType = 3
	BEGIN
		UPDATE Job SET [Name] = @JobName, Responsibility = @Responsibility, Demand = @Demand WHERE ID = @JobID
	END
	--4 给职位添加删除标记
	ELSE IF @sType = 4
	BEGIN
		UPDATE Job SET IsDelete = 1 WHERE ID = @JobID
		UPDATE cpMain SET JobNumber = (SELECT COUNT(1) FROM Job WHERE valid = 1 AND cpMainID = @CpMainID) WHERE ID = @CpMainID
	END
	--5 取消职位的删除标记
	ELSE IF @sType = 5
	BEGIN
		UPDATE Job SET IsDelete = 0 WHERE ID = @JobID
		UPDATE cpMain SET JobNumber = (SELECT COUNT(1) FROM Job WHERE valid = 1 AND cpMainID = @CpMainID) WHERE ID = @CpMainID
	END
	--6 暂停职位
	ELSE IF @sType = 6
	BEGIN
		UPDATE Job SET IssueEnd = GETDATE()-0.1 WHERE ID = @JobID
		UPDATE cpMain SET JobNumber = (SELECT COUNT(1) FROM Job WHERE valid = 1 AND cpMainID = @CpMainID) WHERE ID = @CpMainID
	END
	--7 取消暂停职位
	ELSE IF @sType = 7
	BEGIN
		UPDATE Job SET IssueDate = @IssueDate, IssueEnd = @IssueEnd WHERE ID = @JobID
		UPDATE cpMain SET JobNumber = (SELECT COUNT(1) FROM Job WHERE valid = 1 AND cpMainID = @CpMainID) WHERE ID = @CpMainID
	END
END


GO
/****** Object:  StoredProcedure [dbo].[bpCpMainByIsAgentUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----------------
--创建日期：2010-9-14
--创建人：lambo
--功能说明：修改单位的代理状态，并将操作插入到单位状态操作记录表中
--用于后台单位显示列表页面
-----------------

CREATE PROCEDURE [dbo].[bpCpMainByIsAgentUpdate]
(
	@CpMainID INT,
	@VerifyMan SMALLINT
)
AS
BEGIN TRAN
	BEGIN TRY
		DECLARE @xType AS INT
		DECLARE @OldIsAgent AS BIT
		DECLARE @NewIsAgent AS BIT
		DECLARE @VerifyInfo AS VARCHAR(200)
		UPDATE cpMain SET IsAgent = IsAgent - 1 WHERE ID =@CpMainID
		SELECT @NewIsAgent = IsAgent , @OldIsAgent = IsAgent - 1 FROM cpMain WITH(NOLOCK) WHERE ID =@CpMainID
		SET @VerifyInfo = '修改代理状态，原状态=' + CONVERT(CHAR(1),@OldIsAgent) + ';修改后=' + CONVERT(CHAR(1),@NewIsAgent) + '。'
		IF @NewIsAgent = 1
			SET @xType = 7
		ELSE
			SET @xType = 8
		INSERT bsCpStatus(cpMainID,StatusID,VerifyInfo,HasPassed,VerifyMan,VerifyDate)
			VALUES(@CpMainID,@xType,@VerifyInfo,1,@VerifyMan,GETDATE())
	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH
COMMIT TRAN
RETURN 1
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END














GO
/****** Object:  StoredProcedure [dbo].[bpCpMainByIsDeleteUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----------------
--创建日期：2010-9-14
--创建人：lambo
--功能说明：修改单位的删除状态
--用于后台单位显示列表页面
-----------------
CREATE PROCEDURE [dbo].[bpCpMainByIsDeleteUpdate]
(
	@ID INT,
	@ManagerUserID INT,
	@Remarks NVARCHAR(1000),
	@IsDelete INT
)
AS
BEGIN
	DECLARE @UserName VARCHAR(50)
	DECLARE @PassWord VARCHAR(50)
	DECLARE @cpName NVARCHAR(50)
	DECLARE @LinkMan NVARCHAR(50)
	DECLARE @Telephone NVARCHAR(25)
	DECLARE @SecondId NVARCHAR(10)
	DECLARE @Email VARCHAR(50)
	DECLARE @ProvinceID INT
	DECLARE @ConsultantID SMALLINT
	IF @IsDelete=1
	BEGIN
		IF NOT EXISTS(SELECT 'x' FROM cpMain WITH(NOLOCK) WHERE HasLicence = 0 AND ID = @ID)
			GOTO ERR

		UPDATE cpMain SET IsDelete = @IsDelete WHERE ID=@ID

		SELECT @cpName = Name,@ProvinceID=dcSubSiteID, @ConsultantID = ConsultantID, @SecondId = SecondId
		FROM cpMain WITH(NOLOCK) WHERE ID = @ID

		SELECT TOP 1 @UserName = UserName,@PassWord = PassWord ,@TelePhone = IsNull(TelePhone,Mobile),@Email = Email 
		FROM caMain WITH(NOLOCK) WHERE cpMainID = @ID AND AccountType=1

		INSERT INTO Company_Deleted(Id, Username, Password, Companyname, LinkMan, Telephone, Email, Province_Id, HandleMan, AddDate, Remarks, ManagerUserId, SecondId)
		SELECT @ID, @UserName, @PassWord, @cpName, @LinkMan, @Telephone, @Email, @ProvinceID,@ManagerUserID,GETDATE(),@Remarks,@ConsultantID, @SecondId
 
		IF NOT EXISTS (SELECT id FROM backdata WITH (NOLOCK) WHERE managerid=@ManagerUserID AND CountDate=YEAR(GETDATE())*10000+MONTH(GETDATE())*100+DAY(GETDATE()))
			INSERT INTO BackData (managerid,countdate) VALUES(@ManagerUserID,YEAR(GETDATE())*10000+MONTH(GETDATE())*100+DAY(GETDATE()))
		UPDATE backdata SET companydelete = companydelete+ 1 WHERE managerid=@ManagerUserID AND CountDate=YEAR(GETDATE())*10000+MONTH(GETDATE())*100+DAY(GETDATE())
	END
	ELSE
	BEGIN
		UPDATE cpMain SET IsDelete = @IsDelete WHERE ID=@ID
		DELETE FROM Company_Deleted WHERE ID =@ID
	END 
END
RETURN 1
ERR:
BEGIN
	RETURN 0
END 














GO
/****** Object:  StoredProcedure [dbo].[bpCpMainByIsLimitLoginUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----------------
--创建日期：2010-9-14
--创建人：lambo
--功能说明：修改单位的限制登录状态，并将操作插入到单位状态操作记录表中
--用于后台单位显示列表页面
-----------------
CREATE PROCEDURE [dbo].[bpCpMainByIsLimitLoginUpdate]
(
	@cpMainID INT,
	@IsLimitLogin INT,
	@verifyman SMALLINT,
	@verifyInfo VARCHAR(500)
)
AS
BEGIN TRAN
	BEGIN TRY
		DECLARE @statusID INT
		UPDATE cpMain SET IsLimitLogin = @IsLimitLogin WHERE ID = @cpMainID
		IF @IsLimitLogin = 0		
			SET @statusID=10
		IF @IsLimitLogin = 9	
			SET @statusID=9
		IF @IsLimitLogin = 1
		BEGIN
			SET @statusID=11
			UPDATE cpMain SET Description=LEFT(@verifyInfo + '  审核：' +CONVERT(CHAR(4),@verifyman)+' 于' + CONVERT(VARCHAR(10),GETDATE(),120)+'，'+Description, 500) WHERE ID = @cpMainID

		END

		INSERT INTO bsCpStatus (cpMainID,statusID,verifyMan,verifyInfo,verifyDate)
			VALUES(@cpMainID,@statusID,@verifyman,@verifyInfo,GETDATE())

		--短信发送
		IF @IsLimitLogin = 9
			INSERT SmsMessageLog(SendMan, ManagerUSerId, paMainId, caMainId, Mobile, MsgType, IsCat, Msg)
			SELECT  @verifyman, NULL, NULL, a.ID, a.Mobile, 7, 0, 
				ISNULL(a.Name,'') + '您好，您在' + c.subsitename + c.EmailSite + '上的帐号已被限制登录，请咨询电话4006265151'
			FROM caMain a WITH(NOLOCK), cpMain b WITH(NOLOCK), dcSubSite c WITH(NOLOCK)
			WHERE a.cpMainID = b.ID
			AND AccountType = 1
			AND b.dcSubSiteID = c.ID
			AND a.Mobile > ''
			AND b.ID = @cpMainID
			AND a.IsReceiveSms = 1
		ELSE IF @IsLimitLogin = 0
			INSERT SmsMessageLog(SendMan, ManagerUSerId, paMainId, caMainId, Mobile, MsgType, IsCat, Msg)
			SELECT  @verifyman, NULL, NULL, a.ID, a.Mobile, 8, 0, 
				ISNULL(a.Name,'') + '您好，您在' + c.subsitename + c.EmailSite + '上的帐号已经取消限制登录，请登录网站使用'
			FROM caMain a WITH(NOLOCK), cpMain b WITH(NOLOCK), dcSubSite c WITH(NOLOCK)
			WHERE a.cpMainID = b.ID
			AND AccountType = 1
			AND b.dcSubSiteID = c.ID
			AND a.Mobile > ''
			AND b.ID = @cpMainID
			AND a.IsReceiveSms = 1
	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH
COMMIT TRAN
RETURN 1
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END














GO
/****** Object:  StoredProcedure [dbo].[bpCpMainByIsProtectUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Mice 123>
-- Create date: <2015-7-10>
-- Description:	<更新保护密码>
-- =============================================
CREATE PROCEDURE [dbo].[bpCpMainByIsProtectUpdate]
(
	@cpMainID INT,
	@IsProtect INT 
)
AS
BEGIN
	SET NOCOUNT ON
	IF @IsProtect = 1
	BEGIN
		UPDATE MainDB..cpMain SET IsProtect = 1 WHERE ID = @CpMainID
	END
	ELSE
	BEGIN
		UPDATE MainDB..cpMain SET IsProtect = 0 WHERE ID = @CpMainID
		UPDATE MainDB..caMain SET SecondPassword = NULL WHERE cpMainID = @CpMainID
	END
	SET NOCOUNT OFF
END

GO
/****** Object:  StoredProcedure [dbo].[bpCpMainByLicenceDelete]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--20180302 Lucifer
CREATE PROCEDURE [dbo].[bpCpMainByLicenceDelete]
(
    @cpMainID INT
)
AS
SET NOCOUNT ON
BEGIN
    DELETE FROM cpCertification WHERE cpMainID = @cpMainID
    DELETE FROM cpLicence WHERE cpMainID = @cpMainID
    UPDATE cpMain SET RealName = 0,MemberType = 1, HasLicence = 0 WHERE ID = @cpMainID
END
SET NOCOUNT OFF
GO
/****** Object:  StoredProcedure [dbo].[bpCpMainByMaxJobNumberUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-----------------
--创建日期：2010-11-13
--创建人：lambo
--功能说明：修改单位的最大职位数
--用于后台单位显示页面
-----------------
CREATE PROCEDURE [dbo].[bpCpMainByMaxJobNumberUpdate]
	@ID INT,
	@MaxJobNumber INT
AS
BEGIN TRY
	UPDATE cpMain SET MaxJobNumber = @MaxJobNumber WHERE ID = @ID
END TRY
BEGIN CATCH
	GOTO ERR
END CATCH
RETURN 1
ERR:
BEGIN
	RETURN 0
END 














GO
/****** Object:  StoredProcedure [dbo].[bpCpMainByMaxUserNumberUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-----------------
--创建日期：2010-11-13
--创建人：lambo
--功能说明：修改单位的最大用户数
--用于后台单位显示页面
-----------------
CREATE PROCEDURE [dbo].[bpCpMainByMaxUserNumberUpdate]
	@ID INT,
	@MaxUserNumber INT
AS
BEGIN TRY
	UPDATE cpMain SET MaxUserNumber = @MaxUserNumber WHERE ID = @ID
END TRY
BEGIN CATCH
	GOTO ERR
END CATCH
RETURN 1
ERR:
BEGIN
	RETURN 0
END 














GO
/****** Object:  StoredProcedure [dbo].[bpcpMainByMemberTypeSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--######################################3
--创建：Sean 2010-11-16
--判断企业用户类型
--######################################3
CREATE PROCEDURE [dbo].[bpcpMainByMemberTypeSelect]
(
	@ID INT
)
AS
BEGIN
	--RETURN dbo.MemberType(@ID)
	RETURN (SELECT MemberType FROM cpMain WITH(NOLOCK) WHERE ID = @ID)
END














GO
/****** Object:  StoredProcedure [dbo].[bpCpMainByNameCountSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.12.8
--创建人：John
--说明：根据公司名称查询公司个数
--#####################################################
CREATE PROCEDURE [dbo].[bpCpMainByNameCountSelect]
(
	@CpName VARCHAR(100)
)
AS
BEGIN
	SELECT COUNT(1) cnt FROM cpMain WHERE [Name] = @CpName
END


GO
/****** Object:  StoredProcedure [dbo].[bpCpMainByPointGroupSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--创建人 Andy
--时间 2014-12-31
--积分排行页面为不同的积分段进行统计（50分作为一个分割）
CREATE PROCEDURE [dbo].[bpCpMainByPointGroupSelect]
(		
	@ProvinceID INT	
)
AS
BEGIN	
	SELECT ReMainPoint / 50 AS rowIndex, MemberType, COUNT(id) AS rowNum  
	FROM cpMain WITH(NOLOCK)
	WHERE ReMainPoint >= 0 
	AND MemberType IN (2, 3) 
	AND dcProvinceID = @ProvinceID
	AND Valid = 1
	GROUP BY ReMainPoint / 50, MemberType
	ORDER BY rowIndex ASC, MemberType DESC
END


GO
/****** Object:  StoredProcedure [dbo].[bpCpMainBySecondIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.09.06
--创建人：Nick
--说明：根据jobid查询cpmain
--#####################################################
create PROCEDURE [dbo].[bpCpMainBySecondIDSelect]
(
	@SecondID VARCHAR(50)
)
AS
BEGIN
	SELECT a.SecondId FROM cpMain a, Job b WHERE b.cpMainId = a.Id AND b.SecondId = @SecondID
END

GO
/****** Object:  StoredProcedure [dbo].[bpCpMainByTop50PointSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--创建人 Andy
--时间 2014-12-31
--按照MemberType和ProvinceID查询积分排名前50的企业(用于积分排行页面)
CREATE PROCEDURE [dbo].[bpCpMainByTop50PointSelect]
(		
	@MemberType INT,	
	@ProvinceID INT	
)
AS
BEGIN	
	SELECT TOP 50 * 
	FROM CpMain 
	WHERE  MemberType = @MemberType AND dcProvinceID = @ProvinceID
	ORDER BY ReMainPoint DESC
END

GO
/****** Object:  StoredProcedure [dbo].[bpCpMainByVerifySelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[bpCpMainByVerifySelect]
(
	@VerifyMan SMALLINT,
	@Type TINYINT,	--1:待审核；10：已经审核；20：审核通过；21：审核不通过
	@SubNo TINYINT,	--默认值：0
	@MaxNo TINYINT	--默认值：1
)
AS
BEGIN
	IF @Type = 1
		BEGIN
			IF @MaxNo<1
				SET @MaxNo=1
			IF @SubNo<0 OR @SubNo >= @MaxNo
				SET @SubNo = 0
			SELECT TOP 1000
				ID,
				Name,
				LastModifyDate,
				BlockCount,
		        UnLimitedDate,
				BalanceDate,
				Balance,
		        IsAgent
			FROM cpMain WITH(NOLOCK)
			WHERE VerifyResult=10
			AND (id % @MaxNo) = @SubNo
			AND LastModifyDate < DateAdd(HOUR,-1,GETDATE())
			ORDER BY LastModifyDate
		END
	IF @Type = 10
		BEGIN
			SELECT TOP 500
				ID,
				Name,
				LastModifyDate,
				BlockCount,
		        UnLimitedDate,
				BalanceDate,
				Balance,
		        IsAgent,
				VerifyResult
			FROM cpMain WITH(NOLOCK)
			WHERE VerifyResult<>10
			ORDER BY ID DESC
		END	
	IF @Type = 20
		BEGIN
			SELECT TOP 500
				ID,
				Name,
				LastModifyDate,
				BlockCount,
		        UnLimitedDate,
				BalanceDate,
				Balance,
		        IsAgent,
				VerifyResult
			FROM cpMain WITH(NOLOCK)
			WHERE VerifyResult>10
			ORDER BY ID DESC
		END
	IF @Type = 21
		BEGIN
			SELECT TOP 500
				ID,
				Name,
				LastModifyDate,
				BlockCount,
		        UnLimitedDate,
				BalanceDate,
				Balance,
		        IsAgent,
				VerifyResult
			FROM cpMain WITH(NOLOCK)
			WHERE VerifyResult<10
			ORDER BY ID DESC
		END
END














GO
/****** Object:  StoredProcedure [dbo].[bpCpMainCaMainByAccountTypeSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--###########################
--创建时间：2014.12.10
--创建人：Nick
--说明：营业执照审核页面
--###########################
--lucifer 2017-11-8
CREATE PROCEDURE [dbo].[bpCpMainCaMainByAccountTypeSelect]
(
	@CpmainID INT
)
AS
BEGIN 
	SELECT a.ID cpMainID, a.HasLicence, a.Name companyname, 
		(SELECT TOP 1 CompanyName FROM cpCertification WHERE cpMainID = a.ID AND CerStatus IS NULL) CerCompanyName, 
		a.dcProvinceID, a.RefreshDate, a.RegCapital, a.dcSubSiteID, a.AddMan, 
		a.RegDate, a.RegisterIP, b.mobile, b.Telephone, a.Description, a.HomePage, 
		a.ConsultantID, a.VerifyResult, b.ID caMainID 
	FROM cpMain a WITH(NOLOCK), caMain b WITH(NOLOCK) 
	WHERE a.ID = b.cpMainID 
	AND b.AccountType = 1 
	AND a.ID = @CpmainID
END
GO
/****** Object:  StoredProcedure [dbo].[bpcpMainHomepageSnapshotByCpMainIDDelete]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.12.18
--创建人：Nick
--说明：限制登陆删除cpMainHomepageSnapshot
--#####################################################
CREATE PROCEDURE [dbo].[bpcpMainHomepageSnapshotByCpMainIDDelete]
(
	@CpmainID INT
)
AS
BEGIN 
	DELETE SearchDb..cpMainHomepageSnapshot WHERE RealcpMainId = @CpmainID
End


GO
/****** Object:  StoredProcedure [dbo].[bpCpMainIndustryCountByIndustrySelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/**
*创建者：Peter
*时间：2014-12-03
*按照行业分类查询职位数量
*/
CREATE PROCEDURE [dbo].[bpCpMainIndustryCountByIndustrySelect]
(
	@YearMonth VARCHAR(100),
	@RegionID INT,
	@Industry VARCHAR(50),
	@MemberType VARCHAR(10)
)
AS
BEGIN
	DECLARE @MaxMonth VARCHAR(6),@MinMonth VARCHAR(6),@RecentMonth VARCHAR(6),@SQL VARCHAR(2000)
	
	SET @SQL = 'SELECT a.IndustryID,b.Description'
	
	SELECT * INTO #TYearMonth FROM dbo.fnsplit(@YearMonth,',')
	
	SELECT @MaxMonth = Max(a) FROM #TYearMonth
	SELECT @MinMonth = Min(a) FROM #TYearMonth
	
	WHILE (SELECT COUNT(*) FROM #TYearMonth) > 0
	BEGIN
		SELECT TOP 1 @RecentMonth = a FROM #TYearMonth
		SET @SQL = @SQL + ',MAX(CASE CountMonth WHEN ''' + @RecentMonth + ''' THEN jobCount ELSE 0 END) ''' + @RecentMonth + ''' '
		DELETE FROM #TYearMonth WHERE a = @RecentMonth
	END
	
	DROP TABLE #TYearMonth
	
	SET @SQL = @SQL + '
	FROM(
		SELECT CountMonth,IndustryID,SUM(Number) jobCount
		FROM reportdb..CpMainIndustryCount 
		WHERE 1 = 1 '
	IF @RegionID > 0 
	BEGIN
		SET @SQL = @SQL + 'AND provinceid = ' + CONVERT(VARCHAR(6),@RegionID) + ' '
	END
	
	IF LEN(@MemberType) > 0 
	BEGIN
		SET @SQL = @SQL + 'AND MemberType IN (' + @MemberType + ') '
	END
	
	SET @SQL = @SQL + '
		AND countMonth BETWEEN ' + @MinMonth + ' AND ' + @MaxMonth + '  
		AND IndustryID IN (' + @Industry + ') 
		GROUP BY CountMonth,IndustryID) AS a
	LEFT JOIN dcIndustry b ON b.ID = a.IndustryID
	GROUP BY a.IndustryID,b.Description'
	
	--PRINT @SQL
	EXEC(@SQL)
	
END


GO
/****** Object:  StoredProcedure [dbo].[bpCpMainSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--harry 2018-1-19
CREATE PROCEDURE [dbo].[bpCpMainSelect]
(
    @count INT,
    @WHERE VARCHAR(MAX),
    @ORDER VARCHAR(1000),
    @Page SMALLINT
)
AS
SET NOCOUNT ON
BEGIN
    SET @ORDER = REPLACE(dbo.SafeSQLBack(@ORDER), '''', '''''')
    DECLARE @SQL AS VARCHAR(2000)
    CREATE TABLE #T(
        TitleID BIGINT,
        ID INT,
        [Name] NVARCHAR(100),
        dcProvinceID TINYINT,
        ConsultantID SMALLINT,
        RegDate SMALLDATETIME,
        MemberType TINYINT,
        UnlimitedDate SMALLDATETIME,
        Balance SMALLINT,
        BalanceDate SMALLDATETIME,
        VerifyResult TINYINT,
        IsAgent BIT,
        IsLimitLogin TINYINT,
        DailyGiftQuota TINYINT,
        IsDelete BIT,
        JobNumber SMALLINT,
        HasLicence BIT,
        LoginDate SMALLDATETIME,
        LicenceHasPassed TINYINT,
        LicenceCheckDate SMALLDATETIME,
        LicenceIP VARCHAR(39),
        LogoHasPassed TINYINT,
        VisualHasPassed TINYINT,
        CpImgAll TINYINT,
        CpImgHasPassed TINYINT,
        cpImgWaitPass TINYINT,
        CpImgNotPassed TINYINT,
        RegisterIP VARCHAR(39),
        RealName TINYINT,
	CerMemberType TINYINT,
	CerType TINYINT,
	CerDate SMALLDATETIME
    )

    SET @SQL='
        INSERT INTO #T
        (TitleID,ID,Name,HasLicence,ConsultantID,RegDate,dcProvinceID,MemberType,VerifyResult,
        IsAgent,UnlimitedDate,Balance,BalanceDate,IsLimitLogin,
        DailyGiftQuota,IsDelete,JobNumber,RegisterIP,LoginDate,LicenceIP,RealName)

        SELECT DISTINCT TOP '+LTRIM(STR(@count))+' ROW_NUMBER() OVER (' + @ORDER + ') AS TitleID,a.ID,a.Name,HasLicence,
        ConsultantID,a.RegDate,dcProvinceID,MemberType,VerifyResult,IsAgent,UnlimitedDate,Balance,
        BalanceDate,IsLimitLogin,DailyGiftQuota,a.IsDelete,JobNumber,RegisterIP,LastLoginDate, LastLoginIp,RealName 
        FROM cpMain a WITH(NOLOCK'
	IF @WHERE LIKE '%AND a.Name%'
		SET @SQl = @Sql + ' INDEX(IX_cpMain_Name)) '
	ELSE
		SET @SQl = @Sql + ') '

    IF LEN(@WHERE) > 0
    BEGIN
        IF CHARINDEX('c.', @WHERE) > 0
            SET @SQL = @SQL + ' INNER JOIN caMain c WITH(NOLOCK) ON a.ID = c.cpMainID'
        
        SET @SQL = @SQL + ' WHERE 1=1 ' + @WHERE
    END
    EXEC(@Sql)

    UPDATE #T SET
        LicenceHasPassed = (SELECT TOP 1 CASE HasPassed WHEN 1 THEN 1 WHEN 0 THEN 0 ELSE 2 END FROM cpLicence WITH(NOLOCK) WHERE cpMainID = #T.ID ORDER BY ID DESC),
        LicenceCheckDate = (SELECT TOP 1 CheckDate FROM cpLicence WITH(NOLOCK) WHERE cpMainID = #T.ID ORDER BY ID DESC),
        LogoHasPassed = (SELECT TOP 1 CASE HasPassed WHEN 1 THEN 1 WHEN 0 THEN 0 ELSE 2 END FROM cpImage WITH(NOLOCK) WHERE cpMainID = #T.ID AND ImgType = 1),
        VisualHasPassed = (SELECT TOP 1 CASE HasPassed WHEN 1 THEN 1 WHEN 0 THEN 0 ELSE 2 END FROM cpImage WITH(NOLOCK) WHERE cpMainID = #T.ID AND ImgType = 2),
        CpImgAll = (SELECT COUNT(1) FROM cpImage WITH(NOLOCK) WHERE cpMainID = #T.ID AND ImgType = 3),
        CpImgHasPassed = (SELECT COUNT(1) FROM cpImage WITH(NOLOCK) WHERE cpMainID = #T.ID AND ImgType = 3 AND HasPassed = 1 ),
        cpImgWaitPass = (SELECT COUNT(1) FROM cpImage WITH(NOLOCK) WHERE cpMainID = #T.ID AND ImgType = 3 AND HasPassed IS NULL ),
        CpImgNotPassed = (SELECT COUNT(1) FROM cpImage WITH(NOLOCK) WHERE cpMainID = #T.ID AND ImgType = 3 AND HasPassed = 0 ),
		CerMemberType = (SELECT TOP 1 MemberType FROM cpCertification WITH(NOLOCK) WHERE cpMainID = #T.ID AND CerStatus = 1 ORDER BY CerDate DESC),
		CerType = (SELECT TOP 1 CerType FROM cpCertification WITH(NOLOCK) WHERE cpMainID = #T.ID AND CerStatus = 1 ORDER BY CerDate DESC),
		CerDate = (SELECT TOP 1 CerDate FROM cpCertification WITH(NOLOCK) WHERE cpMainID = #T.ID AND CerStatus = 1 ORDER BY CerDate DESC)
    WHERE TitleID > (@Page-1)*20 AND TitleID <= @Page*20

	--harry注释 2018-1-19，这样update错误，也没有必要
	--UPDATE a SET
	--	CerMemberType = b.MemberType,
	--	CerType = b.CerType,
	--	CerDate = b.CerDate
	--FROM #T a, cpCertification b
	--WHERE a.ID = b.cpMainID AND CerStatus = 1

    SELECT COUNT(*) FROM #T WITH(NOLOCK)
    SELECT a.*, b.MemberType UnFinishedMemberType, b.CerType UnFinishedCerType, c.HasPassed, d.CheckResult PersonalCheckResult, e.CheckResult CompanyEmailCheckResult
	FROM #T a WITH(NOLOCK)
		LEFT JOIN cpCertification b WITH(NOLOCK) ON a.ID = b.cpMainID AND b.CerStatus IS NULL
		LEFT JOIN cpLicence c WITH(NOLOCK) ON b.ID = c.cpCertificationID
		LEFT JOIN cpPersonalAccount d WITH(NOLOCK) ON b.ID = d.cpCertificationID
		LEFT JOIN cpCompanyEmail e WITH(NOLOCK) ON b.ID = e.cpCertificationID
	WHERE TitleID > (@Page-1)*20 AND TitleID <= @Page*20
    DROP TABLE #T
END 
GO
/****** Object:  StoredProcedure [dbo].[bpCpMainSelectbak]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[bpCpMainSelectbak]
(
	@count INT,
	@WHERE VARCHAR(MAX),
	@ORDER VARCHAR(1000),
	@Page SMALLINT
)
AS
BEGIN
	BEGIN TRY
		SET @WHERE = dbo.SafeSQLBack(@WHERE)
		SET @ORDER = dbo.SafeSQLBack(@ORDER)
		DECLARE @SQL AS VARCHAR(2000)
		CREATE TABLE #T(
			TitleID BIGINT,
			ID INT,
			[Name] NVARCHAR(100),
			dcProvinceID TINYINT,
			ConsultantID SMALLINT,
			RegDate SMALLDATETIME,
			MemberType TINYINT,
			UnlimitedDate SMALLDATETIME,
			Balance SMALLINT,
			BalanceDate SMALLDATETIME,
			VerifyResult TINYINT,
			IsAgent BIT,
			IsLimitLogin TINYINT,
			DailyGiftQuota TINYINT,
			IsDelete BIT,
			JobNumber SMALLINT,
			HasLicence BIT,
			LoginDate SMALLDATETIME,
			LicenceHasPassed TINYINT,
			LicenceCheckDate SMALLDATETIME,
			LicenceIP VARCHAR(39),
			LogoHasPassed TINYINT,
			VisualHasPassed TINYINT,
			RegisterIP VARCHAR(39)
		)
				SELECT COUNT(*) FROM #T WITH(NOLOCK)
		SELECT * FROM #T WITH(NOLOCK)
return
		SET @SQL='
			INSERT INTO #T
			(TitleID,ID,Name,HasLicence,ConsultantID,RegDate,dcProvinceID,MemberType,VerifyResult,
			IsAgent,UnlimitedDate,Balance,BalanceDate,IsLimitLogin,
			DailyGiftQuota,IsDelete,JobNumber,RegisterIP,LoginDate,LicenceIP)

			SELECT DISTINCT TOP '+LTRIM(STR(@count))+' ROW_NUMBER() OVER (' + @ORDER + ') AS TitleID,a.ID,a.Name,HasLicence,
			ConsultantID,a.RegDate,dcProvinceID,MemberType,VerifyResult,IsAgent,UnlimitedDate,Balance,
			BalanceDate,IsLimitLogin,DailyGiftQuota,a.IsDelete,JobNumber,RegisterIP,LastLoginDate, LastLoginIp
			FROM cpMain a WITH(NOLOCK) '

		IF LEN(@WHERE) > 0
		BEGIN
			IF CHARINDEX('c.', @WHERE) > 0
				SET @SQL = @SQL + ' INNER JOIN caMain c WITH(NOLOCK) ON a.ID = c.cpMainID'
			
			SET @SQL = @SQL + ' WHERE 1=1 ' + @WHERE
		END
		print @sql
		EXEC(@SQL)

		UPDATE #T SET
			LicenceHasPassed = (SELECT TOP 1 CASE HasPassed WHEN 1 THEN 1 WHEN 0 THEN 0 ELSE 2 END FROM cpLicence WITH(NOLOCK) WHERE cpMainID = #T.ID ORDER BY ID DESC),
			LicenceCheckDate = (SELECT TOP 1 CheckDate FROM cpLicence WITH(NOLOCK) WHERE cpMainID = #T.ID ORDER BY ID DESC),
			LogoHasPassed = (SELECT TOP 1 CASE HasPassed WHEN 1 THEN 1 WHEN 0 THEN 0 ELSE 2 END FROM cpImage WITH(NOLOCK) WHERE cpMainID = #T.ID AND ImgType = 1),
			VisualHasPassed = (SELECT TOP 1 CASE HasPassed WHEN 1 THEN 1 WHEN 0 THEN 0 ELSE 2 END FROM cpImage WITH(NOLOCK) WHERE cpMainID = #T.ID AND ImgType = 2)
		WHERE TitleID > (@Page-1)*20 AND TitleID <= @Page*20

		SELECT COUNT(*) FROM #T WITH(NOLOCK)
		SELECT * FROM #T WITH(NOLOCK) WHERE TitleID > (@Page-1)*20 AND TitleID <= @Page*20
		DROP TABLE #T
	END TRY
	BEGIN CATCH
		DROP TABLE #T
	END CATCH
END





GO
/****** Object:  StoredProcedure [dbo].[bpCpMemberTryoutDelete]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----------------
--创建日期：2010-9-14
--创建人：lambo
--功能说明：删除一条单位免费试用记录
--用于后台单位免费试用记录
-----------------

CREATE PROCEDURE [dbo].[bpCpMemberTryoutDelete]
	@ID INT
AS
BEGIN TRY
	DELETE FROM CpMemberTryout WHERE ID=@ID
END TRY
BEGIN CATCH
	GOTO ERR
END CATCH
RETURN 1
ERR:
BEGIN
	RETURN 0
END 














GO
/****** Object:  StoredProcedure [dbo].[bpCpMemberTryoutSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----------------
--创建日期：2010-9-14
--创建人：lambo
--功能说明：根据条件查询企业免费试用记录
--用于企业免费试用页面
-----------------
CREATE PROCEDURE [dbo].[bpCpMemberTryoutSelect]
(
	@WHERE VARCHAR(1000)
)
AS
BEGIN
	DECLARE @SQL VARCHAR(2000)
	SET @SQL = 'SELECT a.*,b.ConsultantId,b.UnlimitedDate,b.BalanceDate,b.Balance,b.regDate '
	SET @SQL = @SQL + ' FROM CpMemberTryout a WITH(NOLOCK) ,cpMain b WITH(NOLOCK) '
	SET @SQL = @SQL + ' WHERE a.cpMainId = b.ID '
	IF LEN(@WHERE) > 0
	BEGIN
		SET @WHERE = dbo.SafeSql(@Where)
		SET @SQL = @SQL + @WHERE
	END
	SET @SQL=@SQL + ' ORDER BY a.AddDate DESC'
	EXEC(@SQL)
END




GO
/****** Object:  StoredProcedure [dbo].[bpCpPersonalAccountUpdateByVerify]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--审核个人认证法人
CREATE PROCEDURE [dbo].[bpCpPersonalAccountUpdateByVerify]
(
	@cpPersonalAccountID INT,
	@CheckResult INT,
	@CheckMan INT
)
AS
BEGIN
	DECLARE @cpCertificationID INT
	SELECT TOP 1 @cpCertificationID = cpCertificationID 
	FROM MainDB..cpPersonalAccount WITH(NOLOCK) 
	WHERE ID = @cpPersonalAccountID
	IF @cpCertificationID IS NULL
		RETURN

	UPDATE MainDB..cpPersonalAccount 
	SET CheckResult = @CheckResult,CheckMan = @CheckMan,CheckDate = GETDATE()
	WHERE id = @cpPersonalAccountID
	
	IF @CheckResult = 1
	BEGIN
		UPDATE MainDB..cpCertification 
		SET CerStatus = 1
		WHERE ID = @cpCertificationID
	END
	ELSE
	BEGIN
		INSERT INTO SmsMessageLog (SendMan, caMainId, Mobile, Msg, MsgType, IsCat)
		SELECT TOP 1 @CheckMan, b.ID, a.Mobile, '您的法人身份认证未通过，请登录' + d.WebSiteName + '(www.' + d.ProvinceDomain + ')进行查看', 50, 0
		FROM cpCertification a WITH(NOLOCK)
		INNER JOIN caMain b WITH(NOLOCK) ON a.cpMainID = b.cpMainID
		INNER JOIN cpMain c WITH(NOLOCK) ON b.cpMainID = c.ID
		INNER JOIN dcProvince d WITH(NOLOCK) ON c.dcProvinceID = d.ID
		WHERE a.ID = @cpCertificationID AND b.AccountType = 1
	END
END
GO
/****** Object:  StoredProcedure [dbo].[bpCpPointByDeductInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--后台扣除积分--
--修改：harry 增加更新订单使用积分数
CREATE PROCEDURE [dbo].[bpCpPointByDeductInsert]
(
	@Point INT,
	@OrderId INT,
	@CpMainId INT,
	@Remark VARCHAR(15)
)
AS
BEGIN
	IF NOT EXISTS(SELECT 'x' FROM cppoint WHERE relativeID = @OrderId AND ChangeID=15)
	BEGIN	--该订单不存在扣除积分
		IF @Point!=0
		BEGIN
			INSERT INTO cppoint(cpMainID, ChangeID, Point, relativeID, LastModifyDate, Remark)
			VALUES(@CpMainId, 15, @Point, @OrderId, getdate(), @Remark)
			UPDATE caOrder 
			SET PaidPoint=abs(@Point) 
			WHERE id=@OrderId
		END
	END
END 
GO
/****** Object:  StoredProcedure [dbo].[bpCpPointInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--###########################
--创建时间：2014.12.15
--创建人：Nick
--说明：插入cpPoint
--###########################
CREATE PROCEDURE [dbo].[bpCpPointInsert]
(
	@CpmainID INT
)
AS
BEGIN 
	INSERT INTO cpPoint (cpMainID, ChangeID, Point, LastModifyDate) VALUES (@CpmainID, 2, 80, GETDATE())
END


GO
/****** Object:  StoredProcedure [dbo].[bpcpSessionSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----------------
--创建日期：2011-01-17
--创建人：lambo
--功能说明：查询企业的在线信息，查询当前在线的用户
--用于后台企业信息显示页面和客户界面
--修改人：lambo
--从新的在线状态表里取数据
-----------------

CREATE PROCEDURE [dbo].[bpcpSessionSelect]
	@caMainID INT
AS
--SELECT TOP 1 RefreshDate
--	FROM cpSession WITH(NOLOCK)
--	WHERE caMainID = @caMainID
--	AND DATEDIFF(mi,RefreshDate, GETDATE()) <= 2
--	ORDER BY RefreshDate DESC 
select top 1 RefreshDate 
from caonline 
where isonline=1 and caMainID = @caMainID
ORDER BY RefreshDate DESC 







GO
/****** Object:  StoredProcedure [dbo].[bpCustomerTrackingSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--2018-1-24 lucifer
--2018-03-09 Carl 增加有效职位数等临时表字段
--2018-7-2 harry 增加islimitlogin 
CREATE PROCEDURE [dbo].[bpCustomerTrackingSelect]
(
	@WHERE VARCHAR(1000),
	@ORDER TINYINT,
	@Page SMALLINT
)
AS
SET NOCOUNT ON
BEGIN
	SET @WHERE = dbo.SafeSQLBack(@WHERE)
	DECLARE @SQL AS VARCHAR(2000)
	DECLARE @strOrder AS VARCHAR(1000)
	SET @strOrder = ''
	IF @ORDER = 1
		SET @strOrder = @strOrder + ' ORDER BY ConsultantDate DESC'
	ELSE IF @ORDER = 2
		SET @strOrder = @strOrder + ' ORDER BY LastLoginDate DESC'
	ELSE IF @ORDER = 3
		SET @strOrder = @strOrder + ' ORDER BY (SELECT TOP 1 CerDate FROM MainDB..cpCertification WITH(NOLOCK) WHERE cpMainID = a.ID ORDER BY CerDate DESC) DESC'
	ELSE IF @ORDER = 4
		SET @strOrder = @strOrder + ' ORDER BY RegDate DESC'
	ELSE IF @ORDER = 5
		SET @strOrder = @strOrder + ' ORDER BY JobNumber DESC'
	ELSE IF @ORDER = 6
		SET @strOrder = @strOrder + ' ORDER BY (SELECT COUNT(1) FROM CaCvQuotaLog WITH(NOLOCK) WHERE cpMainID = a.ID) DESC'
	ELSE IF @ORDER = 12
		SET @strOrder = @strOrder + ' ORDER BY (SELECT COUNT(1) FROM CaActiveLog WITH(NOLOCK) WHERE cpMainID = a.ID AND AddDate > CONVERT(VARCHAR(10), GETDATE(), 23)) DESC, LastLoginDate DESC'
	ELSE IF @ORDER = 7
		SET @strOrder = @strOrder + ' ORDER BY (SELECT TOP 1 AddDate FROM bsCpStatus WITH(NOLOCK) WHERE cpMainID = a.ID AND statusID=9 ORDER BY AddDate DESC) DESC'
	ELSE IF @ORDER = 8
		SET @strOrder = @strOrder + ' ORDER BY (Select TOP 1 VerifyDate From bsCpVerify Where cpMainID=a.ID) DESC'
	ELSE IF @ORDER = 9
		SET @strOrder = @strOrder + ' ORDER BY (SELECT TOP 1 begintime FROM contact WITH(NOLOCK) WHERE status=2 AND companyid=a.ID ORDER BY begintime DESC) DESC'
	ELSE IF @ORDER = 10
		SET @strOrder = @strOrder + ' ORDER BY (SELECT TOP 1 begintime FROM contact WITH(NOLOCK) WHERE status=2 AND companyid=a.ID ORDER BY begintime DESC)'
	ELSE IF @ORDER = 14
		SET @strOrder = @strOrder + ' ORDER BY (SELECT TOP 1 EndDate FROM caOrder WITH(NOLOCK) WHERE OrderType=8 AND BeginDate<GetDate() AND EndDate>GETDATE() AND cpMainId = a.Id AND IsDeleted = 0)'
	ELSE IF @ORDER = 15
		SET @strOrder = @strOrder + ' ORDER BY BalanceDate'
	ELSE IF @ORDER = 13
		SET @strOrder = @strOrder + ' ORDER BY Balance'
	ELSE IF @ORDER = 17
		SET @strOrder = @strOrder +  ' ORDER BY d.Id DESC'
	Else IF @ORDER = 0
		SET @strOrder = @strOrder + ' ORDER BY LastLoginDate DESC'
	ELSE IF @ORDER = 19
		SET @strOrder = @strOrder + ' ORDER BY (SELECT TOP 1 EndDate FROM caOrder WITH(NOLOCK) WHERE OrderType=8 AND BeginDate<GetDate() AND EndDate>GETDATE() AND cpMainId = a.Id AND IsDeleted = 0) DESC'
	ELSE IF @ORDER = 20
		SET @strOrder = @strOrder + ' ORDER BY BalanceDate DESC'
	Else IF @ORDER = 16
		SET @strOrder = @strOrder + ' ORDER BY MemberDate'
	Else IF @ORDER = 21
		SET @strOrder = @strOrder + ' ORDER BY MemberDate DESC'
	Else IF @ORDER = 22
		SET @strOrder = @strOrder + ' order by (select top 1  checkdate from cpimage WITH(NOLOCK) where cpmainid=a.id and imgtype=1 and HasPassed=1 ORDER BY checkdate  DESC) desc'
	Else IF @ORDER = 23
		SET @strOrder = @strOrder + ' ORDER BY (SELECT TOP 1 OpenDate FROM caOrder WITH(NOLOCK) WHERE OrderType=8 AND BeginDate<GetDate() AND EndDate>GETDATE() AND cpMainId = a.Id AND IsDeleted = 0) DESC'
	--新添加的条件
	Else IF @ORDER = 24 --按级别正序
		SET @strOrder = @strOrder + ' ORDER BY (SELECT TOP 1 Quality FROM contact WITH(NOLOCK) WHERE a.id=companyid ORDER BY AddDate DESC)'
	Else IF @ORDER = 25 --按级别倒序
		SET @strOrder = @strOrder + ' ORDER BY (SELECT TOP 1 Quality FROM contact WITH(NOLOCK) WHERE a.id=companyid ORDER BY AddDate DESC) DESC'
	Else IF @ORDER = 26 --按预约时间倒序
		SET @strOrder = @strOrder + ' ORDER BY (SELECT TOP 1 begintime FROM contact WITH(NOLOCK) WHERE a.id=companyid ORDER BY AddDate DESC) DESC'
        Else IF @ORDER = 27 --按预约时间正序
		SET @strOrder = @strOrder + ' ORDER BY (SELECT TOP 1 begintime FROM contact WITH(NOLOCK) WHERE a.id=companyid ORDER BY AddDate DESC)'

	CREATE TABLE #T(
		TitleID BIGINT,
		ID INT,
		Name VARCHAR(100) COLLATE Chinese_PRC_CI_AS,
		Quality TINYINT,
		ConsultantID SMALLINT, 
		RegDate SMALLDATETIME,
		dcProvinceID TINYINT,
		MemberType TINYINT,
		LastLoginDate SMALLDATETIME,
		ConsultantDate SMALLDATETIME,
		IsLock BIT,
		JobNumber SMALLINT,--有效职位总数
		JobViewNumber SMALLINT,--职位被浏览量
		SendResumeNumber SMALLINT,--简历投递量
		SendResumeNumberHigh SMALLINT,--非开放简历投递量
		DownLoadToday SMALLINT,
		memberdate smalldatetime,
		RealName TINYINT,
		--HasLogo BIT,
		CerMemberType TINYINT,
		CerType TINYINT,
		CerDate SMALLDATETIME,
		--新增项
		ContactQuality INT,    --用户级别
		Title NVARCHAR(50),  --联系活动内容
		Label VARCHAR(10),  --标记客户
		ContactAdd SMALLDATETIME,--联系活动添加时间
		ContactID INT,     --联系活动id
		HasRemark SMALLINT, --是否有备注
		FeeCount INT,  --客户一个月内资费数
                IsLimitLogin INT
	)
	SET @SQL='
		INSERT INTO #T
		(TitleID,ID,Name,Quality,ConsultantID,RegDate,dcProvinceID,MemberType,
		LastLoginDate,ConsultantDate,IsLock,
		JobNumber,memberdate,RealName,IsLimitLogin)
		SELECT TOP 4000 ROW_NUMBER() OVER (' + @strOrder + ') AS TitleID,a.ID,a.Name,Quality,
		ConsultantID,a.RegDate,dcProvinceID,a.MemberType,LastLoginDate,
		ConsultantDate,IsLock,JobNumber, 
		memberdate,a.RealName ,a.IsLimitLogin
		FROM cpMain a WITH(NOLOCK)'

	IF @Order = 17
		SET @SQL = @SQL + ' INNER JOIN (SELECT b.cpMainId, MAX(a.Id) Id 
		FROM caFeePageViewLog a, caMain b
		WHERE a.caMainId = b.Id
		GROUP BY b.cpMainId
		) d ON a.ID=d.cpMainID '
	
	SET @SQL = @SQL + '	WHERE 1=1 '

	IF LEN(@WHERE) > 0
		SET @SQL = @SQL + @WHERE
	--print @SQL
	--insert a0 select @sql, getdate()
	EXEC(@SQL)

	UPDATE #T SET DownLoadToday = (SELECT COUNT(ID) cnt FROM caActiveLog WHERE CONVERT(VARCHAR(10),AddDate,112)=CONVERT(VARCHAR(10),GETDATE(),112) AND cpMainID=#T.ID),
		JobViewNumber = (SELECT COUNT(1) cnt FROM paJobViewLog a WITH(NOLOCK),Job b WITH(NOLOCK) WHERE b.cpMainID=#T.ID AND a.JobID=b.ID AND b.valid=1 AND a.Adddate>GETDATE()-30),
		CerMemberType = (SELECT TOP 1 MemberType FROM cpCertification WITH(NOLOCK) WHERE cpMainID = #T.ID AND CerStatus = 1 ORDER BY CerDate DESC),
		CerType = (SELECT TOP 1 CerType FROM cpCertification WITH(NOLOCK) WHERE cpMainID = #T.ID AND CerStatus = 1 ORDER BY CerDate DESC),
		CerDate = (SELECT TOP 1 CerDate FROM cpCertification WITH(NOLOCK) WHERE cpMainID = #T.ID AND CerStatus = 1 ORDER BY CerDate DESC),
		--新增项
		HasRemark = (SELECT TOP 1 ID FROM cpRemark WITH(NOLOCK) WHERE CpMainId=#T.ID),
		FeeCount=(SELECT COUNT(1) FROM caFeePageViewLog a WITH(NOLOCK) INNER JOIN caMain b WITH(NOLOCK) ON a.caMainID = b.ID INNER JOIN cpMain c WITH(NOLOCK) ON b.cpMainID = c.ID WHERE CONVERT(VARCHAR,a.AddDate,112)>=CONVERT(VARCHAR,GETDATE()-30,112) and c.id=#T.ID)
	WHERE TitleID > (@Page-1)*20 AND TitleID <= @Page*20

	--新增
	UPDATE a SET a.ContactQuality=b.Quality,a.Title=b.Title,a.Label=b.Label,a.ContactAdd=b.AddDate,a.ContactID=b.ID 
	FROM #T a, Contact b
	WHERE a.ID = b.CompanyId AND b.ID IN(
		SELECT MAX(m.ID) FROM Contact m, (
			SELECT ID, ConsultantId FROM #T WHERE TitleID > (@Page-1)*20 AND TitleID <= @Page*20
		) n WHERE m.CompanyId = n.ID AND m.ManageruserId = n.ConsultantId GROUP BY m.CompanyId
	)
	UPDATE a SET SendResumeNumber = AllNumber,
		SendResumeNumberHigh = NotOpenNumber FROM #T a
	INNER JOIN qryJobApplyMonth b ON a.ID=b.cpMainID
	WHERE TitleID > (@Page-1)*20 AND TitleID <= @Page*20

	SELECT COUNT(*) FROM #T WITH(NOLOCK)
	SELECT a.*, b.MemberType UnFinishedMemberType, b.CerType UnFinishedCerType, c.HasPassed, d.CheckResult PersonalCheckResult, e.CheckResult CompanyEmailCheckResult
	FROM #T a WITH(NOLOCK)
		LEFT JOIN cpCertification b WITH(NOLOCK) ON a.ID = b.cpMainID AND b.CerStatus IS NULL
		LEFT JOIN cpLicence c WITH(NOLOCK) ON b.ID = c.cpCertificationID
		LEFT JOIN cpPersonalAccount d WITH(NOLOCK) ON b.ID = d.cpCertificationID
		LEFT JOIN cpCompanyEmail e WITH(NOLOCK) ON b.ID = e.cpCertificationID
	WHERE TitleID > (@Page-1)*20 AND TitleID <= @Page*20
	DROP TABLE #T
END
GO
/****** Object:  StoredProcedure [dbo].[bpCustomerTrackingSelect2]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [dbo].[bpCustomerTrackingSelect2]
(
	@WHERE VARCHAR(1000),
	@ORDER TINYINT,
	@Page SMALLINT
)
AS
SET NOCOUNT ON
BEGIN
print convert(varchar(20), getdate(), 120)
	SET @WHERE = dbo.SafeSQLBack(@WHERE)
	DECLARE @SQL AS VARCHAR(2000)
	DECLARE @strOrder AS VARCHAR(1000)
	SET @strOrder = ''
	IF @ORDER = 1
		SET @strOrder = @strOrder + ' ORDER BY ConsultantDate DESC'
	ELSE IF @ORDER = 2
		SET @strOrder = @strOrder + ' ORDER BY LastLoginDate DESC'
	ELSE IF @ORDER = 3
		SET @strOrder = @strOrder + ' ORDER BY (SELECT TOP 1 CerDate FROM MainDB..cpCertification WITH(NOLOCK) WHERE cpMainID = a.ID ORDER BY CerDate DESC) DESC'
	ELSE IF @ORDER = 4
		SET @strOrder = @strOrder + ' ORDER BY RegDate DESC'
	ELSE IF @ORDER = 5
		SET @strOrder = @strOrder + ' ORDER BY JobNumber DESC'
	ELSE IF @ORDER = 6
		SET @strOrder = @strOrder + ' ORDER BY (SELECT COUNT(1) FROM CaCvQuotaLog WITH(NOLOCK) WHERE cpMainID = a.ID) DESC'
	ELSE IF @ORDER = 12
		SET @strOrder = @strOrder + ' ORDER BY (SELECT COUNT(1) FROM CaActiveLog WITH(NOLOCK) WHERE cpMainID = a.ID AND AddDate > CONVERT(VARCHAR(10), GETDATE(), 23)) DESC, LastLoginDate DESC'
	ELSE IF @ORDER = 7
		SET @strOrder = @strOrder + ' ORDER BY (SELECT TOP 1 AddDate FROM bsCpStatus WITH(NOLOCK) WHERE cpMainID = a.ID AND statusID=9 ORDER BY AddDate DESC) DESC'
	ELSE IF @ORDER = 8
		SET @strOrder = @strOrder + ' ORDER BY (Select TOP 1 VerifyDate From bsCpVerify Where cpMainID=a.ID) DESC'
	ELSE IF @ORDER = 9
		SET @strOrder = @strOrder + ' ORDER BY (SELECT TOP 1 begintime FROM contact WITH(NOLOCK) WHERE status=2 AND companyid=a.ID ORDER BY begintime DESC) DESC'
	ELSE IF @ORDER = 10
		SET @strOrder = @strOrder + ' ORDER BY (SELECT TOP 1 begintime FROM contact WITH(NOLOCK) WHERE status=2 AND companyid=a.ID ORDER BY begintime DESC)'
	ELSE IF @ORDER = 14
		SET @strOrder = @strOrder + ' ORDER BY (SELECT TOP 1 EndDate FROM caOrder WITH(NOLOCK) WHERE OrderType=8 AND BeginDate<GetDate() AND EndDate>GETDATE() AND cpMainId = a.Id AND IsDeleted = 0)'
	ELSE IF @ORDER = 15
		SET @strOrder = @strOrder + ' ORDER BY BalanceDate'
	ELSE IF @ORDER = 13
		SET @strOrder = @strOrder + ' ORDER BY Balance'
	ELSE IF @ORDER = 17
		SET @strOrder = @strOrder +  ' ORDER BY d.Id DESC'
	Else IF @ORDER = 0
		SET @strOrder = @strOrder + ' ORDER BY LastLoginDate DESC'
	ELSE IF @ORDER = 19
		SET @strOrder = @strOrder + ' ORDER BY (SELECT TOP 1 EndDate FROM caOrder WITH(NOLOCK) WHERE OrderType=8 AND BeginDate<GetDate() AND EndDate>GETDATE() AND cpMainId = a.Id AND IsDeleted = 0) DESC'
	ELSE IF @ORDER = 20
		SET @strOrder = @strOrder + ' ORDER BY BalanceDate DESC'
	Else IF @ORDER = 16
		SET @strOrder = @strOrder + ' ORDER BY MemberDate'
	Else IF @ORDER = 21
		SET @strOrder = @strOrder + ' ORDER BY MemberDate DESC'
	Else IF @ORDER = 22
		SET @strOrder = @strOrder + ' order by (select top 1  checkdate from cpimage WITH(NOLOCK) where cpmainid=a.id and imgtype=1 and HasPassed=1 ORDER BY checkdate  DESC) desc'
	Else IF @ORDER = 23
		SET @strOrder = @strOrder + ' ORDER BY (SELECT TOP 1 OpenDate FROM caOrder WITH(NOLOCK) WHERE OrderType=8 AND BeginDate<GetDate() AND EndDate>GETDATE() AND cpMainId = a.Id AND IsDeleted = 0) DESC'
	--新添加的条件
	Else IF @ORDER = 24 --按级别正序
		SET @strOrder = @strOrder + ' ORDER BY (SELECT TOP 1 Quality FROM contact WITH(NOLOCK) WHERE a.id=companyid ORDER BY AddDate DESC)'
	Else IF @ORDER = 25 --按级别倒序
		SET @strOrder = @strOrder + ' ORDER BY (SELECT TOP 1 Quality FROM contact WITH(NOLOCK) WHERE a.id=companyid ORDER BY AddDate DESC) DESC'
	Else IF @ORDER = 26 --按预约时间倒序
		SET @strOrder = @strOrder + ' ORDER BY (SELECT TOP 1 begintime FROM contact WITH(NOLOCK) WHERE a.id=companyid ORDER BY AddDate DESC) DESC'
print '2-' + convert(varchar(20), getdate(), 120)
	CREATE TABLE #T(
		TitleID BIGINT,
		ID INT,
		Name VARCHAR(100) COLLATE Chinese_PRC_CI_AS,
		HasLicence BIT,
		ziliaodate SMALLDATETIME,
		Quality TINYINT,
		ConsultantID SMALLINT,
		RegDate SMALLDATETIME,
		dcProvinceID TINYINT,
		MemberType TINYINT,
		VerifyResult TINYINT,
		IsAgent BIT,
		LastLoginDate SMALLDATETIME,
		UnlimitedDate SMALLDATETIME,
		Balance SMALLINT,
		BalanceDate SMALLDATETIME,
		IsLimitLogin TINYINT,
		RefreshDate SMALLDATETIME,
		ConsultantDate SMALLDATETIME,
		IsLock BIT,
		ResumeQuota SMALLINT,
		IsDelete BIT,
		JobNumber SMALLINT,
		VerifyMan SMALLINT,
		HasPaid BIT,
		ContactDoneDate SMALLDATETIME,
		ContactDoneMan SMALLINT,
		ContactDoneAdd SMALLDATETIME,
		ContactDoneID INT,
		ContactNotDoneDate SMALLDATETIME,
		ContactNotDoneMan SMALLINT,
		ContactNotDoneAdd SMALLDATETIME,
		ContactNotDoneID INT,
		DownLoadToday SMALLINT,
		JobViewNumber SMALLINT,
		SendResumeNumber SMALLINT,
		SendResumeNumberHigh SMALLINT,
		memberdate smalldatetime,
		RealName TINYINT,
		HasLogo BIT,
		CerMemberType TINYINT,
		CerType TINYINT,
		CerDate SMALLDATETIME,
		--新增项
		ContactQuality INT,    --用户级别
		Title NVARCHAR(50),  --联系活动内容
		Label VARCHAR(10),  --标记客户
		ContactAdd SMALLDATETIME,--联系活动添加时间
		ContactID INT,     --联系活动id
		HasRemark SMALLINT, --是否有备注
		FeeCount INT  --客户一个月内资费数
	)
	SET @SQL='
		INSERT INTO #T
		(TitleID,ID,Name,HasLicence,Quality,ConsultantID,RegDate,dcProvinceID,MemberType,VerifyResult,
		IsAgent,LastLoginDate,UnlimitedDate,Balance,BalanceDate,IsLimitLogin,RefreshDate,ConsultantDate,IsLock,
		ResumeQuota,IsDelete,JobNumber,memberdate,RealName,HasLogo)
		SELECT TOP 4000 ROW_NUMBER() OVER (' + @strOrder + ') AS TitleID,a.ID,a.Name,HasLicence,Quality,
		ConsultantID,a.RegDate,dcProvinceID,a.MemberType,VerifyResult,IsAgent,LastLoginDate,UnlimitedDate,Balance,
		BalanceDate,IsLimitLogin,RefreshDate,ConsultantDate,IsLock,ResumeQuota,a.IsDelete,JobNumber, 
		memberdate,a.RealName,a.HasLogo
		FROM cpMain a WITH(NOLOCK)'

	IF @Order = 17
		SET @SQL = @SQL + ' INNER JOIN (SELECT b.cpMainId, MAX(a.Id) Id 
		FROM caFeePageViewLog a, caMain b
		WHERE a.caMainId = b.Id
		GROUP BY b.cpMainId
		) d ON a.ID=d.cpMainID '
	
	SET @SQL = @SQL + '	WHERE 1=1 '

	IF LEN(@WHERE) > 0
		SET @SQL = @SQL + @WHERE
	print @SQL
print '3-' + convert(varchar(20), getdate(), 120)
	--insert a0 select @sql, getdate()
	EXEC(@SQL)
print '4-' + convert(varchar(20), getdate(), 120)
	UPDATE #T SET ziliaodate = (SELECT Top 1 CheckDate FROM cpLicence Where cpMainID=#T.ID ORDER BY ID DESC),
		VerifyMan = (Select TOP 1 VerifyMan From bsCpVerify Where bsCpVerify.cpMainID=#T.ID ORDER BY ID DESC),
		HasPaid = (SELECT TOP 1 ID FROM caOrder WHERE Paid>0 AND OpenDate IS NOT NULL AND cpMainID=#T.ID AND IsDeleted = 0),
		ContactDoneDate = (SELECT top 1 BeginTime FROM contact WITH(NOLOCK) WHERE companyid=#T.ID AND status=2 ORDER BY begintime DESC),
		ContactDoneMan = (SELECT top 1 ManagerUserID FROM contact WITH(NOLOCK) WHERE companyid=#T.ID AND status=2 ORDER BY begintime DESC),
		ContactDoneAdd = (SELECT top 1 AddDate FROM contact WITH(NOLOCK) WHERE companyid=#T.ID AND status=2 ORDER BY begintime DESC),
		ContactDoneID = (SELECT top 1 ID FROM contact WITH(NOLOCK) WHERE companyid=#T.ID AND status=2 ORDER BY begintime DESC),
		ContactNotDoneDate = (SELECT top 1 BeginTime FROM contact WITH(NOLOCK) WHERE companyid=#T.ID AND status=1 ORDER BY begintime DESC),
		ContactNotDoneMan = (SELECT top 1 ManagerUserID FROM contact WITH(NOLOCK) WHERE companyid=#T.ID AND status=1 ORDER BY begintime DESC),
		ContactNotDoneAdd = (SELECT top 1 AddDate FROM contact WITH(NOLOCK) WHERE companyid=#T.ID AND status=1 ORDER BY begintime DESC),
		ContactNotDoneID = (SELECT top 1 ID FROM contact WITH(NOLOCK) WHERE companyid=#T.ID AND status=1 ORDER BY begintime DESC),
		DownLoadToday = (SELECT COUNT(ID) cnt FROM caActiveLog WHERE CONVERT(VARCHAR(10),AddDate,112)=CONVERT(VARCHAR(10),GETDATE(),112) AND cpMainID=#T.ID),
		JobViewNumber = (select COUNT(1) cnt from paJobViewLog a with(nolock),Job b with(nolock) where b.cpMainID=#T.ID and a.JobID=b.ID and b.valid=1 and a.Adddate>getdate()-30),
		CerMemberType = (SELECT TOP 1 MemberType FROM cpCertification WITH(NOLOCK) WHERE cpMainID = #T.ID AND CerStatus = 1 ORDER BY CerDate DESC),
		CerType = (SELECT TOP 1 CerType FROM cpCertification WITH(NOLOCK) WHERE cpMainID = #T.ID AND CerStatus = 1 ORDER BY CerDate DESC),
		CerDate = (SELECT TOP 1 CerDate FROM cpCertification WITH(NOLOCK) WHERE cpMainID = #T.ID AND CerStatus = 1 ORDER BY CerDate DESC),
		--新增项
		ContactQuality=(SELECT TOP 1 Quality FROM contact WITH(NOLOCK) WHERE companyid=#T.ID ORDER BY AddDate DESC),
		Title=(SELECT TOP 1 Title FROM contact WITH(NOLOCK) WHERE companyid=#T.ID ORDER BY AddDate DESC),
		Label=(SELECT TOP 1 Label FROM contact WITH(NOLOCK) WHERE companyid=#T.ID ORDER BY AddDate DESC),
		ContactAdd = (SELECT TOP 1 AddDate FROM contact WITH(NOLOCK) WHERE companyid=#T.ID ORDER BY AddDate DESC),
		ContactID = (SELECT TOP 1 ID FROM contact WITH(NOLOCK) WHERE companyid=#T.ID AND status=2 ORDER BY AddDate DESC),
		HasRemark = (SELECT TOP 1 ID FROM cpRemark WITH(NOLOCK) WHERE CpMainId=#T.ID),
		FeeCount=(SELECT COUNT(1) FROM caFeePageViewLog a WITH(NOLOCK) INNER JOIN caMain b WITH(NOLOCK) ON a.caMainID = b.ID INNER JOIN cpMain c WITH(NOLOCK) ON b.cpMainID = c.ID WHERE CONVERT(VARCHAR,a.AddDate,112)>=CONVERT(VARCHAR,GETDATE()-30,112) and c.id=#T.ID)
	WHERE TitleID > (@Page-1)*20 AND TitleID <= @Page*20
print '5-' + convert(varchar(20), getdate(), 120)
	UPDATE #T SET ContactDoneMan = (SELECT top 1 a.AddMan FROM ColdContact a,Coldcustomer  b WITH(NOLOCK) WHERE b.id=a.CustomerID AND  b.CpMainID=#T.ID AND isnull(a.beginTime,'')!='' ORDER BY a.BeginTime DESC),
		ContactDoneDate= (SELECT top 1 a.AddDate FROM ColdContact a,Coldcustomer  b WITH(NOLOCK) WHERE b.id=a.CustomerID AND  b.CpMainID=#T.ID  AND isnull(a.beginTime,'')!='' ORDER BY a.BeginTime DESC), 
		ContactDoneAdd = (SELECT top 1 a.AddDate FROM ColdContact a,Coldcustomer  b WITH(NOLOCK) WHERE b.id=a.CustomerID AND  b.CpMainID=#T.ID  AND isnull(a.beginTime,'')!='' ORDER BY a.BeginTime DESC) 
	WHERE ISNULL(ContactDoneDate ,'')='' and  TitleID > (@Page-1)*20 AND TitleID <= @Page*20

	UPDATE #T SET ContactNotDoneMan = (SELECT top 1 a.AddMan FROM ColdContact a,Coldcustomer  b WITH(NOLOCK) WHERE b.id=a.CustomerID AND  b.CpMainID=#T.ID AND isnull(a.beginTime,'')='' ORDER BY a.AddDate DESC),
		ContactNotDoneDate = (SELECT top 1 a.AddDate FROM ColdContact a,Coldcustomer  b WITH(NOLOCK) WHERE b.id=a.CustomerID AND  b.CpMainID=#T.ID  AND isnull(a.beginTime,'')='' ORDER BY a.AddDate  DESC) ,
		ContactNotDoneAdd = (SELECT top 1 a.AddDate FROM ColdContact a,Coldcustomer  b WITH(NOLOCK) WHERE b.id=a.CustomerID AND  b.CpMainID=#T.ID  AND isnull(a.beginTime,'')='' ORDER BY a.AddDate  DESC) 
	WHERE ISNULL(ContactNotDoneDate ,'')=''  and  TitleID > (@Page-1)*20 AND TitleID <= @Page*20

	UPDATE a SET SendResumeNumber = AllNumber,
		SendResumeNumberHigh = NotOpenNumber FROM #T a
	INNER JOIN qryJobApplyMonth b ON a.ID=b.cpMainID
	WHERE TitleID > (@Page-1)*20 AND TitleID <= @Page*20
print '6-' + convert(varchar(20), getdate(), 120)
	SELECT COUNT(*) FROM #T WITH(NOLOCK)
	SELECT a.*, b.MemberType UnFinishedMemberType, b.CerType UnFinishedCerType, c.HasPassed, d.CheckResult PersonalCheckResult, e.CheckResult CompanyEmailCheckResult
	FROM #T a WITH(NOLOCK)
		LEFT JOIN cpCertification b WITH(NOLOCK) ON a.ID = b.cpMainID AND b.CerStatus IS NULL
		LEFT JOIN cpLicence c WITH(NOLOCK) ON b.ID = c.cpCertificationID
		LEFT JOIN cpPersonalAccount d WITH(NOLOCK) ON b.ID = d.cpCertificationID
		LEFT JOIN cpCompanyEmail e WITH(NOLOCK) ON b.ID = e.cpCertificationID
	WHERE TitleID > (@Page-1)*20 AND TitleID <= @Page*20
print '7-' + convert(varchar(20), getdate(), 120)
	DROP TABLE #T
END
GO
/****** Object:  StoredProcedure [dbo].[bpCvActivationLogByCountDateSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--bpCvActivationLogByCountDateSelect '',''
--创建人 Andy
--时间 2015-01-23
--按照条件获取个人登录间隔
CREATE PROCEDURE [dbo].[bpCvActivationLogByCountDateSelect] 
(		
	@BeginDate VARCHAR(8),  --格式20140101
	@EndDate VARCHAR(8)		--格式20140101
)
AS
BEGIN		
	SET @BeginDate = dbo.SafeSql(@BeginDate)
	SET @EndDate = dbo.SafeSql(@EndDate)
	
	DECLARE @SQL VARCHAR(1000)	
	SET @SQL = 'SELECT TOP 2000 * FROM LogDb..CvActivationLog Where 1=1 '		
	
	IF LEN(@BeginDate) > 0
		SET @SQL = @SQL + ' And CountDate >= ''' + @BeginDate + ''''		
	IF LEN(@EndDate) > 0
		SET @SQL = @SQL + ' And CountDate <= ''' + @EndDate + ''''			  
	
	--PRINT(@SQL)
	EXEC (@SQL)
END



GO
/****** Object:  StoredProcedure [dbo].[bpCvActivationLogByStatisticsSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--bpCvActivationLogByStatisticsSelect '20100101','20150101'
--创建人 Andy
--时间 2015-01-23
--按照条件统计个人登录间隔
CREATE PROCEDURE [dbo].[bpCvActivationLogByStatisticsSelect] 
(		
	@BeginDate VARCHAR(8),  --格式20140101
	@EndDate VARCHAR(8)		--格式20140101
)
AS
BEGIN		
	SET @BeginDate = dbo.SafeSql(@BeginDate)
	SET @EndDate = dbo.SafeSql(@EndDate)
	
	DECLARE @SQL VARCHAR(1000)	
	SET @SQL = 'SELECT SUM(day1) day1, SUM(day2) day2, SUM(day3) day3, SUM(day7) day7, SUM(day15) day15, SUM(day30) day30, SUM(dayOther) dayOther 
		FROM LogDb..CvActivationLog 
		Where 1 = 1 '		
	
	IF LEN(@BeginDate) > 0
		SET @SQL = @SQL + ' And CountDate >= ''' + @BeginDate + ''''		
	IF LEN(@EndDate) > 0
		SET @SQL = @SQL + ' And CountDate <= ''' + @EndDate + ''''			  
	
	--PRINT(@SQL)
	EXEC (@SQL)
END



GO
/****** Object:  StoredProcedure [dbo].[bpCvAppendixBeVerifingSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- 创建日期:2010-4-20
-- 创建人：Sean
-- 功能：显示待审核或是重新审核的附件内容
-- 应用于cvMainVerify.asp页面
-- 修改时间：2010-9-14
-- 修改人：Lucifer
-- =============================================
CREATE PROCEDURE [dbo].[bpCvAppendixBeVerifingSelect]
	@cvMainID int
AS
BEGIN
	SELECT DISTINCT
		a.ID,
        a.cvMainID,
		dcAppendixID,
        Name,
        NameEng,
        AccessDate,
        Description,
        DescriptionEng

	FROM cvAppendix a WITH(NoLock),bsCvModify b WITH(NOLOCK)
	WHERE a.cvMainID=@cvMainID
	AND a.ID=b.SubID
	AND b.Location LIKE 'c%'
	ORDER BY ID
END














GO
/****** Object:  StoredProcedure [dbo].[bpCvAppendixByIDDelete]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.12.25
--创建人：Nick
--说明：删除证书
--#####################################################
CREATE PROCEDURE [dbo].[bpCvAppendixByIDDelete]
(
	@ID INT
)
AS
BEGIN
	DELETE FROM CvAppendix WHERE ID = @ID
END 


GO
/****** Object:  StoredProcedure [dbo].[bpCvAppendixDelete]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-------===========================
-- 检查:		sean
-- 时间:		2011-6-11
-- 描述：		后台审核删除项目信息
-------===========================
CREATE PROCEDURE [dbo].[bpCvAppendixDelete]
(
	@ID INT,
	@ManagerUserID INT,
	@Type BIT		--0 中文， 1 英文
)
AS
BEGIN
	SET NOCOUNT ON;
	DECLARE @cvMainId AS INT
	DECLARE @RETURN AS VARCHAR(2)
	SELECT @cvMainId = cvMainId FROM cvAppendix WITH(NOLOCK) WHERE ID = @ID
	
	IF @cvMainId IS NULL
		GOTO ERR

	IF dbo.GetPrivi(@ManagerUserID, 29, 6) = 5
	BEGIN TRY
		BEGIN TRAN	
			IF @Type = 0
			BEGIN
				DELETE FROM bsCvModify WHERE SubID = @ID AND Location LIKE 'cc%'
				IF EXISTS(SELECT 'x' FROM cvAppendix WHERE ID = @ID AND NameEng > '')
					UPDATE cvAppendix SET Name = NULL,
							Description = NULL
					WHERE ID = @ID
				ELSE
					DELETE FROM cvAppendix WHERE ID = @ID
			END
			ELSE
			BEGIN
				DELETE FROM bsCvModify WHERE SubID = @ID AND Location LIKE 'ce%'
				IF EXISTS(SELECT 'x' FROM cvAppendix WHERE ID = @ID AND Name > '')
					UPDATE cvAppendix SET NameEng = NULL,
							DescriptionEng = NULL
					WHERE ID = @ID
				ELSE
					DELETE FROM cvAppendix WHERE ID = @ID
			END			
			EXEC @RETURN = pcCvMainByCvLevelCheck @cvMainID, 10
		COMMIT
	END TRY
	BEGIN CATCH
		ROLLBACK TRAN
		GOTO Err
	END CATCH
END
RETURN 0
Err:
	RETURN -1














GO
/****** Object:  StoredProcedure [dbo].[bpCvEducationBeVerifingSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- 创建日期:2010-4-20
-- 创建人：Sean
-- 功能：显示待审核或是重新审核的教育背景内容
-- 应用于cvMainVerify.asp页面
-- 修改时间：2010-9-14
-- 修改人：Lucifer
-- =============================================
-- [bpCvEducationBeVerifingSelect] 38
CREATE PROCEDURE [dbo].[bpCvEducationBeVerifingSelect]
	@cvMainID int
AS
BEGIN
	SELECT DISTINCT
		a.ID, 
		a.cvMainID,
		a.dcMajorID,
		GraduateCollage, 
		GraduateCollageEng, 
		Graduation, 
		dcMajorID, 
		MajorName, 
		MajorNameEng, 
		Degree, 
		EduType, 
		Details,
		DetailsEng
	FROM cvEducation a WITH(NoLock),bsCvModify b WITH(NOLOCK)
	WHERE a.cvMainID=@cvMainID
	AND a.ID=b.SubID
	AND b.Location LIKE 'd%'
	ORDER BY Degree DESC,Graduation Desc
END














GO
/****** Object:  StoredProcedure [dbo].[bpCvEducationByIDDelete]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.12.25
--创建人：Nick
--说明：删除学校经历
--#####################################################
CREATE PROCEDURE [dbo].[bpCvEducationByIDDelete]
(
	@ID INT
)
AS
BEGIN
	DELETE FROM CvEducation WHERE ID = @ID
END 

GO
/****** Object:  StoredProcedure [dbo].[bpCvExperienceBeVerifingSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- 创建日期:2010-4-20
-- 创建人：Sean
-- 功能：显示待审核或是重新审核的工作经历内容
-- 应用于cvMainVerify.asp页面
-- 修改时间：2010-9-14
-- 修改人：Lucifer
-- =============================================
CREATE PROCEDURE [dbo].[bpCvExperienceBeVerifingSelect]
	@cvMainID int
AS
BEGIN
	SELECT DISTINCT
		a.ID,
        a.cvMainID,
		a.dcJobTypeID,
        CompanyName,
        CompanyNameEng,
        dcIndustryID,
        dcCompanySizeID,
        dcJobtypeID,
        JobName,
        JobNameEng,
        BeginDate,
        EndDate,
        SubNodeNum,
        Description,
        DescriptionEng,
        dcCompanyKindID,
        WorkPlace,
        Dept,
        DeptEng,
        UpperPost,
        UpperPostEng,
        dcLeaveResonID
	FROM cvExperience a WITH(NoLock),bsCvModify b WITH(NOLOCK)
	WHERE a.cvMainID=@cvMainID
	AND a.ID=b.SubID
	AND b.Location LIKE 'e%'
	ORDER BY BeginDate DESC
END














GO
/****** Object:  StoredProcedure [dbo].[bpcvExperienceByIDDelete]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.12.25
--创建人：Nick
--说明：删除工作经历
--#####################################################
CREATE PROCEDURE [dbo].[bpcvExperienceByIDDelete]
(
	@ID INT
)
AS
BEGIN
	DELETE FROM cvExperience WHERE ID = @ID
END 


GO
/****** Object:  StoredProcedure [dbo].[bpcvImportPrevByCvMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.12.26
--创建人：Nick
--说明：根据CvMainID查询cvImportPrev
--#####################################################
CREATE PROCEDURE [dbo].[bpcvImportPrevByCvMainIDSelect]
(
	@CvMainID INT
)
AS
BEGIN
	SELECT TOP 1 b.* 
	FROM  pamain a WITH(NOLOCK),marketdb..cvImportPrev b  WITH(NOLOCK)
	WHERE b.pamainid=a.id 
	AND EntryDate IS NOT NULL 
	AND ContactResult<7 
	AND a.VerifyCount=1 
	AND cvmainid = @CvMainID
END 

GO
/****** Object:  StoredProcedure [dbo].[bpcvImportprevByEntryDateUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.09.17
--创建人：Nick
--说明：根据ID修改cvImportPrev
--#####################################################
CREATE PROCEDURE [dbo].[bpcvImportprevByEntryDateUpdate]
(
	@ContactResult INT,
	@Mobile VARCHAR(100),
	@WebsiteName VARCHAR(50),
	@WebSiteUrl VARCHAR(100),
	@ProvinceName VARCHAR(50),
	@PaMainID INT,
	@Email VARCHAR(50),
	@Password VARCHAR(50),
	@ID INT,
	@CvCount INT
)
AS
BEGIN
	IF @PaMainID > 0 AND @CvCount > 0
	BEGIN
		IF @ContactResult <> 7
		BEGIN
			INSERT INTO SmsMessageLog(SendMan,Mobile,Msg,MsgType) VALUES
			(1,@Mobile,@WebsiteName+'('+@WebSiteUrl+')咱'+@ProvinceName+'自己的招聘网站，免费为您推荐工作。用户名'+@Email+'，密码'+@Password,118)

		END
		UPDATE paMain SET Mobile = @Mobile WHERE ID = @PaMainID
		UPDATE marketdb..cvImportprev SET EntryDate=GETDATE(),paMainId=@PaMainID WHERE ID = @ID

	END
	IF @PaMainID = 0
	BEGIN
		DELETE FROM resume_xinxi WHERE username = @Email AND addman>=160 AND addman<=180
	END
END

GO
/****** Object:  StoredProcedure [dbo].[bpCvLanguageBeVerifingSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- 创建日期:2010-4-20
-- 创建人：Sean
-- 功能：显示待审核或是重新审核的语言能力内容
-- 应用于cvMainVerify.asp页面
-- 修改时间：2010-9-14
-- 修改人：Lucifer
-- =============================================
CREATE PROCEDURE [dbo].[bpCvLanguageBeVerifingSelect]
	@cvMainID int
AS
BEGIN
	SELECT DISTINCT
		a.ID,
        a.cvMainID,
        LanguageType,
        Mastery,
        ReadWrite,
        Spoken,
        Score,
        ScoreEng
	FROM cvLanguage a WITH(NoLock),bsCvModify b WITH(NOLOCK)
	WHERE a.cvMainID=@cvMainID
	AND a.ID=b.SubID
	AND b.Location LIKE 'h%'
	ORDER BY ID
END














GO
/****** Object:  StoredProcedure [dbo].[bpCvMainBatchUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----------------
--创建日期：2010-9-26
--创建人：lambo
--功能说明：批量执行sql语句
--用于后台个人用户管理模块个人修改页面内的简历修改
-----------------
CREATE PROCEDURE [dbo].[bpCvMainBatchUpdate]
(
	@SQL NVARCHAR(MAX)
)
AS
BEGIN TRAN
	SET @SQL = dbo.SafeSql(@SQL)
	BEGIN TRY
		EXEC(@SQL)
	END TRY
	BEGIN CATCH	
		GOTO err
	END CATCH
COMMIT TRAN
RETURN 1
err:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END














GO
/****** Object:  StoredProcedure [dbo].[bpCvMainByBeVerifingpaMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[bpCvMainByBeVerifingpaMainIDSelect]
(
	@paMainID INT
)
AS
BEGIN
	SELECT *,(SELECT TOP 1 ID FROM bsCvVerify WHERE paMainID=@paMainID ORDER BY ID DESC) AS bsCvVerifyID
	FROM cvMain WITH(NOLOCK)
	WHERE ID IN(
		SELECT cvMainID
		FROM bscvModify WITH (NOLOCK) WHERE paMainID=@paMainID AND cvMainID>0
	)
END














GO
/****** Object:  StoredProcedure [dbo].[bpCvMainByBeVerifingSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- 创建日期:2010-4-16
-- 创建人：Sean
-- 功能：显示待审核的个人用户列表
-- 应用于cvMainVerifyListOnWait.asp页面
-- 修改时间：2010-9-14
-- 修改人：Lucifer
-- =============================================
--[bpCvMainByBeVerifingSelect] 0,1,''
CREATE PROCEDURE [dbo].[bpCvMainByBeVerifingSelect]
(
	@SubNo TINYINT,	--默认值：0
	@MaxNo TINYINT,	--默认值：1
	@WHERE VARCHAR(1000)
)
AS
--INSERT INTO procLog SELECT 'bpCvMainByBeVerifingSelect', '', GETDATE()
BEGIN TRY
	IF @MaxNo = 0
		BEGIN
			SET @MaxNo=1
			SET @SubNo=0
		END
	IF @SubNo >= @MaxNo
		SET @SubNo = 0
	
	CREATE TABLE #Verify(
		ID INT IDENTITY(1,1) NOT NULL,
		paMainID INT NOT NULL,
		cvMainID INT NULL,
		paMainName VARCHAR(12) COLLATE Chinese_PRC_CI_AS NOT NULL,
		LastModifyDate SMALLDATETIME NOT NULL,
		RegisterMode TINYINT NOT NULL,
		RegisterType TINYINT NULL,
		VerifyResult TINYINT NULL,		
		bsCvVerifyID INT NULL,
		 CONSTRAINT PK_#Verify PRIMARY KEY CLUSTERED 
		 (
			ID ASC
		 )WITH (PAD_INDEX  = OFF, IGNORE_DUP_KEY = OFF)
	)
	INSERT INTO #Verify(paMainID,cvMainID ,paMainName,LastModifyDate,RegisterMode,RegisterType)
		SELECT a.paMainID,a.cvMainID,IsNULL(b.Name,''),Max(a.AddDate),b.RegisterMode,b.RegisterType
        FROM bsCvModify a WITH(NOLOCK),paMain b WITH(NOLOCK)
		WHERE a.paMainID=b.ID AND a.VerifyInfo IS NULL AND a.paMainID % @MaxNo = @SubNo 
        AND paMainID NOT IN(SELECT cvMainID FROM bsCvReview WITH(NOLOCK))
		AND ISNULL(cvMainID, 0) NOT IN(SELECT cvMainID FROM bsCvReview WITH(NOLOCK))
		--AND b.Registermode=1
		GROUP BY a.paMainID,a.cvMainID,b.Name,b.RegisterMode,b.RegisterType

	UPDATE #Verify SET bsCvVerifyID = (
		SELECT TOP 1 ID FROM bsCvVerify WITH(NOLOCK)
		WHERE #Verify.cvMainID=bsCvVerify.cvMainID
		ORDER BY ID DESC
	),VerifyResult = (
		SELECT TOP 1 VerifyResult FROM bsCvVerify WITH(NOLOCK)
		WHERE #Verify.cvMainID=bsCvVerify.cvMainID
		ORDER BY ID DESC
	)
	DECLARE @SQL AS VARCHAR(2000)
	SET @Where = dbo.SafeSql(@Where)
	SET @SQL = 'SELECT *'
	SET @SQL = @sql + ' FROM #Verify WITH(NOLOCK)'
	SET @SQL = @sql + '	WHERE LastModifyDate < DATEADD(MI, -15, GETDATE())'
	SET @SQL = @sql + @Where
	SET @SQL = @sql + '	ORDER BY LastModifyDate ASC'
	EXEC(@SQL)
	DROP TABLE #Verify
END TRY
BEGIN CATCH
	DROP TABLE #Verify
END CATCH

GO
/****** Object:  StoredProcedure [dbo].[bpCvMainByBeVerifingSelectNew]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- 创建日期:2010-4-16
-- 创建人：Sean
-- 功能：显示待审核的个人用户列表
-- 应用于cvMainVerifyListOnWait.asp页面
-- 修改时间：2010-9-14
-- 修改人：Lucifer
-- 修改：harry 2016-2-16
-- 修改显示手机号
-- =============================================
--[bpCvMainByBeVerifingSelect] 0,1,''
CREATE PROCEDURE [dbo].[bpCvMainByBeVerifingSelectNew]
(
	@SubNo TINYINT,	--默认值：0
	@MaxNo TINYINT,	--默认值：1
	@WHERE VARCHAR(1000)
)
AS
SET NOCOUNT ON
BEGIN
	IF @MaxNo = 0
	BEGIN
		SET @MaxNo=1
		SET @SubNo=0
	END
	IF @SubNo = @MaxNo
		SET @SubNo = 0
	
	CREATE TABLE #V2013(
		ID INT IDENTITY(1,1) NOT NULL,
		paMainID INT NOT NULL,
		cvMainID INT NULL,
		paMainName VARCHAR(12) COLLATE Chinese_PRC_CI_AS NOT NULL,
		Gender BIT,
		NameEng VARCHAR(50),
		OnlineContact TINYINT,
		OnlineContactNo VARCHAR(100),
		Mobile CHAR(13),
		MobileCount INT NOT NULL,
		HomePage VARCHAR(200),
		LastModifyDate SMALLDATETIME NOT NULL,
		RegisterMode TINYINT NOT NULL,
		RegisterType TINYINT NULL,
		VerifyResult TINYINT NULL,	
		bsCvVerifyID INT NULL,
		 CONSTRAINT PK_#V2013 PRIMARY KEY CLUSTERED 
		 (
			ID ASC
		 )WITH (PAD_INDEX  = OFF, IGNORE_DUP_KEY = OFF)
	)
	INSERT INTO #V2013(paMainID,cvMainID ,paMainName,Gender,NameEng,OnlineContact,OnlineContactNo,HomePage,LastModifyDate,RegisterMode,RegisterType,Mobile, MobileCount)
		SELECT a.paMainID,a.cvMainID,IsNULL(b.Name,''),Gender,NameEng,OnlineContact,OnlineContactNo,HomePage,Max(a.AddDate),b.RegisterMode,b.RegisterType,b.Mobile,(SELECT count(1) FROM pamain WITH(NOLOCK) WHERE mobile=b.mobile) 
        FROM bsCvModify a WITH(NOLOCK),paMain b WITH(NOLOCK)
		WHERE a.paMainID=b.ID AND a.VerifyInfo IS NULL AND a.paMainID % @MaxNo = @SubNo 
        AND paMainID NOT IN(SELECT cvMainID FROM bsCvReview WITH(NOLOCK))
		AND ISNULL(cvMainID, 0) NOT IN(SELECT cvMainID FROM bsCvReview WITH(NOLOCK))
		--AND b.Registermode=1
		GROUP BY a.paMainID,a.cvMainID,b.Name,b.RegisterMode,b.RegisterType,b.Mobile,Gender,NameEng,OnlineContact,OnlineContactNo,HomePage
 
	UPDATE #V2013 SET bsCvVerifyID = (
		SELECT TOP 1 ID FROM bsCvVerify WITH(NOLOCK)
		WHERE #V2013.cvMainID=bsCvVerify.cvMainID
		ORDER BY ID DESC
	),VerifyResult = (
		SELECT TOP 1 VerifyResult FROM bsCvVerify WITH(NOLOCK)
		WHERE #V2013.cvMainID=bsCvVerify.cvMainID
		ORDER BY ID DESC
	)
	DECLARE @SQL AS VARCHAR(2000)
	SET @Where = dbo.SafeSql(@Where)
	SET @SQL = 'SELECT *' +
		' FROM #V2013 WITH(NOLOCK)' +
		' WHERE LastModifyDate < DATEADD(MI, -15, GETDATE())' +
		@Where +
		' ORDER BY LastModifyDate ASC'
	EXEC(@SQL)
	DROP TABLE #V2013
END
GO
/****** Object:  StoredProcedure [dbo].[bpCvMainBybsCvVerifyIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--获取最近审核 或审核不通过的简历
--nick 20141230
CREATE PROCEDURE [dbo].[bpCvMainBybsCvVerifyIDSelect]
(
	@WHERE VARCHAR(1000)
)
AS
BEGIN TRY
	DECLARE @SQL AS VARCHAR(2000)
	SET @SQL = 'SELECT cvMainID,b.ID paMainID,b.Name,a.ID as bsCvVerifyID,b.RegisterMode,a.VerifyResult,VerifyDate, a.VerifyMan'
	SET @SQL = @sql + ' 	FROM bsCvVerify a WITH(NOLOCK),paMain b WITH(NOLOCK),cvMain c WITH(NOLOCK)'
	SET @SQL = @sql + ' 	WHERE c.paMainID=b.ID AND a.cvMainID=c.ID '
	SET @SQL = @sql + @Where
	SET @SQL = @sql + ' ORDER BY VerifyDate DESC,a.ID DESC'

	EXEC(@SQL)
END TRY
BEGIN CATCH
	
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[bpCvMainByHasVerifiedSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[bpCvMainByHasVerifiedSelect]
(
	@WHERE VARCHAR(1000)
)
AS
BEGIN TRY
	DECLARE @SQL AS VARCHAR(2000)
	SET @Where = dbo.SafeSql(@Where)
	SET @SQL = 'SELECT cvMainID,b.ID paMainID,b.Name,a.ID as bsCvVerifyID,b.RegisterMode,b.RegisterType,a.VerifyResult,VerifyDate, a.VerifyMan' +
		' FROM bsCvVerify a WITH(NOLOCK),paMain b WITH(NOLOCK),cvMain c WITH(NOLOCK)' +
		' WHERE c.paMainID=b.ID AND a.cvMainID=c.ID AND a.VerifyResult<>8 ' +
		@Where +
		' ORDER BY VerifyDate DESC,a.ID DESC'
	EXEC(@SQL)
END TRY
BEGIN CATCH
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[bpCvMainByProblemSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
---------------------------
---创建人：Sean
---创建时间：2010-4-10
---修改人：Lucifer
---修改时间：2010-9-14
---------------------------
CREATE PROCEDURE [dbo].[bpCvMainByProblemSelect]
(
	@WHERE VARCHAR(1000)
)
AS
BEGIN TRY
	DECLARE @SQL AS VARCHAR(2000)
	SET @Where = dbo.SafeSql(@Where)
	SET @SQL = 'SELECT a.*,c.Name,b.paMainID FROM bsCvReview a WITH(NOLOCK),cvMain b WITH(NOLOCK),paMain c WITH(NOLOCK)' +
		' WHERE a.cvMainID=b.ID AND b.paMainID=c.ID' + @Where
	EXEC(@SQL)
END TRY
BEGIN CATCH	
END CATCH




GO
/****** Object:  StoredProcedure [dbo].[bpCvMainBySecondIdForHexSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[bpCvMainBySecondIdForHexSelect]
(
	@SecondID VARCHAR(10),
	@cpMainId INT
)
AS
BEGIN
	SELECT (SELECT Id FROM cvMain WITH(NOLOCK) WHERE SecondId = @SecondId) cvMainId,
		(SELECT paMainId FROM cvMain WITH(NOLOCK) WHERE SecondId = @SecondId) paMainId,
		(SELECT RegisterIp FROM cpMain WITH(NOLOCK) WHERE Id = @CpMainId) RegisterIp
END






GO
/****** Object:  StoredProcedure [dbo].[bpCvMainDelete]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-----------------
--创建日期：2010-9-25
--创建人：lambo
--功能说明：根据编号删除一份简历，同时删除该简历的其它关联表的相关数据
--用于后台个人搜索页面
-----------------
CREATE PROCEDURE [dbo].[bpCvMainDelete]
	@cvMainID INT
AS
BEGIN TRAN
	BEGIN TRY
		DELETE FROM cvMain WHERE ID = @cvMainID
	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH
COMMIT TRAN
RETURN 1
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END














GO
/****** Object:  StoredProcedure [dbo].[bpcvMainSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----------------
--创建日期：2010-9-14
--创建人：lambo
--功能说明：根据条件查询简历
--用于个人用户管理-->简历查询
-----------------
CREATE PROCEDURE [dbo].[bpcvMainSelect]
(
	@WHERE VARCHAR(1000),
	@Order TINYINT
)
AS
SET NOCOUNT ON
BEGIN
	DECLARE @SQL AS VARCHAR(2000)
	SET @Where = dbo.SafeSql(@Where)
	SET @SQL = 'SELECT TOP 200 a.ID,a.dcMajorID,a.isNameHidden,a.Degree,a.RelatedWorkYears,a.EmployType,a.attachMent,a.valid,a.dcSalaryID,a.RefreshDate,a.IsNegotiable,a.Speciality,a.RefreshDate,ISNULL(a.JobName, ''应届毕业生'') JobName,'
	SET @SQL = @SQL + 'j.Gender,j.HasPhoto,j.BirthDay,j.LivePlace,j.lastLoginDate,j.AccountPlace,j.name,(SELECT TOP 1 graduation FROM cvEducation WITH (NOLOCK) WHERE cvMainID = a.ID ORDER BY graduation DESC) graduation,k.FullName '
	SET @SQL = @SQL + 'FROM cvmain a WITH(NOLOCK) ' 
	SET @SQL = @SQL + 'INNER JOIN paMain j WITH(NOLOCK) ON a.paMainID=j.ID '
	SET @SQL = @SQL + 'INNER JOIN dcRegion k WITH(NOLOCK) ON k.ID=j.LivePlace '
	IF CHARINDEX('b.', @Where) >0 
		SET @SQL = @SQL + 'INNER JOIN cvEducation b WITH(NOLOCK) ON a.ID=b.cvMainID '
	IF CHARINDEX('c.', @Where) >0 
		SET @SQL = @SQL + 'INNER JOIN cvExperience c WITH(NOLOCK) ON a.ID=c.cvMainID '
	IF CHARINDEX('d.', @Where) >0 
		SET @SQL = @SQL + 'INNER JOIN cvLanguage d WITH(NOLOCK) ON a.ID=d.cvMainID '
	IF CHARINDEX('e.', @Where) >0 
		SET @SQL = @SQL + 'INNER JOIN cvTraining e WITH(NOLOCK) ON a.ID=e.cvMainID '
	IF CHARINDEX('f.', @Where) >0 
		SET @SQL = @SQL + 'INNER JOIN cvProject f WITH(NOLOCK) ON a.ID=f.cvMainID '
	IF CHARINDEX('g.', @Where) >0 
		SET @SQL = @SQL + 'INNER JOIN cvJobType g WITH(NOLOCK) ON a.ID=g.cvMainID '
	IF CHARINDEX('h.', @Where) >0 
		SET @SQL = @SQL + 'INNER JOIN cvJobPlace h WITH(NOLOCK) ON a.ID=h.cvMainID '
	IF CHARINDEX('i.', @Where) >0 
		SET @SQL = @SQL + 'INNER JOIN cvIndustry i WITH(NOLOCK) ON a.ID=i.cvMainID '
	SET @SQL = @SQL + 'WHERE a.valid>0 '
	SET @SQL = @SQL + '  AND ' + @Where
	SET @SQL = @SQL + ' ORDER BY'
	IF @Order=1 
		SET @SQL = @SQL + ' j.LastLoginDate DESC'
	ELSE IF @Order = 2
		SET @SQL = @SQL + ' a.RefreshDate DESC'
	ELSE 
		SET @SQL = @SQL + ' a.RefreshDate DESC'
	--print @sql
	EXEC(@SQL)
END

GO
/****** Object:  StoredProcedure [dbo].[bpCvProjectBeVerifingSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- 创建日期:2010-4-20
-- 创建人：Sean
-- 功能：显示待审核或是重新审核的项目经历内容
-- 应用于cvMainVerify.asp页面
-- 修改时间：2010-9-14
-- 修改人：Lucifer
-- =============================================
CREATE PROCEDURE [dbo].[bpCvProjectBeVerifingSelect]
(
	@cvMainID int
)
AS
BEGIN
	SELECT DISTINCT
        a.ID,
        a.cvMainID,
        Name,
        NameEng,
        StartDate,
        EndDate,
        Description,
        DescriptionEng,
        Responsibilities,
        ResponsibilitiesEng
	FROM cvProject a WITH(NoLock),bsCvModify b WITH(NOLOCK)
	WHERE a.cvMainID=@cvMainID
	AND a.ID=b.SubID
	AND b.Location LIKE 'f%'
	ORDER BY ID
END














GO
/****** Object:  StoredProcedure [dbo].[bpcvProjectByIDDelete]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.12.25
--创建人：Nick
--说明：删除项目经历
--#####################################################
CREATE PROCEDURE [dbo].[bpcvProjectByIDDelete]
(
	@ID INT
)
AS
BEGIN
	DELETE FROM cvProject WHERE ID = @ID
END 

GO
/****** Object:  StoredProcedure [dbo].[bpCvProjectDelete]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-------===========================
-- 检查:		sean
-- 时间:		2011-6-11
-- 描述：		后台审核删除项目信息
-------===========================
CREATE PROCEDURE [dbo].[bpCvProjectDelete]
(
	@ID INT,
	@ManagerUserID INT,
	@Type BIT		--0 中文， 1 英文
)
AS
BEGIN
	SET NOCOUNT ON;
	DECLARE @cvMainId AS INT
	DECLARE @RETURN AS VARCHAR(2)
	SELECT @cvMainId = cvMainId FROM cvProject WITH(NOLOCK) WHERE ID = @ID
	
	IF @cvMainId IS NULL
		GOTO ERR

	IF dbo.GetPrivi(@ManagerUserID, 29, 6) = 5
	BEGIN TRY
		BEGIN TRAN	
			IF @Type = 0
			BEGIN
				DELETE FROM bsCvModify WHERE SubID = @ID AND Location LIKE 'fc%'
				IF EXISTS(SELECT 'x' FROM cvProject WHERE ID = @ID AND NameEng > '')
					UPDATE cvProject SET Name = NULL,
							Description = NULL,
							Responsibilities = NULL
					WHERE ID = @ID
				ELSE
					DELETE FROM cvProject WHERE ID = @ID
			END
			ELSE
			BEGIN
				DELETE FROM bsCvModify WHERE SubID = @ID AND Location LIKE 'fe%'
				IF EXISTS(SELECT 'x' FROM cvProject WHERE ID = @ID AND Name > '')
					UPDATE cvProject SET NameEng = NULL,
							DescriptionEng = NULL,
							ResponsibilitiesEng = NULL
					WHERE ID = @ID
				ELSE
					DELETE FROM cvProject WHERE ID = @ID
			END
			
			EXEC @RETURN = pcCvMainByCvLevelCheck @cvMainID, 9
		COMMIT
	END TRY
	BEGIN CATCH
		ROLLBACK TRAN
		GOTO Err
	END CATCH
END
RETURN 0
Err:
	RETURN -1














GO
/****** Object:  StoredProcedure [dbo].[bpcvrRecommendByCvMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.12.26
--创建人：Nick
--说明：根据cvmainid修改cvrRecommend
--#####################################################
CREATE PROCEDURE [dbo].[bpcvrRecommendByCvMainIDSelect]
(
	@CvMainID INT
)
AS
BEGIN
	SELECT TOP 1 a.ID,b.name,b.mobile,b.dcSubSiteID 
	FROM marketdb..cvrRecommend  a WITH(NOLOCK),pamain b WITH(NOLOCK) 
	WHERE a.UserID = b.id 
	AND b.id=(
		SELECT pamainid 
		FROM cvmain WITH(NOLOCK) 
		WHERE id = @CvMainID 
		AND (cvlevel LIKE '111111%' OR cvleveleng LIKE '111111%' )
	) AND a.hasValid =0 
	AND a.DeductReason Is NUll 
	ORDER BY a.ID
END 

GO
/****** Object:  StoredProcedure [dbo].[bpcvrRecommendByIDUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.12.26
--创建人：Nick
--说明：根据ID修改cvrRecommend
--#####################################################
CREATE PROCEDURE [dbo].[bpcvrRecommendByIDUpdate]
(
	@ID INT,
	@Valid INT
)
AS
BEGIN
	IF @Valid = 1
	BEGIN
		UPDATE marketdb..cvrRecommend SET hasValid=1 ,ValidTime=GETDATE() WHERE ID = @ID
	END
	ELSE
	BEGIN
		UPDATE marketdb..cvrRecommend SET DeductReason='手机号重复' WHERE ID = @ID 
	END
END 

GO
/****** Object:  StoredProcedure [dbo].[bpcvrRecommendByMobileSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.12.26
--创建人：Nick
--说明：根据mobile修改cvrRecommend
--#####################################################
CREATE PROCEDURE [dbo].[bpcvrRecommendByMobileSelect]
(
	@Mobile VARCHAR(50)
)
AS
BEGIN
	SELECT 'x' FROM marketdb..cvrRecommend WITH(NOLOCK) WHERE mobile = @Mobile AND hasValid=1
END 

GO
/****** Object:  StoredProcedure [dbo].[bpCvTractByChannelSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[bpCvTractByChannelSelect]
(
	@BEGINDATE DATETIME
)
AS
BEGIN
	BEGIN TRY
		CREATE TABLE #T(
			cntAll BIGINT,
			cntEmail INT,
			cntSms INT,
			cntRecommend INT,
			cntAllLogin INT,
			cntEmailLogin INT,
			cntSmsLogin INT,
			cntRecommendLogin INT,
			cntAllView INT,
			cntEmailView INT,
			cntSmsView INT,
			cntRecommendView INT,
			cntAllPosition INT,
			cntEmailPosition INT,
			cntSmsPosition INT,
			cntRecommendPosition INT,
			cntAllInterview INT,
			cntEmailInterview INT,
			cntSmsInterview INT,
			cntRecommendInterview INT,
			cntAllInvited INT,
			cntEmailInvited INT,
			cntSmsInvited INT,
			cntRecommendInvited INT,
			cntAllAccord  INT,
			cntEmailAccord INT,
			cntSmsAccord INT,
			cntRecommendAccord INT,
		)
		INSERT INTO #T VALUES(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)
		CREATE TABLE #TEmail(ID INT)
		CREATE TABLE #TSms(ID INT)
		CREATE TABLE #TRecommend(ID INT)
		INSERT INTO #TEmail 
			SELECT ID FROM paMain WITH(NOLOCK)
				WHERE (RegisterMode=11 OR RegisterType=102)
				AND AddDate>@BEGINDATE
		INSERT INTO #TSms
			SELECT ID FROM paMain WITH(NOLOCK)
				WHERE Mobile in(SELECT MobileNo FROM bsMobileSpread WITH(NOLOCK) WHERE AddDate>@BEGINDATE)
				AND AddDate>@BEGINDATE
		INSERT INTO #TRecommend 
			SELECT ID FROM paMain WITH(NOLOCK)
				WHERE id in(SELECT paMainID FROM marketdb..RmInvitationCode WITH(NOLOCK) WHERE AddDate>@BEGINDATE)
				AND AddDate>@BEGINDATE
		UPDATE #T
			SET cntAll=(SELECT COUNT(*) FROM paMain WITH(NOLOCK) WHERE AddDate>@BEGINDATE),
			cntEmail=(SELECT COUNT(*) FROM #TEmail),
			cntSms=(SELECT COUNT(*) FROM #TSms),
			cntRecommend=(SELECT COUNT(*) FROM #TRecommend),
			cntAllLogin=(SELECT COUNT(*) FROM paLoginLog WITH(NOLOCK) WHERE AddDate>@BEGINDATE),
			cntEmailLogin=(SELECT COUNT(*) FROM paLoginLog WITH(NOLOCK) WHERE paMainID IN(SELECT ID FROM #TEmail)),
			cntSmsLogin=(SELECT COUNT(*) FROM paLoginLog WITH(NOLOCK) WHERE paMainID IN(SELECT ID FROM #TSms)),
			cntRecommendLogin=(SELECT COUNT(*) FROM paLoginLog WITH(NOLOCK) WHERE paMainID IN(SELECT ID FROM #TRecommend)),
			cntAllView =(SELECT COUNT(*) FROM caCvviewlog WITH(NOLOCK) WHERE AddDate>@BEGINDATE),
			cntEmailView =(SELECT COUNT(*) FROM caCvviewlog WITH(NOLOCK) WHERE CvMainID IN(SELECT id FROM cvMain WITH(NOLOCK) WHERE paMainid IN(SELECT ID FROM #TEmail)) AND AddDate>@BEGINDATE),
			cntSmsView =(SELECT COUNT(*) FROM caCvviewlog WITH(NOLOCK) WHERE CvMainID IN(SELECT id FROM cvMain WITH(NOLOCK) WHERE paMainid IN(SELECT ID FROM #TSms)) AND AddDate>@BEGINDATE),
			cntRecommendView =(SELECT COUNT(*) FROM caCvviewlog WITH(NOLOCK) WHERE CvMainID IN(SELECT id FROM cvMain WITH(NOLOCK) WHERE paMainid IN(SELECT ID FROM #TRecommend)) AND AddDate>@BEGINDATE),
			cntAllPosition =(SELECT COUNT(*) FROM exjobapply WITH(NOLOCK) WHERE AddDate>@BEGINDATE),
			cntEmailPosition =(SELECT COUNT(*) FROM exjobapply WITH(NOLOCK) WHERE CvMainID IN(SELECT id FROM cvMain WITH(NOLOCK) WHERE paMainid IN(SELECT ID FROM #TEmail)) AND AddDate>@BEGINDATE),
			cntSmsPosition =(SELECT COUNT(*) FROM exjobapply WITH(NOLOCK) WHERE CvMainID IN(SELECT id FROM cvMain WITH(NOLOCK) WHERE paMainid IN(SELECT ID FROM #TSms)) AND AddDate>@BEGINDATE),
			cntRecommendPosition =(SELECT COUNT(*) FROM exjobapply WITH(NOLOCK) WHERE CvMainID IN(SELECT id FROM cvMain WITH(NOLOCK) WHERE paMainid IN(SELECT ID FROM #TRecommend)) AND AddDate>@BEGINDATE),
			cntAllInterview =(SELECT COUNT(*) FROM exinterview WITH(NOLOCK) WHERE AddDate>@BEGINDATE),
			cntEmailInterview =(SELECT COUNT(*) FROM exinterview WITH(NOLOCK) WHERE CvMainID IN(SELECT id FROM cvMain WITH(NOLOCK) WHERE paMainid IN(SELECT ID FROM #TEmail)) AND AddDate>@BEGINDATE),
			cntSmsInterview =(SELECT COUNT(*) FROM exinterview WITH(NOLOCK) WHERE CvMainID IN(SELECT id FROM cvMain WITH(NOLOCK) WHERE paMainid IN(SELECT ID FROM #TSms)) AND AddDate>@BEGINDATE),
			cntRecommendInterview =(SELECT COUNT(*) FROM exinterview WITH(NOLOCK) WHERE CvMainID IN(SELECT id FROM cvMain WITH(NOLOCK) WHERE paMainid IN(SELECT ID FROM #TRecommend)) AND AddDate>@BEGINDATE),
			cntAllInvited =(SELECT COUNT(*) FROM caCvIntention WITH(NOLOCK) WHERE AddDate>@BEGINDATE),
			cntEmailInvited =(SELECT COUNT(*) FROM caCvIntention WITH(NOLOCK) WHERE CvMainID IN(SELECT id FROM cvMain WITH(NOLOCK) WHERE paMainid IN(SELECT ID FROM #TEmail)) AND AddDate>@BEGINDATE),
			cntSmsInvited =(SELECT COUNT(*) FROM caCvIntention WITH(NOLOCK) WHERE CvMainID IN(SELECT id FROM cvMain WITH(NOLOCK) WHERE paMainid IN(SELECT ID FROM #TSms)) AND AddDate>@BEGINDATE),
			cntRecommendInvited =(SELECT COUNT(*) FROM caCvIntention WITH(NOLOCK) WHERE CvMainID IN(SELECT id FROM cvMain WITH(NOLOCK) WHERE paMainid IN(SELECT ID FROM #TRecommend)) AND AddDate>@BEGINDATE),
			cntAllAccord  =(SELECT COUNT(*) FROM exjobapply WITH(NOLOCK) WHERE Reply=1 AND AddDate>@BEGINDATE),
			cntEmailAccord =(SELECT COUNT(*) FROM exjobapply WITH(NOLOCK) WHERE Reply=1 AND CvMainID IN(SELECT id FROM cvMain WITH(NOLOCK) WHERE paMainid IN(SELECT ID FROM #TEmail)) AND AddDate>@BEGINDATE),
			cntSmsAccord =(SELECT COUNT(*) FROM exjobapply WITH(NOLOCK) WHERE Reply=1 AND CvMainID IN(SELECT id FROM cvMain WITH(NOLOCK) WHERE paMainid IN(SELECT ID FROM #TSms)) AND AddDate>@BEGINDATE),
			cntRecommendAccord =(SELECT COUNT(*) FROM exjobapply WITH(NOLOCK) WHERE Reply=1 AND CvMainID IN(SELECT id FROM cvMain WITH(NOLOCK) WHERE paMainid IN(SELECT ID FROM #TRecommend)) AND AddDate>@BEGINDATE)
		SELECT * FROM #T
		DROP TABLE #TEmail
		DROP TABLE #TSms
		DROP TABLE #TRecommend	
		DROP TABLE #T
	END TRY
	BEGIN CATCH
		DROP TABLE #TEmail
		DROP TABLE #TSms
		DROP TABLE #TRecommend
		DROP TABLE #T
	END CATCH
END

GO
/****** Object:  StoredProcedure [dbo].[bpCvTrainingBeVerifingSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- 创建日期:2010-4-20
-- 创建人：Sean
-- 功能：显示待审核或是重新审核的培训经历内容
-- 应用于cvMainVerify.asp页面
-- 修改时间：2010-9-14
-- 修改人：Lucifer
-- =============================================
CREATE PROCEDURE [dbo].[bpCvTrainingBeVerifingSelect]
	@cvMainID int
AS
BEGIN
	SELECT DISTINCT
        a.ID,
        a.cvMainID,
        StartDate,
        TimeLength,
        TimeUnit,
        Institution,
        InstitutionEng,
        Course,
        CourseEng,
        City,
        CityEng,
        Certificate,
        CertificateEng,
        Details,
        DetailsEng
	FROM cvTraining a WITH(NoLock),bsCvModify b WITH(NOLOCK)
	WHERE a.cvMainID=@cvMainID
	AND a.ID=b.SubID
	AND b.Location LIKE 'g%'
	ORDER BY ID
END














GO
/****** Object:  StoredProcedure [dbo].[bpCvTrainingByIDDelete]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.12.25
--创建人：Nick
--说明：删除培训经历
--#####################################################
CREATE PROCEDURE [dbo].[bpCvTrainingByIDDelete]
(
	@ID INT
)
AS
BEGIN
	DELETE FROM CvTraining WHERE ID = @ID
END 


GO
/****** Object:  StoredProcedure [dbo].[bpCvTrainingDelete]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-------===========================
-- 检查:		sean
-- 时间:		2011-6-11
-- 描述：		后台审核删除配村信息
-------===========================
CREATE PROCEDURE [dbo].[bpCvTrainingDelete]
(
	@ID INT,
	@ManagerUserID INT,
	@Type BIT		--0 中文， 1 英文
)
AS
BEGIN
	SET NOCOUNT ON;
	DECLARE @cvMainId AS INT
	DECLARE @RETURN AS VARCHAR(2)
	SELECT @cvMainId = cvMainId FROM CvTraining WITH(NOLOCK) WHERE ID = @ID
	
	IF @cvMainId IS NULL
		GOTO ERR

	IF dbo.GetPrivi(@ManagerUserID, 29, 6) = 5
	BEGIN TRY
		BEGIN TRAN	
			IF @Type = 0
			BEGIN
				DELETE FROM bsCvModify WHERE SubID = @ID AND Location LIKE 'gc%'
				IF EXISTS(SELECT 'x' FROM CvTraining WHERE ID = @ID AND CourseEng > '')
					UPDATE CvTraining 
					SET	Institution = NULL,
						Course = NULL,
						City = NULL,
						Certificate = NULL,
						Details = NULL
					WHERE ID = @ID
				ELSE
					DELETE FROM CvTraining WHERE ID = @ID
			END
			ELSE
			BEGIN
				DELETE FROM bsCvModify WHERE SubID = @ID AND Location LIKE 'ge%'
				IF EXISTS(SELECT 'x' FROM CvTraining WHERE ID = @ID AND Course > '')
					UPDATE CvTraining
					SET InstitutionEng = NULL,
						CourseEng = NULL,
						CityEng = NULL,
						CertificateEng = NULL,
						DetailsEng = NULL
					WHERE ID = @ID
				ELSE
					DELETE FROM CvTraining WHERE ID = @ID
			END
			
			EXEC @RETURN = pcCvMainByCvLevelCheck @cvMainID, 8
		COMMIT
	END TRY
	BEGIN CATCH
		ROLLBACK TRAN
		GOTO Err
	END CATCH
END
RETURN 0
Err:
	RETURN -1














GO
/****** Object:  StoredProcedure [dbo].[bpDateReportByCompanyPassedUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--###########################
--创建时间：2014.12.15
--创建人：Nick
--说明：根据provinceid修改DateReport
--###########################
CREATE PROCEDURE [dbo].[bpDateReportByCompanyPassedUpdate]
(
	@ProvinceID INT
)
AS
BEGIN 
	UPDATE DateReport 
	SET CompanyPassed = CompanyPassed+1 
	WHERE province_id = @ProvinceID 
	AND CountDate = CONVERT(VARCHAR(8), GETDATE(), 112)
END


GO
/****** Object:  StoredProcedure [dbo].[bpdcFeeByIDsDelete]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--Edit By Andy 2014-12-16
--删除所有dcFee中符合要求的记录
CREATE PROCEDURE [dbo].[bpdcFeeByIDsDelete] 
(
    @Ids VARCHAR(1000)
)
AS
BEGIN
    DELETE 
    FROM dcFee 
    WHERE id IN (SELECT a FROM dbo.FnSplit(@Ids, ',')) 
END






GO
/****** Object:  StoredProcedure [dbo].[bpdcFeeByIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[bpdcFeeByIDSelect]
    @ID INT
AS
BEGIN
    SELECT TOP 1
        *
    FROM dcFee WITH(NOLOCK)
    WHERE ID = @ID
END














GO
/****** Object:  StoredProcedure [dbo].[bpdcFeeByLastEndDateSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


-----------------
--创建日期：2011-3-6
--创建人：lambo
--功能说明：根据同一省市的最后一个结束时间
-----------------
CREATE PROCEDURE [dbo].[bpdcFeeByLastEndDateSelect]
(
	@dcProvinceID INT
)
AS
BEGIN
	DECLARE @endDate AS SMALLDATETIME
	SELECT TOP 1 @endDate = endDate FROM dcFee WITH(NOLOCK) 
		WHERE dcProvinceID = @dcProvinceID
		ORDER BY endDate DESC
END














GO
/****** Object:  StoredProcedure [dbo].[bpdcFeeCopy]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-----------------
--创建日期：2011-06-04
--创建人：lambo
--功能说明：复制广告资费计划
--bpdcFeeCopy 36,'10,32',119
--Mice 2014-8-31 修改 复制项目添加金币返还比例和兑换所需积分 
-----------------
CREATE PROCEDURE [dbo].[bpdcFeeCopy]
	@ID INT,
	@ProvinceID VARCHAR(200),
	@ManagerUserID INT
AS
BEGIN TRAN
	BEGIN TRY
		DECLARE @dcFeeID INT
		DECLARE @startDate SMALLDATETIME
		DECLARE @endDate SMALLDATETIME
		DECLARE @Type INT
		SELECT @Type = Type,@startDate = startDate,@endDate = endDate FROM dcFee WHERE ID = @ID
		DECLARE @dcProvinceID INT
		
		SELECT * INTO #T FROM dbo.fnsplit(@ProvinceID,',')
		WHILE (SELECT COUNT(*) FROM #T)>0
		BEGIN
			SELECT TOP 1 @dcProvinceID = a FROM #T
			IF NOT EXISTS
				(
					SELECT 'x' FROM dcFee WITH(NOLOCK) 
						WHERE 
								(
								(@startDate<=startDate AND @endDate>startDate) 
								OR 
								(@startDate<endDate AND @endDate>=endDate) 
								)
						AND type = @type
						AND dcProvinceID = @dcProvinceID
				)
			BEGIN
				INSERT INTO dcFee(dcProvinceID,name,startDate,endDate,type,Price,Remark,addDate,ManagerUserID, CoinRation)
					SELECT @dcProvinceID,name,startDate,endDate,type,Price,Remark,GETDATE(),@managerUserID, CoinRation FROM dcFee WHERE ID = @ID
				SET @dcFeeID = @@IDENTITY
				INSERT INTO dcFeeDetail(dcFeeID,MinValue,MaxValue,name,Price,remark, NeedPoint) 
					SELECT @dcFeeID,MinValue,MaxValue,name,Price,remark, NeedPoint FROM dcFeeDetail WHERE dcFeeID =  @ID 
			END
			DELETE FROM #T WHERE a = @dcProvinceID		
		END
		DROP TABLE #T
	END TRY
	BEGIN CATCH
		DROP TABLE #T
		GOTO ERR
	END CATCH
COMMIT TRAN
RETURN 1
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END 
ERR2:
BEGIN
	ROLLBACK TRAN
	RETURN -1
END 





GO
/****** Object:  StoredProcedure [dbo].[bpdcFeeDelete]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


-----------------
--创建日期：2016-02-07
--创建人：lambo
--功能说明：删除一条资费计划
-----------------
CREATE PROCEDURE [dbo].[bpdcFeeDelete]
	@ID INT
AS
BEGIN TRY
	DELETE FROM dcFee WHERE ID=@ID AND endDate>GETDATE()
END TRY
BEGIN CATCH
	GOTO ERR
END CATCH
RETURN 1
ERR:
BEGIN
	RETURN 0
END 














GO
/****** Object:  StoredProcedure [dbo].[bpdcFeeDetailByTypeSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--获取单向资费
--Lucifer 2014-12-19
CREATE PROCEDURE [dbo].[bpdcFeeDetailByTypeSelect] 
(
	@ProvinceID SMALLINT,
	@FeeType TINYINT,
	@TypeCount INT
)
AS 
BEGIN 
	SELECT TOP 1 b.Price PrePrice,a.Price,a.ID
	FROM MainDB..dcFeeDetail a WITH(NOLOCK),MainDB..dcFee b WITH(NOLOCK)
	WHERE
		a.dcFeeID=b.ID AND b.dcProvinceID=@ProvinceID AND b.Type=@FeeType
		AND StartDate<GETDATE() AND EndDate>GETDATE() AND ((MinValue<=@TypeCount
		AND MaxValue>=@TypeCount) OR (MinValue<=@TypeCount AND MaxValue=0))
END


GO
/****** Object:  StoredProcedure [dbo].[bpdcFeeDetailDelete]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


-----------------
--创建日期：2011-03-07
--创建人：lambo
--功能说明：删除一条资费计划
-----------------
CREATE PROCEDURE [dbo].[bpdcFeeDetailDelete]
	@ID INT
AS
BEGIN TRY
	IF NOT EXISTS
		(
			SELECT 'x' FROM dcFee a WITH(NOLOCK),dcFeeDetail b WITH(NOLOCK) 
				WHERE a.ID = b.dcFeeID
				AND b.ID = @ID
				AND a.EndDate<GETDATE()
		)
		DELETE FROM dcFeeDetail WHERE ID=@ID
END TRY
BEGIN CATCH
	GOTO ERR
END CATCH
RETURN 1
ERR:
BEGIN
	RETURN 0
END 














GO
/****** Object:  StoredProcedure [dbo].[bpdcFeeDetailSave]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



-----------------
--创建日期：2011-03-07
--创建人：lambo
--功能说明：增加或修改广告资费计划内容
--mice 2014-8-21 修改， 增加 NeedPoint列
-----------------

CREATE PROCEDURE [dbo].[bpdcFeeDetailSave]
(
	@ID INT,
	@dcFeeID INT,
	@name NVARCHAR(50),
	@MinValue INT,
	@MaxValue INT,
	@Price VARCHAR(20),
	@NeedPoint INT = NULL,
	@remark VARCHAR(200)
)
AS
BEGIN TRAN
	Declare @MaxId AS INT
	BEGIN TRY
		IF @ID > 0
			BEGIN
				UPDATE dcFeeDetail 
					SET dcFeeID = @dcFeeID,
					name = @name,
					MinValue = @MinValue,
					MaxValue = @MaxValue,
					Price = CONVERT(DECIMAL(18,2),@Price),
					NeedPoint=@NeedPoint,
					remark = @remark
				WHERE ID=@ID
				SET @MaxID = @ID
			End
		ELSE
			BEGIN
				INSERT INTO dcFeeDetail VALUES(@dcFeeID,@name,@MinValue,@MaxValue,CONVERT(DECIMAL(18,2),@Price),@remark, @NeedPoint )
				SET @MaxID = @@IDENTITY
			END
		END TRY
		BEGIN CATCH
			GOTO err
		END CATCH
COMMIT TRAN
RETURN @MaxID
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END






GO
/****** Object:  StoredProcedure [dbo].[bpdcFeeMonthCopy]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----------------
--创建日期：2011-06-19
--创建人：lambo
--功能说明：复制以前的单项资费计划
--Modify: 2014-11-28 增加订单复制时,复制金币和积分项
-----------------
CREATE PROCEDURE [dbo].[bpdcFeeMonthCopy]
(
	@referDate VARCHAR(20), 
	@startDate VARCHAR(20), 
	@endDate VARCHAR(20), 		
	@province VARCHAR(200), 
	@txt4 VARCHAR(50)=NULL, 
	@txt5 VARCHAR(50)=NULL, 	
	@txt20 VARCHAR(50)=NULL, 	
	@txt21 VARCHAR(50)=NULL, 	
	@txt7 VARCHAR(50)=NULL, 
	@txt9 VARCHAR(50)=NULL, 
	@txt10 VARCHAR(50)=NULL, 		
	@txt11 VARCHAR(50)=NULL, 
	@txt22 VARCHAR(50)=NULL, 
	@txt23 VARCHAR(50)=NULL, 
	@txt15 VARCHAR(50)=NULL, 
	@txt14 VARCHAR(50)=NULL, 
	@area4 VARCHAR(200)=NULL, 
	@area5 VARCHAR(200)=NULL, 
	@area20 VARCHAR(200)=NULL, 
	@area21 VARCHAR(200)=NULL, 
	@area7 VARCHAR(200)=NULL, 		
	@area9 VARCHAR(200)=NULL, 
	@area10 VARCHAR(200)=NULL, 
	@area11 VARCHAR(200)=NULL, 
	@area22 VARCHAR(200)=NULL, 
	@area23 VARCHAR(200)=NULL, 
	@area15 VARCHAR(200)=NULL, 
	@area14 VARCHAR(200)=NULL, 
	@ManagerUserID INT
)
AS
set nocount on
BEGIN TRAN
	BEGIN TRY
		DECLARE @dcProvinceID INT
		DECLARE @Type INT	
		DECLARE @dcFeeID INT
		DECLARE @dcFeeIDOld INT

		DECLARE curProvince CURSOR FOR
		SELECT * FROM dbo.fnsplit(@Province, ',')

		OPEN curProvince
		FETCH curProvince INTO @dcProvinceID

		WHILE @@FETCH_STATUS >= 0
		BEGIN
			SELECT * INTO #T FROM dbo.fnsplit('4,5,20,21,7,9,10,11,22,23,15,14', ',')
			WHILE (SELECT COUNT(*) FROM #T) > 0
			BEGIN
				SELECT TOP 1 @Type = a FROM #T
				SELECT @dcFeeIDOld = 0

				SELECT TOP 1 @dcFeeIDOld = ID FROM dcFee 
				WHERE Type = @Type AND startDate <= @referDate
				AND endDate >= @referDate
				AND dcProvinceID = @dcProvinceID

				IF NOT EXISTS
					(
						SELECT 'x' FROM dcFee WITH(NOLOCK) 
						WHERE 
							(
							(@startDate<=startDate AND @endDate>startDate) 
							OR 
							(@startDate<endDate AND @endDate>=endDate) 
							)
						AND Type = @Type
						AND dcProvinceID = @dcProvinceID
				)
				BEGIN
					IF @dcFeeIDOld IS NOT NULL
					BEGIN
						INSERT INTO dcFee(dcProvinceID, name, startDate, endDate, Type, Price, Remark, addDate, ManagerUserID, CoinRation, NeedPoint)
						SELECT TOP 1 @dcProvinceID, 
							CASE @Type
								WHEN 4 THEN @txt4
								WHEN 5 THEN @txt5
								WHEN 20 THEN @txt20
								WHEN 21 THEN @txt21
								WHEN 7 THEN @txt7
								WHEN 9 THEN @txt9
								WHEN 10 THEN @txt10
								WHEN 11 THEN @txt11
								WHEN 22 THEN @txt22
								WHEN 23 THEN @txt23
								WHEN 15 THEN @txt15
								WHEN 14 THEN @txt14
							END, 							
							@startDate, @endDate, Type, Price, 
							CASE @Type
								WHEN 4 THEN @area4
								WHEN 5 THEN @area5
								WHEN 20 THEN @area20
								WHEN 21 THEN @area21
								WHEN 7 THEN @area7
								WHEN 9 THEN @area9
								WHEN 10 THEN @area10
								WHEN 11 THEN @area11
								WHEN 22 THEN @area22
								WHEN 23 THEN @area23
								WHEN 15 THEN @area15
								WHEN 14 THEN @area14
							END, 
							GETDATE(), @ManagerUserID, CoinRation, NeedPoint
						FROM dcFee WHERE ID = @dcFeeIDOld

						SET @dcFeeID = @@IDENTITY

						INSERT INTO dcFeeDetail(dcFeeID, MinValue, MaxValue, name, Price, remark, NeedPoint) 
						SELECT @dcFeeID, MinValue, MaxValue, name, Price, remark, NeedPoint FROM dcFeeDetail WHERE dcFeeID = @dcFeeIDOld
					END
				END 
				ELSE
					GOTO ERR2

				DELETE FROM #T WHERE a = @Type
			END
			DROP TABLE #T
			FETCH curProvince INTO @dcProvinceID
		END
	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH
COMMIT TRAN
RETURN 1
ERR:
BEGIN
	ROLLBACK TRAN
	print 'err1'
	RETURN 0
END 
ERR2:
BEGIN
	print 'err2'
	ROLLBACK TRAN
	RETURN -1
 END 
GO
/****** Object:  StoredProcedure [dbo].[bpdcFeeMonthCopy6]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
----------------
--创建日期：2011-06-19
--创建人：lambo
--功能说明：复制以前的单项资费计划
-----------------
CREATE PROCEDURE [dbo].[bpdcFeeMonthCopy6]
	@referDate VARCHAR(20),
	@startDate VARCHAR(20),
	@endDate VARCHAR(20),		
	@province VARCHAR(200),
	@txt4 VARCHAR(50),
	@txt5 VARCHAR(50),	
	@txt7 VARCHAR(50),
	@txt9 VARCHAR(50),
	@txt10 VARCHAR(50),		
	@txt11 VARCHAR(50),
	@area4 VARCHAR(200),
	@area5 VARCHAR(200),
	@area7 VARCHAR(200),		
	@area9 VARCHAR(200),
	@area10 VARCHAR(200),
	@area11 VARCHAR(200),
	@ManagerUserID INT
AS
BEGIN TRAN
	BEGIN TRY
		DECLARE @dcProvinceID INT
		DECLARE @type INT	
		DECLARE @dcFeeID INT
		DECLARE @dcFeeIDOld INT

		SELECT * INTO #T FROM dbo.fnsplit(@Province,',')
		WHILE (SELECT COUNT(*) FROM #T)>0
		BEGIN
			SELECT TOP 1 @dcProvinceID =a FROM #T
			SELECT * INTO #T2 FROM dbo.fnsplit('4,5,7,9,10,11',',')
			WHILE (SELECT COUNT(*) FROM #T2)>0
			BEGIN
				SELECT TOP 1 @type =a FROM #T2

				SELECT TOP 1 @dcFeeIDOld =ID FROM dcFee WHERE type=@type AND startDate<=@referDate AND endDate >=@referDate AND dcProvinceID = @dcProvinceID
				IF NOT EXISTS
					(
						SELECT 'x' FROM dcFee WITH(NOLOCK) 
							WHERE 
								(
								(startDate>=@startDate AND endDate<=@startDate) 
								OR 
								(startDate>=@endDate AND endDate<=@endDate) 
								OR 
								(startDate<=@startDate AND startDate>=@endDate) 
								OR (endDate<=@startDate AND endDate<=@endDate)
								)
							AND type = @type
							AND dcProvinceID = @dcProvinceID
					)
				BEGIN
					IF @dcFeeIDOld IS NOT NULL
					BEGIN
						INSERT INTO dcFee(dcProvinceID,name,startDate,endDate,type,Price,Remark,addDate,ManagerUserID)
							SELECT TOP 1 @dcProvinceID,
							CASE @type
								WHEN 4 THEN @txt4
								WHEN 5 THEN @txt5
								WHEN 7 THEN @txt7
								WHEN 9 THEN @txt9
								WHEN 10 THEN @txt10
								WHEN 11 THEN @txt11
							END,							
							@startDate,@endDate,type,Price,
							CASE @type
								WHEN 4 THEN @area4
								WHEN 5 THEN @area5
								WHEN 7 THEN @area7
								WHEN 9 THEN @area9
								WHEN 10 THEN @area10
								WHEN 11 THEN @area11
							END,
							GETDATE(),@ManagerUserID FROM dcFee WHERE ID=@dcFeeIDOld
						SET @dcFeeID = @@IDENTITY
						INSERT INTO dcFeeDetail(dcFeeID,MinValue,MaxValue,name,Price,remark) 
							SELECT @dcFeeID,MinValue,MaxValue,name,Price,remark FROM dcFeeDetail WHERE dcFeeID = @dcFeeIDOld
					END
				END 
				ELSE
					GOTO ERR2
				DELETE FROM #T2 WHERE a = @type
			END

			DELETE FROM #T WHERE a = @dcProvinceID
		END
		DROP TABLE #T
	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH
COMMIT TRAN
RETURN 1
ERR:
BEGIN
	DROP TABLE #T2
	DROP TABLE #T
	ROLLBACK TRAN
	RETURN 0
END 
ERR2:
BEGIN
	DROP TABLE #T2
	DROP TABLE #T
	ROLLBACK TRAN
	RETURN -1
END 














GO
/****** Object:  StoredProcedure [dbo].[bpdcFeeSave]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--peter 2014-8-25
--修改：harry 增加短线订单14 2017-6-2 harry 增加刷新数订单152017-11-11
CREATE PROCEDURE [dbo].[bpdcFeeSave]
(
	@ID INT,
    @dcProvinceID INT,
    @Name NVARCHAR(30),
    @Type int,
    @StartDate VARCHAR(20),
    @EndDate VARCHAR(20),
    @Remark NVARCHAR(200),
    @ManagerUserID INT,
	@CoinRation DECIMAL(4, 2)
)
AS
SET NOCOUNT ON
BEGIN
	SET @CoinRation = @CoinRation
	Declare @MaxId AS INT

	IF @ID > 0
	BEGIN
		IF EXISTS(SELECT 'x' FROM dcFee WITH(NOLOCK) 
			WHERE ((@StartDate <=startDate AND @EndDate > startDate) 
					OR 
				(@StartDate<endDate AND @EndDate>=endDate))
			AND ID<>@ID 
			AND type = @Type
			AND dcProvinceID = @dcProvinceID
			)
			GOTO ERR2

		UPDATE a 
		SET dcProvinceID = @dcProvinceID,
			name = @Name,
			startDate = @StartDate,
			endDate = @EndDate,
			type = @Type,
			Remark = @Remark,
			AddDate = GETDATE(),
			ManagerUserID = @ManagerUserID,
			CoinRation=@CoinRation,
			Price=CASE @Type 
				WHEN 4 THEN b.PriceAD1
				WHEN 5 THEN b.PriceAD2
				WHEN 20 THEN b.PriceAD3
				WHEN 21 THEN b.PriceAD6
 				WHEN 7 THEN b.PriceFixed
 				WHEN 9 THEN b.PriceResume
 				WHEN 10 THEN b.PriceJob
 				WHEN 11 THEN b.PriceUser
 				WHEN 14 THEN b.PriceSms
				WHEN 15 THEN b.PriceJobRefreshNumber
				WHEN 22 THEN b.PriceTop
				WHEN 23 THEN b.PriceAd22
				WHEN 24 THEN b.PriceRefresh
			END
		FROM dcFee a WITH(NOLOCK), dcFeeStandard b WITH(NOLOCK)
		WHERE ID=@ID 
		AND b.dcProvinceID = @dcProvinceID

		SET @MaxID = @ID
	End
	ELSE
	BEGIN
		IF EXISTS(SELECT 'x' FROM dcFee WITH(NOLOCK) 
			WHERE ((@StartDate<=startDate AND @EndDate > startDate) 
				OR 
				(@StartDate<endDate AND @EndDate >=endDate))
			AND type = @Type
			AND dcProvinceID = @dcProvinceID
			)
			GOTO ERR2
		INSERT INTO dcFee(dcProvinceID, name, startDate, endDate, [type], Remark, ManagerUserID, CoinRation, Price)
		SELECT
			@dcProvinceID,
			@Name,
			@StartDate,
			@EndDate,
			@Type,
			@Remark,
			@ManagerUserID,
			@CoinRation,
			CASE @Type 
				WHEN 4 THEN b.PriceAD1
				WHEN 5 THEN b.PriceAD2
				WHEN 20 THEN b.PriceAD3
				WHEN 21 THEN b.PriceAD6
				WHEN 7 THEN b.PriceFixed
				WHEN 9 THEN b.PriceResume
				WHEN 10 THEN b.PriceJob
				WHEN 11 THEN b.PriceUser
				WHEN 14 THEN b.PriceSms
				WHEN 15 THEN b.PriceJobRefreshNumber
				WHEN 22 THEN b.PriceTop
				WHEN 23 THEN b.PriceAd22
				WHEN 24 THEN b.PriceRefresh
			END
		FROM dcFeeStandard b WITH(NOLOCK)
		WHERE b.dcProvinceID = @dcProvinceID
		SET @MaxID = @@IDENTITY
	END
END
RETURN @MaxID
ERR:
	RETURN 0
ERR2:
	RETURN -2

GO
/****** Object:  StoredProcedure [dbo].[bpdcFeeSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


-----------------
--创建日期：2011-3-6
--创建人：lambo
--功能说明：根据条件查询资费计划
--用于订单管理-->资费计划
-----------------
CREATE PROCEDURE [dbo].[bpdcFeeSelect]
(
	@WHERE VARCHAR(1000)
)
AS
SET NOCOUNT ON
BEGIN
	DECLARE @SQL AS VARCHAR(2000)
	SET @SQL = 'SELECT * FROM dcFee WITH(NOLOCK) WHERE 1=1 '
	IF LEN(@WHERE) > 0
	BEGIN
		SET @Where = dbo.SafeSql(@Where)
		SET @SQL = @SQL + @WHERE
	END
	SET @SQL = @SQL + 'ORDER BY startDate DESC,type'
	EXEC(@SQL)
END














GO
/****** Object:  StoredProcedure [dbo].[bpdcFeeStandardBydcProvinceIDUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--********************************************
--创建人：Andy
--创建时间：2014-12-24
--用途：更新资费标准
--修改：harry 2017-6-2 增加短信单价
--修改：harry 2017-11-11增加刷新数单价
--********************************************
CREATE PROCEDURE [dbo].[bpdcFeeStandardBydcProvinceIDUpdate]
(
	@priceResume INT,
  @priceJob INT,
  @priceUser INT,
  @priceAD1 INT,
  @priceAD2 INT,
  @priceAD3 INT,
  @priceAD6 INT,
  @priceAD22 INT,
  @priceFixed INT,
  @priceTop INT,
  @priceRefresh INT,
  @priceMonth INT,
  @NeedPoint INT,
  @dcProvinceID INT,
  @priceSms DECIMAL(5,2),
  @PriceJobRefreshNumber DECIMAL(5,2)
)
AS
SET NOCOUNT ON
BEGIN	
	UPDATE MainDB..dcFeeStandard 
	SET PriceResume = @priceResume, PriceJob = @priceJob, PriceUser = @priceUser, 
		PriceAD1 = @priceAD1, PriceAD2 = @priceAD2, PriceAD3 = @priceAD3, PriceAD6 = @priceAD6,
		PriceAD22 = @priceAD22, PriceFixed = @priceFixed, PriceTop = @priceTop,
		PriceRefresh = @priceRefresh, PriceMonth = @priceMonth, NeedPoint = @NeedPoint, PriceSms = @priceSms, PriceJobRefreshNumber= @PriceJobRefreshNumber
	WHERE dcProvinceID = @dcProvinceID	
END

GO
/****** Object:  StoredProcedure [dbo].[bpDcFeeStandardSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--创建人 Andy
--时间 2014-12-03
--查询所有资费标准
CREATE PROCEDURE [dbo].[bpDcFeeStandardSelect]
AS
BEGIN
	SELECT * 
	FROM MainDB..dcFeeStandard WITH(NOLOCK) 
	ORDER BY dcProvinceID 	
END

GO
/****** Object:  StoredProcedure [dbo].[bpDcLinkManagerByProvinceIDUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----------------
--创建日期：2015-08-20
--创建人：Peter
--功能说明：友链组重新分配
-----------------
CREATE PROCEDURE [dbo].[bpDcLinkManagerByProvinceIDUpdate]
	@GroupID INT,
	@ManagerUserID INT,
	@ProvinceID INT
AS
UPDATE dclinkmanager 
SET groupid=@GroupID,ManagerUserId=@ManagerUserID 
WHERE subsiteid=@ProvinceID
GO
/****** Object:  StoredProcedure [dbo].[bpdcPayMethodByIdSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.12.1
--创建人：Lucifer
--说明：根据ID获取dcPayMethod信息
--#####################################################
CREATE PROCEDURE [dbo].[bpdcPayMethodByIdSelect]
(
	@ID INT
)
AS
BEGIN
    SELECT * FROM dcPayMethod WITH(NOLOCK) WHERE PayMethodID = @ID
END


GO
/****** Object:  StoredProcedure [dbo].[bpdcPayMethodByInvoiceCompanySelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--bpdcPayMethodByInvoiceCompanySelect 2,2
--修改harry 增加invoicecompany=5 2018-6-5
CREATE PROCEDURE [dbo].[bpdcPayMethodByInvoiceCompanySelect]
(
	@PayMethodID SMALLINT,
	@InvoiceCompany SMALLINT
)
AS
BEGIN
	SELECT a.PayMethodID, b.Name, BankName, Account, Receiver
	FROM dcPayMethodProvince a WITH(NOLOCK),
		dcPayMethod b WITH(NOLOCK)
	WHERE a.PayMethodID = b.PayMethodID 
	AND a.PayMethodID = @PayMethodID 
	AND a.dcProvinceID = CASE WHEN @InvoiceCompany = 4 THEN 30 WHEN @InvoiceCompany = 5 THEN 3201  ELSE 10 END
END

GO
/****** Object:  StoredProcedure [dbo].[bpDcPayMethodProvinceByOrderIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--创建人 Andy
--时间 2014-01-05
--按照订单ID查询一个订单的收发人等信息
CREATE PROCEDURE [dbo].[bpDcPayMethodProvinceByOrderIDSelect]
(		
	@OrderID INT	
)
AS
BEGIN
	DECLARE @InvoiceCompany INT, @cpMainId INT
	SELECT @InvoiceCompany = InvoiceCompany, @cpMainId = cpMainId FROM caOrder WITH(NOLOCK) WHERE Id = @OrderId
	IF @InvoiceCompany IS NULL
	BEGIN
		DECLARE @regionId VARCHAR(6)
		SELECT @RegionId = dcRegionId FROM cpMain WITH(NOLOCK) WHERE Id = @cpMainId
		IF LEFT(@RegionId, 2) NOT IN(30, 32)
			SET @InvoiceCompany = 2
		ELSE IF LEFT(@RegionId, 4) IN ('3214', '3217')
			SET @InvoiceCompany = 2
		ELSE
			SET @InvoiceCompany = 4
	END

	SELECT a.*, b.Paid, c.Name 
	FROM dcPayMethodProvince a WITH(NOLOCK), CaOrder b WITH(NOLOCK), dcPayMethod c WITH(NOLOCK)
	WHERE b.PayMethod = c.PayMethodID 
	AND b.PayMethod = a.PayMethodID 
	AND a.dcProvinceId = CASE WHEN @InvoiceCompany = 4 THEN 30 ELSE 10 END
	AND b.id = @OrderID
END

GO
/****** Object:  StoredProcedure [dbo].[bpdcPayMethodProvinceSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--harry 
--2018-6-5 增加 济南，泰安查询
CREATE PROCEDURE [dbo].[bpdcPayMethodProvinceSelect]
(
	@PayMethodID SMALLINT,
	@dcProvinceID SMALLINT
)
AS
--INSERT INTO procLog SELECT 'bpdcPayMethodProvinceSelect', '', GETDATE()
BEGIN
	 
	SELECT a.PayMethodID,b.Name,BankName,Account,Receiver,a.JointNo
	FROM dcPayMethodProvince a WITH(NOLOCK),dcPayMethod b WITH(NOLOCK)
	WHERE a.PayMethodID = b.PayMethodID 
	AND a.PayMethodID=@PayMethodID 
	AND a.dcProvinceID = CASE WHEN @dcProvinceID IN(30, 32) THEN 30 WHEN @dcProvinceID IN(3201,3204,3205,3206,3209,3212,3213,3215,3217) THEN 3201 ELSE 10 END
END


GO
/****** Object:  StoredProcedure [dbo].[bpdcPayMethodRemarkByIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[bpdcPayMethodRemarkByIDSelect]
(
	@ID INT
)
AS
BEGIN
	SELECT ID,PayMethodID,Name,Description,Receiver,Account,Place,BankName,Fax,PrintFax,Telephone,NameRemark
	FROM dcPayMethodRemark WITH(NOLOCK)
	WHERE ID=@ID
END














GO
/****** Object:  StoredProcedure [dbo].[bpdcPayMethodSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--harry 2018-6-5
--修改增加凤栖
CREATE PROCEDURE [dbo].[bpdcPayMethodSelect]
(
	@dcProvinceID INT
)
AS
BEGIN
         IF @dcProvinceID IN(3201, 3205)
	BEGIN
		SELECT b.Name,a.PayMethodID,a.JointNo,
			BankName,Account,Receiver,b.HomePage
		FROM dcPayMethodProvince a WITH(NOLOCK),
			dcPayMethod b WITH(NOLOCK)
		WHERE a.PayMethodID = b.PayMethodID
		AND a.dcProvinceID = 3201
		AND (b.FrontShow = 1 OR a.PayMethodID=21)
                AND a.Receiver!=''
		ORDER BY OrderBy
	END
	ELSE IF @dcProvinceID IN(30, 32)
	BEGIN
		SELECT b.Name,a.PayMethodID,a.JointNo,
			BankName,Account,Receiver,b.HomePage
		FROM dcPayMethodProvince a WITH(NOLOCK),
			dcPayMethod b WITH(NOLOCK)
		WHERE a.PayMethodID = b.PayMethodID
		AND a.dcProvinceID = 30
		AND (b.FrontShow = 1 OR a.PayMethodID=21)
		ORDER BY OrderBy
	END
	ELSE
	BEGIN
		SELECT b.Name,a.PayMethodID,a.JointNo,
			BankName,Account,Receiver,b.HomePage
		FROM dcPayMethodProvince a WITH(NOLOCK),
			dcPayMethod b WITH(NOLOCK)
		WHERE a.PayMethodID = b.PayMethodID
		AND a.dcProvinceID = 10
		AND (b.FrontShow = 1 OR a.PayMethodID=21)
		ORDER BY OrderBy
	END
END

GO
/****** Object:  StoredProcedure [dbo].[bpdcProvinceAllSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[bpdcProvinceAllSelect]
AS
BEGIN
    SELECT ID,ProvinceName
	FROM dcProvince WITH(NOLOCK)
	ORDER BY ID 
END














GO
/****** Object:  StoredProcedure [dbo].[bpdcProvinceByInfoAmountSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--bpdcProvinceByInfoAmountSelect 32
--创建人 Andy
--时间 2015-01-30
--查询省的MaxInfoAmount和MinInfoAmount
CREATE PROCEDURE [dbo].[bpdcProvinceByInfoAmountSelect] 
(
	@ID INT
)
AS
BEGIN	
	SELECT 
		ID,
		ProvinceName,
		(SELECT MinInfoAmount FROM dcSubsite WHERE id = dcprovince.id) MinInfoAmount,
		(SELECT MaxInfoAmount FROM dcSubsite WHERE id = dcprovince.id) MaxInfoAmount 
	FROM dcProvince WITH(NOLOCK)
	WHERE ID = @ID
END
GO
/****** Object:  StoredProcedure [dbo].[bpDcProvinceBySouthNorthSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.08.25
--创建人：Nick
--说明：获取省份信息
--#####################################################
Create PROCEDURE [dbo].[bpDcProvinceBySouthNorthSelect]
AS
BEGIN
	SELECT ID,province 
	FROM province WITH(NOLOCK) 
	ORDER BY CASE southnorth WHEN 4 THEN 1 ELSE southnorth END DESC,id
END

GO
/****** Object:  StoredProcedure [dbo].[bpDcRegionByGuangDongSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.12.15
--创建人：John
--说明：获取广东省的地区用于营业执照最近审核页面
--#####################################################
CREATE PROCEDURE [dbo].[bpDcRegionByGuangDongSelect]
AS
BEGIN
	SELECT Description
	FROM dcRegion WITH(NOLOCK) 
	WHERE ID LIKE '40%' 
	AND Description NOT LIKE '%开发%' 
	AND Description NOT LIKE '%高新%'
END


GO
/****** Object:  StoredProcedure [dbo].[bpDcRegionTdkUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[bpDcRegionTdkUpdate]
(
	@Id INT,
	@Title NVARCHAR(500),
	@Description NVARCHAR(500),
	@Keyword NVARCHAR(500)
)
AS
SET NOCOUNT ON
BEGIN
	UPDATE dcRegionTdk
	SET Title = @Title, 
		Description = @Description, 
		Keyword = @Keyword
	WHERE Id = @ID
END
SET NOCOUNT OFF

GO
/****** Object:  StoredProcedure [dbo].[bpdcSubsiteByEmail_SentTestIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


--创建人 Andy
--时间 2015-01-26
--查询邮件测试记录对应的subsite的名称
CREATE PROCEDURE [dbo].[bpdcSubsiteByEmail_SentTestIDSelect]
(	
	@ID INT
)
AS
BEGIN	
	SELECT a.ID, a.SubsiteName 
	FROM dcSubsite a WITH(NOLOCK), Email_SentTest b WITH(NOLOCK) 
	WHERE IsMainSite = 1 
	AND a.EmailTester = b.ManagerUserID 
	AND b.ID = @ID
END


GO
/****** Object:  StoredProcedure [dbo].[bpdcSubsiteByIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.08.25
--创建人：Nick
--说明：来源分析内页
--#####################################################
CREATE PROCEDURE [dbo].[bpdcSubsiteByIDSelect]
(
	@SiteID INT
)
AS
BEGIN
	IF @SiteID = 0
	BEGIN
		SELECT id,province FROM province WITH(NOLOCK) ORDER BY CASE southnorth WHEN 4 THEN 1 ELSE southnorth END DESC,id
	END
	ELSE
	BEGIN
		SELECT id, SubsiteCity province FROM dcSubsite WITH(NOLOCK) WHERE Id LIKE ''+CONVERT(VARCHAR(10),@SiteID)+'%' ORDER BY id
	END

END

GO
/****** Object:  StoredProcedure [dbo].[bpdcVIPByCopyInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


--创建日期：2011-06-04
--创建人：lambo
--功能说明：复制资费计划
--Mice 2014-8-31 修改 复制项目添加金币返还比例和兑换所需积分 
--nick 20141229修改 加入 折扣
--harry 2017-11-11增加职位刷新数
-----------------
CREATE PROCEDURE [dbo].[bpdcVIPByCopyInsert]
(
	@ID INT, 
	@ProvinceID VARCHAR(200), 
	@ManagerUserID INT
)
AS
SET NOCOUNT ON
SET @ProvinceID = REPLACE(@ProvinceID, ' ', '')
BEGIN TRAN
	DECLARE @dcVipID INT
	DECLARE @startDate SMALLDATETIME
	DECLARE @endDate SMALLDATETIME
	DECLARE @dcProvinceID INT
	
	SELECT * INTO #T FROM dbo.fnsplit(@ProvinceID, ',')
	WHILE (SELECT COUNT(*) FROM #T)>0
	BEGIN
		SELECT TOP 1 @dcProvinceID = a FROM #T
		SELECT @startDate = startDate, @endDate = endDate FROM dcVIP WHERE ID = @ID

		IF NOT EXISTS
		(
			SELECT 'x' FROM dcVip WITH(NOLOCK) 
			WHERE 
				(
				(@startDate<=startDate AND @endDate>startDate) 
				OR 
				(@startDate<endDate AND @endDate>=endDate) 
				)
				AND dcProvinceID = @dcProvinceID
		)
		BEGIN
			INSERT INTO dcVip(dcProvinceID, name, startDate, endDate, PriceJob, PriceUser, PriceResume, MinJobNumber, MinUserNumber, MinResumeNumber , PriceMonth, Remark, addDate, ManagerUserID, CoinRation, PriceSms, MinSmsNumber, priceJobrefreshNumber, MinJobrefreshNumber) 
			SELECT @dcProvinceID, name, startDate, endDate, PriceJob, PriceUser, PriceResume, MinJobNumber, MinUserNumber, MinResumeNumber, PriceMonth, Remark, GETDATE(), @ManagerUserID , CoinRation, PriceSms, MinSmsNumber, priceJobrefreshNumber, MinJobrefreshNumber
			FROM dcVip WHERE ID = @ID

			SET @dcVipID = @@IDENTITY

			INSERT INTO dcVipDetail(dcVipID, DetailName, TimeTitle, Month, JobNumber, UserNumber, ResumeNumber, Price, remark, IsShowFront, NeedPoint, GivePoint, Discount, SmsNumber, JobRefreshNumber) 
			SELECT @dcVipID, DetailName, TimeTitle, Month, JobNumber, UserNumber, ResumeNumber, Price, remark, IsShowFront, NeedPoint, GivePoint, Discount, SmsNumber, JobRefreshNumber
			FROM dcVipDetail WHERE dcVipID =  @ID
		END
		DELETE FROM #T WHERE a = @dcProvinceID			
	END
	DROP TABLE #T
COMMIT TRAN
RETURN 1
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END 
ERR2:
BEGIN
	DROP TABLE #T
	ROLLBACK TRAN
	RETURN -1
END 


GO
/****** Object:  StoredProcedure [dbo].[bpdcVIPByIDsDelete]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[bpdcVIPByIDsDelete]
(    
    @Ids VARCHAR(1000)    
)
AS
BEGIN    
	DELETE FROM dcVip WHERE id IN (SELECT a FROM dbo.FnSplit(@Ids, ','))
END

GO
/****** Object:  StoredProcedure [dbo].[bpdcVipByIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[bpdcVipByIDSelect]
    @ID INT
AS
BEGIN
    SELECT TOP 1
        *
    FROM dcVip WITH(NOLOCK)
    WHERE ID = @ID
END














GO
/****** Object:  StoredProcedure [dbo].[bpdcVipByLastEndDateSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----------------
--创建日期：2011-3-6
--创建人：lambo
--功能说明：根据同一省市的最后一个结束时间
-----------------
CREATE PROCEDURE [dbo].[bpdcVipByLastEndDateSelect]
(
	@dcProvinceID INT
)
AS
BEGIN
	DECLARE @endDate AS SMALLDATETIME
	SELECT TOP 1 @endDate = endDate FROM dcVip WITH(NOLOCK) 
		WHERE dcProvinceID = @dcProvinceID
		ORDER BY endDate DESC
END














GO
/****** Object:  StoredProcedure [dbo].[bpdcVIPByMonthCopyInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--创建日期：2011-06-19
--创建人：lambo
--功能说明：复制以前的单项资费计划
--Modify: 2014-11-28 增加订单复制时，复制金币和积分项
--nick 20141229修改 加入 折扣
--harry 20170602修改 增加短线订单
--harry 20171111修改 增加短信订单
-----------------
CREATE PROCEDURE [dbo].[bpdcVIPByMonthCopyInsert]
(
	@referDate VARCHAR(20), 
	@startDate VARCHAR(20), 
	@endDate VARCHAR(20), 		
	@province VARCHAR(200), 
	@Name VARCHAR(50), 
	@Remark VARCHAR(200), 
	@ManagerUserID INT
)
AS
SET NOCOUNT ON
BEGIN TRAN
	DECLARE @dcVipID INT
	DECLARE @dcProvinceID INT
	DECLARE @dcVipIDOld INT

	SET @Province = REPLACE(@Province, ', ', ',')
	SELECT * INTO #T FROM dbo.fnsplit(@Province, ',')
	WHILE (SELECT COUNT(*) FROM #T)>0
	BEGIN
		SELECT TOP 1 @dcProvinceID = a FROM #T
		SET @dcVipIDOld = 0
		SELECT @dcVipIDOld = ID FROM dcVIP WHERE startDate<=@referDate AND endDate >=@referDate AND dcProvinceID = @dcProvinceID

		IF NOT EXISTS
		(
			SELECT 'x' FROM dcVip WITH(NOLOCK) 
			WHERE 
				(
				(@startDate<=startDate AND @endDate>startDate) 
				OR 
				(@startDate<endDate AND @endDate>=endDate) 
				)
				AND dcProvinceID = @dcProvinceID
		)
		BEGIN
			INSERT INTO dcVip(dcProvinceID, name, startDate, endDate, PriceJob, PriceUser, PriceResume, MinJobNumber, MinUserNumber, MinResumeNumber , PriceMonth, Remark, addDate, ManagerUserID, CoinRation, NeedPoint, PriceSms, MinSmsNumber, priceJobrefreshNumber, MinJobrefreshNumber) 
			SELECT @dcProvinceID, @name, @startDate, @endDate, PriceJob, PriceUser, PriceResume, MinJobNumber, MinUserNumber, MinResumeNumber, PriceMonth, @Remark, GETDATE(), @ManagerUserID , CoinRation, NeedPoint, PriceSms, MinSmsNumber, priceJobrefreshNumber, MinJobrefreshNumber
			FROM dcVip WHERE ID = @dcVipIDOld

			SET @dcVipID = @@IDENTITY

			INSERT INTO dcVipDetail(dcVipID, DetailName, TimeTitle, Month, JobNumber, UserNumber, ResumeNumber, Price, remark, IsShowFront, NeedPoint, Discount, SmsNumber,JobRefreshNumber) 
			SELECT @dcVipID, DetailName, TimeTitle, Month, JobNumber, UserNumber, ResumeNumber, Price, remark, IsShowFront, NeedPoint, Discount, SmsNumber, JobRefreshNumber
			FROM dcVipDetail 
			WHERE dcVipID = @dcVipIDOld
		END
		ELSE
			GOTO ERR2
		DELETE FROM #T WHERE a = @dcProvinceID			
	END
	DROP TABLE #T
COMMIT TRAN
RETURN 1
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END 
ERR2:
BEGIN
	DROP TABLE #T
	ROLLBACK TRAN
	RETURN -1
END 
SET NOCOUNT OFF

GO
/****** Object:  StoredProcedure [dbo].[bpdcVipDelete]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


-----------------
--创建日期：2011-03-07
--创建人：lambo
--功能说明：删除一条资费计划
-----------------
CREATE PROCEDURE [dbo].[bpdcVipDelete]
	@ID INT
AS
BEGIN TRY
	DELETE FROM dcVip WHERE ID=@ID AND endDate>GETDATE()
END TRY
BEGIN CATCH
	GOTO ERR
END CATCH
RETURN 1
ERR:
BEGIN
	RETURN 0
END 














GO
/****** Object:  StoredProcedure [dbo].[bpDcVipDetailByDcVipidSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--创建人 Andy
--时间 2014-12-04
--按照dcVipid查询VIP资费详细
CREATE PROCEDURE [dbo].[bpDcVipDetailByDcVipidSelect]
(
	@ID INT
)
AS
BEGIN
	SELECT * 
	FROM dcVipDetail 
	WHERE dcVipid = @ID 
	ORDER BY [Month], Price	
END

GO
/****** Object:  StoredProcedure [dbo].[bpdcVipDetailByIdSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.12.1
--创建人：Lucifer
--说明：根据ID获取dcVipDetail信息
--#####################################################
CREATE PROCEDURE [dbo].[bpdcVipDetailByIdSelect]
(
	@ID INT
)
AS
BEGIN
    SELECT * FROM dcVipDetail WITH(NOLOCK) WHERE ID = @ID
END


GO
/****** Object:  StoredProcedure [dbo].[bpdcVipDetailDelete]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


-----------------
--创建日期：2011-03-07
--创建人：lambo
--功能说明：删除一条资费计划
-----------------
CREATE PROCEDURE [dbo].[bpdcVipDetailDelete]
	@ID INT
AS
BEGIN TRY
	IF NOT EXISTS
		(
			SELECT 'x' FROM dcVip a WITH(NOLOCK),dcVipDetail b WITH(NOLOCK) 
				WHERE a.ID = b.dcVipID
				AND b.ID = @ID
				AND a.EndDate<GETDATE()
		)
		DELETE FROM dcVipDetail WHERE ID=@ID
END TRY
BEGIN CATCH
	GOTO ERR
END CATCH
RETURN 1
ERR:
BEGIN
	RETURN 0
END 














GO
/****** Object:  StoredProcedure [dbo].[bpdcVipDetailDIYSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[bpdcVipDetailDIYSelect]
    @dcVipID INT
AS
BEGIN
    SELECT a.startDate, a.EndDate, b.*
	FROM dcVip a WITH(NOLOCK), dcVipDetail b WITH(NOLOCK)
    WHERE b.dcVipID = @dcVipID AND b.Discount>0
	AND b.dcVipID = a.ID
	ORDER BY [Month] DESC, Price DESC
END








GO
/****** Object:  StoredProcedure [dbo].[bpdcVipDetailSave]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


--Mice 2014-8-27 修改， 添加VIP套餐详细的兑换积分
--修改：harry 2017-6-2 添加短信订单短信数量
--修改：harry 2017-11-11增加职位刷新数
CREATE PROCEDURE [dbo].[bpdcVipDetailSave]
(
	@ID INT, 
	@dcVipID INT, 
	@DetailName VARCHAR(100), 
	@TimeTitle VARCHAR(100), 
	@Month INT, 
	@JobNumber INT, 
	@UserNumber INT, 
	@ResumeNumber INT, 
	@Price VARCHAR(20), 
	@remark VARCHAR(200), 
	@IsShowFront TINYINT, 
	@Discount TINYINT, 
	@NeedPoint INT = NULL, 
	@GivePoint INT = NULL,
	@SmsNumber INT =NULL,
	@JobRefreshNumber INT =NULL
)
AS
SET NOCOUNT ON
BEGIN TRAN
	DECLARE @MaxId AS INT
	BEGIN TRY
		IF @ID > 0
		BEGIN
			UPDATE dcVipDetail SET
				dcVipID = @dcVipID, 
				DetailName = @DetailName, 
				TimeTitle = @TimeTitle, 
				[Month] = @Month, 
				JobNumber = @JobNumber, 
				UserNumber = @UserNumber, 
				ResumeNumber = @ResumeNumber, 
				Price = CONVERT(DECIMAL(18, 2), @Price), 
				remark = @remark, 
				IsShowFront = @IsShowFront, 
				Discount = @Discount, 
				NeedPoint = @NeedPoint, 
				GivePoint = @GivePoint,
				SmsNumber = @SmsNumber,
				JobRefreshNumber = @JobRefreshNumber
			WHERE ID = @ID
			SET @MaxID = @ID
		End
		ELSE
		BEGIN
			INSERT INTO dcVipDetail(dcVipID, DetailName, TimeTitle, [Month], JobNumber, 
				UserNumber, ResumeNumber, Price, NeedPoint, GivePoint, Remark, ISRecommend, IsShowFront, DisCount, SmsNumber, JobRefreshNumber) 
			VALUES(@dcVipID, @DetailName, @TimeTitle, @Month, @JobNumber, @UserNumber, 
				@ResumeNumber, CONVERT(DECIMAL(18, 2), @Price), @NeedPoint, @GivePoint, @remark, 0, @IsShowFront, @Discount, @SmsNumber, @JobRefreshNumber)
			SET @MaxID = @@IDENTITY
		END
	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH
COMMIT TRAN
RETURN @MaxID
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END
SET NOCOUNT OFF

GO
/****** Object:  StoredProcedure [dbo].[bpDcVipDetailsByIDUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--Edit By Andy 2014-12-05
--更新套餐资费计划条目的ISRecommend列
--修改：harry2016-1-5
--修改@ISRecommend
CREATE PROCEDURE [dbo].[bpDcVipDetailsByIDUpdate]
(
	@ID INT,
	@ISRecommend INT
)
AS
BEGIN
	DECLARE @recommend BIT
	SET @recommend=1
	IF @ISRecommend=2
	BEGIN
		SET @recommend=0
	END
	UPDATE dcVipDetail 
	SET ISRecommend = @recommend  
	WHERE id = @ID
END

GO
/****** Object:  StoredProcedure [dbo].[bpdcVipDetailSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[bpdcVipDetailSelect]
    @dcVipID INT
AS
BEGIN
    SELECT a.startDate, a.EndDate, b.*
	FROM dcVip a WITH(NOLOCK), dcVipDetail b WITH(NOLOCK)
    WHERE b.dcVipID = @dcVipID AND b.Discount=0
	AND b.dcVipID = a.ID
         AND (IsShowFront = 1 OR IsShowFront=0)
	ORDER BY [Month] DESC, Price DESC
END











GO
/****** Object:  StoredProcedure [dbo].[bpdcVipSave]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--mice 2014-8-24 修改， 添加金币兑换比例：CoinRation
CREATE PROCEDURE [dbo].[bpdcVipSave]
(
	@ID INT,
	@dcProvinceID INT,
	@name NVARCHAR(30),
	@startDate VARCHAR(20),
	@endDate VARCHAR(20),
	@Remark NVARCHAR(200),
	@ManagerUserID INT,
	@CoinRation Decimal(4,2) = NULL
)
AS
BEGIN TRAN
	DECLARE @MaxId AS INT
	BEGIN TRY
		IF @ID>0
		BEGIN
			IF EXISTS
				(SELECT 'x' FROM dcVip WITH(NOLOCK) 
				WHERE (
						(startDate<=@startDate AND endDate>=@startDate) 
						OR 
						(startDate<=@endDate AND endDate>=@endDate) 
						OR 
						(startDate>=@startDate AND startDate<=@endDate) 
						OR 
						(endDate>=@startDate AND endDate<=@endDate)
					)
				AND ID<>@ID 
				AND dcProvinceID = @dcProvinceID
				)
				GOTO ERR2

			UPDATE a SET
				dcProvinceID = @dcProvinceID,
				name = @name,
				startDate = @startDate,
				endDate = @endDate,
				Remark = @Remark,
				AddDate = GETDATE(),
				ManagerUserID = @ManagerUserID,
				PriceJob = b.PriceJob,
				PriceUser = b.PriceUser,
				PriceResume = b.PriceResume,
				PriceMonth = b.PriceMonth,
				MinJobNumber = b.MinJobNumber,
				MinUserNumber = b.MinUserNumber,
				MinResumeNumber = b.MinResumeNumber,
				CoinRation=@CoinRation
			FROM dcVip a WITH(NOLOCK),dcFeeStandard b WITH(NOLOCK)
			WHERE ID=@ID 
			AND b.dcProvinceID = @dcProvinceID
			SET @MaxID = @ID
		END
		ELSE
		BEGIN
			IF EXISTS(SELECT 'x' FROM dcVip WITH(NOLOCK) 
				WHERE(
						(startDate<=@startDate AND endDate>=@startDate) 
						OR 
						(startDate<=@endDate AND endDate>=@endDate) 
						OR 
						(startDate>=@startDate AND startDate<=@endDate) 
						OR 
						(endDate>=@startDate AND endDate<=@endDate)
					)
				AND dcProvinceID = @dcProvinceID
				)
				GOTO ERR2
			INSERT INTO dcVip(
				dcProvinceID,
				name ,
				startDate ,
				endDate ,
				Remark ,
				ManagerUserID ,
				PriceJob ,
				PriceUser ,
				PriceResume ,
				PriceMonth,
				MinJobNumber,
				MinUserNumber,
				MinResumeNumber,
				CoinRation
				)
			SELECT
				@dcProvinceID,
				@name,
				@startDate,
				@endDate,
				@Remark,
				@ManagerUserID,
				b.PriceJob,
				b.PriceUser,
				b.PriceResume,
				b.PriceMonth,
				b.MinJobNumber,
				b.MinUserNumber,
				b.MinResumeNumber,
				@CoinRation
			FROM dcFeeStandard b WITH(NOLOCK)
			WHERE b.dcProvinceID = @dcProvinceID
			SET @MaxID = @@IDENTITY
		END
	END TRY
	BEGIN CATCH
	GOTO err
	END CATCH
COMMIT TRAN
RETURN @MaxID
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END
ERR2:
BEGIN
	ROLLBACK TRAN
	RETURN -2
END





GO
/****** Object:  StoredProcedure [dbo].[bpdcVipSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


-----------------
--创建日期：2011-3-6
--创建人：lambo
--功能说明：根据条件查询资费计划
--用于订单管理-->资费计划
-----------------
CREATE PROCEDURE [dbo].[bpdcVipSelect]
(
	@WHERE VARCHAR(1000)
)
AS
BEGIN
	DECLARE @SQL AS VARCHAR(2000)
	SET @SQL='SELECT * FROM dcVip WITH(NOLOCK) WHERE 1=1 '
	IF LEN(@WHERE) > 0
	BEGIN
		SET @Where = dbo.SafeSql(@Where)
		SET @SQL = @SQL + @WHERE
	END
	SET @SQL = @SQL + 'ORDER BY startDate DESC,dcProvinceID'
	EXEC(@SQL)
END




GO
/****** Object:  StoredProcedure [dbo].[bpDeptBsConsultantFreeOrderSetSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------
--创建日期：2014-12-1
--创建人：harry
--功能说明：newoamvc单位用户管理-->顾问开通权限限额分配
--用于后台获取顾问开通权限限额分配
-------------------------------------------------------
CREATE PROCEDURE [dbo].[bpDeptBsConsultantFreeOrderSetSelect]
AS
BEGIN
	SELECT DISTINCT c.Id, c.DeptName, a.Number 
	FROM bsConsultantFreeOrderSet a WITH(NOLOCK), 
		ManagerUser b WITH(NOLOCK), 
		Dept c WITH(NOLOCK)
	WHERE a.ConsultantId = b.Id
	AND b.DeptId = c.Id
END

GO
/****** Object:  StoredProcedure [dbo].[bpDeptByIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.09.06
--创建人：Nick
--说明：得到推广部门
--#####################################################
create PROCEDURE [dbo].[bpDeptByIDSelect]
AS
BEGIN
	SELECT id,deptname FROM dept WITH(NOLOCK) WHERE id IN(15,16,22,26,35) ORDER BY ID
END

GO
/****** Object:  StoredProcedure [dbo].[bpDeptByTypeSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--###########################
--创建时间：2014.12.10
--创建人：Nick
--说明：销售部门
--###########################
CREATE PROCEDURE [dbo].[bpDeptByTypeSelect]
AS
BEGIN 
	SELECT * FROM Dept WITH(NOLOCK) 
	WHERE ID IN(
		SELECT DISTINCT DeptID 
		FROM Manageruser WITH(NOLOCK) WHERE Type IN(1,5)
	) AND Valid=1 AND Grade=2 
	ORDER BY Superior,DeptName
END


GO
/****** Object:  StoredProcedure [dbo].[bpDeptSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[bpDeptSelect]
(
	@ID AS INT
)
AS
BEGIN
	SELECT * FROM DEPT WHERE ID = @ID
END














GO
/****** Object:  StoredProcedure [dbo].[bpDoubanMailByPaMainIDUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.12.26
--创建人：Nick
--说明：根据pamainid修改doubanmail
--#####################################################
CREATE PROCEDURE [dbo].[bpDoubanMailByPaMainIDUpdate]
(
	@PaMainID INT
)
AS
BEGIN
	UPDATE doubanmail SET hasverify=1 WHERE isregister=1 AND pamainid = @PaMainID
END 

GO
/****** Object:  StoredProcedure [dbo].[bpEmail_Senttest_LogByDayReportSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.1.27
--创建人：Andy
--说明：邮件测试管理测试报告
--#####################################################
CREATE PROCEDURE [dbo].[bpEmail_Senttest_LogByDayReportSelect]
(
	@Day VARCHAR(10) --2010-01-01
)
AS
BEGIN	
	DECLARE @StartTime DATETIME, @EndTime DATETIME
	SET @StartTime= CONVERT(DATETIME, @Day, 120)
	SET @EndTime = DATEADD(DAY, 1, @StartTime)
	
	CREATE TABLE #T(
		Province_id INT,
		Status INT,
		Type INT,
		EmailType VARCHAR(20)
	)

	--获取数据
	INSERT INTO #T
	SELECT a.Province_id, a.Status, a.Type, b.EmailType 
	FROM Email_SentTest_Log a WITH(NOLOCK), Email_SentTest b WITH(NOLOCK) 
	WHERE a.Email_SentTest_ID = b.ID AND a.AddDate BETWEEN @StartTime AND @EndTime
	
	--统计：按照省份、EmailType、 TYPE（简历常规、单位常规、简历群发，单位群发）、Status(成功、失败、垃圾箱)
	SELECT	
		b.ID  ProvinceID,
		b.ProvinceName,
		EmailType,
		Type, 		
		(SELECT COUNT(1) FROM #T WHERE Province_id = b.ID AND EmailType = a.EmailType AND Type = a.Type) CntAll,
		(SELECT COUNT(1) FROM #T WHERE Status = 0 AND Province_id = b.ID AND EmailType = a.EmailType AND Type = a.Type) Cnt0,
		(SELECT COUNT(1) FROM #T WHERE Status = 1 AND Province_id = b.ID AND EmailType = a.EmailType AND Type = a.Type) Cnt1,
		(SELECT COUNT(1) FROM #T WHERE Status = 2 AND Province_id = b.ID AND EmailType = a.EmailType AND Type = a.Type) Cnt2,
		(SELECT COUNT(1) FROM #T WHERE Status = 3 AND Province_id = b.ID AND EmailType = a.EmailType AND Type = a.Type) Cnt3	
	FROM #T a LEFT JOIN dcProvince b ON a.Province_id = b.ID
	GROUP BY b.ID, ProvinceName, EmailType, type
END

GO
/****** Object:  StoredProcedure [dbo].[bpEmail_Senttest_LogByDayStatisticsSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--创建时间：2015.1.27
--创建人：Andy
--说明：邮件测试管理每日汇总(只统计六天)
--#####################################################
CREATE PROCEDURE [dbo].[bpEmail_Senttest_LogByDayStatisticsSelect]
AS
BEGIN	
	DECLARE @StartTime VARCHAR(10), @EndTime VARCHAR(10)
	SET @StartTime = CONVERT(VARCHAR(100), GETDATE() - 6, 23)
	SET @EndTime = CONVERT(VARCHAR(100), GETDATE() + 1, 23)	
	
	CREATE TABLE #T(
		ID INT,
		Status INT,
		Email_Senttest_ID INT,
		AddDate VARCHAR(8)
	)

	--获取数据
	INSERT INTO #T
	SELECT ID, Status, Email_Senttest_ID, CONVERT(VARCHAR(8), AddDate, 112)
	FROM Email_SentTest_Log WITH(NOLOCK)	
	WHERE AddDate > @StartTime AND AddDate < @EndTime		
	
	--统计
	SELECT
		Email_Senttest_ID,
		AddDate [Date],		
		(SELECT COUNT(1) FROM #T WHERE AddDate = B.AddDate AND Email_Senttest_ID = B.Email_Senttest_ID) CntAll,
		(SELECT COUNT(1) FROM #T WHERE AddDate = b.AddDate AND Email_Senttest_ID = b.Email_Senttest_ID AND Status = 0) Cnt0,
		(SELECT COUNT(1) FROM #T WHERE AddDate = b.AddDate AND Email_Senttest_ID = b.Email_Senttest_ID AND Status = 1) Cnt1,
		(SELECT COUNT(1) FROM #T WHERE AddDate = b.AddDate AND Email_Senttest_ID = b.Email_Senttest_ID AND Status = 2) Cnt2,
		(SELECT COUNT(1) FROM #T WHERE AddDate = b.AddDate AND Email_Senttest_ID = b.Email_Senttest_ID AND Status = 3) Cnt3	
	FROM #T b
	GROUP BY Email_Senttest_ID, AddDate
END


GO
/****** Object:  StoredProcedure [dbo].[bpEmail_Senttest_LogByMonthReportSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.1.27
--创建人：Andy
--说明：邮件测试管理月度测试报告
--#####################################################
CREATE PROCEDURE [dbo].[bpEmail_Senttest_LogByMonthReportSelect]
(
	@SearchMonth VARCHAR(7) --2010-01
)
AS
BEGIN	
	DECLARE @StartTime DATETIME, @EndTime DATETIME
	SET @EndTime = CONVERT(DATETIME, @SearchMonth+'-26', 120)
	SET @StartTime = DATEADD(MONTH, -1, @EndTime)
	
	CREATE TABLE #T(
		Province_id INT,
		Status INT,
		Type INT,
		EmailType VARCHAR(20)
	)

	--获取数据
	INSERT INTO #T
	SELECT a.Province_id, a.Status, a.Type, b.EmailType 
	FROM Email_SentTest_Log a WITH(NOLOCK), Email_SentTest b WITH(NOLOCK) 
	WHERE a.Email_SentTest_ID = b.ID AND a.AddDate BETWEEN @StartTime AND @EndTime
	
	--统计：按照省份、EmailType、 TYPE（简历常规、单位常规、简历群发，单位群发）、Status(成功、失败、垃圾箱)
	SELECT	
		b.ID  ProvinceID,
		b.ProvinceName,
		EmailType,
		Type, 		
		(SELECT COUNT(1) FROM #T WHERE Province_id = b.ID AND EmailType = a.EmailType AND Type = a.Type) CntAll,
		(SELECT COUNT(1) FROM #T WHERE Status = 0 AND Province_id = b.ID AND EmailType = a.EmailType AND Type = a.Type) Cnt0,
		(SELECT COUNT(1) FROM #T WHERE Status = 1 AND Province_id = b.ID AND EmailType = a.EmailType AND Type = a.Type) Cnt1,
		(SELECT COUNT(1) FROM #T WHERE Status = 2 AND Province_id = b.ID AND EmailType = a.EmailType AND Type = a.Type) Cnt2,
		(SELECT COUNT(1) FROM #T WHERE Status = 3 AND Province_id = b.ID AND EmailType = a.EmailType AND Type = a.Type) Cnt3	
	FROM #T a LEFT JOIN dcProvince b ON a.Province_id = b.ID
	GROUP BY b.ID, ProvinceName, EmailType, type
END
GO
/****** Object:  StoredProcedure [dbo].[bpEmail_Senttest_LogByMonthStatisticsSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.1.27
--创建人：Andy
--说明：邮件测试成功率月度报告
--#####################################################
CREATE PROCEDURE [dbo].[bpEmail_Senttest_LogByMonthStatisticsSelect]
(
	@SearchMonth VARCHAR(7) --2010-01
)
AS
BEGIN	
	DECLARE @StartTime DATETIME, @EndTime DATETIME
	SET @EndTime = CONVERT(DATETIME, @SearchMonth + '-26')
	SET @StartTime = DATEADD(MONTH, -1, @EndTime)
		
	SELECT a.Status, COUNT(1) cnt 
	FROM Email_SentTest_Log a WITH(NOLOCK), Email_SentTest b WITH(NOLOCK) 
	WHERE a.Email_SentTest_ID = b.ID AND a.AddDate > @StartTime AND a.AddDate < @EndTime AND b.ManagerUserID = 373 
	GROUP BY a.Status 
	ORDER BY a.Status
END


GO
/****** Object:  StoredProcedure [dbo].[bpEmail_SentTest_LogSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


--bpEmail_SentTest_LogSelect 1,4,1,''
--创建人 Andy
--时间 2015-01-23
--按照条件查询邮件测试记录
CREATE PROCEDURE [dbo].[bpEmail_SentTest_LogSelect] 
(	
	@ID INT,	
	@Status INT,
	@UserType INT,	
	@AddDate VARCHAR(10)--格式：2014-01-01
)
AS
BEGIN		
	DECLARE @EndDate DATETIME
	SET @EndDate = CONVERT(DATETIME, @AddDate) + 1
	DECLARE @SQL VARCHAR(1000)	
	SET @SQL = '
		SELECT ID, Host, Subject, Body, FromEmail, FromName, AddDate, Status, Province_ID, Type, Code 
		FROM Email_SentTest_Log WITH(NOLOCK) 
		WHERE Email_Senttest_ID = ' + LTRIM(STR(@ID))
	IF @Status > 0	
	BEGIN
		IF @Status = 4
			SET @SQL = @SQL + ' And (Status = 0 AND AddDate <= GETDATE() - 3) ' 
		ELSE IF @Status = 5
			SET @SQL = @SQL + ' And (Status = 0 AND AddDate > GETDATE() - 3) '	
		ELSE
			SET @SQL = @SQL + ' And Status = ' + LTRIM(STR(@Status))
	END
	IF @UserType > 0		
		SET @SQL = @SQL + ' And type = ' + LTRIM(STR(@UserType))				
	IF LEN(@AddDate) > 0
		SET @SQL = @SQL + ' And AddDate BETWEEN ''' + @AddDate + ''' AND ''' + CONVERT(VARCHAR(10), @EndDate, 120) + '''' 			  
	SET @SQL = @SQL + ' ORDER BY AddDate DESC'
	--PRINT(@SQL)
	EXEC (@SQL)
END
GO
/****** Object:  StoredProcedure [dbo].[bpEmail_SentTestByAllSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--创建人 Andy
--时间 2015-01-26
--查找所有Email_SentTest记录
CREATE PROCEDURE [dbo].[bpEmail_SentTestByAllSelect]
AS
BEGIN	
	SELECT *
	FROM Email_SentTest WITH(NOLOCK)
	ORDER BY ManagerUserID DESC	
END


GO
/****** Object:  StoredProcedure [dbo].[bpEmail_SentTestDelete]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--创建人 Andy
--时间 2015-01-26
--删除邮件测试记录
CREATE PROCEDURE [dbo].[bpEmail_SentTestDelete]
(	
	@ID INT
)
AS
BEGIN	
	DELETE FROM Email_SentTest WHERE id	= @ID
END


GO
/****** Object:  StoredProcedure [dbo].[bpEmail_SentTestLogUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--select * from Email_SentTest_Log
--bpEmail_SentTestLogUpdate 1015504, 3, '1111', 7940
--select * from Email_SentTest_Log
--创建人 Andy
--时间 2015-01-26
--保存一条Email_SentTest_Log记录
CREATE PROCEDURE [dbo].[bpEmail_SentTestLogUpdate] 
(	
	@LogID INT,
	@Status INT,
	@Remarks VARCHAR(200),
	@code VARCHAR(20)
)
AS
BEGIN	
	IF @Status = 1
		UPDATE Email_SentTest_Log SET Status = 1 WHERE ID = @LogID AND Code = @code
	ELSE IF @Status = 2
		UPDATE Email_SentTest_Log SET Status = 2, Remarks = @Remarks WHERE id = @LogID
	ELSE IF @Status = 3
		UPDATE Email_SentTest_Log SET Status = 3, Remarks = @Remarks WHERE id = @LogID AND Code = @code	
END
GO
/****** Object:  StoredProcedure [dbo].[bpEmail_SentTestSave]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--bpEmail_SentTestSave 0, 'yincun@163.com', 1, '', 'QQ'
--创建人 Andy
--时间 2015-01-26
--保存一条Email_SentTest_Log记录
CREATE PROCEDURE [dbo].[bpEmail_SentTestSave] 
(	
	@ID INT, 
	@Email VARCHAR(50), 
	@ManagerUserID INT, 
	@CCEmail VARCHAR(50), 
	@EmailType VARCHAR(20)
)
AS
BEGIN		
	IF @ID > 0
		UPDATE Email_SentTest 
		SET Email = @Email, cc_email = @CCEmail, emailtype = @EmailType
		WHERE ID = @ID
	ELSE
		INSERT INTO Email_SentTest (Email, ManagerUserID, EmailType) 
		VALUES (@Email, @ManagerUserID, @EmailType)
END


GO
/****** Object:  StoredProcedure [dbo].[bpEmail_SentTestSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--创建人 Andy
--时间 2015-01-26
--查询邮件测试记录
CREATE PROCEDURE [dbo].[bpEmail_SentTestSelect]
(	
	@CurManagerUserID INT, --当前登录用户ID		
	@Privi INT--当前用户的权限
)
AS
BEGIN
	SELECT a.Email, a.ManagerUserID, a.AddDate, b.Name, a.ID, a.EmailType, a.cc_Email, 
		(SELECT COUNT(*) FROM Email_Senttest_Log WHERE Status = 0 AND Type = 1 AND Email_SentTest_ID = a.ID AND Adddate BETWEEN CONVERT(VARCHAR(10), GETDATE(), 120) AND CONVERT(VARCHAR(10), GETDATE() + 1, 120)) pCount, 
		(SELECT COUNT(*) FROM Email_SentTest_Log WHERE Status = 0 AND Type = 2 AND Email_SentTest_ID = a.ID AND AddDate BETWEEN CONVERT(VARCHAR(10), GETDATE(), 120) AND CONVERT(VARCHAR(10), GETDATE() + 1, 120)) cCount 
	FROM Email_SentTest a WITH(NOLOCK), ManagerUser b WITH(NOLOCK)
	WHERE a.ManagerUserID = b.ID 	
	--AND a.ManagerUserId IN (SELECT ID FROM dbo.LowerUser(LTRIM(STR(@CurManagerUserID)), LTRIM(STR(@Privi))))
	ORDER BY a.ManagerUserID DESC, EmailType	
END

GO
/****** Object:  StoredProcedure [dbo].[bpEmailCheckByDeptIdSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[bpEmailCheckByDeptIdSelect]
( 
	@deptId INT,  
	@privi CHAR(2)
)
AS 
BEGIN
	DECLARE @sql VARCHAR(1000) 
	SET @sql = 'SELECT TOP 500 a.id, a.testdate, a.planhour, a.sendtime, 
		a.replylong, a.ManagerUserid, b.email, b.name, a.planminute, a.remarks 
		FROM EmailCheck a WITH(NOLOCK), 
			ManagerUser b WITH(NOLOCK)
		WHERE a.ManagerUserid = b.id '

	IF(Len(@deptId) > 0) AND (Len(@deptId) < 3) 
		SET @sql = @sql + ' AND b.DeptId = ' + LTRIM(STR(@deptid)) 

	IF(@privi != '5') 
		SET @sql = @sql +' AND (a.replylong IS NOT NULL OR a.sendtime < getdate() -1 )' 

	SET @sql = @sql + ' ORDER BY a.testdate DESC, a.planhour DESC'
	--print @sql
	EXEC(@sql)
END

GO
/****** Object:  StoredProcedure [dbo].[bpEmailCheckUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------
--创建日期：2014-12-3
--创建人：harry
--功能说明：newoamvc单位用户管理-->邮件回复检查-->设置邮件回复的时间和备注
--用于设置邮件回复的时间和备注
-------------------------------------------------------
CREATE PROCEDURE [dbo].[bpEmailCheckUpdate]
(
	@replyLong INT,
	@remarks VARCHAR(100),
	@id INT
)
AS 
BEGIN
	UPDATE emailcheck
	SET replylong = @replyLong, remarks = @remarks
	WHERE id = @id
END


GO
/****** Object:  StoredProcedure [dbo].[bpEmailCompanyByCompanyIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----------------
--创建日期：2010-9-14
--创建人：lambo
--功能说明：根据单位编号查询该单位所有的单位邮件发送记录
--用于单位邮件发送记录页面
-----------------
CREATE PROCEDURE [dbo].[bpEmailCompanyByCompanyIDSelect]
(
	@CompanyID INT
)
AS
BEGIN
	SELECT a.*,b.Name, b.consultantid, b.regdate,b.dcprovinceid,b.id AS cpId FROM EmailCompany a WITH(NOLOCK), 
        cpMain b WITH(NOLOCK),
        caMain c WITH(NOLOCK)
	WHERE a.CompanyId = c.Id
		AND c.cpMainId = b.ID
		AND b.ID = @CompanyID
	ORDER BY AddDate DESC
END 
GO
/****** Object:  StoredProcedure [dbo].[bpEmailCompanySelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----------------
--创建日期：2010-9-14
--创建人：lambo
--功能说明：查询前一千条单位邮件发送记录
--用于单位邮件发送记录页面
-----------------
CREATE PROCEDURE [dbo].[bpEmailCompanySelect]
AS
BEGIN
	SELECT top 1000 a.*,b.Name, b.id AS cpId,b.consultantid, b.regdate,b.dcprovinceid FROM EmailCompany a WITH(NOLOCK),cpMain b WITH(NOLOCK),caMain c WITH(NOLOCK)
	WHERE a.CompanyId=c.ID
	AND c.cpMainId= b.id
	ORDER BY AddDate DESC
END 

GO
/****** Object:  StoredProcedure [dbo].[bpExtendlinkByConsultantIdSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--按顾问统计外链数量
--添加人：harry
--添加时间：2015-4-2
CREATE PROCEDURE [dbo].[bpExtendlinkByConsultantIdSelect]
(
	@beginDate AS SMALLDATETIME,
	@endDate AS SMALLDATETIME,
	@managerUserId AS INT,
	@pri AS INT
)
AS
BEGIN
	CREATE TABLE #T
	(
		ConSultantID INT,
		Pass INT,
		NoPass INT
	)
	INSERT INTO #T (ConSultantID) SELECT ID FROM MainDB..LowerUser(LTRIM(STR(@managerUserId)), LTRIM(STR(@pri)))
	--按顾问统计 顾问名下的连接数
		--pass linkstatus=1
	UPDATE a SET a.Pass=c.cnt FROM #T a,
	(
		SELECT COUNT(1) cnt, consultantid FROM MainDB..extendlink b
		WHERE b.adddate BETWEEN @beginDate AND  @endDate AND b.linkStatus=1  AND b.cpMainID 
		IN (SELECT id FROM Maindb..cpMain WHERE consultantid = a.ConSultantID)
		GROUP BY consultantid
	)c WHERE a.ConsultantId=c.consultantid
		--nopass linkstatus!=1 AND linkstatus!=3
	UPDATE a SET a.Pass=c.cnt FROM #T a,
	(
		SELECT COUNT(1)cnt, consultantid FROM MainDB..extendlink b
		WHERE b.adddate BETWEEN @beginDate AND  @endDate AND b.linkStatus!=1 AND b.linkStatus!=3 AND b.cpMainID 
		IN (SELECT id FROM Maindb..cpMain WHERE consultantid = a.ConSultantID)
		GROUP BY consultantid
	)c WHERE a.ConsultantId=c.consultantid
	SELECT * FROM #T
	DROP TABLE #T
END
GO
/****** Object:  StoredProcedure [dbo].[bpFaxReceiveSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--创建人 Andy
--时间 2014-12-30
--按照条件查询FaxReceive表
CREATE PROCEDURE [dbo].[bpFaxReceiveSelect]
(		
	@Status INT,	
	@Passage INT,
	@SortMinute INT,
	@ManagerUserID INT,
	@FaxNumber VARCHAR(50),
	@CompanyID INT,
	@Where VARCHAR(200)
)
AS
BEGIN	
	DECLARE @SQL AS VARCHAR(2000)
	SET @SQL = ' 
		SELECT Top 500 a.*,b.Name,b.Name_Eng,c.Name CompanyName,c.RegDate 
		FROM FaxReceive a WITH(NOLOCK) 
		LEFT JOIN Manageruser b WITH(NOLOCK) ON a.Manageruserid=b.id 
		LEFT JOIN cpMain c WITH(NOLOCK) ON c.ID = a.CompanyID
		WHERE 1=1'
	IF @Status = 1
		SET @SQL = @SQL + ' AND SortTime Is Null '
	ELSE IF @Status = 2
		SET @SQL = @SQL + '  AND SortTime Is Not Null '
	ELSE IF @Status = 3
		SET @SQL = @SQL + ' AND IsNull(IsDone,0) = 0 '
	ELSE IF @Status = 4
		SET @SQL = @SQL + ' AND IsDone = 1 '	
	
	IF @Passage = 1
		SET @SQL = @SQL + ' AND Passage = 1 '
	ELSE IF @Passage = 2
		SET @SQL = @SQL + ' AND Passage = 2 '	
	
	IF @ManagerUserID > 0
		SET @SQL = @SQL + ' And a.ManagerUserId = ' + LTRIM(STR(@ManagerUserID))	
	
	IF @SortMinute > 0
		SET @SQL = @SQL + ' And a.Sortminute > ' + LTRIM(STR(@SortMinute))	
		
	IF @FaxNumber > '0'
		SET @SQL = @SQL + ' And FaxNumber =  '''+ @FaxNumber + ''''	
	
	IF @CompanyID > 0
		SET @SQL = @SQL + ' AND CompanyID = '+ LTRIM(STR(@CompanyID))	
	
	IF @Where > '0'
		SET @SQL = @SQL + @Where
		
	SET @SQL = @SQL + ' ORDER BY a.Id DESC ' 	
	print @sql
	EXEC(@SQL)		
END


GO
/****** Object:  StoredProcedure [dbo].[bpFnFnLetterByFnInvoiceIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--根据发票ID获取发票邮寄信息 Lucifer 2014-12-24
CREATE PROCEDURE [dbo].[bpFnFnLetterByFnInvoiceIDSelect]
(
	@FnInvoiceID INT
)
AS
BEGIN
	SELECT * FROM MainDB..FnLetter WITH(NOLOCK) WHERE FnInvoiceID=@FnInvoiceID ORDER BY PostDate
END


GO
/****** Object:  StoredProcedure [dbo].[bpFnInvoiceByIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--根据发票ID获取发票信息 Lucifer 2014-12-24
CREATE PROCEDURE [dbo].[bpFnInvoiceByIDSelect]
(
	@ID INT
)
AS
BEGIN
	SELECT * FROM FnInvoice WITH(NOLOCK) WHERE ID=@ID
END


GO
/****** Object:  StoredProcedure [dbo].[bpFnInvoiceByInvalidUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--发票退票 Lucifer 2014-12-24
CREATE PROCEDURE [dbo].[bpFnInvoiceByInvalidUpdate]
(
	@Invalidman INT,
	@InvalidmanName NVARCHAR(50),
	@InvalidReason NVARCHAR(200),
	@ReturnFnInvoiceId INT,
	@InvoiceMonth CHAR(6),
	@ID INT,
	@Code INT
)
AS
BEGIN
	UPDATE Maindb..FnInvoice SET
		InvalidDate=GETDATE(),
		Invalidman=@Invalidman,
		InvalidmanName=@InvalidmanName,
		status=11,
		InvalidReason=@InvalidReason,
		ReturnFnInvoiceId=@ID
	WHERE ID=@ReturnFnInvoiceId

	DECLARE @Money NUMERIC(18,2),@Head NVARCHAR(50),@OrderID INT
	SELECT @Money = Money, @Head = Head, @OrderID = OrderID
	FROM FnInvoice WITH(NOLOCK) WHERE ID = @ReturnFnInvoiceId

	UPDATE FnInvoice SET
		InvalidDate=GETDATE(),
		Invalidman=@Invalidman,
		InvalidmanName=@InvalidmanName,
		status=11,
		InvalidReason=@InvalidReason,
		InvoiceMonth=@InvoiceMonth,
		ReturnFnInvoiceId=@ReturnFnInvoiceId,
		OrderID=@OrderID,
		Money=@Money,
		MakeoutDate=GETDATE(),
		Makeoutman=@Invalidman,
		MakeoutmanName=@Invalidman,
		Head=@Head
	WHERE ID=@ID AND ID*DAY(AddDate)=@Code
END

GO
/****** Object:  StoredProcedure [dbo].[bpFnInvoiceByNoOpenSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--根据开票公司和发票状态获取待开发票信息 Lucifer 2014-12-24
--修改harry2016-8-8 助泽，网聚都可以开增值税专用发票
CREATE PROCEDURE [dbo].[bpFnInvoiceByNoOpenSelect]
(
	@Concern SMALLINT,
	@FnInvoiceType SMALLINT
)
AS
SET NOCOUNT ON
BEGIN
	--IF @Concern = 2
	--	SELECT TOP 1 ID,No FROM MainDB..FnInvoice WITH(NOLOCK)
	--	WHERE Status=0 AND Concern = @Concern
	--	ORDER BY CONVERT(VARCHAR(8), AddDate, 112), No
	--ELSE
		SELECT TOP 1 ID,No FROM MainDB..FnInvoice WITH(NOLOCK)
		WHERE Status=0 AND Concern=@Concern AND FnInvoiceType=@FnInvoiceType
		ORDER BY CONVERT(VARCHAR(8), AddDate, 112),No
END

 
GO
/****** Object:  StoredProcedure [dbo].[bpFnInvoiceByOrderIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--根据订单ID获取所有发票信息 Lucifer 2014-12-24
CREATE PROCEDURE [dbo].[bpFnInvoiceByOrderIDSelect]
(
	@OrderID INT
)
AS
BEGIN
	SELECT * FROM MainDB..FnInvoice WITH(NOLOCK) WHERE OrderID=@OrderID ORDER BY MakeoutDate
END


GO
/****** Object:  StoredProcedure [dbo].[bpFnInvoiceByOrderIDStatusSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.12.2
--创建人：Lucifer
--说明：根据OrderID获取发票信息
--#####################################################
CREATE PROCEDURE [dbo].[bpFnInvoiceByOrderIDStatusSelect]
(
	@OrderID INT,
	@Status TINYINT
)
AS
BEGIN
	SELECT * FROM FnInvoice WITH(NOLOCK) WHERE Status=@Status AND OrderID=@OrderID
END


GO
/****** Object:  StoredProcedure [dbo].[bpFnInvoiceByOrderIDUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--订单与发票关联 Lucifer 2014-12-24
CREATE PROCEDURE [dbo].[bpFnInvoiceByOrderIDUpdate]
(
	@OrderID INT,
	@InvoiceMonth VARCHAR(6),
	@Paid NUMERIC(18,2),
	@MakeOutMan SMALLINT,
	@MakeOutManName NVARCHAR(10),
	@Head NVARCHAR(100),
	@FnInvoiceID INT
)
AS
SET NOCOUNT ON
BEGIN
	UPDATE caOrder SET InvoiceMonth = @InvoiceMonth WHERE InvoiceMonth IS NULL AND ID = @OrderID
	IF(SELECT OrderStatus FROM Caorder WHERE Id = @OrderId) = 12
		UPDATE Caorder SET OrderStatus = 14 WHERE Id = @OrderId

	UPDATE FnInvoice 
	SET Orderid=@OrderID,
		Money=@Paid,
		MakeoutDate=GetDate(),
		InvoiceMonth=CONVERT(VARCHAR(6),GETDATE(),112),
		MakeOutMan=@MakeOutMan,
		MakeOutManName=@MakeOutManName,
		Status=1,
		Head=@Head
	WHERE Status=0 And ID=@FnInvoiceID
END


GO
/****** Object:  StoredProcedure [dbo].[bpFnLetterByOrderIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.12.2
--创建人：Lucifer
--说明：根据OrderID获取发票邮寄信息
--#####################################################
CREATE PROCEDURE [dbo].[bpFnLetterByOrderIDSelect]
(
	@OrderID INT
)
AS
BEGIN
	SELECT * FROM FnInvoice WITH(NOLOCK),FnLetter WHERE FnLetter.FnInvoiceID=FnInvoice.ID
		AND FnLetter.Status IN(1,2) AND FnInvoice.Status=1 AND FnInvoice.OrderID=@OrderID
END

GO
/****** Object:  StoredProcedure [dbo].[bpFnLetterInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--添加发票邮寄 Lucifer 2014-12-24
CREATE PROCEDURE [dbo].[bpFnLetterInsert]
(
	@PostNumber NVARCHAR(50),
	@PostTelephone VARCHAR(50),
	@PostAddress NVARCHAR(100),
	@Recipient NVARCHAR(100),
	@FnInvoiceID INT,
	@Zip CHAR(6),
	@Postman INT,
	@PostmanName NVARCHAR(50),
	@Remarks NVARCHAR(200),
	@Companyname NVARCHAR(50),
	@Fee NUMERIC(18,2)
)
AS
SET NOCOUNT ON
BEGIN
	INSERT INTO Maindb..Fnletter(
		PostNumber,
		PostTelephone,
		PostAddress,
		Recipient,
		FnInvoiceID,
		Zip,
		Postman,
		PostmanName,
		Remarks,
		Status,
		PostDate,
		Companyname,
		Fee
	) 
	VALUES (
		@PostNumber,
		@PostTelephone,
		@PostAddress,
		@Recipient,
		@FnInvoiceID,
		@Zip,
		@Postman,
		@PostmanName,
		@Remarks,
		1,
		GETDATE(),
		@Companyname,
		@Fee
	)
END


GO
/****** Object:  StoredProcedure [dbo].[bpFpHomepageImageSubmitUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Mice 123>
-- Create date: <2014-11-24>
-- Description:	<保存网站头条图片管理记录>
-- =============================================
CREATE PROCEDURE [dbo].[bpFpHomepageImageSubmitUpdate] 
	-- Add the parameters for the stored procedure here
	@pids varchar(200),
	@alt VARCHAR(50),
	@title VARCHAR(50),
	@imagefile VARCHAR(50),
	@url VARCHAR(100),
	@imagetype INT,
	@addman INT

AS
BEGIN TRAN 
	BEGIN TRY
	--首先删除现有的记录
	DELETE  FROM  maindb..fphomepageimage WHERE imagefile=@imagefile
	
	--新增所有provinceID 记录
	INSERT INTO maindb..fpHomepageImage(dcProvinceID,ImageType,ImageFile,Alt,AddMan,AddDate,title,url)	
	SELECT  a, @imagetype,@imagefile,@alt, @addman, getDate(), @title, @url  FROM dbo.fnsplit(@pids,',')

	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH

COMMIT TRAN 
RETURN 1

ERR:
BEGIN
		ROLLBACK TRAN
		RETURN 0

END


GO
/****** Object:  StoredProcedure [dbo].[bpFriendLinkBlackByIdDelete]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----------------
--创建日期：2015-08-24
--创建人：Peter
--功能说明：删除友链黑名单
-----------------
CREATE PROCEDURE [dbo].[bpFriendLinkBlackByIdDelete]
	@ID INT
AS
BEGIN
	DELETE FROM FriendLinkBlack
	WHERE id = @ID
END

GO
/****** Object:  StoredProcedure [dbo].[bpFriendLinkBlackByIdSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----------------
--创建日期：2015-08-24
--创建人：Peter
--功能说明：单个友链黑名单
-----------------
CREATE PROCEDURE [dbo].[bpFriendLinkBlackByIdSelect]
	@ID INT
AS
BEGIN
	SELECT * 
	FROM friendlinkblack WITH(NOLOCK)
	WHERE Id = @ID
END

GO
/****** Object:  StoredProcedure [dbo].[bpFriendLinkBlackSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----------------
--创建日期：2015-08-24
--创建人：Peter
--功能说明：友链黑名单
-----------------
CREATE PROCEDURE [dbo].[bpFriendLinkBlackSelect]
	@SearchItem INT,
	@SearchText NVARCHAR(12),
	@OrderType INT
AS

DECLARE @SQL VARCHAR(MAX)
DECLARE @SQLWhere VARCHAR(1000)

SET @SQL = 'SELECT * 
	FROM friendlinkblack WITH(NOLOCK) 
	WHERE 1=1 '
SET @SQLWhere = ''
	
IF @SearchItem = 1
BEGIN
	SET @SQLWhere = @SQLWhere + ' AND websitename LIKE ''%' + @SearchText + '%'''
END
ELSE IF @SearchItem = 2
BEGIN
	SET @SQLWhere = @SQLWhere + ' AND url LIKE ''%' + @SearchText + '%'''
END

IF @OrderType = 1
BEGIN
	SET @SQLWhere = @SQLWhere + ' ORDER BY url'
END
ELSE IF @OrderType = 2
BEGIN
	SET @SQLWhere = @SQLWhere + ' ORDER BY adddate DESC'
END
ELSE
BEGIN
	SET @SQLWhere = @SQLWhere + ' ORDER BY websitename'
END

SET @SQL = @SQL + @SQLWhere

EXEC(@SQL)
GO
/****** Object:  StoredProcedure [dbo].[bpFriendLinkBlackUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-----------------
--创建日期：2015-08-24
--创建人：Peter
--功能说明：友链黑名单修改
-----------------
CREATE PROCEDURE [dbo].[bpFriendLinkBlackUpdate]
	@ID INT,
	@WebSiteName NVARCHAR(30),
	@Url VARCHAR(30),
	@AddMan INT,
	@Remarks NVARCHAR(1000)
AS
BEGIN
	IF @ID = 0
	BEGIN
		IF EXISTS(SELECT TOP 1 'X' FROM friendlinkblack WHERE Url = @Url)
			RETURN -1
			
		INSERT INTO friendlinkblack (websitename,url,addman,remarks)
		VALUES (@WebSiteName,@Url,@AddMan,@Remarks)
	END
	ELSE
	BEGIN
		UPDATE friendlinkblack
		SET websitename = @WebSiteName,
		Url = @Url,
		Remarks = @Remarks
		WHERE id = @ID
		
	END
	
	RETURN 1
END
GO
/****** Object:  StoredProcedure [dbo].[bpFriendLinkByVersionidSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----------------
--创建日期：2015-08-20
--创建人：Peter
--功能说明：查询友链汇总
-----------------
CREATE PROCEDURE [dbo].[bpFriendLinkByVersionidSelect]
	
AS
SELECT b.id,b.subsitecity province,groupid,(
	SELECT ISNULL(SUM(score), 0) 
	FROM link WITH(NOLOCK) 
	WHERE versionid = b.id AND valid = 1 AND deleted < 1 AND type = 1 AND method = 1
	) mainsitescore_sum,(
	SELECT COUNT(1) 
	FROM link WITH(NOLOCK) 
	WHERE versionid = b.id AND valid=1 AND deleted<1 AND type=1 AND method=1
	) mainsite_num,(
	SELECT COUNT(1) 
	FROM link WITH(NOLOCK) 
	WHERE versionid = b.id AND valid=1 AND deleted<1 AND type=1 AND method=1 AND orderby<100
	) mainsite_num_noself,(
	SELECT COUNT(1) 
	FROM link WITH(NOLOCK),dcsubsite WITH(NOLOCK) 
	WHERE versionid>100 AND left(versionid,2) = b.id AND type=1 AND valid=1 AND deleted<1 AND method=1 AND versionid=dcsubsite.id AND ismainsite=0
	) secondsite_num,(
	SELECT SUM(score) score_sum 
	FROM link WITH(NOLOCK),dcsubsite WITH(NOLOCK) 
	WHERE versionid>100 AND versionid/100 = b.id AND valid=1 AND deleted<1 AND type=1 AND method=1 AND versionid=dcsubsite.id AND ismainsite=0
	) secondsitescore_sum
FROM dclinkmanager a WITH(NOLOCK),dcsubsite b WITH(NOLOCK) 
WHERE a.subsiteid = b.id
ORDER BY SubSiteId
GO
/****** Object:  StoredProcedure [dbo].[bpHRKpiPostByIdSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--获取一条kpi岗位工资信息-----------------
--增加人Harry ---------------------------
--增加时间：2015-1-28--------------------
CREATE PROCEDURE [dbo].[bpHRKpiPostByIdSelect]
(
	@id INT
)
AS
BEGIN
	SELECT Id, KpiPostName, Breadth, Beginning 
	FROM MainDb..HRKpiPost WITH(NOLOCK) 
	WHERE Id = @id
END

GO
/****** Object:  StoredProcedure [dbo].[bpHRKpiPostDelete]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



--删除一条Kpipost信息-----------------
--增加人Harry ---------------------------
--增加时间：2015-1-28--------------------
CREATE PROCEDURE [dbo].[bpHRKpiPostDelete]
(
	@id INT
)
AS
BEGIN
	DELETE 
	FROM MainDb..HRKpiPost 
	WHERE id = @id
END

GO
/****** Object:  StoredProcedure [dbo].[bpHRKpiPostInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


--添加一条Kpipost信息-----------------
--增加人Harry ---------------------------
--增加时间：2015-1-28--------------------
CREATE PROCEDURE [dbo].[bpHRKpiPostInsert]
(
	@kpipostname NVARCHAR(50), 
	@breadth INT, 
	@beginning INT
)
AS
BEGIN
	INSERT INTO MainDb..HRKpiPost (KpiPostName, Breadth, Beginning)
	VALUES(@kpipostname, @breadth, @beginning)
END

GO
/****** Object:  StoredProcedure [dbo].[bpHRKpiPostUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--更新一条kpi岗位工资信息-----------------
--增加人Harry ---------------------------
--增加时间：2015-1-28--------------------
CREATE PROCEDURE [dbo].[bpHRKpiPostUpdate]
(
	@kpipostname NVARCHAR(50), 
	@breadth INT, 
	@beginning INT, 
	@id INT
)
AS
BEGIN
	UPDATE MainDb..HRKpiPost 
	SET KpiPostName = @kpipostname, Breadth = @breadth, Beginning = @beginning 
	WHERE Id = @id	
END

GO
/****** Object:  StoredProcedure [dbo].[bpIInfoAchieveByLocalrateSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.2.2
--创建人：Andy
--说明：获取某个员工某个月份的Localrate
--#####################################################
--bpIInfoAchieveByLocalrateSelect  200311,1
CREATE PROCEDURE [dbo].[bpIInfoAchieveByLocalrateSelect]
(
	@Month VARCHAR(6), --格式：201001
	@ManagerUserID INT
)
AS
BEGIN		
	SELECT Localrate 
	FROM InfoAchieve WITH(NOLOCK) 
	WHERE YearMonth = @Month AND infomanager_id = @ManagerUserID
END


GO
/****** Object:  StoredProcedure [dbo].[bpInfo_DateReportByCountDateStatisticsSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.2.4
--创建人：Andy
--说明：统计信息员统计核算功能所有人的日报
--#####################################################
--bpInfo_DateReportByCountDateStatisticsSelect  '20031110',1,5,0
CREATE PROCEDURE [dbo].[bpInfo_DateReportByCountDateStatisticsSelect]
(
	@CountDate VARCHAR(8), --格式：20150101		
	@CurManagerUserID INT,--当前登录用户ID		
	@Privi INT,--当前用户的权限	
	@Dept INT	
)
AS
BEGIN	
	----用户列表
	DECLARE @SQL VARCHAR(2000)
	CREATE TABLE #T 
	(
		ID INT
	)	
	SET @SQL = '	
		INSERT INTO #T
		SELECT a.ID 		
		FROM manageruser a WITH(NOLOCK), Dept b WITH(NOLOCK)  
		WHERE a.DeptID = b.ID AND a.ID IN
			(
			SELECT ID FROM manageruser WITH(NOLOCK)
			WHERE DeptID IN (SELECT ID FROM Dept WHERE Superior = 11 OR ID = 11 OR ID = 26)
			)'	
	IF @Dept > 0
		SET @SQL = @SQL + ' AND a.DeptID = ' + LTRIM(STR(@Dept))	
	SET @SQL = @SQL + ' AND a.ID IN (SELECT ID FROM dbo.LowerUserAll('+LTRIM(STR(@CurManagerUserID)) + ',' + LTRIM(STR(@Privi)) + '))'	
	SET @SQL = @SQL + ' ORDER BY a.ID'	
	--print (@sql)
	EXEC (@SQL)
	--select * from #t
	----查出数据源
	SELECT 
		a.ID,
		Province_ID,
		SUM(RealCompany) RealCompany,
		SUM(RealResume) RealResume,
		SUM(Validresume) Validresume,
		SUM(Validcompany) Validcompany,		
		SUM(CompanyRegNum_Our) CompanyRegNum_Our,
		SUM(PersonRegNum_our) PersonRegNum_our,
		SUM(Homepage) Homepage,
		SUM(AllResume) AllResume,
		SUM(MobileNum) MobileNum,
		SUM(cpMobileNum) cpMobileNum,
		SUM(ISNULL(MobileReturn,0)) MobileReturn,
		SUM(ISNULL(MobileAccount,0)) MobileAccount,
		SUM(ISNULL(cpMobileRetNum,0)) cpMobileRetNum,
		SUM(ISNULL(cpMobileAccountNum,0)) cpMobileAccountNum
	INTO #T2 
	FROM #T a LEFT JOIN Info_DateReport b WITH(NOLOCK)
	ON a.ID = b.InfoManager_ID
	WHERE b.CountDate = @CountDate	
	GROUP BY a.ID, b.Province_ID	
	--select * from #t2
	
	----取出每一个省的系数
	CREATE TABLE #T_Info_Coeffi
	(
		Province_ID INT,
		Coefficient DECIMAL
	)	
	INSERT INTO #T_Info_Coeffi
	SELECT Province_ID, Coefficient
	FROM (
		SELECT ROW_NUMBER() 
		OVER(PARTITION BY Province_ID ORDER BY BeginDate DESC) AS NO, Province_ID, Coefficient 
		FROM Info_Coeffi 
		WHERE BeginDate <= @CountDate
		) a
	WHERE a.No = 1			

	----乘以相应的系数
	UPDATE #T2 SET 
		--Coefficient = a.Coefficient,
		RealCompany = ROUND(RealCompany * a.Coefficient, 0),	--四舍五入
		Validcompany = ROUND(Validcompany * a.Coefficient, 0),	--四舍五入
		Realresume = FLOOR(Realresume * a.Coefficient),			--不四舍五入
		Validresume = FLOOR(Validresume * a.Coefficient)		--不四舍五入			
	FROM #T_Info_Coeffi a 
	WHERE a.Province_ID = #T2.Province_ID
	
	----按照ManagerUserID把所有的省份合计
	SELECT 
		ID,		
		SUM(RealCompany) RealCompany,
		SUM(RealResume) RealResume,
		SUM(Validresume) Validresume,
		SUM(Validcompany) Validcompany,		
		SUM(CompanyRegNum_Our) CompanyRegNum_Our,
		SUM(PersonRegNum_our) PersonRegNum_our,
		SUM(Homepage) Homepage,
		SUM(AllResume) AllResume,
		SUM(MobileNum) MobileNum,
		SUM(cpMobileNum) cpMobileNum,
		SUM(ISNULL(MobileReturn,0)) MobileReturn,
		SUM(ISNULL(MobileAccount,0)) MobileAccount,
		SUM(ISNULL(cpMobileRetNum,0)) cpMobileRetNum,
		SUM(ISNULL(cpMobileAccountNum,0)) cpMobileAccountNum	
	FROM #T2	
	GROUP BY ID	
		
END


GO
/****** Object:  StoredProcedure [dbo].[bpInfo_DateReportByDeptCountDateStatisticsSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.2.4
--创建人：Andy
--说明：统计信息员统计核算功能部门对比日报
--#####################################################
--bpInfo_DateReportByDeptCountDateStatisticsSelect  '20031110'
CREATE PROCEDURE [dbo].[bpInfo_DateReportByDeptCountDateStatisticsSelect]
(
	@CountDate VARCHAR(8) --格式：20150101			
)
AS
BEGIN		
	----查出数据源
	SELECT 
		b.DeptID,
		Province_ID,
		SUM(RealCompany) RealCompany,
		SUM(RealResume) RealResume,
		SUM(Validresume) Validresume,
		SUM(Validcompany) Validcompany,		
		SUM(CompanyRegNum_Our) CompanyRegNum_Our,
		SUM(PersonRegNum_our) PersonRegNum_our,
		SUM(Homepage) Homepage,
		SUM(AllResume) AllResume,
		SUM(MobileNum) MobileNum,
		SUM(cpMobileNum) cpMobileNum,
		SUM(ISNULL(MobileReturn,0)) MobileReturn,
		SUM(ISNULL(MobileAccount,0)) MobileAccount,
		SUM(ISNULL(cpMobileRetNum,0)) cpMobileRetNum,
		SUM(ISNULL(cpMobileAccountNum,0)) cpMobileAccountNum
	INTO #T 
	FROM Info_DateReport a WITH(NOLOCK) RIGHT JOIN
		(
		--推广一部、二部的所有员工
		SELECT ID, DeptID FROM ManagerUser WHERE DeptID IN (15, 16)
		) b
	ON a.InfoManager_ID = b.ID
	WHERE a.CountDate = @CountDate	
	GROUP BY b.DeptID, a.Province_ID	
	
	--SELECT * FROM #T 
	----取出每一个省的系数
	CREATE TABLE #T_Info_Coeffi
	(
		Province_ID INT,
		Coefficient DECIMAL
	)	
	INSERT INTO #T_Info_Coeffi
	SELECT Province_ID, Coefficient
	FROM (
		SELECT ROW_NUMBER() 
		OVER(PARTITION BY Province_ID ORDER BY BeginDate DESC) AS NO, Province_ID, Coefficient 
		FROM Info_Coeffi 
		WHERE BeginDate <= @CountDate
		) a
	WHERE a.No = 1			
	
	----乘以相应的系数
	UPDATE #T SET 
		--Coefficient = a.Coefficient,
		RealCompany = ROUND(RealCompany * a.Coefficient, 0),	--四舍五入
		Validcompany = ROUND(Validcompany * a.Coefficient, 0),	--四舍五入
		Realresume = FLOOR(Realresume * a.Coefficient),			--不四舍五入
		Validresume = FLOOR(Validresume * a.Coefficient)		--不四舍五入			
	FROM #T_Info_Coeffi a 
	WHERE a.Province_ID = #T.Province_ID
	
	--SELECT * FROM #T
	----按照DeptID把所有的省份合计
	SELECT 
		DeptID,
		SUM(RealCompany) RealCompany,
		SUM(RealResume) RealResume,
		SUM(Validresume) Validresume,
		SUM(Validcompany) Validcompany,		
		SUM(CompanyRegNum_Our) CompanyRegNum_Our,
		SUM(PersonRegNum_our) PersonRegNum_our,
		SUM(Homepage) Homepage,
		SUM(AllResume) AllResume,
		SUM(MobileNum) MobileNum,
		SUM(cpMobileNum) cpMobileNum,
		SUM(ISNULL(MobileReturn,0)) MobileReturn,
		SUM(ISNULL(MobileAccount,0)) MobileAccount,
		SUM(ISNULL(cpMobileRetNum,0)) cpMobileRetNum,
		SUM(ISNULL(cpMobileAccountNum,0)) cpMobileAccountNum	
	FROM #T	
	GROUP BY DeptID	
	DROP TABLE #T	
END


GO
/****** Object:  StoredProcedure [dbo].[bpInfo_DateReportByHistoryStatisticsSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.2.3
--创建人：Andy
--说明：统计信息员统计核算个人历史查询功能
--#####################################################
--SELECT * FROM Info_DateReport
--bpInfo_DateReportByHistoryStatisticsSelect 1, 1,5
CREATE PROCEDURE [dbo].[bpInfo_DateReportByHistoryStatisticsSelect]
(	
	@UserID INT, --被查询的ID
	@CurManagerUserID INT,--当前登录用户ID		
	@Privi INT--当前用户的权限
)
AS
BEGIN	
	SELECT * INTO #T
	FROM InfoAchieve WITH(NOLOCK) 
	WHERE infomanager_id IN (SELECT ID FROM dbo.LowerUser(@CurManagerUserID, @Privi)) 
	AND infomanager_id = @UserID
	ORDER BY YearMonth DESC
	
	--添加两列为计算Sum(mobilenum),sum(cpmobilenum)
	ALTER TABLE #T ADD SumMobileNum DECIMAL
	ALTER TABLE #T ADD SumCpMobileNum DECIMAL
	
	--查询出每一个月的合计
	UPDATE #T SET
		SumMobileNum = (SELECT SUM(a. MobileNum) FROM Info_DateReport a WITH(NOLOCK) WHERE a.infomanager_id = #T.ID 
			AND a.CountDate >= CONVERT(VARCHAR(10), DATEADD(m, -1, CONVERT(DATETIME, #T.YearMonth+'26', 120)), 112)
			AND a.CountDate <= #T.YearMonth + '26'), 
		SumCpMobileNum = (SELECT SUM(a. CpMobileNum) FROM Info_DateReport a WITH(NOLOCK) WHERE a.infomanager_id = #T.ID 
			AND a.CountDate >= CONVERT(VARCHAR(10), DATEADD(m, -1, CONVERT(DATETIME, #T.YearMonth+'26', 120)), 112)
			AND a.CountDate <= #T.YearMonth + '26')
	
	--查询
	SELECT * FROM #T	
END


GO
/****** Object:  StoredProcedure [dbo].[bpInfo_DateReportByIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--bpInfo_DateReportByIDSelect 1
--#####################################################
--创建时间：2015.1.27
--创建人：Andy
--说明：查询信息员统计核算功能个人日报
--#####################################################
CREATE PROCEDURE [dbo].[bpInfo_DateReportByIDSelect]
(
	@ID INT
)
AS
BEGIN	
	DECLARE @StartTime VARCHAR(10), @EndTime VARCHAR(10)
	SET @StartTime = CONVERT(VARCHAR(100), GETDATE() - 6, 23)
	SET @EndTime = CONVERT(VARCHAR(100), GETDATE() + 1, 23)	
	
	CREATE TABLE #T(		
		Countdate VARCHAR(8)
	)

	--获取要查询的时间（只查询40天）
	INSERT INTO #T
	SELECT TOP 40 CountDate 
	FROM Info_DateReport WITH(NOLOCK)  
	WHERE Infomanager_id = @ID		
	--AND Infomanager_id IN (SELECT ID FROM dbo.LowerUser(@CurManagerUserID, @Privi))		
	GROUP BY CountDate 
	ORDER BY CountDate DESC	

	SELECT 
		a.CountDate,
		RealCompany, 
		Realresume,
		Validresume,
		Validcompany,
		Province_id,
		Companyregnum_our,
		Personregnum_our,
		Homepage,
		Allresume, 
		MobileNum, 
		cpMobileNum,
		ISNULL(MobileReturn,0) MobileReturn, 
		ISNULL(MobileAccount,0) MobileAccount, 
		ISNULL(cpMobileRetNum,0) cpMobileRetNum, 
		ISNULL(cpMobileAccountNum,0) cpMobileAccountNum  
	FROM Info_DateReport a WITH(NOLOCK), #T b 
	WHERE a.CountDate = b.CountDate 
	AND InfoManager_ID = @ID
	--GROUP BY b.CountDate
	ORDER BY Province_ID	
END


GO
/****** Object:  StoredProcedure [dbo].[bpInfo_DateReportByMaxManagerUserSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.2.4
--创建人：Andy
--说明：统计信息员统计核算功能某天业绩最好的人
--#####################################################
--bpInfo_DateReportByMaxManagerUserSelect  '20031110'
CREATE PROCEDURE [dbo].[bpInfo_DateReportByMaxManagerUserSelect]
(
	@CountDate VARCHAR(8) --格式：20150101			
)
AS
BEGIN
	SET NOCOUNT ON		
	----查出数据源
	SELECT 
		b.ID,
		Province_ID,
		SUM(RealCompany) RealCompany,
		SUM(RealResume) RealResume,		
		SUM(ISNULL(MobileAccount,0)) MobileAccount,	
		SUM(ISNULL(cpMobileAccountNum,0)) cpMobileAccountNum
	INTO #T 
	FROM Info_DateReport a WITH(NOLOCK) RIGHT JOIN
		(
		--推广一部、二部的所有员工
		SELECT ID, DeptID FROM ManagerUser WHERE DeptID IN (15, 16)
		) b
	ON a.InfoManager_ID = b.ID
	WHERE a.CountDate = @CountDate	
	GROUP BY b.ID, a.Province_ID	
	
	--SELECT * FROM #T 
	----取出每一个省的系数
	CREATE TABLE #T_Info_Coeffi
	(
		Province_ID INT,
		Coefficient DECIMAL
	)	
	INSERT INTO #T_Info_Coeffi
	SELECT Province_ID, Coefficient
	FROM (
		SELECT ROW_NUMBER() 
		OVER(PARTITION BY Province_ID ORDER BY BeginDate DESC) AS NO, Province_ID, Coefficient 
		FROM Info_Coeffi 
		WHERE BeginDate <= @CountDate
		) a
	WHERE a.No = 1			
	
	----乘以相应的系数
	UPDATE #T SET 
		--Coefficient = a.Coefficient,
		RealCompany = ROUND(RealCompany * a.Coefficient, 0),	--四舍五入
		cpMobileAccountNum = ROUND(cpMobileAccountNum * a.Coefficient, 0),	--四舍五入
		Realresume = FLOOR(Realresume * a.Coefficient),			--不四舍五入
		MobileAccount = FLOOR(MobileAccount * a.Coefficient)		--不四舍五入			
	FROM #T_Info_Coeffi a 
	WHERE a.Province_ID = #T.Province_ID
	
	--SELECT * FROM #T
	----按照DeptID把所有的个人合计
	SELECT 
		ID,
		SUM(RealCompany + cpMobileAccountNum) cpSum,
		SUM(RealResume + MobileAccount) paSum	
	INTO #T3	
	FROM #T	
	GROUP BY ID	
	
	--选出最大的人和个数
	SELECT cpSum, ID FROM #T3 ORDER BY cpSum DESC
	SELECT paSum, ID FROM #T3 ORDER BY paSum DESC
	
	DROP TABLE #T
	SET NOCOUNT OFF		
END


GO
/****** Object:  StoredProcedure [dbo].[bpInfo_DateReportByMonthProvinceStatisticsSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.1.27
--创建人：Andy
--说明：统计信息员统计核算功能个人月报(按省分解)
--修改：2015-02-12 修改Localrate列的精度
--#####################################################
--SELECT * FROM Info_DateReport
--bpInfo_DateReportByMonthProvinceStatisticsSelect  200311,1
CREATE PROCEDURE [dbo].[bpInfo_DateReportByMonthProvinceStatisticsSelect]
(
	@Month VARCHAR(6), --格式：201001
	@ManagerUserID INT
)
AS
BEGIN		
	DECLARE @StartDate DATETIME, @EndDate DATETIME
	--注：如11月的数据，应该是10-26到11.26	
	SET @EndDate = CONVERT(DATETIME, @Month + '26')	--11.26
	SET @StartDate = DATEADD(MONTH, -1, @EndDate)	--10.26
	--PRINT CONVERT(VARCHAR(8), @StartDate, 112) 
	--PRINT CONVERT(VARCHAR(8), @EndDate, 112) 
	CREATE TABLE #T
	(		
		Province_id INT,
		Coefficient DECIMAL,		
		RealCompany INT,
		Companyregnum_our INT,
		Validcompany INT,
		Realresume INT,
		Validresume INT,		
		Personregnum_our INT,
		Homepage INT,
		Allresume INT,
		MobileNum INT,
		cpMobileNum INT,
		MobileReturn INT,		
		MobileAccount INT,		
		cpMobileRetNum INT,		
		cpMobileAccountNum INT,
		Pr3 INT,
		CpRepeatRate INT,
		CpRepeat INT,
		PaRepeatRate INT,
		PaRepeat INT,
		Ff3 INT,
		Localrate DECIMAL(18,2)
	)
	
	--查出每一个省合计后的的原始数据
	INSERT INTO #T	
	SELECT 		
		Province_id,	
		0,			
		SUM(RealCompany) RealCompany, 
		SUM(Companyregnum_our) Companyregnum_our, 
		SUM(Validcompany) Validcompany,
		SUM(Realresume) Realresume, 
		SUM(Validresume) Validresume,
		SUM(Personregnum_our) Personregnum_our, 
		SUM(Homepage) Homepage, 
		SUM(Allresume) Allresume, 
		SUM(MobileNum) MobileNum, 
		SUM(cpMobileNum) cpMobileNum, 
		SUM(ISNULL(MobileReturn,0)) MobileReturn, 		
		SUM(ISNULL(MobileAccount,0)) MobileAccount, 		
		SUM(ISNULL(cpMobileRetNum,0)) cpMobileRetNum, 		
		SUM(ISNULL(cpMobileAccountNum,0)) cpMobileAccountNum,	
		0,--PR3
		0,
		0,
		0,
		0,
		0,--FF3
		0--Localrate
	FROM Info_DateReport WITH(NOLOCK)
	WHERE CountDate BETWEEN CONVERT(VARCHAR(8), @StartDate, 112) AND CONVERT(VARCHAR(8), @EndDate, 112) 
	AND InfoManager_ID = @ManagerUserID		
	GROUP BY Province_id
	ORDER BY Province_id
	
	--取出每一个省的系数
	CREATE TABLE #T_Info_Coeffi
	(		
		Province_ID INT,
		Coefficient DECIMAL
	)	
	INSERT INTO #T_Info_Coeffi
	SELECT Province_ID, Coefficient
	FROM (
		SELECT ROW_NUMBER() 
		OVER(PARTITION BY Province_ID ORDER BY BeginDate DESC) AS NO, Province_ID, Coefficient 
		FROM Info_Coeffi 
		WHERE BeginDate <= CONVERT(VARCHAR(8), @EndDate, 112)
		) a
	WHERE a.No = 1			

	----乘以相应的系数
	UPDATE #T SET 
		Coefficient = a.Coefficient,
		RealCompany = ROUND(RealCompany * a.Coefficient, 0),	--四舍五入
		Validcompany = ROUND(Validcompany * a.Coefficient, 0),	--四舍五入
		RealResume = FLOOR(Realresume * a.Coefficient),			--不四舍五入
		ValidResume = FLOOR(Validresume * a.Coefficient),		--不四舍五入	
		Pr3 = RealResume		
		
	FROM #T_Info_Coeffi a 
	WHERE a.Province_ID = #T.Province_ID
	
	-----以下是计算ParepeatRate和PaRepeat-----
	--取ParepeatRate和PaRepeat的数据源
	CREATE TABLE #T2
	(		
		Province_id INT,
		cnt DECIMAL,		
	)
	INSERT INTO #T2
	SELECT ProvinceID, COUNT(1) cnt
	FROM BsMobileSpread 
	WHERE AddDate > CONVERT(VARCHAR(10), @StartDate, 120) AND AddDate < CONVERT(VARCHAR(10), @EndDate, 120) 
	AND addman = @ManagerUserID 
	AND MobileNo IN 
	(
		SELECT a.Mobile 
		FROM PaMain a WITH(NOLOCK), cvMain b WITH(NOLOCK) 
		WHERE (Registermode = 1 OR Registermode = 11 OR RegisterType = 101 OR RegisterType = 102) 
		AND a.Id = b.paMainId AND b.valid > 0 AND a.adddate < bsmobilespread.adddate + 90 AND AddMan IN
		(
			SELECT ManagerUser_Id 
			FROM group_manageruser 
			WHERE group_id IN
			( 
				SELECT  group_id FROM group_manageruser WHERE ManagerUser_Id = @ManagerUserID
			)
		)
	) 
	AND usertype = 1  AND AccountDate IS NOT NULL 
	GROUP BY ProvinceID
	
	--更新RealResume>0的PaRepeatRate和PaRepeat
	UPDATE #T SET 
		PaRepeatRate = a.cnt / RealCompany,
		PaRepeat = a.cnt		
	FROM #T2 a 
	WHERE a.Province_ID = #T.Province_ID AND #T.RealCompany > 0	
	
	-----以下是计算CpRepeatRate和CpRepeat-----
	--取CpRepeatRate和CpRepeat的数据源
	CREATE TABLE #T3
	(		
		Province_id INT,
		cnt DECIMAL,		
	)
	INSERT INTO #T3
	SELECT ProvinceID, COUNT(1) cnt
	FROM BsMobileSpread 
	WHERE AddDate > CONVERT(VARCHAR(10), @StartDate, 120) AND AddDate < CONVERT(VARCHAR(10), @EndDate, 120)
	AND AddMan = @ManagerUserID 
	AND MobileNo IN 
	(
		SELECT Mobile 
		FROM caMain a WITH(NOLOCK), cpMain b WITH(NOLOCK) 
		WHERE a.cpMainId = b.ID	AND (RegisterMode = 1 OR registermode=11) 
		AND b.HasLicence = 1 AND a.regdate < bsmobilespread.adddate + 90 AND AddMan IN
		(
			SELECT ManagerUser_Id 
			FROM Group_manageruser 
			WHERE group_id IN
			( 
				SELECT group_id FROM group_manageruser where ManagerUser_Id = @ManagerUserID
			)
		)
	) 
	AND UserType = 0 AND AccountDate IS NOT NULL
	GROUP BY ProvinceID
	
	--更新RealResume>0的CpRepeatRate和CpRepeat
	UPDATE #T SET 
		CpRepeatRate = a.cnt / RealResume,
		CpRepeat = a.cnt		
	FROM #T3 a 
	WHERE a.Province_ID = #T.Province_ID AND #T.RealResume > 0
	
	--更新localrate
	DECLARE @localrate DECIMAL(18,2)
	IF EXISTS(SELECT localrate FROM infoachieve WITH(NOLOCK) WHERE yearmonth = @Month AND infomanager_id = @ManagerUserID)
		SELECT @localrate = localrate FROM infoachieve WITH(NOLOCK) WHERE yearmonth = @Month AND infomanager_id = @ManagerUserID
	ELSE
		SET @localrate = 100
	UPDATE #T SET	
		Localrate = @localrate,	
		PR3 = ROUND(RealCompany * @localrate, 0),	--四舍五入
		FF3 = PR3 + MobileAccount - paRepeat		
		
	--查询
	SELECT * FROM #T	
END


GO
/****** Object:  StoredProcedure [dbo].[bpInfo_DateReportByMonthStatisticsSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.1.27
--创建人：Andy
--说明：统计信息员统计核算功能个人月报
--#####################################################
--SELECT * FROM Info_DateReport
--bpInfo_DateReportByMonthStatisticsSelect  200311,1
CREATE PROCEDURE [dbo].[bpInfo_DateReportByMonthStatisticsSelect]
(
	@Month VARCHAR(6), --格式：201001
	@ManagerUserID INT
)
AS
BEGIN		
	DECLARE @StartDate DATETIME, @EndDate DATETIME
	--注：如11月的数据，应该是10-26到11.26	
	SET @EndDate = CONVERT(DATETIME, @Month + '26')	--11.26
	SET @StartDate = DATEADD(MONTH, -1, @EndDate)	--10.26
	--PRINT CONVERT(VARCHAR(8), @StartDate, 112) 
	--PRINT CONVERT(VARCHAR(8), @EndDate, 112) 
	CREATE TABLE #T
	(		
		Province_id INT,
		Coefficient DECIMAL,		
		RealCompany INT,
		Companyregnum_our INT,
		Validcompany INT,
		Realresume INT,
		Validresume INT,		
		Personregnum_our INT,
		Homepage INT,
		Allresume INT,
		MobileNum INT,
		cpMobileNum INT,
		MobileReturn INT,		
		MobileAccount INT,		
		cpMobileRetNum INT,		
		cpMobileAccountNum INT,
		Mc INT,
		MM3 INT,
	)
	
	--查出每一个省合计后的的原始数据
	INSERT INTO #T	
	SELECT 		
		Province_id,	
		0,			
		SUM(RealCompany) RealCompany, 
		SUM(Companyregnum_our) Companyregnum_our, 
		SUM(Validcompany) Validcompany,
		SUM(Realresume) Realresume, 
		SUM(Validresume) Validresume,
		SUM(Personregnum_our) Personregnum_our, 
		SUM(Homepage) Homepage, 
		SUM(Allresume) Allresume, 
		SUM(MobileNum) MobileNum, 
		SUM(cpMobileNum) cpMobileNum, 
		SUM(ISNULL(MobileReturn,0)) MobileReturn, 		
		SUM(ISNULL(MobileAccount,0)) MobileAccount, 		
		SUM(ISNULL(cpMobileRetNum,0)) cpMobileRetNum, 		
		SUM(ISNULL(cpMobileAccountNum,0)) cpMobileAccountNum,	
		0,
		0
	FROM Info_DateReport WITH(NOLOCK)
	WHERE CountDate BETWEEN CONVERT(VARCHAR(8), @StartDate, 112) AND CONVERT(VARCHAR(8), @EndDate, 112) 
	AND InfoManager_ID = @ManagerUserID	
	GROUP BY Province_id
	
	--取出每一个省的系数
	CREATE TABLE #T_Info_Coeffi
	(		
		Province_ID INT,
		Coefficient DECIMAL
	)	
	INSERT INTO #T_Info_Coeffi
	SELECT Province_ID, Coefficient
	FROM (
		SELECT ROW_NUMBER() 
		OVER(PARTITION BY Province_ID ORDER BY BeginDate DESC) AS NO, Province_ID, Coefficient 
		FROM Info_Coeffi 
		WHERE BeginDate <= CONVERT(VARCHAR(8), @EndDate, 112)
		) a
	WHERE a.No = 1			

	----乘以相应的系数
	UPDATE #T SET 
		Coefficient = a.Coefficient,
		RealCompany = ROUND(RealCompany * a.Coefficient, 0),	--四舍五入
		Validcompany = ROUND(Validcompany * a.Coefficient, 0),	--四舍五入
		Realresume = FLOOR(Realresume * a.Coefficient),			--不四舍五入
		Validresume = FLOOR(Validresume * a.Coefficient),		--不四舍五入	
		MC = ROUND((RealCompany + cpMobileAccountNum) * a.Coefficient, 0),	--四舍五入	
		MM3 = FLOOR((Realresume + MobileAccount) * a.Coefficient)		--不四舍五入	
	FROM #T_Info_Coeffi a 
	WHERE a.Province_ID = #T.Province_ID
	
	--查询
	SELECT * FROM #T	
END


GO
/****** Object:  StoredProcedure [dbo].[bpInfo_DateReportByProvinceMonthStatisticsSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.2.4
--创建人：Andy
--说明：统计信息员统计核算功能省份月报
--#####################################################
--bpInfo_DateReportByProvinceMonthStatisticsSelect  '200311'
CREATE PROCEDURE [dbo].[bpInfo_DateReportByProvinceMonthStatisticsSelect]
(
	@YearMonth VARCHAR(6) --格式：201501			
)
AS
BEGIN	
	SELECT 
		Province_ID,
		(SELECT ProvinceName FROM dcProvince WITH(NOLOCK) WHERE ID = Info_DateReport.province_id) Province,
		SUM(companyregnum_our) companyregnum_our,
		SUM(Personregnum_Our) Personregnum_Our,
		SUM(ValidCompany) ValidCompany,sum(ValidResume) ValidResume,
		SUM(Homepage) Homepage,
		SUM(RealCompany) RealCompany,
		SUM(RealResume) RealResume,
		SUM(AllResume) AllResume,
		SUM(PersonRegNum_Our_QQ) PersonRegNum_Our_QQ,
		SUM(MobileNum) MobileNum,
		SUM(MobileReturn) MobileReturn,
		SUM(MobileAccount) MobileAccount,
		SUM(cpMobileNum) cpMobileNum,
		SUM(cpMobileRetNum) cpMobileRetNum,
		SUM(cpMobileAccountNum) cpMobileAccountNum 
	FROM Info_DateReport WITH(NOLOCK) 
	WHERE CountDate/100 = @YearMonth
	GROUP BY Province_id
END
GO
/****** Object:  StoredProcedure [dbo].[bpInfo_DateReportByProvinceStatisticsSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.1.27
--创建人：Andy
--说明：统计信息员统计核算功能个人日报（按省分解）
--#####################################################
--SELECT * FROM Info_DateReport
--bpInfo_DateReportByProvinceStatisticsSelect 1, 20031110
CREATE PROCEDURE [dbo].[bpInfo_DateReportByProvinceStatisticsSelect]
(
	@ManagerUserID INT,
	@CountDate VARCHAR(8)
)
AS
BEGIN		
	CREATE TABLE #T
	(		
		Province_id INT,		
		RealCompany INT,
		Companyregnum_our INT,
		Validcompany INT,
		Realresume INT,
		Validresume INT,		
		Personregnum_our INT,
		Homepage INT,
		Allresume INT,
		MobileNum INT,
		cpMobileNum INT,
		MobileReturn INT,		
		MobileAccount INT,		
		cpMobileRetNum INT,		
		cpMobileAccountNum INT,		
	)
	--查出原始数据
	INSERT INTO #T	
	SELECT 				
		Province_id,			
		SUM(RealCompany) RealCompany, 
		SUM(Companyregnum_our) Companyregnum_our, 
		SUM(Validcompany) Validcompany,
		SUM(Realresume) Realresume, 
		SUM(Validresume) Validresume,
		SUM(Personregnum_our) Personregnum_our, 
		SUM(Homepage) Homepage, 
		SUM(Allresume) Allresume, 
		SUM(MobileNum) MobileNum, 
		SUM(cpMobileNum) cpMobileNum, 
		SUM(ISNULL(MobileReturn,0)) MobileReturn, 		
		SUM(ISNULL(MobileAccount,0)) MobileAccount, 		
		SUM(ISNULL(cpMobileRetNum,0)) cpMobileRetNum, 		
		SUM(ISNULL(cpMobileAccountNum,0)) cpMobileAccountNum 		
	FROM Info_DateReport WITH(NOLOCK)
	WHERE CountDate = @CountDate AND InfoManager_ID = @ManagerUserID
	GROUP BY province_id 
	
	--取出每一个省的系数
	CREATE TABLE #T_Info_Coeffi
	(		
		Province_ID INT,
		Coefficient DECIMAL
	)	
	INSERT INTO #T_Info_Coeffi
	SELECT Province_ID, Coefficient
	FROM (
		SELECT ROW_NUMBER() 
		OVER(PARTITION BY Province_ID ORDER BY BeginDate DESC) AS NO, Province_ID, Coefficient 
		FROM Info_Coeffi WHERE BeginDate <= @CountDate) a
	WHERE a.No = 1		
		
	----更新某几列的系数
	UPDATE #T SET 
		RealCompany = ROUND(RealCompany * a.Coefficient, 0),	--四舍五入
		Validcompany = ROUND(Validcompany * a.Coefficient, 0),	--四舍五入
		Realresume = FLOOR(Realresume * a.Coefficient),			--不四舍五入
		Validresume = FLOOR(Validresume * a.Coefficient)		--不四舍五入
	FROM #T_Info_Coeffi a 
	WHERE a.Province_ID = #T.Province_ID
	
	--查询
	SELECT * FROM #T	
END


GO
/****** Object:  StoredProcedure [dbo].[bpInfoAchieveByMonthStatisticsSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.2.3
--创建人：Andy
--说明：统计信息员统计核算个人个人月报
--#####################################################
--SELECT * FROM Info_DateReport
--bpInfoAchieveByMonthStatisticsSelect  1,5,'201001',32
CREATE PROCEDURE [dbo].[bpInfoAchieveByMonthStatisticsSelect]
(		
	@CurManagerUserID INT,--当前登录用户ID		
	@Privi INT,--当前用户的权限
	@YearMonth VARCHAR(6),
	@Dept INT	
)
AS
BEGIN		
	DECLARE @StartDate DATETIME, @EndDate DATETIME
	--注：如11月的数据，应该是10-26到11.26	
	SET @EndDate = CONVERT(DATETIME, @YearMonth + '26')	--11.26
	SET @StartDate = DATEADD(MONTH, -1, @EndDate)	--10.26
	--PRINT CONVERT(VARCHAR(8), @StartDate, 112) 
	--PRINT CONVERT(VARCHAR(8), @EndDate, 112) 
	
	--查出原始数据
	SELECT 
		a.Add_company,
		a.Add_resume,
		a.Realcompany,
		a.Realresume,
		a.Real_company,
		a.Real_resume,
		a.Homepage,
		a.Allresume,
		b.ID ManagerUserID,
		b.Name,
		dept.Deptname,
		dept.ID deptID,
		(a.Real_company * 6 + a.Real_resume * 0.5) cnt,
		b.Name_eng,
		b.Status,
		b.Type,
		a.Salary,
		a.Salary_control,
		a.Localrate, 
		ISNULL(MobileNum, 0) MobileNum, 
		ISNULL(MobileReturn, 0) MobileReturn, 
		ISNULL(cpMobileNum, 0) cpMobileNum, 
		ISNULL(cpMobileRetNum, 0) cpMobileRetNum,		
		paRepeatRate, 
		cpRepeatRate		
	INTO #T		
	FROM InfoAchieve a WITH(NOLOCK), ManagerUser b WITH(NOLOCK), Dept WITH(NOLOCK) 
	WHERE b.ID = a.InfoManager_ID AND b.DeptID = Dept.ID AND a.YearMonth = @YearMonth
	AND b.ID IN 
		(
		SELECT ID FROM ManagerUser WITH(NOLOCK) 
		WHERE DeptID IN (SELECT ID FROM Dept WHERE Superior = 11 OR id = 11 OR id = 26)
		)
	AND b.ID IN (SELECT ID FROM dbo.LowerUserAll(@CurManagerUserID, @Privi)) 	

	--添加两列
	ALTER TABLE #T ADD paRepeat DECIMAL
	ALTER TABLE #T ADD cpRepeat DECIMAL	
	ALTER TABLE #T ADD SumMobileNum DECIMAL
	ALTER TABLE #T ADD SumcpMobileNum DECIMAL
	--计算合计的数据源(计算paRepeat和cpRepeat)
	SELECT * INTO #T2 FROM bsMobileSpread WHERE AddDate > @StartDate AND AddDate < @EndDate
	--计算合计的数据源(计算MobileNum和cpMobileNum)
	SELECT *
	INTO #T3 
	FROM Info_DateReport WITH(NOLOCK) 
	WHERE countdate >= CONVERT(VARCHAR(8), @StartDate, 112) AND countdate <= CONVERT(VARCHAR(8), @EndDate, 112)
	--SELECT * FROM Info_DateReport
	--更新合计
	UPDATE #T SET
		paRepeat = (SELECT COUNT(1) FROM #T2 c 
			WHERE c.AddMan = #T.ManagerUserID AND c.MobileNo IN 
			(
				SELECT a.Mobile FROM paMain a WITH(NOLOCK), cvMain b WITH(NOLOCK)
				WHERE (RegisterMode = 1 OR RegisterMode = 11 OR RegisterType = 101 OR RegisterType = 102) 
				AND a.Id = b.paMainId AND b.valid > 0
			) 
			AND c.Usertype = 1),
		cpRepeat = (SELECT COUNT(1) FROM #T2 c 
			WHERE c.AddMan = #T.ManagerUserID AND c.MobileNo IN 
			(
				SELECT Mobile FROM caMain a WITH(NOLOCK), cpMain b WITH(NOLOCK) 
				WHERE a.cpMainId = b.ID	AND (RegisterMode = 1 OR RegisterMode = 11) AND b.HasLicence = 1 
			) 
			AND c.Usertype = 0),
		SumMobileNum = (SELECT SUM(MobileNum) FROM #T3 d WHERE d.infomanager_id = #T.ManageruserID),
		SumcpMobileNum = (SELECT SUM(cpMobileNum) FROM #T3 d WHERE d.infomanager_id = #T.ManageruserID)
	
	--查询
	IF @Dept > 0
		SELECT * FROM #T WHERE DeptID = @Dept
	ELSE
		SELECT * FROM #T 	
END
GO
/****** Object:  StoredProcedure [dbo].[bpInfoVerifyReportByAddManMonthStatisticsSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.2.3
--创建人：Andy
--说明：统计信息员统计核算个人月度日报或者日报
--#####################################################
--SELECT * FROM Info_DateReport
--bpInfoVerifyReportByAddManMonthStatisticsSelect  1,1,5,6
CREATE PROCEDURE [dbo].[bpInfoVerifyReportByAddManMonthStatisticsSelect]
(	
	@AddMan INT,			--被查询的用户
	@CurManagerUserID INT,	--当前登录用户ID		
	@Privi INT,				--当前用户的权限
	@Length INT				--8表示月报，10表示日报
)
AS
BEGIN
	SET NOCOUNT ON
	
	SELECT 
		CountDate, 
		SUM(cvEmailPrevMonth) cvEmailPrevMonth, 
		SUM(cvEmailThisMonth) cvEmailThisMonth, 
		SUM(cvMobilePrevMonth) cvMobilePrevMonth, 
		SUM(cvMobileThisMonth) cvMobileThisMonth, 
		SUM(cpEmailPrevMonth) cpEmailPrevMonth, 
		SUM(cpEmailThisMonth) cpEmailThisMonth, 
		SUM(cpMobilePrevMonth) cpMobilePrevMonth, 
		SUM(cpMobileThisMonth) cpMobileThisMonth 
	FROM InfoVerifyReport WITH(NOLOCK)	
	WHERE AddMan = @AddMan 
	AND AddMan IN (SELECT ID FROM dbo.LowerUserAll(@CurManagerUserID, @Privi)) 
	AND LEN(COUNTDate) = @Length 
	GROUP BY CountDate 
	ORDER BY CountDate DESC	
	
	SET NOCOUNT OFF
END


GO
/****** Object:  StoredProcedure [dbo].[bpInfoVerifyReportByProvinceSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.2.3
--创建人：Andy
--说明：查询信息员统计核算个人月度日报(按省分解)
--#####################################################
--SELECT * FROM Info_DateReport
--bpInfoVerifyReportByProvinceSelect  1,'2010-01-01'
Create PROCEDURE [dbo].[bpInfoVerifyReportByProvinceSelect]
(	
	@ManagerUserID INT,
	@CountDate VARCHAR(10)
)
AS
BEGIN
	SET NOCOUNT ON
	
	SELECT *, (SELECT ProvinceName FROM dcProvince WHERE id = ProvinceID) ProvinceName 
	FROM InfoVerifyReport 
	WHERE AddMan= @ManagerUserID AND CountDate = @CountDate 
	ORDER BY ProvinceID
	
	SET NOCOUNT OFF
END


GO
/****** Object:  StoredProcedure [dbo].[bpInnerer_Count_DetailByInnerer_CountIdSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.08.27
--创建人：Nick
--说明：根据Innerer_CountId查询Innerer_Count_Detail
--#####################################################
CREATE PROCEDURE [dbo].[bpInnerer_Count_DetailByInnerer_CountIdSelect]
(
	@ID INT
)
AS
BEGIN
	SELECT innerPage,Page_Count FROM Innerer_Count_Detail WITH(NOLOCK) WHERE Innerer_CountId = @ID ORDER BY innerpage
END

GO
/****** Object:  StoredProcedure [dbo].[bpInnerer_Count_DetailByInnerpageSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.9.2
--创建人：Nick
--说明：来源分析统计 内页（月报详细）
--#####################################################
CREATE PROCEDURE [dbo].[bpInnerer_Count_DetailByInnerpageSelect]
(
	@Innerpage INT,
	@StartDate VARCHAR(20),
	@EndDate VARCHAR(20),
	@Site VARCHAR(10)
)
AS
SET NOCOUNT oN
BEGIN
	IF @Site = '100'
	BEGIN
		SELECT ISNULL(SUM(Page_Count),0) cnt 
		FROM innerer_count_detail a WITH(NOLOCK),innerer_countNew b 
		WHERE b.province_id =0 
		AND a.Innerpage=@Innerpage 
		AND b.countdate>=@StartDate 
		AND b.countdate<=@EndDate 
		AND b.id=a.Innerer_CountId 

		SELECT ISNULL(SUM(a.Page_Count), 0) cnt FROM
		 innerer_count_detail a with(nolock),innerer_countNew  b 
		 WHERE b.id=a.Innerer_CountId 
		 AND  b.province_id =0 
		 AND a.Innerpage=@Innerpage 
		 AND b.countdate>=@StartDate 
		 AND b.countdate<=@EndDate 
		 AND  b.Referer NOT LIKE '%opendata.baidu.com%' 
	END
	IF @Site = ''
	BEGIN
		SELECT province_id,ISNULL(SUM(Page_Count), 0) cnt,southnorth  
		FROM(
			SELECT a.ID as Province_ID , D.Page_Count,southnorth  
			FROM dcProvince a LEFT JOIN ( 
				SELECT c.Page_Count, b.Province_ID 
				From Innerer_CountNew b left join innerer_count_detail c 
				ON c.Innerer_CountId = b.id  
				WHERE countdate>=@StartDate 
				AND countdate<=@EndDate
				AND c.Innerpage=@Innerpage 
				AND province_id < 999  
				AND (
					LEN(province_id)=2 OR LEN(province_id)=4 OR province_id=0
				)
			)d  
			ON a.ID  = d.Province_ID
		) E GROUP BY province_id,southnorth ORDER BY CASE southnorth WHEN 4 THEN 1 ELSE southnorth END DESC,province_id
	END
	ELSE IF @Site = '100'
	BEGIN
		SELECT RIGHT(Province_ID,2)as Province_ID,isnull(sum(Page_Count), 0)  cnt,southnorth  
		FROM(
			SELECT a.ID as Province_ID , D.Page_Count,southnorth  
			FROM dcProvince a LEFT JOIN ( 
				SELECT c.Page_Count, b.Province_ID 
				FROM Innerer_CountNew b left join innerer_count_detail c 
				ON c.Innerer_CountId = b.id  
				WHERE countdate>=@StartDate 
				AND countdate<=@EndDate
				AND c.Innerpage=@Innerpage And province_id < 999
			) d  ON a.id=right(d.Province_ID,2) )E
			GROUP BY right(province_id,2),southnorth ORDER BY CASE southnorth when 4 THEN 1 ELSE southnorth END DESC,RIGHT(province_id,2)
	END
	ELSE
	BEGIN
		SELECT RIGHT(Province_ID,2)as Province_ID,isnull(sum(Page_Count), 0)  cnt,southnorth  
		FROM( 
			SELECT a.ID as Province_ID , E.Page_Count,southnorth  
			FROM dcProvince a LEFT JOIN ( 
				SELECT c.Page_Count, b.Province_ID 
				From Innerer_CountNew b left join innerer_count_detail c 
				ON c.Innerer_CountId = b.id  
				WHERE countdate>=@StartDate 
				AND countdate<=@EndDate
				AND c.Innerpage=@Innerpage 
				AND b.province_id like ''+@Site+'__' 
				AND (len(b.province_id)=3 or len(b.province_id)=5)) E  
				ON a.id=right(E.Province_id,2)) F  
				GROUP BY  right(province_id,2),southnorth ORDER BY CASE southnorth when 4 then 1 else southnorth END DESC,province_id
	END
END

GO
/****** Object:  StoredProcedure [dbo].[bpInnerer_Count_DetailByProvinceIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.9.2
--创建人：Nick
--说明：来源分析统计 内页（月报详细）
--#####################################################
CREATE PROCEDURE [dbo].[bpInnerer_Count_DetailByProvinceIDSelect]
(
	@Innerpage INT,
	@StartDate VARCHAR(20),
	@EndDate VARCHAR(20),
	@Site VARCHAR(10),
	@ProvinceID VARCHAR(20)
)
AS
BEGIN
	DECLARE @SQL VARCHAR(MAX)
	SET @SQL = 'SELECT b.countdate,SUM(a.Page_Count)cnt,a.innerPage 
		FROM innerer_count_detail a WITH(NOLOCK),innerer_countNew b WHERE '
	IF @Site = '3'
	BEGIN
		SET @SQL = @SQL + ' b.province_id like ''%'+right(@ProvinceID,2)+'''' 
	END
	ELSE
	BEGIN
		SET @SQL = @SQL + ' b.province_id ='+ @ProvinceID
	END
	SET @SQL = @SQL + ' AND a.innerPage='+CONVERT(VARCHAR(10),@Innerpage)+' AND  a.innerer_countid= b.id  
	AND b.countdate>='''+@StartDate+''' AND b.countdate<='''+@EndDate+''' 
	GROUP BY b.countdate,a.innerPage 
	ORDER BY b.countdate, a.innerPage'
	EXEC(@SQL)
END

GO
/****** Object:  StoredProcedure [dbo].[bpInnerer_Count_KeywordsByReferer_Count_IDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.08.27
--创建人：Nick
--说明：根据referer_count_id查询innerer_count_keywords
--#####################################################
create PROCEDURE [dbo].[bpInnerer_Count_KeywordsByReferer_Count_IDSelect]
(
	@Referer_Count_ID INT
)
AS
BEGIN
	SELECT howmany,keywords 
	FROM innerer_count_keywords WITH(NOLOCK) 
	WHERE referer_count_id=@Referer_Count_ID 
	ORDER BY howmany DESC
END

GO
/****** Object:  StoredProcedure [dbo].[bpInnerer_CountByDayItemSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--sean 2014-8-21
--修改HARRY Innerer_Count改为Innerer_CountNew
--修改时间 2015/3/30
CREATE PROCEDURE [dbo].[bpInnerer_CountByDayItemSelect]
(
	@ProvinceId INT,
	@Site INT,
	@BD VARCHAR(6)
)
AS
BEGIN
	SET NOCOUNT ON
	DECLARE @Sd AS DATETIME, @ED DATETIME, @I INT, @P VARCHAR(30)
	SET @Sd = CONVERT(DATETIME, @BD + '26')
	IF @Sd > GETDATE()
		SET @Sd = CONVERT(VARCHAR(8), DATEADD(MONTH, -1, GETDATE()), 120) + '26'

	IF @Site = 3
	BEGIN
		IF LEN(@ProvinceId) IN(3, 5)
			SET @ProvinceId = RIGHT(@ProvinceId, LEN(@ProvinceId) - 1)
		SET @p = LTRIM(STR(@ProvinceId)) + ',1' + LTRIM(STR(@ProvinceId)) + ',2' + LTRIM(STR(@ProvinceId))
	END
	ELSE
		SET @p = LTRIM(STR(@ProvinceId))	

	
	IF DATEADD(MONTH, 1, @Sd) > GETDATE()
		SET @Ed = CONVERT(VARCHAR(10), GETDATE(), 120)
	ELSE
		SET @Ed = DATEADD(Month, 1, @Sd) - 1

	CREATE TABLE #d(ID INT IDENTITY(1, 1), CountDate VARCHAR(8))

	INSERT #d
	SELECT WorkDate
	FROM Oadb..WorkDate
	WHERE WorkDate BETWEEN CONVERT(VARCHAR(8), @sd, 112) AND CONVERT(VARCHAR(8), @Ed, 112)

	SELECT b.Item_Id, a.CountDate, SUM(a.HowMany) HowMany
	INTO #r
	FROM Referer_Item_Keywords b WITH(NOLOCK),
		Innerer_CountNew a WITH(NOLOCK)
	WHERE a.Province_Id IN(SELECT * FROM dbo.FnSplit(@p, ','))
	AND CHARINDEX(b.Keywords, a.Referer) > 0
	AND a.CountDate IN(SELECT CountDate FROM #d)
	GROUP BY b.Item_Id, a.CountDate
	ORDER BY b.Item_Id, a.CountDate

	DECLARE @Sql VARCHAR(MAX)
	SET @Sql = 'CREATE TABLE LogDb..a_Tmp(ID INT, Item_Name NVARCHAR(50), '
	SELECT @Sql = @Sql + 'Col' + LTRIM(STR(Id)) + ' VARCHAR(10), ' FROM #d
	SET @Sql = @Sql + 'Col100 VARCHAR(10))'
	EXEC(@Sql)
	SELECT * INTO #t FROM LogDb..a_Tmp
	DROP TABLE LogDb..a_Tmp

	SET @Sql = 'INSERT INTO #t SELECT 0, '''', '''
	SELECT @Sql = @sql + RIGHT(CountDate, 4) + ''' , ''' FROM #d ORDER BY ID
	SET @Sql = @sql + '行合计'''
	EXEC(@Sql)

	INSERT INTO #t(Id, Item_Name) SELECT Id, Item_Name FROM Referer_Item
	INSERT INTO #t(Id, Item_Name) SELECT 999, '列合计'
	SET @i = 0
	WHILE EXISTS(SELECT 'x' FROM #d WHERE ID > @i)
	BEGIN
		SELECT TOP 1 @i = Id FROM #d WHERE Id > @i ORDER BY Id
		SET @Sql = 'UPDATE a SET a.Col' + LTRIM(STR(@i)) + ' = b.HowMany FROM #t a, #r b, #d c WHERE a.Id = b.Item_Id AND c.CountDate = b.CountDate AND c.Id = ' + LTRIM(STR(@i))
		--PRINT(@Sql)
		EXEC(@Sql)
		SET @Sql = 'UPDATE #t SET Col' + LTRIM(STR(@i)) + ' = (SELECT SUM(CONVERT(INT, Col' + LTRIM(STR(@i)) + ')) FROM #t WHERE Id > 0 AND Id < 999) WHERE Id = 999'
		--PRINT(@Sql)
		EXEC(@Sql)
	END
	SELECT @Sql = 'UPDATE #t SET Col100 = '
	SELECT @Sql = @Sql + 'CONVERT(INT, ISNULL(Col' + LTRIM(STR(ID)) + ', 0)) + ' FROM #d
	SELECT @Sql = @Sql + '0 WHERE Id > 0'
	EXEC(@Sql)
	
	SELECT * FROM #t ORDER BY CASE ID WHEN 0 THEN 0 WHEN 999 THEN 999 ELSE 2 END, Item_Name
END

GO
/****** Object:  StoredProcedure [dbo].[bpInnerer_CountByDaySelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.08.25
--创建人：Nick
--说明：来源分析统计 内页（日报）
--#####################################################
CREATE PROCEDURE [dbo].[bpInnerer_CountByDaySelect]
(
	@Site VARCHAR(10),
	@Day VARCHAR(8)
)
AS
BEGIN
	DECLARE @WHERE VARCHAR(MAX)
	SET @WHERE  = 'SUM(CASE VersionId WHEN 0 Then HowMany Else 0 END) [51RC]'
	DECLARE @CateID INT,@Province VARCHAR(20)
	DECLARE c_CateGoryID CURSOR FAST_FORWARD FOR
	--读取
	SELECT CASE @Site WHEN '1' THEN 100+ID WHEN '2' THEN 200+ID ELSE ID END,province  
	FROM province WITH(NOLOCK) 
	ORDER BY CASE southnorth WHEN 4 THEN 1 ELSE southnorth END DESC,id
	-- 打开游标.
	OPEN c_CateGoryID;
		WHILE 1=1
		BEGIN
		FETCH NEXT FROM c_CateGoryID INTO @CateID,@Province
		IF @Site = '100'
		BEGIN
			SET @WHERE = @WHERE+',SUM(CASE LEFT(VersionId, 2)  WHEN '+CONVERT(VARCHAR(20),@CateID)+' Then HowMany Else 0 END) ['+@Province+']'
		END
		ELSE
		BEGIN
			SET @WHERE = @WHERE+',SUM(CASE Province_Id WHEN '+CONVERT(VARCHAR(20),@CateID)+' Then HowMany Else 0 END) ['+@Province+']'
		END
		IF @@fetch_status<> 0 BREAK
	END
	-- 关闭游标
	CLOSE c_CateGoryID;
	-- 释放游标.
	DEALLOCATE c_CateGoryID;

	DECLARE @SQL VARCHAR(MAX)
	SET @SQL = 'SELECT '+@WHERE+',SUM(howmany) cnt,item_Name 
		FROM innerer_countNew a WITH(NOLOCK),referer_item_keywords b WITH(NOLOCK),referer_item c WITH(NOLOCK) 
		WHERE Item_Id=c.ID And countdate='+@Day+' and charindex(b.keywords, a.referer) >0'
	IF @Site = '2'
	BEGIN
		SET @SQL = @SQL+'  AND Province_Id LIKE ''2__''  '
	END
	ELSE IF @Site = '1'
	BEGIN
		SET @SQL = @SQL+'  AND Province_Id LIKE ''1__'' '
	END
	--ELSE 
	--BEGIN
	--	SET @SQL = @SQL+' AND LEN(Province_Id) <= 2 '
	--END
	SET @SQL = @SQL + ' GROUP BY item_id,item_Name ORDER BY item_Name'
	EXEC(@SQL)
END

GO
/****** Object:  StoredProcedure [dbo].[bpInnerer_CountBYIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.08.27
--创建人：Nick
--说明：根据ID查询innerer_countNew
--#####################################################
create PROCEDURE [dbo].[bpInnerer_CountBYIDSelect]
(
	@ID INT
)
AS
BEGIN
	SELECT referer 
	FROM innerer_countNew WITH(NOLOCK) 
	WHERE ID = @ID
END

GO
/****** Object:  StoredProcedure [dbo].[bpInnerer_CountByProvinceIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.08.27
--创建人：Nick
--说明：根据province_id查询innerer_countNew
--#####################################################
CREATE PROCEDURE [dbo].[bpInnerer_CountByProvinceIDSelect]
(
	@ProvinceID VARCHAR(10),
	@CountDate VARCHAR(20)
)
AS
BEGIN
	DECLARE @SQL VARCHAR(MAX)
	SET @SQL = 'SELECT howmany,referer,id FROM innerer_countNew WITH(NOLOCK) WHERE '
	IF LEN(@ProvinceID) = 3 AND LEFT(@ProvinceID,1)='3'
	BEGIN
		SET @SQL = @SQL + ' province_id like ''%'+RIGHT(@ProvinceID,2)+'''  '
	END
	ELSE
	BEGIN
		SET @SQL = @SQL + ' province_id = '+@ProvinceID
	END
	SET @SQL = @SQL + ' and countdate= '+ @CountDate +' ORDER BY howmany DESC'
	EXEC(@SQL)
END

GO
/****** Object:  StoredProcedure [dbo].[bpInnerer_YearmonthByDcProvinceSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.9.2
--创建人：Nick
--说明：来源分析 内页（月报）
--#####################################################
create PROCEDURE [dbo].[bpInnerer_YearmonthByDcProvinceSelect]
(
	@Site VARCHAR(10),
	@YearMonth VARCHAR(6)
)
AS
BEGIN
	IF @Site = ''
	BEGIN
		SELECT SUM(howmany) howmany 
		FROM innerer_yearmonth WITH(NOLOCK) 
		WHERE yearmonth=@YearMonth
		AND (Province_id  not LIKE '1__' and Province_id not LIKE '2__')
	END
	ELSE IF @Site = '2'
	BEGIN
		SELECT SUM(howmany) howmany
		FROM innerer_yearmonth WITH(NOLOCK) 
		WHERE Province_id LIKE '2__' 
		AND yearmonth=@YearMonth
	END
	ELSE IF @Site = '1'
	BEGIN
		SELECT SUM(howmany) howmany 
		FROM innerer_yearmonth WITH(NOLOCK) 
		WHERE Province_id LIKE '1__' 
		AND yearmonth=@YearMonth
	END
	ELSE
	BEGIN
		SELECT SUM(howmany) howmany 
		FROM innerer_yearmonth WITH(NOLOCK) 
		WHERE yearmonth=@YearMonth
	END
END

GO
/****** Object:  StoredProcedure [dbo].[bpInnerer_YearmonthByYearMonthSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.9.2
--创建人：Nick
--说明：来源分析统计 内页（月报）
--修改Harry修改统计错误2015-12-29
--#####################################################
CREATE PROCEDURE [dbo].[bpInnerer_YearmonthByYearMonthSelect]
(
	@Site VARCHAR(10),
	@YearMonth VARCHAR(6)
)
AS
BEGIN
	DECLARE @WHERE VARCHAR(MAX)
	SET @WHERE  = 'SUM(CASE Province_Id WHEN 0 Then HowMany Else 0 END) [51RC]'
	DECLARE @CateID INT,@Province VARCHAR(20)
	DECLARE c_CateGoryID CURSOR FAST_FORWARD FOR
	--读取
	SELECT CASE @Site WHEN '1' THEN 100+ID WHEN '2' THEN 200+ID ELSE ID END ,province  
	FROM province WITH(NOLOCK) 
	ORDER BY CASE southnorth WHEN 4 THEN 1 ELSE southnorth END DESC,id
	-- 打开游标.
	OPEN c_CateGoryID;
		WHILE 1=1
		BEGIN
		FETCH NEXT FROM c_CateGoryID INTO @CateID,@Province
		IF @Site=100
		BEGIN
			SET @WHERE = @WHERE+',SUM(CASE right(Province_Id,2) WHEN '+CONVERT(VARCHAR(20),@CateID)+' Then HowMany Else 0 END) ['+@Province+']'
		END
		ELSE
		BEGIN
			SET @WHERE = @WHERE+',SUM(CASE Province_Id WHEN '+CONVERT(VARCHAR(20),@CateID)+' Then HowMany Else 0 END) ['+@Province+']'
		END
		IF @@fetch_status<> 0 BREAK
	END
	-- 关闭游标
	CLOSE c_CateGoryID;
	-- 释放游标.
	DEALLOCATE c_CateGoryID;

	DECLARE @SQL VARCHAR(MAX)
	SET @SQL = 'SELECT '+@WHERE+',SUM(howmany) cnt,item_Name FROM innerer_yearmonth WITH(NOLOCK) WHERE YearMonth='+@YearMonth
	IF @Site = '2'
	BEGIN
		SET @SQL = @SQL+'  AND Province_Id LIKE ''2__''  '
	END
	ELSE IF @Site = '1'
	BEGIN
		SET @SQL = @SQL+'  AND Province_Id LIKE ''1__'' '
	END 
	ELSE IF @Site = ''
	BEGIN
		SET @SQL = @SQL+' AND LEN(Province_Id) <= 2 '
	END
	SET @SQL = @SQL+' GROUP BY item_Name ORDER BY item_Name'
	print @SQL
	EXEC(@SQL)
END

GO
/****** Object:  StoredProcedure [dbo].[bpInnererByKeyWordsSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.08.27
--创建人：Nick
--说明：根据keywords查询Innerer
--#####################################################
create PROCEDURE [dbo].[bpInnererByKeyWordsSelect]
(
	@ProvinceID VARCHAR(10)
)
AS
BEGIN
	DECLARE @SQL VARCHAR(MAX)
	SET @SQL = 'SELECT keywords, Count(*) cnt FROM innerer with(nolock) WHERE '
	IF LEN(@ProvinceID) = 3 AND LEFT(@ProvinceID,1)='3'
	BEGIN
		SET @SQL = @SQL + ' province_id like ''%'+RIGHT(@ProvinceID,2)+'''  '
	END
	ELSE
	BEGIN
		SET @SQL = @SQL + ' province_id = '+@ProvinceID
	END
	SET @SQL  = @SQL + ' GROUP BY keywords ORDER BY COUNT(*) DESC'
	EXEC(@SQL)
END

GO
/****** Object:  StoredProcedure [dbo].[bpInnererByProvinceIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.08.27
--创建人：Nick
--说明：根据province_id查询Innerer
--#####################################################
CREATE PROCEDURE [dbo].[bpInnererByProvinceIDSelect]
(
	@ProvinceID VARCHAR(10),
	@Search_text VARCHAR(50),
	@Search_action  INT,
	@search_item INT,
	@InnerPage INT
)
AS
BEGIN
	DECLARE @SQL VARCHAR(MAX)
	SET @SQL = 'SELECT referer,logindate,ip,keywords,versionid,innerpage FROM Innerer WITH(NOLOCK) WHERE '
	IF LEN(@ProvinceID) = 3 AND LEFT(@ProvinceID,1)='3'
	BEGIN
		SET @SQL = @SQL + ' province_id like ''%'+RIGHT(@ProvinceID,2)+'''  '
	END
	ELSE
	BEGIN
		SET @SQL = @SQL + ' province_id = '+@ProvinceID
	END
	IF @search_item = 1 AND @Search_text<>''
	BEGIN
		IF @Search_action = 1
		BEGIN
			SET @SQL = @SQL + ' AND referer like '''+@Search_text+'%''  '
		END
		IF @Search_action = 2
		BEGIN
			SET @SQL = @SQL + ' AND referer like ''%'+@Search_text+'%''  '
		END
	END
	IF @search_item = 2 AND @Search_text<>''
	BEGIN
		IF @Search_action = 1
		BEGIN
			SET @SQL = @SQL + ' AND IP like '''+@Search_text+'%''  '
		END
		IF @Search_action = 2
		BEGIN
			SET @SQL = @SQL + ' AND IP like ''%'+@Search_text+'%''  '
		END
	END
	IF @InnerPage > 0
	BEGIN
		SET @SQL = @SQL + ' AND innerpage = '+CONVERT(VARCHAR(10),@InnerPage)
	END
	SET @SQL = @SQL + ' AND LoginDate > CONVERT(VARCHAR(10),GETDATE() , 120)'
	SET @SQL  = @SQL + ' ORDER BY logindate DESC'
	EXEC(@SQL)
END

GO
/****** Object:  StoredProcedure [dbo].[bpInvestigaionSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[bpInvestigaionSelect]
(
	 @WHERE VARCHAR(2000) 
)
AS
BEGIN
	DECLARE @SQL AS VARCHAR(2000)
	SET @Where = dbo.SafeSql(@Where)
	SET @SQL = '
		SELECT * 
		FROM MainDb..Investigation WITH(NOLOCK) 
		WHERE 1 = 1'+ @WHERE
	EXEC(@SQL)
END

GO
/****** Object:  StoredProcedure [dbo].[bpInvestigationDelete]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--根据调查id 删除调查--------------------
--增加人Harry ---------------------------
--增加时间：2015-1-28--------------------
CREATE PROCEDURE [dbo].[bpInvestigationDelete]
(
	@id INT,
	@Code INT
)
AS
BEGIN
	DELETE 
	FROM MainDb..Investigation 
	WHERE Id = @id
	AND @Code = DATEPART(HOUR, AddDate) * 100 + DATEPART(MINUTE, AddDate)
END

GO
/****** Object:  StoredProcedure [dbo].[bpInvestigationInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--插入调查-------------------------------
--增加人Harry ---------------------------
--增加时间：2015-1-28--------------------
CREATE PROCEDURE [dbo].[bpInvestigationInsert]
(
	@title NVARCHAR(50), 
	@description NVARCHAR(500), 
	@parti VARCHAR(1200), 
	@enddate SMALLDATETIME, 
	@addman SMALLINT
)
AS
BEGIN
	INSERT INTO MainDb..Investigation (Title, Description, Parti, Enddate, Addman)
	VALUES (@title, @description, @parti, @enddate, @addman)
	SELECT @@IDENTITY AS 'Identity'
END

GO
/****** Object:  StoredProcedure [dbo].[bpInvestigationUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--修改调查-------------------------------
--增加人Harry ---------------------------
--增加时间：2015-1-28--------------------
CREATE PROCEDURE [dbo].[bpInvestigationUpdate]
(
	@title NVARCHAR(50), 
	@description NVARCHAR(500), 
	@parti VARCHAR(1200), 
	@enddate SMALLDATETIME, 
	@id INT
)
AS
BEGIN
	UPDATE  MainDb..Investigation 
	SET Title = @title, Description = @description, Parti = @parti, Enddate = @enddate 
	WHERE id = @id
END

GO
/****** Object:  StoredProcedure [dbo].[bpIPReportSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--创建人 Andy
--时间 2015-01-12
--按照条件查询后台IPReport
CREATE PROCEDURE [dbo].[bpIPReportSelect]
AS
BEGIN		
	SELECT * FROM IPReport WITH(NOLOCK) ORDER BY ID DESC
END
GO
/****** Object:  StoredProcedure [dbo].[bpJobByBeVerifingSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[bpJobByBeVerifingSelect]
    @IDS VARCHAR(1000),
	@cpMainID INT
AS
BEGIN TRY
	DECLARE @JobID Table(ID INT NULL)
	DECLARE @I AS INT
	SET @I= CHARINDEX(',',@IDS)
	WHILE @I >= 1
		BEGIN
			IF LEFT(@IDS, @I - 1) > '' 
				INSERT @JobID VALUES(LEFT(@IDS, @I - 1))
			SET @IDS = SUBSTRING(@IDS, @I + 1, LEN(@IDS) - @I)
			SET @I = CHARINDEX(',', @IDS)
		END
	INSERT @JobID VALUES(@IDS)
	
    SELECT
		a.ID,
		a.cpMainID,
		a.caMainID,
		a.Name,
		a.dcJobTypeID,
		a.dcJobTypeIDMinor,
		a.NeedNumber,
		a.dcSalaryID,
		a.EmployType,
		a.dcRegionID,
		a.Responsibility,
		a.Demand,
		a.dcEducationID,
		a.MinExperience,
		a.MinAge,
		a.MaxAge,
		a.IssueDate,
		a.IssueEnd,
		a.AddDate,
		a.RefreshDate,
		a.LastModifyDate,
		(SELECT TOP 1 ID FROM bsCpVerify WHERE cpMainID=@cpMainID ORDER BY ID DESC) AS bsCpVerifyID
    FROM Job a WITH(NOLOCK), @JobID b
    WHERE a.ID = b.ID
	AND a.IsDelete = 0
END TRY
BEGIN CATCH
END CATCH














GO
/****** Object:  StoredProcedure [dbo].[bpJobByCountSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-----------------
--创建日期：2011-3-17
--创建人：lambo
--功能说明：根据职位编号查询该职位一个月内的浏览数、申请数、开放简历的申请数
-----------------
CREATE PROCEDURE [dbo].[bpJobByCountSelect]
(
    @JobID INT,
	@ViewCount INT OUTPUT,
	@ApplyCount INT OUTPUT,
	@ApplyHighCount INT OUTPUT
)
AS
BEGIN
	SELECT @ViewCount = COUNT(1) FROM paJobViewLog WITH(NOLOCK) WHERE JobId=@JobID AND AddDate > GETDATE()-30
	SELECT @ApplyCount = COUNT(1) FROM ExJobApply WITH(NOLOCK) WHERE JobID=@JobID AND Adddate>GETDATE()-30
	SELECT @ApplyHighCount = COUNT(1) FROM ExJobApply a WITH(NOLOCK) ,cvMain b WITH(NOLOCK) 
		WHERE a.jobid=@JobID 
		AND a.adddate>GETDATE()-30 
		AND b.id=a.cvMainID 
		AND b.IsOpen=0

END














GO
/****** Object:  StoredProcedure [dbo].[bpJobByCpMainID_IsDeleteSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.1.12
--创建人：Nick
--说明：根据cpmainid获取职位
--#####################################################
CREATE PROCEDURE [dbo].[bpJobByCpMainID_IsDeleteSelect]
(
	@CpMainID INT
)
AS
BEGIN 
	SELECT ID,name, valid FROM Job WHERE IsDelete<>1 AND CpmainID=@CpMainID ORDER BY valid DESC 
End

GO
/****** Object:  StoredProcedure [dbo].[bpJobBycpMainIdAllSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[bpJobBycpMainIdAllSelect]
(
	@cpMainID INT, 
	@Status INT
)
AS
BEGIN
	IF @Status = 0
		SELECT c.*, e.FullName, d.Name caName, d.Gender, d.telephone, d.Mobile, d.Title, d.Email
		FROM Job c WITH(NOLOCK), caMain d WITH(NOLOCK), dcRegion e WITH(NOLOCK)
		WHERE c.caMainID = d.ID 
		AND c.dcRegionId = e.Id
		AND c.cpMainID = @cpMainID 
		AND c.IsDelete = 0
		AND c.IssueDate IS NULL
		ORDER BY c.LastModifyDate DESC
	IF @Status = 1
		SELECT c.*, e.FullName, d.Name caName, d.Gender, d.telephone, d.Mobile, d.Title, d.Email, 
			(SELECT COUNT(1) FROM paJobViewLog WITH(NOLOCK) WHERE JobId = c.ID AND AddDate > GETDATE()-30) ViewCount, 
			(SELECT COUNT(1) FROM ExJobApply WITH(NOLOCK) WHERE JobID = c.ID AND Adddate>GETDATE()-30) ApplyCount, 
			(SELECT COUNT(1) FROM ExJobApply a WITH(NOLOCK), cvMain b WITH(NOLOCK) 
			WHERE a.jobid = c.ID 
			AND a.adddate>GETDATE()-30 
			AND b.id = a.cvMainID 
			AND b.IsOpen = 0) ApplyHighCount
		FROM Job c WITH(NOLOCK), caMain d WITH(NOLOCK), dcRegion e WITH(NOLOCK)
		WHERE c.caMainID = d.ID
		AND c.dcRegionId = e.Id
		AND c.cpMainID = @cpMainID 
		AND c.IsDelete = 0 
		AND c.IssueEND > GETDATE()
		ORDER BY c.DisplayNo, CONVERT(VARCHAR(4), c.dcJobtypeId)
	IF @Status = 2
		SELECT c.*, e.FullName, d.Name caName, d.Gender, d.telephone, d.Mobile, d.Title, d.Email
		FROM Job c WITH(NOLOCK), caMain d WITH(NOLOCK), dcRegion e WITH(NOLOCK)
		WHERE c.caMainID = d.ID
		AND c.dcRegionId = e.Id
		AND c.cpMainID = @cpMainID 
		AND c.IsDelete = 0 
		AND c.IssueEND < GETDATE()
		ORDER BY c.IssueEnd DESC
	IF @Status = 3
		SELECT c.*, e.FullName, d.Name caName, d.Gender, d.telephone, d.Mobile, d.Title, d.Email
		FROM Job c WITH(NOLOCK), caMain d WITH(NOLOCK), dcRegion e WITH(NOLOCK)
		WHERE c.caMainID = d.ID 
		AND c.dcRegionId = e.Id
		AND c.cpMainID = @cpMainID
		AND c.IsDelete = 1 
		ORDER BY c.DisplayNo, c.LastModifyDate DESC
END




GO
/****** Object:  StoredProcedure [dbo].[bpJobBycpMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[bpJobBycpMainIDSelect]
(
    @cpMainID INT
)
AS
BEGIN
	SELECT
		ID,
		cpMainID,
		caMainID,
		Name,
		dcJobTypeID,
		dcJobTypeIDMinor,
		Responsibility,
		Demand,
		NeedNumber,
		dcSalaryID,
		EmployType,
		dcRegionID,
		dcEducationID,
		MinExperience,
		MinAge,
		MaxAge,
		DisplayNo,
		IssueDate,
		IssueEnd,
		IsDelete,
		ViewNumber,
		AddDate,
		Valid,
		RefreshDate,
		LastModifyDate
	FROM Job WITH(NOLOCK)
	WHERE cpMainID = @cpMainID 
	ORDER BY IssueEnd desc,DisplayNo,LastModifyDate DESC
END








GO
/****** Object:  StoredProcedure [dbo].[bpJobByCpMainIDValidSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.12.9
--创建人：John
--说明：获取公司未删除的职位
--#####################################################
CREATE PROCEDURE [dbo].[bpJobByCpMainIDValidSelect]
(
	@cpMainID INT
)
AS
BEGIN
	SELECT ID, [name], valid 
	FROM job WITH(NOLOCK) 
	WHERE isdelete =0
	AND cpmainid = @cpMainID 
	ORDER BY valid DESC, id
END


GO
/****** Object:  StoredProcedure [dbo].[bpJobByIDDelete]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.1.12
--创建人：Nick
--说明：删除职位
--#####################################################
CREATE PROCEDURE [dbo].[bpJobByIDDelete]
(
	@JobID VARCHAR(100)
)
AS
BEGIN 
	UPDATE Job Set IsDelete=1 WHERE ID  IN(SELECT * FROM dbo.fnSplit(@JobID,','))
	
	DELETE FROM bsCpModify WHERE Location like 'c%' AND SubID IN (SELECT * FROM dbo.fnSplit(@JobID,',')) 
End

GO
/****** Object:  StoredProcedure [dbo].[bpJobDeletedDateByJobIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.12.9
--创建人：John
--说明：获取最近的职位删除日期
--#####################################################
CREATE PROCEDURE [dbo].[bpJobDeletedDateByJobIDSelect]
(
	@jobID INT
)
AS
BEGIN
	SELECT TOP 1 DeleteDate FROM jobDeleted WITH(NOLOCK) WHERE jobid = @jobID ORDER BY DeleteDate DESC
END


GO
/****** Object:  StoredProcedure [dbo].[bpLinkByAnnounceDateSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 -----------------
--创建日期：2015-08-21
--创建人：Peter
--功能说明：查询新增友链
-----------------
CREATE PROCEDURE [dbo].[bpLinkByAnnounceDateSelect]
(
	@BeginTime DateTime, 
	@EndTime DateTime
)
AS
BEGIN
	SELECT TOP 1000 a.*, 'xxx' InternalIp, 
		(SELECT COUNT(1) cnt 
		FROM link WITH(NOLOCK)
		WHERE Valid = 1 and Deleted = 0 and link = a.link
		) Cnt, 
		(SELECT top 1 pr 
		FROM version WITH(NOLOCK) 
		WHERE id = a.versionid) Pr
	FROM Link a WITH(NOLOCK)
	WHERE Valid = 1 
	AND Deleted < 2 
	AND AnnounceDate > @BeginTime 
	AND announcedate < @EndTime
	ORDER BY manageruserid,announcedate DESC

END

GO
/****** Object:  StoredProcedure [dbo].[bpLinkByDeleteUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----------------
--创建日期：2015-08-25
--创建人：Peter
--功能说明：修改友链状态
-----------------
CREATE PROCEDURE [dbo].[bpLinkByDeleteUpdate]
	@ID INT,
	@DeleteStatus INT,
	@ManagerUserID INT
AS
BEGIN
	IF @DeleteStatus = 1
		UPDATE link 
		SET deleted = 1,deletedate=GETDATE(),deleteman=@ManagerUserID
		WHERE id = @ID
	ELSE IF  @DeleteStatus = 0
		UPDATE link 
		SET deleted = 0,deletedate=NULL,deleteman=NULL
		WHERE id = @ID
	ELSE IF @DeleteStatus = 2
		UPDATE link 
		SET deleted = 2,deletedate=GETDATE()
		WHERE id = @ID
END

GO
/****** Object:  StoredProcedure [dbo].[bpLinkByIdSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----------------
--创建日期：2015-08-25
--创建人：Peter
--功能说明：获取单个友链信息
-----------------
CREATE PROCEDURE [dbo].[bpLinkByIdSelect]
	@ID INT,
	@ProvinceID INT
AS
BEGIN
	DECLARE @VersionID INT
	
	SELECT *
	FROM Link WITH(NOLOCK)
	WHERE id = @ID
	
	SELECT @VersionID = VersionId
	FROM Link WITH(NOLOCK)
	WHERE id = @ID
	
	DECLARE @StrVersionID VARCHAR(6)
	
	IF @ID = 0
	BEGIN
		SET @StrVersionID = SUBSTRING(CONVERT(varchar,@ProvinceID),1,2) + '%'
	END
	ELSE
	BEGIN
		SET @StrVersionID = SUBSTRING(CONVERT(varchar,@VersionID),1,2) + '%'
	END
	
	SELECT id,VersionName,VersionDomain,pr
	FROM Version WITH(NOLOCK)
	WHERE id LIKE @StrVersionID 
	ORDER BY id
END

GO
/****** Object:  StoredProcedure [dbo].[bpLinkByIdUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----------------
--创建日期：2015-08-25
--创建人：Peter
--功能说明：修改友链信息
-----------------
CREATE PROCEDURE [dbo].[bpLinkByIdUpdate]
(
	@ID INT,
	@Text NVARCHAR(50),
	@Link VARCHAR(200),
	@VersionID INT,
	@LinkMan NVARCHAR(50),
	@Telephone VARCHAR(50),
	@Email VARCHAR(100),
	@Pr INT,
	@OutLink INT,
	@Authority INT,
	@Correlation INT,
	@LinkPage VARCHAR(500),
	@NoFollow INT,
	@Score FLOAT,
	@ManagerUserId INT,
	@Method INT,
	@CheckVersionId INT,
	@Category INT,
	@Baiduweight INT,
	@UpdatePriv INT,
	@Linkour INT
)
AS
SET NOCOUNT ON
BEGIN
	IF @Category = 0
		SET @Category = NULL
	IF @ID > 0
	BEGIN
		IF @UpdatePriv = 1
		BEGIN
			UPDATE link 
			SET Category=@Category,
				score=@Score,
				baiduweight=@Baiduweight,
				text=@Text,
				link=@Link,
				linkman=@LinkMan,
				telephone=@Telephone,
				email=@Email,
				linkpage=@LinkPage,
				authority=@Authority,
				correlation=@Correlation,
				nofollow=@NoFollow,
				method=@Method,
				linkour=@Linkour,
				checkVersionID = @CheckVersionId,
				versionid=@VersionID 
			WHERE id = @ID
--			WHERE id IN (
--				SELECT a.id 
--				FROM link a WITH(NOLOCK) ,link b WITH(NOLOCK) 
--				WHERE a.linkpage=b.linkpage 
--				AND LEFT(a.versionid,2)=LEFT(b.versionid,2) 
--				AND b.id=@ID)
		END
		ELSE
		BEGIN
			UPDATE link 
			SET Category=@Category,
				score=@Score,
				baiduweight=@Baiduweight,
				text=@Text,
				link=@Link,
				linkman=@LinkMan,
				telephone=@Telephone,
				email=@Email,
				linkpage=@LinkPage,
				nofollow=@NoFollow,
				linkour=@Linkour,
				checkVersionID = @CheckVersionId,
				versionid=@VersionID 
			WHERE id = @id
--			WHERE id IN (
--				SELECT a.id 
--				FROM link a WITH(NOLOCK) ,link b WITH(NOLOCK) 
--				WHERE a.linkpage=b.linkpage 
--				AND LEFT(a.versionid,2)=LEFT(b.versionid,2) 
--				AND b.id=@ID)
		END
	END
	ELSE
	BEGIN
		IF EXISTS(SELECT TOP 1 'x' FROM friendlinkblack WITH(NOLOCK) WHERE Url LIKE @Link+'%')
			RETURN -1  --黑名单
			
		INSERT INTO link (valid,type,text,link,announcedate,versionid,linkman,telephone,email,pr,outlink,authority,correlation,linkpage,nofollow,score,manageruserid,method,CheckVersionID,Category,baiduweight) 
		VALUES (1,1,@Text,@Link,getdate(),@VersionID,@LinkMan,@Telephone,@Email,@Pr,@OutLink,@Authority,@Correlation,@LinkPage,@NoFollow,@Score,@ManagerUserId,@Method,@CheckVersionId,@Category,@Baiduweight)
	END
	
	RETURN 1
END



GO
/****** Object:  StoredProcedure [dbo].[bpLinkBySqlWhereSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----------------
--创建日期：2015-08-24
--创建人：Peter
--功能说明：根据搜索条件查询友联信息
--修改日期：2015-09-08
--修改人：Peter
--修改说明：优化查询速度
-----------------
CREATE PROCEDURE [dbo].[bpLinkBySqlWhereSelect] 
(
	@SqlWhere VARCHAR(MAX)
)
AS
BEGIN
	SET @SqlWhere = dbo.SafeSql(@SqlWhere)
	DECLARE @SQL VARCHAR(MAX)
	
	SET @SQL = '
		SELECT TOP 800 a.* ,(
		SELECT COUNT(1) cnt 
		FROM link WITH(NOLOCK)
		WHERE Valid=1 AND Deleted=0 AND link = a.link
		) LinkCount,dcSubsite.SubSiteUrl checkversion,dcSubsite.pr
		FROM link a WITH(NOLOCK),dcSubsite WITH(NOLOCK) 
		WHERE dcSubsite.id=a.versionid  AND valid=1 AND deleted < 2' + @SqlWhere
		
	EXEC(@SQL)
	
			
END

GO
/****** Object:  StoredProcedure [dbo].[bpLinkCountByProvinceIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----------------
--创建日期：2015-08-20
--创建人：Peter
--功能说明：友链月报
-----------------
CREATE PROCEDURE [dbo].[bpLinkCountByProvinceIDSelect]
	@ProvinceID INT
AS
IF @ProvinceID = 0
BEGIN
	SELECT link_count.yearmonth yearmonth,SUM(link_count.power) power
	FROM link_count WITH(NOLOCK) 
	GROUP BY link_count.yearmonth 
	ORDER BY yearmonth DESC
END
ELSE IF @ProvinceID < 10
BEGIN
	SELECT link_count.yearmonth yearmonth,SUM(link_count.power) power 
	FROM link_count WITH(NOLOCK),link WITH(NOLOCK),dcSubsite WITH(NOLOCK) 
	WHERE link_count.linkid=link.id AND link.versionid=dcSubsite.ID AND link.versionid in(
		SELECT subsiteid 
		FROM dclinkmanager WITH(NOLOCK)
		WHERE groupid = @ProvinceID )
	GROUP BY link_count.yearmonth 
	ORDER BY yearmonth DESC
END
ELSE
BEGIN
	SELECT link_count.yearmonth yearmonth,SUM(link_count.power) power 
	FROM link_count WITH(NOLOCK),link WITH(NOLOCK) 
	WHERE link_count.linkid=link.id AND link.versionid=@ProvinceID 
	GROUP BY link_count.yearmonth 
	ORDER BY yearmonth DESC
END
GO
/****** Object:  StoredProcedure [dbo].[bpLinkScoreByCountDateSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----------------
--创建日期：2015-08-20
--创建人：Peter
--功能说明：首页历史分数统计
-----------------
CREATE PROCEDURE [dbo].[bpLinkScoreByCountDateSelect]
	@CountDate DATETIME
AS
SELECT DISTINCT TOP 30 countdate 
FROM link_score WITH(NOLOCK) 
ORDER BY countdate DESC

IF @CountDate IS NULL
BEGIN
	SELECT TOP 1 @CountDate = countdate 
	FROM link_score WITH(NOLOCK) 
	ORDER BY countdate DESC
END

SELECT SUM(score) score_sum,SUM(num) cnt_sum,left(versionid,2) VersionID 
INTO #T
FROM link_score WITH(NOLOCK),dcsubsite WITH(NOLOCK) 
WHERE versionid=dcsubsite.id AND ismainsite=0 AND versionid>99 AND countdate=@CountDate
GROUP BY left(versionid,2)

SELECT b.id,b.subsitecity province,a.score,a.num,c.groupid,d.score_sum,d.cnt_sum
FROM link_score a WITH(NOLOCK)
INNER JOIN dcsubsite b  WITH(NOLOCK) on a.versionid=b.id
INNER JOIN dclinkmanager c WITH(NOLOCK) on b.id=c.subsiteid 
LEFT JOIN #T d ON d.VersionID=b.id
WHERE   a.versionid=c.subsiteid AND a.countdate = @CountDate
ORDER BY b.id

DROP TABLE #T
GO
/****** Object:  StoredProcedure [dbo].[bpLinkScoreByProvinceIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----------------
--创建日期：2015-08-20
--创建人：Peter
--功能说明：二级网站历史分数统计
-----------------
CREATE PROCEDURE [dbo].[bpLinkScoreByProvinceIDSelect]
	@CountDate DATETIME,
	@ProvinceID INT
AS
SELECT DISTINCT TOP 30 countdate 
FROM link_score WITH(NOLOCK) 
ORDER BY countdate DESC

IF @CountDate IS NULL
BEGIN
	SELECT TOP 1 @CountDate = countdate 
	FROM link_score WITH(NOLOCK) 
	ORDER BY countdate DESC
END

SELECT version.versionname,link_score.score,link_score.num 
FROM link_score WITH(NOLOCK),version WITH(NOLOCK) 
WHERE link_score.versionid=version.id AND link_score.countdate=@CountDate AND link_score.versionid>100 AND version.province_id=@ProvinceID

GO
/****** Object:  StoredProcedure [dbo].[bpLoginOtpInfoSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--创建人 Andy
--时间 2015-01-06
--按照状态查询动态令牌记录
--@status=10  all
CREATE PROCEDURE [dbo].[bpLoginOtpInfoSelect]
(		
	@Status INT
)
AS
BEGIN	
	IF @Status < 10
	BEGIN
		SELECT a.*, b.Name 
		FROM LoginOtpInfo a 
		LEFT JOIN Manageruser b ON b.ID=a.ManagerUserID
		WHERE a.Status = @Status
	END
	ELSE 
	BEGIN
		SELECT a.*, b.Name 
		FROM LoginOtpInfo a 
		LEFT JOIN Manageruser b ON b.ID=a.ManagerUserID		
	END	
END


GO
/****** Object:  StoredProcedure [dbo].[bpLoginOtpInfoUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
------------------------------------------
--创建人 Andy
--时间 2015-01-06
--重新分配动态令牌
--参数：ManagerUserID:要分配的用户
--		AssignMan:当前操作用户
--结果：1:成功 
--		2:该用户已经分配过动态令牌 
--		3:该用户不存在或正在休长假
------------------------------------------
CREATE PROCEDURE [dbo].[bpLoginOtpInfoUpdate]
(		
	@ManagerUserID INT,
	@AssignMan INT,
	@OtpPin VARCHAR(20)
)
AS
BEGIN	
	DECLARE @Result INT
	--当被分配用户=0时，重置该令牌
	IF @ManagerUserID = 0
	BEGIN
		UPDATE LoginOtpInfo SET ManagerUserId = NULL, status = 0, assigndate = NULL WHERE OtpPin = @OtpPin
		SET @Result = 1
	END		
	ELSE
	BEGIN
		--查询是否有该用户
		IF EXISTS(SELECT 'x' FROM ManagerUser WHERE status < 3 AND ID = @ManagerUserID)
		BEGIN
			--查询是否已经分配
			IF EXISTS(SELECT 'x' FROM LoginOtpInfo WHERE ManagerUserID = @ManagerUserID)
			BEGIN
				--该用户已经分配过动态令牌
				SET @Result = 2
			END
			ELSE
			BEGIN
				UPDATE LoginOtpInfo SET AssignMan = @AssignMan, AssignDate = GetDate(), Status = 1, ManagerUserID = @ManagerUserID WHERE OtpPin = @OtpPin
				SET @Result = 1
			END
		END
		ELSE
		BEGIN
			--该用户不存在或正在休长假
			SET @Result = 3
		END
	END	
	RETURN @Result
END

GO
/****** Object:  StoredProcedure [dbo].[bpLotteryCompanyByGiftOrderIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--根据订单ID获取抽奖信息 Lucifer 2014-12-24
CREATE PROCEDURE [dbo].[bpLotteryCompanyByGiftOrderIDSelect]
(
	@OrderID INT
)
AS
BEGIN
	SELECT TOP 10 * FROM MainDB..LotteryCompany WITH(NOLOCK) WHERE GiftOrderID=@OrderID
END

GO
/****** Object:  StoredProcedure [dbo].[bpManagerLogSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--创建人 Andy
--时间 2015-01-06
--按照条件查询后台登录记录
CREATE PROCEDURE [dbo].[bpManagerLogSelect]
(		
	@Dept INT,	
	@ManagerUserID INT,--被查询的用户ID
	@SearchItem INT,--0:IP,1:cookies,2:Mac
	@SearchAction INT,--0:等于,1:以..开始
	@SearchText VARCHAR(20),
	@CurManagerUserID INT,--当前登录用户ID		
	@Privi INT--当前用户的权限
)
AS
BEGIN	
	SET @SearchText = dbo.SafeSql(@SearchText)	
	DECLARE @SQL VARCHAR(1000)
	SET @SQL = '
		SELECT TOP 200 a.LoginDate, a.IP, b.ID ManagerUserID, b.Name, a.Cookies, a.mac 
		FROM ManagerLog a WITH(NOLOCK), ManagerUser b WITH(NOLOCK) 
		WHERE a.ManagerID=b.ID '
	--部门
	IF @Dept > 0
		SET @SQL = @SQL + '  AND deptID= '+LTRIM(STR(@Dept))  
	--工号
	IF @ManagerUserID > 0
		SET @SQL = @SQL + '  AND b.ID= '+LTRIM(STR(@ManagerUserID))		
	--其他搜索条件
	IF @SearchText > ''
	BEGIN	
		IF @SearchItem = 1 
		BEGIN
			IF @SearchAction = 1 
				SET @SQL = @SQL + ' AND IP = ''' + LTRIM(@SearchText) + ''''
			ELSE IF @SearchAction = 2
				SET @SQL = @SQL + ' AND IP LIKE ''' + LTRIM(@SearchText) + '%'''
		END
		ELSE IF (@SearchItem = 2 AND @SearchAction = 1)			
			SET @SQL = @SQL + '  AND a.cookies= '''+LTRIM(STR(@SearchText))+''''
		ELSE IF (@SearchItem = 3 AND @SearchAction = 1)			
			SET @SQL = @SQL + '  AND MAC LIKE ''%'+LTRIM(STR(@SearchText))+ '%'''
	END 
	--权限
	SET @SQL = @SQL + ' AND b.ID IN (SELECT ID from dbo.LowerUser('+LTRIM(STR(@CurManagerUserID)) + ',' + LTRIM(STR(@Privi)) + '))'	
	--排序
	SET @SQL = @SQL + ' ORDER BY LoginDate DESC'
	--PRINT(@SQL)
	EXEC (@SQL)
END

GO
/****** Object:  StoredProcedure [dbo].[bpManagerUserAllByDeptIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[bpManagerUserAllByDeptIDSelect]
(
	@DeptID AS INT
)
AS
SET NOCOUNT ON
BEGIN
	IF @DeptID = 0
		SELECT ID, Name FROM ManagerUser WITH(NOLOCK) WHERE Status <>3
	ELSE
		SELECT ID, Name FROM ManagerUser WITH(NOLOCK) 
		WHERE DeptId = @DeptId
		OR deptid IN (SELECT ID FROM Dept WHERE Superior = @DeptId)		
END

GO
/****** Object:  StoredProcedure [dbo].[bpManagerUserBy58LoginSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[bpManagerUserBy58LoginSelect]
(
	@UserName VARCHAR(50),
	@Password VARCHAR(50),
	@IP VARCHAR(100),
	@UniCode VARCHAR(20)
)
AS
SET NOCOUNT ON
BEGIN
	DECLARE @Id INT, @Name NVARCHAR(20)
	SELECT @Id = ID, @Name = Name FROM ManagerUser WHERE UserName = @UserName AND Password = @Password
	IF @Id IS NULL
	BEGIN
		SELECT TOP 0 @Id
		RETURN
	END
	IF EXISTS(SELECT 'X' FROM Shortdb..SeekCompanyIpLog WHERE ManageruserId = @Id AND IP = @IP AND RunDate > DATEADD(MINUTE, - 10, GETDATE()))
	BEGIN
		SELECT TOP 0 @Id
		RETURN
	END
	INSERT INTO ShortDb..SeekCompanyIpLog VALUES (@Id, @IP, GETDATE(), @UniCode, GETDATE())
	SELECT @Id ManagerUserId
END
SET NOCOUNT OFF
GO
/****** Object:  StoredProcedure [dbo].[bpManagerUSerByAllLowerSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[bpManagerUSerByAllLowerSelect]
(
	@ID INT
)
AS
BEGIN
	DECLARE @T TABLE(
		ID INT,
		Name VARCHAR(20),
		Name_Eng VARCHAR(20),
		Superior INT
	)	
END














GO
/****** Object:  StoredProcedure [dbo].[bpManagerUserByConditionSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[bpManagerUserByConditionSelect]
(
	@DeptID AS INT,
	@WHERE VARCHAR(MAX)
)
AS
BEGIN
	DECLARE @SQL VARCHAR(MAX)
	SET @SQL = 'SELECT ID, Name,name_eng FROM ManagerUser WITH(NOLOCK) WHERE deptid = '+CONVERT(VARCHAR(10),@DeptID)+' '+@WHERE
	EXEC (@SQL)
END

GO
/****** Object:  StoredProcedure [dbo].[bpManagerUserByConsultantSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[bpManagerUserByConsultantSelect]
(
	@NorthSouth INT
)
AS
BeGIN
	IF @NorthSouth = 0
		SELECT ID,Name,DeptID FROM ManagerUser WITH(NOLOCK) WHERE Type=1 AND Status<>3
	
	IF @NorthSouth = 1
		SELECT ID,Name,DeptID FROM ManagerUser WITH(NOLOCK) WHERE Type=1 AND Status<>3 AND ID<800

	IF @NorthSouth = 2
		SELECT ID,Name,DeptID FROM ManagerUser WITH(NOLOCK) WHERE Type=1 AND Status<>3 AND ID>800
END














GO
/****** Object:  StoredProcedure [dbo].[bpManagerUserByDeptIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[bpManagerUserByDeptIDSelect]
(
	@DeptID AS INT
)
AS
BEGIN
	IF @DeptID = 0
		SELECT ID, Name FROM ManagerUser WITH(NOLOCK) 
        --WHERE Status <> 3
	ELSe
		SELECT ID, Name FROM ManagerUser WITH(NOLOCK) WHERE 
        --Status <> 3 AND 
		deptid =@DeptID
END














GO
/****** Object:  StoredProcedure [dbo].[bpManagerUserByDeptSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.12.04
--创建人：Nick
--说明：获取用户和部门数据
--#####################################################
CREATE PROCEDURE [dbo].[bpManagerUserByDeptSelect]
AS
BEGIN
	SELECT a.ID,b.DeptName 
	FROM ManagerUser a WITH(NOLOCK),Dept b WITH(NOLOCK) 
	WHERE a.deptid = b.id 
	AND Status<>3 
END 


GO
/****** Object:  StoredProcedure [dbo].[bpManagerUserByHRKpiPostIdSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


--获取kpi岗位工资设定-----------------
--增加人Harry ---------------------------
--增加时间：2015-1-28--------------------
CREATE PROCEDURE [dbo].[bpManagerUserByHRKpiPostIdSelect]
(
	@id INT, 
	@grade TINYINT
)
AS
BEGIN
	SELECT Name 
	FROM MainDb..ManagerUser WITH(NOLOCK) 
	WHERE HRKpiPostId = @id 
	AND HRKpiPostGrade = @grade
END

GO
/****** Object:  StoredProcedure [dbo].[bpManagerUserByHrKpiPostUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--修改员工的Kpipost信息-----------------
--增加人Harry ---------------------------
--增加时间：2015-1-28--------------------
CREATE PROCEDURE [dbo].[bpManagerUserByHrKpiPostUpdate]
(
	@id INT, 
	@hrKpiPostId INT, 
	@hrKpiPostGrade TINYINT
)
AS
BEGIN
	UPDATE ManagerUser 
	SET HRKpiPostId = @hrKpiPostId, HRKpiPostGrade = @hrKpiPostGrade 
	WHERE Id = @id
END

GO
/****** Object:  StoredProcedure [dbo].[bpManagerUserByInfoAchieveSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--bpManagerUserByInfoAchieveSelect 0, 119,5
--创建人 Andy
--时间 2015-01-23
--查询信息员统计核算功能需要核算的用户
CREATE PROCEDURE [dbo].[bpManagerUserByInfoAchieveSelect] 
(	
	@DeptID INT,
	@CurManagerUserID INT,--当前登录用户ID		
	@Privi INT--当前用户的权限
)
AS
BEGIN			
	DECLARE @SQL VARCHAR(1000)	
	SET @SQL = '
		SELECT b.status, b.id, b.username, b.password, b.name, b.superiOr, b.title, a.rolename, b.deptid, b.type 
		FROM Role a WITH(NOLOCK) 
		INNER JOIN ManagerUser b WITH(NOLOCK) ON b.roleid = a.ID 
		WHERE (b.deptid = 15 OR b.deptid = 16 OR b.deptid = 22 OR b.deptid = 35)'		
	IF @DeptId > 0	
		SET @SQL = @SQL + '  AND b.DeptId = ' + LTRIM(STR(@DeptId))	
	SET @SQL = @SQL + ' AND b.ID IN (SELECT ID FROM dbo.LowerUserAll('+LTRIM(STR(@CurManagerUserID)) + ',' + LTRIM(STR(@Privi)) + '))'	
	
	SET @SQL = @SQL + ' ORDER BY b.Id' 
	--PRINT(@SQL)
	EXEC (@SQL)
END
GO
/****** Object:  StoredProcedure [dbo].[bpManagerUserByKpiPostSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--获取所有员工的id, 英文, 名称---------
--增加人Harry -----------------------
--增加时间：2015-1-28---------------
CREATE PROCEDURE [dbo].[bpManagerUserByKpiPostSelect]
AS
BEGIN 
	SELECT Id, Name_Eng, Name 
	FROM MainDb..ManagerUser WITH(NOLOCK) 
	ORDER BY Id
END

GO
/****** Object:  StoredProcedure [dbo].[bpManagerUserByLoginSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[bpManagerUserByLoginSelect]
(
    @UserName VARCHAR(50),
    @Password VARCHAR(50)
)
AS
SET NOCOUNT ON
BEGIN
    DECLARE @Id INT, @Name NVARCHAR(20)
    SELECT @Id = ID, @Name = Name FROM ManagerUser WHERE UserName = @UserName AND Password = @Password
    IF @Id IS NULL
    BEGIN
        SELECT TOP 0 @Id
        RETURN
    END
    SELECT @Id ManagerUserId
END


GO
/****** Object:  StoredProcedure [dbo].[bpManagerUserByLoginUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--==================================================
--返回值：
--	0：保存出错
--	-1：用户名密码错误
--	-2：登录状态不正确、
--	-3：用户状态不正确（已删除)
--		Peter 2013-12-12创建 移动令牌验证
--==================================================
CREATE PROCEDURE [dbo].[bpManagerUserByLoginUpdate]
(
	@UserName VARCHAR(50),
	@Password VARCHAR(50),
	@IP VARCHAR(15),
	@Cookie	VARCHAR(20)
)
AS
BEGIN TRAN
	DECLARE @ID AS INT, 
		@LoginStatus AS SMALLINT,
		@Status AS SMALLINT,
		@TotalLoginNum AS INT,
		@LoginIp VARCHAR(15), 
		@ActiveTime SMALLDATETIME,
		@PrevCookie	VARCHAR(20)
	SELECT @ID = ID, @LoginStatus = LoginStatus, 
		@LoginIp = ISNULL(LoginIp, ''), @ActiveTime = ISNULL(ActiveTime, GETDATE() - 1),
		@PrevCookie = Cookies
	FROM ManagerUser WITH(NOLOCK)
	WHERE UserName = @UserName
	AND Password = @Password
	
	BEGIN TRY
		IF @ID > 0
			BEGIN
				IF @LoginStatus = 2
					GOTO Err2
				IF @Status = 3
					GOTO Err3

				BEGIN TRY
					UPDATE ManagerUser SET LoginCount = LoginCount + 1, LastLoginDate = GETDATE(),Cookies=@Cookie, LoginIp = @ip, ActiveTime = GETDATE()
					WHERE ID=@ID
				
					IF ISNULL(@Cookie, '') = ''
						SELECT @Cookie = 'No Cookies'
					IF ISNULL(@Ip, '') = ''
						SELECT @Ip = 'No Ip'

					INSERT INTO ManagerLog(ManagerID, IP, Cookies, Mac) VALUES(@ID, @IP, @Cookie, '')
				END TRY
				BEGIN CATCH
				END CATCH
			END
		ELSE
			GOTO Err1
	END TRY
	BEGIN CATCH
		GOTO Err
	END CATCH
COMMIT TRAN
RETURN @ID
Err:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END
Err1:
BEGIN
	ROLLBACK TRAN
	RETURN -1
END
Err2:
BEGIN
	ROLLBACK TRAN
	RETURN -2
END
Err3:
BEGIN
	ROLLBACK TRAN
	RETURN -3
END









GO
/****** Object:  StoredProcedure [dbo].[bpManagerUserByOutLinkSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.09.08
--创建人：Nick
--说明：
--#####################################################
CREATE PROCEDURE [dbo].[bpManagerUserByOutLinkSelect]
(
	@Where VARCHAR(MAX)
)
AS
BEGIN
	DECLARE @SQL VARCHAR(MAX)
	SET @SQL = 'SELECT id,name FROM manageruser WHERE status<>3 '+@Where
	SET @SQL = @SQL + ' AND id IN (
		SELECT addman  
		FROM outlinkResources WITH(NOLOCK) 
		WHERE status=1 
		AND groupid=4 
	) ORDER BY ID'
	EXEC (@SQL)
END

GO
/****** Object:  StoredProcedure [dbo].[bpManagerUserBySuperiorSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[bpManagerUserBySuperiorSelect]
(
	@SuperiorID INT
)
AS
BEGIN
	SELECT ID,Name FROM ManagerUSer WITH(NOLOCK) WHERE Superior = @SuperiorID AND Status<>3
END














GO
/****** Object:  StoredProcedure [dbo].[bpManagerUserCompanyLogInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.12.9
--创建人：John
--说明：新增ManagerUserCompanyLog
--#####################################################
CREATE PROCEDURE [dbo].[bpManagerUserCompanyLogInsert]
(
	@companyID INT,
	@managerUserID SMALLINT,
	@cookies VARCHAR(16),
	@ip VARCHAR(30),
	@beginDate DATETIME,
	@endDate DATETIME
)
AS
BEGIN
	DECLARE @cnt INT
	SELECT @cnt = COUNT(*) 
	FROM ManagerUserCompanyLog 
	WHERE companyid = @companyID 
	AND manageruserid = @managerUserID 
	AND cookies = @cookies 
	AND ip = @ip 
	AND [source] = 2 
	AND adddate > @beginDate 
	AND adddate < @endDate 

	IF @cnt = 0 
	BEGIN 
		INSERT INTO ManagerUserCompanyLog (companyid,manageruserid,cookies,ip,[source]) 
		VALUES (@companyID,@managerUserID,@cookies,@ip,2)
	END
END


GO
/****** Object:  StoredProcedure [dbo].[bpManagerUserLoginUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--==================================================
--返回值：
--	0：保存出错
--	-1：用户名密码错误
--	-2：登录状态不正确、
--	-3：用户状态不正确（已删除)
--==================================================
CREATE PROCEDURE [dbo].[bpManagerUserLoginUpdate]
(
	@UserName VARCHAR(50),
	@Password VARCHAR(50),
	@IP VARCHAR(15),
	@Cookie	VARCHAR(20),
	@Mac VARCHAR(20)
)
AS
BEGIN TRAN
	DECLARE @ID AS INT, 
		@LoginStatus AS SMALLINT,
		@Status AS SMALLINT,
		@TotalLoginNum AS INT,
		@LoginIp VARCHAR(15), 
		@ActiveTime SMALLDATETIME,
		@PrevCookie	VARCHAR(20)
	SELECT @ID = ID, @LoginStatus = LoginStatus, 
		@LoginIp = ISNULL(LoginIp, ''), @ActiveTime = ISNULL(ActiveTime, GETDATE() - 1),
		@PrevCookie = Cookies
	FROM ManagerUser WITH(NOLOCK)
	WHERE UserName = @UserName
	AND Password = @Password
	/*
	IF((DATEDIFF(MINUTE, @ActiveTime, GETDATE()) < 60) AND (@PrevCookie <> @Cookie))
		GOTO Err
	IF((DATEDIFF(MINUTE, @ActiveTime, GETDATE()) < 60) AND (@LoginIp <> @Ip))
		GOTO Err1
	*/
	BEGIN TRY
		IF @ID > 0
			BEGIN
				IF @LoginStatus = 2
					GOTO Err2
				IF @Status = 3
					GOTO Err3

				SET @Mac = LTRIM(RTRIM(@Mac))
				IF NOT EXISTS(
					SELECT 'x' FROM bsManagerMac 
					WHERE 
						(
						ManagerUserId = LTRIM(STR(@ID)) 
						AND (Mac = @Mac OR Mac = '*')
						) 
					OR (ManagerUserId = '*' And Mac = @Mac)
					)
					GOTO Err4
				BEGIN TRY
					UPDATE ManagerUser SET LoginCount = LoginCount + 1, LastLoginDate = GETDATE(),Cookies=@Cookie, LoginIp = @ip, ActiveTime = GETDATE()
					WHERE ID=@ID
				
					IF ISNULL(@Cookie, '') = ''
						SELECT @Cookie = 'No Cookies'
					IF ISNULL(@Ip, '') = ''
						SELECT @Ip = 'No Ip'

					INSERT INTO ManagerLog(ManagerID, IP, Cookies, Mac) VALUES(@ID, @IP, @Cookie, @Mac)
				END TRY
				BEGIN CATCH
				END CATCH
			END
		ELSE
			GOTO Err1
	END TRY
	BEGIN CATCH
		GOTO Err
	END CATCH
COMMIT TRAN
RETURN @ID
Err:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END
Err1:
BEGIN
	ROLLBACK TRAN
	RETURN -1
END
Err2:
BEGIN
	ROLLBACK TRAN
	RETURN -2
END
Err3:
BEGIN
	ROLLBACK TRAN
	RETURN -3
END
Err4:
BEGIN
	ROLLBACK TRAN
	RETURN -4
END














GO
/****** Object:  StoredProcedure [dbo].[bpManagerUserRoleSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO
--==================================================
--返回值：
--	0：保存出错
--	-1：用户名密码错误
--	-2：登录状态不正确、
--	-3：用户状态不正确（已删除)
--==================================================
CREATE PROCEDURE [dbo].[bpManagerUserRoleSelect]
(
	@ID INT
)
AS
BEGIN
	SELECT b.ID RoleID,b.RoleName RoleName,a.ID ManagerUserID,a.Name Name,b.Province Province,a.DeptID DeptID,a.EMail EMail,a.Superior Superior,a.Type ManagerUserType,a.LoginStatus LoginStatus,b.Grade 
	FROM ManagerUser a WITH(NOLOCK), Role b WITH(NOLOCK)
	WHERE a.RoleID=b.ID
	AND a.ID = @ID
END














GO
/****** Object:  StoredProcedure [dbo].[bpManagerUserSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[bpManagerUserSelect]
(
	@ID INT
)
AS
BEGIN
	SELECT * FROM ManagerUser WITH(NOLOCK) WHERE ID=@ID
END














GO
/****** Object:  StoredProcedure [dbo].[bpMobileSendDelete]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[bpMobileSendDelete]
(
	@ID INT
)
AS
DELETE FROM MobileSend WHERE ID = @ID














GO
/****** Object:  StoredProcedure [dbo].[bpMobileSendInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[bpMobileSendInsert]
(
	@ManagerUserID INT,
	@CompanyID INT,
	@BusinessType NVARCHAR(10),
	@Priority TINYINT,
	@Mobile VARCHAR(13),
	@MSG NVARCHAR(300)
)
AS
BEGIN TRY
	INSERT INTO MobileSend(ManagerUserID,CompanyID,BusinessType,Mobile,Msg,Priority,SendDate)
	VALUES(@ManagerUserID,@CompanyID,@BusinessType,@Mobile,@Msg,@Priority,Null)
	RETURN @@IDENTITY
END TRY
BEGIN CATCH
	RETURN 0
END CATCH














GO
/****** Object:  StoredProcedure [dbo].[bpMsEmailSendSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--创建人 Andy
--时间 2014-01-04
--后台收发邮件记录查询
--2015-3-6 MICE 123 添加邮件类型和host
CREATE PROCEDURE [dbo].[bpMsEmailSendSelect]
(		
	@email VARCHAR(50),
	@mailType INT,
	@mailHost VARCHAR(50)
)
AS
BEGIN	
	SELECT @Email = dbo.SafeSql(@email), @MailHost = dbo.SafeSql(@MailHost)
	DECLARE @SQL AS VARCHAR(5000)
	SET @SQL = 'SELECT TOP 2000 * FROM MsEmailSend WITH(NOLOCK) WHERE 1=1 '
	IF LEN(@email)>1
	BEGIN
		SET @SQL = @SQL + ' AND Email like ''' + @email + '%'''
	END
	IF @mailType > 0
	BEGIN
		SET @SQL = @SQL + ' AND msEmailTypeId = ''' + CONVERT(VARCHAR(4),@mailType)  + ''''
	END
	IF LEN(@mailHost)>1
	BEGIN
		SET @SQL = @SQL + ' AND Host LIKE ''%' + @mailHost + '%'''
	END
	SET @Sql = @Sql + ' ORDER BY Id DESC'
	EXEC(@SQL)
	
END


GO
/****** Object:  StoredProcedure [dbo].[bpMt_PlanByAddManSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015-01-15
--创建人：Andy
--说明：得到七天内预定会议室的发起人
--#####################################################
CREATE PROCEDURE [dbo].[bpMt_PlanByAddManSelect]
AS
BEGIN	
	SELECT DISTINCT a.AddMan, b.Name 
	FROM Mt_Plan a WITH(NOLOCK), ManagerUser b WITH(NOLOCK) 
	WHERE a.AddMan = b.ID AND BeginTime > GETDATE()-7
	ORDER BY a.AddMan	
END


GO
/****** Object:  StoredProcedure [dbo].[bpMt_PlanByPartiSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2015-01-15
--创建人：Andy
--说明：查询某个人在一段时间内参加会议的个数，用于判断其是否有会议要参加。
--#####################################################
CREATE PROCEDURE [dbo].[bpMt_PlanByPartiSelect]
(	
	@Parti VARCHAR(6),	--格式：120
	@BeginTime DATETIME,
	@EndTime DATETIME,
	@AddMan INT         --不包含当前addman添加的这一条
)
AS
BEGIN	
	SELECT *
	FROM Mt_Plan WITH(NOLOCK) 
	WHERE ((BeginTime <= @BeginTime AND EndTime >= @BeginTime) 
		OR (BeginTime <= @EndTime AND EndTime >= @EndTime) 
		OR (BeginTime >= @BeginTime AND BeginTime <= @EndTime) 
		OR (EndTime >= @BeginTime AND EndTime <= @EndTime))
	AND Parti LIKE + '%\[' + @Parti + '\]%' ESCAPE '\'
	AND AddMan <> @AddMan
END

GO
/****** Object:  StoredProcedure [dbo].[bpMt_PlanByTimeSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015-01-15
--创建人：Andy
--说明：按照条件查询会议室预定
--#####################################################
CREATE PROCEDURE [dbo].[bpMt_PlanByTimeSelect]
(	
	@Mt_ID INT,		
	@BeginTime DATETIME,
	@EndTime DATETIME
)
AS
BEGIN
	SELECT * 
	FROM Mt_Plan WITH(NOLOCK) 
	WHERE ((BeginTime <= @BeginTime AND EndTime >= @BeginTime) 
		OR (BeginTime <= @BeginTime AND EndTime >= @EndTime) 
		OR (BeginTime >= @BeginTime AND BeginTime <= @EndTime) 
		OR (EndTime >= @BeginTime AND EndTime <= @EndTime))
	AND Mt_ID = @Mt_ID
END



GO
/****** Object:  StoredProcedure [dbo].[bpMt_PlanDelete]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2015-01-15
--创建人：Andy
--说明：删除指定的会议
--#####################################################
CREATE PROCEDURE [dbo].[bpMt_PlanDelete]
(	
	@ID INT
)
AS
BEGIN	
	DELETE FROM Mt_Plan WHERE ID = @ID
END
GO
/****** Object:  StoredProcedure [dbo].[bpMt_PlanSave]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--alen 2018-2-8
CREATE PROCEDURE [dbo].[bpMt_PlanSave]
(		
	@ID INT, --如果=0，则是insert
	@MtID INT,
	@BeginTime DATETIME,
	@EndTime DATETIME,
	@Title NVARCHAR(100),
	@ManagerUserID INT,
	@Parti VARCHAR(1000)
)
AS
BEGIN
	IF @ID = 0		
		INSERT INTO Mt_Plan (Mt_ID, BeginTime, EndTime, Title, Addman, Parti) 
		VALUES (@MtID, @BeginTime, @EndTime, @Title, @ManagerUserID, @Parti)		
	ELSE
		UPDATE Mt_Plan 
		SET Mt_Id = @MtID, BeginTime =@BeginTime, EndTime = @EndTime, Title = @Title, Parti = @Parti
		WHERE ID = @ID
	RETURN 1		
END
GO
/****** Object:  StoredProcedure [dbo].[bpMt_PlanSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2015-01-15
--创建人：Andy
--说明：按照条件查询会议室预定
--#####################################################
CREATE PROCEDURE [dbo].[bpMt_PlanSelect]
(	
	@Mt_ID INT,	
	@AddMan INT,
	@Part_ID INT,--格式：[120]
	@StartTime DATETIME,
	@EndTime DATETIME,	
	@CurManagerUserID INT,--当前登录用户ID		
	@Privi INT--当前用户的权限
)
AS
insert proclog select 'bpMt_PlanSelect',@Part_ID,getdate()
BEGIN	
	DECLARE @SQL VARCHAR(1000)
	SET @SQL = '
		SELECT TOP 100 a.ID, a.BeginTime, a.EndTime, a.AddMan AddManID, b.Name AddNan, a.Title, a.Parti, a.AddDate, c.MtName, a.AddDate 
		FROM Mt_Plan a WITH(NOLOCK), ManagerUser b WITH(NOLOCK), Mt c WITH(NOLOCK)
		WHERE a.Mt_ID = c.ID AND a.AddMan = b.ID 
		AND a.BeginTime >= ''' + CONVERT(VARCHAR(20),@StartTime, 20) + ''' 
		AND a.BeginTime <= ''' + CONVERT(VARCHAR(20),@EndTime, 20) + ''''
	IF @Mt_ID > 0
		SET @SQL = @SQL + ' AND c.ID = ' + LTRIM(STR(@Mt_ID))	
	IF @AddMan > 0
		SET @SQL = @SQL + ' AND a.AddMan = ' + LTRIM(STR(@AddMan))	
	IF @Part_ID > 0
		SET @SQL = @SQL + ' AND CharIndex(''[' + LTRIM(STR(@Part_ID)) + ']'', Parti) > 0'	
	--权限
	SET @SQL = @SQL + ' AND a.AddMan IN (SELECT ID FROM dbo.LowerUserAll('+LTRIM(STR(@CurManagerUserID)) + ',' + LTRIM(STR(@Privi)) + '))'	
	SET @SQL = @SQL + ' ORDER BY a.BeginTime DESC '
	--PRINT(@SQL)
	EXEC (@SQL)
END

GO
/****** Object:  StoredProcedure [dbo].[bpMtSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


--#####################################################
--创建时间：2015-01-15
--创建人：Andy
--说明：得到所有的会议室
--#####################################################
CREATE PROCEDURE [dbo].[bpMtSelect]
AS
BEGIN	
	SELECT * FROM Mt WITH(NOLOCK) WHERE Valid = 1 ORDER BY MtName
END


GO
/****** Object:  StoredProcedure [dbo].[bpOpCommentCompanyInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--Lucifrer 2015-1-5
CREATE PROCEDURE [dbo].[bpOpCommentCompanyInsert]
(
	@WorkUserID SMALLINT
)
AS
BEGIN
	IF (SELECT COUNT(*) FROM oadb..opCommentCompany WHERE WorkUserID = 0) <  10
	BEGIN
		CREATE TABLE #T(cpMainID INT)

		INSERT INTO #T(cpMainID)  
		SELECT TOP 500 ID FROM cpMain
		WHERE dcProvinceID IN(10,11,12,14,30,32,41,61,72,80)
		AND MemberType > 1
		AND EXISTS(SELECT 'X' FROM Job WHERE cpMainID = cpMain.ID AND Valid=1)
		--AND EXISTS(SELECT 'X' FROM caLoginLog c, caMain d 
		--	WHERE c.caMainID=d.ID 
		--	AND d.cpMainId = cpMain.Id
		--	AND AddDate>GETDATE()-180)
		--  AND ID NOT IN(SELECT cpMainID FROM oadb..opCommentCompany WHERE AddDate > GETDATE() - 31)
		AND Name NOT IN(
			SELECT Name FROM cpMain a, oadb..opCommentCompany b
			WHERE a.ID = b.cpMainID
		)
		AND Valid = 1
		AND IsLimitLogin < 9
		AND LastLoginDate > GETDATE() - 90
		ORDER BY NEWID()

		INSERT oadb..opCommentCompany(cpMainId, WorkUserID) SELECT cpMainId, 0 FROM #t
	END

	DELETE oadb..opCommentCompany WHERE cpMainId IN(SELECT Id FROM cpMain WHERE IsLimitLogin = 9)

	IF @WorkUserId > 0
		UPDATE oadb..opCommentCompany
		SET WorkUserID = @WorkUserId,
			AddDate = GETDATE()
		WHERE ID IN(SELECT TOP 5 ID FROM oadb..opCommentCompany WHERE WorkUserID = 0 ORDER BY ID)
END


GO
/****** Object:  StoredProcedure [dbo].[bpOutLinkByExcelInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.09.06
--创建人：Nick
--说明：外链添加
--#####################################################
create PROCEDURE [dbo].[bpOutLinkByExcelInsert]
(
	@OutUrl VARCHAR(200),
	@ManagerUserID INT,
	@OutlinkResources_id INT,
	@Site VARCHAR(50),
	@KeyWords VARCHAR(200)
)
AS
BEGIN
	INSERT INTO outlink(outurl,manageruserid,outlinkResources_id,site,keywords) 
	VALUES(@OutUrl,@ManagerUserID,@OutlinkResources_id,@Site,@KeyWords)
END

GO
/****** Object:  StoredProcedure [dbo].[bpOutLinkByIDDelete]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.09.06
--创建人：Nick
--说明：删除链接
--修改人：Lucifer 更正批量删除
--#####################################################
CREATE PROCEDURE [dbo].[bpOutLinkByIDDelete]
(
	@Ids VARCHAR(200),
	@ID INT
)
AS
BEGIN
	IF @Ids <> ''
	BEGIN
		DELETE FROM outlink WHERE id in (SELECT a FROM dbo.FnSplit(@Ids, ','))
	END
	ELSE 
	BEGIN
		DELETE FROM outlink WHERE ID = @ID
	END
END
GO
/****** Object:  StoredProcedure [dbo].[bpOutlinkByIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.09.06
--创建人：Nick
--说明：根据ID查询outlink
--#####################################################
create PROCEDURE [dbo].[bpOutlinkByIDSelect]
(
	@ID INT
)
AS
BEGIN
	SELECT * FROM outlink WITH(NOLOCK) WHERE id = @ID
END

GO
/****** Object:  StoredProcedure [dbo].[bpOutLinkByIDUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.09.08
--创建人：Nick
--说明：修改 OutLink
--#####################################################
create PROCEDURE [dbo].[bpOutLinkByIDUpdate]
(
	@KeyWords VARCHAR(200),
	@Site VARCHAR(100),
	@OutUrl VARCHAR(200),
	@Resources_id INT,
	@Remarks VARCHAR(500),
	@UserName VARCHAR(50),
	@Psssword VARCHAR(50),
	@ID INT
)
AS
BEGIN
	UPDATE outlink SET outurl = @OutUrl,site = @Site,outlinkResources_id = @Resources_id,remarks=@Remarks,username=@UserName,
		password = @Psssword,keywords = @KeyWords 
	WHERE id = @ID
END

GO
/****** Object:  StoredProcedure [dbo].[bpOutLinkByManagerUserIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [dbo].[bpOutLinkByManagerUserIDSelect]
(
	@BeginTime VARCHAR(30),
	@EndTime VARCHAR(30),
	@ManagerUserID INT,
	@Type INT
)
AS
BEGIN
	IF @Type = 1
	BEGIN
		SELECT status,COUNT(1) cnt,COUNT(DISTINCT outurl) cnt2 
		FROM outlink WITH(NOLOCK) 
		WHERE adddate>@BeginTime 
		AND adddate<@EndTime 
		AND manageruserid=@ManagerUserID 
		GROUP BY status
	END
	ELSE IF @Type = 2
	BEGIN
		SELECT outlinkresources.kind,COUNT(1) cnt,COUNT(DISTINCT outurl) cnt2 
		FROM outlink WITH(NOLOCK),outlinkresources WITH(NOLOCK) 
		WHERE outlink.outlinkresources_id=outlinkresources.id 
		AND outlink.adddate>@BeginTime 
		AND outlink.adddate<@EndTime		
		AND outlink.manageruserid=@ManagerUserID 
		GROUP BY outlinkresources.kind
	END
	ELSE IF @Type = 3
	BEGIN
		SELECT copy,count(1) cnt,count(DISTINCT outurl) cnt2 
		FROM outlink WITH(NOLOCK) 
		WHERE adddate>@BeginTime 
		AND adddate<@EndTime 
		AND manageruserid=@ManagerUserID 
		GROUP BY copy
	END
END

GO
/****** Object:  StoredProcedure [dbo].[bpOutlinkByOutUrlSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.09.06
--创建人：Nick
--说明：根据outurl查询outlink
--#####################################################
create PROCEDURE [dbo].[bpOutlinkByOutUrlSelect]
(
	@OutUrl VARCHAR(200)
)
AS
BEGIN
	SELECT COUNT(1) cnt FROM outlink with(nolock) WHERE outurl = @OutUrl
END

GO
/****** Object:  StoredProcedure [dbo].[bpOutLinkByStatusSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.09.06
--创建人：Nick
--说明：外部链接列表
--#####################################################
CREATE PROCEDURE [dbo].[bpOutLinkByStatusSelect] 
(
	@WHERE VARCHAR(MAX),
	@Type INT,
	@DCopy VARCHAR(10),
	@Status VARCHAR(10),
	@AddDate VARCHAR(20),
	@Search_Item VARCHAR(10),
	@Search_Text VARCHAR(100),
	@Search_Action VARCHAR(10),
	@UserName VARCHAR(100),
	@BeginDate VARCHAR(20),
	@EndDate VARCHAR(20),
	@BeginTime VARCHAR(30),
	@EndTime VARCHAR(30)
)
AS
BEGIN
	DECLARE @SQL VARCHAR(MAX),@Day INT,@Year INT,@Month INT
	SELECT @Day = DATEPART(DAY,GETDATE()),@Year = DATEPART(YEAR,GETDATE()),@Month = DATEPART(MONTH,GETDATE())

	SET @SQL = 'SELECT TOP 1000 outlink.id,outlink.outurl,outlink.manageruserid,outlink.adddate,outlink.site,outlink.yst_clicknum,outlink.mth_clicknum,
		outlink.status,outlink.checkdate,outlink.remarks,outlink.keywords,outlink.errornum,outlink.username,outlink.password,outlink.outlinkResources_id,
		outlink.ip,outlink.copy 
		FROM outlink WITH(NOLOCK),outlinkresources WITH(NOLOCK) 
		WHERE outlink.outlinkresources_id=outlinkresources.id '
	SET @SQL = @SQL + @WHERE
	IF @Type <> 0
	BEGIN
		SET @SQL = @SQL + ' AND OutLinkResources.Kind = '+CONVERT(VARCHAR(10),@Type)
	END
	IF @DCopy <> ''
	BEGIN
		SET @SQL = @SQL + ' AND outlink.copy = '+@DCopy
	END
	IF @Status <> ''
	BEGIN
		IF @Status = '4'
		BEGIN
			SET @SQL = @SQL + ' AND outLinkResources_id IS NULL'
		END
		ELSE
		BEGIN
			SET @SQL = @SQL + ' AND outlink.status = '+@Status
		END
	END
	IF @AddDate <> ''
	BEGIN
		SET @SQL = @SQL + ' AND outlink.adddate> '+@BeginTime+' AND outlink.adddate< ' + @EndTime
	END
	IF @Search_Item = '1' AND @Search_Text <> ''
	BEGIN
		IF @Search_Action = '1'
		BEGIN
			SET @SQL = @SQL + ' AND outurl LIKE ''%'+@Search_Text+'%'' '
		END
		ELSE IF @Search_Action = '2'
		BEGIN
			SET @SQL = @SQL + ' AND outurl LIKE '''+@Search_Text+''' '
		END
	END
	ELSE IF @Search_Item = '2' AND @Search_Text <> ''
	BEGIN
		IF @Search_Action = '1'
		BEGIN
			SET @SQL = @SQL + ' AND SITE LIKE ''%'+@Search_Text+'%'' '
		END
		ELSE IF @Search_Action = '2'
		BEGIN
			SET @SQL = @SQL + ' AND SITE LIKE '''+@Search_Text+''' '
		END
	END
	ELSE IF @Search_Item = '3' AND @Search_Text <> ''
	BEGIN
		IF @Search_Action = '2'
		BEGIN
			SET @SQL = @SQL + ' AND manageruserid = '+@Search_Text
		END
	END
	ELSE IF @Search_Item = '4' AND @Search_Text <> ''
	BEGIN
		IF @Search_Action = '2' OR @Search_Action = '1'
		BEGIN
			SET @SQL = @SQL + ' AND outlink.keywords LIKE ''%'+@Search_Text+'%'' '
		END
	END
	IF @UserName <> ''
	BEGIN
		SET @SQL = @SQL + ' AND outlink.Username = '+@UserName
	END
	IF @BeginDate <> ''
	BEGIN
		SET @SQL = @SQL + ' AND outlink.adddate >= '''+@BeginDate+' 00:00'' '
	END
	IF @EndDate <> ''
	BEGIN
		SET @SQL = @SQL + ' AND outlink.adddate <= '''+@EndDate+' 23:59'' '
	END
	SET @SQL = @SQL + ' ORDER BY outlink.adddate DESC'
	print (@SQL)
	EXEC (@SQL)
END

GO
/****** Object:  StoredProcedure [dbo].[bpOutlinkByStatusUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.09.06
--创建人：Nick
--说明：根据ID修改outlink
--#####################################################
create PROCEDURE [dbo].[bpOutlinkByStatusUpdate]
(
	@ID INT,
	@Status INT
)
AS
BEGIN
	UPDATE OutLink SET Status = @Status WHERE ID  = @ID
END

GO
/****** Object:  StoredProcedure [dbo].[bpOutLinkInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.09.08
--创建人：Nick
--说明：插入 OutLink
--#####################################################
create PROCEDURE [dbo].[bpOutLinkInsert]
(
	@KeyWords VARCHAR(200),
	@KeyWords2 VARCHAR(200),
	@Site VARCHAR(100),
	@Site2 VARCHAR(100),	
	@ManagerUserID INT,
	@OutUrl VARCHAR(200),
	@Resources_id INT,
	@Remarks VARCHAR(500),
	@UserName VARCHAR(50),
	@Psssword VARCHAR(50),
	@IP VARCHAR(30),
	@Copy INT,
	@AddDate VARCHAR(20)
)
AS
BEGIN
	DECLARE @CNT INT
	IF @KeyWords <> ''
	BEGIN
		SELECT @CNT = COUNT(1) 
		FROM outlink WITH(NOLOCK) 
		WHERE site = @Site 
		AND adddate > ''+@AddDate+''
		IF @CNT >= 50 AND  @ManagerUserID <> 365
		BEGIN
			RETURN 2 --此域名今天已经增加50条，不能继续增加
		END
		ELSE 
		BEGIN
			INSERT INTO outlink (outurl,manageruserid,site,outlinkResources_id,keywords,remarks,username,password,ip,copy) 
			VALUES(@OutUrl,@ManagerUserID,@Site,@Resources_id,@KeyWords,@Remarks,@UserName,@Psssword,@IP,@Copy)

			RETURN 1 --增加成功 
		END
	END
	IF @KeyWords2 <> ''
	BEGIN
		SELECT @CNT = COUNT(1)  
		FROM outlink WITH(NOLOCK) 
		WHERE site = @Site2 
		AND adddate > ''+@AddDate+''
		IF @CNT >= 20 AND  @ManagerUserID <> 365
		BEGIN
			RETURN 3 --此域名今天已经增加9条，不能继续增加
		END
		ELSE 
		BEGIN
			INSERT INTO outlink (outurl,manageruserid,site,outlinkResources_id,keywords,remarks,username,password,ip,copy) 
			VALUES(@OutUrl,@ManagerUserID,@Site2,@Resources_id,@KeyWords2,@Remarks,@UserName,@Psssword,@IP,@Copy)

			RETURN 1 --增加成功 
		END
	END
	RETURN 4 --增加失败
END

GO
/****** Object:  StoredProcedure [dbo].[bpOutlinkResourcesByAddManSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.09.08
--创建人：Nick
--说明：outlinkResources
--#####################################################
create PROCEDURE [dbo].[bpOutlinkResourcesByAddManSelect]
(
	@AddMan INT,
	@RowNo INT
)
AS
BEGIN
	SELECT TOP 3 * 
	FROM (
		SELECT *,row_number() OVER(ORDER BY groupid,kind,name) rowNo  
		FROM outlinkResources WITH(NOLOCK) 
		WHERE status=1 
		AND groupid=4 
		AND addman = @AddMan ) a 
	WHERE rowNo>=@RowNo 
END

GO
/****** Object:  StoredProcedure [dbo].[bpOutlinkResourcesByGroupIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.09.06
--创建人：Nick
--说明：根据GroupID查询outlinkResources
--#####################################################
create PROCEDURE [dbo].[bpOutlinkResourcesByGroupIDSelect]
(
	@Status INT,
	@GroupID INT
)
AS
BEGIN
	SELECT * FROM outlinkResources WITH(NOLOCK) WHERE STATUS=@Status AND groupid=@GroupID ORDER BY groupid,kind,name
END

GO
/****** Object:  StoredProcedure [dbo].[bpOutLinkResourcesByIDDelete]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.09.06
--创建人：Nick
--说明：删除链接 资源
--#####################################################
create PROCEDURE [dbo].[bpOutLinkResourcesByIDDelete]
(
	@ID INT
)
AS
BEGIN
		DELETE FROM outlinkResources WHERE ID = @ID
END

GO
/****** Object:  StoredProcedure [dbo].[bpOutlinkResourcesByIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.09.06
--创建人：Nick
--说明：根据ID查询outlinkResources
--#####################################################
CREATE PROCEDURE [dbo].[bpOutlinkResourcesByIDSelect]
(
	@ID INT
)
AS
BEGIN
	SELECT * FROM outlinkResources WITH(NOLOCK) WHERE id = @ID
END

GO
/****** Object:  StoredProcedure [dbo].[bpOutLinkResourcesByIDUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.09.06
--创建人：Nick
--说明：外链资源修改
--#####################################################
create PROCEDURE [dbo].[bpOutLinkResourcesByIDUpdate]
(
	@Name VARCHAR(50),
	@LoginUrl VARCHAR(200),
	@RegUrl VARCHAR(200),
	@Kind INT,
	@Status INT,
	@Remarks VARCHAR(MAX),
	@GroupID INT,
	@Example VARCHAR(200),
	@SecretQuestion VARCHAR(500),
	@SecretAnswer VARCHAR(500),
	@ID INT
)
AS
BEGIN
	UPDATE outlinkResources 
	SET name=@Name,loginurl=@LoginUrl,regurl=@RegUrl,remarks = @Remarks,kind = @Kind,
		status = @Status,groupid = @GroupID,Example=@Example,SecretQuestion=@SecretQuestion,SecretAnswer=@SecretAnswer 
	WHERE @ID = @ID
END

GO
/****** Object:  StoredProcedure [dbo].[bpOutLinkResourcesByStatusSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.09.06
--创建人：Nick
--说明：外部链接资源列表 
--#####################################################
CREATE PROCEDURE [dbo].[bpOutLinkResourcesByStatusSelect]
(
	@Kind INT,
	@GroupID INT,
	@Status VARCHAR(10),
	@AddDate VARCHAR(20),
	@Search_Item VARCHAR(10),
	@Search_Text VARCHAR(100),
	@Search_Action VARCHAR(10),
	@OrderBy INT,
	@BeginTime VARCHAR(30),
	@EndTime VARCHAR(30)
)
AS
BEGIN
	DECLARE @SQL VARCHAR(MAX)

	SET @SQL = 'SELECT * FROM OutLinkResources WITH(NOLOCK) WHERE 1=1 '
	IF @Kind <> 0
	BEGIN
		SET @SQL = @SQL + ' AND Kind = '+CONVERT(VARCHAR(10),@Kind)
	END
	IF @Status <> ''
	BEGIN
		SET @SQL = @SQL + ' AND status = '+@Status
	END
	IF @GroupID <> 0
	BEGIN
		SET @SQL = @SQL + ' AND GroupID = '+CONVERT(VARCHAR(10),@GroupID)
	END
	IF @AddDate <> ''
	BEGIN
		SET @SQL = @SQL + ' AND adddate> '''+@BeginTime+''' AND adddate< ''' + @EndTime +''''
	END

	IF @Search_Item = '1' AND @Search_Text <> ''
	BEGIN
		IF @Search_Action = '1'
		BEGIN
			SET @SQL = @SQL + ' AND NAME LIKE ''%'+@Search_Text+'%'' '
		END
		ELSE IF @Search_Action = '2'
		BEGIN
			SET @SQL = @SQL + ' AND NAME LIKE '''+@Search_Text+''' '
		END
	END
	ELSE IF @Search_Item = '2' AND @Search_Text <> ''
	BEGIN
		IF @Search_Action = '1'
		BEGIN
			SET @SQL = @SQL + ' AND LoginUrl LIKE ''%'+@Search_Text+'%'' '
		END
		ELSE IF @Search_Action = '2'
		BEGIN
			SET @SQL = @SQL + ' AND LoginUrl LIKE '''+@Search_Text+''' '
		END
	END
	ELSE IF @Search_Item = '3' AND @Search_Text <> ''
	BEGIN
		IF @Search_Action = '1'
		BEGIN
			SET @SQL = @SQL + ' AND RegUrl LIKE ''%'+@Search_Text+'%'' '
		END
		ELSE IF @Search_Action = '2'
		BEGIN
			SET @SQL = @SQL + ' AND RegUrl LIKE '''+@Search_Text+''' '
		END
	END
	ELSE IF @Search_Item = '4' AND @Search_Text <> ''
	BEGIN
		IF @Search_Action = '2'
		BEGIN
			SET @SQL = @SQL + ' AND addman = '+@Search_Text
		END
	END
	IF @OrderBy =1 OR @OrderBy = 0
	BEGIN
		SET @SQL = @SQL + ' ORDER BY kind,name'
	END
	ELSE IF @OrderBy =2
	BEGIN
		SET @SQL = @SQL + ' ORDER BY AddMan'
	END
	ELSE IF @OrderBy =3
	BEGIN
		SET @SQL = @SQL + ' ORDER BY AddDate DESC'
	END
	EXEC (@SQL)
END

GO
/****** Object:  StoredProcedure [dbo].[bpOutLinkResourcesInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.09.06
--创建人：Nick
--说明：外链资源添加
--#####################################################
create PROCEDURE [dbo].[bpOutLinkResourcesInsert]
(
	@Name VARCHAR(50),
	@ManagerUserID INT,
	@LoginUrl VARCHAR(200),
	@RegUrl VARCHAR(200),
	@Kind INT,
	@Remarks VARCHAR(MAX),
	@GroupID INT,
	@Example VARCHAR(200),
	@SecretQuestion VARCHAR(500),
	@SecretAnswer VARCHAR(500)
)
AS
BEGIN
	IF EXISTS(SELECT TOP 1 * FROM OutLinkResources WHERE NAME = @Name)
	BEGIN
		RETURN 0
	END
	INSERT INTO OutLinkResources (name,addman,loginurl,regurl,kind,remarks,groupid,example,SecretQuestion ,SecretAnswer ) 
	VALUES(@Name,@ManagerUserID,@LoginUrl,@RegUrl,@Kind,@Remarks,@GroupID,@Example,@SecretQuestion,@SecretAnswer)
	RETURN 1
END

GO
/****** Object:  StoredProcedure [dbo].[bppaFeedBackByIdSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--==================================================
--创建：	lambo	2010-9-21
--检查 sean 2010-10-8
--描述 后台提取一个个人用户反馈
--==================================================
CREATE PROCEDURE [dbo].[bppaFeedBackByIdSelect]
    @ID INT
AS
BEGIN
    SELECT *
    FROM paFeedBack WITH(NOLOCK INDEX(PK_paFeedback))
    WHERE ID = @ID
	ORDER BY ID DESC
END














GO
/****** Object:  StoredProcedure [dbo].[bpPaFeedbackSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-----------------
--创建日期：2010-9-21
--创建人：lambo
--功能说明：根据条件查询个人用户反馈
--用于后台客户服务模块，个人用户反馈页面
-----------------
CREATE PROCEDURE [dbo].[bpPaFeedbackSelect]
(
	@WHERE VARCHAR(1000)
)
AS
BEGIN
	DECLARE @SQL VARCHAR(2000)
	SET @SQL = 'SELECT TOP 500 * FROM paFeedback WITH(NOLOCK) WHERE 1=1 '
	IF LEN(@WHERE) > 0
	BEGIN
		SET @Where = dbo.SafeSql(@Where)
		SET @SQL = @SQL + @WHERE
	END
	SET @SQL = @SQL + ' ORDER BY AddDate DESC'
	EXEC(@SQL)
END



GO
/****** Object:  StoredProcedure [dbo].[bppaFeedbackUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----------------
--创建日期：2010-9-21
--创建人：lambo
--功能说明：根据编号修改个人用户反馈的回复信息
--用于后台个人用户反馈模块的回复和重新回复
-----------------
CREATE PROCEDURE [dbo].[bppaFeedbackUpdate]
(
	@ID INT,
	@ReplyMessage VARCHAR(2000),
	@ReplyMan INT,
	@SendMsg INT
)
AS
BEGIN TRY
	UPDATE paFeedback SET IsReply=1, ReplyDate=GETDATE(), ReplyMessage=@ReplyMessage,ReplyMan=@ReplyMan WHERE ID=@ID
	--短信发送
	IF @SendMsg = 1
		INSERT SmsMessageLog(SendMan, ManagerUSerId, paMainId, caMainId, Mobile, MsgType, IsCat, Msg)
		SELECT  @ReplyMan, NULL, a.ID, NULL, a.Mobile, 103 ,0, 
			IsNULL(a.Name,'') + '您好，您在' + b.subsitename + b.EmailSite + '上提交的问题已经答复，请登录查看，祝您求职顺利'
		FROM paMain a WITH(NOLOCK), dcSubSite b WITH(NOLOCK), paFeedback c WITH(NOLOCK)
		WHERE a.dcSubSiteID = b.ID
		AND a.ID = c.paMainID
		AND a.Mobile > ''
		AND c.ID = @ID
		AND a.IsReceiveSms = 1

	RETURN 1
END TRY
BEGIN CATCH
	RETURN 0
END CATCH














GO
/****** Object:  StoredProcedure [dbo].[bpPageBaiduIncludeByCheckDateSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.09.06
--创建人：Nick
--说明：百度收录日报
--#####################################################
CREATE PROCEDURE [dbo].[bpPageBaiduIncludeByCheckDateSelect]
(
	@CheckDate VARCHAR(20)
)
AS
BEGIN
	DECLARE @SQL VARCHAR(MAX)
	SET @SQL = 'SELECT TOP 30 CONVERT(VARCHAR(10), checkdate, 120) checkdate, COUNT(*) cnt,	 
		SUM(CASE WHEN includedate > '''' THEN 1 ELSE 0 END) iCount, 
		SUM(CASE WHEN includedate > '''' THEN 1 ELSE 0 END) *1.0/count(*) k 
		FROM PageBaiduInclude '
	IF @CheckDate <> ''
	BEGIN
		SET @SQL = @SQL + ' WHERE CheckDate<'''+@CheckDate+''''
	END
	ELSE
	BEGIN
		SET @SQL = @SQL + ' WHERE CheckDate<GETDATE() ' 
	END
	SET @SQL = @SQL + ' GROUP BY CONVERT(VARCHAR(10), CheckDate, 120) ORDER BY CONVERT(VARCHAR(10), CheckDate, 120) DESC'
	PRINT @SQL
	EXEC (@SQL)
END



GO
/****** Object:  StoredProcedure [dbo].[bpPageBaiduIncludeByDateSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.09.06
--创建人：Nick
--说明：百度收录列表
--#####################################################
CREATE PROCEDURE [dbo].[bpPageBaiduIncludeByDateSelect]
(
	@BeginDate VARCHAR(50),
	@EndDate VARCHAR(50)
)
AS
BEGIN
	DECLARE @SQL VARCHAR(MAX)
	SET @SQL = 'SELECT count(1) cnt,SUM(CASE WHEN includedate > '' THEN 1 ELSE 0 END),
		SUM(CASE WHEN includedate > '' THEN 1 ELSE 0 END) ,
		SUM(CASE WHEN includedate > '' THEN 1 ELSE 0 END) iCount,
		SUM(CASE WHEN includedate > '' THEN 1 ELSE 0 END) * 1.0/COUNT(1) k 
		FROM PageBaiduInclude a WITH(NOLOCK) 
		WHERE  1=1 '
	IF @BeginDate <> ''
	BEGIN
		SET @SQL = @SQL + ' And CheckDate>= '''+@BeginDate+''' '
		IF @EndDate <> ''
		BEGIN
			SET @SQL = @SQL + ' And CheckDate<= '''+@EndDate+' 23:59 '''
		END
	END
	EXEC (@SQL)
END

GO
/****** Object:  StoredProcedure [dbo].[bpPageBaiduIncludeByPageTypeSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.09.06
--创建人：Nick
--说明：百度收录列表
--#####################################################
CREATE PROCEDURE [dbo].[bpPageBaiduIncludeByPageTypeSelect]
(
	@CpMainID VARCHAR(20),
	@JobID VARCHAR(20),
	@CheckType INT,
	@PageType INT,
	@BeginDate VARCHAR(50),
	@EndDate VARCHAR(50),
	@OrderBy INT
)
AS
BEGIN
	DECLARE @SQL VARCHAR(MAX),@WHERE VARCHAR(2000)
	SET @WHERE = ''
	IF @CpMainID <> ''
	BEGIN
		SET @WHERE = @WHERE + ' And PageType=1 and PageID= '+CONVERT(VARCHAR(20),@CpMainID)
	END

	IF @JobID <> ''
	BEGIN
		SET @WHERE = @WHERE + ' And PageType=2 and PageID= '+ CONVERT(VARCHAR(20),@JobID)
	END
	IF @CheckType = 1
	BEGIN
		IF @BeginDate <> ''
		BEGIN
			SET @WHERE = @WHERE + ' And CheckDate>='''+@BeginDate+''''
		END
		IF @EndDate <> ''
		BEGIN
			SET @WHERE = @WHERE + ' And CheckDate<='''+@EndDate+' 23:59'''
		END
	END
	ELSE IF @CheckType = 2
	BEGIN
		IF @BeginDate <> ''
		BEGIN
			SET @WHERE = @WHERE + ' And IncludeDate>='''+@BeginDate+''''
		END
		IF @EndDate <> ''
		BEGIN
			SET @WHERE = @WHERE + ' And IncludeDate<='''+@EndDate+' 23:59'''
		END
	END
	ELSE IF @CheckType = 3
	BEGIN
		IF @BeginDate <> ''
		BEGIN
			SET @WHERE = @WHERE + ' And PageType=1 And exists(
				SELECT ''x'' FROM cpmain WITH(NOLOCK) 
				WHERE RegDate>'''+@BeginDate+''' 
				AND id=a.PageID)'
		END
		IF @EndDate <> ''
		BEGIN
			SET @WHERE = @WHERE + ' And PageType=1 And exists(
				SELECT ''x'' FROM cpmain WITH(NOLOCK) 
				WHERE RegDate<'''+@EndDate+' 23:59'' 
				AND id=a.PageID)'
		END
	END
	ELSE IF @CheckType = 4
	BEGIN
		IF @BeginDate <> ''
		BEGIN
			SET @WHERE = @WHERE + ' And PageType=2 And exists(
				SELECT ''x'' FROM Job WITH(NOLOCK) 
				WHERE AddDate>'''+@BeginDate+''' 
				AND id=a.PageID)'
		END
		IF @EndDate <> ''
		BEGIN
			SET @WHERE = @WHERE + ' And PageType=1 And exists(
				SELECT ''x'' FROM Job WITH(NOLOCK) 
				WHERE AddDate<'''+@EndDate+' 23:59'' 
				AND id=a.PageID)'
		END
	END

	IF @PageType <> 0
	BEGIN
		SET @WHERE = @WHERE + ' And PageType = '+CONVERT(VARCHAR(10),@PageType)
	END

	SET @SQL = 'SELECT TOP 1000 a.*,b.ProvinceName,ProvinceDomain 
		FROM PageBaiduInclude a WITH(NOLOCK),dcprovince b with(nolock) 
		WHERE a.dcSubsiteID = b.id  '+ @WHERE

	IF @OrderBy = 1
	BEGIN
		SET @SQL = @SQL + ' ORDER BY IncludeDate DESC'
	END
	ELSE
	BEGIN
		SET @SQL = @SQL + ' ORDER BY CheckDate DESC'
	END
	PRINT (@SQL)
	EXEC (@SQL)
END

GO
/****** Object:  StoredProcedure [dbo].[bpPageViewMainByStatisticsSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [dbo].[bpPageViewMainByStatisticsSelect]
(
	@intDate INT
)
AS
BEGIN
	CREATE TABLE #Tmp --创建临时表#Tmp
	(
		ID INT IDENTITY(1, 1),
    	CountDate    INT,
    	VersionId    VARCHAR(50),   
    	ViewNumber   INT,
    	ProvinceName VARCHAR(100)
	)

	INSERT INTO #Tmp(CountDate, VersionId, ViewNumber, ProvinceName)
	SELECT a.CountDate,a.VersionId,a.ViewNumber,b.ProvinceName 
	FROM maindb..Counter a WITH(NOLOCK) 
	LEFT JOIN maindb..dcProvince b ON b.Id = a.VersionId 
	WHERE (LEN(VersionId) = 2 OR LEN(VersionId) = 1) AND CONVERT(INT,CountDate) <= @intDate
	ORDER BY CountDate DESC,ISNULL(b.SouthNorth,4) DESC,CASE VersionId WHEN 90 THEN 0 ELSE 1 END,VersionId 
	
	INSERT INTO #Tmp(CountDate, VersionId, ViewNumber, ProvinceName)
	SELECT a.CountDate,a.VersionId,a.ViewNumber,b.ProvinceName
	FROM logdb..CounterLog a WITH(NOLOCK)
	LEFT JOIN maindb..dcProvince b ON b.id = a.VersionId
	WHERE (LEN(VersionId) = 2 OR LEN(VersionId) = 1) AND CONVERT(INT,CountDate) <= @intDate
		AND CONVERT(INT,CountDate) >= LEFT(CONVERT(VARCHAR(50), @intDate),6) + '01'
	ORDER BY CountDate DESC,ISNULL( b.SouthNorth,4) DESC,CASE VersionId WHEN 90 THEN 0 ELSE 1 END,VersionId 

	SELECT * FROM #Tmp ORDER BY ID
END
GO
/****** Object:  StoredProcedure [dbo].[bpPaMainByEmailSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.09.17
--创建人：Nick
--说明：根据ID查询cvImportPrev
--#####################################################
CREATE PROCEDURE [dbo].[bpPaMainByEmailSelect]
(
	@Email VARCHAR(50)
)
AS
BEGIN
	SELECT TOP 1 a.ID,a.Name,a.UserName,b.WebSiteName,(
		SELECT Count(*) 
		FROM cvMain WITH(NOLOCK) 
		WHERE paMainID=a.id AND cvLevel LIKE '1111_1%'
	) cnt  
	FROM PaMain a with(nolock), dcprovince b with(nolock) 
	WHERE a.dcprovinceid = b.id and a.Email=@Email 
	Order BY a.LastLoginDate DESC
END


GO
/****** Object:  StoredProcedure [dbo].[bpPaMainByIDUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.01.23
--创建人：Nick
--说明：审核个人信息
--#####################################################
CREATE PROCEDURE [dbo].[bpPaMainByIDUpdate]
(
    @Name VARCHAR(50),
    @NameEng VARCHAR(50),
    @OnlineContactNo VARCHAR(50),
    @HomePage VARCHAR(200),
    @Mobile VARCHAR(20),
    @ID INT
)
AS
BEGIN
    DECLARE @SQL VARCHAR(1000)
    SET @SQL = 'Update PaMain Set '
    IF @Name <> ''
        SET @SQL = @SQL + ' Name= ''' + @Name + ''','
    
    IF @NameEng <> ''
        SET @SQL = @SQL + ' NameEng=''' + @NameEng + ''','
    
    IF @OnlineContactNo <> ''
        SET @SQL = @SQL + ' OnlineContactNo=''' + @OnlineContactNo + ''','
    ELSE 
        SET @SQL = @SQL + ' OnlineContactNo=Null,OnlineContact=Null,'
    
    IF @HomePage <> ''
        SET @SQL = @SQL + ' HomePage=''' + @HomePage+''','
    ELSE 
        SET @SQL = @SQL + ' HomePage=Null,'

    IF @Mobile <> ''
        SET @SQL = @SQL + ' Mobile=''' + @Mobile + ''','
    ELSE 
        SET @SQL = @SQL + ' Mobile = Null, MobileVerifyDate = NULL,'
    
    SET @SQL = SUBSTRING(@SQL,0,LEN(@SQL))
    
    SET @SQL = @SQL + ' WHERE ID = '+CONVERT(VARCHAR(20),@ID)
    --PRINT @SQL
    EXEC(@SQL)
    
    DELETE FROM bsCvModify WHERE paMainID = @ID
END
GO
/****** Object:  StoredProcedure [dbo].[bpPaMainByRegisterSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--创建人 Andy
--时间 2015-01-23
--按照条件查询个人注册情况
--修改：2015-01-26 andy。添加排序
CREATE PROCEDURE [dbo].[bpPaMainByRegisterSelect] 
(		
	@StartDate DATETIME,
	@EndDate DATETIME,
	@ManagerUserID INT,
	@Province INT,
	@IP VARCHAR(15)	
)
AS
BEGIN	
	SET @IP = dbo.SafeSql(@IP)
	DECLARE @SQL VARCHAR(1000)
	SET @SQL = '
		SELECT TOP 2000 a.*, b.Name ManagerName, c.ProvinceName 
		FROM paMain a, Manageruser b, dcProvince c 
		WHERE a.dcProvinceID = c.ID 
		AND a.AddMan = b.ID 
		AND (a.RegisterMode = 11 or a.RegisterType = 102)  
		AND a.AddDate >= ''' + CONVERT(VARCHAR(20), @StartDate, 20) + ''' 
		AND a.AddDate <= ''' + CONVERT(VARCHAR(20), @EndDate, 20) + ''''
	IF LEN(@IP) > 0
		SET @SQL = @SQL + ' AND a.RegisterIP = ''' + @IP + ''''	
	IF @ManagerUserID > 0
		SET @SQL = @SQL + ' AND a.AddMan = ' + LTRIM(STR(@ManagerUserID))			
	IF @Province > 0
		SET @SQL = @SQL + ' AND a.dcProvinceID = ' + LTRIM(STR(@Province))	
	SET @SQL = @SQL + ' Order By AddDate DESC ' 
			
	--PRINT(@SQL)
	EXEC (@SQL)
END
GO
/****** Object:  StoredProcedure [dbo].[bpPaMainByRegisterStatisticsSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--创建人 Andy
--时间 2015-01-23
--按照条件统计个人注册
CREATE PROCEDURE [dbo].[bpPaMainByRegisterStatisticsSelect] 
(		
	@StartDate DATETIME,
	@EndDate DATETIME,
	@ManagerUserID INT,
	@Province INT,
	@IP VARCHAR(15)	
)
AS
BEGIN	
	SET @IP = dbo.SafeSql(@IP)
	DECLARE @SQL VARCHAR(1000)
	SET @SQL = '
		SELECT TOP 2000 RegisterIP, COUNT(1) cnt 
		FROM paMain 
		WHERE RegisterMode = 11 or RegisterType = 102 		  
		AND AddDate >= ''' + CONVERT(VARCHAR(20), @StartDate, 20) + ''' 
		AND AddDate <= ''' + CONVERT(VARCHAR(20), @EndDate, 20) + ''''
	IF LEN(@IP) > 0
		SET @SQL = @SQL + ' AND RegisterIP = ''' + @IP + ''''	
	IF @ManagerUserID > 0
		SET @SQL = @SQL + ' AND AddMan = ' + LTRIM(STR(@ManagerUserID))			
	IF @Province > 0
		SET @SQL = @SQL + ' AND dcProvinceID = ' + LTRIM(STR(@Province))			
	SET @SQL = @SQL + ' GROUP BY RegisterIP HAVING COUNT(1)>2'
	SET @SQL = @SQL + ' ORDER BY cnt DESC'
	--PRINT(@SQL)
	EXEC (@SQL)
END

GO
/****** Object:  StoredProcedure [dbo].[bpPaMainDelete]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-----------------
--创建日期：2010-9-25
--创建人：lambo
--功能说明：根据编号删除一份简历，同时删除该简历的其它关联表的相关数据
--用于后台个人搜索页面
-----------------
CREATE PROCEDURE [dbo].[bpPaMainDelete]
	@paMainID INT
AS
BEGIN TRAN
	--BEGIN TRY
		DECLARE @cvIDs Table(ID INT)
		INSERT INTO @cvIDS SELECT ID FROM cvMain WHERE paMainID = @paMainID
		DELETE FROM cvEducation WHERE cvMainID IN (SELECT ID FROM @cvIDS)
		DELETE FROM cvExperience WHERE cvMainID IN (SELECT ID FROM @cvIDS)
		DELETE FROM cvIndustry WHERE cvMainID IN (SELECT ID FROM @cvIDS)
		DELETE FROM cvJobPlace WHERE cvMainID IN (SELECT ID FROM @cvIDS)
		DELETE FROM cvJobType WHERE cvMainID IN (SELECT ID FROM @cvIDS)
		DELETE FROM cvLanguage WHERE cvMainID IN (SELECT ID FROM @cvIDS)
		DELETE FROM cvProject WHERE cvMainID IN (SELECT ID FROM @cvIDS)
		DELETE FROM cvTraining WHERE cvMainID IN (SELECT ID FROM @cvIDS)
		DELETE FROM exMessageC2P WHERE cvMainID IN (SELECT ID FROM @cvIDS)
		DELETE FROM exMessageP2C WHERE cvMainID IN (SELECT ID FROM @cvIDS)
		DELETE FROM exJobApply WHERE cvMainID IN (SELECT ID FROM @cvIDS)
		DELETE FROM cvAppendix WHERE cvMainID IN (SELECT ID FROM @cvIDS)
		DELETE FROM caFavorate WHERE cvMainID IN (SELECT ID FROM @cvIDS)
		DELETE FROM exInterview WHERE cvMainID IN (SELECT ID FROM @cvIDS)
		DELETE FROM caCvViewLog WHERE cvMainID IN (SELECT ID FROM @cvIDS)
		DELETE FROM bsCvModify WHERE paMainID = @paMainID
		DELETE FROM bsCvVerifyLog WHERE cvMainID IN (SELECT ID FROM @cvIDS)
		DELETE FROM bsCvVerify WHERE cvMainID IN (SELECT ID FROM @cvIDS)
		DELETE FROM bsPaBackLogin WHERE paMainID = @paMainID
		DELETE FROM cvMain WHERE paMainID =@paMainID

		DELETE FROM paPhoto WHERE paMainID = @paMainID
		DELETE FROM paOperationLog WHERE paMainID = @paMainID
		DELETE FROM paLoginLog WHERE paMainID = @paMainID
		DELETE FROM paJobViewLog WHERE paMainID = @paMainID
		DELETE FROM paCoverLetter WHERE paMainID = @paMainID
		DELETE FROM paLoginContact WHERE paMainId = @paMainId
		DELETE FROM paMain WHERE ID = @paMainID		
--	END TRY
--	BEGIN CATCH
--		GOTO ERR
--	END CATCH
COMMIT TRAN
RETURN 1
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END














GO
/****** Object:  StoredProcedure [dbo].[bpPaMainSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--[bpPaMainSelect] ' order by a.adddate ','50',1,' a.lastlogindate desc '
--carl 2018-2-2
--harry 2018-6-6 修改排序
CREATE PROCEDURE [dbo].[bpPaMainSelect]
(
	@WHERE VARCHAR(1000),
	@recnum VARCHAR(4),
	@Page TINYINT,
	@OrderBy VARCHAR(1000)
)
AS
SET NOCOUNT ON
BEGIN
		DECLARE @SQL VARCHAR(2000)
		CREATE TABLE #T(
			TitleID INT,
			paMainID INT,
			[Name] NVARCHAR(100),
			HasPhoto TINYINT,
			LastLoginDate SMALLDATETIME,
			VerifyResult TINYINT,
			VerifyMan SMALLINT,
			AddDate SMALLDATETIME, --新增项
			Mobile VARCHAR(20)
		)
		SET @SQL='
			INSERT INTO #T
				(TitleID,paMainID,Name,HasPhoto,LastLoginDate,AddDate,Mobile)
			SELECT TOP ' + @recnum + ' ROW_NUMBER() OVER (ORDER BY '+@OrderBy+') AS TitleID,
				a.ID,a.Name,a.HasPhoto,a.LastLoginDate,a.AddDate,a.Mobile FROM paMain a WITH(NOLOCK)'

		IF LEN(@WHERE) > 0
		BEGIN
			IF CHARINDEX('b.', @WHERE)>0 
				SET @SQL = @SQL + ' INNER JOIN cvMain b WITH(NOLOCK) ON a.ID = b.PaMainID'
			SET @SQL = @SQL + ' WHERE 1=1 ' + @WHERE
		END

		EXEC(@SQL)
		--UPDATE a SET a.VerifyMan = b.VerifyMan FROM #T a ,bsCvVerify b WITH(NOLOCK) WHERE b.paMainID = a.paMainID
		--AND TitleID > (@Page-1)*20 AND TitleID <= @Page*20
		SELECT COUNT(*) FROM #T WITH(NOLOCK)
		DECLARE @begin INT, @end INT
		SET @begin= (@Page-1)*20
		SET @end=@Page*20
		SET @SQL='SELECT * FROM #T a WITH(NOLOCK) LEFT JOIN paContact c WITH(NOLOCK) ON c.pamainId=a.pamainId WHERE TitleID > '+CONVERT(varchar(100),@begin)+'AND TitleID <= '+CONVERT(varchar(100),@end)+' order by '+@OrderBy
                 EXEC(@SQL)
		DROP TABLE #T
END
SET NOCOUNT OFF
GO
/****** Object:  StoredProcedure [dbo].[bpPaMainSelect2]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[bpPaMainSelect2]
(
	@WHERE VARCHAR(1000),
	@recnum VARCHAR(3),
	@Page TINYINT,
	@OrderBy VARCHAR(1000)
)
AS
SET NOCOUNT ON
BEGIN
	DECLARE @SQL VARCHAR(2000)
	CREATE TABLE #T(
		TitleID INT,
		paMainID INT,
		[Name] NVARCHAR(100),
		HasPhoto TINYINT,
		LastLoginDate SMALLDATETIME,
		VerifyResult TINYINT,
		VerifyMan SMALLINT
	)
	SET @SQL='
		INSERT INTO #T
			(TitleID,paMainID,Name,HasPhoto,LastLoginDate)
		SELECT TOP ' + @recnum + ' ROW_NUMBER() OVER (ORDER BY '+@OrderBy+') AS TitleID,
			a.ID,a.Name,a.HasPhoto,a.LastLoginDate FROM paMain a WITH(NOLOCK)'

	IF LEN(@WHERE) > 0
	BEGIN
		SET @Where = dbo.SafeSql(@Where)
		IF CHARINDEX('b.', @WHERE)>0 
			SET @SQL = @SQL + ' INNER JOIN cvMain b WITH(NOLOCK) ON a.ID = b.PaMainID'
		SET @SQL = @SQL + ' WHERE 1=1 ' + @WHERE
	END

	EXEC(@SQL)
	--UPDATE a SET a.VerifyMan = b.VerifyMan FROM #T a ,bsCvVerify b WITH(NOLOCK) WHERE b.paMainID = a.paMainID
	--AND TitleID > (@Page-1)*20 AND TitleID <= @Page*20
	SELECT COUNT(*) FROM #T WITH(NOLOCK)
	SELECT * FROM #T WITH(NOLOCK) WHERE TitleID > (@Page-1)*20 AND TitleID <= @Page*20
	DROP TABLE #T
END





GO
/****** Object:  StoredProcedure [dbo].[bpPaNotifyByPaMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----------------
--创建日期：2010-9-14
--创建人：lambo
--功能说明：根据个人编号查询单位网站消息
--用于单位用户管理-->网站消息页面
-----------------
CREATE PROCEDURE [dbo].[bpPaNotifyByPaMainIDSelect]
(
	@paMainID INT
)
AS
BEGIN
	SELECT TOP 300 a.*, b.Name, b.dcProvinceId
	FROM paNotify a WITH(NOLOCK)
	INNER JOIN paMain b WITH(NOLOCK) ON a.paMainID = b.ID
	WHERE a.paMainID = @paMainID
	ORDER BY a.ID DESC
END














GO
/****** Object:  StoredProcedure [dbo].[bppaNotifyDelete]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----------------
--创建日期：2010-9-14
--创建人：lambo
--功能说明：根据编号删除一条网站消息
--用于后台个人用户管理网站消息页面
-----------------
CREATE PROCEDURE [dbo].[bppaNotifyDelete]
(
	@ID INT
)
AS
BEGIN TRY
	DELETE FROM paNotify WHERE ID = @ID
END TRY
BEGIN CATCH
	RETURN 0
END CATCH
RETURN 1














GO
/****** Object:  StoredProcedure [dbo].[bppaNotifyInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-----------------
--创建日期：2010-9-14
--创建人：lambo
--功能说明：增加一条网站消息
--用于后台单位用户管理网站消息页面
-----------------
CREATE PROCEDURE [dbo].[bppaNotifyInsert]
(
	@paMainId INT,
	@NotifyType SMALLINT,
	@Message NVARCHAR(300),
	@EndDate VARCHAR(20),
	@ManagerUserID INT
)
AS
BEGIN TRY
	IF @NotifyType=1
		SET @EndDate = NULL
	INSERT INTO paNotify (paMainId,NotifyType,Message,EndDate,ManagerUserID) 
		VALUES(@paMainId,@NotifyType,@Message,@EndDate,@ManagerUserID) 
END TRY
BEGIN CATCH
	RETURN 0
END CATCH
RETURN 1














GO
/****** Object:  StoredProcedure [dbo].[bpPaNotifySelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----------------
--创建日期：2010-9-14
--创建人：lambo
--功能说明：根据个人编号查询单位网站消息
--用于单位用户管理-->网站消息页面
-----------------
CREATE PROCEDURE [dbo].[bpPaNotifySelect]
AS
BEGIN
	SELECT TOP 300 a.*, b.Name, b.dcProvinceId
	FROM paNotify a WITH(NOLOCK)
	INNER JOIN paMain b WITH(NOLOCK) ON a.paMainID = b.ID
	ORDER BY a.ID DESC
END














GO
/****** Object:  StoredProcedure [dbo].[bpPaPhotoByPaMainIdUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--创建人：harry
--2015-9-8
--后台照片审核不通过
--增加审核记录,用于计算审核延误4
CREATE PROCEDURE [dbo].[bpPaPhotoByPaMainIdUpdate]
(
	@CheckMan INT,
    @CheckMessage VARCHAR(100),
    @PaMainID INT
)
AS
SET NOCOUNT ON
BEGIN
	UPDATE MainDB..paPhoto 
	SET Photo = NULL, CheckMan = @CheckMan, CheckMessage = @CheckMessage, CheckDate = GETDATE() 
	WHERE paMainID = @PaMainID

    UPDATE MainDB..paMain 
    SET HasPhoto = 2 
    WHERE ID = @PaMainID
    
      --插入审核延误记录表
    
	INSERT INTO logdb..VerifyDelayLog(verifyType, relationId, submitDate, verifyDate, verifyMan)
	SELECT 4,@PaMainID,(SELECT TOP 1 AddDate FROM MainDB..paPhoto  WHERE paMainID = @PaMainID), GETDATE(), @CheckMan
 
	-- 插入wxmessagesend
	IF @CheckMessage > ''
	BEGIN
		DECLARE @WxFansId INT
		SELECT @WxFansId = Id 
		FROM Wxfans WHERE PamainId=@PamainId AND [status] = 2
		IF ISNULL(@WxFansId,0)>0
		BEGIN
			INSERT WxMessageSend2(Templatetype, WxFansID, PaMainId, AddDate)
			SELECT 8, @WxFansId, @PamainId, GETDATE()
		END
	END
END 

GO
/****** Object:  StoredProcedure [dbo].[bpPaPhotoByVerifySelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--========================================
--pamain.HasPhoto  null未上传，0上传，未审核；1-审核通过；2-审核不通过
--========================================
CREATE PROCEDURE [dbo].[bpPaPhotoByVerifySelect]
(
	@CheckMan SMALLINT,
	@Type TINYINT,	--10:待审核；1：审核通过；0：审核不通过；20-已经审核，包括通过和未通过
	@SubNo TINYINT,	--默认值：0
	@MaxNo TINYINT	--默认值：1
)
AS
BEGIN
	IF @Type = 10
		BEGIN
			IF @MaxNo<1
				SET @MaxNo=1
			IF @SubNo<0 OR @SubNo >= @MaxNo
				SET @SubNo = 0
			SELECT TOP 1000
				b.ID,
                a.paMainID,
                a.PhotoProcessed,
                a.AddDate,
				b.Name
			FROM paPhoto a WITH(NOLOCK) INNER JOIN paMain b WITH(NOLOCK)
			ON a.paMainID = b.ID
			WHERE b.HasPhoto = 0
			AND (a.paMainID % @MaxNo) = @SubNo
			AND a.AddDate < DATEADD(HOUR,-1,GETDATE())
			ORDER BY a.AddDate
		END
	IF @Type = 1
		BEGIN
			SELECT TOP 500
				b.ID,
                a.paMainID,
                a.PhotoProcessed,
                a.AddDate,
				b.Name,
				a.CheckMan,
				a.CheckDate
			FROM paPhoto a WITH(NOLOCK) INNER JOIN paMain b WITH(NOLOCK)
			ON a.paMainID = b.ID
			WHERE b.HasPhoto = 1
			AND CheckMan=@CheckMan
			ORDER BY CheckDate DESC
		END	
	IF @Type = 0
		BEGIN
			SELECT TOP 500
				b.ID,
                a.paMainID,
                a.PhotoProcessed,
                a.AddDate,
				b.Name,
				a.CheckMan,
				a.CheckDate
			FROM paPhoto a WITH(NOLOCK) INNER JOIN paMain b WITH(NOLOCK)
			ON a.paMainID = b.ID
			WHERE b.HasPhoto = 2
			AND CheckMan=@CheckMan
			ORDER BY CheckDate DESC
		END
	IF @Type = 20
		BEGIN
			SELECT TOP 500
				b.ID,
                a.paMainID,
                a.PhotoProcessed,
                a.AddDate,
				b.Name,
				a.CheckMan,
				a.CheckDate
			FROM paPhoto a WITH(NOLOCK) INNER JOIN paMain b WITH(NOLOCK)
			ON a.paMainID = b.ID
			WHERE b.HasPhoto > 0
			AND CheckMan=@CheckMan
			ORDER BY CheckDate DESC
		END	
END














GO
/****** Object:  StoredProcedure [dbo].[bpPaPlaintByIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----------------
--创建日期：2010-9-26
--创建人：lambo
--功能说明：根据编号查询一条个人投诉单位的信息
--用于客户服务模块，个人投诉单位的处理文件
-----------------
CREATE PROCEDURE [dbo].[bpPaPlaintByIDSelect]
	@ID INT
AS
BEGIN
	SELECT a.*,c.Name CompanyName,c.secondID 
	FROM PaPlaint a WITH(NOLOCK)
	LEFT JOIN caMain b WITH(NOLOCK) ON a.caMainID = b.ID
	LEFT JOIN cpMain c WITH(NOLOCK) ON b.cpMainID = c.ID
	WHERE a.ID = @ID 
END
GO
/****** Object:  StoredProcedure [dbo].[bpPaPlaintSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----------------
--创建日期：2010-9-21
--创建人：lambo
--功能说明：根据条件查询个人投诉单位记录
--用于后台客户服务模块，个人投诉单位页面
--修改人：Alen
--添加cpMain 字段名
-----------------
CREATE PROCEDURE [dbo].[bpPaPlaintSelect]
(
	@WHERE VARCHAR(1000)
)
AS
BEGIN
	DECLARE @SQL VARCHAR(2000)
	SET @SQL = 'SELECT TOP 500 d.mobile,d.email paemail,a.*,b.Name caName ,c.consultantID,c.Name cpName,c.dcProvinceID,b.ID caMainID,c.ID cpMainID,c.regDate'
	SET @SQL = @SQL + ' FROM PaPlaint a WITH(NOLOCK INDEX(PK_paPlaint)),caMain b WITH(NOLOCK INDEX(IX_caMain_cpMainID)),cpMain c WITH(NOLOCK),paMain d WITH(NOLOCK) '
	SET @SQL = @SQL + ' WHERE a.caMainID = b.ID AND b.cpMainID = c.ID AND a.paMainID=d.ID '
	IF LEN(@WHERE) > 0
	BEGIN
		SET @Where = dbo.SafeSql(@Where)
		SET @SQL = @SQL + @WHERE
	END
	SET @SQL=@SQL + ' ORDER BY a.AddDate DESC'
	EXEC(@SQL)
END


GO
/****** Object:  StoredProcedure [dbo].[bpPaPlaintUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----------------
--创建日期：2010-9-26
--创建人：lambo
--功能说明：根据编号修改一条个人投诉单位的记录
--用于后台个人投诉单位页面的处理文件
-----------------
CREATE PROCEDURE [dbo].[bpPaPlaintUpdate]
(
	@ID INT,
	@ReplyType INT,
	@ReplyMan INT,
	@ProcessMessage VARCHAR(500)
)
AS
BEGIN TRY
	UPDATE PaPlaint SET ReplyType=@ReplyType,ReplyMan=@ReplyMan,ProcessMessage=@ProcessMessage,ProcessDate=GETDATE() WHERE ID=@ID
	RETURN 1
END TRY
BEGIN CATCH
	RETURN 0
END CATCH














GO
/****** Object:  StoredProcedure [dbo].[bpPerson_BlackDelete]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----------------
--创建日期：2010-9-14
--创建人：lambo
--功能说明：根据编号删除一条个人黑名单信息
--用于个人黑名单页面
-----------------
CREATE PROCEDURE [dbo].[bpPerson_BlackDelete]
(
	@ID INT
)
AS
BEGIN TRY
	DELETE FROM Person_Black WHERE ID=@ID
	RETURN 1
END TRY
BEGIN CATCH
	RETURN 0
END CATCH














GO
/****** Object:  StoredProcedure [dbo].[bpPerson_BlackInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----------------
--创建日期：2010-9-14
--创建人：lambo
--功能说明：插入一条个人黑名单信息
--用于增加个人黑名单页面
-----------------
CREATE PROCEDURE [dbo].[bpPerson_BlackInsert]
(
	@ManagerID INT,
	@Email VARCHAR(50),
	@Reason VARCHAR(500),
	@Mobile VARCHAR(11)
)
AS
SET NOCOUNT ON
--IF LEN(@Email) <7
--	RETURN 0
BEGIN
	IF NOT EXISTS(SELECT 'x' FROM Person_Black WHERE (Email = @Email AND @Email <> '') OR (Mobile = @Mobile AND @Mobile<>''))
	BEGIN
		INSERT INTO Person_Black
		(	
			ManagerID,
			Email,
			Reason,
			Mobile
		)
		VALUES
		(
			@ManagerID,
			@Email,
			@Reason,
			@Mobile		
		)
		RETURN @@IDENTITY
	END
	ELSE
		RETURN 0
END
GO
/****** Object:  StoredProcedure [dbo].[bpPerson_BlackSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-----------------
--创建日期：2010-9-16
--创建人：lambo
--功能说明：根据条件查询个人黑名单记录
--用于个人黑名单页面
-----------------
CREATE PROCEDURE [dbo].[bpPerson_BlackSelect]
(
	@WHERE VARCHAR(1000)
)
AS
BEGIN
	DECLARE @SQL VARCHAR(2000)
	SET @SQL = 'SELECT * FROM Person_Black WITH(NOLOCK) WHERE 1=1 '
	IF LEN(@WHERE)>0
	BEGIN
		SET @Where = dbo.SafeSql(@Where)
		SET @SQL=@SQL + @WHERE
	END
	SET @SQL=@SQL + ' ORDER BY ID DESC'
	EXEC(@SQL)
END














GO
/****** Object:  StoredProcedure [dbo].[bpPictureDelete]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--********************************************
--创建人：Andy
--创建时间：2014-12-29
--用途：删除Picture表一条数据
--********************************************
CREATE PROCEDURE [dbo].[bpPictureDelete]
(	
	@ID INT      
)
AS
BEGIN	
	DELETE Picture WHERE ID=@ID	
	RETURN 1
END
GO
/****** Object:  StoredProcedure [dbo].[bpPictureSave]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--********************************************
--创建人：Andy
--创建时间：2014-12-29
--用途：更新Picture表一条数据
--********************************************
CREATE PROCEDURE [dbo].[bpPictureSave]
(	
	@ID INT,
    @ManagerUserID INT,
    @Title VARCHAR(50),  
    @Attachment VARCHAR(100),  
    @Type INT    
)
AS
BEGIN
	IF @Id > 0
		UPDATE Picture 
		SET Title = @Title, Attachment = @Attachment, Type = @Type, ManagerUserID = @ManagerUserID
		WHERE ID=@ID	
	ELSE
		INSERT INTO Picture(Manageruserid, Title, Attachment,[Type]) 
		VALUES (@ManagerUserID, @Title,@Attachment,@Type)
END

GO
/****** Object:  StoredProcedure [dbo].[bpPictureSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--创建人 Andy
--时间 2014-12-29
--按照条件查询picture表
CREATE PROCEDURE [dbo].[bpPictureSelect]
(
	@ID INT,  
	@ManagerUserID INT,
	@Title VARCHAR(100),
	@Type INT,
	@Where VARCHAR(1000)
)
AS
SET NOCOUNT ON
BEGIN
	SELECT @Where = dbo.SafeSQL(@Where), @Title = dbo.SafeSql(@Title)
	DECLARE @SQL AS VARCHAR(2000)
	
	SET @SQL = 'SELECT Title, ID, Adddate, Manageruserid, [Type], Attachment 
		FROM Picture WITH(nolock)
		WHERE 1 = 1 '
	
	IF @ID > 0
		SET @SQL = @SQL + ' AND ID = ' + LTRIM(STR(@ID))
	ELSE IF @ManagerUserID <> 0
		SET @SQL = @SQL + ' AND ManagerUserID = ' + LTRIM(STR(@ManagerUserID))
	ELSE IF @Type <> 0
		SET @SQL = @SQL + ' AND Type = ' + LTRIM(STR(@type))
	ELSE IF @Title > ''
		SET @SQL = @SQL + ' AND title LIKE ''%' + @Title + '''%'

	--IF @Where > ''
	--	SET @SQL = @SQL + @Where

	SET @SQL = @SQL + ' ORDER BY adddate DESC ' 
	--PRINT(@SQL)
	EXEC(@SQL)
END


GO
/****** Object:  StoredProcedure [dbo].[bpPr_alexByDcProvinceIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.08.25
--创建人：Nick
--说明：
--#####################################################
Create PROCEDURE [dbo].[bpPr_alexByDcProvinceIDSelect]
(
	@DcProvinceID INT
)
AS
BEGIN
	SELECT TOP 1 pr,alex,baidu,google,sogou,outlink,sitepos,yearmonthday 
	FROM pr_alex WITH(NOLOCK) 
	WHERE province_id=@DcProvinceID 
	ORDER BY yearmonthday DESC
END

GO
/****** Object:  StoredProcedure [dbo].[bpPr_AlexByYearMonthByDaySelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.08.27
--创建人：Nick
--说明：根据yearmonthday查询pr_alex
--#####################################################
CREATE PROCEDURE [dbo].[bpPr_AlexByYearMonthByDaySelect]
(
	@Day VARCHAR(10)
)
AS
BEGIN
	DECLARE @SQL VARCHAR(MAX)
	SET @SQL = 'SELECT DISTINCT TOP 3 yearmonthday FROM pr_alex WITH(NOLOCK) '
	IF @Day<>''
	BEGIN
		SET @SQL = @SQL+' WHERE yearmonthday<= '+@Day
	END
	SET @SQL = @SQL + ' ORDER BY yearmonthday DESC '
	EXEC(@SQL)
END

GO
/****** Object:  StoredProcedure [dbo].[bpPr_AlexByYearMonthByProvinceIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.08.27
--创建人：Nick
--说明：根据ProvinceID查询pr_alex
--#####################################################
CREATE PROCEDURE [dbo].[bpPr_AlexByYearMonthByProvinceIDSelect]
(
	@ProvinceID INT,
	@YearMonthDay VARCHAR(20)
)
AS
BEGIN
	SELECT outlink,pr,alex,baidu,google,sogou 
	FROM Pr_Alex WITH(NOLOCK) 
	WHERE Province_id = @ProvinceID
	AND YearmonthDay = @YearMonthDay
END

GO
/****** Object:  StoredProcedure [dbo].[bpPr_AlexSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.08.27
--创建人：Nick
--说明：查询pr_alex
--#####################################################
CREATE PROCEDURE [dbo].[bpPr_AlexSelect]
AS
BEGIN
	SELECT DISTINCT TOP 20 yearmonthday 
	FROM pr_alex with(nolock) 
	ORDER BY yearmonthday DESC
END

GO
/****** Object:  StoredProcedure [dbo].[bpProjectConcernSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----------------
--创建日期：2016-01-28
--创建人：Peter
--功能说明：获取项目关注列表
-----------------
CREATE PROCEDURE [dbo].[bpProjectConcernSelect]
(
	@SqlWhere VARCHAR(500)
)
AS
BEGIN
	DECLARE @SQL AS VARCHAR(1000)
	SET @SqlWhere = dbo.SafeSql(@SqlWhere)
	SET @SQL = 'SELECT *,
	(STUFF((SELECT '','' + name_eng FROM ProjectConcernManager a,ManagerUser b WHERE b.id=a.ManagerUserID AND a.ProjectConcernID=ProjectConcern.id AND a.ManagerType=0 for xml path('''')),1,1,'''')) Planer,
	(STUFF((SELECT '','' + name_eng FROM ProjectConcernManager a,ManagerUser b WHERE b.id=a.ManagerUserID AND a.ProjectConcernID=ProjectConcern.id AND a.ManagerType=1 for xml path('''')),1,1,'''')) Devoloper
    FROM ProjectConcern  
    WHERE 1 = 1'
    
    IF LEN(@SqlWhere) > 0
		SET @SQL = @SQL + @SqlWhere + ' ORDER BY AddDate DESC'
	
	EXEC(@SQL)
END
GO
/****** Object:  StoredProcedure [dbo].[bpPromoterAchievementSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[bpPromoterAchievementSelect]
(
	@Where VARCHAR(1000),
	@Order VARCHAR(100),
	@Page SMALLINT
)
AS
BEGIN
	BEGIN TRY
		SET @WHERE = dbo.SafeSQL(@WHERE)
		SET @ORDER = dbo.SafeSQL(@ORDER)
		DECLARE @SQL AS VARCHAR(2000)
		CREATE TABLE #T(
			TitleID BIGINT,
			ID INT,
			Payment DECIMAL(18,1),
			ExtraPay DECIMAL(18,1),
			Issue BIT,
			Description NVARCHAR(100),
			PlaceName NVARCHAR(50),
			ManagerName NVARCHAR(50),
			PromoterName VARCHAR(10),
			BeginDate SMALLDATETIME,
			CityID VARCHAR(4),
			RefereeID INT,
			AllCount INT,
			PassCount INT,
			SelfCount INT,
			InvalidCount INT
		)
		SET @Where = dbo.SafeSql(@Where)
		SET @Order = dbo.SafeSql(@Order)
		SET @SQL='
			INSERT INTO #T(TitleID,ID,Payment,ExtraPay,Issue,Description,PlaceName,ManagerName,
				PromoterName,BeginDate,CityID,RefereeID)
			SELECT ROW_NUMBER() OVER (ORDER BY ' + @ORDER + ') AS TitleID,
				a.ID,
				a.Payment,
				a.ExtraPay,
				a.Issue,
				a.Description,
				e.PlaceName,
				c.Name,
				d.Name,
				b.BeginDate,
				b.CityID,
				d.RefereeID
			FROM MarketDB..RmProject a WITH(NOLOCK),
				Recruitment b WITH(NOLOCK),
				ManagerUser c WITH(NOLOCK),
				MarketDB..ExternalUser d WITH(NOLOCK),
				RecruitmentPlace e WITH(NOLOCK)
			WHERE a.RecruitmentID=b.ID 
				AND c.ID=a.Addman 
				AND b.RecruitmentPlaceID=e.ID 
				AND a.Promoter=d.ID ' + @WHERE		
		--PRINT @SQL
		EXEC(@SQL)
		IF(@Page < 1)
			SET @Page = 1
		IF NOT EXISTS(SELECT 'x' FROM #t WHERE TitleID > (@Page-1)*20 AND  TitleID <= @Page*20)
			SET @Page = 1

		UPDATE #T SET
		AllCount = (
			SELECT COUNT(*) FROM MarketDB..RmInvitationCode WITH(NOLOCK)
				WHERE photofile IS NOT NULL AND RmProjectID=#T.ID),
		PassCount = (
			SELECT COUNT(*) FROM MarketDB..RmInvitationCode WITH(NOLOCK)
				WHERE Valid=1 AND RmProjectID=#T.ID),
		SelfCount = (
			SELECT COUNT(*) FROM MarketDB..RmInvitationCode WITH(NOLOCK)
				WHERE Valid=1 AND EntryManID IS NULL AND RmProjectID=#T.ID),
		InvalidCount = (
			SELECT COUNT(*) FROM MarketDB..RmInvitationCode WITH(NOLOCK)
				WHERE Valid=10 AND RmProjectID=#T.ID)
		WHERE TitleID > (@Page-1)*20 AND TitleID <= @Page*20
		
		SELECT COUNT(*) FROM #T WITH(NOLOCK)
		SELECT * FROM #T WITH(NOLOCK) WHERE TitleID > (@Page-1)*20 AND  TitleID <= @Page*20
		DROP TABLE #T
	END TRY
	BEGIN CATCH
		DROP TABLE #T
	END CATCH
END








GO
/****** Object:  StoredProcedure [dbo].[bpPtCommentAndInterviewByStatisticsSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
---增加人Harry---
---运营部兼职工资月报--
---增加时间：2015/3/9--
---修改：统计错误
CREATE PROCEDURE [dbo].[bpPtCommentAndInterviewByStatisticsSelect]
(
	@ManagerUserID SMALLINT,
	@YearMonth VARCHAR(6)
)
AS
BEGIN
	CREATE TABLE #T
	(
		YearMonth VARCHAR(6),
		WorkUserID SMALLINT,
		WorkUserName VARCHAR(10),
		paMainID INT,
		GoodComment INT,
		CommonComment INT,
		InvalidComment INT,
		GoodInterview INT,
		CommonInterview INT,
		InvalidInterview INT
	)
	IF LEN(ISNULL(@YearMonth,'')) = 0
	BEGIN
		IF DAY(GETDATE()) > 25
		BEGIN
			INSERT INTO #T(YearMonth,WorkUserID,WorkUserName,paMainID) 
				SELECT CONVERT(VARCHAR(6), DATEADD(MONTH, 1, GETDATE()), 112), a.WorkUserID, b.name, a.PaMainID 
				FROM oadb..opWorkUserPaMain a, oadb..managerUser b, oadb..workuser  c
				WHERE a.WorkUserID=c.Id AND c.ManagerUserID=b.Id
			INSERT INTO #T(YearMonth, WorkUserID, WorkUserName, paMainID) 
				SELECT CONVERT(VARCHAR(6), GETDATE(), 112), a.WorkUserID, b.name, a.PaMainID 
				FROM oadb..opWorkUserPaMain a, oadb..managerUser b, oadb..workuser  c
				WHERE a.WorkUserID=c.Id AND c.ManagerUserID=b.Id
			INSERT INTO #T(YearMonth, WorkUserID, WorkUserName, paMainID) 
				SELECT CONVERT(VARCHAR(6), DATEADD(MONTH, -1, GETDATE()), 112), a.WorkUserID, b.name, a.PaMainID 
				FROM oadb..opWorkUserPaMain a, oadb..managerUser b, oadb..workuser  c
				WHERE a.WorkUserID=c.Id AND c.ManagerUserID=b.Id
		END
		ELSE
		BEGIN
			INSERT INTO #T(YearMonth, WorkUserID, WorkUserName, paMainID) 
				SELECT CONVERT(VARCHAR(6), GETDATE(), 112), a.WorkUserID, b.name, a.PaMainID 
				FROM oadb..opWorkUserPaMain a, oadb..managerUser b, oadb..workuser  c
				WHERE a.WorkUserID=c.Id AND c.ManagerUserID=b.Id
			INSERT INTO #T(YearMonth, WorkUserID, WorkUserName, paMainID) 
				SELECT CONVERT(VARCHAR(6), DATEADD(MONTH, -1, GETDATE()) ,112), a.WorkUserID, b.name, a.PaMainID 
				FROM oadb..opWorkUserPaMain a, oadb..managerUser b, oadb..workuser  c
				WHERE a.WorkUserID=c.Id AND c.ManagerUserID=b.Id
			INSERT INTO #T(YearMonth, WorkUserID, WorkUserName, paMainID) 
				SELECT CONVERT(VARCHAR(6), DATEADD(MONTH, -2, GETDATE()), 112), a.WorkUserID, b.name, a.PaMainID 
				FROM oadb..opWorkUserPaMain a, oadb..managerUser b, oadb..workuser  c
				WHERE a.WorkUserID=c.Id AND c.ManagerUserID=b.Id
		END
	END
	ELSE
	BEGIN
		INSERT INTO #T(YearMonth,WorkUserID, WorkUserName,paMainID) 
			SELECT @YearMonth, a.WorkUserID, b.Name, a.paMainID 
			FROM oadb..opWorkUserPaMain a, oadb..managerUser b, oadb..workuser  c
			WHERE a.WorkUserID=c.Id AND c.ManagerUserID=b.Id
	END
	IF @ManagerUserID > 0
	BEGIN
		DELETE FROM #T WHERE WorkUserID NOT IN(SELECT ID FROM oadb..WorkUser WHERE ManageruserID=@ManagerUserID)
	END
	--时间处理
	DECLARE @startTime VARCHAR(100)
	DECLARE @endTime  VARCHAR(100)
	SET @startTime=CONVERT(varchar(100), DateAdd(month,-1,Convert(datetime,substring(@YearMonth,1,4)+'-'+substring(@YearMonth,5,2)+'-26 00:00:00')), 120)
	SET @endTime=CONVERT(varchar(100), Convert(datetime,substring(@YearMonth,1,4)+'-'+substring(@YearMonth,5,2)+'-25 23:59:59'), 120)
	print @startTime
	Print @endTime
	--优质评论
	UPDATE a SET a.GoodComment=b.cnt FROM #T a,(
		SELECT paMainID, @YearMonth YearMonth, COUNT(1) cnt FROM(
			SELECT ROW_NUMBER() OVER(PARTITION BY a.PaMainID, a.CpMainID ORDER BY a.ADDDATE DESC) i, a.paMainID,a.AddDate, a.CommentType 
			FROM Comments a, oadb..opWorkUserPaMain b, oadb..opCommentCompany c
			WHERE a.paMainID=b.paMainID AND a.cpMainID=c.cpMainID AND c.WorkUserID=b.WorkUserID AND a.CommentType=2 AND (a.addDate BETWEEN @startTime AND @endTime)
		) a
		WHERE i<4
		GROUP BY paMainID
	) b
	WHERE a.YearMonth=b.YearMonth AND a.paMainID=b.paMainID
	--一般评论
	UPDATE a SET a.CommonComment=b.cnt FROM #T a,(
		SELECT paMainID, @YearMonth YearMonth, COUNT(1) cnt FROM(
			SELECT ROW_NUMBER() OVER(PARTITION BY a.PaMainID, a.CpMainID ORDER BY a.ADDDATE DESC) i, a.paMainID, a.AddDate, a.CommentType 
			FROM Comments a, oadb..opWorkUserPaMain b, oadb..opCommentCompany c 			WHERE a.paMainID=b.paMainID AND a.cpMainID=c.cpMainID AND c.WorkUserID=b.WorkUserID AND a.CommentType=1  AND (a.addDate BETWEEN @startTime AND @endTime)
		) a
		WHERE i<4
		GROUP BY paMainID
	) b
	WHERE a.YearMonth=b.YearMonth AND a.paMainID=b.paMainID
	--无效评论
	UPDATE a SET a.InvalidComment=b.cnt FROM #T a,(
		SELECT paMainID, @YearMonth YearMonth, COUNT(1) cnt FROM(
			SELECT ROW_NUMBER() OVER(PARTITION BY a.PaMainID, a.CpMainID ORDER BY a.ADDDATE DESC) i,a.paMainID,a.AddDate,a.CommentType 
			FROM Comments a, oadb..opWorkUserPaMain b, oadb..opCommentCompany c
			WHERE a.paMainID=b.paMainID AND a.cpMainID=c.cpMainID AND c.WorkUserID=b.WorkUserID AND a.CommentType=3 AND (a.addDate BETWEEN @startTime AND @endTime)
		) a
		WHERE i<4
		GROUP BY paMainID
	) b
	WHERE a.YearMonth=b.YearMonth AND a.paMainID=b.paMainID

	--优质面经
	UPDATE a SET a.GoodInterview=b.cnt FROM #T a,(
		SELECT paMainID, @YearMonth YearMonth, COUNT(1) cnt FROM(
			SELECT ROW_NUMBER() OVER(PARTITION BY a.PaMainID, a.CpMainID ORDER BY a.ADDDATE DESC) i,a.paMainID,a.AddDate,a.InterviewType 
			FROM Interview a, oadb..opWorkUserPaMain b, oadb..opCommentCompany c
			WHERE a.paMainID=b.paMainID AND a.cpMainID=c.cpMainID AND c.WorkUserID=b.WorkUserID AND a.InterviewType=2 AND (a.addDate BETWEEN @startTime AND @endTime)
		) a
		WHERE i<4
		GROUP BY paMainID
	) b
	WHERE a.YearMonth=b.YearMonth AND a.paMainID=b.paMainID
	--一般面经
	UPDATE a SET a.CommonInterview=b.cnt FROM #T a,(
		SELECT paMainID, @YearMonth YearMonth, COUNT(1) cnt FROM(
			SELECT ROW_NUMBER() OVER(PARTITION BY a.PaMainID, a.CpMainID ORDER BY a.ADDDATE DESC) i,a.paMainID,a.AddDate,a.InterviewType 
			FROM Interview a, oadb..opWorkUserPaMain b, oadb..opCommentCompany c
			WHERE a.paMainID=b.paMainID AND a.cpMainID=c.cpMainID AND c.WorkUserID=b.WorkUserID AND a.InterviewType=1 AND (a.addDate BETWEEN @startTime AND @endTime)
		) a
		WHERE i<4
		GROUP BY paMainID
	) b
	WHERE a.YearMonth=b.YearMonth AND a.paMainID=b.paMainID
	--无效面经
	UPDATE a SET a.InvalidInterview=b.cnt FROM #T a,(
		SELECT paMainID, @YearMonth YearMonth,COUNT(1) cnt FROM(
			SELECT ROW_NUMBER() OVER(PARTITION BY a.PaMainID, a.CpMainID ORDER BY a.ADDDATE DESC) i,a.paMainID,a.AddDate,a.InterviewType 
			FROM Interview a, oadb..opWorkUserPaMain b, oadb..opCommentCompany c
			WHERE a.paMainID=b.paMainID AND a.cpMainID=c.cpMainID AND c.WorkUserID=b.WorkUserID AND a.InterviewType=3  AND (a.addDate BETWEEN @startTime AND @endTime)
		) a
		WHERE i<4
		GROUP BY paMainID
	) b
	WHERE a.YearMonth=b.YearMonth AND a.paMainID=b.paMainID
	
	DELETE FROM #T WHERE GoodComment IS NULL
		AND CommonComment IS NULL
		AND InvalidComment IS NULL
		AND GoodInterview IS NULL
		AND CommonInterview IS NULL
		AND InvalidInterview IS NULL
	SELECT * FROM #T
	DROP TABLE #T
END

GO
/****** Object:  StoredProcedure [dbo].[bpQuestionByIdSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--根据问题id 获取问题----------------
--增加人Harry ---------------------------
--增加时间：2015-1-28--------------------
CREATE PROCEDURE [dbo].[bpQuestionByIdSelect]
(
	@id INT
)
AS
BEGIN
	SELECT * 
	FROM MainDb..Question WITH(NOLOCK) 
	WHERE Id = @id
END

GO
/****** Object:  StoredProcedure [dbo].[bpQuestionByInvestIdSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--根据问题id 获取问题----------------
--增加人Harry ---------------------------
--增加时间：2015-1-28--------------------
CREATE PROCEDURE [dbo].[bpQuestionByInvestIdSelect]
(
	@InvestId INT
)
AS
BEGIN 
	SELECT a.*, b.Addman 
	FROM MainDb..Question a WITH(NOLOCK), MainDb..Investigation b WITH(NOLOCK) 
	WHERE a.InvestId = b.Id 
	AND a.InvestId = @InvestId 
	ORDER BY a.Power
END

GO
/****** Object:  StoredProcedure [dbo].[bpQuestionDelete]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--根据调查问题id删除问题----------------
--增加人Harry ---------------------------
--增加时间：2015-1-28--------------------
CREATE PROCEDURE [dbo].[bpQuestionDelete]
(
	@id INT
)
AS
BEGIN
	DELETE 
	FROM MainDb..Question 
	WHERE Id = @id
END

GO
/****** Object:  StoredProcedure [dbo].[bpQuestionInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--根据问题id 获取答案----------------
--增加人Harry ---------------------------
--增加时间：2015-1-28--------------------
--修改人：harry修改内容title 长度
CREATE PROCEDURE [dbo].[bpQuestionInsert]
(
	@title NVARCHAR(100), 
	@type SMALLINT, 
	@answernum SMALLINT, 
	@prompt NVARCHAR(50), 
	@power SMALLINT, 
	@investid INT, 
	@options NVARCHAR(1000)
)
AS
BEGIN 
	INSERT INTO MainDb..Question (Title, Type, Answernum, Prompt, Power, InvestId, Options) 
	VALUES (@title, @type, @answernum, @prompt, @power, @investid, @options)
END
 
GO
/****** Object:  StoredProcedure [dbo].[bpQuestionUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--根据问题id 修改问题----------------
--增加人Harry ---------------------------
--增加时间：2015-1-28--------------------
--修改人Harry,修改内容：title长度
CREATE PROCEDURE [dbo].[bpQuestionUpdate]
(
	@title NVARCHAR(100), 
	@type SMALLINT, 
	@answernum SMALLINT, 
	@prompt NVARCHAR(50), 
	@power SMALLINT, 
	@id INT, 
	@options NVARCHAR(1000)
)
AS
BEGIN
	UPDATE MainDb..Question 
	SET Title = @title, Type = @type, Answernum = @answernum, Prompt = @prompt, Power = @power, Options = @options 
	WHERE Id = @id
END
 
GO
/****** Object:  StoredProcedure [dbo].[bpReferer_Count_KeywordsByReferer_Count_IDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.08.27
--创建人：Nick
--说明：根据referer_count_id查询referer_count_keywords
--#####################################################
CREATE PROCEDURE [dbo].[bpReferer_Count_KeywordsByReferer_Count_IDSelect]
(
	@Referer_Count_ID INT
)
AS
BEGIN
	SELECT howmany,keywords 
	FROM referer_count_keywords WITH(NOLOCK) 
	WHERE referer_count_id=@Referer_Count_ID 
	ORDER BY howmany DESC
END

GO
/****** Object:  StoredProcedure [dbo].[bpReferer_CountByCountDateSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.08.25
--创建人：Nick
--说明：根据日期获取referer_count
--#####################################################
Create PROCEDURE [dbo].[bpReferer_CountByCountDateSelect]
(
	@CountDate VARCHAR(10)
)
AS
BEGIN
	SELECT TOP 1 * FROM Referer_Count WITH(NOLOCK) WHERE CountDate=@CountDate
END

GO
/****** Object:  StoredProcedure [dbo].[bpReferer_CountByDaySelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.08.25
--创建人：Nick
--说明：来源分析统计（日报）
--#####################################################
CREATE PROCEDURE [dbo].[bpReferer_CountByDaySelect]
(
	@Site VARCHAR(10),
	@Day VARCHAR(8)
)
AS
BEGIN
	DECLARE @WHERE VARCHAR(MAX)
	SET @WHERE  = 'SUM(CASE Province_Id WHEN 0 Then HowMany Else 0 END) [51RC]'
	DECLARE @CateID INT,@Province VARCHAR(20)
	DECLARE c_CateGoryID CURSOR FAST_FORWARD FOR
	--读取
	SELECT CASE @Site WHEN '1' THEN 100+ID WHEN '2' THEN 200+ID ELSE ID END,province  
	FROM province WITH(NOLOCK) 
	ORDER BY CASE southnorth WHEN 4 THEN 1 ELSE southnorth END DESC,id
	-- 打开游标.
	OPEN c_CateGoryID;
		WHILE 1=1
		BEGIN
		FETCH NEXT FROM c_CateGoryID INTO @CateID,@Province
		IF @Site = '100'
		BEGIN
			SET @WHERE = @WHERE+',SUM(CASE right(Province_Id,2) WHEN '+CONVERT(VARCHAR(20),@CateID)+' Then HowMany Else 0 END) ['+@Province+']'
		END
		ELSE
		BEGIN
			SET @WHERE = @WHERE+',SUM(CASE Province_Id WHEN '+CONVERT(VARCHAR(20),@CateID)+' Then HowMany Else 0 END) ['+@Province+']'
		END
		IF @@fetch_status<> 0 BREAK
	END
	-- 关闭游标
	CLOSE c_CateGoryID;
	-- 释放游标.
	DEALLOCATE c_CateGoryID;

	DECLARE @SQL VARCHAR(MAX)
	SET @SQL = 'SELECT '+@WHERE+',SUM(howmany) cnt,item_Name 
		FROM referer_count a WITH(NOLOCK),referer_item_keywords b WITH(NOLOCK),referer_item c WITH(NOLOCK) 
		WHERE Item_Id=c.ID And countdate='+@Day+' and charindex(b.keywords, a.referer) >0'
	IF @Site = '2'
	BEGIN
		SET @SQL = @SQL+'  AND Province_Id LIKE ''2__''  '
	END
	ELSE IF @Site = '1'
	BEGIN
		SET @SQL = @SQL+'  AND Province_Id LIKE ''1__'' '
	END
	ELSE IF @Site = ''
	BEGIN
		SET @SQL = @SQL+' AND LEN(Province_Id) <= 2 '
	END
	SET @SQL = @SQL + ' GROUP BY item_id,item_Name ORDER BY item_Name'
	EXEC(@SQL)
END

GO
/****** Object:  StoredProcedure [dbo].[bpReferer_CountByHowManySelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.08.27
--创建人：Nick
--说明：根据yearmonthday查询referer_count
--#####################################################
CREATE PROCEDURE [dbo].[bpReferer_CountByHowManySelect]
(
	@CountDate VARCHAR(20),
	@ProvinceID VARCHAR(10),
	@Site VARCHAR(10),
	@KeyWord VARCHAR(100)
)
AS
BEGIN
	DECLARE @SQL VARCHAR(MAX)
	SET @SQL = 'SELECT SUM(howmany) cnt FROM referer_count with(nolock) WHERE '
	IF @Site = '100'
	BEGIN
		SET @SQL = @SQL+ ' province_id like ''%'+RIGHT(@ProvinceID,2)+''' '
	END
	ELSE
	BEGIN
		SET @SQL = @SQL+ ' province_id = '+@ProvinceID
	END
	SET @SQL = @SQL + ' AND countdate = '+@CountDate +' AND referer LIKE ''%'+@KeyWord+'%'''
	PRINT @SQL
	EXEC(@SQL)
END



GO
/****** Object:  StoredProcedure [dbo].[bpReferer_CountBYIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.08.27
--创建人：Nick
--说明：根据ID查询referer_count
--#####################################################
CREATE PROCEDURE [dbo].[bpReferer_CountBYIDSelect]
(
	@ID INT
)
AS
BEGIN
	SELECT referer 
	FROM referer_count WITH(NOLOCK) 
	WHERE ID = @ID
END

GO
/****** Object:  StoredProcedure [dbo].[bpReferer_CountByProvinceIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.08.27
--创建人：Nick
--说明：根据province_id查询referer_count
--#####################################################
CREATE PROCEDURE [dbo].[bpReferer_CountByProvinceIDSelect]
(
	@ProvinceID VARCHAR(10),
	@CountDate VARCHAR(20)
)
AS
BEGIN
	DECLARE @SQL VARCHAR(MAX)
	SET @SQL = 'SELECT howmany,referer,id FROM referer_count WITH(NOLOCK) WHERE '
	IF LEN(@ProvinceID) = 3 AND LEFT(@ProvinceID,1)='3'
	BEGIN
		SET @SQL = @SQL + ' province_id like ''%'+RIGHT(@ProvinceID,2)+'''  '
	END
	ELSE
	BEGIN
		SET @SQL = @SQL + ' province_id = '+@ProvinceID
	END
	SET @SQL = @SQL + ' and countdate= '+ @CountDate +' ORDER BY howmany DESC'
	EXEC(@SQL)
END

GO
/****** Object:  StoredProcedure [dbo].[bpReferer_CountByRefererSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.08.25
--创建人：Nick
--说明：根据countdate 查询referer_count
--#####################################################
Create PROCEDURE [dbo].[bpReferer_CountByRefererSelect]
(
	@BeginDate VARCHAR(10),
	@EndDate VARCHAR(10),
	@KewWords VARCHAR(500),
	@ProvinceID INT
)
AS
BEGIN
	SELECT SUM(howmany) cnt 
	FROM referer_count WITH(NOLOCK) 
	WHERE province_id = @ProvinceID 
	AND countdate>=@BeginDate 
	AND countdate<@EndDate 
	AND referer like '%'+@KewWords+'%'
END

GO
/****** Object:  StoredProcedure [dbo].[bpReferer_Item_KeywordsByIDDelete]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.08.25
--创建人：Nick
--说明：根据ID虚构关键词
--#####################################################
CREATE PROCEDURE [dbo].[bpReferer_Item_KeywordsByIDDelete]
(
    @ID INT
)
AS
BEGIN
    DELETE FROM referer_item_keywords    WHERE ID = @ID
END
GO
/****** Object:  StoredProcedure [dbo].[bpReferer_Item_KeywordsByIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.08.25
--创建人：Nick
--说明：根据ID查询关键词
--#####################################################
CREATE PROCEDURE [dbo].[bpReferer_Item_KeywordsByIDSelect]
(
	@ID INT
)
AS
BEGIN
	SELECT * FROM referer_item_keywords WITH(NOLOCK) WHERE ID = @ID
END

GO
/****** Object:  StoredProcedure [dbo].[bpReferer_Item_KeywordsByIDUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.08.25
--创建人：Nick
--说明：根据ID修改关键词
--#####################################################
CREATE PROCEDURE [dbo].[bpReferer_Item_KeywordsByIDUpdate]
(
	@ID INT,
	@KeyWords VARCHAR(150)
)
AS
BEGIN
	update referer_item_keywords 
	SET keywords=@KeyWords
	WHERE ID = @ID
END

GO
/****** Object:  StoredProcedure [dbo].[bpReferer_Item_keywordsByItem_IDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.08.25
--创建人：Nick
--说明：根据Item_ID 查询referer_item_keywords
--#####################################################
Create PROCEDURE [dbo].[bpReferer_Item_keywordsByItem_IDSelect]
(
	@Item_ID INT
)
AS
BEGIN
	SELECT id,keywords FROM referer_item_keywords WITH(NOLOCK) WHERE item_id = @Item_ID ORDER BY ID
END

GO
/****** Object:  StoredProcedure [dbo].[bpReferer_Item_KeywordsInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.08.25
--创建人：Nick
--说明：新增关键词
--#####################################################
CREATE PROCEDURE [dbo].[bpReferer_Item_KeywordsInsert]
(
	@Item_ID INT,
	@KeyWords VARCHAR(200)
)
AS
BEGIN
	INSERT INTO referer_item_keywords (item_id,keywords) VALUES (@Item_ID,@KeyWords)
END

GO
/****** Object:  StoredProcedure [dbo].[bpReferer_ItemByIDDelete]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.08.25
--创建人：Nick
--说明：删除关键词
--#####################################################
CREATE PROCEDURE [dbo].[bpReferer_ItemByIDDelete]
(
	@ID INT
)
AS
BEGIN
	DELETE FROM referer_item_keywords WHERE item_id = @ID
	DELETE FROM referer_item WHERE id = @ID
END

GO
/****** Object:  StoredProcedure [dbo].[bpReferer_ItemByIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.08.25
--创建人：Nick
--说明：根据ID查询关键词
--#####################################################
CREATE PROCEDURE [dbo].[bpReferer_ItemByIDSelect]
(
	@ID INT
)
AS
BEGIN
	SELECT * FROM  referer_item WITH(NOLOCK) WHERE id = @ID
END

GO
/****** Object:  StoredProcedure [dbo].[bpReferer_ItemByIDUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.08.25
--创建人：Nick
--说明：修改ID查询关键词
--#####################################################
CREATE PROCEDURE [dbo].[bpReferer_ItemByIDUpdate]
(
	@ID INT,
	@Item_Name VARCHAR(100)
)
AS
BEGIN
	Update referer_item 
	SET item_name = @Item_Name 
	WHERE id = @ID
END

GO
/****** Object:  StoredProcedure [dbo].[bpReferer_itemInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.08.25
--创建人：Nick
--说明：新增关键词
--#####################################################
CREATE PROCEDURE [dbo].[bpReferer_itemInsert]
(
	@Item_Name VARCHAR(200)
)
AS
BEGIN
	INSERT INTO referer_item (item_name) VALUES (@Item_Name)
END

GO
/****** Object:  StoredProcedure [dbo].[bpReferer_ItemSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.08.25
--创建人：Nick
--说明：referer_item 查询
--#####################################################
Create PROCEDURE [dbo].[bpReferer_ItemSelect]
AS
BEGIN
	SELECT id,item_name FROM referer_item WITH(NOLOCK) ORDER BY item_name
END

GO
/****** Object:  StoredProcedure [dbo].[bpReferer_YearmonthByDcProvinceSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.08.25
--创建人：Nick
--说明：来源分析（月报）
--#####################################################
Create PROCEDURE [dbo].[bpReferer_YearmonthByDcProvinceSelect]
(
	@Site VARCHAR(10),
	@YearMonth VARCHAR(6)
)
AS
BEGIN
	IF @Site = ''
	BEGIN
		SELECT SUM(howmany) howmany 
		FROM referer_yearmonth WITH(NOLOCK) 
		WHERE yearmonth=@YearMonth
		AND (LEN(Province_id)=2 OR Province_id=0)
	END
	ELSE IF @Site = '2'
	BEGIN
		SELECT SUM(howmany) howmany
		FROM referer_yearmonth WITH(NOLOCK) 
		WHERE Province_id LIKE '2__' 
		AND yearmonth=@YearMonth
	END
	ELSE IF @Site = '1'
	BEGIN
		SELECT SUM(howmany) howmany 
		FROM referer_yearmonth WITH(NOLOCK) 
		WHERE Province_id LIKE '1__' 
		AND yearmonth=@YearMonth
	END
	ELSE
	BEGIN
		SELECT SUM(howmany) howmany 
		FROM referer_yearmonth WITH(NOLOCK) 
		WHERE yearmonth=@YearMonth
	END
END

GO
/****** Object:  StoredProcedure [dbo].[bpReferer_YearmonthByYearMonthDelete]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.08.25
--创建人：Nick
--说明：删除referer_yearmonth
--#####################################################
Create PROCEDURE [dbo].[bpReferer_YearmonthByYearMonthDelete]
(
	@YearMonth VARCHAR(10)
)
AS
BEGIN
	DELETE FROM Referer_Yearmonth WHERE Yearmonth=@YearMonth
END

GO
/****** Object:  StoredProcedure [dbo].[bpReferer_YearmonthByYearMonthOneSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.08.25
--创建人：Nick
--说明：referer_yearmonth 查询
--#####################################################
Create PROCEDURE [dbo].[bpReferer_YearmonthByYearMonthOneSelect]
(
	@YearMonth VARCHAR(10)
)
AS
BEGIN
	SELECT TOP 1 * FROM Referer_Yearmonth WITH(NOLOCK) WHERE yearmonth = @YearMonth
END

GO
/****** Object:  StoredProcedure [dbo].[bpReferer_YearmonthByYearMonthSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.08.25
--创建人：Nick
--说明：来源分析统计（月报）
--修改Haarry:统计错误2015-12-29
--#####################################################
CREATE PROCEDURE [dbo].[bpReferer_YearmonthByYearMonthSelect]
(
	@Site VARCHAR(10),
	@YearMonth VARCHAR(6)
)
AS
BEGIN
	DECLARE @WHERE VARCHAR(MAX)
	SET @WHERE  = 'SUM(CASE Province_Id WHEN 0 Then HowMany Else 0 END) [51RC]'
	DECLARE @CateID INT,@Province VARCHAR(20)
	DECLARE c_CateGoryID CURSOR FAST_FORWARD FOR
	--读取
	SELECT CASE @Site WHEN '1' THEN 100+ID WHEN '2' THEN 200+ID ELSE ID END,province  
	FROM province WITH(NOLOCK) 
	ORDER BY CASE southnorth WHEN 4 THEN 1 ELSE southnorth END DESC,id
	-- 打开游标.
	OPEN c_CateGoryID;
		WHILE 1=1
		BEGIN
		FETCH NEXT FROM c_CateGoryID INTO @CateID,@Province
		IF @Site=100
		BEGIN
			SET @WHERE = @WHERE+',SUM(CASE right(Province_Id,2) WHEN '+CONVERT(VARCHAR(20),@CateID)+' Then HowMany Else 0 END) ['+@Province+']'
		END
		ELSE
		BEGIN
			SET @WHERE = @WHERE+',SUM(CASE Province_Id WHEN '+CONVERT(VARCHAR(20),@CateID)+' Then HowMany Else 0 END) ['+@Province+']'
		END
 		IF @@fetch_status<> 0 BREAK
	END
	-- 关闭游标
	CLOSE c_CateGoryID;
	-- 释放游标.
	DEALLOCATE c_CateGoryID;

	DECLARE @SQL VARCHAR(MAX)
	SET @SQL = 'SELECT '+@WHERE+',SUM(howmany) cnt,item_Name FROM referer_yearmonth WITH(NOLOCK) WHERE YearMonth='+@YearMonth
	IF @Site = '2'
	BEGIN
		SET @SQL = @SQL+'  AND Province_Id LIKE ''2__''  '
	END
	ELSE IF @Site = '1'
	BEGIN
		SET @SQL = @SQL+'  AND Province_Id LIKE ''1__'' '
	END
	ELSE IF @Site = ''
	BEGIN
		SET @SQL = @SQL+' AND LEN(Province_Id) <= 2 '
	END
	SET @SQL = @SQL+' GROUP BY item_Name ORDER BY item_Name'
	PRINT @SQL
	EXEC(@SQL)
END 

GO
/****** Object:  StoredProcedure [dbo].[bpReferer_YearMonthInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.08.25
--创建人：Nick
--说明：插入referer_yearmonth
--#####################################################
Create PROCEDURE [dbo].[bpReferer_YearMonthInsert]
(
	@YearMonth VARCHAR(10),
	@ItemName VARCHAR(50),
	@ProvinceID INT,
	@HowMany INT
)
AS
BEGIN
	INSERT referer_yearmonth (yearmonth,item_name,province_id,howmany) 
	VALUES (@YearMonth,@ItemName,@ProvinceID,@HowMany)
END

GO
/****** Object:  StoredProcedure [dbo].[bpRefererByProvinceIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.08.27
--创建人：Nick
--说明：根据province_id查询referer
--#####################################################
CREATE PROCEDURE [dbo].[bpRefererByProvinceIDSelect]
(
	@ProvinceID VARCHAR(10),
	@Search_text VARCHAR(50),
	@Search_action  INT,
	@search_item INT
)
AS
BEGIN
	DECLARE @SQL VARCHAR(MAX)
	SET @SQL = 'SELECT referer,logindate,ip,keywords,versionid FROM referer WITH(NOLOCK) WHERE '
	IF LEN(@ProvinceID) = 3 AND LEFT(@ProvinceID,1)='3'
	BEGIN
		SET @SQL = @SQL + ' province_id like ''%'+RIGHT(@ProvinceID,2)+'''  '
	END
	ELSE
	BEGIN
		SET @SQL = @SQL + ' province_id = '+@ProvinceID
	END
	IF @search_item = 1 AND @Search_text<>''
	BEGIN
		IF @Search_action = 1
		BEGIN
			SET @SQL = @SQL + ' AND referer like '''+@Search_text+'%''  '
		END
		IF @Search_action = 2
		BEGIN
			SET @SQL = @SQL + ' AND referer like ''%'+@Search_text+'%''  '
		END
	END
	IF @search_item = 2 AND @Search_text<>''
	BEGIN
		IF @Search_action = 1
		BEGIN
			SET @SQL = @SQL + ' AND IP like '''+@Search_text+'%''  '
		END
		IF @Search_action = 2
		BEGIN
			SET @SQL = @SQL + ' AND IP like ''%'+@Search_text+'%''  '
		END
	END
	SET @SQL  = @SQL + ' ORDER BY logindate DESC'
	EXEC(@SQL)
END

GO
/****** Object:  StoredProcedure [dbo].[bpResume_AnalysisSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.09.06
--创建人：Nick
--说明：简历分析报告
--#####################################################
CREATE PROCEDURE [dbo].[bpResume_AnalysisSelect]
(
    @Type INT
)
AS
BEGIN
    SELECT resume_num,adddate FROM resume_analysis WITH(NOLOCK)
    IF @Type = 1    
    BEGIN
        SELECT id,description,resume_num FROM resume_analysis_1 WITH(NOLOCK) ORDER BY resume_num DESC
    END
    ELSE IF @Type = 2    
    BEGIN
        SELECT id,edulevel,resume_num FROM resume_analysis_2 WITH(NOLOCK) ORDER BY id
    END
    ELSE IF @Type = 3    
    BEGIN
        SELECT id,agelevel,resume_num FROM resume_analysis_3 WITH(NOLOCK) ORDER BY id
    END
    ELSE IF @Type = 4    
    BEGIN
        SELECT experience,sum(resume_num) resume_num 
        FROM resume_analysis_4 WITH(NOLOCK) 
        GROUP BY experience 
        ORDER BY MIN(id)
    END
    ELSE IF @Type = 5    
    BEGIN
        SELECT id,sex,resume_num FROM resume_analysis_5 WITH(NOLOCK) ORDER BY id
    END
    ELSE IF @Type = 6    
    BEGIN
        SELECT id,description,resume_num FROM resume_analysis_6 WITH(NOLOCK) ORDER BY id
    END
    ELSE IF @Type = 7    
    BEGIN
        SELECT id,salary,resume_num FROM resume_analysis_7 WITH(NOLOCK) ORDER BY id
    END
    ELSE IF @Type = 8    
    BEGIN
        SELECT id,salary,resume_num FROM resume_analysis_8 WITH(NOLOCK) ORDER BY id
    END
END
GO
/****** Object:  StoredProcedure [dbo].[bpResume_xinxiDelete]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-----------------
--创建日期：2010-9-14
--创建人：lambo
--功能说明：根据编号删除一条记录
--用于后台临时简历库查询页面
-----------------
CREATE PROCEDURE [dbo].[bpResume_xinxiDelete]
(
	@ID INT
)
AS
INSERT INTO procLog select 'bpResume_xinxiDelete', @id, getdate()
BEGIN TRY
	DELETE FROM Resume_xinxi WHERE ID = @ID
	UPDATE logdb..resume_xinxi_log SET Password = '------' WHERE Id = @Id
	RETURN 1
END TRY
BEGIN CATCH
	RETURN 0
END CATCH














GO
/****** Object:  StoredProcedure [dbo].[bpResume_xinxiSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----------------
--创建日期：2010-9-16
--创建人：lambo
--功能说明：根据条件查询简历库的数据
--用于临时简历库查询页面
-----------------
CREATE PROCEDURE [dbo].[bpResume_xinxiSelect]
(
	@count INT,
	@WHERE VARCHAR(1000)
)
AS
BEGIN
	DECLARE @SQL AS VARCHAR(2000)
	SET @SQL='SELECT TOP '+LTRIM(str(@count))+' * FROM Resume_xinxi with(nolock) WHERE 1=1 '
	IF LEN(@WHERE)>0
	BEGIN
		SET @Where = dbo.SafeSql(@Where)
		SET @SQL = @SQL + @WHERE
	END
	EXEC(@SQL)
END



GO
/****** Object:  StoredProcedure [dbo].[bpResumeInformAllSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----------------
--创建日期：2010-9-16
--创建人：lambo
--功能说明：查询所有的个人用户分类通知
--用于后台个人用户分类通知
-----------------
CREATE PROCEDURE [dbo].[bpResumeInformAllSelect]
AS
BEGIN
	SELECT * FROM ResumeInform WITH(NOLOCK) ORDER BY AddDate DESC
END



GO
/****** Object:  StoredProcedure [dbo].[bpResumeInformByStatusUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----------------
--创建日期：2010-9-16
--创建人：lambo
--功能说明：修改个人用户分类通知的状态
--用于个人用户分类通知页面
-----------------
CREATE PROCEDURE [dbo].[bpResumeInformByStatusUpdate]
	@ID INT
AS
BEGIN TRY
	UPDATE ResumeInform SET Status=Status-1 WHERE ID=@ID
	RETURN 1
END TRY
BEGIN CATCH
	RETURN 0
END CATCH














GO
/****** Object:  StoredProcedure [dbo].[bpResumeInformDelete]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----------------
--创建日期：2010-9-16
--创建人：lambo
--功能说明：删除一条个人分类通知
--用于个人用户管理个人用户分类通知
-----------------
CREATE PROCEDURE [dbo].[bpResumeInformDelete]
	@ID INT
AS
BEGIN TRY
	DELETE FROM ResumeInform WHERE ID=@ID
END TRY
BEGIN CATCH
	GOTO ERR
END CATCH
RETURN 1
ERR:
BEGIN
	RETURN 0
END 














GO
/****** Object:  StoredProcedure [dbo].[bpResumeInformSave]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----------------
--创建日期：2010-9-16
--创建人：lambo
--功能说明：增加或修改个人用户分类通知，如果@ID>0则是修改，否则是增加
--用于后台个人用户管理，增加或修改单位分类通知
-----------------
CREATE PROCEDURE [dbo].[bpResumeInformSave]
(
	@ID INT,
    @Title VARCHAR(50),
	@Content VARCHAR(500),
	@Type INT,
	@Link VARCHAR(100),
	@Province VARCHAR(100),
	@EndDate VARCHAR(20)
)
AS
BEGIN TRAN
	Declare @MaxId AS INT
	BEGIN TRY
		IF @ID>0
			BEGIN
				UPDATE ResumeInform SET
					Title = @Title,
					Content = @Content,
					Type = @Type,
					AddDate = GETDATE(),
					Link = @Link,
					Province = @Province,
					EndDate = @EndDate
				WHERE ID=@ID
				SET @MaxID = @ID
			End
		ELSE
			BEGIN
				INSERT INTO ResumeInform
					(
						Title,Content,Type,
						Province,EndDate,Link
					)
				VALUES
					(
						@Title,@Content,@Type,
						@Province,@EndDate,@Link
					)
				SET @MaxID = @@IDENTITY
		END
	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH
COMMIT TRAN
RETURN @MaxID
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END














GO
/****** Object:  StoredProcedure [dbo].[bpResumeInformSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----------------
--创建日期：2010-9-16
--创建人：lambo
--功能说明：根据编号查询一条单位分类通知
--用于后台个人用户管理单位分类通知
-----------------
CREATE PROCEDURE [dbo].[bpResumeInformSelect]
(
    @ID INT
)
AS
BEGIN
    SELECT * FROM ResumeInform WHERE ID = @ID
END














GO
/****** Object:  StoredProcedure [dbo].[bprmInvitationCodeByCvMainIDUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.12.26
--创建人：Nick
--说明：根据CvMainID查询rmInvitationCode
--#####################################################
CREATE PROCEDURE [dbo].[bprmInvitationCodeByCvMainIDUpdate]
(
	@CvMainID INT
)
AS
BEGIN
	DECLARE @ID INT
	SELECT TOP 1 @ID = a.ID 
	FROM marketdb..rmInvitationCode a WITH(NOLOCK),cvMain b WITH(NOLOCK) 
	WHERE a.paMainID = b.paMainID 
	AND b.id=@CvMainID 
	AND (cvlevel LIKE '111111%' OR cvleveleng LIKE '111111%' OR cvlevel LIKE '111101%' OR cvleveleng LIKE '111101%') 
	AND a.valid IS NULL  
	ORDER BY a.AddDate DESC
	
	IF @ID IS NOT NULL
	BEGIN
		UPDATE marketdb..rmInvitationCode SET Valid=0,EntryManID=NULL,EntryDate=Null WHERE ID=@ID
	END
END 

GO
/****** Object:  StoredProcedure [dbo].[bpRole_DataSourceByRoleIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[bpRole_DataSourceByRoleIDSelect]
(
	@RoleID AS INT
)
AS
BEGIN
	SELECT DataSourceID, Privi
	FROM Role_DataSource WITH(NOLOCK)
	WHERE RoleID=@RoleID
	ORDER BY DataSourceID
END














GO
/****** Object:  StoredProcedure [dbo].[bpSearchKeywordsByIDDelete]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.08.27
--创建人：Nick
--说明：根据ID 删除searchkeywords
--#####################################################
CREATE PROCEDURE [dbo].[bpSearchKeywordsByIDDelete]
(
	@ID INT
)
AS
BEGIN
	DELETE FROM searchkeywords WHERE ID = @ID
END

GO
/****** Object:  StoredProcedure [dbo].[bpSearchKeywordsByIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.08.27
--创建人：Nick
--说明：根据ID 查询searchkeywords
--#####################################################
CREATE PROCEDURE [dbo].[bpSearchKeywordsByIDSelect]
(
	@ID INT
)
AS
BEGIN
	SELECT keywords,power,province_id,version_id,competitionPrice 
	FROM searchkeywords WITH(NOLOCK) 
	WHERE ID = @ID
END

GO
/****** Object:  StoredProcedure [dbo].[bpSearchKeywordsByIDUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.08.27
--创建人：Nick
--说明：修改searchkeywords
--#####################################################
CREATE PROCEDURE [dbo].[bpSearchKeywordsByIDUpdate]
(
	@ID INT,
	@Type VARCHAR(50)
)
AS
BEGIN
	DECLARE @Competition DATETIME,@R INT,@Competition_sogou DATETIME,@Competition_soso DATETIME
	SELECT @Competition = Competition,@Competition_sogou = Competition_sogou,@Competition_soso = Competition_soso 
	FROM SearchKeyWords WITH(NOLOCK) WHERE ID = @ID

	IF  @Type = 'baidu'
	BEGIN
		IF @Competition IS NULL
		BEGIN
			UPDATE searchkeywords SET competition=getdate() WHERE id = @ID
			SET @R = 1
		END
		ELSE
		BEGIN
			UPDATE searchkeywords SET competition=null,competitionPrice=null WHERE id = @ID
			SET @R = 0
		END
	END
	IF  @Type = 'sogou'
	BEGIN
		IF @Competition_sogou IS NULL
		BEGIN
			UPDATE searchkeywords SET competition_sogou=getdate() WHERE id = @ID
			SET @R = 1
		END
		ELSE
		BEGIN
			UPDATE searchkeywords SET competition_sogou=null,competitionPrice_sogou=null WHERE id = @ID
			SET @R = 0
		END
	END
	IF  @Type = 'soso'
	BEGIN
		IF @Competition_soso IS NULL
		BEGIN
			UPDATE searchkeywords SET Competition_soso=getdate() WHERE id = @ID
			SET @R = 1
		END
		ELSE
		BEGIN
			UPDATE searchkeywords SET Competition_soso=null,competitionPrice_soso=null WHERE id = @ID
			SET @R = 0
		END
	END
	RETURN @R
END

GO
/****** Object:  StoredProcedure [dbo].[bpSearchKeyWordsByProvinceIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.08.27
--创建人：Nick
--说明：根据ProvinceID查询searchkeywords
--#####################################################
CREATE PROCEDURE [dbo].[bpSearchKeyWordsByProvinceIDSelect]
(
	@ProvinceID INT,
	@Witch INT,
	@JingJia INT,
	@OrderBy INT
)
AS
BEGIN
	DECLARE @SQL VARCHAR(MAX)
	IF @ProvinceID = 0
	BEGIN
		SET @SQL = 'SELECT searchkeywords.id,searchkeywords.keywords,searchkeywords.power,searchkeywords.province_id,
			searchkeywords.competition,searchkeywords.competition_sogou,searchkeywords.competition_soso,searchkeywords.tunedate,
			''伍亿人才招聘网'' versionname,''www.51rc.com'' versiondomain,searchkeywords.competitionPrice,
			searchkeywords.competitionPrice_soso,searchkeywords.competitionPrice_sogou  
			FROM searchkeywords WITH(NOLOCK) 
			WHERE searchkeywords.province_id = '+CONVERT(VARCHAR(10),@ProvinceID) +
			' ORDER BY searchkeywords.power DESC'
	END
	ELSE IF @ProvinceID = 90
	BEGIN
		SET @SQL = 'SELECT searchkeywords.id,searchkeywords.keywords,searchkeywords.power,searchkeywords.province_id,searchkeywords.competition,
			searchkeywords.competition_sogou,searchkeywords.competition_soso,searchkeywords.tunedate,''伍亿猎头'' versionname,
			''hunter.51rc.com'' versiondomain,searchkeywords.competitionPrice,searchkeywords.competitionPrice_soso,
			searchkeywords.competitionPrice_sogou  
			FROM searchkeywords WITH(NOLOCK) WHERE searchkeywords.province_id= '+CONVERT(VARCHAR(10),@ProvinceID) +
			' ORDER BY searchkeywords.power DESC'
	END
	ELSE 
	BEGIN
		SET @SQL = 'SELECT searchkeywords.id,searchkeywords.keywords,searchkeywords.power,searchkeywords.province_id,searchkeywords.competition,
			searchkeywords.competition_sogou,searchkeywords.competition_soso,searchkeywords.tunedate,version.versionname,version.versiondomain,
			searchkeywords.competitionPrice,searchkeywords.competitionPrice_soso,searchkeywords.competitionPrice_sogou 
			FROM searchkeywords WITH(NOLOCK),version WITH(NOLOCK) 
			WHERE searchkeywords.version_id=version.id 
			AND searchkeywords.province_id = '+CONVERT(VARCHAR(10),@ProvinceID) 
		IF @Witch = 1
		BEGIN
			SET @SQL = @SQL +' AND searchkeywords.version_id<100'
		END
		IF @Witch = 2
		BEGIN
			SET @SQL = @SQL +' AND searchkeywords.version_id>100'
		END
		IF @JingJia = 1
		BEGIN
			SET @SQL = @SQL +' AND (
				SELECT TOP 1 power 
				FROM searchkeywordspower WITH(NOLOCK) 
				WHERE searchkeywords_id=searchkeywords.id 
				AND engine LIKE ''baidu'' 
				ORDER BY yearmonthday DESC)>6 
				AND searchkeywords.competition IS NULL'
		END
		ELSE IF @JingJia = 2
		BEGIN
			SET @SQL = @SQL +' AND (
				SELECT TOP 1 power 
				FROM searchkeywordspower WITH(NOLOCK) 
				WHERE searchkeywords_id=searchkeywords.id 
				AND engine LIKE ''baidu'' 
				ORDER BY yearmonthday DESC)<=6 
				AND searchkeywords.competition IS NOT NULL'
		END
		ELSE IF @JingJia = 3
		BEGIN
			SET @SQL = @SQL +' AND (
				SELECT TOP 1 power 
				FROM searchkeywordspower WITH(NOLOCK) 
				WHERE searchkeywords_id=searchkeywords.id 
				AND engine LIKE ''sogou'' 
				ORDER BY yearmonthday DESC)>6 
				AND searchkeywords.competition IS NULL'
		END
		ELSE IF @JingJia = 4
		BEGIN
			SET @SQL = @SQL +' AND (
				SELECT TOP 1 power 
				FROM searchkeywordspower WITH(NOLOCK) 
				WHERE searchkeywords_id=searchkeywords.id 
				AND engine LIKE ''sogou'' 
				ORDER BY yearmonthday DESC)<=6 
				AND searchkeywords.competition IS NOT NULL'
		END

		ELSE IF @JingJia = 5
		BEGIN
			SET @SQL = @SQL +' AND (
				SELECT TOP 1 power 
				FROM searchkeywordspower WITH(NOLOCK) 
				WHERE searchkeywords_id=searchkeywords.id 
				AND engine LIKE ''soso'' 
				ORDER BY yearmonthday DESC)>6 
				AND searchkeywords.competition IS NULL'
		END
		ELSE IF @JingJia = 6
		BEGIN
			SET @SQL = @SQL +' AND (
				SELECT TOP 1 power 
				FROM searchkeywordspower WITH(NOLOCK) 
				WHERE searchkeywords_id=searchkeywords.id 
				AND engine LIKE ''soso'' 
				ORDER BY yearmonthday DESC)<=6 
				AND searchkeywords.competition IS NOT NULL'
		END

		IF @OrderBy =2
		BEGIN
			SET @SQL = @SQL+' ORDER BY version.id'
		END
		ELSE IF @OrderBy = 1
		BEGIN
			SET @SQL = @SQL+' ORDER BY searchkeywords.power DESC'
		END
		ELSE IF @OrderBy = 3
		BEGIN
			SET @SQL = @SQL+' ORDER BY searchkeywords.competition DESC'
		END
		ELSE 
		BEGIN
			SET @SQL = @SQL+' ORDER BY searchkeywords.power DESC'
		END
	END
	EXEC(@SQL)
END

GO
/****** Object:  StoredProcedure [dbo].[bpSearchKeywordsByRankSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--修改harry2017-2-6
--修改:增加m站排名统计
CREATE PROCEDURE [dbo].[bpSearchKeywordsByRankSelect]
(
	@ProvinceID INT,
	@Site INT,	--0 all, 1 Main SIte, 2 Second Site 3 M站 harry 2017-2-5
	@Sort INT,	--
	@Date DATETIME
)
AS
BEGIN
	DECLARE @t AS TABLE(
		ID INT,
		Keywords VARCHAR(100),
		Power INT,
		Province_Id INT,
		VersionName VARCHAR(20),
		VersionDomain VARCHAR(50),
		Version_Id INT,
		Competition DATETIME,
		Tunedate DATETIME,
		FROMBaidu INT,
		FROM360 INT,
		FROMSogou INT,
		BaiduRank1 INT,
		BaiduRank2 INT,
		BaiduRank3 INT,
		_360Rank1 INT,
		_360Rank2 INT,
		_360Rank3 INT,
		SogouRank1 INT,
		SogouRank2 INT,
		SogouRank3 INT
		)

	DECLARE @u AS TABLE(
		ID INT,
		Url VARCHAR(100)
		)
	IF @Site!=3
	BEGIN
		INSERT @u SELECT 1, 'http://www.baidu.com/'
		INSERT @u SELECT 1, 'http://www.baidu.mobi/'
		INSERT @u SELECT 1, 'http://202.108.22.5/'
		INSERT @u SELECT 2, 'http://so.360.cn/'
		INSERT @u SELECT 2, 'http://360sou.com/'
		INSERT @u SELECT 2, 'http://360so.com/'
		INSERT @u SELECT 2, 'http://www.so.com/'
		INSERT @u SELECT 2, 'http://www.360.cn/'
		INSERT @u SELECT 2, 'http://hao.360.cn/'
		INSERT @u SELECT 2, 'http://www.hao360.cn/'
		INSERT @u SELECT 3, 'http://www.sogou.com/'
	END
	ELSE
	BEGIN
		INSERT @u SELECT 1, 'http://m.baidu.com/'
		INSERT @u SELECT 1, 'http://m1.baidu.com/'
		INSERT @u SELECT 1, 'http://m2.baidu.com/'
		INSERT @u SELECT 1, 'http://m3.baidu.com/'
		INSERT @u SELECT 1, 'http://m4.baidu.com/'
		INSERT @u SELECT 1, 'http://m5.baidu.com/'
		INSERT @u SELECT 1, 'http://m6.baidu.com/'
		INSERT @u SELECT 1, 'http://m7.baidu.com/'
		INSERT @u SELECT 1, 'http://m8.baidu.com/'
		INSERT @u SELECT 1, 'http://m9.baidu.com/'
		INSERT @u SELECT 1, 'http://m10.baidu.com/'
		INSERT @u SELECT 1, 'http://m11.baidu.com/'
		INSERT @u SELECT 1, 'http://m12.baidu.com/'
		INSERT @u SELECT 1, 'http://m13.baidu.com/' 
		INSERT @u SELECT 1, 'http://wap.baidu.com/' 
		
		INSERT @u SELECT 2, 'http://m.so.com/' 
		
		INSERT @u SELECT 3, 'http://wisd.sogou.com/'
		INSERT @u SELECT 3, 'http://se.sogou.com/'
		INSERT @u SELECT 3, 'http://m.sogou.com/'
		INSERT @u SELECT 3, 'http://3g.sogou.com/'
		INSERT @u SELECT 3, 'http://wap.sogou.com/'
		INSERT @u SELECT 3, 'http://ot.wap.sogou.com/'
	END	
	DECLARE @p AS TABLE(YearmonthDay VARCHAR(8), SearchKeywords_Id INT, Engine VARCHAR(10), Power INT)
	DECLARE @r AS TABLE(ID INT, Keywords VARCHAR(50), Cnt INT) 
	
	DECLARE @d AS TABLE(ID INT IDENTITY(1, 1), D VARCHAR(8))
	INSERT @d
	SELECT CONVERT(VARCHAR(8), @Date, 112)
	INSERT @d
	SELECT CONVERT(VARCHAR(8), @Date-1, 112)
	INSERT @d
	SELECT CONVERT(VARCHAR(8), @Date-2, 112) 
	--IF @Site!=3
	--BEGIN
	--	INSERT @d
	--	SELECT DISTINCT TOP 3 YearMonthDay FROM SearchKeywordsPower WHERE engine IN('360','baidu','sogou') AND YearMonthDay <= CONVERT(VARCHAR(8), @Date, 112) ORDER BY YearMonthDay DESC
	--END
	--ELSE
	--BEGIN
	--	INSERT @d
	--	SELECT DISTINCT TOP 3 YearMonthDay FROM SearchKeywordsPower WHERE engine IN('m360','mbaidu','msogou') AND YearMonthDay <= CONVERT(VARCHAR(8), @Date, 112) ORDER BY YearMonthDay DESC
	--END
	IF @ProvinceID > 0
		INSERT INTO @t(Id, Keywords, Power, Province_Id, Competition, Tunedate, Versionname, VersionDomain, Version_id )
		SELECT a.Id, a.Keywords, a.Power, a.Province_Id, a.Competition, Tunedate, b.VersionName, b.VersionDomain, a.Version_id 
		FROM SearchKeywords a WITH(NOLOCK),
			Version b WITH(NOLOCK) 
		WHERE a.Version_id = b.id 
		AND a.Province_id = @ProvinceID 
		ORDER BY a.Power desc
	ELSE
		INSERT INTO @t(Id, Keywords, Power, Province_Id, Competition, Tunedate, Versionname, VersionDomain, Version_id )
		SELECT a.Id, a.Keywords, a.Power, a.Province_Id, a.Competition, Tunedate, 'www.51rc.com', '伍亿人才网', a.Version_id 
		FROM SearchKeywords a WITH(NOLOCK)
		WHERE a.Province_id = @ProvinceID 
		ORDER BY a.Power desc

	IF @Site = 1
		DELETE @t WHERE Version_id > 100 
	IF @Site = 2
		DELETE @t WHERE Version_id < 100 

	DELETE @r
	INSERT INTO @r
	SELECT c.ID, a.Keywords, SUM(a.HowMany) Cnt
	FROM Referer_Count_Keywords a WITH(NOLOCK),
		Referer_Count b WITH(NOLOCK),
		@u c
	WHERE a.Referer_Count_id = b.id 
	AND b.province_id = @ProvinceID
	AND b.Countdate > CONVERT(VARCHAR(8), GETDATE() - 7, 112)
	AND b.Referer = c.Url
	AND a.Keywords in(SELECT Keywords FROM SearchKeywords WITH(NOLOCK) WHERE Province_id = @ProvinceID)
	GROUP BY c.ID, a.Keywords

/*
	INSERT INTO @r
	SELECT b.Referer, a.Keywords, SUM(a.HowMany) Cnt
	FROM Referer_Count_Keywords a WITH(NOLOCK),
		Referer_Count b WITH(NOLOCK)
	WHERE a.Referer_Count_id = b.id 
	AND b.province_id = @ProvinceID
	AND b.Countdate > CONVERT(VARCHAR(8), GETDATE() - 7, 112)
	AND b.Referer IN('http://www.baidu.com/', 'http://www.so.com/', 'http://www.sogou.com/')
	AND a.Keywords in(SELECT Keywords FROM SearchKeywords WITH(NOLOCK) WHERE Province_id = @ProvinceID)
	GROUP BY b.Referer, a.Keywords
*/
	UPDATE a
	SET a.FROMBaidu = b.Cnt
	FROM @t a, @r b
	WHERE a.Keywords = b.Keywords
	AND a.Version_ID < 100
	AND b.Id = 1

	UPDATE a
	SET a.FROM360 = b.Cnt
	FROM @t a, @r b
	WHERE a.Keywords = b.Keywords
	AND a.Version_ID < 100
	AND b.Id = 2

	UPDATE a
	SET a.FROMSogou = b.Cnt
	FROM @t a, @r b
	WHERE a.Keywords = b.Keywords
	AND a.Version_ID < 100
	AND b.Id = 3
	DELETE @r

	INSERT INTO @r
	SELECT c.ID, a.Keywords, SUM(a.HowMany) Cnt
	FROM Seconderer_Count_Keywords a WITH(NOLOCK),
		Seconderer_Count b WITH(NOLOCK),
		@u c
	WHERE a.Referer_Count_id = b.id 
	AND b.province_id = @ProvinceID
	AND b.Countdate > CONVERT(VARCHAR(8), GETDATE() - 7, 112)
	AND b.Referer = c.Url
	AND a.Keywords in(SELECT Keywords FROM SearchKeywords WITH(NOLOCK) WHERE Province_id = @ProvinceID)
	GROUP BY c.ID, a.Keywords

	UPDATE a
	SET a.FROMBaidu = b.Cnt
	FROM @t a, @r b
	WHERE a.Keywords = b.Keywords
	AND a.Version_ID > 100
	AND b.Id = 1

	UPDATE a
	SET a.FROM360 = b.Cnt
	FROM @t a, @r b
	WHERE a.Keywords = b.Keywords
	AND a.Version_ID > 100
	AND b.Id = 2

	UPDATE a
	SET a.FROMSogou = b.Cnt
	FROM @t a, @r b
	WHERE a.Keywords = b.Keywords
	AND a.Version_ID > 100
	AND b.Id = 3
	
	IF @Site!=3
	BEGIN
		INSERT @p
		SELECT YearmonthDay, SearchKeywords_Id, Engine, Power
		FROM SearchKeywordsPower WITH(NOLOCK)
		WHERE  engine IN('360','baidu','sogou')
		AND SearchKeywords_Id IN(SELECT ID FROM SearchKeywords WHERE Province_Id = @ProvinceID)
		AND YearmonthDay IN (SELECT D FROM @d)
	END
	ELSE
	BEGIN
		INSERT @p
		SELECT YearmonthDay, SearchKeywords_Id, Engine, Power
		FROM SearchKeywordsPower WITH(NOLOCK)
		WHERE engine IN('m360','mbaidu','msogou') 
		AND SearchKeywords_Id IN(SELECT ID FROM SearchKeywords WHERE Province_Id = @ProvinceID)
		AND YearmonthDay IN (SELECT D FROM @d)
	END
	
	--UPDATE a
	--SET a.BaiduRank1 = b.Power
	--FROM @t a, @p b, @d c
	--WHERE a.ID = b.SearchKeywords_Id
	--AND b.YearmonthDay = c.D
	--AND c.ID = 1
	--AND b.Engine like '%baidu'

	UPDATE @t
	SET BaiduRank3 = (SELECT TOP 1 Power FROM @p WHERE YearmonthDay = (SELECT D FROM @d WHERE ID = 1) AND Engine like '%baidu' AND SearchKeywords_Id = ID),
		BaiduRank2 = (SELECT TOP 1 Power FROM @p WHERE YearmonthDay = (SELECT D FROM @d WHERE ID = 2) AND Engine like '%baidu' AND SearchKeywords_Id = ID),
		BaiduRank1 = (SELECT TOP 1 Power FROM @p WHERE YearmonthDay = (SELECT D FROM @d WHERE ID = 3) AND Engine like '%baidu' AND SearchKeywords_Id = ID),
		_360Rank3 = (SELECT TOP 1 Power FROM @p WHERE YearmonthDay = (SELECT D FROM @d WHERE ID = 1) AND Engine like '%360' AND SearchKeywords_Id = ID),
		_360Rank2 = (SELECT TOP 1 Power FROM @p WHERE YearmonthDay = (SELECT D FROM @d WHERE ID = 2) AND Engine like '%360' AND SearchKeywords_Id = ID),
		_360Rank1 = (SELECT TOP 1 Power FROM @p WHERE YearmonthDay = (SELECT D FROM @d WHERE ID = 3) AND Engine like '%360' AND SearchKeywords_Id = ID),
		SogouRank3 = (SELECT TOP 1 Power FROM @p WHERE YearmonthDay = (SELECT D FROM @d WHERE ID = 1) AND Engine like '%sogou' AND SearchKeywords_Id = ID),
		SogouRank2 = (SELECT TOP 1 Power FROM @p WHERE YearmonthDay = (SELECT D FROM @d WHERE ID = 2) AND Engine like '%sogou' AND SearchKeywords_Id = ID),
		SogouRank1 = (SELECT TOP 1 Power FROM @p WHERE YearmonthDay = (SELECT D FROM @d WHERE ID = 3) AND Engine like '%sogou' AND SearchKeywords_Id = ID)

	IF @Sort = 3
		SELECT * FROM @t ORDER BY Competition DESC
	Else IF @Sort = 1
		SELECT * FROM @t ORDER BY Power DESC
	ELSE
		SELECT * FROM @t ORDER BY Version_ID DESC	
END

GO
/****** Object:  StoredProcedure [dbo].[bpSearchKeywordsByTuneDateUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.08.27
--创建人：Nick
--说明：修改tunedate
--#####################################################
CREATE PROCEDURE [dbo].[bpSearchKeywordsByTuneDateUpdate]
(
	@ID INT
)
AS
BEGIN
	UPDATE searchkeywords SET tunedate = GETDATE() WHERE ID = @ID
END

GO
/****** Object:  StoredProcedure [dbo].[bpSearchKeywordsByVersionIDUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.08.27
--创建人：Nick
--说明：根据ID 修改searchkeywords
--#####################################################
CREATE PROCEDURE [dbo].[bpSearchKeywordsByVersionIDUpdate]
(
	@ID INT,
	@KeyWords VARCHAR(100),
	@Power INT,
	@Version_ID INT,
	@competitionPrice VARCHAR(20)
)
AS
BEGIN
	DECLARE @SQL VARCHAR(MAX)
	SET @SQL = 'UPDATE searchkeywords SET keywords='''+@KeyWords+''',power='+CONVERT(VARCHAR(10),@Power)+',version_id = '+CONVERT(VARCHAR(10),@Version_ID)
	IF @competitionPrice <> ''
	BEGIN
		SET @SQL = @SQL + ',competitionPrice='+@competitionPrice
	END
	ELSE
	BEGIN
		SET @SQL = @SQL + ',competitionPrice=null '
	END
	SET @SQL = @SQL + ' where id='+CONVERT(VARCHAR(10),@ID)
	EXEC(@SQL)
END



GO
/****** Object:  StoredProcedure [dbo].[bpSearchKeywordsInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.08.27
--创建人：Nick
--说明：插入searchkeywords
--#####################################################
CREATE PROCEDURE [dbo].[bpSearchKeywordsInsert]
(
	@KeyWords VARCHAR(100),
	@Power INT,
	@Province_ID INT,
	@Version_ID INT
)
AS
BEGIN
	INSERT INTO searchkeywords (keywords,power,province_id,version_id) 
	VALUES(@KeyWords,@Power,@Province_ID,@Version_ID)
END

GO
/****** Object:  StoredProcedure [dbo].[bpSearchKeywordsPowerBySearchKeywords_IDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.08.27
--创建人：Nick
--说明：根据ProvinceID查询searchkeywords
--#####################################################
CREATE PROCEDURE [dbo].[bpSearchKeywordsPowerBySearchKeywords_IDSelect]
(
	@ID INT,
	@Engine VARCHAR(50)
)
AS
BEGIN
	SELECT TOP 1 power,id,adddate 
	FROM searchkeywordspower WITH(NOLOCK) 
	WHERE searchkeywords_id = @ID 
	AND engine = @Engine
	ORDER BY yearmonthday DESC
END

GO
/****** Object:  StoredProcedure [dbo].[bpSearchKeywordsPowerByYearMonthDaySelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.08.27
--创建人：Nick
--说明：根据yearmonthday查询pr_alex
--#####################################################
CREATE PROCEDURE [dbo].[bpSearchKeywordsPowerByYearMonthDaySelect]
(
	@Day VARCHAR(10),
	@Type INT
)
AS
BEGIN
	DECLARE @SQL VARCHAR(MAX)
	IF @Type = 1
	BEGIN
		SET @SQL = 'select distinct top 20 yearmonthday from searchkeywordspower with(nolock)  '
	END
	ELSE
	BEGIN
		SET @SQL = 'select distinct top 3 yearmonthday from searchkeywordspower with(nolock)  '
	END
	IF @Day <> ''
	BEGIN
		SET @SQL = @SQL + ' where yearmonthday<='+@Day
	END
	SET @SQL = @SQL + ' ORDER BY yearmonthday DESC'
	EXEC(@SQL)
END

GO
/****** Object:  StoredProcedure [dbo].[bpSeconderer_Count_KeywordsByReferer_Count_IDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.08.27
--创建人：Nick
--说明：根据seconderer_count_id查询seconderer_count_keywords
--#####################################################
CREATE PROCEDURE [dbo].[bpSeconderer_Count_KeywordsByReferer_Count_IDSelect]
(
	@Referer_Count_ID INT
)
AS
BEGIN
	SELECT howmany,keywords 
	FROM seconderer_count_keywords WITH(NOLOCK) 
	WHERE referer_count_id=@Referer_Count_ID 
	ORDER BY howmany DESC
END

GO
/****** Object:  StoredProcedure [dbo].[bpSeconderer_CountByCountdateSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.08.27
--创建人：Nick
--说明：根据countdate查询seconderer_count
--#####################################################
CREATE PROCEDURE [dbo].[bpSeconderer_CountByCountdateSelect]
(
	@ProvinceID VARCHAR(10),
	@CountDate VARCHAR(20),
	@Referer VARCHAR(200)
)
AS
SET NOCOUNT ON
BEGIN
	DECLARE @SQL VARCHAR(MAX)
	SET @SQL = 'SELECT seconderer_count_keywords.howmany,seconderer_count_keywords.keywords 
		FROM seconderer_count_keywords WITH(NOLOCK),seconderer_count WITH(NOLOCK) 
		WHERE seconderer_count_keywords.referer_count_id=seconderer_count.id  '
	IF LEN(@ProvinceID) = 3 AND LEFT(@ProvinceID,1)='3'
	BEGIN
		SET @SQL = @SQL + ' AND seconderer_count.province_id LIKE ''%'+RIGHT(@ProvinceID,2)+'''  '
	END
	ELSE
	BEGIN
		SET @SQL = @SQL + ' AND seconderer_count.province_id = '+@ProvinceID
	END
	SET @SQL = @SQL + ' AND seconderer_count.countdate= '''+ @CountDate +''' AND seconderer_count.referer = '''+@Referer+''' 
	ORDER BY seconderer_count_keywords.howmany DESC'
	EXEC(@SQL)
END

GO
/****** Object:  StoredProcedure [dbo].[bpSeconderer_CountByDayItemSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--nick 2015-10-20
--二级域名城市站 月报
--#####################################################
CREATE PROCEDURE [dbo].[bpSeconderer_CountByDayItemSelect] 
(
	@ProvinceId INT,
	@Site INT,
	@BD VARCHAR(6)
)
AS
BEGIN
	SET NOCOUNT ON
	DECLARE @Sd AS DATETIME, @ED DATETIME, @I INT, @P VARCHAR(30)
	--SET @Sd = CONVERT(DATETIME, @BD + '26')
	--IF @Sd > GETDATE()
	--	SET @Sd = CONVERT(VARCHAR(8), DATEADD(MONTH, -1, GETDATE()), 120) + '26'
	--ELSE 
	--BEGIN

	SET @Sd = DATEADD(Month, -1, @BD + '26')
	--END

	IF @Site = 3
	BEGIN
		IF LEN(@ProvinceId) IN(3, 5)
			SET @ProvinceId = RIGHT(@ProvinceId, LEN(@ProvinceId) - 1)
		SET @p = LTRIM(STR(@ProvinceId)) + ',1' + LTRIM(STR(@ProvinceId)) + ',2' + LTRIM(STR(@ProvinceId))
	END
	ELSE
		SET @p = LTRIM(STR(@ProvinceId))	

	
	--IF DATEADD(MONTH, 1, @Sd) > GETDATE()
	--	SET @Ed = CONVERT(VARCHAR(10), GETDATE(), 120)
	--ELSE
	SET @Ed = DATEADD(Month, 1, @Sd) - 1

	CREATE TABLE #d(ID INT IDENTITY(1, 1), CountDate VARCHAR(8))

	PRINT (CONVERT(VARCHAR(8), @sd, 112)+'**'+CONVERT(VARCHAR(8), @Ed, 112))

	INSERT #d
	SELECT WorkDate
	FROM Oadb..WorkDate
	WHERE WorkDate BETWEEN CONVERT(VARCHAR(8), @sd, 112) AND CONVERT(VARCHAR(8), @Ed, 112)

	SELECT b.Item_Id, a.CountDate, SUM(a.HowMany) HowMany
	INTO #r
	FROM Referer_Item_Keywords b WITH(NOLOCK),
		Seconderer_Count a WITH(NOLOCK)
	WHERE a.VersionId IN(SELECT * FROM dbo.FnSplit(@p, ','))
	AND CHARINDEX(b.Keywords, a.Referer) > 0
	AND a.CountDate IN(SELECT CountDate FROM #d)
	GROUP BY b.Item_Id, a.CountDate
	ORDER BY b.Item_Id, a.CountDate

	DECLARE @Sql VARCHAR(MAX)
	SET @Sql = 'CREATE TABLE LogDb..a_Tmp(ID INT, Item_Name NVARCHAR(50), '
	SELECT @Sql = @Sql + 'Col' + LTRIM(STR(Id)) + ' VARCHAR(10), ' FROM #d
	SET @Sql = @Sql + 'Col100 VARCHAR(10))'
	EXEC(@Sql)
	SELECT * INTO #t FROM LogDb..a_Tmp
	DROP TABLE LogDb..a_Tmp

	SET @Sql = 'INSERT INTO #t SELECT 0, '''', '''
	SELECT @Sql = @sql + RIGHT(CountDate, 4) + ''' , ''' FROM #d ORDER BY ID
	SET @Sql = @sql + '行合计'''
	EXEC(@Sql)

	INSERT INTO #t(Id, Item_Name) SELECT Id, Item_Name FROM Referer_Item
	INSERT INTO #t(Id, Item_Name) SELECT 999, '列合计'
	SET @i = 0
	WHILE EXISTS(SELECT 'x' FROM #d WHERE ID > @i)
	BEGIN
		SELECT TOP 1 @i = Id FROM #d WHERE Id > @i ORDER BY Id
		SET @Sql = 'UPDATE a SET a.Col' + LTRIM(STR(@i)) + ' = b.HowMany FROM #t a, #r b, #d c WHERE a.Id = b.Item_Id AND c.CountDate = b.CountDate AND c.Id = ' + LTRIM(STR(@i))
		--PRINT(@Sql)
		EXEC(@Sql)
		SET @Sql = 'UPDATE #t SET Col' + LTRIM(STR(@i)) + ' = (SELECT SUM(CONVERT(INT, Col' + LTRIM(STR(@i)) + ')) FROM #t WHERE Id > 0 AND Id < 999) WHERE Id = 999'
		--PRINT(@Sql)
		EXEC(@Sql)
	END
	SELECT @Sql = 'UPDATE #t SET Col100 = '
	SELECT @Sql = @Sql + 'CONVERT(INT, ISNULL(Col' + LTRIM(STR(ID)) + ', 0)) + ' FROM #d
	SELECT @Sql = @Sql + '0 WHERE Id > 0'
	EXEC(@Sql)
	
	SELECT * FROM #t ORDER BY CASE ID WHEN 0 THEN 0 WHEN 999 THEN 999 ELSE 2 END, Item_Name
END

GO
/****** Object:  StoredProcedure [dbo].[bpSeconderer_CountByDaySelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.08.25
--创建人：Nick
--说明：来源分析统计（日报）
--#####################################################
CREATE PROCEDURE [dbo].[bpSeconderer_CountByDaySelect]
(
	@Site VARCHAR(10),
	@Day VARCHAR(8)
)
AS
BEGIN
	DECLARE @WHERE VARCHAR(MAX)
	SET @WHERE  = 'SUM(CASE Province_Id WHEN 0 Then HowMany Else 0 END) [51RC]'
	DECLARE @CateID INT,@Province VARCHAR(20)
	DECLARE c_CateGoryID CURSOR FAST_FORWARD FOR
	--读取
	SELECT CASE @Site WHEN '1' THEN 100+ID WHEN '2' THEN 200+ID ELSE ID END,province  
	FROM province WITH(NOLOCK) 
	ORDER BY CASE southnorth WHEN 4 THEN 1 ELSE southnorth END DESC,id
	-- 打开游标.
	OPEN c_CateGoryID;
		WHILE 1=1
		BEGIN
		FETCH NEXT FROM c_CateGoryID INTO @CateID,@Province
		IF @Site = '100'
		BEGIN
			SET @WHERE = @WHERE+',SUM(CASE  WHEN Province_Id IN ('+CONVERT(VARCHAR(20),@CateID)+',1'+CONVERT(VARCHAR(20),@CateID)+') Then HowMany Else 0 END) ['+@Province+']'
		END
		ELSE
		BEGIN
			SET @WHERE = @WHERE+',SUM(CASE Province_Id WHEN '+CONVERT(VARCHAR(20),@CateID)+' Then HowMany Else 0 END) ['+@Province+']'
		END
		IF @@fetch_status<> 0 BREAK
	END
	-- 关闭游标
	CLOSE c_CateGoryID;
	-- 释放游标.
	DEALLOCATE c_CateGoryID;

	DECLARE @SQL VARCHAR(MAX)
	SET @SQL = 'SELECT '+@WHERE+',SUM(howmany) cnt,item_Name 
		FROM seconderer_count a WITH(NOLOCK),referer_item_keywords b WITH(NOLOCK),referer_item c WITH(NOLOCK) 
		WHERE Item_Id=c.ID And countdate='+@Day+' and charindex(b.keywords, a.referer) >0'
	IF @Site = '1'
	BEGIN
		SET @SQL = @SQL+'  AND Province_Id LIKE ''1__'' '
	END
	ELSE IF @Site = ''
	BEGIN
		SET @SQL = @SQL+' AND LEN(Province_Id) <= 2 '
	END
	SET @SQL = @SQL + ' GROUP BY item_Name ORDER BY item_Name'
	print (@SQL)
	EXEC(@SQL)
END


GO
/****** Object:  StoredProcedure [dbo].[bpSeconderer_CountByHowManySelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.08.27
--创建人：Nick
--说明：根据yearmonthday查询referer_count
--#####################################################
CREATE PROCEDURE [dbo].[bpSeconderer_CountByHowManySelect]
(
	@CountDate VARCHAR(20),
	@ProvinceID VARCHAR(10),
	@Site VARCHAR(10),
	@KeyWord VARCHAR(100)
)
AS
BEGIN
	DECLARE @SQL VARCHAR(MAX)
	SET @SQL = 'SELECT SUM(howmany) cnt FROM seconderer_count with(nolock) WHERE '
	IF @Site = '100'
	BEGIN
		SET @SQL = @SQL + ' province_id like ''%'+RIGHT(@ProvinceID,2)+''' '
	END
	ELSE
	BEGIN
		SET @SQL = @SQL + ' province_id = '+@ProvinceID
	END
	SET @SQL = @SQL + ' and countdate = '+@CountDate +' AND referer LIKE ''%'+@KeyWord+'%'''
	EXEC(@SQL)
END

GO
/****** Object:  StoredProcedure [dbo].[bpSeconderer_countBYIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.08.27
--创建人：Nick
--说明：根据ID查询seconderer_count
--#####################################################
CREATE PROCEDURE [dbo].[bpSeconderer_countBYIDSelect]
(
	@ID INT
)
AS
BEGIN
	SELECT referer 
	FROM seconderer_count WITH(NOLOCK) 
	WHERE ID = @ID
END

GO
/****** Object:  StoredProcedure [dbo].[bpSeconderer_CountByProvinceIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.08.27
--创建人：Nick
--说明：根据province_id查询seconderer_count
--#####################################################
CREATE PROCEDURE [dbo].[bpSeconderer_CountByProvinceIDSelect]
(
	@ProvinceID VARCHAR(10),
	@CountDate VARCHAR(20)
)
AS
SET NOCOUNT ON
BEGIN
	DECLARE @SQL VARCHAR(MAX)
	SET @SQL = 'SELECT sum(howmany) howmany,referer FROM seconderer_count WITH(NOLOCK) WHERE '
	IF LEN(@ProvinceID) = 3 AND LEFT(@ProvinceID, 1) = '3'
		SET @SQL = @SQL + ' province_id like ''%' + RIGHT(@ProvinceID, 2) + '''  '
	ELSE
		SET @SQL = @SQL + ' province_id = ' + @ProvinceID
	SET @SQL = @SQL + ' and countdate= ' + @CountDate + ' GROUP BY referer ORDER BY howmany DESC'
	PRINT @SQL
	EXEC(@SQL)
END

GO
/****** Object:  StoredProcedure [dbo].[bpSeconderer_CountByVersionIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.08.27
--创建人：Nick
--说明：根据@VersionID查询seconderer_count
--#####################################################
CREATE PROCEDURE [dbo].[bpSeconderer_CountByVersionIDSelect]
(
	@VersionID VARCHAR(10),
	@CountDate VARCHAR(20),
	@Site Varchar(10)
)
AS
BEGIN
	DECLARE @SQL VARCHAR(MAX)
	IF LEFT(@VersionID,6)='999999'
	BEGIN
		SET @SQL = 'SELECT SUM(howmany) howmany,referer 
		FROM seconderer_count WITH(NOLOCK) 
		WHERE versionid like '''+RIGHT(@VersionID,2)+'____'' 
		AND COUNTDATE = '+@CountDate+' 
		GROUP BY referer 
		ORDER BY SUM(howmany) DESC'
	END
	ELSE
	BEGIN
		SET @SQL = 'SELECT howmany,referer,id 
		FROM seconderer_count WITH(NOLOCK) 
		WHERE versionid = '+@Site+@VersionID+' 
		AND countdate = '+@CountDate+' 
		ORDER BY howmany DESC'
	END
	EXEC(@SQL)
END

GO
/****** Object:  StoredProcedure [dbo].[bpSeconderer_YearmonthByDcProvinceSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.08.25
--创建人：Nick
--说明：来源分析二级域名（月报）
--修改统计错误Harrry2-15-12-29
--#####################################################
CREATE PROCEDURE [dbo].[bpSeconderer_YearmonthByDcProvinceSelect]
(
	@Site VARCHAR(10),
	@YearMonth VARCHAR(6)
)
AS
BEGIN
	IF @Site = ''
	BEGIN
		SELECT SUM(howmany) howmany 
		FROM seconderer_yearmonth WITH(NOLOCK) 
		WHERE yearmonth=@YearMonth
		AND (LEN(Province_id)<=2)
	END
	ELSE IF @Site = '1'
	BEGIN
		SELECT SUM(howmany) howmany 
		FROM seconderer_yearmonth WITH(NOLOCK) 
		WHERE Province_id LIKE '1__' 
		AND yearmonth=@YearMonth
	END
	ELSE
	BEGIN
		SELECT SUM(howmany) howmany 
		FROM seconderer_yearmonth WITH(NOLOCK) 
		WHERE yearmonth=@YearMonth
	END
END
 
GO
/****** Object:  StoredProcedure [dbo].[bpSeconderer_YearmonthByYearMonthSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.08.25
--创建人：Nick
--说明：来源分析二级域名统计（月报）
--修改：统计错误，Harry2015-12-29
--#####################################################
CREATE PROCEDURE [dbo].[bpSeconderer_YearmonthByYearMonthSelect]
(
	@Site VARCHAR(10),
	@YearMonth VARCHAR(6)
)
AS
BEGIN
	DECLARE @WHERE VARCHAR(MAX)
	SET @WHERE  = 'SUM(CASE Province_Id WHEN 0 Then HowMany Else 0 END) [51RC]'
	DECLARE @CateID INT,@Province VARCHAR(20)
	DECLARE c_CateGoryID CURSOR FAST_FORWARD FOR
	--读取
	--SELECT CASE @Site WHEN '1' THEN 100+ID WHEN '2' THEN 200+ID ELSE ID END,province  
	SELECT ID,Province
	FROM province WITH(NOLOCK) 
	ORDER BY CASE southnorth WHEN 4 THEN 1 ELSE southnorth END DESC,id
	-- 打开游标.
	OPEN c_CateGoryID;
		WHILE 1=1
		BEGIN
		FETCH NEXT FROM c_CateGoryID INTO @CateID,@Province
		IF @Site=100
		BEGIN
			SET @WHERE = @WHERE+',SUM(CASE right(Province_Id,2) WHEN '+CONVERT(VARCHAR(20),@CateID)+' Then HowMany Else 0 END) ['+@Province+']'
		END
		ELSE
		BEGIN
			SET @WHERE = @WHERE+',SUM(CASE Province_Id WHEN '+CONVERT(VARCHAR(20),@CateID)+' Then HowMany Else 0 END) ['+@Province+']'
		END
		IF @@fetch_status<> 0 BREAK
	END
	-- 关闭游标
	CLOSE c_CateGoryID;
	-- 释放游标.
	DEALLOCATE c_CateGoryID;

	DECLARE @SQL VARCHAR(MAX)
	SET @SQL = 'SELECT '+@WHERE+',SUM(howmany) cnt,item_Name FROM seconderer_yearmonth WITH(NOLOCK) WHERE YearMonth='+@YearMonth
	IF @Site = '2'
	BEGIN
		SET @SQL = @SQL+'  AND Province_Id LIKE ''2__''  '
	END
	IF @Site = '1'
	BEGIN
		SET @SQL = @SQL+'  AND Province_Id LIKE ''1__'' '
	END
	ELSE IF @Site = '3'
	BEGIN
		SET @SQL = @SQL+'  AND Province_Id LIKE ''3__'' '
	END
	ELSE IF @Site = '' OR @Site = '0'
	BEGIN
		SET @SQL = @SQL+' AND LEN(Province_Id) <= 2 '
	END
	SET @SQL = @SQL +' GROUP BY item_Name ORDER BY item_Name'
	PRINT @SQL
	EXEC(@SQL)
END  

 

GO
/****** Object:  StoredProcedure [dbo].[bpSecondererByKeyWordsSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.08.27
--创建人：Nick
--说明：根据keywords查询seconderer
--#####################################################
CREATE PROCEDURE [dbo].[bpSecondererByKeyWordsSelect]
(
	@ProvinceID VARCHAR(10)
)
AS
BEGIN
	DECLARE @SQL VARCHAR(MAX)
	SET @SQL = 'SELECT keywords, Count(*) cnt FROM seconderer with(nolock) WHERE '
	IF LEN(@ProvinceID) = 3 AND LEFT(@ProvinceID,1)='3'
	BEGIN
		SET @SQL = @SQL + ' province_id like ''%'+RIGHT(@ProvinceID,2)+'''  '
	END
	ELSE
	BEGIN
		SET @SQL = @SQL + ' province_id = '+@ProvinceID
	END
	SET @SQL  = @SQL + ' GROUP BY keywords ORDER BY COUNT(*) DESC'
	EXEC(@SQL)
END

GO
/****** Object:  StoredProcedure [dbo].[bpSecondererByProvinceIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.08.27
--创建人：Nick
--说明：根据province_id查询seconderer
--#####################################################
CREATE PROCEDURE [dbo].[bpSecondererByProvinceIDSelect]
(
	@ProvinceID VARCHAR(10),
	@Search_text VARCHAR(50),
	@Search_action  INT,
	@search_item INT
)
AS
BEGIN
	DECLARE @SQL VARCHAR(MAX)
	SET @SQL = 'SELECT referer,logindate,ip,keywords,versionid FROM seconderer WITH(NOLOCK) WHERE '
	IF LEN(@ProvinceID) = 3 AND LEFT(@ProvinceID,1)='3'
	BEGIN
		SET @SQL = @SQL + ' province_id like ''%'+RIGHT(@ProvinceID,2)+'''  '
	END
	ELSE
	BEGIN
		SET @SQL = @SQL + ' province_id = '+@ProvinceID
	END
	IF @search_item = 1 AND @Search_text<>''
	BEGIN
		IF @Search_action = 1
		BEGIN
			SET @SQL = @SQL + ' AND referer like '''+@Search_text+'%''  '
		END
		IF @Search_action = 2
		BEGIN
			SET @SQL = @SQL + ' AND referer like ''%'+@Search_text+'%''  '
		END
	END
	IF @search_item = 2 AND @Search_text<>''
	BEGIN
		IF @Search_action = 1
		BEGIN
			SET @SQL = @SQL + ' AND IP like '''+@Search_text+'%''  '
		END
		IF @Search_action = 2
		BEGIN
			SET @SQL = @SQL + ' AND IP like ''%'+@Search_text+'%''  '
		END
	END
	SET @SQL  = @SQL + ' ORDER BY logindate DESC'
	EXEC(@SQL)
END

GO
/****** Object:  StoredProcedure [dbo].[bpSeekCompanyIpLogInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[bpSeekCompanyIpLogInsert]
(
	@ManageruserId INT,
	@IP VARCHAR(100),
	@UniCode VARCHAR(20)
)
AS
SET NOCOUNT ON
BEGIN
	INSERT INTO ShortDb..SeekCompanyIpLog VALUES (@ManageruserId, @IP, GETDATE(), @UniCode, GETDATE())
END
SET NOCOUNT OFF
GO
/****** Object:  StoredProcedure [dbo].[bpSeekCompanyIpLogUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

create PROCEDURE [dbo].[bpSeekCompanyIpLogUpdate]
(
	@UniCode VARCHAR(20)
)
AS
SET NOCOUNT ON
BEGIN
	UPDATE ShortDb..SeekCompanyIpLog SET RunDate = GETDATE() WHERE [UniCode] =  @UniCode
END
SET NOCOUNT OFF
GO
/****** Object:  StoredProcedure [dbo].[bpSeocClickLogSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--创建人 sean
--时间 2015-12-14
--按照条件查询员工autoclick点击记录
CREATE PROCEDURE [dbo].[bpSeocClickLogSelect]
(
	@RunLogId INT,
	@StartDate DATETIME,
	@EndDate DATETIME,
	@ManagerUserID INT,
	@KeyWord VARCHAR(20),
	@EndState INT,
	@RunState INT,
	@CurManagerUserID INT,--当前登录用户ID		
	@Privi INT--当前用户的权限
)
AS
SET NOCOUNT ON
BEGIN
	DECLARE @Sql VARCHAR(MAX)
	SET @Sql = '
	SELECT TOP 500 a.*, d.Keyword, d.DisturbWord, d.Url, c.Name ManagerUserName, c.ManagerUserID
	FROM ShortDb..SeocClickLog a WITH(NOLOCK),
		ShortDb..SeocRunLog b WITH(NOLOCK),
		ShortDb..SeocUser c WITH(NOLOCK),
		ShortDb..SeocKeyWord d WITH(NOLOCK)
	WHERE a.SeocRunLogId = b.Id
	AND b.SeocUSerId = c.Id
	AND a.SeocKeywordId = d.Id
	AND c.ManagerUserId IN (
		SELECT ID FROM dbo.LowerUserALL(' + LTRIM(STR(@CurManagerUserID)) + ', ' + LTRIM(STR(@Privi)) + '))'

	IF @RunLogId > 0 
		SET @Sql = @sql + ' AND a.SeocRunLogId = ' + LTRIM(STR(@RunLogId))
	IF @StartDate > '2010-1-1'
		SET @Sql = @sql + ' AND a.AddDate >= ''' + CONVERT(VARCHAR(20), @StartDate, 120) + ''''
	IF @EndDate > '2010-1-1'
		SET @Sql = @sql + ' AND a.AddDate < ''' + CONVERT(VARCHAR(20), @EndDate, 120) + ''''
	IF @ManagerUserID > 0
		SET @Sql = @Sql + ' AND c.ManagerUserId = ' + LTRIM(STR(@ManagerUserID))
	IF @KeyWord > ''
	BEGIN
		SET @KeyWord = dbo.SafeSql(@KeyWord)
		SET @Sql = @Sql + ' AND d.Keyword = ''' + @KeyWord + ''''
	END
	IF @EndState > -1
		SET @Sql = @Sql + ' AND a.EndState = ' + LTRIM(STR(@EndState))
	IF @RunState = 1
		SET @Sql = @Sql + ' AND a.StartDate IS NOT NULL AND a.SourceUrl IS NULL'
	IF @RunState = 2
		SET @Sql = @Sql + ' AND a.SourceUrl IS NOT NULL'
	SET @Sql = @Sql + ' ORDER BY a.Id DESC'

	EXEC(@Sql)
END

GO
/****** Object:  StoredProcedure [dbo].[bpSeocRunLogSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


--创建人 sean
--时间 2015-12-14
--按照条件查询员工autoclick点击记录
CREATE PROCEDURE [dbo].[bpSeocRunLogSelect]
(		
	@StartDate DATETIME,
	@EndDate DATETIME,
	@ManagerUserID INT,
	@CurManagerUserID INT,--当前登录用户ID		
	@Privi INT--当前用户的权限
)
AS
SET NOCOUNT ON
BEGIN	
	DECLARE @SQL VARCHAR(1000)
	SET @SQL = '
		SELECT TOP 500 a.*, b.ManagerUserId, b.Name ManagerUserName
		FROM ShortDb..seocRunLog a, ShortDb..SeocUser b
		WHERE a.SeocUserId = b.Id
		'
	IF @StartDate > '2010-1-1'
		SET @SQL = @SQL + ' AND a.AddDate >= ''' + CONVERT(VARCHAR(20), @StartDate, 120) + ''''
	IF @EndDate > '2010-1-1'
		SET @SQL = @SQL + ' AND a.AddDate <= ''' + CONVERT(VARCHAR(20), @EndDate, 120) + ''''
	IF @ManagerUserID > 0
		SET @SQL = @SQL + ' AND b.ManagerUserId = ' + LTRIM(STR(@ManagerUserID))		
	--权限
	SET @SQL = @SQL + ' AND b.ManagerUserId IN (SELECT ID FROM dbo.LowerUserALL('+LTRIM(STR(@CurManagerUserID)) + ',' + LTRIM(STR(@Privi)) + '))'	
	SET @SQL = @SQL + ' ORDER BY a.adddate desc,Id DESC'
	--PRINT(@SQL)
	EXEC (@SQL)
END

GO
/****** Object:  StoredProcedure [dbo].[bpShareMainLogByMonthStatisticsSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--bpShareMainLogByMonthStatisticsSelect 2015
--#####################################################
--创建时间：2015.1.14
--创建人：Andy
--说明：按照月统计单位分享
--#####################################################
CREATE PROCEDURE [dbo].[bpShareMainLogByMonthStatisticsSelect]
(
	@Year VARCHAR(4)
)
AS
BEGIN
	CREATE TABLE #T(
		[Month] VARCHAR(6),
		SinaWeibo INT,
		WeChat INT,
		RenRen INT,
		QQZone INT,
		QQWeibo INT,
		QQ INT,
		Tieba INT,
		Douban INT
	)
	INSERT #T
	SELECT
		CONVERT(VARCHAR(6), AddDate, 112),0,0,0,0,0,0,0,0
	FROM LogDB..ShareMainLog 
	WHERE PageMark IN (1, 2) AND CONVERT(VARCHAR(4), AddDate, 112) = @Year
	GROUP BY CONVERT(VARCHAR(6), AddDate, 112)

	SELECT CONVERT(VARCHAR(6), AddDate, 112) [Month], ShareWay, SUM(ClickCount) Cnt INTO #Log FROM LogDB..ShareMainLog
	WHERE CONVERT(VARCHAR(4), AddDate, 112) = @Year
	GROUP BY CONVERT(VARCHAR(6), AddDate, 112), ShareWay

	UPDATE #T SET SinaWeibo = (SELECT Cnt FROM #Log WHERE ShareWay = 1 AND #Log.[Month] = #T.[Month])
	UPDATE #T SET WeChat = (SELECT Cnt FROM #Log WHERE ShareWay = 2 AND #Log.[Month] = #T.[Month])
	UPDATE #T SET RenRen = (SELECT Cnt FROM #Log WHERE ShareWay = 3 AND #Log.[Month] = #T.[Month])
	UPDATE #T SET QQZone = (SELECT Cnt FROM #Log WHERE ShareWay = 4 AND #Log.[Month] = #T.[Month])
	UPDATE #T SET QQWeibo = (SELECT Cnt FROM #Log WHERE ShareWay = 5 AND #Log.[Month] = #T.[Month])
	UPDATE #T SET QQ = (SELECT Cnt FROM #Log WHERE ShareWay = 6 AND #Log.[Month] = #T.[Month])
	UPDATE #T SET Tieba = (SELECT Cnt FROM #Log WHERE ShareWay = 7 AND #Log.[Month] = #T.[Month])
	UPDATE #T SET Douban = (SELECT Cnt FROM #Log WHERE ShareWay = 8 AND #Log.[Month] = #T.[Month])
	SELECT * FROM #T
	DROP TABLE #T
	DROP TABLE #Log
END
GO
/****** Object:  StoredProcedure [dbo].[bpShareMainLogByStatisticsSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--[bpShareMainLogByStatisticsSelect] ''
--#####################################################
--创建时间：2015.1.9
--创建人：Lucifer
--修改：harry
--说明：根据条件获取单位分享量统计
--#####################################################
CREATE PROCEDURE [dbo].[bpShareMainLogByStatisticsSelect]
(
	@WHERE VARCHAR(500)
)
AS
BEGIN
	SET @WHERE = dbo.SafeSql(@WHERE)
	CREATE TABLE #T(
		cpMainID INT,
		ClickCount INT,
		ShareWay TINYINT
	)
	
	DECLARE @SQL AS VARCHAR(2000)
	SET @SQL = '
		INSERT INTO #T
		SELECT ShareMan,ClickCount,ShareWay FROM LogDB..ShareMainLog a
		WHERE PageMark = 1' + @WHERE
	EXEC(@SQL)
	SET @SQL = '
		INSERT INTO #T
		SELECT b.cpMainID,ClickCount,ShareWay FROM LogDB..ShareMainLog a, Job b
		WHERE PageMark = 2 AND a.PageID = b.ID' + @WHERE
	EXEC(@SQL)

	SELECT
		cpMainID,
		[Name],
		b.RegDate,
		(SELECT SUM(ClickCount) FROM #T WHERE #T.cpMainID = a.cpMainID AND ShareWay = 1) SinaWeibo,
		(SELECT SUM(ClickCount) FROM #T WHERE #T.cpMainID = a.cpMainID AND ShareWay = 2) WeChat,
		(SELECT SUM(ClickCount) FROM #T WHERE #T.cpMainID = a.cpMainID AND ShareWay = 3) RenRen,
		(SELECT SUM(ClickCount) FROM #T WHERE #T.cpMainID = a.cpMainID AND ShareWay = 4) QQZone,
		(SELECT SUM(ClickCount) FROM #T WHERE #T.cpMainID = a.cpMainID AND ShareWay = 5) QQWeibo,
		(SELECT SUM(ClickCount) FROM #T WHERE #T.cpMainID = a.cpMainID AND ShareWay = 6) QQ,
		(SELECT SUM(ClickCount) FROM #T WHERE #T.cpMainID = a.cpMainID AND ShareWay = 7) Tieba,
		(SELECT SUM(ClickCount) FROM #T WHERE #T.cpMainID = a.cpMainID AND ShareWay = 8) Douban
	FROM #T a, cpMain b
	WHERE a.cpMainID = b.ID 
END 

GO
/****** Object:  StoredProcedure [dbo].[bpShareMainLogByYearStatisticsSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.1.14
--创建人：Andy
--说明：按照年统计单位分享
--#####################################################
CREATE PROCEDURE [dbo].[bpShareMainLogByYearStatisticsSelect]
AS
BEGIN
	CREATE TABLE #T(
		Year VARCHAR(6),
		SinaWeibo INT,
		WeChat INT,
		RenRen INT,
		QQZone INT,
		QQWeibo INT,
		QQ INT,
		Tieba INT,
		Douban INT
	)
	INSERT #T
	SELECT
		CONVERT(VARCHAR(4), AddDate, 112),0,0,0,0,0,0,0,0
	FROM LogDB..ShareMainLog 
	WHERE PageMark IN (1, 2) 
	GROUP BY CONVERT(VARCHAR(4), AddDate, 112)

	SELECT CONVERT(VARCHAR(4), AddDate, 112) Year, ShareWay, SUM(ClickCount) Cnt INTO #Log FROM LogDB..ShareMainLog GROUP BY CONVERT(VARCHAR(4), AddDate, 112), ShareWay

	UPDATE #T SET SinaWeibo = (SELECT Cnt FROM #Log WHERE ShareWay = 1 AND #Log.Year = #T.Year)
	UPDATE #T SET WeChat = (SELECT Cnt FROM #Log WHERE ShareWay = 2 AND #Log.Year = #T.Year)
	UPDATE #T SET RenRen = (SELECT Cnt FROM #Log WHERE ShareWay = 3 AND #Log.Year = #T.Year)
	UPDATE #T SET QQZone = (SELECT Cnt FROM #Log WHERE ShareWay = 4 AND #Log.Year = #T.Year)
	UPDATE #T SET QQWeibo = (SELECT Cnt FROM #Log WHERE ShareWay = 5 AND #Log.Year = #T.Year)
	UPDATE #T SET QQ = (SELECT Cnt FROM #Log WHERE ShareWay = 6 AND #Log.Year = #T.Year)
	UPDATE #T SET Tieba = (SELECT Cnt FROM #Log WHERE ShareWay = 7 AND #Log.Year = #T.Year)
	UPDATE #T SET Douban = (SELECT Cnt FROM #Log WHERE ShareWay = 8 AND #Log.Year = #T.Year)
	SELECT * FROM #T
	DROP TABLE #T
	DROP TABLE #Log
END
GO
/****** Object:  StoredProcedure [dbo].[bpSmsMessageLogInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.09.17
--创建人：Nick
--说明：插入SmsMessageLog
--#####################################################
CREATE PROCEDURE [dbo].[bpSmsMessageLogInsert]
(
	@SendMan INT,
	@Mobile VARCHAR(100),
	@Msg VARCHAR(MAX),
	@MsgType INT
)
AS
BEGIN
	INSERT INTO SmsMessageLog(SendMan,Mobile,Msg,MsgType) 
	VALUES(@SendMan,@Mobile,@Msg,@MsgType)
END

GO
/****** Object:  StoredProcedure [dbo].[bpSmsMessageLogSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--创建人 Andy
--时间 2014-01-04
--按照条件查询短信发送记录
--修改 andy 2015-01-29,修改发送结果查询不准确的bug
--bpSmsMessageLogSelect 0, 0, 0, '', '2001-01-01','2021-01-01',2,0,3,0,''
--bpSmsMessageLogSelect 0, 0, 0, '', '','',2,0,3,0,''
CREATE PROCEDURE [dbo].[bpSmsMessageLogSelect]
(		
	@ManagerUserID INT,
	@cpMainID INT,
	@paMainID INT,
	@Mobile VARCHAR(11),
	@StartDate VARCHAR(10),--2010-01-01
	@EndDate  VARCHAR(10),--2010-01-01
	@MsgType INT,
	@Port INT,
	@SendType INT,
	@SendStatus INT,
	@Where VARCHAR(400)
)
AS
BEGIN
	SET @Mobile = dbo.SafeSql(@Mobile)
	DECLARE @SQL VARCHAR(1000)
	SET @SQL = '
		SELECT TOP 2000 a.*,b.Name companyname ,b.regdate,d.Name paName,c.cpMainID 
		FROM SmsMessageLog a WITH(NOLOCK) 
		LEFT JOIN caMain c ON a.caMainID = c.ID 
		LEFT JOIN cpMain b WITH(NOLOCK) ON c.cpMainid=b.id 
		LEFT JOIN paMain d ON a.paMainID = d.ID 
		WHERE 1 = 1 '		
	--时间
	IF LEN(@StartDate) > 0
		SET @SQL = @SQL + ' AND a.SendDate > '''+ @StartDate + ''''
	IF LEN(@EndDate) > 0
		SET @SQL = @SQL + ' AND a.SendDate < '''+ @EndDate + ''''
	--工号
	IF @ManagerUserID > 0
		SET @SQL = @SQL + ' AND (a.SendMan = ' + LTRIM(STR(@ManagerUserID)) + ' OR a.ManagerUserID= '+LTRIM(STR(@ManagerUserID)) + ' )'
	--企业ID
	IF @cpMainID > 0
		SET @SQL = @SQL + ' AND b.ID = ' + LTRIM(STR(@cpMainID))	
	--个人ID
	IF @paMainID > 0
		SET @SQL = @SQL + ' AND a.paMainID = ' + LTRIM(STR(@paMainID))
	--手机号	
	IF LEN(@Mobile) >= 11
		SET @SQL = @SQL + ' AND a.Mobile = ''' + LTRIM(@Mobile) + ''''
	ELSE IF (LEN(@Mobile) > 0 AND LEN(@Mobile) < 11)
		SET @SQL = @SQL + ' AND a.Mobile LIKE ''%' + LTRIM(@Mobile) + '%'''
	--短信类型
	IF @MsgType > 0
		SET @SQL = @SQL + ' AND a.MsgType = ' + LTRIM(STR(@MsgType))
	--发送端口
	IF @Port = -1
		SET @SQL = @SQL + ' AND IsCat = 0 ' 
	ELSE IF @Port > 0
		SET @SQL = @SQL + ' AND a.PortNo = ' + LTRIM(STR(@Port))
	--发送类型
	IF @SendType > 0
		SET @SQL = @SQL + ' AND a.SmsType = ' + LTRIM(STR(@SendType))
	--发送状态
	IF @SendStatus = 1--已发送
		SET @SQL = @SQL + ' AND a.SendStatus = 1 ' 
	ELSE IF @SendStatus = 2--未发送
		SET @SQL = @SQL + ' AND a.SendStatus Is NULL ' 
	ELSE IF @SendStatus = 3 --发送失败
		SET @SQL = @SQL + ' AND a.SendStatus <> 1 AND a.SendStatus IS NOT NULL ' 
	--WHERE条件
	IF @Where > ''
	BEGIN
		SET @Where = dbo.SafeSql(@Where)	
		SET @SQL = @SQL + @Where 
	END
	--排序
	SET @SQL = @SQL + ' ORDER BY a.id DESC'
	--PRINT(@SQL)
	EXEC (@SQL)
END


GO
/****** Object:  StoredProcedure [dbo].[bpSpreadCallLogByDaySelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--录音记录统计日报Carl
--2018-1-22 carl
CREATE PROCEDURE [dbo].[bpSpreadCallLogByDaySelect]
(
	@WHERE VARCHAR(1000)
)
AS
SET NOCOUNT ON
BEGIN
	SET @WHERE = dbo.SafeSQLBack(@WHERE)
	DECLARE @SQL VARCHAR(2000)
	SET @SQL = 'SELECT CONVERT(VARCHAR,a.addDate,112) addDate,addMan,b.[name],SUM(timeLength) totalTime, '
				+'COUNT(1) cnt FROM SpreadCallLog a WITH(NOLOCK) , ManagerUser b WITH(NOLOCK) '
				+'WHERE a.addMan=b.id '+@WHERE+' GROUP BY CONVERT(VARCHAR,a.addDate,112),a.addMan,b.[name] '
				+'ORDER BY CONVERT(VARCHAR,a.addDate,112) DESC,a.addMan'
	--PRINT @SQL
	EXEC(@SQL)
END
SET NOCOUNT OFF

GO
/****** Object:  StoredProcedure [dbo].[bpSpreadCallLogByMonthSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--录音记录统计月报Carl
--2018-1-19 carl
--2018-1-22 carl
CREATE PROCEDURE [dbo].[bpSpreadCallLogByMonthSelect]
(
	@Month VARCHAR(6),
	@WHERE VARCHAR(1000)
)
AS
SET NOCOUNT ON
BEGIN
	SET @WHERE = dbo.SafeSQLBack(@WHERE)
	DECLARE @SQL VARCHAR(2000)
	IF @Month<>''
		SET @WHERE=@WHERE + ' AND CONVERT(VARCHAR(6),DATEADD(MONTH,1,DATEADD(DD,-25,a.addDate)),112)='+@Month

	SET @SQL = 'SELECT CONVERT(VARCHAR(6),DATEADD(MONTH,1,DATEADD(DD,-25,a.addDate)),112) addDate, '
				+'addMan,b.[name],SUM(timelength) totalTime,COUNT(1) cnt '
				+'FROM SpreadCallLog a WITH(NOLOCK), manageruser b WITH(NOLOCK) '
				+'WHERE a.addMan=b.id '+@WHERE+' GROUP BY CONVERT(VARCHAR(6),DATEADD(MONTH,1,DATEADD(DD,-25,a.addDate)),112), '
				+'a.addMan,b.[name] '
				+'ORDER BY CONVERT(VARCHAR(6),DATEADD(MONTH,1,DATEADD(DD,-25,a.addDate)),112) DESC,a.addMan'
	--PRINT @SQL
	EXEC(@SQL)
END
SET NOCOUNT OFF
GO
/****** Object:  StoredProcedure [dbo].[bpSpreadCallLogInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--录音记录Carl
CREATE PROCEDURE [dbo].[bpSpreadCallLogInsert]
(
	@FileName VARCHAR(100),
	@FileMD5 VARCHAR(200),
	@PhoneNo VARCHAR(20),
	@TimeLength SMALLINT,
	@AddMan SMALLINT,
	@AddDate SMALLDATETIME
)
AS
SET NOCOUNT ON
BEGIN
	IF EXISTS (SELECT 'X' FROM SpreadCallLog WITH(NOLOCK) WHERE FileMD5=@FileMD5)
		RETURN 0
		
	INSERT INTO SpreadCallLog([FileName],FileMD5,PhoneNo,TimeLength,AddMan,AddDate) 
	VALUES(@FileName,@FileMD5,@PhoneNo,@TimeLength,@AddMan,@AddDate)

	RETURN 1
END
SET NOCOUNT OFF

GO
/****** Object:  StoredProcedure [dbo].[bpSpreadCallLogSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--推广部录音记录查询 Carl 2018-1-18
CREATE PROCEDURE [dbo].[bpSpreadCallLogSelect]
(
	@WHERE VARCHAR(1000)
)
AS
SET NOCOUNT ON
BEGIN
	SET @WHERE = dbo.SafeSQLBack(@WHERE)
	DECLARE @SQL VARCHAR(2000)
	SET @SQL = 'SELECT a.*, b.Name FROM SpreadCallLog a WITH(NOLOCK), Manageruser b WITH(NOLOCK) WHERE a.AddMan = b.ID' + @WHERE
	EXEC(@SQL)
END
SET NOCOUNT OFF

GO
/****** Object:  StoredProcedure [dbo].[bpSpreadKeywordAssignInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--创建人 Andy
--时间 2015-01-22
--插入一条百度点击关键字
CREATE PROCEDURE [dbo].[bpSpreadKeywordAssignInsert]
(		
	@Keyword NVARCHAR(20),
	@DeptID VARCHAR(200),
	@EndDate DATETIME,
	@AddMan INT,	
	@dcSubsiteId INT,
	@SubSiteUrl VARCHAR(50)	
)
AS
BEGIN
	UPDATE Marketdb..SpreadKeywordAssign
	SET EndDate = GETDATE() - 0.5
	WHERE DeptId IN(SELECT * FROM dbo.fnsplit(@DeptID, ','))
	AND EndDate > GETDATE()

	INSERT INTO Marketdb..SpreadKeywordAssign (Engine, Keyword, DeptId, EndDate, AddMan, AddDate, dcSubsiteId, SubSiteUrl)
	SELECT 1, @Keyword, ID, @EndDate, @AddMan, GETDATE(), @dcSubsiteId, @SubSiteUrl 
	FROM DEPT 
	WHERE id IN(SELECT * FROM dbo.fnsplit(@DeptID, ',')) 
END

GO
/****** Object:  StoredProcedure [dbo].[bpSpreadKeywordAssignSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--创建人 Andy
--时间 2015-01-22
--查询百度点击关键词记录
CREATE PROCEDURE [dbo].[bpSpreadKeywordAssignSelect] 
(		
	@Keyword NVARCHAR(50),
	@Status INT,	
	@DeptID INT
)
AS
BEGIN	
	SET @Keyword = dbo.SafeSql(@Keyword)
	
	DECLARE @SQL VARCHAR(1000)
	SET @SQL = '
		SELECT TOP 500 a.*, b.DeptName 
		FROM MarketDB..SpreadKeywordAssign a, MainDB..Dept b
		WHERE a.DeptId = b.id
		AND EndDate > GETDATE()'   		
	
	IF LEN(@Keyword) > 0
		SET @SQL = @SQL + ' AND a.KeyWord LIKE ''%' + @KeyWord + '%'''			
	IF @Status = 1
		SET @SQL = @SQL + ' AND a.EndDate >= ''' + CONVERT(VARCHAR(10), GETDATE(), 20) + ''''		
	ELSE IF	@Status = 2
		SET @SQL = @SQL + ' AND a.EndDate <= ''' + CONVERT(VARCHAR(10), GETDATE(), 20) + ''''	
	IF @DeptID > 0
		SET @SQL = @SQL + ' And b.ID = ' + LTRIM(STR(@DeptID)) 				
	SET @SQL = @SQL + ' ORDER BY a.AddDate DESC  '
	--PRINT(@SQL)
	EXEC (@SQL)
END
GO
/****** Object:  StoredProcedure [dbo].[bpSpreadKeywordAssignUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--创建人 Andy
--时间 2015-01-22
--更新百度点击关键字的结束时间
CREATE PROCEDURE [dbo].[bpSpreadKeywordAssignUpdate] 
(		
	@IDs VARCHAR(200)
)
AS
BEGIN	
	UPDATE MarketDB..SpreadKeywordAssign 
	SET EndDate = GETDATE() - 1 
	WHERE ID in (SELECT * FROM dbo.fnSplit(@IDS, ','))
END
GO
/****** Object:  StoredProcedure [dbo].[bpSpreadKeywordRefererLogByDeptMonthReportSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--创建人 Andy
--时间 2015-01-08
--按照条件查询部门点击记录统计
CREATE PROCEDURE [dbo].[bpSpreadKeywordRefererLogByDeptMonthReportSelect] 
(		
	@StartDate DATETIME,
	@EndDate DATETIME,
	@Dept INT	
)
AS
BEGIN	
	IF @Dept = 0
		SELECT TOP 500 
			b.ID, 
			b.DeptName , 
			(SELECT COUNT(id) FROM MarketDB..SpreadKeywordRefererLog WHERE LoginType = 1 AND RefererDate < @EndDate AND RefererDate > @StartDate AND ManagerUserID IN (SELECT id FROM ManagerUser WHERE deptID = b.ID)) AS totalNum,  
			(SELECT COUNT(id) FROM MarketDB..SpreadKeywordRefererLog WHERE IsValid = 1 AND LoginType = 1 AND RefererDate< @EndDate AND RefererDate > @StartDate AND ManagerUserID IN(SELECT id FROM ManagerUser WHERE deptid = b.ID)) AS validNum,  
			(SELECT COUNT(id) FROM ManagerUser WHERE deptID = b.ID AND LastLoginDate > @StartDate AND LoginCount > 0 AND Status <> 4) AS workerNum   
		FROM Dept b 
		WHERE Valid = 1
	ELSE
		SELECT TOP 500 
			b.ID, 
			b.DeptName , 
			(SELECT COUNT(id) FROM MarketDB..SpreadKeywordRefererLog WHERE LoginType = 1 AND RefererDate < @EndDate AND RefererDate > @StartDate AND ManagerUserID IN (SELECT id FROM ManagerUser WHERE deptID = b.ID)) AS totalNum,  
			(SELECT COUNT(id) FROM MarketDB..SpreadKeywordRefererLog WHERE IsValid = 1 AND LoginType = 1 AND RefererDate< @EndDate AND RefererDate > @StartDate AND ManagerUserID IN(SELECT id FROM ManagerUser WHERE deptid = b.ID)) AS validNum,  
			(SELECT COUNT(id) FROM ManagerUser WHERE deptID = b.ID AND LastLoginDate > @StartDate AND LoginCount > 0 AND Status <> 4) AS workerNum   
		FROM Dept b 
		WHERE Valid = 1 AND b.ID = @Dept
END
GO
/****** Object:  StoredProcedure [dbo].[bpSpreadKeywordRefererLogByManagerUserMonthReportSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--创建人 Andy
--时间 2015-01-08
--按照条件查询个人月度点击记录统计
CREATE PROCEDURE [dbo].[bpSpreadKeywordRefererLogByManagerUserMonthReportSelect] 
(		
	@StartDate VARCHAR(20),
	@EndDate VARCHAR(20),
	@ManagerUserID INT,
	@Where VARCHAR(1000)	
)
AS
BEGIN
	DECLARE @SQL VARCHAR(1000)
	IF @ManagerUserID = 0
		BEGIN
			SET @SQL='SELECT ManagerUserID, COUNT(*) AllNumber 
			FROM MarketDB..SpreadKeywordRefererLog 
			WHERE IsValid = 1 
			AND LoginType = 1
			AND RefererDate < '''+@EndDate+ '''' +
			' AND RefererDate > '''+@StartDate +''' ' + @Where +
			' GROUP BY ManagerUserID
			ORDER BY ManagerUserID'
		END
	ELSE
		BEGIN
			SET @SQL='SELECT ManagerUserID, COUNT(*) AllNumber 
			FROM MarketDB..SpreadKeywordRefererLog 
			WHERE IsValid = 1 
			AND LoginType = 1 
			AND RefererDate < '''+@EndDate+ '''' +
			' AND RefererDate > '''+@StartDate +''''+
			' AND ManagerUserId = '+ LTRIM(STR(@ManagerUserID)) +' '+@Where+
			' GROUP BY ManagerUserID
			ORDER BY ManagerUserID'
		END
	print @sql
	EXEC(@SQL)
END

GO
/****** Object:  StoredProcedure [dbo].[bpSpreadKeywordRefererLogByMonthReportSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--创建人 Andy
--时间 2015-01-08
--按照条件统计所有员工点击记录
CREATE PROCEDURE [dbo].[bpSpreadKeywordRefererLogByMonthReportSelect] 
(		
	@StartDate DATETIME,
	@EndDate DATETIME,
	@DeptID INT,	
	@CurManagerUserID INT,--当前登录用户ID		
	@Privi INT--当前用户的权限
)
AS
BEGIN	
	DECLARE @SQL VARCHAR(1000)
	SET @SQL = '
		SELECT TOP 500 
			COUNT(ID) AS Num, 
			KeyWord, 
			ManagerUserID, 			
			SUM(CASE LoginType WHEN 1 THEN 1 ELSE 0 END) AS pcNum,  
			SUM(CASE LoginType WHEN 2 THEN 1 ELSE 0 END) AS cellNum, 
			(SELECT TOP 1 [name] FROM  ManagerUser x WHERE x.ID = a.ManagerUserID) AS ManagerUserName, 
			(SELECT COUNT(id) FROM MarketDB..SpreadKeywordRefererLog WHERE LoginType = 1 AND ManagerUserID = a.ManagerUserID AND KeyWord = a.KeyWord) AS TotalNum  
		FROM MarketDB..SpreadKeywordRefererLog a   
		WHERE IsValid = 1  
		AND a.RefererDate >= ''' + CONVERT(VARCHAR(20), @StartDate, 20) + ''' 
		AND a.RefererDate <= ''' + CONVERT(VARCHAR(20), @EndDate, 20) + ''''
	
	IF @DeptID > 0
		SET @SQL = @SQL + ' AND ManagerUserID IN(SELECT id FROM ManagerUser WHERE deptid= ' + LTRIM(STR(@DeptID)) + ')'		
	--权限
	SET @SQL = @SQL + ' AND a.ManagerUserId IN (SELECT ID FROM dbo.LowerUser('+LTRIM(STR(@CurManagerUserID)) + ',' + LTRIM(STR(@Privi)) + '))'	
	SET @SQL = @SQL + ' GROUP BY KeyWord, ManagerUserID, CONVERT(VARCHAR(7), RefererDate, 120)' 
	SET @SQL = @SQL + ' ORDER BY ManagerUserID DESC '
	--PRINT(@SQL)
	EXEC (@SQL)
END
GO
/****** Object:  StoredProcedure [dbo].[bpSpreadKeywordRefererLogSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--创建人 Andy
--时间 2015-01-23
--按照条件查询员工点击记录
--修改：2015-01-23 修改@IsValid取值不正确的bug
CREATE PROCEDURE [dbo].[bpSpreadKeywordRefererLogSelect]
(		
	@StartDate DATETIME,
	@EndDate DATETIME,
	@ManagerUserID INT,
	@KeyWord NVARCHAR(50),
	@LoginType INT,
	@IsValid INT,
	@IsMore2Valid INT,	
	@CurManagerUserID INT,--当前登录用户ID		
	@Privi INT--当前用户的权限
)
AS
SET NOCOUNT ON
BEGIN	
	DECLARE @SQL VARCHAR(1000)
	SET @SQL = '
		SELECT TOP 500 a.*, b.Name as ManagerUserName, c.SubSiteName 
		FROM MarketDB..SpreadKeywordRefererLog a, ManagerUser b, Maindb..ViewSubSite c 
		WHERE a.ManagerUserID = b.id AND a.dcSubSiteId = c.ID  
		AND a.RefererDate >= ''' + CONVERT(VARCHAR(20), @StartDate, 20) + ''' 
		AND a.RefererDate <= ''' + CONVERT(VARCHAR(20), @EndDate, 20) + ''''
	
	IF @ManagerUserID > 0
		SET @SQL = @SQL + ' AND a.ManagerUserId = ' + LTRIM(STR(@ManagerUserID))		
	IF len(@KeyWord) > 0
		SET @SQL = @SQL + ' AND a.KeyWord LIKE ''%' + @KeyWord + '%'''			
	IF @LoginType > 0 
		SET @SQL = @SQL + ' AND a.LoginType = ' + LTRIM(STR(@LoginType))
	IF @IsValid >= 0 
		SET @SQL = @SQL + ' AND a.IsValid = ' + LTRIM(STR(@IsValid))
	IF @IsMore2Valid > 0
		SET @SQL = @SQL + ' AND a.IsMore2Valid = ' + LTRIM(STR(@IsMore2Valid))		
	--权限
	SET @SQL = @SQL + ' AND a.ManagerUserId IN (SELECT ID FROM dbo.LowerUser('+LTRIM(STR(@CurManagerUserID)) + ',' + LTRIM(STR(@Privi)) + '))'	
	SET @SQL = @SQL + ' ORDER BY RefererDate DESC'
	--PRINT(@SQL)
	EXEC (@SQL)
END

GO
/****** Object:  StoredProcedure [dbo].[bpToolRunLogSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--创建人 Andy
--时间 2014-12-30
--按照条件查询ToolRunLog表
CREATE PROCEDURE [dbo].[bpToolRunLogSelect]
(	
	@Type INT,
	@Status INT
)
AS
BEGIN	
	SELECT TOP 100 *
	FROM ToolRunLog WITH(NOLOCK)
	WHERE ToolType = @Type
	AND RunStatus = @Status		
END

GO
/****** Object:  StoredProcedure [dbo].[bpUrlByIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[bpUrlByIDSelect]
(
	@ID INT
)
AS
BEGIN
	SELECT * FROM Url WITH(NOLOCK) WHERE ID = @ID
END

GO
/****** Object:  StoredProcedure [dbo].[bpUrlByListSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[bpUrlByListSelect]
(
	@Where VARCHAR(2000),
	@Order VARCHAR(1000)
)
AS
BEGIN
	DECLARE @SQL AS VARCHAR(MAX)
	SET @SQL = '
	select type,province_id,a.id,description,url,allclick,todayclick,yestodayclick,allresume,todayresume,yestodayresume,allcompany,
		todaycompany,yestodaycompany,begindate,(allresume*100/(allclick+1)) o7,(todayresume*100/(todayclick+1)) o8,(allcompany*100/(allclick+1)) o9,
		(todaycompany*100/(todayclick+1)) o10,status,ip_repeat,addman,b.*
	from url a with(nolock) left join dcProvince b with(nolock) on a.province_Id = b.ID where 1=1
	' + @Where + @Order
	EXEC(@SQL)
END


GO
/****** Object:  StoredProcedure [dbo].[bpUrlClickLogByAddDateGroupSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[bpUrlClickLogByAddDateGroupSelect]
(
	@UrlID INT
)
AS
BEGIN
	SELECT a.id,a.description,YEAR(adddate)*10000 + MONTH(adddate)*100 + DAY(adddate) daily,COUNT(1) cnt 
	FROM url_click_log b WITH(NOLOCK),url a WITH(NOLOCK) 
	WHERE b.url_id=a.id 
	AND a.id=@UrlID 
	GROUP BY a.id,a.description, YEAR(adddate)*10000 + MONTH(adddate)*100 + DAY(adddate) 
	ORDER BY YEAR(adddate)*10000 + MONTH(adddate)*100 + DAY(adddate) 
END

GO
/****** Object:  StoredProcedure [dbo].[bpUrlClickLogByUrlIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[bpUrlClickLogByUrlIDSelect]
(
	@UrlID INT
)
AS
BEGIN
	SELECT ip,adddate FROM url_click_log WITH(NOLOCK) WHERE url_id = @UrlID ORDER BY AddDate DESC
END

GO
/****** Object:  StoredProcedure [dbo].[bpUrlDelete]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[bpUrlDelete]
(
	@ID INT
)
AS
BEGIN
	DELETE FROM Url WHERE ID = @ID
END

GO
/****** Object:  StoredProcedure [dbo].[bpUrlMonthByUrlIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[bpUrlMonthByUrlIDSelect]
(
	@UrlID INT
)
AS
BEGIN
	SELECT id,click,resume,month,company FROM url_month WITH(NOLOCK) WHERE url_id=@UrlID ORDER BY month DESC
END

GO
/****** Object:  StoredProcedure [dbo].[bpUrlMonthByYearMonthSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[bpUrlMonthByYearMonthSelect]
(
	@dcProvinceID SMALLINT,
	@YearMonth VARCHAR(10)
)
AS
BEGIN
	SELECT a.click,a.resume,a.company,b.description,b.url,b.id
	FROM url_month a WITH(NOLOCK),url b WITH(NOLOCK) 
	WHERE a.url_id = b.id 
	AND a.month = @YearMonth 
	AND b.province_id = @dcProvinceID
	ORDER BY b.id
END

GO
/****** Object:  StoredProcedure [dbo].[bpUrlSave]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[bpUrlSave]
(
	@ID INT,
	@Description VARCHAR(200),
	@Url VARCHAR(200),
	@Type TINYINT,
	@Status BIT,
	@IpRepeat TINYINT,
	@dcProvinceID SMALLINT,
	@ManageruserID SMALLINT
)
AS
BEGIN
	IF @ID = 0
	BEGIN
		INSERT INTO url (description,url,province_id,type,ip_repeat,addman,status) VALUES(
			@Description,@Url,@dcProvinceID,@Type,@IpRepeat,@ManageruserID,@Status)
	END
	ELSE
	BEGIN
		UPDATE url SET description = @Description,url = @Url,type = @Type,ip_repeat = @IpRepeat,status = @Status
		WHERE ID = @ID
	END
END

GO
/****** Object:  StoredProcedure [dbo].[bpUserActionCountInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--创建人 Harry
--时间 2016-2-29 
--useractioncount数据插入
--修改：peter 2016-07-12加入注册方式以及来源统计
--修改：Peter 2016-09-28加入新版你的菜儿一些数据统计
--修改：Peter 2016-10-10加入一些企业简历交互数据统计
--修改：Lucifer 2017-2-22 加入M站相关统计
CREATE PROCEDURE [dbo].[bpUserActionCountInsert]
(
	@Date DATETIME
)
AS
SET NOCOUNT ON
BEGIN 
	DECLARE @YearMonthDay VARCHAR(8), @BeginDate DATETIME, @EndDate DATETIME
	SELECT @YearMonthDay = CONVERT(VARCHAR(8), @Date - 1, 112),
		@BeginDate = CONVERT(VARCHAR(8), @Date - 1, 112),
		@EndDate = CONVERT(VARCHAR(8), @Date, 112)

	DELETE LogDb..UserActionCount WHERE CountDate = @YearMonthDay

	--1 申请职位数量
	INSERT INTO LogDb..UserActionCount(CountDate, dcSubSiteId, ActionType, ActionNumber) 
	SELECT @YearMonthDay, LEFT(b.dcRegionId, 2), 1, COUNT(1) 
	FROM exjobApply A WITH(NOLOCK), JOb b WITH(NOLOCK) 
	WHERE a.AddDate >= @BeginDate
	AND a.AddDate < @EndDate
	AND a.JobId = b.Id
	GROUP BY LEFT(b.dcRegionId, 2)

	--3申请职位回复通过数量
	INSERT INTO LogDb..UserActionCount (CountDate, dcSubSiteId, ActionType, ActionNumber) 
	SELECT @YearMonthDay, LEFT(b.dcRegionId, 2), 3, COUNT(1) 
	FROM exJobApply A WITH(NOLOCK), JOB b WITH(NOLOCK) 
	WHERE a.ReplyDate >= @BeginDate
	AND a.ReplyDate < @EndDate
	AND A.Reply = 1 
	AND a.JobId = b.Id
	GROUP BY LEFT(b.dcRegionId, 2)

	--4申请职位未通过数量	
	INSERT INTO LogDb..UserActionCount (CountDate, dcSubSiteId, ActionType, ActionNumber)
	SELECT @YearMonthDay, LEFT(b.dcRegionId, 2), 4, COUNT(1) 
	FROM exJobApply A WITH(NOLOCK), JOB b WITH(NOLOCK) 
	WHERE a.ReplyDate > @BeginDate
	AND a.ReplyDate < @EndDate
	AND a.JobId = b.Id
	AND A.Reply > 1 
	GROUP BY LEFT(b.dcRegionId, 2)

	--5点击订单页面数量
	INSERT INTO LogDb..UserActionCount (CountDate, dcSubSiteId, ActionType, ActionNumber) 
	SELECT @YearMonthDay, LEFT(c.dcProvinceID, 2), 5, COUNT(1)
	FROM cafeepageviewlog a WITH(NOLOCK), CaMain b WITH(NOLOCK), CpMain c WITH(NOLOCK) 
	WHERE a.AddDate >= @BeginDate
	AND a.AddDate < @EndDate
	AND a.CaMainID = b.Id 
	AND b.cpMainId = c.Id
	GROUP BY LEFT(c.dcProvinceID, 2)

	--6企业收藏数量
	INSERT INTO LogDb..UserActionCount(CountDate, dcSubSiteId, ActionType, ActionNumber) 
	SELECT @YearMonthDay, LEFT(b.dcRegionID, 2), 6, COUNT(1)
	FROM paFavorate a WITH(NOLOCK), job b WITH(NOLOCK) 
	WHERE a.AddDate >= @BeginDate
	AND a.AddDate < @EndDate
	AND a.JobID = b.Id 
	GROUP BY LEFT(b.dcRegionID, 2)

 	--7个人收藏数量
	INSERT INTO LogDb..UserActionCount (CountDate, dcSubSiteId, ActionType, ActionNumber) 
	SELECT @YearMonthDay, LEFT(b.dcProvinceID, 2), 7, COUNT(1)
	FROM paAttention a WITH(NOLOCK), paMain b WITH(NOLOCK) 
	WHERE a.AddDate >= @BeginDate
	AND a.AddDate < @EndDate
	AND a.PaMainID = b.Id 
	GROUP BY LEFT(b.dcProvinceID, 2)

	--8企业取回密码数量
	INSERT INTO LogDb..UserActionCount (CountDate, dcSubSiteId, ActionType, ActionNumber) 
	SELECT @YearMonthDay, LEFT(c.dcProvinceID, 2), 8, COUNT(1)
	FROM caGetPasswordLog a WITH(NOLOCK), CaMain b WITH(NOLOCK), CpMain c WITH(NOLOCK) 
	WHERE a.AddDate >= @BeginDate
	AND a.AddDate < @EndDate
	AND a.CaMainID = b.Id 
	AND b.cpMainId = c.Id
	GROUP BY LEFT(c.dcProvinceID, 2)

	--9个人取回密码数量
	INSERT INTO LogDb..UserActionCount (CountDate, dcSubSiteId, ActionType, ActionNumber) 
	SELECT @YearMonthDay, LEFT(b.dcProvinceID, 2), 9, COUNT(1)
	FROM paGetPasswordLog a WITH(NOLOCK), paMain b WITH(NOLOCK)
	WHERE a.AddDate >= @BeginDate   
	AND a.AddDate < @EndDate
	AND a.paMainID = b.Id 
	GROUP BY LEFT(b.dcProvinceID, 2)

	--10邮件发送数量
	INSERT INTO LogDb..UserActionCount (CountDate, dcSubSiteId, ActionType, ActionNumber) 
	SELECT @YearMonthDay, b.Id, 10, COUNT(1)
	FROM msEmailSend a WITH(NOLOCK), dcProvince b WITH(NOLOCK)
	WHERE (a.Host = 'mail.' + b.ProvinceDomain
		OR a.Host = 'mail2.' + b.ProvinceDomain
		OR a.Host = 'mail3.' + b.ProvinceDomain)
	AND a.AddDate >= @BeginDate   
	AND a.AddDate < @EndDate
	GROUP BY b.Id

	--11短信发送数量-不区分省份
	INSERT INTO LogDb..UserActionCount (CountDate, dcSubSiteId, ActionType, ActionNumber) 
	SELECT @YearMonthDay, 0, 11, COUNT(1)
	FROM SmsMessageLog a WITH(NOLOCK) 
	WHERE a.SendDate >= @BeginDate
	AND a.SendDate < @EndDate
	
	--12微信发送数量
	INSERT INTO LogDb..UserActionCount (CountDate, dcSubSiteId, ActionType, ActionNumber) 
	SELECT @YearMonthDay, ProvinceID, 12, COUNT(1)
	FROM wxMessageSend2 a WITH(NOLOCK), wxFans b WITH(NOLOCK), wxServiceNo c WITH(NOLOCK) 
	WHERE a.SendDate >= @BeginDate 
	AND a.SendDate < @EndDate
	AND a.WxFansID = b.id 
	AND b.wxServiceNoId = c.Id
	GROUP BY c.ProvinceID

	--13上传照片数量 
	INSERT INTO LogDb..UserActionCount (CountDate, dcSubSiteId, ActionType, ActionNumber) 
	SELECT @YearMonthDay, b.dcProvinceID, 13, COUNT(1)
	FROM paPhoto a WITH(NOLOCK), paMain b WITH(NOLOCK) 
	WHERE a.paMainId = b.Id
	AND a.AddDate >= @BeginDate
	AND a.AddDate < @EndDate
	GROUP BY b.dcProvinceID

	--14形象图数量
	INSERT INTO LogDb..UserActionCount (CountDate, dcSubSiteId, ActionType, ActionNumber) 
	SELECT @YearMonthDay, c.dcProvinceID, 14, COUNT(1)
	FROM cpImage a WITH(NOLOCK), cpMain c WITH(NOLOCK) 
	WHERE a.AddDate >= @BeginDate
	AND a.AddDate < @EndDate
	AND a.cpMainId = c.ID 
	AND a.ImgType = 2
	GROUP BY c.dcProvinceID

	--15LOGO数量
	INSERT INTO LogDb..UserActionCount (CountDate, dcSubSiteId, ActionType, ActionNumber) 
	SELECT @YearMonthDay, c.dcProvinceID, 15, COUNT(1)
	FROM cpImage a WITH(NOLOCK), cpMain c WITH(NOLOCK) 
	WHERE a.AddDate >= @BeginDate
	AND a.AddDate < @EndDate
	AND a.cpMainId = c.ID 
	AND a.ImgType = 1
	GROUP BY c.dcProvinceID

	--16环境图数量
	INSERT INTO LogDb..UserActionCount (CountDate, dcSubSiteId, ActionType, ActionNumber) 
	SELECT @YearMonthDay, b.dcProvinceID, 16, COUNT(1)
	FROM cpImage a WITH(NOLOCK), cpMain b WITH(NOLOCK) 
	WHERE a.AddDate >= @BeginDate
	AND a.AddDate < @EndDate
	AND a.cpMainId = b.ID 
	AND a.ImgType = 3
	GROUP BY b.dcProvinceID

	--17面试通知数量
	INSERT INTO LogDb..UserActionCount (CountDate, dcSubSiteId, ActionType, ActionNumber) 
	SELECT @YearMonthDay, LEFT(b.dcRegionID, 2), 17, COUNT(1)
	FROM exInterview a WITH(NOLOCK), job b WITH(NOLOCK) 
	WHERE a.AddDate >= @BeginDate
	AND a.AddDate < @EndDate
	AND a.jobId = b.Id 
	GROUP BY LEFT(b.dcRegionID, 2)

	--18面试回复数量
	INSERT INTO LogDb..UserActionCount (CountDate, dcSubSiteId, ActionType, ActionNumber) 
	SELECT @YearMonthDay, LEFT(b.dcRegionID, 2), 18, COUNT(1)
	FROM exInterview a WITH(NOLOCK), job b WITH(NOLOCK) 
	WHERE a.ReplyDate >= @BeginDate 
	AND a.ReplyDate < @EndDate
	AND a.jobId = b.Id 
	GROUP BY LEFT(b.dcRegionID, 2)

	--19查看职位数量
	INSERT INTO LogDb..UserActionCount (CountDate, dcSubSiteId, ActionType, ActionNumber) 
	SELECT @YearMonthDay, LEFT(b.dcRegionID, 2), 19, COUNT(1)
	FROM pajobviewLog a WITH(NOLOCK), job b WITH(NOLOCK) 
	WHERE a.AddDate >= @BeginDate 
	AND a.AddDate < @EndDate
	AND a.jobId = b.Id 
	GROUP BY LEFT(b.dcRegionID, 2)

	--20查看简历数量
	INSERT INTO LogDb..UserActionCount (CountDate, dcSubSiteId, ActionType, ActionNumber) 
	SELECT @YearMonthDay, LEFT(c.dcRegionID, 2), 20, COUNT(1)
	FROM caCvViewLog a WITH(NOLOCK), caMain b WITH(NOLOCK), cpMain c WITH(NOLOCK) 
	WHERE a.AddDate >= @BeginDate
	AND a.AddDate < @EndDate
	AND a.caMainId = b.Id 
	AND b.cpMainid = c.ID 
	GROUP BY LEFT(c.dcRegionID, 2)

	--21你的菜 yourfood 
	INSERT INTO LogDb..UserActionCount (CountDate, dcSubSiteId, ActionType, ActionNumber) 
	SELECT @YearMonthDay, LEFT(b.dcProvinceID, 2), 21, COUNT(1)
	FROM payourfood a WITH(NOLOCK), paMain b WITH(NOLOCK) 
	WHERE a.AddDate >= @BeginDate
	AND a.AddDate < @EndDate
	AND a.paMainId = b.Id 
	GROUP BY LEFT(b.dcProvinceID, 2)

	--22你的菜微信	
	INSERT INTO LogDb..UserActionCount (CountDate, dcSubSiteId, ActionType, ActionNumber) 
	SELECT @YearMonthDay, ProvinceID, 22, COUNT(1)
	FROM wxMessageSend2 a WITH(NOLOCK), wxFans b WITH(NOLOCK), wxServiceNo c WITH(NOLOCK) 
	WHERE a.SendDate >= @BeginDate 
	AND a.SendDate < @EndDate
	AND a.WxFansID = b.id 
	AND b.wxServiceNoId = c.Id
	AND a.Templatetype=13
	GROUP BY c.ProvinceID


	--23个人推送 papushlog
	INSERT INTO LogDb..UserActionCount (CountDate, dcSubSiteId, ActionType, ActionNumber)
	SELECT @YearMonthDay, LEFT(b.dcProvinceID, 2), 23, COUNT(1)
	FROM paPushlog a WITH(NOLOCK), paMain b WITH(NOLOCK) 
	WHERE a.AddDate >= @BeginDate
	AND a.AddDate < @EndDate
	AND a.paMainId = b.Id 
	GROUP BY LEFT(b.dcProvinceID, 2)
	
	--24微信关注数量
	INSERT INTO LogDb..UserActionCount (CountDate, dcSubSiteId, ActionType, ActionNumber)
	SELECT @YearMonthDay, b.ProvinceID, 24, COUNT(1)
	FROM wxFans a WITH(NOLOCK), WxServiceNo b WITH(NOLOCK) WHERE a.WxServiceNoID = b.ID AND a.Status > 0
	GROUP BY b.ProvinceID
	
	--25微信取消关注数量
	INSERT INTO LogDb..UserActionCount (CountDate, dcSubSiteId, ActionType, ActionNumber)
	SELECT @YearMonthDay, b.ProvinceID, 25, COUNT(1)
	FROM wxFans a WITH(NOLOCK), WxServiceNo b WITH(NOLOCK) WHERE a.WxServiceNoID = b.ID AND a.Status = 0
	GROUP BY b.ProvinceID

	--26微信个人绑定数量
	INSERT INTO LogDb..UserActionCount (CountDate, dcSubSiteId, ActionType, ActionNumber)
	SELECT @YearMonthDay, b.ProvinceID, 26, COUNT(1)
	FROM wxFans a WITH(NOLOCK), WxServiceNo b WITH(NOLOCK)
	WHERE a.WxServiceNoID = b.ID AND a.Status = 2
	GROUP BY b.ProvinceID

	--27微信个人取消绑定数量
	INSERT INTO LogDb..UserActionCount (CountDate, dcSubSiteId, ActionType, ActionNumber)
	SELECT @YearMonthDay, b.ProvinceID, 27, COUNT(1)
	FROM wxFans a WITH(NOLOCK), WxServiceNo b WITH(NOLOCK)
	WHERE a.WxServiceNoID = b.ID AND a.Status = 1 AND a.paMainID IS NOT NULL
	GROUP BY b.ProvinceID

	--28微信企业绑定数量
	INSERT INTO LogDb..UserActionCount (CountDate, dcSubSiteId, ActionType, ActionNumber)
	SELECT @YearMonthDay, b.ProvinceID, 28, COUNT(1)
	FROM wxFans a WITH(NOLOCK), WxServiceNo b WITH(NOLOCK)
	WHERE a.WxServiceNoID = b.ID AND a.caMainID IS NOT NULL AND a.caBindCancelDate IS NULL
	GROUP BY b.ProvinceID

	--29微信企业取消绑定数量
	INSERT INTO LogDb..UserActionCount (CountDate, dcSubSiteId, ActionType, ActionNumber)
	SELECT @YearMonthDay, b.ProvinceID, 29, COUNT(1)
	FROM wxFans a WITH(NOLOCK), WxServiceNo b WITH(NOLOCK)
	WHERE a.WxServiceNoID = b.ID AND a.caMainID IS NOT NULL AND a.caBindCancelDate IS NOT NULL
	GROUP BY b.ProvinceID
	
	--30PC注册总数量
	INSERT INTO LogDb..UserActionCount (CountDate, dcSubSiteId, ActionType, ActionNumber)
	SELECT @YearMonthDay, dcProvinceID, 30, COUNT(1)
	FROM PaMain WITH(NOLOCK)
	WHERE RegisterFrom = 1 
	AND AddDate >= @BeginDate
	AND AddDate < @EndDate
	GROUP BY dcProvinceID
	
	--31 M注册总数量
	INSERT INTO LogDb..UserActionCount (CountDate, dcSubSiteId, ActionType, ActionNumber)
	SELECT @YearMonthDay, dcProvinceID, 31, COUNT(1)
	FROM PaMain WITH(NOLOCK)
	WHERE RegisterFrom = 4 
	AND AddDate >= @BeginDate
	AND AddDate < @EndDate
	GROUP BY dcProvinceID
	
	--32 AndroidApp注册总数量
	INSERT INTO LogDb..UserActionCount (CountDate, dcSubSiteId, ActionType, ActionNumber)
	SELECT @YearMonthDay, dcProvinceID, 32, COUNT(1)
	FROM PaMain WITH(NOLOCK)
	WHERE RegisterFrom = 2 
	AND AddDate >= @BeginDate
	AND AddDate < @EndDate
	GROUP BY dcProvinceID
	
	--33 IOS App注册总数量
	INSERT INTO LogDb..UserActionCount (CountDate, dcSubSiteId, ActionType, ActionNumber)
	SELECT @YearMonthDay, dcProvinceID, 33, COUNT(1)
	FROM PaMain WITH(NOLOCK)
	WHERE RegisterFrom = 3 
	AND AddDate >= @BeginDate
	AND AddDate < @EndDate
	GROUP BY dcProvinceID
	
	--34 微信注册总数量
	INSERT INTO LogDb..UserActionCount (CountDate, dcSubSiteId, ActionType, ActionNumber)
	SELECT @YearMonthDay, dcProvinceID, 34, COUNT(1)
	FROM PaMain WITH(NOLOCK)
	WHERE RegisterFrom = 5 
	AND AddDate >= @BeginDate
	AND AddDate < @EndDate
	GROUP BY dcProvinceID
	
	--35  pcEmail注册总数量
	INSERT INTO LogDb..UserActionCount (CountDate, dcSubSiteId, ActionType, ActionNumber)
	SELECT @YearMonthDay, dcProvinceID, 35, COUNT(1)
	FROM PaMain WITH(NOLOCK)
	WHERE RegisterFrom = 1
	AND RegisterType = 1
	AND AddDate >= @BeginDate
	AND AddDate < @EndDate
	GROUP BY dcProvinceID
	
	--36  pc手机注册总数量
	INSERT INTO LogDb..UserActionCount (CountDate, dcSubSiteId, ActionType, ActionNumber)
	SELECT @YearMonthDay, dcProvinceID, 36, COUNT(1)
	FROM PaMain WITH(NOLOCK)
	WHERE RegisterFrom = 1
	AND RegisterType = 2
	AND AddDate >= @BeginDate
	AND AddDate < @EndDate
	GROUP BY dcProvinceID
	
	--37  pc微信注册总数量
	INSERT INTO LogDb..UserActionCount (CountDate, dcSubSiteId, ActionType, ActionNumber)
	SELECT @YearMonthDay, dcProvinceID, 37, COUNT(1)
	FROM PaMain WITH(NOLOCK)
	WHERE RegisterFrom = 1
	AND RegisterType = 4
	AND AddDate >= @BeginDate
	AND AddDate < @EndDate
	GROUP BY dcProvinceID
	
	--38  pcQQ注册总数量
	INSERT INTO LogDb..UserActionCount (CountDate, dcSubSiteId, ActionType, ActionNumber)
	SELECT @YearMonthDay, dcProvinceID, 38, COUNT(1)
	FROM PaMain WITH(NOLOCK)
	WHERE RegisterFrom = 1
	AND RegisterType = 3
	AND AddDate >= @BeginDate
	AND AddDate < @EndDate
	GROUP BY dcProvinceID
	
	--39  pc微博注册总数量
	INSERT INTO LogDb..UserActionCount (CountDate, dcSubSiteId, ActionType, ActionNumber)
	SELECT @YearMonthDay, dcProvinceID, 39, COUNT(1)
	FROM PaMain WITH(NOLOCK)
	WHERE RegisterFrom = 1
	AND RegisterType = 5
	AND AddDate >= @BeginDate
	AND AddDate < @EndDate
	GROUP BY dcProvinceID
	
	--40  pc人人注册总数量
	INSERT INTO LogDb..UserActionCount (CountDate, dcSubSiteId, ActionType, ActionNumber)
	SELECT @YearMonthDay, dcProvinceID, 40, COUNT(1)
	FROM PaMain WITH(NOLOCK)
	WHERE RegisterFrom = 1
	AND RegisterType = 6
	AND AddDate >= @BeginDate
	AND AddDate < @EndDate
	GROUP BY dcProvinceID
	
	--41  pc百度注册总数量
	INSERT INTO LogDb..UserActionCount (CountDate, dcSubSiteId, ActionType, ActionNumber)
	SELECT @YearMonthDay, dcProvinceID, 41, COUNT(1)
	FROM PaMain WITH(NOLOCK)
	WHERE RegisterFrom = 1
	AND RegisterType = 7
	AND AddDate >= @BeginDate
	AND AddDate < @EndDate
	GROUP BY dcProvinceID
	
	--42  pc一分钟填写简历总数量
	INSERT INTO LogDb..UserActionCount (CountDate, dcSubSiteId, ActionType, ActionNumber)
	SELECT @YearMonthDay, dcProvinceID, 42, COUNT(1)
	FROM PaMain WITH(NOLOCK)
	WHERE RegisterFrom = 1
	AND RegisterType = 8
	AND AddDate >= @BeginDate
	AND AddDate < @EndDate
	GROUP BY dcProvinceID
	
	--43  pc申请职位生成简历总数量
	INSERT INTO LogDb..UserActionCount (CountDate, dcSubSiteId, ActionType, ActionNumber)
	SELECT @YearMonthDay, dcProvinceID, 43, COUNT(1)
	FROM PaMain WITH(NOLOCK)
	WHERE RegisterFrom = 1
	AND RegisterType = 9
	AND AddDate >= @BeginDate
	AND AddDate < @EndDate
	GROUP BY dcProvinceID
	
	--44  pc上传word简历总数量
	INSERT INTO LogDb..UserActionCount (CountDate, dcSubSiteId, ActionType, ActionNumber)
	SELECT @YearMonthDay, dcProvinceID, 44, COUNT(1)
	FROM PaMain WITH(NOLOCK)
	WHERE RegisterFrom = 1
	AND RegisterType = 10
	AND AddDate >= @BeginDate
	AND AddDate < @EndDate
	GROUP BY dcProvinceID
	
	--45  M站一分钟填写简历总数量
	INSERT INTO LogDb..UserActionCount (CountDate, dcSubSiteId, ActionType, ActionNumber)
	SELECT @YearMonthDay, dcProvinceID, 45, COUNT(1)
	FROM PaMain WITH(NOLOCK)
	WHERE RegisterFrom = 4
	AND RegisterType = 8
	AND AddDate >= @BeginDate
	AND AddDate < @EndDate
	GROUP BY dcProvinceID
	
	--46  M站手机号注册总数量
	INSERT INTO LogDb..UserActionCount (CountDate, dcSubSiteId, ActionType, ActionNumber)
	SELECT @YearMonthDay, dcProvinceID, 46, COUNT(1)
	FROM PaMain WITH(NOLOCK)
	WHERE RegisterFrom = 4
	AND RegisterType = 2
	AND AddDate >= @BeginDate
	AND AddDate < @EndDate
	GROUP BY dcProvinceID
	
	--47  M站邮箱注册总数量
	INSERT INTO LogDb..UserActionCount (CountDate, dcSubSiteId, ActionType, ActionNumber)
	SELECT @YearMonthDay, dcProvinceID, 47, COUNT(1)
	FROM PaMain WITH(NOLOCK)
	WHERE RegisterFrom = 4
	AND RegisterType = 1
	AND AddDate >= @BeginDate
	AND AddDate < @EndDate
	GROUP BY dcProvinceID
	
	--48  M站QQ注册总数量
	INSERT INTO LogDb..UserActionCount (CountDate, dcSubSiteId, ActionType, ActionNumber)
	SELECT @YearMonthDay, dcProvinceID, 48, COUNT(1)
	FROM PaMain WITH(NOLOCK)
	WHERE RegisterFrom = 4
	AND RegisterType = 3
	AND AddDate >= @BeginDate
	AND AddDate < @EndDate
	GROUP BY dcProvinceID
	
	--49  M站新浪注册总数量
	INSERT INTO LogDb..UserActionCount (CountDate, dcSubSiteId, ActionType, ActionNumber)
	SELECT @YearMonthDay, dcProvinceID, 49, COUNT(1)
	FROM PaMain WITH(NOLOCK)
	WHERE RegisterFrom = 4
	AND RegisterType = 5
	AND AddDate >= @BeginDate
	AND AddDate < @EndDate
	GROUP BY dcProvinceID
	
	--50  M站百度注册总数量
	INSERT INTO LogDb..UserActionCount (CountDate, dcSubSiteId, ActionType, ActionNumber)
	SELECT @YearMonthDay, dcProvinceID, 50, COUNT(1)
	FROM PaMain WITH(NOLOCK)
	WHERE RegisterFrom = 4
	AND RegisterType = 7
	AND AddDate >= @BeginDate
	AND AddDate < @EndDate
	GROUP BY dcProvinceID
	
	--51  Android App手机号总数量
	INSERT INTO LogDb..UserActionCount (CountDate, dcSubSiteId, ActionType, ActionNumber)
	SELECT @YearMonthDay, dcProvinceID, 51, COUNT(1)
	FROM PaMain WITH(NOLOCK)
	WHERE RegisterFrom = 2
	AND RegisterType = 2
	AND AddDate >= @BeginDate
	AND AddDate < @EndDate
	GROUP BY dcProvinceID
	
	--52  Android App邮箱总数量
	INSERT INTO LogDb..UserActionCount (CountDate, dcSubSiteId, ActionType, ActionNumber)
	SELECT @YearMonthDay, dcProvinceID, 52, COUNT(1)
	FROM PaMain WITH(NOLOCK)
	WHERE RegisterFrom = 2
	AND RegisterType = 1
	AND AddDate >= @BeginDate
	AND AddDate < @EndDate
	GROUP BY dcProvinceID
	
	--53  IOS App邮箱总数量
	INSERT INTO LogDb..UserActionCount (CountDate, dcSubSiteId, ActionType, ActionNumber)
	SELECT @YearMonthDay, dcProvinceID, 53, COUNT(1)
	FROM PaMain WITH(NOLOCK)
	WHERE RegisterFrom = 3
	AND RegisterType = 1
	AND AddDate >= @BeginDate
	AND AddDate < @EndDate
	GROUP BY dcProvinceID
	
	--54  IOS App手机号注册总数量
	INSERT INTO LogDb..UserActionCount (CountDate, dcSubSiteId, ActionType, ActionNumber)
	SELECT @YearMonthDay, dcProvinceID, 54, COUNT(1)
	FROM PaMain WITH(NOLOCK)
	WHERE RegisterFrom = 3
	AND RegisterType = 2
	AND AddDate >= @BeginDate
	AND AddDate < @EndDate
	GROUP BY dcProvinceID
	
	--55  PC 51rc注册总数量
	INSERT INTO LogDb..UserActionCount (CountDate, dcSubSiteId, ActionType, ActionNumber)
	SELECT @YearMonthDay, dcProvinceID, 55, COUNT(1)
	FROM PaMain WITH(NOLOCK)
	WHERE RegisterFrom = 1
	AND RegisterType = 11
	AND AddDate >= @BeginDate
	AND AddDate < @EndDate
	GROUP BY dcProvinceID
	
	--56  信息员邮箱注册，未审核
	INSERT INTO LogDb..UserActionCount (CountDate, dcSubSiteId, ActionType, ActionNumber)
	SELECT @YearMonthDay, dcProvinceID, 56, COUNT(1)
	FROM PaMain WITH(NOLOCK)
	WHERE RegisterType = 101
	AND AddDate >= @BeginDate
	AND AddDate < @EndDate
	GROUP BY dcProvinceID
	
	--57  信息员邮箱注册，已审核
	INSERT INTO LogDb..UserActionCount (CountDate, dcSubSiteId, ActionType, ActionNumber)
	SELECT @YearMonthDay, dcProvinceID, 57, COUNT(1)
	FROM PaMain WITH(NOLOCK)
	WHERE RegisterType = 102
	AND AddDate >= @BeginDate
	AND AddDate < @EndDate
	GROUP BY dcProvinceID
	
	--58  信息员手机号注册，未审核
	INSERT INTO LogDb..UserActionCount (CountDate, dcSubSiteId, ActionType, ActionNumber)
	SELECT @YearMonthDay, dcProvinceID, 58, COUNT(1)
	FROM PaMain a WITH(NOLOCK), bsMobileSpread b WITH(NOLOCK)
	WHERE a.Id = b.RelatedId
	AND b.UserType = 1
	AND b.ReturnDate BETWEEN @BeginDate AND @EndDate
	GROUP BY dcProvinceID
	
	--59  信息员手机号注册 已审核
	INSERT INTO LogDb..UserActionCount (CountDate, dcSubSiteId, ActionType, ActionNumber)
	SELECT @YearMonthDay, dcProvinceID, 59, COUNT(1)
	FROM PaMain a WITH(NOLOCK), bsMobileSpread b WITH(NOLOCK)
	WHERE a.Id = b.RelatedId
	AND b.UserType = 1
	AND b.AccountDate BETWEEN @BeginDate AND @EndDate
	GROUP BY dcProvinceID
	
	--60  招聘会简历
	INSERT INTO LogDb..UserActionCount (CountDate, dcSubSiteId, ActionType, ActionNumber)
	SELECT @YearMonthDay, dcProvinceID, 60, COUNT(1)
	FROM PaMain WITH(NOLOCK)
	WHERE RegisterType = 151
	AND AddDate >= @BeginDate
	AND AddDate < @EndDate
	GROUP BY dcProvinceID
	
	--61  电话简历
	INSERT INTO LogDb..UserActionCount (CountDate, dcSubSiteId, ActionType, ActionNumber)
	SELECT @YearMonthDay, dcProvinceID, 61, COUNT(1)
	FROM PaMain WITH(NOLOCK)
	WHERE RegisterType = 152
	AND AddDate >= @BeginDate
	AND AddDate < @EndDate
	GROUP BY dcProvinceID
	
	--62 首页登录数量
	INSERT INTO LogDb..UserActionCount (CountDate, dcSubSiteId, ActionType, ActionNumber)
	SELECT @YearMonthDay, b.dcProvinceID, 62, COUNT(1)
	FROM PaLoginLog a WITH(NOLOCK)
	LEFT JOIN PaMain b WITH(NOLOCK) ON b.ID = a.PaMainID
	WHERE a.LoginFrom = 11
	AND a.AddDate >= @BeginDate
	AND a.AddDate < @EndDate
	GROUP BY b.dcProvinceID
	
	--63 个人登录页面登录
	INSERT INTO LogDb..UserActionCount (CountDate, dcSubSiteId, ActionType, ActionNumber)
	SELECT @YearMonthDay, b.dcProvinceID, 63, COUNT(1)
	FROM PaLoginLog a WITH(NOLOCK)
	LEFT JOIN PaMain b WITH(NOLOCK) ON b.ID = a.PaMainID
	WHERE a.LoginFrom = 12
	AND a.AddDate >= @BeginDate
	AND a.AddDate < @EndDate
	GROUP BY b.dcProvinceID
	
	--64 内页登录
	INSERT INTO LogDb..UserActionCount (CountDate, dcSubSiteId, ActionType, ActionNumber)
	SELECT @YearMonthDay, b.dcProvinceID, 64, COUNT(1)
	FROM PaLoginLog a WITH(NOLOCK)
	LEFT JOIN PaMain b WITH(NOLOCK) ON b.ID = a.PaMainID
	WHERE a.LoginFrom = 13
	AND a.AddDate >= @BeginDate
	AND a.AddDate < @EndDate
	GROUP BY b.dcProvinceID
	
	--65 前台qq登录
	INSERT INTO LogDb..UserActionCount (CountDate, dcSubSiteId, ActionType, ActionNumber)
	SELECT @YearMonthDay, b.dcProvinceID, 65, COUNT(1)
	FROM PaLoginLog a WITH(NOLOCK)
	LEFT JOIN PaMain b WITH(NOLOCK) ON b.ID = a.PaMainID
	WHERE a.LoginFrom = 14
	AND a.AddDate >= @BeginDate
	AND a.AddDate < @EndDate
	GROUP BY b.dcProvinceID
	
	--66 前台新浪微博登录
	INSERT INTO LogDb..UserActionCount (CountDate, dcSubSiteId, ActionType, ActionNumber)
	SELECT @YearMonthDay, b.dcProvinceID, 66, COUNT(1)
	FROM PaLoginLog a WITH(NOLOCK)
	LEFT JOIN PaMain b WITH(NOLOCK) ON b.ID = a.PaMainID
	WHERE a.LoginFrom = 15
	AND a.AddDate >= @BeginDate
	AND a.AddDate < @EndDate
	GROUP BY b.dcProvinceID
	
	--67 前台人人登录
	INSERT INTO LogDb..UserActionCount (CountDate, dcSubSiteId, ActionType, ActionNumber)
	SELECT @YearMonthDay, b.dcProvinceID, 67, COUNT(1)
	FROM PaLoginLog a WITH(NOLOCK)
	LEFT JOIN PaMain b WITH(NOLOCK) ON b.ID = a.PaMainID
	WHERE a.LoginFrom = 16
	AND a.AddDate >= @BeginDate
	AND a.AddDate < @EndDate
	GROUP BY b.dcProvinceID
	
	--68 前台百度登录
	INSERT INTO LogDb..UserActionCount (CountDate, dcSubSiteId, ActionType, ActionNumber)
	SELECT @YearMonthDay, b.dcProvinceID, 68, COUNT(1)
	FROM PaLoginLog a WITH(NOLOCK)
	LEFT JOIN PaMain b WITH(NOLOCK) ON b.ID = a.PaMainID
	WHERE a.LoginFrom = 17
	AND a.AddDate >= @BeginDate
	AND a.AddDate < @EndDate
	GROUP BY b.dcProvinceID
	
	--69 前台51rc登录
	INSERT INTO LogDb..UserActionCount (CountDate, dcSubSiteId, ActionType, ActionNumber)
	SELECT @YearMonthDay, b.dcProvinceID, 69, COUNT(1)
	FROM PaLoginLog a WITH(NOLOCK)
	LEFT JOIN PaMain b WITH(NOLOCK) ON b.ID = a.PaMainID
	WHERE a.LoginFrom = 18
	AND a.AddDate >= @BeginDate
	AND a.AddDate < @EndDate
	GROUP BY b.dcProvinceID
	
	--70 M站正常登录
	INSERT INTO LogDb..UserActionCount (CountDate, dcSubSiteId, ActionType, ActionNumber)
	SELECT @YearMonthDay, b.dcProvinceID, 70, COUNT(1)
	FROM PaLoginLog a WITH(NOLOCK)
	LEFT JOIN PaMain b WITH(NOLOCK) ON b.ID = a.PaMainID
	WHERE a.LoginFrom = 41
	AND a.AddDate >= @BeginDate
	AND a.AddDate < @EndDate
	GROUP BY b.dcProvinceID
	
	--71 M站QQ登录
	INSERT INTO LogDb..UserActionCount (CountDate, dcSubSiteId, ActionType, ActionNumber)
	SELECT @YearMonthDay, b.dcProvinceID, 71, COUNT(1)
	FROM PaLoginLog a WITH(NOLOCK)
	LEFT JOIN PaMain b WITH(NOLOCK) ON b.ID = a.PaMainID
	WHERE a.LoginFrom = 44
	AND a.AddDate >= @BeginDate
	AND a.AddDate < @EndDate
	GROUP BY b.dcProvinceID
	
	--72 M站新浪登录
	INSERT INTO LogDb..UserActionCount (CountDate, dcSubSiteId, ActionType, ActionNumber)
	SELECT @YearMonthDay, b.dcProvinceID, 72, COUNT(1)
	FROM PaLoginLog a WITH(NOLOCK)
	LEFT JOIN PaMain b WITH(NOLOCK) ON b.ID = a.PaMainID
	WHERE a.LoginFrom = 45
	AND a.AddDate >= @BeginDate
	AND a.AddDate < @EndDate
	GROUP BY b.dcProvinceID
	
	--73 M站百度登录
	INSERT INTO LogDb..UserActionCount (CountDate, dcSubSiteId, ActionType, ActionNumber)
	SELECT @YearMonthDay, b.dcProvinceID, 73, COUNT(1)
	FROM PaLoginLog a WITH(NOLOCK)
	LEFT JOIN PaMain b WITH(NOLOCK) ON b.ID = a.PaMainID
	WHERE a.LoginFrom = 47
	AND a.AddDate >= @BeginDate
	AND a.AddDate < @EndDate
	GROUP BY b.dcProvinceID
	
	--74 Android App登录
	INSERT INTO LogDb..UserActionCount (CountDate, dcSubSiteId, ActionType, ActionNumber)
	SELECT @YearMonthDay, b.dcProvinceID, 74, COUNT(1)
	FROM PaLoginLog a WITH(NOLOCK)
	LEFT JOIN PaMain b WITH(NOLOCK) ON b.ID = a.PaMainID
	WHERE a.LoginFrom = 21
	AND a.AddDate >= @BeginDate
	AND a.AddDate < @EndDate
	GROUP BY b.dcProvinceID
	
	--75 IOS App登录
	INSERT INTO LogDb..UserActionCount (CountDate, dcSubSiteId, ActionType, ActionNumber)
	SELECT @YearMonthDay, b.dcProvinceID, 75, COUNT(1)
	FROM PaLoginLog a WITH(NOLOCK)
	LEFT JOIN PaMain b WITH(NOLOCK) ON b.ID = a.PaMainID
	WHERE a.LoginFrom = 31
	AND a.AddDate >= @BeginDate
	AND a.AddDate < @EndDate
	GROUP BY b.dcProvinceID

	-- 76 微信登陆
	INSERT INTO LogDb..UserActionCount (CountDate, dcSubSiteId, ActionType, ActionNumber)
	SELECT @YearMonthDay, b.dcProvinceID, 76, COUNT(1)
	FROM PaLoginLog a WITH(NOLOCK)
	LEFT JOIN PaMain b WITH(NOLOCK) ON b.ID = a.PaMainID
	WHERE a.Browser like '%weixin%'
	AND a.AddDate >= @BeginDate
	AND a.AddDate < @EndDate
	GROUP BY b.dcProvinceID

	-- 77 其他Ｍ站登陆　主要是回收，session过期等
	INSERT INTO LogDb..UserActionCount (CountDate, dcSubSiteId, ActionType, ActionNumber)
	SELECT @YearMonthDay, b.dcProvinceID, 77, COUNT(1)
	FROM PaLoginLog a WITH(NOLOCK)
	LEFT JOIN PaMain b WITH(NOLOCK) ON b.ID = a.PaMainID
	WHERE a.LoginFrom = 42
	AND a.AddDate >= @BeginDate
	AND a.AddDate < @EndDate
	GROUP BY b.dcProvinceID

	-- 78 其他PC站登陆　主要是回收，session过期等
	INSERT INTO LogDb..UserActionCount (CountDate, dcSubSiteId, ActionType, ActionNumber)
	SELECT @YearMonthDay, b.dcProvinceID, 78, COUNT(1)
	FROM PaLoginLog a WITH(NOLOCK)
	LEFT JOIN PaMain b WITH(NOLOCK) ON b.ID = a.PaMainID
	WHERE a.LoginFrom = 19
	AND a.AddDate >= @BeginDate
	AND a.AddDate < @EndDate
	GROUP BY b.dcProvinceID

	-- 79 注册时的登陆
	INSERT INTO LogDb..UserActionCount (CountDate, dcSubSiteId, ActionType, ActionNumber)
	SELECT @YearMonthDay, b.dcProvinceID, 79, COUNT(1)
	FROM PaLoginLog a WITH(NOLOCK)
	LEFT JOIN PaMain b WITH(NOLOCK) ON b.ID = a.PaMainID
	WHERE a.LoginFrom = 60
	AND a.AddDate >= @BeginDate
	AND a.AddDate < @EndDate
	GROUP BY b.dcProvinceID
	
	-- 80 新版你的菜儿推送人数
	INSERT INTO LogDb..UserActionCount (CountDate, dcSubSiteId, ActionType, ActionNumber)
	SELECT @YearMonthDay, b.dcProvinceID, 80, COUNT(distinct(pamainid))
	FROM pajobcompare a WITH(NOLOCK)
	LEFT JOIN PaMain b WITH(NOLOCK) ON b.ID = a.PaMainID
	WHERE a.AddDate >= @BeginDate
	AND a.AddDate < @EndDate
	GROUP BY b.dcProvinceID
	
	-- 81 新版你的菜儿推送职位数量
	INSERT INTO LogDb..UserActionCount (CountDate, dcSubSiteId, ActionType, ActionNumber)
	SELECT @YearMonthDay, b.dcProvinceID, 81, COUNT(1)
	FROM pajobcompare a WITH(NOLOCK)
	LEFT JOIN PaMain b WITH(NOLOCK) ON b.ID = a.PaMainID
	WHERE a.AddDate >= @BeginDate
	AND a.AddDate < @EndDate
	GROUP BY b.dcProvinceID
	
	-- 82 新版你的菜儿申请推送的职位
	INSERT INTO LogDb..UserActionCount (CountDate, dcSubSiteId, ActionType, ActionNumber)
	SELECT @YearMonthDay, b.dcProvinceID, 82, COUNT(1)
	FROM pajobcompare a WITH(NOLOCK)
	LEFT JOIN PaMain b WITH(NOLOCK) ON b.ID = a.PaMainID
	WHERE a.AddDate >= @BeginDate
	AND a.AddDate < @EndDate
	AND a.applydate IS NOT NULL
	GROUP BY b.dcProvinceID
	
	-- 83 新版你的菜儿微信推送人数
	INSERT INTO LogDb..UserActionCount (CountDate, dcSubSiteId, ActionType, ActionNumber)
	SELECT @YearMonthDay, b.dcProvinceID, 83, ISNULL(COUNT(1),0)
	FROM wxmessagesend2 a WITH(NOLOCK)
	LEFT JOIN PaMain b WITH(NOLOCK) ON b.ID = a.PaMainID
	WHERE a.AddDate >= @BeginDate
	AND a.AddDate < @EndDate
	AND a.Templatetype=13
	GROUP BY b.dcProvinceID
	
	-- 84 新版你的菜儿微信推送职位数量
	INSERT INTO LogDb..UserActionCount (CountDate, dcSubSiteId, ActionType, ActionNumber)
	SELECT @YearMonthDay, b.dcProvinceID, 84, COUNT(1)
	FROM pajobcompare a WITH(NOLOCK)
	LEFT JOIN PaMain b WITH(NOLOCK) ON b.ID = a.PaMainID
	WHERE a.AddDate >= @BeginDate
	AND a.AddDate < @EndDate
	AND EXISTS(
		SELECT 'x' 
		FROM wxmessagesend2 WITH(NOLOCK) 
		WHERE pamainid = a.pamainid 
		AND Templatetype=13  
		AND AddDate >= @BeginDate 
		AND AddDate < @EndDate)
	GROUP BY b.dcProvinceID
	
	--85企业查看简历数量
	INSERT INTO LogDb..UserActionCount (CountDate, dcSubSiteId, ActionType, ActionNumber)
	SELECT @YearMonthDay, b.dcProvinceID, 85, COUNT(1)
	FROM caCvViewLog a WITH(NOLOCK),CpMain b WITH(NOLOCK)
	WHERE a.AddDate >= @BeginDate
	AND a.AddDate < @EndDate
	AND a.caMainID IN(SELECT ID FROM caMain WITH(NOLOCK) WHERE cpMainID = b.ID)
	GROUP BY b.dcProvinceID
	
	--86企业下载简历数量
	INSERT INTO LogDb..UserActionCount (CountDate, dcSubSiteId, ActionType, ActionNumber)
	SELECT @YearMonthDay, dcProvinceID, 86, COUNT(1)
	FROM (
		SELECT cpMainID,caMainID,cvMainID,b.dcProvinceID 
		FROM caDailyGiftLog a WITH(NOLOCK),CpMain b WITH(NOLOCK) 
		WHERE a.cpMainID=b.id 
		AND a.AddDate >= @BeginDate
		AND a.AddDate < @EndDate
		UNION 
		SELECT cpMainID,caMainID,cvMainID,b.dcProvinceID 
		FROM caActiveLog a WITH(NOLOCK),CpMain b WITH(NOLOCK) 
		WHERE a.cpMainID=b.id
		AND a.AddDate >= @BeginDate
		AND a.AddDate < @EndDate) TableDownLoad
	GROUP BY dcProvinceID
	
	--87企业发出应聘邀请数量
	INSERT INTO LogDb..UserActionCount (CountDate, dcSubSiteId, ActionType, ActionNumber)
	SELECT @YearMonthDay, b.dcProvinceID, 87, COUNT(1)
	FROM caCvIntention a WITH(NOLOCK),CpMain b WITH(NOLOCK)
	WHERE a.AddDate >= @BeginDate
	AND a.AddDate < @EndDate
	AND a.caMainID IN(SELECT ID FROM caMain WITH(NOLOCK) WHERE cpMainID = b.ID)
	GROUP BY b.dcProvinceID
	
	--88企业发出面试通知数量
	INSERT INTO LogDb..UserActionCount (CountDate, dcSubSiteId, ActionType, ActionNumber)
	SELECT @YearMonthDay, b.dcProvinceID, 88, COUNT(1)
	FROM exInterview a WITH(NOLOCK),CpMain b WITH(NOLOCK)
	WHERE a.AddDate >= @BeginDate
	AND a.AddDate < @EndDate
	AND a.JobID IN(SELECT ID FROM Job WITH(NOLOCK) WHERE cpMainID = b.ID)
	GROUP BY b.dcProvinceID
	
	--89生成的职位订阅总数量
	INSERT INTO LogDb..UserActionCount (CountDate, dcSubSiteId, ActionType, ActionNumber)
	SELECT @YearMonthDay, b.dcProvinceID, 89, COUNT(1)
	FROM caJobCvMatch a WITH(NOLOCK),CpMain b WITH(NOLOCK)
	WHERE a.AddDate >= @BeginDate
	AND a.AddDate < @EndDate
	AND a.JobID IN(SELECT ID FROM Job WITH(NOLOCK) WHERE cpMainID = b.ID)
	GROUP BY b.dcProvinceID
	
	--90查看订阅的数量
	INSERT INTO LogDb..UserActionCount (CountDate, dcSubSiteId, ActionType, ActionNumber)
	SELECT @YearMonthDay, b.dcProvinceID, 90, COUNT(1)
	FROM caJobCvMatch a WITH(NOLOCK),CpMain b WITH(NOLOCK)
	WHERE a.AddDate >= @BeginDate
	AND a.AddDate < @EndDate
	AND a.JobID IN(SELECT ID FROM Job WITH(NOLOCK) WHERE cpMainID = b.ID)
	AND EXISTS(SELECT 'x' FROM caCvViewLog WITH(NOLOCK) WHERE cvMainID = a.MatchCvMainID AND caMainID IN(SELECT ID FROM caMain WITH(NOLOCK) WHERE cpMainID = b.ID) AND AddDate > @BeginDate)
	GROUP BY b.dcProvinceID

	--M站相关统计 100 M站申请职位 101 微信申请职位 102 M站添加点评 103 微信添加点评
	--104 M站添加面经 105 微信添加面经 106 M站意见反馈 107 微信意见反馈
	--108 M站查看面试通知 109 微信查看面试通知
	--110 M站答复面试通知 111 微信答复面试通知
	--112 M站发送在线沟通信息 113 微信发送在线沟通信息
	--114 M站完善简历 115 微信完善简历
    --企业认证相关统计 200 普通认证（营业执照+个人） 201 普通认证（邮箱）
    --202 实名认证（对公） --203 实名认证（法人）
    --204 取消普通认证（营业执照+个人） 205 取消普通认证（邮箱）
    --206 取消实名认证（对公） --207 取消实名认证（法人）
	INSERT INTO LogDb..UserActionCount(CountDate,dcSubSiteId,ActionType,ActionNumber)
	SELECT CONVERT(VARCHAR(8), AddDate, 112),dcProvinceId,ActionType,COUNT(1)
	FROM LogDb..UserActionDetail
	WHERE AddDate >= @BeginDate
	AND AddDate < @EndDate
	GROUP BY CONVERT(VARCHAR(8), AddDate, 112),ActionType,dcProvinceId	

	--生成全部站点的数据
	INSERT INTO LogDb..UserActionCount (CountDate, dcSubSiteId, ActionType, ActionNumber) 
	SELECT @YearMonthDay, 0, ActionType, SUM(CONVERT(BIGINT, ActionNumber))
	FROM LogDb..UserActionCount
	WHERE ActionType NOT IN (SELECT ActionType FROM LogDb..UserActionCount WHERE CountDate = @YearMonthDay AND dcSubSiteId = 0)
	AND CountDate = @YearMonthDay
	--AND ActionType > 99
	GROUP BY ActionType
END
SET NOCOUNT OFF
GO
/****** Object:  StoredProcedure [dbo].[bpUserActionCountInsert2]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--创建人 Harry
--时间 2016-2-29 
--useractioncount数据插入
create PROCEDURE [dbo].[bpUserActionCountInsert2]
(
	@Date DATETIME
)
AS
SET NOCOUNT ON
BEGIN 
	DECLARE @YearMonthDay VARCHAR(8), @BeginDate DATETIME, @EndDate DATETIME
	SELECT @YearMonthDay = CONVERT(VARCHAR(8), @Date - 1, 112),
		@BeginDate = CONVERT(VARCHAR(8), @Date - 1, 112),
		@EndDate = CONVERT(VARCHAR(8), @Date, 112)

	DELETE LogDb..UserActionCount WHERE CountDate = @YearMonthDay

	--1 申请职位数量
	INSERT INTO LogDb..UserActionCount(CountDate, dcSubSiteId, ActionType, ActionNumber) 
	SELECT @YearMonthDay, LEFT(b.dcRegionId, 2), 1, COUNT(1) 
	FROM exjobApply A WITH(NOLOCK), JOb b WITH(NOLOCK) 
	WHERE a.AddDate >= @BeginDate
	AND a.AddDate < @EndDate
	AND a.JobId = b.Id
	GROUP BY LEFT(b.dcRegionId, 2)

	--3申请职位回复通过数量
	INSERT INTO LogDb..UserActionCount (CountDate, dcSubSiteId, ActionType, ActionNumber) 
	SELECT @YearMonthDay, LEFT(b.dcRegionId, 2), 3, COUNT(1) 
	FROM exJobApply A WITH(NOLOCK), JOB b WITH(NOLOCK) 
	WHERE a.ReplyDate >= @BeginDate
	AND a.ReplyDate < @EndDate
	AND A.Reply = 1 
	AND a.JobId = b.Id
	GROUP BY LEFT(b.dcRegionId, 2)

	--4申请职位未通过数量	
	INSERT INTO LogDb..UserActionCount (CountDate, dcSubSiteId, ActionType, ActionNumber)
	SELECT @YearMonthDay, LEFT(b.dcRegionId, 2), 4, COUNT(1) 
	FROM exJobApply A WITH(NOLOCK), JOB b WITH(NOLOCK) 
	WHERE a.ReplyDate > @BeginDate
	AND a.ReplyDate < @EndDate
	AND a.JobId = b.Id
	AND A.Reply > 1 
	GROUP BY LEFT(b.dcRegionId, 2)

	--生成全部站点的数据
	INSERT INTO LogDb..UserActionCount (CountDate, dcSubSiteId, ActionType, ActionNumber) 
	SELECT @YearMonthDay, 0, ActionType, SUM(CONVERT(BIGINT, ActionNumber))
	FROM LogDb..UserActionCount
	WHERE ActionType NOT IN (SELECT ActionType FROM LogDb..UserActionCount WHERE CountDate = @YearMonthDay AND dcSubSiteId = 0)
	AND CountDate = @YearMonthDay
	GROUP BY ActionType
END
SET NOCOUNT OFF

GO
/****** Object:  StoredProcedure [dbo].[bpVersionByProvince_IDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.08.27
--创建人：Nick
--说明：根据ProvinceID查询version
--#####################################################
CREATE PROCEDURE [dbo].[bpVersionByProvince_IDSelect]
(
	@Province_ID INT
)
AS
BEGIN
	IF @Province_ID = 0
	BEGIN
		SELECT '伍亿人才招聘网' versionname,'www.51rc.com' versiondomain,0 id
	END
	ELSE IF @Province_ID = 90
	BEGIN
		SELECT '伍亿猎头' versionname,'hunter.51rc.com' versiondomain,90 id
	END
	ELSE 
	BEGIN
		SELECT versionname,versiondomain,id FROM version WITH(NOLOCK) 
		WHERE province_id = @Province_ID
		ORDER BY id
	END
END

GO
/****** Object:  StoredProcedure [dbo].[bpVersionByProvinceIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----------------
--创建日期：2015-08-20
--创建人：Peter
--功能说明：二级域名统计
-----------------
CREATE PROCEDURE [dbo].[bpVersionByProvinceIDSelect]
	@ProvinceID INT
AS
IF @ProvinceID < 10
BEGIN
	SELECT id,versionname,(
		SELECT SUM(score) 
		FROM link WITH(NOLOCK) 
		WHERE versionid>100 AND versionid=version.id AND type=1 AND valid=1 AND deleted<2 AND method=1
	) score_sum,(
		SELECT COUNT(1) cnt 
		FROM link WITH(NOLOCK) 
		WHERE versionid>100 AND versionid=version.id AND type=1 AND valid=1 AND deleted<2 AND method=1
	) Cnt
	FROM version WITH(NOLOCK) 
	WHERE id>100 AND id NOT IN(1203,2002,3102,3103,3106,3107,3108,3202,3203,3204,3206,3402,3404,3502,3503,3506,4002,4010,4013) AND province_id = @ProvinceID
	ORDER BY id
END
ELSE
BEGIN
	SELECT id,versionname,(
		SELECT SUM(score) 
		FROM link WITH(NOLOCK) 
		WHERE versionid>100 AND versionid=version.id AND type=1 AND valid=1 AND deleted<2 AND method=1
	) score_sum,(
		SELECT COUNT(1) cnt 
		FROM link WITH(NOLOCK) 
		WHERE versionid>100 AND versionid=version.id AND type=1 AND valid=1 AND deleted<2 AND method=1
	) Cnt 
	FROM version WITH(NOLOCK) 
	WHERE id > 100 AND province_id = @ProvinceID
	ORDER BY id
END
GO
/****** Object:  StoredProcedure [dbo].[bpWeixinFansListByMessageSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Mice 123>
-- Create date: <2015-4-16>
-- Description:	<微信待发送消息的粉丝列表>
-- =============================================
CREATE PROCEDURE [dbo].[bpWeixinFansListByMessageSelect]
(
	@radioType INT,
	@radioMsg INT,
	@wxserviceNoIDs VARCHAR(200)
)
AS
BEGIN
SET NOCOUNT ON

CREATE TABLE #TAB
(
	wxFansID INT,
	validCvNum INT,
	msgSendNum INT
)

--获取48小时之内活动的微信粉丝ID
INSERT INTO #TAB (wxFansID)
SELECT DISTINCT  WxFansID   FROM wxMessageReceive WHERE AddDate > GETDATE() - 2

--更新粉丝的有效简历
UPDATE a SET validCvNum = ( SELECT COUNT(0) FROM cvMain c  WHERE c.paMainID = b.paMainID)
FROM #TAB a, wxFans b
WHERE b.PaMainID IS NOT NULL AND a.wxFansID = b.ID

--更新粉丝在48小时之内发送的消息数量
UPDATE a 
SET msgSendNum = ( SELECT COUNT(0) FROM wxMessageLog c  WHERE c.wxFansID = a.wxFansID AND c.SendDate > GETDATE() - 2 )
FROM #TAB a

DECLARE @strWhere AS VARCHAR(500)
DECLARE @sql AS VARCHAR(300)
SET @strWhere = ''
IF @radioType =2 --未绑定
BEGIN
	SET @strWhere = @strWhere + ' AND y.PaMainID IS NULL ' 
END
ELSE IF @radioType =3 --已绑定+无有效简历
BEGIN
	SET @strWhere = @strWhere + ' AND y.PaMainID IS NOT NULL AND x.validCvNum = 0 ' 
END
ELSE IF @radioType =4 --已绑定+有有效简历
BEGIN
	SET @strWhere = @strWhere + ' AND y.PaMainID IS NOT NULL AND x.validCvNum > 0 ' 
END

IF @radioMsg =2  --48小时内活动过+未发消息
BEGIN
	SET @strWhere = @strWhere + ' AND x.msgSendNum = 0 '
END
ELSE IF @radioMsg =3  --48小时内活动过+消息≤1
BEGIN
	SET @strWhere = @strWhere + ' AND x.msgSendNum <= 1 ' 
END
ELSE IF @radioMsg =4  --48小时内活动过+消息≤2
BEGIN
	SET @strWhere = @strWhere + ' AND x.msgSendNum <= 2 ' 
END
SET @strWhere = @strWhere + ' AND y.WxServiceNoID IN ( ' + @wxserviceNoIDs + ' ) '  --微信服务号


SET @sql = 'SELECT y.* FROM #TAB x, wxFans y WHERE x.wxFansID = y.ID  ' + @strWhere

EXEC (@sql)

DROP TABLE #TAB

SET NOCOUNT OFF
END


GO
/****** Object:  StoredProcedure [dbo].[bpWxFansBySearchSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.01.27
--创建人：John
--说明：根据查询条件获取微信粉丝
--#####################################################
CREATE PROCEDURE [dbo].[bpWxFansBySearchSelect]
(
	@OpenID VARCHAR(50),
	@PaMainID INT,
	@WxServiceNoID INT,
	@LastReceiveStartDate VARCHAR(8),
	@LastReceiveEndDate VARCHAR(8),
	@Status SMALLINT
)
AS
BEGIN
	SET @OpenID = dbo.SafeSql(@OpenID)
	DECLARE @SQL VARCHAR(1000)	
	SET @SQL = 'SELECT a.*, b.Name FROM WxFans a WITH(NOLOCK), WxServiceNo b WITH(NOLOCK) WHERE a.WxServiceNoID = b.ID'
	IF @Status = 3
	BEGIN
		SET @SQL = @SQL + ' AND (a.Status = 1 OR a.Status = 2) '
	END
	ELSE
	BEGIN
		SET @SQL = @SQL + ' AND a.Status = ' + LTRIM(STR(@Status))
	END
	IF LEN(@OpenID) > 0	
		SET @SQL = @SQL + ' AND a.OpenID = ''' + @OpenID + ''''
	IF @PaMainID > 0
		SET @SQL = @SQL + ' AND a.PaMainID = ' + LTRIM(STR(@PaMainID))
	IF @WxServiceNoID > 0
		SET @SQL = @SQL + ' AND a.WxServiceNoID = ' + LTRIM(STR(@WxServiceNoID))
	IF LEN(@LastReceiveStartDate) > 0
		SET @SQL =  @SQL + ' AND CONVERT(VARCHAR(8), a.LastReceiveDate, 112) >= ''' + @LastReceiveStartDate + ''''
	IF LEN(@LastReceiveEndDate) > 0
		SET @SQL =  @SQL + ' AND CONVERT(VARCHAR(8), a.LastReceiveDate, 112) <= ''' + @LastReceiveEndDate + ''''
	IF @Status = 0
	BEGIN
		SET @SQL = @SQL + ' ORDER BY a.AttentionCancelDate DESC'
	END
	ELSE
	BEGIN
		SET @SQL = @SQL + ' ORDER BY a.AttentionDate DESC'
	END
	EXEC(@SQL)
END

GO
/****** Object:  StoredProcedure [dbo].[bpWxMessageReceiveByWxFansIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.01.27
--创建人：John
--说明：获取微信粉丝操作日志
--#####################################################
CREATE PROCEDURE [dbo].[bpWxMessageReceiveByWxFansIDSelect]
(
	@WxFansID INT
)
AS
BEGIN
	SELECT * FROM WxMessageReceive WITH(NOLOCK) WHERE WxFansID = @WxFansID
END

GO
/****** Object:  StoredProcedure [dbo].[bpWxMessageSendBySearchSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.01.27
--创建人：John
--说明：根据查询条件获取微信消息列表
--修改人：harry 2015-7-31
--修改取top 1000
--修改人:harry 2015-9-18
--修改
--#####################################################
CREATE PROCEDURE [dbo].[bpWxMessageSendBySearchSelect]
(
    @OpenID VARCHAR(50),
    @WxServiceNoID INT,
    @WxTemplateID INT,
    @SendStartDate VARCHAR(8),
    @SendEndDate VARCHAR(8)
)
AS
BEGIN
    SET @OpenID = dbo.SafeSql(@OpenID)
    DECLARE @SQL VARCHAR(1000)    
    SET @SQL = 'SELECT TOP 1000 a.*, b.OpenId, d.WebsiteName,e.title FROM WxMessageSend2 a WITH(NOLOCK), WxFans b WITH(NOLOCK), pamain c WITH(NOLOCK),dcprovince d WITH(NOLOCK),wxtemplate e WITH(NOLOCK) 
        WHERE a.wxfansid=b.id AND a.pamainid= c.id AND c.dcprovinceid=d.id AND a.Templatetype=e.id'
    IF LEN(@OpenID) > 0    
        SET @SQL = @SQL + ' AND b.OpenID = ''' + @OpenID + ''''
    IF @WxServiceNoID > 0
        SET @SQL = @SQL + ' AND c.dcProvinceID = ' + LTRIM(STR(@WxServiceNoID))
    IF @WxTemplateID > 0
        SET @SQL = @SQL + ' AND a.Templatetype = ' + LTRIM(STR(@WxTemplateID))+' '
    IF LEN(@SendStartDate) > 0
        SET @SQL = @SQL + ' AND CONVERT(VARCHAR(8), a.SendDate, 112) >= ''' + @SendStartDate + ''''
    IF LEN(@SendEndDate) > 0
        SET @SQL = @SQL + ' AND CONVERT(VARCHAR(8), a.SendDate, 112) <= ''' + @SendEndDate + ''''
    SET @SQL = @SQL + ' ORDER BY a.SendDate DESC'
    EXEC(@SQL)
END 

GO
/****** Object:  StoredProcedure [dbo].[bpWxMessageSendByStatisticsSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.01.28
--创建人：John
--说明：根据查询条件获取微信消息统计
--修改人：harry2015-9-18	
--修改为统计wxmessagesend2
--##################################################### 
CREATE PROCEDURE [dbo].[bpWxMessageSendByStatisticsSelect]
(
	@WxServiceNoID INT,
	@WxTemplateID INT,
	@SendStartDate SMALLDATETIME,
	@SendEndDate SMALLDATETIME
)
AS
SET NOCOUNT ON
BEGIN
	DECLARE @SQL VARCHAR(1000)	
	SET @SQL = 'SELECT c.sendcount,d.WebsiteName,e.title 
		FROM (SELECT COUNT(1) AS SendCount,b.dcprovinceid,a.Templatetype
				FROM wxMessageSend2 a, pamain b
				WHERE a.senddate IS NOT NULL AND a.pamainid = b.id  '
	IF @WxServiceNoID > 0
		SET @SQL = @SQL + ' AND b.dcProvinceID = ' + LTRIM(STR(@WxServiceNoID))
	IF @WxTemplateID > 0
		SET @SQL = @SQL + ' AND a.Templatetype = ' + LTRIM(STR(@WxTemplateID))
	IF LEN(@SendStartDate) > 0
		SET @SQL =  @SQL + ' AND CONVERT(VARCHAR(8), a.SendDate, 112) >= ''' + CONVERT(VARCHAR(8), @SendStartDate, 112) + ''''
	IF LEN(@SendEndDate) > 0
		SET @SQL =  @SQL + ' AND CONVERT(VARCHAR(8), a.SendDate, 112) <= ''' + CONVERT(VARCHAR(8), @SendEndDate, 112) + ''''
	SET @SQL =  @SQL + ' GROUP BY a.Templatetype,b.dcprovinceid) c, 
		dcprovince d, wxtemplate e 
	where c.dcprovinceid=d.id and c.templatetype=e.id
	ORDER BY d.Id, e.ID'
	--print @SQL
	EXEC(@SQL)
END

GO
/****** Object:  StoredProcedure [dbo].[bpWxServiceNoByTemplateIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.01.27
--创建人：John
--说明：根据模板ID获取所属服务号
--#####################################################
CREATE PROCEDURE [dbo].[bpWxServiceNoByTemplateIDSelect]
(
	@TemplateId INT
)
AS
BEGIN
	SELECT b.Name FROM WxTemplateNo a WITH(NOLOCK), WxServiceNo b WITH(NOLOCK) 
	WHERE a.WxServiceNoID = b.ID AND a.WxTemplateId = @TemplateId
END

GO
/****** Object:  StoredProcedure [dbo].[bpWxServiceNoSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.01.27
--创建人：John
--说明：获取微信服务号列表
--#####################################################
CREATE PROCEDURE [dbo].[bpWxServiceNoSelect]
AS
BEGIN
	SELECT a.*,b.ProvinceName FROM WxServiceNo a WITH(NOLOCK), dcProvince b WITH(NOLOCK) 
	WHERE a.ProvinceID = b.ID
END

GO
/****** Object:  StoredProcedure [dbo].[bpWxTemplateByWxServiceNoIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.01.27
--创建人：John
--说明：根据服务号获取相应的微信模板
--#####################################################
CREATE PROCEDURE [dbo].[bpWxTemplateByWxServiceNoIDSelect]
(
	@WxServiceNoID INT
)
AS
BEGIN
	SELECT a.ID,a.Title FROM WxTemplate a WITH(NOLOCK), WxTemplateNo b WITH(NOLOCK) 
	WHERE a.ID = b.WxTemplateId AND b.WxServiceNoID = @WxServiceNoID
END

GO
/****** Object:  StoredProcedure [dbo].[bpWxTemplateParaUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.01.27
--创建人：John
--说明：更新微信模板参数
--#####################################################
CREATE PROCEDURE [dbo].[bpWxTemplateParaUpdate]
(
	@ParaValue VARCHAR(500),
	@ParaColor VARCHAR(50),
	@ID INT
)
AS
BEGIN
	UPDATE WxTemplatePara SET ParaValue = @ParaValue, ParaColor = @ParaColor WHERE ID = @ID
END

GO
/****** Object:  StoredProcedure [dbo].[bpWxTemplateSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.01.27
--创建人：John
--说明：获取微信模板列表
--#####################################################
CREATE PROCEDURE [dbo].[bpWxTemplateSelect]
AS
BEGIN
	SELECT * FROM WxTemplate WITH(NOLOCK)
END

GO
/****** Object:  StoredProcedure [dbo].[bpWxTemplateUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.01.27
--创建人：John
--说明：更新微信模板备注
--#####################################################
CREATE PROCEDURE [dbo].[bpWxTemplateUpdate]
(
	@Remark NVARCHAR(500),
	@TemplateId INT
)
AS
BEGIN
	UPDATE WxTemplate SET Remark = @Remark WHERE ID = @TemplateId
END

GO
/****** Object:  StoredProcedure [dbo].[bpYingYeLogByCntSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--###########################
--创建时间：2014.12.15
--创建人：Nick
--说明：根据manageruserid查询yingyelog 条数
--###########################
CREATE PROCEDURE [dbo].[bpYingYeLogByCntSelect]
(
	@dcProvinceID INT,
	@managerUserID INT
)
AS
BEGIN 
	SELECT Count(1) cnt 
	FROM yingyelog With(Nolock) 
	WHERE countdate=year(getdate())*10000+month(getdate())*100+day(getdate()) 
	AND Province_ID=@dcProvinceID 
	AND manageruserid=@managerUserID
END


GO
/****** Object:  StoredProcedure [dbo].[bpYingYeLogByManageruserID_DailySelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--###########################
--创建时间：2014.12.15
--创建人：Nick
--说明：营业执照审核日志 工号日报
--###########################
CREATE PROCEDURE [dbo].[bpYingYeLogByManageruserID_DailySelect]
(
	@Where VARCHAR(MAX)
)
AS
BEGIN 
	DECLARE @SQL VARCHAR(MAX)
	SET @Where = dbo.SafeSql(@Where)
	SET @SQL = '
		SELECT TOP 300 countdate,SUM(Faxpassed) Faxpassed,SUM(Faxnotpassed) Faxnotpassed,SUM(Uploadpassed) Uploadpassed,
		SUM(Uploadnotpassed) Uploadnotpassed,SUM(Transferpassed) Transferpassed,SUM(Transfernotpassed) Transfernotpassed,
		Manageruserid 
		FROM yingyelog WITH(NOLOCK) 
		WHERE 1=1 '+@Where+' 
		GROUP BY countdate,manageruserid 
		ORDER BY countdate DESC,manageruserid'
	EXEC(@SQL)
END


GO
/****** Object:  StoredProcedure [dbo].[bpYingYeLogByManageruserMonthSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--###########################
--创建时间：2014.12.15
--创建人：Nick
--说明：营业执照审核日志 月报
--###########################
CREATE PROCEDURE [dbo].[bpYingYeLogByManageruserMonthSelect]
(
	@BeginDate VARCHAR(50),
	@EndDate VARCHAR(50)
)
AS
BEGIN 
	SELECT TOP 300 SUM(faxpassed) faxpassed,SUM(faxnotpassed) faxnotpassed,SUM(uploadpassed) uploadpassed,
		SUM(uploadnotpassed) uploadnotpassed,SUM(transferpassed) transferpassed,
		SUM(transfernotpassed) transfernotpassed, manageruserid 
	FROM yingyelog WITH(NOLOCK) 
	WHERE CountDate >= @BeginDate AND CountDate<=@EndDate
	GROUP BY manageruserid 
	ORDER BY manageruserid
END


GO
/****** Object:  StoredProcedure [dbo].[bpYingYeLogByProvinceID_DailySelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--###########################
--创建时间：2014.12.15
--创建人：Nick
--说明：营业执照审核日志 省份日报
--###########################
CREATE PROCEDURE [dbo].[bpYingYeLogByProvinceID_DailySelect]
(
	@Where VARCHAR(MAX)
)
AS
BEGIN 
	DECLARE @SQL VARCHAR(MAX)
	SET @Where = dbo.SafeSql(@Where)
	SET @SQL = '
		SELECT TOP 300 countdate,SUM(faxpassed) faxpassed,SUM(faxnotpassed) faxnotpassed,SUM(uploadpassed) uploadpassed,
		SUM(uploadnotpassed) uploadnotpassed,SUM(transferpassed) transferpassed,SUM(transfernotpassed) transfernotpassed,
		province_id 
		FROM yingyelog WITH(NOLOCK) 
		WHERE 1=1 '+@Where+' 
		GROUP BY countdate,province_id 
		ORDER BY countdate DESC,province_id'
	EXEC(@SQL)
END


GO
/****** Object:  StoredProcedure [dbo].[bpYingYeLogByProvinceMonthSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--###########################
--创建时间：2014.12.15
--创建人：Nick
--说明：营业执照审核日志 月报
--###########################
CREATE PROCEDURE [dbo].[bpYingYeLogByProvinceMonthSelect]
(
	@BeginDate VARCHAR(50),
	@EndDate VARCHAR(50)
)
AS
BEGIN 
	SELECT TOP 300 SUM(faxpassed) faxpassed,SUM(faxnotpassed) faxnotpassed,SUM(uploadpassed) uploadpassed,
		SUM(uploadnotpassed) uploadnotpassed,SUM(transferpassed) transferpassed,
		SUM(transfernotpassed) transfernotpassed, province_id 
	FROM yingyelog WITH(NOLOCK) 
	WHERE CountDate >= @BeginDate AND CountDate<=@EndDate
	GROUP BY province_id 
	ORDER BY province_id
END


GO
/****** Object:  StoredProcedure [dbo].[bpYingYeLogInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--###########################
--创建时间：2014.12.15
--创建人：Nick
--说明：插入yingyelog
--###########################
CREATE PROCEDURE [dbo].[bpYingYeLogInsert]
(
	@dcProvinceID INT,
	@managerUserID INT
)
AS
BEGIN 
	INSERT INTO yingyelog(countdate,Province_ID,manageruserid) 
	VALUES (YEAR(GETDATE())*10000+MONTH(GETDATE())*100+DAY(GETDATE()),@dcProvinceID,@managerUserID)
END


GO
/****** Object:  StoredProcedure [dbo].[bpYingYeLogSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--###########################
--创建时间：2014.12.15
--创建人：Nick
--说明：营业执照审核日志
--###########################
CREATE PROCEDURE [dbo].[bpYingYeLogSelect]
(
	@Where VARCHAR(MAX)
)
AS
BEGIN 
	DECLARE @SQL VARCHAR(MAX)
	SET @Where = dbo.SafeSql(@Where)
	SET @SQL = '
		SELECT TOP 300 countdate,faxpassed,faxnotpassed,uploadpassed,uploadnotpassed,transferpassed,transfernotpassed,
		manageruserid,province_id ,b.Name
		FROM YingyeLog a WITH(NOLOCK) ,ManagerUser b
		WHERE 1=1 AND a.ManagerUserID = b.ID '+@Where+' ORDER BY countdate DESC,manageruserid '
	EXEC(@SQL)
END


GO
/****** Object:  StoredProcedure [dbo].[bsBackdataUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--后台带转化简历数据统计
--harry 
--2018-7-3
--计划任务计算5天内的数据，每次执行计算5天内的数据
CREATE PROCEDURE  [dbo].[bsBackdataUpdate] 
AS
BEGIN
	DECLARE @CountDate INT, @index INT,@complete INT, @apply INT
	SET @index=5
	WHILE @index>0
	BEGIN
		SELECT @CountDate = YEAR(GETDATE()-@index) * 10000 + MONTH(GETDATE()-@index) * 100 + DAY(GETDATE()-@index)
		SELECT DISTINCT ContactMan INTO #addman FROM paContact 
		WHERE contactDate> CONVERT(varchar(10),GETDATE()-@index,120)
		AND contactDate< CONVERT(varchar(10),GETDATE()-@index+1,120)
		--循环
		DECLARE @addman INT
		SET @addman = 0
		WHILE EXISTS(SELECT 'X' FROM #addman)
		BEGIN
			SELECT top 1 @addman=ContactMan FROM #addman ORDER by ContactMan
			DELETE FROM #addman WHERE ContactMan = @addman
			IF NOT EXISTS(SELECT 'X' FROM backdata WHERE managerId= @addman AND CountDate = @CountDate)
			BEGIN
				INSERT INTO backdata(ManagerID, CountDate)
				SELECT @addman,@CountDate
			END
			--更新联系Contact_Count
			UPDATE backdata 
			SET Contact_Count=(SELECT COUNT(1) 
				FROM paContact 
				WHERE ContactMan= @addman 
				AND contactDate> CONVERT(varchar(10),GETDATE()-@index,120)
				AND contactDate< CONVERT(varchar(10),GETDATE()-@index+1,120)
				)
			WHERE ManagerID=@addman AND CountDate =@CountDate
			
			--更新未完善简历数量
			UPDATE backdata 
			SET Contact_NoCvCount=(SELECT COUNT(1) 
				FROM paMain
				WHERE id IN(
				SELECT paMainId
				FROM paContact 
				WHERE ContactMan= @addman 
				AND contactDate> CONVERT(varchar(10),GETDATE()-@index,120)
				AND contactDate< CONVERT(varchar(10),GETDATE()-@index+1,120)
				)
				AND PerfectDate IS NULL
				)
			WHERE ManagerID=@addman AND CountDate =@CountDate
			

			--更新完善简历数量
			SELECT @complete=COUNT(1) 
				FROM paMain
				WHERE id IN(
				SELECT paMainId
				FROM paContact 
				WHERE ContactMan= @addman 
				AND contactDate> CONVERT(varchar(10),GETDATE()-@index,120)
				AND contactDate< CONVERT(varchar(10),GETDATE()-@index+1,120)	
				)
			AND PerfectDate IS NOT NULL
				
			UPDATE backdata 
			SET Contact_CvCount= @complete
			WHERE ManagerID=@addman AND CountDate =@CountDate
			
			--更新申请量Contact_ApplyCount
			SELECT @apply =COUNT(DISTINCT(a.paMainId)) 
				FROM cvmain a, exjobapply b 
				WHERE a.paMainId IN(
				SELECT paMainId
				FROM paContact 
				WHERE ContactMan= @addman 
				AND contactDate> CONVERT(varchar(10),GETDATE()-@index,120)
				AND contactDate< CONVERT(varchar(10),GETDATE()-@index+1,120)	
				)
				AND a.id= b.cvmainId
			UPDATE backdata 
			SET Contact_ApplyCount=@apply
			WHERE ManagerID=@addman AND CountDate =@CountDate
			
			--未投递 
			UPDATE backdata 
			SET Contact_NoApplyCount=(@complete-@apply)
            WHERE ManagerID=@addman AND CountDate =@CountDate
		END
		DROP TABLE #addman
		SET	@index=@index-1
	END
END

GO
/****** Object:  StoredProcedure [dbo].[bsCaCvQuotaLogSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[bsCaCvQuotaLogSelect]
(
	@DeptId INT,
	@StartDate VARCHAR(10),
	@EndDate VARCHAR(10)
)
AS
BEGIN
	CREATE TABLE #t(
		cpMainID INT,
		Cnt INT,
		CompanyName NVARCHAR(50),
		LastLoginIp VARCHAR(31),
		LastLoginPlace NVARCHAR(50),
		LoginCookies VARCHAR(20),
		ConsultantID INT,
		Description NVARCHAR(1000),
		MemberType TINYINT,
		MemberDate SMALLDATETIME,
		Balance INT,
		IsLimitLogin TINYINT,
		RegDate SMALLDATETIME
	)

	INSERT INTO #T(cpMainID, CNT)
	SELECT TOP 100 cpMainId, COUNT(*) from viewCaCvQuotaLog
	WHERE AddDate > @StartDate
	AND AddDate < @EndDate + ' 23:59'
	AND EXISTS (SELECT 'x' FROM cpMain 
		WHERE cpMain.ID = cpMainId 
		AND (cpMain.ConsultantId IN(SELECT ID FROM ManagerUser WHERE Deptid = CASE WHEN @DeptId > 0 THEN @DeptId ELSE DeptId End)
			OR ISNULL(cpMain.ConsultantId, 0) = CASE WHEN @DeptId > 0 THEN @DeptId ELSE 0 End)
		)
	
	GROUP BY cpMainID
	HAVING COUNT(*) > 20
	ORDER BY COUNT(*) DESC, cpMainId
	
	UPDATE a SET a.CompanyName = b.Name,
		a.IsLimitLogin = b.IsLimitLogin,
		a.ConsultantID = b.ConsultantID,
		a.Description = b.Description,
		a.MemberType = b.MemberType,
		a.RegDate = b.RegDate,
		a.MemberDate = CASE b.MemberType WHEN 10 THEN b.UnlimitedDate ELSE b.BalanceDate END,
		a.Balance = CASE b.MemberType WHEN 11 THEN b.Balance ELSE 0 END
	FROM #t a WITH(NOLOCK), cpMain b WITH(NOLOCK)
	WHERE a.cpMainID = b.Id

	UPDATE #t SET LastLoginIp = (SELECT TOP 1 a.LoginIp FROM caLoginLog a WITH(NOLOCK), caMain b WITH(NOLOCK) WHERE a.caMainID = b.ID AND b.cpMainId = #t.cpMainID),
		LoginCookies = (SELECT TOP 1 a.LoginCookies FROM caLoginLog a WITH(NOLOCK), caMain b WITH(NOLOCK) WHERE a.caMainID = b.ID AND b.cpMainId = #t.cpMainID)

	UPDATE #t SET LastLoginPlace = dbo.IpPlace(LastLoginIp)

	SELECT * FROM #t	
END














GO
/****** Object:  StoredProcedure [dbo].[bsCaCvQuotaLogSelect0118]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[bsCaCvQuotaLogSelect0118]
(
	@DeptId INT,
	@StartDate VARCHAR(10),
	@EndDate VARCHAR(10)
)
AS
BEGIN
	DECLARE @Sql AS VARCHAR(MAX), @Table AS VARCHAR(20)
	SELECT @Table = 'viewCaCvQuotaLog'
	SELECT @SQL = 'INSERT INTO #T(cpMainID, CNT) 
		SELECT TOP 100 cpMainId, COUNT(*) from ' + @Table + '
		WHERE AddDate > '''  + @StartDate + '''
		AND AddDate < ''' +@EndDate + ' 23:59'''
	IF @DeptId > 0
		SELECT @SQL = @SQL + '		
		AND EXISTS (SELECT ''x'' FROM cpMain 
					WHERE cpMain.ID = cpMainId 
					AND cpMain.ConsultantId IN(
						SELECT ID FROM ManagerUser WHERE Deptid=' + LTRIM(STR(@DeptId)) + ')
					)'
	SELECT @SQL = @SQL + '
		GROUP BY cpMainID
		HAVING COUNT(*) > 20
		ORDER BY COUNT(*) DESC, cpMainId'

	CREATE TABLE #t(
		cpMainID INT,
		Cnt INT,
		CompanyName NVARCHAR(50),
		LastLoginIp VARCHAR(31),
		LastLoginPlace NVARCHAR(50),
		LoginCookies VARCHAR(20),
		ConsultantID INT,
		Description NVARCHAR(1000),
		MemberType TINYINT,
		MemberDate SMALLDATETIME,
		Balance INT,
		IsLimitLogin TINYINT,
		RegDate SMALLDATETIME
	)
	--PRINT @SQL
	EXEC(@SQL)

	UPDATE a SET a.CompanyName = b.Name,
		a.IsLimitLogin = b.IsLimitLogin,
		a.ConsultantID = b.ConsultantID,
		a.Description = b.Description,
		a.MemberType = b.MemberType,
		a.RegDate = b.RegDate,
		a.MemberDate = CASE b.MemberType WHEN 10 THEN b.UnlimitedDate ELSE b.BalanceDate END,
		a.Balance = CASE b.MemberType WHEN 11 THEN b.Balance ELSE 0 END
	FROM #t a WITH(NOLOCK), cpMain b WITH(NOLOCK)
	WHERE a.cpMainID = b.Id

	UPDATE #t SET LastLoginIp = (SELECT TOP 1 a.LoginIp FROM caLoginLog a WITH(NOLOCK), caMain b WITH(NOLOCK) WHERE a.caMainID = b.ID AND b.cpMainId = #t.cpMainID),
		LoginCookies = (SELECT TOP 1 a.LoginCookies FROM caLoginLog a WITH(NOLOCK), caMain b WITH(NOLOCK) WHERE a.caMainID = b.ID AND b.cpMainId = #t.cpMainID)

	UPDATE #t SET LastLoginPlace = dbo.IpPlace(LastLoginIp)

	SELECT * FROM #t	
END














GO
/****** Object:  StoredProcedure [dbo].[bsCaFeedBackByIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- 创建日期:2010-9-19
-- 创建人：Lucifer
-- 功能：根据ID提取企业用户反馈表中的数据
-- 应用于/BackStage/Consultant/CompanyFeedBackReply.asp页面
-- 修改时间：
-- 修改人：
-- =============================================
CREATE PROCEDURE [dbo].[bsCaFeedBackByIDSelect]
    @ID INT
AS
BEGIN
    SELECT
        *
    FROM CaFeedBack WITH(NOLOCK)
    WHERE ID = @ID
END














GO
/****** Object:  StoredProcedure [dbo].[bsCaFeedBackHomePageUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- 创建日期:2010-9-19
-- 创建人：Lucifer
-- 功能：根据ID修改企业用户反馈表，是否放入首页
-- 应用于/BackStage/Consultant/CompanyFeedBackHomePage.asp页面
-- 修改时间：
-- 修改人：
-- =============================================
CREATE PROCEDURE [dbo].[bsCaFeedBackHomePageUpdate]
	@ID INT,
	@HomePage BIT
AS
BEGIN
	IF @HomePage = 0
		UPDATE caFeedBack SET HomePage=NULL
			WHERE ID=@ID
	ELSE
		UPDATE caFeedBack SET HomePage=1
			WHERE ID=@ID
END














GO
/****** Object:  StoredProcedure [dbo].[bsCaFeedBackReplyUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- 创建日期:2010-9-19
-- 创建人：Lucifer
-- 功能：答复企业用户的反馈
-- 应用于/BackStage/Consultant/CompanyFeedBackReplyProc.asp页面
-- 修改时间：2015-2-27
-- 修改人：harry
-- =============================================
CREATE PROCEDURE [dbo].[bsCaFeedBackReplyUpdate]
(
	@ID INT,
    @ReplyMan INT,
	@ReplyMessage NVARCHAR(2000),
	@HomePage BIT,
	@sendMsg INT
)
AS
BEGIN
	SET @ReplyMessage = dbo.SafeSql(@ReplyMessage)
	IF @HomePage = 0
		UPDATE caFeedBack SET ReplyMan=@ReplyMan,IsReply=1,ReplyDate=GETDATE(),ReplyMessage=@ReplyMessage,HomePage=NULL
		WHERE ID=@ID
	ELSE
		UPDATE caFeedBack SET ReplyMan=@ReplyMan,IsReply=1,ReplyDate=GETDATE(),ReplyMessage=@ReplyMessage,HomePage=1
		WHERE ID=@ID
	--短信发送
	IF @sendMsg = 1
	BEGIN
		INSERT SmsMessageLog(SendMan, ManagerUSerId, paMainId, caMainId, Mobile, MsgType, IsCat, Msg)
		SELECT  @ReplyMan, NULL, NULL, a.ID, a.Mobile, 6, 0, 
			ISNULL(a.Name,'') + '您好，您在' + c.subsitename + c.EmailSite + '上提出的问题已经答复，请及时登录网站查看，祝您招聘顺利！'
		FROM caMain a WITH(NOLOCK), cpMain b WITH(NOLOCK), dcSubSite c WITH(NOLOCK),caFeedBack d WITH(NOLOCK)
		WHERE a.cpMainID = b.ID
		AND b.dcSubSiteID = c.ID
		AND a.ID = d.caMainID
		AND a.Mobile > ''
		AND d.ID = @ID
		AND a.IsReceiveSms = 1
	END
END
GO
/****** Object:  StoredProcedure [dbo].[bsCaFeedBackSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[bsCaFeedBackSelect] 
(
	@WHERE VARCHAR(2000)
) 
AS 
BEGIN 
	DECLARE @SQL AS VARCHAR(2000)
	SET @Where = dbo.SafeSql(@Where)
	SET @SQL = 'SELECT TOP 2000 dbo.ReplyInterval(a.AddDate, ISNULL(a.ReplyDate, GETDATE())) ReplyInterval,a.ReplyDate,a.ID,a.Message content,a.AddDate,a.name,a.Telephone,a.Email,b.Name companyname,b.ID companyid,b.RegDate,b.dcProvinceID province_id,a.ViewDate seedate,b.ConsultantID manageruserid,a.ReplyMessage reply_content,a.HomePage,a.IP,d.status,d.name ManagerUserName
		FROM caFeedBack a WITH(NOLOCK) 
		INNER JOIN caMain c WITH(NOLOCK) ON c.ID=a.caMainID 
		INNER JOIN cpMain b WITH(NOLOCK) ON b.ID=c.cpMainID 
		LEFT JOIN Manageruser d WITH(NOLOCK) ON d.ID=b.ConsultantID
		WHERE 1=1' + @Where + '
		ORDER BY a.adddate DESC' 
	EXEC(@SQL) 
END

GO
/****** Object:  StoredProcedure [dbo].[bsCaMainUpdateByCaMainid]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--更新是否添加了qq好友，是否添加了微信好友
--创建人：harry
--2018-1-15
CREATE PROCEDURE [dbo].[bsCaMainUpdateByCaMainid]
(
	@type INT,
	@caMainId INT,
	@managerUserId INT
)
AS
BEGIN
	IF @type = 1--qq
	BEGIN
		UPDATE caMain 
		SET qqaddMan = @managerUserId
		WHERE id = @caMainId
	END
	ELSE
	BEGIN
		UPDATE caMain 
		SET wechataddMan = @managerUserId
		WHERE id = @caMainId
	END	
END

GO
/****** Object:  StoredProcedure [dbo].[bsCaOrderByIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*****20140721 nick update ****/
/*****20140805 lambo 增加InvoiceReConfirmDate,InvoiceReConfirmMan ****/
/*****20140822 mice  增加 PaidCoin PaidPoint******/
/*****2015-7-9 harry 增加 手动扣除的积分****/
/*****2017-11-11 harry 增加 职位刷新数****/
/*****2018-5-17 harry 增加 invoiceconfirmFile,isdocopen****/

CREATE PROCEDURE [dbo].[bsCaOrderByIDSelect]
(
	@ID INT
)
AS
BEGIN
	SELECT a.id cpmainid,a.ResumeQuota, b.SmsQuota,b.jobRefreshQuota, b.manageruserid manageruserid, a.dcSubSiteID, b.paid, b.dcFeeDetailID,a.dcregionID,
		b.placeweek, b.id orderid, b.activequota, b.jobnumber, b.Usernumber, a.UnlimitedDate, 
		a.id companyid, a.Name companyname, b.paymethod, b.provinceID, b.opendate, b.servicetype,
		b.linkman, a.ConsultantID, ReceiveMan, b.InvoiceCompany, a.Balance, a.BalanceDate, 
		b.telephone, b.linkremark, b.needinvoice, b.invoicetitle, b.mailaddress, b.recipient,
		b.zip, b.accounts, a.RegDate, b.OpenMan, b.BeginDate, b.EndDate, b.InvoiceMonth,
		b.ordertype, b.adddate, a.dcprovinceid, b.posttelephone, b.InvoiceConfirmDate, b.RemittanceFile,
		a.HasLicence, b.InvoiceAskDate, b.MainOrderID, b.InvoiceConfirmMan, b.receivedate, a.address,
		a.zip zip2, c.mobile, c.email caemail, a.dcRegionID, d.FullName, b.Tariff, b.RegisterAddress,
		b.RegisterTel, b.BankName, b.BankAccount, b.InvoiceReConfirmDate,b.InvoiceReConfirmMan,
		b.PaidCoin, b.PaidPoint, b.RemittanceDate,b.contractfile,
		(SELECT ISNULL(SUM(RemainQuota), 0) 
		FROM caOrder WITH(NOLOCK) 
		WHERE MainOrderID=b.MainOrderID
		Or ID = b.MainOrderID) caRemainQuota, 
		b.Balance OrderBalance, a.MemberType, c.ID caMainID,
		b.IsDeleted,b.invoiceconfirmFile,b.isdocopen
	FROM cpMain a WITH(NOLOCK), 
		caorder b WITH(NOLOCK), 
		camain c WITH(NOLOCK), 
		dcregion d with(NOLOCK)
	WHERE b.cpmainid = a.id and d.id = a.dcRegionID
	AND a.id = b.cpMainid 
	AND c.cpMainID = a.ID
	AND c.AccountType = 1
	AND b.id = @ID
END

GO
/****** Object:  StoredProcedure [dbo].[bsCaorderByPaidCoinUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
---后台订单修改支付金币
---harry-2017-10-19
CREATE PROCEDURE [dbo].[bsCaorderByPaidCoinUpdate]
(	
	@cpMainID INT,
 	@PaidCoin INT,
	@caOrderId INT
) 
AS
BEGIN
	IF EXISTS(SELECT 'X' FROM caorder WHERE ID = @caOrderId AND ISNULL(paidCoin,0)>0)
		RETURN
	DECLARE @RemainCoin INT 
	SELECT @RemainCoin = ISNULL(RemainCoin, 0) FROM cpMain WITH(NOLOCK) WHERE Id = @cpMainID
	IF(@RemainCoin<@PaidCoin)
		RETURN
	ELSE
	BEGIN
		UPDATE cpMain 
		SET RemainCoin = (RemainCoin-@PaidCoin)
		WHERE ID = @cpMainID
		
		UPDATE caorder
		SET PaidCoin = @PaidCoin
		WHERE ID = @caOrderId
	END
	
END

GO
/****** Object:  StoredProcedure [dbo].[bscaOrderCountByOpenDate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- 创建日期:2010-9-21
-- 创建人：Lucifer
-- 功能：根据订单的OpenDate来取某个招聘顾问在某一时间段的订单总金额
-- 应用于/BackStage/Consultant/ConsultantCheck.asp页面
-- 修改时间：
-- 修改人：
-- =============================================
CREATE PROCEDURE [dbo].[bscaOrderCountByOpenDate]
(
	@manageruserid INT,
	@BeginDate SMALLDATETIME,
	@EndDate SMALLDATETIME
)
AS
BEGIN
	SELECT SUM(Paid) cnt 
	FROM caOrder WITH(NOLOCK)
	WHERE Manageruserid=@manageruserid
	AND OpenDate BETWEEN @BeginDate AND @EndDate
	AND IsDeleted = 0
END














GO
/****** Object:  StoredProcedure [dbo].[bscaOrderCountByReceiveDate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- 创建日期:2010-9-21
-- 创建人：Lucifer
-- 功能：根据订单的ReceiveDate来取某个招聘顾问在某一时间段的订单总金额
-- 应用于/BackStage/Consultant/ConsultantCheck.asp页面
-- 修改时间：
-- 修改人：
-- =============================================
CREATE PROCEDURE [dbo].[bscaOrderCountByReceiveDate]
(
	@manageruserid INT,
	@BeginDate SMALLDATETIME,
	@EndDate SMALLDATETIME
)
AS
BEGIN
	SELECT SUM(Paid) cnt FROM caOrder WITH(NOLOCK) WHERE Manageruserid=@manageruserid
		AND OpenDate>@BeginDate AND OpenDate<@EndDate
END














GO
/****** Object:  StoredProcedure [dbo].[bsCaOrderDIYInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[bsCaOrderDIYInsert]
(
	@cpMainID INT,
	@caMainID INT,
	@ProvinceID INT,
	@ServiceType INT,
	@PlaceWeek TINYINT=NULL,
	@PayMethod TINYINT,
	@OrderType TINYINT,
	@Accounts NUMERIC(18,2),
	@Paid NUMERIC(18,2),
	@Balance NUMERIC(18,2)=NULL,
	@LinkMan NVARCHAR(50),
	@Telephone VARCHAR(50),
	@LinkRemark NVARCHAR(1000),
	@Manageruserid SMALLINT,
	@ActiveQuota SMALLINT=NULL,
	@JobNumber SMALLINT=NULL,
	@CompanyName VARCHAR(100),
	@MainOrderID INT=NULL,
	@InvoiceCompany SMALLINT,
	@NeedInvoice bit=null,
	@InvoiceTitle NVARCHAR(50)=null,
	@MailAddress NVARCHAR(100)=null,
	@Recipient NVARCHAR(100)=null,
	@PostTelephone NVARCHAR(50)=null,
	@Zip CHAR(6)=null,
	@InvoiceConfirmDate VARCHAR(20)=null,
	@InvoiceConfirmMan SMALLINT=null,
	@UserNumber SMALLINT=NULL,
	@dcFeeDetailsID INT=NULL
)
AS
BEGIN TRAN
	Declare @MaxId AS INT
	BEGIN TRY
		IF @InvoiceConfirmDate = ''
			SET @InvoiceConfirmDate = NULL
		IF @dcFeeDetailsID = 0 
			SET @dcFeeDetailsID = NULL
	
		IF @OrderType = 8 
		BEGIN
			IF NOT EXISTS(SELECT 'x' FROM dcVip a WITH(NOLOCK),dcVipDetail b WITH(NOLOCK) 
							WHERE a.ID = b.dcVipID AND a.dcProvinceID = LEFT(@ProvinceID,2) AND b.ID = @dcFeeDetailsID	AND a.startDate<GETDATE() AND a.endDate > GETDATE())
				GOTO ERR2	--检查是否套餐已过期
			
			DECLARE @MinResumeNumber AS INT,@MinJobNumber AS INT,@MinUserNumber AS INT,@MinPrice AS INT
			SELECT @Accounts = (b.PriceMonth * a.[Month]+@ActiveQuota*b.PriceResume+@JobNumber*b.PriceJob+@UserNumber*b.PriceUser),
					@Paid = (b.PriceMonth * a.[Month]+@ActiveQuota*b.PriceResume+@JobNumber*b.PriceJob+@UserNumber*b.PriceUser)*Discount/100,
					@MinResumeNumber = a.ResumeNumber,
					@MinJobNumber = a.JobNumber,
					@MinUserNumber = a.UserNumber,
					@MinPrice = a.Price
				FROM dcVipDetail a WITH(NOLOCK) ,dcVip b WITH(NOLOCK)
				WHERE a.ID = @dcFeeDetailsID
				AND StartDate < GETDATE() AND EndDate > GETDATE()
				AND a.dcVipID = b.ID
		
			IF @ActiveQuota < @MinResumeNumber OR @JobNumber < @MinJobNumber OR @UserNumber < @MinUserNumber OR @Paid < @MinPrice
				GOTO ERR1	--小于最低标准

			DECLARE @IsAgent AS BIT
			SELECT @IsAgent = IsAgent FROM cpMain WITH(NOLOCK) WHERE ID = @cpMainID
			IF @IsAgent = 1
				SET @Paid = @Accounts
		END

		INSERT INTO caOrder (cpMainID,ProvinceID,ServiceType,PlaceWeek,PayMethod,
		OrderType,Accounts,Paid,Balance,LinkMan,Telephone,LinkRemark,Manageruserid,ActiveQuota,RemainQuota,JobNumber,CompanyName,MainOrderID,InvoiceCompany,
		NeedInvoice,InvoiceTitle,MailAddress,Recipient,PostTelephone,Zip,InvoiceConfirmDate,InvoiceConfirmMan,UserNumber,dcFeeDetailID,IsBackSubmit)
		VALUES(@cpMainID,@ProvinceID,@ServiceType,@PlaceWeek,@PayMethod,
		@OrderType,@Accounts,@Paid,@Balance,@LinkMan,@Telephone,@LinkRemark,@Manageruserid,@ActiveQuota,@ActiveQuota,@JobNumber,@CompanyName,@MainOrderID,@InvoiceCompany,
		@NeedInvoice,@InvoiceTitle,@MailAddress,@Recipient,@PostTelephone,@Zip,@InvoiceConfirmDate,@InvoiceConfirmMan,@UserNumber,@dcFeeDetailsID,1)
		SET @MaxID = @@IDENTITY

		DECLARE @Temp AS NUMERIC(18,2)
		SET @Temp = @Paid -- 1 + CONVERT(NUMERIC(18,2),'0.'+RIGHT(STR(@cpMainID),2))
		UPDATE caOrder SET Paid = @Temp WHERE ID = @MaxID
	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH
COMMIT TRAN
RETURN @MaxID
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END
ERR1:
BEGIN
	ROLLBACK TRAN
	RETURN -2
END
ERR2:
BEGIN
	ROLLBACK TRAN
	RETURN -1
END








GO
/****** Object:  StoredProcedure [dbo].[bsCaOrderDIYInsert2]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- 修改记录: 2015.1.16 John 添加后台提交DIY订单使用金币
-- 修改：harry 增加短信数
-- 短信、刷新书为赠送。原价与实际都不计算在内
-- =============================================
CREATE PROCEDURE [dbo].[bsCaOrderDIYInsert2]
(
	@cpMainID INT,
	@caMainID INT,
	@ProvinceID INT,
	@ServiceType INT,
	@PlaceWeek TINYINT=NULL,
	@PayMethod TINYINT,
	@OrderType TINYINT,
	@Accounts NUMERIC(18,2),
	@Paid NUMERIC(18,2),
	@Balance NUMERIC(18,2)=NULL,
	@LinkMan NVARCHAR(50),
	@Telephone VARCHAR(50),
	@LinkRemark NVARCHAR(1000),
	@Manageruserid SMALLINT,
	@ActiveQuota SMALLINT=NULL,
	@JobNumber SMALLINT=NULL,
	@CompanyName VARCHAR(100),
	@MainOrderID INT=NULL,
	@InvoiceCompany SMALLINT,
	@NeedInvoice bit=null,
	@InvoiceTitle NVARCHAR(50)=null,
	@MailAddress NVARCHAR(100)=null,
	@Recipient NVARCHAR(100)=null,
	@PostTelephone NVARCHAR(50)=null,
	@Zip CHAR(6)=null,
	@InvoiceConfirmDate VARCHAR(20)=null,
	@InvoiceConfirmMan SMALLINT=null,
	@UserNumber SMALLINT=NULL,
	@dcFeeDetailsID INT=NULL,
	@UseCoin INT = NULL,
	@SmsNumber INT=NULL,
	@jobRefreshQuota INT=NULL
)
AS
SET NOCOUNT ON
BEGIN TRAN
	Declare @MaxId AS INT
	BEGIN TRY
		IF @InvoiceConfirmDate = ''
			SET @InvoiceConfirmDate = NULL
		IF @dcFeeDetailsID = 0 
			SET @dcFeeDetailsID = NULL
	
		IF @OrderType = 8 
		BEGIN
			IF NOT EXISTS(SELECT 'x' FROM dcVip a WITH(NOLOCK),dcVipDetail b WITH(NOLOCK) 
							WHERE a.ID = b.dcVipID AND a.dcProvinceID = LEFT(@ProvinceID,2) AND b.ID = @dcFeeDetailsID	AND a.startDate < GETDATE() AND a.endDate > GETDATE())
				GOTO ERR2	--检查是否套餐已过期
			
			DECLARE @MinResumeNumber AS INT,@MinJobNumber AS INT,@MinUserNumber AS INT,@MinPrice AS INT,@MinSmsNumber AS INT
			SELECT @Accounts = (b.PriceMonth * a.[Month]+@ActiveQuota*b.PriceResume+@JobNumber*b.PriceJob+@UserNumber*b.PriceUser),
			@Paid = (b.PriceMonth * a.[Month]+@ActiveQuota*b.PriceResume+@JobNumber*b.PriceJob+@UserNumber*b.PriceUser)*Discount/100,
					@MinResumeNumber = a.ResumeNumber,
					@MinJobNumber = a.JobNumber,
					@MinUserNumber = a.UserNumber,
					@MinSmsNumber = a.SmsNumber,
					@MinPrice = a.Price
				FROM dcVipDetail a WITH(NOLOCK) ,dcVip b WITH(NOLOCK)
				WHERE a.ID = @dcFeeDetailsID
				AND StartDate < GETDATE() AND EndDate > GETDATE()
				AND a.dcVipID = b.ID
		
			--IF @ActiveQuota < @MinResumeNumber OR @JobNumber < @MinJobNumber OR @UserNumber < @MinUserNumber OR @Paid < @MinPrice
			--	GOTO ERR1	--小于最低标准
--			IF @ActiveQuota < @MinResumeNumber 
--				SET @ActiveQuota = @MinResumeNumber 
--			IF @JobNumber < @MinJobNumber
--				SET @JobNumber = @MinJobNumber
--			IF @UserNumber < @MinUserNumber
--				SET @UserNumber = @MinUserNumber
			IF @Paid < @MinPrice
				SET @Paid = @MinPrice

			DECLARE @IsAgent AS BIT
			SELECT @IsAgent = IsAgent FROM cpMain WITH(NOLOCK) WHERE ID = @cpMainID
			IF @IsAgent = 1
				SET @Paid = @Accounts
			--金币支付
			DECLARE @CoinBalance AS INT
			IF @UseCoin IS NOT NULL
			BEGIN
				IF NOT EXISTS(SELECT 'x' FROM cpMain WHERE ID = @cpMainID AND RemainCoin >= @UseCoin)
					GOTO ERR	--检查剩余金币数量是否足够支付
				SET @Paid = @Paid - @UseCoin
			END
			IF @Paid < 0
				SET @Paid = 0
		END

		INSERT INTO caOrder (cpMainID,ProvinceID,ServiceType,PlaceWeek,PayMethod,
		OrderType,Accounts,Paid,Balance,LinkMan,Telephone,LinkRemark,Manageruserid,ActiveQuota,RemainQuota,JobNumber,CompanyName,MainOrderID,InvoiceCompany,
		NeedInvoice,InvoiceTitle,MailAddress,Recipient,PostTelephone,Zip,InvoiceConfirmDate,InvoiceConfirmMan,UserNumber,dcFeeDetailID,IsBackSubmit,PaidCoin,SmsQuota,RemainSmsQuota,jobRefreshQuota, remainJobRefreshQuota)
		VALUES(@cpMainID,@ProvinceID,@ServiceType,@PlaceWeek,@PayMethod,
		@OrderType,Convert(INT,@Accounts),@Paid,@Balance,@LinkMan,@Telephone,@LinkRemark,@Manageruserid,@ActiveQuota,@ActiveQuota,@JobNumber,@CompanyName,@MainOrderID,@InvoiceCompany,
		@NeedInvoice,@InvoiceTitle,@MailAddress,@Recipient,@PostTelephone,@Zip,@InvoiceConfirmDate,@InvoiceConfirmMan,@UserNumber,@dcFeeDetailsID,1,@UseCoin,@SmsNumber,@SmsNumber, @jobRefreshQuota,@jobRefreshQuota)
		SET @MaxID = @@IDENTITY

		DECLARE @Temp AS NUMERIC(18,2)
		SET @Temp = @Paid -- 1 + CONVERT(NUMERIC(18,2),'0.'+RIGHT(STR(@cpMainID),2))
		--金币或订单全额支付
		IF @Temp < 0
			SET @Temp = 0
		UPDATE caOrder SET Paid = @Temp WHERE ID = @MaxID
		IF @UseCoin IS NOT NULL 
		BEGIN
			--插入金币记录
			INSERT INTO cpCoin (cpMainID,caOrderID,Coin,Balance,AddDate)
			VALUES(@cpMainID,@MaxID,0-@UseCoin,0,GETDATE())
		END
	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH
COMMIT TRAN
RETURN @MaxID
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END
ERR1:
BEGIN
	ROLLBACK TRAN
	RETURN -2
END
ERR2:
BEGIN
	ROLLBACK TRAN
	RETURN -1
END 
  
GO
/****** Object:  StoredProcedure [dbo].[bsCaOrderInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[bsCaOrderInsert]
(
	@cpMainID INT,
	@caMainID INT,
	@ProvinceID INT,
	@ServiceType INT,
	@PlaceWeek TINYINT=NULL,
	@PayMethod TINYINT,
	@OrderType TINYINT,
	@Accounts NUMERIC(18,2),
	@Paid NUMERIC(18,2),
	@Balance NUMERIC(18,2)=NULL,
	@LinkMan NVARCHAR(50),
	@Telephone VARCHAR(50),
	@LinkRemark NVARCHAR(1000),
	@Manageruserid SMALLINT,
	@ActiveQuota SMALLINT=NULL,
	@JobNumber SMALLINT=NULL,
	@CompanyName VARCHAR(100),
	@MainOrderID INT=NULL,
	@InvoiceCompany SMALLINT,
	@NeedInvoice bit=null,
	@InvoiceTitle NVARCHAR(50)=null,
	@MailAddress NVARCHAR(100)=null,
	@Recipient NVARCHAR(100)=null,
	@PostTelephone NVARCHAR(50)=null,
	@Zip CHAR(6)=null,
	@InvoiceConfirmDate VARCHAR(20)=null,
	@InvoiceConfirmMan SMALLINT=null,
	@UserNumber SMALLINT=NULL,
	@dcFeeDetailsID INT=NULL
)
AS
IF @ManagerUserId = 0
	SET @ManagerUserId = NULL
BEGIN TRAN
	Declare @MaxId AS INT
	BEGIN TRY
		IF @InvoiceConfirmDate = ''
			SET @InvoiceConfirmDate = NULL
		IF @dcFeeDetailsID = 0 
			SET @dcFeeDetailsID = NULL
	
		IF NOT(@Paid = 0 AND @Accounts = 0)
		BEGIN
			IF @OrderType = 8 
			BEGIN
				IF NOT EXISTS(SELECT 'x' FROM dcVip a WITH(NOLOCK),dcVipDetail b WITH(NOLOCK) 
								WHERE a.ID = b.dcVipID AND a.dcProvinceID = LEFT(@ProvinceID,2) AND b.ID = @dcFeeDetailsID	AND a.startDate<GETDATE() AND a.endDate > GETDATE())
					GOTO ERR	--检查是否套餐已过期
				SELECT @Accounts = (b.PriceMonth * a.[Month]+a.ResumeNumber*b.PriceResume+JobNumber*b.PriceJob+UserNumber*b.PriceUser),
						@Paid = a.Price,
						@ActiveQuota = a.ResumeNumber,
						@JobNumber = a.JobNumber,
						@UserNumber = a.UserNumber 
					FROM dcVipDetail a WITH(NOLOCK) ,dcVip b WITH(NOLOCK)
					WHERE a.ID = @dcFeeDetailsID
					AND StartDate < GETDATE() AND EndDate > GETDATE()
					AND a.dcVipID = b.ID
			END 
			Else IF @OrderType = 4 AND @ServiceType=6			----根据周数查询1/6广告的资费信息
			BEGIN
				SELECT TOP 1 @Accounts = b.Price * @PlaceWeek,
						@Paid = a.Price * @PlaceWeek,
						@dcFeeDetailsID = a.ID
					FROM dcFeeDetail a WITH(NOLOCK) ,dcFee b WITH(NOLOCK)
					WHERE a.dcFeeID = b.ID
					AND b.dcProvinceID = LEFT(@ProvinceID,2)
					AND b.type = 4
					AND StartDate < GETDATE() AND EndDate > GETDATE()
					AND ((MinValue<=@PlaceWeek AND MaxValue>=@PlaceWeek) OR (MinValue<=@PlaceWeek AND MaxValue=0))
				IF @dcFeeDetailsID IS NULL
					SELECT TOP 1 @Accounts = Price,	@Paid = Price * @PlaceWeek
					FROM dcFee  WITH(NOLOCK)
					WHERE type = 4
					AND dcProvinceID = LEFT(@ProvinceID,2)
					AND StartDate < GETDATE() AND EndDate > GETDATE()
			END
			ELSE IF @OrderType = 4 AND @ServiceType=7			----根据周数查询2/6广告的资费信息
			BEGIN
				SELECT TOP 1 @Accounts = b.Price * @PlaceWeek,
						@Paid = a.Price * @PlaceWeek,
						@dcFeeDetailsID = a.ID
					FROM dcFeeDetail a WITH(NOLOCK) ,dcFee b WITH(NOLOCK)
					WHERE b.type = 5
					AND b.dcProvinceID = LEFT(@ProvinceID,2)
					AND StartDate < GETDATE() AND EndDate > GETDATE()
					AND ((MinValue<=@PlaceWeek AND MaxValue>=@PlaceWeek) OR (MinValue<=@PlaceWeek AND MaxValue=0))
					AND a.dcFeeID = b.ID
				IF @dcFeeDetailsID IS NULL
					SELECT TOP 1 @Accounts = Price,	@Paid = Price * @PlaceWeek
					FROM dcFee  WITH(NOLOCK)
					WHERE type = 5
					AND dcProvinceID = LEFT(@ProvinceID,2)
					AND StartDate < GETDATE() AND EndDate > GETDATE()
			END
			Else IF @OrderType = 4 AND @ServiceType=8			----根据周数查询3/6广告的资费信息
			BEGIN
				SELECT TOP 1 @Accounts = b.Price * @PlaceWeek,
						@Paid = a.Price * @PlaceWeek,
						@dcFeeDetailsID = a.ID
					FROM dcFeeDetail a WITH(NOLOCK) ,dcFee b WITH(NOLOCK)
					WHERE a.dcFeeID = b.ID
					AND b.dcProvinceID = LEFT(@ProvinceID,2)
					AND b.type = 20
					AND StartDate < GETDATE() AND EndDate > GETDATE()
					AND ((MinValue<=@PlaceWeek AND MaxValue>=@PlaceWeek) OR (MinValue<=@PlaceWeek AND MaxValue=0))
				IF @dcFeeDetailsID IS NULL
					SELECT TOP 1 @Accounts = Price,	@Paid = Price * @PlaceWeek
					FROM dcFee  WITH(NOLOCK)
					WHERE type = 20
					AND dcProvinceID = LEFT(@ProvinceID,2)
					AND StartDate < GETDATE() AND EndDate > GETDATE()
			END
			ELSE IF @OrderType = 4 AND @ServiceType=9			----根据周数查询6/6广告的资费信息
			BEGIN
				SELECT TOP 1 @Accounts = b.Price * @PlaceWeek,
						@Paid = a.Price * @PlaceWeek,
						@dcFeeDetailsID = a.ID
					FROM dcFeeDetail a WITH(NOLOCK) ,dcFee b WITH(NOLOCK)
					WHERE b.type = 21
					AND b.dcProvinceID = LEFT(@ProvinceID,2)
					AND StartDate < GETDATE() AND EndDate > GETDATE()
					AND ((MinValue<=@PlaceWeek AND MaxValue>=@PlaceWeek) OR (MinValue<=@PlaceWeek AND MaxValue=0))
					AND a.dcFeeID = b.ID
				IF @dcFeeDetailsID IS NULL
					SELECT TOP 1 @Accounts = Price,	@Paid = Price * @PlaceWeek
					FROM dcFee  WITH(NOLOCK)
					WHERE type = 21
					AND dcProvinceID = LEFT(@ProvinceID,2)
					AND StartDate < GETDATE() AND EndDate > GETDATE()
			END
			ELSE IF @OrderType = 4 AND @ServiceType=10			----根据周数查询6/6广告的资费信息
			BEGIN
				SELECT TOP 1 @Accounts = b.Price * @PlaceWeek,
						@Paid = a.Price * @PlaceWeek,
						@dcFeeDetailsID = a.ID
					FROM dcFeeDetail a WITH(NOLOCK) ,dcFee b WITH(NOLOCK)
					WHERE b.type = 23
					AND b.dcProvinceID = LEFT(@ProvinceID,2)
					AND StartDate < GETDATE() AND EndDate > GETDATE()
					AND ((MinValue<=@PlaceWeek AND MaxValue>=@PlaceWeek) OR (MinValue<=@PlaceWeek AND MaxValue=0))
					AND a.dcFeeID = b.ID
				IF @dcFeeDetailsID IS NULL
					SELECT TOP 1 @Accounts = Price,	@Paid = Price * @PlaceWeek
					FROM dcFee  WITH(NOLOCK)
					WHERE type = 23
					AND dcProvinceID = LEFT(@ProvinceID,2)
					AND StartDate < GETDATE() AND EndDate > GETDATE()
			END
			ELSE IF @OrderType =7								----根据周数查询固定位置的资费信息
			BEGIN
				SELECT TOP 1 @Accounts = b.Price * @PlaceWeek,
						@Paid = a.Price * @PlaceWeek,
						@dcFeeDetailsID = a.ID
					FROM dcFeeDetail a WITH(NOLOCK) ,dcFee b WITH(NOLOCK)
					WHERE b.type = 7
					AND a.dcFeeID = b.ID
					AND b.dcProvinceID = LEFT(@ProvinceID,2)
					AND ((MinValue<=@PlaceWeek AND MaxValue>=@PlaceWeek) OR (MinValue<=@PlaceWeek AND MaxValue=0))
					AND StartDate < GETDATE() AND EndDate > GETDATE()

				IF @dcFeeDetailsID IS NULL
					SELECT TOP 1 @Accounts = Price,	@Paid = Price * @PlaceWeek
					FROM dcFee  WITH(NOLOCK)
					WHERE type = 7
					AND dcProvinceID = LEFT(@ProvinceID,2)
					AND StartDate < GETDATE() AND EndDate > GETDATE()
			END
			ELSE IF @OrderType = 12								----根据周数查询职位置顶位置的资费信息
			BEGIN
				SELECT TOP 1 @Accounts = b.Price * @PlaceWeek,
						@Paid = a.Price * @PlaceWeek,
						@dcFeeDetailsID = a.ID
					FROM dcFeeDetail a WITH(NOLOCK) ,dcFee b WITH(NOLOCK)
					WHERE b.type = 22
					AND a.dcFeeID = b.ID
					AND b.dcProvinceID = LEFT(@ProvinceID,2)
					AND ((MinValue<=@PlaceWeek AND MaxValue>=@PlaceWeek) OR (MinValue<=@PlaceWeek AND MaxValue=0))
					AND StartDate < GETDATE() AND EndDate > GETDATE()

				IF @dcFeeDetailsID IS NULL
					SELECT TOP 1 @Accounts = Price,	@Paid = Price * @PlaceWeek
					FROM dcFee  WITH(NOLOCK)
					WHERE type = 22
					AND dcProvinceID = LEFT(@ProvinceID,2)
					AND StartDate < GETDATE() AND EndDate > GETDATE()
			END
			ELSE IF @OrderType = 13								----根据周数查询职位置顶位置的资费信息
			BEGIN
				SELECT TOP 1 @Accounts = b.Price * @PlaceWeek,
						@Paid = a.Price * @PlaceWeek,
						@dcFeeDetailsID = a.ID
					FROM dcFeeDetail a WITH(NOLOCK) ,dcFee b WITH(NOLOCK)
					WHERE b.type = 24
					AND a.dcFeeID = b.ID
					AND b.dcProvinceID = LEFT(@ProvinceID,2)
					AND ((MinValue<=@PlaceWeek AND MaxValue>=@PlaceWeek) OR (MinValue<=@PlaceWeek AND MaxValue=0))
					AND StartDate < GETDATE() AND EndDate > GETDATE()

				IF @dcFeeDetailsID IS NULL
					SELECT TOP 1 @Accounts = Price,	@Paid = Price * @PlaceWeek
					FROM dcFee  WITH(NOLOCK)
					WHERE type = 24
					AND dcProvinceID = LEFT(@ProvinceID,2)
					AND StartDate < GETDATE() AND EndDate > GETDATE()
			END
			ELSE IF @OrderType = 9 								----根据周数查询简历下载的资费信息
			BEGIN
				SELECT TOP 1 @Accounts = b.Price * @ActiveQuota,
						@Paid = a.Price * @ActiveQuota,
						@dcFeeDetailsID = a.ID
					FROM dcFeeDetail a WITH(NOLOCK) ,dcFee b WITH(NOLOCK)
					WHERE b.type = 9
					AND a.dcFeeID = b.ID
					AND ((MinValue<=@ActiveQuota AND MaxValue>=@ActiveQuota) OR (MinValue<=@ActiveQuota AND MaxValue=0))
					AND StartDate < GETDATE() AND EndDate > GETDATE()

				IF @dcFeeDetailsID IS NULL
					SELECT TOP 1 @Accounts = Price,	@Paid = Price * @ActiveQuota
					FROM dcFee  WITH(NOLOCK)
					WHERE type = 9
					AND dcProvinceID = LEFT(@ProvinceID,2)
					AND StartDate < GETDATE() AND EndDate > GETDATE()
			END
			ELSE IF @OrderType = 10 								----根据周数查询职位数的资费信息
			BEGIN
				SELECT TOP 1 @Accounts = b.Price * @JobNumber,
						@Paid = a.Price * @JobNumber,
						@dcFeeDetailsID = a.ID
					FROM dcFeeDetail a WITH(NOLOCK) ,dcFee b WITH(NOLOCK)
					WHERE b.type = 10
					AND a.dcFeeID = b.ID
					AND b.dcProvinceID = LEFT(@ProvinceID,2)
					AND ((MinValue<=@JobNumber AND MaxValue>=@JobNumber) OR (MinValue<=@JobNumber AND MaxValue=0))
					AND StartDate < GETDATE() AND EndDate > GETDATE()

				IF @dcFeeDetailsID IS NULL
					SELECT TOP 1 @Accounts = Price,	@Paid = Price * @JobNumber
					FROM dcFee  WITH(NOLOCK)
					WHERE type = 10
					AND dcProvinceID = LEFT(@ProvinceID,2)
					AND StartDate < GETDATE() AND EndDate > GETDATE()
			END		
			ELSE IF @OrderType = 11								----根据周数查询用户数的资费信息
			BEGIN
				SELECT TOP 1 @Accounts = b.Price * @UserNumber,
						@Paid = a.Price * @UserNumber,
						@dcFeeDetailsID = a.ID
					FROM dcFeeDetail a WITH(NOLOCK) ,dcFee b WITH(NOLOCK)
					WHERE b.type = 11
					AND a.dcFeeID = b.ID
					AND b.dcProvinceID = LEFT(@ProvinceID,2)
					AND ((MinValue<=@UserNumber AND MaxValue>=@UserNumber) OR (MinValue<=@UserNumber AND MaxValue=0))
					AND StartDate < GETDATE() AND EndDate > GETDATE()

				IF @dcFeeDetailsID IS NULL
					SELECT TOP 1 @Accounts = Price,	@Paid = Price * @UserNumber
					FROM dcFee  WITH(NOLOCK)
					WHERE type = 11
					AND dcProvinceID = LEFT(@ProvinceID,2)
					AND StartDate < GETDATE() AND EndDate > GETDATE()
			END
		END
		ELSE
		BEGIN
			IF @OrderType = 8 
			BEGIN
				IF NOT EXISTS(SELECT 'x' FROM dcVip a WITH(NOLOCK),dcVipDetail b WITH(NOLOCK) 
								WHERE a.ID = b.dcVipID AND a.dcProvinceID = LEFT(@ProvinceID,2) AND b.ID = @dcFeeDetailsID	AND a.startDate<GETDATE() AND a.endDate > GETDATE())
					GOTO ERR	--检查是否套餐已过期
				SELECT @Accounts = (b.PriceMonth * a.[Month]+a.ResumeNumber*b.PriceResume+JobNumber*b.PriceJob+UserNumber*b.PriceUser),
						@dcFeeDetailsID = a.Price
					FROM dcVipDetail a WITH(NOLOCK) ,dcVip b WITH(NOLOCK)
					WHERE a.ID = @dcFeeDetailsID
					AND StartDate < GETDATE() AND EndDate > GETDATE()
					AND a.dcVipID = b.ID
			END 
			Else IF @OrderType = 4 AND @ServiceType=6			----根据周数查询1/6广告的资费信息
			BEGIN
				SELECT TOP 1 @Accounts = b.Price * @PlaceWeek,
						@dcFeeDetailsID = a.ID
					FROM dcFeeDetail a WITH(NOLOCK) ,dcFee b WITH(NOLOCK)
					WHERE a.dcFeeID = b.ID
					AND b.dcProvinceID = LEFT(@ProvinceID,2)
					AND b.type = 4
					AND StartDate < GETDATE() AND EndDate > GETDATE()
					AND ((MinValue<=@PlaceWeek AND MaxValue>=@PlaceWeek) OR (MinValue<=@PlaceWeek AND MaxValue=0))
				IF @dcFeeDetailsID IS NULL
					SELECT TOP 1 @Accounts = Price
					FROM dcFee  WITH(NOLOCK)
					WHERE type = 4
					AND dcProvinceID = LEFT(@ProvinceID,2)
					AND StartDate < GETDATE() AND EndDate > GETDATE()
			END
			ELSE IF @OrderType = 4 AND @ServiceType=7			----根据周数查询2/6广告的资费信息
			BEGIN
				SELECT TOP 1 @Accounts = b.Price * @PlaceWeek,
						@dcFeeDetailsID = a.ID
					FROM dcFeeDetail a WITH(NOLOCK) ,dcFee b WITH(NOLOCK)
					WHERE b.type = 5
					AND b.dcProvinceID = LEFT(@ProvinceID,2)
					AND StartDate < GETDATE() AND EndDate > GETDATE()
					AND ((MinValue<=@PlaceWeek AND MaxValue>=@PlaceWeek) OR (MinValue<=@PlaceWeek AND MaxValue=0))
					AND a.dcFeeID = b.ID
				IF @dcFeeDetailsID IS NULL
					SELECT TOP 1 @Accounts = Price
					FROM dcFee  WITH(NOLOCK)
					WHERE type = 5
					AND dcProvinceID = LEFT(@ProvinceID,2)
					AND StartDate < GETDATE() AND EndDate > GETDATE()
			END
			Else IF @OrderType = 4 AND @ServiceType=8			----根据周数查询3/6广告的资费信息
			BEGIN
				SELECT TOP 1 @Accounts = b.Price * @PlaceWeek,
						@dcFeeDetailsID = a.ID
					FROM dcFeeDetail a WITH(NOLOCK) ,dcFee b WITH(NOLOCK)
					WHERE a.dcFeeID = b.ID
					AND b.dcProvinceID = LEFT(@ProvinceID,2)
					AND b.type = 20
					AND StartDate < GETDATE() AND EndDate > GETDATE()
					AND ((MinValue<=@PlaceWeek AND MaxValue>=@PlaceWeek) OR (MinValue<=@PlaceWeek AND MaxValue=0))
				IF @dcFeeDetailsID IS NULL
					SELECT TOP 1 @Accounts = Price
					FROM dcFee  WITH(NOLOCK)
					WHERE type = 20
					AND dcProvinceID = LEFT(@ProvinceID,2)
					AND StartDate < GETDATE() AND EndDate > GETDATE()
			END
			ELSE IF @OrderType = 4 AND @ServiceType=9			----根据周数查询6/6广告的资费信息
			BEGIN
				SELECT TOP 1 @Accounts = b.Price * @PlaceWeek,
						@dcFeeDetailsID = a.ID
					FROM dcFeeDetail a WITH(NOLOCK) ,dcFee b WITH(NOLOCK)
					WHERE b.type = 21
					AND b.dcProvinceID = LEFT(@ProvinceID,2)
					AND StartDate < GETDATE() AND EndDate > GETDATE()
					AND ((MinValue<=@PlaceWeek AND MaxValue>=@PlaceWeek) OR (MinValue<=@PlaceWeek AND MaxValue=0))
					AND a.dcFeeID = b.ID
				IF @dcFeeDetailsID IS NULL
					SELECT TOP 1 @Accounts = Price
					FROM dcFee  WITH(NOLOCK)
					WHERE type = 21
					AND dcProvinceID = LEFT(@ProvinceID,2)
					AND StartDate < GETDATE() AND EndDate > GETDATE()
			END
			ELSE IF @OrderType = 4 AND @ServiceType=10			----根据周数查询6/6广告的资费信息
			BEGIN
				SELECT TOP 1 @Accounts = b.Price * @PlaceWeek,
						@dcFeeDetailsID = a.ID
					FROM dcFeeDetail a WITH(NOLOCK) ,dcFee b WITH(NOLOCK)
					WHERE b.type = 23
					AND b.dcProvinceID = LEFT(@ProvinceID,2)
					AND StartDate < GETDATE() AND EndDate > GETDATE()
					AND ((MinValue<=@PlaceWeek AND MaxValue>=@PlaceWeek) OR (MinValue<=@PlaceWeek AND MaxValue=0))
					AND a.dcFeeID = b.ID
				IF @dcFeeDetailsID IS NULL
					SELECT TOP 1 @Accounts = Price
					FROM dcFee  WITH(NOLOCK)
					WHERE type = 23
					AND dcProvinceID = LEFT(@ProvinceID,2)
					AND StartDate < GETDATE() AND EndDate > GETDATE()
			END
			ELSE IF @OrderType =7								----根据周数查询固定位置的资费信息
			BEGIN
				SELECT TOP 1 @Accounts = b.Price * @PlaceWeek,
						@dcFeeDetailsID = a.ID
					FROM dcFeeDetail a WITH(NOLOCK) ,dcFee b WITH(NOLOCK)
					WHERE b.type = 7
					AND a.dcFeeID = b.ID
					AND b.dcProvinceID = LEFT(@ProvinceID,2)
					AND ((MinValue<=@PlaceWeek AND MaxValue>=@PlaceWeek) OR (MinValue<=@PlaceWeek AND MaxValue=0))
					AND StartDate < GETDATE() AND EndDate > GETDATE()

				IF @dcFeeDetailsID IS NULL
					SELECT TOP 1 @Accounts = Price
					FROM dcFee  WITH(NOLOCK)
					WHERE type = 7
					AND dcProvinceID = LEFT(@ProvinceID,2)
					AND StartDate < GETDATE() AND EndDate > GETDATE()
			END
			ELSE IF @OrderType = 12								----根据周数查询职位置顶位置的资费信息
			BEGIN
				SELECT TOP 1 @Accounts = b.Price * @PlaceWeek,
						@dcFeeDetailsID = a.ID
					FROM dcFeeDetail a WITH(NOLOCK) ,dcFee b WITH(NOLOCK)
					WHERE b.type = 22
					AND a.dcFeeID = b.ID
					AND b.dcProvinceID = LEFT(@ProvinceID,2)
					AND ((MinValue<=@PlaceWeek AND MaxValue>=@PlaceWeek) OR (MinValue<=@PlaceWeek AND MaxValue=0))
					AND StartDate < GETDATE() AND EndDate > GETDATE()

				IF @dcFeeDetailsID IS NULL
					SELECT TOP 1 @Accounts = Price
					FROM dcFee  WITH(NOLOCK)
					WHERE type = 22
					AND dcProvinceID = LEFT(@ProvinceID,2)
					AND StartDate < GETDATE() AND EndDate > GETDATE()
			END
			ELSE IF @OrderType = 13								----根据周数查询职位置顶位置的资费信息
			BEGIN
				SELECT TOP 1 @Accounts = b.Price * @PlaceWeek,
						@dcFeeDetailsID = a.ID
					FROM dcFeeDetail a WITH(NOLOCK) ,dcFee b WITH(NOLOCK)
					WHERE b.type = 24
					AND a.dcFeeID = b.ID
					AND b.dcProvinceID = LEFT(@ProvinceID,2)
					AND ((MinValue<=@PlaceWeek AND MaxValue>=@PlaceWeek) OR (MinValue<=@PlaceWeek AND MaxValue=0))
					AND StartDate < GETDATE() AND EndDate > GETDATE()

				IF @dcFeeDetailsID IS NULL
					SELECT TOP 1 @Accounts = Price
					FROM dcFee  WITH(NOLOCK)
					WHERE type = 24
					AND dcProvinceID = LEFT(@ProvinceID,2)
					AND StartDate < GETDATE() AND EndDate > GETDATE()
			END
			ELSE IF @OrderType = 9 								----根据周数查询简历下载的资费信息
			BEGIN
				SELECT TOP 1 @Accounts = b.Price * @ActiveQuota,
						@dcFeeDetailsID = a.ID
					FROM dcFeeDetail a WITH(NOLOCK) ,dcFee b WITH(NOLOCK)
					WHERE b.type = 9
					AND a.dcFeeID = b.ID
					AND ((MinValue<=@ActiveQuota AND MaxValue>=@ActiveQuota) OR (MinValue<=@ActiveQuota AND MaxValue=0))
					AND StartDate < GETDATE() AND EndDate > GETDATE()

				IF @dcFeeDetailsID IS NULL
					SELECT TOP 1 @Accounts = Price
					FROM dcFee  WITH(NOLOCK)
					WHERE type = 9
					AND dcProvinceID = LEFT(@ProvinceID,2)
					AND StartDate < GETDATE() AND EndDate > GETDATE()
			END
			ELSE IF @OrderType = 10 								----根据周数查询职位数的资费信息
			BEGIN
				SELECT TOP 1 @Accounts = b.Price * @JobNumber,
						@dcFeeDetailsID = a.ID
					FROM dcFeeDetail a WITH(NOLOCK) ,dcFee b WITH(NOLOCK)
					WHERE b.type = 10
					AND a.dcFeeID = b.ID
					AND b.dcProvinceID = LEFT(@ProvinceID,2)
					AND ((MinValue<=@JobNumber AND MaxValue>=@JobNumber) OR (MinValue<=@JobNumber AND MaxValue=0))
					AND StartDate < GETDATE() AND EndDate > GETDATE()

				IF @dcFeeDetailsID IS NULL
					SELECT TOP 1 @Accounts = Price
					FROM dcFee  WITH(NOLOCK)
					WHERE type = 10
					AND dcProvinceID = LEFT(@ProvinceID,2)
					AND StartDate < GETDATE() AND EndDate > GETDATE()
			END		
			ELSE IF @OrderType = 11								----根据周数查询用户数的资费信息
			BEGIN
				SELECT TOP 1 @Accounts = b.Price * @UserNumber,
						@dcFeeDetailsID = a.ID
					FROM dcFeeDetail a WITH(NOLOCK) ,dcFee b WITH(NOLOCK)
					WHERE b.type = 11
					AND a.dcFeeID = b.ID
					AND b.dcProvinceID = LEFT(@ProvinceID,2)
					AND ((MinValue<=@UserNumber AND MaxValue>=@UserNumber) OR (MinValue<=@UserNumber AND MaxValue=0))
					AND StartDate < GETDATE() AND EndDate > GETDATE()

				IF @dcFeeDetailsID IS NULL
					SELECT TOP 1 @Accounts = Price
					FROM dcFee  WITH(NOLOCK)
					WHERE type = 11
					AND dcProvinceID = LEFT(@ProvinceID,2)
					AND StartDate < GETDATE() AND EndDate > GETDATE()
			END
		END
		IF @MainOrderID IS NOT NULL
			IF NOT EXISTS(SELECT 'x' FROM caOrder WITH(NOLOCK) WHERE cpMainID = @cpMainID AND ID = @MainOrderID  AND OrderType = 8 AND EndDate >GETDATE())
				AND @OrderType in (9,10,11)
				GOTO ERR	--检查是否是自己有效的主订单号

		INSERT INTO caOrder (cpMainID,ProvinceID,ServiceType,PlaceWeek,PayMethod,
		OrderType,Accounts,Paid,Balance,LinkMan,Telephone,LinkRemark,Manageruserid,ActiveQuota,RemainQuota,JobNumber,CompanyName,MainOrderID,InvoiceCompany,
		NeedInvoice,InvoiceTitle,MailAddress,Recipient,PostTelephone,Zip,InvoiceConfirmDate,InvoiceConfirmMan,UserNumber,dcFeeDetailID,IsBackSubmit)
		VALUES(@cpMainID,@ProvinceID,@ServiceType,@PlaceWeek,@PayMethod,
		@OrderType,@Accounts,@Paid,@Balance,@LinkMan,@Telephone,@LinkRemark,@Manageruserid,@ActiveQuota,@ActiveQuota,@JobNumber,@CompanyName,@MainOrderID,@InvoiceCompany,
		@NeedInvoice,@InvoiceTitle,@MailAddress,@Recipient,@PostTelephone,@Zip,@InvoiceConfirmDate,@InvoiceConfirmMan,@UserNumber,@dcFeeDetailsID,1)
		SET @MaxID = @@IDENTITY
		IF @Paid != 0
		BEGIN
			DECLARE @Temp AS NUMERIC(18,2)
			SET @Temp = @Paid -- 1 + CONVERT(NUMERIC(18,2),'0.'+RIGHT(STR(@cpMainID),2))
			UPDATE caOrder SET Paid = @Temp WHERE ID = @MaxID
		END
	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH
COMMIT TRAN
RETURN @MaxID
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END











GO
/****** Object:  StoredProcedure [dbo].[bsCaOrderInsert2]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- 修改记录: 2015.1.15 John 添加后台提交订单使用金币
-- 修改记录：2017.6.8 Harry 添加后台提交短信订单
-- 修改记录：2017.11.17 Harry 添加后台提交职位刷新数订单
-- =============================================
CREATE PROCEDURE [dbo].[bsCaOrderInsert2]
(
	@cpMainID INT,
	@caMainID INT,
	@ProvinceID INT,
	@ServiceType INT,
	@PlaceWeek TINYINT=NULL,
	@PayMethod TINYINT,
	@OrderType TINYINT,
	@Accounts NUMERIC(18,2),
	@Paid NUMERIC(18,2),
	@Balance NUMERIC(18,2)=NULL,
	@LinkMan NVARCHAR(50),
	@Telephone VARCHAR(50),
	@LinkRemark NVARCHAR(1000),
	@Manageruserid SMALLINT,
	@ActiveQuota SMALLINT=NULL,
	@JobNumber SMALLINT=NULL,
	@CompanyName VARCHAR(100),
	@MainOrderID INT=NULL,
	@InvoiceCompany SMALLINT,
	@NeedInvoice bit=null,
	@InvoiceTitle NVARCHAR(50)=null,
	@MailAddress NVARCHAR(100)=null,
	@Recipient NVARCHAR(100)=null,
	@PostTelephone NVARCHAR(50)=null,
	@Zip CHAR(6)=null,
	@InvoiceConfirmDate VARCHAR(20)=null,
	@InvoiceConfirmMan SMALLINT=null,
	@UserNumber SMALLINT=NULL,
	@dcFeeDetailsID INT=NULL,
	@UseCoin INT=NULL,
	@SmsQuota INT=NULL,
	@jobRefreshQuota INT=NULL
)
AS
SET NOCOUNT ON
IF @ManagerUserId = 0
	SET @ManagerUserId = NULL
BEGIN TRAN
	Declare @MaxId AS INT
	--BEGIN TRY
		IF @InvoiceConfirmDate = ''
			SET @InvoiceConfirmDate = NULL
		IF @dcFeeDetailsID = 0 
			SET @dcFeeDetailsID = NULL
	
		IF NOT(@Paid = 0 AND @Accounts = 0)
		BEGIN
			IF @OrderType = 8 
			BEGIN
				IF NOT EXISTS(SELECT 'x' FROM dcVip a WITH(NOLOCK),dcVipDetail b WITH(NOLOCK) 
								WHERE a.ID = b.dcVipID AND a.dcProvinceID = LEFT(@ProvinceID,2) AND b.ID = @dcFeeDetailsID AND a.startDate<GETDATE() AND a.endDate > GETDATE())
					GOTO ERR	--检查是否套餐已过期
				SELECT @Accounts = (b.PriceMonth * a.[Month]+a.ResumeNumber*b.PriceResume+JobNumber*b.PriceJob+UserNumber*b.PriceUser+isNULL(b.PriceSms,0)*ISNULL(SmsNumber,0)+isNULL(b.PriceJobRefreshNumber,0)*ISNULL(JobRefreshNumber,0)),
						@Paid = a.Price,
						@ActiveQuota = a.ResumeNumber,
						@JobNumber = a.JobNumber,
						@UserNumber = a.UserNumber,
						@SmsQuota = a.SmsNumber,
						@jobRefreshQuota =a.JobRefreshNumber
					FROM dcVipDetail a WITH(NOLOCK) ,dcVip b WITH(NOLOCK)
					WHERE a.ID = @dcFeeDetailsID
					AND StartDate < GETDATE() AND EndDate > GETDATE()
					AND a.dcVipID = b.ID
			END 
			Else IF @OrderType = 4 AND @ServiceType=6			----根据周数查询1/6广告的资费信息
			BEGIN
				SELECT TOP 1 @Accounts = b.Price * @PlaceWeek,
						@Paid = a.Price * @PlaceWeek,
						@dcFeeDetailsID = a.ID
					FROM dcFeeDetail a WITH(NOLOCK) ,dcFee b WITH(NOLOCK)
					WHERE a.dcFeeID = b.ID
					AND b.dcProvinceID = LEFT(@ProvinceID,2)
					AND b.type = 4
					AND StartDate < GETDATE() AND EndDate > GETDATE()
					AND ((MinValue<=@PlaceWeek AND MaxValue>=@PlaceWeek) OR (MinValue<=@PlaceWeek AND MaxValue=0))
				IF @dcFeeDetailsID IS NULL
					SELECT TOP 1 @Accounts = Price,	@Paid = Price * @PlaceWeek
					FROM dcFee  WITH(NOLOCK)
					WHERE type = 4
					AND dcProvinceID = LEFT(@ProvinceID,2)
					AND StartDate < GETDATE() AND EndDate > GETDATE()
			END
			ELSE IF @OrderType = 4 AND @ServiceType=7			----根据周数查询2/6广告的资费信息
			BEGIN
				SELECT TOP 1 @Accounts = b.Price * @PlaceWeek,
						@Paid = a.Price * @PlaceWeek,
						@dcFeeDetailsID = a.ID
					FROM dcFeeDetail a WITH(NOLOCK) ,dcFee b WITH(NOLOCK)
					WHERE b.type = 5
					AND b.dcProvinceID = LEFT(@ProvinceID,2)
					AND StartDate < GETDATE() AND EndDate > GETDATE()
					AND ((MinValue<=@PlaceWeek AND MaxValue>=@PlaceWeek) OR (MinValue<=@PlaceWeek AND MaxValue=0))
					AND a.dcFeeID = b.ID
				IF @dcFeeDetailsID IS NULL
					SELECT TOP 1 @Accounts = Price,	@Paid = Price * @PlaceWeek
					FROM dcFee  WITH(NOLOCK)
					WHERE type = 5
					AND dcProvinceID = LEFT(@ProvinceID,2)
					AND StartDate < GETDATE() AND EndDate > GETDATE()
			END
			Else IF @OrderType = 4 AND @ServiceType=8			----根据周数查询3/6广告的资费信息
			BEGIN
				SELECT TOP 1 @Accounts = b.Price * @PlaceWeek,
						@Paid = a.Price * @PlaceWeek,
						@dcFeeDetailsID = a.ID
					FROM dcFeeDetail a WITH(NOLOCK) ,dcFee b WITH(NOLOCK)
					WHERE a.dcFeeID = b.ID
					AND b.dcProvinceID = LEFT(@ProvinceID,2)
					AND b.type = 20
					AND StartDate < GETDATE() AND EndDate > GETDATE()
					AND ((MinValue<=@PlaceWeek AND MaxValue>=@PlaceWeek) OR (MinValue<=@PlaceWeek AND MaxValue=0))
				IF @dcFeeDetailsID IS NULL
					SELECT TOP 1 @Accounts = Price,	@Paid = Price * @PlaceWeek
					FROM dcFee  WITH(NOLOCK)
					WHERE type = 20
					AND dcProvinceID = LEFT(@ProvinceID,2)
					AND StartDate < GETDATE() AND EndDate > GETDATE()
			END
			ELSE IF @OrderType = 4 AND @ServiceType=9			----根据周数查询6/6广告的资费信息
			BEGIN
				SELECT TOP 1 @Accounts = b.Price * @PlaceWeek,
						@Paid = a.Price * @PlaceWeek,
						@dcFeeDetailsID = a.ID
					FROM dcFeeDetail a WITH(NOLOCK) ,dcFee b WITH(NOLOCK)
					WHERE b.type = 21
					AND b.dcProvinceID = LEFT(@ProvinceID,2)
					AND StartDate < GETDATE() AND EndDate > GETDATE()
					AND ((MinValue<=@PlaceWeek AND MaxValue>=@PlaceWeek) OR (MinValue<=@PlaceWeek AND MaxValue=0))
					AND a.dcFeeID = b.ID
				IF @dcFeeDetailsID IS NULL
					SELECT TOP 1 @Accounts = Price,	@Paid = Price * @PlaceWeek
					FROM dcFee  WITH(NOLOCK)
					WHERE type = 21
					AND dcProvinceID = LEFT(@ProvinceID,2)
					AND StartDate < GETDATE() AND EndDate > GETDATE()
			END
			ELSE IF @OrderType = 4 AND @ServiceType=10			----根据周数查询6/6广告的资费信息
			BEGIN
				SELECT TOP 1 @Accounts = b.Price * @PlaceWeek,
						@Paid = a.Price * @PlaceWeek,
						@dcFeeDetailsID = a.ID
					FROM dcFeeDetail a WITH(NOLOCK) ,dcFee b WITH(NOLOCK)
					WHERE b.type = 23
					AND b.dcProvinceID = LEFT(@ProvinceID,2)
					AND StartDate < GETDATE() AND EndDate > GETDATE()
					AND ((MinValue<=@PlaceWeek AND MaxValue>=@PlaceWeek) OR (MinValue<=@PlaceWeek AND MaxValue=0))
					AND a.dcFeeID = b.ID
				IF @dcFeeDetailsID IS NULL
					SELECT TOP 1 @Accounts = Price,	@Paid = Price * @PlaceWeek
					FROM dcFee  WITH(NOLOCK)
					WHERE type = 23
					AND dcProvinceID = LEFT(@ProvinceID,2)
					AND StartDate < GETDATE() AND EndDate > GETDATE()
			END
			ELSE IF @OrderType =7								----根据周数查询固定位置的资费信息
			BEGIN
				SELECT TOP 1 @Accounts = b.Price * @PlaceWeek,
						@Paid = a.Price * @PlaceWeek,
						@dcFeeDetailsID = a.ID
					FROM dcFeeDetail a WITH(NOLOCK) ,dcFee b WITH(NOLOCK)
					WHERE b.type = 7
					AND a.dcFeeID = b.ID
					AND b.dcProvinceID = LEFT(@ProvinceID,2)
					AND ((MinValue<=@PlaceWeek AND MaxValue>=@PlaceWeek) OR (MinValue<=@PlaceWeek AND MaxValue=0))
					AND StartDate < GETDATE() AND EndDate > GETDATE()

				IF @dcFeeDetailsID IS NULL
					SELECT TOP 1 @Accounts = Price,	@Paid = Price * @PlaceWeek
					FROM dcFee  WITH(NOLOCK)
					WHERE type = 7
					AND dcProvinceID = LEFT(@ProvinceID,2)
					AND StartDate < GETDATE() AND EndDate > GETDATE()
			END
			ELSE IF @OrderType = 12								----根据周数查询职位置顶位置的资费信息
			BEGIN
				SELECT TOP 1 @Accounts = b.Price * @PlaceWeek,
						@Paid = a.Price * @PlaceWeek,
						@dcFeeDetailsID = a.ID
					FROM dcFeeDetail a WITH(NOLOCK) ,dcFee b WITH(NOLOCK)
					WHERE b.type = 22
					AND a.dcFeeID = b.ID
					AND b.dcProvinceID = LEFT(@ProvinceID,2)
					AND ((MinValue<=@PlaceWeek AND MaxValue>=@PlaceWeek) OR (MinValue<=@PlaceWeek AND MaxValue=0))
					AND StartDate < GETDATE() AND EndDate > GETDATE()

				IF @dcFeeDetailsID IS NULL
					SELECT TOP 1 @Accounts = Price,	@Paid = Price * @PlaceWeek
					FROM dcFee  WITH(NOLOCK)
					WHERE type = 22
					AND dcProvinceID = LEFT(@ProvinceID,2)
					AND StartDate < GETDATE() AND EndDate > GETDATE()
			END
			ELSE IF @OrderType = 13								----根据周数查询职位置顶位置的资费信息
			BEGIN
				SELECT TOP 1 @Accounts = b.Price * @PlaceWeek,
						@Paid = a.Price * @PlaceWeek,
						@dcFeeDetailsID = a.ID
					FROM dcFeeDetail a WITH(NOLOCK) ,dcFee b WITH(NOLOCK)
					WHERE b.type = 24
					AND a.dcFeeID = b.ID
					AND b.dcProvinceID = LEFT(@ProvinceID,2)
					AND ((MinValue<=@PlaceWeek AND MaxValue>=@PlaceWeek) OR (MinValue<=@PlaceWeek AND MaxValue=0))
					AND StartDate < GETDATE() AND EndDate > GETDATE()

				IF @dcFeeDetailsID IS NULL
					SELECT TOP 1 @Accounts = Price,	@Paid = Price * @PlaceWeek
					FROM dcFee  WITH(NOLOCK)
					WHERE type = 24
					AND dcProvinceID = LEFT(@ProvinceID,2)
					AND StartDate < GETDATE() AND EndDate > GETDATE()
			END
			ELSE IF @OrderType = 9 								----根据周数查询简历下载的资费信息
			BEGIN
				SELECT TOP 1 @Accounts = b.Price * @ActiveQuota,
						@Paid = a.Price * @ActiveQuota,
						@dcFeeDetailsID = a.ID
					FROM dcFeeDetail a WITH(NOLOCK) ,dcFee b WITH(NOLOCK)
					WHERE b.type = 9
					AND a.dcFeeID = b.ID
					AND ((MinValue<=@ActiveQuota AND MaxValue>=@ActiveQuota) OR (MinValue<=@ActiveQuota AND MaxValue=0))
					AND StartDate < GETDATE() AND EndDate > GETDATE()

				IF @dcFeeDetailsID IS NULL
					SELECT TOP 1 @Accounts = Price,	@Paid = Price * @ActiveQuota
					FROM dcFee  WITH(NOLOCK)
					WHERE type = 9
					AND dcProvinceID = LEFT(@ProvinceID,2)
					AND StartDate < GETDATE() AND EndDate > GETDATE()
			END
			ELSE IF @OrderType = 10 								----根据周数查询职位数的资费信息
			BEGIN
				SELECT TOP 1 @Accounts = b.Price * @JobNumber,
						@Paid = a.Price * @JobNumber,
						@dcFeeDetailsID = a.ID
					FROM dcFeeDetail a WITH(NOLOCK) ,dcFee b WITH(NOLOCK)
					WHERE b.type = 10
					AND a.dcFeeID = b.ID
					AND b.dcProvinceID = LEFT(@ProvinceID,2)
					AND ((MinValue<=@JobNumber AND MaxValue>=@JobNumber) OR (MinValue<=@JobNumber AND MaxValue=0))
					AND StartDate < GETDATE() AND EndDate > GETDATE()

				IF @dcFeeDetailsID IS NULL
					SELECT TOP 1 @Accounts = Price,	@Paid = Price * @JobNumber
					FROM dcFee  WITH(NOLOCK)
					WHERE type = 10
					AND dcProvinceID = LEFT(@ProvinceID,2)
					AND StartDate < GETDATE() AND EndDate > GETDATE()
			END		
			ELSE IF @OrderType = 11								----根据周数查询用户数的资费信息
			BEGIN
				SELECT TOP 1 @Accounts = b.Price * @UserNumber,
						@Paid = a.Price * @UserNumber,
						@dcFeeDetailsID = a.ID
					FROM dcFeeDetail a WITH(NOLOCK) ,dcFee b WITH(NOLOCK)
					WHERE b.type = 11
					AND a.dcFeeID = b.ID
					AND b.dcProvinceID = LEFT(@ProvinceID,2)
					AND ((MinValue<=@UserNumber AND MaxValue>=@UserNumber) OR (MinValue<=@UserNumber AND MaxValue=0))
					AND StartDate < GETDATE() AND EndDate > GETDATE()

				IF @dcFeeDetailsID IS NULL
					SELECT TOP 1 @Accounts = Price,	@Paid = Price * @UserNumber
					FROM dcFee  WITH(NOLOCK)
					WHERE type = 11
					AND dcProvinceID = LEFT(@ProvinceID,2)
					AND StartDate < GETDATE() AND EndDate > GETDATE()
			END
			ELSE IF @OrderType = 14								----根据周数查询短信数的资费信息
			BEGIN
				SELECT TOP 1 @Accounts = b.Price * @SmsQuota,
						@Paid = a.Price * @SmsQuota,
						@dcFeeDetailsID = a.ID
					FROM dcFeeDetail a WITH(NOLOCK) ,dcFee b WITH(NOLOCK)
					WHERE b.type = 14
					AND a.dcFeeID = b.ID
					AND b.dcProvinceID = LEFT(@ProvinceID,2)
					AND ((MinValue<=@SmsQuota AND MaxValue>=@SmsQuota) OR (MinValue<=@SmsQuota AND MaxValue=0))
					AND StartDate < GETDATE() AND EndDate > GETDATE()

				IF @dcFeeDetailsID IS NULL
					SELECT TOP 1 @Accounts = Price,	@Paid = Price * @SmsQuota
					FROM dcFee  WITH(NOLOCK)
					WHERE type = 14
					AND dcProvinceID = LEFT(@ProvinceID,2)
					AND StartDate < GETDATE() AND EndDate > GETDATE()
			END 
			ELSE IF @OrderType = 15								----职位刷新数
			BEGIN
				SELECT TOP 1 @Accounts = b.Price * @jobRefreshQuota,
						@Paid = a.Price * @jobRefreshQuota,
						@dcFeeDetailsID = a.ID
					FROM dcFeeDetail a WITH(NOLOCK) ,dcFee b WITH(NOLOCK)
					WHERE b.type = 15
					AND a.dcFeeID = b.ID
					AND b.dcProvinceID = LEFT(@ProvinceID,2)
					AND ((MinValue<=@jobRefreshQuota AND MaxValue>=@jobRefreshQuota) OR (MinValue<=@jobRefreshQuota AND MaxValue=0))
					AND StartDate < GETDATE() AND EndDate > GETDATE()

				IF @dcFeeDetailsID IS NULL
					SELECT TOP 1 @Accounts = Price,	@Paid = Price * @jobRefreshQuota
					FROM dcFee  WITH(NOLOCK)
					WHERE type = 15
					AND dcProvinceID = LEFT(@ProvinceID,2)
					AND StartDate < GETDATE() AND EndDate > GETDATE()
			END
		END
		ELSE
		BEGIN
			IF @OrderType = 8 
			BEGIN
				IF NOT EXISTS(SELECT 'x' FROM dcVip a WITH(NOLOCK),dcVipDetail b WITH(NOLOCK) 
								WHERE a.ID = b.dcVipID AND a.dcProvinceID = LEFT(@ProvinceID,2) AND b.ID = @dcFeeDetailsID	AND a.startDate<GETDATE() AND a.endDate > GETDATE())
					GOTO ERR	--检查是否套餐已过期
				SELECT @Accounts = (b.PriceMonth * a.[Month]+a.ResumeNumber*b.PriceResume+JobNumber*b.PriceJob+UserNumber*b.PriceUser+ISNULL(SmsNumber,0)*ISNULL(b.PriceSms,0)+ISNULL(JobRefreshNumber,0)*ISNULL(b.PriceJobRefreshNumber,0)),
						@dcFeeDetailsID = a.Price
					FROM dcVipDetail a WITH(NOLOCK) ,dcVip b WITH(NOLOCK)
					WHERE a.ID = @dcFeeDetailsID
					AND StartDate < GETDATE() AND EndDate > GETDATE()
					AND a.dcVipID = b.ID
			END 
			Else IF @OrderType = 4 AND @ServiceType=6			----根据周数查询1/6广告的资费信息
			BEGIN
				SELECT TOP 1 @Accounts = b.Price * @PlaceWeek,
						@dcFeeDetailsID = a.ID
					FROM dcFeeDetail a WITH(NOLOCK) ,dcFee b WITH(NOLOCK)
					WHERE a.dcFeeID = b.ID
					AND b.dcProvinceID = LEFT(@ProvinceID,2)
					AND b.type = 4
					AND StartDate < GETDATE() AND EndDate > GETDATE()
					AND ((MinValue<=@PlaceWeek AND MaxValue>=@PlaceWeek) OR (MinValue<=@PlaceWeek AND MaxValue=0))
				IF @dcFeeDetailsID IS NULL
					SELECT TOP 1 @Accounts = Price
					FROM dcFee  WITH(NOLOCK)
					WHERE type = 4
					AND dcProvinceID = LEFT(@ProvinceID,2)
					AND StartDate < GETDATE() AND EndDate > GETDATE()
			END
			ELSE IF @OrderType = 4 AND @ServiceType=7			----根据周数查询2/6广告的资费信息
			BEGIN
				SELECT TOP 1 @Accounts = b.Price * @PlaceWeek,
						@dcFeeDetailsID = a.ID
					FROM dcFeeDetail a WITH(NOLOCK) ,dcFee b WITH(NOLOCK)
					WHERE b.type = 5
					AND b.dcProvinceID = LEFT(@ProvinceID,2)
					AND StartDate < GETDATE() AND EndDate > GETDATE()
					AND ((MinValue<=@PlaceWeek AND MaxValue>=@PlaceWeek) OR (MinValue<=@PlaceWeek AND MaxValue=0))
					AND a.dcFeeID = b.ID
				IF @dcFeeDetailsID IS NULL
					SELECT TOP 1 @Accounts = Price
					FROM dcFee  WITH(NOLOCK)
					WHERE type = 5
					AND dcProvinceID = LEFT(@ProvinceID,2)
					AND StartDate < GETDATE() AND EndDate > GETDATE()
			END
			Else IF @OrderType = 4 AND @ServiceType=8			----根据周数查询3/6广告的资费信息
			BEGIN
				SELECT TOP 1 @Accounts = b.Price * @PlaceWeek,
						@dcFeeDetailsID = a.ID
					FROM dcFeeDetail a WITH(NOLOCK) ,dcFee b WITH(NOLOCK)
					WHERE a.dcFeeID = b.ID
					AND b.dcProvinceID = LEFT(@ProvinceID,2)
					AND b.type = 20
					AND StartDate < GETDATE() AND EndDate > GETDATE()
					AND ((MinValue<=@PlaceWeek AND MaxValue>=@PlaceWeek) OR (MinValue<=@PlaceWeek AND MaxValue=0))
				IF @dcFeeDetailsID IS NULL
					SELECT TOP 1 @Accounts = Price
					FROM dcFee  WITH(NOLOCK)
					WHERE type = 20
					AND dcProvinceID = LEFT(@ProvinceID,2)
					AND StartDate < GETDATE() AND EndDate > GETDATE()
			END
			ELSE IF @OrderType = 4 AND @ServiceType=9			----根据周数查询6/6广告的资费信息
			BEGIN
				SELECT TOP 1 @Accounts = b.Price * @PlaceWeek,
						@dcFeeDetailsID = a.ID
					FROM dcFeeDetail a WITH(NOLOCK) ,dcFee b WITH(NOLOCK)
					WHERE b.type = 21
					AND b.dcProvinceID = LEFT(@ProvinceID,2)
					AND StartDate < GETDATE() AND EndDate > GETDATE()
					AND ((MinValue<=@PlaceWeek AND MaxValue>=@PlaceWeek) OR (MinValue<=@PlaceWeek AND MaxValue=0))
					AND a.dcFeeID = b.ID
				IF @dcFeeDetailsID IS NULL
					SELECT TOP 1 @Accounts = Price
					FROM dcFee  WITH(NOLOCK)
					WHERE type = 21
					AND dcProvinceID = LEFT(@ProvinceID,2)
					AND StartDate < GETDATE() AND EndDate > GETDATE()
			END
			ELSE IF @OrderType = 4 AND @ServiceType=10			----根据周数查询6/6广告的资费信息
			BEGIN
				SELECT TOP 1 @Accounts = b.Price * @PlaceWeek,
						@dcFeeDetailsID = a.ID
					FROM dcFeeDetail a WITH(NOLOCK) ,dcFee b WITH(NOLOCK)
					WHERE b.type = 23
					AND b.dcProvinceID = LEFT(@ProvinceID,2)
					AND StartDate < GETDATE() AND EndDate > GETDATE()
					AND ((MinValue<=@PlaceWeek AND MaxValue>=@PlaceWeek) OR (MinValue<=@PlaceWeek AND MaxValue=0))
					AND a.dcFeeID = b.ID
				IF @dcFeeDetailsID IS NULL
					SELECT TOP 1 @Accounts = Price
					FROM dcFee  WITH(NOLOCK)
					WHERE type = 23
					AND dcProvinceID = LEFT(@ProvinceID,2)
					AND StartDate < GETDATE() AND EndDate > GETDATE()
			END
			ELSE IF @OrderType =7								----根据周数查询固定位置的资费信息
			BEGIN
				SELECT TOP 1 @Accounts = b.Price * @PlaceWeek,
						@dcFeeDetailsID = a.ID
					FROM dcFeeDetail a WITH(NOLOCK) ,dcFee b WITH(NOLOCK)
					WHERE b.type = 7
					AND a.dcFeeID = b.ID
					AND b.dcProvinceID = LEFT(@ProvinceID,2)
					AND ((MinValue<=@PlaceWeek AND MaxValue>=@PlaceWeek) OR (MinValue<=@PlaceWeek AND MaxValue=0))
					AND StartDate < GETDATE() AND EndDate > GETDATE()

				IF @dcFeeDetailsID IS NULL
					SELECT TOP 1 @Accounts = Price
					FROM dcFee  WITH(NOLOCK)
					WHERE type = 7
					AND dcProvinceID = LEFT(@ProvinceID,2)
					AND StartDate < GETDATE() AND EndDate > GETDATE()
			END
			ELSE IF @OrderType = 12								----根据周数查询职位置顶位置的资费信息
			BEGIN
				SELECT TOP 1 @Accounts = b.Price * @PlaceWeek,
						@dcFeeDetailsID = a.ID
					FROM dcFeeDetail a WITH(NOLOCK) ,dcFee b WITH(NOLOCK)
					WHERE b.type = 22
					AND a.dcFeeID = b.ID
					AND b.dcProvinceID = LEFT(@ProvinceID,2)
					AND ((MinValue<=@PlaceWeek AND MaxValue>=@PlaceWeek) OR (MinValue<=@PlaceWeek AND MaxValue=0))
					AND StartDate < GETDATE() AND EndDate > GETDATE()

				IF @dcFeeDetailsID IS NULL
					SELECT TOP 1 @Accounts = Price
					FROM dcFee  WITH(NOLOCK)
					WHERE type = 22
					AND dcProvinceID = LEFT(@ProvinceID,2)
					AND StartDate < GETDATE() AND EndDate > GETDATE()
			END
			ELSE IF @OrderType = 13								----根据周数查询职位置顶位置的资费信息
			BEGIN
				SELECT TOP 1 @Accounts = b.Price * @PlaceWeek,
						@dcFeeDetailsID = a.ID
					FROM dcFeeDetail a WITH(NOLOCK) ,dcFee b WITH(NOLOCK)
					WHERE b.type = 24
					AND a.dcFeeID = b.ID
					AND b.dcProvinceID = LEFT(@ProvinceID,2)
					AND ((MinValue<=@PlaceWeek AND MaxValue>=@PlaceWeek) OR (MinValue<=@PlaceWeek AND MaxValue=0))
					AND StartDate < GETDATE() AND EndDate > GETDATE()

				IF @dcFeeDetailsID IS NULL
					SELECT TOP 1 @Accounts = Price
					FROM dcFee  WITH(NOLOCK)
					WHERE type = 24
					AND dcProvinceID = LEFT(@ProvinceID,2)
					AND StartDate < GETDATE() AND EndDate > GETDATE()
			END
			ELSE IF @OrderType = 9 								----根据周数查询简历下载的资费信息
			BEGIN
				SELECT TOP 1 @Accounts = b.Price * @ActiveQuota,
						@dcFeeDetailsID = a.ID
					FROM dcFeeDetail a WITH(NOLOCK) ,dcFee b WITH(NOLOCK)
					WHERE b.type = 9
					AND a.dcFeeID = b.ID
					AND ((MinValue<=@ActiveQuota AND MaxValue>=@ActiveQuota) OR (MinValue<=@ActiveQuota AND MaxValue=0))
					AND StartDate < GETDATE() AND EndDate > GETDATE()

				IF @dcFeeDetailsID IS NULL
					SELECT TOP 1 @Accounts = Price
					FROM dcFee  WITH(NOLOCK)
					WHERE type = 9
					AND dcProvinceID = LEFT(@ProvinceID,2)
					AND StartDate < GETDATE() AND EndDate > GETDATE()
			END
			ELSE IF @OrderType = 10 								----根据周数查询职位数的资费信息
			BEGIN
				SELECT TOP 1 @Accounts = b.Price * @JobNumber,
						@dcFeeDetailsID = a.ID
					FROM dcFeeDetail a WITH(NOLOCK) ,dcFee b WITH(NOLOCK)
					WHERE b.type = 10
					AND a.dcFeeID = b.ID
					AND b.dcProvinceID = LEFT(@ProvinceID,2)
					AND ((MinValue<=@JobNumber AND MaxValue>=@JobNumber) OR (MinValue<=@JobNumber AND MaxValue=0))
					AND StartDate < GETDATE() AND EndDate > GETDATE()

				IF @dcFeeDetailsID IS NULL
					SELECT TOP 1 @Accounts = Price
					FROM dcFee  WITH(NOLOCK)
					WHERE type = 10
					AND dcProvinceID = LEFT(@ProvinceID,2)
					AND StartDate < GETDATE() AND EndDate > GETDATE()
			END		
			ELSE IF @OrderType = 11								----根据周数查询用户数的资费信息
			BEGIN
				SELECT TOP 1 @Accounts = b.Price * @UserNumber,
						@dcFeeDetailsID = a.ID
					FROM dcFeeDetail a WITH(NOLOCK) ,dcFee b WITH(NOLOCK)
					WHERE b.type = 11
					AND a.dcFeeID = b.ID
					AND b.dcProvinceID = LEFT(@ProvinceID,2)
					AND ((MinValue<=@UserNumber AND MaxValue>=@UserNumber) OR (MinValue<=@UserNumber AND MaxValue=0))
					AND StartDate < GETDATE() AND EndDate > GETDATE()

				IF @dcFeeDetailsID IS NULL
					SELECT TOP 1 @Accounts = Price
					FROM dcFee  WITH(NOLOCK)
					WHERE type = 11
					AND dcProvinceID = LEFT(@ProvinceID,2)
					AND StartDate < GETDATE() AND EndDate > GETDATE()
			END
			ELSE IF @OrderType = 14								----根据周数查询短信数的资费信息
			BEGIN
				SELECT TOP 1 @Accounts = b.Price * @SmsQuota,
						@dcFeeDetailsID = a.ID
					FROM dcFeeDetail a WITH(NOLOCK) ,dcFee b WITH(NOLOCK)
					WHERE b.type = 14
					AND a.dcFeeID = b.ID
					AND b.dcProvinceID = LEFT(@ProvinceID,2)
					AND ((MinValue<=@SmsQuota AND MaxValue>=@SmsQuota ) OR (MinValue<=@SmsQuota AND MaxValue=0))
					AND StartDate < GETDATE() AND EndDate > GETDATE()

				IF @dcFeeDetailsID IS NULL
					SELECT TOP 1 @Accounts = Price
					FROM dcFee  WITH(NOLOCK)
					WHERE type = 14
					AND dcProvinceID = LEFT(@ProvinceID,2)
					AND StartDate < GETDATE() AND EndDate > GETDATE()
			END
			ELSE IF @OrderType = 15							----职位刷新数
			BEGIN
				SELECT TOP 1 @Accounts = b.Price * @jobRefreshQuota,
						@dcFeeDetailsID = a.ID
					FROM dcFeeDetail a WITH(NOLOCK) ,dcFee b WITH(NOLOCK)
					WHERE b.type = 15
					AND a.dcFeeID = b.ID
					AND b.dcProvinceID = LEFT(@ProvinceID,2)
					AND ((MinValue<=@jobRefreshQuota AND MaxValue>=@jobRefreshQuota ) OR (MinValue<=@jobRefreshQuota AND MaxValue=0))
					AND StartDate < GETDATE() AND EndDate > GETDATE()

				IF @dcFeeDetailsID IS NULL
					SELECT TOP 1 @Accounts = Price
					FROM dcFee  WITH(NOLOCK)
					WHERE type = 15
					AND dcProvinceID = LEFT(@ProvinceID,2)
					AND StartDate < GETDATE() AND EndDate > GETDATE()
			END
		END
		IF @MainOrderID IS NOT NULL
			IF NOT EXISTS(SELECT 'x' FROM caOrder WITH(NOLOCK) WHERE cpMainID = @cpMainID AND ID = @MainOrderID  AND OrderType = 8 AND EndDate >GETDATE())
				AND @OrderType in (9,10,11,14)
				GOTO ERR	--检查是否是自己有效的主订单号
		
		DECLARE @CoinBalance AS INT
		IF @UseCoin IS NOT NULL  --金币支付
		BEGIN
			IF NOT EXISTS(SELECT 'x' FROM cpMain WHERE ID = @cpMainID AND RemainCoin >= @UseCoin)
				GOTO ERR	--检查剩余金币数量是否足够支付
			SET @Paid = @Paid - @UseCoin
		END
		IF @Paid < 0
			SET @Paid = 0

		INSERT INTO caOrder (cpMainID,ProvinceID,ServiceType,PlaceWeek,PayMethod,
			OrderType,Accounts,Paid,Balance,LinkMan,Telephone,LinkRemark,Manageruserid,ActiveQuota,RemainQuota,JobNumber,CompanyName,MainOrderID,InvoiceCompany,
			NeedInvoice,InvoiceTitle,MailAddress,Recipient,PostTelephone,Zip,InvoiceConfirmDate,InvoiceConfirmMan,UserNumber,dcFeeDetailID,IsBackSubmit,PaidCoin,SmsQuota,RemainSmsQuota, jobRefreshQuota, remainJobRefreshQuota)
		VALUES(@cpMainID,@ProvinceID,@ServiceType,@PlaceWeek,@PayMethod,
			@OrderType,@Accounts,@Paid,@Balance,@LinkMan,@Telephone,@LinkRemark,@Manageruserid,@ActiveQuota,@ActiveQuota,@JobNumber,@CompanyName,@MainOrderID,@InvoiceCompany,
			@NeedInvoice,@InvoiceTitle,@MailAddress,@Recipient,@PostTelephone,@Zip,@InvoiceConfirmDate,@InvoiceConfirmMan,@UserNumber,@dcFeeDetailsID,1,@UseCoin,@SmsQuota,@SmsQuota, @jobRefreshQuota, @jobRefreshQuota)
		SET @MaxID = @@IDENTITY
		IF @Paid != 0
		BEGIN
			DECLARE @Temp AS NUMERIC(18,2)
			SET @Temp = @Paid -- 1 + CONVERT(NUMERIC(18,2),'0.'+RIGHT(STR(@cpMainID),2))
			--金币或订单全额支付
			IF @Temp < 0
				SET @Temp = 0
			UPDATE caOrder SET Paid = @Temp WHERE ID = @MaxID
		END
		IF @UseCoin IS NOT NULL 
		BEGIN
			--插入金币记录
			INSERT INTO cpCoin (cpMainID, caOrderID, Coin, Balance, AddDate)
			VALUES(@cpMainID, @MaxID, 0 - @UseCoin, 0, GETDATE())
		END
	--END TRY
	--BEGIN CATCH
	--	GOTO ERR
	--END CATCH
COMMIT TRAN
RETURN @MaxID
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END
SET NOCOUNT OFF

GO
/****** Object:  StoredProcedure [dbo].[bsColdcustomerByAddManSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--推广冷客户认证等数据统计
--harry 2018-1-23 
--bsColdcustomerByAddManSelect '2017-1-1','2018-12-1'
CREATE PROCEDURE [dbo].[bsColdcustomerByAddManSelect]
(
@begin DATETIME,
@end DATETIME,
@managerUserId INT=0
)
AS
BEGIN
SET NOCOUNT ON
	CREATE TABLE #t(managerUserid INT,name VARCHAR(10), addCount INT , cerPassCount INT, cerIngCount INT,uncerCount INT, regCount INT,superior INT)
	IF @managerUserId IN(201,302,304,363,701,105)
	BEGIN
		INSERT INTO #t(managerUserId)
		SELECT DISTINCT AddMan FROM coldcustomer where addMan IN(select id from manageruser where deptid=15)
		END
	ELSE
	BEGIN
		INSERT INTO #t(managerUserId)
		SELECT DISTINCT AddMan FROM coldcustomer where addMan =@managerUserId
	END
	UPDATE #t
	SET #t.Name= a.NAME,#t.superior = a.superior
	FROM #t, managerUser a
	WHERE #t.managerUserid =a.id
	--添加量
	UPDATE a
	SET a.addCount =(SELECT COUNT(1)FROM coldcustomer b WHERE a.manageruSerId =b.AddMan AND b.AddDate BETWEEN @begin AND @end)
	FROM #t a 
	--认证通过量
	SELECT *
	INTO #tcer
	from logdb..coldcustomerCerLog
	where (CerDate BETWEEN @begin AND @end)  
	AND  addMan IN(select id from manageruser where deptid=15)

	UPDATE a
	SET a.cerPassCount= (SELECT COUNT(1) FROM #tcer b WHERE a.manageruSerId =b.AddMan)
	FROM #t a


	DROP TABLE #tcer

	/*--认证中的数量
	SELECT a.*,b.addMan 
	INTO #tcerIng
	from cpCertification a, coldcustomer b
	where CerStatus!=1 AND (a.AddDate BETWEEN @begin AND @end) 
	AND a.cpMainID IN(select id from cpmain where name IN(select Name from cpmain where id IN(select CpMainID FROM coldcustomer where addMan IN(select id from manageruser where deptid=15) )))
	AND a.cpMainID NOT IN(SELECT cpMainID FROM cpCertification WHERE CerStatus =1 )
	AND (a.CompanyName= b.CompanyName OR a.cpMainId = b.cpMainId)
	AND b.addMan is not NULL


	UPDATE a
	SET a.cerIngCount= (SELECT COUNT(DISTINCT CompanyName) FROM #tcerIng b WHERE a.managerUserId =b.AddMan)
	FROM #t a 

	DROP TABLE #tcerIng
	*/
	--未认证数量(有营业执照，但未认证)
	SELECT b.* 
	INTO #tuncer
	FROM cpMain a,coldcustomer b
	WHERE   a.MemberType = 1 
	AND a.id=b.cpmainid AND EXISTS(SELECT 'X' FROM cpLicence WHERE cpMainID = a.ID AND HasPassed = 1)
	AND b.addMan IN(select id from manageruser where deptid=15) 

	UPDATE a
	SET a.uncerCount= (SELECT COUNT(1) FROM #tuncer b WHERE a.managerUserId =b.AddMan)
	FROM #t a 
	DROP TABLE #tuncer
	--注册量
	SELECT *
	INTO #tReg
	FROM coldcustomer
	WHERE Status =2 AND (RegisterDate BETWEEN @begin AND @end) 
	UPDATE a
	SET a.regCount =(SELECT COUNT(1) FROM #tReg b WHERE a.manageruSerId =b.AddMan)
	FROM #t a

	DROP TABLE #tReg
	SELECT *FROM #t
	DROP TABLE #t
SET NOCOUNT OFF
END

GO
/****** Object:  StoredProcedure [dbo].[bsColdcustomerUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--修改冷客户企业名称
--harry 
--2018-7-3
CREATE PROCEDURE  [dbo].[bsColdcustomerUpdate]
(
	@cpname NVARCHAR(100),
	@coldcustomerId INT
)
AS
BEGIN
	IF EXISTS(select 'x' FROM coldcustomer where CompanyName=@cpname AND id !=@coldcustomerId)
	BEGIN
		select -1 as result--存在重名的冷客户
		return
	END
	IF EXISTS(select 'x' FROM cpmain where Name=@cpname AND ISNULL(ConsultantID,0)!=0)
	BEGIN
		select -2 as result--存在重名的公司且有顾问的企业
		return
	END
	UPDATE coldcustomer  SET CompanyName= @cpname WHERE id=@coldcustomerId
	IF EXISTS( select 'x' FROM cpmain where Name=@cpname AND ISNULL(ConsultantID,0)=0)
	BEGIN
		SELECT id INTO #t FROM cpmain where Name=@cpname AND ISNULL(ConsultantID,0)=0
		DECLARE @cpmainid INT, @manageruserId INT

		SELECT @manageruserId=ManagerUserId
		FROM  oadb..workuser where id=(select AddWorkUserID FROM coldcustomer where id=@coldcustomerId )
		SET @cpmainid=0
		IF ISNULL(@manageruserId,0)!=0
		BEGIN
			WHILE EXISTS ( SELECT 'x' FROM #t)
			BEGIN
				SELECT TOP 1 @cpmainid= id FROM #t ORDER BY id 
				UPDATE cpmain set  ConsultantId = @manageruserId, ConsultantDate = GETDATE()
				WHERE id=@cpmainid
				
				DELETE FROM #t where id=@cpmainid
			END
		END
		DROP TABLE #t
	END
	SELECT 1 AS result
		
END
GO
/****** Object:  StoredProcedure [dbo].[bsCompany_XinxiByEmailExist]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--###########################################
--sean 2010-12-2
--信息员推广用，提交前先检查邮件是否已经注册过
--	-1	黑名单
--	-10	半年内信息员注册过
--	-11	已经是会员
--###########################################
CREATE PROCEDURE [dbo].[bsCompany_XinxiByEmailExist]
(
	@Email VARCHAR(50)
)
AS
BEGIN
	IF EXISTS(SELECT 'x' FROM Company_Xinxi WITH (NOLOCK INDEX(IX_Company_Xinxi_Email)) WHERE Email = @Email AND IsHistory = 0)
		RETURN -10

	IF EXISTS(SELECT 'x' FROM caMain  WITH (NOLOCK INDEX(IX_caMain_Email)) WHERE Email = @Email)
		RETURN -11
    
    IF EXISTS(SELECT 'x' FROM Company_Black WITH(NOLOCK) WHERE Email = @Email)
		RETURN -1
        
	RETURN 1
END














GO
/****** Object:  StoredProcedure [dbo].[bsCompany_XinxiInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- sean	2010-12-1
-- 用于信息员注册， 判断email是否存在
--返回值：
--	-1	邮件黑名单
--	-2	单位名称已被我们列入黑名单，不再接受注册。
--	-3	不要注册保险公司。
--	-4	不要注册娱乐公司。
--	-5	单位名称已重复(最近登录时间一个月内，而且有营业执照、而且登录次数大于0)，不再接受注册
--	-6	不符合本地区规则,请放弃
--	-10	邮件半年内信息员注册过
--	-11	邮件已经是会员
--	-20	其他错误
-- =============================================
CREATE PROCEDURE [dbo].[bsCompany_XinxiInsert]
(
	@CompanyName NVARCHAR(50),
	@Username VARCHAR(50),
	@Email VARCHAR(50),
	@Password VARCHAR(50),
	@ManagerUserID SMALLINT,
	@ProvinceID TINYINT,
	@un VARCHAR(50) OUTPUT,
	@DBPassword VARCHAR(50) OUTPUT
)
AS
SET NOCOUNT ON;
IF LEN(ISNULL(@CompanyName, '')) = 0
	GOTO Err
IF LEN(ISNULL(@Username, '')) = 0
	GOTO Err
IF LEN(ISNULL(@Email, '')) = 0
	GOTO Err
IF LEN(ISNULL(@Password, '')) = 0
	GOTO Err
IF ISNULL(@ManagerUserID, 0) = 0
	GOTO Err
IF ISNULL(@ProvinceID, 0) = 0
	GOTO Err
IF dbo.IsEmail(@Email) = 0
	GOTO Err
IF dbo.IsAccount(@UserName) = 0
	GOTO Err

BEGIN TRY
	DECLARE @r AS INT
	DECLARE @Pass AS INT

	IF @CompanyName LIKE '%人寿%'
		RETURN -3		--不要注册保险公司。

	IF @CompanyName LIKE '%娱乐%'
		RETURN -4		--cont=不要注册娱乐公司。

	--单位名称已重复(最近登录时间一个月内，而且有营业执照)，不再接受注册
	IF EXISTS(SELECT 'x' FROM cpMain WITH(NOLOCK)
				WHERE HasLicence = 1
				AND Name = @CompanyName
				AND LastLoginDate > GETDATE() - 30
				)
		RETURN -5

	--Email重复
	EXEC @r = bsCompany_XinxiByEmailExist @Email
	IF @r < 1
		RETURN @r

	--检查黑名单
	IF EXISTS(SELECT 'x' FROM Company_Black WITH(NOLOCK) WHERE CHARINDEX(LTRIM(RTRIM(CompanyName)), @CompanyName) > 0)
		RETURN -2			--单位名称已被我们列入黑名单，不再接受注册。

	IF dbo.CompanyNameNoCheck(@CompanyName) = 1
		SET @Pass = 1
	ELSE
	BEGIN
		DECLARE @CompanyNameFilter AS NVARCHAR(50)
		SET @CompanyNameFilter = REPLACE(REPLACE(@CompanyName, '高新', ''), '开发', '')
		--本省，含有省市名称关键字
		IF EXISTS(SELECT 'x' FROM dcRegion WITH(NOLOCK)	
				WHERE LEFT(ID, 2) = @ProvinceID AND CHARINDEX(LEFT(LTRIM(RTRIM(Description)), 2), @CompanyNameFilter) > 0)
			SET @Pass = 1
		ELSE	--非本省，含有省市名称关键字                  
			IF EXISTS(SELECT 'x' FROM dcRegion WITH(NOLOCK)
					WHERE LEFT(ID, 2) <> @ProvinceID AND CHARINDEX(LEFT(LTRIM(RTRIM(Description)), 2), @CompanyNameFilter)>0)
				SET @Pass = 0
			ELSE
				SET @Pass = 1
		IF(@Pass = 0)
			IF(@ProvinceID = 83 AND CHARINDEX('巴州', @CompanyNameFilter) > 0)
			SET @Pass = 1
		IF(@Pass = 1)
			IF(@ProvinceID = 21 AND CHARINDEX('马鞍山', @CompanyNameFilter) > 0)
			SET @Pass = 0
		IF(@Pass = 0)
			IF CHARINDEX('中国', @CompanyNameFilter) > 0
			SET @Pass = 1
	END

	IF @Pass = 0
		RETURN -6

	--获取用户名，如果重名则加后缀，直至不重复
	EXEC spGenUserName @UserName, @un OUTPUT
	SELECT @DbPassWord = @PassWord

	BEGIN TRAN
		DECLARE @CountDate AS INT, @CompanyXinxiID AS INT, @TmpID INT,@Addman INT,@RegDate SMALLDATETIME
		SET @CountDate = LTRIM(STR(CONVERT(VARCHAR(8), GETDATE(), 112)))

		--如果在非活动区域则激活，否则增加
		SELECT TOP 1 @CompanyXinxiID = ID,@Addman = Addman,@RegDate = RegDate FROM Company_Xinxi WITH (NOLOCK INDEX(IX_Company_Xinxi_Email))
		WHERE Email = @Email AND IsHistory = 1
		ORDER BY RegDate DESC

		IF @CompanyXinxiID IS NULL
		BEGIN
			INSERT INTO Company_Xinxi(UserName, Password, CompanyName, Email, Province_ID, AddMan, RegDate)
			VALUES(@un, @Password, @CompanyName, @Email, @ProvinceID, @ManagerUserID, GETDATE())
			SELECT @TmpId = @@IDENTITY
		END
		ELSE				--激活
		BEGIN
			UPDATE Company_Xinxi SET CompanyName = @CompanyName, 
				Province_ID = @ProvinceID, AddMan = @ManagerUSerID,
				IsHistory = 0, RegDate =  GETDATE()
			WHERE ID = @CompanyXinxiID
			--将企业信息插入到ActivationCpDetail中 max 2013-08-23
			INSERT INTO LogDB..ActivationCpDetail(Username,Email,AddmanOld,AddmanNew,RegdateOld,RegdateNew)
			VALUES (@Email,@Email,@Addman,@ManagerUserID,@RegDate,GETDATE()) 

			IF NOT EXISTS(SELECT 'x' FROM Info_DateReport WITH(NOLOCK)
					WHERE Infomanager_ID = @ManagerUserID
					AND Province_ID = @ProvinceID
					AND CountDate = @CountDate)
			INSERT INTO Info_DateReport(Province_Id, InfoManager_Id, CountDate)
			VALUES(@ProvinceId, @ManageruserId, @CountDate)

			UPDATE Info_DateReport SET CompanyActivationCount= CompanyActivationCount+ 1
			WHERE Infomanager_ID = @ManagerUserID
			AND Province_ID = @ProvinceID
			AND CountDate = @CountDate

			SELECT @Un = UserName, @DbPassWord = Password FROM Company_Xinxi WITH(NOLOCK)
			WHERE ID = @CompanyXinxiID

			DELETE FROM Company_Xinxi
			WHERE Email = @Email AND IsHistory = 1
			SELECT @TmpId = @CompanyXinxiID
		END

		UPDATE DateReport SET CompanyRegNum_Our = CompanyRegNum_Our + 1
		WHERE Province_ID = @ProvinceID AND CountDate=@CountDate
		--INSERT INTO pamainDatereport SELECT @TmpId, 6, GETDATE() -- SEAN 20130911

		IF NOT EXISTS(SELECT 'x' FROM Info_DateReport WITH(NOLOCK)
					WHERE Infomanager_ID = @ManagerUserID
					AND Province_ID = @ProvinceID
					AND CountDate = @CountDate)
			INSERT INTO Info_DateReport(Province_Id, InfoManager_Id, CountDate)
			VALUES(@ProvinceId, @ManageruserId, @CountDate)

		UPDATE Info_DateReport SET CompanyRegNum_Our = CompanyRegNum_Our + 1
		WHERE Infomanager_ID = @ManagerUserID
		AND Province_ID = @ProvinceID
		AND CountDate = @CountDate
	COMMIT
	RETURN 1
END TRY
BEGIN CATCH
	GOTO Err
END CATCH
Err:
BEGIN
	ROLLBACK TRAN
	RETURN -20
END










GO
/****** Object:  StoredProcedure [dbo].[bsConsultant_FactorByIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- 创建日期:2010-9-25
-- 创建人：Lucifer
-- 功能：根据ID提取表中的数据
-- 应用于/BackStage/Consultant/ConsultantCheckCloseProc.asp页面
-- 修改时间：
-- 修改人：
-- =============================================
CREATE PROCEDURE [dbo].[bsConsultant_FactorByIDSelect]
(
	@ID INT
)
AS
BEGIN
	SELECT *
	FROM Consultant_Factor WITH(NOLOCK)
	WHERE ID=@ID
END














GO
/****** Object:  StoredProcedure [dbo].[bsConsultant_FactorInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- 创建日期:2010-9-25
-- 创建人：Lucifer
-- 功能：
-- 应用于/BackStage/Consultant/ConsultantFactorAddProc.asp页面
-- 修改时间：
-- 修改人：
-- =============================================
CREATE PROCEDURE [dbo].[bsConsultant_FactorInsert]
(
	@yearmonth INT,
	@factor_wuxianzhi SMALLINT,
	@factor_chuzhi SMALLINT,
	@factor_vip SMALLINT,
	@factor_nocontinue SMALLINT,
	@factor_new SMALLINT,
	@factor_active_first SMALLINT,
	@factor_passive_first SMALLINT,
	@factor_dead_first SMALLINT,
	@factor_active_second SMALLINT,
	@factor_passive_second SMALLINT,
	@factor_dead_second SMALLINT,
	@Sn TINYINT
)
AS
BEGIN TRY
	INSERT INTO Consultant_Factor(factor_wuxianzhi,factor_chuzhi,factor_vip,factor_nocontinue,factor_new,factor_active_first,
		factor_passive_first,factor_dead_first,factor_active_second,factor_passive_second,factor_dead_second,
		yearmonth,Sn) VALUES(@factor_wuxianzhi,@factor_chuzhi,@factor_vip,@factor_nocontinue,@factor_new,@factor_active_first,
		@factor_passive_first,@factor_dead_first,@factor_active_second,@factor_passive_second,@factor_dead_second,
		@yearmonth,@Sn)
	RETURN 1
END TRY
BEGIN CATCH
	RETURN 0
END CATCH














GO
/****** Object:  StoredProcedure [dbo].[bsConsultant_FactorSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- 创建日期:2010-9-25
-- 创建人：Lucifer
-- 功能：根据年月和南北方提取表中的数据
-- 应用于/BackStage/Consultant/ConsultantCheckCloseProc.asp页面
-- 修改时间：
-- 修改人：
-- =============================================
CREATE PROCEDURE [dbo].[bsConsultant_FactorSelect]
(
	@yearmonth INT,
	@Sn INT
)
AS
BEGIN
	SELECT *
	FROM Consultant_Factor WITH(NOLOCK)
	WHERE yearmonth=@yearmonth AND Sn=@Sn
END














GO
/****** Object:  StoredProcedure [dbo].[bsConsultant_FactorUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- 创建日期:2010-9-25
-- 创建人：Lucifer
-- 功能：
-- 应用于/BackStage/Consultant/ConsultantFactorEditProc.asp页面
-- 修改时间：
-- 修改人：
-- =============================================
CREATE PROCEDURE [dbo].[bsConsultant_FactorUpdate]
(
	@id INT,
	@factor_wuxianzhi SMALLINT,
	@factor_chuzhi SMALLINT,
	@factor_vip SMALLINT,
	@factor_nocontinue SMALLINT,
	@factor_new SMALLINT,
	@factor_active_first SMALLINT,
	@factor_passive_first SMALLINT,
	@factor_dead_first SMALLINT,
	@factor_active_second SMALLINT,
	@factor_passive_second SMALLINT,
	@factor_dead_second SMALLINT
)
AS
BEGIN TRY
	UPDATE Consultant_Factor SET
		factor_wuxianzhi=@factor_wuxianzhi,
		factor_chuzhi=@factor_chuzhi,
		factor_vip = @factor_vip,
		factor_nocontinue=@factor_nocontinue,
		factor_new=@factor_new,
		factor_active_first=@factor_active_first,
		factor_passive_first=@factor_passive_first,
		factor_dead_first=@factor_dead_first,
		factor_active_second=@factor_active_second,
		factor_passive_second=@factor_passive_second,
		factor_dead_second=@factor_dead_second
	WHERE id=@id
	RETURN 1
END TRY
BEGIN CATCH
	RETURN 0
END CATCH














GO
/****** Object:  StoredProcedure [dbo].[bsconsultant_manageruser_monthByIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- 创建日期:2010-9-21
-- 创建人：Lucifer
-- 功能：根据条件提取招聘顾问销售进度表中的数据
-- 应用于/BackStage/Consultant/ConsultantCheck.asp页面
-- 修改时间：
-- 修改人：
-- =============================================
CREATE PROCEDURE [dbo].[bsconsultant_manageruser_monthByIDSelect]
(
	@ID INT
)
AS
BEGIN
	SELECT *
		FROM consultant_manageruser_month WITH(NOLOCK) WHERE ID=@ID
END














GO
/****** Object:  StoredProcedure [dbo].[bsconsultant_manageruser_monthDelete]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- 创建日期:2010-9-25
-- 创建人：Lucifer
-- 功能：根据ID删除招聘顾问销售进度表中的数据
-- 应用于/BackStage/Consultant/ConsultantCheckDelete.asp页面
-- 修改时间：
-- 修改人：
-- =============================================
CREATE PROCEDURE [dbo].[bsconsultant_manageruser_monthDelete]
(
	@ID INT
)
AS
BEGIN
	DELETE FROM consultant_manageruser_month WHERE ID=@ID
END














GO
/****** Object:  StoredProcedure [dbo].[bsconsultant_manageruser_monthInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = 
-- 创建日期:2010-9-21
-- 创建人：Lucifer
-- 功能：增加一行招聘顾问销售进度，包括年月和招聘顾问ID
-- 应用于/BackStage/Consultant/ConsultantCheckAddProc.asp页面
-- 修改时间：
-- 修改人：
-- = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = 
CREATE PROCEDURE [dbo].[bsconsultant_manageruser_monthInsert]
(
	@yearmonth INT, 
	@consultantid INT
)
AS
BEGIN
	--INSERT INTO consultant_manageruser_month(consultantid, yearmonth) 
	--VALUES(@consultantid, @yearmonth)
	--Richard 2011年8月6日修改

	DECLARE @deptid INT, @name NVARCHAR(50), @name_eng VARCHAR(50), @status SMALLINT

	SELECT @deptid = deptid, @name = name, @name_eng = name_eng, @status = status 
	FROM manageruser WITH(NOLOCK) WHERE id = @consultantid

	INSERT INTO consultant_manageruser_month(consultantid, yearmonth, deptid, name, name_eng, status) 
	VALUES(@consultantid, @yearmonth, @deptid, @name, @name_eng, @status)
	RETURN 1
END














GO
/****** Object:  StoredProcedure [dbo].[bsconsultant_manageruser_monthSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- 创建日期:2010-9-21
-- 创建人：Lucifer
-- 功能：根据条件提取招聘顾问销售进度表中的数据
-- 应用于/BackStage/Consultant/ConsultantCheck.asp页面
-- 修改时间：
-- 修改人：
-- =============================================
CREATE PROCEDURE [dbo].[bsconsultant_manageruser_monthSelect]
(
	@WHERE VARCHAR(1000)
)
AS
BEGIN
		DECLARE @SQL AS VARCHAR(2000)
		--SET @SQL = 'SELECT TOP 400 a.id id,b.id consultantid,b.name name,a.yearmonth,a.obj_sales_first,'
		--SET @SQL = @SQL + ' a.obj_sales_second,a.obj_sales_new,a.real_sales_first,a.real_sales_second,'
		--SET @SQL = @SQL + ' a.real_sales_new,b.deptid,b.name_eng,b.status,a.customer_num,a.obj_sales,a.real_sales,'
		--SET @SQL = @SQL + ' a.ordernum_first,a.ordernum_second,a.ordernum_new,a.remarks'
		--SET @SQL = @SQL + ' FROM consultant_manageruser_month a WITH(NOLOCK),manageruser b WITH(NOLOCK)'
		--SET @SQL = @SQL + ' WHERE a.consultantid=b.id'
		--SET @SQL = @SQL + @Where
		--SET @SQL = @SQL + ' ORDER BY a.yearmonth DESC,b.id'
        --Richard 2011年8月6日修改
		SET @Where = dbo.SafeSql(@Where)
		SET @SQL = 'SELECT TOP 400 a.id id,a.consultantid,a.name name,a.yearmonth,a.obj_sales_first,'
		SET @SQL = @SQL + ' a.obj_sales_second,a.obj_sales_new,a.real_sales_first,a.real_sales_second,'
		SET @SQL = @SQL + ' a.real_sales_new,a.deptid,a.name_eng,a.status,a.customer_num,a.obj_sales,a.real_sales,'
		SET @SQL = @SQL + ' a.ordernum_first,a.ordernum_second,a.ordernum_new,a.remarks'
		SET @SQL = @SQL + ' FROM consultant_manageruser_month a WITH(NOLOCK)'
		SET @SQL = @SQL + ' WHERE 1=1'
		SET @SQL = @SQL + @Where
		--SET @SQL = @SQL + ' ORDER BY a.yearmonth DESC, LEFT(consultantid, 1), deptid, a.consultantid'
		SET @SQL = @SQL + ' ORDER BY yearmonth DESC, (SELECT DeptName FROM MainDb..Dept WHERE Id = deptid), consultantid'
		EXEC(@SQL)
END

GO
/****** Object:  StoredProcedure [dbo].[bsconsultant_manageruser_monthUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- 创建日期:2011-3-24
-- 创建人：Lucifer
-- 功能：修改招聘顾问销售进度
-- 应用于/BackStage/Consultant/ConsultantCheckAdjustProc.asp页面
-- 修改时间：
-- 修改人：
-- =============================================
CREATE PROCEDURE [dbo].[bsconsultant_manageruser_monthUpdate]
(
	@ID INT,
	@obj_sales INT,
	@real_sales INT,
	@remarks NVARCHAR(200)
)
AS
BEGIN
	UPDATE consultant_manageruser_month SET
		obj_sales=@obj_sales,
		real_sales=@real_sales,
		remarks=@remarks
	WHERE ID=@ID
END

GO
/****** Object:  StoredProcedure [dbo].[bsConsultantlistInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[bsConsultantlistInsert]
AS
BEGIN
	TRUNCATE TABLE bsConsultantlist
	--插入所有cpMainID
	INSERT INTO bsConsultantlist(cpMainID) SELECT Id FROM cpmain WITH(NOLOCK)
	--更新Vip类型  Vip套餐
	UPDATE a SET a.vipType = c.DetailName, a.VipMonth = c.Month
	FROM bsConsultantList a WITH(NOLOCK), 
		caOrder b WITH(NOLOCK),
		dcVipDetail c WITH(NOLOCK)
	WHERE b.cpMainID=a.cpMainID 
	AND b.OpenDate IS NOT NULL 
	AND GETDATE() BETWEEN b.BeginDate AND b.EndDate
	AND c.ID = b.dcFeeDetailID

	--更新服务到期时间
	UPDATE a SET a.serviceEndDate=b.UnlimitedDate
	FROM bsConsultantList a WITH(NOLOCK),cpMain b WITH(NOLOCK)
	WHERE a.cpMainID = b.ID
	AND b.MemberType=10

	UPDATE a SET a.serviceEndDate=b.BalanceDate
	FROM bsConsultantList a WITH(NOLOCK),cpMain b WITH(NOLOCK)
	WHERE a.cpMainID=b.ID
	AND b.MemberType=11

	UPDATE a SET a.serviceEndDate=b.EndDate
	FROM bsConsultantList a WITH(NOLOCK),caOrder b WITH(NOLOCK)
	WHERE a.cpMainID=b.cpMainID
	AND b.OrderType=8
	AND b.OpenDate IS NOT NULL
	AND b.BeginDate<GETDATE()
	AND b.EndDate>GETDATE()
	--更新下载简历数(VIP)
	UPDATE bsConsultantList
	SET RemainQuotaSum= a.RemainQuota
	FROM (SELECT cpMainId, SUM(RemainQuota) RemainQuota FROM caOrder WITH(NOLOCK) 
		WHERE OrderType IN (8, 9)
		AND BeginDate<=GETDATE() 
		AND EndDate>=GETDATE() 
		AND OpenDate IS NOT NULL
		GROUP BY cpMainId) a
	WHERE bsConsultantList.cpMainId = a.cpMainID

	--更新最后一次订单开通时间
	UPDATE bsConsultantList 
	SET caOrderLastOpenDate = a.OpenDate
	FROM (SELECT cpMainID, Max(OpenDate) OpenDate FROM caOrder WITH(NOLOCK)
		GROUP BY cpMainId) a
	WHERE bsConsultantList.cpMainID = a.cpMainId

	--更新营业执照审核时间
	UPDATE bsConsultantList
	SET LicenceVerifyDate=a.CheckDate
	FROM (SELECT cpMainId, Max(CheckDate) CheckDate
		FROM cpLicence WITH(NOLOCK)
		GROUP BY CpMainId) a
	WHERE bsConsultantList.cpMainID = a.cpMainId

	--更新今天简历消费数(正式、储值)
	UPDATE bsConsultantList
	SET CaCvQuotaCount=a.Cnt
	FROM (SELECT cpMainId, COUNT(1) cnt
		FROM CaCvQuotaLog WITH(NOLOCK) 
		WHERE AddDate>CONVERT(VARCHAR(10),GETDATE(),120)
		GROUP BY cpMainId) a
	WHERE bsConsultantList.cpMainID = a.cpMainId

	--更新限制时间
	UPDATE bsConsultantList
	SET bsCpStatusAddDate=a.AddDate
	FROM (
		SELECT cpMainId, Max(AddDate) AddDate
		FROM bsCpStatus WITH(NOLOCK) 
		WHERE statusID=9 
		GROUP BY cpMainId) a
	WHERE bsConsultantList.cpMainID = a.cpMainId

	--更新简历隐藏时间
	--UPDATE bsConsultantList SET bsCpVerifyDate=(
	--	SELECT TOP 1 VerifyDate FROM bsCpVerifyLog 
	--		WHERE cpMainID=bsConsultantList.cpMainID)
	--更新今天简历下载数
	UPDATE bsConsultantList
	SET caActiveCount=a.Cnt
	FROM (SELECT cpMainId, COUNT(1) Cnt
		FROM CaActiveLog WITH(NOLOCK) 
		WHERE AddDate > CONVERT(VARCHAR(10), GETDATE(), 23)
		GROUP BY cpMainId) a
	WHERE bsConsultantList.cpMainID = a.cpMainId

	--更新单位点击资费标准时间
	UPDATE a 
	SET a.caFeePageViewAddDate=c.AddDate
	FROM bsConsultantList a,
		(SELECT a.cpMainId, MAX(b.AddDate) AddDate
		FROM caMain a WITH(NOLOCK), caFeePageViewLog b WITH(NOLOCK) 
		WHERE a.Id = b.caMainID
		GROUP BY a.cpMainId) c
	WHERE a.cpmainid = c.cpmainid

	UPDATE a
	SET a.CvViewNumber = c.CvViewNumber
	FROM bsConsultantList a,
		(SELECT a.cpMainId, COUNT(*) CvViewNumber
		FROM caMain a WITH(NOLOCK), cacvviewlog b WITH(NOLOCK)
		WHERE a.Id = b.caMainID
		AND AddDate > CONVERT(VARCHAR(10), GETDATE(), 23)
		GROUP BY a.cpMainId) c
	WHERE a.cpmainid = c.cpmainid

	--更新最后一次未完成联系时间
	UPDATE bsConsultantList 
	SET LastContactDate=a.begintime,LastContactID=a.ID,LastContactAddDate=a.AddDate
	FROM (SELECT b.id,b.companyID, b.begintime,b.addDate 
		FROM contact as b WITH(NOLOCK),(
			SELECT CompanyId,MAX(begintime) begintime
			FROM contact WITH(NOLOCK)
			WHERE status=1 
			GROUP BY CompanyId) c
		WHERE b.CompanyID=c.CompanyId 
		AND b.begintime=c.begintime) a
	WHERE bsConsultantList.cpMainID = a.companyID
	--更新最后一次完成联系时间
	UPDATE bsConsultantList 
	SET contactLastCloseDate=a.closedate,ContactLastCloseID=a.ID,ContactLastCloseAddDate=a.AddDate
	FROM (SELECT b.id,b.companyID, b.closedate,b.addDate 
		FROM contact as b WITH(NOLOCK),(
			SELECT CompanyId,MAX(closedate) CloseDate
			FROM contact WITH(NOLOCK)
			WHERE status=2 
			GROUP BY CompanyId) c
		WHERE b.CompanyID=c.CompanyId 
		AND b.CloseDate=c.CloseDate) a
	WHERE bsConsultantList.cpMainID = a.companyID
	--更新职位被浏览数量
	UPDATE a
	SET a.JobViewNumber = b.Cnt
	FROM bsConsultantList a, (SELECT b.cpMainId, COUNT(1) Cnt
		FROM paJobViewLog a WITH(nolock), Job b WITH(nolock)
		WHERE a.JobID = b.ID
		AND b.valid=1
		AND a.Adddate>GETDATE()-30
		GROUP BY b.cpMainId
		) b
	WHERE a.cpMainId = b.cpMainId
	--更新投递的非开放简历数量
	UPDATE a
	SET a.NotOpen1 = b.Cnt
	FROM bsConsultantList a, (SELECT b.cpMainId, COUNT(1) Cnt
		FROM exJobApply a WITH(nolock), Job b WITH(nolock), cvMain c WITH(NOLOCK)
		WHERE a.JobID = b.ID AND a.cvMainID = c.ID
		AND c.IsOpen = 0
		AND a.Adddate > CONVERT(VARCHAR(10),GETDATE(),120)
		GROUP BY b.cpMainId
		) b
	WHERE a.cpMainId = b.cpMainId

	UPDATE a
	SET a.NotOpen2 = b.Cnt
	FROM bsConsultantList a, (SELECT b.cpMainId, COUNT(1) Cnt
		FROM exJobApply a WITH(nolock), Job b WITH(nolock), cvMain c WITH(NOLOCK)
		WHERE a.JobID = b.ID AND a.cvMainID = c.ID
		AND c.IsOpen = 0
		AND a.Adddate > CONVERT(VARCHAR(10),GETDATE()-1,120)
		GROUP BY b.cpMainId
		) b
	WHERE a.cpMainId = b.cpMainId

	UPDATE a
	SET a.NotOpen3 = b.Cnt
	FROM bsConsultantList a, (SELECT b.cpMainId, COUNT(1) Cnt
		FROM exJobApply a WITH(nolock), Job b WITH(nolock), cvMain c WITH(NOLOCK)
		WHERE a.JobID = b.ID AND a.cvMainID = c.ID
		AND c.IsOpen = 0
		AND a.Adddate > CONVERT(VARCHAR(10),GETDATE()-2,120)
		GROUP BY b.cpMainId
		) b
	WHERE a.cpMainId = b.cpMainId

	UPDATE a
	SET a.NotOpen7 = b.Cnt
	FROM bsConsultantList a, (SELECT b.cpMainId, COUNT(1) Cnt
		FROM exJobApply a WITH(nolock), Job b WITH(nolock), cvMain c WITH(NOLOCK)
		WHERE a.JobID = b.ID AND a.cvMainID = c.ID
		AND c.IsOpen = 0
		AND a.Adddate > CONVERT(VARCHAR(10),GETDATE()-6,120)
		GROUP BY b.cpMainId
		) b
	WHERE a.cpMainId = b.cpMainId
	
	UPDATE a
	SET a.NotOpen14 = b.Cnt
	FROM bsConsultantList a, (SELECT b.cpMainId, COUNT(1) Cnt
		FROM exJobApply a WITH(nolock), Job b WITH(nolock), cvMain c WITH(NOLOCK)
		WHERE a.JobID = b.ID AND a.cvMainID = c.ID
		AND c.IsOpen = 0
		AND a.Adddate > CONVERT(VARCHAR(10),GETDATE()-13,120)
		GROUP BY b.cpMainId
		) b
	WHERE a.cpMainId = b.cpMainId

	UPDATE a
	SET a.NotOpen30 = b.Cnt
	FROM bsConsultantList a, (SELECT b.cpMainId, COUNT(1) Cnt
		FROM exJobApply a WITH(nolock), Job b WITH(nolock), cvMain c WITH(NOLOCK)
		WHERE a.JobID = b.ID AND a.cvMainID = c.ID
		AND c.IsOpen = 0
		AND a.Adddate > CONVERT(VARCHAR(10),GETDATE()-29,120)
		GROUP BY b.cpMainId
		) b
	WHERE a.cpMainId = b.cpMainId
END














GO
/****** Object:  StoredProcedure [dbo].[bsConsultantlistUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[bsConsultantlistUpdate]
AS
BEGIN
	SELECT TOP 0 * INTO #t FROM bsConsultantlist
	INSERT INTO #t(cpMainID) SELECT Id FROM cpmain WITH(NOLOCK INDEX(IX_cpMain_LastModifyDate)) WHERE LastModifyDate > DATEADD(MINUTE, -20, GETDATE()) 
	INSERT INTO #t(cpMainID) 
	SELECT Id FROM cpmain WITH(NOLOCK)
	WHERE (UnLimitedDate BETWEEN DATEADD(MINUTE, -20, GETDATE()) AND GETDATE()
		OR BalanceDate BETWEEN DATEADD(MINUTE, -20, GETDATE()) AND GETDATE())
	AND Id Not In(SELECT ID FROM #t)
	INSERT INTO #t(cpMainID) 
	SELECT cpMainId FROM bsConsultantlist WITH(NOLOCK)
	WHERE ServiceEndDate BETWEEN DATEADD(MINUTE, -20, GETDATE()) AND GETDATE()
	AND cpMainId Not In(SELECT cpMainID FROM #t)

	--更新Vip类型  Vip套餐
	UPDATE a SET a.vipType = c.DetailName, a.VipMonth = c.Month
	FROM #t a WITH(NOLOCK), 
		caOrder b WITH(NOLOCK),
		dcVipDetail c WITH(NOLOCK)
	WHERE b.cpMainID=a.cpMainID 
	AND b.OpenDate IS NOT NULL 
	AND GETDATE() BETWEEN b.BeginDate AND b.EndDate
	AND c.ID = b.dcFeeDetailID

	--更新服务到期时间
	UPDATE a SET a.serviceEndDate=b.UnlimitedDate
	FROM #t a WITH(NOLOCK),cpMain b WITH(NOLOCK)
	WHERE a.cpMainID = b.ID
	AND b.MemberType=10

	UPDATE a SET a.serviceEndDate=b.BalanceDate
	FROM #t a WITH(NOLOCK),cpMain b WITH(NOLOCK)
	WHERE a.cpMainID=b.ID
	AND b.MemberType=11

	UPDATE a SET a.serviceEndDate=b.EndDate
	FROM #t a WITH(NOLOCK),caOrder b WITH(NOLOCK)
	WHERE a.cpMainID=b.cpMainID
	AND b.OrderType=8
	AND b.OpenDate IS NOT NULL
	AND b.BeginDate<GETDATE()
	AND b.EndDate>GETDATE()
	--更新下载简历数(VIP)
	UPDATE #t
	SET RemainQuotaSum= a.RemainQuota
	FROM (SELECT cpMainId, SUM(RemainQuota) RemainQuota FROM caOrder WITH(NOLOCK) 
		WHERE OrderType IN (8, 9)
		AND BeginDate<=GETDATE() 
		AND EndDate>=GETDATE() 
		AND OpenDate IS NOT NULL
		GROUP BY cpMainId) a
	WHERE #t.cpMainId = a.cpMainID

	--更新最后一次订单开通时间
	UPDATE #t 
	SET caOrderLastOpenDate = a.OpenDate
	FROM (SELECT cpMainID, Max(OpenDate) OpenDate FROM caOrder WITH(NOLOCK)
		GROUP BY cpMainId) a
	WHERE #t.cpMainID = a.cpMainId

	--更新营业执照审核时间
	UPDATE #t
	SET LicenceVerifyDate=a.CheckDate
	FROM (SELECT cpMainId, Max(CheckDate) CheckDate
		FROM cpLicence WITH(NOLOCK)
		GROUP BY CpMainId) a
	WHERE #t.cpMainID = a.cpMainId

	--更新今天简历消费数(正式、储值)
	UPDATE #t
	SET CaCvQuotaCount=a.Cnt
	FROM (SELECT cpMainId, COUNT(1) cnt
		FROM CaCvQuotaLog WITH(NOLOCK) 
		WHERE AddDate>CONVERT(VARCHAR(10),GETDATE(),120)
		GROUP BY cpMainId) a
	WHERE #t.cpMainID = a.cpMainId

	--更新限制时间
	UPDATE #t
	SET bsCpStatusAddDate=a.AddDate
	FROM (
		SELECT cpMainId, Max(AddDate) AddDate
		FROM bsCpStatus WITH(NOLOCK) 
		WHERE statusID=9 
		GROUP BY cpMainId) a
	WHERE #t.cpMainID = a.cpMainId

	--更新简历隐藏时间
	--UPDATE #t SET bsCpVerifyDate=(
	--	SELECT TOP 1 VerifyDate FROM bsCpVerifyLog 
	--		WHERE cpMainID=#t.cpMainID)
	--更新今天简历下载数
	UPDATE #t
	SET caActiveCount=a.Cnt
	FROM (SELECT cpMainId, COUNT(1) Cnt
		FROM CaActiveLog WITH(NOLOCK) 
		WHERE AddDate > CONVERT(VARCHAR(10), GETDATE(), 23)
		GROUP BY cpMainId) a
	WHERE #t.cpMainID = a.cpMainId

	--更新单位点击资费标准时间
	UPDATE a 
	SET a.caFeePageViewAddDate=c.AddDate
	FROM #t a,
		(SELECT a.cpMainId, MAX(b.AddDate) AddDate
		FROM caMain a WITH(NOLOCK), caFeePageViewLog b WITH(NOLOCK) 
		WHERE a.Id = b.caMainID
		GROUP BY a.cpMainId) c
	WHERE a.cpmainid = c.cpmainid
	
	--更新最后一次未完成联系时间
	UPDATE #t 
	SET LastContactDate=a.begintime,LastContactID=a.ID,LastContactAddDate=a.AddDate
	FROM (SELECT b.id,b.companyID, b.begintime,b.addDate 
		FROM contact as b WITH(NOLOCK),(
			SELECT CompanyId,MAX(begintime) begintime
			FROM contact WITH(NOLOCK)
			WHERE status=1 
			GROUP BY CompanyId) c
		WHERE b.CompanyID=c.CompanyId 
		AND b.begintime=c.begintime) a
	WHERE #t.cpMainID = a.companyID
	
	
	--更新最后一次完成联系时间
	UPDATE #t 
	SET contactLastCloseDate=a.closedate,ContactLastCloseID=a.ID,ContactLastCloseAddDate=a.AddDate
	FROM (SELECT b.id,b.companyID, b.closedate,b.addDate 
		FROM contact as b WITH(NOLOCK),(
			SELECT CompanyId,MAX(closedate) CloseDate
			FROM contact WITH(NOLOCK)
			WHERE status=2 
			GROUP BY CompanyId) c
		WHERE b.CompanyID=c.CompanyId 
		AND b.CloseDate=c.CloseDate) a
	WHERE #t.cpMainID = a.companyID

	UPDATE a
	SET a.JobViewNumber = b.Cnt
	FROM #t a, (SELECT b.cpMainId, COUNT(1) Cnt
		FROM paJobViewLog a WITH(nolock), Job b WITH(nolock)
		WHERE a.JobID = b.ID
		AND b.valid=1
		AND a.Adddate>GETDATE()-30
		GROUP BY b.cpMainId
		) b
	WHERE a.cpMainId = b.cpMainId
	
	--更新投递的非开放简历数量
	UPDATE a
	SET a.NotOpen1 = b.Cnt
	FROM #t a, (SELECT b.cpMainId, COUNT(1) Cnt
		FROM exJobApply a WITH(nolock), Job b WITH(nolock), cvMain c WITH(NOLOCK)
		WHERE a.JobID = b.ID AND a.cvMainID = c.ID
		AND c.IsOpen = 0
		AND a.Adddate > CONVERT(VARCHAR(10),GETDATE(),120)
		GROUP BY b.cpMainId
		) b
	WHERE a.cpMainId = b.cpMainId

	UPDATE a
	SET a.NotOpen2 = b.Cnt
	FROM #t a, (SELECT b.cpMainId, COUNT(1) Cnt
		FROM exJobApply a WITH(nolock), Job b WITH(nolock), cvMain c WITH(NOLOCK)
		WHERE a.JobID = b.ID AND a.cvMainID = c.ID
		AND c.IsOpen = 0
		AND a.Adddate > CONVERT(VARCHAR(10),GETDATE()-1,120)
		GROUP BY b.cpMainId
		) b
	WHERE a.cpMainId = b.cpMainId

	UPDATE a
	SET a.NotOpen3 = b.Cnt
	FROM #t a, (SELECT b.cpMainId, COUNT(1) Cnt
		FROM exJobApply a WITH(nolock), Job b WITH(nolock), cvMain c WITH(NOLOCK)
		WHERE a.JobID = b.ID AND a.cvMainID = c.ID
		AND c.IsOpen = 0
		AND a.Adddate > CONVERT(VARCHAR(10),GETDATE()-2,120)
		GROUP BY b.cpMainId
		) b
	WHERE a.cpMainId = b.cpMainId

	UPDATE a
	SET a.NotOpen7 = b.Cnt
	FROM #t a, (SELECT b.cpMainId, COUNT(1) Cnt
		FROM exJobApply a WITH(nolock), Job b WITH(nolock), cvMain c WITH(NOLOCK)
		WHERE a.JobID = b.ID AND a.cvMainID = c.ID
		AND c.IsOpen = 0
		AND a.Adddate > CONVERT(VARCHAR(10),GETDATE()-6,120)
		GROUP BY b.cpMainId
		) b
	WHERE a.cpMainId = b.cpMainId
	
	UPDATE a
	SET a.NotOpen14 = b.Cnt
	FROM #t a, (SELECT b.cpMainId, COUNT(1) Cnt
		FROM exJobApply a WITH(nolock), Job b WITH(nolock), cvMain c WITH(NOLOCK)
		WHERE a.JobID = b.ID AND a.cvMainID = c.ID
		AND c.IsOpen = 0
		AND a.Adddate > CONVERT(VARCHAR(10),GETDATE()-13,120)
		GROUP BY b.cpMainId
		) b
	WHERE a.cpMainId = b.cpMainId

	UPDATE a
	SET a.NotOpen30 = b.Cnt
	FROM #t a, (SELECT b.cpMainId, COUNT(1) Cnt
		FROM exJobApply a WITH(nolock), Job b WITH(nolock), cvMain c WITH(NOLOCK)
		WHERE a.JobID = b.ID AND a.cvMainID = c.ID
		AND c.IsOpen = 0
		AND a.Adddate > CONVERT(VARCHAR(10),GETDATE()-29,120)
		GROUP BY b.cpMainId
		) b
	WHERE a.cpMainId = b.cpMainId

	DELETE bsConsultantlist WHERE cpMainId IN(SELECT cpMainId FROM #t)
	INSERT INTO bsConsultantlist SELECT * FROM #t
------------------------------------------------------------------
	--更新下载简历数(VIP)
	UPDATE bsConsultantList
	SET RemainQuotaSum= a.RemainQuota
	FROM (SELECT cpMainId, SUM(RemainQuota) RemainQuota FROM caOrder WITH(NOLOCK) 
		WHERE OrderType IN (8, 9)
		AND BeginDate<=GETDATE() 
		AND EndDate>=GETDATE() 
		AND OpenDate IS NOT NULL
		AND cpMainId IN(SELECT cpMainId FROM caActiveLog WITH(NOLOCK) WHERE AddDate > DATEADD(HOUR, -1, GETDATE()))
		GROUP BY cpMainId) a
	WHERE bsConsultantList.cpMainId = a.cpMainID

	--更新今天简历消费数(正式、储值)
	UPDATE bsConsultantList
	SET CaCvQuotaCount=a.Cnt
	FROM (SELECT cpMainId, COUNT(1) cnt
		FROM CaCvQuotaLog WITH(NOLOCK) 
		WHERE AddDate > CONVERT(VARCHAR(10),GETDATE(),120)
		GROUP BY cpMainId) a
	WHERE bsConsultantList.cpMainID = a.cpMainId

	--更新今天简历下载数
	UPDATE bsConsultantList
	SET caActiveCount=a.Cnt
	FROM (SELECT cpMainId, COUNT(1) Cnt
		FROM CaActiveLog WITH(NOLOCK) 
		WHERE AddDate > CONVERT(VARCHAR(10), GETDATE(), 23)
		GROUP BY cpMainId) a
	WHERE bsConsultantList.cpMainID = a.cpMainId

	--更新单位点击资费标准时间
	UPDATE a 
	SET a.caFeePageViewAddDate=c.AddDate
	FROM bsConsultantList a,
		(SELECT a.cpMainId, MAX(b.AddDate) AddDate
		FROM caMain a WITH(NOLOCK), caFeePageViewLog b WITH(NOLOCK) 
		WHERE a.Id = b.caMainID
		AND AddDate > DATEADD(HOUR, -1, GETDATE())
		GROUP BY a.cpMainId) c
	WHERE a.cpmainid = c.cpmainid

	--更新最后一次联系时间
	UPDATE bsConsultantList 
	SET LastContactDate=a.begintime,LastContactID=a.ID,LastContactAddDate=a.AddDate
	FROM (SELECT b.id,b.companyID, b.begintime,b.addDate 
		FROM contact as b WITH(NOLOCK),(
			SELECT CompanyId,MAX(begintime) begintime
			FROM contact WITH(NOLOCK)
			WHERE status=1 
			AND begintime > DATEADD(HOUR, -1, GETDATE())
			GROUP BY CompanyId) c
		WHERE b.CompanyID=c.CompanyId 
		AND b.begintime=c.begintime) a
	WHERE bsConsultantList.cpMainID = a.companyID
	--更新最后一次完成联系时间
	UPDATE bsConsultantList 
	SET contactLastCloseDate=a.closedate,ContactLastCloseID=a.ID,ContactLastCloseAddDate=a.AddDate
	FROM (SELECT b.id,b.companyID, b.closedate,b.addDate 
		FROM contact as b WITH(NOLOCK),(
			SELECT CompanyId,MAX(closedate) CloseDate
			FROM contact WITH(NOLOCK)
			WHERE status=2 
			AND CloseDate > DATEADD(HOUR, -1, GETDATE())
			GROUP BY CompanyId) c
		WHERE b.CompanyID=c.CompanyId 
		AND b.CloseDate=c.CloseDate) a
	WHERE bsConsultantList.cpMainID = a.companyID
	
	--更新职位浏览数
	UPDATE a
	SET a.JobViewNumber = b.Cnt
	FROM bsConsultantList a, (SELECT b.cpMainId, COUNT(1) Cnt
		FROM paJobViewLog a WITH(nolock), Job b WITH(nolock)
		WHERE a.JobID = b.ID
		AND b.valid=1
		AND a.Adddate>GETDATE()-30
		AND a.AddDate > DATEADD(HOUR, -1, GETDATE())
		GROUP BY b.cpMainId
		) b
	WHERE a.cpMainId = b.cpMainId

	--更新投递的非开放简历数量
	UPDATE a
	SET a.NotOpen1 = b.Cnt
	FROM bsConsultantList a, (
		SELECT b.cpMainId, COUNT(1) Cnt
		FROM exJobApply a WITH(nolock), Job b WITH(nolock), cvMain c WITH(NOLOCK)
		WHERE a.JobID = b.ID AND a.cvMainID = c.ID
		AND c.IsOpen = 0
		AND a.Adddate > CONVERT(VARCHAR(10),GETDATE(),120)
		GROUP BY b.cpMainId
		) b
	WHERE a.cpMainId = b.cpMainId

	UPDATE a
	SET a.NotOpen2 = b.Cnt
	FROM bsConsultantList a, (
		SELECT b.cpMainId, COUNT(1) Cnt
		FROM exJobApply a WITH(nolock), Job b, cvMain c WITH(NOLOCK)
		WHERE a.JobID = b.ID AND a.cvMainID = c.ID
		AND c.IsOpen = 0
		AND a.Adddate > CONVERT(VARCHAR(10),GETDATE()-1,120)
		GROUP BY b.cpMainId
		) b
	WHERE a.cpMainId = b.cpMainId

	SELECT cpMainId  INTO #tt FROM Job a WITH(NOLOCK), ExJobApply b WITH(NOLOCK) WHERE a.ID = b.JobId AND b.AddDate > DATEADD(MINUTE, -20, GETDATE())

	UPDATE a
	SET a.NotOpen3 = b.Cnt
	FROM bsConsultantList a, (SELECT b.cpMainId, COUNT(1) Cnt
		FROM exJobApply a WITH(nolock), Job b WITH(nolock), cvMain c WITH(NOLOCK)
		WHERE a.JobID = b.ID AND a.cvMainID = c.ID
		AND c.IsOpen = 0
		AND a.Adddate > CONVERT(VARCHAR(10),GETDATE()-2,120)
		AND b.cpMainID IN(SELECT cpMainId FROM #tt)
		GROUP BY b.cpMainId
		) b
	WHERE a.cpMainId = b.cpMainId

	UPDATE a
	SET a.NotOpen7 = b.Cnt
	FROM bsConsultantList a, (SELECT b.cpMainId, COUNT(1) Cnt
		FROM exJobApply a WITH(nolock), Job b WITH(nolock), cvMain c WITH(NOLOCK)
		WHERE a.JobID = b.ID AND a.cvMainID = c.ID
		AND c.IsOpen = 0
		AND a.Adddate > CONVERT(VARCHAR(10),GETDATE()-6,120)
		AND b.cpMainID IN(SELECT cpMainId FROM #tt)
		GROUP BY b.cpMainId
		) b
	WHERE a.cpMainId = b.cpMainId
	
	UPDATE a
	SET a.NotOpen14 = b.Cnt
	FROM bsConsultantList a, (
		SELECT b.cpMainId, COUNT(1) Cnt
		FROM exJobApply a WITH(nolock), Job b WITH(nolock), cvMain c WITH(NOLOCK)
		WHERE a.JobID = b.ID AND a.cvMainID = c.ID
		AND c.IsOpen = 0
		AND a.Adddate > CONVERT(VARCHAR(10),GETDATE()-13,120)
		AND b.cpMainID IN(SELECT cpMainId FROM #tt)
		GROUP BY b.cpMainId
		) b
	WHERE a.cpMainId = b.cpMainId

	UPDATE a
	SET a.NotOpen30 = b.Cnt
	FROM bsConsultantList a, (
		SELECT b.cpMainId, COUNT(1) Cnt
		FROM exJobApply a WITH(nolock), Job b WITH(nolock), cvMain c WITH(NOLOCK)
		WHERE a.JobID = b.ID AND a.cvMainID = c.ID
		AND c.IsOpen = 0
		AND a.Adddate > CONVERT(VARCHAR(10),GETDATE()-29,120)
		AND b.cpMainID IN(SELECT cpMainId FROM #tt)
		GROUP BY b.cpMainId
		) b
	WHERE a.cpMainId = b.cpMainId
END














GO
/****** Object:  StoredProcedure [dbo].[bscpmainByNameUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--后台冷客户注册
--harry 2018-6-28
CREATE PROCEDURE [dbo].[bscpmainByNameUpdate]
(
	@addman INT,
	@dcProvinceID INT,
	@cpName NVARCHAR(100)
)
AS
BEGIN
	SELECT Id INTO #a FROM cpmain 
	WHERE dcProvinceID=@dcProvinceID and Name=@cpName

	DECLARE @a1 INT 
	SET @a1=0
	WHILE EXISTS(select 'x' FROM #a )
	BEGIN
		SELECT TOP 1 @a1=id FROM #a  WHERE id>@a1 ORDER BY ID 
		UPDATE cpMain SET ConsultantId = @addman, ConsultantDate = GETDATE() WHERE Id=@a1
		DELETE FROM #a WHERE id=@a1
              	END
	DROP TABLE #a
END

GO
/****** Object:  StoredProcedure [dbo].[bsCpMainByOpenNotPayUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[bsCpMainByOpenNotPayUpdate]
AS
BEGIN
	DECLARE @cpMainID AS INT
	DECLARE curNotPay CURSOR FOR
	SELECT cpMain.ID FROM caOrder WITH(NOLOCK),cpMain WITH(NOLOCK),caMain WITH(NOLOCK) 
	WHERE caOrder.cpMainID=cpMain.id AND cpMain.ID=caMain.cpMainID AND AccountType=1 
	AND caOrder.Paid>0 AND caOrder.OpenDate IS NOT NULL AND caOrder.ReceiveDate IS NULL 
	AND caOrder.OpenDate < CONVERT(VARCHAR(10), GETDATE()-10, 120)
	AND caOrder.OpenDate > GETDATE()-90 AND cpMain.IsLimitLogin=0 
	ORDER BY caOrder.OpenDate DESC

	OPEN curNotPay
	FETCH NEXT FROM curNotPay INTO @cpMainID
	IF @@FETCH_STATUS >= 0
	BEGIN
		WHILE @@FETCH_STATUS = 0
		BEGIN
			INSERT INTO bsCpStatus(cpMainID,statusID,verifyMan,verifyInfo,verifyDate) VALUES(@cpMainID,11,1,'订单开通十天未到账',GETDATE())
			UPDATE cpMain SET IsLimitLogin=1 WHERE ID=@cpMainID
			FETCH NEXT FROM curNotPay INTO @cpMainID
		END
	END
	CLOSE curNotPay 
	DEALLOCATE curNotPay
END














GO
/****** Object:  StoredProcedure [dbo].[bsCpMainLocked]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[bsCpMainLocked]
(
	@cpMainId INT
)
AS
BEGIN
	SET NOCOUNT ON
	DECLARE @Email NVARCHAR(100)
	DECLARE @Name NVARCHAR(50)
	DECLARE @CompanyName NVARCHAR(50)
	DECLARE @BodyStr NVARCHAR(200)
	
	SELECT @CompanyName = a.Name, @Name = b.Name, @Email = b.Email 
	FROM cpMain a WITH(NOLOCK), ManagerUser b WITH(NOLOCK) 
	WHERE a.ConsultantID = b.ID AND a.ID = @cpMainID

	SET @BodyStr = @Name + '，' + @CompanyName + '(编号' + CAST(@cpMainID AS VARCHAR(50)) + ')于'
	SET @BodyStr = @BodyStr + CONVERT(VARCHAR(20), GETDATE(), 120) + ' 登录前台，请予以关注。'
	IF LEN(@Email) > 0
	BEGIN TRY
		EXEC msdb.dbo.sp_send_dbmail @recipients = @email,
			@body = @BodyStr, @body_format ='HTML',
			@subject ='客户登录监控通知', @profile_Name ='service'
	END TRY
	BEGIN CATCH
	END CATCH
	SET NOCOUNT OFF
END














GO
/****** Object:  StoredProcedure [dbo].[bsCpModifyByCpMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[bsCpModifyByCpMainIDSelect]
(
	@cpMainID INT
)
AS
BEGIN
	SELECT
		ID,
        cpMainID,
        caMainID,
        SubID,
        Location,
        AddDate,
        ColValue,
        VerifyInfo,
        FilterWord
	FROM bsCpModify WITH(NOLOCK)
	WHERE cpMainID = @cpMainID
	ORDER BY caMainID, SubID, Location
END


GO
/****** Object:  StoredProcedure [dbo].[bsCpRemarkInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[bsCpRemarkInsert]
(
	@CpMainId INT,
	@AddMan INT,
	@Description VARCHAR(1000)
)
AS
SET NOCOUNT ON
BEGIN
	INSERT INTO cpRemark(CpMainId, AddMan ,[Description]) VALUES (@CpMainId, @AddMan, @Description)
END
SET NOCOUNT OFF

GO
/****** Object:  StoredProcedure [dbo].[bsCpRemarkSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[bsCpRemarkSelect]
(
	@CpMainId INT
)
AS
SET NOCOUNT ON
BEGIN
	SELECT a.*,b.Name AddName,c.Name ConsulantName, d.ConsultantID
	FROM cpRemark a WITH(NOLOCK)
	INNER JOIN cpMain d WITH(NOLOCK) ON a.cpMainId = d.ID
	INNER JOIN manageruser b WITH(NOLOCK) ON a.AddMan = b.ID
	INNER JOIN manageruser c WITH(NOLOCK) ON d.ConsultantId = c.ID
	WHERE a.CpMainId = @CpMainId ORDER BY a.AddDate DESC
END
SET NOCOUNT OFF
GO
/****** Object:  StoredProcedure [dbo].[bsCvModifyByCvMainIDLocationSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[bsCvModifyByCvMainIDLocationSelect]
(
	@cvMainID INT,
	@Location VARCHAR(4)
)
AS
BEGIN
	DECLARE @paMainID AS INT
	SELECT @paMainID=paMainID FROM cvMain
		WITH(NOLOCK)
		WHERE ID=@cvMainID
	SET @Location = LTRIM(RTRIM(@Location))
	SELECT
		ID,
		paMainID,
		cvMainID,
		SubID,
		Location,
		AddDate,
		ColValue,
		VerifyInfo
	FROM bsCvModify WITH(NOLOCK INDEX(IX_bsCvModify_paMainID))
	WHERE paMainID=@paMainID AND ISNULL(cvMainID,@cvMainID)=@cvMainID
	AND Location LIKE @Location + '%'
	ORDER BY Location
END














GO
/****** Object:  StoredProcedure [dbo].[bsCvModifyByCvMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[bsCvModifyByCvMainIDSelect]
(
	@cvMainID INT
)
AS
BEGIN
	DECLARE @paMainID AS INT
	SELECT @paMainID=paMainID FROM cvMain WITH(NOLOCK) WHERE ID=@cvMainID

	SELECT
		ID,
		paMainID,
		cvMainID,
		SubID,
		Location,
		AddDate,
		ColValue,
		VerifyInfo
	FROM bsCvModify WITH(NOLOCK INDEX(IX_bsCvModify_paMainID))
	WHERE paMainID=@paMainID AND ISNULL(cvMainID,@cvMainID)=@cvMainID
	ORDER BY Location
END














GO
/****** Object:  StoredProcedure [dbo].[bsCvModifyByNotifySelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[bsCvModifyByNotifySelect]
(
	@paMainID INT
)
AS
BEGIN
	SELECT
		ID,
		paMainID,
		cvMainID,
		SubID,
		Location,
		AddDate,
		ColValue,
		VerifyInfo
	FROM bsCvModify WITH(NOLOCK INDEX(IX_bsCvModify_paMainID))
	WHERE paMainID=@paMainID
	AND VerifyInfo > ''
	ORDER BY cvMainID,SubID,Location
END














GO
/****** Object:  StoredProcedure [dbo].[bsCvModifyByPaMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[bsCvModifyByPaMainIDSelect]
(
	@paMainID INT
)
AS
BEGIN
	SELECT
		ID,
		paMainID,
		cvMainID,
		SubID,
		Location,
		AddDate,
		ColValue,
		VerifyInfo
	FROM bsCvModify WITH(NOLOCK INDEX(IX_bsCvModify_paMainID))
	WHERE paMainID=@paMainID AND cvMainID IS NULL
	ORDER BY cvMainID,SubID,Location
END














GO
/****** Object:  StoredProcedure [dbo].[bsDoubanMailInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[bsDoubanMailInsert]
	@dcProvinceID INT,
	@ManageruserID INT,
	@UserID VARCHAR(250),
	@Title VARCHAR(100),
	@Body VARCHAR(2000)
AS
BEGIN
	DECLARE @MaxID AS INT
	INSERT INTO DoubanMail(CountDate,dcProvinceID,ManageruserID,UserID,Title) VALUES(CONVERT(varchar(8),getdate(),112),@dcProvinceID,@ManageruserID,@UserID,@Title)
	SET @MaxID = @@IDENTITY
	SET @Body = REPLACE(@Body,'#doubanid',@MaxID)
	UPDATE DoubanMail SET Body=@Body WHERE ID=@MaxID
	RETURN @MaxID
END














GO
/****** Object:  StoredProcedure [dbo].[bsEmailCheckDelete]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- 创建日期:2010-9-26
-- 创建人：Lucifer
-- 功能：删除EmailCheck数据
-- 应用于/BackStage/Consultant/EmailCheckDelete.asp页面
-- 修改时间：
-- 修改人：
-- =============================================
CREATE PROCEDURE [dbo].[bsEmailCheckDelete]
    @ID INT
AS
BEGIN
	DELETE FROM EmailCheck WHERE ID=@ID
END














GO
/****** Object:  StoredProcedure [dbo].[bsEmailCheckSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- 创建日期:2010-9-26
-- 创建人：Lucifer
-- 功能：根据条件读取企业用户反馈表中的数据
-- 应用于/BackStage/Consultant/EmailCheck.asp页面
-- 修改时间：
-- 修改人：
-- =============================================
CREATE PROCEDURE [dbo].[bsEmailCheckSelect]
    @WHERE VARCHAR(2000)
AS
BEGIN
	DECLARE @SQL AS VARCHAR(2000)
	SET @Where = dbo.SafeSql(@Where)
	SET @SQL = 'SELECT a.id,a.testdate,a.planhour,a.sendtime,a.replylong,a.manageruserid,
		b.email,b.name,a.planminute,a.remarks
		FROM emailcheck a WITH(NOLOCK),manageruser b WITH(NOLOCK)
		WHERE a.manageruserid=b.id ' +
		@Where + 
		' ORDER BY a.testdate DESC,a.planhour DESC'
	EXEC(@SQL)
END



GO
/****** Object:  StoredProcedure [dbo].[bsEmailCheckUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- 创建日期:2010-9-26
-- 创建人：Lucifer
-- 功能：更新EmailCheck数据
-- 应用于/BackStage/Consultant/EmailCheckEditProc.asp页面
-- 修改时间：
-- 修改人：
-- =============================================
CREATE PROCEDURE [dbo].[bsEmailCheckUpdate]
    @ID INT,
	@replylong SMALLINT,
	@remarks NVARCHAR(50)
AS
BEGIN
	UPDATE EmailCheck SET replylong=@replylong,remarks=@remarks
	WHERE ID=@ID
END














GO
/****** Object:  StoredProcedure [dbo].[bsFaqByIdSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[bsFaqByIdSelect]
(
	@ID INT
)
AS
BEGIN
    SELECT *
    FROM Faq WITH(NOLOCK)
    WHERE ID = @ID
	UPDATE Faq Set ClickNum = ClickNum +1 WHERE ID = @ID
END














GO
/****** Object:  StoredProcedure [dbo].[bsInfo_DateReportByMobileTodayUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[bsInfo_DateReportByMobileTodayUpdate]
AS
BEGIN
	DECLARE @AddMan INT, @ProvinceID INT, @MobileReturn INT, @MobileAccount INT, @CountDate VARCHAR(8)
	SET @CountDate = CONVERT(VARCHAR(8), GETDATE(), 112)
	--个人部分
	DECLARE curMobile CURSOR FOR 
		SELECT AddMan, ProvinceId, SUM(HasReturn), SUM(HasAccount)
		FROM bsMobileSpread WITH(NOLOCK)
		WHERE (
			CONVERT(VARCHAR(8), ReturnDate, 112) = @CountDate
			OR CONVERT(VARCHAR(8), AccountDate, 112) = @CountDate
		)
		AND UserType=1
		GROUP BY AddMan, ProvinceId

	OPEN curMobile

	FETCH NEXT FROM curMobile INTO @AddMan, @ProvinceID, @MobileReturn, @MobileAccount

	WHILE @@FETCH_STATUS = 0
	BEGIN
		IF NOT EXISTS(SELECT 'x' FROM Info_DateReport WITH(NOLOCK) WHERE CountDate = @CountDate AND Province_ID = @ProvinceID AND InfoManager_ID = @AddMan)
		BEGIN
			INSERT INTO Info_DateReport(Province_ID, InfoManager_ID, CountDate, MobileReturn, MobileAccount)
			VALUES(@ProvinceID, @AddMan, @CountDate, @MobileReturn, @MobileAccount)
		END
		ELSE
		BEGIN
			UPDATE Info_DateReport SET MobileReturn = @MobileReturn, MobileAccount = @MobileAccount
			WHERE CountDate = @CountDate
			AND Province_ID = @ProvinceID
			AND InfoManager_ID = @AddMan
		END
		FETCH NEXT FROM curMobile INTO @AddMan, @ProvinceID, @MobileReturn, @MobileAccount
	END

	CLOSE curMobile
	DEALLOCATE curMobile

	--企业部分
	DECLARE curCpMobile CURSOR FOR 
		SELECT AddMan, ProvinceId, SUM(HasReturn), SUM(HasAccount)
		FROM bsMobileSpread WITH(NOLOCK)
		WHERE (
			CONVERT(VARCHAR(8), ReturnDate, 112) = @CountDate
			OR CONVERT(VARCHAR(8), AccountDate, 112) = @CountDate
		)
		AND UserType=0
		GROUP BY AddMan, ProvinceId

	OPEN curCpMobile

	FETCH NEXT FROM curCpMobile INTO @AddMan, @ProvinceID, @MobileReturn, @MobileAccount

	WHILE @@FETCH_STATUS = 0
	BEGIN
		IF NOT EXISTS(SELECT 'x' FROM Info_DateReport WITH(NOLOCK) WHERE CountDate = @CountDate AND Province_ID = @ProvinceID AND InfoManager_ID = @AddMan)
		BEGIN
			INSERT INTO Info_DateReport(Province_ID, InfoManager_ID, CountDate, cpMobileRetNum, cpMobileAccountNum)
			VALUES(@ProvinceID, @AddMan, @CountDate, @MobileReturn, @MobileAccount)
		END
		ELSE
		BEGIN    
			UPDATE Info_DateReport SET cpMobileRetNum = @MobileReturn, cpMobileAccountNum = @MobileAccount
			WHERE CountDate = @CountDate
			AND Province_ID = @ProvinceID
			AND InfoManager_ID = @AddMan
		END
		FETCH NEXT FROM curCpMobile INTO @AddMan, @ProvinceID, @MobileReturn, @MobileAccount
	END

	CLOSE curCpMobile
	DEALLOCATE curCpMobile
END














GO
/****** Object:  StoredProcedure [dbo].[bsInfo_DateReportByMobileUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[bsInfo_DateReportByMobileUpdate]
AS
BEGIN
	DECLARE @AddMan INT, @ProvinceID INT, @MobileReturn INT, @MobileAccount INT, @CountDate VARCHAR(8)
	SET @CountDate = CONVERT(VARCHAR(8), GETDATE() - 1, 112)
	--个人部分
	DECLARE curMobile CURSOR FOR 
		SELECT AddMan, ProvinceId, SUM(HasReturn), SUM(HasAccount)
		FROM bsMobileSpread WITH(NOLOCK)
		WHERE (
			CONVERT(VARCHAR(8), ReturnDate, 112) = @CountDate
			OR CONVERT(VARCHAR(8), AccountDate, 112) = @CountDate
		)
		AND UserType=1
		GROUP BY AddMan, ProvinceId

	OPEN curMobile

	FETCH NEXT FROM curMobile INTO @AddMan, @ProvinceID, @MobileReturn, @MobileAccount

	WHILE @@FETCH_STATUS = 0
	BEGIN
		IF NOT EXISTS(SELECT 'x' FROM Info_DateReport WITH(NOLOCK) WHERE CountDate = @CountDate AND Province_ID = @ProvinceID AND InfoManager_ID = @AddMan)
		BEGIN
			INSERT INTO Info_DateReport(Province_ID, InfoManager_ID, CountDate, MobileReturn, MobileAccount)
			VALUES(@ProvinceID, @AddMan, @CountDate, @MobileReturn, @MobileAccount)
		END
		ELSE
		BEGIN
			UPDATE Info_DateReport SET MobileReturn = @MobileReturn, MobileAccount = @MobileAccount
			WHERE CountDate = @CountDate
			AND Province_ID = @ProvinceID
			AND InfoManager_ID = @AddMan
		END
		FETCH NEXT FROM curMobile INTO @AddMan, @ProvinceID, @MobileReturn, @MobileAccount
	END

	CLOSE curMobile
	DEALLOCATE curMobile

	--企业部分
	DECLARE curCpMobile CURSOR FOR 
		SELECT AddMan, ProvinceId, SUM(HasReturn), SUM(HasAccount)
		FROM bsMobileSpread WITH(NOLOCK)
		WHERE (
			CONVERT(VARCHAR(8), ReturnDate, 112) = @CountDate
			OR CONVERT(VARCHAR(8), AccountDate, 112) = @CountDate
		)
		AND UserType=0
		GROUP BY AddMan, ProvinceId

	OPEN curCpMobile

	FETCH NEXT FROM curCpMobile INTO @AddMan, @ProvinceID, @MobileReturn, @MobileAccount

	WHILE @@FETCH_STATUS = 0
	BEGIN
		IF NOT EXISTS(SELECT 'x' FROM Info_DateReport WITH(NOLOCK) WHERE CountDate = @CountDate AND Province_ID = @ProvinceID AND InfoManager_ID = @AddMan)
		BEGIN
			INSERT INTO Info_DateReport(Province_ID, InfoManager_ID, CountDate, cpMobileRetNum, cpMobileAccountNum)
			VALUES(@ProvinceID, @AddMan, @CountDate, @MobileReturn, @MobileAccount)
		END
		ELSE
		BEGIN    
			UPDATE Info_DateReport SET cpMobileRetNum = @MobileReturn, cpMobileAccountNum = @MobileAccount
			WHERE CountDate = @CountDate
			AND Province_ID = @ProvinceID
			AND InfoManager_ID = @AddMan
		END
		FETCH NEXT FROM curCpMobile INTO @AddMan, @ProvinceID, @MobileReturn, @MobileAccount
	END

	CLOSE curCpMobile
	DEALLOCATE curCpMobile
END














GO
/****** Object:  StoredProcedure [dbo].[bsJobByJobFinderOutput]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[bsJobByJobFinderOutput]
(
	@dcJobTypeID VARCHAR(100),
	@dcRegionID VARCHAR(100),
	@dcIndustryID VARCHAR(100),
	@dcSalaryID TINYINT,
	@IsNegotiable BIT,
	@MinExperience TINYINT,
	@dcEducationID TINYINT,
	@EmployType VARCHAR(10),
	@EmailNumber SMALLINT,
	@JobDesc VARCHAR(MAX) OUTPUT
)
AS
BEGIN
	SET @JobDesc = ''
	DECLARE @SQL AS VARCHAR(5000)
	IF @dcJobTypeID IS NULL
		SET @dcJobTypeID = ''
	IF @dcRegionID IS NULL
		SET @dcRegionID = ''
	IF @dcIndustryID IS NULL
		Set @dcIndustryID = ''
	IF @dcSalaryID IS NULL
		SET @dcSalaryID = 0
	IF @IsNegotiable IS NULL
		SET @IsNegotiable = 0
	IF @MinExperience IS NULL
		SET @MinExperience = 100
	IF @dcEducationID IS NULL
		SET @dcEducationID = 0
	IF @EmployType IS NULL
		SET @EmployType = ''
	ELSE
		IF @EmployType = '2'
			SET @EmployType = '1,3'

	DECLARE @T_JobPlace AS TABLE(ID INT)
	DECLARE @T_JobType AS TABLE(ID INT)
	DECLARE @JobType AS VARCHAR(3000)
	DECLARE @JobPlace AS VARCHAR(2000)

	SET @JobPlace = ''
	SET @JobType=''
	----生成工作地点的表变量
	IF LEN(@dcRegionID) > 0
	BEGIN
		INSERT INTO @T_JobPlace
		SELECT * FROM dbo.fnSplit(@dcRegionID, ',')
		SELECT @JobPlace = (@JobPlace + ' OR a.dcRegionID Like ''' + LTRIM(STR(ID) + '%''')) FROM @T_JobPlace
		IF LeN(@JobPlace) > 0
			SET @JobPlace = RIGHT(@JobPlace, LEN(@JobPlace) -4)
	END

	----生成求聘职位的表变量
	IF LEN(@dcJobTypeID) > 0
	BEGIN
		DECLARE @T_Temp AS TABLE(ID INT)		--临时表，用于构建组合查询语句
		INSERT INTO @T_Temp
		SELECT * FROM dbo.fnSplit(@dcJobTypeID, ',')

		INSERT INTO @T_JobType
		SELECT DISTINCT ID FROM dcJobType WITH(NOLOCK)
		WHERE ParentId IN(SELECT ID FROM @T_TEMP) 
		OR ParentId2 in(SELECT ID FROM @T_TEMP)
		OR ID IN(SELECT ID FROM @T_TEMP)
		----生成in字符串
		SELECT @JobType = (@JobType + LTRIM(STR(ID) + ',')) FROM @T_JobType
		IF RIGHT(@JobType, 1) = ','
			SET @JobType = LEFT(@JobType, LEN(@JobType) - 1)
	END
	CREATE TABLE #t(
			JobName NVARCHAR(50),
			cpName VARCHAR(100),
			JobID INT,
			Region VARCHAR(100),
			RefreshDate SMALLDATETIME
		)
	SET @SQL='
		INSERT INTO #t
		SELECT Top ' + CONVERT(VARCHAR(5),@EmailNumber) + ' a.Name,b.Name cpName,a.ID,
				(SELECT Description FROM dcRegion WITH(NOLOCK) WHERE dcRegion.ID = a.dcRegionId) Region,
				a.RefreshDate
		FROM Job a WITH(NOLOCK)
		INNER JOIN cpMain b WITH(NOLOCK) ON a.cpMainID=b.ID'
	IF LEN(@dcIndustryID) > 0
		SET @SQL = @SQL + '
	INNER JOIN cpIndustry c WITH(NOLOCK) ON c.cpMainID=b.ID
	AND c.dcIndustryId in(' + @dcIndustryID + ')'
	
	SET @SQL = @SQL + '
			WHERE a.IsDelete=0
			AND a.IssueDate<Getdate()
			AND a.IssueEND>Getdate()
			AND b.Valid = 1'
	----职位类别
	IF LEN(@dcJobTypeID) > 0
	SET @SQL = @SQL + '
			AND (a.dcJobTypeID IN(' + @JobType +')
				OR a.dcJobTypeIDMinor IN(' +@JobType + '))'
	IF LEN(@JobPlace) > 0 
	SET @SQL = @SQL + '
			AND (' + @JobPlace + ')'

	----月薪是本级和上级别的薪金
	IF @dcSalaryID > 0
	BEGIN
		SET @SQL = @SQL + '
			 AND (a.dcSalaryID=' + LTRIM(STR(@dcSalaryID)) + ' OR a.dcSalaryID = ' + LTRIM(STR(@dcSalaryID + 1))

		IF @IsNegotiable = 1		--包括面议
			SET @SQL = @SQL + ' OR a.dcSalaryID = 100'
		SET @SQL = @SQL + ')'
	END
	
	----工作经验要求
	IF @MinExperience < 100
	SET @SQL = @SQL + ' 
			AND a.MinExperience = ' + LTRIM(STR(@MinExperience))

	----学历要求
	----'1初中','2\3\4高中、中技、中专','5大专','6本科','7硕士','8博士
	IF @dcEducationID > 0
		IF @dcEducationID = 2
			SET @SQL = @SQL + '
					AND a.dcEducationID IN(2,3,4)'
		ELSE
			SET @SQL = @SQL + '
					AND a.dcEducationID = ' + LTRIM(STR(@dcEducationID))

	----1、全职；3、兼职；4实习。	2、全职/兼职 职位中无此项
	IF LEN(@EmployType) > 0 		
		SET @SQL = @SQL + '
					AND a.EmployType IN (' + @EmployType + ')'
	----把符合条件的职位全部列出
	SET @SQL = @SQL + 'ORDER BY RefreshDate DESC,a.ID DESC'
	EXEC(@SQL)

	SELECT @JobDesc = @JobDesc + '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;' + cpName
		+ ' 招聘:<a href="http://@@/personal/jb'+ CONVERT(VARCHAR,JobID) + '.html target="_blank">'
		+ JobName + '</a>[职位编号' + CONVERT(VARCHAR,JobID) + ']  工作地点:' + Region + '[' + CONVERT(VARCHAR,RefreshDate,120) + ']<br>'
	FROM #t

	DROP TABLE #t
END














GO
/****** Object:  StoredProcedure [dbo].[bsJobByJobFinderSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[bsJobByJobFinderSelect]
(
	@dcJobTypeID VARCHAR(100),
	@dcRegionID VARCHAR(100),
	@dcIndustryID VARCHAR(100),
	@dcSalaryID TINYINT,
	@IsNegotiable BIT,
	@MinExperience TINYINT,
	@dcEducationID TINYINT,
	@EmployType VARCHAR(10),
	@EmailNumber SMALLINT
)
AS
BEGIN
	DECLARE @SQL AS VARCHAR(5000)
	IF @dcJobTypeID IS NULL
		SET @dcJobTypeID = ''
	IF @dcRegionID IS NULL
		SET @dcRegionID = ''
	IF @dcIndustryID IS NULL
		Set @dcIndustryID = ''
	IF @dcSalaryID IS NULL
		SET @dcSalaryID = 0
	IF @IsNegotiable IS NULL
		SET @IsNegotiable = 0
	IF @MinExperience IS NULL
		SET @MinExperience = 100
	IF @dcEducationID IS NULL
		SET @dcEducationID = 0
	IF @EmployType IS NULL
		SET @EmployType = ''
	ELSE
		IF @EmployType = '2'
			SET @EmployType = '1,3'

	DECLARE @T_JobPlace AS TABLE(ID INT)
	DECLARE @T_JobType AS TABLE(ID INT)
	DECLARE @JobType AS VARCHAR(3000)
	DECLARE @JobPlace AS VARCHAR(2000)

	SET @JobPlace = ''
	SET @JobType=''
	----生成工作地点的表变量
	IF LEN(@dcRegionID) > 0
	BEGIN
		INSERT INTO @T_JobPlace
		SELECT * FROM dbo.fnSplit(@dcRegionID, ',')
		SELECT @JobPlace = (@JobPlace + ' OR a.dcRegionID Like ''' + LTRIM(STR(ID) + '%''')) FROM @T_JobPlace
		IF LeN(@JobPlace) > 0
			SET @JobPlace = RIGHT(@JobPlace, LEN(@JobPlace) -4)
	END

	----生成求聘职位的表变量
	IF LEN(@dcJobTypeID) > 0
	BEGIN
		DECLARE @T_Temp AS TABLE(ID INT)		--临时表，用于构建组合查询语句
		INSERT INTO @T_Temp
		SELECT * FROM dbo.fnSplit(@dcJobTypeID, ',')

		INSERT INTO @T_JobType
		SELECT DISTINCT ID FROM dcJobType WITH(NOLOCK)
		WHERE ParentId IN(SELECT ID FROM @T_TEMP) 
		OR ParentId2 in(SELECT ID FROM @T_TEMP)
		OR ID IN(SELECT ID FROM @T_TEMP)
		----生成in字符串
		SELECT @JobType = (@JobType + LTRIM(STR(ID) + ',')) FROM @T_JobType
		IF RIGHT(@JobType, 1) = ','
			SET @JobType = LEFT(@JobType, LEN(@JobType) - 1)
	END

	SET @SQL='
		SELECT Top ' + CONVERT(VARCHAR(5),@EmailNumber) + ' a.Name,b.Name cpName,a.ID,a.dcJobTypeID,
				a.dcJobTypeIDMinor,a.dcSalaryID,
				a.dcRegionID,(SELECT Description FROM dcRegion WITH(NOLOCK) WHERE dcRegion.ID = a.dcRegionId) Region, a.dcEducationID,a.MinExperience,
				a.RefreshDate
		FROM Job a WITH(NOLOCK)
		INNER JOIN cpMain b WITH(NOLOCK) ON a.cpMainID=b.ID'
	IF LEN(@dcIndustryID) > 0
		SET @SQL = @SQL + '
	INNER JOIN cpIndustry c WITH(NOLOCK) ON c.cpMainID=b.ID
	AND c.dcIndustryId in(' + @dcIndustryID + ')'
	
	SET @SQL = @SQL + '
			WHERE a.IsDelete=0
			AND a.IssueDate<Getdate()
			AND a.IssueEND>Getdate()
			AND b.Valid = 1'
	----职位类别
	IF LEN(@dcJobTypeID) > 0
	SET @SQL = @SQL + '
			AND (a.dcJobTypeID IN(' + @JobType +')
				OR a.dcJobTypeIDMinor IN(' +@JobType + '))'
	IF LEN(@JobPlace) > 0 
	SET @SQL = @SQL + '
			AND (' + @JobPlace + ')'

	----月薪是本级和上级别的薪金
	IF @dcSalaryID > 0
	BEGIN
		SET @SQL = @SQL + '
			 AND (a.dcSalaryID=' + LTRIM(STR(@dcSalaryID)) + ' OR a.dcSalaryID = ' + LTRIM(STR(@dcSalaryID + 1))

		IF @IsNegotiable = 1		--包括面议
			SET @SQL = @SQL + ' OR a.dcSalaryID = 100'
		SET @SQL = @SQL + ')'
	END
	
	----工作经验要求
	IF @MinExperience < 100
	SET @SQL = @SQL + ' 
			AND a.MinExperience = ' + LTRIM(STR(@MinExperience))

	----学历要求
	----'1初中','2\3\4高中、中技、中专','5大专','6本科','7硕士','8博士
	IF @dcEducationID > 0
		IF @dcEducationID = 2
			SET @SQL = @SQL + '
					AND a.dcEducationID IN(2,3,4)'
		ELSE
			SET @SQL = @SQL + '
					AND a.dcEducationID = ' + LTRIM(STR(@dcEducationID))

	----1、全职；3、兼职；4实习。	2、全职/兼职 职位中无此项
	IF LEN(@EmployType) > 0 		
		SET @SQL = @SQL + '
					AND a.EmployType IN (' + @EmployType + ')'
	----把符合条件的职位全部列出
	SET @SQL = @SQL + 'ORDER BY RefreshDate DESC,a.ID DESC'
	EXEC(@SQL)
END














GO
/****** Object:  StoredProcedure [dbo].[bsJobByJobFinderSelectNew]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[bsJobByJobFinderSelectNew]
(
	@dcProvinceID INT
)
AS
BEGIN
	SET NOCOUNT ON;
	DECLARE @dcJobTypeID AS VARCHAR(100), @dcRegionID AS VARCHAR(100), @dcIndustryID AS VARCHAR(100), 
		@dcSalaryID AS TINYINT, @MinExperience AS TINYINT, @dcEducationID AS TINYINT, 
		@EmployType AS VARCHAR(10), @EmailNumber AS SMALLINT, @ID AS INT, @JobDESC VARCHAR(MAX)

	CREATE TABLE #Job(
		ID INT IDENTITY(1, 1), 
		Email VARCHAR(50), 
		FinderName VARCHAR(50), 
		paName NVARCHAR(20), 
		UserName VARCHAR(50), 
		EmailSite VARCHAR(50), 
		SubSiteName VARCHAR(20), 
		dcJobTypeID VARCHAR(100), 
		dcRegionID VARCHAR(100), 
		dcIndustryID VARCHAR(100), 
		dcSalaryID TINYINT, 
		MinExperience TINYINT, 
		dcEducationID TINYINT, 
		EmployType VARCHAR(10), 
		EmailNumber SMALLINT, 
		JobDESC VARCHAR(MAX)
	)

	INSERT INTO #Job(Email, FinderName, paName, UserName, EmailSite, SubSiteName, dcJobTypeID, dcRegionID, dcIndustryID, 
		dcSalaryID, MinExperience, dcEducationID, EmployType, EmailNumber)
	SELECT b.Email, b.Name, CASE LEN(a.Name) WHEN 0 then '亲爱的个人用户' ELSE a.Name END as paname, a.UserName, 
		CASE LEN(a.dcsubsiteid) WHEN 2 then '' ELSE c.emailsite END as emailsite, c.subsitename, 
		dcjobtypeid, dcregionid, dcindustryid, salary, minexperience, education, employtype, emailnumber
	FROM paMain a, paJobFinder b, dcSubSite c 
	WHERE c.ID = a.dcSubSiteID
	AND a.ID = b.paMainID 
	AND b.EmailSent > 0 
	AND b.Email IS NOT NULL 
	AND b.EmailNumber IS NOT NULL 
	AND a.dcProvinceID = @dcProvinceID
	AND EmaiLEndDate > GETDATE() 
	AND (b.LastEmailDate IS NULL 
		OR DATEDIFF(d, b.LastEmailDate, GETDATE()) >= b.EmailSent
		) 
	AND LEN(a.Email) > 0 
	AND a.LastLoginDate > GETDATE() - 183 
	ORDER BY LastLoginDate DESC

	DECLARE curJob CURSOR FOR 
		SELECT id, dcjobtypeid, dcregionid, dcindustryid, dcSalaryID,
			minexperience, dcEducationID, employtype, emailnumber
		FROM #Job WITH(NOLOCK)
	OPEN curJob

	FETCH NEXT FROM curJob INTO @ID, @dcJobTypeID, @dcRegionID, @dcIndustryID, @dcSalaryID,
		@MinExperience, @dcEducationID, @EmployType, @EmailNumber
	
	IF @@FETCH_STATUS >= 0
	BEGIN
		WHILE @@FETCH_STATUS = 0
		BEGIN
			EXEC bsJobByJobFinderOutput @dcJobTypeID, @dcRegionID, @dcIndustryID, @dcSalaryID, 1, 
				@MinExperience, @dcEducationID, @EmployType, @EmailNumber, @JobDESC OUTPUT
			UPDATE #Job SET JobDESC = @JobDESC WHERE ID = @ID
			UPDATE paJobFinder SET LastEmailDate = GETDATE() WHERE ID = @ID
			FETCH NEXT FROM curJob INTO @ID, @dcJobTypeID, @dcRegionID, @dcIndustryID, @dcSalaryID, @MinExperience, @dcEducationID, @EmployType, @EmailNumber
		END
	END
	
	CLOSE curJob 
	DEALLOCATE curJob
	SELECT * FROM #Job WHERE LEN(JobDESC) > 0
	DROP TABLE #Job
END














GO
/****** Object:  StoredProcedure [dbo].[bsJobByPaJobFinderIdSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--**********************************************
--2012 11 1 nick
--根据个人的职位搜索器编号获取订阅的职位
--2013 0731 nick 
--加入邮件发送参数 
--2015-6-2 harry
--修改参数错误
--**********************************************
CREATE PROCEDURE [dbo].[bsJobByPaJobFinderIdSelect]
(
	@paJobFinderID INT
)
AS
BEGIN
	DECLARE	@dcJobTypeID VARCHAR(100),
		@dcRegionID VARCHAR(100),
		@dcIndustryID VARCHAR(100),
		@dcSalaryID TINYINT,
		@IsNegotiable BIT,
		@MinExperience TINYINT,
		@dcEducationID TINYINT,
		@EmployType VARCHAR(10),
		@EmailNumber SMALLINT,
		@Email VARCHAR(100)

	--根据搜索器编号获取email 20130731 nick
	select top 1 @Email = email from pamain where id in (select pamainid from PAJOBFINDER where id=@paJobFinderID)

	SELECT @dcJobTypeID=dcJobTypeID,@dcRegionID=dcRegionID ,@dcIndustryID=dcIndustryID,@dcSalaryID=Salary,
		@IsNegotiable=1,@MinExperience=MinExperience,@dcEducationID=Education,@EmployType=EmployType,@EmailNumber=EmailNumber
	FROM PAJOBFINDER
	WHERE ID=@paJobFinderID AND EmailNumber > 0

	IF @EmailNumber IS NULL
	BEGIN
		SELECT TOP 0 '' JobName, '' cpName, 0 JobID, '' Region, NULL RefreshDate
		RETURN
	END

	DECLARE @SQL AS VARCHAR(5000)
	IF @dcJobTypeID IS NULL
		SET @dcJobTypeID = ''
	IF @dcRegionID IS NULL
		SET @dcRegionID = ''
	IF @dcIndustryID IS NULL
		Set @dcIndustryID = ''
	IF @dcSalaryID IS NULL
		SET @dcSalaryID = 0
	IF @IsNegotiable IS NULL
		SET @IsNegotiable = 0
	IF @MinExperience IS NULL
		SET @MinExperience = 100
	IF @dcEducationID IS NULL
		SET @dcEducationID = 0
	IF @EmployType IS NULL
		SET @EmployType = ''
	ELSE
		IF @EmployType = '2'
			SET @EmployType = '1,3'

	DECLARE @T_JobPlace AS TABLE(ID INT)
	DECLARE @T_JobType AS TABLE(ID INT)
	DECLARE @JobType AS VARCHAR(3000)
	DECLARE @JobPlace AS VARCHAR(2000)

	SET @JobPlace = ''
	SET @JobType=''
	----生成工作地点的表变量
	IF LEN(@dcRegionID) > 0
	BEGIN
		INSERT INTO @T_JobPlace
		SELECT * FROM dbo.fnSplit(@dcRegionID, ',')
		SELECT @JobPlace = (@JobPlace + ' OR a.dcRegionID Like ''' + LTRIM(STR(ID) + '%''')) FROM @T_JobPlace
		IF LeN(@JobPlace) > 0
			SET @JobPlace = RIGHT(@JobPlace, LEN(@JobPlace) -4)
	END

	----生成求聘职位的表变量
	IF LEN(@dcJobTypeID) > 0
	BEGIN
		DECLARE @T_Temp AS TABLE(ID INT)		--临时表，用于构建组合查询语句
		INSERT INTO @T_Temp
		SELECT * FROM dbo.fnSplit(@dcJobTypeID, ',')

		INSERT INTO @T_JobType
		SELECT DISTINCT ID FROM dcJobType WITH(NOLOCK)
		WHERE ParentId IN(SELECT ID FROM @T_TEMP) 
		OR ParentId2 in(SELECT ID FROM @T_TEMP)
		OR ID IN(SELECT ID FROM @T_TEMP)

		----生成in字符串
		SELECT @JobType = (@JobType + LTRIM(STR(ID) + ',')) FROM @T_JobType
		IF RIGHT(@JobType, 1) = ','
			SET @JobType = LEFT(@JobType, LEN(@JobType) - 1)
	END

	CREATE TABLE #t(
		JobName NVARCHAR(50),
		cpName VARCHAR(100),
		JobID INT,
		EnJobID VARCHAR(50),
		Region VARCHAR(100),
		RefreshDate SMALLDATETIME,
		utm_campaign VARCHAR(100),
		utm_source VARCHAR(100)
		)
	SET @SQL='
		INSERT INTO #t
		SELECT TOP ' + CONVERT(VARCHAR(2), @EmailNumber) + '  a.Name,b.Name cpName,a.ID, a.SecondId,
			(SELECT Description FROM dcRegion WITH(NOLOCK) WHERE dcRegion.ID = a.dcRegionId) Region,
			a.RefreshDate,''Email_23&utm_medium=Email'',''utm_source=Mail_'+substring(@Email,PATINDEX('%@%.%',@Email),Len(@Email)-PATINDEX('%@%.%',@Email)+1)+'''
		FROM Job a WITH(NOLOCK)
		INNER JOIN cpMain b WITH(NOLOCK) ON a.cpMainID=b.ID'
	IF LEN(@dcIndustryID) > 0
		SET @SQL = @SQL + '
		INNER JOIN cpIndustry c WITH(NOLOCK) ON c.cpMainID=b.ID
		AND c.dcIndustryId in(' + @dcIndustryID + ')'
	
	SET @SQL = @SQL + '
		WHERE a.IsDelete=0
		AND a.IssueDate<Getdate()
		AND a.IssueEND>Getdate()
		AND b.Valid = 1'
	----职位类别
	IF LEN(@dcJobTypeID) > 0
	SET @SQL = @SQL + '
		AND (a.dcJobTypeID IN(' + @JobType +')
			OR a.dcJobTypeIDMinor IN(' +@JobType + '))'
	IF LEN(@JobPlace) > 0 
	SET @SQL = @SQL + '
		AND (' + @JobPlace + ')'

	----月薪是本级和上级别的薪金
	IF @dcSalaryID > 0
	BEGIN
		SET @SQL = @SQL + '
		AND (a.dcSalaryID=' + LTRIM(STR(@dcSalaryID)) + ' OR a.dcSalaryID = ' + LTRIM(STR(@dcSalaryID + 1))

		IF @IsNegotiable = 1		--包括面议
			SET @SQL = @SQL + ' OR a.dcSalaryID = 100'
		SET @SQL = @SQL + ')'
	END
	
	----工作经验要求
	IF @MinExperience < 100
	SET @SQL = @SQL + ' 
		AND a.MinExperience = ' + LTRIM(STR(@MinExperience))

	----学历要求
	----'1初中','2\3\4高中、中技、中专','5大专','6本科','7硕士','8博士
	IF @dcEducationID > 0
		IF @dcEducationID = 2
			SET @SQL = @SQL + '
		AND a.dcEducationID IN(2,3,4)'
		ELSE
			SET @SQL = @SQL + '
		AND a.dcEducationID = ' + LTRIM(STR(@dcEducationID))

	----1、全职；3、兼职；4实习。	2、全职/兼职 职位中无此项
	IF LEN(@EmployType) > 0 		
		SET @SQL = @SQL + '
		AND a.EmployType IN (' + @EmployType + ')'
	SET @Sql = @Sql + '
		AND a.Id NOT IN(SELECT JobId FROM JobSubScription WITH(NOLOCK) WHERE paJobFinderID = ' + LTRIM(STR(@paJobFinderID)) + ')'

	----把符合条件的职位全部列出
	SET @SQL = @SQL + ' ORDER BY RefreshDate DESC, a.ID DESC'
	PRINT @SQL
	EXEC(@SQL)
    
	INSERT JobSubScription(paJobFinderID, JobId) SELECT @paJobFinderID, JobId FROM #t
	SELECT * FROM #t
END

GO
/****** Object:  StoredProcedure [dbo].[bsJobByRenrenSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


-- =============================================
-- Author:		PETER
-- Create date: 2012-11-05
-- Description: 生成人人XML
-- =============================================
CREATE PROCEDURE [dbo].[bsJobByRenrenSelect] 	
AS
BEGIN
	CREATE TABLE #Job(
		[ID] [int],
		[cpMainID] [int] NOT NULL,
		[Name] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[dcJobTypeID] [smallint] NOT NULL,
		[NeedNumber] [tinyint] NULL,
		[dcSalaryID] [tinyint] NOT NULL,
		[EmployType] [tinyint] NOT NULL,
		[Responsibility] [varchar](max) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[Demand] [varchar](max) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[dcEducationID] [tinyint] NOT NULL,
		[IssueDate] [smalldatetime] NULL,
		[IssueEnd] [smalldatetime] NULL,
		[CompanyName] [Nvarchar](50),
		[SubSiteName] [varchar](50),
		[SubSiteUrl] [varchar](50),
		[RegionName] [nvarchar](50),
		[dcIndustryID] [varchar](50),
		[dcRegionID] [varchar](6),
		[SecondID] [VARCHAR](30)
	)
	CREATE TABLE #cpMain(
		[ID] [int],
		[Name] [varchar](100) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[ShortName] [varchar](40) COLLATE Chinese_PRC_CI_AS NULL,
		[dcCompanyKindID] [smallint] NULL,
		[dcCompanySizeID] [tinyint] NULL,
		[Address] [nvarchar](60) COLLATE Chinese_PRC_CI_AS NULL,
		[HomePage] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
		[Brief] [varchar](6000) COLLATE Chinese_PRC_CI_AS NULL,
		[dcIndustryID] [varchar](50),
		[SecondID] [VARCHAR](30)
	)
	INSERT INTO #Job 
	SELECT  a.ID,a.cpMainID,a.Name,a.dcJobTypeID,a.NeedNumber,a.dcSalaryID,a.EmployType,a.Responsibility,
		a.Demand,a.dcEducationID,a.IssueDate,a.IssueEnd,b.Name CompanyName,c.SubSiteName,c.SubSiteUrl,
		d.MapBarName RegionName ,dbo.GetCpIndustryId(a.cpMainID) dcIndustryID,a.dcRegionID,a.SecondID
	FROM Job AS a WITH(NOLOCK)
	INNER JOIN cpMain AS b WITH(NOLOCK) ON b.ID=a.cpMainID 
	INNER JOIN dcsubsite AS c WITH(NOLOCK) ON c.id=b.dcsubsiteID 
	INNER JOIN dcRegion as d WITH(NOLOCK) on d.id=a.dcregionID 
	WHERE (minexperience=5 or minexperience=0) AND a.valid=1 and b.valid=1
	ORDER BY a.id DESC

	INSERT INTO #cpMain
	SELECT a.ID,a.Name,a.ShortName,a.dcCompanyKindID,a.dcCompanySizeID,a.Address,a.HomePage,a.Brief,
		dbo.GetCpIndustryId(ID) dcIndustryID,a.SecondID
	FROM cpMain a WITH(NOLOCK)
	WHERE id IN(
		SELECT cpMainID 
		FROM #Job)

	SELECT * FROM #Job
	SELECT * FROM #Cpmain
END












GO
/****** Object:  StoredProcedure [dbo].[bsManagerUserByLowerSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[bsManagerUserByLowerSelect]
(
	@ID AS INT
)
AS
BEGIN
	WITH T(ID,Name,Name_Eng,Superior,DispID)
	AS
	( 
		SELECT ID,Name,Name_Eng,Superior, CONVERT(BigINT,ID) AS DispID
		FROM ManagerUSer WITH(NOLOCK)
		WHERE ID = 1
		UNION ALL
		SELECT a.ID,a.Name,a.Name_Eng,a.Superior, DispID*100 + a.ID
		FROM ManagerUSer a WITH(NOLOCK), T
		WHERE a.Superior = T.ID
		AND Status<>3
	)
	SELECT * FROM T ORDER BY CONVERT(VARCHAR(20),DispID)
END














GO
/****** Object:  StoredProcedure [dbo].[bsMobileReceivedInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--============================================= 
-- Lambo 20101020
-- 在现版的基础上修改，用于增加收到的短信记录
-- sean 20110505
-- 增加手机回复请假信息
--============================================= 
CREATE PROCEDURE [dbo].[bsMobileReceivedInsert]
(
	@Mobile VARCHAR(13), 
	@Msg NVARCHAR(200), 
	@ManagerUserId INT OUTPUT, 
	@CompanyID INT OUTPUT, 
	@CompanyName NVARCHAR(100) OUTPUT
)
AS 
BEGIN
	SET NOCOUNT ON;
	DECLARE @MaxID AS INT

	SELECT @MaxID = MAX(ID+1) FROM MobileReceived WITH(NOLOCK)
	--	IF ISNULL(@MaxID, 0) < 4000
	--		SET @MaxID = 4000
	
	INSERT INTO MobileReceived(ID, Mobile, Msg, MessageCenter, Type) VALUES(@MaxID, @Mobile, @Msg, 'qxt', 0)
	
	SELECT TOP 1 @CompanyID = CompanyID, @ManagerUserId = ManagerUserId FROM MobileSend WITH(NOLOCK) WHERE Mobile = @Mobile ORDER BY ID DESC
	IF @CompanyID IS NOT NULL
	BEGIN
		SELECT @CompanyName = Name FROM cpMain WITH(NOLOCK) WHERE ID = @CompanyID
		UPDATE MobileReceived SET CompanyID = @CompanyID, ManagerUserId = @ManagerUserId, Type = 2 WHERE ID = @MaxID
		RETURN
	END

	SELECT TOP 1 @CompanyID = a.ID, @ManagerUserId = a.ConsultantId, @CompanyName = a.Name FROM cpMain a WITH(NOLOCK), caMain b WITH(NOLOCK) WHERE a.ID = b.cpMainID AND b.Mobile = @Mobile OR b.TelePhone = @Mobile
	IF @CompanyID IS NOT NULL
	BEGIN
		UPDATE MobileReceived SET CompanyID = @CompanyID, ManagerUserId = @ManagerUserId, Type = 1 WHERE ID = @MaxID
		RETURN
	END	

	SELECT TOP 1 @CompanyID = a.cpMainID FROM JOB a WITH(NOLOCK), caMain b WITH(NOLOCK) WHERE a.caMainID = b.ID AND b.Mobile = @Mobile OR b.TelePhone = @Mobile
	IF @CompanyID IS NOT NULL
	BEGIN
		SELECT @ManagerUserId = ConsultantId, @CompanyName = CompanyName FROM Company WITH(NOLOCK) WHERE ID = @CompanyID
		UPDATE MobileReceived SET CompanyID = @CompanyID, ManagerUserId = @ManagerUserId, Type = 1 WHERE ID = @MaxID
		RETURN
	END
END














GO
/****** Object:  StoredProcedure [dbo].[bsMobileSpendByMobileExist]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[bsMobileSpendByMobileExist]
(
	@Mobile VARCHAR(11),
	@ProvinceId SMALLINT,
	@UserType TINYINT  --0 企业 1 个人
)
AS
BEGIN
	--个人手机已经注册
IF @UserType = 1 AND EXISTS(SELECT 'x' FROM paMain WITH(NOLOCK) WHERE Mobile = @Mobile)
	RETURN -2

--企业手机已经注册
IF @UserType = 0 AND EXISTS(SELECT 'x' FROM caMain WITH(NOLOCK) WHERE Mobile = @Mobile)
	RETURN -3

--手机已经推广注册
IF EXISTS(SELECT 'x' FROM bsMobileSpread WITH(NOLOCK) WHERE MobileNo = @Mobile AND UserType = @UserType)
	RETURN -4

--个人手机黑名单
IF @UserType = 1 AND  EXISTS(SELECT 'x' FROM Person_Black WITH(NOLOCK) WHERE Mobile = @Mobile)
	RETURN -5

--企业手机黑名单
IF @UserType = 0 AND  EXISTS(SELECT 'x' FROM company_black WITH(NOLOCK) WHERE Mobile = @Mobile)
	RETURN -6

--短信号码和推广地区不一致
IF NOT EXISTS(SELECT 'x' FROM dcMobileArea WITH(NOLOCK) WHERE num = LEFT(@Mobile, 7) AND dcRegionId LIKE LTRIM(STR(@ProvinceId)) + '%')
	RETURN -7

	RETURN 1
END














GO
/****** Object:  StoredProcedure [dbo].[bsMobileSpreadInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--###############################################
--Create Date:2012-05-16
--Creator:labmo
--个人和企业短信推广，前台验证通过后，插入数据
--去掉try,catch，查看出错的原因--harry2015-8-12
--###############################################
CREATE PROCEDURE [dbo].[bsMobileSpreadInsert]
(
	@Mobile VARCHAR(11),
	@ProvinceId SMALLINT,
	@AddMan SMALLINT,
	@UserType BIT,		--0企业; 1个人
	@CompanyName VARCHAR(100)=''
)
AS
SET NOCOUNT ON;
IF dbo.IsMobile(@Mobile) = 0
	RETURN -1

--个人手机已经注册
IF @UserType = 1 AND EXISTS(SELECT 'x' FROM paMain WITH(NOLOCK) WHERE Mobile = @Mobile)
	RETURN -2

--企业手机已经注册
IF @UserType = 0 AND EXISTS(SELECT 'x' FROM caMain WITH(NOLOCK) WHERE Mobile = @Mobile)
	RETURN -3

--个人手机已经推广注册
IF EXISTS(SELECT 'x' FROM bsMobileSpread WITH(NOLOCK) WHERE MobileNo = @Mobile AND UserType = @UserType)
	RETURN -4

--个人手机黑名单
IF @UserType = 1 AND  EXISTS(SELECT 'x' FROM Person_Black WITH(NOLOCK) WHERE Mobile = @Mobile)
	RETURN -5

--企业手机黑名单
IF @UserType = 0 AND  EXISTS(SELECT 'x' FROM Company_Black WITH(NOLOCK) WHERE Mobile = @Mobile)
	RETURN -6

--短信号码和推广地区不一致
IF NOT EXISTS(SELECT 'x' FROM dcMobileArea WITH(NOLOCK) WHERE num = LEFT(@Mobile, 7) AND dcRegionId LIKE LTRIM(STR(@ProvinceId)) + '%')
	RETURN -7

--检查是否超出最大范围
DECLARE @MobileNum AS INT
DECLARE @Sms_Limit AS INT

SELECT @MobileNum = CASE @UserType WHEN 1 THEN MobileNum ELSE cpMobileNum END
FROM Info_DateReport WITH(NOLOCK)
WHERE InfoManager_ID = @AddMan
AND Province_ID = @ProvinceId
AND CountDate = CONVERT(VARCHAR(8), GETDATE(), 112)

SELECT @Sms_Limit = ISNULL(CASE @UserType WHEN 1 THEN Sms_Limit ELSE cpSms_Limit END,2000) FROM Group_Province WITH(NOLOCK)
WHERE Province_ID = @ProvinceID
IF @MobileNum >= @Sms_Limit
	RETURN -8
BEGIN
	DECLARE @R AS INT
	BEGIN TRAN
		INSERT INTO bsMobileSpread(MobileNo, ProvinceId, AddMan,UserType,CompanyName) VALUES(@Mobile, @ProvinceId, @AddMan,@UserType,@CompanyName)
		SELECT @R = @@IDENTITY
		DECLARE @CountDate AS VARCHAR(8)
		SET @CountDate = CONVERT(VARCHAR(8), GETDATE(), 112)
		IF NOT EXISTS(SELECT 'x' FROM Info_DateReport WITH(NOLOCK) WHERE CountDate = @CountDate
						AND Province_ID = @ProvinceID
						AND InfoManager_ID = @AddMan)
			INSERT INTO Info_DateReport(Province_ID, InfoManager_ID, CountDate)
			VALUES(@ProvinceID, @AddMan, @CountDate)
		IF @UserType = 1 
			UPDATE Info_DateReport SET MobileNum = MobileNum + 1
			WHERE CountDate = @CountDate
			AND Province_ID = @ProvinceID
			AND InfoManager_ID = @AddMan
		ELSE
			UPDATE Info_DateReport SET cpMobileNum = cpMobileNum + 1
			WHERE CountDate = @CountDate
			AND Province_ID = @ProvinceID
			AND InfoManager_ID = @AddMan

	COMMIT
	RETURN @R
END
GO
/****** Object:  StoredProcedure [dbo].[bsPaPushLogSchedule]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--前台客户端推送 Lucifer 20160217
--职位订阅，添加推送
--关注的职位未申请的还有两天过期的，添加推送
--每天早上9点执行
CREATE PROCEDURE [dbo].[bsPaPushLogSchedule]
AS
SET NOCOUNT ON
BEGIN
	INSERT INTO paPushLog(paMainID, PushMessage, PushType, DetailID)
	SELECT b.paMainID, '智能职位搜索根据您的订阅，查询出了最近更新的部分职位，快来看看吧！', 7, a.paJobFinderID
	FROM JobSubScription a, paJobFinder b
	WHERE a.paJobFinderID = b.ID AND a.AddDate > CONVERT(VARCHAR(10), GETDATE(), 120)
		AND EXISTS(SELECT 'X' FROM paIOSBind WHERE paMainID = b.paMainID)
	GROUP BY a.paJobFinderID, b.paMainID

	INSERT INTO paPushLog(paMainID, PushMessage, PushType, DetailID)
	SELECT b.paMainID, '亲，您关注的1个职位即将到期，赶快来申请吧！', 8, a.ID FROM Job a INNER JOIN paAttention b
		ON a.ID = b.AttentionID AND b.AttentionType = 2
	WHERE a.Valid = 1 AND DATEDIFF(d, GETDATE(), a.IssueEnd) = 2
		AND NOT EXISTS(SELECT 'X' FROM exJobApply c, cvMain d WHERE c.cvMainID = d.ID AND d.paMainID = b.paMainID AND c.JobID = a.ID)
		AND EXISTS(SELECT 'X' FROM paIOSBind WHERE paMainID = b.paMainID)

	INSERT wxMessageSend2(Templatetype, WxFansID, CpMainID, AddDate, JobId)
	SELECT 18, b.ID, c.cpMainID, GETDATE(), c.Id
	FROM paLoginContact a WITH(NOLOCK), wxFans b WITH(NOLOCK), Job c WITH(NOLOCK)
	WHERE a.OpenID = b.OpenID AND c.caMainID = a.paMainID AND a.ContactType = 101 AND c.Valid = 1 AND DATEDIFF(d, GETDATE(), c.IssueEnd) = 2
END

GO
/****** Object:  StoredProcedure [dbo].[bsResume_XinxiInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- sean	2010-12-1
-- 用于信息员注册， 判断email是否存在
--返回值：
--	-1	黑名单
--	-2	QQ超限
--	-10	paMAin重复
--	-11	Resume_xinxi重复
--	----返回asp发送邮件 2011-5-17 sean
-- =============================================
CREATE PROCEDURE [dbo].[bsResume_XinxiInsert]
(
	@Email VARCHAR(50),
	@Password VARCHAR(10),
	@ManagerUserID SMALLINT,
	@ProvinceID TINYINT,
	@UserName VARCHAR(50) OUTPUT,
	@DbPassword VARCHAR(50) OUTPUT
)
AS
SET NOCOUNT ON;
SELECT @UserName = '', @DbPassword = ''
IF LEN(ISNULL(@Email, '')) = 0
	GOTO Err
IF LEN(ISNULL(@Password, '')) = 0
	GOTO Err
IF ISNULL(@ManagerUserID, 0) = 0
	GOTO Err
IF ISNULL(@ProvinceID, 0) = 0
	GOTO Err
IF dbo.IsEmail(@Email) = 0
	GOTO Err
BEGIN TRAN
	BEGIN TRY
		----检查黑名单
		IF EXISTS(SELECT 'x' FROM Person_Black WITH(NOLOCK INDEX(IX_Person_Black_Email)) WHERE Email = @Email)
			GOTO Err1

		----检查qq
		IF @Email LIKE '%@QQ.com%'
		BEGIN
			DECLARE @PersonRegNum_Our_QQ AS INT
			DECLARE @QQLimit AS INT

			SELECT @PersonRegNum_Our_QQ = PersonRegNum_Our_QQ
			FROM Info_DateReport WITH(NOLOCK)
			WHERE InfoManager_ID = @ManagerUserID
			AND Province_ID = @ProvinceID
			AND CountDate = CONVERT(VARCHAR(8), GETDATE(), 112)

			SELECT @QQLimit = QQ_Limit FROM Group_Province WITH(NOLOCK)
			WHERE Province_ID = @ProvinceID
			
			SELECT @QQLimit = @QQLimit / 5 FROM ManagerUser WITH(NOLOCK) WHERE RoleId = 52 AND ID <> 364 AND ID = @ManagerUserID

			IF @PersonRegNum_Our_QQ > @QQLimit
				GOTO Err2
		END

		----检查活动区
		IF EXISTS(SELECT 'x' FROM Resume_Xinxi WITH(NOLOCK INDEX(IX_Resume_xinxi_Email)) WHERE Email = @Email AND IsHistory = 0)
			GOTO Err11

		----检查账号
		IF EXISTS(SELECT 'x' FROM paMain WITH(NOLOCK INDEX(IX_pamain_Email)) WHERE Email = @Email)
			GOTO Err10

		----检查非活动区
		DECLARE @ResumeXinxiID AS INT, @TmpID INT,@Addman INT,@RegDate SMALLDATETIME
		SELECT TOP 1 @ResumeXinxiID = ID,
			@Addman = Addman,
			@RegDate = RegDate
		FROM Resume_Xinxi WITH(NOLOCK INDEX(IX_Resume_xinxi_Email)) 
		WHERE Email = @Email
		AND IsHistory = 1
		ORDER BY RegDate DESC

		IF @ResumeXinxiID IS NULL		--未注册，增加
		BEGIN
			INSERT INTO Resume_Xinxi(Username, Password, Email, Province_ID, AddMan, RegDate)
			VALUES(@Email, @Password, @Email, @ProvinceID, @ManagerUserID, GETDATE())
			SELECT @TmpID = @@Identity
		END
		ELSE							--已注册，激活，不修改用户名和密码
		BEGIN
			UPDATE Resume_Xinxi SET RegDate = GETDATE(), AddMan = @ManagerUSerID, Province_ID = @ProvinceID, IsHistory = 0
			WHERE ID = @ResumeXinxiID
			--将用户信息插入到ActivationCvDetail中 max 2013-08-23
			INSERT INTO LogDB..ActivationCvDetail(Username,Email,AddmanOld,AddmanNew,RegdateOld,RegdateNew)
			VALUES (@Email,@Email,@Addman,@ManagerUserID,@RegDate,GETDATE()) 

			IF NOT EXISTS(SELECT 'x' FROM Info_DateReport WITH(NOLOCK)
					WHERE Infomanager_ID = @ManagerUserID
					AND Province_ID = @ProvinceID
					AND CountDate = CONVERT(VARCHAR(8), GETDATE(), 112))
			INSERT INTO Info_DateReport(Province_Id, InfoManager_Id, CountDate)
			VALUES(@ProvinceId, @ManageruserId, CONVERT(VARCHAR(8), GETDATE(), 112))

			UPDATE Info_DateReport SET PersonalActivationCount = PersonalActivationCount + 1
			WHERE Infomanager_ID = @ManagerUserID
			AND Province_ID = @ProvinceID
			AND CountDate = CONVERT(VARCHAR(8), GETDATE(), 112)

			----返回asp发送邮件
			SELECT @UserName = UserName, @DbPassword = Password FROM Resume_Xinxi WITH(NOLOCK) 
			WHERE ID = @ResumeXinxiID

			DELETE FROM Resume_Xinxi
			WHERE Email = @Email AND IsHistory = 1

			SELECT @TmpID = @ResumeXinxiID
		END

		-----统计值是否放在这里？？？？？？？？？？？？????????????????
		UPDATE DateReport SET PersonRegNum_Our = PersonRegNum_Our + 1
		WHERE Province_ID = @ProvinceID
		AND CountDate = CONVERT(VARCHAR(8), GETDATE(), 112)
		--INSERT INTO pamainDatereport SELECT @TmpID, 7, GETDATE() -- SEAN 20130911

		IF NOT EXISTS(SELECT 'x' FROM Info_DateReport WITH(NOLOCK)
						WHERE InfoManager_ID = @ManagerUserID
						AND Province_ID = @ProvinceID
						AND CountDate = CONVERT(VARCHAR(8), GETDATE(), 112)
					)
			INSERT INTO Info_DateReport(Province_ID, InfoManager_ID, Countdate)
			VALUES(@ProvinceID, @ManagerUserID, CONVERT(VARCHAR(8), GETDATE(), 112))

		IF @Email LIKE '%@QQ.com%'
			UPDATE Info_DateReport
			SET PersonRegNum_Our = PersonRegNum_Our + 1,
			PersonRegNum_Our_QQ = PersonRegNum_Our_QQ + 1
			WHERE InfoManager_ID = @ManageruserID
			AND Province_ID = @ProvinceID
			AND CountDate = CONVERT(VARCHAR(8), GETDATE(), 112)
		ELSE
			UPDATE Info_DateReport SET PersonRegNum_Our = PersonRegNum_Our + 1
			WHERE InfoManager_ID = @ManageruserID
			AND Province_ID = @ProvinceID
			AND CountDate = CONVERT(VARCHAR(8), GETDATE(), 112)

	END TRY
	BEGIN CATCH
		GOTO Err
	END CATCH
COMMIT
RETURN 1
Err:
BEGIN
	RETURN 0
END
Err1:
BEGIN
	ROLLBACK TRAN
	RETURN -1
END
Err2:
BEGIN
	ROLLBACK TRAN
	RETURN -2
END
Err10:
BEGIN
	ROLLBACK TRAN
	RETURN -10
END
Err11:
BEGIN
	ROLLBACK TRAN
	RETURN -11
END










GO
/****** Object:  StoredProcedure [dbo].[bsschMailPrevJobResumeCreatebak2]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/****** 对象:  StoredProcedure [dbo].[bsschMailPrev2JobResumeCreate]    脚本日期: 10/18/2016 15:06:19 ******/

create PROCEDURE [dbo].[bsschMailPrevJobResumeCreatebak2]
AS
SET NOCOUNT ON
BEGIN
	IF ISNULL((SELECT TOP 1 CONVERT(VARCHAR(8), AddDate, 112) FROM schMailPrev2), '') <> CONVERT(VARCHAR(8), GETDATE(), 112)
	BEGIN
		TRUNCATE TABLE schMailPrev2
		
		--需要推荐简历的职位
		CREATE TABLE #TCaNeedPush(CaMainID INT)
		
		INSERT INTO #TCaNeedPush
		SELECT b.caMainID 
		FROM caPushSet b WITH(NOLOCK)
		WHERE ISNULL(b.PushNo,10) < 10
		AND b.LastPushdate > CONVERT(CHAR(10), GETDATE(), 120) + ' 00:00:00'
		
		INSERT INTO schMailPrev2
		SELECT 1,ISNULL(c.dcProvinceID,0),a.caMainID,ISNULL(b.Name,''),ISNULL(b.UserName,''),ISNULL(b.cpMainID,0),ISNULL(b.Name,'')+'您好，您发布的职位推荐简历',0,CASE LEN(c.dcsubsiteid) WHEN 2 THEN '' ELSE ISNULL(d.emailsite,'') END,ISNULL(b.Email,''),ISNULL(d.SubsiteName,''),NULL,0,GETDATE(),NULL,NULL,NULL,c.dcRegionID,NULL,NULL
		FROM #TCaNeedPush a
		LEFT JOIN caMain b WITH(NOLOCK) ON b.id = a.caMainID
		LEFT JOIN cpMain c WITH(NOLOCK) ON c.id = b.cpMainID
		LEFT JOIN dcSubsite d WITH(NOLOCK) ON d.id = c.dcSubsiteID
		
		DELETE FROM schMailPrev2 WHERE Email LIKE '%qq.com'
	END

	DECLARE @Rows AS INT, @i AS INT, @Content AS VARCHAR(MAX), @MinID AS INT
	SELECT @Rows = COUNT(*), @MinID = MIN(ID), @I=0 FROM schMailPrev2 WITH(NOLOCK) WHERE MailBody IS NULL
	
	DECLARE @TJob AS TABLE(JobID INT,JobName NVARCHAR(50),JobSecondID VARCHAR(20))
	IF @Rows = 0
		RETURN

	WHILE @i < @Rows
	BEGIN
		DELETE FROM  @TJob
		
		INSERT INTO @TJob
		SELECT a.JobID,b.Name JobName,b.SecondID JobSecondID
		FROM caJobCvMatch a WITH(NOLOCK)
		LEFT JOIN JobPublish b WITH(NOLOCK) ON b.ID = a.JobID
		WHERE a.JobID IN (
			SELECT ID 
			FROM JobPublish WITH(NOLOCK) 
			WHERE caMainID = (
				SELECT TOP 1 AccountID 
				FROM schMailPrev2 WITH(NOLOCK) 
				WHERE id = @i + @MinID
			)
		)
		
		DECLARE @PushJobID INT,@PushJobName NVARCHAR(50),@PushJobSecondID VARCHAR(20)
		SET @Content = ''
		
		WHILE EXISTS(SELECT 'x' FROM @TJob)
		BEGIN
			SELECT TOP 1 @PushJobID = JobID,@PushJobName = JobName,@PushJobSecondID = JobSecondID
			FROM @TJob
			ORDER BY JobID ASC
			
			SET @Content = @Content + '<tr><td colspan=5><a href="http://##SiteUrl##/personal/jb' + @PushJobSecondID + '.html" target="_blank">' + @PushJobName + '</a></td></tr>'
			
			SELECT @Content = @Content + '<tr>' + 
			'<td>'+ISNULL(b.Name, '  ')+'[<a href="http://##SiteUrl##/Company/cv/cvview?id=' + CONVERT(VARCHAR, b.ResumeID) + '" target="_blank">' + CONVERT(VARCHAR, b.ResumeID) + '</a>]</td>'+
			'<td>'+(CASE ISNULL(b.Sex, 0) WHEN 0 THEN '男' WHEN 1 THEN '女' END)+'</td>'+
			'<td>'+CONVERT(VARCHAR, ISNULL(b.Age, 30))+'</td>'+
			'<td>'+ISNULL(b.JobType, '  ')+'</td>'+
			'<td>'+ISNULL(b.AtPlaceDesc, '  ')+'</td>'+		
			'</tr>'
			FROM caJobCvMatch a WITH(NOLOCK),caJobResumePre b WITH(NOLOCK)
			WHERE a.MatchCvMainID = b.ResumeID
			AND a.JobID = @PushJobID
			AND a.PushDate IS NULL
			ORDER BY b.LastLoginDate DESC
			
			UPDATE caJobCvMatch 
			SET PushDate = GETDATE() 
			WHERE JobID = @PushJobID
			
			DELETE FROM @TJob WHERE JobID = @PushJobID
		END
		
		IF LEN(LTRIM(RTRIM(ISNULL(@Content, '')))) = 0
			UPDATE schMailPrev2 
			SET MailBody = '<br>&nbsp;&nbsp;符合您招聘职位的推荐简历已经全部发送，暂时没有新的简历出现。您可以登录网站后使用“职位管理”-->“发布中的职位”，修改给你推荐的频率。<br>&nbsp;&nbsp;',
				RefreshDate = GETDATE()
			WHERE ID = @I+@MinID
		ELSE
			UPDATE schMailPrev2 
			SET MailBody = '以下是贵单位招聘职位推荐的部分简历。<br><table style="font-size:12px"><tr style="FONT-WEIGHT: bold; background-color:#f7b666;"><td>求职者</td><td>性别</td><td>年龄</td><td>求职意向</td><td>所在地</td></tr>' + @Content + '</table>详细情况请登录网站后使用“简历搜索”-->“<a href="http://##SiteUrl##/Company/cvSearch/Search" target="_blank">搜索简历</a>”-->点击“更多搜索条件”-->输入“简历编号”搜索。',
				RefreshDate = GETDATE()
			WHERE ID = @I+@MinID

		UPDATE a
		SET a.MailBody = REPLACE(a.MailBody, '##SiteUrl##', 'www.' + b.ProvinceDomain)
		FROM schMailPrev2 a,dcProvince b
		WHERE a.dcProvinceId = b.Id
		AND a.Id = @I+@MinID
		
		SET @i = @i + 1
	END
	DELETE schMailPrev2 WHERE Email LIKE '%qq.com'
END
GO
/****** Object:  StoredProcedure [dbo].[ccActiveDownExist]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--######################################3
--创建：Lambo，修改Sean
--检查企业账号是否消耗日配额看过简历联系方式
--企业有多账号的情况，一个企业内部的查看共享
--######################################3
CREATE PROCEDURE [dbo].[ccActiveDownExist]
(
    @cpMainID INT,
	@cvMainID INT
)
AS
BEGIN
	DECLARE @paMainId INT
	SELECT @paMainID = paMainID FROM cvMain WITH(NOLOCK) WHERE ID = @cvMainID
	IF EXISTS(SELECT 'x' FROM caActiveLog WITH(NOLOCK) 
			WHERE cpMainID = @cpMainID
			AND cvMainId IN(SELECT ID FROM cvMain WITH(NOLOCK) WHERE paMainID = @paMainID)
		)
		RETURN 1
	
	IF EXISTS(SELECT 'x' FROM caDailyGiftLog WITH(NOLOCK) WHERE cpMainID = @cpMainID AND cvMainID = @cvMainID)
		RETURN 1

	IF EXISTS (
		SELECT 'x' FROM ExJobApply a WITH(NOLOCK),Job b 
		WHERE a.JobID = b.ID 
		AND a.IsPassed = 1 
		AND a.cvMainID IN(SELECT ID FROM cvMain WITH(NOLOCK) WHERE paMainID = @paMainID)
		AND b.cpMainID = @cpMainID
	)
		RETURN 1

	RETURN 0
END














GO
/****** Object:  StoredProcedure [dbo].[ccAdverProjectByProvinceIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.31
--创建人：Nick
--说明：获取需要显示的图片
--#####################################################
CREATE PROCEDURE [dbo].[ccAdverProjectByProvinceIDSelect]
(
	@ProvinceID INT,
	@TopNum INT,
	@TypeID INT
)
AS
BEGIN TRY
	DECLARE @SQL VARCHAR(500)
	SET @SQL = 'SELECT TOP '+CONVERT(VARCHAR(4),@TopNum)+'  *  FROM [MainDb]..[AdverProject] ' 
	SET @SQL = @SQL + ' WHERE Province_Id = ' + CONVERT(VARCHAR(6),@ProvinceID) 
	+ ' AND TYPE = ' + CONVERT(VARCHAR(4),@TypeID) + ' AND VALID = 1 '
	SET @SQL = @SQL + ' AND BeginTime <'''+CONVERT(VARCHAR(20),GETDATE()) +''' AND EndTime> ''' + CONVERT(VARCHAR(20),GETDATE()) +''''
	SET @SQL = @SQL + ' ORDER BY OrderBy ASC '
	PRINT(@SQL)
	EXEC(@SQL)
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[ccBsCpModifyVerifyInfoCheckSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.30
--创建人：Nick
--说明：用于判断，企业简介
--#####################################################
CREATE PROCEDURE [dbo].[ccBsCpModifyVerifyInfoCheckSelect]
(
	@CpMainID INT
)
AS
BEGIN
	SELECT VerifyInfo 
	FROM bsCpModify 
	WHERE VerifyInfo > ''
	AND cpMainID = @CpMainID
	AND Location = 'a5'
END

GO
/****** Object:  StoredProcedure [dbo].[ccBsCpModifyVerifyInfoSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.30
--创建人：Nick
--说明：得到修改信息
--#####################################################
CREATE PROCEDURE [dbo].[ccBsCpModifyVerifyInfoSelect]
(
	@CpMainID INT
)
AS
BEGIN
	SELECT 'x'
	FROM bsCpModify 
	WHERE VerifyInfo Is Null 
	AND cpMainID = @CpMainID
END

GO
/****** Object:  StoredProcedure [dbo].[ccbsCpVerifyByCpMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.30
--创建人：Nick
--说明：获取企业审核信息
--#####################################################
CREATE PROCEDURE [dbo].[ccbsCpVerifyByCpMainIDSelect]
(
	@cpMainID INT
)
AS
BEGIN TRY
	SELECT Top 1 * FROM bsCpVerify WITH(NOLOCK) 
	WHERE cpMainID = @cpMainID 
	ORDER BY ID DESC
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[ccbsCvModifyByPaMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----------------
--创建日期：2010-9-26
--创建人：lambo
--功能说明：根据个人编号和简历编号查询一份简历的审核结果记录
--用于前台简历显示页面
-----------------
CREATE PROCEDURE [dbo].[ccbsCvModifyByPaMainIDSelect]
(
    @PaMainID INT,
	@cvMainID INT
)
AS
BEGIN
    SELECT SubID,location,VerifyInfo FROM bsCvModify WITH(NOLOCK) 
		WHERE VerifyInfo IS NOT NULL AND paMainID=@PaMainID AND cvMainID=@cvMainID AND VerifyInfo <> (
			SELECT TOP 1 VerifyInfo FROM bsCvVerify WHERE paMainID=@PaMainID ORDER BY VerifyDate DESC)
END














GO
/****** Object:  StoredProcedure [dbo].[cccaActiveLogByCvMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--Lambo 20101022
--查询某单位是否用简历下载点数或者用每日赠送的点数下载过该简历或者是否在申请的记录中不检查权限
--用于简历显示页面
CREATE PROCEDURE [dbo].[cccaActiveLogByCvMainIDSelect]
(
	@cpMainID INT,
	@cvMainID INT
)
AS
SET NOCOUNT ON
BEGIN
	DECLARE @isInActiveLog INT, @isInDailyGiftLog INT, @paMainID INT
	
	SELECT @isInDailyGiftLog = COUNT(1)
	FROM caDailyGiftLog WITH(NOLOCK INDEX(PK_caDailyGiftLog))
	WHERE cpMainID = @cpMainID
	AND cvMainID = @cvMainID

	IF @isInDailyGiftLog>0 
		RETURN 1

	SELECT @paMainId = paMainId FROM cvMain WITH(NOLOCK) WHERE ID = @cvMainID

	DECLARE @t AS TABLE(ID INT)
	INSERT INTO @t
	SELECT ID FROM cvMain WITH(NOLOCK) WHERE paMainId = @paMainID

	SELECT @isInActiveLog = COUNT(1)
	FROM caActiveLog WITH(NOLOCK INDEX(IX_caActiveLog_cpMainID))
	WHERE cpMainID = @cpMainID
	AND cvMainID IN(SELECT ID FROM @t)

	If @isInActiveLog>0  
		RETURN 1

	IF EXISTS (
		SELECT 'x' FROM ExJobApply a WITH(NOLOCK),Job b 
		WHERE a.JobID = b.ID 
		AND a.IsPassed = 1 
		AND a.cvMainID  IN(SELECT ID FROM @t)
		AND b.cpMainID = @cpMainID
	)
		RETURN 1
	ELSE
		RETURN 0
END
GO
/****** Object:  StoredProcedure [dbo].[ccCaActiveLogInsertNew]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--###################################################3
--###################################################3
--创建：		sean
--时间：		2010-11-15
--查看简历消耗简历下载
--修改harry 增加简历下载配额 2017-12-12
--修改harry 2018-5-24 下载记录增加 人名 
--###################################################3
CREATE PROCEDURE [dbo].[ccCaActiveLogInsertNew]
(
	@cpMainID INT, 	
	@caMainID INT, 
	@cvMainID INT, 
	@IP VARCHAR(31),
	@First TINYINT		--first 1, else 2
)
AS
SET NOCOUNT ON
BEGIN TRAN
	BEGIN TRY
		IF NOT EXISTS(SELECT 'x' FROM cpMain WITH(NOLOCK), caMain WITH(NOLOCK) WHERE cpMain.Id = @cpMainID AND caMain.cpMainID = @cpMainID AND cpMain.Valid=1 AND caMain.IsDelete=0 AND caMain.IsPause = 0)
			GOTO Err1

		IF NOT(ISNULL(@cvMainID, 0) < 0 AND @IP = '每月扣除')
			IF NOT EXISTS(SELECT 'x' FROM paMain a WITH(NOLOCK), cvMain b WITH(NOLOCK) WHERE a.ID = b.paMainID AND b.Id = @cvMainID AND (ISNULL(b.Attachment, '')<>'' OR ISNULL(a.Mobile, '')<>''))
				GOTO Err2

		
		----取订单信息，计算sun(activequota), SUM(remainquota)
		DECLARE @RemainQuota AS INT
		DECLARE @RemainQuotaALL AS INT
		DECLARE @OrderID AS INT
		DECLARE @MainOrderID AS INT --harry
		DECLARE @IsAllocate AS BIT --harry

		SELECT @RemainQuotaALL = SUM(RemainQuota) FROM caOrder WITH(NOLOCK)
		WHERE cpMainID=@cpMainID AND OpenDate IS NOT NULL
		AND BeginDate < GETDATE() AND EndDate > GETDATE()
		AND RemainQuota > 0
	
		IF ISNULL(@RemainQuotaALL, 0) < 1
			GOTO Err3

		SELECT TOP 1 @OrderID = ID, @RemainQuota = RemainQuota FROM caOrder WITH(NOLOCK)
		WHERE cpMainID=@cpMainID AND OpenDate IS NOT NULL
		AND BeginDate < GETDATE() AND EndDate > GETDATE()
		AND RemainQuota > 0
		ORDER BY ID
		
		IF ISNULL(@OrderID, 0) = 0
			GOTO Err4
		
		--harry begin2017-12-12 简历配额
		SELECT TOP 1 @MainOrderID = ID,@IsAllocate = isCvAllocate FROM caOrder WITH(NOLOCK)
		WHERE cpMainID=@cpMainID AND OpenDate IS NOT NULL
		AND orderType = 8 
		AND BeginDate < GETDATE() AND EndDate > GETDATE()
		
		IF ISNULL(@IsAllocate,0)!=0--分配了配额
		BEGIN 
			IF NOT EXISTS(SELECT 'x' FROM quotaLog WHERE CaOrderId = @MainOrderID AND CaMainId=@caMainID AND cpMainID=@cpMainID AND RemainQuota>0)
			BEGIN
				GOTO Err3
			END
		END
                --harry end2017-12-12 简历配额
		DECLARE	@Num AS INT
		EXEC @Num = ccActiveDownExist @cpMainID, @cvMainID
		IF @Num = 0
		BEGIN
			DECLARE @paMainID INT, @CaActiveLogID INT, @wxFansId INT, @Mobile VARCHAR(20)
			SELECT @paMainId = paMainId FROM cvMain WITH(NOLOCK) WHERE Id = @cvMainID
			IF @First = 1
			BEGIN
				SELECT @mobile = Mobile FROM paMain WITH(NOLOCK) WHERE Id = @paMainId
				IF @Mobile > ''
				BEGIN
					IF EXISTS(SELECT 'x' FROM CaActiveLog a WITH(NOLOCK), cvMain b WITH(NOLOCK), paMain c WITH(NOLOCK)
						WHERE a.cpMainId = @cpMainId 
						AND a.cvMainId = b.Id
						AND b.paMAinId = c.Id
						AND c.Mobile = @Mobile 
						AND c.Id <> @paMainId)
						GOTO Err6
				END
			END
			SET @RemainQuota = @RemainQuota - 1
			SET @RemainQuotaALL = @RemainQuotaALL - 1
                        DECLARE @name VARCHAR(20)
			select @name=name from pamain where id=(select paMainID from cvmain where id=@cvMainID)
			INSERT INTO CaActiveLog(cpMainID, caMainID, cvMainID, caOrderID, IP, RemainQuota,paName)
			VALUES(@cpMainID, @caMainID, @cvMainID, @OrderID, @IP, @RemainQuota,@name)
			
			--harry begin2017-12-12 简历配额
			IF ISNULL(@IsAllocate,0)!=0--分配了配额
			BEGIN 
				UPDATE quotalog SET RemainQuota = RemainQuota -1 WHERE CaOrderId = @MainOrderID AND CaMainId=@caMainID AND cpMainID=@cpMainID AND RemainQuota>0
			END
			--harry end2017-12-12 简历配额
			--Harry Begin
			
			SELECT @CaActiveLogID = @@IDENTITY
			UPDATE caOrder SET RemainQuota = RemainQuota - 1 WHERE ID = @OrderID
			SELECT @wxFansId = id FROM wxFans WITH(NOLOCK) WHERE paMainId = @paMainId AND [Status] = 2
			IF @wxFansId > 0
			BEGIN
				--插入到wxMessageSend表中
				INSERT WxMessageSend2(Templatetype, WxFansID, PaMainId, MainTableId, CpMainID, CvMainID, CaMainId, AddDate)
				SELECT 6, @wxFansId, @paMainId, @CaActiveLogID, @cpMainId, @cvMainID, @caMainID, GETDATE()
			END
			--Harry End			
		END
	END TRY
	BEGIN CATCH
		PRINT error_message()
		GOTO Err5
	END CATCH
COMMIT
RETURN @RemainQuotaALL
Err:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END
----企业账号信息不正确
Err1:
BEGIN
	ROLLBACK TRAN
	RETURN -1
END
----简历id是无效简历id
Err2:
BEGIN
	ROLLBACK TRAN
	RETURN -2
END
----剩余点数RemainQuota 不足1
Err3:
BEGIN
	ROLLBACK TRAN
	RETURN -3
END
----无订单号
Err4:
BEGIN
	ROLLBACK TRAN
	RETURN -4
END
----其他错误
Err5:
BEGIN
	ROLLBACK TRAN
	RETURN -5
END
----有手机号重复　提醒是否下载
Err6:
BEGIN
	ROLLBACK TRAN
	RETURN -6
END

GO
/****** Object:  StoredProcedure [dbo].[cccaActiveLogSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--修改harry 2018-5-24
--增加cv secondid
CREATE PROCEDURE [dbo].[cccaActiveLogSelect]
(
	@cpMainID INT,
	@WHERE VARCHAR(1000),
	@ORDER VARCHAR(100)
)
AS
BEGIN
	SET @Where = dbo.SafeSql(@Where)
	SET @ORDER = dbo.SafeSQLBack(@ORDER)
 
	DECLARE @SQL AS VARCHAR(2000)
	SET @SQL = 'SELECT a.*, b.Name, c.paMainID, c.SecondId
		FROM caActiveLog a WITH(NOLOCK) 
		LEFT JOIN caMain b WITH(NOLOCK) ON a.caMainID = b.ID
		LEFT JOIN cvMain c WITH(NOLOCK) ON a.cvMainId = c.Id
		WHERE a.caOrderID IN(SELECT ID FROM caOrder WHERE cpMainID=' + RTRIM(STR(@cpMainID)) + 'AND IsDeleted=0) AND a.cpMainID=' + RTRIM(STR(@cpMainID))
	IF LEN(@WHERE) > 0
		SET @SQL = @SQL + ' ' + @WHERE
	IF LEN(@ORDER) > 0
		SET @SQL = @SQL + '
		ORDER BY ' + @ORDER
	ELSE
		SET @SQL = @SQL + '
		ORDER BY a.caOrderID DESC,a.RemainQuota'
	EXEC(@SQL)
END




GO
/****** Object:  StoredProcedure [dbo].[ccCaBalanceLogByCvMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ccCaBalanceLogByCvMainIDSelect]
(
    @cpMainID INT,
	@cvMainID INT
)
AS
BEGIN
	IF EXISTS(
		SELECT 'x' FROM caBalanceLog WITH(NOLOCK)
		WHERE cpMainID = @cpMainID
		AND cvMainID = @cvMainID
		AND CONVERT(VARCHAR(10), AddDate, 120) = CONVERT(VARCHAR(10), GETDATE(), 120)
		)
		RETURN 1
	ELSE
		RETURN 0
END














GO
/****** Object:  StoredProcedure [dbo].[ccCaBalanceLogInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ccCaBalanceLogInsert]
(
	@cpMainID INT,
	@caMainID INT,	
	@cvMainID INT=NULL,
    @IsAgent BIT,
    @ReduceMoney INT,
    @IP VARCHAR(30),
	@BalanceType TINYINT
)
AS
BEGIN TRAN
	IF NOT EXISTS(SELECT 'x' FROM caMain WITH(NOLOCK) WHERE ID = @caMainID AND cpMainID = @cpMainID)
		GOTO Err
   
	BEGIN TRY
		DECLARE @Balance AS INT
		DECLARE	@IsPaid AS INT

		EXEC @IsPaid = ccCaBalanceLogByCvMainIDSELECT @cpMainID, @cvMainID
		IF @IsPaid != 1
		BEGIN
			SELECT @Balance=Balance FROM cpMain WHERE ID = @cpMainID
			IF @Balance >0		--@ReduceMoney 
			BEGIN
				SET @Balance = @Balance - @ReduceMoney
				INSERT INTO caBalanceLog(cpMainID,caMainID,cvMainID,IsAgent,ReduceMoney,Balance,IP,BalanceType)
				VALUES(@cpMainID,@caMainID,@cvMainID,@IsAgent,@ReduceMoney,@Balance,@IP,@BalanceType)
				UPDATE cpMain SET balance = @balance WHERE ID = @cpMainID
				IF @Balance<1
				BEGIN 
					SET @Balance = 0
					UPDATE cpMain SET balance = 0 WHERE ID = @cpMainID
				END
			END
			ELSE
				GOTO ERR1
		END
	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH
COMMIT
RETURN @Balance
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN -10
END
ERR1:
BEGIN
	ROLLBACK TRAN
	RETURN -11
END
----简历id是无效简历id
ERR2:
BEGIN
	ROLLBACK TRAN
	RETURN -2
END














GO
/****** Object:  StoredProcedure [dbo].[cccaBalanceLogSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--修改人 Lucifer
--修改时间 2013-11-7
--修改原因 添加手机认证时间
CREATE PROCEDURE [dbo].[cccaBalanceLogSelect]
(
	@cpMainID INT,
	@WHERE VARCHAR(1000),
	@ORDER VARCHAR(100),
	@Page SMALLINT,
	@caMainID INT
)
AS
BEGIN
	BEGIN TRY
		SET @Where = dbo.SafeSql(@Where)
		SET @ORDER = dbo.SafeSql(@Order)

		DECLARE @SQL VARCHAR(2000)
		CREATE TABLE #T(
			TitleID BIGINT,
			cvMainID INT,
			ReduceMoney INT,
			Balance INT,
			BalanceType TINYINT,
			IP VARCHAR(39) COLLATE Chinese_PRC_CI_AS NOT NULL,
			Degree TINYINT,
			RelatedWorkYears TINYINT,
			Attachment VARCHAR(50) COLLATE Chinese_PRC_CI_AS ,
			IsNameHidden BIT,
			LivePlace VARCHAR(6) COLLATE Chinese_PRC_CI_AS ,
			Gender BIT,
			paName NVARCHAR(12),
			BirthDay INT,
			HasPhoto TINYINT,
			AddDate SMALLDATETIME,
			Valid TINYINT,
			HasJobApply BIT,
			HasInterview BIT,
			HasRemark BIT,
			HasFavorate BIT,
			MobileVerifyDate SMALLDATETIME
		)
		SET @SQL='
			INSERT INTO #T(TitleID,cvMainID,ReduceMoney,Balance,BalanceType,IP,AddDate,Degree,RelatedWorkYears,
				Attachment,IsNameHidden,LivePlace,Gender,paName,BirthDay,HasPhoto,Valid,MobileVerifyDate)
			SELECT ROW_NUMBER() OVER (ORDER BY ' + @ORDER + ') AS TitleID,
				a.cvMainID,a.ReduceMoney,Balance,BalanceType,IP,a.AddDate,
				b.Degree,b.RelatedWorkYears,b.Attachment,b.IsNameHidden,
				c.LivePlace,c.Gender,c.Name AS paName,c.BirthDay,c.HasPhoto,b.Valid,c.MobileVerifyDate
			FROM caBalanceLog a WITH(NOLOCK)
			LEFT JOIN cvMain b WITH(NOLOCK) ON b.ID = a.cvMainID
			LEFT JOIN paMain c WITH(NOLOCK) ON c.ID = b.paMainID'
		IF LEN(@WHERE) > 0
			SET @SQL = @SQL + ' WHERE cpMainID = ' + LTRIM(STR(@cpMainID)) + @WHERE

		--PRINT @SQL
		EXEC(@SQL)

		UPDATE #T SET paName = dbo.JobApplyName(IsNameHidden, paName, Gender),
			HasJobApply = (SELECT TOP 1 '1' FROM exJobApply a WITH(NOLOCK) INNER JOIN Job b WITH(NOLOCK) ON a.JobID=b.ID WHERE a.CompanyDeleted=0 AND b.caMainID=@caMainID AND cvMainID=#T.cvMainID),
			HasInterview = (SELECT TOP 1 '1' FROM exInterview a WITH(NOLOCK) INNER JOIN Job b WITH(NOLOCK) ON a.JobID=b.ID WHERE a.CompanyDeleted=0 AND b.caMainID=@caMainID AND cvMainID=#T.cvMainID),
			HasRemark = (SELECT TOP 1 '1' FROM caCvRemark WITH(NOLOCK) WHERE caMainID=@caMainID AND cvMainID=#T.cvMainID),
			HasFavorate = (SELECT TOP 1 '1' FROM caFavorate WITH(NOLOCK) WHERE caMainID=@caMainID AND cvMainID=#T.cvMainID)
		WHERE TitleID > (@Page-1)*20 AND TitleID <= @Page*20
		
		SELECT COUNT(*) FROM #T WITH(NOLOCK)
		SELECT * FROM #T WITH(NOLOCK) WHERE TitleID > (@Page-1)*20 AND TitleID <= @Page*20
		
		DROP TABLE #T
	END TRY
	BEGIN CATCH
		DROP TABLE #T
	END CATCH
END












GO
/****** Object:  StoredProcedure [dbo].[ccCaContactByCaMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.7
--创建人：John
--说明：根据参数从caContact表中查询20minutes内有没有提交过
--修改： Mice 123 2015-3-11 修改联系时间为20分钟
--#####################################################
CREATE PROCEDURE [dbo].[ccCaContactByCaMainIDSelect]
(
	@caMainID INT
)
AS
BEGIN
	SELECT TOP 1 'x' FROM CaContact WITH(NOLOCK) WHERE camainid = @caMainID AND adddate > DATEADD(mi,-20,GETDATE())
END
GO
/****** Object:  StoredProcedure [dbo].[ccCaContactInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.30
--创建人：Nick
--说明：//保存客户要求回电记录
--#####################################################
CREATE PROCEDURE [dbo].[ccCaContactInsert]
(
	@caMainID INT,
	@cpMainid INT,
	@telephone VARCHAR(20),
	@name VARCHAR(20)
)
AS
SET NOCOUNT ON
BEGIN
	IF EXISTS(SELECT 'x' FROM CaContact WITH(NOLOCK) WHERE caMainId = @caMainId AND AddDate > DATEADD(MINUTE, -2, GETDATE()))
		RETURN 0

	INSERT INTO CaContact(camainid, cpmainid, telephone, name) 
	VALUES(@caMainID, @cpMainid, @telephone, @name)
	RETURN 1
END
GO
/****** Object:  StoredProcedure [dbo].[cccaCvActionsSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--########################333
--该存储过程的安全验证在asp文件中进行
--########################333
CREATE PROCEDURE [dbo].[cccaCvActionsSelect]
(
	@cvMainID INT,
	@caMainID INT,
	@HasJobApply INT OUT,
	@HasInterview INT OUT,
	@HasRemark INT OUT,	
	@HasFavorate INT OUT
)
AS
BEGIN
	IF EXISTS(SELECT a.ID FROM exJobApply a WITH(NOLOCK) INNER JOIN Job b WITH(NOLOCK) ON a.JobID=b.ID WHERE b.caMainID=@caMainID AND cvMainID=@cvMainID)
		SET @HasJobApply = 1
	ELSE
		SET @HasJobApply = 0
	IF EXISTS(SELECT a.ID FROM exInterview a WITH(NOLOCK) INNER JOIN Job b WITH(NOLOCK) ON a.JobID=b.ID WHERE b.caMainID=@caMainID AND cvMainID=@cvMainID)
		SET @HasInterview = 1
	ELSE
		SET @HasInterview = 0
	IF EXISTS(SELECT ID FROM caCvRemark WITH(NOLOCK) WHERE caMainID=@caMainID AND cvMainID=@cvMainID)
		SET @HasRemark = 1
	ELSE
		SET @HasRemark = 0
	IF EXISTS(SELECT a.ID FROM caFavorate a WITH(NOLOCK) INNER JOIN Job b WITH(NOLOCK) ON a.JobID=b.ID WHERE b.caMainID=@caMainID AND cvMainID=@cvMainID)
		SET @HasFavorate = 1
	ELSE
		SET @HasFavorate = 0
END














GO
/****** Object:  StoredProcedure [dbo].[ccCaCvApplyDeletedSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--lambo 20140428
--查询企业删除的应聘的简历 
--修改:Andy 2015-01-13 添加职位的regionid 
CREATE PROCEDURE [dbo].[ccCaCvApplyDeletedSelect] --'', 'a.adddate', 1, 234434
(
	@WHERE VARCHAR(1000), 
	@Order VARCHAR(100), 
	@Page SMALLINT, 
	@caMainID INT
)
AS
SET NOCOUNT ON
BEGIN
	SET @Where = dbo.SafeSql(@Where)
	SET @ORDER = dbo.SafeSql(@Order)
	DECLARE @SQL AS VARCHAR(2000)
	CREATE TABLE #T(
		TitleID BIGINT, 
		ID INT, 
		JobID INT, 
		jobRegionID INT, 
		JobName NVARCHAR(50), 
		paMainID INT, 
		cvMainID INT, 
		AddDate SMALLDATETIME, 
		ApplyDate SMALLDATETIME, 
		Reply TINYINT, 			
		Degree TINYINT, 
		RelatedWorkYears TINYINT, 
		LivePlace NVARCHAR(50), 
		Gender BIT, 
		paName NVARCHAR(20), 
		BirthDay INT, 
		HasPhoto TINYINT, 
		Attachment VARCHAR(100) COLLATE Chinese_PRC_CI_AS, 
		IsNameHidden BIT, 
		Valid TINYINT, 		
		IsViewed BIT, 
		HasInterview BIT, 
		HasRemark BIT, 
		HasFavorate BIT, 
		cvEducationID INT, 
		College NVARCHAR(100), 
		EduType TINYINT, 
		MajorName NVARCHAR(50), 
		Graduation INT, 
		Speciality VARCHAR(MAX) COLLATE Chinese_PRC_CI_AS, 
		Experience VARCHAR(MAX) COLLATE Chinese_PRC_CI_AS, 						
		MobileVerifyDate SMALLDATETIME, 
		HasWeiXin BIT, 
		cvDeleted BIT, 
		JobDeleted BIT,
		SecondId VARCHAR(10)
	)
	SET @SQL='
		INSERT INTO #T
		(TitleID, ID, JobID, jobRegionID, JobName, paMainID, cvMainID, AddDate, ApplyDate , Reply, 
			Degree, RelatedWorkYears, Attachment, IsNameHidden, LivePlace, Gender, 
			BirthDay, HasPhoto, Valid, MobileVerifyDate, cvDeleted, JobDeleted, SecondId)
		SELECT ROW_NUMBER() OVER (ORDER BY ' + @ORDER + ') AS TitleID, a.ID, a.JobID, d.dcRegionID,
			a.JobName, c.ID, a.cvMainID, a.AddDate, ApplyDate, a.Reply, 
			b.Degree, b.RelatedWorkYears, b.Attachment, b.IsNameHidden, c.LivePlace, 
			c.Gender, c.BirthDay, c.HasPhoto, b.Valid, c.MobileVerifyDate, cvDeleted, JobDeleted, b.SecondId
		FROM CaCvApplyDeleted a WITH(NOLOCK)
		INNER JOIN cvMain b WITH(NOLOCK) ON b.ID = a.cvMainID
		INNER JOIN paMain c WITH(NOLOCK) ON c.ID = b.paMainID
		INNER JOIN Job d WITH(NOLOCK) ON d.ID = a.JobID
		WHERE 1=1 '
	IF LEN(@WHERE) > 0
		SET @SQL = @SQL + ' AND '+@WHERE

	--PRINT @SQL
	EXEC(@SQL)
	
	IF(@Page < 1)
		SET @Page = 1
	IF NOT EXISTS(SELECT 'x' FROM #t WHERE TitleID > (@Page-1)*20 AND TitleID <= @Page*20)
		SET @Page = 1
	
	DECLARE @cpMainID AS INT
	SELECT @cpMainID = cpMainID FROM caMain WITH(NOLOCK) WHERE ID = @caMainID
	UPDATE #T SET paName = LEFT(dbo.GetPersonName(cvMainID, @cpMainID), 20), IsViewed = (SELECT TOP 1 '1' FROM caCvViewLog WITH(NOLOCK) WHERE cvMainID=#T.cvMainID AND caMainID=@caMainID), 
		HasFavorate = (SELECT TOP 1 '1' FROM caFavorate WITH(NOLOCK) WHERE caMainID=@caMainID AND cvMainID=#T.cvMainID), 
		HasInterview = (SELECT TOP 1 '1' FROM exInterview a WITH(NOLOCK) INNER JOIN Job b WITH(NOLOCK) ON a.JobID=b.ID WHERE a.CompanyDeleted=0 AND b.caMainID=@caMainID AND cvMainID=#T.cvMainID), 
		HasRemark = (SELECT TOP 1 '1' FROM caCvRemark WITH(NOLOCK) WHERE caMainID=@caMainID AND cvMainID=#T.cvMainID)
	WHERE TitleID > (@Page-1)*20 AND TitleID <= @Page*20

	UPDATE #T SET Speciality = (
		SELECT Speciality FROM cvMain WITH(NOLOCK)
		WHERE cvMain.ID = #T.cvMainID)
	WHERE TitleID > (@Page-1)*20 AND TitleID <= @Page*20
	
	UPDATE #T SET Experience = (
		SELECT TOP 1 ISNULL(Description, DescriptionEng) FROM cvExperience WITH(NOLOCK)
		WHERE cvExperience.cvMainID = #T.cvMainID
		ORDER BY BeginDate DESC)
	WHERE TitleID > (@Page-1)*20 AND TitleID <= @Page*20

	UPDATE #T SET cvEducationID = (
		SELECT TOP 1 ID FROM cvEducation WITH(NOLOCK)
		WHERE cvEducation.cvMainID = #T.cvMainID
		AND #T.Degree = cvEducation.Degree
		ORDER BY Graduation DESC)
	WHERE TitleID > (@Page-1)*20 AND TitleID <= @Page*20

	UPDATE a SET a.College = ISNULL(b.GraduateCollage, b.GraduateCollageEng), a.EduType = b.EduType, 
		a.MajorName = ISNULL(b.MajorName, b.MajorNameEng), a.Graduation = b.Graduation
	FROM #T a, cvEducation b WITH(NOLOCK)
	WHERE b.ID = a.cvEducationID AND a.TitleID > (@Page-1)*20 AND a. TitleID <= @Page*20

	--修改是否绑定微信
	UPDATE a SET HasWeiXin = 1
	FROM #T a, WxFans b WITH(NOLOCK)
	WHERE a.paMainID = b.PaMainID
	AND b.Status = 2
	AND a.TitleID > (@Page-1)*20 AND TitleID <= @Page*20
	SELECT COUNT(*) FROM #T WITH(NOLOCK)
	SELECT * FROM #T WITH(NOLOCK) WHERE TitleID > (@Page-1)*20 AND TitleID <= @Page*20

	DROP TABLE #T
END


GO
/****** Object:  StoredProcedure [dbo].[ccCaCvContackLogByCvViewSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--######################333
--@caMainID取自Session，caMainID = ca.caMainID cvview.asp line 202
--######################333
CREATE PROCEDURE [dbo].[ccCaCvContackLogByCvViewSelect]
(
	@caMainID INT,
	@cvMainID INT
)
AS
BEGIN
--查询最近2个月的申请记录
	SELECT TOP 1 a.ID,a.AddDate,a.Reply,b.ID JobID,b.Name
	FROM exJobApply a WITH(NOLOCK) 
	INNER JOIN Job b WITH(NOLOCK)
	ON a.JobId = b.Id
	WHERE a.cvMainId =@cvMainID
	AND b.caMainID = @caMainID
	--AND a.AddDate > DATEADD(MONTH, -2, GETDATE())
	ORDER BY a.ID DESC
--查询最近3个月的发送面试通知记录	
	SELECT TOP 1 a.AddDate,b.ID,b.Name
	FROM ExInterview a WITH(NOLOCK) 
	INNER JOIN Job b WITH(NOLOCK)
	ON a.JobId = b.Id
	WHERE a.cvMainId =@cvMainID
	AND b.caMainID = @caMainID
	AND a.AddDate > DATEADD(MONTH, -3, GETDATE())
	ORDER BY a.ID DESC
--查询收藏记录
	SELECT TOP 1 a.AddDate,b.ID,b.Name
	FROM caFavorate a WITH(NOLOCK) 
	INNER JOIN Job b WITH(NOLOCK)
	ON a.JobId = b.Id
	WHERE a.cvMainId =@cvMainID
	AND b.caMainID = @caMainID
	ORDER BY a.ID DESC
--查询2周内浏览简历记录
	SELECT TOP 1 AddDate
	FROM CaCvViewLog a WITH(NOLOCK) 
	WHERE caMainID = @caMainID 
	AND cvMainID = @cvMainID
	AND AddDate>DATEADD(DAY,-14,GETDATE())
END














GO
/****** Object:  StoredProcedure [dbo].[cccaCvFinderBycaMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#########################33333
--@caMainID 取自Session caCvFinder.GetList(ca.caMainID)
--#########################33333
CREATE PROCEDURE [dbo].[cccaCvFinderBycaMainIDSelect]
(
	@caMainID INT
)
AS
BEGIN
	SELECT * FROM caCvFinder WHERE caMainID = @caMainID
END














GO
/****** Object:  StoredProcedure [dbo].[cccaCvFinderDelete]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
----##########################################
----@caMainID 取自Session 
----caCvFinder.ID = co.reqS("ID", 0)
----caCvFinder.caMainID = ca.caMainID
----##########################################
CREATE PROCEDURE [dbo].[cccaCvFinderDelete]
(
	@ID INT,
	@caMainID INT
)
AS
BEGIN
	DELETE FROM caCvFinder WHERE ID = @ID AND caMainID = @caMainID
END














GO
/****** Object:  StoredProcedure [dbo].[cccaCvFinderSave]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[cccaCvFinderSave]
(
	@ID INT,
	@caMainID INT,
	@Name VARCHAR(50),
	@dcJobTypeID VARCHAR(50),
	@dcRegionID VARCHAR(50),
	@dcIndustryID VARCHAR(50),
	@dcSalaryID INT,
	@dcJobTypeIDOld VARCHAR(50),
	@dcIndustryIDOld VARCHAR(50),
	@MinExperience TINYINT,
	@KeyWord VARCHAR(50),
	@SubNodeNum TINYINT,
	@Education VARCHAR(50),
	@Standard BIT,
	@EducationName VARCHAR(200),
	@dcMajorID VARCHAR(50),
	@Graduation VARCHAR(50),
	@LanguageType VARCHAR(50),
	@Gender TINYINT,
	@MinAge TINYINT,
	@MaxAge TINYINT,
	@MinHeight TINYINT,
	@MaxHeight TINYINT,
	@LivePlace VARCHAR(50),
	@AccountPlace VARCHAR(50),
	@MobilePlace VARCHAR(50),
	@cvMainID INT,
	@IsNegotiable BIT,
	@IncludeOld BIT,
	@IsExpand BIT,
	@SortType TINYINT,
	@EmployType TINYINT
)
AS
DECLARE @MaxId AS INT
BEGIN TRY
	IF @ID=0
		SELECT @ID=ID FROM caCvFinder WITH(NOLOCK) WHERE NAME = @Name AND caMainID = @caMainID
 
	IF @ID>0
		BEGIN
			UPDATE caCvFinder SET
				Name=@Name,
				dcJobTypeID=@dcJobTypeID,
				dcRegionID=@dcRegionID,
				dcIndustryID=@dcIndustryID,
				dcSalaryID=@dcSalaryID,
				dcJobTypeIDOld=@dcJobTypeIDOld,
				dcIndustryIDOld=@dcIndustryIDOld,
				MinExperience=@MinExperience,
				KeyWord=@KeyWord,
				SubNodeNum=@SubNodeNum,
				Education=@Education,
				Standard=@Standard,
				EducationName=@EducationName,
				dcMajorID=@dcMajorID,
				Graduation=@Graduation,
				LanguageType=@LanguageType,
				Gender=@Gender,
				MinAge=@MinAge,
				MaxAge=@MaxAge,
				MinHeight=@MinHeight,
				MaxHeight=@MaxHeight,
				LivePlace=@LivePlace,
				AccountPlace=@AccountPlace,
				MobilePlace = @MobilePlace,
				cvMainID=@cvMainID,
				IsNegotiable=@IsNegotiable,
				IncludeOld=@IncludeOld,
				IsExpand=@IsExpand,
				SortType=@SortType,
				EmployType=@EmployType
			WHERE ID=@ID
			SET @MaxID=@ID
		END
	ELSE
		BEGIN
			DECLARE @FinderCount AS TINYINT
			SELECT @FinderCount=COUNT(ID) FROM caCvFinder WITH(NOLOCK) WHERE caMainID=@caMainID
			IF @FinderCount < 20
			BEGIN
				INSERT INTO caCvFinder
					(caMainID,Name,dcJobTypeID,dcRegionID,dcIndustryID,dcSalaryID,dcJobTypeIDOld,dcIndustryIDOld,MinExperience,
					KeyWord,SubNodeNum,Education,Standard,EducationName,dcMajorID,Graduation,SortType,
					LanguageType,Gender,MinAge,MaxAge,MinHeight,MaxHeight,LivePlace,AccountPlace,MobilePlace,cvMainID,IsNegotiable,IncludeOld,IsExpand,EmployType)
				VALUES
					(@caMainID,@Name,@dcJobTypeID,@dcRegionID,@dcIndustryID,@dcSalaryID,@dcJobTypeIDOld,@dcIndustryIDOld,@MinExperience,
					@KeyWord,@SubNodeNum,@Education,@Standard,@EducationName,@dcMajorID,@Graduation,@SortType,
					@LanguageType,@Gender,@MinAge,@MaxAge,@MinHeight,@MaxHeight,@LivePlace,@AccountPlace,@MobilePlace,@cvMainID,@IsNegotiable,@IncludeOld,@IsExpand,@EmployType)
				SET @MaxID = @@IDENTITY
			END
			ELSE
				GOTO ERR
		END
END TRY
BEGIN CATCH
	GOTO ERR
END CATCH
RETURN @MaxID
ERR:
BEGIN
	RETURN 0
END










GO
/****** Object:  StoredProcedure [dbo].[cccaCvFinderSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
----##########################################
----@caMainID 取自Session 
---- Return = caCvFinder.GetData(ca.caMainID, co.reqS("ID", 0))
----##########################################
CREATE PROCEDURE [dbo].[cccaCvFinderSelect]
(
	@caMainID INT,
	@ID INT
)
AS
BEGIN
	SELECT *, 0 IsOnline FROM caCvFinder WITH(NOLOCK) WHERE ID = @ID AND caMainID = @caMainID
END














GO
/****** Object:  StoredProcedure [dbo].[cccaCvIntentionBatchDelete]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[cccaCvIntentionBatchDelete]
(
	@AllID VARCHAR(1000),
	@cpMainID INT 
)
AS
BEGIN TRAN
	BEGIN TRY
		SET @AllID = dbo.FormatIDS(@AllID)
		DECLARE @T AS TABLE(ID INT)
		INSERT INTO @T SELECT * FROM dbo.fnSplit(@AllID, ',')
		
		DELETE FROM caCvIntention WHERE PersonDeleted=1 AND ID IN(SELECT ID FROM @T)
		AND JobID IN (SELECT ID FROM Job WITH(NOLOCK) WHERE cpMainID = @cpMainID)
		
		UPDATE caCvIntention SET CompanyDeleted = 1
		WHERE ID IN(SELECT ID FROM @T)
		AND JobID IN (SELECT ID FROM Job WITH(NOLOCK) WHERE cpMainID = @cpMainID)		
	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH
COMMIT TRAN
RETURN 1
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END














GO
/****** Object:  StoredProcedure [dbo].[cccacvIntentionCountByCaMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.31
--创建人：Nick
--说明：获取今天发送的应聘邀请数量
--#####################################################
CREATE PROCEDURE [dbo].[cccacvIntentionCountByCaMainIDSelect]
(
	@CaMainID INT
)
AS
BEGIN TRY
	SELECT COUNT(1) cnt 
	FROM cacvIntention 
	WHERE caMainID=@CaMainID 
	AND AddDate>CONVERT(VARCHAR(10),GETDATE()) 
	AND AddDate<CONVERT(VARCHAR(10),GETDATE())+' 23:59'
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[ccCacvIntentionInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--2015-8-27Harry
--将绑定关注微信的，插入到wxsendmessage表中
---20160216 Lucifer 添加推送
CREATE PROCEDURE [dbo].[ccCacvIntentionInsert]
(
	@caMainID INT,
	@JobId INT,
	@cvMainID INT
)
AS
SET NOCOUNT ON
BEGIN
	DECLARE @IntertionPoint INT
	SET @IntertionPoint = 5

	DECLARE @CurrentPoint INT
	SELECT @CurrentPoint = RemainPoint
	FROM cpMain WITH(NOLOCK) 
	WHERE ID = (SELECT CpMainID FROM CaMain WITH(NOLOCK) WHERE ID = @caMainID) 

	IF @CurrentPoint < @IntertionPoint
	BEGIN
		RETURN -1
	END

	IF EXISTS(SELECT 'x' FROM Job WITH(NOLOCK) WHERE ID = @JobID AND caMainID = @caMainID)
	BEGIN
		IF EXISTS(SELECT ID FROM cacvIntention WHERE JobId = @JobId AND caMainID = @caMainID AND cvMainID = @cvMainID AND AddDate>GETDATE()-30)
			RETURN 2
		ELSE
		BEGIN
			IF (SELECT COUNT(1) FROM cacvIntention WHERE caMainID=@caMainID AND AddDate>CONVERT(VARCHAR(10),GETDATE()) AND AddDate<CONVERT(VARCHAR(10),GETDATE())+' 23:59') < 200
			BEGIN
				DECLARE  @paMainId INT, @cacvIntentionID INT, @wxFansId INT, @cpMainId INT
				INSERT INTO cacvIntention(caMainID, JobId, cvMainID) VALUES(@caMainID, @JobId, @cvMainID)
				SELECT @cacvIntentionID=@@IDENTITY

				SELECT @paMainId = a.paMainId, @wxFansId = b.id
				FROM cvMain a, wxFans b
				WHERE a.ID = @cvMainID 
				AND b.paMainId = a.paMainId
				AND b.[Status] = 2
				SELECT TOP 1 @cpMainID = cpMainID FROM caMain WITH(NOLOCK) WHERE ID = @caMainID

				SELECT @paMainId = paMainId
				FROM cvMain
				WHERE ID = @cvMainID

				IF @wxFansId IS NOT NULL --0已取消关注 1 正在关注 2 已绑定账号 
				BEGIN
					--插入到wxMessageSend表中
					INSERT INTO WxMessageSend2(Templatetype, WxFansID, PaMainId, MainTableId, CpMainID, CvMainID, JobId, CaMainId, AddDate)
					SELECT 2, @wxFansId, @paMainId, @cacvIntentionID, @cpMainId, @cvMainID, @JobId, @caMainID, GETDATE()
				END

				INSERT INTO paPushLog(paMainID, PushMessage, PushType)
				SELECT @paMainId, '亲，收到一份应聘邀请！', 3 WHERE EXISTS(SELECT 'X' FROM paIOSBind WHERE paMainID = @paMainId)

				--插入积分记录  Peter 2014-08-25
				DECLARE @TodayPoint AS INT
				DECLARE @TodayID AS INT
				SET @TodayPoint = 0
				SET @TodayID = 0				
				--SELECT TOP 1 @TodayPoint = ISNULL(Point,0),@TodayID = ISNULL(ID,0) FROM cpPoint WITH(NOLOCK) WHERE changeID = 5 AND LastModifyDate > CONVERT(VARCHAR(10), GETDATE(),120) AND cpMainID = @cpMainID
				
				--SET @TodayPoint = @TodayPoint + 1
				INSERT INTO cpPoint (cpMainID,ChangeID,Point,LastModifyDate) VALUES(@cpMainID,5,-(@IntertionPoint),GETDATE())
				--IF @TodayPoint <= 50
				--BEGIN
				--	IF @TodayID = 0
				--	BEGIN
				--		INSERT INTO cpPoint (cpMainID,ChangeID,Point,LastModifyDate) VALUES(@cpMainID,5,1,GETDATE())
				--	END
				--	ELSE
				--	BEGIN
				--		UPDATE cpPoint SET Point = @TodayPoint,LastModifyDate = GETDATE() WHERE ID = @TodayID 
				--	END
				--END	
				RETURN 1
			END
			ELSE
				RETURN 3
		END
	END
	ELSE
		RETURN 0
END
GO
/****** Object:  StoredProcedure [dbo].[ccCaCvIntentionSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ccCaCvIntentionSelect]
(
	@WHERE VARCHAR(1000), 
	@Order VARCHAR(100), 
	@Page SMALLINT, 
	@cpMainID INT, 
	@caMainID INT
)
AS
SET NOCOUNT ON
BEGIN
	SET @Where = dbo.SafeSql(@Where)
	SET @ORDER = dbo.SafeSql(@Order)
	DECLARE @SQL AS VARCHAR(2000)
	CREATE TABLE #T(
		TitleID BIGINT, 
		ID INT, 
		Reply TINYINT, 
		ReplyDate SMALLDATETIME, 
		JobID INT, 
		JobName NVARCHAR(50) COLLATE Chinese_PRC_CI_AS NULL, 
		JobRegion VARCHAR(6) NULL, 
		IsJobDelete BIT NULL, 
		cvMainID INT, 
		Degree TINYINT, 
		RelatedWorkYears TINYINT, 
		Attachment VARCHAR(50) COLLATE Chinese_PRC_CI_AS, 
		IsNameHidden BIT, 
		LivePlace VARCHAR(6) COLLATE Chinese_PRC_CI_AS, 
		Gender BIT, 
		paName NVARCHAR(20), 
		BirthDay INT, 
		HasPhoto TINYINT, 
		adddate SMALLDATETIME, 
		Valid TINYINT, 
		IsViewed BIT, 
		HasJobApply BIT, 
		HasInterview BIT, 
		HasRemark BIT, 
		cvEducationID INT, 
		College NVARCHAR(50), 
		EduType TINYINT, 
		MajorName NVARCHAR(20), 
		Graduation INT, 
		Speciality VARCHAR(MAX) COLLATE Chinese_PRC_CI_AS, 
		Experience VARCHAR(MAX) COLLATE Chinese_PRC_CI_AS, 
		cvMatch INT, 
		MobileVerifyDate SMALLDATETIME, 
		IsOnline BIT, 
		paMainId INT, 
		SecondId VARCHAR(10)
	)
	SET @SQL='
		INSERT INTO #T(
			TitleID, ID, Reply, ReplyDate, JobID, cvMainID, Degree, RelatedWorkYears, 
			Attachment, IsNameHidden, LivePlace, Gender, paName, BirthDay, HasPhoto, adddate, 
			Valid, MobileVerifyDate, IsOnline, paMainId, SecondId
		)
		SELECT ROW_NUMBER() OVER (ORDER BY ' + @ORDER + ') AS TitleID, 
			a.ID, Reply, ReplyDate, a.JobID, a.cvMainID, 
			b.Degree, b.RelatedWorkYears, b.Attachment, b.IsNameHidden, 
			c.LivePlace, c.Gender, c.Name AS paName, c.BirthDay, c.HasPhoto, 
			a.adddate, b.Valid, c.MobileVerifyDate, dbo.GetPaOnlineStatus(c.ID), b.paMainId, b.SecondId
		FROM caCvIntention a WITH(NOLOCK)
		INNER JOIN cvMain b WITH(NOLOCK) ON b.ID = a.cvMainID
		INNER JOIN paMain c WITH(NOLOCK) ON c.ID = b.paMainID
		INNER JOIN Job d WITH(NOLOCK) ON d.ID = a.JobID
		WHERE d.IsDelete = 0 AND CompanyDeleted = 0 '

		DECLARE @AccountType TINYINT
		SELECT @AccountType = AccountType FROM caMain WITH(NOLOCK) WHERE id = @caMainId AND cpMainId = @cpMainId
		IF @AccountType = 1
			SET @SQL = @SQL + ' AND d.cpMainID = ' + LTRIM(STR(@cpMainID)) 
		ELSE IF @AccountType = 2
			SET @SQL = @SQL + ' AND a.caMainID = ' + LTRIM(STR(@caMainID)) 
		ELSE IF @AccountType IS NULL
			RETURN
	IF LEN(@WHERE) > 0
		SET @SQL = @SQL + @WHERE
	PRINT @SQL
	EXEC(@SQL)
			
	IF(@Page < 1)
		SET @Page = 1
	
	UPDATE #T
	SET paName = LEFT(dbo.GetPersonName(cvMainID, @cpMainID), 20), 
		IsViewed = (SELECT TOP 1 '1' FROM caCvViewLog WITH(NOLOCK) WHERE cvMainID=#T.cvMainID AND caMainID=@caMainID), 
		HasJobApply = (SELECT TOP 1 '1' FROM exJobApply a WITH(NOLOCK) INNER JOIN Job b WITH(NOLOCK) ON a.JobID=b.ID WHERE a.CompanyDeleted=0 AND b.caMainID=@caMainID AND cvMainID=#T.cvMainID), 
		HasInterview = (SELECT TOP 1 '1' FROM exInterview a WITH(NOLOCK) INNER JOIN Job b WITH(NOLOCK) ON a.JobID=b.ID WHERE a.CompanyDeleted=0 AND b.caMainID=@caMainID AND cvMainID=#T.cvMainID), 
		HasRemark = (SELECT TOP 1 '1' FROM caCvRemark WITH(NOLOCK) WHERE caMainID=@caMainID AND cvMainID=#T.cvMainID)
	WHERE TitleID > (@Page-1) * 20
	AND TitleID <= @Page*20

	UPDATE #T SET Speciality = (
		SELECT Speciality FROM cvMain WITH(NOLOCK)
		WHERE cvMain.ID = #T.cvMainID)
	WHERE TitleID > (@Page-1)*20 AND TitleID <= @Page*20
	
	UPDATE #T SET Experience = (
		SELECT TOP 1 ISNULL(Description, DescriptionEng) FROM cvExperience WITH(NOLOCK)
		WHERE cvExperience.cvMainID = #T.cvMainID
		ORDER BY BeginDate DESC)
	WHERE TitleID > (@Page-1)*20 AND TitleID <= @Page*20

	UPDATE #T SET cvEducationID = (
		SELECT TOP 1 ID FROM cvEducation WITH(NOLOCK)
		WHERE cvEducation.cvMainID = #T.cvMainID
		AND #T.Degree = cvEducation.Degree
		ORDER BY Graduation DESC)
	WHERE TitleID > (@Page-1)*20 AND TitleID <= @Page*20

	UPDATE a SET a.College = ISNULL(b.GraduateCollage, b.GraduateCollageEng), a.EduType = b.EduType, 
		a.MajorName = ISNULL(b.MajorName, b.MajorNameEng), a.Graduation = b.Graduation
	FROM #T a, cvEducation b WITH(NOLOCK)
	WHERE b.ID = a.cvEducationID AND a.TitleID > (@Page-1)*20 AND a.TitleID <= @Page*20

	UPDATE #T SET cvMatch = dbo.GetCvMatch(cvMainID, JobID) WHERE TitleID > (@Page-1)*20 AND  TitleID <= @Page*20
	UPDATE #T SET JobName = a.Name, JobRegion= a.dcRegionID, IsJobDelete = IsDelete
	FROM Job a WITH(NOLOCK)
	WHERE #T.JobID = a.ID	
	
	SELECT COUNT(*) FROM #T WITH(NOLOCK)

	SELECT a.*,b.Description DegreeName,c.MapBarName LivePlaceName,d.Description JobRegionName, dbo.BirthToAge(a.BirthDay) Age
	FROM #T a WITH(NOLOCK) 
	LEFT JOIN dcEducation b WITH(NOLOCK) ON b.ID = a.Degree
	LEFT JOIN dcRegion c WITH(NOLOCK) ON c.ID = a.LivePlace
	LEFT JOIN dcRegion d WITH(NOLOCK) ON d.ID = a.JobRegion 
	WHERE TitleID > (@Page-1)*20 AND TitleID <= @Page*20
	
	DROP TABLE #T
END
GO
/****** Object:  StoredProcedure [dbo].[ccCaCvQuotaLogByCvMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--######################################3
--创建：Lambo，修改Sean
--检查企业账号是否消耗日配额看过简历联系方式
--企业有多账号的情况，一个企业内部的查看情况共享,Copper建议
--######################################3
CREATE PROCEDURE [dbo].[ccCaCvQuotaLogByCvMainIDSelect]
(
    @cpMainID INT,
	@cvMainID INT
)
AS
BEGIN
	IF EXISTS(
		SELECT 'x' FROM CaCvQuotaLog WITH(NOLOCK)
		WHERE cpMainID = @cpMainID
		AND cvMainID = @cvMainID
	)
		RETURN 1
	ELSE
		RETURN 0
END














GO
/****** Object:  StoredProcedure [dbo].[ccCaCvQuotaLogCount]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--######################################3
--创建：Sean
--检查企业账号今天所有的配额消耗数量,用于CompanyAccount
--######################################3
CREATE PROCEDURE [dbo].[ccCaCvQuotaLogCount]
(
    @cpMainID INT
)
AS
BEGIN
	DECLARE @CNT AS INT
	SELECT @CNT = COUNT(1) FROM CaCvQuotaLog WITH(NOLOCK)
	WHERE cpMainID = @cpMainID

	RETURN @CNT
END














GO
/****** Object:  StoredProcedure [dbo].[cccaCvQuotaLogInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--###################################################3
--创建：		sean
--时间：		2010-11-15
--兼容老版，查看一份简历消耗配额
--###################################################3
CREATE PROCEDURE [dbo].[cccaCvQuotaLogInsert]
(
	@cpMainID INT,	
	@caMainID INT,
	@cvMainID INT
)
AS
BEGIN TRAN
	BEGIN TRY
		IF NOT EXISTS(SELECT 'x' FROM cpMain WITH(NOLOCK), caMain WITH(NOLOCK) WHERE cpMain.Id = @cpMainID AND caMain.cpMainID = @cpMainID AND cpMain.Valid=1 AND caMain.IsPause = 0 AND caMain.IsDelete = 0)
			GOTO Err1
		IF NOT EXISTS(SELECT 'x' FROM paMain a WITH(NOLOCK), cvMain b WITH(NOLOCK) WHERE a.ID = b.paMainID AND b.Id = @cvMainID AND (ISNULL(b.Attachment,'')<>'' OR ISNULL(a.Mobile,'')<>''))
			GOTO Err2
		DECLARE @ResumeQuota AS INT
		DECLARE @ResumeConsume AS INT
		SELECT @ResumeQuota = ResumeQuota FROM cpMain WITH(NOLOCK) WHERE ID = @cpMainID
		SELECT @ResumeConsume = COUNT(*) FROM caCvQuotaLog WITH(NOLOCK) WHERE cpMainID = @cpMainID
		IF ISNULL(@ResumeQuota, 0) = 0
			GOTO Err3
		IF @ResumeQuota > @ResumeConsume
		BEGIN
			DECLARE	@Num AS INT
			EXEC @Num = ccCaCvQuotaLogByCvMainIDSELECT @cpMainID, @cvMainID
			IF @Num = 0
			BEGIN
				INSERT INTO caCvQuotalog(cpMainID,caMainID,cvMainID) VALUES(@cpMainID,@caMainID,@cvMainID)
				SET @ResumeConsume = @ResumeConsume + 1
			END
		END
		ELSE
			GOTO Err4
	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH
COMMIT
RETURN @ResumeConsume
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END
----企业账号信息不正确
ERR1:
BEGIN
	ROLLBACK TRAN
	RETURN -1
END
----简历id是无效简历id
ERR2:
BEGIN
	ROLLBACK TRAN
	RETURN -2
END
----本日配额为0，不允许使用配额
ERR3:
BEGIN
	ROLLBACK TRAN
	RETURN -3
END
----本日配额已经消耗完毕
ERR4:
BEGIN
	ROLLBACK TRAN
	RETURN -4
END














GO
/****** Object:  StoredProcedure [dbo].[cccaCvRemarkByCvMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[cccaCvRemarkByCvMainIDSelect]
(
	@caMainID INT,
	@cvMainID INT,
	@cpMainID INT
)
AS
BEGIN
	IF NOT EXISTS(SELECT 'x' FROM caMain WITH(NOLOCK) WHERE ID = @caMainID AND cpMainID = @cpMainID)
		RETURN 0

	BEGIN TRY	
		SELECT ID, Remark, AddDate, caMainID FROM caCvRemark WITH(NOLOCK)
		WHERE cvMainID=@cvMainID AND caMainID=@caMainID
		ORDER BY ID DESc
	END TRY
	BEGIN CATCH
	END CATCH
END














GO
/****** Object:  StoredProcedure [dbo].[cccaCvRemarkDelete]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--Lambo 20101130 修改
--增加cpMainID参数，判断是否是该企业的
CREATE PROCEDURE [dbo].[cccaCvRemarkDelete]
(
	@ID INT	,
	@cpMainID INT
)
AS
BEGIN
	DELETE FROM caCvRemark WHERE ID = @ID AND caMainID IN (SELECT ID FROM caMain WITH(NOLOCK) WHERE cpMainID = @cpMainID)
END














GO
/****** Object:  StoredProcedure [dbo].[cccaCvRemarkInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
----##########################################
----@caMainID 取自Session 
----caMainID = ca.caMainID
----caCvRemark.caMainID = caMainID
----##########################################
CREATE PROCEDURE [dbo].[cccaCvRemarkInsert]
(
	@caMainID INT,
	@cvMainID INT,
	@Remark VARCHAR(200)
)
AS
BEGIN
	INSERT INTO caCvRemark(caMainID, Remark, cvMainID) VALUES(@caMainID, @Remark, @cvMainID)
END














GO
/****** Object:  StoredProcedure [dbo].[ccCaCvViewLogBatchSave]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ccCaCvViewLogBatchSave]
(
	@cvIDs VARCHAR(500),
	@caMainID INT
)
AS
BEGIN
	SET @cvIDs = dbo.FormatIDS(@cvIDs)
	IF @caMainID <> 0
	BEGIN
		UPDATE CaCvViewLog SET AddDate=GETDATE()
		WHERE caMainID = @caMainID AND cvMainID IN (SELECT * FROM dbo.fnSplit(@cvIDs, ','))

		INSERT CaCvViewLog(caMainID,cvMainID) 
		SELECT @caMainID,a FROM dbo.fnSplit(@cvIDs, ',')
		WHERE a NOT IN (SELECT cvMainID FROM CaCvViewLog WITH(NOLOCK) WHERE caMainID = @caMainID)
	END
	
	UPDATE cvMain SET ViewNumber = ViewNumber + 1 WHERE ID IN (SELECT * FROM dbo.fnSplit(@cvIDs, ','))

	UPDATE ExJobApply SET ViewDate = GETDATE()
	WHERE JobId IN(SELECT Id FROM Job WHERE caMainId = @caMainId)
	AND cvMainID IN (SELECT * FROM dbo.fnSplit(@cvIDs, ','))
	AND ViewDate IS NULL
END

GO
/****** Object:  StoredProcedure [dbo].[ccCaCvViewLogBycaMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[ccCaCvViewLogBycaMainIDSelect]
(
	@caMainID INT, 
	@WHERE VARCHAR(1000), 
	@ORDER VARCHAR(1000), 
	@Page SMALLINT, 
	@cpMainID INT
)
AS
SET NOCOUNT ON
BEGIN
	IF NOT EXISTS(SELECT 'x' FROM caMain WITH(NOLOCK) WHERE ID = @caMainID AND cpMainID = @cpMainID)
		RETURN 0

	SET @Where = dbo.SafeSql(@Where)
	SET @ORDER = dbo.SafeSql(@Order)
	CREATE TABLE #t(
		TitleID BIGINT, 
		caMainId INT, 
		cvMainId INT, 
		AddDate SMALLDATETIME, 
		Degree TINYINT, 
		RelatedWorkYears TINYINT, 
		LivePlace VARCHAR(6) COLLATE Chinese_PRC_CI_AS, 
		Gender BIT, 
		paName NVARCHAR(20), 
		BirthDay INT, 
		HasPhoto TINYINT, 
		Attachment VARCHAR(50) COLLATE Chinese_PRC_CI_AS, 
		IsNameHidden BIT, 
		Valid TINYINT, 
		HasJobApply BIT, 
		HasInterview BIT, 
		HasRemark BIT, 
		HasFavorate BIT, 
		cvEducationID INT, 
		College NVARCHAR(50), 
		EduType TINYINT, 
		MajorName NVARCHAR(20), 
		Graduation INT, 
		Speciality VARCHAR(MAX) COLLATE Chinese_PRC_CI_AS, 
		Experience VARCHAR(MAX) COLLATE Chinese_PRC_CI_AS, 
		MobileVerifyDate SMALLDATETIME, 
		IsOnline BIT, 
		HasWeiXin BIT, 
		paMainId INT, 
		SecondId VARCHAR(10)
	)
	DECLARE @SQL AS VARCHAR(2000)
	SET @SQL='INSERT INTO #t(TitleID, caMainID, cvMainID, AddDate, IsOnline, paMainId, SecondId)
		SELECT ROW_NUMBER() OVER (ORDER BY ' + @ORDER + ') AS TitleID, 
			a.caMainID, a.cvMainID, a.AddDate, dbo.GetPaOnlineStatus(c.ID), b.paMainId, b.SecondId
		From CaCvViewLog a WITH(NOLOCK)
		INNER JOIN cvMain b WITH(NOLOCK) ON b.ID = a.cvMainID
		INNER JOIN paMain c WITH(NOLOCK) ON c.ID = b.paMainID'
	
	SET @SQL=@SQL + '
		WHERE 1=1'

	IF LEN(@WHERE) > 0
		SET @SQL = @SQL + @WHERE
	--PRINT @SQL
	EXEC(@SQL)		

	IF(@Page < 1)
		SET @Page = 1
	IF NOT EXISTS(SELECT 'x' FROM #t WHERE TitleID > (@Page-1)*20 AND  TitleID <= @Page*20)
		SET @Page = 1

	UPDATE #t SET Degree = a.Degree, RelatedWorkYears = a.RelatedWorkYears, Attachment = a.Attachment, 
		IsNameHidden = a.IsNameHidden, LivePlace = b.LivePlace, Gender = b.Gender, paName = b.Name, 
		BirthDay = b.BirthDay, HasPhoto = b.HasPhoto, Valid = a.Valid, MobileVerifyDate = b.MobileVerifyDate
	FROM cvMain a WITH(NOLOCK) INNER JOIN paMain b WITH(NOLOCK) ON a.paMainID = b.ID
	WHERE a.ID = #t.cvMainID AND TitleID > (@Page-1)*20 AND TitleID <= @Page*20

	UPDATE #t SET paName = LEFT(dbo.GetPersonName(cvMainID, @cpMainID), 20), 
		HasJobApply = (SELECT TOP 1 '1' FROM exJobApply a WITH(NOLOCK) INNER JOIN Job b WITH(NOLOCK) ON a.JobID=b.ID WHERE a.CompanyDeleted=0 AND b.caMainID=@caMainID AND cvMainID=#t.cvMainID), 
		HasInterview = (SELECT TOP 1 '1' FROM exInterview a WITH(NOLOCK) INNER JOIN Job b WITH(NOLOCK) ON a.JobID=b.ID WHERE a.CompanyDeleted=0 AND b.caMainID=@caMainID AND cvMainID=#t.cvMainID), 
		HasRemark = (SELECT TOP 1 '1' FROM caCvRemark WITH(NOLOCK) WHERE caMainID=@caMainID AND cvMainID=#t.cvMainID), 
		HasFavorate = (SELECT TOP 1 '1' FROM caFavorate WITH(NOLOCK) WHERE caMainID=@caMainID AND cvMainID=#t.cvMainID)
	WHERE TitleID > (@Page - 1)*20 AND TitleID <= @Page*20
	
	UPDATE #T SET Speciality = (
		SELECT Speciality FROM cvMain WITH(NOLOCK)
		WHERE cvMain.ID = #T.cvMainID)
	WHERE TitleID > (@Page-1)*20 AND TitleID <= @Page*20
	
	UPDATE #T SET Experience = (
		SELECT TOP 1 ISNULL(Description, DescriptionEng) FROM cvExperience WITH(NOLOCK)
		WHERE cvExperience.cvMainID = #T.cvMainID
		ORDER BY BeginDate DESC)
	WHERE TitleID > (@Page-1)*20 AND TitleID <= @Page*20

	UPDATE #T SET cvEducationID = (
		SELECT TOP 1 ID FROM cvEducation WITH(NOLOCK)
		WHERE cvEducation.cvMainID = #T.cvMainID
		AND #T.Degree = cvEducation.Degree
		ORDER BY Graduation DESC)
	WHERE TitleID > (@Page-1)*20 AND TitleID <= @Page*20

	UPDATE a SET a.College = ISNULL(b.GraduateCollage, b.GraduateCollageEng), a.EduType = b.EduType, 
		a.MajorName = ISNULL(b.MajorName, b.MajorNameEng), a.Graduation = b.Graduation
	FROM #T a, cvEducation b WITH(NOLOCK)
	WHERE b.ID = a.cvEducationID AND a.TitleID > (@Page-1)*20 AND a.TitleID <= @Page*20

	--修改是否绑定微信
	UPDATE a SET HasWeiXin = 1
	FROM #T a, WxFans b WITH(NOLOCK), CvMain c WITH(NOLOCK)
	WHERE a.CvMainID = c.ID
	AND c.PaMainID = b.PaMainID
	AND b.Status = 2
	AND a.TitleID > (@Page-1)*20 AND  TitleID <= @Page*20

	SELECT COUNT(*) FROM #t WITH(NOLOCK)
	SELECT * FROM #t WITH(NOLOCK) WHERE TitleID > (@Page - 1)*20 AND TitleID <= @Page*20
	
	DROP TABLE #t
END

GO
/****** Object:  StoredProcedure [dbo].[ccCaCvViewLogBycpMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ccCaCvViewLogBycpMainIDSelect]
(
	@cpMainID INT
)
AS
SET NOCOUNT ON
BEGIN 
	SELECT a.caMainID, a.cvmainid, a.AddDate, b.dcMajorID, b.IsOpen, c.LivePlace, c.Name AS paName,
	e.FullName Region,b.Degree, 0 isApply
	INTO #t
	FROM CaCvViewLog a WITH(NOLOCK) 
	INNER JOIN cvMain b WITH(NOLOCK) ON b.ID = a.cvMainID 
	INNER JOIN paMain c WITH(NOLOCK) ON c.ID = b.paMainID 
	INNER JOIN caMain d WITH(NOLOCK) ON a.caMainID = d.ID
	INNER JOIN dcRegion e WITH(NOLOCK) ON e.ID = c.LivePlace
	WHERE d.cpMainId=@cpMainID
	ORDER BY a.AddDate DESC
	
	UPDATE #t SET IsApply=1 
	FROM #t a,exjobapply b, job c,caMain d
	WHERE b.jobid=c.id and a.caMainid = d.id and c.cpMainID=d.cpMainID AND b.cvMainid = a.cvMainId
	SELECT * FROM #t ORDER BY  AddDate DESC
	DROP TABLE #t
END
SET NOCOUNT OFF


GO
/****** Object:  StoredProcedure [dbo].[ccCaCvViewLogByCpViewCountSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[ccCaCvViewLogByCpViewCountSelect]
(
	@cvMainID INT,
	@cpMainID INT
)
AS
BEGIN
	DECLARE @Cnt AS INT
	SELECT @Cnt = COUNT(1)
	FROM caCvViewLog a WITH(NOLOCK)
	INNER JOIN caMain b WITH(NOLOCK) ON a.caMainID = b.ID
	WHERE b.cpMainID = @cpMainID
	--AND a.cvMainID = @cvMainID 
	AND AddDate > CONVERT(VARCHAR(10), GETDATE(), 120)
	RETURN @Cnt
END














GO
/****** Object:  StoredProcedure [dbo].[cccaCvViewLogInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
----##########################################
----@caMainID 取自Session 
----caCvViewLog.caMainID = ca.caMainID
----##########################################
---20160216 Lucifer 添加推送
CREATE PROCEDURE [dbo].[cccaCvViewLogInsert]
(
	@caMainID INT,	
	@cvMainID INT
)
AS
BEGIN
	IF @caMainID > 0
	BEGIN
		IF EXISTS(SELECT 'x' FROM caCvViewLog WITH(NOLOCK) WHERE cvMainID = @cvMainID AND caMainID = @caMainID)
			UPDATE caCvViewLog SET ADDDATE = GETDATE() WHERE cvMainID = @cvMainID AND caMainID = @caMainID
		ELSE
		BEGIN
			INSERT INTO caCvViewLog(cvMainID, caMainID) VALUES(@cvMainID, @caMainID)
			--HarryBegin
			DECLARE @wxFansId INT, @paMainId INT, @cpMainID INT--harry
			SELECT @paMainId = b.paMainId FROM cvMain b WITH(NOLOCK) WHERE id = @cvMainID
			SELECT @wxFansId = id FROM wxFans WITH(NOLOCK) WHERE paMainId = @paMainId AND [Status] = 2
			IF @wxFansId IS NOT NULL 
			BEGIN
				SELECT @cpMainID = cpMainID FROM caMain WITH(NOLOCK) WHERE id = @caMainID 
				--插入到wxMessageSend表中
				INSERT WxMessageSend2(Templatetype, WxFansID, PaMainId, CpMainID, CvMainID, CaMainId, AddDate)
				SELECT 5, @wxFansId, @paMainId, @cpMainId, @cvMainID, @caMainID, GETDATE()
			END
			--HarryEnd
			INSERT INTO paPushLog(paMainID, PushMessage, PushType)
			SELECT @paMainId, '亲，有企业查看了您的简历！', 4 WHERE EXISTS(SELECT 'X' FROM paIOSBind WHERE paMainID = @paMainId)
		END
	END
	UPDATE cvMain SET ViewNumber = ViewNumber + 1 WHERE ID = @cvMainID
	UPDATE ExJobApply SET ViewDate = GETDATE()
	WHERE JobId IN(SELECT Id FROM Job WHERE caMainId = @caMainId)
	AND cvMainID = @cvMainId
	AND ViewDate IS NULL
END

GO
/****** Object:  StoredProcedure [dbo].[ccCaCvViewLogSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
----##########################################
----@caMainID 取自Session 
----caMainID = ca.caMainID
----##########################################
CREATE PROCEDURE [dbo].[ccCaCvViewLogSelect]
(
	@caMainID INT,
	@AllcvMainID VARCHAR(1000)
)
AS
SET NOCOUNT ON
BEGIN
	SET @AllcvMainID = dbo.FormatIDS(@AllcvMainID)

	SELECT a.caMainid, a.cvMainid, a.AddDate	--, b.paMainId, b.SecondId
	FROM CaCvViewLog a WITH(NOLOCK)	--, cvMain b WITH(NOLOCK)
	WHERE 1=1	--a.cvMainId = b.Id
	AND a.cvMainId IN(SELECT * FROM dbo.fnSplit(@AllCvMainID, ',')) 
	AND a.caMainID = @caMainID
	ORDER BY a.AddDate DESC
END

GO
/****** Object:  StoredProcedure [dbo].[ccCadailyGiftlogAddDateSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.31
--创建人：Nick
--说明：获取下次能下载的时间
--#####################################################
CREATE PROCEDURE [dbo].[ccCadailyGiftlogAddDateSelect]
(
	@CpMainID VARCHAR(20)
)
AS
BEGIN TRY
	SELECT MIN(AddDate) AddDate,MIN(AddDate) + 30 enddate 
	FROM (
		SELECT TOP 12 AddDate 
		FROM cadailygiftlog  WITH(NOLOCK) 
		WHERE camainid IN(
			SELECT id FROM caMain WITH(NOLOCK) 
			WHERE cpMainID=@CpMainID
		) ORDER BY adddate DEsc
	)  a
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[ccCaDailyGiftLogByCpMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.31
--创建人：Nick
--说明：判断一个月内免费下载的简历是否超过30
--#####################################################
CREATE PROCEDURE [dbo].[ccCaDailyGiftLogByCpMainIDSelect]
(
	@CpMainID VARCHAR(20)
)
AS
BEGIN TRY
	SELECT COUNT(1) cnt 
	FROM caDailyGiftLog 
	WHERE cpmainid =@CpMainID 
	AND adddate>GETDATE()-30
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[ccCaDailyGiftLogByNeedPointInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


--###################################################3
--创建：		Lambo
--时间：		2014-8-19
--查看简历消耗积分
--增加Err5 sunshine2018-8-30
--###################################################3
CREATE PROCEDURE [dbo].[ccCaDailyGiftLogByNeedPointInsert]
(
	@cpMainID INT,	
	@caMainID INT,
	@cvMainID INT,
	@IP VARCHAR(30)
)
AS
BEGIN TRAN
	BEGIN TRY
		--判断企业帐户状态是否正常
		IF NOT EXISTS(
				SELECT 'x' FROM cpMain WITH(NOLOCK), caMain WITH(NOLOCK) 
				WHERE cpMain.Id = @cpMainID 
				AND caMain.cpMainID = @cpMainID 
				AND cpMain.Address IS NOT NULL 
				AND cpMain.IsLimitLogin < 9 
				AND cpMain.VerifyResult = 1
				AND caMain.IsDelete = 0 
				AND caMain.IsPause = 0)
			GOTO Err1
		--判断该简历是否是否有联系方式 或者是附件简历
		IF NOT EXISTS(
				SELECT 'x' FROM paMain a WITH(NOLOCK), cvMain b WITH(NOLOCK) 
				WHERE a.ID = b.paMainID 
				AND b.Id = @cvMainID 
				AND (ISNULL(b.Attachment,'')<>'' OR ISNULL(a.Mobile,'')<>''))
			GOTO Err2

		DECLARE @RemainPoint AS INT		--企业剩余积分
		DECLARE @PointConsume AS INT	--下载一份简历所需积分
		DECLARE @dcProvinceID AS INT
		SELECT @RemainPoint = RemainPoint, @dcProvinceID = dcProvinceID FROM cpMain WITH(NOLOCK) WHERE ID = @cpMainID
		SELECT @PointConsume = NeedPoint FROM dcFeeStandard WITH(NOLOCK) WHERE dcProvinceID = @dcProvinceID

   		DECLARE @MonthCount AS INT, @CpRealNameStatus AS INT, @MemberType AS INT
		SELECT @CpRealNameStatus =RealName,@MemberType=memberType from CpMain WITH(NOLOCK) where ID=@CpMainID 
		
		SELECT @MonthCount=COUNT(1)   
		FROM caDailyGiftLog 
		WHERE cpmainid =@CpMainID 
		AND adddate>GETDATE()-30
		
		IF @MemberType!=3
		BEGIN 
		IF ((@CpRealNameStatus =1 AND @MonthCount>=24)OR(@CpRealNameStatus !=1 AND @MonthCount>=12))
			GOTO Err5
		END

		IF ISNULL(@RemainPoint, 0) = 0	--没有积分
			GOTO Err3

		IF @RemainPoint >= @PointConsume	--判断企业剩余积分是否够消耗
		BEGIN
			DECLARE	@Num AS INT
			EXEC @Num = ccActiveDownExist @cpMainID, @cvMainID	--判断这份简历是否下载过
			IF @Num = 0
			BEGIN
				--插入简历下载记录  type=1 为积分下载
				INSERT INTO CaDailyGiftLog(cpMainID,caMainID,cvMainID,IP,Type) VALUES(@cpMainID,@caMainID,@cvMainID,@IP,1)

				--Harry Begin
				DECLARE @paMainID INT, @CaDailyGiftLogID INT, @wxFansId INT
				SELECT @CaDailyGiftLogID = @@IDENTITY
				SELECT @paMainId = paMainId FROM cvMain WITH(NOLOCK) WHERE Id = @cvMainID
				SELECT @wxFansId = id FROM wxFans WITH(NOLOCK) WHERE paMainId = @paMainId AND [Status] = 2
				IF @wxFansId>0
				BEGIN
					--插入到wxMessageSend表中
					INSERT WxMessageSend2(Templatetype, WxFansID, PaMainId, MainTableId, CpMainID, CvMainID, CaMainId, AddDate)
					SELECT 6, @wxFansId, @paMainId, @CaDailyGiftLogID, @cpMainId, @cvMainID, @caMainID, GETDATE()
				END
				--Harry End

				--插入积分使用记录，Point是负数表示消耗积分。企业的剩余积分在cppoint的触发器中更新
				INSERT INTO cpPoint (cpMainID, ChangeID, Point, RelativeID, LastModifyDate)
				VALUES(@cpMainID, 17, 0 - @PointConsume, @cvMainID, GETDATE())
			END
		END
		ELSE
			GOTO Err4
	END TRY
	BEGIN CATCH
		GOTO Err
	END CATCH
COMMIT
RETURN 1
Err:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END
----企业账号信息不正确
Err1:
BEGIN
	ROLLBACK TRAN
	RETURN -1
END
----简历id是无效简历id
Err2:
BEGIN
	ROLLBACK TRAN
	RETURN -2
END
----无积分
Err3:
BEGIN
	ROLLBACK TRAN
	RETURN -3
END
----积分不足
Err4:
BEGIN
	ROLLBACK TRAN
	RETURN -4
END
----本月的赠送简历数已经用完了
Err5:
BEGIN
	ROLLBACK TRAN
	RETURN -5
END



























GO
/****** Object:  StoredProcedure [dbo].[ccCaDailyGiftLogCount]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--####################################
--创建：		Sean 2010-11-12
--根据企业账号查看该企业的所有日赠送消费数量
--####################################
CREATE PROCEDURE [dbo].[ccCaDailyGiftLogCount]
(
	@cpMainID INT
)
AS
BEGIN
	DECLARE @Count AS INT

	SELECT @Count = ISNULL(COUNT(*), 0)
	FROM caDailyGiftLog WITH(NOLOCK)
	WHERE cpMainID = @cpMainID
	AND ConsumeDate = CONVERT(VARCHAR(8), GETDATE(), 112)
	
	RETURN @Count
END














GO
/****** Object:  StoredProcedure [dbo].[ccCaDailyGiftLogInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--###################################################3
--创建：		sean
--时间：		2010-11-15
--查看简历消耗日赠送配额
--增加Err5 sunshine2018-30
--###################################################3
CREATE PROCEDURE [dbo].[ccCaDailyGiftLogInsert]
(
	@cpMainID INT,	
	@caMainID INT,
	@cvMainID INT,
	@IP VARCHAR(30)
)
AS
BEGIN TRAN
	BEGIN TRY
		IF NOT EXISTS(SELECT 'x' FROM cpMain WITH(NOLOCK), caMain WITH(NOLOCK) 
				WHERE cpMain.Id = @cpMainID AND caMain.cpMainID = @cpMainID 
				AND cpMain.Address IS NOT NULL AND cpMain.IsLimitLogin < 9 AND cpMain.VerifyResult = 1
				AND caMain.IsDelete = 0 AND caMain.IsPause = 0)
			GOTO Err1
		IF NOT EXISTS(SELECT 'x' FROM paMain a WITH(NOLOCK), cvMain b WITH(NOLOCK) WHERE a.ID = b.paMainID AND b.Id = @cvMainID AND (ISNULL(b.Attachment,'')<>'' OR ISNULL(a.Mobile,'')<>''))
			GOTO Err2

		DECLARE @MonthCount AS INT, @CpRealNameStatus AS INT, @MemberType AS INT
		SELECT @CpRealNameStatus =RealName,@MemberType=memberType from CpMain WITH(NOLOCK) where ID=@CpMainID 
		
		SELECT @MonthCount=COUNT(1)   
		FROM caDailyGiftLog 
		WHERE cpmainid =@CpMainID 
		AND adddate>GETDATE()-30
		
		IF @MemberType!=3
		BEGIN 
		IF ((@CpRealNameStatus =1 AND @MonthCount>=24)OR(@CpRealNameStatus !=1 AND @MonthCount>=12))
			GOTO Err5
		END
		DECLARE @DailyGiftQuota AS INT
		DECLARE @DailyGiftConsume AS INT
		SELECT @DailyGiftQuota = DailyGiftQuota FROM cpMain WITH(NOLOCK) WHERE ID = @cpMainID
		EXEC @DailyGiftConsume = ccCaDailyGiftLogCount @cpMainID

		IF ISNULL(@DailyGiftQuota, 0) = 0
			GOTO Err3

		IF @DailyGiftQuota > @DailyGiftConsume
		BEGIN
			DECLARE	@Num AS INT
			EXEC @Num = ccActiveDownExist @cpMainID,@cvMainID
			IF @Num = 0
			BEGIN
				--Harry Begin
				DECLARE @paMainID INT, @CaDailyGiftLogID INT, @wxFansId INT
				INSERT INTO CaDailyGiftLog(cpMainID,caMainID,cvMainID,IP) VALUES(@cpMainID,@caMainID,@cvMainID,@IP)
				SELECT @CaDailyGiftLogID = @@IDENTITY
				SELECT @paMainId = paMainId FROM cvMain WITH(NOLOCK) WHERE Id = @cvMainID
				SELECT @wxFansId = id FROM wxFans WITH(NOLOCK) WHERE paMainId = @paMainId AND [Status] = 2
				IF @wxFansId>0
				BEGIN
					--插入到wxMessageSend表中
					INSERT WxMessageSend2(Templatetype, WxFansID, PaMainId, MainTableId, CpMainID, CvMainID, CaMainId, AddDate)
					SELECT 6, @wxFansId, @paMainId, @CaDailyGiftLogID, @cpMainId, @cvMainID, @caMainID, GETDATE()
				END
				--Harry End

				SET @DailyGiftConsume = @DailyGiftConsume + 1
			END
		END
		ELSE
			GOTO Err4
	END TRY
	BEGIN CATCH
		GOTO Err
	END CATCH
COMMIT
RETURN @DailyGiftConsume
Err:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END
----企业账号信息不正确
Err1:
BEGIN
	ROLLBACK TRAN
	RETURN -1
END
----简历id是无效简历id
Err2:
BEGIN
	ROLLBACK TRAN
	RETURN -2
END
----本日赠送为0或空
Err3:
BEGIN
	ROLLBACK TRAN
	RETURN -3
END
----本日赠送已经消耗完毕
Err4:
BEGIN
	ROLLBACK TRAN
	RETURN -4
END
----本月的赠送简历数已经用完了
Err5:
BEGIN
	ROLLBACK TRAN
	RETURN -5
END


GO
/****** Object:  StoredProcedure [dbo].[cccaDownloadLogByExcelSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--20180227 Carl 修改 隐藏的姓名导出时也隐藏
CREATE PROCEDURE [dbo].[cccaDownloadLogByExcelSelect]
(
	@cpMainID INT, 
	@WHERE VARCHAR(1000), 
	@ORDER VARCHAR(100), 
	@caMainID INT
)
AS
SET NOCOUNT ON
BEGIN
	SET @Where = dbo.SafeSql(@Where)
	SET @ORDER = dbo.SafeSql(@Order)
	
	DECLARE @SQL VARCHAR(2000)
	CREATE TABLE #T(
		cvMainID INT, 
		Degree TINYINT, 
		RelatedWorkYears TINYINT, 
		Attachment VARCHAR(50) COLLATE Chinese_PRC_CI_AS , 
		IsNameHidden BIT, 
		LivePlace VARCHAR(6) COLLATE Chinese_PRC_CI_AS , 
		Gender BIT, 
		paName NVARCHAR(20), 
		BirthDay INT, 
		HasPhoto TINYINT, 
		Valid TINYINT, 
		Speciality VARCHAR(MAX) COLLATE Chinese_PRC_CI_AS, 
		Email VARCHAR(50), 
        Mobile VARCHAR(13), 
		Adddate SMALLDATETIME, 
		paMainId INT, 
		SecondId VARCHAR(10)
	)

	SET @SQL = '
		INSERT INTO #T(cvMainID, Degree, RelatedWorkYears, Attachment, IsNameHidden,
			LivePlace, Gender, paName, BirthDay, HasPhoto, Valid, Speciality, Email,
			Mobile, Adddate, paMainId, SecondId)
		SELECT b.* FROM (
			SELECT 
				a.cvMainID, b.Degree, b.RelatedWorkYears, b.Attachment, b.IsNameHidden, 
				c.LivePlace, c.Gender, LEFT(dbo.GetPaName(b.Id, '+CONVERT(VARCHAR,@cpMainID)+'), 20) name, c.BirthDay, c.HasPhoto, b.Valid, b.Speciality,
				c.Email, c.Mobile, a.Adddate, b.paMainId, b.SecondId
			FROM caDailyGiftLog a WITH(NOLOCK)
			INNER JOIN cvMain b WITH(NOLOCK) ON b.ID = a.cvMainID
			INNER JOIN paMain c WITH(NOLOCK) ON c.ID = b.paMainID
			WHERE cpMainID = ' + LTRIM(STR(@cpMainID)) + ' ' + REPLACE(@WHERE, 'a.caOrderID', '1') + '
			UNION
			SELECT 
				a.cvMainID, b.Degree, b.RelatedWorkYears, b.Attachment, b.IsNameHidden, 
				c.LivePlace, c.Gender, LEFT(dbo.GetPaName(b.Id, '+CONVERT(VARCHAR,@cpMainID)+'), 20) name, c.BirthDay, c.HasPhoto, b.Valid, b.Speciality,
				c.Email, c.Mobile, a.Adddate, b.paMainId, b.SecondId
			FROM caActiveLog a WITH(NOLOCK)
			INNER JOIN cvMain b WITH(NOLOCK) ON b.ID = a.cvMainID
			INNER JOIN paMain c WITH(NOLOCK) ON c.ID = b.paMainID
			WHERE cpMainID = ' + LTRIM(STR(@cpMainID)) + ' ' + @WHERE + 
			') b'

	--PRINT @SQL
	EXEC(@SQL)
	
	SELECT * FROM #T WITH(NOLOCK) ORDER BY AddDate DESC
	DROP TABLE #T
END


GO
/****** Object:  StoredProcedure [dbo].[cccaDownloadLogSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--20160108 nick 加入是否绑定微信
CREATE PROCEDURE [dbo].[cccaDownloadLogSelect]
(
	@cpMainID INT, 
	@WHERE VARCHAR(1000), 
	@ORDER VARCHAR(100), 
	@Page SMALLINT, 
	@caMainID INT
)
AS
SET NOCOUNT ON
BEGIN
	SET @Where = dbo.SafeSql(@Where)
	SET @ORDER = dbo.SafeSql(@Order)

	DECLARE @SQL VARCHAR(2000)
	CREATE TABLE #T(
		TitleID BIGINT, 
		cvMainID INT, 
		caOrderID INT NULL, 
		IP VARCHAR(39) COLLATE Chinese_PRC_CI_AS NOT NULL, 
		RemainQuota SMALLINT NULL, 
		AddDate SMALLDATETIME, 
		Degree TINYINT, 
		RelatedWorkYears TINYINT, 
		Attachment VARCHAR(50) COLLATE Chinese_PRC_CI_AS , 
		IsNameHidden BIT, 
		LivePlace VARCHAR(6) COLLATE Chinese_PRC_CI_AS , 
		Gender BIT, 
		paName NVARCHAR(20), 
		BirthDay INT, 
		HasPhoto TINYINT, 
		Valid TINYINT, 
		HasJobApply BIT, 
		HasInterview BIT, 
		HasRemark BIT, 
		HasFavorate BIT, 
		cvEducationID INT, 
		College NVARCHAR(50), 
		EduType TINYINT, 
		MajorName NVARCHAR(20), 
		Graduation INT, 
		Speciality VARCHAR(MAX) COLLATE Chinese_PRC_CI_AS, 
		Experience VARCHAR(MAX) COLLATE Chinese_PRC_CI_AS, 
		MobileVerifyDate SMALLDATETIME, 
		IsOnline BIT, 
		HasWeiXin BIT, 
		paMainID INT, 
		SecondId VARCHAR(10)
	)
	SET @SQL = '
		INSERT INTO #T(TitleID, cvMainID, caOrderID, RemainQuota, IP, AddDate, Degree, RelatedWorkYears, 
			Attachment, IsNameHidden, LivePlace, Gender, BirthDay, HasPhoto, Valid, MobileVerifyDate, IsOnline, paMainId, SecondId)
		SELECT ROW_NUMBER() OVER (ORDER BY ' + @ORDER + ') AS TitleID, a.* FROM (
		SELECT 
			a.cvMainID, NULL caOrderID, NULL RemainQuota, a.IP, a.AddDate, 
			b.Degree, b.RelatedWorkYears, b.Attachment, b.IsNameHidden, 
			c.LivePlace, c.Gender, c.BirthDay, c.HasPhoto, b.Valid, c.MobileVerifyDate,
			dbo.GetPaOnlineStatus(c.ID) IsOnline, b.paMainId, b.SecondId
		FROM caDailyGiftLog a WITH(NOLOCK)
		INNER JOIN cvMain b WITH(NOLOCK) ON b.ID = a.cvMainID
		INNER JOIN paMain c WITH(NOLOCK) ON c.ID = b.paMainID
		WHERE cpMainID = ' + LTRIM(STR(@cpMainID)) + ' ' + REPLACE(@WHERE, 'a.caOrderID', '1') + '
		AND a.AddDate > DATEADD(YEAR, -2, GETDATE())
		UNION
		SELECT 
			a.cvMainID, a.caOrderID, a.RemainQuota, a.IP, a.AddDate, 
			b.Degree, b.RelatedWorkYears, b.Attachment, b.IsNameHidden, 
			c.LivePlace, c.Gender, c.BirthDay, c.HasPhoto, b.Valid, c.MobileVerifyDate,
			dbo.GetPaOnlineStatus(c.ID) IsOnline, b.paMainId, b.SecondId
		FROM caActiveLog a WITH(NOLOCK)
		INNER JOIN cvMain b WITH(NOLOCK) ON b.ID = a.cvMainID
		INNER JOIN paMain c WITH(NOLOCK) ON c.ID = b.paMainID
		WHERE cpMainID = ' + LTRIM(STR(@cpMainID)) + '
		AND a.AddDate > DATEADD(YEAR, -2, GETDATE()) ' + @WHERE + ') a'

	--PRINT @SQL
	EXEC(@SQL)

	IF(@Page < 1)
		SET @Page = 1
	IF NOT EXISTS(SELECT 'x' FROM #t WHERE TitleID > (@Page-1)*20 AND  TitleID <= @Page*20)
		SET @Page = 1

	UPDATE #T SET paName = LEFT(dbo.GetPaName(cvMainID, @cpMainID), 20), 
		HasJobApply = (SELECT TOP 1 '1' FROM exJobApply a WITH(NOLOCK) INNER JOIN Job b WITH(NOLOCK) ON a.JobID=b.ID WHERE a.CompanyDeleted=0 AND b.caMainID=@caMainID AND cvMainID=#T.cvMainID), 
		HasInterview = (SELECT TOP 1 '1' FROM exInterview a WITH(NOLOCK) INNER JOIN Job b WITH(NOLOCK) ON a.JobID=b.ID WHERE a.CompanyDeleted=0 AND b.caMainID=@caMainID AND cvMainID=#T.cvMainID), 
		HasRemark = (SELECT TOP 1 '1' FROM caCvRemark WITH(NOLOCK) WHERE caMainID=@caMainID AND cvMainID=#T.cvMainID), 
		HasFavorate = (SELECT TOP 1 '1' FROM caFavorate WITH(NOLOCK) WHERE caMainID=@caMainID AND cvMainID=#T.cvMainID)
	WHERE TitleID > (@Page-1)*20 AND TitleID <= @Page*20
	
	UPDATE #T SET Speciality = (
		SELECT Speciality FROM cvMain WITH(NOLOCK)
		WHERE cvMain.ID = #T.cvMainID)
	WHERE TitleID > (@Page-1)*20 AND TitleID <= @Page*20
	
	UPDATE #T SET Experience = (
		SELECT TOP 1 ISNULL(Description, DescriptionEng) FROM cvExperience WITH(NOLOCK)
		WHERE cvExperience.cvMainID = #T.cvMainID
		ORDER BY BeginDate DESC)
	WHERE TitleID > (@Page-1)*20 AND TitleID <= @Page*20

	UPDATE #T SET cvEducationID = (
		SELECT TOP 1 ID FROM cvEducation WITH(NOLOCK)
		WHERE cvEducation.cvMainID = #T.cvMainID
		AND #T.Degree = cvEducation.Degree
		ORDER BY Graduation DESC)
	WHERE TitleID > (@Page-1)*20 AND TitleID <= @Page*20

	UPDATE a SET a.College = ISNULL(b.GraduateCollage, b.GraduateCollageEng), a.EduType = b.EduType, 
		a.MajorName = ISNULL(b.MajorName, b.MajorNameEng), a.Graduation = b.Graduation
	FROM #T a, cvEducation b WITH(NOLOCK)
	WHERE b.ID = a.cvEducationID AND a.TitleID > (@Page-1)*20 AND a.TitleID <= @Page*20

	--修改是否绑定微信
	UPDATE a SET HasWeiXin = 1
	FROM #T a, WxFans b WITH(NOLOCK), CvMain c WITH(NOLOCK)
	WHERE a.CvMainID = c.ID
	AND c.PaMainID = b.PaMainID
	AND b.Status = 2
	AND a.TitleID > (@Page-1)*20 AND  TitleID <= @Page*20

	SELECT COUNT(*) FROM #T WITH(NOLOCK)
	SELECT * FROM #T WITH(NOLOCK) WHERE TitleID > (@Page-1)*20 AND TitleID <= @Page*20
	
	DROP TABLE #T
END


GO
/****** Object:  StoredProcedure [dbo].[cccaFavorateBatchDelete]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[cccaFavorateBatchDelete]
(
	@AllID VARCHAR(1000),
	@cpMainID INT
)
AS
BEGIN TRY
	SET @AllID = dbo.FormatIDS(@AllID)
	DECLARE @T AS TABLE(ID INT)
	INSERT INTO @T SELECT * FROM dbo.fnSplit(@AllID, ',')

	DELETE FROM caFavorate
	WHERE ID IN(SELECT ID FROM @T)
	AND caMainID IN (SELECT ID FROM caMain WITH(NOLOCK) WHERE cpMainID = @cpMainID)
END TRY
BEGIN CATCH
	GOTO ERR
END CATCH
RETURN 1
ERR:
BEGIN
	RETURN 0
END














GO
/****** Object:  StoredProcedure [dbo].[cccaFavorateByCvMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--修改:Andy 2015-01-13 添加职位的regionid 
CREATE PROCEDURE [dbo].[cccaFavorateByCvMainIDSelect]
(
	@caMainID INT,		--=0时是全部
	@cvMainID INT,
	@cpMainID INT
)
AS
BEGIN
	BEGIN TRY
		IF @caMainID = 0
			SELECT a.caMainID,c.dcRegionID,a.AddDate, b.Name AS caName, a.JobID, c.Name AS JobName
			FROM caFavorate a WITH(NOLOCK)
			INNER JOIN caMain b WITH(NOLOCK) ON a.caMainID = b.ID
			INNER JOIN Job c WITH(NOLOCK) ON a.JobID = c.ID 
			WHERE cvMainID = @cvMainID AND b.cpMainID = @cpMainID

		IF @caMainID > 0
			SELECT a.AddDate, c.dcRegionID,b.Name AS caName, a.JobID, c.Name AS JobName
			FROM caFavorate a WITH(NOLOCK)
			INNER JOIN caMain b WITH(NOLOCK) ON a.caMainID = b.ID
			INNER JOIN Job c WITH(NOLOCK) ON a.JobID = c.ID 
			WHERE cvMainID = @cvMainID
			AND b.cpMainID = @cpMainID
			AND b.ID = @caMainID		
	END TRY
	BEGIN CATCH
	END CATCH
END

GO
/****** Object:  StoredProcedure [dbo].[ccCaFavorateByExcelSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--Add by andy 2014-12-18
--查询收藏的职位（用于网站前台导出excel）
--alen 2018-3-28
CREATE PROCEDURE [dbo].[ccCaFavorateByExcelSelect]
(
	@WHERE VARCHAR(1000),	
	@cpMainID INT,
	@caMainID INT
)
AS
SET NOCOUNT ON
IF NOT EXISTS(SELECT 'x' FROM caMain WHERE id = @caMainId AND cpMainId = @cpMainId)
	RETURN
BEGIN
	SET @WHERE = dbo.SafeSQL(@WHERE)		
	DECLARE @SQL AS VARCHAR(2000)
	CREATE TABLE #T(			
		ID INT, 
		JobID INT, 
		cvMainID INT, 
		caFavorateMarkID INT, 
		Degree TINYINT, 
		RelatedWorkYears TINYINT, 
		Attachment VARCHAR(50) COLLATE Chinese_PRC_CI_AS, 
		IsNameHidden BIT, 
		LivePlace VARCHAR(6) COLLATE Chinese_PRC_CI_AS, 
		Gender BIT, 
		paName NVARCHAR(20), 
		BirthDay INT, 
		HasPhoto TINYINT, 
		adddate SMALLDATETIME, 
		Valid TINYINT, 
		IsViewed BIT, 
		HasJobApply BIT, 
		HasInterview BIT, 
		HasRemark BIT, 
		cvEducationID INT, 
		College NVARCHAR(50), 
		EduType TINYINT, 
		MajorName NVARCHAR(20), 
		Graduation INT, 
		Speciality VARCHAR(MAX) COLLATE Chinese_PRC_CI_AS, 
		Experience VARCHAR(MAX) COLLATE Chinese_PRC_CI_AS, 
		MobileVerifyDate SMALLDATETIME, 
		IsOnline BIT, 
		IsShowContact INT
	)
	SET @SQL = '
		INSERT INTO #T(
			ID, JobID, cvMainID, caFavorateMarkID, Degree, RelatedWorkYears, 
			Attachment, IsNameHidden, LivePlace, Gender, paName, BirthDay, HasPhoto, adddate, 
			Valid, MobileVerifyDate, IsOnline, IsShowContact)
		SELECT a.ID, a.JobID, a.cvMainID, a.caFavorateMarkID, 
			b.Degree, b.RelatedWorkYears, b.Attachment, b.IsNameHidden, 
			c.LivePlace, c.Gender, dbo.GetPaName(a.cvMainID, ' + LTRIM(STR(@cpMainID)) + ') AS paName, c.BirthDay, c.HasPhoto, 
			a.adddate, b.Valid, c.MobileVerifyDate, 0, 0
		FROM caFavorate a WITH(NOLOCK)
		INNER JOIN cvMain b WITH(NOLOCK) ON b.ID = a.cvMainID
		INNER JOIN paMain c WITH(NOLOCK) ON c.ID = b.paMainID
		INNER JOIN Job d WITH(NOLOCK) ON d.ID = a.JobID
		WHERE d.IsDelete = 0 AND a.caMainID = ' +LTRIM(STR(@caMainID))
	IF LEN(@WHERE) > 0
		SET @SQL = @SQL + @WHERE
	SET @SQL = @SQL + ' ORDER BY a.Id DESC'
	--print @sql
	EXEC(@SQL)		

	UPDATE #T 
	SET Speciality = (
		SELECT Speciality 
		FROM cvMain WITH(NOLOCK)
		WHERE cvMain.ID = #T.cvMainID)
			
	UPDATE #T 
	SET Experience = (
		SELECT TOP 1 ISNULL(Description, DescriptionEng) 
		FROM cvExperience WITH(NOLOCK) 
		WHERE cvExperience.cvMainID = #T.cvMainID	
		ORDER BY BeginDate DESC)		

	UPDATE #T SET cvEducationID = (
		SELECT TOP 1 ID FROM cvEducation WITH(NOLOCK)
		WHERE cvEducation.cvMainID = #T.cvMainID AND #T.Degree = cvEducation.Degree
		ORDER BY Graduation DESC)		

	UPDATE a 
	SET a.College = ISNULL(b.GraduateCollage, b.GraduateCollageEng), a.EduType = b.EduType, 
		a.MajorName = ISNULL(b.MajorName, b.MajorNameEng), a.Graduation = b.Graduation
	FROM #T a, cvEducation b WITH(NOLOCK)
	WHERE b.ID = a.cvEducationID 

	UPDATE #t SET IsShowContact = 1 WHERE cvMainId IN(SELECT cvMainId FROM caActiveLog WITH(NOLOCK) WHERE cpMainId = @cpMainId)
	UPDATE #t SET IsShowContact = 1 WHERE cvMainId IN(SELECT cvMainId FROM caDailyGiftLog WITH(NOLOCK) WHERE cpMainId = @cpMainId)
	UPDATE #t SET IsShowContact = 1 WHERE cvMainId IN(SELECT cvMainId FROM exJobApply WITH(NOLOCK) WHERE JobId IN(SELECT ID FROM Job WITH(NOLOCK) WHERE cpMainId = @cpMainId) AND IsPassed = 1)

	SELECT COUNT(*) FROM #T WITH(NOLOCK)
	SELECT * FROM #T WITH(NOLOCK)
	
	DROP TABLE #T
END

GO
/****** Object:  StoredProcedure [dbo].[cccaFavorateInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
----##########################################
----@caMainID 取自Session 
----caMainID = ca.caMainID
----caFavorate.caMainID = caMainID
----2012.1.10增加return,1新增；2：修改
----因为有求职者反映，会收到很多邮件，估计是企业查询收藏再查询收藏，而发邮件没有判断是否以前收藏过造成重复发送邮件
----2015-8-27Harry
----收藏简历时，判断是否关注插入到wxsendmessage表
----##########################################
CREATE PROCEDURE [dbo].[cccaFavorateInsert]
(
	@caMainID INT,
	@JobId INT,
	@cvMainID INT
)
AS
BEGIN
	IF NOT EXISTS(
		SELECT 'x' FROM Job WITH(NOLOCK) 
		WHERE Id = @JobId 
		AND caMainID IN (
			SELECT ID FROM CaMain 
			WHERE CpMainID = (
				SELECT CpMainID FROM CaMain WHERE id = @caMainId
			)
		) 
	)
		RETURN 0

	IF EXISTS(
		SELECT ID FROM caFavorate 
		WHERE JobId = @JobId 
		AND caMainID IN (
			SELECT ID FROM CaMain 
			WHERE CpMainID = (
				SELECT CpMainID FROM CaMain WHERE id = @caMainId
			)
		) 
		AND cvMainID = @cvMainID
	)
	BEGIN
		UPDATE caFavorate SET AddDate = GETDATE() WHERE JobId = @JobId AND caMainID = @caMainID AND cvMainID = @cvMainID
		RETURN 2
	END
	ELSE
	BEGIN
		--about weixin send
		DECLARE @paMainId INT, @caFavorateID INT, @wxFansId INT,@wxStatus INT, @openId VARCHAR(50), @cpMainId INT
		INSERT INTO caFavorate(caMainID, JobId, cvMainID) VALUES(@caMainID, @JobId, @cvMainID)
		SELECT @caFavorateID = @@IDENTITY

		SELECT @paMainId=a.pamainId, @wxFansId = b.id
		FROM cvMain a WITH(NOLOCK), wxFans b WITH(NOLOCK) 
		WHERE a.Id = @cvMainID 
		AND a.paMainId = b.paMainId 
		AND b.[Status] = 2

		IF @wxFansId IS NOT NULL --0已取消关注 1 正在关注 2 已绑定账号
		BEGIN
			SELECT @cpMainId = cpMainId FROM caMain WITH(NOLOCK) WHERE Id = @caMainID
			--插入到wxMessageSend表中
			INSERT WxMessageSend2(Templatetype, WxFansID, PaMainId, MainTableId, CpMainID, CvMainID, JobId, CaMainId, AddDate)
			SELECT 3, @wxFansId, @paMainId, @caFavorateID, @cpMainId, @cvMainID, @JobId, @caMainID, GETDATE()
		END 
		RETURN 1
	END
END

GO
/****** Object:  StoredProcedure [dbo].[cccaFavorateMarkBycaMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[cccaFavorateMarkBycaMainIDSelect]
(
	@caMainID INT
)
AS
BEGIN
	SELECT ID, Mark, AddDate FROM caFavorateMark WHERE caMainID = @caMainID
END














GO
/****** Object:  StoredProcedure [dbo].[cccaFavorateMarkDelete]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--Lambo 20101130 修改
--增加cpMainID 参数，判断是否是本企业的
CREATE PROCEDURE [dbo].[cccaFavorateMarkDelete]
(
	@ID INT,
	@cpMainID INT
)
AS
BEGIN
	DELETE FROM caFavorateMark
	WHERE ID = @ID
	AND caMainID IN(
					SELECT ID FROM caMain WITH(NOLOCK) WHERE cpMainID = @cpMainID
					)

	UPDATE caFavorate SET caFavorateMarkID = NULL
	WHERE caFavorateMarkID = @ID
	AND caMainID IN(
					SELECT ID FROM caMain WITH(NOLOCK) WHERE cpMainID = @cpMainID
					)
END














GO
/****** Object:  StoredProcedure [dbo].[cccaFavorateMarkSave]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--Lambo 20101130 修改
--update语句后面加上增加本账户的条件
--caFavorateMark.caMainID = ca.caMainID
CREATE PROCEDURE [dbo].[cccaFavorateMarkSave]
(
	@ID INT,
	@caMainID INT,
	@Mark VARCHAR(20)
)
AS
BEGIN
	IF @ID > 0
	BEGIN
		UPDATE caFavorateMark SET Mark = @Mark 
		WHERE ID = @ID
		AND caMainID IN (
						SELECT caMainID FROM caMain WITH(NOLOCK)
						WHERE cpMainID = (SELECT cpMainID FROM caMain WITH(NOLOCK) WHERE ID = @caMainID)
						)
		RETURN @ID
	END
	ELSE
	BEGIN
		INSERT INTO caFavorateMark(caMainID, Mark) VALUES(@caMainID, @Mark)
		RETURN @@IDENTITY
	END
END














GO
/****** Object:  StoredProcedure [dbo].[cccaFavorateMarkSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[cccaFavorateMarkSelect]
(
	@ID INT
)
AS
BEGIN
	SELECT ID, caMainID, Mark, AddDate
	FROM caFavorateMark
	WHERE ID = @ID
END














GO
/****** Object:  StoredProcedure [dbo].[cccaFavorateSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


--#####################################################
--修改：
-- 2015-6-3 mice 123 修改管理员类型的ca可以查看子账号收藏的简历
-- 2016-01-08 nick 加入是否绑定微信
--#####################################################
CREATE  PROCEDURE [dbo].[cccaFavorateSelect]
(
	@WHERE VARCHAR(1000), 
	@Order VARCHAR(100), 
	@Page SMALLINT, 
	@cpMainID INT, 
	@caMainID INT
)
AS
SET NOCOUNT ON
IF NOT EXISTS(SELECT 'x' FROM caMain WITH(NOLOCK) WHERE Id = @caMainId AND cpMainId = @cpMainId)
	RETURN

BEGIN
	SELECT @Where = dbo.SafeSql(@Where), @ORDER = dbo.SafeSql(@Order)
	DECLARE @SQL AS VARCHAR(2000)
	CREATE TABLE #T(
		TitleID BIGINT, 
		ID INT, 
		JobID INT, 
		cvMainID INT, 
		caFavorateMarkID INT, 
		Degree TINYINT, 
		RelatedWorkYears TINYINT, 
		Attachment VARCHAR(50) COLLATE Chinese_PRC_CI_AS, 
		IsNameHidden BIT, 
		LivePlace VARCHAR(6) COLLATE Chinese_PRC_CI_AS, 
		Gender BIT, 
		paName NVARCHAR(20), 
		BirthDay INT, 
		HasPhoto TINYINT, 
		adddate SMALLDATETIME, 
		Valid TINYINT, 
		IsViewed BIT, 
		HasJobApply BIT, 
		HasInterview BIT, 
		HasRemark BIT, 
		cvEducationID INT, 
		College NVARCHAR(50), 
		EduType TINYINT, 
		MajorName NVARCHAR(20), 
		Graduation INT, 
		Speciality VARCHAR(MAX) COLLATE Chinese_PRC_CI_AS, 
		Experience VARCHAR(MAX) COLLATE Chinese_PRC_CI_AS, 
		MobileVerifyDate SMALLDATETIME, 
		IsOnline BIT, 
		HasWeiXin BIT, 
		paMainId INT, 
		SecondId VARCHAR(10)
	)

	--ca的类型： 1 管理员  2 普通用户
	DECLARE @AccountType AS TINYINT
	SELECT 	@AccountType = AccountType FROM caMain WITH(NOLOCK) WHERE ID = @caMainID	

	SET @SQL='
		INSERT INTO #T(
			TitleID, ID, JobID, cvMainID, caFavorateMarkID, Degree, RelatedWorkYears, 
			Attachment, IsNameHidden, LivePlace, Gender, paName, BirthDay, HasPhoto, adddate, 
			Valid, MobileVerifyDate, IsOnline, paMainId, SecondId
		)
		SELECT ROW_NUMBER() OVER (ORDER BY ' + @ORDER + ') AS TitleID, 
			a.ID, a.JobID, a.cvMainID, a.caFavorateMarkID, 
			b.Degree, b.RelatedWorkYears, b.Attachment, b.IsNameHidden, 
			c.LivePlace, c.Gender, c.Name AS paName, c.BirthDay, c.HasPhoto, 
			a.adddate, b.Valid, c.MobileVerifyDate, dbo.GetPaOnlineStatus(c.ID),
			b.paMainId, b.SecondId
		FROM caFavorate a WITH(NOLOCK)
		INNER JOIN cvMain b WITH(NOLOCK) ON b.ID = a.cvMainID
		INNER JOIN paMain c WITH(NOLOCK) ON c.ID = b.paMainID
		INNER JOIN Job d WITH(NOLOCK) ON d.ID = a.JobID
		WHERE d.IsDelete = 0  ' 

	--add by mice 123 ca中的管理员可以查看子账号收藏的简历
	IF @AccountType = 1
	BEGIN
		SET @SQL =  @SQL + '  AND a.caMainID  IN  (  SELECT ID FROM caMain WHERE cpMainID =  ' + LTRIM(STR(@cpMainID)) + ' AND IsDelete = 0 AND IsPause = 0 )  '
	END
	ELSE
	BEGIN
		SET @SQL =  @SQL + '  AND a.JobId IN(SELECT Id FROM Job WITH(NOLOCK) WHERE caMainID = ' + LTRIM(STR(@caMainID)) + ')'
	END

	IF LEN(@WHERE) > 0
		SET @SQL = @SQL + @WHERE
	--PRINT @sql
	EXEC(@SQL)

	IF(@Page < 1)
		SET @Page = 1
	IF NOT EXISTS(SELECT 'x' FROM #t WHERE TitleID > (@Page-1)*20 AND TitleID <= @Page*20)
		SET @Page = 1

	UPDATE #T SET paName = LEFT(dbo.GetPersonName(cvMainID, @cpMainID), 20), 
	IsViewed = (SELECT TOP 1 '1' FROM caCvViewLog WITH(NOLOCK) WHERE cvMainID=#T.cvMainID AND caMainID=@caMainID), 
	HasJobApply = (SELECT TOP 1 '1' FROM exJobApply a WITH(NOLOCK) INNER JOIN Job b WITH(NOLOCK) ON a.JobID=b.ID WHERE a.CompanyDeleted=0 AND b.caMainID=@caMainID AND cvMainID=#T.cvMainID), 
	HasInterview = (SELECT TOP 1 '1' FROM exInterview a WITH(NOLOCK) INNER JOIN Job b WITH(NOLOCK) ON a.JobID=b.ID WHERE a.CompanyDeleted=0 AND b.caMainID=@caMainID AND cvMainID=#T.cvMainID), 
	HasRemark = (SELECT TOP 1 '1' FROM caCvRemark WITH(NOLOCK) WHERE caMainID=@caMainID AND cvMainID=#T.cvMainID)
	WHERE TitleID > (@Page-1)*20 AND TitleID <= @Page*20

	UPDATE #T SET Speciality = (
		SELECT Speciality FROM cvMain WITH(NOLOCK)
		WHERE cvMain.ID = #T.cvMainID)
	WHERE TitleID > (@Page-1)*20 AND TitleID <= @Page*20
	
	UPDATE #T SET Experience = (
		SELECT TOP 1 ISNULL(Description, DescriptionEng) FROM cvExperience WITH(NOLOCK)
		WHERE cvExperience.cvMainID = #T.cvMainID
		ORDER BY BeginDate DESC)
	WHERE TitleID > (@Page-1)*20 AND TitleID <= @Page*20

	UPDATE #T SET cvEducationID = (
		SELECT TOP 1 ID FROM cvEducation WITH(NOLOCK)
		WHERE cvEducation.cvMainID = #T.cvMainID
		AND #T.Degree = cvEducation.Degree
		ORDER BY Graduation DESC)
	WHERE TitleID > (@Page-1)*20 AND TitleID <= @Page*20

	UPDATE a SET a.College = ISNULL(b.GraduateCollage, b.GraduateCollageEng), a.EduType = b.EduType, 
		a.MajorName = ISNULL(b.MajorName, b.MajorNameEng), a.Graduation = b.Graduation
	FROM #T a, cvEducation b WITH(NOLOCK)
	WHERE b.ID = a.cvEducationID AND a.TitleID > (@Page-1)*20 AND a.TitleID <= @Page*20

	--修改是否绑定微信
	UPDATE a SET HasWeiXin = 1
	FROM #T a, WxFans b WITH(NOLOCK), CvMain c WITH(NOLOCK)
	WHERE a.CvMainID = c.ID
	AND c.PaMainID = b.PaMainID
	AND b.Status = 2
	AND a.TitleID > (@Page-1)*20 AND  TitleID <= @Page*20

	SELECT COUNT(*) FROM #T WITH(NOLOCK)
	SELECT * FROM #T WITH(NOLOCK) WHERE TitleID > (@Page-1)*20 AND TitleID <= @Page*20
	
	DROP TABLE #T
END


GO
/****** Object:  StoredProcedure [dbo].[cccaFavorateUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[cccaFavorateUpdate]
(
	@AllID VARCHAR(1000),
	@MarkID INT,
	@cpMainId INT
)
AS
BEGIN
	SET @AllID = dbo.FormatIDS(@AllID)
	DECLARE @NewMarkID AS VARCHAR(2000)
	IF @MarkID > 0
		SET @NewMarkID = LTRIM(STR(@MarkID))
	ELSE
		SET @NewMarkID = NULL

	DECLARE @T AS TABLE(ID INT)
	INSERT INTO @T SELECT * FROM dbo.fnSplit(@AllID, ',')

	UPDATE caFavorate SET caFavorateMarkID = @NewMarkID
	WHERE ID IN(SELECT ID FROM @T)
	AND caMainID IN(SELECT ID FROM caMain WITH(NOLOCK) WHERE cpMainID = @cpMainID)
END














GO
/****** Object:  StoredProcedure [dbo].[ccCaFeedBackByCaMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ccCaFeedBackByCaMainIDSelect]
    @CaMainID INT
AS
BEGIN
    SELECT
        *
    FROM CaFeedBack WITH(NOLOCK)
    WHERE caMainID = @caMainID
	ORDER BY ID DESC
END














GO
/****** Object:  StoredProcedure [dbo].[ccCaFeedBackByCpMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ccCaFeedBackByCpMainIDSelect]
    @CpMainID INT
AS
BEGIN
    SELECT
        a.*,b.Name caNAme
    FROM CaFeedBack a WITH(NOLOCK) , caMain b WITH(NOLOCK)
    WHERE  a.caMainID = b.ID
	AND b.cpMainID = @cpMainID
	AND b.isDelete = 0
	ORDER BY a.ID DESC
END














GO
/****** Object:  StoredProcedure [dbo].[ccCaFeedBackInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ccCaFeedBackInsert]
(
	@caMainID INT,
	@dcProvinceID INT,
	@IP VARCHAR(31),
	@Name VARCHAR(100),
	@Telephone VARCHAR(50),
	@Email VARCHAR(100),
	@Message VARCHAR(4000)
)
AS
BEGIN TRY
	SET @Telephone = dbo.TrimNull(@Telephone)
	INSERT INTO CaFeedBack
	(caMainID,dcProvinceID,IP,Name,Telephone,Email,Message,AddDate)
	VALUES
	(@caMainID,@dcProvinceID,@IP,@Name,@Telephone,@Email,@Message,GETDATE())
END TRY
BEGIN CATCH
	GOTO ERR
END CATCH
RETURN 1
ERR:
BEGIN
	RETURN 0
END














GO
/****** Object:  StoredProcedure [dbo].[ccCaFeedBackNoViewSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[ccCaFeedBackNoViewSelect]
    @CaMainID INT
AS
BEGIN
    SELECT
        *
    FROM CaFeedBack WITH(NOLOCK)
    WHERE caMainID = @caMainID
	AND IsReply = 1
	AND ViewDate IS NULL
	ORDER BY ID DESC
END














GO
/****** Object:  StoredProcedure [dbo].[ccCaFeedBackViewDateUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--asp中取所有viewDate is null的id
CREATE PROCEDURE [dbo].[ccCaFeedBackViewDateUpdate]
(
    @Ids VARCHAR(200),
	@caMainID INT
)
AS
BEGIN TRY
	SET @Ids = dbo.FormatIDS(@Ids)
	DECLARE @T AS TABLE(ID INT)
	INSERT INTO @T SELECT * FROM dbo.fnSplit(@Ids, ',')

	UPDATE CaFeedBack SET ViewDate=GETDATE() WHERE ID IN(SELECT ID FROM @T) AND caMainID = @caMainID
    RETURN 1
END TRY
BEGIN CATCH
    RETURN 0
END CATCH














GO
/****** Object:  StoredProcedure [dbo].[ccCaFeePageViewLogInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--##########################################
--间隔1小时，记录一次点击事件
--##########################################
CREATE PROCEDURE [dbo].[ccCaFeePageViewLogInsert]
(
	@caMainID INT,
	@PageID INT
)
AS 
BEGIN
	IF NOT EXISTS(
			SELECT 'x' 
			FROM caFeePageViewLog WITH(NOLOCK)
			WHERE caMainID = @caMainID
			AND FeePageID = @PageID
			AND AddDate > DATEADD(HOUR, -1, GETDATE()))
		INSERT INTO caFeePageViewLog(caMainID, FeePageId)
		VALUES(@caMainID, @PageID)
	RETURN 1
END














GO
/****** Object:  StoredProcedure [dbo].[ccCaGetPasswordLogByMailSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--======================================
--一天之内一个账号不能查询超过5次
--一天之内一个ip不能超过20次
--======================================
CREATE PROCEDURE [dbo].[ccCaGetPasswordLogByMailSelect]
	@caMainID INT,
	@IP VARCHAR(31)
AS
BEGIN
	DECLARE @d AS DATETIME
	DECLARE @C AS INT
	SET @d = CONVERT(DATETIME,(FLOOR(CONVERT(FLOAT,GETDATE()))))

	SELECT @C = COUNT(1) FROM caGetPasswordLog WITH(NOLOCK) WHERE caMainID = @caMainID AND AddDate>=@d
	IF @c >4
		GOTO Err1
		
	SELECT @C = COUNT(1) FROM caGetPasswordLog WITH(NOLOCK) WHERE IP = @IP AND AddDate>=@d
	IF @c > 20
		GOTO Err2

	RETURN 1
END
Err1:
BEGIN
	RETURN -1
END
Err2:
BEGIN
	RETURN -2
END














GO
/****** Object:  StoredProcedure [dbo].[cccaGetPasswordLogByUniqueIDUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.30
--创建人：Nick
--说明：修改取回密碼的状态 重置密码成功后就修改一下状态（IsReset）
--#####################################################
CREATE PROCEDURE [dbo].[cccaGetPasswordLogByUniqueIDUpdate]
(
	@UniqueId VARCHAR(50)
)
AS
BEGIN TRY
	UPDATE caGetPasswordLog SET IsReset=1 
	WHERE AskNo=(SELECT TOP 1 AskNo FROM caGetPasswordLog WITH(NOLOCK) WHERE UniqueID = @UniqueId )
	RETURN 1
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[cccaGetPasswordLogSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.30
--创建人：Nick
--说明：获取企业取回密码记录
--#####################################################
CREATE PROCEDURE [dbo].[cccaGetPasswordLogSelect]
(
	@UniqueType VARCHAR(10),
	@UniqueId VARCHAR(50)
)
AS
BEGIN TRY
	IF @UniqueType = '1'
	BEGIN
		SELECT * FROM caGetPasswordLog WITH(NOLOCK) 
		WHERE UniqueID = @UniqueId AND AddDate > DATEADD(MINUTE, -60, GETDATE()) AND IsReset IS NULL
	END
	ELSE 
	BEGIN
		SELECT * FROM caGetPasswordLog WITH(NOLOCK) 
		WHERE askNo = @UniqueId AND AddDate > DATEADD(MINUTE, -60, GETDATE()) AND IsReset IS NULL 
	END
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[cccaGetsecondPasswordLogSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.30
--创建人：Nick
--说明：验证激活码
--#####################################################
CREATE PROCEDURE [dbo].[cccaGetsecondPasswordLogSelect]
(
	@caSafePasswordUniqueId VARCHAR(50)
)
AS
BEGIN TRY
	SELECT TOP 10 * 
	FROM caGetsecondPasswordLog WITH(NOLOCK) 
	WHERE UniqueId = @caSafePasswordUniqueId  
	AND IsReset is null
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[ccCaInterviewTemplateByCaMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ccCaInterviewTemplateByCaMainIDSelect]
    @caMainID INT
AS
BEGIN
	SELECT
        ID,
		Title,
        InterviewDate,
        InterViewPlace,
        LinkMan,
        Telephone,
        Remark,
        AddDate
    FROM CaInterviewTemplate WITH(NOLOCK)
    WHERE caMainID = @caMainID
END














GO
/****** Object:  StoredProcedure [dbo].[ccCaInterviewTemplateDelete]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--Lambo 20101130 修改
--增加cpMainID参数，判断是否是本企业的
CREATE PROCEDURE [dbo].[ccCaInterviewTemplateDelete]
	@ID INT,
	@cpMainID INT
AS
		BEGIN
			DELETE FROM CaInterviewTemplate 
				WHERE ID=@ID 
				AND caMainID IN
					(SELECT ID FROM caMain WITH(NOLOCK) WHERE cpMainID = @cpMainID)
		END














GO
/****** Object:  StoredProcedure [dbo].[ccCaInterviewTemplateSave]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--Lambo 20101130 修改
--update语句后面增加本账户的条件

CREATE PROCEDURE [dbo].[ccCaInterviewTemplateSave]
	@ID INT,
	@caMainID INT,
	@Title VARCHAR(20),
	@InterviewDate VARCHAR(100),
	@InterViewPlace VARCHAR(200),
	@LinkMan VARCHAR(12),
	@Telephone VARCHAR(20),
	@Remark VARCHAR(1000)
AS
DECLARE @MaxID AS INT
BEGIN TRY
	IF @ID > 0	
		BEGIN
			UPDATE CaInterviewTemplate SET
				Title=@Title,
				InterviewDate = @InterviewDate,
				InterViewPlace = @InterViewPlace,
				LinkMan = @LinkMan,
				Telephone = @Telephone,
				Remark = @Remark,
				AddDate = GETDATE()
			WHERE ID=@ID
			AND caMainID IN (SELECT caMainID FROM caMain WITH(NOLOCK) WHERE cpMainID = (SELECT cpMainID FROM caMain WITH(NOLOCK) WHERE ID = @caMainID))
			SET @MaxID = @ID
		END
	ELSE
		BEGIN
			INSERT INTO CaInterviewTemplate
				(caMainID,Title,InterviewDate,InterViewPlace,LinkMan,Telephone,Remark)
				VALUES(@caMainID,@Title,@InterviewDate,@InterViewPlace,@LinkMan,@Telephone,@Remark)
			SET @MaxID=@@IDENTITY
		END
END TRY
BEGIN CATCH
	GOTO ERR
END CATCH
RETURN @MaxID
ERR:
BEGIN
	RETURN 0
END














GO
/****** Object:  StoredProcedure [dbo].[ccCaInterviewTemplateSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[ccCaInterviewTemplateSelect]
    @ID INT
AS
BEGIN
	SELECT
		Title,
        caMainID,
        InterviewDate,
        InterViewPlace,
        LinkMan,
        Telephone,
        Remark,
        AddDate
    FROM CaInterviewTemplate WITH(NOLOCK)
    WHERE ID = @ID
END














GO
/****** Object:  StoredProcedure [dbo].[cccaJobCvMatchSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
---------------
--创建人Peter
--时间 2016-10-17
--根据职位ID获取推荐简历
CREATE PROCEDURE [dbo].[cccaJobCvMatchSelect]
(
	@JobID INT, 
	@caMainId INT
)
AS
SET NOCOUNT ON
INSERT INTO ProcLog SELECT 'cccaJobCvMatchSelect', @JobId, GETDATE()
BEGIN
	DECLARE @T_CvList AS TABLE(
		ID INT, 
		cvEducationID INT, 
		dcMajorID INT, 
		Degree TINYINT, 
		RelatedWorkYears INT, 
		dcSalaryID TINYINT, 
		Speciality VARCHAR(MAX) COLLATE Chinese_PRC_CI_AS, 
		RefreshDate SMALLDATETIME, 
		LastLoginDate SMALLDATETIME, 
		JobName VARCHAR(100) COLLATE Chinese_PRC_CI_AS, 
		Gender BIT, 
		BirthDay INT, 
		LivePlace INT, 
		Attachment VARCHAR(50) COLLATE Chinese_PRC_CI_AS, 
		HasPhoto TINYINT, 
		College NVARCHAR(50), 
		EduType TINYINT, 
		MajorName NVARCHAR(20), 
		Graduation INT, 
		HasViewed BIT, 
		ViewDate SMALLDATETIME, 
		HasRemarked BIT, 
		LastJobTypeID INT, 
		Valid TINYINT, 
		IsOnline BIT, 
		HasWeiXin BIT, 
		JobRecommendDate SMALLDATETIME,
		JobId INT,
		BelongJobName NVARCHAR(50),
		paMainId INT,
		SecondId VARCHAR(10)
	)
	
	IF(@caMainId > 0)
	BEGIN
		INSERT INTO @T_CvList(ID, dcMajorID, Degree, RelatedWorkYears, dcSalaryID, Speciality, 
			RefreshDate, LastLoginDate, JobName, Gender, BirthDay, LivePlace, LastJobTypeID, Attachment,
			HasPhoto, HasViewed, HasRemarked, Valid, IsOnline, JobRecommendDate, JobId, paMainId, SecondId)
		SELECT a.ID, a.dcMajorID, a.Degree, a.RelatedWorkYears, a.dcSalaryID, ISNULL(a.Speciality, a.SpecialityEng) Speciality,
			a.RefreshDate, j.LastLoginDate, ISNULL(a.JobName, '应届毕业生') JobName, j.Gender, j.BirthDay, j.LivePlace, a.LastJobTypeID, a.Attachment,
			j.HasPhoto, 0, 0, a.Valid, dbo.GetPaOnlineStatus(j.ID), b.AddDate, b.JobId, a.paMainId, a.SecondId
		FROM cvMainPublish a WITH(NOLOCK) 
		INNER JOIN paMainPublish j WITH(NOLOCK) ON a.paMainID = j.ID 
		INNER JOIN caJobCvMatch b ON a.id = b.MatchcvMainID
		WHERE b.JobID IN(SELECT Id FROM JobPublish WITH(NOLOCK) WHERE caMainId = @caMainId AND Valid = 1) 
		ORDER BY b.ID DESC
	END
	ELSE
	BEGIN
		INSERT INTO @T_CvList(ID, dcMajorID, Degree, RelatedWorkYears, dcSalaryID, Speciality,
			RefreshDate, LastLoginDate, JobName, Gender, BirthDay, LivePlace, LastJobTypeID, 
			Attachment, HasPhoto, HasViewed, HasRemarked, Valid, IsOnline, JobRecommendDate, JobId, paMainId, SecondId)
		SELECT a.ID, a.dcMajorID, a.Degree, a.RelatedWorkYears, a.dcSalaryID, ISNULL(a.Speciality, a.SpecialityEng) Speciality,
			a.RefreshDate, j.LastLoginDate, ISNULL(a.JobName, '应届毕业生') JobName, j.Gender, j.BirthDay, j.LivePlace, a.LastJobTypeID, 
			a.Attachment, j.HasPhoto, 0, 0, a.Valid, dbo.GetPaOnlineStatus(j.ID), b.AddDate, b.JobId, a.paMainId, a.SecondId
		FROM cvMainPublish a WITH(NOLOCK) 
		INNER JOIN paMainPublish j WITH(NOLOCK) ON a.paMainID = j.ID 
		INNER JOIN caJobCvMatch b ON a.id = b.MatchcvMainID
		WHERE b.JobID = @JobID
		ORDER BY b.ID DESC
	END

	UPDATE a SET a.cvEducationID = (
		SELECT TOP 1 ID FROM cvEducationPublish WITH(NOLOCK)
		WHERE cvEducationPublish.cvMainID = a.ID
		AND a.Degree = cvEducationPublish.Degree
		ORDER BY Graduation DESC)
	FROM @T_CvList a

	UPDATE a SET a.College = ISNULL(b.GraduateCollage, b.GraduateCollageEng), a.EduType = b.EduType, 
		a.MajorName = ISNULL(b.MajorName, b.MajorNameEng), a.Graduation = b.Graduation
	FROM @T_CvList a, cvEducationPublish b WITH(NOLOCK)
	WHERE b.ID = a.cvEducationID

	--修改是否绑定微信
	UPDATE a SET HasWeiXin = 1
	FROM @T_CvList a, WxFans b WITH(NOLOCK), cvMainPublish c WITH(NOLOCK)
	WHERE a.ID = c.ID
	AND c.PaMainID = b.PaMainID
	AND b.Status = 2

	IF(ISNULL(@caMainId, 0) = 0)
		SELECT @caMainID = caMainID FROM JobPublish WITH(NOLOCK) WHERE ID = @JobID

	UPDATE a SET a.HasViewed = 1, a.ViewDate = b.AddDate
	FROM @T_CvList a, caCvViewLog b WITH(NOLOCK)
	WHERE b.cvMainID = a.ID AND caMainID = @caMainID	

	UPDATE @T_CvList SET BelongJobName = (SELECT Name FROM Job WHERE Id = JobId)

	SELECT * FROM @T_CvList ORDER BY JobRecommendDate DESC
END
GO
/****** Object:  StoredProcedure [dbo].[cccaJobCvMatchSelect2]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
---------------
--创建人Peter
--时间 2016-10-17
--根据职位ID获取推荐简历
CREATE PROCEDURE [dbo].[cccaJobCvMatchSelect2]
(
	@JobID INT, 
	@caMainId INT
)
AS
SET NOCOUNT ON
INSERT INTO ProcLog SELECT 'cccaJobCvMatchSelect2', @JobId, GETDATE()
BEGIN
	DECLARE @T_CvList AS TABLE(
		ID INT, 
		cvEducationID INT, 
		dcMajorID INT, 
		Degree TINYINT, 
		RelatedWorkYears INT, 
		dcSalaryID TINYINT, 
		Speciality VARCHAR(MAX) COLLATE Chinese_PRC_CI_AS, 
		RefreshDate SMALLDATETIME, 
		LastLoginDate SMALLDATETIME, 
		JobName VARCHAR(100) COLLATE Chinese_PRC_CI_AS, 
		Gender BIT, 
		BirthDay INT, 
		LivePlace INT, 
		Attachment VARCHAR(50) COLLATE Chinese_PRC_CI_AS, 
		HasPhoto TINYINT, 
		College NVARCHAR(50), 
		EduType TINYINT, 
		MajorName NVARCHAR(20), 
		Graduation INT, 
		HasViewed BIT, 
		ViewDate SMALLDATETIME, 
		HasRemarked BIT, 
		LastJobTypeID INT, 
		Valid TINYINT, 
		IsOnline BIT, 
		HasWeiXin BIT, 
		JobRecommendDate SMALLDATETIME,
		JobId INT,
		BelongJobName NVARCHAR(50),
		paMainId INT,
		SecondId VARCHAR(10)
	)
	
	IF(@caMainId > 0)
	BEGIN
		INSERT INTO @T_CvList(ID, dcMajorID, Degree, RelatedWorkYears, dcSalaryID, Speciality, 
			RefreshDate, LastLoginDate, JobName, Gender, BirthDay, LivePlace, LastJobTypeID, Attachment,
			HasPhoto, HasViewed, HasRemarked, Valid, IsOnline, JobRecommendDate, JobId, paMainId, SecondId)
		SELECT a.ID, a.dcMajorID, a.Degree, a.RelatedWorkYears, a.dcSalaryID, ISNULL(a.Speciality, a.SpecialityEng) Speciality,
			a.RefreshDate, j.LastLoginDate, ISNULL(a.JobName, '应届毕业生') JobName, j.Gender, j.BirthDay, j.LivePlace, a.LastJobTypeID, a.Attachment,
			j.HasPhoto, 0, 0, a.Valid, dbo.GetPaOnlineStatus(j.ID), b.AddDate, b.JobId, a.paMainId, a.SecondId
		FROM cvMainPublish a WITH(NOLOCK) 
		INNER JOIN paMainPublish j WITH(NOLOCK) ON a.paMainID = j.ID 
		INNER JOIN caJobCvMatch b ON a.id = b.MatchcvMainID
		WHERE b.JobID IN(SELECT Id FROM JobPublish WITH(NOLOCK) WHERE caMainId = @caMainId AND Valid = 1) 
		ORDER BY b.ID DESC
	END
	ELSE
	BEGIN
		INSERT INTO @T_CvList(ID, dcMajorID, Degree, RelatedWorkYears, dcSalaryID, Speciality,
			RefreshDate, LastLoginDate, JobName, Gender, BirthDay, LivePlace, LastJobTypeID, 
			Attachment, HasPhoto, HasViewed, HasRemarked, Valid, IsOnline, JobRecommendDate, JobId, paMainId, SecondId)
		SELECT a.ID, a.dcMajorID, a.Degree, a.RelatedWorkYears, a.dcSalaryID, ISNULL(a.Speciality, a.SpecialityEng) Speciality,
			a.RefreshDate, j.LastLoginDate, ISNULL(a.JobName, '应届毕业生') JobName, j.Gender, j.BirthDay, j.LivePlace, a.LastJobTypeID, 
			a.Attachment, j.HasPhoto, 0, 0, a.Valid, dbo.GetPaOnlineStatus(j.ID), b.AddDate, b.JobId, a.paMainId, a.SecondId
		FROM cvMainPublish a WITH(NOLOCK) 
		INNER JOIN paMainPublish j WITH(NOLOCK) ON a.paMainID = j.ID 
		INNER JOIN caJobCvMatch b ON a.id = b.MatchcvMainID
		WHERE b.JobID = @JobID
		ORDER BY b.ID DESC
	END

	UPDATE a SET a.cvEducationID = (
		SELECT TOP 1 ID FROM cvEducationPublish WITH(NOLOCK)
		WHERE cvEducationPublish.cvMainID = a.ID
		AND a.Degree = cvEducationPublish.Degree
		ORDER BY Graduation DESC)
	FROM @T_CvList a

	UPDATE a SET a.College = ISNULL(b.GraduateCollage, b.GraduateCollageEng), a.EduType = b.EduType, 
		a.MajorName = ISNULL(b.MajorName, b.MajorNameEng), a.Graduation = b.Graduation
	FROM @T_CvList a, cvEducationPublish b WITH(NOLOCK)
	WHERE b.ID = a.cvEducationID

	--修改是否绑定微信
	UPDATE a SET HasWeiXin = 1
	FROM @T_CvList a, WxFans b WITH(NOLOCK), cvMainPublish c WITH(NOLOCK)
	WHERE a.ID = c.ID
	AND c.PaMainID = b.PaMainID
	AND b.Status = 2

	IF(ISNULL(@caMainId, 0) = 0)
		SELECT @caMainID = caMainID FROM JobPublish WITH(NOLOCK) WHERE ID = @JobID

	UPDATE a SET a.HasViewed = 1, a.ViewDate = b.AddDate
	FROM @T_CvList a, caCvViewLog b WITH(NOLOCK)
	WHERE b.cvMainID = a.ID AND caMainID = @caMainID	

	UPDATE @T_CvList SET BelongJobName = (SELECT Name FROM Job WHERE Id = JobId)

	SELECT * FROM @T_CvList
END
GO
/****** Object:  StoredProcedure [dbo].[ccCaJobRefreshLogSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--创建人harry
--2017-11-7
--获取职位刷新数记录
CREATE PROCEDURE [dbo].[ccCaJobRefreshLogSelect]
(
	@cpMainID INT,
	@orderID INT
)
AS
SET NOCOUNT ON
BEGIN
	IF @orderID > 0
	BEGIN
		SELECT a.*, b.Name
		FROM jobRefreshLog a WITH(NOLOCK)  
		LEFT JOIN caMain b WITH(NOLOCK) ON a.operateMan = b.Id
		WHERE a.orderId = @orderID
		AND a.runDateTime is NOT NULL
		ORDER BY a.runDateTime DESC
	END 
	ELSE
	BEGIN
		SELECT a.*, b.Name
		FROM jobRefreshLog a WITH(NOLOCK)  
		LEFT JOIN caMain b WITH(NOLOCK) ON a.operateMan = b.Id
		WHERE a.orderId IN(SELECT ID FROM caOrder WHERE cpMainID = @cpMainID AND orderType IN(8,15))
		AND a.runDateTime is NOT NULL
		ORDER by a.runDateTime DESC
	END	 
END
SET NOCOUNT OFF

GO
/****** Object:  StoredProcedure [dbo].[ccCaLoginLogByAutoInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[ccCaLoginLogByAutoInsert]
(
	@caMainID INT,	
	@cpMainName NVARCHAR(60),
	@caMainName NVARCHAR(12),
	@LoginIP VARCHAR(15),
	@Browser VARCHAR(500)
)
AS
--insert proclog select 'ccCaLoginLogByAutoInsert', @caMainID, getdate()
BEGIN
	DECLARE @ID AS INT
	IF NOT EXISTS(SELECT 'X' FROM caLoginLog WITH(NOLOCK)
		WHERE caMainID = @caMainID 
		AND ADDDATE > CONVERT(VARCHAR(10), GETDATE(), 120))
	BEGIN
		INSERT INTO caLoginLog(caMainID, cpMainName, caMainName, LoginIP, AddDate, Browser, LoginFrom, LoginCookies)
		VALUES(@caMainID, @cpMainName, @caMainName, @LoginIP, GETDATE(), @Browser, 0, 'mblAutoLogin')
		SET @ID = @@IDENTITY
	END
	ELSE
		SET @ID = 0
	RETURN @ID
END




GO
/****** Object:  StoredProcedure [dbo].[ccCaLoginLogByCaLastLoginDateSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--Lambo 20110211
--查询企业用户的上次登陆时间
CREATE PROCEDURE [dbo].[ccCaLoginLogByCaLastLoginDateSelect]
(
    @caMainID INT
)
AS
BEGIN
--	DECLARE @AddDate AS SMALLDATETIME
--    SELECT TOP 1 @AddDate = AddDate
--	FROM caLoginLog WITH(NOLOCK) WHERE caMainID = @caMainID
--	ORDER BY ID DESC
--
--	IF @AddDate IS NULL
--		SELECT @AddDate = RegDate FROM caMain WITH(NOLOCK) WHERE Id = @caMainId
--
--	SELECT @AddDate AddDate
	DECLARE @t AS TABLE(Id INT, AddDate SMALLDATETIME)
 
	INSERT INTO @t
	SELECT TOP 2 Id, AddDate
	FROM caLoginLog WITH(NOLOCK)
	WHERE caMainID = @caMainID
	AND AddDate > DATEADD(MINUTE, -240, GETDATE())
	ORDER BY ID DESC

	IF @@ROWCOUNT = 0
		INSERT @t SELECT 1, GETDATE()

	SELECT * FROM @t ORDER BY ID DESC
END


GO
/****** Object:  StoredProcedure [dbo].[ccCaLoginLogByCpMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----------------------
--修改人：Lucifer
--修改时间：2010-9-27
--修改内容：增加了LoginCookies字段，后台的CompanyLoginLog中用到
-----------------------
CREATE PROCEDURE [dbo].[ccCaLoginLogByCpMainIDSelect]
(
    @cpMainID INT
)
AS
BEGIN
    SELECT TOP 200
        a.ID,
        a.caMainID,
        a.cpMainName,
        a.caMainName,
        a.LoginIP,
		a.browser,
        a.AddDate,
		b.cpMainID,
		a.LoginCookies
    FROM caLoginLog a WITH(NOLOCK), caMain b WITH(NOLOCK)
    WHERE a.caMainID = b.ID
	AND b.cpMainID = @cpMainID
	AND b.IsDelete=0
	ORDER BY a.ID DESC
END














GO
/****** Object:  StoredProcedure [dbo].[ccCaLoginLogByIndexSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--创建：sean 用于用户登陆信息，index.asp页面显示
--本日登陆次数和上次登录信息
--修改：显示上次登录信息错误harry2017-4-19
--#########################333
CREATE PROCEDURE [dbo].[ccCaLoginLogByIndexSelect]
(
	@caMainID INT
)
AS
SET NOCOUNT ON
BEGIN
	DECLARE @TodayLoginNumber AS TINYINT
	DECLARE @LoginIP AS VARCHAR(31)
	DECLARE @AddDate AS SMALLDATETIME

	SELECT @TodayLoginNumber = COUNT(1) FROM CaLoginLog WITH(NOLOCK)
	WHERE caMainID = @caMainID
	AND AddDate > CONVERT(VARCHAR(10), GETDATE(), 120)	
	
	SELECT TOP 1 @LoginIP = LoginIP, @AddDate = AddDate
	FROM (
		SELECT TOP 2 LoginIP, AddDate, ROW_NUMBER() OVER (ORDER BY ID DESC) AS RowNumber FROM caLoginLog WITH(NOLOCK)
		WHERE caMainId = @caMainID
		ORDER BY ID DESC) a
	WHERE RowNumber = 1

	IF ISNULL(@LoginIP, '') = ''
		SELECT TOP 1 @LoginIP = LoginIP, @AddDate = AddDate FROM caLoginLog WITH(NOLOCK) WHERE caMainID = @caMainID ORDER BY ID DESC

	SELECT @TodayLoginNumber AS TodayLoginNumber, @LoginIP AS LoginIP, @AddDate AS AddDate
END













 
GO
/****** Object:  StoredProcedure [dbo].[ccCaLoginLogInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[ccCaLoginLogInsert]
(
	@caMainID INT,	
	@cpMainName NVARCHAR(60),
	@caMainName NVARCHAR(12),
	@LoginIP VARCHAR(31)	
)
AS
insert proclog select 'ccCaLoginLogInsert', @caMainID, getdate()
BEGIN
	DECLARE @ID AS INT
	INSERT INTO caLoginLog(caMainID, cpMainName, caMainName, LoginIP, AddDate, Browser)
	VALUES(@caMainID, @cpMainName, @caMainName, @LoginIP, GETDATE(), '1:')
	SET @ID = @@IDENTITY
	RETURN @ID
END

GO
/****** Object:  StoredProcedure [dbo].[ccCaLoginLogSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[ccCaLoginLogSelect]
(
    @caMainID INT
)
AS
BEGIN
    SELECT TOP 100
        ID,
        caMainID,
        cpMainName,
        caMainName,
        LoginIP,
        AddDate
    FROM caLoginLog WITH(NOLOCK)
    WHERE caMainID = @caMainID
	ORDER BY ADDDATE DESC
END














GO
/****** Object:  StoredProcedure [dbo].[ccCaMainByBackLoginUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--***********************************************************
--返回值:
--  0:未定义错误
-- -1：用户名、密码不正确
-- -2：验证码不正确
-- 正整数:正确的ID
--后台登陆用
--Lambo 20101113修改
--后台需要查看用户浏览单位记录，所以将删除过期数据的sql注释掉了
--***********************************************************
CREATE PROCEDURE [dbo].[ccCaMainByBackLoginUpdate]
(
	@UID VARCHAR(20),
	@caMainID INT,
	@ProvinceID INT,
	@SessionID INT
)
AS
BEGIN TRY
	DECLARE @ID AS INT

	SELECT TOP 1 @ID = ID
	FROM BsCpBackLogin WITH(NOLOCK)
	WHERE UnqueID=@UID
	AND HasLogin = 0
	AND caMainID=@caMainID
	
	SELECT @ProvinceID = LEFT(@ProvinceID, 2)
	IF @ID IS NOT NULL
	BEGIN
		UPDATE BsCpBackLogin SET HasLogin = 1 WHERE ID = @ID
		DELETE FROM BsCpBackLogin WHERE AddDate < GETDATE()- 2

		IF EXISTS(SELECT 'X' FROM caMain a WITH(NOLOCK),cpMain b
					WHERE a.cpMainID = b.ID
					AND a.IsDelete = 0 
					AND b.IsDelete=0
					AND a.ID=@caMainID
					AND LEFT(b.dcProvinceID, 2) = @ProvinceID
				)
		BEGIN
			----单点登录，后台不考虑单点登录
			--DELETE FROM cpSession WHERE caMainID = @caMainID
			--INSERT INTO cpSession(SessionID, caMainID, IP) VALUES(@SessionID, @caMainID, '后台登陆')
			RETURN 1
		END
		ELSE
			RETURN 0		
	END
END TRY
BEGIN CATCH
	RETURN -1
END CATCH














GO
/****** Object:  StoredProcedure [dbo].[ccCaMainByCpMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ccCaMainByCpMainIDSelect]
    @cpMainID INT
AS
BEGIN
    SELECT *, (SELECT TOP 1 ID FROM paLoginContact WHERE paMainID = caMain.ID AND ContactType = 101) IsWeixinBind
    FROM caMain WITH(NOLOCK)
    WHERE cpMainID = @cpMainID AND IsDelete=0
	ORDER BY AccountType,IsPause
END
GO
/****** Object:  StoredProcedure [dbo].[ccCaMainByEMailExist]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--==================================
--企业邮箱是否重复
--检查：	sean	2010-10-22
--==================================
CREATE PROCEDURE [dbo].[ccCaMainByEMailExist]
(
	@EMail VARCHAR(50)
)
AS
SET NOCOUNT ON
BEGIN
	SET @EMail = LTRIM(RTRIM(@EMail))

	IF EXISTS(SELECT 'X' FROM Company_Black WITH(NOLOCK) WHERE Email = @Email AND LEN(@Email) > 6)
	BEGIN
		UPDATE Company_Black SET RefuseCount = RefuseCount + 1
		WHERE Email = @Email
		RETURN 2		--邮件在黑名单
	END
	
	IF EXISTS(SELECT 'x' FROM caMain a WITH(NOLOCK), cpMain b WITH(NOLOCK)
		WHERE (b.RegisterMode = 0 Or b.RegisterMode = 11)
		AND a.cpMainID = b.ID AND a.Email = @Email 
		AND b.Isdelete = 0 AND a.IsDelete = 0 AND a.AccountType = 1)
		RETURN 1

	RETURN 0
END

GO
/****** Object:  StoredProcedure [dbo].[ccCaMainByGetPasswordSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
---- =============================================
---- Author:		Sean
---- Create date: 2010-12-20
---- Description:	取回密码	先检查用户名是否在camain，Company_Xixni。如果没有结果则检查是否有邮箱
---- Update date: 2012-3-7
---- Description:	增加取回前检查取回纪录，取回后增加纪录；增加手机查询
---- =============================================
CREATE PROCEDURE [dbo].[ccCaMainByGetPasswordSelect]
(
	@Username VARCHAR(50), 
	@Email VARCHAR(50),
	@Mobile VARCHAR(11),
	@IP VARCHAR(15),
	@VerifyCode VARCHAR(10),
	@SubSiteName VARCHAR(30)
)
AS
BEGIN
	DECLARE @Cnt AS INT, @Type AS VARCHAR(10), @ToDay AS DATETIME, @QueryMobile AS INT
	----如果用户名、油箱、手机号都为空则返回
	IF LEN(ISNULL(@Username, '')) = 0 AND LEN(ISNULL(@Email, '')) = 0 AND LEN(ISNULL(@Mobile, '')) = 0
		GOTO Err3
	--SET @Mobile = ''
	DECLARE @t AS TABLE(
		ID INT,
		cpMainID INT,
		Name NVARCHAR(50) NOT NULL,
		UserName VARCHAR(50) NOT NULL,
		Email VARCHAR(50) NOT NULL,
		Gender NVARCHAR(10),
		ConsultantID SMALLINT,
		ConsultantName NVARCHAR(10),
		ConsultantEmail VARCHAR(50),
		Mobile VARCHAR(13),
		ReturnType VARCHAR(10),
		UniqueId VARCHAR(40),
		ActivateCode VARCHAR(6),
		AskNo VARCHAR(40)
	)

	SELECT @Type = 'Email', @QueryMobile = 0

	IF dbo.IsMobile(@Mobile) = 1	----手机号是否合法
	BEGIN
		SET @QueryMobile = 1		----手机号合法,则优先使用手机查询
		----一周内手机取回密码次数
		SELECT @Cnt = COUNT(DISTINCT AskNo) FROM caGetPasswordLog WITH(NOLOCK) WHERE Mobile = @Mobile AND AddDate > GETDATE() - 1
		IF @Cnt >= 3					----总数=0，按手机号取回
			GOTO Err4
		SET @Type = 'Mobile'
	END

	IF @Type = 'Email'				----按油箱、用户名取回
	BEGIN
		SET @ToDay = CONVERT(DATETIME, CONVERT(VARCHAR(8), GETDATE(), 112))
		IF @QueryMobile = 1
		BEGIN
			----一天之内手机号至多查询5次
			SELECT @Cnt = COUNT(1) FROM caGetPasswordLog WITH(NOLOCK) WHERE Mobile = @Mobile AND AddDate > @Today
			IF @Cnt > 4								----一天之内一个手机号最多取回5次
				GOTO Err1
		END
		ELSE
		BEGIN
			IF LEN(ISNULL(@Username, '')) > 0		----用户名优先
			BEGIN
				SELECT @Cnt = COUNT(1) FROM caGetPasswordLog WITH(NOLOCK) WHERE Username = @Username AND AddDate > @Today
				SET @Type = 'Username'
			END
			ELSE									----其次Email
				SELECT @Cnt = COUNT(1) FROM caGetPasswordLog WITH(NOLOCK) WHERE Email = @Email AND AddDate > @Today
			IF @Cnt > 4								----一天之内一个账号最多取回5次
				GOTO Err1
		END

		SELECT @Cnt = COUNT(1) FROM caGetPasswordLog WITH(NOLOCK) WHERE IP = @IP AND AddDate >= @Today
		IF @Cnt > 20							----一天之内一个ip不能超过20次
			GOTO Err2
	END

	SELECT @Cnt = 0
	IF @QueryMobile = 1							----按照手机号查询
	BEGIN
		INSERT INTO @t(ID, cpMainId, Name, UserName, Email, Gender, Mobile)
		SELECT TOP 10  ID, cpMainId, ISNULL(Name, ''), Username, Email, Gender, Mobile
		FROM caMain WITH(NOLOCK INDEX(IX_caMain_Mobile))
		WHERE Mobile = @Mobile
		ORDER BY (SELECT MAX(AddDate) FROM caLoginLog WITH(NOLOCK) WHERE caMainID = caMain.ID) DESC

		IF (SELECT COUNT(*) FROM @t) = 0		----有值则返回
			GOTO Err3
	END
	ELSE IF LEN(ISNULL(@Username, '')) > 0		----如果有用户名则以用户名为主
	BEGIN
		SET @Type = 'Username'
		----caMain.UserName = @UserName 区分大小写
		INSERT INTO @t(ID, cpMainId, Name, UserName, Email, Gender, Mobile)
		SELECT ID, cpMainId, ISNULL(Name, ''), Username, Email, Gender, Mobile
		FROM caMain WITH(NOLOCK INDEX(IX_caMain_UserName))
		WHERE Username = @UserName
		
		IF (SELECT COUNT(*) FROM @t) = 1		----有值则返回
			GOTO Retu

		----无值,不区分大小写
		----caMain.UserNameLower = @UserName
		INSERT INTO @t(ID, cpMainId, Name, UserName, Email, Gender, Mobile)
		SELECT  ID, cpMainId, ISNULL(Name, ''), Username, Email, Gender, Mobile
		FROM caMain WITH(NOLOCK INDEX(IX_caMain_UserNameLower))
		WHERE UsernameLower = @UserName
		
		IF (SELECT COUNT(*) FROM @t) > 0		----有值则返回
			GOTO Retu
	
		----无值,再查询Company_Xinxi 区分大小写
		INSERT INTO @t(ID, Name, UserName, Email, Gender, Mobile)
		SELECT 0 ID, Username, Username, Email,NULL, NULL
		FROM Company_Xinxi WITH(NOLOCK INDEX(IX_Company_Xinxi_UserName))
		WHERE UserName = @Username

		IF (SELECT COUNT(*) FROM @t) = 1		----有一个则返回
			GOTO Retu

		----不区分大小写
		INSERT INTO @t(ID, Name, UserName, Email, Gender, Mobile)
		SELECT 0 ID, Username, Username, Email, NULL, NULL
		FROM Company_Xinxi WITH(NOLOCK INDEX(IX_Company_Xinxi_UserNameLower)) 
		WHERE UserNameLower = @Username

		IF (SELECT COUNT(*) FROM @t) > 0
			GOTO Retu		----有值返回结果
		ELSE
			GOTO Err3		----无值返回而Error
	END
	ELSE IF LEN(ISNULL(@Email, '')) > 0		----查询caMain.Email
	BEGIN
		INSERT INTO @t(ID, cpMainId, Name, UserName, Email, Gender, Mobile)
		SELECT TOP 10  ID, cpMainId, ISNULL(Name, ''), Username, Email, Gender, Mobile
		FROM caMain WITH(NOLOCK INDEX(IX_caMain_Email))
		WHERE Email = @Email
		ORDER BY (SELECT MAX(AddDate) FROM caLoginLog WITH(NOLOCK) WHERE caMainID = caMain.ID) DESC
/*
		IF (SELECT COUNT(*) FROM @t) > 0		----有值则返回
			GOTO Retu
*/		
		INSERT INTO @t(ID, Name, UserName, Email)
		SELECT TOP 10  0 ID, Username Name, Username, Email
		FROM Company_Xinxi WITH(NOLOCK INDEX(IX_Company_Xinxi_Email)) 
		WHERE Email = @Email
		ORDER BY ID DESC

		IF (SELECT COUNT(*) FROM @t) > 0
			GOTO Retu		----有值返回结果
		ELSE
			GOTO Err3		----无值返回而Error
	END
END
Retu:	----正确返回，有数据
BEGIN
	--获取随机数,激活码
	DECLARE @Rnd AS INT,@AskNo AS VARCHAR(60)
	SELECT @Rnd = RAND() * 899999 + 100000,@AskNo=REPLACE(NEWID(), '-', '')
	
	UPDATE @t SET ReturnType = @Type, AskNo=@AskNo, ActivateCode = RAND() * 899999 + 100000,UniqueId=REPLACE(NEWID(), '-', '')		----修改返回类型，用于前台显示结果

	----记录取回纪录
	INSERT INTO caGetPasswordLog(caMainID, UserNameIn, EmailIn, VerifyCode, IP, UserName, Email, Mobile, UniqueId, ActivateCode, AskNo )
	SELECT ID, @UserName, @Email, @VerifyCode, @IP, UserName, Email, @Mobile, UniqueId,ActivateCode ,AskNo FROM @t

	UPDATE a SET a.ConsultantName = (SELECT Name FROM ManagerUser WITH(NOLOCK) WHERE ManagerUser.ID = b.consultantID),
		a.ConsultantEmail = (SELECT EMail FROM ManagerUser WITH(NOLOCK) WHERE ManagerUser.ID = b.consultantID)
	FROM @t a, cpMain b WITH(NOLOCK)
	WHERE a.cpMainId = b.Id

	IF @Type = 'Mobile' 
	BEGIN
		INSERT SmsMessageLog(SendMan, ManagerUSerId, paMainId, caMainId, Mobile, MsgType, IsCat, Msg)
		SELECT TOP 1 0, NULL, NULL, a.ID, a.Mobile, 9, 0, 
			'您好，您在' + @SubSiteName  + '的激活码是：' + d.ActivateCode
		FROM caMain a WITH(NOLOCK), cpMain b WITH(NOLOCK), (SELECT TOP 1 ID, ActivateCode FROM @t ORDER BY ID DESC) d
		WHERE a.cpMainID = b.ID
		AND a.ID = d.Id
		AND a.Mobile > ''
		ORDER BY ID DESC
	END

	SELECT * FROM @t ORDER BY ID DESC
	RETURN
END
Err1:	----一个账号一天取回超过5次
BEGIN
	SELECT null ID, NULL Name, NULL Username, NULL Email, NULL Gender, NULL Mobile, 1 ReturnType
	RETURN
END
Err2:	----一个ip一天取回超过20次
BEGIN
	SELECT null ID, NULL Name, NULL Username, NULL Email, NULL Gender, NULL Mobile, 2 ReturnType
	RETURN
END
Err3:	----没有取回数据
BEGIN
	SELECT null ID, NULL Name, NULL Username, NULL Email, NULL Gender, NULL Mobile, 3 ReturnType
	RETURN
END
Err4:	----手机号一天取回超过3次
BEGIN
	SELECT null ID, NULL Name, NULL Username, NULL Email, NULL Gender, NULL Mobile, 4 ReturnType
	RETURN
END














GO
/****** Object:  StoredProcedure [dbo].[ccCaMainByGetPasswordSelect1]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
---- =============================================
---- Author:		Sean
---- Create date: 2010-12-20
---- Description:	取回密码	先检查用户名是否在camain，Company_Xixni。如果没有结果则检查是否有邮箱
---- Update date: 2012-3-7
---- Description:	增加取回前检查取回纪录，取回后增加纪录；增加手机查询
---- 修改harry 2018-4-27
---- 修改短信为实时发送
---- 修改alen 2018-9-18
---- 用户名为手机号的先检查手机号，没有在检查用户名。
---- =============================================
CREATE PROCEDURE [dbo].[ccCaMainByGetPasswordSelect1]
(
	@Username VARCHAR(50), 
	@Email VARCHAR(50),
	@Mobile VARCHAR(11),
	@IP VARCHAR(15),
	@VerifyCode VARCHAR(10),
	@SubSiteName VARCHAR(30)
)
AS
BEGIN
	DECLARE @Cnt AS INT, @Type AS VARCHAR(10), @ToDay AS DATETIME, @QueryMobile AS INT
	----如果用户名、油箱、手机号都为空则返回
	IF LEN(ISNULL(@Username, '')) = 0 AND LEN(ISNULL(@Email, '')) = 0 AND LEN(ISNULL(@Mobile, '')) = 0
		GOTO Err3
	--SET @Mobile = ''
	DECLARE @t AS TABLE(
		ID INT,
		cpMainID INT,
		Name NVARCHAR(50) NOT NULL,
		UserName VARCHAR(50) NOT NULL,
		Email VARCHAR(50) NOT NULL,
		Gender NVARCHAR(10),
		ConsultantID SMALLINT,
		ConsultantName NVARCHAR(10),
		ConsultantEmail VARCHAR(50),
		Mobile VARCHAR(13),
		ReturnType VARCHAR(10),
		UniqueId VARCHAR(40),
		ActivateCode VARCHAR(6),
		AskNo VARCHAR(40)
	)

	SELECT @Type = 'Email', @QueryMobile = 0

	IF dbo.IsMobile(@Mobile) = 1	----手机号是否合法
	BEGIN
		SET @QueryMobile = 1		----手机号合法,则优先使用手机查询
		----一周内手机取回密码次数
		SELECT @Cnt = COUNT(DISTINCT AskNo) FROM caGetPasswordLog WITH(NOLOCK) WHERE Mobile = @Mobile AND AddDate > GETDATE() - 1
		IF @Cnt >= 3					----总数=0，按手机号取回
			GOTO Err4
		SET @Type = 'Mobile'
	END

	IF @Type = 'Email'				----按油箱、用户名取回
	BEGIN
		SET @ToDay = CONVERT(DATETIME, CONVERT(VARCHAR(8), GETDATE(), 112))
		IF @QueryMobile = 1
		BEGIN
			----一天之内手机号至多查询5次
			SELECT @Cnt = COUNT(1) FROM caGetPasswordLog WITH(NOLOCK) WHERE Mobile = @Mobile AND AddDate > @Today
			IF @Cnt > 4								----一天之内一个手机号最多取回5次
				GOTO Err1
		END
		ELSE
		BEGIN
			IF LEN(ISNULL(@Username, '')) > 0		----用户名优先
			BEGIN
				SELECT @Cnt = COUNT(1) FROM caGetPasswordLog WITH(NOLOCK) WHERE Username = @Username AND AddDate > @Today
				SET @Type = 'Username'
			END
			ELSE									----其次Email
				SELECT @Cnt = COUNT(1) FROM caGetPasswordLog WITH(NOLOCK) WHERE Email = @Email AND AddDate > @Today
			IF @Cnt > 4								----一天之内一个账号最多取回5次
				GOTO Err1
		END

		SELECT @Cnt = COUNT(1) FROM caGetPasswordLog WITH(NOLOCK) WHERE IP = @IP AND AddDate >= @Today
		IF @Cnt > 20							----一天之内一个ip不能超过20次
			GOTO Err2
	END

	SELECT @Cnt = 0
	IF @QueryMobile = 1							----按照手机号查询
	BEGIN
		INSERT INTO @t(ID, cpMainId, Name, UserName, Email, Gender, Mobile)
		SELECT TOP 10  ID, cpMainId, ISNULL(Name, ''), Username, Email, Gender, Mobile
		FROM caMain WITH(NOLOCK INDEX(IX_caMain_Mobile))
		WHERE Mobile = @Mobile
		ORDER BY (SELECT MAX(AddDate) FROM caLoginLog WITH(NOLOCK) WHERE caMainID = caMain.ID) DESC

		IF (SELECT COUNT(*) FROM @t) > 0		----有值则返回
			GOTO Retu
		ELSE									----手机号查询不到按照用户名查询
		BEGIN
			INSERT INTO @t(ID, cpMainId, Name, UserName, Email, Gender, Mobile)
			SELECT ID, cpMainId, ISNULL(Name, ''), Username, Email, Gender, Mobile
			FROM caMain WITH(NOLOCK INDEX(IX_caMain_UserName))
			WHERE Username = @Mobile

			IF (SELECT COUNT(*) FROM @t) > 0		----有值则返回
			BEGIN
				SET @Mobile = (SELECT TOP 1 Mobile FROM @t)
				GOTO Retu
			END
			ELSE
				GOTO Err3							----无值返回而Error
		END

	END
	ELSE IF LEN(ISNULL(@Username, '')) > 0		----如果有用户名则以用户名为主
	BEGIN
		SET @Type = 'Username'
		----caMain.UserName = @UserName 区分大小写
		INSERT INTO @t(ID, cpMainId, Name, UserName, Email, Gender, Mobile)
		SELECT ID, cpMainId, ISNULL(Name, ''), Username, Email, Gender, Mobile
		FROM caMain WITH(NOLOCK INDEX(IX_caMain_UserName))
		WHERE Username = @UserName
		
		IF (SELECT COUNT(*) FROM @t) = 1		----有值则返回
			GOTO Retu

		----无值,不区分大小写
		----caMain.UserNameLower = @UserName
		INSERT INTO @t(ID, cpMainId, Name, UserName, Email, Gender, Mobile)
		SELECT  ID, cpMainId, ISNULL(Name, ''), Username, Email, Gender, Mobile
		FROM caMain WITH(NOLOCK INDEX(IX_caMain_UserNameLower))
		WHERE UsernameLower = @UserName
		
		IF (SELECT COUNT(*) FROM @t) > 0		----有值则返回
			GOTO Retu
	
		----无值,再查询Company_Xinxi 区分大小写
		INSERT INTO @t(ID, Name, UserName, Email, Gender, Mobile)
		SELECT 0 ID, Username, Username, Email,NULL, NULL
		FROM Company_Xinxi WITH(NOLOCK INDEX(IX_Company_Xinxi_UserName))
		WHERE UserName = @Username

		IF (SELECT COUNT(*) FROM @t) = 1		----有一个则返回
			GOTO Retu

		----不区分大小写
		INSERT INTO @t(ID, Name, UserName, Email, Gender, Mobile)
		SELECT 0 ID, Username, Username, Email, NULL, NULL
		FROM Company_Xinxi WITH(NOLOCK INDEX(IX_Company_Xinxi_UserNameLower)) 
		WHERE UserNameLower = @Username

		IF (SELECT COUNT(*) FROM @t) > 0
			GOTO Retu		----有值返回结果
		ELSE
			GOTO Err3		----无值返回而Error
	END
	ELSE IF LEN(ISNULL(@Email, '')) > 0		----查询caMain.Email
	BEGIN
		INSERT INTO @t(ID, cpMainId, Name, UserName, Email, Gender, Mobile)
		SELECT TOP 10  ID, cpMainId, ISNULL(Name, ''), Username, Email, Gender, Mobile
		FROM caMain WITH(NOLOCK INDEX(IX_caMain_Email))
		WHERE Email = @Email
		ORDER BY (SELECT MAX(AddDate) FROM caLoginLog WITH(NOLOCK) WHERE caMainID = caMain.ID) DESC
/*
		IF (SELECT COUNT(*) FROM @t) > 0		----有值则返回
			GOTO Retu
*/		
		INSERT INTO @t(ID, Name, UserName, Email)
		SELECT TOP 10  0 ID, Username Name, Username, Email
		FROM Company_Xinxi WITH(NOLOCK INDEX(IX_Company_Xinxi_Email)) 
		WHERE Email = @Email
		ORDER BY ID DESC

		IF (SELECT COUNT(*) FROM @t) > 0
			GOTO Retu		----有值返回结果
		ELSE
			GOTO Err3		----无值返回而Error
	END
END
Retu:	----正确返回，有数据
BEGIN
	--获取随机数,激活码
	DECLARE @Rnd AS INT,@AskNo AS VARCHAR(60)
	SELECT @Rnd = RAND() * 899999 + 100000,@AskNo=REPLACE(NEWID(), '-', '')
	
	UPDATE @t SET ReturnType = @Type, AskNo=@AskNo, ActivateCode = RAND() * 899999 + 100000,UniqueId=REPLACE(NEWID(), '-', '')		----修改返回类型，用于前台显示结果

	----记录取回纪录
	INSERT INTO caGetPasswordLog(caMainID, UserNameIn, EmailIn, VerifyCode, IP, UserName, Email, Mobile, UniqueId, ActivateCode, AskNo )
	SELECT ID, @UserName, @Email, @VerifyCode, @IP, UserName, Email, @Mobile, UniqueId,ActivateCode ,AskNo FROM @t

	UPDATE a SET a.ConsultantName = (SELECT Name FROM ManagerUser WITH(NOLOCK) WHERE ManagerUser.ID = b.consultantID),
		a.ConsultantEmail = (SELECT EMail FROM ManagerUser WITH(NOLOCK) WHERE ManagerUser.ID = b.consultantID)
	FROM @t a, cpMain b WITH(NOLOCK)
	WHERE a.cpMainId = b.Id

	

	SELECT * FROM @t ORDER BY ID DESC
	
	IF @Type = 'Mobile' 
	BEGIN 
		SELECT TOP 1   a.ID AS caMainId, a.Mobile, 9 AS MsgType, 
			'您好，您在' + @SubSiteName  + '的激活码是：' + d.ActivateCode AS Msg
		FROM caMain a WITH(NOLOCK), cpMain b WITH(NOLOCK), (SELECT TOP 1 ID, ActivateCode FROM @t ORDER BY ID DESC) d
		WHERE a.cpMainID = b.ID
		AND a.ID = d.Id
		AND a.Mobile > ''
		ORDER BY a.ID DESC
	END
	RETURN
END
Err1:	----一个账号一天取回超过5次
BEGIN
	SELECT null ID, NULL Name, NULL Username, NULL Email, NULL Gender, NULL Mobile, 1 ReturnType
	RETURN
END
Err2:	----一个ip一天取回超过20次
BEGIN
	SELECT null ID, NULL Name, NULL Username, NULL Email, NULL Gender, NULL Mobile, 2 ReturnType
	RETURN
END
Err3:	----没有取回数据
BEGIN
	SELECT null ID, NULL Name, NULL Username, NULL Email, NULL Gender, NULL Mobile, 3 ReturnType
	RETURN
END
Err4:	----手机号一天取回超过3次
BEGIN
	SELECT null ID, NULL Name, NULL Username, NULL Email, NULL Gender, NULL Mobile, 4 ReturnType
	RETURN
END

GO
/****** Object:  StoredProcedure [dbo].[ccCaMainByGetSecondPasswordSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
---- =============================================
---- 创建人:		Lambo
---- 创建时间: 2014-12-20
---- 功能:	企业重置二次密码
--[ccCaMainByGetSecondPasswordSelect] 9836390,'192.168.1.1','山东'
---- =============================================
CREATE PROCEDURE [dbo].[ccCaMainByGetSecondPasswordSelect]
(
	@CaMainID INT,
	@IP VARCHAR(15),
	@SubSiteName VARCHAR(30)
)
AS
BEGIN
	DECLARE @Cnt AS INT, @Type AS VARCHAR(10), @ToDay AS DATETIME, @QueryMobile AS INT
	----如果用户名、油箱、手机号都为空则返回
	
	DECLARE @t AS TABLE(
		ID INT,
		cpMainID INT,
		Name NVARCHAR(50) NOT NULL,
		UserName VARCHAR(50) NOT NULL,
		Email VARCHAR(50) NOT NULL,
		Gender NVARCHAR(10),
		ConsultantID SMALLINT,
		ConsultantName NVARCHAR(10),
		ConsultantEmail VARCHAR(50),
		Mobile VARCHAR(13),		
		UniqueId VARCHAR(40),
		ActivateCode VARCHAR(6)
	)

	SET @ToDay = CONVERT(DATETIME, CONVERT(VARCHAR(8), GETDATE(), 112))	
	SELECT @Cnt = COUNT(1) FROM caGetSecondPasswordLog WITH(NOLOCK) WHERE caMainID=@CaMainID AND AddDate > @Today	
	
	IF @Cnt > 2								----一天之内一个账号最多取回3次
		GOTO Err1

	SELECT @Cnt = COUNT(1) FROM caGetSecondPasswordLog WITH(NOLOCK) WHERE IP = @IP AND AddDate >= @Today
	IF @Cnt > 20							----一天之内一个ip不能超过20次
		GOTO Err2
		
	--获取随机数,激活码
	DECLARE @Rnd AS INT,@UniqueId AS VARCHAR(60)
	SELECT @Rnd = RAND() * 899999 + 100000,@UniqueId=REPLACE(NEWID(), '-', '')
	
	INSERT INTO @t(ID, cpMainId, Name, UserName, Email, Gender, Mobile,UniqueId,ActivateCode)
	SELECT ID, cpMainId, ISNULL(Name, ''), Username, Email, Gender, Mobile,@UniqueId,@Rnd
	FROM caMain WITH(NOLOCK)
	WHERE id=@caMainID	
	
	----记录取回纪录
	INSERT INTO caGetSecondPasswordLog(caMainID, ActivateCode, IP,  UniqueId)
	SELECT ID, ActivateCode, @IP, UniqueId FROM @t

	UPDATE a SET a.ConsultantName = (SELECT Name FROM ManagerUser WITH(NOLOCK) WHERE ManagerUser.ID = b.consultantID),
		a.ConsultantEmail = (SELECT EMail FROM ManagerUser WITH(NOLOCK) WHERE ManagerUser.ID = b.consultantID)
	FROM @t a, cpMain b WITH(NOLOCK)
	WHERE a.cpMainId = b.Id

	INSERT SmsMessageLog(SendMan, ManagerUSerId, paMainId, caMainId, Mobile, MsgType, IsCat, Msg)
	SELECT TOP 1 0, NULL, NULL, a.ID, a.Mobile, 9, 0, 
		'您好，您在' + @SubSiteName  + '的激活码是：' + d.ActivateCode
	FROM caMain a WITH(NOLOCK), cpMain b WITH(NOLOCK), (SELECT TOP 1 ID, ActivateCode FROM @t ORDER BY ID DESC) d
	WHERE a.cpMainID = b.ID
	AND a.ID = d.Id
	AND a.Mobile > ''
	AND a.ID = @caMainID
	ORDER BY ID DESC

	SELECT TOP 1 * FROM @t 
	RETURN
END
Err1:	----一个账号一天取回超过3次
BEGIN
	SELECT null ID, 1 cpMainID,NULL Name, NULL Username, NULL Email, NULL Gender, NULL Mobile, '' UniqueId 
	RETURN
END
Err2:	----一个ip一天取回超过20次
BEGIN
	SELECT null ID, 2 cpMainID,NULL Name, NULL Username, NULL Email, NULL Gender, NULL Mobile, '' UniqueId 
	RETURN
END









GO
/****** Object:  StoredProcedure [dbo].[ccCaMainByIsPauseUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--##################################################
--检查：		sean 2010-11-1
--暂停企业账号
--##################################################
CREATE PROCEDURE [dbo].[ccCaMainByIsPauseUpdate]
(
	@ManagerID INT,
    @ID INT
)
AS
SET NOCOUNT ON
BEGIN TRAN
	IF @ManagerID = @ID
		RETURN 0

	BEGIN TRY
		IF EXISTS(
			SELECT a.ID FROM 
				caMain a WITH(NOLOCK),
				caMain b WITH(NOLOCK)
			WHERE a.cpMainID=b.cpMainID 
			AND a.AccountType=1 
			AND b.AccountType>1 
			AND a.ID=@ManagerID 
			AND b.ID=@ID
			AND a.IsDelete = 0
		)
			BEGIN
				DECLARE @IsPause AS BIT
				DECLARE @cpMainID AS INT
				DECLARE @Cnt AS INT
				DECLARE @MaxUserNumber AS INT
				DECLARE @DESC AS NVARCHAR(100)
				SELECT @IsPause = IsPause, @cpMainID = cpMainID FROM caMain WHERE ID = @ID
				IF @IsPause = 1
				BEGIN
					SELECT @Cnt = COUNT(1) FROM caMain WITH(NOLOCK) WHERE cpMainID = @cpMainID AND IsPause = 0
					SELECT @MaxUserNumber = MaxUserNumber FROM cpMain WITH(NOLOCK) WHERE ID = @cpMainID
					--PRINT @MaxUserNumber
					IF @Cnt > @MaxUserNumber -1
						GOTO Err
				UPDATE Job 
				SET IssueEnd = GETDATE(), 
					IssueDate = CASE WHEN IssueDate > GETDATE() THEN CONVERT(VARCHAR(10), GETDATE(), 23) ELSE IssueDate END,
					Valid = 0
				WHERE caMainID = @ID
				AND Valid = 1

				END
				UPDATE caMain SET IsPause = IsPause - 1 WHERE ID = @ID
			END
	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH
COMMIT TRAN
RETURN 1
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END














GO
/****** Object:  StoredProcedure [dbo].[ccCaMainByLoginUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--========================
--创建：		sean
--检查：		sean	2010-10-15
--企业用户登录	，增加Company_xinxi表中数据的检索、处理
--检查caMain表
--2010-12-27 sean 企业第一次登录时 注册时间改为信息员推广时间
--2012-09-05 NICK 加密后的登录过程
--2017-10-11 harry 限制实名的，不记录登录时间
--2018-8-7 harry 修改职位登录刷新，今天未刷新的刷新
--========================
CREATE PROCEDURE [dbo].[ccCaMainByLoginUpdate]
(
	@UserName VARCHAR(70), 
	@Password VARCHAR(60), 
	@PlainPassword VARCHAR(50), 
	@IP VARCHAR(31), 
	@dcSubSiteID SMALLINT, 
	@LoginCookies VARCHAR(16), 
	@SessionID VARCHAR(30),
	@browser VARCHAR(500),
	@caMainID AS INT,
	@loginFrom AS INT,
	@CaType INT OUTPUT--camain数据是否从company_xinxi 表中导入
)
AS
SET NOCOUNT ON
IF @UserName LIKE '% %'
	SET @UserName = REPLACE(@UserName, ' ', '')
IF @caMainID > 0
BEGIN
	IF NOT EXISTS(SELECT 'x' FROM cpMain WITH(NOLOCK) WHERE ID IN(SELECT cpMainId FROM caMain WITH(NOLOCK) WHERE Id= @caMainID))
	BEGIN
		IF EXISTS(SELECT 'x' FROM dcLimitIp WHERE LoginIp = @Ip)
			RETURN -1
		IF EXISTS(SELECT 'x' FROM dcLimitCookies WHERE LoginCookies = @LoginCookies)
			RETURN -1
	END
END

BEGIN TRAN
	DECLARE 
		@cpMainID AS INT,
		@SecondID VARCHAR(10),
		@IsPause AS BIT,
		@Name AS NVARCHAR(20),
		@cpName AS NVARCHAR(50),
		@DayLoginNumber AS INT,
		@RefreshDate AS SMALLDATETIME,
		@IsLimitLogin AS TINYINT,
		@IsLock AS INT,
		@thisDcProvinceID AS TINYINT,
		@CountDate AS INT,
		@dcProvinceID AS TINYINT,
		@MemberType AS TINYINT,
		@JobNumber AS INT,
		@JobID AS VARCHAR(300), 
		@JobName AS VARCHAR(1000),
		@LastJobIssueDate AS SMALLDATETIME,
		@LastJobId AS VARCHAR(12),
		@Cnt AS INT,
		@dcREgionID VARCHAR(6),
		@IsAgent BIT,
		@RealNameLimit INT --harry2017-10-11

	SELECT @dcProvinceID = LEFT(@dcSubSiteID, 2),
		@CaType=0,
		@CountDate = YEAR(GETDATE())*10000 + MONTH(GETDATE())*100 + DAY(GETDATE()),
		@UserName = LTRIM(RTRIM(@UserName))
	--caMain中存在账号
	BEGIN TRY
		IF @caMainID <>0
		BEGIN
			SELECT @caMainID = a.ID, @cpMainID = a.cpMainID, @Name = a.Name, @SecondId = SecondID,
			@IsPause = a.IsPause, @dcRegionID = b.dcRegionId, @JobNumber = b.JobNumber,
			@IsLimitLogin = b.IsLimitLogin, @RefreshDate = b.RefreshDate, 
			@cpName = b.Name, @IsAgent = b.IsAgent,
			@IsLock = b.IsLock, @MemberType =MemberType, @thisDcProvinceID = dcProvinceID
			FROM caMain a WITH(NOLOCK), cpMain b WITH(NOLOCK)
			WHERE a.ID=@caMainID AND a.cpmainID = b.ID
		END

		IF @caMainID = 0	--在caMain表中没有记录
		BEGIN
			DECLARE @Company_XinxiID AS INT
			DECLARE @AddMan AS SMALLINT
			DECLARE @RegDate AS SMALLDATETIME
			DECLARE @EMail AS VARCHAR(50)

			SELECT @Cnt = COUNT(1)
			FROM Company_Xinxi WITH(NOLOCK INDEX(IX_Company_Xinxi_UserNameLower))
			WHERE UserNameLower = @UserName AND Password = @PlainPassword

			IF @Cnt = 1
				SELECT @cpName = CompanyName, @EMail = Email, @Company_XinxiID = ID, @AddMan = AddMan, @RegDate = RegDate
				FROM Company_Xinxi WITH(NOLOCK INDEX(IX_Company_Xinxi_UserNameLower))
				WHERE UserNameLower = @UserName
				AND Password = @PlainPassword
			ELSE IF @Cnt > 1
				SELECT @cpName = CompanyName, @EMail = Email, @Company_XinxiID = ID, @AddMan = AddMan, @RegDate = RegDate
				FROM Company_Xinxi WITH(NOLOCK INDEX(IX_Company_Xinxi_UserName))
				WHERE UserName = @UserName
				AND Password = @PlainPassword

			IF @Company_XinxiID IS NOT NULL			--如果在Company_xinxi中, 将其转移到cpmain中，并删除Company_xinxi中的记录
			BEGIN	
				SET @CaType=1
				----企业表
				INSERT INTO cpMain(dcProvinceID, dcRegionID, dcSubSiteID, RegisterIP, Name, RegDate, RegisterMode, AddMan, IsDefaultPassword)
				VALUES(@dcProvinceID, @dcSubSiteID, @dcSubSiteID, @IP, @cpName, @RegDate, 1, @AddMan, 1)
				SELECT @cpMainID = @@IDENTITY
				----账号表
				INSERT INTO caMain(cpMainID, EMail, AccountType, UserName, Password)
				VALUES(@cpMainID, @EMail, 1, @UserName, @Password)
				SELECT TOP 1 @caMainID = ID FROM caMain WITH(NOLOCK) WHERE cpMainID = @cpMainID ORDER BY ID DESC
				--INSERT INTO caPlainPassword(caMainId, PlainPassWord) SELECT @caMainID, @PlainPassword

				----顾问分配
				EXEC ccCpMainByConsultantAssignUpdate @cpMainID, @dcProvinceID

				SET @RefreshDate = GETDATE() - 10		--刷新时间和企业名称等变量
				SET @thisDcProvinceID = @dcProvinceID
				IF @cpName IS NULL
					SET @cpName = '未命名企业'
				----日报表, 信息员推广过的个人注册，160天内作为推广ValIDCompany, 不判断省份
				UPDATE DateReport 
				SET ValIDCompany = ValIDCompany +1
				WHERE CountDate = @CountDate
				AND Province_ID = @dcSubSiteID
				--INSERT INTO pamainDatereport SELECT @cpMainID, 8, GETDATE() -- SEAN 20130911
				------判断是否有该行记录，没有则增加
				IF NOT EXISTS(SELECT 'x' FROM Info_DateReport WITH(NOLOCK) WHERE CountDate = @CountDate AND Province_ID = @dcProvinceID	AND InfoManager_ID = @AddMan)
					INSERT INTO Info_DateReport(Province_ID, InfoManager_ID, CountDate)
					VALUES(@dcProvinceID, @AddMan, @CountDate)
				------记录数据，信息员工作量 + 1
				UPDATE Info_DateReport
				SET ValIDCompany = ValIDCompany + 1  
				WHERE CountDate = @CountDate
				AND Province_ID = @dcProvinceID
				AND InfoManager_ID = @AddMan
			END
			ELSE
				GOTO ERR1	--用户名、密码不正确， cpMain、Company_xinxi中都没有
		END

		IF @IsPause = 1
			GOTO ERR3		--企业账户被暂停
		
		IF @IsLimitLogin = 9
			GOTO Err4		--企业已经被限制登录

		IF @thisDcProvinceID <> @dcProvinceID
			GOTO Err5		--企业登陆网站不是注册网站

		--Added  By mice 123 判断是否为死客户，如果为死客户，则激活
		IF EXISTS(SELECT 'X' FROM MainDb..bsDeadCompany x WITH(NOLOCK) WHERE x.cpMainID = @cpMainID AND x.ActiveDate IS NULL)
		BEGIN
			UPDATE MAINDB..bsDeadCompany SET ActiveDate = GETDATE() WHERE cpMainID = @cpMainID AND ActiveDate IS NULL 
		END

		--根据企业购买的服务，确定每天最大登陆次数
		IF @MemberType >= 3
			SELECT @DayLoginNumber = 30
		ELSE
			SET @DayLoginNumber = 15

		DECLARE @TodayLoginNumber AS INT, @IsOldRefresh BIT, @UnRefreshNumber INT
		SELECT @TodayLoginNumber = COUNT(1)
		FROM CaLoginLog WITH(NOLOCK)
		WHERE caMainID = @caMainID
		AND AddDate > CONVERT(VARCHAR(10), GETDATE(), 120)
		
		--今天还未刷新的职位数 harry 2018-8-7
		SELECT @UnRefreshNumber = COUNT(1)
		FROM Job
		WHERE caMainID = @caMainID AND RefreshDate < CONVERT(VARCHAR(10), GETDATE(), 120) AND Valid = 1
		
		IF @TodayLoginNumber >= @DayLoginNumber
			GOTO ERR2	--超过登陆次数, 每天限制登录次数

		--登陆次数--harry 20171011 实名限制登录时间不更新
		SELECT @RealNameLimit = ISNULL(RealName, 0), @IsOldRefresh = 0 FROM cpMain WITH(NOLOCK) WHERE ID = @cpMainID
		
		IF @RealNameLimit < 2 -----harry 20171011 实名限制登录时间不更新
		BEGIN
			IF EXISTS(SELECT 'x' FROM jobRefreshOldCompany WHERE cpMainId = @cpMainId)
				SET @IsOldRefresh = 1

			UPDATE cpMain SET LoginCount = LoginCount + 1, LastLoginDate = GETDATE(), LastLoginIp = @IP WHERE ID = @cpMainID 
			
			IF @IsOldRefresh = 1 OR @TodayLoginNumber = 0 OR @UnRefreshNumber>0
				UPDATE Job SET RefreshDate = GETDATE() 
				WHERE caMainID = @caMainID AND RefreshDate < CONVERT(VARCHAR(10), GETDATE(), 120) AND Valid = 1

			--检查该企业数据是否已经在SearchDB..cpMainHomepageSnapshot
			IF (@MemberType >= 2) OR (@dcProvinceID NOT IN(32, 30, 31, 35, 10, 11, 12, 40) AND @MemberType = 1)
				IF NOT EXISTS(SELECT 'x' FROM SearchDB..cpMainHomepageSnapshot WITH(NOLOCK) WHERE RealCpMainID = @cpMainID)
					SET @RefreshDate = GETDATE() - 1

			--IF DATEDIFF(MINUTE, @RefreshDate, GETDATE()) > 59 --刷新时间如果超过1个小时，更新为当前时间
			--	UPDATE cpMain SET RefreshDate = GETDATE() WHERE ID = @cpMainID

 			--更新企业刷新时间, 更新职位刷新时间, 间隔时间1小时
			IF DATEDIFF(MINUTE, @RefreshDate, GETDATE()) > 59 --刷新时间如果超过1个小时，更新为当前时间
			BEGIN TRY
				UPDATE cpMain SET RefreshDate = GETDATE() WHERE ID = @cpMainID
				IF (@MemberType > 2)
				BEGIN
					IF EXISTS(SELECT 'x' FROM SearchDB..cpMainHomepageSnapshot WITH(NOLOCK) WHERE RealCpMainID = @cpMainID)
						DELETE FROM SearchDB..cpMainHomepageSnapshot WHERE RealCpMainID = @cpMainID

					SELECT @JobID = dbo.GetJobSecondIds(@cpMainID), @JobName = dbo.GetJobNames(@cpMainID)
					SELECT TOP 1 @LastJobIssueDate = IssueDate, @LastJobId = SecondId FROM Job WITH(NOLOCK)
					WHERE cpMainID = @cpMainID AND Valid = 1 AND CHARINDEX(SecondId, LEFT(@JobId, 22)) > 0
					ORDER BY IssueDate DESC

					INSERT SearchDB..cpMainHomepageSnapshot(dcSubsiteID, dcRegionID, cpMainID, Name, IsAgent, JobNumber, JobID, JobName, LastJobIssueDate, LastJobId, MemberType, RealCpMainId, RefreshDate)
					VALUES(@dcSubSiteID, LEFT(@dcRegionID, 4), @SecondID, @cpName, @IsAgent, @JobNumber, @JobID, @JobName, @LastJobIssueDate, @LastJobId, @MemberType, @cpMainId, GETDATE())
				END
				IF (@MemberType = 2) OR (@dcProvinceID NOT IN(32, 30, 31, 35, 10, 11, 12, 40) AND @MemberType = 1)
				BEGIN
					IF EXISTS(SELECT 'x' FROM SearchDB..cpMainHomepageSnapshot WITH(NOLOCK) WHERE RealCpMainID = @cpMainID)
						DELETE FROM SearchDB..cpMainHomepageSnapshot WHERE RealCpMainID = @cpMainID

					DECLARE @cpLicenceDate AS SMALLDATETIME
					SELECT @cpLicenceDate = AddDate FROM cpLicence WITH(NOLOCK) WHERE cpMainID = @cpMainID

					SELECT @JobID = dbo.GetJobSecondIds(@cpMainID), @JobName = dbo.GetJobNames(@cpMainID)
					SELECT TOP 1 @LastJobIssueDate = IssueDate, @LastJobId = SecondId FROM Job WITH(NOLOCK)
					WHERE cpMainID = @cpMainID AND Valid = 1 ORDER BY IssueDate DESC

					INSERT SearchDB..cpMainHomepageSnapshot(dcSubsiteID, dcRegionID, cpMainID, Name, IsAgent, JobNumber, JobID, JobName, LastJobIssueDate, LastJobId, MemberType, cpLicenceDate, RealCpMainId, RefreshDate)
					VALUES(@dcSubSiteID, LEFT(@dcRegionID, 4), @SecondID, @cpName, @IsAgent, @JobNumber, @JobID, @JobName, @LastJobIssueDate, @LastJobId, @MemberType, @cpLicenceDate, @cpMainId, GETDATE())
				END
			END TRY
			BEGIN CATCH
				--print 'Error '
				INSERT INTO PaMainDateReport SELECT @cpMainID, 99, GETDATE()	--20130709 lambo
			END CATCH

			IF ISNULL(@Name, '') = ''
				SET @Name = @UserName
	 
			--记录每日登录数据
			IF NOT EXISTS(SELECT 'x' FROM caloginlog a WITH(NOLOCK), caMain b WITH(NOLOCK)
					WHERE a.caMainID = b.ID
					AND b.cpMainID = @cpMainID
					AND a.AddDate >= CONVERT(VARCHAR(10), GETDATE(), 120))
				AND @Company_XinxiID IS NULL
			BEGIN
				UPDATE DateReport 
				SET CompanyLoginNum_Net = CompanyLoginNum_Net + 1
				WHERE Province_ID = @dcSubSiteID
				AND CountDate = @CountDate

				--INSERT INTO PaMainDateReport SELECT @cpMainID, 10, GETDATE()	--20130709 lambo
			END

			--登陆日志, 记录Cookies
			IF ISNULL(@LoginCookies, '') = ''
				SET @LoginCookies = RTRIM(CONVERT(VARCHAR(16), @SessionID))

			INSERT INTO caLoginLog(caMainID, cpMainName, caMainName, LoginIP, LoginCookies, browser, loginFrom)
			VALUES(@caMainID, @cpName, @Name, @IP, @LoginCookies, '2:' + ISNULL(@browser, 'Null'), @loginFrom )

--			IF @MemberType = 3 AND GETDATE()<'2014-11-1' 
--			BEGIN
--				IF NOT EXISTS(SELECT TOP 1 'x' FROM LotteryCompanyLoginLog WITH(NOLOCK)
--					WHERE cpMainID = @cpMainID
--					AND LoginDate > CONVERT(VARCHAR(10), GETDATE(), 120))
--				BEGIN
--					--取昨天是第几天登陆 
--					DECLARE @LastLoginNo INT
--					SELECT @LastLoginNo = LoginNo FROM LotteryCompanyLoginLog 
--					WHERE cpMainID=@cpMainID
--					AND CONVERT(VARCHAR(8), LoginDate, 112) = CONVERT(VARCHAR(8), GETDATE() - 1, 112)
--
--					SET @LastLoginNo = ISNULL(@LastLoginNo, 0)
--
--					IF @LastLoginNo = 5
--						SET @LastLoginNo = 1							
--					ELSE 
--					BEGIN
--						SET @LastLoginNo = @LastLoginNo + 1
--						IF @LastLoginNo = 5
--							INSERT INTO lotteryCompany(CpMainID, CaOrderID, LoginDate, Used, AddDate)
--							SELECT @cpMainID, NULL, GETDATE(), 0, GETDATE()
--					END
--					INSERT INTO	LotteryCompanyLoginLog(cpMainID, LoginDate, LoginNo)			
--					SELECT @cpMainID, GETDATE(), @LastLoginNo
--				END
--			END
		END
	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH
COMMIT TRAN
RETURN @caMainID
ERR:
BEGIN
	ROLLBACK TRAN
	print 0
	RETURN 0
END
ERR1:
BEGIN
	ROLLBACK TRAN
	print -1
	RETURN -1
END
ERR2:
BEGIN
	ROLLBACK TRAN
	IF @DayLoginNumber = 15
	BEGIN
		print -2
		RETURN -2
	END
	IF @DayLoginNumber = 30
	BEGIN
		print -3
		RETURN -3
	END
END
ERR3:
BEGIN
	ROLLBACK TRAN
	print -4
	RETURN -4
END
ERR4:
BEGIN
	ROLLBACK TRAN
	print 0
	RETURN -9
END
ERR5:
BEGIN
	ROLLBACK TRAN
	print @cpMainID * -1
	RETURN @cpMainID * -1
END
GO
/****** Object:  StoredProcedure [dbo].[ccCaMainByLoginUpdate2]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--========================
--创建：		sean
--检查：		sean	2010-10-15
--企业用户登录	，增加Company_xinxi表中数据的检索、处理
--检查caMain表
--2010-12-27 sean 企业第一次登录时 注册时间改为信息员推广时间
--2012-09-05 NICK 加密后的登录过程
--========================
CREATE PROCEDURE [dbo].[ccCaMainByLoginUpdate2]
(
	@UserName VARCHAR(70), 
	@Password VARCHAR(60), 
	@PlainPassword VARCHAR(50), 
	@IP VARCHAR(31), 
	@dcSubSiteID SMALLINT, 
	@LoginCookies VARCHAR(16), 
	@SessionID VARCHAR(30),
	@browser VARCHAR(500),
	@caMainID AS INT,
	@loginFrom AS INT,
	@CaType INT OUTPUT--camain数据是否从company_xinxi 表中导入
)
AS
SET NOCOUNT ON
IF @caMainID > 0
BEGIN
	IF NOT EXISTS(SELECT 'x' FROM cpMain WITH(NOLOCK) WHERE ID IN(SELECT cpMainId FROM caMain WITH(NOLOCK) WHERE Id= @caMainID))
	BEGIN
		IF EXISTS(SELECT 'x' FROM dcLimitIp WHERE LoginIp = @Ip)
			RETURN -1
		IF EXISTS(SELECT 'x' FROM dcLimitCookies WHERE LoginCookies = @LoginCookies)
			RETURN -1
	END
END

BEGIN TRAN
	DECLARE 
		@cpMainID AS INT,
		@SecondID VARCHAR(10),
		@IsPause AS BIT,
		@Name AS NVARCHAR(20),
		@cpName AS NVARCHAR(50),
		@DayLoginNumber AS INT,
		@RefreshDate AS SMALLDATETIME,
		@IsLimitLogin AS TINYINT,
		@IsLock AS INT,
		@thisDcProvinceID AS TINYINT,
		@CountDate AS INT,
		@dcProvinceID AS TINYINT,
		@MemberType AS TINYINT,
		@JobNumber AS INT,
		@JobID AS VARCHAR(300), 
		@JobName AS VARCHAR(1000),
		@LastJobIssueDate AS SMALLDATETIME,
		@LastJobId AS INT,
		@Cnt AS INT,
		@dcREgionID VARCHAR(6),
		@IsAgent BIT

	SELECT @dcProvinceID = LEFT(@dcSubSiteID, 2),
		@CaType=0,
		@CountDate = YEAR(GETDATE())*10000 + MONTH(GETDATE())*100 + DAY(GETDATE()),
		@UserName = LTRIM(RTRIM(@UserName))
	--caMain中存在账号
	BEGIN TRY
		IF @caMainID <>0
		BEGIN
			SELECT @caMainID = a.ID, @cpMainID = a.cpMainID, @Name = a.Name, @SecondId = SecondID,
			@IsPause = a.IsPause, @dcRegionID = b.dcRegionId, @JobNumber = b.JobNumber,
			@IsLimitLogin = b.IsLimitLogin, @RefreshDate = b.RefreshDate, 
			@cpName = b.Name, @IsAgent = b.IsAgent,
			@IsLock = b.IsLock, @MemberType =MemberType, @thisDcProvinceID = dcProvinceID
			FROM caMain a WITH(NOLOCK), cpMain b WITH(NOLOCK)
			WHERE a.ID=@caMainID AND a.cpmainID = b.ID
		END

		IF @caMainID = 0	--在caMain表中没有记录
		BEGIN
			DECLARE @Company_XinxiID AS INT
			DECLARE @AddMan AS SMALLINT
			DECLARE @RegDate AS SMALLDATETIME
			DECLARE @EMail AS VARCHAR(50)

			SELECT @Cnt = COUNT(1)
			FROM Company_Xinxi WITH(NOLOCK INDEX(IX_Company_Xinxi_UserNameLower))
			WHERE UserNameLower = @UserName AND Password = @PlainPassword

			IF @Cnt = 1
				SELECT @cpName = CompanyName, @EMail = Email, @Company_XinxiID = ID, @AddMan = AddMan, @RegDate = RegDate
				FROM Company_Xinxi WITH(NOLOCK INDEX(IX_Company_Xinxi_UserNameLower))
				WHERE UserNameLower = @UserName
				AND Password = @PlainPassword
			ELSE IF @Cnt > 1
				SELECT @cpName = CompanyName, @EMail = Email, @Company_XinxiID = ID, @AddMan = AddMan, @RegDate = RegDate
				FROM Company_Xinxi WITH(NOLOCK INDEX(IX_Company_Xinxi_UserName))
				WHERE UserName = @UserName
				AND Password = @PlainPassword

			IF @Company_XinxiID IS NOT NULL			--如果在Company_xinxi中, 将其转移到cpmain中，并删除Company_xinxi中的记录
			BEGIN	
				SET @CaType=1
				----企业表
				INSERT INTO cpMain(dcProvinceID, dcRegionID, dcSubSiteID, RegisterIP, Name, RegDate, RegisterMode, AddMan, IsDefaultPassword)
				VALUES(@dcProvinceID, @dcSubSiteID, @dcSubSiteID, @IP, @cpName, @RegDate, 1, @AddMan, 1)
				SELECT @cpMainID = @@IDENTITY
				----账号表
				INSERT INTO caMain(cpMainID, EMail, AccountType, UserName, Password)
				VALUES(@cpMainID, @EMail, 1, @UserName, @Password)
				SELECT TOP 1 @caMainID = ID FROM caMain WITH(NOLOCK) WHERE cpMainID = @cpMainID ORDER BY ID DESC
				--INSERT INTO caPlainPassword(caMainId, PlainPassWord) SELECT @caMainID, @PlainPassword

				----顾问分配
				EXEC ccCpMainByConsultantAssignUpdate @cpMainID, @dcProvinceID

				SET @RefreshDate = GETDATE() - 10		--刷新时间和企业名称等变量
				SET @thisDcProvinceID = @dcProvinceID
				IF @cpName IS NULL
					SET @cpName = '未命名企业'
				----日报表, 信息员推广过的个人注册，160天内作为推广ValIDCompany, 不判断省份
				UPDATE DateReport 
				SET ValIDCompany = ValIDCompany +1
				WHERE CountDate = @CountDate
				AND Province_ID = @dcSubSiteID
				--INSERT INTO pamainDatereport SELECT @cpMainID, 8, GETDATE() -- SEAN 20130911
				------判断是否有该行记录，没有则增加
				IF NOT EXISTS(SELECT 'x' FROM Info_DateReport WITH(NOLOCK) WHERE CountDate = @CountDate AND Province_ID = @dcProvinceID	AND InfoManager_ID = @AddMan)
					INSERT INTO Info_DateReport(Province_ID, InfoManager_ID, CountDate)
					VALUES(@dcProvinceID, @AddMan, @CountDate)
				------记录数据，信息员工作量 + 1
				UPDATE Info_DateReport
				SET ValIDCompany = ValIDCompany + 1  
				WHERE CountDate = @CountDate
				AND Province_ID = @dcProvinceID
				AND InfoManager_ID = @AddMan
			END
			ELSE
				GOTO ERR1	--用户名、密码不正确， cpMain、Company_xinxi中都没有
		END

		IF @IsPause = 1
			GOTO ERR3		--企业账户被暂停
		
		IF @IsLimitLogin = 9
			GOTO Err4		--企业已经被限制登录

		IF @thisDcProvinceID <> @dcProvinceID
			GOTO Err5		--企业登陆网站不是注册网站

		--Added  By mice 123 判断是否为死客户，如果为死客户，则激活
		IF EXISTS(SELECT 'X' FROM MainDb..bsDeadCompany x WITH(NOLOCK) WHERE x.cpMainID = @cpMainID AND x.ActiveDate IS NULL)
		BEGIN
			UPDATE MAINDB..bsDeadCompany SET ActiveDate = GETDATE() WHERE cpMainID = @cpMainID AND ActiveDate IS NULL 
		END

		--根据企业购买的服务，确定每天最大登陆次数
		IF @MemberType >= 3
			SELECT @DayLoginNumber = 30
		ELSE
			SET @DayLoginNumber = 15

		DECLARE @TodayLoginNumber AS TINYINT
		SELECT @TodayLoginNumber = COUNT(1)
		FROM CaLoginLog WITH(NOLOCK)
		WHERE caMainID = @caMainID
		AND AddDate > CONVERT(VARCHAR(10), GETDATE(), 120)

		IF @TodayLoginNumber >= @DayLoginNumber
			GOTO ERR2	--超过登陆次数, 每天限制登录次数

		--登陆次数
		UPDATE cpMain SET LoginCount = LoginCount + 1, LastLoginDate = GETDATE(), LastLoginIp = @IP WHERE ID = @cpMainID

		UPDATE Job SET RefreshDate = GETDATE() 
		WHERE caMainID = @caMainID AND DATEDIFF(MINUTE, RefreshDate, GETDATE()) > 60 AND Valid = 1

		--检查该企业数据是否已经在SearchDB..cpMainHomepageSnapshot
		IF (@MemberType >= 2) OR (@dcProvinceID NOT IN(32, 30, 31, 35, 10, 11, 12, 40) AND @MemberType = 1)
			IF NOT EXISTS(SELECT 'x' FROM SearchDB..cpMainHomepageSnapshot WITH(NOLOCK) WHERE RealCpMainID = @cpMainID)
				SET @RefreshDate = GETDATE() - 1

		--IF DATEDIFF(MINUTE, @RefreshDate, GETDATE()) > 59 --刷新时间如果超过1个小时，更新为当前时间
		--	UPDATE cpMain SET RefreshDate = GETDATE() WHERE ID = @cpMainID

 		--更新企业刷新时间, 更新职位刷新时间, 间隔时间1小时
		IF DATEDIFF(MINUTE, @RefreshDate, GETDATE()) > 59 --刷新时间如果超过1个小时，更新为当前时间
		BEGIN TRY
			UPDATE cpMain SET RefreshDate = GETDATE() WHERE ID = @cpMainID
			IF (@MemberType > 2)
			BEGIN
				IF EXISTS(SELECT 'x' FROM SearchDB..cpMainHomepageSnapshot WITH(NOLOCK) WHERE RealCpMainID = @cpMainID)
					DELETE FROM SearchDB..cpMainHomepageSnapshot WHERE RealCpMainID = @cpMainID

				SELECT @JobID = dbo.GetJobSecondIds(@cpMainID), @JobName = dbo.GetJobNames(@cpMainID)
				SELECT TOP 1 @LastJobIssueDate = IssueDate, @LastJobId = Id FROM Job WITH(NOLOCK)
				WHERE cpMainID = @cpMainID AND Valid = 1 ORDER BY IssueDate DESC

				INSERT SearchDB..cpMainHomepageSnapshot(dcSubsiteID, dcRegionID, cpMainID, Name, IsAgent, JobNumber, JobID, JobName, LastJobIssueDate, LastJobId, MemberType, RealCpMainId, RefreshDate)
				VALUES(@dcSubSiteID, LEFT(@dcRegionID, 4), @SecondID, @cpName, @IsAgent, @JobNumber, @JobID, @JobName, @LastJobIssueDate, @LastJobId, @MemberType, @cpMainId, GETDATE())
			END
			IF (@MemberType = 2) OR (@dcProvinceID NOT IN(32, 30, 31, 35, 10, 11, 12, 40) AND @MemberType = 1)
			BEGIN
				IF EXISTS(SELECT 'x' FROM SearchDB..cpMainHomepageSnapshot WITH(NOLOCK) WHERE RealCpMainID = @cpMainID)
					DELETE FROM SearchDB..cpMainHomepageSnapshot WHERE RealCpMainID = @cpMainID

				DECLARE @cpLicenceDate AS SMALLDATETIME
				SELECT @cpLicenceDate = AddDate FROM cpLicence WITH(NOLOCK) WHERE cpMainID = @cpMainID

				SELECT @JobID = dbo.GetJobSecondIds(@cpMainID), @JobName = dbo.GetJobNames(@cpMainID)
				SELECT TOP 1 @LastJobIssueDate = IssueDate, @LastJobId = Id FROM Job WITH(NOLOCK)
				WHERE cpMainID = @cpMainID AND Valid = 1 ORDER BY IssueDate DESC

				INSERT SearchDB..cpMainHomepageSnapshot(dcSubsiteID, dcRegionID, cpMainID, Name, IsAgent, JobNumber, JobID, JobName, LastJobIssueDate, LastJobId, MemberType, cpLicenceDate, RealCpMainId, RefreshDate)
				VALUES(@dcSubSiteID, LEFT(@dcRegionID, 4), @SecondID, @cpName, @IsAgent, @JobNumber, @JobID, @JobName, @LastJobIssueDate, @LastJobId, @MemberType, @cpLicenceDate, @cpMainId, GETDATE())
			END
		END TRY
		BEGIN CATCH
			--print 'Error '
			INSERT INTO PaMainDateReport SELECT @cpMainID, 99, GETDATE()	--20130709 lambo
		END CATCH

		IF ISNULL(@Name, '') = ''
			SET @Name = @UserName
 
		--记录每日登录数据
		IF NOT EXISTS(SELECT 'x' FROM caloginlog a WITH(NOLOCK), caMain b WITH(NOLOCK)
						WHERE a.caMainID = b.ID
						AND b.cpMainID = @cpMainID
						AND a.AddDate >= CONVERT(VARCHAR(10), GETDATE(), 120)
					) AND @Company_XinxiID IS NULL
		BEGIN
			UPDATE DateReport 
			SET CompanyLoginNum_Net = CompanyLoginNum_Net + 1
			WHERE Province_ID = @dcSubSiteID
			AND CountDate = @CountDate

			--INSERT INTO PaMainDateReport SELECT @cpMainID, 10, GETDATE()	--20130709 lambo
		END
		--登陆日志, 记录Cookies
		IF ISNULL(@LoginCookies, '') = ''
			SET @LoginCookies = RTRIM(CONVERT(VARCHAR(16), @SessionID))

		INSERT INTO caLoginLog(caMainID, cpMainName, caMainName, LoginIP, LoginCookies, browser, loginFrom)
		VALUES(@caMainID, @cpName, @Name, @IP, @LoginCookies, '2:' + ISNULL(@browser, 'Null'), @loginFrom )

		IF @MemberType = 3 AND GETDATE()<'2014-11-1' 
			IF NOT EXISTS(SELECT TOP 1 'x' FROM LotteryCompanyLoginLog WITH(NOLOCK)
				WHERE cpMainID = @cpMainID
				AND LoginDate > CONVERT(VARCHAR(10), GETDATE(), 120)
				)
			BEGIN
				--取昨天是第几天登陆 
				DECLARE @LastLoginNo INT
				SELECT @LastLoginNo = LoginNo FROM LotteryCompanyLoginLog 
				WHERE cpMainID=@cpMainID
				AND CONVERT(VARCHAR(8), LoginDate, 112) = CONVERT(VARCHAR(8), GETDATE() - 1, 112)

				SET @LastLoginNo = ISNULL(@LastLoginNo, 0)

				IF @LastLoginNo = 5
					SET @LastLoginNo = 1							
				ELSE 
				BEGIN
					SET @LastLoginNo = @LastLoginNo + 1
					IF @LastLoginNo = 5
						INSERT INTO lotteryCompany(CpMainID, CaOrderID, LoginDate, Used, AddDate)
						SELECT @cpMainID, NULL, GETDATE(), 0, GETDATE()
				END
				INSERT INTO	LotteryCompanyLoginLog(cpMainID, LoginDate, LoginNo)			
				SELECT @cpMainID, GETDATE(), @LastLoginNo
			END
	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH
COMMIT TRAN
RETURN @caMainID
ERR:
BEGIN
	ROLLBACK TRAN
	print 0
	RETURN 0
END
ERR1:
BEGIN
	ROLLBACK TRAN
	print -1
	RETURN -1
END
ERR2:
BEGIN
	ROLLBACK TRAN
	IF @DayLoginNumber = 15
	BEGIN
		print -2
		RETURN -2
	END
	IF @DayLoginNumber = 30
	BEGIN
		print -3
		RETURN -3
	END
END
ERR3:
BEGIN
	ROLLBACK TRAN
	print -4
	RETURN -4
END
ERR4:
BEGIN
	ROLLBACK TRAN
	print 0
	RETURN -9
END
ERR5:
BEGIN
	ROLLBACK TRAN
	print @cpMainID * -1
	RETURN @cpMainID * -1
END



GO
/****** Object:  StoredProcedure [dbo].[cccaMainByMobileVerifyDateUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[cccaMainByMobileVerifyDateUpdate]
(
	@caMainID INT,
	@cpMainID INT,
	@Mobile VARCHAR(11),
	@Code VARCHAR(6),
    @IsMobileHide BIT,
    @IP VARCHAR(30)
)
AS
SET NOCOUNT ON
BEGIN
    IF NOT EXISTS(SELECT 'X' FROM caMain WITH(NOLOCK) WHERE ID = @caMainID AND cpMainID = @cpMainID)
        RETURN 0

    DECLARE @VerifyCode VARCHAR(6), @VerifyLogID INT
	SELECT TOP 1 @VerifyCode = VerifyCode, @VerifyLogID = ID FROM CaVerifyLog WITH(NOLOCK) 
	WHERE Mobile = @Mobile
	AND AddDate > DATEADD(HOUR, -1, GETDATE())
		AND IP = @IP
	AND VerifyDate IS NULL
	ORDER BY ID DESC

	IF @VerifyCode IS NULL
		RETURN -1

    IF NOT @VerifyCode = @Code
        RETURN -1

    UPDATE CaVerifyLog SET VerifyDate = GETDATE() WHERE ID = @VerifyLogID
    UPDATE caMain SET IsMobileHide = @IsMobileHide, Mobile = @Mobile, MobileVerifyDate = GETDATE() WHERE ID = @caMainID
    RETURN 1
END
GO
/****** Object:  StoredProcedure [dbo].[ccCaMainByPasswordUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE  [dbo].[ccCaMainByPasswordUpdate]
(
    @ID INT,
	@Password VARCHAR(60),
	@PlainPassword VARCHAR(20)
)
AS
BEGIN TRAN
	--IF dbo.IsAccount(@PlainPassword) = 0
	--BEGIN
	--	GOTO Err
	--END

	IF dbo.IsPassword(@Password) = 0
	BEGIN
		GOTO Err
	END

	BEGIN TRY
		UPDATE caMain SET Password = @Password WHERE ID = @ID
		INSERT INTO caPlainPassword(caMainId, PlainPassWord) SELECT @ID, @PlainPassword
	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH
COMMIT TRAN
RETURN 1
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END














GO
/****** Object:  StoredProcedure [dbo].[ccCaMainByResetPasswordUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
sean 重置密码，2012-10-1 增加密码加密
*/
CREATE PROCEDURE [dbo].[ccCaMainByResetPasswordUpdate]
(
    @ID INT,
	@Password VARCHAR(60),
	@PlainPassword VARCHAR(20),
	@ManagerID INT
)
AS
BEGIN TRAN
	BEGIN TRY
		IF NOT EXISTS(SELECT 'x' FROM caMain WITH(NOLOCK) 
			WHERE AccountType = 1 AND ID = @ManagerID 
			AND cpMainID = (SELECT cpMainID FROM caMain WITH(NOLOCK) WHERE ID = @ID)
			)
			GOTO ERR1
		
		UPDATE caMain SET Password = @Password WHERE ID = @ID
		INSERT INTO caPlainPassword(caMainId, PlainPassWord) SELECT @ID, @PlainPassword 
	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH
COMMIT TRAN
RETURN 1
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END
ERR1:
BEGIN
	ROLLBACK TRAN
	RETURN -1
END














GO
/****** Object:  StoredProcedure [dbo].[ccCaMainByResetUsernameUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ccCaMainByResetUsernameUpdate]
(
    @ID INT,
	@Username VARCHAR(60),
	@ManagerID INT
)
AS
BEGIN TRAN
	BEGIN TRY
		IF NOT EXISTS(SELECT 'x' FROM caMain WITH(NOLOCK) 
			WHERE AccountType = 1 AND ID = @ManagerID 
			AND cpMainID = (SELECT cpMainID FROM caMain WITH(NOLOCK) WHERE ID = @ID)
			)
			GOTO ERR1
		
		UPDATE caMain SET Username = @Username WHERE ID = @ID
	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH
COMMIT TRAN
RETURN 1
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END
ERR1:
BEGIN
	ROLLBACK TRAN
	RETURN -1
END










GO
/****** Object:  StoredProcedure [dbo].[ccCaMainBySelfPasswordUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
sean 重置密码，2012-10-1 增加密码加密
*/
CREATE PROCEDURE [dbo].[ccCaMainBySelfPasswordUpdate]
(
	@ID INT,
	@Password VARCHAR(60),
	@PlainPassword VARCHAR(20)
)
AS
BEGIN TRY
	UPDATE caMain SET Password = @Password WHERE ID = @ID
	INSERT caplainpassword(caMainId, PlainPassword) SELECT @ID, @PlainPassword
	RETURN 1
END TRY
BEGIN CATCH
	RETURN 0
END CATCH









GO
/****** Object:  StoredProcedure [dbo].[ccCaMainByUserCountSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--========================================
--检查sean		2010-10-29
--企业用户数量
--========================================
CREATE PROCEDURE [dbo].[ccCaMainByUserCountSelect]
(
    @cpMainID INT
)
AS
BEGIN
	DECLARE @UserCount AS INT
    SELECT @UserCount=COUNT(*) 
	FROM caMain WITH(NOLOCK) 
	WHERE cpMainID = @cpMainID AND IsDelete=0

	RETURN @UserCount
END














GO
/****** Object:  StoredProcedure [dbo].[ccCaMainByUserNameLowerSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.30
--创建人：Nick
--说明：根据输入用户名得到企业信息
--修改harry:2018-1-8 增加dcregionid
--#####################################################
CREATE PROCEDURE [dbo].[ccCaMainByUserNameLowerSelect]
(
	@UserName VARCHAR(50)
)
AS
BEGIN TRY
	SELECT a.ID,a.Password,a.UserName,a.UserNameLower,b.dcProvinceID, b.dcregionid, b.dcregionid
	FROM caMain a WITH(NOLOCK), cpMain b WITH(NOLOCK)
	WHERE a.UserNameLower = @UserName
	AND a.cpMainID = b.ID
	AND a.IsDelete = 0
	AND b.IsDelete = 0
END TRY
BEGIN CATCH
	RETURN 0
END CATCH
GO
/****** Object:  StoredProcedure [dbo].[ccCaMainByUsernameUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ccCaMainByUsernameUpdate]
(
    @ID INT,
	@NewUsername VARCHAR(20)
)
AS
BEGIN TRAN
	BEGIN TRY
		--用户名不能重复
		IF EXISTS(SELECT ID FROM caMain WITH(NOLOCK) WHERE UserNameLower = @NewUserName)
			GOTO ERR1

		IF EXISTS(SELECT 'x' FROM Company_Xinxi WITH(NOLOCK) WHERE UserNameLower = @NewUSerName)
			GOTO ERR1

		IF dbo.IsAccount(@NewUsername) = 0
		BEGIN
			GOTO Err
		END
	
		UPDATE caMain SET Username = @NewUsername WHERE ID = @ID
	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH
COMMIT
RETURN 1
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END
ERR1:
BEGIN
	ROLLBACK TRAN
	RETURN -10
END














GO
/****** Object:  StoredProcedure [dbo].[ccCaMainDelete]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ccCaMainDelete]
	@OperatorID INT,
    @ID INT
AS
BEGIN TRAN
	IF @OperatorID=@ID
		RETURN 0

	BEGIN TRY
		IF EXISTS(
			SELECT a.ID FROM 
				caMain a WITH(NOLOCK),
				caMain b WITH(NOLOCK)
			WHERE a.cpMainID=b.cpMainID 
			AND a.AccountType=1 
			AND b.AccountType>1 
			AND a.ID=@OperatorID 
			AND b.ID=@ID
		)
			BEGIN
				UPDATE Job SET IsDelete=1 WHERE caMainID = @ID
				DELETE FROM bsCpModify WHERE caMainID = @ID

				UPDATE caMain SET IsDelete=1 WHERE ID=@ID

				DECLARE @desc AS VARCHAR(200)
				SET @desc = '删除用户：用户ID:' + CONVERT(CHAR(10),@ID)
				EXEC ccCaOperationLogInsert @ID, 17, @desc			
			END
	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH
COMMIT TRAN
RETURN 1
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END














GO
/****** Object:  StoredProcedure [dbo].[ccCaMainGenderSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.30
--创建人：Nick
--说明：获取性别
--#####################################################
CREATE PROCEDURE [dbo].[ccCaMainGenderSelect]
(
	@ID INT
)
AS
BEGIN TRY
	SELECT Gender FROM CaMain WITH(NOLOCK) WHERE ID = @ID
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[ccCaMainIsDeleteUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ccCaMainIsDeleteUpdate]
	@OperatorID INT,
    @ID INT
AS
BEGIN TRAN
	IF @OperatorID=@ID
		RETURN 0

	BEGIN TRY
		IF EXISTS(
			SELECT a.ID FROM 
				caMain a WITH(NOLOCK),
				caMain b WITH(NOLOCK)
			WHERE a.cpMainID=b.cpMainID 
			AND a.AccountType=1 
			AND b.AccountType>1 
			AND a.ID=@OperatorID 
			AND b.ID=@ID
		)
		BEGIN
			UPDATE caMain SET IsDelete=1 WHERE ID=@ID
		END
	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH
COMMIT TRAN
RETURN 1
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END














GO
/****** Object:  StoredProcedure [dbo].[ccCaMainSave]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--====================================
--检查：	sean	2010-11-1
--修改harry 2018-1-23
--修改Carl 2018-02-11
--====================================
CREATE PROCEDURE  [dbo].[ccCaMainSave]
(
	@caMainID INT,
	@ID INT,
	@cpMainID INT,
	@AccountType INT,
	@UserName VARCHAR(20),
	@Password VARCHAR(60),
	@PlainPassword VARCHAR(40),
	@Name VARCHAR(12),
	@Gender BIT,
	@Title VARCHAR(40),
	@Dept VARCHAR(40),
	@Telephone VARCHAR(20),
	@Mobile VARCHAR(11),
	@Fax VARCHAR(20),
	@EMail VARCHAR(50),
	@QQ VARCHAR(13),
	@IsPhoneHide BIT,
	@IsNameHide BIT,
	@IsMobileHide BIT,
	@EmailSentType INT,
	@IsReceiveSMS BIT,
	@WeChat VARCHAR(20)
)
AS
SET NOCOUNT ON
IF @Telephone LIKE '00%'
	RETURN 0
BEGIN TRAN
	DECLARE @MaxID AS INT

	SET @Dept = dbo.TrimNULL(@Dept)
	SET @Title = dbo.TrimNULL(@Title)
	SET @Email = dbo.TrimNULL(@Email)
	SET @Telephone = dbo.TrimNULL(@Telephone)
	SET @Mobile = dbo.TrimNULL(@Mobile)
	SET @Fax = dbo.TrimNULL(@Fax)
	SET @QQ = dbo.TrimNULL(@QQ)
	IF @Telephone IS NULL
		SET @IsPhoneHide = 1
	IF @Mobile IS NULL
		SET @IsMobileHide = 1
	BEGIN TRY		
		SET @MaxID = 0
		IF @ID>0
			BEGIN
				DECLARE @MID AS INT 
				SELECT TOP 1 @MID=ID FROM caMain WITH(NOLOCK) WHERE cpMainID=@cpMainID AND AccountType=1 
				IF @caMainID=@ID OR @caMainID=@MID
					BEGIN
						DECLARE @NameOld AS NVARCHAR(60)
						DECLARE @TitleOld AS VARCHAR(MAX)
						DECLARE @DeptOld AS VARCHAR(MAX)
						SELECT @NameOld=RTRIM(ISNULL(Name, '')), @TitleOld=RTRIM(ISNULL(Title, '')), @DeptOld=RTRIM(ISNULL(Dept, ''))
							FROM caMain WITH(NOLOCK)
							WHERE ID=@ID

						--新增
						UPDATE caMain SET QQAddMan=0 WHERE ID=@ID AND QQ<>@QQ
						UPDATE caMain SET WeChatAddMan=0 WHERE ID=@ID AND WeChat<>@WeChat

						UPDATE caMain SET
							Name = @Name,
							Gender = @Gender,
							Title = @Title,
							Dept = @Dept,
							Telephone = @Telephone,
							Mobile = @Mobile,
							Fax = @Fax,
							EMail = @EMail,
							QQ = @QQ,
							IsPhoneHide = @IsPhoneHide,
							IsNameHide = @IsNameHide,
							IsMobileHide = @IsMobileHide,
							EmailSentType = @EmailSentType,
							IsReceiveSMS = @IsReceiveSMS,
							WeChat = @WeChat,
							LastModifyDate = GETDATE()
						WHERE ID=@ID

						
						SET @MaxID = @ID

						IF @NameOld <> RTRIM(@Name)
							BEGIN
								DELETE FROM bsCpModify WHERE caMainID=@ID AND Location='b1'
								INSERT INTO bsCpModify (cpMainID,caMainID,Location,ColValue) VALUES(@cpMainID, @ID,'b1', @Name)
							END
							
						IF RTRIM(@TitleOld) <> RTRIM(@Title)
							BEGIN
								DELETE FROM bsCpModify WHERE caMainID=@ID AND Location='b2'
								INSERT INTO bsCpModify (cpMainID,caMainID,Location,ColValue) VALUES(@cpMainID, @ID,'b2', @Title)
							END

						IF @DeptOld <> RTRIM(@Dept)
							BEGIN
								DELETE FROM bsCpModify WHERE caMainID=@ID AND Location='b3'
								INSERT INTO bsCpModify (cpMainID,caMainID,Location,ColValue) VALUES(@cpMainID, @ID,'b3', @Dept)
							END
						
						EXEC ccCaOperationLogInsert @ID, 18, '更新用户信息'

						--更新企业信息，maxjobnumber=1
--						IF EXISTS(SELECT 'x' FROM cpMain WITH(NOLOCK) WHERE ID = @cpMainID AND ISNULL(MaxJobNumber, 0) = 0)
--							UPDATE cpMain SET MaxJobNumber = 1 WHERE ID = @cpMainID
					END
				ELSE
					SET @MaxID = 0
			END
		ELSE
			BEGIN
				INSERT INTO caMain(
						RegDate, cpMainID, AccountType, UserName,Password,
						Name, Gender, Title, Dept, Telephone, Mobile,
						Fax, QQ, EMail, IsPhoneHide, IsNameHide, IsMobileHide,
						EmailSentType, IsReceiveSMS, LastModifyDate, WeChat
						)
				VALUES(
						GETDATE(), @cpMainID, @AccountType, @UserName, @Password,
						@Name, @Gender, @Title, @Dept, @Telephone, @Mobile,
						@Fax, @QQ, @EMail, @IsPhoneHide, @IsNameHide, @IsMobileHide,
						@EmailSentType, @IsReceiveSMS, GETDATE(), @WeChat
						)
				SET @MaxID = (SELECT TOP 1 ID FROM caMain WITH(NOLOCK) WHERE cpMAinID = @cpMainID ORDER BY ID DESC)
				INSERT INTO caPlainPassword(caMainID,PlainPassword) VALUES(@MaxID,@PlainPassword) 
				INSERT INTO bsCpModify(cpMainID, caMainID, Location, ColValue) VALUES(@cpMainID, @MaxID, 'b1', @Name)
		 		IF @Title IS NOT NULL
					INSERT INTO bsCpModify (cpMainID,caMainID,Location,ColValue) VALUES(@cpMainID, @MaxID,'b2', @Title)
				IF @Dept IS NOT NULL
					INSERT INTO bsCpModify (cpMainID,caMainID,Location,ColValue) VALUES(@cpMainID, @MaxID,'b3', @Dept)
			END
			
			IF EXISTS(SELECT TOP 1 'X' FROM caVerifyLog WHERE VerifyDate > DATEAdd(n, -1, GETDATE()) AND Mobile = @Mobile)
				UPDATE caMain SET MobileVerifyDate = GETDATE() WHERE ID = @MaxID
			--ELSE--harry 2018-1-23 C#代码已处理，修改操作也都是认证了的，在不修改手机号的保存用户的情况下会重复认证
			--	UPDATE caMain SET MobileVerifyDate = NULL WHERE ID = @MaxID
	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH
COMMIT TRAN
RETURN @MaxID
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END

GO
/****** Object:  StoredProcedure [dbo].[ccCaMainSecondPasswordByIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.30
--创建人：Nick
--说明：获取用户的保护密码
--#####################################################
CREATE PROCEDURE [dbo].[ccCaMainSecondPasswordByIDSelect]
(
	@ID INT
)
AS
BEGIN TRY
	SELECT SecondPassword FROM caMain WHERE id=@ID 
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[ccCaMainSecondPasswordByIDUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.30
--创建人：Nick
--说明：修改用户的保护密码
--#####################################################
CREATE PROCEDURE [dbo].[ccCaMainSecondPasswordByIDUpdate]
(
	@ID INT,
	@Password VARCHAR(60)
)
AS
BEGIN TRY
	UPDATE caMain SET SecondPassword = @Password WHERE ID=@ID
	UPDATE cpMain SET IsProtect=1 WHERE ID=(SELECT cpMainID FROM caMain WITH(NOLOCK) WHERE ID = @ID)
	RETURN 1 
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[ccCaMainSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--##################################
--检查：  sean 201011-19  
--##################################
CREATE PROCEDURE [dbo].[ccCaMainSelect]  
(
	@ID INT
)
AS
BEGIN
	SELECT *,
		(SELECT TOP 1 ID 
		FROM paLoginContact WITH(NOLOCK)
		WHERE paMainID = @ID AND ContactType = 101) IsWeixinBind   
	FROM caMain WITH(NOLOCK)      
	WHERE ID = @ID
	AND IsDelete = 0  
END
GO
/****** Object:  StoredProcedure [dbo].[ccCaMainUserNameExist]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--==================================
--UserName已经存在
--检查：	sean	2010-10-22
--==================================
CREATE PROCEDURE [dbo].[ccCaMainUserNameExist]
(
	@UserName VARCHAR(20)
)
AS
BEGIN
	BEGIN TRY
		SET @UserName = LTRIM(RTRIM(@UserName))
		IF EXISTS(SELECT ID FROM caMain WITH(NOLOCK) WHERE UserNameLower = @UserName)
			RETURN 1
		ELSE IF EXISTS(SELECT ID FROM Company_xinxi WITH(NOLOCK) WHERE UserNameLower = @UserName)
			RETURN 1

		RETURN 0
	END TRY
	BEGIN CATCH
		RETURN 0
	END CATCH
END














GO
/****** Object:  StoredProcedure [dbo].[ccCaOperationLogByCaMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--lambo 20110114
--用于企业模块，查询用户自己的操作记录
CREATE PROCEDURE [dbo].[ccCaOperationLogByCaMainIDSelect]
(
    @caMainID INT
)
AS
BEGIN
    SELECT * FROM caOperationLog WITH(NOLOCK)
    WHERE  caMainID=@caMainID
	ORDER BY ID DESC
END














GO
/****** Object:  StoredProcedure [dbo].[ccCaOperationLogByCpMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--lambo 20110114
--用于企业部分，管理员查询所有用户的操作记录
CREATE PROCEDURE [dbo].[ccCaOperationLogByCpMainIDSelect]
(
    @cpMainID INT
)
AS
BEGIN
    SELECT a.*,b.Name,b.Telephone FROM caOperationLog a WITH(NOLOCK),caMain b WITH(NOLOCK)
    WHERE a.caMainID = b.ID 
		AND b.cpMainID=@cpMainID
	ORDER BY a.ID DESC
END


GO
/****** Object:  StoredProcedure [dbo].[ccCaOperationLogByIpInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ccCaOperationLogByIpInsert]
(
	@caMainID AS INT,
	@Operation AS INT,
	@Details AS NVARCHAR(200),
	@IP AS VARCHAR(31)
)
AS
SET NOCOUNT ON
BEGIN
	INSERT INTO CaOperationLog(caMainID, Operation, Details, IP)
	VALUES(@caMainID, @Operation, @Details, @IP)
END














GO
/****** Object:  StoredProcedure [dbo].[ccCaOperationLogInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ccCaOperationLogInsert]
(
	@caMainID AS INT,
	@Operation AS INT,
	@Details AS NVARCHAR(200)
)
AS
BEGIN
	DECLARE @IP AS VARCHAR(31)
	SELECT TOP 1 @IP = LoginIP FROM caLoginLog WITH(NOLOCK) WHERE caMainID = @caMainID ORDER BY ID DESC

	IF @IP IS NULL
	BEGIN
		DECLARE @cpMainID AS INT, @ManagerID AS INT, @RegIP AS VARCHAR(31)
		SELECT @cpMainID = a.ID, @RegIP = a.RegisterIP
		FROM cpMain a WITH(NOLOCK)
		INNER JOIN caMain b WITH(NOLOCK) ON a.ID = b.cpMainID
		WHERE b.ID = @caMainID

		SELECT @ManagerID = ID FROM caMain WITH(NOLOCK) WHERE cpMainID = @cpMainId AND AccountType = 1
		SELECT TOP 1 @IP = LoginIP FROM caLoginLog WITH(NOLOCK) WHERE caMainID = @ManagerID ORDER BY ID DESC
		IF @IP IS NULL
			SET @IP = @RegIP
	END
	IF @IP IS NULL
		SET @IP= ''

	INSERT INTO CaOperationLog(caMainID, Operation, Details, IP)
	VALUES(@caMainID, @Operation, @Details, @IP)
END














GO
/****** Object:  StoredProcedure [dbo].[cccaOrderByAllUsedSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[cccaOrderByAllUsedSelect]
(
	@cpMainID INT
)
AS
BEGIN
	SELECT ID, OrderType, jobRefreshQuota  FROM caOrder a 
		WHERE a.cpMainID = @cpMainID 
		AND (a.OrderType = 8 Or a.OrderType = 9 Or a.OrderType = 14 Or a.OrderType = 15)
		AND a.BeginDate < GETDATE() AND IsDeleted=0
		ORDER BY a.endDate
END
GO
/****** Object:  StoredProcedure [dbo].[cccaOrderByAllValidSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--20110309 lambo
--查询该企业所有有效的VIP套餐订单
--修改：harry,只显示订单OrderStatus=4的2016-4-7
--修改：harry 增加短信数显示2017-6-5
CREATE PROCEDURE [dbo].[cccaOrderByAllValidSelect]
(
	@cpMainID INT
)
AS
SET NOCOUNT ON
BEGIN
	SELECT a.ID, a.beginDate, a.endDate,
		(SELECT ISNULL(SUM(ActiveQuota),0) FROM caOrder WITH(NOLOCK) WHERE MainOrderID=a.ID AND EndDate >GETDATE())+ActiveQuota caActiveQuota,
		(SELECT ISNULL(SUM(RemainQuota),0) FROM caOrder WITH(NOLOCK) WHERE MainOrderID=a.ID AND EndDate >GETDATE())+RemainQuota caRemainQuota,
		(SELECT ISNULL(SUM(UserNumber),0) FROM caOrder WITH(NOLOCK) WHERE MainOrderID=a.ID AND EndDate >GETDATE())+UserNumber caUserNumber,
		(SELECT ISNULL(SUM(JobNumber),0) FROM caOrder WITH(NOLOCK) WHERE MainOrderID=a.ID AND EndDate >GETDATE())+JobNumber caJobNumber,
		(SELECT ISNULL(SUM(RemainSmsQuota),0) FROM caOrder WITH(NOLOCK) WHERE MainOrderID=a.ID AND EndDate >GETDATE())+RemainSmsQuota caSmsNumber
	FROM caOrder a 
	WHERE a.cpMainID = @cpMainID 
	AND a.OrderType = 8 
	AND a.IsDeleted = 0
	AND a.EndDate > GETDATE()
END
SET NOCOUNT OFF

GO
/****** Object:  StoredProcedure [dbo].[ccCaOrderByIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-------------------------------------------------------------------------------------------------------------------
--lambo 20110309 修改
--将INNER JOIN 改为LEFT JOIN, 原因是考虑上门付款的
--[ccCaOrderByIDSelect] 265475
--mice 2014-8-21 修改， 添加返回值： a.PaidCoin, a.PaidPoint
--修改harry 2017-6-6 增加短信订单a.SmsQuota,RemainSmsQuota
--修改harry 2017-10-24 增加职位刷新remainJobRefreshQuota
--修改harry 2018-9-21 增加人才测评
CREATE PROCEDURE [dbo].[ccCaOrderByIDSelect]
(
	@ID INT
)
AS
SET NOCOUNT ON
BEGIN
	DECLARE @InvoiceCompany INT, @cpMainId INT
	SELECT @InvoiceCompany = InvoiceCompany, @cpMainId = cpMainId FROM caOrder WITH(NOLOCK) WHERE Id = @Id
	IF @InvoiceCompany IS NULL
	BEGIN
		DECLARE @regionId VARCHAR(6)
		SELECT @RegionId = dcRegionId FROM cpMain WITH(NOLOCK) WHERE Id = @cpMainId
		IF LEFT(@RegionId, 2) NOT IN(30, 32)
			SET @InvoiceCompany = 2
		ELSE IF LEFT(@RegionId, 4) IN ('3214', '3217')
			SET @InvoiceCompany = 2
                ELSE IF LEFT(@RegionId, 4) IN ('3201', '3205')
			SET @InvoiceCompany = 5
		ELSE
			SET @InvoiceCompany = 4
	END

	SELECT a.ID, a.cpMainId, a.ProvinceID, a.dcFeeDetailID, a.ServiceType, a.PlaceWeek, a.PayMethod, 
		a.OrderType, a.Accounts, a.Paid, a.Balance, a.LinkMan, 
		a.Telephone, a.LinkRemark, a.MailAddress, a.Recipient, a.Zip, a.FaxFile, 
		a.CompanyName, a.RemittanceFile, a.RemittanceDate, a.SmsMobileNumber, 
		a.PostTelephone, a.ReceiveDate, a.NeedInvoice, a.InvoiceTitle, 
		a.InvoiceMonth, a.InvoiceCompany, a.InvoiceConfirmDate, a.ReceiveMan, 
		a.InvoiceConfirmMan, a.InvoiceAskDate, a.ContractFile, a.Manageruserid, a.IsDeleted, 
		a.DeletedMan, a.DeletedDate, a.OpenMan, a.OpenDate, a.BeginDate, 
		a.EndDate, a.AddDate, a.ActiveQuota, a.RemainQuota, a.JobNumber, a.UserNumber, a.MainOrderID, a.jobRefreshQuota, a.remainJobRefreshQuota, a.AssessReportQuota, a.RemainAssessReportQuota,
		a.Tariff, a.RegisterAddress, a.RegisterTel, a.BankName, a.BankAccount, 
		a.PaidCoin, a.PaidPoint, a.SmsQuota, a.RemainSmsQuota, b.JointNo, 
		b.PayMethodID, c.Name as PayMethodName, b.Receiver, b.Account, b.BankName BankNamePre, a.OrderStatus, c.Homepage
	FROM caOrder a WITH(NOLOCK) 
	LEFT JOIN dcPayMethodProvince b WITH(NOLOCK) ON a.PayMethod = b.PayMethodID 
	--AND b.dcProvinceID = CASE WHEN LEFT(a.ProvinceID, 2) = 32 AND InvoiceCompany = 2 THEN 10 ELSE LEFT(a.ProvinceID, 2) END
	AND b.dcProvinceID = CASE @InvoiceCompany WHEN 4 THEN 30 WHEN 5 THEN 3201 ELSE 10 END
	LEFT JOIN dcPayMethod c WITH(NOLOCK) ON a.PayMethod = c.PayMethodID
	WHERE a.ID = @ID
END
SET NOCOUNT OFF

GO
/****** Object:  StoredProcedure [dbo].[ccCaOrderByJobIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.04
--创建人：Nick
--说明：获取职位置顶状态
--#####################################################
CREATE PROCEDURE [dbo].[ccCaOrderByJobIDSelect]
(
	@JobID VARCHAR(20)
)
AS
BEGIN TRY
	SELECT TOP 1 * 
	FROM caorder WITH(NOLOCK) 
	WHERE Balance = @JobID 
	AND OrderType=12 
	AND EndDate > GETDATE() 
	AND BeginDate < GETDATE()
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[ccCaorderByremainJobRefreshQuotaSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--创建：harry
--时间：2017-10-19
--说明：获取企业可用的职位刷新数（手动刷新）
CREATE PROCEDURE [dbo].[ccCaorderByremainJobRefreshQuotaSelect]
(
	@cpMainId INT,
	@caMainId INT,
	@jobIds VARCHAR(200)
)
AS
BEGIN
SET NOCOUNT ON
	
	--删除2分钟以上同一家企业的数据
	DELETE FROM JobRefreshLog_temp WHERE AddDate < DATEADD(MINUTE, -2, GETDATE()) AND cpMainId = @cpMainId

	DECLARE @sumRemain INT,@jobId INT, @jobinfo NVARCHAR(200),@InsertRow INT
	
	SELECT @sumRemain = sum(remainJobRefreshQuota)
	FROM caOrder WITH(NOLOCK)
	WHERE cpMainID = @cpMainId
	AND openDate IS NOT NULL
	AND endDate > GETDATE()
	AND BeginDate < GETDATE()
	AND IsDeleted = 0
	AND OrderType IN(8, 15)	
	
	IF @sumRemain != 0
	BEGIN
		DELETE FROM JobRefreshLog_temp WHERE cpMainId = @cpMainId AND operateMan = @caMainId--清空数据,只能清除自己添加的
	
		--职位id
		DECLARE @TjobId AS TABLE(jobId INT, jobInfo NVARCHAR(200)) 
		INSERT INTO @TjobId (jobId)
		SELECT * FROM dbo.fnSplit(@jobIds, ',') 
 
		--更新职位信息
		UPDATE @TjobId
		SET jobInfo= (SELECT name+','+ b.FullName FROM job a WITH(NOLOCK), dcregion b WITH(NOLOCK) WHERE a.id = jobId AND a.dcregionid = b.id)
		
		--插入此次手动刷新的
		 
		INSERT INTO JobRefreshLog_temp(jobid, jobInfo, refreshType, preRefreshDateTime, operateMan, cpMainId, AddDate)
		SELECT a.jobId, a.jobinfo, 1, getDate(), @caMainId, @cpMainId, GETDATE()
		FROM  @TjobId a 
		
		SELECT @InsertRow = @@ROWCOUNT 

		DECLARE @NeedQuota INT, @remainJobRefreshQuota INT, @AllInsertRow INT
		 
		SELECT @AllInsertRow =count(*) from jobrefreshlog_temp where cpmainid = @cpmainid and runDateTime is null
		SELECT @NeedQuota = count(*) from jobrefreshlog where cpmainid = @cpmainid and runDateTime is null
		SELECT @remainJobRefreshQuota = sum(remainJobRefreshQuota) 
		FROM caorder WITH(NOLOCK) 
		WHERE cpmainid = @cpmainid 
		AND ordertype in(8, 15) AND isdeleted=0 AND opendate > '' AND getdate() BETWEEN begindate AND enddate 
		--计算可用数量
		IF (@NeedQuota +@AllInsertRow)> @remainJobRefreshQuota
		BEGIN 
			SELECT (@remainJobRefreshQuota-(@NeedQuota+@AllInsertRow-@InsertRow)) AS availableNumber
		END
		ELSE
		BEGIN
			SELECT (@remainJobRefreshQuota-@NeedQuota)  AS availableNumber
		END 
		 
	END
	ELSE
	BEGIN
		SELECT 0 AS availableNumber	
	END
SET NOCOUNT OFF
END 

GO
/****** Object:  StoredProcedure [dbo].[ccCaOrderDelete]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Peter
-- Create date: 2014-08-20 09:55
-- Description:	取消订单 -- Mice 2014-10-8 修改： 增加订单取消的原因
-- 修改：harry 修改积分和金币能够同时返还ELSE IF @UseCoin > 0---改为->IF @UseCoin > 0 2015-7-7
-- =============================================
CREATE PROCEDURE [dbo].[ccCaOrderDelete]
(
	@caOrderID INT, 
	@cpMainID INT, 
	@cancelReason  NVARCHAR(70) = ''
)
AS
SET NOCOUNT ON
BEGIN TRAN
	BEGIN TRY
		IF NOT EXISTS(SELECT 'x' FROM caOrder WITH(NOLOCK) 
			WHERE cpMainID = @cpMainID AND ID = @caOrderID AND OrderStatus = 0 AND IsDeleted = 0 AND FaxFile IS NULL)
			GOTO ERR  --检查该订单的有效性

		DECLARE @UsePoint AS INT, @UseCoin AS INT, @GivePoint INT

		--是否是积分订单
		SELECT @UsePoint = PaidPoint, @GivePoint = GivePoint, @UseCoin = PaidCoin FROM caOrder WITH(NOLOCK) WHERE ID = @caOrderID
		IF @UsePoint > 0  --积分订单
		BEGIN
			--插入积分记录
			INSERT INTO cpPoint (cpMainID, changeID, point, relativeID, lastModifyDate)
			VALUES(@cpMainID, 16, @UsePoint, @caOrderID, GETDATE())
		END

		IF @GivePoint > 0  --积分订单
		BEGIN
			--插入积分记录
			INSERT INTO cpPoint (cpMainID, changeID, point, relativeID, lastModifyDate)
			VALUES(@cpMainID, 24, @GivePoint * -1, @caOrderID, GETDATE())
		END

		--Harry
		IF @UseCoin > 0
			--插入金币记录
		BEGIN
			IF (SELECT COUNT(*) FROM cpCoin WITH(NOLOCK) WHERE caOrderId = @caOrderID) = 1
			BEGIN
				DECLARE @RemainCoin INT
				SELECT @RemainCoin = ISNULL(RemainCoin, 0) FROM cpMain WITH(NOLOCK) WHERE Id = @cpMainID

				INSERT INTO cpCoin(cpMainId, caOrderId, Coin, IsCancel, Balance, AddDate)
				SELECT @cpMainId, @caOrderID, @UseCoin, 1, @UseCoin + @RemainCoin, GETDATE()
			END
		END
		--删除订单
		UPDATE caOrder SET IsDeleted = 1 , CancelReason = @cancelReason  WHERE ID = @caOrderID
	
	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH
COMMIT TRAN
	RETURN 1
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END 
GO
/****** Object:  StoredProcedure [dbo].[ccCaOrderEndDateByCpMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.6
--创建人：John
--说明：获取会员订单的到期时间
--#####################################################
CREATE PROCEDURE [dbo].[ccCaOrderEndDateByCpMainIDSelect]
(
	@cpMainID INT
)
AS
BEGIN
	SELECT EndDate FROM caOrder 
	WHERE cpMainID = @cpMainID 
		AND OrderType IN (1,2,8) 
		AND EndDate >= GETDATE() - 62 
		AND OpenDate IS NOT NULL 
		AND IsDeleted = 0	
END


GO
/****** Object:  StoredProcedure [dbo].[ccCaOrderFaxFileUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ccCaOrderFaxFileUpdate]
(
	@ID INT,
	@FaxFile VARCHAR(50)
)
AS
BEGIN
	UPDATE caOrder SET FaxFile=@FaxFile WHERE ID=@ID
END














GO
/****** Object:  StoredProcedure [dbo].[ccCaOrderInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = 
-- Author:		Peter
-- Create date: 2014-08-20 09:55
-- Description:	
-- Modify:      Harry 2015-7-10
-- Description:修改needpoint为从dcfeedetail中取出(282行)
-- Modify:      Harry 修改一年内最大积分数不能超过qlrc  @MaxPoint=20000
--				Other Site @MaxPoint＝10000
-- = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = 
CREATE PROCEDURE [dbo].[ccCaOrderInsert]
(
	@cpMainID INT, 
	@IsAgent BIT, 
	@ProvinceID INT, 
	@ServiceType INT = NULL, 
	@PlaceWeek TINYINT = NULL, 
	@PayMethod TINYINT, 
	@OrderType TINYINT, 
	@Accounts NUMERIC(18, 2), 
	@Paid NUMERIC(18, 2), 
	@Balance NUMERIC(18, 2) = NULL, 
	@LinkMan NVARCHAR(50), 
	@Telephone VARCHAR(50), 
	@LinkRemark NVARCHAR(1000), 
	@Manageruserid SMALLINT, 
	@ActiveQuota SMALLINT = NULL, 
	@JobNumber SMALLINT = NULL, 
	@CompanyName VARCHAR(100), 
	@MainOrderID INT = NULL, 
	@InvoiceCompany SMALLINT, 
	@UserNumber SMALLINT = NULL, 
	@dcFeeDetailsID INT = NULL, 
	@UseCoin INT = NULL, 
	@UsePoint INT = NULL
)
AS
SET NOCOUNT ON
BEGIN TRAN
	DECLARE @MaxId AS INT, @MaxPoint AS INT, @Type INT
	IF LEFT(@ProvinceID, 2) = 32
		SELECT @MaxPoint = 20000--设置1年内最大积分兑换额度
	ELSE
		SELECT @MaxPoint = 10000--设置1年内最大积分兑换额度

	BEGIN TRY
		IF @OrderType = 8 
		BEGIN
			IF NOT EXISTS(SELECT 'x' FROM dcVip a WITH(NOLOCK), dcVipDetail b WITH(NOLOCK) 
				WHERE a.ID = b.dcVipID AND a.dcProvinceID = LEFT(@ProvinceID, 2)
				AND b.ID = @dcFeeDetailsID	AND a.startDate<GETDATE() AND a.endDate > GETDATE())
				GOTO ERR	--检查是否套餐已过期
			SELECT @Accounts = (b.PriceMonth * a.[Month]+a.ResumeNumber*b.PriceResume+JobNumber*b.PriceJob+UserNumber*b.PriceUser), 
				@Paid = a.Price, @ActiveQuota = a.ResumeNumber, @JobNumber = a.JobNumber, @UserNumber = a.UserNumber 
			FROM dcVipDetail a WITH(NOLOCK), dcVip b WITH(NOLOCK)
			WHERE a.ID = @dcFeeDetailsID
			AND StartDate < GETDATE() AND EndDate > = GETDATE()
			AND a.dcVipID = b.ID			
		END 
		ELSE IF @OrderType = 4 AND @ServiceType = 6			----根据周数查询1/6广告的资费信息
		BEGIN
			SET @Type = 4
			SELECT TOP 1 @Accounts = b.Price * @PlaceWeek, 
				@Paid = a.Price * @PlaceWeek, 
				@dcFeeDetailsID = a.ID
			FROM dcFeeDetail a WITH(NOLOCK), dcFee b WITH(NOLOCK)
			WHERE a.dcFeeID = b.ID
			AND b.dcProvinceID = LEFT(@ProvinceID, 2)
			AND b.Type = @Type
			AND StartDate < GETDATE() AND EndDate > = GETDATE()
			AND ((MinValue< = @PlaceWeek AND MaxValue> = @PlaceWeek) OR (MinValue< = @PlaceWeek AND MaxValue = 0))

			IF @dcFeeDetailsID IS NULL
				SELECT TOP 1 @Accounts = Price, 	@Paid = Price * @PlaceWeek
				FROM dcFee WITH(NOLOCK)
				WHERE Type = @Type
				AND dcProvinceID = LEFT(@ProvinceID, 2)
				AND StartDate < GETDATE() AND EndDate > = GETDATE()
		END
		ELSE IF @OrderType = 4 AND @ServiceType = 7			----根据周数查询2/6广告的资费信息
		BEGIN
			SET @Type = 5
			SELECT TOP 1 @Accounts = b.Price * @PlaceWeek, 
				@Paid = a.Price * @PlaceWeek, 
				@dcFeeDetailsID = a.ID
			FROM dcFeeDetail a WITH(NOLOCK), dcFee b WITH(NOLOCK)
			WHERE b.Type = @Type
			AND b.dcProvinceID = LEFT(@ProvinceID, 2)
			AND StartDate < GETDATE() AND EndDate > = GETDATE()
			AND ((MinValue< = @PlaceWeek AND MaxValue> = @PlaceWeek) OR (MinValue< = @PlaceWeek AND MaxValue = 0))
			AND a.dcFeeID = b.ID

			IF @dcFeeDetailsID IS NULL
				SELECT TOP 1 @Accounts = Price, 	@Paid = Price * @PlaceWeek
				FROM dcFee  WITH(NOLOCK)
				WHERE Type = @Type
				AND dcProvinceID = LEFT(@ProvinceID, 2)
				AND StartDate < GETDATE() AND EndDate > = GETDATE()
		END
		ELSE IF @OrderType = 4 AND @ServiceType = 8			----根据周数查询3/6广告的资费信息
		BEGIN
			SET @Type = 20
			SELECT TOP 1 @Accounts = b.Price * @PlaceWeek, 
				@Paid = a.Price * @PlaceWeek, 
				@dcFeeDetailsID = a.ID
			FROM dcFeeDetail a WITH(NOLOCK), dcFee b WITH(NOLOCK)
			WHERE b.Type = @Type
			AND b.dcProvinceID = LEFT(@ProvinceID, 2)
			AND StartDate < GETDATE() AND EndDate > = GETDATE()
			AND ((MinValue< = @PlaceWeek AND MaxValue> = @PlaceWeek) OR (MinValue< = @PlaceWeek AND MaxValue = 0))
			AND a.dcFeeID = b.ID

			IF @dcFeeDetailsID IS NULL
				SELECT TOP 1 @Accounts = Price, 	@Paid = Price * @PlaceWeek
				FROM dcFee  WITH(NOLOCK)
				WHERE Type = @Type
				AND dcProvinceID = LEFT(@ProvinceID, 2)
				AND StartDate < GETDATE() AND EndDate > = GETDATE()
	 	END
		ELSE IF @OrderType = 4 AND @ServiceType = 9			----根据周数查询6/6广告的资费信息
		BEGIN
			SET @Type = 21
			SELECT TOP 1 @Accounts = b.Price * @PlaceWeek, 
				@Paid = a.Price * @PlaceWeek, 
				@dcFeeDetailsID = a.ID
			FROM dcFeeDetail a WITH(NOLOCK), dcFee b WITH(NOLOCK)
			WHERE b.Type = @Type
			AND b.dcProvinceID = LEFT(@ProvinceID, 2)
			AND StartDate < GETDATE() AND EndDate > = GETDATE()
			AND ((MinValue< = @PlaceWeek AND MaxValue> = @PlaceWeek) OR (MinValue< = @PlaceWeek AND MaxValue = 0))
			AND a.dcFeeID = b.ID

			IF @dcFeeDetailsID IS NULL
				SELECT TOP 1 @Accounts = Price, 	@Paid = Price * @PlaceWeek
				FROM dcFee  WITH(NOLOCK)
				WHERE Type = @Type
				AND dcProvinceID = LEFT(@ProvinceID, 2)
				AND StartDate < GETDATE() AND EndDate > = GETDATE()
		END
		ELSE IF @OrderType = 4 AND @ServiceType = 10			----根据周数查询6/6广告的资费信息
		BEGIN
			SET @Type = 23
			SELECT TOP 1 @Accounts = b.Price * @PlaceWeek, 
				@Paid = a.Price * @PlaceWeek, 
				@dcFeeDetailsID = a.ID
			FROM dcFeeDetail a WITH(NOLOCK), dcFee b WITH(NOLOCK)
			WHERE b.Type = @Type
			AND b.dcProvinceID = LEFT(@ProvinceID, 2)
			AND StartDate < GETDATE() AND EndDate > = GETDATE()
			AND ((MinValue< = @PlaceWeek AND MaxValue> = @PlaceWeek) OR (MinValue< = @PlaceWeek AND MaxValue = 0))
			AND a.dcFeeID = b.ID

			IF @dcFeeDetailsID IS NULL
				SELECT TOP 1 @Accounts = Price, 	@Paid = Price * @PlaceWeek
				FROM dcFee  WITH(NOLOCK)
				WHERE Type = @Type
				AND dcProvinceID = LEFT(@ProvinceID, 2)
				AND StartDate < GETDATE() AND EndDate > = GETDATE()
		END
		ELSE IF @OrderType = 7								----根据周数查询固定位置的资费信息
		BEGIN
			SET @Type = 7
			SELECT TOP 1 @Accounts = b.Price * @PlaceWeek, 
				@Paid = a.Price * @PlaceWeek, 
				@dcFeeDetailsID = a.ID
			FROM dcFeeDetail a WITH(NOLOCK), dcFee b WITH(NOLOCK)
			WHERE b.Type = @Type
			AND a.dcFeeID = b.ID
			AND b.dcProvinceID = LEFT(@ProvinceID, 2)
			AND ((MinValue< = @PlaceWeek AND MaxValue> = @PlaceWeek) OR (MinValue< = @PlaceWeek AND MaxValue = 0))
			AND StartDate < GETDATE() AND EndDate > = GETDATE()

			IF @dcFeeDetailsID IS NULL
				SELECT TOP 1 @Accounts = Price, 	@Paid = Price * @PlaceWeek
				FROM dcFee  WITH(NOLOCK)
				WHERE Type = @Type
				AND dcProvinceID = LEFT(@ProvinceID, 2)
				AND StartDate < GETDATE() AND EndDate > = GETDATE()
		END
		ELSE IF @OrderType = 9 								----简历下载
		BEGIN
			SET @Type = 9
			SELECT TOP 1 @Accounts = b.Price * @ActiveQuota, 
				@Paid = a.Price * @ActiveQuota, 
				@dcFeeDetailsID = a.ID
			FROM dcFeeDetail a WITH(NOLOCK), dcFee b WITH(NOLOCK)
			WHERE b.Type = @Type
			AND a.dcFeeID = b.ID
			AND ((MinValue< = @ActiveQuota AND MaxValue> = @ActiveQuota) OR (MinValue< = @ActiveQuota AND MaxValue = 0))
			AND StartDate < GETDATE() AND EndDate > GETDATE() 

			IF @dcFeeDetailsID IS NULL
				SELECT TOP 1 @Accounts = Price, 	@Paid = Price * @ActiveQuota
				FROM dcFee  WITH(NOLOCK)
				WHERE Type = @Type
				AND dcProvinceID = LEFT(@ProvinceID, 2)
				AND StartDate < GETDATE() AND EndDate > GETDATE()
		END
		ELSE IF @OrderType = 10 								----职位数
		BEGIN
			SET @Type = 10
			SELECT TOP 1 @Accounts = b.Price * @JobNumber, 
				@Paid = a.Price * @JobNumber, 
				@dcFeeDetailsID = a.ID
			FROM dcFeeDetail a WITH(NOLOCK), dcFee b WITH(NOLOCK)
			WHERE b.Type = @Type
			AND a.dcFeeID = b.ID
			AND b.dcProvinceID = LEFT(@ProvinceID, 2)
			AND ((MinValue< = @JobNumber AND MaxValue> = @JobNumber) OR (MinValue< = @JobNumber AND MaxValue = 0))
			AND StartDate < GETDATE() AND EndDate > GETDATE()

			IF @dcFeeDetailsID IS NULL
				SELECT TOP 1 @Accounts = Price, 	@Paid = Price * @JobNumber
				FROM dcFee  WITH(NOLOCK)
				WHERE Type = @Type
				AND dcProvinceID = LEFT(@ProvinceID, 2)
				AND StartDate < GETDATE() AND EndDate > GETDATE()
		END		
		ELSE IF @OrderType = 11								----用户数
		BEGIN
			SET @Type = 11
			SELECT TOP 1 @Accounts = b.Price * @UserNumber, 
				@Paid = a.Price * @UserNumber, 
				@dcFeeDetailsID = a.ID
			FROM dcFeeDetail a WITH(NOLOCK), dcFee b WITH(NOLOCK)
			WHERE b.Type = @Type
			AND a.dcFeeID = b.ID
			AND b.dcProvinceID = LEFT(@ProvinceID, 2) 
			AND ((MinValue< = @UserNumber AND MaxValue> = @UserNumber) OR (MinValue< = @UserNumber AND MaxValue = 0))
			AND StartDate < GETDATE() AND EndDate > GETDATE()

			IF @dcFeeDetailsID IS NULL
				SELECT TOP 1 @Accounts = Price, 	@Paid = Price * @UserNumber
				FROM dcFee  WITH(NOLOCK)
				WHERE Type = @Type
				AND dcProvinceID = LEFT(@ProvinceID, 2)
				AND StartDate < GETDATE() AND EndDate > GETDATE() 
		END
		ELSE IF @OrderType = 12			----根据周数职位置顶资费信息
		BEGIN
			SET @Type = 22
			SELECT TOP 1 @Accounts = b.Price * @PlaceWeek, 
				@Paid = a.Price * @PlaceWeek, 
				@dcFeeDetailsID = a.ID
			FROM dcFeeDetail a WITH(NOLOCK), dcFee b WITH(NOLOCK)
			WHERE b.Type = @Type
			AND b.dcProvinceID = LEFT(@ProvinceID, 2)
			AND StartDate < GETDATE() AND EndDate > = GETDATE()
			AND ((MinValue< = @PlaceWeek AND MaxValue> = @PlaceWeek) OR (MinValue< = @PlaceWeek AND MaxValue = 0))
			AND a.dcFeeID = b.ID

			IF @dcFeeDetailsID IS NULL
				SELECT TOP 1 @Accounts = Price, 	@Paid = Price * @PlaceWeek
				FROM dcFee  WITH(NOLOCK)
				WHERE Type = @Type
				AND dcProvinceID = LEFT(@ProvinceID, 2)
				AND StartDate < GETDATE() AND EndDate > = GETDATE()
		END
		ELSE IF @OrderType = 13			----根据周数职位置顶资费信息
		BEGIN
			SET @Type = 24
			SELECT TOP 1 @Accounts = b.Price * @PlaceWeek, 
				@Paid = a.Price * @PlaceWeek, 
				@dcFeeDetailsID = a.ID
			FROM dcFeeDetail a WITH(NOLOCK), dcFee b WITH(NOLOCK)
			WHERE b.Type = @Type
			AND b.dcProvinceID = LEFT(@ProvinceID, 2)
			AND StartDate < GETDATE() AND EndDate > = GETDATE()
			AND ((MinValue< = @PlaceWeek AND MaxValue> = @PlaceWeek) OR (MinValue< = @PlaceWeek AND MaxValue = 0))
			AND a.dcFeeID = b.ID

			IF @dcFeeDetailsID IS NULL
				SELECT TOP 1 @Accounts = Price, 	@Paid = Price * @PlaceWeek
				FROM dcFee  WITH(NOLOCK)
				WHERE Type = @Type
				AND dcProvinceID = LEFT(@ProvinceID, 2)
				AND StartDate < GETDATE() AND EndDate > = GETDATE()
		END

		IF @MainOrderID IS NOT NULL
			IF NOT EXISTS(SELECT 'x' FROM caOrder WITH(NOLOCK) WHERE cpMainID = @cpMainID AND ID = @MainOrderID  AND OrderType = 8 AND EndDate >GETDATE())
				AND @OrderType in (9, 10, 11)
				GOTO ERR	--检查是否是自己有效的主订单号
		
		DECLARE @CoinBalance AS INT
		DECLARE @PointBalance AS INT
		
		IF @UseCoin IS NOT NULL
		BEGIN
			IF NOT EXISTS(SELECT 'x' FROM cpMain WHERE ID = @cpMainID AND RemainCoin > = @UseCoin)
				GOTO ERR	--检查剩余金币数量是否足够支付

			SET @Paid = @Paid - @UseCoin
		END
		
		IF @UsePoint IS NOT NULL --积分支付
		BEGIN
			DECLARE @NeedPoint INT, @dcFeeDetailsID2 INT, @SumPoint AS INT
			SELECT @NeedPoint = NeedPoint FROM dcfeedetail WHERE Id = @dcFeeDetailsID
			IF @NeedPoint IS NULL
			BEGIN
				SELECT TOP 1 @dcFeeDetailsID2 = a.ID
				FROM dcFeeDetail a WITH(NOLOCK), dcFee b WITH(NOLOCK)
				WHERE b.Type = @Type
				AND b.dcProvinceID = LEFT(@ProvinceID, 2)
				AND StartDate < GETDATE() AND EndDate > = GETDATE()
				AND a.NeedPoint > 0
				AND a.dcFeeID = b.ID

				SELECT @NeedPoint = NeedPoint FROM dcfeedetail WHERE id = @dcFeeDetailsID2
			END

			IF @OrderType IN(4, 7, 12, 13)
			BEGIN
				SET @UsePoint = @NeedPoint * @PlaceWeek
			END
			ELSE
			BEGIN
				SET @UsePoint = @NeedPoint
			END
			--积分兑换的积分数是否超过最大数值
			SELECT @SumPoint = SUM(PaidPoint)
			FROM caOrder
			WHERE cpMainid = @cpMainID
			AND IsDeleted = 0			--未删除
			AND ISNULL(Paid, 0) = 0		--付款为0
			AND ISNULL(PaidCoin, 0) = 0	--金币支付为0
			AND ISNULL(PaidPoint, 0) > 0	--积分不为0
			AND Adddate > DATEADD(YEAR, -1, GETDATE()) 
			IF(@SumPoint + @UsePoint) > @MaxPoint
			BEGIN
				GOTO ERR --超过最大积分数量
			END
			--HarryEND
			IF NOT EXISTS(SELECT 'x' FROM cpMain WHERE ID = @cpMainID AND RemainPoint > = @UsePoint)
			BEGIN
				GOTO ERR	--检查剩余积分数量是否足够支付
			END
			SET @Paid = 0
		END
	
		IF @Paid < 0
			SET @Paid = 0
		
		INSERT INTO caOrder (cpMainID, ProvinceID, ServiceType, PlaceWeek, PayMethod, UserNumber, 
			OrderType, Accounts, Paid, Balance, LinkMan, Telephone, LinkRemark, Manageruserid, 
			ActiveQuota, RemainQuota, JobNumber, CompanyName, MainOrderID, InvoiceCompany, 
			dcFeeDetailID, PaidCoin, PaidPoint)
		VALUES(@cpMainID, @ProvinceID, @ServiceType, @PlaceWeek, @PayMethod, @UserNumber, 
			@OrderType, @Accounts, @Paid, @Balance, @LinkMan, @Telephone, @LinkRemark, @Manageruserid, 
			@ActiveQuota, @ActiveQuota, @JobNumber, @CompanyName, @MainOrderID, @InvoiceCompany, 
			@dcFeeDetailsID, @UseCoin, @UsePoint)

		SET @MaxID = @@IDENTITY
		DECLARE @Temp AS NUMERIC(18, 2)
		IF @IsAgent = 1 AND @PayMethod <> 103
			SET @Paid = @Accounts		----SET @Paid = @Paid * 5 Old Rule
		SET @Temp = @Paid -- 1 + CONVERT(NUMERIC(18, 2), '0.' + RIGHT(STR(@cpMainID), 2))
		--金币或订单全额支付
		IF @Temp < 0
			SET @Temp = 0
		UPDATE caOrder SET Paid = @Temp WHERE ID = @MaxID
		
		IF @UseCoin IS NOT NULL 
		BEGIN
			--插入金币记录
			INSERT INTO cpCoin (cpMainID, caOrderID, Coin, Balance, AddDate)
			VALUES(@cpMainID, @MaxID, 0-@UseCoin, 0, GETDATE())
		END
		IF @UsePoint IS NOT NULL
		BEGIN			
			--插入积分记录
			INSERT INTO cpPoint (cpMainID, ChangeID, Point, relativeID, LastModifyDate)
			VALUES(@cpMainID, 15, 0 - @UsePoint, @MaxID, GETDATE())
			UPDATE caOrder SET NeedInvoice = 0 WHERE ID = @MaxID

			DECLARE @BeginDate SMALLDATETIME
			SET @BeginDate = GETDATE()
			IF @Balance > 0
				SELECT TOP 1 @BeginDate = EndDate FROM caOrder WITH(NOLOCK)
				WHERE cpMainID = @cpMainID AND OrderType = @OrderType AND Balance = @Balance
				AND EndDate > GETDATE() AND OpenDate IS NOT NULL AND IsDeleted = 0 ORDER BY EndDate DESC
			ELSE
				SELECT TOP 1 @BeginDate = EndDate FROM caOrder WITH(NOLOCK)
				WHERE cpMainID = @cpMainID AND OrderType = @OrderType
				AND EndDate > GETDATE() AND OpenDate IS NOT NULL AND IsDeleted = 0 ORDER BY EndDate DESC

			IF @OrderType > 4
			BEGIN		-- 立即开通积分订单
				UPDATE caOrder SET BeginDate = @BeginDate,
					EndDate = DATEADD(DAY, PlaceWeek * 7, @BeginDate),
					OpenDate = GETDATE(),
					NeedInvoice = 0
				WHERE PayMethod = 103
				AND PlaceWeek > 0
				AND Id = @MaxID 

				UPDATE caOrder 
				SET NeedInvoice = 0, ReceiveMan = 112, ReceiveDate = GETDATE()
				WHERE PayMethod = 103
				AND PlaceWeek > 0
				AND Id = @MaxID 
			END
		END
	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH
COMMIT
RETURN @MaxID
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END
GO
/****** Object:  StoredProcedure [dbo].[ccCaOrderInsert1]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = 
-- Create date: 2017-06-06 Harry
-- Description:	harry 在ccCaOrderInsert基础上 增加短信订单14
-- = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = 
CREATE PROCEDURE [dbo].[ccCaOrderInsert1]
(
	@cpMainID INT, 
	@IsAgent BIT, 
	@ProvinceID INT, 
	@ServiceType INT = NULL, 
	@PlaceWeek TINYINT = NULL, 
	@PayMethod TINYINT, 
	@OrderType TINYINT, 
	@Accounts NUMERIC(18, 2), 
	@Paid NUMERIC(18, 2), 
	@Balance NUMERIC(18, 2) = NULL, 
	@LinkMan NVARCHAR(50), 
	@Telephone VARCHAR(50), 
	@LinkRemark NVARCHAR(1000), 
	@Manageruserid SMALLINT, 
	@ActiveQuota SMALLINT = NULL, 
	@JobNumber SMALLINT = NULL, 
	@CompanyName VARCHAR(100), 
	@MainOrderID INT = NULL, 
	@InvoiceCompany SMALLINT, 
	@UserNumber SMALLINT = NULL, 
	@dcFeeDetailsID INT = NULL, 
	@smsNumber SMALLINT =NULL,
	@UseCoin INT = NULL, 
	@UsePoint INT = NULL
)
AS
SET NOCOUNT ON
BEGIN TRAN
	DECLARE @MaxId AS INT, @MaxPoint AS INT, @Type INT
	IF LEFT(@ProvinceID, 2) = 32
		SELECT @MaxPoint = 20000--设置1年内最大积分兑换额度
	ELSE
		SELECT @MaxPoint = 10000--设置1年内最大积分兑换额度

	BEGIN TRY
		IF @OrderType = 8 
		BEGIN
			IF NOT EXISTS(SELECT 'x' FROM dcVip a WITH(NOLOCK), dcVipDetail b WITH(NOLOCK) 
				WHERE a.ID = b.dcVipID AND a.dcProvinceID = LEFT(@ProvinceID, 2)
				AND b.ID = @dcFeeDetailsID	AND a.startDate<GETDATE() AND a.endDate > GETDATE())
				GOTO ERR	--检查是否套餐已过期
			SELECT @Accounts = (b.PriceMonth * a.[Month]+a.ResumeNumber*b.PriceResume+JobNumber*b.PriceJob+UserNumber*b.PriceUser+ISNULL(a.SmsNumber,0)*ISNULL(b.PriceSms,0)), 
				@Paid = a.Price, @ActiveQuota = a.ResumeNumber, @JobNumber = a.JobNumber, @UserNumber = a.UserNumber, @smsNumber=ISNULL(a.SmsNumber,0) 
			FROM dcVipDetail a WITH(NOLOCK), dcVip b WITH(NOLOCK)
			WHERE a.ID = @dcFeeDetailsID
			AND StartDate < GETDATE() AND EndDate > = GETDATE()
			AND a.dcVipID = b.ID			
		END 
		ELSE IF @OrderType = 4 AND @ServiceType = 6			----根据周数查询1/6广告的资费信息
		BEGIN
			SET @Type = 4
			SELECT TOP 1 @Accounts = b.Price * @PlaceWeek, 
				@Paid = a.Price * @PlaceWeek, 
				@dcFeeDetailsID = a.ID
			FROM dcFeeDetail a WITH(NOLOCK), dcFee b WITH(NOLOCK)
			WHERE a.dcFeeID = b.ID
			AND b.dcProvinceID = LEFT(@ProvinceID, 2)
			AND b.Type = @Type
			AND StartDate < GETDATE() AND EndDate > = GETDATE()
			AND ((MinValue< = @PlaceWeek AND MaxValue> = @PlaceWeek) OR (MinValue< = @PlaceWeek AND MaxValue = 0))

			IF @dcFeeDetailsID IS NULL
				SELECT TOP 1 @Accounts = Price, 	@Paid = Price * @PlaceWeek
				FROM dcFee WITH(NOLOCK)
				WHERE Type = @Type
				AND dcProvinceID = LEFT(@ProvinceID, 2)
				AND StartDate < GETDATE() AND EndDate > = GETDATE()
		END
		ELSE IF @OrderType = 4 AND @ServiceType = 7			----根据周数查询2/6广告的资费信息
		BEGIN
			SET @Type = 5
			SELECT TOP 1 @Accounts = b.Price * @PlaceWeek, 
				@Paid = a.Price * @PlaceWeek, 
				@dcFeeDetailsID = a.ID
			FROM dcFeeDetail a WITH(NOLOCK), dcFee b WITH(NOLOCK)
			WHERE b.Type = @Type
			AND b.dcProvinceID = LEFT(@ProvinceID, 2)
			AND StartDate < GETDATE() AND EndDate > = GETDATE()
			AND ((MinValue< = @PlaceWeek AND MaxValue> = @PlaceWeek) OR (MinValue< = @PlaceWeek AND MaxValue = 0))
			AND a.dcFeeID = b.ID

			IF @dcFeeDetailsID IS NULL
				SELECT TOP 1 @Accounts = Price, 	@Paid = Price * @PlaceWeek
				FROM dcFee  WITH(NOLOCK)
				WHERE Type = @Type
				AND dcProvinceID = LEFT(@ProvinceID, 2)
				AND StartDate < GETDATE() AND EndDate > = GETDATE()
		END
		ELSE IF @OrderType = 4 AND @ServiceType = 8			----根据周数查询3/6广告的资费信息
		BEGIN
			SET @Type = 20
			SELECT TOP 1 @Accounts = b.Price * @PlaceWeek, 
				@Paid = a.Price * @PlaceWeek, 
				@dcFeeDetailsID = a.ID
			FROM dcFeeDetail a WITH(NOLOCK), dcFee b WITH(NOLOCK)
			WHERE b.Type = @Type
			AND b.dcProvinceID = LEFT(@ProvinceID, 2)
			AND StartDate < GETDATE() AND EndDate > = GETDATE()
			AND ((MinValue< = @PlaceWeek AND MaxValue> = @PlaceWeek) OR (MinValue< = @PlaceWeek AND MaxValue = 0))
			AND a.dcFeeID = b.ID

			IF @dcFeeDetailsID IS NULL
				SELECT TOP 1 @Accounts = Price, 	@Paid = Price * @PlaceWeek
				FROM dcFee  WITH(NOLOCK)
				WHERE Type = @Type
				AND dcProvinceID = LEFT(@ProvinceID, 2)
				AND StartDate < GETDATE() AND EndDate > = GETDATE()
	 	END
		ELSE IF @OrderType = 4 AND @ServiceType = 9			----根据周数查询6/6广告的资费信息
		BEGIN
			SET @Type = 21
			SELECT TOP 1 @Accounts = b.Price * @PlaceWeek, 
				@Paid = a.Price * @PlaceWeek, 
				@dcFeeDetailsID = a.ID
			FROM dcFeeDetail a WITH(NOLOCK), dcFee b WITH(NOLOCK)
			WHERE b.Type = @Type
			AND b.dcProvinceID = LEFT(@ProvinceID, 2)
			AND StartDate < GETDATE() AND EndDate > = GETDATE()
			AND ((MinValue< = @PlaceWeek AND MaxValue> = @PlaceWeek) OR (MinValue< = @PlaceWeek AND MaxValue = 0))
			AND a.dcFeeID = b.ID

			IF @dcFeeDetailsID IS NULL
				SELECT TOP 1 @Accounts = Price, 	@Paid = Price * @PlaceWeek
				FROM dcFee  WITH(NOLOCK)
				WHERE Type = @Type
				AND dcProvinceID = LEFT(@ProvinceID, 2)
				AND StartDate < GETDATE() AND EndDate > = GETDATE()
		END
		ELSE IF @OrderType = 4 AND @ServiceType = 10			----根据周数查询6/6广告的资费信息
		BEGIN
			SET @Type = 23
			SELECT TOP 1 @Accounts = b.Price * @PlaceWeek, 
				@Paid = a.Price * @PlaceWeek, 
				@dcFeeDetailsID = a.ID
			FROM dcFeeDetail a WITH(NOLOCK), dcFee b WITH(NOLOCK)
			WHERE b.Type = @Type
			AND b.dcProvinceID = LEFT(@ProvinceID, 2)
			AND StartDate < GETDATE() AND EndDate > = GETDATE()
			AND ((MinValue< = @PlaceWeek AND MaxValue> = @PlaceWeek) OR (MinValue< = @PlaceWeek AND MaxValue = 0))
			AND a.dcFeeID = b.ID

			IF @dcFeeDetailsID IS NULL
				SELECT TOP 1 @Accounts = Price, 	@Paid = Price * @PlaceWeek
				FROM dcFee  WITH(NOLOCK)
				WHERE Type = @Type
				AND dcProvinceID = LEFT(@ProvinceID, 2)
				AND StartDate < GETDATE() AND EndDate > = GETDATE()
		END
		ELSE IF @OrderType = 7								----根据周数查询固定位置的资费信息
		BEGIN
			SET @Type = 7
			SELECT TOP 1 @Accounts = b.Price * @PlaceWeek, 
				@Paid = a.Price * @PlaceWeek, 
				@dcFeeDetailsID = a.ID
			FROM dcFeeDetail a WITH(NOLOCK), dcFee b WITH(NOLOCK)
			WHERE b.Type = @Type
			AND a.dcFeeID = b.ID
			AND b.dcProvinceID = LEFT(@ProvinceID, 2)
			AND ((MinValue< = @PlaceWeek AND MaxValue> = @PlaceWeek) OR (MinValue< = @PlaceWeek AND MaxValue = 0))
			AND StartDate < GETDATE() AND EndDate > = GETDATE()

			IF @dcFeeDetailsID IS NULL
				SELECT TOP 1 @Accounts = Price, 	@Paid = Price * @PlaceWeek
				FROM dcFee  WITH(NOLOCK)
				WHERE Type = @Type
				AND dcProvinceID = LEFT(@ProvinceID, 2)
				AND StartDate < GETDATE() AND EndDate > = GETDATE()
		END
		ELSE IF @OrderType = 9 								----简历下载
		BEGIN
			SET @Type = 9
			SELECT TOP 1 @Accounts = b.Price * @ActiveQuota, 
				@Paid = a.Price * @ActiveQuota, 
				@dcFeeDetailsID = a.ID
			FROM dcFeeDetail a WITH(NOLOCK), dcFee b WITH(NOLOCK)
			WHERE b.Type = @Type
			AND a.dcFeeID = b.ID
			AND ((MinValue< = @ActiveQuota AND MaxValue> = @ActiveQuota) OR (MinValue< = @ActiveQuota AND MaxValue = 0))
			AND StartDate < GETDATE() AND EndDate > GETDATE() 

			IF @dcFeeDetailsID IS NULL
				SELECT TOP 1 @Accounts = Price, 	@Paid = Price * @ActiveQuota
				FROM dcFee  WITH(NOLOCK)
				WHERE Type = @Type
				AND dcProvinceID = LEFT(@ProvinceID, 2)
				AND StartDate < GETDATE() AND EndDate > GETDATE()
		END
		ELSE IF @OrderType = 10 								----职位数
		BEGIN
			SET @Type = 10
			SELECT TOP 1 @Accounts = b.Price * @JobNumber, 
				@Paid = a.Price * @JobNumber, 
				@dcFeeDetailsID = a.ID
			FROM dcFeeDetail a WITH(NOLOCK), dcFee b WITH(NOLOCK)
			WHERE b.Type = @Type
			AND a.dcFeeID = b.ID
			AND b.dcProvinceID = LEFT(@ProvinceID, 2)
			AND ((MinValue< = @JobNumber AND MaxValue> = @JobNumber) OR (MinValue< = @JobNumber AND MaxValue = 0))
			AND StartDate < GETDATE() AND EndDate > GETDATE()

			IF @dcFeeDetailsID IS NULL
				SELECT TOP 1 @Accounts = Price, 	@Paid = Price * @JobNumber
				FROM dcFee  WITH(NOLOCK)
				WHERE Type = @Type
				AND dcProvinceID = LEFT(@ProvinceID, 2)
				AND StartDate < GETDATE() AND EndDate > GETDATE()
		END		
		ELSE IF @OrderType = 11								----用户数
		BEGIN
			SET @Type = 11
			SELECT TOP 1 @Accounts = b.Price * @UserNumber, 
				@Paid = a.Price * @UserNumber, 
				@dcFeeDetailsID = a.ID
			FROM dcFeeDetail a WITH(NOLOCK), dcFee b WITH(NOLOCK)
			WHERE b.Type = @Type
			AND a.dcFeeID = b.ID
			AND b.dcProvinceID = LEFT(@ProvinceID, 2) 
			AND ((MinValue< = @UserNumber AND MaxValue> = @UserNumber) OR (MinValue< = @UserNumber AND MaxValue = 0))
			AND StartDate < GETDATE() AND EndDate > GETDATE()

			IF @dcFeeDetailsID IS NULL
				SELECT TOP 1 @Accounts = Price, 	@Paid = Price * @UserNumber
				FROM dcFee  WITH(NOLOCK)
				WHERE Type = @Type
				AND dcProvinceID = LEFT(@ProvinceID, 2)
				AND StartDate < GETDATE() AND EndDate > GETDATE() 
		END
		ELSE IF @OrderType = 12			----根据周数职位置顶资费信息
		BEGIN
			SET @Type = 22
			SELECT TOP 1 @Accounts = b.Price * @PlaceWeek, 
				@Paid = a.Price * @PlaceWeek, 
				@dcFeeDetailsID = a.ID
			FROM dcFeeDetail a WITH(NOLOCK), dcFee b WITH(NOLOCK)
			WHERE b.Type = @Type
			AND b.dcProvinceID = LEFT(@ProvinceID, 2)
			AND StartDate < GETDATE() AND EndDate > = GETDATE()
			AND ((MinValue< = @PlaceWeek AND MaxValue> = @PlaceWeek) OR (MinValue< = @PlaceWeek AND MaxValue = 0))
			AND a.dcFeeID = b.ID

			IF @dcFeeDetailsID IS NULL
				SELECT TOP 1 @Accounts = Price, 	@Paid = Price * @PlaceWeek
				FROM dcFee  WITH(NOLOCK)
				WHERE Type = @Type
				AND dcProvinceID = LEFT(@ProvinceID, 2)
				AND StartDate < GETDATE() AND EndDate > = GETDATE()
		END
		ELSE IF @OrderType = 13			----根据周数职位置顶资费信息
		BEGIN
			SET @Type = 24
			SELECT TOP 1 @Accounts = b.Price * @PlaceWeek, 
				@Paid = a.Price * @PlaceWeek, 
				@dcFeeDetailsID = a.ID
			FROM dcFeeDetail a WITH(NOLOCK), dcFee b WITH(NOLOCK)
			WHERE b.Type = @Type
			AND b.dcProvinceID = LEFT(@ProvinceID, 2)
			AND StartDate < GETDATE() AND EndDate > = GETDATE()
			AND ((MinValue< = @PlaceWeek AND MaxValue> = @PlaceWeek) OR (MinValue< = @PlaceWeek AND MaxValue = 0))
			AND a.dcFeeID = b.ID

			IF @dcFeeDetailsID IS NULL
				SELECT TOP 1 @Accounts = Price, 	@Paid = Price * @PlaceWeek
				FROM dcFee  WITH(NOLOCK)
				WHERE Type = @Type
				AND dcProvinceID = LEFT(@ProvinceID, 2)
				AND StartDate < GETDATE() AND EndDate > = GETDATE()
		END
		ELSE IF @OrderType = 14		----短信订单
		BEGIN
			SET @Type = 14
			SELECT TOP 1 @Accounts = b.Price * @smsNumber, 
				@Paid = a.Price * @smsNumber, 
				@dcFeeDetailsID = a.ID
			FROM dcFeeDetail a WITH(NOLOCK), dcFee b WITH(NOLOCK)
			WHERE b.Type = @Type
			AND a.dcFeeID = b.ID
			AND b.dcProvinceID = LEFT(@ProvinceID, 2) 
			AND ((MinValue< = @smsNumber AND MaxValue> = @smsNumber) OR (MinValue< = @smsNumber AND MaxValue = 0))
			AND StartDate < GETDATE() AND EndDate > GETDATE()

			IF @dcFeeDetailsID IS NULL
				SELECT TOP 1 @Accounts = Price, 	@Paid = Price * @smsNumber
				FROM dcFee  WITH(NOLOCK)
				WHERE Type = @Type
				AND dcProvinceID = LEFT(@ProvinceID, 2)
				AND StartDate < GETDATE() AND EndDate > GETDATE() 
		END

		IF @MainOrderID IS NOT NULL
			IF NOT EXISTS(SELECT 'x' FROM caOrder WITH(NOLOCK) WHERE cpMainID = @cpMainID AND ID = @MainOrderID  AND OrderType = 8 AND EndDate >GETDATE())
				AND @OrderType in (9, 10, 11,14)
				GOTO ERR	--检查是否是自己有效的主订单号
		
		DECLARE @CoinBalance AS INT
		DECLARE @PointBalance AS INT
		
		IF @UseCoin IS NOT NULL
		BEGIN
			IF NOT EXISTS(SELECT 'x' FROM cpMain WHERE ID = @cpMainID AND RemainCoin > = @UseCoin)
				GOTO ERR	--检查剩余金币数量是否足够支付

			SET @Paid = @Paid - @UseCoin
		END
		
		IF @UsePoint IS NOT NULL --积分支付
		BEGIN
			DECLARE @NeedPoint INT, @dcFeeDetailsID2 INT, @SumPoint AS INT
			SELECT @NeedPoint = NeedPoint FROM dcfeedetail WHERE Id = @dcFeeDetailsID
			IF @NeedPoint IS NULL
			BEGIN
				SELECT TOP 1 @dcFeeDetailsID2 = a.ID
				FROM dcFeeDetail a WITH(NOLOCK), dcFee b WITH(NOLOCK)
				WHERE b.Type = @Type
				AND b.dcProvinceID = LEFT(@ProvinceID, 2)
				AND StartDate < GETDATE() AND EndDate > = GETDATE()
				AND a.NeedPoint > 0
				AND a.dcFeeID = b.ID

				SELECT @NeedPoint = NeedPoint FROM dcfeedetail WHERE id = @dcFeeDetailsID2
			END

			IF @OrderType IN(4, 7, 12, 13)
			BEGIN
				SET @UsePoint = @NeedPoint * @PlaceWeek
			END
			ELSE
			BEGIN
				SET @UsePoint = @NeedPoint
			END
			--积分兑换的积分数是否超过最大数值
			SELECT @SumPoint = SUM(PaidPoint)
			FROM caOrder
			WHERE cpMainid = @cpMainID
			AND IsDeleted = 0			--未删除
			AND ISNULL(Paid, 0) = 0		--付款为0
			AND ISNULL(PaidCoin, 0) = 0	--金币支付为0
			AND ISNULL(PaidPoint, 0) > 0	--积分不为0
			AND Adddate > DATEADD(YEAR, -1, GETDATE()) 
			IF(@SumPoint + @UsePoint) > @MaxPoint
			BEGIN
				GOTO ERR --超过最大积分数量
			END
			--HarryEND
			IF NOT EXISTS(SELECT 'x' FROM cpMain WHERE ID = @cpMainID AND RemainPoint > = @UsePoint)
			BEGIN
				GOTO ERR	--检查剩余积分数量是否足够支付
			END
			SET @Paid = 0
		END
	
		IF @Paid < 0
			SET @Paid = 0
		
		INSERT INTO caOrder (cpMainID, ProvinceID, ServiceType, PlaceWeek, PayMethod, UserNumber, 
			OrderType, Accounts, Paid, Balance, LinkMan, Telephone, LinkRemark, Manageruserid, 
			ActiveQuota, RemainQuota, JobNumber, CompanyName, MainOrderID, InvoiceCompany, 
			dcFeeDetailID, PaidCoin, PaidPoint, SmsQuota,	RemainSmsQuota)
		VALUES(@cpMainID, @ProvinceID, @ServiceType, @PlaceWeek, @PayMethod, @UserNumber, 
			@OrderType, @Accounts, @Paid, @Balance, @LinkMan, @Telephone, @LinkRemark, @Manageruserid, 
			@ActiveQuota, @ActiveQuota, @JobNumber, @CompanyName, @MainOrderID, @InvoiceCompany, 
			@dcFeeDetailsID, @UseCoin, @UsePoint, @smsNumber, @smsNumber)

		SET @MaxID = @@IDENTITY
		DECLARE @Temp AS NUMERIC(18, 2)
		IF @IsAgent = 1 AND @PayMethod <> 103
			SET @Paid = @Accounts		----SET @Paid = @Paid * 5 Old Rule
		SET @Temp = @Paid -- 1 + CONVERT(NUMERIC(18, 2), '0.' + RIGHT(STR(@cpMainID), 2))
		--金币或订单全额支付
		IF @Temp < 0
			SET @Temp = 0
		UPDATE caOrder SET Paid = @Temp WHERE ID = @MaxID
		
		IF @UseCoin IS NOT NULL 
		BEGIN
			--插入金币记录
			INSERT INTO cpCoin (cpMainID, caOrderID, Coin, Balance, AddDate)
			VALUES(@cpMainID, @MaxID, 0-@UseCoin, 0, GETDATE())
		END
		IF @UsePoint IS NOT NULL
		BEGIN			
			--插入积分记录
			INSERT INTO cpPoint (cpMainID, ChangeID, Point, relativeID, LastModifyDate)
			VALUES(@cpMainID, 15, 0 - @UsePoint, @MaxID, GETDATE())
			UPDATE caOrder SET NeedInvoice = 0 WHERE ID = @MaxID

			DECLARE @BeginDate SMALLDATETIME
			SET @BeginDate = GETDATE()
			IF @Balance > 0
				SELECT TOP 1 @BeginDate = EndDate FROM caOrder WITH(NOLOCK)
				WHERE cpMainID = @cpMainID AND OrderType = @OrderType AND Balance = @Balance
				AND EndDate > GETDATE() AND OpenDate IS NOT NULL AND IsDeleted = 0 ORDER BY EndDate DESC
			ELSE
				SELECT TOP 1 @BeginDate = EndDate FROM caOrder WITH(NOLOCK)
				WHERE cpMainID = @cpMainID AND OrderType = @OrderType
				AND EndDate > GETDATE() AND OpenDate IS NOT NULL AND IsDeleted = 0 ORDER BY EndDate DESC

			IF @OrderType > 4
			BEGIN		-- 立即开通积分订单
				UPDATE caOrder SET BeginDate = @BeginDate,
					EndDate = DATEADD(DAY, PlaceWeek * 7, @BeginDate),
					OpenDate = GETDATE(),
					NeedInvoice = 0
				WHERE PayMethod = 103
				AND PlaceWeek > 0
				AND Id = @MaxID 

				UPDATE caOrder 
				SET NeedInvoice = 0, ReceiveMan = 112, ReceiveDate = GETDATE()
				WHERE PayMethod = 103
				AND PlaceWeek > 0
				AND Id = @MaxID 
			END
		END
	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH
COMMIT
RETURN @MaxID
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END
SET NOCOUNT OFF

GO
/****** Object:  StoredProcedure [dbo].[ccCaOrderInsert2]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = 
-- Author:		Peter
-- Create date: 2014-08-20 09:55
-- Description:	
-- Modify:      Harry 2015-7-10
-- Description:修改needpoint为从dcfeedetail中取出(282行)
-- Modify:      Harry 修改一年内最大积分数不能超过qlrc  @MaxPoint=20000
--				Other Site @MaxPoint＝10000
-- = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = 
CREATE PROCEDURE [dbo].[ccCaOrderInsert2]
(
	@cpMainID INT, 
	@IsAgent BIT, 
	@ProvinceID INT, 
	@ServiceType INT = NULL, 
	@PlaceWeek TINYINT = NULL, 
	@PayMethod TINYINT, 
	@OrderType TINYINT, 
	@Accounts NUMERIC(18, 2), 
	@Paid NUMERIC(18, 2), 
	@Balance NUMERIC(18, 2) = NULL, 
	@LinkMan NVARCHAR(50), 
	@Telephone VARCHAR(50), 
	@LinkRemark NVARCHAR(1000), 
	@Manageruserid SMALLINT, 
	@ActiveQuota SMALLINT = NULL, 
	@JobNumber SMALLINT = NULL, 
	@CompanyName VARCHAR(100), 
	@MainOrderID INT = NULL, 
	@InvoiceCompany SMALLINT, 
	@UserNumber SMALLINT = NULL, 
	@dcFeeDetailsID INT = NULL, 
	@UseCoin INT = NULL, 
	@UsePoint INT = NULL
)
AS
SET NOCOUNT ON
BEGIN
	DECLARE @MaxId AS INT, @MaxPoint AS INT, @Type INT
	IF LEFT(@ProvinceID, 2) = 32
		SELECT @MaxPoint = 20000--设置1年内最大积分兑换额度
	ELSE
		SELECT @MaxPoint = 10000--设置1年内最大积分兑换额度

	BEGIN
		IF @OrderType = 8 
		BEGIN
			IF NOT EXISTS(SELECT 'x' FROM dcVip a WITH(NOLOCK), dcVipDetail b WITH(NOLOCK) 
				WHERE a.ID = b.dcVipID AND a.dcProvinceID = LEFT(@ProvinceID, 2)
				AND b.ID = @dcFeeDetailsID	AND a.startDate<GETDATE() AND a.endDate > GETDATE())
			begin
				select 111
				GOTO ERR	--检查是否套餐已过期
			end

			SELECT @Accounts = (b.PriceMonth * a.[Month]+a.ResumeNumber*b.PriceResume+JobNumber*b.PriceJob+UserNumber*b.PriceUser), 
				@Paid = a.Price, @ActiveQuota = a.ResumeNumber, @JobNumber = a.JobNumber, @UserNumber = a.UserNumber 
			FROM dcVipDetail a WITH(NOLOCK), dcVip b WITH(NOLOCK)
			WHERE a.ID = @dcFeeDetailsID
			AND StartDate < GETDATE() AND EndDate > = GETDATE()
			AND a.dcVipID = b.ID			
		END 
		ELSE IF @OrderType = 4 AND @ServiceType = 6			----根据周数查询1/6广告的资费信息
		BEGIN
			SET @Type = 4
			SELECT TOP 1 @Accounts = b.Price * @PlaceWeek, 
				@Paid = a.Price * @PlaceWeek, 
				@dcFeeDetailsID = a.ID
			FROM dcFeeDetail a WITH(NOLOCK), dcFee b WITH(NOLOCK)
			WHERE a.dcFeeID = b.ID
			AND b.dcProvinceID = LEFT(@ProvinceID, 2)
			AND b.Type = @Type
			AND StartDate < GETDATE() AND EndDate > = GETDATE()
			AND ((MinValue< = @PlaceWeek AND MaxValue> = @PlaceWeek) OR (MinValue< = @PlaceWeek AND MaxValue = 0))

			IF @dcFeeDetailsID IS NULL
				SELECT TOP 1 @Accounts = Price, 	@Paid = Price * @PlaceWeek
				FROM dcFee WITH(NOLOCK)
				WHERE Type = @Type
				AND dcProvinceID = LEFT(@ProvinceID, 2)
				AND StartDate < GETDATE() AND EndDate > = GETDATE()
		END
		ELSE IF @OrderType = 4 AND @ServiceType = 7			----根据周数查询2/6广告的资费信息
		BEGIN
			SET @Type = 5
			SELECT TOP 1 @Accounts = b.Price * @PlaceWeek, 
				@Paid = a.Price * @PlaceWeek, 
				@dcFeeDetailsID = a.ID
			FROM dcFeeDetail a WITH(NOLOCK), dcFee b WITH(NOLOCK)
			WHERE b.Type = @Type
			AND b.dcProvinceID = LEFT(@ProvinceID, 2)
			AND StartDate < GETDATE() AND EndDate > = GETDATE()
			AND ((MinValue< = @PlaceWeek AND MaxValue> = @PlaceWeek) OR (MinValue< = @PlaceWeek AND MaxValue = 0))
			AND a.dcFeeID = b.ID

			IF @dcFeeDetailsID IS NULL
				SELECT TOP 1 @Accounts = Price, 	@Paid = Price * @PlaceWeek
				FROM dcFee  WITH(NOLOCK)
				WHERE Type = @Type
				AND dcProvinceID = LEFT(@ProvinceID, 2)
				AND StartDate < GETDATE() AND EndDate > = GETDATE()
		END
		ELSE IF @OrderType = 4 AND @ServiceType = 8			----根据周数查询3/6广告的资费信息
		BEGIN
			SET @Type = 20
			SELECT TOP 1 @Accounts = b.Price * @PlaceWeek, 
				@Paid = a.Price * @PlaceWeek, 
				@dcFeeDetailsID = a.ID
			FROM dcFeeDetail a WITH(NOLOCK), dcFee b WITH(NOLOCK)
			WHERE b.Type = @Type
			AND b.dcProvinceID = LEFT(@ProvinceID, 2)
			AND StartDate < GETDATE() AND EndDate > = GETDATE()
			AND ((MinValue< = @PlaceWeek AND MaxValue> = @PlaceWeek) OR (MinValue< = @PlaceWeek AND MaxValue = 0))
			AND a.dcFeeID = b.ID

			IF @dcFeeDetailsID IS NULL
				SELECT TOP 1 @Accounts = Price, 	@Paid = Price * @PlaceWeek
				FROM dcFee  WITH(NOLOCK)
				WHERE Type = @Type
				AND dcProvinceID = LEFT(@ProvinceID, 2)
				AND StartDate < GETDATE() AND EndDate > = GETDATE()
	 	END
		ELSE IF @OrderType = 4 AND @ServiceType = 9			----根据周数查询6/6广告的资费信息
		BEGIN
			SET @Type = 21
			SELECT TOP 1 @Accounts = b.Price * @PlaceWeek, 
				@Paid = a.Price * @PlaceWeek, 
				@dcFeeDetailsID = a.ID
			FROM dcFeeDetail a WITH(NOLOCK), dcFee b WITH(NOLOCK)
			WHERE b.Type = @Type
			AND b.dcProvinceID = LEFT(@ProvinceID, 2)
			AND StartDate < GETDATE() AND EndDate > = GETDATE()
			AND ((MinValue< = @PlaceWeek AND MaxValue> = @PlaceWeek) OR (MinValue< = @PlaceWeek AND MaxValue = 0))
			AND a.dcFeeID = b.ID

			IF @dcFeeDetailsID IS NULL
				SELECT TOP 1 @Accounts = Price, 	@Paid = Price * @PlaceWeek
				FROM dcFee  WITH(NOLOCK)
				WHERE Type = @Type
				AND dcProvinceID = LEFT(@ProvinceID, 2)
				AND StartDate < GETDATE() AND EndDate > = GETDATE()
		END
		ELSE IF @OrderType = 4 AND @ServiceType = 10			----根据周数查询6/6广告的资费信息
		BEGIN
			SET @Type = 23
			SELECT TOP 1 @Accounts = b.Price * @PlaceWeek, 
				@Paid = a.Price * @PlaceWeek, 
				@dcFeeDetailsID = a.ID
			FROM dcFeeDetail a WITH(NOLOCK), dcFee b WITH(NOLOCK)
			WHERE b.Type = @Type
			AND b.dcProvinceID = LEFT(@ProvinceID, 2)
			AND StartDate < GETDATE() AND EndDate > = GETDATE()
			AND ((MinValue< = @PlaceWeek AND MaxValue> = @PlaceWeek) OR (MinValue< = @PlaceWeek AND MaxValue = 0))
			AND a.dcFeeID = b.ID

			IF @dcFeeDetailsID IS NULL
				SELECT TOP 1 @Accounts = Price, 	@Paid = Price * @PlaceWeek
				FROM dcFee  WITH(NOLOCK)
				WHERE Type = @Type
				AND dcProvinceID = LEFT(@ProvinceID, 2)
				AND StartDate < GETDATE() AND EndDate > = GETDATE()
		END
		ELSE IF @OrderType = 7								----根据周数查询固定位置的资费信息
		BEGIN
			SET @Type = 7
			SELECT TOP 1 @Accounts = b.Price * @PlaceWeek, 
				@Paid = a.Price * @PlaceWeek, 
				@dcFeeDetailsID = a.ID
			FROM dcFeeDetail a WITH(NOLOCK), dcFee b WITH(NOLOCK)
			WHERE b.Type = @Type
			AND a.dcFeeID = b.ID
			AND b.dcProvinceID = LEFT(@ProvinceID, 2)
			AND ((MinValue< = @PlaceWeek AND MaxValue> = @PlaceWeek) OR (MinValue< = @PlaceWeek AND MaxValue = 0))
			AND StartDate < GETDATE() AND EndDate > = GETDATE()

			IF @dcFeeDetailsID IS NULL
				SELECT TOP 1 @Accounts = Price, 	@Paid = Price * @PlaceWeek
				FROM dcFee  WITH(NOLOCK)
				WHERE Type = @Type
				AND dcProvinceID = LEFT(@ProvinceID, 2)
				AND StartDate < GETDATE() AND EndDate > = GETDATE()
		END
		ELSE IF @OrderType = 9 								----简历下载
		BEGIN
			SET @Type = 9
			SELECT TOP 1 @Accounts = b.Price * @ActiveQuota, 
				@Paid = a.Price * @ActiveQuota, 
				@dcFeeDetailsID = a.ID
			FROM dcFeeDetail a WITH(NOLOCK), dcFee b WITH(NOLOCK)
			WHERE b.Type = @Type
			AND a.dcFeeID = b.ID
			AND ((MinValue< = @ActiveQuota AND MaxValue> = @ActiveQuota) OR (MinValue< = @ActiveQuota AND MaxValue = 0))
			AND StartDate < GETDATE() AND EndDate > GETDATE() 

			IF @dcFeeDetailsID IS NULL
				SELECT TOP 1 @Accounts = Price, 	@Paid = Price * @ActiveQuota
				FROM dcFee  WITH(NOLOCK)
				WHERE Type = @Type
				AND dcProvinceID = LEFT(@ProvinceID, 2)
				AND StartDate < GETDATE() AND EndDate > GETDATE()
		END
		ELSE IF @OrderType = 10 								----职位数
		BEGIN
			SET @Type = 10
			SELECT TOP 1 @Accounts = b.Price * @JobNumber, 
				@Paid = a.Price * @JobNumber, 
				@dcFeeDetailsID = a.ID
			FROM dcFeeDetail a WITH(NOLOCK), dcFee b WITH(NOLOCK)
			WHERE b.Type = @Type
			AND a.dcFeeID = b.ID
			AND b.dcProvinceID = LEFT(@ProvinceID, 2)
			AND ((MinValue< = @JobNumber AND MaxValue> = @JobNumber) OR (MinValue< = @JobNumber AND MaxValue = 0))
			AND StartDate < GETDATE() AND EndDate > GETDATE()

			IF @dcFeeDetailsID IS NULL
				SELECT TOP 1 @Accounts = Price, 	@Paid = Price * @JobNumber
				FROM dcFee  WITH(NOLOCK)
				WHERE Type = @Type
				AND dcProvinceID = LEFT(@ProvinceID, 2)
				AND StartDate < GETDATE() AND EndDate > GETDATE()
		END		
		ELSE IF @OrderType = 11								----用户数
		BEGIN
			SET @Type = 11
			SELECT TOP 1 @Accounts = b.Price * @UserNumber, 
				@Paid = a.Price * @UserNumber, 
				@dcFeeDetailsID = a.ID
			FROM dcFeeDetail a WITH(NOLOCK), dcFee b WITH(NOLOCK)
			WHERE b.Type = @Type
			AND a.dcFeeID = b.ID
			AND b.dcProvinceID = LEFT(@ProvinceID, 2) 
			AND ((MinValue< = @UserNumber AND MaxValue> = @UserNumber) OR (MinValue< = @UserNumber AND MaxValue = 0))
			AND StartDate < GETDATE() AND EndDate > GETDATE()

			IF @dcFeeDetailsID IS NULL
				SELECT TOP 1 @Accounts = Price, 	@Paid = Price * @UserNumber
				FROM dcFee  WITH(NOLOCK)
				WHERE Type = @Type
				AND dcProvinceID = LEFT(@ProvinceID, 2)
				AND StartDate < GETDATE() AND EndDate > GETDATE() 
		END
		ELSE IF @OrderType = 12			----根据周数职位置顶资费信息
		BEGIN
			SET @Type = 22
			SELECT TOP 1 @Accounts = b.Price * @PlaceWeek, 
				@Paid = a.Price * @PlaceWeek, 
				@dcFeeDetailsID = a.ID
			FROM dcFeeDetail a WITH(NOLOCK), dcFee b WITH(NOLOCK)
			WHERE b.Type = @Type
			AND b.dcProvinceID = LEFT(@ProvinceID, 2)
			AND StartDate < GETDATE() AND EndDate > = GETDATE()
			AND ((MinValue< = @PlaceWeek AND MaxValue> = @PlaceWeek) OR (MinValue< = @PlaceWeek AND MaxValue = 0))
			AND a.dcFeeID = b.ID

			IF @dcFeeDetailsID IS NULL
				SELECT TOP 1 @Accounts = Price, 	@Paid = Price * @PlaceWeek
				FROM dcFee  WITH(NOLOCK)
				WHERE Type = @Type
				AND dcProvinceID = LEFT(@ProvinceID, 2)
				AND StartDate < GETDATE() AND EndDate > = GETDATE()
		END
		ELSE IF @OrderType = 13			----根据周数职位置顶资费信息
		BEGIN
			SET @Type = 24
			SELECT TOP 1 @Accounts = b.Price * @PlaceWeek, 
				@Paid = a.Price * @PlaceWeek, 
				@dcFeeDetailsID = a.ID
			FROM dcFeeDetail a WITH(NOLOCK), dcFee b WITH(NOLOCK)
			WHERE b.Type = @Type
			AND b.dcProvinceID = LEFT(@ProvinceID, 2)
			AND StartDate < GETDATE() AND EndDate > = GETDATE()
			AND ((MinValue< = @PlaceWeek AND MaxValue> = @PlaceWeek) OR (MinValue< = @PlaceWeek AND MaxValue = 0))
			AND a.dcFeeID = b.ID

			IF @dcFeeDetailsID IS NULL
				SELECT TOP 1 @Accounts = Price, 	@Paid = Price * @PlaceWeek
				FROM dcFee  WITH(NOLOCK)
				WHERE Type = @Type
				AND dcProvinceID = LEFT(@ProvinceID, 2)
				AND StartDate < GETDATE() AND EndDate > = GETDATE()
		END

		IF @MainOrderID IS NOT NULL
			IF NOT EXISTS(SELECT 'x' FROM caOrder WITH(NOLOCK) WHERE cpMainID = @cpMainID AND ID = @MainOrderID  AND OrderType = 8 AND EndDate >GETDATE())
				AND @OrderType in (9, 10, 11)
			begin
				select 222
				GOTO ERR	--检查是否是自己有效的主订单号
			end
		DECLARE @CoinBalance AS INT
		DECLARE @PointBalance AS INT
		
		IF @UseCoin IS NOT NULL
		BEGIN
			IF NOT EXISTS(SELECT 'x' FROM cpMain WHERE ID = @cpMainID AND RemainCoin > = @UseCoin)
			begin
				select 333
				GOTO ERR	--检查剩余金币数量是否足够支付
			end
			SET @Paid = @Paid - @UseCoin
		END
		
		IF @UsePoint IS NOT NULL --积分支付
		BEGIN
			DECLARE @NeedPoint INT, @dcFeeDetailsID2 INT, @SumPoint AS INT
			SELECT @NeedPoint = NeedPoint FROM dcfeedetail WHERE Id = @dcFeeDetailsID
			IF @NeedPoint IS NULL
			BEGIN
				SELECT TOP 1 @dcFeeDetailsID2 = a.ID
				FROM dcFeeDetail a WITH(NOLOCK), dcFee b WITH(NOLOCK)
				WHERE b.Type = @Type
				AND b.dcProvinceID = LEFT(@ProvinceID, 2)
				AND StartDate < GETDATE() AND EndDate > = GETDATE()
				AND a.NeedPoint > 0
				AND a.dcFeeID = b.ID

				SELECT @NeedPoint = NeedPoint FROM dcfeedetail WHERE id = @dcFeeDetailsID2
			END

			IF @OrderType IN(4, 7, 12, 13)
			BEGIN
				SET @UsePoint = @NeedPoint * @PlaceWeek
			END
			ELSE
			BEGIN
				SET @UsePoint = @NeedPoint
			END
			--积分兑换的积分数是否超过最大数值
			SELECT @SumPoint = SUM(PaidPoint)
			FROM caOrder
			WHERE cpMainid = @cpMainID
			AND IsDeleted = 0			--未删除
			AND ISNULL(Paid, 0) = 0		--付款为0
			AND ISNULL(PaidCoin, 0) = 0	--金币支付为0
			AND ISNULL(PaidPoint, 0) > 0	--积分不为0
			AND Adddate > DATEADD(YEAR, -1, GETDATE()) 
			IF(@SumPoint + @UsePoint) > @MaxPoint
			BEGIN
				select @SumPoint + @UsePoint, @SumPoint , @UsePoint, @MaxPoint
				GOTO ERR --超过最大积分数量
			END
			--HarryEND
			IF NOT EXISTS(SELECT 'x' FROM cpMain WHERE ID = @cpMainID AND RemainPoint > = @UsePoint)
			BEGIN
				select 555
				GOTO ERR	--检查剩余积分数量是否足够支付
			END
			SET @Paid = 0
		END
	
		IF @Paid < 0
			SET @Paid = 0
		
		INSERT INTO caOrder (cpMainID, ProvinceID, ServiceType, PlaceWeek, PayMethod, UserNumber, 
			OrderType, Accounts, Paid, Balance, LinkMan, Telephone, LinkRemark, Manageruserid, 
			ActiveQuota, RemainQuota, JobNumber, CompanyName, MainOrderID, InvoiceCompany, 
			dcFeeDetailID, PaidCoin, PaidPoint)
		VALUES(@cpMainID, @ProvinceID, @ServiceType, @PlaceWeek, @PayMethod, @UserNumber, 
			@OrderType, @Accounts, @Paid, @Balance, @LinkMan, @Telephone, @LinkRemark, @Manageruserid, 
			@ActiveQuota, @ActiveQuota, @JobNumber, @CompanyName, @MainOrderID, @InvoiceCompany, 
			@dcFeeDetailsID, @UseCoin, @UsePoint)

		SET @MaxID = @@IDENTITY
		DECLARE @Temp AS NUMERIC(18, 2)
		IF @IsAgent = 1 AND @PayMethod <> 103
			SET @Paid = @Accounts		----SET @Paid = @Paid * 5 Old Rule
		SET @Temp = @Paid - 1 + CONVERT(NUMERIC(18, 2), '0.' + RIGHT(STR(@cpMainID), 2))
		--金币或订单全额支付
		IF @Temp < 0
			SET @Temp = 0
		UPDATE caOrder SET Paid = @Temp WHERE ID = @MaxID
		
		IF @UseCoin IS NOT NULL 
		BEGIN
			--插入金币记录
			INSERT INTO cpCoin (cpMainID, caOrderID, Coin, Balance, AddDate)
			VALUES(@cpMainID, @MaxID, 0-@UseCoin, 0, GETDATE())
		END
		IF @UsePoint IS NOT NULL
		BEGIN			
			--插入积分记录
			INSERT INTO cpPoint (cpMainID, ChangeID, Point, relativeID, LastModifyDate)
			VALUES(@cpMainID, 15, 0 - @UsePoint, @MaxID, GETDATE())
			UPDATE caOrder SET NeedInvoice = 0 WHERE ID = @MaxID

			DECLARE @BeginDate SMALLDATETIME
			SET @BeginDate = GETDATE()
			IF @Balance > 0
				SELECT TOP 1 @BeginDate = EndDate FROM caOrder WITH(NOLOCK)
				WHERE cpMainID = @cpMainID AND OrderType = @OrderType AND Balance = @Balance
				AND EndDate > GETDATE() AND OpenDate IS NOT NULL AND IsDeleted = 0 ORDER BY EndDate DESC
			ELSE
				SELECT TOP 1 @BeginDate = EndDate FROM caOrder WITH(NOLOCK)
				WHERE cpMainID = @cpMainID AND OrderType = @OrderType
				AND EndDate > GETDATE() AND OpenDate IS NOT NULL AND IsDeleted = 0 ORDER BY EndDate DESC

			IF @OrderType > 4
			BEGIN		-- 立即开通积分订单
				UPDATE caOrder SET BeginDate = @BeginDate,
					EndDate = DATEADD(DAY, PlaceWeek * 7, @BeginDate),
					OpenDate = GETDATE(),
					NeedInvoice = 0
				WHERE PayMethod = 103
				AND PlaceWeek > 0
				AND Id = @MaxID 

				UPDATE caOrder 
				SET NeedInvoice = 0, ReceiveMan = 112, ReceiveDate = GETDATE()
				WHERE PayMethod = 103
				AND PlaceWeek > 0
				AND Id = @MaxID 
			END
		END
	END
END
RETURN @MaxID
select @MaxID
ERR:
BEGIN
	select 'aaa'
	RETURN 0
END
GO
/****** Object:  StoredProcedure [dbo].[ccCaOrderInsert3]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = 
-- Create date: 2017-06-06 Harry
-- Description:	harry 在ccCaOrderInsert1基础上 增加职位刷新数订单15
-- = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = 
CREATE PROCEDURE [dbo].[ccCaOrderInsert3]
(
	@cpMainID INT, 
	@IsAgent BIT, 
	@ProvinceID INT, 
	@ServiceType INT = NULL, 
	@PlaceWeek TINYINT = NULL, 
	@PayMethod TINYINT, 
	@OrderType TINYINT, 
	@Accounts NUMERIC(18, 2), 
	@Paid NUMERIC(18, 2), 
	@Balance NUMERIC(18, 2) = NULL, 
	@LinkMan NVARCHAR(50), 
	@Telephone VARCHAR(50), 
	@LinkRemark NVARCHAR(1000), 
	@Manageruserid SMALLINT, 
	@ActiveQuota SMALLINT = NULL, 
	@JobNumber SMALLINT = NULL, 
	@CompanyName VARCHAR(100), 
	@MainOrderID INT = NULL, 
	@InvoiceCompany SMALLINT, 
	@UserNumber SMALLINT = NULL, 
	@dcFeeDetailsID INT = NULL, 
	@smsNumber SMALLINT =NULL,
	@JobRefreshNumber INT =NULL,
	@UseCoin INT = NULL, 
	@UsePoint INT = NULL
)
AS
SET NOCOUNT ON
BEGIN TRAN
	DECLARE @MaxId AS INT, @MaxPoint AS INT, @Type INT
	IF LEFT(@ProvinceID, 2) = 32
		SELECT @MaxPoint = 20000--设置1年内最大积分兑换额度
	ELSE
		SELECT @MaxPoint = 10000--设置1年内最大积分兑换额度

	BEGIN TRY
		IF @OrderType = 8 
		BEGIN
			IF NOT EXISTS(SELECT 'x' FROM dcVip a WITH(NOLOCK), dcVipDetail b WITH(NOLOCK) 
				WHERE a.ID = b.dcVipID AND a.dcProvinceID = LEFT(@ProvinceID, 2)
				AND b.ID = @dcFeeDetailsID	AND a.startDate<GETDATE() AND a.endDate > GETDATE())
				GOTO ERR	--检查是否套餐已过期
			SELECT @Accounts = (b.PriceMonth * a.[Month]+a.ResumeNumber*b.PriceResume+JobNumber*b.PriceJob+UserNumber*b.PriceUser+ISNULL(a.SmsNumber,0)*ISNULL(b.PriceSms,0)+ISNULL(a.JobRefreshNumber,0)*ISNULL(b.priceJobrefreshNumber,0)), 
				@Paid = a.Price, @ActiveQuota = a.ResumeNumber, @JobNumber = a.JobNumber, @UserNumber = a.UserNumber, @smsNumber=ISNULL(a.SmsNumber,0), @JobRefreshNumber= ISNULL(a.JobRefreshNumber,0) 
			FROM dcVipDetail a WITH(NOLOCK), dcVip b WITH(NOLOCK)
			WHERE a.ID = @dcFeeDetailsID
			AND StartDate < GETDATE() AND EndDate > = GETDATE()
			AND a.dcVipID = b.ID			
		END 
		ELSE IF @OrderType = 4 AND @ServiceType = 6			----根据周数查询1/6广告的资费信息
		BEGIN
			SET @Type = 4
			SELECT TOP 1 @Accounts = b.Price * @PlaceWeek, 
				@Paid = a.Price * @PlaceWeek, 
				@dcFeeDetailsID = a.ID
			FROM dcFeeDetail a WITH(NOLOCK), dcFee b WITH(NOLOCK)
			WHERE a.dcFeeID = b.ID
			AND b.dcProvinceID = LEFT(@ProvinceID, 2)
			AND b.Type = @Type
			AND StartDate < GETDATE() AND EndDate > = GETDATE()
			AND ((MinValue< = @PlaceWeek AND MaxValue> = @PlaceWeek) OR (MinValue< = @PlaceWeek AND MaxValue = 0))

			IF @dcFeeDetailsID IS NULL
				SELECT TOP 1 @Accounts = Price, 	@Paid = Price * @PlaceWeek
				FROM dcFee WITH(NOLOCK)
				WHERE Type = @Type
				AND dcProvinceID = LEFT(@ProvinceID, 2)
				AND StartDate < GETDATE() AND EndDate > = GETDATE()
		END
		ELSE IF @OrderType = 4 AND @ServiceType = 7			----根据周数查询2/6广告的资费信息
		BEGIN
			SET @Type = 5
			SELECT TOP 1 @Accounts = b.Price * @PlaceWeek, 
				@Paid = a.Price * @PlaceWeek, 
				@dcFeeDetailsID = a.ID
			FROM dcFeeDetail a WITH(NOLOCK), dcFee b WITH(NOLOCK)
			WHERE b.Type = @Type
			AND b.dcProvinceID = LEFT(@ProvinceID, 2)
			AND StartDate < GETDATE() AND EndDate > = GETDATE()
			AND ((MinValue< = @PlaceWeek AND MaxValue> = @PlaceWeek) OR (MinValue< = @PlaceWeek AND MaxValue = 0))
			AND a.dcFeeID = b.ID

			IF @dcFeeDetailsID IS NULL
				SELECT TOP 1 @Accounts = Price, 	@Paid = Price * @PlaceWeek
				FROM dcFee  WITH(NOLOCK)
				WHERE Type = @Type
				AND dcProvinceID = LEFT(@ProvinceID, 2)
				AND StartDate < GETDATE() AND EndDate > = GETDATE()
		END
		ELSE IF @OrderType = 4 AND @ServiceType = 8			----根据周数查询3/6广告的资费信息
		BEGIN
			SET @Type = 20
			SELECT TOP 1 @Accounts = b.Price * @PlaceWeek, 
				@Paid = a.Price * @PlaceWeek, 
				@dcFeeDetailsID = a.ID
			FROM dcFeeDetail a WITH(NOLOCK), dcFee b WITH(NOLOCK)
			WHERE b.Type = @Type
			AND b.dcProvinceID = LEFT(@ProvinceID, 2)
			AND StartDate < GETDATE() AND EndDate > = GETDATE()
			AND ((MinValue< = @PlaceWeek AND MaxValue> = @PlaceWeek) OR (MinValue< = @PlaceWeek AND MaxValue = 0))
			AND a.dcFeeID = b.ID

			IF @dcFeeDetailsID IS NULL
				SELECT TOP 1 @Accounts = Price, 	@Paid = Price * @PlaceWeek
				FROM dcFee  WITH(NOLOCK)
				WHERE Type = @Type
				AND dcProvinceID = LEFT(@ProvinceID, 2)
				AND StartDate < GETDATE() AND EndDate > = GETDATE()
	 	END
		ELSE IF @OrderType = 4 AND @ServiceType = 9			----根据周数查询6/6广告的资费信息
		BEGIN
			SET @Type = 21
			SELECT TOP 1 @Accounts = b.Price * @PlaceWeek, 
				@Paid = a.Price * @PlaceWeek, 
				@dcFeeDetailsID = a.ID
			FROM dcFeeDetail a WITH(NOLOCK), dcFee b WITH(NOLOCK)
			WHERE b.Type = @Type
			AND b.dcProvinceID = LEFT(@ProvinceID, 2)
			AND StartDate < GETDATE() AND EndDate > = GETDATE()
			AND ((MinValue< = @PlaceWeek AND MaxValue> = @PlaceWeek) OR (MinValue< = @PlaceWeek AND MaxValue = 0))
			AND a.dcFeeID = b.ID

			IF @dcFeeDetailsID IS NULL
				SELECT TOP 1 @Accounts = Price, 	@Paid = Price * @PlaceWeek
				FROM dcFee  WITH(NOLOCK)
				WHERE Type = @Type
				AND dcProvinceID = LEFT(@ProvinceID, 2)
				AND StartDate < GETDATE() AND EndDate > = GETDATE()
		END
		ELSE IF @OrderType = 4 AND @ServiceType = 10			----根据周数查询6/6广告的资费信息
		BEGIN
			SET @Type = 23
			SELECT TOP 1 @Accounts = b.Price * @PlaceWeek, 
				@Paid = a.Price * @PlaceWeek, 
				@dcFeeDetailsID = a.ID
			FROM dcFeeDetail a WITH(NOLOCK), dcFee b WITH(NOLOCK)
			WHERE b.Type = @Type
			AND b.dcProvinceID = LEFT(@ProvinceID, 2)
			AND StartDate < GETDATE() AND EndDate > = GETDATE()
			AND ((MinValue< = @PlaceWeek AND MaxValue> = @PlaceWeek) OR (MinValue< = @PlaceWeek AND MaxValue = 0))
			AND a.dcFeeID = b.ID

			IF @dcFeeDetailsID IS NULL
				SELECT TOP 1 @Accounts = Price, 	@Paid = Price * @PlaceWeek
				FROM dcFee  WITH(NOLOCK)
				WHERE Type = @Type
				AND dcProvinceID = LEFT(@ProvinceID, 2)
				AND StartDate < GETDATE() AND EndDate > = GETDATE()
		END
		ELSE IF @OrderType = 7								----根据周数查询固定位置的资费信息
		BEGIN
			SET @Type = 7
			SELECT TOP 1 @Accounts = b.Price * @PlaceWeek, 
				@Paid = a.Price * @PlaceWeek, 
				@dcFeeDetailsID = a.ID
			FROM dcFeeDetail a WITH(NOLOCK), dcFee b WITH(NOLOCK)
			WHERE b.Type = @Type
			AND a.dcFeeID = b.ID
			AND b.dcProvinceID = LEFT(@ProvinceID, 2)
			AND ((MinValue< = @PlaceWeek AND MaxValue> = @PlaceWeek) OR (MinValue< = @PlaceWeek AND MaxValue = 0))
			AND StartDate < GETDATE() AND EndDate > = GETDATE()

			IF @dcFeeDetailsID IS NULL
				SELECT TOP 1 @Accounts = Price, 	@Paid = Price * @PlaceWeek
				FROM dcFee  WITH(NOLOCK)
				WHERE Type = @Type
				AND dcProvinceID = LEFT(@ProvinceID, 2)
				AND StartDate < GETDATE() AND EndDate > = GETDATE()
		END
		ELSE IF @OrderType = 9 								----简历下载
		BEGIN
			SET @Type = 9
			SELECT TOP 1 @Accounts = b.Price * @ActiveQuota, 
				@Paid = a.Price * @ActiveQuota, 
				@dcFeeDetailsID = a.ID
			FROM dcFeeDetail a WITH(NOLOCK), dcFee b WITH(NOLOCK)
			WHERE b.Type = @Type
			AND a.dcFeeID = b.ID
			AND ((MinValue< = @ActiveQuota AND MaxValue> = @ActiveQuota) OR (MinValue< = @ActiveQuota AND MaxValue = 0))
			AND StartDate < GETDATE() AND EndDate > GETDATE() 

			IF @dcFeeDetailsID IS NULL
				SELECT TOP 1 @Accounts = Price, 	@Paid = Price * @ActiveQuota
				FROM dcFee  WITH(NOLOCK)
				WHERE Type = @Type
				AND dcProvinceID = LEFT(@ProvinceID, 2)
				AND StartDate < GETDATE() AND EndDate > GETDATE()
		END
		ELSE IF @OrderType = 10 								----职位数
		BEGIN
			SET @Type = 10
			SELECT TOP 1 @Accounts = b.Price * @JobNumber, 
				@Paid = a.Price * @JobNumber, 
				@dcFeeDetailsID = a.ID
			FROM dcFeeDetail a WITH(NOLOCK), dcFee b WITH(NOLOCK)
			WHERE b.Type = @Type
			AND a.dcFeeID = b.ID
			AND b.dcProvinceID = LEFT(@ProvinceID, 2)
			AND ((MinValue< = @JobNumber AND MaxValue> = @JobNumber) OR (MinValue< = @JobNumber AND MaxValue = 0))
			AND StartDate < GETDATE() AND EndDate > GETDATE()

			IF @dcFeeDetailsID IS NULL
				SELECT TOP 1 @Accounts = Price, 	@Paid = Price * @JobNumber
				FROM dcFee  WITH(NOLOCK)
				WHERE Type = @Type
				AND dcProvinceID = LEFT(@ProvinceID, 2)
				AND StartDate < GETDATE() AND EndDate > GETDATE()
		END		
		ELSE IF @OrderType = 11								----用户数
		BEGIN
			SET @Type = 11
			SELECT TOP 1 @Accounts = b.Price * @UserNumber, 
				@Paid = a.Price * @UserNumber, 
				@dcFeeDetailsID = a.ID
			FROM dcFeeDetail a WITH(NOLOCK), dcFee b WITH(NOLOCK)
			WHERE b.Type = @Type
			AND a.dcFeeID = b.ID
			AND b.dcProvinceID = LEFT(@ProvinceID, 2) 
			AND ((MinValue< = @UserNumber AND MaxValue> = @UserNumber) OR (MinValue< = @UserNumber AND MaxValue = 0))
			AND StartDate < GETDATE() AND EndDate > GETDATE()

			IF @dcFeeDetailsID IS NULL
				SELECT TOP 1 @Accounts = Price, 	@Paid = Price * @UserNumber
				FROM dcFee  WITH(NOLOCK)
				WHERE Type = @Type
				AND dcProvinceID = LEFT(@ProvinceID, 2)
				AND StartDate < GETDATE() AND EndDate > GETDATE() 
		END
		ELSE IF @OrderType = 12			----根据周数职位置顶资费信息
		BEGIN
			SET @Type = 22
			SELECT TOP 1 @Accounts = b.Price * @PlaceWeek, 
				@Paid = a.Price * @PlaceWeek, 
				@dcFeeDetailsID = a.ID
			FROM dcFeeDetail a WITH(NOLOCK), dcFee b WITH(NOLOCK)
			WHERE b.Type = @Type
			AND b.dcProvinceID = LEFT(@ProvinceID, 2)
			AND StartDate < GETDATE() AND EndDate > = GETDATE()
			AND ((MinValue< = @PlaceWeek AND MaxValue> = @PlaceWeek) OR (MinValue< = @PlaceWeek AND MaxValue = 0))
			AND a.dcFeeID = b.ID

			IF @dcFeeDetailsID IS NULL
				SELECT TOP 1 @Accounts = Price, 	@Paid = Price * @PlaceWeek
				FROM dcFee  WITH(NOLOCK)
				WHERE Type = @Type
				AND dcProvinceID = LEFT(@ProvinceID, 2)
				AND StartDate < GETDATE() AND EndDate > = GETDATE()
		END
		ELSE IF @OrderType = 13			----根据周数职位置顶资费信息
		BEGIN
			SET @Type = 24
			SELECT TOP 1 @Accounts = b.Price * @PlaceWeek, 
				@Paid = a.Price * @PlaceWeek, 
				@dcFeeDetailsID = a.ID
			FROM dcFeeDetail a WITH(NOLOCK), dcFee b WITH(NOLOCK)
			WHERE b.Type = @Type
			AND b.dcProvinceID = LEFT(@ProvinceID, 2)
			AND StartDate < GETDATE() AND EndDate > = GETDATE()
			AND ((MinValue< = @PlaceWeek AND MaxValue> = @PlaceWeek) OR (MinValue< = @PlaceWeek AND MaxValue = 0))
			AND a.dcFeeID = b.ID

			IF @dcFeeDetailsID IS NULL
				SELECT TOP 1 @Accounts = Price, 	@Paid = Price * @PlaceWeek
				FROM dcFee  WITH(NOLOCK)
				WHERE Type = @Type
				AND dcProvinceID = LEFT(@ProvinceID, 2)
				AND StartDate < GETDATE() AND EndDate > = GETDATE()
		END
		ELSE IF @OrderType = 14		----短信订单
		BEGIN
			SET @Type = 14
			SELECT TOP 1 @Accounts = b.Price * @smsNumber, 
				@Paid = a.Price * @smsNumber, 
				@dcFeeDetailsID = a.ID
			FROM dcFeeDetail a WITH(NOLOCK), dcFee b WITH(NOLOCK)
			WHERE b.Type = @Type
			AND a.dcFeeID = b.ID
			AND b.dcProvinceID = LEFT(@ProvinceID, 2) 
			AND ((MinValue< = @smsNumber AND MaxValue> = @smsNumber) OR (MinValue< = @smsNumber AND MaxValue = 0))
			AND StartDate < GETDATE() AND EndDate > GETDATE()

			IF @dcFeeDetailsID IS NULL
				SELECT TOP 1 @Accounts = Price, 	@Paid = Price * @smsNumber
				FROM dcFee  WITH(NOLOCK)
				WHERE Type = @Type
				AND dcProvinceID = LEFT(@ProvinceID, 2)
				AND StartDate < GETDATE() AND EndDate > GETDATE() 
		END
		ELSE IF @OrderType = 15		----刷新数订单
		BEGIN
			SET @Type = 15
			SELECT TOP 1 @Accounts = b.Price * @JobRefreshNumber, 
				@Paid = a.Price * @JobRefreshNumber, 
				@dcFeeDetailsID = a.ID
			FROM dcFeeDetail a WITH(NOLOCK), dcFee b WITH(NOLOCK)
			WHERE b.Type = @Type
			AND a.dcFeeID = b.ID
			AND b.dcProvinceID = LEFT(@ProvinceID, 2) 
			AND ((MinValue< = @JobRefreshNumber AND MaxValue> = @JobRefreshNumber) OR (MinValue< = @JobRefreshNumber AND MaxValue = 0))
			AND StartDate < GETDATE() AND EndDate > GETDATE()

			IF @dcFeeDetailsID IS NULL
				SELECT TOP 1 @Accounts = Price, 	@Paid = Price * @JobRefreshNumber
				FROM dcFee  WITH(NOLOCK)
				WHERE Type = @Type
				AND dcProvinceID = LEFT(@ProvinceID, 2)
				AND StartDate < GETDATE() AND EndDate > GETDATE() 
		END

		IF @MainOrderID IS NOT NULL
			IF NOT EXISTS(SELECT 'x' FROM caOrder WITH(NOLOCK) WHERE cpMainID = @cpMainID AND ID = @MainOrderID  AND OrderType = 8 AND EndDate >GETDATE())
				AND @OrderType in (9, 10, 11,14)
				GOTO ERR	--检查是否是自己有效的主订单号
		
		DECLARE @CoinBalance AS INT
		DECLARE @PointBalance AS INT
		
		IF @UseCoin IS NOT NULL
		BEGIN
			IF NOT EXISTS(SELECT 'x' FROM cpMain WHERE ID = @cpMainID AND RemainCoin > = @UseCoin)
				GOTO ERR	--检查剩余金币数量是否足够支付

			SET @Paid = @Paid - @UseCoin
		END
		
		IF @UsePoint IS NOT NULL --积分支付
		BEGIN
			DECLARE @NeedPoint INT, @dcFeeDetailsID2 INT, @SumPoint AS INT
			SELECT @NeedPoint = NeedPoint FROM dcfeedetail WHERE Id = @dcFeeDetailsID
			IF @NeedPoint IS NULL
			BEGIN
				SELECT TOP 1 @dcFeeDetailsID2 = a.ID
				FROM dcFeeDetail a WITH(NOLOCK), dcFee b WITH(NOLOCK)
				WHERE b.Type = @Type
				AND b.dcProvinceID = LEFT(@ProvinceID, 2)
				AND StartDate < GETDATE() AND EndDate > = GETDATE()
				AND a.NeedPoint > 0
				AND a.dcFeeID = b.ID

				SELECT @NeedPoint = NeedPoint FROM dcfeedetail WHERE id = @dcFeeDetailsID2
			END

			IF @OrderType IN(4, 7, 12, 13)
			BEGIN
				SET @UsePoint = @NeedPoint * @PlaceWeek
			END
			ELSE
			BEGIN
				SET @UsePoint = @NeedPoint
			END
			--积分兑换的积分数是否超过最大数值
			SELECT @SumPoint = SUM(PaidPoint)
			FROM caOrder
			WHERE cpMainid = @cpMainID
			AND IsDeleted = 0			--未删除
			AND ISNULL(Paid, 0) = 0		--付款为0
			AND ISNULL(PaidCoin, 0) = 0	--金币支付为0
			AND ISNULL(PaidPoint, 0) > 0	--积分不为0
			AND Adddate > DATEADD(YEAR, -1, GETDATE()) 
			IF(@SumPoint + @UsePoint) > @MaxPoint
			BEGIN
				GOTO ERR --超过最大积分数量
			END
			--HarryEND
			IF NOT EXISTS(SELECT 'x' FROM cpMain WHERE ID = @cpMainID AND RemainPoint > = @UsePoint)
			BEGIN
				GOTO ERR	--检查剩余积分数量是否足够支付
			END
			SET @Paid = 0
		END
	
		IF @Paid < 0
			SET @Paid = 0
		
		INSERT INTO caOrder (cpMainID, ProvinceID, ServiceType, PlaceWeek, PayMethod, UserNumber, 
			OrderType, Accounts, Paid, Balance, LinkMan, Telephone, LinkRemark, Manageruserid, 
			ActiveQuota, RemainQuota, JobNumber, CompanyName, MainOrderID, InvoiceCompany, 
			dcFeeDetailID, PaidCoin, PaidPoint, SmsQuota,	RemainSmsQuota,	jobRefreshQuota, remainJobRefreshQuota)
		VALUES(@cpMainID, @ProvinceID, @ServiceType, @PlaceWeek, @PayMethod, @UserNumber, 
			@OrderType, @Accounts, @Paid, @Balance, @LinkMan, @Telephone, @LinkRemark, @Manageruserid, 
			@ActiveQuota, @ActiveQuota, @JobNumber, @CompanyName, @MainOrderID, @InvoiceCompany, 
			@dcFeeDetailsID, @UseCoin, @UsePoint, @smsNumber, @smsNumber, @JobRefreshNumber, @JobRefreshNumber)

		SET @MaxID = @@IDENTITY
		DECLARE @Temp AS NUMERIC(18, 2)
		IF @IsAgent = 1 AND @PayMethod <> 103
			SET @Paid = @Accounts		----SET @Paid = @Paid * 5 Old Rule
		SET @Temp = @Paid -- 1 + CONVERT(NUMERIC(18, 2), '0.' + RIGHT(STR(@cpMainID), 2))
		--金币或订单全额支付
		IF @Temp < 0
			SET @Temp = 0
		UPDATE caOrder SET Paid = @Temp WHERE ID = @MaxID
		
		IF @UseCoin IS NOT NULL 
		BEGIN
			--插入金币记录
			INSERT INTO cpCoin (cpMainID, caOrderID, Coin, Balance, AddDate)
			VALUES(@cpMainID, @MaxID, 0-@UseCoin, 0, GETDATE())
		END
		IF @UsePoint IS NOT NULL
		BEGIN			
			--插入积分记录
			INSERT INTO cpPoint (cpMainID, ChangeID, Point, relativeID, LastModifyDate)
			VALUES(@cpMainID, 15, 0 - @UsePoint, @MaxID, GETDATE())
			UPDATE caOrder SET NeedInvoice = 0 WHERE ID = @MaxID

			DECLARE @BeginDate SMALLDATETIME
			SET @BeginDate = GETDATE()
			IF @Balance > 0
				SELECT TOP 1 @BeginDate = EndDate FROM caOrder WITH(NOLOCK)
				WHERE cpMainID = @cpMainID AND OrderType = @OrderType AND Balance = @Balance
				AND EndDate > GETDATE() AND OpenDate IS NOT NULL AND IsDeleted = 0 ORDER BY EndDate DESC
			ELSE
				SELECT TOP 1 @BeginDate = EndDate FROM caOrder WITH(NOLOCK)
				WHERE cpMainID = @cpMainID AND OrderType = @OrderType
				AND EndDate > GETDATE() AND OpenDate IS NOT NULL AND IsDeleted = 0 ORDER BY EndDate DESC

			IF @OrderType > 4
			BEGIN		-- 立即开通积分订单
				UPDATE caOrder SET BeginDate = @BeginDate,
					EndDate = DATEADD(DAY, PlaceWeek * 7, @BeginDate),
					OpenDate = GETDATE(),
					NeedInvoice = 0
				WHERE PayMethod = 103
				AND PlaceWeek > 0
				AND Id = @MaxID 

				UPDATE caOrder 
				SET NeedInvoice = 0, ReceiveMan = 112, ReceiveDate = GETDATE()
				WHERE PayMethod = 103
				AND PlaceWeek > 0
				AND Id = @MaxID 
			END
		END
	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH
COMMIT
RETURN @MaxID
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END
SET NOCOUNT OFF

GO
/****** Object:  StoredProcedure [dbo].[ccCaOrderInsert4]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = 
-- Create date: 2017-06-06 Harry
-- Description:	harry 在ccCaOrderInsert1基础上 增加职位刷新数订单15
-- Modify Date :2018-09-21 Peter
-- Description:	添加新的订单类型 评测订单为25
-- = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = 
CREATE PROCEDURE [dbo].[ccCaOrderInsert4]
(
	@cpMainID INT, 
	@IsAgent BIT, 
	@ProvinceID INT, 
	@ServiceType INT = NULL, 
	@PlaceWeek TINYINT = NULL, 
	@PayMethod TINYINT, 
	@OrderType TINYINT, 
	@Accounts NUMERIC(18, 2), 
	@Paid NUMERIC(18, 2), 
	@Balance NUMERIC(18, 2) = NULL, 
	@LinkMan NVARCHAR(50), 
	@Telephone VARCHAR(50), 
	@LinkRemark NVARCHAR(1000), 
	@Manageruserid SMALLINT, 
	@ActiveQuota SMALLINT = NULL, 
	@JobNumber SMALLINT = NULL, 
	@CompanyName VARCHAR(100), 
	@MainOrderID INT = NULL, 
	@InvoiceCompany SMALLINT, 
	@UserNumber SMALLINT = NULL, 
	@dcFeeDetailsID INT = NULL, 
	@smsNumber SMALLINT =NULL,
	@JobRefreshNumber INT =NULL,
	@UseCoin INT = NULL, 
	@UsePoint INT = NULL,
	@AssessNumber INT = NULL
)
AS
SET NOCOUNT ON
BEGIN TRAN
	DECLARE @MaxId AS INT, @MaxPoint AS INT, @Type INT
	IF LEFT(@ProvinceID, 2) = 32
		SELECT @MaxPoint = 20000--设置1年内最大积分兑换额度
	ELSE
		SELECT @MaxPoint = 10000--设置1年内最大积分兑换额度

	BEGIN TRY
		IF @OrderType = 8 
		BEGIN
			IF NOT EXISTS(SELECT 'x' FROM dcVip a WITH(NOLOCK), dcVipDetail b WITH(NOLOCK) 
				WHERE a.ID = b.dcVipID AND a.dcProvinceID = LEFT(@ProvinceID, 2)
				AND b.ID = @dcFeeDetailsID	AND a.startDate<GETDATE() AND a.endDate > GETDATE())
				GOTO ERR	--检查是否套餐已过期
			SELECT @Accounts = (b.PriceMonth * a.[Month]+a.ResumeNumber*b.PriceResume+JobNumber*b.PriceJob+UserNumber*b.PriceUser+ISNULL(a.SmsNumber,0)*ISNULL(b.PriceSms,0)+ISNULL(a.JobRefreshNumber,0)*ISNULL(b.priceJobrefreshNumber,0)+ISNULL(a.AssessReportNumber,0)*ISNULL(b.PriceAssessReport,0)), 
				@Paid = a.Price, @ActiveQuota = a.ResumeNumber, @JobNumber = a.JobNumber, @UserNumber = a.UserNumber, @smsNumber=ISNULL(a.SmsNumber,0), @JobRefreshNumber= ISNULL(a.JobRefreshNumber,0) 
			FROM dcVipDetail a WITH(NOLOCK), dcVip b WITH(NOLOCK)
			WHERE a.ID = @dcFeeDetailsID
			AND StartDate < GETDATE() AND EndDate > = GETDATE()
			AND a.dcVipID = b.ID			
		END 
		ELSE IF @OrderType = 4 AND @ServiceType = 6			----根据周数查询1/6广告的资费信息
		BEGIN
			SET @Type = 4
			SELECT TOP 1 @Accounts = b.Price * @PlaceWeek, 
				@Paid = a.Price * @PlaceWeek, 
				@dcFeeDetailsID = a.ID
			FROM dcFeeDetail a WITH(NOLOCK), dcFee b WITH(NOLOCK)
			WHERE a.dcFeeID = b.ID
			AND b.dcProvinceID = LEFT(@ProvinceID, 2)
			AND b.Type = @Type
			AND StartDate < GETDATE() AND EndDate > = GETDATE()
			AND ((MinValue< = @PlaceWeek AND MaxValue> = @PlaceWeek) OR (MinValue< = @PlaceWeek AND MaxValue = 0))

			IF @dcFeeDetailsID IS NULL
				SELECT TOP 1 @Accounts = Price, 	@Paid = Price * @PlaceWeek
				FROM dcFee WITH(NOLOCK)
				WHERE Type = @Type
				AND dcProvinceID = LEFT(@ProvinceID, 2)
				AND StartDate < GETDATE() AND EndDate > = GETDATE()
		END
		ELSE IF @OrderType = 4 AND @ServiceType = 7			----根据周数查询2/6广告的资费信息
		BEGIN
			SET @Type = 5
			SELECT TOP 1 @Accounts = b.Price * @PlaceWeek, 
				@Paid = a.Price * @PlaceWeek, 
				@dcFeeDetailsID = a.ID
			FROM dcFeeDetail a WITH(NOLOCK), dcFee b WITH(NOLOCK)
			WHERE b.Type = @Type
			AND b.dcProvinceID = LEFT(@ProvinceID, 2)
			AND StartDate < GETDATE() AND EndDate > = GETDATE()
			AND ((MinValue< = @PlaceWeek AND MaxValue> = @PlaceWeek) OR (MinValue< = @PlaceWeek AND MaxValue = 0))
			AND a.dcFeeID = b.ID

			IF @dcFeeDetailsID IS NULL
				SELECT TOP 1 @Accounts = Price, 	@Paid = Price * @PlaceWeek
				FROM dcFee  WITH(NOLOCK)
				WHERE Type = @Type
				AND dcProvinceID = LEFT(@ProvinceID, 2)
				AND StartDate < GETDATE() AND EndDate > = GETDATE()
		END
		ELSE IF @OrderType = 4 AND @ServiceType = 8			----根据周数查询3/6广告的资费信息
		BEGIN
			SET @Type = 20
			SELECT TOP 1 @Accounts = b.Price * @PlaceWeek, 
				@Paid = a.Price * @PlaceWeek, 
				@dcFeeDetailsID = a.ID
			FROM dcFeeDetail a WITH(NOLOCK), dcFee b WITH(NOLOCK)
			WHERE b.Type = @Type
			AND b.dcProvinceID = LEFT(@ProvinceID, 2)
			AND StartDate < GETDATE() AND EndDate > = GETDATE()
			AND ((MinValue< = @PlaceWeek AND MaxValue> = @PlaceWeek) OR (MinValue< = @PlaceWeek AND MaxValue = 0))
			AND a.dcFeeID = b.ID

			IF @dcFeeDetailsID IS NULL
				SELECT TOP 1 @Accounts = Price, 	@Paid = Price * @PlaceWeek
				FROM dcFee  WITH(NOLOCK)
				WHERE Type = @Type
				AND dcProvinceID = LEFT(@ProvinceID, 2)
				AND StartDate < GETDATE() AND EndDate > = GETDATE()
	 	END
		ELSE IF @OrderType = 4 AND @ServiceType = 9			----根据周数查询6/6广告的资费信息
		BEGIN
			SET @Type = 21
			SELECT TOP 1 @Accounts = b.Price * @PlaceWeek, 
				@Paid = a.Price * @PlaceWeek, 
				@dcFeeDetailsID = a.ID
			FROM dcFeeDetail a WITH(NOLOCK), dcFee b WITH(NOLOCK)
			WHERE b.Type = @Type
			AND b.dcProvinceID = LEFT(@ProvinceID, 2)
			AND StartDate < GETDATE() AND EndDate > = GETDATE()
			AND ((MinValue< = @PlaceWeek AND MaxValue> = @PlaceWeek) OR (MinValue< = @PlaceWeek AND MaxValue = 0))
			AND a.dcFeeID = b.ID

			IF @dcFeeDetailsID IS NULL
				SELECT TOP 1 @Accounts = Price, 	@Paid = Price * @PlaceWeek
				FROM dcFee  WITH(NOLOCK)
				WHERE Type = @Type
				AND dcProvinceID = LEFT(@ProvinceID, 2)
				AND StartDate < GETDATE() AND EndDate > = GETDATE()
		END
		ELSE IF @OrderType = 4 AND @ServiceType = 10			----根据周数查询6/6广告的资费信息
		BEGIN
			SET @Type = 23
			SELECT TOP 1 @Accounts = b.Price * @PlaceWeek, 
				@Paid = a.Price * @PlaceWeek, 
				@dcFeeDetailsID = a.ID
			FROM dcFeeDetail a WITH(NOLOCK), dcFee b WITH(NOLOCK)
			WHERE b.Type = @Type
			AND b.dcProvinceID = LEFT(@ProvinceID, 2)
			AND StartDate < GETDATE() AND EndDate > = GETDATE()
			AND ((MinValue< = @PlaceWeek AND MaxValue> = @PlaceWeek) OR (MinValue< = @PlaceWeek AND MaxValue = 0))
			AND a.dcFeeID = b.ID

			IF @dcFeeDetailsID IS NULL
				SELECT TOP 1 @Accounts = Price, 	@Paid = Price * @PlaceWeek
				FROM dcFee  WITH(NOLOCK)
				WHERE Type = @Type
				AND dcProvinceID = LEFT(@ProvinceID, 2)
				AND StartDate < GETDATE() AND EndDate > = GETDATE()
		END
		ELSE IF @OrderType = 7								----根据周数查询固定位置的资费信息
		BEGIN
			SET @Type = 7
			SELECT TOP 1 @Accounts = b.Price * @PlaceWeek, 
				@Paid = a.Price * @PlaceWeek, 
				@dcFeeDetailsID = a.ID
			FROM dcFeeDetail a WITH(NOLOCK), dcFee b WITH(NOLOCK)
			WHERE b.Type = @Type
			AND a.dcFeeID = b.ID
			AND b.dcProvinceID = LEFT(@ProvinceID, 2)
			AND ((MinValue< = @PlaceWeek AND MaxValue> = @PlaceWeek) OR (MinValue< = @PlaceWeek AND MaxValue = 0))
			AND StartDate < GETDATE() AND EndDate > = GETDATE()

			IF @dcFeeDetailsID IS NULL
				SELECT TOP 1 @Accounts = Price, 	@Paid = Price * @PlaceWeek
				FROM dcFee  WITH(NOLOCK)
				WHERE Type = @Type
				AND dcProvinceID = LEFT(@ProvinceID, 2)
				AND StartDate < GETDATE() AND EndDate > = GETDATE()
		END
		ELSE IF @OrderType = 9 								----简历下载
		BEGIN
			SET @Type = 9
			SELECT TOP 1 @Accounts = b.Price * @ActiveQuota, 
				@Paid = a.Price * @ActiveQuota, 
				@dcFeeDetailsID = a.ID
			FROM dcFeeDetail a WITH(NOLOCK), dcFee b WITH(NOLOCK)
			WHERE b.Type = @Type
			AND a.dcFeeID = b.ID
			AND ((MinValue< = @ActiveQuota AND MaxValue> = @ActiveQuota) OR (MinValue< = @ActiveQuota AND MaxValue = 0))
			AND StartDate < GETDATE() AND EndDate > GETDATE() 

			IF @dcFeeDetailsID IS NULL
				SELECT TOP 1 @Accounts = Price, 	@Paid = Price * @ActiveQuota
				FROM dcFee  WITH(NOLOCK)
				WHERE Type = @Type
				AND dcProvinceID = LEFT(@ProvinceID, 2)
				AND StartDate < GETDATE() AND EndDate > GETDATE()
		END
		ELSE IF @OrderType = 10 								----职位数
		BEGIN
			SET @Type = 10
			SELECT TOP 1 @Accounts = b.Price * @JobNumber, 
				@Paid = a.Price * @JobNumber, 
				@dcFeeDetailsID = a.ID
			FROM dcFeeDetail a WITH(NOLOCK), dcFee b WITH(NOLOCK)
			WHERE b.Type = @Type
			AND a.dcFeeID = b.ID
			AND b.dcProvinceID = LEFT(@ProvinceID, 2)
			AND ((MinValue< = @JobNumber AND MaxValue> = @JobNumber) OR (MinValue< = @JobNumber AND MaxValue = 0))
			AND StartDate < GETDATE() AND EndDate > GETDATE()

			IF @dcFeeDetailsID IS NULL
				SELECT TOP 1 @Accounts = Price, 	@Paid = Price * @JobNumber
				FROM dcFee  WITH(NOLOCK)
				WHERE Type = @Type
				AND dcProvinceID = LEFT(@ProvinceID, 2)
				AND StartDate < GETDATE() AND EndDate > GETDATE()
		END		
		ELSE IF @OrderType = 11								----用户数
		BEGIN
			SET @Type = 11
			SELECT TOP 1 @Accounts = b.Price * @UserNumber, 
				@Paid = a.Price * @UserNumber, 
				@dcFeeDetailsID = a.ID
			FROM dcFeeDetail a WITH(NOLOCK), dcFee b WITH(NOLOCK)
			WHERE b.Type = @Type
			AND a.dcFeeID = b.ID
			AND b.dcProvinceID = LEFT(@ProvinceID, 2) 
			AND ((MinValue< = @UserNumber AND MaxValue> = @UserNumber) OR (MinValue< = @UserNumber AND MaxValue = 0))
			AND StartDate < GETDATE() AND EndDate > GETDATE()

			IF @dcFeeDetailsID IS NULL
				SELECT TOP 1 @Accounts = Price, 	@Paid = Price * @UserNumber
				FROM dcFee  WITH(NOLOCK)
				WHERE Type = @Type
				AND dcProvinceID = LEFT(@ProvinceID, 2)
				AND StartDate < GETDATE() AND EndDate > GETDATE() 
		END
		ELSE IF @OrderType = 12			----根据周数职位置顶资费信息
		BEGIN
			SET @Type = 22
			SELECT TOP 1 @Accounts = b.Price * @PlaceWeek, 
				@Paid = a.Price * @PlaceWeek, 
				@dcFeeDetailsID = a.ID
			FROM dcFeeDetail a WITH(NOLOCK), dcFee b WITH(NOLOCK)
			WHERE b.Type = @Type
			AND b.dcProvinceID = LEFT(@ProvinceID, 2)
			AND StartDate < GETDATE() AND EndDate > = GETDATE()
			AND ((MinValue< = @PlaceWeek AND MaxValue> = @PlaceWeek) OR (MinValue< = @PlaceWeek AND MaxValue = 0))
			AND a.dcFeeID = b.ID

			IF @dcFeeDetailsID IS NULL
				SELECT TOP 1 @Accounts = Price, 	@Paid = Price * @PlaceWeek
				FROM dcFee  WITH(NOLOCK)
				WHERE Type = @Type
				AND dcProvinceID = LEFT(@ProvinceID, 2)
				AND StartDate < GETDATE() AND EndDate > = GETDATE()
		END
		ELSE IF @OrderType = 13			----根据周数职位置顶资费信息
		BEGIN
			SET @Type = 24
			SELECT TOP 1 @Accounts = b.Price * @PlaceWeek, 
				@Paid = a.Price * @PlaceWeek, 
				@dcFeeDetailsID = a.ID
			FROM dcFeeDetail a WITH(NOLOCK), dcFee b WITH(NOLOCK)
			WHERE b.Type = @Type
			AND b.dcProvinceID = LEFT(@ProvinceID, 2)
			AND StartDate < GETDATE() AND EndDate > = GETDATE()
			AND ((MinValue< = @PlaceWeek AND MaxValue> = @PlaceWeek) OR (MinValue< = @PlaceWeek AND MaxValue = 0))
			AND a.dcFeeID = b.ID

			IF @dcFeeDetailsID IS NULL
				SELECT TOP 1 @Accounts = Price, 	@Paid = Price * @PlaceWeek
				FROM dcFee  WITH(NOLOCK)
				WHERE Type = @Type
				AND dcProvinceID = LEFT(@ProvinceID, 2)
				AND StartDate < GETDATE() AND EndDate > = GETDATE()
		END
		ELSE IF @OrderType = 14		----短信订单
		BEGIN
			SET @Type = 14
			SELECT TOP 1 @Accounts = b.Price * @smsNumber, 
				@Paid = a.Price * @smsNumber, 
				@dcFeeDetailsID = a.ID
			FROM dcFeeDetail a WITH(NOLOCK), dcFee b WITH(NOLOCK)
			WHERE b.Type = @Type
			AND a.dcFeeID = b.ID
			AND b.dcProvinceID = LEFT(@ProvinceID, 2) 
			AND ((MinValue< = @smsNumber AND MaxValue> = @smsNumber) OR (MinValue< = @smsNumber AND MaxValue = 0))
			AND StartDate < GETDATE() AND EndDate > GETDATE()

			IF @dcFeeDetailsID IS NULL
				SELECT TOP 1 @Accounts = Price, 	@Paid = Price * @smsNumber
				FROM dcFee  WITH(NOLOCK)
				WHERE Type = @Type
				AND dcProvinceID = LEFT(@ProvinceID, 2)
				AND StartDate < GETDATE() AND EndDate > GETDATE() 
		END
		ELSE IF @OrderType = 15		----刷新数订单
		BEGIN
			SET @Type = 15
			SELECT TOP 1 @Accounts = b.Price * @JobRefreshNumber, 
				@Paid = a.Price * @JobRefreshNumber, 
				@dcFeeDetailsID = a.ID
			FROM dcFeeDetail a WITH(NOLOCK), dcFee b WITH(NOLOCK)
			WHERE b.Type = @Type
			AND a.dcFeeID = b.ID
			AND b.dcProvinceID = LEFT(@ProvinceID, 2) 
			AND ((MinValue< = @JobRefreshNumber AND MaxValue> = @JobRefreshNumber) OR (MinValue< = @JobRefreshNumber AND MaxValue = 0))
			AND StartDate < GETDATE() AND EndDate > GETDATE()

			IF @dcFeeDetailsID IS NULL
				SELECT TOP 1 @Accounts = Price, 	@Paid = Price * @JobRefreshNumber
				FROM dcFee  WITH(NOLOCK)
				WHERE Type = @Type
				AND dcProvinceID = LEFT(@ProvinceID, 2)
				AND StartDate < GETDATE() AND EndDate > GETDATE() 
		END
		ELSE IF @OrderType = 25		----刷新数订单
		BEGIN
			SET @Type = 25
			SELECT TOP 1 @Accounts = b.Price * @AssessNumber, 
				@Paid = a.Price * @AssessNumber, 
				@dcFeeDetailsID = a.ID
			FROM dcFeeDetail a WITH(NOLOCK), dcFee b WITH(NOLOCK)
			WHERE b.Type = @Type
			AND a.dcFeeID = b.ID
			AND b.dcProvinceID = LEFT(@ProvinceID, 2) 
			AND ((MinValue< = @AssessNumber AND MaxValue> = @AssessNumber) OR (MinValue< = @AssessNumber AND MaxValue = 0))
			AND StartDate < GETDATE() AND EndDate > GETDATE()

			IF @dcFeeDetailsID IS NULL
				SELECT TOP 1 @Accounts = Price,@Paid = Price * @AssessNumber
				FROM dcFee WITH(NOLOCK)
				WHERE Type = @Type
				AND dcProvinceID = LEFT(@ProvinceID, 2)
				AND StartDate < GETDATE() AND EndDate > GETDATE() 
		END

		IF @MainOrderID IS NOT NULL
			IF NOT EXISTS(SELECT 'x' FROM caOrder WITH(NOLOCK) WHERE cpMainID = @cpMainID AND ID = @MainOrderID  AND OrderType = 8 AND EndDate >GETDATE())
				AND @OrderType in (9, 10, 11,14)
				GOTO ERR	--检查是否是自己有效的主订单号
		
		DECLARE @CoinBalance AS INT
		DECLARE @PointBalance AS INT
		
		IF @UseCoin IS NOT NULL
		BEGIN
			IF NOT EXISTS(SELECT 'x' FROM cpMain WHERE ID = @cpMainID AND RemainCoin > = @UseCoin)
				GOTO ERR	--检查剩余金币数量是否足够支付

			SET @Paid = @Paid - @UseCoin
		END
		
		IF @UsePoint IS NOT NULL --积分支付
		BEGIN
			DECLARE @NeedPoint INT, @dcFeeDetailsID2 INT, @SumPoint AS INT
			SELECT @NeedPoint = NeedPoint FROM dcfeedetail WHERE Id = @dcFeeDetailsID
			IF @NeedPoint IS NULL
			BEGIN
				SELECT TOP 1 @dcFeeDetailsID2 = a.ID
				FROM dcFeeDetail a WITH(NOLOCK), dcFee b WITH(NOLOCK)
				WHERE b.Type = @Type
				AND b.dcProvinceID = LEFT(@ProvinceID, 2)
				AND StartDate < GETDATE() AND EndDate > = GETDATE()
				AND a.NeedPoint > 0
				AND a.dcFeeID = b.ID

				SELECT @NeedPoint = NeedPoint FROM dcfeedetail WHERE id = @dcFeeDetailsID2
			END

			IF @OrderType IN(4, 7, 12, 13)
			BEGIN
				SET @UsePoint = @NeedPoint * @PlaceWeek
			END
			ELSE
			BEGIN
				SET @UsePoint = @NeedPoint
			END
			--积分兑换的积分数是否超过最大数值
			SELECT @SumPoint = SUM(PaidPoint)
			FROM caOrder
			WHERE cpMainid = @cpMainID
			AND IsDeleted = 0			--未删除
			AND ISNULL(Paid, 0) = 0		--付款为0
			AND ISNULL(PaidCoin, 0) = 0	--金币支付为0
			AND ISNULL(PaidPoint, 0) > 0	--积分不为0
			AND Adddate > DATEADD(YEAR, -1, GETDATE()) 
			IF(@SumPoint + @UsePoint) > @MaxPoint
			BEGIN
				GOTO ERR --超过最大积分数量
			END
			--HarryEND
			IF NOT EXISTS(SELECT 'x' FROM cpMain WHERE ID = @cpMainID AND RemainPoint > = @UsePoint)
			BEGIN
				GOTO ERR	--检查剩余积分数量是否足够支付
			END
			SET @Paid = 0
		END
	
		IF @Paid < 0
			SET @Paid = 0
		
		INSERT INTO caOrder (cpMainID, ProvinceID, ServiceType, PlaceWeek, PayMethod, UserNumber, 
			OrderType, Accounts, Paid, Balance, LinkMan, Telephone, LinkRemark, Manageruserid, 
			ActiveQuota, RemainQuota, JobNumber, CompanyName, MainOrderID, InvoiceCompany, 
			dcFeeDetailID, PaidCoin, PaidPoint, SmsQuota,	RemainSmsQuota,	jobRefreshQuota, 
			remainJobRefreshQuota,AssessReportQuota,RemainAssessReportQuota)
		VALUES(@cpMainID, @ProvinceID, @ServiceType, @PlaceWeek, @PayMethod, @UserNumber, 
			@OrderType, @Accounts, @Paid, @Balance, @LinkMan, @Telephone, @LinkRemark, @Manageruserid, 
			@ActiveQuota, @ActiveQuota, @JobNumber, @CompanyName, @MainOrderID, @InvoiceCompany, 
			@dcFeeDetailsID, @UseCoin, @UsePoint, @smsNumber, @smsNumber, @JobRefreshNumber, 
			@JobRefreshNumber,@AssessNumber,@AssessNumber)

		SET @MaxID = @@IDENTITY
		DECLARE @Temp AS NUMERIC(18, 2)
		IF @IsAgent = 1 AND @PayMethod <> 103
			SET @Paid = @Accounts		----SET @Paid = @Paid * 5 Old Rule
		SET @Temp = @Paid -- 1 + CONVERT(NUMERIC(18, 2), '0.' + RIGHT(STR(@cpMainID), 2))
		--金币或订单全额支付
		IF @Temp < 0
			SET @Temp = 0
		UPDATE caOrder SET Paid = @Temp WHERE ID = @MaxID
		
		IF @UseCoin IS NOT NULL 
		BEGIN
			--插入金币记录
			INSERT INTO cpCoin (cpMainID, caOrderID, Coin, Balance, AddDate)
			VALUES(@cpMainID, @MaxID, 0-@UseCoin, 0, GETDATE())
		END
		IF @UsePoint IS NOT NULL
		BEGIN			
			--插入积分记录
			INSERT INTO cpPoint (cpMainID, ChangeID, Point, relativeID, LastModifyDate)
			VALUES(@cpMainID, 15, 0 - @UsePoint, @MaxID, GETDATE())
			UPDATE caOrder SET NeedInvoice = 0 WHERE ID = @MaxID

			DECLARE @BeginDate SMALLDATETIME
			SET @BeginDate = GETDATE()
			IF @Balance > 0
				SELECT TOP 1 @BeginDate = EndDate FROM caOrder WITH(NOLOCK)
				WHERE cpMainID = @cpMainID AND OrderType = @OrderType AND Balance = @Balance
				AND EndDate > GETDATE() AND OpenDate IS NOT NULL AND IsDeleted = 0 ORDER BY EndDate DESC
			ELSE
				SELECT TOP 1 @BeginDate = EndDate FROM caOrder WITH(NOLOCK)
				WHERE cpMainID = @cpMainID AND OrderType = @OrderType
				AND EndDate > GETDATE() AND OpenDate IS NOT NULL AND IsDeleted = 0 ORDER BY EndDate DESC

			IF @OrderType > 4
			BEGIN		-- 立即开通积分订单
				UPDATE caOrder SET BeginDate = @BeginDate,
					EndDate = DATEADD(DAY, PlaceWeek * 7, @BeginDate),
					OpenDate = GETDATE(),
					NeedInvoice = 0
				WHERE PayMethod = 103
				AND PlaceWeek > 0
				AND Id = @MaxID 

				UPDATE caOrder 
				SET NeedInvoice = 0, ReceiveMan = 112, ReceiveDate = GETDATE()
				WHERE PayMethod = 103
				AND PlaceWeek > 0
				AND Id = @MaxID 
			END
		END
	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH
COMMIT
RETURN @MaxID
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END
SET NOCOUNT OFF



GO
/****** Object:  StoredProcedure [dbo].[ccCaOrderInvoiceNullUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.6
--创建人：John
--说明：更新会员订单的发票信息为空
--#####################################################
CREATE PROCEDURE [dbo].[ccCaOrderInvoiceNullUpdate]
(
	@caOrderID INT,
	@cpMainID INT
)
AS
BEGIN
	UPDATE caOrder SET InvoiceAskDate = NULL,NeedInvoice = 0,InvoiceConfirmDate = NULL,InvoiceConfirmMan = NULL 
	WHERE ID = @caOrderID AND cpMainID = @cpMainID
END


GO
/****** Object:  StoredProcedure [dbo].[ccCaOrderInvoiceUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ccCaOrderInvoiceUpdate]
(
	@ID INT,
	@caMainID INT,
	@InvoiceTitle NVARCHAR(50),
	@PostTelephone VARCHAR(50),
	@Recipient NVARCHAR(100),
	@Zip char(6),
	@MailAddress NVARCHAR(100)
)
AS
BEGIN
	IF EXISTS(SELECT 'X' FROM caOrder WHERE ID=@ID AND cpMainID = (SELECT cpMainID FROM caMain WITH(NOLOCK) WHERE ID = @caMainID))
	BEGIN
		UPDATE caOrder SET InvoiceAskDate=GETDATE(),NeedInvoice=1,InvoiceTitle=@InvoiceTitle,PostTelephone=@PostTelephone,
			Zip=@Zip,MailAddress=@MailAddress,Recipient=@Recipient WHERE ID=@ID
		RETURN 1
	END
	ELSE
		RETURN 0
END














GO
/****** Object:  StoredProcedure [dbo].[ccCaOrderInvoiceUpdateNew]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ccCaOrderInvoiceUpdateNew]
(
	@ID INT,
	@caMainID INT,
	@InvoiceTitle NVARCHAR(50),
	@PostTelephone VARCHAR(50),
	@Recipient NVARCHAR(100),
	@Zip char(6),
	@MailAddress NVARCHAR(100),
	@Tariff VARCHAR(30),
	@RegisterAddress NVARCHAR(100),
	@RegisterTel VARCHAR(50),
	@BankName VARCHAR(50),
	@BankAccount VARCHAR(50)
)
AS
BEGIN
	IF EXISTS(SELECT 'X' FROM caOrder WHERE ID=@ID AND cpMainID = (SELECT cpMainID FROM caMain WITH(NOLOCK) WHERE ID = @caMainID))
	BEGIN
		UPDATE caOrder SET 
			InvoiceAskDate=GETDATE(),NeedInvoice=1,
			InvoiceTitle=@InvoiceTitle,PostTelephone=@PostTelephone,
			Zip=@Zip,MailAddress=@MailAddress,Recipient=@Recipient,
			Tariff = @Tariff,RegisterAddress = @RegisterAddress,
			RegisterTel = @RegisterTel,BankName = @BankName,
			BankAccount = @BankAccount
		WHERE ID=@ID
		RETURN 1
	END
	ELSE
		RETURN 0
END










GO
/****** Object:  StoredProcedure [dbo].[ccCaOrderPointByCpMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Harry
-- Create date: 2015-7-9
-- Description:	获取企业一年内积分免费兑换的总积分数量
-- =============================================
CREATE PROCEDURE [dbo].[ccCaOrderPointByCpMainIDSelect]
(
	@cpMainID INT
)
AS
BEGIN
	SELECT SUM(PaidPoint)cnt
	FROM caOrder
	WHERE cpMainID=@cpMainID
	AND IsDeleted=0--未删除
	AND ISNULL(Paid,0)=0--付款为0
	AND ISNULL(PaidCoin,0)=0--金币支付为0
	AND ISNULL(PaidPoint,0)>0--积分不为0
	AND Adddate > DATEADD(YEAR, -1, GETDATE())
END

GO
/****** Object:  StoredProcedure [dbo].[ccCaOrderSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
---------------------------------------------------------------------------------------------------------------------
--cccaorderSELECT 8796242,'OpenDate IS NULL'
--mice 2014-8-21 修改， 添加返回值： a.PaidCoin, a.PaidPoint 
--harry 2017-7-8 修改 a.SmsQuota, a.RemainSmsQuota
CREATE PROCEDURE [dbo].[ccCaOrderSelect]
(
	@cpMainID INT,
	@WHERE VARCHAR(200)
)
AS
BEGIN
	SET @Where = REPLACE(dbo.SafeSql(@Where), '''', '''''')
	DECLARE @SQL AS VARCHAR(2000)
	SET @SQL='SELECT a.ID,a.cpMainID,a.ProvinceID,a.ServiceType,a.PlaceWeek,a.PayMethod,a.jobRefreshQuota,a.remainJobRefreshQuota,
		a.OrderType,a.Accounts,a.Paid,a.Balance,a.LinkMan,a.Telephone AS LinkTelephone,
		a.LinkRemark,a.MailAddress,a.Recipient,a.Zip,a.FaxFile,a.CompanyName,
		a.RemittanceFile,a.RemittanceDate,a.PostTelephone,a.ReceiveDate,
		a.NeedInvoice,a.InvoiceTitle,a.InvoiceCompany,
		a.InvoiceConfirmDate,a.InvoiceConfirmMan,a.InvoiceAskDate,
		a.ContractFile,a.Manageruserid,a.IsDeleted,a.DeletedMan,a.DeletedDate,
		a.OpenMan,a.OpenDate,a.BeginDate,a.EndDate,a.AddDate,a.ActiveQuota,
		a.PaidCoin, a.PaidPoint, a.dcFeeDetailID,
		a.RemainQuota,a.JobNumber,a.MainOrderID, a.SmsQuota, a.RemainSmsQuota, a.AssessReportQuota, a.RemainAssessReportQuota, b.PayMethodID,c.Name as PayMethodName,b.Receiver,
		b.Account,b.BankName
	FROM caOrder a WITH(NOLOCK)
	INNER JOIN dcPayMethod c WITH(NOLOCK) ON a.PayMethod = c.PayMethodID
    LEFT JOIN dcPayMethodProvince b WITH(NOLOCK) ON a.PayMethod = b.PayMethodID 
	AND b.dcProvinceID = CASE WHEN a.InvoiceCompany = 4 THEN 30 WHEN a.InvoiceCompany = 2 THEN 10 END
	WHERE (a.IsDeleted=0 OR a.IsDeleted IS NULL) 
	AND a.cpMainID = ' + CONVERT(VARCHAR(10), @cpMainID)
	IF @cpMainId = 8399005
		SET @SQL = @SQL + ' AND a.Id NOT IN(282110,282108,281450,205880)'
	IF LEN(@WHERE)> 0
		SET @SQL = @SQL + ' AND ' + @WHERE
	SET @SQL = @SQL + ' ORDER BY a.ID DESC'
	print @SQL
	EXEC(@SQL)
END

GO
/****** Object:  StoredProcedure [dbo].[ccCaorderSelectByOrdertype]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--根据类型获取订单信息
--Harry
--说明：1：简历下载数只取主订单，从属的简历订单不显示
--2017-12-5
CREATE PROCEDURE [dbo].[ccCaorderSelectByOrdertype]
(
    @orderType INT,--1简历
    @cpMainId INT
)
AS
SET NOCOUNT ON
BEGIN
    IF @orderType=1
    BEGIN
        SELECT * FROM caOrder WITH(NOLOCK)
        WHERE cpMainId = @cpMainId
        AND orderType = 8
        AND OpenDate IS NOT NULl
        AND endDate>GETDATE()
        AND IsDeleted = 0
        ORDER BY endDate 
    END
        
END
SET NOCOUNT OFF
GO
/****** Object:  StoredProcedure [dbo].[ccCaOrderTryOutSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[ccCaOrderTryOutSelect]
(
	@cpMainID INT
)
AS
	IF EXISTS 
		(
			SELECT 'x' FROM caOrder WITH(NOLOCK)
				WHERE cpMainID = @cpMainID
				AND BeginDate<GETDATE()
				AND EndDate>GETDATE()
				AND OrderType = 8
				AND ServiceType = 101
		)
		RETURN 1
	ELSE
		RETURN 0














GO
/****** Object:  StoredProcedure [dbo].[ccCaPlaintByCaMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ccCaPlaintByCaMainIDSelect]
(
	@caMainID INT
)
AS
BEGIN
    SELECT dbo.GetPaName(a.cvMainID,b.cpMainID) paName, c.Name CompanyName, c.ID CompanyID, a.*, d.SecondID, d.paMainID
    FROM CaPlaint a WITH(NOLOCK) 
    INNER JOIN caMain b WITH(NOLOCK) ON a.caMainID = b.ID 
    LEFT JOIN cpMain c WITH(NOLOCK) ON b.cpMainID = c.ID
	INNER JOIN cvMain d WITH(NOLOCK) ON a.cvMainID = d.ID
    WHERE a.caMainID = @caMainID 
    ORDER BY ID DESC
END
GO
/****** Object:  StoredProcedure [dbo].[ccCaPlaintByCpMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ccCaPlaintByCpMainIDSelect]
(
	@cpMainID INT
)
AS
BEGIN
	SELECT dbo.GetPaName(a.cvMainID,@cpMainID) paName,a.*,b.Name caName, c.SecondId, c.paMainID, b.cpMainID CompanyID
	FROM CaPlaint a WITH(NOLOCK), caMain b WITH(NOLOCK), cvMain c WITH(NOLOCK) WHERE a.caMainID = b.ID AND a.cvMainID = c.ID AND b.cpMainID = @cpMainID AND b.isDelete = 0 ORDER BY a.ID DESC
END

GO
/****** Object:  StoredProcedure [dbo].[ccCaPlaintInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--============
--检查	sean，2010-10-9
--查看简历时，对个人进行投诉
--============
CREATE PROCEDURE [dbo].[ccCaPlaintInsert]
(
	@caMainID INT,	
	@cvMainID INT,
    @Plaint VARCHAR(1000),
    @LinkMan VARCHAR(50),
    @Telephone VARCHAR(20)
)
AS
BEGIN TRY
	INSERT INTO caPlaint(caMainID,cvMainID,PlaINT,LinkMan,Telephone)
	VALUES(@caMainID,@cvMainID,@PlaINT,@LinkMan,@Telephone)
	
	RETURN 1
END TRY
BEGIN CATCH
	RETURN 0
END CATCH














GO
/****** Object:  StoredProcedure [dbo].[cccaPushSetSelectByCaMainID]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--------------------
--创建人 Peter
--创建时间：2016-10-17
--获取企业推送的相关数据
CREATE PROCEDURE [dbo].[cccaPushSetSelectByCaMainID]
(
	@CaMainID INT
)
AS
SET NOCOUNT ON
BEGIN
	SELECT * FROM caPushSet WHERE caMainID = @CaMainID 
END


GO
/****** Object:  StoredProcedure [dbo].[cccaPushSetUpdateByCaMainID]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------
--创建人 Peter
--创建时间：2016-10-17
--企业修改推送频率
CREATE PROCEDURE [dbo].[cccaPushSetUpdateByCaMainID]
(
	@CaMainID INT,
	@PushFrequency TINYINT
)
AS
SET NOCOUNT ON
BEGIN
	IF EXISTS(SELECT 'x' FROM caPushSet WITH(NOLOCK) WHERE caMainID = @caMainID)
	BEGIN
		UPDATE caPushSet 
		SET PushFrequency = @PushFrequency,PushNo = 0
		WHERE caMainID = @CaMainID 
	END
	ELSE
	BEGIN
		INSERT INTO caPushSet(caMainID,PushFrequency,PushNo)
		VALUES (@CaMainID,@PushFrequency,0)
	END
END

GO
/****** Object:  StoredProcedure [dbo].[ccCaSmsLogSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--创建人harry
--2017-6-7
--获取短信发送记录
CREATE PROCEDURE [dbo].[ccCaSmsLogSelect]
(
	@cpMainID INT,
	@orderID INT
)
AS
SET NOCOUNT ON
BEGIN
	IF @orderID > 0
	BEGIN
		SELECT a.*, b.Name
		FROM caSmsLog a WITH(NOLOCK)  
		LEFT JOIN caMain b WITH(NOLOCK) ON a.caMainid = b.Id
		WHERE a.caOrderID = @orderID
		ORDER BY a.id
	END 
	ELSE
	BEGIN
		SELECT a.*, b.Name
		FROM caSmsLog a WITH(NOLOCK)  
		LEFT JOIN caMain b WITH(NOLOCK) ON a.caMainid = b.Id
		WHERE a.caOrderID IN(SELECT ID FROM caOrder WHERE cpMainID = @cpMainID)
		ORDER by a.id 
	END	 
END
SET NOCOUNT OFF

GO
/****** Object:  StoredProcedure [dbo].[ccCaVerifyLogByMobileIpSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2017-7-11
--创建人：sean
--说明：获取cpmpany手机验证日志
--#####################################################
CREATE PROCEDURE [dbo].[ccCaVerifyLogByMobileIpSelect]
(
	@Mobile VARCHAR(11),
	@ip VARCHAR(31)
)
AS
BEGIN
	SELECT TOP 1 * FROM CaVerifyLog WITH(NOLOCK) 
	WHERE Mobile = @Mobile 
	AND AddDate > DATEADD(HOUR, -1, GETDATE())
	AND ip = @ip
	AND VerifyDate IS NULL
	ORDER BY id DESC
END


GO
/****** Object:  StoredProcedure [dbo].[ccCaVerifyLogInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--sean 20170711
--手机号注册，前台发送验证码 cmpany
--harry2018-7-20黑名单手机号不发送
CREATE PROCEDURE [dbo].[ccCaVerifyLogInsert] 
(
    @Mobile VARCHAR(11), 
    @IP VARCHAR(31)
)
AS
SET NOCOUNT ON
BEGIN
    IF EXISTS(SELECT 'x' FROM tmp_limitmobile WITH(NOLOCK) WHERE Mobile = @Mobile)
        RETURN -1
     IF EXISTS(SELECT 'x' FROM Company_Black WITH(NOLOCK) WHERE Mobile = @Mobile)
        RETURN -1
    --IF DATEPART(HOUR, GETDATE()) > 22 OR DATEPART(HOUR, GETDATE()) < 7
    --    RETURN -1

    --IF CHARINDEX(', ', @Ip) > 0
    --    RETURN -1
    IF CHARINDEX(', ', @Ip) > 0
        SET @Ip = RIGHT(@ip, LEN(@ip) - CHARINDEX(', ', @ip))

    DECLARE @VerifyCount SMALLINT
	IF(SELECT COUNT(*) FROM Ip_WHite WHERE CHARINDEX(ip, @Ip) > 0 AND Kind = 2) = 0
		SELECT @VerifyCount = COUNT(1) FROM caVerifyLog WITH(NOLOCK)
		WHERE IP = @IP 
		AND AddDate > CONVERT(VARCHAR(10), GETDATE(), 120)
	ELSE
		SET @VerifyCount = 0

    IF @VerifyCount > 3
        RETURN -1

    SELECT @VerifyCount = COUNT(1) FROM caVerifyLog WITH(NOLOCK)
    WHERE Mobile = @Mobile 
    AND AddDate > CONVERT(VARCHAR(10), GETDATE(), 120)

    IF @VerifyCount > 2
        RETURN 0

    SELECT @VerifyCount = COUNT(1) FROM caVerifyLog WITH(NOLOCK)
    WHERE Mobile = @Mobile 
    AND AddDate > DATEADD(MINUTE, -5, GETDATE())

    IF @VerifyCount > 3
        RETURN 0

    DECLARE @VerifyCode AS VARCHAR(6)
    SELECT @VerifyCode = RAND() * 899999 + 100000
    INSERT INTO caVerifyLog(caMainID, Mobile, VerifyCode, VerifyDate, AddDate, ip)
    VALUES(0, @Mobile, @VerifyCode, NULL, GETDATE(), @IP)

    RETURN @VerifyCode
END

GO
/****** Object:  StoredProcedure [dbo].[ccCaVerifyLogUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2017-7-19
--创建人：sean
--说明：UPDATE cpmpany手机验证日志
--#####################################################
CREATE PROCEDURE [dbo].[ccCaVerifyLogUpdate]
(
	@Id INT
)
AS
BEGIN
	UPDATE CaVerifyLog SET VerifyDate = GETDATE() WHERE Id = @Id
END


GO
/****** Object:  StoredProcedure [dbo].[ccChatOnLineByCaMainIDSelectNew]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ccChatOnLineByCaMainIDSelectNew]
(
    @CaMainID INT,	--企业用户的ID
	@GetType INT
)
AS
SET NOCOUNT ON
--INSERT INTO procLog SELECT 'ccChatOnLineByCaMainIDSelectNew', LTRIM(STR(@CaMainID)) + ' ' + LTRIM(STR(@GetType)), GETDATE()
BEGIN
	DECLARE @AddDate AS DATETIME, @CpMainID INT
	IF @GetType = 0
	BEGIN
		IF NOT EXISTS(SELECT 'x' FROM SearchDb..ChatOnlineListLog WITH(NOLOCK)
			WHERE caMainId = @caMainId
			AND AddDate > DATEADD(MINUTE, -10, GETDATE())
			)
			SET @GetType = 1
	END 
	IF @GetType = 1
	BEGIN
		SELECT @CpMainID = cpMainID FROM caMain WITH(NOLOCK) WHERE ID = @CaMainID
		CREATE TABLE #UserList
		(
			ChatOnlineID INT,
			CaMainID INT,
			CvMainID INT,
			EndDate SMALLDATETIME,
			LastChatDate SMALLDATETIME,
			SumUnRead INT,
			IsHidden BIT
		)
		
		UPDATE ChatOnline
		SET caUnViewed = 0
		WHERE caUnViewed > 0
		AND caMainId = @CaMainID

		UPDATE a
		SET a.caUnViewed = b.Cnt
		FROM ChatOnline a WITH(NOLOCK), (
			SELECT MAX(a.ID) Id, COUNT(*) Cnt
			FROM ChatOnline a WITH(NOLOCK), ChatOnlineLog b WITH(NOLOCK)
			WHERE a.id = b.ChatOnlineID
			AND b.IsViewed = 0
			AND b.SenderType <> 1 --不是企业发送的
			AND a.caMainID = @CaMainID
			GROUP BY a.CaMainID, a.CvMainID
			) b
		WHERE a.Id = b.Id

		--企业的联系人列表，有留言的
		INSERT INTO #UserList
		SELECT MAX(ID), @CaMainID, CvMainID, MAX(EndDate), MAX(StartDate), SUM(caUnViewed), 0
		FROM ChatOnline WITH(NOLOCK)
		WHERE caMainId = @CaMainID --当前企业用户
		AND (caUnViewed > 0
			OR StartDate > GETDATE() - 15)
		GROUP BY CvMainID

		--企业联系列表，15之外曾有联系的，隐藏不显示
		INSERT INTO #UserList
		SELECT MAX(ID), @CaMainID, CvMainID, MAX(EndDate), MAX(StartDate), 0, 1
		FROM ChatOnline WITH(NOLOCK)
		WHERE caMainId = @CaMainID --当前企业用户
		AND CvMainID NOT IN(SELECT CvMainID FROM #UserList)
		GROUP BY CvMainID

		--最终结果
		DELETE FROM SearchDb..ChatOnlineListLog WHERE caMainId = @CaMainId
		DELETE FROM SearchDb..ChatOnlineList WHERE caMainId = @CaMainId

		INSERT INTO SearchDb..ChatOnlineListLog SELECT @caMainId, GETDATE()

		INSERT INTO SearchDb..ChatOnlineList
		SELECT TOP 20
			a.*,
			dbo.GetPaName(b.ID, @CpMainID) PaName,
			b.PaMainID,
			b.JobName UserName,
			ISNULL(c.IsOnline, 0) IsOnline
		FROM #UserList a
		INNER JOIN cvMain b ON a.cvMainID = b.ID
		LEFT JOIN paOnline c ON b.paMainId = c.paMainId
		ORDER BY a.LastChatDate DESC

		DROP TABLE #UserList
	END

	SELECT * FROM SearchDb..ChatOnlineList WITH(NOLOCK) 
	WHERE caMainId = @CaMainId
	ORDER BY SumUnRead Desc, LastChatDate DESC
END


GO
/****** Object:  StoredProcedure [dbo].[ccChatOnlineByIsRecentlyContactSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ccChatOnlineByIsRecentlyContactSelect]
(
	@caMainID INT
)
AS
BEGIN TRY
	IF EXISTS(SELECT 'X' FROM ChatOnlineLog WHERE ChatOnlineID IN(
			SELECT ID FROM ChatOnline WHERE caMainID = @caMainID) HAVING MAX(AddDate) > DATEADD(mi, -5, GETDATE()))
		RETURN 1

	IF EXISTS(SELECT 'X' FROM ChatOnlineLog WHERE ChatOnlineID IN(
			SELECT ID FROM ChatOnline WHERE caMainID = @caMainID) AND SenderType=2 AND IsViewed=0)
		RETURN 1

	RETURN 0
END TRY
BEGIN CATCH
	RETURN 0
END CATCH

GO
/****** Object:  StoredProcedure [dbo].[ccChatOnLineLogByCaMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ccChatOnLineLogByCaMainIDSelect]
(
    @CaMainID INT	--企业用户的ID
)
AS
SET NOCOUNT ON
BEGIN	
	CREATE TABLE #ChatLog(
		CaMainID INT,
		CvMainID INT,
		LastMessage VARCHAR(MAX),
		LastReceiverDate SMALLDATETIME,
		Initiative TINYINT)

	INSERT INTO #ChatLog
	SELECT a.CaMainID, a.CvMainID,
		(SELECT TOP 1 Message FROM ChatOnlineLog WHERE ChatOnlineID = MAX(a.ID) ORDER BY AddDate DESC),
		MAX(b.Adddate),
		(SELECT Initiative FROM ChatOnline WHERE ID = MIN(a.ID))
	FROM ChatOnline a, ChatOnlineLog b
	WHERE a.id = b.ChatOnlineID
	--AND b.IsViewed = 0
	AND a.caMainId = @CaMainID --当前个人用户
	GROUP BY a.CaMainID,a.CvMainID

	SELECT a.*,
		c.Name PaName,		
		b.Name CvName,
		b.ID CvID,
		d.Description Education,
		e.FullName LivePlace,
		Initiative,
		b.paMainId,
		b.SecondId
	FROM #ChatLog a, cvMain b, paMain c, dcEducation d, dcRegion e
	WHERE a.cvMainID = b.id
	AND b.paMainID = c.ID
	AND c.livePlace = e.ID
	AND b.Degree=d.ID
END








GO
/****** Object:  StoredProcedure [dbo].[ccChatServiceSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ccChatServiceSelect]
AS
BEGIN
	SELECT TOP 1 * 
	FROM ChatService a 
	LEFT JOIN ManagerUser b ON a.ManageruserID = b.id
	WHERE a.IsOnline = 1
	AND b.SOLStatus = 1
	ORDER BY a.ChatCount
END

GO
/****** Object:  StoredProcedure [dbo].[ccCheckReccomendCvSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.31
--创建人：Nick
--说明：
--修改：harry
--区分主办方：校园，社会，校园主办方只能看本校的学生
--2018-3-15
--harry 18-4-8
--#####################################################
CREATE PROCEDURE [dbo].[ccCheckReccomendCvSelect]
(
	@rmDeptID INT,
	@cvID INT
)
AS
BEGIN
	DECLARE @CNT INT
	SET @CNT = 0
	IF EXISTS(SELECT 'x' FROM marketdb..rmdept where id=@rmDeptID and isSchool =1)
	BEGIN
		--学号必须一致
		SELECT @CNT = COUNT(*) FROM cvMain a WITH(NOLOCK)
			INNER JOIN paMain b WITH(NOLOCK) ON a.paMainID=b.ID 
			INNER JOIN marketdb..RmPerson c WITH(NOLOCK) ON c.paMainID=b.Id
		  	INNER JOIN wutongguodb..RecruitmentSchool d WITH(NOLOCK) ON c.RecruitmentID=d.ID*-1
			LEFT JOIN marketdb..RmStudentIds f ON c.studentId= f.rmStudentId
			WHERE a.ID=@cvID 
			AND d.RecruitmentDeptId=@rmDeptID
			AND c.studentId IS NOT NULL
			AND f.rmdeptId= @rmDeptID
		IF @CNT = 0
		BEGIN
			RETURN 0
		END
		ELSE
		BEGIN
			RETURN 1
		END
			
	END
	ELSE
	BEGIN
		SELECT @CNT = COUNT(*) FROM cvMain a WITH(NOLOCK)
		INNER JOIN paMain d WITH(NOLOCK) ON a.paMainID=d.ID
		INNER JOIN marketdb..ptCvInvitation b WITH(NOLOCK) ON a.paMainID=b.paMainID 
		INNER JOIN marketdb..ptWorkAppoint c WITH(NOLOCK) ON b.PtWorkAppointID1=c.ID
		INNER JOIN Recruitment e WITH(NOLOCK) ON c.RecruitmentID=e.ID
		INNER JOIN RecruitmentDept f WITH(NOLOCK) ON e.RecruitmentDeptId=f.ID
		WHERE a.ID=@cvID AND a.Valid=1 AND f.ID=@rmDeptID
		
		IF @CNT = 0
		BEGIN
			SELECT @CNT = COUNT(*) FROM cvMain a WITH(NOLOCK)
			INNER JOIN paMain d WITH(NOLOCK) ON a.paMainID=d.ID
			INNER JOIN marketdb..RmInvitationCode b WITH(NOLOCK) ON a.paMainID=b.paMainID AND b.Valid=1
			INNER JOIN marketdb..RmProject c WITH(NOLOCK) ON b.RmProjectID=c.ID
			INNER JOIN marketdb..Recruitment e WITH(NOLOCK) ON c.RecruitmentID=e.ID
			INNER JOIN marketdb..RmDept f WITH(NOLOCK) ON e.RecruitmentDeptId=f.ID
			WHERE a.ID=@cvID AND a.Valid=1 AND f.ID=@rmDeptID
			
			IF @CNT = 0
			BEGIN
				RETURN 0
			END
			ELSE
			BEGIN
				RETURN 1
			END
		END
		ELSE
		BEGIN
			RETURN 1
		END
	END
	
END


GO
/****** Object:  StoredProcedure [dbo].[ccColdCustomerByCpRegisterUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--alen 2018-4-8
CREATE PROCEDURE [dbo].[ccColdCustomerByCpRegisterUpdate] 
(
	@cpMainID INT,
	@cpName NVARCHAR(50),
	@provinceID TINYINT
)
AS
BEGIN
	DECLARE @ColdCustomerID AS INT,@IsTure AS BIT

	SET  @ColdCustomerID =0
	IF NOT EXISTS(SELECT 'X' FROM cpMain WITH(NOLOCK) WHERE ID<>@cpMainID AND Name =@cpName AND dcProvinceID=@provinceID)
	BEGIN
		SET @IsTure=1
	END

	IF EXISTS(SELECT 'X' FROM cpMain WITH(NOLOCK) WHERE ID<>@cpMainID AND Name =@cpName AND dcProvinceID=@provinceID AND MemberType<2 AND LastLoginDate<DATEADD(month, -1, GETDATE()))
	BEGIN
		SET @IsTure=1
	END

	IF @IsTure =1
	BEGIN
		SELECT @ColdCustomerID = ID 
		FROM MainDB..ColdCustomer WITH(NOLOCK)
		WHERE companyName = @cpName  
		AND isValid=1 
		AND ProvinceID in  ( 
			SELECT  ID 
			FROM Maindb..dcprovince  
			WHERE SouthNorth = ( 
				SELECT SouthNorth 
				FROM Maindb..dcprovince  
				WHERE id = @provinceID  
				) 
			)
		AND AddDate>DATEADD(day, -14, GETDATE())

		IF @ColdCustomerID > 0
		BEGIN
			UPDATE MainDB..ColdCustomer SET CpMainID = @cpMainID,RegisterDate=GETDATE(),Status=2 WHERE ID=@ColdCustomerID
		END
	END
END

GO
/****** Object:  StoredProcedure [dbo].[ccColdCustomerByIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.30
--创建人：Nick
--说明：判断是否是冷客户
--#####################################################
CREATE PROCEDURE [dbo].[ccColdCustomerByIDSelect]
(
	@CpmainID INT
)
AS
BEGIN TRY
	SELECT TOP 1 * FROM maindb..ColdCustomer WHERE CpmainID = @CpmainID
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[ccCompany_xinxiPasswordByEmailUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.30
--创建人：Nick
--说明：重置Company_xinxi里的密碼
--#####################################################
CREATE PROCEDURE [dbo].[ccCompany_xinxiPasswordByEmailUpdate]
(
	@Password VARCHAR(50),
	@UserName VARCHAR(50),
	@Email VARCHAR(50)
)
AS
BEGIN TRY
	UPDATE Company_xinxi SET password=@Password WHERE username=@UserName AND email=@Email
	RETURN 1
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[ccCompanyInformSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ccCompanyInformSelect]
(
	@Object VARCHAR(50),
	@Province_ID VARCHAR(2)
)
AS
BEGIN
	SELECT ID,TITLE,Type,Link,Content,At1
	FROM CompanyInform WITH(NOLOCK)
	WHERE Status=1 
	AND Object LIKE '%'+@Object+'%'
	AND Province LIKE '%'+@Province_ID+'%'
	AND EndDate > GETDATE()
	ORDER BY AddDate DESC
END














GO
/****** Object:  StoredProcedure [dbo].[ccCompanyLuckDrawByCpMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2016.01.19
--创建人：NICK
--说明：获取企业抽奖记录
--#####################################################
CREATE PROCEDURE [dbo].[ccCompanyLuckDrawByCpMainIDSelect]
(
	@CpMainID INT
)
AS
BEGIN
	SELECT TOP 100 * 
	FROM CompanyLuckDraw WITH(NOLOCK)
	WHERE CpMainID = @CpMainID
	ORDER BY LotteryDate DESC
END


GO
/****** Object:  StoredProcedure [dbo].[ccCompanyNotifyByCompanyIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ccCompanyNotifyByCompanyIDSelect]
(
	@CompanyID INT
)
AS
BEGIN
	SET NOCOUNT ON
	SELECT *
	FROM CompanyNotify WITH(NOLOCK)
	WHERE CompanyID=@CompanyID 
	AND ((Type=1 AND Received=0) Or (Type=2 AND EndDate>GETDATE()))
	ORDER BY AddDate DESC
END














GO
/****** Object:  StoredProcedure [dbo].[ccCompanyNotifyByReceivedUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[ccCompanyNotifyByReceivedUpdate]
(
	@ID INT,
	@CompanyID INT
)
AS
BEGIN
	SET NOCOUNT ON
	UPDATE CompanyNotify SET Received = 1 WHERE ID = @ID AND CompanyID = @CompanyID AND Received = 0
END














GO
/****** Object:  StoredProcedure [dbo].[ccCpCertificationDelete]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ccCpCertificationDelete]
(
    @cpMainID INT
)
AS
SET NOCOUNT ON
BEGIN
    DECLARE @cpCertificationID INT, @MemberType TINYINT, @CerType TINYINT
    SELECT @cpCertificationID = ID, @MemberType = MemberType, @CerType = CerType FROM cpCertification WITH(NOLOCK) WHERE cpMainID = @cpMainID AND CerStatus IS NULL
    IF @cpCertificationID IS NULL
        RETURN 0

    DELETE FROM cpCertification WHERE ID = @cpCertificationID
    DELETE FROM cpLicence WHERE cpCertificationID = @cpCertificationID

	DECLARE @Desc NVARCHAR(50)

    IF @MemberType = 1 AND @CerType = 1
    BEGIN
        INSERT INTO LogDB..UserActionDetail(ActionType, ActionID, dcProvinceID)
        SELECT TOP 1 206, @CpMainID, dcProvinceID FROM cpMain WITH(NOLOCK) WHERE ID = @CpMainID
		SET @Desc = '实名认证（对公）'
    END
    ELSE IF @MemberType = 1 AND @CerType = 2
    BEGIN
        INSERT INTO LogDB..UserActionDetail(ActionType, ActionID, dcProvinceID)
        SELECT TOP 1 207, @CpMainID, dcProvinceID FROM cpMain WITH(NOLOCK) WHERE ID = @CpMainID
		SET @Desc = '实名认证（法人）'
    END
    ELSE IF @MemberType = 2 AND @CerType = 2
    BEGIN
        INSERT INTO LogDB..UserActionDetail(ActionType, ActionID, dcProvinceID)
        SELECT TOP 1 204, @CpMainID, dcProvinceID FROM cpMain WITH(NOLOCK) WHERE ID = @CpMainID
		SET @Desc = '普通认证（营业执照+个人）'
    END
    ELSE IF @MemberType = 2 AND @CerType = 3
    BEGIN
        INSERT INTO LogDB..UserActionDetail(ActionType, ActionID, dcProvinceID)
        SELECT TOP 1 205, @CpMainID, dcProvinceID FROM cpMain WITH(NOLOCK) WHERE ID = @CpMainID
		SET @Desc = '普通认证（邮箱）'
    END

	INSERT INTO RtxNotifyLog(Receiver, RtxTitle, RtxMessage, SendType, DelayTime, ShowType) 
	SELECT ConsultantId, '企业认证取消通知', Name + '(' + LTRIM(STR(ID)) + ')取消了企业认证[' + @Desc + ']。http://sysback.51rc.com/newoa/company/cp/cpMainInfo?id=' + LTRIM(STR(ID)) + '&code=' + LTRIM(STR(DATEPART(HOUR, RegDate) * 100 + DATEPART(MINUTE, RegDate))), 0, 0, 1
	FROM cpMain WHERE ConsultantId > 0 AND ID = @CpMainID

    RETURN 1
END
SET NOCOUNT OFF
GO
/****** Object:  StoredProcedure [dbo].[cccpCertificationInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[cccpCertificationInsert]
(
    @cpMainID INT,
    @CerType TINYINT,
    @CompanyName VARCHAR(100),
    @Mobile VARCHAR(11)
)
AS
SET NOCOUNT ON
BEGIN
    DELETE FROM cpCertification WHERE cpMainID = @cpMainID AND CerStatus IS NULL

    IF @CerType = 0
        SET @CerType = NULL

    IF CHARINDEX('公司', @CompanyName) > 0
        SET @CerType = 1

    INSERT INTO cpCertification(cpMainID, CompanyName, Mobile, MemberType, CerType)
    VALUES(@cpMainID, @CompanyName, @Mobile, 1, @CerType)
END
SET NOCOUNT OFF
GO
/****** Object:  StoredProcedure [dbo].[cccpCertificationUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[cccpCertificationUpdate]
(
	@cpMainID INT,
	@cpCertificationID INT,
	@CerType TINYINT
)
AS
SET NOCOUNT ON
BEGIN
	IF NOT EXISTS(SELECT 'X' FROM cpCertification WITH(NOLOCK) WHERE ID = @cpCertificationID AND cpMainID = @cpMainID AND CerStatus IS NULL)
		RETURN 0

	UPDATE cpCertification SET CerType = @CerType WHERE ID = @cpCertificationID
	RETURN 1
END
SET NOCOUNT OFF
GO
/****** Object:  StoredProcedure [dbo].[ccCpCoinByCpMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		mice
-- Create date: 2014-8-12
-- Description:	返回企业的金币详情
-- Modify: Lucifer 2016-9-29 抽奖赠送orderid=0
-- =============================================
CREATE PROCEDURE [dbo].[ccCpCoinByCpMainIDSelect]
(
	@cpMainID INT
)
AS
BEGIN
	SELECT TOP 200 a.*, b.OrderType , b.ServiceType
	FROM MainDb..cpCoin a LEFT JOIN caOrder b ON a.caOrderID = b.id
	WHERE a.cpMainID = @cpMainID 
	ORDER BY a.AddDate DESC
END
GO
/****** Object:  StoredProcedure [dbo].[ccCpCompanyEmailInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ccCpCompanyEmailInsert]
(
    @CompanyName VARCHAR(100),
	@Mobile VARCHAR(11),
	@Email VARCHAR(50),
    @cpMainID INT
)
AS
SET NOCOUNT ON
BEGIN
    DELETE FROM cpCertification WHERE cpMainID = @cpMainID AND CerStatus IS NULL

    DECLARE @cpCertificationID INT
    INSERT INTO cpCertification(cpMainID, CompanyName, Mobile, MemberType, CerType)
    VALUES(@cpMainID, @CompanyName, @Mobile, 2, 3)
    SET @cpCertificationID = @@IDENTITY
    
    DECLARE @VerifyCode AS VARCHAR(6)
    SELECT @VerifyCode = RAND() * 899999 + 100000
    INSERT INTO cpCompanyEmail(cpCertificationID, Email, VerifyCode)
    VALUES(@cpCertificationID, @Email, @VerifyCode)

    RETURN 1
END
SET NOCOUNT OFF
GO
/****** Object:  StoredProcedure [dbo].[ccCpCompanyEmailUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ccCpCompanyEmailUpdate]
(
	@VerifyCode VARCHAR(6),
	@cpCertificationID INT,
	@cpMainID INT
)
AS
SET NOCOUNT ON
BEGIN
	IF NOT EXISTS(SELECT 'X' FROM cpCertification WITH(NOLOCK) WHERE ID = @cpCertificationID AND cpMainID = @cpMainID AND CerStatus IS NULL)
		RETURN -1
	
	IF EXISTS(SELECT 'X' FROM cpCompanyEmail WITH(NOLOCK) WHERE cpCertificationID = @cpCertificationID AND CheckResult IS NOT NULL)
		RETURN -1

	IF EXISTS(SELECT 'X' FROM cpCompanyEmail WITH(NOLOCK) WHERE cpCertificationID = @cpCertificationID AND VerifyCode = @VerifyCode)
	BEGIN
		UPDATE cpCompanyEmail SET CheckResult = 2 WHERE cpCertificationID = @cpCertificationID
		RETURN 1
	END
	ELSE
		RETURN 0
END
SET NOCOUNT OFF
GO
/****** Object:  StoredProcedure [dbo].[cccpCvShieldByCpMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.31
--创建人：Nick
--说明：根据企业编号，获取屏蔽的简历 编号
--#####################################################
CREATE PROCEDURE [dbo].[cccpCvShieldByCpMainIDSelect]
(
	@CpMainID INT
)
AS
BEGIN TRY
	SELECT * FROM cpCvShield WITH(NOLOCK) WHERE cpMainID = @CpMainID
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[cccpCvShieldByCvMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.31
--创建人：Nick
--说明：根据企业编号、简历编号 获取 屏蔽的简历
--#####################################################
CREATE PROCEDURE [dbo].[cccpCvShieldByCvMainIDSelect]
(
	@CpMainID INT,
	@CvMainID INT
)
AS
BEGIN TRY
	SELECT * FROM cpCvShield WITH(NOLOCK) WHERE cpMainID = @CpMainID AND CvMainID = @CvMainID
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[cccpCvShieldDelete]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.31
--创建人：Nick
--说明：将简历编号 从 cpCvShield表中删除
--#####################################################
CREATE PROCEDURE [dbo].[cccpCvShieldDelete]
(
	@cpMainID INT,
	@cvMainID INT
)
AS
BEGIN TRY
	DELETE FROM cpCvShield Where CpMainID=@cpMainID AND CvMainID=@cvMainID
	RETURN 1
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[cccpCvShieldInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.31
--创建人：Nick
--说明：将建立编号 加入cpCvShield 表
--#####################################################
CREATE PROCEDURE [dbo].[cccpCvShieldInsert]
(
	@cpMainID INT,
	@cvMainID INT
)
AS
BEGIN TRY
	INSERT INTO cpCvShield(cpMainID,cvMainID) VALUES(@cpMainID,@cvMainID)
	RETURN 1
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[cccpImage_beforeInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 将上传logo的信息先放在cpimage_before中
-- harry
--2016-10-19
CREATE PROCEDURE [dbo].[cccpImage_beforeInsert]
	@cpMainID INT,
	@Photo VARCHAR(50)
AS
SET NOCOUNT ON
BEGIN
DECLARE @MaxId AS INT

INSERT INTO cpimage_before (cpMainID,FileUrl,addDate)
	VALUES(@cpMainID,dbo.SafeSQL(@Photo),getdate())
SET @MaxID = @@IDENTITY

RETURN @MaxID
END
SET NOCOUNT OFF

GO
/****** Object:  StoredProcedure [dbo].[ccCpImageByDescriptionUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:        
-- Create date: <2015-1-20>
-- Description:    <修改图片备注>
-- =============================================
CREATE PROCEDURE [dbo].[ccCpImageByDescriptionUpdate]
(
	@ID VARCHAR(20),
	@description NVARCHAR(50)
)
AS
BEGIN
	UPDATE maindb..cpImage 
	SET Description = @description, 
		HasPassed = NULL,
		CheckMan = NULL,	
		CheckDate = NULL,	
		CheckMessage = NULL,
		AddDate=GETDATE()
	WHERE id= @ID
END


GO
/****** Object:  StoredProcedure [dbo].[ccCpImageByHasPassedUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--###########################
--创建时间：2014.11.27
--创建人：Nick
--说明：后台形象图上传
--###########################
CREATE PROCEDURE [dbo].[ccCpImageByHasPassedUpdate]
	@ID INT,
	@HasPassed INT
AS
BEGIN
	UPDATE cpImage SET HasPassed=@HasPassed WHERE ID=@ID
END

GO
/****** Object:  StoredProcedure [dbo].[ccCpImageByIDDelete]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----------------------------
--Peter 2014-08-26修改
--添加积分扣减
--Peter 2014-9-1 修改
--判断企业之前没有上传过
-- [ccCpImageByIDDelete] 112,371108,1, 1
-------------------------
CREATE PROCEDURE [dbo].[ccCpImageByIDDelete]
(
	@OperatorID INT,
	@cpMainID INT,
	@ImgType TINYINT,
	@ID INT
)
AS
SET NOCOUNT ON
BEGIN
	DECLARE @caMainId INT
	--LOGO图
	IF @ImgType = 1
	BEGIN
		DELETE FROM cpImage WHERE cpMainID=@cpMainID AND ImgType=@ImgType

		IF EXISTS (SELECT 'x' FROM cpMain WHERE ID = @cpMainID AND HasLogo = 1)
		BEGIN
			DECLARE @Point INT
			SELECT TOP 1 @Point = Point * -1 FROM cpPoint WHERE cpMainId = @cpMainId AND ChangeId IN(7, 8) ORDER BY ID DESC
			IF @Point < 0
				INSERT INTO cpPoint(cpMainID, ChangeID, Point, LastModifyDate) VALUES(@cpMainID, 8, @Point, GETDATE())
			ELSE
				INSERT INTO cpPoint(cpMainID, ChangeID, Point, LastModifyDate) VALUES(@cpMainID, 8, -10, GETDATE())
		END

		UPDATE cpMain SET HasLogo=0 WHERE ID=@cpMainID

		SELECT TOP 1 @caMainId = Id FROM caMAin WHERE cpMainId = @cpMainId ORDER BY ID
		EXEC ccCaOperationLogInsert @caMainId, 21, '删除企业LOGO图'
	END
	--形象图
	IF @ImgType = 2
	BEGIN
		DELETE FROM cpImage WHERE cpMainID=@cpMainID AND ImgType=@ImgType AND ID=@ID
		IF NOT EXISTS(SELECT 'X' FROM cpImage WITH(NOLOCK) WHERE cpMainID=@cpMainID AND ImgType=2 AND HasPassed=1)
		BEGIN
			IF EXISTS (SELECT 'x' FROM cpMain WHERE ID = @cpMainID AND HasVisual = 1)	
				INSERT INTO cpPoint (cpMainID,ChangeID,Point,LastModifyDate) VALUES(@cpMainID,10,-10,GETDATE())

			UPDATE cpMain SET HasVisual=0 WHERE ID=@cpMainID			
		END

		SELECT TOP 1 @caMainId = Id FROM caMAin WHERE cpMainId = @cpMainId ORDER BY ID
		EXEC ccCaOperationLogInsert @caMainId, 23, '删除企业形象图'
	END
	--环境图
	IF @ImgType = 3
	BEGIN
		IF EXISTS(SELECT 'X' FROM cpImage WITH(NOLOCK) WHERE cpMainID=@cpMainID AND ImgType=@ImgType AND ID=@ID AND HasPassed=1)
		BEGIN
			INSERT INTO cpPoint (cpMainID,ChangeID,Point,LastModifyDate) VALUES(@cpMainID,25,-10,GETDATE())	
		END

		DELETE FROM cpImage WHERE cpMainID=@cpMainID AND ImgType=@ImgType AND ID=@ID

		SELECT TOP 1 @caMainId = Id FROM caMain WHERE cpMainId = @cpMainId ORDER BY ID
		EXEC ccCaOperationLogInsert @caMainId, 46, '删除企业环境图'
	END
END



GO
/****** Object:  StoredProcedure [dbo].[ccCpImageByIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--###########################
--创建时间：2014.11.27
--创建人：Nick
--说明：获取后台审核形象图
--###########################
CREATE PROCEDURE [dbo].[ccCpImageByIDSelect]
	@cpMainID INT,
	@ID INT
AS
BEGIN
	SELECT * FROM cpImage WITH(NOLOCK) 
	WHERE ID = @ID AND CpMainID = @cpMainID
END



GO
/****** Object:  StoredProcedure [dbo].[ccCpImageByVideoInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ccCpImageByVideoInsert]
(
	@OperatorID INT,
	@cpMainID INT,
	@ImgType TINYINT,
	@ImgFile VARCHAR(500),
	@videoId varchar(100),
	@description nvarchar(200)
)
AS
SET NOCOUNT ON
BEGIN
	INSERT INTO cpImage (cpMainID,ImgType,ImgFile,videoId,Description)
	VALUES(@cpMainID,@ImgType,@ImgFile,@videoId,@description)
	EXEC ccCaOperationLogInsert @OperatorID, 43, '上传企业宣传视频'

	RETURN 1
END
SET NOCOUNT OFF

GO
/****** Object:  StoredProcedure [dbo].[ccCpImageClickNumberUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Description:	<企业环境照片点击有用数量更新>;
-- Creater : mice 2015-1-7 
-- =============================================
CREATE PROCEDURE [dbo].[ccCpImageClickNumberUpdate]
(
	@ID INT
)
AS
BEGIN

	UPDATE Maindb..cpImage 
	SET ClickNumber = ISNULL(ClickNumber, 0) + 1
	WHERE ID = @ID

END
GO
/****** Object:  StoredProcedure [dbo].[ccCpImageDelete]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[ccCpImageDelete]
	@OperatorID INT,
	@cpMainID INT,
	@ImgType TINYINT
AS
BEGIN TRAN
	BEGIN TRY
		DELETE FROM cpImage WHERE cpMainID=@cpMainID AND ImgType=@ImgType
		--LOGO图
		IF @ImgType = 1
			BEGIN
				UPDATE cpMain SET HasLOGO=0 WHERE ID=@cpMainID

				EXEC ccCaOperationLogInsert @OperatorID, 21, '删除企业LOGO图'
			END
		--形象图
		IF @ImgType = 2
			BEGIN
				UPDATE cpMain SET HasVisual=0 WHERE ID=@cpMainID

				EXEC ccCaOperationLogInsert @OperatorID, 23, '删除企业形象图'
			END
	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH
COMMIT TRAN
RETURN 1
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END 














GO
/****** Object:  StoredProcedure [dbo].[ccCpImageInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ccCpImageInsert]
(
	@OperatorID INT,
	@cpMainID INT,
	@ImgType TINYINT,
	@ImgFile VARCHAR(50)
)
AS
SET NOCOUNT ON
BEGIN
	DECLARE @MaxId AS INT, @Desc AS VARCHAR(200)
		
	DELETE FROM cpImage WHERE cpMainID=@cpMainID AND ImgType=@ImgType
	INSERT INTO cpImage (cpMainID,ImgType,ImgFile)
	VALUES(@cpMainID,@ImgType,@ImgFile)

	SET @MaxID = @@IDENTITY

	--LOGO图
	IF @ImgType = 1
	BEGIN
		SET @Desc = '上传LOGO图，文件名:' + @ImgFile
		UPDATE cpMain SET HasLOGO=0 WHERE ID=@cpMainID
		IF @OperatorID > 0
			EXEC ccCaOperationLogInsert @OperatorID, 20, @Desc

		INSERT INTO bsCpStatus(cpMainID, StatusID) VALUES(@cpMainID, 2)
	END

	--形象图
	IF @ImgType = 2	
	BEGIN
		SET @Desc = '上传形象图，文件名:' + @ImgFile
		UPDATE cpMain SET HasVisual=0 WHERE ID=@cpMainID
		IF @OperatorID > 0
			EXEC ccCaOperationLogInsert @OperatorID, 22, @Desc

		INSERT INTO bsCpStatus(cpMainID,StatusID) VALUES(@cpMainID,3)
	END

	RETURN @MaxID
END
GO
/****** Object:  StoredProcedure [dbo].[ccCpImageInsertByOperatorID]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--=============================================
-- 创建：	Harry
-- 检查：	2016-10-19		
-- 说明：	企业logo上传
--============================================= 
CREATE PROCEDURE [dbo].[ccCpImageInsertByOperatorID]
	@OperatorID INT,
	@cpMainID INT 
AS
BEGIN TRAN
	DECLARE @MaxId AS INT, @Desc AS VARCHAR(200),@ImgFile VARCHAR(50) 
	BEGIN TRY
		DELETE FROM cpImage WHERE cpMainID=@cpMainID AND ImgType=1
		SELECT TOP 1 @ImgFile=FileUrl FROM cpImage_before WHERE cpMainID = @cpMainID ORDER BY ID DESC
		INSERT INTO cpImage (cpMainID,ImgType,ImgFile)
			SELECT @cpMainID, 1, @ImgFile

		SET @MaxID = @@IDENTITY
		 
		SET @Desc = '上传LOGO图，文件名:' + @ImgFile
		UPDATE cpMain SET HasLOGO=0 WHERE ID=@cpMainID
		IF @OperatorID > 0
			EXEC ccCaOperationLogInsert @OperatorID, 20, @Desc

		INSERT INTO bsCpStatus(cpMainID, StatusID) VALUES(@cpMainID, 2)
			 
		 
	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH
COMMIT TRAN
RETURN @MaxID
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END 

GO
/****** Object:  StoredProcedure [dbo].[ccCpImageOrderNoUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Mice, 123 >
-- Create date: <2015-01-08>
-- Description:	<企业环境照片排序>
-- =============================================
CREATE PROCEDURE [dbo].[ccCpImageOrderNoUpdate]
(
	@ImgID VARCHAR(200),
	@ImgOrderNo VARCHAR(50)
)
AS
BEGIN
	DECLARE @t1 AS TABLE(ID INT IDENTITY(1, 1), ImgId INT, OrderNo INT)
	DECLARE @t2 AS TABLE (ID INT IDENTITY(1, 1), OrderNo INT)

	INSERT INTO @t1(ImgId) SELECT a FROM dbo.fnsplit(@ImgID,',')
	INSERT INTO @t2(OrderNo) SELECT a FROM dbo.fnsplit(@ImgOrderNo,',')

	UPDATE a SET a.OrderNo = b.OrderNo
	FROM @t1 a, @t2 b
	WHERE a.Id = b.ID

	UPDATE a SET a.OrderNo = b.OrderNo
	FROM Maindb..cpImage a, @t1 b
	WHERE a.Id = b.ImgId
END



GO
/****** Object:  StoredProcedure [dbo].[ccCpImageSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ccCpImageSelect]
(
	@cpMainID INT,
	@ImgType INT
)
AS
BEGIN
    IF @ImgType = 4
		SELECT *
        FROM cpImage WITH(NOLOCK)
        WHERE cpMainID = @cpMainID AND ImgType IN(4, 5,6)
    ELSE
        SELECT *
        FROM cpImage WITH(NOLOCK)
        WHERE cpMainID = @cpMainID AND ImgType = @ImgType
END
GO
/****** Object:  StoredProcedure [dbo].[ccCpIndexLinkByCaMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ccCpIndexLinkByCaMainIDSelect]
(
    @caMainID INT,
    @IsManager INT,
    @cpMainID INT
)
AS
BEGIN
    DECLARE @JobCount AS INT        --已发布职位数量
    DECLARE @DownLoadCount AS INT        --下载简历数量
    DECLARE @FavorateCount AS INT        --收藏简历数量
    DECLARE @OneWeekApplyCount AS INT    --一周内应聘简历数量
    DECLARE @NoRepliedJobApply AS INT    --未答复的应聘简历
    DECLARE @NoViewedMessage AS INT        --未查看的留言

    --已发布职位数量
    SELECT @JobCount = COUNT(*)
    FROM Job a WITH(NOLOCK), caMain b WITH(NOLOCK)
    WHERE a.cpMainId = b.cpMainId 
    AND b.ID = @caMainID 
    AND a.IsDelete=0
    AND a.IssueDate IS NOT NULL
    AND a.IssueEnd > GETDATE()

    --下载简历数量
    SELECT @DownLoadCount = SUM(a.cnt) FROM(
        SELECT COUNT(*) cnt
        FROM caDailyGiftLog a WITH(NOLOCK)
        INNER JOIN cvMain b WITH(NOLOCK) ON b.ID = a.cvMainID
        INNER JOIN paMain c WITH(NOLOCK) ON c.ID = b.paMainID
        WHERE caMainID = @caMainID
		AND a.AddDate > DATEADD(YEAR, -2, GETDATE())
        UNION
        SELECT COUNT(*) cnt
        FROM caActiveLog a WITH(NOLOCK)
        INNER JOIN cvMain b WITH(NOLOCK) ON b.ID = a.cvMainID
        INNER JOIN paMain c WITH(NOLOCK) ON c.ID = b.paMainID
        WHERE caMainID = @caMainID
		AND a.AddDate > DATEADD(YEAR, -2, GETDATE())
    )a

    --收藏简历数量
    SELECT @FavorateCount = COUNT(A.ID) 
    FROM caFavorate a,Job b 
    WHERE a.caMainID=@caMainID and a.JobID=b.ID AND b.IsDelete = 0

    IF @IsManager = 1
    BEGIN
        --一Month内应聘简历数量
        SELECT @OneWeekApplyCount = COUNT(1) 
        FROM exJobApply WITH(index(IX_exJobApply_JobId) NOLOCK) 
        WHERE  CompanyDeleted = 0
        AND JobID IN (
            SELECT ID FROM Job WITH(NOLOCK) 
            WHERE cPMainID = @cpMainID AND IsDelete = 0
        )
    END
    ELSE
    BEGIN
        --一Month内应聘简历数量
        SELECT @OneWeekApplyCount = COUNT(1) 
        FROM exJobApply WITH(index(IX_exJobApply_JobId) NOLOCK) 
        WHERE  CompanyDeleted = 0
        AND JobID IN (SELECT ID FROM Job WITH(NOLOCK) WHERE caMainID = @caMainID AND IsDelete = 0)
    END

    --未答复的应聘简历
    SELECT @NoRepliedJobApply = COUNT(1)
    FROM exJobApply a WITH(NOLOCK), 
        Job b WITH(NOLOCK), 
        cvMain c WITH(NOLOCK),
        paMain d WITH(NOLOCK)
    WHERE a.Reply = 0
    And a.CompanyDeleted = 0 
    AND a.JobID =b.ID
    AND b.caMainID = @caMainID
    AND b.IsDelete = 0
    AND a.IsFilter = 0
    AND C.ID = a.cvMainID
    AND D.ID = C.PamainID

    --未查看的留言
    SELECT @NoViewedMessage = COUNT(1)
    FROM exMessageP2C WITH(NOLOCK)
    WHERE IsViewed = 0
    AND CompanyDeleted = 0
    AND caMainID = @caMainID
        
    SELECT @JobCount AS JobCount,@DownLoadCount AS DownLoadCount,
        @FavorateCount AS FavorateCount,@OneWeekApplyCount AS OneWeekApplyCount,
        @NoRepliedJobApply AS NoRepliedJobApply, @NoViewedMessage AS NoViewedMessage
END
GO
/****** Object:  StoredProcedure [dbo].[ccCpIndexLinkByCountSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ccCpIndexLinkByCountSelect]
(
	@caMainID INT
)
AS
BEGIN TRY
	DECLARE @JobCount AS INT			--已发布职位数量
	DECLARE @DownLoadCount AS INT		--下载简历数量
	DECLARE @FavorateCount AS INT		--收藏简历数量
	DECLARE @OneWeekApplyCount AS INT	--一周内应聘简历数量
	DECLARE @NoRepliedJobApply AS INT	--未答复的应聘简历
	DECLARE @NoViewedMessage AS INT		--未查看的留言

	--已发布职位数量
	SELECT @JobCount = COUNT(*)
	FROM Job a WITH(NOLOCK), caMain b WITH(NOLOCK)
	WHERE a.cpMainId = b.cpMainId 
	AND b.ID = @caMainID 
	AND a.IsDelete=0
	AND a.IssueDate IS NOT NULL
	AND a.IssueEnd > GETDATE()

	--下载简历数量
	SELECT @DownLoadCount = SUM(a.cnt) FROM(
--		SELECT COUNT(*) cnt FROM caDailyGiftLog WHERE caMainID  = @caMainID UNION ALL 
--		SELECT COUNT(*) cnt FROM caActiveLog WHERE caMainID  = @caMainID
		SELECT COUNT(*) cnt
		FROM caDailyGiftLog a WITH(NOLOCK)
		INNER JOIN cvMain b WITH(NOLOCK) ON b.ID = a.cvMainID
		INNER JOIN paMain c WITH(NOLOCK) ON c.ID = b.paMainID
		WHERE caMainID  = @caMainID
		UNION
		SELECT COUNT(*) cnt
		FROM caActiveLog a WITH(NOLOCK)
		INNER JOIN cvMain b WITH(NOLOCK) ON b.ID = a.cvMainID
		INNER JOIN paMain c WITH(NOLOCK) ON c.ID = b.paMainID
		WHERE caMainID  = @caMainID
	)a

	--收藏简历数量
	SELECT @FavorateCount = COUNT(A.ID) 
	FROM caFavorate a,Job b 
	WHERE a.caMainID=@caMainID and a.JobID=b.ID AND b.IsDelete = 0

	--一Month内应聘简历数量
	SELECT @OneWeekApplyCount = COUNT(1) 
	FROM exJobApply WITH(index(IX_exJobApply_JobId) NOLOCK) 
	WHERE AddDate > DATEADD(Month,-1,GETDATE()) AND CompanyDeleted = 0
	AND JobID IN (SELECT ID FROM Job WITH(NOLOCK) WHERE caMainID = @caMainID AND IsDelete = 0)

	--未答复的应聘简历
	SELECT @NoRepliedJobApply = COUNT(1)
	FROM exJobApply a WITH(NOLOCK), Job b WITH(NOLOCK),cvMain c,paMain d
	WHERE a.Reply = 0
	And a.CompanyDeleted = 0 
	AND a.JobID =b.ID
	AND b.caMainID = @caMainID
	AND b.IsDelete = 0 
	AND C.ID = a.cvMainID
	AND D.ID = C.PamainID

	--未查看的留言
	SELECT @NoViewedMessage = COUNT(1)
	FROM exMessageP2C WITH(NOLOCK)
	WHERE IsViewed = 0
	AND CompanyDeleted = 0
	AND caMainID = @caMainID
		
	SELECT @JobCount AS JobCount,@DownLoadCount AS DownLoadCount ,@FavorateCount AS FavorateCount,@OneWeekApplyCount AS OneWeekApplyCount,
		 @NoRepliedJobApply AS NoRepliedJobApply, @NoViewedMessage AS NoViewedMessage
END TRY
BEGIN CATCH
	RETURN
END CATCH











GO
/****** Object:  StoredProcedure [dbo].[ccCpIndexPageSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--peter 2017
--sean 2018-4-3
CREATE PROCEDURE [dbo].[ccCpIndexPageSelect]
(
    @cpMainId INT, 
    @caMainId INT, 
    @ProvinceId INT, 
    @IsManager BIT, 
    @Object VARCHAR(10)
)
AS
SET NOCOUNT ON
BEGIN
	IF NOT EXISTS(SELECT 'x' FROM cpIndexPage WITH(NOLOCK) WHERE caMainId = @caMainId AND AddDate > DATEADD(MINUTE, -10, GETDATE()))
	BEGIN
		DECLARE @t AS TABLE(
			Id INT, 
			type INT, 
			ICount INT NULL, 
			Title NVARCHAR(100) NULL, 
			Link NVARCHAR(200) NULL, 
			ContentText NVARCHAR(MAX) NULL, 
			AddDate SMALLDATETIME NULL
		)

		--取未付款订单
		INSERT INTO @T(Id, type, ICount)
		SELECT @cpMainId, 0, COUNT(1) FROM caOrder WITH(NOLOCK)
		WHERE IsDeleted = 0 AND cpMainId = @cpMainId AND OrderStatus = 0 AND AddDate > DATEADD(MONTH, -2, GETDATE())

		--取未查看的网站消息
		INSERT INTO @T(Id, type, ContentText, AddDate, ICount)
		SELECT Id, 1, Content, AddDate, type FROM CompanyNotify WITH(NOLOCK)
		WHERE CompanyId = @cpMainId AND ((Type=1 AND Received=0) OR (Type=2 AND EndDate>GETDATE()))
		ORDER BY AddDate DESC

		--取未查看的反馈
		INSERT INTO @T(Id, type, ContentText, AddDate)
		SELECT TOP 1 Id, 2, ReplyMessage, ReplyDate FROM caFeedBack WITH(NOLOCK)
		WHERE caMainId = @caMainId AND IsReply = 1 AND ViewDate IS NULL 
		ORDER BY Id DESC

		--取未查看的投诉
		IF @IsManager = 1
			INSERT INTO @T(Id, type, ContentText, AddDate)
			SELECT TOP 1 a.Id, 3, a.Plaint, a.AddDate
			FROM PaPlaint a WITH(NOLOCK INDEX(IX_paPlaint_caMainId)), caMain b WITH( NOLOCK INDEX(IX_caMain_cpMainId))
			WHERE a.caMainId = b.Id AND b.cpMainId = @cpMainId AND IsViewed=0 AND ReplyType =1
			ORDER BY a.caMainId, a.Id DESC
		ELSE
			INSERT INTO @T(Id, type, ContentText, AddDate)
			SELECT TOP 1 Id, 3, Plaint, AddDate FROM PaPlaint WITH(NOLOCK INDEX(IX_paPlaint_caMainId))
			WHERE caMainId = @caMainId AND IsViewed=0 AND ReplyType = 1
			ORDER BY Id DESC

		--取未查看的网站分类通知
		INSERT INTO @T(Id, type, Title, ContentText, link, ICount)
		SELECT TOP 1 Id, 4, Title, Content, link, Type 
		FROM CompanyInform WITH(NOLOCK) 
		WHERE Status = 1 
		AND Object LIKE '%' + @Object + '%'
		AND Province LIKE '%' + LTRIM(STR(@ProvinceId)) + '%'
		AND EndDate > GETDATE() ORDER BY AddDate DESC

		--取当前调查
		INSERT INTO @T(Id, type, ContentText) 
		SELECT TOP 1 Id, 5, Title FROM Ivgt_Investigation WITH(NOLOCK) 
		WHERE ENDdate > GETDATE() 
		AND province Like '%' + LTRIM(STR(@provinceId)) + '%'
		AND type=1 
		ORDER BY adddate

		--如果有1个月内到期的职位, 修改截止日期
		IF EXISTS(SELECT 'x' FROM Job WITH(NOLOCK)
			WHERE caMainId = @caMainId
			AND IssueEnd < DATEADD(MONTH, 1, GETDATE())
			AND ValId = 1)
		BEGIN
			UPDATE Job SET IssueEnd = DATEADD(MINUTE, -1, CONVERT(VARCHAR(10), DATEADD(MONTH, 2, GETDATE()) + 1, 120))
			WHERE caMainId = @caMainId
			AND IssueEnd < DATEADD(MONTH, 1, GETDATE())
			AND ValId = 1
			AND @cpMainId <> 10371941
			
			IF @@ROWCOUNT > 0
			BEGIN
				INSERT INTO @T(Id, [Type], ContentText) VALUES(@caMainId, 6, '')
			END
		END

		--面试通知
		DECLARE @InterViewCnt INT
		SELECT @InterViewCnt = COUNT(*)
		FROM exInterview WITH(NOLOCK)
		WHERE JobId IN (
			SELECT Id FROM Job WITH(NOLOCK)
			WHERE cpMainId = @cpMainId
			AND caMainId = @caMainId
			)
		AND Replydate IS NOT NULL
		AND cpResultViewDate IS NULL

		IF @InterViewCnt > 0
			INSERT INTO @T(Id, [Type], ContentText, AddDate) VALUES(@caMainId, 7, @InterViewCnt, GETDATE())
		
		--求答复提醒
		DECLARE @ReplyViewCnt INT
		SELECT @ReplyViewCnt = COUNT(*)
		FROM ExJobApply  WITH(NOLOCK)
		WHERE JobId IN (
			SELECT Id FROM Job WITH(NOLOCK)
			WHERE cpMainId = @cpMainId
			AND caMainId = @caMainId
		)
		AND RemindDate IS NOT NULL
		AND cpRemindViewDate IS NULL

		IF @ReplyViewCnt > 0
			INSERT INTO @T(Id, [Type], ContentText, AddDate) VALUES(@caMainId, 8, @ReplyViewCnt, GETDATE())

		--取未填写发票的订单
		INSERT INTO @T(Id, type, ICount)
		SELECT TOP 1 @cpMainId, 9, Id FROM caOrder WITH(NOLOCK)
		WHERE IsDeleted = 0 AND cpMainId = @cpMainId 
		AND OrderStatus = 6 AND AddDate > DATEADD(DAY, -15, GETDATE())
		AND PaId > 0
		ORDER BY Id DESC

		UPDATE @t SET AddDate = GETDATE() WHERE AddDate IS NULL

		DELETE FROM cpIndexPage WHERE caMainId = @caMainId

		INSERT INTO cpIndexPage
		SELECT @caMainId, * FROM @T ORDER BY Type, Id
	END
	SELECT * FROM cpIndexPage WITH(NOLOCK) WHERE caMainId = @caMainId ORDER BY Type, Id
END

GO
/****** Object:  StoredProcedure [dbo].[ccCpIndexPageSelect2]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[ccCpIndexPageSelect2]
(
    @cpMainID INT, 
    @caMainID INT, 
    @ProvinceID INT, 
    @IsManager BIT, 
    @Object VARCHAR(10)
)
AS
SET NOCOUNT ON
BEGIN
	IF NOT EXISTS(SELECT 'x' FROM cpIndexPage WITH(NOLOCK) WHERE caMainId = @caMainId AND AddDate > DATEADD(MINUTE, -10, GETDATE()))
	BEGIN
		DECLARE @t AS TABLE(
			ID INT, 
			type INT, 
			ICount INT NULL, 
			Title NVARCHAR(100) NULL, 
			Link NVARCHAR(200) NULL, 
			ContentText NVARCHAR(MAX) NULL, 
			AddDate SMALLDATETIME NULL
		)

		--取未付款订单
		INSERT INTO @T(ID, type, ICount)
		SELECT @cpMainID, 0, COUNT(1) FROM caOrder WITH(NOLOCK)
		WHERE IsDeleted = 0 AND cpMainID = @cpMainID AND OrderStatus = 0 AND AddDate > DATEADD(MONTH, -2, GETDATE())

		--取未查看的网站消息
		INSERT INTO @T(ID, type, ContentText, AddDate, ICount)
		SELECT ID, 1, Content, AddDate, type FROM CompanyNotify WITH(NOLOCK)
		WHERE CompanyID = @cpMainID AND ((Type=1 AND Received=0) OR (Type=2 AND EndDate>GETDATE()))
		ORDER BY AddDate DESC

		--取未查看的反馈
		INSERT INTO @T(ID, type, ContentText, AddDate)
		SELECT TOP 1 ID, 2, ReplyMessage, ReplyDate FROM CaFeedBack WITH(NOLOCK)
		WHERE caMainID = @caMainID AND IsReply = 1 AND ViewDate IS NULL 
		ORDER BY ID DESC

		--取未查看的投诉
		IF @IsManager = 1
			INSERT INTO @T(ID, type, ContentText, AddDate)
			SELECT TOP 1 a.ID, 3, a.Plaint, a.AddDate
			FROM PaPlaint a WITH(NOLOCK INDEX(IX_paPlaint_caMainID)), caMain b WITH( NOLOCK INDEX(IX_caMain_cpMainID))
			WHERE a.caMainID = b.ID AND b.cpMainID = @cpMainID AND IsViewed=0 AND ReplyType =1
			ORDER BY a.CaMainID, a.ID DESC
		ELSE
			INSERT INTO @T(ID, type, ContentText, AddDate)
			SELECT TOP 1 ID, 3, Plaint, AddDate FROM PaPlaint WITH(NOLOCK INDEX(IX_paPlaint_caMainID))
			WHERE caMainID = @caMainID AND IsViewed=0 AND ReplyType = 1
			ORDER BY ID DESC

		--取未查看的网站分类通知
		INSERT INTO @T(ID, type, Title, ContentText, link, ICount)
		SELECT TOP 1 ID, 4, Title, Content, link, Type 
		FROM CompanyInform WITH(NOLOCK) 
		WHERE Status = 1 
		AND Object LIKE '%' + @Object + '%'
		AND Province LIKE '%' + LTRIM(STR(@ProvinceID)) + '%'
		AND EndDate > GETDATE() ORDER BY AddDate DESC

		--取当前调查
		INSERT INTO @T(ID, type, ContentText) 
		SELECT TOP 1 ID, 5, Title FROM Ivgt_Investigation WITH(NOLOCK) 
		WHERE ENDdate > GETDATE() 
		AND province Like '%' + LTRIM(STR(@provinceid)) + '%'
		AND type=1 
		ORDER BY adddate

		--如果有1个月内到期的职位, 修改截止日期
		UPDATE Job SET IssueEnd = DATEADD(MINUTE, -1, CONVERT(VARCHAR(10), DATEADD(MONTH, 2, GETDATE()) + 1, 120))
		WHERE caMainId = @caMainID
		AND IssueEnd < DATEADD(MONTH, 1, GETDATE())
		AND Valid = 1
		AND @cpMainID <> 10371941
		
		IF @@ROWCOUNT > 0
		BEGIN
			INSERT INTO @T(ID, [Type], ContentText) VALUES(@caMainID, 6, '')
		END

		--面试通知
		DECLARE @InterViewCnt INT
		SELECT @InterViewCnt = COUNT(*)
		FROM exInterview  WITH(NOLOCK)
		WHERE JOBID IN (
			SELECT ID FROM JOB WITH(NOLOCK)
			WHERE CpMainID = @cpMainID
			AND CaMainID = @caMainID
			)
		AND Replydate IS NOT NULL
		AND CpResultViewDate IS NULL

		IF @InterViewCnt > 0
			INSERT INTO @T(ID, [Type], ContentText, AddDate) VALUES(@caMainID, 7, @InterViewCnt, GETDATE())
		
		--求答复提醒
		DECLARE @ReplyViewCnt INT
		SELECT @ReplyViewCnt = COUNT(*)
		FROM ExJobApply  WITH(NOLOCK)
		WHERE JOBID IN (
			SELECT ID FROM JOB WITH(NOLOCK)
			WHERE CpMainID = @cpMainID
			AND CaMainID = @caMainID
		)
		AND RemindDate IS NOT NULL
		AND CpRemindViewDate IS NULL

		IF @ReplyViewCnt > 0
			INSERT INTO @T(ID, [Type], ContentText, AddDate) VALUES(@caMainID, 8, @ReplyViewCnt, GETDATE())

		--取未填写发票的订单
		INSERT INTO @T(ID, type, ICount)
		SELECT TOP 1 @cpMainID, 9, Id FROM caOrder WITH(NOLOCK)
		WHERE IsDeleted = 0 AND cpMainID = @cpMainID 
		AND OrderStatus = 6 AND AddDate > DATEADD(DAY, -15, GETDATE())
		AND Paid > 0
		ORDER BY ID DESC

		UPDATE @t SET AddDate = GETDATE() WHERE AddDate IS NULL

		DELETE FROM cpIndexPage WHERE caMainId = @caMainId

		INSERT INTO cpIndexPage
		SELECT @caMainId, * FROM @T ORDER BY Type, ID
	END
	SELECT * FROM cpIndexPage WITH(NOLOCK) WHERE caMainId = @caMainId ORDER BY Type, ID
END

GO
/****** Object:  StoredProcedure [dbo].[ccCpIndustryByCpMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.30
--创建人：Nick
--说明：根据cpmainid 获取industryid
--#####################################################
CREATE PROCEDURE [dbo].[ccCpIndustryByCpMainIDSelect]
(
	@CpMainID INT
)
AS
BEGIN TRY
	SELECT TOP 1 dcindustryid  FROM cpindustry WHERE CpmainID=@CpMainID
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[ccCpIndustrySelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ccCpIndustrySelect]
	@ID INT
AS
BEGIN
	SELECT * FROM cpIndustry WITH(NOLOCK) WHERE cpMainID = @ID
END














GO
/****** Object:  StoredProcedure [dbo].[ccCplicenceByCheckDateSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ccCplicenceByCheckDateSelect]
(
	@cpMainID INT,
	@CheckDate VARCHAR(30) OUTPUT
)
AS
BEGIN
	SELECT @CheckDate = CONVERT(VARCHAR(30), CheckDate, 120) FROM cpLicence WITH(NOLOCK)
	WHERE cpMainId = @cpMainID
	AND HasPassed = 1
	--PRINT @CheckDate
END














GO
/****** Object:  StoredProcedure [dbo].[cccpLicenceDelete]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--==========================================
--检查sean	2010-10-28
--营业执照删除
--==========================================
CREATE PROCEDURE [dbo].[cccpLicenceDelete]
	@caMainID INT,
	@cpMainID INT
AS
BEGIN TRAN
	BEGIN TRY
		IF EXISTS(SELECT 'x' FROM caMain WITH(NOLOCK) WHERE ID = @caMainID AND cpMainID = @cpMainId AND IsDelete = 0)
		BEGIN
			DELETE FROM cpLicence WHERE cpMainID=@cpMainID
			UPDATE cpMain SET HasLicence=0 WHERE ID=@cpMainID

			EXEC ccCaOperationLogInsert @caMainID, 25, '删除营业执照'
		END
		ELSE
			GOTO Err
	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH
COMMIT TRAN
RETURN 1
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END 














GO
/****** Object:  StoredProcedure [dbo].[cccpLicenceInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--==========================================
--检查sean	2010-10-28
--营业执照上传
--==========================================
CREATE PROCEDURE [dbo].[cccpLicenceInsert]
	@caMainID INT,
	@cpMainID INT,
	@ImgFile VARCHAR(50)
AS
BEGIN TRAN
	DECLARE @MaxId AS INT, @Desc AS VARCHAR(200)
	BEGIN TRY
		IF NOT EXISTS(SELECT 'x' FROM caMain WITH(NOLOCK) WHERE ID = @caMainID AND AccountType = 1 AND cpMainID = @cpMainID)
			GOTO ERR
		DECLARE @IP AS VARCHAR(31)
		SELECT TOP 1 @IP = LoginIP FROM caLoginLog WITH(NOLOCK) WHERE caMainId = @caMainID ORDER BY ID DESC

		DELETE FROM cpLicence WHERE cpMainID=@cpMainID
		UPDATE cpMain SET HasLicence=0 WHERE ID=@cpMainID
		INSERT INTO cpLicence (cpMainID,ImgFile, FileSource, Ip) VALUES(@cpMainID,@ImgFile, 1, @IP)
		SET @MaxID = @@IDENTITY

		SET @Desc = '上传营业执照，文件名:' + @ImgFile
		EXEC ccCaOperationLogInsert @caMainID, 24, @Desc
		
		--INSERT INTO bsCpStatus(cpMainID,StatusID) VALUES(@cpMainID,1)
	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH
COMMIT TRAN
RETURN @MaxID
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END














GO
/****** Object:  StoredProcedure [dbo].[cccpLicenceInsert20171019]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[cccpLicenceInsert20171019]
	@caMainID INT,
	@cpMainID INT,
	@ImgFile VARCHAR(50),
	@CompanyName VARCHAR(100),
	@Mobile VARCHAR(11)
AS
BEGIN TRAN
	DECLARE @MaxId AS INT, @Desc AS VARCHAR(200)
	BEGIN TRY
		IF NOT EXISTS(SELECT 'x' FROM caMain WITH(NOLOCK) WHERE ID = @caMainID AND AccountType = 1 AND cpMainID = @cpMainID)
			GOTO ERR

		DECLARE @cpCertificationID INT
        SELECT @cpCertificationID = ID FROM cpCertification WITH(NOLOCK) WHERE cpMainID = @cpMainID AND CerStatus IS NULL

        IF @cpCertificationID IS NULL
		BEGIN
			INSERT INTO cpCertification(cpMainID, CompanyName, Mobile, MemberType, CerType)
			VALUES(@cpMainID, @CompanyName, @Mobile, 2, 2)
			SET @cpCertificationID = @@IDENTITY
		END
		ELSE
			UPDATE cpCertification SET CompanyName = @CompanyName, Mobile = @Mobile WHERE ID = @cpCertificationID

		DECLARE @IP AS VARCHAR(31)
		SELECT TOP 1 @IP = LoginIP FROM caLoginLog WITH(NOLOCK) WHERE caMainId = @caMainID ORDER BY ID DESC

		DELETE FROM cpLicence WHERE cpCertificationID = @cpCertificationID 
		--UPDATE cpMain SET HasLicence = 0 WHERE ID = @cpMainID
		INSERT INTO cpLicence (cpMainID, cpCertificationID, ImgFile, FileSource, Ip) VALUES(@cpMainID, @cpCertificationID, @ImgFile, 1, @IP)
		SET @MaxID = @@IDENTITY

		SET @Desc = '上传营业执照，文件名:' + @ImgFile
		EXEC ccCaOperationLogInsert @caMainID, 24, @Desc
	END TRY
    BEGIN CATCH
        GOTO ERR
    END CATCH
COMMIT TRAN
RETURN @MaxID
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END
GO
/****** Object:  StoredProcedure [dbo].[ccCpLicenceLogByCpMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--===================================
--创建：	sean	2010-10-27
--获取最后一次一尼姑也执照审核错误记录
--===================================
CREATE PROCEDURE [dbo].[ccCpLicenceLogByCpMainIDSelect]
(
	@cpMainID INT
)
AS
BEGIN
	SELECT TOP 1 * FROM cpLicenceLog WITH(NOLOCK) WHERE cpMainID =@cpMainID ORDER BY ID DESC
END




















GO
/****** Object:  StoredProcedure [dbo].[cccpLicenceSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--==================================
--lambo 20101020 修改
--增加了FileSource，ip这两个字段
--审核：    Sean 2010-10-26
--==================================
CREATE PROCEDURE [dbo].[cccpLicenceSelect]
(
    @cpMainID INT
)
AS
BEGIN
	IF EXISTS(SELECT TOP 1 'X' FROM cpMain WITH(NOLOCK) WHERE ID = @cpMainID AND HasLicence = 1)
		SELECT a.*, b.AddDate RealNameDate
		FROM cpLicence a WITH(NOLOCK)
		LEFT JOIN CpRealNameLog b WITH(NOLOCK) ON b.cpMainID = a.cpMainID
		WHERE a.cpMainID = @cpMainID AND a.HasPassed = 1
		ORDER BY a.ID DESC
	ELSE
		SELECT a.*, b.AddDate RealNameDate
		FROM cpLicence a WITH(NOLOCK)
		LEFT JOIN CpRealNameLog b WITH(NOLOCK) ON b.cpMainID = a.cpMainID
		WHERE a.cpMainID = @cpMainID
		ORDER BY a.ID DESC
END
GO
/****** Object:  StoredProcedure [dbo].[ccCpMainAutoReplyConfirmUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--企业同意自动答复应聘的简历
--HARRY
--2017-5-17
CREATE PROCEDURE [dbo].[ccCpMainAutoReplyConfirmUpdate]
(
	@cpMainId INT
) 
AS
SET NOCOUNT ON
BEGIN
	UPDATE cpMain SET AutoReplyConfirm = GETDATE(), ReplyRate = 1 WHERE id = @cpMainId
END
SET NOCOUNT OFF

GO
/****** Object:  StoredProcedure [dbo].[ccCpMainBalanceUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ccCpMainBalanceUpdate]
(
	@ID INT,
	@BalanceDate VARCHAR(20),
	@Balance INT
)
AS
	UPDATE cpMain SET BalanceDate=@BalanceDate,Balance=@Balance WHERE ID=@ID
	














GO
/****** Object:  StoredProcedure [dbo].[ccCpMainByBlackEmailExist]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--==================================
--企业邮箱在黑名单
--检查：	sean	2010-10-22
--==================================
CREATE PROCEDURE [dbo].[ccCpMainByBlackEmailExist]
(
	@Email VARCHAR(50),
	@ErrorMessage NVARCHAR(500) OUT
)
AS
BEGIN
	SET @ErrorMessage = ''
	BEGIN TRY
		SET @Email=LTRIM(RTRIM(@Email))
		IF EXISTS(SELECT ID FROM company_black WITH(NOLOCK) WHERE email LIKE '%'+@Email+'%')
			SELECT TOP 1 @ErrorMessage=Reason FROM company_black WITH(NOLOCK) WHERE Email = @Email

	END TRY
	BEGIN CATCH
		SET @ErrorMessage = '检查邮件是否被屏蔽时出现错误，请稍后继续提交！'
	END CATCH
END














GO
/****** Object:  StoredProcedure [dbo].[ccCpMainByBlackNameExist]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--==================================
--企业名称在黑名单
--检查：	sean	2010-10-22
--==================================
CREATE PROCEDURE [dbo].[ccCpMainByBlackNameExist]
(
	@Name VARCHAR(100),
	@ErrorMessage NVARCHAR(500) OUT
)
AS
BEGIN
	SET @ErrorMessage = ''
	BEGIN TRY
		SET @Name=LTRIM(RTRIM(@Name))
		IF EXISTS(SELECT ID FROM company_black WITH(NOLOCK) WHERE CHARINDEX(LTRIM(RTRIM(companyname)),@Name)>0)
		BEGIN
			UPDATE Company_Black SET RefuseCount = RefuseCount + 1
			WHERE CHARINDEX(LTRIM(RTRIM(CompanyName)),@Name)>0

			SELECT TOP 1 @ErrorMessage=Reason
			FROM company_black WITH(NOLOCK)
			WHERE CHARINDEX(LTRIM(RTRIM(companyname)),@Name)>0
		END
	END TRY
	BEGIN CATCH
		SET @ErrorMessage = '检查单位名称是否被屏蔽时出现错误，请稍后继续提交！'
	END CATCH
END














GO
/****** Object:  StoredProcedure [dbo].[ccCpMainByBriefSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--sean 2014-8-13
CREATE PROCEDURE [dbo].[ccCpMainByBriefSelect]
(
	@cpMainId INT
)
AS
BEGIN
	SELECT Id, Name, SecondId, LEFT(Brief, 200) Brief FROM cpMain WITH(NOLOCK) WHERE Id = @cpMainId
END




GO
/****** Object:  StoredProcedure [dbo].[ccCpMainByConsultantAssignUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--==============================================
--创建：	Sean
--时间：	2010-10-22
--说明：	分配招聘顾问
-- Richard  按组分配修改为按省分配 2012-04-23修改
-- Sean  2013-6-19 改为按区域分配，并且增加订单联动
-- harry 2018-5-23 更名时分配不分给推广
--==============================================
CREATE PROCEDURE [dbo].[ccCpMainByConsultantAssignUpdate]
(
	@cpMainID INT,
	@dcProvinceID TINYINT
)
AS
SET NOCOUNT ON
--RETURN 1
IF NOT EXISTS(SELECT 'x' FROM dcProvince WITH(NOLOCK) WHERE AssignConsultant = 1 AND ID = @dcProvinceID)
	RETURN 1
IF EXISTS(SELECT 'x' FROM cpMain WITH(NOLOCK) WHERE id = @cpMainId AND IsLimitLogin = 9)
	RETURN 1

BEGIN TRAN
    --用于暂停客户的分配
	DECLARE @CompanyName AS VARCHAR(100),
		@ManagerUserID AS SMALLINT,
		@ThisManagerUserID AS SMALLINT,
		@ThisManagerDate AS DATETIME,
		@MemberType AS INT

	SELECT @CompanyName = Name, @ThisManagerUserID = ConsultantId,
		@ThisManagerDate = ConsultantDate, @MemberType = MemberType
    FROM cpMain WITH(NOLOCK) WHERE ID = @cpMainID

    IF @ThisManagerDate IS NULL
       SET @ThisManagerDate = GETDATE()

	--sean 2015-5-20 first judge is ColdCustomer
	--企业的营业执照审核通过后，重新分配招聘顾问。
	DECLARE @AddMan2 INT, @SouthNorth AS TINYINT
	SELECT @SouthNorth = SouthNorth FROM dcProvince WITH(NOLOCK) WHERE Id = @dcProvinceId

	SELECT TOP 1 @AddMan2 = AddMan FROM ColdCustomer WITH(NOLOCK) 
	WHERE ProvinceID IN (SELECT ID FROM dcProvince WITH(NOLOCK) WHERE  SouthNorth = @SouthNorth)
	--20160809 Lucifer修改，根据企业名称或关联的cpMainID
    --20170206 Lucifer修改，付费的转给招聘顾问，不给冷客户顾问
	AND (CompanyName = @CompanyName OR CpMainID = @cpMainID)
	AND NOT EXISTS(SELECT TOP 1 'x' FROM cpMain WHERE ([Name] = @CompanyName OR ID = @cpMainID) AND MemberType = 3)
	ORDER BY ID DESC
	
	--SELECT TOP 1 @AddMan2 = AddMan FROM ColdCustomer WITH(NOLOCK) WHERE CompanyName = @CompanyName ORDER BY ID DESC

	-- Richard  按组分配修改为按省分配 2012-04-23修改
	-- Sean  2013-6-19 改为按区域分配，并且增加订单联动
	-- Richard  保险、房地产公司不分给原来的顾问 2012-04-23修改
	IF CHARINDEX('物业顾问',@CompanyName)=0 and CHARINDEX('某公司',@CompanyName)=0 
	   and CHARINDEX('置业',@CompanyName)=0 and CHARINDEX('房地产',@CompanyName)=0 
	   and CHARINDEX('不动产',@CompanyName)=0 and CHARINDEX('房产',@CompanyName)=0
	   and CHARINDEX('住房',@CompanyName)=0 and CHARINDEX('保险',@CompanyName)=0
	BEGIN
		SELECT TOP 1 @ManagerUserID = ConsultantId
		FROM cpMain WITH(NOLOCK)
		WHERE ConsultantId IS NOT NULL
		-- Sean 2013-6-19 回复按区域分配
		AND dcProvinceID IN(SELECT ID FROM dcProvince WITH(NOLOCK) WHERE SouthNorth = @SouthNorth)
		-- Richard  按组分配修改为按省分配 2012-04-23修改
		-- AND dcProvinceID = @dcProvinceID
		AND Name = @CompanyName
		AND ID <> @cpMainID   --Richard 2011年12月6日增加
		AND ConsultantDate < @ThisManagerDate   --Richard 2011年12月11日增加 
		AND consultantId NOT IN(select id FROM manageruser where deptid=15)--harry 2018-5-23
		ORDER BY ConsultantDate desc

		IF @ManagerUserID IS NULL AND @MemberType < 2	--Sean 2011-12-14增加,如果是未审核的
			SELECT TOP 1 @ManagerUserID = ConsultantId
			FROM cpMain WITH(NOLOCK)
			WHERE ConsultantId IS NOT NULL
			-- Sean 2013-6-19 回复按区域分配
			AND dcProvinceID IN(SELECT ID FROM dcProvince WITH(NOLOCK) WHERE SouthNorth = @SouthNorth)
			-- Richard  按组分配修改为按省分配 2012-04-23修改
			--AND dcProvinceID = @dcProvinceID
			AND Name = @CompanyName
			AND ID <> @cpMainID
			AND MemberType > 1  --已经审核过的
			AND consultantId NOT IN(select id FROM manageruser where deptid=15)--harry 2018-5-23
			ORDER BY ConsultantDate desc
	/*
		 同一省组（山东、南方、北方）内，是否存在公司名称完全相同，有招聘顾问，
		 而且分配时间比A账户的分配时间还早的账户(B)？
	*/
	END


	IF @ManagerUserID > 0		----存在重名的企业，招聘顾问不重新分配
	BEGIN
		GOTO ASSIGN
	END
	ELSE IF @AddMan2 > 0
	BEGIN
		--企业是冷客户 
		SET @ManagerUserID = @AddMan2
		GOTO ASSIGN
	END	
	ELSE IF @ThisManagerUserID IS NULL		--当前帐户无顾问
	BEGIN
		DECLARE @T AS TABLE(
			ID INT,
			ManagerUserID SMALLINT,
			Power TINYINT,
			Current_Power TINYINT
			)
		
		INSERT INTO @T
		SELECT a.ID, a.ManageruserID, a.Power, a.Current_Power
		FROM Consultant_Assign a WITH(NOLOCK), Manageruser b WITH(NOLOCK)
		WHERE a.ManageruserID = b.ID
		AND b.ConsultantNum < b.ConsultantNum_Up
		AND b.ConsultantNum_New < b.ConsultantNum_Up_New
		AND a.Province_ID = @dcProvinceID
		AND a.Status = 1
		ORDER BY a.ManageruserID

		IF EXISTS(SELECT 'x' FROM @T)
		BEGIN
			DECLARE @ID AS INT
			--如果全部Current_Power = Power，则清零
			IF NOT EXISTS(SELECT 'x' FROM @T WHERE Current_Power < Power)
			BEGIN
				UPDATE @T SET Current_Power = 0
				UPDATE Consultant_Assign SET Current_Power = 0 WHERE ID IN(SELECT ID FROM @T)	
			END
			--提取第一个顾问
			SELECT TOP 1 @ID = ID, @ManagerUserID = ManagerUserID FROM @T WHERE Current_Power < Power
			IF @ManagerUserID IS NULL
				GOTO Err1

			--修改顾问分配表
			UPDATE Consultant_Assign SET Current_Power = Current_Power + 1 WHERE ID = @ID
		END
	END
	--分配顾问
ASSIGN:
	IF (@ManagerUserID > 0) AND (ISNULL(@ThisManagerUserID, 0) <> @ManagerUserID) --Richard 2011年12月11日修改
	BEGIN
		UPDATE cpMain SET ConsultantId = @ManagerUserID, ConsultantDate = GETDATE() WHERE ID = @cpMainID
		----Sean 2012-2-16增加，记录每次修改情况  中间停止了 2013-6-19继续启用
		DECLARE @Sql AS VARCHAR(200)
		SET @Sql = '系统自动分配招聘顾问:从' + LTRIM(STR(ISNULL(@ThisManagerUserID, 0))) + '给'
		SET @Sql =@Sql + LTRIM(STR(@ManagerUserID))
		INSERT INTO bsManagerUserAction VALUES(@cpMainId, @Sql, '', 112, GETDATE())

		--Sean 2013-7-1
		DECLARE @AddMan INT
		SELECT @AddMan = AddMan FROM ColdCustomer WITH(NOLOCK) WHERE cpMainId = @cpMainId
		IF @AddMan > 0
		BEGIN
			IF EXISTS(SELECT 'x' FROM CaOrder WITH(NOLOCK) WHERE cpMainId = @cpMainId AND OpenDate > DATEADD(DAY, -28, GETDATE()) AND ManagerUSerID <> @ManagerUserID)
			BEGIN
				INSERT INTO bsManagerUserAction 
				SELECT @cpMainId, '冷客户订单28天内转移从' + LTRIM(STR(ISNULL(ManagerUserId, 0))) + '至空', '', 112, GETDATE()
				FROM CaOrder WITH(NOLOCK) WHERE cpMainId = @cpMainId AND OpenDate > DATEADD(MONTH, -1, GETDATE()) AND ManagerUSerID <> @ManagerUserID	
				IF EXISTS(SELECT 'x' FROM CaOrder WHERE cpMainId = @cpMainId AND OpenDate > DATEADD(DAY, -28, GETDATE()) AND ManagerUSerID <> @ManagerUserID)
					UPDATE CaOrder SET ManagerUserId = NULL
					WHERE cpMainId = @cpMainId AND OpenDate > DATEADD(DAY, -28, GETDATE()) AND ManagerUSerID <> @ManagerUserID	
			END
		END
	END
COMMIT
RETURN 1
Err:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END
Err1:
BEGIN
	ROLLBACK TRAN
	RETURN -1
END

GO
/****** Object:  StoredProcedure [dbo].[ccCpMainByEncryptViewSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--根据加密ID查找职位 Lucifer 20131206
--修改harry 2017-4-11 强制实名认证的,限制的不显示
--lucofer 2018-3-2
CREATE PROCEDURE [dbo].[ccCpMainByEncryptViewSelect]
(
    @ID VARCHAR(12)
)
AS 
BEGIN 
    SELECT a.ID, a.dcProvinceID, a.RegDate, a.RegisterIP, a.RegisterMode, a.AddMan, a.IsDefaultPassword,
        a.Name, a.ShortName, a.dcCompanyKindID, a.dcCompanySizeID, a.dcRegionID,
        dbo.CleanAddress(a.Address, a.dcRegionId) Address, 
        --a.Address,
        a.Zip, a.MapBarID, a.HomePage,a.RealName,
        a.Brief, a.HasLicence, a.HasLogo, a.HasVisual, a.ConsultantID, a.ConsultantDate,
        a.DailyGiftQuota, a.UnlimitedDate, a.BalanceDate, a.Balance, a.ResumeQuota, a.MaxUserNumber,
        a.MaxJobNumber, a.Quality, a.SendFeeCount, a.IsAgent, a.IsLimitLogin, a.Islock, a.IsDelete,
        a.MemberType, a.Description, a.VerifyResult, a.BlockCount, a.VerifyCount, a.LoginCount,
        a.JobNumber, a.ViewNumber, a.RefreshDate, a.LastModifyDate, a.RegCapital, a.dcSubSiteID,
        a.LastLoginDate, a.LastLoginIP, a.Valid, a.PerfectDate, a.Lng, a.Lat, a.SecondId,
        dbo.GetCpIndustry(a.ID) Industry,
        b.FullName Region,a.ReplyRate,
        (SELECT COUNT(1) FROM caOnline c WITH(NOLOCK), caMain d WITH(NOLOCK) WHERE c.caMainID = d.ID AND d.cpMainID = a.ID AND IsOnline = 1) OnlineStatus
    FROM cpMain a WITH(NOLOCK INDEX(IX_cpMain_SecondId))
    LEFT JOIN dcRegion b WITH(NOLOCK) ON a.dcRegionId = b.Id
    WHERE a.SecondID = @ID
    AND ISNULL(a.RealName, 0) < 2
   AND a.IsLimitLogin < 9
END
GO
/****** Object:  StoredProcedure [dbo].[cccpMainByLimitedReasonBycaMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Lucifer 根据caMainID获取限制登陆原因
-- =============================================
CREATE PROCEDURE [dbo].[cccpMainByLimitedReasonBycaMainIDSelect]
(
	@caMainID INT,
	@LimiteReason NVARCHAR(200) OUTPUT
)
AS
SET NOCOUNT ON
BEGIN
	DECLARE @ConsultantID AS VARCHAR(20)
	DECLARE @ConsultantPhone AS VARCHAR(20)
	DECLARE @cpMainID AS VARCHAR(20)
	SELECT TOP 1 @LimiteReason = VerifyInfo,@ConsultantID = b.ConsultantID,@cpMainID = b.ID FROM bscpStatus a,cpMain b  
		WHERE a.cpMainID = b.ID AND a.cpMainID = 
			(
				SELECT a.cpMainID
				FROM caMain a WITH(NOLOCK), cpMain b WITH(NOLOCK)
				WHERE a.ID = @caMainID
				AND a.cpMainID = b.ID
				AND a.IsDelete = 0
				AND b.IsDelete = 0
			)
		AND StatusID = 9 
		ORDER BY AddDate DESC
	IF @ConsultantID IS NULL
		SET @LimiteReason = @LimiteReason + '&lt;br /&gt;如有疑问可在工作时间[周一至周五8：30至17：30]拨打400-626-5151与客服人员取得联系，谢谢合作！ 您的会员编号是：' + @cpMainID
	ELSE
	BEGIN
		IF LEFT(@ConsultantID , 1) = '6'
		BEGIN
			SET @ConsultantPhone = '5' + @ConsultantID
		END
		ELSE
		BEGIN
			SET @ConsultantPhone = '6' + @ConsultantID
		END
		SET @LimiteReason = @LimiteReason + '&lt;br /&gt;如有疑问可在工作时间[周一至周五8：30至17：30]拨打400-626-5151转' + @ConsultantPhone +'分机与您的' + @ConsultantID + '号招聘顾问取得联系，谢谢合作！ 您的会员编号是：' + @cpMainID
	END
END
GO
/****** Object:  StoredProcedure [dbo].[cccpMainByLimitedReasonSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- 修改： mice 2015-3-23 修改顾问的的分机号
-- 修改：Harry2017-4-21 修改rean长度为400
-- =============================================
CREATE PROCEDURE [dbo].[cccpMainByLimitedReasonSelect]
(
	@UserName VARCHAR(50),
	@Password VARCHAR(50),
	@LimiteReason NVARCHAR(400) OUTPUT
)
AS
SET NOCOUNT ON
BEGIN
	DECLARE @ConsultantID AS VARCHAR(20)
	DECLARE @ConsultantPhone AS VARCHAR(20)
	DECLARE @cpMainID AS VARCHAR(20)
	SELECT TOP 1 @LimiteReason = VerifyInfo,@ConsultantID = b.ConsultantID,@cpMainID = b.ID FROM bscpStatus a,cpMain b  
		WHERE a.cpMainID = b.ID AND a.cpMainID = 
			(
				SELECT a.cpMainID
				FROM caMain a WITH(NOLOCK), cpMain b WITH(NOLOCK)
				WHERE a.UserName = @UserName
				AND a.cpMainID = b.ID
				AND a.IsDelete = 0
				AND b.IsDelete = 0
			)
		AND StatusID = 9 
		ORDER BY AddDate DESC
	IF @ConsultantID IS NULL
		SET @LimiteReason = @LimiteReason + '<br />如有疑问可在工作时间[周一至周五8：30至17：30]拨打400-626-5151与客服人员取得联系，谢谢合作！ 您的会员编号是：' + @cpMainID
	ELSE
	BEGIN
		DECLARE @officeID AS TINYINT
		SELECT @officeID = office FROM ManagerUser WITH(NOLOCK) WHERE ID = @ConsultantID
		IF @officeID = 1
		BEGIN
			SET @ConsultantPhone = '5' + @ConsultantID
		END
                IF @officeID = 2
		BEGIN
			SET @ConsultantPhone = '6' + @ConsultantID
		END
                IF @officeID = 3
		BEGIN
			SET @ConsultantPhone = '7' + @ConsultantID
		END
                IF @officeID = 4
		BEGIN
			SET @ConsultantPhone = '8' + @ConsultantID
		END
		
		SET @LimiteReason = @LimiteReason + '<br />如有疑问可在工作时间[周一至周五8：30至17：30]拨打400-626-5151转' + @ConsultantPhone +'分机与您的' + @ConsultantID + '号招聘顾问取得联系，谢谢合作！ 您的会员编号是：' + @cpMainID
	END
END


GO
/****** Object:  StoredProcedure [dbo].[ccCpMainByMapBarIDUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Sean
-- Create date: 2010-10-28
-- Description:	修改mapBarID
-- =============================================
CREATE PROCEDURE [dbo].[ccCpMainByMapBarIDUpdate]
	@ID INT,
	@MapBarID VARCHAR(50)
AS
BEGIN
	UPDATE cpMain SET MapBarID=@MapBarID WHERE ID=@ID
END














GO
/****** Object:  StoredProcedure [dbo].[cccpMainByMapBarUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[cccpMainByMapBarUpdate]
	@Lng VARCHAR(20),
	@Lat VARCHAR(20),
	@cpMainID INT
AS
BEGIN
	UPDATE cpMain SET Lng=@Lng,Lat=@Lat WHERE ID=@cpMainID
END














GO
/****** Object:  StoredProcedure [dbo].[ccCpMainByNameExist]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--==================================
--企业名称是否重复
--检查：	sean	2010-10-22
--0 无企业,>0企业id
--sean 2011-1-30 一省之内 不能和营业执照审核通过的重名
--==================================
CREATE PROCEDURE [dbo].[ccCpMainByNameExist]
(
	@Name VARCHAR(100),
	@dcProvinceID TINYINT
)
AS
BEGIN TRY
	SET @Name=LTRIM(RTRIM(@Name))

	IF EXISTS(SELECT 'X' FROM Company_Black WITH(NOLOCK) WHERE CHARINDEX(LTRIM(RTRIM(CompanyName)),@Name)>0)
	BEGIN
		UPDATE Company_Black SET RefuseCount = RefuseCount + 1
		WHERE CHARINDEX(LTRIM(RTRIM(CompanyName)),@Name)>0
		RETURN -1		--企业名称在黑名单
	END

/*	DECLARE @cpMainID AS INT
	SELECT @cpMainID = ID FROM cpMain WITH(NOLOCK)
	WHERE Name=@Name
	AND dcProvinceID=@dcProvinceID
	AND IsDelete=0
	AND HasLicence = 1

	IF @cpMainID > 0
		RETURN @cpMainID
*/
	RETURN 0
END TRY
BEGIN CATCH
	RETURN 0
END CATCH














GO
/****** Object:  StoredProcedure [dbo].[ccCpMainByNameUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Sean
-- Create date: 2010-10-28
-- Description:	修改企业名称
-- =============================================
CREATE PROCEDURE [dbo].[ccCpMainByNameUpdate]
(
	@caMainID INT,
	@cpMainID INT,
	@Name VARCHAR(100)
)
AS
IF EXISTS(SELECT 'x' FROM cpMain WITH(NOLOCK) WHERE Id = @cpMainId AND MemberType > 1)
	RETURN -1

BEGIN TRAN
	BEGIN TRY
		--验证是否是该企业的用户
		IF NOT EXISTS(SELECT 'x' FROM caMain WITH(NOLOCK) WHERE ID = @caMainID AND cpMainID = @cpMainID AND ISDelete = 0 AND AccountType =1)
			GOTO Err1
		--检查新企业名称是否和旧企业名称一致，一致则退出
		DECLARE @NameOld AS VARCHAR(100), @Desc AS NVARCHAR(200)
		SELECT @NameOld = Name FROM cpMain WITH(NOLOCK) WHERE ID=@cpMainID
		IF LTRIM(RTRIM(@Name)) = '' OR LTRIM(RTRIM(@NameOld)) = LTRIM(RTRIM(@Name))
			GOTO ERR2

		IF EXISTS(SELECT 'X' FROM Company_Black WITH(NOLOCK) WHERE CHARINDEX(LTRIM(RTRIM(CompanyName)),@Name)>0)
		BEGIN
			UPDATE Company_Black SET RefuseCount = RefuseCount + 1
			WHERE CHARINDEX(LTRIM(RTRIM(CompanyName)),@Name)>0
			GOTO Err3		--企业名称在黑名单
		END
		IF LTRIM(RTRIM(@NameOld)) <> LTRIM(RTRIM(@Name))
			BEGIN
				UPDATE cpMain SET Name = @Name,LastModifyDate =GETDATE() WHERE ID=@cpMainID
				DELETE FROM bsCpModify WHERE cpMainID=@cpMainID AND Location='a1'
				INSERT INTO bsCpModify (cpMainID,caMainID,Location,ColValue) VALUES(@cpMainID, @caMainID, 'a1',@Name)

				SET @Desc = '修改企业名称：原名称：' + @NameOld + '；新名称：' + @Name
				EXEC ccCaOperationLogInsert @caMainID, 11, @Desc
			END
	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH
COMMIT TRAN
RETURN 1
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END
ERR1:
BEGIN
	ROLLBACK TRAN
	RETURN -1
END
ERR2:
BEGIN
	ROLLBACK TRAN
	RETURN -2
END
ERR3:
BEGIN
	ROLLBACK TRAN
	RETURN -3
END














GO
/****** Object:  StoredProcedure [dbo].[ccCpMainByRefreshDateUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ccCpMainByRefreshDateUpdate]
(
	@cpMainId INT
)
AS
BEGIN
	IF EXISTS(SELECT 'x' FROM cpMain WITH(NOLOCK) WHERE ID = @cpMainId AND RefreshDate < DATEADD(MiNUTE, -60, GETDATE()))
	BEGIN
		UPDATE cpMain SET RefreshDate = GETDATE() WHERE ID = @cpMainId
		UPDATE SearchDb..cpMainHomepageSnapshot SET RefreshDate = GETDATE() WHERE RealCpMainId= @cpMainId
	END
	IF EXISTS(SELECT 'x' FROM Job WITH(NOLOCK) WHERE cpMainID = @cpMainId AND Valid = 1 AND RefreshDate < DATEADD(MiNUTE, -60, GETDATE()))
		UPDATE Job SET RefreshDate = GETDATE() WHERE cpMainID = @cpMainId AND Valid = 1
END







GO
/****** Object:  StoredProcedure [dbo].[ccCpMainByViewSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ccCpMainByViewSelect]
(
	@ID INT
)
AS
BEGIN   
	SELECT a.ID, a.dcProvinceID, a.RegDate, a.RegisterIP, a.RegisterMode, a.AddMan, a.IsDefaultPassword,
		a.Name, a.ShortName, a.dcCompanyKindID, a.dcCompanySizeID, a.dcRegionID,
		dbo.CleanAddress(a.Address, a.dcRegionId) Address, 
		a.Zip, a.MapBarID, a.HomePage, a.RealName,
		a.Brief, a.HasLicence, a.HasLogo, a.HasVisual, a.ConsultantID, a.ConsultantDate,
		a.DailyGiftQuota, a.UnlimitedDate, a.BalanceDate, a.Balance, a.ResumeQuota, a.MaxUserNumber,
		a.MaxJobNumber, a.Quality, a.SendFeeCount, a.IsAgent, a.IsLimitLogin, a.Islock, a.IsDelete,
		a.MemberType, a.Description, a.VerifyResult, a.BlockCount, a.VerifyCount, a.LoginCount,
		a.JobNumber, a.ViewNumber, a.RefreshDate, a.LastModifyDate, a.RegCapital, a.dcSubSiteID,
		a.LastLoginDate, a.LastLoginIP, a.Valid, a.PerfectDate, a.Lng, a.Lat, a.SecondId,
		dbo.GetCpIndustry(a.ID) Industry, b.FullName Region, a.ReplyRate, a.InterViewNumber, a.CommentNumber 
	FROM cpMain a WITH(NOLOCK INDEX(pk_cpMain))
	LEFT JOIN dcRegion b WITH(NOLOCK) ON a.dcRegionId = b.Id
	WHERE a.ID = @ID 
	--AND ID NOT IN(SELECT cpMainID FROM bsJobProblem)  
END 

GO
/****** Object:  StoredProcedure [dbo].[ccCpMainColdInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =  = 
--创建：	sean
--检查：	2010-10-21
--注册企业用户
--1、检查黑名单 企业名
--2、记录黑名单  返回
--3、检查黑名单 邮箱名
--4、记录黑名单  返回
--5、检查企业名重复
--6、检查email重复, RegisterMode<>!
--7、注册
--8、连接地址的来源注册的注册单位
--9、日报
--10、Company_Xinxi处理
--11、分配招聘顾问
--12、生成session	asp处理
--13、发邮件		asp处理
--2011-2-10 取消企业名称重复检查，由审核时手工确认
--密码加密后注册  lambo 
--2015-8-7 harry 增加冷客户id,根据冷客户id,查询到冷客户相关信息后更新到cpmain中
--2015-8-10 harry 将冷客户的来源地址加到cpmain的备注中
--2016-03-10 Peter 取消资料转移
-- = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =  = 
CREATE PROCEDURE  [dbo].[ccCpMainColdInsert]
(
	@Name VARCHAR(100), 
	@Email VARCHAR(50), 
	@Username VARCHAR(20), 
	@Password VARCHAR(60),	--加密后的密码
	@PlainPassword VARCHAR(20),	--加密前的明文
	@dcSubSiteID SMALLINT, 
	@RegisterIP VARCHAR(31), 
	@Url_ID INT, 
	@SessionID INT, 
	@Cookies VARCHAR(20), 
	@cpMainID INT OUTPUT, 
	@caMainID INT OUTPUT,
	@Telephone VARCHAR(100),
	@Mobile VARCHAR(20),
	@QQ VARCHAR(13),
	@ID INT
)
AS
SET NOCOUNT ON
BEGIN
	SET @cpMainID = 0
	SET @caMainID = 0
	SET @Name = LTRIM(RTRIM(@Name))
	DECLARE @dcProvinceID AS TINYINT
	SET @dcProvinceID = LEFT(@dcSubSiteID, 2)

	IF EXISTS(SELECT 'X' FROM Company_Black WITH(NOLOCK) WHERE CHARINDEX(LTRIM(RTRIM(CompanyName)), @Name)>0)
	BEGIN
		UPDATE Company_Black SET RefuseCount = RefuseCount + 1
		WHERE CHARINDEX(LTRIM(RTRIM(CompanyName)), @Name)>0
		GOTO Err1		--企业名称在黑名单
	END

	IF EXISTS(SELECT 'X' FROM Company_Black WITH(NOLOCK) WHERE Email = @Email)
	BEGIN
		UPDATE Company_Black SET RefuseCount = RefuseCount + 1
		WHERE Email = @Email
		GOTO Err2		--邮件在黑名单
	END

	IF dbo.IsEmail(@Email) =0
	GOTO Err2

	IF EXISTS(SELECT 'X' FROM caMain WITH(NOLOCK) WHERE UserNameLower = @UserName)
		GOTO Err3		--用户名重复

	IF EXISTS(SELECT 'X' FROM Company_Xinxi WITH(NOLOCK) WHERE UserNameLower = @UserName)
		GOTO Err3		--用户名重复

	--如果是非工作时间，则检查是否有重复注册
	IF(DATEPART(HOUR, GETDATE()) > 17 OR DATEPART(HOUR, GETDATE()) < 8)
	BEGIN
		IF EXISTS(SELECT 'x' FROM cpMain WITH(NOLOCK) WHERE RegDate > GETDATE()-0.0005 AND Name LIKE '%' + @Name + '%')
			GOTO Err3		--非工作时间，1小时内企业名称重复，认为是恶意注册
		IF EXISTS(SELECT 'x' FROM cpMain WITH(NOLOCK) WHERE RegDate > GETDATE()-0.000005 AND LastLoginIp = @RegisterIP)
			GOTO Err3		--非工作时间，1小时内注册Ip重复，认为是恶意注册
		IF EXISTS(SELECT 'x' FROM caLoginLog WITH(NOLOCK) WHERE LoginCookies = @Cookies AND cpMainName LIKE '%' + @Name + '%' AND AddDate > GETDATE() - 0.0005)
			GOTO Err3		--非工作时间，1小时内注册Cookies重复，认为是恶意注册
	END

	IF EXISTS(SELECT 'x' FROM caMain a WITH(NOLOCK), cpMain b WITH(NOLOCK)
			WHERE (b.RegisterMode = 0 Or b.RegisterMode = 11)
			AND a.cpMainID = b.ID AND a.Email = @Email 
			AND b.Isdelete = 0 AND a.IsDelete = 0 AND a.AccountType = 1)
		GOTO Err5		--Email重复，不是信息员推广的，或者已经审核的
	--###############################3
	--是否应该删除 DELETE cpMain FROM caMain WHERE caMain.cpMainID = cpMain.ID AND RegisterMode = 1 AND caMain.Email = @Email
	--###############################3

	----检查通过，增加到企业表
	--Harry Begin
	--从冷客户表中获取填写的企业信息
	DECLARE @dcCompanyKindID AS INT,
		@dcCompanySizeID INT,
		@dcIndustryID VARCHAR(50),
		@dcRegionID VARCHAR(6),
		@Address VARCHAR(120),
		@SourceLink VARCHAR(1000),
		@Brief VARCHAR(6000),
		@Phone VARCHAR(50),
		@AddDate DATETIME

	SELECT @dcCompanyKindID = CASE dcCompanyKindID WHEN 0 THEN NULL ELSE dcCompanyKindID END, 
		@dcCompanySizeID = dcCompanySizeID, @dcIndustryID = cpIndustry, @dcRegionID = dcRegionID, 
		@Address = [Address], @Brief = Brief, @SourceLink = SourceLink, @Phone = Phone, @AddDate = AddDate
	FROM ColdCustomer 
	WHERE ID = @ID

	IF ISNULL(@Mobile, '') = '' AND ISNULL(@Telephone, '') = '' AND @Phone > ''
	BEGIN
		IF @Phone LIKE '%/%'
		BEGIN
			SELECT @Telephone = LEFT(@Phone, CHARINDEX('/', @Phone) - 1),
				@Mobile = RIGHT(@Phone, LEN(@Phone) - CHARINDEX('/', @Phone))
		END
		ELSE IF	 @Phone LIKE '1%'	
			SET @Mobile = @Phone
		ELSE IF	 @Phone LIKE '0%'	
			SET @Telephone = @Phone
	END

   	SELECT @dcRegionID=ISNULL(@dcRegionID,@dcSubSiteID)
	--Harry END
	DECLARE @CountDate AS INT,
		@IsHistory AS BIT
	SET @CountDate = YEAR(GETDATE())*10000 + MONTH(GETDATE())*100 + DAY(GETDATE())
	SET @Username = LTRIM(RTRIM(@Username))
	BEGIN TRAN
		----企业表
		INSERT INTO cpMain(dcProvinceID,dcSubSiteID, RegisterIP, Name, RegDate, RegisterMode, RefreshDate, LoginCount, LastLoginDate, LastLoginIP,dcRegionID)
		VALUES(@dcProvinceID, @dcSubSiteID, @RegisterIP, @Name, GETDATE(), 0 , GETDATE(), 1, GETDATE(), @RegisterIP, @dcRegionID)
		SELECT @cpMainID = @@IDENTITY
		--保存所属行业
		DELETE FROM cpIndustry WHERE cpMainID = @cpMainID
		INSERT INTO cpIndustry
		SELECT @cpMainID, a FROM dbo.fnSplit(@dcIndustryID, ' ')
		
		----Company_Xinxi处理, 160天内计算工作量，超过160天不计算工作量
		DECLARE @Company_XinxiID AS INT, @AddMan AS SMALLINT, @RegDate AS SMALLDATETIME, @Resume_Xinxi_ProvinceID AS TINYINT

		SELECT @Company_XinxiID = ID, @AddMan = AddMan, @RegDate = RegDate
		FROM Company_Xinxi WITH(NOLOCK)
		WHERE Email = @Email
		AND Province_ID = @dcProvinceID
		AND IsHistory = 0
		ORDER BY RegDate DESC

		----日报表, 信息员推广过的个人注册，Ishistory=0的作为推广ValIDCompany
		IF @AddMan > 200 AND @AddMan < 500 AND @RegDate > GETDATE() - 30
		BEGIN
			UPDATE cpMain SET AddMan = @AddMan, RegisterMode = 1 WHERE ID = @cpMainID
			----记录信息员工作量
			------判断是否有该行记录，没有则增加
			IF NOT EXISTS(SELECT 'x' FROM Info_DateReport WITH(NOLOCK) WHERE CountDate = @CountDate AND Province_ID = @dcProvinceID	AND InfoManager_ID = @AddMan)
				INSERT INTO Info_DateReport(Province_ID, InfoManager_ID, CountDate)
				VALUES(@dcProvinceID, @AddMan, @CountDate)
			------记录数据，信息员工作量 + 1
			UPDATE Info_DateReport
			SET ValIDCompany = ValIDCompany + 1  
			WHERE CountDate = @CountDate
			AND Province_ID = @dcProvinceID
			AND InfoManager_ID = @AddMan
		END

		DELETE Company_Xinxi WHERE Email = @Email
		----账号表
		INSERT INTO caMain(cpMainID, EMail, AccountType, UserName, Password, Telephone, Mobile, QQ)
		VALUES(@cpMainID, @EMail, 1, @UserName, @Password, @Telephone, @Mobile, @QQ)
		SELECT TOP 1 @caMainID = ID FROM caMain WITH(NOLOCK) WHERE cpMainID = @cpMainID
		INSERT INTO caPlainPassword(caMainId, PlainPassWord) SELECT @caMainID, @PlainPassword

		--企业注册数量+1
		UPDATE DateReport 
		SET CompanyRegNum = CompanyRegNum + 1
		WHERE CountDate = @CountDate
		AND Province_ID = @dcSubSiteID
		--INSERT INTO pamainDatereport SELECT @cpMainID, 1, GETDATE() -- SEAN 20130911

		----后台审核
		INSERT INTO bsCpModify (cpMainID, caMainID, Location, ColValue) VALUES(@cpMainID, @caMainID, 'a1', @Name)
		----顾问分配
		EXEC ccCpMainByConsultantAssignUpdate @cpMainID, @dcProvinceID
		----单点登录用
		DELETE FROM cpSession WHERE caMainID = @caMainID
		INSERT INTO cpSession(SessionID, caMainID, IP, Cookies) VALUES(@SessionID, @caMainID, @RegisterIP, @Cookies)

		----注册算一次登录
		INSERT INTO caLoginLog(caMainID, cpMainName, caMainName, LoginIP, LoginCookies, Browser)
		VALUES(@caMainID, @Name, LEFT(@Username, 20), @RegisterIP, '注册登录', '3:')
	COMMIT TRAN
	RETURN 1
END
ERR:				--未知错误
BEGIN
	RETURN 0
END
Err1:				--企业名称在黑名单
BEGIN
	RETURN -1
END
Err2:				--邮件在黑名单
BEGIN
	RETURN -2
END
Err3:				--用户名重复
BEGIN
	RETURN -3
END
Err4:				--企业名称重复
BEGIN
	RETURN -4
END
Err5:				--Email重复，信息员推广的，并且没有审核的
BEGIN
	RETURN -5
END
Err6:				--注册时的错误
BEGIN
	ROLLBACK TRAN
	RETURN -6
END

GO
/****** Object:  StoredProcedure [dbo].[ccCpMainColdInsert1009]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =  = 
--创建：	sean
--检查：	2010-10-21
--注册企业用户
--1、检查黑名单 企业名
--2、记录黑名单  返回
--3、检查黑名单 邮箱名
--4、记录黑名单  返回
--5、检查企业名重复
--6、检查email重复, RegisterMode<>!
--7、注册
--8、连接地址的来源注册的注册单位
--9、日报
--10、Company_Xinxi处理
--11、分配招聘顾问
--12、生成session	asp处理
--13、发邮件		asp处理
--2011-2-10 取消企业名称重复检查，由审核时手工确认
--密码加密后注册  lambo 
-- = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =  = 
CREATE PROCEDURE  [dbo].[ccCpMainColdInsert1009]
(
	@Name VARCHAR(100), 
	@Email VARCHAR(50), 
	@Username VARCHAR(20), 
	@Password VARCHAR(60),	--加密后的密码
	@PlainPassword VARCHAR(20),	--加密前的明文
	@dcSubSiteID SMALLINT, 
	@RegisterIP VARCHAR(31), 
	@Url_ID INT, 
	@SessionID INT, 
	@Cookies VARCHAR(20), 
	@cpMainID INT OUTPUT, 
	@caMainID INT OUTPUT,
	@Telephone VARCHAR(100),
	@Mobile VARCHAR(20)
)
AS
--BEGIN TRY
	SET @cpMainID = 0
	SET @caMainID = 0
	SET @Name = LTRIM(RTRIM(@Name))
	DECLARE @dcProvinceID AS TINYINT
	SET @dcProvinceID = LEFT(@dcSubSiteID, 2)

	IF EXISTS(SELECT 'X' FROM Company_Black WITH(NOLOCK) WHERE CHARINDEX(LTRIM(RTRIM(CompanyName)), @Name)>0)
	BEGIN
		UPDATE Company_Black SET RefuseCount = RefuseCount + 1
		WHERE CHARINDEX(LTRIM(RTRIM(CompanyName)), @Name)>0
		GOTO Err1		--企业名称在黑名单
	END

	IF EXISTS(SELECT 'X' FROM Company_Black WITH(NOLOCK) WHERE Email = @Email)
	BEGIN
		UPDATE Company_Black SET RefuseCount = RefuseCount + 1
		WHERE Email = @Email
		GOTO Err2		--邮件在黑名单
	END

	IF dbo.IsEmail(@Email) =0
	GOTO Err2

	IF EXISTS(SELECT 'X' FROM caMain WITH(NOLOCK) WHERE UserNameLower = @UserName)
		GOTO Err3		--用户名重复

	IF EXISTS(SELECT 'X' FROM Company_Xinxi WITH(NOLOCK) WHERE UserNameLower = @UserName)
		GOTO Err3		--用户名重复

/*	IF EXISTS(SELECT 'X' FROM cpMain WITH(NOLOCK) WHERE Name = @Name AND dcProvinceID = @dcProvinceID AND IsDelete = 0)
		GOTO Err4		--企业名称重复
	IF EXISTS(SELECT 'X' FROM cpMainLimited WITH(NOLOCK) WHERE CompanyName = @Name)
		GOTO Err3		--近期删除的企业名称重复，属于类似黑名单
	IF EXISTS(SELECT 'X' FROM cpMainLimited WITH(NOLOCK) WHERE LoginIp = @RegisterIp AND LoginCookies = @Cookies)
		GOTO Err3		--近期删除的企业名称重复，属于类似黑名单
	IF EXISTS(SELECT 'X' FROM cpMainLimited WITH(NOLOCK) WHERE (LoginIp = @RegisterIp OR LoginCookies = @Cookies) AND CHARINDEX(CompanyName, @Name) > 0)
		GOTO Err3		--近期删除的企业名称重复，属于类似黑名单
*/
	--如果是非工作时间，则检查是否有重复注册
	IF(DATEPART(HOUR, GETDATE()) > 17 OR DATEPART(HOUR, GETDATE()) < 8)
	BEGIN
		IF EXISTS(SELECT 'x' FROM cpMain WITH(NOLOCK) WHERE RegDate > GETDATE()-0.0005 AND Name LIKE '%' + @Name + '%')
			GOTO Err3		--非工作时间，1小时内企业名称重复，认为是恶意注册
		IF EXISTS(SELECT 'x' FROM cpMain WITH(NOLOCK) WHERE RegDate > GETDATE()-0.000005 AND LastLoginIp = @RegisterIP)
			GOTO Err3		--非工作时间，1小时内注册Ip重复，认为是恶意注册
		IF EXISTS(SELECT 'x' FROM caLoginLog WITH(NOLOCK) WHERE LoginCookies = @Cookies AND cpMainName LIKE '%' + @Name + '%' AND AddDate > GETDATE() - 0.0005)
			GOTO Err3		--非工作时间，1小时内注册Cookies重复，认为是恶意注册
	END

	IF EXISTS(SELECT 'x' FROM caMain a WITH(NOLOCK), cpMain b WITH(NOLOCK)
			WHERE (b.RegisterMode = 0 Or b.RegisterMode = 11)
			AND a.cpMainID = b.ID AND a.Email = @Email 
			AND b.Isdelete = 0 AND a.IsDelete = 0 AND a.AccountType = 1)
		GOTO Err5		--Email重复，不是信息员推广的，或者已经审核的
	--###############################3
	--是否应该删除 DELETE cpMain FROM caMain WHERE caMain.cpMainID = cpMain.ID AND RegisterMode = 1 AND caMain.Email = @Email
	--###############################3

	----检查通过，增加到企业表
	DECLARE @CountDate AS INT,
		@IsHistory AS BIT
	SET @CountDate = YEAR(GETDATE())*10000 + MONTH(GETDATE())*100 + DAY(GETDATE())
	SET @Username = LTRIM(RTRIM(@Username))
	BEGIN TRAN
--		BEGIN TRY
			----企业表
			INSERT INTO cpMain(dcProvinceID, dcRegionID, dcSubSiteID, RegisterIP, Name, RegDate, RegisterMode, RefreshDate, LoginCount, LastLoginDate, LastLoginIP)
			VALUES(@dcProvinceID, @dcSubSiteID, @dcSubSiteID, @RegisterIP, @Name, GETDATE(), 0 , GETDATE(), 1, GETDATE(), @RegisterIP)
			SELECT @cpMainID = @@IDENTITY

			----Company_Xinxi处理, 160天内计算工作量，超过160天不计算工作量
			DECLARE @Company_XinxiID AS INT,
				@AddMan AS SMALLINT,
				@RegDate AS SMALLDATETIME,
				@Resume_Xinxi_ProvinceID AS TINYINT

			SELECT @Company_XinxiID = ID, @AddMan = AddMan, @RegDate = RegDate,
				@IsHistory = IsHistory
				FROM Company_Xinxi WITH(NOLOCK)
			WHERE Email = @Email
			AND Province_ID = @dcProvinceID
			ORDER BY IsHistory, RegDate DESC

			----账号表
			INSERT INTO caMain(cpMainID, EMail, AccountType, UserName, Password,Telephone,Mobile)
			VALUES(@cpMainID, @EMail, 1, @UserName, @Password,@Telephone,@Mobile)
			SELECT TOP 1 @caMainID = ID FROM caMain WITH(NOLOCK) WHERE cpMainID = @cpMainID
			INSERT INTO caPlainPassword(caMainId, PlainPassWord) SELECT @caMainID, @PlainPassword

			----日报表, 信息员推广过的个人注册，Ishistory=0的作为推广ValIDCompany
			IF @Company_XinxiID IS NOT NULL AND @AddMan > 1 AND @Ishistory = 0
			BEGIN
				UPDATE cpMain SET AddMan = @AddMan, RegisterMode = 1 WHERE ID = @cpMainID
				----记录信息员工作量
				------判断是否有该行记录，没有则增加
				IF NOT EXISTS(SELECT 'x' FROM Info_DateReport WITH(NOLOCK) WHERE CountDate = @CountDate AND Province_ID = @dcProvinceID	AND InfoManager_ID = @AddMan)
					INSERT INTO Info_DateReport(Province_ID, InfoManager_ID, CountDate)
					VALUES(@dcProvinceID, @AddMan, @CountDate)
				------记录数据，信息员工作量 + 1
				UPDATE Info_DateReport
				SET ValIDCompany = ValIDCompany + 1  
				WHERE CountDate = @CountDate
				AND Province_ID = @dcProvinceID
				AND InfoManager_ID = @AddMan
				-----推广的企业数量+1
				UPDATE DateReport 
				SET ValidCompany = ValidCompany + 1
				WHERE CountDate = @CountDate
				AND Province_ID = @dcSubSiteID
				--INSERT INTO pamainDatereport SELECT @cpMainID, 8, GETDATE() -- SEAN 20130911
			END
			ELSE
			BEGIN
				--企业注册数量+1
				UPDATE DateReport 
				SET CompanyRegNum = CompanyRegNum + 1
				WHERE CountDate = @CountDate
				AND Province_ID = @dcSubSiteID
				--INSERT INTO pamainDatereport SELECT @cpMainID, 1, GETDATE() -- SEAN 20130911
			END
			----连接地址的来源注册的注册单位
			IF @Url_ID > 0
				UPDATE Url
				SET AllCompany = AllCompany + 1, TodayCompany = TodayCompany + 1 
				WHERE ID = @Url_ID

			----后台审核
			INSERT INTO bsCpModify (cpMainID, caMainID, Location, ColValue) VALUES(@cpMainID, @caMainID, 'a1', @Name)
			----顾问分配
			EXEC ccCpMainByConsultantAssignUpdate @cpMainID, @dcProvinceID
			----单点登录用
			DELETE FROM cpSession WHERE caMainID = @caMainID
			INSERT INTO cpSession(SessionID, caMainID, IP, Cookies) VALUES(@SessionID, @caMainID, @RegisterIP, @Cookies)

			----注册算一次登录
			INSERT INTO caLoginLog(caMainID, cpMainName, caMainName, LoginIP, LoginCookies, Browser)
			VALUES(@caMainID, @Name, LEFT(@Username, 20), @RegisterIP, '注册登录', '3:')
--		END TRY
--		BEGIN CATCH
--			GOTO Err6
--		END CATCH
	COMMIT TRAN
	RETURN 1
--END TRY
--BEGIN CATCH
--	GOTO ERR
--END CATCH
ERR:				--未知错误
BEGIN
	RETURN 0
END
Err1:				--企业名称在黑名单
BEGIN
	RETURN -1
END
Err2:				--邮件在黑名单
BEGIN
	RETURN -2
END
Err3:				--用户名重复
BEGIN
	RETURN -3
END
Err4:				--企业名称重复
BEGIN
	RETURN -4
END
Err5:				--Email重复，信息员推广的，并且没有审核的
BEGIN
	RETURN -5
END
Err6:				--注册时的错误
BEGIN
	ROLLBACK TRAN
	RETURN -6
END









GO
/****** Object:  StoredProcedure [dbo].[ccCpMainInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =  = 
--创建：	Lucifer
--检查：	2013-10-9
--注册企业用户
--1、检查黑名单 企业名
--2、记录黑名单  返回
--3、检查黑名单 邮箱名
--4、记录黑名单  返回
--5、检查企业名重复
--6、检查email重复, RegisterMode<>!
--7、注册
--8、连接地址的来源注册的注册单位
--9、日报
--10、Company_Xinxi处理
--11、分配招聘顾问
--12、生成session	asp处理
--13、发邮件		asp处理
-- = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =  = 
CREATE PROCEDURE  [dbo].[ccCpMainInsert]
(
	@Name VARCHAR(100), 
	@Email VARCHAR(50), 
	@Username VARCHAR(20), 
	@Password VARCHAR(60),		--加密后的密码
	@PlainPassword VARCHAR(20),	--加密前的明文
	@CaName NVARCHAR(6),
	@Mobile VARCHAR(11),
	@Telephone VARCHAR(25),
	@dcSubSiteID SMALLINT, 
	@RegisterIP VARCHAR(31), 
	@Url_ID INT, 
	@SessionID INT, 
	@Cookies VARCHAR(20), 
	@cpMainID INT OUTPUT, 
	@caMainID INT OUTPUT
)
AS
SET NOCOUNT ON
--IF CHARINDEX(',', @RegisterIP) > 0
	--SET @RegisterIP = RIGHT(@RegisterIP, LEN(@RegisterIP)- CHARINDEX(',', @RegisterIP))
IF EXISTS(SELECT 'x' FROM Ip_Black WITH(NOLOCK) WHERE Ip = @RegisterIP)
	RETURN 0
IF CHARINDEX(',113.248.157.168', @RegisterIP) > 0
	RETURN 0
BEGIN
	SET @cpMainID = 0
	SET @caMainID = 0
	DECLARE @dcProvinceID AS TINYINT
	SET @dcProvinceID = LEFT(@dcSubSiteID, 2)
	--IF @dcProvinceId = 42
	--	SET @Name = REPLACE(REPLACE(@Name, ' ', ''), '', '')
	--IF @dcProvinceId = 41 AND @CaName = '王林'
	--	GOTO Err3

	SET @Name = LTRIM(RTRIM(@Name))
	
	--IF @dcProvinceID = 42 AND CHARINDEX('公司', @Name) = 0 AND LEN(@Name) > 4
	--	GOTO Err3
	--IF EXISTS(SELECT 'X' FROM Company_Black WITH(NOLOCK) WHERE CHARINDEX(LTRIM(RTRIM(CompanyName)), @Name)>0)
	IF EXISTS(SELECT 'X' FROM Company_Black WITH(NOLOCK) WHERE CompanyName > ' ' AND CHARINDEX(LTRIM(RTRIM(CompanyName)), @Name)>0)
	BEGIN
		UPDATE Company_Black SET RefuseCount = RefuseCount + 1
		WHERE CHARINDEX(LTRIM(RTRIM(CompanyName)), @Name)>0
		GOTO Err1		--企业名称在黑名单
	END

	IF EXISTS(SELECT 'X' FROM Company_Black WITH(NOLOCK) WHERE Email = @Email)
	BEGIN
		UPDATE Company_Black SET RefuseCount = RefuseCount + 1
		WHERE Email = @Email
		GOTO Err2		--邮件在黑名单
	END

	IF dbo.IsEmail(@Email) =0
	GOTO Err2

	IF EXISTS(SELECT 'X' FROM caMain WITH(NOLOCK) WHERE UserNameLower = @UserName)
		GOTO Err3		--用户名重复

	IF EXISTS(SELECT 'X' FROM Company_Xinxi WITH(NOLOCK) WHERE UserNameLower = @UserName)
		GOTO Err3		--用户名重复

/*	IF EXISTS(SELECT 'X' FROM cpMain WITH(NOLOCK) WHERE Name = @Name AND dcProvinceID = @dcProvinceID AND IsDelete = 0)
		GOTO Err4		--企业名称重复
	IF EXISTS(SELECT 'X' FROM cpMainLimited WITH(NOLOCK) WHERE CompanyName = @Name)
		GOTO Err3		--近期删除的企业名称重复，属于类似黑名单
	IF EXISTS(SELECT 'X' FROM cpMainLimited WITH(NOLOCK) WHERE LoginIp = @RegisterIp AND LoginCookies = @Cookies)
		GOTO Err3		--近期删除的企业名称重复，属于类似黑名单
	IF EXISTS(SELECT 'X' FROM cpMainLimited WITH(NOLOCK) WHERE (LoginIp = @RegisterIp OR LoginCookies = @Cookies) AND CHARINDEX(CompanyName, @Name) > 0)
		GOTO Err3		--近期删除的企业名称重复，属于类似黑名单
*/
	--如果是非工作时间，则检查是否有重复注册
	IF(DATEPART(HOUR, GETDATE()) > 17 OR DATEPART(HOUR, GETDATE()) < 8)
	BEGIN
		IF EXISTS(SELECT 'x' FROM cpMain WITH(NOLOCK) WHERE RegDate > DATEADD(MINUTE, -10, GETDATE()) AND Name LIKE '%' + @Name + '%')
			GOTO Err3		--非工作时间，1小时内企业名称重复，认为是恶意注册
		IF EXISTS(SELECT 'x' FROM cpMain WITH(NOLOCK) WHERE RegDate > DATEADD(MINUTE, -3, GETDATE()) AND LastLoginIp = @RegisterIP)
			GOTO Err3		--非工作时间，1小时内注册Ip重复，认为是恶意注册
		IF EXISTS(SELECT 'x' FROM caLoginLog WITH(NOLOCK) WHERE LoginCookies = @Cookies AND cpMainName LIKE '%' + @Name + '%' AND AddDate > DATEADD(MINUTE, -20, GETDATE()))
			GOTO Err3		--非工作时间，1小时内注册Cookies重复，认为是恶意注册
	END
	IF (SELECT COUNT(*) FROM cpMain WITH(NOLOCK) WHERE RegDate > DATEADD(MINUTE, -3, GETDATE()) AND LastLoginIp = @RegisterIP) > 3
		GOTO Err3		--非工作时间，1小时内注册Ip重复，认为是恶意注册
	IF EXISTS (SELECT 'x' FROM Tmp_limitip WITH(NOLOCK) WHERE LastLoginIp = @RegisterIP)
		GOTO Err3		--非工作时间，1小时内注册Ip重复，认为是恶意注册
--	IF CHARINDEX('公司', @Name) = 0 AND @DcProvinceId = 42
--	BEGIN
--		DECLARE @NameLeft AS VARCHAR(10), @NameRight AS VARCHAR(10)
--		IF LEN(@Name) > 8
--			SELECT @NameRight = RIGHT(@Name, 4), @NameLeft = LEFT(@Name, 4)
--		ELSE
--			SELECT @NameRight = RIGHT(@Name, 3), @NameLeft = LEFT(@Name, 3)
--		IF (SELECT COUNT(*) FROM (SELECT TOP 10 Name FROM cpMain WITH(NOLOCK) WHERE dcProvinceId = @dcProvinceId ORDER BY Id DESC) a WHERE CHARINDEX(@NameRight, Name) > 0) > 1
--			GOTO Err3
--		IF (SELECT COUNT(*) FROM (SELECT TOP 10 Name FROM cpMain WITH(NOLOCK) WHERE dcProvinceId = @dcProvinceId ORDER BY Id DESC) a WHERE CHARINDEX(@NameLeft, Name) > 0) > 1
--			GOTO Err3
--	END

	IF EXISTS(SELECT 'x' FROM caMain a WITH(NOLOCK), cpMain b WITH(NOLOCK)
			WHERE (b.RegisterMode = 0 Or b.RegisterMode = 11)
			AND a.cpMainID = b.ID AND a.Email = @Email 
			AND b.Isdelete = 0 AND a.IsDelete = 0 AND a.AccountType = 1)
		GOTO Err5		--Email重复，不是信息员推广的，或者已经审核的
	--###############################3
	--是否应该删除 DELETE cpMain FROM caMain WHERE caMain.cpMainID = cpMain.ID AND RegisterMode = 1 AND caMain.Email = @Email
	--###############################3

	----检查通过，增加到企业表
	DECLARE @CountDate AS INT,
		@IsHistory AS BIT
	SET @CountDate = YEAR(GETDATE())*10000 + MONTH(GETDATE())*100 + DAY(GETDATE())
	SET @Username = LTRIM(RTRIM(@Username))
	BEGIN TRAN
--		BEGIN TRY
			----企业表
			INSERT INTO cpMain(dcProvinceID, dcRegionID, dcSubSiteID, RegisterIP, Name, RegDate, RegisterMode, RefreshDate, LoginCount, LastLoginDate, LastLoginIP)
			VALUES(@dcProvinceID, @dcSubSiteID, @dcSubSiteID, @RegisterIP, @Name, GETDATE(), 0 , GETDATE(), 1, GETDATE(), @RegisterIP)
			SELECT @cpMainID = @@IDENTITY

			----Company_Xinxi处理, 160天内计算工作量，超过160天不计算工作量
			DECLARE @Company_XinxiID AS INT,
				@AddMan AS SMALLINT,
				@RegDate AS SMALLDATETIME,
				@Resume_Xinxi_ProvinceID AS TINYINT

			SELECT @Company_XinxiID = ID, @AddMan = AddMan, @RegDate = RegDate,
				@IsHistory = IsHistory
				FROM Company_Xinxi WITH(NOLOCK)
			WHERE Email = @Email
			AND Province_ID = @dcProvinceID
			ORDER BY IsHistory, RegDate DESC

			----账号表
			INSERT INTO caMain(cpMainID, EMail, AccountType, UserName, Password, Name, Mobile, Telephone)
			VALUES(@cpMainID, @EMail, 1, @UserName, @Password, @CaName, @Mobile, @Telephone)
			SELECT TOP 1 @caMainID = ID FROM caMain WITH(NOLOCK) WHERE cpMainID = @cpMainID
			INSERT INTO caPlainPassword(caMainId, PlainPassWord) SELECT @caMainID, @PlainPassword
			IF EXISTS(SELECT TOP 1 'X' FROM caVerifyLog WHERE VerifyDate > DATEAdd(n, -1, GETDATE()) AND Mobile = @Mobile)
				UPDATE caMain SET MobileVerifyDate = GETDATE() WHERE ID = @caMainID

			----日报表, 信息员推广过的个人注册，Ishistory=0的作为推广ValIDCompany
			IF @Company_XinxiID IS NOT NULL AND @AddMan > 1 AND @Ishistory = 0
			BEGIN
				UPDATE cpMain SET AddMan = @AddMan, RegisterMode = 1 WHERE ID = @cpMainID
				----记录信息员工作量
				------判断是否有该行记录，没有则增加
				IF NOT EXISTS(SELECT 'x' FROM Info_DateReport WITH(NOLOCK) WHERE CountDate = @CountDate AND Province_ID = @dcProvinceID	AND InfoManager_ID = @AddMan)
					INSERT INTO Info_DateReport(Province_ID, InfoManager_ID, CountDate)
					VALUES(@dcProvinceID, @AddMan, @CountDate)
				------记录数据，信息员工作量 + 1
				UPDATE Info_DateReport
				SET ValIDCompany = ValIDCompany + 1  
				WHERE CountDate = @CountDate
				AND Province_ID = @dcProvinceID
				AND InfoManager_ID = @AddMan
				-----推广的企业数量+1
				UPDATE DateReport 
				SET ValidCompany = ValidCompany + 1
				WHERE CountDate = @CountDate
				AND Province_ID = @dcSubSiteID
				--INSERT INTO pamainDatereport SELECT @cpMainID, 8, GETDATE() -- SEAN 20130911
			END
			ELSE
			BEGIN
				--企业注册数量+1
				UPDATE DateReport 
				SET CompanyRegNum = CompanyRegNum + 1
				WHERE CountDate = @CountDate
				AND Province_ID = @dcSubSiteID
				--INSERT INTO pamainDatereport SELECT @cpMainID, 1, GETDATE() -- SEAN 20130911
			END
			----连接地址的来源注册的注册单位
			IF @Url_ID > 0
			BEGIN
				UPDATE Url
				SET AllCompany = AllCompany + 1, TodayCompany = TodayCompany + 1 
				WHERE ID = @Url_ID

				UPDATE cpMain SET RegisterSourceId = @Url_Id WHERE ID = @cpMainID
			END
			----后台审核
			INSERT INTO bsCpModify (cpMainID, caMainID, Location, ColValue) VALUES(@cpMainID, @caMainID, 'a1', @Name)
			----顾问分配
			EXEC ccCpMainByConsultantAssignUpdate @cpMainID, @dcProvinceID
			----单点登录用
			DELETE FROM cpSession WHERE caMainID = @caMainID
			INSERT INTO cpSession(SessionID, caMainID, IP, Cookies) VALUES(@SessionID, @caMainID, @RegisterIP, @Cookies)

			----注册算一次登录
			INSERT INTO caLoginLog(caMainID, cpMainName, caMainName, LoginIP, LoginCookies, Browser)
			VALUES(@caMainID, @Name, @CaName, @RegisterIP, '注册登录', '3:')
--		END TRY
--		BEGIN CATCH
--			GOTO Err6
--		END CATCH
	COMMIT TRAN
	RETURN 1
END
ERR:				--未知错误
BEGIN
	RETURN 0
END
Err1:				--企业名称在黑名单
BEGIN
	RETURN -1
END
Err2:				--邮件在黑名单
BEGIN
	RETURN -2
END
Err3:				--用户名重复
BEGIN
	RETURN -3
END
Err4:				--企业名称重复
BEGIN
	RETURN -4
END
Err5:				--Email重复，信息员推广的，并且没有审核的
BEGIN
	RETURN -5
END
Err6:				--注册时的错误
BEGIN
	ROLLBACK TRAN
	RETURN -6
END









GO
/****** Object:  StoredProcedure [dbo].[ccCpMainMapBarIDUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[ccCpMainMapBarIDUpdate]
	@ID INT,
	@MapBarID VARCHAR(50)
AS
BEGIN
	UPDATE cpMain SET MapBarID=@MapBarID WHERE ID=@ID
END














GO
/****** Object:  StoredProcedure [dbo].[ccCpMainPublishSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--ccCpMainPublishSelect
--创建时间：2014.10.30
--创建人：Nick
--说明：获取想同地区，同一行业的其他公司的名称
--#####################################################*/
CREATE PROCEDURE [dbo].[ccCpMainPublishSelect]
(
	@dcRegionId INT,
	@dcIndustryId INT,
	@cpMainId INT
)
AS
SET NOCOUNT ON
BEGIN
	IF @dcRegionId > 9999
		SET @dcRegionId = LEFT(@dcRegionId, 4)

	IF @dcRegionId LIKE '32%'
		SELECT SecondId AS Id, Name, LogoFile LogoUrl
		FROM SearchDb..CpMainSameIndustry32 WITH(NOLOCK)
		WHERE --dcRegionId = @dcRegionId AND
			dcIndustryId = @dcIndustryId
		--AND RealId != @cpmainId
		ORDER BY Row
	ELSE
		SELECT SecondId AS Id, Name, LogoFile LogoUrl
		FROM SearchDb..CpMainSameIndustry WITH(NOLOCK)
		WHERE dcRegionId = @dcRegionId
		AND dcIndustryId = @dcIndustryId
		--AND RealId != @cpmainId
		ORDER BY Row
END

GO
/****** Object:  StoredProcedure [dbo].[ccCpMainSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--修改harry 增加 是否为职位刷新数老用户2017-10-19
CREATE PROCEDURE [dbo].[ccCpMainSelect]
    @ID INT
AS
BEGIN
SET NOCOUNT ON 
    SELECT a.*, dbo.GetCpIndustry(a.ID) Industry, dbo.GetCpIndustryId(a.ID) dcIndustryID, b.Mobile, CASE WHEN EXISTS(SELECT 'X' FROM JobRefreshOldCompany WITH(NOLOCK) WHERE cpMainId = @ID) THEN 1 ELSE 0 END AS IsJobRefreshOldCompany,
		c.[Description] CompanyKind, d.[Description] CompanySize, e.FullName Region
    FROM cpMain a WITH(NOLOCK) 
    LEFT JOIN Manageruser b WITH(NOLOCK) ON a.ConsultantId = b.ID
    LEFT JOIN dcCompanyKind c WITH(NOLOCK) ON a.dcCompanyKindId = c.ID
    LEFT JOIN dcCompanySize d WITH(NOLOCK) ON a.dcCompanySizeId = d.ID
    LEFT JOIN dcRegion e WITH(NOLOCK) ON a.dcRegionId = e.ID
    WHERE a.ID = @ID
SET NOCOUNT OFF
END
GO
/****** Object:  StoredProcedure [dbo].[ccCpMainUnLimitedDateUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[ccCpMainUnLimitedDateUpdate]
(
	@ID INT,
	@UnLimitedDate VARCHAR(20),
	@ResumeQuota SMALLINT
)
AS
BEGIN
	UPDATE cpMain SET UnLimitedDate=@UnLimitedDate,ResumeQuota=@ResumeQuota WHERE ID = @ID
END














GO
/****** Object:  StoredProcedure [dbo].[ccCpMainUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Sean
-- Create date: 2010-10-28
-- Description:	修改企业信息
-- 因为Name shortname 不在此处修改，所以去掉相关部分
-- mice 123 2015-6-8 添加修改企业简称(shortname)的修改
-- sean  2015-11-27 remove修改企业简称(shortname)的修改
-- =============================================
CREATE PROCEDURE [dbo].[ccCpMainUpdate]
(
	@caMainID INT,
	@cpMainID INT,
	@Name VARCHAR(100),
	@ShortName VARCHAR(40),
	@dcCompanyKindID INT,
	@dcCompanySizeID INT,
	@dcIndustryID VARCHAR(50),
	@dcRegionID VARCHAR(6),
	@Address VARCHAR(120),
	@Zip VARCHAR(6),
	@MapBarID VARCHAR(50),
	@HomePage VARCHAR(50),
	@Brief VARCHAR(6000)
)
AS
SET NOCOUNT ON
SELECT @dcIndustryID = dbo.SafeSql(@dcIndustryID), 
	@Address = dbo.SafeSql(@Address), 
	@HomePage = dbo.SafeSql(@HomePage), 
	@MapBarID = dbo.SafeSql(@MapBarID), 
	@Brief = dbo.SafeSql(@Brief)

IF NOT EXISTS(SELECT 'x' FROM caMain WITH(NOLOCK)
			INNER JOIN cpMain WITH(NOLOCK) ON caMain.cpMainID = cpMain.ID
			WHERE cpMain.ID = @cpMainID
			AND caMain.ID = @caMainID)
	GOTO Err2
--SET @Brief = REPLACE(@Brief, CHAR(13) + CHAR(10) + '?', CHAR(13) + CHAR(10) + ' ')
--IF(LEFT(@Brief, 1) = '?')
--	SET @Brief = REPLACE(@Brief, '?', ' ')
--SET @Brief = REPLACE(@Brief, '&nbsp;', ' ')
IF @Brief LIKE '最少输入20字，最多输入3000字。%'
	SET @Brief = REPLACE(@Brief, '最少输入20字，最多输入3000字。', '')
BEGIN TRAN
	BEGIN TRY
		DECLARE @AddressOld AS NVARCHAR(60),
			@HomePageOld AS VARCHAR(100),
			@BriefOld AS VARCHAR(6000),
			--@ShortNameOld VARCHAR(40),
			@IsVerify AS TINYINT
		SET @IsVerify = 0

		SELECT @MapBarID = dbo.TrimNull(@MapBarID),
			@Zip = dbo.TrimNull(@Zip),
			@Homepage = REPLACE(@Homepage, 'http://', ''),
			@Homepage = dbo.TrimNull(@Homepage)
		
		SELECT @AddressOld=RTRIM(ISNULL(Address, '')),@HomePageOld=RTRIM(ISNULL(HomePage, '')),
			@BriefOld=RTRIM(ISNULL(Brief, ''))
			--,@ShortNameOld = ISNULL(ShortName, '')
		FROM cpMain WITH(NOLOCK)
		WHERE ID=@cpMainID

		--IF LEN(dbo.Trim(@ShortName)) = 0
		--	SET @ShortName = NULL

		UPDATE cpMain SET
			--ShortName = @ShortName,
			dcCompanyKindID = @dcCompanyKindID,
			dcCompanySizeID = @dcCompanySizeID,
			dcRegionID = @dcRegionID,
			Address = @Address,
			Zip = @Zip,
			MapBarID = @MapBarID,
			HomePage = @HomePage,
			Brief = @Brief,
			LastModifyDate =GETDATE()
		WHERE ID=@cpMainID

		--保存所属行业
		DELETE FROM cpIndustry WHERE cpMainID = @cpMainID
		INSERT INTO cpIndustry
		SELECT @cpMainID, a FROM dbo.fnSplit(@dcIndustryID, ' ')

		----记录到bsCpModify审核记录
		IF dbo.TextTrim(@Address) = ''
			DELETE FROM bsCpModify WHERE cpMainID=@cpMainID AND Location='a3'
		ELSE
			IF @AddressOld <> RTRIM(@Address)
			BEGIN
				DELETE FROM bsCpModify WHERE cpMainID=@cpMainID AND Location='a3'
				INSERT INTO bsCpModify (cpMainID,caMainID,Location,ColValue) VALUES(@cpMainID,@caMainID,'a3',@Address)
				SET @IsVerify = 1
			END

		IF dbo.TextTrim(@HomePage) = ''
			DELETE FROM bsCpModify WHERE cpMainID=@cpMainID AND Location='a4'
		ELSE
			IF @HomePageOld <> RTRIM(@HomePage)
			BEGIN
				DELETE FROM bsCpModify WHERE cpMainID=@cpMainID AND Location='a4'
				INSERT INTO bsCpModify (cpMainID,caMainID,Location,ColValue) VALUES(@cpMainID,@caMainID,'a4',@HomePage)
				SET @IsVerify = 1
			END

		IF dbo.TextTrim(@Brief) = ''
			DELETE FROM bsCpModify WHERE cpMainID=@cpMainID AND Location='a5'
		ELSE
			IF @BriefOld <> RTRIM(@Brief)
			BEGIN
				DELETE FROM bsCpModify WHERE cpMainID=@cpMainID AND Location='a5'
				INSERT INTO bsCpModify (cpMainID,caMainID,Location,ColValue) VALUES(@cpMainID,@caMainID,'a5',@Brief)
				SET @IsVerify = 1
			END
/*
		IF dbo.TextTrim(@ShortName) = ''
			DELETE FROM bsCpModify WHERE cpMainID=@cpMainID AND Location='a6'
		ELSE
		BEGIN
			IF CHARINDEX(@ShortName, @Name) = 0
			BEGIN
				IF @ShortNameOld <> RTRIM(@ShortName)
				BEGIN
					DELETE FROM bsCpModify WHERE cpMainID=@cpMainID AND Location='a6'
					INSERT INTO bsCpModify (cpMainID,caMainID,Location,ColValue) VALUES(@cpMainID,@caMainID,'a6',@ShortName)
					SET @IsVerify = 1
				END
			END
			ELSE
				DELETE FROM bsCpModify WHERE cpMainID=@cpMainID AND Location='a6'
		END
*/
		--EXEC ccCaOperationLogInsert @caMainID, 12, '更新企业信息'
	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH
COMMIT TRAN
RETURN 1
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END
ERR2:
BEGIN
	RETURN -1
END


GO
/****** Object:  StoredProcedure [dbo].[cccpMainViewNumberUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.30
--创建人：Nick
--说明：企业查看次数修改
--#####################################################
CREATE PROCEDURE [dbo].[cccpMainViewNumberUpdate]
(
	@ID INT
)
AS
RETURN
BEGIN
	UPDATE cpMain 
	SET ViewNumber = ViewNumber + 1 
	WHERE ID=@ID
END
GO
/****** Object:  StoredProcedure [dbo].[ccCpMainVipBefore20170801Select]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--Lambo 20101022
--查询该简历是否向本公司申请过
--用于简历显示页面
--sean 20170731
CREATE PROCEDURE [dbo].[ccCpMainVipBefore20170801Select]
(
	@cpMainID INT
)
AS
SET NOCOUNT ON
BEGIN
    SELECT * FROM cpMainVip WITH(NOLOCK) WHERE cpMainId = @cpMainId
	--SELECT @cpMainId cpMainId
END

GO
/****** Object:  StoredProcedure [dbo].[ccCpNoViewCountSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2014.10.30
--创建人：John
--说明：获取企业未查看的预约数
--#####################################################
CREATE PROCEDURE [dbo].[ccCpNoViewCountSelect]
(
	@caMainID INT
)
AS
BEGIN
	SELECT COUNT(*) cnt 
	FROM viplaninvitelog a,viplan b 
	WHERE a.viplanid = b.id 
		AND addtype = 0 
		AND viewdate IS NULL 
		AND camainid = @caMainID
END


GO
/****** Object:  StoredProcedure [dbo].[cccpPersonalAccountInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[cccpPersonalAccountInsert]
(
	@cpCertificationID INT,
    @cpMainID INT,
    @Name VARCHAR(50),
	@BankNo VARCHAR(6),
	@IDCard VARCHAR(50)
)
AS
SET NOCOUNT ON
BEGIN
    DECLARE @MemberType TINYINT
    SELECT @MemberType = MemberType FROM cpCertification WITH(NOLOCK) WHERE ID = @cpCertificationID AND cpMainID = @cpMainID AND CerStatus IS NULL 
	IF @MemberType IS NULL
        RETURN -1

	DELETE FROM cpPersonalAccount WHERE cpCertificationID = @cpCertificationID
    INSERT INTO cpPersonalAccount(cpCertificationID, [Name], IDCard, BankNo)
    VALUES(@cpCertificationID, @Name, @IDCard, @BankNo)
    
    IF @MemberType = 2 AND ISNULL(@IDCard, '') <> '' --如果是普通认证并且是芝麻认证 人脸认证需要记录业务凭证
    BEGIN
        IF NOT EXISTS(SELECT 'X' FROM ZmxyTransaction WHERE ID = @Name)
        INSERT INTO ZmxyTransaction(ID, cpMainID, cpCertificationID) VALUES(@Name, @cpMainID, @cpCertificationID)
    END
RETURN 1
END
SET NOCOUNT OFF
GO
/****** Object:  StoredProcedure [dbo].[cccpPersonalAccountUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[cccpPersonalAccountUpdate]
	@cpCertificationID INT,
    @cpMainID INT,
    @CheckResult TINYINT
AS
SET NOCOUNT ON
BEGIN
	IF NOT EXISTS(SELECT 'X' FROM cpCertification WITH(NOLOCK) WHERE ID = @cpCertificationID AND cpMainID = @cpMainID AND CerStatus IS NULL)
        RETURN -1

    DECLARE @cpPersonalAccountID INT
    SELECT TOP 1 @cpPersonalAccountID = ID FROM cpPersonalAccount WITH(NOLOCK) WHERE cpCertificationID = @cpCertificationID AND CheckResult IS NULL AND IDCard IS NOT NULL
	IF @cpPersonalAccountID IS NULL
		RETURN -1

    IF @CheckResult = 0
    BEGIN
        DELETE FROM cpPersonalAccount WHERE ID = @cpPersonalAccountID
    END
    ELSE
    BEGIN
        DECLARE @MemberType TINYINT
        SELECT TOP 1 @MemberType = MemberType FROM cpCertification WITH(NOLOCK) WHERE ID = @cpCertificationID AND cpMainID = @cpMainID AND CerStatus IS NULL
        IF @MemberType = 1
            UPDATE cpPersonalAccount SET CheckResult = 2 WHERE ID = @cpPersonalAccountID
        ELSE
        BEGIN
            UPDATE cpPersonalAccount SET CheckResult = 1 WHERE ID = @cpPersonalAccountID
			BEGIN TRY
				UPDATE cpCertification SET CerStatus = 1 WHERE ID = @cpCertificationID AND cpMainID = @cpMainID AND CerStatus IS NULL
			END TRY
			BEGIN CATCH

			END CATCH
        END
    END
RETURN 1
END
SET NOCOUNT OFF
GO
/****** Object:  StoredProcedure [dbo].[ccCpPointByChatOnlineInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--Peter 2014-08-25修改
--首次在线沟通加分
--修改harry （10积分），每日最多可获得 （200积分）
CREATE PROCEDURE [dbo].[ccCpPointByChatOnlineInsert]
    @caMainID INT
AS
BEGIN
    BEGIN TRY
        --插入积分记录 Peter 2014-08-25
        DECLARE @TodayPoint AS INT
        DECLARE @TodayID AS INT
        DECLARE @cpMainID AS INT
        SET @TodayPoint = 0
        SET @TodayID = 0
        SELECT TOP 1 @cpMainID = cpMainID FROM caMain WITH(NOLOCK) WHERE ID = @caMainID
        SELECT TOP 1 @TodayPoint = ISNULL(Point,0),@TodayID = ISNULL(ID,0) FROM cpPoint WITH(NOLOCK) WHERE changeID = 14 AND LastModifyDate > CONVERT(VARCHAR(10), GETDATE(),120) AND cpMainID = @cpMainID
        SET @TodayPoint = @TodayPoint + 10
        
        IF @TodayPoint <= 200
        BEGIN
            IF @TodayID = 0
            BEGIN
                INSERT INTO cpPoint (cpMainID,ChangeID,Point,LastModifyDate) VALUES(@cpMainID,6,2,GETDATE())
            END
            ELSE
            BEGIN
                UPDATE cpPoint SET Point = @TodayPoint,LastModifyDate = GETDATE() WHERE ID = @TodayID 
            END
        END    
    END TRY
    BEGIN CATCH
    END CATCH
END
 
GO
/****** Object:  StoredProcedure [dbo].[ccCpPointByCpMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Mice
-- Create date: 2014-8-12
-- Description:	获取积分详情
-- Modify:      Harry 增加选择每日的积分综合,取消top200
-- =============================================
CREATE PROCEDURE [dbo].[ccCpPointByCpMainIDSelect]
(
	@cpMainId INT
)
AS
BEGIN
	DECLARE @d DATETIME, @AllPoint INT
	SET @d = convert(varchar(10), getdate(), 120)  
	DELETE cpPointCount WHERE countdate = @d AND cpMainId = @cpMainId
	SELECT @AllPoint = remainpoint FROM cpMain WHERE id = @cpMainId
	INSERT INTO cpPointCount  
	SELECT @d, @cpMainId, sum(point), @AllPoint  
	FROM cppoint   
	WHERE lastmodifydate > @d
	AND cpMainId = @cpMainId

	SELECT TOP 500 a.*, b.RemainPoint , c.ServiceType , c.OrderType  
	FROM cpPoint a
	LEFT JOIN cpMain b ON a.cpMainId = b.id 
	LEFT JOIN caOrder c ON c.id = a.relativeID AND (a.ChangeID = 15 OR a.ChangeID = 16 )
	WHERE a.cpMainId = @cpMainId
	ORDER BY a.LastModifyDate DESC
	
	SELECT TOP 30 * 
	FROM cpPointCount 
	WHERE cpMainId=@cpMainId
	ORDER BY CountDate DESC
END
GO
/****** Object:  StoredProcedure [dbo].[ccCpPointByCvSelectInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Peter
-- Create date: 2014-8-25
-- Description:	首次查询简历插入积分记录
-- =============================================
CREATE PROCEDURE [dbo].[ccCpPointByCvSelectInsert]
	-- Add the parameters for the stored procedure here
	@cpMainID INT
AS
BEGIN
	--插入积分记录
	IF NOT EXISTS (SELECT 'x' FROM cpPoint WITH(NOLOCK) WHERE ChangeID = 3 AND LastModifyDate > CONVERT(VARCHAR(10), GETDATE(),120) AND cpMainID = @cpMainID) 
		INSERT INTO cpPoint (cpMainID,ChangeID,Point,LastModifyDate) VALUES(@cpMainID,3,5,GETDATE())

END





GO
/****** Object:  StoredProcedure [dbo].[ccCpPointByLastModifyDateInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--------------------------------------------------------------------------------------------------------
--Peter 20140825创建
--每天检查添加积分项 计划任务
--修改harry 积分改为5分
CREATE PROCEDURE [dbo].[ccCpPointByLastModifyDateInsert]
AS
BEGIN
    --有有效职位+5分
    INSERT INTO cpPoint (cpMainID, ChangeID, Point, LastModifyDate)
    SELECT ID, 11, 5, GETDATE() FROM cpMain WITH(NOLOCK)
    WHERE EXISTS (SELECT 'x' FROM JobPublish WITH(NOLOCK) WHERE cpMainID = cpMain.ID AND JobPublish.Valid =1) 

    UPDATE cpMain 
    SET RemainPoint = ISNULL(RemainPoint, 0) + 5
    WHERE EXISTS(SELECT 'x' FROM JobPublish WITH(NOLOCK) WHERE JobPublish.Valid = 1 AND JobPublish.cpMainId = cpMain.Id) 
    --AND RemainPoint > 0
    
    --检查视频面试记录        
    /*SELECT a.ID, 13 ChangeID, CASE WHEN COUNT(b.ID)*5 > 50 THEN 50 ELSE COUNT(b.ID)*5 END Point, GETDATE() LastModifyDate
    INTO #t
    FROM cpMain a WITH(NOLOCK), viInterviewRecord b WITH(NOLOCK), caMain c WITH(NOLOCK), viRoom d WITH(NOLOCK)
    WHERE b.viRoomID = d.ID
        AND d.caMainID = c.ID
        AND c.cpMainID = a.ID
        AND b.BeginDate > CONVERT(VARCHAR(10), GETDATE() - 1, 120)
        AND b.BeginDate < CONVERT(VARCHAR(10), GETDATE(), 120)
        AND DATEDIFF(MINUTE, b.BeginDate, b.EndDate) >= 5
    GROUP BY a.ID

    INSERT INTO cpPoint (cpMainID, ChangeID, Point, LastModifyDate)
    SELECT * FROM #t

    UPDATE a SET a.RemainPoint= a.RemainPoint + b.Point
    FROM cpMain a, #t b
    WHERE a.Id = b.Id
    */
END

GO
/****** Object:  StoredProcedure [dbo].[cccpPointByLastModifyDateSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================-- Author:        Peter
-- Create date: 2014-08-20 09:55
-- Description:    
-- 修改Harry 修改为changeid=1 登录积分2017-4-19
-- =============================================
CREATE PROCEDURE [dbo].[cccpPointByLastModifyDateSelect]
(
    @cpMainID INT,
    @BeginDate DATETIME,
    @EndDate DATETIME
)
AS
BEGIN
    SELECT LastModifyDate 
    FROM cpPoint 
    WHERE cpMainID = @cpMainID 
    AND ChangeID= 1
    AND LastModifyDate BETWEEN @BeginDate AND @EndDate
END
GO
/****** Object:  StoredProcedure [dbo].[cccpPointByLoginInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Peter
-- Create date: 2014-08-20 09:55
-- Description:	
-- =============================================
CREATE PROCEDURE [dbo].[cccpPointByLoginInsert]
(
	@cpMainID INT
)
AS
BEGIN TRY
	--查询是否是第一次登陆
	IF EXISTS(SELECT 'x' FROM cpPoint WITH(NOLOCK) 
		WHERE cpMainID = @cpMainID 
		AND ChangeID = 1
		AND LastModifyDate > CONVERT(VARCHAR(10), GETDATE(),120))
		RETURN 0
 
	--查询前一天获取的分值
	DECLARE @LastLoginPoint AS INT
	SET @LastLoginPoint = 0
	SELECT @LastLoginPoint = Point
	FROM cpPoint WITH(NOLOCK) 
	WHERE cpMainID = @cpMainID
		AND ChangeID = 1
		AND LastModifyDate BETWEEN (CONVERT(VARCHAR(10),GETDATE()-1,120) + ' 00:00:00') AND (CONVERT(VARCHAR(10),GETDATE()-1,120) + ' 23:59:59')

	--在前一天的分值基础上+2  最大为10分
	SET @LastLoginPoint = @LastLoginPoint + 2
	IF @LastLoginPoint > 10
		SET @LastLoginPoint = 10

	--插入积分登陆记录
	INSERT INTO cpPoint (cpMainID,ChangeID,Point,LastModifyDate) VALUES(@cpMainID,1,@LastLoginPoint,GETDATE())
	RETURN 1
END TRY
BEGIN CATCH
END CATCH





GO
/****** Object:  StoredProcedure [dbo].[cccpPointByPointSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Peter
-- Create date: 2014-08-20 09:55
-- Description:	
-- Mice 2014-8-28 修改 ： 当天获得的积分中不包括取消订单  
-- =============================================
CREATE PROCEDURE [dbo].[cccpPointByPointSelect]
(
	@cpMainID INT
)
AS
BEGIN
	SELECT (SELECT TOP 1 RemainPoint FROM cpMain WITH(NOLOCK) WHERE ID = @cpMainID) RemainPoint,
		ISNULL((SELECT SUM(Point) FROM cpPoint WITH(NOLOCK) WHERE cpMainID = @cpMainID AND ChangeID <> 16 AND Point > 0 AND LastModifyDate > CONVERT(VARCHAR(10),GETDATE(),120)),0) TodayPoint, 
		ISNULL((SELECT Point FROM cpPoint WITH(NOLOCK) WHERE cpMainID = @cpMainID AND ChangeID = 1 AND LastModifyDate > CONVERT(VARCHAR(10),GETDATE(),120)),0) LoginPoint
END





GO
/****** Object:  StoredProcedure [dbo].[cccpRefreshlogDayByCpMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2014.10.31
--创建人：Nick
--说明：返回企业的日刷新数量
--修改:harry 增加刷新数2017-12-21
--#####################################################
CREATE PROCEDURE [dbo].[cccpRefreshlogDayByCpMainIDSelect]
(
	@dtStart DATETIME,
	@dtEnd DATETIME,
	@CpMainID INT
)
AS
SET NOCOUNT ON
BEGIN
	DECLARE @Tabel AS TABLE(Refreshdate DATETIME)
	--插入数据 刷新数刷新记录
	INSERT INTO @Tabel
	SELECT runDateTime
	FROM jobRefreshLog WITH(NOLOCK)
	WHERE cpMainId = @cpMainId 
	AND  runDateTime> @dtStart  
	AND  runDateTime< @dtEnd 
	
	--插入数据 登录刷新、老刷新
	INSERT INTO @Tabel
	SELECT RefreshDate
	FROM Maindb..cpRefreshlog WITH(NOLOCK)
	WHERE cpMainId = @cpMainId 
	AND  RefreshDate > @dtStart  
	AND  RefreshDate < @dtEnd
	
	SELECT TOP 1000 *
	FROM @Tabel 
        ORDER BY Refreshdate
END
GO
/****** Object:  StoredProcedure [dbo].[cccpRefreshlogMonthByCpMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.31
--创建人：Nick
--说明：返回企业的月刷新数量
--修改：harry 增加职位刷新数记录 2017-11-21
--#####################################################
CREATE PROCEDURE [dbo].[cccpRefreshlogMonthByCpMainIDSelect]
(
	@dtStart DATETIME,
	@dtEnd DATETIME,
	@CpMainID INT
)
AS
SET NOCOUNT ON
BEGIN
	DECLARE @Tabel AS TABLE(Refreshdate DATETIME)
	--插入数据 刷新数刷新记录
	INSERT INTO @Tabel
	SELECT runDateTime
	FROM jobRefreshLog WITH(NOLOCK)
	WHERE cpMainId = @cpMainId 
	AND runDateTime> @dtStart  
	AND runDateTime< @dtEnd 
	
	--插入数据 登录刷新、老刷新
	INSERT INTO @Tabel
	SELECT RefreshDate
	FROM Maindb..cpRefreshlog
	WHERE cpMainId = @cpMainId 
	AND RefreshDate > @dtStart  
	AND RefreshDate < @dtEnd

	SELECT TOP 1000 CONVERT(VARCHAR(10),RefreshDate, 121) AS sdate, COUNT(1) AS refreshNum
	FROM @Tabel 
	GROUP BY CONVERT(varchar(10),RefreshDate, 121)
	ORDER BY CONVERT(varchar(10),RefreshDate, 121)
END


GO
/****** Object:  StoredProcedure [dbo].[ccCpSessionByCaMainIDDelete]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.30
--创建人：Nick
--说明：删除cpsession
--#####################################################
CREATE PROCEDURE [dbo].[ccCpSessionByCaMainIDDelete]
(
	@CamainID INT,
	@Cookies VARCHAR(100)
)
AS
BEGIN TRY
	DELETE FROM cpSession 
	WHERE caMainID=@CamainID 
	AND (Cookies=@Cookies Or RefreshDate < DateAdd(mi, -10, GETDATE()))
	RETURN 1
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[ccCpSessionByCaMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.30
--创建人：Nick
--说明：获取cpsession
--#####################################################
CREATE PROCEDURE [dbo].[ccCpSessionByCaMainIDSelect]
(
	@CamainID INT
)
AS
BEGIN TRY
	SELECT TOP 1 * FROM cpSession WITH(NOLOCK) WHERE caMainID=@CamainID ORDER BY RefreshDate Desc
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[ccCpSessionByCaMainIDUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.30
--创建人：Nick
--说明：修改cpsession
--#####################################################
CREATE PROCEDURE [dbo].[ccCpSessionByCaMainIDUpdate]
(
	@CamainID INT,
	@Cookies VARCHAR(100)
)
AS
BEGIN TRY
	UPDATE cpSession SET RefreshDate=GETDATE() 
	WHERE caMainID=@CamainID AND Cookies=@Cookies
	RETURN 1
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[cccpSessionLogDelete]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.30
--创建人：Nick
--说明：企业退出后删除SessionLOg
--#####################################################
CREATE PROCEDURE [dbo].[cccpSessionLogDelete]
(
	@caMainID INT,
	@Cookie VARCHAR(50)
)
AS
BEGIN TRY
	DELETE FROM cpSession 
	WHERE caMainID = @caMainID 
	AND (Cookies = @Cookie Or RefreshDate < DateAdd(mi, -10, GETDATE()))
	RETURN 1
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[ccCpViInterviewSmsMessageLogInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


--#####################################################
--创建时间：2014.10.29
--创建人：John
--说明：企业邀请个人进入面试室添加短信通知
--#####################################################
CREATE PROCEDURE [dbo].[ccCpViInterviewSmsMessageLogInsert]
(
	@JobID INT,
	@CvMainID INT
)
AS
BEGIN
	DECLARE @cnt INT
	SELECT @cnt = COUNT(1) 
	FROM SmsMessageLog 
	WHERE msgtype = 121 
	AND camainid =
		(
			SELECT camainid 
			FROM job 
			WHERE id = @JobID
		 ) 
	AND adddate > CONVERT(VARCHAR(10), GETDATE(), 23)
	IF @cnt < 10
	BEGIN
		INSERT SmsMessageLog(SendMan, ManagerUserId, paMainId, caMainId, Mobile, MsgType, IsCat, Msg)
			SELECT top 1 0, NULL, a.ID, e.caMainID, b.Mobile, 121, 0, ISNULL(b.Name,'') +'，'+ d.Name +'在'+ c.SubSiteName + c.EmailSite +'上邀请您参加视频面试，请登录网站查看'
			FROM cvMain a WITH(NOLOCK), paMain b WITH(NOLOCK), dcSubSite c WITH(NOLOCK),cpMain d WITH(NOLOCK),job e WITH(NOLOCK)
			WHERE a.paMainID = b.ID 
			AND b.dcSubSiteID = c.ID 
			AND d.id = e.cpMainID 
			AND e.ID = @JobID 
			AND b.Mobile > '' 
			AND a.ID = @CvMainID 
			AND b.IsReceiveSms = 1 
			AND 
				(
					SELECT COUNT(1) 
					FROM SmsMessageLog WITH(NOLOCK) 
					WHERE paMainid =
							(
								SELECT paMainID 
								FROM cvMain 
								WHERE id = @CvMainID
							) 
						AND caMainID =
							(
								SELECT camainid 
								FROM job 
								WHERE id = @JobID
							) 
						AND MsgType = 121
				) = 0 
	END
END


GO
/****** Object:  StoredProcedure [dbo].[ccCvBySearchPublishSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/********************************************************
Update 2012-9-3 sean
object Add Height
********************************************************/
CREATE PROCEDURE [dbo].[ccCvBySearchPublishSelect]
(
	@dcJobTypeID VARCHAR(50),		--职位类别
	@dcRegionID VARCHAR(50),		--求职地区
	@dcIndustryID VARCHAR(50),		--现从事行业
	@IncludeOld BIT,				--1包含曾从事职业
	@dcJobTypeIDExpect VARCHAR(50),--期望职位类别
	@dcIndustryIDExpect VARCHAR(50),--期望求职行业
	@dcSalaryID TINYINT,			--月薪
	@IsNegotiable BIT,				--1允许面议，不面议
	@MinExperience TINYINT,		--工作经验
	@dcEducationID TINYINT,			--最低学历
	@LanguageType SMALLINT,			--语种
	@KeyWord NVARCHAR(20),			--关键词
	@College NVARCHAR(50),			--学校名称
	@Standard BIT,					--是否统招
	@SubNodeNum INT,				--下属人数
	@Major INT,						--所学专业
	@Graduation INT,				--毕业时间 year
	@Gender TINYINT,				--性别,2不限
	@MaxAge SMALLINT,				--最大年龄
	@MinAge	SMALLINT,				--最小年龄
	@LivePlace VARCHAR(50),			--现居住地
	@AccountPlace INT,				--户口所在地
	@MobilePlace VARCHAR(50),		--现居住地
	@SortType TINYINT,				--排序方式
	@CvMainID INT,					--简历ID
	--@dcCareerStatus TINYINT,         --简历状态
	--sessionid，没有采用全部人员共享方式，因为10分钟内，搜索相同条件的可能性很大，	
	--而10分钟搜索的用户翻到第二页时内容可能会和第一页一样。这样让用户很难理解。
	--使用SessionID,可以保证60分钟内查询结果一致。出现不一致的几率很小
	@SessionID INT,
	@PageNumber INT,				--翻页页码
	@IsExpand BIT,					--是否扩大地区范围
	@caMainID INT					--企业用户ID，用来判断是否和建立联系
)
AS
--return
SET NOCOUNT ON
BEGIN TRY
	DECLARE @MajorName AS NVARCHAR(20)
	IF @dcJobTypeID IS NULL
		SET @dcJobTypeID = ''
	SET @dcJobTypeID = dbo.FormatIDS(@dcJobTypeID)
	IF @dcJobTypeIDExpect IS NULL
		SET @dcJobTypeIDExpect = ''
	SET @dcJobTypeIDExpect = dbo.FormatIDS(@dcJobTypeIDExpect)
	IF @dcRegionID IS NULL
		SET @dcRegionID = ''
	SET @dcRegionID = dbo.FormatIDS(@dcRegionID)
	IF @dcIndustryID IS NULL
		Set @dcIndustryID = ''
	SET @dcIndustryID = dbo.FormatIDS(@dcIndustryID)
	IF @dcIndustryIDExpect IS NULL
		SET @dcIndustryIDExpect = ''
	SET @dcIndustryIDExpect = dbo.FormatIDS(@dcIndustryIDExpect)
	IF @dcSalaryID IS NULL
		SET @dcSalaryID = 0
	IF @IsNegotiable IS NULL
		SET @IsNegotiable = 0
	IF @MinExperience IS NULL
		SET @MinExperience = 99
	IF @dcEducationID IS NULL
		SET @dcEducationID = 0
	IF @LanguageType IS NULL
		SET @LanguageType = 0
	IF @College IS NULL
		SET @College = ''
	IF LEN(@College) < 2
		SET @College = ''
	IF @KeyWord IS NULL OR LEN(@KeyWord) < 2
		SET @KeyWord = ''
	ELSE
		IF LEFT(@KeyWord, 7) = 'major::'
			SET @MajorName = REPLACE(@KeyWord, 'major::', '')
			
	SET @KeyWord = LTRIM(RTRIM(dbo.SafeSQL(@KeyWord)))
	SET @KeyWord = REPLACE(@KeyWord, ' ', ' near ')
	
	SET @College = dbo.SafeSQL(@College)
	IF @SubNodeNum IS NULL
		SET @SubNodeNum = 0
	IF @MaxAge IS NULL OR @MaxAge = 0
		SET @MaxAge = 99
	IF @MinAge IS NULL OR @MinAge = 0
		SET @MinAge = 99
	IF @LivePlace IS NULL
		SET @LivePlace = ''
	SET @LivePlace = dbo.FormatIDS(@LivePlace)
	IF @MobilePlace IS NULL
		SET @MobilePlace = ''
	SET @MobilePlace = dbo.FormatIDS(@MobilePlace)
	IF @AccountPlace IS NULL
		SET @AccountPlace = 0
	IF @Gender IS NULL
		SET @Gender = 2
	IF @IncludeOld IS NULL
		SET @IncludeOld = 0
	IF @Major IS NULL
		SET @Major = 0
	IF @Graduation IS NULL
		SET @Graduation = 0
	ELSE IF @Graduation > DATEPART(YEAR, GETDATE()) + 1 OR @Graduation < DATEPART(YEAR, GETDATE()) - 10
		SET @Graduation = 0
	IF @CvMainID IS NULL
		SET @CvMainID = 0
	IF @Standard IS NULL
		SET @Standard = 0
	IF @IsExpand IS NULL
		SET @IsExpand = 0

	IF @CvMainID = 0
	BEGIN
		----给null值变量赋默认值
		DECLARE @cpSearchConditionID AS INT
		SELECT @cpSearchConditionID=0, @SessionID = 1
		DECLARE @MinId AS INT
		
		--sqlserver中计划任务自动删除60分钟前的数据
		SELECT TOP 1 @cpSearchConditionID = ID FROM SearchDB..cpSearchCondition WITH(NOLOCK)
		WHERE SessionID=@SessionID AND dcJobTypeID=@dcJobTypeID AND dcJobTypeIDExpect=@dcJobTypeIDExpect
		AND dcRegionID=@dcRegionID AND dcIndustryID=@dcIndustryID AND dcIndustryIDExpect=@dcIndustryIDExpect
		AND IncludeOld=@IncludeOld AND dcSalaryID=@dcSalaryID AND IsNegotiable=@IsNegotiable 
		AND MinExperience=@MinExperience AND dcEducationID=@dcEducationID AND LanguageType=@LanguageType 
		AND KeyWord=@KeyWord AND College=@College AND Standard=@Standard AND SortType=@SortType
		AND SubNodeNum = @SubNodeNum AND Major = @Major AND Graduation = @Graduation AND Gender=@Gender AND MaxAge=@MaxAge
		AND MinAge=@MinAge AND LivePlace=@LivePlace AND AccountPlace=@AccountPlace AND MobilePlace=@MobilePlace AND IsExpand=@IsExpand
		AND LogTime > DATEADD(M, -60, GETDATE())
		ORDER BY ID DESC

		IF ISNULL(@cpSearchConditionID, 0) = 0
			GOTO SelectReset	--无数据，重新搜索
		ELSE		
			GOTO GetRecordSet	--从临时结果中提取数据
	END
	ELSE
	BEGIN
		----如果有简历id，则直接显示，不再查询
		SELECT COUNT(1) FROM cvMainPublish WITH(NOLOCK) WHERE ID = @CvMainID AND Valid > 0
		DECLARE @T_Cv AS TABLE(
			ID INT,
			dcMajorID INT,
			Degree TINYINT,
			RelatedWorkYears INT,
			dcSalaryID TINYINT,
			Speciality VARCHAR(MAX) COLLATE Chinese_PRC_CI_AS,
			RefreshDate SMALLDATETIME,
			LastLoginDate SMALLDATETIME,
			JobName VARCHAR(100) COLLATE Chinese_PRC_CI_AS,
			Gender BIT,
			BirthDay INT,
			LivePlace INT,
			Attachment VARCHAR(50),
			HasPhoto TINYINT,
			College NVARCHAR(50),
			EduType TINYINT,
			MajorName NVARCHAR(20),
			Graduation INT,
			HasViewed BIT,
			ViewDate SMALLDATETIME,
			HasRemarked BIT,
			LastJobTypeID INT,
			Valid TINYINT
		)

		INSERT INTO @T_Cv(ID,dcMajorID,Degree,RelatedWorkYears,dcSalaryID,Speciality,RefreshDate,LastLoginDate,
			JobName,Gender,BirthDay,LivePlace,LastJobTypeID,Attachment,HasPhoto,HasViewed,HasRemarked,Valid)
		SELECT a.ID,a.dcMajorID,a.Degree,a.RelatedWorkYears,a.dcSalaryID,ISNULL(a.Speciality,a.SpecialityEng) Speciality,a.RefreshDate,
			j.LastLoginDate,ISNULL(a.JobName, '应届毕业生') JobName,j.Gender,j.BirthDay,j.LivePlace,a.LastJobTypeID,
			a.Attachment,j.HasPhoto,0,0,a.Valid FROM cvMainPublish a WITH(NOLOCK) 
			INNER JOIN paMainPublish j WITH(NOLOCK) ON a.paMainID=j.ID
			WHERE a.ID=@CvMainID AND a.Valid > 0

		UPDATE a SET a.College = ISNULL(b.GraduateCollage,b.GraduateCollageEng), a.EduType = b.EduType, 
			a.MajorName = ISNULL(b.MajorName,b.MajorNameEng), a.Graduation = b.Graduation FROM @T_Cv a,
			cvEducationPublish b WITH(NOLOCK) WHERE b.cvMainID = a.ID AND b.Degree = a.Degree

		UPDATE a SET a.HasViewed = 1, a.ViewDate = (SELECT AddDate FROM caCvViewLog WITH(NOLOCK) WHERE cvMainID = a.ID AND caMainID=@caMainID)
			FROM @T_Cv a WHERE EXISTS(SELECT 'X' FROM caCvViewLog WITH(NOLOCK) WHERE cvMainID = a.ID AND caMainID=@caMainID)
		
		UPDATE a SET a.HasRemarked = 1
			FROM @T_Cv a WHERE EXISTS(SELECT 'X' FROM caCvRemark WITH(NOLOCK) WHERE cvMainID = a.ID AND caMainID=@caMainID)

		SELECT * FROM @T_Cv

		RETURN
	END

SelectReset:				--从cv中搜索数据
	BEGIN
		DECLARE @SQL AS VARCHAR(8000)
		DECLARE @WHERE AS VARCHAR(8000)
		DECLARE @FROM AS VARCHAR(1000)
		----记录查询条件
		INSERT INTO SearchDB..cpSearchCondition(SessionID,dcJobTypeID,dcJobTypeIDExpect,dcRegionID,dcIndustryID,
			dcIndustryIDExpect,IncludeOld,dcSalaryID,IsNegotiable,SortType,
			MinExperience,dcEducationID,LanguageType,KeyWord,College,Standard,SubNodeNum,
			Major,Graduation,Gender,MaxAge,MinAge,LivePlace,AccountPlace,MobilePlace,IsExpand, ReuseNumber)
		VALUES(@SessionID,@dcJobTypeID,@dcJobTypeIDExpect,@dcRegionID,@dcIndustryID,
			@dcIndustryIDExpect,@IncludeOld,@dcSalaryID,@IsNegotiable,@SortType,
			@MinExperience,@dcEducationID,@LanguageType,@KeyWord,@College,@Standard,@SubNodeNum,
			@Major,@Graduation,@Gender,@MaxAge,@MinAge,@LivePlace,@AccountPlace,@MobilePlace,@IsExpand, 0)
		SET @cpSearchConditionID = @@IDENTITY

		------生成职位类别的表变量，因为职位类别有包含（父子）关系
		DECLARE @T_JobPlace AS TABLE(ID INT)
		DECLARE @T_JobType AS TABLE(ID INT)
		DECLARE @JobType AS VARCHAR(3000)
		DECLARE @JobTypeExpect AS VARCHAR(3000)
		DECLARE @JobPlace AS VARCHAR(2000)
		DECLARE @tmpLivePlace AS VARCHAR(2000)
		DECLARE @tmpMobilePlace AS VARCHAR(2000)
		
		SET @JobPlace = ''
		SET @tmpLivePlace = ''
		SET @tmpMobilePlace = ''
		SET @JobType=''
		SET @JobTypeExpect = ''
		SET @WHERE = ' WHERE a.Valid > 0'
		----生成工作地点的表变量
		IF LEN(@dcRegionID) > 0
		BEGIN
			INSERT INTO @T_JobPlace
			SELECT * FROM dbo.fnSplit(@dcRegionID, ',')
			SELECT @JobPlace = (@JobPlace + ' OR h.dcRegionID Like ''' + LTRIM(STR(ID) + '%''')) FROM @T_JobPlace
			IF @IsExpand = 1
			BEGIN
				SELECT @JobPlace = (@JobPlace + ' OR h.dcRegionID = ''' + LTRIM(STR(LEFT(ID,2)))+'''' )
				FROM @T_JobPlace WHERE LEN(ID) > 2
				SELECT @JobPlace = (@JobPlace + ' OR h.dcRegionID = ''' + LTRIM(STR(LEFT(ID,4)))+'''' )
				FROM @T_JobPlace WHERE LEN(ID) > 4
			END
			IF LEN(@JobPlace) > 0
				SET @JobPlace = RIGHT(@JobPlace, LEN(@JobPlace) -4)
		END

		IF LEN(@LivePlace) > 0
		BEGIN
			DELETE FROM @T_JobPlace
			INSERT INTO @T_JobPlace
			SELECT * FROM dbo.fnSplit(@LivePlace, ',')
			SELECT @tmpLivePlace = (@tmpLivePlace + ' OR j.LivePlace Like ''' + LTRIM(STR(ID) + '%''')) FROM @T_JobPlace
			IF LEN(@tmpLivePlace) > 0
				SET @tmpLivePlace = RIGHT(@tmpLivePlace, LEN(@tmpLivePlace) -4)
		END
		IF LEN(@MobilePlace) > 0
		BEGIN
			DELETE FROM @T_JobPlace
			INSERT INTO @T_JobPlace
			SELECT * FROM dbo.fnSplit(@MobilePlace, ',')
			SELECT @tmpMobilePlace = (@tmpMobilePlace + ' OR j.MobileRegion Like ''' + LTRIM(STR(ID) + '%''')) FROM @T_JobPlace
			IF LEN(@tmpMobilePlace) > 0
				SET @tmpMobilePlace = RIGHT(@tmpMobilePlace, LEN(@tmpMobilePlace) -4)
		END

		----生成求聘职位的表变量
		IF LEN(@dcJobTypeID) > 0
		BEGIN
			DECLARE @T_Temp AS TABLE(ID INT)		--临时表，用于构建组合查询语句
			INSERT INTO @T_Temp
			SELECT * FROM dbo.fnSplit(@dcJobTypeID, ',')

			INSERT INTO @T_JobType
			SELECT DISTINCT ID FROM dcJobType WITH(NOLOCK)
			WHERE ParentId IN(SELECT ID FROM @T_TEMP) 
			OR ParentId2 in(SELECT ID FROM @T_TEMP)
			OR ID IN(SELECT ID FROM @T_TEMP)
			----生成in字符串
			SELECT @JobType = (@JobType + LTRIM(STR(ID) + ',')) FROM @T_JobType
			IF RIGHT(@JobType, 1) = ','
				SET @JobType = LEFT(@JobType, LEN(@JobType) - 1)
		END

		IF LEN(@dcJobTypeIDExpect) > 0
		BEGIN
			DECLARE @T_Temp1 AS TABLE(ID INT)		--临时表，用于构建组合查询语句
			INSERT INTO @T_Temp1
			SELECT * FROM dbo.fnSplit(@dcJobTypeIDExpect, ',')
			DELETE FROM @T_JobType
			INSERT INTO @T_JobType
			SELECT DISTINCT ID FROM dcJobType WITH(NOLOCK)
			WHERE ParentId IN(SELECT ID FROM @T_TEMP1) 
			OR ParentId2 in(SELECT ID FROM @T_TEMP1)
			OR ID IN(SELECT ID FROM @T_TEMP1)
			----生成in字符串
			SELECT @JobTypeExpect = (@JobTypeExpect + LTRIM(STR(ID) + ',')) FROM @T_JobType
			IF RIGHT(@JobTypeExpect, 1) = ','
				SET @JobTypeExpect = LEFT(@JobTypeExpect, LEN(@JobTypeExpect) - 1)

		END
		----建立关键字搜索的临时表
		CREATE TABLE #FullText(
			CvID INT NOT NULL
		)
		----建立临时表
		CREATE TABLE #Cv(
			ID INT NOT NULL,
			RefreshDate SMALLDATETIME NOT NULL
		)
		----生成插入临时表的Sql语句
		SET @SQL = '
			INSERT INTO #Cv
			SELECT DISTINCT TOP 2000 a.ID'
		IF @SortType = 1
			SET @SQL = @SQL + ', j.LastLoginDate'
		ELSE
			SET @SQL = @SQL + ', a.RefreshDate'
		
		SET @FROM = '
			FROM cvMainPublish a WITH(NOLOCK) INNER JOIN paMainPublish j WITH(NOLOCK) ON a.paMainID=j.ID'
		----工作经验的职位类别
		IF LEN(@dcJobTypeID) > 0
		BEGIN
			IF @IncludeOld = 0  ----最近从事和曾从事职位
				SET @WHERE = @WHERE + '
					AND (a.LastJobTypeID IN(' + @JobType +'))'
			ELSE
				SET @WHERE = @WHERE + '
					AND (c.dcJobTypeID IN(' + @JobType +'))'
		END
		----期望职位类别
		IF LEN(@dcJobTypeIDExpect) > 0
		BEGIN
			SET @WHERE = @WHERE + '
				AND (g.dcJobTypeID IN(' + @JobTypeExpect +'))'

		END

		----工作地点
		IF LEN(@JobPlace) > 0 
			SET @WHERE = @WHERE + '
				AND (' + @JobPlace + ')'

		----现从事行业
		IF LEN(@dcIndustryID) > 0
			SET @WHERE = @WHERE + '
				AND (a.LastIndustryID IN(' + @dcIndustryID + '))'
		----期望行业
		IF LEN(@dcIndustryIDExpect) > 0
		BEGIN
			SET @WHERE = @WHERE + '
				AND (i.dcIndustryID IN(' + @dcIndustryIDExpect + '))'
		END
		----下属人数
		IF @SubNodeNum > 0
		BEGIN
			SET @WHERE = @WHERE + '
				AND a.SubNodeNum = ' + LTRIM(STR(@SubNodeNum))
		END
		----当前所在地
		IF LEN(@tmpLivePlace) > 0
		BEGIN
			SET @WHERE = @WHERE + '
				AND (' + @tmpLivePlace + ')'
		END
		----Mobile所在地
		IF LEN(@tmpMobilePlace) > 0
		BEGIN
			SET @WHERE = @WHERE + '
				AND (' + @tmpMobilePlace + ')'
		END
		----户口所在地
		IF @AccountPlace > 0
		BEGIN
			SET @WHERE = @WHERE + '
				AND j.AccountPlace LIKE ''' + LTRIM(STR(@AccountPlace)) + '%'''
		END
		----专业
		IF @Major > 0
		BEGIN
			SET @WHERE = @WHERE + '
				AND b.dcMajorID = ' + LTRIM(STR(@Major))
		END
		--Graduation
		IF @Graduation = DATEPART(YEAR, GETDATE()) + 1
		BEGIN
			SET @WHERE = @WHERE + '
				AND b.Graduation > ' + LTRIM(STR(@Graduation)) + '00'
		END
		ELSE IF @Graduation > DATEPART(YEAR, GETDATE()) - 10
		BEGIN
			SET @WHERE = @WHERE + '
				AND b.Graduation BETWEEN ' + LTRIM(STR(@Graduation)) + '00 AND ' + LTRIM(STR(@Graduation)) + '99'
		END
		ELSE IF @Graduation = DATEPART(YEAR, GETDATE()) - 10
		BEGIN
			SET @WHERE = @WHERE + '
				AND b.Graduation < ' + LTRIM(STR(@Graduation)) + '99'
		END		
		----性别
		IF @Gender < 2
		BEGIN
			SET @WHERE = @WHERE + '
				AND j.Gender=' + LTRIM(STR(@Gender))
		END
		----年龄
		IF @MinAge < 99
		BEGIN
			SET @WHERE = @WHERE + '
				AND j.BirthDay <= ' + LTRIM(STR(dbo.AgeToBirth(@MinAge)))
		END
		IF @MaxAge < 99
		BEGIN
			SET @MaxAge = @MaxAge + 1
			SET @WHERE = @WHERE + '
				AND j.BirthDay > ' + LTRIM(STR(dbo.AgeToBirth(@MaxAge)))
		END
		----薪水
		IF @dcSalaryID > 0
		BEGIN
			SET @WHERE = @WHERE + '
			AND((
				a.dcSalaryID >=' + LTRIM(STR(@dcSalaryID-1)) + '
				AND a.dcSalaryID <=' + LTRIM(STR(@dcSalaryID+1)) + '
				)'
			IF @IsNegotiable = 1		--包括面议
				SET @WHERE = @WHERE + '
				OR a.IsNegotiable=1'
			SET @WHERE = @WHERE + ')'
		END
		----工作经验要求
		IF @MinExperience < 99
		BEGIN
			IF @MinExperience = 4
				SET @WHERE = @WHERE + ' 
				AND a.RelatedWorkYears=11'
			ELSE IF @MinExperience = 1
				SET @WHERE = @WHERE + ' 
				AND a.RelatedWorkYears>=1 AND a.RelatedWorkYears<=2'
			ELSE IF @MinExperience = 2
				SET @WHERE = @WHERE + '
				AND a.RelatedWorkYears>=3 AND a.RelatedWorkYears<=5'
			ELSE IF @MinExperience = 3
				SET @WHERE = @WHERE + ' 
				AND a.RelatedWorkYears>=6 AND a.RelatedWorkYears<=10'
			ELSE IF @MinExperience = 5
				SET @WHERE = @WHERE + ' 
				AND a.RelatedWorkYears>=2 AND a.RelatedWorkYears<=3'
			ELSE
				SET @WHERE = @WHERE + ' 
				AND a.RelatedWorkYears=0'
		END
		----学历要求
		IF @dcEducationID > 0
		BEGIN
			IF @dcEducationID = 1
				SET @WHERE = @WHERE + ' AND a.Degree IN(1,2,3,4) '
			ELSE IF @dcEducationID = 2
				SET @WHERE = @WHERE + ' AND a.Degree <= 5 '
			ELSE IF @dcEducationID = 3
				SET @WHERE = @WHERE + ' AND a.Degree = 5 '
			ELSE IF @dcEducationID = 4
				SET @WHERE = @WHERE + ' AND a.Degree IN(5,6) '
			ELSE IF @dcEducationID = 5
				SET @WHERE = @WHERE + ' AND a.Degree = 6 '
			ELSE IF @dcEducationID = 6
				SET @WHERE = @WHERE + ' AND a.Degree >= 6 '
			ELSE IF @dcEducationID = 7
				SET @WHERE = @WHERE + ' AND a.Degree = 7 '
			ELSE IF @dcEducationID = 8
				SET @WHERE = @WHERE + ' AND a.Degree = 8 '

			IF @Major > 0 OR LEN(@College) > 0 OR @Standard = 1 OR @MajorName > ''
				SET @WHERE = @WHERE + '
				AND b.Degree = a.Degree'
			IF @Standard = 1
				SET @WHERE = @WHERE + '
				AND b.EduType=1'
		END
		----语种
		IF @LanguageType > 0
			SET @WHERE = @WHERE + '
				AND d.LanguageType = ' + LTRIM(STR(@LanguageType))
		----关键词
		IF LEN(@KeyWord) > 0 AND @MajorName IS NULL
		BEGIN
			DECLARE @S DATETIME, @SqlFt VARCHAR(MAX)
			SELECT @S = GETDATE()

			INSERT INTO #FullText
			SELECT [key] FROM CONTAINSTABLE(CvMainPublish, *, @KeyWord, 20000) AS KeyCv
			
			INSERT INTO #FullText
			SELECT DISTINCT cvMainID FROM CvExperiencePublish WITH(NOLOCK) WHERE ID IN(
				SELECT [key] FROM CONTAINSTABLE(CvExperiencePublish, *, @KeyWord, 20000) AS KeyCv)
			
			INSERT INTO #FullText
			SELECT DISTINCT cvMainID FROM CvEducationPublish WITH(NOLOCK) WHERE ID IN(
				SELECT [key] FROM CONTAINSTABLE(CvEducationPublish, *, @KeyWord, 20000) AS KeyCv)
			
			INSERT INTO #FullText
			SELECT DISTINCT cvMainID FROM cvProjectPublish WITH(NOLOCK) WHERE ID IN(
				SELECT [key] FROM CONTAINSTABLE(cvProjectPublish, *, @KeyWord, 20000) AS KeyCv)

			INSERT INTO #FullText
			SELECT DISTINCT cvMainID FROM CvTrainingPublish WITH(NOLOCK) WHERE ID IN(
				SELECT [key] FROM CONTAINSTABLE(CvTrainingPublish, *, @KeyWord, 20000) AS KeyCv)
            --Richard 2011.8.21增加

			INSERT INTO #FullText
			SELECT DISTINCT cvMainID FROM CvAppendixPublish WITH(NOLOCK) WHERE ID IN(
				SELECT [key] FROM CONTAINSTABLE(CvAppendixPublish, *, @KeyWord, 20000) AS KeyCv)
            --Richard 2011.8.24增加

			SELECT @SqlFt = 'SELECT [key] FROM CONTAINSTABLE(CvMainPublish, *, ''' + @KeyWord + ''',20000) AS KeyCv ORDER BY [key] DESC 开始：' + CONVERT(varchar(8), @S, 8) + '  结束：' + CONVERT(varchar(8), getdate(), 8)

			UPDATE SearchDB..cpSearchCondition SET SqlFT = @SqlFt WHERE ID = @cpSearchConditionID
		END
		----学校名称
		IF LEN(@College) > 0
			SET @WHERE = @WHERE + '
				AND b.GraduateCollage LIKE ''%' + LTRIM((@College)) + '%'''
		IF LEN(@MajorName) > 0
			SET @WHERE = @WHERE + '
				AND b.MajorName LIKE ''%' + LTRIM((@MajorName)) + '%'''

		IF CHARINDEX('b.',@WHERE) > 0
			SET @FROM = @FROM + ' INNER JOIN cvEducationPublish b WITH(NOLOCK) ON a.ID=b.cvMainID'
		IF CHARINDEX('c.',@WHERE) > 0
			SET @FROM = @FROM + ' INNER JOIN CvExperiencePublish c WITH(NOLOCK) ON a.ID=c.cvMainID'
		IF CHARINDEX('d.',@WHERE) > 0
			SET @FROM = @FROM + ' INNER JOIN cvLanguagePublish d WITH(NOLOCK) ON a.ID=d.cvMainID'
		IF CHARINDEX('e.',@WHERE) > 0
			SET @FROM = @FROM + ' INNER JOIN CvTrainingPublish e WITH(NOLOCK) ON a.ID=e.cvMainID'
		IF CHARINDEX('f.',@WHERE) > 0
			SET @FROM = @FROM + ' INNER JOIN cvProjectPublish f WITH(NOLOCK) ON a.ID=f.cvMainID'
		IF CHARINDEX('g.',@WHERE) > 0
			SET @FROM = @FROM + ' INNER JOIN cvJobTypePublish g WITH(NOLOCK) ON a.ID=g.cvMainID'
		IF CHARINDEX('h.',@WHERE) > 0
			SET @FROM = @FROM + ' INNER JOIN cvJobPlacePublish h WITH(NOLOCK) ON a.ID=h.cvMainID'
		IF CHARINDEX('i.',@WHERE) > 0
			SET @FROM = @FROM + ' INNER JOIN cvIndustryPublish i WITH(NOLOCK) ON a.ID=i.cvMainID'
		IF LEN(@KeyWord) > 0 AND @MajorName IS NULL
			SET @FROM = @FROM + ' INNER JOIN #FullText k WITH(NOLOCK) ON a.ID=k.cvID'
		SET @SQL = @SQL + @FROM + @WHERE
		IF @SortType = 1
			SET @SQL = @SQL + '
				ORDER BY j.LastLoginDate DESC, a.ID'
		ELSE
			SET @SQL = @SQL + '
				ORDER BY a.RefreshDate DESC, a.ID'
		--PRINT @SQL
		----把符合条件的职位全部列出
		UPDATE SearchDB..cpSearchCondition SET Sql = REPLACE(@SQL, 'INSERT INTO #Cv', ''), StartDate = GETDATE() WHERE ID = @cpSearchConditionID
		EXEC(@SQL)
		----记录查询结果总数
		DECLARE @ValidCvNumber INT
		SET @ValidCvNumber = @@ROWCOUNT		
		UPDATE SearchDB..cpSearchCondition SET ValidCvNumber = @ValidCvNumber WHERE ID = @cpSearchConditionID
		--记录查询时间
		UPDATE SearchDB..cpSearchCondition SET EndDate = GETDATE() WHERE ID = @cpSearchConditionID

		INSERT INTO SearchDB..cpSearchCvID
		SELECT TOP 2000 @cpSearchConditionID, ID FROM #Cv WITH(NOLOCK)

		DROP TABLE #Cv
		DROP TABLE #FullText
		GOTO GetRecordSet
	END

GetRecordSet:
	BEGIN
		DECLARE @PageSize AS TINYINT
		SET @PageSize = 20		--每页的行数

		----返回查询数量
		UPDATE SearchDB..cpSearchCondition SET ReuseNumber = ReuseNumber + 1 WHERE ID=@cpSearchConditionID
		SELECT ValidCvNumber FROM SearchDB..cpSearchCondition WITH(NOLOCK) WHERE ID=@cpSearchConditionID
		----返回20行查询结果
		IF @PageNumber > 0
		BEGIN
			DECLARE @T_CvList AS TABLE(
				ID INT,
				cvEducationID INT,
				dcMajorID INT,
				Degree TINYINT,
				RelatedWorkYears INT,
				dcSalaryID TINYINT,
				Speciality VARCHAR(MAX) COLLATE Chinese_PRC_CI_AS,
				RefreshDate SMALLDATETIME,
				LastLoginDate SMALLDATETIME,
				JobName VARCHAR(100) COLLATE Chinese_PRC_CI_AS,
				Gender BIT,
				BirthDay INT,
				LivePlace INT,
				Attachment VARCHAR(50) COLLATE Chinese_PRC_CI_AS,
				HasPhoto TINYINT,
				College NVARCHAR(50),
				EduType TINYINT,
				MajorName NVARCHAR(20),
				Graduation INT,
				HasViewed BIT,
				ViewDate SMALLDATETIME,
				HasRemarked BIT,
				LastJobTypeID INT,
				Valid TINYINT
			)

			SELECT @MinId = MIN(ID)FROM SearchDB..cpSearchCvID WITH(NOLOCK) WHERE cpSearchConditionID=@cpSearchConditionID
			SET @MinId = @MinId+(@PageNumber-1)*@PageSize

			INSERT INTO @T_CvList(ID,dcMajorID,Degree,RelatedWorkYears,dcSalaryID,Speciality,RefreshDate,LastLoginDate,
				JobName,Gender,BirthDay,LivePlace,LastJobTypeID,Attachment,HasPhoto,HasViewed,HasRemarked,Valid)

			SELECT top 20 a.ID,a.dcMajorID,a.Degree,a.RelatedWorkYears,a.dcSalaryID,ISNULL(a.Speciality,a.SpecialityEng) Speciality,a.RefreshDate,
				j.LastLoginDate,ISNULL(a.JobName, '应届毕业生') JobName,j.Gender,j.BirthDay,j.LivePlace,a.LastJobTypeID,
				a.Attachment,j.HasPhoto,0,0,a.Valid FROM cvMainPublish a WITH(NOLOCK) 
				INNER JOIN paMainPublish j WITH(NOLOCK) ON a.paMainID=j.ID 
                INNER JOIN SearchDB..cpSearchCvID b ON a.id=b.CvID
				WHERE b.cpSearchConditionID=@cpSearchConditionID AND b.ID>=@MinId 
                ORDER BY b.ID,a.ID DESC
            --RICHARD 2011-7-23 16:51分修改

			UPDATE a SET a.cvEducationID = (
						SELECT TOP 1 ID FROM cvEducationPublish WITH(NOLOCK)
						WHERE cvEducationPublish.cvMainID = a.ID
						AND a.Degree = cvEducationPublish.Degree
						ORDER BY Graduation DESC)
			FROM @T_CvList a

			UPDATE a SET a.College = ISNULL(b.GraduateCollage,b.GraduateCollageEng), a.EduType = b.EduType, 
				a.MajorName = ISNULL(b.MajorName,b.MajorNameEng), a.Graduation = b.Graduation
			FROM @T_CvList a, cvEducationPublish b WITH(NOLOCK)
			WHERE b.ID = a.cvEducationID

			UPDATE a SET a.HasViewed = 1, a.ViewDate = b.AddDate
			FROM @T_CvList a, caCvViewLog b WITH(NOLOCK)
			WHERE b.cvMainID = a.ID AND caMainID=@caMainID	
			
			UPDATE a SET a.HasRemarked = 1
			FROM @T_CvList a WHERE EXISTS(SELECT 'X' FROM caCvRemark WITH(NOLOCK) WHERE cvMainID = a.ID AND caMainID=@caMainID)

			SELECT * FROM @T_CvList
		END
		RETURN
	END
END TRY
BEGIN CATCH
	---检查是否已经建立临时表，已经建立则删除
	BEGIN TRY
		DROP TABLE #FullText
	END TRY
	BEGIN CATCH
	END CATCH
	BEGIN TRY
		DROP TABLE #cv
	END TRY
	BEGIN CATCH
	END CATCH
	PRINT '查询时出现错误，请联系技术人员检查，错误信息：'
	PRINT Error_Message()
	PRINT Error_Number()
	PRINT Error_Line()
END CATCH














GO
/****** Object:  StoredProcedure [dbo].[ccCvBySearchSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--Peter 2014-08-25修改
--添加首次搜索简历积分记录
--Carl 2018-02-08 修改 最低学历添加大专及以上
CREATE PROCEDURE [dbo].[ccCvBySearchSelect]
(
	@dcJobTypeID VARCHAR(50), 		--职位类别
	@dcRegionID VARCHAR(50), 		--求职地区
	@dcIndustryID VARCHAR(50), 		--现从事行业
	@IncludeOld BIT, 				--1包含曾从事职业
	@dcJobTypeIDExpect VARCHAR(50), --期望职位类别
	@dcIndustryIDExpect VARCHAR(50), --期望求职行业
	@dcSalaryID TINYINT, 			--月薪
	@IsNegotiable BIT, 				--1允许面议，不面议
	@MinExperience TINYINT, 		--工作经验
	@dcEducationID TINYINT, 			--最低学历
	@LanguageType SMALLINT, 			--语种
	@KeyWord NVARCHAR(20), 			--关键词
	@College NVARCHAR(50), 			--学校名称
	@Standard BIT, 					--是否统招
	@SubNodeNum INT, 				--下属人数
	@Major INT, 						--所学专业
	@Graduation INT, 				--毕业时间 year
	@Gender TINYINT, 				--性别, 2不限
	@MaxAge SMALLINT, 				--最大年龄
	@MinAge	SMALLINT, 				--最小年龄
	@LivePlace VARCHAR(50), 			--现居住地
	@AccountPlace INT, 				--户口所在地
	@MobilePlace VARCHAR(50), 		--Mobile住地
	@MinHeight TINYINT, 				--MinHeight
	@MaxHeight TINYINT, 				--MaxHeight
	@SortType TINYINT, 				--排序方式
	@CvMainID INT, 					--简历ID
	--@dcCareerStatus TINYINT,         --简历状态
	--sessionid，没有采用全部人员共享方式，因为10分钟内，搜索相同条件的可能性很大，	
	--而10分钟搜索的用户翻到第二页时内容可能会和第一页一样。这样让用户很难理解。
	--使用SessionID, 可以保证60分钟内查询结果一致。出现不一致的几率很小
	@SessionID INT, 
	@PageNumber INT, 				--翻页页码
	@IsExpand BIT, 					--是否扩大地区范围
	@caMainID INT, 					--企业用户ID，用来判断是否和建立联系
	@cvEmployType INT				--期望工作性质ID，用来限制期望工作性质选项
)
AS
--return
SET NOCOUNT ON
BEGIN TRY
	DECLARE @MajorName AS NVARCHAR(20), @KeyTemp NVARCHAR(20)
	IF @dcJobTypeID IS NULL
		SET @dcJobTypeID = ''
	SET @dcJobTypeID = dbo.FormatIDS(@dcJobTypeID)
	IF @dcJobTypeIDExpect IS NULL
		SET @dcJobTypeIDExpect = ''
	SET @dcJobTypeIDExpect = dbo.FormatIDS(@dcJobTypeIDExpect)
	IF @dcRegionID IS NULL
		SET @dcRegionID = ''
	SET @dcRegionID = dbo.FormatIDS(@dcRegionID)
	IF @dcIndustryID IS NULL
		Set @dcIndustryID = ''
	SET @dcIndustryID = dbo.FormatIDS(@dcIndustryID)
	IF @dcIndustryIDExpect IS NULL
		SET @dcIndustryIDExpect = ''
	SET @dcIndustryIDExpect = dbo.FormatIDS(@dcIndustryIDExpect)
	IF @dcSalaryID IS NULL
		SELECT @dcSalaryID = 0, @IsNegotiable = 0
	IF @IsNegotiable IS NULL
		SET @IsNegotiable = 0
	IF @MinExperience IS NULL
		SET @MinExperience = 99
	IF @dcEducationID IS NULL
		SET @dcEducationID = 0
	IF @LanguageType IS NULL
		SET @LanguageType = 0
	IF @College IS NULL
		SET @College = ''
	IF LEN(@College) < 2
		SET @College = ''
	IF @SortType IS NULL
		SET @SortType = 0
	WHILE @KeyWord LIKE '%  %'
		SET @KeyWord = REPLACE(@KeyWord, '  ', ' ')
	SET @KeyWord = LTRIM(RTRIM(dbo.SafeSQL(@KeyWord)))
	SET @KeyTemp = @KeyWord
	IF @KeyWord IS NULL OR LEN(@KeyWord) < 2
		SELECT @KeyWord = '', @KeyTemp = ''
	ELSE
	BEGIN
		IF LEFT(@KeyWord, 7) = 'major::'
		BEGIN
			SELECT @MajorName = REPLACE(@KeyWord, 'major::', '')
			SELECT @KeyWord = '', @KeyTemp = ''
		END
		ELSE
		BEGIN
			DECLARE @p INT
			SET @p = CHARINDEX('@@', @KeyWord)
			IF @p > 0
			BEGIN
				SELECT @MajorName = LTRIM(RTRIM(RIGHT(@KeyWord, LEN(@KeyWord) - @p - 1)))
				SELECT @KeyTemp = LEFT(@KeyWord, @p - 1)
				IF LEN(@KeyTemp) < 2
					SET @KeyTemp = ''
			END
		END
	END	
	SET @KeyTemp = REPLACE(@KeyTemp, ' ', ' near ')
	
	SET @College = LTRIM(RTRIM(dbo.SafeSQL(@College)))
	IF @SubNodeNum IS NULL
		SET @SubNodeNum = 0
	IF @MaxAge IS NULL OR @MaxAge = 0
		SET @MaxAge = 99
	IF @MinAge IS NULL OR @MinAge = 0
		SET @MinAge = 99
	IF @LivePlace IS NULL
		SET @LivePlace = ''
	SET @LivePlace = dbo.FormatIDS(@LivePlace)
	IF @MobilePlace IS NULL
		SET @MobilePlace = ''
	SET @MobilePlace = dbo.FormatIDS(@MobilePlace)
	IF @AccountPlace IS NULL
		SET @AccountPlace = 0
	IF @Gender IS NULL
		SET @Gender = 2
	IF @IncludeOld IS NULL
		SET @IncludeOld = 0
	IF @Major IS NULL
		SET @Major = 0
	IF @Graduation IS NULL
		SET @Graduation = 0
	ELSE IF @Graduation > DATEPART(YEAR, GETDATE()) + 1 OR @Graduation < DATEPART(YEAR, GETDATE()) -10
		SET @Graduation = 0
	IF @CvMainID IS NULL
		SET @CvMainID = 0
	IF @Standard IS NULL
		SET @Standard = 0
	IF @IsExpand IS NULL
		SET @IsExpand = 0
	SET @MinHeight = ISNULL(@MinHeight, 0)
	SET @MaxHeight = ISNULL(@MaxHeight, 250)
	IF @MinHeight < 140 OR @MinHeight > 200
		SET @MinHeight = 0
	IF @cvEmployType IS NULL
		SET @cvEmployType = 0

	IF @CvMainID = 0
	BEGIN
		----给null值变量赋默认值
		DECLARE @cpSearchConditionID AS INT, @MinId AS INT
		SELECT @cpSearchConditionID = 0
		IF @SessionID != -1
			SELECT @SessionId = 1
		
		--sqlserver中计划任务自动删除60分钟前的数据
		SELECT TOP 1 @cpSearchConditionID = ID FROM SearchDB..cpSearchCondition WITH(NOLOCK)
		WHERE SessionID=@SessionID AND dcJobTypeID=@dcJobTypeID AND dcJobTypeIDExpect=@dcJobTypeIDExpect
		AND dcRegionID=@dcRegionID AND dcIndustryID=@dcIndustryID AND dcIndustryIDExpect=@dcIndustryIDExpect
		AND IncludeOld=@IncludeOld AND dcSalaryID=@dcSalaryID AND IsNegotiable=@IsNegotiable 
		AND MinExperience=@MinExperience AND dcEducationID=@dcEducationID AND LanguageType=@LanguageType 
		AND KeyWord=@KeyWord AND College=@College AND Standard=@Standard AND SortType=@SortType
		AND SubNodeNum = @SubNodeNum AND Major = @Major AND Graduation = @Graduation AND Gender=@Gender AND MaxAge=@MaxAge
		AND MinAge=@MinAge AND LivePlace=@LivePlace AND AccountPlace=@AccountPlace AND MobilePlace=@MobilePlace 
		AND IsExpand=@IsExpand AND MinHeight = @MinHeight AND MaxHeight = @MaxHeight AND LogTime > DATEADD(M, -60, GETDATE())
		AND EmployType=@cvEmployType
		ORDER BY ID DESC

		IF ISNULL(@cpSearchConditionID, 0) = 0
			GOTO SelectReset	--无数据，重新搜索
		ELSE		
			GOTO GetRecordSet	--从临时结果中提取数据
	END
	ELSE
	BEGIN
		----如果有简历id，则直接显示，不再查询
		SELECT COUNT(1) FROM cvmainPublish WITH(NOLOCK) WHERE ID = @CvMainID AND Valid > 0
		DECLARE @T_Cv AS TABLE(
			ID INT, 
			dcMajorID INT, 
			Degree TINYINT, 
			RelatedWorkYears INT, 
			dcSalaryID TINYINT, 
			Speciality VARCHAR(MAX) COLLATE Chinese_PRC_CI_AS, 
			RefreshDate SMALLDATETIME, 
			LastLoginDate SMALLDATETIME, 
			JobName VARCHAR(100) COLLATE Chinese_PRC_CI_AS, 
			Gender BIT, 
			BirthDay INT, 
			LivePlace INT, 
			Attachment VARCHAR(50), 
			HasPhoto TINYINT, 
			College NVARCHAR(50), 
			EduType TINYINT, 
			MajorName NVARCHAR(20), 
			Graduation INT, 
			HasViewed BIT, 
			ViewDate SMALLDATETIME, 
			HasRemarked BIT, 
			LastJobTypeID INT, 
			Valid TINYINT, 
			IsOnline BIT, 
			HasWeiXin BIT,
			paMainId INT,
			SecondId VARCHAR(10)
		)

		INSERT INTO @T_Cv(ID, dcMajorID, Degree, RelatedWorkYears, dcSalaryID, Speciality, RefreshDate, LastLoginDate, 
			JobName, Gender, BirthDay, LivePlace, LastJobTypeID, Attachment, HasPhoto, HasViewed, HasRemarked, Valid, IsOnline, paMainId, secondId)
		SELECT a.ID, a.dcMajorID, a.Degree, a.RelatedWorkYears, a.dcSalaryID, ISNULL(a.Speciality, a.SpecialityEng) Speciality, a.RefreshDate, 
			j.LastLoginDate, ISNULL(a.JobName, '应届毕业生') JobName, j.Gender, j.BirthDay, j.LivePlace, a.LastJobTypeID, 
			a.Attachment, j.HasPhoto, 0, 0, a.Valid, dbo.GetPaOnlineStatus(j.ID), a.paMainId, a.secondId
		FROM cvmainPublish a WITH(NOLOCK) 
		INNER JOIN paMainPublish j WITH(NOLOCK) ON a.paMainID = j.ID
		WHERE a.ID = @CvMainID AND a.Valid > 0

		UPDATE a SET a.College = ISNULL(b.GraduateCollage, b.GraduateCollageEng), a.EduType = b.EduType, 
			a.MajorName = ISNULL(b.MajorName, b.MajorNameEng), a.Graduation = b.Graduation 
		FROM @T_Cv a, cvEducationPublish b WITH(NOLOCK) 
		WHERE b.cvMainID = a.ID
		AND b.Degree = a.Degree

		UPDATE a SET a.HasViewed = 1, a.ViewDate = (SELECT AddDate FROM caCvViewLog WITH(NOLOCK) WHERE cvMainID = a.ID AND caMainID=@caMainID)
		FROM @T_Cv a 
		WHERE EXISTS(SELECT 'X' FROM caCvViewLog WITH(NOLOCK) WHERE cvMainID = a.ID AND caMainID=@caMainID)

		--修改是否绑定微信
		UPDATE a SET HasWeiXin = 1
		FROM @T_Cv a, WxFans b WITH(NOLOCK)
		WHERE a.PaMainID = b.PaMainID
		AND b.Status = 2

		SELECT a.*,b.Description DegreeName,c.Description LivePlaceName, dbo.BirthToAge(a.BirthDay) Age,d.Description dcSalaryName
		FROM @T_Cv a
		LEFT JOIN dcEducation b WITH(NOLOCK) ON b.ID = a.Degree
		LEFT JOIN dcRegion c WITH(NOLOCK) ON c.ID = a.LivePlace
		LEFT JOIN dcSalary d WITH(NOLOCK) ON d.ID = a.dcSalaryID

		RETURN
	END

SelectReset:				--从cv中搜索数据
	BEGIN
		DECLARE @SQL AS VARCHAR(8000)
		DECLARE @WHERE AS VARCHAR(8000)
		DECLARE @FROM AS VARCHAR(1000)
		----记录查询条件
		INSERT INTO SearchDB..cpSearchCondition(SessionID, dcJobTypeID, dcJobTypeIDExpect, dcRegionID, dcIndustryID, 
			dcIndustryIDExpect, IncludeOld, dcSalaryID, IsNegotiable, SortType, 
			MinExperience, dcEducationID, LanguageType, KeyWord, College, Standard, SubNodeNum, 
			Major, Graduation, Gender, MaxAge, MinAge, LivePlace, AccountPlace, MobilePlace, IsExpand, MinHeight, MaxHeight, ReuseNumber, EmployType)
		VALUES(@SessionID, @dcJobTypeID, @dcJobTypeIDExpect, @dcRegionID, @dcIndustryID, 
			@dcIndustryIDExpect, @IncludeOld, @dcSalaryID, @IsNegotiable, @SortType, 
			@MinExperience, @dcEducationID, @LanguageType, @KeyWord, @College, @Standard, @SubNodeNum, 
			@Major, @Graduation, @Gender, @MaxAge, @MinAge, @LivePlace, @AccountPlace, @MobilePlace, @IsExpand, @MinHeight, @MaxHeight, 0, @cvEmployType)
		SET @cpSearchConditionID = @@IDENTITY

		------生成职位类别的表变量，因为职位类别有包含（父子）关系
		DECLARE @T_JobPlace AS TABLE(ID INT)
		DECLARE @T_JobType AS TABLE(ID INT)
		DECLARE @tmpMobilePlace AS VARCHAR(2000),
			@JobType AS VARCHAR(3000), @JobTypeExpect AS VARCHAR(3000),
			@JobPlace AS VARCHAR(2000), @tmpLivePlace AS VARCHAR(2000)

		SELECT @JobPlace = '', @tmpLivePlace = '', @tmpMobilePlace = '', @JobType='', @JobTypeExpect = '', @WHERE = ' WHERE a.Valid > 0'

		----生成工作地点的表变量
		IF LEN(@dcRegionID) > 0
		BEGIN
			INSERT INTO @T_JobPlace
			SELECT * FROM dbo.fnSplit(@dcRegionID, ',')
			SELECT @JobPlace = (@JobPlace + ' OR h.dcRegionID Like ''' + LTRIM(STR(ID) + '%''')) FROM @T_JobPlace
			IF @IsExpand = 1
			BEGIN
				SELECT @JobPlace = (@JobPlace + ' OR h.dcRegionID = ''' + LTRIM(STR(LEFT(ID, 2)))+'''' )
				FROM @T_JobPlace WHERE LEN(ID) > 2
				SELECT @JobPlace = (@JobPlace + ' OR h.dcRegionID = ''' + LTRIM(STR(LEFT(ID, 4)))+'''' )
				FROM @T_JobPlace WHERE LEN(ID) > 4
			END
			IF LEN(@JobPlace) > 0
				SET @JobPlace = RIGHT(@JobPlace, LEN(@JobPlace) -4)
		END

		IF LEN(@LivePlace) > 0
		BEGIN
			DELETE FROM @T_JobPlace
			INSERT INTO @T_JobPlace
			SELECT * FROM dbo.fnSplit(@LivePlace, ',')
			SELECT @tmpLivePlace = (@tmpLivePlace + ' OR j.LivePlace Like ''' + LTRIM(STR(ID) + '%''')) FROM @T_JobPlace
			IF LEN(@tmpLivePlace) > 0
				SET @tmpLivePlace = RIGHT(@tmpLivePlace, LEN(@tmpLivePlace) -4)
		END
		IF LEN(@MobilePlace) > 0
		BEGIN
			DELETE FROM @T_JobPlace
			INSERT INTO @T_JobPlace
			SELECT * FROM dbo.fnSplit(@MobilePlace, ',')
			SELECT @tmpMobilePlace = (@tmpMobilePlace + ' OR j.MobileRegion Like ''' + LTRIM(STR(ID) + '%''')) FROM @T_JobPlace
			IF LEN(@tmpMobilePlace) > 0
				SET @tmpMobilePlace = RIGHT(@tmpMobilePlace, LEN(@tmpMobilePlace) -4)
		END

		----生成求聘职位的表变量
		IF LEN(@dcJobTypeID) > 0
		BEGIN
			DECLARE @T_Temp AS TABLE(ID INT)		--临时表，用于构建组合查询语句
			INSERT INTO @T_Temp
			SELECT * FROM dbo.fnSplit(@dcJobTypeID, ',')

			INSERT INTO @T_JobType
			SELECT DISTINCT ID FROM dcJobType WITH(NOLOCK)
			WHERE ParentId IN(SELECT ID FROM @T_TEMP) 
			OR ParentId2 in(SELECT ID FROM @T_TEMP)
			OR ID IN(SELECT ID FROM @T_TEMP)
			----生成in字符串
			SELECT @JobType = (@JobType + LTRIM(STR(ID) + ',')) FROM @T_JobType
			IF RIGHT(@JobType, 1) = ', '
				SET @JobType = LEFT(@JobType, LEN(@JobType) - 1)
		END

		IF LEN(@dcJobTypeIDExpect) > 0
		BEGIN
			DECLARE @T_Temp1 AS TABLE(ID INT)		--临时表，用于构建组合查询语句
			INSERT INTO @T_Temp1
			SELECT * FROM dbo.fnSplit(@dcJobTypeIDExpect, ',')
			DELETE FROM @T_JobType
			INSERT INTO @T_JobType
			SELECT DISTINCT ID FROM dcJobType WITH(NOLOCK)
			WHERE ParentId IN(SELECT ID FROM @T_TEMP1) 
			OR ParentId2 in(SELECT ID FROM @T_TEMP1)
			OR ID IN(SELECT ID FROM @T_TEMP1)
			----生成in字符串
			SELECT @JobTypeExpect = (@JobTypeExpect + LTRIM(STR(ID) + ',')) FROM @T_JobType
			IF RIGHT(@JobTypeExpect, 1) = ', '
				SET @JobTypeExpect = LEFT(@JobTypeExpect, LEN(@JobTypeExpect) - 1)

		END
		----建立关键字搜索的临时表
		CREATE TABLE #FullText(
			CvID INT NOT NULL,
			Rank INT
		)
		----建立临时表
		CREATE TABLE #Cv(
			ID INT NOT NULL, 
			RefreshDate SMALLDATETIME NOT NULL,
			RANK INT
		)
		----生成插入临时表的Sql语句
		SET @SQL = '
			INSERT INTO #Cv
			SELECT DISTINCT TOP 2000 a.ID, j.LastLoginDate'

		IF LEN(@KeyTemp) > 0
			SET @Sql = @Sql + ', k.Rank'
		ELSE
			SET @Sql = @Sql + ', 1'		
		SET @FROM = '
			FROM cvmainPublish a WITH(NOLOCK) INNER JOIN paMainPublish j WITH(NOLOCK) ON a.paMainID = j.ID'

		----工作经验的职位类别
		IF LEN(@dcJobTypeID) > 0
		BEGIN
			IF @IncludeOld = 0  ----最近从事和曾从事职位
				SET @WHERE = @WHERE + '
					AND (a.LastJobTypeID IN(' + @JobType +'))'
			ELSE
				SET @WHERE = @WHERE + '
					AND (c.dcJobTypeID IN(' + @JobType +'))'
		END

		----期望职位类别
		IF LEN(@dcJobTypeIDExpect) > 0
		BEGIN
			SET @WHERE = @WHERE + '
				AND (g.dcJobTypeID IN(' + @JobTypeExpect +'))'

		END

		----工作地点
		IF LEN(@JobPlace) > 0 
			SET @WHERE = @WHERE + '
				AND (' + @JobPlace + ')'

		----现从事行业
		IF LEN(@dcIndustryID) > 0
			SET @WHERE = @WHERE + '
				AND (a.LastIndustryID IN(' + @dcIndustryID + '))'

		----期望行业
		IF LEN(@dcIndustryIDExpect) > 0
		BEGIN
			SET @WHERE = @WHERE + '
				AND (i.dcIndustryID IN(' + @dcIndustryIDExpect + '))'
		END

		----下属人数
		IF @SubNodeNum > 0
		BEGIN
			SET @WHERE = @WHERE + '
				AND a.SubNodeNum = ' + LTRIM(STR(@SubNodeNum))
		END
		----当前所在地
		IF LEN(@tmpLivePlace) > 0
		BEGIN
			SET @WHERE = @WHERE + '
				AND (' + @tmpLivePlace + ')'
		END
		IF @SessionId = -1
		BEGIN
			SET @WHERE = @WHERE + '
				AND j.Id IN(SELECT paMainId FROM paOnline)'
		END

		----Mobile所在地
		IF LEN(@tmpMobilePlace) > 0
		BEGIN
			SET @WHERE = @WHERE + '
				AND (' + @tmpMobilePlace + ')'
		END

		----户口所在地
		IF @AccountPlace > 0
		BEGIN
			SET @WHERE = @WHERE + '
				AND j.AccountPlace LIKE ''' + LTRIM(STR(@AccountPlace)) + '%'''
		END

		----专业
		IF @Major > 0
		BEGIN
			SET @WHERE = @WHERE + '
				AND b.dcMajorID = ' + LTRIM(STR(@Major))
		END

		--Graduation
		IF @Graduation = DATEPART(YEAR, GETDATE()) + 1
		BEGIN
			SET @WHERE = @WHERE + '
				AND b.Graduation > ' + LTRIM(STR(@Graduation)) + '00'
		END
		ELSE IF @Graduation > DATEPART(YEAR, GETDATE()) - 10
		BEGIN
			SET @WHERE = @WHERE + '
				AND b.Graduation BETWEEN ' + LTRIM(STR(@Graduation)) + '00 AND ' + LTRIM(STR(@Graduation)) + '99'
		END
		ELSE IF @Graduation = DATEPART(YEAR, GETDATE()) - 10
		BEGIN
			SET @WHERE = @WHERE + '
				AND b.Graduation < ' + LTRIM(STR(@Graduation)) + '99'
		END
	
		----性别
		IF @Gender < 2
		BEGIN
			SET @WHERE = @WHERE + '
				AND j.Gender = ' + LTRIM(STR(@Gender))
		END

		----年龄
		IF @MinAge < 99
		BEGIN
			SET @WHERE = @WHERE + '
				AND j.BirthDay <= ' + LTRIM(STR(dbo.AgeToBirth(@MinAge)))
		END
		IF @MaxAge < 99
		BEGIN
			SET @MaxAge = @MaxAge + 1
			SET @WHERE = @WHERE + '
				AND j.BirthDay > ' + LTRIM(STR(dbo.AgeToBirth(@MaxAge)))
		END
		IF @MinHeight > 139
		BEGIN
			SET @WHERE = @WHERE + '
				AND j.Height >= ' + LTRIM(STR(@MinHeight))
		END
		IF @MaxHeight < 231
		BEGIN
			SET @WHERE = @WHERE + '
				AND j.Height <= ' + LTRIM(STR(@MaxHeight))
		END

		----薪水
		IF @dcSalaryID > 0
		BEGIN
			SET @WHERE = @WHERE + '
			AND((
				a.dcSalaryID >= ' + LTRIM(STR(@dcSalaryID-1)) + '
				AND a.dcSalaryID <= ' + LTRIM(STR(@dcSalaryID+1)) + '
				)'
			IF @IsNegotiable = 1		--包括面议
				SET @WHERE = @WHERE + '
				OR a.IsNegotiable = 1'
			SET @WHERE = @WHERE + ')'
		END

		----工作经验要求
		IF @MinExperience < 99
		BEGIN
			IF @MinExperience = 4
				SET @WHERE = @WHERE + ' 
				AND a.RelatedWorkYears = 11'
			ELSE IF @MinExperience = 1
				SET @WHERE = @WHERE + ' 
				AND a.RelatedWorkYears >= 1 AND a.RelatedWorkYears <= 2'
			ELSE IF @MinExperience = 2
				SET @WHERE = @WHERE + '
				AND a.RelatedWorkYears >= 3 AND a.RelatedWorkYears <= 5'
			ELSE IF @MinExperience = 3
				SET @WHERE = @WHERE + ' 
				AND a.RelatedWorkYears >= 6 AND a.RelatedWorkYears <= 10'
			ELSE IF @MinExperience = 5
				SET @WHERE = @WHERE + ' 
				AND a.RelatedWorkYears >= 2 AND a.RelatedWorkYears <= 3'
			ELSE
				SET @WHERE = @WHERE + ' 
				AND a.RelatedWorkYears = 0'
		END

		----学历要求
		IF @dcEducationID > 0
		BEGIN
			IF @dcEducationID = 1
				SET @WHERE = @WHERE + ' AND a.Degree IN(1, 2, 3, 4) '
			ELSE IF @dcEducationID = 2
				SET @WHERE = @WHERE + ' AND a.Degree <= 5 '
			ELSE IF @dcEducationID = 3
			SET @WHERE = @WHERE + ' AND a.Degree = 5 '
			ELSE IF @dcEducationID = 4
				SET @WHERE = @WHERE + ' AND a.Degree IN(5, 6) '
			ELSE IF @dcEducationID = 5
				SET @WHERE = @WHERE + ' AND a.Degree = 6 '
			ELSE IF @dcEducationID = 6
				SET @WHERE = @WHERE + ' AND a.Degree >= 6 '
			ELSE IF @dcEducationID = 7
				SET @WHERE = @WHERE + ' AND a.Degree = 7 '
			ELSE IF @dcEducationID = 8
				SET @WHERE = @WHERE + ' AND a.Degree = 8 '
			ELSE IF @dcEducationID = 9
				SET @WHERE = @WHERE + ' AND a.Degree IN(5, 6, 7, 8) '

			IF @Major > 0 OR LEN(@College) > 0 OR @Standard = 1 OR @MajorName > ''
				SET @WHERE = @WHERE + '
				AND b.Degree = a.Degree'
			IF @Standard = 1
				SET @WHERE = @WHERE + '
				AND b.EduType=1'
		END

		----语种
		IF @LanguageType > 0
			SET @WHERE = @WHERE + '
				AND d.LanguageType = ' + LTRIM(STR(@LanguageType))

		----关键词
		IF LEN(@KeyTemp) > 0 --AND @MajorName IS NULL
		BEGIN
			DECLARE @S DATETIME, @SqlFt VARCHAR(MAX)
			SELECT @S = GETDATE()

			--INSERT INTO #FullText
			--SELECT cvMainID, 9999 FROM cvinfo WHERE JobName LIKE '%' + @KeyTemp + '%'

			INSERT INTO #FullText
			SELECT [Key], 100000 + [Rank] FROM CONTAINSTABLE(cvinfo, *, @KeyTemp, 100000) AS KeyCv 
			ORDER BY RANK DESC

			INSERT INTO #FullText
			SELECT [Key], [Rank] FROM FREETEXTTABLE(cvinfo, *, @KeyTemp, 100000) AS KeyCv 
			WHERE [Key] NOT IN(SELECT cvId FROM #FullText)
			ORDER BY RANK DESC

            --Richard 2011.8.24增加
			SELECT @SqlFt = 'SELECT [key] FROM FREETEXTTABLE(cvinfo, *, ''' + @KeyTemp + ''', 100000) AS KeyCv  ORDER BY RANK DESC 开始：' + convert(varchar(8), @S, 8) + '  结束：' + convert(varchar(8), getdate(), 8)
			UPDATE SearchDB..cpSearchCondition SET SqlFT = @SqlFt WHERE ID = @cpSearchConditionID
		END

		----学校名称
		IF LEN(@College) > 0
			IF CHARINDEX(' ', @College)= 0
				SET @WHERE = @WHERE + '
					AND b.GraduateCollage LIKE ''%' + LTRIM((@College)) + '%'''
			ELSE
			BEGIN
				WHILE CHARINDEX('  ', @College)> 0
					SET @College = REPLACE(@College, '  ', ' ')

				SET @WHERE = @WHERE + '
					AND (b.GraduateCollage LIKE ''%' + REPLACE(@College, ' ', '%'' OR b.GraduateCollage LIKE ''%') + '%'')'
			END
		IF LEN(@MajorName) > 0
			IF CHARINDEX(' ', @MajorName)= 0
				SET @WHERE = @WHERE + '
					AND b.MajorName LIKE ''%' + @MajorName + '%'''
			ELSE
			BEGIN
				WHILE CHARINDEX('  ', @MajorName)> 0
					SET @MajorName = REPLACE(@MajorName, '  ', ' ')

				SET @WHERE = @WHERE + '
					AND (b.MajorName LIKE ''%' + REPLACE(@MajorName, ' ', '%'' OR b.MajorName LIKE ''%') + '%'')'
			END

		--工作性质
		IF @cvEmployType IN(2, 4)
			SET @WHERE = @WHERE + '
				AND a.EmployType = ' + LTRIM(STR(@cvEmployType))
		ELSE IF @cvEmployType = 1
			SET @WHERE = @WHERE + '
				AND a.EmployType IN (1, 2) '
		ELSE IF @cvEmployType = 3
			SET @WHERE = @WHERE + '
				AND a.EmployType IN (3, 2) '

		DECLARE @Order AS VARCHAR(50)
		SET @Order = ' ORDER BY j.LastLoginDate DESC, a.ID'
		IF CHARINDEX('b.', @WHERE) > 0
			SET @FROM = @FROM + ' INNER JOIN cvEducationPublish b WITH(NOLOCK) ON a.ID=b.cvMainID'
		IF CHARINDEX('c.', @WHERE) > 0
			SET @FROM = @FROM + ' INNER JOIN CvExperiencePublish c WITH(NOLOCK) ON a.ID=c.cvMainID'
		IF CHARINDEX('d.', @WHERE) > 0
			SET @FROM = @FROM + ' INNER JOIN cvLanguagePublish d WITH(NOLOCK) ON a.ID=d.cvMainID'
		IF CHARINDEX('e.', @WHERE) > 0
			SET @FROM = @FROM + ' INNER JOIN cvTrainingPublish e WITH(NOLOCK) ON a.ID=e.cvMainID'
		IF CHARINDEX('f.', @WHERE) > 0
			SET @FROM = @FROM + ' INNER JOIN cvProjectPublish f WITH(NOLOCK) ON a.ID=f.cvMainID'
		IF CHARINDEX('g.', @WHERE) > 0
			SET @FROM = @FROM + ' INNER JOIN cvJobTypePublish g WITH(NOLOCK) ON a.ID=g.cvMainID'
		IF CHARINDEX('h.', @WHERE) > 0
			SET @FROM = @FROM + ' INNER JOIN cvJobPlacePublish h WITH(NOLOCK) ON a.ID=h.cvMainID'
		IF CHARINDEX('i.', @WHERE) > 0
			SET @FROM = @FROM + ' INNER JOIN cvIndustryPublish i WITH(NOLOCK) ON a.ID=i.cvMainID'
		IF LEN(@KeyTemp) > 0 --AND @MajorName IS NULL
			SELECT @FROM = @FROM + ' INNER JOIN #FullText k WITH(NOLOCK) ON a.ID=k.cvID',
				@Order = ' ORDER BY j.LastLoginDate DESC, a.ID',
				@Where = @Where + ' AND j.LastLoginDate > DATEADD(MONTH, -3, GETDATE())'
				--@Order = ' ORDER BY k.Rank DESC, j.LastLoginDate DESC, a.ID'
		SET @SQL = @SQL + @FROM + @WHERE + @Order

		--PRINT @SQL
		----把符合条件的职位全部列出
		UPDATE SearchDB..cpSearchCondition SET Sql = REPLACE(@SQL, 'INSERT INTO #Cv', ''), StartDate = GETDATE() WHERE ID = @cpSearchConditionID
		EXEC(@SQL)

		----记录查询结果总数
		DECLARE @ValidCvNumber INT
		SET @ValidCvNumber = @@ROWCOUNT		
		UPDATE SearchDB..cpSearchCondition SET ValidCvNumber = @ValidCvNumber WHERE ID = @cpSearchConditionID

		IF (SELECT COUNT(*) FROM #FullText) > 100
			INSERT INTO SearchDB..cpSearchCvID
			SELECT TOP 2000 @cpSearchConditionID, ID 
			FROM #Cv WITH(NOLOCK)
			Order BY DATEADD(MINUTE, Rank, RefreshDate) DESC
		ELSE
			INSERT INTO SearchDB..cpSearchCvID
			SELECT TOP 2000 @cpSearchConditionID, ID 
			FROM #Cv WITH(NOLOCK)
			Order BY RefreshDate DESC

		DROP TABLE #Cv
		DROP TABLE #FullText
		GOTO GetRecordSet
	END

GetRecordSet:
	BEGIN
		DECLARE @PageSize AS TINYINT
		SET @PageSize = 20		--每页的行数

		----返回查询数量
		UPDATE SearchDB..cpSearchCondition SET ReuseNumber = ReuseNumber + 1 WHERE ID=@cpSearchConditionID
		SELECT ValidCvNumber FROM SearchDB..cpSearchCondition WITH(NOLOCK) WHERE ID=@cpSearchConditionID

		----返回20行查询结果
		IF @PageNumber > 0
		BEGIN
			DECLARE @T_CvList AS TABLE(
				ID INT, 
				cvEducationID INT, 
				dcMajorID INT, 
				Degree TINYINT, 
				RelatedWorkYears INT, 
				dcSalaryID TINYINT, 
				Speciality VARCHAR(MAX) COLLATE Chinese_PRC_CI_AS, 
				RefreshDate SMALLDATETIME, 
				LastLoginDate SMALLDATETIME, 
				JobName VARCHAR(100) COLLATE Chinese_PRC_CI_AS, 
				Gender BIT, 
				BirthDay INT, 
				LivePlace INT, 
				Attachment VARCHAR(50) COLLATE Chinese_PRC_CI_AS, 
				HasPhoto TINYINT, 
				College NVARCHAR(50), 
				EduType TINYINT, 
				MajorName NVARCHAR(20), 
				Graduation INT, 
				HasViewed BIT, 
				ViewDate SMALLDATETIME, 
				HasRemarked BIT, 
				LastJobTypeID INT, 
				Valid TINYINT, 
				IsOnline BIT, 
				HasWeiXin BIT, 
				paMainId int, 
				SecondId VARCHAR(10),
				Seq INT IDENTITY(1, 1)
			)

			SELECT @MinId = MIN(ID) FROM SearchDB..cpSearchCvID WITH(NOLOCK) WHERE cpSearchConditionID=@cpSearchConditionID
			SET @MinId = @MinId+(@PageNumber-1)*@PageSize

			INSERT INTO @T_CvList(ID, dcMajorID, Degree, RelatedWorkYears, dcSalaryID, Speciality, RefreshDate, LastLoginDate, 
				JobName, Gender, BirthDay, LivePlace, LastJobTypeID, Attachment, HasPhoto, HasViewed, HasRemarked, Valid, IsOnline, paMainId, SecondId)

			SELECT TOP 20 a.ID, a.dcMajorID, a.Degree, a.RelatedWorkYears, a.dcSalaryID, ISNULL(a.Speciality, a.SpecialityEng) Speciality, a.RefreshDate, 
				j.LastLoginDate, ISNULL(a.JobName, '应届毕业生') JobName, j.Gender, j.BirthDay, j.LivePlace, a.LastJobTypeID, 
				a.Attachment, j.HasPhoto, 0, 0, a.Valid, dbo.GetPaOnlineStatus(j.ID), a.paMainId, a.SecondId
			FROM cvmainPublish a WITH(NOLOCK) 
			INNER JOIN paMainPublish j WITH(NOLOCK) ON a.paMainID=j.ID 
            INNER JOIN SearchDB..cpSearchCvID b ON a.id=b.CvID
			WHERE b.cpSearchConditionID=@cpSearchConditionID AND b.ID>=@MinId 
            ORDER BY b.ID, a.ID DESC

            --RICHARD 2011-7-23 16:51分修改
			UPDATE a SET a.cvEducationID = (
				SELECT TOP 1 ID FROM cvEducationPublish WITH(NOLOCK)
				WHERE cvEducationPublish.cvMainID = a.ID
				AND a.Degree = cvEducationPublish.Degree
				ORDER BY Graduation DESC)
			FROM @T_CvList a

			UPDATE a SET a.College = ISNULL(b.GraduateCollage, b.GraduateCollageEng), a.EduType = b.EduType, 
				a.MajorName = ISNULL(b.MajorName, b.MajorNameEng), a.Graduation = b.Graduation
			FROM @T_CvList a, cvEducationPublish b WITH(NOLOCK)
			WHERE b.ID = a.cvEducationID

			--修改是否绑定微信
			UPDATE a SET HasWeiXin = 1
			FROM @T_CvList a, WxFans b WITH(NOLOCK), CvMainPublish c WITH(NOLOCK)
			WHERE a.ID = c.ID
			AND c.PaMainID = b.PaMainID
			AND b.Status = 2

			UPDATE a SET a.HasViewed = 1, a.ViewDate = b.AddDate
			FROM @T_CvList a, caCvViewLog b WITH(NOLOCK)
			WHERE b.cvMainID = a.ID AND caMainID=@caMainID	
			
			SELECT a.*, b.Description DegreeName,c.Description LivePlaceName, dbo.BirthToAge(a.BirthDay) Age,d.Description dcSalaryName
			FROM @T_CvList a
			LEFT JOIN dcEducation b WITH(NOLOCK) ON b.ID = a.Degree
			LEFT JOIN dcRegion c WITH(NOLOCK) ON c.ID = a.LivePlace
			LEFT JOIN dcSalary d WITH(NOLOCK) ON d.ID = a.dcSalaryID
			ORDER BY a.Seq
		END

		--记录查询时间
		UPDATE SearchDB..cpSearchCondition SET EndDate = GETDATE() WHERE ID = @cpSearchConditionID

		RETURN
	END
END TRY
BEGIN CATCH
	---检查是否已经建立临时表，已经建立则删除
	BEGIN TRY
		DROP TABLE #FullText
	END TRY
	BEGIN CATCH
	END CATCH
	BEGIN TRY
		DROP TABLE #cv
	END TRY
	BEGIN CATCH
	END CATCH
	PRINT '查询时出现错误，请联系技术人员检查，错误信息：'
	PRINT Error_Message()
	PRINT Error_Number()
	PRINT Error_Line()
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[ccCvBySearchSelectTest]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ccCvBySearchSelectTest]
(
	@dcJobTypeID VARCHAR(50),		--职位类别
	@dcRegionID VARCHAR(50),		--求职地区
	@dcIndustryID VARCHAR(50),		--现从事行业
	@IncludeOld BIT,				--1包含曾从事职业
	@dcJobTypeIDExpect VARCHAR(50),--期望职位类别
	@dcIndustryIDExpect VARCHAR(50),--期望求职行业
	@dcSalaryID TINYINT,			--月薪
	@IsNegotiable BIT,				--1允许面议，不面议
	@MinExperience TINYINT,		--工作经验
	@dcEducationID TINYINT,			--最低学历
	@LanguageType SMALLINT,			--语种
	@KeyWord NVARCHAR(20),			--关键词
	@College NVARCHAR(50),			--学校名称
	@Standard BIT,					--是否统招
	@SubNodeNum INT,				--下属人数
	@Major INT,						--所学专业
	@Graduation INT,				--毕业时间 year
	@Gender TINYINT,				--性别,2不限
	@MaxAge SMALLINT,				--最大年龄
	@MinAge	SMALLINT,				--最小年龄
	@LivePlace VARCHAR(50),			--现居住地
	@AccountPlace INT,				--户口所在地
	@MobilePlace VARCHAR(50),		--Mobile住地
	@MinHeight TINYINT,				--MinHeight
	@MaxHeight TINYINT,				--MaxHeight
	@SortType TINYINT,				--排序方式
	@CvMainID INT,					--简历ID
	--@dcCareerStatus TINYINT,         --简历状态
	--sessionid，没有采用全部人员共享方式，因为10分钟内，搜索相同条件的可能性很大，	
	--而10分钟搜索的用户翻到第二页时内容可能会和第一页一样。这样让用户很难理解。
	--使用SessionID,可以保证60分钟内查询结果一致。出现不一致的几率很小
	@SessionID INT,
	@PageNumber INT,				--翻页页码
	@IsExpand BIT,					--是否扩大地区范围
	@caMainID INT,					--企业用户ID，用来判断是否和建立联系
	@cvEmployType INT				--期望工作性质ID，用来限制期望工作性质选项
)
AS
--return
SET NOCOUNT ON
BEGIN TRY
	DECLARE @MajorName AS NVARCHAR(20), @KeyTemp NVARCHAR(20)
	IF @dcJobTypeID IS NULL
		SET @dcJobTypeID = ''
	SET @dcJobTypeID = dbo.FormatIDS(@dcJobTypeID)
	IF @dcJobTypeIDExpect IS NULL
		SET @dcJobTypeIDExpect = ''
	SET @dcJobTypeIDExpect = dbo.FormatIDS(@dcJobTypeIDExpect)
	IF @dcRegionID IS NULL
		SET @dcRegionID = ''
	SET @dcRegionID = dbo.FormatIDS(@dcRegionID)
	IF @dcIndustryID IS NULL
		Set @dcIndustryID = ''
	SET @dcIndustryID = dbo.FormatIDS(@dcIndustryID)
	IF @dcIndustryIDExpect IS NULL
		SET @dcIndustryIDExpect = ''
	SET @dcIndustryIDExpect = dbo.FormatIDS(@dcIndustryIDExpect)
	IF @dcSalaryID IS NULL
		SET @dcSalaryID = 0
	IF @IsNegotiable IS NULL
		SET @IsNegotiable = 0
	IF @MinExperience IS NULL
		SET @MinExperience = 99
	IF @dcEducationID IS NULL
		SET @dcEducationID = 0
	IF @LanguageType IS NULL
		SET @LanguageType = 0
	IF @College IS NULL
		SET @College = ''
	IF LEN(@College) < 2
		SET @College = ''
	WHILE @KeyWord LIKE '%  %'
		SET @KeyWord = REPLACE(@KeyWord, '  ', ' ')
	SET @KeyWord = LTRIM(RTRIM(dbo.SafeSQL(@KeyWord)))
	SET @KeyTemp = @KeyWord
	IF @KeyWord IS NULL OR LEN(@KeyWord) < 2
		SELECT @KeyWord = '', @KeyTemp = ''
	ELSE
	BEGIN
		IF LEFT(@KeyWord, 7) = 'major::'
		BEGIN
			SELECT @MajorName = REPLACE(@KeyWord, 'major::', '')
			SELECT @KeyWord = '', @KeyTemp = ''
		END
		ELSE
		BEGIN
			DECLARE @p INT
			SET @p = CHARINDEX('@@', @KeyWord)
			IF @p > 0
			BEGIN
				SELECT @MajorName = LTRIM(RTRIM(RIGHT(@KeyWord, LEN(@KeyWord) - @p - 1)))
				SELECT @KeyTemp = LEFT(@KeyWord, @p - 1)
				IF LEN(@KeyTemp) < 2
					SET @KeyTemp = ''
			END
		END
	END	
	SET @KeyTemp = REPLACE(@KeyTemp, ' ', ' near ')
	
	SET @College = dbo.SafeSQL(@College)
	IF @SubNodeNum IS NULL
		SET @SubNodeNum = 0
	IF @MaxAge IS NULL OR @MaxAge = 0
		SET @MaxAge = 99
	IF @MinAge IS NULL OR @MinAge = 0
		SET @MinAge = 99
	IF @LivePlace IS NULL
		SET @LivePlace = ''
	SET @LivePlace = dbo.FormatIDS(@LivePlace)
	IF @MobilePlace IS NULL
		SET @MobilePlace = ''
	SET @MobilePlace = dbo.FormatIDS(@MobilePlace)
	IF @AccountPlace IS NULL
		SET @AccountPlace = 0
	IF @Gender IS NULL
		SET @Gender = 2
	IF @IncludeOld IS NULL
		SET @IncludeOld = 0
	IF @Major IS NULL
		SET @Major = 0
	IF @Graduation IS NULL
		SET @Graduation = 0
	ELSE IF @Graduation > DATEPART(YEAR, GETDATE()) + 1 OR @Graduation < DATEPART(YEAR, GETDATE()) - 10
		SET @Graduation = 0
	IF @CvMainID IS NULL
		SET @CvMainID = 0
	IF @Standard IS NULL
		SET @Standard = 0
	IF @IsExpand IS NULL
		SET @IsExpand = 0
	SET @MinHeight = ISNULL(@MinHeight, 0)
	SET @MaxHeight = ISNULL(@MaxHeight, 250)
	IF @MinHeight < 140 OR @MinHeight > 200
		SET @MinHeight = 0
	IF @cvEmployType IS NULL
		SET @cvEmployType = 0

	IF @CvMainID = 0
	BEGIN
		----给null值变量赋默认值
		DECLARE @cpSearchConditionID AS INT
		SELECT @cpSearchConditionID=0, @SessionID = 1
		DECLARE @MinId AS INT
		
		--sqlserver中计划任务自动删除60分钟前的数据
		SELECT TOP 1 @cpSearchConditionID = ID FROM SearchDB..cpSearchCondition WITH(NOLOCK)
		WHERE SessionID=@SessionID AND dcJobTypeID=@dcJobTypeID AND dcJobTypeIDExpect=@dcJobTypeIDExpect
		AND dcRegionID=@dcRegionID AND dcIndustryID=@dcIndustryID AND dcIndustryIDExpect=@dcIndustryIDExpect
		AND IncludeOld=@IncludeOld AND dcSalaryID=@dcSalaryID AND IsNegotiable=@IsNegotiable 
		AND MinExperience=@MinExperience AND dcEducationID=@dcEducationID AND LanguageType=@LanguageType 
		AND KeyWord=@KeyWord AND College=@College AND Standard=@Standard AND SortType=@SortType
		AND SubNodeNum = @SubNodeNum AND Major = @Major AND Graduation = @Graduation AND Gender=@Gender AND MaxAge=@MaxAge
		AND MinAge=@MinAge AND LivePlace=@LivePlace AND AccountPlace=@AccountPlace AND MobilePlace=@MobilePlace 
		AND IsExpand=@IsExpand AND MinHeight = @MinHeight AND MaxHeight = @MaxHeight AND LogTime > DATEADD(M, -60, GETDATE())
		AND EmployType=@cvEmployType
		ORDER BY ID DESC

		IF ISNULL(@cpSearchConditionID, 0) = 0
			GOTO SelectReset	--无数据，重新搜索
		ELSE		
			GOTO GetRecordSet	--从临时结果中提取数据
	END
	ELSE
	BEGIN
		----如果有简历id，则直接显示，不再查询
		SELECT COUNT(1) FROM cvmainPublish WITH(NOLOCK) WHERE ID = @CvMainID AND Valid > 0
		DECLARE @T_Cv AS TABLE(
			ID INT,
			dcMajorID INT,
			Degree TINYINT,
			RelatedWorkYears INT,
			dcSalaryID TINYINT,
			Speciality VARCHAR(MAX) COLLATE Chinese_PRC_CI_AS,
			RefreshDate SMALLDATETIME,
			LastLoginDate SMALLDATETIME,
			JobName VARCHAR(100) COLLATE Chinese_PRC_CI_AS,
			Gender BIT,
			BirthDay INT,
			LivePlace INT,
			Attachment VARCHAR(50),
			HasPhoto TINYINT,
			College NVARCHAR(50),
			EduType TINYINT,
			MajorName NVARCHAR(20),
			Graduation INT,
			HasViewed BIT,
			ViewDate SMALLDATETIME,
			HasRemarked BIT,
			LastJobTypeID INT,
			Valid TINYINT
		)

		INSERT INTO @T_Cv(ID,dcMajorID,Degree,RelatedWorkYears,dcSalaryID,Speciality,RefreshDate,LastLoginDate,
			JobName,Gender,BirthDay,LivePlace,LastJobTypeID,Attachment,HasPhoto,HasViewed,HasRemarked,Valid)
		SELECT a.ID,a.dcMajorID,a.Degree,a.RelatedWorkYears,a.dcSalaryID,ISNULL(a.Speciality,a.SpecialityEng) Speciality,a.RefreshDate,
			j.LastLoginDate,ISNULL(a.JobName, '应届毕业生') JobName,j.Gender,j.BirthDay,j.LivePlace,a.LastJobTypeID,
			a.Attachment,j.HasPhoto,0,0,a.Valid FROM cvmainPublish a WITH(NOLOCK) 
			INNER JOIN paMainPublish j WITH(NOLOCK) ON a.paMainID=j.ID
			WHERE a.ID=@CvMainID AND a.Valid > 0

		UPDATE a SET a.College = ISNULL(b.GraduateCollage,b.GraduateCollageEng), a.EduType = b.EduType, 
			a.MajorName = ISNULL(b.MajorName,b.MajorNameEng), a.Graduation = b.Graduation FROM @T_Cv a,
			cvEducationPublish b WITH(NOLOCK) WHERE b.cvMainID = a.ID AND b.Degree = a.Degree

		UPDATE a SET a.HasViewed = 1, a.ViewDate = (SELECT AddDate FROM caCvViewLog WITH(NOLOCK) WHERE cvMainID = a.ID AND caMainID=@caMainID)
			FROM @T_Cv a WHERE EXISTS(SELECT 'X' FROM caCvViewLog WITH(NOLOCK) WHERE cvMainID = a.ID AND caMainID=@caMainID)
		
--		UPDATE a SET a.HasRemarked = 1
--			FROM @T_Cv a WHERE EXISTS(SELECT 'X' FROM caCvRemark WITH(NOLOCK) WHERE cvMainID = a.ID AND caMainID=@caMainID)

		SELECT * FROM @T_Cv

		RETURN
	END

SelectReset:				--从cv中搜索数据
	BEGIN
		DECLARE @SQL AS VARCHAR(8000)
		DECLARE @WHERE AS VARCHAR(8000)
		DECLARE @FROM AS VARCHAR(1000)
		----记录查询条件
		INSERT INTO SearchDB..cpSearchCondition(SessionID,dcJobTypeID,dcJobTypeIDExpect,dcRegionID,dcIndustryID,
			dcIndustryIDExpect,IncludeOld,dcSalaryID,IsNegotiable,SortType,
			MinExperience,dcEducationID,LanguageType,KeyWord,College,Standard,SubNodeNum,
			Major,Graduation,Gender,MaxAge,MinAge,LivePlace,AccountPlace,MobilePlace,IsExpand, MinHeight, MaxHeight, ReuseNumber, EmployType)
		VALUES(@SessionID,@dcJobTypeID,@dcJobTypeIDExpect,@dcRegionID,@dcIndustryID,
			@dcIndustryIDExpect,@IncludeOld,@dcSalaryID,@IsNegotiable,@SortType,
			@MinExperience,@dcEducationID,@LanguageType,@KeyWord,@College,@Standard,@SubNodeNum,
			@Major,@Graduation,@Gender,@MaxAge,@MinAge,@LivePlace,@AccountPlace,@MobilePlace,@IsExpand, @MinHeight, @MaxHeight, 0,@cvEmployType)
		SET @cpSearchConditionID = @@IDENTITY

		------生成职位类别的表变量，因为职位类别有包含（父子）关系
		DECLARE @T_JobPlace AS TABLE(ID INT)
		DECLARE @T_JobType AS TABLE(ID INT)
		DECLARE @JobType AS VARCHAR(3000)
		DECLARE @JobTypeExpect AS VARCHAR(3000)
		DECLARE @JobPlace AS VARCHAR(2000)
		DECLARE @tmpLivePlace AS VARCHAR(2000)
		DECLARE @tmpMobilePlace AS VARCHAR(2000)
		
		SET @JobPlace = ''
		SET @tmpLivePlace = ''
		SET @tmpMobilePlace = ''
		SET @JobType=''
		SET @JobTypeExpect = ''
		SET @WHERE = ' WHERE a.Valid > 0'
		----生成工作地点的表变量
		IF LEN(@dcRegionID) > 0
		BEGIN
			INSERT INTO @T_JobPlace
			SELECT * FROM dbo.fnSplit(@dcRegionID, ',')
			SELECT @JobPlace = (@JobPlace + ' OR h.dcRegionID Like ''' + LTRIM(STR(ID) + '%''')) FROM @T_JobPlace
			IF @IsExpand = 1
			BEGIN
				SELECT @JobPlace = (@JobPlace + ' OR h.dcRegionID = ''' + LTRIM(STR(LEFT(ID,2)))+'''' )
				FROM @T_JobPlace WHERE LEN(ID) > 2
				SELECT @JobPlace = (@JobPlace + ' OR h.dcRegionID = ''' + LTRIM(STR(LEFT(ID,4)))+'''' )
				FROM @T_JobPlace WHERE LEN(ID) > 4
			END
			IF LEN(@JobPlace) > 0
				SET @JobPlace = RIGHT(@JobPlace, LEN(@JobPlace) -4)
		END

		IF LEN(@LivePlace) > 0
		BEGIN
			DELETE FROM @T_JobPlace
			INSERT INTO @T_JobPlace
			SELECT * FROM dbo.fnSplit(@LivePlace, ',')
			SELECT @tmpLivePlace = (@tmpLivePlace + ' OR j.LivePlace Like ''' + LTRIM(STR(ID) + '%''')) FROM @T_JobPlace
			IF LEN(@tmpLivePlace) > 0
				SET @tmpLivePlace = RIGHT(@tmpLivePlace, LEN(@tmpLivePlace) -4)
		END
		IF LEN(@MobilePlace) > 0
		BEGIN
			DELETE FROM @T_JobPlace
			INSERT INTO @T_JobPlace
			SELECT * FROM dbo.fnSplit(@MobilePlace, ',')
			SELECT @tmpMobilePlace = (@tmpMobilePlace + ' OR j.MobileRegion Like ''' + LTRIM(STR(ID) + '%''')) FROM @T_JobPlace
			IF LEN(@tmpMobilePlace) > 0
				SET @tmpMobilePlace = RIGHT(@tmpMobilePlace, LEN(@tmpMobilePlace) -4)
		END

		----生成求聘职位的表变量
		IF LEN(@dcJobTypeID) > 0
		BEGIN
			DECLARE @T_Temp AS TABLE(ID INT)		--临时表，用于构建组合查询语句
			INSERT INTO @T_Temp
			SELECT * FROM dbo.fnSplit(@dcJobTypeID, ',')

			INSERT INTO @T_JobType
			SELECT DISTINCT ID FROM dcJobType WITH(NOLOCK)
			WHERE ParentId IN(SELECT ID FROM @T_TEMP) 
			OR ParentId2 in(SELECT ID FROM @T_TEMP)
			OR ID IN(SELECT ID FROM @T_TEMP)
			----生成in字符串
			SELECT @JobType = (@JobType + LTRIM(STR(ID) + ',')) FROM @T_JobType
			IF RIGHT(@JobType, 1) = ','
				SET @JobType = LEFT(@JobType, LEN(@JobType) - 1)
		END

		IF LEN(@dcJobTypeIDExpect) > 0
		BEGIN
			DECLARE @T_Temp1 AS TABLE(ID INT)		--临时表，用于构建组合查询语句
			INSERT INTO @T_Temp1
			SELECT * FROM dbo.fnSplit(@dcJobTypeIDExpect, ',')
			DELETE FROM @T_JobType
			INSERT INTO @T_JobType
			SELECT DISTINCT ID FROM dcJobType WITH(NOLOCK)
			WHERE ParentId IN(SELECT ID FROM @T_TEMP1) 
			OR ParentId2 in(SELECT ID FROM @T_TEMP1)
			OR ID IN(SELECT ID FROM @T_TEMP1)
			----生成in字符串
			SELECT @JobTypeExpect = (@JobTypeExpect + LTRIM(STR(ID) + ',')) FROM @T_JobType
			IF RIGHT(@JobTypeExpect, 1) = ','
				SET @JobTypeExpect = LEFT(@JobTypeExpect, LEN(@JobTypeExpect) - 1)

		END
		----建立关键字搜索的临时表
		CREATE TABLE #FullText(
			CvID INT NOT NULL
		)
		----建立临时表
		CREATE TABLE #Cv(
			ID INT NOT NULL,
			RefreshDate SMALLDATETIME NOT NULL
		)
		----生成插入临时表的Sql语句
		SET @SQL = '
			INSERT INTO #Cv
			SELECT DISTINCT TOP 2000 a.ID'
		IF @SortType = 1
			SET @SQL = @SQL + ', j.LastLoginDate'
		ELSE
			SET @SQL = @SQL + ', a.RefreshDate'
		
		SET @FROM = '
			FROM cvmainPublish a WITH(NOLOCK) INNER JOIN paMainPublish j WITH(NOLOCK) ON a.paMainID=j.ID'
		----工作经验的职位类别
		IF LEN(@dcJobTypeID) > 0
		BEGIN
			IF @IncludeOld = 0  ----最近从事和曾从事职位
				SET @WHERE = @WHERE + '
					AND (a.LastJobTypeID IN(' + @JobType +'))'
			ELSE
				SET @WHERE = @WHERE + '
					AND (c.dcJobTypeID IN(' + @JobType +'))'
		END
		----期望职位类别
		IF LEN(@dcJobTypeIDExpect) > 0
		BEGIN
			SET @WHERE = @WHERE + '
				AND (g.dcJobTypeID IN(' + @JobTypeExpect +'))'

		END

		----工作地点
		IF LEN(@JobPlace) > 0 
			SET @WHERE = @WHERE + '
				AND (' + @JobPlace + ')'

		----现从事行业
		IF LEN(@dcIndustryID) > 0
			SET @WHERE = @WHERE + '
				AND (a.LastIndustryID IN(' + @dcIndustryID + '))'
		----期望行业
		IF LEN(@dcIndustryIDExpect) > 0
		BEGIN
			SET @WHERE = @WHERE + '
				AND (i.dcIndustryID IN(' + @dcIndustryIDExpect + '))'
		END
		----下属人数
		IF @SubNodeNum > 0
		BEGIN
			SET @WHERE = @WHERE + '
				AND a.SubNodeNum = ' + LTRIM(STR(@SubNodeNum))
		END
		----当前所在地
		IF LEN(@tmpLivePlace) > 0
		BEGIN
			SET @WHERE = @WHERE + '
				AND (' + @tmpLivePlace + ')'
		END
		----Mobile所在地
		IF LEN(@tmpMobilePlace) > 0
		BEGIN
			SET @WHERE = @WHERE + '
				AND (' + @tmpMobilePlace + ')'
		END
		----户口所在地
		IF @AccountPlace > 0
		BEGIN
			SET @WHERE = @WHERE + '
				AND j.AccountPlace LIKE ''' + LTRIM(STR(@AccountPlace)) + '%'''
		END
		----专业
		IF @Major > 0
		BEGIN
			SET @WHERE = @WHERE + '
				AND b.dcMajorID = ' + LTRIM(STR(@Major))
		END
		--Graduation
		IF @Graduation = DATEPART(YEAR, GETDATE()) + 1
		BEGIN
			SET @WHERE = @WHERE + '
				AND b.Graduation > ' + LTRIM(STR(@Graduation)) + '00'
		END
		ELSE IF @Graduation > DATEPART(YEAR, GETDATE()) - 10
		BEGIN
			SET @WHERE = @WHERE + '
				AND b.Graduation BETWEEN ' + LTRIM(STR(@Graduation)) + '00 AND ' + LTRIM(STR(@Graduation)) + '99'
		END
		ELSE IF @Graduation = DATEPART(YEAR, GETDATE()) - 10
		BEGIN
			SET @WHERE = @WHERE + '
				AND b.Graduation < ' + LTRIM(STR(@Graduation)) + '99'
		END		
		----性别
		IF @Gender < 2
		BEGIN
			SET @WHERE = @WHERE + '
				AND j.Gender=' + LTRIM(STR(@Gender))
		END
		----年龄
		IF @MinAge < 99
		BEGIN
			SET @WHERE = @WHERE + '
				AND j.BirthDay <= ' + LTRIM(STR(dbo.AgeToBirth(@MinAge)))
		END
		IF @MaxAge < 99
		BEGIN
			SET @MaxAge = @MaxAge + 1
			SET @WHERE = @WHERE + '
				AND j.BirthDay > ' + LTRIM(STR(dbo.AgeToBirth(@MaxAge)))
		END
		IF @MinHeight > 139
		BEGIN
			SET @WHERE = @WHERE + '
				AND j.Height >= ' + LTRIM(STR(@MinHeight))
		END
		IF @MaxHeight < 231
		BEGIN
			SET @WHERE = @WHERE + '
				AND j.Height <= ' + LTRIM(STR(@MaxHeight))
		END
		----薪水
		IF @dcSalaryID > 0
		BEGIN
			SET @WHERE = @WHERE + '
			AND((
				a.dcSalaryID >=' + LTRIM(STR(@dcSalaryID-1)) + '
				AND a.dcSalaryID <=' + LTRIM(STR(@dcSalaryID+1)) + '
				)'
			IF @IsNegotiable = 1		--包括面议
				SET @WHERE = @WHERE + '
				OR a.IsNegotiable=1'
			SET @WHERE = @WHERE + ')'
		END
		----工作经验要求
		IF @MinExperience < 99
		BEGIN
			IF @MinExperience = 4
				SET @WHERE = @WHERE + ' 
				AND a.RelatedWorkYears=11'
			ELSE IF @MinExperience = 1
				SET @WHERE = @WHERE + ' 
				AND a.RelatedWorkYears>=1 AND a.RelatedWorkYears<=2'
			ELSE IF @MinExperience = 2
				SET @WHERE = @WHERE + '
				AND a.RelatedWorkYears>=3 AND a.RelatedWorkYears<=5'
			ELSE IF @MinExperience = 3
				SET @WHERE = @WHERE + ' 
				AND a.RelatedWorkYears>=6 AND a.RelatedWorkYears<=10'
			ELSE IF @MinExperience = 5
				SET @WHERE = @WHERE + ' 
				AND a.RelatedWorkYears>=2 AND a.RelatedWorkYears<=3'
			ELSE
				SET @WHERE = @WHERE + ' 
				AND a.RelatedWorkYears=0'
		END
		----学历要求
		IF @dcEducationID > 0
		BEGIN
			IF @dcEducationID = 1
				SET @WHERE = @WHERE + ' AND a.Degree IN(1,2,3,4) '
			ELSE IF @dcEducationID = 2
				SET @WHERE = @WHERE + ' AND a.Degree <= 5 '
			ELSE IF @dcEducationID = 3
				SET @WHERE = @WHERE + ' AND a.Degree = 5 '
			ELSE IF @dcEducationID = 4
				SET @WHERE = @WHERE + ' AND a.Degree IN(5,6) '
			ELSE IF @dcEducationID = 5
				SET @WHERE = @WHERE + ' AND a.Degree = 6 '
			ELSE IF @dcEducationID = 6
				SET @WHERE = @WHERE + ' AND a.Degree >= 6 '
			ELSE IF @dcEducationID = 7
				SET @WHERE = @WHERE + ' AND a.Degree = 7 '
			ELSE IF @dcEducationID = 8
				SET @WHERE = @WHERE + ' AND a.Degree = 8 '

			IF @Major > 0 OR LEN(@College) > 0 OR @Standard = 1 OR @MajorName > ''
				SET @WHERE = @WHERE + '
				AND b.Degree = a.Degree'
			IF @Standard = 1
				SET @WHERE = @WHERE + '
				AND b.EduType=1'
		END
		----语种
		IF @LanguageType > 0
			SET @WHERE = @WHERE + '
				AND d.LanguageType = ' + LTRIM(STR(@LanguageType))
		----关键词
		IF LEN(@KeyTemp) > 0 --AND @MajorName IS NULL
		BEGIN
			DECLARE @S DATETIME, @SqlFt VARCHAR(MAX)
			SELECT @S = GETDATE()

			INSERT INTO #FullText
			SELECT [key] FROM CONTAINSTABLE(CvMainPublish, *, @KeyTemp, 100000) AS KeyCv
			
			INSERT INTO #FullText
			SELECT DISTINCT cvMainID FROM CvExperiencePublish WITH(NOLOCK) WHERE ID IN(
				SELECT [key] FROM CONTAINSTABLE(CvExperiencePublish, *, @KeyTemp, 100000) AS KeyCv)
			
			INSERT INTO #FullText
			SELECT DISTINCT cvMainID FROM CvEducationPublish WITH(NOLOCK) WHERE ID IN(
				SELECT [key] FROM CONTAINSTABLE(CvEducationPublish, *, @KeyTemp, 100000) AS KeyCv)
			
			INSERT INTO #FullText
			SELECT DISTINCT cvMainID FROM CvProjectPublish WITH(NOLOCK) WHERE ID IN(
				SELECT [key] FROM CONTAINSTABLE(CvProjectPublish, *, @KeyTemp, 100000) AS KeyCv)

			INSERT INTO #FullText
			SELECT DISTINCT cvMainID FROM CvTrainingPublish WITH(NOLOCK) WHERE ID IN(
				SELECT [key] FROM CONTAINSTABLE(CvTrainingPublish, *, @KeyTemp, 100000) AS KeyCv)
            --Richard 2011.8.21增加

			INSERT INTO #FullText
			SELECT DISTINCT cvMainID FROM CvAppendixPublish WITH(NOLOCK) WHERE ID IN(
				SELECT [key] FROM CONTAINSTABLE(CvAppendixPublish, *, @KeyTemp, 100000) AS KeyCv)
            --Richard 2011.8.24增加

			SELECT @SqlFt = 'SELECT [key] FROM CONTAINSTABLE(CvMainPublish, *, ''' + @KeyTemp + ''',100000) AS KeyCv ORDER BY [key] DESC 开始：' + CONVERT(varchar(8), @S, 8) + '  结束：' + CONVERT(varchar(8), getdate(), 8)

			UPDATE SearchDB..cpSearchCondition SET SqlFT = @SqlFt WHERE ID = @cpSearchConditionID
		END
		----学校名称
		IF LEN(@College) > 0
			SET @WHERE = @WHERE + '
				AND b.GraduateCollage LIKE ''%' + LTRIM((@College)) + '%'''
		IF LEN(@MajorName) > 0
			SET @WHERE = @WHERE + '
				AND b.MajorName LIKE ''%' + LTRIM((@MajorName)) + '%'''
		--工作性质
		IF @cvEmployType IN(2, 4)
			SET @WHERE = @WHERE + '
				AND a.EmployType = ' + LTRIM(STR(@cvEmployType))
		ELSE IF @cvEmployType = 1
			SET @WHERE = @WHERE + '
				AND a.EmployType IN (1, 2) '
		ELSE IF @cvEmployType = 3
			SET @WHERE = @WHERE + '
				AND a.EmployType IN (3, 2) '

		IF CHARINDEX('b.',@WHERE) > 0
			SET @FROM = @FROM + ' INNER JOIN cvEducationPublish b WITH(NOLOCK) ON a.ID=b.cvMainID'
		IF CHARINDEX('c.',@WHERE) > 0
			SET @FROM = @FROM + ' INNER JOIN CvExperiencePublish c WITH(NOLOCK) ON a.ID=c.cvMainID'
		IF CHARINDEX('d.',@WHERE) > 0
			SET @FROM = @FROM + ' INNER JOIN cvLanguagePublish d WITH(NOLOCK) ON a.ID=d.cvMainID'
		IF CHARINDEX('e.',@WHERE) > 0
			SET @FROM = @FROM + ' INNER JOIN cvTrainingPublish e WITH(NOLOCK) ON a.ID=e.cvMainID'
		IF CHARINDEX('f.',@WHERE) > 0
			SET @FROM = @FROM + ' INNER JOIN cvProjectPublish f WITH(NOLOCK) ON a.ID=f.cvMainID'
		IF CHARINDEX('g.',@WHERE) > 0
			SET @FROM = @FROM + ' INNER JOIN cvJobTypePublish g WITH(NOLOCK) ON a.ID=g.cvMainID'
		IF CHARINDEX('h.',@WHERE) > 0
			SET @FROM = @FROM + ' INNER JOIN cvJobPlacePublish h WITH(NOLOCK) ON a.ID=h.cvMainID'
		IF CHARINDEX('i.',@WHERE) > 0
			SET @FROM = @FROM + ' INNER JOIN cvIndustryPublish i WITH(NOLOCK) ON a.ID=i.cvMainID'
		IF LEN(@KeyTemp) > 0 --AND @MajorName IS NULL
			SET @FROM = @FROM + ' INNER JOIN #FullText k WITH(NOLOCK) ON a.ID=k.cvID'
		SET @SQL = @SQL + @FROM + @WHERE
		IF @SortType = 1
			SET @SQL = @SQL + '
				ORDER BY j.LastLoginDate DESC, a.ID'
		ELSE
			SET @SQL = @SQL + '
				ORDER BY a.RefreshDate DESC, a.ID'
		--PRINT @SQL
		----把符合条件的职位全部列出
		UPDATE SearchDB..cpSearchCondition SET Sql = REPLACE(@SQL, 'INSERT INTO #Cv', ''), StartDate = GETDATE() WHERE ID = @cpSearchConditionID
		EXEC(@SQL)
		----记录查询结果总数
		DECLARE @ValidCvNumber INT
		SET @ValidCvNumber = @@ROWCOUNT		
		UPDATE SearchDB..cpSearchCondition SET ValidCvNumber = @ValidCvNumber WHERE ID = @cpSearchConditionID
		--记录查询时间
		UPDATE SearchDB..cpSearchCondition SET EndDate = GETDATE() WHERE ID = @cpSearchConditionID

		INSERT INTO SearchDB..cpSearchCvID
		SELECT TOP 2000 @cpSearchConditionID, ID FROM #Cv WITH(NOLOCK)

		DROP TABLE #Cv
		DROP TABLE #FullText
		GOTO GetRecordSet
	END

GetRecordSet:
	BEGIN
		DECLARE @PageSize AS TINYINT
		SET @PageSize = 20		--每页的行数

		----返回查询数量
		UPDATE SearchDB..cpSearchCondition SET ReuseNumber = ReuseNumber + 1 WHERE ID=@cpSearchConditionID
		SELECT ValidCvNumber FROM SearchDB..cpSearchCondition WITH(NOLOCK) WHERE ID=@cpSearchConditionID
		----返回20行查询结果
		IF @PageNumber > 0
		BEGIN
			DECLARE @T_CvList AS TABLE(
				ID INT,
				cvEducationID INT,
				dcMajorID INT,
				Degree TINYINT,
				RelatedWorkYears INT,
				dcSalaryID TINYINT,
				Speciality VARCHAR(MAX) COLLATE Chinese_PRC_CI_AS,
				RefreshDate SMALLDATETIME,
				LastLoginDate SMALLDATETIME,
				JobName VARCHAR(100) COLLATE Chinese_PRC_CI_AS,
				Gender BIT,
				BirthDay INT,
				LivePlace INT,
				Attachment VARCHAR(50) COLLATE Chinese_PRC_CI_AS,
				HasPhoto TINYINT,
				College NVARCHAR(50),
				EduType TINYINT,
				MajorName NVARCHAR(20),
				Graduation INT,
				HasViewed BIT,
				ViewDate SMALLDATETIME,
				HasRemarked BIT,
				LastJobTypeID INT,
				Valid TINYINT
			)

			SELECT @MinId = MIN(ID)FROM SearchDB..cpSearchCvID WITH(NOLOCK) WHERE cpSearchConditionID=@cpSearchConditionID
			SET @MinId = @MinId+(@PageNumber-1)*@PageSize

			INSERT INTO @T_CvList(ID,dcMajorID,Degree,RelatedWorkYears,dcSalaryID,Speciality,RefreshDate,LastLoginDate,
				JobName,Gender,BirthDay,LivePlace,LastJobTypeID,Attachment,HasPhoto,HasViewed,HasRemarked,Valid)

			SELECT top 20 a.ID,a.dcMajorID,a.Degree,a.RelatedWorkYears,a.dcSalaryID,ISNULL(a.Speciality,a.SpecialityEng) Speciality,a.RefreshDate,
				j.LastLoginDate,ISNULL(a.JobName, '应届毕业生') JobName,j.Gender,j.BirthDay,j.LivePlace,a.LastJobTypeID,
				a.Attachment,j.HasPhoto,0,0,a.Valid FROM cvmainPublish a WITH(NOLOCK) 
				INNER JOIN paMainPublish j WITH(NOLOCK) ON a.paMainID=j.ID 
                INNER JOIN SearchDB..cpSearchCvID b ON a.id=b.CvID
				WHERE b.cpSearchConditionID=@cpSearchConditionID AND b.ID>=@MinId 
                ORDER BY b.ID,a.ID DESC
            --RICHARD 2011-7-23 16:51分修改

			UPDATE a SET a.cvEducationID = (
						SELECT TOP 1 ID FROM cvEducationPublish WITH(NOLOCK)
						WHERE cvEducationPublish.cvMainID = a.ID
						AND a.Degree = cvEducationPublish.Degree
						ORDER BY Graduation DESC)
			FROM @T_CvList a

			UPDATE a SET a.College = ISNULL(b.GraduateCollage,b.GraduateCollageEng), a.EduType = b.EduType, 
				a.MajorName = ISNULL(b.MajorName,b.MajorNameEng), a.Graduation = b.Graduation
			FROM @T_CvList a, cvEducationPublish b WITH(NOLOCK)
			WHERE b.ID = a.cvEducationID

			UPDATE a SET a.HasViewed = 1, a.ViewDate = b.AddDate
			FROM @T_CvList a, caCvViewLog b WITH(NOLOCK)
			WHERE b.cvMainID = a.ID AND caMainID=@caMainID	
			
--			UPDATE a SET a.HasRemarked = 1
--			FROM @T_CvList a WHERE EXISTS(SELECT 'X' FROM caCvRemark WITH(NOLOCK) WHERE cvMainID = a.ID AND caMainID=@caMainID)

			SELECT * FROM @T_CvList
		END
		RETURN
	END
END TRY
BEGIN CATCH
	---检查是否已经建立临时表，已经建立则删除
	BEGIN TRY
		DROP TABLE #FullText
	END TRY
	BEGIN CATCH
	END CATCH
	BEGIN TRY
		DROP TABLE #cv
	END TRY
	BEGIN CATCH
	END CATCH
	PRINT '查询时出现错误，请联系技术人员检查，错误信息：'
	PRINT Error_Message()
	PRINT Error_Number()
	PRINT Error_Line()
END CATCH











GO
/****** Object:  StoredProcedure [dbo].[ccCvLinkByCountSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ccCvLinkByCountSelect]
(
    @caMainID INT
)
AS
SET NOCOUNT ON
BEGIN
    DECLARE @JobApply AS INT
    DECLARE @NoRepliedJobApply AS INT
    DECLARE @Message AS INT
    DECLARE @NoViewedMessage AS INT
    DECLARE @JobView AS INT

    DECLARE @IsManager INT
    SELECT @IsManager = AccountType FROM camain WHERE ID = @caMainID

    IF @IsManager = 1
    BEGIN
        SELECT @JobApply = COUNT(*)
        FROM exJobApply a WITH(NOLOCK), Job b WITH(NOLOCK)
        WHERE a.CompanyDeleted = 0
        AND a.JobID = b.ID
        AND b.cpMainID = (SELECT CpMainID FROM CaMain WITH(NOLOCK) WHERE ID = @caMainID)
        AND b.IsDelete = 0

	SELECT @JobView = COUNT(*)
        FROM PaJobViewLog a
        INNER JOIN Job b WITH(NOLOCK) ON a.JobId = b.ID
        INNER JOIN paMain c WITH(NOLOCK) ON c.ID = a.paMainID
        INNER JOIN cvMain d WITH(NOLOCK) ON d.paMainID=c.ID AND d.Valid>0
        WHERE b.cpMainID = (SELECT CpMainID FROM CaMain WITH(NOLOCK) WHERE ID = @caMainID)
    END
    ELSE
    BEGIN
        SELECT @JobApply = COUNT(*)
        FROM exJobApply a WITH(NOLOCK), Job b WITH(NOLOCK)
        WHERE a.CompanyDeleted = 0 
        AND a.JobID =b.ID
        AND b.caMainID = @caMainID
        AND b.IsDelete = 0

	SELECT @JobView = COUNT(*)
        FROM PaJobViewLog a
        INNER JOIN Job b WITH(NOLOCK) ON a.JobId = b.ID
        INNER JOIN paMain c WITH(NOLOCK) ON c.ID = a.paMainID
        INNER JOIN cvMain d WITH(NOLOCK) ON d.paMainID=c.ID AND d.Valid>0
        WHERE b.caMainID = @caMainID
    END
        

    SELECT @NoRepliedJobApply = COUNT(*)
    FROM exJobApply a WITH(NOLOCK), Job b WITH(NOLOCK)
    WHERE a.Reply = 0
    And a.CompanyDeleted = 0 
    AND a.JobID =b.ID
    AND b.caMainID = @caMainID
    AND b.IsDelete = 0

    SELECT @NoViewedMessage = 0
        
    SELECT @Message = 0

    SELECT @NoRepliedJobApply AS NoRepliedJobApply, @NoViewedMessage AS NoViewedMessage, @JobApply AS JobApply, @Message AS [Message],@JobView JobView
END
GO
/****** Object:  StoredProcedure [dbo].[ccCvMainByExJobApplyIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



--2016-1-6 nick
--根据申请ID查询简历ID、姓名
create PROCEDURE [dbo].[ccCvMainByExJobApplyIDSelect]
(
	@ExJobApplyID INT
)
AS
BEGIN
	SELECT b.ID,c.Name,d.Name AS JobName
	FROM exjobapply a WITH(NOLOCK),CvMain b WITH(NOLOCK),PaMain c WITH(NOLOCK),Job d WITH(NOLOCK)
	WHERE a.ID = @ExJobApplyID
	AND a.CvMainID = b.ID
	AND b.PaMainID = c.ID
	AND a.JobID = d.ID
END

GO
/****** Object:  StoredProcedure [dbo].[ccCvMainBySecondIdAllSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [dbo].[ccCvMainBySecondIdAllSelect]
(
	@SecondID VARCHAR(10)
)
AS
BEGIN
	SELECT *, dbo.GetPaOnlineStatus(paMainID) IsOnline
	FROM cvMain WITH(NOLOCK INDEX(IX_CvMain_SecondId))
	WHERE SecondID = @SecondID
END






GO
/****** Object:  StoredProcedure [dbo].[ccCvMainBySecondIdSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [dbo].[ccCvMainBySecondIdSelect]
(
	@SecondId VARCHAR(10)
)
AS
BEGIN
	SELECT Id, paMainId FROM cvMain WITH(NOLOCK) WHERE SecondId = @SecondId
END
GO
/****** Object:  StoredProcedure [dbo].[ccCvmainRelatedWorkYearsByIDUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.31
--创建人：Nick
--说明：修改工作时间
--#####################################################
CREATE PROCEDURE [dbo].[ccCvmainRelatedWorkYearsByIDUpdate]
(
	@cvMainID INT,
	@WorkYears INT
)
AS
BEGIN TRY
	UPDATE cvMain 
	SET RelatedWorkYears=@WorkYears 
	WHERE ID=@cvMainID


END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[ccCvMainSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[ccCvMainSelect]
	@ID INT
AS
BEGIN
	SELECT *
	FROM cvMain a WITH(NOLOCK),paMain b WITH(NOLOCK)
	WHERE a.paMainID=b.ID
	AND a.ID=@ID
END














GO
/****** Object:  StoredProcedure [dbo].[ccdcFeeByCoinRationSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================-- Author:		Peter
-- Create date: 2014-08-20 09:55
-- Description:	
-- =============================================
CREATE PROCEDURE [dbo].[ccdcFeeByCoinRationSelect]
(
	@cpMainID INT,
	@dcFeeDetailID INT
)
AS
BEGIN
	SELECT CoinRation,(SELECT ReMainCoin FROM cpMain WHERE id=@cpMainID) CoinBalance 
	FROM dcFee
	WHERE ID=@dcFeeDetailID
END





GO
/****** Object:  StoredProcedure [dbo].[ccDcFeeByOrderTypeSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		mice
-- Create date: 2014-8-21
-- Description:	返回当前时间内的积分兑换订单
-- 修改：harry 2015-7-3
-- 修改： a.NeedPoint >0
-- =============================================
CREATE PROCEDURE [dbo].[ccDcFeeByOrderTypeSelect]
(
	@dcProvinceID INT
)
AS
BEGIN
	CREATE TABLE #PointOrderCount(
		typeID INT,
		typeCount INT )

	DECLARE @VipOrderCount AS INT
	SELECT @VipOrderCount = COUNT(a.id) FROM dcVipDetail a, dcVip b 
	WHERE b.id = a.dcVipID AND a.NeedPoint > 0
	AND b.dcProvinceID = @dcProvinceID AND b.startDate < GETDATE() 
	AND endDate > GETDATE()

	INSERT INTO #PointOrderCount VALUES(8, @VipOrderCount)

	INSERT INTO #PointOrderCount 
	SELECT b.Type AS typeID, COUNT(a.id) AS typeCount
	FROM dcFeeDetail a WITH(NOLOCK), dcFee b WITH(NOLOCK)
	WHERE a.dcFeeID = b.id AND a.NeedPoint >0
	AND b.dcProvinceID = @dcProvinceID AND b.startDate < GETDATE() AND endDate > GETDATE()
	AND b.Type IN (10, 11, 22, 24, 21, 20, 23, 5, 4, 7)
	GROUP BY b.Type

	SELECT * FROM #PointOrderCount
	DROP TABLE #PointOrderCount
END




 
GO
/****** Object:  StoredProcedure [dbo].[ccDcFeeByProvinceIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.6
--创建人：John
--说明：根据省份获取所有资费
--#####################################################
CREATE PROCEDURE [dbo].[ccDcFeeByProvinceIDSelect]
(
	@ProvinceID INT,
	@BackTestDate VARCHAR(50)
)
AS
set nocount on
if ISnull(@BackTestDate, '') > ''
	insert proclog select 'ccDcFeeByProvinceIDSelect', @BackTestDate, getdate()
else
	insert proclog select 'ccDcFeeByProvinceIDSelect2', '', getdate()
BEGIN
	IF @BackTestDate <> ''
	BEGIN
		SELECT a.type,a.name allname,a.price allprice,a.enddate,a.remark allremark ,b.name,b.price,b.minvalue,b.remark 
		FROM DcFee a WITH(NOLOCK), dcFeeDetail b WITH(NOLOCK) 
		WHERE a.id = b.dcfeeid 
			AND a.dcprovinceid = @ProvinceID 
			AND a.StartDate <= @BackTestDate 
			AND a.EndDate >= @BackTestDate 
		ORDER BY a.type,b.minvalue
	END
	ELSE
	BEGIN
		SELECT a.type,a.name allname,a.price allprice,a.enddate,a.remark allremark ,b.name,b.price,b.minvalue,b.remark 
		FROM DcFee a WITH(NOLOCK), dcFeeDetail b WITH(NOLOCK) 
		WHERE a.id = b.dcfeeid 
			AND a.dcprovinceid = @ProvinceID 
			AND GETDATE() BETWEEN a.startdate AND a.enddate 
		ORDER BY a.type,b.minvalue
	END
END


GO
/****** Object:  StoredProcedure [dbo].[ccdcFeeByStartDateSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[ccdcFeeByStartDateSelect]
    @dcProvinceID INT,
	@type INT,
	@BackTestDate VARCHAR(20)
AS
SET NOCOUNT ON
INSERT PROCLOG SELECT 'ccdcFeeByStartDateSelect', @BackTestDate, GETDATE()
BEGIN
    SELECT TOP 1 *
    FROM dcFee WITH(NOLOCK)
    WHERE dcProvinceID = @dcProvinceID
	AND type = @type
	AND StartDate <= @BackTestDate AND EndDate >= @BackTestDate
END














GO
/****** Object:  StoredProcedure [dbo].[ccdcFeeDetailByIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================-- Author:		Peter
-- Create date: 2014-08-20 09:55
-- Description:	
-- =============================================
CREATE PROCEDURE [dbo].[ccdcFeeDetailByIDSelect]
    @ID INT
AS
BEGIN
    SELECT a.ID,a.dcFeeID,a.Name detailName,a.MinValue,a.MaxValue,a.Price,a.Remark,a.NeedPoint, b.Price PrePrice, b.Name
	FROM dcFeeDetail a WITH(NOLOCK) ,dcFee b WITH(NOLOCK)
	WHERE a.dcFeeID = b.ID AND a.ID = @ID
END





GO
/****** Object:  StoredProcedure [dbo].[ccdcFeeDetailByMinValueSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ccdcFeeDetailByMinValueSelect]
    @dcProvinceID INT,
    @Type INT
AS
BEGIN
    DECLARE @MinValue INT
    SELECT @MinValue = Min(MinValue) FROM dcFee a WITH(NOLOCK), dcFeeDetail b WITH(NOLOCK)
    WHERE a.dcProvinceID = @dcProvinceID
    AND a.Type = @Type
    AND b.dcFeeID = a.ID
    AND a.StartDate <= GETDATE() AND a.EndDate >= GETDATE()

    RETURN @MinValue
END














GO
/****** Object:  StoredProcedure [dbo].[ccdcFeeDetailSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[ccdcFeeDetailSelect]
    @dcFeeID INT
AS
BEGIN
    SELECT a.startDate, a.EndDate,a.Price PrePrice, b.*
	FROM dcFee a WITH(NOLOCK), dcFeeDetail b WITH(NOLOCK)
    WHERE b.dcFeeID = @dcFeeID
	AND b.dcFeeID = a.ID
	ORDER BY MinValue
END














GO
/****** Object:  StoredProcedure [dbo].[ccdcFeeSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[ccdcFeeSelect]
(
    @dcProvinceID INT,
	@type INT
)
AS
SET NOCOUNT ON
--INSERT PROCLOG SELECT 'ccdcFeeSelect', @TYPE, GETDATE()
--this proc is valid
BEGIN
    SELECT TOP 1 *
    FROM dcFee WITH(NOLOCK)
    WHERE dcProvinceID = @dcProvinceID
	AND type = @type
	AND StartDate <=GETDATE() AND EndDate >= GETDATE()
END














GO
/****** Object:  StoredProcedure [dbo].[ccDcJobNameSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ccDcJobNameSelect]
(
	@Name NVARCHAR(50)
)
AS
SET NOCOUNT ON
BEGIN
	IF(@Name = '微信运营')
	BEGIN
		SELECT Id, Description FROM dcJobType WHERE ID = 2313
		RETURN
	END

	IF(@Name = '招标')
	BEGIN
		SELECT Id, Description FROM dcJobType WHERE ID = 1918
		RETURN
	END

	DECLARE @t AS TABLE(ID INT IDENTITY(1, 1), Name NVARCHAR(100), dcJobTypeId VARCHAR(4))

	INSERT @t
	SELECT TOP 3 Name, dcJobTypeId 
	FROM dcJobName WITH(NOLOCK)
	WHERE Name = @Name 
	AND dcJobTypeId IN(SELECT dcJobTypeID FROM dcJobTypetemplate)
	ORDER BY Cnt DESC

	IF(SELECT COUNT(*) FROM @t) > 0
	BEGIN
		SELECT Id, Description FROM dcJobType WHERE 
		ID IN(SELECT dcJobTypeId FROM @t)
		AND ID IN(SELECT dcJobTypeID FROM dcJobTypetemplate WHERE LEN(Responsibility) > 0)
		RETURN
	END
	ELSE
	BEGIN
		INSERT @t
		SELECT TOP 3 Name, dcJobTypeId 
		FROM dcJobName WITH(NOLOCK) 
		WHERE CHARINDEX(@Name, Name) >0 
		AND dcJobTypeId IN(SELECT dcJobTypeID FROM dcJobTypetemplate)
		ORDER BY Cnt DESC

		IF(SELECT COUNT(*) FROM @t) > 0
		BEGIN
			SELECT Id, Description 
			FROM dcJobType 
			WHERE ID IN(SELECT dcJobTypeId FROM @t)
			AND ID IN(SELECT dcJobTypeID FROM dcJobTypetemplate WHERE LEN(Responsibility) > 0)
			RETURN
		END
	        
		IF NOT EXISTS(SELECT 'X' FROM dcJobType WHERE Description = @Name)
		BEGIN
			INSERT @t
			SELECT TOP 3 Name, dcJobTypeId
			FROM dcJobName WITH(NOLOCK) 
			WHERE CHARINDEX(Name, @Name) > 0 
			AND dcJobTypeId IN(SELECT dcJobTypeID FROM dcJobTypetemplate)
			ORDER BY Cnt DESC

			SELECT Id, Description 
			FROM dcJobType 
			WHERE ID IN(SELECT dcJobTypeId FROM @t) 
			AND ID IN(SELECT dcJobTypeID FROM dcJobTypetemplate WHERE LEN(Responsibility) > 0)
		END
		ELSE
			SELECT TOP 0 Id, Description FROM dcJobType WHERE ID IN(SELECT dcJobTypeId FROM @t)
	END
END

GO
/****** Object:  StoredProcedure [dbo].[ccDcJobNameSelect11]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ccDcJobNameSelect11]
(
	@Name NVARCHAR(50)
)
AS
BEGIN
	DECLARE @t AS TABLE(ID INT IDENTITY(1, 1), Name NVARCHAR(100), dcJobTypeId VARCHAR(4))
	
	INSERT @t
	SELECT TOP 1 DescrIption, Id FROM dcJobType WITH(NOLOCK) WHERE CHARINDEX(@Name, Description) >0 AND Description NOT LIKE '其他%' ORDER BY ID
	IF(SELECT COUNT(*) FROM @t) > 0
	BEGIN
		SELECT a.Id, a.Description FROM dcJobType a, @t b
		WHERE a.ID = b.dcJobTypeId
		AND a.ID IN(SELECT dcJobTypeID FROM dcJobTypetemplate)
		ORDER BY b.ID
		RETURN
	END

	INSERT @t
	SELECT TOP 3 Name, dcJobTypeId FROM dcJobName WITH(NOLOCK) WHERE Name = @Name  AND dcJobTypeId IN(SELECT dcJobTypeID FROM dcJobTypetemplate)
 ORDER BY Cnt DESC

	IF(SELECT COUNT(*) FROM @t) > 0
	BEGIN
		SELECT a.Id, a.Description FROM dcJobType a, @t b
		WHERE a.ID = b.dcJobTypeId
		AND a.ID IN(SELECT dcJobTypeID FROM dcJobTypetemplate)
		ORDER BY b.ID
		RETURN
	END

	INSERT @t
	SELECT TOP 3 Name, dcJobTypeId FROM dcJobName WITH(NOLOCK) WHERE CHARINDEX(@Name, Name) >0  AND dcJobTypeId IN(SELECT dcJobTypeID FROM dcJobTypetemplate)
 ORDER BY Cnt DESC
	
	IF(SELECT COUNT(*) FROM @t) > 0
	BEGIN
		SELECT a.Id, a.Description FROM dcJobType a, @t b
		WHERE a.ID = b.dcJobTypeId
		AND a.ID IN(SELECT dcJobTypeID FROM dcJobTypetemplate)
		ORDER BY b.ID
		RETURN
	END

	INSERT @t
	SELECT TOP 3 Name, dcJobTypeId FROM dcJobName WITH(NOLOCK) WHERE CHARINDEX(Name, @Name) >0  AND dcJobTypeId IN(SELECT dcJobTypeID FROM dcJobTypetemplate)
 ORDER BY Cnt DESC

	SELECT a.Id, a.Description FROM dcJobType a, @t b
	WHERE a.ID = b.dcJobTypeId
	AND a.ID IN(SELECT dcJobTypeID FROM dcJobTypetemplate)
	ORDER BY b.ID
END











GO
/****** Object:  StoredProcedure [dbo].[ccdcPayMethodSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--3201,3204,3205,3206,3209,3212,3213,3215,3217
CREATE PROCEDURE [dbo].[ccdcPayMethodSelect]
(
	@dcProvinceID INT
)
AS
BEGIN
	IF @dcProvinceID IN (3201,3204,3205,3206,3209,3212,3213,3215,3217)
	BEGIN
		SELECT b.Name,a.PayMethodID,a.JointNo,
			BankName,Account,Receiver,b.HomePage
		FROM dcPayMethodProvince a WITH(NOLOCK),
			dcPayMethod b WITH(NOLOCK)
		WHERE a.PayMethodID = b.PayMethodID
		AND a.dcProvinceID = @dcProvinceID AND b.FrontShow = 1
		ORDER BY OrderBy
	END
	ELSE IF @dcProvinceID IN(30, 32)
	BEGIN
		SELECT b.Name,a.PayMethodID,a.JointNo,
			BankName,Account,Receiver,b.HomePage
		FROM dcPayMethodProvince a WITH(NOLOCK),
			dcPayMethod b WITH(NOLOCK)
		WHERE a.PayMethodID = b.PayMethodID
		AND a.dcProvinceID = 30 AND b.FrontShow = 1
		ORDER BY OrderBy
	END
	ELSE
	BEGIN
		SELECT b.Name,a.PayMethodID,a.JointNo,
			BankName,Account,Receiver,b.HomePage
		FROM dcPayMethodProvince a WITH(NOLOCK),
			dcPayMethod b WITH(NOLOCK)
		WHERE a.PayMethodID = b.PayMethodID
		AND a.dcProvinceID = 10 AND b.FrontShow = 1
		ORDER BY OrderBy
	END
END

GO
/****** Object:  StoredProcedure [dbo].[ccdcVipByCoinRationSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Peter
-- Create date: 2014-08-20 09:55
-- Description:
-- =============================================
CREATE PROCEDURE [dbo].[ccdcVipByCoinRationSelect]
(
	@cpMainID INT,
	@dcFeeDetailID INT
)
AS
BEGIN
	SELECT a.CoinRation,(SELECT RemainCoin FROM cpMain WHERE id=@cpMainID) CoinBalance 
	FROM dcVip a, dcVipdetail b 
	WHERE b.dcVipID=a.ID AND b.ID=@dcFeeDetailID
END





GO
/****** Object:  StoredProcedure [dbo].[ccdcVipByStartDateSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[ccdcVipByStartDateSelect]
(
    @dcProvinceID INT,
	@BackTestDate VARCHAR(20)
)
AS
SET NOCOUNT ON
INSERT ProcLog SELECT 'ccdcVipByStartDateSelect', @BackTestDate, GETDATE()
BEGIN
    SELECT TOP 1 *
    FROM dcVip WITH(NOLOCK)
    WHERE dcProvinceID = @dcProvinceID
	AND StartDate <= @BackTestDate AND EndDate >= @BackTestDate
END














GO
/****** Object:  StoredProcedure [dbo].[ccdcVipDetailByIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--修改harry 2017-6-5 增加短信订单
--修改harry 2017-11-11 增加刷新数订单
CREATE PROCEDURE [dbo].[ccdcVipDetailByIDSelect]
(
    @ID INT
)
AS
--INSERT INTO procLog SELECT 'ccDcVipDetailByIDSelect', '', GETDATE()
SET NOCOUNT ON
BEGIN
	IF(@Id = 0)
		SELECT * FROM dcVipTryOut
	ELSE
		SELECT a.*, b.PriceJOb, b.PriceUser, b.PriceResume, b.PriceMonth, b.PriceSms,b.priceJobrefreshNumber, b.Name
		FROM dcVipDetail a WITH(NOLOCK), dcVip b WITH(NOLOCK)
		WHERE a.dcVipID = b.ID AND a.ID = @ID
END
SET NOCOUNT OFF

GO
/****** Object:  StoredProcedure [dbo].[ccdcVipDetailPointSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Mice
-- Create date: 2014-08-15
-- Description:	查询可用积分兑换Vip订单信息
-- =============================================
CREATE PROCEDURE [dbo].[ccdcVipDetailPointSelect]
(
	@dcVipID INT
)
AS
BEGIN
    SELECT a.startDate, a.EndDate, b.*
	FROM dcVip a WITH(NOLOCK), dcVipDetail b WITH(NOLOCK)
    WHERE b.dcVipID = @dcVipID
	AND b.dcVipID = a.ID
	AND b.IsShowFront = 1
	AND b.NeedPoint IS NOT NULL 
	AND b.NeedPoint <> 0
	ORDER BY [Month] DESC, Price DESC
END




GO
/****** Object:  StoredProcedure [dbo].[ccdcVipDetailSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--创建人 lambo 
--功能：前台根据资费计划取资费套餐
--修改：增加IsShowFront=0的条件，取前台显示的记录  lambo 20131125
CREATE PROCEDURE [dbo].[ccdcVipDetailSelect]
(
    @dcVipID INT
)
AS
BEGIN
    SELECT a.startDate, a.EndDate, b.*
	FROM dcVip a WITH(NOLOCK), dcVipDetail b WITH(NOLOCK)
    WHERE b.dcVipID = @dcVipID
	AND b.dcVipID = a.ID
	AND b.IsShowFront=1
	ORDER BY [Month] DESC, Price DESC
END












GO
/****** Object:  StoredProcedure [dbo].[ccdcVipSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[ccdcVipSelect]
(
    @dcProvinceID INT
)
AS
SET NOCOUNT ON
--INSERT ProcLog SELECT 'ccdcVipSelect', @dcProvinceID, GETDATE()
--this proc is valid
BEGIN
    SELECT TOP 1 *
    FROM dcVip WITH(NOLOCK)
    WHERE dcProvinceID = @dcProvinceID
	AND StartDate <= GETDATE() AND EndDate >= GETDATE()
END














GO
/****** Object:  StoredProcedure [dbo].[ccExInterviewBatchDelete]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


--Lambo 20101130 修改
--增加cpMainID参数，判断是否是本企业的
--Lambo 20110223修改 
--增加时间、是否回复的判断，一个月内，未回复的不能删除
CREATE PROCEDURE [dbo].[ccExInterviewBatchDelete]
(
	@AllID VARCHAR(1000),
	@cpMainID INT
)
AS
BEGIN TRAN
	BEGIN TRY
		SET @AllID = dbo.FormatIDS(@AllID)
		DECLARE @T AS TABLE(ID INT)
		INSERT INTO @T SELECT * FROM dbo.fnSplit(@AllID, ',')

		DELETE FROM ExInterview
		WHERE ID IN(SELECT ID FROM @T)
		AND (Reply <> 0 Or AddDate < GETDATE()-30)
		AND JobID IN (SELECT ID FROM Job WITH(NOLOCK) WHERE cpMainID = @cpMainID)
		AND PersonDeleted = 1

		UPDATE ExInterview SET CompanyDeleted = 1, CompanyDeleteDate = GETDATE()
		WHERE ID IN(SELECT ID FROM @T)
		AND (Reply <> 0 Or AddDate < GETDATE()-30)
		AND JobID IN (SELECT ID FROM Job WITH(NOLOCK) WHERE cpMainID = @cpMainID)	
	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH
COMMIT TRAN
RETURN 1
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END














GO
/****** Object:  StoredProcedure [dbo].[ccExInterviewByCvMainID30DaysSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ccExInterviewByCvMainID30DaysSelect]
	@AllID VARCHAR(1000),
	@JobID INT
AS
BEGIN
	SET @AllID = dbo.FormatIDS(@AllID)
	DECLARE @T AS TABLE(ID INT)
	INSERT INTO @T SELECT * FROM dbo.fnSplit(@AllID, ',')

	SELECT cvMainID,AddDate FROM exInterview WITH(NOLOCK)
	WHERE JOBID = @JobID
	AND GETDATE()-AddDate < 30
	AND cvMainID IN(SELECT ID FROM @T)	
END














GO
/****** Object:  StoredProcedure [dbo].[ccExInterViewByCvMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--说明：得到面试通知列表
--修改：2015-01-15 Andy
--		1. 添加dcRegionID列
--		2. 去掉try catch
--#####################################################
CREATE PROCEDURE [dbo].[ccExInterViewByCvMainIDSelect]
(
	@caMainID INT,
	@cvMainID INT,
	@cpMainID INT
)
AS
BEGIN	
	IF @cpMainID > 0
	BEGIN
		SELECT a.ID, a.JobID, b.dcRegionID, a.cvMainID, a.InterviewDate, a.InterViewPlace, a.LinkMan, a.Telephone,  
			   a.Remark, a.AddDate, a.Reply, a.ReplyMessage, a.Replydate, a.CompanyDeleted, a.CompanyDeleteDate, 
			   a.PersonDeleted, a.PersonDeleteDate, a.ViewDate, b.Name AS JobName, b.caMainID 
		FROM exInterView a WITH(NOLOCK) 
		INNER JOIN Job b WITH(NOLOCK) ON b.ID = a.JobID 
		WHERE cvMainID = @cvMainID AND cpMainID = @cpMainID
	END
	IF @cpMainID = 0
	BEGIN
		SELECT a.ID, a.JobID, b.dcRegionID, a.cvMainID, a.InterviewDate, a.InterViewPlace, a.LinkMan, a.Telephone, 
			   a.Remark, a.AddDate, a.Reply, a.ReplyMessage, a.Replydate, a.CompanyDeleted, a.CompanyDeleteDate, 
			   a.PersonDeleted, a.PersonDeleteDate, a.ViewDate, b.Name AS JobName, b.caMainID 
		FROM exInterView a WITH(NOLOCK) 
		INNER JOIN Job b WITH(NOLOCK) ON b.ID = a.JobID 
		WHERE cvMainID = @cvMainID AND caMainID=@caMainID	
	END
END


GO
/****** Object:  StoredProcedure [dbo].[ccExInterviewByIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.30
--创建人：Nick
--说明：//得到面试通知详情
--#####################################################
CREATE PROCEDURE [dbo].[ccExInterviewByIDSelect]
(
	@ID INT
)
AS
BEGIN TRY
	SELECT a.ID,a.Name ,a.Mobile,a.dcSubSiteID,a.IsReceiveSms,d.Name JobName 
	FROM paMain a WITH(NOLOCK) ,cvMain b WITH(NOLOCK) ,ExInterview c WITH(NOLOCK) ,Job d WITH(NOLOCK) 
	WHERE a.ID = b.paMainID AND b.ID = c.cvMainID AND c.JobID = d.ID AND c.ID =@ID 
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[ccexInterviewByIDUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.30
--创建人：Nick
--说明：修改面试通知
--#####################################################
CREATE PROCEDURE [dbo].[ccexInterviewByIDUpdate]
(
	@Result VARCHAR(50),
	@CamainID INT,
	@ID INT
)
AS
BEGIN TRY
	DECLARE @IsManager INT,@CpMainID INT

	SELECT @IsManager = AccountType,@CpMainID = CpMainID 
	FROM caMain WITH(NOLOCK) 
	WHERE ID = @CamainID

	IF @IsManager = 1
	BEGIN
		UPDATE exInterview 
		SET Result=@Result,ResultDate=GETDATE() 
		WHERE ID =  @ID And JobID IN (SELECT ID From Job WHERE cpMainID = @CpMainID)
	END
	ELSE
	BEGIN
		UPDATE exInterview 
		SET Result=@Result,ResultDate=GETDATE() 
		WHERE ID =  @ID And JobID IN (SELECT ID From Job WHERE caMainID = @CaMainID)
	END
	
	RETURN 1
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[ccExInterViewByJobIDInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*#######################################
---面试通知
2012-10-23 sean
update msgcount from smsmessagelog
2014-08-25 Peter
添加积分记录
---2015-8-27 Harry
---增加将绑定关注微信的，插入到wxsendmessage表中
---20160216 Lucifer 添加推送
#######################################*/
CREATE PROCEDURE [dbo].[ccExInterViewByJobIDInsert]
(
	@JobID INT, 
	@cpMainID INT, 
	@cvMainID INT, 
	@InterviewDate VARCHAR(100), 
	@InterViewPlace VARCHAR(200), 
	@LinkMan VARCHAR(12), 
	@Telephone VARCHAR(20), 
	@Remark VARCHAR(1000)
)
AS
SET NOCOUNT ON
BEGIN
	SET NOCOUNT ON
	DECLARE @InterviewPoint INT --直接发送面试通知 赠送积分
	DECLARE @ReplyInterviewPoint INT --答复后 发送面试通知 赠送积分
	SET @InterviewPoint =7
	SET @ReplyInterviewPoint = 10

	DECLARE @caMainID INT, @paMainId INT, @ExInterViewID INT, @wxFansId INT, @MsgCount INT
	SELECT @caMainID = caMainId FROM Job WITH(NOLOCK) WHERE ID = @JobID AND cpMainID = @cpMainID
	IF ISNULL(@caMainID, 0) = 0
		RETURN -1

	SELECT @Remark = dbo.TrimNull(@Remark),
		@InterviewDate = dbo.Trim(@InterviewDate),
		@InterViewPlace = dbo.Trim(@InterViewPlace),
		@Telephone = dbo.Trim(@Telephone)

	INSERT INTO ExInterView(JobID, cvMainID, InterviewDate, InterViewPlace, LinkMan, Telephone, Remark)
	VALUES(@JobID, @cvMainID, @InterviewDate, @InterViewPlace, @LinkMan, @Telephone, @Remark)
	SET @ExInterViewID = @@IDENTITY
	
	--未答复的修改答复状态
	UPDATE exJobApply SET Reply =1 WHERE JobID = @JobID AND CvMainID = @cvMainID

	BEGIN TRY
		SELECT @paMainId = paMainId FROM cvMain WITH(NOLOCK) WHERE Id = @cvMainId
		SELECT @wxFansId = id FROM wxFans WITH(NOLOCK) WHERE paMainId = @paMainId AND [Status] = 2
		IF @wxFansId IS NULL
		BEGIN
			SELECT @MsgCount = SUM(smsNumber) FROM ExInterView WITH(NOLOCK)
			WHERE JobId IN(SELECT ID FROM Job WITH(NOLOCK) WHERE cpMainId = @cpMainID)
			AND AddDate > CONVERT(VARCHAR(10), GETDATE() - 29, 120)
 
			IF @MsgCount < 30
			BEGIN
				INSERT SmsMessageLog(SendMan, ManagerUSerId, paMainId, caMainId, Mobile, MsgType, IsCat, Msg)
				SELECT  0, NULL, b.ID, @caMainID, b.Mobile, 101, 0, 
					ISNULL(b.Name,'') +'，'+ d.Name +'在'+ c.SubSiteName + c.EmailSite +'上邀请您面试，请登录网站查看'
				FROM cvMain a WITH(NOLOCK), paMain b WITH(NOLOCK), dcSubSite c WITH(NOLOCK),cpMain d WITH(NOLOCK)
				WHERE a.paMainID = b.ID
				AND b.dcSubSiteID = c.ID
				AND d.ID = @cpMainID
				AND b.Mobile > ''
				AND a.ID = @cvMainID
				AND b.IsReceiveSms = 1

				UPDATE ExInterView SET SmsNumber = ISNULL(SmsNumber, 0) + 1 WHERE ID = @ExInterViewID
			END
		END
		ELSE		--关注的用户发送微信消息提醒
		BEGIN
			--插入到wxMessageSend表中
			INSERT WxMessageSend2(Templatetype, WxFansID, PaMainId, MainTableId, CpMainID, CvMainID, JobId, CaMainId, AddDate)
			SELECT 1, @wxFansId, @paMainId, @ExInterViewID, @cpMainId, @cvMainID, @JobId, @caMainID, GETDATE()
		END
		
		INSERT INTO paPushLog(paMainID, PushMessage, PushType)
		SELECT @paMainId, '亲，收到一份面试通知！', 2 WHERE EXISTS(SELECT 'X' FROM paIOSBind WHERE paMainID = @paMainId)
	END TRY
	BEGIN CATCH
	END CATCH
	
	--插入积分记录
	BEGIN TRY
	--插入积分记录
		DECLARE @TodayPoint AS INT
		DECLARE @TodayID AS INT
		SET @TodayPoint = 0
		SET @TodayID = 0
		SELECT TOP 1 @TodayPoint = ISNULL(Point,0),
			@TodayID = ISNULL(ID, 0) 
		FROM cpPoint WITH(NOLOCK)
		WHERE changeID = 4 AND LastModifyDate > CONVERT(VARCHAR(10), GETDATE(),120)
		AND cpMainID = @cpMainID
		
		--判断是否是应聘的简历
--		DECLARE @JobApplyID INT,@Reply INT
--
--		SELECT @JobApplyID = 0,@Reply = 0
--		SELECT @JobApplyID = ID,@Reply = Reply 
--		FROM ExJobApply WITH(NOLOCK)
--		WHERE JobID = @JobID
--		AND CvMainID = @cvMainID
--
--		IF @JobApplyID = 0	--未应聘
--		BEGIN
--			SET @TodayPoint = @ReplyInterviewPoint
--		END
--		ELSE 
--		BEGIN
--			IF @Reply = 0
--			BEGIN
--				UPDATE ExJobApply 
--				SET Reply = 1
--				WHERE ID = @JobApplyID
--
--				SET @TodayPoint = @InterviewPoint
--			END
--			ELSE
--			BEGIN
--				SET @TodayPoint = @ReplyInterviewPoint
--			END
--		END

		SET @TodayPoint = @TodayPoint + @ReplyInterviewPoint
		
		IF @TodayPoint <= 200
		BEGIN
			IF @TodayID = 0
			BEGIN
				INSERT INTO cpPoint (cpMainID,ChangeID,Point,LastModifyDate) VALUES(@cpMainID,4,@TodayPoint,GETDATE())
			END
			ELSE
			BEGIN
				UPDATE cpPoint SET Point = Point + @TodayPoint,LastModifyDate = GETDATE() WHERE ID = @TodayID 
			END
		END	
		
	END TRY
	BEGIN CATCH
	END CATCH
--	RETURN @Return
	RETURN ISNULL(@MsgCount, 0)
END  

GO
/****** Object:  StoredProcedure [dbo].[ccexInterviewByJobIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：20160104
--创建人：Nick
--说明：是否发送过面试通知
--#####################################################
create PROCEDURE [dbo].[ccexInterviewByJobIDSelect]
(
	@JobID INT,
	@CvMainID INT,
	@CaMainID INT
)
AS
SET NOCOUNT ON
BEGIN	
	SELECT TOP 1 a.* FROM exInterview a,Job b
	WHERE JobID = @JobID
	AND CvMainID = @CvMainID
	AND b.CaMainID = @CaMainID
	AND a.JobID  = b.ID
	ORDER BY a.ID DESC
END 

GO
/****** Object:  StoredProcedure [dbo].[ccExInterViewByJobIDSendSmsInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*#######################################
---面试通知(是否发送短信)
---创建人harry
#######################################*/
CREATE PROCEDURE [dbo].[ccExInterViewByJobIDSendSmsInsert]
(
	@JobID INT, 
	@cpMainID INT, 
	@cvMainID INT, 
	@InterviewDate VARCHAR(100), 
	@InterViewPlace VARCHAR(200), 
	@LinkMan VARCHAR(12), 
	@Telephone VARCHAR(20), 
	@Remark VARCHAR(1000),
	@SendSms INT--发送短信
)
AS
SET NOCOUNT ON
BEGIN
	SET NOCOUNT ON
	DECLARE @InterviewPoint INT --直接发送面试通知 赠送积分
	DECLARE @ReplyInterviewPoint INT --答复后 发送面试通知 赠送积分
	SET @InterviewPoint =7
	SET @ReplyInterviewPoint = 10

	DECLARE @caMainID INT, @paMainId INT, @ExInterViewID INT, @wxFansId INT,@JobName NVARCHAR(50)
	SELECT @caMainID = caMainId, @JobName = Name FROM Job WITH(NOLOCK) WHERE ID = @JobID AND cpMainID = @cpMainID
	IF ISNULL(@caMainID, 0) = 0
		RETURN -1

	SELECT @Remark = dbo.TrimNull(@Remark),
		@InterviewDate = dbo.Trim(@InterviewDate),
		@InterViewPlace = dbo.Trim(@InterViewPlace),
		@Telephone = dbo.Trim(@Telephone)

	INSERT INTO ExInterView(JobID, cvMainID, InterviewDate, InterViewPlace, LinkMan, Telephone, Remark)
	VALUES(@JobID, @cvMainID, @InterviewDate, @InterViewPlace, @LinkMan, @Telephone, @Remark)
	SET @ExInterViewID = @@IDENTITY
	
	--未答复的修改答复状态
	UPDATE exJobApply SET Reply =1,ReplyDate=GETDATE() WHERE JobID = @JobID AND CvMainID = @cvMainID

	BEGIN TRY
		SELECT @paMainId = paMainId FROM cvMain WITH(NOLOCK) WHERE Id = @cvMainId
		SELECT @wxFansId = id FROM wxFans WITH(NOLOCK) WHERE paMainId = @paMainId AND [Status] = 2
		IF @wxFansId IS NOT NULL--关注的用户发送微信消息提醒
		BEGIN			
			--插入到wxMessageSend表中
			INSERT INTO WxMessageSend2(Templatetype, WxFansID, PaMainId, MainTableId, CpMainID, CvMainID, JobId, CaMainId, AddDate)
			SELECT 1, @wxFansId, @paMainId, @ExInterViewID, @cpMainId, @cvMainID, @JobId, @caMainID, GETDATE()
		END
		
		IF @SendSms > 0 --发送短信
		BEGIN
			--获取剩余可用短信量 
			--优先取主订单id
			DECLARE @orderId INT --订单id

			SELECT TOP 1 @orderId = id
			FROM caOrder 
			WHERE cpMainId = @cpMainId
			AND RemainSmsQuota > 0 
			AND OrderType IN (8,14)
			AND OpenDate IS NOT NULL  
			AND BeginDate< GETDATE() 
			AND EndDate > GETDATE()  
			AND IsDeleted = 0
			ORDER BY ID
				
			IF ISNULL(@orderId, 0)>0 
			BEGIN
				DECLARE @smsLogId INT, @msg VARCHAR(400), @mobile CHAR(11)
					
				SELECT @mobile = Mobile, @msg = ISNULL(Name, '') 
				FROM paMain WITH(NOLOCK)
				WHERE ID = @paMainId  
				AND Mobile > ''
				AND IsReceiveSms = 1
					
				IF ISNULL(@mobile, '') <> ''
				BEGIN					
					SELECT @msg = @msg +'你好，' + d.Name +'在' + c.SubSiteName + c.EmailSite + '给您发了面试通知，面试职位：'+ @JobName +'，面试时间：' + @InterviewDate +
						'，地点：' + @InterViewPlace + '，联系电话：' + @Telephone + '。'
					FROM dcSubSite c WITH(NOLOCK), cpMain d WITH(NOLOCK)
					WHERE d.dcProvinceID = c.ID
					AND d.ID = @cpMainID						 
						
					INSERT SmsMessageLog(SendMan, ManagerUSerId, paMainId, caMainId, Mobile, MsgType, IsCat, Msg)
					SELECT 0, NULL, @paMainId, @caMainID, @mobile, 101, 0, @msg						 
						
					SET @smsLogId = @@IDENTITY

					--短信-1
					UPDATE caOrder set RemainSmsQuota = RemainSmsQuota-1 WHERE id = @orderId
						
					--插入消耗记录
					INSERT INTO casmslog(caOrderId,	cvMainId, caMainId, Mobile, MsgType, RelationId, SmsMessageLogId, SendStatus, SendDate, Msg, AddDate)
					SELECT @orderId, @cvMainID, @caMainID, @mobile, 101, @ExInterViewID, @smsLogId, NULL, NULL, @msg,GETDATE()

					UPDATE ExInterView SET SmsNumber = ISNULL(SmsNumber, 0) + 1 WHERE ID = @ExInterViewID			
				END 
			END
		END 
		
		INSERT INTO paPushLog(paMainID, PushMessage, PushType)
		SELECT @paMainId, '亲，收到一份面试通知！', 2 WHERE EXISTS(SELECT 'X' FROM paIOSBind WHERE paMainID = @paMainId)
	END TRY
	BEGIN CATCH
	END CATCH
	
	--插入积分记录
	BEGIN TRY
		--插入积分记录
		DECLARE @TodayPoint AS INT, @TodayID AS INT, @JobApplyID INT,@Reply INT
		SELECT @TodayPoint = 0, @TodayID = 0
		SELECT TOP 1 @TodayPoint = ISNULL(Point,0),@TodayID = ISNULL(ID,0) FROM cpPoint WITH(NOLOCK) WHERE changeID = 4 AND LastModifyDate > CONVERT(VARCHAR(10), GETDATE(),120) AND cpMainID = @cpMainID
		
--		--判断是否是应聘的简历
--		SELECT @JobApplyID = 0, @Reply = 0
--
--		SELECT @JobApplyID = ID, @Reply = Reply 
--		FROM ExJobApply WITH(NOLOCK)
--		WHERE JobID = @JobID
--		AND CvMainID = @cvMainID

--		IF @JobApplyID = 0	--未应聘
--		BEGIN
--			SET @TodayPoint = @ReplyInterviewPoint
--		END
--		ELSE 
--		BEGIN
--			IF @Reply = 0
--			BEGIN
--				UPDATE ExJobApply 
--				SET Reply = 1
--				WHERE ID = @JobApplyID
--
--				SET @TodayPoint = @InterviewPoint
--			END
--			ELSE
--			BEGIN
--				SET @TodayPoint = @ReplyInterviewPoint
--			END
--		END

		SET @TodayPoint = @TodayPoint + @ReplyInterviewPoint
		
		IF @TodayPoint <= 200
		BEGIN
			IF @TodayID = 0
			BEGIN
				INSERT INTO cpPoint (cpMainID,ChangeID,Point,LastModifyDate) VALUES(@cpMainID,4,@TodayPoint,GETDATE())
			END
			ELSE
			BEGIN
				UPDATE cpPoint SET Point = Point + @TodayPoint,LastModifyDate = GETDATE() WHERE ID = @TodayID 
			END
		END		
	END TRY
	BEGIN CATCH
	END CATCH 
END
SET NOCOUNT OFF
GO
/****** Object:  StoredProcedure [dbo].[ccExInterViewByOneWeekSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[ccExInterViewByOneWeekSelect]
(
	@caMainID INT
)
AS
BEGIN
	BEGIN TRY
		DECLARE @return INT
		SELECT @return = COUNT(1) FROM exInterView WITH(NOLOCK) 
		WHERE AddDate > DATEADD(week,-1,GETDATE())
		AND JobID IN (SELECT ID FROM Job WITH(NOLOCK) WHERE caMainID = @caMainID)
		RETURN @return
	END TRY
	BEGIN CATCH
		RETURN 0
	END CATCH
END














GO
/****** Object:  StoredProcedure [dbo].[ccExInterViewInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*#######################################
---面试通知
2012-10-23 sean
update msgcount from smsmessagelog
2014-08-25 Peter
添加积分记录
---2015-8-27 Harry
---增加将绑定关注微信的，插入到wxsendmessage表中
--修改Harry2017-4-17
#######################################*/
CREATE PROCEDURE [dbo].[ccExInterViewInsert]
(
    @JobID INT, 
    @cpMainID INT, 
    @cvMainID INT, 
    @InterviewDate VARCHAR(100), 
    @InterViewPlace VARCHAR(200), 
    @LinkMan VARCHAR(12), 
    @Telephone VARCHAR(20), 
    @Remark VARCHAR(1000)
)
AS
SET NOCOUNT ON
BEGIN
    SET NOCOUNT ON
    DECLARE @caMainID INT, @paMainId INT, @ExInterViewID INT, @wxFansId INT, @MsgCount INT
    SELECT @caMainID = caMainId FROM Job WITH(NOLOCK) WHERE ID = @JobID AND cpMainID = @cpMainID
    IF ISNULL(@caMainID, 0) = 0
        RETURN -1

    SELECT @Remark = dbo.TrimNull(@Remark),
        @InterviewDate = dbo.Trim(@InterviewDate),
        @InterViewPlace = dbo.Trim(@InterViewPlace),
        @Telephone = dbo.Trim(@Telephone)

    INSERT INTO ExInterView(JobID, cvMainID, InterviewDate, InterViewPlace, LinkMan, Telephone, Remark)
    VALUES(@JobID, @cvMainID, @InterviewDate, @InterViewPlace, @LinkMan, @Telephone, @Remark)
    SET @ExInterViewID = @@IDENTITY
    
    BEGIN TRY
        SELECT @paMainId = paMainId FROM cvMain WITH(NOLOCK) WHERE Id = @cvMainId
    
        SELECT @MsgCount = SUM(smsNumber) FROM ExInterView WITH(NOLOCK)
        WHERE JobId IN(SELECT ID FROM Job WITH(NOLOCK) WHERE cpMainId = @cpMainID)
        AND AddDate > CONVERT(VARCHAR(10), GETDATE() - 29, 120)

        IF @MsgCount < 45
        BEGIN
            INSERT SmsMessageLog(SendMan, ManagerUSerId, paMainId, caMainId, Mobile, MsgType, IsCat, Msg)
            SELECT 0, NULL, b.ID, @caMainID, b.Mobile, 101, 0, 
                ISNULL(b.Name,'') +'，'+ d.Name +'在'+ c.SubSiteName + c.EmailSite +'上邀请您面试，请登录网站查看'
            FROM cvMain a WITH(NOLOCK), paMain b WITH(NOLOCK), dcSubSite c WITH(NOLOCK),cpMain d WITH(NOLOCK)
            WHERE a.paMainID = b.ID
            AND b.dcSubSiteID = c.ID
            AND d.ID = @cpMainID
            AND b.Mobile > ''
            AND a.ID = @cvMainID
            AND b.IsReceiveSms = 1

            UPDATE ExInterView SET SmsNumber = ISNULL(SmsNumber, 0) + 1 WHERE ID = @ExInterViewID
        END
        ELSE        --关注的用户发送微信消息提醒        
        BEGIN
            SELECT @wxFansId = id FROM wxFans WITH(NOLOCK) WHERE paMainId = @paMainId AND [Status] = 2
            IF @wxFansId > 0
                --插入到wxMessageSend表中
                INSERT WxMessageSend2(Templatetype, WxFansID, PaMainId, MainTableId, CpMainID, CvMainID, JobId, CaMainId, AddDate)
                SELECT 1, @wxFansId, @paMainId, @ExInterViewID, @cpMainId, @cvMainID, @JobId, @caMainID, GETDATE()
        END
    END TRY
    BEGIN CATCH
    END CATCH
    
    --插入积分记录
    BEGIN TRY
    --插入积分记录
        DECLARE @TodayPoint AS INT
        DECLARE @TodayID AS INT
        SET @TodayPoint = 0
        SET @TodayID = 0
        SELECT TOP 1 @TodayPoint = ISNULL(Point,0),@TodayID = ISNULL(ID,0) FROM cpPoint WITH(NOLOCK) WHERE changeID = 4 AND LastModifyDate > CONVERT(VARCHAR(10), GETDATE(),120) AND cpMainID = @cpMainID
        
        SET @TodayPoint = @TodayPoint + 10
        
        IF @TodayPoint <= 200
        BEGIN
            IF @TodayID = 0
            BEGIN
                INSERT INTO cpPoint (cpMainID,ChangeID,Point,LastModifyDate) VALUES(@cpMainID,4,2,GETDATE())
            END
            ELSE
            BEGIN
                UPDATE cpPoint SET Point = @TodayPoint,LastModifyDate = GETDATE() WHERE ID = @TodayID 
            END
        END    
        
    END TRY
    BEGIN CATCH
    END CATCH
--    RETURN @Return
    RETURN ISNULL(@MsgCount, 0)
END

GO
/****** Object:  StoredProcedure [dbo].[ccExInterviewSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
---修改Harry 2017-6-7 增加显示短信订单内容
CREATE PROCEDURE [dbo].[ccExInterviewSelect]
(
	@WHERE VARCHAR(1000), 
	@Order VARCHAR(100), 
	@page SMALLINT, 
	@caMainID INT, 
	@cpMainID INT
)
AS
SET NOCOUNT ON
BEGIN
	SET @WHERE = dbo.SafeSQL(@WHERE)
	SET @ORDER = dbo.SafeSQL(@ORDER)
	CREATE TABLE #T(
		TitleID BIGINT, 
		ID INT, 
		JobID INT, 
		JobName NVARCHAR(50) COLLATE Chinese_PRC_CI_AS NULL, 
		JobRegion VARCHAR(6) NULL, 
		IsJobDelete BIT NULL, 
		cvMainID INT, 
		InterviewDate VARCHAR(100) COLLATE Chinese_PRC_CI_AS NULL, 
		InterviewPlace NVARCHAR(200), 
		LinkMan NVARCHAR(40), 
		Telephone VARCHAR(30) COLLATE Chinese_PRC_CI_AS NULL, 
		Remark VARCHAR(1000) COLLATE Chinese_PRC_CI_AS NULL, 
		AddDate SMALLDATETIME, 
		Reply TINYINT, 
		ReplyMessage VARCHAR(500) COLLATE Chinese_PRC_CI_AS NULL, 
		Degree TINYINT, 
		RelatedWorkYears TINYINT, 
		Attachment VARCHAR(50) COLLATE Chinese_PRC_CI_AS NULL, 
		IsNameHidden BIT, 
		LivePlace VARCHAR(6) COLLATE Chinese_PRC_CI_AS NULL, 
		Gender BIT, 
		paName NVARCHAR(20), 
		BirthDay INT, 
		HasPhoto TINYINT, 
		Valid TINYINT, 
		IsViewed BIT, 
		HasJobApply BIT, 
		HasFavorate BIT, 
		HasRemark BIT, 
		Result BIT, 
		ResultDate SMALLDATETIME, 
		MobileVerifyDate SMALLDATETIME, 
		IsOnline BIT, 
		SmsMsg NVARCHAR(210) NULL, --短信内容
		paMainID INT, 
		SecondId VARCHAR(10)
	)

	DECLARE @SQL AS VARCHAR(2000)
	SET @SQL='
		INSERT INTO #T(TitleID, ID, JobID, cvMainID, InterviewDate, InterviewPlace, LinkMan, 
			Telephone, Remark, AddDate, Reply, ReplyMessage, Result, ResultDate, IsOnline, paMainId, SecondId)
		SELECT ROW_NUMBER() OVER (ORDER BY ' + @ORDER + ') AS TitleID, a.ID, a.JobID, a.cvMainID, 
			a.InterviewDate, a.InterviewPlace, a.LinkMan, a.Telephone, a.Remark, a.AddDate, a.Reply, a.ReplyMessage, 
			a.Result, a.ResultDate, dbo.GetPaOnlineStatus(c.ID), b.paMainId, b.SecondId
		FROM exInterview a WITH(NOLOCK)
		INNER JOIN cvMain b WITH(NOLOCK) ON b.ID = a.cvMainID
		INNER JOIN paMain c WITH(NOLOCK) ON c.ID = b.paMainID
		WHERE a.JobID IN(SELECT id FROM Job WITH(NOLOCK) WHERE cpMainID = ' + CONVERT(VARCHAR,@cpMainID) + ') '
	
	SET @SQL = @SQL + ' AND CompanyDeleted=0'

	IF LEN(@WHERE) > 0
	BEGIN
		SET @Where = dbo.SafeSql(@Where)
		SET @SQL = @SQL + @WHERE
	END
	--PRINT @SQL
	EXEC(@SQL)

	IF(@Page < 1)
		SET @Page = 1
	
	UPDATE #T SET Degree = a.Degree, RelatedWorkYears = a.RelatedWorkYears, Attachment = a.Attachment, 
		IsNameHidden = a.IsNameHidden, LivePlace = b.LivePlace, Gender = b.Gender, paName = b.Name, 
		BirthDay = b.BirthDay, HasPhoto = b.HasPhoto, Valid = a.Valid, MobileVerifyDate = b.MobileVerifyDate
	FROM cvMain a WITH(NOLOCK) INNER JOIN paMain b WITH(NOLOCK) ON a.paMainID = b.ID
	WHERE a.ID = #T.cvMainID AND TitleID > (@Page-1)*20 AND TitleID <= @Page*20

	UPDATE #T SET paName = LEFT(dbo.GetPersonName(cvMainID, @cpMainID), 20), 
		IsViewed = (SELECT TOP 1 '1' FROM caCvViewLog WITH(NOLOCK) WHERE cvMainID=#T.cvMainID AND caMainID=@caMainID), 
		HasJobApply = (SELECT TOP 1 '1' FROM exJobApply a WITH(NOLOCK) INNER JOIN Job b WITH(NOLOCK) ON a.JobID=b.ID WHERE a.CompanyDeleted=0 AND b.caMainID=@caMainID AND cvMainID=#T.cvMainID), 
		HasFavorate = (SELECT TOP 1 '1' FROM caFavorate WITH(NOLOCK) WHERE caMainID=@caMainID AND cvMainID=#T.cvMainID), 
		HasRemark = (SELECT TOP 1 '1' FROM caCvRemark WITH(NOLOCK) WHERE caMainID=@caMainID AND cvMainID=#T.cvMainID), 
		SmsMsg = (SELECT TOP 1 Msg FROM casmslog WITH(NOLOCK) WHERE MsgType = 101 AND RelationId = #T.ID)
	WHERE TitleID > (@Page-1)*20 AND TitleID <= @Page*20
	
	UPDATE #T SET JobName = a.Name, JobRegion= a.dcRegionID, IsJobDelete = IsDelete
	FROM Job a WITH(NOLOCK)
	WHERE #T.JobID = a.ID
	
	--修改查看状态
	UPDATE exInterview
	SET CpResultViewDate = GETDATE()
	WHERE JobID IN
	(
		SELECT ID FROM Job WITH(NOLOCK) 
		WHERE CpMainID = @cpMainID
		AND CaMainID = @caMainID
	) 
	AND CpResultViewDate IS NULL
	AND Replydate IS NOT NULL 
	
	SELECT COUNT(*) FROM #T WITH(NOLOCK)

	SELECT a.*, dbo.BirthToAge(a.BirthDay) Age, b.Description DegreeName, c.MapBarName LivePlaceName, d.Description JobRegionName
	FROM #T a WITH(NOLOCK) 
	LEFT JOIN dcEducation b WITH(NOLOCK) ON b.ID = a.Degree
	LEFT JOIN dcRegion c WITH(NOLOCK) ON c.ID = a.LivePlace
	LEFT JOIN dcRegion d WITH(NOLOCK) ON d.ID = a.JobRegion
	WHERE a.TitleID > (@Page-1)*20 AND a.TitleID <= @Page*20
	
	DROP TABLE #T
END
SET NOCOUNT OFF
GO
/****** Object:  StoredProcedure [dbo].[ccExJobApplyBatchDelete]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--Lambo 20101130 修改
-- 增加cpMainID 参数，只能删除本公司的
CREATE PROCEDURE [dbo].[ccExJobApplyBatchDelete]
(
	@AllID VARCHAR(1000),
	@cpMainID INT 
)
AS
BEGIN TRAN
	BEGIN TRY
		SET @AllID = dbo.FormatIDS(@AllID)
		DECLARE @T AS TABLE(ID INT)
		INSERT INTO @T SELECT * FROM dbo.fnSplit(@AllID, ',')
		
		INSERT INTO CaCvApplyDeleted(JobID,JobName,CvMainId,ApplyDate,AddDate,Reply)
		SELECT b.ID,b.Name,a.cvMainid,a.AddDate,GETDATE(),ISNULL(Reply,0) 
		FROM exjobapply a,job b 
		WHERE a.jobid = b.id 
		AND a.id in (SELECT id FROM @t)

		DELETE FROM ExJobApply WHERE PersonDeleted=1 AND ID IN(SELECT ID FROM @T)
		AND JobID IN (SELECT ID FROM Job WITH(NOLOCK) WHERE cpMainID = @cpMainID)
		
		UPDATE ExJobApply SET CompanyDeleted = 1, CompanyDeleteDate = GETDATE(),ReplyDate=GETDATE()
		WHERE Reply <> 0 AND ID IN(SELECT ID FROM @T)
		AND JobID IN (SELECT ID FROM Job WITH(NOLOCK) WHERE cpMainID = @cpMainID)
		
		UPDATE ExJobApply SET CompanyDeleted = 1, CompanyDeleteDate = GETDATE(), Reply = 4,ReplyDate=GETDATE()
		WHERE Reply = 0 AND ID IN(SELECT ID FROM @T)
		AND JobID IN (SELECT ID FROM Job WITH(NOLOCK) WHERE cpMainID = @cpMainID)
	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH
COMMIT TRAN
RETURN 1
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END
GO
/****** Object:  StoredProcedure [dbo].[ccExJobApplyByApplyCountSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------
--创建时间：2015.7.14
--创建人：Mice
--说明：查询申请数量（包括过滤和未过滤）
-------------------------------------------------------
CREATE PROCEDURE [dbo].[ccExJobApplyByApplyCountSelect]
(
	@JobID INT
)
AS
BEGIN
	SET NOCOUNT ON
	SELECT COUNT(ID) AS ApplyCount 
	FROM exJobApply WITH(NOLOCK) 
	WHERE JobID = @JobID 
	SET NOCOUNT OFF
END
GO
/****** Object:  StoredProcedure [dbo].[ccExJobApplyByCaMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



--Nick 20140821 修改
-- 加入修改应聘简历的查看日期viewdate
--20160107 
--加入是否绑定微信
--Carl 修改 自动答复的 应放到储备下面而不是 待答复下面
--carl 2018-2-26
--harry 2018-6-11 cpCvShield中的不显示
CREATE PROCEDURE [dbo].[ccExJobApplyByCaMainIDSelect] 
(
	@WHERE VARCHAR(1000), 
	@Order VARCHAR(100), 
	@Page SMALLINT, 
	@caMainID INT, 
	@ReplyType INT 
)
AS
SET NOCOUNT ON
BEGIN
	DECLARE @WHERE2 VARCHAR(MAX)
	IF @ReplyType = 5
	BEGIN
		SET @WHERE2 = ' And IsFilter = 0 AND Reply = 0 AND ViewDate IS NULL'
	END
	ELSE IF @ReplyType = 1
	BEGIN
		SET @WHERE2 = ' And IsFilter = 0 AND Reply = 0 AND ViewDate IS NOT NULL'
	END
	ELSE IF @ReplyType = 2
	BEGIN
		SET @WHERE2 = ' And IsFilter = 0 AND Reply = 1 AND ViewDate IS NOT NULL'
	END
	ELSE IF @ReplyType = 3
	BEGIN
		SET @WHERE2 = ' And IsFilter = 0 AND (Reply = 2 OR Reply = 5) AND ViewDate IS NOT NULL'
	END
	ELSE IF @ReplyType = 4
	BEGIN
		SET @WHERE2 = ' And IsFilter = 1 '	--AND ViewDate is null'
	END
	ELSE
		SET @WHERE2 = ' And IsFilter = 0'

	SET @Where = dbo.SafeSql(@Where)
	SET @ORDER = REPLACE(dbo.SafeSQL(@ORDER), '''', '''''')
	
	DECLARE @SQL AS VARCHAR(2000)
	CREATE TABLE #T(
		TitleID BIGINT, 
		ID INT, 
		JobID INT, 
		paMainID INT, 
		cvMainID INT, 
		AddDate SMALLDATETIME, 
		Reply TINYINT, 
		ReplyDate SMALLDATETIME, 
		IsMatched BIT, 
		Degree TINYINT, 
		RelatedWorkYears TINYINT, 
		LivePlace NVARCHAR(50), 
		Gender BIT, 
		paName NVARCHAR(20), 
		BirthDay INT, 
		HasPhoto TINYINT, 
		Attachment VARCHAR(50) COLLATE Chinese_PRC_CI_AS, 
		IsNameHidden BIT, 
		Valid TINYINT, 
		ApplyMessage NVARCHAR(1), 
		IsViewed BIT, 
		HasInterview BIT, 
		HasRemark BIT, 
		HasFavorate BIT, 
		cvEducationID INT, 
		College NVARCHAR(50), 
		EduType TINYINT, 
		MajorName NVARCHAR(20), 
		Graduation INT, 
		Speciality VARCHAR(MAX) COLLATE Chinese_PRC_CI_AS, 
		Experience VARCHAR(MAX) COLLATE Chinese_PRC_CI_AS, 
		cvMatch INT, 
		RecruitmentID INT, 
		RecruitmentName NVARCHAR(100), 
		RecruitmentDate SMALLDATETIME, 
		MobileVerifyDate SMALLDATETIME, 
		IsOnline BIT, 
		RemindDate DATETIME, 
		HasWeiXin BIT, 
		ReplyReason VARCHAR(200), 
		Accept BIT, 
		NoAccept BIT, 
		SecondId VARCHAR(10) 
	)
	SET @SQL='
		INSERT INTO #T(TitleID, ID, JobID, paMainID, cvMainID, AddDate, Reply, ReplyDate, IsMatched,
			ApplyMessage, Degree, RelatedWorkYears, Attachment, IsNameHidden, LivePlace, Gender, BirthDay,
			HasPhoto, Valid, RecruitmentID, MobileVerifyDate, IsOnline, RemindDate, ReplyReason, SecondId)
		SELECT ROW_NUMBER() OVER (ORDER BY ' + @ORDER + ') AS TitleID, a.ID, a.JobID, c.ID, a.cvMainID, 
			a.AddDate, a.Reply, a.ReplyDate, a.IsMatched, LEFT(a.ApplyMessage, 1) ApplyMessage, b.Degree,
			b.RelatedWorkYears, b.Attachment, b.IsNameHidden, c.LivePlace, c.Gender, c.BirthDay, c.HasPhoto,
			b.Valid, a.RecruitmentID, c.MobileVerifyDate, dbo.GetPaOnlineStatus(c.ID), a.RemindDate,
			a.ReplyReason, b.SecondId
		FROM exJobApply a WITH(NOLOCK)
		INNER JOIN cvMain b WITH(NOLOCK) ON b.ID = a.cvMainID
		INNER JOIN paMain c WITH(NOLOCK) ON c.ID = b.paMainID
		INNER JOIN Job d WITH(NOLOCK) ON d.ID = a.JobID
		WHERE a.CompanyDeleted = 0 AND d.IsDelete = 0 '
	IF LEN(@WHERE) > 0
		SET @SQL = @SQL + ' AND ' + @WHERE + @WHERE2

	--PRINT @SQL
	EXEC(@SQL)
	DECLARE @cpMainID AS INT
	SELECT @cpMainID = cpMainID FROM caMain WITH(NOLOCK) WHERE ID = @caMainID
	--删除在cpCvShield中的简历
        DELETE FROM #t
	WHERE cvMainId IN(select cvMainId FROM cpCvShield WHERE cpMainID=@cpMainID)

	IF(@Page < 1)
		SET @Page = 1
	IF NOT EXISTS(SELECT 'x' FROM #t WHERE TitleID > (@Page-1)*20 AND  TitleID <= @Page*20)
		SET @Page = 1
	
	
	UPDATE #T SET paName = LEFT(dbo.GetPersonName(cvMainID, @cpMainID), 20), IsViewed = (SELECT TOP 1 '1' FROM caCvViewLog WITH(NOLOCK) WHERE cvMainID=#T.cvMainID AND caMainID=@caMainID), 
		HasFavorate = (SELECT TOP 1 '1' FROM caFavorate WITH(NOLOCK) WHERE caMainID=@caMainID AND cvMainID=#T.cvMainID), 
		HasInterview = (SELECT TOP 1 '1' FROM exInterview a WITH(NOLOCK) INNER JOIN Job b WITH(NOLOCK) ON a.JobID=b.ID WHERE a.CompanyDeleted=0 AND b.caMainID=@caMainID AND cvMainID=#T.cvMainID), 
		HasRemark = (SELECT TOP 1 '1' FROM caCvRemark WITH(NOLOCK) WHERE caMainID=@caMainID AND cvMainID=#T.cvMainID)
	WHERE TitleID > (@Page-1)*20 AND  TitleID <= @Page*20

	IF EXISTS(SELECT TOP 1 'X' FROM caMain WHERE ID = @caMainID AND AccountType = 1)
	BEGIN
		UPDATE #T SET
		HasInterview = (SELECT TOP 1 '1' FROM exInterview a WITH(NOLOCK) INNER JOIN Job b WITH(NOLOCK) ON a.JobID=b.ID WHERE a.CompanyDeleted=0 AND b.cpMainID=@cpMainID AND cvMainID=#T.cvMainID)
		WHERE TitleID > (@Page-1)*20 AND  TitleID <= @Page*20
	END

	UPDATE #T 
	SET	Accept = (SELECT TOP 1 '1' FROM exInterview a WITH(NOLOCK) WHERE a.CompanyDeleted=0 AND a.JobID = #t.JobId AND a.cvMainID = #T.cvMainID AND a.Reply = 1), 
		NoAccept = (SELECT TOP 1 '1' FROM exInterview a WITH(NOLOCK) WHERE a.CompanyDeleted=0 AND a.JobID = #t.JobId AND a.cvMainID = #T.cvMainID AND a.Reply > 1)
	WHERE TitleID > (@Page-1)*20 AND  TitleID <= @Page*20
	AND HasInterview = 1

	UPDATE #T SET Speciality = (
		SELECT Speciality FROM cvMain WITH(NOLOCK)
		WHERE cvMain.ID = #T.cvMainID)
	WHERE TitleID > (@Page-1)*20 AND  TitleID <= @Page*20
	
	UPDATE #T SET Experience = (
		SELECT TOP 1 ISNULL(Description, DescriptionEng) FROM cvExperience WITH(NOLOCK)
		WHERE cvExperience.cvMainID = #T.cvMainID
		ORDER BY BeginDate DESC)
	WHERE TitleID > (@Page-1)*20 AND  TitleID <= @Page*20

	UPDATE #T SET cvEducationID = (
		SELECT TOP 1 ID FROM cvEducation WITH(NOLOCK)
		WHERE cvEducation.cvMainID = #T.cvMainID
		AND #T.Degree = cvEducation.Degree
		ORDER BY Graduation DESC)
	WHERE TitleID > (@Page-1)*20 AND  TitleID <= @Page*20

	--修改是否绑定微信
	UPDATE a SET HasWeiXin = 1
	FROM #T a, WxFans b WITH(NOLOCK)
	WHERE a.paMainID = b.PaMainID
	AND b.Status = 2
	AND a.TitleID > (@Page-1)*20 AND  TitleID <= @Page*20

	UPDATE a SET a.College = ISNULL(b.GraduateCollage, b.GraduateCollageEng), a.EduType = b.EduType, 
		a.MajorName = ISNULL(b.MajorName, b.MajorNameEng), a.Graduation = b.Graduation
	FROM #T a, cvEducation b WITH(NOLOCK)
	WHERE b.ID = a.cvEducationID AND a.TitleID > (@Page-1)*20 AND a. TitleID <= @Page*20
	
	UPDATE a SET a.RecruitmentName = b.RecruitmentName, a.RecruitmentDate = b.EndDate
	FROM #T a, Recruitment b WITH(NOLOCK)
	WHERE b.ID = a.RecruitmentID AND a.TitleID > (@Page-1)*20 AND a. TitleID <= @Page*20
	
	UPDATE #T SET cvMatch = dbo.GetCvMatch(cvMainID, JobID) WHERE TitleID > (@Page-1)*20 AND  TitleID <= @Page*20

	SELECT COUNT(*) FROM #T WITH(NOLOCK)
	SELECT * FROM #T WITH(NOLOCK) WHERE TitleID > (@Page-1)*20 AND  TitleID <= @Page*20

	DECLARE @NoViewCnt INT, @NoReply INT, @ReplyYes INT, @ReplyNo INT, @SQL2 NVARCHAR(4000), @Filter INT

	--未查看数量
	SET @SQL2 = '
	SELECT @NoViewCnt1 = COUNT(*) 
	FROM exJobApply a WITH(NOLOCK)
	INNER JOIN cvMain b WITH(NOLOCK) ON b.ID = a.cvMainID
	INNER JOIN paMain c WITH(NOLOCK) ON c.ID = b.paMainID
	INNER JOIN Job d WITH(NOLOCK) ON d.ID = a.JobID
	WHERE a.CompanyDeleted = 0 AND d.IsDelete = 0
	And a.IsFilter = 0
	AND a.Reply=0 
	AND a.ViewDate is null AND ' + @WHERE
	EXEC SP_EXECUTESQL  @SQL2, N'@NoViewCnt1 int OUTPUT', @NoViewCnt OUTPUT

	--待答复数量
	SET @SQL2 = '
	SELECT @NoReply1 = COUNT(*) 
	FROM exJobApply a WITH(NOLOCK)
	INNER JOIN cvMain b WITH(NOLOCK) ON b.ID = a.cvMainID
	INNER JOIN paMain c WITH(NOLOCK) ON c.ID = b.paMainID
	INNER JOIN Job d WITH(NOLOCK) ON d.ID = a.JobID
	WHERE a.CompanyDeleted = 0 
	AND d.IsDelete = 0
	And a.IsFilter = 0
	AND Reply=0
	AND ViewDate IS NOT NULL
	AND ' + @WHERE
	EXEC SP_EXECUTESQL @SQL2, N'@NoReply1 int OUTPUT', @NoReply OUTPUT

	--符合要求数量
	SET @SQL2 = '
	SELECT @ReplyYes1 = COUNT(*) 
	FROM exJobApply a WITH(NOLOCK)
	INNER JOIN cvMain b WITH(NOLOCK) ON b.ID = a.cvMainID
	INNER JOIN paMain c WITH(NOLOCK) ON c.ID = b.paMainID
	INNER JOIN Job d WITH(NOLOCK) ON d.ID = a.JobID
	WHERE a.CompanyDeleted = 0 AND d.IsDelete = 0
	And a.IsFilter = 0
    AND Reply=1 
	AND ' + @WHERE
	EXEC SP_EXECUTESQL  @SQL2, N'@ReplyYes1 int OUTPUT', @ReplyYes OUTPUT

	--不符合要求数量
	SET @SQL2 = ' SELECT @ReplyNo1 = COUNT(*) 
	FROM exJobApply a WITH(NOLOCK)
	INNER JOIN cvMain b WITH(NOLOCK) ON b.ID = a.cvMainID
	INNER JOIN paMain c WITH(NOLOCK) ON c.ID = b.paMainID
	INNER JOIN Job d WITH(NOLOCK) ON d.ID = a.JobID
	WHERE a.CompanyDeleted = 0 AND d.IsDelete = 0
	And a.IsFilter = 0
    AND Reply IN(2, 5) AND ' + @WHERE
	EXEC SP_EXECUTESQL  @SQL2, N'@ReplyNo1 int OUTPUT', @ReplyNo OUTPUT


	--未查看数量
	SET @SQL2 = '
	SELECT @Filter1 = COUNT(*) 
	FROM exJobApply a WITH(NOLOCK)
	INNER JOIN cvMain b WITH(NOLOCK) ON b.ID = a.cvMainID
	INNER JOIN paMain c WITH(NOLOCK) ON c.ID = b.paMainID
	INNER JOIN Job d WITH(NOLOCK) ON d.ID = a.JobID
	WHERE a.CompanyDeleted = 0 AND d.IsDelete = 0
	And a.IsFilter = 1
	AND ' + @WHERE
	EXEC SP_EXECUTESQL  @SQL2, N'@Filter1 int OUTPUT', @Filter OUTPUT

	--计算匹配度
	SELECT @NoViewCnt AS NoViewCnt, @NoReply AS NoReply, @ReplyYes AS ReplyYes, @ReplyNo AS ReplyNo, @Filter AS FilterCnt

	--修改 已查看提醒时间
	UPDATE ExJobApply
	SET CpRemindViewDate = GETDATE()
	WHERE JobID IN (
		SELECT ID FROM JOB WITH(NOLOCK)
		WHERE CaMainID  = @caMainID 
	) AND RemindDate IS NOT NULL
	AND CpRemindViewDate IS NULL

	DROP TABLE #T
END



GO
/****** Object:  StoredProcedure [dbo].[ccExJobApplyByCaMainIDSelect2]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--Nick 20140821 修改
-- 加入修改应聘简历的查看日期viewdate
--20160107 
--加入是否绑定微信
CREATE PROCEDURE [dbo].[ccExJobApplyByCaMainIDSelect2] 
(
	@WHERE VARCHAR(1000), 
	@Order VARCHAR(100), 
	@Page SMALLINT, 
	@caMainID INT, 
	@ReplyType INT 
)
AS
SET NOCOUNT ON
BEGIN
	DECLARE @WHERE2 VARCHAR(MAX)
	IF @ReplyType = 5
	BEGIN
		SET @WHERE2 = ' And IsFilter = 0 AND Reply = 0 AND ViewDate IS NULL'
	END
	ELSE IF @ReplyType = 1
	BEGIN
		SET @WHERE2 = ' And IsFilter = 0 AND (Reply = 0 OR Reply = 5) AND ViewDate IS NOT NULL'
	END
	ELSE IF @ReplyType = 2
	BEGIN
		SET @WHERE2 = ' And IsFilter = 0 AND Reply = 1 AND ViewDate IS NOT NULL'
	END
	ELSE IF @ReplyType = 3
	BEGIN
		SET @WHERE2 = ' And IsFilter = 0 AND Reply = 2 AND ViewDate IS NOT NULL'
	END
	ELSE IF @ReplyType = 4
	BEGIN
		SET @WHERE2 = ' And IsFilter = 1 '	--AND ViewDate is null'
	END
	ELSE
		SET @WHERE2 = ' And IsFilter = 0'

	SET @Where = dbo.SafeSql(@Where)
	SET @ORDER = REPLACE(dbo.SafeSQL(@ORDER), '''', '''''')
	
	DECLARE @SQL AS VARCHAR(2000)
	CREATE TABLE #T(
		TitleID BIGINT, 
		ID INT, 
		JobID INT, 
		paMainID INT, 
		cvMainID INT, 
		AddDate SMALLDATETIME, 
		Reply TINYINT, 
		ReplyDate SMALLDATETIME, 
		IsMatched BIT, 
		Degree TINYINT, 
		RelatedWorkYears TINYINT, 
		LivePlace NVARCHAR(50), 
		Gender BIT, 
		paName NVARCHAR(20), 
		BirthDay INT, 
		HasPhoto TINYINT, 
		Attachment VARCHAR(50) COLLATE Chinese_PRC_CI_AS, 
		IsNameHidden BIT, 
		Valid TINYINT, 
		ApplyMessage NVARCHAR(1), 
		IsViewed BIT, 
		HasInterview BIT, 
		HasRemark BIT, 
		HasFavorate BIT, 
		cvEducationID INT, 
		College NVARCHAR(50), 
		EduType TINYINT, 
		MajorName NVARCHAR(20), 
		Graduation INT, 
		Speciality VARCHAR(MAX) COLLATE Chinese_PRC_CI_AS, 
		Experience VARCHAR(MAX) COLLATE Chinese_PRC_CI_AS, 
		cvMatch INT, 
		RecruitmentID INT, 
		RecruitmentName NVARCHAR(100), 
		RecruitmentDate SMALLDATETIME, 
		MobileVerifyDate SMALLDATETIME, 
		IsOnline BIT, 
		RemindDate DATETIME, 
		HasWeiXin BIT, 
		ReplyReason VARCHAR(200), 
		Accept BIT, 
		NoAccept BIT, 
		SecondId VARCHAR(10)
	)
	SET @SQL='
		INSERT INTO #T(TitleID, ID, JobID, paMainID, cvMainID, AddDate, Reply, ReplyDate, IsMatched,
			ApplyMessage, Degree, RelatedWorkYears, Attachment, IsNameHidden, LivePlace, Gender, BirthDay,
			HasPhoto, Valid, RecruitmentID, MobileVerifyDate, IsOnline, RemindDate, ReplyReason, SecondId)
		SELECT ROW_NUMBER() OVER (ORDER BY ' + @ORDER + ') AS TitleID, a.ID, a.JobID, c.ID, a.cvMainID, 
			a.AddDate, a.Reply, a.ReplyDate, a.IsMatched, LEFT(a.ApplyMessage, 1) ApplyMessage, b.Degree,
			b.RelatedWorkYears, b.Attachment, b.IsNameHidden, c.LivePlace, c.Gender, c.BirthDay, c.HasPhoto,
			b.Valid, a.RecruitmentID, c.MobileVerifyDate, dbo.GetPaOnlineStatus(c.ID), a.RemindDate,
			a.ReplyReason, b.SecondId
		FROM exJobApply a WITH(NOLOCK)
		INNER JOIN cvMain b WITH(NOLOCK) ON b.ID = a.cvMainID
		INNER JOIN paMain c WITH(NOLOCK) ON c.ID = b.paMainID
		INNER JOIN Job d WITH(NOLOCK) ON d.ID = a.JobID
		WHERE a.CompanyDeleted = 0 AND d.IsDelete = 0'
	IF LEN(@WHERE) > 0
		SET @SQL = @SQL + ' AND ' + @WHERE + @WHERE2

	EXEC(@SQL)
	
	IF(@Page < 1)
		SET @Page = 1
	IF NOT EXISTS(SELECT 'x' FROM #t WHERE TitleID > (@Page-1)*20 AND  TitleID <= @Page*20)
		SET @Page = 1
	
	DECLARE @cpMainID AS INT
	SELECT @cpMainID = cpMainID FROM caMain WITH(NOLOCK) WHERE ID = @caMainID
	UPDATE #T SET paName = LEFT(dbo.GetPersonName(cvMainID, @cpMainID), 20), IsViewed = (SELECT TOP 1 '1' FROM caCvViewLog WITH(NOLOCK) WHERE cvMainID=#T.cvMainID AND caMainID=@caMainID), 
		HasFavorate = (SELECT TOP 1 '1' FROM caFavorate WITH(NOLOCK) WHERE caMainID=@caMainID AND cvMainID=#T.cvMainID), 
		HasInterview = (SELECT TOP 1 '1' FROM exInterview a WITH(NOLOCK) INNER JOIN Job b WITH(NOLOCK) ON a.JobID=b.ID WHERE a.CompanyDeleted=0 AND b.caMainID=@caMainID AND cvMainID=#T.cvMainID), 
		HasRemark = (SELECT TOP 1 '1' FROM caCvRemark WITH(NOLOCK) WHERE caMainID=@caMainID AND cvMainID=#T.cvMainID)
	WHERE TitleID > (@Page-1)*20 AND  TitleID <= @Page*20

	IF EXISTS(SELECT TOP 1 'X' FROM caMain WHERE ID = @caMainID AND AccountType = 1)
	BEGIN
		UPDATE #T SET
		HasInterview = (SELECT TOP 1 '1' FROM exInterview a WITH(NOLOCK) INNER JOIN Job b WITH(NOLOCK) ON a.JobID=b.ID WHERE a.CompanyDeleted=0 AND b.cpMainID=@cpMainID AND cvMainID=#T.cvMainID)
		WHERE TitleID > (@Page-1)*20 AND  TitleID <= @Page*20
	END

	UPDATE #T 
	SET	Accept = (SELECT TOP 1 '1' FROM exInterview a WITH(NOLOCK) WHERE a.CompanyDeleted=0 AND a.JobID = #t.JobId AND a.cvMainID = #T.cvMainID AND a.Reply = 1), 
		NoAccept = (SELECT TOP 1 '1' FROM exInterview a WITH(NOLOCK) WHERE a.CompanyDeleted=0 AND a.JobID = #t.JobId AND a.cvMainID = #T.cvMainID AND a.Reply > 1)
	WHERE TitleID > (@Page-1)*20 AND  TitleID <= @Page*20
	AND HasInterview = 1

	UPDATE #T SET Speciality = (
		SELECT Speciality FROM cvMain WITH(NOLOCK)
		WHERE cvMain.ID = #T.cvMainID)
	WHERE TitleID > (@Page-1)*20 AND  TitleID <= @Page*20
	
	UPDATE #T SET Experience = (
		SELECT TOP 1 ISNULL(Description, DescriptionEng) FROM cvExperience WITH(NOLOCK)
		WHERE cvExperience.cvMainID = #T.cvMainID
		ORDER BY BeginDate DESC)
	WHERE TitleID > (@Page-1)*20 AND  TitleID <= @Page*20

	UPDATE #T SET cvEducationID = (
		SELECT TOP 1 ID FROM cvEducation WITH(NOLOCK)
		WHERE cvEducation.cvMainID = #T.cvMainID
		AND #T.Degree = cvEducation.Degree
		ORDER BY Graduation DESC)
	WHERE TitleID > (@Page-1)*20 AND  TitleID <= @Page*20

	--修改是否绑定微信
	UPDATE a SET HasWeiXin = 1
	FROM #T a, WxFans b WITH(NOLOCK)
	WHERE a.paMainID = b.PaMainID
	AND b.Status = 2
	AND a.TitleID > (@Page-1)*20 AND  TitleID <= @Page*20

	UPDATE a SET a.College = ISNULL(b.GraduateCollage, b.GraduateCollageEng), a.EduType = b.EduType, 
		a.MajorName = ISNULL(b.MajorName, b.MajorNameEng), a.Graduation = b.Graduation
	FROM #T a, cvEducation b WITH(NOLOCK)
	WHERE b.ID = a.cvEducationID AND a.TitleID > (@Page-1)*20 AND a. TitleID <= @Page*20
	
	UPDATE a SET a.RecruitmentName = b.RecruitmentName, a.RecruitmentDate = b.EndDate
	FROM #T a, Recruitment b WITH(NOLOCK)
	WHERE b.ID = a.RecruitmentID AND a.TitleID > (@Page-1)*20 AND a. TitleID <= @Page*20
	
	UPDATE #T SET cvMatch = dbo.GetCvMatch(cvMainID, JobID) WHERE TitleID > (@Page-1)*20 AND  TitleID <= @Page*20

	SELECT COUNT(*) FROM #T WITH(NOLOCK)
	SELECT * FROM #T WITH(NOLOCK) WHERE TitleID > (@Page-1)*20 AND  TitleID <= @Page*20

	DECLARE @NoViewCnt INT, @NoReply INT, @ReplyYes INT, @ReplyNo INT, @SQL2 NVARCHAR(4000), @Filter INT

	--未查看数量
	SET @SQL2 = '
	SELECT @NoViewCnt1 = COUNT(*) 
	FROM exJobApply a WITH(NOLOCK)
	INNER JOIN cvMain b WITH(NOLOCK) ON b.ID = a.cvMainID
	INNER JOIN paMain c WITH(NOLOCK) ON c.ID = b.paMainID
	INNER JOIN Job d WITH(NOLOCK) ON d.ID = a.JobID
	WHERE a.CompanyDeleted = 0 AND d.IsDelete = 0
	And a.IsFilter = 0
	AND a.Reply=0 
	AND a.ViewDate is null AND ' + @WHERE
	EXEC SP_EXECUTESQL  @SQL2, N'@NoViewCnt1 int OUTPUT', @NoViewCnt OUTPUT

	--待答复数量
	SET @SQL2 = '
	SELECT @NoReply1 = COUNT(*) 
	FROM exJobApply a WITH(NOLOCK)
	INNER JOIN cvMain b WITH(NOLOCK) ON b.ID = a.cvMainID
	INNER JOIN paMain c WITH(NOLOCK) ON c.ID = b.paMainID
	INNER JOIN Job d WITH(NOLOCK) ON d.ID = a.JobID
	WHERE a.CompanyDeleted = 0 
	AND d.IsDelete = 0
	And a.IsFilter = 0
	AND (Reply=0 OR Reply = 5)
	AND ViewDate IS NOT NULL
	AND ' + @WHERE
	EXEC SP_EXECUTESQL @SQL2, N'@NoReply1 int OUTPUT', @NoReply OUTPUT

	--符合要求数量
	SET @SQL2 = '
	SELECT @ReplyYes1 = COUNT(*) 
	FROM exJobApply a WITH(NOLOCK)
	INNER JOIN cvMain b WITH(NOLOCK) ON b.ID = a.cvMainID
	INNER JOIN paMain c WITH(NOLOCK) ON c.ID = b.paMainID
	INNER JOIN Job d WITH(NOLOCK) ON d.ID = a.JobID
	WHERE a.CompanyDeleted = 0 AND d.IsDelete = 0
	And a.IsFilter = 0
    AND Reply=1 
	AND ' + @WHERE
	EXEC SP_EXECUTESQL  @SQL2, N'@ReplyYes1 int OUTPUT', @ReplyYes OUTPUT

	--不符合要求数量
	SET @SQL2 = '
	SELECT @ReplyNo1 = COUNT(*) 
	FROM exJobApply a WITH(NOLOCK)
	INNER JOIN cvMain b WITH(NOLOCK) ON b.ID = a.cvMainID
	INNER JOIN paMain c WITH(NOLOCK) ON c.ID = b.paMainID
	INNER JOIN Job d WITH(NOLOCK) ON d.ID = a.JobID
	WHERE a.CompanyDeleted = 0 AND d.IsDelete = 0
	And a.IsFilter = 0
    AND Reply = 2 AND ' + @WHERE
	EXEC SP_EXECUTESQL  @SQL2, N'@ReplyNo1 int OUTPUT', @ReplyNo OUTPUT


	--未查看数量
	SET @SQL2 = '
	SELECT @Filter1 = COUNT(*) 
	FROM exJobApply a WITH(NOLOCK)
	INNER JOIN cvMain b WITH(NOLOCK) ON b.ID = a.cvMainID
	INNER JOIN paMain c WITH(NOLOCK) ON c.ID = b.paMainID
	INNER JOIN Job d WITH(NOLOCK) ON d.ID = a.JobID
	WHERE a.CompanyDeleted = 0 AND d.IsDelete = 0
	And a.IsFilter = 1
	AND ' + @WHERE
	EXEC SP_EXECUTESQL  @SQL2, N'@Filter1 int OUTPUT', @Filter OUTPUT

	--计算匹配度
	SELECT @NoViewCnt AS NoViewCnt, @NoReply AS NoReply, @ReplyYes AS ReplyYes, @ReplyNo AS ReplyNo, @Filter AS FilterCnt

	--修改 已查看提醒时间
	UPDATE ExJobApply
	SET CpRemindViewDate = GETDATE()
	WHERE JobID IN (
		SELECT ID FROM JOB WITH(NOLOCK)
		WHERE CaMainID  = @caMainID 
	) AND RemindDate IS NOT NULL
	AND CpRemindViewDate IS NULL

	DROP TABLE #T
END


GO
/****** Object:  StoredProcedure [dbo].[ccExJobApplyByCpMainIDReplyUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--答复后修改答复状态（无积分）
--2017-5-25harry 
CREATE PROCEDURE [dbo].[ccExJobApplyByCpMainIDReplyUpdate]
(
	@AllID VARCHAR(1000),
	@Reply INT,
	@cpMainID INT
)
AS
SET NOCOUNT ON
BEGIN 
	SET @AllID = dbo.FormatIDS(@AllID)
	DECLARE @T AS TABLE(ID INT)
	INSERT INTO @T SELECT * FROM dbo.fnSplit(@AllID, ',')

	--SELECT TOP 20 * FROM EXJOBAPPLY
	SELECT ID,Reply,RemindDate FROM EXJOBAPPLY WHERE ID IN (SELECT ID FROM @t) 
	 
	--未提醒答复数量
	DECLARE @CNT1 INT,@CNT2 INT,@CNT3 INT
	SELECT @CNT1 = COUNT(*) 
	FROM exJobApply 
	WHERE ID IN (SELECT ID FROM @T)
	AND Reply = 0
	AND JobID IN (SELECT ID FROM Job WITH(NOLOCK) WHERE cpMainID = @cpMainID) 
	AND RemindDate IS NULL
	--提醒答复72小时内回复的
	SELECT @CNT2 = COUNT(*) 
	FROM exJobApply 
	WHERE ID IN (SELECT ID FROM @T)
	AND Reply = 0
	AND JobID IN (SELECT ID FROM Job WITH(NOLOCK) WHERE cpMainID = @cpMainID) 
	AND DATEADD(DAY,3,RemindDate)>GETDATE()
	--提醒答复72小时内未回复的
	SELECT @CNT3 = COUNT(*) 
	FROM exJobApply 
	WHERE ID IN (SELECT ID FROM @T)
	AND Reply = 0
	AND JobID IN (SELECT ID FROM Job WITH(NOLOCK) WHERE cpMainID = @cpMainID) 
	AND DATEADD(DAY,3,RemindDate)<=GETDATE()

	 
	UPDATE exJobApply SET Reply = @Reply, ReplyDate = GETDATE(),IsDeleted = 0,PersonDeleted = 0
	WHERE ID IN(SELECT ID FROM @T) 
	AND JobID IN (SELECT ID FROM Job WITH(NOLOCK)
	WHERE cpMainID = @cpMainID)

	--修改查看时间
	UPDATE exJobApply SET ViewDate = GETDATE()
	WHERE ID IN(SELECT ID FROM @T) 
	AND JobID IN (SELECT ID FROM Job WITH(NOLOCK)
	WHERE cpMainID = @cpMainID)
	AND ViewDate IS NULL

	--Harry Begin
	IF @Reply IN(1, 2, 3, 4)
	BEGIN
		INSERT WxMessageSend2(Templatetype, WxFansID, PaMainId, MainTableId, CpMainID, CvMainID, JobId, AddDate)
		SELECT 9, b.Id, c.paMainId, a.Id, @cpMainId, c.Id, a.JobId, GETDATE() 
		FROM exJobApply a WITH(NOLOCK), 
			wxFans b WITH(NOLOCK), 
			cvMain c WITH(NOLOCK) 
		WHERE a.ID IN(SELECT ID FROM @T)
		AND a.cvMainID = c.ID
		AND b.PaMainId = c.PaMainId 
		AND b.[Status] = 2
		
		INSERT INTO paPushLog(paMainID, PushMessage, PushType)
		SELECT b.paMainID, '亲，有企业回复了您的职位申请！', 1
		FROM exJobApply a WITH(NOLOCK),
			cvMain b WITH(NOLOCK) 
 		WHERE a.ID IN(SELECT ID FROM @T)
		AND a.cvMainID = b.ID
		AND b.paMainID IN(SELECT paMainID FROM paIOSBind WITH(NOLOCK))
	END
	--Harry End
END

GO
/****** Object:  StoredProcedure [dbo].[ccExJobApplyByCpMainIDUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--添加积分记录
--答复后修改答复状态
--20151124 nick
--20160215 Lucifer 添加推送内容
--修改Harry2017-5-25 增加自动答复的答复率计算
--20180223 Carl 自动答复之后再手动答复也送积分
CREATE PROCEDURE [dbo].[ccExJobApplyByCpMainIDUpdate]
(
	@AllID VARCHAR(1000),
	@Reply INT,
	@cpMainID INT
)
AS
SET NOCOUNT ON
BEGIN
	DECLARE @Reply72Point INT --72小时内答复简历 赠送积分
	DECLARE @ReplyPoint INT --答复应聘简历 赠送积分

	SET @Reply72Point = 15
	SET @ReplyPoint = 10

	SET @AllID = dbo.FormatIDS(@AllID)
	DECLARE @T AS TABLE(ID INT)
	INSERT INTO @T SELECT * FROM dbo.fnSplit(@AllID, ',')

	--SELECT TOP 20 * FROM EXJOBAPPLY
	SELECT ID,Reply,RemindDate FROM EXJOBAPPLY WHERE ID IN (SELECT ID FROM @t)

	--查询7天之内应聘的数量
	--DECLARE @ExJobApplyNum AS INT
	--SELECT @ExJobApplyNum = COUNT(1) 
	--FROM exJobApply
	--WHERE ID IN(SELECT ID FROM @T) 
	--	AND Reply = 0
	--	AND JobID IN (SELECT ID FROM Job WITH(NOLOCK) WHERE cpMainID = @cpMainID) 
	--	AND Adddate > (CONVERT(VARCHAR(10),GETDATE()-7,120))
		
	--插入积分记录  Peter 2014-08-25
	DECLARE @TodayPoint AS INT, @TodayID AS INT
	SELECT @TodayPoint = 0, @TodayID = 0
	SELECT TOP 1 @TodayPoint = ISNULL(Point, 0), @TodayID = ISNULL(ID,0) 
	FROM cpPoint WITH(NOLOCK) 
	WHERE changeID = 14 
	AND LastModifyDate > CONVERT(VARCHAR(10), GETDATE(),120) 
	AND cpMainID = @cpMainID

	--未提醒答复数量
	DECLARE @CNT1 INT,@CNT2 INT,@CNT3 INT
	SELECT @CNT1 = COUNT(*) 
	FROM exJobApply 
	WHERE ID IN (SELECT ID FROM @T)
	AND Reply in (0,5) 
	AND JobID IN (SELECT ID FROM Job WITH(NOLOCK) WHERE cpMainID = @cpMainID) 
	AND RemindDate IS NULL
	--提醒答复72小时内回复的
	SELECT @CNT2 = COUNT(*) 
	FROM exJobApply 
	WHERE ID IN (SELECT ID FROM @T)
	AND Reply in (0,5) 
	AND JobID IN (SELECT ID FROM Job WITH(NOLOCK) WHERE cpMainID = @cpMainID) 
	AND DATEADD(DAY,3,RemindDate)>GETDATE()
	--提醒答复72小时内未回复的
	SELECT @CNT3 = COUNT(*) 
	FROM exJobApply 
	WHERE ID IN (SELECT ID FROM @T)
	AND Reply in (0,5) 
	AND JobID IN (SELECT ID FROM Job WITH(NOLOCK) WHERE cpMainID = @cpMainID) 
	AND DATEADD(DAY,3,RemindDate)<=GETDATE()

	SET @TodayPoint = @TodayPoint + @CNT1*@ReplyPoint+@CNT2*@Reply72Point+@CNT3*(@Reply72Point-@ReplyPoint)
	IF @TodayPoint > 100
	BEGIN
		SET @TodayPoint = 100
		UPDATE cpPoint SET Point = @TodayPoint,LastModifyDate = GETDATE() WHERE ID = @TodayID
	END
	ELSE
	BEGIN
		IF @TodayID = 0
		BEGIN
			INSERT INTO cpPoint (cpMainID,ChangeID,Point,LastModifyDate) 
			VALUES(@cpMainID,14,@CNT1*@ReplyPoint+@CNT2*@Reply72Point+@CNT3*(@Reply72Point-@ReplyPoint),GETDATE()) 
		END
		ELSE
		BEGIN
			UPDATE cpPoint SET Point = @TodayPoint+@CNT1*@ReplyPoint+@CNT2*@Reply72Point+@CNT3*(@Reply72Point-@ReplyPoint),LastModifyDate = GETDATE() WHERE ID = @TodayID 
		END
	END
 

	UPDATE exJobApply SET Reply = @Reply, ReplyDate = GETDATE(),IsDeleted = 0,PersonDeleted = 0
	WHERE ID IN(SELECT ID FROM @T) 
	AND JobID IN (SELECT ID FROM Job WITH(NOLOCK)
	WHERE cpMainID = @cpMainID)

	--修改查看时间
	UPDATE exJobApply SET ViewDate = GETDATE()
	WHERE ID IN(SELECT ID FROM @T) 
	AND JobID IN (SELECT ID FROM Job WITH(NOLOCK)
	WHERE cpMainID = @cpMainID)
	AND ViewDate IS NULL

	--Harry Begin
	IF @Reply IN(1, 2, 3, 4)
	BEGIN
		INSERT WxMessageSend2(Templatetype, WxFansID, PaMainId, MainTableId, CpMainID, CvMainID, JobId, AddDate)
		SELECT 9, b.Id, c.paMainId, a.Id, @cpMainId, c.Id, a.JobId, GETDATE() 
		FROM exJobApply a WITH(NOLOCK), 
			wxFans b WITH(NOLOCK), 
			cvMain c WITH(NOLOCK) 
		WHERE a.ID IN(SELECT ID FROM @T)
		AND a.cvMainID = c.ID
		AND b.PaMainId = c.PaMainId 
		AND b.[Status] = 2
		
		INSERT INTO paPushLog(paMainID, PushMessage, PushType)
		SELECT b.paMainID, '亲，有企业回复了您的职位申请！', 1
		FROM exJobApply a WITH (NOLOCK),
			cvMain b WITH(NOLOCK) 
 		WHERE a.ID IN(SELECT ID FROM @T)
		AND a.cvMainID = b.ID
		AND b.paMainID IN(SELECT paMainID FROM paIOSBind WITH(NOLOCK))
	END
	--Harry End
 
END 

GO
/****** Object:  StoredProcedure [dbo].[ccExJobApplyBycvMainIDDelete]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


--lambo 20101122
--删除该简历所有对本企业的申请记录
--用于发送面试通知页面
CREATE PROCEDURE [dbo].[ccExJobApplyBycvMainIDDelete]
(
	@cvMainID INT,
	@cpMainID INT
)
AS
BEGIN
	BEGIN TRY
		DELETE FROM exJobApply
		WHERE cvMainID = @cvMainID
		AND JobID IN 
		(
			SELECT ID FROM Job WITH(NOLOCK) WHERE cpMainID = @cpMainID
		)

		RETURN 1
	END TRY
	BEGIN CATCH
		RETURN 0
	END CATCH
END














GO
/****** Object:  StoredProcedure [dbo].[ccExJobApplyByCvMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--修改:Andy 2015-01-13 添加职位的regionid 
--修改：harry 提升企业答复率，企业删除的也需要答复2017-5-4
--#####################################################
CREATE PROCEDURE [dbo].[ccExJobApplyByCvMainIDSelect]
(
	@caMainID INT,
	@cvMainID INT,
	@cpMainID INT
)
AS
BEGIN
	IF @cpMainID > 0
		SELECT a.ID,a.JobID,b.dcRegionID,a.cvMainID,a.ApplyMessage,a.AddDate,c.Name caName,
			a.CompanyDeleted,a.CompanyDeleteDate,a.PersonDeleted,
			a.Reply,a.ReplyDate,a.IsPassed,
			b.Name JobName,b.caMainID, a.RemindDate
		FROM exJobApply a WITH(NOLOCK) 
		INNER JOIN Job b WITH(NOLOCK) ON b.ID=a.JobID
		INNER JOIN caMain c WITH(NOLOCK) ON b.caMainID=c.ID
		WHERE cvMainID=@cvMainID
		AND c.cpMainID=@cpMainID
		--AND CompanyDeleted=0
		ORDER BY a.adddate asc

	IF @cpMainID = 0
		SELECT a.ID,a.JobID,b.dcRegionID,a.cvMainID,a.ApplyMessage,a.AddDate,
			a.CompanyDeleted,a.CompanyDeleteDate,a.PersonDeleted,
			a.Reply,a.ReplyDate,a.IsPassed,
			b.Name as JobName,b.caMainID, a.RemindDate
		FROM exJobApply a WITH(NOLOCK)
		inner join Job b WITH(NOLOCK) On b.ID=a.JobID
		inner join cpMain c WITH(NOLOCK) On b.cpMainID=c.ID
		WHERE caMainID=@caMainID
		AND cvMainID=@cvMainID
		--AND CompanyDeleted=0
		ORDER BY a.adddate asc
END 

GO
/****** Object:  StoredProcedure [dbo].[ccExJobApplyByExcelSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--alen 2018-3-28
CREATE PROCEDURE [dbo].[ccExJobApplyByExcelSelect]
(
	@cpMainID INT, 
	@WHERE VARCHAR(2000), 
	@Order VARCHAR(100)
)
AS
SET NOCOUNT ON
BEGIN	
	DECLARE @SQL AS VARCHAR(2000)
	SET @SQL = 'SELECT a.ID, a.JobID, dbo.ShowContact(a.cvMainID, ' + LTRIM(STR(@cpMainID)) + ') AS ShowContact, b.paMainId, b.SecondId,
			a.cvMainID, a.AddDate, a.Reply, a.ReplyDate, c.Mobile, b.Degree, b.RelatedWorkYears, c.Email, d.Name JobName, 
			c.LivePlace, c.Gender, c.Name AS paName, c.BirthDay, c.HasPhoto, b.Attachment, b.IsNameHidden, b.JobName JobNameRece
		FROM exJobApply a WITH(NOLOCK) 
		inner join cvMain b WITH(NOLOCK) ON b.ID = a.cvMainID
		INNER JOIN paMain c WITH(NOLOCK) ON c.ID = b.paMainID
		INNER JOIN Job d WITH(NOLOCK) ON a.JobID = d.ID
		WHERE CompanyDeleted = 0'
	IF LEN(@WHERE)> 0
	BEGIN
		SET @Where = dbo.SafeSql(@Where)
		SET @SQL=@SQL + ' AND ' + @WHERE
	END
	IF LEN(@ORDER)> 0
	BEGIN
		SET @ORDER = REPLACE(dbo.SafeSQLBack(@ORDER), '''', '''')
		SET @SQL=@SQL + ' ORDER BY ' + @ORDER
	END

	EXEC(@SQL)
END

GO
/****** Object:  StoredProcedure [dbo].[ccExJobApplyByFilterNoRepliedCountSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ccExJobApplyByFilterNoRepliedCountSelect]
(
	@caMainID INT
)
AS
BEGIN
	SELECT COUNT(1) Cnt
	FROM exJobApply a WITH(NOLOCK), Job b WITH(NOLOCK), CvMain c WITH(NOLOCK)
	WHERE a.Reply = 0
	And a.CompanyDeleted = 0 
	AND a.JobID =b.ID
	AND b.caMainID = @caMainID
	AND b.IsDelete = 0 
	AND a.IsFilter = 1
	AND a.cvMainID= c.ID 
END










GO
/****** Object:  StoredProcedure [dbo].[ccExJobApplyByHasAppliedSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--Lambo 20101022
--查询该简历是否向本公司申请过
--用于简历显示页面
CREATE PROCEDURE [dbo].[ccExJobApplyByHasAppliedSelect]
(
    @cpMainID INT,
	@cvMainID INT
)
AS
BEGIN
	IF EXISTS (
		SELECT 'x' FROM ExJobApply a WITH(NOLOCK),Job b 
		WHERE a.JobID = b.ID 
		AND a.cvMainID = @cvMainID
		AND b.cpMainID = @cpMainID
	)
		RETURN 1
	ELSE
		RETURN 0
END














GO
/****** Object:  StoredProcedure [dbo].[ccExJobApplyByIDUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：20160105
--创建人：Nick
--说明：根据ID修改答复原因
--修改harry,@point>0的才进行积分计算
--#####################################################
CREATE PROCEDURE [dbo].[ccExJobApplyByIDUpdate]
(
	@ID INT,
	@ReplyReason NVARCHAR(100),
	@JobID INT,
	@CpMainID INT,
	@Point INT
)
AS
BEGIN 
	UPDATE ExJobApply
	SET ReplyReason = @ReplyReason
	WHERE ID = @ID
	AND JobID = @JobID
        
        IF @Point >0
	BEGIN
		--修改积分
		DECLARE @TodayPoint AS INT
		DECLARE @TodayID AS INT
		SET @TodayPoint = 0
		SET @TodayID = 0	
				
		SELECT TOP 1 @TodayPoint = ISNULL(Point,0),@TodayID = ISNULL(ID,0) 
		FROM cpPoint WITH(NOLOCK) 
		WHERE changeID = 14 
		AND LastModifyDate > CONVERT(VARCHAR(10), GETDATE(),120) 
		AND cpMainID = @CpMainID

		IF @TodayID = 0
		BEGIN
			INSERT INTO cpPoint (cpMainID,ChangeID,Point,LastModifyDate) VALUES(@CpMainID,14,@Point,GETDATE())
		END 
		ELSE 
		BEGIN 
			SET @TodayPoint = @TodayPoint + @Point 
    			IF @TodayPoint > 100
   			BEGIN
        			SET @TodayPoint = 100
			END 
			UPDATE cpPoint SET Point = @TodayPoint,LastModifyDate = GETDATE() WHERE ID = @TodayID
		END
	END

END 
 
GO
/****** Object:  StoredProcedure [dbo].[ccExJobApplyByJobIDCountSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ccExJobApplyByJobIDCountSelect]
(
	@JobID INT
)
AS
BEGIN
	SELECT COUNT(ID) AS ApplyCount FROM exJobApply WITH(NOLOCK) WHERE CompanyDeleted=0 AND JobID=@JobID AND (IsFilter IS NULL OR IsFilter=0)
END














GO
/****** Object:  StoredProcedure [dbo].[ccExJobApplyByJobIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--nick 20160125 
--根据简历 职位查询 应聘信息
create PROCEDURE [dbo].[ccExJobApplyByJobIDSelect]
(
	@JobID INT,
	@CvMainID INT
)
AS
BEGIN 
	SELECT TOP 1 * FROM ExJobApply WITH(NOLOCK) WHERE JobID = @JobID AND CvMainID = @CvMainID ORDER BY ID DESC
END

GO
/****** Object:  StoredProcedure [dbo].[ccExJobApplyByOneWeekSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ccExJobApplyByOneWeekSelect]
(
	@caMainID INT
)
AS
BEGIN
	BEGIN TRY
		DECLARE @return INT
		SELECT @return = COUNT(1) FROM exJobApply WITH(index(IX_exJobApply_JobId) NOLOCK) 
		WHERE AddDate > GETDATE() - 7
		AND CompanyDeleted = 0
		AND JobID IN (SELECT ID FROM Job WITH(NOLOCK) WHERE caMainID = @caMainID AND IsDelete = 0)
		--AND (IsFilter IS NULL OR IsFilter=0)
		RETURN @return
	END TRY
	BEGIN CATCH
		RETURN 0
	END CATCH
END










GO
/****** Object:  StoredProcedure [dbo].[ccExjobApplyByRecoverUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ccExjobApplyByRecoverUpdate]
(
	@cpMainId INT,
	@Ids VARCHAR(200)
)
AS
SET NOCOUNT ON
BEGIN
	DECLARE @t AS TABLE(Id INT)
	INSERT INTO @t SELECT a FROM dbo.FnSplit(@Ids, ',')
	DECLARE @Num INT
	IF EXISTS(
		SELECT 'x' FROM Job 
		WHERE Id IN(SELECT jobId FROM CaCvApplyDeleted WITH(NOLOCK) WHERE ID IN(SELECT ID FROM @t))
		AND cpMainId != @cpMainId
	)
	BEGIN
		SELECT -1 NUM
		RETURN
	END

	INSERT INTO	ExjobApply(JobId, cvMainId, AddDate, IsFilter, Reply, ReplyDate)
	SELECT JobId, cvMainId, GETDATE(), 0, Reply, GETDATE()
	FROM CaCvApplyDeleted WITH(NOLOCK)
	WHERE ID IN(SELECT ID FROM @t)
	AND cvDeleted = 0
	AND JobDeleted = 0

	SET @Num = @@RowCount

	IF @Num > 0
		DELETE FROM CaCvApplyDeleted
		WHERE ID IN(SELECT ID FROM @t)
		AND cvDeleted = 0
		AND JobDeleted = 0

	SELECT @Num AS Num
END

GO
/****** Object:  StoredProcedure [dbo].[ccExJobApplyByViewDateUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--2016-1-6 nick
--修改简历状态为已查看
CREATE PROCEDURE [dbo].[ccExJobApplyByViewDateUpdate]
(
	@CvMainID INT,
	@JobID INT
)
AS
BEGIN
	UPDATE ExJobApply 
	SET ViewDate = GETDATE()	--,isFilter = 0
	WHERE CvMainID = @CvMainID
	AND JobID = @JobID
	AND ViewDate IS NULL 
END

GO
/****** Object:  StoredProcedure [dbo].[ccExJobApplyForJobIdSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--Sean 20160127
--修改harry 2017-6-14 按照申请的时间，优先显示最新申请的
CREATE PROCEDURE [dbo].[ccExJobApplyForJobIdSelect]
(
    @cpMainID INT,
	@cvMainID INT
)
AS
BEGIN
	DECLARE @JobId VARCHAR(10)
	SELECT TOP 1 @JobId = b.Id 
	FROM ExJobApply a WITH(NOLOCK), 
	Job b WITH(NOLOCK)
	WHERE a.JobID = b.ID 
	AND a.cvMainID = @cvMainID
	AND b.cpMainID = @cpMainID
	ORDER BY a.Id DESC	

	RETURN ISNULL(@JobId, '0')
END

GO
/****** Object:  StoredProcedure [dbo].[ccExJobApplySelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[ccExJobApplySelect]
(
	@WHERE VARCHAR(1000),
	@Order VARCHAR(100),
	@Page SMALLINT,
	@caMainID INT
)
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
		SET @Where = dbo.SafeSql(@Where)
		SET @ORDER = REPLACE(dbo.SafeSQL(@ORDER), '''', '''''')
		
		DECLARE @SQL AS VARCHAR(2000)
		CREATE TABLE #T(
			TitleID BIGINT,
			ID INT,
			JobID INT,
			paMainID INT,
			cvMainID INT,
			AddDate SMALLDATETIME,
			Reply TINYINT,
			ReplyDate SMALLDATETIME,
			IsMatched BIT,
			Degree TINYINT,
			RelatedWorkYears TINYINT,
			LivePlace NVARCHAR(50),
			Gender BIT,
			paName NVARCHAR(20),
			BirthDay INT,
			HasPhoto TINYINT,
			Attachment VARCHAR(50) COLLATE Chinese_PRC_CI_AS,
			IsNameHidden BIT,
			Valid TINYINT,
			ApplyMessage NVARCHAR(1),
			IsViewed BIT,
			HasInterview BIT,
			HasRemark BIT,
			HasFavorate BIT,
			cvEducationID INT,
			College NVARCHAR(50),
			EduType TINYINT,
			MajorName NVARCHAR(20),
			Graduation INT,
			Speciality VARCHAR(MAX) COLLATE Chinese_PRC_CI_AS,
			Experience VARCHAR(MAX) COLLATE Chinese_PRC_CI_AS,
			cvMatch INT,
			RecruitmentID INT,
			RecruitmentName NVARCHAR(100),
			RecruitmentDate SMALLDATETIME,
			MobileVerifyDate SMALLDATETIME,
			IsOnline BIT,
			RemindDate DATETIME,
			HasWeiXin BIT,
			HasAccept BIT,
			HsaNoAccept BIT
		)
		SET @SQL='
			INSERT INTO #T
			(TitleID, ID, JobID, paMainID, cvMainID, AddDate, Reply, ReplyDate, IsMatched, ApplyMessage,
				Degree,RelatedWorkYears,Attachment,IsNameHidden,LivePlace,Gender,
				BirthDay,HasPhoto,Valid,RecruitmentID,MobileVerifyDate,IsOnline,RemindDate)

			SELECT ROW_NUMBER() OVER (ORDER BY ' + @ORDER + ') AS TitleID, a.ID, a.JobID, c.ID, a.cvMainID,
				a.AddDate, a.Reply, a.ReplyDate, a.IsMatched, LEFT(a.ApplyMessage, 1) ApplyMessage,
				b.Degree,b.RelatedWorkYears,b.Attachment,b.IsNameHidden,c.LivePlace,
				c.Gender,c.BirthDay,c.HasPhoto,b.Valid,a.RecruitmentID,c.MobileVerifyDate,dbo.GetPaOnlineStatus(c.ID),a.RemindDate
			FROM exJobApply a WITH(NOLOCK)
			INNER JOIN cvMain b WITH(NOLOCK) ON b.ID = a.cvMainID
			INNER JOIN paMain c WITH(NOLOCK) ON c.ID = b.paMainID
			INNER JOIN Job d WITH(NOLOCK) ON d.ID = a.JobID
			WHERE a.CompanyDeleted = 0 AND d.IsDelete = 0'
		IF LEN(@WHERE) > 0
			SET @SQL = @SQL + ' AND '+@WHERE

		--PRINT @SQL
		EXEC(@SQL)
		
		IF(@Page < 1)
			SET @Page = 1
		IF NOT EXISTS(SELECT 'x' FROM #t WHERE TitleID > (@Page-1)*20 AND  TitleID <= @Page*20)
			SET @Page = 1
		
		DECLARE @cpMainID AS INT
		SELECT @cpMainID = cpMainID FROM caMain WITH(NOLOCK) WHERE ID = @caMainID
		UPDATE #T SET paName = LEFT(dbo.GetPersonName(cvMainID, @cpMainID), 20), IsViewed = (SELECT TOP 1 '1' FROM caCvViewLog WITH(NOLOCK) WHERE cvMainID=#T.cvMainID AND caMainID=@caMainID),
			HasFavorate = (SELECT TOP 1 '1' FROM caFavorate WITH(NOLOCK) WHERE caMainID=@caMainID AND cvMainID=#T.cvMainID),
			HasInterview = (SELECT TOP 1 '1' FROM exInterview a WITH(NOLOCK) INNER JOIN Job b WITH(NOLOCK) ON a.JobID=b.ID WHERE a.CompanyDeleted=0 AND b.caMainID=@caMainID AND cvMainID=#T.cvMainID),
			HasRemark = (SELECT TOP 1 '1' FROM caCvRemark WITH(NOLOCK) WHERE caMainID=@caMainID AND cvMainID=#T.cvMainID),
			HasAccept = (SELECT TOP 1 '1' FROM exInterview a WITH(NOLOCK) INNER JOIN Job b WITH(NOLOCK) ON a.JobID=b.ID WHERE a.CompanyDeleted=0 AND b.caMainID=@caMainID AND cvMainID=#T.cvMainID AND a.Result = 1),
			HsaNoAccept = (SELECT TOP 1 '1' FROM exInterview a WITH(NOLOCK) INNER JOIN Job b WITH(NOLOCK) ON a.JobID=b.ID WHERE a.CompanyDeleted=0 AND b.caMainID=@caMainID AND cvMainID=#T.cvMainID AND a.Result > 1)
		WHERE TitleID > (@Page-1)*20 AND  TitleID <= @Page*20

		UPDATE #T SET Speciality = (
			SELECT Speciality FROM cvMain WITH(NOLOCK)
			WHERE cvMain.ID = #T.cvMainID)
		WHERE TitleID > (@Page-1)*20 AND  TitleID <= @Page*20
		
		UPDATE #T SET Experience = (
			SELECT TOP 1 ISNULL(Description,DescriptionEng) FROM cvExperience WITH(NOLOCK)
			WHERE cvExperience.cvMainID = #T.cvMainID
			ORDER BY BeginDate DESC)
		WHERE TitleID > (@Page-1)*20 AND  TitleID <= @Page*20

		UPDATE #T SET cvEducationID = (
			SELECT TOP 1 ID FROM cvEducation WITH(NOLOCK)
			WHERE cvEducation.cvMainID = #T.cvMainID
			AND #T.Degree = cvEducation.Degree
			ORDER BY Graduation DESC)
		WHERE TitleID > (@Page-1)*20 AND  TitleID <= @Page*20

		--修改是否绑定微信
		UPDATE a SET HasWeiXin = 1
		FROM #T a,WxFans b WITH(NOLOCK)
		WHERE a.paMainID = b.PaMainID
		AND b.Status = 2
		AND a.TitleID > (@Page-1)*20 AND  TitleID <= @Page*20

		UPDATE a SET a.College = ISNULL(b.GraduateCollage,b.GraduateCollageEng),a.EduType = b.EduType, 
			a.MajorName = ISNULL(b.MajorName,b.MajorNameEng), a.Graduation = b.Graduation
		FROM #T a, cvEducation b WITH(NOLOCK)
		WHERE b.ID = a.cvEducationID AND a.TitleID > (@Page-1)*20 AND a. TitleID <= @Page*20
		
		UPDATE a SET a.RecruitmentName = b.RecruitmentName, a.RecruitmentDate = b.EndDate
		FROM #T a, Recruitment b WITH(NOLOCK)
		WHERE b.ID = a.RecruitmentID AND a.TitleID > (@Page-1)*20 AND a. TitleID <= @Page*20
		
		UPDATE #T SET cvMatch = dbo.GetCvMatch(cvMainID,JobID) WHERE TitleID > (@Page-1)*20 AND  TitleID <= @Page*20

		SELECT COUNT(*) FROM #T WITH(NOLOCK)
		SELECT * FROM #T WITH(NOLOCK) WHERE TitleID > (@Page-1)*20 AND  TitleID <= @Page*20

		--计算匹配度
		

		DROP TABLE #T
	END TRY
	BEGIN CATCH
		DROP TABLE #T
	END CATCH
END


GO
/****** Object:  StoredProcedure [dbo].[ccExJobApplyUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--Lambo 20101130 修改
-- 增加cpMainID 参数，只能删除本公司的
--Peter 20140825修改
--添加积分记录
--答复后修改答复状态
--20151124 nick
--修改Harry2017-4-17
CREATE PROCEDURE [dbo].[ccExJobApplyUpdate]
(
    @AllID VARCHAR(1000),
    @Reply INT,
    @cpMainID INT
)
AS
SET NOCOUNT ON
BEGIN
    SET @AllID = dbo.FormatIDS(@AllID)
    DECLARE @T AS TABLE(ID INT)
    INSERT INTO @T SELECT * FROM dbo.fnSplit(@AllID, ',')

    --查询7天之内应聘的数量
    DECLARE @ExJobApplyNum AS INT
    SELECT @ExJobApplyNum = COUNT(1) 
    FROM exJobApply
    WHERE ID IN(SELECT ID FROM @T) 
    AND Reply = 0
    AND JobID IN (SELECT ID FROM Job WITH(NOLOCK) WHERE cpMainID = @cpMainID) 
    AND Adddate > (CONVERT(VARCHAR(10),GETDATE()-7,120))
        
    --插入积分记录 Peter 2014-08-25
    DECLARE @TodayPoint AS INT, @TodayID AS INT
    SELECT @TodayPoint = 0, @TodayID = 0
    SELECT TOP 1 @TodayPoint = ISNULL(Point, 0), @TodayID = ISNULL(ID,0) 
    FROM cpPoint WITH(NOLOCK) 
    WHERE changeID = 14 
    AND LastModifyDate > CONVERT(VARCHAR(10), GETDATE(),120) 
    AND cpMainID = @cpMainID

    SET @TodayPoint = @TodayPoint + (@ExJobApplyNum * 2)
    
    IF @TodayPoint > 100
        SET @TodayPoint = 100
    IF @TodayID = 0
        INSERT INTO cpPoint (cpMainID,ChangeID,Point,LastModifyDate) VALUES(@cpMainID,14,@TodayPoint,GETDATE())
    ELSE
        UPDATE cpPoint SET Point = @TodayPoint,LastModifyDate = GETDATE() WHERE ID = @TodayID 

    UPDATE exJobApply SET Reply = @Reply, ReplyDate = GETDATE(),IsDeleted = 0,PersonDeleted = 0
    WHERE ID IN(SELECT ID FROM @T) AND Reply = 0
    AND JobID IN (SELECT ID FROM Job WITH(NOLOCK)
    WHERE cpMainID = @cpMainID)

    --Harry Begin 2017-5-23
    IF @Reply IN(1, 2, 3, 4)--4企业删除
    BEGIN
        INSERT WxMessageSend2(Templatetype, WxFansID, PaMainId, MainTableId, CpMainID, CvMainID, JobId, AddDate)
        SELECT 9, b.Id, c.paMainId, a.Id, @cpMainId, c.Id, a.JobId, GETDATE() 
        FROM exJobApply a WITH(NOLOCK), 
            wxFans b WITH(NOLOCK), 
            cvMain c WITH(NOLOCK) 
        WHERE a.ID IN(SELECT ID FROM @T)
        AND a.cvMainID = c.ID 
        AND b.PaMainId = c.PaMainId 
        AND b.[Status] = 2
    END
    	 
    DECLARE @Cnt INT, @ReplyCnt INT, @ReplyRate DECIMAL(9, 3)
	 --是否同意自动答复
	IF EXISTS(SELECT 'x' FROM cpMain WHERE id=@cpMainID AND AutoReplyConfirm is NULL)
	BEGIN 
		SELECT @Cnt = COUNT(*), @ReplyCnt = COUNT(ReplyDate)
		FROM ExjobApply
		WHERE JobId IN(SELECT Id FROM Job WHERE cpMainId = @cpMainId)
		AND AddDate > GETDATE() - 183

		IF @Cnt > 0
			SELECT @ReplyRate = @ReplyCnt * 1.0 / @Cnt
			--WHERE @ReplyCnt * 1.0 / @Cnt >= 0.1
		ELSE
			SELECT @ReplyRate =1	
	END
	ELSE
	BEGIN
		DECLARE @AutoReplyConfirm DATETIME
		SELECT @AutoReplyConfirm=AutoReplyConfirm 
		FROM CpMain WITH(NOLOCK)
		WHERE Id = @cpMainId

		SELECT @ReplyCnt = SUM(CASE WHEN reply<>5 THEN 1 ELSE 0 END),  @Cnt= COUNT(ReplyDate)
		FROM ExjobApply
		WHERE JobId IN(SELECT Id FROM Job WHERE cpMainId = @cpMainId)
		AND reply!=0
 		AND adddate>@AutoReplyConfirm

		IF @Cnt > 0
			SELECT @ReplyRate = @ReplyCnt * 1.0 / @Cnt
		ELSE
			SELECT @ReplyRate =1	
	END 

    UPDATE cpMain SET ReplyRate = @ReplyRate WHERE Id = @cpMainId 

    UPDATE a SET a.replyrate = b.ReplyRate FROM cpMainPublish a, cpMain b WHERE a.Id = b.Id AND ISNULL(a.replyrate, 0) <> ISNULL(b.replyrate, 0) 

	--Harry end
END

GO
/****** Object:  StoredProcedure [dbo].[ccExMessageC2PDelete]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--Lambo 20101130 修改
-- 增加cpMainID 参数，只能删除本公司的

CREATE PROCEDURE [dbo].[ccExMessageC2PDelete]
(
	@ID INT,
	@cpMainID INT
)
AS
BEGIN TRY
	IF EXISTS(SELECT ID FROM ExMessageC2P WITH(NOLOCK)
			WHERE PersonDeleted = 1
			AND ID = @ID
			AND caMainID IN (SELECT ID FROM caMain WITH(NOLOCK) WHERE cpMainID = @cpMainID))
		DELETE FROM ExMessageC2P WHERE PersonDeleted = 1 AND ID = @ID
	ELSE
		UPDATE ExMessageC2P SET CompanyDeleted = 1
		WHERE ID = @ID AND caMainID IN (SELECT ID FROM caMain WITH(NOLOCK)
										WHERE cpMainID = @cpMainID)
END TRY
BEGIN CATCH
	GOTO ERR
END CATCH
RETURN 1
ERR:
BEGIN
	RETURN 0
END














GO
/****** Object:  StoredProcedure [dbo].[ccexMessageC2PInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--ccexMessageC2PInsert 0,371108,14792626,'sssssssssss'

--#########################################
--修改：sean 
--增加了非收费会员不能超过100条的判断
--@ID 是个人留言的id，>0：回复个人留言，=0：主动留言
--#########################################
CREATE PROCEDURE [dbo].[ccexMessageC2PInsert]
(
	@ID INT,
	@caMainID INT,
	@cvMainID INT,
	@Message NVARCHAR(200)
)
AS
BEGIN
	DECLARE @cpMainID AS INT, @MemberType AS TINYINT, @cnt AS INT
	SELECT @cpMainID = cpMainID FROM caMain WITH(NOLOCK) WHERE ID = @caMainID
	SELECT @MemberType = MemberType FROM cpMain WITH(NOLOCK) WHERE ID = @cpMainID

	IF @MemberType < 3		--费收费用户
	BEGIN
		SELECT @cnt = COUNT(1) FROM exMessageC2P WITH(NOLOCK)
		WHERE caMainID = @caMainID
		
		IF @cnt >= 100		--最多100条留言
			GOTO Err1
	END

	SET @Message = LTRIM(RTRIM(@Message))
	INSERT exMessageC2P(caMainID, cvMainID, Message)
	VALUES(@caMainID, @cvMainID, @Message)
	IF @ID > 0	
		Update exMessageP2C Set IsReply=1 WHERE ID = @ID
	RETURN
END
ERR1:
BEGIN
	RETURN -1
END














GO
/****** Object:  StoredProcedure [dbo].[ccExMessageC2PSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--[ccExMessageC2PSelect] 'And caMainID =371108 And c.Name=''杨''','a.id desc',1,371108,371108

CREATE PROCEDURE [dbo].[ccExMessageC2PSelect]
(
	@WHERE VARCHAR(1000),
	@Order VARCHAR(100),
	@Page SMALLINT,
	@cpMainID INT,
	@caMainID INT
)
AS
BEGIN
	BEGIN TRY
		SET @Where = dbo.SafeSql(@Where)
		SET @ORDER = dbo.SafeSql(@Order)
		CREATE TABLE #T(
			TitleID BIGINT,
			ID INT,
			caMainID INT,
			cvMainID INT,
			Message VARCHAR(1000) COLLATE Chinese_PRC_CI_AS,
			AddDate SMALLDATETIME,
			IsViewed BIT,
			IsReply BIT,
			Degree TINYINT,
			RelatedWorkYears TINYINT,
			Attachment VARCHAR(50) COLLATE Chinese_PRC_CI_AS,
			IsNameHidden BIT,
			LivePlace VARCHAR(6),
			Gender BIT,
			paName NVARCHAR(20),
			BirthDay INT,
			HasPhoto TINYINT,
			Valid TINYINT,
			HasJobApply BIT,
			HasInterview BIT,
			HasRemark BIT,
			HasFavorate BIT,
			CvIsViewed BIT
		)
		DECLARE @SQL AS VARCHAR(2000)
		SET @SQL='
			INSERT INTO #T(TitleID,
				ID,caMainID,cvMainID,Message,AddDate,IsViewed,IsReply)
			SELECT ROW_NUMBER() OVER (ORDER BY ' + @ORDER + ') AS TitleID,
				a.ID,a.caMainID,a.cvMainID,a.Message,a.AddDate,a.IsViewed,a.IsReply
			FROM exMessageC2P a WITH(NOLOCK)'
		IF CHARINDEX('c.',@WHERE) > 0
			SET @SQL=@SQL + '
				INNER JOIN cvMain b WITH(NOLOCK) ON b.ID = a.cvMainID
				INNER JOIN paMain c WITH(NOLOCK) ON c.ID = b.paMainID'

		SET @SQL=@SQL + '
			WHERE CompanyDeleted=0'
		IF @caMainId > 0
			SET @SQL=@SQL + '
				AND a.caMainId = ' + LTRIM(STR(@caMainID))

		IF LEN(@WHERE) > 0
			SET @SQL = @SQL + @WHERE
		--PRINT @SQL
		EXEC(@SQL)

		IF(@Page < 1)
			SET @Page = 1
		IF NOT EXISTS(SELECT 'x' FROM #t WHERE TitleID > (@Page-1)*20 AND  TitleID <= @Page*20)
			SET @Page = 1

		UPDATE #T SET Degree = a.Degree,RelatedWorkYears = a.RelatedWorkYears,Attachment = a.Attachment,
			IsNameHidden = a.IsNameHidden,LivePlace = b.LivePlace,Gender = b.Gender,paName = b.Name,
			BirthDay = b.BirthDay,HasPhoto = b.HasPhoto,Valid = a.Valid
		FROM cvMain a WITH(NOLOCK) INNER JOIN paMain b WITH(NOLOCK) ON a.paMainID = b.ID
		WHERE a.ID = #T.cvMainID AND TitleID > (@Page-1)*20 AND TitleID <= @Page*20

		UPDATE #T SET paName = LEFT(dbo.GetPaName(cvMainID, @cpMainID), 20),
			CvIsViewed = (SELECT TOP 1 '1' FROM caCvViewLog WITH(NOLOCK) WHERE cvMainID=#T.cvMainID AND caMainID=@caMainID),
			HasJobApply = (SELECT TOP 1 '1' FROM exJobApply a WITH(NOLOCK) INNER JOIN Job b WITH(NOLOCK) ON a.JobID=b.ID WHERE a.CompanyDeleted=0 AND b.caMainID=@caMainID AND cvMainID=#T.cvMainID),
			HasInterview = (SELECT TOP 1 '1' FROM exInterview a WITH(NOLOCK) INNER JOIN Job b WITH(NOLOCK) ON a.JobID=b.ID WHERE a.CompanyDeleted=0 AND b.caMainID=@caMainID AND cvMainID=#T.cvMainID),
			HasRemark = (SELECT TOP 1 '1' FROM caCvRemark WITH(NOLOCK) WHERE caMainID=@caMainID AND cvMainID=#T.cvMainID),
			HasFavorate = (SELECT TOP 1 '1' FROM caFavorate WITH(NOLOCK) WHERE caMainID=@caMainID AND cvMainID=#T.cvMainID)
		WHERE TitleID > (@Page-1)*20 AND TitleID <= @Page*20
		SELECT COUNT(*) FROM #T WITH(NOLOCK)
		SELECT * FROM #T WITH(NOLOCK) WHERE TitleID > (@Page-1)*20 AND TitleID <= @Page*20
		
		DROP TABLE #T
	END TRY
	BEGIN CATCH
		DROP TABLE #T
	END CATCH
END














GO
/****** Object:  StoredProcedure [dbo].[ccExMessageLogSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ccExMessageLogSelect]
    @caMainID INT,
	@cvMainID INT
AS
BEGIN
   SELECT * FROM (
	SELECT addDate,Message,1 IsCompany FROM exMessageC2p WITH(NOLOCK) WHERE cvMainID = @cvMainID AND caMainID = @caMainID AND CompanyDeleted=0
	UNION
	SELECT addDate,Message,0 IsCompany FROM exMessageP2C WITH(NOLOCK) WHERE cvMainID = @cvMainID AND caMainID = @caMainID  AND CompanyDeleted=0
	) a ORDER BY a.AddDate DESC
END














GO
/****** Object:  StoredProcedure [dbo].[ccExMessageP2CByHasMessageSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--Nick 20130716
--查询该简历是否向本公司留言过
--用于简历显示页面
CREATE PROCEDURE [dbo].[ccExMessageP2CByHasMessageSelect]
(
    @cpMainID INT,
	@cvMainID INT
)
AS
BEGIN
	IF EXISTS (
		SELECT 'x' FROM ExMessageP2C WITH(NOLOCK)
		WHERE cvMainID = @cvMainID
		AND caMainID IN(SELECT ID FROM CaMain WITH(NOLOCK) WHERE CpMainID = @cpMainID)
		AND CompanyDeleted = 0
	)
		RETURN 1
	ELSE
		RETURN 0
END












GO
/****** Object:  StoredProcedure [dbo].[ccExMessageP2CDelete]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--Lambo 20101130 修改
-- 增加cpMainID 参数，只能删除本公司的

CREATE PROCEDURE [dbo].[ccExMessageP2CDelete]
(
	@ID INT,
	@cpMainID INT
)
AS
BEGIN TRY
	IF EXISTS(SELECT ID FROM ExMessageP2C WITH(NOLOCK)
		WHERE PersonDeleted = 1
		AND ID = @ID
		AND caMainID IN (SELECT ID FROM caMain WITH(NOLOCK) WHERE cpMainID = @cpMainID))
		DELETE FROM ExMessageP2C WHERE PersonDeleted = 1 AND ID = @ID
	ELSE
		UPDATE ExMessageP2C SET CompanyDeleted = 1
		WHERE ID = @ID AND caMainID IN (SELECT ID FROM caMain WITH(NOLOCK) WHERE cpMainID = @cpMainID)
END TRY
BEGIN CATCH
	GOTO ERR
END CATCH
RETURN 1
ERR:
BEGIN
	RETURN 0
END














GO
/****** Object:  StoredProcedure [dbo].[ccExMessageP2CIsViewedUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[ccExMessageP2CIsViewedUpdate]
(
	@ID INT,
	@caMainID INT
)
AS
BEGIN TRY
	UPDATE exMessageP2C SET IsViewed = 1
	WHERE ID = @ID
	AND caMainID = @caMainID
END TRY
BEGIN CATCH
	GOTO ERR
END CATCH
RETURN 1
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END














GO
/****** Object:  StoredProcedure [dbo].[ccExMessageP2CSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--[ccExMessageP2CSelect] 'caMainID =1002941','a.id desc'
CREATE PROCEDURE [dbo].[ccExMessageP2CSelect]
(
	@WHERE VARCHAR(1000),
	@Order VARCHAR(100),
	@Page SMALLINT,
	@cpMainID INT,
	@caMainID INT
)
AS
BEGIN
	BEGIN TRY
		SET @Where = dbo.SafeSql(@Where)
		SET @ORDER = dbo.SafeSql(@Order)
		CREATE TABLE #T(
			TitleID BIGINT,
			ID INT,
			caMainID INT,
			cvMainID INT,
			Message VARCHAR(200) COLLATE Chinese_PRC_CI_AS,
			AddDate SMALLDATETIME,
			IsViewed BIT,
			IsReply BIT,
			Degree TINYINT,
			RelatedWorkYears TINYINT,
			Attachment VARCHAR(50) COLLATE Chinese_PRC_CI_AS,
			IsNameHidden BIT,
			LivePlace VARCHAR(6),
			Gender BIT,
			paName NVARCHAR(20),
			BirthDay INT,
			HasPhoto TINYINT,
			IsOpen BIT,
			Valid TINYINT,
			HasJobApply BIT,
			HasInterview BIT,
			HasRemark BIT,
			HasFavorate BIT,
			CvIsViewed BIT
		)
		DECLARE @SQL AS VARCHAR(2000)
		SET @SQL='
			INSERT INTO #T(TitleID,ID,caMainID,cvMainID,Message,AddDate,IsViewed,IsReply)
			SELECT ROW_NUMBER() OVER (ORDER BY ' + @ORDER + ') AS TitleID,
				a.ID,a.caMainID,a.cvMainID,a.Message,a.AddDate,a.IsViewed,a.IsReply
		FROM exMessageP2C a WITH(NOLOCK)'
		
		IF CHARINDEX('c.',@WHERE) > 0
			SET @SQL=@SQL + '
				INNER JOIN cvMain b WITH(NOLOCK) ON b.ID = a.cvMainID
				INNER JOIN paMain c WITH(NOLOCK) ON c.ID = b.paMainID'
		
		SET @SQL=@SQL + '
			WHERE CompanyDeleted=0'
		IF @caMainId > 0
			SET @SQL=@SQL + '
				AND a.caMainId = ' + LTRIM(STR(@caMainID))
		
		IF LEN(@WHERE)>0
			SET @SQL=@SQL + @WHERE	
		--PRINT @SQL
		EXEC(@SQL)

		IF(@Page < 1)
			SET @Page = 1
		IF NOT EXISTS(SELECT 'x' FROM #t WHERE TitleID > (@Page-1)*20 AND  TitleID <= @Page*20)
			SET @Page = 1

		UPDATE #T SET Degree = a.Degree,RelatedWorkYears = a.RelatedWorkYears,Attachment = a.Attachment,
			IsNameHidden = a.IsNameHidden,LivePlace = b.LivePlace,Gender = b.Gender,paName = b.Name,
			BirthDay = b.BirthDay,HasPhoto = b.HasPhoto,Valid = a.Valid
		FROM cvMain a WITH(NOLOCK) INNER JOIN paMain b WITH(NOLOCK) ON a.paMainID = b.ID
		WHERE a.ID = #T.cvMainID AND TitleID > (@Page-1)*20 AND TitleID <= @Page*20

		UPDATE #T SET paName = LEFT(dbo.GetPaName(cvMainID, @cpMainID), 20),
			CvIsViewed = (SELECT TOP 1 '1' FROM caCvViewLog WITH(NOLOCK) WHERE cvMainID=#T.cvMainID AND caMainID=@caMainID),
			HasJobApply = (SELECT TOP 1 '1' FROM exJobApply a WITH(NOLOCK) INNER JOIN Job b WITH(NOLOCK) ON a.JobID=b.ID WHERE a.CompanyDeleted=0 AND b.caMainID=@caMainID AND cvMainID=#T.cvMainID),
			HasInterview = (SELECT TOP 1 '1' FROM exInterview a WITH(NOLOCK) INNER JOIN Job b WITH(NOLOCK) ON a.JobID=b.ID WHERE a.CompanyDeleted=0 AND b.caMainID=@caMainID AND cvMainID=#T.cvMainID),
			HasRemark = (SELECT TOP 1 '1' FROM caCvRemark WITH(NOLOCK) WHERE caMainID=@caMainID AND cvMainID=#T.cvMainID),
			HasFavorate = (SELECT TOP 1 '1' FROM caFavorate WITH(NOLOCK) WHERE caMainID=@caMainID AND cvMainID=#T.cvMainID)
		WHERE TitleID > (@Page-1)*20 AND TitleID <= @Page*20
		SELECT COUNT(*) FROM #T WITH(NOLOCK)
		SELECT * FROM #T WITH(NOLOCK) WHERE TitleID > (@Page-1)*20 AND TitleID <= @Page*20
		
		DROP TABLE #T
	END TRY
	BEGIN CATCH
		DROP TABLE #T
	END CATCH
END














GO
/****** Object:  StoredProcedure [dbo].[ccExtendLinkByCpMainIDUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--创建时间：2015.7.13
--创建人：Mice
--说明：更新状态
-------------------------------------------------------
CREATE PROCEDURE [dbo].[ccExtendLinkByCpMainIDUpdate]
(
	@cpMainID INT
)
AS
BEGIN
	UPDATE ExtendLink 
	SET LinkStatus = 4, RunStatus = 0 
	WHERE CpMainID = @cpMainID AND RunStatus = 1
END
GO
/****** Object:  StoredProcedure [dbo].[ccExtendLinkByCustomLinkSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROC [dbo].[ccExtendLinkByCustomLinkSelect]
(
	@cpMainId INT,
	@CustomLink VARCHAR(300)
)
AS
SET NOCOUNT ON
BEGIN
	SELECT TOP 100 * FROM ExtendLink WITH(NOLOCK)
	WHERE cpMainId <> @cpMainId
	AND CustomLink LIKE '%' + LTRIM(RTRIM(@CustomLink)) + '%'
	--AND LinkStatus <> 3
END

GO
/****** Object:  StoredProcedure [dbo].[ccExtendLinkByEditSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ccExtendLinkByEditSelect]
(
	@cpMainId INT
)
AS
BEGIN
	SELECT TOP 1 *, SPACE(50) jobName, GETDATE() SelectDate
	INTO #t
	FROM ExtendLink
	WHERE cpMainID = @cpMainID 
	ORDER BY id DESC

	UPDATE #t SET JobName = (SELECT Name FROM Job WITH(NOLOCK) WHERE Job.Id = #t.Ids)

	DECLARE @SelectDate DATETIME
	SELECT TOP 1 @SelectDate = DATEADD(MONTH, 1, Begindate) FROM ExtendLinkRunLog
	WHERE cpMainId = @cpMainId
	ORDER BY ID DESC

 	IF ISNULL(@SelectDate, GETDATE() - 1) < GETDATE()
		SET @SelectDate = CONVERT(VARCHAR(10), GETDATE() + 1, 120)
	UPDATE #t SET SelectDate = @SelectDate

	SELECT * FROM #t
END

GO
/****** Object:  StoredProcedure [dbo].[ccExtendLinkRunLogSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ccExtendLinkRunLogSelect]
(
	@cpMainId INT
)
AS
BEGIN
	SELECT a.*, CASE a.ShowType WHEN 1 THEN b.Name ELSE '' END as jobName
	FROM ExtendLinkRunLog a
	LEFT JOIN Job b on b.id = a.IDs  
	WHERE a.cpMainID = @cpMainID 
	ORDER BY a.id DESC
END

GO
/****** Object:  StoredProcedure [dbo].[ccExtendLinkSave]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ccExtendLinkSave]
(
	@cpMainID INT,
	@keyword NVARCHAR(20),
	@keywordUrl VARCHAR(300),
	@CustomLink VARCHAR(300),
	@showType INT,
	@ids INT,
	@NextRunDate DATETIME
)
AS
SET NOCOUNT ON
BEGIN
	IF EXISTS(SELECT 'x' FROM ExtendLink WITH(NOLOCK) 
			WHERE cpMainID = @cpMainID
			AND keyword = @keyword
			AND keywordUrl = @keywordUrl
			AND CustomLink = @CustomLink
			AND showType = @showType
			AND ids = @ids
			AND ShowDay = DATEPART(DAY, @NextRunDate)
			AND RunStatus IN(1, 2)
			)
	RETURN

	DECLARE @BeginDate DATETIME, @IsAdd INT, @AddDate DATETIME, @LinkId INT, @LinkStatus INT,
			@keywordUrlOld VARCHAR(300), @CustomLinkOld VARCHAR(300), @ShowDay INT, 
			@ManagerUserId INT
	SELECT @IsAdd = 1, @LinkStatus = 1, @ShowDay = DATEPART(DAY, @NextRunDate) 

	SELECT TOP 1 @AddDate = AddDate, @LinkId = ID, @LinkStatus = LinkStatus,
		@keywordUrlOld = KeywordUrl, @CustomLinkOld = CustomLink
	FROM ExtendLink WITH(NOLOCK) 
	WHERE cpMainId = @cpMainId
	ORDER BY ID DESC

	IF @showType <> 1
		SET @ids = 0

	IF @AddDate IS NOT NULL
	BEGIN
		SELECT TOP 1 @BeginDate = BeginDate FROM ExtendLinkRunLog WITH(NOLOCK) WHERE cpMainId = @cpMainId ORDER BY ID DESC
		IF ISNULL(@BeginDate, '2000-1-1') < @AddDate
			SET @IsAdd = 0
	END
	
	SELECT @ManagerUserId = ConsultantId FROM cpMain WITH(NOLOCK) WHERE id = @cpMainId
	UPDATE ExtendLink  SET ManagerUserID = @ManagerUserId WHERE CpMainID=@cpMainId
	
	IF @IsAdd = 1
	BEGIN
		IF @keywordUrlOld <> @keywordUrl OR @CustomLinkOld <> @CustomLink
			SELECT @LinkStatus = 1
		SELECT @ManagerUserId = ConsultantId FROM cpMain WITH(NOLOCK) WHERE id = @cpMainId

		INSERT INTO ExtendLink(CpMainID, AddDate, KeyWord, KeywordUrl, CustomLink, RunStatus, LinkStatus, ShowType, IDs, ShowDay, NextRunDate,LinkStatusPre, ManagerUserId) 
		SELECT @CpMainID, GETDATE(), @Keyword, @KeywordUrl, @CustomLink, 0, @LinkStatus, @ShowType, @IDs, @ShowDay, @NextRunDate , @LinkStatus, @ManagerUserId
		SET @linkId = @@IDENTITY 
		
	END
	ELSE
	BEGIN
		IF @keywordUrlOld = @keywordUrl AND @CustomLinkOld = @CustomLink
			UPDATE ExtendLink 
			SET CpMainID = @CpMainID, 
			ShowType = @ShowType, 
			IDs = @ids,
			ShowDay = @ShowDay,
			NextRunDate=@NextRunDate,
			AddDate = GETDATE() 
			Where Id = @linkId
		ELSE
			UPDATE ExtendLink
			SET CpMainID = @CpMainID, 
			KeyWord = @Keyword,
			KeywordUrl = @KeywordUrl, 
			CustomLink = @CustomLink, 
			ShowType = @ShowType, 
			RunStatus = 0,
			LinkStatus = 1,
			IDs = @ids,
			ShowDay = @ShowDay,
			NextRunDate=@NextRunDate,
			LinkStatusPre = 1,
			AddDate = GETDATE() 
			Where Id = @linkId
	END

	UPDATE ExtendLink SET RunStatus = 4 WHERE RunStatus < 3 AND cpMainId = @cpMainId AND ID < @linkId
END


GO
/****** Object:  StoredProcedure [dbo].[ccExtendLinkSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ccExtendLinkSelect]
(
	@cpMainId INT
)
AS
BEGIN
	SELECT TOP 12 a.*, CASE a.ShowType WHEN 1 THEN b.Name ELSE '' END as jobName
	FROM ExtendLink a
	LEFT JOIN Job b ON b.id = a.IDs
	WHERE a.cpMainID = @cpMainID 
	ORDER BY a.id DESC
END

GO
/****** Object:  StoredProcedure [dbo].[ccFaqByCategoryIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.30
--创建人：Nick
--说明：//根据类别获取常见问题信息
--#####################################################
CREATE PROCEDURE [dbo].[ccFaqByCategoryIDSelect]
(
	@CategoryID INT
)
AS
BEGIN TRY
	SELECT ID, Question,answer,CategoryID 
	FROM Faq WITH(NOLOCK) 
	WHERE Type=1 AND CategoryID =@CategoryID  
	ORDER BY Power
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[ccFaqSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ccFaqSelect]
AS
BEGIN
    SELECT ID, Question,CategoryID
    FROM Faq WITH(NOLOCK)
    WHERE Type=1
	ORDER BY Power
END








GO
/****** Object:  StoredProcedure [dbo].[ccFeeLogSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--Lambo 20110125
--查询单位的交费记录
CREATE PROCEDURE [dbo].[ccFeeLogSelect]
(
    @cpMainID INT
)
AS
BEGIN
	SELECT * FROM FeeLog WITH(NOLOCK) WHERE company_id = @cpMainID
END














GO
/****** Object:  StoredProcedure [dbo].[ccFnInvoiceByOrderIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.6
--创建人：John
--说明：根据订单ID获取发出发票的信息
--#####################################################
CREATE PROCEDURE [dbo].[ccFnInvoiceByOrderIDSelect]
(
	@OrderID INT
)
AS
BEGIN
	SELECT * FROM FnInvoice WITH(NOLOCK) WHERE Status = 1 AND OrderID = @OrderID
END


GO
/****** Object:  StoredProcedure [dbo].[ccFnLetterByInvoiceIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.6
--创建人：John
--说明：根据发票ID获取邮寄发票的信息
--#####################################################
CREATE PROCEDURE [dbo].[ccFnLetterByInvoiceIDSelect]
(
	@invoiceID INT
)
AS
BEGIN
	SELECT * FROM FnLetter WITH(NOLOCK) WHERE status <> 4 AND status <> 3 AND FnInvoiceID = @invoiceID
END


GO
/****** Object:  StoredProcedure [dbo].[ccFnLetterByOrderIDUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*********************
SEAN 2014-10-29
**********************/
CREATE PROCEDURE [dbo].[ccFnLetterByOrderIDUpdate]
(
	@ID INT,
	@CpName NVARCHAR(100)
)
AS
--INSERT INTO procLog SELECT 'ccFnLetterByOrderIDUpdate', '', GETDATE()
BEGIN
	UPDATE FnLetter
	SET Status = 2, ReceivedDate = GETDATE(), ReceivedManName = @CpName
	FROM FnInvoice 
	WHERE FnInvoice.OrderID = @ID
	AND FnLetter.FnInvoiceID = FnInvoice.ID
	AND FnLetter.Status = 1
END


GO
/****** Object:  StoredProcedure [dbo].[ccFnLetterReceiveByInvoiceIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.6
--创建人：John
--说明：根据发票ID获取邮寄发票收到的信息
--#####################################################
CREATE PROCEDURE [dbo].[ccFnLetterReceiveByInvoiceIDSelect]
(
	@invoiceID INT
)
AS
BEGIN
	SELECT * FROM FnLetter WITH(NOLOCK) WHERE Status = 2 AND FnInvoiceID = @invoiceID
END


GO
/****** Object:  StoredProcedure [dbo].[ccIndexPageByMSiteSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [dbo].[ccIndexPageByMSiteSelect]
(
    @cpMainID INT,
    @caMainID INT,
    @ProvinceID INT,
    @IsManager BIT,
    @Object VARCHAR(10)
)
AS
BEGIN
	DECLARE @t AS TABLE(
	  ID INT,
	  type INT,
	  iCount INT NULL,
	  Title NVARCHAR(100) NULL,
	  Link NVARCHAR(200) NULL,
	  ContentText NVARCHAR(500) NULL,
	  AddDate SMALLDATETIME NULL
	)
--取未付款订单
	INSERT INTO @T(ID,type,iCount) SELECT @cpMainID,0,count(1) FROM caOrder a WITH(NOLOCK) WHERE  (a.IsDeleted=0 OR a.IsDeleted IS NULL) AND a.cpMainID = @cpMainID AND OrderStatus = 0 AND AddDate > DATEADD(Month,-2,GETDATE())
--取未查看的网站消息
	INSERT INTO @T(ID,type,ContentText,AddDate,iCount) SELECT ID,1,Content,AddDate,type FROM CompanyNotify WITH(NOLOCK) WHERE CompanyID = @cpMainID AND ((Type=1 AND Received=0) Or (Type=2 AND EndDate>GETDATE())) ORDER BY AddDate DESC
--取未查看的反馈
	INSERT INTO @T(ID,type,ContentText,AddDate) SELECT Top 1 ID,2,ReplyMessage,ReplyDate FROM CaFeedBack WITH(NOLOCK) WHERE caMainID = @caMainID AND IsReply = 1 AND ViewDate IS NULL ORDER BY ID DESC
--取未查看的投诉
	IF @ISManager=1
		INSERT INTO @T(ID,type,ContentText,AddDate) SELECT TOP 1 a.ID,3,a.Plaint,a.AddDate FROM PaPlaint a WITH(NOLOCK INDEX(IX_paPlaint_caMainID)), caMain b WITH( NOLOCK INDEX(IX_caMain_cpMainID)) WHERE a.caMainID = b.ID AND b.cpMainID = @cpMainID AND IsViewed=0 AND ReplyType =1 ORDER BY a.CaMainID,a.ID DESC
	ELSE
		INSERT INTO @T(ID,type,ContentText,AddDate) SELECT TOP 1 ID,3,Plaint,AddDate FROM PaPlaint WITH(NOLOCK INDEX(IX_paPlaint_caMainID)) WHERE caMainID = @caMainID AND IsViewed=0 AND ReplyType =1 ORDER BY ID DESC
--取未查看的网站分类通知
	INSERT INTO @T(ID, type, Title, ContentText, link, iCount)
	SELECT TOP 1 ID, 4, Title, Content, link, Type 
	FROM CompanyInform WITH(NOLOCK) 
	WHERE Status = 1 
	AND Object LIKE '%' + @Object + '%'
	AND Province LIKE '%' + LTRIM(STR(@ProvinceID)) + '%'
	AND EndDate > GETDATE() ORDER BY AddDate DESC
--取当前调查
--	INSERT INTO @T(ID,type,ContentText) 
--	SELECT TOP 1 ID, 5, Title FROM Ivgt_Investigation WITH(NOLOCK) 
--	WHERE ENDdate > GETDATE() 
--	AND province Like '%' + LTRIM(STR(@provinceid)) + '%'
--	AND type = 1 
--	ORDER BY adddate

	--如果有1个月内到期的职位,修改截止日期
	BEGIN TRY
		UPDATE Job SET IssueEnd = DATEADD(MINUTE,-1, CONVERT(VARCHAR(10), DATEADD(MONTH, 2, GETDATE()) + 1, 120))
		WHERE caMainId = @caMainID
		AND IssueEnd < DATEADD(MONTH, 1, GETDATE())
		AND Valid = 1
		AND @cpMainId <> 10371941 
	END TRY
	BEGIN CATCH
	END CATCH

	IF @@ROWCOUNT > 0
	BEGIN
		INSERT INTO @T(ID, [Type], ContentText) VALUES(@caMainID, 6, '')
	END

	----面试通知
	--DECLARE @InterViewCnt INT
	--SELECT @InterViewCnt = COUNT(*)
	--FROM exInterview  WITH(NOLOCK)
	--WHERE JOBID IN (
	--	SELECT ID FROM JOB WITH(NOLOCK)
	--	WHERE CpMainID = @cpMainID
	--	AND CaMainID = @caMainID
	--) AND ResultDate IS NOT NULL
	--AND CpResultViewDate IS NULL

	--IF @InterViewCnt > 0
	--BEGIN
	--	INSERT INTO @T(ID, [Type], ContentText,AddDate) VALUES(@caMainID, 7, '有'+@InterViewCnt+'位求职者答复了面试通知',GETDATE())
	--END

	----求答复提醒
	--DECLARE @ReplyViewCnt INT
	--SELECT @ReplyViewCnt = COUNT(*)
	--FROM ExJobApply  WITH(NOLOCK)
	--WHERE JOBID IN (
	--	SELECT ID FROM JOB WITH(NOLOCK)
	--	WHERE CpMainID = @cpMainID
	--	AND CaMainID = @caMainID
	--) AND RemindDate IS NOT NULL
	--AND CpRemindViewDate IS NULL

	--IF @ReplyViewCnt > 0
	--BEGIN
	--	INSERT INTO @T(ID, [Type], ContentText,AddDate) VALUES(@caMainID, 8, @ReplyViewCnt,GETDATE())
	--END

	SELECT * FROM @T ORDER BY Type,ID
END

GO
/****** Object:  StoredProcedure [dbo].[ccIndexPageSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ccIndexPageSelect]
(
    @cpMainID INT,
    @caMainID INT,
    @ProvinceID INT,
    @IsManager BIT,
    @Object VARCHAR(10)
)
AS
BEGIN
	DECLARE @t AS TABLE(
	  ID INT,
	  type INT,
	  iCount INT NULL,
	  Title NVARCHAR(100) NULL,
	  Link NVARCHAR(200) NULL,
	  ContentText NVARCHAR(500) NULL,
	  AddDate SMALLDATETIME NULL
	)
--取未付款订单
	INSERT INTO @T(ID,type,iCount) SELECT @cpMainID,0,count(1) FROM caOrder a WITH(NOLOCK) WHERE  (a.IsDeleted=0 OR a.IsDeleted IS NULL) AND a.cpMainID = @cpMainID AND OrderStatus = 0 AND AddDate > DATEADD(Month,-2,GETDATE())
--取未查看的网站消息
	INSERT INTO @T(ID,type,ContentText,AddDate,iCount) SELECT ID,1,Content,AddDate,type FROM CompanyNotify WITH(NOLOCK) WHERE CompanyID = @cpMainID AND ((Type=1 AND Received=0) Or (Type=2 AND EndDate>GETDATE())) ORDER BY AddDate DESC
--取未查看的反馈
	INSERT INTO @T(ID,type,ContentText,AddDate) SELECT Top 1 ID,2,ReplyMessage,ReplyDate FROM CaFeedBack WITH(NOLOCK) WHERE caMainID = @caMainID AND IsReply = 1 AND ViewDate IS NULL ORDER BY ID DESC
--取未查看的投诉
	IF @ISManager=1
		INSERT INTO @T(ID,type,ContentText,AddDate) SELECT TOP 1 a.ID,3,a.Plaint,a.AddDate FROM PaPlaint a WITH(NOLOCK INDEX(IX_paPlaint_caMainID)), caMain b WITH( NOLOCK INDEX(IX_caMain_cpMainID)) WHERE a.caMainID = b.ID AND b.cpMainID = @cpMainID AND IsViewed=0 AND ReplyType =1 ORDER BY a.CaMainID,a.ID DESC
	ELSE
		INSERT INTO @T(ID,type,ContentText,AddDate) SELECT TOP 1 ID,3,Plaint,AddDate FROM PaPlaint WITH(NOLOCK INDEX(IX_paPlaint_caMainID)) WHERE caMainID = @caMainID AND IsViewed=0 AND ReplyType =1 ORDER BY ID DESC
--取未查看的网站分类通知
	INSERT INTO @T(ID, type, Title, ContentText, link, iCount)
	SELECT TOP 1 ID, 4, Title, Content, link, Type 
	FROM CompanyInform WITH(NOLOCK) 
	WHERE Status = 1 
	AND Object LIKE '%' + @Object + '%'
	AND Province LIKE '%' + LTRIM(STR(@ProvinceID)) + '%'
	AND EndDate > GETDATE() ORDER BY AddDate DESC
--取当前调查
	INSERT INTO @T(ID,type,ContentText) 
	SELECT TOP 1 ID,5,Title FROM Ivgt_Investigation WITH(NOLOCK) 
	WHERE ENDdate > GETDATE() 
	AND province Like '%' + LTRIM(STR(@provinceid)) + '%'
	AND type=1 
	ORDER BY adddate

	--如果有1个月内到期的职位,修改截止日期
	BEGIN TRY
		UPDATE Job SET IssueEnd = DATEADD(MINUTE,-1, CONVERT(VARCHAR(10), DATEADD(MONTH, 2, GETDATE()) + 1, 120))
		WHERE caMainId = @caMainID
		AND IssueEnd < DATEADD(MONTH, 1, GETDATE())
		AND Valid = 1
		AND @cpMainId <> 10371941 
	END TRY
	BEGIN CATCH
	END CATCH

	IF @@ROWCOUNT > 0
	BEGIN
		INSERT INTO @T(ID, [Type], ContentText) VALUES(@caMainID, 6, '')
	END

	----面试通知
	--DECLARE @InterViewCnt INT
	--SELECT @InterViewCnt = COUNT(*)
	--FROM exInterview  WITH(NOLOCK)
	--WHERE JOBID IN (
	--	SELECT ID FROM JOB WITH(NOLOCK)
	--	WHERE CpMainID = @cpMainID
	--	AND CaMainID = @caMainID
	--) AND ResultDate IS NOT NULL
	--AND CpResultViewDate IS NULL

	--IF @InterViewCnt > 0
	--BEGIN
	--	INSERT INTO @T(ID, [Type], ContentText,AddDate) VALUES(@caMainID, 7, '有'+@InterViewCnt+'位求职者答复了面试通知',GETDATE())
	--END

	----求答复提醒
	--DECLARE @ReplyViewCnt INT
	--SELECT @ReplyViewCnt = COUNT(*)
	--FROM ExJobApply  WITH(NOLOCK)
	--WHERE JOBID IN (
	--	SELECT ID FROM JOB WITH(NOLOCK)
	--	WHERE CpMainID = @cpMainID
	--	AND CaMainID = @caMainID
	--) AND RemindDate IS NOT NULL
	--AND CpRemindViewDate IS NULL

	--IF @ReplyViewCnt > 0
	--BEGIN
	--	INSERT INTO @T(ID, [Type], ContentText,AddDate) VALUES(@caMainID, 8, @ReplyViewCnt,GETDATE())
	--END

	SELECT * FROM @T ORDER BY Type,ID
END

GO
/****** Object:  StoredProcedure [dbo].[ccJobByCaMainIDIssuedSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--时间 2014-01-05
--查询某个企业用户发布的所有职位
CREATE PROCEDURE [dbo].[ccJobByCaMainIDIssuedSelect]
(
    @caMainID INT
)
AS
BEGIN
	SELECT a.ID,a.Name,a.IssueEnd,a.dcRegionID
	FROM Job a WITH(NOLOCK)
	WHERE a.caMainID = @caMainID AND a.IsDelete=0 AND a.IssueDate IS NOT NULL
	GROUP BY a.ID,a.Valid,a.IssueEnd,a.Name,a.dcRegionID
	ORDER BY a.Valid DESC,a.IssueEnd DESC
END

GO
/****** Object:  StoredProcedure [dbo].[ccJobByCaMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--修改harry 2017-10-19 修改status=1的显示定制刷新状态jobrefreshIng
--a;en 2018-4-9
CREATE PROCEDURE [dbo].[ccJobByCaMainIDSelect]
(
    @caMainID INT,
	@Status INT
)
AS
BEGIN
	IF @Status=0
		SELECT *,(SELECT COUNT(ID) FROM exJobApply WITH(NOLOCK) WHERE CompanyDeleted=0 AND JobID=Job.ID AND (IsFilter IS NULL OR IsFilter=0)) ApplyCount
		FROM Job WITH(NOLOCK)
		WHERE caMainID = @caMainID AND IsDelete=0 AND IssueDate IS NULL
		ORDER BY LastModifyDate DESC
	IF @Status=1
		SELECT *, CASE WHEN EXISTS(SELECT 'X' FROM jobRefreshLog WHERE jobId = job.id AND runDateTime is NULL) THEN 1 ELSE 0 END AS jobrefreshIng,
		(SELECT COUNT(ID) FROM exJobApply WITH(NOLOCK) WHERE CompanyDeleted=0 AND JobID=Job.ID AND (IsFilter IS NULL OR IsFilter=0)) ApplyCount
		FROM Job  WITH(NOLOCK)
		WHERE caMainID = @caMainID AND IsDelete=0 AND IssueEND > GETDATE()
		ORDER BY DisplayNo, IssueEnd, ID DESC
	IF @Status=2
		SELECT *,(SELECT COUNT(ID) FROM exJobApply WITH(NOLOCK) WHERE CompanyDeleted=0 AND JobID=Job.ID AND (IsFilter IS NULL OR IsFilter=0)) ApplyCount
		FROM Job WITH(NOLOCK)
		WHERE caMainID = @caMainID AND IsDelete=0 AND IssueEND < GETDATE()
		ORDER BY IssueEnd DESC
END

GO
/****** Object:  StoredProcedure [dbo].[ccJobBycaMainIDSelectAll]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[ccJobBycaMainIDSelectAll]
(
    @caMainID INT
)
AS
BEGIN
		SELECT *
		FROM Job WITH(NOLOCK)
		WHERE caMainID = @caMainID AND IsDelete=0
		ORDER BY DisplayNo,LastModifyDate DESC

END














GO
/****** Object:  StoredProcedure [dbo].[ccJobBycaMainIDSelectCount]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[ccJobBycaMainIDSelectCount]
(
    @caMainID INT
)
AS
BEGIN
		SELECT COUNT(*) cnt
		FROM Job WITH(NOLOCK)
		WHERE caMainID = @caMainID AND IsDelete=0 AND IssueDate IS NOT NULL
		AND IssueEnd > GETDATE()
END














GO
/****** Object:  StoredProcedure [dbo].[ccJobBycaMainIDSelectFilter]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ccJobBycaMainIDSelectFilter]
(
    @caMainID INT
)
AS
--INSERT INTO procLog select 'ccJobByCaMainIDSelectFilter', '', getdate()
BEGIN
	SELECT a.ID,a.Name,a.IssueEnd
	FROM Job a WITH(NOLOCK), exJobApply b WITH(NOLOCK)
	WHERE a.ID=b.JobID AND a.caMainID = @caMainID AND a.IsDelete=0 AND a.IssueDate IS NOT NULL
	GROUP BY a.ID,a.Valid,a.IssueEnd,a.Name
	ORDER BY a.Valid DESC,a.IssueEnd DESC
END


GO
/****** Object:  StoredProcedure [dbo].[ccJobBycaMainIDSelectHasIssued]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--修改人：harry2015-8-28
--管理员用户可以查看所有的职位
CREATE PROCEDURE [dbo].[ccJobBycaMainIDSelectHasIssued]
(
    @caMainID INT
)
AS
BEGIN
		DECLARE @cpMainId INT,@accountType INT
		SELECT @cpMainId=cpMainID, @accountType=AccountType
		FROM caMain
		WHERE ID=@caMainID
		IF @accountType=1
		BEGIN
			SELECT *
			FROM Job WITH(NOLOCK)
			WHERE cpMainID = @cpMainId AND IsDelete=0 AND IssueDate IS NOT NULL
			ORDER BY Valid DESC,DisplayNo,IssueEnd DESC,LastModifyDate DESC
		END
		ELSE
		BEGIN
			SELECT *
			FROM Job WITH(NOLOCK)
			WHERE caMainID = @caMainID AND IsDelete=0 AND IssueDate IS NOT NULL
			ORDER BY Valid DESC,DisplayNo,IssueEnd DESC,LastModifyDate DESC
		END
END

GO
/****** Object:  StoredProcedure [dbo].[ccJobByCaMainIDUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--lambo 20110616
--修改职位的所属用户
--[dbo].[ccJobByCaMainIDUpdate] 2458146,9041691,9041691
CREATE PROCEDURE [dbo].[ccJobByCaMainIDUpdate] 
	@ID INT,
	@caMainID INT,
    @cpMainID INT
AS
BEGIN TRAN
	BEGIN TRY
		IF EXISTS(SELECT 'x' FROM caMain WITH(NOLOCK) WHERE ID = @caMainID AND cpMainID = @cpMainID)
			BEGIN
				UPDATE Job SET caMainID = @caMainID WHERE ID = @ID AND cpMainID = @cpMainID
				UPDATE caFavorate SET caMainID = @caMainID WHERE JobID = @ID
				UPDATE paPlaint SET caMainID = @caMainID WHERE JobID = @ID
			END
		ELSE
			GOTO ERR
	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH
COMMIT TRAN
RETURN 1
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END














GO
/****** Object:  StoredProcedure [dbo].[ccJobByCpMainIDIssuedSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--Edit By Andy 2014-12-05
--添加a.dcRegionID列
CREATE PROCEDURE [dbo].[ccJobByCpMainIDIssuedSelect]
(
    @cpMainID INT
)
AS
BEGIN
	SELECT a.ID, a.Name,  a.IssueEnd, a.dcRegionID
	FROM Job a WITH(NOLOCK)
	WHERE a.cpMainID = @cpMainID 
	AND a.IsDelete=0 
	AND a.IssueDate IS NOT NULL
	ORDER BY a.Valid DESC, a.IssueEnd DESC	
END





GO
/****** Object:  StoredProcedure [dbo].[ccJobBycpMainIDNewSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--根据企业ID查询职位 20151121
CREATE PROCEDURE [dbo].[ccJobBycpMainIDNewSelect]
(
    @cpMainID INT,
	@Status INT,
	@PaMainID INT
)
AS
BEGIN
	IF @Status=0
	BEGIN
		SELECT *, 0 IsOnline,0 IsAttention INTO #T1
		FROM Job WITH(NOLOCK)
		WHERE cpMainID = @cpMainID AND IsDelete = 0 AND IssueDate IS NULL
		ORDER BY LastModifyDate DESC

		IF @PaMainID<>0
		BEGIN
			UPDATE #T1 SET IsAttention = 1
			WHERE ID IN(
				SELECT AttentionID FROM PaAttention 
				WHERE AttentionType = 2 AND PaMainID = @paMainID
			)
		END
		SELECT * FROM #T1
	END
	IF @Status=1
	BEGIN
		SELECT a.*, ISNULL(b.IsOnline, 0) IsOnline ,0 IsAttention INTO #T2
		FROM Job a WITH(NOLOCK)
		LEFT JOIN caOnline b WITH(NOLOCK) ON a.caMainId = b.caMainId
		WHERE a.cpMainID = @cpMainID AND a.Valid = 1
		ORDER BY a.DisplayNo, CONVERT(VARCHAR(4), a.dcJobtypeId)


		IF @PaMainID<>0
		BEGIN
			UPDATE #T2 SET IsAttention = 1
			WHERE ID IN(
				SELECT AttentionID FROM PaAttention 
				WHERE AttentionType = 2 AND PaMainID = @paMainID
			)
		END
		SELECT * FROM #2
	END
	IF @Status=2
	BEGIN
		SELECT *, 0 IsOnline,0 IsAttention INTO #T3
		FROM Job WITH(NOLOCK)
		WHERE cpMainID = @cpMainID AND IsDelete = 0 AND IssueEND < GETDATE()
		ORDER BY IssueEnd DESC

		IF @PaMainID<>0
		BEGIN
			UPDATE #T3 SET IsAttention = 1
			WHERE ID IN(
				SELECT AttentionID FROM PaAttention 
				WHERE AttentionType = 2 AND PaMainID = @paMainID
			)
		END
		SELECT * FROM #T3
	END
	IF @Status=3
	BEGIN
		SELECT *, 0 IsOnline,0 IsAttention INTO #T4
		FROM Job WITH(NOLOCK)
		WHERE cpMainID = @cpMainID AND IsDelete = 1 
		ORDER BY DisplayNo, LastModifyDate DESC

		IF @PaMainID<>0
		BEGIN
			UPDATE #T4 SET IsAttention = 1
			WHERE ID IN(
				SELECT AttentionID FROM PaAttention 
				WHERE AttentionType = 2 AND PaMainID = @paMainID
			)
		END
		SELECT * FROM #T4
	END
	IF @Status=4
	BEGIN
		SELECT a.*, b.FullName Region, 0 IsOnline,0 IsAttention INTO #T5
		FROM Job a WITH(NOLOCK)
		LEFT JOIN dcRegion b WITH(NOLOCK) ON a.dcRegionId = b.ID
		WHERE cpMainID = @cpMainID AND IsDelete = 0
		ORDER BY Valid DESC, DisplayNo, CONVERT(VARCHAR(4), dcJobtypeId)

		IF @PaMainID<>0
		BEGIN
			UPDATE #T5 SET IsAttention = 1
			WHERE ID IN(
				SELECT AttentionID FROM PaAttention 
				WHERE AttentionType = 2 AND PaMainID = @paMainID
			)
		END
		SELECT * FROM #T5
	END
	IF @Status=5
	BEGIN
		SELECT a.*, b.FullName Region, 
		(SELECT IsOnline FROM caOnline WHERE caOnline.caMainId = a.caMainId) IsOnline,0 IsAttention INTO #T6
		FROM Job a WITH(NOLOCK)
		LEFT JOIN dcRegion b WITH(NOLOCK) ON a.dcRegionId = b.ID
		WHERE cpMainID = @cpMainID AND IsDelete = 0 
		AND IssueEnd > GETDATE() AND IssueDate < GETDATE()
		ORDER BY DisplayNo, CONVERT(VARCHAR(4), dcJobtypeId)

		IF @PaMainID<>0
		BEGIN
			UPDATE #T6 SET IsAttention = 1
			WHERE ID IN(
				SELECT AttentionID FROM PaAttention 
				WHERE AttentionType = 2 AND PaMainID = @paMainID
			)
		END
		SELECT * FROM #T6
	END
END


GO
/****** Object:  StoredProcedure [dbo].[ccJobByCpMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--修改harry 2017-10-19 修改status=1的显示定制刷新状态jobrefreshIng
--lucifer 2018-4-2
CREATE PROCEDURE [dbo].[ccJobByCpMainIDSelect]
(
    @cpMainID INT,
    @Status INT
)
AS
SET NOCOUNT ON
BEGIN
    IF @Status=0
        SELECT *, 0 IsOnline, '' LogoUrl --dbo.GetCpLogo(cpMainID) LogoUrl
        FROM Job WITH(NOLOCK)
        WHERE cpMainID = @cpMainID AND IsDelete = 0 AND IssueDate IS NULL
        ORDER BY LastModifyDate DESC
    IF @Status=1
        SELECT a.*, ISNULL(b.IsOnline, 0) IsOnline, '' LogoUrl, CASE WHEN EXISTS(SELECT 'X' FROM jobRefreshLog WHERE jobId = a.id AND runDateTime is NULL) THEN 1 ELSE 0 END AS jobrefreshIng,
		(SELECT COUNT(ID) FROM exJobApply WITH(NOLOCK) WHERE CompanyDeleted=0 AND JobID=a.ID AND (IsFilter IS NULL OR IsFilter=0)) ApplyCount
        FROM Job a WITH(NOLOCK)
        LEFT JOIN caOnline b WITH(NOLOCK) ON a.caMainId = b.caMainId
        WHERE a.cpMainID = @cpMainID AND a.Valid = 1
        ORDER BY a.DisplayNo, CONVERT(VARCHAR(4), a.dcJobtypeId)
    IF @Status=2
        SELECT *, 0 IsOnline, '' LogoUrl, --dbo.GetCpLogo(cpMainID) LogoUrl,
		(SELECT COUNT(ID) FROM exJobApply WITH(NOLOCK) WHERE CompanyDeleted=0 AND JobID=Job.ID AND (IsFilter IS NULL OR IsFilter=0)) ApplyCount
        FROM Job WITH(NOLOCK)
        WHERE cpMainID = @cpMainID AND IsDelete = 0 AND IssueEND < GETDATE()
        ORDER BY IssueEnd DESC
    IF @Status=3
        SELECT *, 0 IsOnline, '' LogoUrl --dbo.GetCpLogo(cpMainID) LogoUrl
        FROM Job WITH(NOLOCK)
        WHERE cpMainID = @cpMainID AND IsDelete = 1 
        ORDER BY DisplayNo, LastModifyDate DESC
    IF @Status=4
        SELECT a.*, b.FullName Region, 0 IsOnline, '' LogoUrl --dbo.GetCpLogo(a.cpMainID) LogoUrl
        FROM Job a WITH(NOLOCK)
        LEFT JOIN dcRegion b WITH(NOLOCK) ON a.dcRegionId = b.ID
        WHERE cpMainID = @cpMainID AND IsDelete = 0
        ORDER BY Valid DESC, DisplayNo, CONVERT(VARCHAR(4), dcJobtypeId)
    IF @Status=5
        SELECT a.*, (b.MapBarName + (CASE LEN(dcRegionID) WHEN 6 THEN b.Description ELSE '' END)) Region, c.DescriptionCp Salary, d.DescriptionCp SalaryMax, e.Description Eudcation, f.Description Experience,
        (SELECT IsOnline FROM caOnline WHERE caOnline.caMainId = a.caMainId) IsOnline, '' LogoUrl --dbo.GetCpLogo(a.cpMainID) LogoUrl
        FROM Job a WITH(NOLOCK)
        LEFT JOIN dcRegion b WITH(NOLOCK) ON a.dcRegionId = b.ID
	LEFT JOIN dcSalary c WITH(NOLOCK) ON a.dcSalaryID = c.ID
	LEFT JOIN dcSalary d WITH(NOLOCK) ON a.dcSalaryIDMax = d.ID
	LEFT JOIN dcEducation e WITH(NOLOCK) ON a.dcEducationID = e.ID
	LEFT JOIN dcOthers f WITH(NOLOCK) ON a.MinExperience = f.DetailID AND f.Category = '职位要求工作经验'
        WHERE cpMainID = @cpMainID AND IsDelete = 0 
        AND IssueEnd > GETDATE() AND IssueDate < GETDATE()
        ORDER BY DisplayNo, CONVERT(VARCHAR(4), dcJobtypeId)
END
GO
/****** Object:  StoredProcedure [dbo].[ccJobBycpMainIDSelectFilter]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--Edit By Andy 2014-12-05
--添加a.dcRegionID列
CREATE PROCEDURE [dbo].[ccJobBycpMainIDSelectFilter]
(
    @cpMainID INT
)
AS
--INSERT INTO procLog select 'ccJobBycpMainIDSelectFilter', '', getdate()
BEGIN
	SELECT a.ID, a.Name,  a.IssueEnd, a.dcRegionID
	FROM Job a WITH(NOLOCK)
	WHERE a.cpMainID = @cpMainID 
	AND a.IsDelete=0 
	AND a.IssueDate IS NOT NULL
	ORDER BY a.Valid DESC, a.IssueEnd DESC	
END


GO
/****** Object:  StoredProcedure [dbo].[ccJobByEncryptViewSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--职位修改页面获取职位信息
CREATE PROCEDURE [dbo].[ccJobByEncryptViewSelect]
(
    @ID VARCHAR(12)
)
AS
BEGIN
    SELECT a.*, b.FullName Region, ISNULL(c.IsOnline, 0) IsOnline,
    STUFF((SELECT '@' + Tags FROM jobTags WITH(NOLOCK) WHERE jobID = a.ID FOR XML PATH('')),1,1,'') JobTags
    FROM Job a WITH(NOLOCK)
	INNER JOIN dcRegion b WITH(NOLOCK) ON a.dcRegionID = b.ID
	LEFT JOIN caOnline c WITH(NOLOCK) ON a.caMainId = c.caMainId
    WHERE a.SecondID = @ID
END
GO
/****** Object:  StoredProcedure [dbo].[ccJobByIssueStopUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--终止职位
--修改harry 增加职位刷新操作2017-11-8
CREATE PROCEDURE [dbo].[ccJobByIssueStopUpdate]
(
	@ID INT,
	@caMainID INT,
	@cpMainID INT
)
AS
BEGIN TRAN
	IF NOT EXISTS(SELECT 'x' FROM Job WHERE ID = @ID AND cpMainID = @cpMainID)
		GOTO ERR
	UPDATE JOB 
	SET IssueDate = (CASE WHEN IssueDate >= GETDATE() THEN CONVERT(VARCHAR(10), GETDATE(), 23) ELSE IssueDate END),
		IssueEnd = DATEADD(MINUTE, -1, GETDATE()) 
	WHERE ID = @ID
	
	UPDATE jobrefreshSet
	SET runState =0 
	WHERE runState =1 
	AND jobId = @ID

	----暂停职位
	--DECLARE @JobNum AS INT, @JobName AS NVARCHAR(100), @Desc AS NVARCHAR(200)
	--SELECT @JobName = LTRIM(RTRIM([Name])) FROM Job WITH(NOLOCK) WHERE ID = @ID
	--SET @Desc = '停止职位：编号<' + LTRIM(STR(@ID)) + '>职位名称<' + @JobName +'>。'
	--EXEC ccCaOperationLogInsert @caMainID, 41, @Desc
COMMIT TRAN
RETURN 1
ERR: 
BEGIN
	ROLLBACK TRAN
    RETURN 0
END

GO
/****** Object:  StoredProcedure [dbo].[ccJobByIssueUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--##############################################################################
--Sean 2012-4-20
--Cancel 计划发布职位：编号
--Peter 2016-10-17修改
--harry 管理员操作暂停用户的职位时有效2018-4-23 
--##############################################################################
CREATE PROCEDURE [dbo].[ccJobByIssueUpdate]
(
	@ID INT,
	@IssueDate SMALLDATETIME,
	@IssueEnd SMALLDATETIME,
	@maxJobNum INT,
	@cpMainId INT
)
AS
SET NOCOUNT ON
DECLARE @JobNum AS INT, @JobName AS NVARCHAR(100), @Desc AS NVARCHAR(200), @caMainID AS INT
IF ISNULL(@cpMainId, 0) != 10880312
BEGIN
	SET @IssueDate = DATEADD(MINUTE, -1, GETDATE())
	IF @IssueEnd < GETDATE()
		SET @IssueEnd = DATEADD(MONTH, 2, GETDATE())

	SET @IssueEnd = CONVERT(VARCHAR(10), @IssueEnd, 120) + ' 23:59'
	IF @IssueEnd < @IssueDate
		SET @IssueEnd = CONVERT(VARCHAR(10), @IssueDate, 120) + ' 23:59'

	BEGIN TRAN	
		BEGIN TRY
			IF NOT EXISTS(SELECT 'x' FROM Job WITH(NOLOCK) WHERE ID = @ID AND cpMainID = @cpMainID)
				GOTO ERR
			
			SELECT @JobName = LTRIM(RTRIM([Name])), @caMainID = caMainID FROM Job WITH(NOLOCK) WHERE ID = @ID

			IF @IssueEnd > GETDATE()
			BEGIN
				SELECT @JobNum = COUNT(*) FROM Job WITH(NOLOCK)
				WHERE IsDelete = 0 AND IssueDate<GETDATE() AND IssueEnd>GETDATE()
				AND cpMainID=@cpMainID AND ID <> @ID

				SELECT @maxJobNum = MaxJobNumber FROM cpMain WITH(NOLOCK) WHERE Id = @cpMainId
				IF @maxJobNum <= @JobNum
					GOTO ERR1
			END

			IF EXISTS(SELECT 'X' FROM caMain WITH(NOLOCK) WHERE ID=@caMainID AND IsPause=1)
			BEGIN
				--GOTO ERR2
				UPDATE job SET caMainId=(select TOP 1 id from caMain where cpmainid=@cpMainId AND accountType=1)
				FROM Job WITH(NOLOCK) WHERE ID = @ID
			END 
			UPDATE Job SET IssueDate = @IssueDate, IssueEnd = @IssueEnd WHERE ID=@ID

			----立即发布职位
			--SET @Desc = '发布职位：编号<' + LTRIM(STR(@ID)) + '>职位名称<' + @JobName +'>，有效期至' + CONVERT(VARCHAR(19), @IssueEnd, 120) + '。'
			--EXEC ccCaOperationLogInsert @caMainID, 40, @Desc
		
			INSERT INTO paPushLog(paMainID, PushMessage, PushType, DetailID)
			SELECT PaMainID, '亲，您关注的企业发布新职位啦！', 6, @ID FROM paAttention
			WHERE AttentionType = 1 AND AttentionID = @cpMainId AND EXISTS(
				SELECT 'X' FROM paIOSBind WHERE paMainID = paAttention.paMainID
			)
			--修改推送的相关信息
			IF EXISTS(SELECT 'x' FROM caPushSet WITH(NOLOCK) WHERE caMainID = @caMainID)
			BEGIN
				UPDATE caPushSet 
				SET PushNo = 0
				WHERE caMainID = @caMainID 
			END
			ELSE
			BEGIN
				INSERT INTO caPushSet(caMainID,PushFrequency,PushNo)
				VALUES (@CaMainID,99,0)
			END
		END TRY
		BEGIN CATCH
			RETURN -3
		END CATCH
	COMMIT TRAN
	RETURN 1
END
ELSE
------------------------------------------------------
BEGIN
	SET @IssueDate = DATEADD(MINUTE, -1, GETDATE())
	IF @IssueEnd < GETDATE()
		SET @IssueEnd = DATEADD(MONTH, 2, GETDATE())

	SET @IssueEnd = CONVERT(VARCHAR(10), @IssueEnd, 120) + ' 23:59'
	IF @IssueEnd < @IssueDate
		SET @IssueEnd = CONVERT(VARCHAR(10), @IssueDate, 120) + ' 23:59'

--	BEGIN TRAN	
--		BEGIN TRY
			IF NOT EXISTS(SELECT 'x' FROM Job WITH(NOLOCK) WHERE ID = @ID AND cpMainID = @cpMainID)
				GOTO ERR
			
--			DECLARE @JobNum AS INT, @JobName AS NVARCHAR(100), @Desc AS NVARCHAR(200), @caMainID AS INT

			SELECT @JobName = LTRIM(RTRIM([Name])), @caMainID = caMainID FROM Job WITH(NOLOCK) WHERE ID = @ID
			

			IF @IssueEnd > GETDATE()
			BEGIN
				SELECT @JobNum = COUNT(*) FROM Job WITH(NOLOCK)
				WHERE IsDelete = 0 AND IssueDate<GETDATE() AND IssueEnd>GETDATE()
				AND cpMainID=@cpMainID AND ID <> @ID

				SELECT @maxJobNum = MaxJobNumber FROM cpMain WITH(NOLOCK) WHERE Id = @cpMainId
				IF @maxJobNum <= @JobNum
					GOTO ERR1
			END

			IF EXISTS(SELECT 'X' FROM caMain WITH(NOLOCK) WHERE ID=@caMainID AND IsPause=1)
			BEGIN
				--GOTO ERR2
				UPDATE job SET caMainId=(select TOP 1 id from caMain where cpmainid=@cpMainId AND accountType=1)
				FROM Job WITH(NOLOCK) WHERE ID = @ID
			END 
			UPDATE Job SET IssueDate = @IssueDate, IssueEnd = @IssueEnd WHERE ID=@ID

			----立即发布职位
			--SET @Desc = '发布职位：编号<' + LTRIM(STR(@ID)) + '>职位名称<' + @JobName +'>，有效期至' + CONVERT(VARCHAR(19), @IssueEnd, 120) + '。'
			--EXEC ccCaOperationLogInsert @caMainID, 40, @Desc
		
			INSERT INTO paPushLog(paMainID, PushMessage, PushType, DetailID)
			SELECT PaMainID, '亲，您关注的企业发布新职位啦！', 6, @ID FROM paAttention
			WHERE AttentionType = 1 AND AttentionID = @cpMainId AND EXISTS(
				SELECT 'X' FROM paIOSBind WHERE paMainID = paAttention.paMainID
			)
			--修改推送的相关信息
			IF EXISTS(SELECT 'x' FROM caPushSet WITH(NOLOCK) WHERE caMainID = @caMainID)
			BEGIN
				UPDATE caPushSet 
				SET PushNo = 0
				WHERE caMainID = @caMainID 
			END
			ELSE
			BEGIN
				INSERT INTO caPushSet(caMainID,PushFrequency,PushNo)
				VALUES (@CaMainID,99,0)
			END
--		END TRY
--		BEGIN CATCH
--			GOTO ERR
--		END CATCH
--	COMMIT TRAN
	RETURN 1
END
---------------------------------------------------------------
ERR:
BEGIN
	IF ISNULL(@cpMainId, 0) != 10880312
		ROLLBACK TRAN
	RETURN 0
END
ERR1:
BEGIN
	IF ISNULL(@cpMainId, 0) != 10880312
		ROLLBACK TRAN
	RETURN -1
END
ERR2:
BEGIN
	IF ISNULL(@cpMainId, 0) != 10880312
		ROLLBACK TRAN
	RETURN -2
END



GO
/****** Object:  StoredProcedure [dbo].[ccJobByIssueUpdate2]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--##############################################################################
--Sean 2012-4-20
--Cancel 计划发布职位：编号
--##############################################################################
CREATE PROCEDURE [dbo].[ccJobByIssueUpdate2]
(
	@ID INT,
	@IssueDate SMALLDATETIME,
	@IssueEnd SMALLDATETIME,
	@maxJobNum INT,
	@cpMainId INT
)
AS
SET NOCOUNT ON
INSERT INTO aa SELECT @Id, @IssueDate, @IssueEnd, @MaxJobNum, @CpMainId
BEGIN
	SET @IssueDate = DATEADD(MINUTE, -1, GETDATE())
	SET @IssueEnd = CONVERT(VARCHAR(10), @IssueEnd, 120) + ' 23:59'
	IF @IssueEnd < @IssueDate
		SET @IssueEnd = CONVERT(VARCHAR(10), @IssueDate, 120) + ' 23:59'

	BEGIN TRAN	
		BEGIN TRY
			IF NOT EXISTS(SELECT 'x' FROM Job WITH(NOLOCK) WHERE ID = @ID AND cpMainID = @cpMainID)
				GOTO ERR
			
			DECLARE @JobNum AS INT, @JobName AS NVARCHAR(100), @Desc AS NVARCHAR(200), @caMainID AS INT

			SELECT @JobName = LTRIM(RTRIM([Name])), @caMainID = caMainID FROM Job WITH(NOLOCK) WHERE ID = @ID
			IF EXISTS(SELECT 'X' FROM caMain WITH(NOLOCK) WHERE ID=@caMainID AND IsPause=1)
				GOTO ERR2

			IF @IssueEnd > GETDATE()
			BEGIN
				SELECT @JobNum = COUNT(*) FROM Job WITH(NOLOCK)
				WHERE IsDelete = 0 AND IssueDate<GETDATE() AND IssueEnd>GETDATE() AND cpMainID=@cpMainID
				AND ID <> @ID	

				IF @maxJobNum <= @JobNum
					GOTO ERR1
			END
			UPDATE Job SET IssueDate = @IssueDate, IssueEnd = @IssueEnd WHERE ID=@ID

			----立即发布职位
			--SET @Desc = '发布职位：编号<' + LTRIM(STR(@ID)) + '>职位名称<' + @JobName +'>，有效期至' + CONVERT(VARCHAR(19), @IssueEnd, 120) + '。'
			--EXEC ccCaOperationLogInsert @caMainID, 40, @Desc
		END TRY
		BEGIN CATCH
			GOTO ERR
		END CATCH
	COMMIT TRAN
	RETURN 1
END
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END
ERR1:
BEGIN
	ROLLBACK TRAN
	RETURN -1
END
ERR2:
BEGIN
	ROLLBACK TRAN
	RETURN -2
END




GO
/****** Object:  StoredProcedure [dbo].[ccJobByIssueUpdate3]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--##############################################################################
--Sean 2012-4-20
--Cancel 计划发布职位：编号
--Peter 2016-10-17修改
--harry 管理员操作暂停用户的职位时有效2018-4-23
--##############################################################################
CREATE PROCEDURE [dbo].[ccJobByIssueUpdate3]
(
	@ID INT,
	@IssueDate SMALLDATETIME,
	@IssueEnd SMALLDATETIME,
	@maxJobNum INT,
	@cpMainId INT
)
AS
SET NOCOUNT ON
BEGIN
	SET @IssueDate = DATEADD(MINUTE, -1, GETDATE())
	IF @IssueEnd < GETDATE()
		SET @IssueEnd = DATEADD(MONTH, 2, GETDATE())

	SET @IssueEnd = CONVERT(VARCHAR(10), @IssueEnd, 120) + ' 23:59'
	IF @IssueEnd < @IssueDate
		SET @IssueEnd = CONVERT(VARCHAR(10), @IssueDate, 120) + ' 23:59'

	DECLARE @JobNum AS INT, @JobName AS NVARCHAR(100), @Desc AS NVARCHAR(200), @caMainID AS INT

	SELECT @JobName = LTRIM(RTRIM([Name])), @caMainID = caMainID FROM Job WITH(NOLOCK) WHERE ID = @ID			

	IF @IssueEnd > GETDATE()
	BEGIN
		SELECT @JobNum = COUNT(*) FROM Job WITH(NOLOCK)
		WHERE IsDelete = 0 AND IssueDate<GETDATE() AND IssueEnd>GETDATE()
		AND cpMainID=@cpMainID AND ID <> @ID

		SELECT @maxJobNum = MaxJobNumber FROM cpMain WITH(NOLOCK) WHERE Id = @cpMainId
		IF @maxJobNum <= @JobNum
			GOTO ERR1
	END

	IF EXISTS(SELECT 'X' FROM caMain WITH(NOLOCK) WHERE ID=@caMainID AND IsPause=1)
	BEGIN
		--GOTO ERR2
		UPDATE job SET caMainId=(select TOP 1 id from caMain where cpmainid=@cpMainId AND accountType=1)
		FROM Job WITH(NOLOCK) WHERE ID = @ID
	END 
	UPDATE Job SET IssueDate = @IssueDate, IssueEnd = @IssueEnd WHERE ID=@ID

	----立即发布职位
	--SET @Desc = '发布职位：编号<' + LTRIM(STR(@ID)) + '>职位名称<' + @JobName +'>，有效期至' + CONVERT(VARCHAR(19), @IssueEnd, 120) + '。'
	--EXEC ccCaOperationLogInsert @caMainID, 40, @Desc

	INSERT INTO paPushLog(paMainID, PushMessage, PushType, DetailID)
	SELECT PaMainID, '亲，您关注的企业发布新职位啦！', 6, @ID FROM paAttention
	WHERE AttentionType = 1 AND AttentionID = @cpMainId AND EXISTS(
		SELECT 'X' FROM paIOSBind WHERE paMainID = paAttention.paMainID
	)
	--修改推送的相关信息
	IF EXISTS(SELECT 'x' FROM caPushSet WITH(NOLOCK) WHERE caMainID = @caMainID)
	BEGIN
		UPDATE caPushSet 
		SET PushNo = 0
		WHERE caMainID = @caMainID 
	END
	ELSE
	BEGIN
		INSERT INTO caPushSet(caMainID,PushFrequency,PushNo)
		VALUES (@CaMainID,99,0)
	END

	RETURN 1
END
---------------------------------------------------------------
ERR:
BEGIN
	print 'aaa'
	RETURN 0
END
ERR1:
BEGIN
	select @maxJobNum , @JobNum
	print 'bbb'
	RETURN -1
END
ERR2:
BEGIN
	print 'ccc'
	RETURN -2
END


GO
/****** Object:  StoredProcedure [dbo].[ccJobByMapBarIDUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[ccJobByMapBarIDUpdate]
	@ID INT,
	@MapBarID VARCHAR(50),
	@cpMainID INT
AS
BEGIN
	UPDATE Job SET MapBarID=@MapBarID WHERE ID=@ID AND cpMainID = @cpMainID
END














GO
/****** Object:  StoredProcedure [dbo].[ccJobByMapBarUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ccJobByMapBarUpdate]
	@ID INT,
	@Lng VARCHAR(20),
	@Lat VARCHAR(20),
	@Address NVARCHAR(50),
	@cpMainID INT
AS
BEGIN
	UPDATE Job SET Lng=@Lng,Lat=@Lat WHERE ID=@ID AND cpMainID = @cpMainID
END









GO
/****** Object:  StoredProcedure [dbo].[ccJobByNameExist]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--sean 2013-1-30
--update ccJobNameExist
--nick 2013-07-22
--update 判断 发布中还是过期 重名
CREATE PROCEDURE [dbo].[ccJobByNameExist]
(
	@ID INT ,
	@cpMainID INT,
	@Name VARCHAR(100)
)
AS
SET NOCOUNT ON
INSERT INTO procLog select 'ccJobByNameExist', @ID, getdate()
BEGIN TRY
	DECLARE @IssueEnd DATETIME --截止时间
	SET @Name = LTRIM(RTRIM(@Name))
	SELECT @IssueEnd = IssueEnd 
	FROM Job WITH(NOLOCK) 
	WHERE NAME=@Name 
	AND ID<>@ID 
	AND cpMainID = @cpMainID 
	AND IsDelete = 0

	IF @IssueEND > GETDATE()
		RETURN 1  --发布中

	IF @IssueEND < GETDATE()
		RETURN 2  --已过期
	
	RETURN 0
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[ccJobByNameExist2]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--sean 2013-1-30
--update ccJobNameExist
--nick 2013-07-22
--update 判断 发布中还是过期 重名
CREATE PROCEDURE [dbo].[ccJobByNameExist2]
(
	@ID INT ,
	@cpMainID INT,
	@Name VARCHAR(100),
	@dcRegionId VARCHAR(6)
)
AS
SET NOCOUNT ON
--INSERT INTO procLog select 'ccJobByNameExist2', @ID, getdate()
--this proc is valid
IF @cpMainID = 10576676
	RETURN 0
BEGIN
	DECLARE @IssueEnd DATETIME --截止时间
	SET @Name = LTRIM(RTRIM(@Name))

	SELECT @IssueEnd = IssueEnd 
	FROM Job WITH(NOLOCK) 
	WHERE cpMainID = @cpMainID 
	AND Name = @Name 
	AND dcREgionId = @dcRegionId
	AND ID <> @ID 
	AND IsDelete = 0

	IF @IssueEND > GETDATE()
		RETURN 1  --发布中

	IF @IssueEND < GETDATE()
		RETURN 2  --已过期
	
	RETURN 0
END
GO
/****** Object:  StoredProcedure [dbo].[ccJobByRecentApplySelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ccJobByRecentApplySelect]
(
	@dcRegionID VARCHAR(50),	--求职地区
	@dcJobTypeID VARCHAR(50),	--期望职位类别
	@RowCount INT
)
AS
SET NOCOUNT ON
BEGIN
	SET @dcJobTypeID = dbo.FormatIDS(@dcJobTypeID)
	DECLARE @T_JobType AS TABLE(ID INT)
	DECLARE @JobTypeExpect AS VARCHAR(3000)
	DECLARE @T_Temp1 AS TABLE(ID INT)		--临时表，用于构建组合查询语句
	INSERT INTO @T_Temp1
	SELECT * FROM dbo.fnSplit(@dcJobTypeID, ',')
	INSERT INTO @T_JobType
	SELECT DISTINCT ID FROM dcJobType WITH(NOLOCK)
	WHERE ParentId IN(SELECT ID FROM @T_TEMP1) 
	OR ParentId2 in(SELECT ID FROM @T_TEMP1)
	OR ID IN(SELECT ID FROM @T_TEMP1)
	----生成in字符串
	SELECT @JobTypeExpect = ''
	SELECT @JobTypeExpect = (@JobTypeExpect + LTRIM(STR(ID) + ',')) FROM @T_JobType
	IF RIGHT(@JobTypeExpect, 1) = ','
		SET @JobTypeExpect = LEFT(@JobTypeExpect, LEN(@JobTypeExpect) - 1)
	
	DECLARE @T_JobPlace AS TABLE(ID INT)
	DECLARE @JobPlace AS VARCHAR(3000)
	INSERT INTO @T_JobPlace
	SELECT * FROM dbo.fnSplit(@dcRegionID, ',')
	SELECT @JobPlace = ''
	SELECT @JobPlace = (@JobPlace + ' OR c.dcRegionID Like ''' + LTRIM(STR(ID) + '%''')) FROM @T_JobPlace
	SELECT @JobPlace = (@JobPlace + ' OR c.dcRegionID = ''' + LTRIM(STR(LEFT(ID,2)))+'''' )
	FROM @T_JobPlace WHERE LEN(ID) > 2
	SELECT @JobPlace = (@JobPlace + ' OR c.dcRegionID = ''' + LTRIM(STR(LEFT(ID,4)))+'''' )
	FROM @T_JobPlace WHERE LEN(ID) > 4
	SET @JobPlace = RIGHT(@JobPlace, LEN(@JobPlace) -4)
	DECLARE @SQL AS VARCHAR(3000)
	SET @SQL = 'SELECT TOP ' + CONVERT(VARCHAR, @RowCount) + ' b.SecondID EnJobID, b.Name JobName, c.Name CpName,
			c.HasLicence, c.SecondID EnCpMainID, b.ID,dbo.GetCaOnlineStatus(b.caMainID) AS IsOnline,b.caMainID,
			b.dcRegionID, b.dcSalaryID, b.Refreshdate, b.Responsibility, b.Demand, b.dcEducationID,
			b.MinExperience, c.dcCompanySizeID, b.EmployType,b.Welfare1,b.Welfare2,b.Welfare3,b.Welfare4,b.Welfare5,b.Welfare6,b.Welfare7,b.Welfare8,
		b.Welfare9,b.Welfare10,b.Welfare11,b.Welfare12,b.Welfare13,b.Welfare14,b.Welfare15,b.Welfare16,
		b.Welfare17,b.Welfare18,b.Welfare19
		FROM exJobApply a WITH(NOLOCK), JobPublish b WITH(NOLOCK), cpMainPublish c WITH(NOLOCK)
		WHERE a.JobID = b.ID AND b.cpMainID = c.ID AND a.cvMainID IN(
			SELECT a.ID FROM cvMainPublish a WITH(NOLOCK)
			INNER JOIN paMainPublish b WITH(NOLOCK) ON a.paMainID = b.ID
			INNER JOIN cvJobPlacePublish c ON a.ID = c.cvMainID
			INNER JOIN cvJobTypePublish d ON a.ID = d.cvMainID
			WHERE d.dcJobTypeID IN(' + @JobTypeExpect +') AND (' + @JobPlace + ')
		) ORDER BY a.AddDate DESC'
	--PRINT(@SQL)
	EXEC(@SQL)
END
GO
/****** Object:  StoredProcedure [dbo].[ccJobByViewSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--Peter 2016-10-31修改读取职位订阅内容时区别
CREATE PROCEDURE [dbo].[ccJobByViewSelect]
(
	@ID INT
)
AS
BEGIN
	SELECT *, b.FullName Region, ISNULL(c.IsOnline, 0) IsOnline,dbo.Int2Bin(a.EMailSendFreq) PushFreq,
	STUFF((SELECT '@' + Tags FROM jobTags WITH(NOLOCK) WHERE jobID = a.ID FOR XML PATH('')),1,1,'') JobTags,
	ISNULL((SELECT Description FROM dcEducation WHERE Id = dcEducationId), '不限') Education, d.Name cpName,
	e.Description JobTypeName,f.Description JobTypeMinorName,g.Description NeedNumName,h.Description EmployTypeName,
	i.Description ExperienceName,j.DescriptionCp SalaryName,k.DescriptionCp SalaryMaxName
	FROM Job a WITH(NOLOCK)
	INNER JOIN dcRegion b WITH(NOLOCK) ON a.dcRegionID = b.ID
	LEFT JOIN caOnline c WITH(NOLOCK) ON a.caMainId = c.caMainId
	INNER JOIN cpMain d WITH(NOLOCK) ON a.cpMainId = d.ID
	LEFT JOIN dcJobType e WITH(NOLOCK) ON a.dcJobTypeId = e.ID
	LEFT JOIN dcJobType f WITH(NOLOCK) ON a.dcJobTypeIdMinor = f.ID
	LEFT JOIN dcOthers g WITH(NOLOCK) ON a.NeedNumber = g.DetailID AND g.Category = '招聘人数'
	LEFT JOIN dcOthers h WITH(NOLOCK) ON a.EmployType = h.DetailID AND h.Category = '工作性质'
	LEFT JOIN dcOthers i WITH(NOLOCK) ON a.MinExperience = i.DetailID AND i.Category = '职位要求工作经验'
	LEFT JOIN dcSalary j WITH(NOLOCK) ON a.dcSalaryId = j.ID 
	LEFT JOIN dcSalary k WITH(NOLOCK) ON a.dcSalaryIdMax = k.ID
	WHERE a.ID = @ID
END
GO
/****** Object:  StoredProcedure [dbo].[ccJobDelete]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ccJobDelete]
(
	@OperatorID INT,
	@ID INT,
	@caMainID INT
)
AS
BEGIN TRAN
	DECLARE @JobName AS NVARCHAR(100)
	DECLARE @caID AS INT
	DECLARE @jobnumber AS INT
	DECLARE @cpMainID AS INT
	DECLARE @cpID AS INT
	DECLARE @AccountType AS INT
	SELECT @JobName = Name, @caID = caMainId, @cpID = cpMainID FROM Job WITH(NOLOCK) WHERE ID = @ID
	SELECT @AccountType=AccountType,@cpMainID=cpMainID FROM caMain WITH(NOLOCK) WHERE id = @OperatorID
	IF @JobName Is NUll 
		GOTO ERR1
	IF @caID != @caMainID 
		BEGIN
			IF @AccountType != 1
				GOTO ERR2
			IF 	@cpMainID != @cpID
				GOTO ERR2								
		END
	
	IF EXISTS(SELECT 'x' FROM caMain WHERE Id = @caMainId)
		INSERT INTO caOperationLog(caMainId, Operation, Details, Ip)
		VALUES(@caMainId, 42, '删除职位：编号<' + LTRIM(STR(@ID)) + '>职位名称<' + @JobName + '>。', ' ')

	UPDATE Job SET isDelete = 1 WHERE id = @ID 

	INSERT INTO CaCvApplyDeleted(JobID, JobName, CvMainId, ApplyDate, AddDate, Reply)
	SELECT b.ID, b.Name, a.cvMainid, a.AddDate, GETDATE(), ISNULL(Reply, 0) 
	FROM exjobapply a,job b 
	WHERE a.jobid = b.id 
	AND b.id=@ID
	AND a.CompanyDeleted=0

	IF @@ERROR <> 0 
		GOTO ERR

	SELECT @JobNumber = COUNT(1) FROM Job WITH(NOLOCK)
	WHERE IsDelete = 0 
	AND IssueDate < GETDATE() 
	AND IssueEnd > GETDATE()
	AND cpMainID = @cpMainID

	UPDATE cpMain SET jobNumber = @jobnumber WHERE ID = @cpMainID
	DELETE FROM bsCpModify WHERE SubID = @ID AND Location Like 'c%'
COMMIT TRAN
RETURN 1
ERR: 
BEGIN
	ROLLBACK TRAN
    RETURN 0
END
ERR1:
BEGIN
	ROLLBACK TRAN
	RETURN -1
END
ERR2:
BEGIN
	ROLLBACK TRAN
	RETURN -2
END










GO
/****** Object:  StoredProcedure [dbo].[ccJobDeleteNew]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Create PROCEDURE [dbo].[ccJobDeleteNew]
(
	@OperatorID INT,
	@ID INT,
	@caMainID INT,
	@Ip VARCHAR(15)
)
AS
BEGIN TRAN
	DECLARE @JobName AS NVARCHAR(100)
	DECLARE @caID AS INT
	DECLARE @jobnumber AS INT
	DECLARE @cpMainID AS INT
	DECLARE @cpID AS INT
	DECLARE @AccountType AS INT
	SELECT @JobName = Name, @caID = caMainId, @cpID = cpMainID FROM Job WITH(NOLOCK) WHERE ID = @ID
	SELECT @AccountType=AccountType,@cpMainID=cpMainID FROM caMain WITH(NOLOCK) WHERE id = @OperatorID
	IF @JobName Is NUll 
		GOTO ERR1
	IF @caID != @caMainID 
		BEGIN
			IF @AccountType != 1
				GOTO ERR2
			IF 	@cpMainID != @cpID
				GOTO ERR2								
		END
	
	IF EXISTS(SELECT 'x' FROM caMain WHERE Id = @caMainId)
		INSERT INTO caOperationLog(caMainId, Operation, Details, Ip)
		VALUES(@caMainId, 42, '删除职位：编号<' + LTRIM(STR(@ID)) + '>职位名称<' + @JobName + '>。', @Ip)

	UPDATE Job SET isDelete = 1 WHERE id = @ID 

	INSERT INTO CaCvApplyDeleted(JobID, JobName, CvMainId, ApplyDate, AddDate, Reply)
	SELECT b.ID, b.Name, a.cvMainid, a.AddDate, GETDATE(), ISNULL(Reply, 0) 
	FROM exjobapply a,job b 
	WHERE a.jobid = b.id 
	AND b.id=@ID
	AND a.CompanyDeleted=0

	IF @@ERROR <> 0 
		GOTO ERR

	SELECT @JobNumber = COUNT(1) FROM Job WITH(NOLOCK)
	WHERE IsDelete = 0 
	AND IssueDate < GETDATE() 
	AND IssueEnd > GETDATE()
	AND cpMainID = @cpMainID

	UPDATE cpMain SET jobNumber = @jobnumber WHERE ID = @cpMainID
	DELETE FROM bsCpModify WHERE SubID = @ID AND Location Like 'c%'
COMMIT TRAN
RETURN 1
ERR: 
BEGIN
	ROLLBACK TRAN
    RETURN 0
END
ERR1:
BEGIN
	ROLLBACK TRAN
	RETURN -1
END
ERR2:
BEGIN
	ROLLBACK TRAN
	RETURN -2
END










GO
/****** Object:  StoredProcedure [dbo].[ccJobDisplayNoByAutoSortUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ccJobDisplayNoByAutoSortUpdate]
(
	@cpMainID INT,
	@Type INT
)
AS
BEGIN
	BEGIN TRY
		DECLARE @SQL VARCHAR(400)
		DECLARE @ColName VARCHAR(200)
		IF @Type = 0 
			SET @ColName = 'c.LastModifyDate DESC'
		IF @Type = 1 
			SET @ColName = 'c.IssueEnd'
		IF @Type = 2 
			SET @ColName = '(SELECT count(1) FROM exJobApply WITH(NOLOCK) WHERE jobID = c.id),CONVERT(VARCHAR(4), c.dcJobtypeId)'
		SET @SQL = 'UPDATE a SET displayno =b.num
			FROM Job a ,
				(SELECT ROW_NUMBER() OVER(ORDER BY ' + @ColName + ' ) num ,id
				FROM Job c WITH(NOLOCK) WHERE c.cpMainID = ' + LTRIM(STR(@cpMainID)) + '
				AND c.IsDelete=0 AND c.IssueEND>GETDATE() ) b 
			WHERE a.id = b.id AND a.IsDelete=0 AND a.IssueEND > GETDATE() 
			AND a.cpMainID = ' + LTRIM(STR(@cpMainID))
		EXEC(@SQL)
		RETURN 1
	END TRY
	BEGIN CATCH
		RETURN 0
	END CATCH
END














GO
/****** Object:  StoredProcedure [dbo].[ccJobDisplayNoByPlusTenUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ccJobDisplayNoByPlusTenUpdate]
(
	@cpMainID INT
)
AS
BEGIN
	BEGIN TRY
		UPDATE Job SET DisplayNO = DisplayNO + 10 
			WHERE cpMainID = @cpMainID 
	--		AND IssueDate < GETDATE() 
			AND IssueEND > GETDATE()
			AND IsDelete = 0
		UPDATE Job SET DisplayNO = 999 
			WHERE cpMainID = @cpMainID 
			AND DisplayNo > 999
		RETURN 1
	END TRY
	BEGIN CATCH
		RETURN 0
	END CATCH
END














GO
/****** Object:  StoredProcedure [dbo].[ccJobDisplayNoByResetUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ccJobDisplayNoByResetUpdate]
(
	@cpMainID INT
)
AS
BEGIN
	BEGIN TRY
		UPDATE Job SET DisplayNO = 1
			WHERE cpMainID = @cpMainID 
	--		AND IssueDate < GETDATE() 
			AND IssueEND > GETDATE()
			AND IsDelete = 0
		RETURN 1
	END TRY
	BEGIN CATCH
		RETURN 0
	END CATCH
END














GO
/****** Object:  StoredProcedure [dbo].[ccJobDisplayNoUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ccJobDisplayNoUpdate]
(
	@ID INT,
	@DisplayNO SMALLINT	,
	@cpMainID INT
)
AS
BEGIN
	BEGIN TRY
		UPDATE Job SET DisplayNo=@DisplayNO WHERE ID=@ID AND cpMainID = @cpMainID
		RETURN 1
	END TRY
	BEGIN CATCH
		RETURN 0
	END CATCH
END














GO
/****** Object:  StoredProcedure [dbo].[ccJobRefreshLogBypreRefreshDateTimeUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--职位刷新数计划任务
--每分钟执行一次，执行后分配订单号，更新职位刷新时间，同时刷新数remainJobRefreshQuota-1
--harry 2017-11-9
--修改harry 2018-5-14 修改过期的刷新只刷过期时间不超过1h的
CREATE PROCEDURE [dbo].[ccJobRefreshLogBypreRefreshDateTimeUpdate]
AS
--return
BEGIN
SET NOCOUNT ON	 
	--获取待执行的数据 preRefreshDateTime<DATEADD(minute,1,getdate()) AND refreshType=0 AND runDateTime IS NULL
	SELECT * INTO #t 
	FROM JobRefreshLog 
	WHERE preRefreshDateTime<=DATEADD(minute,1,getdate()) AND preRefreshDateTime>=DATEADD(hour,-1,getdate())  AND refreshType=0 AND runDateTime IS NULL
	
	--遍历#t
	DECLARE @Id INT, @jobId INT, @cpMainId INT, @orderId INT, @preRefreshDateTime DATETIME --职位,jobrefrshid 
	
	--获取所有可用的订单
	SELECT * INTO #tOrder FROM caOrder WITH(NOLOCK)
	WHERE cpMainID IN(SELECT DISTINCT cpMainId FROM #t)
	AND openDate is NOT NULL
	AND endDate >GETDATE()
	AND OrderType IN(8,15)
	AND ISNULL(remainJobRefreshQuota,0) != 0
	ORDER BY endDate 

	WHILE EXISTS (SELECT TOP 1  ID FROM #t)
	BEGIN 
		SELECT TOP 1 @Id = ID, @jobId = jobid, @cpMainId =cpMainId, @preRefreshDateTime =preRefreshDateTime  FROM #t
		IF EXISTS(SELECT 'X' FROM #tOrder WHERE cpMainId = @cpMainId AND openDate is NOT NULL AND endDate >GETDATE() AND OrderType IN(8,15) AND ISNULL(remainJobRefreshQuota,0) != 0 )
		BEGIN
			SELECT TOP 1 @orderId = Id 
			FROM #tOrder 
			WHERE cpMainId = @cpMainId 
			AND openDate is NOT NULL
			AND endDate >GETDATE()
			AND OrderType IN(8,15)
			AND ISNULL(remainJobRefreshQuota,0) != 0 
			ORDER BY endDate 
			--更新订单
			UPDATE caorder SET remainJobRefreshQuota =remainJobRefreshQuota -1
			WHERE id = @orderId
			--更新jobrefreshlog,
			UPDATE jobrefreshlog
			SET runDateTime =GETDATE(), orderId =  @orderId
			WHERE ID =@Id
			--更新job refrshdate
			UPDATE job 
			SET RefreshDate= @preRefreshDateTime
			WHERE id =@jobId				
		END
		ELSE
		BEGIN
			DELETE FROM jobrefreshlog WHERE ID= @Id
		END 
		DELETE FROM #t WHERE ID= @Id
	END
	DROP TABLE #tOrder
	DROP TABLE #t
SET NOCOUNT OFF
END


GO
/****** Object:  StoredProcedure [dbo].[ccJobRefreshLogBypreRefreshDateTimeUpdatetest]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--职位刷新数计划任务
--每分钟执行一次，执行后分配订单号，更新职位刷新时间，同时刷新数remainJobRefreshQuota-1
--harry 2017-11-9
CREATE PROCEDURE [dbo].[ccJobRefreshLogBypreRefreshDateTimeUpdatetest]
AS
BEGIN
SET NOCOUNT ON	 
	--获取待执行的数据 preRefreshDateTime<DATEADD(minute,1,getdate()) AND refreshType=0 AND runDateTime IS NULL
	SELECT * INTO #t 
	FROM JobRefreshLog 
	WHERE preRefreshDateTime<=DATEADD(minute,1,getdate()) AND refreshType=0 AND runDateTime IS NULL
	
	--遍历#t
	DECLARE @Id INT, @jobId INT, @cpMainId INT, @orderId INT, @preRefreshDateTime DATETIME --职位,jobrefrshid 
	
	--获取所有可用的订单
	SELECT * INTO #tOrder FROM caOrder WITH(NOLOCK)
	WHERE cpMainID IN(SELECT DISTINCT cpMainId FROM #t)
	AND openDate is NOT NULL
	AND endDate >GETDATE()
	AND OrderType IN(8,15)
	AND ISNULL(remainJobRefreshQuota,0) != 0
	ORDER BY endDate 

	WHILE EXISTS (SELECT TOP 1  ID FROM #t)
	BEGIN 
		SELECT TOP 1 @Id = ID, @jobId = jobid, @cpMainId =cpMainId, @preRefreshDateTime =preRefreshDateTime  FROM #t
		IF EXISTS(SELECT 'X' FROM #tOrder WHERE cpMainId = @cpMainId AND openDate is NOT NULL AND endDate >GETDATE() AND OrderType IN(8,15) AND ISNULL(remainJobRefreshQuota,0) != 0 )
		BEGIN
			SELECT TOP 1 @orderId = Id 
			FROM #tOrder 
			WHERE cpMainId = @cpMainId 
			AND openDate is NOT NULL
			AND endDate >GETDATE()
			AND OrderType IN(8,15)
			AND ISNULL(remainJobRefreshQuota,0) != 0 
			ORDER BY endDate 
			--更新订单
			UPDATE caorder SET remainJobRefreshQuota =remainJobRefreshQuota -1
			WHERE id = @orderId
			--更新jobrefreshlog,
			UPDATE jobrefreshlog
			SET runDateTime =GETDATE(), orderId =  @orderId
			WHERE ID =@Id
			--更新job refrshdate
			UPDATE job 
			SET RefreshDate= @preRefreshDateTime
			WHERE id =@jobId
				
		END
		ELSE
		BEGIN
			DELETE FROM jobrefreshlog WHERE ID= @Id
		END 
		DELETE FROM #t WHERE ID= @Id
	END
	DROP TABLE #tOrder
	DROP TABLE #t
SET NOCOUNT OFF
END

GO
/****** Object:  StoredProcedure [dbo].[ccJobRefreshLogInsertByJobId]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
---职位刷新数手动刷新
---harry
---返回值 -1 可用刷新数不够,其它为刷新成功数量
---2017-11-2
CREATE PROCEDURE [dbo].[ccJobRefreshLogInsertByJobId]
(
	@jobIds VARCHAR(200),
	@caMainId INT,
	@cpMainId INT 
)
AS
BEGIN
	--职位id
	DECLARE @jobId INT
	DECLARE @jobInfo NVARCHAR(200)
	DECLARE @TjobId AS TABLE(jobId INT, jobInfo NVARCHAR(200)) 
	INSERT INTO @TjobId (jobId)
	SELECT * FROM dbo.fnSplit(@jobIds, ',') 
	--更新职位信息
	UPDATE @TjobId
	SET jobInfo= (SELECT name+','+ b.FullName FROM job a WITH(NOLOCK), dcregion b WITH(NOLOCK) WHERE a.id = jobId AND a.dcregionid = b.id)
	
	--判断是否可用
	CREATE TABLE #temp(availableNumber INT)
	INSERT INTO #temp EXEC ccCaorderByremainJobRefreshQuotaSelect @cpMainId, @caMainId, @jobIds
	 
	DECLARE @availableNumber INT
	SELECT TOP 1 @availableNumber = availableNumber FROM #temp
	IF @availableNumber=0 OR @availableNumber< (SELECT COUNT(1) FROM @TjobId)
	BEGIN
		DROP TABLE #temp
		SELECT -1 AS result
	END
	ELSE
	BEGIN
		--获取所有可用的订单
		SELECT * INTO #tOrder FROM caOrder WITH(NOLOCK)
		WHERE cpMainID = @cpMainID
		AND openDate is NOT NULL
		AND endDate >GETDATE()
		AND OrderType IN(8,15)
		AND ISNULL(remainJobRefreshQuota,0) != 0
		AND IsDeleted !=1
		ORDER BY endDate 
		
		DECLARE @successNum INT 
		SELECT @successNum = 0
		DECLARE @caoderId INT, @remainJobRefreshQuota INT
		WHILE EXISTS(SELECT TOP 1 id FROM #tOrder) AND EXISTS(SELECT 'x' FROM  @TjobId)
		BEGIN
			SELECT TOP 1 @caoderId = id, @remainJobRefreshQuota = remainJobRefreshQuota FROM #tOrder ORDER BY endDate 
			WHILE @remainJobRefreshQuota > 0 AND EXISTS(SELECT 'x' FROM  @TjobId)
			BEGIN
				SELECT TOP 1 @jobId =jobId, @jobInfo = jobInfo FROM @TjobId
				---插入刷新log
				INSERT INTO jobRefreshLog(orderId, jobId, jobInfo, refreshType,preRefreshDateTime, runDateTime,	operateMan, cpMainId)
				SELECT @caoderId, @jobId, @jobInfo, 1, GETDATE(), GETDATE(), @caMainId,@cpMainId
				---更新刷新时间
				UPDATE job SET refreshDate = GETDATE() WHERE id = @jobId
				--刷新数减去1
				UPDATE caorder SET remainJobRefreshQuota= remainJobRefreshQuota-1 WHERE id =@caoderId
				SELECT @remainJobRefreshQuota=@remainJobRefreshQuota-1
				DELETE FROM @TjobId WHERE jobId = @jobId
				--成功数+1
				SELECT @successNum = @successNum+1
			END
			DELETE FROM #tOrder WHERE id = @caoderId 
		END
		DROP TABLE #temp
		DROP TABLE #tOrder
		SELECT @successNum AS result
	END 
END

GO
/****** Object:  StoredProcedure [dbo].[ccJobRefreshSetByRunStateSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--过滤掉正在刷新数定制中的职位，返回未定制的职位信息
--harry
--2017-11-6
CREATE PROCEDURE [dbo].[ccJobRefreshSetByRunStateSelect]
(
	@jobIds VARCHAR(200)
)
AS
BEGIN
	--职位id
	DECLARE @TjobId AS TABLE(jobId INT) 
		 
	INSERT INTO @TjobId (jobId)
	SELECT * FROM dbo.fnSplit(@jobIds, ',')
	
	--校正定制刷新的状态
	UPDATE  a SET a.runState =0
	FROM jobRefreshSet a 
	WHERE a.runState =1 AND a.jobId IN(SELECT jobId FROM @TjobId ) AND NOT EXISTS(SELECT 'x' FROM jobrefreshLog WITH(NOLOCK) WHERE jobid= a.jobId AND refreshType=0 and runDateTime is null )

	DELETE FROM @TjobId WHERE jobId IN( SELECT jobId FROM JobRefreshSet WHERE jobId IN(SELECT jobId FROM @TjobId ) AND runState = 1)--删除定制中的jobid
	
	SELECT jobId FROM @TjobId --返回非定制中的职位id,最大开始时间 最小结束时间

    	SELECT  MAX(IssueDate) AS MaxIssueDate ,MIN(IssueEnd) AS MinIssueEnd 
	FROM job WHERE id in(select jobId FROM @TjobId) AND valid=1
END

GO
/****** Object:  StoredProcedure [dbo].[ccJobRefreshSetInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--刷新数定制刷新设置
--harry
--2017-11-3
CREATE PROCEDURE [dbo].[ccJobRefreshSetInsert]
(
	@beginDate	SMALLDATETIME,
	@endDate SMALLDATETIME,
	@refreshType TINYINT, --1d 2week
	@weekDays CHAR(13),
	@hours VARCHAR(100),
	@minute	INT,
	@jobIds VARCHAR(200),
	@caMainId INT,
	@cpMainId INT 
)
AS
BEGIN
	--职位id
	DECLARE @jobId INT, @jobRefreshSetId INT 
	DECLARE @TjobId AS TABLE(jobId INT) 
	INSERT INTO @TjobId (jobId)
	SELECT * FROM dbo.fnSplit(@jobIds, ',') 
	 
	WHILE EXISTS (SELECT TOP 1  jobid FROM @TjobId)
	BEGIN 
		SELECT TOP 1 @jobId = jobid  FROM @TjobId 
		IF NOT EXISTS(SELECT 'x' FROM jobRefreshset WITH(NOLOCK) WHERE jobid = @jobId AND runState =1 )--排除定制中的职位
		BEGIN
			DELETE FROM jobRefreshset WHERE jobid = @jobId AND runState = 0
			INSERT INTO jobRefreshset(beginDate, endDate, refreshType, weekDays,[hours],[minute], jobId, caMainId, runState, addDate)
			SELECT @beginDate, @endDate, @refreshType, @weekDays, @hours, @minute, @jobId, @caMainId, 1, GETDATE() 
			SELECT @jobRefreshSetId =SCOPE_IDENTITY()
			--选取jobrefreshlog_temp表中预插入的数据
			INSERT INTO jobRefreshLog(jobRefreshSetId, jobId, jobInfo, refreshType, preRefreshDateTime, operateMan, cpMainId)
			SELECT @jobRefreshSetId, @jobId, jobInfo,refreshType, preRefreshDateTime, @caMainId, @cpMainId
			FROM jobRefreshLog_temp 
			WHERE jobid = @jobId AND operateMan = @caMainId AND cpMainId = @cpMainId AND ISNULL(jobRefreshSetId,0) = 0 AND preRefreshDateTime BETWEEN @beginDate AND DATEADD(DAY,1,@endDate) AND refreshType =0
			
			--删除以插入的数据
			DELETE FROM jobRefreshLog_temp
			WHERE jobid = @jobId AND operateMan = @caMainId AND cpMainId = @cpMainId AND ISNULL(jobRefreshSetId,0) = 0 AND preRefreshDateTime BETWEEN @beginDate AND DATEADD(DAY,1,@endDate) AND refreshType =0
		END
		DELETE FROM @TjobId WHERE jobid = @jobId
	END 
END

GO
/****** Object:  StoredProcedure [dbo].[ccJobRefreshSetSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--根据职位id获取职位的定制信息
--harry
--2017-11-6
CREATE PROCEDURE [dbo].[ccJobRefreshSetSelect]
(
    @jobId INT
)
AS
SET NOCOUNT ON
BEGIN
    CREATE TABLE #t
    (
    [refreshType] [tinyint] NULL,
    [weekDays] [char](13) NULL,
    [hours] [varchar](100) NULL,
    [minute] [tinyint] NULL,
    [jobId] [int] NOT NULL, 
    [runState] [tinyint] NULL,
    [IssueDate] DATETIME NOT NULL,
    [IssueEnd] DATETIME NOT NULL,
    [beginDate] SMALLDATETIME NULL,
    [endDate] SMALLDATETIME NULL
    )
    --校正定制刷新的状态
    UPDATE a SET a.runState =0
    FROM jobRefreshSet a 
    WHERE a.runState =1 AND a.jobId =@jobId AND NOT EXISTS(SELECT 'x' FROM jobrefreshLog WITH(NOLOCK) WHERE jobid= @jobId AND refreshType=0 and runDateTime is null )

    INSERT INTO #t(jobId, IssueDate,IssueEnd)
    SELECT id, IssueDate, IssueEnd FROM job WHERE id = @jobId
    
    IF EXISTS( SELECT 'X' FROM jobRefreshset WHERE jobid = @jobId)
    BEGIN
        UPDATE a
        SET a.beginDate = b.beginDate, a.endDate = b.endDate, a.refreshType =b.refreshType, a.weekDays= b.weekDays, a.[hours] = b.[hours], a.[minute]=b.[minute], a.runState= b.runState
        FROM #t a, jobRefreshset b
        WHERE a.jobId =b.jobId AND b.Id =(SELECT TOP 1 id FROM jobRefreshset WHERE jobid = @jobId ORDER BY addDate DESC,ID DESC)
        
    END
    SELECT * FROM #t
    DROP TABLE #t    
END
GO
/****** Object:  StoredProcedure [dbo].[ccJobRefrshSetUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--停止职位刷新的定制
--harry
--2017-11-3
CREATE PROCEDURE [dbo].[ccJobRefrshSetUpdate]
(
	@jobIds VARCHAR(200),
	@cpMainId INT
)
AS
BEGIN
	--职位id
	DECLARE @jobId INT, @usedRefreshNum INT , @setId INT
	DECLARE @TjobId AS TABLE(jobId INT)
	DECLARE @TsetId AS TABLE(setId INT)
	INSERT INTO @TjobId (jobId)
	SELECT * FROM dbo.fnSplit(@jobIds, ',') 
	INSERT INTO @TsetId(setId)
        SELECT id FROM jobRefreshSet  WHERE jobId IN(SELECT jobId FROM @TjobId) AND runState =1
        --设置set runState =0 
	UPDATE jobRefreshSet SET runState = 0 WHERE id IN(select setId FROM @TsetId) AND runState =1
	--删除未执行的定制刷新
	DELETE FROM jobRefreshLog WHERE runDateTime IS NULL AND jobRefreshSetId IN(select setId FROM @TsetId) AND refreshType =0 
	--计算使用的刷新数
	SELECT @usedRefreshNum = COUNT(1) FROM jobRefreshLog WHERE runDateTime IS NOT NULL AND cpMainId = @cpMainId AND jobId IN(SELECT jobId FROM @TjobId) AND refreshType =0 AND jobRefreshSetId IN (select setId FROM @TsetId)
	
	--返回使用的刷新数
	SELECT @usedRefreshNum AS usedRefreshNum
	
END

GO
/****** Object:  StoredProcedure [dbo].[ccjobReportDataSelectByCpMainId]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--职位发布效果统计
--harry 
--2017-11-27
CREATE PROCEDURE [dbo].[ccjobReportDataSelectByCpMainId]
(
	@cpMainId INT,
	@beginDate INT,
	@endDate INT,
	@caMainId INT
)
AS
SET NOCOUNT ON
BEGIN
	IF @caMainId = 0
	BEGIN
		SELECT b.name, a.jobid, a.countdate,SUM(applycount) applycount,SUM(viewcount) viewcount,SUM(interview) interview,
		SUM(interviewreply) interviewreply,SUM(interviewresult) interviewresult 
		FROM ReportDB..jobReportData a WITH(NOLOCK),job b WITH(NOLOCK)
		WHERE a.countdate>=@beginDate 
		AND a.countdate<= @endDate
		AND a.jobid =b.id 
		AND a.jobid in (
				(
					SELECT id FROM Job with(nolock) 
					WHERE isdelete=0 
					AND cpmainid= @cpMainId 
				) union (
					SELECT jobid id 
					FROM JobDeleted WITH(NOLOCK) 
					WHERE cpmainid= @cpMainId 
				)
			) 
		GROUP BY a.jobid,a.countdate,b.name
		ORDER BY a.countdate
	END
	ELSE
	BEGIN
		SELECT b.name, a.jobid, a.countdate,SUM(applycount) applycount,SUM(viewcount) viewcount,SUM(interview) interview,
		SUM(interviewreply) interviewreply,SUM(interviewresult) interviewresult 
		FROM ReportDB..jobReportData a WITH(NOLOCK),job b WITH(NOLOCK)
		WHERE a.countdate>=@beginDate 
		AND a.countdate<= @endDate
		AND a.jobid =b.id 
		AND a.jobid in (
				(
					SELECT id FROM Job with(nolock) 
					WHERE isdelete=0 
					AND camainid= @caMainId 
				) union (
					SELECT jobid id 
					FROM JobDeleted WITH(NOLOCK) 
					WHERE camainid= @caMainId 
				)
			) 
		GROUP BY a.jobid,a.countdate,b.name
		ORDER BY a.countdate
	END
END
SET NOCOUNT OFF

GO
/****** Object:  StoredProcedure [dbo].[ccJobSave]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--nick 20130815 update
--去掉filtercvmainid相关内容
--Peter 2016-10-31修改 订阅方式的修改
-- 应该已经被ｃｃｊｏｂｓａｖｅｎｅｗ取代了
CREATE PROCEDURE [dbo].[ccJobSave]
(
	@OperatorID INT, 
	@ID INT, 
	@cpMainID INT, 
	@caMainID INT, 
	@Name VARCHAR(50), 
	@dcJobTypeID INT, 
	@dcJobTypeIDMinor INT, 
	@NeedNumber SMALLINT, 
	@dcSalaryID TINYINT, 
	@EmployType TINYINT, 
	@dcRegionID VARCHAR(6), 
	@Lng DECIMAL(8, 5), 
	@Lat DECIMAL(8, 5), 
	@Responsibility VARCHAR(MAX), 
	@Demand VARCHAR(MAX), 
	@dcEducationID TINYINT, 
	@MinExperience TINYINT, 
	@MinAge TINYINT, 
	@MaxAge TINYINT, 
	@EMailSendFreq VARCHAR(7), 
	@EMailSendNumber TINYINT, 
	--屏蔽简历相关
	@FilterMaxDegree TINYINT, 
	@FilterMinDegree TINYINT, 
	@FilterMaxWorkYear TINYINT, 
	@FilterMinWorkYear TINYINT, 
	@FilterMaxAge TINYINT, 
	@FilterMinAge TINYINT, 
	@FilterGender VARCHAR(1), 
	@FilterJobRegion VARCHAR(6), 
	@ForwardEmail VARCHAR(100)
)
AS
return
SET NOCOUNT ON
IF @dcRegionID NOT LIKE '[0-9]%'
RETURN -1
IF ISNULL(@dcSalaryID, 0) = 0
	SET @dcSalaryID = 100
IF ISNULL(@dcEducationID, 0) = 0
	SET @dcEducationID = 100
BEGIN TRAN
	BEGIN TRY
		SET @Name = dbo.TrimNull(@Name)
		IF @Name IS NULL
			GOTO Err
		-- Can Not Name Repeat
		IF @cpMainID <> 10576676
		BEGIN
			IF EXISTS(SELECT 'x' FROM Job WITH(NOLOCK) 
				WHERE Name = @Name 
				AND dcRegionId = @dcRegionID
				AND cpMainId = @CpMainId 
				AND ID <> ISNULL(@ID, 0) 
				AND IsDelete = 0)
				GOTO Err1
		END

		SET @Responsibility = REPLACE(dbo.TextTrim(@Responsibility), '', '')
		SET @Demand = REPLACE(dbo.TextTrim(@Demand), '', '')
		IF CHARINDEX(', ', @Name) > 0
			SELECT @Name = REPLACE(@Name, ',', '，')
		DECLARE @MaxID AS INT
		IF @ID>0
		BEGIN
			IF @OperatorID <> (SELECT ID FROM caMain WITH(NOLOCK) WHERE cpMainID = @cpMainID AND AccountType = 1) AND @OperatorID<>@caMainID
				RETURN 0

			DECLARE @NameOld AS NVARCHAR(60), @ResponsibilityOld AS VARCHAR(MAX), 
				@DemandOld AS VARCHAR(MAX), @IsVerify AS BIT
			SELECT @NameOld = dbo.TextTrim(ISNULL(Name, '')), @ResponsibilityOld = ISNULL(Responsibility, ''), 
				@DemandOld = ISNULL(Demand, '')
			FROM Job WITH(NOLOCK)
			WHERE ID = @ID

			UPDATE Job SET
				Name = @Name, 
				dcJobTypeID = @dcJobTypeID, 
				dcJobTypeIDMinor = @dcJobTypeIDMinor, 
				NeedNumber = @NeedNumber, 
				dcSalaryID = @dcSalaryID, 
				EmployType = @EmployType, 
				dcRegionID = @dcRegionID, 
				Lng = @Lng, 
				Lat = @Lat, 
				Responsibility = @Responsibility, 
				Demand = @Demand, 
				dcEducationID = @dcEducationID, 
				MinExperience = @MinExperience, 
				MinAge = @MinAge, 
				MaxAge = @MaxAge, 
				EMailSendFreq = dbo.BinToINT(@EMailSendFreq), 
				RefreshDate = GETDATE(), 
				LastModifyDate = GETDATE(), 
				FilterMaxDegree = @FilterMaxDegree, 
				FilterMinDegree = @FilterMinDegree, 
				FilterMaxWorkYear = @FilterMaxWorkYear, 
				FilterMinWorkYear = @FilterMinWorkYear, 
				FilterMaxAge = @FilterMaxAge, 
				FilterMinAge = @FilterMinAge, 
				FilterGender = @FilterGender, 
				FilterJobRegion = @FilterJobRegion, 
				ForwardEmail = @ForwardEmail
			WHERE ID = @ID
			SET @MaxID = @ID

			SET @IsVerify = 0
			IF @NameOld <> dbo.TextTrim(@Name)
			BEGIN
				DELETE FROM bsCpModify WHERE SubId = @ID AND Location = 'c1'
				INSERT INTO bsCpModify (cpMainID, caMainID, SubID, Location, ColValue) VALUES (@cpMainID, @caMainID, @ID, 'c1', @Name)
				SET @IsVerify = 1
			END

			IF @ResponsibilityOld <> @Responsibility
			BEGIN
				DELETE FROM bsCpModify WHERE SubId = @ID AND Location = 'c2'
				INSERT INTO bsCpModify (cpMainID, caMainID, SubID, Location, ColValue) VALUES (@cpMainID, @caMainID, @ID, 'c2', @Responsibility)
				SET @IsVerify = 1
			END

			IF @DemandOld <> @Demand
			BEGIN
				DELETE FROM bsCpModify WHERE SubId = @ID AND Location = 'c3'
				INSERT INTO bsCpModify (cpMainID, caMainID, SubID, Location, ColValue) VALUES (@cpMainID, @caMainID, @ID, 'c3', @Demand)
				SET @IsVerify = 1
			END
		END
		ELSE
		BEGIN
			INSERT INTO Job
				(
					cpMainID, caMainID, Name, dcJobTypeID, dcJobTypeIDMinor, 
					NeedNumber, dcSalaryID, EmployType, dcRegionID, Lng, Lat, 
					Responsibility, Demand, dcEducationID, MinExperience, 
					MinAge, MaxAge, EMailSendFreq, 
					AddDate, LastModifyDate, RefreshDate, IssueDate, IssueEnd, 
					FilterMaxDegree, FilterMinDegree, FilterMaxWorkYear, FilterMinWorkYear, 
					FilterMaxAge, FilterMinAge, FilterGender, FilterJobRegion, 
					ForwardEmail
				)
			VALUES
				(
					@cpMainID, @caMainID, @Name, @dcJobTypeID, @dcJobTypeIDMinor, 
					@NeedNumber, @dcSalaryID, @EmployType, @dcRegionID, @Lng, @Lat, 
					@Responsibility, @Demand, @dcEducationID, @MinExperience, 
					@MinAge, @MaxAge, dbo.BinToINT(@EMailSendFreq), 
					GETDATE(), GETDATE(), GETDATE(), GETDATE(), DATEADD(MONTH, 2, GETDATE()), 
					@FilterMaxDegree, @FilterMinDegree, @FilterMaxWorkYear, @FilterMinWorkYear, 
					@FilterMaxAge, @FilterMinAge, @FilterGender, @FilterJobRegion, 
					@ForwardEmail
				)

			SET @MaxID = @@IDENTITY

			INSERT INTO bsCpModify (cpMainID, caMainID, SubID, Location, ColValue) VALUES (@cpMainID, @caMainID, @MaxID, 'c1', @Name)
			INSERT INTO bsCpModify (cpMainID, caMainID, SubID, Location, ColValue) VALUES (@cpMainID, @caMainID, @MaxID, 'c2', @Responsibility)
			INSERT INTO bsCpModify (cpMainID, caMainID, SubID, Location, ColValue) VALUES (@cpMainID, @caMainID, @MaxID, 'c3', @Demand)
			SET @IsVerify = 1
		END
		
	END TRY
	BEGIN CATCH		
		GOTO ERR
	END CATCH
COMMIT TRAN
RETURN @MaxID
ERR:
BEGIN
	--insert into a_tmp select ERROR_MESSAGE(), getdate()
	ROLLBACK TRAN
	RETURN 0
END
RETURN @MaxID
ERR1:
BEGIN
	--insert into a_tmp select ERROR_MESSAGE(), getdate()
	ROLLBACK TRAN
	RETURN -1
END
SET NOCOUNT OFF


GO
/****** Object:  StoredProcedure [dbo].[ccJobSaveNew]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--nick 20130815 update
--去掉filtercvmainid相关内容
--Peter 2016-10-31修改 订阅方式的修改
--Lucifer 2017-3-21修改 月薪改为范围，添加可面议
CREATE PROCEDURE [dbo].[ccJobSaveNew]
(
	@OperatorID INT, 
	@ID INT, 
	@cpMainID INT, 
	@caMainID INT, 
	@Name VARCHAR(50), 
	@dcJobTypeID INT, 
	@dcJobTypeIDMinor INT, 
	@NeedNumber SMALLINT, 
	@dcSalaryID TINYINT, 
	@EmployType TINYINT, 
	@dcRegionID VARCHAR(6), 
	@Lng DECIMAL(8, 5), 
	@Lat DECIMAL(8, 5), 
	@Responsibility VARCHAR(MAX), 
	@Demand VARCHAR(MAX), 
	@dcEducationID TINYINT, 
	@MinExperience TINYINT, 
	@MinAge TINYINT, 
	@MaxAge TINYINT, 
	@EMailSendFreq VARCHAR(7), 
	@EMailSendNumber TINYINT, 
	--屏蔽简历相关
	@FilterMaxDegree TINYINT, 
	@FilterMinDegree TINYINT, 
	@FilterMaxWorkYear TINYINT, 
	@FilterMinWorkYear TINYINT, 
	@FilterMaxAge TINYINT, 
	@FilterMinAge TINYINT, 
	@FilterGender VARCHAR(1), 
	@FilterJobRegion VARCHAR(6), 
	@ForwardEmail VARCHAR(100),
	@dcSalaryMaxID TINYINT,
	@Negotiable BIT
)
AS
SET NOCOUNT ON
IF @dcRegionID NOT LIKE '[0-9]%'
RETURN -1

IF ISNULL(@dcSalaryID, 0) = 0
	SET @dcSalaryID = 100
IF ISNULL(@dcEducationID, 0) = 0
	SET @dcEducationID = 100
BEGIN TRAN
	SET @Name = dbo.TrimNull(@Name)
	IF @Name IS NULL
		GOTO Err
	-- Can Not Name Repeat
	IF @cpMainID <> 10576676
	BEGIN
		IF EXISTS(SELECT 'x' FROM Job WITH(NOLOCK) 
			WHERE Name = @Name 
			AND dcRegionId = @dcRegionID
			AND cpMainId = @CpMainId 
			AND ID <> ISNULL(@ID, 0) 
			AND IsDelete = 0)
			GOTO Err1
	END

	SET @Responsibility = REPLACE(dbo.TextTrim(@Responsibility), '', '')
	SET @Demand = REPLACE(dbo.TextTrim(@Demand), '', '')
	IF CHARINDEX(', ', @Name) > 0
		SELECT @Name = REPLACE(@Name, ',', '，')
	DECLARE @MaxID AS INT
	IF @ID>0
	BEGIN
		IF @OperatorID <> (SELECT ID FROM caMain WITH(NOLOCK) WHERE cpMainID = @cpMainID AND AccountType = 1) AND @OperatorID<>@caMainID
			RETURN 0

		DECLARE @NameOld AS NVARCHAR(60), @ResponsibilityOld AS VARCHAR(MAX), 
			@DemandOld AS VARCHAR(MAX), @IsVerify AS BIT
		SELECT @NameOld = dbo.TextTrim(ISNULL(Name, '')), @ResponsibilityOld = ISNULL(Responsibility, ''), 
			@DemandOld = ISNULL(Demand, '')
		FROM Job WITH(NOLOCK)
		WHERE ID = @ID

		UPDATE Job SET
			Name = @Name, 
			dcJobTypeID = @dcJobTypeID, 
			dcJobTypeIDMinor = @dcJobTypeIDMinor, 
			NeedNumber = @NeedNumber, 
			dcSalaryID = @dcSalaryID,
			EmployType = @EmployType, 
			dcRegionID = @dcRegionID, 
			Lng = @Lng, 
			Lat = @Lat, 
			Responsibility = @Responsibility, 
			Demand = @Demand, 
			dcEducationID = @dcEducationID, 
			MinExperience = @MinExperience, 
			MinAge = @MinAge, 
			MaxAge = @MaxAge, 
			EMailSendFreq = dbo.BinToINT(@EMailSendFreq), 
			RefreshDate = GETDATE(), 
			LastModifyDate = GETDATE(), 
			FilterMaxDegree = @FilterMaxDegree, 
			FilterMinDegree = @FilterMinDegree, 
			FilterMaxWorkYear = @FilterMaxWorkYear, 
			FilterMinWorkYear = @FilterMinWorkYear, 
			FilterMaxAge = @FilterMaxAge, 
			FilterMinAge = @FilterMinAge, 
			FilterGender = @FilterGender, 
			FilterJobRegion = @FilterJobRegion, 
			ForwardEmail = @ForwardEmail,
			dcSalaryIdMax = @dcSalaryMaxID,
			Negotiable = @Negotiable
		WHERE ID = @ID
		SET @MaxID = @ID

		SET @IsVerify = 0
		IF @NameOld <> dbo.TextTrim(@Name)
		BEGIN
			DELETE FROM bsCpModify WHERE SubId = @ID AND Location = 'c1'
			INSERT INTO bsCpModify (cpMainID, caMainID, SubID, Location, ColValue) VALUES (@cpMainID, @caMainID, @ID, 'c1', @Name)
			SET @IsVerify = 1
		END

		IF @ResponsibilityOld <> @Responsibility
		BEGIN
			DELETE FROM bsCpModify WHERE SubId = @ID AND Location = 'c2'
			INSERT INTO bsCpModify (cpMainID, caMainID, SubID, Location, ColValue) VALUES (@cpMainID, @caMainID, @ID, 'c2', @Responsibility)
			SET @IsVerify = 1
		END

		IF @DemandOld <> @Demand
		BEGIN
			DELETE FROM bsCpModify WHERE SubId = @ID AND Location = 'c3'
			INSERT INTO bsCpModify (cpMainID, caMainID, SubID, Location, ColValue) VALUES (@cpMainID, @caMainID, @ID, 'c3', @Demand)
			SET @IsVerify = 1
		END
	END
	ELSE
	BEGIN
		INSERT INTO Job
			(
				cpMainID, caMainID, Name, dcJobTypeID, dcJobTypeIDMinor, 
				NeedNumber, dcSalaryID, EmployType, dcRegionID, Lng, Lat, 
				Responsibility, Demand, dcEducationID, MinExperience, 
				MinAge, MaxAge, EMailSendFreq, 
				AddDate, LastModifyDate, RefreshDate, IssueDate, IssueEnd, 
				FilterMaxDegree, FilterMinDegree, FilterMaxWorkYear, FilterMinWorkYear, 
				FilterMaxAge, FilterMinAge, FilterGender, FilterJobRegion, 
				ForwardEmail, dcSalaryIdMax, Negotiable
			)
		VALUES
			(
				@cpMainID, @caMainID, @Name, @dcJobTypeID, @dcJobTypeIDMinor, 
				@NeedNumber, @dcSalaryID, @EmployType, @dcRegionID, @Lng, @Lat, 
				@Responsibility, @Demand, @dcEducationID, @MinExperience, 
				@MinAge, @MaxAge, dbo.BinToINT(@EMailSendFreq), 
				GETDATE(), GETDATE(), GETDATE(), GETDATE(), DATEADD(MONTH, 2, GETDATE()), 
				@FilterMaxDegree, @FilterMinDegree, @FilterMaxWorkYear, @FilterMinWorkYear, 
				@FilterMaxAge, @FilterMinAge, @FilterGender, @FilterJobRegion, 
				@ForwardEmail, @dcSalaryMaxID, @Negotiable
			)

		SET @MaxID = @@IDENTITY

		INSERT INTO bsCpModify (cpMainID, caMainID, SubID, Location, ColValue) VALUES (@cpMainID, @caMainID, @MaxID, 'c1', @Name)
		INSERT INTO bsCpModify (cpMainID, caMainID, SubID, Location, ColValue) VALUES (@cpMainID, @caMainID, @MaxID, 'c2', @Responsibility)
		INSERT INTO bsCpModify (cpMainID, caMainID, SubID, Location, ColValue) VALUES (@cpMainID, @caMainID, @MaxID, 'c3', @Demand)
		SET @IsVerify = 1
	END	
COMMIT TRAN
RETURN @MaxID
ERR:
BEGIN
	--insert into a_tmp select ERROR_MESSAGE(), getdate()
	ROLLBACK TRAN
	RETURN 0
END
RETURN @MaxID
ERR1:
BEGIN
	--insert into a_tmp select ERROR_MESSAGE(), getdate()
	ROLLBACK TRAN
	RETURN -1
END
SET NOCOUNT OFF

GO
/****** Object:  StoredProcedure [dbo].[ccJobSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[ccJobSelect]
(
    @ID INT
)
AS
SET NOCOUNT ON
BEGIN
    SELECT *
    FROM Job WITH(NOLOCK)
    WHERE ID = @ID
	AND IsDelete = 0
END














GO
/****** Object:  StoredProcedure [dbo].[ccJobTemplateBycaMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ccJobTemplateBycaMainIDSelect]
    @caMainID INT
AS
BEGIN
    SELECT a.*, b.FullName Region,dbo.Int2Bin(EMailSendFreq) PushFreq,
	ISNULL((SELECT Description FROM dcEducation WHERE Id = dcEducationId), '不限') Education, 
	e.Description JobTypeName,f.Description JobTypeMinorName,g.Description NeedNumName,h.Description EmployTypeName,
	i.Description ExperienceName,j.DescriptionCp SalaryName,k.DescriptionCp SalaryMaxName
    FROM JobTemplate a WITH(NOLOCK)
	LEFT JOIN dcRegion b WITH(NOLOCK) ON a.dcRegionID = b.ID
	LEFT JOIN caOnline c WITH(NOLOCK) ON a.caMainId = c.caMainId
	LEFT JOIN dcJobType e WITH(NOLOCK) ON a.dcJobTypeId = e.ID
	LEFT JOIN dcJobType f WITH(NOLOCK) ON a.dcJobTypeIdMinor = f.ID
	LEFT JOIN dcOthers g WITH(NOLOCK) ON a.NeedNumber = g.DetailID AND g.Category = '招聘人数'
	LEFT JOIN dcOthers h WITH(NOLOCK) ON a.EmployType = h.DetailID AND h.Category = '工作性质'
	LEFT JOIN dcOthers i WITH(NOLOCK) ON a.MinExperience = i.DetailID AND i.Category = '职位要求工作经验'
	LEFT JOIN dcSalary j WITH(NOLOCK) ON a.dcSalaryId = j.ID 
	LEFT JOIN dcSalary k WITH(NOLOCK) ON a.dcSalaryIdMax = k.ID
    WHERE a.caMainID = @caMainID
	ORDER BY a.ID DESC
END
GO
/****** Object:  StoredProcedure [dbo].[ccJobTemplateByMapBarUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ccJobTemplateByMapBarUpdate]
	@ID INT,
	@Lng VARCHAR(20),
	@Lat VARCHAR(20),
	@cpMainID INT
AS
BEGIN
	UPDATE JobTemplate SET Lng=@Lng,Lat=@Lat WHERE ID=@ID AND cpMainID=@cpMainID
END














GO
/****** Object:  StoredProcedure [dbo].[ccJobTemplateDelete]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[ccJobTemplateDelete]
(
	@ID INT,
	@caMainID INT
)
AS
BEGIN TRAN
	DECLARE @caID AS INT
	DECLARE @AccountType AS INT
	DECLARE @cpMainID AS INT 
	DECLARE @cpID AS INT
	SELECT @caID=caMainId ,@cpID = cpMainID FROM JobTemplate WITH(NOLOCK) WHERE ID = @ID AND caMainID = @caMainID
	SELECT @AccountType=AccountType,@cpMainID=cpMainID FROM caMain WITH(NOLOCK) WHERE id = @caMainID
	IF @caID Is NUll 
		GOTO ERR1
	IF @caID != @caMainID 
		BEGIN
			IF @AccountType != 1
				GOTO ERR2
			IF 	@cpMainID != @cpID
				GOTO ERR2								
		END
	IF @caID Is NUll 
		GOTO ERR1
	IF @caID != @caMainID 
		GOTO ERR2
	DELETE FROM JobTemplate WHERE ID = @ID
	IF @@ERROR <>0 
		GOTO ERR
COMMIT TRAN
RETURN 1
ERR: 
BEGIN
	ROLLBACK TRAN
    RETURN 0
END
ERR1:
BEGIN
	ROLLBACK TRAN
	RETURN -1
END
ERR2:
BEGIN
	ROLLBACK TRAN
	RETURN -2
END














GO
/****** Object:  StoredProcedure [dbo].[ccJobTemplateMapBarIDUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[ccJobTemplateMapBarIDUpdate]
	@ID INT,
	@MapBarID VARCHAR(50),
	@cpMainID INT
AS
BEGIN
	UPDATE JobTemplate SET MapBarID=@MapBarID WHERE ID=@ID AND cpMainID = @cpMainID
END














GO
/****** Object:  StoredProcedure [dbo].[ccJobTemplateSave]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--修改职位模板
--Peter 2016-10-31修改 修改职位订阅的订阅方式
CREATE PROCEDURE [dbo].[ccJobTemplateSave]
(
	@ID INT,
	@cpMainID INT,
	@caMainID INT,
	@Name VARCHAR(50),
	@dcJobTypeID INT,
	@dcJobTypeIDMinor INT,
	@NeedNumber SMALLINT,
	@dcSalaryID TINYINT,
	@EmployType TINYINT,
	@dcRegionID VARCHAR(6),
	@Lng DECIMAL(8, 5),
	@Lat DECIMAL(8, 5),
	@Responsibility VARCHAR(MAX),
	@DemAND VARCHAR(MAX),
	@dcEducationID TINYINT,
	@MinExperience TINYINT,
	@MinAge TINYINT,
	@MaxAge TINYINT,
	@EMailSendFreq VARCHAR(7),
	@EMailSendNumber TINYINT
)
AS
SELECT @Responsibility = dbo.SafeSql(@Responsibility), @Demand = dbo.SafeSql(@Demand)
BEGIN TRY
	IF @ID>0
		BEGIN
			UPDATE JobTemplate SET
				Name = @Name,
				dcJobTypeID = @dcJobTypeID,
				dcJobTypeIDMinor = @dcJobTypeIDMinor,
				NeedNumber = @NeedNumber,
				dcSalaryID = @dcSalaryID,
				EmployType = @EmployType,
				dcRegionID = @dcRegionID,
				Lng = @Lng,
				Lat = @Lat,
				Responsibility = @Responsibility,
				DemAND = @Demand,
				dcEducationID = @dcEducationID,
				MinExperience = @MinExperience,
				MinAge = @MinAge,
				MaxAge = @MaxAge,
				EMailSendFreq = dbo.BinToINT(@EMailSendFreq),
				LastModifyDate = GETDATE()
			WHERE ID=@ID
			AND caMainID = @caMainID
		End
	ELSE
		BEGIN
			INSERT INTO JobTemplate
				(
					cpMainID,caMainID,Name,dcJobTypeID,dcJobTypeIDMinor,
					NeedNumber,dcSalaryID,EmployType,dcRegionID,Lng,Lat,
					Responsibility,Demand,dcEducationID,MinExperience,
					MinAge,MaxAge,EMailSendFreq,
					AddDate,LastModifyDate
				)
			VALUES
				(
					@cpMainID,@caMainID,@Name,@dcJobTypeID,@dcJobTypeIDMinor,
					@NeedNumber,@dcSalaryID,@EmployType,@dcRegionID,@Lng,@Lat,
					@Responsibility,@Demand,@dcEducationID,@MinExperience,
					@MinAge,@MaxAge,dbo.BinToINT(@EMailSendFreq),
					GETDATE(),GETDATE()
				)
	END
END TRY
BEGIN CATCH
	GOTO ERR
END CATCH
RETURN 1
ERR:
BEGIN
	RETURN 0
END



GO
/****** Object:  StoredProcedure [dbo].[ccJobTemplateSave2]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--修改职位模板
--Peter 2016-10-31修改 修改职位订阅的订阅方式
--Peter 2017-2-7修改 添加职位标签保存
CREATE PROCEDURE [dbo].[ccJobTemplateSave2]
(
	@ID INT,
	@cpMainID INT,
	@caMainID INT,
	@Name VARCHAR(50),
	@dcJobTypeID INT,
	@dcJobTypeIDMinor INT,
	@NeedNumber SMALLINT,
	@dcSalaryID TINYINT,
	@EmployType TINYINT,
	@dcRegionID VARCHAR(6),
	@Lng DECIMAL(8, 5),
	@Lat DECIMAL(8, 5),
	@Responsibility VARCHAR(MAX),
	@DemAND VARCHAR(MAX),
	@dcEducationID TINYINT,
	@MinExperience TINYINT,
	@MinAge TINYINT,
	@MaxAge TINYINT,
	@EMailSendFreq VARCHAR(7),
	@EMailSendNumber TINYINT,
	@JobTags NVARCHAR(100)
)
AS
SELECT @Responsibility = dbo.SafeSql(@Responsibility), @Demand = dbo.SafeSql(@Demand)
BEGIN TRY
	IF @ID>0
		BEGIN
			UPDATE JobTemplate SET
				Name = @Name,
				dcJobTypeID = @dcJobTypeID,
				dcJobTypeIDMinor = @dcJobTypeIDMinor,
				NeedNumber = @NeedNumber,
				dcSalaryID = @dcSalaryID,
				EmployType = @EmployType,
				dcRegionID = @dcRegionID,
				Lng = @Lng,
				Lat = @Lat,
				Responsibility = @Responsibility,
				DemAND = @Demand,
				dcEducationID = @dcEducationID,
				MinExperience = @MinExperience,
				MinAge = @MinAge,
				MaxAge = @MaxAge,
				EMailSendFreq = dbo.BinToINT(@EMailSendFreq),
				LastModifyDate = GETDATE(),
				JobTags = @JobTags
			WHERE ID=@ID
			AND caMainID = @caMainID
		End
	ELSE
		BEGIN
			INSERT INTO JobTemplate
				(
					cpMainID,caMainID,Name,dcJobTypeID,dcJobTypeIDMinor,
					NeedNumber,dcSalaryID,EmployType,dcRegionID,Lng,Lat,
					Responsibility,Demand,dcEducationID,MinExperience,
					MinAge,MaxAge,EMailSendFreq,
					AddDate,LastModifyDate,JobTags
				)
			VALUES
				(
					@cpMainID,@caMainID,@Name,@dcJobTypeID,@dcJobTypeIDMinor,
					@NeedNumber,@dcSalaryID,@EmployType,@dcRegionID,@Lng,@Lat,
					@Responsibility,@Demand,@dcEducationID,@MinExperience,
					@MinAge,@MaxAge,dbo.BinToINT(@EMailSendFreq),
					GETDATE(),GETDATE(),@JobTags
				)
	END
END TRY
BEGIN CATCH
	GOTO ERR
END CATCH
RETURN 1
ERR:
BEGIN
	RETURN 0
END


GO
/****** Object:  StoredProcedure [dbo].[ccJobTemplateSaveNew]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--修改职位模板
--Peter 2016-10-31修改 修改职位订阅的订阅方式
--Peter 2017-2-7修改 添加职位标签保存
--Lucifer 2017-3-21修改 月薪改为范围，添加可面议
CREATE PROCEDURE [dbo].[ccJobTemplateSaveNew]
(
	@ID INT,
	@cpMainID INT,
	@caMainID INT,
	@Name VARCHAR(50),
	@dcJobTypeID INT,
	@dcJobTypeIDMinor INT,
	@NeedNumber SMALLINT,
	@dcSalaryID TINYINT,
	@EmployType TINYINT,
	@dcRegionID VARCHAR(6),
	@Lng DECIMAL(8, 5),
	@Lat DECIMAL(8, 5),
	@Responsibility VARCHAR(MAX),
	@DemAND VARCHAR(MAX),
	@dcEducationID TINYINT,
	@MinExperience TINYINT,
	@MinAge TINYINT,
	@MaxAge TINYINT,
	@EMailSendFreq VARCHAR(7),
	@EMailSendNumber TINYINT,
	@JobTags NVARCHAR(100),
	@dcSalaryMaxID TINYINT,
	@Negotiable BIT
)
AS
SELECT @Responsibility = dbo.SafeSql(@Responsibility), @Demand = dbo.SafeSql(@Demand)
BEGIN TRY
	IF @ID>0
		BEGIN
			UPDATE JobTemplate SET
				Name = @Name,
				dcJobTypeID = @dcJobTypeID,
				dcJobTypeIDMinor = @dcJobTypeIDMinor,
				NeedNumber = @NeedNumber,
				dcSalaryID = @dcSalaryID,
				EmployType = @EmployType,
				dcRegionID = @dcRegionID,
				Lng = @Lng,
				Lat = @Lat,
				Responsibility = @Responsibility,
				DemAND = @Demand,
				dcEducationID = @dcEducationID,
				MinExperience = @MinExperience,
				MinAge = @MinAge,
				MaxAge = @MaxAge,
				EMailSendFreq = dbo.BinToINT(@EMailSendFreq),
				LastModifyDate = GETDATE(),
				JobTags = @JobTags,
				dcSalaryIDMax = @dcSalaryMaxID,
				Negotiable = @Negotiable
			WHERE ID=@ID
			AND caMainID = @caMainID
		End
	ELSE
		BEGIN
			INSERT INTO JobTemplate
				(
					cpMainID,caMainID,Name,dcJobTypeID,dcJobTypeIDMinor,
					NeedNumber,dcSalaryID,EmployType,dcRegionID,Lng,Lat,
					Responsibility,Demand,dcEducationID,MinExperience,
					MinAge,MaxAge,EMailSendFreq,
					AddDate,LastModifyDate,JobTags,dcSalaryIDMax,Negotiable
				)
			VALUES
				(
					@cpMainID,@caMainID,@Name,@dcJobTypeID,@dcJobTypeIDMinor,
					@NeedNumber,@dcSalaryID,@EmployType,@dcRegionID,@Lng,@Lat,
					@Responsibility,@Demand,@dcEducationID,@MinExperience,
					@MinAge,@MaxAge,dbo.BinToINT(@EMailSendFreq),
					GETDATE(),GETDATE(),@JobTags,@dcSalaryMaxID,@Negotiable
				)
	END
END TRY
BEGIN CATCH
	GOTO ERR
END CATCH
RETURN 1
ERR:
BEGIN
	RETURN 0
END
GO
/****** Object:  StoredProcedure [dbo].[ccJobTemplateSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--Peter 2016-10-31修改职位订阅内容展现
CREATE PROCEDURE [dbo].[ccJobTemplateSelect]
(
    @ID INT
)
AS
BEGIN
    SELECT a.*, b.FullName Region,dbo.Int2Bin(EMailSendFreq) PushFreq,
	ISNULL((SELECT Description FROM dcEducation WHERE Id = dcEducationId), '不限') Education, 
	e.Description JobTypeName,f.Description JobTypeMinorName,g.Description NeedNumName,h.Description EmployTypeName,
	i.Description ExperienceName,j.DescriptionCp SalaryName,k.DescriptionCp SalaryMaxName
    FROM JobTemplate a WITH(NOLOCK)
	LEFT JOIN dcRegion b WITH(NOLOCK) ON a.dcRegionID = b.ID
	LEFT JOIN caOnline c WITH(NOLOCK) ON a.caMainId = c.caMainId
	LEFT JOIN dcJobType e WITH(NOLOCK) ON a.dcJobTypeId = e.ID
	LEFT JOIN dcJobType f WITH(NOLOCK) ON a.dcJobTypeIdMinor = f.ID
	LEFT JOIN dcOthers g WITH(NOLOCK) ON a.NeedNumber = g.DetailID AND g.Category = '招聘人数'
	LEFT JOIN dcOthers h WITH(NOLOCK) ON a.EmployType = h.DetailID AND h.Category = '工作性质'
	LEFT JOIN dcOthers i WITH(NOLOCK) ON a.MinExperience = i.DetailID AND i.Category = '职位要求工作经验'
	LEFT JOIN dcSalary j WITH(NOLOCK) ON a.dcSalaryId = j.ID 
	LEFT JOIN dcSalary k WITH(NOLOCK) ON a.dcSalaryIdMax = k.ID
    WHERE a.ID = @ID
END

GO
/****** Object:  StoredProcedure [dbo].[ccLotteryCompany201310Update]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--创建人：lambo
--创建时间：2013-9-29
--企业13周年抽奖
--奖项内容：	平时	10月8日、18日、28日
--	10职位并发	20%	20%
--	20份简历	30%	30%
--	50份简历	10%	10%
--	2周文字广告	5%	5%
--	2周职位置顶	5%	5%
--	2周职位自动刷新 	10%	10%
--	Vip会员—季度  	0%	5%（至少有一个）
--	1:1的赠送	0%	5%（至少有一个）
--	空奖	20%	10%
--	保险公司，抽奖中奖概率调整为10%		
CREATE PROCEDURE [dbo].[ccLotteryCompany201310Update]
(
	@caMainID INT 
)
AS
BEGIN
RETURN 9 --活动已结束
	DECLARE @LotteryID INT
	DECLARE @cpMainID INT 
	SELECT TOP 1 @LotteryID = ID,@cpMainID = cpMainID FROM LotteryCompany201310 WITH(NOLOCK) WHERE Used = 0 AND cpMainID = (select cpMainID FROM caMain WITH(NOLOCK) WHERE ID = @caMainID AND AccountType=1) 

	IF @LotteryID IS NULL	
		RETURN -1 --没有抽奖次数
	UPDATE LotteryCompany201310 SET Used = 1,LotteryDate=GETDATE() WHERE ID = @LotteryID --更新状态 防止重复抽奖

	------------------****************生成抽奖结果****************-----------------
	DECLARE @IsAgent INT --是否是保险公司
	SELECT top 1 @IsAgent = IsAgent FROM cpMain WITH(NOLOCK) WHERE ID = @cpMainID
	
	DECLARE @Today VARCHAR(4)	--用于判断 是否是10月8日、18日、28日
	SELECT @Today = RIGHT(CONVERT(VARCHAR(8) , GETDATE() , 112) , 4)
	
	DECLARE @GiftNo INT
	SELECT @GiftNo = CAST((RAND()*999+1) AS INT) --生成抽奖的数字
		
	--奖品类型：1、10职位并发 2、20份简历  3、50份简历 4、2周文字广告 5、2周职位置顶 6、2周职位自动刷新  7、Vip会员—季度   8、1:1的赠送 9、空奖
	DECLARE @GiftType INT 

	IF @IsAgent = 0
	BEGIN
		IF @GiftNo BETWEEN 51 AND 250	--51-250之间 职位并发 20%概率
			SET @GiftType = 1
		ELSE IF @GiftNo BETWEEN 251 AND 550	--251-550之间 20简历下载 30%概率
			SET @GiftType = 2
		ELSE IF @GiftNo BETWEEN 551 AND 650	--551-650之间 50简历下载 10%概率
			SET @GiftType = 3
		ELSE IF @GiftNo BETWEEN 651 AND 700	--651-700之间 两周文字广告 5%概率
			SET @GiftType = 4
		ELSE IF @GiftNo BETWEEN 701 AND 750	--701-750之间 两周职位置顶 5%概率
			SET @GiftType = 5
		ELSE IF @GiftNo BETWEEN 751 AND 850	--751-850之间 两周职位刷新 10%概率
			SET @GiftType = 6
		ELSE IF @GiftNo BETWEEN 0 AND 50 AND (@Today = '1008' OR @Today = '1018' OR @Today = '1028' )	--0-50之间 Vip会员—季度 5%概率
			SET @GiftType = 7
		ELSE IF @GiftNo BETWEEN 951 AND 1000 AND (@Today = '1008' OR @Today = '1018' OR @Today = '1028' )	--951-1000之间 1:1赠送 5%概率
			SET @GiftType = 8
		ELSE	--空奖  20%概率
			SET @GiftType = 9
	END
	ELSE  -- 保险公司中奖概率10%
	BEGIN
		IF @GiftNo BETWEEN 61 AND 80 	--61-80之间 职位并发 20%概率
			SET @GiftType = 1
		ELSE IF @GiftNo BETWEEN 281 AND 310	--281-310之间 20简历下载 30%概率
			SET @GiftType = 2
		ELSE IF @GiftNo BETWEEN 581 AND 590	--551-650之间 50简历下载 10%概率
			SET @GiftType = 3
		ELSE IF @GiftNo BETWEEN 661 AND 665	--651-700之间 两周文字广告 5%概率
			SET @GiftType = 4
		ELSE IF @GiftNo BETWEEN 731 AND 735	--701-750之间 两周职位置顶 5%概率
			SET @GiftType = 5
		ELSE IF @GiftNo BETWEEN 761 AND 770	--751-850之间 两周职位刷新 10%概率
			SET @GiftType = 6
		ELSE IF @GiftNo BETWEEN 31 AND 35 AND (@Today = '1008' OR @Today = '1018' OR @Today = '1028' )	--0-50之间 Vip会员—季度 5%概率
			SET @GiftType = 7
		ELSE IF @GiftNo BETWEEN 981 AND 985 AND (@Today = '1008' OR @Today = '1018' OR @Today = '1028' )	--951-1000之间 1:1赠送  5%概率
			SET @GiftType = 8
		ELSE	--空奖  20%概率
			SET @GiftType = 9
	END
	--	IF @GiftType =7 OR @GiftType = 8
	--		SET @GiftType = 1
	/*---------****************自动提交订单**************-------------*/
	DECLARE @ProvinceID INT
	DECLARE @PayMethod INT	--取上次订单的付款方式
	DECLARE @LinkMan NVARCHAR(50) 
	DECLARE @Telephone NVARCHAR(50)
	DECLARE @CompanyName NVARCHAR(50)
	DECLARE @Accounts NUMERIC(18,2)	
	DECLARE @dcFeeDetailsID INT
	DECLARE @Manageruserid INT
	DECLARE @MemberType INT
	DECLARE @MainOrderID INT
	DECLARE @InvoiceCompany NVARCHAR(50)	
	SELECT TOP 1 
		@ProvinceID = b.dcProvinceID,
		@PayMethod = c.PayMethod,
		@MemberType = MemberType,
		@LinkMan = LinkMan,
		@Telephone = Telephone,
		@CompanyName = CompanyName,
		@InvoiceCompany = InvoiceCompany,
		@Manageruserid = ConsultantID
	FROM LotteryCompany201310 a,cpMain b ,caOrder c
	WHERE a.cpMainID = b.ID 
	AND a.caOrderID = c.ID
	AND a.cpMainID = @cpMainID	
	ORDER BY a.ID 
         
         SET @PayMethod = 7 
	DECLARE	@NewOrderID INT
	IF @GiftType = 1 AND @MemberType=3	--自动提交职位并发订单
	BEGIN			
		--取原价和对应的资费ID
		SELECT TOP 1 @Accounts = b.Price * 10,					
					@dcFeeDetailsID = a.ID
				FROM dcFeeDetail a WITH(NOLOCK) ,dcFee b WITH(NOLOCK)
				WHERE b.type = 10
				AND a.dcFeeID = b.ID
				AND b.dcProvinceID = LEFT(@ProvinceID,2)
				AND ((MinValue<=10 AND MaxValue>=10) OR (MinValue<=10 AND MaxValue=0))
				AND StartDate < GETDATE() AND EndDate > GETDATE()

		SELECT TOP 1 @MainOrderID = ID FROM CaOrder WITH(NOLOCK) WHERE cpMainID = @cpMainID AND OpenDate IS NOT NULL AND EndDate>GETDATE() AND OrderType = 8 ORDER BY EndDate DESC
		--EXEC @NewOrderID = [dbo].[ccCaOrderInsert] @cpMainID,0, 32, NULL,NULL,@PayMethod,10,@Accounts,0,0,@LinkMan,@Telephone,'',@Manageruserid,0,10,@CompanyName,@MainOrderID,@InvoiceCompany,0,@dcFeeDetailsID
		INSERT INTO caOrder (cpMainID,ProvinceID,ServiceType,PlaceWeek,PayMethod,UserNumber,
		OrderType,Accounts,Paid,Balance,LinkMan,Telephone,LinkRemark,Manageruserid,ActiveQuota,RemainQuota,JobNumber,CompanyName,MainOrderID,InvoiceCompany,dcFeeDetailID)
		VALUES(@cpMainID,@ProvinceID,null,null,@PayMethod,0,
		10,@Accounts,0,0,@LinkMan,@Telephone,'',@Manageruserid,0,0,10,@CompanyName,@MainOrderID,@InvoiceCompany,@dcFeeDetailsID)
		SET @NewOrderID = @@IDENTITY
	END
	ELSE IF @GiftType = 2 AND @MemberType=3	--自动提交20简历下载订单
	BEGIN
		--取原价和对应的资费ID
		SELECT TOP 1 @Accounts = b.Price * 20,					
					@dcFeeDetailsID = a.ID
				FROM dcFeeDetail a WITH(NOLOCK) ,dcFee b WITH(NOLOCK)
				WHERE b.type = 9
				AND a.dcFeeID = b.ID
				AND b.dcProvinceID = LEFT(@ProvinceID,2)
				AND ((MinValue<=20 AND MaxValue>=20) OR (MinValue<=20 AND MaxValue=0))
				AND StartDate < GETDATE() AND EndDate > GETDATE()
		IF @dcFeeDetailsID IS NULL
				SELECT TOP 1 @Accounts = Price * 20
				FROM dcFee  WITH(NOLOCK)
				WHERE type = 9
				AND dcProvinceID = LEFT(@ProvinceID,2)
				AND StartDate < GETDATE() AND EndDate > GETDATE()
		SELECT TOP 1 @MainOrderID = ID FROM CaOrder WITH(NOLOCK) WHERE cpMainID = @cpMainID AND OpenDate IS NOT NULL AND EndDate>GETDATE() AND OrderType = 8 ORDER BY EndDate DESC
		INSERT INTO caOrder (cpMainID,ProvinceID,ServiceType,PlaceWeek,PayMethod,UserNumber,
		OrderType,Accounts,Paid,Balance,LinkMan,Telephone,LinkRemark,Manageruserid,ActiveQuota,RemainQuota,JobNumber,CompanyName,MainOrderID,InvoiceCompany,dcFeeDetailID)
		VALUES(@cpMainID,@ProvinceID,null,null,@PayMethod,0,
		9,@Accounts,0,0,@LinkMan,@Telephone,'',@Manageruserid,20,20,0,@CompanyName,@MainOrderID,@InvoiceCompany,@dcFeeDetailsID)
		SET @NewOrderID = @@IDENTITY
	END
	ELSE IF @GiftType = 3 AND @MemberType=3	--自动提交50简历下载订单
	BEGIN
		--取原价和对应的资费ID
		SELECT TOP 1 @Accounts = b.Price * 50,					
					@dcFeeDetailsID = a.ID
				FROM dcFeeDetail a WITH(NOLOCK) ,dcFee b WITH(NOLOCK)
				WHERE b.type = 9
				AND a.dcFeeID = b.ID
				AND b.dcProvinceID = LEFT(@ProvinceID,2)
				AND ((MinValue<=50 AND MaxValue>=50) OR (MinValue<=50 AND MaxValue=0))
				AND StartDate < GETDATE() AND EndDate > GETDATE()
		IF @dcFeeDetailsID IS NULL
				SELECT TOP 1 @Accounts = Price * 50
				FROM dcFee  WITH(NOLOCK)
				WHERE type = 9
				AND dcProvinceID = LEFT(@ProvinceID,2)
				AND StartDate < GETDATE() AND EndDate > GETDATE()

		SELECT TOP 1 @MainOrderID = ID FROM CaOrder WITH(NOLOCK) WHERE cpMainID = @cpMainID AND OpenDate IS NOT NULL AND EndDate>GETDATE() AND OrderType = 8 ORDER BY EndDate DESC
		INSERT INTO caOrder (cpMainID,ProvinceID,ServiceType,PlaceWeek,PayMethod,UserNumber,
		OrderType,Accounts,Paid,Balance,LinkMan,Telephone,LinkRemark,Manageruserid,ActiveQuota,RemainQuota,JobNumber,CompanyName,MainOrderID,InvoiceCompany,dcFeeDetailID)
		VALUES(@cpMainID,@ProvinceID,null,null,@PayMethod,0,
		9,@Accounts,0,0,@LinkMan,@Telephone,'',@Manageruserid,50,50,0,@CompanyName,@MainOrderID,@InvoiceCompany,@dcFeeDetailsID)
		SET @NewOrderID = @@IDENTITY
	END
	ELSE IF @GiftType = 4	--自动提交2周固定位置订单
	BEGIN
		--取原价和对应的资费ID
		SELECT TOP 1 @Accounts = b.Price * 2,					
					@dcFeeDetailsID = a.ID
				FROM dcFeeDetail a WITH(NOLOCK) ,dcFee b WITH(NOLOCK)
				WHERE b.type = 7
				AND a.dcFeeID = b.ID
				AND b.dcProvinceID = LEFT(@ProvinceID,2)
				AND ((MinValue<=2 AND MaxValue>=2) OR (MinValue<=2 AND MaxValue=0))
				AND StartDate < GETDATE() AND EndDate > GETDATE()
		INSERT INTO caOrder (cpMainID,ProvinceID,ServiceType,PlaceWeek,PayMethod,UserNumber,
		OrderType,Accounts,Paid,Balance,LinkMan,Telephone,LinkRemark,Manageruserid,ActiveQuota,RemainQuota,JobNumber,CompanyName,MainOrderID,InvoiceCompany,dcFeeDetailID)
		VALUES(@cpMainID,@ProvinceID,null,2,@PayMethod,0,
		7,@Accounts,0,0,@LinkMan,@Telephone,'',@Manageruserid,0,0,0,@CompanyName,@MainOrderID,@InvoiceCompany,@dcFeeDetailsID)
		SET @NewOrderID = @@IDENTITY
		--EXEC @NewOrderID = [dbo].[ccCaOrderInsert] @cpMainID,@IsAgent, 32, NULL,2,@PayMethod,7,@Accounts,0,0,@LinkMan,@Telephone,'',@Manageruserid,0,0,@CompanyName,@MainOrderID,@InvoiceCompany,0,@dcFeeDetailsID
	END
	ELSE IF @GiftType = 5	--自动提交2周职位置顶订单，职位默认取最新发布的，前台企业选择后再修改
	BEGIN
		--取原价和对应的资费ID
		SELECT TOP 1 @Accounts = b.Price * 2,					
					@dcFeeDetailsID = a.ID
				FROM dcFeeDetail a WITH(NOLOCK) ,dcFee b WITH(NOLOCK)
				WHERE b.type = 22
				AND a.dcFeeID = b.ID
				AND b.dcProvinceID = LEFT(@ProvinceID,2)
				AND ((MinValue<=2 AND MaxValue>=2) OR (MinValue<=2 AND MaxValue=0))
				AND StartDate < GETDATE() AND EndDate > GETDATE()
		DECLARE @JobID INT
		SELECT @JobID = ID FROM Job WITH(NOLOCK) WHERE Valid = 1  AND cpMainID= @cpMainID AND ID NOT IN(SELECT Balance FROM caOrder WITH(NOLOCK) WHERE OrderType=12 AND BeginDate>GETDATE() AND EndDate<GETDATE()  )
		IF @JobID >0
		BEGIN
			INSERT INTO caOrder (cpMainID,ProvinceID,ServiceType,PlaceWeek,PayMethod,UserNumber,
			OrderType,Accounts,Paid,Balance,LinkMan,Telephone,LinkRemark,Manageruserid,ActiveQuota,RemainQuota,JobNumber,CompanyName,MainOrderID,InvoiceCompany,dcFeeDetailID)
			VALUES(@cpMainID,@ProvinceID,null,2,@PayMethod,0,
			12,@Accounts,0,@JobID,@LinkMan,@Telephone,'',@Manageruserid,0,0,0,@CompanyName,@MainOrderID,@InvoiceCompany,@dcFeeDetailsID)
			SET @NewOrderID = @@IDENTITY
			--EXEC @NewOrderID = [dbo].[ccCaOrderInsert] @cpMainID,@IsAgent, 32, NULL,2,@PayMethod,12,@Accounts,0,@JobID,@LinkMan,@Telephone,'',@Manageruserid,0,0,@CompanyName,@MainOrderID,@InvoiceCompany,0,@dcFeeDetailsID
		END
	END
	ELSE IF @GiftType = 6	--自动提交2周职位刷新订单
	BEGIN
		--取原价和对应的资费ID
		SELECT TOP 1 @Accounts = b.Price * 2,					
					@dcFeeDetailsID = a.ID
				FROM dcFeeDetail a WITH(NOLOCK) ,dcFee b WITH(NOLOCK)
				WHERE b.type = 24
				AND a.dcFeeID = b.ID
				AND b.dcProvinceID = LEFT(@ProvinceID,2)
				AND ((MinValue<=2 AND MaxValue>=2) OR (MinValue<=2 AND MaxValue=0))
				AND StartDate < GETDATE() AND EndDate > GETDATE()
		INSERT INTO caOrder (cpMainID,ProvinceID,ServiceType,PlaceWeek,PayMethod,UserNumber,
		OrderType,Accounts,Paid,Balance,LinkMan,Telephone,LinkRemark,Manageruserid,ActiveQuota,RemainQuota,JobNumber,CompanyName,MainOrderID,InvoiceCompany,dcFeeDetailID)
		VALUES(@cpMainID,@ProvinceID,null,2,@PayMethod,0,
		13,@Accounts,0,0,@LinkMan,@Telephone,'',@Manageruserid,0,0,0,@CompanyName,@MainOrderID,@InvoiceCompany,@dcFeeDetailsID)
		SET @NewOrderID = @@IDENTITY
		--EXEC @NewOrderID = [dbo].[ccCaOrderInsert] @cpMainID,@IsAgent, 32, NULL,2,@PayMethod,13,@Accounts,0,0,@LinkMan,@Telephone,'',@Manageruserid,0,0,@CompanyName,@MainOrderID,@InvoiceCompany,0,@dcFeeDetailsID
	END
	ELSE IF @GiftType = 7	--自动提交VIP订单  
	BEGIN		
		DECLARE @ActiveQuota INT
		DECLARE @JobNumber INT
		DECLARE @UserNumber INT

		--取本省份价格最便宜的季度套餐
		SELECT @dcFeeDetailsID = b.ID, 
		@Accounts = (a.PriceMonth * b.[Month]+b.ResumeNumber*a.PriceResume+JobNumber*a.PriceJob+UserNumber*a.PriceUser),
		@ActiveQuota = b.ResumeNumber,
		@JobNumber = b.JobNumber,
		@UserNumber = b.UserNumber 
		FROM dcVip a WITH(NOLOCK),dcVipDetail b WITH(NOLOCK) 
		WHERE a.id = b.dcVipId 
		AND dcProvinceid=32 
		AND b.[Month]=3 
		AND startDate<GETDATE() 
		AND enddate > GETDATE()
		ORDER BY Price

		INSERT INTO caOrder (cpMainID,ProvinceID,ServiceType,PlaceWeek,PayMethod,UserNumber,
		OrderType,Accounts,Paid,Balance,LinkMan,Telephone,LinkRemark,Manageruserid,ActiveQuota,RemainQuota,JobNumber,CompanyName,MainOrderID,InvoiceCompany,dcFeeDetailID)
		VALUES(@cpMainID,@ProvinceID,null,NULL,@PayMethod,@UserNumber,
		8,@Accounts,0,0,@LinkMan,@Telephone,'',@Manageruserid,@ActiveQuota,@ActiveQuota,@JobNumber,@CompanyName,@MainOrderID,@InvoiceCompany,@dcFeeDetailsID)
		SET @NewOrderID = @@IDENTITY
		--EXEC @NewOrderID = [dbo].[ccCaOrderInsert] @cpMainID,@IsAgent, 32, NULL,0,@PayMethod,8,@Accounts,0,0,@LinkMan,@Telephone,'',@Manageruserid,@ActiveQuota,@JobNumber,@CompanyName,@MainOrderID,@InvoiceCompany,@UserNumber,@dcFeeDetailsID
	END
	ELSE IF @GiftType = 8	--自动提交 1:1赠送 
	BEGIN		

		---取最新有赠送抽奖次数的订单 
		INSERT INTO caOrder (cpMainID,ProvinceID,ServiceType,PlaceWeek,PayMethod,UserNumber,
		OrderType,Accounts,Paid,Balance,LinkMan,Telephone,LinkRemark,Manageruserid,ActiveQuota,RemainQuota,JobNumber,CompanyName,MainOrderID,InvoiceCompany,dcFeeDetailID)
		SELECT cpMainID,ProvinceID,ServiceType,PlaceWeek,PayMethod,UserNumber,
		OrderType,Accounts,0,0,LinkMan,Telephone,LinkRemark,Manageruserid,ActiveQuota,ActiveQuota,JobNumber,CompanyName,MainOrderID,InvoiceCompany,dcFeeDetailID
		FROM caOrder WITH(NOLOCK)
		WHERE ID IN (SELECT TOP 1 caOrderID FROM LotteryCompany201310 WHERE caOrderID IS NOT NULL  AND cpMainID= @cpMainID ORDER BY ID DESC)
		SET @NewOrderID = @@IDENTITY
	END	
	
	BEGIN TRY
      IF @GiftType<>9 
      BEGIN
		IF @Manageruserid IS NULL
		BEGIN	
			INSERT INTO rtxnotifylog
			SELECT STUFF((SELECT ','+LTRIM(x.ID) FROM Manageruser x WHERE ID >= 180 and ID <190 FOR XML PATH('')),1,1,'')
				,'中奖通知',@CompanyName+'('+LTRIM(STR(@cpMainID))+')中奖了，请及时处理',1,0,0,null,getdate()
		END
		ELSE
		BEGIN
			INSERT INTO rtxnotifylog
			SELECT @Manageruserid
				,'中奖通知',@CompanyName+'('+LTRIM(STR(@cpMainID))+')中奖了，请及时处理',1,0,0,null,getdate()
		END
		Update caOrder Set InvoiceConfirmDate=GetDate(),InvoiceConfirmMan=119,InvoiceAskDate=Null,NeedInvoice=0 Where ID=@NewOrderID
      END
	END TRY
	BEGIN CATCH
		
	END CATCH
	--更新LotteryCompany201310，保存订单号和中奖类型
	UPDATE LotteryCompany201310 SET GiftOrderID=@NewOrderID,[type]=@GiftType WHERE ID = @LotteryID
	RETURN @GiftType
END










GO
/****** Object:  StoredProcedure [dbo].[ccLotteryCompanyUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--创建人：lambo
--创建时间：2014-9-29
--企业14周年抽奖
--奖项内容：	平时	10月8日、18日、28日
--	50职位并发	15%	5%
--	50份简历	15%	20%
--	100份简历	15%	20%
--	200份简历	10%	15%
--	4周六分之一图片	    10%	15%
--	2周知名企业	10%	10%
--	2周职位置顶	5%	5%
--	2周职位自动刷新 	15%	9%
--	4周六分之二图片	0%	8%
--	Vip会员—季度  	0%	2%（至少有一个，不能重复 ）
--	1:1的赠送	0%	1%（至少有一个，不能重复，如果是年度的不能抽到）
--	保险公司，培训公司，代理招聘类公司仅能够中奖的范围：职位数、简历数、自动刷新。其他内容不允许抽中。需要在抽选中排除。
--修改人：nick
--修改时间：2014-10-10
--修改内容：发送rtx消息，加入奖品名称
CREATE PROCEDURE [dbo].[ccLotteryCompanyUpdate] 
(
	@caMainID INT 
)
AS
BEGIN
	DECLARE @LotteryID INT
	DECLARE @cpMainID INT 
	SELECT TOP 1 @LotteryID = ID,@cpMainID = cpMainID FROM LotteryCompany WITH(NOLOCK) WHERE Used = 0 AND cpMainID = (select cpMainID FROM caMain WITH(NOLOCK) WHERE ID = @caMainID AND AccountType=1) 

	IF @LotteryID IS NULL	
		RETURN -1 --没有抽奖次数
	UPDATE LotteryCompany SET Used = 1,LotteryDate=GETDATE() WHERE ID = @LotteryID --更新状态 防止重复抽奖

	------------------****************生成抽奖结果****************-----------------
	DECLARE @IsAgent INT --是否是保险公司
	DECLARE @Name NVARCHAR(200)
	SELECT top 1 @IsAgent = IsAgent,@Name = Name FROM cpMain WITH(NOLOCK) WHERE ID = @cpMainID
	IF @IsAgent=0
	BEGIN
		IF @Name LIKE '%人寿%' OR @Name LIKE '%保险%' 
			SET @IsAgent=1
	END
	DECLARE @Today VARCHAR(4)	--用于判断 是否是10月8日、18日、28日
	SELECT @Today = RIGHT(CONVERT(VARCHAR(8) , GETDATE() , 112) , 4)
	
	DECLARE @GiftNo INT
	SELECT @GiftNo = CAST((RAND()*999+1) AS INT) --生成抽奖的数字
		
	--奖品类型：1、50职位并发  2、50份简历 3、100份简历 4、200份简历 5、4周六分之一图片 6、2周文字广告 7、2周职位置顶 
	--8、2周职位自动刷新  9、4周六分之二 10、Vip会员—季度   11、1:1的赠送 
	DECLARE @GiftType INT 

	IF @IsAgent = 0
	BEGIN
		IF (@Today = '1008' OR @Today = '1016' OR @Today = '1028' OR @Today = '1025' ) 
		BEGIN
			IF @GiftNo BETWEEN 51 AND 100 	--51-100之间 职位并发 5%概率
				SET @GiftType = 1
			ELSE IF @GiftNo BETWEEN 101 AND 200	--101-200之间 50份简历 10%概率
				SET @GiftType = 2
			ELSE IF @GiftNo BETWEEN 201 AND 400	--201-400之间 100份简历 20%概率
				SET @GiftType = 3
			ELSE IF @GiftNo BETWEEN 401 AND 550	--401-500之间 200份简历 15%概率
				SET @GiftType = 4
			ELSE IF @GiftNo BETWEEN 551 AND 700	--401-500之间 六分之一广告 15%概率
				SET @GiftType = 5
			ELSE IF @GiftNo BETWEEN 701 AND 800	--701-750之间 2周文字广告 10%概率
				SET @GiftType = 6
			ELSE IF @GiftNo BETWEEN 801 AND 850	--801-850之间 两周职位置顶 5%概率
				SET @GiftType = 7
			ELSE IF @GiftNo BETWEEN 851 AND 940	--851-940之间 两周职位刷新 9%概率
				SET @GiftType = 8
			ELSE IF @GiftNo BETWEEN 941 AND 1000 OR	@GiftNo BETWEEN 1 AND 20  --941-1000之间  1到20  六分之二广告 8%概率
				SET @GiftType = 9
			ELSE IF @GiftNo BETWEEN 21 AND 40 	--21-40之间 Vip会员—季度 2%概率
				SET @GiftType = 10
			ELSE IF @GiftNo BETWEEN 41 AND 50 	--41-50之间 1:1赠送 1%概率
				SET @GiftType = 11			
			ELSE	--空奖  0%概率
				SET @GiftType = 12
		END
		ELSE
		BEGIN
			IF @GiftNo BETWEEN 51 AND 200 	--51-200之间 职位并发 15%概率
				SET @GiftType = 1
			ELSE IF @GiftNo BETWEEN 201 AND 400	--201-400之间 50份简历 20%概率
				SET @GiftType = 2
			ELSE IF @GiftNo BETWEEN 401 AND 550	--201-400之间 100份简历 15%概率
				SET @GiftType = 3
			ELSE IF @GiftNo BETWEEN 551 AND 650	--401-500之间 200份简历 10%概率
				SET @GiftType = 4
			ELSE IF @GiftNo BETWEEN 651 AND 800	--401-500之间 六分之一广告 15%概率
				SET @GiftType = 5
			ELSE IF @GiftNo BETWEEN 801 AND 900	--701-750之间 2周文字广告 10%概率
				SET @GiftType = 6
			ELSE IF @GiftNo BETWEEN 901 AND 950	--801-850之间 两周职位置顶 5%概率
				SET @GiftType = 7
			ELSE IF @GiftNo BETWEEN 951 AND 1000 OR @GiftNo BETWEEN 1 AND 50 	--851-940之间 两周职位刷新 15%概率
				SET @GiftType = 8			
			ELSE	--空奖  0%概率
				SET @GiftType = 12
		END
	END
	ELSE  -- 保险公司中奖概率10%
	BEGIN
		IF @GiftNo BETWEEN 1 AND 200 	--1-200之间 职位并发 15%概率
			SET @GiftType = 1
		ELSE IF @GiftNo BETWEEN 201 AND 450	--201-450之间 50份简历 25%概率
			SET @GiftType = 2
		ELSE IF @GiftNo BETWEEN 451 AND 650	--201-400之间 100份简历 20%概率
			SET @GiftType = 3
		ELSE IF @GiftNo BETWEEN 651 AND 800	--401-500之间 200份简历 15%概率
			SET @GiftType = 4		
		ELSE IF @GiftNo BETWEEN 801 AND 1000 	--851-940之间 两周职位刷新 20%概率
			SET @GiftType = 8			
		ELSE	--空奖  0%概率
			SET @GiftType = 12	
	END
	IF GETDATE()>'2015-11-1'	
		SET @GiftType = 9		
	/*---------****************抽奖结果处理，判断是否合理，重复 **************-------------*/
	IF (@GiftType =9 OR @GiftType = 10 OR @GiftType = 11) AND NOT (@Today = '1008' OR @Today = '1016' OR @Today = '1028'  OR @Today = '1025' ) --不是带8的日子不能抽到
		SET @GiftType = 1
	IF @Today = '1008' OR @Today = '1016' OR @Today = '1028'  OR @Today = '1025' 
	BEGIN
		IF EXISTS(SELECT TOP 1 'x' FROM LotteryCompany WHERE [Type]=@GiftType AND cpMainID=@cpMainID)  --重复抽到了
			SELECT TOP 1 @GiftType = s.a
			FROM (SELECT  a FROM dbo.FnSplit('1,2,3,4,5,6,7,8',',') x ) s where s.a not in(SELECT Type FROM LotteryCompany WHERE [Type]=@GiftType AND cpMainID=@cpMainID)				
	END
	ELSE
	BEGIN
		IF (SELECT COUNT(1) FROM LotteryCompany WHERE [Type]=@GiftType AND cpMainID=@cpMainID)>1  --重复抽到了一次
			SELECT TOP 1 @GiftType = s.a FROM (SELECT * FROM dbo.FnSplit('1,2,3,4,5,6,7,8',',') x ) s where s.a not in(SELECT Type FROM LotteryCompany WHERE [Type]=@GiftType AND cpMainID=@cpMainID)				
	
	END
	IF @GiftType IN (10,11) AND EXISTS(SELECT TOP 1 'x' FROM LotteryCompany WHERE [Type]=@GiftType AND cpMainID=@cpMainID)  --重复抽到了
		SET @GiftType = 1
	IF @GiftType IN (10,11) 	--本月开通的非年度的才赠送
		IF NOT EXISTS(SELECT TOP 1 'x' FROM caOrder WITH(NOLOCK)
					WHERE ID IN (SELECT TOP 1 caOrderID FROM LotteryCompany WITH(NOLOCK)
									WHERE caOrderID IS NOT NULL  AND cpMainID= @cpMainID 
									ORDER BY ID DESC)		
					AND dcFeeDetailId in (SELECT id FROM dcVipDetail WITH(NOLOCK) WHERE [Month]<12)
					AND orderType=8
					AND OpenDate>'2015-10-1'
					AND Paid>0
				) OR EXISTS(SELECT TOP 1 'x' FROM caOrder WITH(NOLOCK)
					WHERE ID IN (SELECT TOP 1 caOrderID FROM LotteryCompany WITH(NOLOCK)
									WHERE caOrderID IS NOT NULL  AND cpMainID= @cpMainID 
									ORDER BY ID DESC)		
					AND dcFeeDetailId in (SELECT id FROM dcVipDetail WITH(NOLOCK) WHERE [Month]>=12)
					AND orderType=8
					AND OpenDate>'2015-10-1'

				) 
			SET @GiftType = 1
	/*---------****************自动提交订单**************-------------*/
	DECLARE @ProvinceID INT
	DECLARE @PayMethod INT	--取上次订单的付款方式
	DECLARE @LinkMan NVARCHAR(50) 
	DECLARE @Telephone NVARCHAR(50)
	DECLARE @CompanyName NVARCHAR(50)
	DECLARE @Accounts NUMERIC(18,2)	
	DECLARE @dcFeeDetailsID INT
	DECLARE @Manageruserid INT
	DECLARE @MemberType INT
	DECLARE @MainOrderID INT
	DECLARE @MainEndDate SMALLDATETIME
	DECLARE @InvoiceCompany NVARCHAR(50)
	DECLARE @Hour INT
	DECLARE @Minute INT
	DECLARE @Code VARCHAR(10)
	DECLARE @RegDate DATETIME
	SELECT TOP 1 
		@ProvinceID = b.dcProvinceID,
		@PayMethod = c.PayMethod,
		@MemberType = MemberType,
		@LinkMan = LinkMan,
		@Telephone = Telephone,
		@CompanyName = CompanyName,
		@InvoiceCompany = InvoiceCompany,
		@Manageruserid = ConsultantID,
		@RegDate = RegDate
	FROM cpMain b ,caOrder c
	WHERE b.id =c.cpmainid
	AND c.cpMainID = @cpMainID 
	AND Paid>0
	ORDER BY c.ID DESC
	
	SELECT @Hour = DATEPART(HOUR,@RegDate)
    SELECT @Minute = DATEPART(Minute,@RegDate)
    
    SET @Code = CONVERT(VARCHAR(10),@Hour*100+@Minute)
         
    SET @PayMethod = 7 
	DECLARE	@NewOrderID INT
	IF @GiftType= 1 AND @MemberType=3	--自动提交50个职位并发数的订单
	BEGIN			
		--取原价和对应的资费ID
		SELECT TOP 1 @Accounts = b.Price * 50,					
					@dcFeeDetailsID = a.ID
				FROM dcFeeDetail a WITH(NOLOCK) ,dcFee b WITH(NOLOCK)
				WHERE b.type = 10
				AND a.dcFeeID = b.ID
				AND b.dcProvinceID = LEFT(@ProvinceID,2)
				AND ((MinValue<=50 AND MaxValue>=50) OR (MinValue<=50 AND MaxValue=0))
				AND StartDate < GETDATE() AND EndDate > GETDATE()

		SELECT TOP 1 @MainOrderID = ID ,@MainEndDate=EndDate FROM CaOrder WITH(NOLOCK) WHERE cpMainID = @cpMainID AND OpenDate IS NOT NULL AND EndDate>GETDATE() AND OrderType = 8 ORDER BY EndDate DESC	
		INSERT INTO caOrder (cpMainID,ProvinceID,ServiceType,PlaceWeek,PayMethod,UserNumber,
		OrderType,Accounts,Paid,Balance,LinkMan,Telephone,LinkRemark,Manageruserid,ActiveQuota,RemainQuota,JobNumber,CompanyName,MainOrderID,InvoiceCompany,dcFeeDetailID,BeginDate,EndDate,OpenDate,OpenMan,OrderStatus)
		VALUES(@cpMainID,@ProvinceID,null,null,@PayMethod,0,
		10,@Accounts,0,0,@LinkMan,@Telephone,'',@Manageruserid,0,0,50,@CompanyName,@MainOrderID,@InvoiceCompany,@dcFeeDetailsID,GETDATE(),@MainEndDate,GETDATE(),119,4)
		SET @NewOrderID = @@IDENTITY
		UPDATE caOrder SET ReceiveDate=GETDATE() ,ReceiveMan=146 WHERE ID=@NewOrderID
	END
	ELSE IF @GiftType = 5	--自动提交4周1/6图片 广告
	BEGIN
		--取原价和对应的资费ID
		SELECT TOP 1 @Accounts = b.Price * 4,					
					@dcFeeDetailsID = a.ID
				FROM dcFeeDetail a WITH(NOLOCK) ,dcFee b WITH(NOLOCK)
				WHERE b.type = 4
				AND a.dcFeeID = b.ID
				AND b.dcProvinceID = LEFT(@ProvinceID,2)
				AND ((MinValue<=4 AND MaxValue>=4) OR (MinValue<=4 AND MaxValue=0))
				AND StartDate < GETDATE() AND EndDate > GETDATE()
		INSERT INTO caOrder (cpMainID,ProvinceID,ServiceType,PlaceWeek,PayMethod,UserNumber,
		OrderType,Accounts,Paid,Balance,LinkMan,Telephone,LinkRemark,Manageruserid,ActiveQuota,RemainQuota,JobNumber,CompanyName,MainOrderID,InvoiceCompany,dcFeeDetailID,NeedInvoice)
		VALUES(@cpMainID,@ProvinceID,6,4,@PayMethod,0,
		4,@Accounts,0,0,@LinkMan,@Telephone,'',@Manageruserid,0,0,0,@CompanyName,@MainOrderID,@InvoiceCompany,@dcFeeDetailsID,0)
		SET @NewOrderID = @@IDENTITY		
	END
	ELSE IF @GiftType = 9	--自动提交4周2/6图片 广告
	BEGIN
		--取原价和对应的资费ID
		SELECT TOP 1 @Accounts = b.Price * 4,					
					@dcFeeDetailsID = a.ID
				FROM dcFeeDetail a WITH(NOLOCK) ,dcFee b WITH(NOLOCK)
				WHERE b.type = 4
				AND a.dcFeeID = b.ID
				AND b.dcProvinceID = LEFT(@ProvinceID,2)
				AND ((MinValue<=4 AND MaxValue>=4) OR (MinValue<=4 AND MaxValue=0))
				AND StartDate < GETDATE() AND EndDate > GETDATE()
		INSERT INTO caOrder (cpMainID,ProvinceID,ServiceType,PlaceWeek,PayMethod,UserNumber,
		OrderType,Accounts,Paid,Balance,LinkMan,Telephone,LinkRemark,Manageruserid,ActiveQuota,RemainQuota,JobNumber,CompanyName,MainOrderID,InvoiceCompany,dcFeeDetailID,NeedInvoice)
		VALUES(@cpMainID,@ProvinceID,7,4,@PayMethod,0,
		4,@Accounts,0,0,@LinkMan,@Telephone,'',@Manageruserid,0,0,0,@CompanyName,@MainOrderID,@InvoiceCompany,@dcFeeDetailsID,0)
		SET @NewOrderID = @@IDENTITY		
	END
	ELSE IF @GiftType = 2 AND @MemberType=3	--自动提交50简历下载订单
	BEGIN
		--取原价和对应的资费ID
		SELECT TOP 1 @Accounts = b.Price * 50,					
					@dcFeeDetailsID = a.ID
				FROM dcFeeDetail a WITH(NOLOCK) ,dcFee b WITH(NOLOCK)
				WHERE b.type = 9
				AND a.dcFeeID = b.ID
				AND b.dcProvinceID = LEFT(@ProvinceID,2)
				AND ((MinValue<=50 AND MaxValue>=50) OR (MinValue<=50 AND MaxValue=0))
				AND StartDate < GETDATE() AND EndDate > GETDATE()
		IF @dcFeeDetailsID IS NULL
				SELECT TOP 1 @Accounts = Price * 50
				FROM dcFee  WITH(NOLOCK)
				WHERE type = 9
				AND dcProvinceID = LEFT(@ProvinceID,2)
				AND StartDate < GETDATE() AND EndDate > GETDATE()

		SELECT TOP 1 @MainOrderID = ID,@MainEndDate=EndDate FROM CaOrder WITH(NOLOCK) WHERE cpMainID = @cpMainID AND OpenDate IS NOT NULL AND EndDate>GETDATE() AND OrderType = 8 ORDER BY EndDate DESC
		INSERT INTO caOrder (cpMainID,ProvinceID,ServiceType,PlaceWeek,PayMethod,UserNumber,
		OrderType,Accounts,Paid,Balance,LinkMan,Telephone,LinkRemark,Manageruserid,ActiveQuota,RemainQuota,JobNumber,CompanyName,MainOrderID,InvoiceCompany,dcFeeDetailID,BeginDate,EndDate)
		VALUES(@cpMainID,@ProvinceID,null,null,@PayMethod,0,
		9,@Accounts,0,0,@LinkMan,@Telephone,'',@Manageruserid,50,50,0,@CompanyName,@MainOrderID,@InvoiceCompany,@dcFeeDetailsID,GETDATE(),@MainEndDate)
		SET @NewOrderID = @@IDENTITY
		--UPDATE caOrder SET ReceiveDate=GETDATE() ,ReceiveMan=146 WHERE ID=@NewOrderID
	END
	ELSE IF @GiftType = 3 AND @MemberType=3	--自动提交100简历下载订单
	BEGIN
		--取原价和对应的资费ID
		SELECT TOP 1 @Accounts = b.Price * 100,					
					@dcFeeDetailsID = a.ID
				FROM dcFeeDetail a WITH(NOLOCK) ,dcFee b WITH(NOLOCK)
				WHERE b.type = 9
				AND a.dcFeeID = b.ID
				AND b.dcProvinceID = LEFT(@ProvinceID,2)
				AND ((MinValue<=100 AND MaxValue>=100) OR (MinValue<=100 AND MaxValue=0))
				AND StartDate < GETDATE() AND EndDate > GETDATE()
		IF @dcFeeDetailsID IS NULL
				SELECT TOP 1 @Accounts = Price * 100
				FROM dcFee  WITH(NOLOCK)
				WHERE type = 9
				AND dcProvinceID = LEFT(@ProvinceID,2)
				AND StartDate < GETDATE() AND EndDate > GETDATE()

		SELECT TOP 1 @MainOrderID = ID,@MainEndDate=EndDate FROM CaOrder WITH(NOLOCK) WHERE cpMainID = @cpMainID AND OpenDate IS NOT NULL AND EndDate>GETDATE() AND OrderType = 8 ORDER BY EndDate DESC
		INSERT INTO caOrder (cpMainID,ProvinceID,ServiceType,PlaceWeek,PayMethod,UserNumber,
		OrderType,Accounts,Paid,Balance,LinkMan,Telephone,LinkRemark,Manageruserid,ActiveQuota,RemainQuota,JobNumber,CompanyName,MainOrderID,InvoiceCompany,dcFeeDetailID,BeginDate,EndDate)
		VALUES(@cpMainID,@ProvinceID,null,null,@PayMethod,0,
		9,@Accounts,0,0,@LinkMan,@Telephone,'',@Manageruserid,100,100,0,@CompanyName,@MainOrderID,@InvoiceCompany,@dcFeeDetailsID,GETDATE(),@MainEndDate)
		SET @NewOrderID = @@IDENTITY
		--UPDATE caOrder SET ReceiveDate=GETDATE() ,ReceiveMan=146 WHERE ID=@NewOrderID
	END
ELSE IF @GiftType = 4 AND @MemberType=3	--自动提交200简历下载订单
	BEGIN
		--取原价和对应的资费ID
		SELECT TOP 1 @Accounts = b.Price * 200,					
					@dcFeeDetailsID = a.ID
				FROM dcFeeDetail a WITH(NOLOCK) ,dcFee b WITH(NOLOCK)
				WHERE b.type = 9
				AND a.dcFeeID = b.ID
				AND b.dcProvinceID = LEFT(@ProvinceID,2)
				AND ((MinValue<=50 AND MaxValue>=200) OR (MinValue<=200 AND MaxValue=0))
				AND StartDate < GETDATE() AND EndDate > GETDATE()
		IF @dcFeeDetailsID IS NULL
				SELECT TOP 1 @Accounts = Price * 200
				FROM dcFee  WITH(NOLOCK)
				WHERE type = 9
				AND dcProvinceID = LEFT(@ProvinceID,2)
				AND StartDate < GETDATE() AND EndDate > GETDATE()

		SELECT TOP 1 @MainOrderID = ID,@MainEndDate=EndDate FROM CaOrder WITH(NOLOCK) WHERE cpMainID = @cpMainID AND OpenDate IS NOT NULL AND EndDate>GETDATE() AND OrderType = 8 ORDER BY EndDate DESC
		INSERT INTO caOrder (cpMainID,ProvinceID,ServiceType,PlaceWeek,PayMethod,UserNumber,
		OrderType,Accounts,Paid,Balance,LinkMan,Telephone,LinkRemark,Manageruserid,ActiveQuota,RemainQuota,JobNumber,CompanyName,MainOrderID,InvoiceCompany,dcFeeDetailID,BeginDate,EndDate)
		VALUES(@cpMainID,@ProvinceID,null,null,@PayMethod,0,
		9,@Accounts,0,0,@LinkMan,@Telephone,'',@Manageruserid,200,200,0,@CompanyName,@MainOrderID,@InvoiceCompany,@dcFeeDetailsID,GETDATE(),@MainEndDate)
		SET @NewOrderID = @@IDENTITY
		--UPDATE caOrder SET ReceiveDate=GETDATE() ,ReceiveMan=146 WHERE ID=@NewOrderID
	END
	ELSE IF @GiftType =6	--自动提交2周固定位置订单
	BEGIN
		--取原价和对应的资费ID
		SELECT TOP 1 @Accounts = b.Price * 2,					
					@dcFeeDetailsID = a.ID
				FROM dcFeeDetail a WITH(NOLOCK) ,dcFee b WITH(NOLOCK)
				WHERE b.type = 7
				AND a.dcFeeID = b.ID
				AND b.dcProvinceID = LEFT(@ProvinceID,2)
				AND ((MinValue<=2 AND MaxValue>=2) OR (MinValue<=2 AND MaxValue=0))
				AND StartDate < GETDATE() AND EndDate > GETDATE()
		DECLARE @FixBeginDate SMALLDATETIME
		--取最后一个固定位置的订单
		SELECT TOP 1 @FixBeginDate=EndDate FROM caOrder WHERE cpMainID=@cpMainID AND OrderType=7 AND OpenDate IS NOT NULL AND EndDate>GETDATE() ORDER BY ID DESC
		SET @FixBeginDate=ISNULL(@FixBeginDate,GETDATE())

		INSERT INTO caOrder (cpMainID,ProvinceID,ServiceType,PlaceWeek,PayMethod,UserNumber,
		OrderType,Accounts,Paid,Balance,LinkMan,Telephone,LinkRemark,Manageruserid,ActiveQuota,RemainQuota,JobNumber,CompanyName,MainOrderID,InvoiceCompany,dcFeeDetailID,BeginDate,EndDate,OpenDate,OpenMan,OrderStatus)
		VALUES(@cpMainID,@ProvinceID,null,2,@PayMethod,0,
		7,@Accounts,0,0,@LinkMan,@Telephone,'',@Manageruserid,0,0,0,@CompanyName,@MainOrderID,@InvoiceCompany,@dcFeeDetailsID,@FixBeginDate,DATEADD(day,14,@FixBeginDate),GETDATE(),119,4)
		SET @NewOrderID = @@IDENTITY
		UPDATE caOrder SET ReceiveDate=GETDATE() ,ReceiveMan=146 WHERE ID=@NewOrderID
		--EXEC @NewOrderID = [dbo].[ccCaOrderInsert] @cpMainID,@IsAgent, 32, NULL,2,@PayMethod,7,@Accounts,0,0,@LinkMan,@Telephone,'',@Manageruserid,0,0,@CompanyName,@MainOrderID,@InvoiceCompany,0,@dcFeeDetailsID
	END
	ELSE IF @GiftType = 7	--自动提交2周职位置顶订单，职位默认取最新发布的，前台企业选择后再修改
	BEGIN
		--取原价和对应的资费ID
		SELECT TOP 1 @Accounts = b.Price * 2,					
					@dcFeeDetailsID = a.ID
				FROM dcFeeDetail a WITH(NOLOCK) ,dcFee b WITH(NOLOCK)
				WHERE b.type = 22
				AND a.dcFeeID = b.ID
				AND b.dcProvinceID = LEFT(@ProvinceID,2)
				AND ((MinValue<=2 AND MaxValue>=2) OR (MinValue<=2 AND MaxValue=0))
				AND StartDate < GETDATE() AND EndDate > GETDATE()
		DECLARE @JobID INT
		SELECT @JobID = ID FROM Job WITH(NOLOCK) WHERE Valid = 1  AND cpMainID= @cpMainID AND ID NOT IN(SELECT Balance FROM caOrder WITH(NOLOCK) WHERE OrderType=12 AND BeginDate>GETDATE() AND EndDate<GETDATE()  )
		IF @JobID >0
		BEGIN
			INSERT INTO caOrder (cpMainID,ProvinceID,ServiceType,PlaceWeek,PayMethod,UserNumber,
			OrderType,Accounts,Paid,Balance,LinkMan,Telephone,LinkRemark,Manageruserid,ActiveQuota,RemainQuota,JobNumber,CompanyName,MainOrderID,InvoiceCompany,dcFeeDetailID,NeedInvoice)
			VALUES(@cpMainID,@ProvinceID,null,2,@PayMethod,0,
			12,@Accounts,0,@JobID,@LinkMan,@Telephone,'',@Manageruserid,0,0,0,@CompanyName,@MainOrderID,@InvoiceCompany,@dcFeeDetailsID,0)
			SET @NewOrderID = @@IDENTITY
			--EXEC @NewOrderID = [dbo].[ccCaOrderInsert] @cpMainID,@IsAgent, 32, NULL,2,@PayMethod,12,@Accounts,0,@JobID,@LinkMan,@Telephone,'',@Manageruserid,0,0,@CompanyName,@MainOrderID,@InvoiceCompany,0,@dcFeeDetailsID
		END
	END
	ELSE IF @GiftType = 8	--自动提交2周职位刷新订单
	BEGIN
		--取原价和对应的资费ID
		SELECT TOP 1 @Accounts = b.Price * 2,					
					@dcFeeDetailsID = a.ID
				FROM dcFeeDetail a WITH(NOLOCK) ,dcFee b WITH(NOLOCK)
				WHERE b.type = 24
				AND a.dcFeeID = b.ID
				AND b.dcProvinceID = LEFT(@ProvinceID,2)
				AND ((MinValue<=2 AND MaxValue>=2) OR (MinValue<=2 AND MaxValue=0))
				AND StartDate < GETDATE() AND EndDate > GETDATE()
		DECLARE @RefreshBeginDate SMALLDATETIME
		--取最后一个固定位置的订单
		SELECT TOP 1 @RefreshBeginDate=EndDate FROM caOrder WHERE cpMainID=@cpMainID AND OrderType=13 AND OpenDate IS NOT NULL AND EndDate>GETDATE() ORDER BY ID DESC
		SET @RefreshBeginDate=ISNULL(@RefreshBeginDate,GETDATE())

		INSERT INTO caOrder (cpMainID,ProvinceID,ServiceType,PlaceWeek,PayMethod,UserNumber,
		OrderType,Accounts,Paid,Balance,LinkMan,Telephone,LinkRemark,Manageruserid,ActiveQuota,RemainQuota,JobNumber,CompanyName,MainOrderID,InvoiceCompany,dcFeeDetailID,BeginDate,EndDate,OpenDate,OpenMan,OrderStatus)
		VALUES(@cpMainID,@ProvinceID,null,2,@PayMethod,0,
		13,@Accounts,0,0,@LinkMan,@Telephone,'',@Manageruserid,0,0,0,@CompanyName,@MainOrderID,@InvoiceCompany,@dcFeeDetailsID,@RefreshBeginDate,DATEADD(day,14,@RefreshBeginDate),GETDATE(),119,4)
		SET @NewOrderID = @@IDENTITY
		UPDATE caOrder SET ReceiveDate=GETDATE() ,ReceiveMan=146 WHERE ID=@NewOrderID
		--EXEC @NewOrderID = [dbo].[ccCaOrderInsert] @cpMainID,@IsAgent, 32, NULL,2,@PayMethod,13,@Accounts,0,0,@LinkMan,@Telephone,'',@Manageruserid,0,0,@CompanyName,@MainOrderID,@InvoiceCompany,0,@dcFeeDetailsID
	END
	ELSE IF @GiftType = 10	--自动提交VIP订单  
	BEGIN		
		DECLARE @ActiveQuota INT
		DECLARE @JobNumber INT
		DECLARE @UserNumber INT

		--取本省份价格最便宜的季度套餐
		SELECT TOP 1 @dcFeeDetailsID = b.ID, 
		@Accounts = (a.PriceMonth * b.[Month]+b.ResumeNumber*a.PriceResume+JobNumber*a.PriceJob+UserNumber*a.PriceUser),
		@ActiveQuota = b.ResumeNumber,
		@JobNumber = b.JobNumber,
		@UserNumber = b.UserNumber 
		FROM dcVip a WITH(NOLOCK),dcVipDetail b WITH(NOLOCK) 
		WHERE a.id = b.dcVipId 
		AND dcProvinceid=@ProvinceID 
		AND b.[Month]=3 
		AND startDate<GETDATE() 
		AND enddate > GETDATE()
		ORDER BY Price

		INSERT INTO caOrder (cpMainID,ProvinceID,ServiceType,PlaceWeek,PayMethod,UserNumber,
		OrderType,Accounts,Paid,Balance,LinkMan,Telephone,LinkRemark,Manageruserid,ActiveQuota,RemainQuota,JobNumber,CompanyName,MainOrderID,InvoiceCompany,dcFeeDetailID,NeedInvoice)
		VALUES(@cpMainID,@ProvinceID,null,NULL,@PayMethod,@UserNumber,
		8,@Accounts,0,0,@LinkMan,@Telephone,'',@Manageruserid,@ActiveQuota,@ActiveQuota,@JobNumber,@CompanyName,@MainOrderID,@InvoiceCompany,@dcFeeDetailsID,0)
		SET @NewOrderID = @@IDENTITY
		--EXEC @NewOrderID = [dbo].[ccCaOrderInsert] @cpMainID,@IsAgent, 32, NULL,0,@PayMethod,8,@Accounts,0,0,@LinkMan,@Telephone,'',@Manageruserid,@ActiveQuota,@JobNumber,@CompanyName,@MainOrderID,@InvoiceCompany,@UserNumber,@dcFeeDetailsID
	END
	ELSE IF @GiftType = 11	--自动提交 1:1赠送 
	BEGIN		
		---取最新有赠送抽奖次数的订单 
		INSERT INTO caOrder (cpMainID,ProvinceID,ServiceType,PlaceWeek,PayMethod,UserNumber,
		OrderType,Accounts,Paid,Balance,LinkMan,Telephone,LinkRemark,Manageruserid,ActiveQuota,RemainQuota,JobNumber,CompanyName,MainOrderID,InvoiceCompany,dcFeeDetailID,NeedInvoice)
		SELECT cpMainID,ProvinceID,ServiceType,PlaceWeek,PayMethod,UserNumber,
		OrderType,Accounts,0,0,LinkMan,Telephone,LinkRemark,Manageruserid,ActiveQuota,ActiveQuota,JobNumber,CompanyName,MainOrderID,InvoiceCompany,dcFeeDetailID,0
		FROM caOrder WITH(NOLOCK)
		WHERE ID IN (SELECT TOP 1 caOrderID FROM LotteryCompany WHERE caOrderID IS NOT NULL  AND cpMainID= @cpMainID ORDER BY ID DESC)		
		SET @NewOrderID = @@IDENTITY
	END	
	
	BEGIN TRY
      IF @GiftType<>12
      BEGIN
		--奖品类型：1、50职位并发  2、50份简历 3、100份简历 4、200份简历 5、4周六分之一图片 6、2周文字广告 7、2周职位置顶 
	--8、2周职位自动刷新  9、4周六分之二 10、Vip会员—季度   11、1:1的赠送 
		DECLARE @GiftName VARCHAR(50)
		IF @GiftType =1 
		BEGIN
			SET @GiftName = '50职位并发'
		END
		ELSE IF @GiftType =2
		BEGIN
			SET @GiftName = '50份简历'
		END
		ELSE IF @GiftType =3
		BEGIN
			SET @GiftName = '100份简历'
		END
		ELSE IF @GiftType =4
		BEGIN
			SET @GiftName = '200份简历 '
		END
		ELSE IF @GiftType =5
		BEGIN
			SET @GiftName = '4周六分之一图片广告'
		END
		ELSE IF @GiftType =6
		BEGIN
			SET @GiftName = '2周文字广告'
		END
		ELSE IF @GiftType =7
		BEGIN
			SET @GiftName = '2周职位置顶'
		END
		ELSE IF @GiftType =8
		BEGIN
			SET @GiftName = '2周职位自动刷新'
		END
		ELSE IF @GiftType =9
		BEGIN
			SET @GiftName = '4周六分之二'
		END
		ELSE IF @GiftType =10
		BEGIN
			SET @GiftName = 'Vip会员—季度'
		END
		ELSE
		BEGIN
			SET @GiftName = '1:1的赠送'
		END
			
		IF @Manageruserid IS NULL
		BEGIN	
			INSERT INTO rtxnotifylog
			SELECT STUFF((SELECT ','+LTRIM(x.ID) FROM Manageruser x WHERE ID IN (180,181,182) FOR XML PATH('')),1,1,'')
				,'中奖通知',@CompanyName+'('+LTRIM(STR(@cpMainID))+')中奖了，奖品为['+@GiftName+']，请及时处理http://sysback.51rc.com/yehgiiaovbjkaie871/cp/cpMainInfo.asp?id='+LTRIM(STR(@cpMainID))+'&code='+@Code,1,0,0,null,getdate()
		END
		ELSE
		BEGIN
			INSERT INTO rtxnotifylog
			SELECT @Manageruserid
				,'中奖通知',@CompanyName+'('+LTRIM(STR(@cpMainID))+')中奖了，奖品为['+@GiftName+']，请及时处理http://sysback.51rc.com/yehgiiaovbjkaie871/cp/cpMainInfo.asp?id='+LTRIM(STR(@cpMainID))+'&code='+@Code,1,0,0,null,getdate()
		END
		Update caOrder Set InvoiceConfirmDate=GetDate(),InvoiceConfirmMan=119,InvoiceAskDate=Null,NeedInvoice=0 Where ID=@NewOrderID
      END
	END TRY
	BEGIN CATCH
		
	END CATCH
	--更新LotteryCompany，保存订单号和中奖类型
	UPDATE LotteryCompany SET GiftOrderID=@NewOrderID,[type]=@GiftType WHERE ID= @LotteryID
	RETURN @GiftType
END


GO
/****** Object:  StoredProcedure [dbo].[ccLotteryCompanyUpdate2014]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--创建人：lambo
--创建时间：2014-9-29
--企业14周年抽奖
--奖项内容：	平时	10月8日、18日、28日
--	20职位并发	15%	20%
--	2周图片	    10%	10%
--	50份简历	30%	30%
--	2周文字广告	5%	5%
--	2周职位置顶	5%	5%
--	2周职位自动刷新 	10%	10%
--	Vip会员—季度  	0%	5%（至少有一个，不能重复 ）
--	1:1的赠送	0%	1%（至少有一个，不能重复，如果是年度的不能抽到）
--	学习卡	5%	4%（至少有一个，不能重复）
--	空奖	20%	10%
--	保险公司，抽奖中奖概率调整为10%		
--修改人：nick
--修改时间：2014-10-10
--修改内容：发送rtx消息，加入奖品名称
CREATE PROCEDURE [dbo].[ccLotteryCompanyUpdate2014] 
(
	@caMainID INT 
)
AS
BEGIN
	DECLARE @LotteryID INT
	DECLARE @cpMainID INT 
	SELECT TOP 1 @LotteryID = ID,@cpMainID = cpMainID FROM LotteryCompany WITH(NOLOCK) WHERE Used = 0 AND cpMainID = (select cpMainID FROM caMain WITH(NOLOCK) WHERE ID = @caMainID AND AccountType=1) 

	IF @LotteryID IS NULL	
		RETURN -1 --没有抽奖次数
	UPDATE LotteryCompany SET Used = 1,LotteryDate=GETDATE() WHERE ID = @LotteryID --更新状态 防止重复抽奖

	------------------****************生成抽奖结果****************-----------------
	DECLARE @IsAgent INT --是否是保险公司
	SELECT top 1 @IsAgent = IsAgent FROM cpMain WITH(NOLOCK) WHERE ID = @cpMainID
	
	DECLARE @Today VARCHAR(4)	--用于判断 是否是10月8日、18日、28日
	SELECT @Today = RIGHT(CONVERT(VARCHAR(8) , GETDATE() , 112) , 4)
	
	DECLARE @GiftNo INT
	SELECT @GiftNo = CAST((RAND()*999+1) AS INT) --生成抽奖的数字
		
	--奖品类型：1、20职位并发 2、2周图片  3、50份简历 4、2周文字广告 5、2周职位置顶 6、2周职位自动刷新  7、Vip会员—季度   8、1:1的赠送 9、空奖 10、学习卡
	DECLARE @GiftType INT 

	IF @IsAgent = 0
	BEGIN
		IF @GiftNo BETWEEN 51 AND 200 OR (@GiftNo BETWEEN 201 AND 250 AND (@Today = '1008' OR @Today = '1018' OR @Today = '1028' ))	--51-200之间 职位并发 15%概率
			SET @GiftType = 1
		ELSE IF @GiftNo BETWEEN 251 AND 350	--251-350之间 2周图片	 10%概率
			SET @GiftType = 2
		ELSE IF @GiftNo BETWEEN 351 AND 650	--351-650之间 50简历下载 30%概率
			SET @GiftType = 3
		ELSE IF @GiftNo BETWEEN 651 AND 700	--651-700之间 两周文字广告 5%概率
			SET @GiftType = 4
		ELSE IF @GiftNo BETWEEN 701 AND 750	--701-750之间 两周职位置顶 5%概率
			SET @GiftType = 5
		ELSE IF @GiftNo BETWEEN 751 AND 850	--751-850之间 两周职位刷新 10%概率
			SET @GiftType = 6
		ELSE IF @GiftNo BETWEEN 851 AND 900 AND (@Today = '1008' OR @Today = '1018' OR @Today = '1028' )	--0-50之间 Vip会员—季度 5%概率
			SET @GiftType = 7
		ELSE IF @GiftNo BETWEEN 951 AND 960 AND (@Today = '1008' OR @Today = '1018' OR @Today = '1028' )	--951-1000之间 1:1赠送 1%概率
			SET @GiftType = 8
		ELSE IF @GiftNo BETWEEN 961 AND 1000 OR (@GiftNo BETWEEN 910 AND 920 AND (@Today = '1008' OR @Today = '1018' OR @Today = '1028' ))	--学习卡 4%概率
			SET @GiftType = 10
		ELSE	--空奖  20%概率
			SET @GiftType = 9
	END
	ELSE  -- 保险公司中奖概率10%
	BEGIN
		IF @GiftNo BETWEEN 61 AND 81	--61-80之间 职位并发 15%概率
			SET @GiftType = 1
		ELSE IF @GiftNo BETWEEN 281 AND 310	--281-310之间 2周图片 不能被抽到
			SET @GiftType = 9
		ELSE IF @GiftNo BETWEEN 581 AND 590	--581-590之间 50简历下载 30%概率
			SET @GiftType = 3
		ELSE IF @GiftNo BETWEEN 661 AND 665	--661-665 两周文字广告 不能被抽到
			SET @GiftType = 9
		ELSE IF @GiftNo BETWEEN 731 AND 735	--731-735 两周职位置顶 5%概率
			SET @GiftType = 5
		ELSE IF @GiftNo BETWEEN 761 AND 770	--761-770 两周职位刷新 10%概率
			SET @GiftType = 6
		ELSE IF @GiftNo = 851 AND (@Today = '1008' OR @Today = '1018' OR @Today = '1028' )
			SET @GiftType = 7
		ELSE IF @GiftNo = 951 AND (@Today = '1008' OR @Today = '1018' OR @Today = '1028' )
			SET @GiftType = 8
		ELSE IF @GiftNo BETWEEN 961 AND 966 
			SET @GiftType = 10
		ELSE	--空奖  20%概率
			SET @GiftType = 9		
	END
	IF GETDATE()>'2014-11-1'	
		SET @GiftType = 9		
	/*---------****************抽奖结果处理，判断是否合理，重复 **************-------------*/
	IF (@GiftType =7 OR @GiftType = 8) AND NOT (@Today = '1008' OR @Today = '1018' OR @Today = '1028' ) --不是带8的日子不能抽到
		SET @GiftType = 1
	IF @GiftType IN (7,8,10) AND EXISTS(SELECT TOP 1 'x' FROM LotteryCompany WHERE [Type]=@GiftType AND cpMainID=@cpMainID)  --重复抽到了
		SET @GiftType = 1
	IF @GiftType =8	--本月开通的非年度的才赠送
		IF NOT EXISTS(SELECT TOP 1 'x' FROM caOrder WITH(NOLOCK)
					WHERE ID IN (SELECT TOP 1 caOrderID FROM LotteryCompany WITH(NOLOCK)
									WHERE caOrderID IS NOT NULL  AND cpMainID= @cpMainID 
									ORDER BY ID DESC)		
					AND dcFeeDetailId in (SELECT id FROM dcVipDetail WITH(NOLOCK) WHERE [Month]<12)
					AND orderType=8
					AND OpenDate>'2014-10-1'
					AND Paid>0
				) OR EXISTS(SELECT TOP 1 'x' FROM caOrder WITH(NOLOCK)
					WHERE ID IN (SELECT TOP 1 caOrderID FROM LotteryCompany WITH(NOLOCK)
									WHERE caOrderID IS NOT NULL  AND cpMainID= @cpMainID 
									ORDER BY ID DESC)		
					AND dcFeeDetailId in (SELECT id FROM dcVipDetail WITH(NOLOCK) WHERE [Month]>=12)
					AND orderType=8
					AND OpenDate>'2014-10-1'

				) 
			SET @GiftType = 1
	IF @GiftType =7	--本月开通的会员的才赠送
		IF NOT EXISTS(SELECT TOP 1 'x' FROM caOrder WITH(NOLOCK)
					WHERE ID IN (SELECT TOP 1 caOrderID FROM LotteryCompany WITH(NOLOCK)
									WHERE caOrderID IS NOT NULL  AND cpMainID= @cpMainID 
									ORDER BY ID DESC)							
					AND orderType=8
					AND OpenDate>'2014-10-1'
					AND Paid>0
				)
			SET @GiftType = 1
					
	DECLARE @GiftCount INT
	SELECT @GiftCount = COUNT(*) FROM LotteryCompany WHERE cpMainID=@cpMainID and [type]<>9 and used=1
	--年度、双年度以上最多中奖为8次，最多中8次奖。
	IF @GiftCount>=8
	BEGIN		
		SET @GiftType = 9	
	END	
	ELSE IF @GiftCount>=5 --季度、半年度最多中奖为5次。
	BEGIN
		IF NOT EXISTS(SELECT TOP 1 'x' FROM caOrder WITH(NOLOCK)
					WHERE ID IN (SELECT TOP 1 caOrderID FROM LotteryCompany WITH(NOLOCK)
									WHERE caOrderID IS NOT NULL  AND cpMainID= @cpMainID 
									ORDER BY ID DESC)		
					AND dcFeeDetailId in (SELECT id FROM dcVipDetail WITH(NOLOCK) WHERE [Month]>=12)					
					AND orderType=8)
		BEGIN
			SET @GiftType = 9
		END
	END
	ELSE IF @GiftCount>=3 --如果当月没有购买会员，仅进行连续登陆，那么最多中奖为3次。
	BEGIN
		IF NOT EXISTS(SELECT TOP 1 'x' FROM caOrder WITH(NOLOCK)
					WHERE ID IN (SELECT TOP 1 caOrderID FROM LotteryCompany WITH(NOLOCK)
									WHERE caOrderID IS NOT NULL  AND cpMainID= @cpMainID 
									ORDER BY ID DESC)		
					AND dcFeeDetailId in (SELECT id FROM dcVipDetail WITH(NOLOCK) WHERE [Month]>=3)					
					AND orderType=8)
		BEGIN
			SET @GiftType = 9
		END
	END	
	IF @GiftType = 10
	BEGIN
		DECLARE @GiftCardCount INT
		SELECT @GiftCardCount = COUNT(*) FROM LotteryCompany WHERE [type] =10 and used=1
		IF @GiftCardCount>=80
			SET @GiftType = 9
	END
	IF @cpMainID =371108
	BEGIN
		SET @GiftType = 6
	END
	/*---------****************自动提交订单**************-------------*/
	DECLARE @ProvinceID INT
	DECLARE @PayMethod INT	--取上次订单的付款方式
	DECLARE @LinkMan NVARCHAR(50) 
	DECLARE @Telephone NVARCHAR(50)
	DECLARE @CompanyName NVARCHAR(50)
	DECLARE @Accounts NUMERIC(18,2)	
	DECLARE @dcFeeDetailsID INT
	DECLARE @Manageruserid INT
	DECLARE @MemberType INT
	DECLARE @MainOrderID INT
	DECLARE @MainEndDate SMALLDATETIME
	DECLARE @InvoiceCompany NVARCHAR(50)
	DECLARE @Hour INT
	DECLARE @Minute INT
	DECLARE @Code VARCHAR(10)
	DECLARE @RegDate DATETIME
	SELECT TOP 1 
		@ProvinceID = b.dcProvinceID,
		@PayMethod = c.PayMethod,
		@MemberType = MemberType,
		@LinkMan = LinkMan,
		@Telephone = Telephone,
		@CompanyName = CompanyName,
		@InvoiceCompany = InvoiceCompany,
		@Manageruserid = ConsultantID,
		@RegDate = RegDate
	FROM cpMain b ,caOrder c
	WHERE b.id =c.cpmainid
	AND c.cpMainID = @cpMainID 
	AND Paid>0
	ORDER BY c.ID DESC
	
	SELECT @Hour = DATEPART(HOUR,@RegDate)
    SELECT @Minute = DATEPART(Minute,@RegDate)
    
    SET @Code = CONVERT(VARCHAR(10),@Hour*100+@Minute)
         
    SET @PayMethod = 7 
	DECLARE	@NewOrderID INT
	IF @GiftType= 1 AND @MemberType=3	--自动提交20个职位并发数的订单
	BEGIN			
		--取原价和对应的资费ID
		SELECT TOP 1 @Accounts = b.Price * 10,					
					@dcFeeDetailsID = a.ID
				FROM dcFeeDetail a WITH(NOLOCK) ,dcFee b WITH(NOLOCK)
				WHERE b.type = 10
				AND a.dcFeeID = b.ID
				AND b.dcProvinceID = LEFT(@ProvinceID,2)
				AND ((MinValue<=20 AND MaxValue>=20) OR (MinValue<=20 AND MaxValue=0))
				AND StartDate < GETDATE() AND EndDate > GETDATE()

		SELECT TOP 1 @MainOrderID = ID ,@MainEndDate=EndDate FROM CaOrder WITH(NOLOCK) WHERE cpMainID = @cpMainID AND OpenDate IS NOT NULL AND EndDate>GETDATE() AND OrderType = 8 ORDER BY EndDate DESC
		--EXEC @NewOrderID = [dbo].[ccCaOrderInsert] @cpMainID,0, 32, NULL,NULL,@PayMethod,10,@Accounts,0,0,@LinkMan,@Telephone,'',@Manageruserid,0,10,@CompanyName,@MainOrderID,@InvoiceCompany,0,@dcFeeDetailsID
		INSERT INTO caOrder (cpMainID,ProvinceID,ServiceType,PlaceWeek,PayMethod,UserNumber,
		OrderType,Accounts,Paid,Balance,LinkMan,Telephone,LinkRemark,Manageruserid,ActiveQuota,RemainQuota,JobNumber,CompanyName,MainOrderID,InvoiceCompany,dcFeeDetailID,BeginDate,EndDate,OpenDate,OpenMan,OrderStatus)
		VALUES(@cpMainID,@ProvinceID,null,null,@PayMethod,0,
		10,@Accounts,0,0,@LinkMan,@Telephone,'',@Manageruserid,0,0,20,@CompanyName,@MainOrderID,@InvoiceCompany,@dcFeeDetailsID,GETDATE(),@MainEndDate,GETDATE(),119,4)
		SET @NewOrderID = @@IDENTITY
		UPDATE caOrder SET ReceiveDate=GETDATE() ,ReceiveMan=146 WHERE ID=@NewOrderID
	END
	ELSE IF @GiftType = 2	--自动提交2周1/6图片 广告
	BEGIN
		--取原价和对应的资费ID
		SELECT TOP 1 @Accounts = b.Price * 2,					
					@dcFeeDetailsID = a.ID
				FROM dcFeeDetail a WITH(NOLOCK) ,dcFee b WITH(NOLOCK)
				WHERE b.type = 4
				AND a.dcFeeID = b.ID
				AND b.dcProvinceID = LEFT(@ProvinceID,2)
				AND ((MinValue<=2 AND MaxValue>=2) OR (MinValue<=2 AND MaxValue=0))
				AND StartDate < GETDATE() AND EndDate > GETDATE()
		INSERT INTO caOrder (cpMainID,ProvinceID,ServiceType,PlaceWeek,PayMethod,UserNumber,
		OrderType,Accounts,Paid,Balance,LinkMan,Telephone,LinkRemark,Manageruserid,ActiveQuota,RemainQuota,JobNumber,CompanyName,MainOrderID,InvoiceCompany,dcFeeDetailID,NeedInvoice)
		VALUES(@cpMainID,@ProvinceID,6,2,@PayMethod,0,
		4,@Accounts,0,0,@LinkMan,@Telephone,'',@Manageruserid,0,0,0,@CompanyName,@MainOrderID,@InvoiceCompany,@dcFeeDetailsID,0)
		SET @NewOrderID = @@IDENTITY
		--EXEC @NewOrderID = [dbo].[ccCaOrderInsert] @cpMainID,@IsAgent, 32, NULL,2,@PayMethod,7,@Accounts,0,0,@LinkMan,@Telephone,'',@Manageruserid,0,0,@CompanyName,@MainOrderID,@InvoiceCompany,0,@dcFeeDetailsID
	END
	ELSE IF @GiftType = 3 AND @MemberType=3	--自动提交50简历下载订单
	BEGIN
		--取原价和对应的资费ID
		SELECT TOP 1 @Accounts = b.Price * 50,					
					@dcFeeDetailsID = a.ID
				FROM dcFeeDetail a WITH(NOLOCK) ,dcFee b WITH(NOLOCK)
				WHERE b.type = 9
				AND a.dcFeeID = b.ID
				AND b.dcProvinceID = LEFT(@ProvinceID,2)
				AND ((MinValue<=50 AND MaxValue>=50) OR (MinValue<=50 AND MaxValue=0))
				AND StartDate < GETDATE() AND EndDate > GETDATE()
		IF @dcFeeDetailsID IS NULL
				SELECT TOP 1 @Accounts = Price * 50
				FROM dcFee  WITH(NOLOCK)
				WHERE type = 9
				AND dcProvinceID = LEFT(@ProvinceID,2)
				AND StartDate < GETDATE() AND EndDate > GETDATE()

		SELECT TOP 1 @MainOrderID = ID,@MainEndDate=EndDate FROM CaOrder WITH(NOLOCK) WHERE cpMainID = @cpMainID AND OpenDate IS NOT NULL AND EndDate>GETDATE() AND OrderType = 8 ORDER BY EndDate DESC
		INSERT INTO caOrder (cpMainID,ProvinceID,ServiceType,PlaceWeek,PayMethod,UserNumber,
		OrderType,Accounts,Paid,Balance,LinkMan,Telephone,LinkRemark,Manageruserid,ActiveQuota,RemainQuota,JobNumber,CompanyName,MainOrderID,InvoiceCompany,dcFeeDetailID,BeginDate,EndDate)
		VALUES(@cpMainID,@ProvinceID,null,null,@PayMethod,0,
		9,@Accounts,0,0,@LinkMan,@Telephone,'',@Manageruserid,50,50,0,@CompanyName,@MainOrderID,@InvoiceCompany,@dcFeeDetailsID,GETDATE(),@MainEndDate)
		SET @NewOrderID = @@IDENTITY
		--UPDATE caOrder SET ReceiveDate=GETDATE() ,ReceiveMan=146 WHERE ID=@NewOrderID
	END
	ELSE IF @GiftType = 4	--自动提交2周固定位置订单
	BEGIN
		--取原价和对应的资费ID
		SELECT TOP 1 @Accounts = b.Price * 2,					
					@dcFeeDetailsID = a.ID
				FROM dcFeeDetail a WITH(NOLOCK) ,dcFee b WITH(NOLOCK)
				WHERE b.type = 7
				AND a.dcFeeID = b.ID
				AND b.dcProvinceID = LEFT(@ProvinceID,2)
				AND ((MinValue<=2 AND MaxValue>=2) OR (MinValue<=2 AND MaxValue=0))
				AND StartDate < GETDATE() AND EndDate > GETDATE()
		DECLARE @FixBeginDate SMALLDATETIME
		--取最后一个固定位置的订单
		SELECT TOP 1 @FixBeginDate=EndDate FROM caOrder WHERE cpMainID=@cpMainID AND OrderType=7 AND OpenDate IS NOT NULL AND EndDate>GETDATE() ORDER BY ID DESC
		SET @FixBeginDate=ISNULL(@FixBeginDate,GETDATE())

		INSERT INTO caOrder (cpMainID,ProvinceID,ServiceType,PlaceWeek,PayMethod,UserNumber,
		OrderType,Accounts,Paid,Balance,LinkMan,Telephone,LinkRemark,Manageruserid,ActiveQuota,RemainQuota,JobNumber,CompanyName,MainOrderID,InvoiceCompany,dcFeeDetailID,BeginDate,EndDate,OpenDate,OpenMan,OrderStatus)
		VALUES(@cpMainID,@ProvinceID,null,2,@PayMethod,0,
		7,@Accounts,0,0,@LinkMan,@Telephone,'',@Manageruserid,0,0,0,@CompanyName,@MainOrderID,@InvoiceCompany,@dcFeeDetailsID,@FixBeginDate,DATEADD(day,14,@FixBeginDate),GETDATE(),119,4)
		SET @NewOrderID = @@IDENTITY
		UPDATE caOrder SET ReceiveDate=GETDATE() ,ReceiveMan=146 WHERE ID=@NewOrderID
		--EXEC @NewOrderID = [dbo].[ccCaOrderInsert] @cpMainID,@IsAgent, 32, NULL,2,@PayMethod,7,@Accounts,0,0,@LinkMan,@Telephone,'',@Manageruserid,0,0,@CompanyName,@MainOrderID,@InvoiceCompany,0,@dcFeeDetailsID
	END
	ELSE IF @GiftType = 5	--自动提交2周职位置顶订单，职位默认取最新发布的，前台企业选择后再修改
	BEGIN
		--取原价和对应的资费ID
		SELECT TOP 1 @Accounts = b.Price * 2,					
					@dcFeeDetailsID = a.ID
				FROM dcFeeDetail a WITH(NOLOCK) ,dcFee b WITH(NOLOCK)
				WHERE b.type = 22
				AND a.dcFeeID = b.ID
				AND b.dcProvinceID = LEFT(@ProvinceID,2)
				AND ((MinValue<=2 AND MaxValue>=2) OR (MinValue<=2 AND MaxValue=0))
				AND StartDate < GETDATE() AND EndDate > GETDATE()
		DECLARE @JobID INT
		SELECT @JobID = ID FROM Job WITH(NOLOCK) WHERE Valid = 1  AND cpMainID= @cpMainID AND ID NOT IN(SELECT Balance FROM caOrder WITH(NOLOCK) WHERE OrderType=12 AND BeginDate>GETDATE() AND EndDate<GETDATE()  )
		IF @JobID >0
		BEGIN
			INSERT INTO caOrder (cpMainID,ProvinceID,ServiceType,PlaceWeek,PayMethod,UserNumber,
			OrderType,Accounts,Paid,Balance,LinkMan,Telephone,LinkRemark,Manageruserid,ActiveQuota,RemainQuota,JobNumber,CompanyName,MainOrderID,InvoiceCompany,dcFeeDetailID,NeedInvoice)
			VALUES(@cpMainID,@ProvinceID,null,2,@PayMethod,0,
			12,@Accounts,0,@JobID,@LinkMan,@Telephone,'',@Manageruserid,0,0,0,@CompanyName,@MainOrderID,@InvoiceCompany,@dcFeeDetailsID,0)
			SET @NewOrderID = @@IDENTITY
			--EXEC @NewOrderID = [dbo].[ccCaOrderInsert] @cpMainID,@IsAgent, 32, NULL,2,@PayMethod,12,@Accounts,0,@JobID,@LinkMan,@Telephone,'',@Manageruserid,0,0,@CompanyName,@MainOrderID,@InvoiceCompany,0,@dcFeeDetailsID
		END
	END
	ELSE IF @GiftType = 6	--自动提交2周职位刷新订单
	BEGIN
		--取原价和对应的资费ID
		SELECT TOP 1 @Accounts = b.Price * 2,					
					@dcFeeDetailsID = a.ID
				FROM dcFeeDetail a WITH(NOLOCK) ,dcFee b WITH(NOLOCK)
				WHERE b.type = 24
				AND a.dcFeeID = b.ID
				AND b.dcProvinceID = LEFT(@ProvinceID,2)
				AND ((MinValue<=2 AND MaxValue>=2) OR (MinValue<=2 AND MaxValue=0))
				AND StartDate < GETDATE() AND EndDate > GETDATE()
		DECLARE @RefreshBeginDate SMALLDATETIME
		--取最后一个固定位置的订单
		SELECT TOP 1 @RefreshBeginDate=EndDate FROM caOrder WHERE cpMainID=@cpMainID AND OrderType=13 AND OpenDate IS NOT NULL AND EndDate>GETDATE() ORDER BY ID DESC
		SET @RefreshBeginDate=ISNULL(@RefreshBeginDate,GETDATE())

		INSERT INTO caOrder (cpMainID,ProvinceID,ServiceType,PlaceWeek,PayMethod,UserNumber,
		OrderType,Accounts,Paid,Balance,LinkMan,Telephone,LinkRemark,Manageruserid,ActiveQuota,RemainQuota,JobNumber,CompanyName,MainOrderID,InvoiceCompany,dcFeeDetailID,BeginDate,EndDate,OpenDate,OpenMan,OrderStatus)
		VALUES(@cpMainID,@ProvinceID,null,2,@PayMethod,0,
		13,@Accounts,0,0,@LinkMan,@Telephone,'',@Manageruserid,0,0,0,@CompanyName,@MainOrderID,@InvoiceCompany,@dcFeeDetailsID,@RefreshBeginDate,DATEADD(day,14,@RefreshBeginDate),GETDATE(),119,4)
		SET @NewOrderID = @@IDENTITY
		UPDATE caOrder SET ReceiveDate=GETDATE() ,ReceiveMan=146 WHERE ID=@NewOrderID
		--EXEC @NewOrderID = [dbo].[ccCaOrderInsert] @cpMainID,@IsAgent, 32, NULL,2,@PayMethod,13,@Accounts,0,0,@LinkMan,@Telephone,'',@Manageruserid,0,0,@CompanyName,@MainOrderID,@InvoiceCompany,0,@dcFeeDetailsID
	END
	ELSE IF @GiftType = 7	--自动提交VIP订单  
	BEGIN		
		DECLARE @ActiveQuota INT
		DECLARE @JobNumber INT
		DECLARE @UserNumber INT

		--取本省份价格最便宜的季度套餐
		SELECT TOP 1 @dcFeeDetailsID = b.ID, 
		@Accounts = (a.PriceMonth * b.[Month]+b.ResumeNumber*a.PriceResume+JobNumber*a.PriceJob+UserNumber*a.PriceUser),
		@ActiveQuota = b.ResumeNumber,
		@JobNumber = b.JobNumber,
		@UserNumber = b.UserNumber 
		FROM dcVip a WITH(NOLOCK),dcVipDetail b WITH(NOLOCK) 
		WHERE a.id = b.dcVipId 
		AND dcProvinceid=@ProvinceID 
		AND b.[Month]=3 
		AND startDate<GETDATE() 
		AND enddate > GETDATE()
		ORDER BY Price

		INSERT INTO caOrder (cpMainID,ProvinceID,ServiceType,PlaceWeek,PayMethod,UserNumber,
		OrderType,Accounts,Paid,Balance,LinkMan,Telephone,LinkRemark,Manageruserid,ActiveQuota,RemainQuota,JobNumber,CompanyName,MainOrderID,InvoiceCompany,dcFeeDetailID,NeedInvoice)
		VALUES(@cpMainID,@ProvinceID,null,NULL,@PayMethod,@UserNumber,
		8,@Accounts,0,0,@LinkMan,@Telephone,'',@Manageruserid,@ActiveQuota,@ActiveQuota,@JobNumber,@CompanyName,@MainOrderID,@InvoiceCompany,@dcFeeDetailsID,0)
		SET @NewOrderID = @@IDENTITY
		--EXEC @NewOrderID = [dbo].[ccCaOrderInsert] @cpMainID,@IsAgent, 32, NULL,0,@PayMethod,8,@Accounts,0,0,@LinkMan,@Telephone,'',@Manageruserid,@ActiveQuota,@JobNumber,@CompanyName,@MainOrderID,@InvoiceCompany,@UserNumber,@dcFeeDetailsID
	END
	ELSE IF @GiftType = 8	--自动提交 1:1赠送 
	BEGIN		
		---取最新有赠送抽奖次数的订单 
		INSERT INTO caOrder (cpMainID,ProvinceID,ServiceType,PlaceWeek,PayMethod,UserNumber,
		OrderType,Accounts,Paid,Balance,LinkMan,Telephone,LinkRemark,Manageruserid,ActiveQuota,RemainQuota,JobNumber,CompanyName,MainOrderID,InvoiceCompany,dcFeeDetailID,NeedInvoice)
		SELECT cpMainID,ProvinceID,ServiceType,PlaceWeek,PayMethod,UserNumber,
		OrderType,Accounts,0,0,LinkMan,Telephone,LinkRemark,Manageruserid,ActiveQuota,ActiveQuota,JobNumber,CompanyName,MainOrderID,InvoiceCompany,dcFeeDetailID,0
		FROM caOrder WITH(NOLOCK)
		WHERE ID IN (SELECT TOP 1 caOrderID FROM LotteryCompany WHERE caOrderID IS NOT NULL  AND cpMainID= @cpMainID ORDER BY ID DESC)		
		SET @NewOrderID = @@IDENTITY
	END	
	
	BEGIN TRY
      IF @GiftType<>9 
      BEGIN
		--奖品类型：1、20职位并发 2、2周图片  3、50份简历 4、2周文字广告 5、2周职位置顶 6、2周职位自动刷新  7、Vip会员—季度   8、1:1的赠送 9、空奖 10、学习卡
		DECLARE @GiftName VARCHAR(50)
		IF @GiftType =1 
		BEGIN
			SET @GiftName = '20职位并发'
		END
		ELSE IF @GiftType =2
		BEGIN
			SET @GiftName = '2周图片'
		END
		ELSE IF @GiftType =3
		BEGIN
			SET @GiftName = '50份简历'
		END
		ELSE IF @GiftType =4
		BEGIN
			SET @GiftName = '2周文字广告'
		END
		ELSE IF @GiftType =5
		BEGIN
			SET @GiftName = '2周职位置顶'
		END
		ELSE IF @GiftType =6
		BEGIN
			SET @GiftName = '2周职位自动刷新'
		END
		ELSE IF @GiftType =7
		BEGIN
			SET @GiftName = 'Vip会员—季度'
		END
		ELSE IF @GiftType =8
		BEGIN
			SET @GiftName = '1:1的赠送'
		END
		ELSE IF @GiftType =10
		BEGIN
			SET @GiftName = '学习卡'
		END
		ELSE
		BEGIN
			SET @GiftName = '空奖'
		END
			
		IF @Manageruserid IS NULL
		BEGIN	
			INSERT INTO rtxnotifylog
			SELECT STUFF((SELECT ','+LTRIM(x.ID) FROM Manageruser x WHERE ID IN (180,181,182) FOR XML PATH('')),1,1,'')
				,'中奖通知',@CompanyName+'('+LTRIM(STR(@cpMainID))+')中奖了，奖品为['+@GiftName+']，请及时处理http://115.182.8.38:81/yehgiiaovbjkaie871/cp/cpMainInfo.asp?id='+LTRIM(STR(@cpMainID))+'&code='+@Code,1,0,0,null,getdate()
		END
		ELSE
		BEGIN
			INSERT INTO rtxnotifylog
			SELECT @Manageruserid
				,'中奖通知',@CompanyName+'('+LTRIM(STR(@cpMainID))+')中奖了，奖品为['+@GiftName+']，请及时处理http://115.182.8.38:81/yehgiiaovbjkaie871/cp/cpMainInfo.asp?id='+LTRIM(STR(@cpMainID))+'&code='+@Code,1,0,0,null,getdate()
		END
		Update caOrder Set InvoiceConfirmDate=GetDate(),InvoiceConfirmMan=119,InvoiceAskDate=Null,NeedInvoice=0 Where ID=@NewOrderID
      END
	END TRY
	BEGIN CATCH
		
	END CATCH
	--更新LotteryCompany，保存订单号和中奖类型
	UPDATE LotteryCompany SET GiftOrderID=@NewOrderID,[type]=@GiftType WHERE ID= @LotteryID
	RETURN @GiftType
END


GO
/****** Object:  StoredProcedure [dbo].[ccLotteryCompanyUpdate2016]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--创建人：Lucifer
--创建时间：2016-9-20
--企业16周年抽奖
--奖项内容：		平时	10月8日、18日、25日、28日
--50职位并发		15%		5%
--50份简历			20%		10%
--100份简历			15%		20%
--200份简历			10%		15%
--4周六分之一图片	10%		15%
--2周知名企业		10%		10%
--2周职位置顶		5%		5%
--2周职位自动刷新 	15%		10%
--4周六分之二图片	0%		8%
--Vip会员—季度  	0%		2%（至少有一个，不能重复）
--保险公司，培训公司，代理招聘类公司仅能够中奖的范围：职位数、简历数、自动刷新。其他内容不允许抽中。需要在抽选中排除。
CREATE PROCEDURE [dbo].[ccLotteryCompanyUpdate2016] 
(
	@caMainID INT 
)
AS
BEGIN
	DECLARE @LotteryID INT
	DECLARE @cpMainID INT 
	SELECT TOP 1 @LotteryID = ID,@cpMainID = cpMainID FROM LotteryCompany WITH(NOLOCK) WHERE Used = 0 AND cpMainID = (select cpMainID FROM caMain WITH(NOLOCK) WHERE ID = @caMainID AND AccountType=1) 

	IF @LotteryID IS NULL	
		RETURN -1 --没有抽奖次数
	UPDATE LotteryCompany SET Used = 1,LotteryDate = GETDATE() WHERE ID = @LotteryID --更新状态 防止重复抽奖

	------------------****************生成抽奖结果****************-----------------
	DECLARE @IsAgent INT --是否是保险公司
	DECLARE @Name NVARCHAR(200)
	SELECT TOP 1 @IsAgent = IsAgent,@Name = Name FROM cpMain WITH(NOLOCK) WHERE ID = @cpMainID
	IF @IsAgent = 0
	BEGIN
		IF @Name LIKE '%人寿%' OR @Name LIKE '%保险%' 
			SET @IsAgent = 1
	END
	
	DECLARE @GiftNo INT, @GiftType INT, @LoopCount INT
	SELECT @GiftNo = CAST((RAND()*999+1) AS INT) --生成抽奖的数字
	SELECT @GiftType = dbo.GetLotteryGiftType(@IsAgent, @GiftNo)
	SET @LoopCount = 0
	WHILE EXISTS(SELECT 'X' FROM LotteryCompany WHERE [Type] = @GiftType AND cpMainID = @cpMainID) OR @LoopCount < 1000
	BEGIN
		SELECT @GiftNo = CAST((RAND()*999 + 1) AS INT) --生成抽奖的数字
		SELECT @GiftType = dbo.GetLotteryGiftType(@IsAgent, @GiftNo)
		SET @LoopCount = @LoopCount + 1
	END
	PRINT @GiftType
	/*---------****************自动提交订单**************-------------*/
	DECLARE @ProvinceID INT
	DECLARE @PayMethod INT	--取上次订单的付款方式
	DECLARE @LinkMan NVARCHAR(50) 
	DECLARE @Telephone NVARCHAR(50)
	DECLARE @CompanyName NVARCHAR(50)
	DECLARE @Accounts NUMERIC(18,2)	
	DECLARE @dcFeeDetailsID INT
	DECLARE @Manageruserid INT
	DECLARE @MemberType INT
	DECLARE @MainOrderID INT
	DECLARE @InvoiceCompany NVARCHAR(50)
	DECLARE @Hour INT
	DECLARE @MainEndDate SMALLDATETIME
	DECLARE @Minute INT
	DECLARE @Code VARCHAR(10)
	DECLARE @RegDate DATETIME
	SELECT TOP 1 
		@ProvinceID = b.dcProvinceID,
		@PayMethod = c.PayMethod,
		@MemberType = MemberType,
		@LinkMan = LinkMan,
		@Telephone = Telephone,
		@CompanyName = CompanyName,
		@InvoiceCompany = InvoiceCompany,
		@Manageruserid = ConsultantID,
		@RegDate = RegDate
	FROM cpMain b ,caOrder c
	WHERE b.id =c.cpmainid
	AND c.cpMainID = @cpMainID
	AND Paid>0
	ORDER BY c.ID DESC
	
	SELECT @Hour = DATEPART(HOUR,@RegDate)
    SELECT @Minute = DATEPART(Minute,@RegDate)
    
    SET @Code = CONVERT(VARCHAR(10),@Hour*100+@Minute)
         
    SET @PayMethod = 7 
	DECLARE	@NewOrderID INT
	IF @GiftType= 1 AND @MemberType=3	--自动提交50个职位并发数的订单
	BEGIN			
		--取原价和对应的资费ID
		SELECT TOP 1 @Accounts = b.Price * 50,					
					@dcFeeDetailsID = a.ID
				FROM dcFeeDetail a WITH(NOLOCK) ,dcFee b WITH(NOLOCK)
				WHERE b.type = 10
				AND a.dcFeeID = b.ID
				AND b.dcProvinceID = LEFT(@ProvinceID,2)
				AND ((MinValue <= 50 AND MaxValue >= 50) OR (MinValue <= 50 AND MaxValue = 0))
				AND StartDate < GETDATE() AND EndDate > GETDATE()

		SELECT TOP 1 @MainOrderID = ID, @MainEndDate = EndDate FROM CaOrder WITH(NOLOCK) WHERE cpMainID = @cpMainID AND OpenDate IS NOT NULL AND EndDate>GETDATE() AND OrderType = 8 ORDER BY EndDate DESC	
		INSERT INTO caOrder (cpMainID,ProvinceID,ServiceType,PlaceWeek,PayMethod,UserNumber,
		OrderType,Accounts,Paid,Balance,LinkMan,Telephone,LinkRemark,Manageruserid,ActiveQuota,RemainQuota,JobNumber,CompanyName,MainOrderID,InvoiceCompany,dcFeeDetailID,BeginDate,EndDate,OpenDate,OpenMan,OrderStatus)
		VALUES(@cpMainID,@ProvinceID,NULL,NULL,@PayMethod,0,
		10,@Accounts,0,0,@LinkMan,@Telephone,'',@Manageruserid,0,0,50,@CompanyName,@MainOrderID,@InvoiceCompany,@dcFeeDetailsID,GETDATE(),@MainEndDate,GETDATE(),116,4)
		SET @NewOrderID = @@IDENTITY
	END
	ELSE IF @GiftType = 5	--自动提交4周1/6图片 广告
	BEGIN
		--取原价和对应的资费ID
		SELECT TOP 1 @Accounts = b.Price * 4,					
					@dcFeeDetailsID = a.ID
				FROM dcFeeDetail a WITH(NOLOCK) ,dcFee b WITH(NOLOCK)
				WHERE b.type = 4
				AND a.dcFeeID = b.ID
				AND b.dcProvinceID = LEFT(@ProvinceID,2)
				AND ((MinValue<=4 AND MaxValue>=4) OR (MinValue<=4 AND MaxValue=0))
				AND StartDate < GETDATE() AND EndDate > GETDATE()
		INSERT INTO caOrder (cpMainID,ProvinceID,ServiceType,PlaceWeek,PayMethod,UserNumber,
		OrderType,Accounts,Paid,Balance,LinkMan,Telephone,LinkRemark,Manageruserid,ActiveQuota,RemainQuota,JobNumber,CompanyName,MainOrderID,InvoiceCompany,dcFeeDetailID,NeedInvoice)
		VALUES(@cpMainID,@ProvinceID,6,4,@PayMethod,0,
		4,@Accounts,0,0,@LinkMan,@Telephone,'',@Manageruserid,0,0,0,@CompanyName,@MainOrderID,@InvoiceCompany,@dcFeeDetailsID,0)
		SET @NewOrderID = @@IDENTITY		
	END
	ELSE IF @GiftType = 9	--自动提交4周2/6图片 广告
	BEGIN
		--取原价和对应的资费ID
		SELECT TOP 1 @Accounts = b.Price * 4,					
					@dcFeeDetailsID = a.ID
				FROM dcFeeDetail a WITH(NOLOCK) ,dcFee b WITH(NOLOCK)
				WHERE b.type = 4
				AND a.dcFeeID = b.ID
				AND b.dcProvinceID = LEFT(@ProvinceID,2)
				AND ((MinValue<=4 AND MaxValue>=4) OR (MinValue<=4 AND MaxValue=0))
				AND StartDate < GETDATE() AND EndDate > GETDATE()
		INSERT INTO caOrder (cpMainID,ProvinceID,ServiceType,PlaceWeek,PayMethod,UserNumber,
		OrderType,Accounts,Paid,Balance,LinkMan,Telephone,LinkRemark,Manageruserid,ActiveQuota,RemainQuota,JobNumber,CompanyName,MainOrderID,InvoiceCompany,dcFeeDetailID,NeedInvoice)
		VALUES(@cpMainID,@ProvinceID,7,4,@PayMethod,0,
		4,@Accounts,0,0,@LinkMan,@Telephone,'',@Manageruserid,0,0,0,@CompanyName,@MainOrderID,@InvoiceCompany,@dcFeeDetailsID,0)
		SET @NewOrderID = @@IDENTITY		
	END
	ELSE IF @GiftType = 2 AND @MemberType=3	--自动提交50简历下载订单
	BEGIN
		--取原价和对应的资费ID
		SELECT TOP 1 @Accounts = b.Price * 50,					
					@dcFeeDetailsID = a.ID
				FROM dcFeeDetail a WITH(NOLOCK) ,dcFee b WITH(NOLOCK)
				WHERE b.type = 9
				AND a.dcFeeID = b.ID
				AND b.dcProvinceID = LEFT(@ProvinceID,2)
				AND ((MinValue<=50 AND MaxValue>=50) OR (MinValue<=50 AND MaxValue=0))
				AND StartDate < GETDATE() AND EndDate > GETDATE()
		IF @dcFeeDetailsID IS NULL
				SELECT TOP 1 @Accounts = Price * 50
				FROM dcFee  WITH(NOLOCK)
				WHERE type = 9
				AND dcProvinceID = LEFT(@ProvinceID,2)
				AND StartDate < GETDATE() AND EndDate > GETDATE()

		SELECT TOP 1 @MainOrderID = ID FROM CaOrder WITH(NOLOCK) WHERE cpMainID = @cpMainID AND OpenDate IS NOT NULL AND EndDate>GETDATE() AND OrderType = 8 ORDER BY EndDate DESC
		INSERT INTO caOrder (cpMainID,ProvinceID,ServiceType,PlaceWeek,PayMethod,UserNumber,
		OrderType,Accounts,Paid,Balance,LinkMan,Telephone,LinkRemark,Manageruserid,ActiveQuota,RemainQuota,JobNumber,CompanyName,MainOrderID,InvoiceCompany,dcFeeDetailID)
		VALUES(@cpMainID,@ProvinceID,null,null,@PayMethod,0,
		9,@Accounts,0,0,@LinkMan,@Telephone,'',@Manageruserid,50,50,0,@CompanyName,@MainOrderID,@InvoiceCompany,@dcFeeDetailsID)
		SET @NewOrderID = @@IDENTITY
	END
	ELSE IF @GiftType = 3 AND @MemberType=3	--自动提交100简历下载订单
	BEGIN
		--取原价和对应的资费ID
		SELECT TOP 1 @Accounts = b.Price * 100,					
					@dcFeeDetailsID = a.ID
				FROM dcFeeDetail a WITH(NOLOCK) ,dcFee b WITH(NOLOCK)
				WHERE b.type = 9
				AND a.dcFeeID = b.ID
				AND b.dcProvinceID = LEFT(@ProvinceID,2)
				AND ((MinValue<=100 AND MaxValue>=100) OR (MinValue<=100 AND MaxValue=0))
				AND StartDate < GETDATE() AND EndDate > GETDATE()
		IF @dcFeeDetailsID IS NULL
				SELECT TOP 1 @Accounts = Price * 100
				FROM dcFee  WITH(NOLOCK)
				WHERE type = 9
				AND dcProvinceID = LEFT(@ProvinceID,2)
				AND StartDate < GETDATE() AND EndDate > GETDATE()

		SELECT TOP 1 @MainOrderID = ID FROM CaOrder WITH(NOLOCK) WHERE cpMainID = @cpMainID AND OpenDate IS NOT NULL AND EndDate>GETDATE() AND OrderType = 8 ORDER BY EndDate DESC
		INSERT INTO caOrder (cpMainID,ProvinceID,ServiceType,PlaceWeek,PayMethod,UserNumber,
		OrderType,Accounts,Paid,Balance,LinkMan,Telephone,LinkRemark,Manageruserid,ActiveQuota,RemainQuota,JobNumber,CompanyName,MainOrderID,InvoiceCompany,dcFeeDetailID)
		VALUES(@cpMainID,@ProvinceID,null,null,@PayMethod,0,
		9,@Accounts,0,0,@LinkMan,@Telephone,'',@Manageruserid,100,100,0,@CompanyName,@MainOrderID,@InvoiceCompany,@dcFeeDetailsID)
		SET @NewOrderID = @@IDENTITY
	END
	ELSE IF @GiftType = 4 AND @MemberType=3	--自动提交200简历下载订单
	BEGIN
		--取原价和对应的资费ID
		SELECT TOP 1 @Accounts = b.Price * 200,					
					@dcFeeDetailsID = a.ID
				FROM dcFeeDetail a WITH(NOLOCK) ,dcFee b WITH(NOLOCK)
				WHERE b.type = 9
				AND a.dcFeeID = b.ID
				AND b.dcProvinceID = LEFT(@ProvinceID,2)
				AND ((MinValue<=50 AND MaxValue>=200) OR (MinValue<=200 AND MaxValue=0))
				AND StartDate < GETDATE() AND EndDate > GETDATE()
		IF @dcFeeDetailsID IS NULL
				SELECT TOP 1 @Accounts = Price * 200
				FROM dcFee  WITH(NOLOCK)
				WHERE type = 9
				AND dcProvinceID = LEFT(@ProvinceID,2)
				AND StartDate < GETDATE() AND EndDate > GETDATE()

		SELECT TOP 1 @MainOrderID = ID FROM CaOrder WITH(NOLOCK) WHERE cpMainID = @cpMainID AND OpenDate IS NOT NULL AND EndDate>GETDATE() AND OrderType = 8 ORDER BY EndDate DESC
		INSERT INTO caOrder (cpMainID,ProvinceID,ServiceType,PlaceWeek,PayMethod,UserNumber,
		OrderType,Accounts,Paid,Balance,LinkMan,Telephone,LinkRemark,Manageruserid,ActiveQuota,RemainQuota,JobNumber,CompanyName,MainOrderID,InvoiceCompany,dcFeeDetailID)
		VALUES(@cpMainID,@ProvinceID,null,null,@PayMethod,0,
		9,@Accounts,0,0,@LinkMan,@Telephone,'',@Manageruserid,200,200,0,@CompanyName,@MainOrderID,@InvoiceCompany,@dcFeeDetailsID)
		SET @NewOrderID = @@IDENTITY
	END
	ELSE IF @GiftType = 6	--自动提交2周固定位置订单
	BEGIN
		--取原价和对应的资费ID
		SELECT TOP 1 @Accounts = b.Price * 2,					
					@dcFeeDetailsID = a.ID
				FROM dcFeeDetail a WITH(NOLOCK) ,dcFee b WITH(NOLOCK)
				WHERE b.type = 7
				AND a.dcFeeID = b.ID
				AND b.dcProvinceID = LEFT(@ProvinceID,2)
				AND ((MinValue<=2 AND MaxValue>=2) OR (MinValue<=2 AND MaxValue=0))
				AND StartDate < GETDATE() AND EndDate > GETDATE()
		DECLARE @FixBeginDate SMALLDATETIME
		--取最后一个固定位置的订单
		SELECT TOP 1 @FixBeginDate=EndDate FROM caOrder WHERE cpMainID=@cpMainID AND OrderType=7 AND OpenDate IS NOT NULL AND EndDate>GETDATE() ORDER BY ID DESC
		SET @FixBeginDate=ISNULL(@FixBeginDate,GETDATE())

		INSERT INTO caOrder (cpMainID,ProvinceID,ServiceType,PlaceWeek,PayMethod,UserNumber,
		OrderType,Accounts,Paid,Balance,LinkMan,Telephone,LinkRemark,Manageruserid,ActiveQuota,RemainQuota,JobNumber,CompanyName,MainOrderID,InvoiceCompany,dcFeeDetailID,BeginDate,EndDate,OpenDate,OpenMan,OrderStatus)
		VALUES(@cpMainID,@ProvinceID,null,2,@PayMethod,0,
		7,@Accounts,0,0,@LinkMan,@Telephone,'',@Manageruserid,0,0,0,@CompanyName,@MainOrderID,@InvoiceCompany,@dcFeeDetailsID,@FixBeginDate,DATEADD(DAY,14,@FixBeginDate),GETDATE(),116,4)
		SET @NewOrderID = @@IDENTITY
	END
	ELSE IF @GiftType = 7	--自动提交2周职位置顶订单，职位默认取最新发布的，前台企业选择后再修改
	BEGIN
		--取原价和对应的资费ID
		SELECT TOP 1 @Accounts = b.Price * 2,					
					@dcFeeDetailsID = a.ID
				FROM dcFeeDetail a WITH(NOLOCK) ,dcFee b WITH(NOLOCK)
				WHERE b.type = 22
				AND a.dcFeeID = b.ID
				AND b.dcProvinceID = LEFT(@ProvinceID,2)
				AND ((MinValue<=2 AND MaxValue>=2) OR (MinValue<=2 AND MaxValue=0))
				AND StartDate < GETDATE() AND EndDate > GETDATE()
		DECLARE @JobID INT
		SELECT @JobID = ID FROM Job WITH(NOLOCK) WHERE Valid = 1  AND cpMainID= @cpMainID AND ID NOT IN(SELECT Balance FROM caOrder WITH(NOLOCK) WHERE OrderType=12 AND BeginDate>GETDATE() AND EndDate<GETDATE())
		IF @JobID >0
		BEGIN
			INSERT INTO caOrder (cpMainID,ProvinceID,ServiceType,PlaceWeek,PayMethod,UserNumber,
			OrderType,Accounts,Paid,Balance,LinkMan,Telephone,LinkRemark,Manageruserid,ActiveQuota,RemainQuota,JobNumber,CompanyName,MainOrderID,InvoiceCompany,dcFeeDetailID,NeedInvoice)
			VALUES(@cpMainID,@ProvinceID,null,2,@PayMethod,0,
			12,@Accounts,0,@JobID,@LinkMan,@Telephone,'',@Manageruserid,0,0,0,@CompanyName,@MainOrderID,@InvoiceCompany,@dcFeeDetailsID,0)
			SET @NewOrderID = @@IDENTITY
		END
	END
	ELSE IF @GiftType = 8	--自动提交2周职位刷新订单
	BEGIN
		--取原价和对应的资费ID
		SELECT TOP 1 @Accounts = b.Price * 2,					
					@dcFeeDetailsID = a.ID
				FROM dcFeeDetail a WITH(NOLOCK) ,dcFee b WITH(NOLOCK)
				WHERE b.type = 24
				AND a.dcFeeID = b.ID
				AND b.dcProvinceID = LEFT(@ProvinceID,2)
				AND ((MinValue<=2 AND MaxValue>=2) OR (MinValue<=2 AND MaxValue=0))
				AND StartDate < GETDATE() AND EndDate > GETDATE()
		DECLARE @RefreshBeginDate SMALLDATETIME
		--取最后一个固定位置的订单
		SELECT TOP 1 @RefreshBeginDate=EndDate FROM caOrder WHERE cpMainID=@cpMainID AND OrderType=13 AND OpenDate IS NOT NULL AND EndDate>GETDATE() ORDER BY ID DESC
		SET @RefreshBeginDate=ISNULL(@RefreshBeginDate,GETDATE())

		INSERT INTO caOrder (cpMainID,ProvinceID,ServiceType,PlaceWeek,PayMethod,UserNumber,
		OrderType,Accounts,Paid,Balance,LinkMan,Telephone,LinkRemark,Manageruserid,ActiveQuota,RemainQuota,JobNumber,CompanyName,MainOrderID,InvoiceCompany,dcFeeDetailID,BeginDate,EndDate,OpenDate,OpenMan,OrderStatus)
		VALUES(@cpMainID,@ProvinceID,null,2,@PayMethod,0,
		13,@Accounts,0,0,@LinkMan,@Telephone,'',@Manageruserid,0,0,0,@CompanyName,@MainOrderID,@InvoiceCompany,@dcFeeDetailsID,@RefreshBeginDate,DATEADD(DAY,14,@RefreshBeginDate),GETDATE(),116,4)
		SET @NewOrderID = @@IDENTITY
	END
	ELSE IF @GiftType = 10	--自动提交VIP订单  
	BEGIN		
		DECLARE @ActiveQuota INT
		DECLARE @JobNumber INT
		DECLARE @UserNumber INT

		--取本省份价格最便宜的季度套餐
		SELECT TOP 1 @dcFeeDetailsID = b.ID, 
		@Accounts = (a.PriceMonth * b.[Month]+b.ResumeNumber*a.PriceResume+JobNumber*a.PriceJob+UserNumber*a.PriceUser),
		@ActiveQuota = b.ResumeNumber,
		@JobNumber = b.JobNumber,
		@UserNumber = b.UserNumber 
		FROM dcVip a WITH(NOLOCK),dcVipDetail b WITH(NOLOCK) 
		WHERE a.id = b.dcVipId 
		AND dcProvinceid=@ProvinceID 
		AND b.[Month]=3 
		AND startDate<GETDATE() 
		AND enddate > GETDATE()
		ORDER BY Price

		INSERT INTO caOrder (cpMainID,ProvinceID,ServiceType,PlaceWeek,PayMethod,UserNumber,
		OrderType,Accounts,Paid,Balance,LinkMan,Telephone,LinkRemark,Manageruserid,ActiveQuota,RemainQuota,JobNumber,CompanyName,MainOrderID,InvoiceCompany,dcFeeDetailID,NeedInvoice)
		VALUES(@cpMainID,@ProvinceID,NULL,NULL,@PayMethod,@UserNumber,
		8,@Accounts,0,0,@LinkMan,@Telephone,'',@Manageruserid,@ActiveQuota,@ActiveQuota,@JobNumber,@CompanyName,@MainOrderID,@InvoiceCompany,@dcFeeDetailsID,0)
		SET @NewOrderID = @@IDENTITY
	END
	
	BEGIN TRY
      IF @GiftType<>12
      BEGIN
		--奖品类型：1、50职位并发  2、50份简历 3、100份简历 4、200份简历 5、4周六分之一图片 6、2周文字广告 7、2周职位置顶 
	--8、2周职位自动刷新  9、4周六分之二 10、Vip会员—季度
		DECLARE @GiftName VARCHAR(50)
		IF @GiftType =1 
		BEGIN
			SET @GiftName = '50职位并发'
		END
		ELSE IF @GiftType =2
		BEGIN
			SET @GiftName = '50份简历'
		END
		ELSE IF @GiftType =3
		BEGIN
			SET @GiftName = '100份简历'
		END
		ELSE IF @GiftType =4
		BEGIN
			SET @GiftName = '200份简历 '
		END
		ELSE IF @GiftType =5
		BEGIN
			SET @GiftName = '4周六分之一图片广告'
		END
		ELSE IF @GiftType =6
		BEGIN
			SET @GiftName = '2周文字广告'
		END
		ELSE IF @GiftType =7
		BEGIN
			SET @GiftName = '2周职位置顶'
		END
		ELSE IF @GiftType =8
		BEGIN
			SET @GiftName = '2周职位自动刷新'
		END
		ELSE IF @GiftType =9
		BEGIN
			SET @GiftName = '4周六分之二'
		END
		ELSE IF @GiftType =10
		BEGIN
			SET @GiftName = 'Vip会员—季度'
		END
			
		IF @Manageruserid IS NULL
		BEGIN	
			INSERT INTO rtxnotifylog
			SELECT STUFF((SELECT ','+LTRIM(x.ID) FROM Manageruser x WHERE ID IN (180,181,182) FOR XML PATH('')),1,1,'')
				,'中奖通知',@CompanyName+'('+LTRIM(STR(@cpMainID))+')中奖了，奖品为['+@GiftName+']，请及时处理http://115.182.8.38:81/yehgiiaovbjkaie871/cp/cpMainInfo.asp?id='+LTRIM(STR(@cpMainID))+'&code='+@Code,1,0,0,null,getdate()
		END
		ELSE
		BEGIN
			INSERT INTO rtxnotifylog
			SELECT @Manageruserid
				,'中奖通知',@CompanyName+'('+LTRIM(STR(@cpMainID))+')中奖了，奖品为['+@GiftName+']，请及时处理http://115.182.8.38:81/yehgiiaovbjkaie871/cp/cpMainInfo.asp?id='+LTRIM(STR(@cpMainID))+'&code='+@Code,1,0,0,null,getdate()
		END
		Update caOrder Set InvoiceConfirmDate=GetDate(),InvoiceConfirmMan=116,InvoiceAskDate=Null,NeedInvoice=0 Where ID=@NewOrderID
      END
	END TRY
	BEGIN CATCH
		
	END CATCH
	--更新LotteryCompany，保存订单号和中奖类型
	UPDATE LotteryCompany SET GiftOrderID=@NewOrderID,[type]=@GiftType WHERE ID= @LotteryID
	RETURN @GiftType
END
GO
/****** Object:  StoredProcedure [dbo].[ccLotteryCompanyUpdate2017]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--创建人：Lucifer
--创建时间：2017-10-9
--企业17周年抽奖
--奖项内容：		VIP会员	        普通会员
--50职位并发		20%		0%
--50份简历		20%		0%
--2周六分之一图片	5%		10%
--2周知名企业		15%		15%
--2周职位置顶		5%		5%
--100次职位刷新 	20%		15%
--2周六分之二图片	5%		10%
--满1000-50优惠券       10%              45%
--蓝皮书          	特殊
--记事本		特殊
--热水壶                特殊
--特殊奖项时间定为：蓝皮书：山东（10本）25号抽6本，28号抽4本，记事本：山东（35本）每天抽5本，电水壶：山东（两个）其他地区合计（两个）25号抽山东1个，其他合计1个。28号抽山东1个，其他合计1个
--保险公司，培训公司，代理招聘类公司仅能够中奖的范围：职位数、简历数、自动刷新。其他内容不允许抽中。需要在抽选中排除。
--50职位并发		30%
--50份简历		20%
--100次自动刷新 	50%
--奖品类型：1、50职位并发  2、50份简历 3、记事本 4、200份简历 5、2周六分之一图片 6、2周知名企业 7、2周职位置顶  8、100次职位刷新  9、2周六分之二 10、蓝皮书 11、满1000-50优惠券 12、电热水壶 99、没中奖
--lucifer 2018-2-23
CREATE PROCEDURE [dbo].[ccLotteryCompanyUpdate2017] 
(
	@caMainID INT 
)
AS
BEGIN
	DECLARE @LotteryID INT
	DECLARE @cpMainID INT
	SELECT TOP 1 @LotteryID = ID,@cpMainID = cpMainID FROM LotteryCompany WITH(NOLOCK) WHERE Used = 0 AND cpMainID = (select cpMainID FROM caMain WITH(NOLOCK) WHERE ID = @caMainID AND AccountType=1) 

	IF @LotteryID IS NULL	
		RETURN -1 --没有抽奖次数

	UPDATE LotteryCompany SET Used = 1,LotteryDate = GETDATE() WHERE ID = @LotteryID --更新状态 防止重复抽奖

	------------------****************生成抽奖结果****************-----------------
	DECLARE @IsAgent TINYINT --是否是保险公司
	DECLARE @IsVip TINYINT --是否是VIP
	DECLARE @ProvinceId SMALLINT
	DECLARE @Name NVARCHAR(200)
	SELECT TOP 1 @IsAgent = IsAgent, @ProvinceId = dcProvinceId, @Name = Name, @IsVip = (CASE MemberType WHEN 3 THEN 1 ELSE 0 END) FROM cpMain WITH(NOLOCK) WHERE ID = @cpMainID
	IF @IsAgent = 0
	BEGIN
		IF @Name LIKE '%人寿%' OR @Name LIKE '%保险%' 
			SET @IsAgent = 1
	END
	
	DECLARE @GiftNo INT, @GiftType INT, @LoopCount INT
	SELECT @GiftNo = CAST((RAND()*999+1) AS INT) --生成抽奖的数字
	SELECT @GiftType = dbo.GetLotteryGiftType(@IsAgent, @GiftNo, @IsVip)
	SET @LoopCount = 0
	WHILE EXISTS(SELECT 'X' FROM LotteryCompany WHERE [Type] = @GiftType AND cpMainID = @cpMainID) OR @LoopCount < 1000
	BEGIN
		SELECT @GiftNo = CAST((RAND()*999 + 1) AS INT) --生成抽奖的数字
		SELECT @GiftType = dbo.GetLotteryGiftType(@IsAgent, @GiftNo, @IsVip)
		SET @LoopCount = @LoopCount + 1
	END

	--特殊奖项时间定为：蓝皮书：山东（10本）25号抽6本，28号抽4本，记事本：山东（35本）每天抽5本，电水壶：山东（两个）其他地区合计（两个）25号抽山东1个，其他合计1个。28号抽山东1个，其他合计1个
	DECLARE @Today VARCHAR(4)
	SELECT @Today = RIGHT(CONVERT(VARCHAR(8), GETDATE(), 112), 4)
	IF @IsVip = 1 AND @IsAgent = 0
	BEGIN
		IF @ProvinceId = 32 AND NOT EXISTS(SELECT 'X' FROM maindb..LotteryCompany a, cpMain b WHERE a.cpMainID = b.ID AND [type] = 3 AND RIGHT(CONVERT(VARCHAR(8), LotteryDate, 112), 4) = @Today AND b.dcProvinceID = 32 AND a.cpMainID IN (SELECT cpMainID FROM caMain WHERE ID =@caMainID))
		BEGIN
			IF (SELECT COUNT(1) FROM maindb..LotteryCompany a, cpMain b WHERE a.cpMainID = b.ID AND [type] = 3 AND RIGHT(CONVERT(VARCHAR(8), LotteryDate, 112), 4) = @Today AND b.dcProvinceID = 32)<5
			SELECT @GiftType = 3
		END

		ELSE IF @Today = '0205'
		BEGIN
			IF @ProvinceId = 32
			BEGIN
				IF NOT EXISTS(SELECT 'X' FROM maindb..LotteryCompany a, cpMain b WHERE a.cpMainID = b.ID AND [type] = 10 AND RIGHT(CONVERT(VARCHAR(8), LotteryDate, 112), 4) = @Today AND b.dcProvinceID = 32 AND a.cpMainID IN (SELECT cpMainID FROM caMain WHERE ID =@caMainID))
				BEGIN
					IF (SELECT COUNT(1) FROM maindb..LotteryCompany a, cpMain b WHERE a.cpMainID = b.ID AND [type] = 10 AND RIGHT(CONVERT(VARCHAR(8), LotteryDate, 112), 4) = @Today AND b.dcProvinceID = 32)<6
						SELECT @GiftType = 10
				END
				ELSE IF NOT EXISTS(SELECT 'X' FROM maindb..LotteryCompany a, cpMain b WHERE a.cpMainID = b.ID AND [type] = 12 AND RIGHT(CONVERT(VARCHAR(8), LotteryDate, 112), 4) = @Today AND b.dcProvinceID = 32)
					SELECT @GiftType = 12
			END
			ELSE
			BEGIN
				 IF NOT EXISTS(SELECT 'X' FROM maindb..LotteryCompany a, cpMain b WHERE a.cpMainID = b.ID AND [type] = 12 AND RIGHT(CONVERT(VARCHAR(8), LotteryDate, 112), 4) = @Today AND b.dcProvinceID <> 32)
					SELECT @GiftType = 12
			END
		END

		ELSE IF @Today = '1020'
		BEGIN
			IF @ProvinceId = 32
			BEGIN
				IF NOT EXISTS(SELECT 'X' FROM maindb..LotteryCompany a, cpMain b WHERE a.cpMainID = b.ID AND [type] = 10 AND RIGHT(CONVERT(VARCHAR(8), LotteryDate, 112), 4) = @Today AND b.dcProvinceID = 32 AND a.cpMainID IN (SELECT cpMainID FROM caMain WHERE ID =@caMainID))
				BEGIN
					IF (SELECT COUNT(1) FROM maindb..LotteryCompany a, cpMain b WHERE a.cpMainID = b.ID AND [type] = 10 AND RIGHT(CONVERT(VARCHAR(8), LotteryDate, 112), 4) = @Today AND b.dcProvinceID = 32)<4
						SELECT @GiftType = 10
				END
				ELSE IF NOT EXISTS(SELECT 'X' FROM maindb..LotteryCompany a, cpMain b WHERE a.cpMainID = b.ID AND [type] = 12 AND RIGHT(CONVERT(VARCHAR(8), LotteryDate, 112), 4) = @Today AND b.dcProvinceID = 32)
					SELECT @GiftType = 12
			END
ELSE
		BEGIN
				 IF NOT EXISTS(SELECT 'X' FROM maindb..LotteryCompany a, cpMain b WHERE a.cpMainID = b.ID AND [type] = 12 AND RIGHT(CONVERT(VARCHAR(8), LotteryDate, 112), 4) = @Today AND b.dcProvinceID <> 32)
					SELECT @GiftType = 12
		END
		END
		
	END

--	IF @IsVip = 1
--	BEGIN
--		IF (SELECT COUNT(1) FROM LotteryCompany WHERE cpMainID=@cpMainID AND caOrderID IS NULL) >= 2
--			SELECT @GiftType = 99 		
--	END
--	ELSE
--	BEGIN
--		IF (SELECT COUNT(1) FROM LotteryCompany WHERE cpMainID=@cpMainID AND caOrderID IS NULL) >= 1
--			SELECT @GiftType = 99
--	END

	--每个企业最多中奖3次
	IF (SELECT COUNT(1) FROM maindb..LotteryCompany WHERE cpMainID = @cpMainID AND LotteryDate IS NOT NULL) >= 4
		SELECT @GiftType = 99 

	PRINT @GiftType
	/*---------****************自动提交订单**************-------------*/
	DECLARE @PayMethod INT	--取上次订单的付款方式
	DECLARE @LinkMan NVARCHAR(50) 
	DECLARE @Telephone NVARCHAR(50)
	DECLARE @CompanyName NVARCHAR(50)
	DECLARE @Accounts NUMERIC(18,2)	
	DECLARE @dcFeeDetailsID INT
	DECLARE @Manageruserid INT
	DECLARE @MemberType INT
	DECLARE @MainOrderID INT
	DECLARE @InvoiceCompany NVARCHAR(50)
	DECLARE @Hour INT
	DECLARE @MainEndDate SMALLDATETIME
	DECLARE @Minute INT
	DECLARE @Code VARCHAR(10)
	DECLARE @RegDate DATETIME
	SELECT TOP 1 
		@ProvinceID = b.dcProvinceID,
		@PayMethod = c.PayMethod,
		@MemberType = MemberType,
		@LinkMan = LinkMan,
		@Telephone = Telephone,
		@CompanyName = CompanyName,
		@InvoiceCompany = InvoiceCompany,
		@Manageruserid = ConsultantID,
		@RegDate = RegDate
	FROM cpMain b ,caOrder c
	WHERE b.id = c.cpmainid
	AND c.cpMainID = @cpMainID
	AND Paid > 0
	ORDER BY c.ID DESC

	IF @CompanyName IS NULL
	BEGIN
		SELECT TOP 1 
			@ProvinceID = dcProvinceID,
			@PayMethod = 1,
			@MemberType = MemberType,
			@CompanyName = [Name],
			@InvoiceCompany = 4,
			@Manageruserid = ConsultantID,
			@RegDate = RegDate
		FROM cpMain
		WHERE ID = @cpMainID
	END

	SELECT TOP 1
		@LinkMan = LinkMan,
		@Telephone = Mobile
	FROM LotteryCompany WHERE cpMainID = @cpMainID AND LinkMan IS NOT NULL
	
	SELECT @Hour = DATEPART(HOUR,@RegDate)
    SELECT @Minute = DATEPART(Minute,@RegDate)
    
    SET @Code = CONVERT(VARCHAR(10),@Hour*100+@Minute)
         
    SET @PayMethod = 7 
	DECLARE	@NewOrderID INT
	IF @GiftType = 1 AND @MemberType = 3	--自动提交50个职位并发数的订单
	BEGIN			
		--取原价和对应的资费ID
		SELECT TOP 1 @Accounts = b.Price * 50,					
					@dcFeeDetailsID = a.ID
				FROM dcFeeDetail a WITH(NOLOCK) ,dcFee b WITH(NOLOCK)
				WHERE b.type = 10
				AND a.dcFeeID = b.ID
				AND b.dcProvinceID = LEFT(@ProvinceID,2)
				AND ((MinValue <= 50 AND MaxValue >= 50) OR (MinValue <= 50 AND MaxValue = 0))
				AND StartDate < GETDATE() AND EndDate > GETDATE()

		SELECT TOP 1 @MainOrderID = ID, @MainEndDate = EndDate FROM CaOrder WITH(NOLOCK) WHERE cpMainID = @cpMainID AND OpenDate IS NOT NULL AND EndDate>GETDATE() AND OrderType = 8 ORDER BY EndDate DESC	
		INSERT INTO caOrder (cpMainID,ProvinceID,ServiceType,PlaceWeek,PayMethod,UserNumber,
		OrderType,Accounts,Paid,Balance,LinkMan,Telephone,LinkRemark,Manageruserid,ActiveQuota,RemainQuota,JobNumber,CompanyName,MainOrderID,InvoiceCompany,dcFeeDetailID,BeginDate,EndDate,OpenDate,OpenMan,OrderStatus)
		VALUES(@cpMainID,@ProvinceID,NULL,NULL,@PayMethod,0,
		10,@Accounts,0,0,@LinkMan,@Telephone,'',@Manageruserid,0,0,50,@CompanyName,@MainOrderID,@InvoiceCompany,@dcFeeDetailsID,GETDATE(),@MainEndDate,GETDATE(),116,4)
		SET @NewOrderID = @@IDENTITY
	END
	ELSE IF @GiftType = 5	--自动提交2周1/6图片 广告
	BEGIN
		--取原价和对应的资费ID
		SELECT TOP 1 @Accounts = b.Price * 4,					
					@dcFeeDetailsID = a.ID
				FROM dcFeeDetail a WITH(NOLOCK) ,dcFee b WITH(NOLOCK)
				WHERE b.type = 4
				AND a.dcFeeID = b.ID
				AND b.dcProvinceID = LEFT(@ProvinceID,2)
				AND ((MinValue<=4 AND MaxValue>=4) OR (MinValue<=4 AND MaxValue=0))
				AND StartDate < GETDATE() AND EndDate > GETDATE()
		INSERT INTO caOrder (cpMainID,ProvinceID,ServiceType,PlaceWeek,PayMethod,UserNumber,
		OrderType,Accounts,Paid,Balance,LinkMan,Telephone,LinkRemark,Manageruserid,ActiveQuota,RemainQuota,JobNumber,CompanyName,MainOrderID,InvoiceCompany,dcFeeDetailID,NeedInvoice)
		VALUES(@cpMainID,@ProvinceID,6,2,@PayMethod,0,
		4,@Accounts,0,0,@LinkMan,@Telephone,'',@Manageruserid,0,0,0,@CompanyName,@MainOrderID,@InvoiceCompany,@dcFeeDetailsID,0)
		SET @NewOrderID = @@IDENTITY		
	END
	ELSE IF @GiftType = 9	--自动提交2周2/6图片 广告
	BEGIN
		--取原价和对应的资费ID
		SELECT TOP 1 @Accounts = b.Price * 4,					
					@dcFeeDetailsID = a.ID
				FROM dcFeeDetail a WITH(NOLOCK) ,dcFee b WITH(NOLOCK)
				WHERE b.type = 4
				AND a.dcFeeID = b.ID
				AND b.dcProvinceID = LEFT(@ProvinceID,2)
				AND ((MinValue<=4 AND MaxValue>=4) OR (MinValue<=4 AND MaxValue=0))
				AND StartDate < GETDATE() AND EndDate > GETDATE()
		INSERT INTO caOrder (cpMainID,ProvinceID,ServiceType,PlaceWeek,PayMethod,UserNumber,
		OrderType,Accounts,Paid,Balance,LinkMan,Telephone,LinkRemark,Manageruserid,ActiveQuota,RemainQuota,JobNumber,CompanyName,MainOrderID,InvoiceCompany,dcFeeDetailID,NeedInvoice)
		VALUES(@cpMainID,@ProvinceID,7,2,@PayMethod,0,
		4,@Accounts,0,0,@LinkMan,@Telephone,'',@Manageruserid,0,0,0,@CompanyName,@MainOrderID,@InvoiceCompany,@dcFeeDetailsID,0)
		SET @NewOrderID = @@IDENTITY		
	END
	ELSE IF @GiftType = 2 AND @MemberType = 3	--自动提交50简历下载订单
	BEGIN
		--取原价和对应的资费ID
		SELECT TOP 1 @Accounts = b.Price * 50,					
					@dcFeeDetailsID = a.ID
				FROM dcFeeDetail a WITH(NOLOCK) ,dcFee b WITH(NOLOCK)
				WHERE b.type = 9
				AND a.dcFeeID = b.ID
				AND b.dcProvinceID = LEFT(@ProvinceID,2)
				AND ((MinValue<=50 AND MaxValue>=50) OR (MinValue<=50 AND MaxValue=0))
				AND StartDate < GETDATE() AND EndDate > GETDATE()
		IF @dcFeeDetailsID IS NULL
				SELECT TOP 1 @Accounts = Price * 50
				FROM dcFee  WITH(NOLOCK)
				WHERE type = 9
				AND dcProvinceID = LEFT(@ProvinceID,2)
				AND StartDate < GETDATE() AND EndDate > GETDATE()

		SELECT TOP 1 @MainOrderID = ID FROM CaOrder WITH(NOLOCK) WHERE cpMainID = @cpMainID AND OpenDate IS NOT NULL AND EndDate>GETDATE() AND OrderType = 8 ORDER BY EndDate DESC
		INSERT INTO caOrder (cpMainID,ProvinceID,ServiceType,PlaceWeek,PayMethod,UserNumber,
		OrderType,Accounts,Paid,Balance,LinkMan,Telephone,LinkRemark,Manageruserid,ActiveQuota,RemainQuota,JobNumber,CompanyName,MainOrderID,InvoiceCompany,dcFeeDetailID)
		VALUES(@cpMainID,@ProvinceID,null,null,@PayMethod,0,
		9,@Accounts,0,0,@LinkMan,@Telephone,'',@Manageruserid,50,50,0,@CompanyName,@MainOrderID,@InvoiceCompany,@dcFeeDetailsID)
		SET @NewOrderID = @@IDENTITY
	END
	--ELSE IF @GiftType = 3 AND @MemberType = 3	--自动提交100简历下载订单
	--BEGIN
	--	--取原价和对应的资费ID
	--	SELECT TOP 1 @Accounts = b.Price * 100,					
	--				@dcFeeDetailsID = a.ID
	--			FROM dcFeeDetail a WITH(NOLOCK) ,dcFee b WITH(NOLOCK)
	--			WHERE b.type = 9
	--			AND a.dcFeeID = b.ID
	--			AND b.dcProvinceID = LEFT(@ProvinceID,2)
	--			AND ((MinValue<=100 AND MaxValue>=100) OR (MinValue<=100 AND MaxValue=0))
	--			AND StartDate < GETDATE() AND EndDate > GETDATE()
	--	IF @dcFeeDetailsID IS NULL
	--			SELECT TOP 1 @Accounts = Price * 100
	--			FROM dcFee  WITH(NOLOCK)
	--			WHERE type = 9
	--			AND dcProvinceID = LEFT(@ProvinceID,2)
	--			AND StartDate < GETDATE() AND EndDate > GETDATE()

	--	SELECT TOP 1 @MainOrderID = ID FROM CaOrder WITH(NOLOCK) WHERE cpMainID = @cpMainID AND OpenDate IS NOT NULL AND EndDate>GETDATE() AND OrderType = 8 ORDER BY EndDate DESC
	--	INSERT INTO caOrder (cpMainID,ProvinceID,ServiceType,PlaceWeek,PayMethod,UserNumber,
	--	OrderType,Accounts,Paid,Balance,LinkMan,Telephone,LinkRemark,Manageruserid,ActiveQuota,RemainQuota,JobNumber,CompanyName,MainOrderID,InvoiceCompany,dcFeeDetailID)
	--	VALUES(@cpMainID,@ProvinceID,null,null,@PayMethod,0,
	--	9,@Accounts,0,0,@LinkMan,@Telephone,'',@Manageruserid,100,100,0,@CompanyName,@MainOrderID,@InvoiceCompany,@dcFeeDetailsID)
	--	SET @NewOrderID = @@IDENTITY
	--END
	ELSE IF @GiftType = 4 AND @MemberType = 3	--自动提交200简历下载订单
	BEGIN
		--取原价和对应的资费ID
		SELECT TOP 1 @Accounts = b.Price * 200,					
					@dcFeeDetailsID = a.ID
				FROM dcFeeDetail a WITH(NOLOCK) ,dcFee b WITH(NOLOCK)
				WHERE b.type = 9
				AND a.dcFeeID = b.ID
				AND b.dcProvinceID = LEFT(@ProvinceID,2)
				AND ((MinValue<=50 AND MaxValue>=200) OR (MinValue<=200 AND MaxValue=0))
				AND StartDate < GETDATE() AND EndDate > GETDATE()
		IF @dcFeeDetailsID IS NULL
				SELECT TOP 1 @Accounts = Price * 200
				FROM dcFee  WITH(NOLOCK)
				WHERE type = 9
				AND dcProvinceID = LEFT(@ProvinceID,2)
				AND StartDate < GETDATE() AND EndDate > GETDATE()

		SELECT TOP 1 @MainOrderID = ID FROM CaOrder WITH(NOLOCK) WHERE cpMainID = @cpMainID AND OpenDate IS NOT NULL AND EndDate>GETDATE() AND OrderType = 8 ORDER BY EndDate DESC
		INSERT INTO caOrder (cpMainID,ProvinceID,ServiceType,PlaceWeek,PayMethod,UserNumber,
		OrderType,Accounts,Paid,Balance,LinkMan,Telephone,LinkRemark,Manageruserid,ActiveQuota,RemainQuota,JobNumber,CompanyName,MainOrderID,InvoiceCompany,dcFeeDetailID)
		VALUES(@cpMainID,@ProvinceID,null,null,@PayMethod,0,
		9,@Accounts,0,0,@LinkMan,@Telephone,'',@Manageruserid,200,200,0,@CompanyName,@MainOrderID,@InvoiceCompany,@dcFeeDetailsID)
		SET @NewOrderID = @@IDENTITY
	END
	ELSE IF @GiftType = 6	--自动提交2周知名企业
	BEGIN
		--取原价和对应的资费ID
		SELECT TOP 1 @Accounts = b.Price * 2,					
					@dcFeeDetailsID = a.ID
				FROM dcFeeDetail a WITH(NOLOCK) ,dcFee b WITH(NOLOCK)
				WHERE b.type = 7
				AND a.dcFeeID = b.ID
				AND b.dcProvinceID = LEFT(@ProvinceID,2)
				AND ((MinValue<=2 AND MaxValue>=2) OR (MinValue<=2 AND MaxValue=0))
				AND StartDate < GETDATE() AND EndDate > GETDATE()
		DECLARE @FixBeginDate SMALLDATETIME
		--取最后一个固定位置的订单
		SELECT TOP 1 @FixBeginDate=EndDate FROM caOrder WHERE cpMainID=@cpMainID AND OrderType=7 AND OpenDate IS NOT NULL AND EndDate>GETDATE() ORDER BY ID DESC
		SET @FixBeginDate=ISNULL(@FixBeginDate,GETDATE())

		INSERT INTO caOrder (cpMainID,ProvinceID,ServiceType,PlaceWeek,PayMethod,UserNumber,
		OrderType,Accounts,Paid,Balance,LinkMan,Telephone,LinkRemark,Manageruserid,ActiveQuota,RemainQuota,JobNumber,CompanyName,MainOrderID,InvoiceCompany,dcFeeDetailID,BeginDate,EndDate,OpenDate,OpenMan,OrderStatus)
		VALUES(@cpMainID,@ProvinceID,null,2,@PayMethod,0,
		7,@Accounts,0,0,@LinkMan,@Telephone,'',@Manageruserid,0,0,0,@CompanyName,@MainOrderID,@InvoiceCompany,@dcFeeDetailsID,@FixBeginDate,DATEADD(DAY,14,@FixBeginDate),GETDATE(),116,4)
		SET @NewOrderID = @@IDENTITY
	END
	ELSE IF @GiftType = 7	--自动提交2周职位置顶订单，职位默认取最新发布的，前台企业选择后再修改
	BEGIN
		--取原价和对应的资费ID
		SELECT TOP 1 @Accounts = b.Price * 2,					
					@dcFeeDetailsID = a.ID
				FROM dcFeeDetail a WITH(NOLOCK) ,dcFee b WITH(NOLOCK)
				WHERE b.type = 22
				AND a.dcFeeID = b.ID
				AND b.dcProvinceID = LEFT(@ProvinceID,2)
				AND ((MinValue<=2 AND MaxValue>=2) OR (MinValue<=2 AND MaxValue=0))
				AND StartDate < GETDATE() AND EndDate > GETDATE()
		DECLARE @JobID INT
		SELECT @JobID = ID FROM Job WITH(NOLOCK) WHERE Valid = 1  AND cpMainID= @cpMainID AND ID NOT IN(SELECT Balance FROM caOrder WITH(NOLOCK) WHERE OrderType=12 AND BeginDate>GETDATE() AND EndDate<GETDATE())
		IF @JobID >0
		BEGIN
			INSERT INTO caOrder (cpMainID,ProvinceID,ServiceType,PlaceWeek,PayMethod,UserNumber,
			OrderType,Accounts,Paid,Balance,LinkMan,Telephone,LinkRemark,Manageruserid,ActiveQuota,RemainQuota,JobNumber,CompanyName,MainOrderID,InvoiceCompany,dcFeeDetailID,NeedInvoice)
			VALUES(@cpMainID,@ProvinceID,null,2,@PayMethod,0,
			12,@Accounts,0,@JobID,@LinkMan,@Telephone,'',@Manageruserid,0,0,0,@CompanyName,@MainOrderID,@InvoiceCompany,@dcFeeDetailsID,0)
			SET @NewOrderID = @@IDENTITY
		END
	END
	ELSE IF @GiftType = 8	--100次职位刷新
	BEGIN
		--取原价和对应的资费ID
		SELECT TOP 1 @Accounts = b.Price * 100,					
					@dcFeeDetailsID = a.ID
				FROM dcFeeDetail a WITH(NOLOCK) ,dcFee b WITH(NOLOCK)
				WHERE b.type = 15
				AND a.dcFeeID = b.ID
				AND b.dcProvinceID = LEFT(@ProvinceID,2)
				AND StartDate < GETDATE() AND EndDate > GETDATE()
		DECLARE @RefreshBeginDate SMALLDATETIME
		--取最后一个固定位置的订单
		SELECT TOP 1 @RefreshBeginDate=EndDate FROM caOrder WHERE cpMainID=@cpMainID AND OrderType=15 AND OpenDate IS NOT NULL AND EndDate>GETDATE() ORDER BY ID DESC
		SET @RefreshBeginDate=ISNULL(@RefreshBeginDate,GETDATE())

		INSERT INTO caOrder (cpMainID,ProvinceID,ServiceType,PayMethod,
		OrderType,Accounts,Paid,Balance,LinkMan,Telephone,LinkRemark,Manageruserid,ActiveQuota,RemainQuota,JobNumber,CompanyName,MainOrderID,InvoiceCompany,dcFeeDetailID,jobRefreshQuota,remainJobRefreshQuota,OrderStatus)
		VALUES(@cpMainID,@ProvinceID,null,@PayMethod,
		15,@Accounts,0,0,@LinkMan,@Telephone,'',@Manageruserid,0,0,0,@CompanyName,@MainOrderID,@InvoiceCompany,@dcFeeDetailsID,100,100,0)
		SET @NewOrderID = @@IDENTITY
	END
	--ELSE IF @GiftType = 10	--自动提交VIP订单  
	--BEGIN		
	--	DECLARE @ActiveQuota INT
	--	DECLARE @JobNumber INT
	--	DECLARE @UserNumber INT

	--	--取本省份价格最便宜的季度套餐
	--	SELECT TOP 1 @dcFeeDetailsID = b.ID, 
	--	@Accounts = (a.PriceMonth * b.[Month]+b.ResumeNumber*a.PriceResume+JobNumber*a.PriceJob+UserNumber*a.PriceUser),
	--	@ActiveQuota = b.ResumeNumber,
	--	@JobNumber = b.JobNumber,
	--	@UserNumber = b.UserNumber 
	--	FROM dcVip a WITH(NOLOCK),dcVipDetail b WITH(NOLOCK) 
	--	WHERE a.id = b.dcVipId 
	--	AND dcProvinceid=@ProvinceID 
	--	AND b.[Month]=3 
	--	AND startDate<GETDATE() 
	--	AND enddate > GETDATE()
	--	ORDER BY Price

	--	INSERT INTO caOrder (cpMainID,ProvinceID,ServiceType,PlaceWeek,PayMethod,UserNumber,
	--	OrderType,Accounts,Paid,Balance,LinkMan,Telephone,LinkRemark,Manageruserid,ActiveQuota,RemainQuota,JobNumber,CompanyName,MainOrderID,InvoiceCompany,dcFeeDetailID,NeedInvoice)
	--	VALUES(@cpMainID,@ProvinceID,NULL,NULL,@PayMethod,@UserNumber,
	--	8,@Accounts,0,0,@LinkMan,@Telephone,'',@Manageruserid,@ActiveQuota,@ActiveQuota,@JobNumber,@CompanyName,@MainOrderID,@InvoiceCompany,@dcFeeDetailsID,0)
	--	SET @NewOrderID = @@IDENTITY
	--END
	
	BEGIN TRY
		IF @GiftType <> 99
		BEGIN
			DECLARE @GiftName VARCHAR(50)
			IF @GiftType = 1 
			BEGIN
				SET @GiftName = '50职位并发'
			END
			ELSE IF @GiftType = 2
			BEGIN
				SET @GiftName = '50份简历'
			END
			ELSE IF @GiftType = 3
			BEGIN
				SET @GiftName = '记事本'
			END
			ELSE IF @GiftType = 4
			BEGIN
				SET @GiftName = '200份简历 '
			END
			ELSE IF @GiftType = 5
			BEGIN
				SET @GiftName = '2周六分之一图片广告'
			END
			ELSE IF @GiftType = 6
			BEGIN
				SET @GiftName = '2周知名企业'
			END
			ELSE IF @GiftType = 7
			BEGIN
				SET @GiftName = '2周职位置顶'
			END
			ELSE IF @GiftType = 8
			BEGIN
				SET @GiftName = '100次职位刷新'
			END
			ELSE IF @GiftType = 9
			BEGIN
				SET @GiftName = '2周六分之二'
			END
			ELSE IF @GiftType = 10
			BEGIN
				SET @GiftName = '蓝皮书'
			END
			ELSE IF @GiftType = 11
			BEGIN
				SET @GiftName = '满1000-50优惠券'
			END
			ELSE IF @GiftType = 12
			BEGIN
				SET @GiftName = '电热水壶'
			END
				
			IF @Manageruserid IS NULL
			BEGIN	
				INSERT INTO rtxnotifylog
				SELECT STUFF((SELECT ','+LTRIM(x.ID) FROM Manageruser x WHERE ID IN (180,182) FOR XML PATH('')),1,1,'')
					,'中奖通知',@CompanyName+'('+LTRIM(STR(@cpMainID))+')中奖了，奖品为[' + @GiftName + ']，请及时处理http://sysback.51rc.com/yehgiiaovbjkaie871/cp/cpMainInfo.asp?id='+LTRIM(STR(@cpMainID))+'&code=' + @Code,1,0,0,null,getdate()
			END
			ELSE
			BEGIN
				INSERT INTO rtxnotifylog
				SELECT @Manageruserid
					,'中奖通知',@CompanyName+'('+LTRIM(STR(@cpMainID))+')中奖了，奖品为[' + @GiftName + ']，请及时处理http://sysback.51rc.com/yehgiiaovbjkaie871/cp/cpMainInfo.asp?id='+LTRIM(STR(@cpMainID))+'&code=' + @Code,1,0,0,null,getdate()
			END
			Update caOrder Set InvoiceConfirmDate=GetDate(),InvoiceConfirmMan=116,InvoiceAskDate=Null,NeedInvoice=0 Where ID=@NewOrderID
		END
	END TRY
	BEGIN CATCH
		
	END CATCH
	--更新LotteryCompany，保存订单号和中奖类型
	UPDATE LotteryCompany SET GiftOrderID = @NewOrderID,[type] = @GiftType WHERE ID= @LotteryID
	RETURN @GiftType
END
GO
/****** Object:  StoredProcedure [dbo].[ccManagerLogByIpSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*********************
SEAN 2014-10-29
**********************/
CREATE PROCEDURE [dbo].[ccManagerLogByIpSelect]
(
	@Ip VARCHAR(15)
)
AS
--INSERT INTO procLog SELECT 'ccManagerLogByIpSelect', '', GETDATE()
BEGIN
	SELECT * FROM ManagerLog WITH(NOLOCK) WHERE LoginDate > GETDATE() - 0.1 AND ip = @IP
END

GO
/****** Object:  StoredProcedure [dbo].[ccManagerUserByIdSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/**********************8
sean 2014-10-29
***********************/
CREATE PROCEDURE [dbo].[ccManagerUserByIdSelect]
(
	@ID INT
)
AS
--INSERT INTO procLog SELECT 'ccManagerUserByIdSelect', '', GETDATE()
BEGIN
	SELECT ID,Name ShowName,ID ShowID, Name UserName
	FROM Manageruser WITH(NOLOCK)
	WHERE ID = @ID
END


GO
/****** Object:  StoredProcedure [dbo].[ccManagerUserIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.30
--创建人：Nick
--说明：//得到客服id
--#####################################################
CREATE PROCEDURE [dbo].[ccManagerUserIDSelect]
AS
BEGIN
	SELECT id FROM ManagerUser WITH(NOLOCK) WHERE Type=5 AND (Status=1 OR Status=2)
END
GO
/****** Object:  StoredProcedure [dbo].[ccManagerUserSuperiorByID]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.30
--创建人：Nick
--说明：得到招聘顾问上级的ID
--#####################################################
CREATE PROCEDURE [dbo].[ccManagerUserSuperiorByID]
(
	@ID INT
)
AS
BEGIN TRY
	SELECT Superior FROM  ManagerUser WITH(NOLOCK) WHERE ID = @ID
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[ccMessageC2pCountSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--Lambo 20101122
--查询单位在两个月内留言的数量
--用户简历显示页面，单位给求职者浏览，普通用户两个月内只能发100个留言
CREATE PROCEDURE [dbo].[ccMessageC2pCountSelect]
(
	@cpMainID INT
)
AS
BEGIN
	DECLARE @MessageCount INT 
	SELECT @MessageCount=COUNT(*) FROM exMessageC2P WITH(NOLOCK) 
	WHERE caMainID in  (SELECT ID FROM caMain WITH(NOLOCK) WHERE cpMainID = @cpMainID)
	AND AddDate >=DateAdd(Month,-2,GETDATE())
	------PRINT @MessageCount
	RETURN @MessageCount
END














GO
/****** Object:  StoredProcedure [dbo].[ccNVexMessageLogSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ccNVexMessageLogSelect]
(
	@paMainID INT,
	@caMainID INT
)
AS
BEGIN
	SELECT * FROM (
		SELECT cvMainID,ID,addDate,Message,1 IsCompany,IsViewed FROM exMessageC2p WITH(NOLOCK)
		WHERE cvMainID IN(SELECT ID FROM cvMain WITH(NOLOCK) WHERE paMainID=@paMainID) AND caMainID=@caMainID
		AND CompanyDeleted=0
	UNION
		SELECT cvMainID,ID,addDate,Message,0 IsCompany,IsViewed FROM exMessageP2C WITH(NOLOCK)
		WHERE cvMainID IN(SELECT ID FROM cvMain WITH(NOLOCK) WHERE paMainID=@paMainID) AND caMainID=@caMainID
		AND CompanyDeleted=0
	) a ORDER BY a.AddDate
	UPDATE exMessageP2c SET isViewed = 1 WHERE cvMainID IN(SELECT ID FROM cvMain WITH(NOLOCK) WHERE paMainID=@paMainID) AND caMainID=@caMainID
END











GO
/****** Object:  StoredProcedure [dbo].[ccNVpaMainByexMessageP2CCaMainIdSelectNew]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[ccNVpaMainByexMessageP2CCaMainIdSelectNew] 
( 
	@caMainID INT,
	@Where VARCHAR(100)
)
AS
BEGIN
	BEGIN TRY
		DECLARE @SQL AS VARCHAR(MAX)
		DECLARE @cpMainID AS INT
		CREATE TABLE #T1(
			paMainID INT,
			cvMainID INT,
			paName NVARCHAR(20),
			AddDate DATETIME,
			Message	VARCHAR(500),
			isC2P INT,
			hasJobApply INT,
			hasInterview INT,
			hasRemark INT,
			hasFavorate INT,
			isViewed INT
		)
		--该用户所有聊天信息保存至临时表
		INSERT INTO #T1(paMainID,cvMainID,paName,AddDate,Message,isC2P,isViewed)
			SELECT c.ID paMainID,b.ID cvMainID,c.Name,a.AddDate,a.Message,1 isC2P,isViewed
				FROM exMessageC2p a WITH(NOLOCK),
					cvMain b WITH(NOLOCK),
					paMain c WITH(NOLOCK) 
				WHERE a.cvMainID=b.ID 
					AND b.paMainID=c.ID 
					AND caMainID=@caMainID 
					AND CompanyDeleted=0 
			UNION
			SELECT c.ID paMainID,b.ID cvMainID,c.Name,a.AddDate,a.Message,0 isC2P,isViewed
				FROM exMessageP2c a WITH(NOLOCK),
					cvMain b WITH(NOLOCK),
					paMain c WITH(NOLOCK) 
				WHERE a.cvMainID=b.ID 
					AND b.paMainID=c.ID 
					AND caMainID=@caMainID 
					AND CompanyDeleted=0 

		SELECT @cpMainID=cpMainID FROM caMain WHERE ID=@caMainID
		UPDATE #T1 SET paName = LEFT(dbo.GetPaName(cvMainID, @cpMainID), 20),
			HasJobApply = (SELECT TOP 1 '1' FROM exJobApply a WITH(NOLOCK) INNER JOIN Job b WITH(NOLOCK) ON a.JobID=b.ID WHERE a.CompanyDeleted=0 AND b.caMainID=@caMainID AND cvMainID=#T1.cvMainID),
			HasInterview = (SELECT TOP 1 '1' FROM exInterview a WITH(NOLOCK) INNER JOIN Job b WITH(NOLOCK) ON a.JobID=b.ID WHERE a.CompanyDeleted=0 AND b.caMainID=@caMainID AND cvMainID=#T1.cvMainID),
			HasRemark = (SELECT TOP 1 '1' FROM caCvRemark WITH(NOLOCK) WHERE caMainID=@caMainID AND cvMainID=#T1.cvMainID),
			HasFavorate = (SELECT TOP 1 '1' FROM caFavorate WITH(NOLOCK) WHERE caMainID=@caMainID AND cvMainID=#T1.cvMainID)


		CREATE TABLE #T2(
			paMainID INT,
			MsgCount INT,
			MsgUnRead INT
		)
		--保存数量
		INSERT INTO #T2 SELECT paMainID,Count(*),0 FROM #T1 GROUP BY paMainID
		--保存未读数量
		UPDATE #T2 SET MsgUnRead = (SELECT COUNT(*) FROM #T1 WHERE isC2p = 0 AND isViewed = 0 AND #T1.paMainID = #T2.paMainID GROUP BY paMainID)
		
		SET @SQL = '
		SELECT a.paMainID,a.cvMainID,a.paName,c.MsgCount,c.MsgUnRead,d.FullName AccountPlace,a.Message,a.AddDate,a.isC2P,a.hasJobApply,a.hasInterview,a.hasRemark,a.hasFavorate,a.isViewed FROM
		(
			SELECT paMainID,cvMainID,AddDate,paName,isC2P,Message,hasJobApply,hasInterview,hasRemark,hasFavorate,isViewed,ROW_NUMBER() OVER(PARTITION BY cvMainID ORDER BY AddDate DESC) RowNumber FROM #T1
		) a,paMain b WITH(NOLOCK),#T2 c WITH(NOLOCK),dcRegion d WITH(NOLOCK)
		WHERE a.RowNumber=1 AND a.paMainID=b.ID AND c.paMainID=a.paMainID AND d.ID=b.AccountPlace '
		IF LEN(@Where) > 0
		BEGIN
			SET @Where = dbo.SafeSql(@Where)
			SET @SQL = @SQL + @Where
		END
		SET @SQL=@SQL+' ORDER BY a.AddDate DESC'
		EXEC(@SQL)
		DROP TABLE #T1
		DROP TABLE #T2
	END TRY
	BEGIN CATCH
		DROP TABLE #T1
		DROP TABLE #T2
	END CATCH
END











GO
/****** Object:  StoredProcedure [dbo].[ccNVpaMainByexMessageP2CPaMainIdSelectNew]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ccNVpaMainByexMessageP2CPaMainIdSelectNew] 
( 
	@cvMainID INT,
	@caMainID INT
)
AS
BEGIN
	BEGIN TRY
		DECLARE @cpMainID AS INT
		CREATE TABLE #T(
			paMainID INT,
			cvMainID INT,
			AccountPlace NVARCHAR(20),
			Gender BIT,
			Birthday INT,
			Degree NVARCHAR(10),
			RelatedYears INT,
			paName NVARCHAR(20),
			hasJobApply INT,
			hasInterview INT,
			hasRemark INT,
			hasFavorate INT
		)
		--该用户基本信息保存至临时表
		INSERT INTO #T(paMainID,cvMainID,AccountPlace,Gender,Birthday,Degree,RelatedYears,paName)
			SELECT a.ID paMainID,b.ID cvMainID,d.FullName AccountPlace,a.Gender,a.Birthday,c.Description Degree,b.RelatedWorkYears,a.Name
				FROM paMain a WITH(NOLOCK)  
					left join cvMain b WITH(NOLOCK) on a.ID=b.paMainID
					left join dcEducation c WITH(NOLOCK) on b.Degree=c.ID

					left join dcRegion d WITH(NOLOCK) on  a.AccountPlace=d.ID
				WHERE 
					b.ID=@cvMainID
		SELECT @cpMainID=cpMainID FROM caMain WHERE ID=@caMainID
		UPDATE #T SET paName = LEFT(dbo.GetPaName(cvMainID, @cpMainID), 20),
			HasJobApply = (SELECT TOP 1 '1' FROM exJobApply a WITH(NOLOCK) INNER JOIN Job b WITH(NOLOCK) ON a.JobID=b.ID WHERE a.CompanyDeleted=0 AND b.caMainID=@caMainID AND cvMainID=#T.cvMainID),
			HasInterview = (SELECT TOP 1 '1' FROM exInterview a WITH(NOLOCK) INNER JOIN Job b WITH(NOLOCK) ON a.JobID=b.ID WHERE a.CompanyDeleted=0 AND b.caMainID=@caMainID AND cvMainID=#T.cvMainID),
			HasRemark = (SELECT TOP 1 '1' FROM caCvRemark WITH(NOLOCK) WHERE caMainID=@caMainID AND cvMainID=#T.cvMainID),
			HasFavorate = (SELECT TOP 1 '1' FROM caFavorate WITH(NOLOCK) WHERE caMainID=@caMainID AND cvMainID=#T.cvMainID)
		SELECT * FROM #T
		
		DROP TABLE #T
	END TRY
	BEGIN CATCH
		DROP TABLE #T
	END CATCH
END










GO
/****** Object:  StoredProcedure [dbo].[ccPaAttentionSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--Nick 20151120
--企业关注列表
CREATE PROCEDURE [dbo].[ccPaAttentionSelect]
(
	@WHERE VARCHAR(1000), 
	@Order VARCHAR(100), 
	@Page SMALLINT, 
	@caMainID INT, 
	@cpMainID INT, 
	@AttentionType SMALLINT --1关注企业 2关注职位
)
AS
SET NOCOUNT ON
BEGIN
	SET @Where = dbo.SafeSql(@Where)
	SET @ORDER = REPLACE(dbo.SafeSQL(@ORDER), '''', '''''')
		
	DECLARE @SQL AS VARCHAR(2000)

		CREATE TABLE #T(
			TitleID BIGINT, 
			ID INT, 
			paMainID INT, 
			cvMainID INT, 
			AddDate SMALLDATETIME, 
			IsMatched BIT, 
			Degree TINYINT, 
			RelatedWorkYears TINYINT, 
			LivePlace NVARCHAR(50), 
			Gender BIT, 
			paName NVARCHAR(20), 
			BirthDay INT, 
			HasPhoto TINYINT, 
			Attachment VARCHAR(50) COLLATE Chinese_PRC_CI_AS, 
			IsNameHidden BIT, 
			Valid TINYINT, 
			IsViewed BIT, 
			HasJobApply BIT, 
			HasInterview BIT, 
			HasRemark BIT, 
			HasFavorate BIT, 
			cvEducationID INT, 
			College NVARCHAR(50), 
			EduType TINYINT, 
			MajorName NVARCHAR(20), 
			Graduation INT, 
			Speciality VARCHAR(MAX) COLLATE Chinese_PRC_CI_AS, 
			Experience VARCHAR(MAX) COLLATE Chinese_PRC_CI_AS, 
			cvMatch INT, 
			RecruitmentID INT, 
			RecruitmentName NVARCHAR(100), 
			RecruitmentDate SMALLDATETIME, 
			MobileVerifyDate SMALLDATETIME, 
			IsOnline BIT, 
			JobID INT, 
			JobName VARCHAR(50), 
			HasWeiXin BIT, 
			SecondId VARCHAR(10)
		)

	IF @AttentionType = 1   --企业
	BEGIN
		SET @SQL='
			INSERT INTO #T
			(TitleID, ID, paMainID, AddDate, LivePlace, Gender, 
				BirthDay, HasPhoto, MobileVerifyDate, IsOnline)
			SELECT ROW_NUMBER() OVER (ORDER BY ' + @ORDER + ') AS TitleID, a.ID, c.ID, a.AddDate, c.LivePlace, 
				c.Gender, c.BirthDay, c.HasPhoto, c.MobileVerifyDate, dbo.GetPaOnlineStatus(c.ID)
			FROM paAttention a WITH(NOLOCK), paMain c WITH(NOLOCK)
			WHERE a.paMainID = c.ID AND AttentionType = 1 AND AttentionID = '+CONVERT(VARCHAR(20), @cpMainID) 
		--PRINT @SQL
		IF LEN(@WHERE) > 0
			SET @SQL = @SQL + ' AND ' + @WHERE

		SET @SQL = @SQL + 'ORDER BY a.AddDate '
		EXEC(@SQL)
	END
	ELSE
	BEGIN
		SET @SQL='
			INSERT INTO #T
			(TitleID, ID, paMainID, AddDate, LivePlace, Gender, 
				BirthDay, HasPhoto, MobileVerifyDate, IsOnline, JobID, JobName)
			SELECT ROW_NUMBER() OVER (ORDER BY ' + @ORDER + ') AS TitleID, a.ID, c.ID, a.AddDate, c.LivePlace, 
				c.Gender, c.BirthDay, c.HasPhoto, c.MobileVerifyDate, dbo.GetPaOnlineStatus(c.ID), b.ID, b.Name
			FROM paAttention a WITH(NOLOCK), Job b WITH(NOLOCK), paMain c WITH(NOLOCK)
			WHERE a.paMainID = c.ID 
			AND AttentionType = 2
			AND a.AttentionID = b.ID
			AND b.IsDelete = 0'			
		IF LEN(@WHERE) > 0
			SET @SQL = @SQL + ' AND '+@WHERE

		SET @SQL = @SQL + ' ORDER BY a.AddDate '
		--PRINT @SQL
		EXEC(@SQL)
	END
	--修改cvmainID
	UPDATE a SET CvMainID = (
		SELECT TOP 1 ID FROM CvMain WITH(NOLOCK)
		WHERE PaMainID  = a.PaMainID
		AND (Valid > 0 OR substring(CvLevel, 0, 6)='111111' OR substring(CvLevel, 0, 6) = '111101' )
		ORDER BY RefreshDate DESC
	) FROM #T a

	UPDATE a
	SET CvMainID = (SELECT TOP 1 ID FROM CvMain WITH(NOLOCK)
			WHERE PaMainID  = a.PaMainID
			ORDER BY RefreshDate DESC, Id DESC),
		SecondId = (SELECT TOP 1 SecondId FROM CvMain WITH(NOLOCK)
			WHERE PaMainID  = a.PaMainID
			ORDER BY RefreshDate DESC, Id DESC)
	FROM #T a 

	DELETE FROM #T WHERE CvMainID IS NULL

	--修改简历信息
	UPDATE  a
	SET a.Degree = b.Degree, 
	a.RelatedWorkYears = b.RelatedWorkYears, 
	a.Attachment = b.Attachment, 
	a.IsNameHidden = b.IsNameHidden, 
	a.Valid = b.Valid
	FROM #T a, CvMain b
	WHERE a.CvMainID = b.ID

	IF LEN(@WHERE) > 0
		SET @SQL = @SQL + ' AND ' + @WHERE

	IF(@Page < 1)
		SET @Page = 1
	IF NOT EXISTS(SELECT 'x' FROM #t WHERE TitleID > (@Page-1)*20 AND  TitleID <= @Page*20)
		SET @Page = 1
		
	UPDATE #T SET paName = LEFT(dbo.GetPersonName(cvMainID, @cpMainID), 20), IsViewed = (SELECT TOP 1 '1' FROM caCvViewLog WITH(NOLOCK) WHERE cvMainID=#T.cvMainID AND caMainID=@caMainID), 
		HasFavorate = (SELECT TOP 1 '1' FROM caFavorate WITH(NOLOCK) WHERE caMainID=@caMainID AND cvMainID=#T.cvMainID), 
		HasInterview = (SELECT TOP 1 '1' FROM exInterview a WITH(NOLOCK) INNER JOIN Job b WITH(NOLOCK) ON a.JobID=b.ID WHERE a.CompanyDeleted=0 AND b.caMainID=@caMainID AND cvMainID=#T.cvMainID), 
		HasRemark = (SELECT TOP 1 '1' FROM caCvRemark WITH(NOLOCK) WHERE caMainID=@caMainID AND cvMainID=#T.cvMainID), 
		HasJobApply = (SELECT TOP 1 '1' FROM exJobApply a WITH(NOLOCK) INNER JOIN Job b WITH(NOLOCK) ON a.JobID=b.ID WHERE a.CompanyDeleted=0 AND b.caMainID=@caMainID AND cvMainID=#t.cvMainID)
	WHERE TitleID > (@Page-1)*20 AND  TitleID <= @Page*20

	UPDATE #T SET Speciality = (
		SELECT Speciality FROM cvMain WITH(NOLOCK)
		WHERE cvMain.ID = #T.cvMainID)
	WHERE TitleID > (@Page-1)*20 AND  TitleID <= @Page*20
		
	UPDATE #T SET Experience = (
		SELECT TOP 1 ISNULL(Description, DescriptionEng) FROM cvExperience WITH(NOLOCK)
		WHERE cvExperience.cvMainID = #T.cvMainID
		ORDER BY BeginDate DESC)
	WHERE TitleID > (@Page-1)*20 AND  TitleID <= @Page*20

	UPDATE #T SET cvEducationID = (
		SELECT TOP 1 ID FROM cvEducation WITH(NOLOCK)
		WHERE cvEducation.cvMainID = #T.cvMainID
		AND #T.Degree = cvEducation.Degree
		ORDER BY Graduation DESC)
	WHERE TitleID > (@Page-1)*20 AND  TitleID <= @Page*20

	UPDATE a SET a.College = ISNULL(b.GraduateCollage, b.GraduateCollageEng), a.EduType = b.EduType, 
		a.MajorName = ISNULL(b.MajorName, b.MajorNameEng), a.Graduation = b.Graduation
	FROM #T a, cvEducation b WITH(NOLOCK)
	WHERE b.ID = a.cvEducationID AND a.TitleID > (@Page-1)*20 AND a. TitleID <= @Page*20
		
	--UPDATE a SET a.RecruitmentName = b.RecruitmentName, a.RecruitmentDate = b.EndDate
	--FROM #T a, Recruitment b WITH(NOLOCK)
	--WHERE b.ID = a.RecruitmentID AND a.TitleID > (@Page-1)*20 AND a. TitleID <= @Page*20
	
	--修改是否绑定微信
	UPDATE a SET HasWeiXin = 1
	FROM #T a, WxFans b WITH(NOLOCK)
	WHERE a.paMainID = b.PaMainID
	AND b.Status = 2
	AND a.TitleID > (@Page-1)*20 AND  TitleID <= @Page*20
			
	UPDATE #T SET cvMatch = dbo.GetCvMatch(cvMainID, JobID) WHERE TitleID > (@Page-1)*20 AND  TitleID <= @Page*20

	SELECT COUNT(*) FROM #T WITH(NOLOCK)
	SELECT * FROM #T WITH(NOLOCK) WHERE TitleID > (@Page-1)*20 AND  TitleID <= @Page*20

	--计算匹配度
	DROP TABLE #T
END



GO
/****** Object:  StoredProcedure [dbo].[ccPaBlackByMobileSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- 检查:		Sean
-- 日期:		2010-10-5
-- 描述:		手机黑名单
-- =============================================
CREATE PROCEDURE [dbo].[ccPaBlackByMobileSelect]
AS
BEGIN
    SELECT Mobile FROM Person_Black WITH(NOLOCK) WHERE ISNULL(Mobile, '') > ''
END














GO
/****** Object:  StoredProcedure [dbo].[ccPaJobViewLogBycaMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--修改:Andy 2015-01-13
--1. 去掉try catch
--2. 添加职位的regionid
CREATE PROCEDURE [dbo].[ccPaJobViewLogBycaMainIDSelect]
(
	@caMainID INT, 
	@WHERE VARCHAR(1000), 
	@ORDER VARCHAR(1000), 
	@Page SMALLINT, 
	@cpMainID INT
)
AS
SET NOCOUNT ON
BEGIN
	IF NOT EXISTS(SELECT 'x' FROM caMain WITH(NOLOCK) WHERE ID = @caMainID AND cpMainID = @cpMainID)
		RETURN 0
	
	SET @Where = dbo.SafeSql(@Where)
	SET @ORDER = dbo.SafeSql(@Order)
	CREATE TABLE #t(
		TitleID BIGINT, 
		caMainId INT, 
		cvMainId INT, 
		jobId INT, 
		jobRegionID INT, 
		CvJobMatch INT, 
		JobName NVARCHAR(50), 
		AddDate SMALLDATETIME, 
		Degree TINYINT, 
		RelatedWorkYears TINYINT, 
		LivePlace VARCHAR(6) COLLATE Chinese_PRC_CI_AS, 
		Gender BIT, 
		paName NVARCHAR(20), 
		BirthDay INT, 
		HasPhoto TINYINT, 
		Attachment VARCHAR(50) COLLATE Chinese_PRC_CI_AS, 
		IsNameHidden BIT, 
		Valid TINYINT, 
		IsViewed BIT, 
		HasJobApply BIT, 
		HasInterview BIT, 
		HasRemark BIT, 
		HasFavorate BIT, 
		cvEducationID INT, 
		College NVARCHAR(50), 
		EduType TINYINT, 
		MajorName NVARCHAR(20), 
		Graduation INT, 
		Speciality VARCHAR(MAX) COLLATE Chinese_PRC_CI_AS, 
		Experience VARCHAR(MAX) COLLATE Chinese_PRC_CI_AS, 
		MobileVerifyDate SMALLDATETIME, 
		IsOnline BIT, 
		PaMainID INT, 
		HasWeiXin BIT, 
		SecondId VARCHAR(100)
	)
	DECLARE @SQL AS VARCHAR(2000)
	SET @SQL='
		INSERT INTO #t(TitleID, caMainID, cvMainID, jobId, jobRegionID, AddDate, JobName,
			MobileVerifyDate, IsOnline, PaMainID, SecondId)
		SELECT ROW_NUMBER() OVER (ORDER BY ' + @ORDER + ') AS TitleID, 
			b.caMainID, d.ID, b.ID, b.dcRegionID, a.AddDate, b.Name,
			c.MobileVerifyDate, dbo.GetPaOnlineStatus(c.ID), c.ID, d.SecondId
		From PaJobViewLog a WITH(NOLOCK)
		INNER JOIN Job b WITH(NOLOCK) ON b.ID=a.JobID
		INNER JOIN paMain c WITH(NOLOCK) ON c.ID=a.paMainID
		INNER JOIN cvMain d WITH(NOLOCK) ON d.paMainID=c.ID AND d.Valid>0'

	SET @SQL = @SQL + '
		WHERE 1=1 '

	IF LEN(@WHERE)> 0
		SET @SQL=@SQL + @WHERE
	--PRINT(@SQL)
	EXEC(@SQL)

	IF(@Page < 1)
		SET @Page = 1
	IF NOT EXISTS(SELECT 'x' FROM #t WHERE TitleID > (@Page-1)*20 AND  TitleID <= @Page*20)
		SET @Page = 1

	--添加匹配度  Peter 2013-11-12 14:33
	UPDATE #t SET CvJobMatch = dbo.GetCvMatch(cvMainId, jobID), Degree = a.Degree, RelatedWorkYears = a.RelatedWorkYears, Attachment = a.Attachment, 
		IsNameHidden = a.IsNameHidden, LivePlace = b.LivePlace, Gender = b.Gender, paName = b.Name, 
		BirthDay = b.BirthDay, HasPhoto = b.HasPhoto, Valid = a.Valid
	FROM cvMain a WITH(NOLOCK) INNER JOIN paMain b WITH(NOLOCK) ON a.paMainID = b.ID
	WHERE a.ID = #t.cvMainID AND TitleID > (@Page-1)*20 AND TitleID <= @Page*20

	UPDATE #t SET paName = LEFT(dbo.GetPersonName(cvMainID, @cpMainID), 20), 
		IsViewed = (SELECT TOP 1 '1' FROM caCvViewLog WITH(NOLOCK) WHERE cvMainID=#T.cvMainID AND caMainID=@caMainID), 
		HasJobApply = (SELECT TOP 1 '1' FROM exJobApply a WITH(NOLOCK) INNER JOIN Job b WITH(NOLOCK) ON a.JobID=b.ID WHERE a.CompanyDeleted=0 AND b.caMainID=@caMainID AND cvMainID=#t.cvMainID), 
		HasInterview = (SELECT TOP 1 '1' FROM exInterview a WITH(NOLOCK) INNER JOIN Job b WITH(NOLOCK) ON a.JobID=b.ID WHERE a.CompanyDeleted=0 AND b.caMainID=@caMainID AND cvMainID=#t.cvMainID), 
		HasRemark = (SELECT TOP 1 '1' FROM caCvRemark WITH(NOLOCK) WHERE caMainID=@caMainID AND cvMainID=#t.cvMainID), 
		HasFavorate = (SELECT TOP 1 '1' FROM caFavorate WITH(NOLOCK) WHERE caMainID=@caMainID AND cvMainID=#t.cvMainID)
	WHERE TitleID > (@Page - 1)*20 AND TitleID <= @Page*20

	UPDATE #T SET Speciality = (
		SELECT Speciality FROM cvMain WITH(NOLOCK)
		WHERE cvMain.ID = #T.cvMainID)
	WHERE TitleID > (@Page-1)*20 AND TitleID <= @Page*20
	
	UPDATE #T SET Experience = (
		SELECT TOP 1 ISNULL(Description, DescriptionEng) FROM cvExperience WITH(NOLOCK)
		WHERE cvExperience.cvMainID = #T.cvMainID
		ORDER BY BeginDate DESC)
	WHERE TitleID > (@Page-1)*20 AND TitleID <= @Page*20

	UPDATE #T SET cvEducationID = (
		SELECT TOP 1 ID FROM cvEducation WITH(NOLOCK)
		WHERE cvEducation.cvMainID = #T.cvMainID
		AND #T.Degree = cvEducation.Degree
		ORDER BY Graduation DESC)
	WHERE TitleID > (@Page-1)*20 AND TitleID <= @Page*20

	UPDATE a SET a.College = ISNULL(b.GraduateCollage, b.GraduateCollageEng), a.EduType= b.EduType, 
		a.MajorName = ISNULL(b.MajorName, b.MajorNameEng), a.Graduation = b.Graduation
	FROM #T a, cvEducation b WITH(NOLOCK)
	WHERE b.ID = a.cvEducationID AND a.TitleID > (@Page-1) * 20 AND a.TitleID <= @Page*20

	--修改是否绑定微信
	UPDATE a SET HasWeiXin = 1
	FROM #T a, WxFans b WITH(NOLOCK)
	WHERE a.paMainID = b.PaMainID
	AND b.Status = 2
	AND a.TitleID > (@Page-1)*20 AND  TitleID <= @Page*20

	SELECT COUNT(*) FROM #t WITH(NOLOCK)
	SELECT * FROM #t WITH(NOLOCK) WHERE TitleID > (@Page - 1)*20 AND TitleID <= @Page*20
	
	DROP TABLE #t	
END

GO
/****** Object:  StoredProcedure [dbo].[ccpaLoginContactByOpenIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2016.4.6
--创建人：Lucifer
--说明：判断是否已绑定微信企业账号
--#####################################################
CREATE PROCEDURE [dbo].[ccpaLoginContactByOpenIDSelect]
(
	@OpenID VARCHAR(100)
)
AS
BEGIN
	SELECT * FROM paLoginContact WITH(NOLOCK) WHERE openid = @OpenID AND ContactType = 101
END

GO
/****** Object:  StoredProcedure [dbo].[ccpaLoginContactDelete]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ccpaLoginContactDelete]
(
    @caMainID INT,
@cpMainID INT
)
AS
SET NOCOUNT ON
BEGIN
IF NOT EXISTS(SELECT 'X' FROM caMain WITH(NOLOCK) WHERE ID = @caMainID AND cpMainID = @cpMainID)
        RETURN
    UPDATE wxFans SET caBindCancelDate = GETDATE() WHERE caMainID = @caMainID
    DELETE FROM paLoginContact WHERE paMainID = @caMainID AND ContactType = 101
    INSERT INTO cpPoint (cpMainID,ChangeID,Point,LastModifyDate) VALUES(@cpMainID,22,-200,GETDATE())
END
GO
/****** Object:  StoredProcedure [dbo].[ccPaMainBycpMainIdSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/**********************8
sean 2014-10-29
***********************/
CREATE PROCEDURE [dbo].[ccPaMainBycpMainIdSelect]
(
	@cvMainID INT,
	@cpMainID INT
)
AS
--INSERT INTO procLog SELECT 'ccPaMainBycpMainIdSelect', LTRIM(STR(@cvMainID)) + ' ' + LTRIM(STR(@cpMainId)), GETDATE()
BEGIN
	IF (@cpMainID = 0)
		SELECT a.Name UserName, b.ID ShowID, a.Name ShowName, a.ID
		FROM paMain a WITH(NOLOCK),
			cvMain b WITH(NOLOCK)
		WHERE a.ID = b.paMainID 
		AND b.ID = @cvMainID
	ELSE
	BEGIN
		DECLARE @RegisterIp VARCHAR(50)
		SELECT @RegisterIp = RegisterIp FROM cpMain WITH(NOLOCK) WHERE Id = @cpMainId
		SELECT dbo.GetPaName(b.ID, @cpMainID) UserName, b.ID ShowID, 
			dbo.GetPaName(b.ID, @cpMainID) + '（' + (CASE Gender WHEN 0 THEN '男' WHEN 1 THEN '女' END) + '/' + CONVERT(VARCHAR(5),
			dbo.BirthToAge(BirthDay)) + '岁/' + ISNULL(c.Description, '') + '）' ShowName,
			LOWER(b.SecondId + SUBSTRING(SYS.Fn_VarbinToHexStr(HASHBYTES('SHA1', LTRIM(STR(a.Id)) + '-' + LTRIM(STR(@cpMainId)) + '#' + @RegisterIp + '*')), 13, 10)) HexId 
		FROM paMain a WITH(NOLOCK)
		INNER JOIN cvMain b WITH(NOLOCK) ON a.ID = b.paMainID 
		LEFT JOIN dcEducation c WITH(NOLOCK) ON b.Degree = c.ID
		WHERE b.ID = @cvMainID
	END
END

GO
/****** Object:  StoredProcedure [dbo].[ccPaMainByCvMainIdsSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--根据简历编号查询个人
--harry 
--2017-6-12
CREATE PROCEDURE [dbo].[ccPaMainByCvMainIdsSelect]
(
	@cvMainIds VARCHAR(200)
)
AS
SET NOCOUNT ON
BEGIN
	SELECT COUNT(*) AS ReceiveNum FROM paMain WITH (NOLOCK) 
	WHERE id IN (SELECT paMainId FROM cvMain WHERE Id IN (SELECT * FROM dbo.FnSplit(@cvMainIds, ',')))
	AND IsReceiveSms > 0
END
SET NOCOUNT OFF
 
GO
/****** Object:  StoredProcedure [dbo].[ccPaMainByGetPaNameSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


--lambo 20110221
--企业会员中心，根据cvMainID,cpMainID判断是否显示姓名
CREATE PROCEDURE [dbo].[ccPaMainByGetPaNameSelect]
(
	@cvMainID INT,
	@cpMainID INT
)
AS
BEGIN
	SELECT dbo.GetPaName(@cvMainID, @cpMainID) Name
END	














GO
/****** Object:  StoredProcedure [dbo].[ccPaMainByGetPaNameSelect2]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--lambo 20110221
--企业会员中心，根据cvMainID,cpMainID判断是否显示姓名
CREATE PROCEDURE [dbo].[ccPaMainByGetPaNameSelect2]
(
	@cvMainID VARCHAR(50),
	@cpMainID VARCHAR(50)
)
AS
BEGIN
	SELECT dbo.GetPaName(@cvMainID, @cpMainID) Name
END 
GO
/****** Object:  StoredProcedure [dbo].[ccPaPlaintByCaMainIDNoViewedSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--==================================================
--检查 sean 2010-10-8
--描述 企业账号未查看的个人用户反馈
--==================================================
CREATE PROCEDURE [dbo].[ccPaPlaintByCaMainIDNoViewedSelect]
(
	@caMainID INT
)
AS
BEGIN
	SELECT *
	FROM PaPlaint WITH(NOLOCK INDEX(IX_paPlaint_caMainID))
	WHERE caMainID = @caMainID 
	AND IsViewed=0
	AND ReplyType =1
	ORDER BY ID DESC
END














GO
/****** Object:  StoredProcedure [dbo].[ccPaPlaintByCaMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--==================================================
--检查 sean 2010-10-8
--描述 企业账号查看个人用户反馈
--==================================================
CREATE PROCEDURE [dbo].[ccPaPlaintByCaMainIDSelect]
(
	@caMainID INT
)
AS
BEGIN
	SELECT *
	FROM PaPlaint WITH(NOLOCK INDEX(IX_paPlaint_caMainID)) 
	WHERE caMainID =@caMainID 
	AND ReplyType =1
	ORDER BY ID DESC
END














GO
/****** Object:  StoredProcedure [dbo].[ccPaPlaintByCpMainIDNoViewedSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--==================================================
--检查 sean 2010-10-8
--描述 该企业所有账号的未查看的个人用户反馈
--==================================================
CREATE PROCEDURE [dbo].[ccPaPlaintByCpMainIDNoViewedSelect]
(
	@cpMainID INT
)
AS
BEGIN
	SELECT *
	FROM PaPlaint a WITH(NOLOCK INDEX(IX_paPlaint_caMainID)), caMain b WITH(NOLOCK INDEX(IX_caMain_cpMainID))		
	WHERE a.caMainID = b.ID
	AND b.cpMainID = @cpMainID
	AND IsViewed=0
	AND ReplyType =1
	ORDER BY a.CaMainID,a.ID DESC
END














GO
/****** Object:  StoredProcedure [dbo].[ccPaPlaintByCpMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--==================================================
--检查 sean 2010-10-8
--描述 该企业所有账号的个人用户反馈
--==================================================
CREATE PROCEDURE [dbo].[ccPaPlaintByCpMainIDSelect]
(
	@cpMainID INT
)
AS
BEGIN
	SELECT a.*,
		b.Name caName
	FROM PaPlaint a WITH(NOLOCK INDEX(IX_paPlaint_caMainID)), caMain b WITH(NOLOCK INDEX(IX_caMain_cpMainID))			
	WHERE a.caMainID = b.ID
	AND b.cpMainID = @cpMainID
	AND ReplyType = 1
	AND b.isDelete = 0
	ORDER BY a.CaMainID,a.ID DESC
END














GO
/****** Object:  StoredProcedure [dbo].[ccPaplaintByIsViewedUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--==================================================
--检查 sean 2010-10-8
--描述 修改个人用户反馈的查看状态 ，一次一屏，asp中取所有IsViewed = false的id
--==================================================
CREATE PROCEDURE [dbo].[ccPaplaintByIsViewedUpdate]
(
    @AllID VARCHAR(200),
	@caMainID INT
)
AS
BEGIN TRY
	SET @AllID = dbo.FormatIDS(@AllID)

	DECLARE @T AS TABLE(ID INT)
	INSERT INTO @T SELECT * FROM dbo.fnSplit(@AllID, ',')

	UPDATE paplaint SET IsViewed=1 WHERE ID IN(SELECT ID FROM @T) AND caMainID = @caMainID
    RETURN 1
END TRY
BEGIN CATCH
    RETURN 0
END CATCH














GO
/****** Object:  StoredProcedure [dbo].[ccQuotaLogInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--分配配额
--harry
--2017-12-5
CREATE PROCEDURE [dbo].[ccQuotaLogInsert]
(
 	@quotaType INT, ---1简历
	@orderId INT,
	@cpMainId INT,
	@caIds VARCHAR(1000),
	@data VARCHAR(1000),
	@isallocate BIT---0共享 1分配
)
AS
SET NOCOUNT ON
	DECLARE @sumCount INT ,@sumSetCount INT
	IF @quotaType = 1--简历
	BEGIN
		IF @isallocate =0 
		BEGIN
			DELETE FROM QuotaLog WHERE CaOrderId = @orderId AND cpMainId = @cpMainId
			UPDATE caOrder SET isCvAllocate= 0 WHERE id = @orderId
		END
		ELSE
		BEGIN
			--计算分配总数是否=简历数
			SELECT @sumCount=SUM(ActiveQuota) FROM caOrder 
			WHERE orderType IN(8,9)
    		AND OpenDate IS NOT NULl
    		AND IsDeleted = 0
    		AND (MainOrderID = @orderId OR Id =@orderId)
			
			DECLARE @T AS TABLE(id INT  identity(1,1),data INT)
			INSERT INTO @T(data) SELECT * FROM dbo.fnSplit(@data, ',')
			
			SELECT @sumSetCount=SUM(data)FROM @T
			IF @sumSetCount	= @sumCount --数值正确，进行分配
			BEGIN
				DECLARE @Tid AS TABLE(id INT identity(1,1),caId INT)
				DECLARE @caId INT, @id INT
				INSERT INTO @Tid(caId) SELECT * FROM dbo.fnSplit(@caIds, ',')

				WHILE EXISTS(SELECT 'x' FROM @Tid)
				BEGIN
					SELECT TOP 1 @id = id, @caId =caId FROM @Tid
					IF EXISTS(SELECT 'x' FROM QuotaLog WHERE CaOrderId = @orderId AND cpMainId = @cpMainId AND CaMainId = @caId AND QuotaType =1 )
					BEGIN
						UPDATE QuotaLog
						SET Quota =(SELECT TOP 1 data FROM @T WHERE id = @id)
						WHERE CaOrderId = @orderId AND cpMainId = @cpMainId AND CaMainId = @caId AND QuotaType =1
						
						DELETE FROM @Tid WHERE id = @id
					END
					ELSE
					BEGIN
						INSERT INTO QuotaLog(QuotaType, CaOrderId, CaMainId,CpMainId, Quota, RemainQuota, AddDate)
						SELECT 1, @orderId, @caId, @cpMainId, (SELECT TOP 1 data FROM @T WHERE id = @id),(SELECT TOP 1 data FROM @T WHERE id = @id), GETDATE() 
						DELETE FROM @Tid WHERE id = @id
					END
				END 
				UPDATE QuotaLog
				SET RemainQuota= Quota -(SELECT COUNT(1) FROM caactivelog WHERE caMainId = QuotaLog.CaMainId AND CaOrderId =QuotaLog.CaOrderId)
				WHERE QuotaType =1 AND cpMainId = @cpMainId
				UPDATE caOrder SET isCvAllocate= 1 WHERE id = @orderId
				
			END 
		END
	END
      
SET NOCOUNT OFF
GO
/****** Object:  StoredProcedure [dbo].[ccQuotaLogSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--根据订单号获取简历下载信息
--harry
--2017-12-5
CREATE PROCEDURE [dbo].[ccQuotaLogSelect]
(
 	@quotaType INT, ---1简历
	@orderId INT,
	@cpMainId INT
)
AS
INSERT INTO ProcLog SELECT 'ccQuotaLogSelect', @cpMainId, GETDATE()

SET NOCOUNT ON
       CREATE TABLE #t
	(
	caMainId INT,
        Username VARCHAR(100),
	name NVARCHAR(50),
	accountType INT,
	IsPause BIT,
	IsDelete BIT,
	Quota INT,
	UsedQuota INT 
	)

	DECLARE @isAllocate BIT --该内容是否分享是否分享
	
	IF @quotaType =1
	BEGIN
		SELECT @isAllocate = ISNULL(isCvAllocate,0) FROM caOrder WITH(NOLOCK) WHERE id= @orderId
	END
	--先插入用户
	INSERT INTO #t(caMainId, Username, name, accountType, isPause, isDelete, Quota, UsedQuota)
        SELECT ID, userName, Name,accountType, isPause, isDelete, 0, 0
	FROM caMain 
	WHERE cpMainId = @cpMainId

        --再更新分配的用户数据
	UPDATE #t
	SET Quota = b.Quota, UsedQuota =(b.Quota-b.ReMainQuota)
	FROM #t a, QuotaLog b
	WHERE b.caOrderId = @orderId
	AND a.caMainId = b.caMainid
	AND b.QuotaType = @quotaType 

	IF @isAllocate = 0--共享的计算使用量
	BEGIN
		IF @quotaType = 1
		BEGIN
			UPDATE #t
			SET UsedQuota = (SELECT COUNT(1) FROM caActivelog WHERE caMainID = #t.caMainId AND (caOrderId= @orderId OR caOrderId IN (SELECT Id FROM caOrder WITH(NOLOCK)
			WHERE orderType = 9
			AND OpenDate IS NOT NULl
			AND IsDeleted = 0
			AND MainOrderID = @orderId))) 
		END
	END 
	

	--先获取订单信息
	IF @quotaType = 1
	BEGIN
	SELECT * FROM caOrder WITH(NOLOCK)
	WHERE (id = @orderId 
	OR MainOrderID = @orderId)
	AND (orderType = 8 OR orderType = 9)
	AND OpenDate IS NOT NULl
	AND IsDeleted = 0
	END

	--再获取分配信息
    SELECT * FROM #t

	DROP TABLE #t 
SET NOCOUNT OFF
GO
/****** Object:  StoredProcedure [dbo].[ccQuotaLogSelectByCaMainid]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--分配配额查询
--harry
--2017-12-11
CREATE PROCEDURE [dbo].[ccQuotaLogSelectByCaMainid]
(
 	@quotaType INT, ---1简历
	@cpMainId INT,
	@caMainId INT 
)
AS
SET NOCOUNT ON
	DECLARE @isAllocate BIT ,@validVipOrder INT, @ActiveQuota INT, @RemainQuota INT
	IF @quotaType = 1--简历
	BEGIN
		--获取当前的vip订单号
		SELECT @validVipOrder =id, @ActiveQuota = ActiveQuota, @RemainQuota = RemainQuota, @isAllocate = isCvAllocate 
		FROM caOrder 
		WHERE cpMainId = @cpMainId
		AND IsDeleted =0 
		AND openDate<GETDATE()
		AND beginDate<GETDATE()
		AND endDate>GETDATE()
		AND orderType = 8 
		--筛选判断是否进行分配 
		IF ISNULL(@isAllocate,0) =1
		BEGIN
			SELECT Quota,RemainQuota, @isAllocate IsAllocate FROM QuotaLog WITH(NOLOCK) WHERE caOrderId = @validVipOrder AND caMainId = @caMainId AND cpMainId = @cpMainId
		END
		ELSE
		BEGIN
			SELECT 	SUM(ISNULL(ActiveQuota,0)) AS Quota, SUM(ISNULL(RemainQuota,0)) AS RemainQuota, @isAllocate IsAllocate
			FROM caOrder
			WHERE cpMainId = @cpMainId
			AND IsDeleted =0 
			AND openDate<GETDATE()
			AND beginDate<GETDATE()
			AND endDate>GETDATE()
		END
	END
      
SET NOCOUNT OFF
GO
/****** Object:  StoredProcedure [dbo].[ccRecommendCvBySearchSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--修改Harry2018-4-19
--将ptCvInvitation 换为 ptWeixinFollow
CREATE PROCEDURE [dbo].[ccRecommendCvBySearchSelect]
(
	@dcRegionID INT, 					--求职地区
	@RecruitmentPlaceID INT, 			--场馆ID
	@PageNumber INT, 					--翻页页码
	@caMainID INT, 						--企业用户ID，用来判断是否和建立联系
	@dcJobTypeIDExpect VARCHAR(50), 		--职位类别
	@KeyWord NVARCHAR(20)				--关键词
)
AS
--return
SET NOCOUNT ON
BEGIN TRY
	IF @dcRegionID IS NULL
		SET @dcRegionID = ''
	IF @RecruitmentPlaceID > 0
		SET @dcRegionID = ''

	DECLARE @KeyTemp NVARCHAR(20)
	SET @KeyWord = LTRIM(RTRIM(dbo.SafeSQL(REPLACE(@KeyWord, '  ', ' '))))
	SET @KeyWord = REPLACE(@KeyWord, '''', '')
	SET @KeyTemp = @KeyWord
	IF @KeyWord IS NULL OR LEN(@KeyWord) < 2
		SELECT @KeyWord = '', @KeyTemp = ''

	IF @dcJobTypeIDExpect IS NULL
		SET @dcJobTypeIDExpect = ''
	ELSE
		SET @dcJobTypeIDExpect = REPLACE(REPLACE(LTRIM(RTRIM(@dcJobTypeIDExpect)), ' ', ','), '''', '')
	SET @dcJobTypeIDExpect = dbo.FormatIDS(@dcJobTypeIDExpect)
	
	IF @RecruitmentPlaceID IS NULL OR @RecruitmentPlaceID = 0
		SET @RecruitmentPlaceID = 0
	
	DECLARE @cpSearchConditionID AS INT
	SELECT @cpSearchConditionID=0
	DECLARE @MinId AS INT
	
	--SQLSERVER中计划任务自动删除60分钟前的数据
	SELECT TOP 1 @cpSearchConditionID = ID 
	FROM SearchDB..cpSearchCondition WITH(NOLOCK)
	WHERE dcRegionID=@dcRegionID AND RecruitmentPlaceID=@RecruitmentPlaceID 
	AND dcJobTypeID=@dcJobTypeIDExpect AND KeyWord=@KeyWord
	ORDER BY ID DESC

	IF ISNULL(@cpSearchConditionID, 0) = 0
		GOTO SELECTRESET	--无数据，重新搜索
	ELSE		
		GOTO GETRECORDSET	--从临时结果中提取数据

	SELECTRESET:				--从cv中搜索数据
	BEGIN
		DECLARE @SQL AS VARCHAR(8000), 
			@WHERE AS VARCHAR(8000), 
			@FROM AS VARCHAR(1000)
		SELECT @WHERE = ''
		----记录查询条件
		INSERT INTO SearchDB..cpSearchCondition(SessionID, dcRegionID, RecruitmentPlaceID, ReuseNumber, dcJobTypeIDExpect, KeyWord)
		VALUES(1, @dcRegionID, @RecruitmentPlaceID, 0, @dcJobTypeIDExpect, @KeyWord)
		SET @cpSearchConditionID = @@IDENTITY

		----建立关键字搜索的临时表
		CREATE TABLE #FullText(
			CvID INT NOT NULL
		)
		----建立临时表
		CREATE TABLE #Cv(
			ID INT NOT NULL, 
			RefreshDate SMALLDATETIME NOT NULL, 
			ptCvInvitationId INT
		)

		----生成求聘职位的表变量
		DECLARE @JobTypeExpect AS VARCHAR(3000)
		SET @JobTypeExpect=''
		DECLARE @T_JobType AS TABLE(ID INT)
		IF LEN(@dcJobTypeIDExpect) > 0
		BEGIN
			DECLARE @T_Temp AS TABLE(ID INT)		--临时表，用于构建组合查询语句
			INSERT INTO @T_Temp
			SELECT * FROM dbo.fnSplit(@dcJobTypeIDExpect, ',')

			INSERT INTO @T_JobType
			SELECT DISTINCT ID FROM dcJobType WITH(NOLOCK)
			WHERE ParentId IN(SELECT ID FROM @T_TEMP) 
			OR ParentId2 in(SELECT ID FROM @T_TEMP)
			OR ID IN(SELECT ID FROM @T_TEMP)
			----生成in字符串
			SELECT @JobTypeExpect = (@JobTypeExpect + LTRIM(STR(ID) + ',')) FROM @T_JobType
			IF RIGHT(@JobTypeExpect, 1) = ','
				SET @JobTypeExpect = LEFT(@JobTypeExpect, LEN(@JobTypeExpect) - 1)
		END

		----期望职位类别
		IF LEN(@dcJobTypeIDExpect) > 0
		BEGIN
			SET @WHERE = '
				AND (g.dcJobTypeID IN(' + @JobTypeExpect +'))'
		END

		----关键词
		IF LEN(@KeyTemp) > 0 --AND @MajorName IS NULL
		BEGIN
			DECLARE @S DATETIME, @SqlFt VARCHAR(MAX)
			SELECT @S = GETDATE()

			INSERT INTO #FullText
			SELECT [key] FROM CONTAINSTABLE(CvMainPublish, *, @KeyTemp, 100000) AS KeyCv
			
			INSERT INTO #FullText
			SELECT DISTINCT cvMainID FROM CvExperiencePublish WITH(NOLOCK) WHERE ID IN(
				SELECT [key] FROM CONTAINSTABLE(CvExperiencePublish, *, @KeyTemp, 100000) AS KeyCv)
			
			INSERT INTO #FullText
			SELECT DISTINCT cvMainID FROM CvEducationPublish WITH(NOLOCK) WHERE ID IN(
				SELECT [key] FROM CONTAINSTABLE(CvEducationPublish, *, @KeyTemp, 100000) AS KeyCv)
			
			INSERT INTO #FullText
			SELECT DISTINCT cvMainID FROM CvProjectPublish WITH(NOLOCK) WHERE ID IN(
				SELECT [key] FROM CONTAINSTABLE(CvProjectPublish, *, @KeyTemp, 100000) AS KeyCv)

			INSERT INTO #FullText
			SELECT DISTINCT cvMainID FROM CvTrainingPublish WITH(NOLOCK) WHERE ID IN(
				SELECT [key] FROM CONTAINSTABLE(CvTrainingPublish, *, @KeyTemp, 100000) AS KeyCv)
			--Richard 2011.8.21增加

			INSERT INTO #FullText
			SELECT DISTINCT cvMainID FROM CvAppendixPublish WITH(NOLOCK) WHERE ID IN(
				SELECT [key] FROM CONTAINSTABLE(CvAppendixPublish, *, @KeyTemp, 100000) AS KeyCv)
            --Richard 2011.8.24增加

			SELECT @SqlFt = 'SELECT [key] FROM CONTAINSTABLE(CvMainPublish, *, ''' + @KeyTemp + ''', 100000) AS KeyCv ORDER BY [key] DESC 开始：' + CONVERT(varchar(8), @S, 8) + '  结束：' + CONVERT(varchar(8), getdate(), 8)

			UPDATE SearchDB..cpSearchCondition SET SqlFT = @SqlFt WHERE ID = @cpSearchConditionID
		END

		----生成插入临时表的Sql语句
		SET @SQL = '
			INSERT INTO #Cv
			SELECT DISTINCT TOP 2000 a.ID, j.LastLoginDate, b.Id'
		
		SET @FROM = '
			FROM cvmainPublish a WITH(NOLOCK) 
			INNER JOIN paMainPublish j WITH(NOLOCK) ON a.paMainId = j.Id
			INNER JOIN MarketDb..ptWeixinFollow b WITH(NOLOCK) ON a.paMainID=b.BindPaMainID AND  b.AddDate > GETDATE() - 90
			INNER JOIN MarketDb..ptWorkAppoint c WITH(NOLOCK) ON b.ptWorkAppointID=c.ID
			INNER JOIN Recruitment d WITH(NOLOCK) ON c.RecruitmentID=d.ID
			INNER JOIN RecruitmentPlace e WITH(NOLOCK) ON d.RecruitmentPlaceID=e.ID'
		
		IF @RecruitmentPlaceID = 0
			SET @FROM = @FROM + ' AND e.dcRegionID LIKE ''' + CONVERT(VARCHAR, @dcRegionID) + '%'''
		ELSE
			SET @FROM = @FROM + ' AND e.ID=' + CONVERT(VARCHAR, @RecruitmentPlaceID)

		IF CHARINDEX('g.', @WHERE) > 0
			SET @FROM = @FROM + ' INNER JOIN cvJobTypePublish g WITH(NOLOCK) ON a.ID=g.cvMainID'
		IF LEN(@KeyTemp) > 0 --AND @MajorName IS NULL
			SET @FROM = @FROM + ' INNER JOIN #FullText k WITH(NOLOCK) ON a.ID=k.cvID'

		SET @SQL = @SQL + @FROM + @WHERE
		SET @SQL = @SQL + ' ORDER BY b.Id DESC'		--j.LastLoginDate DESC, a.ID'
		PRINT @SQL
		----把符合条件的职位全部列出
		UPDATE SearchDB..cpSearchCondition SET Sql = REPLACE(@SQL, 'INSERT INTO #Cv', ''), StartDate = GETDATE() WHERE ID = @cpSearchConditionID
		EXEC(@SQL)
		----记录查询结果总数
		DECLARE @ValidCvNumber INT
		SET @ValidCvNumber = @@ROWCOUNT		
		UPDATE SearchDB..cpSearchCondition SET ValidCvNumber = @ValidCvNumber WHERE ID = @cpSearchConditionID
		--记录查询时间
		UPDATE SearchDB..cpSearchCondition SET EndDate = GETDATE() WHERE ID = @cpSearchConditionID

		INSERT INTO SearchDB..cpSearchCvID
		SELECT TOP 2000 @cpSearchConditionID, ID FROM #Cv WITH(NOLOCK)

		DROP TABLE #Cv
		DROP TABLE #FullText
		GOTO GETRECORDSET
	END

	GETRECORDSET:
	BEGIN
		DECLARE @PageSize AS TINYINT
		SET @PageSize = 20		--每页的行数

		----返回查询数量
		UPDATE SearchDB..cpSearchCondition SET ReuseNumber = ReuseNumber + 1 WHERE ID=@cpSearchConditionID
		SELECT ValidCvNumber FROM SearchDB..cpSearchCondition WITH(NOLOCK) WHERE ID=@cpSearchConditionID
		----返回20行查询结果
		IF @PageNumber > 0
		BEGIN
			DECLARE @T_CvList AS TABLE(
				ID INT, 
				cvEducationID INT, 
				dcMajorID INT, 
				Degree TINYINT, 
				RelatedWorkYears INT, 
				dcSalaryID TINYINT, 
				RefreshDate SMALLDATETIME, 
				LastLoginDate SMALLDATETIME, 
				JobName VARCHAR(100) COLLATE Chinese_PRC_CI_AS, 
				Gender BIT, 
				BirthDay INT, 
				LivePlace INT, 
				Attachment VARCHAR(50) COLLATE Chinese_PRC_CI_AS, 
				HasPhoto TINYINT, 
				College NVARCHAR(50), 
				EduType TINYINT, 
				MajorName NVARCHAR(20), 
				Graduation INT, 
				HasViewed BIT, 
				ViewDate SMALLDATETIME, 
				LastJobTypeID INT, 
				Valid TINYINT, 
				PlaceName NVARCHAR(50), 
				RecommendDate SMALLDATETIME, 
				RecruitmentName NVARCHAR(50), 
				IsOnline BIT, 
				HasWeiXin BIT,
				paMainId INT,
				SecondId VARCHAR(10)
			)

			SELECT @MinId = MIN(ID) FROM SearchDB..cpSearchCvID WITH(NOLOCK) WHERE cpSearchConditionID = @cpSearchConditionID
			SET @MinId = @MinId + (@PageNumber-1) * @PageSize

			INSERT INTO @T_CvList(ID, dcMajorID, Degree, RelatedWorkYears, dcSalaryID, RefreshDate, LastLoginDate, 
				JobName, Gender, BirthDay, LivePlace, LastJobTypeID, Attachment, HasPhoto, HasViewed, Valid, IsOnline, paMainId, SecondId)
			SELECT TOP 20 a.ID, a.dcMajorID, a.Degree, a.RelatedWorkYears, a.dcSalaryID, a.RefreshDate, 
				j.LastLoginDate, ISNULL(a.JobName, '应届毕业生') JobName, j.Gender, j.BirthDay, j.LivePlace, a.LastJobTypeID, 
				a.Attachment, j.HasPhoto, 0, a.Valid, dbo.GetPaOnlineStatus(j.ID), a.paMainId, a.SecondId
			FROM cvmain a WITH(NOLOCK) 
			INNER JOIN paMainPublish j WITH(NOLOCK) ON a.paMainID=j.ID 
               INNER JOIN SearchDB..cpSearchCvID b ON a.id=b.CvID
			WHERE b.cpSearchConditionID=@cpSearchConditionID AND b.ID >= @MinId 
            ORDER BY b.ID, a.ID DESC
            --RICHARD 2011-7-23 16:51分修改

			UPDATE a 
			SET a.cvEducationID = (
				SELECT TOP 1 ID FROM cvEducation WITH(NOLOCK)
				WHERE cvEducation.cvMainID = a.ID
				AND a.Degree = cvEducation.Degree
				ORDER BY Graduation DESC)
			FROM @T_CvList a
			
			UPDATE a SET a.PlaceName = f.PlaceName, a.LastLoginDate = c.AddDate, 	--a.RecommendDate = c.AddDate, 
				a.RecruitmentName = e.RecruitmentName
			FROM @T_CvList a, cvMain b WITH(NOLOCK), MarketDb..ptWeixinFollow c WITH(NOLOCK), 
				MarketDb..ptWorkAppoint d WITH(NOLOCK), 
				Recruitment e WITH(NOLOCK), RecruitmentPlace f WITH(NOLOCK)
			WHERE a.ID=b.ID AND b.paMainID=c.BindPaMainID AND c.ptWorkAppointID=d.ID 
			AND d.RecruitmentID=e.ID AND e.RecruitmentPlaceID=f.ID
			 

			UPDATE a SET a.College = ISNULL(b.GraduateCollage, b.GraduateCollageEng), a.EduType = b.EduType, 
				a.MajorName = ISNULL(b.MajorName, b.MajorNameEng), a.Graduation = b.Graduation
			FROM @T_CvList a, cvEducation b WITH(NOLOCK)
			WHERE b.ID = a.cvEducationID

			--修改是否绑定微信
			UPDATE a SET HasWeiXin = 1
			FROM @T_CvList a, WxFans b WITH(NOLOCK), CvMain c WITH(NOLOCK)
			WHERE a.ID = c.ID
			AND c.PaMainID = b.PaMainID
			AND b.Status = 2

			UPDATE a SET a.HasViewed = 1, a.ViewDate = b.AddDate
			FROM @T_CvList a, caCvViewLog b WITH(NOLOCK)
			WHERE b.cvMainID = a.ID AND caMainID=@caMainID

			SELECT a.*,b.Description DegreeName,c.Description LivePlaceName, dbo.BirthToAge(a.BirthDay) Age,d.Description dcSalaryName
			FROM @T_CvList a
			LEFT JOIN MainDB..dcEducation b WITH(NOLOCK) ON b.ID = a.Degree
			LEFT JOIN MainDB..dcRegion c WITH(NOLOCK) ON c.ID = a.LivePlace
			LEFT JOIN dcSalary d WITH(NOLOCK) ON d.ID = a.dcSalaryID
		END
		RETURN
	END
END TRY
BEGIN CATCH
	---检查是否已经建立临时表，已经建立则删除
	BEGIN TRY
		DROP TABLE #FullText
	END TRY
	BEGIN CATCH
	END CATCH
	BEGIN TRY
		DROP TABLE #cv
	END TRY
	BEGIN CATCH
	END CATCH
	PRINT '查询时出现错误，请联系技术人员检查，错误信息：'
	PRINT Error_Message()
	PRINT Error_Number()
	PRINT Error_Line()
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[ccRecommendCvBySearchSelect0630]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ccRecommendCvBySearchSelect0630]
(
	@dcRegionID INT,					--求职地区
	@RecruitmentPlaceID INT,			--场馆ID
	@PageNumber INT,					--翻页页码
	@caMainID INT,						--企业用户ID，用来判断是否和建立联系
	@dcJobTypeIDExpect VARCHAR(50),		--职位类别
	@KeyWord NVARCHAR(20)				--关键词
)
AS
--return
SET NOCOUNT ON
BEGIN TRY
	IF @dcRegionID IS NULL
		SET @dcRegionID = ''
	
	DECLARE @KeyTemp NVARCHAR(20)
	WHILE @KeyWord LIKE '%  %'
		SET @KeyWord = REPLACE(@KeyWord, '  ', ' ')
	SET @KeyWord = LTRIM(RTRIM(dbo.SafeSQL(@KeyWord)))
	SET @KeyTemp = @KeyWord
	IF @KeyWord IS NULL OR LEN(@KeyWord) < 2
		SELECT @KeyWord = '', @KeyTemp = ''

	IF @dcJobTypeIDExpect IS NULL
		SET @dcJobTypeIDExpect = ''
	ELSE
		SET @dcJobTypeIDExpect = REPLACE(LTRIM(RTRIM(@dcJobTypeIDExpect)), ' ', ',')
	SET @dcJobTypeIDExpect = dbo.FormatIDS(@dcJobTypeIDExpect)
	
	IF @RecruitmentPlaceID IS NULL OR @RecruitmentPlaceID = 0
		SET @RecruitmentPlaceID = 0
	
	DECLARE @cpSearchConditionID AS INT
	SELECT @cpSearchConditionID=0
	DECLARE @MinId AS INT
	
	--SQLSERVER中计划任务自动删除60分钟前的数据
	SELECT TOP 1 @cpSearchConditionID = ID FROM SearchDB..cpSearchCondition WITH(NOLOCK)
	WHERE dcRegionID=@dcRegionID AND RecruitmentPlaceID=@RecruitmentPlaceID AND dcJobTypeID=@dcJobTypeIDExpect AND KeyWord=@KeyWord
	ORDER BY ID DESC

	IF ISNULL(@cpSearchConditionID, 0) = 0
		GOTO SELECTRESET	--无数据，重新搜索
	ELSE		
		GOTO GETRECORDSET	--从临时结果中提取数据

	SELECTRESET:				--从cv中搜索数据
	BEGIN
		DECLARE @SQL AS VARCHAR(8000)
		DECLARE @WHERE AS VARCHAR(8000)
		DECLARE @FROM AS VARCHAR(1000)
		SELECT @WHERE = ''
		----记录查询条件
		INSERT INTO SearchDB..cpSearchCondition(SessionID,dcRegionID,RecruitmentPlaceID,ReuseNumber,dcJobTypeIDExpect,KeyWord)
		VALUES(1,@dcRegionID,@RecruitmentPlaceID,0,@dcJobTypeIDExpect,@KeyWord)
		SET @cpSearchConditionID = @@IDENTITY

		----建立关键字搜索的临时表
		CREATE TABLE #FullText(
			CvID INT NOT NULL
		)
		----建立临时表
		CREATE TABLE #Cv(
			ID INT NOT NULL,
			RefreshDate SMALLDATETIME NOT NULL
		)

		----生成求聘职位的表变量
		DECLARE @JobTypeExpect AS VARCHAR(3000)
		SET @JobTypeExpect=''
		DECLARE @T_JobType AS TABLE(ID INT)
		IF LEN(@dcJobTypeIDExpect) > 0
		BEGIN
			DECLARE @T_Temp AS TABLE(ID INT)		--临时表，用于构建组合查询语句
			INSERT INTO @T_Temp
			SELECT * FROM dbo.fnSplit(@dcJobTypeIDExpect, ',')

			INSERT INTO @T_JobType
			SELECT DISTINCT ID FROM dcJobType WITH(NOLOCK)
			WHERE ParentId IN(SELECT ID FROM @T_TEMP) 
			OR ParentId2 in(SELECT ID FROM @T_TEMP)
			OR ID IN(SELECT ID FROM @T_TEMP)
			----生成in字符串
			SELECT @JobTypeExpect = (@JobTypeExpect + LTRIM(STR(ID) + ',')) FROM @T_JobType
			IF RIGHT(@JobTypeExpect, 1) = ','
				SET @JobTypeExpect = LEFT(@JobTypeExpect, LEN(@JobTypeExpect) - 1)
		END

		----期望职位类别
		IF LEN(@dcJobTypeIDExpect) > 0
		BEGIN
			SET @WHERE = '
				AND (g.dcJobTypeID IN(' + @JobTypeExpect +'))'
		END

		----关键词
		IF LEN(@KeyTemp) > 0 --AND @MajorName IS NULL
		BEGIN
			DECLARE @S DATETIME, @SqlFt VARCHAR(MAX)
			SELECT @S = GETDATE()

			INSERT INTO #FullText
			SELECT [key] FROM CONTAINSTABLE(CvMainPublish, *, @KeyTemp, 100000) AS KeyCv
			
			INSERT INTO #FullText
			SELECT DISTINCT cvMainID FROM CvExperiencePublish WITH(NOLOCK) WHERE ID IN(
				SELECT [key] FROM CONTAINSTABLE(CvExperiencePublish, *, @KeyTemp, 100000) AS KeyCv)
			
			INSERT INTO #FullText
			SELECT DISTINCT cvMainID FROM CvEducationPublish WITH(NOLOCK) WHERE ID IN(
				SELECT [key] FROM CONTAINSTABLE(CvEducationPublish, *, @KeyTemp, 100000) AS KeyCv)
			
			INSERT INTO #FullText
			SELECT DISTINCT cvMainID FROM CvProjectPublish WITH(NOLOCK) WHERE ID IN(
				SELECT [key] FROM CONTAINSTABLE(CvProjectPublish, *, @KeyTemp, 100000) AS KeyCv)

			INSERT INTO #FullText
			SELECT DISTINCT cvMainID FROM CvTrainingPublish WITH(NOLOCK) WHERE ID IN(
				SELECT [key] FROM CONTAINSTABLE(CvTrainingPublish, *, @KeyTemp, 100000) AS KeyCv)
            --Richard 2011.8.21增加

			INSERT INTO #FullText
			SELECT DISTINCT cvMainID FROM CvAppendixPublish WITH(NOLOCK) WHERE ID IN(
				SELECT [key] FROM CONTAINSTABLE(CvAppendixPublish, *, @KeyTemp, 100000) AS KeyCv)
            --Richard 2011.8.24增加

			SELECT @SqlFt = 'SELECT [key] FROM CONTAINSTABLE(CvMainPublish, *, ''' + @KeyTemp + ''',100000) AS KeyCv ORDER BY [key] DESC 开始：' + CONVERT(varchar(8), @S, 8) + '  结束：' + CONVERT(varchar(8), getdate(), 8)

			UPDATE SearchDB..cpSearchCondition SET SqlFT = @SqlFt WHERE ID = @cpSearchConditionID
		END

		----生成插入临时表的Sql语句
		SET @SQL = '
			INSERT INTO #Cv
			SELECT DISTINCT TOP 2000 a.ID, j.LastLoginDate'
		
		SET @FROM = '
			FROM cvmainPublish a WITH(NOLOCK) 
			INNER JOIN paMainPublish j WITH(NOLOCK) ON a.paMainId = j.Id
			INNER JOIN marketdb..RmInvitationCode b WITH(NOLOCK) ON a.paMainID=b.paMainID AND b.Valid=1
			INNER JOIN marketdb..RmProject c WITH(NOLOCK) ON b.RmProjectID=c.ID
			INNER JOIN Recruitment d WITH(NOLOCK) ON c.RecruitmentID=d.ID
			INNER JOIN RecruitmentPlace e WITH(NOLOCK) ON d.RecruitmentPlaceID=e.ID'
		
		IF @RecruitmentPlaceID = 0
			SET @FROM = @FROM + ' AND e.dcRegionID LIKE ''' + CONVERT(VARCHAR,@dcRegionID) + '%'''
		ELSE
			SET @FROM = @FROM + ' AND e.ID=' + CONVERT(VARCHAR,@RecruitmentPlaceID)

		SET @FROM = @FROM + ' AND b.AddDate>GETDATE()-90'
		IF CHARINDEX('g.',@WHERE) > 0
			SET @FROM = @FROM + ' INNER JOIN cvJobTypePublish g WITH(NOLOCK) ON a.ID=g.cvMainID'
		IF LEN(@KeyTemp) > 0 --AND @MajorName IS NULL
			SET @FROM = @FROM + ' INNER JOIN #FullText k WITH(NOLOCK) ON a.ID=k.cvID'

		SET @SQL = @SQL + @FROM + @WHERE
		SET @SQL = @SQL + ' ORDER BY j.LastLoginDate DESC, a.ID'
		--PRINT @SQL
		----把符合条件的职位全部列出
		UPDATE SearchDB..cpSearchCondition SET Sql = REPLACE(@SQL, 'INSERT INTO #Cv', ''), StartDate = GETDATE() WHERE ID = @cpSearchConditionID
		EXEC(@SQL)
		----记录查询结果总数
		DECLARE @ValidCvNumber INT
		SET @ValidCvNumber = @@ROWCOUNT		
		UPDATE SearchDB..cpSearchCondition SET ValidCvNumber = @ValidCvNumber WHERE ID = @cpSearchConditionID
		--记录查询时间
		UPDATE SearchDB..cpSearchCondition SET EndDate = GETDATE() WHERE ID = @cpSearchConditionID

		INSERT INTO SearchDB..cpSearchCvID
		SELECT TOP 2000 @cpSearchConditionID, ID FROM #Cv WITH(NOLOCK)

		DROP TABLE #Cv
		DROP TABLE #FullText
		GOTO GETRECORDSET
	END

	GETRECORDSET:
	BEGIN
		DECLARE @PageSize AS TINYINT
		SET @PageSize = 20		--每页的行数

		----返回查询数量
		UPDATE SearchDB..cpSearchCondition SET ReuseNumber = ReuseNumber + 1 WHERE ID=@cpSearchConditionID
		SELECT ValidCvNumber FROM SearchDB..cpSearchCondition WITH(NOLOCK) WHERE ID=@cpSearchConditionID
		----返回20行查询结果
		IF @PageNumber > 0
		BEGIN
			DECLARE @T_CvList AS TABLE(
				ID INT,
				cvEducationID INT,
				dcMajorID INT,
				Degree TINYINT,
				RelatedWorkYears INT,
				dcSalaryID TINYINT,
				RefreshDate SMALLDATETIME,
				LastLoginDate SMALLDATETIME,
				JobName VARCHAR(100) COLLATE Chinese_PRC_CI_AS,
				Gender BIT,
				BirthDay INT,
				LivePlace INT,
				Attachment VARCHAR(50) COLLATE Chinese_PRC_CI_AS,
				HasPhoto TINYINT,
				College NVARCHAR(50),
				EduType TINYINT,
				MajorName NVARCHAR(20),
				Graduation INT,
				HasViewed BIT,
				ViewDate SMALLDATETIME,
				LastJobTypeID INT,
				Valid TINYINT,
				PlaceName NVARCHAR(50),
				RecommendDate SMALLDATETIME,
				RecruitmentName NVARCHAR(50)
			)

			SELECT @MinId = MIN(ID) FROM SearchDB..cpSearchCvID WITH(NOLOCK) WHERE cpSearchConditionID = @cpSearchConditionID
			SET @MinId = @MinId + (@PageNumber-1) * @PageSize

			INSERT INTO @T_CvList(ID,dcMajorID,Degree,RelatedWorkYears,dcSalaryID,RefreshDate,LastLoginDate,
				JobName,Gender,BirthDay,LivePlace,LastJobTypeID,Attachment,HasPhoto,HasViewed,Valid)
			SELECT TOP 20 a.ID,a.dcMajorID,a.Degree,a.RelatedWorkYears,a.dcSalaryID,a.RefreshDate,
				j.LastLoginDate,ISNULL(a.JobName, '应届毕业生') JobName,j.Gender,j.BirthDay,j.LivePlace,a.LastJobTypeID,
				a.Attachment,j.HasPhoto,0,a.Valid FROM cvmain a WITH(NOLOCK) 
				INNER JOIN paMainPublish j WITH(NOLOCK) ON a.paMainID=j.ID 
                INNER JOIN SearchDB..cpSearchCvID b ON a.id=b.CvID
				WHERE b.cpSearchConditionID=@cpSearchConditionID AND b.ID >= @MinId 
                ORDER BY b.ID, a.ID DESC
            --RICHARD 2011-7-23 16:51分修改

			UPDATE a SET a.cvEducationID = (
						SELECT TOP 1 ID FROM cvEducation WITH(NOLOCK)
						WHERE cvEducation.cvMainID = a.ID
						AND a.Degree = cvEducation.Degree
						ORDER BY Graduation DESC)
			FROM @T_CvList a
			
			UPDATE a SET a.PlaceName = f.PlaceName, a.RecommendDate = c.AddDate, a.RecruitmentName = e.RecruitmentName
			FROM @T_CvList a, cvMain b WITH(NOLOCK), marketdb..RmInvitationCode c WITH(NOLOCK), marketdb..RmProject d WITH(NOLOCK),
			Recruitment e WITH(NOLOCK), RecruitmentPlace f WITH(NOLOCK)
			WHERE a.ID=b.ID AND b.paMainID=c.paMainID AND c.RmProjectID=d.ID AND d.RecruitmentID=e.ID AND e.RecruitmentPlaceID=f.ID

			UPDATE a SET a.College = ISNULL(b.GraduateCollage,b.GraduateCollageEng), a.EduType = b.EduType, 
				a.MajorName = ISNULL(b.MajorName,b.MajorNameEng), a.Graduation = b.Graduation
			FROM @T_CvList a, cvEducation b WITH(NOLOCK)
			WHERE b.ID = a.cvEducationID

			UPDATE a SET a.HasViewed = 1, a.ViewDate = b.AddDate
			FROM @T_CvList a, caCvViewLog b WITH(NOLOCK)
			WHERE b.cvMainID = a.ID AND caMainID=@caMainID

			SELECT * FROM @T_CvList
		END
		RETURN
	END
END TRY
BEGIN CATCH
	---检查是否已经建立临时表，已经建立则删除
	BEGIN TRY
		DROP TABLE #FullText
	END TRY
	BEGIN CATCH
	END CATCH
	BEGIN TRY
		DROP TABLE #cv
	END TRY
	BEGIN CATCH
	END CATCH
	PRINT '查询时出现错误，请联系技术人员检查，错误信息：'
	PRINT Error_Message()
	PRINT Error_Number()
	PRINT Error_Line()
END CATCH









GO
/****** Object:  StoredProcedure [dbo].[ccRecruitmentByPaMainIdSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ccRecruitmentByPaMainIdSelect]
(
	@paMainID INT
)
AS
--INSERT INTO procLog SELECT 'ccRecruitmentByPaMainIdSelect', @paMainID, GETDATE()  --using
BEGIN
	SELECT c.BeginDate, c.RecruitmentName
	FROM marketdb..ptCvInvitation a WITH(NOLOCK)
	INNER JOIN marketdb..ptWorkAppoint b WITH(NOLOCK) ON a.PtWorkAppointID1 = b.ID
	INNER JOIN Recruitment c WITH(NOLOCK) ON b.RecruitmentID = c.ID
	WHERE a.paMainID = @paMainID
END

GO
/****** Object:  StoredProcedure [dbo].[ccRecruitmentPaMainSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ccRecruitmentPaMainSelect]
(
	@RecruitmentID INT,
	@Page SMALLINT,
	@caMainID INT,
	@cpMainID INT
)
AS
BEGIN
	CREATE TABLE #T(
		TitleID BIGINT,
		ID INT,
		cvMainID INT,
		Degree TINYINT,
		RelatedWorkYears TINYINT,
		Attachment VARCHAR(50) COLLATE Chinese_PRC_CI_AS,
		IsNameHidden BIT,
		LivePlace VARCHAR(6) COLLATE Chinese_PRC_CI_AS,
		Gender BIT,
		paName NVARCHAR(20),
		BirthDay INT,
		HasPhoto TINYINT,
		adddate SMALLDATETIME,
		Valid TINYINT,
		IsViewed BIT,
		cvEducationID INT,
		College NVARCHAR(50),
		EduType TINYINT,
		MajorName NVARCHAR(20),
		Graduation INT,
		Speciality VARCHAR(MAX) COLLATE Chinese_PRC_CI_AS,
		Experience VARCHAR(MAX) COLLATE Chinese_PRC_CI_AS
	)

	INSERT INTO #T(
		TitleID,ID, cvMainID, Degree, RelatedWorkYears,
		Attachment, IsNameHidden, LivePlace, Gender, paName,
		BirthDay, HasPhoto, adddate, Valid
	)
	SELECT ROW_NUMBER() OVER (ORDER BY a.AddDate DESC) AS TitleID,
		a.ID, b.ID, b.Degree, b.RelatedWorkYears, b.Attachment, 
		b.IsNameHidden, c.LivePlace, c.Gender, c.Name AS paName, 
		c.BirthDay, c.HasPhoto, a.adddate, b.Valid
	FROM RecruitmentPaMain a WITH(NOLOCK)
	INNER JOIN paMain c WITH(NOLOCK) ON c.ID = a.paMainID
	INNER JOIN cvMain b WITH(NOLOCK) ON b.paMainID = c.ID
	WHERE b.Valid = 1 AND a.RecruitmentID = @RecruitmentID

	IF(@Page < 1)
		SET @Page = 1
	IF NOT EXISTS(SELECT 'x' FROM #t WHERE TitleID > (@Page-1)*20 AND TitleID <= @Page*20)
		SET @Page = 1

	DELETE #t WHERE TitleID <= (@Page-1) * 20 AND TitleID > @Page*20  --sean add

	UPDATE #T SET paName = LEFT(dbo.GetPaName(cvMainID, @cpMainID), 20),
		IsViewed = (SELECT TOP 1 '1' FROM caCvViewLog WITH(NOLOCK) WHERE cvMainID=#T.cvMainID AND caMainID=@caMainID)
	--sean delete WHERE TitleID > (@Page-1)*20 AND TitleID <= @Page*20

	UPDATE #T SET Speciality = (
	SELECT Speciality FROM cvMain WITH(NOLOCK)
	WHERE cvMain.ID = #T.cvMainID)
	--sean delete WHERE TitleID > (@Page-1)*20 AND TitleID <= @Page*20
	
	UPDATE #T 
	SET Experience = (
		SELECT TOP 1 ISNULL(Description, DescriptionEng) FROM cvExperience WITH(NOLOCK)
		WHERE cvExperience.cvMainID = #T.cvMainID
		ORDER BY BeginDate DESC)
	--sean delete WHERE TitleID > (@Page-1)*20 AND TitleID <= @Page*20

	UPDATE #T SET cvEducationID = (
		SELECT TOP 1 ID FROM cvEducation WITH(NOLOCK)
		WHERE cvEducation.cvMainID = #T.cvMainID
		AND #T.Degree = cvEducation.Degree
		ORDER BY Graduation DESC)
	--sean delete WHERE TitleID > (@Page-1)*20 AND TitleID <= @Page*20

	UPDATE a SET a.College = ISNULL(b.GraduateCollage, b.GraduateCollageEng), a.EduType = b.EduType, 
		a.MajorName = ISNULL(b.MajorName, b.MajorNameEng), a.Graduation = b.Graduation
	FROM #T a, cvEducation b WITH(NOLOCK)
	WHERE b.ID = a.cvEducationID 
	--sean delete AND a.TitleID > (@Page-1)*20 AND a.TitleID <= @Page*20

	SELECT COUNT(*) FROM #T WITH(NOLOCK)
	SELECT * FROM #T WITH(NOLOCK) WHERE TitleID > (@Page-1)*20 AND TitleID <= @Page*20
	
	DROP TABLE #T
END
GO
/****** Object:  StoredProcedure [dbo].[ccSearchTextLogInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----------------
--创建日期：2013-6-9
--创建人：Lucifer
--功能说明：增加一条简历搜索关键词记录
-----------------
CREATE PROCEDURE [dbo].[ccSearchTextLogInsert]
(
	@caMainID INT,
	@SearchText VARCHAR(50),
	@IP VARCHAR(15)
)
AS
BEGIN
	IF @SearchText IS NULL
		RETURN 0
	IF LEN(LTRIM(RTRIM(@SearchText))) = ''
		RETURN 0
	BEGIN TRY
		--IF CHARINDEX('公务员', @SearchText) + CHARINDEX('事业单位', @SearchText) + CHARINDEX('军队', @SearchText) = 0
		--	RETURN 0
		INSERT INTO ReportDB..SearchTextLog (caMainID, SearchText, IP) 
		VALUES(@caMainID, @SearchText, @IP) 
	END TRY
	BEGIN CATCH
		RETURN 0
	END CATCH
	RETURN 1
END














GO
/****** Object:  StoredProcedure [dbo].[ccShareMainLogByCpIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--统计企业分享量
--添加人Peter
--添加时间：2016-04-08
CREATE PROCEDURE [dbo].[ccShareMainLogByCpIDSelect]
(
	@CpMainId INT
)
AS
BEGIN
	SELECT ShareWay,COUNT(1) cnt,SUM(ClickCount) clickcnt 
	FROM logdb..sharemainlog WITH(NOLOCK) 
	WHERE PageMark = 3 AND shareman = @CpMainId 
	GROUP BY ShareWay
	
	SELECT TOP 50 * 
	FROM logdb..sharemainlog WITH(NOLOCK)
	WHERE PageMark = 3
	AND shareman = @CpMainId 
	ORDER BY AddDate DESc
END



GO
/****** Object:  StoredProcedure [dbo].[ccShareMainLogByStatisticsSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--统计企业职位分享量------------------
--添加人Harry -----------------------
--添加时间：2015-1-14---------------
CREATE PROCEDURE [dbo].[ccShareMainLogByStatisticsSelect]
(
	@CpMainId INT
)
AS
BEGIN
	CREATE TABLE #T
	(
		PageId INT,
		PageName NVARCHAR(50),
		PageMark VARCHAR(10),
		SecondId VARCHAR(30),
		WeiBo  INT DEFAULT 0,
		RenRen INT DEFAULT 0,
		QZone INT DEFAULT 0,
		QWeiBo INT DEFAULT 0,
		QQ INT DEFAULT 0,
		Weixin INT DEFAULT 0
	)
	INSERT INTO #T(PageId,PageName,SecondId,PageMark)
	SELECT DISTINCT Id, Name,SecondId,1
	FROM Maindb..Job WITH (NOLOCK)
	WHERE CpMainId = CAST(@CpMainId AS VARCHAR) 
	AND Valid=1 

	INSERT INTO #T(PageId,PageName,PageMark)
	VALUES(CAST(@CpMainId AS VARCHAR),'公司招聘页面','2')

	CREATE TABLE #1
	(
		PageId INT,
		PageMark VARCHAR(10),
		ShareWay INT,
		ShareNumber INT DEFAULT 0
	)
	INSERT INTO #1
	SELECT PageId, PageMark, ShareWay, COUNT(1)
	FROM LogDb..ShareMainLog WITH (NOLOCK) 
	WHERE ShareBy = 2
	AND ShareMode = 1 
	AND ShareMan = @CpMainId
	GROUP BY PageId, PageMark, ShareWay

	UPDATE a 
	SET a.RenRen = (SELECT b.ShareNumber FROM #1 b  WITH (NOLOCK)  WHERE b.PageId = a.PageId AND a.PageMark = b.PageMark  AND b.shareWay = 3),
		a.QQ = (SELECT b.ShareNumber FROM #1 b WITH (NOLOCK)  WHERE b.PageId = a.PageId AND a.PageMark = b.PageMark  AND b.shareWay = 6),
		a.WeiBo = (SELECT b.ShareNumber FROM #1 b WITH (NOLOCK)  WHERE b.PageId = a.PageId AND a.PageMark = b.PageMark  AND b.shareWay = 1),
		a.QZone = (SELECT b.ShareNumber FROM #1 b WITH (NOLOCK)  WHERE b.PageId = a.PageId AND a.PageMark = b.PageMark  AND b.shareWay = 4),
		a.QWeiBo = (SELECT b.ShareNumber FROM #1 b WITH (NOLOCK)  WHERE b.PageId = a.PageId AND a.PageMark = b.PageMark  AND b.shareWay = 5),
		a.Weixin = (SELECT b.ShareNumber FROM #1 b WITH (NOLOCK)  WHERE b.PageId = a.PageId AND a.PageMark = b.PageMark  AND b.shareWay = 2)
	FROM #T a

	SELECT  * FROM  #T
END

GO
/****** Object:  StoredProcedure [dbo].[ccShareMainLogSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ccShareMainLogSelect]
(
	@CpMainId INT
)
AS
BEGIN
	SELECT a.Shareway, a.Adddate, b.Name, b.Secondid, a.PageMark, a.PageId  
	FROM Logdb..ShareMainLog a WITH (NOLOCK)
	LEFT JOIN Maindb..Job b WITH (NOLOCK)
	ON a.PageId=b.Id 
	WHERE a.ShareBy = '2'
	AND a.ShareMode = '1'
	AND a.ShareMan = @CpMainId 
	ORDER BY a.Adddate DESC
END


GO
/****** Object:  StoredProcedure [dbo].[ccsmsMessageLogCountByCaMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.30
--创建人：Nick
--说明：//得到面试通知数量
--#####################################################
CREATE PROCEDURE [dbo].[ccsmsMessageLogCountByCaMainIDSelect]
(
	@ID INT
)
AS
BEGIN
	SELECT ISNULL(SUM(SmsNumber), 0) Cnt 
	FROM ExInterView WITH(NOLOCK)
	WHERE JobId IN(SELECT ID FROM Job WITH(NOLOCK) WHERE cpMainId = @Id)
	AND AddDate > CONVERT(VARCHAR(10), GETDATE() - 29, 120)
	/*
	SELECT Cnt = COUNT(*) 
	FROM smsMessageLog WITH(NOLOCK) 
	WHERE caMainId = @ID AND AddDate > CONVERT(VARCHAR(10), GETDATE() - 29, 120) 
	AND MsgType IN(101,105)
	*/
END

GO
/****** Object:  StoredProcedure [dbo].[ccValidViPlanDateSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2014.10.30
--创建人：John
--说明：获取企业发送视频面试通知时的面试时间选项
--#####################################################
CREATE PROCEDURE [dbo].[ccValidViPlanDateSelect]
(
	@caMainID INT
)
AS
BEGIN
	SELECT * 
	FROM ( 
		SELECT TOP 1 id,begindate,1 orderby 
		FROM viroom 
		WHERE enddate IS NULL 
			AND camainid = @caMainID 
		UNION 
		SELECT TOP 50 id,interviewdate,2 orderby 
		FROM viplan 
		WHERE interviewdate > GETDATE() 
			AND iscancel = 0 
			AND camainid = @caMainID 
		) a 
	ORDER BY orderby ,begindate
END


GO
/****** Object:  StoredProcedure [dbo].[ccvCpMainActiveQuotaByIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.31
--创建人：Nick
--说明：获取企业简历下载数 和 已经使用的简历下载数
--#####################################################
CREATE PROCEDURE [dbo].[ccvCpMainActiveQuotaByIDSelect]
(
	@CpMainID VARCHAR(20)
)
AS
BEGIN TRY
	SELECT ActiveQuota,RemainQuota FROM vCpMain WITH(NOLOCK) WHERE Id=@CpMainID
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[ccvCpMainByIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2014.10.30
--创建人：Nick
--说明：获取状态
--修改：harry2017-6-6 增加短信RemainSmsQuota ,SmsQuota配额
--修改：harry2018-9-21 增加人才测评配额
--#####################################################
CREATE PROCEDURE [dbo].[ccvCpMainByIDSelect]
(
	@ID INT
)
AS
BEGIN
	SELECT VipDate, ActiveQuota, MaxJobNumber, MaxUserNumber, RemainQuota, RemainSmsQuota, SmsQuota, remainJobRefreshQuota,jobRefreshQuota,AssessReportQuota, RemainAssessReportQuota 
	FROM vCpMain WITH(NOLOCK) 
	WHERE Id=@ID
END

GO
/****** Object:  StoredProcedure [dbo].[ccViPlanByCaMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.30
--创建人：John
--说明：企业获取自己的未过期的面试计划
--#####################################################
CREATE PROCEDURE [dbo].[ccViPlanByCaMainIDSelect]
(
	@caMainID INT
)
AS
BEGIN
	SELECT TOP 500 a.ID,InterviewDate,IsCancel,b.name,
		(
			SELECT COUNT(*) 
			FROM viplaninvitelog 
			WHERE viplanid = a.id 
			AND addtype = 0
		) cnt1,
		(
			SELECT COUNT(*) 
			FROM viplaninvitelog 
			WHERE viplanid = a.id 
			AND addtype = 1
		) cnt2 
	FROM viplan a,caMain b 
	WHERE a.camainid = b.id 
	AND interviewdate > GETDATE() 
	AND IsCancel = 0 
	AND camainid = @caMainID 
	ORDER BY interviewdate
END


GO
/****** Object:  StoredProcedure [dbo].[ccViPlanExpiredByCaMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2014.10.30
--创建人：John
--说明：企业获取自己的已过期的面试计划
--#####################################################
CREATE PROCEDURE [dbo].[ccViPlanExpiredByCaMainIDSelect]
(
	@caMainID INT
)
AS
BEGIN
	SELECT TOP 500 a.ID,InterviewDate,IsCancel,b.name,
		(
			SELECT COUNT(*) 
			FROM viplaninvitelog 
			WHERE viplanid = a.id 
			AND addtype = 0
		) cnt1,
		(
			SELECT COUNT(*) 
			FROM viplaninvitelog 
			WHERE viplanid = a.id 
			AND addtype = 1
		) cnt2 
	FROM viplan a,caMain b 
	WHERE a.camainid = b.id 
	AND (interviewdate < GETDATE() OR IsCancel = 1)
	AND camainid = @caMainID 
	ORDER BY interviewdate DESC
END


GO
/****** Object:  StoredProcedure [dbo].[ccViPlanInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ccViPlanInsert]
(
	@CaMainID INT, 
	@InterviewDate SMALLDATETIME
)
AS
BEGIN
	INSERT INTO viplan (CaMainID	 ,InterviewDate) select @CaMainID ,@InterviewDate 
	Return @@IDENTITY 
END











GO
/****** Object:  StoredProcedure [dbo].[ccViPlanInviteLog30DaysSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2014.10.30
--创建人：John
--说明：30天内有没有邀请过
--#####################################################
CREATE PROCEDURE [dbo].[ccViPlanInviteLog30DaysSelect]
(
	@cvMainID INT,
	@jobID INT
)
AS
BEGIN
	SELECT TOP 1 * 
	FROM viplaninvitelog 
	WHERE adddate > GETDATE()-30 
		AND cvMainID = @cvMainID 
		AND jobid = @jobID
END


GO
/****** Object:  StoredProcedure [dbo].[ccVIPlanInviteLogSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[ccVIPlanInviteLogSelect]
(
	@WHERE VARCHAR(1000),
    @caMainID INT
)
AS
BEGIN
	CREATE TABLE #t(
		paMainID INT,				
		cvmainid INT,			
		Name NVARCHAR(10),
		JobName NVARCHAR(50),
		AddDate SMALLDATETIME,
		InterviewDate SMALLDATETIME,
		Degree NVARCHAR(10),
		RelatedWorkYears TINYINT,
		LivePlace NVARCHAR(20) COLLATE Chinese_PRC_CI_AS,
		Gender BIT,
		paName NVARCHAR(20),
		BirthDay INT,
		HasPhoto TINYINT,
		Attachment VARCHAR(50) COLLATE Chinese_PRC_CI_AS,
		IsNameHidden BIT,
		Valid TINYINT,
		AddType  BIT			
	)
	DECLARE @SQL AS VARCHAR(2000)
	DECLARE @SQL2 AS VARCHAR(2000)
	SET @SQL='
			INSERT INTO #t(paMainID,cvMainID,Name,JobName,AddDate,InterviewDate,AddType)
			SELECT 
				c.ID,b.ID,c.Name,d.name,a.AddDate,e.InterviewDate,a.AddType
				From viplaninvitelog  a WITH(NOLOCK)												
				INNER JOIN cvMain b WITH(NOLOCK) ON a.cvMainID=b.ID
				INNER JOIN paMain c WITH(NOLOCK) ON c.ID=b.paMainID
				INNER JOIN job d WITH(NOLOCK) ON a.jobid=d.id 
				INNER JOIN VIPlan e WITH(NOLOCK) ON a.VIPlanID=e.id 
			'	
	SET @SQL=@SQL + '
		WHERE e.camainid= '+ltrim(str(@caMainID))

	IF LEN(@WHERE)>0
		SET @SQL=@SQL + @WHERE
	--PRINT @sql
	EXEC(@SQL)
	
	DECLARE @cpMainID int
	SELECT @cpMainID=cpMainid from caMain where id=@caMainID
	
	UPDATE #t SET Name=LEFT(dbo.GetPaName(cvMainID, @cpMainID), 20),RelatedWorkYears = a.RelatedWorkYears,Attachment = a.Attachment,
		IsNameHidden = a.IsNameHidden,LivePlace = c.FullName,Gender = b.Gender,
		BirthDay = b.BirthDay,HasPhoto = b.HasPhoto,Valid = a.Valid,Degree=d.Description
	FROM cvMain a WITH(NOLOCK) INNER JOIN paMain b ON a.paMainID = b.ID INNER JOIN dcregion c WITH(NOLOCK) ON  b.liveplace=c.id INNER JOIN dceducation d ON a.Degree=d.id
	WHERE a.ID = #t.cvMainID 
	
	IF CHARINDEX('interviewdate<getdate',@WHERE)>0
		SELECT * FROM #t WITH(NOLOCK)  ORDER BY InterviewDate DESC,AddDATE
	ELSE
		SELECT * FROM #t WITH(NOLOCK)  ORDER BY InterviewDate ,AddDATE
	DROP TABLE #t
END


GO
/****** Object:  StoredProcedure [dbo].[ccViPlanInviteLogViewDateUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2014.10.30
--创建人：John
--说明：企业修改未查看面试计划邀请记录的查看时间
--#####################################################
CREATE PROCEDURE [dbo].[ccViPlanInviteLogViewDateUpdate]
(
	@caMainID INT
)
AS
BEGIN
	UPDATE a SET viewdate = GETDATE() 
	FROM viplaninvitelog a,viplan b 
	WHERE a.viplanid = b.id 
		AND addtype = 0 
		AND viewdate IS NULL 
		AND camainid = @caMainID
END


GO
/****** Object:  StoredProcedure [dbo].[ccViPlanIsCancelUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2014.10.30
--创建人：John
--说明：面试计划取消
--#####################################################
CREATE PROCEDURE [dbo].[ccViPlanIsCancelUpdate]
(
	@caMainID INT,
	@id INT
)
AS
BEGIN
	UPDATE viplan SET IsCancel = 1 WHERE id = @id AND caMainID = @caMainID
END


GO
/****** Object:  StoredProcedure [dbo].[ccViPlanTopFirstSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2014.10.30
--创建人：John
--说明：企业获取一条今天要进行的面试计划
--#####################################################
CREATE PROCEDURE [dbo].[ccViPlanTopFirstSelect]
(
	@caMainID INT
)
AS
BEGIN
	SELECT TOP 1 interviewdate 
	FROM viplan 
	WHERE CONVERT(VARCHAR(10),interviewdate,112) = CONVERT(VARCHAR(10),GETDATE(),112) 
		AND interviewdate > GETDATE() 
		AND iscancel = 0 
		AND caMainid = @caMainID
END


GO
/****** Object:  StoredProcedure [dbo].[ccViRoomNotOverByCaMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2014.10.30
--创建人：John
--说明：检查该公司是否还有未结束的面试
--#####################################################
CREATE PROCEDURE [dbo].[ccViRoomNotOverByCaMainIDSelect]
(
	@caMainID INT
)
AS
BEGIN
	SELECT TOP 1 * FROM viRoom WITH(NOLOCK) WHERE caMainID=@caMainID AND EndDate IS NULL
END


GO
/****** Object:  StoredProcedure [dbo].[FaxSendInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[FaxSendInsert]
(
	@companyId INT,
	@manageruserId INT,
	@FaxNumber VARCHAR(20),
	@FileName VARCHAR(50),
	@Passage TINYINT
)
AS
DECLARE @MaxID AS INT
BEGIN TRY
	INSERT INTO FaxSend
	(companyId,manageruserId,FileName,FaxNumber,Passage)
	VALUES
	(@companyId,@manageruserId,@FileName,@FaxNumber,@Passage)
	SET @MaxId = @@IDENTITY
END TRY
BEGIN CATCH
	GOTO ERR
END CATCH
RETURN @MaxID
ERR:
BEGIN
	RETURN 0
END














GO
/****** Object:  StoredProcedure [dbo].[GetJobListByJobFinderIDApp]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[GetJobListByJobFinderIDApp]
(
	@paJobFinderID INT
)
AS
BEGIN
	SELECT TOP 30 a.ID, a.cpMainID, a.caMainID, a.Name as JobName, a.dcJobTypeID, 
		a.dcJobTypeIDMinor, a.NeedNumber, a.dcSalaryID, a.EmployType, 
		a.dcRegionID, a.Responsibility, a.Demand, a.dcEducationID, 
		a.MinExperience, a.MinAge, a.MaxAge, a.IssueDate, a.IssueEND, 
		a.IsDelete, a.AddDate, a.RefreshDate, a.Welfare1, a.Welfare2, a.Welfare3,
		a.Welfare4, a.Welfare5, a.Welfare6, a.Welfare7, a.Welfare8,
		a.Welfare9, a.Welfare10, a.Welfare11, a.Welfare12, a.Welfare13,
		a.Welfare14, a.Welfare15, a.Welfare16, a.Welfare17, a.Welfare18, a.Welfare19,
		a.SecondId EnJobID, b.SecondId EnCpMainID, 
		a.LastModifyDate, b.Name cpName, b.dcCompanySizeID, 
		b.HasLicence, b.UnLimitedDate, b.BalanceDate, b.Balance, 
		b.MemberType, '' cpIndustry, b.IsRefreshed, ISNULL(d.IsOnline, 0) IsOnline, d.IsVi, d.ViPlanId, d.InterviewDate, e.FullName Region	
	FROM JobPublish a WITH(NOLOCK)
	INNER JOIN cpMainPublish b WITH(NOLOCK) ON a.cpMainID = b.ID 
	INNER JOIN JobSubScription c WITH(NOLOCK) ON a.ID = c.JobID
	INNER JOIN dcRegion e WITH(NOLOCK) ON a.dcRegionId = e.Id
	LEFT JOIN caOnline d WITH(NOLOCK) ON a.caMainId = d.caMainId
	WHERE c.paJobFinderID = @paJobFinderID
	ORDER BY a.RefreshDate DESC
END
GO
/****** Object:  StoredProcedure [dbo].[info_datereportCpUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[info_datereportCpUpdate]
(
	@cpMainID INT,
	@AddMan INT,
	@province_id VARCHAR(32)
)
AS
BEGIN TRAN
	DECLARE @ID AS INT
	BEGIN TRY
		SET @ID=0
		SELECT TOP 1 @ID=province_id FROM info_datereport WITH(NOLOCK)
		WHERE infomanager_id=@AddMan
		AND province_id=@province_id
		AND CountDate = CONVERT(VARCHAR(8), GETDATE(), 112)

		IF @ID=0
			INSERT INTO info_datereport(province_id,infomanager_id,countdate)
			VALUES(@province_id,@AddMan, CONVERT(VARCHAR(8), GETDATE(), 112))

		UPDATE info_datereport SET realcompany=realcompany + 1 
		WHERE infomanager_id=@AddMan
		AND province_id=@province_id
		AND CountDate = CONVERT(VARCHAR(8), GETDATE(), 112)

		UPDATE cpMain SET RegisterMode=11 WHERE ID=@cpMainID
	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH
COMMIT TRAN
RETURN 1
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END














GO
/****** Object:  StoredProcedure [dbo].[mblAdverprojectBannerByProvinceIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[mblAdverprojectBannerByProvinceIDSelect]
(
	@regionID VARCHAR(20),
	@Type INT
)
AS
BEGIN
	SELECT * FROM adverproject WHERE type=@Type 
	AND GETDATE() BETWEEN BeginTime 
	AND EndTime AND province_id=@regionID AND valid=1 ORDER BY AddDate DESC
END

GO
/****** Object:  StoredProcedure [dbo].[mblAdverprojectByProvinceIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--—##################################################### 
--—创建时间：2014.11.7 
--—创建人：Nick 
--—说明：获取最新的启动图片 
--—##################################################### 
CREATE PROCEDURE [dbo].[mblAdverprojectByProvinceIDSelect] 
( 
	@regionID VARCHAR(20) 
) 
AS 
BEGIN 
	SELECT * FROM adverproject
	WHERE type in(23,24)
	AND GETDATE() BETWEEN BeginTime
	AND EndTime AND province_id=@regionID
	AND Valid=1
	ORDER BY Type DESC
END
GO
/****** Object:  StoredProcedure [dbo].[mblAppRunLogInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/**
*Android 个人App安装运行状态信息
*Peter 2014-01-17 10:26
*/
CREATE PROCEDURE [dbo].[mblAppRunLogInsert]
(
	@DeviceID VARCHAR(50),
	@Imei VARCHAR(50),
	@AppId SMALLINT,
	@AccountID INT,
	@Ip VARCHAR(15)
)
AS
BEGIN
	INSERT INTO AppRunLog (DeviceId, Imei, AppId, AccountId, Ip)
	SELECT @DeviceId, @Imei, @AppId, @AccountId, @Ip
END










GO
/****** Object:  StoredProcedure [dbo].[mblCaCvContactByCvViewSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[mblCaCvContactByCvViewSelect]
(	
	@cpMainID INT, 
	@JobID INT, 
	@caMainID INT, 
	@cvMainID INT
)
AS
SET NOCOUNT ON
BEGIN
	IF @JobID > 0 
	BEGIN
		--查询申请记录
		SELECT TOP 1 a.ID, a.AddDate, a.Reply, b.ID JobID, b.Name
		FROM exJobApply a WITH(NOLOCK) 
		INNER JOIN Job b WITH(NOLOCK) ON a.JobId = b.Id
		WHERE a.cvMainId = @cvMainID
		AND b.ID = @JobID
		AND CompanyDeleted = 0
		ORDER BY a.ID DESC

		--查询最近3个月的发送面试通知记录	
		SELECT TOP 1 a.AddDate, b.ID, b.Name
		FROM ExInterview a WITH(NOLOCK) 
		INNER JOIN Job b WITH(NOLOCK)
		ON a.JobId = b.Id
		WHERE a.cvMainId =@cvMainID
		AND b.ID = @JobID
		AND a.AddDate > DATEADD(MONTH, -3, GETDATE())
		ORDER BY a.ID DESC

		--查询收藏记录
		SELECT TOP 1 a.AddDate, b.ID, b.Name
		FROM caFavorate a WITH(NOLOCK) 
		INNER JOIN Job b WITH(NOLOCK)
		ON a.JobId = b.Id
		WHERE a.cvMainId = @cvMainID
		AND b.ID = @JobID
		ORDER BY a.ID DESC

		--查询2周内浏览简历记录
		SELECT TOP 1 AddDate
		FROM CaCvViewLog a WITH(NOLOCK) 
		WHERE caMainID IN(SELECT ID FROM caMain WITH(NOLOCK) WHERE cpMainID = @cpMainID)
		AND cvMainID = @cvMainID
		AND AddDate>DATEADD(DAY, -14, GETDATE())
	END
	ELSE
	BEGIN
		IF @cpMainID > 0
		BEGIN
			--查询最近2个月的申请记录
			SELECT TOP 1 a.ID, a.AddDate, a.Reply, b.ID JobID, b.Name
			FROM exJobApply a WITH(NOLOCK) 
			INNER JOIN Job b WITH(NOLOCK)
			ON a.JobId = b.Id
			WHERE a.cvMainId =@cvMainID
			AND b.cpMainID = @cpMainID
			AND CompanyDeleted = 0
			ORDER BY a.ID DESC

			--查询最近3个月的发送面试通知记录	
			SELECT TOP 1 a.AddDate, b.ID, b.Name
			FROM ExInterview a WITH(NOLOCK) 
			INNER JOIN Job b WITH(NOLOCK)
			ON a.JobId = b.Id
			WHERE a.cvMainId =@cvMainID
			AND b.cpMainID = @cpMainID
			AND a.AddDate > DATEADD(MONTH, -3, GETDATE())
			ORDER BY a.ID DESC

			--查询收藏记录
			SELECT TOP 1 a.AddDate, b.ID, b.Name
			FROM caFavorate a WITH(NOLOCK) 
			INNER JOIN Job b WITH(NOLOCK)
			ON a.JobId = b.Id
			WHERE a.cvMainId =@cvMainID
			AND b.cpMainID = @cpMainID
			ORDER BY a.ID DESC

			--查询2周内浏览简历记录
			SELECT TOP 1 AddDate
			FROM CaCvViewLog a WITH(NOLOCK) 
			WHERE caMainID IN(SELECT ID FROM caMain WITH(NOLOCK) WHERE cpMainID = @cpMainID)
			AND cvMainID = @cvMainID
			AND AddDate>DATEADD(DAY, -14, GETDATE())
		END
		ELSE
		BEGIN
			--查询最近2个月的申请记录
			SELECT TOP 1 a.ID, a.AddDate, a.Reply, b.ID JobID, b.Name
			FROM exJobApply a WITH(NOLOCK) 
			INNER JOIN Job b WITH(NOLOCK)
			ON a.JobId = b.Id
			WHERE a.cvMainId =@cvMainID
			AND b.caMainID = @caMainID
			AND CompanyDeleted = 0
			ORDER BY a.ID DESC
			--查询最近3个月的发送面试通知记录	
			SELECT TOP 1 a.AddDate, b.ID, b.Name
			FROM ExInterview a WITH(NOLOCK) 
			INNER JOIN Job b WITH(NOLOCK)
			ON a.JobId = b.Id
			WHERE a.cvMainId =@cvMainID
			AND b.caMainID = @caMainID
			AND a.AddDate > DATEADD(MONTH, -3, GETDATE())
			ORDER BY a.ID DESC
			--查询收藏记录
			SELECT TOP 1 a.AddDate, b.ID, b.Name
			FROM caFavorate a WITH(NOLOCK) 
			INNER JOIN Job b WITH(NOLOCK)
			ON a.JobId = b.Id
			WHERE a.cvMainId =@cvMainID
			AND b.caMainID = @caMainID
			ORDER BY a.ID DESC
			--查询2周内浏览简历记录
			SELECT TOP 1 AddDate
			FROM CaCvViewLog a WITH(NOLOCK) 
			WHERE caMainID = @caMainID 
			AND cvMainID IN(SELECT ID FROM caMain WITH(NOLOCK) WHERE cpMainID = @cpMainID)
			AND AddDate>DATEADD(DAY, -14, GETDATE())
		END		
	END	
END
GO
/****** Object:  StoredProcedure [dbo].[mblCaCvViewLogSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[mblCaCvViewLogSelect]
(
	@paMainID AS INT,
	@PageNum AS INT,
	@PageSize AS INT
)
AS
BEGIN
	DECLARE @COUNT INT
	SELECT @COUNT = COUNT(*) 
	FROM CaCvViewLog a WITH(NOLOCK), caMain b WITH(NOLOCK), cpMain c WITH(NOLOCK)
	WHERE a.caMainID = b.ID
	AND b.cpMainID=c.ID
	AND a.cvMainId IN(SELECT ID FROM CvMain WITH(NOLOCK) WHERE paMainId = @PaMainID)

	IF @COUNT > 200
		SET @COUNT = 200

	SELECT *, @COUNT AS cnt 
	FROM (SELECT TOP 200 ROW_NUMBER() OVER (ORDER BY a.AddDate DESC) AS Rows,
			c.Name CompanyName, a.AddDate, b.cpMainID ,c.secondid encpmainid
			FROM CaCvViewLog a WITH(NOLOCK), caMain b WITH(NOLOCK), cpMain c WITH(NOLOCK)
			WHERE a.caMainID = b.ID AND b.cpMainID=c.ID
			AND a.cvMainId IN(SELECT ID FROM CvMain WITH(NOLOCK) WHERE paMainId = @PaMainID)
	) AS a 
	WHERE a.Rows BETWEEN (@PageNum - 1) * @PageSize + 1 AND @PageNum * @PageSize ORDER BY Rows
END










GO
/****** Object:  StoredProcedure [dbo].[mblcaDownloadLogSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

 --20160108 nick 加入是否绑定微信
CREATE PROCEDURE [dbo].[mblcaDownloadLogSelect]
(
	@cpMainID INT, 
	@WHERE VARCHAR(1000), 
	@ORDER VARCHAR(100), 
	@Page SMALLINT, 
	@caMainID INT
)
AS
SET NOCOUNT ON
BEGIN
	SET @Where = dbo.SafeSql(@Where)
	SET @ORDER = dbo.SafeSql(@Order)

	DECLARE @SQL VARCHAR(2000)
	CREATE TABLE #T(
		TitleID BIGINT, 
		cvMainID INT, 
		caOrderID INT NULL, 
		paMainID INT, 
		IP VARCHAR(39) COLLATE Chinese_PRC_CI_AS NOT NULL, 
		RemainQuota SMALLINT NULL, 
		AddDate SMALLDATETIME, 
		Degree TINYINT, 
		RelatedWorkYears TINYINT, 
		Attachment VARCHAR(50) COLLATE Chinese_PRC_CI_AS , 
		IsNameHidden BIT, 
		LivePlace VARCHAR(6) COLLATE Chinese_PRC_CI_AS , 
		Gender BIT, 
		paName NVARCHAR(20), 
		BirthDay INT, 
		HasPhoto TINYINT, 
		Valid TINYINT, 
		HasJobApply BIT, 
		HasInterview BIT, 
		HasRemark BIT, 
		HasFavorate BIT, 
		cvEducationID INT, 
		College NVARCHAR(50), 
		EduType TINYINT, 
		MajorName NVARCHAR(20), 
		Graduation INT, 
		Speciality VARCHAR(MAX) COLLATE Chinese_PRC_CI_AS, 
		Experience VARCHAR(MAX) COLLATE Chinese_PRC_CI_AS, 
		MobileVerifyDate SMALLDATETIME, 
		IsOnline BIT, 
		HasWeiXin BIT, 
		PaPhoto VARCHAR(50), 
		dcSalaryID SMALLINT, 
		SecondId VARCHAR(10)
	)
	SET @SQL = '
		INSERT INTO #T(TitleID, cvMainID, caOrderID, paMainID, RemainQuota, IP, AddDate, Degree,
			RelatedWorkYears, Attachment, IsNameHidden, LivePlace, Gender, BirthDay, HasPhoto,
			Valid, MobileVerifyDate, IsOnline, dcSalaryID, SecondId)
		SELECT ROW_NUMBER() OVER (ORDER BY ' + @ORDER + ') AS TitleID, a.* FROM (
		SELECT 
			a.cvMainID, NULL caOrderID, c.ID paMainID, NULL RemainQuota, a.IP, a.AddDate, b.Degree,
			b.RelatedWorkYears, b.Attachment, b.IsNameHidden, c.LivePlace, c.Gender, c.BirthDay, c.HasPhoto,
			b.Valid, c.MobileVerifyDate, dbo.GetPaOnlineStatus(c.ID) IsOnline, b.dcSalaryID, b.SecondId
		FROM caDailyGiftLog a WITH(NOLOCK)
		INNER JOIN cvMain b WITH(NOLOCK) ON b.ID = a.cvMainID
		INNER JOIN paMain c WITH(NOLOCK) ON c.ID = b.paMainID
		WHERE cpMainID = ' + LTRIM(STR(@cpMainID)) + ' ' + REPLACE(@WHERE, 'a.caOrderID', '1') + '
		AND a.AddDate > DATEADD(YEAR, -2, GETDATE())
		UNION
		SELECT 
			a.cvMainID, a.caOrderID, c.ID paMainID, a.RemainQuota, a.IP, a.AddDate, b.Degree,
			b.RelatedWorkYears, b.Attachment, b.IsNameHidden, c.LivePlace, c.Gender, c.BirthDay, c.HasPhoto,
			b.Valid, c.MobileVerifyDate, dbo.GetPaOnlineStatus(c.ID) IsOnline, b.dcSalaryID, b.SecondId
		FROM caActiveLog a WITH(NOLOCK)
		INNER JOIN cvMain b WITH(NOLOCK) ON b.ID = a.cvMainID
		INNER JOIN paMain c WITH(NOLOCK) ON c.ID = b.paMainID
		WHERE cpMainID = ' + LTRIM(STR(@cpMainID)) + '
		AND a.AddDate > DATEADD(YEAR, -2, GETDATE()) ' + @WHERE + ') a'

	--PRINT @SQL
	EXEC(@SQL)

	IF(@Page < 1)
		SET @Page = 1
	IF NOT EXISTS(SELECT 'x' FROM #t WHERE TitleID > (@Page-1)*20 AND  TitleID <= @Page*20)
		SET @Page = 1

	UPDATE #T SET paName = LEFT(dbo.GetPaName(cvMainID, @cpMainID), 20), 
		HasJobApply = (SELECT TOP 1 '1' FROM exJobApply a WITH(NOLOCK) INNER JOIN Job b WITH(NOLOCK) ON a.JobID=b.ID WHERE a.CompanyDeleted=0 AND b.caMainID=@caMainID AND cvMainID=#T.cvMainID), 
		HasInterview = (SELECT TOP 1 '1' FROM exInterview a WITH(NOLOCK) INNER JOIN Job b WITH(NOLOCK) ON a.JobID=b.ID WHERE a.CompanyDeleted=0 AND b.caMainID=@caMainID AND cvMainID=#T.cvMainID), 
		HasRemark = (SELECT TOP 1 '1' FROM caCvRemark WITH(NOLOCK) WHERE caMainID=@caMainID AND cvMainID=#T.cvMainID), 
		HasFavorate = (SELECT TOP 1 '1' FROM caFavorate WITH(NOLOCK) WHERE caMainID=@caMainID AND cvMainID=#T.cvMainID)
	WHERE TitleID > (@Page-1)*20 AND TitleID <= @Page*20
	
	UPDATE #T SET Speciality = (
		SELECT Speciality FROM cvMain WITH(NOLOCK)
		WHERE cvMain.ID = #T.cvMainID)
	WHERE TitleID > (@Page-1)*20 AND TitleID <= @Page*20
	
	UPDATE #T SET PaPhoto = (
		SELECT TOP 1 PhotoProcessed 
		FROM paPhoto a WITH(NOLOCK INDEX(IX_paPhoto_paMainId)) 
		WHERE paMainID = (SELECT PaMainID FROM cvMain WITH(NOLOCK) WHERE ID = #T.cvMainID))
	WHERE TitleID > (@Page-1)*20 AND TitleID <= @Page*20
	
	UPDATE #T SET Experience = (
		SELECT TOP 1 ISNULL(Description, DescriptionEng) FROM cvExperience WITH(NOLOCK)
		WHERE cvExperience.cvMainID = #T.cvMainID
		ORDER BY BeginDate DESC)
	WHERE TitleID > (@Page-1)*20 AND TitleID <= @Page*20

	UPDATE #T SET cvEducationID = (
		SELECT TOP 1 ID FROM cvEducation WITH(NOLOCK)
		WHERE cvEducation.cvMainID = #T.cvMainID
		AND #T.Degree = cvEducation.Degree
		ORDER BY Graduation DESC)
	WHERE TitleID > (@Page-1)*20 AND TitleID <= @Page*20

	UPDATE a SET a.College = ISNULL(b.GraduateCollage, b.GraduateCollageEng), a.EduType = b.EduType, 
		a.MajorName = ISNULL(b.MajorName, b.MajorNameEng), a.Graduation = b.Graduation
	FROM #T a, cvEducation b WITH(NOLOCK)
	WHERE b.ID = a.cvEducationID AND a.TitleID > (@Page-1)*20 AND a.TitleID <= @Page*20

	--修改是否绑定微信
	UPDATE a SET HasWeiXin = 1
	FROM #T a, WxFans b WITH(NOLOCK), CvMain c WITH(NOLOCK)
	WHERE a.CvMainID = c.ID
	AND c.PaMainID = b.PaMainID
	AND b.Status = 2
	AND a.TitleID > (@Page-1)*20 AND  TitleID <= @Page*20

	SELECT COUNT(*) FROM #T WITH(NOLOCK)
	
	SELECT a.*,b.Description DegreeName,c.MapBarName LivePlaceName, dbo.BirthToAge(a.BirthDay) Age,d.Description dcSalaryName
	FROM #T a WITH(NOLOCK) 
	LEFT JOIN dcEducation b WITH(NOLOCK) ON b.ID = a.Degree
	LEFT JOIN dcRegion c WITH(NOLOCK) ON c.ID = a.LivePlace
	LEFT JOIN dcSalary d WITH(NOLOCK) ON d.ID = a.dcSalaryID
	WHERE a.TitleID > (@Page-1)*20 AND a.TitleID <= @Page*20
	
	DROP TABLE #T
END


GO
/****** Object:  StoredProcedure [dbo].[mblcaFavorateSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[mblcaFavorateSelect]
(
	@WHERE VARCHAR(1000), 
	@Order VARCHAR(100), 
	@Page SMALLINT, 
	@cpMainID INT, 
	@caMainID INT
)
AS
SET NOCOUNT ON
IF NOT EXISTS(SELECT 'x' FROM caMain WITH(NOLOCK) WHERE Id = @caMainId AND cpMainId = @cpMainId)
	RETURN
BEGIN
	SELECT @Where = dbo.SafeSql(@Where), @ORDER = dbo.SafeSql(@Order)
	DECLARE @SQL AS VARCHAR(2000)
	CREATE TABLE #T(
		TitleID BIGINT,
		ID INT,
		JobID INT,
		JobName VARCHAR(50),
		cvMainID INT,
		paMainID INT,
		caFavorateMarkID INT,
		Degree TINYINT,
		RelatedWorkYears TINYINT,
		Attachment VARCHAR(50) COLLATE Chinese_PRC_CI_AS,
		IsNameHidden BIT,
		LivePlace VARCHAR(6) COLLATE Chinese_PRC_CI_AS,
		Gender BIT,
		paName NVARCHAR(20),
		BirthDay INT,
		HasPhoto TINYINT,
		adddate SMALLDATETIME,
		Valid TINYINT,
		IsViewed BIT,
		HasJobApply BIT,
		HasInterview BIT,
		HasRemark BIT,
		cvEducationID INT,
		College NVARCHAR(50),
		EduType TINYINT,
		MajorName NVARCHAR(20),
		Graduation INT,
		Speciality VARCHAR(MAX) COLLATE Chinese_PRC_CI_AS,
		Experience VARCHAR(MAX) COLLATE Chinese_PRC_CI_AS,
		MobileVerifyDate SMALLDATETIME,
		IsOnline BIT,
		HasWeiXin BIT,
		PaPhoto VARCHAR(50),
		dcSalaryID SMALLINT,
		SecondId VARCHAR(10)
	)

	--ca的类型： 1 管理员  2 普通用户
	DECLARE @AccountType AS TINYINT
	SELECT 	@AccountType = AccountType FROM caMain WITH(NOLOCK) WHERE ID = @caMainID	

	SET @SQL='
		INSERT INTO #T(
			TitleID, ID, JobID, JobName, cvMainID, paMainID, caFavorateMarkID, Degree, RelatedWorkYears, 
			Attachment, IsNameHidden, LivePlace, Gender, paName, BirthDay, HasPhoto, adddate, 
			Valid, MobileVerifyDate, IsOnline, dcSalaryID, SecondId
		)
		SELECT ROW_NUMBER() OVER (ORDER BY ' + @ORDER + ') AS TitleID, 
			a.ID, a.JobID, d.Name, a.cvMainID, c.ID paMainID, a.caFavorateMarkID, 
			b.Degree, b.RelatedWorkYears, b.Attachment, b.IsNameHidden, 
			c.LivePlace, c.Gender, c.Name AS paName, c.BirthDay, c.HasPhoto, 
			a.adddate, b.Valid, c.MobileVerifyDate, dbo.GetPaOnlineStatus(c.ID),
			b.dcSalaryID, b.SecondId
		FROM caFavorate a WITH(NOLOCK)
		INNER JOIN cvMain b WITH(NOLOCK) ON b.ID = a.cvMainID
		INNER JOIN paMain c WITH(NOLOCK) ON c.ID = b.paMainID
		INNER JOIN Job d WITH(NOLOCK) ON d.ID = a.JobID
		WHERE d.IsDelete = 0  ' 

	--add by mice 123 ca中的管理员可以查看子账号收藏的简历
	IF @AccountType = 1
		SET @SQL =  @SQL + '  AND a.caMainID  IN  (  SELECT ID FROM caMain WHERE cpMainID =  ' + LTRIM(STR(@cpMainID)) + ' AND IsDelete = 0 AND IsPause = 0 )  '
	ELSE
		SET @SQL =  @SQL + '  AND a.caMainID = ' + LTRIM(STR(@caMainID))
	
	IF LEN(@WHERE) > 0
		SET @SQL = @SQL + @WHERE
	--PRINT @sql
	EXEC(@SQL)

	IF(@Page < 1)
		SET @Page = 1
	
	UPDATE #T
	SET paName = LEFT(dbo.GetPersonName(cvMainID, @cpMainID), 20), 
		IsViewed = (SELECT TOP 1 '1' FROM caCvViewLog WITH(NOLOCK) WHERE cvMainID=#T.cvMainID AND caMainID=@caMainID), 
		HasJobApply = (SELECT TOP 1 '1' FROM exJobApply a WITH(NOLOCK) INNER JOIN Job b WITH(NOLOCK) ON a.JobID=b.ID WHERE a.CompanyDeleted=0 AND b.caMainID=@caMainID AND cvMainID=#T.cvMainID), 
		HasInterview = (SELECT TOP 1 '1' FROM exInterview a WITH(NOLOCK) INNER JOIN Job b WITH(NOLOCK) ON a.JobID=b.ID WHERE a.CompanyDeleted=0 AND b.caMainID=@caMainID AND cvMainID=#T.cvMainID), 
		HasRemark = (SELECT TOP 1 '1' FROM caCvRemark WITH(NOLOCK) WHERE caMainID=@caMainID AND cvMainID=#T.cvMainID)
	WHERE TitleID > (@Page-1)*20 AND TitleID <= @Page*20

	UPDATE #T SET Speciality = (
		SELECT Speciality FROM cvMain WITH(NOLOCK)
		WHERE cvMain.ID = #T.cvMainID)
	WHERE TitleID > (@Page-1)*20 AND TitleID <= @Page*20
	
	UPDATE #T SET PaPhoto = dbo.GetPaPhotoByCpView(#T.cvMainID, @cpMainID)
	WHERE TitleID > (@Page-1)*20 AND  TitleID <= @Page*20
	
	UPDATE #T SET Experience = (
		SELECT TOP 1 ISNULL(Description, DescriptionEng) FROM cvExperience WITH(NOLOCK)
		WHERE cvExperience.cvMainID = #T.cvMainID
		ORDER BY BeginDate DESC)
	WHERE TitleID > (@Page-1)*20 AND TitleID <= @Page*20

	UPDATE #T SET cvEducationID = (
		SELECT TOP 1 ID FROM cvEducation WITH(NOLOCK)
		WHERE cvEducation.cvMainID = #T.cvMainID
		AND #T.Degree = cvEducation.Degree
		ORDER BY Graduation DESC)
	WHERE TitleID > (@Page-1)*20 AND TitleID <= @Page*20

	UPDATE a SET a.College = ISNULL(b.GraduateCollage, b.GraduateCollageEng), a.EduType = b.EduType, 
		a.MajorName = ISNULL(b.MajorName, b.MajorNameEng), a.Graduation = b.Graduation
	FROM #T a, cvEducation b WITH(NOLOCK)
	WHERE b.ID = a.cvEducationID AND a.TitleID > (@Page-1)*20 AND a.TitleID <= @Page*20

	--修改是否绑定微信
	UPDATE a SET HasWeiXin = 1
	FROM #T a, WxFans b WITH(NOLOCK), CvMain c WITH(NOLOCK)
	WHERE a.CvMainID = c.ID
	AND c.PaMainID = b.PaMainID
	AND b.Status = 2
	AND a.TitleID > (@Page-1)*20 AND  TitleID <= @Page*20

	SELECT COUNT(*) FROM #T WITH(NOLOCK)

	SELECT a.*,b.Description DegreeName,c.MapBarName LivePlaceName, dbo.BirthToAge(a.BirthDay) Age,d.Description dcSalaryName
	FROM #T a WITH(NOLOCK) 
	LEFT JOIN dcEducation b WITH(NOLOCK) ON b.ID = a.Degree
	LEFT JOIN dcRegion c WITH(NOLOCK) ON c.ID = a.LivePlace
	LEFT JOIN dcSalary d WITH(NOLOCK) ON d.ID = a.dcSalaryID
	WHERE a.TitleID > (@Page-1)*20 AND a.TitleID <= @Page*20
	
	DROP TABLE #T
END

GO
/****** Object:  StoredProcedure [dbo].[mblcaIOSBindDelete]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[mblcaIOSBindDelete]
(
	@caMainID INT,
	@UniqueID VARCHAR(100)
)
AS
BEGIN
	DELETE FROM caIOSBind WHERE UniqueID = @UniqueID
END

GO
/****** Object:  StoredProcedure [dbo].[mblcaIOSBindInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[mblcaIOSBindInsert]
(
	@caMainID INT,
	@UniqueID VARCHAR(100),
	@ClientType TINYINT
)
AS
BEGIN TRY
	IF LEN(ISNULL(@UniqueID,'')) = 0
		RETURN
	IF NOT EXISTS(SELECT 1 FROM caIOSBind WITH(NOLOCK) WHERE caMainID = @caMainID AND UniqueID = @UniqueID AND ClientType = @ClientType)
	BEGIN
		INSERT INTO caIOSBind VALUES(@caMainID,@UniqueID,GETDATE(),@ClientType)
		RETURN 1
	END
	ELSE
	BEGIN
		RETURN 0
	END
END TRY
BEGIN CATCH
	RETURN 0
END CATCH



GO
/****** Object:  StoredProcedure [dbo].[mblcaJobCvMatchByCaMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
---------------
--创建人Peter
--时间 2017-4-17
--根据caMainID获取推荐简历
CREATE PROCEDURE [dbo].[mblcaJobCvMatchByCaMainIDSelect]
(
	@caMainID INT, 
	@PageNo INT
)
AS
SET NOCOUNT ON
BEGIN
	DECLARE @T_CvList AS TABLE(
		iIndex INT IDENTITY(1, 1), 
		ID INT, 
		cvEducationID INT, 
		dcMajorID INT, 
		Degree TINYINT, 
		RelatedWorkYears INT, 
		dcSalaryID TINYINT, 
		Speciality VARCHAR(MAX) COLLATE Chinese_PRC_CI_AS, 
		RefreshDate SMALLDATETIME, 
		LastLoginDate SMALLDATETIME, 
		JobName VARCHAR(100) COLLATE Chinese_PRC_CI_AS, 
		MatchJobID INT, 
		MatchJobName VARCHAR(100) COLLATE Chinese_PRC_CI_AS, 
		Gender BIT, 
		BirthDay INT, 
		LivePlace INT, 
		Attachment VARCHAR(50) COLLATE Chinese_PRC_CI_AS, 
		HasPhoto TINYINT, 
		College NVARCHAR(50), 
		EduType TINYINT, 
		MajorName NVARCHAR(20), 
		Graduation INT, 
		HasViewed BIT, 
		ViewDate SMALLDATETIME, 
		HasRemarked BIT, 
		LastJobTypeID INT, 
		Valid TINYINT, 
		IsOnline BIT, 
		HasWeiXin BIT, 
		JobRecommendDate SMALLDATETIME, 
		paMainID INT, 
		SecondId VARCHAR(10)
	)
	
	CREATE TABLE #T_JobID(
		JobID INT
	)
	
	DECLARE @cpMainID INT
	
	SELECT @cpMainID = CASE AccountType WHEN 1 THEN CpMainID ELSE 0 END FROM caMain WITH(NOLOCK) WHERE ID = @caMainID
	
	IF @cpMainID <> 0 --管理员用户
	BEGIN
		INSERT INTO #T_JobID (JobID)
		SELECT ID FROM Job WITH(NOLOCK)
		WHERE cpMainID = @cpMainID
	END
	ELSE
	BEGIN
		INSERT INTO #T_JobID (JobID)
		SELECT ID FROM Job WITH(NOLOCK)
		WHERE caMainID = @caMainID
	END
	
	INSERT INTO @T_CvList(ID, dcMajorID, Degree, RelatedWorkYears, dcSalaryID, Speciality, RefreshDate,
		LastLoginDate, JobName, MatchJobID, Gender, BirthDay, LivePlace, LastJobTypeID, Attachment,
		HasPhoto, HasViewed, HasRemarked, Valid, IsOnline, JobRecommendDate, paMainId, SecondId)
	SELECT a.ID, a.dcMajorID, a.Degree, a.RelatedWorkYears, a.dcSalaryID, ISNULL(a.Speciality, a.SpecialityEng) Speciality,
		a.RefreshDate, j.LastLoginDate, ISNULL(a.JobName, '应届毕业生') JobName, b.JobID, j.Gender, j.BirthDay, j.LivePlace,
		a.LastJobTypeID, a.Attachment, j.HasPhoto, 0, 0, a.Valid, dbo.GetPaOnlineStatus(j.ID), b.AddDate, a.paMainId, a.SecondId
	FROM cvmainPublish a WITH(NOLOCK) 
	INNER JOIN paMainPublish j WITH(NOLOCK) ON a.paMainID=j.ID 
	INNER JOIN caJobCvMatch b ON a.id=b.MatchCvMainID
	WHERE b.JobID IN (SELECT JobID FROM #T_JobID)
	ORDER BY b.AddDate DESC
	
	DECLARE @PageLowerBound  INT --定义此页的底码
    DECLARE @PageUpperBound  INT --定义此页的顶码
    SET @PageLowerBound = (@PageNo -1) * 20
    SET @PageUpperBound = @PageLowerBound + 20

	UPDATE a SET a.cvEducationID = (
		SELECT TOP 1 ID FROM cvEducationPublish WITH(NOLOCK)
		WHERE cvEducationPublish.cvMainID = a.ID
		AND a.Degree = cvEducationPublish.Degree
		ORDER BY Graduation DESC)
	FROM @T_CvList a
	WHERE a.iIndex > @PageLowerBound
	AND a.iIndex <= @PageUpperBound
	
	UPDATE a SET a.College = ISNULL(b.GraduateCollage, b.GraduateCollageEng), a.EduType = b.EduType, 
		a.MajorName = ISNULL(b.MajorName, b.MajorNameEng), a.Graduation = b.Graduation
	FROM @T_CvList a, cvEducationPublish b WITH(NOLOCK)
	WHERE b.ID = a.cvEducationID
	AND a.iIndex > @PageLowerBound
	AND a.iIndex <= @PageUpperBound

	--修改是否绑定微信
	UPDATE a SET HasWeiXin = 1
	FROM @T_CvList a, WxFans b WITH(NOLOCK), CvMainPublish c WITH(NOLOCK)
	WHERE a.ID = c.ID
	AND c.PaMainID = b.PaMainID
	AND b.Status = 2
	AND a.iIndex > @PageLowerBound
	AND a.iIndex <= @PageUpperBound
	
	UPDATE a SET a.MatchJobName = b.Name
	FROM @T_CvList a, Job b WITH(NOLOCK)
	WHERE a.MatchJobID = b.ID
	AND a.iIndex > @PageLowerBound
	AND a.iIndex <= @PageUpperBound

	UPDATE a SET a.HasViewed = 1, a.ViewDate = b.AddDate
	FROM @T_CvList a, caCvViewLog b WITH(NOLOCK)
	WHERE b.cvMainID = a.ID AND caMainID=@caMainID	
	AND a.iIndex > @PageLowerBound
	AND a.iIndex <= @PageUpperBound

	SELECT a.*,b.Description DegreeName,dbo.BirthToAge(a.BirthDay) Age,c.Description LivePlaceName 
	FROM @T_CvList a 
	LEFT JOIN MainDB..dcEducation b WITH(NOLOCK) ON b.ID = a.Degree
	LEFT JOIN MainDB..dcRegion c WITH(NOLOCK) ON c.ID = a.LivePlace
	WHERE a.iIndex > @PageLowerBound
	AND a.iIndex <= @PageUpperBound
	
	DROP TABLE #T_JobID
END

GO
/****** Object:  StoredProcedure [dbo].[mblcaLoginContactByOpenIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2016.4.1
--创建人：Lucifer
--说明：根据微信号得到微信绑定企业信息
--#####################################################
CREATE PROCEDURE [dbo].[mblcaLoginContactByOpenIDSelect]
(
	@OpenID VARCHAR(50)
)
AS
BEGIN
	SELECT a.*, b.UserName 
	FROM paLoginContact a, caMain b, cpMain c
	WHERE a.openid=@OpenID 
	AND a.ContactType = 101
	AND a.PamainID = b.ID
	AND b.cpMainId = c.Id
	AND b.IsPause = 0
	AND c.IsLimitLogin IN(0, 1)
END
GO
/****** Object:  StoredProcedure [dbo].[mblCaMainByIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[mblCaMainByIDSelect]
(
	@caMainID INT
)
AS
BEGIN TRY
	SELECT a.name,b.name as companyname,b.id cpMainID,dbo.GetCaOnlineStatus(a.id) IsOnline,b.SecondId EnCpMainId
	FROM camain a,cpmain b 
	WHERE a.id=@caMainID 
	AND a.cpmainid = b.id
END TRY
BEGIN CATCH
	RETURN 0
END CATCH
GO
/****** Object:  StoredProcedure [dbo].[mblCampusSchoolByIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.06
--创建人：Nick
--说明：根据ID获取学校名称
--#####################################################
CREATE PROCEDURE [dbo].[mblCampusSchoolByIDSelect]
(
	@ID INT
)
AS
BEGIN TRY
	SELECT * FROM marketdb..CampusSchool WHERE ID  = @ID
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[mblcaPageViewLogByNoViewSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[mblcaPageViewLogByNoViewSelect]
(
	@caMainID INT
)
AS
SET NOCOUNT ON
IF @caMainID = 0
BEGIN
	SELECT TOP 0 0 ID
	RETURN
END
BEGIN	
	IF NOT EXISTS(SELECT 'x' FROM caPageViewLog WITH(NOLOCK) WHERE caMainId = @caMainID)
	BEGIN
		INSERT INTO caPageViewLog(caMainId,addDate,ApplyCvDate,RecommendCvDate,InterviewReplyDate) 
		VALUES(@caMainID, DATEADD(MINUTE, -10, GETDATE()), DATEADD(MINUTE, -10, GETDATE()), DATEADD(MINUTE, -10, GETDATE()), DATEADD(MINUTE, -10, GETDATE()))
		--RETURN
	END
	 
    DECLARE @AddDate SMALLDATETIME, @ApplyCvDate SMALLDATETIME, @RecommendCvDate SMALLDATETIME,
		@InterviewReplyDate SMALLDATETIME, @ApplyCvCount INT, @RecommendCvCount INT,
		@InterviewReplyCount INT,@ChatCount INT,@cpMainID INT,@AccountType SMALLINT
	 
	SELECT @AddDate = AddDate, 
		@ApplyCvDate = ISNULL(ApplyCvDate, DATEADD(MINUTE, -10, GETDATE())),
		@RecommendCvDate = ISNULL(RecommendCvDate, DATEADD(MINUTE, -10, GETDATE())),
		@InterviewReplyDate = ISNULL(InterviewReplyDate, DATEADD(MINUTE, -10, GETDATE())),
		@ApplyCvCount = ISNULL(ApplyCvCount, 0),
		@RecommendCvCount = ISNULL(RecommendCvCount, 0),
		@InterviewReplyCount = ISNULL(InterviewReplyCount, 0),
		@ChatCount = ISNULL(ChatCount, 0)
	FROM caPageViewLog WITH(NOLOCK)
	WHERE caMainId = @caMainID
	
	SELECT @cpMainID=cpMainID,@AccountType=AccountType
	FROM caMain WITH(NOLOCK)
	WHERE ID = @caMainID
	
	CREATE TABLE #TJobIDs
	(
		ID INT
	)
	
	IF @AccountType = 1 --管理员账户
	BEGIN
		INSERT INTO #TJobIDs(ID)
		SELECT ID 
		FROM Job WITH(NOLOCK)
		WHERE cpMainID = @cpMainID
	END
	ELSE
	BEGIN
		INSERT INTO #TJobIDs(ID)
		SELECT ID 
		FROM Job WITH(NOLOCK)
		WHERE caMainID = @caMainID
	END
	
    --更新时间超过30分钟的，重新计算提醒内容
	IF GETDATE() > DATEADD(MINUTE, 30, @AddDate)	--30分钟内的不重新生成	 
	BEGIN 
		--新应聘的简历
		IF @ApplyCvCount = 0
		BEGIN
			SELECT @ApplyCvCount = COUNT(1)
			FROM exJobApply WITH(NOLOCK)
			WHERE JobID IN(SELECT ID FROM #TJobIDs)
			AND AddDate > @ApplyCvDate 
		END 
		
		--新推荐简历
		IF @RecommendCvCount = 0
		BEGIN
			SELECT @RecommendCvCount = COUNT(1)
			FROM caJobCvMatch WITH(NOLOCK)
			WHERE JobID IN(SELECT ID FROM #TJobIDs)
			AND AddDate > @RecommendCvDate
		END
		
		--新面试通知答复
		IF @InterviewReplyCount = 0
		BEGIN
			SELECT @InterviewReplyCount = COUNT(1)
			FROM exInterview WITH(NOLOCK)
			WHERE JobID IN(SELECT ID FROM #TJobIDs)
			AND Replydate > @RecommendCvDate
		END
		
		--新的聊天信息
		IF @ChatCount = 0 
		BEGIN
			SELECT @ChatCount=COUNT(1)
			FROM ChatOnlineLog a WITH(NOLOCK)
			LEFT JOIN ChatOnline b WITH(NOLOCK) ON a.ChatOnlineID = b.ID
			WHERE b.caMainID = @caMainID
			AND a.IsViewed = 0
			AND a.SenderType = 2
		END	
		
		--更新添加时间
		IF (@ApplyCvCount + @RecommendCvCount + @InterviewReplyCount + @ChatCount)>0 
			UPDATE caPageViewLog
			SET AddDate = GETDATE(),
			ApplyCvCount = @ApplyCvCount,
			RecommendCvCount = @RecommendCvCount,
			InterviewReplyCount = @InterviewReplyCount,
			ChatCount =@ChatCount
			WHERE caMainId = @caMainID  
		ELSE
			UPDATE caPageViewLog
			SET AddDate = GETDATE()
			WHERE caMainId = @caMainID  
	END
	SELECT * FROM caPageViewLog WHERE caMainId = @caMainID --查询表内容 	

	DROP TABLE #TJobIDs 
END

GO
/****** Object:  StoredProcedure [dbo].[mblChatOnlineByCaIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.06
--创建人：Nick
--说明：根据camainid manageruserid 得到会话信息
--#####################################################
CREATE PROCEDURE [dbo].[mblChatOnlineByCaIDSelect]
(
	@caMainID INT,
	@mID INT
)
AS
BEGIN TRY
	SELECT TOP 1 * 
	FROM chatonline 
	WHERE caMainID = @caMainID 
	AND manageruserid=@mID 
	AND enddate IS NULL
	ORDER BY adddate DESC
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[mblChatOnlineByCaMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.06
--创建人：Nick
--说明：获取客服
--#####################################################
CREATE PROCEDURE [dbo].[mblChatOnlineByCaMainIDSelect]
(
	@caMainID INT
)
AS
BEGIN TRY
	SELECT a.manageruserid,b.Name 
	FROM chatonline a,ManagerUser b
	WHERE a.camainid = @caMainID 
	AND a.enddate is null
	AND a.manageruserid <> 0 
	AND a.ManagerUserID  = b.ID
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[mblChatOnlineByCvMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.06
--创建人：Nick
--说明：根据cvmainid camainid 得到会话信息
--#####################################################
CREATE PROCEDURE [dbo].[mblChatOnlineByCvMainIDSelect]
(
	@cvMainID INT,
	@caMainID INT
)
AS
BEGIN TRY
	SELECT TOP 1 * 
	FROM chatonline 
	WHERE cvMainID = @cvMainID 
	AND caMainID=@caMainID 
	AND enddate IS NULL 
	ORDER BY adddate DESC
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[mblChatOnlineByMIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.06
--创建人：Nick
--说明：根据cvmainid manageruserid 得到会话信息
--#####################################################
CREATE PROCEDURE [dbo].[mblChatOnlineByMIDSelect]
(
	@cvMainID INT,
	@manageruserid INT
)
AS
BEGIN TRY
	SELECT TOP 1 * 
	FROM chatonline 
	WHERE cvMainID = @cvMainID 
	AND manageruserid=@manageruserid 
	AND enddate IS NULL 
	ORDER BY adddate DESC
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[mblChatOnlineCpNoViewCntSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.7
--创建人：John
--说明：在线沟通企业未读总条数
--#####################################################
CREATE PROCEDURE [dbo].[mblChatOnlineCpNoViewCntSelect]
(
	@caMainID INT
)
AS
BEGIN
	SELECT COUNT(*) cnt FROM chatonlinelog a WITH(NOLOCK) INNER JOIN chatonline b WITH(NOLOCK) ON a.chatonlineid=b.id 
	WHERE a.sendertype = 2 AND a.isviewed = 0 AND b.caMainID = @caMainID
END


GO
/****** Object:  StoredProcedure [dbo].[mblChatOnlineInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.06
--创建人：Nick
--说明：获取个人信息
--#####################################################
CREATE PROCEDURE [dbo].[mblChatOnlineInsert]
(
	@cvMainID INT,
	@caMainID INT
)
AS
BEGIN TRY
	INSERT INTO chatonline (cvMainID,caMainID,initiative,startDate,valid,adddate)
	VALUES(@cvMainID,@caMainID,1,getdate(),0,getdate())
	RETURN 1
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[mblChatOnlineLogByCaIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.06
--创建人：Nick
--说明：企业会话列表
--#####################################################
CREATE PROCEDURE [dbo].[mblChatOnlineLogByCaIDSelect]
	@cvMainID INT,
	@caMainID INT
AS
BEGIN TRY
	SELECT a.* FROM ChatOnlineLog a 
	WHERE a.ChatOnlineID IN(
		SELECT ID FROM
		ChatOnline WHERE cvMainID=@cvMainID AND caMainID=@caMainID
	)
	ORDER BY a.AddDate
END TRY
BEGIN CATCH
	RETURN 0
END CATCH




GO
/****** Object:  StoredProcedure [dbo].[mblChatOnlineLogByConditionSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.06
--创建人：Nick
--说明：获取企业与顾问的回话信息
--#####################################################
CREATE PROCEDURE [dbo].[mblChatOnlineLogByConditionSelect]
(
	@caMainID INT,
	@consultantID INT,
	@Condition VARCHAR(MAX)
)
AS
BEGIN TRY
	DECLARE @SQL VARCHAR(MAX)
	SET @SQL = '
	SELECT a.* FROM ChatOnlineLog a 
	WHERE a.ChatOnlineID IN(
		SELECT ID FROM
		ChatOnline WHERE caMainID='+CONVERT(VARCHAR(20),@caMainID)+'
		AND managerUserID='+CONVERT(VARCHAR(10),@consultantID)+' 
		'+@Condition+'
	)
	ORDER BY a.AddDate'
	PRINT @SQL
	EXEC (@SQL)
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[mblChatOnlineLogByCvMainIDUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.06
--创建人：Nick
--说明：将消息修改为已读
--#####################################################
CREATE PROCEDURE [dbo].[mblChatOnlineLogByCvMainIDUpdate]
(
	@cvMainID INT,
	@caMainID INT
)
AS
BEGIN TRY
	UPDATE chatonlinelog 
	SET isviewed=1 
	WHERE isviewed=0 
	AND chatonlineid IN(
		SELECT ID FROM chatonline 
		WHERE cvmainid = @cvMainID 
		AND camainid = @caMainID
	) AND SenderType = 1
	RETURN 1
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[mblChatOnlineLogByIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.06
--创建人：Nick
--说明：根据ID获取会话信息
--#####################################################
CREATE PROCEDURE [dbo].[mblChatOnlineLogByIDSelect]
(
	@ID INT
)
AS
BEGIN TRY
	SELECT * FROM chatonline WHERE id=@ID
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[mblChatOnlineLogByMIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.06
--创建人：Nick
--说明：顾问或客服会话
--#####################################################
CREATE PROCEDURE [dbo].[mblChatOnlineLogByMIDSelect]
(
	@cvMainID INT,
	@managerUserID INT
)
AS
BEGIN TRY
	SELECT a.* FROM ChatOnlineLog a 
	WHERE a.ChatOnlineID IN(
		SELECT ID 
		FROM ChatOnline 
		WHERE cvMainID=@cvMainID 
		AND managerUserID=@managerUserID)
	ORDER BY a.AddDate
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[mblChatOnlineLogByMIDUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.06
--创建人：Nick
--说明：将消息修改为已读
--#####################################################
CREATE PROCEDURE [dbo].[mblChatOnlineLogByMIDUpdate]
(
	@cvMainID INT,
	@mID INT
)
AS
BEGIN TRY
	UPDATE chatonlinelog 
	SET isviewed=1 
	WHERE isviewed=0 
	AND chatonlineid IN(
		SELECT ID FROM chatonline 
		WHERE cvmainid = @cvMainID 
		AND managerUserID = @mID
	) 
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[mblChatOnlineLogBySenderTypeUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.06
--创建人：Nick
--说明：将消息修改为已读
--#####################################################
CREATE PROCEDURE [dbo].[mblChatOnlineLogBySenderTypeUpdate]
(
	@cvMainID INT,
	@caMainID INT
)
AS
BEGIN TRY
	UPDATE chatonlinelog 
	SET isviewed=1 
	WHERE isviewed=0 
	AND chatonlineid IN(
		SELECT ID FROM chatonline 
		WHERE cvmainid = @cvMainID 
		AND camainid = @caMainID
	) AND SenderType = 2
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[mblChatOnlineLogInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.06
--创建人：Nick
--说明：发送消息 插入
--#####################################################
CREATE PROCEDURE [dbo].[mblChatOnlineLogInsert]
(
	@chatOnlineID INT,
	@senderType INT,
	@Message VARCHAR(500)
)
AS
BEGIN TRY
	INSERT INTO chatonlinelog (chatOnlineID,SenderType,isviewed,message,adddate)
	VALUES(@chatOnlineID,@senderType,0,@Message,getdate())
	RETURN 1
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[mblChatonlineLogNoViewCntByPaMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.06
--创建人：Nick
--说明：个人未读总条数
--#####################################################
CREATE PROCEDURE [dbo].[mblChatonlineLogNoViewCntByPaMainIDSelect]
	@PamainID INT
AS
BEGIN TRY
	SELECT COUNT(*) cnt 
	FROM chatonlinelog 
	WHERE sendertype=1 
	AND isviewed = 0 
	AND chatonlineid IN (
		SELECT id 
		FROM chatonline 
		WHERE cvmainid in (
			SELECT ID FROM cvmain 
			WHERE pamainid=@PaMainID
		)
	)
END TRY
BEGIN CATCH
	RETURN 0
END CATCH



GO
/****** Object:  StoredProcedure [dbo].[mblChatOnlineLogViewByCaMainIDUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.06
--创建人：Nick
--说明：将消息修改为已读
--#####################################################
CREATE PROCEDURE [dbo].[mblChatOnlineLogViewByCaMainIDUpdate]
(
	@caMainID INT,
	@cvMainID INT
)
AS
BEGIN TRY
	UPDATE chatonlinelog 
	SET isviewed=1 
	WHERE isviewed=0 
	AND chatonlineid IN(
		SELECT ID FROM chatonline 
		WHERE camainid = @caMainID 
		AND cvmainid = @cvMainID)
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[mblChatOnlineLogViewByCIDUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.06
--创建人：Nick
--说明：将消息修改为已读
--#####################################################
CREATE PROCEDURE [dbo].[mblChatOnlineLogViewByCIDUpdate]
(
	@caMainID INT
)
AS
BEGIN TRY
	UPDATE chatonlinelog 
	SET isviewed=1 
	WHERE isviewed=0 
	AND chatonlineid IN(
		SELECT ID FROM chatonline 
		WHERE camainid = @caMainID 
		AND managerUserID <=200)
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[mblChatOnlineLogViewByMIDUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.06
--创建人：Nick
--说明：将消息修改为已读
--#####################################################
CREATE PROCEDURE [dbo].[mblChatOnlineLogViewByMIDUpdate]
(
	@caMainID INT,
	@mID INT
)
AS
BEGIN TRY
	UPDATE chatonlinelog 
	SET isviewed=1 
	WHERE isviewed=0 
	AND chatonlineid IN(
		SELECT ID FROM chatonline 
		WHERE camainid = @caMainID 
		AND managerUserID = @mID)
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[mblChatServiceSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.06
--创建人：Nick
--说明：获取客服
--#####################################################
CREATE PROCEDURE [dbo].[mblChatServiceSelect]
(
	@IsOnline INT
)
AS
BEGIN TRY
	IF @IsOnline = 1
	BEGIN
		SELECT TOP 1 * FROM ChatService WHERE IsOnline=1 ORDER BY ChatCount
	END
	ELSE
	BEGIN
		SELECT TOP 1 * FROM ChatService ORDER BY ChatCount
	END
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[mblCpMainByIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.7
--创建人：John
--说明：根据ID或SecondID获取CpMain相关信息
--修改：harry2015-6-18
--增加secondid
--修改：peter 2016-12-16 添加logo获取
--#####################################################
CREATE PROCEDURE [dbo].[mblCpMainByIDSelect]
(
	@ID VARCHAR(20), 
	@ColumnType TINYINT
)
AS
BEGIN
	IF @ColumnType = 1
		SELECT a.secondId, a.Lng, a.Lat, a.ID, a.Name, a.Address, a.MemberType, a.Brief, b.FullName RegionName, c.Description CompanyKind, d.Description CompanySize, dbo.GetCpIndustry(a.ID) Industry , e.ImgFile LogoUrl, a.RealName, a.LogoFile, a.ReplyRate, a.HomePage, a.dcProvinceId
		FROM CpMain a WITH(NOLOCK) 
		LEFT JOIN dcRegion b WITH(NOLOCK) ON a.dcRegionID = b.ID 
		LEFT JOIN dcCompanyKind c WITH(NOLOCK) ON a.dcCompanyKindID = c.ID 
		LEFT JOIN dcCompanySize d WITH(NOLOCK) ON a.dcCompanySizeID = d.ID 
		LEFT JOIN cpImage e WITH(NOLOCK) ON e.cpMainID = a.ID AND e.ImgType = 1 AND e.HasPassed = 1
		WHERE a.ID = @ID 
		AND a.IsLimitLogin <> 9
	ELSE
		SELECT a.secondId, a.Lng, a.Lat, a.ID, a.Name, a.Address, a.MemberType, a.Brief, b.FullName RegionName, c.Description CompanyKind, d.Description CompanySize, dbo.GetCpIndustry(a.ID) Industry, e.ImgFile LogoUrl, a.RealName, a.LogoFile, a.ReplyRate, a.HomePage, a.dcProvinceId
		FROM CpMain a WITH(NOLOCK) 
		LEFT JOIN dcRegion b WITH(NOLOCK) ON a.dcRegionID = b.ID 
		LEFT JOIN dcCompanyKind c WITH(NOLOCK) ON a.dcCompanyKindID = c.ID 
		LEFT JOIN dcCompanySize d WITH(NOLOCK) ON a.dcCompanySizeID = d.ID 
		LEFT JOIN cpImage e WITH(NOLOCK) ON e.cpMainID = a.ID AND e.ImgType = 1 AND e.HasPassed = 1
		WHERE a.SecondID = @ID 
		AND a.IsLimitLogin <> 9
END
GO
/****** Object:  StoredProcedure [dbo].[mblCvEducationByIdSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[mblCvEducationByIdSelect]
(
	@ID int
)
AS
BEGIN
	SELECT a.*, b.Description Major, c.Description EduTypeName, d.Description Education
	FROM cvEducation a WITH(NOLOCK INDEX(IX_cvEducation_CvMainID)),
		dcMajor b WITH(NOLOCK),
		dcEduType c WITH(NOLOCK),
		dcEducation d WITH(NOLOCK)
	WHERE a.dcMajorID = b.ID 
	AND a.EduType = c.ID
	AND a.Degree = d.ID
	AND a.ID = @ID
	ORDER BY a.Degree DESC,
		a.Graduation Desc
END














GO
/****** Object:  StoredProcedure [dbo].[mblCvEducationSave]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[mblCvEducationSave]
	@ID INT,
	@cvMainID INT,
	@GraduateCollage VARCHAR(250),
	@Graduation INT,
	@dcMajorID SMALLINT,
	@MajorName VARCHAR(100),
	@Degree TINYINT,
	@EduType TINYINT,
	@paMainID INT 
AS
BEGIN TRAN
	----检查是否是该账号的简历
	IF NOT EXISTS(SELECT 'x' FROM cvMain WITH(NOLOCK) WHERE ID =@cvMainID AND paMainID = @paMainID)
		GOTO ERR
	----检查是否是该简历的教育背景
	IF @ID > 0
		IF NOT EXISTS(SELECT 'x' FROM cvEducation WITH(NOLOCK) WHERE ID = @ID AND cvMainID = @cvMainID)
			GOTO ERR
	
	SET @GraduateCollage = dbo.SafeSql(dbo.TextTrim(@GraduateCollage))
	SET @MajorName  = dbo.SafeSql(dbo.TextTrim(@MajorName))

	DECLARE @MaxId AS INT
	DECLARE @CNT AS INT
	DECLARE @GraduateCollageOld AS VARCHAR(250)
	DECLARE @MajorNameOld AS VARCHAR(100)
	DECLARE @cvdcMajorID AS SMALLINT
	DECLARE @Modify AS INT
	SET @Modify=-1

	BEGIN TRY
		BEGIN
			DECLARE @GC AS NVARCHAR(50)
			DECLARE @MN AS NVARCHAR(20)
			SET @GC = @GraduateCollage
			SET @MN = @MajorName

			IF @ID>0
				BEGIN
					SELECT @GraduateCollageOld = dbo.TextTrim(GraduateCollage),
						@MajorNameOld = dbo.TextTrim(MajorName)
						FROM cvEducation WITH(NOLOCK INDEX(PK_cvEducation)) WHERE ID=@ID
					UPDATE cvEducation SET
						GraduateCollage = @GC,
						Graduation = @Graduation,
						dcMajorID = @dcMajorID,
						MajorName =@MN,
						Degree = @Degree,
						EduType = @EduType
					WHERE ID=@ID
					SET @MaxID=@ID

					IF ISNULL(@GraduateCollageOld, '') <> ISNULL(@GC, '')
						BEGIN
							DELETE FROM bsCvModify WHERE SubID = @ID AND Location = 'dc1'
							INSERT INTO bsCvModify(paMainID,cvMainID,SubID,Location,ColValue) VALUES(@paMainID,@cvMainID,@MaxID,'dc1',@GC)
							SET @Modify=0
						END

					IF ISNULL(@MajorNameOld, '') <> ISNULL(@MN, '')
						BEGIN
							DELETE FROM bsCvModify WHERE paMainID=@paMainID AND cvMainID=@cvMainID AND SubID = @ID AND Location = 'dc2'
							INSERT INTO bsCvModify(paMainID,cvMainID,SubID,Location,ColValue) VALUES(@paMainID,@cvMainID,@MaxID,'dc2',@MN)
							SET @Modify=0
						END
				END
			ELSE
				BEGIN
					SELECT @CNT=COUNT(*) FROM cvEducation WITH(NOLOCK INDEX(PK_cvEducation)) WHERE cvMainID = @cvMAinID
					IF @CNT<5
						BEGIN
							INSERT INTO cvEducation(cvMainID,GraduateCollage,Graduation,dcMajorID,MajorName,Degree,EduType)	
								VALUES(@cvMainID,@GC,@Graduation,@dcMajorID,@MN,@Degree,@EduType)
							SET @MaxID = @@IDENTITY

							INSERT INTO bsCvModify(paMainID,cvMainID,SubID,Location,ColValue) VALUES(@paMainID,@cvMainID,@MaxID,'dc1',@GC)
							INSERT INTO bsCvModify(paMainID,cvMainID,SubID,Location,ColValue) VALUES(@paMainID,@cvMainID,@MaxID,'dc2',@MN)
							SET @Modify=0
						END
					ELSE
						GOTO ERR
				END
		END
		
		SELECT @Degree = MAX(DEGREE) FROM cvEducation WITH(NOLOCK) WHERE cvMainID = @cvMainID
		UPDATE cvMain SET Degree=@Degree, dcMajorID=@dcMajorID WHERE ID=@cvMainID

		--修改cvLevel
		DECLARE @SQL AS VARCHAR(100)
		SET @SQL = 'EXEC pcCvMainByCvLevelUpdateNew ' + CONVERT(CHAR(1), 0) + ',' + CONVERT(VARCHAR(10), @cvMainID) + ',3,1'
		EXEC(@SQL)
	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH
COMMIT TRAN
RETURN @MaxID
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END














GO
/****** Object:  StoredProcedure [dbo].[mblCvEducationSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[mblCvEducationSelect]
(
	@cvMainID int
)
AS
BEGIN
	SELECT a.*, b.Description Major, c.Description EduTypeName, d.Description Education
	FROM cvEducation a WITH(NOLOCK INDEX(IX_cvEducation_CvMainID)),
		dcMajor b WITH(NOLOCK),
		dcEduType c WITH(NOLOCK),
		dcEducation d WITH(NOLOCK)
	WHERE a.dcMajorID=b.ID AND a.EduType=c.ID AND a.Degree=d.ID AND a.cvMainID=@cvMainID
	ORDER BY a.Degree DESC,a.Graduation Desc
END


set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON














GO
/****** Object:  StoredProcedure [dbo].[mblCvExperienceByIdSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[mblCvExperienceByIdSelect]
(
	@ID INT
)
AS
BEGIN
	SELECT a.*, b.Description JobType, c.Description CpmpanySize, d.Description Industry,
		g.Description LowerNumber, e.Description CompanyKind, f.Description LeaveReson, h.FullName Region
	FROM cvExperience a WITH(NOLOCK INDEX(IX_cvExperience_cvMainID))
	LEFT JOIN dcJobType b WITH(NOLOCK) ON a.dcJobTypeID=b.ID
	LEFT JOIN dcCompanySize c WITH(NOLOCK) ON a.dcCompanySizeID=c.ID
	LEFT JOIN dcIndustry d WITH(NOLOCK) ON a.dcIndustryID=d.ID
	LEFT JOIN dcLowerNumber g WITH(NOLOCK) ON a.SubNodeNum=g.ID
	LEFT JOIN dcCompanyKind e WITH(NOLOCK) ON a.dcCompanyKindID=e.ID
	LEFT JOIN dcLeaveReson f WITH(NOLOCK) ON a.dcLeaveResonID=f.ID
	LEFT JOIN dcRegion h WITH(NOLOCK) ON a.WorkPlace=h.ID
	WHERE a.ID = @ID
	ORDER BY a.BeginDate DESC
END














GO
/****** Object:  StoredProcedure [dbo].[mblCvExperienceDelete]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----------------------------------------------
--创建Sean
--检查时间	2010-9-27
--修改了有无工作经验的判断, 取消pcCvMainVerifyResultCheck
--修改：Lambo，2010-11-25
--描述：增加了paMainID参数，判断是否是本人的
-----------------------------------------------
CREATE PROCEDURE [dbo].[mblCvExperienceDelete]
(
	@ID INT,
	@paMainID INT
)
AS
SET NOCOUNT ON
BEGIN TRAN
	BEGIN TRY
		DECLARE @cvMainId AS INT
		DECLARE @RETURN AS VARCHAR(2)

		SELECT @cvMainId = cvMainId FROM cvExperience WITH(NOLOCK) WHERE ID=@ID

		IF @cvMainId IS NULL
			GOTO ERR

		IF NOT EXISTS(SELECT 'x' FROM cvMain WITH(NOLOCK) WHERE paMainID = @paMainID AND ID = @cvMainID)
			GOTO ERR

		DELETE FROM bsCvModify WHERE SubID = @ID AND Location LIKE 'e%'
		DELETE FROM cvExperience WHERE ID = @ID

		IF (SELECT COUNT(*) FROM cvExperience WITH(NOLOCK) WHERE cvMainId = @cvMainId) = 0
			UPDATE cvMain SET cvType = 1, cvLevel = LEFT(cvLevel, 3) + '1' + RIGHT(cvLevel, 6),
				cvLevelEng = LEFT(cvLevelEng, 3) + '1' + RIGHT(cvLevelEng, 6)
			WHERE Id = @cvMainId
	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH
COMMIT TRAN
RETURN @RETURN
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 3
END














GO
/****** Object:  StoredProcedure [dbo].[mblCvExperienceSave]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[mblCvExperienceSave]
(
	@ID INT,
	@cvMainID INT,
	@CompanyName VARCHAR(100),
	@dcIndustryID INT,
	@dcCompanySizeID INT,
	@dcJobtypeID INT,
	@JobName VARCHAR(100),
	@BeginDate INT,
	@EndDate INT,
	@SubNodeNum INT,
	@Description VARCHAR(Max),
	@paMainID INT
)
AS
SET NOCOUNT ON
BEGIN TRAN
	----检查是否是该账号的简历
	IF NOT EXISTS(SELECT 'x' FROM cvMain WITH(NOLOCK) WHERE ID = @cvMainID AND paMainID = @paMainID)
		GOTO ERR
	----检查是否是该简历的工作经验
	IF @ID > 0
		IF NOT EXISTS(SELECT 'x' FROM cvExperience WITH(NOLOCK) WHERE ID = @ID AND cvMainID = @cvMainID)
			GOTO ERR

	SET @CompanyName = dbo.SafeSql(dbo.TextTrim(@CompanyName))
	SET @JobName = dbo.SafeSql(dbo.TextTrim(@JobName))
	SET @Description = dbo.SafeSql(dbo.TextTrim(@Description))
	IF CHARINDEX(',', @JobName) > 0
		SELECT @JobName = dbo.SafeSql(REPLACE(@JobName, ',', '，'))

	DECLARE @MaxId AS INT
	DECLARE @CNT AS INT
	DECLARE @CompanyNameOld AS VARCHAR(100)
	DECLARE @JobNameOld AS VARCHAR(100)
	DECLARE @DescriptionOld AS VARCHAR(Max)
	DECLARE @Modify AS INT
	SET @Modify = -1

	BEGIN TRY
		BEGIN
			DECLARE @C_CompanyName AS NVARCHAR(30)
			DECLARE @C_JobName AS NVARCHAR(50)
			DECLARE @C_Description AS NVARCHAR(2000)

			SET @C_CompanyName = dbo.TextTrim(@CompanyName)
			SET @C_JobName = dbo.TextTrim(@JobName)
			SET @C_Description = dbo.TextTrim(@Description)
			
			IF @ID>0
				BEGIN
					SELECT @CompanyNameOld = dbo.TextTrim(ISNULL(CompanyName, '')),
						@JobNameOld = dbo.TextTrim(ISNULL(JobName, '')),
						@DescriptionOld = dbo.TextTrim(ISNULL(Description, ''))
						FROM cvExperience WITH(NOLOCK INDEX(PK_cvExperience)) WHERE ID = @ID

					UPDATE cvExperience SET
						CompanyName = @C_CompanyName,
						dcIndustryID = @dcIndustryID,
						dcCompanySizeID = @dcCompanySizeID,
						dcJobtypeID = @dcJobtypeID,
						JobName = @C_JobName,
						BeginDate = @BeginDate,
						EndDate = @EndDate,
						SubNodeNum = @SubNodeNum,
						Description = @C_Description
					WHERE ID = @ID
					SET @MaxID = @ID

					IF ISNULL(@CompanyNameOld, '') <> ISNULL(@C_CompanyName, '')
						BEGIN
							DELETE FROM bsCvModify WHERE SubID = @ID AND Location = 'ec1'
							INSERT INTO bsCvModify(paMainID,cvMainID,SubID,Location,ColValue) VALUES(@paMainID,@cvMainID,@MaxID,'ec1',@CompanyName)
							SET @Modify = 0
						END

					IF ISNULL(@JobNameOld, '') <> ISNULL(@C_JobName, '')
						BEGIN
							DELETE FROM bsCvModify WHERE paMainID = @paMainID AND cvMainID = @cvMainID AND SubID = @ID AND Location = 'ec2'
							INSERT INTO bsCvModify(paMainID,cvMainID,SubID,Location,ColValue) VALUES(@paMainID,@cvMainID,@MaxID,'ec2',@C_JobName)
							SET @Modify = 0
						END

					IF ISNULL(@DescriptionOld, '') <> ISNULL(@C_Description, '')
						BEGIN
							DELETE FROM bsCvModify WHERE paMainID = @paMainID AND cvMainID = @cvMainID AND SubID = @ID AND Location = 'ec3'
							INSERT INTO bsCvModify(paMainID,cvMainID,SubID,Location,ColValue) VALUES(@paMainID,@cvMainID,@MaxID,'ec3',@C_Description)
							SET @Modify = 0
						END
					
				END
			ELSE
				BEGIN
					SELECT @CNT = COUNT(*) FROM cvExperience WITH(NOLOCK INDEX(IX_cvExperience_cvMainID)) WHERE cvMainID = @cvMainID
					IF @CNT<20
						BEGIN
							INSERT INTO cvExperience
								(cvMainID,CompanyName,dcIndustryID,dcCompanySizeID,dcJobtypeID,JobName,
								BeginDate,EndDate,SubNodeNum,Description)
							 VALUES
								(@cvMainID,@CompanyName,@dcIndustryID,@dcCompanySizeID,@dcJobtypeID,@JobName,
								@BeginDate,@EndDate,@SubNodeNum,@Description)
							SET @MaxID = @@IDENTITY

							INSERT INTO bsCvModify(paMainID,cvMainID,SubID,Location,ColValue) VALUES(@paMainID,@cvMainID,@MaxID,'ec1',@C_CompanyName)
							INSERT INTO bsCvModify(paMainID,cvMainID,SubID,Location,ColValue) VALUES(@paMainID,@cvMainID,@MaxID,'ec2',@C_JobName)
							INSERT INTO bsCvModify(paMainID,cvMainID,SubID,Location,ColValue) VALUES(@paMainID,@cvMainID,@MaxID,'ec3',@C_Description)
							SET @Modify = 0
						END
					ELSE
						GOTO ERR
				END
		END

		UPDATE cvMain SET cvType = 0 WHERE Id = @CvMainId AND cvType = 1
		--修改cvLevel
		DECLARE @SQL AS VARCHAR(100)
		SET @SQL = 'EXEC pcCvMainByCvLevelUpdateNew ' + CONVERT(CHAR(1), 0) + ',' + CONVERT(VARCHAR(10), @cvMainID) + ',4,1'
		EXEC(@SQL)
	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH
COMMIT TRAN
RETURN @MaxID
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END














GO
/****** Object:  StoredProcedure [dbo].[mblCvExperienceSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[mblCvExperienceSelect]
(
	@cvMainID INT
)
AS
BEGIN
	SELECT a.*, b.Description JobType, c.Description CpmpanySize, d.Description Industry,
		g.Description LowerNumber, e.Description CompanyKind, f.Description LeaveReson, h.FullName Region
	FROM cvExperience a WITH(NOLOCK INDEX(IX_cvExperience_cvMainID))
	LEFT JOIN dcJobType b WITH(NOLOCK) ON a.dcJobTypeID=b.ID
	LEFT JOIN dcCompanySize c WITH(NOLOCK) ON a.dcCompanySizeID=c.ID
	LEFT JOIN dcIndustry d WITH(NOLOCK) ON a.dcIndustryID=d.ID
	LEFT JOIN dcLowerNumber g WITH(NOLOCK) ON a.SubNodeNum=g.ID
	LEFT JOIN dcCompanyKind e WITH(NOLOCK) ON a.dcCompanyKindID=e.ID
	LEFT JOIN dcLeaveReson f WITH(NOLOCK) ON a.dcLeaveResonID=f.ID
	LEFT JOIN dcRegion h WITH(NOLOCK) ON a.WorkPlace=h.ID
	WHERE cvMainID = @cvMainID
	ORDER BY a.BeginDate DESC
END

set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON














GO
/****** Object:  StoredProcedure [dbo].[mblCvInfoSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[mblCvInfoSelect]
(
	@cvMainID INT, 
	@paMainID INT
)
AS
BEGIN
	--获取个人信息
	SELECT 1 dcCareerStatus,  a.*, 
		b.FullName LiveRegion, c.FullName GrowRegion, d.FullName AccountRegion,
		ISNULL(e.Description, '目前处于离职状态，可即刻上岗') CareerStatus, f.PhotoProcessed,
		(SELECT TOP 1 LoginIP FROM paLoginLog WITH(NOLOCK) WHERE paLoginLog.paMainID = a.ID ORDER BY ID DESC) AS LastLoginIP, 
		(SELECT COUNT(1) FROM paLoginLog WITH(NOLOCK) WHERE paLoginLog.paMainID = a.ID AND AddDate > CONVERT(VARCHAR(10),  GETDATE(),  120)) AS TodayLoginNum, 
		dbo.BirthToAge(a.BirthDay) Age
	FROM paMain a WITH(NOLOCK INDEX(PK_paMain))
	LEFT JOIN dcRegion b WITH(NOLOCK) ON a.LivePlace=b.ID
	LEFT JOIN dcRegion c WITH(NOLOCK) ON a.GrowPlace=c.ID
	LEFT JOIN dcRegion d WITH(NOLOCK) ON a.AccountPlace=d.ID
	LEFT JOIN dcCareerStatus e WITH(NOLOCK) ON a.dcCareerStatus=e.ID
	LEFT JOIN paPhoto f WITH(NOLOCK) ON a.HasPhoto<2 AND a.ID=f.paMainID
	WHERE a.ID = @paMainID

	--获取简历信息
	SELECT *
	FROM cvMain WITH(NOLOCK INDEX(PK_cvMain))
	WHERE ID = @cvMainID
	
	--获取教育背景
	SELECT a.*, b.Description Major,  c.Description EduTypeName,  d.Description Education
	FROM cvEducation a WITH(NOLOCK INDEX(IX_cvEducation_CvMainID)), 
		dcMajor b WITH(NOLOCK), 
		dcEduType c WITH(NOLOCK), 
		dcEducation d WITH(NOLOCK)
	WHERE a.dcMajorID=b.ID AND a.EduType=c.ID AND a.Degree=d.ID AND a.cvMainID=@cvMainID
	ORDER BY a.Degree DESC, a.Graduation Desc
	
	--获取工作经验
	SELECT a.*,  b.Description JobType,  c.Description CpmpanySize,  d.Description Industry, 
		g.Description LowerNumber,  e.Description CompanyKind,  f.Description LeaveReson,  h.FullName Region
	FROM cvExperience a WITH(NOLOCK INDEX(IX_cvExperience_cvMainID))
	LEFT JOIN dcJobType b WITH(NOLOCK) ON a.dcJobTypeID=b.ID
	LEFT JOIN dcCompanySize c WITH(NOLOCK) ON a.dcCompanySizeID=c.ID
	LEFT JOIN dcIndustry d WITH(NOLOCK) ON a.dcIndustryID=d.ID
	LEFT JOIN dcLowerNumber g WITH(NOLOCK) ON a.SubNodeNum=g.ID
	LEFT JOIN dcCompanyKind e WITH(NOLOCK) ON a.dcCompanyKindID=e.ID
	LEFT JOIN dcLeaveReson f WITH(NOLOCK) ON a.dcLeaveResonID=f.ID
	LEFT JOIN dcRegion h WITH(NOLOCK) ON a.WorkPlace=h.ID
	WHERE cvMainID=@cvMainID
	ORDER BY a.BeginDate DESC

	--获取求职意向
	DECLARE @JobType AS VARCHAR(100)
	DECLARE @JobTypeName AS VARCHAR(1000)
	DECLARE @JobPlace AS VARCHAR(100)
	DECLARE @JobPlaceName AS VARCHAR(100)
	DECLARE @Industry AS VARCHAR(100)
	DECLARE @IndustryName AS VARCHAR(100)
	DECLARE @INTTemp AS INT
	DECLARE @STRTemp AS VARCHAR(20)
	DECLARE #JobType CURSOR FOR SELECT a.dcJobTypeID, b.Description JobType FROM cvJobType a WITH(NOLOCK), dcJobType b WITH(NOLOCK) WHERE a.dcJobTypeID=b.ID AND a.cvMainID=@cvMainID ORDER BY a.dcJobTypeID
	DECLARE #JobPlace CURSOR FOR SELECT a.dcRegionID, b.FullName Region FROM cvJobPlace a WITH(NOLOCK), dcRegion b WITH(NOLOCK) WHERE a.dcRegionID=b.ID AND a.cvMainID=@cvMainID ORDER BY a.dcRegionID
	DECLARE #Industry CURSOR FOR SELECT a.dcIndustryID, b.Description Industry FROM cvIndustry a WITH(NOLOCK), dcIndustry b WITH(NOLOCK) WHERE a.dcIndustryID=b.ID AND a.cvMainID=@cvMainID ORDER BY dcIndustryID
 
	--取得JobType	
	OPEN #JobType
	FETCH NEXT FROM #JobType INTO @INTTemp, @STRTemp
	WHILE @@FETCH_STATUS = 0 
	BEGIN 
		IF Len(@JobType) > 0
		BEGIN
			SET @JobType = @JobType + ' ' +  Rtrim(CONVERT(CHAR(10), @INTTemp))
			SET @JobTypeName = @JobTypeName + ' ' + @STRTemp
		END
		ELSE
		BEGIN
			SET @JobType = Rtrim(CONVERT(CHAR(10), @INTTemp))
			SET @JobTypeName = @STRTemp
		END
		FETCH NEXT FROM #JobType INTO @INTTemp, @STRTemp
	END
	CLOSE #JobType
	DEALLOCATE #JobType
 
	--取得JobPlace	
	OPEN #JobPlace
	FETCH NEXT FROM #JobPlace INTO @INTTemp, @STRTemp
	WHILE @@FETCH_STATUS = 0 
	BEGIN 
		IF Len(@JobPlace) > 0
		BEGIN
			SET @JobPlace = @JobPlace + ' ' + Rtrim(CONVERT(CHAR(10), @INTTemp))
			SET @JobPlaceName = @JobPlaceName + ' ' + @STRTemp
		END
		ELSE
		BEGIN
			SET @JobPlace = Rtrim(CONVERT(CHAR(10), @INTTemp))
			SET @JobPlaceName = @STRTemp
		END
		FETCH NEXT FROM #JobPlace INTO @INTTemp, @STRTemp
	END
	CLOSE #JobPlace
	DEALLOCATE #JobPlace 
	--取得Industry	
	OPEN #Industry
	FETCH NEXT FROM #Industry INTO @INTTemp, @STRTemp
	WHILE @@FETCH_STATUS = 0 
	BEGIN 
		IF Len(@Industry) > 0
		BEGIN
			SET @Industry = @Industry + ' ' + Rtrim(CONVERT(CHAR(10), @INTTemp))
			SET @IndustryName = @IndustryName + ' ' + @STRTemp
		END
		ELSE
		BEGIN
			SET @Industry = Rtrim(CONVERT(CHAR(10), @INTTemp))
			SET @IndustryName = @STRTemp
		END
		FETCH NEXT FROM #Industry INTO @INTTemp, @STRTemp
	END
	CLOSE #Industry
	DEALLOCATE #Industry
	SELECT
		RelatedWorkYears, 
		EmployType, 
		dcSalaryID, 
		IsNegotiable, 
		b.Description Salary, 
		@JobType AS JobType, 
		@JobPlace AS JobPlace, 
		@Industry AS Industry, 
		@JobTypeName AS JobTypeName, 
		@JobPlaceName AS JobPlaceName, 
		@IndustryName AS IndustryName
	From cvMain a WITH(NOLOCK)
	LEFT JOIN dcSalary b WITH(NOLOCK) ON a.dcSalaryID=b.ID
	WHERE a.id=@cvMainID
END



GO
/****** Object:  StoredProcedure [dbo].[mblCvInfoSelect2]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--peter 2018-3-28
CREATE PROCEDURE [dbo].[mblCvInfoSelect2]
(
	@cvMainID INT, 
	@paMainID INT
)
AS
SET NOCOUNT ON
BEGIN
	--获取个人信息
	SELECT a.*, b.FullName LiveRegion, c.FullName GrowRegion, d.FullName AccountRegion,
		e.Description CareerStatus, f.PhotoProcessed,g.Description OnlineContactName,h.Name MapPlaceName,
		(SELECT TOP 1 LoginIP FROM paLoginLog WITH(NOLOCK) WHERE paLoginLog.paMainID = a.ID ORDER BY ID DESC) AS LastLoginIP, 
		(SELECT COUNT(1) FROM paLoginLog WITH(NOLOCK) WHERE paLoginLog.paMainID = a.ID AND AddDate > CONVERT(VARCHAR(10),  GETDATE(),  120)) AS TodayLoginNum, 
		dbo.BirthToAge(a.BirthDay) Age
	FROM paMain a WITH(NOLOCK INDEX(PK_paMain))
	LEFT JOIN dcRegion b WITH(NOLOCK) ON a.LivePlace=b.ID
	LEFT JOIN dcRegion c WITH(NOLOCK) ON a.GrowPlace=c.ID
	LEFT JOIN dcRegion d WITH(NOLOCK) ON a.AccountPlace=d.ID
	LEFT JOIN dcCareerStatus e WITH(NOLOCK) ON a.dcCareerStatus=e.ID
	LEFT JOIN paPhoto f WITH(NOLOCK) ON a.HasPhoto<2 AND a.ID=f.paMainID
	LEFT JOIN dcOnlineContact g WITH(NOLOCK) ON a.OnlineContact = g.ID
	LEFT JOIN dcMapPlace h WITH(NOLOCK) ON a.dcMapPlaceID = h.ID
	WHERE a.ID = @paMainID

	--获取简历信息
	SELECT a.*, b.Description EmployTypeName, c.Description DegreeName
    FROM cvMain a WITH(NOLOCK INDEX(PK_cvMain))
    LEFT JOIN dcOthers b WITH(NOLOCK) ON a.EmployType = b.DetailID AND b.Category = '工作性质'
    LEFT JOIN dcEducation c WITH(NOLOCK) ON a.Degree = c.ID
    WHERE a.ID = @cvMainID
	
	--获取教育背景
	SELECT a.*, b.Description Major,  c.Description EduTypeName, d.Description DegreeName
	FROM cvEducation a WITH(NOLOCK INDEX(IX_cvEducation_CvMainID)), 
		dcMajor b WITH(NOLOCK), 
		dcEduType c WITH(NOLOCK), 
		dcEducation d WITH(NOLOCK)
	WHERE a.dcMajorID=b.ID AND a.EduType=c.ID AND a.Degree=d.ID AND a.cvMainID=@cvMainID
	ORDER BY a.Degree DESC, a.Graduation Desc
	
	--获取工作经验
	SELECT a.*,  b.Description JobType,  c.Description CpmpanySize,  d.Description Industry, 
		g.Description LowerNumber,  e.Description CompanyKind,  f.Description LeaveReson,  h.FullName Region
	FROM cvExperience a WITH(NOLOCK INDEX(IX_cvExperience_cvMainID))
	LEFT JOIN dcJobType b WITH(NOLOCK) ON a.dcJobTypeID=b.ID
	LEFT JOIN dcCompanySize c WITH(NOLOCK) ON a.dcCompanySizeID=c.ID
	LEFT JOIN dcIndustry d WITH(NOLOCK) ON a.dcIndustryID=d.ID
	LEFT JOIN dcLowerNumber g WITH(NOLOCK) ON a.SubNodeNum=g.ID
	LEFT JOIN dcCompanyKind e WITH(NOLOCK) ON a.dcCompanyKindID=e.ID
	LEFT JOIN dcLeaveReson f WITH(NOLOCK) ON a.dcLeaveResonID=f.ID
	LEFT JOIN dcRegion h WITH(NOLOCK) ON a.WorkPlace=h.ID
	WHERE cvMainID=@cvMainID
	ORDER BY a.BeginDate DESC

	--获取求职意向
	DECLARE @JobType AS VARCHAR(100)
	DECLARE @JobTypeName AS VARCHAR(1000)
	DECLARE @JobPlace AS VARCHAR(100)
	DECLARE @JobPlaceName AS VARCHAR(100)
	DECLARE @Industry AS VARCHAR(100)
	DECLARE @IndustryName AS VARCHAR(100)
	DECLARE @INTTemp AS INT
	DECLARE @STRTemp AS VARCHAR(50)
	DECLARE #JobType CURSOR FOR SELECT a.dcJobTypeID, b.Description JobType FROM cvJobType a WITH(NOLOCK), dcJobType b WITH(NOLOCK) WHERE a.dcJobTypeID=b.ID AND a.cvMainID=@cvMainID ORDER BY a.dcJobTypeID
	DECLARE #JobPlace CURSOR FOR SELECT a.dcRegionID, b.FullName Region FROM cvJobPlace a WITH(NOLOCK), dcRegion b WITH(NOLOCK) WHERE a.dcRegionID=b.ID AND a.cvMainID=@cvMainID ORDER BY a.dcRegionID
	DECLARE #Industry CURSOR FOR SELECT a.dcIndustryID, b.Description Industry FROM cvIndustry a WITH(NOLOCK), dcIndustry b WITH(NOLOCK) WHERE a.dcIndustryID=b.ID AND a.cvMainID=@cvMainID ORDER BY dcIndustryID
 
	--取得JobType	
	OPEN #JobType
	FETCH NEXT FROM #JobType INTO @INTTemp, @STRTemp
	WHILE @@FETCH_STATUS = 0 
	BEGIN 
		IF Len(@JobType) > 0
		BEGIN
			SET @JobType = @JobType + ' ' +  Rtrim(CONVERT(VARCHAR(20), @INTTemp))
			SET @JobTypeName = @JobTypeName + ' ' + @STRTemp
		END
		ELSE
		BEGIN
			SET @JobType = Rtrim(CONVERT(VARCHAR(20), @INTTemp))
			SET @JobTypeName = @STRTemp
		END
		FETCH NEXT FROM #JobType INTO @INTTemp, @STRTemp
	END
	CLOSE #JobType
	DEALLOCATE #JobType
 
	--取得JobPlace	
	OPEN #JobPlace
	FETCH NEXT FROM #JobPlace INTO @INTTemp, @STRTemp
	WHILE @@FETCH_STATUS = 0 
	BEGIN 
		IF Len(@JobPlace) > 0
		BEGIN
			SET @JobPlace = @JobPlace + ' ' + Rtrim(CONVERT(VARCHAR(20), @INTTemp))
			SET @JobPlaceName = @JobPlaceName + ' ' + @STRTemp
		END
		ELSE
		BEGIN
			SET @JobPlace = Rtrim(CONVERT(VARCHAR(20),@INTTemp))
			SET @JobPlaceName = @STRTemp
		END
		FETCH NEXT FROM #JobPlace INTO @INTTemp, @STRTemp
	END
	CLOSE #JobPlace
	DEALLOCATE #JobPlace 
	--取得Industry	
	OPEN #Industry
	FETCH NEXT FROM #Industry INTO @INTTemp, @STRTemp
	WHILE @@FETCH_STATUS = 0 
	BEGIN 
		IF Len(@Industry) > 0
		BEGIN
			SET @Industry = @Industry + ' ' + Rtrim(CONVERT(VARCHAR(20), @INTTemp))
			SET @IndustryName = @IndustryName + ' ' + @STRTemp
		END
		ELSE
		BEGIN
			SET @Industry = Rtrim(CONVERT(VARCHAR(20), @INTTemp))
			SET @IndustryName = @STRTemp
		END
		FETCH NEXT FROM #Industry INTO @INTTemp, @STRTemp
	END
	CLOSE #Industry
	DEALLOCATE #Industry
	SELECT
		RelatedWorkYears, 
		EmployType, 
		dcSalaryID, 
		IsNegotiable, 
		b.Description Salary, 
		@JobType AS JobType, 
		@JobPlace AS JobPlace, 
		@Industry AS Industry, 
		@JobTypeName AS JobTypeName, 
		@JobPlaceName AS JobPlaceName, 
		@IndustryName AS IndustryName
	From cvMain a WITH(NOLOCK)
	LEFT JOIN dcSalary b WITH(NOLOCK) ON a.dcSalaryID=b.ID
	WHERE a.id=@cvMainID
END

GO
/****** Object:  StoredProcedure [dbo].[mblCvmainByIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.06
--创建人：Nick
--说明：获取个人信息
--#####################################################
CREATE PROCEDURE [dbo].[mblCvmainByIDSelect]
(
	@cvMainID INT
)
AS
BEGIN TRY
	SELECT pamainid FROM cvmain WHERE id=@cvMainID
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[mblCvMainByPaMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.06
--创建人：Nick
--说明：获取能够申请职位的简历列表
--#####################################################
CREATE PROCEDURE [dbo].[mblCvMainByPaMainIDSelect]
(
	@paMainID INT
)
AS
BEGIN TRY
	SELECT * FROM cvMain WITH(NOLOCK) 
	WHERE paMainID=@paMainID 
	AND (LEFT(cvLevel,6)='111111' OR LEFT(cvLevel,6)='111101')
	AND VerifyResult=1
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[mbldcJobtypeHotByPinYinSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.06
--创建人：Nick
--说明：获取热门职位信息
--#####################################################
CREATE PROCEDURE [dbo].[mbldcJobtypeHotByPinYinSelect]
(
	@PinYin VARCHAR(50)
)
AS
BEGIN TRY
	SELECT jobname,dcjobtypeid FROM dcjobtypehot WHERE pinyin = @PinYin
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[mblDcJobTypeHotNumberSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.7
--创建人：John
--说明：根据地区取得一定数量的热门职位关键字
--#####################################################
CREATE PROCEDURE [dbo].[mblDcJobTypeHotNumberSelect]
(
	@topNum INT,
	@siteId INT
)
AS
BEGIN
	SELECT b.* FROM (
		SELECT TOP (@topNum) dcJobTypeHotId 
		FROM dcJobTypeHotNumber WITH(NOLOCK)
		WHERE dcProvinceId = @siteId 
		ORDER BY jobnumber DESC
		) a LEFT JOIN dcJobTypeHot b WITH(NOLOCK) ON a.dcJobTypeHotId = b.ID
END


GO
/****** Object:  StoredProcedure [dbo].[mbldcSubSiteByAddressSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.7
--创建人：Nick
--说明：根据详细地址获取站点
--#####################################################
CREATE PROCEDURE [dbo].[mbldcSubSiteByAddressSelect]
(
	@Address VARCHAR(100)
)
AS
BEGIN
	SELECT TOP 1 * FROM dcSubSite WITH(NOLOCK) 
	WHERE CHARINDEX(SubSiteCity,@Address)>0 
	AND IsMainSite=1 AND LEN(ID)=2
END


GO
/****** Object:  StoredProcedure [dbo].[mblDcSubSiteMainSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.7
--创建人：John
--说明：获取主站的url
--#####################################################
CREATE PROCEDURE [dbo].[mblDcSubSiteMainSelect]
AS
BEGIN
	SELECT id, REPLACE(SubSiteUrl, 'www.', 'm.') Site FROM dcSubsite WITH(NOLOCK) WHERE IsMainSite = 1 ORDER BY Id
END

GO
/****** Object:  StoredProcedure [dbo].[mbldcSubSiteSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.7
--创建人：Nick
--说明：获取网站信息
--#####################################################
CREATE PROCEDURE [dbo].[mbldcSubSiteSelect]
AS
BEGIN
	SELECT *, REPLACE(SubSiteUrl, 'www.', 'm.') Site
	FROM dcSubSite WITH(NOLOCK) WHERE IsMainSite=1 AND LEN(ID)=2
END


GO
/****** Object:  StoredProcedure [dbo].[mblExInterViewByReplyUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[mblExInterViewByReplyUpdate]
(
	@ID INT,
	@Reply TINYINT,
	@ReplyMessage VARCHAR(500),
	@paMainID INT
)
AS
BEGIN TRY
	IF NOT EXISTS(SELECT 'x' FROM exInterview a WITH(NOLOCK), cvMain b WITH(NOLOCK) WHERE a.id=@ID AND a.cvMainID=b.ID AND b.paMainID=@paMainID)
		GOTO ERR

	UPDATE exInterView 
	SET Reply = @Reply, ReplyMessage = dbo.SafeSql(@ReplyMessage), ReplyDate=GETDATE()
	WHERE ID = @ID
	
	RETURN 1
END TRY
BEGIN CATCH
	GOTO ERR
END CATCH
ERR:
BEGIN
	SELECT 0
	RETURN
END














GO
/****** Object:  StoredProcedure [dbo].[mblexInterViewCountByPaMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.4
--创建人：Nick
--说明：未查看面试通知消息数量
--#####################################################
CREATE PROCEDURE [dbo].[mblexInterViewCountByPaMainIDSelect]
(
	@paMainID INT
)
AS
BEGIN
	SELECT COUNT(*) 
	FROM paMain a INNER JOIN cvMain b ON a.id =b.pamainid 
	INNER JOIN exInterView c ON b.id=c.cvmainid 
	WHERE a.id=@paMainID AND c.viewdate IS NULL
END


GO
/****** Object:  StoredProcedure [dbo].[mblExInterviewSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[mblExInterviewSelect]
(
	@paMainID AS INT,
	@PageNum AS INT,
	@PageSize AS INT
)
AS
BEGIN
	DECLARE @COUNT INT
	SELECT @COUNT=COUNT(1) 
		FROM exInterview a WITH(NOLOCK)
		INNER JOIN cvMain b WITH(NOLOCK) ON a.cvMainID = b.ID 
	WHERE PersonDeleted=0 AND b.paMainID=@paMainID
 
 
	SELECT *,@COUNT AS cnt FROM(
		SELECT ROW_NUMBER() OVER(ORDER BY a.AddDate DESC) AS Rows,a.*, b.Name as JobName, b.caMainID, b.dcRegionID, c.Name as cpName, c.ID as cpID,
				c.HasLicence, c.IsAgent, b.IssueDate, b.IssueEND, b.IsDelete, d.Name cvName,b.secondid enjobid
				FROM exInterview a WITH(NOLOCK) 
				inner join Job b WITH(NOLOCK) On b.ID=a.JobID 
				Inner Join cpMain c WITH(NOLOCK) ON b.cpMainID=c.ID 
				INNER JOIN cvMain d WITH(NOLOCK) ON a.cvMainID = d.ID 
		WHERE PersonDeleted=0 AND d.paMainID=@paMainID
	) AS a 
	WHERE a.Rows BETWEEN (@PageNum-1)*@PageSize+1 AND @PageNum*@PageSize ORDER BY a.ID desc
END











GO
/****** Object:  StoredProcedure [dbo].[mblExJobApplyByApplyCvSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[mblExJobApplyByApplyCvSelect]
(
	@WHERE VARCHAR(1000), 
	@Order VARCHAR(100), 
	@Page SMALLINT, 
	@caMainID INT
)
AS
SET NOCOUNT ON
BEGIN
	SET @Where = dbo.SafeSql(@Where)
	SET @ORDER = REPLACE(dbo.SafeSQL(@ORDER), '''', '''''')
	
	DECLARE @SQL AS VARCHAR(2000)
	CREATE TABLE #T(
		TitleID BIGINT, 
		ID INT, 
		JobID INT, 
		JobName NVARCHAR(50) COLLATE Chinese_PRC_CI_AS NULL,
		JobRegion VARCHAR(6) NULL, 
		paMainID INT, 
		cvMainID INT, 
		AddDate SMALLDATETIME, 
		Reply TINYINT, 
		ReplyDate SMALLDATETIME, 
		IsMatched BIT, 
		Degree TINYINT, 
		RelatedWorkYears TINYINT, 
		LivePlace NVARCHAR(50), 
		Gender BIT, 
		paName NVARCHAR(50), 
		BirthDay INT, 
		HasPhoto TINYINT, 
		Attachment VARCHAR(50) COLLATE Chinese_PRC_CI_AS, 
		IsNameHidden BIT, 
		Valid TINYINT, 
		ApplyMessage NVARCHAR(1), 
		IsViewed BIT, 
		HasInterview BIT, 
		HasRemark BIT, 
		HasFavorate BIT, 
		cvEducationID INT, 
		College NVARCHAR(50), 
		EduType TINYINT, 
		MajorName NVARCHAR(20), 
		Graduation INT, 
		Speciality VARCHAR(MAX) COLLATE Chinese_PRC_CI_AS, 
		Experience VARCHAR(MAX) COLLATE Chinese_PRC_CI_AS, 
		cvMatch INT, 
		RecruitmentID INT, 
		RecruitmentName NVARCHAR(100), 
		RecruitmentDate SMALLDATETIME, 
		MobileVerifyDate SMALLDATETIME, 
		IsOnline BIT, 
		RemindDate DATETIME, 
		HasWeiXin BIT, 
		HasAccept BIT, 
		HsaNoAccept BIT, 
		PaPhoto VARCHAR(50), 
		SecondId VARCHAR(10)
	)

	SET @SQL='
		INSERT INTO #T
		(TitleID, ID, JobID, JobName, JobRegion, paMainID, cvMainID, AddDate, Reply, ReplyDate, IsMatched, ApplyMessage, 
			Degree, RelatedWorkYears, Attachment, IsNameHidden, LivePlace, Gender, 
			BirthDay, HasPhoto, Valid, RecruitmentID, MobileVerifyDate, IsOnline, RemindDate, SecondId)
		SELECT ROW_NUMBER() OVER (ORDER BY ' + @ORDER + ') AS TitleID, a.ID, a.JobID, d.Name, d.dcRegionID, c.ID, a.cvMainID, 
			a.AddDate, a.Reply, a.ReplyDate, a.IsMatched, LEFT(a.ApplyMessage, 1) ApplyMessage, 
			b.Degree, b.RelatedWorkYears, b.Attachment, b.IsNameHidden, c.LivePlace, 
			c.Gender, c.BirthDay, c.HasPhoto, b.Valid, a.RecruitmentID, c.MobileVerifyDate,
			dbo.GetPaOnlineStatus(c.ID), a.RemindDate, b.SecondId
		FROM exJobApply a WITH(NOLOCK)
		INNER JOIN cvMain b WITH(NOLOCK) ON b.ID = a.cvMainID
		INNER JOIN paMain c WITH(NOLOCK) ON c.ID = b.paMainID
		INNER JOIN Job d WITH(NOLOCK) ON d.ID = a.JobID
		WHERE a.CompanyDeleted = 0 AND d.IsDelete = 0'
	IF LEN(@WHERE) > 0
		SET @SQL = @SQL + ' AND '+@WHERE

	--PRINT @SQL
	EXEC(@SQL)
	
	IF(@Page < 1)
		SET @Page = 1	
	
	DECLARE @cpMainID AS INT
	SELECT @cpMainID = cpMainID FROM caMain WITH(NOLOCK) WHERE ID = @caMainID
	UPDATE #T SET paName = LEFT(dbo.GetPersonName(cvMainID, @cpMainID), 20), IsViewed = (SELECT TOP 1 '1' FROM caCvViewLog WITH(NOLOCK) WHERE cvMainID=#T.cvMainID AND caMainID=@caMainID), 
		HasFavorate = (SELECT TOP 1 '1' FROM caFavorate WITH(NOLOCK) WHERE caMainID=@caMainID AND cvMainID=#T.cvMainID), 
		HasInterview = (SELECT TOP 1 '1' FROM exInterview a WITH(NOLOCK) INNER JOIN Job b WITH(NOLOCK) ON a.JobID=b.ID WHERE a.CompanyDeleted=0 AND b.caMainID=@caMainID AND cvMainID=#T.cvMainID), 
		HasRemark = (SELECT TOP 1 '1' FROM caCvRemark WITH(NOLOCK) WHERE caMainID=@caMainID AND cvMainID=#T.cvMainID), 
		HasAccept = (SELECT TOP 1 '1' FROM exInterview a WITH(NOLOCK) INNER JOIN Job b WITH(NOLOCK) ON a.JobID=b.ID WHERE a.CompanyDeleted=0 AND b.caMainID=@caMainID AND cvMainID=#T.cvMainID AND a.Result = 1), 
		HsaNoAccept = (SELECT TOP 1 '1' FROM exInterview a WITH(NOLOCK) INNER JOIN Job b WITH(NOLOCK) ON a.JobID=b.ID WHERE a.CompanyDeleted=0 AND b.caMainID=@caMainID AND cvMainID=#T.cvMainID AND a.Result > 1)
	WHERE TitleID > (@Page-1)*20 AND  TitleID <= @Page*20

	UPDATE #T SET Speciality = (
		SELECT Speciality FROM cvMain WITH(NOLOCK)
		WHERE cvMain.ID = #T.cvMainID)
	WHERE TitleID > (@Page - 1) * 20 AND TitleID <= @Page * 20
	
	--sean 2018-3－６调整，原版本速度太慢
	--UPDATE #T SET PaPhoto = dbo.GetPaPhotoByCpView(#T.cvMainID, @cpMainID)
	--WHERE TitleID > (@Page-1)*20 AND  TitleID <= @Page*20
	UPDATE a SET a.PaPhoto = b.PhotoProcessed 
	FROM #T a,
		paPhoto b WITH(NOLOCK INDEX(IX_paPhoto_paMainId)),
		cpCvPrivi c WITH(NOLOCK)
	WHERE a.paMainID = b.paMainId
	AND a.TitleID > (@Page-1)*20 AND a.TitleID <= @Page*20
	AND a.cvMainId = c.cvMainId
	AND c.cpMainId = @cpMainId
		

	UPDATE #T SET Experience = (
		SELECT TOP 1 ISNULL(Description, DescriptionEng) FROM cvExperience WITH(NOLOCK)
		WHERE cvExperience.cvMainID = #T.cvMainID
		ORDER BY BeginDate DESC)
	WHERE TitleID > (@Page-1)*20 AND  TitleID <= @Page*20

	UPDATE #T SET cvEducationID = (
		SELECT TOP 1 ID FROM cvEducation WITH(NOLOCK)
		WHERE cvEducation.cvMainID = #T.cvMainID
		AND #T.Degree = cvEducation.Degree
		ORDER BY Graduation DESC)
	WHERE TitleID > (@Page-1)*20 AND  TitleID <= @Page*20

	--修改是否绑定微信
	UPDATE a SET HasWeiXin = 1
	FROM #T a, WxFans b WITH(NOLOCK)
	WHERE a.paMainID = b.PaMainID
	AND b.Status = 2
	AND a.TitleID > (@Page-1)*20 AND  TitleID <= @Page*20

	UPDATE a SET a.College = ISNULL(b.GraduateCollage, b.GraduateCollageEng), a.EduType = b.EduType, 
		a.MajorName = ISNULL(b.MajorName, b.MajorNameEng), a.Graduation = b.Graduation
	FROM #T a, cvEducation b WITH(NOLOCK)
	WHERE b.ID = a.cvEducationID AND a.TitleID > (@Page-1)*20 AND a. TitleID <= @Page*20
	
	UPDATE a SET a.RecruitmentName = b.RecruitmentName, a.RecruitmentDate = b.EndDate
	FROM #T a, Recruitment b WITH(NOLOCK)
	WHERE b.ID = a.RecruitmentID AND a.TitleID > (@Page-1)*20 AND a. TitleID <= @Page*20
	
	UPDATE #T SET cvMatch = dbo.GetCvMatch(cvMainID, JobID) WHERE TitleID > (@Page-1)*20 AND  TitleID <= @Page*20

	SELECT COUNT(*) FROM #T WITH(NOLOCK)
	
	SELECT a.*,b.Description DegreeName,c.MapBarName LivePlaceName,d.Description JobRegionName, dbo.BirthToAge(a.BirthDay) Age
	FROM #T a WITH(NOLOCK) 
	LEFT JOIN dcEducation b WITH(NOLOCK) ON b.ID = a.Degree
	LEFT JOIN dcRegion c WITH(NOLOCK) ON c.ID = a.LivePlace
	LEFT JOIN dcRegion d WITH(NOLOCK) ON d.ID = a.JobRegion 
	WHERE a.TitleID > (@Page-1)*20 AND a.TitleID <= @Page*20

	--计算匹配度
	DROP TABLE #T
END

GO
/****** Object:  StoredProcedure [dbo].[mblexJobApplyNoViewByCaMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.06
--创建人：Nick
--说明：简历管理未查看的应聘简历
--#####################################################
CREATE PROCEDURE [dbo].[mblexJobApplyNoViewByCaMainIDSelect]
(
	@caMainID INT
)
AS
BEGIN TRY
	SELECT COUNT(*) Cnt 
	FROM exJobApply a WITH(NOLOCK), Job b WITH(NOLOCK) 
	WHERE  a.JobID =b.ID 
	AND b.caMainID = @caMainID 
	AND a.viewdate IS NULL
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[mblExJobApplySelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[mblExJobApplySelect]
(
	@paMainID AS INT,
	@PageNum AS INT,
	@PageSize AS INT
)
AS
SET NOCOUNT ON
INSERT  ProcLog SELECT 'mblExJobApplySelect', '', GETDATE()
BEGIN
	DECLARE @COUNT INT
	SELECT @COUNT=COUNT(1) 
		FROM exJobApply a WITH(NOLOCK)
		INNER JOIN cvMain b WITH(NOLOCK) ON a.cvMainID = b.ID 
	WHERE b.paMainID=@paMainID 
 
 
	SELECT *,@COUNT AS cnt FROM(
		SELECT ROW_NUMBER() OVER(ORDER BY a.AddDate DESC) AS Rows,a.ID, a.JobID, a.cvMainID, a.ApplyMessage, a.AddDate, a.CompanyDeleted, a.CompanyDeleteDate,
				a.PersonDeleted, a.Reply, a.ReplyDate, b.Name as JobName, b.caMainID, b.dcRegionID, c.Name as cpName, c.ID as cpID,c.secondid encpid,
				c.HasLicence, c.IsAgent, b.IssueDate, b.IssueEND, b.IsDelete, d.Name cvName, b.secondid enjobid
				FROM exJobApply a WITH(NOLOCK) 
				inner join Job b WITH(NOLOCK) On b.ID=a.JobID 
				Inner Join cpMain c WITH(NOLOCK) ON b.cpMainID=c.ID 
				INNER JOIN cvMain d WITH(NOLOCK) ON a.cvMainID = d.ID 
		WHERE PersonDeleted=0 AND d.paMainID=@paMainID 
	) AS a 
	WHERE a.Rows BETWEEN (@PageNum-1)*@PageSize+1 AND @PageNum*@PageSize ORDER BY A.ID desc
END











GO
/****** Object:  StoredProcedure [dbo].[mblFeedBackInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[mblFeedBackInsert]
(
	@Content NVARCHAR(200),
	@Version VARCHAR(50),
	@paMainID INT
)
AS
BEGIN
	INSERT INTO mblFeedBack(Content,Version,paMainID) VALUES(dbo.SafeSQL(@Content),dbo.SafeSQL(@Version),@paMainID)
END














GO
/****** Object:  StoredProcedure [dbo].[mblGovNewsList]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[mblGovNewsList]
(
	@dcProvinceID AS SMALLINT,
	@PageNum AS INT,
	@PageSize AS INT
)
AS
BEGIN
	DECLARE @COUNT INT
	SELECT @COUNT=COUNT(1) 
		FROM QlrcNews WITH(NOLOCK) WHERE (
			EXISTS(SELECT 'x' FROM fnSplit(DetailType,',') b,dcNewsType c WITH(NOLOCK) WHERE b.a=c.ID AND c.Category=1) OR DetailType IS NULL) 
			AND (VersionID=@dcProvinceID OR VersionID=0) AND NewsType = 2 AND DetailType like '%,2,%'

	IF @COUNT > 200
		SET @COUNT = 200

	SELECT *,@COUNT AS cnt FROM(
		SELECT TOP 200 ROW_NUMBER() OVER(ORDER BY RefreshDate DESC) AS Rows,ID,Title,RefreshDate,Author 
		FROM QlrcNews WITH(NOLOCK) WHERE (
			EXISTS(SELECT 'x' FROM fnSplit(DetailType,',') b,dcNewsType c WITH(NOLOCK) WHERE b.a=c.ID AND c.Category=1) OR DetailType IS NULL) 
			AND (VersionID=@dcProvinceID OR VersionID=0) AND NewsType = 2 AND DetailType like '%,2,%'
	) AS a 
	WHERE a.Rows BETWEEN (@PageNum-1)*@PageSize+1 AND @PageNum*@PageSize ORDER BY Rows
END

set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON














GO
/****** Object:  StoredProcedure [dbo].[mblInfoSetByIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.7
--创建人：Nick
--说明：获取手机APP下载设置
--#####################################################
CREATE PROCEDURE [dbo].[mblInfoSetByIDSelect]
(
	@ID INT
)
AS
BEGIN
	SELECT * FROM reportdb..InfoSet WITH(NOLOCK) WHERE id=@ID
END


GO
/****** Object:  StoredProcedure [dbo].[mblInfoSetInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.7
--创建人：Nick
--说明：添加手机APP下载记录
--#####################################################
CREATE PROCEDURE [dbo].[mblInfoSetInsert]
(
	@InfoId VARCHAR(20),
	@IP VARCHAR(20),
	@Source VARCHAR(200),
	@SubSiteID VARCHAR(6)
)
AS
BEGIN
	INSERT INTO reportdb..InfoLog(InfoId,IP,Source,SubSiteID,AddDate) 
	VALUES(@InfoId,@IP,@Source,@SubSiteID,GETDATE())
END


GO
/****** Object:  StoredProcedure [dbo].[mblJobByAppSearchSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE proCEDURE [dbo].[mblJobByAppSearchSelect]
(
	@dcJobTypeID VARCHAR(100), 		--职位类别
	@dcRegionID VARCHAR(100), 		--求职地区
	@dcIndustryID VARCHAR(100), 	--求职行业
	@dcSalaryID TINYINT, 			--月薪
	@IsNegotiable BIT, 				--1允许面议，不面议
	@MinExperience TINYINT, 		--工作经验，100为未选择
	@dcEducationID TINYINT, 		--最低学历
	@EmployType VARCHAR(10), 		--工作性质，1全职；3兼职；4实习，
	@KeyWord NVARCHAR(50), 			--关键词
	@KeyType TINYINT, 				--搜索类别，0无；1-全文；2-职位；3-公司 
	@ORDER VARCHAR(4), 				--显示顺序，没有用
	@RefreshNo INT, 				--1, 1天内；2, 3天内；3，一周内；4，15天内；5，一个月内；6超过一个月
	@Type INT, 						--1：主动搜索  点击搜索按钮 10分钟，翻页60分钟有效；0：翻页搜索，不刷新
	@PageNumber INT, 				--翻页页码
	@SessionID varchar(50),					--10
	@CompanySizeID VARCHAR(1), 		--企业规模
	@IsOnline INT,
	@Welfare VARCHAR(50)					--
)
AS
--return   @SessionId = 10
SET NOCOUNT ON
insert into aa
select getdate(), @dcJobTypeID, @dcRegionID, @dcIndustryID, @dcSalaryID, @IsNegotiable,
	@MinExperience, @dcEducationID, @EmployType, @KeyWord, @KeyType, @ORDER, @RefreshNo,
	@Type, @PageNumber, @SessionID, @CompanySizeID, @IsOnline, @Welfare

INSERT INTO SearchIp(Ip, Source) SELECT @SessionId, 'm'
IF EXISTS(SELECT 'x' FROM RefuseIp WITH(NOLOCK) WHERE CHARINDEX(Ip,@SessionId) > 0)
	RETURN
INSERT INTO SearchDB..paSearchLog(ProcType, SessionID, LogTime, JobType, JobPlace, Industry, Education, Experience, 
	Salary, IsNegotiable, EmployType, CompanySizeID, KeyWord, KeyType, ReuseNumber, Welfare, IsOnline, RefreshNo)
VALUES('pcJobBySearchSelect', @SessionId, GETDATE(), @dcJobTypeID, @dcRegionID, @dcIndustryID, @dcEducationID, @MinExperience, 
	@dcSalaryID, 0, @EmployType, @CompanySizeID, @KeyWord, @KeyType, 0, @Welfare, @IsOnline, @RefreshNo)

SET @SessionId = 'a' + @SessionId
SET @KeyType = 0
BEGIN TRY
	DECLARE @ReuseNumber AS INT, @dcProvinceId VARCHAR(2), @Order2 VARCHAR(100)
	----给null值变量赋默认值
	IF NOT LEFT(@dcRegionID,1) = 'p'
		SELECT @dcRegionID = RTRIM(dbo.FormatIDS(@dcRegionID))

	SELECT @dcJobTypeID = RTRIM(dbo.FormatIDS(@dcJobTypeID)),
		@dcIndustryID = RTRIM(dbo.FormatIDS(@dcIndustryID)),
		@dcSalaryID = ISNULL(@dcSalaryID, 0),
		@IsNegotiable = ISNULL(@IsNegotiable, 0),
		@MinExperience = ISNULL(@MinExperience, 100),
		@dcEducationID = ISNULL(@dcEducationID, 0),
		@EmployType = CASE @EmployType WHEN '2' THEN '1,3' ELSE ISNULL(@EmployType, '') END,
		@CompanySizeID = ISNULL(@CompanySizeID, '0'),
		@KeyWord = dbo.SafeSQL(ISNULL(@KeyWord, '')),
		@ORDER = ISNULL(@Order, ''),
		@Type = ISNULL(@Type, 0),
		@PageNumber = ISNULL(@PageNumber, 0),
		@Welfare = RTRIM(dbo.FormatIDS(@Welfare)),
		@IsOnline = ISNULL(@IsOnline, 0),
		@Order2 = ' ORDER BY a.RefreshDate DESC, a.SecondID DESC'

	IF @dcSalaryID = 0
		SET @IsNegotiable = 0

	IF @Order LIKE 'p=%'
		SET @dcProvinceId = REPLACE(@Order, 'p=', '')
	ELSE
		SET @dcProvinceId = 0

	--@RefreshNo = 0选择全部数据，不限制时间
	SET @RefreshNo = 0
	IF(@KeyWord = '' AND ISNULL(@dcJobTypeID, '') = '' AND ISNULL(@dcRegionID, '') = '' AND ISNULL(@dcIndustryID, '') = '')
		RETURN

	--如果关键词不为空 查询关键词对应的搜索类型 max 2012-12-25 
	
	IF RIGHT(@KeyWord, 2) = '公司'
		SET @KeyWord = LEFT(@KeyWord, LEN(@KeyWord) - 2)
		
	IF RIGHT(@dcJobTypeID, 1) = ','
		SET @dcJobTypeID = LEFT(@dcJobTypeID, LEN(@dcJobTypeID) - 1)
	IF RIGHT(@dcRegionID, 1) = ','
		SET @dcRegionID = LEFT(@dcRegionID, LEN(@dcRegionID) - 1)
	IF RIGHT(@dcIndustryID, 1) = ','
		SET @dcIndustryID = LEFT(@dcIndustryID, LEN(@dcIndustryID) - 1)

	DECLARE @paSearchConditionID AS INT, 
		@MinId AS INT, 
		@PageSize AS TINYINT, 
		@TableID AS TINYINT

	SELECT @paSearchConditionID = 0, @PageSize = 30	

	----搜索1分钟前的数据
	SELECT TOP 1 @paSearchConditionID = ID,
		@ReuseNumber = ReuseNumber
	FROM SearchDB..paSearchCondition WITH(NOLOCK)
	WHERE JobType=@dcJobTypeID AND IsOnline = @IsOnline
	AND JobPlace=@dcRegionID AND Industry=@dcIndustryID AND Education=@dcEducationID
	AND Experience=@MinExperience AND Salary=@dcSalaryID AND IsNegotiable=@IsNegotiable 
	AND EmployType=@EmployType AND ISNULL(KeyWord, '') = @KeyWord AND KeyType = @KeyType
	AND CompanySizeID = @CompanySizeID AND Welfare = @Welfare AND IsDelete = 0
	AND LogTime > DATEADD(MINUTE, -1, GETDATE()) AND ReuseNumber > 0
	AND RefreshNo = 0 AND ISNULL(dcProvinceId, 0) = @dcProvinceId
	ORDER BY ID DESC

	IF @ReuseNumber = 0
	BEGIN
		SELECT TOP 1 @paSearchConditionID = ID
		FROM SearchDB..paSearchCondition WITH(NOLOCK)
		WHERE JobType=@dcJobTypeID AND IsOnline = @IsOnline
		AND JobPlace=@dcRegionID AND Industry=@dcIndustryID AND Education=@dcEducationID
		AND Experience=@MinExperience AND Salary=@dcSalaryID AND IsNegotiable=@IsNegotiable 
		AND EmployType=@EmployType AND ISNULL(KeyWord, '') = @KeyWord AND KeyType=@KeyType
		AND CompanySizeID = @CompanySizeID AND Welfare = @Welfare AND ReuseNumber > 0
		AND ReuseNumber > 0 AND LogTime > DATEADD(MINUTE, -2, GETDATE()) 
		AND RefreshNo = 0 AND ISNULL(dcProvinceId, 0) = @dcProvinceId
		ORDER BY ID DESC
	END

	IF ISNULL(@paSearchConditionID, 0) = 0
	BEGIN
		SET @Type =1
		GOTO SelectReset	--无数据，重新搜索
	END
	ELSE
	BEGIN
		SELECT @TableID = @paSearchConditionID % 4
		GOTO GetRecordSet	--从临时结果中提取数据
	END

SelectReset:
	--从job中搜索数据
	BEGIN TRAN
		DECLARE @SQL AS VARCHAR(8000)
		DECLARE @WHERE AS VARCHAR(8000)
		DECLARE @FROM AS VARCHAR(1000)
		----记录查询条件
		INSERT INTO SearchDB..paSearchCondition(SessionID, LogTime, JobType, JobPlace, Industry, Education, Experience, 
			Salary, IsNegotiable, EmployType, CompanySizeID, KeyWord, KeyType, ReuseNumber, Welfare, IsOnline, dcProvinceId)
		VALUES(@SessionId, GETDATE(), @dcJobTypeID, @dcRegionID, @dcIndustryID, @dcEducationID, @MinExperience, 
			@dcSalaryID, @IsNegotiable, @EmployType, @CompanySizeID, @KeyWord, @KeyType, 0, @Welfare, @IsOnline, @dcProvinceId)
		SET @paSearchConditionID = @@IDENTITY
		SELECT @TableID = @paSearchConditionID % 4

		------生成职位类别的表变量，因为职位类别有包含（父子）关系
		DECLARE @T_JobPlace AS TABLE(ID INT)
		DECLARE @T_JobType AS TABLE(ID INT)
		DECLARE @JobPlaceLen AS INT, @JobTypeLen AS INT
		IF CHARINDEX(',', @dcJobTypeID) > 0
			SET @JobTypeLen = -1
		ELSE
			SET @JobTypeLen = LEN(@dcJobTypeID)

		DECLARE @JobType AS VARCHAR(3000), @JobPlace AS VARCHAR(2000), @ValidJobNumber AS INT

		SELECT @JobPlace = '', @JobType=''
		----生成工作地点的表变量
		IF LEN(@dcRegionID) > 0
		BEGIN
			IF LEFT(@dcRegionID,1) = 'p'
			BEGIN
				DECLARE @Degree AS DECIMAL(8,5),@LBLng AS DECIMAL(8,5),@LBLat AS DECIMAL(8,5),
				@RTLng AS DECIMAL(8,5),@RTLat AS DECIMAL(8,5),@Lat AS DECIMAL(8,5),@Lng AS DECIMAL(8,5)
				
				SELECT @Lat = Lat,@Lng = Lng FROM dcMapPlace WITH(NOLOCK) WHERE ID = RIGHT(@dcRegionID,LEN(@dcRegionID)-1)
				IF @dcRegionID LIKE '3201%'
					SET @Degree = 1000 / 100000.0
				ELSE
					SET @Degree = 2000 / 100000.0

				SET @LBLng = @Lng - @Degree
				SET @LBLat = @Lat - @Degree
				SET @RTLng = @Lng + @Degree
				SET @RTLat = @Lat + @Degree
				SET @JobPlace = 'a.Lng BETWEEN ' + CONVERT(VARCHAR,@LBLng) + ' AND ' + CONVERT(VARCHAR,@RTLng) + '
					AND a.Lat BETWEEN ' + CONVERT(VARCHAR,@LBLat) + ' AND ' + CONVERT(VARCHAR,@RTLat) + '
					AND (a.Lng-' + CONVERT(VARCHAR,@Lng) + ')*(a.Lng-' + CONVERT(VARCHAR,@Lng) + ')+
					(a.Lat-' + CONVERT(VARCHAR,@Lat) + ')*(a.Lat-' + CONVERT(VARCHAR,@Lat) + ')<' + CONVERT(VARCHAR,@Degree*@Degree)
				SELECT @JobPlaceLen = 8
			END
			ELSE
			BEGIN
				INSERT INTO @T_JobPlace
				SELECT * FROM dbo.fnSplit(@dcRegionID, ',')
				SELECT @JobPlace = (@JobPlace + ' OR a.dcRegionID Like ''' + LTRIM(STR(ID) + '%''')) FROM @T_JobPlace
				IF LEN(@JobPlace) > 0
					SET @JobPlace = RIGHT(@JobPlace, LEN(@JobPlace) -4)
				IF (SELECT COUNT(*) FROM @T_JobPlace) > 1
					SET @JobPlaceLen = -1
				ELSE
					SET @JobPlaceLen = LEN(@dcRegionID)
			END
		END
		ELSE 
			SELECT @JobPlaceLen = 0


		----生成求聘职位的表变量
		IF LEN(@dcJobTypeID) > 0
		BEGIN
			DECLARE @T_Temp AS TABLE(ID INT)		--临时表，用于构建组合查询语句
			INSERT INTO @T_Temp
			SELECT * FROM dbo.fnSplit(@dcJobTypeID, ',')

			INSERT INTO @T_JobType
			SELECT DISTINCT ID FROM dcJobType WITH(NOLOCK)
			WHERE ParentId IN(SELECT ID FROM @T_TEMP) 
			OR ParentId2 in(SELECT ID FROM @T_TEMP)
			OR ID IN(SELECT ID FROM @T_TEMP)
			----生成in字符串
			SELECT @JobType = (@JobType + LTRIM(STR(ID) + ',')) FROM @T_JobType
			IF RIGHT(@JobType, 1) = ','
				SET @JobType = LEFT(@JobType, LEN(@JobType) - 1)
		END

		----建立临时表
		CREATE TABLE #Job(
			RowID INT IDENTITY(1, 1), 
			ID INT NOT NULL,
			cpMainId INT,
			dcJobTypeID SMALLINT NOT NULL, 
			dcJobTypeIDMinor SMALLINT NULL, 
			dcSalaryID TINYINT NOT NULL, 
			dcRegionID VARCHAR(6) NULL, 
			dcEducationID TINYINT NOT NULL, 
			MinExperience TINYINT NOT NULL, 
			RefreshDate SMALLDATETIME NULL,
			EmployType TINYINT NULL,
			dcCompanySizeID SMALLINT NULL
		)

		CREATE TABLE #FullText(
			Priority INT,
			JobId INT NOT NULL
		)

		------刷新时间，根据刷新时间编号计算
		----生成插入临时表的Sql语句
		SET @SQL='
			INSERT INTO #Job
			SELECT a.ID, a.cpMainId, a.dcJobTypeID, 
				a.dcJobTypeIDMinor, a.dcSalaryID, 
				a.dcRegionID, a.dcEducationID, a.MinExperience, 
				a.IssueDate,a.EmployType,b.dcCompanySizeID'
		SET @FROM = '
			FROM JobPublish a WITH(NOLOCK)
			INNER JOIN cpMainPublish b WITH(NOLOCK) ON a.cpMainID=b.ID'
		----职位有效，单位新有效
		IF LEN(@dcIndustryID) > 0
			SET @WHERE = '
			WHERE b.ID IN (SELECT cpMainID FROM cpIndustry WHERE dcIndustryId in(' + @dcIndustryID + '))
			AND a.Valid = 1
			AND b.Valid = 1'
		ELSE
			SET @WHERE = '
			WHERE a.Valid = 1
			AND b.Valid = 1'
		
		IF LEN(@dcProvinceId) > 1
			SET @WHere = @Where + ' AND b.dcProvinceId = ' + @dcProvinceId

		----职位类别
		IF LEN(@JobType) > 0
			SET @WHERE = @WHERE + '
			AND (a.dcJobTypeID IN(' + @JobType +')
				OR a.dcJobTypeIDMinor IN(' +@JobType + '))'
		IF LEN(@JobPlace) > 0 
			SET @WHERE = @WHERE + '
			AND (' + @JobPlace + ')'

		IF @dcSalaryID > 0
		BEGIN
			IF @dcSalaryID < 100				----从form中搜索，月薪跨2个级别, 是本级和上级别的薪金
				SET @WHERE = @WHERE + '
			AND a.dcSalaryID IN(' + LTRIM(STR(@dcSalaryID)) + ',' + LTRIM(STR(@dcSalaryID + 1)) + ')'
			ELSE IF @dcSalaryID = 100	----从筛选结果中点击面议，值是100
				SET @WHERE = @WHERE + '
			AND a.dcSalaryID = 100'
			ELSE IF @dcSalaryID BETWEEN 101 AND 106	----从筛选结果中点击搜索，月薪只有1个级别，传值时增加100
				SET @WHERE = @WHERE + '
			AND a.dcSalaryID <= ' + LTRIM(STR(@dcSalaryID-99)) + ' AND a.dcSalaryIDMax > ' + LTRIM(STR(@dcSalaryID-100))
			ELSE IF @dcSalaryID BETWEEN 107 AND 113	----从筛选结果中点击搜索，月薪只有1个级别，传值时增加100
				SET @WHERE = @WHERE + '
			AND a.dcSalaryID <= ' + LTRIM(STR(@dcSalaryID - 100)) + ' AND a.dcSalaryIDMax > ' + LTRIM(STR(@dcSalaryID-100))
			ELSE IF @dcSalaryID BETWEEN 114 AND 120
				SET @WHERE = @WHERE + '
			AND a.dcSalaryID  < 100 AND a.dcSalaryIDMax > ' + LTRIM(STR(@dcSalaryID - 100))		
		END
		----工作经验要求
		IF @MinExperience < 100
		SET @WHERE = @WHERE + ' 
			AND a.MinExperience = ' + LTRIM(STR(@MinExperience))

		----学历要求
		----'1初中', '2\3\4高中、中技、中专', '5大专', '6本科', '7硕士', '8博士
		IF @dcEducationID > 0
			IF @dcEducationID = 2
				SET @WHERE = @WHERE + '
			AND a.dcEducationID IN(2, 3, 4)'
			ELSE
				SET @WHERE = @WHERE + '
			AND a.dcEducationID = ' + LTRIM(STR(@dcEducationID))
		----1、全职；3、兼职；4实习。	2、全职/兼职 职位中无此项
		IF LEN(@EmployType) > 0
			SET @WHERE = @WHERE + '
			AND a.EmployType IN (' + @EmployType + ')'

		IF @CompanySizeID BETWEEN 1 AND 6
			SET @WHERE = @WHERE + '
			AND b.dcCompanySizeID = ' + LTRIM(STR(@CompanySizeID))

		IF LEN(@Welfare) > 0
			SET @WHERE = @WHERE + '
			AND a.Welfare' + REPLACE(@Welfare, ',', ' = 1 AND a.Welfare') + ' = 1'

		IF @IsOnline = 1
			SET @WHERE = @WHERE + '
			AND a.caMainId IN(SELECT caMainId FROM caOnline WITH(NOLOCK) WHERE IsOnline = 1)'

		IF LEN(@KeyWord) > 0  ----使用全文搜索job和cpmain2个表，经过测试发现union最快
		BEGIN
			IF EXISTS(SELECT TOP 1 'x' FROM cpMainPublish WITH(NOLOCK) WHERE Name = @KeyWord)
			BEGIN
				SET @WHERE = @WHERE + '
			AND b.Name = ''' + @KeyWord + ''''
				SET @SQL = @SQL + @FROM + @WHERE
			END
			ELSE
			BEGIN
				DECLARE @KeyWordTemp NVARCHAR(50)
				SET @KeyWordTemp = REPLACE(@KeyWord, ' ', '%')
				IF LEN(@KeyWordTemp) > 1
				BEGIN
					IF @dcProvinceId > 0
					BEGIN
						INSERT #FullText
						SELECT TOP 2000 2, b.ID
						FROM cpMainPublish a WITH(NOLOCK),
							JobPublish b WITH(NOLOCK)
						WHERE a.Id = b.cpMainId
						AND a.Name LIKE '%' + @KeyWordTemp + '%'
						AND a.dcProvinceId = @dcprovinceId
						ORDER BY b.RefreshDate DESC

						INSERT #FullText
						SELECT TOP 2000 1, b.ID
						FROM cpMainPublish a WITH(NOLOCK),
							JobPublish b WITH(NOLOCK)
						WHERE a.Id = b.cpMainId
						AND b.Name LIKE '%' + @KeyWordTemp + '%'
						AND a.dcProvinceId = @dcprovinceId
						ORDER BY b.RefreshDate DESC
					END
					ELSE
					BEGIN
						INSERT #FullText
						SELECT TOP 2000 2, b.ID
						FROM cpMainPublish a WITH(NOLOCK),
							JobPublish b WITH(NOLOCK)
						WHERE a.Id = b.cpMainId
						AND a.Name LIKE '%' + @KeyWordTemp + '%'
						ORDER BY b.RefreshDate DESC

						INSERT #FullText
						SELECT TOP 2000 1, b.ID
						FROM cpMainPublish a WITH(NOLOCK),
							JobPublish b WITH(NOLOCK)
						WHERE a.Id = b.cpMainId
						AND b.Name LIKE '%' + @KeyWordTemp + '%'
						ORDER BY b.RefreshDate DESC
					END
				END
				IF (SELECT COUNT(*) FROM #FullText) < 800
				BEGIN
					INSERT #FullText
					SELECT TOP 5000 3, [Key]
					FROM FREETEXTTABLE(cpMainJob, *, @KeyWord, 100000) AS KeyJob ORDER BY RANK DESC
				END
				DELETE a FROM #FullText a, #FullText b WHERE a.JobId = b.JobId AND a.Priority > b.Priority
				--------------------
				SELECT @FROM = @FROM + '
			INNER JOIN #FullText ON a.ID = #FullText.JobId',
					@ORDER2 = ' ORDER BY #FullText.Priority, a.RefreshDate DESC, a.SecondID DESC'
				SET @SQL = @SQL + @FROM + @WHERE
			END
		END
		ELSE
			SELECT @SQL = @SQL + @FROM + @WHERE
		
		SET @SQL = @SQL + @Order2
		--原来是ORDER BY a.IssueDate DESC, a.ID，Richard 2011年11月23日17：06分修改

		----把符合条件的职位全部列出
		--PRINT @SQL
		EXEC(@SQL)
		SET @ValidJobNumber = @@ROWCOUNT
		----记录查询结果总数
		UPDATE SearchDB..paSearchCondition SET ValidJobNumber=@ValidJobNumber, SQl=@sql WHERE ID=@paSearchConditionID
		IF LEN(@JobType) > 0	--IN(2, 4)
			UPDATE #Job SET dcJobTypeId = dcJobTypeIDMinor
			WHERE dcJobTypeID NOT IN(SELECT a FROM dbo.fnSplit(@JobType, ','))

		----插入JobType数据
		DECLARE @TitleValue AS INT, @TopRows AS INT, @AllRows AS INT
		DECLARE @sc AS TABLE (
			paSearchConditionID int,
			Title varchar(20),
			TitleID varchar(10),
			TitleValue int
		)
		DECLARE @sc2 AS TABLE (
			paSearchConditionID int,
			Title varchar(20),
			TitleID varchar(10),
			TitleValue int
		)

		IF (@TableID = 0)
		BEGIN
			INSERT INTO @sc2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'JobType', dcJobTypeID, COUNT(*)
			FROM #Job WITH(NOLOCK)
			GROUP BY dcJobTypeID ORDER BY dcJobTypeID			

			----计算全部某职位类别，2, 4位的数据
			IF @JobTypeLen NOT IN(2, 4)
			BEGIN
				INSERT INTO @Sc(paSearchConditionID, Title, TitleId, TitleValue)
				SELECT  @paSearchConditionID, 'JobType', LEFT(TitleID, 2) TitleID, SUM(TitleValue) TitleValue 
				FROM @sc2 GROUP BY LEFT(TitleID, 2)
			END
			IF @JobTypeLen NOT IN(0, 4)
			BEGIN
				INSERT INTO @Sc(paSearchConditionID, Title, TitleId, TitleValue)
				SELECT  @paSearchConditionID, 'JobType', TitleId, TitleValue
				FROM @sc2 WHERE LEN(TitleId) = 4
			END

			IF @JobTypeLen = -1
				DELETE @sc WHERE TitleID NOT IN(SELECT a FROM dbo.fnSplit(@dcJobTypeID, ','))

			INSERT INTO SearchDB..paSearchCount_0(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT  @paSearchConditionID, 'JobType', TitleId, TitleValue FROM @sc
			DELETE @sc
			DELETE @sc2
			--------
			INSERT INTO @sc2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Region', dcRegionID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcRegionID ORDER BY dcRegionID
			----计算全部地区，2位的数据
			IF @JobPlaceLen IN(-1, 0)
				INSERT INTO @sc(paSearchConditionID, Title, TitleId, TitleValue)
				SELECT @paSearchConditionID, 'Region', LEFT(TitleID, 2) TitleID, SUM(TitleValue) TitleValue 
				FROM @sc2 GROUP BY LEFT(TitleID, 2)
			IF @JobPlaceLen IN(-1, 2)
				INSERT INTO @sc(paSearchConditionID, Title, TitleId, TitleValue)
				SELECT @paSearchConditionID, 'Region', LEFT(TitleID, 4) TitleID, SUM(TitleValue) TitleValue 
				FROM @sc2 WHERE LEN(TitleID) >= 4 GROUP BY LEFT(TitleID, 4)
			IF @JobPlaceLen IN(-1, 4)
				INSERT INTO @sc(paSearchConditionID, Title, TitleId, TitleValue)
				SELECT @paSearchConditionID, 'Region', TitleID, TitleValue 
				FROM @sc2 WHERE LEN(TitleID) = 6
			IF @JobPlaceLen = -1
				DELETE @sc WHERE TitleID NOT IN(SELECT ID FROM @T_JobPlace)
			ELSE
				DELETE @sc WHERE LEN(TitleID) <> @JobPlaceLen + 2

			INSERT INTO SearchDB..paSearchCount_0(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT paSearchConditionID, Title, TitleId, TitleValue FROM @sc
			----------------

			INSERT INTO SearchDB..paSearchCount_0(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'EmployType', EmployType, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY EmployType ORDER BY EmployType

			INSERT INTO SearchDB..paSearchCount_0(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Education', CASE WHEN dcEducationId IN(2, 3, 4) THEN 2 ELSE dcEducationId END, COUNT(*) 
			FROM #Job WITH(NOLOCK)
			GROUP BY CASE WHEN dcEducationId IN(2, 3, 4) THEN 2 ELSE dcEducationId END
			ORDER BY CASE WHEN dcEducationId IN(2, 3, 4) THEN 2 ELSE dcEducationId END

			INSERT INTO SearchDB..paSearchCount_0(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Experience', MinExperience, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY MinExperience ORDER BY MinExperience

			INSERT INTO SearchDB..paSearchCount_0(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'CompanySize', dcCompanySizeID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcCompanySizeID ORDER BY dcCompanySizeID

			INSERT INTO SearchDB..paSearchCount_0(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Salary', dcSalaryID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcSalaryID ORDER BY dcSalaryID

			INSERT INTO SearchDB..paSearchCount_0(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Industry', dcIndustryID, COUNT(*) 
			FROM #Job a WITH(NOLOCK), cpIndustry b WITH(NOLOCK)
			WHERE a.cpMainId = b.cpMainId
			GROUP BY b.dcIndustryId ORDER BY b.dcIndustryId

			IF EXISTS(SELECT TOP 1 'x' FROM #FullText)
				INSERT INTO SearchDB..paSearchJobID_0(paSearchConditionID, JobId, IsTop)
				SELECT TOP 10 @paSearchConditionID, a.JobId, 1 
				FROM SearchJobTop a WITH(NOLOCK), (SELECT ID FROM #Job WITH(NOLOCK) WHERE RowId < 2001) b 
				WHERE b.ID = a.JobId
				AND CHARINDEX(@KeyWord, a.JobName) > 0
				ORDER BY a.OrderType, a.OpenDate DESC
			ELSE
				INSERT INTO SearchDB..paSearchJobID_0(paSearchConditionID, JobId, IsTop)
				SELECT TOP 10 @paSearchConditionID, a.JobId, 1 
				FROM SearchJobTop a WITH(NOLOCK), (SELECT ID FROM #Job WITH(NOLOCK) WHERE RowId < 2001) b 
				WHERE b.ID = a.JobId
				ORDER BY a.OrderType, a.OpenDate DESC
			SET @TopRows = @@ROWCOUNT

			INSERT INTO SearchDB..paSearchJobID_0(paSearchConditionID, JobId, IsTop)
			SELECT TOP 2000 @paSearchConditionID, ID, 0 FROM #Job WITH(NOLOCK) ORDER BY RowID
			SET @AllRows = @@ROWCOUNT

			IF @TopRows = 0 AND @AllRows > 100
				UPDATE SearchDB..paSearchJobID_0 SET IsTop = 1 
				WHERE paSearchConditionID = @paSearchConditionID
				AND ID IN (SELECT TOP 3 ID FROM SearchDB..paSearchJobID_0 WITH(NOLOCK) WHERE paSearchConditionID = @paSearchConditionID ORDER BY ID)
		END
		ELSE IF (@TableId = 1)
		BEGIN
			----------------------------jobtype
			INSERT INTO @sc2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'JobType', dcJobTypeID, COUNT(*)
			FROM #Job WITH(NOLOCK)
			GROUP BY dcJobTypeID ORDER BY dcJobTypeID			

			----计算全部某职位类别，2, 4位的数据
			IF @JobTypeLen NOT IN(2, 4)
			BEGIN
				INSERT INTO @Sc(paSearchConditionID, Title, TitleId, TitleValue)
				SELECT  @paSearchConditionID, 'JobType', LEFT(TitleID, 2) TitleID, SUM(TitleValue) TitleValue 
				FROM @sc2 GROUP BY LEFT(TitleID, 2)
			END
			IF @JobTypeLen NOT IN(0, 4)
			BEGIN
				INSERT INTO @Sc(paSearchConditionID, Title, TitleId, TitleValue)
				SELECT  @paSearchConditionID, 'JobType', TitleId, TitleValue
				FROM @sc2 WHERE LEN(TitleId) = 4
			END

			IF @JobTypeLen = -1
				DELETE @sc WHERE TitleID NOT IN(SELECT a FROM dbo.fnSplit(@dcJobTypeID, ','))

			INSERT INTO SearchDB..paSearchCount_1(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT  @paSearchConditionID, 'JobType', TitleId, TitleValue FROM @sc
			DELETE @sc
			DELETE @sc2
			--------------------------region
			INSERT INTO @sc2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Region', dcRegionID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcRegionID ORDER BY dcRegionID
			----计算全部地区，2位的数据
			IF @JobPlaceLen IN(-1, 0)
				INSERT INTO @sc(paSearchConditionID, Title, TitleId, TitleValue)
				SELECT @paSearchConditionID, 'Region', LEFT(TitleID, 2) TitleID, SUM(TitleValue) TitleValue 
				FROM @sc2 GROUP BY LEFT(TitleID, 2)
			IF @JobPlaceLen IN(-1, 2)
				INSERT INTO @sc(paSearchConditionID, Title, TitleId, TitleValue)
				SELECT @paSearchConditionID, 'Region', LEFT(TitleID, 4) TitleID, SUM(TitleValue) TitleValue 
				FROM @sc2 WHERE LEN(TitleID) >= 4 GROUP BY LEFT(TitleID, 4)
			IF @JobPlaceLen IN(-1, 4)
				INSERT INTO @sc(paSearchConditionID, Title, TitleId, TitleValue)
				SELECT @paSearchConditionID, 'Region', TitleID, TitleValue 
				FROM @sc2 WHERE LEN(TitleID) = 6
			IF @JobPlaceLen = -1
				DELETE @sc WHERE TitleID NOT IN(SELECT ID FROM @T_JobPlace)
			ELSE
				DELETE @sc WHERE LEN(TitleID) <> @JobPlaceLen + 2

			INSERT INTO SearchDB..paSearchCount_1(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT paSearchConditionID, Title, TitleId, TitleValue FROM @sc
			----------------------------
			INSERT INTO SearchDB..paSearchCount_1(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Education', CASE WHEN dcEducationId IN(2, 3, 4) THEN 2 ELSE dcEducationId END, COUNT(*)
			FROM #Job WITH(NOLOCK)
			GROUP BY CASE WHEN dcEducationId IN(2, 3, 4) THEN 2 ELSE dcEducationId END
			ORDER BY CASE WHEN dcEducationId IN(2, 3, 4) THEN 2 ELSE dcEducationId END
			
			INSERT INTO SearchDB..paSearchCount_1(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Experience', MinExperience, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY MinExperience ORDER BY MinExperience
	
			INSERT INTO SearchDB..paSearchCount_1(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'EmployType', EmployType, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY EmployType ORDER BY EmployType

			INSERT INTO SearchDB..paSearchCount_1(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'CompanySize', dcCompanySizeID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcCompanySizeID ORDER BY dcCompanySizeID

			INSERT INTO SearchDB..paSearchCount_1(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Salary', dcSalaryID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcSalaryID ORDER BY dcSalaryID

			INSERT INTO SearchDB..paSearchCount_1(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Industry', dcIndustryID, COUNT(*) 
			FROM #Job a WITH(NOLOCK), cpIndustry b WITH(NOLOCK)
			WHERE a.cpMainId = b.cpMainId
			GROUP BY dcIndustryID ORDER BY dcIndustryID
			
			IF EXISTS(SELECT TOP 1 'x' FROM #FullText)
				INSERT INTO SearchDB..paSearchJobID_1(paSearchConditionID, JobId, IsTop)
				SELECT TOP 10 @paSearchConditionID, a.JobId, 1 
				FROM SearchJobTop a WITH(NOLOCK), (SELECT ID FROM #Job WITH(NOLOCK) WHERE RowId < 2001) b 
				WHERE b.ID = a.JobId
				AND CHARINDEX(@KeyWord, a.JobName) > 0
				ORDER BY a.OrderType, a.OpenDate DESC
			ELSE
				INSERT INTO SearchDB..paSearchJobID_1(paSearchConditionID, JobId, IsTop)
				SELECT TOP 10 @paSearchConditionID, a.JobId, 1 
				FROM SearchJobTop a WITH(NOLOCK), (SELECT ID FROM #Job WITH(NOLOCK) WHERE RowId < 2001) b 
				WHERE b.ID = a.JobId
				ORDER BY a.OrderType, a.OpenDate DESC
			SET @TopRows = @@ROWCOUNT

			INSERT INTO SearchDB..paSearchJobID_1(paSearchConditionID, JobId, IsTop)
			SELECT TOP 2000 @paSearchConditionID, ID, 0 FROM #Job WITH(NOLOCK) ORDER BY RowID
			SET @AllRows = @@ROWCOUNT

			IF @TopRows = 0 AND @AllRows > 100
				UPDATE SearchDB..paSearchJobID_1 SET IsTop = 1 
				WHERE paSearchConditionID = @paSearchConditionID
				AND ID IN (SELECT TOP 3 ID FROM SearchDB..paSearchJobID_1 WITH(NOLOCK) WHERE paSearchConditionID = @paSearchConditionID ORDER BY ID)
		END
		ELSE IF (@TableId = 2)
		BEGIN
			----------------------------jobtype
			INSERT INTO @sc2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'JobType', dcJobTypeID, COUNT(*)
			FROM #Job WITH(NOLOCK)
			GROUP BY dcJobTypeID ORDER BY dcJobTypeID			

			----计算全部某职位类别，2, 4位的数据
			IF @JobTypeLen NOT IN(2, 4)
			BEGIN
				INSERT INTO @Sc(paSearchConditionID, Title, TitleId, TitleValue)
				SELECT  @paSearchConditionID, 'JobType', LEFT(TitleID, 2) TitleID, SUM(TitleValue) TitleValue 
				FROM @sc2 GROUP BY LEFT(TitleID, 2)
			END
			IF @JobTypeLen NOT IN(0, 4)
			BEGIN
				INSERT INTO @Sc(paSearchConditionID, Title, TitleId, TitleValue)
				SELECT  @paSearchConditionID, 'JobType', TitleId, TitleValue
				FROM @sc2 WHERE LEN(TitleId) = 4
			END

			IF @JobTypeLen = -1
				DELETE @sc WHERE TitleID NOT IN(SELECT a FROM dbo.fnSplit(@dcJobTypeID, ','))

			INSERT INTO SearchDB..paSearchCount_2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT  @paSearchConditionID, 'JobType', TitleId, TitleValue FROM @sc
			DELETE @sc
			DELETE @sc2
			--------------------------region
			INSERT INTO @sc2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Region', dcRegionID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcRegionID ORDER BY dcRegionID
			----计算全部地区，2位的数据
			IF @JobPlaceLen IN(-1, 0)
				INSERT INTO @sc(paSearchConditionID, Title, TitleId, TitleValue)
				SELECT @paSearchConditionID, 'Region', LEFT(TitleID, 2) TitleID, SUM(TitleValue) TitleValue 
				FROM @sc2 GROUP BY LEFT(TitleID, 2)
			IF @JobPlaceLen IN(-1, 2)
				INSERT INTO @sc(paSearchConditionID, Title, TitleId, TitleValue)
				SELECT @paSearchConditionID, 'Region', LEFT(TitleID, 4) TitleID, SUM(TitleValue) TitleValue 
				FROM @sc2 WHERE LEN(TitleID) >= 4 GROUP BY LEFT(TitleID, 4)
			IF @JobPlaceLen IN(-1, 4)
				INSERT INTO @sc(paSearchConditionID, Title, TitleId, TitleValue)
				SELECT @paSearchConditionID, 'Region', TitleID, TitleValue 
				FROM @sc2 WHERE LEN(TitleID) = 6
			IF @JobPlaceLen = -1
				DELETE @sc WHERE TitleID NOT IN(SELECT ID FROM @T_JobPlace)
			ELSE
				DELETE @sc WHERE LEN(TitleID) <> @JobPlaceLen + 2

			INSERT INTO SearchDB..paSearchCount_2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT paSearchConditionID, Title, TitleId, TitleValue FROM @sc
			----------------------------
			INSERT INTO SearchDB..paSearchCount_2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Education', CASE WHEN dcEducationId IN(2, 3, 4) THEN 2 ELSE dcEducationId END, COUNT(*) 
			FROM #Job WITH(NOLOCK)
			GROUP BY CASE WHEN dcEducationId IN(2, 3, 4) THEN 2 ELSE dcEducationId END
			ORDER BY CASE WHEN dcEducationId IN(2, 3, 4) THEN 2 ELSE dcEducationId END
			
			INSERT INTO SearchDB..paSearchCount_2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Experience', MinExperience, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY MinExperience ORDER BY MinExperience

			INSERT INTO SearchDB..paSearchCount_2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Salary', dcSalaryID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcSalaryID ORDER BY dcSalaryID

			INSERT INTO SearchDB..paSearchCount_2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'EmployType', EmployType, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY EmployType ORDER BY EmployType

			INSERT INTO SearchDB..paSearchCount_2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'CompanySize', dcCompanySizeID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcCompanySizeID ORDER BY dcCompanySizeID

			INSERT INTO SearchDB..paSearchCount_2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Industry', dcIndustryID, COUNT(*) 
			FROM #Job a WITH(NOLOCK), cpIndustry b WITH(NOLOCK)
			WHERE a.cpMainId = b.cpMainId
			GROUP BY dcIndustryID ORDER BY dcIndustryID

			
			IF EXISTS(SELECT TOP 1 'x' FROM #FullText)
				INSERT INTO SearchDB..paSearchJobID_2(paSearchConditionID, JobId, IsTop)
				SELECT TOP 10 @paSearchConditionID, a.JobId, 1 
				FROM SearchJobTop a WITH(NOLOCK), (SELECT ID FROM #Job WITH(NOLOCK) WHERE RowId < 2001) b 
				WHERE b.ID = a.JobId
				AND CHARINDEX(@KeyWord, a.JobName) > 0
				ORDER BY a.OrderType, a.OpenDate DESC
			ELSE
				INSERT INTO SearchDB..paSearchJobID_2(paSearchConditionID, JobId, IsTop)
				SELECT TOP 10 @paSearchConditionID, a.JobId, 1 
				FROM SearchJobTop a WITH(NOLOCK), (SELECT ID FROM #Job WITH(NOLOCK) WHERE RowId < 2001) b 
				WHERE b.ID = a.JobId
				ORDER BY a.OrderType, a.OpenDate DESC
			SET @TopRows = @@ROWCOUNT

			INSERT INTO SearchDB..paSearchJobID_2(paSearchConditionID, JobId, IsTop)
			SELECT TOP 2000 @paSearchConditionID, ID, 0 FROM #Job WITH(NOLOCK) ORDER BY RowID
			SET @AllRows = @@ROWCOUNT

			IF @TopRows = 0 AND @AllRows > 100
				UPDATE SearchDB..paSearchJobID_2 SET IsTop = 1 
				WHERE paSearchConditionID = @paSearchConditionID
				AND ID IN (SELECT TOP 3 ID FROM SearchDB..paSearchJobID_2 WITH(NOLOCK) WHERE paSearchConditionID = @paSearchConditionID ORDER BY ID)
		END
		ELSE IF (@TableId = 3)
		BEGIN
			----------------------------jobtype
			INSERT INTO @sc2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'JobType', dcJobTypeID, COUNT(*)
			FROM #Job WITH(NOLOCK)
			GROUP BY dcJobTypeID ORDER BY dcJobTypeID			

			----计算全部某职位类别，2, 4位的数据
			IF @JobTypeLen NOT IN(2, 4)
			BEGIN
				INSERT INTO @Sc(paSearchConditionID, Title, TitleId, TitleValue)
				SELECT  @paSearchConditionID, 'JobType', LEFT(TitleID, 2) TitleID, SUM(TitleValue) TitleValue 
				FROM @sc2 GROUP BY LEFT(TitleID, 2)
			END
			IF @JobTypeLen NOT IN(0, 4)
			BEGIN
				INSERT INTO @Sc(paSearchConditionID, Title, TitleId, TitleValue)
				SELECT  @paSearchConditionID, 'JobType', TitleId, TitleValue
				FROM @sc2 WHERE LEN(TitleId) = 4
			END

			IF @JobTypeLen = -1
				DELETE @sc WHERE TitleID NOT IN(SELECT a FROM dbo.fnSplit(@dcJobTypeID, ','))

			INSERT INTO SearchDB..paSearchCount_3(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT  @paSearchConditionID, 'JobType', TitleId, TitleValue FROM @sc
			DELETE @sc
			DELETE @sc2
			--------------------------region
			INSERT INTO @sc2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Region', dcRegionID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcRegionID ORDER BY dcRegionID
			----计算全部地区，2位的数据
			IF @JobPlaceLen IN(-1, 0)
				INSERT INTO @sc(paSearchConditionID, Title, TitleId, TitleValue)
				SELECT @paSearchConditionID, 'Region', LEFT(TitleID, 2) TitleID, SUM(TitleValue) TitleValue 
				FROM @sc2 GROUP BY LEFT(TitleID, 2)
			IF @JobPlaceLen IN(-1, 2)
				INSERT INTO @sc(paSearchConditionID, Title, TitleId, TitleValue)
				SELECT @paSearchConditionID, 'Region', LEFT(TitleID, 4) TitleID, SUM(TitleValue) TitleValue 
				FROM @sc2 WHERE LEN(TitleID) >= 4 GROUP BY LEFT(TitleID, 4)
			IF @JobPlaceLen IN(-1, 4)
				INSERT INTO @sc(paSearchConditionID, Title, TitleId, TitleValue)
				SELECT @paSearchConditionID, 'Region', TitleID, TitleValue 
				FROM @sc2 WHERE LEN(TitleID) = 6
			IF @JobPlaceLen = -1
				DELETE @sc WHERE TitleID NOT IN(SELECT ID FROM @T_JobPlace)
			ELSE
				DELETE @sc WHERE LEN(TitleID) <> @JobPlaceLen + 2

			INSERT INTO SearchDB..paSearchCount_3(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT paSearchConditionID, Title, TitleId, TitleValue FROM @sc
			----------------------------
			INSERT INTO SearchDB..paSearchCount_3(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Education', CASE WHEN dcEducationId IN(2, 3, 4) THEN 2 ELSE dcEducationId END, COUNT(*) 
			FROM #Job WITH(NOLOCK)
			GROUP BY CASE WHEN dcEducationId IN(2, 3, 4) THEN 2 ELSE dcEducationId END
			ORDER BY CASE WHEN dcEducationId IN(2, 3, 4) THEN 2 ELSE dcEducationId END
			
			INSERT INTO SearchDB..paSearchCount_3(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Experience', MinExperience, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY MinExperience ORDER BY MinExperience

			INSERT INTO SearchDB..paSearchCount_3(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Salary', dcSalaryID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcSalaryID ORDER BY dcSalaryID

			INSERT INTO SearchDB..paSearchCount_3(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'EmployType', EmployType, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY EmployType ORDER BY EmployType

			INSERT INTO SearchDB..paSearchCount_3(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'CompanySize', dcCompanySizeID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcCompanySizeID ORDER BY dcCompanySizeID

			INSERT INTO SearchDB..paSearchCount_3(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Industry', dcIndustryID, COUNT(*) 
			FROM #Job a WITH(NOLOCK), cpIndustry b WITH(NOLOCK)
			WHERE a.cpMainId = b.cpMainId
			GROUP BY dcIndustryID ORDER BY dcIndustryID

			
			IF EXISTS(SELECT TOP 1 'x' FROM #FullText)
				INSERT INTO SearchDB..paSearchJobID_3(paSearchConditionID, JobId, IsTop)
				SELECT TOP 10 @paSearchConditionID, a.JobId, 1 
				FROM SearchJobTop a WITH(NOLOCK), (SELECT ID FROM #Job WITH(NOLOCK) WHERE RowId < 2001) b 
				WHERE b.ID = a.JobId
				AND CHARINDEX(@KeyWord, a.JobName) > 0
				ORDER BY a.OrderType, a.OpenDate DESC
			ELSE
				INSERT INTO SearchDB..paSearchJobID_3(paSearchConditionID, JobId, IsTop)
				SELECT TOP 10 @paSearchConditionID, a.JobId, 1 
				FROM SearchJobTop a WITH(NOLOCK), (SELECT ID FROM #Job WITH(NOLOCK) WHERE RowId < 2001) b 
				WHERE b.ID = a.JobId
				ORDER BY a.OrderType, a.OpenDate DESC
			SET @TopRows = @@ROWCOUNT

			INSERT INTO SearchDB..paSearchJobID_3(paSearchConditionID, JobId, IsTop)
			SELECT TOP 2000 @paSearchConditionID, ID, 0 FROM #Job WITH(NOLOCK) ORDER BY RowID
			SET @AllRows = @@ROWCOUNT

			IF @TopRows = 0 AND @AllRows > 100
				UPDATE SearchDB..paSearchJobID_3 SET IsTop = 1 
				WHERE paSearchConditionID = @paSearchConditionID
				AND ID IN (SELECT TOP 3 ID FROM SearchDB..paSearchJobID_3 WITH(NOLOCK) WHERE paSearchConditionID = @paSearchConditionID ORDER BY ID)
		END
		DROP TABLE #Job
		--PRINT 'DROP #JOB  ' + CONVERT(VARCHAR(30), GETDATE(), 121)
	COMMIT
	--GOTO GetRecordSet

	GetRecordSet:
	BEGIN
		DECLARE @AllJobCount AS INT
		----返回查询数量
		SELECT ValidJobNumber FROM SearchDB..paSearchCondition WITH(NOLOCK) WHERE ID=@paSearchConditionID
		SELECT @AllJobCount = ValidJobNumber FROM SearchDB..paSearchCondition WITH(NOLOCK) WHERE ID=@paSearchConditionID
		UPDATE SearchDB..paSearchCondition SET ReuseNumber = ReuseNumber + 1 WHERE ID=@paSearchConditionID
		----返回20行查询结果
		IF (@TableID = 0)
		BEGIN
			SELECT @MinId = MIN(ID) FROM SearchDB..paSearchJobID_0 WITH(NOLOCK) WHERE paSearchConditionID=@paSearchConditionID

			SET @MinId = @MinId+(@PageNumber-1)*@PageSize
			SELECT TOP 30 a.ID, a.cpMainID, a.caMainID, a.Name as JobName, a.MinExperience ,
				a.dcJobTypeIDMinor, a.NeedNumber, a.dcSalaryID, a.dcSalaryIDMax, a.EmployType, 
				a.dcRegionID,  a.dcEducationID, a.RefreshDate,a.SecondId EnJobID,
				b.SecondId EnCpMainID, b.Name as cpName, b.HasLicence, c.IsTop, 
				ISNULL(d.IsOnline, 0) IsOnline, d.ViPlanId, d.InterviewDate, 
				e.FullName Region, b.LogoFile LogoUrl,@AllJobCount JobNumber,
				f.Description EducationName,g.Description ExperienceName,
				h.DescriptionCp dcSalary,i.DescriptionCp dcSalaryMax
			FROM JobPublish a WITH(NOLOCK)
			INNER JOIN cpMainPublish b WITH(NOLOCK) ON a.cpMainID = b.ID 
			INNER JOIN SearchDB..paSearchJobID_0 c WITH(NOLOCK) ON a.id = c.JobID
			INNER JOIN dcRegion e WITH(NOLOCK) ON a.dcRegionId = e.Id
			LEFT JOIN caOnline d WITH(NOLOCK) ON a.caMainId = d.caMainId
			INNER JOIN dcEducation f WITH(NOLOCK) ON f.ID = a.dcEducationID
			INNER JOIN dcOthers g WITH(NOLOCK) ON g.DetailID = a.MinExperience AND g.Category='职位要求工作经验' 
			INNER JOIN dcSalary h WITH(NOLOCK) ON h.ID = a.dcSalaryID
			INNER JOIN dcSalary i WITH(NOLOCK) ON i.ID = a.dcSalaryIDMax
			WHERE paSearchConditionID=@paSearchConditionID 
			AND c.ID >= @MinId
			ORDER BY c.ID, a.ID DESC
		END
		ELSE IF (@TableID = 1)
		BEGIN
			SELECT @MinId = MIN(ID) FROM SearchDB..paSearchJobID_1 WITH(NOLOCK) WHERE paSearchConditionID=@paSearchConditionID

			SET @MinId = @MinId+(@PageNumber-1)*@PageSize
			SELECT TOP 30 a.ID, a.cpMainID, a.caMainID, a.Name as JobName, a.MinExperience ,
				a.dcJobTypeIDMinor, a.NeedNumber, a.dcSalaryID, a.dcSalaryIDMax, a.EmployType, 
				a.dcRegionID,  a.dcEducationID, a.RefreshDate,a.SecondId EnJobID,
				b.SecondId EnCpMainID, b.Name as cpName, b.HasLicence, c.IsTop, 
				ISNULL(d.IsOnline, 0) IsOnline, d.ViPlanId, d.InterviewDate, 
				e.FullName Region, b.LogoFile LogoUrl,@AllJobCount JobNumber,
				f.Description EducationName,g.Description ExperienceName,
				h.DescriptionCp dcSalary,i.DescriptionCp dcSalaryMax
			FROM JobPublish a WITH(NOLOCK)
			INNER JOIN cpMainPublish b WITH(NOLOCK) ON a.cpMainID = b.ID 
			INNER JOIN SearchDB..paSearchJobID_1 c WITH(NOLOCK) ON a.id = c.JobID
			INNER JOIN dcRegion e WITH(NOLOCK) ON a.dcRegionId = e.Id
			LEFT JOIN caOnline d WITH(NOLOCK) ON a.caMainId = d.caMainId
			INNER JOIN dcEducation f WITH(NOLOCK) ON f.ID = a.dcEducationID
			INNER JOIN dcOthers g WITH(NOLOCK) ON g.DetailID = a.MinExperience AND g.Category='职位要求工作经验' 
			INNER JOIN dcSalary h WITH(NOLOCK) ON h.ID = a.dcSalaryID
			INNER JOIN dcSalary i WITH(NOLOCK) ON i.ID = a.dcSalaryIDMax
			WHERE paSearchConditionID=@paSearchConditionID 
			AND c.ID >= @MinId
			ORDER BY c.ID, a.ID DESC
		END
		ELSE IF (@TableID = 2)
		BEGIN
			SELECT @MinId = MIN(ID) FROM SearchDB..paSearchJobID_2 WITH(NOLOCK) WHERE paSearchConditionID=@paSearchConditionID

			SET @MinId = @MinId+(@PageNumber-1)*@PageSize
			SELECT TOP 30 a.ID, a.cpMainID, a.caMainID, a.Name as JobName, a.MinExperience ,
				a.dcJobTypeIDMinor, a.NeedNumber, a.dcSalaryID, a.dcSalaryIDMax, a.EmployType, 
				a.dcRegionID,  a.dcEducationID, a.RefreshDate,a.SecondId EnJobID,
				b.SecondId EnCpMainID, b.Name as cpName, b.HasLicence, c.IsTop, 
				ISNULL(d.IsOnline, 0) IsOnline, d.ViPlanId, d.InterviewDate, 
				e.FullName Region, b.LogoFile LogoUrl,@AllJobCount JobNumber,
				f.Description EducationName,g.Description ExperienceName,
				h.DescriptionCp dcSalary,i.DescriptionCp dcSalaryMax
			FROM JobPublish a WITH(NOLOCK)
			INNER JOIN cpMainPublish b WITH(NOLOCK) ON a.cpMainID = b.ID 
			INNER JOIN SearchDB..paSearchJobID_2 c WITH(NOLOCK) ON a.id = c.JobID
			INNER JOIN dcRegion e WITH(NOLOCK) ON a.dcRegionId = e.Id
			LEFT JOIN caOnline d WITH(NOLOCK) ON a.caMainId = d.caMainId
			INNER JOIN dcEducation f WITH(NOLOCK) ON f.ID = a.dcEducationID
			INNER JOIN dcOthers g WITH(NOLOCK) ON g.DetailID = a.MinExperience AND g.Category='职位要求工作经验' 
			INNER JOIN dcSalary h WITH(NOLOCK) ON h.ID = a.dcSalaryID
			INNER JOIN dcSalary i WITH(NOLOCK) ON i.ID = a.dcSalaryIDMax
			WHERE paSearchConditionID=@paSearchConditionID 
			AND c.ID >= @MinId
			ORDER BY c.ID, a.ID DESC
		END
		ELSE IF (@TableID = 3)
		BEGIN
			SELECT @MinId = MIN(ID) FROM SearchDB..paSearchJobID_3 WITH(NOLOCK) WHERE paSearchConditionID=@paSearchConditionID

			SET @MinId = @MinId+(@PageNumber-1)*@PageSize
			SELECT TOP 30 a.ID, a.cpMainID, a.caMainID, a.Name as JobName, a.MinExperience ,
				a.dcJobTypeIDMinor, a.NeedNumber, a.dcSalaryID, a.dcSalaryIDMax, a.EmployType, 
				a.dcRegionID,  a.dcEducationID, a.RefreshDate,a.SecondId EnJobID,
				b.SecondId EnCpMainID, b.Name as cpName, b.HasLicence, c.IsTop, 
				ISNULL(d.IsOnline, 0) IsOnline, d.ViPlanId, d.InterviewDate, 
				e.FullName Region, b.LogoFile LogoUrl,@AllJobCount JobNumber,
				f.Description EducationName,g.Description ExperienceName,
				h.DescriptionCp dcSalary,i.DescriptionCp dcSalaryMax
			FROM JobPublish a WITH(NOLOCK)
			INNER JOIN cpMainPublish b WITH(NOLOCK) ON a.cpMainID = b.ID 
			INNER JOIN SearchDB..paSearchJobID_3 c WITH(NOLOCK) ON a.id = c.JobID
			INNER JOIN dcRegion e WITH(NOLOCK) ON a.dcRegionId = e.Id
			LEFT JOIN caOnline d WITH(NOLOCK) ON a.caMainId = d.caMainId
			INNER JOIN dcEducation f WITH(NOLOCK) ON f.ID = a.dcEducationID
			INNER JOIN dcOthers g WITH(NOLOCK) ON g.DetailID = a.MinExperience AND g.Category='职位要求工作经验' 
			INNER JOIN dcSalary h WITH(NOLOCK) ON h.ID = a.dcSalaryID
			INNER JOIN dcSalary i WITH(NOLOCK) ON i.ID = a.dcSalaryIDMax
			WHERE paSearchConditionID=@paSearchConditionID 
			AND c.ID >= @MinId
			ORDER BY c.ID, a.ID DESC
		END
        --RICHARD 2011-7-23 16:51分修改
		----返回统计数量
		IF @Type=1
		BEGIN
			DECLARE @RegionCount AS INT
			SELECT @RegionCount = -1
			IF CHARINDEX(',', @dcRegionID) = 0 AND LEN(@dcRegionID) > 0
			BEGIN
				IF NOT LEFT(@dcRegionID,1) = 'p'
					SELECT @RegionCount = COUNT(*) FROM dcRegion WHERE ParentID = @dcRegionID
			END
			IF (@TableID = 0)
			BEGIN
				SELECT a.*,b.Description FROM SearchDB..paSearchCount_0 a WITH(NOLOCK) LEFT JOIN dcJobType b ON b.ID = a.TitleID WHERE Title = 'JobType' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(VARCHAR(10), TitleID)
				IF @RegionCount = 0
					SELECT * FROM dcMapPlace WITH(NOLOCK) WHERE dcRegionID = @dcRegionID
				ELSE
					SELECT a.*,b.Description FROM SearchDB..paSearchCount_0 a WITH(NOLOCK) LEFT JOIN dcRegion b ON b.ID = a.TitleID WHERE Title = 'Region' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(VARCHAR(10), TitleID)
				
				SELECT a.*,b.Description FROM SearchDB..paSearchCount_0 a WITH(NOLOCK) LEFT JOIN dcEducation b ON b.ID = a.TitleID WHERE Title = 'Education' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT a.*,b.Description FROM SearchDB..paSearchCount_0 a WITH(NOLOCK) LEFT JOIN dcOthers b ON b.DetailID = a.TitleID AND Category='职位要求工作经验' WHERE Title = 'Experience' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT * FROM SearchDB..paSearchCount_0 WITH(NOLOCK) WHERE Title = 'Salary' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT a.*,b.Description FROM SearchDB..paSearchCount_0 a WITH(NOLOCK) LEFT JOIN dcOthers b ON b.DetailID = a.TitleID AND Category='工作性质' WHERE Title = 'EmployType' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT a.*,b.Description FROM SearchDB..paSearchCount_0 a WITH(NOLOCK) LEFT JOIN dcCompanySize b ON b.ID = a.TitleID WHERE Title = 'CompanySize' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
			END
			IF (@TableID = 1)
			BEGIN
				SELECT a.*,b.Description FROM SearchDB..paSearchCount_1 a WITH(NOLOCK) LEFT JOIN dcJobType b ON b.ID = a.TitleID WHERE Title = 'JobType' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(VARCHAR(10), TitleID)
				IF @RegionCount = 0
					SELECT * FROM dcMapPlace WITH(NOLOCK) WHERE dcRegionID = @dcRegionID
				ELSE
					SELECT a.*,b.Description FROM SearchDB..paSearchCount_1 a WITH(NOLOCK) LEFT JOIN dcRegion b ON b.ID = a.TitleID WHERE Title = 'Region' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(VARCHAR(10), TitleID)
				
				SELECT a.*,b.Description FROM SearchDB..paSearchCount_1 a WITH(NOLOCK) LEFT JOIN dcEducation b ON b.ID = a.TitleID WHERE Title = 'Education' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT a.*,b.Description FROM SearchDB..paSearchCount_1 a WITH(NOLOCK) LEFT JOIN dcOthers b ON b.DetailID = a.TitleID AND Category='职位要求工作经验' WHERE Title = 'Experience' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT * FROM SearchDB..paSearchCount_1 a WITH(NOLOCK) WHERE Title = 'Salary' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT a.*,b.Description FROM SearchDB..paSearchCount_1 a WITH(NOLOCK) LEFT JOIN dcOthers b ON b.DetailID = a.TitleID AND Category='工作性质' WHERE Title = 'EmployType' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT a.*,b.Description FROM SearchDB..paSearchCount_1 a WITH(NOLOCK) LEFT JOIN dcCompanySize b ON b.ID = a.TitleID WHERE Title = 'CompanySize' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
			END
			IF (@TableID = 2)
			BEGIN
				SELECT a.*,b.Description FROM SearchDB..paSearchCount_2 a WITH(NOLOCK) LEFT JOIN dcJobType b ON b.ID = a.TitleID WHERE Title = 'JobType' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(VARCHAR(10), TitleID)
				IF @RegionCount = 0
					SELECT * FROM dcMapPlace WITH(NOLOCK) WHERE dcRegionID = @dcRegionID
				ELSE
					SELECT a.*,b.Description FROM SearchDB..paSearchCount_2 a WITH(NOLOCK) LEFT JOIN dcRegion b ON b.ID = a.TitleID WHERE Title = 'Region' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(VARCHAR(10), TitleID)
				
				SELECT a.*,b.Description FROM SearchDB..paSearchCount_2 a WITH(NOLOCK) LEFT JOIN dcEducation b ON b.ID = a.TitleID WHERE Title = 'Education' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT a.*,b.Description FROM SearchDB..paSearchCount_2 a WITH(NOLOCK) LEFT JOIN dcOthers b ON b.DetailID = a.TitleID AND Category='职位要求工作经验' WHERE Title = 'Experience' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT * FROM SearchDB..paSearchCount_2 a WITH(NOLOCK) WHERE Title = 'Salary' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT a.*,b.Description FROM SearchDB..paSearchCount_2 a WITH(NOLOCK) LEFT JOIN dcOthers b ON b.DetailID = a.TitleID AND Category='工作性质' WHERE Title = 'EmployType' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT a.*,b.Description FROM SearchDB..paSearchCount_2 a WITH(NOLOCK) LEFT JOIN dcCompanySize b ON b.ID = a.TitleID WHERE Title = 'CompanySize' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
			END
			IF (@TableID = 3)
			BEGIN
				SELECT a.*,b.Description FROM SearchDB..paSearchCount_3 a WITH(NOLOCK) LEFT JOIN dcJobType b ON b.ID = a.TitleID WHERE Title = 'JobType' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(VARCHAR(10), TitleID)
				IF @RegionCount = 0
					SELECT * FROM dcMapPlace WITH(NOLOCK) WHERE dcRegionID = @dcRegionID
				ELSE
					SELECT a.*,b.Description FROM SearchDB..paSearchCount_3 a WITH(NOLOCK) LEFT JOIN dcRegion b ON b.ID = a.TitleID WHERE Title = 'Region' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(VARCHAR(10), TitleID)
				
				SELECT a.*,b.Description FROM SearchDB..paSearchCount_3 a WITH(NOLOCK) LEFT JOIN dcEducation b ON b.ID = a.TitleID WHERE Title = 'Education' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT a.*,b.Description FROM SearchDB..paSearchCount_3 a WITH(NOLOCK) LEFT JOIN dcOthers b ON b.DetailID = a.TitleID AND Category='职位要求工作经验' WHERE Title = 'Experience' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT * FROM SearchDB..paSearchCount_3 a WITH(NOLOCK) WHERE Title = 'Salary' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT a.*,b.Description FROM SearchDB..paSearchCount_3 a WITH(NOLOCK) LEFT JOIN dcOthers b ON b.DetailID = a.TitleID AND Category='工作性质' WHERE Title = 'EmployType' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT a.*,b.Description FROM SearchDB..paSearchCount_3 a WITH(NOLOCK) LEFT JOIN dcCompanySize b ON b.ID = a.TitleID WHERE Title = 'CompanySize' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
			END
		END

		RETURN
	END
END TRY
BEGIN CATCH
	---检查是否已经建立临时表，已经建立则删除
	ROLLBACK TRANSACTION
	---检查是否已经建立临时表，已经建立则删除
	DECLARE @para VARCHAR(MAX)
	SET @para = '@dcJobTypeID=' + ISNULL(@dcJobTypeID, '') + '|' +
		'@dcRegionID=' + ISNULL(@dcRegionID, '') + '|' +
		'@dcIndustryID=' + ISNULL(@dcIndustryID, '') + '|' +
		'@EmployType=' + ISNULL(@EmployType, '') + '|' +
		'@KeyWord=' + ISNULL(@KeyWord, '') + '|' +
		'@ORDER=' + ISNULL(@ORDER, '') + '|' +
		'@SessionID=' + ISNULL(@SessionID, '') + '|' +
		'@Welfare=' + ISNULL(@Welfare, '')
	INSERT INTO ErrorLog	
	SELECT 'm2 ' + ISNULL(error_Message(), ' no msg')+ ' para=' + ISNULL(@Para, 'no para ') + ISNULL(@SQL, ' no sql'), error_number(), error_line(), GETDATE()
END CATCH





GO
/****** Object:  StoredProcedure [dbo].[mblJobByCpMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2016.3.22
--创建人：Lucifer
--alen 2018-4-9
--#####################################################
CREATE PROCEDURE [dbo].[mblJobByCpMainIDSelect]
(
	@cpMainID INT
)
AS
BEGIN
	SELECT a.ForwardEmail,a.IssueEnd,a.id,a.lng,a.lat,a.caMainID,a.RefreshDate,a.dcRegionId,a.dcJobTypeId,a.Welfare1,a.dcSalaryID,a.dcSalaryIDMax,
		a.Welfare2,a.Welfare3,a.Welfare4,a.Welfare5,a.Welfare6,a.Welfare7,a.Welfare8,a.Welfare9,a.Welfare10,
		a.Welfare11,a.Welfare12,a.Welfare13,a.Welfare14,a.Welfare15,a.Welfare16,a.Welfare17,a.Welfare18,a.Welfare19,
		a.Lng,a.Lat,a.Name,a.cpMainID,i.secondid encpmainid,a.secondid enjobid,i.Name cpName,i.MemberType,a.Responsibility,
		a.Demand,a.MinAge,a.MaxAge,b.Description JobType,c.FullName JobRegion,d.Description NeedNumber,
		e.Description EmployType,ISNULL((SELECT IsOnline FROM caOnline WHERE caMainId =a.caMainID), 0) AS IsOnline,
		f.Description Salary,(CASE WHEN g.Description IS NULL THEN '不限' ELSE g.Description END) Education,a.IssueEnd,
		h.Description Experience ,a.IssueEnd,a.Promotion,STUFF((SELECT '@' + Tags FROM jobTags WITH(NOLOCK) WHERE jobID = a.ID FOR XML PATH('')),1,1,'') JobTags 
	FROM Job a WITH(NOLOCK)
	LEFT JOIN dcJobType b WITH(NOLOCK) ON a.dcJobTypeID=b.ID 
	LEFT JOIN dcRegion c WITH(NOLOCK) ON a.dcRegionID=c.ID 
	LEFT JOIN dcOthers d WITH(NOLOCK) ON a.NeedNumber=d.DetailID AND d.Category='招聘人数'
	LEFT JOIN dcOthers e WITH(NOLOCK) ON a.EmployType=e.DetailID AND e.Category='工作性质'
	LEFT JOIN dcSalary f WITH(NOLOCK) ON a.dcSalaryID=f.ID 
	LEFT JOIN dcEducation g WITH(NOLOCK) ON a.dcEducationID=g.ID 
	LEFT JOIN dcOthers h WITH(NOLOCK) ON a.MinExperience=h.DetailID AND h.Category='职位要求工作经验'
	LEFT JOIN cpMain i WITH(NOLOCK) ON a.cpMainID=i.ID 
	WHERE a.cpMainID = @cpMainID
	AND a.Valid = 1
	ORDER BY DisplayNo,a.IssueEnd,a.id,a.LastModifyDate DESC
END

GO
/****** Object:  StoredProcedure [dbo].[mblJobByIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.06
--创建人：Nick
--说明：获取职位信息
--harry 2015-6-3
--增加forwardemail
--John 2015-8-19
--增加MemberType
--#####################################################
CREATE PROCEDURE [dbo].[mblJobByIDSelect]
(
    @JobID VARCHAR(20),
    @ColumnName VARCHAR(10)
)
AS
SET NOCOUNT ON
BEGIN
    DECLARE @SQL VARCHAR(MAX)
    SELECT @ColumnName = REPLACE(@ColumnName, '''', ''),
    @JobID = REPLACE(@JobID, '''', '')

    SET @SQL = '
SELECT a.ForwardEmail,a.IssueEnd,a.id,a.lng,a.lat,a.caMainID,a.RefreshDate,a.dcRegionId,a.dcJobTypeId,a.Welfare1,
	a.Welfare2,a.Welfare3,a.Welfare4,a.Welfare5,a.Welfare6,a.Welfare7,a.Welfare8,a.Welfare9,a.Welfare10,
	a.Welfare11,a.Welfare12,a.Welfare13,a.Welfare14,a.Welfare15,a.Welfare16,a.Welfare17,a.Welfare18,Welfare19,Negotiable,
	a.dcSalaryId, a.dcSalaryIdMax,a.Name,a.cpMainID,i.secondid encpmainid,a.secondid enjobid,i.Name cpName,i.MemberType,a.Responsibility,
	a.Demand,a.MinAge,a.MaxAge,b.Description JobType,c.FullName JobRegion,d.Description NeedNumber,
	e.Description EmployType,ISNULL((SELECT IsOnline FROM caOnline WHERE caMainId =a.caMainID), 0) AS IsOnline,
	f.DescriptionCp Salary,j.DescriptionCp SalaryMax,(CASE WHEN g.Description IS NULL THEN ''不限'' ELSE g.Description END) Education,
	h.Description Experience,a.Valid, i.dcProvinceId, 
	STUFF((SELECT ''@'' + Tags FROM jobTags WITH(NOLOCK) WHERE jobID = a.ID FOR XML PATH('''')),1,1,'''') JobTags
FROM Job a WITH(NOLOCK)
LEFT JOIN dcJobType b WITH(NOLOCK) ON a.dcJobTypeID=b.ID 
LEFT JOIN dcRegion c WITH(NOLOCK) ON a.dcRegionID=c.ID 
LEFT JOIN dcOthers d WITH(NOLOCK) ON a.NeedNumber=d.DetailID AND d.Category=''招聘人数'' 
LEFT JOIN dcOthers e WITH(NOLOCK) ON a.EmployType=e.DetailID AND e.Category=''工作性质''
LEFT JOIN dcSalary f WITH(NOLOCK) ON a.dcSalaryID=f.ID 
LEFT JOIN dcEducation g WITH(NOLOCK) ON a.dcEducationID=g.ID 
LEFT JOIN dcOthers h WITH(NOLOCK) ON a.MinExperience=h.DetailID AND h.Category=''职位要求工作经验'' 
LEFT JOIN cpMain i WITH(NOLOCK) ON a.cpMainID=i.ID
LEFT JOIN dcSalary j WITH(NOLOCK) ON a.dcSalaryIDMax=j.ID
WHERE a.' + @ColumnName + ' = ''' + @JobID + ''''
    --print @sql
    EXEC(@SQL)
END
GO
/****** Object:  StoredProcedure [dbo].[mblJobByIntentionSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


--[pcJobByIntentionSelectByPhone] 8100669
CREATE PROCEDURE [dbo].[mblJobByIntentionSelect]
(
	@cvMainID INT
)
AS
BEGIN
	DECLARE @JobType AS VARCHAR(100)
	DECLARE @JobTypeName AS VARCHAR(1000)
	DECLARE @JobPlace AS VARCHAR(100)
	DECLARE @JobPlaceName AS VARCHAR(100)
	DECLARE @Industry AS VARCHAR(100)
	DECLARE @IndustryName AS VARCHAR(100)
	DECLARE @INTTemp AS INT
	DECLARE @STRTemp AS VARCHAR(20)
	DECLARE #JobType CURSOR FOR SELECT a.dcJobTypeID,b.Description JobType FROM cvJobType a WITH(NOLOCK),dcJobType b WITH(NOLOCK) WHERE a.dcJobTypeID=b.ID AND a.cvMainID=@cvMainID ORDER BY a.dcJobTypeID
	DECLARE #JobPlace CURSOR FOR SELECT a.dcRegionID,b.FullName Region FROM cvJobPlace a WITH(NOLOCK),dcRegion b WITH(NOLOCK) WHERE a.dcRegionID=b.ID AND a.cvMainID=@cvMainID ORDER BY a.dcRegionID
	DECLARE #Industry CURSOR FOR SELECT a.dcIndustryID,b.Description Industry FROM cvIndustry a WITH(NOLOCK),dcIndustry b WITH(NOLOCK) WHERE a.dcIndustryID=b.ID AND a.cvMainID=@cvMainID ORDER BY dcIndustryID
 
	--取得JobType	
	OPEN #JobType
	FETCH NEXT FROM #JobType INTO @INTTemp,@STRTemp
	WHILE @@FETCH_STATUS = 0 
	BEGIN 
		IF Len(@JobType) > 0
		BEGIN
			SET @JobType = @JobType + ' ' +  Rtrim(CONVERT(CHAR(10),@INTTemp))
			SET @JobTypeName = @JobTypeName + ' ' + @STRTemp
		END
		ELSE
		BEGIN
			SET @JobType = Rtrim(CONVERT(CHAR(10),@INTTemp))
			SET @JobTypeName = @STRTemp
		END
		FETCH NEXT FROM #JobType INTO @INTTemp,@STRTemp
	END
	CLOSE #JobType
	DEALLOCATE #JobType

	--取得JobPlace	
	OPEN #JobPlace
	FETCH NEXT FROM #JobPlace INTO @INTTemp,@STRTemp
	WHILE @@FETCH_STATUS = 0 
	BEGIN 
		IF Len(@JobPlace) > 0
		BEGIN
			SET @JobPlace = @JobPlace + ' ' + Rtrim(CONVERT(CHAR(10),@INTTemp))
			SET @JobPlaceName = @JobPlaceName + ' ' + @STRTemp
		END
		ELSE
		BEGIN
			SET @JobPlace = Rtrim(CONVERT(CHAR(10),@INTTemp))
			SET @JobPlaceName = @STRTemp
		END
		FETCH NEXT FROM #JobPlace INTO @INTTemp,@STRTemp
	END
	CLOSE #JobPlace
	DEALLOCATE #JobPlace 
	--取得Industry	
	OPEN #Industry
	FETCH NEXT FROM #Industry INTO @INTTemp,@STRTemp
	WHILE @@FETCH_STATUS = 0 
	BEGIN 
		IF Len(@Industry) > 0
		BEGIN
			SET @Industry = @Industry + ' ' + Rtrim(CONVERT(CHAR(10),@INTTemp))
			SET @IndustryName = @IndustryName + ' ' + @STRTemp
		END
		ELSE
		BEGIN
			SET @Industry = Rtrim(CONVERT(CHAR(10),@INTTemp))
			SET @IndustryName = @STRTemp
		END
		FETCH NEXT FROM #Industry INTO @INTTemp,@STRTemp
	END
	CLOSE #Industry
	DEALLOCATE #Industry
	SELECT
		RelatedWorkYears,
		EmployType,
		dcSalaryID,
		IsNegotiable,
		b.Description Salary,
		@JobType AS JobType,
		@JobPlace AS JobPlace,
		@Industry AS Industry,
		@JobTypeName AS JobTypeName,
		@JobPlaceName AS JobPlaceName,
		@IndustryName AS IndustryName
	From cvMain a WITH(NOLOCK)
	LEFT JOIN dcSalary b WITH(NOLOCK) ON a.dcSalaryID=b.ID
	WHERE a.id=@cvMainID
END














GO
/****** Object:  StoredProcedure [dbo].[mblJobByJobIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.6
--创建人：Nick
--说明：
--#####################################################
CREATE PROCEDURE [dbo].[mblJobByJobIDSelect]
(
	@jobID VARCHAR(MAX)
)
AS
BEGIN
	SELECT DISTINCT cpmainid 
	FROM Job WITH(NOLOCK)
	WHERE id IN (SELECT a FROM fnsplit(@jobID, ',')) 
	GROUP BY cpmainid
	HAVING COUNT(1) > 3
END


GO
/****** Object:  StoredProcedure [dbo].[mblJobByMapSearchSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[mblJobByMapSearchSelect] 
(
	@Distance INT,				--距离范围
	@Lng DECIMAL(8,5),			--经度
	@Lat DECIMAL(8,5),			--纬度
	@dcJobTypeID VARCHAR(100), 	--职位类别
	@dcIndustryID VARCHAR(40), --dcprovinceid  --求职行业
	@dcSalaryID TINYINT, 		--月薪
	@MinExperience TINYINT, 	--工作经验，100为未选择
	@dcEducationID TINYINT,		--最低学历
	@EmployType VARCHAR(10),	--工作性质，1全职；3兼职；4实习，
	@CompanySizeID VARCHAR(1), 	--企业规模
	@Welfare NVARCHAR(50), 		--福利待遇
	@Status TINYINT, 			--0：无关；1：企业在线；2：企业不在线 
	@Type INT, 					--1：主动搜索  点击搜索按钮 10分钟，翻页60分钟有效；0：翻页搜索，不刷新
	@PageNumber INT 			--翻页页码
)
AS
--INSERT procLog SELECT 'mblJobByMapSearchSelect', @Lng, GETDATE()
IF @Distance IS NULL OR @Lng IS NULL OR @Lat IS NULL
	RETURN
--@SessionId = 50
SET NOCOUNT ON
BEGIN TRY
	DECLARE @IsOnline INT, @dcProvinceID VARCHAR(2)
	IF @dcIndustryID LIKE 'p=%'
		SET @dcProvinceID = REPLACE(@dcIndustryID, 'p=', '')
	ELSE
		SET @dcProvinceID = 0
	
	BEGIN
		----给null值变量赋默认值
		SELECT @dcJobTypeID = RTRIM(dbo.FormatIDS(@dcJobTypeID)),
			@dcIndustryID = ISNULL(@dcIndustryID, ''),
			@Welfare = RTRIM(dbo.FormatIDS(ISNULL(@Welfare, ''))),
			@Type = ISNULL(@Type, 0),
			@dcSalaryID = ISNULL(@dcSalaryID, 0),
			@MinExperience = ISNULL(@MinExperience, 100),
			@dcEducationID = ISNULL(@dcEducationID, 0),
			@PageNumber = ISNULL(@PageNumber, 0),
			@CompanySizeID = ISNULL(@CompanySizeID, '0'),
			@EmployType = CASE @EmployType WHEN '2' THEN '1,3' ELSE ISNULL(@EmployType, '') END,
			@IsOnline = ISNULL(@Status, 0)
		IF @dcEducationID = 100
			SET @dcEducationID = 0
		IF RIGHT(@dcJobTypeID, 1) = ','
			SET @dcJobTypeID = LEFT(@dcJobTypeID, LEN(@dcJobTypeID) - 1)
		IF RIGHT(@dcIndustryID, 1) = ','
			SET @dcIndustryID = LEFT(@dcIndustryID, LEN(@dcIndustryID) - 1)

		DECLARE @paSearchConditionID AS INT, 
			@MinId AS INT, 
			@PageSize AS TINYINT, 
			@TableID AS TINYINT

		SELECT @paSearchConditionID = 0, @PageSize = 30  --每页的行数
		
		----搜索1分钟前的数据
		SELECT TOP 1 @paSearchConditionID = ID
		FROM SearchDB..paSearchCondition WITH(NOLOCK)
		WHERE JobType=@dcJobTypeID AND IsOnline = @IsOnline
		AND Industry=@dcIndustryID AND Education=@dcEducationID
		AND Experience=@MinExperience AND Salary=@dcSalaryID
		AND EmployType=@EmployType AND CompanySizeID = @CompanySizeID
		AND Lat = @Lat AND LNg = @Lng AND Distance = @Distance
		AND Welfare = @Welfare AND IsDelete = 0 AND dcProvinceId = @dcProvinceId
		ORDER BY ID DESC

		IF ISNULL(@paSearchConditionID, 0) = 0
		BEGIN
			SET @Type =1
			GOTO SelectReset	--无数据，重新搜索
		END
		ELSE
		BEGIN
			SELECT @TableID = @paSearchConditionID % 4
			GOTO GetRecordSet	--从临时结果中提取数据
		END
	END

	SelectReset:				--从job中搜索数据
	BEGIN TRAN
		DECLARE @SQL AS VARCHAR(8000), @WHERE AS VARCHAR(8000), @FROM AS VARCHAR(1000),
			@JobType AS VARCHAR(3000), @ValidJobNumber AS INT
		DECLARE @T_JobType AS TABLE(ID INT)
		
		----记录查询条件
		INSERT INTO SearchDB..paSearchCondition(SessionID, LogTime, JobType, Industry, 
			Lng, Lat, Distance, Welfare, KeyWord, KeyType, ReuseNumber, Education, Experience, 
			Salary, EmployType, CompanySizeID, IsOnline, dcProvinceId)
		VALUES(
			50, GETDATE(), @dcJobTypeID, @dcIndustryID, @Lng, @Lat, 
			@Distance, @Welfare, '', 0, 0, @dcEducationID, @MinExperience, 
			@dcSalaryID, @EmployType, @CompanySizeID, @IsOnline, @dcProvinceId)

		SET @paSearchConditionID = @@IDENTITY
		SELECT @TableID = @paSearchConditionID % 4

		------生成职位类别的表变量，因为职位类别有包含（父子）关系
		SELECT @JobType=''
		
		----生成求聘职位的表变量
		IF LEN(@dcJobTypeID) > 0
		BEGIN
			DECLARE @T_Temp AS TABLE(ID INT)		--临时表，用于构建组合查询语句
			INSERT INTO @T_Temp
			SELECT * FROM dbo.fnSplit(@dcJobTypeID, ',')

			INSERT INTO @T_JobType
			SELECT DISTINCT ID FROM dcJobType WITH(NOLOCK)
			WHERE ParentId IN(SELECT ID FROM @T_TEMP) 
			OR ParentId2 in(SELECT ID FROM @T_TEMP)
			OR ID IN(SELECT ID FROM @T_TEMP)
			----生成in字符串
			SELECT @JobType = (@JobType + LTRIM(STR(ID) + ',')) FROM @T_JobType
			IF RIGHT(@JobType, 1) = ','
				SET @JobType = LEFT(@JobType, LEN(@JobType) - 1)
		END
		
		----建立临时表
		CREATE TABLE #Job(
			RowID INT IDENTITY(1, 1), 
			ID INT NOT NULL, 
			dcJobTypeID SMALLINT NOT NULL, 
			dcJobTypeIDMinor SMALLINT NULL, 
			dcSalaryID TINYINT NOT NULL, 
			dcRegionID VARCHAR(6) NULL, 
			dcEducationID TINYINT NOT NULL, 
			MinExperience TINYINT NOT NULL, 
			RefreshDate SMALLDATETIME NULL,
			EmployType TINYINT NULL,
			dcCompanySizeID SMALLINT NULL
		)
		------刷新时间，根据刷新时间编号计算
		----生成插入临时表的Sql语句
		SET @SQL='
			INSERT INTO #Job
			SELECT a.ID, a.dcJobTypeID, 
				a.dcJobTypeIDMinor, a.dcSalaryID, 
				a.dcRegionID, a.dcEducationID, a.MinExperience, 
				a.IssueDate,a.EmployType,b.dcCompanySizeID'
		SET @FROM = '
			FROM JobPublish a WITH(NOLOCK)
			INNER JOIN cpMainPublish b WITH(NOLOCK) ON a.cpMainID=b.ID'
		----职位有效，单位新有效
		IF LEN(@dcProvinceID) > 1
			SET @WHERE = '
			WHERE b.dcProvinceID = ' + @dcProvinceID + '
			AND a.Valid = 1
			AND b.Valid = 1'
		ELSE
			SET @WHERE = '
			WHERE a.Valid = 1
			AND b.Valid = 1'
		----需要增加全文索引的关键字查询	
		----职位类别
		IF LEN(@dcJobTypeID) > 0
			SET @WHERE = @WHERE + '
			AND (a.dcJobTypeID IN(' + @JobType +')
				OR a.dcJobTypeIDMinor IN(' + @JobType + '))'
		IF @dcSalaryID > 0
		BEGIN
			IF @dcSalaryID < 100				----从form中搜索，月薪跨2个级别, 是本级和上级别的薪金
			BEGIN
				SET @WHERE = @WHERE + '
			AND a.dcSalaryID IN(' + LTRIM(STR(@dcSalaryID)) + ',' + LTRIM(STR(@dcSalaryID + 1))
				SET @WHERE = @WHERE + ')'
			END
			IF @dcSalaryID = 100	----从筛选结果中点击面议，值是100
			BEGIN
				SET @WHERE = @WHERE + '
			AND a.dcSalaryID = 100'
			END
			IF @dcSalaryID > 100	----从筛选结果中点击搜索，月薪只有1个级别，传值时增加100
				SET @WHERE = @WHERE + '
			AND a.dcSalaryID=' + LTRIM(STR(@dcSalaryID-100))
		END
		----工作经验要求
		IF @MinExperience < 100
		SET @WHERE = @WHERE + ' 
			AND a.MinExperience = ' + LTRIM(STR(@MinExperience))

		----学历要求
		----'1初中', '2\3\4高中、中技、中专', '5大专', '6本科', '7硕士', '8博士
		IF @dcEducationID > 0
			IF @dcEducationID = 2
				SET @WHERE = @WHERE + '
			AND a.dcEducationID IN(2, 3, 4)'
			ELSE
				SET @WHERE = @WHERE + '
			AND a.dcEducationID = ' + LTRIM(STR(@dcEducationID))
		----1、全职；3、兼职；4实习。	2、全职/兼职 职位中无此项
		IF LEN(@EmployType) > 0
			SET @WHERE = @WHERE + '
			AND a.EmployType IN (' + @EmployType + ')'
		IF @CompanySizeID BETWEEN 1 AND 6
			SET @WHERE = @WHERE + '
			AND b.dcCompanySizeID = ' + LTRIM(STR(@CompanySizeID))
		IF LEN(@Welfare) > 0
			SET @WHERE = @WHERE + '
			AND a.Welfare' + REPLACE(@Welfare, ',', ' = 1 AND a.Welfare') + ' = 1'
		IF @IsOnline = 1
			SET @WHERE = @WHERE + '
			AND a.caMainId IN(SELECT caMainId FROM caOnline WITH(NOLOCK) WHERE IsOnline = 1) '
 
		DECLARE @Degree AS DECIMAL(8,5),@LBLng AS DECIMAL(8,5),@LBLat AS DECIMAL(8,5),
		@RTLng AS DECIMAL(8,5),@RTLat AS DECIMAL(8,5)
		SET @Degree = @Distance / 100000.0;

		SET @LBLng = @Lng - @Degree
		SET @LBLat = @Lat - @Degree
		SET @RTLng = @Lng + @Degree
		SET @RTLat = @Lat + @Degree
		SET @WHERE = @WHERE + '
			AND a.Lng BETWEEN ' + CONVERT(VARCHAR,@LBLng) + ' AND ' + CONVERT(VARCHAR,@RTLng) + '
			AND a.Lat BETWEEN ' + CONVERT(VARCHAR,@LBLat) + ' AND ' + CONVERT(VARCHAR,@RTLat) + '
			AND (a.Lng-' + CONVERT(VARCHAR,@Lng) + ')*(a.Lng-' + CONVERT(VARCHAR,@Lng) + ')+
			(a.Lat-' + CONVERT(VARCHAR,@Lat) + ')*(a.Lat-' + CONVERT(VARCHAR,@Lat) + ')<' + CONVERT(VARCHAR,@Degree*@Degree)

		SET @SQL = @SQL + @FROM + @WHERE
		
		--IF LEN(@ORDER)>0
		SET @SQL=@SQL + ' ORDER BY a.RefreshDate DESC, a.ID'
		--原来是ORDER BY a.IssueDate DESC, a.ID，Richard 2011年11月23日17：06分修改

		----把符合条件的职位全部列出
		--PRINT @SQL
		EXEC(@SQL)
		
		SET @ValidJobNumber = @@ROWCOUNT
		----记录查询结果总数
		UPDATE SearchDB..paSearchCondition SET ValidJobNumber=@ValidJobNumber, SQl=@SQL WHERE ID=@paSearchConditionID
		----插入JobType数据
		DECLARE @TitleValue AS INT, @TopRows AS INT, @AllRows AS INT
		IF (@TableID = 0)
		BEGIN
			INSERT INTO SearchDB..paSearchCount_0(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'JobType', dcJobTypeID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcJobTypeID ORDER BY dcJobTypeID
			----计算全部某职位类别，2, 4位的数据
			UPDATE a SET a.TitleValue = b.TitleValue
			FROM SearchDB..paSearchCount_0 a WITH(NOLOCK), 
				(SELECT LEFT(TitleID, 2) TitleID, SUM(TitleValue) TitleValue
				FROM SearchDB..paSearchCount_0 WITH(NOLOCK)
				WHERE paSearchConditionID = @paSearchConditionID AND Title = 'JobType'
				GROUP BY LEFT(TitleID, 2)) b
			WHERE a.TitleId = b.TitleID
			AND a.paSearchConditionID = @paSearchConditionID AND a.Title = 'JobType'
			----写入TitleDesc
			UPDATE a SET a.TitleDesc = b.Description
			FROM SearchDB..paSearchCount_0 a WITH(NOLOCK), dcJobType b WITH(NOLOCK)
			WHERE a.TitleID = b.ID AND a.paSearchConditionID = @paSearchConditionID
			AND a.Title = 'JobType'
			
			INSERT INTO SearchDB..paSearchCount_0(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Salary', dcSalaryID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcSalaryID ORDER BY dcSalaryID

			INSERT INTO SearchDB..paSearchCount_0(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Region', dcRegionID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcRegionID ORDER BY dcRegionID
			----计算全部地区，2位的数据
			UPDATE a SET a.TitleValue = b.TitleValue
			FROM SearchDB..paSearchCount_0 a WITH(NOLOCK), 
			(SELECT LEFT(TitleID, 2) TitleID, SUM(TitleValue) TitleValue
			FROM SearchDB..paSearchCount_0 WITH(NOLOCK)
			WHERE paSearchConditionID = @paSearchConditionID AND Title = 'Region'
			GROUP BY LEFT(TitleID, 2)) b
			WHERE a.TitleId = b.TitleID
			AND a.paSearchConditionID = @paSearchConditionID AND a.Title = 'Region'
			----计算全部地区，4位的数据
			UPDATE a SET a.TitleValue = b.TitleValue
			FROM SearchDB..paSearchCount_0 a WITH(NOLOCK), (
				SELECT LEFT(TitleID, 4) TitleID, SUM(TitleValue) TitleValue
				FROM SearchDB..paSearchCount_0 WITH(NOLOCK)
				WHERE paSearchConditionID = @paSearchConditionID AND Title = 'Region'
				AND LEN(TitleID) >3
				GROUP BY LEFT(TitleID, 4)) b
			WHERE a.TitleId = b.TitleID
			AND a.paSearchConditionID = @paSearchConditionID AND a.Title = 'Region'
			----写入TitleDesc
			UPDATE a SET a.TitleDesc = b.Description
			FROM SearchDB..paSearchCount_0 a WITH(NOLOCK), dcRegion b WITH(NOLOCK)
			WHERE a.TitleID = b.ID AND a.paSearchConditionID = @paSearchConditionID
			AND a.Title = 'Region'

			INSERT INTO SearchDB..paSearchCount_0(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Education', CASE WHEN dcEducationId IN(2, 3, 4) THEN 2 ELSE dcEducationId END, COUNT(*) 
			FROM #Job WITH(NOLOCK)
			GROUP BY CASE WHEN dcEducationId IN(2, 3, 4) THEN 2 ELSE dcEducationId END
			ORDER BY CASE WHEN dcEducationId IN(2, 3, 4) THEN 2 ELSE dcEducationId END
			
			INSERT INTO SearchDB..paSearchCount_0(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Experience', MinExperience, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY MinExperience ORDER BY MinExperience
			
			INSERT INTO SearchDB..paSearchCount_0(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'EmployType', EmployType, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY EmployType ORDER BY EmployType

			INSERT INTO SearchDB..paSearchCount_0(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'CompanySize', dcCompanySizeID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcCompanySizeID ORDER BY dcCompanySizeID

			INSERT INTO SearchDB..paSearchJobID_0(paSearchConditionID, JobId, IsTop)
			SELECT Top 3 @paSearchConditionID, a.JobId, 1 
			FROM SearchJobTop a WITH(NOLOCK), (SELECT TOP 2000 ID FROM #Job WITH(NOLOCK)) b 
			WHERE b.ID = a.JobId ORDER BY a.OpenDate DESC
			SET @TopRows = @@ROWCOUNT

			INSERT INTO SearchDB..paSearchJobID_0(paSearchConditionID, JobId, IsTop)
			SELECT TOP 2000 @paSearchConditionID, ID, 0 FROM #Job WITH(NOLOCK)
			SET @AllRows = @@ROWCOUNT

			IF @TopRows = 0 AND @AllRows > 100
				UPDATE SearchDB..paSearchJobID_0 SET IsTop = 1 
				WHERE paSearchConditionID = @paSearchConditionID
				AND ID IN (SELECT TOP 3 ID FROM SearchDB..paSearchJobID_0 WITH(NOLOCK) WHERE paSearchConditionID = @paSearchConditionID)
		END
		ELSE IF (@TableId = 1)
		BEGIN
			INSERT INTO SearchDB..paSearchCount_1(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'JobType', dcJobTypeID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcJobTypeID ORDER BY dcJobTypeID
			----计算全部某职位类别，2, 4位的数据
			UPDATE a SET a.TitleValue = b.TitleValue
			FROM SearchDB..paSearchCount_1 a WITH(NOLOCK), 
			(SELECT LEFT(TitleID, 2) TitleID, SUM(TitleValue) TitleValue
			FROM SearchDB..paSearchCount_1 WITH(NOLOCK)
			WHERE paSearchConditionID = @paSearchConditionID AND Title = 'JobType'
			GROUP BY LEFT(TitleID, 2)) b
			WHERE a.TitleId = b.TitleID
			AND a.paSearchConditionID = @paSearchConditionID AND a.Title = 'JobType'
			----写入TitleDesc
			UPDATE a SET a.TitleDesc = b.Description
			FROM SearchDB..paSearchCount_1 a WITH(NOLOCK), dcJobType b WITH(NOLOCK)
			WHERE a.TitleID = b.ID AND a.paSearchConditionID = @paSearchConditionID
			AND a.Title = 'JobType'
			
			INSERT INTO SearchDB..paSearchCount_1(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Salary', dcSalaryID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcSalaryID ORDER BY dcSalaryID

			INSERT INTO SearchDB..paSearchCount_1(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Region', dcRegionID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcRegionID ORDER BY dcRegionID
			----计算全部地区，2位的数据
			UPDATE a SET a.TitleValue = b.TitleValue
			FROM SearchDB..paSearchCount_1 a WITH(NOLOCK), 
			(SELECT LEFT(TitleID, 2) TitleID, SUM(TitleValue) TitleValue
			FROM SearchDB..paSearchCount_1 WITH(NOLOCK)
			WHERE paSearchConditionID = @paSearchConditionID AND Title = 'Region'
			GROUP BY LEFT(TitleID, 2)) b
			WHERE a.TitleId = b.TitleID
			AND a.paSearchConditionID = @paSearchConditionID AND a.Title = 'Region'
			----计算全部地区，4位的数据
			UPDATE a SET a.TitleValue = b.TitleValue
			FROM SearchDB..paSearchCount_1 a WITH(NOLOCK), (
				SELECT LEFT(TitleID, 4) TitleID, SUM(TitleValue) TitleValue
				FROM SearchDB..paSearchCount_1 WITH(NOLOCK)
				WHERE paSearchConditionID = @paSearchConditionID AND Title = 'Region'
				AND LEN(TitleID) >3
				GROUP BY LEFT(TitleID, 4)) b
			WHERE a.TitleId = b.TitleID
			AND a.paSearchConditionID = @paSearchConditionID AND a.Title = 'Region'
			----写入TitleDesc
			UPDATE a SET a.TitleDesc = b.Description
			FROM SearchDB..paSearchCount_1 a WITH(NOLOCK), dcRegion b WITH(NOLOCK)
			WHERE a.TitleID = b.ID AND a.paSearchConditionID = @paSearchConditionID
			AND a.Title = 'Region'

			INSERT INTO SearchDB..paSearchCount_1(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Education', CASE WHEN dcEducationId IN(2, 3, 4) THEN 2 ELSE dcEducationId END, COUNT(*)
			FROM #Job WITH(NOLOCK)
			GROUP BY CASE WHEN dcEducationId IN(2, 3, 4) THEN 2 ELSE dcEducationId END
			ORDER BY CASE WHEN dcEducationId IN(2, 3, 4) THEN 2 ELSE dcEducationId END
			
			INSERT INTO SearchDB..paSearchCount_1(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Experience', MinExperience, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY MinExperience ORDER BY MinExperience
			
			INSERT INTO SearchDB..paSearchCount_1(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'EmployType', EmployType, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY EmployType ORDER BY EmployType

			INSERT INTO SearchDB..paSearchCount_1(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'CompanySize', dcCompanySizeID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcCompanySizeID ORDER BY dcCompanySizeID

			INSERT INTO SearchDB..paSearchJobID_1(paSearchConditionID, JobId, IsTop)
			SELECT Top 3 @paSearchConditionID, a.JobId, 1 
			FROM SearchJobTop a WITH(NOLOCK), (SELECT TOP 2000 ID FROM #Job WITH(NOLOCK)) b 
			WHERE b.ID = a.JobId ORDER BY a.OpenDate DESC
			SET @TopRows = @@ROWCOUNT

			INSERT INTO SearchDB..paSearchJobID_1(paSearchConditionID, JobId, IsTop)
			SELECT TOP 2000 @paSearchConditionID, ID, 0 FROM #Job WITH(NOLOCK)
			SET @AllRows = @@ROWCOUNT

			IF @TopRows = 0 AND @AllRows > 100
				UPDATE SearchDB..paSearchJobID_1 SET IsTop = 1 
				WHERE paSearchConditionID = @paSearchConditionID
				AND ID IN (SELECT TOP 3 ID FROM SearchDB..paSearchJobID_1 WITH(NOLOCK) WHERE paSearchConditionID = @paSearchConditionID)
		END
		ELSE IF (@TableId = 2)
		BEGIN
			INSERT INTO SearchDB..paSearchCount_2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'JobType', dcJobTypeID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcJobTypeID ORDER BY dcJobTypeID
			----计算全部某职位类别，2, 4位的数据
			UPDATE a SET a.TitleValue = b.TitleValue
			FROM SearchDB..paSearchCount_2 a WITH(NOLOCK), 
			(SELECT LEFT(TitleID, 2) TitleID, SUM(TitleValue) TitleValue
			FROM SearchDB..paSearchCount_2 WITH(NOLOCK)
			WHERE paSearchConditionID = @paSearchConditionID AND Title = 'JobType'
			GROUP BY LEFT(TitleID, 2)) b
			WHERE a.TitleId = b.TitleID
			AND a.paSearchConditionID = @paSearchConditionID AND a.Title = 'JobType'
			----写入TitleDesc
			UPDATE a SET a.TitleDesc = b.Description
			FROM SearchDB..paSearchCount_2 a WITH(NOLOCK), dcJobType b WITH(NOLOCK)
			WHERE a.TitleID = b.ID AND a.paSearchConditionID = @paSearchConditionID
			AND a.Title = 'JobType'
			
			INSERT INTO SearchDB..paSearchCount_2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Salary', dcSalaryID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcSalaryID ORDER BY dcSalaryID

			INSERT INTO SearchDB..paSearchCount_2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Region', dcRegionID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcRegionID ORDER BY dcRegionID
			----计算全部地区，2位的数据
			UPDATE a SET a.TitleValue = b.TitleValue
			FROM SearchDB..paSearchCount_2 a WITH(NOLOCK), 
			(SELECT LEFT(TitleID, 2) TitleID, SUM(TitleValue) TitleValue
			FROM SearchDB..paSearchCount_2 WITH(NOLOCK)
			WHERE paSearchConditionID = @paSearchConditionID AND Title = 'Region'
			GROUP BY LEFT(TitleID, 2)) b
			WHERE a.TitleId = b.TitleID
			AND a.paSearchConditionID = @paSearchConditionID AND a.Title = 'Region'
			----计算全部地区，4位的数据
			UPDATE a SET a.TitleValue = b.TitleValue
			FROM SearchDB..paSearchCount_2 a WITH(NOLOCK), (
				SELECT LEFT(TitleID, 4) TitleID, SUM(TitleValue) TitleValue
				FROM SearchDB..paSearchCount_2 WITH(NOLOCK)
				WHERE paSearchConditionID = @paSearchConditionID AND Title = 'Region'
				AND LEN(TitleID) >3
				GROUP BY LEFT(TitleID, 4)) b
			WHERE a.TitleId = b.TitleID
			AND a.paSearchConditionID = @paSearchConditionID AND a.Title = 'Region'
			----写入TitleDesc
			UPDATE a SET a.TitleDesc = b.Description
			FROM SearchDB..paSearchCount_2 a WITH(NOLOCK), dcRegion b WITH(NOLOCK)
			WHERE a.TitleID = b.ID AND a.paSearchConditionID = @paSearchConditionID
			AND a.Title = 'Region'

			INSERT INTO SearchDB..paSearchCount_2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Education', CASE WHEN dcEducationId IN(2, 3, 4) THEN 2 ELSE dcEducationId END, COUNT(*)
			FROM #Job WITH(NOLOCK)
			GROUP BY CASE WHEN dcEducationId IN(2, 3, 4) THEN 2 ELSE dcEducationId END
			ORDER BY CASE WHEN dcEducationId IN(2, 3, 4) THEN 2 ELSE dcEducationId END
			
			INSERT INTO SearchDB..paSearchCount_2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Experience', MinExperience, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY MinExperience ORDER BY MinExperience
			
			INSERT INTO SearchDB..paSearchCount_2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'EmployType', EmployType, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY EmployType ORDER BY EmployType

			INSERT INTO SearchDB..paSearchCount_2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'CompanySize', dcCompanySizeID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcCompanySizeID ORDER BY dcCompanySizeID

			INSERT INTO SearchDB..paSearchJobID_2(paSearchConditionID, JobId, IsTop)
			SELECT Top 3 @paSearchConditionID, a.JobId, 1 
			FROM SearchJobTop a WITH(NOLOCK), (SELECT TOP 2000 ID FROM #Job WITH(NOLOCK)) b 
			WHERE b.ID = a.JobId ORDER BY a.OpenDate DESC
			SET @TopRows = @@ROWCOUNT

			INSERT INTO SearchDB..paSearchJobID_2(paSearchConditionID, JobId, IsTop)
			SELECT TOP 2000 @paSearchConditionID, ID, 0 FROM #Job WITH(NOLOCK)
			SET @AllRows = @@ROWCOUNT

			IF @TopRows = 0 AND @AllRows > 100
				UPDATE SearchDB..paSearchJobID_2 SET IsTop = 1 
				WHERE paSearchConditionID = @paSearchConditionID
				AND ID IN (SELECT TOP 3 ID FROM SearchDB..paSearchJobID_2 WITH(NOLOCK) WHERE paSearchConditionID = @paSearchConditionID)
		END
		ELSE IF (@TableId = 3)
		BEGIN
			INSERT INTO SearchDB..paSearchCount_3(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'JobType', dcJobTypeID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcJobTypeID ORDER BY dcJobTypeID
			----计算全部某职位类别，2, 4位的数据
			UPDATE a SET a.TitleValue = b.TitleValue
			FROM SearchDB..paSearchCount_3 a WITH(NOLOCK), 
			(SELECT LEFT(TitleID, 2) TitleID, SUM(TitleValue) TitleValue
			FROM SearchDB..paSearchCount_3 WITH(NOLOCK)
			WHERE paSearchConditionID = @paSearchConditionID AND Title = 'JobType'
			GROUP BY LEFT(TitleID, 2)) b
			WHERE a.TitleId = b.TitleID
			AND a.paSearchConditionID = @paSearchConditionID AND a.Title = 'JobType'
			----写入TitleDesc
			UPDATE a SET a.TitleDesc = b.Description
			FROM SearchDB..paSearchCount_3 a WITH(NOLOCK), dcJobType b WITH(NOLOCK)
			WHERE a.TitleID = b.ID AND a.paSearchConditionID = @paSearchConditionID
			AND a.Title = 'JobType'
			
			INSERT INTO SearchDB..paSearchCount_3(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Salary', dcSalaryID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcSalaryID ORDER BY dcSalaryID

			INSERT INTO SearchDB..paSearchCount_3(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Region', dcRegionID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcRegionID ORDER BY dcRegionID
			----计算全部地区，2位的数据
			UPDATE a SET a.TitleValue = b.TitleValue
			FROM SearchDB..paSearchCount_3 a WITH(NOLOCK), 
			(SELECT LEFT(TitleID, 2) TitleID, SUM(TitleValue) TitleValue
			FROM SearchDB..paSearchCount_3 WITH(NOLOCK)
			WHERE paSearchConditionID = @paSearchConditionID AND Title = 'Region'
			GROUP BY LEFT(TitleID, 2)) b
			WHERE a.TitleId = b.TitleID
			AND a.paSearchConditionID = @paSearchConditionID AND a.Title = 'Region'
			----计算全部地区，4位的数据
			UPDATE a SET a.TitleValue = b.TitleValue
			FROM SearchDB..paSearchCount_3 a WITH(NOLOCK), (
				SELECT LEFT(TitleID, 4) TitleID, SUM(TitleValue) TitleValue
				FROM SearchDB..paSearchCount_3 WITH(NOLOCK)
				WHERE paSearchConditionID = @paSearchConditionID AND Title = 'Region'
				AND LEN(TitleID) >3
				GROUP BY LEFT(TitleID, 4)) b
			WHERE a.TitleId = b.TitleID
			AND a.paSearchConditionID = @paSearchConditionID AND a.Title = 'Region'
			----写入TitleDesc
			UPDATE a SET a.TitleDesc = b.Description
			FROM SearchDB..paSearchCount_3 a WITH(NOLOCK), dcRegion b WITH(NOLOCK)
			WHERE a.TitleID = b.ID AND a.paSearchConditionID = @paSearchConditionID
			AND a.Title = 'Region'

			INSERT INTO SearchDB..paSearchCount_3(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Education', CASE WHEN dcEducationId IN(2, 3, 4) THEN 2 ELSE dcEducationId END, COUNT(*)
			FROM #Job WITH(NOLOCK)
			GROUP BY CASE WHEN dcEducationId IN(2, 3, 4) THEN 2 ELSE dcEducationId END
			ORDER BY CASE WHEN dcEducationId IN(2, 3, 4) THEN 2 ELSE dcEducationId END
			
			INSERT INTO SearchDB..paSearchCount_3(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Experience', MinExperience, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY MinExperience ORDER BY MinExperience
			
			INSERT INTO SearchDB..paSearchCount_3(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'EmployType', EmployType, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY EmployType ORDER BY EmployType

			INSERT INTO SearchDB..paSearchCount_3(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'CompanySize', dcCompanySizeID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcCompanySizeID ORDER BY dcCompanySizeID

			INSERT INTO SearchDB..paSearchJobID_3(paSearchConditionID, JobId, IsTop)
			SELECT Top 3 @paSearchConditionID, a.JobId, 1 
			FROM SearchJobTop a WITH(NOLOCK), (SELECT TOP 2000 ID FROM #Job WITH(NOLOCK)) b 
			WHERE b.ID = a.JobId ORDER BY a.OpenDate DESC
			SET @TopRows = @@ROWCOUNT

			INSERT INTO SearchDB..paSearchJobID_3(paSearchConditionID, JobId, IsTop)
			SELECT TOP 2000 @paSearchConditionID, ID, 0 FROM #Job WITH(NOLOCK)
			SET @AllRows = @@ROWCOUNT

			IF @TopRows = 0 AND @AllRows > 100
				UPDATE SearchDB..paSearchJobID_3 SET IsTop = 1 
				WHERE paSearchConditionID = @paSearchConditionID
				AND ID IN (SELECT TOP 3 ID FROM SearchDB..paSearchJobID_3 WITH(NOLOCK) WHERE paSearchConditionID = @paSearchConditionID)
		END
		DROP TABLE #Job
		--PRINT 'DROP #JOB  ' + CONVERT(VARCHAR(30), GETDATE(), 121)
	COMMIT
	--GOTO GetRecordSet

	GetRecordSet:
	BEGIN
		DECLARE @AllJobCount AS INT
		----返回查询数量
		SELECT ValidJobNumber FROM SearchDB..paSearchCondition WITH(NOLOCK) WHERE ID=@paSearchConditionID
		SELECT @AllJobCount = ValidJobNumber FROM SearchDB..paSearchCondition WITH(NOLOCK) WHERE ID=@paSearchConditionID
		UPDATE SearchDB..paSearchCondition SET ReuseNumber = ReuseNumber + 1 WHERE ID=@paSearchConditionID
		----返回20行查询结果
		IF (@TableID = 0)
		BEGIN
			SELECT @MinId = MIN(ID) FROM SearchDB..paSearchJobID_0 WITH(NOLOCK) WHERE paSearchConditionID=@paSearchConditionID

			SET @MinId = @MinId+(@PageNumber-1)*@PageSize
			SELECT TOP 30 a.ID, a.cpMainID, a.caMainID, a.Name as JobName, 
				a.dcJobTypeIDMinor, a.NeedNumber, a.dcSalaryID, a.dcSalaryIDMax, a.EmployType, 
				a.dcRegionID, a.dcEducationID, b.HasLicence, b.IsRefreshed, dcCompanySizeID,
				a.MinExperience, a.MinAge, a.MaxAge, a.RefreshDate, a.Lng, a.Lat,
				b.Name as cpName, c.IsTop, a.SecondId EnJobID, b.SecondId EnCpMainID,a.Welfare1,a.Welfare2,
				a.Welfare3, a.Welfare4,a.Welfare5,a.Welfare6,a.Welfare7,a.Welfare8, a.Welfare9,a.Welfare10,
				a.Welfare11,a.Welfare12,a.Welfare13, a.Welfare14,a.Welfare15,a.Welfare16,a.Welfare17,a.Welfare18,
				ISNULL((SELECT IsOnline FROM caOnline WITH(NOLOCK) WHERE caMainId = a.caMainId), 0) IsOnline, b.LogoFile LogoUrl,@AllJobCount JobNumber,
				d.FullName RegionName,e.Description EducationName,f.Description ExperienceName,g.DescriptionCp dcSalary,h.DescriptionCp dcSalaryMax
			FROM JobPublish a WITH(NOLOCK), cpMainPublish b WITH(NOLOCK), SearchDB..paSearchJobID_0 c WITH(NOLOCK),
			dcRegion d WITH(NOLOCK),dcEducation e WITH(NOLOCK),dcOthers f WITH(NOLOCK),dcSalary g WITH(NOLOCK),dcSalary h WITH(NOLOCK)
			WHERE a.cpMainID = b.ID AND a.id=c.JobID AND c.paSearchConditionID=@paSearchConditionID 
			AND d.ID = a.dcRegionID AND e.ID = a.dcEducationID AND f.DetailID = a.MinExperience 
			AND f.Category='职位要求工作经验' AND g.ID = a.dcSalaryID AND h.ID = a.dcSalaryIDMax
			AND c.ID>=@MinId ORDER BY c.ID, a.ID DESC
		END

		ELSE IF (@TableID = 1)
		BEGIN
			SELECT @MinId = MIN(ID) FROM SearchDB..paSearchJobID_1 WITH(NOLOCK) WHERE paSearchConditionID=@paSearchConditionID

			SET @MinId = @MinId+(@PageNumber-1)*@PageSize
			SELECT TOP 30 a.ID, a.cpMainID, a.caMainID, a.Name as JobName, 
				a.dcJobTypeIDMinor, a.NeedNumber, a.dcSalaryID, a.dcSalaryIDMax, a.EmployType, 
				a.dcRegionID, a.dcEducationID, b.HasLicence, b.IsRefreshed, dcCompanySizeID,
				a.MinExperience, a.MinAge, a.MaxAge, a.RefreshDate, a.Lng, a.Lat,
				b.Name as cpName, c.IsTop, a.SecondId EnJobID, b.SecondId EnCpMainID,a.Welfare1,a.Welfare2,
				a.Welfare3, a.Welfare4,a.Welfare5,a.Welfare6,a.Welfare7,a.Welfare8, a.Welfare9,a.Welfare10,
				a.Welfare11,a.Welfare12,a.Welfare13, a.Welfare14,a.Welfare15,a.Welfare16,a.Welfare17,a.Welfare18,
				ISNULL((SELECT IsOnline FROM caOnline WITH(NOLOCK) WHERE caMainId = a.caMainId), 0) IsOnline,
				b.LogoFile LogoUrl,@AllJobCount JobNumber,
				d.FullName RegionName,e.Description EducationName,f.Description ExperienceName,g.DescriptionCp dcSalary,h.DescriptionCp dcSalaryMax
			FROM JobPublish a WITH(NOLOCK), cpMainPublish b WITH(NOLOCK), SearchDB..paSearchJobID_1 c WITH(NOLOCK),
			dcRegion d WITH(NOLOCK),dcEducation e WITH(NOLOCK),dcOthers f WITH(NOLOCK),dcSalary g WITH(NOLOCK),dcSalary h WITH(NOLOCK)
			WHERE a.cpMainID = b.ID AND a.id=c.JobID AND c.paSearchConditionID=@paSearchConditionID 
			AND d.ID = a.dcRegionID AND e.ID = a.dcEducationID AND f.DetailID = a.MinExperience 
			AND f.Category='职位要求工作经验' AND g.ID = a.dcSalaryID AND h.ID = a.dcSalaryIDMax
			AND c.ID>=@MinId ORDER BY c.ID, a.ID DESC
		END
		ELSE IF (@TableID = 2)
		BEGIN
			SELECT @MinId = MIN(ID) FROM SearchDB..paSearchJobID_2 WITH(NOLOCK) WHERE paSearchConditionID=@paSearchConditionID

			SET @MinId = @MinId+(@PageNumber-1)*@PageSize
			SELECT TOP 30 a.ID, a.cpMainID, a.caMainID, a.Name as JobName, 
				a.dcJobTypeIDMinor, a.NeedNumber, a.dcSalaryID, a.dcSalaryIDMax, a.EmployType, 
				a.dcRegionID, a.dcEducationID, b.HasLicence, b.IsRefreshed, dcCompanySizeID,
				a.MinExperience, a.MinAge, a.MaxAge, a.RefreshDate, a.Lng, a.Lat,
				b.Name as cpName, c.IsTop, a.SecondId EnJobID, b.SecondId EnCpMainID,a.Welfare1,a.Welfare2,
				a.Welfare3, a.Welfare4,a.Welfare5,a.Welfare6,a.Welfare7,a.Welfare8, a.Welfare9,a.Welfare10,
				a.Welfare11,a.Welfare12,a.Welfare13, a.Welfare14,a.Welfare15,a.Welfare16,a.Welfare17,a.Welfare18,
				ISNULL((SELECT IsOnline FROM caOnline WITH(NOLOCK) WHERE caMainId = a.caMainId), 0) IsOnline, 
				b.LogoFile LogoUrl, @AllJobCount JobNumber,
				d.FullName RegionName,e.Description EducationName,f.Description ExperienceName,g.DescriptionCp dcSalary,h.DescriptionCp dcSalaryMax
			FROM JobPublish a WITH(NOLOCK), cpMainPublish b WITH(NOLOCK), SearchDB..paSearchJobID_2 c WITH(NOLOCK),
			dcRegion d WITH(NOLOCK),dcEducation e WITH(NOLOCK),dcOthers f WITH(NOLOCK),dcSalary g WITH(NOLOCK),dcSalary h WITH(NOLOCK)
			WHERE a.cpMainID = b.ID AND a.id=c.JobID AND c.paSearchConditionID=@paSearchConditionID 
			AND d.ID = a.dcRegionID AND e.ID = a.dcEducationID AND f.DetailID = a.MinExperience 
			AND f.Category='职位要求工作经验' AND g.ID = a.dcSalaryID AND h.ID = a.dcSalaryIDMax
			AND c.ID>=@MinId ORDER BY c.ID, a.ID DESC
		END
		ELSE IF (@TableID = 3)
		BEGIN
			SELECT @MinId = MIN(ID) FROM SearchDB..paSearchJobID_3 WITH(NOLOCK) WHERE paSearchConditionID=@paSearchConditionID

			SET @MinId = @MinId+(@PageNumber-1)*@PageSize
			SELECT TOP 30 a.ID, a.cpMainID, a.caMainID, a.Name as JobName, a.dcJobTypeID, 
				a.dcJobTypeIDMinor, a.NeedNumber, a.dcSalaryID, a.dcSalaryIDMax, a.EmployType, 
				a.dcRegionID, a.Responsibility, a.Demand, a.dcEducationID, b.HasLicence, b.IsRefreshed, dcCompanySizeID,
				a.MinExperience, a.MinAge, a.MaxAge, a.IssueDate, a.IssueEND, 
				a.IsDelete, a.AddDate, a.RefreshDate, a.Lng, a.Lat,
				a.LastModifyDate, b.Name as cpName, b.dcCompanySizeID, 
				b.UnLimitedDate, b.BalanceDate, b.Balance, 
				b.MemberType, '' cpIndustry,
				c.IsTop, b.IsRefreshed, a.SecondId EnJobID, b.SecondId EnCpMainID,a.Welfare1,a.Welfare2,
				a.Welfare3, a.Welfare4,a.Welfare5,a.Welfare6,a.Welfare7,a.Welfare8, a.Welfare9,a.Welfare10,
				a.Welfare11,a.Welfare12,a.Welfare13, a.Welfare14,a.Welfare15,a.Welfare16,a.Welfare17,a.Welfare18,
				ISNULL((SELECT IsOnline FROM caOnline WITH(NOLOCK) WHERE caMainId = a.caMainId), 0) IsOnline, 
				b.LogoFile LogoUrl,@AllJobCount JobNumber,
				d.FullName RegionName,e.Description EducationName,f.Description ExperienceName,g.DescriptionCp dcSalary,h.DescriptionCp dcSalaryMax
			FROM JobPublish a WITH(NOLOCK), cpMainPublish b WITH(NOLOCK), SearchDB..paSearchJobID_3 c WITH(NOLOCK),
			dcRegion d WITH(NOLOCK),dcEducation e WITH(NOLOCK),dcOthers f WITH(NOLOCK),dcSalary g WITH(NOLOCK),dcSalary h WITH(NOLOCK)
			WHERE a.cpMainID = b.ID AND a.id=c.JobID AND c.paSearchConditionID=@paSearchConditionID 
			AND d.ID = a.dcRegionID AND e.ID = a.dcEducationID AND f.DetailID = a.MinExperience 
			AND f.Category='职位要求工作经验' AND g.ID = a.dcSalaryID AND h.ID = a.dcSalaryIDMax
		    AND c.ID>=@MinId ORDER BY c.ID, a.ID DESC
		END
        --RICHARD 2011-7-23 16:51分修改
		----返回统计数量
		IF @Type=1
		BEGIN
			IF (@TableID = 0)
			BEGIN
				SELECT a.*,b.Description FROM SearchDB..paSearchCount_0 a WITH(NOLOCK) LEFT JOIN dcJobType b ON b.ID = a.TitleID WHERE Title = 'JobType' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(VARCHAR(10), TitleID)
				SELECT a.*,b.Description FROM SearchDB..paSearchCount_0 a WITH(NOLOCK) LEFT JOIN dcRegion b ON b.ID = a.TitleID WHERE Title = 'Region' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(VARCHAR(10), TitleID)
				SELECT a.*,b.Description FROM SearchDB..paSearchCount_0 a WITH(NOLOCK) LEFT JOIN dcEducation b ON b.ID = a.TitleID WHERE Title = 'Education' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT a.*,b.Description FROM SearchDB..paSearchCount_0 a WITH(NOLOCK) LEFT JOIN dcOthers b ON b.DetailID = a.TitleID AND Category='职位要求工作经验' WHERE Title = 'Experience' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT * FROM SearchDB..paSearchCount_0 a WITH(NOLOCK) WHERE Title = 'Salary' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT a.*,b.Description FROM SearchDB..paSearchCount_0 a WITH(NOLOCK) LEFT JOIN dcOthers b ON b.DetailID = a.TitleID AND Category='工作性质' WHERE Title = 'EmployType' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT a.*,b.Description FROM SearchDB..paSearchCount_0 a WITH(NOLOCK) LEFT JOIN dcCompanySize b ON b.ID = a.TitleID WHERE Title = 'CompanySize' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
			END
			IF (@TableID = 1)
			BEGIN
				SELECT a.*,b.Description FROM SearchDB..paSearchCount_1 a WITH(NOLOCK) LEFT JOIN dcJobType b ON b.ID = a.TitleID WHERE Title = 'JobType' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(VARCHAR(10), TitleID)
				SELECT a.*,b.Description FROM SearchDB..paSearchCount_1 a WITH(NOLOCK) LEFT JOIN dcRegion b ON b.ID = a.TitleID WHERE Title = 'Region' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(VARCHAR(10), TitleID)
				SELECT a.*,b.Description FROM SearchDB..paSearchCount_1 a WITH(NOLOCK) LEFT JOIN dcEducation b ON b.ID = a.TitleID WHERE Title = 'Education' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT a.*,b.Description FROM SearchDB..paSearchCount_1 a WITH(NOLOCK) LEFT JOIN dcOthers b ON b.DetailID = a.TitleID AND Category='职位要求工作经验' WHERE Title = 'Experience' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT * FROM SearchDB..paSearchCount_1 a WITH(NOLOCK) WHERE Title = 'Salary' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT a.*,b.Description FROM SearchDB..paSearchCount_1 a WITH(NOLOCK) LEFT JOIN dcOthers b ON b.DetailID = a.TitleID AND Category='工作性质' WHERE Title = 'EmployType' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT a.*,b.Description FROM SearchDB..paSearchCount_1 a WITH(NOLOCK) LEFT JOIN dcCompanySize b ON b.ID = a.TitleID WHERE Title = 'CompanySize' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
			END
			IF (@TableID = 2)
			BEGIN
				SELECT a.*,b.Description FROM SearchDB..paSearchCount_2 a WITH(NOLOCK) LEFT JOIN dcJobType b ON b.ID = a.TitleID WHERE Title = 'JobType' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(VARCHAR(10), TitleID)
				SELECT a.*,b.Description FROM SearchDB..paSearchCount_2 a WITH(NOLOCK) LEFT JOIN dcRegion b ON b.ID = a.TitleID WHERE Title = 'Region' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(VARCHAR(10), TitleID)
				SELECT a.*,b.Description FROM SearchDB..paSearchCount_2 a WITH(NOLOCK) LEFT JOIN dcEducation b ON b.ID = a.TitleID WHERE Title = 'Education' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT a.*,b.Description FROM SearchDB..paSearchCount_2 a WITH(NOLOCK) LEFT JOIN dcOthers b ON b.DetailID = a.TitleID AND Category='职位要求工作经验' WHERE Title = 'Experience' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT * FROM SearchDB..paSearchCount_2 a WITH(NOLOCK) WHERE Title = 'Salary' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT a.*,b.Description FROM SearchDB..paSearchCount_2 a WITH(NOLOCK) LEFT JOIN dcOthers b ON b.DetailID = a.TitleID AND Category='工作性质' WHERE Title = 'EmployType' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT a.*,b.Description FROM SearchDB..paSearchCount_2 a WITH(NOLOCK) LEFT JOIN dcCompanySize b ON b.ID = a.TitleID WHERE Title = 'CompanySize' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
			END
			IF (@TableID = 3)
			BEGIN
				SELECT a.*,b.Description FROM SearchDB..paSearchCount_3 a WITH(NOLOCK) LEFT JOIN dcJobType b ON b.ID = a.TitleID WHERE Title = 'JobType' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(VARCHAR(10), TitleID)
				SELECT a.*,b.Description FROM SearchDB..paSearchCount_3 a WITH(NOLOCK) LEFT JOIN dcRegion b ON b.ID = a.TitleID WHERE Title = 'Region' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(VARCHAR(10), TitleID)
				SELECT a.*,b.Description FROM SearchDB..paSearchCount_3 a WITH(NOLOCK) LEFT JOIN dcEducation b ON b.ID = a.TitleID WHERE Title = 'Education' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT a.*,b.Description FROM SearchDB..paSearchCount_3 a WITH(NOLOCK) LEFT JOIN dcOthers b ON b.DetailID = a.TitleID AND Category='职位要求工作经验' WHERE Title = 'Experience' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT * FROM SearchDB..paSearchCount_3 a WITH(NOLOCK) WHERE Title = 'Salary' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT a.*,b.Description FROM SearchDB..paSearchCount_3 a WITH(NOLOCK) LEFT JOIN dcOthers b ON b.DetailID = a.TitleID AND Category='工作性质' WHERE Title = 'EmployType' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT a.*,b.Description FROM SearchDB..paSearchCount_3 a WITH(NOLOCK) LEFT JOIN dcCompanySize b ON b.ID = a.TitleID WHERE Title = 'CompanySize' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
			END
		END
		RETURN
	END
END TRY
BEGIN CATCH
	---检查是否已经建立临时表，已经建立则删除
	ROLLBACK TRANSACTION
	---检查是否已经建立临时表，已经建立则删除
	DECLARE @para VARCHAR(MAX)
	SET @para = '@dcJobTypeID=' + ISNULL(@dcJobTypeID, '') + '|' +
		'@dcIndustryID=' + ISNULL(@dcIndustryID, '') + '|' +
		'@EmployType=' + ISNULL(@EmployType, '') + '|' +
		'@Welfare=' + ISNULL(@Welfare, '')
	INSERT INTO ErrorLog	
	SELECT 'm3 ' + ISNULL(error_Message(), ' no msg')+ ' para=' + ISNULL(@Para, 'no para ') + ISNULL(@SQL, ' no sql'), error_number(), error_line(), GETDATE()
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[mblJobBySearchCount]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[mblJobBySearchCount] 
(
	@dcJobTypeID INT, 		--职位类别
	@dcRegionID INT, 		--求职地区
	@dcIndustryID INT		--求职行业
)
AS
BEGIN
	DECLARE @COUNT INT, @ALLCOUNT INT
	IF @dcIndustryID > 0
		SELECT @COUNT = COUNT(*) FROM Job a WITH(NOLOCK) 
			INNER JOIN cpMain b ON a.cpMainID=b.ID
			INNER JOIN cpIndustry d WITH(NOLOCK) ON d.cpMainID=b.ID AND d.dcIndustryID=@dcIndustryID
		WHERE (dcJobTypeID=@dcJobTypeID OR dcJobTypeIDMinor=@dcJobTypeID)
			AND LEFT(a.dcRegionID,4)=@dcRegionID AND a.Valid=1
	ELSE
		SELECT @COUNT=COUNT(*) FROM Job WITH(NOLOCK) 
		WHERE (dcJobTypeID=@dcJobTypeID OR dcJobTypeIDMinor=@dcJobTypeID)
		AND LEFT(dcRegionID,4) = @dcRegionID 
		AND Valid=1
	
	RETURN @Count
END

set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON














GO
/****** Object:  StoredProcedure [dbo].[mblJobBySearchSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE proCEDURE [dbo].[mblJobBySearchSelect]
(
	@dcJobTypeID VARCHAR(100), 		--职位类别
	@dcRegionID VARCHAR(100), 		--求职地区
	@dcIndustryID VARCHAR(100), 	--求职行业
	@dcSalaryID TINYINT, 			--月薪
	@IsNegotiable BIT, 				--1允许面议，不面议
	@MinExperience TINYINT, 		--工作经验，100为未选择
	@dcEducationID TINYINT, 		--最低学历
	@EmployType VARCHAR(10), 		--工作性质，1全职；3兼职；4实习，
	@KeyWord NVARCHAR(50), 			--关键词
	@KeyType TINYINT, 				--搜索类别，0无；1-全文；2-职位；3-公司 
	@ORDER VARCHAR(4), 				--显示顺序，没有用
	@RefreshNo INT, 				--1, 1天内；2, 3天内；3，一周内；4，15天内；5，一个月内；6超过一个月
	@Type INT, 						--1：主动搜索  点击搜索按钮 10分钟，翻页60分钟有效；0：翻页搜索，不刷新
	@PageNumber INT, 				--翻页页码
	@SessionID varchar(50),					--10
	@CompanySizeID VARCHAR(1), 		--企业规模
	@IsOnline INT,
	@Welfare VARCHAR(50)					--
)
AS
--return   @SessionId = 10
SET NOCOUNT ON
INSERT INTO SearchIp(Ip, Source) SELECT @SessionId, 'm'
IF EXISTS(SELECT 'x' FROM RefuseIp WITH(NOLOCK) WHERE CHARINDEX(Ip,@SessionId) > 0)
	RETURN
INSERT INTO SearchDB..paSearchLog(ProcType, SessionID, LogTime, JobType, JobPlace, Industry, Education, Experience, 
	Salary, IsNegotiable, EmployType, CompanySizeID, KeyWord, KeyType, ReuseNumber, Welfare, IsOnline, RefreshNo)
VALUES('pcJobBySearchSelect', @SessionId, GETDATE(), @dcJobTypeID, @dcRegionID, @dcIndustryID, @dcEducationID, @MinExperience, 
	@dcSalaryID, 0, @EmployType, @CompanySizeID, @KeyWord, @KeyType, 0, @Welfare, @IsOnline, @RefreshNo)

SET @SessionId = 'b' + @SessionId
SET @KeyType = 0
BEGIN TRY
	DECLARE @ReuseNumber AS INT, @dcProvinceId VARCHAR(2), @Order2 VARCHAR(100)
	----给null值变量赋默认值
	IF NOT LEFT(@dcRegionID,1) = 'p'
		SELECT @dcRegionID = RTRIM(dbo.FormatIDS(@dcRegionID))

	SELECT @dcJobTypeID = RTRIM(dbo.FormatIDS(@dcJobTypeID)),
		@dcIndustryID = RTRIM(dbo.FormatIDS(@dcIndustryID)),
		@dcSalaryID = ISNULL(@dcSalaryID, 0),
		@IsNegotiable = ISNULL(@IsNegotiable, 0),
		@MinExperience = ISNULL(@MinExperience, 100),
		@dcEducationID = ISNULL(@dcEducationID, 0),
		@EmployType = CASE @EmployType WHEN '2' THEN '1,3' ELSE ISNULL(@EmployType, '') END,
		@CompanySizeID = ISNULL(@CompanySizeID, '0'),
		@KeyWord = dbo.SafeSQL(ISNULL(@KeyWord, '')),
		@ORDER = ISNULL(@Order, ''),
		@Type = ISNULL(@Type, 0),
		@PageNumber = ISNULL(@PageNumber, 0),
		@Welfare = RTRIM(dbo.FormatIDS(@Welfare)),
		@IsOnline = ISNULL(@IsOnline, 0),
		@Order2 = ' ORDER BY a.RefreshDate DESC, a.SecondID DESC'

	IF @dcSalaryID = 0
		SET @IsNegotiable = 0

	IF @Order LIKE 'p=%'
		SET @dcProvinceId = REPLACE(@Order, 'p=', '')
	ELSE
		SET @dcProvinceId = 0

	--@RefreshNo = 0选择全部数据，不限制时间
	SET @RefreshNo = 0
	IF(@KeyWord = '' AND ISNULL(@dcJobTypeID, '') = '' AND ISNULL(@dcRegionID, '') = '' AND ISNULL(@dcIndustryID, '') = '')
		RETURN

	--如果关键词不为空 查询关键词对应的搜索类型 max 2012-12-25 
	
	IF RIGHT(@KeyWord, 2) = '公司'
		SET @KeyWord = LEFT(@KeyWord, LEN(@KeyWord) - 2)
		
	IF RIGHT(@dcJobTypeID, 1) = ','
		SET @dcJobTypeID = LEFT(@dcJobTypeID, LEN(@dcJobTypeID) - 1)
	IF RIGHT(@dcRegionID, 1) = ','
		SET @dcRegionID = LEFT(@dcRegionID, LEN(@dcRegionID) - 1)
	IF RIGHT(@dcIndustryID, 1) = ','
		SET @dcIndustryID = LEFT(@dcIndustryID, LEN(@dcIndustryID) - 1)

	DECLARE @paSearchConditionID AS INT, 
		@MinId AS INT, 
		@PageSize AS TINYINT, 
		@TableID AS TINYINT

	SELECT @paSearchConditionID = 0, @PageSize = 30	

	----搜索1分钟前的数据
	SELECT TOP 1 @paSearchConditionID = ID,
		@ReuseNumber = ReuseNumber
	FROM SearchDB..paSearchCondition WITH(NOLOCK)
	WHERE JobType=@dcJobTypeID AND IsOnline = @IsOnline
	AND JobPlace=@dcRegionID AND Industry=@dcIndustryID AND Education=@dcEducationID
	AND Experience=@MinExperience AND Salary=@dcSalaryID AND IsNegotiable=@IsNegotiable 
	AND EmployType=@EmployType AND ISNULL(KeyWord, '') = @KeyWord AND KeyType = @KeyType
	AND CompanySizeID = @CompanySizeID AND Welfare = @Welfare AND IsDelete = 0
	AND LogTime > DATEADD(MINUTE, -1, GETDATE()) AND ReuseNumber > 0
	AND RefreshNo = 0 AND ISNULL(dcProvinceId, 0) = @dcProvinceId
	ORDER BY ID DESC

	IF @ReuseNumber = 0
	BEGIN
		SELECT TOP 1 @paSearchConditionID = ID
		FROM SearchDB..paSearchCondition WITH(NOLOCK)
		WHERE JobType=@dcJobTypeID AND IsOnline = @IsOnline
		AND JobPlace=@dcRegionID AND Industry=@dcIndustryID AND Education=@dcEducationID
		AND Experience=@MinExperience AND Salary=@dcSalaryID AND IsNegotiable=@IsNegotiable 
		AND EmployType=@EmployType AND ISNULL(KeyWord, '') = @KeyWord AND KeyType=@KeyType
		AND CompanySizeID = @CompanySizeID AND Welfare = @Welfare AND ReuseNumber > 0
		AND ReuseNumber > 0 AND LogTime > DATEADD(MINUTE, -2, GETDATE()) 
		AND RefreshNo = 0 AND ISNULL(dcProvinceId, 0) = @dcProvinceId
		ORDER BY ID DESC
	END

	IF ISNULL(@paSearchConditionID, 0) = 0
	BEGIN
		SET @Type =1
		GOTO SelectReset	--无数据，重新搜索
	END
	ELSE
	BEGIN
		SELECT @TableID = @paSearchConditionID % 4
		GOTO GetRecordSet	--从临时结果中提取数据
	END

SelectReset:
	--从job中搜索数据
	BEGIN TRAN
		DECLARE @SQL AS VARCHAR(8000)
		DECLARE @WHERE AS VARCHAR(8000)
		DECLARE @FROM AS VARCHAR(1000)
		----记录查询条件
		INSERT INTO SearchDB..paSearchCondition(SessionID, LogTime, JobType, JobPlace, Industry, Education, Experience, 
			Salary, IsNegotiable, EmployType, CompanySizeID, KeyWord, KeyType, ReuseNumber, Welfare, IsOnline, dcProvinceId)
		VALUES(@SessionId, GETDATE(), @dcJobTypeID, @dcRegionID, @dcIndustryID, @dcEducationID, @MinExperience, 
			@dcSalaryID, @IsNegotiable, @EmployType, @CompanySizeID, @KeyWord, @KeyType, 0, @Welfare, @IsOnline, @dcProvinceId)
		SET @paSearchConditionID = @@IDENTITY
		SELECT @TableID = @paSearchConditionID % 4

		------生成职位类别的表变量，因为职位类别有包含（父子）关系
		DECLARE @T_JobPlace AS TABLE(ID INT)
		DECLARE @T_JobType AS TABLE(ID INT)
		DECLARE @JobPlaceLen AS INT, @JobTypeLen AS INT
		IF CHARINDEX(',', @dcJobTypeID) > 0
			SET @JobTypeLen = -1
		ELSE
			SET @JobTypeLen = LEN(@dcJobTypeID)

		DECLARE @JobType AS VARCHAR(3000), @JobPlace AS VARCHAR(2000), @ValidJobNumber AS INT

		SELECT @JobPlace = '', @JobType=''
		----生成工作地点的表变量
		IF LEN(@dcRegionID) > 0
		BEGIN
			IF LEFT(@dcRegionID,1) = 'p'
			BEGIN
				DECLARE @Degree AS DECIMAL(8,5),@LBLng AS DECIMAL(8,5),@LBLat AS DECIMAL(8,5),
				@RTLng AS DECIMAL(8,5),@RTLat AS DECIMAL(8,5),@Lat AS DECIMAL(8,5),@Lng AS DECIMAL(8,5)
				
				SELECT @Lat = Lat,@Lng = Lng FROM dcMapPlace WITH(NOLOCK) WHERE ID = RIGHT(@dcRegionID,LEN(@dcRegionID)-1)
				IF @dcRegionID LIKE '3201%'
					SET @Degree = 1000 / 100000.0
				ELSE
					SET @Degree = 2000 / 100000.0

				SET @LBLng = @Lng - @Degree
				SET @LBLat = @Lat - @Degree
				SET @RTLng = @Lng + @Degree
				SET @RTLat = @Lat + @Degree
				SET @JobPlace = 'a.Lng BETWEEN ' + CONVERT(VARCHAR,@LBLng) + ' AND ' + CONVERT(VARCHAR,@RTLng) + '
					AND a.Lat BETWEEN ' + CONVERT(VARCHAR,@LBLat) + ' AND ' + CONVERT(VARCHAR,@RTLat) + '
					AND (a.Lng-' + CONVERT(VARCHAR,@Lng) + ')*(a.Lng-' + CONVERT(VARCHAR,@Lng) + ')+
					(a.Lat-' + CONVERT(VARCHAR,@Lat) + ')*(a.Lat-' + CONVERT(VARCHAR,@Lat) + ')<' + CONVERT(VARCHAR,@Degree*@Degree)
				SELECT @JobPlaceLen = 8
			END
			ELSE
			BEGIN
				INSERT INTO @T_JobPlace
				SELECT * FROM dbo.fnSplit(@dcRegionID, ',')
				SELECT @JobPlace = (@JobPlace + ' OR a.dcRegionID Like ''' + LTRIM(STR(ID) + '%''')) FROM @T_JobPlace
				IF LEN(@JobPlace) > 0
					SET @JobPlace = RIGHT(@JobPlace, LEN(@JobPlace) -4)
				IF (SELECT COUNT(*) FROM @T_JobPlace) > 1
					SET @JobPlaceLen = -1
				ELSE
					SET @JobPlaceLen = LEN(@dcRegionID)
			END
		END
		ELSE 
			SELECT @JobPlaceLen = 0


		----生成求聘职位的表变量
		IF LEN(@dcJobTypeID) > 0
		BEGIN
			DECLARE @T_Temp AS TABLE(ID INT)		--临时表，用于构建组合查询语句
			INSERT INTO @T_Temp
			SELECT * FROM dbo.fnSplit(@dcJobTypeID, ',')

			INSERT INTO @T_JobType
			SELECT DISTINCT ID FROM dcJobType WITH(NOLOCK)
			WHERE ParentId IN(SELECT ID FROM @T_TEMP) 
			OR ParentId2 in(SELECT ID FROM @T_TEMP)
			OR ID IN(SELECT ID FROM @T_TEMP)
			----生成in字符串
			SELECT @JobType = (@JobType + LTRIM(STR(ID) + ',')) FROM @T_JobType
			IF RIGHT(@JobType, 1) = ','
				SET @JobType = LEFT(@JobType, LEN(@JobType) - 1)
		END

		----建立临时表
		CREATE TABLE #Job(
			RowID INT IDENTITY(1, 1), 
			ID INT NOT NULL,
			cpMainId INT,
			dcJobTypeID SMALLINT NOT NULL, 
			dcJobTypeIDMinor SMALLINT NULL, 
			dcSalaryID TINYINT NOT NULL, 
			dcRegionID VARCHAR(6) NULL, 
			dcEducationID TINYINT NOT NULL, 
			MinExperience TINYINT NOT NULL, 
			RefreshDate SMALLDATETIME NULL,
			EmployType TINYINT NULL,
			dcCompanySizeID SMALLINT NULL
		)

		CREATE TABLE #FullText(
			Priority INT,
			JobId INT NOT NULL
		)

		------刷新时间，根据刷新时间编号计算
		----生成插入临时表的Sql语句
		SET @SQL='
			INSERT INTO #Job
			SELECT a.ID, a.cpMainId, a.dcJobTypeID, 
				a.dcJobTypeIDMinor, a.dcSalaryID, 
				a.dcRegionID, a.dcEducationID, a.MinExperience, 
				a.IssueDate,a.EmployType,b.dcCompanySizeID'
		SET @FROM = '
			FROM JobPublish a WITH(NOLOCK)
			INNER JOIN cpMainPublish b WITH(NOLOCK) ON a.cpMainID=b.ID'
		----职位有效，单位新有效
		IF LEN(@dcIndustryID) > 0
			SET @WHERE = '
			WHERE b.ID IN (SELECT cpMainID FROM cpIndustry WHERE dcIndustryId in(' + @dcIndustryID + '))
			AND a.Valid = 1
			AND b.Valid = 1'
		ELSE
			SET @WHERE = '
			WHERE a.Valid = 1
			AND b.Valid = 1'
		
		IF LEN(@dcProvinceId) > 1
			SET @WHere = @Where + ' AND b.dcProvinceId = ' + @dcProvinceId

		----职位类别
		IF LEN(@JobType) > 0
			SET @WHERE = @WHERE + '
			AND (a.dcJobTypeID IN(' + @JobType +')
				OR a.dcJobTypeIDMinor IN(' +@JobType + '))'
		IF LEN(@JobPlace) > 0 
			SET @WHERE = @WHERE + '
			AND (' + @JobPlace + ')'

		IF @dcSalaryID > 0
		BEGIN
			IF @dcSalaryID < 100				----从form中搜索，月薪跨2个级别, 是本级和上级别的薪金
				SET @WHERE = @WHERE + '
			AND a.dcSalaryID IN(' + LTRIM(STR(@dcSalaryID)) + ',' + LTRIM(STR(@dcSalaryID + 1)) + ')'
			ELSE IF @dcSalaryID = 100	----从筛选结果中点击面议，值是100
				SET @WHERE = @WHERE + '
			AND a.dcSalaryID = 100'
			ELSE IF @dcSalaryID BETWEEN 101 AND 106	----从筛选结果中点击搜索，月薪只有1个级别，传值时增加100
				SET @WHERE = @WHERE + '
			AND a.dcSalaryID <= ' + LTRIM(STR(@dcSalaryID-99)) + ' AND a.dcSalaryIDMax > ' + LTRIM(STR(@dcSalaryID-100))
			ELSE IF @dcSalaryID BETWEEN 107 AND 113	----从筛选结果中点击搜索，月薪只有1个级别，传值时增加100
				SET @WHERE = @WHERE + '
			AND a.dcSalaryID <= ' + LTRIM(STR(@dcSalaryID - 100)) + ' AND a.dcSalaryIDMax > ' + LTRIM(STR(@dcSalaryID-100))
			ELSE IF @dcSalaryID BETWEEN 114 AND 120
				SET @WHERE = @WHERE + '
			AND a.dcSalaryID  < 100 AND a.dcSalaryIDMax > ' + LTRIM(STR(@dcSalaryID - 100))
		END
		----工作经验要求
		IF @MinExperience < 100
		SET @WHERE = @WHERE + ' 
			AND a.MinExperience = ' + LTRIM(STR(@MinExperience))

		----学历要求
		----'1初中', '2\3\4高中、中技、中专', '5大专', '6本科', '7硕士', '8博士
		IF @dcEducationID > 0
			IF @dcEducationID = 2
				SET @WHERE = @WHERE + '
			AND a.dcEducationID IN(2, 3, 4)'
			ELSE
				SET @WHERE = @WHERE + '
			AND a.dcEducationID = ' + LTRIM(STR(@dcEducationID))
		----1、全职；3、兼职；4实习。	2、全职/兼职 职位中无此项
		IF LEN(@EmployType) > 0
			SET @WHERE = @WHERE + '
			AND a.EmployType IN (' + @EmployType + ')'

		IF @CompanySizeID BETWEEN 1 AND 6
			SET @WHERE = @WHERE + '
			AND b.dcCompanySizeID = ' + LTRIM(STR(@CompanySizeID))

		IF LEN(@Welfare) > 0
			SET @WHERE = @WHERE + '
			AND a.Welfare' + REPLACE(@Welfare, ',', ' = 1 AND a.Welfare') + ' = 1'

		IF @IsOnline = 1
			SET @WHERE = @WHERE + '
			AND a.caMainId IN(SELECT caMainId FROM caOnline WITH(NOLOCK) WHERE IsOnline = 1)'

		IF LEN(@KeyWord) > 0  ----使用全文搜索job和cpmain2个表，经过测试发现union最快
		BEGIN
			IF EXISTS(SELECT TOP 1 'x' FROM cpMainPublish WITH(NOLOCK) WHERE Name = @KeyWord)
			BEGIN
				SET @WHERE = @WHERE + '
			AND b.Name = ''' + @KeyWord + ''''
				SET @SQL = @SQL + @FROM + @WHERE
			END
			ELSE
			BEGIN
				DECLARE @KeyWordTemp NVARCHAR(50)
				SET @KeyWordTemp = REPLACE(@KeyWord, ' ', '%')
				IF LEN(@KeyWordTemp) > 1
				BEGIN
					IF @dcProvinceId > 0
					BEGIN
						INSERT #FullText
						SELECT TOP 2000 2, b.ID
						FROM cpMainPublish a WITH(NOLOCK),
							JobPublish b WITH(NOLOCK)
						WHERE a.Id = b.cpMainId
						AND a.Name LIKE '%' + @KeyWordTemp + '%'
						AND a.dcProvinceId = @dcprovinceId
						ORDER BY b.RefreshDate DESC

						INSERT #FullText
						SELECT TOP 2000 1, b.ID
						FROM cpMainPublish a WITH(NOLOCK),
							JobPublish b WITH(NOLOCK)
						WHERE a.Id = b.cpMainId
						AND b.Name LIKE '%' + @KeyWordTemp + '%'
						AND a.dcProvinceId = @dcprovinceId
						ORDER BY b.RefreshDate DESC
					END
					ELSE
					BEGIN
						INSERT #FullText
						SELECT TOP 2000 2, b.ID
						FROM cpMainPublish a WITH(NOLOCK),
							JobPublish b WITH(NOLOCK)
						WHERE a.Id = b.cpMainId
						AND a.Name LIKE '%' + @KeyWordTemp + '%'
						ORDER BY b.RefreshDate DESC

						INSERT #FullText
						SELECT TOP 2000 1, b.ID
						FROM cpMainPublish a WITH(NOLOCK),
							JobPublish b WITH(NOLOCK)
						WHERE a.Id = b.cpMainId
						AND b.Name LIKE '%' + @KeyWordTemp + '%'
						ORDER BY b.RefreshDate DESC
					END
				END
				IF (SELECT COUNT(*) FROM #FullText) < 800
				BEGIN
					INSERT #FullText
					SELECT TOP 5000 3, [Key]
					FROM FREETEXTTABLE(cpMainJob, *, @KeyWord, 100000) AS KeyJob ORDER BY RANK DESC
				END
				DELETE a FROM #FullText a, #FullText b WHERE a.JobId = b.JobId AND a.Priority > b.Priority
				--------------------
				SELECT @FROM = @FROM + '
			INNER JOIN #FullText ON a.ID = #FullText.JobId',
					@ORDER2 = ' ORDER BY #FullText.Priority, a.RefreshDate DESC, a.SecondID DESC'
				SET @SQL = @SQL + @FROM + @WHERE
			END
		END
		ELSE
			SELECT @SQL = @SQL + @FROM + @WHERE
		
		SET @SQL = @SQL + @Order2
		--原来是ORDER BY a.IssueDate DESC, a.ID，Richard 2011年11月23日17：06分修改

		----把符合条件的职位全部列出
		--PRINT @SQL
		EXEC(@SQL)
		SET @ValidJobNumber = @@ROWCOUNT
		----记录查询结果总数
		UPDATE SearchDB..paSearchCondition SET ValidJobNumber=@ValidJobNumber, SQl=@SQL WHERE ID=@paSearchConditionID
		IF LEN(@JobType) > 0	--IN(2, 4)
			UPDATE #Job SET dcJobTypeId = dcJobTypeIDMinor
			WHERE dcJobTypeID NOT IN(SELECT a FROM dbo.fnSplit(@JobType, ','))

		----插入JobType数据
		DECLARE @TitleValue AS INT, @TopRows AS INT, @AllRows AS INT
		DECLARE @sc AS TABLE (
			paSearchConditionID int,
			Title varchar(20),
			TitleID varchar(10),
			TitleValue int
		)
		DECLARE @sc2 AS TABLE (
			paSearchConditionID int,
			Title varchar(20),
			TitleID varchar(10),
			TitleValue int
		)

		IF (@TableID = 0)
		BEGIN
			INSERT INTO @sc2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'JobType', dcJobTypeID, COUNT(*)
			FROM #Job WITH(NOLOCK)
			GROUP BY dcJobTypeID ORDER BY dcJobTypeID			

			----计算全部某职位类别，2, 4位的数据
			IF @JobTypeLen NOT IN(2, 4)
			BEGIN
				INSERT INTO @Sc(paSearchConditionID, Title, TitleId, TitleValue)
				SELECT  @paSearchConditionID, 'JobType', LEFT(TitleID, 2) TitleID, SUM(TitleValue) TitleValue 
				FROM @sc2 GROUP BY LEFT(TitleID, 2)
			END
			IF @JobTypeLen NOT IN(0, 4)
			BEGIN
				INSERT INTO @Sc(paSearchConditionID, Title, TitleId, TitleValue)
				SELECT  @paSearchConditionID, 'JobType', TitleId, TitleValue
				FROM @sc2 WHERE LEN(TitleId) = 4
			END

			IF @JobTypeLen = -1
				DELETE @sc WHERE TitleID NOT IN(SELECT a FROM dbo.fnSplit(@dcJobTypeID, ','))

			INSERT INTO SearchDB..paSearchCount_0(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT  @paSearchConditionID, 'JobType', TitleId, TitleValue FROM @sc
			DELETE @sc
			DELETE @sc2
			--------
			INSERT INTO @sc2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Region', dcRegionID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcRegionID ORDER BY dcRegionID
			----计算全部地区，2位的数据
			IF @JobPlaceLen IN(-1, 0)
				INSERT INTO @sc(paSearchConditionID, Title, TitleId, TitleValue)
				SELECT @paSearchConditionID, 'Region', LEFT(TitleID, 2) TitleID, SUM(TitleValue) TitleValue 
				FROM @sc2 GROUP BY LEFT(TitleID, 2)
			IF @JobPlaceLen IN(-1, 2)
				INSERT INTO @sc(paSearchConditionID, Title, TitleId, TitleValue)
				SELECT @paSearchConditionID, 'Region', LEFT(TitleID, 4) TitleID, SUM(TitleValue) TitleValue 
				FROM @sc2 WHERE LEN(TitleID) >= 4 GROUP BY LEFT(TitleID, 4)
			IF @JobPlaceLen IN(-1, 4)
				INSERT INTO @sc(paSearchConditionID, Title, TitleId, TitleValue)
				SELECT @paSearchConditionID, 'Region', TitleID, TitleValue 
				FROM @sc2 WHERE LEN(TitleID) = 6
			IF @JobPlaceLen = -1
				DELETE @sc WHERE TitleID NOT IN(SELECT ID FROM @T_JobPlace)
			ELSE
				DELETE @sc WHERE LEN(TitleID) <> @JobPlaceLen + 2

			INSERT INTO SearchDB..paSearchCount_0(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT paSearchConditionID, Title, TitleId, TitleValue FROM @sc
			----------------

			INSERT INTO SearchDB..paSearchCount_0(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'EmployType', EmployType, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY EmployType ORDER BY EmployType

			INSERT INTO SearchDB..paSearchCount_0(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Education', CASE WHEN dcEducationId IN(2, 3, 4) THEN 2 ELSE dcEducationId END, COUNT(*) 
			FROM #Job WITH(NOLOCK)
			GROUP BY CASE WHEN dcEducationId IN(2, 3, 4) THEN 2 ELSE dcEducationId END
			ORDER BY CASE WHEN dcEducationId IN(2, 3, 4) THEN 2 ELSE dcEducationId END

			INSERT INTO SearchDB..paSearchCount_0(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Experience', MinExperience, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY MinExperience ORDER BY MinExperience

			INSERT INTO SearchDB..paSearchCount_0(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'CompanySize', dcCompanySizeID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcCompanySizeID ORDER BY dcCompanySizeID

			INSERT INTO SearchDB..paSearchCount_0(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Salary', dcSalaryID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcSalaryID ORDER BY dcSalaryID

			INSERT INTO SearchDB..paSearchCount_0(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Industry', dcIndustryID, COUNT(*) 
			FROM #Job a WITH(NOLOCK), cpIndustry b WITH(NOLOCK)
			WHERE a.cpMainId = b.cpMainId
			GROUP BY b.dcIndustryId ORDER BY b.dcIndustryId

			IF EXISTS(SELECT TOP 1 'x' FROM #FullText)
				INSERT INTO SearchDB..paSearchJobID_0(paSearchConditionID, JobId, IsTop)
				SELECT TOP 10 @paSearchConditionID, a.JobId, 1 
				FROM SearchJobTop a WITH(NOLOCK), (SELECT ID FROM #Job WITH(NOLOCK) WHERE RowId < 2001) b 
				WHERE b.ID = a.JobId
				AND CHARINDEX(@KeyWord, a.JobName) > 0
				ORDER BY a.OrderType, a.OpenDate DESC
			ELSE
				INSERT INTO SearchDB..paSearchJobID_0(paSearchConditionID, JobId, IsTop)
				SELECT TOP 10 @paSearchConditionID, a.JobId, 1 
				FROM SearchJobTop a WITH(NOLOCK), (SELECT ID FROM #Job WITH(NOLOCK) WHERE RowId < 2001) b 
				WHERE b.ID = a.JobId
				ORDER BY a.OrderType, a.OpenDate DESC
			SET @TopRows = @@ROWCOUNT

			INSERT INTO SearchDB..paSearchJobID_0(paSearchConditionID, JobId, IsTop)
			SELECT TOP 2000 @paSearchConditionID, ID, 0 FROM #Job WITH(NOLOCK) ORDER BY RowID
			SET @AllRows = @@ROWCOUNT

			IF @TopRows = 0 AND @AllRows > 100
				UPDATE SearchDB..paSearchJobID_0 SET IsTop = 1 
				WHERE paSearchConditionID = @paSearchConditionID
				AND ID IN (SELECT TOP 3 ID FROM SearchDB..paSearchJobID_0 WITH(NOLOCK) WHERE paSearchConditionID = @paSearchConditionID ORDER BY ID)
		END
		ELSE IF (@TableId = 1)
		BEGIN
			----------------------------jobtype
			INSERT INTO @sc2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'JobType', dcJobTypeID, COUNT(*)
			FROM #Job WITH(NOLOCK)
			GROUP BY dcJobTypeID ORDER BY dcJobTypeID			

			----计算全部某职位类别，2, 4位的数据
			IF @JobTypeLen NOT IN(2, 4)
			BEGIN
				INSERT INTO @Sc(paSearchConditionID, Title, TitleId, TitleValue)
				SELECT  @paSearchConditionID, 'JobType', LEFT(TitleID, 2) TitleID, SUM(TitleValue) TitleValue 
				FROM @sc2 GROUP BY LEFT(TitleID, 2)
			END
			IF @JobTypeLen NOT IN(0, 4)
			BEGIN
				INSERT INTO @Sc(paSearchConditionID, Title, TitleId, TitleValue)
				SELECT  @paSearchConditionID, 'JobType', TitleId, TitleValue
				FROM @sc2 WHERE LEN(TitleId) = 4
			END

			IF @JobTypeLen = -1
				DELETE @sc WHERE TitleID NOT IN(SELECT a FROM dbo.fnSplit(@dcJobTypeID, ','))

			INSERT INTO SearchDB..paSearchCount_1(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT  @paSearchConditionID, 'JobType', TitleId, TitleValue FROM @sc
			DELETE @sc
			DELETE @sc2
			--------------------------region
			INSERT INTO @sc2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Region', dcRegionID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcRegionID ORDER BY dcRegionID
			----计算全部地区，2位的数据
			IF @JobPlaceLen IN(-1, 0)
				INSERT INTO @sc(paSearchConditionID, Title, TitleId, TitleValue)
				SELECT @paSearchConditionID, 'Region', LEFT(TitleID, 2) TitleID, SUM(TitleValue) TitleValue 
				FROM @sc2 GROUP BY LEFT(TitleID, 2)
			IF @JobPlaceLen IN(-1, 2)
				INSERT INTO @sc(paSearchConditionID, Title, TitleId, TitleValue)
				SELECT @paSearchConditionID, 'Region', LEFT(TitleID, 4) TitleID, SUM(TitleValue) TitleValue 
				FROM @sc2 WHERE LEN(TitleID) >= 4 GROUP BY LEFT(TitleID, 4)
			IF @JobPlaceLen IN(-1, 4)
				INSERT INTO @sc(paSearchConditionID, Title, TitleId, TitleValue)
				SELECT @paSearchConditionID, 'Region', TitleID, TitleValue 
				FROM @sc2 WHERE LEN(TitleID) = 6
			IF @JobPlaceLen = -1
				DELETE @sc WHERE TitleID NOT IN(SELECT ID FROM @T_JobPlace)
			ELSE
				DELETE @sc WHERE LEN(TitleID) <> @JobPlaceLen + 2

			INSERT INTO SearchDB..paSearchCount_1(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT paSearchConditionID, Title, TitleId, TitleValue FROM @sc
			----------------------------
			INSERT INTO SearchDB..paSearchCount_1(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Education', CASE WHEN dcEducationId IN(2, 3, 4) THEN 2 ELSE dcEducationId END, COUNT(*)
			FROM #Job WITH(NOLOCK)
			GROUP BY CASE WHEN dcEducationId IN(2, 3, 4) THEN 2 ELSE dcEducationId END
			ORDER BY CASE WHEN dcEducationId IN(2, 3, 4) THEN 2 ELSE dcEducationId END
			
			INSERT INTO SearchDB..paSearchCount_1(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Experience', MinExperience, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY MinExperience ORDER BY MinExperience
	
			INSERT INTO SearchDB..paSearchCount_1(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'EmployType', EmployType, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY EmployType ORDER BY EmployType

			INSERT INTO SearchDB..paSearchCount_1(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'CompanySize', dcCompanySizeID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcCompanySizeID ORDER BY dcCompanySizeID

			INSERT INTO SearchDB..paSearchCount_1(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Salary', dcSalaryID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcSalaryID ORDER BY dcSalaryID

			INSERT INTO SearchDB..paSearchCount_1(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Industry', dcIndustryID, COUNT(*) 
			FROM #Job a WITH(NOLOCK), cpIndustry b WITH(NOLOCK)
			WHERE a.cpMainId = b.cpMainId
			GROUP BY dcIndustryID ORDER BY dcIndustryID

			IF EXISTS(SELECT TOP 1 'x' FROM #FullText)
				INSERT INTO SearchDB..paSearchJobID_1(paSearchConditionID, JobId, IsTop)
				SELECT TOP 10 @paSearchConditionID, a.JobId, 1 
				FROM SearchJobTop a WITH(NOLOCK), (SELECT ID FROM #Job WITH(NOLOCK) WHERE RowId < 2001) b 
				WHERE b.ID = a.JobId
				AND CHARINDEX(@KeyWord, a.JobName) > 0
				ORDER BY a.OrderType, a.OpenDate DESC
			ELSE
				INSERT INTO SearchDB..paSearchJobID_1(paSearchConditionID, JobId, IsTop)
				SELECT TOP 10 @paSearchConditionID, a.JobId, 1 
				FROM SearchJobTop a WITH(NOLOCK), (SELECT ID FROM #Job WITH(NOLOCK) WHERE RowId < 2001) b 
				WHERE b.ID = a.JobId
				ORDER BY a.OrderType, a.OpenDate DESC
			SET @TopRows = @@ROWCOUNT

			INSERT INTO SearchDB..paSearchJobID_1(paSearchConditionID, JobId, IsTop)
			SELECT TOP 2000 @paSearchConditionID, ID, 0 FROM #Job WITH(NOLOCK) ORDER BY RowID
			SET @AllRows = @@ROWCOUNT

			IF @TopRows = 0 AND @AllRows > 100
				UPDATE SearchDB..paSearchJobID_1 SET IsTop = 1 
				WHERE paSearchConditionID = @paSearchConditionID
				AND ID IN (SELECT TOP 3 ID FROM SearchDB..paSearchJobID_1 WITH(NOLOCK) WHERE paSearchConditionID = @paSearchConditionID ORDER BY ID)
		END
		ELSE IF (@TableId = 2)
		BEGIN
			----------------------------jobtype
			INSERT INTO @sc2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'JobType', dcJobTypeID, COUNT(*)
			FROM #Job WITH(NOLOCK)
			GROUP BY dcJobTypeID ORDER BY dcJobTypeID			

			----计算全部某职位类别，2, 4位的数据
			IF @JobTypeLen NOT IN(2, 4)
			BEGIN
				INSERT INTO @Sc(paSearchConditionID, Title, TitleId, TitleValue)
				SELECT  @paSearchConditionID, 'JobType', LEFT(TitleID, 2) TitleID, SUM(TitleValue) TitleValue 
				FROM @sc2 GROUP BY LEFT(TitleID, 2)
			END
			IF @JobTypeLen NOT IN(0, 4)
			BEGIN
				INSERT INTO @Sc(paSearchConditionID, Title, TitleId, TitleValue)
				SELECT  @paSearchConditionID, 'JobType', TitleId, TitleValue
				FROM @sc2 WHERE LEN(TitleId) = 4
			END

			IF @JobTypeLen = -1
				DELETE @sc WHERE TitleID NOT IN(SELECT a FROM dbo.fnSplit(@dcJobTypeID, ','))

			INSERT INTO SearchDB..paSearchCount_2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT  @paSearchConditionID, 'JobType', TitleId, TitleValue FROM @sc
			DELETE @sc
			DELETE @sc2
			--------------------------region
			INSERT INTO @sc2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Region', dcRegionID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcRegionID ORDER BY dcRegionID
			----计算全部地区，2位的数据
			IF @JobPlaceLen IN(-1, 0)
				INSERT INTO @sc(paSearchConditionID, Title, TitleId, TitleValue)
				SELECT @paSearchConditionID, 'Region', LEFT(TitleID, 2) TitleID, SUM(TitleValue) TitleValue 
				FROM @sc2 GROUP BY LEFT(TitleID, 2)
			IF @JobPlaceLen IN(-1, 2)
				INSERT INTO @sc(paSearchConditionID, Title, TitleId, TitleValue)
				SELECT @paSearchConditionID, 'Region', LEFT(TitleID, 4) TitleID, SUM(TitleValue) TitleValue 
				FROM @sc2 WHERE LEN(TitleID) >= 4 GROUP BY LEFT(TitleID, 4)
			IF @JobPlaceLen IN(-1, 4)
				INSERT INTO @sc(paSearchConditionID, Title, TitleId, TitleValue)
				SELECT @paSearchConditionID, 'Region', TitleID, TitleValue 
				FROM @sc2 WHERE LEN(TitleID) = 6
			IF @JobPlaceLen = -1
				DELETE @sc WHERE TitleID NOT IN(SELECT ID FROM @T_JobPlace)
			ELSE
				DELETE @sc WHERE LEN(TitleID) <> @JobPlaceLen + 2

			INSERT INTO SearchDB..paSearchCount_2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT paSearchConditionID, Title, TitleId, TitleValue FROM @sc
			----------------------------
			INSERT INTO SearchDB..paSearchCount_2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Education', CASE WHEN dcEducationId IN(2, 3, 4) THEN 2 ELSE dcEducationId END, COUNT(*) 
			FROM #Job WITH(NOLOCK)
			GROUP BY CASE WHEN dcEducationId IN(2, 3, 4) THEN 2 ELSE dcEducationId END
			ORDER BY CASE WHEN dcEducationId IN(2, 3, 4) THEN 2 ELSE dcEducationId END
			
			INSERT INTO SearchDB..paSearchCount_2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Experience', MinExperience, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY MinExperience ORDER BY MinExperience

			INSERT INTO SearchDB..paSearchCount_2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Salary', dcSalaryID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcSalaryID ORDER BY dcSalaryID

			INSERT INTO SearchDB..paSearchCount_2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'EmployType', EmployType, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY EmployType ORDER BY EmployType

			INSERT INTO SearchDB..paSearchCount_2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'CompanySize', dcCompanySizeID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcCompanySizeID ORDER BY dcCompanySizeID

			INSERT INTO SearchDB..paSearchCount_2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Industry', dcIndustryID, COUNT(*) 
			FROM #Job a WITH(NOLOCK), cpIndustry b WITH(NOLOCK)
			WHERE a.cpMainId = b.cpMainId
			GROUP BY dcIndustryID ORDER BY dcIndustryID

			IF EXISTS(SELECT TOP 1 'x' FROM #FullText)
				INSERT INTO SearchDB..paSearchJobID_2(paSearchConditionID, JobId, IsTop)
				SELECT TOP 10 @paSearchConditionID, a.JobId, 1 
				FROM SearchJobTop a WITH(NOLOCK), (SELECT ID FROM #Job WITH(NOLOCK) WHERE RowId < 2001) b 
				WHERE b.ID = a.JobId
				AND CHARINDEX(@KeyWord, a.JobName) > 0
				ORDER BY a.OrderType, a.OpenDate DESC
			ELSE
				INSERT INTO SearchDB..paSearchJobID_2(paSearchConditionID, JobId, IsTop)
				SELECT TOP 10 @paSearchConditionID, a.JobId, 1 
				FROM SearchJobTop a WITH(NOLOCK), (SELECT ID FROM #Job WITH(NOLOCK) WHERE RowId < 2001) b 
				WHERE b.ID = a.JobId
				ORDER BY a.OrderType, a.OpenDate DESC
			SET @TopRows = @@ROWCOUNT

			INSERT INTO SearchDB..paSearchJobID_2(paSearchConditionID, JobId, IsTop)
			SELECT TOP 2000 @paSearchConditionID, ID, 0 FROM #Job WITH(NOLOCK) ORDER BY RowID
			SET @AllRows = @@ROWCOUNT

			IF @TopRows = 0 AND @AllRows > 100
				UPDATE SearchDB..paSearchJobID_2 SET IsTop = 1 
				WHERE paSearchConditionID = @paSearchConditionID
				AND ID IN (SELECT TOP 3 ID FROM SearchDB..paSearchJobID_2 WITH(NOLOCK) WHERE paSearchConditionID = @paSearchConditionID ORDER BY ID)
		END
		ELSE IF (@TableId = 3)
		BEGIN
			----------------------------jobtype
			INSERT INTO @sc2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'JobType', dcJobTypeID, COUNT(*)
			FROM #Job WITH(NOLOCK)
			GROUP BY dcJobTypeID ORDER BY dcJobTypeID			

			----计算全部某职位类别，2, 4位的数据
			IF @JobTypeLen NOT IN(2, 4)
			BEGIN
				INSERT INTO @Sc(paSearchConditionID, Title, TitleId, TitleValue)
				SELECT  @paSearchConditionID, 'JobType', LEFT(TitleID, 2) TitleID, SUM(TitleValue) TitleValue 
				FROM @sc2 GROUP BY LEFT(TitleID, 2)
			END
			IF @JobTypeLen NOT IN(0, 4)
			BEGIN
				INSERT INTO @Sc(paSearchConditionID, Title, TitleId, TitleValue)
				SELECT  @paSearchConditionID, 'JobType', TitleId, TitleValue
				FROM @sc2 WHERE LEN(TitleId) = 4
			END

			IF @JobTypeLen = -1
				DELETE @sc WHERE TitleID NOT IN(SELECT a FROM dbo.fnSplit(@dcJobTypeID, ','))

			INSERT INTO SearchDB..paSearchCount_3(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT  @paSearchConditionID, 'JobType', TitleId, TitleValue FROM @sc
			DELETE @sc
			DELETE @sc2
			--------------------------region
			INSERT INTO @sc2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Region', dcRegionID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcRegionID ORDER BY dcRegionID
			----计算全部地区，2位的数据
			IF @JobPlaceLen IN(-1, 0)
				INSERT INTO @sc(paSearchConditionID, Title, TitleId, TitleValue)
				SELECT @paSearchConditionID, 'Region', LEFT(TitleID, 2) TitleID, SUM(TitleValue) TitleValue 
				FROM @sc2 GROUP BY LEFT(TitleID, 2)
			IF @JobPlaceLen IN(-1, 2)
				INSERT INTO @sc(paSearchConditionID, Title, TitleId, TitleValue)
				SELECT @paSearchConditionID, 'Region', LEFT(TitleID, 4) TitleID, SUM(TitleValue) TitleValue 
				FROM @sc2 WHERE LEN(TitleID) >= 4 GROUP BY LEFT(TitleID, 4)
			IF @JobPlaceLen IN(-1, 4)
				INSERT INTO @sc(paSearchConditionID, Title, TitleId, TitleValue)
				SELECT @paSearchConditionID, 'Region', TitleID, TitleValue 
				FROM @sc2 WHERE LEN(TitleID) = 6
			IF @JobPlaceLen = -1
				DELETE @sc WHERE TitleID NOT IN(SELECT ID FROM @T_JobPlace)
			ELSE
				DELETE @sc WHERE LEN(TitleID) <> @JobPlaceLen + 2

			INSERT INTO SearchDB..paSearchCount_3(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT paSearchConditionID, Title, TitleId, TitleValue FROM @sc
			----------------------------
			INSERT INTO SearchDB..paSearchCount_3(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Education', CASE WHEN dcEducationId IN(2, 3, 4) THEN 2 ELSE dcEducationId END, COUNT(*) 
			FROM #Job WITH(NOLOCK)
			GROUP BY CASE WHEN dcEducationId IN(2, 3, 4) THEN 2 ELSE dcEducationId END
			ORDER BY CASE WHEN dcEducationId IN(2, 3, 4) THEN 2 ELSE dcEducationId END
			
			INSERT INTO SearchDB..paSearchCount_3(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Experience', MinExperience, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY MinExperience ORDER BY MinExperience

			INSERT INTO SearchDB..paSearchCount_3(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Salary', dcSalaryID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcSalaryID ORDER BY dcSalaryID

			INSERT INTO SearchDB..paSearchCount_3(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'EmployType', EmployType, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY EmployType ORDER BY EmployType

			INSERT INTO SearchDB..paSearchCount_3(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'CompanySize', dcCompanySizeID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcCompanySizeID ORDER BY dcCompanySizeID

			INSERT INTO SearchDB..paSearchCount_3(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Industry', dcIndustryID, COUNT(*) 
			FROM #Job a WITH(NOLOCK), cpIndustry b WITH(NOLOCK)
			WHERE a.cpMainId = b.cpMainId
			GROUP BY dcIndustryID ORDER BY dcIndustryID

			IF EXISTS(SELECT TOP 1 'x' FROM #FullText)
				INSERT INTO SearchDB..paSearchJobID_3(paSearchConditionID, JobId, IsTop)
				SELECT TOP 10 @paSearchConditionID, a.JobId, 1 
				FROM SearchJobTop a WITH(NOLOCK), (SELECT ID FROM #Job WITH(NOLOCK) WHERE RowId < 2001) b 
				WHERE b.ID = a.JobId
				AND CHARINDEX(@KeyWord, a.JobName) > 0
				ORDER BY a.OrderType, a.OpenDate DESC
			ELSE
				INSERT INTO SearchDB..paSearchJobID_3(paSearchConditionID, JobId, IsTop)
				SELECT TOP 10 @paSearchConditionID, a.JobId, 1 
				FROM SearchJobTop a WITH(NOLOCK), (SELECT ID FROM #Job WITH(NOLOCK) WHERE RowId < 2001) b 
				WHERE b.ID = a.JobId
				ORDER BY a.OrderType, a.OpenDate DESC
			SET @TopRows = @@ROWCOUNT

			INSERT INTO SearchDB..paSearchJobID_3(paSearchConditionID, JobId, IsTop)
			SELECT TOP 2000 @paSearchConditionID, ID, 0 FROM #Job WITH(NOLOCK) ORDER BY RowID
			SET @AllRows = @@ROWCOUNT

			IF @TopRows = 0 AND @AllRows > 100
				UPDATE SearchDB..paSearchJobID_3 SET IsTop = 1 
				WHERE paSearchConditionID = @paSearchConditionID
				AND ID IN (SELECT TOP 3 ID FROM SearchDB..paSearchJobID_3 WITH(NOLOCK) WHERE paSearchConditionID = @paSearchConditionID ORDER BY ID)
		END
		DROP TABLE #Job
		--PRINT 'DROP #JOB  ' + CONVERT(VARCHAR(30), GETDATE(), 121)
	COMMIT
	--GOTO GetRecordSet

	GetRecordSet:
	BEGIN
		DECLARE @AllJobCount AS INT
		----返回查询数量
		SELECT ValidJobNumber FROM SearchDB..paSearchCondition WITH(NOLOCK) WHERE ID=@paSearchConditionID
		SELECT @AllJobCount = ValidJobNumber FROM SearchDB..paSearchCondition WITH(NOLOCK) WHERE ID=@paSearchConditionID
		UPDATE SearchDB..paSearchCondition SET ReuseNumber = ReuseNumber + 1 WHERE ID=@paSearchConditionID
		----返回20行查询结果
		IF (@TableID = 0)
		BEGIN
			SELECT @MinId = MIN(ID) FROM SearchDB..paSearchJobID_0 WITH(NOLOCK) WHERE paSearchConditionID=@paSearchConditionID

			SET @MinId = @MinId+(@PageNumber-1)*@PageSize
			SELECT TOP 30 a.ID, a.cpMainID, a.caMainID, a.Name as JobName, a.MinExperience ,
				a.dcJobTypeIDMinor, a.NeedNumber, a.dcSalaryID, a.dcSalaryIDMax, a.EmployType, 
				a.dcRegionID,  a.dcEducationID, a.RefreshDate,a.SecondId EnJobID,
				b.SecondId EnCpMainID, b.Name as cpName, b.HasLicence, c.IsTop, 
				ISNULL(d.IsOnline, 0) IsOnline, d.ViPlanId, d.InterviewDate, 
				e.FullName Region, b.LogoFile LogoUrl,@AllJobCount JobNumber
			FROM JobPublish a WITH(NOLOCK)
			INNER JOIN cpMainPublish b WITH(NOLOCK) ON a.cpMainID = b.ID 
			INNER JOIN SearchDB..paSearchJobID_0 c WITH(NOLOCK) ON a.id = c.JobID
			INNER JOIN dcRegion e WITH(NOLOCK) ON a.dcRegionId = e.Id
			LEFT JOIN caOnline d WITH(NOLOCK) ON a.caMainId = d.caMainId
			WHERE paSearchConditionID=@paSearchConditionID 
			AND c.ID >= @MinId
			ORDER BY c.ID, a.ID DESC
		END
		ELSE IF (@TableID = 1)
		BEGIN
			SELECT @MinId = MIN(ID) FROM SearchDB..paSearchJobID_1 WITH(NOLOCK) WHERE paSearchConditionID=@paSearchConditionID

			SET @MinId = @MinId+(@PageNumber-1)*@PageSize
			SELECT TOP 30 a.ID, a.cpMainID, a.caMainID, a.Name as JobName, a.MinExperience ,
				a.dcJobTypeIDMinor, a.NeedNumber, a.dcSalaryID, a.dcSalaryIDMax, a.EmployType, 
				a.dcRegionID,  a.dcEducationID, a.RefreshDate,a.SecondId EnJobID,
				b.SecondId EnCpMainID, b.Name as cpName, b.HasLicence, c.IsTop, 
				ISNULL(d.IsOnline, 0) IsOnline, d.ViPlanId, d.InterviewDate, 
				e.FullName Region, b.LogoFile LogoUrl,@AllJobCount JobNumber
			FROM JobPublish a WITH(NOLOCK)
			INNER JOIN cpMainPublish b WITH(NOLOCK) ON a.cpMainID = b.ID 
			INNER JOIN SearchDB..paSearchJobID_1 c WITH(NOLOCK) ON a.id = c.JobID
			INNER JOIN dcRegion e WITH(NOLOCK) ON a.dcRegionId = e.Id
			LEFT JOIN caOnline d WITH(NOLOCK) ON a.caMainId = d.caMainId
			WHERE paSearchConditionID=@paSearchConditionID 
			AND c.ID >= @MinId
			ORDER BY c.ID, a.ID DESC
		END
		ELSE IF (@TableID = 2)
		BEGIN
			SELECT @MinId = MIN(ID) FROM SearchDB..paSearchJobID_2 WITH(NOLOCK) WHERE paSearchConditionID=@paSearchConditionID

			SET @MinId = @MinId+(@PageNumber-1)*@PageSize
			SELECT TOP 30 a.ID, a.cpMainID, a.caMainID, a.Name as JobName, a.MinExperience ,
				a.dcJobTypeIDMinor, a.NeedNumber, a.dcSalaryID, a.dcSalaryIDMax, a.EmployType, 
				a.dcRegionID,  a.dcEducationID, a.RefreshDate,a.SecondId EnJobID,
				b.SecondId EnCpMainID, b.Name as cpName, b.HasLicence, c.IsTop, 
				ISNULL(d.IsOnline, 0) IsOnline, d.ViPlanId, d.InterviewDate, 
				e.FullName Region, b.LogoFile LogoUrl,@AllJobCount JobNumber
			FROM JobPublish a WITH(NOLOCK)
			INNER JOIN cpMainPublish b WITH(NOLOCK) ON a.cpMainID = b.ID 
			INNER JOIN SearchDB..paSearchJobID_2 c WITH(NOLOCK) ON a.id = c.JobID
			INNER JOIN dcRegion e WITH(NOLOCK) ON a.dcRegionId = e.Id
			LEFT JOIN caOnline d WITH(NOLOCK) ON a.caMainId = d.caMainId
			WHERE paSearchConditionID=@paSearchConditionID 
			AND c.ID >= @MinId
			ORDER BY c.ID, a.ID DESC
		END
		ELSE IF (@TableID = 3)
		BEGIN
			SELECT @MinId = MIN(ID) FROM SearchDB..paSearchJobID_3 WITH(NOLOCK) WHERE paSearchConditionID=@paSearchConditionID

			SET @MinId = @MinId+(@PageNumber-1)*@PageSize
			SELECT TOP 30 a.ID, a.cpMainID, a.caMainID, a.Name as JobName, a.MinExperience ,
				a.dcJobTypeIDMinor, a.NeedNumber, a.dcSalaryID, a.dcSalaryIDMax, a.EmployType, 
				a.dcRegionID,  a.dcEducationID, a.RefreshDate,a.SecondId EnJobID,
				b.SecondId EnCpMainID, b.Name as cpName, b.HasLicence, c.IsTop, 
				ISNULL(d.IsOnline, 0) IsOnline, d.ViPlanId, d.InterviewDate, 
				e.FullName Region, b.LogoFile LogoUrl,@AllJobCount JobNumber
			FROM JobPublish a WITH(NOLOCK)
			INNER JOIN cpMainPublish b WITH(NOLOCK) ON a.cpMainID = b.ID 
			INNER JOIN SearchDB..paSearchJobID_3 c WITH(NOLOCK) ON a.id = c.JobID
			INNER JOIN dcRegion e WITH(NOLOCK) ON a.dcRegionId = e.Id
			LEFT JOIN caOnline d WITH(NOLOCK) ON a.caMainId = d.caMainId
			WHERE paSearchConditionID=@paSearchConditionID 
			AND c.ID >= @MinId
			ORDER BY c.ID, a.ID DESC
		END
        --RICHARD 2011-7-23 16:51分修改
		----返回统计数量
		IF @Type=1
		BEGIN
			DECLARE @RegionCount AS INT
			SELECT @RegionCount = -1
			IF CHARINDEX(',', @dcRegionID) = 0 AND LEN(@dcRegionID) > 0
			BEGIN
				IF NOT LEFT(@dcRegionID,1) = 'p'
					SELECT @RegionCount = COUNT(*) FROM dcRegion WHERE ParentID = @dcRegionID
			END
			IF (@TableID = 0)
			BEGIN
				SELECT * FROM SearchDB..paSearchCount_0 WITH(NOLOCK) WHERE Title = 'JobType' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(VARCHAR(10), TitleID)
				IF @RegionCount = 0
					SELECT * FROM dcMapPlace WITH(NOLOCK) WHERE dcRegionID = @dcRegionID
				ELSE
					SELECT * FROM SearchDB..paSearchCount_0 WITH(NOLOCK) WHERE Title = 'Region' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(VARCHAR(10), TitleID)
				SELECT * FROM SearchDB..paSearchCount_0 WITH(NOLOCK) WHERE Title = 'Education' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT * FROM SearchDB..paSearchCount_0 WITH(NOLOCK) WHERE Title = 'Experience' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT * FROM SearchDB..paSearchCount_0 WITH(NOLOCK) WHERE Title = 'Salary' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT * FROM SearchDB..paSearchCount_0 WITH(NOLOCK) WHERE Title = 'EmployType' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT * FROM SearchDB..paSearchCount_0 WITH(NOLOCK) WHERE Title = 'CompanySize' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
			END
			IF (@TableID = 1)
			BEGIN
				SELECT * FROM SearchDB..paSearchCount_1 WITH(NOLOCK) WHERE Title = 'JobType' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(VARCHAR(10), TitleID)
				IF @RegionCount = 0
					SELECT * FROM dcMapPlace WITH(NOLOCK) WHERE dcRegionID = @dcRegionID
				ELSE
					SELECT * FROM SearchDB..paSearchCount_1 WITH(NOLOCK) WHERE Title = 'Region' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(VARCHAR(10), TitleID)
				SELECT * FROM SearchDB..paSearchCount_1 WITH(NOLOCK) WHERE Title = 'Education' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT * FROM SearchDB..paSearchCount_1 WITH(NOLOCK) WHERE Title = 'Experience' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT * FROM SearchDB..paSearchCount_1 WITH(NOLOCK) WHERE Title = 'Salary' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT * FROM SearchDB..paSearchCount_1 WITH(NOLOCK) WHERE Title = 'EmployType' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT * FROM SearchDB..paSearchCount_1 WITH(NOLOCK) WHERE Title = 'CompanySize' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
			END
			IF (@TableID = 2)
			BEGIN
				SELECT * FROM SearchDB..paSearchCount_2 WITH(NOLOCK) WHERE Title = 'JobType' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(VARCHAR(10), TitleID)
				IF @RegionCount = 0
					SELECT * FROM dcMapPlace WITH(NOLOCK) WHERE dcRegionID = @dcRegionID
				ELSE
					SELECT * FROM SearchDB..paSearchCount_2 WITH(NOLOCK) WHERE Title = 'Region' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(VARCHAR(10), TitleID)
				SELECT * FROM SearchDB..paSearchCount_2 WITH(NOLOCK) WHERE Title = 'Education' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT * FROM SearchDB..paSearchCount_2 WITH(NOLOCK) WHERE Title = 'Experience' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT * FROM SearchDB..paSearchCount_2 WITH(NOLOCK) WHERE Title = 'Salary' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT * FROM SearchDB..paSearchCount_2 WITH(NOLOCK) WHERE Title = 'EmployType' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT * FROM SearchDB..paSearchCount_2 WITH(NOLOCK) WHERE Title = 'CompanySize' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
			END
			IF (@TableID = 3)
			BEGIN
				SELECT * FROM SearchDB..paSearchCount_3 WITH(NOLOCK) WHERE Title = 'JobType' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(VARCHAR(10), TitleID)
				IF @RegionCount = 0
					SELECT * FROM dcMapPlace WITH(NOLOCK) WHERE dcRegionID = @dcRegionID
				ELSE
					SELECT * FROM SearchDB..paSearchCount_3 WITH(NOLOCK) WHERE Title = 'Region' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(VARCHAR(10), TitleID)
				SELECT * FROM SearchDB..paSearchCount_3 WITH(NOLOCK) WHERE Title = 'Education' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT * FROM SearchDB..paSearchCount_3 WITH(NOLOCK) WHERE Title = 'Experience' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT * FROM SearchDB..paSearchCount_3 WITH(NOLOCK) WHERE Title = 'Salary' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT * FROM SearchDB..paSearchCount_3 WITH(NOLOCK) WHERE Title = 'EmployType' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT * FROM SearchDB..paSearchCount_3 WITH(NOLOCK) WHERE Title = 'CompanySize' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
			END
		END

		RETURN
	END
END TRY
BEGIN CATCH
	ROLLBACK TRANSACTION
	---检查是否已经建立临时表，已经建立则删除
	DECLARE @para VARCHAR(MAX)
	SET @para = '@dcJobTypeID=' + ISNULL(@dcJobTypeID, '') + '|' +
		'@dcRegionID=' + ISNULL(@dcRegionID, '') + '|' +
		'@dcIndustryID=' + ISNULL(@dcIndustryID, '') + '|' +
		'@EmployType=' + ISNULL(@EmployType, '') + '|' +
		'@KeyWord=' + ISNULL(@KeyWord, '') + '|' +
		'@ORDER=' + ISNULL(@ORDER, '') + '|' +
		'@SessionID=' + ISNULL(@SessionID, '') + '|' +
		'@Welfare=' + ISNULL(@Welfare, '')
	INSERT INTO ErrorLog	
	SELECT 'm1 ' + ISNULL(error_Message(), ' no msg')+ ' para=' + ISNULL(@Para, 'no para ') + ISNULL(@SQL, ' no sql'), error_number(), error_line(), GETDATE()
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[mblJobBySearchSelect2]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[mblJobBySearchSelect2]
(
	@dcJobTypeID VARCHAR(100), 		--职位类别
	@dcRegionID VARCHAR(100), 		--求职地区
	@dcIndustryID VARCHAR(100), 	--求职行业
	@dcSalaryID TINYINT, 			--月薪
	@IsNegotiable BIT, 				--1允许面议，不面议
	@MinExperience TINYINT, 		--工作经验，100为未选择
	@dcEducationID TINYINT, 		--最低学历
	@EmployType VARCHAR(10), 		--工作性质，1全职；3兼职；4实习，
	@KeyWord NVARCHAR(50), 			--关键词
	@KeyType TINYINT, 				--搜索类别，0无；1-全文；2-职位；3-公司 
	@ORDER VARCHAR(4), 				--显示顺序，没有用
	@RefreshNo INT, 				--1, 1天内；2, 3天内；3，一周内；4，15天内；5，一个月内；6超过一个月
	@Type INT, 						--1：主动搜索  点击搜索按钮 10分钟，翻页60分钟有效；0：翻页搜索，不刷新
	@PageNumber INT, 				--翻页页码
	@SessionID varchar(50),					--10
	@CompanySizeID VARCHAR(1), 		--企业规模
	@IsOnline INT,
	@Welfare VARCHAR(50)					--
)
AS
--return   @SessionId = 10
SET NOCOUNT ON
INSERT INTO SearchIp(Ip, Source) SELECT @SessionId, 'm'
IF EXISTS(SELECT 'x' FROM RefuseIp WITH(NOLOCK) WHERE CHARINDEX(Ip,@SessionId) > 0)
	RETURN
SET @SessionId = 10
SET @KeyType = 0
BEGIN TRY
	DECLARE @ReuseNumber AS INT, @dcProvinceId VARCHAR(2), @Order2 VARCHAR(100)
	----给null值变量赋默认值
	IF NOT LEFT(@dcRegionID,1) = 'p'
		SELECT @dcRegionID = RTRIM(dbo.FormatIDS(@dcRegionID))

	SELECT @dcJobTypeID = RTRIM(dbo.FormatIDS(@dcJobTypeID)),
		@dcIndustryID = RTRIM(dbo.FormatIDS(@dcIndustryID)),
		@dcSalaryID = ISNULL(@dcSalaryID, 0),
		@IsNegotiable = ISNULL(@IsNegotiable, 0),
		@MinExperience = ISNULL(@MinExperience, 100),
		@dcEducationID = ISNULL(@dcEducationID, 0),
		@EmployType = CASE @EmployType WHEN '2' THEN '1,3' ELSE ISNULL(@EmployType, '') END,
		@CompanySizeID = ISNULL(@CompanySizeID, '0'),
		@KeyWord = dbo.SafeSQL(ISNULL(@KeyWord, '')),
		@ORDER = ISNULL(@Order, ''),
		@Type = ISNULL(@Type, 0),
		@PageNumber = ISNULL(@PageNumber, 0),
		@Welfare = RTRIM(dbo.FormatIDS(@Welfare)),
		@IsOnline = ISNULL(@IsOnline, 0),
		@Order2 = ' ORDER BY a.RefreshDate DESC, a.SecondID DESC'

	IF @dcSalaryID = 0
		SET @IsNegotiable = 0

	IF @Order LIKE 'p=%'
		SET @dcProvinceId = REPLACE(@Order, 'p=', '')
	ELSE
		SET @dcProvinceId = 0

	--@RefreshNo = 0选择全部数据，不限制时间
	SET @RefreshNo = 0
	IF(@KeyWord = '' AND ISNULL(@dcJobTypeID, '') = '' AND ISNULL(@dcRegionID, '') = '' AND ISNULL(@dcIndustryID, '') = '')
		RETURN

	--如果关键词不为空 查询关键词对应的搜索类型 max 2012-12-25 
	
	IF RIGHT(@KeyWord, 2) = '公司'
		SET @KeyWord = LEFT(@KeyWord, LEN(@KeyWord) - 2)
		
	IF RIGHT(@dcJobTypeID, 1) = ','
		SET @dcJobTypeID = LEFT(@dcJobTypeID, LEN(@dcJobTypeID) - 1)
	IF RIGHT(@dcRegionID, 1) = ','
		SET @dcRegionID = LEFT(@dcRegionID, LEN(@dcRegionID) - 1)
	IF RIGHT(@dcIndustryID, 1) = ','
		SET @dcIndustryID = LEFT(@dcIndustryID, LEN(@dcIndustryID) - 1)

	DECLARE @paSearchConditionID AS INT, 
		@MinId AS INT, 
		@PageSize AS TINYINT, 
		@TableID AS TINYINT

	SELECT @paSearchConditionID = 0, @PageSize = 30	

	----搜索1分钟前的数据
	SELECT TOP 1 @paSearchConditionID = ID,
		@ReuseNumber = ReuseNumber
	FROM SearchDB..paSearchCondition WITH(NOLOCK)
	WHERE JobType=@dcJobTypeID AND IsOnline = @IsOnline
	AND JobPlace=@dcRegionID AND Industry=@dcIndustryID AND Education=@dcEducationID
	AND Experience=@MinExperience AND Salary=@dcSalaryID AND IsNegotiable=@IsNegotiable 
	AND EmployType=@EmployType AND ISNULL(KeyWord, '') = @KeyWord AND KeyType = @KeyType
	AND CompanySizeID = @CompanySizeID AND Welfare = @Welfare AND IsDelete = 0
	AND LogTime > DATEADD(MINUTE, -1, GETDATE()) AND ReuseNumber > 0
	AND RefreshNo = 0 AND ISNULL(dcProvinceId, 0) = @dcProvinceId
	ORDER BY ID DESC

	IF @ReuseNumber = 0
	BEGIN
		SELECT TOP 1 @paSearchConditionID = ID
		FROM SearchDB..paSearchCondition WITH(NOLOCK)
		WHERE JobType=@dcJobTypeID AND IsOnline = @IsOnline
		AND JobPlace=@dcRegionID AND Industry=@dcIndustryID AND Education=@dcEducationID
		AND Experience=@MinExperience AND Salary=@dcSalaryID AND IsNegotiable=@IsNegotiable 
		AND EmployType=@EmployType AND ISNULL(KeyWord, '') = @KeyWord AND KeyType=@KeyType
		AND CompanySizeID = @CompanySizeID AND Welfare = @Welfare AND ReuseNumber > 0
		AND ReuseNumber > 0 AND LogTime > DATEADD(MINUTE, -2, GETDATE()) 
		AND RefreshNo = 0 AND ISNULL(dcProvinceId, 0) = @dcProvinceId
		ORDER BY ID DESC
	END

	IF ISNULL(@paSearchConditionID, 0) = 0
	BEGIN
		SET @Type =1
		GOTO SelectReset	--无数据，重新搜索
	END
	ELSE
	BEGIN
		SELECT @TableID = @paSearchConditionID % 4
		GOTO GetRecordSet	--从临时结果中提取数据
	END

SelectReset:
	--从job中搜索数据
	BEGIN TRAN
		DECLARE @SQL AS VARCHAR(8000)
		DECLARE @WHERE AS VARCHAR(8000)
		DECLARE @FROM AS VARCHAR(1000)
		----记录查询条件
		INSERT INTO SearchDB..paSearchCondition(SessionID, LogTime, JobType, JobPlace, Industry, Education, Experience, 
			Salary, IsNegotiable, EmployType, CompanySizeID, KeyWord, KeyType, ReuseNumber, Welfare, IsOnline, dcProvinceId)
		VALUES(@SessionId, GETDATE(), @dcJobTypeID, @dcRegionID, @dcIndustryID, @dcEducationID, @MinExperience, 
			@dcSalaryID, @IsNegotiable, @EmployType, @CompanySizeID, @KeyWord, @KeyType, 0, @Welfare, @IsOnline, @dcProvinceId)
		SET @paSearchConditionID = @@IDENTITY
		SELECT @TableID = @paSearchConditionID % 4

		------生成职位类别的表变量，因为职位类别有包含（父子）关系
		DECLARE @T_JobPlace AS TABLE(ID INT)
		DECLARE @T_JobType AS TABLE(ID INT)
		DECLARE @JobPlaceLen AS INT, @JobTypeLen AS INT
		IF CHARINDEX(',', @dcJobTypeID) > 0
			SET @JobTypeLen = -1
		ELSE
			SET @JobTypeLen = LEN(@dcJobTypeID)

		DECLARE @JobType AS VARCHAR(3000), @JobPlace AS VARCHAR(2000), @ValidJobNumber AS INT

		SELECT @JobPlace = '', @JobType=''
		----生成工作地点的表变量
		IF LEN(@dcRegionID) > 0
		BEGIN
			IF LEFT(@dcRegionID,1) = 'p'
			BEGIN
				DECLARE @Degree AS DECIMAL(8,5),@LBLng AS DECIMAL(8,5),@LBLat AS DECIMAL(8,5),
				@RTLng AS DECIMAL(8,5),@RTLat AS DECIMAL(8,5),@Lat AS DECIMAL(8,5),@Lng AS DECIMAL(8,5)
				
				SELECT @Lat = Lat,@Lng = Lng FROM dcMapPlace WITH(NOLOCK) WHERE ID = RIGHT(@dcRegionID,LEN(@dcRegionID)-1)
				IF @dcRegionID LIKE '3201%'
					SET @Degree = 1000 / 100000.0
				ELSE
					SET @Degree = 2000 / 100000.0

				SET @LBLng = @Lng - @Degree
				SET @LBLat = @Lat - @Degree
				SET @RTLng = @Lng + @Degree
				SET @RTLat = @Lat + @Degree
				SET @JobPlace = 'a.Lng BETWEEN ' + CONVERT(VARCHAR,@LBLng) + ' AND ' + CONVERT(VARCHAR,@RTLng) + '
					AND a.Lat BETWEEN ' + CONVERT(VARCHAR,@LBLat) + ' AND ' + CONVERT(VARCHAR,@RTLat) + '
					AND (a.Lng-' + CONVERT(VARCHAR,@Lng) + ')*(a.Lng-' + CONVERT(VARCHAR,@Lng) + ')+
					(a.Lat-' + CONVERT(VARCHAR,@Lat) + ')*(a.Lat-' + CONVERT(VARCHAR,@Lat) + ')<' + CONVERT(VARCHAR,@Degree*@Degree)
				SELECT @JobPlaceLen = 8
			END
			ELSE
			BEGIN
				INSERT INTO @T_JobPlace
				SELECT * FROM dbo.fnSplit(@dcRegionID, ',')
				SELECT @JobPlace = (@JobPlace + ' OR a.dcRegionID Like ''' + LTRIM(STR(ID) + '%''')) FROM @T_JobPlace
				IF LEN(@JobPlace) > 0
					SET @JobPlace = RIGHT(@JobPlace, LEN(@JobPlace) -4)
				IF (SELECT COUNT(*) FROM @T_JobPlace) > 1
					SET @JobPlaceLen = -1
				ELSE
					SET @JobPlaceLen = LEN(@dcRegionID)
			END
		END
		ELSE 
			SELECT @JobPlaceLen = 0


		----生成求聘职位的表变量
		IF LEN(@dcJobTypeID) > 0
		BEGIN
			DECLARE @T_Temp AS TABLE(ID INT)		--临时表，用于构建组合查询语句
			INSERT INTO @T_Temp
			SELECT * FROM dbo.fnSplit(@dcJobTypeID, ',')

			INSERT INTO @T_JobType
			SELECT DISTINCT ID FROM dcJobType WITH(NOLOCK)
			WHERE ParentId IN(SELECT ID FROM @T_TEMP) 
			OR ParentId2 in(SELECT ID FROM @T_TEMP)
			OR ID IN(SELECT ID FROM @T_TEMP)
			----生成in字符串
			SELECT @JobType = (@JobType + LTRIM(STR(ID) + ',')) FROM @T_JobType
			IF RIGHT(@JobType, 1) = ','
				SET @JobType = LEFT(@JobType, LEN(@JobType) - 1)
		END

		----建立临时表
		CREATE TABLE #Job(
			RowID INT IDENTITY(1, 1), 
			ID INT NOT NULL,
			cpMainId INT,
			dcJobTypeID SMALLINT NOT NULL, 
			dcJobTypeIDMinor SMALLINT NULL, 
			dcSalaryID TINYINT NOT NULL, 
			dcRegionID VARCHAR(6) NULL, 
			dcEducationID TINYINT NOT NULL, 
			MinExperience TINYINT NOT NULL, 
			RefreshDate SMALLDATETIME NULL,
			EmployType TINYINT NULL,
			dcCompanySizeID SMALLINT NULL
		)

		CREATE TABLE #FullText(
			Priority INT,
			JobId INT NOT NULL
		)

		------刷新时间，根据刷新时间编号计算
		----生成插入临时表的Sql语句
		SET @SQL='
			INSERT INTO #Job
			SELECT a.ID, a.cpMainId, a.dcJobTypeID, 
				a.dcJobTypeIDMinor, a.dcSalaryID, 
				a.dcRegionID, a.dcEducationID, a.MinExperience, 
				a.IssueDate,a.EmployType,b.dcCompanySizeID'
		SET @FROM = '
			FROM JobPublish a WITH(NOLOCK)
			INNER JOIN cpMainPublish b WITH(NOLOCK) ON a.cpMainID=b.ID'
		----职位有效，单位新有效
		IF LEN(@dcIndustryID) > 0
			SET @WHERE = '
			WHERE b.ID IN (SELECT cpMainID FROM cpIndustry WHERE dcIndustryId in(' + @dcIndustryID + '))
			AND a.Valid = 1
			AND b.Valid = 1'
		ELSE
			SET @WHERE = '
			WHERE a.Valid = 1
			AND b.Valid = 1'
		
		IF LEN(@dcProvinceId) > 1
			SET @WHere = @Where + ' AND b.dcProvinceId = ' + @dcProvinceId

		----职位类别
		IF LEN(@JobType) > 0
			SET @WHERE = @WHERE + '
			AND (a.dcJobTypeID IN(' + @JobType +')
				OR a.dcJobTypeIDMinor IN(' +@JobType + '))'
		IF LEN(@JobPlace) > 0 
			SET @WHERE = @WHERE + '
			AND (' + @JobPlace + ')'

		IF @dcSalaryID > 0
		BEGIN
			IF @dcSalaryID < 100				----从form中搜索，月薪跨2个级别, 是本级和上级别的薪金
			BEGIN
				SET @WHERE = @WHERE + '
			AND a.dcSalaryID IN(' + LTRIM(STR(@dcSalaryID)) + ',' + LTRIM(STR(@dcSalaryID + 1))
				IF @IsNegotiable = 1		--包括面议
					SET @WHERE = @WHERE + ', 100'
				SET @WHERE = @WHERE + ')'
			END
			IF @dcSalaryID = 100	----从筛选结果中点击面议，值是100
			BEGIN
				SET @WHERE = @WHERE + '
			AND a.dcSalaryID = 100'
			END
			IF @dcSalaryID BETWEEN 101 AND 106	----从筛选结果中点击搜索，月薪只有1个级别，传值时增加100
				SET @WHERE = @WHERE + '
			AND a.dcSalaryID <= ' + LTRIM(STR(@dcSalaryID-99)) + ' AND a.dcSalaryIDMax > ' + LTRIM(STR(@dcSalaryID-100))
			IF @dcSalaryID > 106	----从筛选结果中点击搜索，月薪只有1个级别，传值时增加100
				SET @WHERE = @WHERE + '
			AND a.dcSalaryID <= ' + LTRIM(STR(@dcSalaryID - 100)) + ' AND a.dcSalaryIDMax > ' + LTRIM(STR(@dcSalaryID-100))
		END
		----工作经验要求
		IF @MinExperience < 100
		SET @WHERE = @WHERE + ' 
			AND a.MinExperience = ' + LTRIM(STR(@MinExperience))

		----学历要求
		----'1初中', '2\3\4高中、中技、中专', '5大专', '6本科', '7硕士', '8博士
		IF @dcEducationID > 0
			IF @dcEducationID = 2
				SET @WHERE = @WHERE + '
			AND a.dcEducationID IN(2, 3, 4)'
			ELSE
				SET @WHERE = @WHERE + '
			AND a.dcEducationID = ' + LTRIM(STR(@dcEducationID))
		----1、全职；3、兼职；4实习。	2、全职/兼职 职位中无此项
		IF LEN(@EmployType) > 0
			SET @WHERE = @WHERE + '
			AND a.EmployType IN (' + @EmployType + ')'

		IF @CompanySizeID BETWEEN 1 AND 6
			SET @WHERE = @WHERE + '
			AND b.dcCompanySizeID = ' + LTRIM(STR(@CompanySizeID))

		IF LEN(@Welfare) > 0
			SET @WHERE = @WHERE + '
			AND a.Welfare' + REPLACE(@Welfare, ',', ' = 1 AND a.Welfare') + ' = 1'

		IF @IsOnline = 1
			SET @WHERE = @WHERE + '
			AND a.caMainId IN(SELECT caMainId FROM caOnline WITH(NOLOCK) WHERE IsOnline = 1)'

		IF LEN(@KeyWord) > 0  ----使用全文搜索job和cpmain2个表，经过测试发现union最快
		BEGIN
			IF EXISTS(SELECT TOP 1 'x' FROM cpMainPublish WITH(NOLOCK) WHERE Name = @KeyWord)
			BEGIN
				SET @WHERE = @WHERE + '
			AND b.Name = ''' + @KeyWord + ''''
				SET @SQL = @SQL + @FROM + @WHERE
			END
			ELSE
			BEGIN
				DECLARE @KeyWordTemp NVARCHAR(50)
				SET @KeyWordTemp = REPLACE(@KeyWord, ' ', '%')
				IF LEN(@KeyWordTemp) > 1
				BEGIN
					IF @dcProvinceId > 0
					BEGIN
						INSERT #FullText
						SELECT TOP 2000 2, b.ID
						FROM cpMainPublish a WITH(NOLOCK),
							JobPublish b WITH(NOLOCK)
						WHERE a.Id = b.cpMainId
						AND a.Name LIKE '%' + @KeyWordTemp + '%'
						AND a.dcProvinceId = @dcprovinceId
						ORDER BY b.RefreshDate DESC

						INSERT #FullText
						SELECT TOP 2000 1, b.ID
						FROM cpMainPublish a WITH(NOLOCK),
							JobPublish b WITH(NOLOCK)
						WHERE a.Id = b.cpMainId
						AND b.Name LIKE '%' + @KeyWordTemp + '%'
						AND a.dcProvinceId = @dcprovinceId
						ORDER BY b.RefreshDate DESC
					END
					ELSE
					BEGIN
						INSERT #FullText
						SELECT TOP 2000 2, b.ID
						FROM cpMainPublish a WITH(NOLOCK),
							JobPublish b WITH(NOLOCK)
						WHERE a.Id = b.cpMainId
						AND a.Name LIKE '%' + @KeyWordTemp + '%'
						ORDER BY b.RefreshDate DESC

						INSERT #FullText
						SELECT TOP 2000 1, b.ID
						FROM cpMainPublish a WITH(NOLOCK),
							JobPublish b WITH(NOLOCK)
						WHERE a.Id = b.cpMainId
						AND b.Name LIKE '%' + @KeyWordTemp + '%'
						ORDER BY b.RefreshDate DESC
					END
				END
				IF (SELECT COUNT(*) FROM #FullText) < 800
				BEGIN
					INSERT #FullText
					SELECT TOP 5000 3, [Key]
					FROM FREETEXTTABLE(cpMainJob, *, @KeyWord, 100000) AS KeyJob ORDER BY RANK DESC
				END
				DELETE a FROM #FullText a, #FullText b WHERE a.JobId = b.JobId AND a.Priority > b.Priority
				--------------------
				SELECT @FROM = @FROM + '
			INNER JOIN #FullText ON a.ID = #FullText.JobId',
					@ORDER2 = ' ORDER BY #FullText.Priority, a.RefreshDate DESC, a.SecondID DESC'
				SET @SQL = @SQL + @FROM + @WHERE
			END
		END
		ELSE
			SELECT @SQL = @SQL + @FROM + @WHERE
		
		SET @SQL = @SQL + @Order2
		--原来是ORDER BY a.IssueDate DESC, a.ID，Richard 2011年11月23日17：06分修改

		----把符合条件的职位全部列出
		--PRINT @SQL
		EXEC(@SQL)
		SET @ValidJobNumber = @@ROWCOUNT
		----记录查询结果总数
		UPDATE SearchDB..paSearchCondition SET ValidJobNumber=@ValidJobNumber, SQl=@SQL WHERE ID=@paSearchConditionID
		IF LEN(@JobType) > 0	--IN(2, 4)
			UPDATE #Job SET dcJobTypeId = dcJobTypeIDMinor
			WHERE dcJobTypeID NOT IN(SELECT a FROM dbo.fnSplit(@JobType, ','))

		----插入JobType数据
		DECLARE @TitleValue AS INT, @TopRows AS INT, @AllRows AS INT
		DECLARE @sc AS TABLE (
			paSearchConditionID int,
			Title varchar(20),
			TitleID varchar(10),
			TitleValue int
		)
		DECLARE @sc2 AS TABLE (
			paSearchConditionID int,
			Title varchar(20),
			TitleID varchar(10),
			TitleValue int
		)

		IF (@TableID = 0)
		BEGIN
			INSERT INTO @sc2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'JobType', dcJobTypeID, COUNT(*)
			FROM #Job WITH(NOLOCK)
			GROUP BY dcJobTypeID ORDER BY dcJobTypeID			

			----计算全部某职位类别，2, 4位的数据
			IF @JobTypeLen NOT IN(2, 4)
			BEGIN
				INSERT INTO @Sc(paSearchConditionID, Title, TitleId, TitleValue)
				SELECT  @paSearchConditionID, 'JobType', LEFT(TitleID, 2) TitleID, SUM(TitleValue) TitleValue 
				FROM @sc2 GROUP BY LEFT(TitleID, 2)
			END
			IF @JobTypeLen NOT IN(0, 4)
			BEGIN
				INSERT INTO @Sc(paSearchConditionID, Title, TitleId, TitleValue)
				SELECT  @paSearchConditionID, 'JobType', TitleId, TitleValue
				FROM @sc2 WHERE LEN(TitleId) = 4
			END

			IF @JobTypeLen = -1
				DELETE @sc WHERE TitleID NOT IN(SELECT a FROM dbo.fnSplit(@dcJobTypeID, ','))

			INSERT INTO SearchDB..paSearchCount_0(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT  @paSearchConditionID, 'JobType', TitleId, TitleValue FROM @sc
			DELETE @sc
			DELETE @sc2
			--------
			INSERT INTO @sc2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Region', dcRegionID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcRegionID ORDER BY dcRegionID
			----计算全部地区，2位的数据
			IF @JobPlaceLen IN(-1, 0)
				INSERT INTO @sc(paSearchConditionID, Title, TitleId, TitleValue)
				SELECT @paSearchConditionID, 'Region', LEFT(TitleID, 2) TitleID, SUM(TitleValue) TitleValue 
				FROM @sc2 GROUP BY LEFT(TitleID, 2)
			IF @JobPlaceLen IN(-1, 2)
				INSERT INTO @sc(paSearchConditionID, Title, TitleId, TitleValue)
				SELECT @paSearchConditionID, 'Region', LEFT(TitleID, 4) TitleID, SUM(TitleValue) TitleValue 
				FROM @sc2 WHERE LEN(TitleID) >= 4 GROUP BY LEFT(TitleID, 4)
			IF @JobPlaceLen IN(-1, 4)
				INSERT INTO @sc(paSearchConditionID, Title, TitleId, TitleValue)
				SELECT @paSearchConditionID, 'Region', TitleID, TitleValue 
				FROM @sc2 WHERE LEN(TitleID) = 6
			IF @JobPlaceLen = -1
				DELETE @sc WHERE TitleID NOT IN(SELECT ID FROM @T_JobPlace)
			ELSE
				DELETE @sc WHERE LEN(TitleID) <> @JobPlaceLen + 2

			INSERT INTO SearchDB..paSearchCount_0(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT paSearchConditionID, Title, TitleId, TitleValue FROM @sc
			----------------

			INSERT INTO SearchDB..paSearchCount_0(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'EmployType', EmployType, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY EmployType ORDER BY EmployType

			INSERT INTO SearchDB..paSearchCount_0(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Education', CASE WHEN dcEducationId IN(2, 3, 4) THEN 2 ELSE dcEducationId END, COUNT(*) 
			FROM #Job WITH(NOLOCK)
			GROUP BY CASE WHEN dcEducationId IN(2, 3, 4) THEN 2 ELSE dcEducationId END
			ORDER BY CASE WHEN dcEducationId IN(2, 3, 4) THEN 2 ELSE dcEducationId END

			INSERT INTO SearchDB..paSearchCount_0(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Experience', MinExperience, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY MinExperience ORDER BY MinExperience

			INSERT INTO SearchDB..paSearchCount_0(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'CompanySize', dcCompanySizeID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcCompanySizeID ORDER BY dcCompanySizeID

			INSERT INTO SearchDB..paSearchCount_0(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Salary', dcSalaryID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcSalaryID ORDER BY dcSalaryID

			INSERT INTO SearchDB..paSearchCount_0(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Industry', dcIndustryID, COUNT(*) 
			FROM #Job a WITH(NOLOCK), cpIndustry b WITH(NOLOCK)
			WHERE a.cpMainId = b.cpMainId
			GROUP BY b.dcIndustryId ORDER BY b.dcIndustryId

			INSERT INTO SearchDB..paSearchJobID_0(paSearchConditionID, JobId, IsTop)
			SELECT Top 3 @paSearchConditionID, a.JobId, 1 
			FROM SearchJobTop a WITH(NOLOCK), (SELECT TOP 2000 ID FROM #Job WITH(NOLOCK)) b 
			WHERE b.ID = a.JobId ORDER BY a.OpenDate DESC
			SET @TopRows = @@ROWCOUNT

			INSERT INTO SearchDB..paSearchJobID_0(paSearchConditionID, JobId, IsTop)
			SELECT TOP 2000 @paSearchConditionID, ID, 0 FROM #Job WITH(NOLOCK)
			SET @AllRows = @@ROWCOUNT

			IF @TopRows = 0 AND @AllRows > 100
				UPDATE SearchDB..paSearchJobID_0 SET IsTop = 1 
				WHERE paSearchConditionID = @paSearchConditionID
				AND ID IN (SELECT TOP 3 ID FROM SearchDB..paSearchJobID_0 WITH(NOLOCK) WHERE paSearchConditionID = @paSearchConditionID)
		END
		ELSE IF (@TableId = 1)
		BEGIN
			----------------------------jobtype
			INSERT INTO @sc2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'JobType', dcJobTypeID, COUNT(*)
			FROM #Job WITH(NOLOCK)
			GROUP BY dcJobTypeID ORDER BY dcJobTypeID			

			----计算全部某职位类别，2, 4位的数据
			IF @JobTypeLen NOT IN(2, 4)
			BEGIN
				INSERT INTO @Sc(paSearchConditionID, Title, TitleId, TitleValue)
				SELECT  @paSearchConditionID, 'JobType', LEFT(TitleID, 2) TitleID, SUM(TitleValue) TitleValue 
				FROM @sc2 GROUP BY LEFT(TitleID, 2)
			END
			IF @JobTypeLen NOT IN(0, 4)
			BEGIN
				INSERT INTO @Sc(paSearchConditionID, Title, TitleId, TitleValue)
				SELECT  @paSearchConditionID, 'JobType', TitleId, TitleValue
				FROM @sc2 WHERE LEN(TitleId) = 4
			END

			IF @JobTypeLen = -1
				DELETE @sc WHERE TitleID NOT IN(SELECT a FROM dbo.fnSplit(@dcJobTypeID, ','))

			INSERT INTO SearchDB..paSearchCount_1(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT  @paSearchConditionID, 'JobType', TitleId, TitleValue FROM @sc
			DELETE @sc
			DELETE @sc2
			--------------------------region
			INSERT INTO @sc2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Region', dcRegionID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcRegionID ORDER BY dcRegionID
			----计算全部地区，2位的数据
			IF @JobPlaceLen IN(-1, 0)
				INSERT INTO @sc(paSearchConditionID, Title, TitleId, TitleValue)
				SELECT @paSearchConditionID, 'Region', LEFT(TitleID, 2) TitleID, SUM(TitleValue) TitleValue 
				FROM @sc2 GROUP BY LEFT(TitleID, 2)
			IF @JobPlaceLen IN(-1, 2)
				INSERT INTO @sc(paSearchConditionID, Title, TitleId, TitleValue)
				SELECT @paSearchConditionID, 'Region', LEFT(TitleID, 4) TitleID, SUM(TitleValue) TitleValue 
				FROM @sc2 WHERE LEN(TitleID) >= 4 GROUP BY LEFT(TitleID, 4)
			IF @JobPlaceLen IN(-1, 4)
				INSERT INTO @sc(paSearchConditionID, Title, TitleId, TitleValue)
				SELECT @paSearchConditionID, 'Region', TitleID, TitleValue 
				FROM @sc2 WHERE LEN(TitleID) = 6
			IF @JobPlaceLen = -1
				DELETE @sc WHERE TitleID NOT IN(SELECT ID FROM @T_JobPlace)
			ELSE
				DELETE @sc WHERE LEN(TitleID) <> @JobPlaceLen + 2

			INSERT INTO SearchDB..paSearchCount_1(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT paSearchConditionID, Title, TitleId, TitleValue FROM @sc
			----------------------------
			INSERT INTO SearchDB..paSearchCount_1(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Education', CASE WHEN dcEducationId IN(2, 3, 4) THEN 2 ELSE dcEducationId END, COUNT(*)
			FROM #Job WITH(NOLOCK)
			GROUP BY CASE WHEN dcEducationId IN(2, 3, 4) THEN 2 ELSE dcEducationId END
			ORDER BY CASE WHEN dcEducationId IN(2, 3, 4) THEN 2 ELSE dcEducationId END
			
			INSERT INTO SearchDB..paSearchCount_1(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Experience', MinExperience, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY MinExperience ORDER BY MinExperience
	
			INSERT INTO SearchDB..paSearchCount_1(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'EmployType', EmployType, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY EmployType ORDER BY EmployType

			INSERT INTO SearchDB..paSearchCount_1(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'CompanySize', dcCompanySizeID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcCompanySizeID ORDER BY dcCompanySizeID

			INSERT INTO SearchDB..paSearchCount_1(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Salary', dcSalaryID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcSalaryID ORDER BY dcSalaryID

			INSERT INTO SearchDB..paSearchCount_1(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Industry', dcIndustryID, COUNT(*) 
			FROM #Job a WITH(NOLOCK), cpIndustry b WITH(NOLOCK)
			WHERE a.cpMainId = b.cpMainId
			GROUP BY dcIndustryID ORDER BY dcIndustryID

			INSERT INTO SearchDB..paSearchJobID_1(paSearchConditionID, JobId, IsTop)
			SELECT Top 3 @paSearchConditionID, a.JobId, 1 
			FROM SearchJobTop a WITH(NOLOCK), (SELECT TOP 2000 ID FROM #Job WITH(NOLOCK)) b 
			WHERE b.ID = a.JobId ORDER BY a.OpenDate DESC
			SET @TopRows = @@ROWCOUNT

			INSERT INTO SearchDB..paSearchJobID_1(paSearchConditionID, JobId, IsTop)
			SELECT TOP 2000 @paSearchConditionID, ID, 0 FROM #Job WITH(NOLOCK)
			SET @AllRows = @@ROWCOUNT

			IF @TopRows = 0 AND @AllRows > 100
				UPDATE SearchDB..paSearchJobID_1 SET IsTop = 1 
				WHERE paSearchConditionID = @paSearchConditionID
				AND ID IN (SELECT TOP 3 ID FROM SearchDB..paSearchJobID_1 WITH(NOLOCK) WHERE paSearchConditionID = @paSearchConditionID)
		END
		ELSE IF (@TableId = 2)
		BEGIN
			----------------------------jobtype
			INSERT INTO @sc2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'JobType', dcJobTypeID, COUNT(*)
			FROM #Job WITH(NOLOCK)
			GROUP BY dcJobTypeID ORDER BY dcJobTypeID			

			----计算全部某职位类别，2, 4位的数据
			IF @JobTypeLen NOT IN(2, 4)
			BEGIN
				INSERT INTO @Sc(paSearchConditionID, Title, TitleId, TitleValue)
				SELECT  @paSearchConditionID, 'JobType', LEFT(TitleID, 2) TitleID, SUM(TitleValue) TitleValue 
				FROM @sc2 GROUP BY LEFT(TitleID, 2)
			END
			IF @JobTypeLen NOT IN(0, 4)
			BEGIN
				INSERT INTO @Sc(paSearchConditionID, Title, TitleId, TitleValue)
				SELECT  @paSearchConditionID, 'JobType', TitleId, TitleValue
				FROM @sc2 WHERE LEN(TitleId) = 4
			END

			IF @JobTypeLen = -1
				DELETE @sc WHERE TitleID NOT IN(SELECT a FROM dbo.fnSplit(@dcJobTypeID, ','))

			INSERT INTO SearchDB..paSearchCount_2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT  @paSearchConditionID, 'JobType', TitleId, TitleValue FROM @sc
			DELETE @sc
			DELETE @sc2
			--------------------------region
			INSERT INTO @sc2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Region', dcRegionID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcRegionID ORDER BY dcRegionID
			----计算全部地区，2位的数据
			IF @JobPlaceLen IN(-1, 0)
				INSERT INTO @sc(paSearchConditionID, Title, TitleId, TitleValue)
				SELECT @paSearchConditionID, 'Region', LEFT(TitleID, 2) TitleID, SUM(TitleValue) TitleValue 
				FROM @sc2 GROUP BY LEFT(TitleID, 2)
			IF @JobPlaceLen IN(-1, 2)
				INSERT INTO @sc(paSearchConditionID, Title, TitleId, TitleValue)
				SELECT @paSearchConditionID, 'Region', LEFT(TitleID, 4) TitleID, SUM(TitleValue) TitleValue 
				FROM @sc2 WHERE LEN(TitleID) >= 4 GROUP BY LEFT(TitleID, 4)
			IF @JobPlaceLen IN(-1, 4)
				INSERT INTO @sc(paSearchConditionID, Title, TitleId, TitleValue)
				SELECT @paSearchConditionID, 'Region', TitleID, TitleValue 
				FROM @sc2 WHERE LEN(TitleID) = 6
			IF @JobPlaceLen = -1
				DELETE @sc WHERE TitleID NOT IN(SELECT ID FROM @T_JobPlace)
			ELSE
				DELETE @sc WHERE LEN(TitleID) <> @JobPlaceLen + 2

			INSERT INTO SearchDB..paSearchCount_2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT paSearchConditionID, Title, TitleId, TitleValue FROM @sc
			----------------------------
			INSERT INTO SearchDB..paSearchCount_2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Education', CASE WHEN dcEducationId IN(2, 3, 4) THEN 2 ELSE dcEducationId END, COUNT(*) 
			FROM #Job WITH(NOLOCK)
			GROUP BY CASE WHEN dcEducationId IN(2, 3, 4) THEN 2 ELSE dcEducationId END
			ORDER BY CASE WHEN dcEducationId IN(2, 3, 4) THEN 2 ELSE dcEducationId END
			
			INSERT INTO SearchDB..paSearchCount_2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Experience', MinExperience, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY MinExperience ORDER BY MinExperience

			INSERT INTO SearchDB..paSearchCount_2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Salary', dcSalaryID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcSalaryID ORDER BY dcSalaryID

			INSERT INTO SearchDB..paSearchCount_2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'EmployType', EmployType, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY EmployType ORDER BY EmployType

			INSERT INTO SearchDB..paSearchCount_2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'CompanySize', dcCompanySizeID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcCompanySizeID ORDER BY dcCompanySizeID

			INSERT INTO SearchDB..paSearchCount_2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Industry', dcIndustryID, COUNT(*) 
			FROM #Job a WITH(NOLOCK), cpIndustry b WITH(NOLOCK)
			WHERE a.cpMainId = b.cpMainId
			GROUP BY dcIndustryID ORDER BY dcIndustryID

			INSERT INTO SearchDB..paSearchJobID_2(paSearchConditionID, JobId, IsTop)
			SELECT Top 3 @paSearchConditionID, a.JobId, 1 
			FROM SearchJobTop a WITH(NOLOCK), (SELECT TOP 2000 ID FROM #Job WITH(NOLOCK)) b 
			WHERE b.ID = a.JobId ORDER BY a.OpenDate DESC
			SET @TopRows = @@ROWCOUNT

			INSERT INTO SearchDB..paSearchJobID_2(paSearchConditionID, JobId, IsTop)
			SELECT TOP 2000 @paSearchConditionID, ID, 0 FROM #Job WITH(NOLOCK)
			SET @AllRows = @@ROWCOUNT

			IF @TopRows = 0 AND @AllRows > 100
				UPDATE SearchDB..paSearchJobID_2 SET IsTop = 1 
				WHERE paSearchConditionID = @paSearchConditionID
				AND ID IN (SELECT TOP 3 ID FROM SearchDB..paSearchJobID_2 WITH(NOLOCK) WHERE paSearchConditionID = @paSearchConditionID)
		END
		ELSE IF (@TableId = 3)
		BEGIN
			----------------------------jobtype
			INSERT INTO @sc2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'JobType', dcJobTypeID, COUNT(*)
			FROM #Job WITH(NOLOCK)
			GROUP BY dcJobTypeID ORDER BY dcJobTypeID			

			----计算全部某职位类别，2, 4位的数据
			IF @JobTypeLen NOT IN(2, 4)
			BEGIN
				INSERT INTO @Sc(paSearchConditionID, Title, TitleId, TitleValue)
				SELECT  @paSearchConditionID, 'JobType', LEFT(TitleID, 2) TitleID, SUM(TitleValue) TitleValue 
				FROM @sc2 GROUP BY LEFT(TitleID, 2)
			END
			IF @JobTypeLen NOT IN(0, 4)
			BEGIN
				INSERT INTO @Sc(paSearchConditionID, Title, TitleId, TitleValue)
				SELECT  @paSearchConditionID, 'JobType', TitleId, TitleValue
				FROM @sc2 WHERE LEN(TitleId) = 4
			END

			IF @JobTypeLen = -1
				DELETE @sc WHERE TitleID NOT IN(SELECT a FROM dbo.fnSplit(@dcJobTypeID, ','))

			INSERT INTO SearchDB..paSearchCount_3(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT  @paSearchConditionID, 'JobType', TitleId, TitleValue FROM @sc
			DELETE @sc
			DELETE @sc2
			--------------------------region
			INSERT INTO @sc2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Region', dcRegionID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcRegionID ORDER BY dcRegionID
			----计算全部地区，2位的数据
			IF @JobPlaceLen IN(-1, 0)
				INSERT INTO @sc(paSearchConditionID, Title, TitleId, TitleValue)
				SELECT @paSearchConditionID, 'Region', LEFT(TitleID, 2) TitleID, SUM(TitleValue) TitleValue 
				FROM @sc2 GROUP BY LEFT(TitleID, 2)
			IF @JobPlaceLen IN(-1, 2)
				INSERT INTO @sc(paSearchConditionID, Title, TitleId, TitleValue)
				SELECT @paSearchConditionID, 'Region', LEFT(TitleID, 4) TitleID, SUM(TitleValue) TitleValue 
				FROM @sc2 WHERE LEN(TitleID) >= 4 GROUP BY LEFT(TitleID, 4)
			IF @JobPlaceLen IN(-1, 4)
				INSERT INTO @sc(paSearchConditionID, Title, TitleId, TitleValue)
				SELECT @paSearchConditionID, 'Region', TitleID, TitleValue 
				FROM @sc2 WHERE LEN(TitleID) = 6
			IF @JobPlaceLen = -1
				DELETE @sc WHERE TitleID NOT IN(SELECT ID FROM @T_JobPlace)
			ELSE
				DELETE @sc WHERE LEN(TitleID) <> @JobPlaceLen + 2

			INSERT INTO SearchDB..paSearchCount_3(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT paSearchConditionID, Title, TitleId, TitleValue FROM @sc
			----------------------------
			INSERT INTO SearchDB..paSearchCount_3(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Education', CASE WHEN dcEducationId IN(2, 3, 4) THEN 2 ELSE dcEducationId END, COUNT(*) 
			FROM #Job WITH(NOLOCK)
			GROUP BY CASE WHEN dcEducationId IN(2, 3, 4) THEN 2 ELSE dcEducationId END
			ORDER BY CASE WHEN dcEducationId IN(2, 3, 4) THEN 2 ELSE dcEducationId END
			
			INSERT INTO SearchDB..paSearchCount_3(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Experience', MinExperience, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY MinExperience ORDER BY MinExperience

			INSERT INTO SearchDB..paSearchCount_3(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Salary', dcSalaryID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcSalaryID ORDER BY dcSalaryID

			INSERT INTO SearchDB..paSearchCount_3(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'EmployType', EmployType, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY EmployType ORDER BY EmployType

			INSERT INTO SearchDB..paSearchCount_3(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'CompanySize', dcCompanySizeID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcCompanySizeID ORDER BY dcCompanySizeID

			INSERT INTO SearchDB..paSearchCount_3(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Industry', dcIndustryID, COUNT(*) 
			FROM #Job a WITH(NOLOCK), cpIndustry b WITH(NOLOCK)
			WHERE a.cpMainId = b.cpMainId
			GROUP BY dcIndustryID ORDER BY dcIndustryID

			INSERT INTO SearchDB..paSearchJobID_3(paSearchConditionID, JobId, IsTop)
			SELECT Top 3 @paSearchConditionID, a.JobId, 1 
			FROM SearchJobTop a WITH(NOLOCK), (SELECT TOP 2000 ID FROM #Job WITH(NOLOCK)) b 
			WHERE b.ID = a.JobId ORDER BY a.OpenDate DESC
			SET @TopRows = @@ROWCOUNT

			INSERT INTO SearchDB..paSearchJobID_3(paSearchConditionID, JobId, IsTop)
			SELECT TOP 2000 @paSearchConditionID, ID, 0 FROM #Job WITH(NOLOCK)
			SET @AllRows = @@ROWCOUNT

			IF @TopRows = 0 AND @AllRows > 100
				UPDATE SearchDB..paSearchJobID_3 SET IsTop = 1 
				WHERE paSearchConditionID = @paSearchConditionID
				AND ID IN (SELECT TOP 3 ID FROM SearchDB..paSearchJobID_3 WITH(NOLOCK) WHERE paSearchConditionID = @paSearchConditionID)
		END
		DROP TABLE #Job
		--PRINT 'DROP #JOB  ' + CONVERT(VARCHAR(30), GETDATE(), 121)
	COMMIT
	--GOTO GetRecordSet

	GetRecordSet:
	BEGIN
		DECLARE @AllJobCount AS INT
		----返回查询数量
		SELECT ValidJobNumber FROM SearchDB..paSearchCondition WITH(NOLOCK) WHERE ID=@paSearchConditionID
		SELECT @AllJobCount = ValidJobNumber FROM SearchDB..paSearchCondition WITH(NOLOCK) WHERE ID=@paSearchConditionID
		UPDATE SearchDB..paSearchCondition SET ReuseNumber = ReuseNumber + 1 WHERE ID=@paSearchConditionID
		----返回20行查询结果
		IF (@TableID = 0)
		BEGIN
			SELECT @MinId = MIN(ID) FROM SearchDB..paSearchJobID_0 WITH(NOLOCK) WHERE paSearchConditionID=@paSearchConditionID

			SET @MinId = @MinId+(@PageNumber-1)*@PageSize
			SELECT TOP 30 a.ID, a.cpMainID, a.caMainID, a.Name as JobName, a.MinExperience ,
				a.dcJobTypeIDMinor, a.NeedNumber, a.dcSalaryID, a.dcSalaryIDMax, a.EmployType, 
				a.dcRegionID,  a.dcEducationID, a.RefreshDate,a.SecondId EnJobID,
				b.SecondId EnCpMainID, b.Name as cpName, b.HasLicence, c.IsTop, 
				ISNULL(d.IsOnline, 0) IsOnline, d.ViPlanId, d.InterviewDate, 
				e.FullName Region, b.LogoFile LogoUrl,@AllJobCount JobNumber,
				f.Description EducationName,g.Description ExperienceName,
				h.DescriptionCp dcSalary,i.DescriptionCp dcSalaryMax
			FROM JobPublish a WITH(NOLOCK)
			INNER JOIN cpMainPublish b WITH(NOLOCK) ON a.cpMainID = b.ID 
			INNER JOIN SearchDB..paSearchJobID_0 c WITH(NOLOCK) ON a.id = c.JobID
			INNER JOIN dcRegion e WITH(NOLOCK) ON a.dcRegionId = e.Id
			LEFT JOIN caOnline d WITH(NOLOCK) ON a.caMainId = d.caMainId
			INNER JOIN dcEducation f WITH(NOLOCK) ON f.ID = a.dcEducationID
			INNER JOIN dcOthers g WITH(NOLOCK) ON g.DetailID = a.MinExperience AND g.Category='职位要求工作经验' 
			INNER JOIN dcSalary h WITH(NOLOCK) ON h.ID = a.dcSalaryID
			INNER JOIN dcSalary i WITH(NOLOCK) ON i.ID = a.dcSalaryIDMax
			WHERE paSearchConditionID=@paSearchConditionID 
			AND c.ID >= @MinId
			ORDER BY c.ID, a.ID DESC
		END
		ELSE IF (@TableID = 1)
		BEGIN
			SELECT @MinId = MIN(ID) FROM SearchDB..paSearchJobID_1 WITH(NOLOCK) WHERE paSearchConditionID=@paSearchConditionID

			SET @MinId = @MinId+(@PageNumber-1)*@PageSize
			SELECT TOP 30 a.ID, a.cpMainID, a.caMainID, a.Name as JobName, a.MinExperience ,
				a.dcJobTypeIDMinor, a.NeedNumber, a.dcSalaryID, a.dcSalaryIDMax, a.EmployType, 
				a.dcRegionID,  a.dcEducationID, a.RefreshDate,a.SecondId EnJobID,
				b.SecondId EnCpMainID, b.Name as cpName, b.HasLicence, c.IsTop, 
				ISNULL(d.IsOnline, 0) IsOnline, d.ViPlanId, d.InterviewDate, 
				e.FullName Region, b.LogoFile LogoUrl,@AllJobCount JobNumber,
				f.Description EducationName,g.Description ExperienceName,
				h.DescriptionCp dcSalary,i.DescriptionCp dcSalaryMax
			FROM JobPublish a WITH(NOLOCK)
			INNER JOIN cpMainPublish b WITH(NOLOCK) ON a.cpMainID = b.ID 
			INNER JOIN SearchDB..paSearchJobID_1 c WITH(NOLOCK) ON a.id = c.JobID
			INNER JOIN dcRegion e WITH(NOLOCK) ON a.dcRegionId = e.Id
			LEFT JOIN caOnline d WITH(NOLOCK) ON a.caMainId = d.caMainId
			INNER JOIN dcEducation f WITH(NOLOCK) ON f.ID = a.dcEducationID
			INNER JOIN dcOthers g WITH(NOLOCK) ON g.DetailID = a.MinExperience AND g.Category='职位要求工作经验' 
			INNER JOIN dcSalary h WITH(NOLOCK) ON h.ID = a.dcSalaryID
			INNER JOIN dcSalary i WITH(NOLOCK) ON i.ID = a.dcSalaryIDMax
			WHERE paSearchConditionID=@paSearchConditionID 
			AND c.ID >= @MinId
			ORDER BY c.ID, a.ID DESC
		END
		ELSE IF (@TableID = 2)
		BEGIN
			SELECT @MinId = MIN(ID) FROM SearchDB..paSearchJobID_2 WITH(NOLOCK) WHERE paSearchConditionID=@paSearchConditionID

			SET @MinId = @MinId+(@PageNumber-1)*@PageSize
			SELECT TOP 30 a.ID, a.cpMainID, a.caMainID, a.Name as JobName, a.MinExperience ,
				a.dcJobTypeIDMinor, a.NeedNumber, a.dcSalaryID, a.dcSalaryIDMax, a.EmployType, 
				a.dcRegionID,  a.dcEducationID, a.RefreshDate,a.SecondId EnJobID,
				b.SecondId EnCpMainID, b.Name as cpName, b.HasLicence, c.IsTop, 
				ISNULL(d.IsOnline, 0) IsOnline, d.ViPlanId, d.InterviewDate, 
				e.FullName Region, b.LogoFile LogoUrl,@AllJobCount JobNumber,
				f.Description EducationName,g.Description ExperienceName,
				h.DescriptionCp dcSalary,i.DescriptionCp dcSalaryMax
			FROM JobPublish a WITH(NOLOCK)
			INNER JOIN cpMainPublish b WITH(NOLOCK) ON a.cpMainID = b.ID 
			INNER JOIN SearchDB..paSearchJobID_2 c WITH(NOLOCK) ON a.id = c.JobID
			INNER JOIN dcRegion e WITH(NOLOCK) ON a.dcRegionId = e.Id
			LEFT JOIN caOnline d WITH(NOLOCK) ON a.caMainId = d.caMainId
			INNER JOIN dcEducation f WITH(NOLOCK) ON f.ID = a.dcEducationID
			INNER JOIN dcOthers g WITH(NOLOCK) ON g.DetailID = a.MinExperience AND g.Category='职位要求工作经验' 
			INNER JOIN dcSalary h WITH(NOLOCK) ON h.ID = a.dcSalaryID
			INNER JOIN dcSalary i WITH(NOLOCK) ON i.ID = a.dcSalaryIDMax
			WHERE paSearchConditionID=@paSearchConditionID 
			AND c.ID >= @MinId
			ORDER BY c.ID, a.ID DESC
		END
		ELSE IF (@TableID = 3)
		BEGIN
			SELECT @MinId = MIN(ID) FROM SearchDB..paSearchJobID_3 WITH(NOLOCK) WHERE paSearchConditionID=@paSearchConditionID

			SET @MinId = @MinId+(@PageNumber-1)*@PageSize
			SELECT TOP 30 a.ID, a.cpMainID, a.caMainID, a.Name as JobName, a.MinExperience ,
				a.dcJobTypeIDMinor, a.NeedNumber, a.dcSalaryID, a.dcSalaryIDMax, a.EmployType, 
				a.dcRegionID,  a.dcEducationID, a.RefreshDate,a.SecondId EnJobID,
				b.SecondId EnCpMainID, b.Name as cpName, b.HasLicence, c.IsTop, 
				ISNULL(d.IsOnline, 0) IsOnline, d.ViPlanId, d.InterviewDate, 
				e.FullName Region, b.LogoFile LogoUrl,@AllJobCount JobNumber,
				f.Description EducationName,g.Description ExperienceName,
				h.DescriptionCp dcSalary,i.DescriptionCp dcSalaryMax
			FROM JobPublish a WITH(NOLOCK)
			INNER JOIN cpMainPublish b WITH(NOLOCK) ON a.cpMainID = b.ID 
			INNER JOIN SearchDB..paSearchJobID_3 c WITH(NOLOCK) ON a.id = c.JobID
			INNER JOIN dcRegion e WITH(NOLOCK) ON a.dcRegionId = e.Id
			LEFT JOIN caOnline d WITH(NOLOCK) ON a.caMainId = d.caMainId
			INNER JOIN dcEducation f WITH(NOLOCK) ON f.ID = a.dcEducationID
			INNER JOIN dcOthers g WITH(NOLOCK) ON g.DetailID = a.MinExperience AND g.Category='职位要求工作经验' 
			INNER JOIN dcSalary h WITH(NOLOCK) ON h.ID = a.dcSalaryID
			INNER JOIN dcSalary i WITH(NOLOCK) ON i.ID = a.dcSalaryIDMax
			WHERE paSearchConditionID=@paSearchConditionID 
			AND c.ID >= @MinId
			ORDER BY c.ID, a.ID DESC
		END
        --RICHARD 2011-7-23 16:51分修改
		----返回统计数量
		IF @Type=1
		BEGIN
			DECLARE @RegionCount AS INT
			SELECT @RegionCount = -1
			IF CHARINDEX(',', @dcRegionID) = 0 AND LEN(@dcRegionID) > 0
			BEGIN
				IF NOT LEFT(@dcRegionID,1) = 'p'
					SELECT @RegionCount = COUNT(*) FROM dcRegion WHERE ParentID = @dcRegionID
			END
			IF (@TableID = 0)
			BEGIN
				SELECT a.*,b.Description FROM SearchDB..paSearchCount_0 a WITH(NOLOCK) LEFT JOIN dcJobType b ON b.ID = a.TitleID WHERE Title = 'JobType' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(VARCHAR(10), TitleID)
				IF @RegionCount = 0
					SELECT * FROM dcMapPlace WITH(NOLOCK) WHERE dcRegionID = @dcRegionID
				ELSE
					SELECT a.*,b.Description FROM SearchDB..paSearchCount_0 a WITH(NOLOCK) LEFT JOIN dcRegion b ON b.ID = a.TitleID WHERE Title = 'Region' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(VARCHAR(10), TitleID)
				
				SELECT a.*,b.Description FROM SearchDB..paSearchCount_0 a WITH(NOLOCK) LEFT JOIN dcEducation b ON b.ID = a.TitleID WHERE Title = 'Education' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT a.*,b.Description FROM SearchDB..paSearchCount_0 a WITH(NOLOCK) LEFT JOIN dcOthers b ON b.DetailID = a.TitleID AND Category='职位要求工作经验' WHERE Title = 'Experience' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT * FROM SearchDB..paSearchCount_0 WITH(NOLOCK) WHERE Title = 'Salary' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT a.*,b.Description FROM SearchDB..paSearchCount_0 a WITH(NOLOCK) LEFT JOIN dcOthers b ON b.DetailID = a.TitleID AND Category='工作性质' WHERE Title = 'EmployType' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT a.*,b.Description FROM SearchDB..paSearchCount_0 a WITH(NOLOCK) LEFT JOIN dcCompanySize b ON b.ID = a.TitleID WHERE Title = 'CompanySize' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
			END
			IF (@TableID = 1)
			BEGIN
				SELECT a.*,b.Description FROM SearchDB..paSearchCount_1 a WITH(NOLOCK) LEFT JOIN dcJobType b ON b.ID = a.TitleID WHERE Title = 'JobType' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(VARCHAR(10), TitleID)
				IF @RegionCount = 0
					SELECT * FROM dcMapPlace WITH(NOLOCK) WHERE dcRegionID = @dcRegionID
				ELSE
					SELECT a.*,b.Description FROM SearchDB..paSearchCount_1 a WITH(NOLOCK) LEFT JOIN dcRegion b ON b.ID = a.TitleID WHERE Title = 'Region' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(VARCHAR(10), TitleID)
				
				SELECT a.*,b.Description FROM SearchDB..paSearchCount_1 a WITH(NOLOCK) LEFT JOIN dcEducation b ON b.ID = a.TitleID WHERE Title = 'Education' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT a.*,b.Description FROM SearchDB..paSearchCount_1 a WITH(NOLOCK) LEFT JOIN dcOthers b ON b.DetailID = a.TitleID AND Category='职位要求工作经验' WHERE Title = 'Experience' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT * FROM SearchDB..paSearchCount_1 a WITH(NOLOCK) WHERE Title = 'Salary' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT a.*,b.Description FROM SearchDB..paSearchCount_1 a WITH(NOLOCK) LEFT JOIN dcOthers b ON b.DetailID = a.TitleID AND Category='工作性质' WHERE Title = 'EmployType' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT a.*,b.Description FROM SearchDB..paSearchCount_1 a WITH(NOLOCK) LEFT JOIN dcCompanySize b ON b.ID = a.TitleID WHERE Title = 'CompanySize' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
			END
			IF (@TableID = 2)
			BEGIN
				SELECT a.*,b.Description FROM SearchDB..paSearchCount_2 a WITH(NOLOCK) LEFT JOIN dcJobType b ON b.ID = a.TitleID WHERE Title = 'JobType' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(VARCHAR(10), TitleID)
				IF @RegionCount = 0
					SELECT * FROM dcMapPlace WITH(NOLOCK) WHERE dcRegionID = @dcRegionID
				ELSE
					SELECT a.*,b.Description FROM SearchDB..paSearchCount_2 a WITH(NOLOCK) LEFT JOIN dcRegion b ON b.ID = a.TitleID WHERE Title = 'Region' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(VARCHAR(10), TitleID)
				
				SELECT a.*,b.Description FROM SearchDB..paSearchCount_2 a WITH(NOLOCK) LEFT JOIN dcEducation b ON b.ID = a.TitleID WHERE Title = 'Education' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT a.*,b.Description FROM SearchDB..paSearchCount_2 a WITH(NOLOCK) LEFT JOIN dcOthers b ON b.DetailID = a.TitleID AND Category='职位要求工作经验' WHERE Title = 'Experience' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT * FROM SearchDB..paSearchCount_2 a WITH(NOLOCK) WHERE Title = 'Salary' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT a.*,b.Description FROM SearchDB..paSearchCount_2 a WITH(NOLOCK) LEFT JOIN dcOthers b ON b.DetailID = a.TitleID AND Category='工作性质' WHERE Title = 'EmployType' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT a.*,b.Description FROM SearchDB..paSearchCount_2 a WITH(NOLOCK) LEFT JOIN dcCompanySize b ON b.ID = a.TitleID WHERE Title = 'CompanySize' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
			END
			IF (@TableID = 3)
			BEGIN
				SELECT a.*,b.Description FROM SearchDB..paSearchCount_3 a WITH(NOLOCK) LEFT JOIN dcJobType b ON b.ID = a.TitleID WHERE Title = 'JobType' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(VARCHAR(10), TitleID)
				IF @RegionCount = 0
					SELECT * FROM dcMapPlace WITH(NOLOCK) WHERE dcRegionID = @dcRegionID
				ELSE
					SELECT a.*,b.Description FROM SearchDB..paSearchCount_3 a WITH(NOLOCK) LEFT JOIN dcRegion b ON b.ID = a.TitleID WHERE Title = 'Region' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(VARCHAR(10), TitleID)
				
				SELECT a.*,b.Description FROM SearchDB..paSearchCount_3 a WITH(NOLOCK) LEFT JOIN dcEducation b ON b.ID = a.TitleID WHERE Title = 'Education' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT a.*,b.Description FROM SearchDB..paSearchCount_3 a WITH(NOLOCK) LEFT JOIN dcOthers b ON b.DetailID = a.TitleID AND Category='职位要求工作经验' WHERE Title = 'Experience' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT * FROM SearchDB..paSearchCount_3 a WITH(NOLOCK) WHERE Title = 'Salary' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT a.*,b.Description FROM SearchDB..paSearchCount_3 a WITH(NOLOCK) LEFT JOIN dcOthers b ON b.DetailID = a.TitleID AND Category='工作性质' WHERE Title = 'EmployType' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT a.*,b.Description FROM SearchDB..paSearchCount_3 a WITH(NOLOCK) LEFT JOIN dcCompanySize b ON b.ID = a.TitleID WHERE Title = 'CompanySize' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
			END
		END

		RETURN
	END
END TRY
BEGIN CATCH
	---检查是否已经建立临时表，已经建立则删除
	PRINT 'error'
	PRINT error_Message()
	PRINT error_number()
	PRINT error_line()
END CATCH
GO
/****** Object:  StoredProcedure [dbo].[mblJobBySearchSelectSean]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[mblJobBySearchSelectSean]
(
	@dcJobTypeID VARCHAR(100), 		--职位类别
	@dcRegionID VARCHAR(100), 		--求职地区
	@dcIndustryID VARCHAR(100), 	--求职行业
	@KeyWord NVARCHAR(50), 			--关键词
	@PageNum INT,
	@PageSize INT
)
AS
--return
SET NOCOUNT ON
BEGIN TRY
	DECLARE @KeyWordTemp AS NVARCHAR(50),
		@dcSalaryID AS TINYINT,
		@IsNegotiable AS BIT,
		@MinExperience AS TINYINT,
		@dcEducationID AS TINYINT,
		@EmployType AS VARCHAR(10),
		@KeyType AS TINYINT,
		@SessionID AS INT,
		@ReuseNumber INT,
		@ORDER VARCHAR(100)
	
	IF @dcJobTypeID = '0'
		SET @dcJobTypeID = ''
	IF @dcRegionID = '0'
		SET @dcRegionID = ''
	IF @dcIndustryID = '0'
		SET @dcIndustryID = ''

	SET @KeyType = 1
	----给null值变量赋默认值
	SELECT @dcJobTypeID = RTRIM(dbo.FormatIDS(@dcJobTypeID)),
		@dcRegionID = RTRIM(dbo.FormatIDS(@dcRegionID)),
		@dcIndustryID = RTRIM(dbo.FormatIDS(@dcIndustryID)),
		@dcSalaryID = ISNULL(@dcSalaryID, 0),
		@IsNegotiable = ISNULL(@IsNegotiable, 0),
		@MinExperience = ISNULL(@MinExperience, 100),
		@dcEducationID = ISNULL(@dcEducationID, 0),
		@EmployType = CASE @EmployType WHEN '2' THEN '1,3' ELSE ISNULL(@EmployType, '') END,
		@KeyWord = REPLACE(dbo.SafeSQL(ISNULL(@KeyWord, '')), '''', ''),
		@KeyType = CASE @KeyWord WHEN NULL THEN 0 ELSE @KeyType END,
		@PageNum = ISNULL(@PageNum, 0),
		@ORDER = ' ORDER BY a.RefreshDate DESC, a.ID'

	IF (@KeyWord IS NOT NULL)
		SET @KeyWordTemp = @KeyWord
	IF LEN(@KeyWordTemp) > 2
		SET @KeyWordTemp = REPLACE(@KeyWordTemp, '公司', '')

	IF(@KeyType = 0 AND ISNULL(@dcJobTypeID, '') = '' AND ISNULL(@dcRegionID, '') = '' AND ISNULL(@dcIndustryID, '') = '')
		RETURN

	IF RIGHT(@dcJobTypeID, 1) = ','
		SET @dcJobTypeID = LEFT(@dcJobTypeID, LEN(@dcJobTypeID) - 1)
	IF RIGHT(@dcRegionID, 1) = ','
		SET @dcRegionID = LEFT(@dcRegionID, LEN(@dcRegionID) - 1)
	IF RIGHT(@dcIndustryID, 1) = ','
		SET @dcIndustryID = LEFT(@dcIndustryID, LEN(@dcIndustryID) - 1)

	DECLARE @paSearchConditionID AS INT, 
		@MinId AS INT, 
		@TableID AS TINYINT

	SELECT @paSearchConditionID = 0, @SessionID = ISNULL(@SessionID, 9902)  --每页的行数
	
	----搜索1分钟前的数据
	SELECT TOP 1 @paSearchConditionID = ID,
			@ReuseNumber = ReuseNumber
	FROM SearchDB..paSearchCondition WITH(NOLOCK)
	WHERE JobType=@dcJobTypeID
	AND JobPlace=@dcRegionID AND Industry=@dcIndustryID AND Education=@dcEducationID
	AND Experience=@MinExperience AND Salary=@dcSalaryID AND IsNegotiable=@IsNegotiable 
	AND EmployType=@EmployType AND KeyWord=@KeyWord AND KeyType=@KeyType
	AND CompanySizeID IS NULL
	AND Welfare IS NULL
	AND IsDelete = 0
	ORDER BY ID DESC

	IF @ReuseNumber = 0
	BEGIN
		SELECT TOP 1 @paSearchConditionID = ID
		FROM SearchDB..paSearchCondition WITH(NOLOCK)
		WHERE SessionID=@SessionID AND JobType=@dcJobTypeID
		AND JobPlace=@dcRegionID AND Industry=@dcIndustryID AND Education=@dcEducationID
		AND Experience=@MinExperience AND Salary=@dcSalaryID AND IsNegotiable=@IsNegotiable 
		AND EmployType=@EmployType AND KeyWord=@KeyWord AND KeyType=@KeyType
		AND CompanySizeID IS NULL
		AND Welfare IS NULL
		AND ReuseNumber > 0
		ORDER BY ID DESC
	END

	IF ISNULL(@paSearchConditionID, 0) = 0
	BEGIN
		GOTO SelectReset	--无数据，重新搜索
	END
	ELSE
	BEGIN
		SELECT @TableID = @paSearchConditionID % 4
		GOTO GetRecordSet	--从临时结果中提取数据
	END

	SelectReset:				--从job中搜索数据
	BEGIN TRAN
		DECLARE @SQL AS VARCHAR(8000)
		DECLARE @WHERE AS VARCHAR(8000)
		DECLARE @FROM AS VARCHAR(1000)
		----记录查询条件
		INSERT INTO SearchDB..paSearchCondition(SessionID, LogTime, JobType, JobPlace, Industry, Education, Experience, 
			Salary, IsNegotiable, EmployType, KeyWord, KeyType, ReuseNumber, Welfare)
		VALUES(
			ISNULL(@SessionId, 9902), GETDATE(), @dcJobTypeID, @dcRegionID, @dcIndustryID, @dcEducationID, @MinExperience, 
			@dcSalaryID, @IsNegotiable, @EmployType, @KeyWord, @KeyType, 0, '')
		SET @paSearchConditionID = @@IDENTITY
		SELECT @TableID = @paSearchConditionID % 4

		------生成职位类别的表变量，因为职位类别有包含（父子）关系
		DECLARE @T_JobPlace AS TABLE(ID INT)
		DECLARE @T_JobType AS TABLE(ID INT)
		DECLARE @JobType AS VARCHAR(3000)
		DECLARE @JobPlace AS VARCHAR(2000)
		DECLARE @ValidJobNumber AS INT

		SET @JobPlace = ''
		SET @JobType=''
		----生成工作地点的表变量
		IF LEN(@dcRegionID) > 0
		BEGIN
			INSERT INTO @T_JobPlace
			SELECT * FROM dbo.fnSplit(@dcRegionID, ',')
			SELECT @JobPlace = (@JobPlace + ' OR a.dcRegionID Like ''' + LTRIM(STR(ID) + '%''')) FROM @T_JobPlace
			IF LEN(@JobPlace) > 0
				SET @JobPlace = RIGHT(@JobPlace, LEN(@JobPlace) -4)
		END

		----生成求聘职位的表变量
		IF LEN(@dcJobTypeID) > 0
		BEGIN
			DECLARE @T_Temp AS TABLE(ID INT)		--临时表，用于构建组合查询语句
			INSERT INTO @T_Temp
			SELECT * FROM dbo.fnSplit(@dcJobTypeID, ',')

			INSERT INTO @T_JobType
			SELECT DISTINCT ID FROM dcJobType WITH(NOLOCK)
			WHERE ParentId IN(SELECT ID FROM @T_TEMP) 
			OR ParentId2 in(SELECT ID FROM @T_TEMP)
			OR ID IN(SELECT ID FROM @T_TEMP)
			----生成in字符串
			SELECT @JobType = (@JobType + LTRIM(STR(ID) + ',')) FROM @T_JobType
			IF RIGHT(@JobType, 1) = ','
				SET @JobType = LEFT(@JobType, LEN(@JobType) - 1)
		END

		----建立临时表
		CREATE TABLE #Job(
			RowID INT IDENTITY(1, 1), 
			ID INT NOT NULL, 
			dcJobTypeID SMALLINT NOT NULL, 
			dcJobTypeIDMinor SMALLINT NULL, 
			dcSalaryID TINYINT NOT NULL, 
			dcRegionID VARCHAR(6) NULL, 
			dcEducationID TINYINT NOT NULL, 
			MinExperience TINYINT NOT NULL, 
			RefreshDate SMALLDATETIME NULL
		)

		CREATE TABLE #FullText(
			Priority INT,
			JobId INT NOT NULL
		)
		------刷新时间，根据刷新时间编号计算
		----生成插入临时表的Sql语句
		SET @SQL='
			INSERT INTO #Job
			SELECT a.ID, a.dcJobTypeID, 
				a.dcJobTypeIDMinor, a.dcSalaryID, 
				a.dcRegionID, a.dcEducationID, a.MinExperience, 
				a.IssueDate'
		SET @FROM = '
			FROM JobPublish a WITH(NOLOCK)
			INNER JOIN cpMainPublish b WITH(NOLOCK) ON a.cpMainID=b.ID'
		----职位有效，单位新有效
		IF LEN(@dcIndustryID) > 0
			SET @WHERE = '
			WHERE b.ID IN (SELECT cpMainID FROM cpIndustry WHERE dcIndustryId in(' + @dcIndustryID + '))
			AND a.Valid = 1
			AND b.Valid = 1'
		ELSE
			SET @WHERE = '
			WHERE a.Valid = 1
			AND b.Valid = 1'
		----需要增加全文索引的关键字查询
		IF @KeyWord LIKE '% %'
		BEGIN
			SET @KeyWord = REPLACE(@KeyWord, '  ', ' ')
			SET @KeyWord = REPLACE(@KeyWord, '  ', ' ')
			SET @KeyWord = REPLACE(@KeyWord, '  ', ' ')
			SET @KeyWord = '"' + REPLACE(@KeyWord, ' ', '" OR "') + '"'
		END
		IF @KeyWordTemp LIKE '% %'
		BEGIN
			SET @KeyWordTemp = REPLACE(@KeyWordTemp, '  ', ' ')
			SET @KeyWordTemp = REPLACE(@KeyWordTemp, '  ', ' ')
			SET @KeyWordTemp = REPLACE(@KeyWordTemp, '  ', ' ')
			SET @KeyWordTemp = '"' + REPLACE(@KeyWordTemp, ' ', '" OR "') + '"'
		END

		----职位类别
		IF LEN(@dcJobTypeID) > 0
			SET @WHERE = @WHERE + '
			AND (a.dcJobTypeID IN(' + @JobType +')
				OR a.dcJobTypeIDMinor IN(' +@JobType + '))'
		IF LEN(@JobPlace) > 0 
			SET @WHERE = @WHERE + '
			AND (' + @JobPlace + ')'

		IF LEN(@KeyWord) > 0 AND @KeyType = 1	----使用全文搜索job和cpmain2个表，经过测试发现union最快
			IF EXISTS(SELECT TOP 1 'x' FROM cpMainPublish WITH(NOLOCK) WHERE Name = @KeyWord)
			BEGIN
				SET @WHERE = @WHERE + '
			AND b.Name = ''' + @KeyWord + ''''
				SET @SQL = @SQL + @FROM + @WHERE
			END
			ELSE
			BEGIN
				INSERT #FullText
				SELECT 1, [Key]
				FROM CONTAINSTABLE(JobPublish, Name, @KeyWord, 100000) AS KeyJob

				INSERT #FullText
				SELECT 2, a.ID
				FROM JobPublish a WITH(NOLOCK),
					CONTAINSTABLE(cpMainPublish, Name, @KeyWord, 100000) AS b
				WHERE a.cpMainId = b.[Key]
				DELETE #FullText WHERE Priority = 2 AND JobId IN(SELECT JobId FROM #FullText WHERE Priority = 1)

				IF (SELECT COUNT(*) FROM #FullText) < 5000
				BEGIN
					INSERT #FullText
					SELECT 3, [Key]
					FROM CONTAINSTABLE(JobPublish, *, @KeyWord, 100000) AS KeyJob
					DELETE #FullText WHERE Priority = 3 AND JobId IN(SELECT JobId FROM #FullText WHERE Priority < 3)

					IF (SELECT COUNT(*) FROM #FullText) < 5000
					BEGIN
						INSERT #FullText
						SELECT 4, a.ID
						FROM JobPublish a WITH(NOLOCK),
							CONTAINSTABLE(cpMainPublish, *, @KeyWord, 100000) AS b
						WHERE a.cpMainId = b.[Key]
					
						DELETE #FullText WHERE Priority = 4 AND JobId IN(SELECT JobId FROM #FullText WHERE Priority < 4)
					END
				END
				--------------------
				SELECT @FROM = @FROM + '
			INNER JOIN #FullText ON a.ID = #FullText.JobId',
					@ORDER = ' ORDER BY #FullText.Priority, a.RefreshDate DESC, a.ID'
				SET @SQL = @SQL + @FROM + @WHERE
			END
		ELSE
			SET @SQL = @SQL + @FROM + @WHERE
		
		SET @SQL = @SQL + @ORDER
		EXEC(@SQL)
		
		SET @ValidJobNumber = @@ROWCOUNT
		----记录查询结果总数
		UPDATE SearchDB..paSearchCondition SET ValidJobNumber=@ValidJobNumber, SQl=@SQL WHERE ID=@paSearchConditionID
		
		----插入JobType数据
		IF (@TableID = 0)
		BEGIN		
			INSERT INTO SearchDB..paSearchJobID_0(paSearchConditionID, JobId, IsTop)
			SELECT TOP 2000 @paSearchConditionID, ID, 0 FROM #Job WITH(NOLOCK)
		END
		ELSE IF (@TableId = 1)
		BEGIN
			INSERT INTO SearchDB..paSearchJobID_1(paSearchConditionID, JobId, IsTop)
			SELECT TOP 2000 @paSearchConditionID, ID, 0 FROM #Job WITH(NOLOCK)
		END
		ELSE IF (@TableId = 2)
		BEGIN
			INSERT INTO SearchDB..paSearchJobID_2(paSearchConditionID, JobId, IsTop)
			SELECT TOP 2000 @paSearchConditionID, ID, 0 FROM #Job WITH(NOLOCK)
		END
		ELSE IF (@TableId = 3)
		BEGIN
			INSERT INTO SearchDB..paSearchJobID_3(paSearchConditionID, JobId, IsTop)
			SELECT TOP 2000 @paSearchConditionID, ID, 0 FROM #Job WITH(NOLOCK)
		END
		DROP TABLE #Job
	COMMIT

	GetRecordSet:
	BEGIN
		----返回查询数量
		SELECT @ValidJobNumber=ValidJobNumber FROM SearchDB..paSearchCondition WITH(NOLOCK) WHERE ID=@paSearchConditionID
		UPDATE SearchDB..paSearchCondition SET ReuseNumber = ReuseNumber + 1 WHERE ID=@paSearchConditionID
		----返回20行查询结果
		IF (@TableID = 0)
		BEGIN
			SELECT @MinId = MIN(ID) FROM SearchDB..paSearchJobID_0 WITH(NOLOCK) WHERE paSearchConditionID=@paSearchConditionID

			SET @MinId = @MinId+(@PageNum-1)*@PageSize
			SELECT TOP 20 @ValidJobNumber AS cnt, a.ID,a.Name AS JobName,a.RefreshDate,b.Name cpName,
			d.FullName Region, a.SecondId EnJobID, b.SecondId EnCpMainID
			FROM JOBPublish a WITH(NOLOCK), cpMainPublish b WITH(NOLOCK), SearchDB..paSearchJobID_0 c WITH(NOLOCK),
			dcRegion d WITH(NOLOCK)
			WHERE a.cpMainID = b.ID AND a.id=c.JobID AND a.dcRegionID=d.ID AND c.paSearchConditionID=@paSearchConditionID 
				  AND c.ID>=@MinId ORDER BY c.ID, a.ID DESC
		END
		ELSE IF (@TableID = 1)
		BEGIN
			SELECT @MinId = MIN(ID) FROM SearchDB..paSearchJobID_1 WITH(NOLOCK) WHERE paSearchConditionID=@paSearchConditionID

			SET @MinId = @MinId+(@PageNum-1)*@PageSize
			SELECT TOP 20 @ValidJobNumber AS cnt, a.ID,a.Name AS JobName,a.RefreshDate,b.Name cpName,
			d.FullName Region, a.SecondId EnJobID, b.SecondId EnCpMainID
			FROM JOBPublish a WITH(NOLOCK), cpMainPublish b WITH(NOLOCK), SearchDB..paSearchJobID_1 c WITH(NOLOCK),
			dcRegion d WITH(NOLOCK)
			WHERE a.cpMainID = b.ID AND a.id=c.JobID AND a.dcRegionID=d.ID AND c.paSearchConditionID=@paSearchConditionID 
				  AND c.ID>=@MinId ORDER BY c.ID, a.ID DESC
		END
		ELSE IF (@TableID = 2)
		BEGIN
			SELECT @MinId = MIN(ID) FROM SearchDB..paSearchJobID_2 WITH(NOLOCK) WHERE paSearchConditionID=@paSearchConditionID

			SET @MinId = @MinId+(@PageNum-1)*@PageSize
			SELECT TOP 20 @ValidJobNumber AS cnt, a.ID,a.Name AS JobName,a.RefreshDate,b.Name cpName,
			d.FullName Region, a.SecondId EnJobID, b.SecondId EnCpMainID
			FROM JOBPublish a WITH(NOLOCK), cpMainPublish b WITH(NOLOCK), SearchDB..paSearchJobID_2 c WITH(NOLOCK),
			dcRegion d WITH(NOLOCK)
			WHERE a.cpMainID = b.ID AND a.id=c.JobID AND a.dcRegionID=d.ID AND c.paSearchConditionID=@paSearchConditionID 
				  AND c.ID>=@MinId ORDER BY c.ID, a.ID DESC
		END
		ELSE IF (@TableID = 3)
		BEGIN
			SELECT @MinId = MIN(ID) FROM SearchDB..paSearchJobID_3 WITH(NOLOCK) WHERE paSearchConditionID=@paSearchConditionID

			SET @MinId = @MinId+(@PageNum-1)*@PageSize
			SELECT TOP 20 @ValidJobNumber AS cnt, a.ID,a.Name AS JobName,a.RefreshDate,b.Name cpName,
			d.FullName Region, a.SecondId EnJobID, b.SecondId EnCpMainID
			FROM JOBPublish a WITH(NOLOCK), cpMainPublish b WITH(NOLOCK), SearchDB..paSearchJobID_3 c WITH(NOLOCK),
			dcRegion d WITH(NOLOCK)
			WHERE a.cpMainID = b.ID AND a.id=c.JobID AND a.dcRegionID=d.ID AND c.paSearchConditionID=@paSearchConditionID 
				  AND c.ID>=@MinId ORDER BY c.ID, a.ID DESC
		END
		RETURN
	END
END TRY
BEGIN CATCH
	---检查是否已经建立临时表，已经建立则删除
	PRINT 'error'
	PRINT error_Message()
	PRINT error_number()
	PRINT error_line()
END CATCH










GO
/****** Object:  StoredProcedure [dbo].[mblJobByWeixinSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[mblJobByWeixinSelect] 
(
	@FromUserName VARCHAR(50),
	@Type INT		--0：订阅号关键词查询；10：服务号的关键词查询；11：服务号的周边职位
)
AS
insert into proclog select 'mblJobByWeixinSelect', LTRIM(STR(@Type)) + ' ' + @FromUserName, getdate()
SET NOCOUNT ON
BEGIN TRY
	DECLARE @dcRegionID VARCHAR(4),@KeyWord NVARCHAR(20),
		@Lng DECIMAL(8,5),@Lat DECIMAL(8,5),@Distance INT,
		@KeyType TINYINT, @ValidJobNumber INT, @PageNumber SMALLINT

	IF @Type =11
	BEGIN
		SELECT @dcRegionID=dcRegionID,@KeyWord=KeyWord,
			@Lng=Lng,@Lat=Lat,@PageNumber=PageNumber
		FROM wxMessage WITH(NOLOCK) 
		WHERE FromUserName=@FromUserName AND CONTENT='推荐职位'

		DELETE FROM wxMessage WHERE FromUserName=@FromUserName AND CONTENT <> '推荐职位'
	END
	ELSE
	BEGIN
		SELECT TOP 1 @dcRegionID=dcRegionID,@KeyWord=KeyWord,@PageNumber=PageNumber
		FROM wxMessage WITH(NOLOCK) WHERE FromUserName=@FromUserName
		ORDER BY ID DESC

		DELETE FROM wxMessage WHERE FromUserName=@FromUserName AND CONTENT='推荐职位'
	END

	IF @Type =11 OR @Type = 10
	BEGIN
		UPDATE wxMessage SET PageNumber = 2 WHERE FromUserName=@FromUserName
	END
	ELSE
	BEGIN
		UPDATE wxMessage SET PageNumber=PageNumber+1 WHERE FromUserName=@FromUserName
	END


	--UPDATE wxMessage SET PageNumber=PageNumber+1 WHERE FromUserName=@FromUserName
	SELECT @KeyWord = dbo.SafeSQL(ISNULL(@KeyWord, '')),
		@KeyType = 2,
		@Distance = 5000,
		@PageNumber = ISNULL(@PageNumber, 1),
		@dcRegionID = ISNULL(@dcRegionID, 0),
		@Lng = ISNULL(@Lng, 0),
		@Lat = ISNULL(@Lat, 0)

	IF @dcRegionID = 0 AND @Lng = 0 AND @Lat = 0
		RETURN

	DECLARE @paSearchConditionID AS INT, 
		@MinId AS INT, 
		@PageSize AS TINYINT, 
		@TableID AS TINYINT


	IF @Type =11 OR  @Type =10
	BEGIN
		SELECT @paSearchConditionID = 0, @PageSize = 5  --每页的行数
	END 
	ELSE 
	BEGIN
		SELECT @paSearchConditionID = 0, @PageSize = 8  --每页的行数
	END

	--SELECT @paSearchConditionID = 0, @PageSize = 8  --每页的行数
	
	----搜索60分钟前的数据
	SELECT TOP 1 @paSearchConditionID=ID FROM SearchDB..paSearchCondition WITH(NOLOCK)
	WHERE JobType=''
	AND JobPlace=@dcRegionID AND ISNULL(Industry,'')='' AND ISNULL(Education,'')=''
	AND ISNULL(Experience,'')='' AND ISNULL(Salary,'')='' AND ISNULL(IsNegotiable,'')='' 
	AND ISNULL(EmployType,'')='' AND KeyWord=@KeyWord AND KeyType=@KeyType
	AND ISNULL(CompanySizeID,'')='' AND Lng=@Lng AND Lat=@Lat
	ORDER BY ID DESC

	IF ISNULL(@paSearchConditionID, 0) = 0
	BEGIN
		GOTO SelectReset	--无数据，重新搜索
	END
	ELSE
	BEGIN
		SELECT @TableID = @paSearchConditionID % 4
		GOTO GetRecordSet	--从临时结果中提取数据
	END

	SelectReset:
	--从job中搜索数据
	BEGIN TRAN
		DECLARE @SQL AS VARCHAR(8000)
		DECLARE @WHERE AS VARCHAR(8000)
		DECLARE @FROM AS VARCHAR(1000)
		----记录查询条件
		INSERT INTO SearchDB..paSearchCondition(SessionID, LogTime, JobType, JobPlace, Industry, Education, Experience, 
			Salary, IsNegotiable, EmployType, CompanySizeID, KeyWord, KeyType, ReuseNumber, Lng, Lat, Distance)
		VALUES(1, GETDATE(), '', @dcRegionID, '', '', '', '', '', '', '', @KeyWord, @KeyType, 0, @Lng, @Lat, @Distance)
		SET @paSearchConditionID = @@IDENTITY
		SELECT @TableID = @paSearchConditionID % 4

		----建立临时表
		CREATE TABLE #Job(
			RowID INT IDENTITY(1, 1), 
			ID INT NOT NULL, 
			dcJobTypeID SMALLINT NOT NULL, 
			dcJobTypeIDMinor SMALLINT NULL, 
			dcSalaryID TINYINT NOT NULL, 
			dcRegionID VARCHAR(6) NULL, 
			dcEducationID TINYINT NOT NULL, 
			MinExperience TINYINT NOT NULL, 
			RefreshDate SMALLDATETIME NULL
		)
		------刷新时间，根据刷新时间编号计算
		----生成插入临时表的Sql语句
		SET @SQL='
			INSERT INTO #Job
			SELECT a.ID, a.dcJobTypeID, 
				a.dcJobTypeIDMinor, a.dcSalaryID, 
				a.dcRegionID, a.dcEducationID, a.MinExperience, 
				a.IssueDate'
		SET @FROM = '
			FROM JobPublish a WITH(NOLOCK)
			INNER JOIN cpMainPublish b WITH(NOLOCK) ON a.cpMainID=b.ID'
		----职位有效，单位新有效
		SET @WHERE = '
			WHERE a.Valid = 1
			AND b.Valid = 1'
		----需要增加全文索引的关键字查询
		IF @KeyWord LIKE '% %'
		BEGIN
			SET @KeyWord = REPLACE(@KeyWord, '  ', ' ')
			SET @KeyWord = REPLACE(@KeyWord, '  ', ' ')
			SET @KeyWord = REPLACE(@KeyWord, '  ', ' ')
			SET @KeyWord = '"' + REPLACE(@KeyWord, ' ', '" OR "') + '"'
		END

		IF LEN(@KeyWord) > 0
		BEGIN
			IF @KeyType = 2
				SET @FROM = @FROM + '
			INNER JOIN CONTAINSTABLE(JobPublish, *, ''' + @KeyWord + ''', 1000000) AS KeyJob
			ON a.ID = KeyJob.[Key]'
		END
		---地区
		IF @dcRegionID > 0 
			SET @WHERE = @WHERE + '
			AND a.dcRegionID Like ''' + CONVERT(VARCHAR(6),@dcRegionID) + '%'''

		IF @Lng > 0 AND @Lat > 0
		BEGIN
			DECLARE @Degree AS DECIMAL(8,5),@LBLng AS DECIMAL(8,5),@LBLat AS DECIMAL(8,5),
			@RTLng AS DECIMAL(8,5),@RTLat AS DECIMAL(8,5)
			SET @Degree = @Distance / 100000.0;

			SET @LBLng = @Lng - @Degree
			SET @LBLat = @Lat - @Degree
			SET @RTLng = @Lng + @Degree
			SET @RTLat = @Lat + @Degree
			SET @WHERE = @WHERE + '
				AND a.Lng BETWEEN ' + CONVERT(VARCHAR,@LBLng) + ' AND ' + CONVERT(VARCHAR,@RTLng) + '
				AND a.Lat BETWEEN ' + CONVERT(VARCHAR,@LBLat) + ' AND ' + CONVERT(VARCHAR,@RTLat)
		END
		SET @SQL = @SQL + @FROM + @WHERE
		
		SET @SQL=@SQL + ' ORDER BY a.RefreshDate DESC, a.ID'

		----把符合条件的职位全部列出
		--PRINT @SQL
		EXEC(@SQL)
		
		SET @ValidJobNumber = @@ROWCOUNT
		----记录查询结果总数
		UPDATE SearchDB..paSearchCondition SET ValidJobNumber=@ValidJobNumber, SQl=@SQL WHERE ID=@paSearchConditionID
		
		----插入JobType数据
		DECLARE @TitleValue AS INT, @TopRows AS INT, @AllRows AS INT
		IF (@TableID = 0)
		BEGIN
			INSERT INTO SearchDB..paSearchCount_0(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'JobType', dcJobTypeID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcJobTypeID ORDER BY dcJobTypeID
			----计算全部某职位类别，2, 4位的数据
			UPDATE a SET a.TitleValue = b.TitleValue
			FROM SearchDB..paSearchCount_0 a WITH(NOLOCK), 
				(SELECT LEFT(TitleID, 2) TitleID, SUM(TitleValue) TitleValue
				FROM SearchDB..paSearchCount_0 WITH(NOLOCK)
				WHERE paSearchConditionID = @paSearchConditionID AND Title = 'JobType'
				GROUP BY LEFT(TitleID, 2)) b
			WHERE a.TitleId = b.TitleID
			AND a.paSearchConditionID = @paSearchConditionID AND a.Title = 'JobType'
			----写入TitleDesc
			UPDATE a SET a.TitleDesc = b.Description
			FROM SearchDB..paSearchCount_0 a WITH(NOLOCK), dcJobType b WITH(NOLOCK)
			WHERE a.TitleID = b.ID AND a.paSearchConditionID = @paSearchConditionID
			AND a.Title = 'JobType'
			
			INSERT INTO SearchDB..paSearchCount_0(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Salary', dcSalaryID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcSalaryID ORDER BY dcSalaryID

			INSERT INTO SearchDB..paSearchCount_0(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Region', dcRegionID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcRegionID ORDER BY dcRegionID
			----计算全部地区，2位的数据
			UPDATE a SET a.TitleValue = b.TitleValue
			FROM SearchDB..paSearchCount_0 a WITH(NOLOCK), 
			(SELECT LEFT(TitleID, 2) TitleID, SUM(TitleValue) TitleValue
			FROM SearchDB..paSearchCount_0 WITH(NOLOCK)
			WHERE paSearchConditionID = @paSearchConditionID AND Title = 'Region'
			GROUP BY LEFT(TitleID, 2)) b
			WHERE a.TitleId = b.TitleID
			AND a.paSearchConditionID = @paSearchConditionID AND a.Title = 'Region'
			----计算全部地区，4位的数据
			UPDATE a SET a.TitleValue = b.TitleValue
			FROM SearchDB..paSearchCount_0 a WITH(NOLOCK), (
				SELECT LEFT(TitleID, 4) TitleID, SUM(TitleValue) TitleValue
				FROM SearchDB..paSearchCount_0 WITH(NOLOCK)
				WHERE paSearchConditionID = @paSearchConditionID AND Title = 'Region'
				AND LEN(TitleID) >3
				GROUP BY LEFT(TitleID, 4)) b
			WHERE a.TitleId = b.TitleID
			AND a.paSearchConditionID = @paSearchConditionID AND a.Title = 'Region'
			----写入TitleDesc
			UPDATE a SET a.TitleDesc = b.Description
			FROM SearchDB..paSearchCount_0 a WITH(NOLOCK), dcRegion b WITH(NOLOCK)
			WHERE a.TitleID = b.ID AND a.paSearchConditionID = @paSearchConditionID
			AND a.Title = 'Region'

			INSERT INTO SearchDB..paSearchCount_0(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Education', dcEducationID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcEducationID ORDER BY dcEducationID
			--学历 高中、中专、中级合并		
			SELECT @TitleValue = SUM(TitleValue) FROM SearchDB..paSearchCount_0 WITH(NOLOCK)
			WHERE paSearchConditionID = @paSearchConditionID
			AND Title = 'Education' AND TitleID IN(2, 3, 4)		
			IF @TitleValue IS NOT NULL
			BEGIN
				IF EXISTS(SELECT 'X' FROM SearchDB..paSearchCount_0 WITH(NOLOCK) WHERE paSearchConditionID = @paSearchConditionID AND Title = 'Education' AND TitleID = 2)
					UPDATE SearchDB..paSearchCount_0 SET TitleValue = @TitleValue 
					WHERE paSearchConditionID = @paSearchConditionID
					AND Title = 'Education' AND TitleID = 2
				ELSE
					INSERT INTO SearchDB..paSearchCount_0(paSearchConditionID, Title, TitleId, TitleValue) VALUES
					(@paSearchConditionID, 'Education', 2, @TitleValue)

				DELETE FROM SearchDB..paSearchCount_0
				WHERE paSearchConditionID = @paSearchConditionID
				AND Title = 'Education' AND TitleID IN(3, 4)
			END 

			INSERT INTO SearchDB..paSearchCount_0(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Experience', MinExperience, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY MinExperience ORDER BY MinExperience
			
			INSERT INTO SearchDB..paSearchJobID_0(paSearchConditionID, JobId, IsTop)
			SELECT Top 3 @paSearchConditionID,Balance,1 
			FROM caOrder WITH(NOLOCK), (SELECT TOP 2000 ID FROM #Job WITH(NOLOCK)) b 
			WHERE caOrder.OrderType = 12 AND BeginDate<GETDATE() AND EndDate>GETDATE() AND b.ID = caOrder.Balance ORDER BY OpenDate DESC
			SET @TopRows = @@ROWCOUNT

			INSERT INTO SearchDB..paSearchJobID_0(paSearchConditionID, JobId, IsTop)
			SELECT TOP 2000 @paSearchConditionID, ID, 0 FROM #Job WITH(NOLOCK)
			SET @AllRows = @@ROWCOUNT

			IF @TopRows = 0 AND @AllRows > 100
				UPDATE SearchDB..paSearchJobID_0 SET IsTop = 1 
				WHERE paSearchConditionID = @paSearchConditionID
				AND ID IN (SELECT TOP 3 ID FROM SearchDB..paSearchJobID_0 WITH(NOLOCK) WHERE paSearchConditionID = @paSearchConditionID)
		END
		ELSE IF (@TableId = 1)
		BEGIN
			INSERT INTO SearchDB..paSearchCount_1(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'JobType', dcJobTypeID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcJobTypeID ORDER BY dcJobTypeID
			----计算全部某职位类别，2, 4位的数据
			UPDATE a SET a.TitleValue = b.TitleValue
			FROM SearchDB..paSearchCount_1 a WITH(NOLOCK), 
			(SELECT LEFT(TitleID, 2) TitleID, SUM(TitleValue) TitleValue
			FROM SearchDB..paSearchCount_1 WITH(NOLOCK)
			WHERE paSearchConditionID = @paSearchConditionID AND Title = 'JobType'
			GROUP BY LEFT(TitleID, 2)) b
			WHERE a.TitleId = b.TitleID
			AND a.paSearchConditionID = @paSearchConditionID AND a.Title = 'JobType'
			----写入TitleDesc
			UPDATE a SET a.TitleDesc = b.Description
			FROM SearchDB..paSearchCount_1 a WITH(NOLOCK), dcJobType b WITH(NOLOCK)
			WHERE a.TitleID = b.ID AND a.paSearchConditionID = @paSearchConditionID
			AND a.Title = 'JobType'
			
			INSERT INTO SearchDB..paSearchCount_1(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Salary', dcSalaryID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcSalaryID ORDER BY dcSalaryID

			INSERT INTO SearchDB..paSearchCount_1(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Region', dcRegionID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcRegionID ORDER BY dcRegionID
			----计算全部地区，2位的数据
			UPDATE a SET a.TitleValue = b.TitleValue
			FROM SearchDB..paSearchCount_1 a WITH(NOLOCK), 
			(SELECT LEFT(TitleID, 2) TitleID, SUM(TitleValue) TitleValue
			FROM SearchDB..paSearchCount_1 WITH(NOLOCK)
			WHERE paSearchConditionID = @paSearchConditionID AND Title = 'Region'
			GROUP BY LEFT(TitleID, 2)) b
			WHERE a.TitleId = b.TitleID
			AND a.paSearchConditionID = @paSearchConditionID AND a.Title = 'Region'
			----计算全部地区，4位的数据
			UPDATE a SET a.TitleValue = b.TitleValue
			FROM SearchDB..paSearchCount_1 a WITH(NOLOCK), (
				SELECT LEFT(TitleID, 4) TitleID, SUM(TitleValue) TitleValue
				FROM SearchDB..paSearchCount_1 WITH(NOLOCK)
				WHERE paSearchConditionID = @paSearchConditionID AND Title = 'Region'
				AND LEN(TitleID) >3
				GROUP BY LEFT(TitleID, 4)) b
			WHERE a.TitleId = b.TitleID
			AND a.paSearchConditionID = @paSearchConditionID AND a.Title = 'Region'
			----写入TitleDesc
			UPDATE a SET a.TitleDesc = b.Description
			FROM SearchDB..paSearchCount_1 a WITH(NOLOCK), dcRegion b WITH(NOLOCK)
			WHERE a.TitleID = b.ID AND a.paSearchConditionID = @paSearchConditionID
			AND a.Title = 'Region'

			INSERT INTO SearchDB..paSearchCount_1(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Education', dcEducationID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcEducationID ORDER BY dcEducationID
			--学历 高中、中专、中级合并		
			SELECT @TitleValue = SUM(TitleValue) FROM SearchDB..paSearchCount_1 WITH(NOLOCK)
			WHERE paSearchConditionID = @paSearchConditionID
			AND Title = 'Education' AND TitleID IN(2, 3, 4)		
			IF @TitleValue IS NOT NULL
			BEGIN
				IF EXISTS(SELECT 'X' FROM SearchDB..paSearchCount_1 WITH(NOLOCK) WHERE paSearchConditionID = @paSearchConditionID AND Title = 'Education' AND TitleID = 2)
					UPDATE SearchDB..paSearchCount_1 SET TitleValue = @TitleValue 
					WHERE paSearchConditionID = @paSearchConditionID
					AND Title = 'Education' AND TitleID = 2
				ELSE
					INSERT INTO SearchDB..paSearchCount_1(paSearchConditionID, Title, TitleId, TitleValue) VALUES
					(@paSearchConditionID, 'Education', 2, @TitleValue)

				DELETE FROM SearchDB..paSearchCount_1
				WHERE paSearchConditionID = @paSearchConditionID
				AND Title = 'Education' AND TitleID IN(3, 4)
			END 

			INSERT INTO SearchDB..paSearchCount_1(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Experience', MinExperience, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY MinExperience ORDER BY MinExperience
	
			INSERT INTO SearchDB..paSearchJobID_1(paSearchConditionID, JobId, IsTop)
			SELECT Top 3 @paSearchConditionID,Balance,1
			FROM caOrder WITH(NOLOCK), (SELECT TOP 2000 ID FROM #Job WITH(NOLOCK)) b
			WHERE caOrder.OrderType = 12 AND BeginDate<GETDATE() AND EndDate>GETDATE() AND b.ID = caOrder.Balance ORDER BY OpenDate DESC
			SET @TopRows = @@ROWCOUNT

			INSERT INTO SearchDB..paSearchJobID_1(paSearchConditionID, JobId, IsTop)
			SELECT TOP 2000 @paSearchConditionID, ID, 0 FROM #Job WITH(NOLOCK)
			SET @AllRows = @@ROWCOUNT

			IF @TopRows = 0 AND @AllRows > 100
				UPDATE SearchDB..paSearchJobID_1 SET IsTop = 1 
				WHERE paSearchConditionID = @paSearchConditionID
				AND ID IN (SELECT TOP 3 ID FROM SearchDB..paSearchJobID_1 WITH(NOLOCK) WHERE paSearchConditionID = @paSearchConditionID)
		END
		ELSE IF (@TableId = 2)
		BEGIN
			INSERT INTO SearchDB..paSearchCount_2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'JobType', dcJobTypeID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcJobTypeID ORDER BY dcJobTypeID
			----计算全部某职位类别，2, 4位的数据
			UPDATE a SET a.TitleValue = b.TitleValue
			FROM SearchDB..paSearchCount_2 a WITH(NOLOCK), 
			(SELECT LEFT(TitleID, 2) TitleID, SUM(TitleValue) TitleValue
			FROM SearchDB..paSearchCount_2 WITH(NOLOCK)
			WHERE paSearchConditionID = @paSearchConditionID AND Title = 'JobType'
			GROUP BY LEFT(TitleID, 2)) b
			WHERE a.TitleId = b.TitleID
			AND a.paSearchConditionID = @paSearchConditionID AND a.Title = 'JobType'
			----写入TitleDesc
			UPDATE a SET a.TitleDesc = b.Description
			FROM SearchDB..paSearchCount_2 a WITH(NOLOCK), dcJobType b WITH(NOLOCK)
			WHERE a.TitleID = b.ID AND a.paSearchConditionID = @paSearchConditionID
			AND a.Title = 'JobType'
			
			INSERT INTO SearchDB..paSearchCount_2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Salary', dcSalaryID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcSalaryID ORDER BY dcSalaryID

			INSERT INTO SearchDB..paSearchCount_2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Region', dcRegionID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcRegionID ORDER BY dcRegionID
			----计算全部地区，2位的数据
			UPDATE a SET a.TitleValue = b.TitleValue
			FROM SearchDB..paSearchCount_2 a WITH(NOLOCK), 
			(SELECT LEFT(TitleID, 2) TitleID, SUM(TitleValue) TitleValue
			FROM SearchDB..paSearchCount_2 WITH(NOLOCK)
			WHERE paSearchConditionID = @paSearchConditionID AND Title = 'Region'
			GROUP BY LEFT(TitleID, 2)) b
			WHERE a.TitleId = b.TitleID
			AND a.paSearchConditionID = @paSearchConditionID AND a.Title = 'Region'
			----计算全部地区，4位的数据
			UPDATE a SET a.TitleValue = b.TitleValue
			FROM SearchDB..paSearchCount_2 a WITH(NOLOCK), (
				SELECT LEFT(TitleID, 4) TitleID, SUM(TitleValue) TitleValue
				FROM SearchDB..paSearchCount_2 WITH(NOLOCK)
				WHERE paSearchConditionID = @paSearchConditionID AND Title = 'Region'
				AND LEN(TitleID) >3
				GROUP BY LEFT(TitleID, 4)) b
			WHERE a.TitleId = b.TitleID
			AND a.paSearchConditionID = @paSearchConditionID AND a.Title = 'Region'
			----写入TitleDesc
			UPDATE a SET a.TitleDesc = b.Description
			FROM SearchDB..paSearchCount_2 a WITH(NOLOCK), dcRegion b WITH(NOLOCK)
			WHERE a.TitleID = b.ID AND a.paSearchConditionID = @paSearchConditionID
			AND a.Title = 'Region'

			INSERT INTO SearchDB..paSearchCount_2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Education', dcEducationID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcEducationID ORDER BY dcEducationID
			--学历 高中、中专、中级合并		
			SELECT @TitleValue = SUM(TitleValue) FROM SearchDB..paSearchCount_2 WITH(NOLOCK)
			WHERE paSearchConditionID = @paSearchConditionID
			AND Title = 'Education' AND TitleID IN(2, 3, 4)		
			IF @TitleValue IS NOT NULL
			BEGIN
				IF EXISTS(SELECT 'X' FROM SearchDB..paSearchCount_2 WITH(NOLOCK) WHERE paSearchConditionID = @paSearchConditionID AND Title = 'Education' AND TitleID = 2)
					UPDATE SearchDB..paSearchCount_2 SET TitleValue = @TitleValue 
					WHERE paSearchConditionID = @paSearchConditionID
					AND Title = 'Education' AND TitleID = 2
				ELSE
					INSERT INTO SearchDB..paSearchCount_2(paSearchConditionID, Title, TitleId, TitleValue) VALUES
					(@paSearchConditionID, 'Education', 2, @TitleValue)

				DELETE FROM SearchDB..paSearchCount_2
				WHERE paSearchConditionID = @paSearchConditionID
				AND Title = 'Education' AND TitleID IN(3, 4)
			END 

			INSERT INTO SearchDB..paSearchCount_2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Experience', MinExperience, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY MinExperience ORDER BY MinExperience

			INSERT INTO SearchDB..paSearchJobID_2(paSearchConditionID, JobId, IsTop)
			SELECT Top 3 @paSearchConditionID,Balance,1
			FROM caOrder WITH(NOLOCK), (SELECT TOP 2000 ID FROM #Job WITH(NOLOCK)) b
			WHERE caOrder.OrderType = 12 AND BeginDate<GETDATE() AND EndDate>GETDATE() AND b.ID = caOrder.Balance ORDER BY OpenDate DESC
			SET @TopRows = @@ROWCOUNT

			INSERT INTO SearchDB..paSearchJobID_2(paSearchConditionID, JobId, IsTop)
			SELECT TOP 2000 @paSearchConditionID, ID, 0 FROM #Job WITH(NOLOCK)
			SET @AllRows = @@ROWCOUNT

			IF @TopRows = 0 AND @AllRows > 100
				UPDATE SearchDB..paSearchJobID_2 SET IsTop = 1 
				WHERE paSearchConditionID = @paSearchConditionID
				AND ID IN (SELECT TOP 3 ID FROM SearchDB..paSearchJobID_2 WITH(NOLOCK) WHERE paSearchConditionID = @paSearchConditionID)
		END
		ELSE IF (@TableId = 3)
		BEGIN
			INSERT INTO SearchDB..paSearchCount_3(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'JobType', dcJobTypeID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcJobTypeID ORDER BY dcJobTypeID
			----计算全部某职位类别，2, 4位的数据
			UPDATE a SET a.TitleValue = b.TitleValue
			FROM SearchDB..paSearchCount_3 a WITH(NOLOCK), 
			(SELECT LEFT(TitleID, 2) TitleID, SUM(TitleValue) TitleValue
			FROM SearchDB..paSearchCount_3 WITH(NOLOCK)
			WHERE paSearchConditionID = @paSearchConditionID AND Title = 'JobType'
			GROUP BY LEFT(TitleID, 2)) b
			WHERE a.TitleId = b.TitleID
			AND a.paSearchConditionID = @paSearchConditionID AND a.Title = 'JobType'
			----写入TitleDesc
			UPDATE a SET a.TitleDesc = b.Description
			FROM SearchDB..paSearchCount_3 a WITH(NOLOCK), dcJobType b WITH(NOLOCK)
			WHERE a.TitleID = b.ID AND a.paSearchConditionID = @paSearchConditionID
			AND a.Title = 'JobType'
			
			INSERT INTO SearchDB..paSearchCount_3(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Salary', dcSalaryID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcSalaryID ORDER BY dcSalaryID

			INSERT INTO SearchDB..paSearchCount_3(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Region', dcRegionID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcRegionID ORDER BY dcRegionID
			----计算全部地区，2位的数据
			UPDATE a SET a.TitleValue = b.TitleValue
			FROM SearchDB..paSearchCount_3 a WITH(NOLOCK), 
			(SELECT LEFT(TitleID, 2) TitleID, SUM(TitleValue) TitleValue
			FROM SearchDB..paSearchCount_3 WITH(NOLOCK)
			WHERE paSearchConditionID = @paSearchConditionID AND Title = 'Region'
			GROUP BY LEFT(TitleID, 2)) b
			WHERE a.TitleId = b.TitleID
			AND a.paSearchConditionID = @paSearchConditionID AND a.Title = 'Region'
			----计算全部地区，4位的数据
			UPDATE a SET a.TitleValue = b.TitleValue
			FROM SearchDB..paSearchCount_3 a WITH(NOLOCK), (
				SELECT LEFT(TitleID, 4) TitleID, SUM(TitleValue) TitleValue
				FROM SearchDB..paSearchCount_3 WITH(NOLOCK)
				WHERE paSearchConditionID = @paSearchConditionID AND Title = 'Region'
				AND LEN(TitleID) >3
				GROUP BY LEFT(TitleID, 4)) b
			WHERE a.TitleId = b.TitleID
			AND a.paSearchConditionID = @paSearchConditionID AND a.Title = 'Region'
			----写入TitleDesc
			UPDATE a SET a.TitleDesc = b.Description
			FROM SearchDB..paSearchCount_3 a WITH(NOLOCK), dcRegion b WITH(NOLOCK)
			WHERE a.TitleID = b.ID AND a.paSearchConditionID = @paSearchConditionID
			AND a.Title = 'Region'

			INSERT INTO SearchDB..paSearchCount_3(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Education', dcEducationID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcEducationID ORDER BY dcEducationID
			--学历 高中、中专、中级合并		
			SELECT @TitleValue = SUM(TitleValue) FROM SearchDB..paSearchCount_3 WITH(NOLOCK)
			WHERE paSearchConditionID = @paSearchConditionID
			AND Title = 'Education' AND TitleID IN(2, 3, 4)		
			IF @TitleValue IS NOT NULL
			BEGIN
				IF EXISTS(SELECT 'X' FROM SearchDB..paSearchCount_3 WITH(NOLOCK) WHERE paSearchConditionID = @paSearchConditionID AND Title = 'Education' AND TitleID = 2)
					UPDATE SearchDB..paSearchCount_3 SET TitleValue = @TitleValue 
					WHERE paSearchConditionID = @paSearchConditionID
					AND Title = 'Education' AND TitleID = 2
				ELSE
					INSERT INTO SearchDB..paSearchCount_3(paSearchConditionID, Title, TitleId, TitleValue) VALUES
					(@paSearchConditionID, 'Education', 2, @TitleValue)

				DELETE FROM SearchDB..paSearchCount_3
				WHERE paSearchConditionID = @paSearchConditionID
				AND Title = 'Education' AND TitleID IN(3, 4)
			END 

			INSERT INTO SearchDB..paSearchCount_3(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Experience', MinExperience, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY MinExperience ORDER BY MinExperience
			
			INSERT INTO SearchDB..paSearchJobID_3(paSearchConditionID, JobId, IsTop)
			SELECT Top 3 @paSearchConditionID,Balance,1 
			FROM caOrder WITH(NOLOCK), (SELECT TOP 2000 ID FROM #Job WITH(NOLOCK)) b 
			WHERE caOrder.OrderType = 12 AND BeginDate<GETDATE() AND EndDate>GETDATE() AND b.ID = caOrder.Balance ORDER BY OpenDate DESC
			SET @TopRows = @@ROWCOUNT

			INSERT INTO SearchDB..paSearchJobID_3(paSearchConditionID, JobId, IsTop)
			SELECT TOP 2000 @paSearchConditionID, ID, 0 FROM #Job WITH(NOLOCK)
			SET @AllRows = @@ROWCOUNT

			IF @TopRows = 0 AND @AllRows > 100
				UPDATE SearchDB..paSearchJobID_3 SET IsTop = 1 
				WHERE paSearchConditionID = @paSearchConditionID
				AND ID IN (SELECT TOP 3 ID FROM SearchDB..paSearchJobID_3 WITH(NOLOCK) WHERE paSearchConditionID = @paSearchConditionID)
		END
		DROP TABLE #Job
	COMMIT

	GetRecordSet:
	BEGIN
		----返回查询数量
		SELECT ValidJobNumber FROM SearchDB..paSearchCondition WITH(NOLOCK) WHERE ID=@paSearchConditionID
		UPDATE SearchDB..paSearchCondition SET ReuseNumber = ReuseNumber + 1 WHERE ID=@paSearchConditionID
		----返回20行查询结果
		IF (@TableID = 0)
		BEGIN
			SELECT @MinId = MIN(ID) FROM SearchDB..paSearchJobID_0 WITH(NOLOCK) WHERE paSearchConditionID=@paSearchConditionID

			SET @MinId = @MinId+(@PageNumber-1)*@PageSize
			SELECT TOP(@PageSize)a.ID, a.cpMainID, a.caMainID, a.Name as JobName, a.dcJobTypeID, 
				a.dcJobTypeIDMinor, a.NeedNumber, a.dcSalaryID, a.EmployType, 
				a.dcRegionID, a.Responsibility, a.Demand, a.dcEducationID, 
				a.MinExperience, a.MinAge, a.MaxAge, a.IssueDate, a.IssueEND, 
				a.IsDelete, a.AddDate, a.RefreshDate, 
				a.LastModifyDate, b.Name as cpName, b.dcCompanySizeID, 
				b.HasLicence, b.UnLimitedDate, b.BalanceDate, b.Balance, 
				b.MemberType, STUFF((SELECT ','+LTRIM(x.dcIndustryid)+',c'+LTRIM(isnull(y.Category,0)) 
							FROM cpIndustry x,dcIndustry y WHERE x.dcIndustryid = y.id 
							AND x.cpMainid = b.id FOR XML PATH('')),1,1,'') cpIndustry,
				c.IsTop, b.IsRefreshed, a.SecondId EnJobID, b.SecondId EnCpMainID
			FROM JobPublish a WITH(NOLOCK), cpMainPublish b WITH(NOLOCK), SearchDB..paSearchJobID_0 c WITH(NOLOCK)
			WHERE a.cpMainID = b.ID AND a.id=c.JobID AND c.paSearchConditionID=@paSearchConditionID 
				  AND c.ID>=@MinId ORDER BY c.ID, a.ID DESC
		END
		ELSE IF (@TableID = 1)
		BEGIN
			SELECT @MinId = MIN(ID) FROM SearchDB..paSearchJobID_1 WITH(NOLOCK) WHERE paSearchConditionID=@paSearchConditionID

			SET @MinId = @MinId+(@PageNumber-1)*@PageSize
			SELECT TOP(@PageSize)a.ID, a.cpMainID, a.caMainID, a.Name as JobName, a.dcJobTypeID, 
				a.dcJobTypeIDMinor, a.NeedNumber, a.dcSalaryID, a.EmployType, 
				a.dcRegionID, a.Responsibility, a.Demand, a.dcEducationID, 
				a.MinExperience, a.MinAge, a.MaxAge, a.IssueDate, a.IssueEND, 
				a.IsDelete, a.AddDate, a.RefreshDate, 
				a.LastModifyDate, b.Name as cpName, b.dcCompanySizeID, 
				b.HasLicence, b.UnLimitedDate, b.BalanceDate, b.Balance, 
				b.MemberType, STUFF((SELECT ','+LTRIM(x.dcIndustryid)+',c'+LTRIM(isnull(y.Category,0)) 
							FROM cpIndustry x,dcIndustry y WHERE x.dcIndustryid = y.id 
							AND x.cpMainid = b.id FOR XML PATH('')),1,1,'') cpIndustry,
				c.IsTop, b.IsRefreshed, a.SecondId EnJobID, b.SecondId EnCpMainID
			FROM JobPublish a WITH(NOLOCK), cpMainPublish b WITH(NOLOCK), SearchDB..paSearchJobID_1 c WITH(NOLOCK)
			WHERE a.cpMainID = b.ID AND a.id=c.JobID AND c.paSearchConditionID=@paSearchConditionID 
				  AND c.ID>=@MinId ORDER BY c.ID, a.ID DESC
		END
		ELSE IF (@TableID = 2)
		BEGIN
			SELECT @MinId = MIN(ID) FROM SearchDB..paSearchJobID_2 WITH(NOLOCK) WHERE paSearchConditionID=@paSearchConditionID

			SET @MinId = @MinId+(@PageNumber-1)*@PageSize
			SELECT TOP(@PageSize)a.ID, a.cpMainID, a.caMainID, a.Name as JobName, a.dcJobTypeID, 
				a.dcJobTypeIDMinor, a.NeedNumber, a.dcSalaryID, a.EmployType, 
				a.dcRegionID, a.Responsibility, a.Demand, a.dcEducationID, 
				a.MinExperience, a.MinAge, a.MaxAge, a.IssueDate, a.IssueEND, 
				a.IsDelete, a.AddDate, a.RefreshDate, 
				a.LastModifyDate, b.Name as cpName, b.dcCompanySizeID, 
				b.HasLicence, b.UnLimitedDate, b.BalanceDate, b.Balance, 
				b.MemberType, STUFF((SELECT ','+LTRIM(x.dcIndustryid)+',c'+LTRIM(isnull(y.Category,0)) 
							FROM cpIndustry x,dcIndustry y WHERE x.dcIndustryid = y.id 
							AND x.cpMainid = b.id FOR XML PATH('')),1,1,'') cpIndustry,
				c.IsTop, b.IsRefreshed, a.SecondId EnJobID, b.SecondId EnCpMainID
			FROM JobPublish a WITH(NOLOCK), cpMainPublish b WITH(NOLOCK), SearchDB..paSearchJobID_2 c WITH(NOLOCK)
			WHERE a.cpMainID = b.ID AND a.id=c.JobID AND c.paSearchConditionID=@paSearchConditionID 
				  AND c.ID>=@MinId ORDER BY c.ID, a.ID DESC
		END
		ELSE IF (@TableID = 3)
		BEGIN
			SELECT @MinId = MIN(ID) FROM SearchDB..paSearchJobID_3 WITH(NOLOCK) WHERE paSearchConditionID=@paSearchConditionID

			SET @MinId = @MinId+(@PageNumber-1)*@PageSize
			SELECT TOP(@PageSize)a.ID, a.cpMainID, a.caMainID, a.Name as JobName, a.dcJobTypeID, 
				a.dcJobTypeIDMinor, a.NeedNumber, a.dcSalaryID, a.EmployType, 
				a.dcRegionID, a.Responsibility, a.Demand, a.dcEducationID, 
				a.MinExperience, a.MinAge, a.MaxAge, a.IssueDate, a.IssueEND, 
				a.IsDelete, a.AddDate, a.RefreshDate, 
				a.LastModifyDate, b.Name as cpName, b.dcCompanySizeID, 
				b.HasLicence, b.UnLimitedDate, b.BalanceDate, b.Balance, 
				b.MemberType, STUFF((SELECT ','+LTRIM(x.dcIndustryid)+',c'+LTRIM(isnull(y.Category,0)) 
							FROM cpIndustry x,dcIndustry y WHERE x.dcIndustryid = y.id 
							AND x.cpMainid = b.id FOR XML PATH('')),1,1,'') cpIndustry,
				c.IsTop, b.IsRefreshed, a.SecondId EnJobID, b.SecondId EnCpMainID
			FROM JobPublish a WITH(NOLOCK), cpMainPublish b WITH(NOLOCK), SearchDB..paSearchJobID_3 c WITH(NOLOCK)
			WHERE a.cpMainID = b.ID AND a.id=c.JobID AND c.paSearchConditionID=@paSearchConditionID 
				  AND c.ID>=@MinId ORDER BY c.ID, a.ID DESC
		END
		RETURN
	END
END TRY
BEGIN CATCH
	---检查是否已经建立临时表，已经建立则删除
	PRINT 'error'
	PRINT error_Message()
	PRINT error_number()
	PRINT error_line()
END CATCH










GO
/****** Object:  StoredProcedure [dbo].[mblJobByWeixinSelect1]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[mblJobByWeixinSelect1] 
(
	@FromUserName VARCHAR(50),
	@Type INT		--0：订阅号关键词查询；10：服务号的关键词查询；11：服务号的周边职位
)
AS
--return
SET NOCOUNT ON
BEGIN TRY
	DECLARE @dcRegionID INT,@KeyWord NVARCHAR(20),
	@Lng DECIMAL(8,5),@Lat DECIMAL(8,5),@Distance INT,
	@KeyType TINYINT, @ValidJobNumber INT, @PageNumber SMALLINT

	IF @Type =11
	BEGIN
		SELECT @dcRegionID=dcRegionID,@KeyWord=KeyWord,@Lng=Lng,@Lat=Lat
		FROM wxMessage WITH(NOLOCK) WHERE FromUserName=@FromUserName AND CONTENT='推荐职位'
	END
	ELSE
	BEGIN
		SELECT @dcRegionID=dcRegionID,@KeyWord=KeyWord,
			@Lng=Lng,@Lat=Lat,@PageNumber=PageNumber
		FROM wxMessage WITH(NOLOCK) WHERE FromUserName=@FromUserName
	END
	
	SELECT @KeyWord = dbo.SafeSQL(ISNULL(@KeyWord, '')),
		@KeyType = 2,
		@Distance = 5000,
		@PageNumber = ISNULL(@PageNumber, 1),
		@dcRegionID = ISNULL(@dcRegionID, 0),
		@Lng = ISNULL(@Lng, 0),
		@Lat = ISNULL(@Lat, 0)

	IF @Type IN (10, 11)
		SELECT @PageNumber = 1
	
	UPDATE wxMessage SET PageNumber = @PageNumber + 1  WHERE FromUserName=@FromUserName

	IF @dcRegionID = 0 AND @Lng = 0 AND @Lat = 0
		RETURN

	DECLARE @paSearchConditionID AS INT, 
		@MinId AS INT, 
		@PageSize AS TINYINT, 
		@TableID AS TINYINT

	IF @Type =11 OR  @Type =10
	BEGIN
		SELECT @paSearchConditionID = 0, @PageSize = 5  --每页的行数
	END 
	ELSE 
	BEGIN
		SELECT @paSearchConditionID = 0, @PageSize = 8  --每页的行数
	END

	----搜索60分钟前的数据
	SELECT TOP 1 @paSearchConditionID=ID FROM SearchDB..paSearchCondition WITH(NOLOCK)
	WHERE JobType=''
	AND JobPlace=@dcRegionID AND ISNULL(Industry,'')='' AND ISNULL(Education,'')=''
	AND ISNULL(Experience,'')='' AND ISNULL(Salary,'')='' AND ISNULL(IsNegotiable,'')='' 
	AND ISNULL(EmployType,'')='' AND KeyWord=@KeyWord AND KeyType=@KeyType
	AND ISNULL(CompanySizeID,'')='' AND Lng=@Lng AND Lat=@Lat
	ORDER BY ID DESC

	IF ISNULL(@paSearchConditionID, 0) = 0
	BEGIN
		GOTO SelectReset	--无数据，重新搜索
	END
	ELSE
	BEGIN
		SELECT @TableID = @paSearchConditionID % 4
		GOTO GetRecordSet	--从临时结果中提取数据
	END

	SelectReset:
	--从job中搜索数据
	BEGIN TRAN
		DECLARE @SQL AS VARCHAR(8000)
		DECLARE @WHERE AS VARCHAR(8000)
		DECLARE @FROM AS VARCHAR(1000)
		----记录查询条件
		INSERT INTO SearchDB..paSearchCondition(SessionID, LogTime, JobType, JobPlace, Industry, Education, Experience, 
			Salary, IsNegotiable, EmployType, CompanySizeID, KeyWord, KeyType, ReuseNumber, Lng, Lat, Distance)
		VALUES(1, GETDATE(), '', @dcRegionID, '', '', '', '', '', '', '', @KeyWord, @KeyType, 0, @Lng, @Lat, @Distance)
		SET @paSearchConditionID = @@IDENTITY
		SELECT @TableID = @paSearchConditionID % 4

		----建立临时表
		CREATE TABLE #Job(
			RowID INT IDENTITY(1, 1), 
			ID INT NOT NULL, 
			dcJobTypeID SMALLINT NOT NULL, 
			dcJobTypeIDMinor SMALLINT NULL, 
			dcSalaryID TINYINT NOT NULL, 
			dcRegionID VARCHAR(6) NULL, 
			dcEducationID TINYINT NOT NULL, 
			MinExperience TINYINT NOT NULL, 
			RefreshDate SMALLDATETIME NULL
		)
		------刷新时间，根据刷新时间编号计算
		----生成插入临时表的Sql语句
		SET @SQL='
			INSERT INTO #Job
			SELECT a.ID, a.dcJobTypeID, 
				a.dcJobTypeIDMinor, a.dcSalaryID, 
				a.dcRegionID, a.dcEducationID, a.MinExperience, 
				a.IssueDate'
		SET @FROM = '
			FROM JobPublish a WITH(NOLOCK)
			INNER JOIN cpMainPublish b WITH(NOLOCK) ON a.cpMainID=b.ID'
		----职位有效，单位新有效
		SET @WHERE = '
			WHERE a.Valid = 1
			AND b.Valid = 1'
		----需要增加全文索引的关键字查询
		IF @KeyWord LIKE '% %'
		BEGIN
			SET @KeyWord = REPLACE(@KeyWord, '  ', ' ')
			SET @KeyWord = REPLACE(@KeyWord, '  ', ' ')
			SET @KeyWord = REPLACE(@KeyWord, '  ', ' ')
			SET @KeyWord = '"' + REPLACE(@KeyWord, ' ', '" OR "') + '"'
		END

		IF LEN(@KeyWord) > 0
		BEGIN
			IF @KeyType = 2
				SET @FROM = @FROM + '
			INNER JOIN CONTAINSTABLE(JobPublish, *, ''' + @KeyWord + ''', 1000000) AS KeyJob
			ON a.ID = KeyJob.[Key]'
		END
		---地区
		IF @dcRegionID > 0 
			SET @WHERE = @WHERE + '
			AND a.dcRegionID Like ''' + CONVERT(VARCHAR(6),@dcRegionID) + '%'''

		IF @Lng > 0 AND @Lat > 0
		BEGIN
			DECLARE @Degree AS DECIMAL(8,5),@LBLng AS DECIMAL(8,5),@LBLat AS DECIMAL(8,5),
			@RTLng AS DECIMAL(8,5),@RTLat AS DECIMAL(8,5)
			SET @Degree = @Distance / 100000.0;

			SET @LBLng = @Lng - @Degree
			SET @LBLat = @Lat - @Degree
			SET @RTLng = @Lng + @Degree
			SET @RTLat = @Lat + @Degree
			SET @WHERE = @WHERE + '
				AND a.Lng BETWEEN ' + CONVERT(VARCHAR,@LBLng) + ' AND ' + CONVERT(VARCHAR,@RTLng) + '
				AND a.Lat BETWEEN ' + CONVERT(VARCHAR,@LBLat) + ' AND ' + CONVERT(VARCHAR,@RTLat)
		END
		SET @SQL = @SQL + @FROM + @WHERE
		
		SET @SQL=@SQL + ' ORDER BY a.RefreshDate DESC, a.ID'

		----把符合条件的职位全部列出
		--PRINT @SQL
		EXEC(@SQL)
		
		SET @ValidJobNumber = @@ROWCOUNT
		----记录查询结果总数
		UPDATE SearchDB..paSearchCondition SET ValidJobNumber=@ValidJobNumber, SQl=@SQL WHERE ID=@paSearchConditionID
		
		----插入JobType数据
		DECLARE @TitleValue AS INT, @TopRows AS INT, @AllRows AS INT
		IF (@TableID = 0)
		BEGIN
			INSERT INTO SearchDB..paSearchCount_0(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'JobType', dcJobTypeID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcJobTypeID ORDER BY dcJobTypeID
			----计算全部某职位类别，2, 4位的数据
			UPDATE a SET a.TitleValue = b.TitleValue
			FROM SearchDB..paSearchCount_0 a WITH(NOLOCK), 
				(SELECT LEFT(TitleID, 2) TitleID, SUM(TitleValue) TitleValue
				FROM SearchDB..paSearchCount_0 WITH(NOLOCK)
				WHERE paSearchConditionID = @paSearchConditionID AND Title = 'JobType'
				GROUP BY LEFT(TitleID, 2)) b
			WHERE a.TitleId = b.TitleID
			AND a.paSearchConditionID = @paSearchConditionID AND a.Title = 'JobType'
			----写入TitleDesc
			UPDATE a SET a.TitleDesc = b.Description
			FROM SearchDB..paSearchCount_0 a WITH(NOLOCK), dcJobType b WITH(NOLOCK)
			WHERE a.TitleID = b.ID AND a.paSearchConditionID = @paSearchConditionID
			AND a.Title = 'JobType'
			
			INSERT INTO SearchDB..paSearchCount_0(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Salary', dcSalaryID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcSalaryID ORDER BY dcSalaryID

			INSERT INTO SearchDB..paSearchCount_0(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Region', dcRegionID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcRegionID ORDER BY dcRegionID
			----计算全部地区，2位的数据
			UPDATE a SET a.TitleValue = b.TitleValue
			FROM SearchDB..paSearchCount_0 a WITH(NOLOCK), 
			(SELECT LEFT(TitleID, 2) TitleID, SUM(TitleValue) TitleValue
			FROM SearchDB..paSearchCount_0 WITH(NOLOCK)
			WHERE paSearchConditionID = @paSearchConditionID AND Title = 'Region'
			GROUP BY LEFT(TitleID, 2)) b
			WHERE a.TitleId = b.TitleID
			AND a.paSearchConditionID = @paSearchConditionID AND a.Title = 'Region'
			----计算全部地区，4位的数据
			UPDATE a SET a.TitleValue = b.TitleValue
			FROM SearchDB..paSearchCount_0 a WITH(NOLOCK), (
				SELECT LEFT(TitleID, 4) TitleID, SUM(TitleValue) TitleValue
				FROM SearchDB..paSearchCount_0 WITH(NOLOCK)
				WHERE paSearchConditionID = @paSearchConditionID AND Title = 'Region'
				AND LEN(TitleID) >3
				GROUP BY LEFT(TitleID, 4)) b
			WHERE a.TitleId = b.TitleID
			AND a.paSearchConditionID = @paSearchConditionID AND a.Title = 'Region'
			----写入TitleDesc
			UPDATE a SET a.TitleDesc = b.Description
			FROM SearchDB..paSearchCount_0 a WITH(NOLOCK), dcRegion b WITH(NOLOCK)
			WHERE a.TitleID = b.ID AND a.paSearchConditionID = @paSearchConditionID
			AND a.Title = 'Region'

			INSERT INTO SearchDB..paSearchCount_0(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Education', dcEducationID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcEducationID ORDER BY dcEducationID
			--学历 高中、中专、中级合并		
			SELECT @TitleValue = SUM(TitleValue) FROM SearchDB..paSearchCount_0 WITH(NOLOCK)
			WHERE paSearchConditionID = @paSearchConditionID
			AND Title = 'Education' AND TitleID IN(2, 3, 4)		
			IF @TitleValue IS NOT NULL
			BEGIN
				IF EXISTS(SELECT 'X' FROM SearchDB..paSearchCount_0 WITH(NOLOCK) WHERE paSearchConditionID = @paSearchConditionID AND Title = 'Education' AND TitleID = 2)
					UPDATE SearchDB..paSearchCount_0 SET TitleValue = @TitleValue 
					WHERE paSearchConditionID = @paSearchConditionID
					AND Title = 'Education' AND TitleID = 2
				ELSE
					INSERT INTO SearchDB..paSearchCount_0(paSearchConditionID, Title, TitleId, TitleValue) VALUES
					(@paSearchConditionID, 'Education', 2, @TitleValue)

				DELETE FROM SearchDB..paSearchCount_0
				WHERE paSearchConditionID = @paSearchConditionID
				AND Title = 'Education' AND TitleID IN(3, 4)
			END 

			INSERT INTO SearchDB..paSearchCount_0(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Experience', MinExperience, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY MinExperience ORDER BY MinExperience
			
			INSERT INTO SearchDB..paSearchJobID_0(paSearchConditionID, JobId, IsTop)
			SELECT Top 3 @paSearchConditionID,Balance,1 
			FROM caOrder WITH(NOLOCK), (SELECT TOP 2000 ID FROM #Job WITH(NOLOCK)) b 
			WHERE caOrder.OrderType = 12 AND BeginDate<GETDATE() AND EndDate>GETDATE() AND b.ID = caOrder.Balance ORDER BY OpenDate DESC
			SET @TopRows = @@ROWCOUNT

			INSERT INTO SearchDB..paSearchJobID_0(paSearchConditionID, JobId, IsTop)
			SELECT TOP 2000 @paSearchConditionID, ID, 0 FROM #Job WITH(NOLOCK)
			SET @AllRows = @@ROWCOUNT

			IF @TopRows = 0 AND @AllRows > 100
				UPDATE SearchDB..paSearchJobID_0 SET IsTop = 1 
				WHERE paSearchConditionID = @paSearchConditionID
				AND ID IN (SELECT TOP 3 ID FROM SearchDB..paSearchJobID_0 WITH(NOLOCK) WHERE paSearchConditionID = @paSearchConditionID)
		END
		ELSE IF (@TableId = 1)
		BEGIN
			INSERT INTO SearchDB..paSearchCount_1(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'JobType', dcJobTypeID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcJobTypeID ORDER BY dcJobTypeID
			----计算全部某职位类别，2, 4位的数据
			UPDATE a SET a.TitleValue = b.TitleValue
			FROM SearchDB..paSearchCount_1 a WITH(NOLOCK), 
			(SELECT LEFT(TitleID, 2) TitleID, SUM(TitleValue) TitleValue
			FROM SearchDB..paSearchCount_1 WITH(NOLOCK)
			WHERE paSearchConditionID = @paSearchConditionID AND Title = 'JobType'
			GROUP BY LEFT(TitleID, 2)) b
			WHERE a.TitleId = b.TitleID
			AND a.paSearchConditionID = @paSearchConditionID AND a.Title = 'JobType'
			----写入TitleDesc
			UPDATE a SET a.TitleDesc = b.Description
			FROM SearchDB..paSearchCount_1 a WITH(NOLOCK), dcJobType b WITH(NOLOCK)
			WHERE a.TitleID = b.ID AND a.paSearchConditionID = @paSearchConditionID
			AND a.Title = 'JobType'
			
			INSERT INTO SearchDB..paSearchCount_1(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Salary', dcSalaryID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcSalaryID ORDER BY dcSalaryID

			INSERT INTO SearchDB..paSearchCount_1(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Region', dcRegionID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcRegionID ORDER BY dcRegionID
			----计算全部地区，2位的数据
			UPDATE a SET a.TitleValue = b.TitleValue
			FROM SearchDB..paSearchCount_1 a WITH(NOLOCK), 
			(SELECT LEFT(TitleID, 2) TitleID, SUM(TitleValue) TitleValue
			FROM SearchDB..paSearchCount_1 WITH(NOLOCK)
			WHERE paSearchConditionID = @paSearchConditionID AND Title = 'Region'
			GROUP BY LEFT(TitleID, 2)) b
			WHERE a.TitleId = b.TitleID
			AND a.paSearchConditionID = @paSearchConditionID AND a.Title = 'Region'
			----计算全部地区，4位的数据
			UPDATE a SET a.TitleValue = b.TitleValue
			FROM SearchDB..paSearchCount_1 a WITH(NOLOCK), (
				SELECT LEFT(TitleID, 4) TitleID, SUM(TitleValue) TitleValue
				FROM SearchDB..paSearchCount_1 WITH(NOLOCK)
				WHERE paSearchConditionID = @paSearchConditionID AND Title = 'Region'
				AND LEN(TitleID) >3
				GROUP BY LEFT(TitleID, 4)) b
			WHERE a.TitleId = b.TitleID
			AND a.paSearchConditionID = @paSearchConditionID AND a.Title = 'Region'
			----写入TitleDesc
			UPDATE a SET a.TitleDesc = b.Description
			FROM SearchDB..paSearchCount_1 a WITH(NOLOCK), dcRegion b WITH(NOLOCK)
			WHERE a.TitleID = b.ID AND a.paSearchConditionID = @paSearchConditionID
			AND a.Title = 'Region'

			INSERT INTO SearchDB..paSearchCount_1(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Education', dcEducationID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcEducationID ORDER BY dcEducationID
			--学历 高中、中专、中级合并		
			SELECT @TitleValue = SUM(TitleValue) FROM SearchDB..paSearchCount_1 WITH(NOLOCK)
			WHERE paSearchConditionID = @paSearchConditionID
			AND Title = 'Education' AND TitleID IN(2, 3, 4)		
			IF @TitleValue IS NOT NULL
			BEGIN
				IF EXISTS(SELECT 'X' FROM SearchDB..paSearchCount_1 WITH(NOLOCK) WHERE paSearchConditionID = @paSearchConditionID AND Title = 'Education' AND TitleID = 2)
					UPDATE SearchDB..paSearchCount_1 SET TitleValue = @TitleValue 
					WHERE paSearchConditionID = @paSearchConditionID
					AND Title = 'Education' AND TitleID = 2
				ELSE
					INSERT INTO SearchDB..paSearchCount_1(paSearchConditionID, Title, TitleId, TitleValue) VALUES
					(@paSearchConditionID, 'Education', 2, @TitleValue)

				DELETE FROM SearchDB..paSearchCount_1
				WHERE paSearchConditionID = @paSearchConditionID
				AND Title = 'Education' AND TitleID IN(3, 4)
			END 

			INSERT INTO SearchDB..paSearchCount_1(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Experience', MinExperience, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY MinExperience ORDER BY MinExperience
	
			INSERT INTO SearchDB..paSearchJobID_1(paSearchConditionID, JobId, IsTop)
			SELECT Top 3 @paSearchConditionID,Balance,1
			FROM caOrder WITH(NOLOCK), (SELECT TOP 2000 ID FROM #Job WITH(NOLOCK)) b
			WHERE caOrder.OrderType = 12 AND BeginDate<GETDATE() AND EndDate>GETDATE() AND b.ID = caOrder.Balance ORDER BY OpenDate DESC
			SET @TopRows = @@ROWCOUNT

			INSERT INTO SearchDB..paSearchJobID_1(paSearchConditionID, JobId, IsTop)
			SELECT TOP 2000 @paSearchConditionID, ID, 0 FROM #Job WITH(NOLOCK)
			SET @AllRows = @@ROWCOUNT

			IF @TopRows = 0 AND @AllRows > 100
				UPDATE SearchDB..paSearchJobID_1 SET IsTop = 1 
				WHERE paSearchConditionID = @paSearchConditionID
				AND ID IN (SELECT TOP 3 ID FROM SearchDB..paSearchJobID_1 WITH(NOLOCK) WHERE paSearchConditionID = @paSearchConditionID)
		END
		ELSE IF (@TableId = 2)
		BEGIN
			INSERT INTO SearchDB..paSearchCount_2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'JobType', dcJobTypeID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcJobTypeID ORDER BY dcJobTypeID
			----计算全部某职位类别，2, 4位的数据
			UPDATE a SET a.TitleValue = b.TitleValue
			FROM SearchDB..paSearchCount_2 a WITH(NOLOCK), 
			(SELECT LEFT(TitleID, 2) TitleID, SUM(TitleValue) TitleValue
			FROM SearchDB..paSearchCount_2 WITH(NOLOCK)
			WHERE paSearchConditionID = @paSearchConditionID AND Title = 'JobType'
			GROUP BY LEFT(TitleID, 2)) b
			WHERE a.TitleId = b.TitleID
			AND a.paSearchConditionID = @paSearchConditionID AND a.Title = 'JobType'
			----写入TitleDesc
			UPDATE a SET a.TitleDesc = b.Description
			FROM SearchDB..paSearchCount_2 a WITH(NOLOCK), dcJobType b WITH(NOLOCK)
			WHERE a.TitleID = b.ID AND a.paSearchConditionID = @paSearchConditionID
			AND a.Title = 'JobType'
			
			INSERT INTO SearchDB..paSearchCount_2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Salary', dcSalaryID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcSalaryID ORDER BY dcSalaryID

			INSERT INTO SearchDB..paSearchCount_2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Region', dcRegionID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcRegionID ORDER BY dcRegionID
			----计算全部地区，2位的数据
			UPDATE a SET a.TitleValue = b.TitleValue
			FROM SearchDB..paSearchCount_2 a WITH(NOLOCK), 
			(SELECT LEFT(TitleID, 2) TitleID, SUM(TitleValue) TitleValue
			FROM SearchDB..paSearchCount_2 WITH(NOLOCK)
			WHERE paSearchConditionID = @paSearchConditionID AND Title = 'Region'
			GROUP BY LEFT(TitleID, 2)) b
			WHERE a.TitleId = b.TitleID
			AND a.paSearchConditionID = @paSearchConditionID AND a.Title = 'Region'
			----计算全部地区，4位的数据
			UPDATE a SET a.TitleValue = b.TitleValue
			FROM SearchDB..paSearchCount_2 a WITH(NOLOCK), (
				SELECT LEFT(TitleID, 4) TitleID, SUM(TitleValue) TitleValue
				FROM SearchDB..paSearchCount_2 WITH(NOLOCK)
				WHERE paSearchConditionID = @paSearchConditionID AND Title = 'Region'
				AND LEN(TitleID) >3
				GROUP BY LEFT(TitleID, 4)) b
			WHERE a.TitleId = b.TitleID
			AND a.paSearchConditionID = @paSearchConditionID AND a.Title = 'Region'
			----写入TitleDesc
			UPDATE a SET a.TitleDesc = b.Description
			FROM SearchDB..paSearchCount_2 a WITH(NOLOCK), dcRegion b WITH(NOLOCK)
			WHERE a.TitleID = b.ID AND a.paSearchConditionID = @paSearchConditionID
			AND a.Title = 'Region'

			INSERT INTO SearchDB..paSearchCount_2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Education', dcEducationID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcEducationID ORDER BY dcEducationID
			--学历 高中、中专、中级合并		
			SELECT @TitleValue = SUM(TitleValue) FROM SearchDB..paSearchCount_2 WITH(NOLOCK)
			WHERE paSearchConditionID = @paSearchConditionID
			AND Title = 'Education' AND TitleID IN(2, 3, 4)		
			IF @TitleValue IS NOT NULL
			BEGIN
				IF EXISTS(SELECT 'X' FROM SearchDB..paSearchCount_2 WITH(NOLOCK) WHERE paSearchConditionID = @paSearchConditionID AND Title = 'Education' AND TitleID = 2)
					UPDATE SearchDB..paSearchCount_2 SET TitleValue = @TitleValue 
					WHERE paSearchConditionID = @paSearchConditionID
					AND Title = 'Education' AND TitleID = 2
				ELSE
					INSERT INTO SearchDB..paSearchCount_2(paSearchConditionID, Title, TitleId, TitleValue) VALUES
					(@paSearchConditionID, 'Education', 2, @TitleValue)

				DELETE FROM SearchDB..paSearchCount_2
				WHERE paSearchConditionID = @paSearchConditionID
				AND Title = 'Education' AND TitleID IN(3, 4)
			END 

			INSERT INTO SearchDB..paSearchCount_2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Experience', MinExperience, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY MinExperience ORDER BY MinExperience

			INSERT INTO SearchDB..paSearchJobID_2(paSearchConditionID, JobId, IsTop)
			SELECT Top 3 @paSearchConditionID,Balance,1
			FROM caOrder WITH(NOLOCK), (SELECT TOP 2000 ID FROM #Job WITH(NOLOCK)) b
			WHERE caOrder.OrderType = 12 AND BeginDate<GETDATE() AND EndDate>GETDATE() AND b.ID = caOrder.Balance ORDER BY OpenDate DESC
			SET @TopRows = @@ROWCOUNT

			INSERT INTO SearchDB..paSearchJobID_2(paSearchConditionID, JobId, IsTop)
			SELECT TOP 2000 @paSearchConditionID, ID, 0 FROM #Job WITH(NOLOCK)
			SET @AllRows = @@ROWCOUNT

			IF @TopRows = 0 AND @AllRows > 100
				UPDATE SearchDB..paSearchJobID_2 SET IsTop = 1 
				WHERE paSearchConditionID = @paSearchConditionID
				AND ID IN (SELECT TOP 3 ID FROM SearchDB..paSearchJobID_2 WITH(NOLOCK) WHERE paSearchConditionID = @paSearchConditionID)
		END
		ELSE IF (@TableId = 3)
		BEGIN
			INSERT INTO SearchDB..paSearchCount_3(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'JobType', dcJobTypeID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcJobTypeID ORDER BY dcJobTypeID
			----计算全部某职位类别，2, 4位的数据
			UPDATE a SET a.TitleValue = b.TitleValue
			FROM SearchDB..paSearchCount_3 a WITH(NOLOCK), 
			(SELECT LEFT(TitleID, 2) TitleID, SUM(TitleValue) TitleValue
			FROM SearchDB..paSearchCount_3 WITH(NOLOCK)
			WHERE paSearchConditionID = @paSearchConditionID AND Title = 'JobType'
			GROUP BY LEFT(TitleID, 2)) b
			WHERE a.TitleId = b.TitleID
			AND a.paSearchConditionID = @paSearchConditionID AND a.Title = 'JobType'
			----写入TitleDesc
			UPDATE a SET a.TitleDesc = b.Description
			FROM SearchDB..paSearchCount_3 a WITH(NOLOCK), dcJobType b WITH(NOLOCK)
			WHERE a.TitleID = b.ID AND a.paSearchConditionID = @paSearchConditionID
			AND a.Title = 'JobType'
			
			INSERT INTO SearchDB..paSearchCount_3(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Salary', dcSalaryID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcSalaryID ORDER BY dcSalaryID

			INSERT INTO SearchDB..paSearchCount_3(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Region', dcRegionID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcRegionID ORDER BY dcRegionID
			----计算全部地区，2位的数据
			UPDATE a SET a.TitleValue = b.TitleValue
			FROM SearchDB..paSearchCount_3 a WITH(NOLOCK), 
			(SELECT LEFT(TitleID, 2) TitleID, SUM(TitleValue) TitleValue
			FROM SearchDB..paSearchCount_3 WITH(NOLOCK)
			WHERE paSearchConditionID = @paSearchConditionID AND Title = 'Region'
			GROUP BY LEFT(TitleID, 2)) b
			WHERE a.TitleId = b.TitleID
			AND a.paSearchConditionID = @paSearchConditionID AND a.Title = 'Region'
			----计算全部地区，4位的数据
			UPDATE a SET a.TitleValue = b.TitleValue
			FROM SearchDB..paSearchCount_3 a WITH(NOLOCK), (
				SELECT LEFT(TitleID, 4) TitleID, SUM(TitleValue) TitleValue
				FROM SearchDB..paSearchCount_3 WITH(NOLOCK)
				WHERE paSearchConditionID = @paSearchConditionID AND Title = 'Region'
				AND LEN(TitleID) >3
				GROUP BY LEFT(TitleID, 4)) b
			WHERE a.TitleId = b.TitleID
			AND a.paSearchConditionID = @paSearchConditionID AND a.Title = 'Region'
			----写入TitleDesc
			UPDATE a SET a.TitleDesc = b.Description
			FROM SearchDB..paSearchCount_3 a WITH(NOLOCK), dcRegion b WITH(NOLOCK)
			WHERE a.TitleID = b.ID AND a.paSearchConditionID = @paSearchConditionID
			AND a.Title = 'Region'

			INSERT INTO SearchDB..paSearchCount_3(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Education', dcEducationID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcEducationID ORDER BY dcEducationID
			--学历 高中、中专、中级合并		
			SELECT @TitleValue = SUM(TitleValue) FROM SearchDB..paSearchCount_3 WITH(NOLOCK)
			WHERE paSearchConditionID = @paSearchConditionID
			AND Title = 'Education' AND TitleID IN(2, 3, 4)		
			IF @TitleValue IS NOT NULL
			BEGIN
				IF EXISTS(SELECT 'X' FROM SearchDB..paSearchCount_3 WITH(NOLOCK) WHERE paSearchConditionID = @paSearchConditionID AND Title = 'Education' AND TitleID = 2)
					UPDATE SearchDB..paSearchCount_3 SET TitleValue = @TitleValue 
					WHERE paSearchConditionID = @paSearchConditionID
					AND Title = 'Education' AND TitleID = 2
				ELSE
					INSERT INTO SearchDB..paSearchCount_3(paSearchConditionID, Title, TitleId, TitleValue) VALUES
					(@paSearchConditionID, 'Education', 2, @TitleValue)

				DELETE FROM SearchDB..paSearchCount_3
				WHERE paSearchConditionID = @paSearchConditionID
				AND Title = 'Education' AND TitleID IN(3, 4)
			END 

			INSERT INTO SearchDB..paSearchCount_3(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Experience', MinExperience, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY MinExperience ORDER BY MinExperience
			
			INSERT INTO SearchDB..paSearchJobID_3(paSearchConditionID, JobId, IsTop)
			SELECT Top 3 @paSearchConditionID,Balance,1 
			FROM caOrder WITH(NOLOCK), (SELECT TOP 2000 ID FROM #Job WITH(NOLOCK)) b 
			WHERE caOrder.OrderType = 12 AND BeginDate<GETDATE() AND EndDate>GETDATE() AND b.ID = caOrder.Balance ORDER BY OpenDate DESC
			SET @TopRows = @@ROWCOUNT

			INSERT INTO SearchDB..paSearchJobID_3(paSearchConditionID, JobId, IsTop)
			SELECT TOP 2000 @paSearchConditionID, ID, 0 FROM #Job WITH(NOLOCK)
			SET @AllRows = @@ROWCOUNT

			IF @TopRows = 0 AND @AllRows > 100
				UPDATE SearchDB..paSearchJobID_3 SET IsTop = 1 
				WHERE paSearchConditionID = @paSearchConditionID
				AND ID IN (SELECT TOP 3 ID FROM SearchDB..paSearchJobID_3 WITH(NOLOCK) WHERE paSearchConditionID = @paSearchConditionID)
		END
		DROP TABLE #Job
	COMMIT

	GetRecordSet:
	BEGIN
		----返回查询数量
		SELECT ValidJobNumber FROM SearchDB..paSearchCondition WITH(NOLOCK) WHERE ID=@paSearchConditionID
		UPDATE SearchDB..paSearchCondition SET ReuseNumber = ReuseNumber + 1 WHERE ID=@paSearchConditionID
		----返回20行查询结果
		IF (@TableID = 0)
		BEGIN
			SELECT @MinId = MIN(ID) FROM SearchDB..paSearchJobID_0 WITH(NOLOCK) WHERE paSearchConditionID=@paSearchConditionID

			SET @MinId = @MinId+(@PageNumber-1)*@PageSize
			SELECT TOP (@PageSize) a.ID, a.cpMainID, a.caMainID, a.Name as JobName, a.dcJobTypeID, 
				a.dcJobTypeIDMinor, a.NeedNumber, a.dcSalaryID, a.EmployType, 
				a.dcRegionID, a.Responsibility, a.Demand, a.dcEducationID, 
				a.MinExperience, a.MinAge, a.MaxAge, a.IssueDate, a.IssueEND, 
				a.IsDelete, a.AddDate, a.RefreshDate, 
				a.LastModifyDate, b.Name as cpName, b.dcCompanySizeID, 
				b.HasLicence, b.UnLimitedDate, b.BalanceDate, b.Balance, 
				b.MemberType, STUFF((SELECT ','+LTRIM(x.dcIndustryid)+',c'+LTRIM(isnull(y.Category,0)) 
							FROM cpIndustry x,dcIndustry y WHERE x.dcIndustryid = y.id 
							AND x.cpMainid = b.id FOR XML PATH('')),1,1,'') cpIndustry,
				c.IsTop, b.IsRefreshed, a.SecondId EnJobID, b.SecondId EnCpMainID
			FROM JobPublish a WITH(NOLOCK), cpMainPublish b WITH(NOLOCK), SearchDB..paSearchJobID_0 c WITH(NOLOCK)
			WHERE a.cpMainID = b.ID AND a.id=c.JobID AND c.paSearchConditionID=@paSearchConditionID 
				  AND c.ID>=@MinId ORDER BY c.ID, a.ID DESC
		END
		ELSE IF (@TableID = 1)
		BEGIN
			SELECT @MinId = MIN(ID) FROM SearchDB..paSearchJobID_1 WITH(NOLOCK) WHERE paSearchConditionID=@paSearchConditionID

			SET @MinId = @MinId+(@PageNumber-1)*@PageSize
			SELECT TOP (@PageSize) a.ID, a.cpMainID, a.caMainID, a.Name as JobName, a.dcJobTypeID, 
				a.dcJobTypeIDMinor, a.NeedNumber, a.dcSalaryID, a.EmployType, 
				a.dcRegionID, a.Responsibility, a.Demand, a.dcEducationID, 
				a.MinExperience, a.MinAge, a.MaxAge, a.IssueDate, a.IssueEND, 
				a.IsDelete, a.AddDate, a.RefreshDate, 
				a.LastModifyDate, b.Name as cpName, b.dcCompanySizeID, 
				b.HasLicence, b.UnLimitedDate, b.BalanceDate, b.Balance, 
				b.MemberType, STUFF((SELECT ','+LTRIM(x.dcIndustryid)+',c'+LTRIM(isnull(y.Category,0)) 
							FROM cpIndustry x,dcIndustry y WHERE x.dcIndustryid = y.id 
							AND x.cpMainid = b.id FOR XML PATH('')),1,1,'') cpIndustry,
				c.IsTop, b.IsRefreshed, a.SecondId EnJobID, b.SecondId EnCpMainID
			FROM JobPublish a WITH(NOLOCK), cpMainPublish b WITH(NOLOCK), SearchDB..paSearchJobID_1 c WITH(NOLOCK)
			WHERE a.cpMainID = b.ID AND a.id=c.JobID AND c.paSearchConditionID=@paSearchConditionID 
				  AND c.ID>=@MinId ORDER BY c.ID, a.ID DESC
		END
		ELSE IF (@TableID = 2)
		BEGIN
			SELECT @MinId = MIN(ID) FROM SearchDB..paSearchJobID_2 WITH(NOLOCK) WHERE paSearchConditionID=@paSearchConditionID

			SET @MinId = @MinId+(@PageNumber-1)*@PageSize
			SELECT TOP (@PageSize) a.ID, a.cpMainID, a.caMainID, a.Name as JobName, a.dcJobTypeID, 
				a.dcJobTypeIDMinor, a.NeedNumber, a.dcSalaryID, a.EmployType, 
				a.dcRegionID, a.Responsibility, a.Demand, a.dcEducationID, 
				a.MinExperience, a.MinAge, a.MaxAge, a.IssueDate, a.IssueEND, 
				a.IsDelete, a.AddDate, a.RefreshDate, 
				a.LastModifyDate, b.Name as cpName, b.dcCompanySizeID, 
				b.HasLicence, b.UnLimitedDate, b.BalanceDate, b.Balance, 
				b.MemberType, STUFF((SELECT ','+LTRIM(x.dcIndustryid)+',c'+LTRIM(isnull(y.Category,0)) 
							FROM cpIndustry x,dcIndustry y WHERE x.dcIndustryid = y.id 
							AND x.cpMainid = b.id FOR XML PATH('')),1,1,'') cpIndustry,
				c.IsTop, b.IsRefreshed, a.SecondId EnJobID, b.SecondId EnCpMainID
			FROM JobPublish a WITH(NOLOCK), cpMainPublish b WITH(NOLOCK), SearchDB..paSearchJobID_2 c WITH(NOLOCK)
			WHERE a.cpMainID = b.ID AND a.id=c.JobID AND c.paSearchConditionID=@paSearchConditionID 
				  AND c.ID>=@MinId ORDER BY c.ID, a.ID DESC
		END
		ELSE IF (@TableID = 3)
		BEGIN
			SELECT @MinId = MIN(ID) FROM SearchDB..paSearchJobID_3 WITH(NOLOCK) WHERE paSearchConditionID=@paSearchConditionID

			SET @MinId = @MinId+(@PageNumber-1)*@PageSize
			SELECT TOP (@PageSize) a.ID, a.cpMainID, a.caMainID, a.Name as JobName, a.dcJobTypeID, 
				a.dcJobTypeIDMinor, a.NeedNumber, a.dcSalaryID, a.EmployType, 
				a.dcRegionID, a.Responsibility, a.Demand, a.dcEducationID, 
				a.MinExperience, a.MinAge, a.MaxAge, a.IssueDate, a.IssueEND, 
				a.IsDelete, a.AddDate, a.RefreshDate, 
				a.LastModifyDate, b.Name as cpName, b.dcCompanySizeID, 
				b.HasLicence, b.UnLimitedDate, b.BalanceDate, b.Balance, 
				b.MemberType, STUFF((SELECT ','+LTRIM(x.dcIndustryid)+',c'+LTRIM(isnull(y.Category,0)) 
							FROM cpIndustry x,dcIndustry y WHERE x.dcIndustryid = y.id 
							AND x.cpMainid = b.id FOR XML PATH('')),1,1,'') cpIndustry,
				c.IsTop, b.IsRefreshed, a.SecondId EnJobID, b.SecondId EnCpMainID
			FROM JobPublish a WITH(NOLOCK), cpMainPublish b WITH(NOLOCK), SearchDB..paSearchJobID_3 c WITH(NOLOCK)
			WHERE a.cpMainID = b.ID AND a.id=c.JobID AND c.paSearchConditionID=@paSearchConditionID 
				  AND c.ID>=@MinId ORDER BY c.ID, a.ID DESC
		END
		RETURN
	END
END TRY
BEGIN CATCH
	---检查是否已经建立临时表，已经建立则删除
	PRINT 'error'
	PRINT error_Message()
	PRINT error_number()
	PRINT error_line()
END CATCH









GO
/****** Object:  StoredProcedure [dbo].[mblJobEnByIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.06
--创建人：Nick
--说明：获取职位信息
--#####################################################
CREATE PROCEDURE [dbo].[mblJobEnByIDSelect]
(
	@JobID INT
)
AS
BEGIN TRY
	SELECT a.lng,a.lat,a.caMainID,a.RefreshDate,a.dcRegionId,a.dcJobTypeId,a.Welfare1,a.Welfare2,a.Welfare3,a.Welfare4,
	a.Welfare5,a.Welfare6,a.Welfare7,a.Welfare8,a.Welfare9,a.Welfare10,a.Welfare11,a.Welfare12,a.Welfare13,a.Welfare14,
	a.Welfare15,a.Welfare16,a.Welfare17,a.Welfare18,a.Welfare19,a.Lng,a.Lat,a.Name,a.cpMainID,i.secondid encpmainid,a.secondid enjobid,
	i.Name cpName,a.Responsibility,a.Demand,a.MinAge,
    a.MaxAge,b.Description JobType,c.FullName JobRegion,d.Description NeedNumber,e.Description EmployType,
    f.Description Salary,(CASE WHEN g.Description IS NULL THEN '不限' ELSE g.Description END) Education,
    h.Description Experience FROM Job a WITH(NOLOCK) 
    LEFT JOIN dcJobType b WITH(NOLOCK) ON a.dcJobTypeID=b.ID LEFT JOIN dcRegion c WITH(NOLOCK) ON 
    a.dcRegionID=c.ID LEFT JOIN dcOthers d WITH(NOLOCK) ON a.NeedNumber=d.DetailID AND d.Category='招聘人数' 
    LEFT JOIN dcOthers e WITH(NOLOCK) ON a.EmployType=e.DetailID AND e.Category='工作性质' 
    LEFT JOIN dcSalary f WITH(NOLOCK) ON a.dcSalaryID=f.ID LEFT JOIN dcEducation g WITH(NOLOCK) 
    ON a.dcEducationID=g.ID LEFT JOIN dcOthers h WITH(NOLOCK) ON a.MinExperience=h.DetailID AND 
    h.Category='职位要求工作经验' LEFT JOIN cpMain i WITH(NOLOCK) ON a.cpMainID=i.ID WHERE a.SecondId=@JobID
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[mblJobIntentionSave]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[mblJobIntentionSave]
(
	@cvMainID INT, 
	@RelatedWorkYears TINYINT,
	@EmployType TINYINT,
	@dcSalaryID TINYINT,
	@JobType VARCHAR(100),
	@JobPlace VARCHAR(100),
	@paMainID INT,
	@IsNegotiable BIT
)
AS
BEGIN
	IF @RelatedWorkYears IS NULL
		RETURN 0
	IF @EmployType IS NULL
		RETURN 0
	IF @dcSalaryID IS NULL
		RETURN 0
	IF @JobType IS NULL
		RETURN 0
	IF @JobPlace IS NULL
		RETURN 0

	IF NOT EXISTS(SELECT 'x' FROM cvMain WITH(NOLOCK) WHERE ID = @cvMainID AND paMainID = @paMainID)
		RETURN 0

	DECLARE @i INT, 
		@Name AS VARCHAR(100), 
		@JobType1 AS VARCHAR(10), 
		@JobPlace1 AS VARCHAR(10)

	BEGIN TRY
		DELETE FROM cvJobType WHERE cvMainID = @cvMainID
		SET @i = CHARINDEX(' ', @JobType)
		WHILE @i >= 1
		BEGIN
			IF LEFT(@JobType, @i-1) > ''
			BEGIN
				INSERT cvJobType(cvMainID, dcJobTypeID) VALUES(@cvMainID, LEFT(@JobType, @i-1))
				IF @JobType1 IS NULL
					SET @JobType1 = LEFT(@JobType, @i-1)
			END
			SET @JobType = SUBSTRING(@JobType, @i+1, LEN(@JobType)-@i)
			SET @i = CHARINDEX(' ', @JobType)
		END

		IF @JobType > ''
		BEGIN
			INSERT cvJobType(cvMainID, dcJobTypeID) VALUES(@cvMainID, @JobType)
			IF @JobType1 IS NULL
				SET @JobType1 = @JobType
		END

		DELETE FROM cvJobPlace WHERE cvMainID = @cvMainID
		SET @i = CHARINDEX(' ', @JobPlace)
		WHILE @i >= 1
		BEGIN
			IF LEFT(@JobPlace, @i-1) > '' 
			BEGIN
				INSERT cvJobPlace(cvMainID, dcRegionID) VALUES(@cvMainID, LEFT(@JobPlace, @i-1))
				IF @JobPlace1 IS NULL
					SET @JobPlace1 = LEFT(@JobPlace, @i-1)
			END
			SET @JobPlace = SUBSTRING(@JobPlace, @i+1, LEN(@JobPlace)-@i)
			SET @i = CHARINDEX(' ', @JobPlace)
		END
		IF @JobPlace > ''
		BEGIN
			INSERT cvJobPlace(cvMainID, dcRegionID) VALUES(@cvMainID, @JobPlace)
			IF @JobPlace1 IS NULL
				SET @JobPlace1 = @JobPlace
		END

		SELECT @Name = Name FROM cvMain WITH(NOLOCK) WHERE ID = @cvMainID
		IF(ISNULL(@Name, '未完成简历') = '未完成简历')
		BEGIN
			SELECT @Name = Description FROM dcRegion WITH(NOLOCK) WHERE ID = @JobPlace1
			SELECT @Name = @Name + '+' + Description FROM dcJobType WITH(NOLOCK) WHERE ID = @JobType1
			
			UPDATE cvMain SET Name = @Name,
				RelatedWorkYears = @RelatedWorkYears, 
				EmployType = @EmployType, 
				dcSalaryID = @dcSalaryID,
				IsNegotiable = @IsNegotiable
			WHERE ID = @cvMainID
		END
		ELSE
		BEGIN
			UPDATE cvMain SET RelatedWorkYears = @RelatedWorkYears, 
				EmployType = @EmployType, 
				dcSalaryID = @dcSalaryID,
				IsNegotiable = @IsNegotiable
			WHERE ID = @cvMainID
		END

		DECLARE @SQL AS VARCHAR(100)
		SET @SQL = 'EXEC pcCvMainByCvLevelUpdateNew 0, ' + LTRIM(STR(@cvMainID)) + ', 6, 1'
		EXEC(@SQL)
		SET @SQL = 'EXEC pcCvMainByCvLevelUpdateNew 1, ' + LTRIM(STR(@cvMainID)) + ', 6, 1'
		EXEC(@SQL)
		RETURN 1
	END TRY
	BEGIN CATCH
		RETURN 0
	END CATCH
END


set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON














GO
/****** Object:  StoredProcedure [dbo].[mblJobNewsList]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--Carl 2018-03-06 修改 增加 就业大数据信息及媒体动态
CREATE PROCEDURE [dbo].[mblJobNewsList]
(
	@dcProvinceID AS SMALLINT,
	@PageNum AS INT,
	@PageSize AS INT,
	@NewsType AS INT
)
AS
BEGIN
	DECLARE @COUNT INT
	IF @NewsType=18 --就业大数据
	BEGIN 
		SELECT @COUNT=COUNT(1) FROM NewsAnalysis WITH(NOLOCK) WHERE newstype=1 AND IsDelete = 0 

		IF @COUNT>200
			SET @COUNT=200

		SELECT *,@COUNT AS cnt FROM ( 
			SELECT TOP 200 ROW_NUMBER() OVER(ORDER BY AnnounceDate DESC) AS Rows,ID,Title,Author,AnnounceDate 
				FROM NewsAnalysis WITH(NOLOCK) WHERE newstype=1 AND IsDelete = 0 ) AS a 
				WHERE a.Rows BETWEEN (@PageNum-1)*@PageSize+1 AND @PageNum*@PageSize ORDER BY Rows

	END
	ELSE IF @NewsType=19 --媒体动态
	BEGIN
		SELECT @COUNT=COUNT(1) FROM MarketDb..MarketMedia a, MarketDb..MarketProvince b
				WHERE a.ID = b.MarketID
				AND b.Type = 1 AND a.MediaType = 1
				AND (b.ProvinceID = 0 OR b.ProvinceID = @dcProvinceID)
				
		IF @COUNT>200
			SET @COUNT=200

		SELECT *,@COUNT AS cnt FROM (
			SELECT TOP 200 ROW_NUMBER() OVER(ORDER BY a.AddDate DESC) AS Rows,a.Id,a.Title,a.Brief AS [Content],a.Url,a.AddDate AS AnnounceDate FROM MarketDb..MarketMedia a, MarketDb..MarketProvince b
					WHERE a.ID = b.MarketID
					AND b.Type = 1 AND a.MediaType = 1
					AND (b.ProvinceID = 0 OR b.ProvinceID = @dcProvinceID) ) AS a 
				WHERE a.Rows BETWEEN (@PageNum-1)*@PageSize+1 AND @PageNum*@PageSize ORDER BY Rows
	END
	ELSE
	BEGIN
		SELECT @COUNT=COUNT(1) FROM QlrcNews WITH(NOLOCK) WHERE 
			   (VersionID=@dcProvinceID) AND DetailType like '%,'+CONVERT(VARCHAR(10),@NewsType)+',%' AND DetailType NOT LIKE '%,2,%'
				AND NewsType = 2

		IF @COUNT>200
			SET @COUNT=200

		SELECT *,@COUNT AS cnt FROM(
			SELECT TOP 200 ROW_NUMBER() OVER(ORDER BY RefreshDate DESC) AS Rows,ID,Title,RefreshDate,Author,AnnounceDate  
			FROM QlrcNews WITH(NOLOCK) WHERE 
			   (VersionID=@dcProvinceID) AND DetailType like '%,'+CONVERT(VARCHAR(10),@NewsType)+',%' AND DetailType NOT LIKE '%,2,%'
				AND NewsType = 2
		) AS a 
		WHERE a.Rows BETWEEN (@PageNum-1)*@PageSize+1 AND @PageNum*@PageSize ORDER BY Rows
	END	
END
GO
/****** Object:  StoredProcedure [dbo].[mblJobStatusByIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.06
--创建人：Nick
--说明：获取职位当前状态
--#####################################################
CREATE PROCEDURE [dbo].[mblJobStatusByIDSelect]
(
	@ID INT
)
AS
BEGIN TRY
	SELECT IsDelete,(CASE WHEN IssueEnd<GETDATE() THEN 1 ELSE 0 END) IsOver,caMainid FROM Job WHERE ID=@ID
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[mblManagerSOLStatusByIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.06
--创建人：Nick
--说明：得到顾问的在线状态
--#####################################################
CREATE PROCEDURE [dbo].[mblManagerSOLStatusByIDSelect]
(
    @manageruserid INT
)
AS
BEGIN
    SELECT TOP 1 Id, Name, SOLStatus, Photo, OpenName FROM ManagerUser WHERE Id = @manageruserid
END
GO
/****** Object:  StoredProcedure [dbo].[mblMblFeedBackInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.7
--创建人：Nick
--说明：在线反馈
--#####################################################
CREATE PROCEDURE [dbo].[mblMblFeedBackInsert]
(
	@Content VARCHAR(500),
	@Version VARCHAR(50),
	@paMainID VARCHAR(20),
	@Name VARCHAR(50),
	@strMobile VARCHAR(20),
	@Email VARCHAR(50)
)
AS
BEGIN
	INSERT INTO mblFeedBack(Content,Version,paMainID,Name,Mobile,Email) 
	VALUES(dbo.SafeSQL(@Content),dbo.SafeSQL(@Version),@paMainID,@Name,@strMobile,@Email)
END


GO
/****** Object:  StoredProcedure [dbo].[mblMblSqlByVersionSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.7
--创建人：Nick
--说明：
--#####################################################
CREATE PROCEDURE [dbo].[mblMblSqlByVersionSelect]
(
	@version VARCHAR(100)
)
AS
BEGIN
	SELECT * FROM mblSql WITH(NOLOCK) WHERE Version>@version
END


GO
/****** Object:  StoredProcedure [dbo].[mblMblSqlSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.7
--创建人：Nick
--说明：
--#####################################################
CREATE PROCEDURE [dbo].[mblMblSqlSelect]
AS
BEGIN
	SELECT Top 1 Version FROM mblSql WITH(NOLOCK) ORDER BY Version DESC
END


GO
/****** Object:  StoredProcedure [dbo].[mblMblVersionByAppTypeSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.7
--创建人：Nick
--说明：获取最新版本信息
--#####################################################
CREATE PROCEDURE [dbo].[mblMblVersionByAppTypeSelect]
(
	@appType VARCHAR(20)
)
AS
BEGIN
	SELECT TOP 1 * FROM mblVersion WITH(NOLOCK) WHERE AppType=@appType ORDER BY AddDate DESC
END


GO
/****** Object:  StoredProcedure [dbo].[mblmsEmailPrevSendInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.7
--创建人：Nick
--说明：发送邮件
--#####################################################
CREATE PROCEDURE [dbo].[mblmsEmailPrevSendInsert]
(
	@cpMainId INT,
	@paMainId INT,
	@EmailNo INT,
	@JasonData VARCHAR(MAX),
	@EmailTitle VARCHAR(50),
	@Email VARCHAR(50),
	@dcSubsiteId INT
)
AS
BEGIN
	INSERT INTO msEmailPrevSend
	(cpMainId,paMainId,EmailNo,EmailTitle,JsonData,Email,dcSubsiteId,IsSend)
	VALUES(@cpMainId,@paMainId,@EmailNo,@EmailTitle,@JasonData,@Email,@dcSubsiteId,0)
END

GO
/****** Object:  StoredProcedure [dbo].[mblMyBespeakListSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.7
--创建人：Nick
--说明：我的预约
--#####################################################
CREATE PROCEDURE [dbo].[mblMyBespeakListSelect]
(
	@PamainID INT
)
AS
BEGIN
	SELECT TOP 500 a.paMainID, b.id , b.RecruitmentName , b.BeginDate,c.Description as cityName, 
	d.PlaceName,d.lng,d.lat, d.Address,
	( SELECT COUNT(id) from [MarketDb]..[RmCompany] WHERE RecruitmentID = b.id AND [Status]<=1 ) as cpNum,
	( SELECT COUNT(id) from [MarketDb]..[RmPerson] WHERE RecruitmentID = b.id) as paNum,
	( SELECT COUNT(id) from [MarketDb]..[RmPersonInvitation] WHERE RecruitmentID = b.id and paMainID=@paMainID ) as myInvitCpNum 
	FROM [MarketDb]..[RmPerson] a, [MarketDb]..[Recruitment] b, [MainDb]..[dcRegion] c, [MarketDb]..[RmPlace] d 
	WHERE a.RecruitmentID=b.id 
	AND b.CityID = c.id 
	AND b.RecruitmentPlaceId = d.id 
	AND a.paMainID=@PamainID
	ORDER BY a.AddDate DESC
END


GO
/****** Object:  StoredProcedure [dbo].[mblNewsList]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[mblNewsList]
(
	@dcProvinceID AS SMALLINT,
	@PageNum AS INT,
	@PageSize AS INT
)
AS
BEGIN
	SELECT *
	FROM SearchDb..mblQlrcNews WITH(NOLOCK)
	WHERE ProvinceId = @dcProvinceID
	AND Rows BETWEEN (@PageNum-1) * @PageSize+1 AND @PageNum * @PageSize
	ORDER BY Rows
END





GO
/****** Object:  StoredProcedure [dbo].[mblPaAttentionSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[mblPaAttentionSelect]
(
	@WHERE VARCHAR(1000),
	@Order VARCHAR(100),
	@Page SMALLINT,
	@caMainID INT,
	@cpMainID INT
)
AS
SET NOCOUNT ON
BEGIN
	SET @Where = dbo.SafeSql(@Where)
	SET @ORDER = REPLACE(dbo.SafeSQL(@ORDER), '''', '''''')
		
	DECLARE @SQL AS VARCHAR(2000)

	CREATE TABLE #T1(
		TitleID BIGINT,
		ID INT,
		paMainID INT,
		cvMainID INT,
		AddDate SMALLDATETIME,
		IsMatched BIT,
		Degree TINYINT,
		RelatedWorkYears TINYINT,
		LivePlace NVARCHAR(50),
		Gender BIT,
		paName NVARCHAR(20),
		BirthDay INT,
		HasPhoto TINYINT,
		Attachment VARCHAR(50) COLLATE Chinese_PRC_CI_AS,
		IsNameHidden BIT,
		Valid TINYINT,
		IsViewed BIT,
		HasJobApply BIT,
		HasInterview BIT,
		HasRemark BIT,
		HasFavorate BIT,
		cvEducationID INT,
		College NVARCHAR(50),
		EduType TINYINT,
		MajorName NVARCHAR(20),
		Graduation INT,
		Speciality VARCHAR(MAX) COLLATE Chinese_PRC_CI_AS,
		Experience VARCHAR(MAX) COLLATE Chinese_PRC_CI_AS,
		cvMatch INT,
		RecruitmentID INT,
		RecruitmentName NVARCHAR(100),
		RecruitmentDate SMALLDATETIME,
		MobileVerifyDate SMALLDATETIME,
		IsOnline BIT,
		JobID INT,
		JobName VARCHAR(50),
		AttentionType INT
	)
	CREATE TABLE #T(
		TitleID BIGINT,
		ID INT,
		paMainID INT,
		cvMainID INT,
		AddDate SMALLDATETIME,
		IsMatched BIT,
		Degree TINYINT,
		RelatedWorkYears TINYINT,
		LivePlace NVARCHAR(50),
		Gender BIT,
		paName NVARCHAR(20),
		BirthDay INT,
		HasPhoto TINYINT,
		Attachment VARCHAR(50) COLLATE Chinese_PRC_CI_AS,
		IsNameHidden BIT,
		Valid TINYINT,
		IsViewed BIT,
		HasJobApply BIT,
		HasInterview BIT,
		HasRemark BIT,
		HasFavorate BIT,
		cvEducationID INT,
		College NVARCHAR(50),
		EduType TINYINT,
		MajorName NVARCHAR(20),
		Graduation INT,
		Speciality VARCHAR(MAX) COLLATE Chinese_PRC_CI_AS,
		Experience VARCHAR(MAX) COLLATE Chinese_PRC_CI_AS,
		cvMatch INT,
		RecruitmentID INT,
		RecruitmentName NVARCHAR(100),
		RecruitmentDate SMALLDATETIME,
		MobileVerifyDate SMALLDATETIME,
		IsOnline BIT,
		JobID INT,
		JobName VARCHAR(50),
		AttentionType INT
	)
	SET @SQL='
		INSERT INTO #T1
		(TitleID, ID, paMainID, AddDate,LivePlace,Gender,
			BirthDay,HasPhoto,MobileVerifyDate,IsOnline,AttentionType)

		SELECT ROW_NUMBER() OVER (ORDER BY ' + @ORDER + ') AS TitleID, a.ID, c.ID,a.AddDate, c.LivePlace,
			c.Gender,c.BirthDay,c.HasPhoto,c.MobileVerifyDate,dbo.GetPaOnlineStatus(c.ID),1
		FROM paAttention a WITH(NOLOCK),paMain c WITH(NOLOCK)
		WHERE a.paMainID = c.ID AND AttentionType = 1 AND AttentionID = '+CONVERT(VARCHAR(20),@cpMainID) 
	PRINT @SQL
	--IF LEN(@WHERE) > 0
	--	SET @SQL = @SQL + ' AND ' + @WHERE

	SET @SQL = @SQL + 'ORDER BY a.AddDate '
	EXEC(@SQL)
	SET @SQL='
		INSERT INTO #T1
		(TitleID, ID, paMainID, AddDate,LivePlace,Gender,
			BirthDay,HasPhoto,MobileVerifyDate,IsOnline,JobID,JobName,AttentionType)
		SELECT ROW_NUMBER() OVER (ORDER BY ' + @ORDER + ') AS TitleID, a.ID, c.ID,a.AddDate, c.LivePlace,
			c.Gender,c.BirthDay,c.HasPhoto,c.MobileVerifyDate,dbo.GetPaOnlineStatus(c.ID),b.ID,b.Name,2
		FROM paAttention a WITH(NOLOCK),Job b WITH(NOLOCK),paMain c WITH(NOLOCK)
		WHERE a.paMainID = c.ID 
		AND AttentionType = 2
		AND a.AttentionID = b.ID
		AND b.IsDelete = 0'			
	IF LEN(@WHERE) > 0
		SET @SQL = @SQL + ' AND '+@WHERE

	SET @SQL = @SQL + ' ORDER BY a.AddDate '
	--PRINT @SQL
	EXEC(@SQL)

	INSERT INTO #T 
	SELECT *  FROM #T1 ORDER BY AddDate DESC 

	--修改cvmainID
	UPDATE a SET CvMainID = (
		SELECT TOP 1 ID FROM CvMain WITH(NOLOCK)
		WHERE PaMainID  = a.PaMainID
		AND (Valid > 0 OR substring(CvLevel,0,7)='111111' OR substring(CvLevel,0,7) = '111101' )
		ORDER BY RefreshDate DESC
	) FROM #T a

	UPDATE a SET CvMainID = (
		SELECT TOP 1 ID FROM CvMain WITH(NOLOCK)
		WHERE PaMainID  = a.PaMainID
		ORDER BY RefreshDate DESC
	) FROM #T a 

	DELETE FROM #T WHERE CvMainID IS NULL

	--修改简历信息
	UPDATE  a
	SET a.Degree = b.Degree,
	a.RelatedWorkYears = b.RelatedWorkYears,
	a.Attachment = b.Attachment,
	a.IsNameHidden = b.IsNameHidden,
	a.Valid = b.Valid
	FROM #T a,CvMain b
	WHERE a.CvMainID = b.ID

	IF LEN(@WHERE) > 0
		SET @SQL = @SQL + ' AND ' + @WHERE

	IF(@Page < 1)
		SET @Page = 1
	IF NOT EXISTS(SELECT 'x' FROM #t WHERE TitleID > (@Page-1)*20 AND  TitleID <= @Page*20)
		SET @Page = 1
		
	UPDATE #T SET paName = LEFT(dbo.GetPersonName(cvMainID, @cpMainID), 20), IsViewed = (SELECT TOP 1 '1' FROM caCvViewLog WITH(NOLOCK) WHERE cvMainID=#T.cvMainID AND caMainID=@caMainID),
		HasFavorate = (SELECT TOP 1 '1' FROM caFavorate WITH(NOLOCK) WHERE caMainID=@caMainID AND cvMainID=#T.cvMainID),
		HasInterview = (SELECT TOP 1 '1' FROM exInterview a WITH(NOLOCK) INNER JOIN Job b WITH(NOLOCK) ON a.JobID=b.ID WHERE a.CompanyDeleted=0 AND b.caMainID=@caMainID AND cvMainID=#T.cvMainID),
		HasRemark = (SELECT TOP 1 '1' FROM caCvRemark WITH(NOLOCK) WHERE caMainID=@caMainID AND cvMainID=#T.cvMainID),
		HasJobApply = (SELECT TOP 1 '1' FROM exJobApply a WITH(NOLOCK) INNER JOIN Job b WITH(NOLOCK) ON a.JobID=b.ID WHERE a.CompanyDeleted=0 AND b.caMainID=@caMainID AND cvMainID=#t.cvMainID)
	WHERE TitleID > (@Page-1)*20 AND  TitleID <= @Page*20

	UPDATE #T SET Speciality = (
		SELECT Speciality FROM cvMain WITH(NOLOCK)
		WHERE cvMain.ID = #T.cvMainID)
	WHERE TitleID > (@Page-1)*20 AND  TitleID <= @Page*20
		
	UPDATE #T SET Experience = (
		SELECT TOP 1 ISNULL(Description,DescriptionEng) FROM cvExperience WITH(NOLOCK)
		WHERE cvExperience.cvMainID = #T.cvMainID
		ORDER BY BeginDate DESC)
	WHERE TitleID > (@Page-1)*20 AND  TitleID <= @Page*20

	UPDATE #T SET cvEducationID = (
		SELECT TOP 1 ID FROM cvEducation WITH(NOLOCK)
		WHERE cvEducation.cvMainID = #T.cvMainID
		AND #T.Degree = cvEducation.Degree
		ORDER BY Graduation DESC)
	WHERE TitleID > (@Page-1)*20 AND  TitleID <= @Page*20

	UPDATE a SET a.College = ISNULL(b.GraduateCollage,b.GraduateCollageEng),a.EduType = b.EduType, 
		a.MajorName = ISNULL(b.MajorName,b.MajorNameEng), a.Graduation = b.Graduation
	FROM #T a, cvEducation b WITH(NOLOCK)
	WHERE b.ID = a.cvEducationID AND a.TitleID > (@Page-1)*20 AND a. TitleID <= @Page*20
		
	--UPDATE a SET a.RecruitmentName = b.RecruitmentName, a.RecruitmentDate = b.EndDate
	--FROM #T a, Recruitment b WITH(NOLOCK)
	--WHERE b.ID = a.RecruitmentID AND a.TitleID > (@Page-1)*20 AND a. TitleID <= @Page*20
		
	UPDATE #T SET cvMatch = dbo.GetCvMatch(cvMainID,JobID) WHERE TitleID > (@Page-1)*20 AND  TitleID <= @Page*20

	SELECT COUNT(*) FROM #T WITH(NOLOCK)
	SELECT * FROM #T WITH(NOLOCK) WHERE TitleID > (@Page-1)*20 AND  TitleID <= @Page*20

	--计算匹配度
	DROP TABLE #T1
	DROP TABLE #T
END

 SELECT @@ROWCOUNT
GO
/****** Object:  StoredProcedure [dbo].[mblPaByExchangeSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[mblPaByExchangeSelect]
(
	@paMainId INT
)
AS
BEGIN
	SELECT
		(SELECT COUNT(*) FROM ExJobApply WITH(NOLOCK) WHERE cvMainId IN(SELECT id FROM cvMain WITH(NOLOCK) WHERE paMainId = @paMainId)) AS JobApplyNumber,
		(SELECT COUNT(*) FROM paFavorate WITH(NOLOCK) WHERE paMainId = @paMainId) AS FavorateNumber,
		(SELECT COUNT(*) FROM caCvViewLog WITH(NOLOCK) WHERE cvMainId IN(SELECT id FROM cvMain WITH(NOLOCK) WHERE paMainId = @paMainId)) AS cvViewNumber
END


set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON














GO
/****** Object:  StoredProcedure [dbo].[mblPaFavorateBatchDelete]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[mblPaFavorateBatchDelete]
(
	@AllID VARCHAR(1000),
	@paMainID INT
)
AS
BEGIN TRY
	--生成临时表
	DECLARE @t AS TABLE(ID INT)
	INSERT INTO @t
	SELECT * FROM dbo.fnSplit(@AllID, ',')
 
	DELETE FROM paFavorate WHERE JobID IN(SELECT ID FROM @t) AND paMainID=@paMainID
END TRY
BEGIN CATCH
	GOTO ERR
END CATCH
RETURN 1
ERR:
BEGIN
	RETURN 0
END














GO
/****** Object:  StoredProcedure [dbo].[mblPaFavorateSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[mblPaFavorateSelect]
(
	@WHERE VARCHAR(1000),
	@Order VARCHAR(100)
)
AS
BEGIN
	BEGIN TRY
		SET @Where = dbo.SafeSql(@Where)
		SET @ORDER = dbo.SafeSql(@Order)
		IF LEN(@ORDER)=0
			SET @ORDER = 'a.ID DESC '
		DECLARE @SQL AS VARCHAR(2000)
		SET @SQL='SELECT a.ID,a.paMainID,a.JobID,a.AddDate,a.Remark,b.Name as JobName,b.IssueDate,
				b.IssueEND,b.dcRegionID,b.IsDelete, c.Name as cpName,c.ID as cpID,c.HasLicence,c.IsAgent,
				c.Membertype,d.FullName Region
			FROM paFavorate a WITH(NOLOCK) Inner Join Job b WITH(NOLOCK) ON a.JobID=b.ID 
			Inner Join cpMain c WITH(NOLOCK) ON b.cpMainID=c.ID 
			INNER JOIN dcRegion d ON d.ID=b.dcRegionID '
		IF LEN(@WHERE)>0
			SET @SQL=@SQL + ' WHERE '+ @WHERE
		IF LEN(@ORDER)>0
			SET @SQL=@SQL + ' ORDER BY '+@ORDER
		EXEC(@SQL)
	END TRY
	BEGIN CATCH
	END CATCH
END



GO
/****** Object:  StoredProcedure [dbo].[mblPaFeedBackInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[mblPaFeedBackInsert]
(
	@Content NVARCHAR(200),
	@Version VARCHAR(50),
	@paMainID INT,
	@Name VARCHAR(50),
	@Telephone VARCHAR(11),
	@Email VARCHAR(50)
)
AS
BEGIN
	INSERT INTO mblFeedBack(Content,Version,paMainID,Name,Mobile,Email) VALUES(@Content,@Version,@paMainID,@Name,@Telephone,@Email)
END










GO
/****** Object:  StoredProcedure [dbo].[mblpaGetPasswordLogByPamainIDUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.6
--创建人：Nick
--说明：重置密码
--#####################################################
CREATE PROCEDURE [dbo].[mblpaGetPasswordLogByPamainIDUpdate]
(
	@PaMainID INT
)
AS
BEGIN
	UPDATE paGetPasswordLog SET IsReset=1 
	WHERE AskNo=(
		SELECT TOP 1 AskNo 
		FROM paGetPasswordLog WITH(NOLOCK) 
		WHERE pamainID = @PaMainID
		ORDER BY ID DESC
	) 
END


GO
/****** Object:  StoredProcedure [dbo].[mblpaIOSBindDelete]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[mblpaIOSBindDelete]
(
	@paMainID INT,
	@UniqueID VARCHAR(100)
)
AS
BEGIN
	DELETE FROM paIOSBind WHERE UniqueID = @UniqueID
END
GO
/****** Object:  StoredProcedure [dbo].[mblpaIOSBindInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[mblpaIOSBindInsert]
(
	@paMainID INT,
	@UniqueID VARCHAR(100),
	@ClientType TINYINT
)
AS
BEGIN TRY
	IF LEN(ISNULL(@UniqueID,'')) = 0
		RETURN
	IF NOT EXISTS(SELECT 1 FROM paIOSBind WITH(NOLOCK) WHERE PaMainID = @paMainID AND UniqueID = @UniqueID AND ClientType = @ClientType)
	BEGIN
		INSERT INTO paIOSBind VALUES(@paMainID,@UniqueID,GETDATE(),@ClientType)
		RETURN 1
	END
	ELSE
	BEGIN
		RETURN 0
	END
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[mblpaLoginContactByIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.6
--创建人：Nick
--说明：获取第三方登录的用户信息
--#####################################################
CREATE PROCEDURE [dbo].[mblpaLoginContactByIDSelect]
(
	@Openid VARCHAR(100)
)
AS
BEGIN
	SELECT TOP 1 b.ID,b.UserName,b.PassWord 
	FROM paLoginContact a WITH(NOLOCK), paMain b WITH(NOLOCK) 
	WHERE a.paMainID = b.ID 
		AND a.OpenID = @Openid 
		AND a.OpenID > '' 
	ORDER BY a.AddDate DESC
END


GO
/****** Object:  StoredProcedure [dbo].[mblpaLoginContactByOpenIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.06
--创建人：Nick
--说明：根据微信号得到微信绑定信息
--#####################################################
CREATE PROCEDURE [dbo].[mblpaLoginContactByOpenIDSelect]
(
	@OpenID VARCHAR(50)
)
AS
BEGIN TRY
	SELECT a.*,b.UserName 
	FROM paLoginContact a,pamain b 
	WHERE a.openid=@OpenID 
	AND a.ContactType=4 
	AND a.PamainID = b.ID
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[mblPaLoginContactDelete]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.4
--创建人：Nick
--说明：删除绑定信息
--#####################################################
CREATE PROCEDURE [dbo].[mblPaLoginContactDelete]
(
	@OpenID VARCHAR(50)
)
AS
BEGIN
	DECLARE @paMainId INT
	SELECT @paMainId = paMainId FROM PaLoginContact WHERE OpenID = @OpenID AND ContactType = 4
	DELETE FROM PaLoginContact WHERE OpenID = @OpenID AND ContactType = 4
	UPDATE paMain SET IsUseYourFood = 0 WHERE id = @paMainId AND isUseYourFood = 1
END


GO
/****** Object:  StoredProcedure [dbo].[mblPaMainByCvIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.06
--创建人：Nick
--说明：获取个人用户信息
--#####################################################
CREATE PROCEDURE [dbo].[mblPaMainByCvIDSelect]
(
	@cvMainID INT
)
AS
BEGIN TRY
	SELECT a.mobile,a.Gender,a.id,dbo.GetPaOnlineStatus(a.id) IsOnline,name 
	FROM pamain a 
	WHERE id IN (
		SELECT pamainid 
		FROM cvmain 
		WHERE id=@cvMainID)
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[mblPaMainByIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.6
--创建人：Nick
--说明：获取注册时间
--#####################################################
CREATE PROCEDURE [dbo].[mblPaMainByIDSelect]
(
	@ID INT
)
AS
BEGIN
	SELECT AddDate,name FROM paMain WITH(NOLOCK) WHERE ID=@ID
END


GO
/****** Object:  StoredProcedure [dbo].[mblPaMainRegisterModeUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.6
--创建人：Nick
--说明：修改mode
--#####################################################
CREATE PROCEDURE [dbo].[mblPaMainRegisterModeUpdate]
(
	@RegisterMode INT,
	@ID INT
)
AS
BEGIN
	UPDATE pamain SET RegisterMode=@RegisterMode WHERE id=@ID
END


GO
/****** Object:  StoredProcedure [dbo].[mblPaMainSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[mblPaMainSelect]
	@ID INT
AS
BEGIN
	SELECT 1 dcCareerStatus,a.*, b.FullName LiveRegion, c.FullName GrowRegion, d.FullName AccountRegion, ISNULL(e.Description,'目前处于离职状态，可即刻上岗') CareerStatus, f.PhotoProcessed,
		(SELECT TOP 1 LoginIP FROM paLoginLog WITH(NOLOCK) WHERE paLoginLog.paMainID = a.ID ORDER BY ID DESC) AS LastLoginIP,
		(SELECT COUNT(1) FROM paLoginLog WITH(NOLOCK) WHERE paLoginLog.paMainID = a.ID AND AddDate > CONVERT(VARCHAR(10), GETDATE(), 120)) AS TodayLoginNum
	FROM paMain a WITH(NOLOCK INDEX(PK_paMain))
	LEFT JOIN dcRegion b WITH(NOLOCK) ON a.LivePlace=b.ID
	LEFT JOIN dcRegion c WITH(NOLOCK) ON a.GrowPlace=c.ID
	LEFT JOIN dcRegion d WITH(NOLOCK) ON a.AccountPlace=d.ID
	LEFT JOIN dcCareerStatus e WITH(NOLOCK) ON a.dcCareerStatus=e.ID
	LEFT JOIN paPhoto f WITH(NOLOCK) ON a.HasPhoto<2 AND a.ID=f.paMainID
	WHERE a.ID=@ID
END














GO
/****** Object:  StoredProcedure [dbo].[mblPaMainUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--修改harry 2018-7-5 处理liveplace等
CREATE PROCEDURE [dbo].[mblPaMainUpdate]
(
	@paMainID INT,
	@cvMainID INT,
	@Name VARCHAR(30),
	@Gender BIT,
	@BirthDay INT,
	@LivePlace VARCHAR(6),
	@AccountPlace VARCHAR(6),
	@GrowPlace VARCHAR(6),
	@Mobile VARCHAR(13),
	@dcCareerStatus TINYINT,
	@IP VARCHAR(39)
)
AS
IF ISNULL(@paMainID, 0) = 0
	RETURN -1
IF dbo.TrimNULL(@Name) IS NULL
	RETURN -1
IF dbo.TrimNULL(@Mobile) IS NULL
	RETURN -1
IF  CHARINDEX(' ', @LivePlace) >2
BEGIN
	SET @LivePlace=substring(@LivePlace,1,charindex(' ',@LivePlace)-1)
END
IF  CHARINDEX(' ', @AccountPlace) >2
BEGIN
	SET @AccountPlace=substring(@AccountPlace,1,charindex(' ',@AccountPlace)-1)
END
IF  CHARINDEX(' ', @GrowPlace) >2
BEGIN
	SET @GrowPlace=substring(@GrowPlace,1,charindex(' ',@GrowPlace)-1)
END

IF EXISTS(SELECT 'x' FROM Person_BLACK WITH(NOLOCK) WHERE Mobile = @Mobile)
BEGIN
	----有黑名单，则增加拒绝次数
	UPDATE Person_Black SET RefuseCount = RefuseCount + 1 WHERE Mobile = @Mobile
	RETURN -1
END
BEGIN TRAN
	BEGIN TRY
		DECLARE @NameOld AS VARCHAR(12)
		DECLARE @MobileOld AS VARCHAR(13)
		DECLARE @Modify AS INT
		-- @Modify=-1未修改需审核项， @Modify=0修改中文项目； @Modify=1修改了英文项目
		SET @Modify=-1

		--获得原始数据
		SELECT @NameOld=Name,@MobileOld=Mobile
		FROM paMain WITH(NOLOCK INDEX(PK_paMain))
		WHERE ID = @paMainID

		DECLARE @CNAME AS VARCHAR(12)
		SET @CNAME = @Name

		IF @BirthDay!=0
		BEGIN 
			UPDATE paMain
			SET Name=@CNAME,
				Gender=@Gender,
				BirthDay=@BirthDay,
				LivePlace=@LivePlace,
				AccountPlace=@AccountPlace,
				GrowPlace=@GrowPlace,
				Mobile=@Mobile,
				dcCareerStatus=@dcCareerStatus,
				LastModifyDate=GETDATE()
			WHERE ID=@paMainID
			 
		END 
		
		--保存到bsCvModify,姓名
		IF ISNULL(@NameOld, '') <> @CNAME
		BEGIN
			DELETE FROM bsCvModify WHERE paMainID = @paMainID AND Location = 'ac1'
			INSERT INTO bsCvModify(paMainID,Location,ColValue) VALUES(@paMainID,'ac1',@CNAME)
			SET @Modify=0

			INSERT INTO paOperationLog (paMainID, Operation, Details, IP) 
			VALUES(@paMainID, 30,'更新姓名，原姓名：<' + ISNULL(@NameOld, '') + '>；新姓名：<' + @CName + '>', @IP)
		END

		--手机号码
		IF ISNULL(@MobileOld, '') <> @Mobile
		BEGIN
			DELETE FROM bsCvModify WHERE paMainID = @paMainID AND Location = 'ac4'
			--INSERT INTO bsCvModify(paMainID,Location,ColValue) VALUES(@paMainID,'ac4',@Mobile)
			--SET @Modify=0

			INSERT INTO paOperationLog (paMainID, Operation, Details, IP) 
			VALUES(@paMainID, 35,'更新手机号，原手机号：<' + ISNULL(@MobileOld, '') + '>；新手机号：<' + @Mobile + '>', @IP)
		END
		
		----修改cvMain.cvLevel
		UPDATE cvMain SET cvLevel='11' + RIGHT(cvLevel,8) WHERE paMainID = @paMainID

		--1小时内不重复刷新，防止刷新排名
		UPDATE cvmain SET RefreshDate = GETDATE() WHERE ID=@cvMainID AND DATEADD(HOUR, 1, RefreshDate) < GETDATE() AND paMainID = @paMainID
		----12小时内只保留一次修改记录
		DELETE FROM paOperationLog WHERE paMainID=@paMainID AND Operation=11 AND AddDate>GETDATE()-0.5
		INSERT INTO paOperationLog (paMainID,Operation,Details,IP) VALUES(@paMainID,11,'更新基本信息成功。',@IP)

	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH

COMMIT TRAN
RETURN 1
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END



GO
/****** Object:  StoredProcedure [dbo].[mblPaMainUpdate20171110]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--修改harry 2018-7-5 处理liveplace等
CREATE PROCEDURE [dbo].[mblPaMainUpdate20171110]
(
    @paMainID INT,
    @cvMainID INT,
    @Name VARCHAR(30),
    @Gender BIT,
    @BirthDay INT,
    @LivePlace VARCHAR(6),
    @AccountPlace VARCHAR(6),
    @GrowPlace VARCHAR(6),
    @Mobile VARCHAR(13),
    @dcCareerStatus TINYINT,
    @IP VARCHAR(39),
	@dcMapPlaceID INT
)
AS
IF ISNULL(@paMainID, 0) = 0
    RETURN -1
IF dbo.TrimNULL(@Name) IS NULL
    RETURN -1
IF dbo.TrimNULL(@Mobile) IS NULL
    RETURN -1

IF EXISTS(SELECT 'x' FROM Person_BLACK WITH(NOLOCK) WHERE Mobile = @Mobile)
BEGIN
    ----有黑名单，则增加拒绝次数
    UPDATE Person_Black SET RefuseCount = RefuseCount + 1 WHERE Mobile = @Mobile
    RETURN -1
END
BEGIN TRAN
    BEGIN TRY
	
		IF  CHARINDEX(' ', @LivePlace) >2
		BEGIN
			SET @LivePlace=substring(@LivePlace,1,charindex(' ',@LivePlace)-1)
		END
		IF  CHARINDEX(' ', @AccountPlace) >2
		BEGIN
			SET @AccountPlace=substring(@AccountPlace,1,charindex(' ',@AccountPlace)-1)
		END
		IF  CHARINDEX(' ', @GrowPlace) >2
		BEGIN
			SET @GrowPlace=substring(@GrowPlace,1,charindex(' ',@GrowPlace)-1)
		END
		
	
        DECLARE @NameOld AS VARCHAR(12)
        DECLARE @MobileOld AS VARCHAR(13)
        DECLARE @Modify AS INT
        -- @Modify=-1未修改需审核项， @Modify=0修改中文项目； @Modify=1修改了英文项目
        SET @Modify=-1

        --获得原始数据
        SELECT @NameOld=Name,@MobileOld=Mobile
        FROM paMain WITH(NOLOCK INDEX(PK_paMain))
        WHERE ID = @paMainID

        DECLARE @CNAME AS VARCHAR(12)
        SET @CNAME = @Name
        UPDATE paMain
        SET Name=@CNAME,
            Gender=@Gender,
            BirthDay=@BirthDay,
            LivePlace=@LivePlace,
            AccountPlace=@AccountPlace,
            GrowPlace=@GrowPlace,
            Mobile=@Mobile,
			dcMapPlaceID=@dcMapPlaceID,
            --dcCareerStatus#@dcCareerStatus,
            LastModifyDate=GETDATE()
        WHERE ID=@paMainID
        
        --保存到bsCvModify,姓名
        IF ISNULL(@NameOld, '') <> @CNAME
        BEGIN
            DELETE FROM bsCvModify WHERE paMainID = @paMainID AND Location = 'ac1'
            INSERT INTO bsCvModify(paMainID,Location,ColValue) VALUES(@paMainID,'ac1',@CNAME)
            SET @Modify=0

            INSERT INTO paOperationLog (paMainID, Operation, Details, IP) 
            VALUES(@paMainID, 30,'更新姓名，原姓名：<' + ISNULL(@NameOld, '') + '>；新姓名：<' + @CName + '>', @IP)
        END

        --手机号码
        IF ISNULL(@MobileOld, '') <> @Mobile
        BEGIN
            DELETE FROM bsCvModify WHERE paMainID = @paMainID AND Location = 'ac4'
            --INSERT INTO bsCvModify(paMainID,Location,ColValue) VALUES(@paMainID,'ac4',@Mobile)
            --SET @Modify=0

            INSERT INTO paOperationLog (paMainID, Operation, Details, IP) 
            VALUES(@paMainID, 35,'更新手机号，原手机号：<' + ISNULL(@MobileOld, '') + '>；新手机号：<' + @Mobile + '>', @IP)
        END
        
        ----修改cvMain.cvLevel
        UPDATE cvMain SET cvLevel='11' + RIGHT(cvLevel,8) WHERE paMainID = @paMainID

        --1小时内不重复刷新，防止刷新排名
        UPDATE cvmain SET RefreshDate = GETDATE() WHERE ID=@cvMainID AND DATEADD(HOUR, 1, RefreshDate) < GETDATE() AND paMainID = @paMainID
        ----12小时内只保留一次修改记录
        DELETE FROM paOperationLog WHERE paMainID=@paMainID AND Operation=11 AND AddDate>GETDATE()-0.5
        INSERT INTO paOperationLog (paMainID,Operation,Details,IP) VALUES(@paMainID,11,'更新基本信息成功。',@IP)

    END TRY
    BEGIN CATCH
        GOTO ERR
    END CATCH

COMMIT TRAN
RETURN 1
ERR:
BEGIN
    ROLLBACK TRAN
    RETURN 0
END

GO
/****** Object:  StoredProcedure [dbo].[mblPaPageViewLogByNoViewSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[mblPaPageViewLogByNoViewSelect]
(
	@PaMainID INT,
	@PageType INT --页面类型1 页脚 2 Notice页面
)
AS
SET NOCOUNT ON
IF @paMainID = 0
	RETURN
BEGIN	
	IF NOT EXISTS(SELECT 'x' FROM paPageViewLog WITH(NOLOCK) WHERE paMainId = @PaMainID)
	BEGIN
		INSERT INTO paPageViewLog(paMainId,addDate,InterviewDate,IntentionDate,ViewLogDate,AttentionDate,YourFoodDate,ApplyReplyDate) 
		VALUES(@PaMainID, GETDATE() - 10, GETDATE() - 10, GETDATE() - 10, GETDATE() - 10, GETDATE() - 10, GETDATE() - 10, GETDATE() - 10)
		--RETURN
	END
	 
    DECLARE @AddDate DATETIME, @InterviewDate DATETIME, @IntentionDate DATETIME,
		@ViewLogDate DATETIME, @AttentionDate DATETIME, @YourFoodDate DATETIME, 
		@ApplyReplyDate DATETIME, @ChangeCount INT, @CvViewLogCount INT,
		@YourFoodCount INT,@JobAppliedCount INT, @InterviewCount INT,
		@CpInvitationCount INT, @ChatCount INT
	 
	SELECT @AddDate = AddDate, @InterviewDate = ISNULL(InterviewDate, GETDATE() - 10),
		@IntentionDate = ISNULL(IntentionDate, GETDATE() - 10),
		@ViewLogDate = ISNULL(ViewLogDate, GETDATE() - 10),
		@AttentionDate = ISNULL(AttentionDate, GETDATE() - 10),
		@YourFoodDate = ISNULL(YourFoodDate, GETDATE() - 10),
		@ApplyReplyDate = ISNULL(ApplyReplyDate, GETDATE() - 10),
		@ChangeCount = ISNULL(MyAttentionCount, 0),
		@CvViewLogCount = ISNULL(CvViewLogCount, 0),
		@YourFoodCount = ISNULL(YourFoodCount, 0),
		@JobAppliedCount = ISNULL(JobAppliedCount, 0),
		@InterviewCount = ISNULL(InterviewCount, 0),
		@CpInvitationCount = ISNULL(CpInvitationCount, 0),
		@ChatCount = ISNULL(ChatCount, 0)
	FROM paPageViewLog WITH(NOLOCK)
	WHERE paMainId = @PaMainID
	
	SELECT ID 
	INTO #TCvIDs
	FROM cvMain WITH(NOLOCK) 
	WHERE paMainID = @PaMainID
    
	--更新时间超过1个小时的，重新计算提醒内容
	IF GETDATE() > DATEADD(MINUTE, 60, @AddDate)	--60分钟内的不重新生成	 
	BEGIN 
		--我的关注
		SELECT AttentionID, AttentionType
		INTO #TAttention
		FROM PaAttention WITH(NOLOCK)
		WHERE PaMainID = @PaMainID
		
		--职位有更新数量
		SELECT @ChangeCount = COUNT(1)
		FROM Job WITH(NOLOCK)
		WHERE CpMainID IN (SELECT AttentionID 
		FROM #TAttention WHERE AttentionType = 1)
		AND AddDate > @AttentionDate 
		
		SELECT @ChangeCount = COUNT(1) + @ChangeCount
		FROM Job WITH(NOLOCK)
		WHERE ID IN (SELECT AttentionID 
		FROM #TAttention WHERE AttentionType = 2)
		AND IssueEnd > @AttentionDate
		AND IssueEnd < GETDATE() 
			
		--新环境照片数量
		SELECT @ChangeCount = COUNT(1) + @ChangeCount
		FROM cpImage WITH(NOLOCK)
		WHERE cpMainID IN (SELECT AttentionID FROM #TAttention WHERE AttentionType = 1) 
		AND ImgType = 3 
		AND CheckDate > @AttentionDate 
		AND HasPassed = 1

		--删除临时表
		DROP TABLE #TAttention 
			
		
		--更新简历浏览量
		SELECT @CvViewLogCount = COUNT(1)
		FROM caCvViewLog WITH(NOLOCK)
		WHERE cvMainID IN(SELECT ID FROM #TCvIDs)
		AND AddDate > @ViewLogDate 
		
		--更新你的菜儿数量
		SELECT @YourFoodCount=COUNT(1)
		FROM PaJobCompare WITH(NOLOCK)
		WHERE PaMainID = @PaMainID
		AND AddDate > @YourFoodDate		 
		
		--申请的职位
		SELECT @JobAppliedCount=count(1)
		FROM exJobApply a WITH(NOLOCK) 
		WHERE a.cvMainID IN(
			SELECT ID FROM #TCvIDs
		)
		AND a.ReplyDate > @ApplyReplyDate 			
		 
		--面试通知
		SELECT @InterviewCount=COUNT(1)
		FROM exInterview a WITH(NOLOCK) 
		WHERE a.cvMainID IN(
			SELECT ID FROM #TCvIDs
		)
		AND a.AddDate > @InterviewDate	

		--应聘邀请
		SELECT @CpInvitationCount=COUNT(1)
		FROM caCvIntention a WITH(NOLOCK) 
		WHERE a.cvMainID IN(
			SELECT ID FROM #TCvIDs
		)
		AND a.AddDate > @IntentionDate 			

		--聊天记录
		SELECT @ChatCount=COUNT(1)
		FROM ChatOnlineLog a WITH(NOLOCK)
		LEFT JOIN ChatOnline b WITH(NOLOCK) ON a.ChatOnlineID = b.ID
		WHERE b.cvMainID IN(
			SELECT ID FROM #TCvIDs
		)
		AND a.IsViewed = 0
		AND a.SenderType = 1			

		--更新添加时间
		UPDATE paPageViewLog
		SET AddDate = GETDATE(),
		MyAttentionCount = @ChangeCount,
		CvViewLogCount = @CvViewLogCount,
		YourFoodCount = @YourFoodCount,
		JobAppliedCount =@JobAppliedCount,
		InterviewCount=@InterviewCount,
		CpInvitationCount=@CpInvitationCount,
		ChatCount = @ChatCount
		WHERE paMainId = @PaMainID  
	END
	SELECT * FROM paPageViewLog WHERE paMainId = @PaMainID --查询表内容 	
	
	IF @PageType = 2			--通知页面-页脚不查询其他表内容	  
	BEGIN						--通知页面 
		--申请的职位
		IF @JobAppliedCount > 0 
			SELECT TOP 1 a.Reply, a.ReplyDate, c.Name cpName
			FROM exJobApply a WITH(NOLOCK)
			LEFT JOIN Job b WITH(NOLOCK) ON b.ID = a.JobID
			LEFT JOIN CpMain c WITH(NOLOCK) ON c.ID = b.CpMainID
			WHERE a.cvMainID IN(
				SELECT ID FROM #TCvIDs
			)
			AND a.ReplyDate > @ApplyReplyDate
			ORDER BY a.ReplyDate DESC
		ELSE
			SELECT TOP 0 ''Reply,'' ReplyDate,'' cpName
		
		--面试通知
		IF @InterviewCount>0
			SELECT TOP 1 c.Name cpName, a.AddDate
			FROM exInterview a WITH(NOLOCK)
			LEFT JOIN Job b WITH(NOLOCK) ON b.ID = a.JobID
			LEFT JOIN CpMain c WITH(NOLOCK) ON c.ID = b.CpMainID
			WHERE a.cvMainID IN(
				SELECT ID FROM #TCvIDs
			)
			AND a.AddDate > @InterviewDate
			ORDER BY a.AddDate DESC
		ELSE
			SELECT TOP 0 '' cpName,'' AddDate
		
		--应聘邀请
		IF @CpInvitationCount > 0
			SELECT TOP 1 c.Name CpName, b.Name JobName, a.AddDate
			FROM caCvIntention a WITH(NOLOCK)
			LEFT JOIN Job b WITH(NOLOCK) ON b.ID = a.JobID
			LEFT JOIN CpMain c WITH(NOLOCK) ON c.ID = b.CpMainID
			WHERE a.cvMainID IN(
				SELECT ID FROM #TCvIDs
			)
			AND a.AddDate > @IntentionDate
			ORDER BY a.AddDate DESC
		ELSE
			SELECT TOP 0 '' CpName,'' JobName,'' AddDate
		
		--聊天记录
		IF @ChatCount > 0
			SELECT TOP 1 a.Message, a.AddDate, d.Name CpName
			FROM ChatOnlineLog a WITH(NOLOCK)
			LEFT JOIN ChatOnline b WITH(NOLOCK) ON a.ChatOnlineID = b.ID
			LEFT JOIN caMain c WITH(NOLOCK) ON c.ID = b.caMainID
			LEFT JOIN cpMain d WITH(NOLOCK) ON d.ID = c.cpMainID
			WHERE b.cvMainID IN(SELECT ID FROM #TCvIDs)
			AND a.IsViewed = 0
			AND a.SenderType = 1
			AND b.AddDate > GETDATE() - 7
			ORDER BY a.AddDate Desc
		ELSE
			SELECT TOP 0 '' [Message],'' AddDate,''CpName
		
		--谁在关注我
		IF @CvViewLogCount > 0
			SELECT TOP 1 c.Name CpName, a.AddDate
			FROM caCvViewLog a WITH(NOLOCK)
			INNER JOIN caMain b WITH(NOLOCK) ON a.caMainID = b.ID
			INNER JOIN cpMain c WITH(NOLOCK) ON b.cpMainID = c.ID
			WHERE a.cvMainID IN(SELECT ID FROM #TCvIDs)
			ORDER BY a.AddDate DESC
		ELSE
			SELECT TOP 0 '' AddDate,''CpName

		IF @ChangeCount > 0
		BEGIN
			SELECT AttentionID, AttentionType
			INTO #TAttention2
			FROM PaAttention WITH(NOLOCK)
			WHERE PaMainID = @PaMainID

			CREATE TABLE #TAttentionModify
			(
				ModifyDesc NVARCHAR(100),
				ModifyDate DATETIME
			)
			--企业新增职位了
			INSERT INTO #TAttentionModify(ModifyDesc,ModifyDate)
			SELECT TOP 1 '您关注的企业“' + b.Name + '”发布了新的职位' ModifyDesc,AddDate
			FROM Job a WITH(NOLOCK)
			LEFT JOIN CpMain b WITH(NOLOCK) ON b.ID = a.CpMainID
			WHERE CpMainID IN (SELECT AttentionID FROM #TAttention2 WHERE AttentionType = 1)
			ORDER BY AddDate DESC
			
			--职位截止
			INSERT INTO #TAttentionModify(ModifyDesc,ModifyDate)
			SELECT TOP 1 '您关注的职位“' + Name + '”已经过期' ModifyDesc,IssueEnd
			FROM Job WITH(NOLOCK)
			WHERE ID IN (SELECT AttentionID FROM #TAttention2 WHERE AttentionType = 2)
			AND IssueEnd < GETDATE()  
			ORDER BY IssueEnd DESC

			INSERT INTO #TAttentionModify(ModifyDesc,ModifyDate)
			SELECT TOP 1 '您关注的企业“' + b.Name + '”上传了新的环境照片' ModifyDesc,CheckDate
			FROM cpImage a WITH(NOLOCK)
			LEFT JOIN CpMain b WITH(NOLOCK) ON b.ID = a.CpMainID
			WHERE cpMainID IN (SELECT AttentionID FROM #TAttention2 WHERE AttentionType = 1)
			AND ImgType = 3 
			AND HasPassed = 1  
			ORDER BY CheckDate DESC

			SELECT TOP 1 * 
			FROM #TAttentionModify 
			ORDER BY ModifyDate DESC

			DROP TABLE #TAttention2
			DROP TABLE #TAttentionModify
		END	
		ELSE
		BEGIN
			SELECT TOP 0 '' ModifyDesc,'' ModifyDate
		END

		IF @YourFoodCount > 0
		BEGIN
			SELECT TOP 1 AddDate 
			FROM paYourfood WITH(NOLOCK) 
			WHERE PaMainID = @PaMainID
			ORDER BY AddDate DESC
		END
		ELSE
		BEGIN
			SELECT TOP 0 '' AddDate
		END
	END 

	DROP TABLE #TCvIDs 
END
GO
/****** Object:  StoredProcedure [dbo].[mblpaPhotoInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[mblpaPhotoInsert]
	@paMainID INT,
	@Photo VARCHAR(50)
AS
BEGIN TRAN
	BEGIN TRY
		DELETE FROM paPhoto WHERE paMainID=@paMainID
		UPDATE paMain SET HasPhoto=0 WHERE ID=@paMainID
		INSERT INTO paPhoto (paMainID,Photo,PhotoProcessed) VALUES(@paMainID,@Photo,@Photo)
		INSERT INTO paOperationLog (paMainID,Operation,Details,IP) 
			VALUES(@paMainID,40,'更新照片', '')

	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH
COMMIT TRAN
RETURN 1
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END














GO
/****** Object:  StoredProcedure [dbo].[mblPaPushLogSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--读取未推送的消息
--Lucifer 20160217
--修改Harry 2018-6-11 增加企业推送9,10,11,12,13
CREATE PROCEDURE [dbo].[mblPaPushLogSelect]
AS
BEGIN
	SELECT TOP 0 a.ID, a.PushMessage, a.PushType, a.DetailID, b.UniqueID, b.ClientType
	INTO #t
	FROM paPushLog a WITH(NOLOCK), paIOSBind b WITH(NOLOCK)
	WHERE a.paMainID = b.paMainID 
	AND a.PushDate IS NULL  
	AND a.AddDate > DATEADD(MINUTE, -20, GETDATE())
	
	--企业
	INSERT INTO #t
	SELECT TOP 130 a.ID, a.PushMessage, a.PushType, a.DetailID, b.UniqueID, b.ClientType
	FROM paPushLog a WITH(NOLOCK), caIOSBind b WITH(NOLOCK)
	WHERE a.paMainID = b.caMainID 
	AND a.PushDate IS NULL  
	AND a.AddDate > DATEADD(MINUTE, -20, GETDATE())
	AND PushType IN(9,10,11,12,13)
	ORDER BY a.Id DESC
	
	--个人
	INSERT INTO #t
	SELECT TOP 130 a.ID, a.PushMessage, a.PushType, a.DetailID, b.UniqueID, b.ClientType
	FROM paPushLog a WITH(NOLOCK), paIOSBind b WITH(NOLOCK)
	WHERE a.paMainID = b.paMainID 
	AND a.PushDate IS NULL 
	--AND a.paMainID IN(26537325, 12222868, 26502145, 26533836)
	AND a.AddDate > DATEADD(MINUTE, -20, GETDATE())
	AND PushType NOT IN(9,10,11,12,13)
	ORDER BY a.Id DESC
        SELECT * FROM #t
        drop table #t
END



GO
/****** Object:  StoredProcedure [dbo].[mblPaPushLogUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--将推送的加上推送时间
--Lucifer 20160217
CREATE PROCEDURE [dbo].[mblPaPushLogUpdate]
(
	@ID INT
)
AS
BEGIN TRY
	UPDATE paPushLog SET PushDate = GETDATE() WHERE ID = @ID
END TRY
BEGIN CATCH
END CATCH
GO
/****** Object:  StoredProcedure [dbo].[mblProjectErrorLogInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.7
--创建人：Nick
--说明：提交崩溃，错误日志信息
--#####################################################
CREATE PROCEDURE [dbo].[mblProjectErrorLogInsert]
(
	@ProjectType VARCHAR(20),
	@ErrorType VARCHAR(20),
	@AccountID VARCHAR(20),
	@ErrorLog VARCHAR(MAX),
	@Ip VARCHAR(20)
)
AS
BEGIN
	INSERT INTO ProjectErrorLog VALUES(@ProjectType,@ErrorType,@Ip,@AccountID,'','',@ErrorLog,GETDATE())
END


GO
/****** Object:  StoredProcedure [dbo].[mblProvinceSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.7
--创建人：Nick
--说明：获取省份
--#####################################################
CREATE PROCEDURE [dbo].[mblProvinceSelect]
AS
BEGIN
	SELECT * FROM dcProvince WITH(NOLOCK)
END


GO
/****** Object:  StoredProcedure [dbo].[mblQlrcNewsByIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.06
--创建人：Nick
--说明：获取新闻内容
--#####################################################
CREATE PROCEDURE [dbo].[mblQlrcNewsByIDSelect]
(
	@ID INT
)
AS
BEGIN TRY
	SELECT TOP 1 id,title,refreshdate,Appendix,AppendixName,Label tag,author,ViewNumber_All ViewNumber,
	REPLACE(REPLACE(REPLACE(Content,'</p><p style=\"text-indent:2em\">','<br> <br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'),'</p><p>','<br> <br>'),'<p style=\"text-indent:2em\">','&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;') Content 
	FROM QlrcNews WITH(NOLOCK) WHERE ID=@ID
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[mblQlrcNewsByProvinceIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.06
--创建人：Nick
--说明：最新热点7条
--#####################################################
CREATE PROCEDURE [dbo].[mblQlrcNewsByProvinceIDSelect]
(
	@ProvinceID INT
)
AS
BEGIN TRY
	SELECT TOP 7 * FROM qlrcnews 
	WHERE VersionId=@ProvinceID AND smallImg!='' 
	ORDER BY announcedate DESC
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[mblQlrcNewsMobileByIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.06
--创建人：Nick
--说明：获取新闻内容
--#####################################################
CREATE PROCEDURE [dbo].[mblQlrcNewsMobileByIDSelect]
(
	@ID INT
)
AS
BEGIN
	SELECT TOP 1 id, title, refreshdate, Appendix, AppendixName, author, ViewNumber_All ViewNumber, Label, Content, VersionId
	FROM QlrcNews WITH(NOLOCK) 
	WHERE ID = @ID
END
GO
/****** Object:  StoredProcedure [dbo].[mblRecruitmentByBeginTimeSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.7
--创建人：Nick
--说明：返回在指定该日期内举办招聘会的场馆，不重复
--#####################################################
CREATE PROCEDURE [dbo].[mblRecruitmentByBeginTimeSelect]
(
	@ProvinceID INT,
	@STime VARCHAR(500)
)
AS
BEGIN
	DECLARE @SQL VARCHAR(MAX)
	SET @SQL  = '
		SELECT DISTINCT TOP 500 b.id ,b.PlaceName 
		FROM [MarketDb]..[Recruitment] a, [MarketDb]..[RmPlace] b  
		WHERE a.RecruitmentPlaceId=b.id  AND a.IsPause=0 
		AND b.dcRegionID LIKE   '''+CONVERT(VARCHAR(6),@ProvinceID)+'%''
	' + @STime
	PRINT (@SQL)
	EXEC (@SQL)
END


GO
/****** Object:  StoredProcedure [dbo].[mblRecruitmentByProvinceIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.7
--创建人：John
--说明：企业客户端获取招聘会列表
--#####################################################
CREATE PROCEDURE [dbo].[mblRecruitmentByProvinceIDSelect]
(
	@ProvinceID VARCHAR(6)
)
AS
BEGIN
	SELECT TOP 100 a.ID,RecruitmentName,BeginDate,PlaceName 
	FROM Recruitment a WITH(NOLOCK),RecruitmentPlace b WITH(NOLOCK) 
	WHERE RecruitmentPlaceID = b.ID 
		AND CityID LIKE @ProvinceID + '%' 
		AND EndDate > GETDATE() 
		AND IsPause = 0 
		ORDER BY IsCompanyTop DESC, orderby, a.ID DESC
END


GO
/****** Object:  StoredProcedure [dbo].[mblRecruitmentList]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[mblRecruitmentList]
(
	@dcProvinceID AS SMALLINT, 
	@PageNum AS INT, 
	@PageSize AS INT
)
AS
BEGIN
	SELECT *
	FROM RecruitmentList
	WHERE ProvinceID = @dcProvinceID
	AND Rows BETWEEN (@PageNum - 1) * @PageSize + 1 
	AND @PageNum * @PageSize
	ORDER BY Rows
END














GO
/****** Object:  StoredProcedure [dbo].[mblRecruitmentList0715]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[mblRecruitmentList0715]
(
	@dcProvinceID AS SMALLINT, 
	@PageNum AS INT, 
	@PageSize AS INT
)
AS
BEGIN
	DECLARE @COUNT INT
	SELECT @COUNT = COUNT(*)
	FROM Recruitment a, dcRegion b, RecruitmentPlace c, RecruitmentDept d 
	WHERE d.ID = a.RecruitmentDeptID AND d.ID <> 1767 AND b.ID = c.dcRegionID AND a.RecruitmentPlaceId = c.id 
	AND LEFT(c.dcRegionID, 2) = @dcProvinceID AND EndDate>GETDATE() AND a.IsPause = 0 AND Len(ManagerUserID)>0 
 
	IF @COUNT > 200
		SET @COUNT  =  200

	SELECT *, @COUNT AS cnt
	FROM (SELECT TOP 200 ROW_NUMBER() OVER(ORDER BY OrderBy, a.EndDate) AS Rows, a.ID, a.RecruitmentName, a.EndDate, a.BeginDate, c.PlaceName, c.Address, b.Description City 
		FROM Recruitment a, dcRegion b, RecruitmentPlace c, RecruitmentDept d 
		WHERE d.ID = a.RecruitmentDeptID AND d.ID<>1767 AND b.ID = c.dcRegionID AND a.RecruitmentPlaceId = c.id 
		AND LEFT(c.dcRegionID, 2) = @dcProvinceID AND EndDate>GETDATE() AND a.IsPause = 0 AND LEN(ManagerUserID)>0
		) AS a 
	WHERE a.Rows BETWEEN (@PageNum - 1) * @PageSize + 1 AND @PageNum * @PageSize ORDER BY Rows
END














GO
/****** Object:  StoredProcedure [dbo].[mblRmInvitationCodeByCodeSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.7
--创建人：Nick
--说明：获取招聘会邀请码
--#####################################################
CREATE PROCEDURE [dbo].[mblRmInvitationCodeByCodeSelect]
(
	@Code VARCHAR(50)
)
AS
BEGIN
	SELECT * FROM MarketDB..RmInvitationCode WITH(NOLOCK)
	WHERE AddDate>DateAdd(Month,1,Getdate()) AND Code = @Code
END


GO
/****** Object:  StoredProcedure [dbo].[mblRmInvitationCodeByIDUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.7
--创建人：Nick
--说明：获取招聘会邀请码
--#####################################################
CREATE PROCEDURE [dbo].[mblRmInvitationCodeByIDUpdate]
(
	@ID INT,
	@Mobile VARCHAR(20)
)
AS
BEGIN
	UPDATE MarketDB..RmInvitationCode SET Mobile=@Mobile WHERE ID=@ID
END


GO
/****** Object:  StoredProcedure [dbo].[mblRmInvitationCodeByPaMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.06
--创建人：Nick
--说明：获取应聘邀请列表
--#####################################################
CREATE PROCEDURE [dbo].[mblRmInvitationCodeByPaMainIDSelect]
(
	@Mobile VARCHAR(20),
	@PamainID INT,
	@Type INT
)
AS
BEGIN TRY
	IF @Type = 1
	BEGIN
		SELECT TOP 1 ID,code 
		FROM MarketDB..RmInvitationCode WITH(NOLOCK) 
		WHERE AddDate>DateAdd(Month,-1,Getdate()) 
		AND (mobile=@Mobile OR paMainID=@PamainID) 
		ORDER BY ID DESC
	END
	ELSE 
	BEGIN
		SELECT TOP 1 ID,code 
		FROM MarketDB..RmInvitationCode WITH(NOLOCK) 
		WHERE AddDate>CONVERT(VARCHAR(10),Getdate(),120) 
		AND AddDate<dateAdd(n,-10,Getdate()) 
		AND (mobile=@Mobile OR paMainID=@PamainID) 
		ORDER BY ID DESC
	END
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[mblRmInvitationCodeInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.7
--创建人：Nick
--说明：插入招聘会邀请码
--#####################################################
CREATE PROCEDURE [dbo].[mblRmInvitationCodeInsert]
(
	@paMainID INT,
	@mobile VARCHAR(20),
	@code VARCHAR(20)
)
AS
BEGIN
	INSERT INTO MarketDB..RmInvitationCode(paMainID,Mobile,code) VALUES(@paMainID,@mobile,@code)
END


GO
/****** Object:  StoredProcedure [dbo].[mblSchoolNewsList]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--修改显示招聘简章显示全部（过期和非过期的）top 200  Harry 2015-7-15
CREATE PROCEDURE [dbo].[mblSchoolNewsList]
(
	@dcProvinceID AS SMALLINT,
	@PageNum AS INT,
	@PageSize AS INT
)
AS
BEGIN
	DECLARE @COUNT INT
	SELECT @COUNT = COUNT(1) 
	FROM marketdb..CampusBrochure a WITH(nolock),
		marketdb..CampusBrochureSite b WITH(nolock) 
	WHERE a.id = b.CampusBrochure and b.dcSubSiteID = @dcProvinceID  

	IF @COUNT > 200
		SET @COUNT = 200
 
	SELECT *,@COUNT AS cnt 
	FROM (SELECT TOP 200 ROW_NUMBER() OVER(ORDER BY EndDate DESC, CASE a.id WHEN 7866 THEN 1 WHEN 7865 THEN 1 WHEN 7870 THEN 1 ELSE 2 END ,a.OrderBy ,AddDate desc) AS Rows,
			a.id,a.Title,0 IsHot 
		FROM marketdb..CampusBrochure a WITH(NOLOCK),
			marketdb..CampusBrochureSite b WITH(nolock) 
		WHERE a.id = b.CampusBrochure AND b.dcSubSiteID = @dcProvinceID
		) AS a 
	WHERE a.Rows BETWEEN (@PageNum-1) * @PageSize + 1 AND @PageNum * @PageSize ORDER BY Rows
END
GO
/****** Object:  StoredProcedure [dbo].[mblSearchHistoryInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[mblSearchHistoryInsert]
(
	@paMainId INT,
	@Title VARCHAR(50),
	@dcRegionId int,
	@dcIndustryId int,
	@dcJobTypeId int
)
AS
BEGIN TRY
	INSERT INTO mblSearchHistory(paMainId, Title, dcRegionId, dcIndustryId, dcJobTypeId)
	VALUES(@paMainId, @Title, @dcRegionId, @dcIndustryId, @dcJobTypeId)
	RETURN 1
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON














GO
/****** Object:  StoredProcedure [dbo].[mblSearchHistorySelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[mblSearchHistorySelect]
(
	@paMainId int
)
AS
BEGIN
	SELECT TOP 30 * FROM mblSearchHistory WITH(NOLOCK) WHERE paMainId = @paMainId ORDER BY AddDate DESC
END














GO
/****** Object:  StoredProcedure [dbo].[mblSearchKeywordByKeyWordSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.06
--创建人：Nick
--说明：获取关键词
--#####################################################
CREATE PROCEDURE [dbo].[mblSearchKeywordByKeyWordSelect]
(
	@key VARCHAR(200)
)
AS
BEGIN TRY
	SELECT TOP 10 KeyType,KeyWord,KeyWordPinYin,SearchResult,SearchType 
	FROM searchdb..SearchKeyword WITH(NOLOCK) 
	WHERE (KeyWord LIKE @key+'%' OR KeyWordPinYin LIKE @key+'%') 
	ORDER BY SearchNumber DESC
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[mblSpreadRefererLogSessionUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.7
--创建人：John
--说明：更新sessionid，因为是主站跳转到m站的
--#####################################################
CREATE PROCEDURE [dbo].[mblSpreadRefererLogSessionUpdate]
(
	@Id INT,
	@sessionId VARCHAR(30)
)
AS
BEGIN
	UPDATE SpreadRefererLog SET VisitType = 2, SessionId = @sessionId 
	WHERE VisitType = 1 AND RefererDate > DATEADD(MINUTE, -12, GETDATE()) AND SpreadLoginLogid = @Id
END


GO
/****** Object:  StoredProcedure [dbo].[mblWeixinSave]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[mblWeixinSave]
(
	@Content NVARCHAR(300),
	@Lat VARCHAR(20),
	@Lng VARCHAR(20),
	@FromUserName VARCHAR(50)
)
AS
BEGIN TRY
	SET @Content = dbo.SafeSql(@Content)
	DELETE FROM wxMessage WHERE FromUserName=@FromUserName
	IF ISNULL(@Content,'')=''
	BEGIN
		INSERT INTO wxMessage(FromUserName,Lat,Lng,Content) VALUES
			(@FromUserName,@Lat,@Lng,@Content)
	END
	ELSE
	BEGIN
		DECLARE @dcRegionID INT, @KeyWord NVARCHAR(20), @c NVARCHAR(50)
		IF @Content LIKE '% %'
			SET @c = LEFT(@Content, CHARINDEX(' ', @Content) - 1)
		ELSE
			SET @c = @Content
		SELECT TOP 1 @dcRegionID = ID FROM dcRegion WITH(NOLOCK)
		WHERE CHARINDEX(Abbr, @c)>0 
		ORDER BY ID DESC
		IF ISNULL(@dcRegionID,0)=0
			RETURN 0

		SELECT @KeyWord=REPLACE(REPLACE(@Content,MapbarName,''),REPLACE(MapbarName,'市',''),'') FROM dcRegion WITH(NOLOCK) WHERE ID=@dcRegionID
		SELECT @KeyWord=REPLACE(REPLACE(REPLACE(@KeyWord,Description,''),REPLACE(Description,'市',''),''),REPLACE(Description,'区',''),'') FROM dcRegion WITH(NOLOCK) WHERE ID=@dcRegionID
		SELECT @KeyWord=REPLACE(REPLACE(@KeyWord,LEFT(FullName,CHARINDEX('省',FullName)),''),REPLACE(LEFT(FullName,CHARINDEX('省',FullName)),'省',''),'') FROM dcRegion WITH(NOLOCK) WHERE ID=@dcRegionID
		SELECT @KeyWord=REPLACE(@KeyWord,' ','')
		SELECT @KeyWord=REPLACE(@KeyWord,'+','')

		INSERT INTO wxMessage(FromUserName,dcRegionID,KeyWord,Content) VALUES
			(@FromUserName,@dcRegionID,@KeyWord,@Content)
	END
	RETURN 1
END TRY
BEGIN CATCH
	RETURN 0
END CATCH














GO
/****** Object:  StoredProcedure [dbo].[mblWeixinServiceSave]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[mblWeixinServiceSave]
(
	@Content NVARCHAR(50),
	@Lat VARCHAR(20),
	@Lng VARCHAR(20),
	@FromUserName VARCHAR(50),
	@ProvinceID int
)
AS
BEGIN TRY
	IF(@Content<>'推荐职位')
	BEGIN
		DELETE FROM wxMessage WHERE FromUserName=@FromUserName AND CONTENT <>'推荐职位'
	END
	ELSE
	BEGIN
		DELETE FROM wxMessage WHERE FromUserName=@FromUserName		
	END
	IF ISNULL(@Content,'')='' OR @Content='推荐职位'
	BEGIN
		INSERT INTO wxMessage(FromUserName,Lat,Lng,Content) VALUES
			(@FromUserName,@Lat,@Lng,@Content)
	END
	ELSE
	BEGIN
		DECLARE @dcRegionID INT,@KeyWord NVARCHAR(20)
		SELECT TOP 1 @dcRegionID=ID FROM dcRegion WITH(NOLOCK) WHERE
			CHARINDEX(Description,@Content)>0 OR
			CHARINDEX(REPLACE(Description,'市',''),@Content)>0 OR
			CHARINDEX(REPLACE(Description,'省',''),@Content)>0
		ORDER BY ID DESC
		IF ISNULL(@dcRegionID,0)=0
			SELECT @dcRegionID = @ProvinceID

		SELECT @KeyWord=REPLACE(REPLACE(@Content,MapbarName,''),REPLACE(MapbarName,'市',''),'') FROM dcRegion WITH(NOLOCK) WHERE ID=@dcRegionID
		SELECT @KeyWord=REPLACE(REPLACE(REPLACE(@KeyWord,Description,''),REPLACE(Description,'市',''),''),REPLACE(Description,'区',''),'') FROM dcRegion WITH(NOLOCK) WHERE ID=@dcRegionID
		SELECT @KeyWord=REPLACE(REPLACE(@KeyWord,LEFT(FullName,CHARINDEX('省',FullName)),''),REPLACE(LEFT(FullName,CHARINDEX('省',FullName)),'省',''),'') FROM dcRegion WITH(NOLOCK) WHERE ID=@dcRegionID
		SELECT @KeyWord=REPLACE(@KeyWord,' ','')
		SELECT @KeyWord=REPLACE(@KeyWord,'+','')

		INSERT INTO wxMessage(FromUserName,dcRegionID,KeyWord,Content) VALUES
			(@FromUserName,@dcRegionID,@KeyWord,@Content)
	END
	RETURN 1
END TRY
BEGIN CATCH
	RETURN 0
END CATCH








GO
/****** Object:  StoredProcedure [dbo].[mblWxMessageSendSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



--#####################################################
--创建时间：2015.2.26
--创建人：Nick
--说明：获取提醒信息
--#####################################################
CREATE PROCEDURE  [dbo].[mblWxMessageSendSelect]
AS
BEGIN
SET NOCOUNT ON
	SELECT senddate,a.ID,c.ID PaMainID,a.Message ContentText,b.OpenID,c.Name,e.ProvinceId,d.Token,e.AppID, e.AppSecret,f.No AS TemplateNo
	FROM WxMessageSend a WITH(NOLOCK),WxFans b WITH(NOLOCK),PaMain c WITH(NOLOCK),dcWxtoken d WITH(NOLOCK), wxServiceNo e,WxTemplateno f
	WHERE a.SendDate IS NULL
	AND a.WxFansID = b.id	
	AND b.Status = 2
	AND b.PaMainID = c.ID
	AND c.IsWeiXinNotice = 1
	AND b.wxServiceNoId = e.ID
	AND e.ProvinceId = d.dcProvinceId
	AND a.WxTemplatenoID = f.ID
	ORDER BY a.ID DESC
SET NOCOUNT OFF	
END

GO
/****** Object:  StoredProcedure [dbo].[mblWXQrImageByIDUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.7
--创建人：Nick
--说明：根据ＩＤ修改WXQrImage
--#####################################################
CREATE PROCEDURE [dbo].[mblWXQrImageByIDUpdate]
(
	@ID INT,
	@Status INT,
	@OpenID VARCHAR(50)
)
AS
BEGIN
	UPDATE WXQrImage 
	SET Status = @Status, paMainID=(
		SELECT TOP 1 paMainID 
		FROM palogincontact WITH(NOLOCK) 
		WHERE ContactType=4 
		AND  Openid=@OpenID 
		ORDER BY id DESC
	) WHERE ID=@ID
END
GO
/****** Object:  StoredProcedure [dbo].[mblWXQrImageByIDUpdateNew]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2016.4.7
--创建人：Lucifer
--说明：根据ＩＤ修改WXQrImage
--#####################################################
CREATE PROCEDURE [dbo].[mblWXQrImageByIDUpdateNew]
(
	@ID INT,
	@Status INT,
	@OpenID VARCHAR(50),
	@ContactType INT
)
AS
BEGIN
	UPDATE WXQrImage 
	SET Status = @Status, 
		paMainID = (
		SELECT TOP 1 paMainID 
		FROM paLoginContact WITH(NOLOCK) 
		WHERE ContactType = @ContactType 
		AND Openid = @OpenID 
		ORDER BY id DESC)
	WHERE ID = @ID
END
GO
/****** Object:  StoredProcedure [dbo].[mblWXQRIMAGEByOpenIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.7
--创建人：Nick
--说明：根据ＩＤ查询WXQRIMAGE
--#####################################################
CREATE PROCEDURE [dbo].[mblWXQRIMAGEByOpenIDSelect]
(
	@OpenID VARCHAR(50)
)
AS
INSERT INTO ProcLog SELECT 'mblWXQRIMAGEByOpenIDSelect', '', GETDATE()
BEGIN
	SELECT TOP 1 *  
	FROM WXQRIMAGE 
	WHERE openid=@OpenID 
	AND pamainid IS NULL
	ORDER BY id DESC
END


GO
/****** Object:  StoredProcedure [dbo].[mblWXQrImageStatusUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.7
--创建人：Nick
--说明：修改 WXQrImage 状态
--#####################################################
CREATE PROCEDURE [dbo].[mblWXQrImageStatusUpdate]
(
	@ID INT,
	@Status INT,
	@OpenID VARCHAR(50)
)
AS
INSERT INTO ProcLog SELECT 'mblWXQrImageStatusUpdate', @OpenID, GETDATE()
BEGIN
	UPDATE WXQrImage 
	SET status=@Status 
	WHERE ID=@ID 
	AND paMainID=(
		SELECT TOP 1 paMainID 
		FROM palogincontact WITH(NOLOCK) 
		WHERE ContactType=4 
		AND Openid=@OpenID
	)
END


GO
/****** Object:  StoredProcedure [dbo].[p_killspid]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE procedure [dbo].[p_killspid] 
(
	@dbname varchar(200)    --要关闭进程的数据库名 
)
as  
begin
    declare @sql  nvarchar(500)  
    declare @spid nvarchar(20)
    declare #tb cursor for 
        select spid=cast(spid as varchar(20)) from master..sysprocesses where dbid=db_id(@dbname) 
    open #tb 
    fetch next from #tb into @spid 
    while @@fetch_status=0 
    begin  
        print 'exec(kill ' + @spid + ') '
		exec('kill '+@spid) 
        fetch next from #tb into @spid 
    end  
    close #tb 
    deallocate #tb
end

GO
/****** Object:  StoredProcedure [dbo].[paCvTagsByCvMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--个人标签查询  Peter 2017-1-13
CREATE PROCEDURE [dbo].[paCvTagsByCvMainIDSelect] 
(	
	@paMainID INT,
	@cvMainID INT
)
AS
BEGIN	
	SELECT * 
	FROM CvTags WITH(NOLOCK)
	WHERE cvMainID = @cvMainID
	AND EXISTS(
		SELECT 'x' 
		FROM cvMain 
		WHERE paMainID = @paMainID 
		AND id = @cvMainID)
END
GO
/****** Object:  StoredProcedure [dbo].[paCvTagsSave]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--个人标签保存  Peter 2017-1-13
CREATE PROCEDURE [dbo].[paCvTagsSave] 
(	
	@paMainID INT,
	@cvMainID INT,
	@Tags NVARCHAR(1000)
)
AS
BEGIN		
	IF NOT EXISTS(SELECT 'x' FROM cvMain WHERE paMainID = @paMainID AND id = @cvMainID)
	BEGIN
		RETURN -1
	END
	
	DECLARE @TagsCount INT
	
	SELECT @TagsCount = COUNT(1)
	FROM dbo.fnSplit(@Tags,'@')
	
	IF @TagsCount > 10
	BEGIN
		RETURN 0
	END
	
	DELETE FROM cvTags WHERE cvMainID = @cvMainID
	
	CREATE TABLE #T(
		cvMainID INT,
		Tag NVARCHAR(20),
		VerifyDate SMALLDATETIME
	)
	
	INSERT INTO #T(cvMainID,Tag)
	SELECT @cvMainID cvMainID,a Tag
	FROM dbo.fnSplit(@Tags,'@')
	
	UPDATE #T 
	SET VerifyDate = GETDATE()
	WHERE EXISTS(SELECT 'x' FROM paTagsMain WHERE Tag = #T.Tag)
	
	INSERT INTO cvTags(cvMainID,Tags,VerifyDate)
	SELECT * 
	FROM #T
	
	DROP TABLE #T
	
	RETURN 1
END
GO
/****** Object:  StoredProcedure [dbo].[paJobByWeixinSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[paJobByWeixinSelect] 
(
	@FromUserName VARCHAR(50)
)
AS
--return
SET NOCOUNT ON
BEGIN TRY
	SET @FromUserName = dbo.SafeSql(@FromUserName)
		
	DECLARE @dcRegionID INT,@KeyWord NVARCHAR(20),
	@Lng DECIMAL(8,5),@Lat DECIMAL(8,5),@Distance INT,
	@KeyType TINYINT, @ValidJobNumber INT, @PageNumber SMALLINT

	SELECT @dcRegionID=dcRegionID,@KeyWord=KeyWord,
		@Lng=Lng,@Lat=Lat,@PageNumber=PageNumber
		FROM wxMessage WITH(NOLOCK) WHERE FromUserName=@FromUserName

	UPDATE wxMessage SET PageNumber=PageNumber+1 WHERE FromUserName=@FromUserName
	SELECT @KeyWord = dbo.SafeSQL(ISNULL(@KeyWord, '')),
		@KeyType = 2,
		@Distance = 5000,
		@PageNumber = ISNULL(@PageNumber, 1),
		@dcRegionID = ISNULL(@dcRegionID, 0),
		@Lng = ISNULL(@Lng, 0),
		@Lat = ISNULL(@Lat, 0)

	IF @dcRegionID = 0 AND @Lng = 0 AND @Lat = 0
		RETURN

	DECLARE @paSearchConditionID AS INT, 
		@MinId AS INT, 
		@PageSize AS TINYINT, 
		@TableID AS TINYINT

	SELECT @paSearchConditionID = 0, @PageSize = 8  --每页的行数
	
	----搜索60分钟前的数据
	SELECT TOP 1 @paSearchConditionID=ID FROM SearchDB..paSearchCondition WITH(NOLOCK)
	WHERE JobType=''
	AND JobPlace=@dcRegionID AND ISNULL(Industry,'')='' AND ISNULL(Education,'')=''
	AND ISNULL(Experience,'')='' AND ISNULL(Salary,'')='' AND ISNULL(IsNegotiable,'')='' 
	AND ISNULL(EmployType,'')='' AND KeyWord=@KeyWord AND KeyType=@KeyType
	AND ISNULL(CompanySizeID,'')='' AND Lng=@Lng AND Lat=@Lat
	ORDER BY ID DESC

	IF ISNULL(@paSearchConditionID, 0) = 0
	BEGIN
		GOTO SelectReset	--无数据，重新搜索
	END
	ELSE
	BEGIN
		SELECT @TableID = @paSearchConditionID % 4
		GOTO GetRecordSet	--从临时结果中提取数据
	END

	SelectReset:
	--从job中搜索数据
	BEGIN TRAN
		DECLARE @SQL AS VARCHAR(8000)
		DECLARE @WHERE AS VARCHAR(8000)
		DECLARE @FROM AS VARCHAR(1000)
		----记录查询条件
		INSERT INTO SearchDB..paSearchCondition(SessionID, LogTime, JobType, JobPlace, Industry, Education, Experience, 
			Salary, IsNegotiable, EmployType, CompanySizeID, KeyWord, KeyType, ReuseNumber, Lng, Lat, Distance)
		VALUES(1, GETDATE(), '', @dcRegionID, '', '', '', '', '', '', '', @KeyWord, @KeyType, 0, @Lng, @Lat, @Distance)
		SET @paSearchConditionID = @@IDENTITY
		SELECT @TableID = @paSearchConditionID % 4

		----建立临时表
		CREATE TABLE #Job(
			RowID INT IDENTITY(1, 1), 
			ID INT NOT NULL, 
			dcJobTypeID SMALLINT NOT NULL, 
			dcJobTypeIDMinor SMALLINT NULL, 
			dcSalaryID TINYINT NOT NULL, 
			dcRegionID VARCHAR(6) NULL, 
			dcEducationID TINYINT NOT NULL, 
			MinExperience TINYINT NOT NULL, 
			RefreshDate SMALLDATETIME NULL
		)
		------刷新时间，根据刷新时间编号计算
		----生成插入临时表的Sql语句
		SET @SQL='
			INSERT INTO #Job
			SELECT a.ID, a.dcJobTypeID, 
				a.dcJobTypeIDMinor, a.dcSalaryID, 
				a.dcRegionID, a.dcEducationID, a.MinExperience, 
				a.IssueDate'
		SET @FROM = '
			FROM JobPublish a WITH(NOLOCK)
			INNER JOIN cpMainPublish b WITH(NOLOCK) ON a.cpMainID=b.ID'
		----职位有效，单位新有效
		SET @WHERE = '
			WHERE a.Valid = 1
			AND b.Valid = 1'
		----需要增加全文索引的关键字查询
		IF @KeyWord LIKE '% %'
		BEGIN
			SET @KeyWord = REPLACE(@KeyWord, '  ', ' ')
			SET @KeyWord = REPLACE(@KeyWord, '  ', ' ')
			SET @KeyWord = REPLACE(@KeyWord, '  ', ' ')
			SET @KeyWord = '"' + REPLACE(@KeyWord, ' ', '" OR "') + '"'
		END

		IF LEN(@KeyWord) > 0
		BEGIN
			IF @KeyType = 2
				SET @FROM = @FROM + '
			INNER JOIN CONTAINSTABLE(JobPublish, *, ''' + @KeyWord + ''', 1000000) AS KeyJob
			ON a.ID = KeyJob.[Key]'
		END
		---地区
		IF @dcRegionID > 0 
			SET @WHERE = @WHERE + '
			AND a.dcRegionID Like ''' + CONVERT(VARCHAR(6),@dcRegionID) + '%'''

		IF @Lng > 0 AND @Lat > 0
		BEGIN
			DECLARE @Degree AS DECIMAL(8,5),@LBLng AS DECIMAL(8,5),@LBLat AS DECIMAL(8,5),
			@RTLng AS DECIMAL(8,5),@RTLat AS DECIMAL(8,5)
			SET @Degree = @Distance / 100000.0;

			SET @LBLng = @Lng - @Degree
			SET @LBLat = @Lat - @Degree
			SET @RTLng = @Lng + @Degree
			SET @RTLat = @Lat + @Degree
			SET @WHERE = @WHERE + '
				AND a.Lng BETWEEN ' + CONVERT(VARCHAR,@LBLng) + ' AND ' + CONVERT(VARCHAR,@RTLng) + '
				AND a.Lat BETWEEN ' + CONVERT(VARCHAR,@LBLat) + ' AND ' + CONVERT(VARCHAR,@RTLat)
		END
		SET @SQL = @SQL + @FROM + @WHERE
		
		SET @SQL=@SQL + ' ORDER BY a.RefreshDate DESC, a.ID'

		----把符合条件的职位全部列出
		--PRINT @SQL
		EXEC(@SQL)
		
		SET @ValidJobNumber = @@ROWCOUNT
		----记录查询结果总数
		UPDATE SearchDB..paSearchCondition SET ValidJobNumber=@ValidJobNumber, SQl=@SQL WHERE ID=@paSearchConditionID
		
		----插入JobType数据
		DECLARE @TitleValue AS INT, @TopRows AS INT, @AllRows AS INT
		IF (@TableID = 0)
		BEGIN
			INSERT INTO SearchDB..paSearchCount_0(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'JobType', dcJobTypeID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcJobTypeID ORDER BY dcJobTypeID
			----计算全部某职位类别，2, 4位的数据
			UPDATE a SET a.TitleValue = b.TitleValue
			FROM SearchDB..paSearchCount_0 a WITH(NOLOCK), 
				(SELECT LEFT(TitleID, 2) TitleID, SUM(TitleValue) TitleValue
				FROM SearchDB..paSearchCount_0 WITH(NOLOCK)
				WHERE paSearchConditionID = @paSearchConditionID AND Title = 'JobType'
				GROUP BY LEFT(TitleID, 2)) b
			WHERE a.TitleId = b.TitleID
			AND a.paSearchConditionID = @paSearchConditionID AND a.Title = 'JobType'
			----写入TitleDesc
			UPDATE a SET a.TitleDesc = b.Description
			FROM SearchDB..paSearchCount_0 a WITH(NOLOCK), dcJobType b WITH(NOLOCK)
			WHERE a.TitleID = b.ID AND a.paSearchConditionID = @paSearchConditionID
			AND a.Title = 'JobType'
			
			INSERT INTO SearchDB..paSearchCount_0(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Salary', dcSalaryID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcSalaryID ORDER BY dcSalaryID

			INSERT INTO SearchDB..paSearchCount_0(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Region', dcRegionID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcRegionID ORDER BY dcRegionID
			----计算全部地区，2位的数据
			UPDATE a SET a.TitleValue = b.TitleValue
			FROM SearchDB..paSearchCount_0 a WITH(NOLOCK), 
			(SELECT LEFT(TitleID, 2) TitleID, SUM(TitleValue) TitleValue
			FROM SearchDB..paSearchCount_0 WITH(NOLOCK)
			WHERE paSearchConditionID = @paSearchConditionID AND Title = 'Region'
			GROUP BY LEFT(TitleID, 2)) b
			WHERE a.TitleId = b.TitleID
			AND a.paSearchConditionID = @paSearchConditionID AND a.Title = 'Region'
			----计算全部地区，4位的数据
			UPDATE a SET a.TitleValue = b.TitleValue
			FROM SearchDB..paSearchCount_0 a WITH(NOLOCK), (
				SELECT LEFT(TitleID, 4) TitleID, SUM(TitleValue) TitleValue
				FROM SearchDB..paSearchCount_0 WITH(NOLOCK)
				WHERE paSearchConditionID = @paSearchConditionID AND Title = 'Region'
				AND LEN(TitleID) >3
				GROUP BY LEFT(TitleID, 4)) b
			WHERE a.TitleId = b.TitleID
			AND a.paSearchConditionID = @paSearchConditionID AND a.Title = 'Region'
			----写入TitleDesc
			UPDATE a SET a.TitleDesc = b.Description
			FROM SearchDB..paSearchCount_0 a WITH(NOLOCK), dcRegion b WITH(NOLOCK)
			WHERE a.TitleID = b.ID AND a.paSearchConditionID = @paSearchConditionID
			AND a.Title = 'Region'

			INSERT INTO SearchDB..paSearchCount_0(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Education', dcEducationID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcEducationID ORDER BY dcEducationID
			--学历 高中、中专、中级合并		
			SELECT @TitleValue = SUM(TitleValue) FROM SearchDB..paSearchCount_0 WITH(NOLOCK)
			WHERE paSearchConditionID = @paSearchConditionID
			AND Title = 'Education' AND TitleID IN(2, 3, 4)		
			IF @TitleValue IS NOT NULL
			BEGIN
				IF EXISTS(SELECT 'X' FROM SearchDB..paSearchCount_0 WITH(NOLOCK) WHERE paSearchConditionID = @paSearchConditionID AND Title = 'Education' AND TitleID = 2)
					UPDATE SearchDB..paSearchCount_0 SET TitleValue = @TitleValue 
					WHERE paSearchConditionID = @paSearchConditionID
					AND Title = 'Education' AND TitleID = 2
				ELSE
					INSERT INTO SearchDB..paSearchCount_0(paSearchConditionID, Title, TitleId, TitleValue) VALUES
					(@paSearchConditionID, 'Education', 2, @TitleValue)

				DELETE FROM SearchDB..paSearchCount_0
				WHERE paSearchConditionID = @paSearchConditionID
				AND Title = 'Education' AND TitleID IN(3, 4)
			END 

			INSERT INTO SearchDB..paSearchCount_0(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Experience', MinExperience, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY MinExperience ORDER BY MinExperience
			
			INSERT INTO SearchDB..paSearchJobID_0(paSearchConditionID, JobId, IsTop)
			SELECT Top 3 @paSearchConditionID,Balance,1 
			FROM caOrder WITH(NOLOCK), (SELECT TOP 2000 ID FROM #Job WITH(NOLOCK)) b 
			WHERE caOrder.OrderType = 12 AND BeginDate<GETDATE() AND EndDate>GETDATE() AND b.ID = caOrder.Balance ORDER BY OpenDate DESC
			SET @TopRows = @@ROWCOUNT

			INSERT INTO SearchDB..paSearchJobID_0(paSearchConditionID, JobId, IsTop)
			SELECT TOP 2000 @paSearchConditionID, ID, 0 FROM #Job WITH(NOLOCK)
			SET @AllRows = @@ROWCOUNT

			IF @TopRows = 0 AND @AllRows > 100
				UPDATE SearchDB..paSearchJobID_0 SET IsTop = 1 
				WHERE paSearchConditionID = @paSearchConditionID
				AND ID IN (SELECT TOP 3 ID FROM SearchDB..paSearchJobID_0 WITH(NOLOCK) WHERE paSearchConditionID = @paSearchConditionID)
		END
		ELSE IF (@TableId = 1)
		BEGIN
			INSERT INTO SearchDB..paSearchCount_1(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'JobType', dcJobTypeID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcJobTypeID ORDER BY dcJobTypeID
			----计算全部某职位类别，2, 4位的数据
			UPDATE a SET a.TitleValue = b.TitleValue
			FROM SearchDB..paSearchCount_1 a WITH(NOLOCK), 
			(SELECT LEFT(TitleID, 2) TitleID, SUM(TitleValue) TitleValue
			FROM SearchDB..paSearchCount_1 WITH(NOLOCK)
			WHERE paSearchConditionID = @paSearchConditionID AND Title = 'JobType'
			GROUP BY LEFT(TitleID, 2)) b
			WHERE a.TitleId = b.TitleID
			AND a.paSearchConditionID = @paSearchConditionID AND a.Title = 'JobType'
			----写入TitleDesc
			UPDATE a SET a.TitleDesc = b.Description
			FROM SearchDB..paSearchCount_1 a WITH(NOLOCK), dcJobType b WITH(NOLOCK)
			WHERE a.TitleID = b.ID AND a.paSearchConditionID = @paSearchConditionID
			AND a.Title = 'JobType'
			
			INSERT INTO SearchDB..paSearchCount_1(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Salary', dcSalaryID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcSalaryID ORDER BY dcSalaryID

			INSERT INTO SearchDB..paSearchCount_1(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Region', dcRegionID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcRegionID ORDER BY dcRegionID
			----计算全部地区，2位的数据
			UPDATE a SET a.TitleValue = b.TitleValue
			FROM SearchDB..paSearchCount_1 a WITH(NOLOCK), 
			(SELECT LEFT(TitleID, 2) TitleID, SUM(TitleValue) TitleValue
			FROM SearchDB..paSearchCount_1 WITH(NOLOCK)
			WHERE paSearchConditionID = @paSearchConditionID AND Title = 'Region'
			GROUP BY LEFT(TitleID, 2)) b
			WHERE a.TitleId = b.TitleID
			AND a.paSearchConditionID = @paSearchConditionID AND a.Title = 'Region'
			----计算全部地区，4位的数据
			UPDATE a SET a.TitleValue = b.TitleValue
			FROM SearchDB..paSearchCount_1 a WITH(NOLOCK), (
				SELECT LEFT(TitleID, 4) TitleID, SUM(TitleValue) TitleValue
				FROM SearchDB..paSearchCount_1 WITH(NOLOCK)
				WHERE paSearchConditionID = @paSearchConditionID AND Title = 'Region'
				AND LEN(TitleID) >3
				GROUP BY LEFT(TitleID, 4)) b
			WHERE a.TitleId = b.TitleID
			AND a.paSearchConditionID = @paSearchConditionID AND a.Title = 'Region'
			----写入TitleDesc
			UPDATE a SET a.TitleDesc = b.Description
			FROM SearchDB..paSearchCount_1 a WITH(NOLOCK), dcRegion b WITH(NOLOCK)
			WHERE a.TitleID = b.ID AND a.paSearchConditionID = @paSearchConditionID
			AND a.Title = 'Region'

			INSERT INTO SearchDB..paSearchCount_1(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Education', dcEducationID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcEducationID ORDER BY dcEducationID
			--学历 高中、中专、中级合并		
			SELECT @TitleValue = SUM(TitleValue) FROM SearchDB..paSearchCount_1 WITH(NOLOCK)
			WHERE paSearchConditionID = @paSearchConditionID
			AND Title = 'Education' AND TitleID IN(2, 3, 4)		
			IF @TitleValue IS NOT NULL
			BEGIN
				IF EXISTS(SELECT 'X' FROM SearchDB..paSearchCount_1 WITH(NOLOCK) WHERE paSearchConditionID = @paSearchConditionID AND Title = 'Education' AND TitleID = 2)
					UPDATE SearchDB..paSearchCount_1 SET TitleValue = @TitleValue 
					WHERE paSearchConditionID = @paSearchConditionID
					AND Title = 'Education' AND TitleID = 2
				ELSE
					INSERT INTO SearchDB..paSearchCount_1(paSearchConditionID, Title, TitleId, TitleValue) VALUES
					(@paSearchConditionID, 'Education', 2, @TitleValue)

				DELETE FROM SearchDB..paSearchCount_1
				WHERE paSearchConditionID = @paSearchConditionID
				AND Title = 'Education' AND TitleID IN(3, 4)
			END 

			INSERT INTO SearchDB..paSearchCount_1(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Experience', MinExperience, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY MinExperience ORDER BY MinExperience
	
			INSERT INTO SearchDB..paSearchJobID_1(paSearchConditionID, JobId, IsTop)
			SELECT Top 3 @paSearchConditionID,Balance,1
			FROM caOrder WITH(NOLOCK), (SELECT TOP 2000 ID FROM #Job WITH(NOLOCK)) b
			WHERE caOrder.OrderType = 12 AND BeginDate<GETDATE() AND EndDate>GETDATE() AND b.ID = caOrder.Balance ORDER BY OpenDate DESC
			SET @TopRows = @@ROWCOUNT

			INSERT INTO SearchDB..paSearchJobID_1(paSearchConditionID, JobId, IsTop)
			SELECT TOP 2000 @paSearchConditionID, ID, 0 FROM #Job WITH(NOLOCK)
			SET @AllRows = @@ROWCOUNT

			IF @TopRows = 0 AND @AllRows > 100
				UPDATE SearchDB..paSearchJobID_1 SET IsTop = 1 
				WHERE paSearchConditionID = @paSearchConditionID
				AND ID IN (SELECT TOP 3 ID FROM SearchDB..paSearchJobID_1 WITH(NOLOCK) WHERE paSearchConditionID = @paSearchConditionID)
		END
		ELSE IF (@TableId = 2)
		BEGIN
			INSERT INTO SearchDB..paSearchCount_2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'JobType', dcJobTypeID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcJobTypeID ORDER BY dcJobTypeID
			----计算全部某职位类别，2, 4位的数据
			UPDATE a SET a.TitleValue = b.TitleValue
			FROM SearchDB..paSearchCount_2 a WITH(NOLOCK), 
			(SELECT LEFT(TitleID, 2) TitleID, SUM(TitleValue) TitleValue
			FROM SearchDB..paSearchCount_2 WITH(NOLOCK)
			WHERE paSearchConditionID = @paSearchConditionID AND Title = 'JobType'
			GROUP BY LEFT(TitleID, 2)) b
			WHERE a.TitleId = b.TitleID
			AND a.paSearchConditionID = @paSearchConditionID AND a.Title = 'JobType'
			----写入TitleDesc
			UPDATE a SET a.TitleDesc = b.Description
			FROM SearchDB..paSearchCount_2 a WITH(NOLOCK), dcJobType b WITH(NOLOCK)
			WHERE a.TitleID = b.ID AND a.paSearchConditionID = @paSearchConditionID
			AND a.Title = 'JobType'
			
			INSERT INTO SearchDB..paSearchCount_2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Salary', dcSalaryID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcSalaryID ORDER BY dcSalaryID

			INSERT INTO SearchDB..paSearchCount_2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Region', dcRegionID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcRegionID ORDER BY dcRegionID
			----计算全部地区，2位的数据
			UPDATE a SET a.TitleValue = b.TitleValue
			FROM SearchDB..paSearchCount_2 a WITH(NOLOCK), 
			(SELECT LEFT(TitleID, 2) TitleID, SUM(TitleValue) TitleValue
			FROM SearchDB..paSearchCount_2 WITH(NOLOCK)
			WHERE paSearchConditionID = @paSearchConditionID AND Title = 'Region'
			GROUP BY LEFT(TitleID, 2)) b
			WHERE a.TitleId = b.TitleID
			AND a.paSearchConditionID = @paSearchConditionID AND a.Title = 'Region'
			----计算全部地区，4位的数据
			UPDATE a SET a.TitleValue = b.TitleValue
			FROM SearchDB..paSearchCount_2 a WITH(NOLOCK), (
				SELECT LEFT(TitleID, 4) TitleID, SUM(TitleValue) TitleValue
				FROM SearchDB..paSearchCount_2 WITH(NOLOCK)
				WHERE paSearchConditionID = @paSearchConditionID AND Title = 'Region'
				AND LEN(TitleID) >3
				GROUP BY LEFT(TitleID, 4)) b
			WHERE a.TitleId = b.TitleID
			AND a.paSearchConditionID = @paSearchConditionID AND a.Title = 'Region'
			----写入TitleDesc
			UPDATE a SET a.TitleDesc = b.Description
			FROM SearchDB..paSearchCount_2 a WITH(NOLOCK), dcRegion b WITH(NOLOCK)
			WHERE a.TitleID = b.ID AND a.paSearchConditionID = @paSearchConditionID
			AND a.Title = 'Region'

			INSERT INTO SearchDB..paSearchCount_2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Education', dcEducationID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcEducationID ORDER BY dcEducationID
			--学历 高中、中专、中级合并		
			SELECT @TitleValue = SUM(TitleValue) FROM SearchDB..paSearchCount_2 WITH(NOLOCK)
			WHERE paSearchConditionID = @paSearchConditionID
			AND Title = 'Education' AND TitleID IN(2, 3, 4)		
			IF @TitleValue IS NOT NULL
			BEGIN
				IF EXISTS(SELECT 'X' FROM SearchDB..paSearchCount_2 WITH(NOLOCK) WHERE paSearchConditionID = @paSearchConditionID AND Title = 'Education' AND TitleID = 2)
					UPDATE SearchDB..paSearchCount_2 SET TitleValue = @TitleValue 
					WHERE paSearchConditionID = @paSearchConditionID
					AND Title = 'Education' AND TitleID = 2
				ELSE
					INSERT INTO SearchDB..paSearchCount_2(paSearchConditionID, Title, TitleId, TitleValue) VALUES
					(@paSearchConditionID, 'Education', 2, @TitleValue)

				DELETE FROM SearchDB..paSearchCount_2
				WHERE paSearchConditionID = @paSearchConditionID
				AND Title = 'Education' AND TitleID IN(3, 4)
			END 

			INSERT INTO SearchDB..paSearchCount_2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Experience', MinExperience, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY MinExperience ORDER BY MinExperience

			INSERT INTO SearchDB..paSearchJobID_2(paSearchConditionID, JobId, IsTop)
			SELECT Top 3 @paSearchConditionID,Balance,1
			FROM caOrder WITH(NOLOCK), (SELECT TOP 2000 ID FROM #Job WITH(NOLOCK)) b
			WHERE caOrder.OrderType = 12 AND BeginDate<GETDATE() AND EndDate>GETDATE() AND b.ID = caOrder.Balance ORDER BY OpenDate DESC
			SET @TopRows = @@ROWCOUNT

			INSERT INTO SearchDB..paSearchJobID_2(paSearchConditionID, JobId, IsTop)
			SELECT TOP 2000 @paSearchConditionID, ID, 0 FROM #Job WITH(NOLOCK)
			SET @AllRows = @@ROWCOUNT

			IF @TopRows = 0 AND @AllRows > 100
				UPDATE SearchDB..paSearchJobID_2 SET IsTop = 1 
				WHERE paSearchConditionID = @paSearchConditionID
				AND ID IN (SELECT TOP 3 ID FROM SearchDB..paSearchJobID_2 WITH(NOLOCK) WHERE paSearchConditionID = @paSearchConditionID)
		END
		ELSE IF (@TableId = 3)
		BEGIN
			INSERT INTO SearchDB..paSearchCount_3(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'JobType', dcJobTypeID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcJobTypeID ORDER BY dcJobTypeID
			----计算全部某职位类别，2, 4位的数据
			UPDATE a SET a.TitleValue = b.TitleValue
			FROM SearchDB..paSearchCount_3 a WITH(NOLOCK), 
			(SELECT LEFT(TitleID, 2) TitleID, SUM(TitleValue) TitleValue
			FROM SearchDB..paSearchCount_3 WITH(NOLOCK)
			WHERE paSearchConditionID = @paSearchConditionID AND Title = 'JobType'
			GROUP BY LEFT(TitleID, 2)) b
			WHERE a.TitleId = b.TitleID
			AND a.paSearchConditionID = @paSearchConditionID AND a.Title = 'JobType'
			----写入TitleDesc
			UPDATE a SET a.TitleDesc = b.Description
			FROM SearchDB..paSearchCount_3 a WITH(NOLOCK), dcJobType b WITH(NOLOCK)
			WHERE a.TitleID = b.ID AND a.paSearchConditionID = @paSearchConditionID
			AND a.Title = 'JobType'
			
			INSERT INTO SearchDB..paSearchCount_3(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Salary', dcSalaryID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcSalaryID ORDER BY dcSalaryID

			INSERT INTO SearchDB..paSearchCount_3(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Region', dcRegionID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcRegionID ORDER BY dcRegionID
			----计算全部地区，2位的数据
			UPDATE a SET a.TitleValue = b.TitleValue
			FROM SearchDB..paSearchCount_3 a WITH(NOLOCK), 
			(SELECT LEFT(TitleID, 2) TitleID, SUM(TitleValue) TitleValue
			FROM SearchDB..paSearchCount_3 WITH(NOLOCK)
			WHERE paSearchConditionID = @paSearchConditionID AND Title = 'Region'
			GROUP BY LEFT(TitleID, 2)) b
			WHERE a.TitleId = b.TitleID
			AND a.paSearchConditionID = @paSearchConditionID AND a.Title = 'Region'
			----计算全部地区，4位的数据
			UPDATE a SET a.TitleValue = b.TitleValue
			FROM SearchDB..paSearchCount_3 a WITH(NOLOCK), (
				SELECT LEFT(TitleID, 4) TitleID, SUM(TitleValue) TitleValue
				FROM SearchDB..paSearchCount_3 WITH(NOLOCK)
				WHERE paSearchConditionID = @paSearchConditionID AND Title = 'Region'
				AND LEN(TitleID) >3
				GROUP BY LEFT(TitleID, 4)) b
			WHERE a.TitleId = b.TitleID
			AND a.paSearchConditionID = @paSearchConditionID AND a.Title = 'Region'
			----写入TitleDesc
			UPDATE a SET a.TitleDesc = b.Description
			FROM SearchDB..paSearchCount_3 a WITH(NOLOCK), dcRegion b WITH(NOLOCK)
			WHERE a.TitleID = b.ID AND a.paSearchConditionID = @paSearchConditionID
			AND a.Title = 'Region'

			INSERT INTO SearchDB..paSearchCount_3(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Education', dcEducationID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcEducationID ORDER BY dcEducationID
			--学历 高中、中专、中级合并		
			SELECT @TitleValue = SUM(TitleValue) FROM SearchDB..paSearchCount_3 WITH(NOLOCK)
			WHERE paSearchConditionID = @paSearchConditionID
			AND Title = 'Education' AND TitleID IN(2, 3, 4)		
			IF @TitleValue IS NOT NULL
			BEGIN
				IF EXISTS(SELECT 'X' FROM SearchDB..paSearchCount_3 WITH(NOLOCK) WHERE paSearchConditionID = @paSearchConditionID AND Title = 'Education' AND TitleID = 2)
					UPDATE SearchDB..paSearchCount_3 SET TitleValue = @TitleValue 
					WHERE paSearchConditionID = @paSearchConditionID
					AND Title = 'Education' AND TitleID = 2
				ELSE
					INSERT INTO SearchDB..paSearchCount_3(paSearchConditionID, Title, TitleId, TitleValue) VALUES
					(@paSearchConditionID, 'Education', 2, @TitleValue)

				DELETE FROM SearchDB..paSearchCount_3
				WHERE paSearchConditionID = @paSearchConditionID
				AND Title = 'Education' AND TitleID IN(3, 4)
			END 

			INSERT INTO SearchDB..paSearchCount_3(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Experience', MinExperience, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY MinExperience ORDER BY MinExperience
			
			INSERT INTO SearchDB..paSearchJobID_3(paSearchConditionID, JobId, IsTop)
			SELECT Top 3 @paSearchConditionID,Balance,1 
			FROM caOrder WITH(NOLOCK), (SELECT TOP 2000 ID FROM #Job WITH(NOLOCK)) b 
			WHERE caOrder.OrderType = 12 AND BeginDate<GETDATE() AND EndDate>GETDATE() AND b.ID = caOrder.Balance ORDER BY OpenDate DESC
			SET @TopRows = @@ROWCOUNT

			INSERT INTO SearchDB..paSearchJobID_3(paSearchConditionID, JobId, IsTop)
			SELECT TOP 2000 @paSearchConditionID, ID, 0 FROM #Job WITH(NOLOCK)
			SET @AllRows = @@ROWCOUNT

			IF @TopRows = 0 AND @AllRows > 100
				UPDATE SearchDB..paSearchJobID_3 SET IsTop = 1 
				WHERE paSearchConditionID = @paSearchConditionID
				AND ID IN (SELECT TOP 3 ID FROM SearchDB..paSearchJobID_3 WITH(NOLOCK) WHERE paSearchConditionID = @paSearchConditionID)
		END
		DROP TABLE #Job
	COMMIT

	GetRecordSet:
	BEGIN
		----返回查询数量
		SELECT ValidJobNumber FROM SearchDB..paSearchCondition WITH(NOLOCK) WHERE ID=@paSearchConditionID
		UPDATE SearchDB..paSearchCondition SET ReuseNumber = ReuseNumber + 1 WHERE ID=@paSearchConditionID
		----返回20行查询结果
		IF (@TableID = 0)
		BEGIN
			SELECT @MinId = MIN(ID) FROM SearchDB..paSearchJobID_0 WITH(NOLOCK) WHERE paSearchConditionID=@paSearchConditionID

			SET @MinId = @MinId+(@PageNumber-1)*@PageSize
			SELECT TOP 8 a.ID, a.cpMainID, a.caMainID, a.Name as JobName, a.dcJobTypeID, 
				a.dcJobTypeIDMinor, a.NeedNumber, a.dcSalaryID, a.EmployType, 
				a.dcRegionID, a.Responsibility, a.Demand, a.dcEducationID, 
				a.MinExperience, a.MinAge, a.MaxAge, a.IssueDate, a.IssueEND, 
				a.IsDelete, a.AddDate, a.RefreshDate, 
				a.LastModifyDate, b.Name as cpName, b.dcCompanySizeID, 
				b.HasLicence, b.UnLimitedDate, b.BalanceDate, b.Balance, 
				b.MemberType, STUFF((SELECT ','+LTRIM(x.dcIndustryid)+',c'+LTRIM(isnull(y.Category,0)) 
							FROM cpIndustry x,dcIndustry y WHERE x.dcIndustryid = y.id 
							AND x.cpMainid = b.id FOR XML PATH('')),1,1,'') cpIndustry,
				c.IsTop, b.IsRefreshed, a.SecondId EnJobID, b.SecondId EnCpMainID
			FROM JobPublish a WITH(NOLOCK), cpMainPublish b WITH(NOLOCK), SearchDB..paSearchJobID_0 c WITH(NOLOCK)
			WHERE a.cpMainID = b.ID AND a.id=c.JobID AND c.paSearchConditionID=@paSearchConditionID 
				  AND c.ID>=@MinId ORDER BY c.ID, a.ID DESC
		END
		ELSE IF (@TableID = 1)
		BEGIN
			SELECT @MinId = MIN(ID) FROM SearchDB..paSearchJobID_1 WITH(NOLOCK) WHERE paSearchConditionID=@paSearchConditionID

			SET @MinId = @MinId+(@PageNumber-1)*@PageSize
			SELECT TOP 8 a.ID, a.cpMainID, a.caMainID, a.Name as JobName, a.dcJobTypeID, 
				a.dcJobTypeIDMinor, a.NeedNumber, a.dcSalaryID, a.EmployType, 
				a.dcRegionID, a.Responsibility, a.Demand, a.dcEducationID, 
				a.MinExperience, a.MinAge, a.MaxAge, a.IssueDate, a.IssueEND, 
				a.IsDelete, a.AddDate, a.RefreshDate, 
				a.LastModifyDate, b.Name as cpName, b.dcCompanySizeID, 
				b.HasLicence, b.UnLimitedDate, b.BalanceDate, b.Balance, 
				b.MemberType, STUFF((SELECT ','+LTRIM(x.dcIndustryid)+',c'+LTRIM(isnull(y.Category,0)) 
							FROM cpIndustry x,dcIndustry y WHERE x.dcIndustryid = y.id 
							AND x.cpMainid = b.id FOR XML PATH('')),1,1,'') cpIndustry,
				c.IsTop, b.IsRefreshed, a.SecondId EnJobID, b.SecondId EnCpMainID
			FROM JobPublish a WITH(NOLOCK), cpMainPublish b WITH(NOLOCK), SearchDB..paSearchJobID_1 c WITH(NOLOCK)
			WHERE a.cpMainID = b.ID AND a.id=c.JobID AND c.paSearchConditionID=@paSearchConditionID 
				  AND c.ID>=@MinId ORDER BY c.ID, a.ID DESC
		END
		ELSE IF (@TableID = 2)
		BEGIN
			SELECT @MinId = MIN(ID) FROM SearchDB..paSearchJobID_2 WITH(NOLOCK) WHERE paSearchConditionID=@paSearchConditionID

			SET @MinId = @MinId+(@PageNumber-1)*@PageSize
			SELECT TOP 8 a.ID, a.cpMainID, a.caMainID, a.Name as JobName, a.dcJobTypeID, 
				a.dcJobTypeIDMinor, a.NeedNumber, a.dcSalaryID, a.EmployType, 
				a.dcRegionID, a.Responsibility, a.Demand, a.dcEducationID, 
				a.MinExperience, a.MinAge, a.MaxAge, a.IssueDate, a.IssueEND, 
				a.IsDelete, a.AddDate, a.RefreshDate, 
				a.LastModifyDate, b.Name as cpName, b.dcCompanySizeID, 
				b.HasLicence, b.UnLimitedDate, b.BalanceDate, b.Balance, 
				b.MemberType, STUFF((SELECT ','+LTRIM(x.dcIndustryid)+',c'+LTRIM(isnull(y.Category,0)) 
							FROM cpIndustry x,dcIndustry y WHERE x.dcIndustryid = y.id 
							AND x.cpMainid = b.id FOR XML PATH('')),1,1,'') cpIndustry,
				c.IsTop, b.IsRefreshed, a.SecondId EnJobID, b.SecondId EnCpMainID
			FROM JobPublish a WITH(NOLOCK), cpMainPublish b WITH(NOLOCK), SearchDB..paSearchJobID_2 c WITH(NOLOCK)
			WHERE a.cpMainID = b.ID AND a.id=c.JobID AND c.paSearchConditionID=@paSearchConditionID 
				  AND c.ID>=@MinId ORDER BY c.ID, a.ID DESC
		END
		ELSE IF (@TableID = 3)
		BEGIN
			SELECT @MinId = MIN(ID) FROM SearchDB..paSearchJobID_3 WITH(NOLOCK) WHERE paSearchConditionID=@paSearchConditionID

			SET @MinId = @MinId+(@PageNumber-1)*@PageSize
			SELECT TOP 8 a.ID, a.cpMainID, a.caMainID, a.Name as JobName, a.dcJobTypeID, 
				a.dcJobTypeIDMinor, a.NeedNumber, a.dcSalaryID, a.EmployType, 
				a.dcRegionID, a.Responsibility, a.Demand, a.dcEducationID, 
				a.MinExperience, a.MinAge, a.MaxAge, a.IssueDate, a.IssueEND, 
				a.IsDelete, a.AddDate, a.RefreshDate, 
				a.LastModifyDate, b.Name as cpName, b.dcCompanySizeID, 
				b.HasLicence, b.UnLimitedDate, b.BalanceDate, b.Balance, 
				b.MemberType, STUFF((SELECT ','+LTRIM(x.dcIndustryid)+',c'+LTRIM(isnull(y.Category,0)) 
							FROM cpIndustry x,dcIndustry y WHERE x.dcIndustryid = y.id 
							AND x.cpMainid = b.id FOR XML PATH('')),1,1,'') cpIndustry,
				c.IsTop, b.IsRefreshed, a.SecondId EnJobID, b.SecondId EnCpMainID
			FROM JobPublish a WITH(NOLOCK), cpMainPublish b WITH(NOLOCK), SearchDB..paSearchJobID_3 c WITH(NOLOCK)
			WHERE a.cpMainID = b.ID AND a.id=c.JobID AND c.paSearchConditionID=@paSearchConditionID 
				  AND c.ID>=@MinId ORDER BY c.ID, a.ID DESC
		END
		RETURN
	END
END TRY
BEGIN CATCH
	---检查是否已经建立临时表，已经建立则删除
	PRINT 'error'
	PRINT error_Message()
	PRINT error_number()
	PRINT error_line()
END CATCH












GO
/****** Object:  StoredProcedure [dbo].[paJobByWeixinSelect1]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[paJobByWeixinSelect1] 
(
	@FromUserName VARCHAR(50),
	@Type INT		--0：订阅号关键词查询；10：服务号的关键词查询；11：服务号的周边职位

)
AS
--return
SET NOCOUNT ON
BEGIN TRY
	DECLARE @dcRegionID INT,@KeyWord NVARCHAR(20),
	@Lng DECIMAL(8,5),@Lat DECIMAL(8,5),@Distance INT,
	@KeyType TINYINT, @ValidJobNumber INT, @PageNumber SMALLINT

	IF @Type =11
	BEGIN
		SELECT @dcRegionID=dcRegionID,@KeyWord=KeyWord,
			@Lng=Lng,@Lat=Lat,@PageNumber=PageNumber
			FROM wxMessage WITH(NOLOCK) WHERE FromUserName=@FromUserName AND CONTENT='推荐职位'
	END
	ELSE
	BEGIN
		SELECT @dcRegionID=dcRegionID,@KeyWord=KeyWord,
			@Lng=Lng,@Lat=Lat,@PageNumber=PageNumber
			FROM wxMessage WITH(NOLOCK) WHERE FromUserName=@FromUserName
	END

	IF @Type =11 OR @Type = 10
	BEGIN
		UPDATE wxMessage SET PageNumber = 2 WHERE FromUserName=@FromUserName
	END
	ELSE
	BEGIN
		UPDATE wxMessage SET PageNumber=PageNumber+1 WHERE FromUserName=@FromUserName
	END


	--UPDATE wxMessage SET PageNumber=PageNumber+1 WHERE FromUserName=@FromUserName
	SELECT @KeyWord = dbo.SafeSQL(ISNULL(@KeyWord, '')),
		@KeyType = 2,
		@Distance = 5000,
		@PageNumber = ISNULL(@PageNumber, 1),
		@dcRegionID = ISNULL(@dcRegionID, 0),
		@Lng = ISNULL(@Lng, 0),
		@Lat = ISNULL(@Lat, 0)

	IF @dcRegionID = 0 AND @Lng = 0 AND @Lat = 0
		RETURN

	DECLARE @paSearchConditionID AS INT, 
		@MinId AS INT, 
		@PageSize AS TINYINT, 
		@TableID AS TINYINT


	IF @Type =11 OR  @Type =10
	BEGIN
		SELECT @paSearchConditionID = 0, @PageSize = 5  --每页的行数
	END 
	ELSE 
	BEGIN
		SELECT @paSearchConditionID = 0, @PageSize = 8  --每页的行数
	END

	--SELECT @paSearchConditionID = 0, @PageSize = 8  --每页的行数
	
	----搜索60分钟前的数据
	SELECT TOP 1 @paSearchConditionID=ID FROM SearchDB..paSearchCondition WITH(NOLOCK)
	WHERE JobType=''
	AND JobPlace=@dcRegionID AND ISNULL(Industry,'')='' AND ISNULL(Education,'')=''
	AND ISNULL(Experience,'')='' AND ISNULL(Salary,'')='' AND ISNULL(IsNegotiable,'')='' 
	AND ISNULL(EmployType,'')='' AND KeyWord=@KeyWord AND KeyType=@KeyType
	AND ISNULL(CompanySizeID,'')='' AND Lng=@Lng AND Lat=@Lat
	ORDER BY ID DESC

	IF ISNULL(@paSearchConditionID, 0) = 0
	BEGIN
		GOTO SelectReset	--无数据，重新搜索
	END
	ELSE
	BEGIN
		SELECT @TableID = @paSearchConditionID % 4
		GOTO GetRecordSet	--从临时结果中提取数据
	END

	SelectReset:
	--从job中搜索数据
	BEGIN TRAN
		DECLARE @SQL AS VARCHAR(8000)
		DECLARE @WHERE AS VARCHAR(8000)
		DECLARE @FROM AS VARCHAR(1000)
		----记录查询条件
		INSERT INTO SearchDB..paSearchCondition(SessionID, LogTime, JobType, JobPlace, Industry, Education, Experience, 
			Salary, IsNegotiable, EmployType, CompanySizeID, KeyWord, KeyType, ReuseNumber, Lng, Lat, Distance)
		VALUES(1, GETDATE(), '', @dcRegionID, '', '', '', '', '', '', '', @KeyWord, @KeyType, 0, @Lng, @Lat, @Distance)
		SET @paSearchConditionID = @@IDENTITY
		SELECT @TableID = @paSearchConditionID % 4

		----建立临时表
		CREATE TABLE #Job(
			RowID INT IDENTITY(1, 1), 
			ID INT NOT NULL, 
			dcJobTypeID SMALLINT NOT NULL, 
			dcJobTypeIDMinor SMALLINT NULL, 
			dcSalaryID TINYINT NOT NULL, 
			dcRegionID VARCHAR(6) NULL, 
			dcEducationID TINYINT NOT NULL, 
			MinExperience TINYINT NOT NULL, 
			RefreshDate SMALLDATETIME NULL
		)
		------刷新时间，根据刷新时间编号计算
		----生成插入临时表的Sql语句
		SET @SQL='
			INSERT INTO #Job
			SELECT a.ID, a.dcJobTypeID, 
				a.dcJobTypeIDMinor, a.dcSalaryID, 
				a.dcRegionID, a.dcEducationID, a.MinExperience, 
				a.IssueDate'
		SET @FROM = '
			FROM JobPublish a WITH(NOLOCK)
			INNER JOIN cpMainPublish b WITH(NOLOCK) ON a.cpMainID=b.ID'
		----职位有效，单位新有效
		SET @WHERE = '
			WHERE a.Valid = 1
			AND b.Valid = 1'
		----需要增加全文索引的关键字查询
		IF @KeyWord LIKE '% %'
		BEGIN
			SET @KeyWord = REPLACE(@KeyWord, '  ', ' ')
			SET @KeyWord = REPLACE(@KeyWord, '  ', ' ')
			SET @KeyWord = REPLACE(@KeyWord, '  ', ' ')
			SET @KeyWord = '"' + REPLACE(@KeyWord, ' ', '" OR "') + '"'
		END

		IF LEN(@KeyWord) > 0
		BEGIN
			IF @KeyType = 2
				SET @FROM = @FROM + '
			INNER JOIN CONTAINSTABLE(JobPublish, *, ''' + @KeyWord + ''', 1000000) AS KeyJob
			ON a.ID = KeyJob.[Key]'
		END
		---地区
		IF @dcRegionID > 0 
			SET @WHERE = @WHERE + '
			AND a.dcRegionID Like ''' + CONVERT(VARCHAR(6),@dcRegionID) + '%'''

		IF @Lng > 0 AND @Lat > 0
		BEGIN
			DECLARE @Degree AS DECIMAL(8,5),@LBLng AS DECIMAL(8,5),@LBLat AS DECIMAL(8,5),
			@RTLng AS DECIMAL(8,5),@RTLat AS DECIMAL(8,5)
			SET @Degree = @Distance / 100000.0;

			SET @LBLng = @Lng - @Degree
			SET @LBLat = @Lat - @Degree
			SET @RTLng = @Lng + @Degree
			SET @RTLat = @Lat + @Degree
			SET @WHERE = @WHERE + '
				AND a.Lng BETWEEN ' + CONVERT(VARCHAR,@LBLng) + ' AND ' + CONVERT(VARCHAR,@RTLng) + '
				AND a.Lat BETWEEN ' + CONVERT(VARCHAR,@LBLat) + ' AND ' + CONVERT(VARCHAR,@RTLat)
		END
		SET @SQL = @SQL + @FROM + @WHERE
		
		SET @SQL=@SQL + ' ORDER BY a.RefreshDate DESC, a.ID'

		----把符合条件的职位全部列出
		--PRINT @SQL
		EXEC(@SQL)
		
		SET @ValidJobNumber = @@ROWCOUNT
		----记录查询结果总数
		UPDATE SearchDB..paSearchCondition SET ValidJobNumber=@ValidJobNumber, SQl=@SQL WHERE ID=@paSearchConditionID
		
		----插入JobType数据
		DECLARE @TitleValue AS INT, @TopRows AS INT, @AllRows AS INT
		IF (@TableID = 0)
		BEGIN
			INSERT INTO SearchDB..paSearchCount_0(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'JobType', dcJobTypeID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcJobTypeID ORDER BY dcJobTypeID
			----计算全部某职位类别，2, 4位的数据
			UPDATE a SET a.TitleValue = b.TitleValue
			FROM SearchDB..paSearchCount_0 a WITH(NOLOCK), 
				(SELECT LEFT(TitleID, 2) TitleID, SUM(TitleValue) TitleValue
				FROM SearchDB..paSearchCount_0 WITH(NOLOCK)
				WHERE paSearchConditionID = @paSearchConditionID AND Title = 'JobType'
				GROUP BY LEFT(TitleID, 2)) b
			WHERE a.TitleId = b.TitleID
			AND a.paSearchConditionID = @paSearchConditionID AND a.Title = 'JobType'
			----写入TitleDesc
			UPDATE a SET a.TitleDesc = b.Description
			FROM SearchDB..paSearchCount_0 a WITH(NOLOCK), dcJobType b WITH(NOLOCK)
			WHERE a.TitleID = b.ID AND a.paSearchConditionID = @paSearchConditionID
			AND a.Title = 'JobType'
			
			INSERT INTO SearchDB..paSearchCount_0(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Salary', dcSalaryID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcSalaryID ORDER BY dcSalaryID

			INSERT INTO SearchDB..paSearchCount_0(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Region', dcRegionID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcRegionID ORDER BY dcRegionID
			----计算全部地区，2位的数据
			UPDATE a SET a.TitleValue = b.TitleValue
			FROM SearchDB..paSearchCount_0 a WITH(NOLOCK), 
			(SELECT LEFT(TitleID, 2) TitleID, SUM(TitleValue) TitleValue
			FROM SearchDB..paSearchCount_0 WITH(NOLOCK)
			WHERE paSearchConditionID = @paSearchConditionID AND Title = 'Region'
			GROUP BY LEFT(TitleID, 2)) b
			WHERE a.TitleId = b.TitleID
			AND a.paSearchConditionID = @paSearchConditionID AND a.Title = 'Region'
			----计算全部地区，4位的数据
			UPDATE a SET a.TitleValue = b.TitleValue
			FROM SearchDB..paSearchCount_0 a WITH(NOLOCK), (
				SELECT LEFT(TitleID, 4) TitleID, SUM(TitleValue) TitleValue
				FROM SearchDB..paSearchCount_0 WITH(NOLOCK)
				WHERE paSearchConditionID = @paSearchConditionID AND Title = 'Region'
				AND LEN(TitleID) >3
				GROUP BY LEFT(TitleID, 4)) b
			WHERE a.TitleId = b.TitleID
			AND a.paSearchConditionID = @paSearchConditionID AND a.Title = 'Region'
			----写入TitleDesc
			UPDATE a SET a.TitleDesc = b.Description
			FROM SearchDB..paSearchCount_0 a WITH(NOLOCK), dcRegion b WITH(NOLOCK)
			WHERE a.TitleID = b.ID AND a.paSearchConditionID = @paSearchConditionID
			AND a.Title = 'Region'

			INSERT INTO SearchDB..paSearchCount_0(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Education', dcEducationID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcEducationID ORDER BY dcEducationID
			--学历 高中、中专、中级合并		
			SELECT @TitleValue = SUM(TitleValue) FROM SearchDB..paSearchCount_0 WITH(NOLOCK)
			WHERE paSearchConditionID = @paSearchConditionID
			AND Title = 'Education' AND TitleID IN(2, 3, 4)		
			IF @TitleValue IS NOT NULL
			BEGIN
				IF EXISTS(SELECT 'X' FROM SearchDB..paSearchCount_0 WITH(NOLOCK) WHERE paSearchConditionID = @paSearchConditionID AND Title = 'Education' AND TitleID = 2)
					UPDATE SearchDB..paSearchCount_0 SET TitleValue = @TitleValue 
					WHERE paSearchConditionID = @paSearchConditionID
					AND Title = 'Education' AND TitleID = 2
				ELSE
					INSERT INTO SearchDB..paSearchCount_0(paSearchConditionID, Title, TitleId, TitleValue) VALUES
					(@paSearchConditionID, 'Education', 2, @TitleValue)

				DELETE FROM SearchDB..paSearchCount_0
				WHERE paSearchConditionID = @paSearchConditionID
				AND Title = 'Education' AND TitleID IN(3, 4)
			END 

			INSERT INTO SearchDB..paSearchCount_0(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Experience', MinExperience, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY MinExperience ORDER BY MinExperience
			
			INSERT INTO SearchDB..paSearchJobID_0(paSearchConditionID, JobId, IsTop)
			SELECT Top 3 @paSearchConditionID,Balance,1 
			FROM caOrder WITH(NOLOCK), (SELECT TOP 2000 ID FROM #Job WITH(NOLOCK)) b 
			WHERE caOrder.OrderType = 12 AND BeginDate<GETDATE() AND EndDate>GETDATE() AND b.ID = caOrder.Balance ORDER BY OpenDate DESC
			SET @TopRows = @@ROWCOUNT

			INSERT INTO SearchDB..paSearchJobID_0(paSearchConditionID, JobId, IsTop)
			SELECT TOP 2000 @paSearchConditionID, ID, 0 FROM #Job WITH(NOLOCK)
			SET @AllRows = @@ROWCOUNT

			IF @TopRows = 0 AND @AllRows > 100
				UPDATE SearchDB..paSearchJobID_0 SET IsTop = 1 
				WHERE paSearchConditionID = @paSearchConditionID
				AND ID IN (SELECT TOP 3 ID FROM SearchDB..paSearchJobID_0 WITH(NOLOCK) WHERE paSearchConditionID = @paSearchConditionID)
		END
		ELSE IF (@TableId = 1)
		BEGIN
			INSERT INTO SearchDB..paSearchCount_1(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'JobType', dcJobTypeID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcJobTypeID ORDER BY dcJobTypeID
			----计算全部某职位类别，2, 4位的数据
			UPDATE a SET a.TitleValue = b.TitleValue
			FROM SearchDB..paSearchCount_1 a WITH(NOLOCK), 
			(SELECT LEFT(TitleID, 2) TitleID, SUM(TitleValue) TitleValue
			FROM SearchDB..paSearchCount_1 WITH(NOLOCK)
			WHERE paSearchConditionID = @paSearchConditionID AND Title = 'JobType'
			GROUP BY LEFT(TitleID, 2)) b
			WHERE a.TitleId = b.TitleID
			AND a.paSearchConditionID = @paSearchConditionID AND a.Title = 'JobType'
			----写入TitleDesc
			UPDATE a SET a.TitleDesc = b.Description
			FROM SearchDB..paSearchCount_1 a WITH(NOLOCK), dcJobType b WITH(NOLOCK)
			WHERE a.TitleID = b.ID AND a.paSearchConditionID = @paSearchConditionID
			AND a.Title = 'JobType'
			
			INSERT INTO SearchDB..paSearchCount_1(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Salary', dcSalaryID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcSalaryID ORDER BY dcSalaryID

			INSERT INTO SearchDB..paSearchCount_1(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Region', dcRegionID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcRegionID ORDER BY dcRegionID
			----计算全部地区，2位的数据
			UPDATE a SET a.TitleValue = b.TitleValue
			FROM SearchDB..paSearchCount_1 a WITH(NOLOCK), 
			(SELECT LEFT(TitleID, 2) TitleID, SUM(TitleValue) TitleValue
			FROM SearchDB..paSearchCount_1 WITH(NOLOCK)
			WHERE paSearchConditionID = @paSearchConditionID AND Title = 'Region'
			GROUP BY LEFT(TitleID, 2)) b
			WHERE a.TitleId = b.TitleID
			AND a.paSearchConditionID = @paSearchConditionID AND a.Title = 'Region'
			----计算全部地区，4位的数据
			UPDATE a SET a.TitleValue = b.TitleValue
			FROM SearchDB..paSearchCount_1 a WITH(NOLOCK), (
				SELECT LEFT(TitleID, 4) TitleID, SUM(TitleValue) TitleValue
				FROM SearchDB..paSearchCount_1 WITH(NOLOCK)
				WHERE paSearchConditionID = @paSearchConditionID AND Title = 'Region'
				AND LEN(TitleID) >3
				GROUP BY LEFT(TitleID, 4)) b
			WHERE a.TitleId = b.TitleID
			AND a.paSearchConditionID = @paSearchConditionID AND a.Title = 'Region'
			----写入TitleDesc
			UPDATE a SET a.TitleDesc = b.Description
			FROM SearchDB..paSearchCount_1 a WITH(NOLOCK), dcRegion b WITH(NOLOCK)
			WHERE a.TitleID = b.ID AND a.paSearchConditionID = @paSearchConditionID
			AND a.Title = 'Region'

			INSERT INTO SearchDB..paSearchCount_1(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Education', dcEducationID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcEducationID ORDER BY dcEducationID
			--学历 高中、中专、中级合并		
			SELECT @TitleValue = SUM(TitleValue) FROM SearchDB..paSearchCount_1 WITH(NOLOCK)
			WHERE paSearchConditionID = @paSearchConditionID
			AND Title = 'Education' AND TitleID IN(2, 3, 4)		
			IF @TitleValue IS NOT NULL
			BEGIN
				IF EXISTS(SELECT 'X' FROM SearchDB..paSearchCount_1 WITH(NOLOCK) WHERE paSearchConditionID = @paSearchConditionID AND Title = 'Education' AND TitleID = 2)
					UPDATE SearchDB..paSearchCount_1 SET TitleValue = @TitleValue 
					WHERE paSearchConditionID = @paSearchConditionID
					AND Title = 'Education' AND TitleID = 2
				ELSE
					INSERT INTO SearchDB..paSearchCount_1(paSearchConditionID, Title, TitleId, TitleValue) VALUES
					(@paSearchConditionID, 'Education', 2, @TitleValue)

				DELETE FROM SearchDB..paSearchCount_1
				WHERE paSearchConditionID = @paSearchConditionID
				AND Title = 'Education' AND TitleID IN(3, 4)
			END 

			INSERT INTO SearchDB..paSearchCount_1(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Experience', MinExperience, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY MinExperience ORDER BY MinExperience
	
			INSERT INTO SearchDB..paSearchJobID_1(paSearchConditionID, JobId, IsTop)
			SELECT Top 3 @paSearchConditionID,Balance,1
			FROM caOrder WITH(NOLOCK), (SELECT TOP 2000 ID FROM #Job WITH(NOLOCK)) b
			WHERE caOrder.OrderType = 12 AND BeginDate<GETDATE() AND EndDate>GETDATE() AND b.ID = caOrder.Balance ORDER BY OpenDate DESC
			SET @TopRows = @@ROWCOUNT

			INSERT INTO SearchDB..paSearchJobID_1(paSearchConditionID, JobId, IsTop)
			SELECT TOP 2000 @paSearchConditionID, ID, 0 FROM #Job WITH(NOLOCK)
			SET @AllRows = @@ROWCOUNT

			IF @TopRows = 0 AND @AllRows > 100
				UPDATE SearchDB..paSearchJobID_1 SET IsTop = 1 
				WHERE paSearchConditionID = @paSearchConditionID
				AND ID IN (SELECT TOP 3 ID FROM SearchDB..paSearchJobID_1 WITH(NOLOCK) WHERE paSearchConditionID = @paSearchConditionID)
		END
		ELSE IF (@TableId = 2)
		BEGIN
			INSERT INTO SearchDB..paSearchCount_2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'JobType', dcJobTypeID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcJobTypeID ORDER BY dcJobTypeID
			----计算全部某职位类别，2, 4位的数据
			UPDATE a SET a.TitleValue = b.TitleValue
			FROM SearchDB..paSearchCount_2 a WITH(NOLOCK), 
			(SELECT LEFT(TitleID, 2) TitleID, SUM(TitleValue) TitleValue
			FROM SearchDB..paSearchCount_2 WITH(NOLOCK)
			WHERE paSearchConditionID = @paSearchConditionID AND Title = 'JobType'
			GROUP BY LEFT(TitleID, 2)) b
			WHERE a.TitleId = b.TitleID
			AND a.paSearchConditionID = @paSearchConditionID AND a.Title = 'JobType'
			----写入TitleDesc
			UPDATE a SET a.TitleDesc = b.Description
			FROM SearchDB..paSearchCount_2 a WITH(NOLOCK), dcJobType b WITH(NOLOCK)
			WHERE a.TitleID = b.ID AND a.paSearchConditionID = @paSearchConditionID
			AND a.Title = 'JobType'
			
			INSERT INTO SearchDB..paSearchCount_2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Salary', dcSalaryID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcSalaryID ORDER BY dcSalaryID

			INSERT INTO SearchDB..paSearchCount_2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Region', dcRegionID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcRegionID ORDER BY dcRegionID
			----计算全部地区，2位的数据
			UPDATE a SET a.TitleValue = b.TitleValue
			FROM SearchDB..paSearchCount_2 a WITH(NOLOCK), 
			(SELECT LEFT(TitleID, 2) TitleID, SUM(TitleValue) TitleValue
			FROM SearchDB..paSearchCount_2 WITH(NOLOCK)
			WHERE paSearchConditionID = @paSearchConditionID AND Title = 'Region'
			GROUP BY LEFT(TitleID, 2)) b
			WHERE a.TitleId = b.TitleID
			AND a.paSearchConditionID = @paSearchConditionID AND a.Title = 'Region'
			----计算全部地区，4位的数据
			UPDATE a SET a.TitleValue = b.TitleValue
			FROM SearchDB..paSearchCount_2 a WITH(NOLOCK), (
				SELECT LEFT(TitleID, 4) TitleID, SUM(TitleValue) TitleValue
				FROM SearchDB..paSearchCount_2 WITH(NOLOCK)
				WHERE paSearchConditionID = @paSearchConditionID AND Title = 'Region'
				AND LEN(TitleID) >3
				GROUP BY LEFT(TitleID, 4)) b
			WHERE a.TitleId = b.TitleID
			AND a.paSearchConditionID = @paSearchConditionID AND a.Title = 'Region'
			----写入TitleDesc
			UPDATE a SET a.TitleDesc = b.Description
			FROM SearchDB..paSearchCount_2 a WITH(NOLOCK), dcRegion b WITH(NOLOCK)
			WHERE a.TitleID = b.ID AND a.paSearchConditionID = @paSearchConditionID
			AND a.Title = 'Region'

			INSERT INTO SearchDB..paSearchCount_2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Education', dcEducationID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcEducationID ORDER BY dcEducationID
			--学历 高中、中专、中级合并		
			SELECT @TitleValue = SUM(TitleValue) FROM SearchDB..paSearchCount_2 WITH(NOLOCK)
			WHERE paSearchConditionID = @paSearchConditionID
			AND Title = 'Education' AND TitleID IN(2, 3, 4)		
			IF @TitleValue IS NOT NULL
			BEGIN
				IF EXISTS(SELECT 'X' FROM SearchDB..paSearchCount_2 WITH(NOLOCK) WHERE paSearchConditionID = @paSearchConditionID AND Title = 'Education' AND TitleID = 2)
					UPDATE SearchDB..paSearchCount_2 SET TitleValue = @TitleValue 
					WHERE paSearchConditionID = @paSearchConditionID
					AND Title = 'Education' AND TitleID = 2
				ELSE
					INSERT INTO SearchDB..paSearchCount_2(paSearchConditionID, Title, TitleId, TitleValue) VALUES
					(@paSearchConditionID, 'Education', 2, @TitleValue)

				DELETE FROM SearchDB..paSearchCount_2
				WHERE paSearchConditionID = @paSearchConditionID
				AND Title = 'Education' AND TitleID IN(3, 4)
			END 

			INSERT INTO SearchDB..paSearchCount_2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Experience', MinExperience, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY MinExperience ORDER BY MinExperience

			INSERT INTO SearchDB..paSearchJobID_2(paSearchConditionID, JobId, IsTop)
			SELECT Top 3 @paSearchConditionID,Balance,1
			FROM caOrder WITH(NOLOCK), (SELECT TOP 2000 ID FROM #Job WITH(NOLOCK)) b
			WHERE caOrder.OrderType = 12 AND BeginDate<GETDATE() AND EndDate>GETDATE() AND b.ID = caOrder.Balance ORDER BY OpenDate DESC
			SET @TopRows = @@ROWCOUNT

			INSERT INTO SearchDB..paSearchJobID_2(paSearchConditionID, JobId, IsTop)
			SELECT TOP 2000 @paSearchConditionID, ID, 0 FROM #Job WITH(NOLOCK)
			SET @AllRows = @@ROWCOUNT

			IF @TopRows = 0 AND @AllRows > 100
				UPDATE SearchDB..paSearchJobID_2 SET IsTop = 1 
				WHERE paSearchConditionID = @paSearchConditionID
				AND ID IN (SELECT TOP 3 ID FROM SearchDB..paSearchJobID_2 WITH(NOLOCK) WHERE paSearchConditionID = @paSearchConditionID)
		END
		ELSE IF (@TableId = 3)
		BEGIN
			INSERT INTO SearchDB..paSearchCount_3(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'JobType', dcJobTypeID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcJobTypeID ORDER BY dcJobTypeID
			----计算全部某职位类别，2, 4位的数据
			UPDATE a SET a.TitleValue = b.TitleValue
			FROM SearchDB..paSearchCount_3 a WITH(NOLOCK), 
			(SELECT LEFT(TitleID, 2) TitleID, SUM(TitleValue) TitleValue
			FROM SearchDB..paSearchCount_3 WITH(NOLOCK)
			WHERE paSearchConditionID = @paSearchConditionID AND Title = 'JobType'
			GROUP BY LEFT(TitleID, 2)) b
			WHERE a.TitleId = b.TitleID
			AND a.paSearchConditionID = @paSearchConditionID AND a.Title = 'JobType'
			----写入TitleDesc
			UPDATE a SET a.TitleDesc = b.Description
			FROM SearchDB..paSearchCount_3 a WITH(NOLOCK), dcJobType b WITH(NOLOCK)
			WHERE a.TitleID = b.ID AND a.paSearchConditionID = @paSearchConditionID
			AND a.Title = 'JobType'
			
			INSERT INTO SearchDB..paSearchCount_3(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Salary', dcSalaryID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcSalaryID ORDER BY dcSalaryID

			INSERT INTO SearchDB..paSearchCount_3(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Region', dcRegionID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcRegionID ORDER BY dcRegionID
			----计算全部地区，2位的数据
			UPDATE a SET a.TitleValue = b.TitleValue
			FROM SearchDB..paSearchCount_3 a WITH(NOLOCK), 
			(SELECT LEFT(TitleID, 2) TitleID, SUM(TitleValue) TitleValue
			FROM SearchDB..paSearchCount_3 WITH(NOLOCK)
			WHERE paSearchConditionID = @paSearchConditionID AND Title = 'Region'
			GROUP BY LEFT(TitleID, 2)) b
			WHERE a.TitleId = b.TitleID
			AND a.paSearchConditionID = @paSearchConditionID AND a.Title = 'Region'
			----计算全部地区，4位的数据
			UPDATE a SET a.TitleValue = b.TitleValue
			FROM SearchDB..paSearchCount_3 a WITH(NOLOCK), (
				SELECT LEFT(TitleID, 4) TitleID, SUM(TitleValue) TitleValue
				FROM SearchDB..paSearchCount_3 WITH(NOLOCK)
				WHERE paSearchConditionID = @paSearchConditionID AND Title = 'Region'
				AND LEN(TitleID) >3
				GROUP BY LEFT(TitleID, 4)) b
			WHERE a.TitleId = b.TitleID
			AND a.paSearchConditionID = @paSearchConditionID AND a.Title = 'Region'
			----写入TitleDesc
			UPDATE a SET a.TitleDesc = b.Description
			FROM SearchDB..paSearchCount_3 a WITH(NOLOCK), dcRegion b WITH(NOLOCK)
			WHERE a.TitleID = b.ID AND a.paSearchConditionID = @paSearchConditionID
			AND a.Title = 'Region'

			INSERT INTO SearchDB..paSearchCount_3(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Education', dcEducationID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcEducationID ORDER BY dcEducationID
			--学历 高中、中专、中级合并		
			SELECT @TitleValue = SUM(TitleValue) FROM SearchDB..paSearchCount_3 WITH(NOLOCK)
			WHERE paSearchConditionID = @paSearchConditionID
			AND Title = 'Education' AND TitleID IN(2, 3, 4)		
			IF @TitleValue IS NOT NULL
			BEGIN
				IF EXISTS(SELECT 'X' FROM SearchDB..paSearchCount_3 WITH(NOLOCK) WHERE paSearchConditionID = @paSearchConditionID AND Title = 'Education' AND TitleID = 2)
					UPDATE SearchDB..paSearchCount_3 SET TitleValue = @TitleValue 
					WHERE paSearchConditionID = @paSearchConditionID
					AND Title = 'Education' AND TitleID = 2
				ELSE
					INSERT INTO SearchDB..paSearchCount_3(paSearchConditionID, Title, TitleId, TitleValue) VALUES
					(@paSearchConditionID, 'Education', 2, @TitleValue)

				DELETE FROM SearchDB..paSearchCount_3
				WHERE paSearchConditionID = @paSearchConditionID
				AND Title = 'Education' AND TitleID IN(3, 4)
			END 

			INSERT INTO SearchDB..paSearchCount_3(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Experience', MinExperience, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY MinExperience ORDER BY MinExperience
			
			INSERT INTO SearchDB..paSearchJobID_3(paSearchConditionID, JobId, IsTop)
			SELECT Top 3 @paSearchConditionID,Balance,1 
			FROM caOrder WITH(NOLOCK), (SELECT TOP 2000 ID FROM #Job WITH(NOLOCK)) b 
			WHERE caOrder.OrderType = 12 AND BeginDate<GETDATE() AND EndDate>GETDATE() AND b.ID = caOrder.Balance ORDER BY OpenDate DESC
			SET @TopRows = @@ROWCOUNT

			INSERT INTO SearchDB..paSearchJobID_3(paSearchConditionID, JobId, IsTop)
			SELECT TOP 2000 @paSearchConditionID, ID, 0 FROM #Job WITH(NOLOCK)
			SET @AllRows = @@ROWCOUNT

			IF @TopRows = 0 AND @AllRows > 100
				UPDATE SearchDB..paSearchJobID_3 SET IsTop = 1 
				WHERE paSearchConditionID = @paSearchConditionID
				AND ID IN (SELECT TOP 3 ID FROM SearchDB..paSearchJobID_3 WITH(NOLOCK) WHERE paSearchConditionID = @paSearchConditionID)
		END
		DROP TABLE #Job
	COMMIT

	GetRecordSet:
	BEGIN
		----返回查询数量
		SELECT ValidJobNumber FROM SearchDB..paSearchCondition WITH(NOLOCK) WHERE ID=@paSearchConditionID
		UPDATE SearchDB..paSearchCondition SET ReuseNumber = ReuseNumber + 1 WHERE ID=@paSearchConditionID
		----返回20行查询结果
		IF (@TableID = 0)
		BEGIN
			SELECT @MinId = MIN(ID) FROM SearchDB..paSearchJobID_0 WITH(NOLOCK) WHERE paSearchConditionID=@paSearchConditionID

			SET @MinId = @MinId+(@PageNumber-1)*@PageSize
			SELECT TOP 8 a.ID, a.cpMainID, a.caMainID, a.Name as JobName, a.dcJobTypeID, 
				a.dcJobTypeIDMinor, a.NeedNumber, a.dcSalaryID, a.EmployType, 
				a.dcRegionID, a.Responsibility, a.Demand, a.dcEducationID, 
				a.MinExperience, a.MinAge, a.MaxAge, a.IssueDate, a.IssueEND, 
				a.IsDelete, a.AddDate, a.RefreshDate, 
				a.LastModifyDate, b.Name as cpName, b.dcCompanySizeID, 
				b.HasLicence, b.UnLimitedDate, b.BalanceDate, b.Balance, 
				b.MemberType, STUFF((SELECT ','+LTRIM(x.dcIndustryid)+',c'+LTRIM(isnull(y.Category,0)) 
							FROM cpIndustry x,dcIndustry y WHERE x.dcIndustryid = y.id 
							AND x.cpMainid = b.id FOR XML PATH('')),1,1,'') cpIndustry,
				c.IsTop, b.IsRefreshed, a.SecondId EnJobID, b.SecondId EnCpMainID
			FROM JobPublish a WITH(NOLOCK), cpMainPublish b WITH(NOLOCK), SearchDB..paSearchJobID_0 c WITH(NOLOCK)
			WHERE a.cpMainID = b.ID AND a.id=c.JobID AND c.paSearchConditionID=@paSearchConditionID 
				  AND c.ID>=@MinId ORDER BY c.ID, a.ID DESC
		END
		ELSE IF (@TableID = 1)
		BEGIN
			SELECT @MinId = MIN(ID) FROM SearchDB..paSearchJobID_1 WITH(NOLOCK) WHERE paSearchConditionID=@paSearchConditionID

			SET @MinId = @MinId+(@PageNumber-1)*@PageSize
			SELECT TOP 8 a.ID, a.cpMainID, a.caMainID, a.Name as JobName, a.dcJobTypeID, 
				a.dcJobTypeIDMinor, a.NeedNumber, a.dcSalaryID, a.EmployType, 
				a.dcRegionID, a.Responsibility, a.Demand, a.dcEducationID, 
				a.MinExperience, a.MinAge, a.MaxAge, a.IssueDate, a.IssueEND, 
				a.IsDelete, a.AddDate, a.RefreshDate, 
				a.LastModifyDate, b.Name as cpName, b.dcCompanySizeID, 
				b.HasLicence, b.UnLimitedDate, b.BalanceDate, b.Balance, 
				b.MemberType, STUFF((SELECT ','+LTRIM(x.dcIndustryid)+',c'+LTRIM(isnull(y.Category,0)) 
							FROM cpIndustry x,dcIndustry y WHERE x.dcIndustryid = y.id 
							AND x.cpMainid = b.id FOR XML PATH('')),1,1,'') cpIndustry,
				c.IsTop, b.IsRefreshed, a.SecondId EnJobID, b.SecondId EnCpMainID
			FROM JobPublish a WITH(NOLOCK), cpMainPublish b WITH(NOLOCK), SearchDB..paSearchJobID_1 c WITH(NOLOCK)
			WHERE a.cpMainID = b.ID AND a.id=c.JobID AND c.paSearchConditionID=@paSearchConditionID 
				  AND c.ID>=@MinId ORDER BY c.ID, a.ID DESC
		END
		ELSE IF (@TableID = 2)
		BEGIN
			SELECT @MinId = MIN(ID) FROM SearchDB..paSearchJobID_2 WITH(NOLOCK) WHERE paSearchConditionID=@paSearchConditionID

			SET @MinId = @MinId+(@PageNumber-1)*@PageSize
			SELECT TOP 8 a.ID, a.cpMainID, a.caMainID, a.Name as JobName, a.dcJobTypeID, 
				a.dcJobTypeIDMinor, a.NeedNumber, a.dcSalaryID, a.EmployType, 
				a.dcRegionID, a.Responsibility, a.Demand, a.dcEducationID, 
				a.MinExperience, a.MinAge, a.MaxAge, a.IssueDate, a.IssueEND, 
				a.IsDelete, a.AddDate, a.RefreshDate, 
				a.LastModifyDate, b.Name as cpName, b.dcCompanySizeID, 
				b.HasLicence, b.UnLimitedDate, b.BalanceDate, b.Balance, 
				b.MemberType, STUFF((SELECT ','+LTRIM(x.dcIndustryid)+',c'+LTRIM(isnull(y.Category,0)) 
							FROM cpIndustry x,dcIndustry y WHERE x.dcIndustryid = y.id 
							AND x.cpMainid = b.id FOR XML PATH('')),1,1,'') cpIndustry,
				c.IsTop, b.IsRefreshed, a.SecondId EnJobID, b.SecondId EnCpMainID
			FROM JobPublish a WITH(NOLOCK), cpMainPublish b WITH(NOLOCK), SearchDB..paSearchJobID_2 c WITH(NOLOCK)
			WHERE a.cpMainID = b.ID AND a.id=c.JobID AND c.paSearchConditionID=@paSearchConditionID 
				  AND c.ID>=@MinId ORDER BY c.ID, a.ID DESC
		END
		ELSE IF (@TableID = 3)
		BEGIN
			SELECT @MinId = MIN(ID) FROM SearchDB..paSearchJobID_3 WITH(NOLOCK) WHERE paSearchConditionID=@paSearchConditionID

			SET @MinId = @MinId+(@PageNumber-1)*@PageSize
			SELECT TOP 8 a.ID, a.cpMainID, a.caMainID, a.Name as JobName, a.dcJobTypeID, 
				a.dcJobTypeIDMinor, a.NeedNumber, a.dcSalaryID, a.EmployType, 
				a.dcRegionID, a.Responsibility, a.Demand, a.dcEducationID, 
				a.MinExperience, a.MinAge, a.MaxAge, a.IssueDate, a.IssueEND, 
				a.IsDelete, a.AddDate, a.RefreshDate, 
				a.LastModifyDate, b.Name as cpName, b.dcCompanySizeID, 
				b.HasLicence, b.UnLimitedDate, b.BalanceDate, b.Balance, 
				b.MemberType, STUFF((SELECT ','+LTRIM(x.dcIndustryid)+',c'+LTRIM(isnull(y.Category,0)) 
							FROM cpIndustry x,dcIndustry y WHERE x.dcIndustryid = y.id 
							AND x.cpMainid = b.id FOR XML PATH('')),1,1,'') cpIndustry,
				c.IsTop, b.IsRefreshed, a.SecondId EnJobID, b.SecondId EnCpMainID
			FROM JobPublish a WITH(NOLOCK), cpMainPublish b WITH(NOLOCK), SearchDB..paSearchJobID_3 c WITH(NOLOCK)
			WHERE a.cpMainID = b.ID AND a.id=c.JobID AND c.paSearchConditionID=@paSearchConditionID 
				  AND c.ID>=@MinId ORDER BY c.ID, a.ID DESC
		END
		RETURN
	END
END TRY
BEGIN CATCH
	---检查是否已经建立临时表，已经建立则删除
	PRINT 'error'
	PRINT error_Message()
	PRINT error_number()
	PRINT error_line()
END CATCH








GO
/****** Object:  StoredProcedure [dbo].[paPaRemindLogSelectByIndex]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[paPaRemindLogSelectByIndex]
(
	@paMainID INT
)
AS
BEGIN
	SET NOCOUNT ON
	SELECT TOP 0 * FROM paRemindLog 
--	DECLARE @LastLoginDate SMALLDATETIME
--	SELECT @LastLoginDate = ISNULL(AddDate,GETDATE()) FROM(
--		SELECT TOP 2 AddDate,ROW_NUMBER() OVER(ORDER BY AddDate DESC) row FROM paLoginLog WHERE paMainID = @paMainID
--	) a WHERE row = 2
--	SELECT * FROM paRemindLog WHERE AddDate > ISNULL(@LastLoginDate,GETDATE()) AND PaMainID = @paMainID
	SET NOCOUNT OFF
END
GO
/****** Object:  StoredProcedure [dbo].[paTagsMainByJobTypeSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--根据职位类别获取该职位类别下关键字信息  Peter 2017-1-13
CREATE PROCEDURE [dbo].[paTagsMainByJobTypeSelect] 
(
	@JobType VARCHAR(50)
)
AS
BEGIN
	SELECT TOP 100 Tag
	FROM (
		SELECT DISTINCT Tag
		FROM paTagsMain WITH(NOLOCK)
		WHERE dcJobTypeID IN (
			SELECT a FROM dbo.fnSplit(@JobType, ',')
		)) a
	ORDER BY NEWID()
END


GO
/****** Object:  StoredProcedure [dbo].[paWeixinSave]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[paWeixinSave]
(
	@Content NVARCHAR(50),
	@Lat VARCHAR(20),
	@Lng VARCHAR(20),
	@FromUserName VARCHAR(50)
)
AS
BEGIN TRY
	SET @Content = dbo.SafeSql(@Content)
	DELETE FROM wxMessage WHERE FromUserName=@FromUserName
	IF ISNULL(@Content,'')=''
	BEGIN
		INSERT INTO wxMessage(FromUserName,Lat,Lng,Content) VALUES
			(@FromUserName,@Lat,@Lng,@Content)
	END
	ELSE
	BEGIN
		DECLARE @dcRegionID INT, @KeyWord NVARCHAR(20), @c NVARCHAR(50)
		IF @Content LIKE '% %'
			SET @c = LEFT(@Content, CHARINDEX(' ', @Content) - 1)
		ELSE
			SET @c = @Content
		SELECT TOP 1 @dcRegionID = ID FROM dcRegion WITH(NOLOCK)
		WHERE CHARINDEX(Abbr, @c)>0 
		ORDER BY ID DESC
		IF ISNULL(@dcRegionID,0)=0
			RETURN 0

		SELECT @KeyWord=REPLACE(REPLACE(@Content,MapbarName,''),REPLACE(MapbarName,'市',''),'') FROM dcRegion WITH(NOLOCK) WHERE ID=@dcRegionID
		SELECT @KeyWord=REPLACE(REPLACE(REPLACE(@KeyWord,Description,''),REPLACE(Description,'市',''),''),REPLACE(Description,'区',''),'') FROM dcRegion WITH(NOLOCK) WHERE ID=@dcRegionID
		SELECT @KeyWord=REPLACE(REPLACE(@KeyWord,LEFT(FullName,CHARINDEX('省',FullName)),''),REPLACE(LEFT(FullName,CHARINDEX('省',FullName)),'省',''),'') FROM dcRegion WITH(NOLOCK) WHERE ID=@dcRegionID
		SELECT @KeyWord=REPLACE(@KeyWord,' ','')
		SELECT @KeyWord=REPLACE(@KeyWord,'+','')

		INSERT INTO wxMessage(FromUserName,dcRegionID,KeyWord,Content) VALUES
			(@FromUserName,@dcRegionID,@KeyWord,@Content)
	END
	RETURN 1
END TRY
BEGIN CATCH
	RETURN 0
END CATCH














GO
/****** Object:  StoredProcedure [dbo].[pcAdvantageAnalysisByExJobApplySelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[pcAdvantageAnalysisByExJobApplySelect]
(
	@JobID INT
)
AS
--Lucifer 添加
--2013-11-4 应聘优势分析
BEGIN
	SELECT b.dcSalaryID,COUNT(1) Cnt FROM exJobApply a WITH(NOLOCK),cvMain b WITH(NOLOCK) WHERE a.cvMainID=b.ID
		AND a.JobID=@JobID AND b.dcSalaryID IS NOT NULL GROUP BY b.dcSalaryID

	SELECT b.RelatedWorkYears,COUNT(1) Cnt FROM exJobApply a WITH(NOLOCK),cvMain b WITH(NOLOCK) WHERE a.cvMainID=b.ID
		AND a.JobID=@JobID AND b.RelatedWorkYears IS NOT NULL GROUP BY b.RelatedWorkYears

	SELECT b.Degree,COUNT(1) Cnt FROM exJobApply a WITH(NOLOCK),cvMain b WITH(NOLOCK) WHERE a.cvMainID=b.ID
		AND a.JobID=@JobID AND b.Degree IS NOT NULL GROUP BY b.Degree
END











GO
/****** Object:  StoredProcedure [dbo].[pcbsCvModifySelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.31
--创建人：Nick
--说明：获取简历所有的审核信息
--#####################################################
CREATE PROCEDURE [dbo].[pcbsCvModifySelect]
(
	@PamainID INT,
	@CvMainID INT
)
AS
BEGIN TRY
	SELECT * FROM bsCvModify WITH(NOLOCK) 
	WHERE VerifyInfo Is NOT NULL
	AND paMainID=@PamainID 
	And cvMainID=@CvMainID
	And VerifyInfo<>(Select Top 1 VerifyInfo From bsCvVerify Where cvMainID=@CvMainID
	Order By VerifyDate Desc
	) 
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[pcBsPaStatusInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[pcBsPaStatusInsert]
(
	@paMainID INT,
	@cvMainID INT,
	@StatusID INT,
	@ApplyInfo VARCHAR(400)
)
AS
BEGIN TRY
	DECLARE @MaxID AS INT
	INSERT INTO bsPaStatus (paMainID,cvMainID,StatusID,ApplyInfo) VALUES(@paMainID,@cvMainID,@StatusID,@ApplyInfo)
	SET @MaxID = @@IDENTITY
END TRY
BEGIN CATCH
	GOTO ERR
END CATCH
RETURN @MaxID
ERR:
BEGIN
	RETURN 0
END














GO
/****** Object:  StoredProcedure [dbo].[pcCaCvIntentionBatchDelete]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[pcCaCvIntentionBatchDelete]
(
	@AllID VARCHAR(1000),
	@paMainID INT
)
AS
SET NOCOUNT ON
BEGIN TRAN
	BEGIN TRY
		--生成临时表
		DECLARE @t AS TABLE(
			ID INT
		)
		DECLARE @i INT
		SET @i=CHARINDEX(',',@AllID)
		WHILE @i>=1
		BEGIN
			IF LEFT(@AllID,@i-1) > ''
				INSERT @t VALUES(LEFT(@AllID,@i-1))
			SET @AllID=SUBSTRING(@AllID,@i+1,LEN(@AllID)-@i)
			SET @i=CHARINDEX(',',@AllID)
		END
		IF @AllID > ''
			INSERT @t VALUES(@AllID)

		IF EXISTS(SELECT 'X' FROM caCvIntention a WITH(NOLOCK),@t b,cvMain c WITH(NOLOCK)
			WHERE a.id=b.id AND a.cvMainID=c.ID AND c.paMainID<>@paMainID)
			GOTO Err

		DELETE FROM caCvIntention WHERE CompanyDeleted=1 AND ID IN(SELECT ID FROM @t)
		UPDATE CaCvIntention SET PersonDeleted=1 WHERE ID IN(SELECT ID FROM @t)
		UPDATE CaCvIntention SET Reply=2,ReplyDate=GETDATE() WHERE ID IN(SELECT ID FROM @t) AND PersonDeleted=1
		AND Reply IS NULL
		
	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH
COMMIT TRAN
RETURN 1
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END
GO
/****** Object:  StoredProcedure [dbo].[pcCaCvIntentionByBaiduPushSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--====================================
--创建：	Andy Yin
--获得所有PaMainID简历浏览记录个数，用于给app推送数据。
--====================================
CREATE PROCEDURE [dbo].[pcCaCvIntentionByBaiduPushSelect]
(
	@WHERE VARCHAR(1000)
)
AS
BEGIN
	BEGIN TRY
		SET @WHERE = REPLACE(dbo.SafeSQL(@WHERE), '''', '')
		DECLARE @SQL AS VARCHAR(2000)
		SET @SQL = 'SELECT d.paMainID, count(*) as Count
				FROM caCvIntention a WITH(NOLOCK)
				inner join Job b WITH(NOLOCK) On a.JobID = b.ID 
				inner join cpMain c WITH(NOLOCK) On b.cpMainID = c.ID
				inner join cvMain d WITH(NOLOCK) On a.cvMainID = d.ID
			WHERE PersonDeleted=0'
 
		IF LEN(@WHERE)>0
			SET @SQL = @SQL + ' ' + @WHERE 
		SET @SQL=@SQL + ' GROUP BY d.pamainiD '		
		EXEC(@SQL)
 
	END TRY
	BEGIN CATCH
	END CATCH
END




















GO
/****** Object:  StoredProcedure [dbo].[pcCaCvIntentionSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--lucifer 2018-3-22
CREATE PROCEDURE [dbo].[pcCaCvIntentionSelect]
(
    @WHERE VARCHAR(1000),
    @Order VARCHAR(100)
)
AS
SET NOCOUNT ON
BEGIN
    SET @WHERE = dbo.SafeSQL(@WHERE)
    SET @ORDER = dbo.SafeSQL(@ORDER)
    DECLARE @SQL AS VARCHAR(2000)
    SET @SQL = 'SELECT JobID,cvMainID,a.AddDate,b.Name as JobName,b.IssueDate,b.IssueEnd,Reply,ReplyDate,d.Name cvName,
            b.dcRegionID,b.IsDelete,c.Name as cpName,c.ID as cpID,c.HasLicence, c.IsAgent, c.MemberType,a.ID, 
            b.dcSalaryId, b.dcSalaryIdMax, b.SecondId EnJobID, c.SecondId EnCpMainID,ISNULL((SELECT IsOnline FROM caOnline WHERE caMainId =b.caMainID), 0) AS IsOnline,b.CaMainID,b.Valid JobValid,
            b.Welfare1,b.Welfare2,b.Welfare3,b.Welfare4,b.Welfare5,b.Welfare6,b.Welfare7,b.Welfare8,
            b.Welfare9,b.Welfare10,b.Welfare11,b.Welfare12,b.Welfare13,b.Welfare14,b.Welfare15,b.Welfare16,
            b.Welfare17,b.Welfare18,b.Welfare19,c.ReplyRate, c.LogoFile LogoUrl, e.DescriptionCp SalaryMin, f.DescriptionCp SalaryMax
            FROM caCvIntention a WITH(NOLOCK)
            inner join Job b WITH(NOLOCK) On a.JobID = b.ID 
            inner join cpMain c WITH(NOLOCK) On b.cpMainID = c.ID
            inner join cvMain d WITH(NOLOCK) On a.cvMainID = d.ID
            inner join dcSalary e WITH(NOLOCK) On b.dcSalaryId = e.ID
            inner join dcSalary f WITH(NOLOCK) On b.dcSalaryIdMax = f.ID
        WHERE PersonDeleted=0'

    IF LEN(@WHERE) > 0
        SET @SQL=@SQL + ' ' + @WHERE

    IF LEN(@ORDER) > 0
        SET @SQL=@SQL + ' ORDER BY '+@ORDER

    --PRINT @SQL
    EXEC(@SQL)
END
GO
/****** Object:  StoredProcedure [dbo].[pcCaCvIntentionUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[pcCaCvIntentionUpdate]
(
	@ID INT,
	@Reply TINYINT,
	@paMainID INT
)
AS
BEGIN TRY
	IF NOT EXISTS(SELECT 'x' FROM caCvIntention a WITH(NOLOCK),cvMain b WITH(NOLOCK) WHERE a.id=@ID AND a.cvMainID=b.ID AND b.paMainID=@paMainID)
		GOTO ERR

	UPDATE caCvIntention 
	SET Reply=@Reply,ReplyDate=GETDATE()
	WHERE ID=@ID
	RETURN 1
END TRY
BEGIN CATCH
	GOTO ERR
END CATCH
ERR:
BEGIN
	RETURN 0
END














GO
/****** Object:  StoredProcedure [dbo].[pcCaCvViewLogByBaiduPushSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--====================================
--创建：	Andy Yin
--获得半小时内所有的简历浏览记录个数，按照个人PamainID查找。用于给app推送数据。
--====================================
CREATE PROCEDURE [dbo].[pcCaCvViewLogByBaiduPushSelect]
AS
BEGIN
	SELECT e.paMainID, COUNT(a.camainid) AS Count
	FROM caCvviewLog a WITH(NOLOCK)
	inner join camain b WITH(NOLOCK) on a.camainid=b.id
	inner join cpmain c with(nolock) on c.id=b.cpmainid
	inner join cvmain e WITH(NOLOCK) on a.cvmainid=e.id
	inner join job d with(nolock) on a.camainid=d.camainid
	WHERE a.AddDate>DATEADD(hour,-0.5,GetDate())		--当前日期加一周后的日期()
	Group by e.paMainID
END




GO
/****** Object:  StoredProcedure [dbo].[pcCaCvViewLogSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--====================================
--创建：	lucifer
--检查：	Sean 2010-10-14
--企业浏览记录
--====================================
CREATE PROCEDURE [dbo].[pcCaCvViewLogSelect]
(
	@AllJobID VARCHAR(1000),
	@AllCvMainID VARCHAR(1000),
	@ORDER VARCHAR(200)
)
AS
SET NOCOUNT ON
BEGIN
	SET @AllJobID = dbo.FormatIDS(@AllJobID)
	SET @AllCvMainID = dbo.FormatIDS(@AllCvMainID)
	SET @ORDER = REPLACE(dbo.SafeSQL(@ORDER), '''', '')

	SELECT * ,0 AS IsApply INTO #t FROM caCvviewLog WITH(NOLOCK)
	WHERE cvMainId in(SELECT * FROM dbo.fnSplit(@AllCvMainID, ','))
        
        UPDATE #t SET IsApply=1 
	FROM #t a,exjobapply b, job c,caMain d
	WHERE b.jobid=c.id and a.caMainid = d.id and c.cpMainID=d.cpMainID

	DECLARE @SQL VARCHAR(2000)
	SET @SQL = 'SELECT DISTINCT a.camainid,a.cvmainid,a.adddate,b.Name as caName,
				b.Email,b.Mobile,b.Telephone,b.Gender,b.IsPhoneHide,b.IsNameHide,
				b.IsMobileHide,c.Name as cpName,c.Address,c.ID as cpID,c.HasLicence,
				c.IsAgent,e.Name cvName, c.Membertype, c.dcRegionId, c.SecondId EnCpMainID, c.LogoFile LogoUrl
				from #t a WITH(NOLOCK)
				inner join camain b WITH(NOLOCK) on a.camainid=b.id
				inner join cpmain c with(nolock) on c.id=b.cpmainid
				inner join cvmain e WITH(NOLOCK) on a.cvmainid=e.id'

	IF LEN(@AllJobID) > 0
		SET @SQL = @SQL + ' inner join job d with(nolock) on a.camainid=d.camainid'

	SET @SQL = @SQL + ' WHERE a.cvMainId in(' + @AllCvMainID +')'

	IF LEN(@AllJobID) > 0
		SET @SQL = @SQL + ' AND d.id in(' + @AllJobID +')'

	IF LEN(@ORDER) > 0
		SET @SQL = @SQL + ' ORDER BY ' + @ORDER

	EXEC(@SQL)
END 
SET NOCOUNT OFF
GO
/****** Object:  StoredProcedure [dbo].[pcCaCvViewLogSelect20171218]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[pcCaCvViewLogSelect20171218]
(
	@AllCvMainID VARCHAR(1000),
	@Page SMALLINT
)
AS
SET NOCOUNT ON
BEGIN
	IF @AllCvMainID = ''
		RETURN

	SET @AllCvMainID = dbo.FormatIDS(@AllCvMainID)

	SELECT ROW_NUMBER() OVER(ORDER BY AddDate DESC) TitleID, caMainId, cvMainId, AddDate, NULL JobId ,0 IsApply 
	INTO #1
	FROM caCvviewLog WITH(NOLOCK INDEX(IX_caCvViewLog_cvMainID))
	WHERE cvMainId IN(SELECT a FROM dbo.fnSplit(@AllCvMainID, ','))
	AND EXISTS(SELECT TOP 1 'X' FROM JobPublish WITH(NOLOCK) WHERE caMainID = caCvviewLog.caMainID)

	SELECT * INTO #T
	FROM #1
	WHERE TitleID > (@Page - 1) * 20 AND TitleID <= @Page * 20

--	SELECT * INTO #T FROM (
--		SELECT ROW_NUMBER() OVER(ORDER BY AddDate DESC) TitleID, caMainId, cvMainId, AddDate, NULL JobId ,0 IsApply 
--		FROM caCvviewLog WITH(NOLOCK INDEX(IX_caCvViewLog_cvMainID))
--		WHERE cvMainId IN(SELECT a FROM dbo.fnSplit(@AllCvMainID, ','))
--		AND EXISTS(SELECT TOP 1 'X' FROM JobPublish WITH(NOLOCK) WHERE caMainID = caCvviewLog.caMainID)
--	) a WHERE TitleID > (@Page - 1) * 20 AND TitleID <= @Page * 20
        
    UPDATE #T SET IsApply = 1
    WHERE EXISTS(
		SELECT TOP 1 'X' FROM exJobApply a WITH(NOLOCK), JobPublish b WITH(NOLOCK)
		WHERE a.JobID = b.ID AND a.cvMainID = #T.cvMainID AND b.caMainID = #T.caMainID
	)

	UPDATE #T SET JobId = (SELECT TOP 1 a.ID FROM JobPublish a WITH(NOLOCK), caMain b WITH(NOLOCK), cpMainPublish c WITH(NOLOCK)
	WHERE a.cpMainId = b.cpMainID AND b.cpMainID = c.ID AND a.dcJobTypeId IN(SELECT dcJobTypeID FROM cvJobType WITH(NOLOCK) WHERE cvMainId = #T.cvMainId)
		AND b.Id = #T.caMainID ORDER BY a.RefreshDate DESC)
		
	UPDATE #T SET JobId = (SELECT TOP 1 a.ID FROM JobPublish a WITH(NOLOCK), caMain b WITH(NOLOCK), cpMainPublish c WITH(NOLOCK)
	WHERE a.cpMainId = b.cpMainID AND b.cpMainID = c.ID AND LEFT(a.dcJobTypeId, 2) IN(SELECT dcJobTypeID FROM cvJobType WITH(NOLOCK) WHERE cvMainId = #T.cvMainId)
		AND b.Id = #T.caMainID ORDER BY a.RefreshDate DESC) WHERE JobId IS NULL
	
	UPDATE #T SET JobId = (SELECT TOP 1 a.ID FROM JobPublish a WITH(NOLOCK), caMain b WITH(NOLOCK), cpMainPublish c WITH(NOLOCK)
	WHERE a.cpMainId = b.cpMainID AND b.cpMainID = c.ID
		AND b.Id = #T.caMainID ORDER BY a.RefreshDate DESC) WHERE JobId IS NULL
	
	SELECT a.caMainId,a.cvMainId,a.AddDate adddate,b.Name as caName,d.Id jobId,d.Name jobName,
		d.SecondId EnJobId,d.NeedNumber,d.dcSalaryID, d.dcSalaryIDMax,
		b.Email,b.Mobile,b.Telephone,b.Gender,b.IsPhoneHide,b.IsNameHide,b.IsMobileHide,
		c.Name as cpName,c.Address,c.ID as cpID,c.HasLicence,c.IsAgent,e.Name cvName,
		c.Membertype, c.dcRegionId, c.SecondId EnCpMainID, c.LogoFile LogoUrl
	FROM #T a WITH(NOLOCK)
	INNER JOIN caMain b WITH(NOLOCK) ON a.caMainID = b.ID
	INNER JOIN cpMain c WITH(NOLOCK) ON c.ID = b.cpMainId
	INNER JOIN cvMain e WITH(NOLOCK) ON a.cvMainId = e.Id
	INNER JOIN JobPublish d WITH(NOLOCK) ON a.JobId = d.Id
	
	SELECT COUNT(1)
	FROM #1
END 
SET NOCOUNT OFF
GO
/****** Object:  StoredProcedure [dbo].[pcCaCvViewLogSelectBak]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--====================================
--创建：	lucifer
--检查：	Sean 2010-10-14
--企业浏览记录
--====================================
CREATE PROCEDURE [dbo].[pcCaCvViewLogSelectBak]
(
	@AllJobID VARCHAR(1000),
	@AllCvMainID VARCHAR(1000),
	@ORDER VARCHAR(200)
)
AS
BEGIN
	SET @AllJobID = dbo.FormatIDS(@AllJobID)
	SET @AllCvMainID = dbo.FormatIDS(@AllCvMainID)
	SET @ORDER = REPLACE(dbo.SafeSQL(@ORDER), '''', '')

	DECLARE @SQL VARCHAR(2000)
	SET @SQL='SELECT DISTINCT a.camainid,a.cvmainid,a.adddate,b.Name as caName,
				b.Email,b.Mobile,b.Telephone,b.Gender,b.IsPhoneHide,b.IsNameHide,
				b.IsMobileHide,c.Name as cpName,c.Address,c.ID as cpID,c.HasLicence,
				c.IsAgent,e.Name cvName, c.Membertype
				from cacvviewlog a WITH(NOLOCK)
				inner join camain b WITH(NOLOCK) on a.camainid=b.id
				inner join cpmain c with(nolock) on c.id=b.cpmainid
				inner join cvmain e WITH(NOLOCK) on a.cvmainid=e.id'

	IF LEN(@AllJobID)>0
		SET @SQL=@SQL+' inner join job d with(nolock) on a.camainid=d.camainid'

	SET @SQL=@SQL+' WHERE a.cvMainId in(' + @AllCvMainID +')'

	IF LEN(@AllJobID)>0
		SET @SQL=@SQL+' AND d.id in(' + @AllJobID +')'

	IF LEN(@ORDER)>0
		SET @SQL=@SQL+' ORDER BY '+@ORDER

	EXEC(@SQL)
END














GO
/****** Object:  StoredProcedure [dbo].[PcCaMainByIsShowEmailContactSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [dbo].[PcCaMainByIsShowEmailContactSelect]
(
	@JobId INT
)
AS
BEGIN
	SELECT 'x' FROM caMain WHERE id IN(SELECT caMainId FROM Job WHERE Id = @JobId) AND IsShowEmailContact = 1
END


GO
/****** Object:  StoredProcedure [dbo].[pcCaPlaintByIDSelect_old]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--============
--应该没有用了
--============
CREATE PROCEDURE [dbo].[pcCaPlaintByIDSelect_old]
(
    @ID INT
)
AS
BEGIN
    SELECT *
    FROM CaPlaint WITH(NOLOCK)
    WHERE ID = @ID
END














GO
/****** Object:  StoredProcedure [dbo].[pccaplaintIsViewedUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--========================================
--asp中取所有IsViewed = false的id
--检查  sean	2010-10-10
--========================================
CREATE PROCEDURE [dbo].[pccaplaintIsViewedUpdate]
(
    @AllID VARCHAR(200)
)
AS
BEGIN TRY
	SET @AllID = dbo.FormatIDS(@AllID)

	DECLARE @T AS TABLE(ID INT)
	INSERT INTO @T SELECT * FROM dbo.fnSplit(@AllID, ',')
	UPDATE caplaint SET IsViewed=1 WHERE ID IN(SELECT ID FROM @T)
    RETURN 1
END TRY
BEGIN CATCH
    RETURN 0
END CATCH














GO
/****** Object:  StoredProcedure [dbo].[pcCaPlaintNoViewSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--========================================
--asp中取所有IsViewed = false的id
--检查  sean	2010-10-10
--个人首页用，未查看的企业投诉
--========================================
CREATE PROCEDURE [dbo].[pcCaPlaintNoViewSelect]
(
    @PaMainID INT
)
AS
BEGIN
    SELECT a.*
    FROM CaPlaint a WITH(NOLOCK INDEX(IX_caPlaint_cvMainID)), cvMain b WITH(NOLOCK INDEX(IX_cvMain_paMainID)), caMain c WITH(NOLOCK)
    WHERE a.cvMainID = b.ID
	AND b.PaMainID = @PaMainID
	AND a.caMainID = c.ID
	AND c.IsDelete = 0
	AND a.IsViewed = 0
	AND a.ReplyType = 1
	ORDER BY a.ID DESC
END














GO
/****** Object:  StoredProcedure [dbo].[pcCaPlaintSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[pcCaPlaintSelect]
(
    @PaMainID INT
)
AS
BEGIN
    SELECT a.*,d.ID cpMainID ,d.name CompanyName
    FROM CaPlaint a WITH(NOLOCK INDEX(IX_caPlaint_cvMainID))
	INNER JOIN cvMain b WITH(NOLOCK INDEX(IX_cvMain_paMainID))
		ON a.cvMainID = b.ID
	LEFT JOIN caMain c WITH(NOLOCK)
		ON a.caMainID = c.ID
	LEFT JOIN cpMain d WITH(NOLOCK)
		ON c.cpMainID = d.ID
    WHERE  b.PaMainID = @PaMainID
	AND (c.IsDelete = 0 OR c.IsDelete IS NULL)
	AND a.ReplyType = 1
	ORDER BY a.ID DESC
END














GO
/****** Object:  StoredProcedure [dbo].[pcChatOnLineByPaMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[pcChatOnLineByPaMainIDSelect]
(
    @PaMainID INT	--求职者的ID
)
AS
SET NOCOUNT ON
--INSERT INTO procLog SELECT 'pcChatOnLineByPaMainIDSelect', @PaMainID, GETDATE()
BEGIN
	CREATE TABLE #UserList
	(
		ChatOnlineID INT,
		CaMainID INT,
		CvMainID INT,
		EndDate SMALLDATETIME,
		LastChatDate SMALLDATETIME,
		SumUnRead INT,
		IsHidden BIT	
	)

	UPDATE ChatOnline
	SET paUnViewed = 0
	WHERE paUnViewed > 0
		AND cvMainId IN(SELECT ID FROM cvMain WHERE paMainId = @PaMainId)
	UPDATE a
	SET a.paUnViewed = b.Cnt
	FROM ChatOnline a, (
		SELECT MAX(a.ID) Id, COUNT(*) Cnt
		FROM ChatOnline a, ChatOnlineLog b
		WHERE a.id = b.ChatOnlineID
		AND b.IsViewed = 0
		AND b.SenderType <> 2 --不是个人发送的
		AND a.cvMainId IN(SELECT ID FROM cvMain WHERE paMainId = @PaMainId)
		GROUP BY a.CaMainId, a.CvMainID
		) b
	WHERE a.Id = b.Id
	--个人的联系人列表，有留言的
	INSERT INTO #UserList
	SELECT MAX(ID), CaMainID, CvMainID, MAX(EndDate), MAX(StartDate), SUM(paUnViewed), 0
	FROM ChatOnline
	WHERE cvMainId IN(SELECT ID FROM cvMain WHERE paMainId = @PaMainId) --当前个人
	AND (paUnViewed > 0 OR StartDate > GETDATE() - 15)
	GROUP BY CaMainID, cvMainId

	--个人联系列表，15之外曾有联系的，隐藏不显示
	INSERT INTO #UserList
	SELECT MAX(ID), CaMainID, CvMainID, MAX(EndDate), MAX(StartDate), 0, 1
	FROM ChatOnline
	WHERE cvMainId IN (SELECT ID FROM CvMain WHERE PaMainID = @PaMainID) --当前个人用户
	AND CaMainID NOT IN(SELECT CaMainID FROM #UserList)
	GROUP BY caMainId, CvMainID

	SELECT a.*, b.Name CpName, b.SecondID, c.Name UserName,
		c.cpMainID, ISNULL(d.IsOnline, 0) IsOnline
	FROM #UserList a
	INNER JOIN caMain c ON a.caMainID = c.ID
	INNER JOIN cpMain b ON b.ID = c.cpMainID
	LEFT JOIN caOnline d ON c.Id = d.caMainId
	ORDER BY a.LastChatDate DESC
	
	DROP TABLE #UserList
END


GO
/****** Object:  StoredProcedure [dbo].[pcChatOnLineListByCaMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----创建人：Nick
-----创建时间：2014-9-9
-----用途：根据企业用户ID获取聊天列表
CREATE PROCEDURE [dbo].[pcChatOnLineListByCaMainIDSelect]
(
    @CaMainID INT	--企业用户ID
)
AS
--INSERT INTO procLog SELECT 'pcChatOnLineListByCaMainIDSelect', @caMainID, GETDATE()
BEGIN
	DECLARE @ChatList1 AS TABLE
	(
		CvMainID INT,
		CaMainID INT,
		ManagerUserID SMALLINT,
		Name VARCHAR(100),
		Message NVARCHAR(200),
		SendDate DATETIME,
		NoViewedNum INT,
		OnlineStatus INT,
		Photo VARCHAR(50),
		OpenName INT
	)
	DECLARE @ChatList2 AS TABLE
	(
		CvMainID INT,
		CaMainID INT,
		ManagerUserID SMALLINT,
		Name VARCHAR(100),
		Message NVARCHAR(200),
		SendDate DATETIME,
		NoViewedNum INT,
		OnlineStatus INT,
		Photo VARCHAR(50),
		HasPhoto INT
	)
	--客服或顾问聊天列表
	INSERT INTO @ChatList1(CvMainID,CaMainID,ManagerUserID,Name,OnlineStatus)
	SELECT DISTINCT a.cvMainID,a.caMainID ,a.ManagerUserID,'客服' as Name,0
	FROM ChatOnline a
	WHERE a.caMainID = @CaMainID
	AND (a.AddDate > GETDATE() - 15 OR ID IN (
		SELECT ChatOnlineID FROM ChatOnlineLog WHERE IsViewed = 0 ))
	AND (a.cvMainID IS NULL or a.cvMainID = 0)
		
	UPDATE a SET 
		Message = (
			SELECT TOP 1 MESSAGE 
			FROM ChatOnlineLog 
			WHERE ChatOnlineID IN (SELECT ID FROM CHATONLINE WHERE CaMainID = a.CaMainID AND ManagerUserID = a.ManagerUserID)
			Order BY AddDate DESC
		),
		SendDate = (
			SELECT TOP 1 AddDate 
			FROM ChatOnlineLog 
			WHERE ChatOnlineID IN (SELECT ID FROM CHATONLINE WHERE CaMainID = a.CaMainID AND ManagerUserID = a.ManagerUserID)
			Order BY AddDate DESC),
		NoViewedNum = (
			SELECT COUNT(*) 
			FROM ChatOnlineLog 
			WHERE ChatOnlineID IN (SELECT ID FROM CHATONLINE WHERE CaMainID = a.CaMainID AND ManagerUserID = a.ManagerUserID)
			AND IsViewed = 0
		),
		Photo = (
			SELECT TOP 1 Photo FROM ManagerUser WHERE ID = a.ManagerUserID
		),
		OnlineStatus = (
			SELECT TOP 1 SOLStatus FROM ManagerUser WHERE ID = a.ManagerUserID
		),
		OpenName = (
			SELECT TOP 1 OpenName FROM ManagerUser WHERE ID = a.ManagerUserID
		)
	FROM @ChatList1 a
	
	UPDATE @ChatList1 SET Photo = '' WHERE OpenName <> 1
		
	--跟个人聊天列表
	INSERT INTO @ChatList2(CvMainID,CaMainID,ManagerUserID,Name,OnlineStatus)
	SELECT DISTINCT a.cvMainID,a.caMainID ,a.ManagerUserID,c.Name,dbo.GetPaOnlineStatus(c.ID)
	FROM ChatOnline a , cvMain b,PaMain c
	WHERE a.caMainID = @CaMainID
	AND a.cvMainID = b.ID
	AND b.PaMainID = c.ID
	AND (a.AddDate > GETDATE() - 15 OR a.ID IN (
		SELECT ChatOnlineID FROM ChatOnlineLog WHERE IsViewed = 0 AND SenderType = 2))
	AND (a.ManagerUserID IS NULL or a.ManagerUserID = 0)
	
	UPDATE a SET 
		Message = (
			SELECT TOP 1 MESSAGE 
			FROM ChatOnlineLog 
			WHERE ChatOnlineID IN (SELECT ID FROM CHATONLINE WHERE CvMainID = a.CvMainID AND CaMainID = a.CaMainID)
			Order BY AddDate DESC
		),
		SendDate = (
			SELECT TOP 1 AddDate 
			FROM ChatOnlineLog 
			WHERE ChatOnlineID IN (SELECT ID FROM CHATONLINE WHERE CvMainID = a.CvMainID AND CaMainID = a.CaMainID)
			Order BY AddDate DESC),
		NoViewedNum = (
			SELECT COUNT(*) 
			FROM ChatOnlineLog 
			WHERE ChatOnlineID IN (SELECT ID FROM CHATONLINE WHERE CvMainID = a.CvMainID AND CaMainID = a.CaMainID)
			AND IsViewed = 0
			AND SenderType = 2
		),
		Photo = (
			SELECT PhotoProcessed FROM paPhoto WHERE paMainID = (
				SELECT PaMainID FROM CvMain WHERE ID = a.CvMainID
			)
		),
		HasPhoto = (
			SELECT HasPhoto FROM paMain WHERE ID = (
				SELECT PaMainID FROM CvMain WHERE ID = a.CvMainID
			)
		)
	FROM @ChatList2 a
	
	SELECT * FROM @ChatList1 
	SELECT * FROM @ChatList2
END




GO
/****** Object:  StoredProcedure [dbo].[pcChatOnLineListByPaMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =  = 
--修改人：	Nick
--修改日期：2014-10-09
--修改内容：未查看消息数量问题
-- = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =  = 

CREATE PROCEDURE [dbo].[pcChatOnLineListByPaMainIDSelect]
(
    @PaMainID INT	--求职者的ID
)
AS
--INSERT INTO procLog SELECT 'pcChatOnlineListByPaMainIDSelect', @PaMainID, GETDATE()
BEGIN
	CREATE TABLE #ChatList1
	(
		CvMainID INT,
		CaMainID INT,
		ManagerUserID SMALLINT,
		Name VARCHAR(100),
		Message NVARCHAR(200),
		SendDate DATETIME,
		NoViewedNum INT,
		OnlineStatus INT,
		LogoUrl VARCHAR(300)
	)
	CREATE TABLE #ChatList2
	(
		CvMainID INT,
		CaMainID INT,
		ManagerUserID SMALLINT,
		Name VARCHAR(100),
		Message NVARCHAR(200),
		SendDate DATETIME,
		NoViewedNum INT,
		OnlineStatus INT,
		LogoUrl VARCHAR(300)
	)
	--客服聊天列表
	INSERT INTO #ChatList1(CvMainID, CaMainID, ManagerUserID, Name, OnlineStatus, LogoUrl)
	SELECT DISTINCT a.cvMainID, a.caMainID, a.ManagerUserID, '客服' as Name, 0, ''
	FROM ChatOnline a, caMain b
	WHERE a.caMainID = b.ID AND a.cvMainID In (SELECT ID FROM CVMAIN WHERE PaMainID = @PaMainID)
	AND (a.AddDate > GETDATE() - 15 OR a.ID IN (
		SELECT ChatOnlineID FROM ChatOnlineLog WHERE IsViewed = 0 ))
	AND (a.caMainID IS NULL or a.caMainID = 0)
		
	UPDATE a SET 
		Message = (
			SELECT TOP 1 MESSAGE 
			FROM ChatOnlinelog 
			WHERE ChatOnlineID IN (SELECT ID FROM ChatOnline WHERE CvMainID = a.CvMainID AND ManagerUserID = a.ManagerUserID)
			Order BY AddDate DESC
		),
		SendDate = (
			SELECT TOP 1 AddDate 
			FROM ChatOnlinelog 
			WHERE ChatOnlineID IN (SELECT ID FROM ChatOnline WHERE CvMainID = a.CvMainID AND ManagerUserID = a.ManagerUserID)
			Order BY AddDate DESC),
		NoViewedNum = (
			SELECT COUNT(*) 
			FROM ChatOnlinelog 
			WHERE ChatOnlineID IN (SELECT ID FROM ChatOnline WHERE CvMainID = a.CvMainID AND ManagerUserID = a.ManagerUserID)
			AND IsViewed = 0
			AND SenderType = 3
		)
	FROM #ChatList1 a
		
	--跟企业聊天列表
	INSERT INTO #ChatList2(CvMainID, CaMainID, ManagerUserID, Name, OnlineStatus, LogoUrl)
	SELECT DISTINCT a.cvMainID, a.caMainID, a.ManagerUserID, c.Name, dbo.GetCaOnlineStatus(a.caMainID), c.LogoFile
	FROM ChatOnline a, caMain b, CpMain c
	WHERE a.cvMainID In (SELECT ID FROM CVMAIN WHERE PaMainID = @PaMainID)
	AND a.caMainID = b.ID
	AND b.CpMainID = c.ID
	AND (a.AddDate > GETDATE() - 15 OR a.ID IN (
		SELECT ChatOnlineID FROM ChatOnlineLog WHERE IsViewed = 0 ))
	AND (a.ManagerUserID IS NULL or a.ManagerUserID = 0)
	
	UPDATE a SET 
		Message = (
			SELECT TOP 1 MESSAGE 
			FROM ChatOnlinelog 
			WHERE ChatOnlineID IN (SELECT ID FROM ChatOnline WHERE CvMainID = a.CvMainID AND CaMainID = a.CaMainID)
			Order BY AddDate DESC
		),
		SendDate = (
			SELECT TOP 1 AddDate 
			FROM ChatOnlinelog 
			WHERE ChatOnlineID IN (SELECT ID FROM ChatOnline WHERE CvMainID = a.CvMainID AND CaMainID = a.CaMainID)
			Order BY AddDate DESC),
		NoViewedNum = (
			SELECT COUNT(*) 
			FROM ChatOnlinelog 
			WHERE ChatOnlineID IN (SELECT ID FROM ChatOnline WHERE CvMainID = a.CvMainID AND CaMainID = a.CaMainID)
			AND IsViewed = 0
			AND SenderType = 1
		)
	FROM #ChatList2 a

	SELECT * FROM #ChatList1 UNION SELECT * FROM #ChatList2
END
GO
/****** Object:  StoredProcedure [dbo].[PcChatOnlineLogByPaMainIdForServiceSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [dbo].[PcChatOnlineLogByPaMainIdForServiceSelect]
(
	@Id INT
)
AS
BEGIN
	SELECT b.AddDate, a.ManagerUserID, b.Message, c.Name AS ManagerUserName, e.Name AS PaName, b.senderType
	FROM ChatOnline a, ChatOnlineLog b, ManagerUser c, cvMain d, paMain e 
	WHERE a.ID = b.ChatOnlineID AND a.cvMainID=d.ID AND d.paMainID=e.ID AND a.ManagerUserID=c.ID
	AND e.ID = @Id 
	AND ManagerUserID != 0 
	ORDER BY b.AddDate 
END
GO
/****** Object:  StoredProcedure [dbo].[pcChatOnLineLogByPaMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[pcChatOnLineLogByPaMainIDSelect]
(
    @PaMainID INT	--求职者的ID
)
AS
SET NOCOUNT ON
--INSERT INTO procLog SELECT 'pcChatOnLineLogByPaMainIDSelect', @PaMainID, GETDATE()
BEGIN	
	CREATE TABLE #ChatLog
	(
		CaMainID INT,
		CvMainID INT,
		LastMessage VARCHAR(MAX),
		LastReceiverDate SMALLDATETIME,
		Initiative TINYINT
	)
	INSERT INTO #ChatLog
	SELECT 
		a.CaMainID,
		a.CvMainID,
		(SELECT TOP 1 Message FROM ChatOnlineLog WHERE ChatOnlineID = MAX(a.ID) ORDER BY AddDate DESC),
		MAX(b.Adddate),
		(SELECT Initiative FROM ChatOnline WHERE ID = MIN(a.ID))
	FROM ChatOnline a, ChatOnlineLog b
	WHERE a.id = b.ChatOnlineID
		AND a.cvMainId IN (SELECT ID FROM CvMain WHERE PaMainID = @PaMainID) --当前个人用户
	GROUP BY a.CaMainID,a.CvMainID

	SELECT
		a.*,
		dbo.GetCaName(b.ID) CaName,
		c.Name CpName,
		d.Name CvName,
		c.SecondID EnCpMainID,
		c.HasLicence,
		c.MemberType,
		c.IsAgent,
		Initiative
	FROM #ChatLog a,caMain b,cpMain c,cvMain d
	WHERE a.caMainID = b.id AND b.cpMainID = c.ID AND a.cvMainID = d.ID
	ORDER BY LastReceiverDate DESC
END

GO
/****** Object:  StoredProcedure [dbo].[pcChatOnlineSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[pcChatOnlineSelect]
(
    @caMainId INT,
    @paMainId INT
)
AS
SET NOCOUNT ON
BEGIN
    CREATE TABLE #ChatList
	(
		cvMainID INT,
		caMainID INT,
		[Name] VARCHAR(100),
		NoViewedNum INT,
		OnlineStatus INT,
		paMainId INT,
		SecondId VARCHAR(10)
	)
    IF @paMainId > 0
    BEGIN
		DELETE FROM ChatOnlineExchange WHERE UserID = @paMainId AND UserType = 2
        INSERT INTO #ChatList(cvMainID, caMainID, OnlineStatus)
        SELECT TOP 100 cvMainID, caMainID, dbo.GetCaOnlineStatus(caMainID)
        FROM ChatOnline WITH(NOLOCK)
        WHERE caMainID > 0 AND cvMainID IN(
            SELECT ID FROM cvMain WITH(NOLOCK) WHERE paMainID = @paMainId
        )
        ORDER BY AddDate DESC

        UPDATE #ChatList SET NoViewedNum = (
            SELECT COUNT(1)
			FROM ChatOnlineLog WITH(NOLOCK)
			WHERE ChatOnlineID IN (
                SELECT ID FROM ChatOnline WITH(NOLOCK)
                WHERE cvMainID = #ChatList.cvMainID AND caMainID = #ChatList.caMainID
            )
			AND IsViewed = 0 AND SenderType = 1 AND MessageType NOT IN(6, 7)
        )
        UPDATE a SET a.[Name] = c.[Name] + ' ' + b.[Name]
        FROM #ChatList a, cpMain b WITH(NOLOCK), caMain c WITH(NOLOCK)
        WHERE b.ID = c.cpMainID AND c.ID = a.caMainID
    END
    ELSE IF @caMainID > 0
    BEGIN
		DELETE FROM ChatOnlineExchange WHERE UserID = @caMainID AND UserType = 1
        INSERT INTO #ChatList(cvMainID, caMainID)
        SELECT TOP 100 cvMainID, caMainID
        FROM ChatOnline
        WHERE caMainID = @caMainId AND cvMainID > 0
        ORDER BY AddDate DESC

        UPDATE #ChatList SET NoViewedNum = (
            SELECT COUNT(1)
			FROM ChatOnlineLog WITH(NOLOCK)
			WHERE ChatOnlineID IN (
                SELECT ID FROM ChatOnline WITH(NOLOCK)
                WHERE cvMainID = #ChatList.cvMainID AND caMainID = #ChatList.caMainID
            )
			AND IsViewed = 0 AND SenderType = 2 AND MessageType NOT IN(6, 7)
        )
        UPDATE #ChatList SET OnlineStatus = (
            SELECT TOP 1 dbo.GetPaOnlineStatus(paMainID)
            FROM cvMain WITH(NOLOCK)
            WHERE ID = #ChatList.cvMainID
        )
        UPDATE #ChatList SET [Name] = (
            SELECT TOP 1 dbo.GetPaName(#ChatList.cvMainId, cpMainId)
            FROM caMain WITH(NOLOCK)
            WHERE ID = #ChatList.caMainId
        )
		UPDATE a SET a.paMainId = b.paMainId, a.SecondId = b.SecondId FROM #ChatList a, cvMain b WHERE a.cvMainId = b.Id
    END
    SELECT * FROM #ChatList
END


GO
/****** Object:  StoredProcedure [dbo].[pcChatOnLineStatusUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----创建人：Nick
-----创建时间：2014-9-11
-----用途：用于修改个人或企业的在线状态
CREATE PROCEDURE [dbo].[pcChatOnLineStatusUpdate]
(
    @CaMainID INT,	--企业用户ID
    @PaMainID INT   --个人用户ID
)
AS
SET NOCOUNT ON
--INSERT INTO _1 SELECT @caMainID, @paMainId, GETDATE()
BEGIN
	IF(@CaMainID !=0)  --修改企业用户在线状态
	BEGIN
		IF NOT EXISTS(SELECT 'x' FROM caOnline WITH(NOLOCK)
						WHERE caMainID = @CaMainID)
			INSERT INTO caOnline (CaMainID,IsOnline,IsVi,RefreshDate)
			VALUES (@CaMainID,1,0,GETDATE())
		ELSE
			UPDATE caOnline SET RefreshDate=GETDATE(),IsOnline=1 where caMainID=@caMainID
	END
	ELSE				--修改个人用户在线状态
	BEGIN
		IF NOT EXISTS(SELECT 'x' FROM paOnline WITH(NOLOCK)
						WHERE paMainID = @PaMainID)
			INSERT INTO paOnline (paMainID,IsOnline,RefreshDate)
			VALUES (@PaMainID,1,GETDATE())
		ELSE
			UPDATE paOnline SET RefreshDate=GETDATE(),IsOnline=1 where PaMainID=@PaMainID
	END
END





GO
/****** Object:  StoredProcedure [dbo].[pccpImageSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--=============================================
CREATE PROCEDURE [dbo].[pccpImageSelect]
	@cpMainID INT
AS
BEGIN
SET NOCOUNT ON
	SELECT a.*,b.HasLogo 
	FROM cpImage a WITH(NOLOCK ),cpMain b with(NOLOCK) 
	WHERE a.cpMainID= b.ID and a.ImgType=1 AND a.cpMainID=@cpMainID
SET NOCOUNT OFF
END

GO
/****** Object:  StoredProcedure [dbo].[pcCpMainBycaMainIdSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/**********************8
sean 2014-10-29
***********************/
CREATE PROCEDURE [dbo].[pcCpMainBycaMainIdSelect]
(
	@caMainID INT
)
AS
--INSERT INTO procLog SELECT 'pcCpMainBycaMainIdSelect', @caMainID, GETDATE()
BEGIN
	SELECT a.ID, a.Name ShowName, a.SecondID ShowID, dbo.GetCaName(b.ID) UserName, a.RegDate, 
		ISNULL((SELECT IsOnline FROM caOnline WITH(NOLOCK) WHERE caMainId = @caMainID), 0) IsOnline 
	FROM cpMain a, caMain b 
	WHERE a.ID = b.cpMainID 
	AND b.ID = @caMainID
END

GO
/****** Object:  StoredProcedure [dbo].[pcCpMainByNameSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[pcCpMainByNameSelect] 
(
	@Name VARCHAR(25)
)
AS
--INSERT INTO procLog SELECT 'pcCpMainByNameSelect', @Name, GETDATE()
BEGIN
	DECLARE @t AS TABLE(ID INT,	
		SecondId VARCHAR(12),
		ProvinceName NVARCHAR(10),
		Name NVARCHAR(50)
	)

	INSERT INTO @t
	SELECT TOP 50 a.ID, a.SecondId, 
		(SELECT ProvinceName
		FROM dcProvince WITH(NOLOCK)
		WHERE dcProvince.ID = LEFT(a.dcRegionID, 2)) ProvinceName, 
		a.Name
	FROM cpMainPublish a WITH(NOLOCK),
		CONTAINSTABLE(cpMainPublish, Name, @Name, 100) AS b
	WHERE a.Id = b.[Key]

	IF NOT EXISTS(SELECT 'x' FROM @t)
	BEGIN
		INSERT @t	
		SELECT TOP 50 ID,SecondId, 
			(SELECT ProvinceName
			FROM dcProvince WITH(NOLOCK)
			WHERE dcProvince.ID = LEFT(cpMainPublish.dcRegionID, 2)) ProvinceName, 
			Name
		FROM cpMainPublish WITH(NOLOCK INDEX(IX_cpMainPublish_Name))
		WHERE Name LIKE @Name + '%'
		ORDER BY RefreshDate DESC	
	END

	SELECT * FROM @t
	/*
	IF (@Name LIKE '%公司%' AND LEN(@Name) > 6) OR LEN(@Name) > 10
	BEGIN
		SELECT TOP 50 ID,SecondId, 
			(SELECT ProvinceName
			FROM dcProvince WITH(NOLOCK)
			WHERE dcProvince.ID = cpMain.dcProvinceID)
			ProvinceName, 
			Name
		FROM cpMain WITH(NOLOCK INDEX(IX_cpmain_Name))
		WHERE Name LIKE @Name + '%'
		ORDER BY RefreshDate DESC	
	END
	ELSE
	BEGIN
		SELECT TOP 50 ID, SecondId, 
			(SELECT ProvinceName
			FROM dcProvince WITH(NOLOCK)
			WHERE dcProvince.ID = cpMain.dcProvinceID) ProvinceName,
			Name
		FROM cpMain WITH(NOLOCK)
		WHERE Name LIKE '%' + @Name + '%'
		ORDER BY RefreshDate DESC
	END
	*/
END


GO
/****** Object:  StoredProcedure [dbo].[pcCvAppendixByIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--=============================================
-- 创建：		sean
-- 检查：		2010-9-27
-- 说明：		取消各字段，改为*
--=============================================
CREATE PROCEDURE [dbo].[pcCvAppendixByIDSelect]
	@ID INT
AS
BEGIN
	SELECT *
	FROM CvAppendix WITH(NOLOCK INDEX(PK_cvAppendix))
	WHERE ID = @ID
END














GO
/****** Object:  StoredProcedure [dbo].[pcCvAppendixDelete]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--=============================================
-- 创建：		sean
-- 检查：		2010-9-27
-- 说明：		取消pcCvMainByCvLevelUpdate,取消pcCvMainVerifyResultCheck
-- 修改：Lambo，2010-11-25
-- 描述：增加了paMainID参数，判断是否是本人的
--=============================================
CREATE PROCEDURE [dbo].[pcCvAppendixDelete]
	@ID INT,
	@paMainID INT
AS
BEGIN TRAN
	BEGIN TRY
		DECLARE @cvMainID AS INT
		DECLARE @RETURN AS VARCHAR(2)

		SELECT @cvMainID = cvMainID FROM CvAppendix WITH(NOLOCK) WHERE ID = @ID
		
		IF @cvMainID IS NULL
			GOTO ERR

		IF NOT EXISTS(SELECT 'x' FROM cvMain WITH(NOLOCK)
						WHERE ID = @cvMainID AND paMainID = @paMainID)
			GOTO ERR

		DELETE FROM bsCvModify WHERE SubID = @ID AND Location LIKE 'c%'
		DELETE FROM CvAppendix WHERE ID=@ID
		EXEC @RETURN = pcCvMainByCvLevelCheck @cvMainID, 10
	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH
COMMIT TRAN
RETURN @RETURN
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 3
END














GO
/****** Object:  StoredProcedure [dbo].[pcCvAppendixSave]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = 
-- 创建：		Sean
-- 检查：		2010-9-27 未完成，原先隐藏了对bsCvModify的操作
-- 修改：Lambo，2010-11-25
-- 描述：增加了paMainID参数，判断是否是本人的
-- 修改：harry 重复证书 增加描述时间判断是否重复 2018-1-4
-- = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = 
CREATE PROCEDURE [dbo].[pcCvAppendixSave]
(
	@Type INT,
	@ID INT,
	@cvMainID INT,
	@dcAppendixID SMALLINT,
	@Name VARCHAR(250),
	@Description VARCHAR(1000),
	@AccessDate SMALLINT,
	@paMainID INT
)
AS
SET NOCOUNT ON
IF CHARINDEX('<', @Name) > 0
	SET @Name = REPLACE(@Name, '<', '')
IF CHARINDEX('<', @Description) > 0
	SET @Description = REPLACE(@Description, '<', '')
BEGIN TRAN
	----检查是否是该账号的简历
	IF NOT EXISTS(SELECT 'x' FROM cvMain WITH(NOLOCK) WHERE ID  = @cvMainID AND paMainID = @paMainID)
		GOTO ERR1
	----检查是否是该简历的证书
	IF @ID > 0
		IF NOT EXISTS(SELECT 'x' FROM cvAppendix WITH(NOLOCK) WHERE ID = @ID AND cvMainID = @cvMainID)
			GOTO ERR2
	----不能有重复的证件
	IF EXISTS(SELECT 'x' FROM cvAppendix WITH(NOLOCK)
				WHERE cvMainID = @cvMainID AND dcAppendixID = @dcAppendixID
				AND ID <> @ID AND dcAppendixID < 999 AND Description = @Description AND AccessDate = @AccessDate)
		GOTO ERR3
	SELECT @Description = dbo.SafeSql(dbo.TextTrim(@Description)),
		@Name = dbo.SafeSql(dbo.TextTrim(@Name))
	IF @dcAppendixID IS NULL
		GOTO ERR4
	IF @dcAppendixID = 999 AND @Name IS NULL
		GOTO ERR5

	IF @dcAppendixID < 999
		SELECT @Name = Description FROM dcAppendix WITH(NOLOCK) WHERE ID = @dcAppendixID

	DECLARE @MaxId AS INT
	DECLARE @NameOld AS VARCHAR(250)
	DECLARE @DescriptionOld AS VARCHAR(1000)
	DECLARE @CNT AS INT

	BEGIN TRY
		IF @Type = 0		--中文
			BEGIN
				DECLARE @N AS NVARCHAR(50)
				DECLARE @D AS NVARCHAR(200)

				SET @N = @Name
				SET @D = @Description

				IF @ID>0		--修改证书
					BEGIN
						SELECT @NameOld = dbo.TextTrim(Name), @DescriptionOld = dbo.TextTrim(Description)
						FROM cvAppendix WITH(NOLOCK)
						WHERE ID = @ID

						UPDATE CvAppendix SET 
							Name = @N,
							dcAppendixID = @dcAppendixID,
							Description = @D,
							AccessDate = @AccessDate
						WHERE ID = @ID
						SET @MaxID = @ID

						IF @dcAppendixID = 999
							BEGIN
								IF ISNULL(@NameOld, '') <> ISNULL(@N, '')
									BEGIN
										DELETE FROM bsCvModify WHERE SubID = @ID AND Location = 'cc1'
										INSERT INTO bsCvModify(paMainID,cvMainID,SubID,Location,ColValue) VALUES(@paMainID,@cvMainID,@MaxID,'cc1',@N)
									END
							END
						ELSE
							DELETE FROM bsCvModify WHERE SubID = @ID AND Location = 'cc1'


						IF @D IS NULL
							DELETE FROM bsCvModify WHERE SubID = @ID AND Location = 'cc2'
						ELSE
							IF ISNULL(LTRIM(@DescriptionOld), '') <> @D
								BEGIN
									DELETE FROM bsCvModify WHERE SubID = @ID AND Location = 'cc2'
									INSERT INTO bsCvModify(paMainID,cvMainID,SubID,Location,ColValue) VALUES(@paMainID,@cvMainID,@MaxID,'cc2',@D)

								END

					END
				ELSE		--新增证书
					BEGIN
						SELECT @CNT=COUNT(*) FROM CvAppendix WITH(NOLOCK) WHERE cvMainID = @cvMainID
						IF @CNT<10
							BEGIN
								INSERT INTO CvAppendix(cvMainID, Name, AccessDate, dcAppendixID, Description)
								VALUES(@cvMainID, @N, @AccessDate, @dcAppendixID, @D)
								SET @MaxID = @@IDENTITY

								IF @dcAppendixID = 999
									INSERT INTO bsCvModify(paMainID,cvMainID,SubID,Location,ColValue) VALUES(@paMainID,@cvMainID,@MaxID,'cc1',@Name)
								IF LTRIM(@Description) >''
									INSERT INTO bsCvModify(paMainID,cvMainID,SubID,Location,ColValue) VALUES(@paMainID,@cvMainID,@MaxID,'cc2',@Description)
							END
					END
			END
		ELSE			--英文
			BEGIN
				IF @ID>0			--修改证书
					BEGIN
						SELECT @NameOld = dbo.TextTrim(NameEng), @DescriptionOld = dbo.TextTrim(DescriptionEng)
						FROM cvAppendix WITH(NOLOCK)
						WHERE ID = @ID

						UPDATE CvAppendix SET
							NameEng = @Name,
							AccessDate = @AccessDate,
							dcAppendixID = @dcAppendixID,
							DescriptionEng = @Description
						WHERE ID = @ID
						SET @MaxID = @ID

						IF @dcAppendixID = 999
							BEGIN
								IF ISNULL(@NameOld, '') <> ISNULL(@Name, '') 
									BEGIN
										DELETE FROM bsCvModify WHERE SubID = @ID AND Location = 'ce1'
										INSERT INTO bsCvModify(paMainID,cvMainID,SubID,Location,ColValue) VALUES(@paMainID,@cvMainID,@MaxID,'ce1',@Name)
									END
							END
						ELSE
							DELETE FROM bsCvModify WHERE SubID = @ID AND Location = 'ce1'

						IF @Description IS NULL
							DELETE FROM bsCvModify WHERE SubID = @ID AND Location = 'ce2'
						ELSE
							IF ISNULL(@DescriptionOld, '') <> @Description
								BEGIN
									DELETE FROM bsCvModify WHERE SubID = @ID AND Location = 'ce2'
									INSERT INTO bsCvModify(paMainID,cvMainID,SubID,Location,ColValue) VALUES(@paMainID,@cvMainID,@MaxID,'ce2',@Description)
								END

					END
				ELSE		--新增证书
					BEGIN
						SELECT @CNT=COUNT(*) FROM CvAppendix WITH(NOLOCK) WHERE cvMainID = @cvMainID
						IF @CNT<5
							BEGIN
								INSERT INTO CvAppendix(cvMainID, NameEng, dcAppendixID, AccessDate, DescriptionEng)
								VALUES(@cvMainID, @Name, @dcAppendixID, @AccessDate, @Description)
								SET @MaxID = @@IDENTITY

								IF @dcAppendixID = 999
									INSERT INTO bsCvModify(paMainID,cvMainID,SubID,Location,ColValue) VALUES(@paMainID,@cvMainID,@MaxID,'ce1',@Name)
								IF @Description IS NOT NULL
									INSERT INTO bsCvModify(paMainID,cvMainID,SubID,Location,ColValue) VALUES(@paMainID,@cvMainID,@MaxID,'ce2',@Description)
							END
					END
			END

		--修改cvLevel
		DECLARE @SQL AS VARCHAR(100)
		SET @SQL = 'EXEC pcCvMainByCvLevelUpdateNew ' + CONVERT(CHAR(1), @Type) + ',' + CONVERT(VARCHAR(10), @cvMainID) + ',10,1'
		EXEC(@SQL)

		EXEC pcCvMainByCvLevelCheck @cvMainID, 10
	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH
COMMIT TRAN
RETURN @MaxID
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END
ERR1:
BEGIN
	ROLLBACK TRAN
	RETURN -1
END
ERR2:
BEGIN
	ROLLBACK TRAN
	RETURN -2
END
ERR3:
BEGIN
	ROLLBACK TRAN
	RETURN -3
END
ERR4:
BEGIN
	ROLLBACK TRAN
	RETURN -4
END
ERR5:
BEGIN
	ROLLBACK TRAN
	RETURN -5
END



  
GO
/****** Object:  StoredProcedure [dbo].[pcCvAppendixSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*############################################
 创建：		sean
 检查：		2010-10-5
 说明：		取消各字段，改为*
############################################*/
CREATE PROCEDURE [dbo].[pcCvAppendixSelect]
(
	@cvMainID INT,
	@lan INT
)
AS
BEGIN
	SELECT *
	FROM CvAppendix WITH(NOLOCK INDEX(IX_cvAppendix_cvMainID))
	WHERE cvMainID = @cvMainID
	ORDER BY AccessDate DESC, ID
/*
	IF @lan>0 
		SELECT *
		FROM CvAppendix WITH(NOLOCK INDEX(IX_cvAppendix_cvMainID))
		WHERE cvMainID = @cvMainID
			AND (dcAppendixID<999 OR name>'')
	ELSE IF @lan=0
		SELECT *
		FROM CvAppendix WITH(NOLOCK INDEX(IX_cvAppendix_cvMainID))
		WHERE cvMainID = @cvMainID
			AND (dcAppendixID<999 OR nameEng>'')
	ELSE		用于个人后台修改页面
		SELECT *
		FROM CvAppendix WITH(NOLOCK INDEX(IX_cvAppendix_cvMainID))
		WHERE cvMainID = @cvMainID
*/
END














GO
/****** Object:  StoredProcedure [dbo].[pcCvAttachmentBySaveInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--新版的附件简历上传简历
CREATE PROCEDURE [dbo].[pcCvAttachmentBySaveInsert]
(
	@ID INT,
	@Attachment VARCHAR(50),
	@FileName VARCHAR(50),
	@paMainID INT
)
AS
SET NOCOUNT ON
IF CHARINDEX('<', @Attachment) > 0
	SET @Attachment = REPLACE(@Attachment, '<', '&lt;')
IF CHARINDEX('<', @FileName) > 0
	SET @FileName = REPLACE(@FileName, '<', '&lt;')
BEGIN TRY
	DECLARE @paID AS INT
	SELECT @paID = paMainID FROM cvMain WITH(NOLOCK) WHERE ID = @ID
	IF @paMainID = 0
		BEGIN
			--无账号
			IF @paID IS NULL
				RETURN 0

		END
	ELSE
		IF @paID <> @paMainID		--cvMainID.paMainID <> paMain.ID，简历和账号不对应
			RETURN 0
	
	IF (SELECT COUNT(1) FROM cvAttachment WITH(NOLOCK) WHERE cvMainID = @ID AND VerifyResult <> 0) >= 3  --一份简历的附件不能超过3份
		RETURN -1

	INSERT INTO cvAttachment(cvMainID,FilePath,[FileName])
	VALUES(@ID,@Attachment,@FileName)
	
	UPDATE CvMain SET Attachment = 'X' WHERE id = @ID

	IF(SELECT RefreshDate FROM cvMain WITH(NOLOCK) WHERE ID = @ID) > DATEADD(HOUR, -1, GETDATE())
		UPDATE cvMain SET RefreshDate = GETDATE() WHERE ID = @ID
	
	RETURN 1
END TRY
BEGIN CATCH
	print 0
	RETURN 0
END CATCH
GO
/****** Object:  StoredProcedure [dbo].[pccvEducationByCvMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.31
--创建人：Nick
--说明：得到毕业院校信息
--#####################################################
CREATE PROCEDURE [dbo].[pccvEducationByCvMainIDSelect]
(
	@CvMainID INT,
	@Degree INT
)
AS
BEGIN TRY
	SELECT TOP 1 GraduateCollage, MajorName, Graduation 
	FROM cvEducation WITH(NOLOCK)
	WHERE cvMainID=@CvMainID 
	AND Degree=@Degree 
	ORDER BY Graduation DESC
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[pcCvEducationByIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Sean
-- Create date: 2010-9-27
-- Description:	
-- =============================================
CREATE PROCEDURE [dbo].[pcCvEducationByIDSelect]
	@ID int
AS
BEGIN
	SELECT 
		*
	FROM cvEducation WITH(NOLOCK INDEX(PK_cvEducation))
	WHERE ID=@ID 
END














GO
/****** Object:  StoredProcedure [dbo].[pcCvEducationDelete]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-----------------------------------------------------------
--修改：Sean，2010-9-27
--描述：取消执行pcCvMainByCvLevelUpdate，因为js执行了cvLevelProc.asp，这个应该上线后调整
--取消pcCvMainVerifyResultCheck
--修改：Lambo，2010-11-25
--描述：增加了paMainID参数，判断是否是本人的
-----------------------------------------------------------
--[pcCvEducationDelete] 7424951,12222868
CREATE PROCEDURE [dbo].[pcCvEducationDelete] 
	@ID INT,
	@paMainID INT
AS
BEGIN TRAN
	BEGIN TRY
		DECLARE @cvMainId AS INT
		DECLARE @RETURN AS VARCHAR(2)

		SELECT @cvMainId = cvMainId FROM cvEducation WITH(NOLOCK) WHERE ID=@ID
		
		IF @cvMainId IS NULL
			GOTO ERR

		IF NOT EXISTS(SELECT 'x' FROM cvMain WITH(NOLOCK)
						WHERE paMainID = @paMainID AND ID = @cvMainID)
			GOTO ERR
		
		DELETE FROM bsCvModify WHERE SubID = @ID AND Location LIKE 'd%'
		DELETE FROM cvEducation WHERE ID=@ID

		----重新计算最高学位和专业
		DECLARE @dcMajorID AS SMALLINT
		DECLARE @Degree AS TINYINT
		SELECT TOP 1 @dcMajorID = dcMajorID, @Degree = Degree FROM cvEducation WITH(NOLOCK) WHERE cvMainID = @cvMainID ORDER BY Degree DESC
		UPDATE cvMain SET Degree = @Degree, dcMajorID = @dcMajorID WHERE ID = @cvMainID
		EXEC @RETURN = pcCvMainByCvLevelCheck @cvMainID, 3
	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH
COMMIT TRAN
RETURN @RETURN
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 3
END














GO
/****** Object:  StoredProcedure [dbo].[pcCvEducationSave]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----------------------------------------------------------
--修改：Sean，2010-9-25
--描述：LastModifyDate=GETDATE()，不再调用存储过程
--取消执行pcCvMainByCvLevelUpdate，因为js执行了cvLevelProc.asp，这个应该上线后调整
-- 修改：Lambo，2010-11-25
-- 描述：增加了paMainID参数，判断是否是本人的
-----------------------------------------------------------
CREATE PROCEDURE [dbo].[pcCvEducationSave]
(
	@Type INT,
	@ID INT,
	@cvMainID INT,
	@GraduateCollage VARCHAR(250),
	@Graduation INT,
	@dcMajorID SMALLINT,
	@MajorName VARCHAR(100),
	@Degree TINYINT,
	@EduType TINYINT,
	@Details VARCHAR(2000),
	@paMainID INT 
)
AS
SET NOCOUNT ON
IF CHARINDEX('<', @GraduateCollage) > 0
	SET @GraduateCollage = REPLACE(@GraduateCollage, '<', '&lt;')
IF CHARINDEX('<', @MajorName) > 0
	SET @MajorName = REPLACE(@MajorName, '<', '&lt;')
IF CHARINDEX('<', @Details) > 0
	SET @Details = REPLACE(@Details, '<', '&lt;')
BEGIN TRAN
	----检查是否是该账号的简历
	IF NOT EXISTS(SELECT 'x' FROM cvMain WITH(NOLOCK) WHERE ID = @cvMainID AND paMainID = @paMainID)
		GOTO ERR
	----检查是否是该简历的教育背景
	IF @ID > 0
		IF NOT EXISTS(SELECT 'x' FROM cvEducation WITH(NOLOCK) WHERE ID = @ID AND cvMainID = @cvMainID)
			GOTO ERR
	
	SELECT @GraduateCollage = dbo.SafeSql(dbo.TextTrim(@GraduateCollage)),
		@MajorName  = dbo.SafeSql(dbo.TextTrim(@MajorName)),
		@Details  = dbo.SafeSql(dbo.TextTrim(@Details))

	DECLARE @MaxId AS INT
	DECLARE @CNT AS INT
	DECLARE @GraduateCollageOld AS VARCHAR(250)
	DECLARE @MajorNameOld AS VARCHAR(100)
	DECLARE @DetailsOld AS VARCHAR(2000)
	DECLARE @cvdcMajorID AS SMALLINT
	DECLARE @Modify AS INT
	SET @Modify=-1

	BEGIN TRY
		IF @Type=0
			BEGIN
				DECLARE @GC AS NVARCHAR(50)
				DECLARE @MN AS NVARCHAR(20)
				DECLARE @D AS NVARCHAR(400)
				SET @GC = @GraduateCollage
				SET @MN = @MajorName
				SET @D = @Details

				IF @ID>0
					BEGIN
						SELECT @GraduateCollageOld = dbo.TextTrim(GraduateCollage),
							@MajorNameOld = dbo.TextTrim(MajorName),
							@DetailsOld = dbo.TextTrim(Details)
							FROM cvEducation WITH(NOLOCK INDEX(PK_cvEducation)) WHERE ID=@ID
						UPDATE cvEducation SET
							GraduateCollage = @GC,
							Graduation = @Graduation,
							dcMajorID = @dcMajorID,
							MajorName =@MN,
							Degree = @Degree,
							EduType = @EduType,
							Details = @D
						WHERE ID=@ID
						SET @MaxID=@ID

						IF ISNULL(@GraduateCollageOld, '') <> ISNULL(@GC, '')
							BEGIN
								DELETE FROM bsCvModify WHERE SubID = @ID AND Location = 'dc1'
								INSERT INTO bsCvModify(paMainID,cvMainID,SubID,Location,ColValue) VALUES(@paMainID,@cvMainID,@MaxID,'dc1',@GC)
								SET @Modify=0
							END

						IF ISNULL(@MajorNameOld, '') <> ISNULL(@MN, '')
							BEGIN
								DELETE FROM bsCvModify WHERE paMainID=@paMainID AND cvMainID=@cvMainID AND SubID = @ID AND Location = 'dc2'
								INSERT INTO bsCvModify(paMainID,cvMainID,SubID,Location,ColValue) VALUES(@paMainID,@cvMainID,@MaxID,'dc2',@MN)
								SET @Modify=0
							END
						IF @D IS NULL
							DELETE FROM bsCvModify WHERE paMainID=@paMainID AND cvMainID=@cvMainID AND SubID = @ID AND Location = 'dc3'
						ELSE
							IF ISNULL(@DetailsOld, '') <> @D
								BEGIN
									DELETE FROM bsCvModify WHERE paMainID=@paMainID AND cvMainID=@cvMainID AND SubID = @ID AND Location = 'dc3'
									INSERT INTO bsCvModify(paMainID,cvMainID,SubID,Location,ColValue) VALUES(@paMainID,@cvMainID,@MaxID,'dc3',@D)
									SET @Modify=0
								END
					END
				ELSE
					BEGIN
						SELECT @CNT=COUNT(*) FROM cvEducation WITH(NOLOCK INDEX(PK_cvEducation)) WHERE cvMainID = @cvMAinID
						IF @CNT<5
							BEGIN
								INSERT INTO cvEducation(cvMainID,GraduateCollage,Graduation,dcMajorID,MajorName,Degree,EduType,Details)	
									VALUES(@cvMainID,@GC,@Graduation,@dcMajorID,@MN,@Degree,@EduType,@D)
								SET @MaxID = @@IDENTITY

								INSERT INTO bsCvModify(paMainID,cvMainID,SubID,Location,ColValue) VALUES(@paMainID,@cvMainID,@MaxID,'dc1',@GC)
								INSERT INTO bsCvModify(paMainID,cvMainID,SubID,Location,ColValue) VALUES(@paMainID,@cvMainID,@MaxID,'dc2',@MN)
								SET @Modify=0
								IF @D > ''
									INSERT INTO bsCvModify(paMainID,cvMainID,SubID,Location,ColValue) VALUES(@paMainID,@cvMainID,@MaxID,'dc3',@D)
							END
						ELSE
							GOTO ERR
					END
			END
		ELSE
			BEGIN
				IF @ID>0
					BEGIN
						SELECT @GraduateCollageOld = dbo.TextTrim(GraduateCollageEng),
							@MajorNameOld = dbo.TextTrim(MajorNameEng),
							@DetailsOld = dbo.TextTrim(DetailsEng)
							FROM cvEducation WITH(NOLOCK INDEX(PK_cvEducation)) WHERE ID=@ID

						UPDATE cvEducation SET
							GraduateCollageENG = @GraduateCollage,
							Graduation = @Graduation,
							dcMajorID = @dcMajorID,
							MajorNameEng =@MajorName,
							Degree = @Degree,
							EduType = @EduType,
							DetailsEng = @Details
						WHERE ID=@ID
						SET @MaxID=@ID

						IF ISNULL(@GraduateCollageOld, '') <> ISNULL(@GraduateCollage, '')
							BEGIN
								DELETE FROM bsCvModify WHERE SubID = @ID AND Location = 'de1'
								INSERT INTO bsCvModify(paMainID,cvMainID,SubID,Location,ColValue) VALUES(@paMainID,@cvMainID,@MaxID,'de1',@GraduateCollage)
								SET @Modify=1
							END
						IF ISNULL(@MajorNameOld, '') <> ISNULL(@MajorName, '')
							BEGIN
								DELETE FROM bsCvModify WHERE paMainID=@paMainID AND cvMainID=@cvMainID AND SubID = @ID AND Location = 'de2'
								INSERT INTO bsCvModify(paMainID,cvMainID,SubID,Location,ColValue) VALUES(@paMainID,@cvMainID,@MaxID,'de2',@MajorName)
								SET @Modify=1
							END
						IF @Details IS NULL
							DELETE FROM bsCvModify WHERE paMainID=@paMainID AND cvMainID=@cvMainID AND SubID = @ID AND Location = 'de3'
						ELSE
							IF ISNULL(@DetailsOld, '') <> @Details
								BEGIN
									DELETE FROM bsCvModify WHERE paMainID=@paMainID AND cvMainID=@cvMainID AND SubID = @ID AND Location = 'de3'
									INSERT INTO bsCvModify(paMainID,cvMainID,SubID,Location,ColValue) VALUES(@paMainID,@cvMainID,@MaxID,'de3',@Details)
									SET @Modify=1
								END
					END
				ELSE
					BEGIN
						SELECT @CNT=COUNT(*) FROM cvEducation WITH(NOLOCK INDEX(PK_cvEducation)) WHERE cvMainID = @cvMainID
						IF @CNT<5
							BEGIN
								INSERT INTO cvEducation(cvMainID,GraduateCollageEng,Graduation,dcMajorID,MajorNameEng,Degree,EduType,DetailsEng)
									VALUES(@cvMainID,@GraduateCollage,@Graduation,@dcMajorID,@MajorName,@Degree,@EduType,@Details)
								SET @MaxID = @@IDENTITY
								INSERT INTO bsCvModify(paMainID,cvMainID,SubID,Location,ColValue) VALUES(@paMainID,@cvMainID,@MaxID,'de1',@GraduateCollage)
								INSERT INTO bsCvModify(paMainID,cvMainID,SubID,Location,ColValue) VALUES(@paMainID,@cvMainID,@MaxID,'de2',@MajorName)								
								SET @Modify=1
								IF @Details > ''
									INSERT INTO bsCvModify(paMainID,cvMainID,SubID,Location,ColValue) VALUES(@paMainID,@cvMainID,@MaxID,'de3',@Details)
							END
						ELSE
							GOTO ERR
					END
			END

		SELECT @Degree = MAX(DEGREE) FROM cvEducation WITH(NOLOCK) WHERE cvMainID = @cvMainID
		UPDATE cvMain SET Degree=@Degree, dcMajorID=@dcMajorID WHERE ID=@cvMainID

		--修改cvLevel
		DECLARE @SQL AS VARCHAR(100)
		SET @SQL = 'EXEC pcCvMainByCvLevelUpdateNew ' + CONVERT(CHAR(1), @Type) + ',' + CONVERT(VARCHAR(10), @cvMainID) + ',3,1'
		EXEC(@SQL)
		IF EXISTS(SELECT 'x' FROM cvMain WITH(NOLOCK) WHERE Id = @cvMainId AND cvType = 1 AND SUBSTRING(cvLevel, 4, 1) = '0')
		BEGIN
			SET @SQL = 'EXEC pcCvMainByCvLevelUpdateNew ' + CONVERT(CHAR(1), @Type) + ',' + CONVERT(VARCHAR(10), @cvMainID) + ',4,1'
			EXEC(@SQL)
		END
	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH
COMMIT TRAN
RETURN @MaxID
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END














GO
/****** Object:  StoredProcedure [dbo].[pcCvEducationSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Sean
-- Create date: 2010-9-27
-- Description:	
-- =============================================
CREATE PROCEDURE [dbo].[pcCvEducationSelect] 
	@cvMainID int
AS
BEGIN
	SELECT *,
	(SELECT Description FROM DcMajor WITH(NOLOCK) WHERE ID = cvEducation.dcMajorID  ) dcMajorName
	FROM cvEducation WITH(NOLOCK INDEX(IX_cvEducation_CvMainID))
	WHERE cvMainID=@cvMainID 
	ORDER BY Degree DESC,Graduation Desc
END













GO
/****** Object:  StoredProcedure [dbo].[pcCvEducationSelectByPhone]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[pcCvEducationSelectByPhone]
	@cvMainID int
AS
BEGIN
	SELECT a.*,b.Description Major,c.Description EduTypeName,d.Description Education
	FROM cvEducation a WITH(NOLOCK INDEX(IX_cvEducation_CvMainID)),dcMajor b WITH(NOLOCK),dcEduType c WITH(NOLOCK),dcEducation d WITH(NOLOCK)
	WHERE a.dcMajorID=b.ID AND a.EduType=c.ID AND a.Degree=d.ID AND a.cvMainID=@cvMainID
	ORDER BY a.Degree DESC,a.Graduation Desc
END














GO
/****** Object:  StoredProcedure [dbo].[pcCvExperienceByIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
---------------------------------------------------
--创建	Sean
--		2010-9-27
--		各字段改为*
---------------------------------------------------
CREATE PROCEDURE [dbo].[pcCvExperienceByIDSelect]
	@ID INT
AS
BEGIN
	SELECT *
	FROM cvExperience WITH(NOLOCK INDEX(PK_cvExperience))
	WHERE ID = @ID
END














GO
/****** Object:  StoredProcedure [dbo].[pcCvExperienceDelete]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----------------------------------------------
--创建Sean
--检查时间	2010-9-27
--修改了有无工作经验的判断, 取消pcCvMainVerifyResultCheck
--修改：Lambo，2010-11-25
--描述：增加了paMainID参数，判断是否是本人的
-----------------------------------------------
CREATE PROCEDURE [dbo].[pcCvExperienceDelete]
(
	@ID INT,
	@paMainID INT
)
AS
SET NOCOUNT ON
BEGIN TRAN
	BEGIN TRY
		DECLARE @cvMainId AS INT
		DECLARE @RETURN AS VARCHAR(2)

		SELECT @cvMainId = cvMainId FROM cvExperience WITH(NOLOCK) WHERE ID=@ID

		IF @cvMainId IS NULL
			GOTO ERR

		IF NOT EXISTS(SELECT 'x' FROM cvMain WITH(NOLOCK) WHERE paMainID = @paMainID AND ID = @cvMainID)
			GOTO ERR


		DELETE FROM bsCvModify WHERE SubID = @ID AND Location LIKE 'e%'
		DELETE FROM cvExperience WHERE ID=@ID
	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH
COMMIT TRAN
RETURN @RETURN
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 3
END














GO
/****** Object:  StoredProcedure [dbo].[pcCvExperienceSave]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----------------------------------------------------------
--修改：Sean，2010-9-26
--描述：LastModifyDate = GETDATE()，不再调用存储过程
--屏蔽了@Modify，上线后在调整
--修改：Lambo，2010-11-25
--描述：增加了paMainID参数，判断是否是本人的
-----------------------------------------------------------
CREATE PROCEDURE [dbo].[pcCvExperienceSave]
(
	@Type INT,
	@ID INT,
	@cvMainID INT,
	@CompanyName VARCHAR(100),
	@dcIndustryID INT,
	@dcCompanySizeID INT,
	@dcJobtypeID INT,
	@JobName VARCHAR(100),
	@BeginDate INT,
	@EndDate INT,
	@SubNodeNum INT,
	@Description VARCHAR(Max),
	@dcCompanyKindID INT = NULL,
	@WorkPlace VARCHAR(6) = NULL,
	@Dept VARCHAR(100) = NULL,
	@UpperPost VARCHAR(100) = NULL,
	@dcLeaveResonID INT = NULL,
	@paMainID INT
)
AS
SET NOCOUNT ON
IF CHARINDEX('<', @CompanyName) > 0
	SET @CompanyName = REPLACE(@CompanyName, '<', '')
IF CHARINDEX('<', @JobName) > 0
	SET @JobName = REPLACE(@JobName, '<', '')
IF CHARINDEX('<', @Description) > 0
	SET @Description = REPLACE(@Description, '<', '')
IF CHARINDEX('<', @Dept) > 0
	SET @Dept = REPLACE(@Dept, '<', '')
IF CHARINDEX('<', @UpperPost) > 0
	SET @UpperPost = REPLACE(@UpperPost, '<', '')
BEGIN TRAN
	----检查是否是该账号的简历
	IF NOT EXISTS(SELECT 'x' FROM cvMain WITH(NOLOCK) WHERE ID = @cvMainID AND paMainID = @paMainID)
		GOTO ERR
	----检查是否是该简历的工作经验
	IF @ID > 0
		IF NOT EXISTS(SELECT 'x' FROM cvExperience WITH(NOLOCK) WHERE ID = @ID AND cvMainID = @cvMainID)
			GOTO ERR

	SELECT @CompanyName = dbo.SafeSQL(dbo.TextTrim(@CompanyName)),
		@JobName = dbo.SafeSQL(dbo.TextTrim(@JobName)),
		@Description = dbo.SafeSQL(dbo.TextTrim(@Description)),
		@WorkPlace = dbo.TextTrim(@WorkPlace),
		@Dept = dbo.SafeSQL(dbo.TextTrim(@Dept)),
		@UpperPost = dbo.SafeSQL(dbo.TextTrim(@UpperPost))

	IF CHARINDEX(',', @JobName) > 0
		SELECT @JobName = dbo.SafeSql(REPLACE(@JobName, ',', '，'))

	DECLARE @MaxId AS INT
	DECLARE @CNT AS INT
	DECLARE @CompanyNameOld AS VARCHAR(100)
	DECLARE @JobNameOld AS VARCHAR(100)
	DECLARE @DescriptionOld AS VARCHAR(Max)
	DECLARE @DeptOld AS VARCHAR(100)
	DECLARE @UpperPostOld AS VARCHAR(100)
	DECLARE @Modify AS INT
	SET @Modify = -1

	BEGIN TRY
		IF @Type = 0
			BEGIN
				DECLARE @C_CompanyName AS NVARCHAR(30)
				DECLARE @C_JobName AS NVARCHAR(50)
				DECLARE @C_Description AS NVARCHAR(2000)
				DECLARE @C_Dept AS NVARCHAR(20)
				DECLARE @C_UpperPost AS NVARCHAR(20)

				SET @C_CompanyName = dbo.TextTrim(@CompanyName)
				SET @C_JobName = dbo.TextTrim(@JobName)
				SET @C_Description = dbo.TextTrim(@Description)
				SET @C_Dept = dbo.TextTrim(@Dept)
				SET @C_UpperPost = dbo.TextTrim(@UpperPost)
				
				IF @ID>0
					BEGIN
						SELECT @CompanyNameOld = dbo.TextTrim(ISNULL(CompanyName, '')),
							@JobNameOld = dbo.TextTrim(ISNULL(JobName, '')),
							@DescriptionOld = dbo.TextTrim(ISNULL(Description, '')),
							@DeptOld = dbo.TextTrim(ISNULL(Dept, '')),
							@UpperPostOld = dbo.TextTrim(ISNULL(UpperPost, ''))
							FROM cvExperience WITH(NOLOCK INDEX(PK_cvExperience)) WHERE ID = @ID

						UPDATE cvExperience SET
							CompanyName = @C_CompanyName,
							dcIndustryID = @dcIndustryID,
							dcCompanySizeID = @dcCompanySizeID,
							dcJobtypeID = @dcJobtypeID,
							JobName = @C_JobName,
							BeginDate = @BeginDate,
							EndDate = @EndDate,
							SubNodeNum = @SubNodeNum,
							Description = @C_Description,
							dcCompanyKindID = @dcCompanyKindID,
							WorkPlace = @WorkPlace,
							Dept = @C_Dept,
							UpperPost = @C_UpperPost,
							dcLeaveResonID = @dcLeaveResonID
						WHERE ID = @ID
						SET @MaxID = @ID

						IF ISNULL(@CompanyNameOld, '') <> ISNULL(@C_CompanyName, '')
							BEGIN
								DELETE FROM bsCvModify WHERE SubID = @ID AND Location = 'ec1'
								INSERT INTO bsCvModify(paMainID,cvMainID,SubID,Location,ColValue) VALUES(@paMainID,@cvMainID,@MaxID,'ec1',@CompanyName)
								SET @Modify = 0
							END

						IF ISNULL(@JobNameOld, '') <> ISNULL(@C_JobName, '')
							BEGIN
								DELETE FROM bsCvModify WHERE paMainID = @paMainID AND cvMainID = @cvMainID AND SubID = @ID AND Location = 'ec2'
								INSERT INTO bsCvModify(paMainID,cvMainID,SubID,Location,ColValue) VALUES(@paMainID,@cvMainID,@MaxID,'ec2',@C_JobName)
								SET @Modify = 0
							END

						IF ISNULL(@DescriptionOld, '') <> ISNULL(@C_Description, '')
							BEGIN
								DELETE FROM bsCvModify WHERE paMainID = @paMainID AND cvMainID = @cvMainID AND SubID = @ID AND Location = 'ec3'
								INSERT INTO bsCvModify(paMainID,cvMainID,SubID,Location,ColValue) VALUES(@paMainID,@cvMainID,@MaxID,'ec3',@C_Description)
								SET @Modify = 0
							END
						IF @C_Dept IS NULL
							DELETE FROM bsCvModify WHERE paMainID = @paMainID AND cvMainID = @cvMainID AND SubID = @ID AND Location = 'ec4'
						ELSE
							IF ISNULL(@DeptOld, '') <> @C_Dept
								BEGIN
									DELETE FROM bsCvModify WHERE paMainID = @paMainID AND cvMainID = @cvMainID AND SubID = @ID AND Location = 'ec4'
									INSERT INTO bsCvModify(paMainID,cvMainID,SubID,Location,ColValue) VALUES(@paMainID,@cvMainID,@MaxID,'ec4',@C_Dept)
									SET @Modify = 0
								END
						IF @UpperPost IS NULL
							DELETE FROM bsCvModify WHERE paMainID = @paMainID AND cvMainID = @cvMainID AND SubID = @ID AND Location = 'ec5'
						ELSE
							IF ISNULL(@UpperPostOld, '') <> @C_UpperPost 
								BEGIN
									DELETE FROM bsCvModify WHERE paMainID = @paMainID AND cvMainID = @cvMainID AND SubID = @ID AND Location = 'ec5'
									INSERT INTO bsCvModify(paMainID,cvMainID,SubID,Location,ColValue) VALUES(@paMainID,@cvMainID,@MaxID,'ec5',@C_UpperPost)
									SET @Modify = 0
								END
					END
				ELSE
					BEGIN
						SELECT @CNT = COUNT(*) FROM cvExperience WITH(NOLOCK INDEX(IX_cvExperience_cvMainID)) WHERE cvMainID = @cvMainID
						IF @CNT<20
							BEGIN
								INSERT INTO cvExperience
									(cvMainID,CompanyName,dcIndustryID,dcCompanySizeID,dcJobtypeID,JobName,
									BeginDate,EndDate,SubNodeNum,Description,dcCompanyKindID,WorkPlace,Dept,
									UpperPost,dcLeaveResonID)
								 VALUES
									(@cvMainID,@CompanyName,@dcIndustryID,@dcCompanySizeID,@dcJobtypeID,@JobName,
									@BeginDate,@EndDate,@SubNodeNum,@Description,@dcCompanyKindID,@WorkPlace,@Dept,
									@UpperPost,@dcLeaveResonID)
								SET @MaxID = @@IDENTITY

								INSERT INTO bsCvModify(paMainID,cvMainID,SubID,Location,ColValue) VALUES(@paMainID,@cvMainID,@MaxID,'ec1',@C_CompanyName)
								INSERT INTO bsCvModify(paMainID,cvMainID,SubID,Location,ColValue) VALUES(@paMainID,@cvMainID,@MaxID,'ec2',@C_JobName)
								INSERT INTO bsCvModify(paMainID,cvMainID,SubID,Location,ColValue) VALUES(@paMainID,@cvMainID,@MaxID,'ec3',@C_Description)
								IF @Dept > ''
									INSERT INTO bsCvModify(paMainID,cvMainID,SubID,Location,ColValue) VALUES(@paMainID,@cvMainID,@MaxID,'ec4',@C_Dept)
								IF @UpperPost > ''
									INSERT INTO bsCvModify(paMainID,cvMainID,SubID,Location,ColValue) VALUES(@paMainID,@cvMainID,@MaxID,'ec5',@C_UpperPost)
								SET @Modify = 0
							END
						ELSE
							GOTO ERR
					END
			END
		ELSE
			BEGIN
				IF @ID>0
					BEGIN
						SELECT @CompanyNameOld = dbo.TextTrim(ISNULL(CompanyNameEng, '')),
							@JobNameOld = dbo.TextTrim(iSNULL(JobNameEng, '')),
							@DescriptionOld = dbo.TextTrim(ISNULL(DescriptionEng, '')),
							@DeptOld = dbo.TextTrim(ISNULL(DeptEng, '')),
							@UpperPostOld = dbo.TextTrim(ISNULL(UpperPostEng, ''))
						FROM cvExperience WITH(NOLOCK INDEX(PK_cvExperience))
						WHERE ID = @ID

						UPDATE cvExperience SET
							CompanyNameEng = @CompanyName,
							dcIndustryID = @dcIndustryID,
							dcCompanySizeID = @dcCompanySizeID,
							dcJobtypeID = @dcJobtypeID,
							JobNameEng = @JobName,
							BeginDate = @BeginDate,
							EndDate = @EndDate,
							SubNodeNum = @SubNodeNum,
							DescriptionEng = @Description,
							dcCompanyKindID = @dcCompanyKindID,
							WorkPlace = @WorkPlace,
							DeptEng = @Dept,
							UpperPostEng = @UpperPost,
							dcLeaveResonID = @dcLeaveResonID
						WHERE ID = @ID
						SET @MaxID = @ID

						IF ISNULL(@CompanyNameOld, '') <> ISNULL(@CompanyName, '')
							BEGIN
								DELETE FROM bsCvModify WHERE SubID = @ID AND Location = 'ee1'
								INSERT INTO bsCvModify(paMainID,cvMainID,SubID,Location,ColValue) VALUES(@paMainID,@cvMainID,@MaxID,'ee1',@CompanyName)
								SET @Modify = 1
							END

						IF ISNULL(@JobNameOld, '') <> ISNULL(@JobName, '')
							BEGIN
								DELETE FROM bsCvModify WHERE paMainID = @paMainID AND cvMainID = @cvMainID AND SubID = @ID AND Location = 'ee2'
								INSERT INTO bsCvModify(paMainID,cvMainID,SubID,Location,ColValue) VALUES(@paMainID,@cvMainID,@MaxID,'ee2',@JobName)
								SET @Modify = 1
							END

						IF ISNULL(@DescriptionOld, '') <> ISNULL(@Description, '')
							BEGIN
								DELETE FROM bsCvModify WHERE paMainID = @paMainID AND cvMainID = @cvMainID AND SubID = @ID AND Location = 'ee3'
								INSERT INTO bsCvModify(paMainID,cvMainID,SubID,Location,ColValue) VALUES(@paMainID,@cvMainID,@MaxID,'ee3',@Description)
								SET @Modify = 1
							END
						IF @Dept IS NULL
							DELETE FROM bsCvModify WHERE paMainID = @paMainID AND cvMainID = @cvMainID AND SubID = @ID AND Location = 'ee4'
						ELSE
							IF ISNULL(@DeptOld, '') <> @Dept
								BEGIN
									DELETE FROM bsCvModify WHERE paMainID = @paMainID AND cvMainID = @cvMainID AND SubID = @ID AND Location = 'ee4'
									INSERT INTO bsCvModify(paMainID,cvMainID,SubID,Location,ColValue) VALUES(@paMainID,@cvMainID,@MaxID,'ee4',@Dept)
									SET @Modify = 1
								END
						IF @UpperPost IS NULL
							DELETE FROM bsCvModify WHERE paMainID = @paMainID AND cvMainID = @cvMainID AND SubID = @ID AND Location = 'ee5'								
						ELSE
							IF ISNULL(@UpperPostOld, '') <> @UpperPost
								BEGIN
									DELETE FROM bsCvModify WHERE paMainID = @paMainID AND cvMainID = @cvMainID AND SubID = @ID AND Location = 'ee5'								
									INSERT INTO bsCvModify(paMainID,cvMainID,SubID,Location,ColValue) VALUES(@paMainID,@cvMainID,@MaxID,'ee5',@UpperPost)
									SET @Modify = 1
								END
					END
				ELSE
					BEGIN
						INSERT INTO cvExperience
							(cvMainID,CompanyNameEng,dcIndustryID,dcCompanySizeID,dcJobtypeID,JobNameEng,
							BeginDate,EndDate,SubNodeNum,DescriptionEng,dcCompanyKindID,WorkPlace,DeptEng,
							UpperPostEng,dcLeaveResonID)
						 VALUES
							(@cvMainID,@CompanyName,@dcIndustryID,@dcCompanySizeID,@dcJobtypeID,@JobName,
							@BeginDate,@EndDate,@SubNodeNum,@Description,@dcCompanyKindID,@WorkPlace,@Dept,
							@UpperPost,@dcLeaveResonID)
						SET @MaxID = @@IDENTITY
						INSERT INTO bsCvModify(paMainID,cvMainID,SubID,Location,ColValue) VALUES(@paMainID,@cvMainID,@MaxID,'ee1',@CompanyName)
						INSERT INTO bsCvModify(paMainID,cvMainID,SubID,Location,ColValue) VALUES(@paMainID,@cvMainID,@MaxID,'ee2',@JobName)
						INSERT INTO bsCvModify(paMainID,cvMainID,SubID,Location,ColValue) VALUES(@paMainID,@cvMainID,@MaxID,'ee3',@Description)
						SET @Modify = 1

						IF @Dept > ''
							INSERT INTO bsCvModify(paMainID,cvMainID,SubID,Location,ColValue) VALUES(@paMainID,@cvMainID,@MaxID,'ee4',@Dept)
						IF @UpperPost > ''
							INSERT INTO bsCvModify(paMainID,cvMainID,SubID,Location,ColValue) VALUES(@paMainID,@cvMainID,@MaxID,'ee5',@UpperPost)

					END
			END

		UPDATE cvMain SET cvType = 0 WHERE Id = @CvMainId AND cvType = 1
		--修改cvLevel
		DECLARE @SQL AS VARCHAR(100)
		SET @SQL = 'EXEC pcCvMainByCvLevelUpdateNew ' + CONVERT(CHAR(1), @Type) + ',' + CONVERT(VARCHAR(10), @cvMainID) + ',4,1'
		EXEC(@SQL)
	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH
COMMIT TRAN
RETURN @MaxID
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END




GO
/****** Object:  StoredProcedure [dbo].[pcCvExperienceSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
----------------------------------
--创建：		Sean
--检查：		2010-9-27
----------------------------------
CREATE PROCEDURE [dbo].[pcCvExperienceSelect]
	@cvMainID INT
AS
BEGIN
	SELECT *
	FROM cvExperience WITH(NOLOCK INDEX(IX_cvExperience_cvMainID))
	WHERE cvMainID = @cvMainID
	ORDER BY BeginDate DESC
END














GO
/****** Object:  StoredProcedure [dbo].[pcCvExperienceSelectByPhone]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[pcCvExperienceSelectByPhone]
	@cvMainID INT
AS
BEGIN
	SELECT a.*,b.Description JobType,c.Description CpmpanySize,d.Description Industry,
	g.Description LowerNumber,e.Description CompanyKind,f.Description LeaveReson,h.FullName Region
		FROM cvExperience a WITH(NOLOCK INDEX(IX_cvExperience_cvMainID))
		INNER JOIN dcJobType b WITH(NOLOCK) ON a.dcJobTypeID=b.ID
		INNER JOIN dcCompanySize c WITH(NOLOCK) ON a.dcCompanySizeID=c.ID
		INNER JOIN dcIndustry d WITH(NOLOCK) ON a.dcIndustryID=d.ID
		INNER JOIN dcLowerNumber g WITH(NOLOCK) ON a.SubNodeNum=g.ID
		LEFT JOIN dcCompanyKind e WITH(NOLOCK) ON a.dcCompanyKindID=e.ID
		LEFT JOIN dcLeaveReson f WITH(NOLOCK) ON a.dcLeaveResonID=f.ID
		LEFT JOIN dcRegion h WITH(NOLOCK) ON a.WorkPlace=h.ID
	WHERE cvMainID=@cvMainID
	ORDER BY a.BeginDate DESC
END














GO
/****** Object:  StoredProcedure [dbo].[pccvImportPrevByPaMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.31
--创建人：Nick
--说明：获取该简历在简历导入的认证信息
--#####################################################
CREATE PROCEDURE [dbo].[pccvImportPrevByPaMainIDSelect]
(
	@paMainID VARCHAR(20)
)
AS
BEGIN TRY
	SELECT TOP 1 EntryDate,ContactResult  
	FROM marketdb..cvImportPrev WITH(NOLOCK) 
	WHERE pamainid = @paMainID 
	AND EntryDate IS NOT NULL 
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[pcCvLanguageByIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
----------------------------
--创建：		Sean
--检查：		2010-9-27
----------------------------
CREATE PROCEDURE [dbo].[pcCvLanguageByIDSelect]
	@ID INT
AS
BEGIN
	SELECT *
	FROM CvLanguage WITH(NOLOCK INDEX(PK_cvLanguage))
	WHERE ID = @ID
END














GO
/****** Object:  StoredProcedure [dbo].[pcCvLanguageDelete]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-----------------------------------------------------------
--修改：Sean，2010-9-27
--描述：取消执行pcCvMainByCvLevelUpdate，因为js执行了cvLevelProc.asp，这个应该上线后调整
--		取消pcCvMainVerifyResultCheck的执行，因为与审核状态无关
--修改：Lambo，2010-11-25
--描述：增加了paMainID参数，判断是否是本人的
-----------------------------------------------------------
CREATE PROCEDURE [dbo].[pcCvLanguageDelete]
	@ID INT,
	@paMainID INT
AS
BEGIN TRAN
	BEGIN TRY
		DECLARE @cvMainId AS INT
		DECLARE @RETURN AS VARCHAR(2)
		SELECT @cvMainId = cvMainId FROM cvLanguage WITH(NOLOCK) WHERE ID=@ID
		
		IF @cvMainId IS NULL
			GOTO ERR

		IF NOT EXISTS(SELECT 'x' FROM cvMain WITH(NOLOCK)
						WHERE paMainID = @paMainID AND ID = @cvMainID)
			GOTO ERR

		DELETE FROM bsCvModify WHERE SubID = @ID AND Location LIKE 'h%'
		DELETE FROM cvLanguage WHERE ID=@ID
		EXEC @RETURN = pcCvMainByCvLevelCheck @cvMainID, 7
	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH
COMMIT TRAN
RETURN @RETURN
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 3
END














GO
/****** Object:  StoredProcedure [dbo].[pcCvLanguageSave]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


-----------------------------------------------------------
--修改：		Sean
--检查：		2010-9-27
--描述：		取消执行pcCvMainByCvLevelUpdate，因为js执行了cvLevelProc.asp，这个应该上线后调整
--				取消pcCvMainVerifyResultUpdate
--修改：Lambo，2010-11-25
--描述：增加了paMainID参数，判断是否是本人的
-----------------------------------------------------------
CREATE PROCEDURE [dbo].[pcCvLanguageSave]
(
	@Type INT,
	@ID INT,
	@cvMainID INT,
	@LanguageType INT,
	@Mastery INT,
	@ReadWrite INT,
	@Spoken INT,
	@Score VARCHAR(100),
	@paMainID INT
)
AS
SET NOCOUNT ON
IF CHARINDEX('<', @Score) > 0
	SET @Score = REPLACE(@Score, '<', '')
BEGIN TRAN
	----检查是否是该账号的简历
	IF NOT EXISTS(SELECT 'x' FROM cvMain WITH(NOLOCK) WHERE ID = @cvMainID AND paMainID = @paMainID)
		GOTO ERR
	----检查是否是该简历的语言能力
	IF @ID > 0
		IF NOT EXISTS(SELECT 'x' FROM cvLanguage WITH(NOLOCK) WHERE ID = @ID AND cvMainID = @cvMainID)
			GOTO ERR

	SET @Score = dbo.SafeSql(dbo.TextTrim(@Score))

	DECLARE @MaxId AS INT
	DECLARE @ScoreOld AS VARCHAR(100)
	DECLARE @Modify AS INT
	SET @Modify=-1

	BEGIN TRY
		IF @Type=0
			BEGIN
				DECLARE @S AS NVARCHAR(30)
				SET @S = @Score
				SELECT @ScoreOld = dbo.TextTrim(ISNULL(Score, '')) FROM cvLanguage WITH(NOLOCK INDEX(PK_cvLanguage)) WHERE ID = @ID
				IF @ID>0
					BEGIN
						--DELETE FROM CvLanguage WHERE LanguageType = @LanguageType AND cvMainID=@cvMainID
						UPDATE CvLanguage SET
							LanguageType = @LanguageType,
							Mastery = @Mastery,
							ReadWrite = @ReadWrite,
							Spoken = @Spoken,
							Score = @S
						WHERE ID=@ID
						SET @MaxID = @ID

						IF @S IS NULL
							DELETE FROM bsCvModify WHERE SubID = @ID AND Location = 'hc1'
						ELSE						
							IF @S <> ISNULL(@ScoreOld, '')
								BEGIN
									DELETE FROM bsCvModify WHERE SubID = @ID AND Location = 'hc1'
									INSERT INTO bsCvModify(paMainID,cvMainID,SubID,Location,ColValue) VALUES(@paMainID,@cvMainID,@MaxID,'hc1',@S)
									SET @Modify=0
								END
					END
				ELSE
					BEGIN
						INSERT INTO CvLanguage(cvMainID,LanguageType,Mastery,ReadWrite,Spoken,Score) 
						VALUES(@cvMainID,@LanguageType,@Mastery,@ReadWrite,@Spoken,@Score)
						SET @MaxID = @@IDENTITY

						IF @S > ''
							BEGIN
								INSERT INTO bsCvModify(paMainID,cvMainID,SubID,Location,ColValue) VALUES(@paMainID,@cvMainID,@MaxID,'hc1',@S)
								SET @Modify=0
							END
					END
			END
		ELSE
			BEGIN
				IF @ID>0
					BEGIN
						--DELETE FROM CvLanguage WHERE LanguageType = @LanguageType AND cvMainID=@cvMainID
						SELECT @ScoreOld = dbo.TextTrim(ISNULL(Score, '')) FROM cvLanguage WITH(NOLOCK INDEX(PK_cvLanguage)) WHERE ID = @ID
						UPDATE CvLanguage SET
							LanguageType = @LanguageType,
							Mastery = @Mastery,
							ReadWrite = @ReadWrite,
							Spoken = @Spoken,
							ScoreEng = @Score
						WHERE ID=@ID
						SET @MaxID = @ID

						IF @Score IS NULL
							DELETE FROM bsCvModify WHERE SubID = @ID AND Location = 'he1'
						ELSE
							IF @Score <> ISNULL(@ScoreOld, '')
								BEGIN
									DELETE FROM bsCvModify WHERE SubID = @ID AND Location = 'he1'
									INSERT INTO bsCvModify(paMainID,cvMainID,SubID,Location) VALUES(@paMainID,@cvMainID,@MaxID,'he1')
									SET @Modify=1
								END
					END
				ELSE
					BEGIN
						INSERT INTO CvLanguage(cvMainID,LanguageType,Mastery,ReadWrite,Spoken,ScoreEng) 
						VALUES(@cvMainID,@LanguageType,@Mastery,@ReadWrite,@Spoken,@Score)
						SET @MaxID = @@IDENTITY

						IF @Score > ''
							BEGIN
								INSERT INTO bsCvModify(paMainID,cvMainID,SubID,Location) VALUES(@paMainID,@cvMainID,@MaxID,'he1')
								SET @Modify=1
							END
					END
			END
		--修改cvLevel
		DECLARE @SQL AS VARCHAR(100)
		SET @SQL = 'EXEC pcCvMainByCvLevelUpdateNew ' + CONVERT(CHAR(1), @Type) + ',' + CONVERT(VARCHAR(10), @cvMainID) + ',7,1'
		EXEC(@SQL)
	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH
COMMIT TRAN
RETURN @MaxID
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END














GO
/****** Object:  StoredProcedure [dbo].[pcCvLanguageSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----------------------------------------------------------
--修改：		Sean
--检查：		2010-9-27
-----------------------------------------------------------
CREATE PROCEDURE [dbo].[pcCvLanguageSelect]
	@cvMainID INT
AS
BEGIN
	SELECT *
	FROM CvLanguage WITH(NOLOCK INDEX(IX_cvLanguage_cvMainID))
	WHERE cvMainID = @cvMainID
END














GO
/****** Object:  StoredProcedure [dbo].[pcCvMainByApplySelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[pcCvMainByApplySelect]
    @paMainID INT
AS
BEGIN
    SELECT
        ID,
        paMainID,
        Name,
        EmployType,
        dcSalaryID,
        Attachment,
        WordFileNAme,
        cvType,
        IsNameHidden,
        IscvHidden,
        isOpen,
        cvLevel,
        cvLevelEng,
        VerifyResult,
        VerifyResultEng,
        Valid,
        ViewNumber,
        RefreshDate,
        Degree
    FROM cvMain WITH(NOLOCK) 
    WHERE paMainID=@paMainID
    AND ((cvLevel like '111__1%' AND VerifyResult=1) OR (cvLevelEng like '111__1%' AND VerifyResultEng=1))
    ORDER BY RefreshDate DESC
END
GO
/****** Object:  StoredProcedure [dbo].[pcCvMainByAttachmentClear]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--=============================================
--修改：		Sean
--检查：		2010-10-5
--=============================================
CREATE PROCEDURE [dbo].[pcCvMainByAttachmentClear]
	@ID INT,		--cvMain.ID
	@paMainID INT
AS
BEGIN TRY
	----检查是否是该账号的简历
	IF NOT EXISTS(SELECT 'x' FROM cvMain WITH(NOLOCK) WHERE ID = @ID AND paMainID = @paMainID)
		RETURN 0

	UPDATE CvMain SET Attachment = NULL, WordFilename = NULL WHERE ID = @ID
	IF(SELECT RefreshDate FROM cvMain WITH(NOLOCK) WHERE ID = @ID) > DATEADD(HOUR, -1, GETDATE())
		UPDATE cvMain SET RefreshDate = GETDATE() WHERE ID = @ID

	DELETE FROM bsCvModify WHERE Location = 'ac5' AND cvMainID = @ID
	RETURN 1
END TRY
BEGIN CATCH
	RETURN 0
END CATCH














GO
/****** Object:  StoredProcedure [dbo].[pcCvMainByAttachmentUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--=============================================
--检查：		Sean，2010-10-5
--
--=============================================
CREATE PROCEDURE [dbo].[pcCvMainByAttachmentUpdate]
(
	@ID INT,
	@Attachment VARCHAR(50),
	@WordFileName VARCHAR(50),
	@paMainID INT
)
AS
SET NOCOUNT ON
IF CHARINDEX('<', @Attachment) > 0
	SET @Attachment = REPLACE(@Attachment, '<', '&lt;')
IF CHARINDEX('<', @WordFileName) > 0
	SET @WordFileName = REPLACE(@WordFileName, '<', '&lt;')
BEGIN TRY
	DECLARE @paID AS INT
	SELECT @paID = paMainID FROM cvMain WITH(NOLOCK) WHERE ID = @ID
	IF @paMainID = 0
		BEGIN
			--无账号
			IF @paID IS NULL
				RETURN 0

			--账号不是附件上传建立的，附件上传新建的账号密码=123456
			IF NOT EXISTS(SELECT 'x' FROM paMain WITH(NOLOCK) WHERE ID = @paID AND Password = '123456')
				RETURN 0
		END
	ELSE
		IF @paID <> @paMainID		--cvMainID.paMainID <> paMain.ID，简历和账号不对应
			RETURN 0

	UPDATE CvMain SET Attachment = dbo.SafeSql(@Attachment), WordFileNAme=dbo.SafeSql(@WordFileName) WHERE ID = @ID
	DELETE FROM bsCvModify WHERE cvMainID = @ID AND Location = 'ac5'
	INSERT INTO bsCvModify(paMainID,cvMainID,Location,colvalue) VALUES(@paID, @ID, 'ac5', @Attachment)
	IF(SELECT RefreshDate FROM cvMain WITH(NOLOCK) WHERE ID = @ID) > DATEADD(HOUR, -1, GETDATE())
		UPDATE cvMain SET RefreshDate = GETDATE() WHERE ID = @ID
	
	RETURN 1
END TRY
BEGIN CATCH
	print 0
	RETURN 0
END CATCH














GO
/****** Object:  StoredProcedure [dbo].[pcCvMainByCvJobTypeSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[pcCvMainByCvJobTypeSelect]
(
    @strJobType VARCHAR(10)
)
AS
BEGIN
    SELECT a.MajorName, a.dcMajorId, a.PinYin, a.jianPin, b.* 
    FROM dcJobTypeMajorMap a WITH(NOLOCK) LEFT JOIN dcMajor b WITH(NOLOCK) ON b.id = a.dcMajorID
    WHERE a.dcJobTypeid= @strJobType 
    AND a.dcMajorId = b.Id
END
GO
/****** Object:  StoredProcedure [dbo].[pcCvMainByCvLevelCheck]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--[pcCvMainByCvLevelCheck] 12222868,3
CREATE PROCEDURE [dbo].[pcCvMainByCvLevelCheck]
(
	@cvMainID INT,
	@Pos INT
)
AS
SET NOCOUNT ON
BEGIN TRAN
	BEGIN TRY
		DECLARE @Chs AS INT
		DECLARE @Eng AS INT
		DECLARE @paID AS INT
		DECLARE @Return AS VARCHAR(2)

		SELECT @paID = paMainID FROM cvMain WHERE ID = @cvMainID
		--教育背景
		IF @Pos = 3
			BEGIN
				SELECT @Chs = COUNT(1) FROM cvEducation WITH(NOLOCK) WHERE cvMainID = @cvMainID AND GraduateCollage > ''
				SELECT @Eng = COUNT(1) FROM cvEducation WITH(NOLOCK) WHERE cvMainID = @cvMainID AND GraduateCollageEng > ''
			END
		--工作经历
		IF @Pos = 4
			BEGIN
				SELECT @Chs = COUNT(1) FROM cvExperience WITH(NOLOCK) WHERE cvMainID = @cvMainID AND CompanyName > ''
				SELECT @Eng = COUNT(1) FROM cvExperience WITH(NOLOCK) WHERE cvMainID = @cvMainID AND CompanyNameEng > ''
			END

		--求职意向
		IF @Pos = 6
			BEGIN
				SELECT @Chs = COUNT(1) FROM cvMain WITH(NOLOCK) WHERE ID = @cvMainID AND dcSalaryID > 0
				SELECT @Eng = @Chs
			END

		--工作能力
		IF @Pos = 5
			BEGIN
				SELECT @Chs = COUNT(1) FROM cvMain WITH(NOLOCK) WHERE ID = @cvMainID AND Speciality IS NOT NULL
				SELECT @Eng = COUNT(1) FROM cvMain WITH(NOLOCK) WHERE ID = @cvMainID AND SpecialityEng IS NOT NULL
			END

		-- 7	语言能力
		IF @Pos = 7
			BEGIN
				SELECT @Chs = COUNT(1) FROM cvLanguage WITH(NOLOCK) WHERE cvMainID = @cvMainID
				SELECT @Eng = @Chs
			END

		-- 8	培训经历
		IF @Pos = 8
			BEGIN
				SELECT @Chs = COUNT(1) FROM cvTraining WITH(NOLOCK) WHERE cvMainID = @cvMainID AND Institution IS NOT NULL
				SELECT @Eng = COUNT(1) FROM cvTraining WITH(NOLOCK) WHERE cvMainID = @cvMainID AND InstitutionEng IS NOT NULL
			END

		-- 9	项目经历
		IF @Pos = 9
			BEGIN
				SELECT @Chs = COUNT(1) FROM cvProject WITH(NOLOCK) WHERE cvMainID = @cvMainID AND Name IS NOT NULL
				SELECT @Eng = COUNT(1) FROM cvProject WITH(NOLOCK) WHERE cvMainID = @cvMainID AND NameEng IS NOT NULL
			END

		-- 10	证书附件
		IF @Pos = 10
			BEGIN
				SELECT @Chs = COUNT(1) FROM cvAppendix WITH(NOLOCK) WHERE cvMainID = @cvMainID AND (dcAppendixID < 999 OR (dcAppendixID = 999 AND Name > ''))
				SELECT @Eng = COUNT(1) FROM cvAppendix WITH(NOLOCK) WHERE cvMainID = @cvMainID AND (dcAppendixID < 999 OR (dcAppendixID = 999 AND NameEng > ''))
			END

		SET @Chs = ISNULL(@Chs, 0)
		SET @Eng = ISNULL(@Eng, 0)

		IF @Chs > 0
			SET @Chs = 1

		IF @Eng > 0
			SET @Eng = 1
		
		EXEC pcCvMainByCvLevelUpdateNew 0, @cvMainID, @Pos, @Chs
		EXEC pcCvMainByCvLevelUpdateNew 1, @cvMainID, @Pos, @Eng
	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH
	SET @Return = LTRIM(STR(@Chs)) + LTRIM(STR(@Eng))
COMMIT TRAN
RETURN @Return
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 3
END














GO
/****** Object:  StoredProcedure [dbo].[pcCvMainByCvLevelUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		Sean
-- Create date: 2010-10-5
-- Description:	<Description,,>
-- 1	存在简历
-- 2	基本信息
-- 3	教育背景
-- 4	工作经历
-- 5	工作能力
-- 6	求职意向
-- 7	语言能力
-- 8	培训经历
-- 9	项目经历
-- 10	证书附件
--  修改cvmain的lastmodifydate和refreshdate
--检查：sean 2010-9-27
-- =============================================
CREATE PROCEDURE [dbo].[pcCvMainByCvLevelUpdate]
(
	@Type INT,
	@cvMainID INT,
	@pos INT,
	@cvLevel CHAR(1),
	@PamainID INT
)
AS
BEGIN TRAN
	BEGIN TRY
		DECLARE @Level AS VARCHAR(10),
			@cvName AS VARCHAR(100),
			@c AS CHAR(1)

		IF @Type = 0
		BEGIN
			SELECT @c = SUBSTRING(cvLevel, @pos, 1) FROM cvMain WITH(NOLOCK) WHERE ID = @cvMainID
			IF(@c <> @cvLevel)
				UPDATE cvmain SET cvLevel = dbo.ComputeCvLevel(cvLevel, @Pos, @cvLevel) WHERE ID = @cvMainID
		END
		ELSE
		BEGIN
			SELECT @c = SUBSTRING(cvLevelEng, @pos, 1) FROM cvMain WITH(NOLOCK) WHERE ID = @cvMainID
			IF(@c <> @cvLevel)
				UPDATE cvmain SET cvLevelEng = dbo.ComputeCvLevel(cvLevelEng, @Pos, @cvLevel) WHERE ID = @cvMainID
		END

		--SELECT @Level = cvLevel, @cvName = Name FROM cvMain WITH(NOLOCK) WHERE ID = @cvMainID
		--IF @cvName Is NULL
		--	UPDATE cvMain SET Name = '未完成简历' WHERE ID = @cvMainID
		
		UPDATE cvmain SET RefreshDate = GETDATE() WHERE ID = @cvMainID AND DATEADD(HOUR, 1, RefreshDate) < GETDATE()
	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH
COMMIT TRAN
RETURN 1
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END














GO
/****** Object:  StoredProcedure [dbo].[pcCvMainByCvLevelUpdateNew]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[pcCvMainByCvLevelUpdateNew]
(
	@Type INT,
	@cvMainID INT,
	@pos INT,
	@cvLevel CHAR(1)
)
AS
BEGIN TRAN
	BEGIN TRY
		DECLARE @Level AS VARCHAR(10),
			@cvName AS VARCHAR(100),
			@c AS CHAR(1)

		IF @Type = 0
		BEGIN
			SELECT @c = SUBSTRING(cvLevel, @pos, 1) FROM cvMain WITH(NOLOCK) WHERE ID = @cvMainID
			IF(@c <> @cvLevel)
				UPDATE cvmain SET cvLevel = dbo.ComputeCvLevel(cvLevel, @Pos, @cvLevel) WHERE ID = @cvMainID
		END
		ELSE
		BEGIN
			SELECT @c = SUBSTRING(cvLevelEng, @pos, 1) FROM cvMain WITH(NOLOCK) WHERE ID = @cvMainID
			IF(@c <> @cvLevel)
				UPDATE cvmain SET cvLevelEng = dbo.ComputeCvLevel(cvLevelEng, @Pos, @cvLevel) WHERE ID = @cvMainID
		END
		
		UPDATE cvmain SET RefreshDate = GETDATE() WHERE ID = @cvMainID AND DATEADD(HOUR, 1, RefreshDate) < GETDATE()
	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH
COMMIT TRAN
RETURN 1
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END














GO
/****** Object:  StoredProcedure [dbo].[pcCvMainByEngClearUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/**创建时间：2013-12-09 13:22
*创建人：Peter
*功能：清空英文简历
*/
CREATE PROCEDURE [dbo].[pcCvMainByEngClearUpdate]
(
	@cvMainID INT,
	@paMainID INT
)
AS
BEGIN TRAN
	BEGIN TRY
		--判断cvMainID是否属于该paMain
		DECLARE @CountTemp AS INT
		SELECT @CountTemp = COUNT(*) 
		FROM cvMain 
		WHERE id = @cvMainID AND paMainID = @paMainID
		IF @CountTemp = 1
		BEGIN
			--清空证书信息
			UPDATE cvAppendix 
			SET NameEng = NULL, DescriptionEng = NULL 
			WHERE cvMainID = @cvMainID

			--清空教育信息
			UPDATE cvEducation
			SET GraduateCollageEng = NULL, MajorNameEng = NULL, DetailsEng = NULL
			WHERE cvMainID = @cvMainID
			
			--清空工作经历信息
			UPDATE cvExperience
			SET CompanyNameEng = NULL, JobNameEng = NULL, DescriptionEng = NULL, DeptEng = NULL, UpperPostEng = NULL
			WHERE cvMainID = @cvMainID

			--清空语言信息
			UPDATE cvLanguage
			SET ScoreEng = NULL
			WHERE cvMainID = @cvMainID

			--清空项目经历信息
			UPDATE cvProject
			SET NameEng = NULL, DescriptionEng = NULL, ResponsibilitiesEng = NULL
			WHERE cvMainID = @cvMainID

			--清空培训经历信息
			UPDATE cvTraining
			SET InstitutionEng = NULL, CourseEng = NULL, CityEng = NULL, CertificateEng = NULL, DetailsEng = NULL
			WHERE cvMainID = @cvMainID
			
			--清空paMain中的英文名称
			UPDATE paMain
			SET NameEng = NULL
			WHERE ID = @paMainID

			--清空CvMain中的信息
			UPDATE cvMain
			SET SpecialityEng = NULL, VerifyResultEng = 0, cvLevelEng = '1000000000'
			WHERE ID = @cvMainID

			--删除修改日志里该简历的数据
			DELETE FROM bsCvModify
			WHERE cvMainID = @cvMainID 
			AND paMainID = @paMainID 
			AND Location LIKE '_e_'
		END
		ELSE
		BEGIN
			RETURN -1
		END
 	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH
COMMIT TRAN
RETURN 1
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END
















GO
/****** Object:  StoredProcedure [dbo].[pcCvMainByIscvHiddenUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--====================================
--检查：	Sean，2010-10-5
--说明：	隐藏简历
--在ajax文件中判断caMain.paMainID = pa.ID 
--====================================
CREATE PROCEDURE [dbo].[pcCvMainByIscvHiddenUpdate]
	@ID INT,
	@IscvHidden INT,		----0:不隐藏；1：隐藏
	@paMainID INT
AS
BEGIN
	BEGIN TRY
		UPDATE CvMain SET IscvHidden = @IscvHidden WHERE ID = @ID AND paMainID = @paMainID
		RETURN 1
	END TRY
	BEGIN CATCH
		RETURN 0
	END CATCH
END














GO
/****** Object:  StoredProcedure [dbo].[pcCvMainByIsNameHiddenUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
--检查：	Sean，2010-12-9
--说明：	隐藏姓名
--在ajax文件中判断caMain.paMainID = pa.ID 
-- =============================================
CREATE PROCEDURE [dbo].[pcCvMainByIsNameHiddenUpdate]
	@ID INT,
	@IsNameHidden INT,		----0:不隐藏；1：隐藏
	@paMainID INT
AS
BEGIN TRY
	IF NOT EXISTS(SELECT 'x' FROM cvMain WITH(NOLOCK) WHERE ID = @ID AND paMainID = @paMainID)
		RETURN 0

	UPDATE CvMain SET IsNameHidden = @IsNameHidden WHERE ID = @ID
	RETURN 1
END TRY
BEGIN CATCH
	RETURN 0
END CATCH














GO
/****** Object:  StoredProcedure [dbo].[pcCvMainByNameUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--=============================================
-- 检查：		Sean
-- 时间：		2010-9-28
-- 描述：		取消了对简历名称的审核，取消了对cvlevel的修改，cvlevel做第一位一直是1。
--修改：Lambo，2010-11-25
--描述：增加了paMainID参数，判断是否是本人的
--=============================================
CREATE PROCEDURE [dbo].[pcCvMainByNameUpdate]
(
	@Type INT,
	@ID INT,
	@paMainID INT,
	@Name VARCHAR(100)
)
AS
SET NOCOUNT ON
IF LEN(ISNULL(@Name, '')) = 0
	RETURN 0
IF CHARINDEX('<', @Name) > 0
	SET @Name = REPLACE(@Name, '<', '')
BEGIN TRAN
	BEGIN TRY
		IF NOT EXISTS(SELECT 'x' FROM cvMain WITH(NOLOCK) WHERE ID = @ID AND paMainID = @paMainID)
			GOTO ERR
		SET @Name = dbo.SafeSql(@Name)
		DECLARE @N NVARCHAR(20)
		SET @N = @Name
		IF @Type = 0
			UPDATE CvMain SET Name = @N WHERE ID = @ID
		ELSE
			UPDATE CvMain SET Name = @Name WHERE ID = @ID
	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH
COMMIT TRAN
RETURN 1
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END

GO
/****** Object:  StoredProcedure [dbo].[pcCvMainByNoExpCreate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[pcCvMainByNoExpCreate]
(
	@paMainID INT,
	@IP VARCHAR(39)
)
AS
BEGIN TRY
	DECLARE @Count INT
	SELECT @Count=COUNT(*) FROM cvMain WITH(NOLOCK INDEX(IX_cvMain_paMainID)) WHERE paMainID=@paMainID
	--已经有3份简历
	IF @Count>2
		RETURN 0
	ELSE
	BEGIN
		DECLARE @Mobile VARCHAR(13), @Name VARCHAR(20), @cvLevel AS CHAR(10), @cvLevelEng AS CHAR(10)
		SELECT @cvLevel = '1000000000', @cvLevelEng = '1000000000'

		SELECT @Name = ISNULL(Name, ''), @Mobile = ISNULL(Mobile, '') FROM paMain WITH(NOLOCK INDEX(PK_paMain)) WHERE ID = @paMainID
		IF (LEN(@Mobile) > 0 AND LEN(@Name) > 0)
		BEGIN
			SELECT @cvLevel = '1100000000', @cvLevelEng = '1100000000'	
		END

		BEGIN TRAN
			DECLARE @cvMainID AS INT
			INSERT INTO cvMain(paMainID, Name, cvLevel, cvLevelEng, cvType)
			VALUES(@paMainID, '未完成简历', @cvLevel, @cvLevelEng,1)
			SET @cvMainID = @@IDENTITY

			INSERT INTO paOperationLog (paMainID,Operation,Details,IP)
			VALUES(@paMainID, 14, '创建简历，编号' + RTRIM(CONVERT(VARCHAR(10),@cvMainID)), @IP)

		COMMIT
		RETURN @cvMainID
	END	
END TRY
BEGIN CATCH
	PRINT ''
	ROLLBACK TRAN
	RETURN 0
END CATCH














GO
/****** Object:  StoredProcedure [dbo].[pcCvMainByPaMainIDBaseSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[pcCvMainByPaMainIDBaseSelect]
(
	@paMainID INT
)
AS
BEGIN
	SELECT ID,
		paMainID,
		Name,
		IsNameHidden,
		IscvHidden,
		isOpen,
		cvLevel,
		cvLevelEng,
		VerifyResult,
		VerifyResultEng,
		Valid,
		ViewNumber,
		RefreshDate,
                   Attachment,
		cvType,
		JobName
	FROM cvMain WITH(NOLOCK) 
	WHERE paMainID=@paMainID
	ORDER BY RefreshDate DESC, ID
END














GO
/****** Object:  StoredProcedure [dbo].[pcCvMainByPaMainIDMinSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--====================================
--Creatoe：		sean，2011-8-4
--主要用于个人用户自己的查看，而不是搜索，所以不加valid>0条件
--====================================
CREATE PROCEDURE [dbo].[pcCvMainByPaMainIDMinSelect]
(
	@paMainID INT
)
AS
BEGIN
	SELECT ID, Name
	FROM cvMain WITH(NOLOCK) 
	WHERE paMainID=@paMainID
	ORDER BY RefreshDate DESC, ID
END














GO
/****** Object:  StoredProcedure [dbo].[pcCvMainByPaMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--====================================
--检查：		sean，2010-10-5
--主要用于个人用户自己的查看，而不是搜索，所以不加valid>0条件
--====================================
CREATE PROCEDURE [dbo].[pcCvMainByPaMainIDSelect]
(
	@paMainID INT
)
AS
BEGIN
	SELECT *
	FROM cvMain WITH(NOLOCK) 
	WHERE paMainID=@paMainID
	ORDER BY RefreshDate DESC, ID
END














GO
/****** Object:  StoredProcedure [dbo].[pcCvMainByRecommendSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[pcCvMainByRecommendSelect]
	@paMainID INT
AS
BEGIN
	SELECT
		ID,
		paMainID,
		Name,
		EmployType,
		dcSalaryID,
		Attachment,
		WordFileNAme,
		cvType,
		IsNameHidden,
		IscvHidden,
		isOpen,
		cvLevel,
		cvLevelEng,
		VerifyResult,
		VerifyResultEng,
		Valid,
		ViewNumber,
		RefreshDate,
		Degree
	FROM cvMain WITH(NOLOCK) 
	WHERE paMainID=@paMainID
	AND ((cvLevel like '1111_1%' AND VerifyResult=1) OR (cvLevelEng like '1111_1%' AND VerifyResultEng=1))
END














GO
/****** Object:  StoredProcedure [dbo].[pcCvMainBySpecialitySelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- 创建:		Sean
-- 检查:		2010-9-27
-- 说明：		提取工作能力
-- =============================================
CREATE PROCEDURE [dbo].[pcCvMainBySpecialitySelect]
	@Type INT,
	@ID INT,
	@Speciality NVARCHAR(Max) OutPut
AS
BEGIN
	IF @Type=0
		SELECT @Speciality=Speciality FROM cvMain WITH(NOLOCK) WHERE ID = @ID
	ELSE
		SELECT @Speciality=SpecialityEng FROM cvMain WITH(NOLOCK) WHERE ID = @ID
END














GO
/****** Object:  StoredProcedure [dbo].[pcCvMainBySpecialityUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[pcCvMainBySpecialityUpdate]
(
	@Type INT,
	@ID INT,
	@Speciality VARCHAR(MAX),
	@paMainID INT
)
AS
SET NOCOUNT ON
IF CHARINDEX('<', @Speciality) > 0
	SET @Speciality = REPLACE(@Speciality, '<', '&lt;')
BEGIN TRAN
	BEGIN TRY
		IF NOT EXISTS(SELECT 'x' FROM cvMain WITH(NOLOCK) WHERE ID = @ID AND paMainID = @paMainID)
			GOTO err

		SET @Speciality = dbo.SafeSql(dbo.TextTrim(@Speciality))

		DECLARE @SpecialityOld VARCHAR(MAX)
		DECLARE @S NVARCHAR(2000)
		
		IF @Type=0
			BEGIN
				SELECT @SpecialityOld = dbo.TextTrim(Speciality) FROM cvMain WHERE ID = @ID
				SET @S=@Speciality
				IF ISNULL(@SpecialityOld, '') <> ISNULL(@S, '')
					BEGIN
						UPDATE cvMain SET Speciality = @S WHERE ID = @ID
						DELETE FROM bsCvModify WHERE cvMainID=@ID AND Location = 'bc2'
						IF @S IS NOT NULL
							INSERT INTO bsCvModify(paMainID,cvMainID,Location,ColValue) VALUES(@paMainID,@ID,'bc2',@S)
					END
			END
		ELSE
			BEGIN
				SELECT @SpecialityOld = dbo.TextTrim(SpecialityEng) FROM cvMain WHERE ID = @ID
				IF ISNULL(@SpecialityOld, '') <> ISNULL(@Speciality, '')
					BEGIN
						UPDATE cvMain SET SpecialityEng = @Speciality WHERE ID = @ID
						DELETE FROM bsCvModify WHERE cvMainID=@ID AND Location = 'be2'
						IF @Speciality IS NOT NULL
							INSERT INTO bsCvModify(paMainID,cvMainID,Location,ColValue) VALUES(@paMainID,@ID,'be2',@Speciality)
					END
			END
		--修改cvLevel
		DECLARE @SQL AS VARCHAR(100)
		IF @Speciality >''
			SET @SQL = 'EXEC pcCvMainByCvLevelUpdateNew ' + CONVERT(CHAR(1), @Type) + ',' + CONVERT(VARCHAR(10), @ID) + ',5,1'
		ELSE
			SET @SQL = 'EXEC pcCvMainByCvLevelUpdateNew ' + CONVERT(CHAR(1), @Type) + ',' + CONVERT(VARCHAR(10), @ID) + ',5,0'
		EXEC(@SQL)
	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH
COMMIT TRAN
RETURN 1
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END



GO
/****** Object:  StoredProcedure [dbo].[pcCvMainByWordCreate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Sean
-- Create date: 2010-10-5
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[pcCvMainByWordCreate]
(
	@paMainID INT,
	@IP VARCHAR(39)
)
AS
BEGIN TRY
	DECLARE @Count INT
	SELECT @Count = COUNT(*) FROM cvMain WITH(NOLOCK INDEX(IX_cvMain_paMainID)) WHERE paMainID = @paMainID
	--已经有3份简历
	IF @Count>2
		RETURN 0
	ELSE
	BEGIN
		DECLARE @Mobile VARCHAR(13), @Name VARCHAR(20), @cvLevel AS CHAR(10), @cvLevelEng AS CHAR(10)
		SELECT @cvLevel = '1000000000', @cvLevelEng = '1000000000'

		SELECT @Name = ISNULL(Name, ''), @Mobile = ISNULL(Mobile, '') FROM paMain WITH(NOLOCK INDEX(PK_paMain)) WHERE ID = @paMainID
		IF (LEN(@Mobile) > 0 AND LEN(@Name) > 0)
		BEGIN
			SELECT @cvLevel = '1100000000', @cvLevelEng = '1100000000'	
		END

		BEGIN TRAN
			DECLARE @cvMainID AS INT
			INSERT INTO cvMain(paMainID, Name, cvLevel, cvLevelEng, JobName)
			VALUES(@paMainID, '未完成简历', @cvLevel, @cvLevelEng, '附件简历')
			SET @cvMainID = @@IDENTITY

			INSERT INTO paOperationLog (paMainID,Operation,Details,IP)
			VALUES(@paMainID, 14, '创建简历，编号' + RTRIM(CONVERT(VARCHAR(10),@cvMainID)), @IP)

		COMMIT
		RETURN @cvMainID
	END	
END TRY
BEGIN CATCH
	PRINT ''
	ROLLBACK TRAN
	RETURN 0
END CATCH














GO
/****** Object:  StoredProcedure [dbo].[pcCvMainCreate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Sean
-- Create date: 2010-10-5
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[pcCvMainCreate]
(
	@paMainID INT,
	@IP VARCHAR(39)
)
AS
SET NOCOUNT ON
BEGIN TRY
	DECLARE @Count INT
	SELECT @Count=COUNT(*) FROM cvMain WITH(NOLOCK INDEX(IX_cvMain_paMainID)) WHERE paMainID = @paMainID
	--已经有3份简历
	IF @Count>2
	BEGIN
		DELETE FROM cvMain WHERE paMainid = @paMainID AND cvLevel = '1100000000' AND Name = '未完成简历'
		SELECT @Count=COUNT(*) FROM cvMain WITH(NOLOCK INDEX(IX_cvMain_paMainID)) WHERE paMainID = @paMainID
		--已经有3份简历
		IF @Count>2
			RETURN 0
	END
	ELSE
	BEGIN
		DECLARE @Mobile VARCHAR(13), @Name VARCHAR(20), @cvLevel AS CHAR(10), @cvLevelEng AS CHAR(10)
		SELECT @cvLevel = '1000000000', @cvLevelEng = '1000000000'

		SELECT @Name = ISNULL(Name, ''), @Mobile = ISNULL(Mobile, '') FROM paMain WITH(NOLOCK INDEX(PK_paMain)) WHERE ID = @paMainID
		IF (LEN(@Mobile) > 0 AND LEN(@Name) > 0)
		BEGIN
			SELECT @cvLevel = '1100000000', @cvLevelEng = '1100000000'	
		END

		BEGIN TRAN
			DECLARE @cvMainID AS INT
			INSERT INTO cvMain(paMainID, Name, cvLevel, cvLevelEng)
			VALUES(@paMainID, '未完成简历', @cvLevel, @cvLevelEng)
			SET @cvMainID = @@IDENTITY

			INSERT INTO paOperationLog (paMainID,Operation,Details,IP)
			VALUES(@paMainID, 14, '创建简历，编号' + RTRIM(CONVERT(VARCHAR(10),@cvMainID)), @IP)

			UPDATE dcSystemData SET Value = Value + RAND() * 5.4 WHERE ID = 1
		COMMIT
		--PRINT @cvMainID
		RETURN @cvMainID
	END	
END TRY
BEGIN CATCH
	PRINT ''
	ROLLBACK TRAN
	RETURN 0
END CATCH














GO
/****** Object:  StoredProcedure [dbo].[pcCvMainCvTypeUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--===================================
--检查：	Sean,2010-10-5
--修改：Lambo，2010-11-25
--描述：增加了paMainID参数，判断是否是本人的
--===================================
CREATE PROCEDURE [dbo].[pcCvMainCvTypeUpdate]
(
	@ID INT,
	@cvType TINYINT,
	@paMainID INT
)
AS
BEGIN
	BEGIN TRY
		IF NOT EXISTS(SELECT 'x' FROM cvMain WITH(NOLOCK) WHERE ID = @ID AND paMainID = @paMainID)
			RETURN 0

		UPDATE CvMain SET cvType = @cvType WHERE ID = @ID
		DECLARE @SQL AS VARCHAR(100)
		IF @cvType = 1
			BEGIN				
				SET @SQL = 'EXEC pcCvMainByCvLevelUpdateNew 0,' + CONVERT(VARCHAR(10),@ID) + ',4,1'
				EXEC(@SQL)
				SET @SQL = 'EXEC pcCvMainByCvLevelUpdateNew 1,' + CONVERT(VARCHAR(10),@ID) + ',4,1'
				EXEC(@SQL)
			END
		ELSE
			BEGIN				
				IF NOT EXISTS(SELECT ID FROM cvExperience WITH(NOLOCK INDEX(IX_cvExperience_cvMainID)) WHERE cvMainID = @ID AND CompanyName>'')
					BEGIN
						SET @SQL = 'EXEC pcCvMainByCvLevelUpdateNew 0,' + CONVERT(VARCHAR(10),@ID) + ',4,0'
						EXEC(@SQL)
					END
				IF NOT EXISTS(SELECT ID FROM cvExperience WITH(NOLOCK INDEX(IX_cvExperience_cvMainID)) WHERE cvMainID = @ID AND CompanyNameEng>'')
					BEGIN
						SET @SQL = 'EXEC pcCvMainByCvLevelUpdateNew 1,' + CONVERT(VARCHAR(10),@ID) + ',4,0'
						EXEC(@SQL)
					END
			END	
		RETURN 1
	END TRY
	BEGIN CATCH
		RETURN 0
	END CATCH
END














GO
/****** Object:  StoredProcedure [dbo].[pcCvMainDelete]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--====================================
--检查：		Sean，2010-10-5
--说明：	假删改为真删
--====================================
CREATE PROCEDURE [dbo].[pcCvMainDelete]
	@ID INT,
	@paMainID INT,
	@IP VARCHAR(30)
AS
SET NOCOUNT ON
BEGIN TRAN
	BEGIN TRY
		DECLARE @paID AS INT
		SELECT @paID = paMainID FROM cvMain WITH(NOLOCK INDEX(PK_cvMain)) WHERE ID = @ID
		IF @paMainID <> @paID
			GOTO Err

		INSERT INTO paOperationLog (paMainID,Operation,Details,IP)
			VALUES(@paID, 15, '删除简历，编号'+RTRIM(CONVERT(VARCHAR(10),@ID)), @IP)

		DELETE FROM cvMain WHERE ID=@ID

	END TRY
	BEGIN CATCH
		PRINT '错误编号' + CONVERT(VARCHAR(10),ERROR_NUMBER()) + '错误发生的行号' + CONVERT(VARCHAR(10),ERROR_LINE()) +'错误信息' + ERROR_MESSAGE()
		GOTO ERR
	END CATCH
COMMIT TRAN
RETURN 1
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END














GO
/****** Object:  StoredProcedure [dbo].[pcCvMainDetailByIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.31
--创建人：Nick
--说明：获取简历对应的年龄、学历、工作年限、性别、工作地点
--#####################################################
CREATE PROCEDURE [dbo].[pcCvMainDetailByIDSelect]
(
	@CvMainID INT
)
AS
BEGIN TRY
	SELECT b.LivePlace,b.gender,dbo.BirthToAge(b.birthday) AS age,a.dcMajorID,
	a.RelatedWorkYears,c.dcRegionID, a.Degree, a.Attachment 
	FROM cvmain a,pamain b,cvjobPlace c 
	WHERE a.id=@CvMainID 
	AND a.pamainID=b.ID 
	AND a.id=c.cvMainID
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[pcCvMainIDByJobApplyIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.4
--创建人：John
--说明：根据JobApplyID取得CvMainID
--#####################################################
CREATE PROCEDURE [dbo].[pcCvMainIDByJobApplyIDSelect]
(
	@PaMainID INT
)
AS
BEGIN
	DECLARE @CvMainID INT
	SET @CvMainID = 0
	SELECT @CvMainID = cvMainID FROM
		(
			SELECT TOP 1 cvMainID
			FROM exJobApply WITH(NOLOCK) 
			WHERE cvMainID IN ( SELECT ID FROM cvMain WITH(NOLOCK) WHERE paMainID = @PaMainID )
			ORDER BY AddDate DESC
		) TEMP1
	IF @CvMainID = 0
	BEGIN
		SELECT @CvMainID = ID FROM
			(
				SELECT TOP 1 ID 
				FROM cvMain WITH(NOLOCK) 
				WHERE paMainID = @PaMainID 
				ORDER BY RefreshDate DESC
			) TEMP2
	END
	RETURN @CvMainID
END


GO
/****** Object:  StoredProcedure [dbo].[pcCvMainIDByPaMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.10
--创建人：Nick
--说明：
--#####################################################
CREATE PROCEDURE [dbo].[pcCvMainIDByPaMainIDSelect]
(
	@cvMainID INT,
	@paMainID INT
)
AS
BEGIN TRY
	IF @cvMainID = 0
	BEGIN
		SELECT TOP 1 ID 
		FROM cvMain WITH(NOLOCK) 
		WHERE (
			cvLevel like '111111%' 
			OR cvLevelEng LIKE '111111%' 
			OR cvLevel like '111101%' 
			OR cvLevelEng LIKE '111101%'
		) AND paMainID = @paMainID ORDER BY ID DESC
	END
	ELSE 
	BEGIN
		SELECT TOP 1 ID 
		FROM cvMain WITH(NOLOCK) 
		WHERE (
			cvLevel like '111111%' 
			OR cvLevelEng LIKE '111111%' 
			OR cvLevel like '111101%' 
			OR cvLevelEng LIKE '111101%'
		) AND paMainID = @paMainID And ID = @cvMainID
	END
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[pcCvMainNameByIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.31
--创建人：Nick
--说明：获取简历名称
--#####################################################
CREATE PROCEDURE [dbo].[pcCvMainNameByIDSelect]
(
	@ID INT
)
AS
BEGIN TRY
	SELECT Name FROM cvMain WHERE ID = @ID
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[pcCvMainNameByPamainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.31
--创建人：Nick
--说明：获取简历名称
--#####################################################
CREATE PROCEDURE [dbo].[pcCvMainNameByPamainIDSelect]
(
	@paMainID INT
)
AS
BEGIN TRY
	SELECT ID, Name FROM cvMain WITH(NOLOCK) Where VerifyResult=10 And paMainID=@paMainID ORDER BY ID
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[pcCvMainResultByPaMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.31
--创建人：Nick
--说明：获取CVMAIN
--#####################################################
CREATE PROCEDURE [dbo].[pcCvMainResultByPaMainIDSelect]
(
	@PamainID INT
)
AS
BEGIN TRY
	SELECT * FROM cvMain WITH(NOLOCK) 
	WHERE paMainID = @PamainID 
	AND (AttachMent <> '' OR((cvLevel LIKE '111111%' OR cvLevel LIKE '111101%') AND VerifyResult = 1) 
		OR((cvLevelEng LIKE '111111%' OR cvLevelEng LIKE '111101%') AND VerifyResultEng = 1))
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[pcCvMainSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[pcCvMainSelect]
	@ID INT
AS
BEGIN
	SELECT *,dbo.GetPaOnlineStatus(paMainID) IsOnline
	FROM cvMain WITH(NOLOCK INDEX(PK_cvMain))
	WHERE ID=@ID
END






GO
/****** Object:  StoredProcedure [dbo].[pcCvMainSelectTest]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[pcCvMainSelectTest]
(
    @ID INT
)
AS
BEGIN
    SELECT *,dbo.GetPaOnlineStatus(paMainID) IsOnline
    FROM cvMain WITH(NOLOCK INDEX(PK_cvMain))
    WHERE ID=@ID
END
GO
/****** Object:  StoredProcedure [dbo].[pcCvMainVerifyResultCheck_OLD]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--==============================================
-- 名称：		pcCvMainVerifyResultCheck
-- 删除：		Sean
-- 时间：		2010-9-29
-- 原因：		VerifyResult修改后不变，只有审核时变化，审核时列表不从cvMain提取，所以该存储过程应该无用了
--==============================================
CREATE PROCEDURE [dbo].[pcCvMainVerifyResultCheck_OLD]
	@cvMainID INT
AS
BEGIN TRAN
	BEGIN TRY
		IF EXISTS(SELECT ID FROM bsCvModify WITH(NOLOCK)WHERE cvMainID=@cvMainID AND SUBSTRING(Location,2,1)='c' AND SUBSTRING(Location,1,1)<>'a')
			UPDATE cvMain SET VerifyResult=11 WHERE ID=@cvMainID
		ELSE
			UPDATE cvMain SET VerifyResult=100 WHERE ID=@cvMainID

		IF EXISTS(SELECT ID FROM bsCvModify WITH(NOLOCK)WHERE cvMainID=@cvMainID AND SUBSTRING(Location,2,1)='e' AND SUBSTRING(Location,1,1)<>'a')
			UPDATE cvMain SET VerifyResultEng=11 WHERE ID=@cvMainID
		ELSE
			UPDATE cvMain SET VerifyResultEng=100 WHERE ID=@cvMainID
	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH
COMMIT TRAN
RETURN 1
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END














GO
/****** Object:  StoredProcedure [dbo].[pcCvProjectByIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------===========================
-- 检查:		sean
-- 时间:		2010-9-29
-- 描述：		提取项目信息
-------===========================
CREATE PROCEDURE [dbo].[pcCvProjectByIDSelect]
	@ID INT
AS
BEGIN
	SELECT *
	FROM CvProject WITH(NOLOCK INDEX(PK_cvProject))
	WHERE ID = @ID
END














GO
/****** Object:  StoredProcedure [dbo].[pcCvProjectDelete]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-------===========================
-- 检查:		sean
-- 时间:		2010-9-29
-- 描述：		删除项目信息  取消pcCvMainByCvLevelUpdate，取消pcCvMainVerifyResultCheck
-- 修改：Lambo，2010-11-25
-- 描述：增加了paMainID参数，判断是否是本人的
-------===========================
CREATE PROCEDURE [dbo].[pcCvProjectDelete]
	@ID INT,
	@paMainID INT
AS
BEGIN TRAN
	BEGIN TRY
		DECLARE @cvMainId AS INT
		DECLARE @RETURN AS VARCHAR(2)
		SELECT @cvMainId = cvMainId FROM cvProject WITH(NOLOCK) WHERE ID=@ID
		
		IF @cvMainId IS NULL
			GOTO ERR

		IF NOT EXISTS(SELECT 'x' FROM cvMain WITH(NOLOCK)
						WHERE paMainID = @paMainID AND ID = @cvMainID)
			GOTO ERR

		DELETE FROM bsCvModify WHERE SubID = @ID AND Location LIKE 'f%'
		DELETE FROM cvProject WHERE ID=@ID
		EXEC @RETURN = pcCvMainByCvLevelCheck @cvMainID, 9
	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH
COMMIT TRAN
RETURN @RETURN
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 3
END














GO
/****** Object:  StoredProcedure [dbo].[pcCvProjectSave]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--===============================
-- 检查：		sean
-- 时间：		2010-9-29
-- 描述：		取消pcCvMainByCvLevelUpdate， pcCvMainVerifyResultUpdate
-- 修改：Lambo，2010-11-25
-- 描述：增加了paMainID参数，判断是否是本人的
--===============================
CREATE PROCEDURE [dbo].[pcCvProjectSave]
(
	@Type INT,
	@ID INT,
	@cvMainID INT,
	@Name VARCHAR(250),
	@StartDate INT,
	@ENDDate INT,
	@Description VARCHAR(MAX),
	@Responsibilities VARCHAR(1000),
	@paMainID INT
)
AS
SET NOCOUNT ON
IF CHARINDEX('<', @Description) > 0
	SET @Description = REPLACE(@Description, '<', '')
IF CHARINDEX('<', @Responsibilities) > 0
	SET @Responsibilities = REPLACE(@Responsibilities, '<', '')
IF CHARINDEX('<', @Name) > 0
	SET @Name = REPLACE(@Name, '<', '')
BEGIN TRAN
	----检查是否是该账号的简历
	IF NOT EXISTS(SELECT 'x' FROM cvMain WITH(NOLOCK) WHERE ID = @cvMainID AND paMainID = @paMainID)
		GOTO ERR
	----检查是否是该简历的工作经验
	IF @ID > 0
		IF NOT EXISTS(SELECT 'x' FROM cvProject WITH(NOLOCK) WHERE ID = @ID AND cvMainID = @cvMainID)
			GOTO ERR

	SELECT @Name = dbo.SafeSql(dbo.TextTrim(@Name)),
		@Description = dbo.SafeSql(dbo.TextTrim(@Description)),
		@Responsibilities = dbo.SafeSql(dbo.TextTrim(@Responsibilities))

	DECLARE @MaxId AS INT
	DECLARE @NameOld AS VARCHAR(250)
	DECLARE @DescriptionOld AS VARCHAR(MAX)
	DECLARE @ResponsibilitiesOld AS VARCHAR(1000)
	DECLARE @Modify AS INT
	SET @Modify=-1

	BEGIN TRY
		IF NOT EXISTS(SELECT 'x' FROM cvMain WITH(NOLOCK) WHERE ID =@cvMainID AND paMainID = @paMainID)
			GOTO ERR
		IF @Type=0
		BEGIN
			DECLARE @N AS NVARCHAR(50)
			DECLARE @R AS NVARCHAR(200)
			DECLARE @D AS NVARCHAR(2000)
			SET @N = @Name
			SET @D = @Description
			SET @R = @Responsibilities
			IF @ID>0
			BEGIN
				IF NOT EXISTS(SELECT 'x' FROM CvProject WITH(NOLOCK) WHERE ID =@ID AND cvMainID = @cvMainID)
					GOTO ERR
				SELECT @NameOld = dbo.TextTrim(ISNULL(Name, '')),
					@DescriptionOld = dbo.TextTrim(ISNULL(Description, '')),
					@ResponsibilitiesOld = dbo.TextTrim(ISNULL(Responsibilities, ''))
					FROM CvProject WITH(NOLOCK) WHERE ID = @ID

				UPDATE CvProject SET
					Name = @N,
					StartDate = @StartDate,
					ENDDate = @ENDDate,
					Description = @D,
					Responsibilities = @R
				WHERE ID=@ID
				SET @MaxID = @ID
				
				IF ISNULL(@NameOld, '') <> ISNULL(@N, '')
				BEGIN
					DELETE FROM bsCvModify WHERE SubID = @ID AND Location = 'fc1'
					INSERT INTO bsCvModify(paMainID,cvMainID,SubID,Location,ColValue) VALUES(@paMainID,@cvMainID,@MaxID,'fc1',@N)
					SET @Modify=0
				END

				IF @D IS NULL
					DELETE FROM bsCvModify WHERE paMainID=@paMainID AND cvMainID=@cvMainID AND SubID = @ID AND Location = 'fc2'
				ELSE
					IF ISNULL(@DescriptionOld, '') <> @D
					BEGIN
						DELETE FROM bsCvModify WHERE paMainID=@paMainID AND cvMainID=@cvMainID AND SubID = @ID AND Location = 'fc2'
						INSERT INTO bsCvModify(paMainID,cvMainID,SubID,Location,ColValue) VALUES(@paMainID,@cvMainID,@MaxID,'fc2',@D)
						SET @Modify=0
					END

				IF @R IS NULL
					DELETE FROM bsCvModify WHERE paMainID=@paMainID AND cvMainID=@cvMainID AND SubID = @ID AND Location = 'fc3'
				ELSE
					IF ISNULL(@ResponsibilitiesOld, '') <> @R
					BEGIN
						DELETE FROM bsCvModify WHERE paMainID=@paMainID AND cvMainID=@cvMainID AND SubID = @ID AND Location = 'fc3'
						INSERT INTO bsCvModify(paMainID,cvMainID,SubID,Location,ColValue) VALUES(@paMainID,@cvMainID,@MaxID,'fc3',@R)
						SET @Modify=0
					END
			END
			ELSE
			BEGIN
				INSERT INTO CvProject
					(cvMainID,Name,StartDate,ENDDate,Description,Responsibilities)
				VALUES(@cvMainID,@Name,@StartDate,@ENDDate,@D,@R)
				SET @MaxID = @@IDENTITY
				SET @Modify=0

				INSERT INTO bsCvModify(paMainID,cvMainID,SubID,Location,ColValue) VALUES(@paMainID,@cvMainID,@MaxID,'fc1',@N)
				IF @D > ''
					INSERT INTO bsCvModify(paMainID,cvMainID,SubID,Location,ColValue) VALUES(@paMainID,@cvMainID,@MaxID,'fc2',@D)
				IF @R > ''
					INSERT INTO bsCvModify(paMainID,cvMainID,SubID,Location,ColValue) VALUES(@paMainID,@cvMainID,@MaxID,'fc3',@R)
			END
		END
		ELSE
		BEGIN
			IF NOT EXISTS(SELECT 'x' FROM cvMain WITH(NOLOCK) WHERE ID =@cvMainID AND paMainID = @paMainID)
				GOTO ERR
			IF @ID>0
			BEGIN
				IF NOT EXISTS(SELECT 'x' FROM CvProject WITH(NOLOCK) WHERE ID =@ID AND cvMainID = @cvMainID)
					GOTO ERR

				SELECT @NameOld = dbo.TextTrim(ISNULL(NameEng, '')),
					@DescriptionOld = dbo.TextTrim(ISNULL(DescriptionEng, '')),
					@ResponsibilitiesOld = dbo.TextTrim(ISNULL(ResponsibilitiesEng, ''))
					FROM CvProject WITH(NOLOCK) WHERE ID = @ID

				UPDATE CvProject SET
					NameEng = @Name,
					StartDate = @StartDate,
					ENDDate = @ENDDate,
					DescriptionEng = @Description,
					ResponsibilitiesEng = @Responsibilities
				WHERE ID=@ID
				SET @MaxID = @ID

				IF ISNULL(@NameOld, '') <> ISNULL(@Name, '')
				BEGIN
					DELETE FROM bsCvModify WHERE SubID = @ID AND Location = 'fe1'
					INSERT INTO bsCvModify(paMainID,cvMainID,SubID,Location,ColValue) VALUES(@paMainID,@cvMainID,@MaxID,'fe1',@Name)
					SET @Modify=1
				END

				IF @Description IS NULL
					DELETE FROM bsCvModify WHERE paMainID=@paMainID AND cvMainID=@cvMainID AND SubID = @ID AND Location = 'fe2'
				ELSE
					IF ISNULL(@DescriptionOld, '') <> @Description
					BEGIN
						DELETE FROM bsCvModify WHERE paMainID=@paMainID AND cvMainID=@cvMainID AND SubID = @ID AND Location = 'fe2'
						INSERT INTO bsCvModify(paMainID,cvMainID,SubID,Location,ColValue) VALUES(@paMainID,@cvMainID,@MaxID,'fe2',@Description)
						SET @Modify=1
					END

				IF @Responsibilities IS NULL
					DELETE FROM bsCvModify WHERE paMainID=@paMainID AND cvMainID=@cvMainID AND SubID = @ID AND Location = 'fe3'
				ELSE
					IF ISNULL(@ResponsibilitiesOld, '') <> @Responsibilities
					BEGIN
						DELETE FROM bsCvModify WHERE paMainID=@paMainID AND cvMainID=@cvMainID AND SubID = @ID AND Location = 'fe3'
						INSERT INTO bsCvModify(paMainID,cvMainID,SubID,Location,ColValue) VALUES(@paMainID,@cvMainID,@MaxID,'fe3',@Responsibilities)
						SET @Modify=1
					END
			END
			ELSE
			BEGIN
				INSERT INTO CvProject
					(cvMainID,NameEng,StartDate,ENDDate,DescriptionEng,ResponsibilitiesEng)
				VALUES(@cvMainID,@Name,@StartDate,@ENDDate,@Description,@Responsibilities)
				SET @MaxID = @@IDENTITY
				SET @Modify=1

				INSERT INTO bsCvModify(paMainID,cvMainID,SubID,Location,ColValue) VALUES(@paMainID,@cvMainID,@MaxID,'fe1',@Name)
				IF @Description > ''
					INSERT INTO bsCvModify(paMainID,cvMainID,SubID,Location,ColValue) VALUES(@paMainID,@cvMainID,@MaxID,'fe2',@Description)
				IF @Responsibilities > ''
					INSERT INTO bsCvModify(paMainID,cvMainID,SubID,Location,ColValue) VALUES(@paMainID,@cvMainID,@MaxID,'fe3',@Responsibilities)
			END
		END
		--修改cvLevel
		DECLARE @SQL AS VARCHAR(100)
		SET @SQL = 'EXEC pcCvMainByCvLevelUpdateNew ' + CONVERT(CHAR(1), @Type) + ',' + CONVERT(VARCHAR(10), @cvMainID) + ',9,1'
		EXEC(@SQL)
	END TRY
	BEGIN cATCH
		GOTO ERR
	END CATCH
COMMIT TRAN
RETURN @MaxID
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END














GO
/****** Object:  StoredProcedure [dbo].[pcCvProjectSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Sean
-- Create date: 2010-10-5
-- Description:	选择项目信息
-- =============================================
CREATE PROCEDURE [dbo].[pcCvProjectSelect]
	@cvMainID INT
AS
BEGIN
	SELECT *
	FROM CvProject WITH(NOLOCK INDEX(IX_cvProject_cvMainID))
	WHERE cvMainID = @cvMainID
	ORDER BY StartDate DESC
END














GO
/****** Object:  StoredProcedure [dbo].[pcCvrExchangeInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[pcCvrExchangeInsert]
(
	@RecommendID INT,
	@dcSubSiteId INT,
	@ExchangeNumber INT,
	@cvrGift INT,
	@Recipient VARCHAR(50),
	@RecipientMobile VARCHAR(15),
	@RecipientAddress VARCHAR(100),
	@Remark VARCHAR(MAX)
)
AS
BEGIN TRY
	DECLARE @Amount INT
	DECLARE @lastIntegral INT
	IF NOT EXISTS(SELECT 'x' FROM marketDB..cvrGift WITH(NOLOCK) WHERE ID = @cvrGift AND isonline=1 AND remainder >= @ExchangeNumber)
		RETURN -1

	SELECT @Amount = Cost * @ExchangeNumber FROM marketDB..cvrGift WHERE ID = @cvrGift 
	SELECT @lastIntegral = (SELECT COUNT(*) FROM marketdb..cvrRecommend WITH(NOLOCK)
							WHERE RecommendID=@RecommendID
							AND HasValid=3 AND HasReply=1) - 
						ISNULL((SELECT SUM(Amount) FROM marketdb..cvrExchange WITH(NOLOCK)
							WHERE RecommendID=@RecommendID
							AND HasVerify<>2), 0)
	IF @lastIntegral<@Amount
		RETURN -2

	INSERT INTO marketDB..cvrExchange(RecommendID, dcSubSiteId, ExchangeNumber, cvrGift, Amount, ApplyTime, Recipient, RecipientMobile, RecipientAddress, Remark) 
	SELECT @RecommendID, @dcSubSiteId, @ExchangeNumber, @cvrGift, @Amount, GETDATE(), dbo.SafeSQL(@Recipient),
		dbo.SafeSQL(@RecipientMobile), dbo.SafeSQL(@RecipientAddress), dbo.SafeSQL(@Remark)

	UPDATE  marketDB..cvrGift SET Remainder = Remainder - @ExchangeNumber WHERE ID = @cvrGift

	RETURN 1
END TRY
BEGIN CATCH
	RETURN 0
END CATCH














GO
/****** Object:  StoredProcedure [dbo].[pcCvTrainingByIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- 检查:		Sean
-- 日期:		2010-10-5
-- 描述:		提取培训经历
-- =============================================
CREATE PROCEDURE [dbo].[pcCvTrainingByIDSelect]
	@ID INT
AS
BEGIN
	SELECT *
	FROM CvTraining WITH(NOLOCK INDEX(PK_cvTraining)) 
	WHERE ID = @ID
END














GO
/****** Object:  StoredProcedure [dbo].[pcCvTrainingDelete]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--===============================
-- 检查：		sean
-- 时间：		2010-9-29
-- 描述：		删除培训经历  取消pcCvMainByCvLevelUpdate，pcCvMainVerifyResultCheck
-- 修改：Lambo，2010-11-25
-- 描述：增加了paMainID参数，判断是否是本人的
--===============================
CREATE PROCEDURE [dbo].[pcCvTrainingDelete]
(
	@ID INT,
	@paMainID INT
)
AS
BEGIN TRAN
	BEGIN TRY
		DECLARE @cvMainId AS INT
		DECLARE @RETURN AS VARCHAR(2)
		SELECT @cvMainId = cvMainId FROM CvTraining WITH(NOLOCK) WHERE ID=@ID
		
		IF @cvMainId IS NULL
			GOTO ERR

		IF NOT EXISTS(SELECT 'x' FROM cvMain WITH(NOLOCK)
			WHERE paMainID = @paMainID AND ID = @cvMainID)
			GOTO ERR

		DELETE FROM CvTraining WHERE ID=@ID
		DELETE FROM bsCvModify WHERE SubID = @ID AND Location LIKE 'g%'
		EXEC @RETURN = pcCvMainByCvLevelCheck @cvMainID, 8
	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH
COMMIT TRAN
RETURN @RETURN
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 3
END














GO
/****** Object:  StoredProcedure [dbo].[pcCvTrainingSave]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--==================================================
-- 检查：		sean
-- 时间:		2010-9-29
-- 说明：		保存培训信息  取消pcCvMainByCvLevelUpdate pcCvMainVerifyResultUpdate
----------------
CREATE PROCEDURE [dbo].[pcCvTrainingSave]
(
	@Type INT,
	@ID INT,
	@cvMainID INT,
	@StartDate INT,
	@TimeLength INT,
	@TimeUnit INT,
	@Institution VARCHAR(150),
	@Course VARCHAR(250),
	@City VARCHAR(50),
	@Certificate VARCHAR(250),
	@Details VARCHAR(2500),
	@paMainID INT
)
AS
SET NOCOUNT ON
IF CHARINDEX('<', @Institution) > 0
	SET @Institution = REPLACE(@Institution, '<', '')
IF CHARINDEX('<', @Course) > 0
	SET @Course = REPLACE(@Course, '<', '')
IF CHARINDEX('<', @City) > 0
	SET @City = REPLACE(@City, '<', '')
IF CHARINDEX('<', @Certificate) > 0
	SET @Certificate = REPLACE(@Certificate, '<', '')
IF CHARINDEX('<', @Details) > 0
	SET @Details = REPLACE(@Details, '<', '')
BEGIN TRAN
	----检查是否是该账号的简历
	IF NOT EXISTS(SELECT 'x' FROM cvMain WITH(NOLOCK) WHERE ID = @cvMainID AND paMainID = @paMainID)
		GOTO ERR
	----检查是否是该简历的培训信息
	IF @ID > 0
		IF NOT EXISTS(SELECT 'x' FROM CvTraining WITH(NOLOCK) WHERE ID = @ID AND cvMainID = @cvMainID)
			GOTO ERR

	SELECT @Institution = dbo.SafeSql(dbo.TextTrim(@Institution)),
		@Course = dbo.SafeSql(dbo.TextTrim(@Course)),
		@City = dbo.SafeSql(dbo.TextTrim(@City)),
		@Certificate = dbo.SafeSql(dbo.TextTrim(@Certificate)),
		@Details = dbo.SafeSql(dbo.TextTrim(@Details))

	BEGIN TRY	
		DECLARE @MaxId AS INT
		DECLARE @InstitutionOld AS VARCHAR(150)
		DECLARE @CourseOld AS VARCHAR(250)
		DECLARE @CityOld AS VARCHAR(50)
		DECLARE @CertificateOld AS VARCHAR(250)
		DECLARE @DetailsOld AS VARCHAR(2500)
		DECLARE @Modify AS INT
		SET @Modify=-1

		IF @Type=0
		BEGIN
			DECLARE @I AS NVARCHAR(30)
			DECLARE @C AS NVARCHAR(50)
			DECLARE @Ci AS NVARCHAR(10)
			DECLARE @Ce AS NVARCHAR(50)
			DECLARE @D AS NVARCHAR(500)
			SET @I = @Institution
			SET @C = @Course
			SET @Ci = @City
			SET @Ce = @Certificate
			SET @D = @Details
				
			IF @ID>0
			BEGIN
				SELECT @InstitutionOld=dbo.TextTrim(ISNULL(Institution, '')),
					@CourseOld=dbo.TextTrim(ISNULL(Course, '')),
					@CityOld=dbo.TextTrim(ISNULL(City, '')),
					@CertificateOld=dbo.TextTrim(ISNULL(Certificate, '')),
					@DetailsOld=dbo.TextTrim(ISNULL(Details, ''))
				FROM CvTraining WITH(NOLOCK INDEX(PK_cvTraining))
				WHERE ID =@ID

				UPDATE CvTraining SET
					StartDate = @StartDate,
					TimeLength = @TimeLength,
					TimeUnit = @TimeUnit,
					Institution = @I,
					Course = @C,
					City = @Ci,
					Certificate = @Ce,
					Details = @D
				WHERE ID=@ID
				SET @MaxID = @ID
				
				IF ISNULL(@InstitutionOld, '') <> ISNULL(@I, '')
				BEGIN
					DELETE FROM bsCvModify WHERE paMainID=@paMainID AND cvMainID=@cvMainID AND SubID = @ID AND Location = 'gc1'
					INSERT INTO bsCvModify(paMainID,cvMainID,SubID,Location,ColValue) VALUES(@paMainID,@cvMainID,@MaxID,'gc1',@I)
					SET @Modify=0
				END

				IF ISNULL(@CourseOld, '') <> ISNULL(@C, '')
				BEGIN
					DELETE FROM bsCvModify WHERE paMainID=@paMainID AND cvMainID=@cvMainID AND SubID = @ID AND Location = 'gc2'
					INSERT INTO bsCvModify(paMainID,cvMainID,SubID,Location,ColValue) VALUES(@paMainID,@cvMainID,@MaxID,'gc2',@C)
					SET @Modify=0
				END
				
				IF @Ci IS NULL
					DELETE FROM bsCvModify WHERE paMainID=@paMainID AND cvMainID=@cvMainID AND SubID = @ID AND Location = 'gc3'
				ELSE
					IF ISNULL(@CityOld, '') <> ISNULL(@Ci, '')
					BEGIN
						DELETE FROM bsCvModify WHERE paMainID=@paMainID AND cvMainID=@cvMainID AND SubID = @ID AND Location = 'gc3'
						INSERT INTO bsCvModify(paMainID,cvMainID,SubID,Location,ColValue) VALUES(@paMainID,@cvMainID,@MaxID,'gc3',@ci)
						SET @Modify=0
					END

				IF @Ce IS NULL
					DELETE FROM bsCvModify WHERE paMainID=@paMainID AND cvMainID=@cvMainID AND SubID = @ID AND Location = 'gc4'
				ELSE
					IF ISNULL(@CertificateOld, '') <> ISNULL(@Ce, '')
					BEGIN
						DELETE FROM bsCvModify WHERE paMainID=@paMainID AND cvMainID=@cvMainID AND SubID = @ID AND Location = 'gc4'
						INSERT INTO bsCvModify(paMainID,cvMainID,SubID,Location,ColValue) VALUES(@paMainID,@cvMainID,@MaxID,'gc4',@ce)
						SET @Modify=0
					END

				IF @D IS NULL
					DELETE FROM bsCvModify WHERE paMainID=@paMainID AND cvMainID=@cvMainID AND SubID = @ID AND Location = 'gc5'
				ELSE
					IF ISNULL(@DetailsOld, '') <> ISNULL(@D, '')
					BEGIN
						DELETE FROM bsCvModify WHERE paMainID=@paMainID AND cvMainID=@cvMainID AND SubID = @ID AND Location = 'gc5'
						INSERT INTO bsCvModify(paMainID,cvMainID,SubID,Location,ColValue) VALUES(@paMainID,@cvMainID,@MaxID,'gc5',@D)
						SET @Modify=0
					END
			END
			ELSE
			BEGIN
				INSERT INTO CvTraining
					(cvMainID,StartDate,TimeLength,TimeUnit,Institution,
					Course,City,Certificate,Details) 
				VALUES(@cvMainID,@StartDate,@TimeLength,@TimeUnit,@I,
					@c,@Ci,@Ce,@D)
				SET @MaxID = @@IDENTITY
				SET @Modify=0

				INSERT INTO bsCvModify(paMainID,cvMainID,SubID,Location,ColValue) VALUES(@paMainID,@cvMainID,@MaxID,'gc1',@I)
				INSERT INTO bsCvModify(paMainID,cvMainID,SubID,Location,ColValue) VALUES(@paMainID,@cvMainID,@MaxID,'gc2',@C)
				IF @ci > ''
					INSERT INTO bsCvModify(paMainID,cvMainID,SubID,Location,ColValue) VALUES(@paMainID,@cvMainID,@MaxID,'gc3',@ci)
				IF @Ce > ''
					INSERT INTO bsCvModify(paMainID,cvMainID,SubID,Location,ColValue) VALUES(@paMainID,@cvMainID,@MaxID,'gc4',@ce)
				IF @D > ''
					INSERT INTO bsCvModify(paMainID,cvMainID,SubID,Location,ColValue) VALUES(@paMainID,@cvMainID,@MaxID,'gc5',@D)
			END
		END
		ELSE
		BEGIN
			IF @ID>0
			BEGIN
				SELECT @InstitutionOld=dbo.TextTrim(ISNULL(InstitutionEng, '')),
					@CourseOld=dbo.TextTrim(ISNULL(CourseEng, '')),
					@CityOld=dbo.TextTrim(ISNULL(CityEng, '')),
					@CertificateOld=dbo.TextTrim(ISNULL(CertificateEng, '')),
					@DetailsOld=dbo.TextTrim(ISNULL(DetailsEng, ''))
					FROM CvTraining WITH(NOLOCK INDEX(PK_cvTraining)) WHERE ID =@ID	

				UPDATE CvTraining SET
					StartDate = @StartDate,
					TimeLength = @TimeLength,
					TimeUnit = @TimeUnit,
					InstitutionEng = @Institution,
					CourseEng = @Course,
					CityEng = @City,
					CertificateEng = @Certificate,
					DetailsEng = @Details
				WHERE ID=@ID
				SET @MaxID = @ID

				IF ISNULL(@InstitutionOld, '') <> ISNULL(@Institution, '')
				BEGIN
					DELETE FROM bsCvModify WHERE paMainID=@paMainID AND cvMainID=@cvMainID AND SubID = @ID AND Location = 'ge1'
					INSERT INTO bsCvModify(paMainID,cvMainID,SubID,Location,ColValue) VALUES(@paMainID,@cvMainID,@MaxID,'ge1',@Institution)
					SET @Modify=1
				END
				IF ISNULL(@CourseOld, '') <> ISNULL(@Course, '')
				BEGIN
					DELETE FROM bsCvModify WHERE paMainID=@paMainID AND cvMainID=@cvMainID AND SubID = @ID AND Location = 'ge2'
					INSERT INTO bsCvModify(paMainID,cvMainID,SubID,Location,ColValue) VALUES(@paMainID,@cvMainID,@MaxID,'ge2',@Course)
					SET @Modify=1
				END
				IF @City IS NULL
					DELETE FROM bsCvModify WHERE paMainID=@paMainID AND cvMainID=@cvMainID AND SubID = @ID AND Location = 'ge3'
				ELSE
					IF ISNULL(@CityOld, '') <> ISNULL(@City, '')
					BEGIN
						DELETE FROM bsCvModify WHERE paMainID=@paMainID AND cvMainID=@cvMainID AND SubID = @ID AND Location = 'ge3'
						INSERT INTO bsCvModify(paMainID,cvMainID,SubID,Location,ColValue) VALUES(@paMainID,@cvMainID,@MaxID,'ge3',@City)
						SET @Modify=1
					END
				IF  @Certificate IS NULL
					DELETE FROM bsCvModify WHERE paMainID=@paMainID AND cvMainID=@cvMainID AND SubID = @ID AND Location = 'ge4'
				ELSE
					IF ISNULL(@CertificateOld, '') <> ISNULL(@Certificate, '')
					BEGIN
						DELETE FROM bsCvModify WHERE paMainID=@paMainID AND cvMainID=@cvMainID AND SubID = @ID AND Location = 'ge4'
						INSERT INTO bsCvModify(paMainID,cvMainID,SubID,Location,ColValue) VALUES(@paMainID,@cvMainID,@MaxID,'ge4',@Certificate)
						SET @Modify=1
					END
				IF @Details IS NULL
					DELETE FROM bsCvModify WHERE paMainID=@paMainID AND cvMainID=@cvMainID AND SubID = @ID AND Location = 'ge5'
				ELSE
					IF ISNULL(@DetailsOld, '') <> ISNULL(@Details, '')
					BEGIN
						DELETE FROM bsCvModify WHERE paMainID=@paMainID AND cvMainID=@cvMainID AND SubID = @ID AND Location = 'ge5'
						INSERT INTO bsCvModify(paMainID,cvMainID,SubID,Location,ColValue) VALUES(@paMainID,@cvMainID,@MaxID,'ge5',@Details)
						SET @Modify=1
					END
			END
			ELSE
			BEGIN
				INSERT INTO CvTraining
					(cvMainID,StartDate,TimeLength,TimeUnit,InstitutionEng,
					CourseEng,CityEng,CertificateEng,DetailsEng) 
				VALUES(@cvMainID,@StartDate,@TimeLength,@TimeUnit,@Institution,
					@Course,@City,@Certificate,@Details)
				SET @MaxID = @@IDENTITY
				SET @Modify=1

				INSERT INTO bsCvModify(paMainID,cvMainID,SubID,Location,ColValue) VALUES(@paMainID,@cvMainID,@MaxID,'ge1',@Institution)
				INSERT INTO bsCvModify(paMainID,cvMainID,SubID,Location,ColValue) VALUES(@paMainID,@cvMainID,@MaxID,'ge2',@Course)
				IF @City > ''
					INSERT INTO bsCvModify(paMainID,cvMainID,SubID,Location,ColValue) VALUES(@paMainID,@cvMainID,@MaxID,'ge3',@City)
				IF  @Certificate > ''
					INSERT INTO bsCvModify(paMainID,cvMainID,SubID,Location,ColValue) VALUES(@paMainID,@cvMainID,@MaxID,'ge4',@Certificate)
				IF @Details > ''
					INSERT INTO bsCvModify(paMainID,cvMainID,SubID,Location,ColValue) VALUES(@paMainID,@cvMainID,@MaxID,'ge5',@Details)
			END
		END
		--修改cvLevel
		DECLARE @SQL AS VARCHAR(100)
		SET @SQL = 'EXEC pcCvMainByCvLevelUpdateNew ' + CONVERT(CHAR(1), @Type) + ',' + CONVERT(VARCHAR(10), @cvMainID) + ',8,1'
		EXEC(@SQL)
	END TRY
	BEGIN cATCH
		GOTO ERR
	END CATCH
COMMIT TRAN
RETURN @MaxID
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END














GO
/****** Object:  StoredProcedure [dbo].[pcCvTrainingSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- 检查:		Sean
-- 日期:		2010-10-5
-- 描述:		选择培训信息
-- =============================================
CREATE PROCEDURE [dbo].[pcCvTrainingSelect]
	@cvMainID INT
AS
BEGIN
	SELECT *
	FROM CvTraining WITH(NOLOCK INDEX(IX_cvTraining_cvMainID))
	WHERE cvMainID = @cvMainID
	ORDER BY StartDate DESC
END














GO
/****** Object:  StoredProcedure [dbo].[pcDcAutoEmailByWordSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[pcDcAutoEmailByWordSelect]
AS
SET NOCOUNT ON
BEGIN
	DECLARE @Id INT, @Email VARCHAR(50)
	IF NOT EXISTS(SELECT TOP 1 'X' FROM dcAutoEmail)
	BEGIN
		EXEC ProcDcAutoEmailInsert
	END
	SELECT TOP 1 @Id = id,@Email=Email  FROM dcAutoEmail ORDER BY id
	DELETE FROM dcAutoEmail WHERE id= @Id

	SELECT @Email Email
END
GO
/****** Object:  StoredProcedure [dbo].[pcDcAutoEmailDelete]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.4
--创建人：John
--说明：删除记录
--#####################################################
CREATE PROCEDURE [dbo].[pcDcAutoEmailDelete]
(
	@id INT
)
AS
BEGIN
	DELETE FROM dcAutoEmail WHERE id= @id
END


GO
/****** Object:  StoredProcedure [dbo].[pcDcAutoEmailSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.4
--创建人：John
--说明：获取第一条记录
--#####################################################
CREATE PROCEDURE [dbo].[pcDcAutoEmailSelect]
AS
BEGIN
	SELECT TOP 1 *  FROM dcAutoEmail ORDER BY id
END


GO
/****** Object:  StoredProcedure [dbo].[pcdcFeeDelete]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[pcdcFeeDelete]
(
	@ID INT
)
AS
BEGIN TRAN
	BEGIN TRY
		UPDATE dcFee SET EndDate = GETDATE() WHERE ID = @ID
		--INSERT INTO dcFeeLog SELECT * FROM dcFee WITH(NOLOCK) WHERE ID=@ID
		DELETE FROM dcFee WHERE ID = @ID
	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH
COMMIT TRAN
RETURN 1
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END














GO
/****** Object:  StoredProcedure [dbo].[pcdcVipDelete]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[pcdcVipDelete]
(
	@ID INT
)
AS
BEGIN TRAN
	BEGIN TRY
		UPDATE dcVip SET EndDate = GETDATE() WHERE ID = @ID
		--INSERT INTO dcVipLog SELECT * FROM dcVip WITH(NOLOCK) WHERE ID=@ID
		DELETE FROM dcVip WHERE ID = @ID
	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH
COMMIT TRAN
RETURN 1
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END














GO
/****** Object:  StoredProcedure [dbo].[pcexImageInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[pcexImageInsert]
(
	@OutID INT,
	@OutType INT,
	@UID VARCHAR(20) OUTPUT
)
AS
BEGIN
	DECLARE @T AS VARCHAR(20)
	SET @T = CONVERT(VARCHAR(20), CONVERT(DECIMAL(18,12),GETDATE()))
	SET @T = RTRIM(CONVERT(VARCHAR(12), @OutID)) + '_' + RIGHT(@T,8)
	Insert Into exImage(OutID,OutType,UniqueID)
	Values(@OutID,@OutType,@T)
	SET @UID = @T
END














GO
/****** Object:  StoredProcedure [dbo].[pcExInterViewByBaiduPushSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--===================================
--创建：	Andy
--描述：	获取所有paMainID面试通知个数，
--===================================
CREATE PROCEDURE [dbo].[pcExInterViewByBaiduPushSelect]
(
	@WHERE VARCHAR(1000)	
)
AS
BEGIN
	SET @WHERE = dbo.SafeSql(@Where)
	DECLARE @SQL AS VARCHAR(2000)
	SET @SQL='SELECT d.paMainID, count(*) as Count
	 FROM exInterView a WITH(NOLOCK) 
	 Inner Join Job b WITH(NOLOCK) On b.ID=a.JobID 
	 Inner Join cpMain c WITH(NOLOCK) ON b.cpMainID=c.ID 
	 Inner Join cvMain d WITH(NOLOCK) ON a.cvMainID=d.ID
	 WHERE PersonDeleted=0  '
	IF LEN(@WHERE)>0
		SET @SQL=@SQL + ' AND '+@WHERE	
	SET @SQL=@SQL + ' GROUP BY d.pamainiD '
	EXEC(@SQL)
END




GO
/****** Object:  StoredProcedure [dbo].[pcexInterViewByMailUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--===================================
--创建：	lucifer
--检查：	Sean
--描述：	回复面试通知 ，增加paMainID
--===================================
CREATE PROCEDURE [dbo].[pcexInterViewByMailUpdate]
(
	@ID INT,
	@Reply TINYINT,
	@ReplyMessage VARCHAR(500),
	@paMainID INT
)
AS
SET NOCOUNT ON
IF CHARINDEX('<', @ReplyMessage) > 0
	SET @ReplyMessage = REPLACE(@ReplyMessage, '<', '')
BEGIN TRY
	IF NOT EXISTS(SELECT 'x' FROM exInterview a WITH(NOLOCK), cvMain b WITH(NOLOCK) WHERE a.id=@ID AND a.cvMainID=b.ID AND b.paMainID=@paMainID)
		GOTO ERR1

	UPDATE exInterView 
	SET Reply = @Reply, ReplyMessage = dbo.SafeSql(@ReplyMessage), ReplyDate=GETDATE()
	WHERE ID = @ID
	DECLARE @Str AS VARCHAR(3000),
		@CompanyName AS NVARCHAR(50),
		@JobName AS VARCHAR(50),
		@ConsultantId AS INT,
		@ConsultantName AS VARCHAR(100),
		@JobId AS INT,
		@cvMainId AS INT

	SELECT @JobId = JobId, @cvMainId = cvMainId FROM exInterView WITH(NOLOCK) WHERE ID = @ID

	SELECT @CompanyName = a.Name, @JobName = b.Name, @ConsultantId = a.ConsultantId
	FROM cpMain a WITH(NOLOCK)
	INNER JOIN Job b WITH(NOLOCK) ON a.ID = b.cpMainId
	WHERE b.Id = @JobId

	SET @str = '<html><body><font style="font-family:''宋体'';font-size:14px">'
	SET @Str = @Str + @CompanyName
	SET @Str = @Str + '，您好：<br>&nbsp;&nbsp;您曾在::WebSite'
	SET @Str = @Str + '(<a href=''http://::EmailSite'' target=''_blank''>http://::EmailSite</a>)上通知求职者<b>::paName'
	SET @Str = @Str + '[简历编号:' + LTRIM(STR(@cvMainId)) + ']</b>参加['
	SET @Str = @Str + @JobName
	SET @Str = @Str + ']的面试，'
	IF @Reply = 1
		SET @Str = @Str + '对方表示能够赴约'
	ELSE
		SET @Str = @Str + '对方表示不能够赴约'

	SET @Str = @Str + '。详细情况请登录::WebSite(<a href=''http://::EmailSite'' target=''_blank''>http://::EmailSite</a>)查看。'
	IF @ConsultantId > 0
	BEGIN
		SELECT @ConsultantName = Name FROM ManagerUser WITH(NOLOCK) WHERE ID = @ConsultantId
		SET @Str = @Str + '您的招聘顾问是'
		SET @Str = @Str + LTRIM(STR(@ConsultantId))
		SET @Str = @Str + '号'
		SET @Str = @Str + @ConsultantName
		SET @Str = @Str + '。'
	END
	SET @Str = @Str + '<br>&nbsp;&nbsp;此通知信委托网站发送，请不要直接回复该邮件，该求职者无法收到。为保证您的权益，请使用正确的网址http://::EmailSite访问，建议将该网址添加到浏览器收藏夹。</font></body></html>'	
	SELECT @Str
	RETURN
END TRY
BEGIN CATCH
	GOTO ERR
END CATCH
ERR:
BEGIN
	SELECT 0
	RETURN
END
ERR1:
BEGIN
	SELECT -1
END














GO
/****** Object:  StoredProcedure [dbo].[pcexInterViewByMailUpdateNew]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--===================================
--创建：    Nick 2012-12-7
--描述：    回复面试通知
--修改: Nick 2013-1-24
--描述： 查询企业Email
---20160411 Lucifer 添加企业微信提醒
--===================================
CREATE PROCEDURE [dbo].[pcexInterViewByMailUpdateNew]
(
    @ID INT,
    @Reply TINYINT,
    @ReplyMessage VARCHAR(500),
    @paMainID INT
)
AS
SET NOCOUNT ON
IF CHARINDEX('<', @ReplyMessage) > 0
    SET @ReplyMessage = REPLACE(@ReplyMessage, '<', '')
BEGIN TRY
    IF NOT EXISTS(SELECT 'x' FROM exInterview a WITH(NOLOCK), cvMain b WITH(NOLOCK) WHERE a.id=@ID AND a.cvMainID=b.ID AND b.paMainID=@paMainID)
        GOTO ERR1

    UPDATE exInterView 
    SET Reply = @Reply, ReplyMessage = dbo.SafeSQL(@ReplyMessage), ReplyDate=GETDATE()
    WHERE ID = @ID
    DECLARE @Str AS VARCHAR(3000),
        @CompanyName AS NVARCHAR(50),
        @JobName AS VARCHAR(50),
        @ConsultantId AS INT,
        @ConsultantName AS VARCHAR(100),
        @JobId AS INT,
        @cvMainId AS INT,
        @ReplyInfo AS NVARCHAR(100),
        @CompanyEmail AS VARCHAR(200),
	@cpMainID AS INT

    SELECT @JobId = JobId, @cvMainId = cvMainId FROM exInterView WITH(NOLOCK) WHERE ID = @ID

    SELECT @CompanyName = a.Name, @JobName = b.Name, @ConsultantId = a.ConsultantId ,@CompanyEmail = c.Email, @cpMainID = a.ID 
    FROM cpMain a WITH(NOLOCK), Job b WITH(NOLOCK) , CaMain c WITH(NOLOCK) 
    WHERE a.ID = b.cpMainId
    AND b.Id = @JobId 
    AND b.CaMainID = c.ID

    ---是否能够赴约
    IF @Reply = 1
        SET @ReplyInfo = '对方表示能够赴约'
    ELSE
        SET @ReplyInfo = '对方表示不能够赴约'

    SELECT @ReplyInfo AS Reply, @CompanyName AS CompanyName, @cvMainId AS cvMainId,
        @CompanyName AS CompanyName, @JobName AS JobName, @ConsultantId AS ConsultantId,
        @CompanyEmail AS CompanyEmail, @cpMainID AS cpMainId

    INSERT wxMessageSend2(Templatetype, WxFansID, PaMainId, CvMainId, CpMainID, CaMainId, JobId, AddDate)
    SELECT 15, b.ID, @paMainID, d.cvMainID, c.cpMainID, c.caMainID, c.ID, GETDATE()
    FROM paLoginContact a WITH(NOLOCK), wxFans b WITH(NOLOCK), Job c WITH(NOLOCK), exInterview d WITH(NOLOCK)
    WHERE a.OpenID = b.OpenID AND c.caMainID = a.paMainID AND d.JobID = c.ID AND a.ContactType = 101 AND d.ID = @ID
   
    INSERT INTO paPushLog(paMainID, PushMessage, PushType) 
    SELECT a.caMainID, e.name+'回复'+ REPLACE(@ReplyInfo,'对方表示',''), 13 
	FROM caIOSBind a WITH(NOLOCK),Job b WITH(NOLOCK), exInterview c WITH(NOLOCK),cvMain d WITH(NOLOCK),paMain e WITH(NOLOCK)
	WHERE a.caMainID = b.caMainID AND b.ID = c.JobID AND c.cvMainId= d.id AND d.paMainId= e.id AND c.id = @ID
    
END TRY
BEGIN CATCH
    GOTO ERR
END CATCH
ERR:
BEGIN
    SELECT 0
    RETURN
END
ERR1:
BEGIN
    SELECT -1
END

GO
/****** Object:  StoredProcedure [dbo].[pcExInterViewDelete]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--===============================
--创建：	lucifer
--检查：	sean，2010-10-13
--返回值：	0：未知错误
--			-1：该留言不存在
--			-2：您没有权限查看该留言,该留言不是你写的
--			如果企业已经删除了该面试通知，个人删除
CREATE PROCEDURE [dbo].[pcExInterViewDelete]
(
	@ID INT,
	@paMainID INT
)
AS
BEGIN TRY
	DECLARE @CompanyDeleted AS BIT
	DECLARE @cvMainID AS INT
	DECLARE @paID AS INT
	SELECT @CompanyDeleted=CompanyDeleted,@cvMainID=cvMainID FROM ExInterView WITH(NOLOCK) WHERE ID=@ID
	IF @cvMainID IS NULL
		GOTO Err1
	ELSE
		SELECT @paID=paMainID FROM cvMain WITH(NOLOCK) WHERE ID = @cvMainID
	
	IF @paMainID = @paID
		IF @CompanyDeleted=1
			DELETE FROM ExInterView WHERE CompanyDeleted=1 AND ID = @ID
		ELSE
			UPDATE ExInterView SET PersonDeleted=1, PersonDeleteDate=GETDATE() WHERE ID = @ID
	ELSE
		GOTO Err2
END TRY
BEGIN CATCH
	GOTO ERR
END CATCH
RETURN 1
ERR:
BEGIN
	RETURN 0
END
ERR1:
BEGIN
	RETURN -1
END
ERR2:
BEGIN
	RETURN -2
END














GO
/****** Object:  StoredProcedure [dbo].[pcExInterViewSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--===================================
--创建：    lucifer
--检查：    Sean
--描述：    个人用户查看面试通知，面试通知选择
--修改： Harry 2015-6-24
--修改内容： dcregionID改为dcregionId
--===================================
CREATE PROCEDURE [dbo].[pcExInterViewSelect]
(
    @WHERE VARCHAR(1000),
    @Order VARCHAR(100)
)
AS
BEGIN
    SELECT @WHERE = dbo.SafeSQL(@WHERE),
        @ORDER = dbo.SafeSQL(@ORDER)

    DECLARE @SQL AS VARCHAR(2000)
    SET @SQL='SELECT a.ID,a.JobID,a.cvMainID,a.InterviewDate,a.InterViewPlace,a.LinkMan,a.Telephone,a.Remark,a.AddDate,a.Reply,a.ReplyMessage,a.Replydate,a.CompanyDeleted,a.CompanyDeleteDate,a.PersonDeleted,a.PersonDeleteDate,a.ViewDate,
b.Name as JobName,b.dcRegionId,c.Name as cpName,c.ID as cpID,c.HasLicence,c.IsAgent,b.IssueDate,b.IssueEND,b.IsDelete,d.Name cvName, c.Membertype, b.SecondId EnJobID, c.SecondId EnCpMainID,ISNULL((SELECT IsOnline FROM caOnline WHERE caMainId =b.caMainID), 0) AS IsOnline,b.CaMainID, c.LogoFile LogoUrl, b.Valid JobValid'
    SET @SQL=@SQl+' FROM exInterView a WITH(NOLOCK) inner join Job b WITH(NOLOCK) On
b.ID=a.JobID Inner Join cpMain c WITH(NOLOCK) ON b.cpMainID=c.ID Inner Join cvMain d WITH(NOLOCK) ON a.cvMainID=d.ID'
    SET @SQL=@SQl+' WHERE PersonDeleted=0 '
    IF LEN(@WHERE) > 0
        SET @SQL = @SQL + ' AND ' + @WHERE
    IF LEN(@ORDER) > 0
        SET @SQL = @SQL + ' ORDER BY ' + @ORDER
    EXEC(@SQL)
END
GO
/****** Object:  StoredProcedure [dbo].[pcexInterViewUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--===================================
--创建：	lucifer
--检查：	Sean
--描述：	回复面试通知 ，增加paMainID
--===================================
CREATE PROCEDURE [dbo].[pcexInterViewUpdate]
(
	@ID INT,
	@Reply TINYINT,
	@ReplyMessage VARCHAR(500),
	@paMainID INT
)
AS
SET NOCOUNT ON
IF CHARINDEX('<', @ReplyMessage) > 0
	SET @ReplyMessage = REPLACE(@ReplyMessage, '<', '')
BEGIN TRY
	IF NOT EXISTS(SELECT 'x' FROM exInterview a WITH(NOLOCK),cvMain b WITH(NOLOCK) WHERE a.id=@ID AND a.cvMainID=b.ID AND b.paMainID=@paMainID)
		GOTO ERR1

	UPDATE exInterView 
	SET Reply=@Reply, ReplyMessage = dbo.SafeSql(@ReplyMessage), ReplyDate=GETDATE()
	WHERE ID=@ID
	RETURN 1
END TRY
BEGIN CATCH
	GOTO ERR
END CATCH
ERR:
BEGIN
	RETURN 0
END
ERR1:
BEGIN
	RETURN -1
END














GO
/****** Object:  StoredProcedure [dbo].[pcexInterViewViewDateUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--===================================
--创建：	lucifer
--检查：	Sean
--描述：	面试通知查看时间修改 ，增加了pamainid
--===================================
CREATE PROCEDURE [dbo].[pcexInterViewViewDateUpdate]
(
	@ID INT,
	@paMainID INT
)
AS
BEGIN TRY
	UPDATE a SET a.ViewDate=GETDATE()
	FROM exInterView a, cvMain b
	WHERE a.ID=@ID
	AND a.cvMainID = b.ID
	AND b.paMainID = @paMainID
END TRY
BEGIN CATCH
	GOTO ERR
END CATCH
RETURN 1
ERR:
BEGIN
	RETURN 0
END














GO
/****** Object:  StoredProcedure [dbo].[pcExJobApplyApplyMessageByCvMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[pcExJobApplyApplyMessageByCvMainIDSelect]
(
	@CvMainID INT
)
AS
BEGIN
	SELECT TOP 1 ApplyMessage FROM exJobApply WITH(NOLOCK) WHERE cvMainID = @CvMainID ORDER BY ID DESC
END
GO
/****** Object:  StoredProcedure [dbo].[pcExJobApplyBatchDelete]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--====================================
--返回值：-1：不是你的求职申请
--创建：	luicifer
--检查：	sean 2010-10-13
--====================================
CREATE PROCEDURE [dbo].[pcExJobApplyBatchDelete]
(
	@AllID VARCHAR(1000),
	@paMainID INT
)
AS
SET NOCOUNT ON
BEGIN TRAN
	BEGIN TRY
		IF LEN(ISNULL(@AllID, '')) < 2
			GOTO Err2
		--生成临时表
		DECLARE @t AS TABLE(
			ID INT
		)
		DECLARE @i INT
		SET @i=CHARINDEX(',',@AllID)
		WHILE @i>=1
		BEGIN
			IF LEFT(@AllID,@i-1) > ''
				INSERT @t VALUES(LEFT(@AllID,@i-1))
			SET @AllID=SUBSTRING(@AllID,@i+1,LEN(@AllID)-@i)
			SET @i=CHARINDEX(',',@AllID)
		END
		IF @AllID > ''
			INSERT @t VALUES(@AllID)
		----判断是否这些id是同一个paMainID
		IF EXISTS(SELECT 'X' FROM ExJobApply a WITH(NOLOCK),@t b,cvMain c  WITH(NOLOCK)
			WHERE a.id=b.id AND a.cvMainID=c.ID AND c.paMainID<>@paMainID)
			GOTO Err1

		DELETE FROM ExJobApply WHERE CompanyDeleted=1 AND ID IN(SELECT ID FROM @t)
		UPDATE ExJobApply SET PersonDeleted=1 WHERE ID IN(SELECT ID FROM @t)
	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH
COMMIT TRAN
	--PRINT -1
RETURN 1
ERR:
BEGIN
	--PRINT 0
	ROLLBACK TRAN
	RETURN 0
END
ERR1:
BEGIN
	--PRINT -1
	ROLLBACK TRAN
	RETURN -1
END
ERR2:
BEGIN
	--PRINT 2
	ROLLBACK TRAN
	RETURN -2
END














GO
/****** Object:  StoredProcedure [dbo].[pcExjobApplyByAddDateSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--harry 2018-6-21
--14天内是否申请过职位
CREATE PROCEDURE [dbo].[pcExjobApplyByAddDateSelect]
(
	@paMainId INT
)
AS
BEGIN
	SET NOCOUNT ON
	SELECT * FROM exjobapply
	WHERE cvMainId IN(select id FROM cvmain WHERE valid=1 AND paMainId = @paMainId)
	AND AddDate>GETDATE()-14
	SET NOCOUNT OFF
END

GO
/****** Object:  StoredProcedure [dbo].[pcExJobApplyByApplyMessageUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[pcExJobApplyByApplyMessageUpdate]
(
	@ApplyIds VARCHAR(2000),
	@ApplyMessage VARCHAR(3000),
	@cvMainID INT
)
AS
SET NOCOUNT ON
IF CHARINDEX('<', @ApplyMessage) > 0
	SET @ApplyMessage = REPLACE(@ApplyMessage, '<', '')
BEGIN
	UPDATE exJobApply SET ApplyMessage = @ApplyMessage WHERE ID IN(SELECT a FROM dbo.FnSplit(@ApplyIds, ',')) AND cvMainID = @cvMainID
	RETURN 1
END
SET NOCOUNT ON
GO
/****** Object:  StoredProcedure [dbo].[pcExJobApplyByBaiduPushSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--====================================
--创建：	Andy Yin
--获取所有PaMainID对应的职位邀请数据个数。用于给app推送数据。
--====================================
CREATE PROCEDURE [dbo].[pcExJobApplyByBaiduPushSelect]
(
	@WHERE VARCHAR(1000)
)
AS
BEGIN
	BEGIN TRY
		SET @WHERE = REPLACE(dbo.SafeSQL(@WHERE), '''', '')

		DECLARE @SQL AS VARCHAR(2000)
		SET @SQL='SELECT  d.paMainID, COUNT(*) as Count
				FROM exJobApply a WITH(NOLOCK) 
				INNER JOIN Job b WITH(NOLOCK) On b.ID=a.JobID 
				INNER JOIN cpMain c WITH(NOLOCK) ON b.cpMainID=c.ID 
				INNER JOIN cvMain d WITH(NOLOCK) ON a.cvMainID = d.ID WHERE PersonDeleted=0'
		IF LEN(@WHERE)>0
			SET @SQL=@SQL + ' AND '+@WHERE	
		SET @SQL=@SQL + ' GROUP BY d.pamainid '	
		EXEC(@SQL)
	END TRY
	BEGIN CATCH
	END CATCH
END






GO
/****** Object:  StoredProcedure [dbo].[pcExJobApplyByCpMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.31
--创建人：Nick
--说明：向企业申请的职位
--#####################################################
CREATE PROCEDURE [dbo].[pcExJobApplyByCpMainIDSelect]
(
	@cpmainID INT,
	@cvMainID INT
)
AS
BEGIN TRY
	SELECT b.id, b.Name
	FROM ExJobApply a WITH(NOLOCK),Job b 
	WHERE a.JobID = b.ID 
	AND a.cvMainID = @cvMainID 
	AND b.cpMainID = @cpMainID
	AND CompanyDeleted = 0
	AND PersonDeleted = 0
	ORDER BY a.IsFilter, 
		a.ID DESC
END TRY
BEGIN CATCH
	RETURN 0
END CATCH

GO
/****** Object:  StoredProcedure [dbo].[pcExJobApplyByIDsDelete]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.4
--创建人：John
--说明：删除职位信息
--#####################################################
CREATE PROCEDURE [dbo].[pcExJobApplyByIDsDelete]
(
	@ApplyIDs VARCHAR(MAX)
)
AS
BEGIN
	SET @ApplyIDs = dbo.FormatIDS(@ApplyIDs)
	DECLARE @SQL AS VARCHAR(MAX)
	SET @SQL = 'DELETE FROM exJobApply WHERE ID IN(' + @ApplyIDs + ')'
	EXEC(@SQL)
END


GO
/****** Object:  StoredProcedure [dbo].[pcExJobApplyByIDUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--创建：Nick
--创建日期：2015-11-09
--个人中心，还原职位
--------------------------------------------------
CREATE PROCEDURE  [dbo].[pcExJobApplyByIDUpdate]
(
	@ID INT,
	@PaMainID INT
)
AS
BEGIN 
SET NOCOUNT ON
	UPDATE ExJobApply SET PersonDeleted=0 
	WHERE CvMainID IN(SELECT ID FROM CVMAIN WITH(NOLOCK) WHERE PaMainID = @PaMainID)
	AND ID = @ID
	AND PersonDeleted = 1
SET NOCOUNT OFF	
END

GO
/****** Object:  StoredProcedure [dbo].[pcExJobApplyByIsDeletedSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--创建：Nick
--创建日期：2015-11-09
--个人中心，职位回收站
--------------------------------------------------
CREATE PROCEDURE [dbo].[pcExJobApplyByIsDeletedSelect]
(
	@WHERE VARCHAR(1000),
	@Order VARCHAR(100)
)
AS
SET NOCOUNT ON
BEGIN
	SET @WHERE = REPLACE(dbo.SafeSQL(@WHERE), '''', '')
	SET @ORDER = REPLACE(dbo.SafeSQL(@ORDER), '''', '')
	SET @Where = REPLACE(@Where, 'LIKE %', 'LIKE ''%')
	SET @Where = REPLACE(@Where, '% OR ', '%'' OR ')
	SET @Where = REPLACE(@Where, '%)', '%'')')

	DECLARE @SQL AS VARCHAR(2000)
	SET @SQL='SELECT a.ID, a.JobID, b.SecondId EnJobID, c.SecondId EnCpMainID, a.cvMainID, a.ApplyMessage, a.AddDate, a.CompanyDeleted, a.CompanyDeleteDate,
			a.PersonDeleted, a.Reply, a.ReplyDate, a.ViewDate, b.Name as JobName, b.caMainID, b.dcRegionID, c.Name as cpName, c.ID as cpID,
			c.HasLicence, c.IsAgent, c.MemberType, b.IssueDate, b.IssueEND, b.IsDelete, d.Name cvName, dbo.GetCvMatch(a.cvMainID,a.JobID) cvMatch, dbo.GetCaOnlineStatus(b.caMainID) AS IsOnline,a.RemindDate
			FROM exJobApply a WITH(NOLOCK) 
			inner join Job b WITH(NOLOCK) On b.ID=a.JobID 
			Inner Join cpMain c WITH(NOLOCK) ON b.cpMainID=c.ID 
			INNER JOIN cvMain d WITH(NOLOCK) ON a.cvMainID = d.ID 
			WHERE PersonDeleted=1 AND IsDeleted = 0'
	IF LEN(@WHERE)>0
		SET @SQL=@SQL + ' AND '+@WHERE
	IF LEN(@ORDER)>0
		SET @SQL=@SQL + ' ORDER BY '+@ORDER
	EXEC(@SQL)	
END

GO
/****** Object:  StoredProcedure [dbo].[pcExJobApplyByJobIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.31
--创建人：Nick
--说明：根据职位ID获取一条申请记录
--修改：harry2017-5-4提升企业答复率，按照申请时间显示最早的申请记录,未答复的
--#####################################################
CREATE PROCEDURE [dbo].[pcExJobApplyByJobIDSelect]
(
	@CvMainID INT,
	@JobID INT
)
AS
BEGIN TRY
	SELECT TOP 1 a.ID,a.reply,a.AddDate,b.ID jobID,b.name,a.*,b.CaMainID
	FROM exjobapply a,job b
	WHERE a.jobid = b.id 
	AND a.cvMainID = @CvMainID 
	AND b.id =@JobID
	ORDER BY a.reply asc ,a.adddate asc
END TRY
BEGIN CATCH
	RETURN 0
END CATCH

GO
/****** Object:  StoredProcedure [dbo].[pcExJobApplyByPaMainIDDelete]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



--====================================
--返回值：-1：个人彻底删除职申请位
--创建：	Nick 20151110
--====================================
CREATE PROCEDURE [dbo].[pcExJobApplyByPaMainIDDelete]
(
	@AllID VARCHAR(1000),
	@paMainID INT
)
AS
SET NOCOUNT ON
BEGIN TRAN
	IF LEN(ISNULL(@AllID, '')) < 2
		GOTO Err2
	--生成临时表
	DECLARE @t AS TABLE(
		ID INT
	)
	DECLARE @i INT
	SET @i=CHARINDEX(',',@AllID)
	WHILE @i>=1
	BEGIN
		IF LEFT(@AllID,@i-1) > ''
			INSERT @t VALUES(LEFT(@AllID,@i-1))
		SET @AllID=SUBSTRING(@AllID,@i+1,LEN(@AllID)-@i)
		SET @i=CHARINDEX(',',@AllID)
	END
	IF @AllID > ''
		INSERT @t VALUES(@AllID)
	----判断是否这些id是同一个paMainID
	IF EXISTS(SELECT 'X' FROM ExJobApply a WITH(NOLOCK),@t b,cvMain c  WITH(NOLOCK)
		WHERE a.id=b.id AND a.cvMainID=c.ID AND c.paMainID<>@paMainID)
		GOTO Err1

	DELETE FROM ExJobApply WHERE CompanyDeleted=1 AND ID IN(SELECT ID FROM @t)
	UPDATE ExJobApply SET IsDeleted = 1 WHERE ID IN(SELECT ID FROM @t) AND PersonDeleted=1
COMMIT TRAN
	--PRINT -1
RETURN 1
ERR:
BEGIN
	--PRINT 0
	ROLLBACK TRAN
	RETURN 0
END
ERR1:
BEGIN
	--PRINT -1
	ROLLBACK TRAN
	RETURN -1
END
ERR2:
BEGIN
	--PRINT 2
	ROLLBACK TRAN
	RETURN -2
END


GO
/****** Object:  StoredProcedure [dbo].[pcExJobApplyByPaMainIDUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--创建：Nick
--创建日期：2015-11-09
--个人中心，提醒企业
--harry 2018-06-13 增加推送
--------------------------------------------------
CREATE PROCEDURE  [dbo].[pcExJobApplyByPaMainIDUpdate]
(
	@ID VARCHAR(200),
	@PaMainID INT
)
AS
BEGIN 
	SET NOCOUNT ON
	UPDATE ExJobApply
	SET RemindDate  = GETDATE()
	WHERE CvMainID IN (SELECT ID FROM CVMAIN WITH(NOLOCK) WHERE PaMainID = @PaMainID)
	AND ID IN (SELECT * FROM dbo.fnSplit(@ID,','))
        
        SELECT DISTINCT b.caMainid INTO #t 
	FROM exjobapply a WITH(NOLOCK), job b WITH(NOLOCK)
	WHERE a.ID IN (SELECT * FROM dbo.fnSplit(@ID,','))
	AND a.jobId=b.id
        
	DECLARE @name VARCHAR(20)
	SELECT @name=name FROM paMain WHERE id= @PaMainID

	INSERT INTO paPushLog(paMainID, PushMessage, PushType) 
	SELECT a.caMainid, @name+'求答复&#10084;',10
	FROM caIOSBind a WITH(NOLOCK), #t b WITH(NOLOCK)
	WHERE a.caMainId= b.caMainId
	
	DROP TABLE #t

	SET NOCOUNT OFF
END





GO
/****** Object:  StoredProcedure [dbo].[pcExJobApplyByTempDelete]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[pcExJobApplyByTempDelete]
(
	@JobIDs VARCHAR(1000),
	@paMainID INT
)
AS
BEGIN
	SET @JobIDs = dbo.FormatIDS(@JobIDs)
	DECLARE @Sql AS VARCHAR(1000)
	SET @Sql = 'DELETE FROM exJobApply WHERE JobId IN(' + @JobIDS + ') 
	AND cvMainID IN(SELECT ID FROM cvMain WITH(NOLOCK) WHERE paMainId = ' + LTRIM(STR(@PaMainID)) + ')
	AND ISTempInsert = 1'
	EXEC(@SQL)
END











GO
/****** Object:  StoredProcedure [dbo].[pcExJobApplyByTempInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--修改harry 增加企业app提醒2018-6-11
CREATE PROCEDURE [dbo].[pcExJobApplyByTempInsert]
(
	@JobID INT,
	@cvMainID INT,
	@ApplyMessage VARCHAR(4000),
	@paMainID INT,
	@IsFilter bit
)
AS
SET NOCOUNT ON
IF CHARINDEX('<', @ApplyMessage) > 0
	SET @ApplyMessage = REPLACE(@ApplyMessage, '<', '')
BEGIN
	SET @ApplyMessage = dbo.SafeSql(@ApplyMessage)
	DECLARE @MaxID AS INT
	SET @IsFilter = dbo.IsJobApplyFilter(@JobID, @cvMainID)
	BEGIN TRY
		IF EXISTS(SELECT ID FROM cvMain WITH(NOLOCK) WHERE paMainID = @paMainID AND ID = @cvMainID)
			IF EXISTS(SELECT ID FROM ExJobApply WITH(NOLOCK) WHERE JobID = @JobID AND cvMainID = @cvMainID AND AddDate > GETDATE()-30)
				SET @MaxID = 0
			ELSE
			BEGIN
				IF EXISTS(SELECT ID FROM JOB WITH(NOLOCK) WHERE ID=@JobID AND Valid = 0)
					SET @MaxID = 0
				ELSE
				BEGIN
					INSERT INTO ExJobApply(JobID,cvMainID,ApplyMessage,IsTempInsert,IsFilter) VALUES(@JobID,@cvMainID,@ApplyMessage, 1,@IsFilter)
					SET @MaxID=@@IDENTITY
					
					INSERT INTO paPushLog(paMainID, PushMessage, PushType) 
					SELECT a.caMainId, b.Name+'应聘：'+a.Name+'，'+CASE b.Gender WHEN 0 THEN '男' WHEN 1 THEN '女' END+'|'
					+ CONVERT(VARCHAR(5), dbo.BirthToAge(b.BirthDay)) + '岁|'
					+LTRIM(STR(ISNULL(RelatedWorkYears, 0))) + '年工作经验|'+f.Description, 9  
					FROM exJobApply c LEFT JOIN job a   ON a.id= c.jobId
					LEFT JOIN cvMain d ON c.cvMainID= d.id
					LEFT JOIN paMain b ON d.paMainId= b.id
					LEFT JOIN dceducation e ON e.id= d.degree 
					LEFT JOIN dcRegion f ON f.id=b.AccountPlace
					WHERE  c.Id= @MaxID 

					IF NOT EXISTS(SELECT 'x' FROM paJobViewLog WITH(NOLOCK) WHERE paMainId = @PaMainId AND JobId = @JobId)
					BEGIN
						INSERT INTO paJobViewLog(JobId, paMainId, AddDate) VALUES(@JobId, @paMainId, GETDATE())
						UPDATE Job SET ViewNumber = ViewNumber + 1 WHERE ID = @JobId
					END

					IF EXISTS(SELECT 'x' FROM caCvIntention WITH(NOLOCK) WHERE cvMainID = @cvMainId AND JobId = @JobId)
						UPDATE caCvIntention SET Reply = 1, ReplyDate = GETDATE() WHERE cvMainID = @cvMainId AND JobId = @JobId
				END
				INSERT wxMessageSend2(Templatetype, WxFansID, PaMainId, CvMainId, CpMainID, CaMainId, JobId, AddDate)
				SELECT 14, b.ID, @paMainID, @cvMainID, c.cpMainID, c.caMainID, c.ID, GETDATE()
				FROM paLoginContact a WITH(NOLOCK), wxFans b WITH(NOLOCK), Job c WITH(NOLOCK)
				WHERE a.OpenID = b.OpenID AND c.caMainID = a.paMainID AND a.ContactType = 101 AND c.ID = @JobID
			END
	END TRY
	BEGIN cATCH
		GOTO ERR
	END CATCH
	RETURN @MaxID
END
ERR:
BEGIN
	RETURN 0
END

GO
/****** Object:  StoredProcedure [dbo].[pcExJobApplyByTempInsertNew]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[pcExJobApplyByTempInsertNew]
(
	@JobID INT,
	@cvMainID INT,
	@ApplyMessage VARCHAR(4000),
	@paMainID INT,
	@IsFilter bit
)
AS
BEGIN
	SET @ApplyMessage = dbo.SafeSql(@ApplyMessage)
	DECLARE @MaxID AS INT
	SET @IsFilter = dbo.IsJobApplyFilter(@JobID, @cvMainID)
	BEGIN TRY
		IF EXISTS(SELECT ID FROM cvMain WITH(NOLOCK) WHERE paMainID = @paMainID AND ID = @cvMainID)
			IF EXISTS(SELECT ID FROM ExJobApply WITH(NOLOCK) WHERE JobID=@JobID AND cvMainID=@cvMainID AND AddDate>GETDATE()-30)
				SET @MaxID = 0
			ELSE
				IF EXISTS(SELECT ID FROM JOB WITH(NOLOCK) WHERE ID=@JobID AND Valid = 0)
					SET @MaxID = 0
				ELSE
					BEGIN
						INSERT INTO ExJobApply(JobID,cvMainID,ApplyMessage,IsTempInsert,IsFilter) VALUES(@JobID,@cvMainID,@ApplyMessage, 1,@IsFilter)
						SET @MaxID=@@IDENTITY

						IF NOT EXISTS(SELECT 'x' FROM paJobViewLog WITH(NOLOCK) WHERE paMainId = @PaMainId AND JobId = @JobId)
						BEGIN
							INSERT INTO paJobViewLog(JobId, paMainId, AddDate) VALUES(@JobId, @paMainId, GETDATE())
							UPDATE Job SET ViewNumber = ViewNumber + 1 WHERE ID = @JobId
						END
					END
	END TRY
	BEGIN cATCH
		GOTO ERR
	END CATCH
	RETURN @MaxID
END
ERR:
BEGIN
	RETURN 0
END














GO
/****** Object:  StoredProcedure [dbo].[pcExJobApplyInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--修改harry 增加企业app提醒2018-6-11
CREATE PROCEDURE [dbo].[pcExJobApplyInsert]
(
	@JobID INT,
	@cvMainID INT,
	@ApplyMessage VARCHAR(4000),
	@paMainID INT,
	@IsFilter BIT
)
AS
SET NOCOUNT ON
IF CHARINDEX('<', @ApplyMessage) > 0
	SET @ApplyMessage = REPLACE(@ApplyMessage, '<', '')
BEGIN
	SET @ApplyMessage = dbo.SafeSql(@ApplyMessage)
	SET @IsFilter = dbo.IsJobApplyFilter(@JobID, @cvMainID)
	DECLARE @MaxID AS INT
	BEGIN TRY
		IF EXISTS(SELECT ID FROM cvMain WITH(NOLOCK) WHERE paMainID = @paMainID AND ID = @cvMainID)		--是否是有效简历
			IF EXISTS(SELECT ID FROM ExJobApply WITH(NOLOCK) WHERE JobID=@JobID AND cvMainID = @cvMainID AND AddDate > GETDATE()-30)	--是否在30天申请过
				SET @MaxID = 0
			ELSE
			BEGIN
				IF EXISTS(SELECT ID FROM JOB WITH(NOLOCK) WHERE ID = @JobID AND Valid = 0)	--是否是有效职位
					SET @MaxID = 0
				ELSE
				BEGIN
					INSERT INTO ExJobApply(JobID,cvMainID,ApplyMessage,IsFilter) VALUES(@JobID,@cvMainID,@ApplyMessage,@IsFilter)
					SET @MaxID = @@IDENTITY
					UPDATE Job SET ApplyNumber = ApplyNumber + 1 WHERE ID = @JobID
                                        
					INSERT INTO paPushLog(paMainID, PushMessage, PushType) 
					SELECT a.caMainId, b.Name+'应聘：'+a.Name+'，'+CASE b.Gender WHEN 0 THEN '男' WHEN 1 THEN '女' END+'|'
					+ CONVERT(VARCHAR(5), dbo.BirthToAge(b.BirthDay)) + '岁|'
					+LTRIM(STR(ISNULL(RelatedWorkYears, 0))) + '年工作经验|'+f.Description, 9  
					FROM exJobApply c LEFT JOIN job a   ON c.jobId =a.id 
					LEFT JOIN cvMain d ON c.cvMainID= d.id
					LEFT JOIN paMain b ON d.paMainId= b.id
					LEFT JOIN dceducation e ON e.id= d.degree 
					LEFT JOIN dcRegion f ON f.id=b.AccountPlace
					WHERE  c.Id= @MaxID 
					
					IF EXISTS(SELECT 'x' FROM caCvIntention WITH(NOLOCK) WHERE cvMainID = @cvMainId AND JobId = @JobId)
						UPDATE caCvIntention SET Reply = 1, ReplyDate = GETDATE() WHERE cvMainID = @cvMainId AND JobId = @JobId

					INSERT wxMessageSend2(Templatetype, WxFansID, PaMainId, CvMainId, CpMainID, CaMainId, JobId, AddDate)
					SELECT 14, b.ID, @paMainID, @cvMainID, c.cpMainID, c.caMainID, c.ID, GETDATE()
					FROM paLoginContact a WITH(NOLOCK), wxFans b WITH(NOLOCK), Job c WITH(NOLOCK)
					WHERE a.OpenID = b.OpenID AND c.caMainID = a.paMainID AND a.ContactType = 101 AND c.ID = @JobID
				END
			END
	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH
	RETURN @MaxID
END
ERR:
BEGIN
	RETURN 0
END



GO
/****** Object:  StoredProcedure [dbo].[pcExJobApplyInsertNew]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[pcExJobApplyInsertNew]
(
	@JobID INT,
	@cvMainID INT,
	@ApplyMessage VARCHAR(4000),
	@paMainID INT,
	@IsFilter BIT
)
AS
SET NOCOUNT ON
IF CHARINDEX('<', @ApplyMessage) > 0
	SET @ApplyMessage = REPLACE(@ApplyMessage, '<', '')
BEGIN
	SET @ApplyMessage = dbo.SafeSql(@ApplyMessage)
	SET @IsFilter = dbo.IsJobApplyFilter(@JobID, @cvMainID)
	DECLARE @MaxID AS INT
	BEGIN TRY
		IF EXISTS(SELECT ID FROM cvMain WITH(NOLOCK) WHERE paMainID = @paMainID AND ID = @cvMainID)		--是否是有效简历
			IF EXISTS(SELECT ID FROM ExJobApply WITH(NOLOCK) WHERE JobID=@JobID AND cvMainID = @cvMainID AND AddDate > GETDATE()-30)	--是否在30天申请过
				SET @MaxID = 0
			ELSE
				IF EXISTS(SELECT ID FROM JOB WITH(NOLOCK) WHERE ID = @JobID AND Valid = 0)	--是否是有效职位
					SET @MaxID = 0
				ELSE
					BEGIN
						INSERT INTO ExJobApply(JobID,cvMainID,ApplyMessage,IsFilter) VALUES(@JobID,@cvMainID,@ApplyMessage,@IsFilter)
						SET @MaxID = @@IDENTITY
						UPDATE Job SET ApplyNumber = ApplyNumber + 1 WHERE ID = @JobID
					END
	END TRY
	BEGIN cATCH
		GOTO ERR
	END CATCH
	RETURN @MaxID
END
ERR:
BEGIN
	RETURN 0
END














GO
/****** Object:  StoredProcedure [dbo].[pcExJobApplyInsertOld]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[pcExJobApplyInsertOld]
(
	@JobID INT,
	@cvMainID INT,
	@ApplyMessage VARCHAR(4000),
	@paMainID INT
)
AS
BEGIN
	DECLARE @MaxID AS INT, @IsFilter AS BIT
	SET @IsFilter = dbo.IsJobApplyFilter(@JobID, @cvMainID)
	BEGIN TRY
		IF EXISTS(SELECT ID FROM cvMain WITH(NOLOCK) WHERE paMainID = @paMainID AND ID = @cvMainID)		--是否是有效简历
			IF EXISTS(SELECT ID FROM ExJobApply WITH(NOLOCK) WHERE JobID=@JobID AND cvMainID = @cvMainID AND AddDate > GETDATE()-30)	--是否在30天申请过
				SET @MaxID = 0
			ELSE
				IF EXISTS(SELECT ID FROM JOB WITH(NOLOCK) WHERE ID = @JobID AND Valid = 0)	--是否是有效职位
					SET @MaxID = 0
				ELSE
					BEGIN
						INSERT INTO ExJobApply(JobID,cvMainID,ApplyMessage,IsFilter) VALUES(@JobID,@cvMainID,@ApplyMessage, @IsFilter)
						SET @MaxID = @@IDENTITY
						UPDATE Job SET ApplyNumber = ApplyNumber + 1 WHERE ID = @JobID
					END
	END TRY
	BEGIN cATCH
		GOTO ERR
	END CATCH
	RETURN @MaxID
END
ERR:
BEGIN
	RETURN 0
END














GO
/****** Object:  StoredProcedure [dbo].[pcExJobApplySelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[pcExJobApplySelect]
(
	@WHERE VARCHAR(1000),
	@Order VARCHAR(100)
)
AS
SET NOCOUNT ON
BEGIN
	SET @WHERE = REPLACE(dbo.SafeSQL(@WHERE), '''', '')
	SET @ORDER = REPLACE(dbo.SafeSQL(@ORDER), '''', '')
	SET @Where = REPLACE(@Where, 'LIKE %', 'LIKE ''%')
	SET @Where = REPLACE(@Where, '% OR ', '%'' OR ')
	SET @Where = REPLACE(@Where, '%)', '%'')')

	DECLARE @SQL AS VARCHAR(2000)
	SET @SQL='SELECT a.ID, a.JobID, b.SecondId EnJobID, c.SecondId EnCpMainID, a.cvMainID, a.ApplyMessage, a.AddDate, a.CompanyDeleted, a.CompanyDeleteDate,
			a.PersonDeleted, a.Reply, a.ReplyDate, a.ViewDate, b.Name as JobName, b.caMainID, b.dcRegionID, c.Name as cpName, c.ID as cpID,
			b.Welfare1,b.Welfare2,b.Welfare3,b.Welfare4,b.Welfare5,b.Welfare6,b.Welfare7,b.Welfare8,
			b.Welfare9,b.Welfare10,b.Welfare11,b.Welfare12,b.Welfare13,b.Welfare14,b.Welfare15,b.Welfare16,
			b.Welfare17,b.Welfare18,b.Welfare19,b.Valid JobValid, c.LogoFile LogoUrl,
			c.HasLicence, c.IsAgent, c.MemberType, b.IssueDate, b.IssueEND, b.IsDelete, d.Name cvName, dbo.GetCvMatch(a.cvMainID,a.JobID) cvMatch, dbo.GetCaOnlineStatus(b.caMainID) AS IsOnline,a.RemindDate,a.ReplyReason, c.ReplyRate
			FROM exJobApply a WITH(NOLOCK) 
			inner join Job b WITH(NOLOCK) On b.ID=a.JobID 
			Inner Join cpMain c WITH(NOLOCK) ON b.cpMainID=c.ID 
			INNER JOIN cvMain d WITH(NOLOCK) ON a.cvMainID = d.ID 
			WHERE PersonDeleted=0 AND IsDeleted = 0'
	IF LEN(@WHERE) > 0
		SET @SQL = @SQL + ' AND ' + @WHERE
	IF LEN(@ORDER) > 0
		SET @SQL = @SQL + ' ORDER BY ' + @ORDER
	EXEC(@SQL)
END

GO
/****** Object:  StoredProcedure [dbo].[pcExMessageByCaMainIdDelete]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--===============================
--返回值：	0：未知错误
--返回值：  1：正常删除
--用于个人删除留言，2013-08个人会员中心改版，删除留言就删除整个会话
--如果企业已经删除了该留言，个人删除时就真删除，否则只增加个人删除标签
--创建：	Peter

--===============================
CREATE PROCEDURE [dbo].[pcExMessageByCaMainIdDelete]
(
	@caMainID INT,
	@paMainID INT
)
AS
	BEGIN TRY
		DELETE FROM ExMessageC2P 
			WHERE CompanyDeleted = 1 
			AND caMainID = @caMainID
			AND cvMainID IN (SELECT ID FROM CvMain WITH(NOLOCK) WHERE paMainID = @paMainID)
	
		UPDATE ExMessageC2P 
			SET PersonDeleted=1
			WHERE CompanyDeleted = 0 
			AND caMainID = @caMainID
			AND cvMainID IN (SELECT ID FROM CvMain WITH(NOLOCK) WHERE paMainID = @paMainID)

		DELETE FROM ExMessageP2C 
			WHERE CompanyDeleted = 1 
			AND caMainID = @caMainID
			AND cvMainID IN (SELECT ID FROM CvMain WITH(NOLOCK) WHERE paMainID = @paMainID)
	
		UPDATE ExMessageP2C
			SET PersonDeleted=1
			WHERE CompanyDeleted = 0 
			AND caMainID = @caMainID
			AND cvMainID IN (SELECT ID FROM CvMain WITH(NOLOCK) WHERE paMainID = @paMainID)

	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH
RETURN 1
ERR:
BEGIN
	RETURN 0
END












GO
/****** Object:  StoredProcedure [dbo].[pcExMessageC2PDelete]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--===============================
--返回值：	0：未知错误
--			-1：该留言不存在
--			-2：您没有权限查看该留言
--如果企业已经删除了该留言，个人删除时就真删除，否则只增加删除标签
--收到的留言删除
--创建：	lucifer
--检查：	sean，2010-10-13
--===============================
CREATE PROCEDURE [dbo].[pcExMessageC2PDelete]
(
	@ID INT,
	@paMainID INT
)
AS
	BEGIN TRY
		DECLARE @CompanyDeleted AS BIT
		DECLARE @cvMainID AS INT
		DECLARE @paID AS INT
		SELECT @CompanyDeleted=CompanyDeleted,@cvMainID=cvMainID FROM ExMessageC2P WITH(NOLOCK) WHERE ID=@ID
		IF @cvMainID IS NULL
			GOTO Err1
		ELSE
			SELECT @paID=paMainID FROM cvMain WITH(NOLOCK) WHERE ID = @cvMainID
		
		IF @paMainID = @paID
			IF @CompanyDeleted=1
				DELETE FROM ExMessageC2P WHERE CompanyDeleted=1 AND ID = @ID
			ELSE
				UPDATE ExMessageC2P SET PersonDeleted=1 WHERE ID = @ID
		ELSE
			GOTO Err2

	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH
RETURN 1
ERR:
BEGIN
	RETURN 0
END
ERR1:
BEGIN
	RETURN -1
END
ERR2:
BEGIN
	RETURN -2
END














GO
/****** Object:  StoredProcedure [dbo].[pcexMessageC2PIsViewedUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--==========================
--创建：lucifer
--检查：sean，2010-10-14
--记录个人查看单位留言时间
--==========================
CREATE PROCEDURE [dbo].[pcexMessageC2PIsViewedUpdate]
(
	@ID INT,
	@paMainID INT
)
AS
BEGIN TRY
	IF NOT EXISTS(SELECT 'x' FROM exMessageC2P a WITH(NOLOCK), cvMain b WITH(NOLOCK) WHERE a.ID=@ID AND b.paMainID=@paMainID AND a.cvMainID = b.ID)
		GOTO ERR
	
	UPDATE exMessageC2P SET IsViewed=1 WHERE ID=@ID
END TRY
BEGIN CATCH
	GOTO ERR
END CATCH
RETURN 1
ERR:
BEGIN
	RETURN 0
END














GO
/****** Object:  StoredProcedure [dbo].[pcExMessageC2PSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--=======================================
--创建：	lucifer
--检查：	Sean，2010-10-13
--=======================================
CREATE PROCEDURE [dbo].[pcExMessageC2PSelect]
(
	@WHERE VARCHAR(1000),
	@Order VARCHAR(100)
)
AS
BEGIN
	BEGIN TRY
		SET @WHERE = REPLACE(dbo.SafeSQL(@WHERE), '''', '')
		SET @ORDER = REPLACE(dbo.SafeSQL(@ORDER), '''', '')
		DECLARE @SQL AS VARCHAR(2000)
		SET @SQL='SELECT a.ID,a.caMainID,a.cvMainID,a.Message,a.AddDate,a.IsViewed,a.IsReply,a.CompanyDeleted,a.PersonDeleted,
b.Name as caName,b.Title,b.Email,b.Mobile,b.Telephone,b.Dept,b.GENDer,b.IsPhoneHide,b.IsNameHide,b.IsMobileHide,c.Name as cpName,c.ID as cpID,c.HasLicence,c.IsAgent,d.Name cvName, c.Membertype'
		SET @SQL=@SQl+' FROM exMessageC2P a WITH(NOLOCK) inner join caMain b WITH(NOLOCK) On
b.ID=a.caMainID Inner Join cpMain c WITH(NOLOCK) ON b.cpMainID=c.ID Inner Join cvMain d WITH(NOLOCK) ON a.cvMainID=d.ID'
		SET @SQL=@SQl+' WHERE PersonDeleted=0'
		IF LEN(@WHERE)>0
			SET @SQL=@SQL + ' AND ' + @WHERE
		IF LEN(@ORDER)>0
			SET @SQL=@SQL + ' ORDER BY ' + @ORDER
		EXEC(@SQL)
	END TRY
	BEGIN CATCH
	END CATCH
END














GO
/****** Object:  StoredProcedure [dbo].[pcexMessageP2CByC2PInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[pcexMessageP2CByC2PInsert]
(
	@ID INT,
	@caMainID INT,
	@cvMainID INT,
	@Message VARCHAR(200),
	@paMainID INT
)
AS
BEGIN
	IF EXISTS(SELECT ID FROM cvMain WITH(NOLOCK) WHERE paMainID = @paMainID AND ID=@cvMainID)
	BEGIN
		SET @Message = dbo.SafeSQL(LTRIM(RTRIM(@Message)))
		INSERT exMessageP2C(caMainID,cvMainID,Message) VALUES(@caMainID,@cvMainID,@Message)
		IF @ID > 0
			Update exMessageC2P Set IsReply=1 WHERE ID=@ID
	END
END














GO
/****** Object:  StoredProcedure [dbo].[pcExMessageP2CDelete]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--===============================
--返回值：	0：未知错误
--			-1：该留言不存在
--			-2：您没有权限查看该留言,该留言不是你写的
--			如果企业已经删除了该留言，个人删除时就真删除，否则只增加删除标签
--创建：	Lucifer
--检查：	Sean,2010-10-13
--===============================
CREATE PROCEDURE [dbo].[pcExMessageP2CDelete]
(
	@ID INT,
	@paMainID INT
)
AS
BEGIN TRY
	DECLARE @CompanyDeleted AS BIT
	DECLARE @cvMainID AS INT
	DECLARE @paID AS INT
	SELECT @CompanyDeleted=CompanyDeleted,@cvMainID=cvMainID FROM ExMessageP2C WITH(NOLOCK) WHERE ID=@ID
	IF @cvMainID IS NULL
		GOTO Err1
	
	SELECT @paID=paMainID FROM cvMain WITH(NOLOCK) WHERE ID = @cvMainID
	
	IF @paMainID = @paID
		IF @CompanyDeleted=1
			DELETE FROM ExMessageP2C WHERE CompanyDeleted=1 AND ID = @ID
		ELSE
			UPDATE ExMessageP2C SET PersonDeleted=1 WHERE ID = @ID
	ELSE
		GOTO Err2
END TRY
BEGIN CATCH
	GOTO ERR
END CATCH
RETURN 1
ERR:
BEGIN
	RETURN 0
END
ERR1:
BEGIN
	RETURN -1
END
ERR2:
BEGIN
	RETURN -2
END














GO
/****** Object:  StoredProcedure [dbo].[pcexMessageP2CInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[pcexMessageP2CInsert]
(
	@caMainID INT,
	@cvMainID INT,
	@Message VARCHAR(200),
	@paMainID INT
)
AS
BEGIN
	IF EXISTS(SELECT ID FROM cvMain WITH(NOLOCK) WHERE paMainID = @paMainID AND ID=@cvMainID)
	BEGIN
		SET @Message = dbo.SafeSql(LTRIM(RTRIM(@Message)))
		INSERT exMessageP2C(caMainID,cvMainID,Message) VALUES(@caMainID,@cvMainID,@Message)
	END
END














GO
/****** Object:  StoredProcedure [dbo].[pcExMessageP2CSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--=================================
--创建：	lucifer
--检查：	sean，2010-10-13
--描述：	发出的留言列表
--=================================
CREATE PROCEDURE [dbo].[pcExMessageP2CSelect]
(
	@WHERE VARCHAR(1000),
	@Order VARCHAR(100)
)
AS
BEGIN
	SET @WHERE = REPLACE(dbo.SafeSQL(@WHERE), '''', '')
	SET @ORDER = REPLACE(dbo.SafeSQL(@ORDER), '''', '')
	BEGIN TRY
		DECLARE @SQL AS VARCHAR(2000)
		SET @SQL='SELECT a.ID,a.caMainID,a.cvMainID,a.Message,a.AddDate,a.IsViewed,a.IsReply,a.CompanyDeleted,a.PersonDeleted,
b.Name as caName,b.Title,b.Dept,b.GENDer,b.IsNameHide,c.Name as cpName,c.ID as cpID,c.HasLicence,c.IsAgent,d.Name as cvName, c.MemberType'
		SET @SQL=@SQl+' FROM exMessageP2C a WITH(NOLOCK) inner join caMain b WITH(NOLOCK) On
b.ID=a.caMainID Inner Join cpMain c WITH(NOLOCK) ON b.cpMainID=c.ID Inner Join cvMain d WITH(NOLOCK) ON a.cvMainID=d.ID'
		SET @SQL=@SQl+' WHERE PersonDeleted=0'
		IF LEN(@WHERE)>0
			SET @SQL=@SQL + ' AND '+@WHERE
		IF LEN(@ORDER)>0
			SET @SQL=@SQL + ' ORDER BY '+@ORDER
		EXEC(@SQL)
	END TRY
	BEGIN CATCH
	END CATCH
END














GO
/****** Object:  StoredProcedure [dbo].[pcFaqSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[pcFaqSelect]
AS
BEGIN
    SELECT ID, Question
    FROM Faq WITH(NOLOCK)
    WHERE Type=2
	ORDER BY Power
END














GO
/****** Object:  StoredProcedure [dbo].[pcGetCvMainByCvIDsSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.31
--创建人：Nick
--说明：根据 Id1，Id2获取简历信息
--#####################################################
CREATE PROCEDURE [dbo].[pcGetCvMainByCvIDsSelect]
(
	@CvIds VARCHAR(200)
)
AS
BEGIN
	SELECT a.Id, a.Name AS cvName, b.Name AS paName, a.paMainId, a.SecondId
	FROM cvMain a, paMain b 
	WHERE a.paMainId = b.Id 
	AND a.Id IN(SELECT * FROM dbo.fnSplit(@CvIds, ','))
END
GO
/****** Object:  StoredProcedure [dbo].[pcGovNewsListByPhone]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[pcGovNewsListByPhone]
(
	@dcProvinceID AS SMALLINT,
	@PageNum AS INT,
	@PageSize AS INT
)
AS
BEGIN
	DECLARE @COUNT INT
	SELECT @COUNT=COUNT(1) 
		FROM QlrcNews WITH(NOLOCK) WHERE (
			EXISTS(SELECT 'x' FROM fnSplit(DetailType,',') b,dcNewsType c WITH(NOLOCK) WHERE b.a=c.ID AND c.Category=1) OR DetailType IS NULL) 
			AND (VersionID=@dcProvinceID OR VersionID=0) AND NewsType = 2 AND DetailType like '%,2,%'

	IF @COUNT > 200
		SET @COUNT = 200

	SELECT *,@COUNT FROM(
		SELECT TOP 200 ROW_NUMBER() OVER(ORDER BY RefreshDate DESC) AS Rows,ID,Title,RefreshDate,Author 
		FROM QlrcNews WITH(NOLOCK) WHERE (
			EXISTS(SELECT 'x' FROM fnSplit(DetailType,',') b,dcNewsType c WITH(NOLOCK) WHERE b.a=c.ID AND c.Category=1) OR DetailType IS NULL) 
			AND (VersionID=@dcProvinceID OR VersionID=0) AND NewsType = 2 AND DetailType like '%,2,%'
	) AS a 
	WHERE a.Rows BETWEEN (@PageNum-1)*@PageSize+1 AND @PageNum*@PageSize ORDER BY Rows
END














GO
/****** Object:  StoredProcedure [dbo].[pcHasCvByCvMainIDPaMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2014.10.30
--创建人：John
--说明：检查简历是否属于当前用户
--#####################################################
CREATE PROCEDURE [dbo].[pcHasCvByCvMainIDPaMainIDSelect]
(
	@cvMainID INT,
	@paMainID INT
)
AS
BEGIN
	SELECT TOP 1 * FROM cvMain WITH(NOLOCK) WHERE id=@cvMainID AND paMainID=@paMainID
END


GO
/****** Object:  StoredProcedure [dbo].[pcHasExJobApplyByCvMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2014.10.31
--创建人：John
--说明：判断简历是否申请过职位
--#####################################################
CREATE PROCEDURE [dbo].[pcHasExJobApplyByCvMainIDSelect]
(
	@cvMainID INT,
	@jobID INT
)
AS
BEGIN
	IF EXISTS (
					SELECT TOP 1 'x' 
					FROM exjobapply WITH(NOLOCK) 
					WHERE cvMainID = @cvMainID AND AddDate > GETDATE()-30 AND jobID = @jobID
					)
	BEGIN
		RETURN 1
	END
	ELSE
	BEGIN
		RETURN 0
	END
END


GO
/****** Object:  StoredProcedure [dbo].[pcIndexPageSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--修改Harry 调查增加exLink 2017-8-3
CREATE PROCEDURE [dbo].[pcIndexPageSelect]
(
    @paMainID INT,
    @ProvinceID INT
)
AS
SET NOCOUNT ON
BEGIN
	DECLARE @t AS TABLE(
	  ID INT,
	  type INT,
	  iCount INT NULL,
	  Title NVARCHAR(100) NULL,
	  Link NVARCHAR(200) NULL,
	  ContentText NVARCHAR(MAX) NULL,
	  AddDate SMALLDATETIME NULL
	)

	--取未答复的面试通知
	INSERT INTO @T(ID,type,iCount)
		SELECT @paMainID,1,Count(a.ID) FROM exInterView a WITH(NOLOCK) 
		INNER JOIN cvMain d WITH(NOLOCK) ON a.cvMainID=d.ID 
		WHERE PersonDeleted=0  AND paMainID=@paMainID AND Reply=0

	--取未查看的留言	
	INSERT INTO @T(ID,type,iCount)
		SELECT @paMainID,2,Count(a.ID) FROM exMessageC2P a WITH(NOLOCK) 
		INNER JOIN cvMain d WITH(NOLOCK) ON a.cvMainID=d.ID 
		WHERE PersonDeleted=0 AND paMainID=@paMainID AND IsViewed=0

	--取未答复的应聘邀请	
	INSERT INTO @T(ID,type,iCount)
		SELECT @paMainID,8,Count(a.ID) FROM caCvIntention a WITH(NOLOCK) 
		INNER JOIN cvMain d WITH(NOLOCK) ON a.cvMainID=d.ID 
		WHERE PersonDeleted=0 AND paMainID=@paMainID AND Reply IS NULL

	--取未查看的反馈
	INSERT INTO @T(ID,type, ContentText,AddDate)
		SELECT Top 1 ID,3, LEFT(ReplyMessage, 300), ReplyDate
		FROM paFeedBack WITH(NOLOCK INDEX(IX_paFeedBack_paMainID))
		WHERE paMainID = @paMainID	AND IsReply = 1	AND ViewDate IS NULL
		ORDER BY ID DESC

	--取未查看的网站消息
	INSERT INTO @T(ID,type,ContentText,AddDate)
		SELECT TOP 2 ID,4,LEFT(Message, 300), AddDate
		FROM PaNotify WITH(NOLOCK)
		WHERE paMainID = @paMainID 
		AND (
			(NotifyType = 1 AND IsViewed = 0)			--一次性消息，看过就不再通知了
			OR (NotifyType=2 AND ENDDate > GETDATE())	--即时消息，到期前（ENDdate）一直通知
		)
		ORDER BY ID DESC

	--取未查看的网站分类通知
	INSERT INTO @T(ID,type,Title,ContentText,link,iCount)
		SELECT TOP 2 ID,5, Title,LEFT(Content, 300), link,Type
		FROM ResumeInform WITH(NOLOCK)
		WHERE Status=1 
		AND Province like '%' + LTRIM(str(@ProvinceID)) + '%'
		AND EndDate > GETDATE()
		ORDER BY ID DESC	

	--取未查看的投诉
	INSERT INTO @T(ID,type,ContentText,AddDate)
		SELECT TOP 1 a.ID,6,LEFT(a.Plaint, 300),a.AddDate
		FROM CaPlaint a WITH(NOLOCK INDEX(IX_caPlaint_cvMainID)), cvMain b WITH(NOLOCK INDEX(IX_cvMain_paMainID))
		WHERE a.cvMainID = b.ID AND b.PaMainID = @PaMainID	AND a.IsViewed = 0	AND a.ReplyType = 1
		ORDER BY a.ID DESC

	--取当前调查
	DECLARE @Reg AS INT
	SET @Reg = 0
	IF @ProvinceID=32
	BEGIN
		IF EXISTS(SELECT 'x' FROM paMain WITH(NOLOCK) WHERE ID=@paMainId AND AddDate > '2012-1-26')
			SET @Reg = 1
	END

	IF @Reg = 1
		INSERT INTO @T(ID,type,ContentText,Link)
		SELECT TOP 1 ID, 7, Title,exLink FROM Ivgt_Investigation WITH(NOLOCK)
		WHERE ENDDate > GETDATE() AND Province LIKE '%' + LTRIM(str(@ProvinceID))+'%' AND Type=2
		ORDER BY ID DESC
	ELSE
		INSERT INTO @T(ID,type,ContentText,Link)
		SELECT TOP 1 ID, 7, Title,exLink FROM Ivgt_Investigation WITH(NOLOCK)
		WHERE ENDDate > GETDATE() AND Province LIKE '%' + LTRIM(str(@ProvinceID))+'%' AND Type=2
		AND ID <> 276
		ORDER BY ID DESC
	
	SELECT * FROM @T
END

GO
/****** Object:  StoredProcedure [dbo].[pcInterviewRecordByPaMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2014.10.30
--创建人：John
--说明：个人获取面试记录
--#####################################################
CREATE PROCEDURE [dbo].[pcInterviewRecordByPaMainIDSelect]
(
	@paMainID INT
)
AS
BEGIN
	SELECT a.*,c.Name caName,d.Name cpName,ISNULL(d.SecondId ,d.ID) cpMainID 
	FROM viInterviewRecord a 
		LEFT JOIN viRoom b ON b.ID=a.viRoomID 
		LEFT JOIN caMain c ON c.ID=b.caMainID 
		LEFT JOIN cpMain d ON d.ID=c.cpMainID 
	WHERE a.Begindate IS NOT NULL 
	AND a.cvMainID IN
		(
			SELECT ID 
			FROM cvMain 
			WHERE paMainID=@paMainID
		) 
	ORDER BY a.ID DESC
END


GO
/****** Object:  StoredProcedure [dbo].[pcJobByCountySearchSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[pcJobByCountySearchSelect] 
(
	@dcJobTypeID VARCHAR(100), 		--职位类别
	@dcRegionID VARCHAR(6), 		--求职地区
	@PageNumber INT 				--翻页页码
)
AS
SELECT 0 JobNumber 
SELECT TOP 0 * FROM SearchDb..CountyJob WITH(NOLOCK)
RETURN
BEGIN
	DECLARE @crDate DATETIME
	SELECT TOP 1 @crDate = crDate FROM SearchDb..CountyJob WITH(NOLOCK) WHERE JobPlaceId = @dcRegionID
	IF DATEADD(HOUR, -2, GETDATE()) > ISNULL(@crDate, GETDATE() - 1)
	BEGIN
		EXEC procCountyJobInsert @dcRegionID
	END
	
	IF ISNULL(@PageNumber, 0)  = 0
		SET @PageNumber = 1
	IF @PageNumber > 67
		SET @PageNumber = 67

	SELECT JobNumber FROM SearchDb..CountyJobNumber WHERE ProvinceId = LEFT(@dcRegionID, 2)

	SELECT * FROM SearchDb..CountyJob WITH(NOLOCK)
	WHERE JobPlaceId = @dcRegionID
	AND PageID = @PageNumber
	ORDER BY RowID
END

GO
/****** Object:  StoredProcedure [dbo].[pcJobByHighSalarySelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--lambo 2014-9-17
--前台校园招聘 取靠普高薪职位 山东北京上海取5000以上的 ，其它地区取4000以上的 
--Mice 2014-9-26 添加 with(nolock)
CREATE PROCEDURE [dbo].[pcJobByHighSalarySelect]
(
	@dcProvinceID INT 	
)
AS
BEGIN
	SELECT * FROM HighJob WITH(NOLOCK) WHERE ProvinceId = @dcProvinceId
END



GO
/****** Object:  StoredProcedure [dbo].[pcJobByIntentionSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = 
-- 检查:		Sean
-- 日期:		2010-10-5
-- 描述:		提取求职意向
--peter 2018-3-27
-- = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = 
CREATE PROCEDURE [dbo].[pcJobByIntentionSelect]
(
	@cvMainID INT
)
AS
SET NOCOUNT ON
BEGIN
	DECLARE @JobType AS VARCHAR(30),
		@JobTypeName AS VARCHAR(1000),
		@JobPlace AS VARCHAR(40),
		@JobPlaceName AS VARCHAR(100),
		@Industry AS VARCHAR(30),
		@IndustryName AS VARCHAR(100)

	SELECT @JobType = '',@JobTypeName= '' , @JobPlace = '',@JobPlaceName = '', @Industry = '',@IndustryName = ''

	SELECT @JobType = @JobType + LTRIM(STR(dcJobTypeID)) + ' ', 
		@JobTypeName =@JobTypeName + (SELECT TOP 1 Description+' ' FROM dcJobType WITH(NOLOCK) WHERE ID = dcJobTypeID)
	FROM cvJobType WITH(NOLOCK) 
	WHERE cvMainID = @cvMainID ORDER BY dcJobTypeID

	SELECT @JobPlace = @JobPlace + LTRIM(STR(dcRegionID)) + ' ',
		@JobPlaceName = @JobPlaceName + (SELECT TOP 1 Description+' ' FROM dcRegion WITH(NOLOCK) WHERE ID = dcRegionID)
	FROM cvJobPlace WITH(NOLOCK) 
	WHERE cvMainID = @cvMainID ORDER BY dcRegionID

	SELECT @Industry = @Industry + LTRIM(STR(dcIndustryID)) + ' ',
		@IndustryName = @IndustryName + (SELECT TOP 1 Description+' ' FROM dcIndustry WITH(NOLOCK) WHERE ID = dcIndustryID)
	FROM cvIndustry WITH(NOLOCK) 
	WHERE cvMainID = @cvMainID ORDER BY dcIndustryID

	SELECT RelatedWorkYears,
		EmployType,
		dcSalaryID,
		IsNegotiable,
		RTRIM(@JobType) AS JobType,
		RTRIM(@JobTypeName) AS JobTypeName,
		RTRIM(@JobPlace) AS JobPlace,
		RTRIM(@JobPlaceName) AS JobPlaceName,
		RTRIM(@Industry) AS Industry, 
		RTRIM(@IndustryName) AS IndustryName
	FROM cvMain WITH(NOLOCK) 
	WHERE id = @cvMainID
END
GO
/****** Object:  StoredProcedure [dbo].[pcJobByIntentionSelectByPhone]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[pcJobByIntentionSelectByPhone]
	@cvMainID INT
AS
BEGIN
	DECLARE @JobType AS VARCHAR(100)
	DECLARE @JobTypeName AS VARCHAR(1000)
	DECLARE @JobPlace AS VARCHAR(100)
	DECLARE @JobPlaceName AS VARCHAR(100)
	DECLARE @Industry AS VARCHAR(100)
	DECLARE @IndustryName AS VARCHAR(100)
	DECLARE @INTTemp AS INT
	DECLARE @STRTemp AS VARCHAR(20)
	DECLARE #JobType CURSOR FOR SELECT a.dcJobTypeID,b.Description JobType FROM cvJobType a WITH(NOLOCK),dcJobType b WITH(NOLOCK) WHERE a.dcJobTypeID=b.ID AND a.cvMainID=@cvMainID ORDER BY a.dcJobTypeID
	DECLARE #JobPlace CURSOR FOR SELECT a.dcRegionID,b.FullName Region FROM cvJobPlace a WITH(NOLOCK),dcRegion b WITH(NOLOCK) WHERE a.dcRegionID=b.ID AND a.cvMainID=@cvMainID ORDER BY a.dcRegionID
	DECLARE #Industry CURSOR FOR SELECT a.dcIndustryID,b.Description Industry FROM cvIndustry a WITH(NOLOCK),dcIndustry b WITH(NOLOCK) WHERE a.dcIndustryID=b.ID AND a.cvMainID=@cvMainID ORDER BY dcIndustryID
 
	--取得JobType	
	OPEN #JobType
	FETCH NEXT FROM #JobType INTO @INTTemp,@STRTemp
	WHILE @@FETCH_STATUS = 0 
	BEGIN 
		IF Len(@JobType) > 0
		BEGIN
			SET @JobType = @JobType + ' ' +  Rtrim(CONVERT(CHAR(10),@INTTemp))
			SET @JobTypeName = @JobTypeName + ' ' + @STRTemp
		END
		ELSE
		BEGIN
			SET @JobType = Rtrim(CONVERT(CHAR(10),@INTTemp))
			SET @JobTypeName = @STRTemp
		END
		FETCH NEXT FROM #JobType INTO @INTTemp,@STRTemp
	END
	CLOSE #JobType
	DEALLOCATE #JobType

	--取得JobPlace	
	OPEN #JobPlace
	FETCH NEXT FROM #JobPlace INTO @INTTemp,@STRTemp
	WHILE @@FETCH_STATUS = 0 
	BEGIN 
		IF Len(@JobPlace) > 0
		BEGIN
			SET @JobPlace = @JobPlace + ' ' + Rtrim(CONVERT(CHAR(10),@INTTemp))
			SET @JobPlaceName = @JobPlaceName + ' ' + @STRTemp
		END
		ELSE
		BEGIN
			SET @JobPlace = Rtrim(CONVERT(CHAR(10),@INTTemp))
			SET @JobPlaceName = @STRTemp
		END
		FETCH NEXT FROM #JobPlace INTO @INTTemp,@STRTemp
	END
	CLOSE #JobPlace
	DEALLOCATE #JobPlace 
	--取得Industry	
	OPEN #Industry
	FETCH NEXT FROM #Industry INTO @INTTemp,@STRTemp
	WHILE @@FETCH_STATUS = 0 
	BEGIN 
		IF Len(@Industry) > 0
		BEGIN
			SET @Industry = @Industry + ' ' + Rtrim(CONVERT(CHAR(10),@INTTemp))
			SET @IndustryName = @IndustryName + ' ' + @STRTemp
		END
		ELSE
		BEGIN
			SET @Industry = Rtrim(CONVERT(CHAR(10),@INTTemp))
			SET @IndustryName = @STRTemp
		END
		FETCH NEXT FROM #Industry INTO @INTTemp,@STRTemp
	END
	CLOSE #Industry
	DEALLOCATE #Industry
	SELECT
		RelatedWorkYears,
		EmployType,
		dcSalaryID,
		IsNegotiable,
		b.Description Salary,
		@JobType AS JobType,
		@JobPlace AS JobPlace,
		@Industry AS Industry,
		@JobTypeName AS JobTypeName,
		@JobPlaceName AS JobPlaceName,
		@IndustryName AS IndustryName
	From cvMain a WITH(NOLOCK)
	LEFT JOIN dcSalary b WITH(NOLOCK) ON a.dcSalaryID=b.ID
	WHERE a.id=@cvMainID
END














GO
/****** Object:  StoredProcedure [dbo].[pcJobByJobApplyCount]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[pcJobByJobApplyCount]
(
	@JobID INT
)
AS
BEGIN
	DECLARE @ApplyCount AS INT
	SELECT @ApplyCount = COUNT(ID) FROM exJobApply WITH(NOLOCK) WHERE JobID = @JobID
	RETURN @ApplyCount
END














GO
/****** Object:  StoredProcedure [dbo].[pcJobByJobIDsSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[pcJobByJobIDsSelect]
(
	@JobIDs VARCHAR(300)
)

AS
BEGIN
	SELECT * FROM Job WITH(NOLOCK) WHERE ID IN (SELECT A FROM dbo.fnsplit(@JobIDs ,','))
END

GO
/****** Object:  StoredProcedure [dbo].[pcJobByListSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[pcJobByListSelect]
(
	@AllJobID VARCHAR(1000)
)
AS
BEGIN
	SET @AllJobID = dbo.FormatIDS(@AllJobID)
	DECLARE @T AS TABLE(ID INT)
	INSERT INTO @T SELECT * FROM dbo.fnSplit(@AllJobID, ',')

	SELECT c.ID,c.cpMainID,c.caMainID,c.Name AS JobName,c.dcJobTypeID,c.dcJobTypeIDMinor,
	c.NeedNumber,c.dcSalaryID,c.EmployType,c.dcRegionID,c.dcEducationID,c.MinExperience,
	c.IssueDate,c.IssueEND,c.IsDelete,b.AccountType,b.Name AS caName,b.GENDer,
	b.Title,b.Dept,b.TelePhone,b.Mobile,b.Fax,
	b.IsPhoneHide,b.IsNameHide,b.IsMobileHide,a.Name AS cpName,
	a.ShortName,a.dcCompanyKindID,a.dcCompanySizeID,
	a.dcRegionID AS cpDcRegionID,a.Address,a.Zip,c.SecondID EnJobID,a.SecondID EnCpMainID
	FROM cpMain a WITH(NOLOCK) 
	INNER JOIN caMain b WITH(NOLOCK) ON a.ID = b.cpMainID
	INNER JOIN Job c WITH(NOLOCK) ON b.ID = c.caMainID
	WHERE c.ID IN (SELECT ID FROM @t)
END








GO
/****** Object:  StoredProcedure [dbo].[pcJobByMapSearchSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[pcJobByMapSearchSelect] 
(
	@dcJobTypeID VARCHAR(100), 	--职位类别
	@dcIndustryID VARCHAR(100), --求职行业
	@KeyWord NVARCHAR(50), 		--关键词
	@KeyType TINYINT, 			--关键词类别，0无；1-全文；2-职位；3-公司 
	@Type INT, 					--1：主动搜索  点击搜索按钮 10分钟，翻页60分钟有效；0：翻页搜索，不刷新
	@PageNumber INT, 			--翻页页码
	@Distance INT,				--距离范围
	@Lng DECIMAL(8,5),			--经度
	@Lat DECIMAL(8,5),			--纬度
	@dcSalaryID TINYINT, 		--月薪
	@MinExperience TINYINT, 	--工作经验，100为未选择
	@dcEducationID TINYINT,		--最低学历
	@EmployType VARCHAR(10),	--是否在线   -----工作性质，1全职；3兼职；4实习，
	@CompanySizeID VARCHAR(2) 	--dcprovinceid   --fei 是否环境照片    --企业规模
)
AS
--return
SET NOCOUNT ON
IF @Lng IS NULL OR @Lat IS NULL
	RETURN
BEGIN TRY
	BEGIN
		----给null值变量赋默认值
		SELECT @dcJobTypeID = RTRIM(dbo.FormatIDS(@dcJobTypeID)),
			@dcIndustryID = RTRIM(dbo.FormatIDS(@dcIndustryID)),
			@Type = ISNULL(@Type, 0),
			@dcSalaryID = 0,
			@MinExperience = 0,
			@dcEducationID = 0,
			@PageNumber = ISNULL(@PageNumber, 0),
			@CompanySizeID = ISNULL(@CompanySizeID, '0'),
			@EmployType = ISNULL(@EmployType, '')
		
		IF RIGHT(@dcJobTypeID, 1) = ','
			SET @dcJobTypeID = LEFT(@dcJobTypeID, LEN(@dcJobTypeID) - 1)
		IF RIGHT(@dcIndustryID, 1) = ','
			SET @dcIndustryID = LEFT(@dcIndustryID, LEN(@dcIndustryID) - 1)

		DECLARE @paSearchConditionID AS INT, 
			@MinId AS INT, 
			@PageSize AS TINYINT, 
			@TableID AS TINYINT

		SELECT @paSearchConditionID = 0, @PageSize = 30  --每页的行数
		
		----搜索60分钟前的数据
		SELECT TOP 1 @paSearchConditionID=ID FROM SearchDB..paSearchCondition WITH(NOLOCK)
		WHERE IsDelete = 0 AND JobType = @dcJobTypeID
		AND Industry = @dcIndustryID AND Lng = @Lng 
		AND Distance = @Distance AND Lat = @Lat 
		AND Education = @dcEducationID AND EmployType = @EmployType 
		AND Experience = @MinExperience AND Salary = @dcSalaryID
		AND CompanySizeID = 0 AND dcProvinceId = @CompanySizeID
		ORDER BY ID DESC

		IF ISNULL(@paSearchConditionID, 0) = 0
		BEGIN
			SET @Type =1
			GOTO SelectReset	--无数据，重新搜索
		END
		ELSE
		BEGIN
			SELECT @TableID = @paSearchConditionID % 4
			GOTO GetRecordSet	--从临时结果中提取数据
		END
	END

	SelectReset:				--从job中搜索数据
	BEGIN TRAN
		DECLARE @SQL AS VARCHAR(8000)
		DECLARE @WHERE AS VARCHAR(8000)
		DECLARE @FROM AS VARCHAR(1000)

		----记录查询条件
		INSERT INTO SearchDB..paSearchCondition(SessionID, LogTime, JobType, Industry, 
			Lng, Lat, Distance, ReuseNumber, Education, Experience, 
			Salary, EmployType, CompanySizeID, dcProvinceId, Keyword)
		VALUES(51, GETDATE(), @dcJobTypeID, @dcIndustryID, @Lng, @Lat, 
			@Distance, 0, @dcEducationID, @MinExperience, 
			@dcSalaryID, @EmployType, 0, @CompanySizeID, '')

		SET @paSearchConditionID = @@IDENTITY
		SELECT @TableID = @paSearchConditionID % 4

		------生成职位类别的表变量，因为职位类别有包含（父子）关系
		DECLARE @T_JobType AS TABLE(ID INT)
		DECLARE @JobType AS VARCHAR(3000)
		DECLARE @ValidJobNumber AS INT

		SET @JobType=''

		----生成求聘职位的表变量
		IF LEN(@dcJobTypeID) > 0
		BEGIN
			DECLARE @T_Temp AS TABLE(ID INT)		--临时表，用于构建组合查询语句
			INSERT INTO @T_Temp
			SELECT * FROM dbo.fnSplit(@dcJobTypeID, ',')

			INSERT INTO @T_JobType
			SELECT DISTINCT ID FROM dcJobType WITH(NOLOCK)
			WHERE ParentId IN(SELECT ID FROM @T_TEMP) 
			OR ParentId2 in(SELECT ID FROM @T_TEMP)
			OR ID IN(SELECT ID FROM @T_TEMP)
			----生成in字符串
			SELECT @JobType = (@JobType + LTRIM(STR(ID) + ',')) FROM @T_JobType
			IF RIGHT(@JobType, 1) = ','
				SET @JobType = LEFT(@JobType, LEN(@JobType) - 1)
		END
		
		----建立临时表
		CREATE TABLE #Job(
			RowID INT IDENTITY(1, 1), 
			ID INT NOT NULL, 
			dcJobTypeID SMALLINT NOT NULL, 
			dcJobTypeIDMinor SMALLINT NULL, 
			dcSalaryID TINYINT NOT NULL, 
			dcRegionID VARCHAR(6) NULL, 
			dcEducationID TINYINT NOT NULL, 
			MinExperience TINYINT NOT NULL, 
			RefreshDate SMALLDATETIME NULL,
			EmployType TINYINT NULL,
			dcCompanySizeID SMALLINT NULL
		)
		------刷新时间，根据刷新时间编号计算
		----生成插入临时表的Sql语句
		SET @SQL='
			INSERT INTO #Job
			SELECT a.ID, a.dcJobTypeID, 
				a.dcJobTypeIDMinor, a.dcSalaryID, 
				a.dcRegionID, a.dcEducationID, a.MinExperience, 
				a.IssueDate,a.EmployType,b.dcCompanySizeID'
		SET @FROM = '
			FROM JobPublish a WITH(NOLOCK)
			INNER JOIN cpMainPublish b WITH(NOLOCK) ON a.cpMainID=b.ID'
		----职位有效，单位新有效
		IF LEN(@dcIndustryID) > 0
			SET @WHERE = '
			WHERE b.ID IN (SELECT cpMainID FROM cpIndustry WHERE dcIndustryId in(' + @dcIndustryID + '))
			AND a.Valid = 1
			AND b.Valid = 1'
		ELSE
			SET @WHERE = '
			WHERE a.Valid = 1
			AND b.Valid = 1'
		IF LEN(@CompanySizeId) = 2
		SET @WHERE = @WHERE + '
			AND b.dcProvinceID = ' + @CompanySizeId

		----职位类别
		IF LEN(@dcJobTypeID) > 0
			SET @WHERE = @WHERE + '
			AND (a.dcJobTypeID IN(' + @JobType +')
				OR a.dcJobTypeIDMinor IN(' +@JobType + '))'
		----1、全职；3、兼职；4实习。	2、全职/兼职 职位中无此项
		IF LEN(@EmployType) = '1'
			SET @WHERE = @WHERE + '
			AND a.caMainId IN(SELECT caMainId FROM caOnline WITH(NOLOCK) WHERE IsOnline = 1)'
		
		DECLARE @Degree AS DECIMAL(8,5),@LBLng AS DECIMAL(8,5),@LBLat AS DECIMAL(8,5),
			@RTLng AS DECIMAL(8,5),@RTLat AS DECIMAL(8,5)
		SET @Degree = @Distance / 100000.0;

		SET @LBLng = @Lng - @Degree
		SET @LBLat = @Lat - @Degree
		SET @RTLng = @Lng + @Degree
		SET @RTLat = @Lat + @Degree
		SET @WHERE = @WHERE + '
			AND a.Lng BETWEEN ' + CONVERT(VARCHAR,@LBLng) + ' AND ' + CONVERT(VARCHAR,@RTLng) + '
			AND a.Lat BETWEEN ' + CONVERT(VARCHAR,@LBLat) + ' AND ' + CONVERT(VARCHAR,@RTLat) + '
			AND (a.Lng-' + CONVERT(VARCHAR,@Lng) + ')*(a.Lng-' + CONVERT(VARCHAR,@Lng) + ')+
			(a.Lat-' + CONVERT(VARCHAR,@Lat) + ')*(a.Lat-' + CONVERT(VARCHAR,@Lat) + ')<' + CONVERT(VARCHAR,@Degree*@Degree)

		SET @SQL = @SQL + @FROM + @WHERE
		
		--IF LEN(@ORDER)>0
		SET @SQL=@SQL + ' ORDER BY a.RefreshDate DESC, a.ID'
		--原来是ORDER BY a.IssueDate DESC, a.ID，Richard 2011年11月23日17：06分修改

		----把符合条件的职位全部列出
		--PRINT @SQL
		EXEC(@SQL)
		
		SET @ValidJobNumber = @@ROWCOUNT
		----记录查询结果总数
		UPDATE SearchDB..paSearchCondition SET ValidJobNumber=@ValidJobNumber, SQl=@SQL WHERE ID=@paSearchConditionID
		----插入JobType数据
		DECLARE @TitleValue AS INT, @TopRows AS INT, @AllRows AS INT
		IF (@TableID = 0)
		BEGIN
			INSERT INTO SearchDB..paSearchCount_0(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'JobType', dcJobTypeID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcJobTypeID ORDER BY dcJobTypeID
			----计算全部某职位类别，2, 4位的数据
			UPDATE a SET a.TitleValue = b.TitleValue
			FROM SearchDB..paSearchCount_0 a WITH(NOLOCK), 
				(SELECT LEFT(TitleID, 2) TitleID, SUM(TitleValue) TitleValue
				FROM SearchDB..paSearchCount_0 WITH(NOLOCK)
				WHERE paSearchConditionID = @paSearchConditionID AND Title = 'JobType'
				GROUP BY LEFT(TitleID, 2)) b
			WHERE a.TitleId = b.TitleID
			AND a.paSearchConditionID = @paSearchConditionID AND a.Title = 'JobType'
			----写入TitleDesc
			UPDATE a SET a.TitleDesc = b.Description
			FROM SearchDB..paSearchCount_0 a WITH(NOLOCK), dcJobType b WITH(NOLOCK)
			WHERE a.TitleID = b.ID AND a.paSearchConditionID = @paSearchConditionID
			AND a.Title = 'JobType'
			
			INSERT INTO SearchDB..paSearchCount_0(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Salary', dcSalaryID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcSalaryID ORDER BY dcSalaryID

			INSERT INTO SearchDB..paSearchCount_0(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Region', dcRegionID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcRegionID ORDER BY dcRegionID
			----计算全部地区，2位的数据
			UPDATE a SET a.TitleValue = b.TitleValue
			FROM SearchDB..paSearchCount_0 a WITH(NOLOCK), 
			(SELECT LEFT(TitleID, 2) TitleID, SUM(TitleValue) TitleValue
			FROM SearchDB..paSearchCount_0 WITH(NOLOCK)
			WHERE paSearchConditionID = @paSearchConditionID AND Title = 'Region'
			GROUP BY LEFT(TitleID, 2)) b
			WHERE a.TitleId = b.TitleID
			AND a.paSearchConditionID = @paSearchConditionID AND a.Title = 'Region'
			----计算全部地区，4位的数据
			UPDATE a SET a.TitleValue = b.TitleValue
			FROM SearchDB..paSearchCount_0 a WITH(NOLOCK), (
				SELECT LEFT(TitleID, 4) TitleID, SUM(TitleValue) TitleValue
				FROM SearchDB..paSearchCount_0 WITH(NOLOCK)
				WHERE paSearchConditionID = @paSearchConditionID AND Title = 'Region'
				AND LEN(TitleID) >3
				GROUP BY LEFT(TitleID, 4)) b
			WHERE a.TitleId = b.TitleID
			AND a.paSearchConditionID = @paSearchConditionID AND a.Title = 'Region'
			----写入TitleDesc
			UPDATE a SET a.TitleDesc = b.Description
			FROM SearchDB..paSearchCount_0 a WITH(NOLOCK), dcRegion b WITH(NOLOCK)
			WHERE a.TitleID = b.ID AND a.paSearchConditionID = @paSearchConditionID
			AND a.Title = 'Region'

			INSERT INTO SearchDB..paSearchCount_0(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Education', CASE WHEN dcEducationId IN(2, 3, 4) THEN 2 ELSE dcEducationId END, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY CASE WHEN dcEducationId IN(2, 3, 4) THEN 2 ELSE dcEducationId END
			ORDER BY CASE WHEN dcEducationId IN(2, 3, 4) THEN 2 ELSE dcEducationId END
			
			INSERT INTO SearchDB..paSearchCount_0(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Experience', MinExperience, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY MinExperience ORDER BY MinExperience
			
			INSERT INTO SearchDB..paSearchCount_0(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'EmployType', EmployType, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY EmployType ORDER BY EmployType

			INSERT INTO SearchDB..paSearchCount_0(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'CompanySize', dcCompanySizeID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcCompanySizeID ORDER BY dcCompanySizeID

			INSERT INTO SearchDB..paSearchJobID_0(paSearchConditionID, JobId, IsTop)
			SELECT Top 3 @paSearchConditionID, a.JobId, 1 
			FROM SearchJobTop a WITH(NOLOCK), (SELECT TOP 2000 ID FROM #Job WITH(NOLOCK)) b 
			WHERE b.ID = a.JobId ORDER BY a.OpenDate DESC
			SET @TopRows = @@ROWCOUNT

			INSERT INTO SearchDB..paSearchJobID_0(paSearchConditionID, JobId, IsTop)
			SELECT TOP 2000 @paSearchConditionID, ID, 0 FROM #Job WITH(NOLOCK)
			SET @AllRows = @@ROWCOUNT

			IF @TopRows = 0 AND @AllRows > 100
				UPDATE SearchDB..paSearchJobID_0 SET IsTop = 1 
				WHERE paSearchConditionID = @paSearchConditionID
				AND ID IN (SELECT TOP 3 ID FROM SearchDB..paSearchJobID_0 WITH(NOLOCK) WHERE paSearchConditionID = @paSearchConditionID)
		END
		ELSE IF (@TableId = 1)
		BEGIN
			INSERT INTO SearchDB..paSearchCount_1(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'JobType', dcJobTypeID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcJobTypeID ORDER BY dcJobTypeID
			----计算全部某职位类别，2, 4位的数据
			UPDATE a SET a.TitleValue = b.TitleValue
			FROM SearchDB..paSearchCount_1 a WITH(NOLOCK), 
			(SELECT LEFT(TitleID, 2) TitleID, SUM(TitleValue) TitleValue
			FROM SearchDB..paSearchCount_1 WITH(NOLOCK)
			WHERE paSearchConditionID = @paSearchConditionID AND Title = 'JobType'
			GROUP BY LEFT(TitleID, 2)) b
			WHERE a.TitleId = b.TitleID
			AND a.paSearchConditionID = @paSearchConditionID AND a.Title = 'JobType'
			----写入TitleDesc
			UPDATE a SET a.TitleDesc = b.Description
			FROM SearchDB..paSearchCount_1 a WITH(NOLOCK), dcJobType b WITH(NOLOCK)
			WHERE a.TitleID = b.ID AND a.paSearchConditionID = @paSearchConditionID
			AND a.Title = 'JobType'
			
			INSERT INTO SearchDB..paSearchCount_1(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Salary', dcSalaryID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcSalaryID ORDER BY dcSalaryID

			INSERT INTO SearchDB..paSearchCount_1(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Region', dcRegionID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcRegionID ORDER BY dcRegionID
			----计算全部地区，2位的数据
			UPDATE a SET a.TitleValue = b.TitleValue
			FROM SearchDB..paSearchCount_1 a WITH(NOLOCK), 
			(SELECT LEFT(TitleID, 2) TitleID, SUM(TitleValue) TitleValue
			FROM SearchDB..paSearchCount_1 WITH(NOLOCK)
			WHERE paSearchConditionID = @paSearchConditionID AND Title = 'Region'
			GROUP BY LEFT(TitleID, 2)) b
			WHERE a.TitleId = b.TitleID
			AND a.paSearchConditionID = @paSearchConditionID AND a.Title = 'Region'
			----计算全部地区，4位的数据
			UPDATE a SET a.TitleValue = b.TitleValue
			FROM SearchDB..paSearchCount_1 a WITH(NOLOCK), (
				SELECT LEFT(TitleID, 4) TitleID, SUM(TitleValue) TitleValue
				FROM SearchDB..paSearchCount_1 WITH(NOLOCK)
				WHERE paSearchConditionID = @paSearchConditionID AND Title = 'Region'
				AND LEN(TitleID) >3
				GROUP BY LEFT(TitleID, 4)) b
			WHERE a.TitleId = b.TitleID
			AND a.paSearchConditionID = @paSearchConditionID AND a.Title = 'Region'
			----写入TitleDesc
			UPDATE a SET a.TitleDesc = b.Description
			FROM SearchDB..paSearchCount_1 a WITH(NOLOCK), dcRegion b WITH(NOLOCK)
			WHERE a.TitleID = b.ID AND a.paSearchConditionID = @paSearchConditionID
			AND a.Title = 'Region'

			INSERT INTO SearchDB..paSearchCount_1(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Education', CASE WHEN dcEducationId IN(2, 3, 4) THEN 2 ELSE dcEducationId END, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY CASE WHEN dcEducationId IN(2, 3, 4) THEN 2 ELSE dcEducationId END
			ORDER BY CASE WHEN dcEducationId IN(2, 3, 4) THEN 2 ELSE dcEducationId END
			
			INSERT INTO SearchDB..paSearchCount_1(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Experience', MinExperience, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY MinExperience ORDER BY MinExperience
			
			INSERT INTO SearchDB..paSearchCount_1(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'EmployType', EmployType, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY EmployType ORDER BY EmployType

			INSERT INTO SearchDB..paSearchCount_1(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'CompanySize', dcCompanySizeID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcCompanySizeID ORDER BY dcCompanySizeID

			INSERT INTO SearchDB..paSearchJobID_1(paSearchConditionID, JobId, IsTop)
			SELECT Top 3 @paSearchConditionID, a.JobId, 1 
			FROM SearchJobTop a WITH(NOLOCK), (SELECT TOP 2000 ID FROM #Job WITH(NOLOCK)) b 
			WHERE b.ID = a.JobId ORDER BY a.OpenDate DESC
			SET @TopRows = @@ROWCOUNT

			INSERT INTO SearchDB..paSearchJobID_1(paSearchConditionID, JobId, IsTop)
			SELECT TOP 2000 @paSearchConditionID, ID, 0 FROM #Job WITH(NOLOCK)
			SET @AllRows = @@ROWCOUNT

			IF @TopRows = 0 AND @AllRows > 100
				UPDATE SearchDB..paSearchJobID_1 SET IsTop = 1 
				WHERE paSearchConditionID = @paSearchConditionID
				AND ID IN (SELECT TOP 3 ID FROM SearchDB..paSearchJobID_1 WITH(NOLOCK) WHERE paSearchConditionID = @paSearchConditionID)
		END
		ELSE IF (@TableId = 2)
		BEGIN
			INSERT INTO SearchDB..paSearchCount_2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'JobType', dcJobTypeID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcJobTypeID ORDER BY dcJobTypeID
			----计算全部某职位类别，2, 4位的数据
			UPDATE a SET a.TitleValue = b.TitleValue
			FROM SearchDB..paSearchCount_2 a WITH(NOLOCK), 
			(SELECT LEFT(TitleID, 2) TitleID, SUM(TitleValue) TitleValue
			FROM SearchDB..paSearchCount_2 WITH(NOLOCK)
			WHERE paSearchConditionID = @paSearchConditionID AND Title = 'JobType'
			GROUP BY LEFT(TitleID, 2)) b
			WHERE a.TitleId = b.TitleID
			AND a.paSearchConditionID = @paSearchConditionID AND a.Title = 'JobType'
			----写入TitleDesc
			UPDATE a SET a.TitleDesc = b.Description
			FROM SearchDB..paSearchCount_2 a WITH(NOLOCK), dcJobType b WITH(NOLOCK)
			WHERE a.TitleID = b.ID AND a.paSearchConditionID = @paSearchConditionID
			AND a.Title = 'JobType'
			
			INSERT INTO SearchDB..paSearchCount_2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Salary', dcSalaryID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcSalaryID ORDER BY dcSalaryID

			INSERT INTO SearchDB..paSearchCount_2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Region', dcRegionID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcRegionID ORDER BY dcRegionID
			----计算全部地区，2位的数据
			UPDATE a SET a.TitleValue = b.TitleValue
			FROM SearchDB..paSearchCount_2 a WITH(NOLOCK), 
			(SELECT LEFT(TitleID, 2) TitleID, SUM(TitleValue) TitleValue
			FROM SearchDB..paSearchCount_2 WITH(NOLOCK)
			WHERE paSearchConditionID = @paSearchConditionID AND Title = 'Region'
			GROUP BY LEFT(TitleID, 2)) b
			WHERE a.TitleId = b.TitleID
			AND a.paSearchConditionID = @paSearchConditionID AND a.Title = 'Region'
			----计算全部地区，4位的数据
			UPDATE a SET a.TitleValue = b.TitleValue
			FROM SearchDB..paSearchCount_2 a WITH(NOLOCK), (
				SELECT LEFT(TitleID, 4) TitleID, SUM(TitleValue) TitleValue
				FROM SearchDB..paSearchCount_2 WITH(NOLOCK)
				WHERE paSearchConditionID = @paSearchConditionID AND Title = 'Region'
				AND LEN(TitleID) >3
				GROUP BY LEFT(TitleID, 4)) b
			WHERE a.TitleId = b.TitleID
			AND a.paSearchConditionID = @paSearchConditionID AND a.Title = 'Region'
			----写入TitleDesc
			UPDATE a SET a.TitleDesc = b.Description
			FROM SearchDB..paSearchCount_2 a WITH(NOLOCK), dcRegion b WITH(NOLOCK)
			WHERE a.TitleID = b.ID AND a.paSearchConditionID = @paSearchConditionID
			AND a.Title = 'Region'

			INSERT INTO SearchDB..paSearchCount_2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Education', CASE WHEN dcEducationId IN(2, 3, 4) THEN 2 ELSE dcEducationId END, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY CASE WHEN dcEducationId IN(2, 3, 4) THEN 2 ELSE dcEducationId END
			ORDER BY CASE WHEN dcEducationId IN(2, 3, 4) THEN 2 ELSE dcEducationId END
			
			INSERT INTO SearchDB..paSearchCount_2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Experience', MinExperience, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY MinExperience ORDER BY MinExperience
			
			INSERT INTO SearchDB..paSearchCount_2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'EmployType', EmployType, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY EmployType ORDER BY EmployType

			INSERT INTO SearchDB..paSearchCount_2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'CompanySize', dcCompanySizeID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcCompanySizeID ORDER BY dcCompanySizeID

			INSERT INTO SearchDB..paSearchJobID_2(paSearchConditionID, JobId, IsTop)
			SELECT Top 3 @paSearchConditionID, a.JobId, 1 
			FROM SearchJobTop a WITH(NOLOCK), (SELECT TOP 2000 ID FROM #Job WITH(NOLOCK)) b 
			WHERE b.ID = a.JobId ORDER BY a.OpenDate DESC
			SET @TopRows = @@ROWCOUNT

			INSERT INTO SearchDB..paSearchJobID_2(paSearchConditionID, JobId, IsTop)
			SELECT TOP 2000 @paSearchConditionID, ID, 0 FROM #Job WITH(NOLOCK)
			SET @AllRows = @@ROWCOUNT

			IF @TopRows = 0 AND @AllRows > 100
				UPDATE SearchDB..paSearchJobID_2 SET IsTop = 1 
				WHERE paSearchConditionID = @paSearchConditionID
				AND ID IN (SELECT TOP 3 ID FROM SearchDB..paSearchJobID_2 WITH(NOLOCK) WHERE paSearchConditionID = @paSearchConditionID)
		END
		ELSE IF (@TableId = 3)
		BEGIN
			INSERT INTO SearchDB..paSearchCount_3(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'JobType', dcJobTypeID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcJobTypeID ORDER BY dcJobTypeID
			----计算全部某职位类别，2, 4位的数据
			UPDATE a SET a.TitleValue = b.TitleValue
			FROM SearchDB..paSearchCount_3 a WITH(NOLOCK), 
			(SELECT LEFT(TitleID, 2) TitleID, SUM(TitleValue) TitleValue
			FROM SearchDB..paSearchCount_3 WITH(NOLOCK)
			WHERE paSearchConditionID = @paSearchConditionID AND Title = 'JobType'
			GROUP BY LEFT(TitleID, 2)) b
			WHERE a.TitleId = b.TitleID
			AND a.paSearchConditionID = @paSearchConditionID AND a.Title = 'JobType'
			----写入TitleDesc
			UPDATE a SET a.TitleDesc = b.Description
			FROM SearchDB..paSearchCount_3 a WITH(NOLOCK), dcJobType b WITH(NOLOCK)
			WHERE a.TitleID = b.ID AND a.paSearchConditionID = @paSearchConditionID
			AND a.Title = 'JobType'
			
			INSERT INTO SearchDB..paSearchCount_3(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Salary', dcSalaryID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcSalaryID ORDER BY dcSalaryID

			INSERT INTO SearchDB..paSearchCount_3(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Region', dcRegionID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcRegionID ORDER BY dcRegionID
			----计算全部地区，2位的数据
			UPDATE a SET a.TitleValue = b.TitleValue
			FROM SearchDB..paSearchCount_3 a WITH(NOLOCK), 
			(SELECT LEFT(TitleID, 2) TitleID, SUM(TitleValue) TitleValue
			FROM SearchDB..paSearchCount_3 WITH(NOLOCK)
			WHERE paSearchConditionID = @paSearchConditionID AND Title = 'Region'
			GROUP BY LEFT(TitleID, 2)) b
			WHERE a.TitleId = b.TitleID
			AND a.paSearchConditionID = @paSearchConditionID AND a.Title = 'Region'
			----计算全部地区，4位的数据
			UPDATE a SET a.TitleValue = b.TitleValue
			FROM SearchDB..paSearchCount_3 a WITH(NOLOCK), (
				SELECT LEFT(TitleID, 4) TitleID, SUM(TitleValue) TitleValue
				FROM SearchDB..paSearchCount_3 WITH(NOLOCK)
				WHERE paSearchConditionID = @paSearchConditionID AND Title = 'Region'
				AND LEN(TitleID) >3
				GROUP BY LEFT(TitleID, 4)) b
			WHERE a.TitleId = b.TitleID
			AND a.paSearchConditionID = @paSearchConditionID AND a.Title = 'Region'
			----写入TitleDesc
			UPDATE a SET a.TitleDesc = b.Description
			FROM SearchDB..paSearchCount_3 a WITH(NOLOCK), dcRegion b WITH(NOLOCK)
			WHERE a.TitleID = b.ID AND a.paSearchConditionID = @paSearchConditionID
			AND a.Title = 'Region'

			INSERT INTO SearchDB..paSearchCount_3(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Education', CASE WHEN dcEducationId IN(2, 3, 4) THEN 2 ELSE dcEducationId END, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY CASE WHEN dcEducationId IN(2, 3, 4) THEN 2 ELSE dcEducationId END
			ORDER BY CASE WHEN dcEducationId IN(2, 3, 4) THEN 2 ELSE dcEducationId END
			
			INSERT INTO SearchDB..paSearchCount_3(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Experience', MinExperience, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY MinExperience ORDER BY MinExperience
			
			INSERT INTO SearchDB..paSearchCount_3(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'EmployType', EmployType, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY EmployType ORDER BY EmployType

			INSERT INTO SearchDB..paSearchCount_3(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'CompanySize', dcCompanySizeID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcCompanySizeID ORDER BY dcCompanySizeID

			INSERT INTO SearchDB..paSearchJobID_3(paSearchConditionID, JobId, IsTop)
			SELECT Top 3 @paSearchConditionID, a.JobId, 1 
			FROM SearchJobTop a WITH(NOLOCK), (SELECT TOP 2000 ID FROM #Job WITH(NOLOCK)) b 
			WHERE b.ID = a.JobId ORDER BY a.OpenDate DESC
			SET @TopRows = @@ROWCOUNT

			INSERT INTO SearchDB..paSearchJobID_3(paSearchConditionID, JobId, IsTop)
			SELECT TOP 2000 @paSearchConditionID, ID, 0 FROM #Job WITH(NOLOCK)
			SET @AllRows = @@ROWCOUNT

			IF @TopRows = 0 AND @AllRows > 100
				UPDATE SearchDB..paSearchJobID_3 SET IsTop = 1 
				WHERE paSearchConditionID = @paSearchConditionID
				AND ID IN (SELECT TOP 3 ID FROM SearchDB..paSearchJobID_3 WITH(NOLOCK) WHERE paSearchConditionID = @paSearchConditionID)
		END
		DROP TABLE #Job
		--PRINT 'DROP #JOB  ' + CONVERT(VARCHAR(30), GETDATE(), 121)
	COMMIT
	--GOTO GetRecordSet

	GetRecordSet:
	BEGIN
		----返回查询数量
		SELECT ValidJobNumber FROM SearchDB..paSearchCondition WITH(NOLOCK) WHERE ID=@paSearchConditionID
		UPDATE SearchDB..paSearchCondition SET ReuseNumber = ReuseNumber + 1 WHERE ID=@paSearchConditionID
		----返回20行查询结果
		IF (@TableID = 0)
		BEGIN
			SELECT @MinId = MIN(ID) FROM SearchDB..paSearchJobID_0 WITH(NOLOCK) WHERE paSearchConditionID=@paSearchConditionID

			SET @MinId = @MinId+(@PageNumber-1)*@PageSize
			SELECT TOP 30 a.ID, a.cpMainID, a.caMainID, a.Name as JobName, a.dcJobTypeID, 
				a.dcJobTypeIDMinor, a.NeedNumber, a.dcSalaryID, a.dcSalaryIDMax, a.EmployType, 
				a.dcRegionID, a.Responsibility, a.Demand, a.dcEducationID, 
				a.MinExperience, a.MinAge, a.MaxAge, a.IssueDate, a.IssueEND, 
				a.IsDelete, a.AddDate, a.RefreshDate, a.Lng, a.Lat,
				a.LastModifyDate, b.Name as cpName, b.dcCompanySizeID, 
				b.HasLicence, b.UnLimitedDate, b.BalanceDate, b.Balance, 
				b.MemberType, STUFF((SELECT ','+LTRIM(x.dcIndustryid)+',c'+LTRIM(isnull(y.Category,0)) 
							FROM cpIndustry x,dcIndustry y WHERE x.dcIndustryid = y.id 
							AND x.cpMainid = b.id FOR XML PATH('')),1,1,'') cpIndustry,
				c.IsTop, b.IsRefreshed, a.SecondId EnJobID, b.SecondId EnCpMainID, a.Welfare1,a.Welfare2,
				a.Welfare3, a.Welfare4,a.Welfare5,a.Welfare6,a.Welfare7,a.Welfare8, a.Welfare9,a.Welfare10,
				a.Welfare11,a.Welfare12,a.Welfare13, a.Welfare14,a.Welfare15,a.Welfare16,a.Welfare17,a.Welfare18,a.Welfare19, dbo.GetCaOnlineStatus(a.caMainID) AS IsOnline,
				CASE WHEN b.ReplyRate >= 0.6 THEN b.ReplyRate ELSE NULL END Replyrate, b.RealName
			FROM JobPublish a WITH(NOLOCK), cpMainPublish b WITH(NOLOCK), SearchDB..paSearchJobID_0 c WITH(NOLOCK)
			WHERE a.cpMainID = b.ID AND a.id=c.JobID AND c.paSearchConditionID=@paSearchConditionID 
				  AND c.ID>=@MinId ORDER BY c.ID, a.ID DESC
		END

		ELSE IF (@TableID = 1)
		BEGIN
			SELECT @MinId = MIN(ID) FROM SearchDB..paSearchJobID_1 WITH(NOLOCK) WHERE paSearchConditionID=@paSearchConditionID

			SET @MinId = @MinId+(@PageNumber-1)*@PageSize
			SELECT TOP 30 a.ID, a.cpMainID, a.caMainID, a.Name as JobName, a.dcJobTypeID, 
				a.dcJobTypeIDMinor, a.NeedNumber, a.dcSalaryID, a.dcSalaryIDMax, a.EmployType, 
				a.dcRegionID, a.Responsibility, a.Demand, a.dcEducationID, 
				a.MinExperience, a.MinAge, a.MaxAge, a.IssueDate, a.IssueEND, 
				a.IsDelete, a.AddDate, a.RefreshDate, a.Lng, a.Lat,
				a.LastModifyDate, b.Name as cpName, b.dcCompanySizeID, 
				b.HasLicence, b.UnLimitedDate, b.BalanceDate, b.Balance, 
				b.MemberType, STUFF((SELECT ','+LTRIM(x.dcIndustryid)+',c'+LTRIM(isnull(y.Category,0)) 
							FROM cpIndustry x,dcIndustry y WHERE x.dcIndustryid = y.id 
							AND x.cpMainid = b.id FOR XML PATH('')),1,1,'') cpIndustry,
				c.IsTop, b.IsRefreshed, a.SecondId EnJobID, b.SecondId EnCpMainID, a.Welfare1,a.Welfare2,
				a.Welfare3, a.Welfare4,a.Welfare5,a.Welfare6,a.Welfare7,a.Welfare8, a.Welfare9,a.Welfare10,
				a.Welfare11,a.Welfare12,a.Welfare13, a.Welfare14,a.Welfare15,a.Welfare16,a.Welfare17,a.Welfare18,a.Welfare19, dbo.GetCaOnlineStatus(a.caMainID) AS IsOnline,
				CASE WHEN b.ReplyRate >= 0.6 THEN b.ReplyRate ELSE NULL END Replyrate, b.RealName
			FROM JobPublish a WITH(NOLOCK), cpMainPublish b WITH(NOLOCK), SearchDB..paSearchJobID_1 c WITH(NOLOCK)
			WHERE a.cpMainID = b.ID AND a.id=c.JobID AND c.paSearchConditionID=@paSearchConditionID 
				  AND c.ID>=@MinId ORDER BY c.ID, a.ID DESC
		END
		ELSE IF (@TableID = 2)
		BEGIN
			SELECT @MinId = MIN(ID) FROM SearchDB..paSearchJobID_2 WITH(NOLOCK) WHERE paSearchConditionID=@paSearchConditionID

			SET @MinId = @MinId+(@PageNumber-1)*@PageSize
			SELECT TOP 30 a.ID, a.cpMainID, a.caMainID, a.Name as JobName, a.dcJobTypeID, 
				a.dcJobTypeIDMinor, a.NeedNumber, a.dcSalaryID, a.dcSalaryIDMax, a.EmployType, 
				a.dcRegionID, a.Responsibility, a.Demand, a.dcEducationID, 
				a.MinExperience, a.MinAge, a.MaxAge, a.IssueDate, a.IssueEND, 
				a.IsDelete, a.AddDate, a.RefreshDate, a.Lng, a.Lat,
				a.LastModifyDate, b.Name as cpName, b.dcCompanySizeID, 
				b.HasLicence, b.UnLimitedDate, b.BalanceDate, b.Balance, 
				b.MemberType, STUFF((SELECT ','+LTRIM(x.dcIndustryid)+',c'+LTRIM(isnull(y.Category,0)) 
							FROM cpIndustry x,dcIndustry y WHERE x.dcIndustryid = y.id 
							AND x.cpMainid = b.id FOR XML PATH('')),1,1,'') cpIndustry,
				c.IsTop, b.IsRefreshed, a.SecondId EnJobID, b.SecondId EnCpMainID, a.Welfare1,a.Welfare2,
				a.Welfare3, a.Welfare4,a.Welfare5,a.Welfare6,a.Welfare7,a.Welfare8, a.Welfare9,a.Welfare10,
				a.Welfare11,a.Welfare12,a.Welfare13, a.Welfare14,a.Welfare15,a.Welfare16,a.Welfare17,a.Welfare18,a.Welfare19, dbo.GetCaOnlineStatus(a.caMainID) AS IsOnline,
				CASE WHEN b.ReplyRate >= 0.6 THEN b.ReplyRate ELSE NULL END Replyrate, b.RealName
			FROM JobPublish a WITH(NOLOCK), cpMainPublish b WITH(NOLOCK), SearchDB..paSearchJobID_2 c WITH(NOLOCK)
			WHERE a.cpMainID = b.ID AND a.id=c.JobID AND c.paSearchConditionID=@paSearchConditionID 
				  AND c.ID>=@MinId ORDER BY c.ID, a.ID DESC
		END
		ELSE IF (@TableID = 3)
		BEGIN
			SELECT @MinId = MIN(ID) FROM SearchDB..paSearchJobID_3 WITH(NOLOCK) WHERE paSearchConditionID=@paSearchConditionID

			SET @MinId = @MinId+(@PageNumber-1)*@PageSize
			SELECT TOP 30 a.ID, a.cpMainID, a.caMainID, a.Name as JobName, a.dcJobTypeID, 
				a.dcJobTypeIDMinor, a.NeedNumber, a.dcSalaryID, a.dcSalaryIDMax, a.EmployType, 
				a.dcRegionID, a.Responsibility, a.Demand, a.dcEducationID, 
				a.MinExperience, a.MinAge, a.MaxAge, a.IssueDate, a.IssueEND, 
				a.IsDelete, a.AddDate, a.RefreshDate, a.Lng, a.Lat,
				a.LastModifyDate, b.Name as cpName, b.dcCompanySizeID, 
				b.HasLicence, b.UnLimitedDate, b.BalanceDate, b.Balance, 
				b.MemberType, STUFF((SELECT ','+LTRIM(x.dcIndustryid)+',c'+LTRIM(isnull(y.Category,0)) 
							FROM cpIndustry x,dcIndustry y WHERE x.dcIndustryid = y.id 
							AND x.cpMainid = b.id FOR XML PATH('')),1,1,'') cpIndustry,
				c.IsTop, b.IsRefreshed, a.SecondId EnJobID, b.SecondId EnCpMainID, a.Welfare1,a.Welfare2,
				a.Welfare3, a.Welfare4,a.Welfare5,a.Welfare6,a.Welfare7,a.Welfare8, a.Welfare9,a.Welfare10,
				a.Welfare11,a.Welfare12,a.Welfare13, a.Welfare14,a.Welfare15,a.Welfare16,a.Welfare17,a.Welfare18,a.Welfare19, dbo.GetCaOnlineStatus(a.caMainID) AS IsOnline,
				CASE WHEN b.ReplyRate >= 0.6 THEN b.ReplyRate ELSE NULL END Replyrate, b.RealName
			FROM JobPublish a WITH(NOLOCK), cpMainPublish b WITH(NOLOCK), SearchDB..paSearchJobID_3 c WITH(NOLOCK)
			WHERE a.cpMainID = b.ID AND a.id=c.JobID AND c.paSearchConditionID=@paSearchConditionID 
				  AND c.ID>=@MinId ORDER BY c.ID, a.ID DESC
		END
        --RICHARD 2011-7-23 16:51分修改
		----返回统计数量
		IF @Type=1
		BEGIN
			IF (@TableID = 0)
			BEGIN
				SELECT * FROM SearchDB..paSearchCount_0 WITH(NOLOCK) WHERE Title = 'JobType' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(VARCHAR(10), TitleID)
				SELECT * FROM SearchDB..paSearchCount_0 WITH(NOLOCK) WHERE Title = 'Region' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(VARCHAR(10), TitleID)
				SELECT * FROM SearchDB..paSearchCount_0 WITH(NOLOCK) WHERE Title = 'Education' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT * FROM SearchDB..paSearchCount_0 WITH(NOLOCK) WHERE Title = 'Experience' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT * FROM SearchDB..paSearchCount_0 WITH(NOLOCK) WHERE Title = 'Salary' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT * FROM SearchDB..paSearchCount_0 WITH(NOLOCK) WHERE Title = 'EmployType' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT * FROM SearchDB..paSearchCount_0 WITH(NOLOCK) WHERE Title = 'CompanySize' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
			END
			IF (@TableID = 1)
			BEGIN
				SELECT * FROM SearchDB..paSearchCount_1 WITH(NOLOCK) WHERE Title = 'JobType' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(VARCHAR(10), TitleID)
				SELECT * FROM SearchDB..paSearchCount_1 WITH(NOLOCK) WHERE Title = 'Region' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(VARCHAR(10), TitleID)
				SELECT * FROM SearchDB..paSearchCount_1 WITH(NOLOCK) WHERE Title = 'Education' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT * FROM SearchDB..paSearchCount_1 WITH(NOLOCK) WHERE Title = 'Experience' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT * FROM SearchDB..paSearchCount_1 WITH(NOLOCK) WHERE Title = 'Salary' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT * FROM SearchDB..paSearchCount_1 WITH(NOLOCK) WHERE Title = 'EmployType' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT * FROM SearchDB..paSearchCount_1 WITH(NOLOCK) WHERE Title = 'CompanySize' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
			END
			IF (@TableID = 2)
			BEGIN
				SELECT * FROM SearchDB..paSearchCount_2 WITH(NOLOCK) WHERE Title = 'JobType' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(VARCHAR(10), TitleID)
				SELECT * FROM SearchDB..paSearchCount_2 WITH(NOLOCK) WHERE Title = 'Region' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(VARCHAR(10), TitleID)
				SELECT * FROM SearchDB..paSearchCount_2 WITH(NOLOCK) WHERE Title = 'Education' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT * FROM SearchDB..paSearchCount_2 WITH(NOLOCK) WHERE Title = 'Experience' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT * FROM SearchDB..paSearchCount_2 WITH(NOLOCK) WHERE Title = 'Salary' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT * FROM SearchDB..paSearchCount_2 WITH(NOLOCK) WHERE Title = 'EmployType' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT * FROM SearchDB..paSearchCount_2 WITH(NOLOCK) WHERE Title = 'CompanySize' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
			END
			IF (@TableID = 3)
			BEGIN
				SELECT * FROM SearchDB..paSearchCount_3 WITH(NOLOCK) WHERE Title = 'JobType' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(VARCHAR(10), TitleID)
				SELECT * FROM SearchDB..paSearchCount_3 WITH(NOLOCK) WHERE Title = 'Region' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(VARCHAR(10), TitleID)
				SELECT * FROM SearchDB..paSearchCount_3 WITH(NOLOCK) WHERE Title = 'Education' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT * FROM SearchDB..paSearchCount_3 WITH(NOLOCK) WHERE Title = 'Experience' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT * FROM SearchDB..paSearchCount_3 WITH(NOLOCK) WHERE Title = 'Salary' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT * FROM SearchDB..paSearchCount_3 WITH(NOLOCK) WHERE Title = 'EmployType' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT * FROM SearchDB..paSearchCount_3 WITH(NOLOCK) WHERE Title = 'CompanySize' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
			END
		END
		RETURN
	END
END TRY
BEGIN CATCH
	---检查是否已经建立临时表，已经建立则删除
	DECLARE @para VARCHAR(MAX)
	SET @para = '@dcJobTypeID=' + ISNULL(@dcJobTypeID, '') + '|' +
		'@dcIndustryID=' + ISNULL(@dcIndustryID, '') + '|' +
		'@EmployType=' + ISNULL(@EmployType, '') + '|' +
		'@KeyWord=' + ISNULL(@KeyWord, '')
	INSERT INTO ErrorLog	
	SELECT 'p3 ' +ISNULL(error_Message(), ' no msg')+ ' para=' + ISNULL(@Para, 'no para ') + ISNULL(@SQL, ' no sql'), error_number(), error_line(), GETDATE()
END CATCH






GO
/****** Object:  StoredProcedure [dbo].[pcJobByNewstSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[pcJobByNewstSelect] 
(
	@dcProvinceID INT
)
AS
SET NOCOUNT ON
--insert proclog select 'pcJobByNewstSelect', @dcProvinceID, getdate()
BEGIN
	IF NOT EXISTS(SELECT 'x' FROM SearchDb..JobNewst WHERE AddDate > DATEADD(MINUTE, -3, GETDATE()) AND ProvinceId = @dcProvinceID)
	BEGIN
		DELETE FROM SearchDb..JobNewst WHERE ProvinceId = @dcProvinceID

		INSERT INTO SearchDb..JobNewst(cpMainName, JobName, JobId, CpMainID, cpId, JId, ProvinceID, AddDate)
		SELECT TOP 10 a.Name, b.Name, b.ID, a.Id, a.SecondId, b.SecondId, @dcProvinceID, GETDATE()
		FROM cpMainPublish a WITH(NOLOCK)
		INNER JOIN JobPublish b WITH(NOLOCK) ON a.ID = b.cpMainId
		WHERE b.dcRegionID LIKE LTRIM(STR(@dcProvinceID)) + '%'
		AND a.Valid = 1
		AND b.Valid = 1
		AND a.MemberType > 1
		AND a.dcProvinceId = LEFT(@dcProvinceId, 2)
		ORDER BY b.ID DESC
	END
	SELECT cpMainName, JobName, JobId, CpMainID, cpId, JId FROM SearchDb..JobNewst WITH(NOLOCK) WHERE ProvinceId = @dcProvinceID
END



GO
/****** Object:  StoredProcedure [dbo].[pcJobByRecommendSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[pcJobByRecommendSelect] 
(
	@dcJobTypeID VARCHAR(100), 		--职位类别
	@dcRegionID VARCHAR(100), 		--求职地区
	@dcIndustryID VARCHAR(100), 	--求职行业
	@dcSalaryID TINYINT, 			--月薪
	@MinExperience TINYINT, 		--工作经验，100为未选择
	@dcEducationID TINYINT, 		--最低学历
	@EmployType VARCHAR(10), 		--工作性质，1全职；3兼职；4实习
	@RowCount SMALLINT				--需要显示的行数
)
AS
SET NOCOUNT ON
BEGIN
	SELECT @dcJobTypeID = RTRIM(dbo.FormatIDS(@dcJobTypeID)),
		@dcRegionID = RTRIM(dbo.FormatIDS(@dcRegionID)),
		@dcIndustryID = RTRIM(dbo.FormatIDS(@dcIndustryID)),
		@dcSalaryID = ISNULL(@dcSalaryID, 0),
		@MinExperience = ISNULL(@MinExperience, 100),
		@dcEducationID = ISNULL(@dcEducationID, 0),
		@EmployType = CASE @EmployType WHEN '2' THEN '1,3' ELSE ISNULL(@EmployType, '') END

	IF @dcJobTypeID LIKE '%,%,%,%,%,%'
		SET @dcJobTypeID = LEFT(@dcJobTypeID, 2)
	IF @dcRegionID LIKE '%,%,%,%,%,%'
		SET @dcRegionID = LEFT(@dcRegionID, 2)

	IF RIGHT(@dcJobTypeID, 1) = ','
		SET @dcJobTypeID = LEFT(@dcJobTypeID, LEN(@dcJobTypeID) - 1)
	IF RIGHT(@dcRegionID, 1) = ','
		SET @dcRegionID = LEFT(@dcRegionID, LEN(@dcRegionID) - 1)
	IF RIGHT(@dcIndustryID, 1) = ','
		SET @dcIndustryID = LEFT(@dcIndustryID, LEN(@dcIndustryID) - 1)

	------生成职位类别的表变量，因为职位类别有包含（父子）关系
	DECLARE @T_JobPlace AS TABLE(ID INT)
	DECLARE @T_JobType AS TABLE(ID INT)
	DECLARE @JobType AS VARCHAR(3000)
	DECLARE @JobPlace AS VARCHAR(2000)
	DECLARE @SQL AS NVARCHAR(MAX)
	DECLARE @WHERE AS VARCHAR(8000)
	DECLARE @FROM AS VARCHAR(1000)

	SET @JobPlace = ''
	SET @JobType=''
	----生成工作地点的表变量
	IF LEN(@dcRegionID) > 0
	BEGIN
		INSERT INTO @T_JobPlace
		SELECT * FROM dbo.fnSplit(@dcRegionID, ',')
		SELECT @JobPlace = (@JobPlace + ' OR a.dcRegionID Like ''' + LTRIM(STR(ID) + '%''')) FROM @T_JobPlace
		IF LEN(@JobPlace) > 0
			SET @JobPlace = RIGHT(@JobPlace, LEN(@JobPlace) -4)
	END

	----生成求聘职位的表变量
	IF LEN(@dcJobTypeID) > 0
	BEGIN
		DECLARE @T_Temp AS TABLE(ID INT)		--临时表，用于构建组合查询语句
		INSERT INTO @T_Temp
		SELECT * FROM dbo.fnSplit(@dcJobTypeID, ',')

		INSERT INTO @T_JobType
		SELECT DISTINCT ID FROM dcJobType WITH(NOLOCK)
		WHERE ParentId IN(SELECT ID FROM @T_TEMP) 
		OR ParentId2 in(SELECT ID FROM @T_TEMP)
		OR ID IN(SELECT ID FROM @T_TEMP)
		----生成in字符串
		SELECT @JobType = (@JobType + LTRIM(STR(ID) + ',')) FROM @T_JobType                                              
		IF RIGHT(@JobType, 1) = ','
			SET @JobType = LEFT(@JobType, LEN(@JobType) - 1)
	END

	----建立临时表
	CREATE TABLE #Job(
		RowID INT IDENTITY(1, 1), 
		ID INT NOT NULL, 
		dcJobTypeID SMALLINT NOT NULL, 
		dcJobTypeIDMinor SMALLINT NULL, 
		dcSalaryID TINYINT NOT NULL, 
		dcRegionID VARCHAR(6) NULL, 
		dcEducationID TINYINT NOT NULL, 
		MinExperience TINYINT NOT NULL, 
		RefreshDate SMALLDATETIME NULL
	)

	----生成插入临时表的Sql语句
	SET @SQL = '
		INSERT INTO #Job
		SELECT TOP ' + CONVERT(VARCHAR(3),@RowCount) + ' a.ID, a.dcJobTypeID, 
			a.dcJobTypeIDMinor, a.dcSalaryID, 
			a.dcRegionID, a.dcEducationID, a.MinExperience, 
			a.IssueDate'
	SET @FROM = '
		FROM JobPublish a WITH(NOLOCK)
		INNER JOIN cpMainPublish b WITH(NOLOCK) ON a.cpMainID=b.ID'
	----职位有效，单位新有效
	IF LEN(@dcIndustryID) > 0
		SET @WHERE = '
		WHERE b.ID IN (SELECT cpMainID FROM cpIndustry WHERE dcIndustryId in(' + @dcIndustryID + '))
		AND a.Valid = 1
		AND b.Valid = 1'
	ELSE
		SET @WHERE = '
		WHERE a.Valid = 1
		AND b.Valid = 1'

	----职位类别
	IF LEN(@dcJobTypeID) > 0
		SET @WHERE = @WHERE + '
		AND (a.dcJobTypeID IN(' + @JobType +')
			OR a.dcJobTypeIDMinor IN(' +@JobType + '))'
	IF LEN(@JobPlace) > 0 
		SET @WHERE = @WHERE + '
		AND (' + @JobPlace + ')'

	IF @dcSalaryID > 0
	BEGIN
		IF @dcSalaryID < 100				----从form中搜索，月薪跨2个级别, 是本级和上级别的薪金
		BEGIN
			SET @WHERE = @WHERE + '
		AND a.dcSalaryID IN(' + LTRIM(STR(@dcSalaryID)) + ',' + LTRIM(STR(@dcSalaryID + 1))
			SET @WHERE = @WHERE + ')'
		END
		IF @dcSalaryID = 100	----从筛选结果中点击面议，值是100
		BEGIN
			SET @WHERE = @WHERE + '
		AND a.dcSalaryID = 100'
		END
		IF @dcSalaryID > 100	----从筛选结果中点击搜索，月薪只有1个级别，传值时增加100
			SET @WHERE = @WHERE + '
		AND a.dcSalaryID=' + LTRIM(STR(@dcSalaryID-100))
	END
	----工作经验要求
	IF @MinExperience < 100
	SET @WHERE = @WHERE + ' 
		AND a.MinExperience = ' + LTRIM(STR(@MinExperience))

	----学历要求
	----'1初中', '2\3\4高中、中技、中专', '5大专', '6本科', '7硕士', '8博士
	IF @dcEducationID > 0
		IF @dcEducationID = 2
			SET @WHERE = @WHERE + '
		AND a.dcEducationID IN(2, 3, 4)'
		ELSE
			SET @WHERE = @WHERE + '
		AND a.dcEducationID = ' + LTRIM(STR(@dcEducationID))
	----1、全职；3、兼职；4实习。	2、全职/兼职 职位中无此项
	IF LEN(@EmployType) > 0
		SET @WHERE = @WHERE + '
		AND a.EmployType IN (' + @EmployType + ')'

	SET @SQL = @SQL + @FROM + @WHERE
	SET @SQL = @SQL + ' ORDER BY a.RefreshDate DESC, a.ID'
	EXEC(@SQL)
	DECLARE @CurrentCount AS SMALLINT
	DECLARE @NeedCount AS SMALLINT
	SELECT @CurrentCount = COUNT(*) FROM #Job
	IF @CurrentCount < @RowCount
	BEGIN
		SET @NeedCount = @RowCount - @CurrentCount
		----生成插入临时表的Sql语句
		SET @SQL = '
			INSERT INTO #Job
			SELECT TOP ' + CONVERT(VARCHAR(3),@NeedCount) + ' a.ID, a.dcJobTypeID, 
				a.dcJobTypeIDMinor, a.dcSalaryID, 
				a.dcRegionID, a.dcEducationID, a.MinExperience, 
				a.IssueDate'
		SET @FROM = '
			FROM JobPublish a WITH(NOLOCK)
			INNER JOIN cpMainPublish b WITH(NOLOCK) ON a.cpMainID=b.ID'
		----职位有效，单位新有效
		SET @WHERE = '
		WHERE a.Valid = 1
		AND b.Valid = 1 AND a.ID NOT IN(SELECT ID FROM #Job)'

		----职位类别
		IF LEN(@dcJobTypeID) > 0
			SET @WHERE = @WHERE + '
			AND (a.dcJobTypeID IN(' + @JobType +')
				OR a.dcJobTypeIDMinor IN(' +@JobType + '))'
		IF LEN(@JobPlace) > 0 
			SET @WHERE = @WHERE + '
			AND (' + @JobPlace + ')'
		SET @SQL = @SQL + @FROM + @WHERE
		SET @SQL = @SQL + ' ORDER BY a.RefreshDate DESC, a.ID'
		EXEC(@SQL)
		SELECT @CurrentCount = COUNT(*) FROM #Job
		IF @CurrentCount < @RowCount
		BEGIN
			SET @NeedCount = @RowCount - @CurrentCount
			--将工作地点扩大一级
			DECLARE @T_JobPlaceDistinct AS TABLE(ID INT)
			UPDATE @T_JobPlace SET ID = LEFT(ID,LEN(ID)-2) WHERE LEN(ID) > 2
			INSERT INTO @T_JobPlaceDistinct SELECT DISTINCT ID FROM @T_JobPlace
			SELECT @JobPlace = ''
			SELECT @JobPlace = (@JobPlace + ' OR a.dcRegionID Like ''' + LTRIM(STR(ID) + '%''')) FROM @T_JobPlaceDistinct
			IF LEN(@JobPlace) > 0
				SET @JobPlace = RIGHT(@JobPlace, LEN(@JobPlace) -4)

			--将职位类别扩大一级
			UPDATE @T_TEMP SET ID = LEFT(ID,LEN(ID)-2) WHERE LEN(ID) > 2
			DELETE FROM @T_JobType
			INSERT INTO @T_JobType
				SELECT DISTINCT ID FROM dcJobType WITH(NOLOCK)
				WHERE ParentId IN(SELECT ID FROM @T_TEMP) 
				OR ParentId2 in(SELECT ID FROM @T_TEMP)
				OR ID IN(SELECT ID FROM @T_TEMP)

			SELECT @JobType = ''
			SELECT @JobType = (@JobType + LTRIM(STR(ID) + ',')) FROM @T_JobType

			IF RIGHT(@JobType, 1) = ','
				SET @JobType = LEFT(@JobType, LEN(@JobType) - 1)

			----生成插入临时表的Sql语句
			SET @SQL = '
				INSERT INTO #Job
				SELECT TOP ' + CONVERT(VARCHAR(3),@NeedCount) + ' a.ID, a.dcJobTypeID, 
					a.dcJobTypeIDMinor, a.dcSalaryID, 
					a.dcRegionID, a.dcEducationID, a.MinExperience, 
					a.IssueDate'
			SET @FROM = '
				FROM JobPublish a WITH(NOLOCK)
				INNER JOIN cpMainPublish b WITH(NOLOCK) ON a.cpMainID=b.ID'
			----职位有效，单位新有效
			SET @WHERE = '
			WHERE a.Valid = 1
			AND b.Valid = 1 AND a.ID NOT IN(SELECT ID FROM #Job)'

			----职位类别
			IF LEN(@dcJobTypeID) > 0
				SET @WHERE = @WHERE + '
				AND (a.dcJobTypeID IN(' + @JobType +')
					OR a.dcJobTypeIDMinor IN(' +@JobType + '))'
			IF LEN(@JobPlace) > 0 
				SET @WHERE = @WHERE + '
				AND (' + @JobPlace + ')'
			SET @SQL = @SQL + @FROM + @WHERE
			SET @SQL = @SQL + ' ORDER BY a.RefreshDate DESC, a.ID'
			EXEC(@SQL)
		END
	END
	SELECT TOP 20 a.ID, a.cpMainID, a.caMainID, a.Name as JobName, a.dcJobTypeID, 
		a.dcJobTypeIDMinor, a.NeedNumber, a.dcSalaryID, a.dcSalaryIDMax, a.EmployType, 
		a.dcRegionID, a.Responsibility, a.Demand, a.dcEducationID, 
		a.MinExperience, a.MinAge, a.MaxAge, a.IssueDate, a.IssueEND, 
		a.IsDelete, a.AddDate, a.RefreshDate, a.SecondId EnJobID, b.SecondId EnCpMainID,
		a.LastModifyDate, b.Name as cpName, b.dcCompanySizeID, 
		b.HasLicence, b.UnLimitedDate, b.BalanceDate, b.Balance, 
		ISNULL((SELECT IsOnline FROM caOnline WHERE caMainId =a.caMainID), 0) AS IsOnline,
		b.MemberType, STUFF((SELECT ','+LTRIM(x.dcIndustryid)+',c'+LTRIM(isnull(y.Category,0)) 
					FROM cpIndustry x,dcIndustry y WHERE x.dcIndustryid = y.id 
					AND x.cpMainid = b.id FOR XML PATH('')),1,1,'') cpIndustry, b.IsRefreshed,
		dbo.GetCaOnlineStatus(a.caMainID) AS IsOnline, CASE WHEN b.ReplyRate >= 0.6 THEN b.ReplyRate ELSE NULL END Replyrate
	FROM JobPublish a WITH(NOLOCK), cpMainPublish b WITH(NOLOCK), #Job c WITH(NOLOCK)
	WHERE a.cpMainID = b.ID AND a.ID = c.ID ORDER BY c.RowID
END




GO
/****** Object:  StoredProcedure [dbo].[pcJobByRecommendSelectNew]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[pcJobByRecommendSelectNew] 
(
	@dcJobTypeID VARCHAR(100), 		--职位类别
	@dcRegionID VARCHAR(100), 		--求职地区
	@dcIndustryID VARCHAR(100), 	--求职行业
	@dcSalaryID TINYINT, 			--月薪
	@MinExperience TINYINT, 		--工作经验，100为未选择
	@dcEducationID TINYINT, 		--最低学历
	@EmployType VARCHAR(10), 		--工作性质，1全职；3兼职；4实习
	@RowCount SMALLINT				--需要显示的行数
)
AS
--INSERT INTO procLog SELECT 'pcJobByRecommendSelectNew', '', GETDATE()
BEGIN
	SELECT @dcJobTypeID = RTRIM(dbo.FormatIDS(@dcJobTypeID)),
		@dcRegionID = RTRIM(dbo.FormatIDS(@dcRegionID)),
		@dcIndustryID = RTRIM(dbo.FormatIDS(@dcIndustryID)),
		@dcSalaryID = ISNULL(@dcSalaryID, 0),
		@MinExperience = ISNULL(@MinExperience, 100),
		@dcEducationID = ISNULL(@dcEducationID, 0),
		@EmployType = CASE @EmployType WHEN '2' THEN '1,3' ELSE ISNULL(@EmployType, '') END

	IF @dcJobTypeID LIKE '%,%,%,%,%,%'
		SET @dcJobTypeID = LEFT(@dcJobTypeID, 2)
	IF @dcRegionID LIKE '%,%,%,%,%,%'
		SET @dcRegionID = LEFT(@dcRegionID, 2)

	IF RIGHT(@dcJobTypeID, 1) = ','
		SET @dcJobTypeID = LEFT(@dcJobTypeID, LEN(@dcJobTypeID) - 1)
	IF RIGHT(@dcRegionID, 1) = ','
		SET @dcRegionID = LEFT(@dcRegionID, LEN(@dcRegionID) - 1)
	IF RIGHT(@dcIndustryID, 1) = ','
		SET @dcIndustryID = LEFT(@dcIndustryID, LEN(@dcIndustryID) - 1)

	------生成职位类别的表变量，因为职位类别有包含（父子）关系
	DECLARE @T_JobPlace AS TABLE(ID INT)
	DECLARE @T_JobType AS TABLE(ID INT)
	DECLARE @JobType AS VARCHAR(3000)
	DECLARE @JobPlace AS VARCHAR(2000)
	DECLARE @SQL AS NVARCHAR(MAX)
	DECLARE @WHERE AS VARCHAR(8000)
	DECLARE @FROM AS VARCHAR(1000)

	SET @JobPlace = ''
	SET @JobType=''
	----生成工作地点的表变量
	IF LEN(@dcRegionID) > 0
	BEGIN
		INSERT INTO @T_JobPlace
		SELECT * FROM dbo.fnSplit(@dcRegionID, ',')
		SELECT @JobPlace = (@JobPlace + ' OR a.dcRegionID Like ''' + LTRIM(STR(ID) + '%''')) FROM @T_JobPlace
		IF LEN(@JobPlace) > 0
			SET @JobPlace = RIGHT(@JobPlace, LEN(@JobPlace) -4)
	END

	----生成求聘职位的表变量
	IF LEN(@dcJobTypeID) > 0
	BEGIN
		DECLARE @T_Temp AS TABLE(ID INT)		--临时表，用于构建组合查询语句
		INSERT INTO @T_Temp
		SELECT * FROM dbo.fnSplit(@dcJobTypeID, ',')

		INSERT INTO @T_JobType
		SELECT DISTINCT ID FROM dcJobType WITH(NOLOCK)
		WHERE ParentId IN(SELECT ID FROM @T_TEMP) 
		OR ParentId2 in(SELECT ID FROM @T_TEMP)
		OR ID IN(SELECT ID FROM @T_TEMP)
		----生成in字符串
		SELECT @JobType = (@JobType + LTRIM(STR(ID) + ',')) FROM @T_JobType                                              
		IF RIGHT(@JobType, 1) = ','
			SET @JobType = LEFT(@JobType, LEN(@JobType) - 1)
	END

	----建立临时表
	CREATE TABLE #Job(
		RowID INT IDENTITY(1, 1), 
		ID INT NOT NULL, 
		dcJobTypeID SMALLINT NOT NULL, 
		dcJobTypeIDMinor SMALLINT NULL, 
		dcSalaryID TINYINT NOT NULL, 
		dcRegionID VARCHAR(6) NULL, 
		dcEducationID TINYINT NOT NULL, 
		MinExperience TINYINT NOT NULL, 
		RefreshDate SMALLDATETIME NULL
	)

	----生成插入临时表的Sql语句
	SET @SQL = '
		INSERT INTO #Job
		SELECT TOP ' + CONVERT(VARCHAR(3),@RowCount) + ' a.ID, a.dcJobTypeID, 
			a.dcJobTypeIDMinor, a.dcSalaryID, 
			a.dcRegionID, a.dcEducationID, a.MinExperience, 
			a.IssueDate'
	SET @FROM = '
		FROM JobPublish a WITH(NOLOCK)
		INNER JOIN cpMainPublish b WITH(NOLOCK) ON a.cpMainID=b.ID'
	----职位有效，单位新有效
	IF LEN(@dcIndustryID) > 0
		SET @WHERE = '
		WHERE b.ID IN (SELECT cpMainID FROM cpIndustry WHERE dcIndustryId in(' + @dcIndustryID + '))
		AND a.Valid = 1
		AND b.Valid = 1'
	ELSE
		SET @WHERE = '
		WHERE a.Valid = 1
		AND b.Valid = 1'

	----职位类别
	IF LEN(@dcJobTypeID) > 0
		SET @WHERE = @WHERE + '
		AND (a.dcJobTypeID IN(' + @JobType +')
			OR a.dcJobTypeIDMinor IN(' +@JobType + '))'
	IF LEN(@JobPlace) > 0 
		SET @WHERE = @WHERE + '
		AND (' + @JobPlace + ')'

	IF @dcSalaryID > 0
	BEGIN
		IF @dcSalaryID < 100				----从form中搜索，月薪跨2个级别, 是本级和上级别的薪金
		BEGIN
			SET @WHERE = @WHERE + '
		AND a.dcSalaryID IN(' + LTRIM(STR(@dcSalaryID)) + ',' + LTRIM(STR(@dcSalaryID + 1))
			SET @WHERE = @WHERE + ')'
		END
		IF @dcSalaryID = 100	----从筛选结果中点击面议，值是100
		BEGIN
			SET @WHERE = @WHERE + '
		AND a.dcSalaryID = 100'
		END
		IF @dcSalaryID > 100	----从筛选结果中点击搜索，月薪只有1个级别，传值时增加100
			SET @WHERE = @WHERE + '
		AND a.dcSalaryID=' + LTRIM(STR(@dcSalaryID-100))
	END
	----工作经验要求
	IF @MinExperience < 100
	SET @WHERE = @WHERE + ' 
		AND a.MinExperience = ' + LTRIM(STR(@MinExperience))

	----学历要求
	----'1初中', '2\3\4高中、中技、中专', '5大专', '6本科', '7硕士', '8博士
	IF @dcEducationID > 0
		IF @dcEducationID = 2
			SET @WHERE = @WHERE + '
		AND a.dcEducationID IN(2, 3, 4)'
		ELSE
			SET @WHERE = @WHERE + '
		AND a.dcEducationID = ' + LTRIM(STR(@dcEducationID))
	----1、全职；3、兼职；4实习。	2、全职/兼职 职位中无此项
	IF LEN(@EmployType) > 0
		SET @WHERE = @WHERE + '
		AND a.EmployType IN (' + @EmployType + ')'

	SET @SQL = @SQL + @FROM + @WHERE
	SET @SQL = @SQL + ' ORDER BY a.RefreshDate DESC, a.ID'
	EXEC(@SQL)
	DECLARE @CurrentCount AS SMALLINT
	DECLARE @NeedCount AS SMALLINT
	SELECT @CurrentCount = COUNT(*) FROM #Job
	IF @CurrentCount < @RowCount
	BEGIN
		SET @NeedCount = @RowCount - @CurrentCount
		----生成插入临时表的Sql语句
		SET @SQL = '
			INSERT INTO #Job
			SELECT TOP ' + CONVERT(VARCHAR(3),@NeedCount) + ' a.ID, a.dcJobTypeID, 
				a.dcJobTypeIDMinor, a.dcSalaryID, 
				a.dcRegionID, a.dcEducationID, a.MinExperience, 
				a.IssueDate'
		SET @FROM = '
			FROM JobPublish a WITH(NOLOCK)
			INNER JOIN cpMainPublish b WITH(NOLOCK) ON a.cpMainID=b.ID'
		----职位有效，单位新有效
		SET @WHERE = '
		WHERE a.Valid = 1
		AND b.Valid = 1 AND a.ID NOT IN(SELECT ID FROM #Job)'

		----职位类别
		IF LEN(@dcJobTypeID) > 0
			SET @WHERE = @WHERE + '
			AND (a.dcJobTypeID IN(' + @JobType +')
				OR a.dcJobTypeIDMinor IN(' +@JobType + '))'
		IF LEN(@JobPlace) > 0 
			SET @WHERE = @WHERE + '
			AND (' + @JobPlace + ')'
		SET @SQL = @SQL + @FROM + @WHERE
		SET @SQL = @SQL + ' ORDER BY a.RefreshDate DESC, a.ID'
		EXEC(@SQL)
		SELECT @CurrentCount = COUNT(*) FROM #Job
		IF @CurrentCount < @RowCount
		BEGIN
			SET @NeedCount = @RowCount - @CurrentCount
			--将工作地点扩大一级
			DECLARE @T_JobPlaceDistinct AS TABLE(ID INT)
			UPDATE @T_JobPlace SET ID = LEFT(ID,LEN(ID)-2) WHERE LEN(ID) > 2
			INSERT INTO @T_JobPlaceDistinct SELECT DISTINCT ID FROM @T_JobPlace
			SELECT @JobPlace = ''
			SELECT @JobPlace = (@JobPlace + ' OR a.dcRegionID Like ''' + LTRIM(STR(ID) + '%''')) FROM @T_JobPlaceDistinct
			IF LEN(@JobPlace) > 0
				SET @JobPlace = RIGHT(@JobPlace, LEN(@JobPlace) -4)

			--将职位类别扩大一级
			UPDATE @T_TEMP SET ID = LEFT(ID,LEN(ID)-2) WHERE LEN(ID) > 2
			DELETE FROM @T_JobType
			INSERT INTO @T_JobType
				SELECT DISTINCT ID FROM dcJobType WITH(NOLOCK)
				WHERE ParentId IN(SELECT ID FROM @T_TEMP) 
				OR ParentId2 in(SELECT ID FROM @T_TEMP)
				OR ID IN(SELECT ID FROM @T_TEMP)

			SELECT @JobType = ''
			SELECT @JobType = (@JobType + LTRIM(STR(ID) + ',')) FROM @T_JobType

			IF RIGHT(@JobType, 1) = ','
				SET @JobType = LEFT(@JobType, LEN(@JobType) - 1)

			----生成插入临时表的Sql语句
			SET @SQL = '
				INSERT INTO #Job
				SELECT TOP ' + CONVERT(VARCHAR(3),@NeedCount) + ' a.ID, a.dcJobTypeID, 
					a.dcJobTypeIDMinor, a.dcSalaryID, 
					a.dcRegionID, a.dcEducationID, a.MinExperience, 
					a.IssueDate'
			SET @FROM = '
				FROM JobPublish a WITH(NOLOCK)
				INNER JOIN cpMainPublish b WITH(NOLOCK) ON a.cpMainID=b.ID'
			----职位有效，单位新有效
			SET @WHERE = '
			WHERE a.Valid = 1
			AND b.Valid = 1 AND a.ID NOT IN(SELECT ID FROM #Job)'

			----职位类别
			IF LEN(@dcJobTypeID) > 0
				SET @WHERE = @WHERE + '
				AND (a.dcJobTypeID IN(' + @JobType +')
					OR a.dcJobTypeIDMinor IN(' +@JobType + '))'
			IF LEN(@JobPlace) > 0 
				SET @WHERE = @WHERE + '
				AND (' + @JobPlace + ')'
			SET @SQL = @SQL + @FROM + @WHERE
			SET @SQL = @SQL + ' ORDER BY a.RefreshDate DESC, a.ID'
			EXEC(@SQL)
		END
	END
	SELECT TOP 20 a.ID, a.cpMainID, a.caMainID, a.Name as JobName, a.dcJobTypeID, 
		a.dcJobTypeIDMinor, a.NeedNumber, a.dcSalaryID, a.EmployType, 
		a.dcRegionID, a.Responsibility, a.Demand, a.dcEducationID, 
		a.MinExperience, a.MinAge, a.MaxAge, a.IssueDate, a.IssueEND, 
		a.IsDelete, a.AddDate, a.RefreshDate, a.SecondId EnJobID, b.SecondId EnCpMainID,
		a.LastModifyDate, b.Name as cpName, b.dcCompanySizeID, 
		b.HasLicence, b.UnLimitedDate, b.BalanceDate, b.Balance, 
		ISNULL((SELECT IsOnline FROM caOnline WHERE caMainId =a.caMainID), 0) AS IsOnline,
		b.MemberType, STUFF((SELECT ','+LTRIM(x.dcIndustryid)+',c'+LTRIM(isnull(y.Category,0)) 
					FROM cpIndustry x,dcIndustry y WHERE x.dcIndustryid = y.id 
					AND x.cpMainid = b.id FOR XML PATH('')),1,1,'') cpIndustry, b.IsRefreshed,
		dbo.GetCaOnlineStatus(a.caMainID) AS IsOnline
	FROM JobPublish a WITH(NOLOCK), cpMainPublish b WITH(NOLOCK), #Job c WITH(NOLOCK)
	WHERE a.cpMainID = b.ID AND a.ID = c.ID ORDER BY c.RowID
END






GO
/****** Object:  StoredProcedure [dbo].[pcJobBySearchSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE proCEDURE [dbo].[pcJobBySearchSelect]
(
	@dcJobTypeID VARCHAR(100), 		--职位类别
	@dcRegionID VARCHAR(100), 		--求职地区
	@dcIndustryID VARCHAR(100), 	--求职行业
	@dcSalaryID TINYINT, 			--月薪
	@IsNegotiable BIT, 				--1允许面议，不面议
	@MinExperience TINYINT, 		--工作经验，100为未选择
	@dcEducationID TINYINT, 		--最低学历
	@EmployType VARCHAR(10), 		--工作性质，1全职；3兼职；4实习，
	@KeyWord NVARCHAR(50), 			--关键词
	@KeyType TINYINT, 				--搜索类别，0无；1-全文；2-职位；3-公司 
	@ORDER VARCHAR(100), 			--显示顺序，没有用
	@RefreshNo INT, 				--1, 1天内；2, 3天内；3，一周内；4，15天内；5，一个月内；6超过一个月
	@Type INT, 						--1：主动搜索  点击搜索按钮 10分钟，翻页60分钟有效；0：翻页搜索，不刷新
	@PageNumber INT, 				--翻页页码
	@SessionID varchar(50), 
	@CompanySizeID VARCHAR(1), 		--企业规模
	@JobId INT,
	@Welfare VARCHAR(50),
	@IsOnline BIT				--是否在线
)
AS
SET NOCOUNT ON
INSERT INTO SearchIp(Ip, Source) SELECT @SessionId, 'r'

DECLARE @CanReturn BIT
SET @CanReturn = 0
IF EXISTS(SELECT 'x' FROM RefuseIp WITH(NOLOCK) WHERE CHARINDEX(Ip,@SessionId) > 0)
	SET @CanReturn = 1
IF CHARINDEX(',0', @dcRegionID) > 0 OR CHARINDEX(',0', @dcJobTypeID) > 0 
	OR CHARINDEX(',,', @dcRegionID) > 0 OR CHARINDEX(',,', @dcJobTypeID) > 0
	OR LEN(@dcRegionID) > 35 OR LEN(@dcJobTypeID) > 25
	SET @CanReturn = 1
IF @CanReturn = 1
BEGIN
	SELECT 0 ValidJobNumber
	SELECT TOP 0 * FROM JobTemp
	SELECT TOP 0 * FROM SearchDB..paSearchCount_0
	SELECT TOP 0 * FROM SearchDB..paSearchCount_0
	SELECT TOP 0 * FROM SearchDB..paSearchCount_0
	SELECT TOP 0 * FROM SearchDB..paSearchCount_0
	SELECT TOP 0 * FROM SearchDB..paSearchCount_0
	SELECT TOP 0 * FROM SearchDB..paSearchCount_0
	SELECT TOP 0 * FROM SearchDB..paSearchCount_0
	--insert into _0 select @SessionId, getdate()
	RETURN
END
IF Rand() * 10 > 5  AND (@SessionId LIKE '123.125.71%' OR @SessionId LIKE '220.181.108%')
BEGIN
	SELECT 0 ValidJobNumber
	SELECT TOP 0 * FROM JobTemp
	SELECT TOP 0 * FROM SearchDB..paSearchCount_0
	SELECT TOP 0 * FROM SearchDB..paSearchCount_0
	SELECT TOP 0 * FROM SearchDB..paSearchCount_0
	SELECT TOP 0 * FROM SearchDB..paSearchCount_0
	SELECT TOP 0 * FROM SearchDB..paSearchCount_0
	SELECT TOP 0 * FROM SearchDB..paSearchCount_0
	SELECT TOP 0 * FROM SearchDB..paSearchCount_0

	RETURN
END
INSERT INTO SearchDB..paSearchLog(ProcType, SessionID, LogTime, JobType, JobPlace, Industry, Education, Experience, 
	Salary, IsNegotiable, EmployType, CompanySizeID, KeyWord, KeyType, ReuseNumber, Welfare, IsOnline, RefreshNo)
VALUES('pcJobBySearchSelect', @SessionId, GETDATE(), @dcJobTypeID, @dcRegionID, @dcIndustryID, @dcEducationID, @MinExperience, 
	@dcSalaryID, 0, @EmployType, @CompanySizeID, @KeyWord, @KeyType, 0, @Welfare, @IsOnline, @RefreshNo)

SET @SessionId = 20
----------------------20160126 nick 得到 省份、排序
DECLARE @paMainId INT, @SQL AS VARCHAR(8000)
SET @paMainId = 0
BEGIN TRY
	IF @Order LIKE 'r=%'
		SET @KeyType = CONVERT(DECIMAL(4, 2), RIGHT(LEFT(@Order, 5), 3)) * 100
	ELSE
		SET @KeyType = 0
	IF @Order LIKE '%p=%'
		SET @paMainId = RIGHT(@Order, LEN(@Order) - CHARINDEX('p=', @Order) - 1)	
END TRY
BEGIN CATCH
	SET @KeyType = 0
END CATCH
BEGIN TRY
	BEGIN
		IF CHARINDEX('请填写', @Keyword) > 0
			SET @Keyword = ''

		DECLARE @ReuseNumber AS INT, @dcProvinceId INT
		----给null值变量赋默认值
		IF NOT LEFT(@dcRegionID, 1) = 'p'
			SELECT @dcRegionID = RTRIM(dbo.FormatIDS(@dcRegionID))
		IF @EmployType NOT IN('1', '2', '3', '4')
			SET @EmployType = ''
		SELECT @dcJobTypeID = RTRIM(dbo.FormatIDS(@dcJobTypeID)),
			@dcIndustryID = RTRIM(dbo.FormatIDS(@dcIndustryID)),
			@dcSalaryID = ISNULL(@dcSalaryID, 0),
			@MinExperience = ISNULL(@MinExperience, 100),
			@dcEducationID = ISNULL(@dcEducationID, 0),
			@EmployType = CASE @EmployType WHEN '2' THEN '1,3' ELSE ISNULL(@EmployType, '') END,
			@CompanySizeID = ISNULL(@CompanySizeID, '0'),
			@KeyWord = LTRIM(RTRIM(dbo.SafeSQL(ISNULL(@KeyWord, '')))),
			@ORDER = ' ORDER BY a.RefreshDate DESC, a.SecondID DESC',
			@Type = ISNULL(@Type, 0),
			@PageNumber = ISNULL(@PageNumber, 0),
			@Welfare = RTRIM(dbo.FormatIDS(@Welfare)),
			@IsOnline = ISNULL(@IsOnline, 0),
			@ReuseNumber = 0

		IF LEN(@Welfare) > 1
		BEGIN
			DECLARE @wf VARCHAR(50)
			SET @wf = ''
			SELECT @wf = @wf + a + ',' FROM dbo.fnSplit(@Welfare, ',') WHERE a <= 19 AND LEN(a) < 3
			IF LEN(@wf) > 1
				SET @wf = LEFT(@wf, LEN(@wf) - 1)
			SET @Welfare = @wf
		END
		--@RefreshNo = 0选择全部数据，不限制时间
		IF ISNULL(@RefreshNo, 0) > 100
			SELECT @dcProvinceId = @RefreshNo - 100
		ELSE IF ISNULL(@RefreshNo, 0) > 9
			SELECT @dcProvinceId = @RefreshNo
		ELSE
			SELECT @dcProvinceId = 0

		IF RIGHT(@KeyWord, 2) = '公司'
			SET @KeyWord = LEFT(@KeyWord, LEN(@KeyWord) - 2)
		
		IF RIGHT(@dcJobTypeID, 1) = ','
			SET @dcJobTypeID = LEFT(@dcJobTypeID, LEN(@dcJobTypeID) - 1)
		IF RIGHT(@dcRegionID, 1) = ','
			SET @dcRegionID = LEFT(@dcRegionID, LEN(@dcRegionID) - 1)
		IF RIGHT(@dcIndustryID, 1) = ','
			SET @dcIndustryID = LEFT(@dcIndustryID, LEN(@dcIndustryID) - 1)

		DECLARE @paSearchConditionID AS INT, @MinId AS INT, @PageSize AS TINYINT, @TableID AS TINYINT

		SELECT @paSearchConditionID = 0, @PageSize = 30

		----搜索1分钟前的数据
		SELECT TOP 1 @paSearchConditionID = ID, @ReuseNumber = ReuseNumber
		FROM SearchDB..paSearchCondition WITH(NOLOCK)
		WHERE JobType = @dcJobTypeID AND IsOnline = @IsOnline AND JobPlace = @dcRegionID
		AND Industry = @dcIndustryID AND Education = @dcEducationID AND Experience = @MinExperience
		AND Salary = @dcSalaryID AND EmployType = @EmployType AND ISNULL(KeyWord, '') = @KeyWord
		AND CompanySizeID = @CompanySizeID AND Welfare = @Welfare AND IsOnline = @IsOnline
		AND LogTime > DATEADD(MINUTE, -1, GETDATE()) AND ReuseNumber > 0
		AND RefreshNo = @RefreshNo AND KeyType = @KeyType AND dcProvinceId = @dcProvinceId

		IF ISNULL(@paSearchConditionID, 0) = 0
		BEGIN
			SET @Type = 1
			GOTO SelectReset	--无数据，重新搜索
		END
		ELSE
		BEGIN
			SELECT @TableID = @paSearchConditionID % 4
			GOTO GetRecordSet	--从临时结果中提取数据
		END
	END

SelectReset:
	--从job中搜索数据
	--BEGIN TRAN
		DECLARE @WHERE AS VARCHAR(8000)
		DECLARE @FROM AS VARCHAR(1000)
		----记录查询条件
		INSERT INTO SearchDB..paSearchCondition(SessionID, LogTime, JobType, JobPlace, Industry, Education, Experience, 
			Salary, IsNegotiable, EmployType, CompanySizeID, KeyWord, KeyType, ReuseNumber, Welfare, IsOnline, RefreshNo, dcProvinceId)
		VALUES(@SessionId, GETDATE(), @dcJobTypeID, @dcRegionID, @dcIndustryID, @dcEducationID, @MinExperience, 
			@dcSalaryID, 0, @EmployType, @CompanySizeID, @KeyWord, @KeyType, 0, @Welfare, @IsOnline, @RefreshNo, @dcProvinceId)
		
		SET @paSearchConditionID = @@IDENTITY
		SELECT @TableID = @paSearchConditionID % 4

		------生成职位类别的表变量，因为职位类别有包含（父子）关系
		DECLARE @T_JobPlace AS TABLE(ID INT)
		DECLARE @T_JobType AS TABLE(ID INT)
		DECLARE @JobPlaceLen AS INT, @JobTypeLen AS INT
		IF CHARINDEX(',', @dcJobTypeID) > 0
			SET @JobTypeLen = -1
		ELSE
			SET @JobTypeLen = LEN(@dcJobTypeID)

		DECLARE @JobType AS VARCHAR(3000), @JobPlace AS VARCHAR(2000), @ValidJobNumber AS INT

		SELECT @JobPlace = '', @JobType=''
		----生成工作地点的表变量
		IF LEN(@dcRegionID) > 0
		BEGIN
			IF LEFT(@dcRegionID, 1) = 'p'
			BEGIN
				DECLARE @Degree AS DECIMAL(8,5),@LBLng AS DECIMAL(8,5),@LBLat AS DECIMAL(8,5),
				@RTLng AS DECIMAL(8,5),@RTLat AS DECIMAL(8,5),@Lat AS DECIMAL(8,5),@Lng AS DECIMAL(8,5)
				
				SELECT @Lat = Lat,@Lng = Lng FROM dcMapPlace WITH(NOLOCK) WHERE ID = RIGHT(@dcRegionID,LEN(@dcRegionID)-1)
				IF @dcRegionID LIKE '3201%'
					SET @Degree = 1000 / 100000.0
				ELSE
					SET @Degree = 2000 / 100000.0

				SET @LBLng = @Lng - @Degree
				SET @LBLat = @Lat - @Degree
				SET @RTLng = @Lng + @Degree
				SET @RTLat = @Lat + @Degree
				SET @JobPlace = 'a.Lng BETWEEN ' + CONVERT(VARCHAR,@LBLng) + ' AND ' + CONVERT(VARCHAR,@RTLng) + '
					AND a.Lat BETWEEN ' + CONVERT(VARCHAR,@LBLat) + ' AND ' + CONVERT(VARCHAR,@RTLat) + '
					AND (a.Lng-' + CONVERT(VARCHAR,@Lng) + ')*(a.Lng-' + CONVERT(VARCHAR,@Lng) + ')+
					(a.Lat-' + CONVERT(VARCHAR,@Lat) + ')*(a.Lat-' + CONVERT(VARCHAR,@Lat) + ')<' + CONVERT(VARCHAR,@Degree*@Degree)
				SELECT @JobPlaceLen = 8
			END
			ELSE IF LEN(@dcRegionID) > 1
			BEGIN
				INSERT INTO @T_JobPlace
				SELECT * FROM dbo.fnSplit(@dcRegionID, ',')
				WHERE LEN(a) IN(2, 4, 6)
				SELECT @JobPlace = (@JobPlace + ' OR a.dcRegionID Like ''' + LTRIM(STR(ID) + '%''')) FROM @T_JobPlace
				IF LEN(@JobPlace) > 0
					SET @JobPlace = RIGHT(@JobPlace, LEN(@JobPlace) -4)
				IF (SELECT COUNT(*) FROM @T_JobPlace) > 1
					SET @JobPlaceLen = -1
				ELSE
					SET @JobPlaceLen = LEN(@dcRegionID)
			END
		END
		ELSE 
			SELECT @JobPlaceLen = 0

		----生成求聘职位的表变量
		IF LEN(@dcJobTypeID) > 0
		BEGIN
			DECLARE @T_Temp AS TABLE(ID INT)		--临时表，用于构建组合查询语句
			INSERT INTO @T_Temp
			SELECT * FROM dbo.fnSplit(@dcJobTypeID, ',')
			WHERE LEN(a) IN(2, 4)

			INSERT INTO @T_JobType
			SELECT DISTINCT ID FROM dcJobType WITH(NOLOCK)
			WHERE ParentId IN(SELECT ID FROM @T_TEMP) 
			OR ParentId2 in(SELECT ID FROM @T_TEMP)
			OR ID IN(SELECT ID FROM @T_TEMP)
			----生成in字符串
			SELECT @JobType = (@JobType + LTRIM(STR(ID) + ',')) FROM @T_JobType
			IF RIGHT(@JobType, 1) = ','
				SET @JobType = LEFT(@JobType, LEN(@JobType) - 1)
		END

		----建立临时表
		CREATE TABLE #Job(
			RowID INT IDENTITY(1, 1), 
			ID INT NOT NULL, 
			cpMainId INT,
			dcJobTypeID SMALLINT NOT NULL, 
			dcJobTypeIDMinor SMALLINT NULL, 
			dcSalaryID TINYINT NOT NULL, 
			dcRegionID VARCHAR(6) NULL, 
			dcEducationID TINYINT NOT NULL, 
			MinExperience TINYINT NOT NULL, 
			RefreshDate SMALLDATETIME NULL,
			EmployType TINYINT NULL,
			dcCompanySizeID SMALLINT NULL
		)

		CREATE TABLE #FullText(
			Id INT IDENTITY(1, 1),
			Priority INT,
			JobId INT NOT NULL
		)

		------刷新时间，根据刷新时间编号计算
		----生成插入临时表的Sql语句
		SET @SQL='
			INSERT INTO #Job
			SELECT a.ID, a.cpMainId, a.dcJobTypeID, a.dcJobTypeIDMinor, a.dcSalaryID, 
				a.dcRegionID, a.dcEducationID, a.MinExperience, a.IssueDate,a.EmployType,b.dcCompanySizeID'
		SET @FROM = '
			FROM JobPublish a WITH(NOLOCK)
			INNER JOIN cpMainPublish b WITH(NOLOCK) ON a.cpMainID=b.ID'
		----职位有效，单位新有效
		IF LEN(@dcIndustryID) > 0
			SET @WHERE = '
			WHERE b.ID IN (SELECT cpMainID FROM cpIndustry WHERE dcIndustryId in(' + @dcIndustryID + '))
			AND a.Valid = 1
			AND b.Valid = 1'
		ELSE
			SET @WHERE = '
			WHERE a.Valid = 1
			AND b.Valid = 1'
		IF @dcProvinceId > 0
			SET @WHERE = @WHERE + ' AND b.dcProvinceId = ' + LTRIM(STR(@dcProvinceId))

		IF @KeyType IN(60, 70, 80, 90, 100)
			SET @WHERE = @WHERE + '
			AND b.ReplyRate >= ' + LEFT(@KeyType / 100.0, 3)

		IF @RefreshNo > 100
			SET @WHERE = @WHERE + '
			AND b.HasEnvironment = 1'

		----需要增加全文索引的关键字查询
		--SET @KeyWord = dbo.CutWord(@KeyWord)
		
		----职位类别
		IF LEN(@dcJobTypeID) > 0 AND @JobType > ''
		BEGIN
			SET @WHERE = @WHERE + '
			AND (a.dcJobTypeID IN(' + @JobType +')
				OR a.dcJobTypeIDMinor IN(' +@JobType + ')'
			IF LEN(@dcJobTypeID) IN(2, 4)
			BEGIN
				DECLARE @JobtypeName NVARCHAR(50)
				SELECT @JobtypeName = Description FROM dcJobType WITH(NOLOCK) WHERE Id = @dcJobTypeID
				IF CHARINDEX('/', @JobtypeName) = 0
					SET @WHERE = @WHERE + '				
				OR a.Name LIKE ''%' + @JobtypeName + '%'''
				ELSE
					SET @WHERE = @WHERE + '				
				OR a.Name LIKE ''%' + LEFT(@JobtypeName, CHARINDEX('/', @JobtypeName) - 1) + '%'''
			END
			SET @WHERE = @WHERE + ')'
		END
		IF LEN(@JobPlace) > 0 
			SET @WHERE = @WHERE + '
			AND (' + @JobPlace + ')'

		IF @dcSalaryID > 0
		BEGIN
			IF @dcSalaryID < 100				----从form中搜索，月薪跨2个级别, 是本级和上级别的薪金
				SET @WHERE = @WHERE + '
			AND a.dcSalaryID IN(' + LTRIM(STR(@dcSalaryID)) + ',' + LTRIM(STR(@dcSalaryID + 1)) + ')'
			ELSE IF @dcSalaryID = 100	----从筛选结果中点击面议，值是100
				SET @WHERE = @WHERE + '
			AND a.dcSalaryID = 100'
			ELSE IF @dcSalaryID BETWEEN 101 AND 106	----从筛选结果中点击搜索，月薪只有1个级别，传值时增加100
				SET @WHERE = @WHERE + '
			AND a.dcSalaryID <= ' + LTRIM(STR(@dcSalaryID-99)) + ' AND a.dcSalaryIDMax > ' + LTRIM(STR(@dcSalaryID-100))
			ELSE IF @dcSalaryID BETWEEN 107 AND 113	----从筛选结果中点击搜索，月薪只有1个级别，传值时增加100
				SET @WHERE = @WHERE + '
			AND a.dcSalaryID <= ' + LTRIM(STR(@dcSalaryID - 100)) + ' AND a.dcSalaryIDMax > ' + LTRIM(STR(@dcSalaryID-100))
			ELSE IF @dcSalaryID BETWEEN 114 AND 120
				SET @WHERE = @WHERE + '
			AND a.dcSalaryID  < 100 AND a.dcSalaryIDMax > ' + LTRIM(STR(@dcSalaryID - 100))
		END
		----工作经验要求
		IF @MinExperience < 100
		SET @WHERE = @WHERE + ' 
			AND a.MinExperience = ' + LTRIM(STR(@MinExperience))

		----学历要求
		----'1初中', '2\3\4高中、中技、中专', '5大专', '6本科', '7硕士', '8博士
		IF @dcEducationID > 0
			IF @dcEducationID = 2
				SET @WHERE = @WHERE + '
			AND a.dcEducationID IN(2, 3, 4)'
			ELSE
				SET @WHERE = @WHERE + '
			AND a.dcEducationID = ' + LTRIM(STR(@dcEducationID))
		----1、全职；3、兼职；4实习。	2、全职/兼职 职位中无此项
		IF LEN(@EmployType) > 0
			SET @WHERE = @WHERE + '
			AND a.EmployType IN (' + @EmployType + ')'

		IF @CompanySizeID BETWEEN 1 AND 6
			SET @WHERE = @WHERE + '
			AND b.dcCompanySizeID = ' + LTRIM(STR(@CompanySizeID))

		IF LEN(@Welfare) > 0
			SET @WHERE = @WHERE + '
			AND a.Welfare' + REPLACE(@Welfare, ',', ' = 1 AND a.Welfare') + ' = 1'
		
		IF @IsOnline = 1
			SET @WHERE = @WHERE + '
			AND a.caMainId IN(SELECT caMainId FROM caOnline WITH(NOLOCK) WHERE IsOnline = 1)'

		IF LEN(@KeyWord) > 1	----使用全文搜索job和cpmain2个表，经过测试发现union最快
		BEGIN
			IF EXISTS(SELECT TOP 1 'x' FROM cpMainPublish WITH(NOLOCK) WHERE Name = @KeyWord)
			BEGIN
				SET @WHERE = @WHERE + '
			AND b.Name = ''' + @KeyWord + ''''
				SET @SQL = @SQL + @FROM + @WHERE
			END
			ELSE
			BEGIN
				DECLARE @KeyWordTemp NVARCHAR(50)
				SET @KeyWordTemp = REPLACE(@KeyWord, ' ', '%')
				SET @KeyWordTemp = REPLACE(REPLACE(@KeyWordTemp, '(', ''), ')', '')
				IF LEN(@KeyWordTemp) > 1
				BEGIN
					IF @dcProvinceId > 0
					BEGIN
						IF @dcRegionId > '' AND @dcRegionId NOT LIKE '%,%'
							INSERT #FullText
							SELECT TOP 2000 1, b.ID
							FROM cpMainPublish a WITH(NOLOCK),
								JobPublish b WITH(NOLOCK)
							WHERE a.Id = b.cpMainId
							AND CHARINDEX(@KeyWord, b.Name) > 0
							AND a.dcProvinceId = @dcprovinceId
							AND b.dcRegionID LIKE @dcRegionId + '%'
							ORDER BY b.RefreshDate DESC
						ELSE
							INSERT #FullText
							SELECT TOP 2000 1, b.ID
							FROM cpMainPublish a WITH(NOLOCK),
								JobPublish b WITH(NOLOCK)
							WHERE a.Id = b.cpMainId
							AND CHARINDEX(@KeyWord, b.Name) > 0
							AND a.dcProvinceId = @dcprovinceId
							ORDER BY b.RefreshDate DESC

						INSERT #FullText
						SELECT TOP 2000 2, b.ID
						FROM cpMainPublish a WITH(NOLOCK),
							JobPublish b WITH(NOLOCK)
						WHERE a.Id = b.cpMainId
						AND CHARINDEX(@KeyWord, a.Name) > 0
						AND a.dcProvinceId = @dcprovinceId
						ORDER BY b.RefreshDate DESC
					END
					ELSE
					BEGIN
						INSERT #FullText
						SELECT TOP 2000 2, b.ID
						FROM cpMainPublish a WITH(NOLOCK),
							JobPublish b WITH(NOLOCK)
						WHERE a.Id = b.cpMainId
						AND CHARINDEX(@KeyWord, a.Name) > 0
						ORDER BY b.RefreshDate DESC

						INSERT #FullText
						SELECT TOP 2000 1, b.ID
						FROM cpMainPublish a WITH(NOLOCK),
							JobPublish b WITH(NOLOCK)
						WHERE a.Id = b.cpMainId
						AND CHARINDEX(@KeyWord, b.Name) > 0
						ORDER BY b.RefreshDate DESC
					END
				END
				IF (SELECT COUNT(*) FROM #FullText) < 2000
				BEGIN
					INSERT #FullText
					SELECT TOP 5000 3 + RANK, [Key]
					FROM FREETEXTTABLE(cpMainJob, JobName, @KeyWordTemp, 100000) AS KeyJob ORDER BY RANK DESC
				END
				IF (SELECT COUNT(*) FROM #FullText) < 2000
				BEGIN
					INSERT #FullText
					SELECT TOP 5000 3000 + RANK, [Key]
					FROM FREETEXTTABLE(cpMainJob, *, @KeyWordTemp, 100000) AS KeyJob ORDER BY RANK DESC
				END
				DELETE a FROM #FullText a, #FullText b WHERE a.JobId = b.JobId AND a.Priority > b.Priority
				DELETE a FROM #FullText a, #FullText b WHERE a.JobId = b.JobId AND a.Id > b.Id
				--------------------
				SELECT @FROM = @FROM + '
			INNER JOIN #FullText ON a.ID = #FullText.JobId',
					@ORDER = ' ORDER BY #FullText.Priority, a.RefreshDate DESC, a.SecondId DESC'
				SET @SQL = @SQL + @FROM + @WHERE
			END
		END
		ELSE
			SET @SQL = @SQL + @FROM + @WHERE
		
		SET @SQL = @SQL + @ORDER	--' ORDER BY a.RefreshDate DESC, a.ID'
		--原来是ORDER BY a.IssueDate DESC, a.ID，Richard 2011年11月23日17：06分修改

		----把符合条件的职位全部列出
		--PRINT @SQL
		EXEC(@SQL)
		SET @ValidJobNumber = @@ROWCOUNT
		----记录查询结果总数
		UPDATE SearchDB..paSearchCondition SET ValidJobNumber=@ValidJobNumber, SQl = @SQL 
		WHERE ID=@paSearchConditionID

		IF LEN(@dcJobTypeID) > 0	--IN(2, 4)
			UPDATE #Job SET dcJobTypeId = dcJobTypeIDMinor
			WHERE dcJobTypeID NOT IN(SELECT a FROM dbo.fnSplit(@JobType, ','))
			AND dcJobTypeIDMinor> 0
		----插入JobType数据
		DECLARE @TitleValue AS INT, @TopRows AS INT, @AllRows AS INT
		DECLARE @sc AS TABLE (
			paSearchConditionID int,
			Title varchar(20),
			TitleID varchar(10),
			TitleValue int
		)
		DECLARE @sc2 AS TABLE (
			paSearchConditionID int,
			Title varchar(20),
			TitleID varchar(10),
			TitleValue int
		)

		IF (@TableID = 0)
		BEGIN
			----------------------------jobtype
			INSERT INTO @sc2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'JobType', dcJobTypeID, COUNT(*)
			FROM #Job WITH(NOLOCK)
			GROUP BY dcJobTypeID ORDER BY dcJobTypeID			

			----计算全部某职位类别，2, 4位的数据
			IF @JobTypeLen NOT IN(2, 4)
			BEGIN
				INSERT INTO @Sc(paSearchConditionID, Title, TitleId, TitleValue)
				SELECT  @paSearchConditionID, 'JobType', LEFT(TitleID, 2) TitleID, SUM(TitleValue) TitleValue 
				FROM @sc2 GROUP BY LEFT(TitleID, 2)
			END
			IF @JobTypeLen NOT IN(0, 4)
			BEGIN
				INSERT INTO @Sc(paSearchConditionID, Title, TitleId, TitleValue)
				SELECT  @paSearchConditionID, 'JobType', TitleId, TitleValue
				FROM @sc2 WHERE LEN(TitleId) = 4
			END

			IF @JobTypeLen = -1
				DELETE @sc WHERE TitleID NOT IN(SELECT a FROM dbo.fnSplit(@dcJobTypeID, ','))

			INSERT INTO SearchDB..paSearchCount_0(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT  @paSearchConditionID, 'JobType', TitleId, TitleValue FROM @sc
			DELETE @sc
			DELETE @sc2
			--------------------------region
			INSERT INTO @sc2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Region', dcRegionID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcRegionID ORDER BY dcRegionID
			----计算全部地区，2位的数据
			IF @JobPlaceLen IN(-1, 0)
				INSERT INTO @sc(paSearchConditionID, Title, TitleId, TitleValue)
				SELECT @paSearchConditionID, 'Region', LEFT(TitleID, 2) TitleID, SUM(TitleValue) TitleValue 
				FROM @sc2 GROUP BY LEFT(TitleID, 2)
			IF @JobPlaceLen IN(-1, 2)
				INSERT INTO @sc(paSearchConditionID, Title, TitleId, TitleValue)
				SELECT @paSearchConditionID, 'Region', LEFT(TitleID, 4) TitleID, SUM(TitleValue) TitleValue 
				FROM @sc2 WHERE LEN(TitleID) >= 4 GROUP BY LEFT(TitleID, 4)
			IF @JobPlaceLen IN(-1, 4)
				INSERT INTO @sc(paSearchConditionID, Title, TitleId, TitleValue)
				SELECT @paSearchConditionID, 'Region', TitleID, TitleValue 
				FROM @sc2 WHERE LEN(TitleID) = 6
			IF @JobPlaceLen = -1
				DELETE @sc WHERE TitleID NOT IN(SELECT ID FROM @T_JobPlace)
			ELSE
				DELETE @sc WHERE LEN(TitleID) <> @JobPlaceLen + 2

			INSERT INTO SearchDB..paSearchCount_0(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT paSearchConditionID, Title, TitleId, TitleValue FROM @sc
			----------------------------
			INSERT INTO SearchDB..paSearchCount_0(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'EmployType', EmployType, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY EmployType ORDER BY EmployType

			INSERT INTO SearchDB..paSearchCount_0(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Education', CASE WHEN dcEducationId IN(2, 3, 4) THEN 2 ELSE dcEducationId END, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY CASE WHEN dcEducationId IN(2, 3, 4) THEN 2 ELSE dcEducationId END
			ORDER BY CASE WHEN dcEducationId IN(2, 3, 4) THEN 2 ELSE dcEducationId END

			INSERT INTO SearchDB..paSearchCount_0(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Experience', MinExperience, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY MinExperience ORDER BY MinExperience

			INSERT INTO SearchDB..paSearchCount_0(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'CompanySize', dcCompanySizeID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcCompanySizeID ORDER BY dcCompanySizeID

			INSERT INTO SearchDB..paSearchCount_0(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Salary', dcSalaryID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcSalaryID ORDER BY dcSalaryID

			INSERT INTO SearchDB..paSearchCount_0(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Industry', dcIndustryID, COUNT(*) 
			FROM #Job a WITH(NOLOCK), cpIndustry b WITH(NOLOCK)
			WHERE a.cpMainId = b.cpMainId
			GROUP BY b.dcIndustryId ORDER BY b.dcIndustryId

			IF EXISTS(SELECT TOP 1 'x' FROM #FullText)
				INSERT INTO SearchDB..paSearchJobID_0(paSearchConditionID, JobId, IsTop)
				SELECT TOP 10 @paSearchConditionID, a.JobId, 1 
				FROM SearchJobTop a WITH(NOLOCK), (SELECT ID FROM #Job WITH(NOLOCK) WHERE RowId < 2001) b 
				WHERE b.ID = a.JobId
				AND CHARINDEX(@KeyWord, a.JobName) > 0
				ORDER BY a.OrderType, a.OpenDate DESC
			ELSE
				INSERT INTO SearchDB..paSearchJobID_0(paSearchConditionID, JobId, IsTop)
				SELECT TOP 10 @paSearchConditionID, a.JobId, 1 
				FROM SearchJobTop a WITH(NOLOCK), (SELECT ID FROM #Job WITH(NOLOCK) WHERE RowId < 2001) b 
				WHERE b.ID = a.JobId
				ORDER BY a.OrderType, a.OpenDate DESC

			SET @TopRows = @@ROWCOUNT

			INSERT INTO SearchDB..paSearchJobID_0(paSearchConditionID, JobId, IsTop)
			SELECT TOP 2000 @paSearchConditionID, ID, 0 FROM #Job WITH(NOLOCK) ORDER BY RowId
			SET @AllRows = @@ROWCOUNT

			IF @TopRows = 0 AND @AllRows > 100
				UPDATE SearchDB..paSearchJobID_0 SET IsTop = 1 
				WHERE paSearchConditionID = @paSearchConditionID
				AND ID IN (SELECT TOP 3 ID FROM SearchDB..paSearchJobID_0 WITH(NOLOCK) WHERE paSearchConditionID = @paSearchConditionID ORDER BY ID)
		END
		ELSE IF (@TableId = 1)
		BEGIN
			----------------------------jobtype
			INSERT INTO @sc2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'JobType', dcJobTypeID, COUNT(*)
			FROM #Job WITH(NOLOCK)
			GROUP BY dcJobTypeID ORDER BY dcJobTypeID			

			----计算全部某职位类别，2, 4位的数据
			IF @JobTypeLen NOT IN(2, 4)
			BEGIN
				INSERT INTO @Sc(paSearchConditionID, Title, TitleId, TitleValue)
				SELECT  @paSearchConditionID, 'JobType', LEFT(TitleID, 2) TitleID, SUM(TitleValue) TitleValue 
				FROM @sc2 GROUP BY LEFT(TitleID, 2)
			END
			IF @JobTypeLen NOT IN(0, 4)
			BEGIN
				INSERT INTO @Sc(paSearchConditionID, Title, TitleId, TitleValue)
				SELECT  @paSearchConditionID, 'JobType', TitleId, TitleValue
				FROM @sc2 WHERE LEN(TitleId) = 4
			END

			IF @JobTypeLen = -1
				DELETE @sc WHERE TitleID NOT IN(SELECT a FROM dbo.fnSplit(@dcJobTypeID, ','))

			INSERT INTO SearchDB..paSearchCount_1(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT  @paSearchConditionID, 'JobType', TitleId, TitleValue FROM @sc
			DELETE @sc
			DELETE @sc2
			--------------------------region
			INSERT INTO @sc2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Region', dcRegionID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcRegionID ORDER BY dcRegionID
			----计算全部地区，2位的数据
			IF @JobPlaceLen IN(-1, 0)
				INSERT INTO @sc(paSearchConditionID, Title, TitleId, TitleValue)
				SELECT @paSearchConditionID, 'Region', LEFT(TitleID, 2) TitleID, SUM(TitleValue) TitleValue 
				FROM @sc2 GROUP BY LEFT(TitleID, 2)
			IF @JobPlaceLen IN(-1, 2)
				INSERT INTO @sc(paSearchConditionID, Title, TitleId, TitleValue)
				SELECT @paSearchConditionID, 'Region', LEFT(TitleID, 4) TitleID, SUM(TitleValue) TitleValue 
				FROM @sc2 WHERE LEN(TitleID) >= 4 GROUP BY LEFT(TitleID, 4)
			IF @JobPlaceLen IN(-1, 4)
				INSERT INTO @sc(paSearchConditionID, Title, TitleId, TitleValue)
				SELECT @paSearchConditionID, 'Region', TitleID, TitleValue 
				FROM @sc2 WHERE LEN(TitleID) = 6
			IF @JobPlaceLen = -1
				DELETE @sc WHERE TitleID NOT IN(SELECT ID FROM @T_JobPlace)
			ELSE
				DELETE @sc WHERE LEN(TitleID) <> @JobPlaceLen + 2

			INSERT INTO SearchDB..paSearchCount_1(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT paSearchConditionID, Title, TitleId, TitleValue FROM @sc
			----------------------------
			INSERT INTO SearchDB..paSearchCount_1(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Salary', dcSalaryID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcSalaryID ORDER BY dcSalaryID

			INSERT INTO SearchDB..paSearchCount_1(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Education', CASE WHEN dcEducationId IN(2, 3, 4) THEN 2 ELSE dcEducationId END, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY CASE WHEN dcEducationId IN(2, 3, 4) THEN 2 ELSE dcEducationId END
			ORDER BY CASE WHEN dcEducationId IN(2, 3, 4) THEN 2 ELSE dcEducationId END

			INSERT INTO SearchDB..paSearchCount_1(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Experience', MinExperience, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY MinExperience ORDER BY MinExperience

			INSERT INTO SearchDB..paSearchCount_1(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'EmployType', EmployType, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY EmployType ORDER BY EmployType

			INSERT INTO SearchDB..paSearchCount_1(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'CompanySize', dcCompanySizeID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcCompanySizeID ORDER BY dcCompanySizeID

			INSERT INTO SearchDB..paSearchCount_1(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Industry', dcIndustryID, COUNT(*) 
			FROM #Job a WITH(NOLOCK), cpIndustry b WITH(NOLOCK)
			WHERE a.cpMainId = b.cpMainId
			GROUP BY dcIndustryID ORDER BY dcIndustryID

			IF EXISTS(SELECT TOP 1 'x' FROM #FullText)
				INSERT INTO SearchDB..paSearchJobID_1(paSearchConditionID, JobId, IsTop)
				SELECT TOP 10 @paSearchConditionID, a.JobId, 1 
				FROM SearchJobTop a WITH(NOLOCK), (SELECT ID FROM #Job WITH(NOLOCK) WHERE RowId < 2001) b 
				WHERE b.ID = a.JobId
				AND CHARINDEX(@KeyWord, a.JobName) > 0
				ORDER BY a.OrderType, a.OpenDate DESC
			ELSE
				INSERT INTO SearchDB..paSearchJobID_1(paSearchConditionID, JobId, IsTop)
				SELECT TOP 10 @paSearchConditionID, a.JobId, 1 
				FROM SearchJobTop a WITH(NOLOCK), (SELECT ID FROM #Job WITH(NOLOCK) WHERE RowId < 2001) b 
				WHERE b.ID = a.JobId
				ORDER BY a.OrderType, a.OpenDate DESC

			SET @TopRows = @@ROWCOUNT
 
			INSERT INTO SearchDB..paSearchJobID_1(paSearchConditionID, JobId, IsTop)
			SELECT TOP 2000 @paSearchConditionID, ID, 0 FROM #Job WITH(NOLOCK) ORDER BY RowId
			SET @AllRows = @@ROWCOUNT

			IF @TopRows = 0 AND @AllRows > 100
				UPDATE SearchDB..paSearchJobID_1 SET IsTop = 1 
				WHERE paSearchConditionID = @paSearchConditionID
				AND ID IN (SELECT TOP 3 ID FROM SearchDB..paSearchJobID_1 WITH(NOLOCK) WHERE paSearchConditionID = @paSearchConditionID ORDER BY ID)
		END
		ELSE IF (@TableId = 2)
		BEGIN
			----------------------------jobtype
			INSERT INTO @sc2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'JobType', dcJobTypeID, COUNT(*)
			FROM #Job WITH(NOLOCK)
			GROUP BY dcJobTypeID ORDER BY dcJobTypeID			

			----计算全部某职位类别，2, 4位的数据
			IF @JobTypeLen NOT IN(2, 4)
			BEGIN
				INSERT INTO @Sc(paSearchConditionID, Title, TitleId, TitleValue)
				SELECT  @paSearchConditionID, 'JobType', LEFT(TitleID, 2) TitleID, SUM(TitleValue) TitleValue 
				FROM @sc2 GROUP BY LEFT(TitleID, 2)
			END
			IF @JobTypeLen NOT IN(0, 4)
			BEGIN
				INSERT INTO @Sc(paSearchConditionID, Title, TitleId, TitleValue)
				SELECT  @paSearchConditionID, 'JobType', TitleId, TitleValue
				FROM @sc2 WHERE LEN(TitleId) = 4
			END

			IF @JobTypeLen = -1
				DELETE @sc WHERE TitleID NOT IN(SELECT a FROM dbo.fnSplit(@dcJobTypeID, ','))

			INSERT INTO SearchDB..paSearchCount_2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT  @paSearchConditionID, 'JobType', TitleId, TitleValue FROM @sc
			DELETE @sc
			DELETE @sc2
			--------------------------region
			INSERT INTO @sc2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Region', dcRegionID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcRegionID ORDER BY dcRegionID
			----计算全部地区，2位的数据
			IF @JobPlaceLen IN(-1, 0)
				INSERT INTO @sc(paSearchConditionID, Title, TitleId, TitleValue)
				SELECT @paSearchConditionID, 'Region', LEFT(TitleID, 2) TitleID, SUM(TitleValue) TitleValue 
				FROM @sc2 GROUP BY LEFT(TitleID, 2)
			IF @JobPlaceLen IN(-1, 2)
				INSERT INTO @sc(paSearchConditionID, Title, TitleId, TitleValue)
				SELECT @paSearchConditionID, 'Region', LEFT(TitleID, 4) TitleID, SUM(TitleValue) TitleValue 
				FROM @sc2 WHERE LEN(TitleID) >= 4 GROUP BY LEFT(TitleID, 4)
			IF @JobPlaceLen IN(-1, 4)
				INSERT INTO @sc(paSearchConditionID, Title, TitleId, TitleValue)
				SELECT @paSearchConditionID, 'Region', TitleID, TitleValue 
				FROM @sc2 WHERE LEN(TitleID) = 6
			IF @JobPlaceLen = -1
				DELETE @sc WHERE TitleID NOT IN(SELECT ID FROM @T_JobPlace)
			ELSE
				DELETE @sc WHERE LEN(TitleID) <> @JobPlaceLen + 2

			INSERT INTO SearchDB..paSearchCount_2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT paSearchConditionID, Title, TitleId, TitleValue FROM @sc
			----------------------------
			INSERT INTO SearchDB..paSearchCount_2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Salary', dcSalaryID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcSalaryID ORDER BY dcSalaryID

			INSERT INTO SearchDB..paSearchCount_2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Education', CASE WHEN dcEducationId IN(2, 3, 4) THEN 2 ELSE dcEducationId END, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY CASE WHEN dcEducationId IN(2, 3, 4) THEN 2 ELSE dcEducationId END
			ORDER BY CASE WHEN dcEducationId IN(2, 3, 4) THEN 2 ELSE dcEducationId END

			INSERT INTO SearchDB..paSearchCount_2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Experience', MinExperience, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY MinExperience ORDER BY MinExperience

			INSERT INTO SearchDB..paSearchCount_2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'EmployType', EmployType, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY EmployType ORDER BY EmployType

			INSERT INTO SearchDB..paSearchCount_2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'CompanySize', dcCompanySizeID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcCompanySizeID ORDER BY dcCompanySizeID

			INSERT INTO SearchDB..paSearchCount_2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Industry', dcIndustryID, COUNT(*) 
			FROM #Job a WITH(NOLOCK), cpIndustry b WITH(NOLOCK)
			WHERE a.cpMainId = b.cpMainId
			GROUP BY dcIndustryID ORDER BY dcIndustryID

			IF EXISTS(SELECT TOP 1 'x' FROM #FullText)
				INSERT INTO SearchDB..paSearchJobID_2(paSearchConditionID, JobId, IsTop)
				SELECT TOP 10 @paSearchConditionID, a.JobId, 1 
				FROM SearchJobTop a WITH(NOLOCK), (SELECT ID FROM #Job WITH(NOLOCK) WHERE RowId < 2001) b 
				WHERE b.ID = a.JobId
				AND CHARINDEX(@KeyWord, a.JobName) > 0
				ORDER BY a.OrderType, a.OpenDate DESC
			ELSE
				INSERT INTO SearchDB..paSearchJobID_2(paSearchConditionID, JobId, IsTop)
				SELECT TOP 10 @paSearchConditionID, a.JobId, 1 
				FROM SearchJobTop a WITH(NOLOCK), (SELECT ID FROM #Job WITH(NOLOCK) WHERE RowId < 2001) b 
				WHERE b.ID = a.JobId
				ORDER BY a.OrderType, a.OpenDate DESC

			SET @TopRows = @@ROWCOUNT

			INSERT INTO SearchDB..paSearchJobID_2(paSearchConditionID, JobId, IsTop)
			SELECT TOP 2000 @paSearchConditionID, ID, 0 FROM #Job WITH(NOLOCK) ORDER BY RowId
			SET @AllRows = @@ROWCOUNT

			IF @TopRows = 0 AND @AllRows > 100
				UPDATE SearchDB..paSearchJobID_2 SET IsTop = 1 
				WHERE paSearchConditionID = @paSearchConditionID
				AND ID IN (SELECT TOP 3 ID FROM SearchDB..paSearchJobID_2 WITH(NOLOCK) WHERE paSearchConditionID = @paSearchConditionID ORDER BY ID)
		END
		ELSE IF (@TableId = 3)
		BEGIN
			----------------------------jobtype
			INSERT INTO @sc2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'JobType', dcJobTypeID, COUNT(*)
			FROM #Job WITH(NOLOCK)
			GROUP BY dcJobTypeID ORDER BY dcJobTypeID			

			----计算全部某职位类别，2, 4位的数据
			IF @JobTypeLen NOT IN(2, 4)
			BEGIN
				INSERT INTO @Sc(paSearchConditionID, Title, TitleId, TitleValue)
				SELECT  @paSearchConditionID, 'JobType', LEFT(TitleID, 2) TitleID, SUM(TitleValue) TitleValue 
				FROM @sc2 GROUP BY LEFT(TitleID, 2)
			END
			IF @JobTypeLen NOT IN(0, 4)
			BEGIN
				INSERT INTO @Sc(paSearchConditionID, Title, TitleId, TitleValue)
				SELECT  @paSearchConditionID, 'JobType', TitleId, TitleValue
				FROM @sc2 WHERE LEN(TitleId) = 4
			END

			IF @JobTypeLen = -1
				DELETE @sc WHERE TitleID NOT IN(SELECT a FROM dbo.fnSplit(@dcJobTypeID, ','))

			INSERT INTO SearchDB..paSearchCount_3(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT  @paSearchConditionID, 'JobType', TitleId, TitleValue FROM @sc
			DELETE @sc
			DELETE @sc2
			--------------------------region
			INSERT INTO @sc2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Region', dcRegionID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcRegionID ORDER BY dcRegionID
			----计算全部地区，2位的数据
			IF @JobPlaceLen IN(-1, 0)
				INSERT INTO @sc(paSearchConditionID, Title, TitleId, TitleValue)
				SELECT @paSearchConditionID, 'Region', LEFT(TitleID, 2) TitleID, SUM(TitleValue) TitleValue 
				FROM @sc2 GROUP BY LEFT(TitleID, 2)
			IF @JobPlaceLen IN(-1, 2)
				INSERT INTO @sc(paSearchConditionID, Title, TitleId, TitleValue)
				SELECT @paSearchConditionID, 'Region', LEFT(TitleID, 4) TitleID, SUM(TitleValue) TitleValue 
				FROM @sc2 WHERE LEN(TitleID) >= 4 GROUP BY LEFT(TitleID, 4)
			IF @JobPlaceLen IN(-1, 4)
				INSERT INTO @sc(paSearchConditionID, Title, TitleId, TitleValue)
				SELECT @paSearchConditionID, 'Region', TitleID, TitleValue 
				FROM @sc2 WHERE LEN(TitleID) = 6
			IF @JobPlaceLen = -1
				DELETE @sc WHERE TitleID NOT IN(SELECT ID FROM @T_JobPlace)
			ELSE
				DELETE @sc WHERE LEN(TitleID) <> @JobPlaceLen + 2

			INSERT INTO SearchDB..paSearchCount_3(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT paSearchConditionID, Title, TitleId, TitleValue FROM @sc
			----------------------------
			INSERT INTO SearchDB..paSearchCount_3(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Salary', dcSalaryID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcSalaryID ORDER BY dcSalaryID

			INSERT INTO SearchDB..paSearchCount_3(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Education', CASE WHEN dcEducationId IN(2, 3, 4) THEN 2 ELSE dcEducationId END, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY CASE WHEN dcEducationId IN(2, 3, 4) THEN 2 ELSE dcEducationId END
			ORDER BY CASE WHEN dcEducationId IN(2, 3, 4) THEN 2 ELSE dcEducationId END
			
			INSERT INTO SearchDB..paSearchCount_3(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Experience', MinExperience, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY MinExperience ORDER BY MinExperience

			INSERT INTO SearchDB..paSearchCount_3(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'EmployType', EmployType, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY EmployType ORDER BY EmployType

			INSERT INTO SearchDB..paSearchCount_3(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'CompanySize', dcCompanySizeID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcCompanySizeID ORDER BY dcCompanySizeID

			INSERT INTO SearchDB..paSearchCount_3(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Industry', dcIndustryID, COUNT(*) 
			FROM #Job a WITH(NOLOCK), cpIndustry b WITH(NOLOCK)
			WHERE a.cpMainId = b.cpMainId
			GROUP BY dcIndustryID ORDER BY dcIndustryID

			IF EXISTS(SELECT TOP 1 'x' FROM #FullText)
				INSERT INTO SearchDB..paSearchJobID_3(paSearchConditionID, JobId, IsTop)
				SELECT TOP 10 @paSearchConditionID, a.JobId, 1 
				FROM SearchJobTop a WITH(NOLOCK), (SELECT ID FROM #Job WITH(NOLOCK) WHERE RowId < 2001) b 
				WHERE b.ID = a.JobId
				AND CHARINDEX(@KeyWord, a.JobName) > 0
				ORDER BY a.OrderType, a.OpenDate DESC
			ELSE
				INSERT INTO SearchDB..paSearchJobID_3(paSearchConditionID, JobId, IsTop)
				SELECT TOP 10 @paSearchConditionID, a.JobId, 1 
				FROM SearchJobTop a WITH(NOLOCK), (SELECT ID FROM #Job WITH(NOLOCK) WHERE RowId < 2001) b 
				WHERE b.ID = a.JobId
				ORDER BY a.OrderType, a.OpenDate DESC

			SET @TopRows = @@ROWCOUNT

			INSERT INTO SearchDB..paSearchJobID_3(paSearchConditionID, JobId, IsTop)
			SELECT TOP 2000 @paSearchConditionID, ID, 0 FROM #Job WITH(NOLOCK) ORDER BY RowId
			SET @AllRows = @@ROWCOUNT

			IF @TopRows = 0 AND @AllRows > 100
				UPDATE SearchDB..paSearchJobID_3 SET IsTop = 1 
				WHERE paSearchConditionID = @paSearchConditionID
				AND ID IN (SELECT TOP 3 ID FROM SearchDB..paSearchJobID_3 WITH(NOLOCK) WHERE paSearchConditionID = @paSearchConditionID ORDER BY ID)
		END
		DROP TABLE #Job
		DROP TABLE #FullText
		--PRINT 'DROP #JOB  ' + CONVERT(VARCHAR(30), GETDATE(), 121)
	--COMMIT
	--GOTO GetRecordSet

	GetRecordSet:
	BEGIN
		----返回查询数量
		SELECT ValidJobNumber FROM SearchDB..paSearchCondition WITH(NOLOCK) WHERE ID=@paSearchConditionID
		UPDATE SearchDB..paSearchCondition SET ReuseNumber = ReuseNumber + 1 WHERE ID=@paSearchConditionID
		----返回20行查询结果
		IF (@TableID = 0)
		BEGIN
			SELECT @MinId = MIN(ID) FROM SearchDB..paSearchJobID_0 WITH(NOLOCK) WHERE paSearchConditionID=@paSearchConditionID

			SET @MinId = @MinId+(@PageNumber-1)*@PageSize
			SELECT TOP 30 a.ID, a.cpMainID, a.caMainID, a.Name as JobName, a.dcJobTypeID, 
				a.dcJobTypeIDMinor, a.NeedNumber, a.dcSalaryID, a.dcSalaryIDMax, a.EmployType, 
				a.dcRegionID, a.Responsibility, a.Demand, a.dcEducationID, 
				a.MinExperience, a.MinAge, a.MaxAge, a.IssueDate, a.IssueEND, 
				a.IsDelete, a.AddDate, a.RefreshDate,  a.Welfare1, a.Welfare2, a.Welfare3,
				a.Welfare4, a.Welfare5, a.Welfare6, a.Welfare7, a.Welfare8,
				a.Welfare9, a.Welfare10, a.Welfare11, a.Welfare12, a.Welfare13,
				a.Welfare14, a.Welfare15, a.Welfare16, a.Welfare17, a.Welfare18,
				a.Welfare19, a.SecondId EnJobID, b.SecondId EnCpMainID,
				a.LastModifyDate, b.Name as cpName, b.dcCompanySizeID, 
				b.HasLicence, b.RealName, b.UnLimitedDate, b.BalanceDate, b.Balance, 
				b.MemberType, '' cpIndustry, --STUFF((SELECT ','+LTRIM(x.dcIndustryid)+',c'+LTRIM(isnull(y.Category,0)) FROM cpIndustry x,dcIndustry y WHERE x.dcIndustryid = y.id AND x.cpMainid = b.id FOR XML PATH('')),1,1,'') cpIndustry,
				c.IsTop, b.IsRefreshed, ISNULL(d.IsOnline, 0) IsOnline, d.IsVi, d.ViPlanId, d.InterviewDate, CASE WHEN b.ReplyRate >= 0.6 THEN b.ReplyRate ELSE NULL END Replyrate,
				(SELECT TOP 1 ID from paAttention WITH(NOLOCK) WHERE AttentionType=2 AND AttentionID=a.ID AND paMainId = @paMainId) AttentionId
			FROM JobPublish a WITH(NOLOCK)
			INNER JOIN cpMainPublish b WITH(NOLOCK) ON a.cpMainID = b.ID 
			INNER JOIN SearchDB..paSearchJobID_0 c WITH(NOLOCK) ON a.id = c.JobID
			LEFT JOIN caOnline d WITH(NOLOCK) ON a.caMainId = d.caMainId
			WHERE paSearchConditionID=@paSearchConditionID 
			AND c.ID >= @MinId
			ORDER BY c.ID, a.ID DESC
		END
		ELSE IF (@TableID = 1)
		BEGIN
			SELECT @MinId = MIN(ID) FROM SearchDB..paSearchJobID_1 WITH(NOLOCK) WHERE paSearchConditionID=@paSearchConditionID

			SET @MinId = @MinId+(@PageNumber-1)*@PageSize
			SELECT TOP 30 a.ID, a.cpMainID, a.caMainID, a.Name as JobName, a.dcJobTypeID, 
				a.dcJobTypeIDMinor, a.NeedNumber, a.dcSalaryID, a.dcSalaryIDMax, a.EmployType, 
				a.dcRegionID, a.Responsibility, a.Demand, a.dcEducationID, 
				a.MinExperience, a.MinAge, a.MaxAge, a.IssueDate, a.IssueEND, 
				a.IsDelete, a.AddDate, a.RefreshDate, a.Welfare1, a.Welfare2, a.Welfare3,
				a.Welfare4, a.Welfare5, a.Welfare6, a.Welfare7, a.Welfare8,
				a.Welfare9, a.Welfare10, a.Welfare11, a.Welfare12, a.Welfare13,
				a.Welfare14, a.Welfare15, a.Welfare16, a.Welfare17, a.Welfare18, a.Welfare19, 
				a.SecondId EnJobID, b.SecondId EnCpMainID,
				a.LastModifyDate, b.Name cpName, b.dcCompanySizeID, 
				b.HasLicence, b.RealName, b.UnLimitedDate, b.BalanceDate, b.Balance, 
				b.MemberType, '' cpIndustry, --STUFF((SELECT ','+LTRIM(x.dcIndustryid)+',c'+LTRIM(isnull(y.Category,0)) FROM cpIndustry x,dcIndustry y WHERE x.dcIndustryid = y.id AND x.cpMainid = b.id FOR XML PATH('')),1,1,'') cpIndustry,
				c.IsTop, b.IsRefreshed, ISNULL(d.IsOnline, 0) IsOnline, d.IsVi, d.ViPlanId, d.InterviewDate, CASE WHEN b.ReplyRate >= 0.6 THEN b.ReplyRate ELSE NULL END Replyrate,
				(SELECT TOP 1 ID from paAttention WITH(NOLOCK) WHERE AttentionType=2 AND AttentionID=a.ID AND paMainId = @paMainId) AttentionId
			FROM JobPublish a WITH(NOLOCK)
			INNER JOIN cpMainPublish b WITH(NOLOCK) ON a.cpMainID = b.ID 
			INNER JOIN SearchDB..paSearchJobID_1 c WITH(NOLOCK) ON a.id = c.JobID
			LEFT JOIN caOnline d WITH(NOLOCK) ON a.caMainId = d.caMainId
			WHERE paSearchConditionID=@paSearchConditionID 
			AND c.ID >= @MinId
			ORDER BY c.ID, a.ID DESC
		END
		ELSE IF (@TableID = 2)
		BEGIN
			SELECT @MinId = MIN(ID) FROM SearchDB..paSearchJobID_2 WITH(NOLOCK) WHERE paSearchConditionID=@paSearchConditionID

			SET @MinId = @MinId+(@PageNumber-1)*@PageSize
			SELECT TOP 30 a.ID, a.cpMainID, a.caMainID, a.Name as JobName, a.dcJobTypeID, 
				a.dcJobTypeIDMinor, a.NeedNumber, a.dcSalaryID, a.dcSalaryIDMax, a.EmployType, 
				a.dcRegionID, a.Responsibility, a.Demand, a.dcEducationID, 
				a.MinExperience, a.MinAge, a.MaxAge, a.IssueDate, a.IssueEND, 
				a.IsDelete, a.AddDate, a.RefreshDate, a.Welfare1, a.Welfare2, a.Welfare3,
				a.Welfare4, a.Welfare5, a.Welfare6, a.Welfare7, a.Welfare8,
				a.Welfare9, a.Welfare10, a.Welfare11, a.Welfare12, a.Welfare13,
				a.Welfare14, a.Welfare15, a.Welfare16, a.Welfare17, a.Welfare18, a.Welfare19,
				a.SecondId EnJobID, b.SecondId EnCpMainID, 
				a.LastModifyDate, b.Name cpName, b.dcCompanySizeID, 
				b.HasLicence, b.RealName, b.UnLimitedDate, b.BalanceDate, b.Balance, 
				b.MemberType, '' cpIndustry, --STUFF((SELECT ','+LTRIM(x.dcIndustryid)+',c'+LTRIM(isnull(y.Category,0)) FROM cpIndustry x,dcIndustry y WHERE x.dcIndustryid = y.id AND x.cpMainid = b.id FOR XML PATH('')),1,1,'') cpIndustry,
				c.IsTop, b.IsRefreshed, ISNULL(d.IsOnline, 0) IsOnline, d.IsVi, d.ViPlanId, d.InterviewDate, CASE WHEN b.ReplyRate >= 0.6 THEN b.ReplyRate ELSE NULL END Replyrate,
				(SELECT TOP 1 ID from paAttention WITH(NOLOCK) WHERE AttentionType=2 AND AttentionID=a.ID AND paMainId = @paMainId) AttentionId
			FROM JobPublish a WITH(NOLOCK)
			INNER JOIN cpMainPublish b WITH(NOLOCK) ON a.cpMainID = b.ID 
			INNER JOIN SearchDB..paSearchJobID_2 c WITH(NOLOCK) ON a.id = c.JobID
			LEFT JOIN caOnline d WITH(NOLOCK) ON a.caMainId = d.caMainId
			WHERE paSearchConditionID=@paSearchConditionID 
			AND c.ID >= @MinId
			ORDER BY c.ID, a.ID DESC
		END
		ELSE IF (@TableID = 3)
		BEGIN
			SELECT @MinId = MIN(ID) FROM SearchDB..paSearchJobID_3 WITH(NOLOCK) WHERE paSearchConditionID=@paSearchConditionID

			SET @MinId = @MinId+(@PageNumber-1)*@PageSize
			SELECT TOP 30 a.ID, a.cpMainID, a.caMainID, a.Name as JobName, a.dcJobTypeID, 
				a.dcJobTypeIDMinor, a.NeedNumber, a.dcSalaryID, a.dcSalaryIDMax, a.EmployType, 
				a.dcRegionID, a.Responsibility, a.Demand, a.dcEducationID, 
				a.MinExperience, a.MinAge, a.MaxAge, a.IssueDate, a.IssueEND, 
				a.IsDelete, a.AddDate, a.RefreshDate, a.Welfare1, a.Welfare2, a.Welfare3,
				a.Welfare4, a.Welfare5, a.Welfare6, a.Welfare7, a.Welfare8,
				a.Welfare9, a.Welfare10, a.Welfare11, a.Welfare12, a.Welfare13,
				a.Welfare14, a.Welfare15, a.Welfare16, a.Welfare17, a.Welfare18, a.Welfare19,
				a.SecondId EnJobID, b.SecondId EnCpMainID, 
				a.LastModifyDate, b.Name cpName, b.dcCompanySizeID, 
				b.HasLicence, b.RealName, b.UnLimitedDate, b.BalanceDate, b.Balance, 
				b.MemberType, '' cpIndustry, --STUFF((SELECT ',' + LTRIM(x.dcIndustryid) + ',c' + LTRIM(isnull(y.Category,0)) FROM cpIndustry x,dcIndustry y WHERE x.dcIndustryid = y.id AND x.cpMainid = b.id FOR XML PATH('')),1,1,'') cpIndustry,
				c.IsTop, b.IsRefreshed, ISNULL(d.IsOnline, 0) IsOnline, d.IsVi, d.ViPlanId, d.InterviewDate, CASE WHEN b.ReplyRate >= 0.6 THEN b.ReplyRate ELSE NULL END Replyrate,
				(SELECT TOP 1 ID from paAttention WITH(NOLOCK) WHERE AttentionType=2 AND AttentionID=a.ID AND paMainId = @paMainId) AttentionId
			FROM JobPublish a WITH(NOLOCK)
			INNER JOIN cpMainPublish b WITH(NOLOCK) ON a.cpMainID = b.ID 
			INNER JOIN SearchDB..paSearchJobID_3 c WITH(NOLOCK) ON a.id = c.JobID
			LEFT JOIN caOnline d WITH(NOLOCK) ON a.caMainId = d.caMainId
			WHERE paSearchConditionID=@paSearchConditionID 
			AND c.ID >= @MinId
			ORDER BY c.ID, a.ID DESC
		END
        --RICHARD 2011-7-23 16:51分修改
		----返回统计数量
		IF @Type=1
		BEGIN
			DECLARE @RegionCount AS INT
			SELECT @RegionCount = -1
			IF CHARINDEX(',', @dcRegionID) = 0 AND LEN(@dcRegionID) > 0
			BEGIN
				IF NOT LEFT(@dcRegionID, 1) = 'p'
					SELECT @RegionCount = COUNT(*) FROM dcRegion WHERE ParentID = @dcRegionID
			END
			IF (@TableID = 0)
			BEGIN
				SELECT * FROM SearchDB..paSearchCount_0 WITH(NOLOCK) WHERE Title = 'JobType' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(VARCHAR(10), TitleID)
				IF @RegionCount = 0
					SELECT * FROM dcMapPlace WITH(NOLOCK) WHERE dcRegionID = @dcRegionID
				ELSE
					SELECT * FROM SearchDB..paSearchCount_0 WITH(NOLOCK) WHERE Title = 'Region' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(VARCHAR(10), TitleID)
				SELECT * FROM SearchDB..paSearchCount_0 WITH(NOLOCK) WHERE Title = 'Education' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT * FROM SearchDB..paSearchCount_0 WITH(NOLOCK) WHERE Title = 'Experience' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT * FROM SearchDB..paSearchCount_0 WITH(NOLOCK) WHERE Title = 'Salary' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT * FROM SearchDB..paSearchCount_0 WITH(NOLOCK) WHERE Title = 'EmployType' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT * FROM SearchDB..paSearchCount_0 WITH(NOLOCK) WHERE Title = 'CompanySize' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT * FROM SearchDB..paSearchCount_0 WITH(NOLOCK) WHERE Title = 'Industry' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
			END
			IF (@TableID = 1)
			BEGIN
				SELECT * FROM SearchDB..paSearchCount_1 WITH(NOLOCK) WHERE Title = 'JobType' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(VARCHAR(10), TitleID)
				IF @RegionCount = 0
					SELECT * FROM dcMapPlace WITH(NOLOCK) WHERE dcRegionID = @dcRegionID
				ELSE
					SELECT * FROM SearchDB..paSearchCount_1 WITH(NOLOCK) WHERE Title = 'Region' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(VARCHAR(10), TitleID)
				SELECT * FROM SearchDB..paSearchCount_1 WITH(NOLOCK) WHERE Title = 'Education' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT * FROM SearchDB..paSearchCount_1 WITH(NOLOCK) WHERE Title = 'Experience' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT * FROM SearchDB..paSearchCount_1 WITH(NOLOCK) WHERE Title = 'Salary' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT * FROM SearchDB..paSearchCount_1 WITH(NOLOCK) WHERE Title = 'EmployType' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT * FROM SearchDB..paSearchCount_1 WITH(NOLOCK) WHERE Title = 'CompanySize' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT * FROM SearchDB..paSearchCount_1 WITH(NOLOCK) WHERE Title = 'Industry' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
			END
			IF (@TableID = 2)
			BEGIN
				SELECT * FROM SearchDB..paSearchCount_2 WITH(NOLOCK) WHERE Title = 'JobType' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(VARCHAR(10), TitleID)
				IF @RegionCount = 0
					SELECT * FROM dcMapPlace WITH(NOLOCK) WHERE dcRegionID = @dcRegionID
				ELSE
					SELECT * FROM SearchDB..paSearchCount_2 WITH(NOLOCK) WHERE Title = 'Region' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(VARCHAR(10), TitleID)
				SELECT * FROM SearchDB..paSearchCount_2 WITH(NOLOCK) WHERE Title = 'Education' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT * FROM SearchDB..paSearchCount_2 WITH(NOLOCK) WHERE Title = 'Experience' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT * FROM SearchDB..paSearchCount_2 WITH(NOLOCK) WHERE Title = 'Salary' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT * FROM SearchDB..paSearchCount_2 WITH(NOLOCK) WHERE Title = 'EmployType' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT * FROM SearchDB..paSearchCount_2 WITH(NOLOCK) WHERE Title = 'CompanySize' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT * FROM SearchDB..paSearchCount_2 WITH(NOLOCK) WHERE Title = 'Industry' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
			END
			IF (@TableID = 3)
			BEGIN
				SELECT * FROM SearchDB..paSearchCount_3 WITH(NOLOCK) WHERE Title = 'JobType' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(VARCHAR(10), TitleID)
				IF @RegionCount = 0
					SELECT * FROM dcMapPlace WITH(NOLOCK) WHERE dcRegionID = @dcRegionID
				ELSE
					SELECT * FROM SearchDB..paSearchCount_3 WITH(NOLOCK) WHERE Title = 'Region' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(VARCHAR(10), TitleID)
				SELECT * FROM SearchDB..paSearchCount_3 WITH(NOLOCK) WHERE Title = 'Education' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT * FROM SearchDB..paSearchCount_3 WITH(NOLOCK) WHERE Title = 'Experience' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT * FROM SearchDB..paSearchCount_3 WITH(NOLOCK) WHERE Title = 'Salary' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT * FROM SearchDB..paSearchCount_3 WITH(NOLOCK) WHERE Title = 'EmployType' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT * FROM SearchDB..paSearchCount_3 WITH(NOLOCK) WHERE Title = 'CompanySize' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT * FROM SearchDB..paSearchCount_3 WITH(NOLOCK) WHERE Title = 'Industry' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
			END
		END
		--UPDATE SearchDB..paSearchCondition SET SQl=@JobPlaceLen WHERE ID=@paSearchConditionID
		RETURN
	END
END TRY
BEGIN CATCH
	---检查是否已经建立临时表，已经建立则删除
	DECLARE @para VARCHAR(MAX)
	SET @para = '@dcJobTypeID=' + ISNULL(@dcJobTypeID, '') + '|' +
		'@dcRegionID=' + ISNULL(@dcRegionID, '') + '|' +
		'@dcIndustryID=' + ISNULL(@dcIndustryID, '') + '|' +
		'@EmployType=' + ISNULL(@EmployType, '') + '|' +
		'@KeyWord=' + ISNULL(@KeyWord, '') + '|' +
		'@ORDER=' + ISNULL(@ORDER, '') + '|' +
		'@SessionID=' + ISNULL(@SessionID, '') + '|' +
		'@Welfare=' + ISNULL(@Welfare, '')
	INSERT INTO ErrorLog	
	SELECT 'p1 ' +ISNULL(error_Message(), ' no msg')+ ' para=' + ISNULL(@Para, 'no para ') + ISNULL(@SQL, ' no sql'), error_number(), error_line(), GETDATE()
END CATCH

GO
/****** Object:  StoredProcedure [dbo].[pcJobBySearchSelectHotPlace]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[pcJobBySearchSelectHotPlace] 
(
	@dcJobTypeID VARCHAR(100), 		--职位类别
	@dcRegionID VARCHAR(100), 		--求职地区
	@dcIndustryID VARCHAR(100), 	--求职行业
	@dcSalaryID TINYINT, 			--月薪
	@IsNegotiable BIT, 				--1允许面议，不面议
	@MinExperience TINYINT, 		--工作经验，100为未选择
	@dcEducationID TINYINT, 		--最低学历
	@EmployType VARCHAR(10), 		--工作性质，1全职；3兼职；4实习，
	@KeyWord NVARCHAR(50), 			--关键词
	@KeyType TINYINT, 				--搜索类别，0无；1-全文；2-职位；3-公司 
	@ORDER VARCHAR(100), 			--显示顺序，没有用
	@RefreshNo INT, 				--1, 1天内；2, 3天内；3，一周内；4，15天内；5，一个月内；6超过一个月
	@Type INT, 						--1：主动搜索  点击搜索按钮 10分钟，翻页60分钟有效；0：翻页搜索，不刷新
	@PageNumber INT, 				--翻页页码
	@SessionID INT, 
	@CompanySizeID VARCHAR(1), 		--企业规模
	@JobId INT,
	@Welfare VARCHAR(50)					--
	--sessionid，没有采用全部人员共享方式，因为10分钟内，搜索相同条件的可能性很大，	
	--而10分钟搜索的用户翻到第二页时内容可能会和第一页一样。这样让用户很难理解。
	--使用SessionID, 可以保证60分钟内查询结果一致。出现不一致的几率很小
)
AS
INSERT proclog SELECT 'pcJobBySearchSelectHotPlace', @dcRegionID, GETDATE()
--return @SessionId = 15
SET NOCOUNT ON
BEGIN TRY
	IF @JobID > 0
	BEGIN
		IF EXISTS(SELECT 'x' FROM JobPublish WITH(NOLOCK) WHERE ID = @JobId AND Valid = 1)
		BEGIN
			SELECT 1
			SELECT a.ID, a.cpMainID, a.caMainID, a.Name as JobName, a.dcJobTypeID, 
				a.dcJobTypeIDMinor, a.NeedNumber, a.dcSalaryID, a.EmployType, 
				a.dcRegionID, a.Responsibility, a.Demand, a.dcEducationID, 
				a.MinExperience, a.MinAge, a.MaxAge, a.IssueDate, a.IssueEND, 
				a.IsDelete, a.AddDate, a.RefreshDate, 
				a.LastModifyDate,a.Welfare1,a.Welfare2,a.Welfare3,
				a.Welfare4,a.Welfare5,a.Welfare6,a.Welfare7,a.Welfare8,
				a.Welfare9,a.Welfare10,a.Welfare11,a.Welfare12,a.Welfare13,
				a.Welfare14,a.Welfare15,a.Welfare16,a.Welfare17,a.Welfare18,a.SecondId EnJobID,b.SecondId EnCpMainID, 
				b.Name as cpName, b.dcCompanySizeID, 
				b.HasLicence, b.UnLimitedDate, b.BalanceDate, b.Balance, b.MemberType,
				'' cpIndustry, --STUFF((SELECT ','+LTRIM(x.dcIndustryid)+',c'+LTRIM(isnull(y.Category,0)) FROM cpIndustry x,dcIndustry y WHERE x.dcIndustryid = y.id AND x.cpMainid = b.id FOR XML PATH('')),1,1,'') cpIndustry,
				0 IsTop, 0 IsRefreshed, c.IsOnline, c.IsVi, c.ViPlanId, c.InterviewDate
			FROM JobPublish a WITH(NOLOCK)
			INNER JOIN cpMainPublish b WITH(NOLOCK) ON a.cpMainID = b.ID
			LEFT Join caOnline c WITH(NOLOCK) ON a.caMainId = c.caMainId
			WHERE a.id = @JobID AND a.Valid = 1 AND b.Valid = 1
		END
		ELSE
		BEGIN
			SELECT 0
			SELECT TOP 0 NULL
		END
		SELECT TOP 0 * FROM SearchDB..paSearchCount WITH(NOLOCK)
		SELECT TOP 0 * FROM SearchDB..paSearchCount WITH(NOLOCK)
		SELECT TOP 0 * FROM SearchDB..paSearchCount WITH(NOLOCK)
		SELECT TOP 0 * FROM SearchDB..paSearchCount WITH(NOLOCK)
		SELECT TOP 0 * FROM SearchDB..paSearchCount WITH(NOLOCK)
		RETURN
	END
	ELSE
	BEGIN
		DECLARE @KeyWordTemp AS NVARCHAR(50), @KeyTypeTemp AS INT, @ReuseNumber AS INT
		----给null值变量赋默认值
		IF NOT LEFT(@dcRegionID,1) = 'p'
			SELECT @dcRegionID = RTRIM(dbo.FormatIDS(@dcRegionID))

		SELECT @dcJobTypeID = RTRIM(dbo.FormatIDS(@dcJobTypeID)),
			@dcIndustryID = RTRIM(dbo.FormatIDS(@dcIndustryID)),
			@dcSalaryID = ISNULL(@dcSalaryID, 0),
			@IsNegotiable = ISNULL(@IsNegotiable, 0),
			@MinExperience = ISNULL(@MinExperience, 100),
			@dcEducationID = ISNULL(@dcEducationID, 0),
			@EmployType = CASE @EmployType WHEN '2' THEN '1,3' ELSE ISNULL(@EmployType, '') END,
			@CompanySizeID = ISNULL(@CompanySizeID, '0'),
			@KeyWord = dbo.SafeSQL(ISNULL(@KeyWord, '')),
			@ORDER = ' ORDER BY a.RefreshDate DESC, a.ID',		--@ORDER = dbo.SafeSQL(ISNULL(@ORDER, '')),
			@Type = ISNULL(@Type, 0),
			@PageNumber = ISNULL(@PageNumber, 0),
			@KeyType = CASE @KeyWord WHEN NULL THEN 0 ELSE 1 END,
			@Welfare = RTRIM(dbo.FormatIDS(@Welfare))

		IF @dcSalaryID = 0
			SET @IsNegotiable = 0
			
		--@RefreshNo = 0选择全部数据，不限制时间
		SET @RefreshNo = 0
		IF(@KeyType = 0 AND ISNULL(@dcJobTypeID, '') = '' AND ISNULL(@dcRegionID, '') = '' AND ISNULL(@dcIndustryID, '') = '')
			RETURN

		--如果关键词不为空 查询关键词对应的搜索类型 max 2012-12-25 
		
		IF (@KeyWord IS NOT NULL)
		BEGIN
			SELECT @KeyTypeTemp = @KeyType
			SELECT @KeyType = KeyType 
			FROM Searchdb..SearchKeyword WITH(NOLOCK) 
			WHERE Keyword = @KeyWord

			-- 如果搜索类型不是职位类别 按照原搜索类型搜索 max 2012-12-25 
			IF @KeyType <> 4
				SET @KeyType = @KeyTypeTemp

			IF @KeyWord = ''
				SET @KeyType = 0
		END	

		-- 搜索类型4为职业类别
		IF(@KeyType = 4)
		BEGIN
			IF ISNULL(@dcJobTypeID, '') = ''
			BEGIN
				SELECT @dcJobTypeID = ID 
				FROM dcJobType WITH(NOLOCK) 
				WHERE Description = @KeyWord 
				OR DescriptionEng = @KeyWord
				SELECT @KeyWord = '', @KeyType = 0
			END
			ELSE
				SET @KeyType = @KeyTypeTemp		
		END

		IF (@KeyWord IS NOT NULL)
		BEGIN
			SET @KeyWordTemp = @KeyWord
		END
		IF LEN(@KeyWordTemp) > 2
		BEGIN
			SET @KeyWordTemp = REPLACE(@KeyWordTemp, '公司', '')
		END
		IF ISNULL(@KeyType, 0) NOT IN (1, 2, 3, 4, 5)
		BEGIN
			SET @KeyType = 0
			SET @KeyWord = ''
		END
			
		IF RIGHT(@dcJobTypeID, 1) = ','
			SET @dcJobTypeID = LEFT(@dcJobTypeID, LEN(@dcJobTypeID) - 1)
		IF RIGHT(@dcRegionID, 1) = ','
			SET @dcRegionID = LEFT(@dcRegionID, LEN(@dcRegionID) - 1)
		IF RIGHT(@dcIndustryID, 1) = ','
			SET @dcIndustryID = LEFT(@dcIndustryID, LEN(@dcIndustryID) - 1)

		DECLARE @paSearchConditionID AS INT, 
			@MinId AS INT, 
			@PageSize AS TINYINT, 
			@TableID AS TINYINT

		SELECT @paSearchConditionID = 0, @PageSize = 30
		/*, @SessionId = ISNULL(@SessionId, 9908)  --每页的行数
		IF @SessionId = 0
			SET @SessionId = 9920
		IF @SessionId = 1
			SET @SessionId = 9921
		IF @SessionId = 11
			SET @SessionId = 9922
		IF @SessionId = 111
			SET @SessionId = 9923
		*/
		SET @SessionId = 15
		----搜索1分钟前的数据
		SELECT TOP 1 @paSearchConditionID = ID,
			@ReuseNumber = ReuseNumber
		FROM SearchDB..paSearchCondition WITH(NOLOCK)
		WHERE JobType=@dcJobTypeID
		AND JobPlace=@dcRegionID AND Industry=@dcIndustryID AND Education=@dcEducationID
		AND Experience=@MinExperience AND Salary=@dcSalaryID AND IsNegotiable=@IsNegotiable 
		AND EmployType=@EmployType AND KeyWord=@KeyWord AND KeyType=@KeyType
		AND CompanySizeID = @CompanySizeID AND Welfare = @Welfare
		AND LogTime > DATEADD(MINUTE, -1, GETDATE()) AND ReuseNumber > 0
		AND RefreshNo = 0
		ORDER BY ID DESC

		IF @ReuseNumber = 0
		BEGIN
			SELECT TOP 1 @paSearchConditionID = ID
			FROM SearchDB..paSearchCondition WITH(NOLOCK)
			WHERE JobType=@dcJobTypeID
			AND JobPlace=@dcRegionID AND Industry=@dcIndustryID AND Education=@dcEducationID
			AND Experience=@MinExperience AND Salary=@dcSalaryID AND IsNegotiable=@IsNegotiable 
			AND EmployType=@EmployType AND KeyWord=@KeyWord AND KeyType=@KeyType
			AND CompanySizeID = @CompanySizeID AND Welfare = @Welfare
			AND ReuseNumber > 0 AND LogTime > DATEADD(MINUTE, -2, GETDATE()) 
			AND RefreshNo = 0
			ORDER BY ID DESC
		END

		IF ISNULL(@paSearchConditionID, 0) = 0
		BEGIN
			SET @Type =1
			GOTO SelectReset	--无数据，重新搜索
		END
		ELSE
		BEGIN
			SELECT @TableID = @paSearchConditionID % 4
			GOTO GetRecordSet	--从临时结果中提取数据
		END
	END

SelectReset:
	--从job中搜索数据
	BEGIN TRAN
		DECLARE @SQL AS VARCHAR(8000)
		DECLARE @WHERE AS VARCHAR(8000)
		DECLARE @FROM AS VARCHAR(1000)
		----记录查询条件
		INSERT INTO SearchDB..paSearchCondition(SessionID, LogTime, JobType, JobPlace, Industry, Education, Experience, 
			Salary, IsNegotiable, EmployType, CompanySizeID, KeyWord, KeyType, ReuseNumber, Welfare)
		VALUES(
			@SessionId, GETDATE(), @dcJobTypeID, @dcRegionID, @dcIndustryID, @dcEducationID, @MinExperience, 
			@dcSalaryID, @IsNegotiable, @EmployType, @CompanySizeID, @KeyWord, @KeyType, 0, @Welfare)
		SET @paSearchConditionID = @@IDENTITY
		SELECT @TableID = @paSearchConditionID % 4

		------生成职位类别的表变量，因为职位类别有包含（父子）关系
		DECLARE @T_JobPlace AS TABLE(ID INT)
		DECLARE @T_JobType AS TABLE(ID INT)
		DECLARE @JobType AS VARCHAR(3000), @JobPlace AS VARCHAR(2000), @ValidJobNumber AS INT

		SELECT @JobPlace = '', @JobType=''
		----生成工作地点的表变量
		IF LEN(@dcRegionID) > 0
		BEGIN
			IF LEFT(@dcRegionID,1) = 'p'
			BEGIN
				DECLARE @Degree AS DECIMAL(8,5),@LBLng AS DECIMAL(8,5),@LBLat AS DECIMAL(8,5),
				@RTLng AS DECIMAL(8,5),@RTLat AS DECIMAL(8,5),@Lat AS DECIMAL(8,5),@Lng AS DECIMAL(8,5)
				
				SELECT @Lat = Lat,@Lng = Lng FROM dcMapPlace WITH(NOLOCK) WHERE ID = RIGHT(@dcRegionID,LEN(@dcRegionID)-1)
				IF @dcRegionID LIKE '3201%'
					SET @Degree = 1000 / 100000.0
				ELSE
					SET @Degree = 2000 / 100000.0

				SET @LBLng = @Lng - @Degree
				SET @LBLat = @Lat - @Degree
				SET @RTLng = @Lng + @Degree
				SET @RTLat = @Lat + @Degree
				SET @JobPlace = 'a.Lng BETWEEN ' + CONVERT(VARCHAR,@LBLng) + ' AND ' + CONVERT(VARCHAR,@RTLng) + '
					AND a.Lat BETWEEN ' + CONVERT(VARCHAR,@LBLat) + ' AND ' + CONVERT(VARCHAR,@RTLat) + '
					AND (a.Lng-' + CONVERT(VARCHAR,@Lng) + ')*(a.Lng-' + CONVERT(VARCHAR,@Lng) + ')+
					(a.Lat-' + CONVERT(VARCHAR,@Lat) + ')*(a.Lat-' + CONVERT(VARCHAR,@Lat) + ')<' + CONVERT(VARCHAR,@Degree*@Degree)
			END
			ELSE
			BEGIN
				INSERT INTO @T_JobPlace
				SELECT * FROM dbo.fnSplit(@dcRegionID, ',')
				SELECT @JobPlace = (@JobPlace + ' OR a.dcRegionID Like ''' + LTRIM(STR(ID) + '%''')) FROM @T_JobPlace
				IF LEN(@JobPlace) > 0
					SET @JobPlace = RIGHT(@JobPlace, LEN(@JobPlace) -4)
			END
		END

		----生成求聘职位的表变量
		IF LEN(@dcJobTypeID) > 0
		BEGIN
			DECLARE @T_Temp AS TABLE(ID INT)		--临时表，用于构建组合查询语句
			INSERT INTO @T_Temp
			SELECT * FROM dbo.fnSplit(@dcJobTypeID, ',')

			INSERT INTO @T_JobType
			SELECT DISTINCT ID FROM dcJobType WITH(NOLOCK)
			WHERE ParentId IN(SELECT ID FROM @T_TEMP) 
			OR ParentId2 in(SELECT ID FROM @T_TEMP)
			OR ID IN(SELECT ID FROM @T_TEMP)
			----生成in字符串
			SELECT @JobType = (@JobType + LTRIM(STR(ID) + ',')) FROM @T_JobType
			IF RIGHT(@JobType, 1) = ','
				SET @JobType = LEFT(@JobType, LEN(@JobType) - 1)
		END

		----建立临时表
		CREATE TABLE #Job(
			RowID INT IDENTITY(1, 1), 
			ID INT NOT NULL, 
			dcJobTypeID SMALLINT NOT NULL, 
			dcJobTypeIDMinor SMALLINT NULL, 
			dcSalaryID TINYINT NOT NULL, 
			dcRegionID VARCHAR(6) NULL, 
			dcEducationID TINYINT NOT NULL, 
			MinExperience TINYINT NOT NULL, 
			RefreshDate SMALLDATETIME NULL,
			EmployType TINYINT NULL,
			dcCompanySizeID SMALLINT NULL
		)

		CREATE TABLE #FullText(
			Priority INT,
			JobId INT NOT NULL
		)

		------刷新时间，根据刷新时间编号计算
		----生成插入临时表的Sql语句
		SET @SQL='
			INSERT INTO #Job
			SELECT a.ID, a.dcJobTypeID, 
				a.dcJobTypeIDMinor, a.dcSalaryID, 
				a.dcRegionID, a.dcEducationID, a.MinExperience, 
				a.IssueDate,a.EmployType,b.dcCompanySizeID'
		SET @FROM = '
			FROM JobPublish a WITH(NOLOCK)
			INNER JOIN cpMainPublish b WITH(NOLOCK) ON a.cpMainID=b.ID'
		----职位有效，单位新有效
		IF LEN(@dcIndustryID) > 0
			SET @WHERE = '
			WHERE b.ID IN (SELECT cpMainID FROM cpIndustry WHERE dcIndustryId in(' + @dcIndustryID + '))
			AND a.Valid = 1
			AND b.Valid = 1'
		ELSE
			SET @WHERE = '
			WHERE a.Valid = 1
			AND b.Valid = 1'
		----需要增加全文索引的关键字查询
		IF @KeyWord LIKE '% %'
		BEGIN
			SET @KeyWord = REPLACE(@KeyWord, '  ', ' ')
			SET @KeyWord = REPLACE(@KeyWord, '  ', ' ')
			SET @KeyWord = REPLACE(@KeyWord, '  ', ' ')
			SET @KeyWord = '"' + REPLACE(@KeyWord, ' ', '" OR "') + '"'
		END
		IF @KeyWordTemp LIKE '% %'
		BEGIN
			SET @KeyWordTemp = REPLACE(@KeyWordTemp, '  ', ' ')
			SET @KeyWordTemp = REPLACE(@KeyWordTemp, '  ', ' ')
			SET @KeyWordTemp = REPLACE(@KeyWordTemp, '  ', ' ')
			SET @KeyWordTemp = '"' + REPLACE(@KeyWordTemp, ' ', '" OR "') + '"'
		END

		----职位类别
		IF LEN(@dcJobTypeID) > 0
			SET @WHERE = @WHERE + '
			AND (a.dcJobTypeID IN(' + @JobType +')
				OR a.dcJobTypeIDMinor IN(' +@JobType + '))'
		IF LEN(@JobPlace) > 0 
			SET @WHERE = @WHERE + '
			AND (' + @JobPlace + ')'

		IF @dcSalaryID > 0
		BEGIN
			IF @dcSalaryID < 100				----从form中搜索，月薪跨2个级别, 是本级和上级别的薪金
			BEGIN
				SET @WHERE = @WHERE + '
			AND a.dcSalaryID IN(' + LTRIM(STR(@dcSalaryID)) + ',' + LTRIM(STR(@dcSalaryID + 1))
				IF @IsNegotiable = 1		--包括面议
					SET @WHERE = @WHERE + ', 100'
				SET @WHERE = @WHERE + ')'
			END
			IF @dcSalaryID = 100	----从筛选结果中点击面议，值是100
			BEGIN
				SET @WHERE = @WHERE + '
			AND a.dcSalaryID = 100'
			END
			IF @dcSalaryID > 100	----从筛选结果中点击搜索，月薪只有1个级别，传值时增加100
				SET @WHERE = @WHERE + '
			AND a.dcSalaryID=' + LTRIM(STR(@dcSalaryID-100))
		END
		----工作经验要求
		IF @MinExperience < 100
		SET @WHERE = @WHERE + ' 
			AND a.MinExperience = ' + LTRIM(STR(@MinExperience))

		----学历要求
		----'1初中', '2\3\4高中、中技、中专', '5大专', '6本科', '7硕士', '8博士
		IF @dcEducationID > 0
			IF @dcEducationID = 2
				SET @WHERE = @WHERE + '
			AND a.dcEducationID IN(2, 3, 4)'
			ELSE
				SET @WHERE = @WHERE + '
			AND a.dcEducationID = ' + LTRIM(STR(@dcEducationID))
		----1、全职；3、兼职；4实习。	2、全职/兼职 职位中无此项
		IF LEN(@EmployType) > 0
			SET @WHERE = @WHERE + '
			AND a.EmployType IN (' + @EmployType + ')'

		IF @CompanySizeID BETWEEN 1 AND 6
			SET @WHERE = @WHERE + '
			AND b.dcCompanySizeID = ' + LTRIM(STR(@CompanySizeID))

		IF LEN(@Welfare) > 0
			SET @WHERE = @WHERE + '
			AND a.Welfare' + REPLACE(@Welfare, ',', ' = 1 AND a.Welfare') + ' = 1'

		IF LEN(@KeyWord) > 0 AND @KeyType > 0	----使用全文搜索job和cpmain2个表，经过测试发现union最快
		BEGIN
			IF EXISTS(SELECT TOP 1 'x' FROM cpMainPublish WITH(NOLOCK) WHERE Name = @KeyWord)
			BEGIN
				SET @WHERE = @WHERE + '
			AND b.Name = ''' + @KeyWord + ''''
				SET @SQL = @SQL + @FROM + @WHERE
			END
			ELSE
			BEGIN
				INSERT #FullText
				SELECT 1, [Key]
				FROM CONTAINSTABLE(JobPublish, Name, @KeyWord, 100000) AS KeyJob

				INSERT #FullText
				SELECT 2, a.ID
				FROM JobPublish a WITH(NOLOCK),
					CONTAINSTABLE(cpMainPublish, Name, @KeyWord, 100000) AS b
				WHERE a.cpMainId = b.[Key]
				DELETE #FullText WHERE Priority = 2 AND JobId IN(SELECT JobId FROM #FullText WHERE Priority = 1)

				IF (SELECT COUNT(*) FROM #FullText) < 5000
				BEGIN
					INSERT #FullText
					SELECT 3, [Key]
					FROM CONTAINSTABLE(JobPublish, *, @KeyWord, 100000) AS KeyJob
					DELETE #FullText WHERE Priority = 3 AND JobId IN(SELECT JobId FROM #FullText WHERE Priority < 3)

					IF (SELECT COUNT(*) FROM #FullText) < 5000
					BEGIN
						INSERT #FullText
						SELECT 4, a.ID
						FROM JobPublish a WITH(NOLOCK),
							CONTAINSTABLE(cpMainPublish, *, @KeyWord, 100000) AS b
						WHERE a.cpMainId = b.[Key]
					
						DELETE #FullText WHERE Priority = 4 AND JobId IN(SELECT JobId FROM #FullText WHERE Priority < 4)
					END
				END
				--------------------
				SELECT @FROM = @FROM + '
			INNER JOIN #FullText ON a.ID = #FullText.JobId',
					@ORDER = ' ORDER BY #FullText.Priority, a.RefreshDate DESC, a.ID'
				SET @SQL = @SQL + @FROM + @WHERE
			END
		END
		ELSE
			SET @SQL = @SQL + @FROM + @WHERE
		
		SET @SQL = @SQL + @ORDER	--' ORDER BY a.RefreshDate DESC, a.ID'
		--原来是ORDER BY a.IssueDate DESC, a.ID，Richard 2011年11月23日17：06分修改
		----把符合条件的职位全部列出
		--PRINT @SQL
		EXEC(@SQL)
		SET @ValidJobNumber = @@ROWCOUNT
		----记录查询结果总数
		UPDATE SearchDB..paSearchCondition SET ValidJobNumber=@ValidJobNumber, SQl=@SQL WHERE ID=@paSearchConditionID
		
		IF LEN(@dcJobTypeID) > 0	--IN(2, 4)
			UPDATE #Job SET dcJobTypeId = dcJobTypeIDMinor
			WHERE dcJobTypeID NOT IN(SELECT a FROM dbo.fnSplit(@JobType, ','))

		----插入JobType数据
		DECLARE @TitleValue AS INT, @TopRows AS INT, @AllRows AS INT
		IF (@TableID = 0)
		BEGIN
			--IF LEN(@dcJobTypeID) IN(2, 4)
				INSERT INTO SearchDB..paSearchCount_0(paSearchConditionID, Title, TitleId, TitleValue)
				SELECT @paSearchConditionID, 'JobType', dcJobTypeID, COUNT(*) FROM #Job WITH(NOLOCK)
			--	WHERE dcJobTypeID LIKE @dcJobTypeID + '%'
			--	OR dcJobTypeIDMinor LIKE @dcJobTypeID + '%'
				GROUP BY dcJobTypeID ORDER BY dcJobTypeID
			--ELSE
			--	INSERT INTO SearchDB..paSearchCount_0(paSearchConditionID, Title, TitleId, TitleValue)
			--	SELECT @paSearchConditionID, 'JobType', dcJobTypeID, COUNT(*) FROM #Job WITH(NOLOCK)
			--	GROUP BY dcJobTypeID ORDER BY dcJobTypeID

			----计算全部某职位类别，2, 4位的数据
			UPDATE a SET a.TitleValue = b.TitleValue
			FROM SearchDB..paSearchCount_0 a WITH(NOLOCK), 
				(SELECT LEFT(TitleID, 2) TitleID, SUM(TitleValue) TitleValue
				FROM SearchDB..paSearchCount_0 WITH(NOLOCK)
				WHERE paSearchConditionID = @paSearchConditionID AND Title = 'JobType'
				GROUP BY LEFT(TitleID, 2)) b
			WHERE a.TitleId = b.TitleID
			AND a.paSearchConditionID = @paSearchConditionID AND a.Title = 'JobType'
			
			INSERT INTO SearchDB..paSearchCount_0(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'EmployType', EmployType, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY EmployType ORDER BY EmployType

			INSERT INTO SearchDB..paSearchCount_0(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'CompanySize', dcCompanySizeID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcCompanySizeID ORDER BY dcCompanySizeID

			INSERT INTO SearchDB..paSearchCount_0(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Salary', dcSalaryID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcSalaryID ORDER BY dcSalaryID

			INSERT INTO SearchDB..paSearchCount_0(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Region', dcRegionID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcRegionID ORDER BY dcRegionID
			----计算全部地区，2位的数据
			UPDATE a SET a.TitleValue = b.TitleValue
			FROM SearchDB..paSearchCount_0 a WITH(NOLOCK), 
			(SELECT LEFT(TitleID, 2) TitleID, SUM(TitleValue) TitleValue
			FROM SearchDB..paSearchCount_0 WITH(NOLOCK)
			WHERE paSearchConditionID = @paSearchConditionID AND Title = 'Region'
			GROUP BY LEFT(TitleID, 2)) b
			WHERE a.TitleId = b.TitleID
			AND a.paSearchConditionID = @paSearchConditionID AND a.Title = 'Region'
			----计算全部地区，4位的数据
			UPDATE a SET a.TitleValue = b.TitleValue
			FROM SearchDB..paSearchCount_0 a WITH(NOLOCK), (
				SELECT LEFT(TitleID, 4) TitleID, SUM(TitleValue) TitleValue
				FROM SearchDB..paSearchCount_0 WITH(NOLOCK)
				WHERE paSearchConditionID = @paSearchConditionID AND Title = 'Region'
				AND LEN(TitleID) >3
				GROUP BY LEFT(TitleID, 4)) b
			WHERE a.TitleId = b.TitleID
			AND a.paSearchConditionID = @paSearchConditionID AND a.Title = 'Region'

			INSERT INTO SearchDB..paSearchCount_0(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Education', dcEducationID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcEducationID ORDER BY dcEducationID
			--学历 高中、中专、中级合并		
			SELECT @TitleValue = SUM(TitleValue) FROM SearchDB..paSearchCount_0 WITH(NOLOCK)
			WHERE paSearchConditionID = @paSearchConditionID
			AND Title = 'Education' AND TitleID IN(2, 3, 4)		
			IF @TitleValue IS NOT NULL
			BEGIN
				IF EXISTS(SELECT 'X' FROM SearchDB..paSearchCount_0 WITH(NOLOCK) WHERE paSearchConditionID = @paSearchConditionID AND Title = 'Education' AND TitleID = 2)
					UPDATE SearchDB..paSearchCount_0 SET TitleValue = @TitleValue 
					WHERE paSearchConditionID = @paSearchConditionID
					AND Title = 'Education' AND TitleID = 2
				ELSE
					INSERT INTO SearchDB..paSearchCount_0(paSearchConditionID, Title, TitleId, TitleValue) VALUES
					(@paSearchConditionID, 'Education', 2, @TitleValue)

				DELETE FROM SearchDB..paSearchCount_0
				WHERE paSearchConditionID = @paSearchConditionID
				AND Title = 'Education' AND TitleID IN(3, 4)
			END 

			INSERT INTO SearchDB..paSearchCount_0(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Experience', MinExperience, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY MinExperience ORDER BY MinExperience
			
/*			----写入TitleDesc
			UPDATE a SET a.TitleDesc = b.Description
			FROM SearchDB..paSearchCount_0 a WITH(NOLOCK), dcEducation b WITH(NOLOCK)
			WHERE a.TitleID = b.ID AND a.paSearchConditionID = @paSearchConditionID
			AND a.Title = 'Education'
			
			UPDATE a SET a.TitleDesc = b.Description
			FROM SearchDB..paSearchCount_0 a WITH(NOLOCK), dcRegion b WITH(NOLOCK)
			WHERE a.TitleID = b.ID AND a.paSearchConditionID = @paSearchConditionID
			AND a.Title = 'Region'

			UPDATE a SET a.TitleDesc = b.Description
			FROM SearchDB..paSearchCount_0 a WITH(NOLOCK), dcJobType b WITH(NOLOCK)
			WHERE a.TitleID = b.ID AND a.paSearchConditionID = @paSearchConditionID
			AND a.Title = 'JobType'

			UPDATE a SET a.TitleDesc = b.Description
			FROM SearchDB..paSearchCount_0 a WITH(NOLOCK), dcSalary b WITH(NOLOCK)
			WHERE a.TitleID = b.ID AND a.paSearchConditionID = @paSearchConditionID
			AND a.Title = 'Salary'

			UPDATE a SET a.TitleDesc = b.Description
			FROM SearchDB..paSearchCount_0 a WITH(NOLOCK), dcCompanySize b WITH(NOLOCK)
			WHERE a.TitleID = b.ID AND a.paSearchConditionID = @paSearchConditionID
			AND a.Title = 'CompanySize'

			UPDATE a SET a.TitleDesc = b.Description
			FROM SearchDB..paSearchCount_0 a WITH(NOLOCK), dcCompanySize b WITH(NOLOCK)
			WHERE a.TitleID = b.ID AND a.paSearchConditionID = @paSearchConditionID
			AND a.Title = 'CompanySize'
			
			UPDATE SearchDB..paSearchCount_0 SET TitleDesc = 
			CASE TitleID
				WHEN 0 THEN '不限'
				WHEN 1 THEN '1~2年'
				WHEN 2 THEN '3~5年'
				WHEN 3 THEN '6~10年'
				WHEN 4 THEN '10年以上'
				WHEN 5 THEN '应届毕业生'
			END
			WHERE paSearchConditionID = @paSearchConditionID
			AND Title = 'Experience'

			UPDATE SearchDB..paSearchCount_0 SET TitleDesc = 
			CASE TitleID
				WHEN 1 THEN '全职'
				WHEN 3 THEN '兼职'
				WHEN 4 THEN '实习'
			END
			WHERE paSearchConditionID = @paSearchConditionID
			AND Title = 'EmployType'
*/
			INSERT INTO SearchDB..paSearchJobID_0(paSearchConditionID, JobId, IsTop)
			SELECT Top 3 @paSearchConditionID, a.JobId, 1 
			FROM SearchJobTop a WITH(NOLOCK), (SELECT TOP 2000 ID FROM #Job WITH(NOLOCK)) b 
			WHERE b.ID = a.JobId ORDER BY a.OpenDate DESC
			SET @TopRows = @@ROWCOUNT

			INSERT INTO SearchDB..paSearchJobID_0(paSearchConditionID, JobId, IsTop)
			SELECT TOP 2000 @paSearchConditionID, ID, 0 FROM #Job WITH(NOLOCK)
			SET @AllRows = @@ROWCOUNT

			IF @TopRows = 0 AND @AllRows > 100
				UPDATE SearchDB..paSearchJobID_0 SET IsTop = 1 
				WHERE paSearchConditionID = @paSearchConditionID
				AND ID IN (SELECT TOP 3 ID FROM SearchDB..paSearchJobID_0 WITH(NOLOCK) WHERE paSearchConditionID = @paSearchConditionID)
		END
		ELSE IF (@TableId = 1)
		BEGIN
			--IF LEN(@dcJobTypeID) IN(2, 4)
				INSERT INTO SearchDB..paSearchCount_1(paSearchConditionID, Title, TitleId, TitleValue)
				SELECT @paSearchConditionID, 'JobType', dcJobTypeID, COUNT(*) FROM #Job WITH(NOLOCK)
			--	WHERE dcJobTypeID LIKE @dcJobTypeID + '%'
			--	OR dcJobTypeIDMinor LIKE @dcJobTypeID + '%'
				GROUP BY dcJobTypeID ORDER BY dcJobTypeID
			--ELSE
			--	INSERT INTO SearchDB..paSearchCount_1(paSearchConditionID, Title, TitleId, TitleValue)
			--	SELECT @paSearchConditionID, 'JobType', dcJobTypeID, COUNT(*) FROM #Job WITH(NOLOCK)
			--	GROUP BY dcJobTypeID ORDER BY dcJobTypeID

			----计算全部某职位类别，2, 4位的数据
			UPDATE a SET a.TitleValue = b.TitleValue
			FROM SearchDB..paSearchCount_1 a WITH(NOLOCK), 
			(SELECT LEFT(TitleID, 2) TitleID, SUM(TitleValue) TitleValue
			FROM SearchDB..paSearchCount_1 WITH(NOLOCK)
			WHERE paSearchConditionID = @paSearchConditionID AND Title = 'JobType'
			GROUP BY LEFT(TitleID, 2)) b
			WHERE a.TitleId = b.TitleID
			AND a.paSearchConditionID = @paSearchConditionID AND a.Title = 'JobType'
			
			INSERT INTO SearchDB..paSearchCount_1(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Salary', dcSalaryID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcSalaryID ORDER BY dcSalaryID

			INSERT INTO SearchDB..paSearchCount_1(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Region', dcRegionID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcRegionID ORDER BY dcRegionID

			INSERT INTO SearchDB..paSearchCount_1(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'EmployType', EmployType, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY EmployType ORDER BY EmployType

			INSERT INTO SearchDB..paSearchCount_1(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'CompanySize', dcCompanySizeID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcCompanySizeID ORDER BY dcCompanySizeID

			----计算全部地区，2位的数据
			UPDATE a SET a.TitleValue = b.TitleValue
			FROM SearchDB..paSearchCount_1 a WITH(NOLOCK), 
			(SELECT LEFT(TitleID, 2) TitleID, SUM(TitleValue) TitleValue
			FROM SearchDB..paSearchCount_1 WITH(NOLOCK)
			WHERE paSearchConditionID = @paSearchConditionID AND Title = 'Region'
			GROUP BY LEFT(TitleID, 2)) b
			WHERE a.TitleId = b.TitleID
			AND a.paSearchConditionID = @paSearchConditionID AND a.Title = 'Region'
			----计算全部地区，4位的数据
			UPDATE a SET a.TitleValue = b.TitleValue
			FROM SearchDB..paSearchCount_1 a WITH(NOLOCK), (
				SELECT LEFT(TitleID, 4) TitleID, SUM(TitleValue) TitleValue
				FROM SearchDB..paSearchCount_1 WITH(NOLOCK)
				WHERE paSearchConditionID = @paSearchConditionID AND Title = 'Region'
				AND LEN(TitleID) >3
				GROUP BY LEFT(TitleID, 4)) b
			WHERE a.TitleId = b.TitleID
			AND a.paSearchConditionID = @paSearchConditionID AND a.Title = 'Region'

			INSERT INTO SearchDB..paSearchCount_1(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Education', dcEducationID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcEducationID ORDER BY dcEducationID
			--学历 高中、中专、中级合并		
			SELECT @TitleValue = SUM(TitleValue) FROM SearchDB..paSearchCount_1 WITH(NOLOCK)
			WHERE paSearchConditionID = @paSearchConditionID
			AND Title = 'Education' AND TitleID IN(2, 3, 4)		
			IF @TitleValue IS NOT NULL
			BEGIN
				IF EXISTS(SELECT 'X' FROM SearchDB..paSearchCount_1 WITH(NOLOCK) WHERE paSearchConditionID = @paSearchConditionID AND Title = 'Education' AND TitleID = 2)
					UPDATE SearchDB..paSearchCount_1 SET TitleValue = @TitleValue 
					WHERE paSearchConditionID = @paSearchConditionID
					AND Title = 'Education' AND TitleID = 2
				ELSE
					INSERT INTO SearchDB..paSearchCount_1(paSearchConditionID, Title, TitleId, TitleValue) VALUES
					(@paSearchConditionID, 'Education', 2, @TitleValue)

				DELETE FROM SearchDB..paSearchCount_1
				WHERE paSearchConditionID = @paSearchConditionID
				AND Title = 'Education' AND TitleID IN(3, 4)
			END 

			INSERT INTO SearchDB..paSearchCount_1(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Experience', MinExperience, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY MinExperience ORDER BY MinExperience
	
/*			----写入TitleDesc
			UPDATE a SET a.TitleDesc = b.Description
			FROM SearchDB..paSearchCount_1 a WITH(NOLOCK), dcEducation b WITH(NOLOCK)
			WHERE a.TitleID = b.ID AND a.paSearchConditionID = @paSearchConditionID
			AND a.Title = 'Education'
			
			UPDATE a SET a.TitleDesc = b.Description
			FROM SearchDB..paSearchCount_1 a WITH(NOLOCK), dcRegion b WITH(NOLOCK)
			WHERE a.TitleID = b.ID AND a.paSearchConditionID = @paSearchConditionID
			AND a.Title = 'Region'

			UPDATE a SET a.TitleDesc = b.Description
			FROM SearchDB..paSearchCount_1 a WITH(NOLOCK), dcJobType b WITH(NOLOCK)
			WHERE a.TitleID = b.ID AND a.paSearchConditionID = @paSearchConditionID
			AND a.Title = 'JobType'

			UPDATE a SET a.TitleDesc = b.Description
			FROM SearchDB..paSearchCount_1 a WITH(NOLOCK), dcSalary b WITH(NOLOCK)
			WHERE a.TitleID = b.ID AND a.paSearchConditionID = @paSearchConditionID
			AND a.Title = 'Salary'

			UPDATE a SET a.TitleDesc = b.Description
			FROM SearchDB..paSearchCount_1 a WITH(NOLOCK), dcCompanySize b WITH(NOLOCK)
			WHERE a.TitleID = b.ID AND a.paSearchConditionID = @paSearchConditionID
			AND a.Title = 'CompanySize'

			UPDATE a SET a.TitleDesc = b.Description
			FROM SearchDB..paSearchCount_1 a WITH(NOLOCK), dcCompanySize b WITH(NOLOCK)
			WHERE a.TitleID = b.ID AND a.paSearchConditionID = @paSearchConditionID
			AND a.Title = 'CompanySize'
			
			UPDATE SearchDB..paSearchCount_1 SET TitleDesc = 
			CASE TitleID
				WHEN 0 THEN '不限'
				WHEN 1 THEN '1~2年'
				WHEN 2 THEN '3~5年'
				WHEN 3 THEN '6~10年'
				WHEN 4 THEN '10年以上'
				WHEN 5 THEN '应届毕业生'
			END
			WHERE paSearchConditionID = @paSearchConditionID
			AND Title = 'Experience'

			UPDATE SearchDB..paSearchCount_1 SET TitleDesc = 
			CASE TitleID
				WHEN 1 THEN '全职'
				WHEN 3 THEN '兼职'
				WHEN 4 THEN '实习'
			END
			WHERE paSearchConditionID = @paSearchConditionID
			AND Title = 'EmployType'
*/
			INSERT INTO SearchDB..paSearchJobID_1(paSearchConditionID, JobId, IsTop)
			SELECT Top 3 @paSearchConditionID, a.JobId, 1 
			FROM SearchJobTop a WITH(NOLOCK), (SELECT TOP 2000 ID FROM #Job WITH(NOLOCK)) b 
			WHERE b.ID = a.JobId ORDER BY a.OpenDate DESC
			SET @TopRows = @@ROWCOUNT

			INSERT INTO SearchDB..paSearchJobID_1(paSearchConditionID, JobId, IsTop)
			SELECT TOP 2000 @paSearchConditionID, ID, 0 FROM #Job WITH(NOLOCK)
			SET @AllRows = @@ROWCOUNT

			IF @TopRows = 0 AND @AllRows > 100
				UPDATE SearchDB..paSearchJobID_1 SET IsTop = 1 
				WHERE paSearchConditionID = @paSearchConditionID
				AND ID IN (SELECT TOP 3 ID FROM SearchDB..paSearchJobID_1 WITH(NOLOCK) WHERE paSearchConditionID = @paSearchConditionID)
		END
		ELSE IF (@TableId = 2)
		BEGIN
			--IF LEN(@dcJobTypeID) IN(2, 4)
				INSERT INTO SearchDB..paSearchCount_2(paSearchConditionID, Title, TitleId, TitleValue)
				SELECT @paSearchConditionID, 'JobType', dcJobTypeID, COUNT(*) FROM #Job WITH(NOLOCK)
			--	WHERE dcJobTypeID LIKE @dcJobTypeID + '%'
			--	OR dcJobTypeIDMinor LIKE @dcJobTypeID + '%'
				GROUP BY dcJobTypeID ORDER BY dcJobTypeID
			--ELSE
			--	INSERT INTO SearchDB..paSearchCount_2(paSearchConditionID, Title, TitleId, TitleValue)
			--	SELECT @paSearchConditionID, 'JobType', dcJobTypeID, COUNT(*) FROM #Job WITH(NOLOCK)
			--	GROUP BY dcJobTypeID ORDER BY dcJobTypeID

			----计算全部某职位类别，2, 4位的数据
			UPDATE a SET a.TitleValue = b.TitleValue
			FROM SearchDB..paSearchCount_2 a WITH(NOLOCK), 
			(SELECT LEFT(TitleID, 2) TitleID, SUM(TitleValue) TitleValue
			FROM SearchDB..paSearchCount_2 WITH(NOLOCK)
			WHERE paSearchConditionID = @paSearchConditionID AND Title = 'JobType'
			GROUP BY LEFT(TitleID, 2)) b
			WHERE a.TitleId = b.TitleID
			AND a.paSearchConditionID = @paSearchConditionID AND a.Title = 'JobType'
			
			INSERT INTO SearchDB..paSearchCount_2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Salary', dcSalaryID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcSalaryID ORDER BY dcSalaryID

			INSERT INTO SearchDB..paSearchCount_2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'EmployType', EmployType, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY EmployType ORDER BY EmployType

			INSERT INTO SearchDB..paSearchCount_2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'CompanySize', dcCompanySizeID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcCompanySizeID ORDER BY dcCompanySizeID

			INSERT INTO SearchDB..paSearchCount_2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Region', dcRegionID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcRegionID ORDER BY dcRegionID
			----计算全部地区，2位的数据
			UPDATE a SET a.TitleValue = b.TitleValue
			FROM SearchDB..paSearchCount_2 a WITH(NOLOCK), 
			(SELECT LEFT(TitleID, 2) TitleID, SUM(TitleValue) TitleValue
			FROM SearchDB..paSearchCount_2 WITH(NOLOCK)
			WHERE paSearchConditionID = @paSearchConditionID AND Title = 'Region'
			GROUP BY LEFT(TitleID, 2)) b
			WHERE a.TitleId = b.TitleID
			AND a.paSearchConditionID = @paSearchConditionID AND a.Title = 'Region'
			----计算全部地区，4位的数据
			UPDATE a SET a.TitleValue = b.TitleValue
			FROM SearchDB..paSearchCount_2 a WITH(NOLOCK), (
				SELECT LEFT(TitleID, 4) TitleID, SUM(TitleValue) TitleValue
				FROM SearchDB..paSearchCount_2 WITH(NOLOCK)
				WHERE paSearchConditionID = @paSearchConditionID AND Title = 'Region'
				AND LEN(TitleID) >3
				GROUP BY LEFT(TitleID, 4)) b
			WHERE a.TitleId = b.TitleID
			AND a.paSearchConditionID = @paSearchConditionID AND a.Title = 'Region'

			INSERT INTO SearchDB..paSearchCount_2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Education', dcEducationID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcEducationID ORDER BY dcEducationID
			--学历 高中、中专、中级合并		
			SELECT @TitleValue = SUM(TitleValue) FROM SearchDB..paSearchCount_2 WITH(NOLOCK)
			WHERE paSearchConditionID = @paSearchConditionID
			AND Title = 'Education' AND TitleID IN(2, 3, 4)		
			IF @TitleValue IS NOT NULL
			BEGIN
				IF EXISTS(SELECT 'X' FROM SearchDB..paSearchCount_2 WITH(NOLOCK) WHERE paSearchConditionID = @paSearchConditionID AND Title = 'Education' AND TitleID = 2)
					UPDATE SearchDB..paSearchCount_2 SET TitleValue = @TitleValue 
					WHERE paSearchConditionID = @paSearchConditionID
					AND Title = 'Education' AND TitleID = 2
				ELSE
					INSERT INTO SearchDB..paSearchCount_2(paSearchConditionID, Title, TitleId, TitleValue) VALUES
					(@paSearchConditionID, 'Education', 2, @TitleValue)

				DELETE FROM SearchDB..paSearchCount_2
				WHERE paSearchConditionID = @paSearchConditionID
				AND Title = 'Education' AND TitleID IN(3, 4)
			END 

			INSERT INTO SearchDB..paSearchCount_2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Experience', MinExperience, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY MinExperience ORDER BY MinExperience
			
/*			----写入TitleDesc
			UPDATE a SET a.TitleDesc = b.Description
			FROM SearchDB..paSearchCount_2 a WITH(NOLOCK), dcEducation b WITH(NOLOCK)
			WHERE a.TitleID = b.ID AND a.paSearchConditionID = @paSearchConditionID
			AND a.Title = 'Education'
			
			UPDATE a SET a.TitleDesc = b.Description
			FROM SearchDB..paSearchCount_2 a WITH(NOLOCK), dcRegion b WITH(NOLOCK)
			WHERE a.TitleID = b.ID AND a.paSearchConditionID = @paSearchConditionID
			AND a.Title = 'Region'

			UPDATE a SET a.TitleDesc = b.Description
			FROM SearchDB..paSearchCount_2 a WITH(NOLOCK), dcJobType b WITH(NOLOCK)
			WHERE a.TitleID = b.ID AND a.paSearchConditionID = @paSearchConditionID
			AND a.Title = 'JobType'

			UPDATE a SET a.TitleDesc = b.Description
			FROM SearchDB..paSearchCount_2 a WITH(NOLOCK), dcSalary b WITH(NOLOCK)
			WHERE a.TitleID = b.ID AND a.paSearchConditionID = @paSearchConditionID
			AND a.Title = 'Salary'

			UPDATE a SET a.TitleDesc = b.Description
			FROM SearchDB..paSearchCount_2 a WITH(NOLOCK), dcCompanySize b WITH(NOLOCK)
			WHERE a.TitleID = b.ID AND a.paSearchConditionID = @paSearchConditionID
			AND a.Title = 'CompanySize'

			UPDATE a SET a.TitleDesc = b.Description
			FROM SearchDB..paSearchCount_2 a WITH(NOLOCK), dcCompanySize b WITH(NOLOCK)
			WHERE a.TitleID = b.ID AND a.paSearchConditionID = @paSearchConditionID
			AND a.Title = 'CompanySize'
			
			UPDATE SearchDB..paSearchCount_2 SET TitleDesc = 
			CASE TitleID
				WHEN 0 THEN '不限'
				WHEN 1 THEN '1~2年'
				WHEN 2 THEN '3~5年'
				WHEN 3 THEN '6~10年'
				WHEN 4 THEN '10年以上'
				WHEN 5 THEN '应届毕业生'
			END
			WHERE paSearchConditionID = @paSearchConditionID
			AND Title = 'Experience'

			UPDATE SearchDB..paSearchCount_2 SET TitleDesc = 
			CASE TitleID
				WHEN 1 THEN '全职'
				WHEN 3 THEN '兼职'
				WHEN 4 THEN '实习'
			END
			WHERE paSearchConditionID = @paSearchConditionID
			AND Title = 'EmployType'
*/
			INSERT INTO SearchDB..paSearchJobID_2(paSearchConditionID, JobId, IsTop)
			SELECT Top 3 @paSearchConditionID, a.JobId, 1 
			FROM SearchJobTop a WITH(NOLOCK), (SELECT TOP 2000 ID FROM #Job WITH(NOLOCK)) b 
			WHERE b.ID = a.JobId ORDER BY a.OpenDate DESC
			SET @TopRows = @@ROWCOUNT

			INSERT INTO SearchDB..paSearchJobID_2(paSearchConditionID, JobId, IsTop)
			SELECT TOP 2000 @paSearchConditionID, ID, 0 FROM #Job WITH(NOLOCK)
			SET @AllRows = @@ROWCOUNT

			IF @TopRows = 0 AND @AllRows > 100
				UPDATE SearchDB..paSearchJobID_2 SET IsTop = 1 
				WHERE paSearchConditionID = @paSearchConditionID
				AND ID IN (SELECT TOP 3 ID FROM SearchDB..paSearchJobID_2 WITH(NOLOCK) WHERE paSearchConditionID = @paSearchConditionID)
		END
		ELSE IF (@TableId = 3)
		BEGIN
			--IF LEN(@dcJobTypeID) IN(2, 4)
				INSERT INTO SearchDB..paSearchCount_3(paSearchConditionID, Title, TitleId, TitleValue)
				SELECT @paSearchConditionID, 'JobType', dcJobTypeID, COUNT(*) FROM #Job WITH(NOLOCK)
			--	WHERE dcJobTypeID LIKE @dcJobTypeID + '%'
			--	OR dcJobTypeIDMinor LIKE @dcJobTypeID + '%'
				GROUP BY dcJobTypeID ORDER BY dcJobTypeID
			--ELSE
			--	INSERT INTO SearchDB..paSearchCount_3(paSearchConditionID, Title, TitleId, TitleValue)
			--	SELECT @paSearchConditionID, 'JobType', dcJobTypeID, COUNT(*) FROM #Job WITH(NOLOCK)
			--	GROUP BY dcJobTypeID ORDER BY dcJobTypeID

			----计算全部某职位类别，2, 4位的数据
			UPDATE a SET a.TitleValue = b.TitleValue
			FROM SearchDB..paSearchCount_3 a WITH(NOLOCK), 
			(SELECT LEFT(TitleID, 2) TitleID, SUM(TitleValue) TitleValue
			FROM SearchDB..paSearchCount_3 WITH(NOLOCK)
			WHERE paSearchConditionID = @paSearchConditionID AND Title = 'JobType'
			GROUP BY LEFT(TitleID, 2)) b
			WHERE a.TitleId = b.TitleID
			AND a.paSearchConditionID = @paSearchConditionID AND a.Title = 'JobType'			
			
			INSERT INTO SearchDB..paSearchCount_3(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Salary', dcSalaryID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcSalaryID ORDER BY dcSalaryID

			INSERT INTO SearchDB..paSearchCount_3(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'EmployType', EmployType, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY EmployType ORDER BY EmployType

			INSERT INTO SearchDB..paSearchCount_3(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'CompanySize', dcCompanySizeID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcCompanySizeID ORDER BY dcCompanySizeID

			INSERT INTO SearchDB..paSearchCount_3(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Region', dcRegionID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcRegionID ORDER BY dcRegionID
			----计算全部地区，2位的数据
			UPDATE a SET a.TitleValue = b.TitleValue
			FROM SearchDB..paSearchCount_3 a WITH(NOLOCK), 
			(SELECT LEFT(TitleID, 2) TitleID, SUM(TitleValue) TitleValue
			FROM SearchDB..paSearchCount_3 WITH(NOLOCK)
			WHERE paSearchConditionID = @paSearchConditionID AND Title = 'Region'
			GROUP BY LEFT(TitleID, 2)) b
			WHERE a.TitleId = b.TitleID
			AND a.paSearchConditionID = @paSearchConditionID AND a.Title = 'Region'
			----计算全部地区，4位的数据
			UPDATE a SET a.TitleValue = b.TitleValue
			FROM SearchDB..paSearchCount_3 a WITH(NOLOCK), (
				SELECT LEFT(TitleID, 4) TitleID, SUM(TitleValue) TitleValue
				FROM SearchDB..paSearchCount_3 WITH(NOLOCK)
				WHERE paSearchConditionID = @paSearchConditionID AND Title = 'Region'
				AND LEN(TitleID) >3
				GROUP BY LEFT(TitleID, 4)) b
			WHERE a.TitleId = b.TitleID
			AND a.paSearchConditionID = @paSearchConditionID AND a.Title = 'Region'

			INSERT INTO SearchDB..paSearchCount_3(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Education', dcEducationID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcEducationID ORDER BY dcEducationID
			--学历 高中、中专、中级合并		
			SELECT @TitleValue = SUM(TitleValue) FROM SearchDB..paSearchCount_3 WITH(NOLOCK)
			WHERE paSearchConditionID = @paSearchConditionID
			AND Title = 'Education' AND TitleID IN(2, 3, 4)		
			IF @TitleValue IS NOT NULL
			BEGIN
				IF EXISTS(SELECT 'X' FROM SearchDB..paSearchCount_3 WITH(NOLOCK) WHERE paSearchConditionID = @paSearchConditionID AND Title = 'Education' AND TitleID = 2)
					UPDATE SearchDB..paSearchCount_3 SET TitleValue = @TitleValue 
					WHERE paSearchConditionID = @paSearchConditionID
					AND Title = 'Education' AND TitleID = 2
				ELSE
					INSERT INTO SearchDB..paSearchCount_3(paSearchConditionID, Title, TitleId, TitleValue) VALUES
					(@paSearchConditionID, 'Education', 2, @TitleValue)

				DELETE FROM SearchDB..paSearchCount_3
				WHERE paSearchConditionID = @paSearchConditionID
				AND Title = 'Education' AND TitleID IN(3, 4)
			END 


			INSERT INTO SearchDB..paSearchCount_3(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Experience', MinExperience, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY MinExperience ORDER BY MinExperience
/*			----写入TitleDesc
			UPDATE a SET a.TitleDesc = b.Description
			FROM SearchDB..paSearchCount_3 a WITH(NOLOCK), dcEducation b WITH(NOLOCK)
			WHERE a.TitleID = b.ID AND a.paSearchConditionID = @paSearchConditionID
			AND a.Title = 'Education'
			
			UPDATE a SET a.TitleDesc = b.Description
			FROM SearchDB..paSearchCount_3 a WITH(NOLOCK), dcRegion b WITH(NOLOCK)
			WHERE a.TitleID = b.ID AND a.paSearchConditionID = @paSearchConditionID
			AND a.Title = 'Region'

			UPDATE a SET a.TitleDesc = b.Description
			FROM SearchDB..paSearchCount_3 a WITH(NOLOCK), dcJobType b WITH(NOLOCK)
			WHERE a.TitleID = b.ID AND a.paSearchConditionID = @paSearchConditionID
			AND a.Title = 'JobType'

			UPDATE a SET a.TitleDesc = b.Description
			FROM SearchDB..paSearchCount_3 a WITH(NOLOCK), dcSalary b WITH(NOLOCK)
			WHERE a.TitleID = b.ID AND a.paSearchConditionID = @paSearchConditionID
			AND a.Title = 'Salary'

			UPDATE a SET a.TitleDesc = b.Description
			FROM SearchDB..paSearchCount_3 a WITH(NOLOCK), dcCompanySize b WITH(NOLOCK)
			WHERE a.TitleID = b.ID AND a.paSearchConditionID = @paSearchConditionID
			AND a.Title = 'CompanySize'

			UPDATE a SET a.TitleDesc = b.Description
			FROM SearchDB..paSearchCount_3 a WITH(NOLOCK), dcCompanySize b WITH(NOLOCK)
			WHERE a.TitleID = b.ID AND a.paSearchConditionID = @paSearchConditionID
			AND a.Title = 'CompanySize'
			
			UPDATE SearchDB..paSearchCount_3 SET TitleDesc = 
			CASE TitleID
				WHEN 0 THEN '不限'
				WHEN 1 THEN '1~2年'
				WHEN 2 THEN '3~5年'
				WHEN 3 THEN '6~10年'
				WHEN 4 THEN '10年以上'
				WHEN 5 THEN '应届毕业生'
			END
			WHERE paSearchConditionID = @paSearchConditionID
			AND Title = 'Experience'

			UPDATE SearchDB..paSearchCount_3 SET TitleDesc = 
			CASE TitleID
				WHEN 1 THEN '全职'
				WHEN 3 THEN '兼职'
				WHEN 4 THEN '实习'
			END
			WHERE paSearchConditionID = @paSearchConditionID
			AND Title = 'EmployType'
*/
			INSERT INTO SearchDB..paSearchJobID_3(paSearchConditionID, JobId, IsTop)
			SELECT Top 3 @paSearchConditionID, a.JobId, 1 
			FROM SearchJobTop a WITH(NOLOCK), (SELECT TOP 2000 ID FROM #Job WITH(NOLOCK)) b 
			WHERE b.ID = a.JobId ORDER BY a.OpenDate DESC
			SET @TopRows = @@ROWCOUNT

			INSERT INTO SearchDB..paSearchJobID_3(paSearchConditionID, JobId, IsTop)
			SELECT TOP 2000 @paSearchConditionID, ID, 0 FROM #Job WITH(NOLOCK)
			SET @AllRows = @@ROWCOUNT

			IF @TopRows = 0 AND @AllRows > 100
				UPDATE SearchDB..paSearchJobID_3 SET IsTop = 1 
				WHERE paSearchConditionID = @paSearchConditionID
				AND ID IN (SELECT TOP 3 ID FROM SearchDB..paSearchJobID_3 WITH(NOLOCK) WHERE paSearchConditionID = @paSearchConditionID)
		END
		DROP TABLE #Job
		--PRINT 'DROP #JOB  ' + CONVERT(VARCHAR(30), GETDATE(), 121)
	COMMIT
	--GOTO GetRecordSet

	GetRecordSet:
	BEGIN
		----返回查询数量
		SELECT ValidJobNumber FROM SearchDB..paSearchCondition WITH(NOLOCK) WHERE ID=@paSearchConditionID
		UPDATE SearchDB..paSearchCondition SET ReuseNumber = ReuseNumber + 1 WHERE ID=@paSearchConditionID
		----返回20行查询结果
		IF (@TableID = 0)
		BEGIN
			SELECT @MinId = MIN(ID) FROM SearchDB..paSearchJobID_0 WITH(NOLOCK) WHERE paSearchConditionID=@paSearchConditionID

			SET @MinId = @MinId+(@PageNumber-1)*@PageSize
			SELECT TOP 30 a.ID, a.cpMainID, a.caMainID, a.Name as JobName, a.dcJobTypeID, 
				a.dcJobTypeIDMinor, a.NeedNumber, a.dcSalaryID, a.EmployType, 
				a.dcRegionID, a.Responsibility, a.Demand, a.dcEducationID, 
				a.MinExperience, a.MinAge, a.MaxAge, a.IssueDate, a.IssueEND, 
				a.IsDelete, a.AddDate, a.RefreshDate,  a.Welfare1,a.Welfare2,a.Welfare3,
				a.Welfare4,a.Welfare5,a.Welfare6,a.Welfare7,a.Welfare8,
				a.Welfare9,a.Welfare10,a.Welfare11,a.Welfare12,a.Welfare13,
				a.Welfare14,a.Welfare15,a.Welfare16,a.Welfare17,a.Welfare18,a.SecondId EnJobID,b.SecondId EnCpMainID,
				a.LastModifyDate, b.Name as cpName, b.dcCompanySizeID, 
				b.HasLicence, b.UnLimitedDate, b.BalanceDate, b.Balance, 
				b.MemberType, '' cpIndustry, --STUFF((SELECT ','+LTRIM(x.dcIndustryid)+',c'+LTRIM(isnull(y.Category,0)) FROM cpIndustry x,dcIndustry y WHERE x.dcIndustryid = y.id AND x.cpMainid = b.id FOR XML PATH('')),1,1,'') cpIndustry,
				c.IsTop, b.IsRefreshed, d.IsOnline, d.IsVi, d.ViPlanId, d.InterviewDate			
			FROM JobPublish a WITH(NOLOCK)
			INNER JOIN cpMainPublish b WITH(NOLOCK) ON a.cpMainID = b.ID 
			INNER JOIN SearchDB..paSearchJobID_0 c WITH(NOLOCK) ON a.id = c.JobID
			LEFT JOIN caOnline d WITH(NOLOCK) ON a.caMainId = d.caMainId
			WHERE paSearchConditionID=@paSearchConditionID 
			AND c.ID >= @MinId
			ORDER BY c.ID, a.ID DESC
		END
		ELSE IF (@TableID = 1)
		BEGIN
			SELECT @MinId = MIN(ID) FROM SearchDB..paSearchJobID_1 WITH(NOLOCK) WHERE paSearchConditionID=@paSearchConditionID

			SET @MinId = @MinId+(@PageNumber-1)*@PageSize
			SELECT TOP 30 a.ID, a.cpMainID, a.caMainID, a.Name as JobName, a.dcJobTypeID, 
				a.dcJobTypeIDMinor, a.NeedNumber, a.dcSalaryID, a.EmployType, 
				a.dcRegionID, a.Responsibility, a.Demand, a.dcEducationID, 
				a.MinExperience, a.MinAge, a.MaxAge, a.IssueDate, a.IssueEND, 
				a.IsDelete, a.AddDate, a.RefreshDate, a.Welfare1, a.Welfare2, a.Welfare3,
				a.Welfare4, a.Welfare5, a.Welfare6, a.Welfare7, a.Welfare8,
				a.Welfare9, a.Welfare10, a.Welfare11, a.Welfare12, a.Welfare13,
				a.Welfare14, a.Welfare15, a.Welfare16, a.Welfare17, a.Welfare18, 
				a.SecondId EnJobID, b.SecondId EnCpMainID,
				a.LastModifyDate, b.Name cpName, b.dcCompanySizeID, 
				b.HasLicence, b.UnLimitedDate, b.BalanceDate, b.Balance, 
				b.MemberType, '' cpIndustry, --STUFF((SELECT ','+LTRIM(x.dcIndustryid)+',c'+LTRIM(isnull(y.Category,0)) FROM cpIndustry x,dcIndustry y WHERE x.dcIndustryid = y.id AND x.cpMainid = b.id FOR XML PATH('')),1,1,'') cpIndustry,
				c.IsTop, b.IsRefreshed, d.IsOnline, d.IsVi, d.ViPlanId, d.InterviewDate			
			FROM JobPublish a WITH(NOLOCK)
			INNER JOIN cpMainPublish b WITH(NOLOCK) ON a.cpMainID = b.ID 
			INNER JOIN SearchDB..paSearchJobID_1 c WITH(NOLOCK) ON a.id = c.JobID
			LEFT JOIN caOnline d WITH(NOLOCK) ON a.caMainId = d.caMainId
			WHERE paSearchConditionID=@paSearchConditionID 
			AND c.ID >= @MinId
			ORDER BY c.ID, a.ID DESC
		END
		ELSE IF (@TableID = 2)
		BEGIN
			SELECT @MinId = MIN(ID) FROM SearchDB..paSearchJobID_2 WITH(NOLOCK) WHERE paSearchConditionID=@paSearchConditionID

			SET @MinId = @MinId+(@PageNumber-1)*@PageSize
			SELECT TOP 30 a.ID, a.cpMainID, a.caMainID, a.Name as JobName, a.dcJobTypeID, 
				a.dcJobTypeIDMinor, a.NeedNumber, a.dcSalaryID, a.EmployType, 
				a.dcRegionID, a.Responsibility, a.Demand, a.dcEducationID, 
				a.MinExperience, a.MinAge, a.MaxAge, a.IssueDate, a.IssueEND, 
				a.IsDelete, a.AddDate, a.RefreshDate, a.Welfare1, a.Welfare2, a.Welfare3,
				a.Welfare4, a.Welfare5, a.Welfare6, a.Welfare7, a.Welfare8,
				a.Welfare9, a.Welfare10, a.Welfare11, a.Welfare12, a.Welfare13,
				a.Welfare14, a.Welfare15, a.Welfare16, a.Welfare17, a.Welfare18,
				a.SecondId EnJobID, b.SecondId EnCpMainID, 
				a.LastModifyDate, b.Name cpName, b.dcCompanySizeID, 
				b.HasLicence, b.UnLimitedDate, b.BalanceDate, b.Balance, 
				b.MemberType, '' cpIndustry, --STUFF((SELECT ','+LTRIM(x.dcIndustryid)+',c'+LTRIM(isnull(y.Category,0)) FROM cpIndustry x,dcIndustry y WHERE x.dcIndustryid = y.id AND x.cpMainid = b.id FOR XML PATH('')),1,1,'') cpIndustry,
				c.IsTop, b.IsRefreshed, d.IsOnline, d.IsVi, d.ViPlanId, d.InterviewDate			
			FROM JobPublish a WITH(NOLOCK)
			INNER JOIN cpMainPublish b WITH(NOLOCK) ON a.cpMainID = b.ID 
			INNER JOIN SearchDB..paSearchJobID_2 c WITH(NOLOCK) ON a.id = c.JobID
			LEFT JOIN caOnline d WITH(NOLOCK) ON a.caMainId = d.caMainId
			WHERE paSearchConditionID=@paSearchConditionID 
			AND c.ID >= @MinId
			ORDER BY c.ID, a.ID DESC
		END
		ELSE IF (@TableID = 3)
		BEGIN
			SELECT @MinId = MIN(ID) FROM SearchDB..paSearchJobID_3 WITH(NOLOCK) WHERE paSearchConditionID=@paSearchConditionID

			SET @MinId = @MinId+(@PageNumber-1)*@PageSize
			SELECT TOP 30 a.ID, a.cpMainID, a.caMainID, a.Name as JobName, a.dcJobTypeID, 
				a.dcJobTypeIDMinor, a.NeedNumber, a.dcSalaryID, a.EmployType, 
				a.dcRegionID, a.Responsibility, a.Demand, a.dcEducationID, 
				a.MinExperience, a.MinAge, a.MaxAge, a.IssueDate, a.IssueEND, 
				a.IsDelete, a.AddDate, a.RefreshDate, a.Welfare1, a.Welfare2, a.Welfare3,
				a.Welfare4, a.Welfare5, a.Welfare6, a.Welfare7, a.Welfare8,
				a.Welfare9, a.Welfare10, a.Welfare11, a.Welfare12, a.Welfare13,
				a.Welfare14, a.Welfare15, a.Welfare16, a.Welfare17, a.Welfare18,
				a.SecondId EnJobID, b.SecondId EnCpMainID, 
				a.LastModifyDate, b.Name cpName, b.dcCompanySizeID, 
				b.HasLicence, b.UnLimitedDate, b.BalanceDate, b.Balance, 
				b.MemberType, '' cpIndustry, --STUFF((SELECT ',' + LTRIM(x.dcIndustryid) + ',c' + LTRIM(isnull(y.Category,0)) FROM cpIndustry x,dcIndustry y WHERE x.dcIndustryid = y.id AND x.cpMainid = b.id FOR XML PATH('')),1,1,'') cpIndustry,
				c.IsTop, b.IsRefreshed, d.IsOnline, d.IsVi, d.ViPlanId, d.InterviewDate			
			FROM JobPublish a WITH(NOLOCK)
			INNER JOIN cpMainPublish b WITH(NOLOCK) ON a.cpMainID = b.ID 
			INNER JOIN SearchDB..paSearchJobID_3 c WITH(NOLOCK) ON a.id = c.JobID
			LEFT JOIN caOnline d WITH(NOLOCK) ON a.caMainId = d.caMainId
			WHERE paSearchConditionID=@paSearchConditionID 
			AND c.ID >= @MinId
			ORDER BY c.ID, a.ID DESC
		END
        --RICHARD 2011-7-23 16:51分修改
		----返回统计数量
		IF @Type=1
		BEGIN
			DECLARE @RegionCount AS INT
			SELECT @RegionCount = -1
			IF CHARINDEX(',', @dcRegionID) = 0 AND LEN(@dcRegionID) > 0
			BEGIN
				IF NOT LEFT(@dcRegionID,1) = 'p'
					SELECT @RegionCount = COUNT(*) FROM dcRegion WHERE ParentID = @dcRegionID
			END
			IF (@TableID = 0)
			BEGIN
				SELECT * FROM SearchDB..paSearchCount_0 WITH(NOLOCK) WHERE Title = 'JobType' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(VARCHAR(10), TitleID)
				IF @RegionCount = 0
					SELECT * FROM dcMapPlace WITH(NOLOCK) WHERE dcRegionID = @dcRegionID
				ELSE
					SELECT * FROM SearchDB..paSearchCount_0 WITH(NOLOCK) WHERE Title = 'Region' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(VARCHAR(10), TitleID)
				SELECT * FROM SearchDB..paSearchCount_0 WITH(NOLOCK) WHERE Title = 'Education' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT * FROM SearchDB..paSearchCount_0 WITH(NOLOCK) WHERE Title = 'Experience' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT * FROM SearchDB..paSearchCount_0 WITH(NOLOCK) WHERE Title = 'Salary' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT * FROM SearchDB..paSearchCount_0 WITH(NOLOCK) WHERE Title = 'EmployType' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT * FROM SearchDB..paSearchCount_0 WITH(NOLOCK) WHERE Title = 'CompanySize' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
			END
			IF (@TableID = 1)
			BEGIN
				SELECT * FROM SearchDB..paSearchCount_1 WITH(NOLOCK) WHERE Title = 'JobType' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(VARCHAR(10), TitleID)
				IF @RegionCount = 0
					SELECT * FROM dcMapPlace WITH(NOLOCK) WHERE dcRegionID = @dcRegionID
				ELSE
					SELECT * FROM SearchDB..paSearchCount_1 WITH(NOLOCK) WHERE Title = 'Region' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(VARCHAR(10), TitleID)
				SELECT * FROM SearchDB..paSearchCount_1 WITH(NOLOCK) WHERE Title = 'Education' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT * FROM SearchDB..paSearchCount_1 WITH(NOLOCK) WHERE Title = 'Experience' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT * FROM SearchDB..paSearchCount_1 WITH(NOLOCK) WHERE Title = 'Salary' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT * FROM SearchDB..paSearchCount_1 WITH(NOLOCK) WHERE Title = 'EmployType' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT * FROM SearchDB..paSearchCount_1 WITH(NOLOCK) WHERE Title = 'CompanySize' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
			END
			IF (@TableID = 2)
			BEGIN
				SELECT * FROM SearchDB..paSearchCount_2 WITH(NOLOCK) WHERE Title = 'JobType' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(VARCHAR(10), TitleID)
				IF @RegionCount = 0
					SELECT * FROM dcMapPlace WITH(NOLOCK) WHERE dcRegionID = @dcRegionID
				ELSE
					SELECT * FROM SearchDB..paSearchCount_2 WITH(NOLOCK) WHERE Title = 'Region' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(VARCHAR(10), TitleID)
				SELECT * FROM SearchDB..paSearchCount_2 WITH(NOLOCK) WHERE Title = 'Education' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT * FROM SearchDB..paSearchCount_2 WITH(NOLOCK) WHERE Title = 'Experience' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT * FROM SearchDB..paSearchCount_2 WITH(NOLOCK) WHERE Title = 'Salary' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT * FROM SearchDB..paSearchCount_2 WITH(NOLOCK) WHERE Title = 'EmployType' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT * FROM SearchDB..paSearchCount_2 WITH(NOLOCK) WHERE Title = 'CompanySize' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
			END
			IF (@TableID = 3)
			BEGIN
				SELECT * FROM SearchDB..paSearchCount_3 WITH(NOLOCK) WHERE Title = 'JobType' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(VARCHAR(10), TitleID)
				IF @RegionCount = 0
					SELECT * FROM dcMapPlace WITH(NOLOCK) WHERE dcRegionID = @dcRegionID
				ELSE
					SELECT * FROM SearchDB..paSearchCount_3 WITH(NOLOCK) WHERE Title = 'Region' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(VARCHAR(10), TitleID)
				SELECT * FROM SearchDB..paSearchCount_3 WITH(NOLOCK) WHERE Title = 'Education' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT * FROM SearchDB..paSearchCount_3 WITH(NOLOCK) WHERE Title = 'Experience' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT * FROM SearchDB..paSearchCount_3 WITH(NOLOCK) WHERE Title = 'Salary' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT * FROM SearchDB..paSearchCount_3 WITH(NOLOCK) WHERE Title = 'EmployType' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT * FROM SearchDB..paSearchCount_3 WITH(NOLOCK) WHERE Title = 'CompanySize' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
			END
		END
		RETURN
	END
END TRY
BEGIN CATCH
	---检查是否已经建立临时表，已经建立则删除
	PRINT 'error'
	PRINT error_Message()
	PRINT error_number()
	PRINT error_line()
END CATCH



GO
/****** Object:  StoredProcedure [dbo].[pcJobBySimilarSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[pcJobBySimilarSelect]
(  
	@dcJobTypeID VARCHAR(6),
	@dcRegionID VARCHAR(6),
	@JobId INT  
)  
AS
SET NOCOUNT ON
BEGIN
	DECLARE @SecondId VARCHAR(12)
	SELECT @SecondId = SecondId
	FROM JobPublish WITH(NOLOCK)
	WHERE ID = @JobID

	IF @SecondId IS NULL
		SELECT @SecondId = ''

	IF @dcRegionID LIKE '32%'
		SET @dcRegionID = '30'
		
	SELECT TOP 10 *    
	FROM (
		SELECT TOP 50 NeedNumber, JobName, a.ID, cpMainID, cpName, SubSiteUrl, 
			b.FullName, dcSalaryID, dcSalaryIDMax, LastLoginDate
		FROM JobSimilar a WITH(NOLOCK INDEX(IX_JobSimilar_Complex)),
			dcRegion b WITH(NOLOCK)    
		WHERE a.dcRegionID = b.ID
		AND dcJobTypeID LIKE @dcJobTypeID + '%'
		AND dcRegionID LIKE @dcRegionID + '%'
		) a
	WHERE ID <> @SecondId   
	ORDER BY NEWID()
END

GO
/****** Object:  StoredProcedure [dbo].[pcJobByZhaopinSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[pcJobByZhaopinSelect] 
(
	@dcJobTypeID VARCHAR(100),		--职位类别
	@dcRegionID VARCHAR(100),		--求职地区
	@dcIndustryID VARCHAR(100),		--求职行业
	@dcSalaryID TINYINT,			--月薪
	@IsNegotiable BIT,				--1允许面议，不面议
	@MinExperience TINYINT,			--工作经验，100为未选择
	@dcEducationID TINYINT,			--最低学历
	@EmployType VARCHAR(10),		--工作性质，1全职；3兼职；4实习，
	@KeyWord NVARCHAR(10),			--关键词
	@KeyType TINYINT,				--关键词类别，0无；1-全文；2-职位；3-公司 
	@ORDER VARCHAR(100),			--显示顺序，没有用
	@RefreshNo INT,					--1,1天内；2,3天内；3，一周内；4，15天内；5，一个月内；6超过一个月
	@Type INT,						--1：主动搜索  点击搜索按钮 10分钟，翻页60分钟有效；0：翻页搜索，不刷新
	@PageNumber INT,				--翻页页码
	@SessionID VARCHAR(50)
)
AS
--return @SessionId = 16
SET NOCOUNT ON
INSERT INTO SearchIp(Ip, Source) SELECT @SessionId, 'z'
IF EXISTS(SELECT 'x' FROM RefuseIp WITH(NOLOCK) WHERE CHARINDEX(Ip,@SessionId) > 0)
BEGIN
	SELECT 0 ValidJobNumber
	SELECT TOP 0 * FROM JobTemp
	SELECT TOP 0 * FROM SearchDB..paSearchCount_0
	SELECT TOP 0 * FROM SearchDB..paSearchCount_0
	SELECT TOP 0 * FROM SearchDB..paSearchCount_0
	SELECT TOP 0 * FROM SearchDB..paSearchCount_0
	SELECT TOP 0 * FROM SearchDB..paSearchCount_0
	SELECT TOP 0 * FROM SearchDB..paSearchCount_0
	SELECT TOP 0 * FROM SearchDB..paSearchCount_0
	RETURN
END
SET @SessionId = 30
BEGIN TRY
	BEGIN
		----给null值变量赋默认值
		SELECT @dcJobTypeID = dbo.FormatIDS(@dcJobTypeID),
			@dcRegionID = dbo.FormatIDS(@dcRegionID),
			@dcIndustryID = dbo.FormatIDS(@dcIndustryID)
		IF @dcSalaryID IS NULL
			SET @dcSalaryID = 0
		IF @MinExperience IS NULL
			SET @MinExperience = 100
		IF @dcEducationID IS NULL
			SET @dcEducationID = 0
		IF @EmployType IS NULL
			SET @EmployType = ''
		IF @EmployType = '2'
			SET @EmployType = '1,3'	
		IF @ORDER IS NULL
			SET @ORDER = ''
		SET @ORDER = dbo.SafeSQL(@ORDER)
		--@RefreshNo = 0选择全部数据，不限制时间
		DECLARE @dcProvinceId INT
		IF ISNULL(@RefreshNo, 0) > 9
			SELECT @dcProvinceId = @RefreshNo
		ELSE
			SELECT @dcProvinceId = 0

		IF @Type IS NULL
			SET @Type = 0
		IF @PageNumber IS NULL
			SET @PageNumber = 0
		
		IF(ISNULL(@dcJobTypeID, '') = '' AND ISNULL(@dcRegionID, '') = '' AND ISNULL(@dcIndustryID, '') = '')
			RETURN

		DECLARE @paSearchConditionID AS INT, @MinId AS INT, @PageSize AS TINYINT, @TableID AS TINYINT

		SELECT @paSearchConditionID = 0, @PageSize = 50

		----搜索2分钟的数据
		SELECT TOP 1 @paSearchConditionID = ID 
		FROM SearchDB..paSearchCondition WITH(NOLOCK)
		WHERE JobType=@dcJobTypeID AND JobPlace=@dcRegionID AND Industry=@dcIndustryID
		AND Education=@dcEducationID AND Experience=@MinExperience AND Salary=@dcSalaryID
		AND EmployType=@EmployType AND KeyWord='' AND CompanySizeID = 0
		AND Welfare = '' AND IsOnline=0 AND dcProvinceId = @dcProvinceId
		AND LogTime > DATEADD(MINUTE, -1, GETDATE()) AND ReuseNumber > 0
		ORDER BY ID DESC
	
		IF ISNULL(@paSearchConditionID, 0) = 0
		BEGIN
			SET @Type =1
			GOTO SelectReset	--无数据，重新搜索
		END
		ELSE
		BEGIN
			SELECT @TableID = @paSearchConditionID % 4
			GOTO GetRecordSet	--从临时结果中提取数据
		END
	END

SelectReset:				--从job中搜索数据
	BEGIN TRAN
		DECLARE @SQL AS VARCHAR(8000)
		DECLARE @WHERE AS VARCHAR(8000)
		DECLARE @FROM AS VARCHAR(1000)
		----记录查询条件
		INSERT INTO SearchDB..paSearchCondition(SessionID, LogTime, JobType, JobPlace, Industry, Education, Experience, 
			Salary, IsNegotiable, EmployType, KeyWord, KeyType, ReuseNumber, CompanySizeID, dcProvinceId)
		SELECT @SessionId, GETDATE(), @dcJobTypeID, @dcRegionID, @dcIndustryID, @dcEducationID, @MinExperience, 
			@dcSalaryID, @IsNegotiable, @EmployType, '', 0, 0, 0, @dcProvinceId

		SET @paSearchConditionID = @@IDENTITY
		SELECT @TableID = @paSearchConditionID % 4

		------生成职位类别的表变量，因为职位类别有包含（父子）关系
		DECLARE @T_JobPlace AS TABLE(ID INT)
		DECLARE @T_JobType AS TABLE(ID INT)
		DECLARE @JobType AS VARCHAR(3000)
		DECLARE @JobPlace AS VARCHAR(2000)
		DECLARE @ValidJobNumber AS INT
		DECLARE @JobPlaceLen AS INT, @JobTypeLen AS INT
		IF CHARINDEX(',', @dcJobTypeID) > 0
			SET @JobTypeLen = -1
		ELSE
			SET @JobTypeLen = LEN(@dcJobTypeID)
		SELECT @JobPlace = '', @JobType=''
		----生成工作地点的表变量
		IF LEN(@dcRegionID) > 0
		BEGIN
			INSERT INTO @T_JobPlace
			SELECT * FROM dbo.fnSplit(@dcRegionID, ',')
			SELECT @JobPlace = (@JobPlace + ' OR a.dcRegionID Like ''' + LTRIM(STR(ID) + '%''')) FROM @T_JobPlace
			IF LEN(@JobPlace) > 0
				SET @JobPlace = RIGHT(@JobPlace, LEN(@JobPlace) -4)
			IF (SELECT COUNT(*) FROM @T_JobPlace) > 1
				SET @JobPlaceLen = -1
			ELSE
				SET @JobPlaceLen = LEN(@dcRegionID)
		END

		----生成求聘职位的表变量
		IF LEN(@dcJobTypeID) > 0
		BEGIN
			DECLARE @T_Temp AS TABLE(ID INT)		--临时表，用于构建组合查询语句
			INSERT INTO @T_Temp
			SELECT * FROM dbo.fnSplit(@dcJobTypeID, ',')

			INSERT INTO @T_JobType
			SELECT DISTINCT ID FROM dcJobType WITH(NOLOCK)
			WHERE ParentId IN(SELECT ID FROM @T_TEMP) 
			OR ParentId2 in(SELECT ID FROM @T_TEMP)
			OR ID IN(SELECT ID FROM @T_TEMP)
			----生成in字符串
			SELECT @JobType = (@JobType + LTRIM(STR(ID) + ',')) FROM @T_JobType
			IF RIGHT(@JobType, 1) = ','
				SET @JobType = LEFT(@JobType, LEN(@JobType) - 1)
		END

		----建立临时表
		CREATE TABLE #Job(
			RowID INT IDENTITY(1, 1),
			ID INT NOT NULL, 
			cpMainId INT,
			dcJobTypeID SMALLINT NOT NULL,
			dcJobTypeIDMinor SMALLINT NULL,
			dcSalaryID TINYINT NOT NULL,
			dcRegionID VARCHAR(6) NULL,
			dcEducationID TINYINT NOT NULL,
			MinExperience TINYINT NOT NULL,
			RefreshDate SMALLDATETIME NULL,
			EmployType TINYINT NULL,
			dcCompanySizeID SMALLINT NULL
		)
		------刷新时间，根据刷新时间编号计算
		----生成插入临时表的Sql语句
		SET @SQL='
			INSERT INTO #Job
			SELECT a.ID, a.cpMainId, a.dcJobTypeID, a.dcJobTypeIDMinor, a.dcSalaryID,
				a.dcRegionID, a.dcEducationID, a.MinExperience, a.IssueDate, a.EmployType, b.dcCompanySizeID'
		SET @FROM = '
			FROM JobPublish a WITH(NOLOCK)
			INNER JOIN cpMainPublish b WITH(NOLOCK) ON a.cpMainID=b.ID'
		----职位有效，单位新有效
		IF LEN(@dcIndustryID) > 0
			SET @WHERE = '
			WHERE b.ID IN (SELECT cpMainID FROM cpIndustry WHERE dcIndustryId in(' + @dcIndustryID + '))
			AND a.Valid = 1
			AND b.Valid = 1'
		ELSE
			SET @WHERE = '
			WHERE a.Valid = 1
			AND b.Valid = 1'
		IF @dcProvinceId > 0
			SET @WHERE = @WHERE + ' AND b.dcProvinceId = ' + LTRIM(STR(@dcProvinceId))
		----职位类别
		IF LEN(@dcJobTypeID) > 0
			SET @WHERE = @WHERE + '
			AND (a.dcJobTypeID IN(' + @JobType +')
				OR a.dcJobTypeIDMinor IN(' +@JobType + '))'
		IF LEN(@JobPlace) > 0 
			SET @WHERE = @WHERE + '
			AND (' + @JobPlace + ')'

		IF @dcSalaryID > 0
		BEGIN
			IF @dcSalaryID < 100				----从form中搜索，月薪跨2个级别,是本级和上级别的薪金
			BEGIN
				SET @WHERE = @WHERE + '
			AND a.dcSalaryID IN(' + LTRIM(STR(@dcSalaryID)) + ', ' + LTRIM(STR(@dcSalaryID + 1))
				IF @IsNegotiable = 1		--包括面议
					SET @WHERE = @WHERE + ', 100'
				SET @WHERE = @WHERE + ')'
			END
			IF @dcSalaryID = 100	----从筛选结果中点击面议，值是100
			BEGIN
				SET @WHERE = @WHERE + '
			AND a.dcSalaryID = 100'
			END
			IF @dcSalaryID > 100	----从筛选结果中点击搜索，月薪只有1个级别，传值时增加100
				SET @WHERE = @WHERE + '
			AND a.dcSalaryID=' + LTRIM(STR(@dcSalaryID-100))
		END
		----工作经验要求
		IF @MinExperience < 100
		SET @WHERE = @WHERE + ' 
			AND a.MinExperience = ' + LTRIM(STR(@MinExperience))

		----学历要求
		----'1初中','2\3\4高中、中技、中专','5大专','6本科','7硕士','8博士
		IF @dcEducationID > 0
			IF @dcEducationID = 2
				SET @WHERE = @WHERE + '
			AND a.dcEducationID IN(2,3,4)'
			ELSE
				SET @WHERE = @WHERE + '
			AND a.dcEducationID = ' + LTRIM(STR(@dcEducationID))
		----1、全职；3、兼职；4实习。	2、全职/兼职 职位中无此项
		IF LEN(@EmployType) > 0
			SET @WHERE = @WHERE + '
			AND a.EmployType IN (' + @EmployType + ')'
		SET @SQL = @SQL + @FROM + @WHERE
		
		--IF LEN(@ORDER)>0
		SET @SQL=@SQL + ' ORDER BY a.RefreshDate DESC, a.SecondID'
		--原来是ORDER BY a.IssueDate DESC, a.ID，Richard 2011年11月23日17：06分修改

		----把符合条件的职位全部列出
		--PRINT @SQL
		EXEC(@SQL)
		
		SET @ValidJobNumber = @@ROWCOUNT
		----记录查询结果总数
		UPDATE SearchDB..paSearchCondition SET ValidJobNumber=@ValidJobNumber, SQl=@SQL WHERE ID=@paSearchConditionID
	
		DECLARE @TitleValue AS INT, @TopRows AS INT, @AllRows AS INT
		DECLARE @sc AS TABLE (
			paSearchConditionID int,
			Title varchar(20),
			TitleID varchar(10),
			TitleValue int
		)
		DECLARE @sc2 AS TABLE (
			paSearchConditionID int,
			Title varchar(20),
			TitleID varchar(10),
			TitleValue int
		)
		----插入JobType数据
		IF (@TableID = 0)
		BEGIN
			----------------------------jobtype
			INSERT INTO @sc2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'JobType', dcJobTypeID, COUNT(*)
			FROM #Job WITH(NOLOCK)
			GROUP BY dcJobTypeID ORDER BY dcJobTypeID			

			----计算全部某职位类别，2, 4位的数据
			IF @JobTypeLen NOT IN(2, 4)
			BEGIN
				INSERT INTO @Sc(paSearchConditionID, Title, TitleId, TitleValue)
				SELECT  @paSearchConditionID, 'JobType', LEFT(TitleID, 2) TitleID, SUM(TitleValue) TitleValue 
				FROM @sc2 GROUP BY LEFT(TitleID, 2)
			END
			IF @JobTypeLen NOT IN(0, 4)
			BEGIN
				INSERT INTO @Sc(paSearchConditionID, Title, TitleId, TitleValue)
				SELECT  @paSearchConditionID, 'JobType', TitleId, TitleValue
				FROM @sc2 WHERE LEN(TitleId) = 4
			END

			IF @JobTypeLen = -1
				DELETE @sc WHERE TitleID NOT IN(SELECT a FROM dbo.fnSplit(@dcJobTypeID, ','))

			INSERT INTO SearchDB..paSearchCount_0(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT  @paSearchConditionID, 'JobType', TitleId, TitleValue FROM @sc
			DELETE @sc
			DELETE @sc2
			--------------------------region
			INSERT INTO @sc2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Region', dcRegionID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcRegionID ORDER BY dcRegionID
			----计算全部地区，2位的数据
			IF @JobPlaceLen IN(-1, 0)
				INSERT INTO @sc(paSearchConditionID, Title, TitleId, TitleValue)
				SELECT @paSearchConditionID, 'Region', LEFT(TitleID, 2) TitleID, SUM(TitleValue) TitleValue 
				FROM @sc2 GROUP BY LEFT(TitleID, 2)
			IF @JobPlaceLen IN(-1, 2)
				INSERT INTO @sc(paSearchConditionID, Title, TitleId, TitleValue)
				SELECT @paSearchConditionID, 'Region', LEFT(TitleID, 4) TitleID, SUM(TitleValue) TitleValue 
				FROM @sc2 WHERE LEN(TitleID) >= 4 GROUP BY LEFT(TitleID, 4)
			IF @JobPlaceLen IN(-1, 4)
				INSERT INTO @sc(paSearchConditionID, Title, TitleId, TitleValue)
				SELECT @paSearchConditionID, 'Region', TitleID, TitleValue 
				FROM @sc2 WHERE LEN(TitleID) = 6
			IF @JobPlaceLen = -1
				DELETE @sc WHERE TitleID NOT IN(SELECT ID FROM @T_JobPlace)
			ELSE
				DELETE @sc WHERE LEN(TitleID) <> @JobPlaceLen + 2

			INSERT INTO SearchDB..paSearchCount_0(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT paSearchConditionID, Title, TitleId, TitleValue FROM @sc
			----------------------------
			INSERT INTO SearchDB..paSearchCount_0(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'EmployType', EmployType, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY EmployType ORDER BY EmployType

			INSERT INTO SearchDB..paSearchCount_0(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Education', CASE WHEN dcEducationId IN(2, 3, 4) THEN 2 ELSE dcEducationId END, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY CASE WHEN dcEducationId IN(2, 3, 4) THEN 2 ELSE dcEducationId END
			ORDER BY CASE WHEN dcEducationId IN(2, 3, 4) THEN 2 ELSE dcEducationId END

			INSERT INTO SearchDB..paSearchCount_0(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Experience', MinExperience, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY MinExperience ORDER BY MinExperience

			INSERT INTO SearchDB..paSearchCount_0(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'CompanySize', dcCompanySizeID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcCompanySizeID ORDER BY dcCompanySizeID

			INSERT INTO SearchDB..paSearchCount_0(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Salary', dcSalaryID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcSalaryID ORDER BY dcSalaryID

			INSERT INTO SearchDB..paSearchCount_0(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Industry', dcIndustryID, COUNT(*) 
			FROM #Job a WITH(NOLOCK), cpIndustry b WITH(NOLOCK)
			WHERE a.cpMainId = b.cpMainId
			GROUP BY b.dcIndustryId ORDER BY b.dcIndustryId

			INSERT INTO SearchDB..paSearchJobID_0(paSearchConditionId, JobId)
			SELECT TOP 2000 @paSearchConditionID, ID FROM #Job WITH(NOLOCK) ORDER BY RowId
		END
		ELSE IF (@TableId = 1)
		BEGIN
			----------------------------jobtype
			INSERT INTO @sc2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'JobType', dcJobTypeID, COUNT(*)
			FROM #Job WITH(NOLOCK)
			GROUP BY dcJobTypeID ORDER BY dcJobTypeID			

			----计算全部某职位类别，2, 4位的数据
			IF @JobTypeLen NOT IN(2, 4)
			BEGIN
				INSERT INTO @Sc(paSearchConditionID, Title, TitleId, TitleValue)
				SELECT  @paSearchConditionID, 'JobType', LEFT(TitleID, 2) TitleID, SUM(TitleValue) TitleValue 
				FROM @sc2 GROUP BY LEFT(TitleID, 2)
			END
			IF @JobTypeLen NOT IN(0, 4)
			BEGIN
				INSERT INTO @Sc(paSearchConditionID, Title, TitleId, TitleValue)
				SELECT  @paSearchConditionID, 'JobType', TitleId, TitleValue
				FROM @sc2 WHERE LEN(TitleId) = 4
			END

			IF @JobTypeLen = -1
				DELETE @sc WHERE TitleID NOT IN(SELECT a FROM dbo.fnSplit(@dcJobTypeID, ','))

			INSERT INTO SearchDB..paSearchCount_1(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT  @paSearchConditionID, 'JobType', TitleId, TitleValue FROM @sc
			DELETE @sc
			DELETE @sc2
			--------------------------region
			INSERT INTO @sc2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Region', dcRegionID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcRegionID ORDER BY dcRegionID
			----计算全部地区，2位的数据
			IF @JobPlaceLen IN(-1, 0)
				INSERT INTO @sc(paSearchConditionID, Title, TitleId, TitleValue)
				SELECT @paSearchConditionID, 'Region', LEFT(TitleID, 2) TitleID, SUM(TitleValue) TitleValue 
				FROM @sc2 GROUP BY LEFT(TitleID, 2)
			IF @JobPlaceLen IN(-1, 2)
				INSERT INTO @sc(paSearchConditionID, Title, TitleId, TitleValue)
				SELECT @paSearchConditionID, 'Region', LEFT(TitleID, 4) TitleID, SUM(TitleValue) TitleValue 
				FROM @sc2 WHERE LEN(TitleID) >= 4 GROUP BY LEFT(TitleID, 4)
			IF @JobPlaceLen IN(-1, 4)
				INSERT INTO @sc(paSearchConditionID, Title, TitleId, TitleValue)
				SELECT @paSearchConditionID, 'Region', TitleID, TitleValue 
				FROM @sc2 WHERE LEN(TitleID) = 6
			IF @JobPlaceLen = -1
				DELETE @sc WHERE TitleID NOT IN(SELECT ID FROM @T_JobPlace)
			ELSE
				DELETE @sc WHERE LEN(TitleID) <> @JobPlaceLen + 2

			INSERT INTO SearchDB..paSearchCount_1(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT paSearchConditionID, Title, TitleId, TitleValue FROM @sc
			----------------------------
			INSERT INTO SearchDB..paSearchCount_1(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Salary', dcSalaryID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcSalaryID ORDER BY dcSalaryID

			INSERT INTO SearchDB..paSearchCount_1(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Education',  CASE WHEN dcEducationId IN(2, 3, 4) THEN 2 ELSE dcEducationId END, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY CASE WHEN dcEducationId IN(2, 3, 4) THEN 2 ELSE dcEducationId END
			ORDER BY CASE WHEN dcEducationId IN(2, 3, 4) THEN 2 ELSE dcEducationId END
			
			INSERT INTO SearchDB..paSearchCount_1(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Experience', MinExperience, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY MinExperience ORDER BY MinExperience

			INSERT INTO SearchDB..paSearchCount_1(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'EmployType', EmployType, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY EmployType ORDER BY EmployType

			INSERT INTO SearchDB..paSearchCount_1(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'CompanySize', dcCompanySizeID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcCompanySizeID ORDER BY dcCompanySizeID

			INSERT INTO SearchDB..paSearchCount_1(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Industry', dcIndustryID, COUNT(*) 
			FROM #Job a WITH(NOLOCK), cpIndustry b WITH(NOLOCK)
			WHERE a.cpMainId = b.cpMainId
			GROUP BY dcIndustryID ORDER BY dcIndustryID

			INSERT INTO SearchDB..paSearchJobID_1(paSearchConditionId, JobId)
			SELECT TOP 2000 @paSearchConditionID, ID FROM #Job WITH(NOLOCK) ORDER BY RowId
		END
		ELSE IF (@TableId = 2)
		BEGIN
			----------------------------jobtype
			INSERT INTO @sc2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'JobType', dcJobTypeID, COUNT(*)
			FROM #Job WITH(NOLOCK)
			GROUP BY dcJobTypeID ORDER BY dcJobTypeID			

			----计算全部某职位类别，2, 4位的数据
			IF @JobTypeLen NOT IN(2, 4)
			BEGIN
				INSERT INTO @Sc(paSearchConditionID, Title, TitleId, TitleValue)
				SELECT  @paSearchConditionID, 'JobType', LEFT(TitleID, 2) TitleID, SUM(TitleValue) TitleValue 
				FROM @sc2 GROUP BY LEFT(TitleID, 2)
			END
			IF @JobTypeLen NOT IN(0, 4)
			BEGIN
				INSERT INTO @Sc(paSearchConditionID, Title, TitleId, TitleValue)
				SELECT  @paSearchConditionID, 'JobType', TitleId, TitleValue
				FROM @sc2 WHERE LEN(TitleId) = 4
			END

			IF @JobTypeLen = -1
				DELETE @sc WHERE TitleID NOT IN(SELECT a FROM dbo.fnSplit(@dcJobTypeID, ','))

			INSERT INTO SearchDB..paSearchCount_2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT  @paSearchConditionID, 'JobType', TitleId, TitleValue FROM @sc
			DELETE @sc
			DELETE @sc2
			--------------------------region
			INSERT INTO @sc2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Region', dcRegionID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcRegionID ORDER BY dcRegionID
			----计算全部地区，2位的数据
			IF @JobPlaceLen IN(-1, 0)
				INSERT INTO @sc(paSearchConditionID, Title, TitleId, TitleValue)
				SELECT @paSearchConditionID, 'Region', LEFT(TitleID, 2) TitleID, SUM(TitleValue) TitleValue 
				FROM @sc2 GROUP BY LEFT(TitleID, 2)
			IF @JobPlaceLen IN(-1, 2)
				INSERT INTO @sc(paSearchConditionID, Title, TitleId, TitleValue)
				SELECT @paSearchConditionID, 'Region', LEFT(TitleID, 4) TitleID, SUM(TitleValue) TitleValue 
				FROM @sc2 WHERE LEN(TitleID) >= 4 GROUP BY LEFT(TitleID, 4)
			IF @JobPlaceLen IN(-1, 4)
				INSERT INTO @sc(paSearchConditionID, Title, TitleId, TitleValue)
				SELECT @paSearchConditionID, 'Region', TitleID, TitleValue 
				FROM @sc2 WHERE LEN(TitleID) = 6
			IF @JobPlaceLen = -1
				DELETE @sc WHERE TitleID NOT IN(SELECT ID FROM @T_JobPlace)
			ELSE
				DELETE @sc WHERE LEN(TitleID) <> @JobPlaceLen + 2

			INSERT INTO SearchDB..paSearchCount_2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT paSearchConditionID, Title, TitleId, TitleValue FROM @sc
			----------------------------
			INSERT INTO SearchDB..paSearchCount_2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Salary', dcSalaryID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcSalaryID ORDER BY dcSalaryID

			INSERT INTO SearchDB..paSearchCount_2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Education', CASE WHEN dcEducationId IN(2, 3, 4) THEN 2 ELSE dcEducationId END, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY CASE WHEN dcEducationId IN(2, 3, 4) THEN 2 ELSE dcEducationId END
			ORDER BY CASE WHEN dcEducationId IN(2, 3, 4) THEN 2 ELSE dcEducationId END
			
			INSERT INTO SearchDB..paSearchCount_2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Experience', MinExperience, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY MinExperience ORDER BY MinExperience

			INSERT INTO SearchDB..paSearchCount_2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'EmployType', EmployType, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY EmployType ORDER BY EmployType

			INSERT INTO SearchDB..paSearchCount_2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'CompanySize', dcCompanySizeID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcCompanySizeID ORDER BY dcCompanySizeID

			INSERT INTO SearchDB..paSearchCount_2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Industry', dcIndustryID, COUNT(*) 
			FROM #Job a WITH(NOLOCK), cpIndustry b WITH(NOLOCK)
			WHERE a.cpMainId = b.cpMainId
			GROUP BY dcIndustryID ORDER BY dcIndustryID

			INSERT INTO SearchDB..paSearchJobID_2(paSearchConditionId, JobId)
			SELECT TOP 2000 @paSearchConditionID, ID FROM #Job WITH(NOLOCK) ORDER BY RowId
		END
		ELSE IF (@TableId = 3)
		BEGIN
			----------------------------jobtype
			INSERT INTO @sc2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'JobType', dcJobTypeID, COUNT(*)
			FROM #Job WITH(NOLOCK)
			GROUP BY dcJobTypeID ORDER BY dcJobTypeID			

			----计算全部某职位类别，2, 4位的数据
			IF @JobTypeLen NOT IN(2, 4)
			BEGIN
				INSERT INTO @Sc(paSearchConditionID, Title, TitleId, TitleValue)
				SELECT  @paSearchConditionID, 'JobType', LEFT(TitleID, 2) TitleID, SUM(TitleValue) TitleValue 
				FROM @sc2 GROUP BY LEFT(TitleID, 2)
			END
			IF @JobTypeLen NOT IN(0, 4)
			BEGIN
				INSERT INTO @Sc(paSearchConditionID, Title, TitleId, TitleValue)
				SELECT  @paSearchConditionID, 'JobType', TitleId, TitleValue
				FROM @sc2 WHERE LEN(TitleId) = 4
			END

			IF @JobTypeLen = -1
				DELETE @sc WHERE TitleID NOT IN(SELECT a FROM dbo.fnSplit(@dcJobTypeID, ','))

			INSERT INTO SearchDB..paSearchCount_3(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT  @paSearchConditionID, 'JobType', TitleId, TitleValue FROM @sc
			DELETE @sc
			DELETE @sc2
			--------------------------region
			INSERT INTO @sc2(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Region', dcRegionID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcRegionID ORDER BY dcRegionID
			----计算全部地区，2位的数据
			IF @JobPlaceLen IN(-1, 0)
				INSERT INTO @sc(paSearchConditionID, Title, TitleId, TitleValue)
				SELECT @paSearchConditionID, 'Region', LEFT(TitleID, 2) TitleID, SUM(TitleValue) TitleValue 
				FROM @sc2 GROUP BY LEFT(TitleID, 2)
			IF @JobPlaceLen IN(-1, 2)
				INSERT INTO @sc(paSearchConditionID, Title, TitleId, TitleValue)
				SELECT @paSearchConditionID, 'Region', LEFT(TitleID, 4) TitleID, SUM(TitleValue) TitleValue 
				FROM @sc2 WHERE LEN(TitleID) >= 4 GROUP BY LEFT(TitleID, 4)
			IF @JobPlaceLen IN(-1, 4)
				INSERT INTO @sc(paSearchConditionID, Title, TitleId, TitleValue)
				SELECT @paSearchConditionID, 'Region', TitleID, TitleValue 
				FROM @sc2 WHERE LEN(TitleID) = 6
			IF @JobPlaceLen = -1
				DELETE @sc WHERE TitleID NOT IN(SELECT ID FROM @T_JobPlace)
			ELSE
				DELETE @sc WHERE LEN(TitleID) <> @JobPlaceLen + 2

			INSERT INTO SearchDB..paSearchCount_3(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT paSearchConditionID, Title, TitleId, TitleValue FROM @sc
			----------------------------
			INSERT INTO SearchDB..paSearchCount_3(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Salary', dcSalaryID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcSalaryID ORDER BY dcSalaryID

			INSERT INTO SearchDB..paSearchCount_3(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Education', CASE WHEN dcEducationId IN(2, 3, 4) THEN 2 ELSE dcEducationId END, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY CASE WHEN dcEducationId IN(2, 3, 4) THEN 2 ELSE dcEducationId END
			ORDER BY CASE WHEN dcEducationId IN(2, 3, 4) THEN 2 ELSE dcEducationId END
			
			INSERT INTO SearchDB..paSearchCount_3(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Experience', MinExperience, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY MinExperience ORDER BY MinExperience

			INSERT INTO SearchDB..paSearchCount_3(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'EmployType', EmployType, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY EmployType ORDER BY EmployType

			INSERT INTO SearchDB..paSearchCount_3(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'CompanySize', dcCompanySizeID, COUNT(*) FROM #Job WITH(NOLOCK)
			GROUP BY dcCompanySizeID ORDER BY dcCompanySizeID

			INSERT INTO SearchDB..paSearchCount_3(paSearchConditionID, Title, TitleId, TitleValue)
			SELECT @paSearchConditionID, 'Industry', dcIndustryID, COUNT(*) 
			FROM #Job a WITH(NOLOCK), cpIndustry b WITH(NOLOCK)
			WHERE a.cpMainId = b.cpMainId
			GROUP BY dcIndustryID ORDER BY dcIndustryID

			INSERT INTO SearchDB..paSearchJobID_3(paSearchConditionId, JobId)
			SELECT TOP 2000 @paSearchConditionID, ID FROM #Job WITH(NOLOCK) ORDER BY RowId
		END
		DROP TABLE #Job
		--PRINT 'DROP #Job  ' + CONVERT(VARCHAR(30), GETDATE(), 121)
	COMMIT
	--GOTO GetRecordSet

GetRecordSet:
	BEGIN
		----返回查询数量
		SELECT ValidJobNumber FROM SearchDB..paSearchCondition WITH(NOLOCK) WHERE ID=@paSearchConditionID
		UPDATE SearchDB..paSearchCondition SET ReuseNumber = ReuseNumber + 1 WHERE ID=@paSearchConditionID
		----返回20行查询结果
		IF (@TableID = 0)
		BEGIN
			SELECT @MinId = MIN(ID)FROM SearchDB..paSearchJobID_0 WITH(NOLOCK) WHERE paSearchConditionID=@paSearchConditionID

			SET @MinId = @MinId+(@PageNumber-1)*@PageSize
			SELECT top 50 a.ID,a.cpMainID,a.caMainID,a.Name as JobName,a.dcJobTypeID,
				a.dcJobTypeIDMinor,a.NeedNumber,a.dcSalaryID, a.dcSalaryIDMax, a.EmployType,
				a.dcRegionID,a.Responsibility,a.Demand,a.dcEducationID,
				a.MinExperience,a.MinAge,a.MaxAge,a.IssueDate,a.IssueEND,
				a.IsDelete,a.AddDate,a.RefreshDate,
				a.LastModifyDate,b.Name as cpName, b.dcCompanySizeID,
				b.HasLicence,b.UnLimitedDate,b.BalanceDate,b.Balance,
				b.MemberType, a.SecondId EnJobID, b.SecondId EnCpMainID,a.Welfare1,a.Welfare2,a.Welfare3,
				a.Welfare4,a.Welfare5,a.Welfare6,a.Welfare7,a.Welfare8,
				a.Welfare9,a.Welfare10,a.Welfare11,a.Welfare12,a.Welfare13,
				a.Welfare14,a.Welfare15,a.Welfare16,a.Welfare17,a.Welfare18,a.Welfare19,
				dbo.GetCaOnlineStatus(a.caMainID) IsOnline, CASE WHEN b.ReplyRate >= 0.6 THEN b.ReplyRate ELSE NULL END Replyrate, b.RealName
			FROM JobPublish a WITH(NOLOCK),cpMainPublish b WITH(NOLOCK),SearchDB..paSearchJobID_0 c WITH(NOLOCK)
			WHERE a.cpMainID = b.ID and a.id=c.JobID and c.paSearchConditionID=@paSearchConditionID 
				  AND c.ID>=@MinId ORDER BY c.ID,a.ID DESC
		END
		ELSE IF (@TableID = 1)
		BEGIN
			SELECT @MinId = MIN(ID)FROM SearchDB..paSearchJobID_1 WITH(NOLOCK) WHERE paSearchConditionID=@paSearchConditionID

			SET @MinId = @MinId+(@PageNumber-1)*@PageSize
			SELECT top 50 a.ID,a.cpMainID,a.caMainID,a.Name as JobName,a.dcJobTypeID,
				a.dcJobTypeIDMinor,a.NeedNumber,a.dcSalaryID, a.dcSalaryIDMax, a.EmployType,
				a.dcRegionID,a.Responsibility,a.Demand,a.dcEducationID,
				a.MinExperience,a.MinAge,a.MaxAge,a.IssueDate,a.IssueEND,
				a.IsDelete, a.AddDate,a.RefreshDate,
				a.LastModifyDate,b.Name as cpName,b.dcCompanySizeID,
				b.HasLicence,b.UnLimitedDate,b.BalanceDate,b.Balance,
				b.MemberType, a.SecondId EnJobID, b.SecondId EnCpMainID,a.Welfare1,a.Welfare2,a.Welfare3,
				a.Welfare4,a.Welfare5,a.Welfare6,a.Welfare7,a.Welfare8,
				a.Welfare9,a.Welfare10,a.Welfare11,a.Welfare12,a.Welfare13,
				a.Welfare14,a.Welfare15,a.Welfare16,a.Welfare17,a.Welfare18,a.Welfare19,
				dbo.GetCaOnlineStatus(a.caMainID) IsOnline, CASE WHEN b.ReplyRate >= 0.6 THEN b.ReplyRate ELSE NULL END Replyrate, b.RealName
			FROM JobPublish a WITH(NOLOCK),cpMainPublish b WITH(NOLOCK),SearchDB..paSearchJobID_1 c WITH(NOLOCK)
			WHERE a.cpMainID = b.ID and a.id=c.JobID and c.paSearchConditionID=@paSearchConditionID 
				  AND c.ID>=@MinId ORDER BY c.ID,a.ID DESC
		END
		ELSE IF (@TableID = 2)
		BEGIN
			SELECT @MinId = MIN(ID)FROM SearchDB..paSearchJobID_2 WITH(NOLOCK) WHERE paSearchConditionID=@paSearchConditionID

			SET @MinId = @MinId+(@PageNumber-1)*@PageSize
			SELECT top 50 a.ID,a.cpMainID,a.caMainID,a.Name as JobName,a.dcJobTypeID,
				a.dcJobTypeIDMinor,a.NeedNumber,a.dcSalaryID, a.dcSalaryIDMax, a.EmployType,
				a.dcRegionID,a.Responsibility,a.Demand,a.dcEducationID,
				a.MinExperience,a.MinAge,a.MaxAge,a.IssueDate,a.IssueEND,
				a.IsDelete, a.AddDate,a.RefreshDate,
				a.LastModifyDate,b.Name as cpName,b.dcCompanySizeID,
				b.HasLicence,b.UnLimitedDate,b.BalanceDate,b.Balance,
				b.MemberType, a.SecondId EnJobID, b.SecondId EnCpMainID,a.Welfare1,a.Welfare2,a.Welfare3,
				a.Welfare4,a.Welfare5,a.Welfare6,a.Welfare7,a.Welfare8,
				a.Welfare9,a.Welfare10,a.Welfare11,a.Welfare12,a.Welfare13,
				a.Welfare14,a.Welfare15,a.Welfare16,a.Welfare17,a.Welfare18,a.Welfare19,
				dbo.GetCaOnlineStatus(a.caMainID) IsOnline, CASE WHEN b.ReplyRate >= 0.6 THEN b.ReplyRate ELSE NULL END Replyrate, b.RealName
			FROM JobPublish a WITH(NOLOCK),cpMainPublish b WITH(NOLOCK),SearchDB..paSearchJobID_2 c WITH(NOLOCK)
			WHERE a.cpMainID = b.ID and a.id=c.JobID and c.paSearchConditionID=@paSearchConditionID 
				  AND c.ID>=@MinId ORDER BY c.ID,a.ID DESC
		END
		ELSE IF (@TableID = 3)
		BEGIN
			SELECT @MinId = MIN(ID)FROM SearchDB..paSearchJobID_3 WITH(NOLOCK) WHERE paSearchConditionID=@paSearchConditionID

			SET @MinId = @MinId+(@PageNumber-1)*@PageSize
			SELECT top 50 a.ID,a.cpMainID,a.caMainID,a.Name as JobName,a.dcJobTypeID,
				a.dcJobTypeIDMinor,a.NeedNumber,a.dcSalaryID, a.dcSalaryIDMax, a.EmployType,
				a.dcRegionID,a.Responsibility,a.Demand,a.dcEducationID,
				a.MinExperience,a.MinAge,a.MaxAge,a.IssueDate,a.IssueEND,
				a.IsDelete, a.AddDate,a.RefreshDate,
				a.LastModifyDate,b.Name as cpName,b.dcCompanySizeID,
				b.HasLicence,b.UnLimitedDate,b.BalanceDate,b.Balance,
				b.MemberType, a.SecondId EnJobID, b.SecondId EnCpMainID,a.Welfare1,a.Welfare2,a.Welfare3,
				a.Welfare4,a.Welfare5,a.Welfare6,a.Welfare7,a.Welfare8,
				a.Welfare9,a.Welfare10,a.Welfare11,a.Welfare12,a.Welfare13,
				a.Welfare14,a.Welfare15,a.Welfare16,a.Welfare17,a.Welfare18,a.Welfare19,
				dbo.GetCaOnlineStatus(a.caMainID) IsOnline, CASE WHEN b.ReplyRate >= 0.6 THEN b.ReplyRate ELSE NULL END Replyrate, b.RealName
			FROM JobPublish a WITH(NOLOCK),cpMainPublish b WITH(NOLOCK),SearchDB..paSearchJobID_3 c WITH(NOLOCK)
			WHERE a.cpMainID = b.ID and a.id=c.JobID and c.paSearchConditionID=@paSearchConditionID 
				  AND c.ID>=@MinId ORDER BY c.ID,a.ID DESC
		END
        --RICHARD 2011-7-23 16:51分修改
		----返回统计数量
		IF @Type=1
			IF (@TableID = 0)
			BEGIN
				SELECT * FROM SearchDB..paSearchCount_0 WITH(NOLOCK) WHERE Title = 'JobType' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(VARCHAR(10), TitleID)
				SELECT * FROM SearchDB..paSearchCount_0 WITH(NOLOCK) WHERE Title = 'Region' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(VARCHAR(10), TitleID)
				SELECT * FROM SearchDB..paSearchCount_0 WITH(NOLOCK) WHERE Title = 'Education' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT * FROM SearchDB..paSearchCount_0 WITH(NOLOCK) WHERE Title = 'Experience' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT * FROM SearchDB..paSearchCount_0 WITH(NOLOCK) WHERE Title = 'Salary' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT * FROM SearchDB..paSearchCount_0 WITH(NOLOCK) WHERE Title = 'EmployType' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT * FROM SearchDB..paSearchCount_0 WITH(NOLOCK) WHERE Title = 'CompanySize' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)

			END
			IF (@TableID = 1)
			BEGIN
				SELECT * FROM SearchDB..paSearchCount_1 WITH(NOLOCK) WHERE Title = 'JobType' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(VARCHAR(10), TitleID)
				SELECT * FROM SearchDB..paSearchCount_1 WITH(NOLOCK) WHERE Title = 'Region' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(VARCHAR(10), TitleID)
				SELECT * FROM SearchDB..paSearchCount_1 WITH(NOLOCK) WHERE Title = 'Education' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT * FROM SearchDB..paSearchCount_1 WITH(NOLOCK) WHERE Title = 'Experience' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT * FROM SearchDB..paSearchCount_1 WITH(NOLOCK) WHERE Title = 'Salary' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT * FROM SearchDB..paSearchCount_1 WITH(NOLOCK) WHERE Title = 'EmployType' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT * FROM SearchDB..paSearchCount_1 WITH(NOLOCK) WHERE Title = 'CompanySize' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
			END
			IF (@TableID = 2)
			BEGIN
				SELECT * FROM SearchDB..paSearchCount_2 WITH(NOLOCK) WHERE Title = 'JobType' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(VARCHAR(10), TitleID)
				SELECT * FROM SearchDB..paSearchCount_2 WITH(NOLOCK) WHERE Title = 'Region' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(VARCHAR(10), TitleID)
				SELECT * FROM SearchDB..paSearchCount_2 WITH(NOLOCK) WHERE Title = 'Education' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT * FROM SearchDB..paSearchCount_2 WITH(NOLOCK) WHERE Title = 'Experience' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT * FROM SearchDB..paSearchCount_2 WITH(NOLOCK) WHERE Title = 'Salary' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT * FROM SearchDB..paSearchCount_2 WITH(NOLOCK) WHERE Title = 'EmployType' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT * FROM SearchDB..paSearchCount_2 WITH(NOLOCK) WHERE Title = 'CompanySize' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
			END
			IF (@TableID = 3)
			BEGIN
				SELECT * FROM SearchDB..paSearchCount_3 WITH(NOLOCK) WHERE Title = 'JobType' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(VARCHAR(10), TitleID)
				SELECT * FROM SearchDB..paSearchCount_3 WITH(NOLOCK) WHERE Title = 'Region' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(VARCHAR(10), TitleID)
				SELECT * FROM SearchDB..paSearchCount_3 WITH(NOLOCK) WHERE Title = 'Education' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT * FROM SearchDB..paSearchCount_3 WITH(NOLOCK) WHERE Title = 'Experience' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT * FROM SearchDB..paSearchCount_3 WITH(NOLOCK) WHERE Title = 'Salary' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT * FROM SearchDB..paSearchCount_3 WITH(NOLOCK) WHERE Title = 'EmployType' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
				SELECT * FROM SearchDB..paSearchCount_3 WITH(NOLOCK) WHERE Title = 'CompanySize' AND paSearchConditionID=@paSearchConditionID ORDER BY Title, CONVERT(INT, TitleID)
			END
		RETURN
	END
END TRY
BEGIN CATCH
	---检查是否已经建立临时表，已经建立则删除
		DECLARE @para VARCHAR(MAX)
	SET @para = '@dcJobTypeID=' + ISNULL(@dcJobTypeID, '') + '|' +
		'@dcRegionID=' + ISNULL(@dcRegionID, '') + '|' +
		'@dcIndustryID=' + ISNULL(@dcIndustryID, '') + '|' +
		'@EmployType=' + ISNULL(@EmployType, '') + '|' +
		'@KeyWord=' + ISNULL(@KeyWord, '') + '|' +
		'@ORDER=' + ISNULL(@ORDER, '') + '|' +
		'@SessionID=' + ISNULL(@SessionID, '')
	INSERT INTO ErrorLog	
	SELECT 'p2 ' +ISNULL(error_Message(), ' no msg')+ ' para=' + ISNULL(@Para, 'no para ') + ISNULL(@SQL, ' no sql'), error_number(), error_line(), GETDATE()
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[pcJobIntentionSave]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =  = 
-- 检查:		Sean
-- 日期:		2010-9-29
-- 描述:		保存求职意向		执行pcCvMainByCvLevelUpdate，取消中英文判断
-- 修改：Lambo，2010-11-25
-- 描述：增加了paMainID参数，判断是否是本人的
-- = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =  = 
CREATE PROCEDURE [dbo].[pcJobIntentionSave]
(
	@cvMainID INT, 
	@RelatedWorkYears TINYINT, 
	@EmployType TINYINT, 
	@dcSalaryID TINYINT, 
	@IsNegotiable TINYINT, 
	@JobType VARCHAR(100), 
	@JobPlace VARCHAR(100), 
	@Industry VARCHAR(100), 
	@paMainID INT
)
AS
SET NOCOUNT ON
BEGIN
	IF @cvMainID IS NULL
		RETURN 0
	IF @paMainID IS NULL
		RETURN 0
	IF @RelatedWorkYears IS NULL
		RETURN 0
	IF @EmployType IS NULL
		RETURN 0
	IF @dcSalaryID IS NULL
		RETURN 0
	IF @JobType IS NULL
		RETURN 0
	IF @JobPlace IS NULL
		RETURN 0

	IF NOT EXISTS(SELECT 'x' FROM cvMain WITH(NOLOCK) WHERE ID = @cvMainID AND paMainID = @paMainID)
		RETURN 0

	DECLARE @i INT, @Name AS VARCHAR(100), @JobType1 AS VARCHAR(10), @JobPlace1 AS VARCHAR(10)
 
	DELETE FROM cvJobType WHERE cvMainID = @cvMainID
	SET @i = CHARINDEX(' ', @JobType)
	WHILE @i >= 1
	BEGIN
		IF LEFT(@JobType, @i-1) > ''
		BEGIN
			INSERT cvJobType(cvMainID, dcJobTypeID) VALUES(@cvMainID, LEFT(@JobType, @i-1))
			IF @JobType1 IS NULL
				SET @JobType1 = LEFT(@JobType, @i-1)
		END
		SET @JobType = SUBSTRING(@JobType, @i+1, LEN(@JobType)-@i)
		SET @i = CHARINDEX(' ', @JobType)
	END

	IF @JobType > ''
	BEGIN
		INSERT cvJobType(cvMainID, dcJobTypeID) VALUES(@cvMainID, @JobType)
		IF @JobType1 IS NULL
			SET @JobType1 = @JobType
	END

	DELETE FROM cvJobPlace WHERE cvMainID = @cvMainID
	SET @i = CHARINDEX(' ', @JobPlace)
	WHILE @i >= 1
	BEGIN
		IF LEFT(@JobPlace, @i-1) > '' 
		BEGIN
			INSERT cvJobPlace(cvMainID, dcRegionID) VALUES(@cvMainID, LEFT(@JobPlace, @i-1))
			IF @JobPlace1 IS NULL
				SET @JobPlace1 = LEFT(@JobPlace, @i-1)
		END
		SET @JobPlace = SUBSTRING(@JobPlace, @i+1, LEN(@JobPlace)-@i)
		SET @i = CHARINDEX(' ', @JobPlace)
	END
	IF @JobPlace > ''
	BEGIN
		INSERT cvJobPlace(cvMainID, dcRegionID) VALUES(@cvMainID, @JobPlace)
		IF @JobPlace1 IS NULL
			SET @JobPlace1 = @JobPlace
	END

	DELETE FROM cvIndustry WHERE cvMainID = @cvMainID
	SET @i = CHARINDEX(' ', @Industry)
	WHILE @i >= 1
	BEGIN
		IF LEFT(@Industry, @i-1) > '' 
		INSERT cvIndustry(cvMainID, dcIndustryID) VALUES(@cvMainID, LEFT(@Industry, @i-1))
		SET @Industry = SUBSTRING(@Industry, @i+1, LEN(@Industry)-@i)
		SET @i = CHARINDEX(' ', @Industry)
	END
	IF @Industry > '' 
		INSERT cvIndustry(cvMainID, dcIndustryID) VALUES(@cvMainID, @Industry)

	SELECT @Name = Name FROM cvMain WITH(NOLOCK) WHERE ID = @cvMainID
	IF(ISNULL(@Name, '未完成简历') = '未完成简历')
	BEGIN
		SELECT @Name = Description FROM dcRegion WITH(NOLOCK) WHERE ID = @JobPlace1
		SELECT @Name = @Name + '+' + Description FROM dcJobType WITH(NOLOCK) WHERE ID = @JobType1
		
		IF (@RelatedWorkYears = 0 AND NOT EXISTS(SELECT 'x' FROM cvExperience WITH(NOLOCK) WHERE cvMainId = @cvMainId))
		BEGIN
			UPDATE cvMain SET Name = @Name,
				RelatedWorkYears = @RelatedWorkYears, 
				EmployType = @EmployType, 
				dcSalaryID = @dcSalaryID, 
				IsNegotiable = @IsNegotiable,
				cvType = 1
			WHERE ID = @cvMainID

			DECLARE @EXECSQL AS VARCHAR(100)	
			SET @EXECSQL = 	'EXEC pcCvMainByCvLevelUpdateNew 0, ' + LTRIM(STR(@cvMainID)) + ', 4, 1'
			EXEC(@EXECSQL)
			SET @EXECSQL = 	'EXEC pcCvMainByCvLevelUpdateNew 1, ' + LTRIM(STR(@cvMainID)) + ', 4, 1'
			EXEC(@EXECSQL)
		END
		ELSE
			UPDATE cvMain SET Name = @Name,
				RelatedWorkYears = @RelatedWorkYears, 
				EmployType = @EmployType, 
				dcSalaryID = @dcSalaryID, 
				IsNegotiable = @IsNegotiable
			WHERE ID = @cvMainID
	END
	ELSE
	BEGIN
		UPDATE cvMain SET RelatedWorkYears = @RelatedWorkYears, 
			EmployType = @EmployType, 
			dcSalaryID = @dcSalaryID, IsNegotiable = @IsNegotiable
		WHERE ID = @cvMainID
	END

	DECLARE @SQL AS VARCHAR(100)
	SET @SQL = 'EXEC pcCvMainByCvLevelUpdateNew 0, ' + LTRIM(STR(@cvMainID)) + ', 6, 1'
	EXEC(@SQL)
	SET @SQL = 'EXEC pcCvMainByCvLevelUpdateNew 1, ' + LTRIM(STR(@cvMainID)) + ', 6, 1'
	EXEC(@SQL)

	RETURN 1	 
END

 
				
GO
/****** Object:  StoredProcedure [dbo].[pcJobSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[pcJobSelect]
    @ID INT
AS
BEGIN
    SELECT *
    FROM Job WITH(NOLOCK)
    WHERE ID = @ID And Valid = 1
END














GO
/****** Object:  StoredProcedure [dbo].[pcMapPlaceSelectByRegionID]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[pcMapPlaceSelectByRegionID]
(
	@dcRegionID VARCHAR(6)
)
AS
BEGIN
	IF LEN(@dcRegionID) = 6
	BEGIN
		IF EXISTS(SELECT TOP 1 'X' FROM dcMapPlace WHERE dcRegionID = @dcRegionID)
			SELECT * FROM dcMapPlace WHERE dcRegionID = @dcRegionID ORDER BY OrderNo
		ELSE
			SELECT * FROM dcMapPlace WHERE dcRegionID = LEFT(@dcRegionID,4) ORDER BY OrderNo
	END
	ELSE IF LEN(@dcRegionID) = 4
	BEGIN
		IF EXISTS(SELECT TOP 1 'X' FROM dcMapPlace WHERE dcRegionID = @dcRegionID)
			SELECT * FROM dcMapPlace WHERE dcRegionID = @dcRegionID ORDER BY OrderNo
		ELSE IF EXISTS(SELECT TOP 1 'X' FROM dcMapPlace WHERE dcRegionID LIKE @dcRegionID + '%' AND IsHot = 1)
			SELECT * FROM dcMapPlace WHERE dcRegionID LIKE @dcRegionID + '%' AND IsHot = 1
		ELSE
			SELECT * FROM dcMapPlace WHERE dcRegionID = LEFT(@dcRegionID,2) ORDER BY OrderNo
	END
	ELSE
	BEGIN
		IF EXISTS(SELECT TOP 1 'X' FROM dcMapPlace WHERE dcRegionID = @dcRegionID)
			SELECT * FROM dcMapPlace WHERE dcRegionID = @dcRegionID ORDER BY OrderNo
		ELSE
			SELECT * FROM dcMapPlace WHERE dcRegionID LIKE @dcRegionID + '%' AND LEN(dcRegionID) = 4 AND IsHot = 1
	END
END








GO
/****** Object:  StoredProcedure [dbo].[pcNewsListByPhone]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[pcNewsListByPhone]
(
	@dcProvinceID AS SMALLINT,
	@PageNum AS INT,
	@PageSize AS INT
)
AS
BEGIN
	DECLARE @COUNT INT
	SELECT @COUNT=COUNT(1) 
		FROM QlrcNews WITH(NOLOCK) WHERE (
			EXISTS(SELECT 'x' FROM fnSplit(DetailType,',') b,dcNewsType c WITH(NOLOCK) WHERE b.a=c.ID AND c.Category=1) OR DetailType IS NULL) 
			AND (VersionID=@dcProvinceID OR VersionID=0) AND NewsType = 2 AND DetailType NOT LIKE '%,2,%'

	IF @COUNT > 200
		SET @COUNT = 200

	SELECT *,@COUNT AS cnt FROM(
		SELECT TOP 200 ROW_NUMBER() OVER(ORDER BY RefreshDate DESC) AS Rows,ID,Title,RefreshDate,Author 
		FROM QlrcNews WITH(NOLOCK) WHERE (
			EXISTS(SELECT 'x' FROM fnSplit(DetailType,',') b,dcNewsType c WITH(NOLOCK) WHERE b.a=c.ID AND c.Category=1) OR DetailType IS NULL) 
			AND (VersionID=@dcProvinceID OR VersionID=0) AND NewsType = 2 AND DetailType NOT LIKE '%,2,%'
	) AS a 
	WHERE a.Rows BETWEEN (@PageNum-1)*@PageSize+1 AND @PageNum*@PageSize ORDER BY Rows
END














GO
/****** Object:  StoredProcedure [dbo].[pcNoViewViPlanInviteByPaMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2014.10.30
--创建人：John
--说明：个人获取没有查看过的面试邀请
--#####################################################
CREATE PROCEDURE [dbo].[pcNoViewViPlanInviteByPaMainIDSelect]
(
	@paMainID INT
)
AS
BEGIN
	SELECT a.*,b.interviewdate,c.Name JobName ,ISNULL(c.SecondId,c.id) jobSecondId,d.Name CompanyName,ISNULL(d.SecondId ,d.id) cpMainID,e.Name caName 
	FROM viplaninvitelog a,viplan b,job c ,cpMain d ,caMain e 
	WHERE c.caMainID=e.id 
		AND a.viplanid=b.id 
		AND a.jobid=c.id 
		AND c.cpMainid=d.id 
		AND addtype=1 
		AND viewdate IS NULL 
		AND cvMainID IN ( SELECT id FROM cvMain WHERE pamainid = @paMainID )
END


GO
/****** Object:  StoredProcedure [dbo].[pcNoViewViRoomInviteByPaMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2014.10.30
--创建人：John
--说明：个人获取没有查看过的面试室邀请
--#####################################################
CREATE PROCEDURE [dbo].[pcNoViewViRoomInviteByPaMainIDSelect]
(
	@paMainID INT
)
AS
BEGIN
	SELECT TOP 1 a.*,b.BeginDate interviewdate,c.Name JobName ,ISNULL(c.SecondId,c.id) jobSecondId,d.Name CompanyName,ISNULL(d.SecondId ,d.id) cpMainID,e.Name caName 
	FROM viinterviewrecord a,viroom b,job c ,cpMain d,caMain e 
	WHERE c.camainid = e.id 
		AND a.viroomid = b.id 
		AND a.jobid = c.id 
		AND c.cpMainid = d.id 
		AND Applytype = 1 
		AND b.enddate IS NULL 
		AND a.viewdate IS NULL 
		AND cvMainID IN ( SELECT id FROM cvMain WHERE pamainid = @paMainID )
END


GO
/****** Object:  StoredProcedure [dbo].[pcNoViewViRoomInviteReplyByPaMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2014.10.30
--创建人：John
--说明：个人获取没有查看过的面试室邀请回复
--#####################################################
CREATE PROCEDURE [dbo].[pcNoViewViRoomInviteReplyByPaMainIDSelect]
(
	@paMainID INT
)
AS
BEGIN
	SELECT TOP 1 a.*,b.BeginDate interviewdate,c.Name JobName ,ISNULL(c.SecondId,c.id) jobSecondId,d.Name CompanyName,ISNULL(d.SecondId ,d.id) cpMainID,e.Name caName 
	FROM viinterviewrecord a,viroom b,job c ,cpMain d,caMain e 
	WHERE c.camainid = e.id 
		AND a.viroomid = b.id 
		AND a.jobid = c.id 
		AND c.cpMainid = d.id 
		AND Applytype = 0 
		AND b.enddate IS NULL 
		AND a.ReplyDate IS NOT NULL
		AND a.ReplyViewDate IS NULL 
		AND cvMainID IN ( SELECT id FROM cvMain WHERE pamainid = @paMainID )
END


GO
/****** Object:  StoredProcedure [dbo].[pcNVCaMainByexMessageC2PPaMainIdSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[pcNVCaMainByexMessageC2PPaMainIdSelect] 
( 
	@paMainID INT,
	@Where VARCHAR(100)
)
AS
BEGIN
	DECLARE @SQL AS VARCHAR(MAX)
	SET @SQL = '
	SELECT a.caMainID,b.Name,b.Gender,b.Dept,b.Telephone,b.Mobile,b.IsPhoneHide,
	b.IsNameHide,b.IsMobileHide,c.Name CompanyName,c.ID cpMainID, c.SecondId EnCpMainID FROM
	(
		SELECT caMainID,AddDate,ROW_NUMBER() OVER(PARTITION BY caMainID ORDER BY AddDate DESC) RowNumber FROM
		(
			SELECT caMainID,ID,addDate,Message,1 IsCompany,IsViewed FROM exMessageC2p WITH(NOLOCK) 
			WHERE cvMainID IN(SELECT ID FROM cvMain WITH(NOLOCK) WHERE paMainID='+CONVERT(VARCHAR,@paMainID)+'
		) AND PersonDeleted=0 
		UNION
		SELECT caMainID,ID,addDate,Message,0 IsCompany,1 FROM exMessageP2C WITH(NOLOCK) WHERE cvMainID IN
		(
			SELECT ID FROM cvMain WITH(NOLOCK) WHERE paMainID='+CONVERT(VARCHAR,@paMainID)+') AND PersonDeleted=0
		) t
	) a,caMain b WITH(NOLOCK),cpMain c WITH(NOLOCK)
	WHERE a.RowNumber=1 AND a.caMainID=b.ID AND b.cpMainID=c.ID'
	IF LEN(@Where) > 0
	BEGIN
		SET @Where = dbo.SafeSql(@Where)
		SET @SQL = @SQL + @Where
	END
	SET @SQL = @SQL + ' ORDER BY AddDate DESC'
	EXEC(@SQL)
END












GO
/****** Object:  StoredProcedure [dbo].[pcNVexMessageLogSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--==================================
--添加人：Lucifer（个人会员中心改版）
--添加时间：2013-7-19
--==================================
CREATE PROCEDURE [dbo].[pcNVexMessageLogSelect]
(
	@paMainID INT,
	@caMainID INT
)
AS
BEGIN
	SELECT * FROM (
		SELECT cvMainID,ID,addDate,Message,1 IsCompany,IsViewed FROM exMessageC2p WITH(NOLOCK)
		WHERE cvMainID IN(SELECT ID FROM cvMain WITH(NOLOCK) WHERE paMainID=@paMainID) AND caMainID=@caMainID
		AND PersonDeleted=0
	UNION
		SELECT cvMainID,ID,addDate,Message,0 IsCompany,1 FROM exMessageP2C WITH(NOLOCK)
		WHERE cvMainID IN(SELECT ID FROM cvMain WITH(NOLOCK) WHERE paMainID=@paMainID) AND caMainID=@caMainID
		AND PersonDeleted=0
	) a ORDER BY a.AddDate
END










GO
/****** Object:  StoredProcedure [dbo].[pcNVexMessageP2CByReplyInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--================================
--添加人：Lucifer（个人会员中心改版）
--添加时间：2013-7-19
--================================
CREATE PROCEDURE [dbo].[pcNVexMessageP2CByReplyInsert]
(
	@caMainID INT,
	@cvMainID INT,
	@Message VARCHAR(200),
	@paMainID INT
)
AS
BEGIN
	IF EXISTS(SELECT ID FROM cvMain WITH(NOLOCK) WHERE paMainID=@paMainID AND ID=@cvMainID)
	BEGIN
		DECLARE @MaxID INT
		SET @Message = dbo.SafeSQL(LTRIM(RTRIM(@Message)))
		INSERT exMessageP2C(caMainID,cvMainID,Message) VALUES(@caMainID,@cvMainID,@Message)
		SET @MaxID = @@IDENTITY
		Update exMessageC2P Set IsReply=1 WHERE cvMainID=@cvMainID AND caMainID=@caMainID AND AddDate<GETDATE()
		RETURN @MaxID		
	END
	ELSE
		RETURN 0
END











GO
/****** Object:  StoredProcedure [dbo].[pcNVPaMainByPaVerifySelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[pcNVPaMainByPaVerifySelect]
(
    @paMainID INT,
    @Mobile VARCHAR(11),
    @Email VARCHAR(50)
)
AS
SET NOCOUNT ON
BEGIN
    DECLARE @VerifyCount SMALLINT
    IF EXISTS(SELECT 'x' FROM paVerifyLog WITH(NOLOCK) WHERE AddDate > DATEADD(Second, -150, GETDATE()) AND (paMainId = @paMainId OR Mobile = @Mobile))
        RETURN -2

    SELECT @VerifyCount=COUNT(1) FROM paVerifyLog WHERE paMainID = @paMainID AND Mobile=@Mobile AND Email=@Email AND AddDate>CONVERT(VARCHAR(10),GETDATE(),120)
    IF @VerifyCount > 4
        RETURN 0
    
    DECLARE @MobileVerifyDate SMALLDATETIME,@EmailVerifyDate SMALLDATETIME,@MobileOld VARCHAR(11)
    SELECT @MobileVerifyDate = MobileVerifyDate,@EmailVerifyDate = EmailVerifyDate,@MobileOld = ISNULL(Mobile,'') 
    FROM paMain WHERE ID=@paMainID
    IF LEN(@Mobile)=0 AND ISNULL(@EmailVerifyDate,'')<>''
        RETURN -1
    IF LEN(@Email)=0 AND ISNULL(@MobileVerifyDate,'')<>'' AND @MobileOld = @Mobile
        RETURN -1

    DECLARE @VerifyCode AS VARCHAR(6)
    SELECT @VerifyCode = RAND() * 899999 + 100000
    INSERT INTO paVerifyLog(paMainID, Email, Mobile, VerifyCode, VerifyDate, AddDate)
    VALUES(@paMainID,@Email,@Mobile,@VerifyCode,NULL,GETDATE())

    RETURN @VerifyCode
END
GO
/****** Object:  StoredProcedure [dbo].[pcNVPaMainByVerifyUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[pcNVPaMainByVerifyUpdate]
(
	@paMainID INT, 
	@Mobile VARCHAR(11), 
	@Email VARCHAR(50), 
	@VerifyCode VARCHAR(6)
)
AS
BEGIN
	DECLARE @MobileVerifyDate SMALLDATETIME, @EmailVerifyDate SMALLDATETIME, @MobileOld VARCHAR(11)
	SELECT @MobileVerifyDate = MobileVerifyDate, @EmailVerifyDate = EmailVerifyDate, @MobileOld = ISNULL(Mobile, '') FROM paMain WHERE ID = @paMainID
	IF LEN(@Mobile) = 0 AND ISNULL(@EmailVerifyDate, '') <> ''
		RETURN -1
	IF LEN(@Email) = 0 AND ISNULL(@MobileVerifyDate, '') <> '' AND @MobileOld = @Mobile
		RETURN -1

	DECLARE @paVerifyLogID AS INT
	SET @paVerifyLogID = 0	
	SELECT @paVerifyLogID = ID FROM paVerifyLog WHERE paMainID = @paMainID AND Mobile = @Mobile AND Email = @Email 
		AND VerifyCode = @VerifyCode AND AddDate>DATEADD(HOUR, -1, GETDATE())
	
	IF @paVerifyLogID = 0
		RETURN 0
	
	UPDATE paVerifyLog SET VerifyDate = GETDATE() WHERE paMainID = @paMainID AND Mobile = @Mobile AND Email = @Email 
		AND VerifyCode = @VerifyCode AND AddDate>DATEADD(HOUR, -1, GETDATE())
	
	IF LEN(@Mobile) = 0
		UPDATE paMain SET EmailVerifyDate = GETDATE() WHERE ID = @paMainID
	
	IF LEN(@Email) = 0
	BEGIN
		UPDATE paMain SET Mobile = @Mobile WHERE ID = @paMainID
		--修改本手机号对应的其他帐号的认证状态
		UPDATE paMain SET MobileVerifyDate = NULL WHERE Mobile = @Mobile 
		UPDATE paMain SET MobileVerifyDate = GETDATE() WHERE ID = @paMainID AND Mobile = @Mobile
	END

	RETURN 1
END
GO
/****** Object:  StoredProcedure [dbo].[pcPaActstatusInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [dbo].[pcPaActstatusInsert]
(
	@paMainId INT,
	@ActStatus INt
)
AS
SET NOCOUNT ON
BEGIN
	INSERT INTO ShortDb..paActStatus(paMainId, ActStatus, AddDate)
	SELECT @paMainId, @ActStatus, GETDATE()
END
GO
/****** Object:  StoredProcedure [dbo].[pcPaAttentionByCpMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--创建时间：2015.11.09
--创建人：nick 
--说明：企业关注详情
--harry 增加logourl
--##################################################### 
CREATE PROCEDURE [dbo].[pcPaAttentionByCpMainIDSelect]
(
    @CpMainID INT,
    @AttentionDate DATETIME,
    @PaMainID INT
)
AS
BEGIN 
SET NOCOUNT ON
    --行业信息
    SELECT a.CpMainiD,b.Description
    FROM CpIndustry a WITH(NOLOCK),dcIndustry b WITH(NOLOCK)
    WHERE a.CpMainiD = @CpMainID
    AND a.DcIndustryID = b.ID
    
    --职位数量
    SELECT TOP 5 a.ID,a.SecondID ,a.Name,a.AddDate,a.IssueEnd,a.IsDelete,b.FullName,c.Description AS SalaryName,a.NeedNumber,a.RefreshDate,0 AS ISApply,
    a.dcSalaryID, c.DescriptionCp Salary, d.DescriptionCp SalaryMax, e.Description Education, f.Description Experience, g.Description NeedNuberDesc, b.MapBarName Region, h.LogoFile LogoUrl
    INTO #TJob 
    FROM Job a WITH(NOLOCK),DcRegion b WITH(NOLOCK),dcSalary c WITH(NOLOCK),dcSalary d WITH(NOLOCK),dcEducation e WITH(NOLOCK),dcOthers f WITH(NOLOCK),dcOthers g WITH(NOLOCK), cpMainPublish h WITH(NOLOCK)
    WHERE CpMainID = @CpMainID
    AND a.cpMainId= h.id
    AND a.DcRegionID = b.ID
    AND a.DcSalaryID = c.ID
    AND a.dcSalaryIDMax = d.ID
    AND a.dcEducationID = e.ID
    AND a.MinExperience = f.DetailID AND f.Category = '职位要求工作经验'
    AND a.NeedNumber = g.DetailID AND g.Category = '招聘人数'
    AND a.AddDate > @AttentionDate
    AND a.Valid = 1
    ORDER BY a.AddDate DESC

    UPDATE #TJob
    SET ISApply = 1
    WHERE ID IN(
        SELECT ID
        FROM exJobApply WITH(NOLOCK)
        WHERE CvMainiD in (
            SELECT ID FROM CvMain WITH(NOLOCK)
            WHERE PaMainID = @paMainID
        ) AND PersonDeleted = 0
    )

    SELECT * FROM #TJob
    --面经数量
    SELECT COUNT(*) FROM Comments WITH(NOLOCK)
    WHERE CommentType IN(1,2)
    AND CpMainID = @CpMainID
    AND AddDate > @AttentionDate

    --点评数量
    SELECT COUNT(*) FROM InterView WITH(NOLOCK)
    WHERE InterViewType IN(1,2)
    AND CpMainID = @CpMainID
    AND AddDate > @AttentionDate

    --环境照片数量
    SELECT COUNT(*) FROM cpImage WHERE cpMainID = @CpMainID AND ImgType = 3 AND AddDate > @AttentionDate AND HasPassed = 1
    
SET NOCOUNT OFF    
END 
GO
/****** Object:  StoredProcedure [dbo].[pcPaAttentionByIDDelete]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--创建：Nick
--创建日期：2015-11-09
--个人中心，取消关注
--------------------------------------------------
CREATE PROCEDURE  [dbo].[pcPaAttentionByIDDelete]
(
	@ID VARCHAR(200),
	@PaMainID INT
)
AS
BEGIN 
	SET NOCOUNT ON
	DELETE FROM PaAttention WHERE ID IN (SELECT * FROM dbo.fnSplit(@ID,','))
	AND PaMainID = @PaMainID
	SET NOCOUNT OFF
END


GO
/****** Object:  StoredProcedure [dbo].[pcPaAttentionByPaMainIDAPPSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--创建时间：2016.1.1 
--创建人：Lucifer 
--说明：个人关注详情 
--##################################################### 
CREATE PROCEDURE [dbo].[pcPaAttentionByPaMainIDAPPSelect] 
( 
	@paMainID INT, 
	@AttentionType INT --1.企业 2.职位
) 
AS 
BEGIN 
	SET NOCOUNT ON
	IF @AttentionType=1 --企业 
	BEGIN 
		SELECT a.PaMainID,a.ID,a.AddDate,b.ID AS CpMainID,b.SecondID CpSecondID,b.Name,b.DcCompanyKindID, 
			c.Description AS DcCompanyKindName,d.Description AS CompanySizeName,a.AddDate AS SortDate,
			(SELECT COUNT(1) FROM Comments e WHERE e.cpMainID = b.ID AND e.CommentType IN(1,2) AND e.AddDate > a.AddDate) commentCount,
			(SELECT COUNT(1) FROM Interview f WHERE f.cpMainID = b.ID AND f.InterviewType IN(1,2) AND f.AddDate > a.AddDate) interviewCount,
			(SELECT COUNT(1) FROM cpImage g WHERE g.cpMainID = b.ID AND g.ImgType = 3 AND g.HasPassed = 1 AND g.AddDate > a.AddDate) environmentCount
		INTO #tcp 
		FROM PaAttention a WITH(NOLOCK), CpMain b WITH(NOLOCK),DcCompanyKind c WITH(NOLOCK),dcCompanySize d WITH(NOLOCK)
		WHERE a.AttentionType=1 
		AND a.AttentionID = b.ID 
		AND a.PaMainID = @paMainID 
		AND b.DcCompanyKindID = C.ID 
		AND b.DcCompanySizeID = d.ID 
		AND b.IsDelete = 0 
		ORDER BY a.AddDate DESC 

		--企业职位最近更新时间 
		UPDATE d SET d.SortDate = c.JobAddDate 
		FROM #tcp d, 
		(SELECT a.CpMainID, MAX(a.LastModifyDate) AS JobAddDate 
		FROM Job a WITH(NOLOCK) 
		WHERE a.CpMainID IN (SELECT CpMainID FROM #tcp) 
		GROUP BY a.CpMainID) c 
		WHERE d.CpMainID = c.CpMainID AND d.SortDate < c.JobAddDate 

		--企业点评、面经最近更新时间 
		UPDATE d SET d.SortDate = c.PreachAddDate 
		FROM #tcp d, 
		(SELECT a.CpMainID, MAX(a.AddDate) AS PreachAddDate 
		FROM Comments a WITH(NOLOCK) 
		WHERE a.CpMainID IN (SELECT CpMainID FROM #tcp) 
		AND a.CommentType IN(1,2) 
		GROUP BY a.CpMainID) c 
		WHERE d.CpMainID = c.CpMainID AND d.SortDate < c.PreachAddDate 

		--企业点评、面经最近更新时间 
		UPDATE d SET d.SortDate = c.PreachAddDate 
		FROM #tcp d, 
		(SELECT a.CpMainID, MAX(a.AddDate) AS PreachAddDate 
		FROM InterView a WITH(NOLOCK) 
		WHERE a.CpMainID IN (SELECT CpMainID FROM #tcp) 
		AND a.InterViewType IN(1,2) 
		GROUP BY a.CpMainID) c 
		WHERE d.CpMainID = c.CpMainID AND d.SortDate < c.PreachAddDate 
		SELECT * FROM #tcp ORDER BY SortDate DESC
		
		--行业信息 
		SELECT a.CpMainiD,b.Description 
		FROM CpIndustry a WITH(NOLOCK),dcIndustry b WITH(NOLOCK) 
		WHERE a.CpMainiD IN(SELECT cpMainID FROM #tcp) 
		AND a.DcIndustryID = b.ID 
		
		--职位数量
		SELECT a.ID,a.cpMainID,a.SecondID ,a.Name,a.AddDate,a.IssueEnd,a.IsDelete,b.FullName,c.Description AS SalaryName,e.Description NeedNumber,a.RefreshDate,0 AS ISApply INTO #TJob
		FROM Job a WITH(NOLOCK),DcRegion b WITH(NOLOCK),dcsalary c WITH(NOLOCK),#tcp d WITH(NOLOCK),dcOthers e WITH(NOLOCK)
		WHERE a.DcRegionID = b.ID 
		AND a.DcSalaryID = c.ID
		AND a.cpMainID = d.cpMainID
		AND a.AddDate > d.AddDate
		AND a.Valid = 1
		AND a.NeedNumber = e.DetailID
		AND e.Category = '招聘人数'
		ORDER BY a.AddDate DESC

		--SELECT a.ID,a.SecondID ,a.Name,a.AddDate,a.IssueEnd,a.IsDelete,b.FullName,c.Description AS SalaryName,a.NeedNumber,a.RefreshDate,0 AS ISApply INTO #TJob
		--FROM Job a WITH(NOLOCK),DcRegion b WITH(NOLOCK),dcsalary c WITH(NOLOCK),#tcp d WITH(NOLOCK)
		--WHERE a.DcRegionID = b.ID 
		--AND a.DcSalaryID = c.ID
		--AND a.cpMainID = d.cpMainID
		--AND a.AddDate > d.AddDate
		--AND a.Valid = 1
		--ORDER BY a.AddDate DESC 
			
		UPDATE #TJob 
		SET ISApply = 1 
		WHERE ID IN( 
			SELECT ID 
			FROM exJobApply WITH(NOLOCK) 
			WHERE CvMainiD in ( 
				SELECT ID FROM CvMain WITH(NOLOCK) 
				WHERE PaMainID = @paMainID 
			) 
			AND PersonDeleted = 0 
		)
		
		SELECT * FROM #TJob
	END 
	ELSE IF @AttentionType=2 --职位 
	BEGIN 
		SELECT a.PaMainID,a.ID,a.AddDate,b.ID AS JobID ,b.SecondID JobSecondID,b.Name AS JobName,c.FullName,f. Description  NeedNumber,
		d.ID as CpMainiD,d.SecondID CpSecondID,d.Name AS CpName,b.IsDelete,0 AS ISApply,IssueEnd,e.Description AS SalaryName,b.RefreshDate
		INTO #TJob2
		FROM PaAttention a WITH(NOLOCK),Job b WITH(NOLOCK),DcRegion c WITH(NOLOCK),CpMain d WITH(NOLOCK),dcSalary e WITH(NOLOCK),dcOthers f WITH(NOLOCK)
		WHERE a.AttentionType=2
		AND a.AttentionID = b.ID
		AND a.PaMainID = @paMainID
		AND b.CpMainID = d.ID
		AND b.DcRegionID = c.ID
		AND b.DcSalaryID = e.ID
		AND b.NeedNumber = f.DetailID
		AND f.Category = '招聘人数'
		ORDER BY a.AddDate DESC
		
		UPDATE #TJob2 SET ISApply = 1
		WHERE JobID IN(
			SELECT JobID
			FROM exJobApply WITH(NOLOCK)
			WHERE CvMainiD in (
				SELECT ID FROM CvMain WITH(NOLOCK)
				WHERE PaMainID = @paMainID
			) AND PersonDeleted = 0
		)
		--职位
		SELECT * FROM #TJob2
	END
	SET NOCOUNT OFF
END
GO
/****** Object:  StoredProcedure [dbo].[pcPaAttentionByPaMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--====================================
--返回值：获取个人关注列表
--创建：Nick 20151109
--====================================
CREATE PROCEDURE [dbo].[pcPaAttentionByPaMainIDSelect]
(
@paMainID INT,
@AttentionType INT --1.企业 2.职位
)
AS 
BEGIN
SET NOCOUNT ON
	IF @AttentionType=1 --企业
	BEGIN
		SELECT a.PaMainID,a.ID,a.AddDate,b.ID AS CpMainID,b.SecondID CpSecondID,b.Name,b.DcCompanyKindID,
		c.Description AS DcCompanyKindName,d.Description AS CompanySizeName,a.AddDate AS SortDate, dbo.GetCpIndustry(b.ID) Industry, b.LogoFile LogoUrl INTO #tcp
		FROM PaAttention a WITH(NOLOCK), CpMain b WITH(NOLOCK),DcCompanyKind c WITH(NOLOCK),dcCompanySize d WITH(NOLOCK)
		WHERE a.AttentionType=1
		AND a.AttentionID = b.ID
		AND a.PaMainID = @paMainID
		AND b.DcCompanyKindID = C.ID
		AND b.DcCompanySizeID = d.ID
		AND b.IsDelete = 0
		ORDER BY a.AddDate DESC
		--企业职位最近更新时间
		UPDATE d SET d.SortDate = c.JobAddDate
		FROM #tcp d,
		(SELECT a.CpMainID, MAX(a.LastModifyDate) AS JobAddDate
		FROM Job a WITH(NOLOCK)
		WHERE a.CpMainID IN (SELECT CpMainID FROM #tcp)
		GROUP BY a.CpMainID) c 
		WHERE d.CpMainID = c.CpMainID AND d.SortDate < c.JobAddDate
		--企业点评、面经最近更新时间 
		UPDATE d SET d.SortDate = c.PreachAddDate
		FROM #tcp d,
		(SELECT a.CpMainID, MAX(a.AddDate) AS PreachAddDate
		FROM Comments a WITH(NOLOCK)
		WHERE a.CpMainID IN (SELECT CpMainID FROM #tcp)
		AND a.CommentType IN(1,2)
		GROUP BY a.CpMainID) c 
		WHERE d.CpMainID = c.CpMainID AND d.SortDate < c.PreachAddDate

		--企业点评、面经最近更新时间 
		UPDATE d SET d.SortDate = c.PreachAddDate
		FROM #tcp d,
		(SELECT a.CpMainID, MAX(a.AddDate) AS PreachAddDate
		FROM InterView a WITH(NOLOCK)
		WHERE a.CpMainID IN (SELECT CpMainID FROM #tcp)
		AND a.InterViewType IN(1,2)
		GROUP BY a.CpMainID) c 
		WHERE d.CpMainID = c.CpMainID AND d.SortDate < c.PreachAddDate

		SELECT * FROM #tcp ORDER BY SortDate DESC
	END
	ELSE IF @AttentionType=2 --职位
		BEGIN
		SELECT a.PaMainID,a.ID,a.AddDate,b.ID AS JobID ,b.SecondID JobSecondID,b.Name AS JobName,c.FullName,b.NeedNumber,
		d.ID as CpMainiD,d.SecondID CpSecondID,d.Name AS CpName,b.IsDelete,0 AS IsApply,IssueEnd,e.Description AS SalaryName,b.RefreshDate, e.DescriptionCp SalaryMin,f.DescriptionCp SalaryMax, g.Description Experience, c.MapBarName Region, b.dcSalaryID, b.dcSalaryIDMax, b.Valid, dbo.GetCaOnlineStatus(b.caMainID) IsOnline
		INTO #TJob
		FROM PaAttention a WITH(NOLOCK),Job b WITH(NOLOCK),DcRegion c WITH(NOLOCK),CpMain d WITH(NOLOCK),dcSalary e WITH(NOLOCK),dcSalary f WITH(NOLOCK),dcOthers g WITH(NOLOCK)
		WHERE a.AttentionType=2 
		AND a.AttentionID = b.ID
		AND a.PaMainID = @paMainID
		AND b.CpMainID = d.ID
		AND b.dcRegionID = c.ID
		AND b.dcSalaryID = e.ID
		AND b.dcSalaryIdMax = f.ID
		AND b.MinExperience = g.DetailID AND g.Category = '职位要求工作经验'
		ORDER BY a.AddDate DESC

		UPDATE #TJob
		SET IsApply = 1
		WHERE JobID IN(
		SELECT JobID
		FROM exJobApply WITH(NOLOCK)
		WHERE CvMainiD in (
		SELECT ID FROM CvMain WITH(NOLOCK)
		WHERE PaMainID = @paMainID
		) AND PersonDeleted = 0
		)

		--职位
		SELECT * FROM #TJob
	END
SET NOCOUNT OFF 
END
GO
/****** Object:  StoredProcedure [dbo].[pcPaAttentionInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--个人关注
--20151123 nick
CREATE PROCEDURE [dbo].[pcPaAttentionInsert] 
(
	@paMainID INT,
	@AttentionType INT,
	@AttentionID INT
)
AS
BEGIN
	SET NOCOUNT ON	

	IF NOT EXISTS(	--判断是否已关注
		SELECT TOP 1 'x' FROM PaAttention 
		WHERE PaMainID  = @paMainID
		AND AttentionType = @AttentionType
		AND AttentionID = @AttentionID
		) 
	BEGIN
		INSERT INTO PaAttention (paMainID,AttentionType,AttentionID,AddDate)
		VALUES(@paMainID,@AttentionType,@AttentionID,GETDATE())
		
		RETURN 1
	END
	ELSE 
	BEGIN
		RETURN 0
	END

	SET NOCOUNT OFF	
END 

GO
/****** Object:  StoredProcedure [dbo].[pcPaCoverLetterByIsDefaultUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


--=============================================
-- 创建：		sean
-- 检查：		2010-10-6
-- 说明：		求职信默认值修改		，改名
--=============================================
CREATE PROCEDURE [dbo].[pcPaCoverLetterByIsDefaultUpdate]
	@paMainID INT,
	@ID INT
AS
BEGIN TRY
	IF NOT EXISTS(SELECT 'X' FROM paCoverLetter WITH(NOLOCK INDEX(IX_paCoverLetter_paMainID)) WHERE paMainID = @paMainID AND ID = @ID)
		RETURN 0
	
	UPDATE paCoverLetter SET IsDefault = 0 WHERE paMainID = @paMainID AND ID <> @ID
	UPDATE paCoverLetter SET IsDefault = IsDefault - 1 WHERE ID=@ID
END TRY
BEGIN CATCH
	GOTO ERR
END CATCH
RETURN 1
ERR:
BEGIN
	RETURN 0
END














GO
/****** Object:  StoredProcedure [dbo].[pcPaCoverLetterByPaMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--=============================================
-- 创建：		sean
-- 检查：		2010-10-6
-- 说明：		求职信列表
--=============================================
CREATE PROCEDURE [dbo].[pcPaCoverLetterByPaMainIDSelect]
	@paMainID INT
AS
BEGIN TRY
    SELECT *
    FROM paCoverLetter WITH(NOLOCK INDEX(IX_paCoverLetter_paMainID))
    WHERE paMainID = @paMainID
	ORDER BY IsDefault DESC,ID DESC
END TRY
BEGIN CATCH
END CATCH














GO
/****** Object:  StoredProcedure [dbo].[pcPaCoverLetterDelete]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--=============================================
-- 创建：		sean
-- 检查：		2010-10-6
-- 说明：		求职信删除
--=============================================
CREATE PROCEDURE [dbo].[pcPaCoverLetterDelete]
	@paMainID INT,
	@ID INT
AS
BEGIN TRY
	IF NOT EXISTS(SELECT 'X' FROM paCoverLetter WITH(NOLOCK) WHERE paMainID = @paMainID AND ID = @ID)
		RETURN 0
	
	DELETE FROM paCoverLetter WHERE ID = @ID
	RETURN 1
		
END TRY
BEGIN CATCH
	RETURN 0
END CATCH














GO
/****** Object:  StoredProcedure [dbo].[pcPaCoverLetterMainTextByIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.4
--创建人：John
--说明：根据ID 从 PaCoverLetter中得到MainText
--#####################################################
CREATE PROCEDURE [dbo].[pcPaCoverLetterMainTextByIDSelect]
(
	@ID INT
)
AS
BEGIN
	SELECT MainText FROM PaCoverLetter WHERE id = @ID
END


GO
/****** Object:  StoredProcedure [dbo].[pcPaCoverLetterMainTextByPaMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.4
--创建人：John
--说明：从 PaCoverLetter中得到MainText
--#####################################################
CREATE PROCEDURE [dbo].[pcPaCoverLetterMainTextByPaMainIDSelect]
(
	@PaMainID INT
)
AS
BEGIN
	SELECT MainText FROM PaCoverLetter WHERE paMainID = @PaMainID AND IsDefault = 1
END


GO
/****** Object:  StoredProcedure [dbo].[pcPaCoverLetterSave]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--=============================================
-- 创建：		sean
-- 检查：		2010-10-6
-- 说明：		求职信保存		，改名
--=============================================
CREATE PROCEDURE [dbo].[pcPaCoverLetterSave]
(
	@ID INT,
	@paMainID INT,
	@IsDefault BIT,
	@Title NVARCHAR(20),
	@MainText NVARCHAR(2000)
)
AS
SELECT @MainText = dbo.SafeSQL(dbo.TextTrim(@MainText)), @Title = dbo.SafeSQL(@Title)
DECLARE @MaxID AS INT
BEGIN TRY
	IF @ID>0		
		BEGIN
			IF NOT EXISTS(SELECT 'x' FROM paCoverLetter WITH(NOLOCK INDEX(PK_paCoverLetter)) WHERE paMainID=@paMainID AND ID = @ID)
				GOTO Err

			UPDATE paCoverLetter
				SET Title = @Title,MainText = @MainText,AddDate=GETDATE()
			WHERE ID=@ID
			AND paMainID = @paMainID
			SET @MaxID = @ID
		END
	ELSE
		BEGIN
			IF EXISTS(SELECT 'x' FROM paCoverLetter WITH(NOLOCK INDEX(IX_paCoverLetter_paMainID)) WHERE paMainID=@paMainID)
				INSERT INTO paCoverLetter(paMainID, IsDefault, Title, MainText)
				VALUES(@paMainID, 0, @Title, @MainText)
			ELSE
				INSERT INTO paCoverLetter(paMainID, IsDefault, Title, MainText)
				VALUES(@paMainID, 1, @Title, @MainText)
	
			SET @MaxID = @@IDENTITY
		END
END TRY
BEGIN CATCH
	GOTO ERR
END CATCH
RETURN @MaxID
ERR:
BEGIN
	RETURN 0
END














GO
/****** Object:  StoredProcedure [dbo].[pcPaCoverLetterSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--=============================================
-- 创建：		sean
-- 检查：		2010-10-6
-- 说明：		求职信新提取
--=============================================
CREATE PROCEDURE [dbo].[pcPaCoverLetterSelect]
(
	@ID INT,
	@paMainID INT OUTPUT,
	@IsDefault Bit OUTPUT,
	@Title VARCHAR(40) OUTPUT,
	@MainText VARCHAR(MAX) OUTPUT,
	@AddDate DateTime OUTPUT
)
AS
SELECT @paMainID=paMainID,@IsDefault=IsDefault,@Title=Title,@MainText=MainText,@AddDate=AddDate
FROM PaCoverLetter WITH(NOLOCK)
WHERE ID=@ID AND paMainID = @paMainID














GO
/****** Object:  StoredProcedure [dbo].[pcpaCvImportLogByCvMainIDUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.31
--创建人：Nick
--说明：修改 paCvImportLog
--#####################################################
CREATE PROCEDURE [dbo].[pcpaCvImportLogByCvMainIDUpdate]
(
	@cvMainID INT
)
AS
BEGIN TRY
	UPDATE paCvImportLog SET isSuccess = 1 WHERE cvMainID=@cvMainID
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[pcpaCvImportLogInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.31
--创建人：Nick
--说明：插入 paCvImportLog
--#####################################################
CREATE PROCEDURE [dbo].[pcpaCvImportLogInsert]
(
	@cvMainID INT,
	@cvFrom VARCHAR(200)
)
AS
BEGIN TRY
	INSERT INTO paCvImportLog VALUES(@cvMainID,@cvFrom,0,GETDATE())
END TRY
BEGIN CATCH
	RETURN 0
END CATCH

GO
/****** Object:  StoredProcedure [dbo].[pcPaCvMainByIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.4
--创建人：John
--说明：根据PaMain的id获取PaMain，CvMain
--#####################################################
CREATE PROCEDURE [dbo].[pcPaCvMainByIDSelect]
(
	@ID INT
)
AS
BEGIN
	SELECT a.ID,a.NAME,a.UserName,a.Email,b.ID cvMainID,b.Name cvName,Adddate
	FROM paMain a WITH(NOLOCK) 
	LEFT JOIN cvMain b WITH(NOLOCK) ON a.ID = b.paMainID 
	WHERE a.ID = @ID
END

GO
/****** Object:  StoredProcedure [dbo].[pcPaCvviewCountSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[pcPaCvviewCountSelect]
(
	@paMainId INT
)
AS
SET NOCOUNT ON
BEGIN
	IF ISNULL(@paMainId, 0) = 0
	BEGIN
		SELECT 0 ViewNumber
		RETURN
	END

	DECLARE @ViewNumber INT, @Cnt INT, @AddDate DateTime
	SELECT @ViewNumber = ViewNumber, @AddDate = AddDate
	FROM paCvViewCount
	WHERE paMainId = @paMainId

	IF ISNULL(@AddDate, GETDATE() - 1) < DATEADD(MINUTE, -120, GETDATE())
	BEGIN
		SELECT @Cnt = COUNT(1)
		FROM caCvviewLog WITH(NOLOCK)
		WHERE cvMainId IN(SELECT ID FROM cvMain WITH(NOLOCK) WHERE paMainId = @paMainId)
		AND EXISTS(SELECT TOP 1 'X' FROM JobPublish WITH(NOLOCK) WHERE caMainID = caCvviewLog.caMainID)

		IF @ViewNumber IS NOT NULL
			DELETE FROM paCvViewCount WHERE paMainId = @paMainId

		INSERT INTO paCvViewCount(paMainId, ViewNumber, AddDate) SELECT @paMainId, @Cnt, GETDATE()
		SET @ViewNumber = @Cnt
	END
	SELECT @ViewNumber ViewNumber
END 
SET NOCOUNT OFF
GO
/****** Object:  StoredProcedure [dbo].[pcPaFavorateBatchDelete]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--====================================
--返回值：-1：不是你的收藏职位
--创建：	lucifer
--检查：	Sean 2010-10-14
--删除收藏的职位
--====================================
CREATE PROCEDURE [dbo].[pcPaFavorateBatchDelete]
(
	@AllID VARCHAR(1000),
	@paMainID INT
)
AS
BEGIN TRY
	--生成临时表
	DECLARE @t AS TABLE(ID INT)
/*
	DECLARE @i INT
	SET @i=CHARINDEX(',',@AllID)
	WHILE @i>=1
	BEGIN
		IF LEFT(@AllID,@i-1) > ''
			INSERT @t VALUES(LEFT(@AllID,@i-1))
		SET @AllID=SUBSTRING(@AllID,@i+1,LEN(@AllID)-@i)
		SET @i=CHARINDEX(',',@AllID)
	END
	IF @AllID > '' 
		INSERT @t VALUES(@AllID)
*/
	INSERT INTO @t
	SELECT * FROM dbo.fnSplit(@AllID, ',')

	----判断是否这些id是同一个paMainID
	IF EXISTS(SELECT 'X' FROM paFavorate a WITH(NOLOCK), @t b
				WHERE a.id=b.id AND a.paMainID<>@paMainID)
		GOTO Err1

	DELETE FROM paFavorate WHERE ID IN(SELECT ID FROM @t)
END TRY
BEGIN CATCH
	GOTO ERR
END CATCH
RETURN 1
ERR:
BEGIN
	RETURN 0
END
ERR1:
BEGIN
	RETURN -1
END














GO
/****** Object:  StoredProcedure [dbo].[pcPaFavorateInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--====================================
--返回值：-1：不是你的收藏职位
--创建：	lucifer
--检查：	Sean 2010-10-14
--保存收藏的职位	，先删除、再添加
--====================================
CREATE PROCEDURE [dbo].[pcPaFavorateInsert]
(
	@paMainID INT,
	@JobId INT,
	@Remark VARCHAR(200)
)
AS
BEGIN
	SET @Remark = dbo.SafeSQL(dbo.TRIM(@Remark))
	DECLARE @cnt AS INT
	SELECT @cnt = COUNT(1) FROM paFavorate WITH(NOLOCK) WHERE paMainID = @paMainID
	IF @cnt > 199
		RETURN 0
	IF LEN(@Remark) = 0
		SET @Remark = NULL
	INSERT INTO paFavorate(paMainID,JobId,Remark) VALUES(@paMainID,@JobId,@Remark)
	RETURN 1
END














GO
/****** Object:  StoredProcedure [dbo].[pcPaFavorateSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[pcPaFavorateSelect]
(
	@WHERE VARCHAR(1000),
	@Order VARCHAR(100)
)
AS
BEGIN
	BEGIN TRY
		SET @Where = dbo.SafeSql(@Where)
		SET @Order = dbo.SafeSql(@Order)
		DECLARE @SQL AS VARCHAR(2000)
		SET @SQL='SELECT a.ID,a.paMainID,a.JobID,a.AddDate,a.Remark,b.Name as JobName,b.IssueDate,
				b.IssueEND,b.dcRegionID,b.IsDelete,c.Name as cpName,c.ID as cpID,c.HasLicence,
				c.IsAgent, c.Membertype, b.dcSalaryID, b.SecondId EnJobID, c.SecondId EnCpMainID,
				b.caMainID, dbo.GetCaOnlineStatus(b.caMainID) AS IsOnline
			FROM paFavorate a WITH(NOLOCK) 
			Inner Join Job b WITH(NOLOCK) ON a.JobID=b.ID 
			Inner Join cpMain c WITH(NOLOCK) ON b.cpMainID=c.ID'
		IF LEN(@WHERE)>0
			SET @SQL=@SQL + ' WHERE '+ @WHERE
		IF LEN(@ORDER)>0
			SET @SQL=@SQL + ' ORDER BY '+@ORDER
		EXEC(@SQL)
	END TRY
	BEGIN CATCH
	END CATCH
END




GO
/****** Object:  StoredProcedure [dbo].[pcpaFavorateUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--====================================
--创建：	lucifer
--检查：	Sean 2010-10-14
--修改备注
--====================================
CREATE PROCEDURE [dbo].[pcpaFavorateUpdate]
(
	@ID INT,
	@Remark VARCHAR(200),
	@paMainId INT
)
AS
BEGIN TRAN
	BEGIN TRY
		UPDATE paFavorate SET Remark=dbo.SafeSQL(@Remark) WHERE ID=@ID AND paMainID = @paMainID
	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH
COMMIT TRAN
RETURN 1
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END














GO
/****** Object:  StoredProcedure [dbo].[pcpaFeedBackInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--==================================================
--检查 sean 2010-10-8
--描述 新增个人用户反馈
--==================================================
CREATE PROCEDURE [dbo].[pcpaFeedBackInsert]
(
	@paMainID INT,
	@dcProvinceID INT,
	@IP VARCHAR(31),
	@Name VARCHAR(100),
	@Telephone VARCHAR(50),
	@Email VARCHAR(100),
	@Message VARCHAR(4000)
)
AS
BEGIN TRY
	INSERT INTO PaFeedBack(paMainID,dcProvinceID,IP,Name,Telephone,Email,Message,AddDate)
	VALUES(@paMainID,@dcProvinceID,@IP,dbo.SafeSQL(@Name),dbo.SafeSQL(@Telephone),dbo.SafeSQL(@Email),dbo.SafeSQL(@Message),GETDATE())

	RETURN 1
END TRY
BEGIN CATCH
	RETURN 0
END CATCH














GO
/****** Object:  StoredProcedure [dbo].[pcpaFeedBackNoViewSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--==================================================
--检查 sean 2010-10-8
--描述 选择未查看的个人用户反馈
--==================================================
CREATE PROCEDURE [dbo].[pcpaFeedBackNoViewSelect]
(
    @paMainID INT
)
AS
BEGIN
    SELECT *
    FROM paFeedBack WITH(NOLOCK INDEX(IX_paFeedBack_paMainID))
    WHERE paMainID = @paMainID
	AND IsReply = 1
	AND ViewDate IS NULL
	ORDER BY ID DESC
END














GO
/****** Object:  StoredProcedure [dbo].[pcpaFeedBackSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--==================================================
--检查 sean 2010-10-8
--描述 选择个人用户反馈
--==================================================
CREATE PROCEDURE [dbo].[pcpaFeedBackSelect]
    @paMainID INT
AS
BEGIN
    SELECT *
    FROM paFeedBack WITH(NOLOCK INDEX(IX_paFeedBack_paMainID))
    WHERE paMainID = @paMainID
	ORDER BY ID DESC
END














GO
/****** Object:  StoredProcedure [dbo].[pcPaFeedbackViewDateUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--==================================================
--检查 sean 2010-10-8
--描述asp中取所有viewDate is null的id
--==================================================
CREATE PROCEDURE [dbo].[pcPaFeedbackViewDateUpdate]
    @AllID VARCHAR(200),
	@paMainID INT
AS
BEGIN TRY
	SET @AllID = dbo.FormatIDS(@AllID)
	DECLARE @T AS TABLE(ID INT)
	INSERT INTO @T SELECT * FROM dbo.fnSplit(@AllID, ',')

	UPDATE paFeedback SET ViewDate=GETDATE() WHERE ID IN(SELECT ID FROM @T) AND paMainID = @paMainID
    RETURN 1
END TRY
BEGIN CATCH
    RETURN 0
END CATCH














GO
/****** Object:  StoredProcedure [dbo].[pcPaGetPasswordLogByMailSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--======================================
--一天之内一个账号不能查询超过5次
--一天之内一个ip不能超过20次
--======================================
CREATE PROCEDURE [dbo].[pcPaGetPasswordLogByMailSelect]
	@paMainID INT,
	@IP VARCHAR(31)
AS
BEGIN
	DECLARE @d AS DATETIME
	DECLARE @C AS INT
	SET @d = CONVERT(DATETIME,(FLOOR(CONVERT(FLOAT,GETDATE()))))

	SELECT @C = COUNT(1) FROM paGetPasswordLog WITH(NOLOCK) WHERE paMainID = @paMainID AND AddDate>=@d
	IF @c >4
		GOTO Err1
		
	SELECT @C = COUNT(1) FROM paGetPasswordLog WITH(NOLOCK) WHERE IP = @IP AND AddDate>=@d
	IF @c > 20
		GOTO Err2

	RETURN 1
END
Err1:
BEGIN
	RETURN -1
END
Err2:
BEGIN
	RETURN -2
END
	
		














GO
/****** Object:  StoredProcedure [dbo].[pcPaJobClickLogByIpSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.30
--创建人：Nick
--说明：得到点击次数
--#####################################################
CREATE PROCEDURE [dbo].[pcPaJobClickLogByIpSelect]
(
	@Ip VARCHAR(50),
	@PaMainID INT
)
AS
SET NOCOUNT ON
--insert proclog select 'pcPaJobClickLogByIpSelect', @ip, getdate()
BEGIN
	DECLARE @canview TINYINT
	IF EXISTS(SELECT 'x' FROM paJobClickCount WITH(NOLOCK) WHERE Ip = @Ip)
		SET @canview = '0'
	ELSE
		SET @canview = '1'

	SELECT @canview canview
/*
	DECLARE @Cnt1 INT, @Cnt2 INT

	IF ISNULL(@PaMainID, 0) > 0
		SELECT @Cnt2 = COUNT(1) 
		FROM paJobClickLog WITH(NOLOCK) 
		WHERE paMainID = @PaMainID
	ELSE
		SET @Cnt2 = 0

	IF @Cnt2 > 9
	BEGIN
		SELECT '0' canview
		RETURN
	END

	SELECT @Cnt1 = COUNT(1) 
	FROM paJobClickLog WITH(NOLOCK) 
	WHERE Ip = @ip

	DECLARE @canview VARCHAR(1)
	SET @canview = ''

	IF @Cnt1 > 9
	BEGIN
		IF EXISTS(SELECT 'x' FROM Ip_White WHERE CHARINDEX(ip, @ip) > 0)
		BEGIN
			IF @Cnt1 > 99
				SET @canview = '0'
		END
		ELSE
			SET @canview = '0'
	END

	IF @canview = ''
		SET @canview = '1'

	SELECT @canview canview
*/
END

GO
/****** Object:  StoredProcedure [dbo].[pcPaJobClickLogCountSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.30
--创建人：Nick
--说明：得到点击次数
--#####################################################
CREATE PROCEDURE [dbo].[pcPaJobClickLogCountSelect]
(
	@PaMainID INT
)
AS
BEGIN
	SELECT COUNT(1) cnt 
	FROM paJobClickLog WITH(NOLOCK) 
	WHERE paMainID = @PaMainID
	--AND AddDate > CONVERT(VARCHAR(10), GETDATE(), 112) 
END


GO
/****** Object:  StoredProcedure [dbo].[pcPaJobClickLogSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.30
--创建人：Nick
--说明：根据职位ID，个人ID 判断是否点击过
--#####################################################
CREATE PROCEDURE [dbo].[pcPaJobClickLogSelect]
(
	@JobID INT,
	@PaMainID INT
)
AS
BEGIN
	SELECT 'x' 
	FROM paJobClickLog WITH(NOLOCK) 
	WHERE AddDate > CONVERT(VARCHAR(10), GETDATE(), 112) 
	AND JobID = @JobID
	AND paMainID = @PaMainID
END
GO
/****** Object:  StoredProcedure [dbo].[pcPaJobCompareByHomePageSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--修改harry 过期的职位不显示2017-10-23
CREATE PROCEDURE [dbo].[pcPaJobCompareByHomePageSelect]
(
	@PaMainID INT
)
AS
SET NOCOUNT ON
BEGIN
	SELECT TOP 9 b.ID JobID, b.SecondID EnJobID, b.Name JobName,b.dcSalaryIdMax,b.Negotiable, c.Name CpName,c.HasLicence, c.SecondID EnCpMainID,
		(SELECT CASE WHEN LEN(e.Id) = 6
			THEN RIGHT(e.FullName, LEN(e.FullName) - CHARINDEX(LEFT(e.MapBarName, 2), e.FullName) + 1)
			ELSE e.Abbr
			END 
		FROM dcRegion e WITH(NOLOCK) WHERE e.Id = b.dcRegionId) WorkPlace,
		ISNULL((SELECT Description FROM dcEducation WHERE id = b.dcEducationId), '不限') Education,
		b.dcSalaryID,
		(SELECT Description FROM dcOthers WHERE Category = '招聘人数' AND DetailId = b.NeedNumber) NeedNumber,
		'http://down.51rc.com/imagefolder/Logo/L' + CASE WHEN c.Id < 90000 THEN '0' ELSE '' END + LTRIM(STR(c.Id / 10000 + 1)) + '0000/' + d.ImgFile ImgFile
	FROM PaJobCompare a WITH(NOLOCK)
	INNER JOIN Job b WITH(NOLOCK) ON b.ID = a.CompareJobID
	INNER JOIN CpMain c WITH(NOLOCK) ON c.ID = b.CpMainID
	INNER Join cpImage d WITH(NOLOCK) ON d.cpMainId = c.Id
	WHERE PaMainID = @PaMainID
	AND b.valid = 1
	AND c.HasLogo = 1
	AND d.Imgtype = 1
	ORDER BY a.AddDate DESC
END

GO
/****** Object:  StoredProcedure [dbo].[pcPaJobCompareByPaMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--Harry过期职位不显示2017-10-23
CREATE PROCEDURE [dbo].[pcPaJobCompareByPaMainIDSelect]
(
    @PaMainID INT,
    @IsLastBatch BIT,
    @BatchNo SMALLINT
)
AS
SET NOCOUNT ON
BEGIN
    IF @BatchNo > 0
    BEGIN
        SELECT a.*,b.*,c.Name CpName,c.HasLicence,c.SecondID EnCpMainID,b.ID JobID,b.SecondID EnJobID,
        b.Name JobName,a.AddDate RecommenedDate,c.RealName,
        ISNULL((SELECT IsOnline FROM caOnline WHERE caMainId =b.caMainID), 0) AS IsOnline, c.LogoFile LogoUrl
        FROM PaJobCompare a WITH(NOLOCK)
        LEFT JOIN Job b WITH(NOLOCK) ON b.ID = a.CompareJobID
        LEFT JOIN CpMain c WITH(NOLOCK) ON c.ID = b.CpMainID
        WHERE PaMainID = @PaMainID
        AND BatchNo = @BatchNo
        ORDER BY a.AddDate DESC
    END
    ELSE IF @IsLastBatch = 1
    BEGIN
        SELECT a.*,b.*,c.Name CpName,c.HasLicence,c.SecondID EnCpMainID,b.ID JobID,b.SecondID EnJobID,
            b.Name JobName,a.AddDate RecommenedDate, ISNULL((SELECT IsOnline FROM caOnline WHERE caMainId =b.caMainID), 0) AS IsOnline,
            c.LogoFile LogoUrl, c.RealName
        FROM PaJobCompare a WITH(NOLOCK)
        LEFT JOIN Job b WITH(NOLOCK) ON b.ID = a.CompareJobID
        LEFT JOIN CpMain c WITH(NOLOCK) ON c.ID = b.CpMainID
        WHERE PaMainID = @PaMainID
		AND b.valid = 1
        AND BatchNo = (
            SELECT MAX(BatchNo) 
            FROM PaJobCompare WITH(NOLOCK)
            WHERE PaMainID = @PaMainID
        )
        ORDER BY a.AddDate DESC
    END
    ELSE
    BEGIN
        SELECT a.*,b.*,c.Name CpName,c.HasLicence,c.SecondID EnCpMainID,b.ID JobID,b.SecondID EnJobID,
            b.Name JobName,a.AddDate RecommenedDate,ISNULL((SELECT IsOnline FROM caOnline WHERE caMainId =b.caMainID), 0) AS IsOnline,
            c.LogoFile LogoUrl,c.RealName, d.DescriptionCp Salary, e.DescriptionCp SalaryMax, f.MapBarName Region, g.Description Education, h.Description Experience
        FROM PaJobCompare a WITH(NOLOCK)
        LEFT JOIN Job b WITH(NOLOCK) ON b.ID = a.CompareJobID
        LEFT JOIN CpMain c WITH(NOLOCK) ON c.ID = b.CpMainID
	LEFT JOIN dcSalary d WITH(NOLOCK) ON b.dcSalaryId = d.ID
	LEFT JOIN dcSalary e WITH(NOLOCK) ON b.dcSalaryIdMax = e.ID
	LEFT JOIN dcRegion f WITH(NOLOCK) ON b.dcRegionId = f.ID
	LEFT JOIN dcEducation g WITH(NOLOCK) ON b.dcEducationId = g.ID
	LEFT JOIN dcOthers h WITH(NOLOCK) ON b.MinExperience = h.DetailID AND Category = '职位要求工作经验'
    WHERE PaMainID = @PaMainID
	AND b.valid = 1
    ORDER BY a.AddDate DESC
    END
END 

GO
/****** Object:  StoredProcedure [dbo].[pcpaJobFinderByEmailUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--增加人：LAMBO 20110104 
--作用：修改搜索器的订阅信息，用于我的搜索器页面
CREATE PROCEDURE [dbo].[pcpaJobFinderByEmailUpdate]
	@ID INT,
	@paMainID INT,
	@EmailSent SMALLINT,
	@EmailEndDate VARCHAR(20),
	@Email VARCHAR(50),
	@EmailNumber INT
AS
BEGIN TRY
	UPDATE paJobFinder SET
		EmailSent=@EmailSent,
		EmailEndDate=dbo.SafeSQL(@EmailEndDate),
		EmailNumber=@EmailNumber,
		Email=dbo.SafeSQL(@Email)
	WHERE ID=@ID
	AND paMainID = @paMainID
	RETURN 1
END TRY
BEGIN CATCH
	RETURN 0
END CATCH














GO
/****** Object:  StoredProcedure [dbo].[pcPaJobFinderByIDUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--修改订阅接收频次
--nick 20151118
create PROCEDURE [dbo].[pcPaJobFinderByIDUpdate]
(
	@ID INT,
	@PaMainID INT,
	@EmailSent INT
)
AS
BEGIN 
SET NOCOUNT ON
	UPDATE PaJobFinder
	SET EmailSent = @EmailSent
	WHERE ID = @ID
	AND PaMainID = @PaMainID
SET NOCOUNT OFF	
END

GO
/****** Object:  StoredProcedure [dbo].[pcpaJobFinderBypaMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[pcpaJobFinderBypaMainIDSelect]
	@paMainID INT
AS
BEGIN
	SELECT * FROM paJobFinder WITH(NOLOCK) WHERE paMainID=@paMainID
END














GO
/****** Object:  StoredProcedure [dbo].[pcpaJobFinderDelete]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
----###############################
--删除职位搜索器
----###############################
CREATE PROCEDURE [dbo].[pcpaJobFinderDelete]
(
	@ID INT,
	@paMainID INT
)
AS
BEGIN
	DELETE FROM paJobFinder WHERE ID = @ID AND paMainID = @paMainID

	IF @@ROWCOUNT = 0
		RETURN 0
	ELSE
		RETURN 1
END














GO
/****** Object:  StoredProcedure [dbo].[pcpaJobFinderSave]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--LAMBO 20101125 修改
--增加对搜索器个数的判断
CREATE PROCEDURE [dbo].[pcpaJobFinderSave]
(
	@ID INT,
	@paMainID INT,
	@Name VARCHAR(50),
	@dcJobTypeID VARCHAR(50),
	@dcIndustryID VARCHAR(50),
	@dcRegionID VARCHAR(50),
	@KeyType TINYINT,
	@KeyWord VARCHAR(50),
	@Education TINYINT,
	@EmployType VARCHAR(50),
	@MinExperience VARCHAR(50),
	@Salary VARCHAR(50),
	@EmailSent SMALLINT,
	@EmailEndDate VARCHAR(20),
	@Email VARCHAR(50),
	@EmailNumber INT
)
AS
DECLARE @MaxId AS INT
BEGIN TRY
IF @dcJobTypeID = ''
	SET @dcJobTypeID = NULL
IF @dcIndustryID = ''
	SET @dcIndustryID = NULL
IF @dcRegionID = ''
	SET @dcRegionID = NULL
IF @Education = ''
	SET @Education = NULL
IF @EmployType = ''
	SET @EmployType = NULL
IF @MinExperience = ''
	SET @MinExperience = NULL
IF @Salary = ''
	SET @Salary = NULL

	IF @EmailSent = 0 
	BEGIN
		SET @EmailEndDate = NUll
		SET @Email = NUll
		SET @EmailNumber = NULL
	END
	ELSE
		SET @EmailEndDate = CONVERT(VARCHAR(10), CONVERT(DATETIME, @EmailEndDate), 120) + ' 23:59:00'
--PRINT @EmailEndDate
	IF @ID>0
		BEGIN
			UPDATE paJobFinder SET
				dcJobTypeID=@dcJobTypeID,
				dcIndustryID=@dcIndustryID,
				dcRegionID=@dcRegionID,
				KeyType=@KeyType,
				KeyWord=@KeyWord,
				Education=@Education,
				EmployType=@EmployType,
				MinExperience=@MinExperience,
				Salary=@Salary,
				EmailSent=@EmailSent,
				EmailEndDate=@EmailEndDate,
				EmailNumber=@EmailNumber,
				Email=@Email
			WHERE ID=@ID
			AND paMainID = @paMainID
			SET @MaxID=@ID
		END
	ELSE
		BEGIN
			DECLARE @FinderCount INT
			SELECT @FinderCount = COUNT(1) FROM paJobFinder WHERE paMainID = @paMainID
			IF @FinderCount >= 6
				RETURN -1
			INSERT INTO paJobFinder
				(paMainID,Name,dcJobTypeID,dcIndustryID,
				dcRegionID,KeyType,KeyWord,Education,
				EmployType,MinExperience,Salary,
				EmailSent,EmailEndDate,EmailNumber,Email)
			VALUES
				(@paMainID,@Name,@dcJobTypeID,@dcIndustryID,
				@dcRegionID,@KeyType,@KeyWord,@Education,
				@EmployType,@MinExperience,@Salary,
				@EmailSent,@EmailEndDate,@EmailNumber,@Email)
			SET @MaxID = @@IDENTITY
		END
END TRY
BEGIN CATCH
	GOTO ERR
END CATCH
RETURN @MaxID
ERR:
BEGIN
	RETURN 0
END














GO
/****** Object:  StoredProcedure [dbo].[pcpaJobFinderSave2]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[pcpaJobFinderSave2]
(
	@ID INT,
	@paMainID INT,
	@Name VARCHAR(50),
	@dcJobTypeID VARCHAR(50),
	@dcIndustryID VARCHAR(50),
	@dcRegionID VARCHAR(50),
	@KeyType TINYINT,
	@KeyWord VARCHAR(50),
	@Education TINYINT,
	@EmployType VARCHAR(50),
	@MinExperience VARCHAR(50),
	@Salary VARCHAR(50),
	@EmailSent SMALLINT,
	@EmailEndDate VARCHAR(20),
	@Email VARCHAR(50),
	@EmailNumber INT,
	@IsNegotiable BIT,
	@dcCompanySizeID TINYINT
)
AS
DECLARE @MaxId AS INT
BEGIN TRY
	IF @dcJobTypeID = ''
		SET @dcJobTypeID = NULL
	IF @dcIndustryID = ''
		SET @dcIndustryID = NULL
	IF @dcRegionID = ''
		SET @dcRegionID = NULL
	IF @Education = ''
		SET @Education = NULL
	IF @EmployType = ''
		SET @EmployType = NULL
	IF @MinExperience = ''
		SET @MinExperience = NULL
	IF @Salary = ''
		SET @Salary = NULL
	IF @IsNegotiable IS NULL
		SET @IsNegotiable = 0	

	IF @EmailSent = 0 
	BEGIN
		SET @EmailEndDate = NUll
		SET @Email = NUll
		SET @EmailNumber = NULL
	END
	ELSE
		SET @EmailEndDate = CONVERT(VARCHAR(10), CONVERT(DATETIME, @EmailEndDate), 120) + ' 23:59:00'
	----PRINT @EmailEndDate

	IF @ID>0
		BEGIN
			UPDATE paJobFinder 
			SET Name = @Name,
				dcJobTypeID=@dcJobTypeID,
				dcIndustryID=@dcIndustryID,
				dcRegionID=@dcRegionID,
				KeyType=@KeyType,
				KeyWord=@KeyWord,
				Education=@Education,
				EmployType=@EmployType,
				MinExperience=@MinExperience,
				Salary=@Salary,
				EmailSent=@EmailSent,
				EmailEndDate=@EmailEndDate,
				EmailNumber=@EmailNumber,
				Email=@Email,
				IsNegotiable = @IsNegotiable,
				dcCompanySizeID = @dcCompanySizeID
			WHERE ID=@ID
			AND paMainID = @paMainID
			SET @MaxID=@ID
		END
	ELSE
		BEGIN
			DECLARE @FinderCount INT
			SELECT @FinderCount = COUNT(1) FROM paJobFinder WHERE paMainID = @paMainID
			IF @FinderCount >= 6
			BEGIN
				--大于6个将第一个删除 再进行添加
				DELETE FROM paJobFinder WHERE paMainID = @paMainID 
				AND ID IN (
					SELECT TOP 1 ID FROM paJobFinder WHERE paMainID = @paMainID 
					ORDER BY ID
				)
				--RETURN -1
			END
			INSERT INTO paJobFinder
				(paMainID,Name,dcJobTypeID,dcIndustryID,
				dcRegionID,KeyType,KeyWord,Education,
				EmployType,MinExperience,Salary,
				EmailSent,EmailEndDate,EmailNumber,Email, IsNegotiable, dcCompanySizeID)
			VALUES
				(@paMainID,@Name,@dcJobTypeID,@dcIndustryID,
				@dcRegionID,@KeyType,@KeyWord,@Education,
				@EmployType,@MinExperience,@Salary,
				@EmailSent,@EmailEndDate,@EmailNumber,@Email, @IsNegotiable, @dcCompanySizeID)
			SET @MaxID = @@IDENTITY
		END
END TRY
BEGIN CATCH
	GOTO ERR
END CATCH
RETURN @MaxID
ERR:
BEGIN
	RETURN 0
END

GO
/****** Object:  StoredProcedure [dbo].[pcpaJobFinderSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[pcpaJobFinderSelect]
	@ID INT
AS
SELECT * FROM paJobFinder WITH(NOLOCK) WHERE ID=@ID














GO
/****** Object:  StoredProcedure [dbo].[pcPaJobViewLogBatchSave]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[pcPaJobViewLogBatchSave]
(
	@JobIDs VARCHAR(500),
	@paMainID INT
)
AS
BEGIN
	SET @JobIDs = dbo.FormatIDS(@JobIDs)
	IF @paMainID <> 0
	BEGIN
			UPDATE PaJobViewLog SET AddDate=GETDATE()
			WHERE paMainID = @paMainID AND JobID IN (SELECT * FROM dbo.fnSplit(@JobIDs, ','))
			INSERT PaJobViewLog(paMainID,JobID) 
			SELECT @paMainID,a FROM dbo.fnSplit(@JobIDs, ',')
			WHERE a NOT IN (SELECT JobID FROM paJobViewLog WITH(NOLOCK) WHERE paMainID = @paMainID)
	END
	
	UPDATE Job SET ViewNumber = ViewNumber + 1 WHERE ID IN (SELECT * FROM dbo.fnSplit(@JobIDs, ','))
END














GO
/****** Object:  StoredProcedure [dbo].[pcPaJobViewLogSave]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--====================================
--创建：	lucifer
--检查：	Sean 2010-10-14
--职位查看记录
--====================================
CREATE PROCEDURE [dbo].[pcPaJobViewLogSave]
(
	@paMainID INT,
	@JobID INT
)
AS
SET NOCOUNT ON
BEGIN TRY
	IF @paMainID > 0
		IF EXISTS(SELECT 'x' FROM PaJobViewLog WITH(NOLOCK) WHERE paMainID=@paMainID AND JobID=@JobID)
			UPDATE PaJobViewLog SET AddDate = GETDATE() WHERE paMainID = @paMainID AND JobID = @JobID
		ELSE
			INSERT PaJobViewLog(paMainID, JobID) VALUES(@paMainID, @JobID)
	
	UPDATE Job SET ViewNumber = ViewNumber + 1 WHERE ID = @JobID
END TRY
BEGIN CATCH
END CATCH














GO
/****** Object:  StoredProcedure [dbo].[pcPaJobViewLogSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[pcPaJobViewLogSelect]
(
	@WHERE VARCHAR(1000),
	@Order VARCHAR(100)
)
AS
BEGIN
	BEGIN TRY
		SET @Where = dbo.SafeSql(@Where)
		SET @Order = dbo.SafeSql(@Order)
		DECLARE @SQL AS VARCHAR(2000)
		SET @SQL = 'SELECT JobID,paMainID,a.AddDate,b.Name as JobName,b.IssueDate,b.IssueEND, b.SecondId EnJobID, c.SecondId EnCpMainID,
				b.dcRegionID,b.IsDelete,c.Name as cpName,c.ID as cpID,c.HasLicence, c.IsAgent, c.MemberType, b.dcSalaryId,b.caMainID,
				dbo.GetCaOnlineStatus(b.caMainID) AS IsOnline
				FROM paJobViewLog a WITH(NOLOCK)
				inner join Job b WITH(NOLOCK) On a.JobID = b.ID 
				inner join cpMain c WITH(NOLOCK) On b.cpMainID = c.ID'

		IF LEN(@WHERE)>0
			SET @SQL=@SQL + ' WHERE '+@WHERE
		IF LEN(@ORDER)>0
			SET @SQL=@SQL + ' ORDER BY '+@ORDER

		EXEC(@SQL)
	END TRY
	BEGIN CATCH
	END CATCH
END





GO
/****** Object:  StoredProcedure [dbo].[pcPaLoginLogSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[pcPaLoginLogSelect]
(
    @paMainID INT
)
AS
BEGIN
    SELECT Top 100 a.*,b.Name
    FROM PaLoginLog a WITH(NOLOCK),paMain b WITH(NOLOCK)
    WHERE a.paMainID = @paMainID 
	AND a.paMainID = b.ID
	ORDER BY a.Adddate DESC
END














GO
/****** Object:  StoredProcedure [dbo].[pcPaLoginRegCountByDcSubSiteIdUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*++++++++++++++++++++++++++++++++++++
sean 2014-2-17
++++++++++++++++++++++++++++++++++++*/
CREATE PROCEDURE [dbo].[pcPaLoginRegCountByDcSubSiteIdUpdate]
(
	@dcSubSiteId INT,
	@Col VARCHAR(20)
)
AS
BEGIN
	IF @Col = 'oneminuteload'
		UPDATE PaLoginRegCount SET OneMinuteLoad = OneMinuteLoad + 1 WHERE CountDate = CONVERT(VARCHAR(8), GETDATE(), 112) AND dcSubSiteId = @dcSubSiteId
	ELSE IF @Col = 'OneMinuteCreate'
		UPDATE PaLoginRegCount SET OneMinuteCreate = OneMinuteCreate + 1 WHERE CountDate = CONVERT(VARCHAR(8), GETDATE(), 112) AND dcSubSiteId = @dcSubSiteId
	ELSE IF @Col = 'OneMinuteLogin'
		UPDATE PaLoginRegCount SET OneMinuteLogin = OneMinuteLogin + 1 WHERE CountDate = CONVERT(VARCHAR(8), GETDATE(), 112) AND dcSubSiteId = @dcSubSiteId
	ELSE IF @Col = 'LoginPageLogin'
		UPDATE PaLoginRegCount SET LoginPageLogin = LoginPageLogin + 1 WHERE CountDate = CONVERT(VARCHAR(8), GETDATE(), 112) AND dcSubSiteId = @dcSubSiteId
	ELSE IF @Col = 'LoginPageReg'
		UPDATE PaLoginRegCount SET LoginPageReg = LoginPageReg + 1 WHERE CountDate = CONVERT(VARCHAR(8), GETDATE(), 112) AND dcSubSiteId = @dcSubSiteId
END










GO
/****** Object:  StoredProcedure [dbo].[pcPaLoginRegCountUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*++++++++++++++++++++++++++++++++++++
sean 2014-2-13
++++++++++++++++++++++++++++++++++++*/
CREATE PROCEDURE [dbo].[pcPaLoginRegCountUpdate]
(
	@Col VARCHAR(20)
)
AS
BEGIN
	IF @Col = 'oneminuteload'
		UPDATE PaLoginRegCount SET OneMinuteLoad = OneMinuteLoad + 1 WHERE CountDate = CONVERT(VARCHAR(8), GETDATE(), 112) AND dcSubSiteId = 0
	ELSE IF @Col = 'OneMinuteCreate'
		UPDATE PaLoginRegCount SET OneMinuteCreate = OneMinuteCreate + 1 WHERE CountDate = CONVERT(VARCHAR(8), GETDATE(), 112) AND dcSubSiteId = 0
	ELSE IF @Col = 'OneMinuteLogin'
		UPDATE PaLoginRegCount SET OneMinuteLogin = OneMinuteLogin + 1 WHERE CountDate = CONVERT(VARCHAR(8), GETDATE(), 112) AND dcSubSiteId = 0
	ELSE IF @Col = 'LoginPageLogin'
		UPDATE PaLoginRegCount SET LoginPageLogin = LoginPageLogin + 1 WHERE CountDate = CONVERT(VARCHAR(8), GETDATE(), 112) AND dcSubSiteId = 0
	ELSE IF @Col = 'LoginPageReg'
		UPDATE PaLoginRegCount SET LoginPageReg = LoginPageReg + 1 WHERE CountDate = CONVERT(VARCHAR(8), GETDATE(), 112) AND dcSubSiteId = 0		
END










GO
/****** Object:  StoredProcedure [dbo].[pcPaMailLogRegisterInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[pcPaMailLogRegisterInsert]
	@paMainID INT,
	@Email VARCHAR(50),
	@Subject VARCHAR(50),
	@Remark VARCHAR(500)
AS
BEGIN
	BEGIN TRY
		INSERT INTO paMailLog(paMainID,Email,Subject,Remark) VALUES(@paMainID,dbo.SafeSQL(@Email),dbo.SafeSQL(@Subject),dbo.SafeSQL(@Remark))
		RETURN @@IDENTITY
	END TRY
	BEGIN CATCH
		RETURN 0
	END CATCH
END














GO
/****** Object:  StoredProcedure [dbo].[pcPaMainByAllSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[pcPaMainByAllSelect]
	@ID INT
AS
BEGIN
	SELECT *,
	(SELECT TOP 1 LoginIP FROM paLoginLog WITH(NOLOCK) WHERE paLoginLog.paMainID = paMain.ID ORDER BY ID DESC) AS LastLoginIP,
	(SELECT COUNT(1) FROM paLoginLog WITH(NOLOCK) WHERE paLoginLog.paMainID = paMain.ID AND AddDate > CONVERT(VARCHAR(10), GETDATE(), 120)) AS TodayLoginNum
	FROM paMain WITH(NOLOCK INDEX(PK_paMain)) 
	WHERE ID=@ID
END














GO
/****** Object:  StoredProcedure [dbo].[pcPaMainByBackLogin]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--***********************************************************
--返回值:
--  0:未定义错误
-- -1：用户名、密码不正确
-- -2：验证码不正确
-- 正整数:正确的ID
--后台登陆用
--***********************************************************
CREATE PROCEDURE [dbo].[pcPaMainByBackLogin]
(
	@UID VARCHAR(20),
	@PaMainID INT
)
AS
BEGIN TRY
	DECLARE @ID AS INT

	SELECT TOP 1 @ID = ID
	FROM BsPaBackLogin WITH(NOLOCK)
	WHERE UnqueID=@UID
	AND HasLogin = 0
	AND PaMainID=@PaMainID

	IF @ID IS NOT NULL
	BEGIN
		UPDATE BsPaBackLogin SET HasLogin = 1 WHERE ID = @ID
		--DELETE FROM BsPaBackLogin WHERE AddDate < GETDATE()-0.2

		IF EXISTS(SELECT 'X' FROM paMain WITH(NOLOCK)
					WHERE ID=@PaMainID
				)
			RETURN 1
		ELSE
			RETURN 0		
	END
END TRY
BEGIN CATCH
	RETURN -1
END CATCH














GO
/****** Object:  StoredProcedure [dbo].[pcPaMainByCareerStatusUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--####################################
--更新求职状态
--返回值：
--	-2	求职状态为空
--####################################
CREATE PROCEDURE [dbo].[pcPaMainByCareerStatusUpdate]
(
	@PaMainID INT,
	@dcCareerStatus TINYINT,
	@IP VARCHAR(39)
)
AS
SET NOCOUNT ON
BEGIN
	SET NOCOUNT ON
	IF @dcCareerStatus IS NULL
		RETURN -2		--求职状态为空
	UPDATE paMain 
	SET dcCareerStatus = @dcCareerStatus, 
		LastModifyDate = GETDATE() 
	WHERE ID = @PaMainID
	UPDATE CvMain SET RefreshDate = GETDATE() WHERE paMainID = @paMainID
	SET NOCOUNT OFF
END
GO
/****** Object:  StoredProcedure [dbo].[pcPaMainByCvMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.31
--创建人：Nick
--说明：
--#####################################################
CREATE PROCEDURE [dbo].[pcPaMainByCvMainIDSelect]
(
	@CvMainID INT,
	@CpMainID INT
)
AS
BEGIN TRY
	SELECT a.ID paMainID,a.Name,UserName,Email,dbo.GetPaName(b.ID,@CpMainID) AS paName,b.ID
	FROM paMain a WITH(NOLOCK),cvMain b WITH(NOLOCK) 
	WHERE a.ID=b.paMainID AND b.ID=@CvMainID
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[pcPaMainByGetPasswordSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Sean
-- Create date: 2012-3-6
-- Description:	取回密码	先检查用户名是否在pamain，Resume_Xixni。如果没有结果则检查是否有邮箱
--2012.3.6 和取回前、取回后的验证、插入一起
-- =============================================
CREATE PROCEDURE [dbo].[pcPaMainByGetPasswordSelect]
(
	@Username VARCHAR(50),
	@Email VARCHAR(50),
	@Mobile VARCHAR(11),
	@IP VARCHAR(15),
	@VerifyCode VARCHAR(10),
	@SubSiteName VARCHAR(40)
)
AS
BEGIN
	DECLARE @Cnt AS INT, @Type AS VARCHAR(10), @ToDay AS DATETIME, @QueryMobile AS INT
	----如果用户名、邮箱、手机号都为空则返回
	IF LEN(ISNULL(@Username, '')) = 0 AND LEN(ISNULL(@Email, '')) = 0 AND LEN(ISNULL(@Mobile, '')) = 0
		GOTO Err3
	--SET @Mobile = ''
	----@t是返回结果临时表
	DECLARE @t AS TABLE(
		ID INT,
		Name NVARCHAR(50) NOT NULL,
		UserName VARCHAR(50) NOT NULL,
		Email VARCHAR(50) NOT NULL,
		Gender NVARCHAR(10),
		Mobile VARCHAR(13),
		ReturnType VARCHAR(10),
		UniqueId VARCHAR(40),
		ActivateCode VARCHAR(6),
		AskNo VARCHAR(40)
	)

	SELECT @Type = 'Email', @QueryMobile = 0

	IF dbo.IsMobile(@Mobile) = 1	----手机号是否合法
	BEGIN
		SET @QueryMobile = 1		----手机号合法,则优先使用手机查询
		----一天内手机取回密码次数
		SELECT @Cnt = COUNT(DISTINCT AskNo) FROM paGetPasswordLog WITH(NOLOCK) WHERE Mobile = @Mobile AND AddDate > GETDATE() - 1
		IF @Cnt >= 3					----总数=0，按手机号取回
			GOTO Err4
		SET @Type = 'Mobile'
	END

	IF @Type = 'Email'				----按油箱、用户名取回次数
	BEGIN
		SET @ToDay = CONVERT(DATETIME, CONVERT(VARCHAR(8), GETDATE(), 112))

		IF LEN(ISNULL(@Username, '')) > 0		----用户名
		BEGIN
			SELECT @Cnt = COUNT(1) FROM paGetPasswordLog WITH(NOLOCK) WHERE Username = @Username AND AddDate > @Today
			SET @Type='Username'
		END
		ELSE									----其次Email
			SELECT @Cnt = COUNT(1) FROM paGetPasswordLog WITH(NOLOCK) WHERE Email = @Email AND AddDate > @Today

		IF @Cnt > 4								----一天之内一个账号最多取回5次
			GOTO Err1

		SELECT @Cnt = COUNT(1) FROM paGetPasswordLog WITH(NOLOCK) WHERE IP = @IP AND AddDate >= @Today
		IF @Cnt > 20							----一天之内一个ip不能超过20次,很多手机是一个ip，所以不管手机了
			GOTO Err2
	END

	SELECT @Cnt = 0
	IF @QueryMobile = 1							----按照手机号查询
	BEGIN
		INSERT INTO @t(ID, Name, UserName, Email, Gender, Mobile)
		SELECT TOP 10  ID,
			ISNULL(ISNULL(CONVERT(VARCHAR(50), Name), CONVERT(VARCHAR(50), NameEng)), UserName) Name, 
			Username,			
			Email,
			CASE Gender WHEN 0 THEN '先生' WHEN 1 THEN '女士' ELSE NULL END Gender,
			Mobile
		FROM paMain WITH(NOLOCK INDEX(IX_PaMain_Mobile))
		WHERE Mobile = @Mobile
		AND MobileVerifyDate IS NOT NULL
		ORDER BY Lastlogindate DESC

		IF NOT EXISTS(SELECT 'x' FROM @t)
			GOTO Err3	
	END
	ELSE IF LEN(ISNULL(@Username, '')) > 0  --如果有用户名则以用户名为主
	BEGIN
		SET @Type='Username'
		--先查询paMain.UserName = @UserName 区分大小写
		INSERT INTO @t(ID, Name, UserName, Email, Gender, Mobile)
		SELECT TOP 1 ID,
			ISNULL(ISNULL(CONVERT(VARCHAR(50), Name), CONVERT(VARCHAR(50), NameEng)), UserName) COLLATE Chinese_PRC_CI_AS Name, 
			Username COLLATE Chinese_PRC_CI_AS,
			Email,
			CASE Gender WHEN 0 THEN '先生' WHEN 1 THEN '女士' ELSE NULL END Gender,
			Mobile
		FROM paMain WITH(NOLOCK INDEX(IX_PaMain_UserName))
		WHERE UserName = @Username

		IF (SELECT COUNT(*) FROM @t) > 0		--有值则返回
			GOTO Retu

		INSERT INTO @t(ID, Name, UserName, Email, Gender, Mobile)
		SELECT top 1 0 ID,
			Username COLLATE Chinese_PRC_CI_AS Name,
			Username COLLATE Chinese_PRC_CI_AS,
			Email,
			NULL Gender,
			NULL Mobile
		FROM Resume_Xinxi WITH(NOLOCK INDEX(IX_Resume_Xinxi_UserName)) 
		WHERE UserName = @Username

		IF (SELECT COUNT(*) FROM @t) > 0		--有值则返回
			GOTO Retu

		--先查询paMain.UserName = @UserName 不区分大小写
		INSERT INTO @t(ID, Name, UserName, Email, Gender, Mobile)
		SELECT TOP 1 ID,
			ISNULL(ISNULL(CONVERT(VARCHAR(50), Name), CONVERT(VARCHAR(50), NameEng)), UserName) COLLATE Chinese_PRC_CI_AS Name, 
			Username COLLATE Chinese_PRC_CI_AS,
			Email,
			CASE Gender WHEN 0 THEN '先生' WHEN 1 THEN '女士' ELSE NULL END Gender,
			Mobile
		FROM paMain WITH(NOLOCK INDEX(IX_PaMain_UserNameLower))
		WHERE UserNameLower = @Username
		ORDER BY Lastlogindate DESC

		IF (SELECT COUNT(*) FROM @t) > 0		--有值则返回
			GOTO Retu

		INSERT INTO @t(ID, Name, UserName, Email, Gender, Mobile)
		SELECT top 1 0 ID,
			Username COLLATE Chinese_PRC_CI_AS Name,
			Username COLLATE Chinese_PRC_CI_AS,
			Email,
			NULL Gender,
			NULL Mobile
		FROM Resume_Xinxi WITH(NOLOCK INDEX(IX_Resume_Xinxi_UserNameLower)) 
		WHERE UserNameLower = @Username

		IF NOT EXISTS(SELECT 'x' FROM @t)
			GOTO Err3
	END
	ELSE IF LEN(ISNULL(@Email, '')) > 0 ----查询paMain.Email
	BEGIN
		INSERT INTO @t(ID, Name, UserName, Email, Gender, Mobile)
		SELECT top 10 ID,
			ISNULL(ISNULL(Name, NameEng), UserName) Name, 
			Username,
			Email,
			CASE Gender WHEN 0 THEN '先生' WHEN 1 THEN '女士' ELSE NULL END Gender,
			Mobile
		FROM paMain WITH(NOLOCK INDEX(IX_paMain_Email)) 
		WHERE Email = @Email

		--IF (SELECT COUNT(*) FROM @t) > 0		--有值则返回
		--	GOTO Retu

		INSERT INTO @t(ID, Name, UserName, Email, Gender, Mobile)
		SELECT 0 ID,
			Username Name,
			Username,
			Email,
			NULL Gender,
			NULL Mobile
		FROM Resume_Xinxi WITH(NOLOCK INDEX(IX_Resume_Xinxi_Email)) 
		WHERE Email = @Email

		IF NOT EXISTS(SELECT 'x' FROM @t)
			GOTO Err3		
	END
END
Retu:	----正确返回，有数据
BEGIN
	DECLARE @AskNo AS VARCHAR(40),@ActivateCode AS VARCHAR(6)
	SELECT @AskNo = REPLACE(NEWID(), '-', ''), @ActivateCode = RAND() * 899999 + 100000
	
	UPDATE @t SET ReturnType = @Type, UniqueId = REPLACE(NEWID(), '-', ''), ActivateCode = @ActivateCode, AskNo=@AskNo		----修改返回类型，用于前台显示结果

	----记录取回纪录
	INSERT INTO PaGetPasswordLog(paMainID, UserNameIn, EmailIn, VerifyCode, IP, UserName, Email, Mobile,UniqueId,ActivateCode,AskNo)
	SELECT ID, @UserName, @Email, @VerifyCode, @IP, UserName, Email, Mobile,UniqueId, ActivateCode,@AskNo FROM @t

	IF @Type = 'Mobile' 
	BEGIN
		DECLARE @curUserName AS VARCHAR(50),@curActivateCode AS VARCHAR(10),@Msg AS VARCHAR(200),@Index AS INT	
		INSERT SmsMessageLog(SendMan, ManagerUSerId, paMainId, caMainId, Mobile, MsgType, IsCat, Msg)
		SELECT TOP 1 0, NULL, a.ID, NULL, a.Mobile, 104, 0, 
			'您好，您在' + REPLACE(@SubSiteName, 'http://', '') + '的激活码是：' + d.ActivateCode
		FROM paMain a WITH(NOLOCK), (SELECT TOP 1 ID, ActivateCode FROM @t ORDER BY ID DESC) d
		WHERE a.ID = d.Id
		AND a.Mobile > ''
		ORDER BY ID DESC
	END

	UPDATE @t SET ReturnType = @Type		----修改返回类型，用于前台显示结果

	SELECT * FROM @t ORDER BY ID DESC
	RETURN
END
Err1:	----一个账号一天取回超过5次
BEGIN
	SELECT null ID, NULL Name, NULL Username, NULL Email, NULL Gender, NULL Mobile, 1 ReturnType
	RETURN
END
Err2:	----一个ip一天取回超过20次
BEGIN
	SELECT null ID, NULL Name, NULL Username, NULL Email, NULL Gender, NULL Mobile, 2 ReturnType
	RETURN
END
Err3:	----没有取回数据
BEGIN
	SELECT null ID, NULL Name, NULL Username, NULL Email, NULL Gender, NULL Mobile, 3 ReturnType
	RETURN
END
Err4:	----手机号一天取回超过3次
BEGIN
	SELECT null ID, NULL Name, NULL Username, NULL Email, NULL Gender, NULL Mobile, 4 ReturnType
	RETURN
END














GO
/****** Object:  StoredProcedure [dbo].[pcPaMainByGetPasswordSelectNew]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[pcPaMainByGetPasswordSelectNew]
(
	@Username VARCHAR(50),
	@Email VARCHAR(50),
	@Mobile VARCHAR(11),
	@IP VARCHAR(15),
	@VerifyCode VARCHAR(10),
	@SubSiteName VARCHAR(40),
    @txtRealName NVARCHAR(10)
)
AS
BEGIN
	DECLARE @Cnt AS INT, @Type AS VARCHAR(10), @ToDay AS DATETIME, @QueryMobile AS INT
	----如果用户名、邮箱、手机号都为空则返回
	IF LEN(ISNULL(@Username, '')) = 0 AND LEN(ISNULL(@Email, '')) = 0 AND LEN(ISNULL(@Mobile, '')) = 0
		GOTO Err3
	--SET @Mobile = ''
	----@t是返回结果临时表
	DECLARE @t AS TABLE(
		ID INT,
		Name NVARCHAR(50) NOT NULL,
		UserName VARCHAR(50) NOT NULL,
		Email VARCHAR(50) NOT NULL,
		Gender NVARCHAR(10),
		Mobile VARCHAR(13),
		ReturnType VARCHAR(10),
		UniqueId VARCHAR(40),
		ActivateCode VARCHAR(6),
		AskNo VARCHAR(40)		
	)

	SELECT @Type = 'Email', @QueryMobile = 0

	IF dbo.IsMobile(@Mobile) = 1	----手机号是否合法
	BEGIN
		SET @QueryMobile = 1		----手机号合法,则优先使用手机查询
		----一天内手机取回密码次数
		SELECT @Cnt = COUNT(DISTINCT AskNo) FROM paGetPasswordLog WITH(NOLOCK) WHERE Mobile = @Mobile AND AddDate > GETDATE() - 1
		IF @Cnt >= 3					----总数=0，按手机号取回
			GOTO Err4
		
		SET @Type = 'Mobile'
	END

	IF @Type = 'Email'				----按油箱、用户名取回次数
	BEGIN
		SET @ToDay = CONVERT(DATETIME, CONVERT(VARCHAR(8), GETDATE(), 112))

		IF LEN(ISNULL(@Username, '')) > 0		----用户名
		BEGIN
			SELECT @Cnt = COUNT(1) FROM paGetPasswordLog WITH(NOLOCK) WHERE Username = @Username AND AddDate > @Today
			SET @Type='Username'
		END
		ELSE									----其次Email
			SELECT @Cnt = COUNT(1) FROM paGetPasswordLog WITH(NOLOCK) WHERE Email = @Email AND AddDate > @Today

		IF @Cnt > 4								----一天之内一个账号最多取回5次
			GOTO Err1

		SELECT @Cnt = COUNT(1) FROM paGetPasswordLog WITH(NOLOCK) WHERE IP = @IP AND AddDate >= @Today
		IF @Cnt > 20							----一天之内一个ip不能超过20次,很多手机是一个ip，所以不管手机了
			GOTO Err2
	END

	SELECT @Cnt = 0
	IF @QueryMobile = 1							----按照手机号查询
	BEGIN
		INSERT INTO @t(ID, Name, UserName, Email, Gender, Mobile)
		SELECT TOP 10  ID,
			ISNULL(ISNULL(CONVERT(VARCHAR(50), Name), CONVERT(VARCHAR(50), NameEng)), UserName) Name, 
			Username,			
			Email,
			CASE Gender WHEN 0 THEN '先生' WHEN 1 THEN '女士' ELSE NULL END Gender,
			Mobile
		FROM paMain WITH(NOLOCK INDEX(IX_PaMain_Mobile))
		WHERE Mobile = @Mobile
		AND MobileVerifyDate IS NOT NULL
		ORDER BY Lastlogindate DESC

		IF NOT EXISTS(SELECT 'x' FROM @t)
			GOTO Err3	
		IF LEN(ISNULL(@txtRealName, '')) > 0
		BEGIN
			IF NOT EXISTS(SELECT 'x' FROM @t WHERE Name = @txtRealName)  --姓名不一致
			BEGIN
				GOTO Err5
			END
			ELSE
			BEGIN
				DELETE FROM @t WHERE Name <> @txtRealName   --手机号取回的 需要姓名一致
			END
		END
	END
	ELSE IF LEN(ISNULL(@Username, '')) > 0  --如果有用户名则以用户名为主
	BEGIN
		SET @Type='Username'
		--先查询paMain.UserName = @UserName 区分大小写
		INSERT INTO @t(ID, Name, UserName, Email, Gender, Mobile)
		SELECT TOP 1 ID,
			ISNULL(ISNULL(CONVERT(VARCHAR(50), Name), CONVERT(VARCHAR(50), NameEng)), UserName) COLLATE Chinese_PRC_CI_AS Name, 
			Username COLLATE Chinese_PRC_CI_AS,
			Email,
			CASE Gender WHEN 0 THEN '先生' WHEN 1 THEN '女士' ELSE NULL END Gender,
			Mobile
		FROM paMain WITH(NOLOCK INDEX(IX_PaMain_UserName))
		WHERE UserName = @Username

		IF (SELECT COUNT(*) FROM @t) > 0		--有值则返回
			GOTO Retu

		INSERT INTO @t(ID, Name, UserName, Email, Gender, Mobile)
		SELECT top 1 0 ID,
			Username COLLATE Chinese_PRC_CI_AS Name,
			Username COLLATE Chinese_PRC_CI_AS,
			Email,
			NULL Gender,
			NULL Mobile
		FROM Resume_Xinxi WITH(NOLOCK INDEX(IX_Resume_Xinxi_UserName)) 
		WHERE UserName = @Username

		IF (SELECT COUNT(*) FROM @t) > 0		--有值则返回
			GOTO Retu

		--先查询paMain.UserName = @UserName 不区分大小写
		INSERT INTO @t(ID, Name, UserName, Email, Gender, Mobile)
		SELECT TOP 1 ID,
			ISNULL(ISNULL(CONVERT(VARCHAR(50), Name), CONVERT(VARCHAR(50), NameEng)), UserName) COLLATE Chinese_PRC_CI_AS Name, 
			Username COLLATE Chinese_PRC_CI_AS,
			Email,
			CASE Gender WHEN 0 THEN '先生' WHEN 1 THEN '女士' ELSE NULL END Gender,
			Mobile
		FROM paMain WITH(NOLOCK INDEX(IX_PaMain_UserNameLower))
		WHERE UserNameLower = @Username
		ORDER BY Lastlogindate DESC

		IF (SELECT COUNT(*) FROM @t) > 0		--有值则返回
			GOTO Retu

		INSERT INTO @t(ID, Name, UserName, Email, Gender, Mobile)
		SELECT top 1 0 ID,
			Username COLLATE Chinese_PRC_CI_AS Name,
			Username COLLATE Chinese_PRC_CI_AS,
			Email,
			NULL Gender,
			NULL Mobile
		FROM Resume_Xinxi WITH(NOLOCK INDEX(IX_Resume_Xinxi_UserNameLower)) 
		WHERE UserNameLower = @Username

		IF NOT EXISTS(SELECT 'x' FROM @t)
			GOTO Err3
	END
	ELSE IF LEN(ISNULL(@Email, '')) > 0 ----查询paMain.Email
	BEGIN
		INSERT INTO @t(ID, Name, UserName, Email, Gender, Mobile)
		SELECT top 10 ID,
			ISNULL(ISNULL(Name, NameEng), UserName) Name, 
			Username,
			Email,
			CASE Gender WHEN 0 THEN '先生' WHEN 1 THEN '女士' ELSE NULL END Gender,
			Mobile
		FROM paMain WITH(NOLOCK INDEX(IX_paMain_Email)) 
		WHERE Email = @Email

		--IF (SELECT COUNT(*) FROM @t) > 0		--有值则返回
		--	GOTO Retu

		INSERT INTO @t(ID, Name, UserName, Email, Gender, Mobile)
		SELECT 0 ID,
			Username Name,
			Username,
			Email,
			NULL Gender,
			NULL Mobile
		FROM Resume_Xinxi WITH(NOLOCK INDEX(IX_Resume_Xinxi_Email)) 
		WHERE Email = @Email

		IF NOT EXISTS(SELECT 'x' FROM @t)
			GOTO Err3		
	END
END
Retu:	----正确返回，有数据
BEGIN
	DECLARE @AskNo AS VARCHAR(40),@ActivateCode AS VARCHAR(6)
	SELECT @AskNo = REPLACE(NEWID(), '-', ''), @ActivateCode = RAND() * 899999 + 100000
	
	UPDATE @t SET ReturnType = @Type, UniqueId = REPLACE(NEWID(), '-', ''), ActivateCode = @ActivateCode, AskNo=@AskNo		----修改返回类型，用于前台显示结果

	----记录取回纪录
	INSERT INTO PaGetPasswordLog(paMainID, UserNameIn, EmailIn, VerifyCode, IP, UserName, Email, Mobile,UniqueId,ActivateCode,AskNo)
	SELECT ID, @UserName, @Email, @VerifyCode, @IP, UserName, Email, Mobile,UniqueId, ActivateCode,@AskNo FROM @t

	IF @Type = 'Mobile' 
	BEGIN
		DECLARE @curUserName AS VARCHAR(50),@curActivateCode AS VARCHAR(10),@Msg AS VARCHAR(200),@Index AS INT	
		INSERT SmsMessageLog(SendMan, ManagerUSerId, paMainId, caMainId, Mobile, MsgType, IsCat, Msg)
		SELECT TOP 1 0, NULL, a.ID, NULL, a.Mobile, 104, 0, 
			'您好，您在' + REPLACE(@SubSiteName, 'http://', '') + '的激活码是：' + d.ActivateCode
		FROM paMain a WITH(NOLOCK), (SELECT TOP 1 ID, ActivateCode FROM @t ORDER BY ID DESC) d
		WHERE a.ID = d.Id
		AND a.Mobile > ''
		ORDER BY ID DESC
	END

	UPDATE @t SET ReturnType = @Type		----修改返回类型，用于前台显示结果

	SELECT * FROM @t ORDER BY ID DESC
	RETURN
END
Err1:	----一个账号一天取回超过5次
BEGIN
	SELECT null ID, NULL Name, NULL Username, NULL Email, NULL Gender, NULL Mobile, 1 ReturnType
	RETURN
END
Err2:	----一个ip一天取回超过20次
BEGIN
	SELECT null ID, NULL Name, NULL Username, NULL Email, NULL Gender, NULL Mobile, 2 ReturnType
	RETURN
END
Err3:	----没有取回数据
BEGIN
	SELECT null ID, NULL Name, NULL Username, NULL Email, NULL Gender, NULL Mobile, 3 ReturnType
	RETURN
END
Err4:	----手机号一天取回超过3次
BEGIN
	SELECT null ID, NULL Name, NULL Username, NULL Email, NULL Gender, NULL Mobile, 4 ReturnType
	RETURN
END
Err5:	----认证手机号 姓名对应出现问题
BEGIN
	SELECT null ID, NULL Name, NULL Username, NULL Email, NULL Gender, NULL Mobile, 5 ReturnType
	RETURN
END

GO
/****** Object:  StoredProcedure [dbo].[pcPaMainByGetPasswordSelectNew1]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--个人取回密码
--harry
--2018-4-27
--修改短信激活码为实时发送
CREATE PROCEDURE [dbo].[pcPaMainByGetPasswordSelectNew1]
(
	@Username VARCHAR(50),
	@Email VARCHAR(50),
	@Mobile VARCHAR(11),
	@IP VARCHAR(15),
	@VerifyCode VARCHAR(10),
	@SubSiteName VARCHAR(40),
    @txtRealName NVARCHAR(10)
)
AS
BEGIN
	DECLARE @Cnt AS INT, @Type AS VARCHAR(10), @ToDay AS DATETIME, @QueryMobile AS INT
	----如果用户名、邮箱、手机号都为空则返回
	IF LEN(ISNULL(@Username, '')) = 0 AND LEN(ISNULL(@Email, '')) = 0 AND LEN(ISNULL(@Mobile, '')) = 0
		GOTO Err3
	--SET @Mobile = ''
	----@t是返回结果临时表
	DECLARE @t AS TABLE(
		ID INT,
		Name NVARCHAR(50) NOT NULL,
		UserName VARCHAR(50) NOT NULL,
		Email VARCHAR(50) NOT NULL,
		Gender NVARCHAR(10),
		Mobile VARCHAR(13),
		ReturnType VARCHAR(10),
		UniqueId VARCHAR(40),
		ActivateCode VARCHAR(6),
		AskNo VARCHAR(40)		
	)

	SELECT @Type = 'Email', @QueryMobile = 0

	IF dbo.IsMobile(@Mobile) = 1	----手机号是否合法
	BEGIN
		SET @QueryMobile = 1		----手机号合法,则优先使用手机查询
		----一天内手机取回密码次数
		SELECT @Cnt = COUNT(DISTINCT AskNo) FROM paGetPasswordLog WITH(NOLOCK) WHERE Mobile = @Mobile AND AddDate > GETDATE() - 1
		IF @Cnt >= 3					----总数=0，按手机号取回
			GOTO Err4
		
		SET @Type = 'Mobile'
	END

	IF @Type = 'Email'				----按油箱、用户名取回次数
	BEGIN
		SET @ToDay = CONVERT(DATETIME, CONVERT(VARCHAR(8), GETDATE(), 112))

		IF LEN(ISNULL(@Username, '')) > 0		----用户名
		BEGIN
			SELECT @Cnt = COUNT(1) FROM paGetPasswordLog WITH(NOLOCK) WHERE Username = @Username AND AddDate > @Today
			SET @Type='Username'
		END
		ELSE									----其次Email
			SELECT @Cnt = COUNT(1) FROM paGetPasswordLog WITH(NOLOCK) WHERE Email = @Email AND AddDate > @Today

		IF @Cnt > 4								----一天之内一个账号最多取回5次
			GOTO Err1

		SELECT @Cnt = COUNT(1) FROM paGetPasswordLog WITH(NOLOCK) WHERE IP = @IP AND AddDate >= @Today
		IF @Cnt > 20							----一天之内一个ip不能超过20次,很多手机是一个ip，所以不管手机了
			GOTO Err2
	END

	SELECT @Cnt = 0
	IF @QueryMobile = 1							----按照手机号查询
	BEGIN
		INSERT INTO @t(ID, Name, UserName, Email, Gender, Mobile)
		SELECT TOP 10  ID,
			ISNULL(ISNULL(CONVERT(VARCHAR(50), Name), CONVERT(VARCHAR(50), NameEng)), UserName) Name, 
			Username,			
			Email,
			CASE Gender WHEN 0 THEN '先生' WHEN 1 THEN '女士' ELSE NULL END Gender,
			Mobile
		FROM paMain WITH(NOLOCK INDEX(IX_PaMain_Mobile))
		WHERE Mobile = @Mobile
		AND MobileVerifyDate IS NOT NULL
		ORDER BY Lastlogindate DESC

		IF NOT EXISTS(SELECT 'x' FROM @t)
			GOTO Err3	
		IF LEN(ISNULL(@txtRealName, '')) > 0
		BEGIN
			IF NOT EXISTS(SELECT 'x' FROM @t WHERE Name = @txtRealName)  --姓名不一致
			BEGIN
				GOTO Err5
			END
			ELSE
			BEGIN
				DELETE FROM @t WHERE Name <> @txtRealName   --手机号取回的 需要姓名一致
			END
		END
	END
	ELSE IF LEN(ISNULL(@Username, '')) > 0  --如果有用户名则以用户名为主
	BEGIN
		SET @Type='Username'
		--先查询paMain.UserName = @UserName 区分大小写
		INSERT INTO @t(ID, Name, UserName, Email, Gender, Mobile)
		SELECT TOP 1 ID,
			ISNULL(ISNULL(CONVERT(VARCHAR(50), Name), CONVERT(VARCHAR(50), NameEng)), UserName) COLLATE Chinese_PRC_CI_AS Name, 
			Username COLLATE Chinese_PRC_CI_AS,
			Email,
			CASE Gender WHEN 0 THEN '先生' WHEN 1 THEN '女士' ELSE NULL END Gender,
			Mobile
		FROM paMain WITH(NOLOCK INDEX(IX_PaMain_UserName))
		WHERE UserName = @Username

		IF (SELECT COUNT(*) FROM @t) > 0		--有值则返回
			GOTO Retu

		INSERT INTO @t(ID, Name, UserName, Email, Gender, Mobile)
		SELECT top 1 0 ID,
			Username COLLATE Chinese_PRC_CI_AS Name,
			Username COLLATE Chinese_PRC_CI_AS,
			Email,
			NULL Gender,
			NULL Mobile
		FROM Resume_Xinxi WITH(NOLOCK INDEX(IX_Resume_Xinxi_UserName)) 
		WHERE UserName = @Username

		IF (SELECT COUNT(*) FROM @t) > 0		--有值则返回
			GOTO Retu

		--先查询paMain.UserName = @UserName 不区分大小写
		INSERT INTO @t(ID, Name, UserName, Email, Gender, Mobile)
		SELECT TOP 1 ID,
			ISNULL(ISNULL(CONVERT(VARCHAR(50), Name), CONVERT(VARCHAR(50), NameEng)), UserName) COLLATE Chinese_PRC_CI_AS Name, 
			Username COLLATE Chinese_PRC_CI_AS,
			Email,
			CASE Gender WHEN 0 THEN '先生' WHEN 1 THEN '女士' ELSE NULL END Gender,
			Mobile
		FROM paMain WITH(NOLOCK INDEX(IX_PaMain_UserNameLower))
		WHERE UserNameLower = @Username
		ORDER BY Lastlogindate DESC

		IF (SELECT COUNT(*) FROM @t) > 0		--有值则返回
			GOTO Retu

		INSERT INTO @t(ID, Name, UserName, Email, Gender, Mobile)
		SELECT top 1 0 ID,
			Username COLLATE Chinese_PRC_CI_AS Name,
			Username COLLATE Chinese_PRC_CI_AS,
			Email,
			NULL Gender,
			NULL Mobile
		FROM Resume_Xinxi WITH(NOLOCK INDEX(IX_Resume_Xinxi_UserNameLower)) 
		WHERE UserNameLower = @Username

		IF NOT EXISTS(SELECT 'x' FROM @t)
			GOTO Err3
	END
	ELSE IF LEN(ISNULL(@Email, '')) > 0 ----查询paMain.Email
	BEGIN
		INSERT INTO @t(ID, Name, UserName, Email, Gender, Mobile)
		SELECT top 10 ID,
			ISNULL(ISNULL(Name, NameEng), UserName) Name, 
			Username,
			Email,
			CASE Gender WHEN 0 THEN '先生' WHEN 1 THEN '女士' ELSE NULL END Gender,
			Mobile
		FROM paMain WITH(NOLOCK INDEX(IX_paMain_Email)) 
		WHERE Email = @Email

		--IF (SELECT COUNT(*) FROM @t) > 0		--有值则返回
		--	GOTO Retu

		INSERT INTO @t(ID, Name, UserName, Email, Gender, Mobile)
		SELECT 0 ID,
			Username Name,
			Username,
			Email,
			NULL Gender,
			NULL Mobile
		FROM Resume_Xinxi WITH(NOLOCK INDEX(IX_Resume_Xinxi_Email)) 
		WHERE Email = @Email

		IF NOT EXISTS(SELECT 'x' FROM @t)
			GOTO Err3		
	END
END
Retu:	----正确返回，有数据
BEGIN
	DECLARE @AskNo AS VARCHAR(40),@ActivateCode AS VARCHAR(6)
	SELECT @AskNo = REPLACE(NEWID(), '-', ''), @ActivateCode = RAND() * 899999 + 100000
	
	UPDATE @t SET ReturnType = @Type, UniqueId = REPLACE(NEWID(), '-', ''), ActivateCode = @ActivateCode, AskNo=@AskNo		----修改返回类型，用于前台显示结果

	----记录取回纪录
	INSERT INTO PaGetPasswordLog(paMainID, UserNameIn, EmailIn, VerifyCode, IP, UserName, Email, Mobile,UniqueId,ActivateCode,AskNo)
	SELECT ID, @UserName, @Email, @VerifyCode, @IP, UserName, Email, Mobile,UniqueId, ActivateCode,@AskNo FROM @t

	

	UPDATE @t SET ReturnType = @Type		----修改返回类型，用于前台显示结果

	SELECT * FROM @t ORDER BY ID DESC
	IF @Type = 'Mobile' 
	BEGIN 
		SELECT TOP 1 a.ID AS paMainId, a.Mobile, 104 AS MsgType, 
			'您好，您在' + REPLACE(@SubSiteName, 'http://', '') + '的激活码是：' + d.ActivateCode AS Msg
		FROM paMain a WITH(NOLOCK), (SELECT TOP 1 ID, ActivateCode FROM @t ORDER BY ID DESC) d
		WHERE a.ID = d.Id
		AND a.Mobile > ''
		ORDER BY a.ID DESC
	END
	RETURN
END
Err1:	----一个账号一天取回超过5次
BEGIN
	SELECT null ID, NULL Name, NULL Username, NULL Email, NULL Gender, NULL Mobile, 1 ReturnType
	RETURN
END
Err2:	----一个ip一天取回超过20次
BEGIN
	SELECT null ID, NULL Name, NULL Username, NULL Email, NULL Gender, NULL Mobile, 2 ReturnType
	RETURN
END
Err3:	----没有取回数据
BEGIN
	SELECT null ID, NULL Name, NULL Username, NULL Email, NULL Gender, NULL Mobile, 3 ReturnType
	RETURN
END
Err4:	----手机号一天取回超过3次
BEGIN
	SELECT null ID, NULL Name, NULL Username, NULL Email, NULL Gender, NULL Mobile, 4 ReturnType
	RETURN
END
Err5:	----认证手机号 姓名对应出现问题
BEGIN
	SELECT null ID, NULL Name, NULL Username, NULL Email, NULL Gender, NULL Mobile, 5 ReturnType
	RETURN
END

GO
/****** Object:  StoredProcedure [dbo].[pcPaMainByHideConditionsDelete]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--=============================================
-- 创建：		sean
-- 检查：		2010-10-6
-- 说明：		隐藏条件删除
--=============================================
CREATE PROCEDURE [dbo].[pcPaMainByHideConditionsDelete]
	@ID INT,
	@Shield NVARCHAR(60),
	@IP VARCHAR(30)
AS
BEGIN TRY
	DECLARE @HideConditions AS NVARCHAR(500)
	SELECT @HideConditions = ISNULL(HideConditions, '') FROM PaMain WITH(NOLOCK) WHERE ID = @ID
	SET @Shield = '<' + @Shield + '>'
	IF CHARINDEX(@Shield, @HideConditions) = 0
		RETURN 2
	ELSE
	BEGIN
		SET @HideConditions = Replace(@HideConditions, @Shield, '')
		IF @HideConditions = ''
			SET @HideConditions = NULL
		UPDATE PaMain SET HideConditions = @HideConditions WHERE ID=@ID
		INSERT INTO paOperationLog (paMainID,Operation,Details,IP)
			VALUES(@ID,50,'更新屏蔽设置成功。',@IP)
		RETURN 1
	END
END TRY
BEGIN CATCH
	RETURN 0
END CATCH
GO
/****** Object:  StoredProcedure [dbo].[pcPaMainByHideConditionsSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--=============================================
-- 创建：		sean
-- 检查：		2010-10-6
-- 说明：		隐藏条件提取
--=============================================
CREATE PROCEDURE [dbo].[pcPaMainByHideConditionsSelect]
	@ID INT,
	@HideConditions NVARCHAR(500) OUTPUT
AS
SELECT @HideConditions = ISNULL(HideConditions, '') FROM PaMain WITH(NOLOCK INDEX(PK_paMain)) WHERE ID = @ID














GO
/****** Object:  StoredProcedure [dbo].[pcPaMainByHideConditionsUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
----------------------------------------
--返回值：
-- 		4 超过100条数据
--		3超长
--		2已经存在
--		  0保存出错
--		  1保存正确
----------------------------------------
CREATE PROCEDURE [dbo].[pcPaMainByHideConditionsUpdate]
	@ID INT,
	@Shield NVARCHAR(60),
	@IP VARCHAR(30)
AS
BEGIN TRY
	DECLARE @HideConditions AS NVARCHAR(500)
	SELECT @HideConditions = ISNULL(HideConditions, '') FROM PaMain WITH(NOLOCK) WHERE ID = @ID
	SET @Shield = '<' + @Shield + '>'
	IF CHARINDEX(@Shield, @HideConditions) > 0
		RETURN 2
	ELSE
	IF LEN(@HideConditions+@Shield)>500
		RETURN 3
	--判断已经插入了多少数据
	DECLARE @temp AS NVARCHAR(500)
	SET @temp=@HideConditions
	IF len(@temp)-len(replace(@temp,'<',''))>100
	BEGIN
		RETURN 4
	END
	BEGIN
		
		
		SET @HideConditions = @Shield + @HideConditions
		UPDATE PaMain SET HideConditions = @HideConditions WHERE ID=@ID
		INSERT INTO paOperationLog (paMainID,Operation,Details,IP)
			VALUES(@ID,50,'更新屏蔽设置成功。',@IP)
		RETURN 1
	END
END TRY
BEGIN CATCH
	RETURN 0
END CATCH

GO
/****** Object:  StoredProcedure [dbo].[pcPaMainByIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.4
--创建人：John
--说明：根据id获取PaMain
--#####################################################
CREATE PROCEDURE [dbo].[pcPaMainByIDSelect]
(
	@ID INT
)
AS
BEGIN
	SELECT TOP 1 * FROM paMain WITH(NOLOCK) WHERE id=@ID
END


GO
/****** Object:  StoredProcedure [dbo].[pcpaMainByIDUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--------------------------------------------------
--修改：Nick
--修改日期：2106-3-17
--根据百度修改pamain
--------------------------------------------------
create PROCEDURE [dbo].[pcpaMainByIDUpdate]
(
	@ID INT,
	@Name VARCHAR(50),
	@Mobile VARCHAR(11),
	@BirthDay INT, 
	@LivePlace VARCHAR(6),
	@AccountPlace VARCHAR(6),
	@GrowPlace VARCHAR(6),
	@Gender BIT
)
AS
BEGIN 
	UPDATE PaMain
	SET Name  = @Name,
	BirthDay = @BirthDay,
	Mobile = @Mobile,
	LivePlace = @LivePlace,
	AccountPlace = @AccountPlace,
	GrowPlace = @GrowPlace,
	Gender = @Gender
	WHERE ID = @ID
END

GO
/****** Object:  StoredProcedure [dbo].[pcPaMainByImportUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


-- =============================================
-- Author:		Sean
-- Check date:	2013-6-21
-- Description:	修改账号信息，cvMainID为0时不修改cvmain信息 Mobile Can be null.
-- Data imported from zhaopin.com,51job.com
--修改harry 2018-7-5 处理liveplace等
-- =============================================
CREATE PROCEDURE [dbo].[pcPaMainByImportUpdate]
(
	@Type INT,
	@paMainID INT,
	@cvMainID INT,
	@Name VARCHAR(30),
	@Gender BIT,
	@BirthDay INT,
	@LivePlace VARCHAR(6),
	@AccountPlace VARCHAR(6),
	@GrowPlace VARCHAR(6),
	@Mobile VARCHAR(13),
	@OnlineContact TINYINT,
	@OnlineContactNo VARCHAR(50),
	@Homepage VARCHAR(200),
	@Marriage TINYINT,
	@Nation TINYINT,
	@Height TINYINT,
	@dcCareerStatus TINYINT,
	@IP VARCHAR(39)
)
AS
IF ISNULL(@paMainID, 0) = 0
	RETURN -1
IF dbo.TrimNULL(@Name) IS NULL
	RETURN -1
--IF dbo.TrimNULL(@Mobile) IS NULL
--	RETURN -1
IF @Marriage = 0
	SET @Marriage = NULL
IF @Height = 0
	SET @Height = NULL
IF EXISTS(SELECT 'x' FROM Person_BLACK WITH(NOLOCK) WHERE Mobile = @Mobile AND Mobile > '')
BEGIN
	----有黑名单，则增加拒绝次数
	UPDATE Person_Black SET RefuseCount = RefuseCount + 1 WHERE Mobile = @Mobile
	RETURN -1
END
BEGIN TRAN
	BEGIN TRY
		IF  CHARINDEX(' ', @LivePlace) >2
		BEGIN
			SET @LivePlace=substring(@LivePlace,1,charindex(' ',@LivePlace)-1)
		END
		IF  CHARINDEX(' ', @AccountPlace) >2
		BEGIN
			SET @AccountPlace=substring(@AccountPlace,1,charindex(' ',@AccountPlace)-1)
		END
		IF  CHARINDEX(' ', @GrowPlace) >2
		BEGIN
			SET @GrowPlace=substring(@GrowPlace,1,charindex(' ',@GrowPlace)-1)
		END
		
		
		DECLARE @NameEngOld AS VARCHAR(30)
		DECLARE @NameOld AS VARCHAR(12)
		DECLARE @OnlineContactNoOld AS VARCHAR(50)
		DECLARE @HomepageOld AS VARCHAR(200)
		DECLARE @MobileOld AS VARCHAR(13)
		DECLARE @Modify AS INT
		-- @Modify=-1未修改需审核项， @Modify=0修改中文项目； @Modify=1修改了英文项目
		SET @Modify=-1
		--检查在线联系方式和号码
		IF @OnlineContact IS NULL
			SET @OnlineContactNo = ''
		ELSE
			SET @OnlineContactNo = dbo.SafeSQL(@OnlineContactNo)
		--取消不正确的主页格式
		SET @Homepage=REPLACE(@Homepage,'http%3A//','http://')
		SET @Homepage=REPLACE(@Homepage,'http://','')
		IF LTRIM(RTRIM(@Homepage)) = 'http://'
			SET @Homepage = null
		IF ISNULL(@Homepage, '') = ''
			SET @Homepage = null
		IF ISNULL(@OnlineContactNo, '') = ''
			SET @OnlineContactNo = null

		--获得原始数据
		SELECT @NameOld=Name,@NameEngOld=NameEng,@OnlineContactNoOld=OnlineContactNo,@HomepageOld=Homepage,@MobileOld=Mobile
		FROM paMain WITH(NOLOCK INDEX(PK_paMain))
		WHERE ID = @paMainID

		--0中文，1英文，只有姓名不同
		IF @TYPE=0
		BEGIN
			DECLARE @CNAME AS VARCHAR(12)
			SET @CNAME = @Name
			UPDATE paMain
			SET Name=@CNAME,
				Gender=@Gender,
				BirthDay=@BirthDay,
				LivePlace=@LivePlace,
				AccountPlace=@AccountPlace,
				GrowPlace=@GrowPlace,
				Mobile=@Mobile,
				OnlineContact=@OnlineContact,
				OnlineContactNo=@OnlineContactNo,
				Homepage=@Homepage,
				Marriage=@Marriage, 
				Nation=@Nation,
				Height=@Height,
				--dcCareerStatus#@dcCareerStatus,
				LastModifyDate=GETDATE()
			WHERE ID=@paMainID
		END
		ELSE
			UPDATE paMain
			SET NameENG=@Name,
				Gender=@Gender,
				BirthDay=@BirthDay,
				LivePlace=@LivePlace,
				AccountPlace=@AccountPlace,
				GrowPlace=@GrowPlace,
				Mobile=@Mobile,
				OnlineContact=@OnlineContact,
				OnlineContactNo=@OnlineContactNo,
				Homepage=@Homepage,
				Marriage=@Marriage, 
				Nation=@Nation,
				Height=@Height,
				--dcCareerStatus#@dcCareerStatus,
				LastModifyDate=GETDATE()
			WHERE ID=@paMainID

		--保存到bsCvModify,姓名
		IF @TYPE=0
		BEGIN
			IF ISNULL(@NameOld, '') <> @CNAME
			BEGIN
				DELETE FROM bsCvModify WHERE paMainID = @paMainID AND Location = 'ac1'
				INSERT INTO bsCvModify(paMainID,Location,ColValue) VALUES(@paMainID,'ac1',@CNAME)
				SET @Modify=0

				INSERT INTO paOperationLog (paMainID, Operation, Details, IP) 
				VALUES(@paMainID, 30,'更新姓名，原姓名：<' + ISNULL(@NameOld, '') + '>；新姓名：<' + @CName + '>', @IP)
			END
		END
		ELSE
			IF ISNULL(@NameOld, '') <> @Name
			BEGIN
				DELETE FROM bsCvModify WHERE paMainID = @paMainID AND Location = 'ae1'
				INSERT INTO bsCvModify(paMainID,Location,ColValue) VALUES(@paMainID,'ae1',@CNAME)
				SET @Modify=1

				INSERT INTO paOperationLog (paMainID, Operation, Details, IP) 
				VALUES(@paMainID, 31,'更新英文名，原英文名：<' + ISNULL(@NameOld, '') + '>；新英文名：<' + @Name + '>', @IP)
			END

		--在线联系号码
		IF @OnlineContactNo IS NULL
			DELETE FROM bsCvModify WHERE paMainID = @paMainID AND Location = 'ac2'
		ELSE
			IF @OnlineContactNo <> ISNULL(@OnlineContactNoOld, '')
			BEGIN
				DELETE FROM bsCvModify WHERE paMainID = @paMainID AND Location = 'ac2'
				INSERT INTO bsCvModify(paMainID,Location,ColValue) VALUES(@paMainID,'ac2',@OnlineContactNo)
				SET @Modify=0
			END

		--主页
		IF @Homepage IS NULL
			DELETE FROM bsCvModify WHERE paMainID = @paMainID AND Location = 'ac3'
		ELSE
			IF @Homepage <> ISNULL(@HomepageOld, '')
			BEGIN
				DELETE FROM bsCvModify WHERE paMainID = @paMainID AND Location = 'ac3'
				INSERT INTO bsCvModify(paMainID,Location,ColValue) VALUES(@paMainID,'ac3',@Homepage)
				SET @Modify=0
			END

		--手机号码
		IF ISNULL(@MobileOld, '') <> @Mobile
		BEGIN
			DELETE FROM bsCvModify WHERE paMainID = @paMainID AND Location = 'ac4'
			--INSERT INTO bsCvModify(paMainID,Location,ColValue) VALUES(@paMainID,'ac4',@Mobile)
			--SET @Modify=0

			INSERT INTO paOperationLog (paMainID, Operation, Details, IP) 
			VALUES(@paMainID, 35,'更新手机号，原手机号：<' + ISNULL(@MobileOld, '') + '>；新手机号：<' + @Mobile + '>', @IP)
		END
		
		----修改cvMain.cvLevel
		IF @TYPE=0
		BEGIN
			IF dbo.IsMobile(@Mobile) = 1
				UPDATE cvMain SET cvLevel='11' + RIGHT(cvLevel,8) WHERE paMainID = @paMainID
			ELSE
				UPDATE cvMain SET cvLevelEng='10' + RIGHT(cvLevelEng,8) WHERE paMainID = @paMainID
		END
		ELSE
		BEGIN
			IF dbo.IsMobile(@Mobile) = 1
				UPDATE cvMain SET cvLevel='11' + RIGHT(cvLevel,8) WHERE paMainID = @paMainID
			ELSE
				UPDATE cvMain SET cvLevelEng='10' + RIGHT(cvLevelEng,8) WHERE paMainID = @paMainID
		END

		--1小时内不重复刷新，防止刷新排名
		UPDATE cvmain SET RefreshDate = GETDATE() WHERE ID=@cvMainID AND DATEADD(HOUR, 1, RefreshDate) < GETDATE() AND paMainID = @paMainID
		----12小时内只保留一次修改记录
		DELETE FROM paOperationLog WHERE paMainID=@paMainID AND Operation=11 AND AddDate>GETDATE()-0.5
		INSERT INTO paOperationLog (paMainID,Operation,Details,IP) VALUES(@paMainID,11,'更新基本信息成功。',@IP)

	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH

COMMIT TRAN
RETURN 1
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END

GO
/****** Object:  StoredProcedure [dbo].[pcPaMainByIsReceiveSmsUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Sean
-- Check date:	2010-9-17
-- Description:	修改账号信息	，cvMainID为0时不修改cvmain信息
-- =============================================
CREATE PROCEDURE [dbo].[pcPaMainByIsReceiveSmsUpdate]
(
	@paMainID INT,
	@IsReceiveSms BIT,
	@IP VARCHAR(15)
)
AS
IF ISNULL(@paMainID, 0) = 0
	RETURN -1
BEGIN TRAN
	BEGIN TRY
		INSERT INTO paOperationLog (paMainID, Operation, Details, IP) 
		VALUES(@paMainID, 60,'更改接收短信设置为' + CASE @IsReceiveSms WHEN 1 THEN '<接收短信>' ELSE '<不接收短信>' END, @IP)	

		UPDATE paMain SET IsReceiveSMS = @IsReceiveSMS WHERE ID = @paMainId
	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH

COMMIT TRAN
RETURN 1
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END














GO
/****** Object:  StoredProcedure [dbo].[pcPaMainByIsUseYourFoodSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[pcPaMainByIsUseYourFoodSelect]
(
	@Id INT
)
AS
SET NOCOUNT ON
BEGIN
	IF EXISTS(SELECT 'x' FROM ShortDb..paActStatus WITH(NOLOCK) WHERE paMainId = @id AND ActStatus = 1 AND AddDate > DATEADD(MINUTe, -5, GETDATE()))
		IF EXISTS(SELECT 'x' FROM WxFans WITH(NOLOCK) WHERE paMainId = @id AND Status = 2)
		BEGIN
			DELETE ShortDb..paActStatus WHERE paMainId = @id AND ActStatus = 1 AND AddDate > DATEADD(MINUTe, -5, GETDATE())
			UPDATE paMain SET IsUseYourFood = 1 WHERE Id = @Id
		END

	SELECT 'x' FROM paMain WHERE Id = @Id AND IsUseYourFood = 1
END

GO
/****** Object:  StoredProcedure [dbo].[pcPaMainByIsUseYourFoodUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [dbo].[pcPaMainByIsUseYourFoodUpdate]
(
	@Id INT,
	@State INT
)
AS
BEGIN
	UPDATE paMain SET IsUseYourFood = @State WHERE Id = @Id
END

GO
/****** Object:  StoredProcedure [dbo].[PcpaMainByLastLoginDateCheckUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[PcpaMainByLastLoginDateCheckUpdate]
(
	@PaMainId INT
)
AS
SET NOCOUNT ON
BEGIN
	IF NOT EXISTS(SELECT 'x' FROM paMain WITH(NOLOCK) WHERE id = @paMainId AND LastLoginDate > CONVERT(VARCHAR(10), GETDATE(), 120))
		UPDATE paMain SET LastLoginDate = GETDATE() WHERE Id = @paMAinId
END
GO
/****** Object:  StoredProcedure [dbo].[pcPaMainByLastLoginDateUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[pcPaMainByLastLoginDateUpdate]
(
	@PaMainId INT,
	@dcSubSiteID INT,
	@Ip VARCHAR(31),
	@browser VARCHAR(500)
)
AS
SET NOCOUNT ON
BEGIN
	DECLARE	@LoginFrom AS TINYINT
	IF LEFT(@Browser, 3) = 'fm='
		SELECT @LoginFrom = 42 --, @Browser = REPLACE(@Browser, 'ismobile:', '')
	ELSE IF LEFT(@Browser, 3) = 'fp=' AND @LoginFrom IS NULL
		SET @LoginFrom = 19
	ELSE
		SET @LoginFrom = 43  --1

	UPDATE PaMain Set LastLoginDate=GETDATE() WHERE ID = @PaMainId
	IF NOT EXISTS(SELECT 'x' FROM paLoginLog WITH(NOLOCK) WHERE paMainID = @PaMainId AND AddDate >= CONVERT(VARCHAR(10), GETDATE(), 120))
	BEGIN
		UPDATE DateReport
		SET PersonLoginNum_Net = PersonLoginNum_Net + 1  
		WHERE CountDate = CONVERT(VARCHAR(8), GETDATE(), 112)
		AND Province_Id = @dcSubSiteID

		--INSERT INTO PaMainDateReport SELECT @PaMainId, 11, GETDATE()	--sean 20130708
		INSERT INTO paLoginLog(paMainID, LoginIP, Browser, LoginFrom) VALUES(@PaMainId, @IP, ISNULL(@browser, 'Null'), @LoginFrom)
	END
END

GO
/****** Object:  StoredProcedure [dbo].[pcpaMainByLoginSELECT]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--lambo 20140904 
--个人登陆查询账号列表
CREATE PROCEDURE [dbo].[pcpaMainByLoginSELECT]
(
	@UserName VARCHAR(50)
)
AS
SET NOCOUNT ON
--INSERT INTO a1 SELECT @UserName, GETDATE()
BEGIN 
	DECLARE @T TABLE(
		ID INT,
		Password VARCHAR(60),
		UserName VARCHAR(50),
		UserNameLower VARCHAR(50),
		Mobile VARCHAR(13),
		LoginType TINYINT
	)
	IF dbo.ISMobile(@UserName)=1 
	BEGIN
		INSERT INTO @T(ID, Password, UserName, UserNameLower, Mobile, LoginType)
		SELECT ID, Password, UserName, UserNameLower,Mobile,1 
		FROM PaMain WITH(INDEX(IX_paMain_Mobile)) 
		WHERE Mobile = @UserName
		AND MobileVerifyDate IS NOT NULL
	END

	INSERT INTO @T(ID, Password, UserName, UserNameLower, Mobile, LoginType)
	SELECT ID, Password, UserName, UserNameLower,Mobile,2
	FROM PaMain WITH(NOLOCK) 
	WHERE UserNameLower = @UserName
	SELECT * FROM @T
END





GO
/****** Object:  StoredProcedure [dbo].[pcpaMainByLoginUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--------------------------------------------------
--修改：sean
--修改日期：2010-9-15
--说明：个人用户登陆	增加从Resume_Xinxi导数据的步骤
--2010-12-27 sean 修改个人第一次登录时 注册时间改为信息员推广时间
--密码加密后登录，2012-09-05修改 NIck
--------------------------------------------------
CREATE PROCEDURE [dbo].[pcpaMainByLoginUpdate]
(
	@UserName VARCHAR(50),
	@PlainPassword VARCHAR(50),
	@Password VARCHAR(60),
	@IP VARCHAR(31),
	@dcSubSiteId SMALLINT,
	@AutoLogin TINYINT,
	@browser VARCHAR(500),
	@ID INT,
	@IDType INT
)
AS
SET NOCOUNT ON
BEGIN TRY
	BEGIN TRAN
		DECLARE
			@Resume_XinxiID AS INT,
			@AddMan AS INT,
			@AddDate AS DATETIME,
			@Email AS VARCHAR(50),
			@CountDate AS INT,
			@dcProvinceID AS TINYINT,
			@TotalLoginNum AS INT,
			@LastLoginDate AS SMALLDATETIME,
			@LoginFrom AS TINYINT,
			@PaType INT

		IF LEFT(@Browser, 9) = 'ismobile:'
			SELECT @LoginFrom = 5, @Browser = REPLACE(@Browser, 'ismobile:', '')
		ELSE
			SELECT @LoginFrom = 1, @Browser = '53:' + @Browser

		SET @UserName = REPLACE(@UserName, ' ', '')
		SELECT @CountDate = CONVERT(VARCHAR(8), GETDATE(), 112), @dcProvinceID = LEFT(@dcSubSiteId, 2)
		SET @PaType = @IDType
		BEGIN TRY
			IF @PaType = 3
			BEGIN
				SELECT @Resume_XinxiID = ID, @AddMan =AddMan, @AddDate = RegDate, @Email = Email
				FROM Resume_Xinxi WITH(NOLOCK INDEX(IX_Resume_Xinxi_UserName))
				WHERE UserName = @UserName AND Password = @PlainPassword
				IF @Resume_XinxiID IS NOT NULL
					SET @PaType = 2
			END			
			ELSE IF @PaType=0
			BEGIN
				SELECT TOP 1 @Resume_XinxiID = ID, @AddMan =AddMan, @AddDate = RegDate, @Email = Email
				FROM Resume_Xinxi WITH(NOLOCK INDEX(IX_Resume_Xinxi_UserNameLower))
				WHERE UserNameLower = @UserName AND Password = @PlainPassword
				ORDER BY ID DESC

				IF @Resume_XinxiID IS NOT NULL
					SET @PaType = 4
			END

			IF @PaType = 0
				GOTO Err1

			IF @Resume_XinxiID > 0	----账号在Resume_xinxi
			BEGIN
				--lucifer添加，添加新的注册模式
				DECLARE @RegisterFrom AS TINYINT
				SELECT @RegisterFrom = 1
				IF CHARINDEX('ios',LOWER(@browser)) > 0
					SELECT @RegisterFrom = 3
				ELSE IF CHARINDEX('android',LOWER(@browser)) > 0
					SELECT @RegisterFrom = 2

				--把数据从Resume_Xini转换到paMain
				INSERT INTO paMain(RegisterMode, AddMan, UserName, Password, Email, dcProvinceID, dcSubSiteId, RegisterIP, IsDefaultPassword, AddDate, RegisterFrom, RegisterType, SpreadDate)
				VALUES(1, @AddMan, @UserName, @Password, @Email, @dcProvinceID, @dcSubSiteId, @IP, 1, GETDATE(), @RegisterFrom, 101, @AddDate)
				SET @ID = @@IDENTITY
				INSERT INTO paOperationLog (paMainID, Operation, Details, IP) VALUES(@ID, 10, '导入个人账号成功。', @IP)

				--记录日报
				UPDATE DateReport SET ValidResume = ValidResume + 1
				WHERE province_id = @dcSubSiteID AND CountDate = @CountDate
				INSERT INTO pamainDatereport SELECT @ID, 9, GETDATE() -- SEAN 20130911
				--统计信息员注册数据
				SELECT TOP 1 CountDate
				FROM Info_Datereport WITH(NOLOCK)
				WHERE CountDate = @CountDate
				AND province_id = @dcProvinceID
				AND InfoManager_ID = @AddMan
				IF (@@ROWCOUNT=0)
					INSERT INTO Info_DateReport(province_id,infomanager_id,countdate) 
					VALUES(@dcProvinceID, @AddMan, @CountDate)
				
				UPDATE Info_Datereport 
				SET ValidResume=ValidResume + 1  
				WHERE CountDate=@CountDate
				AND province_id=@dcProvinceID
				AND InfoManager_ID = @AddMan
			END

			--超过登陆次数,每天限制登录次数位20次
			IF (SELECT COUNT(1) FROM paLoginLog WITH(NOLOCK) WHERE paMainID = @ID AND AddDate > CONVERT(VARCHAR(10), GETDATE(), 120)) > 19
				GOTO ERR2

			--登陆日志
			SELECT @LastLoginDate = LastLoginDate, @TotalLoginNum = TotalLoginNum FROM paMain WITH(NOLOCK) WHERE ID = @Id

			IF CONVERT(VARCHAR(8), @LastLoginDate, 112) = CONVERT(VARCHAR(8), GETDATE(), 112)	--今天已经登陆过
			BEGIN
				IF @AutoLogin = 0			--首页的自动登录不计算在每日登陆次数
				BEGIN
					IF NOT EXISTS(SELECT 'x' FROM paLoginLog WITH(NOLOCK) WHERE paMainID = @ID AND AddDate > CONVERT(VARCHAR(10), GETDATE(), 120))
					BEGIN
						UPDATE DateReport
						SET PersonLoginNum_Net = PersonLoginNum_Net + 1  
						WHERE CountDate = CONVERT(VARCHAR(8), GETDATE(), 112)
						AND Province_Id = @dcSubSiteID
					
						SELECT @TotalLoginNum = @TotalLoginNum + 1
					END
					INSERT INTO paLoginLog(paMainID, LoginIP, Browser, LoginFrom) VALUES(@ID, @IP, '1:' + ISNULL(@browser, 'Null'), @LoginFrom)
				END
				ELSE
					SELECT @TotalLoginNum = @TotalLoginNum + 1			

				IF @LastLoginDate < DATEADD(HOUR, -1, GETDATE())	--登录间隔>1小时更新登录时间
					UPDATE paMain SET LastLoginDate = GETDATE(), TotalLoginNum = @TotalLoginNum WHERE ID = @ID
				ELSE
					UPDATE paMain SET TotalLoginNum = @TotalLoginNum WHERE ID = @ID
			END
			ELSE
			BEGIN
				----今天第一次登录
				INSERT INTO paLoginLog(paMainID, LoginIP, Browser, LoginFrom) VALUES(@ID, @IP, '2:' + ISNULL(@browser, 'Null'), @LoginFrom)
				SELECT @TotalLoginNum = @TotalLoginNum + 1

				UPDATE paMain SET TotalLoginNum = @TotalLoginNum, LastLoginDate = GETDATE() WHERE ID = @ID

				UPDATE DateReport
				SET PersonLoginNum_Net = PersonLoginNum_Net + 1  
				WHERE CountDate = CONVERT(VARCHAR(8), GETDATE(), 112)
				AND Province_Id = @dcSubSiteID

				--INSERT INTO PaMainDateReport SELECT @Id, 11, GETDATE()	--sean 20130708
			END
		END TRY
		BEGIN CATCH
			GOTO Err3
		END CATCH
	COMMIT
	RETURN @ID
	ERR1:
	BEGIN
		ROLLBACK TRAN
		INSERT INTO LogDb..RegisterErrorLog SELECT @ID, '0|' + LTRIM(STR(@IDType)) + '|' + @IP, @UserName + ' ' + @PlainPassword, GETDATE()
		RETURN 0
	END
	ERR2:
	BEGIN
		ROLLBACK TRAN
		INSERT INTO LogDb..RegisterErrorLog SELECT @ID, '-1|' + LTRIM(STR(@IDType)) + '|' + @IP, @UserName + ' ' + @PlainPassword, GETDATE()
		RETURN -1
	END
	ERR3:
	BEGIN
		ROLLBACK TRAN
		INSERT INTO LogDb..RegisterErrorLog SELECT @ID, '-2|' + LTRIM(STR(@IDType)) + '|' + @IP, @UserName + ' ' + @PlainPassword, GETDATE()
		RETURN -2
	END
END TRY
BEGIN CATCH
	ROLLBACK TRAN
	INSERT INTO LogDb..RegisterErrorLog
	SELECT @ID, '9|' + LTRIM(STR(@IDType)) + '|' + @IP, @UserName + ' ' + @PlainPassword, GETDATE()
END CATCH

GO
/****** Object:  StoredProcedure [dbo].[pcpaMainByLoginUpdateNew]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--------------------------------------------------
--修改：sean
--修改日期：2010-9-15
--说明：个人用户登陆	增加从Resume_Xinxi导数据的步骤
--2010-12-27 sean 修改个人第一次登录时 注册时间改为信息员推广时间
--密码加密后登录，2012-09-05修改 NIck
--修改:Peter 提取LoginFrom  以便统计登录来源，删掉Broser前缀
--修改:Carl 来源于毕业生信息网的账号 第一次登录时 简历状态改为公开
--lucifer 2018-2-24
--------------------------------------------------
CREATE PROCEDURE [dbo].[pcpaMainByLoginUpdateNew]
(
	@UserName VARCHAR(50),
	@PlainPassword VARCHAR(50),
	@Password VARCHAR(60),
	@IP VARCHAR(31),
	@dcSubSiteId SMALLINT,
	@AutoLogin TINYINT,
	@browser VARCHAR(500),
	@ID INT,
	@IDType INT,
	@LoginFrom TINYINT
)
AS
SET NOCOUNT ON
BEGIN TRY
	BEGIN TRAN
		DECLARE
			@Resume_XinxiID AS INT,
			@AddMan AS INT,
			@AddDate AS DATETIME,
			@Email AS VARCHAR(50),
			@CountDate AS INT,
			@dcProvinceID AS TINYINT,
			@TotalLoginNum AS INT,
			@LastLoginDate AS SMALLDATETIME,
			@PaType INT

		--SELECT @LoginFrom = 1, @Browser = '54:' + @Browser

		SET @UserName = REPLACE(@UserName, ' ', '')
		SELECT @CountDate = CONVERT(VARCHAR(8), GETDATE(), 112), @dcProvinceID = LEFT(@dcSubSiteId, 2)
		SET @PaType = @IDType
		BEGIN TRY
			--第一次登录Carl
			IF EXISTS (SELECT 'X' FROM paMain WITH(NOLOCK) WHERE RegisterType=200 AND Id=@ID AND TotalLoginNum=1)
				UPDATE cvMain SET IscvHidden=0 WHERE paMainId=@ID

			IF @PaType = 3
			BEGIN
				SELECT @Resume_XinxiID = ID, @AddMan =AddMan, @AddDate = RegDate, @Email = Email
				FROM Resume_Xinxi WITH(NOLOCK INDEX(IX_Resume_Xinxi_UserName))
				WHERE UserName = @UserName AND Password = @PlainPassword
				IF @Resume_XinxiID IS NOT NULL
					SET @PaType = 2
			END			
			ELSE IF @PaType=0
			BEGIN
				SELECT TOP 1 @Resume_XinxiID = ID, @AddMan =AddMan, @AddDate = RegDate, @Email = Email
				FROM Resume_Xinxi WITH(NOLOCK INDEX(IX_Resume_Xinxi_UserNameLower))
				WHERE UserNameLower = @UserName AND Password = @PlainPassword
				ORDER BY ID DESC

				IF @Resume_XinxiID IS NOT NULL
					SET @PaType = 4
			END

			IF @PaType = 0
				GOTO Err1

			IF @Resume_XinxiID > 0	----账号在Resume_xinxi
			BEGIN
				--lucifer添加，添加新的注册模式
				DECLARE @RegisterFrom AS TINYINT
				SELECT @RegisterFrom = 1
				IF CHARINDEX('ios',LOWER(@browser)) > 0
					SELECT @RegisterFrom = 3
				ELSE IF CHARINDEX('android',LOWER(@browser)) > 0
					SELECT @RegisterFrom = 2

				--把数据从Resume_Xini转换到paMain
				INSERT INTO paMain(RegisterMode, AddMan, UserName, Password, Email, dcProvinceID, dcSubSiteId, RegisterIP, IsDefaultPassword, AddDate, RegisterFrom, RegisterType, SpreadDate)
				VALUES(1, @AddMan, @UserName, @Password, @Email, @dcProvinceID, @dcSubSiteId, @IP, 1, GETDATE(), @RegisterFrom, 101, @AddDate)
				SET @ID = @@IDENTITY
				INSERT INTO paOperationLog (paMainID, Operation, Details, IP) VALUES(@ID, 10, '导入个人账号成功。', @IP)

				--记录日报
				UPDATE DateReport SET ValidResume = ValidResume + 1
				WHERE province_id = @dcSubSiteID AND CountDate = @CountDate
				INSERT INTO pamainDatereport SELECT @ID, 9, GETDATE() -- SEAN 20130911
				--统计信息员注册数据
				SELECT TOP 1 CountDate
				FROM Info_Datereport WITH(NOLOCK)
				WHERE CountDate = @CountDate
				AND province_id = @dcProvinceID
				AND InfoManager_ID = @AddMan
				IF (@@ROWCOUNT=0)
					INSERT INTO Info_DateReport(province_id,infomanager_id,countdate) 
					VALUES(@dcProvinceID, @AddMan, @CountDate)
				
				UPDATE Info_Datereport 
				SET ValidResume=ValidResume + 1  
				WHERE CountDate=@CountDate
				AND province_id=@dcProvinceID
				AND InfoManager_ID = @AddMan
			END

			--超过登陆次数,每天限制登录次数位20次
			IF (SELECT COUNT(1) FROM paLoginLog WITH(NOLOCK) WHERE paMainID = @ID AND AddDate > CONVERT(VARCHAR(10), GETDATE(), 120)) > 19
				GOTO ERR2

			--登陆日志
			SELECT @LastLoginDate = LastLoginDate, @TotalLoginNum = TotalLoginNum FROM paMain WITH(NOLOCK) WHERE ID = @Id

			IF CONVERT(VARCHAR(8), @LastLoginDate, 112) = CONVERT(VARCHAR(8), GETDATE(), 112)	--今天已经登陆过
			BEGIN
				IF @AutoLogin = 0			--首页的自动登录不计算在每日登陆次数
				BEGIN
					IF NOT EXISTS(SELECT 'x' FROM paLoginLog WITH(NOLOCK) WHERE paMainID = @ID AND AddDate > CONVERT(VARCHAR(10), GETDATE(), 120))
					BEGIN
						UPDATE DateReport
						SET PersonLoginNum_Net = PersonLoginNum_Net + 1  
						WHERE CountDate = CONVERT(VARCHAR(8), GETDATE(), 112)
						AND Province_Id = @dcSubSiteID
					
						SELECT @TotalLoginNum = @TotalLoginNum + 1
					END
					INSERT INTO paLoginLog(paMainID, LoginIP, Browser, LoginFrom) VALUES(@ID, @IP, ISNULL(@browser, 'Null'), @LoginFrom)
				END
				ELSE
					SELECT @TotalLoginNum = @TotalLoginNum + 1			

				IF @LastLoginDate < DATEADD(HOUR, -1, GETDATE())	--登录间隔>1小时更新登录时间
					UPDATE paMain SET LastLoginDate = GETDATE(), TotalLoginNum = @TotalLoginNum WHERE ID = @ID
				ELSE
					UPDATE paMain SET TotalLoginNum = @TotalLoginNum WHERE ID = @ID
			END
			ELSE
			BEGIN
				----今天第一次登录
				INSERT INTO paLoginLog(paMainID, LoginIP, Browser, LoginFrom) VALUES(@ID, @IP, ISNULL(@browser, 'Null'), @LoginFrom)
				SELECT @TotalLoginNum = @TotalLoginNum + 1

				UPDATE paMain SET TotalLoginNum = @TotalLoginNum, LastLoginDate = GETDATE() WHERE ID = @ID

				UPDATE DateReport
				SET PersonLoginNum_Net = PersonLoginNum_Net + 1  
				WHERE CountDate = CONVERT(VARCHAR(8), GETDATE(), 112)
				AND Province_Id = @dcSubSiteID

				--INSERT INTO PaMainDateReport SELECT @Id, 11, GETDATE()	--sean 20130708
			END
		END TRY
		BEGIN CATCH
			GOTO Err3
		END CATCH
	COMMIT
	RETURN @ID
	ERR1:
	BEGIN
		ROLLBACK TRAN
		INSERT INTO LogDb..RegisterErrorLog SELECT @ID, 'a|' + LTRIM(STR(@IDType)) + '|' + @IP, @UserName + ' ' + @PlainPassword, GETDATE()
		RETURN 0
	END
	ERR2:
	BEGIN
		ROLLBACK TRAN
		INSERT INTO LogDb..RegisterErrorLog SELECT @ID, 'b|' + LTRIM(STR(@IDType)) + '|' + @IP, @UserName + ' ' + @PlainPassword, GETDATE()
		RETURN -1
	END
	ERR3:
	BEGIN
		ROLLBACK TRAN
		INSERT INTO LogDb..RegisterErrorLog SELECT @ID, 'c|' + LTRIM(STR(@IDType)) + '|' + @IP, @UserName + ' ' + @PlainPassword, GETDATE()
		RETURN -2
	END
END TRY
BEGIN CATCH
	ROLLBACK TRAN
	INSERT INTO LogDb..RegisterErrorLog
	SELECT @ID, 'd|' + LTRIM(STR(@IDType)) + '|' + @IP, @UserName + ' ' + @PlainPassword, GETDATE()
END CATCH

GO
/****** Object:  StoredProcedure [dbo].[pcPaMainByMobileExist]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Sean
-- Create date: 2012-2-6
-- Description:	根据手机号取回密码，取回最新的5条
-- =============================================
CREATE PROCEDURE [dbo].[pcPaMainByMobileExist]
(
	@Mobile VARCHAR(11)
)
AS
BEGIN
	IF(dbo.IsMobile(@Mobile) = 0)
		RETURN -1

	IF EXISTS(SELECT 'x' FROM paMain WITH(NOLOCK) WHERE Mobile = @Mobile)
		RETURN 1
	ELSE
		RETURN 0
END














GO
/****** Object:  StoredProcedure [dbo].[pcPaMainByMobileSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Lambo 20140909
-- 根据手机号取回个人用户，用于验证是否认证过手机号
-- =============================================
CREATE PROCEDURE [dbo].[pcPaMainByMobileSelect]
(
	@Mobile VARCHAR(11)
)
AS
BEGIN
	IF(dbo.IsMobile(@Mobile) = 0)
		RETURN -1

	SELECT Id, MobileVerifyDate FROM paMain WITH(INDEX(IX_paMain_Mobile)) 
	WHERE Mobile = @Mobile 
	AND MobileVerifyDate IS NOT NULL
END





GO
/****** Object:  StoredProcedure [dbo].[pcPaMainByMobileUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- 检查:		Sean
-- 日期:		2010-10-5
-- 描述:		修改手机号,首先检查是否在手机黑名单
-- =============================================
CREATE PROCEDURE [dbo].[pcPaMainByMobileUpdate]
(
	@ID INT,
	@Mobile VARCHAR(13),
	@IP VARCHAR(31)
)
AS
IF EXISTS(SELECT 'x' FROM Person_BLACK WITH(NOLOCK) WHERE Mobile = @Mobile)
BEGIN
	----有黑名单，则增加拒绝次数
	UPDATE Person_Black SET RefuseCount = RefuseCount + 1 WHERE Mobile = @Mobile
	RETURN -1
END
BEGIN TRAN
	DECLARE @MobileOld VARCHAR(13)
	
	SELECT @MobileOld = ISNULL(Mobile ,'') FROM paMain WITH(NOLOCK INDEX(PK_paMain)) WHERE ID=@ID
	IF @MobileOld <> @Mobile
	BEGIN
		UPDATE paMain SET Mobile = @Mobile, LastModifyDate=GETDATE() WHERE ID =@ID
		INSERT INTO paOperationLog (paMainID,Operation,Details,IP) 
		VALUES(@ID,35,'更新手机号码，原号码：<'+@MobileOld +'>；新手机号码：<'+@Mobile+'>', @IP)
	END
COMMIT
RETURN 1
ERR1:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END














GO
/****** Object:  StoredProcedure [dbo].[pcPaMainByMobileUpdateNew]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[pcPaMainByMobileUpdateNew]
(
	@ID INT,
	@Mobile VARCHAR(13),
	@IP VARCHAR(31),
	@VerifyCode VARCHAR(6)
)
AS
BEGIN
	IF EXISTS(SELECT 'x' FROM Person_BLACK WITH(NOLOCK) WHERE Mobile = @Mobile)
	BEGIN
		----有黑名单，则增加拒绝次数
		UPDATE Person_Black SET RefuseCount = RefuseCount + 1 WHERE Mobile = @Mobile
		RETURN -1
	END

	BEGIN
		----验证验证码是否正确
		DECLARE @paVerifyLogID AS INT
		SET @paVerifyLogID = 0	
		SELECT @paVerifyLogID = ID FROM paVerifyLog WHERE Mobile = @Mobile AND VerifyCode = @VerifyCode AND AddDate>DATEADD(HOUR, -1, GETDATE())
	
		IF @paVerifyLogID = 0
			RETURN 0

	END
	BEGIN TRY
		DECLARE @MobileOld VARCHAR(13)
		SELECT @MobileOld = ISNULL(Mobile ,'') FROM paMain WITH(NOLOCK INDEX(PK_paMain)) WHERE ID=@ID AND MobileVerifyDate IS NOT NULL
		IF NOT EXISTS(SELECT 'x' FROM PaMain WITH(NOLOCK) WHERE ID = @ID AND MobileVerifyDate IS NOT NULL AND Mobile = @Mobile)
		BEGIN
			UPDATE paMain SET Mobile = @Mobile, LastModifyDate=GETDATE() WHERE ID = @ID
			
	
			---- 把该手机号的其他账号状态修改为未认证
			UPDATE paMain SET MobileVerifyDate = NULL WHERE mobile = @Mobile

			UPDATE paMain SET MobileVerifyDate=GETDATE() WHERE ID =@ID

			INSERT INTO paOperationLog (paMainID,Operation,Details,[IP]) 
			VALUES(28404611,35,'更新手机号码，原号码：<'+ISNULL(@MobileOld,'')+'>；新手机号码：<'+@Mobile+'>', @IP)
			
		END

		RETURN 1
	END TRY
	BEGIN CATCH
		RETURN 0
	END CATCH

END
GO
/****** Object:  StoredProcedure [dbo].[pcPaMainByMobileVerifyDateUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[pcPaMainByMobileVerifyDateUpdate]
(
	@ID INT,
	@PaMainID INT,
	@Mobile VARCHAR(13),
	@dcCareerStatus TINYINT,
	@IP VARCHAR(39),
	@VerifyCode VARCHAR(6)
)
AS
SET NOCOUNT ON
SET @Mobile = dbo.TextTrim(@Mobile)

IF @Mobile IS NULL OR @dcCareerStatus IS NULL
	RETURN -2		--手机号或求职状态为空

IF EXISTS(SELECT 'x' FROM Person_BLACK WITH(NOLOCK) WHERE Mobile = @Mobile)
BEGIN
	----有黑名单，则增加拒绝次数
	UPDATE Person_Black SET RefuseCount = RefuseCount + 1 WHERE Mobile = @Mobile
	RETURN -1
END

IF @ID > 0
	IF NOT EXISTS(SELECT 'x' FROM cvMain WITH(NOLOCK) WHERE ID = @ID AND paMainID = @paMainID)
		RETURN -3


----验证验证码是否正确
DECLARE @paVerifyLogID AS INT
SET @paVerifyLogID = 0	
SELECT @paVerifyLogID = ID FROM paVerifyLog WHERE Mobile = @Mobile AND VerifyCode = @VerifyCode AND AddDate>DATEADD(HOUR, -1, GETDATE())
	
IF @paVerifyLogID = 0
RETURN 0



BEGIN TRAN 
	BEGIN TRY
		--如果新旧日志不相同，记录更新手机号的操作
		DECLARE @MobileOld AS VARCHAR(13)
		SELECT @MobileOld = Mobile FROM paMain WITH(NOLOCK) WHERE ID = @paMAinID
		IF ISNULL(@MobileOld, '') <> @Mobile
			INSERT INTO paOperationLog (paMainID, Operation, Details, IP) 
			VALUES(@paMainID, 35,'更新手机号，原手机号：<' + ISNULL(@MobileOld, '') + '>；新手机号：<' + @Mobile + '>', @IP)

		UPDATE paMain SET Mobile = @mobile, dcCareerStatus = @dcCareerStatus, 
			LastModifyDate = GETDATE() WHERE ID = @PaMainID
		UPDATE paMain SET MobileVerifyDate = GETDATE() WHERE ID = @PaMainID
		UPDATE paMain SET MobileVerifyDate = null WHERE Mobile = @mobile AND ID <> @PaMainID
		IF @ID > 0
			UPDATE CvMain SET RefreshDate = GETDATE() WHERE paMainID = @paMainID AND ID = @ID
		ELSe
			UPDATE CvMain SET RefreshDate = GETDATE() WHERE paMainID = @paMainID
	END TRY
	BEGIN CATCH
		GOTO Err
	END CATCH
COMMIT TRAN
RETURN 1
Err:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END

GO
/****** Object:  StoredProcedure [dbo].[pcPaMainByNoticeUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--创建时间：2015.11.09
--创建人：nick  
--说明：修改是否提醒
--##################################################### 
CREATE PROCEDURE [dbo].[pcPaMainByNoticeUpdate]
(
	@PaMainID INT,
	@Type INT ,--1是否app 2是否邮件 3是否微信
	@IsNotice INT
)
AS
BEGIN
	IF @Type = 1
	BEGIN
		UPDATE Pamain SET IsAppNotice = @IsNotice WHERE ID = @PaMainID
	END
	ELSE IF @Type = 2
	BEGIN
		UPDATE Pamain SET IsEmailNotice = @IsNotice WHERE ID = @PaMainID
	END
	ELSE IF @Type = 3
	BEGIN
		UPDATE Pamain SET IsWeixinNotice = @IsNotice WHERE ID = @PaMainID
	END
	ELSE IF @Type = 4
	BEGIN
		UPDATE Pamain SET IsAppJobFinder = @IsNotice WHERE ID = @PaMainID
	END
	ELSE IF @Type = 5
	BEGIN
		UPDATE Pamain SET IsEmailJobFinder = @IsNotice WHERE ID = @PaMainID
	END
	ELSE IF @Type = 6
	BEGIN
		UPDATE Pamain SET IsWeixinJobFinder = @IsNotice WHERE ID = @PaMainID
	END
END

GO
/****** Object:  StoredProcedure [dbo].[pcPaMainByPasswordUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- 检查:		Sean
-- 日期:		2010-10-5
-- 描述:		修改密码
-- =============================================
CREATE PROCEDURE [dbo].[pcPaMainByPasswordUpdate]
	@ID INT,
	@Password VARCHAR(50),
	@PasswordOld VARCHAR(50),
	@IP VARCHAR(50)
AS
BEGIN TRY
	UPDATE paMain SET Password = @Password, IsDefaultPassword = 0 WHERE ID=@ID AND Password = @PasswordOld
	IF @@RowCount =0
		RETURN 0
	ELSE
		INSERT INTO paOperationLog (paMainID,Operation,Details,IP) VALUES(@ID,21,'更新密码，原密码：<'+@PasswordOld +'>；新密码：<'+@Password+'>', @IP)
	RETURN 1
END TRY
BEGIN CATCH
	RETURN 0
END CATCH














GO
/****** Object:  StoredProcedure [dbo].[pcPaMainByPtCvInvitationInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE  [dbo].[pcPaMainByPtCvInvitationInsert]
(
	@Email VARCHAR(50),
	@Mobile VARCHAR(11),
	@Password VARCHAR(60),
	@dcSubSiteID SMALLINT,
	@RegisterIP VARCHAR(50)
)
AS
SET NOCOUNT ON
BEGIN
	DECLARE @RegisterFrom AS VARCHAR(5), @RegisterType AS VARCHAR(5)
	SELECT @RegisterFrom = 1, @RegisterType = 151

	----在黑名单中则终止
	IF LEN(@Email) > 6 AND EXISTS(SELECT 'X' FROM Person_Black WITH(NOLOCK) WHERE Email = @Email)
	BEGIN
		UPDATE Person_black SET refusecount = refusecount + 1 where email = @Email
		RETURN -1
	END

	----在paMain中邮件重复则终止，新注册的都要是新邮箱
	IF EXISTS(SELECT 'X' FROM paMain WITH(NOLOCK) WHERE EMail = @Email)
		RETURN -2

	DECLARE @MaxId AS INT, @AddMan SMALLINT, @RegisterMode TINYINT, @dcProvinceID TINYINT, @RegDate DATETIME
	SELECT @RegisterMode = 0, @dcProvinceID = LEFT(@dcSubSiteID, 2)

	--160天内，是否推广邮件，IsHistory有计划任务保证
	SELECT TOP 1 @AddMan = AddMan, @RegDate = RegDate FROM Resume_Xinxi WITH( INDEX(IX_Resume_Xinxi_Email) NOLOCK)
	WHERE Email = @Email AND IsHistory = 0
	AND Province_ID = @dcProvinceID
	ORDER BY RegDate DESC

	----是160天内推广的
	IF @AddMan > 0
		SELECT @RegisterMode = 1, @RegisterType = 111

	DECLARE @CountDate AS INT
	SET @CountDate = YEAR(GETDATE()) * 10000 + MONTH(GETDATE()) * 100 + DAY(GETDATE())

	IF @RegisterMode = 0		--非推广，自己注册的
	BEGIN
		INSERT INTO paMain(Username, Password, dcProvinceID, dcSubSiteID, Email, Mobile, RegisterIP, LastLoginDate, TotalLoginNum, RegisterFrom, RegisterType)
		VALUES(@Email, @Password, @dcProvinceID, @dcSubSiteID, @Email, @Mobile, @RegisterIP, GETDATE(), 1, @RegisterFrom, @RegisterType)
		SET @MaxId = @@IDENTITY
		UPDATE DateReport SET PersonRegNum = PersonRegNum + 1, PersonLoginNum_Net = PersonLoginNum_Net + 1
		WHERE province_id = @dcSubSiteID AND CountDate = @CountDate
		--INSERT INTO PaMainDateReport SELECT @MaxId, 11, GETDATE()	--sean 20130708
		INSERT INTO PaMainDateReport SELECT @MaxId, 2, GETDATE()	--sean 20130708
	END
	ELSE						--推广的
	BEGIN
		INSERT INTO paMain(Username, Password, dcProvinceID, dcSubSiteID, Email, RegisterIP, AddMan, RegisterMode, LastLoginDate, TotalLoginNum, AddDate, SpreadDate, RegisterFrom, RegisterType)
		VALUES(@Email, @Password, @dcProvinceID, @dcSubSiteID, @Email, @RegisterIP, @AddMan, @RegisterMode, GETDATE(), 1, GETDATE(), @RegDate, @RegisterFrom, @RegisterType)
		SET @MaxId = @@IDENTITY

		UPDATE DateReport SET ValidResume = ValidResume + 1, PersonLoginNum_Net = PersonLoginNum_Net + 1
		WHERE province_id = @dcSubSiteID AND CountDate = @CountDate
		INSERT INTO PaMainDateReport SELECT @MaxId, 9, GETDATE()	--sean 20130708
		--INSERT INTO PaMainDateReport SELECT @MaxId, 11, GETDATE()	--sean 20130708
		IF NOT EXISTS(SELECT 'x' FROM Info_DateReport WITH(NOLOCK)
						WHERE CountDate = @CountDate
						AND Province_ID = @dcProvinceID
						AND InfoManager_ID = @AddMan
					)
			INSERT INTO Info_DateReport(Province_ID, Infomanager_ID, CountDate) 
			VALUES(@dcProvinceID,  @AddMan, @CountDate)

		UPDATE Info_DateReport
		SET ValidResume = ValidResume + 1  
		WHERE CountDate = @CountDate
		AND Province_ID = @dcProvinceID
		AND InfoManager_ID = @AddMan

		--Lucifer添加，新的register模式
		UPDATE paMain SET SpreadDate = @RegDate, RegisterType=101 WHERE ID=@MaxId
	END

	INSERT INTO paOperationLog (paMainID,Operation,Details,IP) VALUES(@MaxID,10,'注册个人账号成功。',@RegisterIP)
	INSERT INTO paLoginLog (paMainID, LoginIP, AddDate, LoginFrom, Browser) VALUES(@MaxID, @RegisterIP, GETDATE(), 1, '52:From PtCvInvitation')

	RETURN @MaxID
END
ERR:
BEGIN
	INSERT INTO LogDb..RegisterErrorLog SELECT @MaxId, '12|' + @RegisterIP, @Email + ' ' + @Password, GETDATE()
	RETURN -3
END

GO
/****** Object:  StoredProcedure [dbo].[pcpaMainByQQLoginUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--------------------------------------------------
--lambo 2012-11-12
--前台QQ登陆和人人网登陆相关的存储过程，用于登陆后增加登陆日志
--------------------------------------------------
CREATE PROCEDURE [dbo].[pcpaMainByQQLoginUpdate]
(
	@ID INT,
	@browser VARCHAR(500),
	@ip VARCHAR(31),
	@dcProvinceID INT
)
AS
SET NOCOUNT ON
BEGIN TRAN
	BEGIN TRY
		DECLARE @TotalLoginNum AS INT, @LastLoginDate AS SMALLDATETIME

		--超过登陆次数,每天限制登录次数位20次
		IF (SELECT COUNT(1) FROM paLoginLog WITH(NOLOCK) WHERE paMainID = @ID AND AddDate > CONVERT(VARCHAR(10), GETDATE(), 120)) > 19
			GOTO ERR2

		--登陆日志
		SELECT @LastLoginDate = LastLoginDate, @TotalLoginNum = TotalLoginNum FROM paMain WITH(NOLOCK) WHERE ID = @Id

		IF CONVERT(VARCHAR(8), @LastLoginDate, 112) = CONVERT(VARCHAR(8), GETDATE(), 112)	--今天已经登陆过
		BEGIN
			INSERT INTO paLoginLog(paMainID, LoginIP, browser) VALUES(@ID, @IP, '3:' + ISNULL(@browser, 'Null'))
			SELECT @TotalLoginNum = @TotalLoginNum + 1

			IF @LastLoginDate < DATEADD(HOUR, -1, GETDATE())	--登录间隔>1小时更新登录时间
				UPDATE paMain SET LastLoginDate = GETDATE(), TotalLoginNum = @TotalLoginNum WHERE ID = @ID
			ELSE
				UPDATE paMain SET TotalLoginNum = @TotalLoginNum WHERE ID = @ID
		END
		ELSE
		BEGIN
			----今天第一次登录
			INSERT INTO paLoginLog(paMainID, LoginIP, browser, LoginFrom) VALUES(@ID, @IP, '4:' + ISNULL(@browser, 'Null'), 55)
			SELECT @TotalLoginNum = @TotalLoginNum + 1

			UPDATE paMain SET TotalLoginNum = @TotalLoginNum, LastLoginDate = GETDATE() WHERE ID = @ID

			UPDATE DateReport
			SET PersonLoginNum_Net = PersonLoginNum_Net + 1  
			WHERE CountDate = CONVERT(VARCHAR(8), GETDATE(), 112)
			AND Province_Id = @dcProvinceID

			--INSERT INTO PaMainDateReport SELECT @Id, 11, GETDATE()	--sean 20130708
		END
	END TRY
	BEGIN CATCH
		GOTO Err3
	END CATCH
COMMIT
RETURN @ID
ERR1:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END
ERR2:
BEGIN
	ROLLBACK TRAN
	RETURN -1
END
ERR3:
BEGIN
	ROLLBACK TRAN
	RETURN -2
END














GO
/****** Object:  StoredProcedure [dbo].[pcpaMainByQQLoginUpdateNew]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--------------------------------------------------
--lambo 2012-11-12
--前台QQ登陆和人人网登陆相关的存储过程，用于登陆后增加登陆日志
--修改Peter 提取LoginFrom 用来统计登录来源 2016-07-15
--------------------------------------------------
CREATE PROCEDURE [dbo].[pcpaMainByQQLoginUpdateNew]
(
	@ID INT,
	@browser VARCHAR(500),
	@ip VARCHAR(31),
	@dcProvinceID INT,
	@LoginFrom TINYINT
)
AS
SET NOCOUNT ON
SET @LoginFrom = 56
BEGIN TRAN
	BEGIN TRY
		DECLARE @TotalLoginNum AS INT, @LastLoginDate AS SMALLDATETIME

		--超过登陆次数,每天限制登录次数位20次
		IF (SELECT COUNT(1) FROM paLoginLog WITH(NOLOCK) WHERE paMainID = @ID AND AddDate > CONVERT(VARCHAR(10), GETDATE(), 120)) > 19
			GOTO ERR2

		--登陆日志
		SELECT @LastLoginDate = LastLoginDate, @TotalLoginNum = TotalLoginNum FROM paMain WITH(NOLOCK) WHERE ID = @Id

		IF CONVERT(VARCHAR(8), @LastLoginDate, 112) = CONVERT(VARCHAR(8), GETDATE(), 112)	--今天已经登陆过
		BEGIN
			INSERT INTO paLoginLog(paMainID, LoginIP, browser,LoginFrom) VALUES(@ID, @IP, ISNULL(@browser, 'Null') , @LoginFrom)
			SELECT @TotalLoginNum = @TotalLoginNum + 1

			IF @LastLoginDate < DATEADD(HOUR, -1, GETDATE())	--登录间隔>1小时更新登录时间
				UPDATE paMain SET LastLoginDate = GETDATE(), TotalLoginNum = @TotalLoginNum WHERE ID = @ID
			ELSE
				UPDATE paMain SET TotalLoginNum = @TotalLoginNum WHERE ID = @ID
		END
		ELSE
		BEGIN
			----今天第一次登录
			INSERT INTO paLoginLog(paMainID, LoginIP, browser, LoginFrom) VALUES(@ID, @IP, ISNULL(@browser, 'Null'), @LoginFrom)
			SELECT @TotalLoginNum = @TotalLoginNum + 1

			UPDATE paMain SET TotalLoginNum = @TotalLoginNum, LastLoginDate = GETDATE() WHERE ID = @ID

			UPDATE DateReport
			SET PersonLoginNum_Net = PersonLoginNum_Net + 1  
			WHERE CountDate = CONVERT(VARCHAR(8), GETDATE(), 112)
			AND Province_Id = @dcProvinceID

			--INSERT INTO PaMainDateReport SELECT @Id, 11, GETDATE()	--sean 20130708
		END
	END TRY
	BEGIN CATCH
		GOTO Err3
	END CATCH
COMMIT
RETURN @ID
ERR1:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END
ERR2:
BEGIN
	ROLLBACK TRAN
	RETURN -1
END
ERR3:
BEGIN
	ROLLBACK TRAN
	RETURN -2
END
GO
/****** Object:  StoredProcedure [dbo].[pcPaMainByRefreshDateUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--####################################33
--更新求职状态，简历列表中使用
--@ID=cvmainID
--@ID=0 则更新全部简历
--返回值：
--	0	数据库错误
--	-1	手机号已经列入黑名单
--	-2	手机号或求职状态为空
--	-3	该简历不属于该账号
--####################################33
CREATE PROCEDURE [dbo].[pcPaMainByRefreshDateUpdate]
(
	@ID INT,
	@PaMainID INT,
	@Mobile VARCHAR(13),
	@dcCareerStatus TINYINT,
	@IP VARCHAR(39)
)
AS
SET NOCOUNT ON
SET @Mobile = dbo.TextTrim(@Mobile)
IF @Mobile IS NULL OR @dcCareerStatus IS NULL
	RETURN -2		--手机号或求职状态为空

IF EXISTS(SELECT 'x' FROM Person_BLACK WITH(NOLOCK) WHERE Mobile = @Mobile)
BEGIN
	----有黑名单，则增加拒绝次数
	UPDATE Person_Black SET RefuseCount = RefuseCount + 1 WHERE Mobile = @Mobile
	RETURN -1
END

IF @ID > 0
	IF NOT EXISTS(SELECT 'x' FROM cvMain WITH(NOLOCK) WHERE ID = @ID AND paMainID = @paMainID)
		RETURN -3

BEGIN TRAN 
	BEGIN TRY
		--如果新旧日志不相同，记录更新手机号的操作
		DECLARE @MobileOld AS VARCHAR(13)
		SELECT @MobileOld = Mobile FROM paMain WITH(NOLOCK) WHERE ID = @paMAinID
		IF ISNULL(@MobileOld, '') <> @Mobile
			INSERT INTO paOperationLog (paMainID, Operation, Details, IP) 
			VALUES(@paMainID, 35,'更新手机号，原手机号：<' + ISNULL(@MobileOld, '') + '>；新手机号：<' + @Mobile + '>', @IP)

		UPDATE paMain SET Mobile = @mobile, dcCareerStatus = @dcCareerStatus, 
			LastModifyDate = GETDATE() WHERE ID = @PaMainID
		IF @ID > 0
			UPDATE CvMain SET RefreshDate = GETDATE() WHERE paMainID = @paMainID AND ID = @ID
		ELSe
			UPDATE CvMain SET RefreshDate = GETDATE() WHERE paMainID = @paMainID
	END TRY
	BEGIN CATCH
		GOTO Err
	END CATCH
COMMIT TRAN
RETURN 1
Err:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END














GO
/****** Object:  StoredProcedure [dbo].[pcPaMainByResetPasswordUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
---*******************
--lambo 2012-11-9
--peter 2018-4-20
---*******************
CREATE PROCEDURE [dbo].[pcPaMainByResetPasswordUpdate]
(
	@ID INT,
	@Password VARCHAR(80),
	@PlainPassword VARCHAR(40),
	@IP VARCHAR(50)
)
AS
BEGIN
	IF NOT (dbo.ISAccount(@PlainPassword) = 1)
	BEGIN
		RETURN -2
	END
	ELSE
	BEGIN
		UPDATE paMain SET Password = @Password, IsDefaultPassword = 0 WHERE ID = @ID 
		IF @@RowCount =0
			RETURN -3
		ELSE
			INSERT INTO paOperationLog (paMainID, Operation, Details, IP) VALUES(@ID, 21, '重置密码，新密码：<' + LEFT(@PlainPassword, 3) + '****>', @IP)
		RETURN 1
	END
END

GO
/****** Object:  StoredProcedure [dbo].[pcPaMainByUserNameExist]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- 检查:		Sean
-- 日期:		2010-10-5
-- 描述:		检查Email是否存在
-- =============================================
CREATE PROCEDURE [dbo].[pcPaMainByUserNameExist]
(
	@UserName VARCHAR(50)
)
AS
BEGIN
	IF EXISTS(SELECT ID FROM paMain WITH(NOLOCK) WHERE UserNameLower = @UserName)
		RETURN 1
	ELSE
		RETURN 0
END














GO
/****** Object:  StoredProcedure [dbo].[pcPaMainByUsernameUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


-- =============================================
-- Author:		Sean
-- Create date: 2010-9-15
-- Description:	修改用户名 ，EMail邮触发器联动修改
--lambo 20121109
-- =============================================
CREATE PROCEDURE  [dbo].[pcPaMainByUsernameUpdate]
(
	@ID INT,
	@Username VARCHAR(50),
	@IP VARCHAR(31)
)
AS
set nocount off
IF EXISTS(SELECT 'x' FROM Person_BLACK WITH(NOLOCK) WHERE EMail = @Username)
BEGIN
	----有黑名单，则增加拒绝次数
	UPDATE Person_Black SET RefuseCount = RefuseCount + 1 WHERE EMail = @Username
	RETURN 20
END
SET @Username = dbo.TextTrim(@Username)
BEGIN TRAN
	BEGIN TRY
		----用户名不是邮箱格式
		IF dbo.IsEmail(@Username) = 0
			GOTO Err10

		DECLARE @UsernameOld AS VARCHAR(50), @dcProvinceID INT, @AddMan INT,
			@RegDate SMALLDATETIME, @RegisterMode INT, @RegisterType INT,
			@CountDate VARCHAR(8)

		SELECT @UsernameOld = UsernameLower, @dcProvinceID = dcProvinceID 
		FROM paMain WITH(NOLOCK INDEX(PK_paMain)) WHERE ID = @ID

		--用户名重复验证，必须与原用户名不同
		IF EXISTS(SELECT 'x' FROM paMain WITH(NOLOCK INDEX(IX_paMain_UserNameLower)) WHERE UserNameLower = @Username)
			GOTO ERR11

		--resume_xinxi的处理，这是删除
		IF @UserNameOld LIKE '%@your_email.com'
		BEGIN
			--160天内，是否推广邮件，IsHistory有计划任务保证
			SELECT TOP 1 @AddMan = AddMan, @RegDate = RegDate FROM Resume_Xinxi WITH( INDEX(IX_Resume_Xinxi_Email) NOLOCK)
			WHERE Email = @UserName AND IsHistory = 0
			AND Province_ID = @dcProvinceID
			ORDER BY RegDate DESC

			----是160天内推广的
			IF @AddMan > 0
			BEGIN
				SET @CountDate = CONVERT(VARCHAR(8), GETDATE(), 112)
				SELECT @RegisterMode = 1, @RegisterType = 111		

				UPDATE DateReport SET ValidResume = ValidResume + 1
				WHERE province_id = @dcProvinceID AND CountDate = CONVERT(VARCHAR(8), GETDATE(), 112)
			
				IF NOT EXISTS(SELECT 'x' FROM Info_DateReport WITH(NOLOCK)
					WHERE CountDate = @CountDate
					AND Province_ID = @dcProvinceID
					AND InfoManager_ID = @AddMan
					)
					INSERT INTO Info_DateReport(Province_ID, Infomanager_ID, CountDate) 
					VALUES(@dcProvinceID,  @AddMan, @CountDate)

				UPDATE Info_DateReport
				SET ValidResume = ValidResume + 1  
				WHERE CountDate = @CountDate
				AND Province_ID = @dcProvinceID
				AND InfoManager_ID = @AddMan

				--Lucifer添加，新的register模式
				UPDATE paMain SET AddMan = @AddMan, SpreadDate = @RegDate, RegisterType=101 WHERE ID=@Id
			END
		END

		IF EXISTS(SELECT 'x' FROM Resume_Xinxi WITH(NOLOCK INDEX(IX_Resume_Xinxi_Email)) WHERE EMail = @Username)
			DELETE FROM Resume_Xinxi WHERE EMail = @Username

		UPDATE paMain SET Username = @Username WHERE ID = @ID
		IF @@RowCount = 0
			GOTO ERR
		ELSE
			INSERT INTO paOperationLog (paMainID, Operation, Details, IP) 
			VALUES(@ID, 20, '更新用户名，原用户名：<' + @UsernameOld + '>；新用户名：<' + @Username + '>', @IP)
	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH
COMMIT TRAN
RETURN 1
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END
ERR10:
BEGIN
	ROLLBACK TRAN
	RETURN 10
END
ERR11:
BEGIN
	ROLLBACK TRAN
	RETURN 11
END
ERR21:
BEGIN
	ROLLBACK TRAN
	RETURN 21
END

GO
/****** Object:  StoredProcedure [dbo].[pcPaMainByUsernameUpdate0320]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


-- =============================================
-- Author:		Sean
-- Create date: 2010-9-15
-- Description:	修改用户名 ，EMail邮触发器联动修改
--lambo 20121109
-- =============================================
create PROCEDURE  [dbo].[pcPaMainByUsernameUpdate0320]
(
	@ID INT,
	@Username VARCHAR(50),
	@IP VARCHAR(31)
)
AS
IF EXISTS(SELECT 'x' FROM Person_BLACK WITH(NOLOCK) WHERE EMail = @Username)
BEGIN
	----有黑名单，则增加拒绝次数
	UPDATE Person_Black SET RefuseCount = RefuseCount + 1 WHERE EMail = @Username
	RETURN 20
END
SET @Username = dbo.TextTrim(@Username)
BEGIN TRAN
	BEGIN TRY
		----用户名不是邮箱格式
		IF dbo.IsEmail(@Username) = 0
			GOTO Err10


		DECLARE @UsernameOld AS VARCHAR(50)
		SELECT @UsernameOld = Username FROM paMain WITH(NOLOCK INDEX(PK_paMain)) WHERE ID = @ID

		--用户名重复验证，必须与原用户名不同
		IF EXISTS(SELECT 'x' FROM paMain WITH(NOLOCK INDEX(IX_paMain_UserNameLower)) 
				WHERE UserNameLower = @Username)
			GOTO ERR11

		--resume_xinxi的处理，这是删除
		IF EXISTS(SELECT 'x' FROM Resume_Xinxi WITH(NOLOCK INDEX(IX_Resume_Xinxi_Email)) WHERE EMail = @Username)
			DELETE FROM Resume_Xinxi WHERE EMail = @Username
		
		UPDATE paMain SET Username = @Username WHERE ID = @ID
		IF @@RowCount = 0
			GOTO ERR
		ELSE
			INSERT INTO paOperationLog (paMainID, Operation, Details, IP) 
			VALUES(@ID, 20, '更新用户名，原用户名：<' + @UsernameOld + '>；新用户名：<' + @Username + '>', @IP)
	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH
COMMIT TRAN
RETURN 1
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END
ERR10:
BEGIN
	ROLLBACK TRAN
	RETURN 10
END
ERR11:
BEGIN
	ROLLBACK TRAN
	RETURN 11
END
ERR21:
BEGIN
	ROLLBACK TRAN
	RETURN 21
END














GO
/****** Object:  StoredProcedure [dbo].[pcPaMainByUsernameUpdate2]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


-- =============================================
-- Author:		Sean
-- Create date: 2010-9-15
-- Description:	修改用户名 ，EMail邮触发器联动修改
--lambo 20121109
-- =============================================
CREATE PROCEDURE  [dbo].[pcPaMainByUsernameUpdate2]
(
	@ID INT,
	@Username VARCHAR(50),
	@IP VARCHAR(31)
)
AS
set nocount off
IF EXISTS(SELECT 'x' FROM Person_BLACK WITH(NOLOCK) WHERE EMail = @Username)
BEGIN
	----有黑名单，则增加拒绝次数
	UPDATE Person_Black SET RefuseCount = RefuseCount + 1 WHERE EMail = @Username
	RETURN 20
END
SET @Username = dbo.TextTrim(@Username)
BEGIN TRAN
	BEGIN TRY
		----用户名不是邮箱格式
		IF dbo.IsEmail(@Username) = 0
			GOTO Err10

		DECLARE @UsernameOld AS VARCHAR(50), @dcProvinceID INT, @AddMan INT,
			@RegDate SMALLDATETIME, @RegisterMode INT, @RegisterType INT,
			@CountDate VARCHAR(8)

		SELECT @UsernameOld = UsernameLower, @dcProvinceID = dcProvinceID 
		FROM paMain WITH(NOLOCK INDEX(PK_paMain)) WHERE ID = @ID

		--用户名重复验证，必须与原用户名不同
		IF EXISTS(SELECT 'x' FROM paMain WITH(NOLOCK INDEX(IX_paMain_UserNameLower)) WHERE UserNameLower = @Username)
			GOTO ERR11

		--resume_xinxi的处理，这是删除
		IF @UserNameOld LIKE '%@your_email.com'
		BEGIN
			--160天内，是否推广邮件，IsHistory有计划任务保证
			SELECT TOP 1 @AddMan = AddMan, @RegDate = RegDate FROM Resume_Xinxi WITH( INDEX(IX_Resume_Xinxi_Email) NOLOCK)
			WHERE Email = @UserName AND IsHistory = 0
			AND Province_ID = @dcProvinceID
			ORDER BY RegDate DESC

			----是160天内推广的
			IF @AddMan > 0
			BEGIN
				SET @CountDate = CONVERT(VARCHAR(8), GETDATE(), 112)
				SELECT @RegisterMode = 1, @RegisterType = 111		

				UPDATE DateReport SET ValidResume = ValidResume + 1
				WHERE province_id = @dcProvinceID AND CountDate = CONVERT(VARCHAR(8), GETDATE(), 112)
			
				IF NOT EXISTS(SELECT 'x' FROM Info_DateReport WITH(NOLOCK)
					WHERE CountDate = @CountDate
					AND Province_ID = @dcProvinceID
					AND InfoManager_ID = @AddMan
					)
					INSERT INTO Info_DateReport(Province_ID, Infomanager_ID, CountDate) 
					VALUES(@dcProvinceID,  @AddMan, @CountDate)

				UPDATE Info_DateReport
				SET ValidResume = ValidResume + 1  
				WHERE CountDate = @CountDate
				AND Province_ID = @dcProvinceID
				AND InfoManager_ID = @AddMan

				--Lucifer添加，新的register模式
				UPDATE paMain SET AddMan = @AddMan, SpreadDate = @RegDate, RegisterType=101 WHERE ID=@Id
			END
		END

		IF EXISTS(SELECT 'x' FROM Resume_Xinxi WITH(NOLOCK INDEX(IX_Resume_Xinxi_Email)) WHERE EMail = @Username)
			DELETE FROM Resume_Xinxi WHERE EMail = @Username

		UPDATE paMain SET Username = @Username WHERE ID = @ID
		IF @@RowCount = 0
			GOTO ERR
		ELSE
			INSERT INTO paOperationLog (paMainID, Operation, Details, IP) 
			VALUES(@ID, 20, '更新用户名，原用户名：<' + @UsernameOld + '>；新用户名：<' + @Username + '>', @IP)
	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH
COMMIT TRAN
RETURN 1
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END
ERR10:
BEGIN
	ROLLBACK TRAN
	RETURN 10
END
ERR11:
BEGIN
	ROLLBACK TRAN
	RETURN 11
END
ERR21:
BEGIN
	ROLLBACK TRAN
	RETURN 21
END

GO
/****** Object:  StoredProcedure [dbo].[pcPaMainByValidCvNumberSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[pcPaMainByValidCvNumberSelect]
(
	@paMainID INT
)
AS
BEGIN
	DECLARE @Cnt AS INT
	SELECT @Cnt = COUNT(*) FROM cvMain WITH(NOLOCK)
	WHERE paMainID = @paMainID
	AND (
		AttachMent > ''
		OR(
			cvLevel LIKE '1111_1%'
			AND VerifyResult = 1
		  )
		OR(
			cvLevelEng LIKE '1111_1%'
			AND VerifyResultEng = 1
		  )
		)

	RETURN @Cnt
END














GO
/****** Object:  StoredProcedure [dbo].[pcPaMainByVerifyUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--20180322 Carl 修改
CREATE PROCEDURE [dbo].[pcPaMainByVerifyUpdate]
(
	@paMainID INT,
	@Mobile VARCHAR(11),
	@Email VARCHAR(50),
	@VerifyCode VARCHAR(6)
)
AS
SET NOCOUNT ON
BEGIN
	DECLARE @MobileVerifyDate SMALLDATETIME,@EmailVerifyDate SMALLDATETIME
	SELECT @MobileVerifyDate = MobileVerifyDate,@EmailVerifyDate=EmailVerifyDate FROM paMain WHERE ID=@paMainID
	IF LEN(@Mobile)=0 AND ISNULL(@EmailVerifyDate,'')<>''
		RETURN -1

	DECLARE @paVerifyLogID AS INT
	SET @paVerifyLogID=0	
	SELECT @paVerifyLogID=ID FROM paVerifyLog WHERE paMainID=@paMainID AND ISNULL(Mobile,'')=@Mobile AND ISNULL(Email,'')=@Email 
		AND VerifyCode=@VerifyCode AND AddDate>DATEADD(HOUR,-1,GETDATE())
	
	IF @paVerifyLogID=0
		RETURN 0
	
	UPDATE paVerifyLog SET VerifyDate=GETDATE() WHERE paMainID=@paMainID AND ISNULL(Mobile,'')=@Mobile AND ISNULL(Email,'')=@Email 
		AND VerifyCode=@VerifyCode AND AddDate>DATEADD(HOUR,-1,GETDATE())
	
	IF LEN(@Mobile)=0
		UPDATE paMain SET EmailVerifyDate=GETDATE() WHERE ID=@paMainID
	
	IF LEN(@Email)=0
	BEGIN
		UPDATE paMain SET Mobile = @Mobile WHERE ID = @paMainID
		--修改本手机号对应的其他帐号的认证状态
		UPDATE paMain SET MobileVerifyDate = NULL WHERE Mobile = @Mobile
		UPDATE paMain SET MobileVerifyDate = GETDATE() WHERE ID = @paMainID

		IF @@ROWCOUNT > 0
			DELETE FROM paMain WHERE ID IN(SELECT ID FROM paMain WITH(INDEX(IX_paMain_Mobile)) WHERE Mobile = @Mobile AND ID < @paMainID AND AddDate > DATEADD(MINUTE, -3, GETDATE()))

		IF EXISTS(SELECT 'X' FROM paMobileFollowUp WHERE ISNULL(ContactDate,0)>DATEADD(hh,-1,GETDATE()) AND Mobile = @Mobile)
			UPDATE paMobileFollowUp SET PaMainId=@paMainID WHERE Mobile = @Mobile
		ELSE
			DELETE FROM paMobileFollowUp WHERE Mobile = @Mobile

	END

	RETURN 1
END
GO
/****** Object:  StoredProcedure [dbo].[pcPaMainByWordInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[pcPaMainByWordInsert]
(
	@Username VARCHAR(50),	
	@Name NVARCHAR(6),
	@Gender BIT,
	@dcSubSiteID SMALLINT,
	@RegisterIP VARCHAR(31),
	@R VARCHAR(50) OUT
)
AS
BEGIN
	DECLARE @paMainID AS INT
	DECLARE @cvMainID AS INT
	EXEC @paMainID = pcPaMainInsert @Username, '$2a$08$wCjRdWcKgup74i.L3sk6OOlCAQ/qAPmAWE4ZMzpJL7K85N0.x/WIu', @dcSubSiteID, @RegisterIP, 0, 0

	UPDATE paMain SET Name = @Name, Gender = @Gender, IsDefaultPassword = 1 WHERE ID = @paMainID

	EXEC @cvMainID = pcCvMainCreate @paMainID, @RegisterIP

	UPDATE cvMain SET IsOpen = 0 WHERE Id = @cvMainId
	--INSERT INTO cvJobPlace(cvMainId, dcRegionId) SELECT @cvMainId, @dcSubSiteID
	SET @R = CAST(@cvMainID AS VARCHAR(10)) + ',' + CAST(@paMainID AS VARCHAR(10))
END


GO
/****** Object:  StoredProcedure [dbo].[pcPaMainByWordInsertNew]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[pcPaMainByWordInsertNew]
(
	@Username VARCHAR(50),	
	@Name NVARCHAR(6),
	@Gender BIT,
	@dcSubSiteID SMALLINT,
	@RegisterIP VARCHAR(31),
	@Mobile VARCHAR(11),
	@txtVeriyCode VARCHAR(6),
	@R VARCHAR(50) OUT
)
AS
SET NOCOUNT ON
BEGIN
	DECLARE @paMainID AS INT
	DECLARE @cvMainID AS INT
	EXEC @paMainID = pcPaMainInsert @Username, '$2a$08$wCjRdWcKgup74i.L3sk6OOlCAQ/qAPmAWE4ZMzpJL7K85N0.x/WIu', @dcSubSiteID, @RegisterIP, 0, 0

	UPDATE paMain SET Name = @Name, Gender = @Gender, IsDefaultPassword = 1 WHERE ID = @paMainID
	
	IF CHARINDEX('$', @RegisterIP) > 0
		SET @RegisterIP = REPLACE(@RegisterIP,'|1$10', '')
	
	EXEC pcPaVerifyLogUpdate @paMainID, @Mobile, @RegisterIP 
	EXEC pcPaMainByVerifyUpdate @paMainID, @Mobile, '', @txtVeriyCode
	EXEC @cvMainID = pcCvMainCreate @paMainID, @RegisterIP

	UPDATE cvMain SET IsOpen = 0 WHERE Id = @cvMainId
	SET @R = CAST(@cvMainID AS VARCHAR(10)) + ','+ CAST(@paMainID AS VARCHAR(10))
END

GO
/****** Object:  StoredProcedure [dbo].[pcPaMainEmailExist]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- 检查:		Sean
-- 日期:		2010-10-5
-- 描述:		检查Email是否存在
-- =============================================
CREATE PROCEDURE [dbo].[pcPaMainEmailExist]
(
	@Email VARCHAR(50)
)
AS
BEGIN
	IF EXISTS(SELECT ID FROM paMain WITH(NOLOCK) WHERE Email = @Email)
		RETURN 1
	ELSE
		RETURN 0
END














GO
/****** Object:  StoredProcedure [dbo].[pcPaMainImport]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--创建：Max 2013-8-14
--说明：北大青鸟简历导入注册个人存储过程。没有IP限制。
--注册新用户，记录到dateReport
--过程：
--检查是否在黑名单		-1
--检查是否在paMain		-2
--检查是否在推广表
--	在推广表，并且160天内推广过的
--		认为是推广有效，记录Addman，registermode=1
--删除推广表中的该邮件
--检查发帖来源
--检查连接来源
--保存错误		-3
--加密后的注册 暂时保留明文PlainPassword
---------------------------------------------------
CREATE PROCEDURE  [dbo].[pcPaMainImport]
(
	@Email VARCHAR(50),
	@Password VARCHAR(60),
	@dcSubSiteID SMALLINT,
	@RegisterIP VARCHAR(31),
	@UrlID INT,
	@InfoID INT
)
AS
SET NOCOUNT ON
IF (@RegisterIP = '180.129.225.52' OR @RegisterIP = '180.129.225.50' OR @RegisterIP = '220.164.162.215') AND LEN(@Email) > 30
	RETURN 1
BEGIN TRAN
	----在黑名单中则终止
	IF EXISTS(SELECT 'X' FROM Person_Black WITH(NOLOCK) WHERE Email = @Email)
    BEGIN
        UPDATE Person_black SET refusecount=refusecount+1 where email = @Email
		COMMIT
		RETURN -1
    END

	----在paMain中邮件重复则终止，新注册的都要是新邮箱
	IF EXISTS(SELECT 'X' FROM paMain WITH(NOLOCK) WHERE EMail = @Email)
	BEGIN
		ROLLBACK TRAN
		RETURN -2
	END
	DECLARE @MaxId AS INT
	DECLARE @AddMan SMALLINT
	DECLARE @RegisterMode TINYINT
	DECLARE @dcProvinceID TINYINT
	SELECT @RegisterMode = 0, @dcProvinceID = LEFT(@dcSubSiteID, 2)

	SET @Email = REPLACE(@Email, ' ', '')
	--160天内，是否推广邮件，IsHistory有计划任务保证
	SELECT TOP 1 @AddMan = AddMan FROM Resume_Xinxi WITH( INDEX(IX_Resume_Xinxi_Email) NOLOCK)
	WHERE Email = @Email AND IsHistory = 0
	AND Province_ID = @dcProvinceID
	ORDER BY RegDate DESC

	----是160天内推广的
	IF @AddMan > 0
		SET @RegisterMode = 1

	DECLARE @CountDate AS INT
	SET @CountDate = YEAR(GETDATE())*10000+MONTH(GETDATE())*100+DAY(GETDATE())

	IF @RegisterMode = 0		--非推广，自己注册的
	BEGIN
		INSERT INTO paMain(Username, Password, dcProvinceID, dcSubSiteID, Email, RegisterIP, LastLoginDate, TotalLoginNum)
		VALUES(@Email, @Password, @dcProvinceID, @dcSubSiteID, @Email, @RegisterIP, GETDATE(), 1)
		SET @MaxId = @@IDENTITY
        UPDATE DateReport SET PersonRegNum = PersonRegNum + 1, PersonLoginNum_Net = PersonLoginNum_Net + 1
		WHERE province_id = @dcSubSiteID AND CountDate = @CountDate
		--INSERT INTO PaMainDateReport SELECT @MaxId, 11, GETDATE()	--sean 20130708
		INSERT INTO PaMainDateReport SELECT @MaxId, 2, GETDATE()	--sean 20130708
	END
	ELSE						--推广的
	BEGIN
		INSERT INTO paMain(Username, Password, dcProvinceID, dcSubSiteID, Email, RegisterIP, AddMan, RegisterMode, LastLoginDate, TotalLoginNum)
		VALUES(@Email, @Password, @dcProvinceID, @dcSubSiteID, @Email, @RegisterIP, @AddMan, @RegisterMode, GETDATE(), 1)
		SET @MaxId = @@IDENTITY

		UPDATE DateReport SET ValidResume = ValidResume + 1, PersonLoginNum_Net = PersonLoginNum_Net + 1
		WHERE province_id = @dcSubSiteID AND CountDate = @CountDate
		INSERT INTO PaMainDateReport SELECT @MaxId, 9, GETDATE()	--sean 20130708
		--INSERT INTO PaMainDateReport SELECT @MaxId, 11, GETDATE()	--sean 20130708
		IF NOT EXISTS(SELECT 'x' FROM Info_DateReport WITH(NOLOCK)
						WHERE CountDate = @CountDate
						AND Province_ID = @dcProvinceID
						AND InfoManager_ID = @AddMan
					)
			INSERT INTO Info_DateReport(Province_ID, Infomanager_ID, CountDate) 
			VALUES(@dcProvinceID,  @AddMan, @CountDate)

		UPDATE Info_DateReport
		SET ValidResume = ValidResume + 1  
		WHERE CountDate = @CountDate
		AND Province_ID = @dcProvinceID
		AND InfoManager_ID = @AddMan
	END
	
	INSERT INTO paOperationLog (paMainID,Operation,Details,IP) VALUES(@MaxID,10,'注册个人账号成功。',@RegisterIP)
	INSERT INTO paLoginLog (paMainID, LoginIP, AddDate, LoginFrom, Browser) VALUES(@MaxID, @RegisterIP, GETDATE(), 1, '50:From Import')
COMMIT
BEGIN TRY
	IF @UrlID>0
		UPDATE Url SET AllResume=AllResume+1,TodayResume=TodayResume+1 WHERE ID=@UrlID
	IF @InfoID>0
	BEGIN
		IF NOT EXISTS(SELECT 'x' FROM Info_DateReport WITH(NOLOCK)
					WHERE CountDate = @CountDate
					AND Province_ID = @dcProvinceID
					AND InfoManager_ID = @InfoID
					)
		INSERT INTO Info_DateReport(Province_ID, Infomanager_ID, CountDate) 
		VALUES(@dcProvinceID, @InfoID, @CountDate)

		UPDATE Info_DateReport 
		SET AllResume = AllResume + 1
		WHERE CountDate = @CountDate
		AND Province_ID = @dcSubSiteID
		AND InfoManager_ID = @InfoID
	END
END TRY
BEGIN CATCH
	RETURN -4
END CATCH

RETURN @MaxID
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN -3
END











GO
/****** Object:  StoredProcedure [dbo].[pcPaMainInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
---------------------------------------------------
--修改：Sean 2010-9-14
--说明：这是用户自己注册的主要存储过程
--注册新用户，记录到dateReport
--过程：
--检查是否在黑名单		-1
--检查是否在paMain		-2
--检查是否在推广表
--	在推广表，并且160天内推广过的
--		认为是推广有效，记录Addman，registermode=1
--删除推广表中的该邮件
--检查发帖来源
--检查连接来源
--保存错误		-3
--加密后的注册 暂时保留明文PlainPassword
--Lucifer添加 修改registermode，将注册的类型和方式放到@RegisterIP传过来，举例192.168.1.1|1$120
--20180228 Carl 如果RegisterType=200，不进行时间限制
---------------------------------------------------
CREATE PROCEDURE  [dbo].[pcPaMainInsert]
(
	@Email VARCHAR(50),
	@Password VARCHAR(60),
	@dcSubSiteID SMALLINT,
	@RegisterIP VARCHAR(50),
	@UrlID INT,
	@InfoID INT
)
AS
SET NOCOUNT ON
IF EXISTS(SELECT 'x' FROM Ip_Black WITH(NOLOCK) WHERE Ip = @RegisterIP)
	RETURN 0
BEGIN TRY
	--Lucifer添加，拆解@RegisterIP
	DECLARE @RegisterParam AS VARCHAR(20), @RegisterFrom AS VARCHAR(5), @RegisterType AS VARCHAR(5), @RegFrom AS VARCHAR(5)
	SELECT @RegisterFrom = 1, @RegFrom = ''
	IF CHARINDEX('|', @RegisterIP) > 0
	BEGIN
		SET @RegisterParam = SUBSTRING(@RegisterIP, CHARINDEX('|', @RegisterIP) + 1, LEN(@RegisterIP) - CHARINDEX('|', @RegisterIP))
		SET @RegisterIP = SUBSTRING(@RegisterIP, 1, CHARINDEX('|', @RegisterIP) - 1)
		IF (LEN(@RegisterIP) > 31)
			SET @RegisterIp = LEFT(@RegisterIp, 31)
		--Lucifer添加，拆解@RegisterIP
		IF LEN(ISNULL(@RegisterParam, '')) > 0
		BEGIN
			SELECT @RegisterFrom = SUBSTRING(@RegisterParam, 1, CHARINDEX('$',@RegisterParam) - 1),
				@RegisterType = SUBSTRING(@RegisterParam, CHARINDEX('$', @RegisterParam) + 1, LEN(@RegisterParam) - CHARINDEX('$', @RegisterParam))
			IF @RegisterFrom = 'a'
				SELECT @RegisterFrom = 1, @RegFrom = 'a'
		END
	END
	--ELSE
	--BEGIN
	--	SELECT @RegisterFrom = 9, @RegisterType = 9
	--END

	IF @RegisterType = 0
		SELECT @RegisterType = NULL

	--IF (@RegisterIP = '180.129.225.52' OR @RegisterIP = '180.129.225.50' OR @RegisterIP = '220.164.162.215') AND LEN(@Email) > 30
	--	RETURN 1
	IF (SELECT COUNT(*) FROM paMain WITH(NOLOCK) WHERE RegisterIp = @RegisterIp AND AddDate > DATEADD(MINUTE, -10, GETDATE())) > 10 AND @RegisterType<>200
		RETURN 1
--	IF NOT EXISTS(SELECT 'x' FROM Ip_White WHERE CHARINDEX(ip, @RegisterIp) > 0)
--	BEGIN
--		IF (SELECT COUNT(*) FROM paMain WITH(NOLOCK) WHERE RegisterIp = @RegisterIp AND AddDate > DATEADD(MINUTE, -30, GETDATE())) > 10
--			RETURN -1
--		--IF EXISTS(SELECT 'x' FROM tmp_limitip2 WHERE ip = @RegisterIP)
--		--	RETURN -1
--	END
	BEGIN TRAN
		----在黑名单中则终止
		IF LEN(@Email) > 6 AND EXISTS(SELECT 'X' FROM Person_Black WITH(NOLOCK) WHERE Email = @Email)
		BEGIN
			UPDATE Person_black SET refusecount = refusecount + 1 where email = @Email
			COMMIT
			RETURN -1
		END

		----在paMain中邮件重复则终止，新注册的都要是新邮箱
		IF EXISTS(SELECT 'X' FROM paMain WITH(NOLOCK) WHERE EMail = @Email)
		BEGIN
			ROLLBACK TRAN
			RETURN -2
		END
		DECLARE @MaxId AS INT, @AddMan SMALLINT, @RegisterMode TINYINT, @dcProvinceID TINYINT, @RegDate DATETIME
		SELECT @RegisterMode = 0, @dcProvinceID = LEFT(@dcSubSiteID, 2)
		IF @RegisterType NOT IN(101)
		BEGIN
			SET @Email = dbo.SafeSQL(REPLACE(@Email, ' ', ''))
			--160天内，是否推广邮件，IsHistory有计划任务保证
			SELECT TOP 1 @AddMan = AddMan, @RegDate = RegDate FROM Resume_Xinxi WITH( INDEX(IX_Resume_Xinxi_Email) NOLOCK)
			WHERE Email = @Email AND IsHistory = 0
			AND Province_ID = @dcProvinceID AND @RegisterType<>200
			ORDER BY RegDate DESC

			----是160天内推广的
			IF @AddMan > 0
				SELECT @RegisterMode = 1, @RegisterType = 111
		END
		IF @RegisterMode = 0 AND @InfoID BETWEEN 201 AND 499
		BEGIN
			SELECT @RegisterMode = 1, @RegisterType = 111, @AddMan = @InfoID
		END

		DECLARE @CountDate AS INT
		SET @CountDate = YEAR(GETDATE()) * 10000 + MONTH(GETDATE()) * 100 + DAY(GETDATE())
 
		IF @RegisterMode = 0		--非推广，自己注册的
		BEGIN
			INSERT INTO paMain(Username, Password, dcProvinceID, dcSubSiteID, Email, RegisterIP, LastLoginDate, TotalLoginNum, RegisterFrom, RegisterType)
			VALUES(@Email, @Password, @dcProvinceID, @dcSubSiteID, @Email, @RegisterIP, GETDATE(), 1, @RegisterFrom, @RegisterType)
			SET @MaxId = @@IDENTITY
			IF @RegisterType <> 200
			BEGIN
				UPDATE DateReport SET PersonRegNum = PersonRegNum + 1, PersonLoginNum_Net = PersonLoginNum_Net + 1
				WHERE province_id = @dcSubSiteID AND CountDate = @CountDate
			
				INSERT INTO PaMainDateReport SELECT @MaxId, 2, GETDATE()	--sean 20130708
			END
			ELSE
				INSERT INTO PaMainDateReport SELECT @MaxId, 3, GETDATE()	--sean 20130708
		END
		ELSE						--推广的
		BEGIN
			INSERT INTO paMain(Username, Password, dcProvinceID, dcSubSiteID, Email, RegisterIP, AddMan, RegisterMode, LastLoginDate, TotalLoginNum, AddDate, SpreadDate, RegisterFrom, RegisterType)
			VALUES(@Email, @Password, @dcProvinceID, @dcSubSiteID, @Email, @RegisterIP, @AddMan, @RegisterMode, GETDATE(), 1, GETDATE(), @RegDate, @RegisterFrom, @RegisterType)
			SET @MaxId = @@IDENTITY

			UPDATE DateReport SET ValidResume = ValidResume + 1, PersonLoginNum_Net = PersonLoginNum_Net + 1
			WHERE province_id = @dcSubSiteID AND CountDate = @CountDate
			INSERT INTO PaMainDateReport SELECT @MaxId, 9, GETDATE()	--sean 20130708
			--INSERT INTO PaMainDateReport SELECT @MaxId, 11, GETDATE()	--sean 20130708
			IF NOT EXISTS(SELECT 'x' FROM Info_DateReport WITH(NOLOCK)
							WHERE CountDate = @CountDate
							AND Province_ID = @dcProvinceID
							AND InfoManager_ID = @AddMan
						)
				INSERT INTO Info_DateReport(Province_ID, Infomanager_ID, CountDate) 
				VALUES(@dcProvinceID,  @AddMan, @CountDate)

			UPDATE Info_DateReport
			SET ValidResume = ValidResume + 1  
			WHERE CountDate = @CountDate
			AND Province_ID = @dcProvinceID
			AND InfoManager_ID = @AddMan

			--Lucifer添加，新的register模式
			UPDATE paMain SET SpreadDate = @RegDate, RegisterType=101 WHERE ID=@MaxId
		END
		
		INSERT INTO paOperationLog (paMainID,Operation,Details,IP) VALUES(@MaxID,10,'注册个人账号成功。',@RegisterIP)
		INSERT INTO paLoginLog (paMainID, LoginIP, AddDate, LoginFrom, Browser) VALUES(@MaxID, @RegisterIP, GETDATE(), 60, '51:From Register')
	COMMIT
END TRY
BEGIN CATCH
	ROLLBACK TRAN
	INSERT INTO LogDb..RegisterErrorLog SELECT @MaxId, '10|' + @RegisterIP+'|'+@RegisterFrom, @Email + ' ' + @Password, GETDATE()
END CATCH
BEGIN TRY
	IF @UrlID>0
	BEGIN
		UPDATE Url SET AllResume=AllResume+1,TodayResume=TodayResume+1 WHERE ID=@UrlID
		--Lucifer添加，如果是百度竞价
		IF EXISTS(SELECT 'X' FROM Url WHERE ID=@UrlID AND DescrIption LIKE '%百度竞价%')
			INSERT INTO UrlAccount VALUES(@UrlID,@MaxID,NULL,GETDATE())
	END
	IF @InfoID > 0
	BEGIN
		IF NOT EXISTS(SELECT 'x' FROM Info_DateReport WITH(NOLOCK)
					WHERE CountDate = @CountDate
					AND Province_ID = @dcProvinceID
					AND InfoManager_ID = @InfoID
					)
		INSERT INTO Info_DateReport(Province_ID, Infomanager_ID, CountDate) 
		VALUES(@dcProvinceID, @InfoID, @CountDate)

		UPDATE Info_DateReport 
		SET AllResume = AllResume + 1
		WHERE CountDate = @CountDate
		AND Province_ID = @dcSubSiteID
		AND InfoManager_ID = @InfoID

		INSERT INTO InfoLog(InfoManager_Id, Ip, Referer, paMainId) 
		VALUES(@InfoID, @RegisterIp, '', @MaxID)
	END

	IF @RegFrom = 'a'
		INSERT INTO paFromSeoLog SELECT @MaxId, GETDATE()

END TRY
BEGIN CATCH
	INSERT INTO LogDb..RegisterErrorLog SELECT @MaxId, '11|' + @RegisterIP, @Email + ' ' + @Password, GETDATE()
	RETURN -4
END CATCH

RETURN @MaxID
ERR:
BEGIN
	ROLLBACK TRAN
	INSERT INTO LogDb..RegisterErrorLog SELECT @MaxId, '12|' + @RegisterIP, @Email + ' ' + @Password, GETDATE()
	RETURN -3
END

GO
/****** Object:  StoredProcedure [dbo].[pcPaMainSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[pcPaMainSelect]
(
    @ID INT
)
AS
BEGIN
    SELECT a.*, b.Name AS MapPlaceName,c.Description LiveRegion,d.Description AccountRegion,e.Description GrowRegion,dbo.BirthToAge(a.BirthDay) Age,
        (SELECT COUNT(1) FROM paMain WITH(NOLOCK) WHERE Mobile = a.Mobile) AS MobileCount,
        (SELECT TOP 1 LoginIP FROM paLoginLog WITH(NOLOCK) WHERE paLoginLog.paMainID = a.ID ORDER BY ID DESC) AS LastLoginIP,
        (SELECT COUNT(1) FROM paLoginLog WITH(NOLOCK) WHERE paLoginLog.paMainID = a.ID AND AddDate > CONVERT(VARCHAR(10), GETDATE(), 120)) AS TodayLoginNum,
        (SELECT TOP 1 AddDate FROM PaLoginLog WITH(NOLOCK) WHERE paLoginLog.paMainID = a.ID AND paLoginLog.AddDate < DATEADD(MINUTE, -2, a.LastLoginDate) ORDER BY Adddate DESC) AS PrevLoginDate,
        (SELECT COUNT(1) FROM MainDB..WxFans WHERE PaMainID = a.ID AND Status = 2) WechatBind,
        (SELECT TOP 1 PhotoProcessed FROM paPhoto WITH(NOLOCK INDEX(IX_paPhoto_paMainId)) WHERE paMainID = a.ID AND a.HasPhoto <> 2) AS PhotoProcessed,
		(SELECT TOP 1 Description FROM dcCareerStatus WITH(NOLOCK) WHERE ID = a.dcCareerStatus) AS CareerStatus
    FROM paMain a WITH(NOLOCK INDEX(PK_paMain)) LEFT JOIN dcMapPlace b WITH(NOLOCK) ON a.dcMapPlaceID = b.ID 
	LEFT JOIN dcRegion c WITH(NOLOCK) ON c.ID = a.LivePlace
	LEFT JOIN dcRegion d WITH(NOLOCK) ON d.ID = a.AccountPlace
	LEFT JOIN dcRegion e WITH(NOLOCK) ON e.ID = a.GrowPlace
    WHERE a.ID = @ID
END
GO
/****** Object:  StoredProcedure [dbo].[pcPaMainSelect1]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- 检查:		Sean
-- 日期:		2010-10-5
-- 描述:		提取个人账号信息
-- =============================================
-- =============================================
-- 修改:		Peter
-- 日期:		2013-9-5
-- 描述:		添加获取上一次登录的登录时间
-- =============================================
CREATE PROCEDURE [dbo].[pcPaMainSelect1]
	@ID INT
AS
BEGIN
	SELECT *
	,(SELECT TOP 1 LoginIP FROM paLoginLog WITH(NOLOCK) WHERE paLoginLog.paMainID = paMain.ID ORDER BY ID DESC) AS LastLoginIP
	,(SELECT COUNT(1) FROM paLoginLog WITH(NOLOCK) WHERE paLoginLog.paMainID = paMain.ID AND AddDate > CONVERT(VARCHAR(10), GETDATE(), 120)) AS TodayLoginNum
	,(SELECT TOP 1 AddDate FROM PaLoginLog WITH(NOLOCK) WHERE paLoginLog.paMainID = paMain.ID AND paLoginLog.AddDate < DATEADD(MINUTE, -2, paMain.LastLoginDate) ORDER BY Adddate DESC) AS PrevLoginDate
	FROM paMain WITH(NOLOCK INDEX(PK_paMain)) 
	WHERE ID=@ID
END











GO
/****** Object:  StoredProcedure [dbo].[pcPaMainSelectByPhone]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[pcPaMainSelectByPhone]
	@ID INT
AS
BEGIN
	SELECT a.*,b.FullName LiveRegion,c.FullName GrowRegion,d.FullName AccountRegion,e.Description CareerStatus
	,(SELECT TOP 1 LoginIP FROM paLoginLog WITH(NOLOCK) WHERE paLoginLog.paMainID = a.ID ORDER BY ID DESC) AS LastLoginIP,
	(SELECT COUNT(1) FROM paLoginLog WITH(NOLOCK) WHERE paLoginLog.paMainID = a.ID AND AddDate > CONVERT(VARCHAR(10), GETDATE(), 120)) AS TodayLoginNum
	FROM paMain a WITH(NOLOCK INDEX(PK_paMain))
	INNER JOIN dcRegion b WITH(NOLOCK) ON a.LivePlace=b.ID
	INNER JOIN dcRegion c WITH(NOLOCK) ON a.GrowPlace=c.ID
	INNER JOIN dcRegion d WITH(NOLOCK) ON a.AccountPlace=d.ID
	INNER JOIN dcCareerStatus e WITH(NOLOCK) ON a.dcCareerStatus=e.ID
	WHERE a.ID=@ID
END














GO
/****** Object:  StoredProcedure [dbo].[pcPaMainUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


-- =============================================
-- Author:		Sean
-- Check date:	2010-9-17
-- Description:	修改账号信息	，cvMainID为0时不修改cvmain信息
--修改：Peter 2016-03-30 一分钟填写简历同时修改求职状态
--修改harry 2018-7-5 处理liveplace等
-- =============================================
CREATE PROCEDURE [dbo].[pcPaMainUpdate]
(
	@Type INT,
	@paMainID INT,
	@cvMainID INT,
	@Name VARCHAR(30),
	@Gender BIT,
	@BirthDay INT,
	@LivePlace VARCHAR(6),
	@AccountPlace VARCHAR(6),
	@GrowPlace VARCHAR(6),
	@Mobile VARCHAR(13),
	@OnlineContact TINYINT,
	@OnlineContactNo VARCHAR(50),
	@Homepage VARCHAR(200),
	@Marriage TINYINT,
	@Nation TINYINT,
	@Height TINYINT,
	@dcCareerStatus TINYINT,
	@IP VARCHAR(39)
)
AS
SET NOCOUNT ON
IF CHARINDEX('<', @Name) > 0
	SET @Name = REPLACE(@Name, '<', '')
IF CHARINDEX('<', @OnlineContactNo) > 0
	SET @OnlineContactNo = REPLACE(@OnlineContactNo, '<', '')
IF CHARINDEX('<', @Homepage) > 0
	SET @Homepage = REPLACE(@Homepage, '<', '')
IF ISNULL(@paMainID, 0) = 0
	RETURN -9
IF dbo.TrimNULL(@Name) IS NULL
	RETURN -8
IF dbo.TrimNULL(@Mobile) IS NULL
	RETURN -7
IF @dcCareerStatus = 0
	SET @dcCareerStatus = NULL
IF @Marriage = 0
	SET @Marriage = NULL
IF @Nation = 0
	SET @Nation = NULL
IF EXISTS(SELECT 'x' FROM Person_BLACK WITH(NOLOCK) WHERE Mobile = @Mobile)
BEGIN
	----有黑名单，则增加拒绝次数
	UPDATE Person_Black SET RefuseCount = RefuseCount + 1 WHERE Mobile = @Mobile
	RETURN -1
END
BEGIN TRAN
	BEGIN TRY
	
		IF  CHARINDEX(' ', @LivePlace) >2
		BEGIN
			SET @LivePlace=substring(@LivePlace,1,charindex(' ',@LivePlace)-1)
		END
		IF  CHARINDEX(' ', @AccountPlace) >2
		BEGIN
			SET @AccountPlace=substring(@AccountPlace,1,charindex(' ',@AccountPlace)-1)
		END
		IF  CHARINDEX(' ', @GrowPlace) >2
		BEGIN
			SET @GrowPlace=substring(@GrowPlace,1,charindex(' ',@GrowPlace)-1)
		END
		
		DECLARE @NameEngOld AS VARCHAR(30)
		DECLARE @NameOld AS VARCHAR(12)
		DECLARE @OnlineContactNoOld AS VARCHAR(50)
		DECLARE @HomepageOld AS VARCHAR(200)
		DECLARE @MobileOld AS VARCHAR(13)
		DECLARE @Modify AS INT
		-- @Modify=-1未修改需审核项， @Modify=0修改中文项目； @Modify=1修改了英文项目
		SET @Modify=-1
		--检查在线联系方式和号码
		IF @OnlineContact IS NULL
			SET @OnlineContactNo = ''
		ELSE
			SET @OnlineContactNo = dbo.SafeSql(@OnlineContactNo)
		--取消不正确的主页格式
		SET @Homepage=REPLACE(@Homepage,'http%3A//','http://')
		SET @Homepage=REPLACE(@Homepage,'http://','')
		IF LTRIM(RTRIM(@Homepage)) = 'http://'
			SET @Homepage = null
		IF ISNULL(@Homepage, '') = ''
			SET @Homepage = null
		IF ISNULL(@OnlineContactNo, '') = ''
			SET @OnlineContactNo = null

		--获得原始数据
		SELECT @NameOld=Name,@NameEngOld=NameEng,@OnlineContactNoOld=OnlineContactNo,@HomepageOld=Homepage,@MobileOld=Mobile
		FROM paMain WITH(NOLOCK INDEX(PK_paMain))
		WHERE ID = @paMainID

		--0中文，1英文，只有姓名不同
		IF @TYPE=0
		BEGIN
			DECLARE @CNAME AS VARCHAR(12)
			SET @CNAME = @Name
			UPDATE paMain
			SET Name=@CNAME,
				Gender=@Gender,
				BirthDay=@BirthDay,
				LivePlace=@LivePlace,
				AccountPlace=@AccountPlace,
				GrowPlace=@GrowPlace,
				Mobile=@Mobile,
				OnlineContact=@OnlineContact,
				OnlineContactNo=@OnlineContactNo,
				Homepage=@Homepage,
				Marriage=@Marriage, 
				Nation=@Nation,
				Height=@Height,
				dcCareerStatus=@dcCareerStatus,
				LastModifyDate=GETDATE()
			WHERE ID=@paMainID
		END
		ELSE
			UPDATE paMain
			SET NameENG=@Name,
				Gender=@Gender,
				BirthDay=@BirthDay,
				LivePlace=@LivePlace,
				AccountPlace=@AccountPlace,
				GrowPlace=@GrowPlace,
				Mobile=@Mobile,
				OnlineContact=@OnlineContact,
				OnlineContactNo=@OnlineContactNo,
				Homepage=@Homepage,
				Marriage=@Marriage, 
				Nation=@Nation,
				Height=@Height,
				dcCareerStatus=@dcCareerStatus,
				LastModifyDate=GETDATE()
			WHERE ID=@paMainID

		--保存到bsCvModify,姓名
		IF @TYPE=0
		BEGIN
			IF ISNULL(@NameOld, '') <> @CNAME
			BEGIN
				DELETE FROM bsCvModify WHERE paMainID = @paMainID AND Location = 'ac1'
				INSERT INTO bsCvModify(paMainID,Location,ColValue) VALUES(@paMainID,'ac1',@CNAME)
				SET @Modify=0

				INSERT INTO paOperationLog (paMainID, Operation, Details, IP) 
				VALUES(@paMainID, 30,'更新姓名，原姓名：<' + ISNULL(@NameOld, '') + '>；新姓名：<' + @CName + '>', @IP)
			END
		END
		ELSE
			IF ISNULL(@NameOld, '') <> @Name
			BEGIN
				DELETE FROM bsCvModify WHERE paMainID = @paMainID AND Location = 'ae1'
				INSERT INTO bsCvModify(paMainID,Location,ColValue) VALUES(@paMainID,'ae1',@CNAME)
				SET @Modify=1

				INSERT INTO paOperationLog (paMainID, Operation, Details, IP) 
				VALUES(@paMainID, 31,'更新英文名，原英文名：<' + ISNULL(@NameOld, '') + '>；新英文名：<' + @Name + '>', @IP)
			END

		--在线联系号码
		IF @OnlineContactNo IS NULL
			DELETE FROM bsCvModify WHERE paMainID = @paMainID AND Location = 'ac2'
		ELSE
			IF @OnlineContactNo <> ISNULL(@OnlineContactNoOld, '')
			BEGIN
				DELETE FROM bsCvModify WHERE paMainID = @paMainID AND Location = 'ac2'
				INSERT INTO bsCvModify(paMainID,Location,ColValue) VALUES(@paMainID,'ac2',@OnlineContactNo)
				SET @Modify=0
			END

		--主页
		IF @Homepage IS NULL
			DELETE FROM bsCvModify WHERE paMainID = @paMainID AND Location = 'ac3'
		ELSE
			IF @Homepage <> ISNULL(@HomepageOld, '')
			BEGIN
				DELETE FROM bsCvModify WHERE paMainID = @paMainID AND Location = 'ac3'
				INSERT INTO bsCvModify(paMainID,Location,ColValue) VALUES(@paMainID,'ac3',@Homepage)
				SET @Modify=0
			END

		--手机号码
		IF ISNULL(@MobileOld, '') <> @Mobile
		BEGIN
			DELETE FROM bsCvModify WHERE paMainID = @paMainID AND Location = 'ac4'
			--INSERT INTO bsCvModify(paMainID,Location,ColValue) VALUES(@paMainID,'ac4',@Mobile)
			--SET @Modify=0

			INSERT INTO paOperationLog (paMainID, Operation, Details, IP) 
			VALUES(@paMainID, 35,'更新手机号，原手机号：<' + ISNULL(@MobileOld, '') + '>；新手机号：<' + @Mobile + '>', @IP)
		END
		
		----修改cvMain.cvLevel
		IF @TYPE=0
			UPDATE cvMain SET cvLevel='11' + RIGHT(cvLevel,8) WHERE paMainID = @paMainID
		ELSE
			UPDATE cvMain SET cvLevelEng='11' + RIGHT(cvLevelEng,8) WHERE paMainID = @paMainID

		--1小时内不重复刷新，防止刷新排名
		UPDATE cvmain SET RefreshDate = GETDATE() WHERE ID=@cvMainID AND DATEADD(HOUR, 1, RefreshDate) < GETDATE() AND paMainID = @paMainID
		----12小时内只保留一次修改记录
		DELETE FROM paOperationLog WHERE paMainID=@paMainID AND Operation=11 AND AddDate>GETDATE()-0.5
		INSERT INTO paOperationLog (paMainID,Operation,Details,IP) VALUES(@paMainID,11,'更新基本信息成功。',@IP)

	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH

COMMIT TRAN
RETURN 1
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END 

GO
/****** Object:  StoredProcedure [dbo].[pcPaMainUpdate20171108]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


-- =============================================
-- Author:		Sean
-- Check date:	2010-9-17
-- Description:	修改账号信息	，cvMainID为0时不修改cvmain信息
--修改：Peter 2016-03-30 一分钟填写简历同时修改求职状态
--修改harry 2018-7-5 处理liveplace等
-- =============================================
CREATE PROCEDURE [dbo].[pcPaMainUpdate20171108]
(
	@Type INT,
	@paMainID INT,
	@cvMainID INT,
	@Name VARCHAR(30),
	@Gender BIT,
	@BirthDay INT,
	@LivePlace VARCHAR(6),
	@AccountPlace VARCHAR(6),
	@GrowPlace VARCHAR(6),
	@Mobile VARCHAR(13),
	@OnlineContact TINYINT,
	@OnlineContactNo VARCHAR(50),
	@Homepage VARCHAR(200),
	@Marriage TINYINT,
	@Nation TINYINT,
	@Height TINYINT,
	@dcCareerStatus TINYINT,
	@IP VARCHAR(39),
	@dcMapPlaceId INT
)
AS
SET NOCOUNT ON
IF CHARINDEX('<', @Name) > 0
	SET @Name = REPLACE(@Name, '<', '')
IF CHARINDEX('<', @OnlineContactNo) > 0
	SET @OnlineContactNo = REPLACE(@OnlineContactNo, '<', '')
IF CHARINDEX('<', @Homepage) > 0
	SET @Homepage = REPLACE(@Homepage, '<', '')
IF ISNULL(@paMainID, 0) = 0
	RETURN -9
IF dbo.TrimNULL(@Name) IS NULL
	RETURN -8
IF dbo.TrimNULL(@Mobile) IS NULL
	RETURN -7
IF @dcCareerStatus = 0
	SET @dcCareerStatus = NULL
IF @Marriage = 0
	SET @Marriage = NULL
IF @Nation = 0
	SET @Nation = NULL
IF EXISTS(SELECT 'x' FROM Person_BLACK WITH(NOLOCK) WHERE Mobile = @Mobile)
BEGIN
	----有黑名单，则增加拒绝次数
	UPDATE Person_Black SET RefuseCount = RefuseCount + 1 WHERE Mobile = @Mobile
	RETURN -1
END
BEGIN TRAN
	BEGIN TRY
	
		IF  CHARINDEX(' ', @LivePlace) >2
		BEGIN
			SET @LivePlace=substring(@LivePlace,1,charindex(' ',@LivePlace)-1)
		END
		IF  CHARINDEX(' ', @AccountPlace) >2
		BEGIN
			SET @AccountPlace=substring(@AccountPlace,1,charindex(' ',@AccountPlace)-1)
		END
		IF  CHARINDEX(' ', @GrowPlace) >2
		BEGIN
			SET @GrowPlace=substring(@GrowPlace,1,charindex(' ',@GrowPlace)-1)
		END
		
		DECLARE @NameEngOld AS VARCHAR(30)
		DECLARE @NameOld AS VARCHAR(12)
		DECLARE @OnlineContactNoOld AS VARCHAR(50)
		DECLARE @HomepageOld AS VARCHAR(200)
		DECLARE @MobileOld AS VARCHAR(13)
		DECLARE @Modify AS INT
		-- @Modify=-1未修改需审核项， @Modify=0修改中文项目； @Modify=1修改了英文项目
		SET @Modify=-1
		--检查在线联系方式和号码
		IF @OnlineContact IS NULL
			SET @OnlineContactNo = ''
		ELSE
			SET @OnlineContactNo = dbo.SafeSql(@OnlineContactNo)
		--取消不正确的主页格式
		SET @Homepage=REPLACE(@Homepage,'http%3A//','http://')
		SET @Homepage=REPLACE(@Homepage,'http://','')
		IF LTRIM(RTRIM(@Homepage)) = 'http://'
			SET @Homepage = null
		IF ISNULL(@Homepage, '') = ''
			SET @Homepage = null
		IF ISNULL(@OnlineContactNo, '') = ''
			SET @OnlineContactNo = null

		--获得原始数据
		SELECT @NameOld=Name,@NameEngOld=NameEng,@OnlineContactNoOld=OnlineContactNo,@HomepageOld=Homepage,@MobileOld=Mobile
		FROM paMain WITH(NOLOCK INDEX(PK_paMain))
		WHERE ID = @paMainID

		--0中文，1英文，只有姓名不同
		IF @TYPE=0
		BEGIN
			DECLARE @CNAME AS VARCHAR(12)
			SET @CNAME = @Name
			UPDATE paMain
			SET Name=@CNAME,
				Gender=@Gender,
				BirthDay=@BirthDay,
				LivePlace=@LivePlace,
				AccountPlace=@AccountPlace,
				GrowPlace=@GrowPlace,
				Mobile=@Mobile,
				OnlineContact=@OnlineContact,
				OnlineContactNo=@OnlineContactNo,
				Homepage=@Homepage,
				Marriage=@Marriage, 
				Nation=@Nation,
				Height=@Height,
				dcCareerStatus=@dcCareerStatus,
				dcMapPlaceId = @dcMapPlaceId,
				LastModifyDate=GETDATE()
			WHERE ID=@paMainID
		END
		ELSE
			UPDATE paMain
			SET NameENG=@Name,
				Gender=@Gender,
				BirthDay=@BirthDay,
				LivePlace=@LivePlace,
				AccountPlace=@AccountPlace,
				GrowPlace=@GrowPlace,
				Mobile=@Mobile,
				OnlineContact=@OnlineContact,
				OnlineContactNo=@OnlineContactNo,
				Homepage=@Homepage,
				Marriage=@Marriage, 
				Nation=@Nation,
				Height=@Height,
				dcCareerStatus=@dcCareerStatus,
				dcMapPlaceId = @dcMapPlaceId,
				LastModifyDate=GETDATE()
			WHERE ID=@paMainID

		--保存到bsCvModify,姓名
		IF @TYPE=0
		BEGIN
			IF ISNULL(@NameOld, '') <> @CNAME
			BEGIN
				DELETE FROM bsCvModify WHERE paMainID = @paMainID AND Location = 'ac1'
				INSERT INTO bsCvModify(paMainID,Location,ColValue) VALUES(@paMainID,'ac1',@CNAME)
				SET @Modify=0

				INSERT INTO paOperationLog (paMainID, Operation, Details, IP) 
				VALUES(@paMainID, 30,'更新姓名，原姓名：<' + ISNULL(@NameOld, '') + '>；新姓名：<' + @CName + '>', @IP)
			END
		END
		ELSE
			IF ISNULL(@NameOld, '') <> @Name
			BEGIN
				DELETE FROM bsCvModify WHERE paMainID = @paMainID AND Location = 'ae1'
				INSERT INTO bsCvModify(paMainID,Location,ColValue) VALUES(@paMainID,'ae1',@CNAME)
				SET @Modify=1

				INSERT INTO paOperationLog (paMainID, Operation, Details, IP) 
				VALUES(@paMainID, 31,'更新英文名，原英文名：<' + ISNULL(@NameOld, '') + '>；新英文名：<' + @Name + '>', @IP)
			END

		--在线联系号码
		IF @OnlineContactNo IS NULL
			DELETE FROM bsCvModify WHERE paMainID = @paMainID AND Location = 'ac2'
		ELSE
			IF @OnlineContactNo <> ISNULL(@OnlineContactNoOld, '')
			BEGIN
				DELETE FROM bsCvModify WHERE paMainID = @paMainID AND Location = 'ac2'
				INSERT INTO bsCvModify(paMainID,Location,ColValue) VALUES(@paMainID,'ac2',@OnlineContactNo)
				SET @Modify=0
			END

		--主页
		IF @Homepage IS NULL
			DELETE FROM bsCvModify WHERE paMainID = @paMainID AND Location = 'ac3'
		ELSE
			IF @Homepage <> ISNULL(@HomepageOld, '')
			BEGIN
				DELETE FROM bsCvModify WHERE paMainID = @paMainID AND Location = 'ac3'
				INSERT INTO bsCvModify(paMainID,Location,ColValue) VALUES(@paMainID,'ac3',@Homepage)
				SET @Modify=0
			END

		--手机号码
		IF ISNULL(@MobileOld, '') <> @Mobile
		BEGIN
			DELETE FROM bsCvModify WHERE paMainID = @paMainID AND Location = 'ac4'
			--INSERT INTO bsCvModify(paMainID,Location,ColValue) VALUES(@paMainID,'ac4',@Mobile)
			--SET @Modify=0

			INSERT INTO paOperationLog (paMainID, Operation, Details, IP) 
			VALUES(@paMainID, 35,'更新手机号，原手机号：<' + ISNULL(@MobileOld, '') + '>；新手机号：<' + @Mobile + '>', @IP)
		END
		
		----修改cvMain.cvLevel
		IF @TYPE=0
			UPDATE cvMain SET cvLevel='11' + RIGHT(cvLevel,8) WHERE paMainID = @paMainID
		ELSE
			UPDATE cvMain SET cvLevelEng='11' + RIGHT(cvLevelEng,8) WHERE paMainID = @paMainID

		--1小时内不重复刷新，防止刷新排名
		UPDATE cvmain SET RefreshDate = GETDATE() WHERE ID=@cvMainID AND DATEADD(HOUR, 1, RefreshDate) < GETDATE() AND paMainID = @paMainID
		----12小时内只保留一次修改记录
		DELETE FROM paOperationLog WHERE paMainID=@paMainID AND Operation=11 AND AddDate>GETDATE()-0.5
		INSERT INTO paOperationLog (paMainID,Operation,Details,IP) VALUES(@paMainID,11,'更新基本信息成功。',@IP)

	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH

COMMIT TRAN
RETURN 1
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END


GO
/****** Object:  StoredProcedure [dbo].[pcPaNotifyByIsViewedUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


-----------------
--个人会员中心首页，修改网站消息是否查看
-----------------
CREATE PROCEDURE [dbo].[pcPaNotifyByIsViewedUpdate]
(
	@paNotifyID INT,
	@paMainID INT	
)
AS
BEGIN
	IF EXISTS(SELECT 'x' FROM paNotify WITH(NOLOCK)
				WHERE ID = @paNotifyID
				AND paMainID = @paMainID
				AND IsViewed = 0)
		UPDATE paNotify SET IsViewed = 1
		WHERE ID = @paNotifyID
		AND paMainID = @paMainID
END














GO
/****** Object:  StoredProcedure [dbo].[pcPaNotifyByPaMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


-----------------
--网站消息列表
-----------------
CREATE PROCEDURE [dbo].[pcPaNotifyByPaMainIDSelect]
(
 @paMainID INT
)
AS
BEGIN
	SELECT ID, AddDate, NotifyType, Substring(Message, 0 ,20) Message, IsViewed, ENDDate
	FROM PaNotify WITH(NOLOCK)
	WHERE paMainID = @paMainID 
	ORDER BY ID DESC
END














GO
/****** Object:  StoredProcedure [dbo].[pcPaNotifySelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


-----------------
--个人会员中心首页，显示网站消息通知
-----------------
CREATE PROCEDURE [dbo].[pcPaNotifySelect]
(
 @paMainID INT
)
AS
BEGIN
	SELECT ID, AddDate, NotifyType, Message
	FROM PaNotify WITH(NOLOCK)
	WHERE paMainID = @paMainID 
	AND (
		(NotifyType = 1 AND IsViewed = 0)			--一次性消息，看过就不再通知了
		OR (NotifyType=2 AND ENDDate > GETDATE())	--即时消息，到期前（ENDdate）一直通知
	)
	ORDER BY ID DESC
END



GO
/****** Object:  StoredProcedure [dbo].[pcpaOperationLogSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--=============================================
-- 创建：		sean
-- 检查：		2010-10-6
-- 说明：		操作记录列表
--=============================================
CREATE PROCEDURE [dbo].[pcpaOperationLogSelect]
(
	@paMainID INT
)
AS
BEGIN
	SELECT TOP 1000 * FROM paOperationLog WITH(NOLOCK INDEX(IX_paOperationLog_paMainID)) 
	WHERE paMainID = @paMainID
	ORDER BY ID DESC	
END



GO
/****** Object:  StoredProcedure [dbo].[pcpaPhoto_beforeInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- lambo
-- 2011-05-24
-- 将上传照片的信息先放在paPhoto_before中

CREATE PROCEDURE [dbo].[pcpaPhoto_beforeInsert]
	@paMainID INT,
	@Photo VARCHAR(50)
AS

DECLARE @MaxId AS INT

INSERT INTO paPhoto_before (paMainID,FileUrl)
	VALUES(@paMainID,dbo.SafeSQL(@Photo))
SET @MaxID = @@IDENTITY

RETURN @MaxID














GO
/****** Object:  StoredProcedure [dbo].[pcpaPhotoDelete]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--=============================================
-- 创建：		sean
-- 检查：		2010-10-6
-- 说明：		照片删除
--=============================================
CREATE PROCEDURE [dbo].[pcpaPhotoDelete]
(
	@paMainID INT,
	@IP VARCHAR(39)
)
AS
BEGIN TRAN
	BEGIN TRY
		DELETE FROM paPhoto WHERE paMainID=@paMainID
		UPDATE paMain SET HasPhoto=NULL WHERE ID=@paMainID

		INSERT INTO paOperationLog (paMainID, Operation, Details, IP) 
			VALUES(@paMainID, 41, '删除照片', @IP)
	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH
COMMIT TRAN
RETURN 1
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END 














GO
/****** Object:  StoredProcedure [dbo].[pcpaPhotoInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--=============================================
-- 创建：		sean
-- 检查：		2010-10-6
-- 说明：		照片上传
--=============================================
CREATE PROCEDURE [dbo].[pcpaPhotoInsert]
	@paMainID INT
AS
BEGIN TRAN
	DECLARE @MaxId AS INT
	BEGIN TRY
		DELETE FROM paPhoto WHERE paMainID=@paMainID
		UPDATE paMain SET HasPhoto=0 WHERE ID=@paMainID
		INSERT INTO paPhoto (paMainID,Photo,PhotoProcessed)
			SELECT TOP 1 paMainID , FileUrl,FileUrl FROM paPhoto_before WHERE paMainID = @paMainID ORDER BY ID DESC
		DELETE FROM paPhoto_before WHERE ID  = (SELECT TOP 1 ID FROM paPhoto_before WHERE paMainID = @paMainID ORDER BY ID DESC) 
		INSERT INTO paOperationLog (paMainID,Operation,Details,IP) 
			VALUES(@paMainID,40,'更新照片', '')
		SET @MaxID = @@IDENTITY
	END TRY
	BEGIN cATCH
		GOTO ERR
	END CATCH
COMMIT TRAN
RETURN @MaxID
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END














GO
/****** Object:  StoredProcedure [dbo].[pcpaPhotoSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--=============================================
-- 创建：		sean
-- 检查：		2010-10-6
-- 说明：		照片信息提取
--=============================================
CREATE PROCEDURE [dbo].[pcpaPhotoSelect]
	@paMainID INT
AS
BEGIN
	SELECT a.*,b.HasPhoto
	FROM paPhoto a WITH(NOLOCK INDEX(IX_paPhoto_paMainId)),paMain b with(NOLOCK) WHERE a.paMainID = b.ID AND a.paMainID=@paMainID
END














GO
/****** Object:  StoredProcedure [dbo].[pcPaPlaintByIsViewedUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--==================================================
--检查 Alen 2017-9-15
--描述 修改投诉记录为已查看
--==================================================
CREATE PROCEDURE [dbo].[pcPaPlaintByIsViewedUpdate]
(
	@paMainID INT
)
AS
BEGIN
	UPDATE MainDB..paplaint 
	SET IsViewed = 1 
	WHERE paMainID = @paMainID 
	AND IsViewed = 0 
	AND ReplyType > 0
END
GO
/****** Object:  StoredProcedure [dbo].[pcPaPlaintByNameInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--修改harry，增加顾问提醒2017-9-26
--修改harry 无顾问的提醒给客服
CREATE PROCEDURE [dbo].[pcPaPlaintByNameInsert]
(
    @paMainID INT, 
	@caMainID INT, 
    @jobID INT, 
    @IP VARCHAR(50), 
    @Name NVARCHAR(50), 
    @Telephone VARCHAR(11), 
    @Email VARCHAR(50), 
    @Plaint NVARCHAR(200)
)
AS
SET NOCOUNT ON
BEGIN
	INSERT INTO mainDB..paPlaint(paMainID, caMainID, jobID, IP, Name, Telephone, Email, Plaint, AddDate, ReplyType)
    VALUES(@paMainID, @caMainID, @jobID, @IP, @Name, @Telephone, @Email, @Plaint, GETDATE(), 0)
    
    IF EXISTS (SELECT 'x' FROM caMain a, cpMain b, managerUser c 
    	WHERE a.cpMainId = b.Id 
		AND b.ConsultantId > 0 AND a.id =@caMainID AND c.id=b.ConsultantId AND c.status<3)
	BEGIN
		INSERT INTO RtxNotifyLog(Receiver, RtxTitle, RtxMessage, SendType, DelayTime, ShowType) 
    	SELECT ConsultantId, '个人投诉企业通知','投诉内容：'+@Plaint+ ' http://sysback.51rc.com/newoa/operate/complaint/paPlaint?isReply=3&selType=2&selOption=0&txtSearch='+CONVERT(CHAR(10),@caMainID), 1, 0, 0
    	FROM caMain a, cpMain b WHERE a.cpMainId = b.Id AND b.ConsultantId > 0 AND a.id =@caMainID
	END
	ELSE
	BEGIN
		INSERT INTO RtxNotifyLog(Receiver, RtxTitle, RtxMessage, SendType, DelayTime, ShowType) 
    	SELECT '180,182,222,223,216', '个人投诉企业通知','投诉内容：'+@Plaint+ ' http://sysback.51rc.com/newoa/operate/complaint/paPlaint?isReply=3&selType=2&selOption=0&txtSearch='+CONVERT(CHAR(10),@caMainID), 1, 0, 0
    	FROM caMain a, cpMain b WHERE a.cpMainId = b.Id AND a.id =@caMainID
	END
END 
SET NOCOUNT OFF 

GO
/****** Object:  StoredProcedure [dbo].[pcPaPlaintInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[pcPaPlaintInsert]
(
	@paMainID INT,
	@caMainID INT,
	@Plaint VARCHAR(1000),
	@JobID INT,
	@ConsultantId INT OUTPUT
)
AS
BEGIN TRY
	IF NOT EXISTS(SELECT 'X' FROM paPlaint 
		WHERE paMainID = @paMainID AND JobID = @JobID AND AddDate > GETDATE() - 30)
	BEGIN
		INSERT INTO paPlaint(paMainID, caMainID, PlaINT, JobID)
		VALUES(@paMainID, @caMainID, dbo.SafeSQL(@PlaINT), @JobID)
	 
		SELECT @ConsultantId = ConsultantID FROM cpMain a WITH(NOLOCK), caMain b WITH(NOLOCK)
		WHERE a.Id = b.cpMainId
		AND b.Id = @caMainId
	 
		RETURN 1
	END
	ELSE
	BEGIN
		SELECT @ConsultantId = 0
		RETURN 0
	END
END TRY
BEGIN CATCH
	RETURN 0
END CATCH














GO
/****** Object:  StoredProcedure [dbo].[pcPaPlaintSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--=================================
--检查		sean 2010-10-9
--描述		个人查看自己的投诉记录
--修改      Alen 个人投诉二次改版   2017-9-15
--=================================
CREATE PROCEDURE [dbo].[pcPaPlaintSelect]
(
    @paMainID INT,
	@isIndex TINYINT
)
AS
BEGIN
	IF @isIndex = 0
	BEGIN
		SELECT a.*,c.ID cpMainID,c.Name CompanyName,c.secondID
		FROM PaPlaint a WITH(NOLOCK)
		LEFT JOIN caMain b WITH(NOLOCK) ON a.caMainID = b.ID
		LEFT JOIN cpMain c WITH(NOLOCK) ON b.cpMainID = c.ID
		WHERE paMainID = @paMainID
		ORDER BY ID DESC
	END
	ELSE
	BEGIN
		SELECT a.*,c.ID cpMainID,c.Name CompanyName,c.secondID
		FROM PaPlaint a WITH(NOLOCK)
		LEFT JOIN caMain b WITH(NOLOCK) ON a.caMainID = b.ID
		LEFT JOIN cpMain c WITH(NOLOCK) ON b.cpMainID = c.ID
		WHERE paMainID = @paMainID
		AND IsViewed = 0
		AND ReplyType > 0
		ORDER BY ID DESC
	END
END

GO
/****** Object:  StoredProcedure [dbo].[PcPaRefererInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[PcPaRefererInsert]
(
	@PaMainId INT,
	@Referer VARCHAR(500)
)
AS
SET NOCOUNT ON
BEGIN TRY
	--IF EXISTS(SELECT 'x' FROM paMain WITH(NOLOCK) 
	--	WHERE Id = @paMainId AND AddDate > DATEADD(MINUTE, -2, GETDATE()))
		INSERT INTO paReferer(paMainId, Referer)
		SELECT @paMainId, @Referer
END TRY
BEGIN CATCH
END CATCH
GO
/****** Object:  StoredProcedure [dbo].[pcPaVerifyLogByLoginInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--个人手机号登录验证码插入
--peter 2018-2-28
CREATE PROCEDURE [dbo].[pcPaVerifyLogByLoginInsert] 
(
    @Mobile VARCHAR(11), 
    @IP VARCHAR(31),
	@PaMainID INT
)
AS
SET NOCOUNT ON
BEGIN
    IF CHARINDEX(', ', @Ip) > 0
        SET @Ip = RIGHT(@ip, LEN(@ip) - CHARINDEX(', ', @ip))

    DECLARE @VerifyCount SMALLINT
    SELECT @VerifyCount = COUNT(1) FROM paVerifyLog WITH(NOLOCK)
    WHERE IP = @IP 
    AND AddDate > CONVERT(VARCHAR(10), GETDATE(), 120)

    IF @VerifyCount > 10  --一天同一IP验证超过三次
        RETURN -2

    SELECT @VerifyCount = COUNT(1) FROM paVerifyLog WITH(NOLOCK)
    WHERE Mobile = @Mobile 
    AND AddDate > CONVERT(VARCHAR(10), GETDATE(), 120)

    IF @VerifyCount > 5  --一天同一手机号验证超过两次
        RETURN -3

    SELECT @VerifyCount = COUNT(1) FROM paVerifyLog WITH(NOLOCK)
    WHERE Mobile = @Mobile 
    AND AddDate > DATEADD(MINUTE, -5, GETDATE())  --五分钟内同一手机号超过三次

    IF @VerifyCount > 3
        RETURN -4

    DECLARE @VerifyCode AS VARCHAR(6)
    SELECT @VerifyCode = RAND() * 899999 + 100000
    INSERT INTO paVerifyLog(paMainID, Email, Mobile, VerifyCode, VerifyDate, AddDate, ip)
    VALUES(@PaMainID, '', @Mobile, @VerifyCode, NULL, GETDATE(), @IP)

    RETURN @VerifyCode
END
GO
/****** Object:  StoredProcedure [dbo].[pcPaVerifyLogByMobileIpSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.4
--创建人：John
--说明：获取个人手机/邮件验证日志
--#####################################################
CREATE PROCEDURE [dbo].[pcPaVerifyLogByMobileIpSelect]
(
	@Mobile VARCHAR(11),
	@ip VARCHAR(31)
)
AS
BEGIN
	SELECT TOP 1 * FROM paVerifyLog WITH(NOLOCK) 
	WHERE Mobile = @Mobile AND AddDate > DATEADD(HOUR,-1,GETDATE()) ORDER BY id DESC
END
GO
/****** Object:  StoredProcedure [dbo].[pcPaVerifyLogInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--lambo 20140909
--手机号注册，前台发送验证码
--20180327 Carl 修改  增加个人黑名单
CREATE PROCEDURE [dbo].[pcPaVerifyLogInsert] 
(
	@Mobile VARCHAR(11), 
	@IP VARCHAR(31)
)
AS
SET NOCOUNT ON
BEGIN

	IF EXISTS(SELECT 'X' FROM Person_Black WITH(NOLOCK) WHERE Mobile = @Mobile)
		RETURN -5

	IF EXISTS(SELECT 'x' FROM tmp_limitmobile WITH(NOLOCK) WHERE Mobile = @Mobile)
		RETURN -1

	IF DATEPART(HOUR, GETDATE()) > 22 OR DATEPART(HOUR, GETDATE()) < 7
		RETURN -1

	--IF CHARINDEX(', ', @Ip) > 0
	--	RETURN -1
	IF CHARINDEX(', ', @Ip) > 0
		SET @Ip = RIGHT(@ip, LEN(@ip) - CHARINDEX(', ', @ip))

	DECLARE @MobileVerifyDate DATETIME
	SELECT @MobileVerifyDate = MobileVerifyDate FROM paMain WITH(NOLOCK INDEX(IX_paMain_Mobile)) 
	WHERE Mobile = @Mobile 
	AND MobileVerifyDate IS NOT NULL

	IF @MobileVerifyDate IS NOT NULL
		IF DATEDIFF(DAY, @MobileVerifyDate, GETDATE()) < 60
			RETURN -2

	DECLARE @VerifyCount SMALLINT
	SELECT @VerifyCount = COUNT(1) FROM paVerifyLog WITH(NOLOCK)
	WHERE IP = @IP 
	AND AddDate > CONVERT(VARCHAR(10), GETDATE(), 120)

	IF @VerifyCount > 3		--IF @VerifyCount > 3
		RETURN -1

	SELECT @VerifyCount = COUNT(1) FROM paVerifyLog WITH(NOLOCK)
	WHERE Mobile = @Mobile 
	AND AddDate > CONVERT(VARCHAR(10), GETDATE(), 120)

	IF @VerifyCount > 2		--IF @VerifyCount > 2
		RETURN 0

	SELECT @VerifyCount = COUNT(1) FROM paVerifyLog WITH(NOLOCK)
	WHERE Mobile = @Mobile 
	AND AddDate > DATEADD(MINUTE, -5, GETDATE())

	IF @VerifyCount > 3		--IF @VerifyCount > 3
		RETURN 0

	DECLARE @VerifyCode AS VARCHAR(6)
	SELECT @VerifyCode = RAND() * 899999 + 100000
	INSERT INTO paVerifyLog(paMainID, Email, Mobile, VerifyCode, VerifyDate, AddDate, ip)
	VALUES(0, '', @Mobile, @VerifyCode, NULL, GETDATE(), @IP)

	RETURN @VerifyCode
END

GO
/****** Object:  StoredProcedure [dbo].[pcPaVerifyLogPaMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.4
--创建人：John
--说明：获取1小时内是否发送过认证请求
--#####################################################
CREATE PROCEDURE [dbo].[pcPaVerifyLogPaMainIDSelect]
(
	@Mobile VARCHAR(11),
	@paMainID INT,
	@Email VARCHAR(50)
)
AS
BEGIN
	IF @Mobile <> ''
	BEGIN
		SELECT paMainID FROM paVerifyLog WITH(NOLOCK) 
		WHERE paMainID = @paMainID AND Mobile = @Mobile AND AddDate > DATEADD(HOUR,-1,GETDATE()) AND VerifyDate IS NULL
	END
	ELSE
	BEGIN
		SELECT paMainID FROM paVerifyLog WITH(NOLOCK) 
		WHERE paMainID = @paMainID AND Email = @Email AND AddDate> DATEADD(HOUR,-1,GETDATE())
	END
END


GO
/****** Object:  StoredProcedure [dbo].[pcPaVerifyLogUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.4
--创建人：John
--说明：更新个人手机/邮件验证日志
--#####################################################
CREATE PROCEDURE [dbo].[pcPaVerifyLogUpdate]
(
	@paMainID INT,
	@Mobile VARCHAR(11),
	@ip VARCHAR(31)
)
AS
BEGIN
	UPDATE paVerifyLog SET paMainID = @paMainID 
	WHERE id = ( 
				SELECT TOP 1 id FROM paVerifyLog WITH(NOLOCK) 
				WHERE  Mobile = @Mobile AND AddDate > DATEADD(HOUR,-1,GETDATE()) AND ip = @ip 
				ORDER BY id DESC 
				)
END


GO
/****** Object:  StoredProcedure [dbo].[pcPaYourFoodSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[pcPaYourFoodSelect] 
(
	@paMainId INT
)
AS
SET NOCOUNT ON
BEGIN
	SELECT a.Id, a.paMainID, a.cvMainId, a.JobId,b.camainid, b.Name JobName,
		c.Name cpName, d.Description Region,
		(SELECT Description FROM dcSalary WHERE Id = dcSalaryId) Salary,
		dbo.GetCvMatch(a.cvMainId, a.JobId) MatvhRate , 
			(
			SELECT COUNT(1) FROM ExJobApply  WITH(NOLOCK) 
			WHERE cvMainId IN(
				SELECT Id FROM cvMain WITH(NOLOCK) 
				WHERE paMainId = @paMainId) 
				AND JobId = a.JobId
			) HasApply,
		 a.AddDate, b.RefreshDate, b.SecondID EnJobID , c.SecondID EnCpMainID ,
		b.Welfare1,b.Welfare2,b.Welfare3,b.Welfare4,b.Welfare5,b.Welfare6,b.Welfare7,b.Welfare8,
		b.Welfare9,b.Welfare10,b.Welfare11,b.Welfare12,b.Welfare13,b.Welfare14,b.Welfare15,b.Welfare16,
		b.Welfare17,b.Welfare18,b.Welfare19,ISNULL((SELECT IsOnline FROM caOnline WHERE caMainId =b.caMainID), 0) AS IsOnline,
		c.HasLicence, c.ReplyRate
	FROM paYourFood a WITH(NOLOCK),
		Job b WITH(NOLOCK),
		cpMain c WITH(NOLOCK),
		dcRegion d WITH(NOLOCK)
	WHERE a.paMainId = @paMainId
	AND a.JobId = b.Id
	AND b.cpMainId = c.Id
	AND b.dcRegionId = d.ID
	ORDER BY a.AddDate DESC
END
GO
/****** Object:  StoredProcedure [dbo].[pcPerson_BlackEmailExist]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[pcPerson_BlackEmailExist]
(
	@Email VARCHAR(50)
)
AS
BEGIN
	IF EXISTS(SELECT 'X' FROM Person_Black WITH(NOLOCK) WHERE Email=@Email)
		RETURN 1
	ELSE
		RETURN 0
END





GO
/****** Object:  StoredProcedure [dbo].[pcRecruitmentCpMainByRmIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.4
--创建人：John
--说明：得到谁在关注我列表
--#####################################################
CREATE PROCEDURE [dbo].[pcRecruitmentCpMainByRmIDSelect]
(
	@RecruitmentID INT
)
AS
BEGIN
	SELECT d.RecruitmentName,a.AddDate,a.cpMainID,b.Name AS caName,b.Email,b.Mobile,b.Telephone,b.Gender,b.IsPhoneHide,b.IsNameHide,
		b.IsMobileHide,c.Name as cpName,c.Address,c.HasLicence,c.SecondId,c.IsAgent,c.Membertype
	FROM RecruitmentCpMain a WITH(NOLOCK) INNER JOIN caMain b WITH(NOLOCK) ON a.cpMainID = b.cpMainID 
		INNER JOIN cpMain c WITH(NOLOCK) ON c.ID = b.cpMainID JOIN Recruitment d on a.RecruitmentID = d.id 
	WHERE a.RecruitmentID = @RecruitmentID
END


GO
/****** Object:  StoredProcedure [dbo].[pcRecruitmentListByPhone]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[pcRecruitmentListByPhone]
(
	@dcProvinceID AS SMALLINT,
	@PageNum AS INT,
	@PageSize AS INT
)
AS
BEGIN
	DECLARE @COUNT INT
	SELECT @COUNT=COUNT(*)
		FROM Recruitment a,dcRegion b,RecruitmentPlace c,RecruitmentDept d 
		WHERE d.ID=a.RecruitmentDeptID AND d.ID<>1767 AND b.ID=c.dcRegionID AND a.RecruitmentPlaceId=c.id 
		AND LEFT(c.dcRegionID,2)=@dcProvinceID AND EndDate>GetDate() AND a.IsPause=0 AND Len(ManagerUserID)>0 

	IF @COUNT > 200
		SET @COUNT = 200

	SELECT *,@COUNT AS cnt FROM(
		SELECT TOP 200 ROW_NUMBER() OVER(ORDER BY OrderBy,a.EndDate DESC) AS Rows,a.ID,a.RecruitmentName,a.EndDate,a.BeginDate,c.PlaceName,c.Address,b.Description City 
		FROM Recruitment a,dcRegion b,RecruitmentPlace c,RecruitmentDept d 
		WHERE d.ID=a.RecruitmentDeptID AND d.ID<>1767 AND b.ID=c.dcRegionID AND a.RecruitmentPlaceId=c.id 
		AND LEFT(c.dcRegionID,2)=@dcProvinceID AND EndDate>GetDate() AND a.IsPause=0 AND Len(ManagerUserID)>0 
	) AS a 
	WHERE a.Rows BETWEEN (@PageNum-1)*@PageSize+1 AND @PageNum*@PageSize ORDER BY Rows
END














GO
/****** Object:  StoredProcedure [dbo].[pcResumeInformSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----------------
--个人会员中心首页，网站分类通知
-----------------
CREATE PROCEDURE [dbo].[pcResumeInformSelect]
(
   @ProvinceID INT
)
AS
BEGIN
	SELECT TOP 1 ID, Title,Content,link,Type
	FROM ResumeInform WITH(NOLOCK)
	WHERE Status=1 
	AND Province like '%' + LTRIM(str(@ProvinceID)) + '%'
	AND EndDate > GETDATE()
	ORDER BY ID DESC
END














GO
/****** Object:  StoredProcedure [dbo].[pcResumeXinxiPasswordUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.4
--创建人：John
--说明：重置resume_xinxi里的密碼
--#####################################################
CREATE PROCEDURE [dbo].[pcResumeXinxiPasswordUpdate]
(
	@username VARCHAR(50),
	@password VARCHAR(50),
	@email VARCHAR(50)
)
AS
BEGIN
	UPDATE resume_xinxi SET password = @password WHERE username = @username AND email = @email
END


GO
/****** Object:  StoredProcedure [dbo].[pcRmInvitationCodeByPaMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.31
--创建人：Nick
--说明：获取RmInvitationCode
--#####################################################
CREATE PROCEDURE [dbo].[pcRmInvitationCodeByPaMainIDSelect]
(
	@PamainID INT
)
AS
BEGIN TRY
	SELECT AddDate
	FROM marketdb..RmInvitationCode WITH(NOLOCK)
	WHERE pamainid=@PamainID 
	AND valid = 1 
	AND rmprojectid = 1 
	AND adddate > GETDATE()-90
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[pcViInterviewRecordReplyViewDateUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2014.10.30
--创建人：John
--说明：修改未查看面试记录的回复时间-个人
--#####################################################
CREATE PROCEDURE [dbo].[pcViInterviewRecordReplyViewDateUpdate]
(
	@paMainID INT
)
AS
BEGIN
	UPDATE a SET ReplyViewDate = GETDATE() 
	FROM viinterviewrecord a,viroom b,job c ,cpMain d,caMain e 
	WHERE c.camainid = e.id 
		AND a.viroomid = b.id 
		AND a.jobid = c.id 
		AND c.cpMainid = d.id 
		AND Applytype = 0 
		AND b.enddate IS NULL 
		AND a.ReplyDate IS NOT NULL
		AND a.ReplyViewDate IS NULL 
		AND cvMainID IN ( SELECT id FROM cvMain WHERE pamainid = @paMainID)
END


GO
/****** Object:  StoredProcedure [dbo].[pcViInterviewRecordViewDateUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2014.10.30
--创建人：John
--说明：修改未查看面试记录的查看时间-个人
--#####################################################
CREATE PROCEDURE [dbo].[pcViInterviewRecordViewDateUpdate]
(
	@paMainID INT
)
AS
BEGIN
	UPDATE a SET viewdate = GETDATE() 
	FROM viinterviewrecord a,viroom b,job c ,cpMain d,caMain e 
	WHERE c.camainid = e.id 
		AND a.viroomid = b.id 
		AND a.jobid = c.id 
		AND c.cpMainid = d.id 
		AND Applytype = 1 
		AND b.enddate IS NULL 
		AND a.viewdate IS NULL 
		AND cvMainID IN ( SELECT id FROM cvMain WHERE pamainid = @paMainID)
END


GO
/****** Object:  StoredProcedure [dbo].[pcViInterviewStatusSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.31
--创建人：John
--说明：个人面试状态 2正在排队或正在面试 3已经申请过 4已经申请过职位
--#####################################################
CREATE PROCEDURE [dbo].[pcViInterviewStatusSelect]
(
	@cvMainID INT,
	@jobID INT,
	@viRoomID INT
)
AS
BEGIN
	IF EXISTS (
				SELECT TOP 1 'x' 
				FROM ViInterviewRecord WITH(NOLOCK) 
				WHERE ((WaitBeginDate IS NOT NULL AND WaitEndDate IS NULL) 
					OR (BeginDate IS NOT NULL AND  EndDate IS NULL)) 
					AND cvMainid = @cvMainID
				)
	BEGIN
		RETURN 2
	END
	ELSE IF EXISTS (
					SELECT TOP 1 'x' 
					FROM ViInterviewRecord WITH(NOLOCK) 
					WHERE cvMainid = @cvMainID AND viRoomID = @viRoomID 
					)
	BEGIN
		RETURN 3
	END
	ELSE IF EXISTS (
					SELECT TOP 1 'x' 
					FROM exjobapply WITH(NOLOCK) 
					WHERE cvMainID = @cvMainID AND AddDate > GETDATE()-30 AND jobID = @jobID
					)
	BEGIN
		RETURN 4
	END
	ELSE
	BEGIN
		RETURN 0
	END
END


GO
/****** Object:  StoredProcedure [dbo].[pcViPlanInviteLogExpiredSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2014.10.30
--创建人：John
--说明：获取已过期的预约邀请记录
--#####################################################
CREATE PROCEDURE [dbo].[pcViPlanInviteLogExpiredSelect]
(
	@paMainID INT,
	@cvMainID INT,
	@addType INT,
	@companyName VARCHAR(100)
)
AS
BEGIN
	DECLARE @SQL VARCHAR(2000)
	SET @SQL = ' SELECT TOP 500 e.interviewdate,a.adddate,a.addtype,ISNULL(b.secondid,b.id) jobid,b.name jobName,ISNULL(c.secondid,c.ID) cpMainID,c.Name CompanyName,d.name cvName '
	SET @SQL = @SQL +' FROM viplaninvitelog a WITH(NOLOCK),job b ,cpmain c WITH(NOLOCK),cvmain d WITH(NOLOCK),viplan e WITH(NOLOCK) '
	SET @SQL = @SQL +' WHERE a.jobid = b.id AND b.cpmainid = c.id AND a.cvmainid = d.id AND a.viplanid = e.id AND e.interviewdate <= GETDATE() AND d.pamainid = ' + CONVERT(VARCHAR(20),@paMainID)
	IF(@cvMainID > 0)
	BEGIN
		SET @SQL = @SQL + ' AND a.cvMainID = ' + CONVERT(VARCHAR(20),@cvMainID)
	END
	IF(@addType <= 1)
	BEGIN
		SET @SQL = @SQL + ' AND a.AddType= ' + CONVERT(VARCHAR(20),@addType)
	END
	SET @SQL = @SQL +' AND c.Name LIKE ''' + @companyName + ''' ORDER BY interviewdate DESC'
	EXEC(@SQL)
END


GO
/****** Object:  StoredProcedure [dbo].[pcViPlanInviteLogSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2014.10.30
--创建人：John
--说明：获取未过期预约邀请记录
--#####################################################
CREATE PROCEDURE [dbo].[pcViPlanInviteLogSelect]
(
	@paMainID INT,
	@cvMainID INT,
	@addType INT,
	@companyName VARCHAR(100)
)
AS
BEGIN
	DECLARE @SQL VARCHAR(2000)
	SET @SQL = ' SELECT TOP 500 e.interviewdate,a.adddate,a.addtype,ISNULL(b.secondid,b.ID) jobid,b.name jobName,ISNULL(c.secondid,c.ID) cpMainID,c.Name CompanyName,d.name cvName '
	SET @SQL = @SQL +' FROM viplaninvitelog a WITH(NOLOCK),job b ,cpmain c WITH(NOLOCK),cvmain d WITH(NOLOCK),viplan e WITH(NOLOCK) '
	SET @SQL = @SQL +' WHERE a.jobid = b.id AND b.cpmainid = c.id AND a.cvmainid = d.id AND a.viplanid = e.id AND e.interviewdate > GETDATE() AND d.pamainid = ' + CONVERT(VARCHAR(20),@paMainID)
	IF(@cvMainID > 0)
	BEGIN
		SET @SQL = @SQL + ' AND a.cvMainID = ' + CONVERT(VARCHAR(20),@cvMainID)
	END
	IF(@addType <= 1)
	BEGIN
		SET @SQL = @SQL + ' AND a.AddType= ' + CONVERT(VARCHAR(20),@addType)
	END
	SET @SQL = @SQL +' AND c.Name LIKE ''' + @companyName + ''' ORDER BY interviewdate '
	EXEC(@SQL)
END


GO
/****** Object:  StoredProcedure [dbo].[pcViPlanInviteLogViewDateUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2014.10.30
--创建人：John
--说明：修改未查看面试计划邀请记录的查看时间-个人
--#####################################################
CREATE PROCEDURE [dbo].[pcViPlanInviteLogViewDateUpdate]
(
	@paMainID INT
)
AS
BEGIN
	UPDATE a SET viewdate = GETDATE() 
	FROM viplaninvitelog a,viplan b 
	WHERE a.viplanid = b.id 
	AND addtype = 1 
	AND viewdate IS NULL 
	AND cvMainID IN (SELECT id FROM cvMain WHERE pamainid = @paMainID)
END


GO
/****** Object:  StoredProcedure [dbo].[pcViRoomByJobIDCpMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2014.10.30
--创建人：John
--说明：获取企业当前的面试室
--#####################################################
CREATE PROCEDURE [dbo].[pcViRoomByJobIDCpMainIDSelect]
(
	@jobID INT,
	@cpMainID INT
)
AS
BEGIN
	DECLARE @SQL VARCHAR(1000)
	IF(@jobID > 0)
	BEGIN
		SET @SQL = ' SELECT TOP 1 * FROM viroom WHERE camainid = ( SELECT camainid FROM job WHERE id= ' + CONVERT(VARCHAR(20),@jobID) + ' ) AND enddate IS NULL AND LastRefreshTime > GETDATE()-0.1 ORDER BY id DESC '
	END
	ELSE
	BEGIN
		SET @SQL = ' SELECT TOP 1 * FROM viroom WHERE camainid = ( SELECT TOP 1 id FROM camain WHERE cpMainid = ' + CONVERT(VARCHAR(20),@cpMainID) + ' ) AND enddate IS NULL AND LastRefreshTime > GETDATE()-0.1 ORDER BY id DESC '
	END
	EXEC(@SQL)
END


GO
/****** Object:  StoredProcedure [dbo].[pcViWaitingHallByPaMainEnterInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
----Peter 2014-04-15 个人进入视频面试等待大厅
----Lambo 2014-05-26 修改表结构
CREATE PROCEDURE [dbo].[pcViWaitingHallByPaMainEnterInsert]
(
	@ViRoomID INT,
	@cvMainID INT
)
AS
BEGIN TRY
	DECLARE @ViWaitingHallID INT
	SELECT @ViWaitingHallID = ID  FROM ViWaitingHall WHERE cvMainID = @cvMainID AND viRoomID = @ViRoomID
	IF @ViWaitingHallID IS NOT NULL
		UPDATE ViWaitingHall SET BeginDate = GETDATE(),
			LastRefreshTime = GETDATE(),
			EndDate = NULL,
			Status = 1
		WHERE ID = @ViWaitingHallID
	ELSE
		INSERT INTO ViWaitingHall(viRoomID,cvMainID,LastRefreshTime,BeginDate,Status) 
		VALUES(@viRoomID,@cvMainID,GETDATE(),GETDATE(),1)

        DECLARE @BeginDate DATETIME
        ---下面的是新的  系统上线后 将上面的删除
	SELECT top 1 @ViWaitingHallID = ID,@BeginDate=WaitBeginDate  FROM viinterviewrecord WHERE cvMainID = @cvMainID AND viRoomID = @ViRoomID ORDER BY ID DESC
	IF @BeginDate IS NOT NULL
		UPDATE viinterviewrecord SET 
			WaitLastRefreshTime  = GETDATE(),
			Status = 1
		WHERE ID = @ViWaitingHallID
	ELSE
		UPDATE viinterviewrecord SET WaitBeginDate= GETDATE(),
			WaitLastRefreshTime  = GETDATE(),
			Status = 1
		WHERE ID = @ViWaitingHallID
END TRY
BEGIN CATCH
END CATCH










GO
/****** Object:  StoredProcedure [dbo].[pcViWaitingHallByPaMainRefreshUpDate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
----Peter 2014-04-15 个人刷新视频面试等待大厅
CREATE PROCEDURE [dbo].[pcViWaitingHallByPaMainRefreshUpDate]
(
    @ViRoomID INT,
	@cvMainID INT
)
AS
BEGIN TRY
	CREATE TABLE #T(
		WaitingNum INT,
		BeforeNum INT,
		WaitingStatus INT,--1.等待，2.自己退出，3.拒绝邀请,4.邀请成功，5.被邀请无响应，6.被踢出
		ViRoomStatus INT,--1.正常面试中，2.面试官离线
	) 
	INSERT INTO #T VALUES(0,0,0,0)
	
	UPDATE ViWaitingHall SET LastRefreshTime = GETDATE() 
	WHERE viRoomID = @viRoomID AND cvMainID = @cvMainID
	
	DECLARE @BeginDateTemp DateTime
	DECLARE @WaitingStatus INT
	SELECT @BeginDateTemp = BeginDate,@WaitingStatus = Status FROM viWaitingHall WHERE viRoomID = @viRoomID AND cvMainID = @cvMainID

	DECLARE @ViRoomStatus INT
	SELECT @ViRoomStatus = CASE EndDate WHEN NULL THEN 1 ELSE 2 END FROM ViRoom WHERE ID = @viRoomID

	UPDATE #T SET
	WaitingNum = 
		(SELECT COUNT(1) FROM viWaitingHall 
		WHERE viRoomID = @viRoomID AND Status = 1),
	BeforeNum =
		(SELECT COUNT(1) FROM viWaitingHall 
		WHERE viRoomID = @viRoomID AND Status = 1 AND BeginDate < @BeginDateTemp),
	WaitingStatus = @WaitingStatus,
	ViRoomStatus = @ViRoomStatus
		
	SELECT TOP 1 * FROM #T
	DROP TABLE #T
END TRY
BEGIN CATCH
END CATCH










GO
/****** Object:  StoredProcedure [dbo].[pcViWaitingHallByPaMainRefreshUpDateNew]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
----Peter 2014-04-15 个人刷新视频面试等待大厅
--Lambo 2014-5-26 修改表结构
CREATE PROCEDURE [dbo].[pcViWaitingHallByPaMainRefreshUpDateNew]
(
    @ViRoomID INT,
	@cvMainID INT
)
AS
BEGIN TRY
	CREATE TABLE #T(
		WaitingNum INT,
		BeforeNum INT,
		WaitingStatus INT,--1.等待，2.自己退出，3.拒绝邀请,4.邀请成功，5.被邀请无响应，6.被踢出
		ViRoomStatus INT,--1.正常面试中，2.面试官离线,
                InterViewStatus int,
                paNames NVARCHAR(100)
	) 
	INSERT INTO #T VALUES(0,0,0,0,0,'')
	
	UPDATE viinterviewrecord SET WaitLastRefreshTime  = GETDATE() 
	WHERE viRoomID = @viRoomID AND cvMainID = @cvMainID
	
	DECLARE @BeginDateTemp DateTime
	DECLARE @WaitingStatus INT
	SELECT TOP 1 @BeginDateTemp = WaitBeginDate,@WaitingStatus = Status FROM viinterviewrecord WHERE viRoomID = @viRoomID AND cvMainID = @cvMainID  order by id DESC

	DECLARE @ViRoomStatus INT
	SELECT @ViRoomStatus = CASE EndDate WHEN NULL THEN 1 ELSE 2 END FROM ViRoom WHERE ID = @viRoomID

	UPDATE #T SET
	WaitingNum = 
		(SELECT COUNT(1) FROM viinterviewrecord 
		WHERE viRoomID = @viRoomID AND Status = 1 and WaitEndDate is null ),
	BeforeNum =
		(SELECT COUNT(1) FROM viinterviewrecord 
		WHERE viRoomID = @viRoomID AND Status = 1 AND  WaitEndDate is null and WaitBeginDate< @BeginDateTemp),
paNames = STUFF((SELECT top 6 ','+c.name FROM viinterviewrecord a,cvMain b,paMain c where a.cvmainid=b.id and b.paMainid=c.id and viRoomID = @viRoomID  AND Status = 1  and WaitEndDate is null order by waitbegindate FOR XML PATH('')),1,1,''),
        InterViewStatus = (SELECT COUNT(1) FROM viinterviewrecord 
		WHERE viRoomID = @viRoomID AND begindate is not null and enddate is null),
	WaitingStatus = @WaitingStatus,
	ViRoomStatus = @ViRoomStatus
		
	SELECT TOP 1 * FROM #T
	DROP TABLE #T
END TRY
BEGIN CATCH
END CATCH









GO
/****** Object:  StoredProcedure [dbo].[pcViWaitingHallRejectInviteUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2014.10.30
--创建人：John
--说明：求职者拒绝邀请
--#####################################################
CREATE PROCEDURE [dbo].[pcViWaitingHallRejectInviteUpdate]
(
	@cvMainID INT
)
AS
BEGIN
	UPDATE ViWaitingHall SET Status = 3, [enddate] = GETDATE() 
	WHERE ID = 
		(
			SELECT TOP 1 ID 
			FROM ViWaitingHall 
			WHERE cvMainID = @cvMainID 
			ORDER BY id DESC
		)
END


GO
/****** Object:  StoredProcedure [dbo].[pcWXQrImageByIdSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--lambo 20140904   
--根据ID获取一条微信二维码记录  
CREATE PROCEDURE [dbo].[pcWXQrImageByIdSelect]   
(   
@ID INT  
)  
AS  
--INSERT INTO ProcLog SELECT 'pcWXQrImageByIdSelect', '', GETDATE()  
SET NOCOUNT ON
BEGIN    
	SELECT * FROM WXQrImage WITH(NOLOCK) WHERE ID=@ID  
END        

GO
/****** Object:  StoredProcedure [dbo].[pcWXQrImageInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--lambo 20140904
--lucifer 20160415 小于0的为企业用户绑定
--插入一条微信二维码生成记录
CREATE PROCEDURE [dbo].[pcWXQrImageInsert] 
(
	@PageType INT,
	@ip varchar(31)
)
AS
BEGIN 
	DECLARE @paMainID INT
	IF @PageType > 100 
	BEGIN
		SET @paMainID = @PageType
		SET @PageType = 3
	END
	ELSE IF @PageType < 0
	BEGIN
		SET @paMainID = @PageType
		SET @PageType = 52
	END
	INSERT INTO WXQrImage (Ticket, PageType, ip, paMainid)
	SELECT '', @PageType, @ip, @paMainID
	RETURN @@IDENTITY
END
GO
/****** Object:  StoredProcedure [dbo].[pcWXQrImageInsertNew]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--Lucifer 20160901
--插入一条微信二维码生成记录
CREATE PROCEDURE [dbo].[pcWXQrImageInsertNew] 
(
	@PageType INT,
	@Ip VARCHAR(31),
	@TypeID INT
)
AS
BEGIN
	INSERT INTO WXQrImage (Ticket, PageType, Ip, paMainID)
	SELECT '', @PageType, @Ip, @TypeID
	RETURN @@IDENTITY
END
GO
/****** Object:  StoredProcedure [dbo].[pcWxTokenUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--创建：Nick
--创建日期：2015-3-4
--获取token
--------------------------------------------------
CREATE PROCEDURE  [dbo].[pcWxTokenUpdate]
(
	@token VARCHAR(200),
	@provinceID INT
)
AS
BEGIN 
SET NOCOUNT ON
	UPDATE dcWxToken SET Token=@token,AddDate=GETDATE()
	WHERE dcProvinceId = @provinceID
SET NOCOUNT OFF	
END

GO
/****** Object:  StoredProcedure [dbo].[probsCvModifyByPamainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.31
--创建人：Nick
--说明：
--#####################################################
CREATE PROCEDURE [dbo].[probsCvModifyByPamainIDSelect]
(
	@PamainID INT
)
AS
BEGIN TRY
	SELECT a.ID,cvMainID,a.Location,a.VerifyInfo,b.Name 
	FROM bsCvModify a WITH(NOLOCK),cvMain b WITH(NOLOCK) 
	WHERE a.cvMainID=b.ID And b.paMainID=@PamainID 
	ORDER BY cvMainID, Location
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[probsCvVerifyByPamainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.31
--创建人：Nick
--说明：
--#####################################################
CREATE PROCEDURE [dbo].[probsCvVerifyByPamainIDSelect]
(
	@PamainID INT
)
AS
BEGIN TRY
	SELECT TOP 1 VerifyResult, VerifyInfo 
	FROM bsCvVerify WITH(NOLOCK) 
	WHERE cvMainID In(
		SELECT ID FROM cvMain WITH(NOLOCK) 
		WHERE paMainID=@PamainID) 
	ORDER BY ID DESC
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[proc51JobRegionToOurIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.31
--创建人：Nick
--说明：由地区名称获取地区ID 51
--#####################################################
CREATE PROCEDURE [dbo].[proc51JobRegionToOurIDSelect]
(
	@RegionName VARCHAR(20)
)
AS
BEGIN TRY
	SELECT dbo._51JobRegionToOurID(@RegionName) ID
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[procA_TempCheckInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[procA_TempCheckInsert] 
(
	@province_id SMALLINT,
    @VersionID SMALLINT,
    @referer VARCHAR(190),
    @ip VARCHAR(15),
    @Url VARCHAR(max)
)  
AS
RETURN
GO
/****** Object:  StoredProcedure [dbo].[ProcActivationLogInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--创建：Max 2013-8-26
--说明：对推广邮件多长时间会登录、注册进行统计
---------------------------------------------------
CREATE PROCEDURE [dbo].[ProcActivationLogInsert]
AS
BEGIN TRAN
	IF EXISTS(
		SELECT TOP 1 'x' 
		FROM LogDB..CpActivationLog 
		WHERE Countdate = CONVERT(VARCHAR(8),getdate()-1, 112)
	)
		GOTO ERR
	DECLARE @MaxID AS INT
	DECLARE @MaxID2 AS INT
	DECLARE @Day1 AS INT
	DECLARE @Day2 AS INT
	DECLARE @Day3 AS INT
	DECLARE @Day7 AS INT
	DECLARE @Day15 AS INT
	DECLARE @Day30 AS INT
	DECLARE @DayOther AS INT
	BEGIN TRY
		SET @MaxID=0
    -------------------------------个人统计------------------------------------
		---取前天正常注册的最大ID		
		SELECT @MaxID = MAX(ID) 
		FROM Pamain		
		WHERE Adddate > (CONVERT(VARCHAR(100), GETDATE()-2, 23) + ' 00:00:00') 
		AND Adddate < (CONVERT(VARCHAR(100), GETDATE()-1, 23) + ' 00:00:00') 
		AND RegisterMode NOT IN (1,11) AND RegisterType NOT IN (101,102)

		---取昨天正常注册的最大ID
		SELECT @MaxID2 = MAX(ID) 
		FROM Pamain		
		WHERE Adddate > (CONVERT(VARCHAR(100), GETDATE()-1, 23) + ' 00:00:00') 
		AND Adddate < (CONVERT(VARCHAR(100), GETDATE(), 23) + ' 00:00:00') 
		AND RegisterMode NOT IN (1,11) AND RegisterType NOT IN (101,102)	

		--PRINT @MaxID
		--PRINT @MaxID2

		DECLARE @TempTable TABLE(ID INT IDENTITY(1,1), CountDate INT,AllCount INT)   
		INSERT @TempTable  
		SELECT CONVERT(VARCHAR(8),adddate, 112) CountDate,COUNT(*) AllCount
		FROM pamain WHERE id > @MaxID  AND id < @MaxID2 
		AND (registermode IN(1, 11) OR RegisterType IN (101,102))
		GROUP BY CONVERT(VARCHAR(8),adddate, 112)

		SELECT * FROM @TempTable ORDER BY countDate DESC
		--取 day1
		SELECT @Day1 = SUM(AllCount) 
		FROM @TempTable
		WHERE CountDate > CONVERT(VARCHAR(8),getdate()-2, 112)
		--PRINT @Day1
		--取 day2 
		SELECT @Day2 = SUM(AllCount) 
		FROM @TempTable
		WHERE CountDate > CONVERT(VARCHAR(8),getdate()-3, 112)
		--PRINT @Day2
		--取 day3
		SELECT @Day3 = SUM(AllCount) 
		FROM @TempTable
		WHERE CountDate > CONVERT(VARCHAR(8),getdate()-4, 112)

		--PRINT @Day3
		--取 day7  
		SELECT @Day7 = SUM(AllCount) 
		FROM @TempTable
		WHERE CountDate > CONVERT(VARCHAR(8),getdate()-8, 112)
		--PRINT @Day7
		--取 day15  
		SELECT @Day15 = SUM(AllCount) 
		FROM @TempTable
		WHERE CountDate > CONVERT(VARCHAR(8),getdate()-16, 112)
		--PRINT @Day15
		--取 day30 
		SELECT @Day30 = SUM(AllCount) 
		FROM @TempTable
		WHERE CountDate > CONVERT(VARCHAR(8),getdate()-31, 112)
		--PRINT @Day30
		--取 dayOther
		SELECT @DayOther = SUM(AllCount) 
		FROM @TempTable
		WHERE CountDate <= CONVERT(VARCHAR(8),getdate()-31, 112)
		--PRINT @DayOther
		--插入日志表
		INSERT INTO LogDB..CvActivationLog(countdate,day1,day2,day3,day7,day15,day30,dayOther)
		VALUES(CONVERT(VARCHAR(8),getdate()-1, 112),@Day1,@Day2-@Day1,@Day3-@Day2,@Day7-@Day3,@Day15-@Day7,@Day30-@Day15,@DayOther)
		
		-------------------------------企业统计------------------------------------
		---取前天正常注册的最大ID
		SELECT @MaxID = MAX(ID) 
		FROM CpMain		
		WHERE Regdate > (CONVERT(VARCHAR(10), GETDATE()-2, 23) + ' 00:00:00') 
		AND Regdate < (CONVERT(VARCHAR(10), GETDATE()-1, 23) + ' 00:00:00') 
		AND RegisterMode NOT IN (1,11)

		---取昨天正常注册的最大ID
		SELECT @MaxID2 = MAX(ID) 
		FROM CpMain		
		WHERE Regdate > (CONVERT(VARCHAR(10), GETDATE()-1, 23) + ' 00:00:00') 
		AND Regdate < (CONVERT(VARCHAR(10), GETDATE(), 23) + ' 00:00:00') 
		AND RegisterMode NOT IN (1,11)
			
		--PRINT @MaxID
		--PRINT @MaxID2

		DELETE FROM @TempTable 
		INSERT @TempTable  
		SELECT CONVERT(VARCHAR(8),Regdate, 112) CountDate,COUNT(*) AllCount
		FROM CpMain WHERE id > @MaxID  AND id < @MaxID2 
		AND Registermode IN(1, 11)
		GROUP BY CONVERT(VARCHAR(8),Regdate, 112)

		SELECT * FROM @TempTable ORDER BY CountDate DESC
		--取day1
		SELECT @Day1 = SUM(AllCount) 
		FROM @TempTable
		WHERE CountDate > CONVERT(VARCHAR(8),getdate()-2, 112)
		--PRINT @Day1
		--取 day2 
		SELECT @Day2 = SUM(AllCount) 
		FROM @TempTable
		WHERE CountDate > CONVERT(VARCHAR(8),getdate()-3, 112)
		--PRINT @Day2
		--取 day3
		SELECT @Day3 = SUM(AllCount) 
		FROM @TempTable
		WHERE CountDate > CONVERT(VARCHAR(8),getdate()-4, 112)
		--PRINT @Day3
		--取 day7  
		SELECT @Day7 = SUM(AllCount) 
		FROM @TempTable
		WHERE CountDate > CONVERT(VARCHAR(8),getdate()-8, 112)
		--PRINT @Day7
		--取 day15  
		SELECT @Day15 = SUM(AllCount) 
		FROM @TempTable
		WHERE CountDate > CONVERT(VARCHAR(8),getdate()-16, 112)
		--PRINT @Day15
		--取 day30 
		SELECT @Day30 = SUM(AllCount) 
		FROM @TempTable
		WHERE CountDate > CONVERT(VARCHAR(8),getdate()-31, 112)
		--PRINT @Day30
		--取 dayOther
		SELECT @DayOther = SUM(AllCount) 
		FROM @TempTable
		WHERE CountDate <= CONVERT(VARCHAR(8),getdate()-31, 112)
		--PRINT @DayOther
		--插入日志表
		INSERT INTO LogDB..CpActivationLog(countdate,day1,day2,day3,day7,day15,day30,dayOther)
		VALUES(CONVERT(VARCHAR(8),getdate()-1, 112),@Day1,@Day2-@Day1,@Day3-@Day2,@Day7-@Day3,@Day15-@Day7,@Day30-@Day15,@DayOther)
		
		--统计推广员推广登录量
		INSERT INTO Logdb..ActivationLog(AddMan,CountDate,CvCount,cpCount)		
		SELECT a.Addman,a.CountDate,a.cvCount,b.cpCount 
		FROM (
			SELECT Addmannew Addman,CONVERT(VARCHAR(8),Regdatenew, 112) CountDate,count(*) cvCount
			FROM logdb..ActivationCvDetail 
			WHERE Regdatenew > (CONVERT(VARCHAR(100), GETDATE()-1, 23) + ' 00:00:00') 
			AND Regdatenew < (CONVERT(VARCHAR(100), GETDATE(), 23) + ' 00:00:00') 
			GROUP BY Addmannew,CONVERT(VARCHAR(8),Regdatenew, 112)
		) a 
		JOIN (
			SELECT Addmannew Addman,CONVERT(VARCHAR(8),Regdatenew, 112) CountDate,count(*) cpCount
			FROM logdb..ActivationCpDetail 
			WHERE Regdatenew > (CONVERT(VARCHAR(100), GETDATE()-1, 23) + ' 00:00:00') 
			AND Regdatenew < (CONVERT(VARCHAR(100), GETDATE(), 23) + ' 00:00:00') 
			GROUP BY Addmannew,CONVERT(VARCHAR(8),Regdatenew, 112)
		) b ON a.Addman = b.Addman AND a.CountDate=b.CountDate
	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH
COMMIT TRAN
RETURN 1
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END


GO
/****** Object:  StoredProcedure [dbo].[procAdverProjectAutoSort]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--Carl 2018-04-23
--前台广告自动排序
CREATE PROCEDURE [dbo].[procAdverProjectAutoSort]
(
	@Method INT, --0上线(新增，valid) 1手动暂停 2自动暂停,预备只替换下线的那一个
	@ProvinceId INT, 
	@Type INT --限制  type<>10 不执行
)
AS
SET NOCOUNT OFF
BEGIN

	IF @ProvinceId=0
	BEGIN
		--PRINT '51人才编辑自己操作'
		RETURN 
	END
	
	--IF @ProvinceId<>64 AND @ProvinceId<>83 
	--BEGIN
		----PRINT '不是西藏、新疆的不执行'
		--RETURN 
	--END

	IF @Type<>10
	BEGIN
		--PRINT '非首页横排广告不执行'
		RETURN 
	END

	DECLARE @Id INT
	DECLARE @Width INT
	DECLARE @LineNum3 INT
	DECLARE @TotalWidth INT
	DECLARE @IsSelf INT
	DECLARE @RemainWidth INT

	SET @LineNum3=0
	SET @TotalWidth=0

	--上下线时的操作，下线所有的自己的
	UPDATE AdverProject SET Valid=0 WHERE ID IN (SELECT Id FROM AdverProject WHERE Province_ID = @ProvinceId 
			AND [Type] = 10
			AND BeginTime <= CONVERT(SMALLDATETIME, GETDATE())
			AND EndTime > CONVERT(SMALLDATETIME, GETDATE())
			AND Valid = 1 AND IsSelf=1)

	--查询目前该省份展示的广告,遍历获取 总行数
	DECLARE CurrentInfo CURSOR FOR 
		SELECT Id,Width FROM AdverProject WHERE Province_ID = @ProvinceId
			AND [Type] = 10
			AND BeginTime <= CONVERT(SMALLDATETIME, GETDATE())
			AND EndTime > CONVERT(SMALLDATETIME, GETDATE())
			AND Valid = 1 

	OPEN CurrentInfo
	FETCH NEXT FROM CurrentInfo INTO @Id,@Width 
	WHILE @@fetch_status<>-1
	BEGIN
		IF @Width=948 OR @Width=986 OR @Width=1100 OR @Width=1098
		BEGIN
			SET @Width=6
		END
		ELSE IF @Width=471 OR @Width=488 OR @Width=545 OR @Width=546
		BEGIN
			SET @Width=3
			SET @LineNum3=@LineNum3+1	
		END
		ELSE IF @Width=312 OR @Width=322 OR @Width=360 OR @Width=362
		BEGIN
			SET @Width=2
		END
		ELSE IF @Width=153 OR @Width=156 OR @Width=175 OR @Width=178
		BEGIN
			SET @Width=1
		END
		SET @TotalWidth=@TotalWidth+@Width 
		FETCH NEXT FROM CurrentInfo INTO @Id,@Width 
	END
	CLOSE CurrentInfo
	DEALLOCATE CurrentInfo

	--PRINT '之前总宽度'
	--PRINT @TotalWidth

	IF @LineNum3%2<>0
	BEGIN 
		--PRINT '3/6不为整行'
		
		--PRINT '自动下线、手动下线或上线的补自己的'
		UPDATE AdverProject SET Valid=1,BeginTime=GETDATE()-1,EndTime=DATEADD(YEAR,5,GETDATE()) 
				WHERE ID IN (SELECT TOP 1 ID FROM AdverProject 
					WHERE Province_ID = @ProvinceId AND [Type] = 10 
						AND IsSelf=1 AND Valid=0 AND Width IN (471,488, 545, 546))

		SET @TotalWidth=@TotalWidth+3
		SET @LineNum3=@LineNum3+1
	END

	--PRINT '现在总宽度'
	--PRINT @TotalWidth

	SET @RemainWidth=6-(@TotalWidth%6)
	--PRINT '遗留空位'
	--PRINT @RemainWidth
	
	--如果遗留空位 为 1 2 3 4 5 
	IF @RemainWidth>0 AND @RemainWidth<>6
	BEGIN
		--此时3/6的肯定是整行的了
		--PRINT '遗留空位'
		--PRINT @RemainWidth

		--遍历 自己网站中的数据
		DECLARE MySelfInfo CURSOR FOR 
			SELECT Id,Width FROM AdverProject WHERE Province_ID = @ProvinceId 
			AND [Type] = 10 AND IsSelf=1 AND Valid=0 
				AND Width IN (312,322,360,362,153,156,175,178) ORDER BY Width DESC

		OPEN MySelfInfo
		FETCH NEXT FROM MySelfInfo INTO @Id,@Width 
		WHILE @@fetch_status<>-1 AND @RemainWidth>0
		BEGIN
			IF @Width=312 OR @Width=322 OR @Width=360 OR @Width=362
			BEGIN
				SET @Width=2
			END
			ELSE IF @Width=153 OR @Width=156 OR @Width=175 OR @Width=178
			BEGIN
				SET @Width=1
			END
			IF (@RemainWidth-@Width)>=0
			BEGIN
				UPDATE AdverProject SET Valid=1,BeginTime=GETDATE()-1,
					EndTime=DATEADD(YEAR,5,GETDATE()) WHERE ID=@Id
				SET @RemainWidth=@RemainWidth-@Width
			END
			FETCH NEXT FROM MySelfInfo INTO @Id,@Width 
		END
		CLOSE MySelfInfo
		DEALLOCATE MySelfInfo 
	END

	--重新排序
	UPDATE AdverProject SET AdverProject.OrderBy=b.RowNum 
		FROM (SELECT id,ROW_NUMBER() OVER(ORDER BY Width DESC,EndTime) RowNum FROM AdverProject 
			WHERE Province_ID = @ProvinceId AND [Type] = 10
				AND BeginTime <= CONVERT(SMALLDATETIME, GETDATE())
				AND EndTime > CONVERT(SMALLDATETIME, GETDATE())
				AND Valid = 1 ) b WHERE AdverProject.id=b.id


END
SET NOCOUNT ON


GO
/****** Object:  StoredProcedure [dbo].[procAdverProjectByCampusSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015-10-19
--创建人：Lucifer
--说明：根据provincieid得到校园招聘首页图片
--#####################################################
CREATE PROCEDURE [dbo].[procAdverProjectByCampusSelect]
(
	@ProvinceID INT,
	@Type INT
)
AS
BEGIN
	SELECT a.ID, a.ImageFile, a.Url, a.Width, a.Height, a.Remarks, b.SecondID CompanyId
	FROM adverproject a WITH(NOLOCK) LEFT JOIN cpMain b WITH(NOLOCK) ON a.CompanyId = b.ID
	WHERE a.Type=@Type
	AND a.begintime<=CAST(GETDATE() AS SMALLDATETIME)
	AND a.endtime>=CAST(GETDATE() AS SMALLDATETIME)
	AND a.valid=1
	AND a.province_id = @ProvinceID
	ORDER BY a.Orderby
END
GO
/****** Object:  StoredProcedure [dbo].[procAdverprojectByClickCountUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[procAdverprojectByClickCountUpdate]
(
	@Id INT,
	@CompanyID INT
)
AS
BEGIN
	UPDATE Adverproject SET ClickCount = ClickCount + 1
	WHERE ID = @ID
	AND CompanyID = @CompanyID
END














GO
/****** Object:  StoredProcedure [dbo].[ProcAdverProjectByHomepageFloatSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ProcAdverProjectByHomepageFloatSelect]
(
	@ProvinceID INT
)
AS
BEGIN
	SELECT * FROM AdverProject 
	WHERE Type IN (13, 14, 15)
	AND BeginTime < GETDATE()
	AND EndTime > GETDATE()
	AND Province_ID = @ProvinceId
	AND Valid = 1
END














GO
/****** Object:  StoredProcedure [dbo].[procAdverProjectByOfflineUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--Carl 2018-04-26
--Carl 2018-05-25
--定时任务存储过程 51编辑自己修改
CREATE PROCEDURE [dbo].[procAdverProjectByOfflineUpdate]
(
	@Method INT --1、过期下线 2、自动暂停
)
AS
SET NOCOUNT ON
BEGIN
	DECLARE @Id INT 
	DECLARE @Width INT 
	DECLARE @ProvinceId INT 
	DECLARE @LineNumNew6 INT --下线6/6的个数
	DECLARE @LineNumNew3 INT --下线3/6的个数
	DECLARE @RemainNum6 INT --剩余6/6的个数
	DECLARE @TotalWidth INT --现有总宽度
	DECLARE @WidthNew INT 
	DECLARE @IdNew INT 
	DECLARE @BeforeProvinceId INT 
	DECLARE @RemainCount INT --剩余空位数量 
	DECLARE @MaxLineNum INT --最大行数 
	DECLARE @MaxLineNumNew6 INT --6/6最大个数
	DECLARE @MaxLineNumNew3 INT --3/6最大个数
	DECLARE @ReadyWidth INT --预备宽度
	DECLARE @ReadyId INT --预备Id

	DECLARE @CompanyId INT --企业id
	DECLARE @AddMan INT --添加人

	DECLARE @SendList VARCHAR(100)  --信息接收人员
	DECLARE @Consultant INT --企业当前顾问

	SET @SendList='153,158,212' 

	SET @BeforeProvinceId=0
	SET @LineNumNew6=0
	SET @LineNumNew3=0
	SET @RemainNum6=0
	SET @TotalWidth=0

	SET @MaxLineNum=14
	SET @MaxLineNumNew6=3
	SET @MaxLineNumNew3=8

	--定义游标
	DECLARE @DownLineInfo CURSOR

	--查询目前西藏省份过期的广告,遍历获取 总行数
	IF @Method=1
	BEGIN
		--PRINT '过期下线'
		SET @DownLineInfo=CURSOR FOR 
		SELECT Id,Width,Province_Id,CompanyId,AddMan FROM AdverProject WHERE Province_ID<>0 AND [Type] = 10 
				--AND EndTime = '2018-04-12 23:59:00' 
			AND EndTime = CONVERT(VARCHAR(100), GETDATE()-1, 23)+' 23:59:00' 
			--AND EndTime = CONVERT(SMALLDATETIME, GETDATE()) 
			AND Valid = 1 ORDER BY Province_Id 
	END
	ELSE IF @Method=2 
	BEGIN

		SET @DownLineInfo = CURSOR FOR 
		SELECT Id,Width,Province_Id,CompanyId,AddMan FROM AdverProject WHERE 
						Province_ID<>0 AND [Type] = 10 AND BeginTime <= CONVERT(SMALLDATETIME, GETDATE())
						AND EndTime > CONVERT(SMALLDATETIME, GETDATE())
						AND Valid = 1 AND ISNULL(IsSelf,0)<>1  
						AND CompanyId IS NOT NULL 
						AND NOT EXISTS(SELECT 'X' FROM Job WITH(NOLOCK) WHERE cpMainID =AdverProject.CompanyId 
						AND IsDelete = 0 AND IssueEnd> GETDATE() AND IssueDate < GETDATE()) 
						AND NOT EXISTS(SELECT 'X' FROM CaOrder WITH(NOLOCK) WHERE Id=AdverProject.CaOrderID AND Paid>0) 
						ORDER BY Province_Id 
	END
	--PRINT '打开游标'
	OPEN @DownLineInfo
	FETCH NEXT FROM @DownLineInfo INTO @Id,@Width,@ProvinceId,@CompanyId,@AddMan 
	WHILE @@fetch_status<>-1
	BEGIN
		
		UPDATE AdverProject SET Valid=0 WHERE ID =@Id

		IF @BeforeProvinceId=0
			SET @BeforeProvinceId=@ProvinceId

		IF @BeforeProvinceId<>@ProvinceId
		BEGIN
			--存储过程还需要再执行下(预备里无广告或6/6 3/6无法到前台的情况)
			--PRINT '存储过程1'
			EXEC procAdverProjectAutoSort 2,@BeforeProvinceId,10
			SET @BeforeProvinceId=@ProvinceId 

			SET @LineNumNew6=0
			SET @LineNumNew3=0
			SET @TotalWidth=0
		END

		--获取总宽度
		IF @TotalWidth=0
		BEGIN
			--查询目前该省份展示的广告,遍历获取 总行数
			DECLARE TotalInfo CURSOR FOR 
				SELECT Width FROM AdverProject WHERE Province_ID = @ProvinceId
					AND [Type] = 10
					AND BeginTime <= CONVERT(SMALLDATETIME, GETDATE())
					AND EndTime > CONVERT(SMALLDATETIME, GETDATE())
					AND Valid = 1 

			OPEN TotalInfo
			FETCH NEXT FROM TotalInfo INTO @WidthNew 
			WHILE @@fetch_status<>-1
			BEGIN
				IF @WidthNew=948 OR @WidthNew=986 OR @WidthNew=1100 OR @WidthNew=1098
				BEGIN
					SET @WidthNew=6 
					SET @LineNumNew6=@LineNumNew6+1
				END
				ELSE IF @WidthNew=471 OR @WidthNew=488 OR @WidthNew=545 OR @WidthNew=546
				BEGIN
					SET @WidthNew=3 
					SET @LineNumNew3=@LineNumNew3+1
				END
				ELSE IF @WidthNew=312 OR @WidthNew=322 OR @WidthNew=360 OR @WidthNew=362
				BEGIN
					SET @WidthNew=2
				END
				ELSE IF @WidthNew=153 OR @WidthNew=156 OR @WidthNew=175 OR @WidthNew=178
				BEGIN
					SET @WidthNew=1
				END
				SET @TotalWidth=@TotalWidth+@WidthNew 
				FETCH NEXT FROM TotalInfo INTO @WidthNew 
			END
			CLOSE TotalInfo
			DEALLOCATE TotalInfo
		END

		IF @Method=2
		BEGIN
			--检查企业广告是否 三天后全部过期
			IF (SELECT CONVERT(VARCHAR,MAX(IssueEnd),23) FROM Job WITH(NOLOCK) WHERE cpMainID =@CompanyId AND IsDelete = 0 
			AND IssueEnd> GETDATE() AND IssueDate < GETDATE())<=CONVERT(VARCHAR,GETDATE()+3,23)
			BEGIN
				--PRINT '发送rtx提醒'
				--获取企业当前顾问
				SELECT @Consultant=ISNULL(ConsultantID,0) FROM cpMain WHERE ID=@CompanyId			

				INSERT oadb..RtxSend (Receiver, RtxTitle, RtxMessage, SendType, DelayTime, SendTime, AddTime) 
							VALUES (CONVERT(VARCHAR,@Consultant), 
						'广告通知', '公司id：'+CONVERT(VARCHAR,@CompanyId)+',该企业职位三天内即将全部过期,请联系用户及时发布', 
						1, 0, null, getdate())
			END
		END

		IF @TotalWidth/6>=@MaxLineNum
		BEGIN
			--如果总行数大于14 补自己的 继续下次循环
			FETCH NEXT FROM @DownLineInfo INTO @Id,@Width,@ProvinceId,@CompanyId,@AddMan 
			CONTINUE 
		END
		ELSE
		BEGIN
			--未到达最大行数
			--PRINT '总行数未到达最大行数'
			--获取遗留空位数，从预备中取，然后执行存储过程自动排序 
			SET @RemainCount=(6*@MaxLineNum)-@TotalWidth 
			--遍历预备中的广告，6/6 3/6需要单独判断下
			--遍历该省份预备中的数据
			DECLARE ReadyInfo CURSOR FOR 
				SELECT Id,Width FROM AdverProject WHERE Province_ID = @BeforeProvinceId 
				AND [Type] = 10 AND BeginTime>GETDATE() and Valid=1 ORDER BY OrderBy

			OPEN ReadyInfo
			FETCH NEXT FROM ReadyInfo INTO @ReadyId,@ReadyWidth 
			WHILE @@fetch_status<>-1 AND @RemainCount>0
			BEGIN
				IF @ReadyWidth=948 OR @ReadyWidth=986 OR @ReadyWidth=1100 OR @ReadyWidth=1098
				BEGIN
					SET @ReadyWidth=6
				END
				ELSE IF @ReadyWidth=471 OR @ReadyWidth=488 OR @ReadyWidth=545 OR @ReadyWidth=546
				BEGIN
					SET @ReadyWidth=3
				END
				ELSE IF @ReadyWidth=312 OR @ReadyWidth=322 OR @ReadyWidth=360 OR @ReadyWidth=362
				BEGIN
					SET @ReadyWidth=2
				END
				ELSE IF @ReadyWidth=153 OR @ReadyWidth=156 OR @ReadyWidth=175 OR @ReadyWidth=178
				BEGIN
					SET @ReadyWidth=1
				END
				
				IF @ReadyWidth=6
				BEGIN
					--查看6/6 是否到达总行数，若达到，预备进行下次循环
					IF @LineNumNew6>=@MaxLineNumNew6
					BEGIN
						--PRINT '6/6到达最大行数'
						FETCH NEXT FROM ReadyInfo INTO @ReadyId,@ReadyWidth 
						CONTINUE
					END
					ELSE
					BEGIN
						IF @RemainCount>=6
						BEGIN
							SET @LineNumNew6=@LineNumNew6+1
						END
						
					END
				END
				IF @ReadyWidth=3
				BEGIN
					IF @LineNumNew3>=@MaxLineNumNew3
					BEGIN
						--PRINT '3/6到达最大行数'
						FETCH NEXT FROM ReadyInfo INTO @ReadyId,@ReadyWidth 
						CONTINUE
					END
					ELSE
					BEGIN
						IF @RemainCount>=3
						BEGIN
							SET @LineNumNew3=@LineNumNew3+1
						END
					END
				END

				IF (@RemainCount-@ReadyWidth)>=0
				BEGIN
					UPDATE AdverProject SET BeginTime=CONVERT(SMALLDATETIME,GETDATE()),
						EndTime=CONVERT(VARCHAR,DATEADD(DAY,DATEDIFF(DD,BeginTime,EndTime),GETDATE()),23)+' 23:59:00' WHERE ID=@ReadyId

					SET @RemainCount=@RemainCount-@ReadyWidth 
					SET @TotalWidth=@TotalWidth+@ReadyWidth
				END
				FETCH NEXT FROM ReadyInfo INTO @ReadyId,@ReadyWidth 
			END
			CLOSE ReadyInfo
			DEALLOCATE ReadyInfo 			
		END
		FETCH NEXT FROM @DownLineInfo INTO @Id,@Width,@ProvinceId,@CompanyId,@AddMan 
	END

	--PRINT '存储过程2'
	--PRINT @BeforeProvinceId
	EXEC procAdverProjectAutoSort 2,@BeforeProvinceId,10
	--PRINT @BeforeProvinceId 
	CLOSE @DownLineInfo
	DEALLOCATE @DownLineInfo

	IF @Method=2
	BEGIN
		--PRINT '自动暂停执行完,查下前台广告是否有小于三行的'
		
		DECLARE @SubsiteName VARCHAR(1000)

		SET @BeforeProvinceId=0
		SET @TotalWidth=0
		SET @SubsiteName=''

		DECLARE TotalProvince CURSOR FOR 
			SELECT Province_Id FROM AdverProject WHERE Province_Id<>0 AND [Type] = 10 
				AND BeginTime <= CONVERT(SMALLDATETIME, GETDATE()) 
				AND EndTime > CONVERT(SMALLDATETIME, GETDATE()) AND Valid = 1 GROUP BY Province_Id

		OPEN TotalProvince
		FETCH NEXT FROM TotalProvince INTO @ProvinceId 
		WHILE @@fetch_status<>-1
		BEGIN
			
			IF @BeforeProvinceId=0
				SET @BeforeProvinceId=@ProvinceId

			IF @BeforeProvinceId<>@ProvinceId
			BEGIN 
				IF @TotalWidth/6<3
				BEGIN 
					--根据省份id 获取 网站名称
					SELECT @SubsiteName=SubSiteName FROM dcsubsite WHERE ProvinceID=@BeforeProvinceId
					--PRINT '发送rtx提醒'
					IF @SubsiteName<>''
					BEGIN
						INSERT INTO oadb..RtxSend (Receiver, RtxTitle, RtxMessage, SendType, DelayTime, SendTime, AddTime) 
							VALUES (@SendList, 
							'广告通知', @SubsiteName+',前台广告少于三行', 
							1, 0, null, getdate())
					END
				END				
				SET @BeforeProvinceId=@ProvinceId 
				SET @TotalWidth=0 
			END

			--获取总宽度
			IF @TotalWidth=0
			BEGIN
				--查询目前该省份展示的广告,遍历获取 总行数
				DECLARE TotalInfo CURSOR FOR 
					SELECT Width FROM AdverProject WHERE Province_ID = @ProvinceId
						AND [Type] = 10
						AND BeginTime <= CONVERT(SMALLDATETIME, GETDATE())
						AND EndTime > CONVERT(SMALLDATETIME, GETDATE())
						AND Valid = 1 

				OPEN TotalInfo
				FETCH NEXT FROM TotalInfo INTO @WidthNew 
				WHILE @@fetch_status<>-1
				BEGIN
					IF @WidthNew=948 OR @WidthNew=986 OR @WidthNew=1100 OR @WidthNew=1098
					BEGIN
						SET @WidthNew=6 
					END
					ELSE IF @WidthNew=471 OR @WidthNew=488 OR @WidthNew=545 OR @WidthNew=546
					BEGIN
						SET @WidthNew=3 
					END
					ELSE IF @WidthNew=312 OR @WidthNew=322 OR @WidthNew=360 OR @WidthNew=362
					BEGIN
						SET @WidthNew=2
					END
					ELSE IF @WidthNew=153 OR @WidthNew=156 OR @WidthNew=175 OR @WidthNew=178
					BEGIN
						SET @WidthNew=1
					END
					SET @TotalWidth=@TotalWidth+@WidthNew 
					FETCH NEXT FROM TotalInfo INTO @WidthNew 
				END
				CLOSE TotalInfo
				DEALLOCATE TotalInfo
			END

			FETCH NEXT FROM TotalProvince INTO @ProvinceId 
		END
		CLOSE TotalProvince
		DEALLOCATE TotalProvince
		
		IF @TotalWidth/6<3
		BEGIN 
			--根据省份id 获取 网站名称
			SELECT @SubsiteName=SubSiteName FROM dcsubsite WHERE ProvinceID=@BeforeProvinceId
			--PRINT '发送rtx提醒'
			IF @SubsiteName<>''
			BEGIN
				INSERT INTO oadb..RtxSend (Receiver, RtxTitle, RtxMessage, SendType, DelayTime, SendTime, AddTime) 
					VALUES (@SendList, 
					'广告通知', @SubsiteName+',前台广告少于三行', 
					1, 0, null, getdate())
			END
		END
	END
END
GO
/****** Object:  StoredProcedure [dbo].[procAdverProjectByProvince_IDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.3
--创建人：NICK
--说明：根据provincieid得到adverproject
--#####################################################
CREATE PROCEDURE [dbo].[procAdverProjectByProvince_IDSelect]
(
	@ProvinceID INT,
	@Type INT
)
AS
BEGIN
	SELECT top 1 id,imagefile,width,url,companyid,remarks 
	FROM adverproject WITH(NOLOCK) WHERE TYPE=@Type
	AND begintime<=CAST(GETDATE() AS SMALLDATETIME)
	AND endtime>=CAST(GETDATE() AS SMALLDATETIME)
	AND valid=1
	AND province_id = @ProvinceID
	ORDER BY id DESC
END


GO
/****** Object:  StoredProcedure [dbo].[procAdverProjectByProvinceID16Select]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.03
--创建人：Nick
--说明：取新职业指导切换图片的数据
--#####################################################
CREATE PROCEDURE [dbo].[procAdverProjectByProvinceID16Select]
(
	@ProvinceID INT
)
AS
BEGIN TRY
	SELECT id, imagefile, remarks, url, companyid
	FROM adverproject WITH(NOLOCK)
	WHERE type = 16
	AND begintime <= CAST(GETDATE() AS SMALLDATETIME)
	AND endtime >= CAST(GETDATE() AS SMALLDATETIME)
	AND valid = 1
	AND province_id = @ProvinceID
	AND inNews = 1
	ORDER BY orderby
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[procAdverprojectChangeadSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


--创建人 Lambo  20101010
--用于首页查询切换的广告图片
CREATE PROCEDURE [dbo].[procAdverprojectChangeadSelect] 
(
	@province_id SMALLINT
)
AS
BEGIN
	SELECT id, imagefile, remarks, url, companyid
	FROM adverproject with(nolock)
	WHERE type=9 
	AND begintime<=CAST(GETDATE() AS SMALLDATETIME) 
	AND endtime>=CAST(GETDATE() AS SMALLDATETIME)  
	AND valid=1 
	AND province_id=@province_id
	ORDER BY orderby
END

GO
/****** Object:  StoredProcedure [dbo].[procAdverprojectChangeadSelectNew]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[procAdverprojectChangeadSelectNew] 
(
	@province_id SMALLINT
)
AS
BEGIN
	SELECT id, imagefile, remarks, url, companyid
	FROM adverproject with(nolock)
	WHERE type=16
	AND begintime<=CAST(GETDATE() AS SMALLDATETIME) 
	AND endtime>=CAST(GETDATE() AS SMALLDATETIME)  
	AND valid=1 
	AND province_id=@province_id
	ORDER BY orderby
END














GO
/****** Object:  StoredProcedure [dbo].[procAdverprojectClickCountByIDUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.03
--创建人：Nick
--说明：修改点击次数
--#####################################################
CREATE PROCEDURE [dbo].[procAdverprojectClickCountByIDUpdate]
(
	@ID INT
)
AS
BEGIN TRY
	UPDATE adverproject SET clickcount=clickcount+1 WHERE id = @ID
	RETURN 1
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[ProcAdverProjectErrorLogInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.28
--创建人：Nick
--说明：插入 广告日志
--#####################################################
CREATE PROCEDURE [dbo].[ProcAdverProjectErrorLogInsert]
	@Log VARCHAR(500)
AS
BEGIN TRY
	INSERT INTO AdverProject_Errorlog (errorlog) 
	VALUES (@Log)
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[ProcAdverProjectHWSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.28
--创建人：Nick
--说明：获取首页横排广告的宽度信息
--#####################################################
CREATE PROCEDURE [dbo].[ProcAdverProjectHWSelect]
(
    @dcProvinceId VARCHAR(10),
    @Date VARCHAR(50)
)
AS
BEGIN
    SELECT width, height 
    FROM AdverProject WITH(Nolock) 
    WHERE Province_ID = @dcProvinceId
    AND Type = 10
    AND BeginTime <= CONVERT(SMALLDATETIME, @Date)
    AND EndTime > CONVERT(SMALLDATETIME, @Date)
    AND Valid = 1
    ORDER BY OrderBy
END
GO
/****** Object:  StoredProcedure [dbo].[procAdverprojectLogoSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[procAdverprojectLogoSelect] 
(
	@province_id SMALLINT
)
AS
BEGIN
	SELECT id, imagefile, remarks, url, companyid
	FROM adverproject with(nolock)
	WHERE type=17
	AND begintime<=CAST(GETDATE() AS SMALLDATETIME) 
	AND endtime>=CAST(GETDATE() AS SMALLDATETIME)  
	AND valid=1 
	AND province_id=@province_id
	ORDER BY orderby
END














GO
/****** Object:  StoredProcedure [dbo].[ProcAdverprojectRowad]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--######################################################33
--创建人 Lambo	
--20101009
--用于首页查询六分之一模块的广告图片
--修改 sean 2011-10-11 增加每个企业的职位和简介
--sean 2014-01-10
--######################################################33
CREATE PROCEDURE [dbo].[ProcAdverprojectRowad]
(
	@Province_Id SMALLINT
)
AS
BEGIN
	IF @Province_Id < 99 OR @Province_Id LIKE '32%'
	BEGIN
		SELECT Id, Type,Province_Id,ImageFile,Url,Width,Height,Remarks,NoFollow + CompanyId CompanyId,Orderby,JobID,JobName,CompanyBiref
		FROM SearchDb..AdverProjectShot WITH(NOLOCK)
		WHERE Type=10 
		AND Province_Id = @Province_Id
		ORDER BY OrderBy
	END
	ELSE
	BEGIN
		DECLARE @t AS TABLE(
			oId INT identity(1, 1),
			id INT,
			Type Int,
			Province_Id int,
			ImageFile VARCHAR(100),
			Url VARCHAR(200),
			Width int,
			Height int,
			Remarks NVARCHAR(200),
			CompanyId VARCHAR(20),
			OrderBy INT,
			JobId VARCHAR(200),
			JobName NVARCHAR(1000),
			CompanyBiref NVARCHAR(200)
		)
		INSERT @t(Id, Type, Province_Id, ImageFile, Url, Width, Height, Remarks, CompanyId, Orderby, JobID, JobName, CompanyBiref)
		SELECT Id, Type, Province_Id, ImageFile, Url, Width, Height, Remarks, NoFollow + CompanyId CompanyId, Orderby, JobID, JobName, CompanyBiref
		FROM SearchDb..AdverProjectShot WITH(NOLOCK)
		WHERE Type=10 
		AND Province_Id = @Province_Id
		ORDER BY OrderBy

		INSERT @t(Id, Type, Province_Id, ImageFile, Url, Width, Height, Remarks, CompanyId, Orderby, JobID, JobName, CompanyBiref)
		SELECT Id, Type, Province_Id, ImageFile, Url, Width, Height, Remarks, NoFollow + CompanyId CompanyId, Orderby, JobID, JobName, CompanyBiref
		FROM SearchDb..AdverProjectShot WITH(NOLOCK)
		WHERE Type=10 
		AND Province_Id = LEFT(@Province_Id, 2)
		ORDER BY OrderBy
		SELECT Id, Type, Province_Id, ImageFile, Url, Width, Height, Remarks, CompanyId, Orderby, JobID, JobName, CompanyBiref FROM @t ORDER BY Oid
	END
END










GO
/****** Object:  StoredProcedure [dbo].[procAdverprojectRowTopadSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--创建人 Lambo
--时间 20101009
--用于网站首页查询网站头部广告
CREATE PROCEDURE [dbo].[procAdverprojectRowTopadSelect] 
(
	@province_id int
)
AS
BEGIN
	SELECT id,imagefile,width,url,companyid,remarks
	FROM adverproject WITH(NOLOCK)
	WHERE TYPE=11 
	AND begintime<=CAST(GETDATE() AS SMALLDATETIME) 
	AND endtime>=CAST(GETDATE()-7 AS SMALLDATETIME) 
	AND valid=1 
	AND province_id=@province_id
	ORDER BY orderby
END 

GO
/****** Object:  StoredProcedure [dbo].[procAdverProjectShotByProvinceIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.10
--创建人：Nick
--说明：首页广告
--#####################################################
CREATE PROCEDURE [dbo].[procAdverProjectShotByProvinceIDSelect]
AS
BEGIN TRY
	SELECT *,b.dcProvinceID 
	FROM SearchDb..AdverProjectShot a WITH(NOLOCK) 
	left join cpMain b WITH(NOLOCK) on a.CompanyID=b.SecondID 
	WHERE type=10  
	AND Province_Id = 0 
	ORDER BY OrderBy
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[ProcAdverProjectShotRebuild]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ProcAdverProjectShotRebuild]
AS
BEGIN
	SET NOCOUNT ON
	DECLARE @t AS TABLE(
		[Id] [int] NOT NULL,
		[Type] [smallint] NOT NULL,
		[Province_Id] [int] NOT NULL,
		[ImageFile] [varchar](100) NULL,
		[Url] [varchar](200) NULL,
		[Width] [smallint] NULL,
		Height SmallINT NULL,
		[Remarks] [nvarchar](200) NULL,
		[CompanyId] varchar(12) NULL,
		[Orderby] [smallint] NULL,
		[JobID] [varchar](300) NULL,
		[JobName] [nvarchar](1000) NULL,
		[CompanyBiref] [nvarchar](200) NULL,
		RealCpMainID INT,
		NoFollow VARCHAR(1)
	)

--	DECLARE @OrderBy1 AS INT
--	DECLARE @OrderBy2 AS INT
--	SELECT @ORderBy1 = OrderBy FROM AdverProject WITH(NOLOCK) WHERE ID = 28078 AND Valid = 1
--	SELECT @ORderBy2 = OrderBy FROM AdverProject WITH(NOLOCK) WHERE ID = 31536 AND Valid = 1
--	IF @OrderBy1 > 0 AND @OrderBy2 > 0
--	BEGIN
--		UPDATE AdverProject SET OrderBy = @OrderBy1 WHERE ID = 31536
--		UPDATE AdverProject SET OrderBy = @OrderBy2 WHERE ID = 28078
--	END

	INSERT INTO @t(Id, Imagefile, Width, Height, Url, Companyid, Remarks, Province_Id, Type, ORderBy, RealCpMainID, NoFollow)
	SELECT Id, Imagefile, Width, Height, Url, Companyid, Remarks, Province_Id, Type, ORderBy, Companyid, '_'
	FROM AdverProject WITH(NOLOCK)
	WHERE Type=10 
	AND BeginTime <= CAST(GETDATE() AS SMALLDATETIME) 
	AND EndTime > CAST(GETDATE() AS SMALLDATETIME) 
	AND Valid = 1 

	DECLARE @RUN AS INT
	SET @Run = 0

	UPDATE @t SET JobID = dbo.GetJobSecondIds(Companyid), JobName = dbo.GetJobNames(Companyid)
	UPDATE a SET a.Companyid = b.SecondId
	FROM @t a, cpMain b WITH(NOLOCK)
	WHERE a.RealCpMainID = b.Id

	UPDATE a
	SET a.CompanyBiref = LEFT(ISNULL(b.Brief, ''), 200)
	FROM @t a,
	cpMain b WITH(NOLOCK)
	WHERE b.ID = a.RealCpMainID
	
	UPDATE @t SET NoFollow = ''
	--WHERE CompanyID IN(SELECT PageId FROM MarketDb..PageBaiduInclude WHERE PageType = 1 AND IncludeDate IS Null)

	TRUNCATE TABLE SearchDB..AdverProjectShot
	INSERT INTO SearchDB..AdverProjectShot
	SELECT * FROM @t
END













GO
/****** Object:  StoredProcedure [dbo].[procAgent_BlackSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.03
--创建人：Nick
--说明：Agent黑名单
--#####################################################
CREATE PROCEDURE [dbo].[procAgent_BlackSelect]
AS
BEGIN TRY
	SELECT * FROM agent_Black With(Nolock) ORDER BY ID
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[procAgent_WhiteSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.03
--创建人：Nick
--说明：Agent白名单
--#####################################################
CREATE PROCEDURE [dbo].[procAgent_WhiteSelect]
AS
BEGIN TRY
	SELECT * FROM agent_White With(Nolock) ORDER BY ID
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[procAvgSalarySelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.03
--创建人：Nick
--说明：得到平均工资信息
--#####################################################
CREATE PROCEDURE [dbo].[procAvgSalarySelect]
(
	@RegionID INT,
	@JobTypeID INT,
	@Cnt INT
)
AS
BEGIN TRY
	SELECT dcsalaryid,d.description,CONVERT(decimal(18,1),count(*)/CONVERT(DECIMAL(18,1),@Cnt)*100) pct,count(*) cnt 
	FROM job a WITH(NOLOCK),dcsalary d WITH(NOLOCK)
	WHERE d.id=a.dcsalaryid
	AND a.dcjobtypeid = @JobTypeID
	AND a.dcregionid like ''+CONVERT(VARCHAR(6),@RegionID)+'%'
	AND a.dcSalaryID<>100
	AND a.Valid > 0
	AND a.dcSalaryID IS NOT NULL AND a.RefreshDate>GetDate()-365
	GROUP BY a.dcsalaryid, d.description 
	ORDER BY a.dcsalaryid
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[ProcBaiduLinkLogSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ProcBaiduLinkLogSelect]
(
	@ProvinceId TINYINT
)
AS
BEGIN
	SELECT TOP 480 *, SPACE(200) Url INTO #T FROM LogDb..BaiduLinkLog WHERE AddSubmitDate IS NULL AND ProvinceID = @ProvinceId
	DECLARE @Site VARCHAR(50)

	SELECT @Site = ProvinceDomain FROM dcProvince WHERE ID = @ProvinceId
	
	UPDATE #t
	SET Url = 'http://www.' + @Site + '/personal/cp' + SecondId + '.html'
	WHERE cpMainId > 0
	
	UPDATE #t
	SET Url = 'http://www.' + @Site + '/personal/jb' + SecondId + '.html'
	WHERE JobId > 0

	SELECT Url FROM #t
	UPDATE LogDb..BaiduLinkLog SET AddSubmitDate = GETDATE() WHERE Id IN(SELECT Id FROM #t)
	DROP TABLE #T
END

GO
/****** Object:  StoredProcedure [dbo].[procBaiduMapLogByJobIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.04
--创建人：Nick
--说明：获取职位标注地点
--#####################################################
CREATE PROCEDURE [dbo].[procBaiduMapLogByJobIDSelect]
(
	@JobID VARCHAR(20)
)
AS
BEGIN TRY
	SELECT FullName FROM LogDB..BaiduMapLog WITH(NOLOCK) WHERE JobID=@JobID
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[procBaiduMapLogSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.10
--创建人：John
--说明：获取待同步的地图信息
--#####################################################
CREATE PROCEDURE [dbo].[procBaiduMapLogSelect]
AS
BEGIN
	SELECT TOP 30000 JobId, JobName, Address, cpMainName, Lng, Lat, Salary, JobUrl, cpMainUrl, Status 
	FROM BaiduMapLog WITH(NOLOCK) WHERE Status IN(1, 2, 3)
END


GO
/****** Object:  StoredProcedure [dbo].[procBaiduMapLogUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.10
--创建人：John
--说明：更新地图信息
--#####################################################
CREATE PROCEDURE [dbo].[procBaiduMapLogUpdate]
(
	@JobID INT
)
AS
BEGIN
	UPDATE BaiduMapLog SET [Status] = 0, UploadDate = GETDATE() WHERE Status IN(1, 2) AND JobID = @JobID
	DELETE BaiduMapLog WHERE Status = 3 AND JobID = @JobID
END


GO
/****** Object:  StoredProcedure [dbo].[ProcBaiduSiteFileByExpiredCpMainSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
------------------
--sean 2013-12-12
CREATE PROCEDURE [dbo].[ProcBaiduSiteFileByExpiredCpMainSelect]
(
	@ProvinceId INT
)
AS
BEGIN
	DECLARE @i INT, @Sd DATETIME
	SELECT @i = DATEDIFF(DAY, '2013-12-11', GETDATE()),
		@sd = CONVERT(VARCHAR(10), GETDATE() - @i* 2, 120)
 
	DELETE BaiduExpiredCpMain WHERE cpMainId IN(SELECT ID FROM cpMain WITH(NOLOCK) WHERE Valid = 1)

	SELECT TOP 0 cpMainId, SecondId INTO #t FROM BaiduExpiredCpMain
	--------7天内受限制的职位
	INSERT #t
	SELECT ID, SecondId
	FROM cpMain WITH(NOLOCK)
	WHERE isLimitlogin = 9 
	AND Id in(SELECT cpMainid FROM bsCpstatus WHERE statusId=9 AND AddDate > GETDATE() - 7)
	AND dcProvinceId = @ProvinceID

	-------2天内删除的职位
	INSERT INTO #t
	SELECT Id, SecondID
	FROM company_deleted
	WHERE AddDate > GETDATE() - 2 
	AND Province_ID = @ProvinceID

	-------不在CpMain表中的职位
	INSERT INTO #t
	SELECT Id, SecondId
	FROM LogDb..AllCpMainLog
	WHERE Id NOT IN(SELECT Id FROM cpMain WITH(NOLOCK)) 

	DELETE #t WHERE cpMainId IN (SELECT cpMainId FROM BaiduExpiredCpMain WHERE AddDate < GETDATE() - 1)
	SELECT DISTINCT * INTO #t1 FROM #t
	INSERT BaiduExpiredCpMain
	SELECT DISTINCT *, GETDATE()
	FROM #t
	WHERE cpMainID NOT IN(SELECT cpMainId FROM BaiduExpiredCpMain)
	ORDER BY cpMainId

	SELECT '/personal/cp' + CONVERT(VARCHAR, SecondID) + '.html' Link
	FROM #t1 order by SecondID desc
END










GO
/****** Object:  StoredProcedure [dbo].[ProcBaiduSiteFileByExpiredJobSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--sean 2013-12-12
CREATE PROCEDURE [dbo].[ProcBaiduSiteFileByExpiredJobSelect]
(
	@ProvinceId INT
)
AS
BEGIN
	DECLARE @i INT, @Sd DATETIME
	SELECT @i = DATEDIFF(DAY, '2013-12-11', GETDATE()),
		@sd = CONVERT(VARCHAR(10), GETDATE() - @i* 2, 120)
 
	DELETE BaiduExpiredJob WHERE JobId IN(
		SELECT a.ID FROM Job a WITH(NOLOCK), cpMain b WITH(NOLOCK)
		WHERE a.cpMainId = b.Id
		AND a.Valid = 1 AND b.Valid = 1)

	SELECT TOP 0 * INTO #t FROM BaiduExpiredJob
	--------7天内受限制的职位
	INSERT #t
	SELECT a.ID, a.SecondId, GETDATE()
	FROM Job a WITH(NOLOCK),
		cpMain b WITH(NOLOCK)
	WHERE a.cpMainid = b.id
	AND b.isLimitlogin = 9 
	AND b.Id in(SELECT cpMainid FROM bsCpstatus WHERE statusId=9 AND AddDate > GETDATE() - 7)
	AND b.dcProvinceId = @ProvinceID

	-------2天内删除的职位
	INSERT INTO #t
	SELECT JobId, SecondID, GETDATE()
	FROM JobDeleted
	WHERE DeleteDate > @sd 
	AND ProvinceID = @ProvinceID

	-------不在Job表中的职位
	INSERT INTO #t
	SELECT JobId, JobSecondId, GETDATE() FROM LogDb..AllJobLog WHERE JobId NOT IN(SELECT Id FROM Job WITH(NOLOCK))

	DELETE #t WHERE JobId IN (SELECT JobId FROM BaiduExpiredJob WHERE AddDate < GETDATE() - 1)
	SELECT DISTINCT * INTO #t1 FROM #t
	INSERT BaiduExpiredJob 
	SELECT DISTINCT * FROM #t
	WHERE JobId NOT IN(SELECT JobId FROM BaiduExpiredJob)
	ORDER BY JobId

	DELETE LogDb..AllJobLog WHERE JobId IN(SELECT JobId FROM #t)

	SELECT '/personal/jb' + CONVERT(VARCHAR, SecondID) + '.html' Link
	FROM #t order by SecondID desc
END









GO
/****** Object:  StoredProcedure [dbo].[ProcBaiduSiteFileByExpiredSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--sean 2013-12-12
CREATE PROCEDURE [dbo].[ProcBaiduSiteFileByExpiredSelect]
(
	@ProvinceId INT
)
AS
BEGIN
	--SELECT TOP 0 NULL Link
	--RETURN

	DECLARE @i INT, @Sd DATETIME
	SELECT @i = DATEDIFF(DAY, '2013-12-11', GETDATE()),
		@sd = CONVERT(VARCHAR(10), GETDATE() - @i* 2, 120)
 
	DELETE BaiduExpiredJob WHERE JobId IN(
		SELECT a.ID FROM Job a WITH(NOLOCK), cpMain b WITH(NOLOCK)
		WHERE a.cpMainId = b.Id
		AND a.Valid = 1 AND b.Valid = 1)

	SELECT TOP 0 * INTO #t FROM BaiduExpiredJob
	--------7天内受限制的职位
	INSERT #t
	SELECT a.ID, a.SecondId, GETDATE()
	FROM Job a WITH(NOLOCK),
		cpMain b WITH(NOLOCK)
	WHERE a.cpMainid = b.id
	AND b.isLimitlogin = 9 
	AND b.Id in(SELECT cpMainid FROM bsCpstatus WHERE statusId=9 AND AddDate > GETDATE() - 7)
	AND b.dcProvinceId = @ProvinceID

	-------2天内删除的职位
	INSERT INTO #t
	SELECT JobId, SecondID, GETDATE()
	FROM JobDeleted
	WHERE DeleteDate > @sd 
	AND ProvinceID = @ProvinceID

	-------不在Job表中的职位
	INSERT INTO #t
	SELECT JobId, JobSecondId, GETDATE() FROM LogDb..AllJobLog WHERE JobId NOT IN(SELECT Id FROM Job WITH(NOLOCK))

	DELETE #t WHERE JobId IN (SELECT JobId FROM BaiduExpiredJob WHERE AddDate < GETDATE() - 1)
	SELECT DISTINCT * INTO #t1 FROM #t
	INSERT BaiduExpiredJob 
	SELECT DISTINCT * FROM #t
	WHERE JobId NOT IN(SELECT JobId FROM BaiduExpiredJob)
	ORDER BY JobId

	DELETE LogDb..AllJobLog WHERE JobId IN(SELECT JobId FROM #t)

	SELECT '/personal/jb' + CONVERT(VARCHAR, SecondID) + '.html' Link
	FROM #t order by SecondID desc
END









GO
/****** Object:  StoredProcedure [dbo].[ProcBaiduSiteFileCompanySelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--++++++++++++++++++++++++++++++++++++++++++++++++++++++++
--sean 2014-2-27 update,modify secondid
--++++++++++++++++++++++++++++++++++++++++++++++++++++++++
CREATE PROCEDURE [dbo].[ProcBaiduSiteFileCompanySelect]
(
	@SiteId INT
)
AS
BEGIN
	IF EXISTS(SELECT 'x' FROM dcSubSite WHERE IsMainSite = 1 AND ID = @SiteId)
	BEGIN
		IF @SiteId < 99
		BEGIN
			SELECT TOP 50000 '/personal/cp' + SecondId + '.html' link FROM CpMainPublish WITH(NOLOCK)
			WHERE Valid>0 --AND RefreshDate > CONVERT(varchar(10),GetDate(),120)
			AND dcRegionID LIKE LTRIM(STR(@SiteId)) + '%'
			AND SecondId IN(SELECT PageId FROM MarketDb..PageBaiduInclude WITH(NOLOCK) WHERE IncludeDate IS NULL)
		END
		ELSE
		BEGIN
			SELECT TOP 50000 '/personal/cp' + SecondId + '.html' link FROM CpMainPublish WITH(NOLOCK)
			WHERE Valid>0 --AND RefreshDate > CONVERT(varchar(10),GetDate(),120)
			AND dcRegionID LIKE LTRIM(STR(@SiteId)) + '%'
			AND SecondId IN(SELECT PageId FROM MarketDb..PageBaiduInclude WITH(NOLOCK) WHERE IncludeDate IS NULL)
			
		END
	END
	ELSE
	BEGIN
		IF @SiteId LIKE '35__'
		BEGIN
			SELECT TOP 50000 '/personal/cp' + SecondId + '.html' link FROM CpMain WITH(NOLOCK)
			WHERE Valid>0 AND RefreshDate > CONVERT(varchar(10), GetDate(),120) AND dcProvinceID=LEFT(@SiteId, 2)
			AND SecondId IN(SELECT PageId FROM MarketDb..PageBaiduInclude WITH(NOLOCK) WHERE IncludeDate IS NULL)
			UNION
			SELECT TOP 50000 '/corp/cp-' + SecondId + '.html' link FROM CpMain WITH(NOLOCK)
			WHERE Valid>0 AND RefreshDate > CONVERT(varchar(10), GetDate(),120) AND dcProvinceID=LEFT(@SiteId, 2)
			AND SecondId IN(SELECT PageId FROM MarketDb..PageBaiduInclude WITH(NOLOCK) WHERE IncludeDate IS NULL)		
		END
		ELSE
		BEGIN
			SELECT TOP 50000 '/personal/cp' + SecondId + '.html' link FROM CpMainPublish WITH(NOLOCK)
			WHERE Valid>0 --AND RefreshDate>CONVERT(varchar(10),GetDate(),120) AND dcProvinceID=LEFT(@SiteId, 2)
			AND dcRegionID LIKE LTRIM(STR(@SiteId)) + '%'
			AND SecondId IN(SELECT PageId FROM MarketDb..PageBaiduInclude WITH(NOLOCK) WHERE IncludeDate IS NULL)
		END
	END
END










GO
/****** Object:  StoredProcedure [dbo].[ProcBaiduSiteFileCpJobSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--++++++++++++++++++++++++++++++++++++++++++++++++++++++++
--sean 2014-2-27 update,modify secondid
--++++++++++++++++++++++++++++++++++++++++++++++++++++++++
CREATE PROCEDURE [dbo].[ProcBaiduSiteFileCpJobSelect]
(
    @SiteId INT
)
AS
BEGIN
    IF EXISTS(SELECT 'x' FROM dcSubSite WHERE IsMainSite = 1 AND ID = @SiteId)
    BEGIN
        IF @SiteId < 99
        BEGIN
            SELECT TOP 50000 '/personal/cpjob' + SecondId + '.html' link 
			FROM CpMainPublish WITH(NOLOCK)
            WHERE Valid > 0 --AND RefreshDate > CONVERT(varchar(10),GetDate(),120)
            AND dcRegionID LIKE LTRIM(STR(@SiteId)) + '%'
            AND SecondId IN(SELECT PageId FROM MarketDb..PageBaiduInclude WITH(NOLOCK) WHERE IncludeDate IS NULL)
        END
        ELSE
        BEGIN
            SELECT TOP 50000 '/personal/cpJob' + SecondId + '.html' link FROM CpMainPublish WITH(NOLOCK)
            WHERE Valid > 0 --AND RefreshDate > CONVERT(varchar(10),GetDate(),120)
            AND dcRegionID LIKE LTRIM(STR(@SiteId)) + '%'
            AND SecondId IN(SELECT PageId FROM MarketDb..PageBaiduInclude WITH(NOLOCK) WHERE IncludeDate IS NULL)
        END
    END
    ELSE
    BEGIN
		SELECT TOP 50000 '/personal/cpjob' + SecondId + '.html' link FROM CpMainPublish WITH(NOLOCK)
        WHERE Valid > 0 --AND RefreshDate>CONVERT(varchar(10),GetDate(),120) AND dcProvinceID=LEFT(@SiteId, 2)
        AND dcRegionID LIKE LTRIM(STR(@SiteId)) + '%'
        AND SecondId IN(SELECT PageId FROM MarketDb..PageBaiduInclude WITH(NOLOCK) WHERE IncludeDate IS NULL)
    END
END

GO
/****** Object:  StoredProcedure [dbo].[ProcBaiduSiteFileJobSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ProcBaiduSiteFileJobSelect]
(
	@SiteId INT
)
AS
BEGIN
	CREATE TABLE #t(ID INT, SecondId VARCHAR(12))
	IF EXISTS(SELECT 'x' FROM dcSubSite WHERE IsMainSite = 1 AND ID = @SiteId)
	BEGIN
		IF @SiteId < 99
		BEGIN
			INSERT INTO #t
			SELECT a.Id, a.SecondId
			FROM Job a, cpMain b
			WHERE a.cpMainID = b.ID
			AND a.Valid>0 AND a.RefreshDate > CONVERT(VARCHAR(10), GETDATE(), 120)
			AND b.dcProvinceID = @SiteId 

			DELETE #t WHERE SecondId IN(SELECT PageId FROM MarketDb..PageBaiduInclude WITH(NOLOCK) WHERE IncludeDate IS NOT NULL)

			SELECT TOP 50000 '/personal/jb' + SecondID + '.html' link 
			FROM Job
			WHERE ID IN(SELECT ID FROM #t)
		END
		ELSE
		BEGIN
			INSERT INTO #t
			SELECT a.Id, a.SecondId
			FROM Job a, cpMain b
			WHERE a.cpMainID = b.ID
			AND a.Valid>0 AND a.RefreshDate > CONVERT(VARCHAR(10), GETDATE(), 120)
			AND b.dcSubSiteID = @SiteId

			DELETE #t WHERE SecondId IN(SELECT PageId FROM MarketDb..PageBaiduInclude WITH(NOLOCK) WHERE IncludeDate IS NOT NULL)

			SELECT TOP 50000 '/personal/jb' + SecondID + '.html' link 
			FROM Job
			WHERE ID IN(SELECT ID FROM #t)
		END
	END
	ELSE
	BEGIN
		IF @SiteId LIKE '35__'
		BEGIN
			INSERT INTO #t
			SELECT a.Id, a.SecondId
			FROM Job a, cpMain b
			WHERE a.cpMainID = b.ID
			AND a.Valid > 0 AND a.RefreshDate > CONVERT(VARCHAR(10), GETDATE(), 120)
			AND b.dcProvinceID = LEFT(@SiteId, 2)
			DELETE #t WHERE SecondId IN(SELECT PageId FROM MarketDb..PageBaiduInclude WITH(NOLOCK) WHERE IncludeDate IS NOT NULL)

			SELECT TOP 50000 '/personal/jb' + SecondID + '.html' link 
			FROM Job
			WHERE ID IN(SELECT ID FROM #t)
			UNION
			SELECT TOP 50000 '/Job/jb-' + SecondID + '.html' link 
			FROM Job
			WHERE ID IN(SELECT ID FROM #t)
		END
		ELSE
		BEGIN
			INSERT INTO #t
			SELECT a.Id, a.SecondId
			FROM Job a, cpMain b
			WHERE a.cpMainID = b.ID
			AND a.Valid>0 AND a.RefreshDate > CONVERT(VARCHAR(10), GETDATE(), 120)
			AND b.dcProvinceID = LEFT(@SiteId, 2)
			DELETE #t WHERE SecondId IN(SELECT PageId FROM MarketDb..PageBaiduInclude WITH(NOLOCK) WHERE IncludeDate IS NOT NULL)

			SELECT TOP 50000 '/personal/jb' + SecondID + '.html' link 
			FROM Job
			WHERE ID IN(SELECT ID FROM #t)
		END
	END	
END










GO
/****** Object:  StoredProcedure [dbo].[ProcBaiduSubSiteByUrlSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2014.10.28
--创建人：John
--说明：获取网站站点数据 用于百度数据
--@subSiteUrl 网站Url
--#####################################################
CREATE PROCEDURE [dbo].[ProcBaiduSubSiteByUrlSelect]
(
	@subSiteUrl VARCHAR(50)
)
AS
BEGIN TRY
	SELECT id, SecondSiteName WebSite, SubSiteUrl Domain 
	FROM dcSubSite WITH(NOLOCK) 
	WHERE SubSiteUrl = @subSiteUrl
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[ProcBaiduXmlBy51rcSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ProcBaiduXmlBy51rcSelect]
AS
SET NOCOUNT ON
BEGIN	
	SELECT * FROM  ShortDb..BaiduXmlJob51rcOut  ORDER By RefreshDate DESC
END

GO
/****** Object:  StoredProcedure [dbo].[ProcBaiduXMLByAllSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--------------------------------------------------
--创建人：SEAN
--创建日期：2016-09-06
--功能说明：查询生成百度XML全部数据
--------------------------------------------------
CREATE PROCEDURE [dbo].[ProcBaiduXMLByAllSelect]
(
	@dcProvinceID SMALLINT, 
	@ServerId SMALLINT
)
AS
SET NOCOUNT ON
IF @ServerId IS NULL
	SET @ServerId = 99
IF @dcProvinceID IS NULL
	RETURN
BEGIN
	DECLARE @PageNo SMALLINT, @GetRows INT, @BeginJobId INT, @PageCount INT,
		@AddDate DATETIME, @Id INT, @CurrentStatus TINYINT, @MaxJobId INT,
		@PageRows INT
	SELECT @PageRows = 1500
	SELECT @Id = Id, @PageNo = PageNo, @BeginJobId = BeginJobId, @PageCount = [PageCount],
		@AddDate = AddDate, @CurrentStatus = CurrentStatus, @GetRows = GetRows
	FROM LogDb..BaiduXmlRunLog WITH(NOLOCK)
	WHERE ServerID = @ServerID
	AND dcProvinceID = @dcProvinceID

	IF @PageNo IS NULL OR @AddDate < DATEADD(HOUR, -4, GETDATE())
	BEGIN	
		DELETE FROM LogDb..BaiduXmlRunLog WHERE Id = @Id

		SELECT TOP 1 @MaxJobId = RowNo + 10 FROM Shortdb..BaiduXMLJobOut WITH(NOLOCK) ORDER BY RowNo DESC
		SELECT @PageNo = 1, @CurrentStatus = 0, @BeginJobId = @MaxJobId, @CurrentStatus = 0, @GetRows = NULL

		INSERT INTO Logdb..BaiduXmlRunLog(ServerId, dcProvinceId, PageNo, BeginJobId, CurrentStatus, AddDate)
		SELECT @ServerId, @dcProvinceID, @PageNo, @BeginJobId, @CurrentStatus, GETDATE()
	END

	IF @CurrentStatus = 10
	BEGIN
		SELECT TOP 0 * FROM LogDb..BaiduXmlRunLog 
		RETURN
	END

	IF @CurrentStatus = 2
	BEGIN
		SELECT * FROM LogDb..BaiduXmlRunLog WHERE Id = @Id
		RETURN
	END
	--判断最后一次是否成功
	IF @CurrentStatus = 1
	BEGIN
		IF @GetRows = @PageRows
			UPDATE LogDb..BaiduXmlRunLog
			SET CurrentStatus = 0, GetRows = 0, PageNo = PageNo + 1
			WHERE Id = @Id
		ELSE
			UPDATE LogDb..BaiduXmlRunLog
			SET CurrentStatus = 0, GetRows = 0
			WHERE Id = @Id
	END
	
	SELECT @Id = Id, @PageNo = PageNo, @BeginJobId = BeginJobId,
		@AddDate = AddDate, @CurrentStatus = CurrentStatus, @PageCount = [PageCount]
	FROM LogDb..BaiduXmlRunLog WITH(NOLOCK)
	WHERE ServerID = @ServerID
	AND dcProvinceID = @dcProvinceID
	--------------------------------------
	CREATE TABLE #t
	(
		id int,
		jobname nvarchar(80),
		JobDESC varchar(max),
		JobDemand varchar(max),
		jobregion varchar(6),
		companyname varchar(100),
		edulevel tinyint,
		IsDelete bit,
		experiencelevel tinyint,
		AnnounceDate datetime,
		dcSalaryID tinyint,
		dcjobtypeID smallint,
		ShortName varchar(40),
		Address nvarchar(100),
		dcCompanySizeID tinyint,
		Brief varchar(6000),
		EmployType tinyint,
		adddate smalldatetime,
		dcCompanyKindID smallint,
		enddate smalldatetime,
		email varchar(50),
		EnJobID varchar(12),
		EnCpMainID varchar(10),
		IndustryId smallint,
		SubSiteUrl varchar(50),
		SubSiteName varchar(50),
		NeedNumber nvarchar(10),
		Welfare1 bit,
		Welfare2 bit,
		Welfare3 bit,
		Welfare4 bit,
		Welfare5 bit,
		Welfare6 bit,
		Welfare7 bit,
		Welfare8 bit,
		Welfare9 bit,
		Welfare10 bit,
		Welfare11 bit,
		Welfare12 bit,
		Welfare13 bit,
		Welfare14 bit,
		Welfare15 bit,
		Welfare16 bit,
		Welfare17 bit,
		Welfare18 bit,
		RowNo int,
		IsVip BIt
	)

	IF @dcProvinceID = 32 AND @ServerId > 900
	BEGIN
		IF @PageCount = 0
		BEGIN
			SELECT @PageCount = (COUNT(*) - 1) / @PageRows + 1
			FROM ShortDb..BaiduXMLJobOut WITH(NOLOCK)
			WHERE SiteId = @dcProvinceID AND RowNo > 0

			UPDATE LogDb..BaiduXmlRunLog SET PageCount = @PageCount WHERE Id = @Id 
		END

		INSERT INTO #t
		SELECT TOP (@PageRows) id, jobname, JobDESC, JobDemand, jobregion, companyname, edulevel, IsDelete,
			experiencelevel, AnnounceDate, dcSalaryID, dcjobtypeID, ShortName, Address, dcCompanySizeID, Brief,
			EmployType, adddate, dcCompanyKindID, enddate, email, EnJobID, EnCpMainID,
			IndustryId, SubSiteUrl, SubSiteName, NeedNumber, Welfare1, Welfare2, Welfare3, Welfare4, Welfare5,
			Welfare6, Welfare7, Welfare8, Welfare9, Welfare10, Welfare11, Welfare12, Welfare13, Welfare14,
			Welfare15, Welfare16, Welfare17, Welfare18, RowNo
		FROM ShortDb..BaiduXMLJobOut WITH(NOLOCK)
		WHERE SiteId = @dcProvinceID
		AND RowNo < @BeginJobId 
		ORDER BY RowNo DESC
	END
	ELSE
	BEGIN
		IF @PageCount = 0
		BEGIN
			SELECT @PageCount = (COUNT(*) - 1) / @PageRows + 1
			FROM ShortDb..BaiduXMLJobOut WITH(NOLOCK)
			WHERE SiteId = @dcProvinceID AND RowNo > 0

			UPDATE LogDb..BaiduXmlRunLog SET [PageCount] = @PageCount WHERE Id = @Id
		END
			
		INSERT INTO #t
		SELECT TOP (@PageRows) id, jobname, JobDESC, JobDemand, jobregion, companyname, edulevel, IsDelete,
			experiencelevel, AnnounceDate, dcSalaryID, dcjobtypeID, ShortName, Address, dcCompanySizeID, Brief,
			EmployType, adddate, dcCompanyKindID, enddate, email, EnJobID, EnCpMainID,
			IndustryId, SubSiteUrl, SubSiteName, NeedNumber, Welfare1, Welfare2, Welfare3, Welfare4, Welfare5,
			Welfare6, Welfare7, Welfare8, Welfare9, Welfare10, Welfare11, Welfare12, Welfare13, Welfare14,
			Welfare15, Welfare16, Welfare17, Welfare18, RowNo, IsVip
		FROM ShortDb..BaiduXMLJobOut WITH(NOLOCK)
		WHERE SiteId = @dcProvinceID
		AND RowNo < @BeginJobId 
		ORDER BY RowNo DESC
	END
	UPDATE #t SET EndDate = GETDATE() + 10 WHERE EndDate < GETDATE() + 1
	DECLARE @JobCount INT
	
	SELECT @JobCount = COUNT(1) FROM #T
	
	IF @JobCount > 0
	BEGIN
		DECLARE @MinJobID INT
		
		SELECT @MinJobID = MIN(RowNo) FROM #T
		
		UPDATE LogDb..BaiduXmlRunLog 
		SET EndJobId = @MinJobID, GetRows = @JobCount, LastRunDate = GETDATE()
		WHERE Id = @Id
	
		SELECT * 
		FROM Logdb..BaiduXmlRunLog WITH(NOLOCK)
		WHERE id = @id
		
		SELECT * FROM #T
	END
	ELSE
	BEGIN
		UPDATE LogDb..BaiduXmlRunLog 
		SET CurrentStatus = 2, LastRunDate = GETDATE()
		WHERE Id = @Id

		SELECT * 
		FROM LogDb..BaiduXmlRunLog WITH(NOLOCK)
		WHERE Id = @Id
	END
	
	DROP TABLE #T
END

GO
/****** Object:  StoredProcedure [dbo].[ProcBaiduXmlByNewstSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--获取10分钟内的数据
CREATE PROCEDURE [dbo].[ProcBaiduXmlByNewstSelect]
(
	@SiteId INT
)
AS
SET NOCOUNT ON
BEGIN
	CREATE TABLE #t
	(
		RowNo INT IDENTITY(1, 1), 
		[Id] [int] NOT NULL, 
		[JobName] [nvarchar](80) NOT NULL, 
		[JobDESC] [varchar](max) NOT NULL, 
		[JobDemand] [varchar](max) NOT NULL, 
		[JobRegion] [varchar](6) NULL, 
		[CompanyName] [varchar](100) NOT NULL, 
		[EduLevel] [tinyint] NOT NULL, 
		[IsDelete] [bit] NOT NULL, 
		[ExperienceLevel] [tinyint] NOT NULL, 
		[Announcedate] [datetime] NOT NULL, 
		[dcSalaryID] [tinyint] NOT NULL, 
		[dcJobtypeID] [smallint] NOT NULL, 
		[ShortName] [varchar](40) NULL, 
		[Address] [nvarchar](100) NULL, 
		[dcCompanySizeID] [tinyint] NULL, 
		[Brief] [varchar](6000) NULL, 
		[EmployType] [tinyint] NOT NULL, 
		[AddDate] [smalldatetime] NOT NULL, 
		[dcCompanyKindID] [smallint] NULL, 
		[EndDate] [smalldatetime] NULL, 
		[Email] [varchar](50) NOT NULL, 
		[EnJobID] [varchar](12) NULL, 
		[EnCpMainID] [varchar](10) NULL, 
		[IndustryId] [smallint] NULL, 
		[SubSiteUrl] [varchar](50) NOT NULL, 
		[SubSiteName] [varchar](50) NOT NULL, 
		NeedNumber VARCHAR(10), 
		[Welfare1] [bit] NULL, 
		[Welfare2] [bit] NULL, 
		[Welfare3] [bit] NULL, 
		[Welfare4] [bit] NULL, 
		[Welfare5] [bit] NULL, 
		[Welfare6] [bit] NULL, 
		[Welfare7] [bit] NULL, 
		[Welfare8] [bit] NULL, 
		[Welfare9] [bit] NULL, 
		[Welfare10] [bit] NULL, 
		[Welfare11] [bit] NULL, 
		[Welfare12] [bit] NULL, 
		[Welfare13] [bit] NULL, 
		[Welfare14] [bit] NULL, 
		[Welfare15] [bit] NULL, 
		[Welfare16] [bit] NULL, 
		[Welfare17] [bit] NULL, 
		[Welfare18] [bit] NULL, 
		RegionDesc NVARCHAR(50), 
		CompanyRegionId VARCHAR(6), 
		IsVip BIT
	)

	DECLARE @SubSiteUrl VARCHAR(100), @SubSiteName VARCHAR(100)
	SELECT @SubSiteUrl = SubSiteUrl, @SubSiteName = SubSiteName
	FROM dcsubsite WITH(NOLOCK)
	WHERE Id = LEFT(@SiteId, 2)

	IF @SiteId > 99
		INSERT INTO #t
		SELECT a.Id, a.Name JobName, a.Responsibility JobDESC, a.Demand JobDemand, 
			a.dcRegionId JobRegion, b.Name CompanyName, a.dcEducationID EduLevel, a.IsDelete, 
			a.MinExperience ExperienceLevel, GETDATE() Announcedate, 	--a.RefreshDate Announcedate, 
			a.dcSalaryID, a.dcJobtypeID, ISNULL(b.ShortName, b.Name) ShortName, b.Address, dcCompanySizeID, Brief, 
			a.EmployType, a.AddDate, b.dcCompanyKindID, a.IssueEnd EndDate, c.Email, a.SecondId EnJobID, b.SecondId EnCpMainID, 
			(SELECT TOP 1 dcIndustryId FROM cpIndustry WITH(NOLOCK) WHERE cpIndustry.cpMainID = b.ID) IndustryId, 
			@SubSiteUrl SubSiteUrl, @SubSiteName SubSiteName, a.NeedNumber, a.Welfare1, a.Welfare2, a.Welfare3, a.Welfare4, a.Welfare5, a.Welfare6, a.Welfare7, a.Welfare8, a.Welfare9, a.Welfare10, a.Welfare11, a.Welfare12, a.Welfare13, a.Welfare14, a.Welfare15, a.Welfare16, a.Welfare17, a.Welfare18, '', 
			b.dcRegionId, CASE WHEN b.MemberType = 3 THEN 1 ELSE 0 END IsVip	
		FROM job a WITH(NOLOCK), cpmain b WITH(NOLOCK), camain c WITH(NOLOCK) 
		WHERE c.Id = a.caMainId AND a.cpMainId = b.Id
		AND a.Valid = 1 AND b.Valid = 1 
		AND IssueEnd > CONVERT(VARCHAR(10), GETDATE() + 1, 120) AND b.VerifyCount > 0 
		AND b.dcProvinceID = LEFT(@SiteId, 2)
		AND a.dcRegionId LIKE LTRIM(STR(@SiteId)) + '%'
		AND LEN(RTRIM(a.Name)) > 1 
		AND a.LastModifyDate > DATEADD(MINUTe, -10, GETDATE())
		ORDER BY a.RefreshDate DESC
	ELSE
	BEGIN
		IF EXISTS(SELECT 'x' FROM Job WITH(NOLOCK) WHERE dcRegionId LIKE LTRIM(STR(@SiteId)) + '%' AND  Valid = 1 AND LastModifyDate > DATEADD(MINUTe, -10, GETDATE()))
			INSERT INTO #t
			SELECT a.id, a.name jobname, a.responsibility JobDESC, a.Demand JobDemand, 
				a.dcregionid jobregion, b.name companyname, a.dcEducationID edulevel, a.IsDelete, 
				a.MinExperience experiencelevel, GETDATE() announcedate, 
				a.dcSalaryID, a.dcjobtypeID, ISNULL(b.ShortName, b.Name) ShortName, b.Address, dcCompanySizeID, Brief, 
				a.EmployType, a.adddate, b.dcCompanyKindID, a.IssueEnd enddate, c.email, a.SecondId EnJobID, b.SecondId EnCpMainID, 
				(SELECT TOP 1 dcIndustryId FROM cpindustry WITH(NOLOCK) WHERE cpindustry.cpMainID = b.ID) IndustryId, 
				@SubSiteUrl SubSiteUrl, @SubSiteName SubSiteName, a.NeedNumber, a.Welfare1, a.Welfare2, a.Welfare3, a.Welfare4, a.Welfare5, a.Welfare6, a.Welfare7, a.Welfare8, a.Welfare9, a.Welfare10, a.Welfare11, a.Welfare12, a.Welfare13, a.Welfare14, a.Welfare15, a.Welfare16, a.Welfare17, a.Welfare18, '', 
				b.dcREgionId, CASE WHEN b.MemberType = 3 THEN 1 ELSE 0 END IsVip	
			FROM job a WITH(NOLOCK), cpmain b WITH(NOLOCK), camain c 
			WHERE a.camainid=c.id AND a.cpmainid=b.id AND a.valid=1
			AND issueend>CONVERT(VARCHAR(10), GETDATE()+1, 120)
			AND b.valid=1 AND b.VerifyCount > 0 
			AND b.dcprovinceid = @SiteId
			AND LEN(RTRIM(a.name)) > 1
			AND a.dcRegionId LIKE LTRIM(STR(@SiteId)) + '%'
			AND a.LastModifyDate > DATEADD(MINUTe, -15, GETDATE())
			ORDER BY a.RefreshDate DESC
		ELSE
			INSERT INTO #t
			SELECT TOP 20 a.id, a.name jobname, a.responsibility JobDESC, a.Demand JobDemand, 
				a.dcregionid jobregion, b.name companyname, a.dcEducationID edulevel, a.IsDelete, 
				a.MinExperience experiencelevel, GETDATE() announcedate, 
				a.dcSalaryID, a.dcjobtypeID, ISNULL(b.ShortName, b.Name) ShortName, b.Address, dcCompanySizeID, Brief, 
				a.EmployType, a.adddate, b.dcCompanyKindID, a.IssueEnd enddate, c.email, a.SecondId EnJobID, b.SecondId EnCpMainID, 
				(SELECT TOP 1 dcIndustryId FROM cpindustry WITH(NOLOCK) WHERE cpindustry.cpMainID = b.ID) IndustryId, 
				@SubSiteUrl SubSiteUrl, @SubSiteName SubSiteName, a.NeedNumber, a.Welfare1, a.Welfare2, a.Welfare3, a.Welfare4, a.Welfare5, a.Welfare6, a.Welfare7, a.Welfare8, a.Welfare9, a.Welfare10, a.Welfare11, a.Welfare12, a.Welfare13, a.Welfare14, a.Welfare15, a.Welfare16, a.Welfare17, a.Welfare18, '', 
				b.dcREgionId, CASE WHEN b.MemberType = 3 THEN 1 ELSE 0 END IsVip	
			FROM job a WITH(NOLOCK), cpmain b WITH(NOLOCK), camain c 
			WHERE a.camainid=c.id AND a.cpmainid=b.id AND a.valid=1
			AND issueend>CONVERT(VARCHAR(10), GETDATE()+1, 120)
			AND b.valid=1 AND b.VerifyCount > 0 
			AND b.dcprovinceid = @SiteId
			AND LEN(RTRIM(a.name)) > 1
			AND a.dcRegionId LIKE LTRIM(STR(@SiteId)) + '%'
			--AND a.LastModifyDate > DATEADD(MINUTe, -10, GETDATE())
			ORDER BY a.LastModifyDate DESC
	END

	ALTER TABLE #t ADD RegionName VARCHAR(50)
	ALTER TABLE #t ADD RegionName2 VARCHAR(50)
	UPDATE a SET a.RegionName = b.Description FROM #t a, dcRegion b WHERE LEFT(a.JobRegion, 4) = b.Id
	UPDATE #t SET RegionName2 = LEFT(RegionName, LEN(RegionName) - 1) WHERE LEN(RegionName) > 2
	UPDATE #t SET JobName = RegionName + JobName WHERE CHARINDEX(RegionName2, JobName) = 0
	UPDATE #t SET JobName = JobName + '招聘' WHERE CHARINDEX('聘', JobName) = 0

	DECLARE @t AS TABLE(Id INT, Description NVARCHAR(110))
	INSERT INTO @t SELECT DetailId, REPLACE(Description, '以上', '') FROM dcOthers WHERE Category = '招聘人数' AND Description NOT LIKE '%~%'
	INSERT INTO @t SELECT DetailId, LEFT(Description, CHARINDEX('~', Description) - 1) + '人' FROM dcOthers WHERE Category = '招聘人数' AND Description LIKE '%~%'
	UPDATE a SET NeedNumber = b.Description FROM #t a, @t b WHERE a.NeedNumber = b.Id

	UPDATE #t
	SET JobDesc = REPLACE(JobDesc, '', ''), 
		JobDemand = REPLACE(JobDemand, '', ''), 
		Brief = REPLACE(Brief, '', '')
	WHERE CHARINDEX('', JobDesc) > 0
	OR CHARINDEX('', JobDemand) > 0
	OR CHARINDEX('', Brief) > 0

	UPDATE a
	SET a.RegionDesc = b.FullName
	FROM #t a, MainDb..dcRegion b
	WHERE a.CompanyRegionId = b.Id

	UPDATE #t SET RegionDesc = '' WHERE CHARINDEX(RegionDesc, Address) > 0
	UPDATE #t
	SET Address = RIGHT(Address, LEN(Address) - 3)
	WHERE CHARINDEX(LEFT(Address, 3), RegionDesc) > 0
	AND LEN(Address) > 3 AND LEN(RegionDesc) > 0
	UPDATE #t
	SET Address = RIGHT(Address, LEN(Address) - 3)
	WHERE CHARINDEX(LEFT(Address, 3), RegionDesc) > 0
	AND LEN(Address) > 3 AND LEN(RegionDesc) > 0
	UPDATE #t
	SET Address = RIGHT(Address, LEN(Address) - 3)
	WHERE CHARINDEX(LEFT(Address, 3), RegionDesc) > 0
	AND LEN(Address) > 3 AND LEN(RegionDesc) > 0
	UPDATE #t SET Address = '' WHERE CHARINDEX(Address, RegionDesc) > 0 AND LEN(RegionDesc) > 0
	UPDATE #t SET Address = RegionDesc + Address WHERE LEN(RegionDesc) > 0

	SELECT id, jobname, JobDESC, JobDemand, jobregion, companyname, edulevel, IsDelete, 
		experiencelevel, AnnounceDate, dcSalaryID, dcjobtypeID, ShortName, Address, dcCompanySizeID, Brief, 
		EmployType, adddate, dcCompanyKindID, enddate, email, EnJobID, EnCpMainID, 
		IndustryId, SubSiteUrl, SubSiteName, NeedNumber, Welfare1, Welfare2, Welfare3, Welfare4, Welfare5, 
		Welfare6, Welfare7, Welfare8, Welfare9, Welfare10, Welfare11, Welfare12, Welfare13, Welfare14, 
		Welfare15, Welfare16, Welfare17, Welfare18, IsVip
	FROM #t ORDER BY RowNo
END
GO
/****** Object:  StoredProcedure [dbo].[ProcBaiduXmlJob51rcOutSave]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ProcBaiduXmlJob51rcOutSave]
AS
SET NOCOUNT ON
BEGIN
	IF EXISTS(SELECT 'x' FROM ShortDb..BaiduXmlJob51rcOut WHERE crDate > DATEADD(MINUTE, -480, GETDATE()))
		RETURN

	SELECT a.id, a.name jobname, a.responsibility JobDESC, a.Demand JobDemand, 
		LEFT(a.dcregionid,4) jobregion, b.name companyname, b.shortName, b.[Address], b.dcCompanySizeID, a.dcEducationID edulevel, 
		a.MinExperience experiencelevel, a.IsDelete, a.EmployType, a.adddate, 
		a.IssueDate AnnounceDate,
		a.dcSalaryID, a.dcjobtypeID, b.dcCompanyKindID, b.Brief,
		a.IssueEnd enddate, c.email, a.SecondId EnJobID, b.SecondId EnCpMainID,
		(SELECT TOP 1 dcIndustryId FROM cpindustry WITH(NOLOCK) WHERE cpindustry.cpMainID = b.ID) industryid,
		'www.51rc.com' SubSiteUrl, '伍亿人才网' SubSiteName,
		ISNULL((SELECT PinYin FROM dcRegion WITH(NOLOCK) WHERE dcRegion.id= LEFT(a.dcRegionId, 2)), 'shandong') pinyin,
		SPACE(50) RegionName, SPACE(50) RegionName2, a.Refreshdate
		--ISNULL((SELECT SubSiteUrl FROM dcsubsite WITH(NOLOCK) WHERE dcsubsite.id= LEFT(a.dcregionid, 2)),'www.qlrc.com') SubSiteUrl,
		--ISNULL((SELECT SubSiteName FROM dcsubsite WITH(NOLOCK) WHERE dcsubsite.id= LEFT(a.dcregionid, 2)),'齐鲁人才网') SubSiteName 
	INTO #t
	FROM job a WITH(NOLOCK), cpmain b WITH(NOLOCK),camain c 
	WHERE a.camainid=c.id AND a.cpmainid=b.id AND a.valid=1
	AND issueend>CONVERT(VARCHAR(10),GETDATE()+1,120) AND b.valid=1 AND b.VerifyCount > 0 
	AND LEN(RTRIM(a.name)) > 2 
	AND a.Refreshdate > CONVERT(VARCHAR(10), GETDATE() -1, 120) 
	AND LEFT(a.dcRegionId, 2) = b.dcProvinceId
	ORDER BY a.RefreshDate DESC

	UPDATE a SET a.RegionName = b.Description FROM #t a, dcRegion b WHERE LEFT(a.JobRegion, 4) = b.Id
	UPDATE #t SET RegionName2 = LEFT(RegionName, LEN(RegionName) - 1) WHERE LEN(RegionName) > 2
	UPDATE #t SET JobName = LEFT(RegionName + JobName, 50) WHERE CHARINDEX(RegionName2, JobName) = 0
	UPDATE #t SET JobName = LEFT(JobName + '招聘', 50) WHERE CHARINDEX('聘', JobName) = 0

	UPDATE #t
	SET Brief = REPLACE(REPLACE(REPLACE(REPLACE(Brief, '&nbsp;', ''), '&lt;', ''), '&gt;', ''), '&#', '')
	WHERE Brief LIKE '%&%'

	UPDATE #t SET Brief = REPLACE(Brief, '  ', '') WHERE Brief LIKE '%  %'

	TRUNCATE TABLE ShortDb..BaiduXmlJob51rcOut

	INSERT INTO ShortDb..BaiduXmlJob51rcOut
	SELECT *, GETDATE() FROM #t ORDER By RefreshDate DESC
END
GO
/****** Object:  StoredProcedure [dbo].[ProcBaiduXmlOutByAllSave]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ProcBaiduXmlOutByAllSave]
AS
BEGIN
	TRUNCATE TABLE ShortDb..BaiduXMLJobTemp
	DECLARE @MinId INT
	SELECT TOP 1 @MinId = Id FROM ShortDb..BaiduXMLJobOut WITH(NOLOCK) ORDER BY Id DESC
	INSERT INTO ShortDb..BaiduXMLJobTemp
	SELECT TOP 10000 b.dcProvinceId, a.id, a.Name JobName, a.responsibility JobDESC, a.Demand JobDemand, 
		a.dcregionid Jobregion, b.Name companyName, a.dcEducationID eduLevel, 
		a.MinExperience experienceLevel, a.IsDELETE, a.EmployType, a.adddate,
		a.IssueDate AnnounceDate,
		a.dcSalaryID, a.dcJobtypeID, b.dcCompanyKindID, ISNULL(b.ShortName, b.Name) ShortName, 
		b.Address, dcCompanySizeID, Brief, 
		a.IssueEnd enddate, c.email, a.SecondId EnJobID, b.SecondId EncpMainID, 
		(SELECT TOP 1 dcIndustryId FROM cpindustry WITH(NOLOCK) WHERE cpindustry.cpMainID = b.ID) IndustryId, 
		d.SubSiteUrl, d.SubSiteName, a.RefreshDate RDate, a.NeedNumber, a.Welfare1, 
		a.Welfare2, a.Welfare3, a.Welfare4, a.Welfare5, a.Welfare6, a.Welfare7, a.Welfare8, a.Welfare9, 
		a.Welfare10, a.Welfare11, a.Welfare12, a.Welfare13, a.Welfare14, a.Welfare15, a.Welfare16, 
		a.Welfare17, a.Welfare18, '', '', '', b.dcRegionId
	FROM Job a WITH(NOLOCK),
		cpMain b WITH(NOLOCK),
		caMain c WITH(NOLOCK),
		dcSubSite d WITH(NOLOCK)
	WHERE b.dcProvinceId = d.Id
	AND a.caMainid = c.id
	AND a.cpMainid = b.id
	AND LEN(RTRIM(a.Name)) > 1 
	AND b.IsDELETE = 0
	AND a.IsDELETE = 0
	AND b.IsLimitLogin < 9
	--AND a.Id > ISNULL(@MinId, 0)
	AND LEFT(a.dcRegionId, 2) = b.dcProvinceId
	AND a.Id NOT IN(SELECT ID FROM ShortDb..BaiduXMLJobOut WITH(NOLOCK))
	AND a.Valid = 1
	AND b.Valid = 1
	ORDER BY a.RefreshDate

	UPDATE ShortDb..BaiduXMLJobTemp
	SET Brief = REPLACE(REPLACE(REPLACE(REPLACE(Brief, '&nbsp;', ''), '&lt;', ''), '&gt;', ''), '&#', '')
	WHERE Brief LIKE '%&%'

	UPDATE ShortDb..BaiduXMLJobTemp SET Brief = REPLACE(Brief, '  ', '') WHERE Brief LIKE '%  %'

	UPDATE ShortDb..BaiduXMLJobTemp
	SET JobDesc = REPLACE(JobDesc, '', ''), 
		JobDemand = REPLACE(JobDemand, '', ''), 
		Brief = REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(Brief, '&nbsp;', ''), '  ', ''), '&lt;', ''), '&gt;', ''), '&#', ''), '', '')
	WHERE CHARINDEX('', JobDesc) > 0
	OR CHARINDEX('', JobDemand) > 0
	OR CHARINDEX('', Brief) > 0

	UPDATE a
	SET a.RegionDesc = b.FullName
	FROM ShortDb..BaiduXMLJobTemp a, MainDb..dcRegion b
	WHERE a.CompanyRegionId = b.Id

	UPDATE ShortDb..BaiduXMLJobTemp SET RegionDesc = '' WHERE CHARINDEX(RegionDesc, Address) > 0
	UPDATE ShortDb..BaiduXMLJobTemp
	SET Address = RIGHT(Address, LEN(Address) - 3)
	WHERE CHARINDEX(LEFT(Address, 3), RegionDesc) > 0
	AND LEN(Address) > 3 AND LEN(RegionDesc) > 0
	UPDATE ShortDb..BaiduXMLJobTemp
	SET Address = RIGHT(Address, LEN(Address) - 3)
	WHERE CHARINDEX(LEFT(Address, 3), RegionDesc) > 0
	AND LEN(Address) > 3 AND LEN(RegionDesc) > 0
	UPDATE ShortDb..BaiduXMLJobTemp
	SET Address = RIGHT(Address, LEN(Address) - 3)
	WHERE CHARINDEX(LEFT(Address, 3), RegionDesc) > 0
	AND LEN(Address) > 3 AND LEN(RegionDesc) > 0
	UPDATE ShortDb..BaiduXMLJobTemp SET Address = '' WHERE CHARINDEX(Address, RegionDesc) > 0 AND LEN(RegionDesc) > 0
	UPDATE ShortDb..BaiduXMLJobTemp SET Address = RegionDesc + Address WHERE LEN(RegionDesc) > 0

	UPDATE a SET a.RegionName = b.Description FROM ShortDb..BaiduXMLJobTemp a, dcRegion b WHERE LEFT(a.JobRegion, 4) = b.Id
	UPDATE ShortDb..BaiduXMLJobTemp SET RegionName2 = LEFT(RegionName, LEN(RegionName) - 1) WHERE LEN(RegionName) > 2
	UPDATE ShortDb..BaiduXMLJobTemp SET JobName = LEFT(RegionName + JobName, 50) WHERE CHARINDEX(RegionName2, JobName) = 0
	UPDATE ShortDb..BaiduXMLJobTemp SET JobName = LEFT(JobName + '招聘', 50) WHERE CHARINDEX('聘', JobName) = 0

	DECLARE @t AS TABLE(Id INT, Description NVARCHAR(110))
	INSERT INTO @t SELECT DetailId, REPLACE(Description, '以上', '') FROM dcOthers WHERE Category = '招聘人数' AND Description NOT LIKE '%~%'
	INSERT INTO @t SELECT DetailId, LEFT(Description, CHARINDEX('~', Description) - 1) + '人' FROM dcOthers WHERE Category = '招聘人数' AND Description LIKE '%~%'
	UPDATE a SET NeedNumber = b.Description FROM ShortDb..BaiduXMLJobTemp a, @t b WHERE a.NeedNumber = b.Id

	--TRUNCATE TABLE ShortDb..BaiduXMLJobOut
	DECLARE @Mr INT
	SELECT @Mr = MAX(RowNo) FROM ShortDb..BaiduXMLJobOut
	INSERT INTO ShortDb..BaiduXMLJobOut(SiteId, id, JobName, JobDESC, JobDemand, Jobregion, companyName, eduLevel, IsDELETE, 
		experienceLevel, AnnounceDate, dcSalaryID, dcJobtypeID, ShortName, Address, dcCompanySizeID, Brief, 
		EmployType, adddate, dcCompanyKindID, enddate, email, EnJobID, EncpMainID, 
		IndustryId, SubSiteUrl, SubSiteName, NeedNumber, Welfare1, Welfare2, Welfare3, Welfare4, Welfare5, 
		Welfare6, Welfare7, Welfare8, Welfare9, Welfare10, Welfare11, Welfare12, Welfare13, Welfare14, 
		Welfare15, Welfare16, Welfare17, Welfare18, crDate, RowNo)
	SELECT SiteId, id, JobName, JobDESC, JobDemand, Jobregion, companyName, eduLevel, IsDELETE, 
		experienceLevel, AnnounceDate, dcSalaryID, dcJobtypeID, ShortName, Address, dcCompanySizeID, Brief, 
		EmployType, adddate, dcCompanyKindID, enddate, email, EnJobID, EncpMainID, 
		IndustryId, SubSiteUrl, SubSiteName, NeedNumber, Welfare1, Welfare2, Welfare3, Welfare4, Welfare5, 
		Welfare6, Welfare7, Welfare8, Welfare9, Welfare10, Welfare11, Welfare12, Welfare13, Welfare14, 
		Welfare15, Welfare16, Welfare17, Welfare18, GETDATE(), @Mr + RowNo
	FROM ShortDb..BaiduXMLJobTemp
	ORDER BY RDate DESC, id DESC

	DELETE FROM ShortDb..BaiduXMLJobOut WHERE Id IN(SELECT ID FROM Job WITH(NOLOCK) WHERE Id IN(SELECT SubId FROM bsCvModify WHERE AddDate < GETDATE() - 15) AND Valid = 0)

	SELECT id INTO #t FROM ShortDb..BaiduXMLJobOut
	DELETE #t WHERE id in(SELECT id FROM maindb..Job WHERE IsDelete = 0)
	DELETE ShortDb..BaiduXMLJobOut WHERE id IN(SELECT id FROM #t)

	SELECT id INTO #c FROM MainDb..cpMain WHERE (IsDelete = 1 OR islimitlogin = 9 OR Valid = 0) 
	SELECT id INTO #j FROM MainDb..Job WHERE cpMainid IN(SELECT id FROM #c)
	DELETE ShortDb..BaiduXMLJobOut WHERE id IN(SELECT id FROM #j)

	-----------==============================
	DELETE FROM ShortDb..BaiduXMLJobOut WHERE Id IN(SELECT Id FROM Job WHERE Issueend < GETDATE() AND cpMainId IN(SELECT cpMainId FROM noshowoldjob))

	SELECT a.id INTO #vj FROM JobPublish a, cpMainPubLish b WHERE a.cpMainId = b.Id AND a.Valid = 1 AND b.Valid = 1 

	UPDATE Shortdb..BaiduXMLJobOut
	SET RowNo = Id + 80000000
	WHERE RowNo < 80000000
	AND Id IN(SELECT id FROM #vj)

	CREATE TABLE #JobOrder(id INT, RowNo INT IDENTITY(1, 1))
	INSERT INTO #JobOrder
	SELECT Id FROM Shortdb..BaiduXMLJobOut
	WHERE RowNo > 80000000
	AND Id NOT IN(SELECT id FROM #vj)

	DECLARE @MaxRowNo INT
	SELECT TOP 1 @MaxRowNo = RowNo FROM Shortdb..BaiduXMLJobOut WHERE RowNo < 80000000 ORDER BY ROwNo DESC

	IF @MaxRowNo < 70000000
	BEGIN
		UPDATE a
		SET a.RowNo = @MaxRowNo + b.RowNo
		FROM Shortdb..BaiduXMLJobOut a, #JobOrder b
		WHERE a.Id = b.Id
	END
	ELSE
	BEGIN
		UPDATE a
		SET a.RowNo = @MaxRowNo + b.RowNo
		FROM Shortdb..BaiduXMLJobOut a, #JobOrder b
		WHERE a.Id = b.Id

		TRUNCATE TABLE #JobOrder

		INSERT INTO #JobOrder
		SELECT a.id
		FROM Shortdb..BaiduXMLJobOut a, Job b
		WHERE a.RowNo < 80000000
		AND a.Id = b.Id 
		ORDER BY IssueEnd, Id Desc

		--INSERT INTO #JobOrder
		--SELECT Id FROM Shortdb..BaiduXMLJobOut WHERE RowNo < 80000000 ORDER BY ROwNo DESC

		UPDATE a
		SET a.RowNo = b.RowNo
		FROM Shortdb..BaiduXMLJobOut a, #JobOrder b
		WHERE a.Id = b.Id
	END	
/*
	CREATE TABLE #tb(JobId INT, RowNo INT IDENTITY(1, 1))
	CREATE TABLE #tb1(JobId INT, RowNo INT IDENTITY(1, 1))
	INSERT INTO #tb1
	SELECT a.Id
	FROM MainDB..Job a, MainDb..cpMain b, Shortdb..BaiduXMLJobOut c
	WHERE a.Id = c.Id
	AND a.CpMainId = b.Id
	AND a.Valid = 1
	AND b.Valid = 1
	ORDER BY a.IssueDate, a.Id

	INSERT INTO #tb
	SELECT a.Id
	FROM MainDB..Job a, MainDb..cpMain b, Shortdb..BaiduXMLJobOut c
	WHERE a.Id = c.Id
	AND a.CpMainId = b.Id
	AND a.Id NOT IN(SELECT JobId FROM #tb1)
	ORDER BY a.IssueDate, a.Id

	INSERT INTO #tb SELECT JobID FROM #tb1 ORDER BY RowNo

	UPDATE a SET a.RowNo = b.RowNo FROM Shortdb..BaiduXMLJobOut a, #tb b WHERE a.Id = b.JobId
*/
END

GO
/****** Object:  StoredProcedure [dbo].[ProcBaiduXmlOutByNewstSave]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ProcBaiduXmlOutByNewstSave]
AS
SET NOCOUNT ON
IF (DATEPART(HOUR, GETDATE()) - 7) % 4 > 0
	RETURN
BEGIN
	SELECT TOP 0 * INTO #t FROM ShortDb..BaiduXMLJobTemp

	INSERT INTO #t
	SELECT b.dcProvinceId, a.id, a.Name JobName, a.responsibility JobDESC, a.Demand JobDemand, 
		a.dcregionid Jobregion, b.Name companyName, a.dcEducationID eduLevel, 
		a.MinExperience experienceLevel, a.IsDelete, a.EmployType, a.adddate,
		a.IssueDate AnnounceDate,
		a.dcSalaryID, a.dcJobtypeID, b.dcCompanyKindID, ISNULL(b.ShortName, b.Name) ShortName, 
		b.Address, dcCompanySizeID, Brief, 
		a.IssueEnd enddate, c.email, a.SecondId EnJobID, b.SecondId EncpMainID, 
		(SELECT TOP 1 dcIndustryId FROM cpindustry WITH(NOLOCK) WHERE cpindustry.cpMainID = b.ID) IndustryId, 
		d.SubSiteUrl, d.SubSiteName, a.RefreshDate RDate, a.NeedNumber, a.Welfare1, 
		a.Welfare2, a.Welfare3, a.Welfare4, a.Welfare5, a.Welfare6, a.Welfare7, a.Welfare8, a.Welfare9, 
		a.Welfare10, a.Welfare11, a.Welfare12, a.Welfare13, a.Welfare14, a.Welfare15, a.Welfare16, 
		a.Welfare17, a.Welfare18, '', '', '', b.dcRegionId
	FROM Job a WITH(NOLOCK),
		cpMain b WITH(NOLOCK),
		caMain c WITH(NOLOCK),
		dcSubSite d WITH(NOLOCK)
	WHERE b.dcProvinceId = d.Id
	AND a.caMainid = c.id
	AND a.cpMainid = b.id
	AND LEN(RTRIM(a.Name)) > 1 
	AND b.IsDelete = 0
	AND a.IsDelete = 0
	AND b.IsLimitLogin < 9
	AND LEFT(a.dcRegionId, 2) = b.dcProvinceId
	AND (a.LastModifyDate > CONVERT(VARCHAR(10), GETDATE() - 1, 120)
		OR a.IssueEnd BETWEEN CONVERT(VARCHAR(10), GETDATE() - 1, 120) AND GETDATE() + 0.2
		OR a.IssueDate > CONVERT(VARCHAR(10), GETDATE() - 1, 120))
	ORDER BY a.Refreshdate

	UPDATE #t
	SET Brief = REPLACE(REPLACE(REPLACE(REPLACE(Brief, '&nbsp;', ''), '&lt;', ''), '&gt;', ''), '&#', '')
	WHERE Brief LIKE '%&%'

	UPDATE #t SET Brief = REPLACE(Brief, '  ', '') WHERE Brief LIKE '%  %'

	UPDATE #t
	SET JobDesc = REPLACE(JobDesc, '', ''), 
		JobDemand = REPLACE(JobDemand, '', ''), 
		Brief = REPLACE(Brief, '', '')
	WHERE CHARINDEX('', JobDesc) > 0
	OR CHARINDEX('', JobDemand) > 0
	OR CHARINDEX('', Brief) > 0

	UPDATE a
	SET a.RegionDesc = b.FullName
	FROM #t a, MainDb..dcRegion b
	WHERE a.CompanyRegionId = b.Id

	UPDATE #t SET RegionDesc = '' WHERE CHARINDEX(RegionDesc, Address) > 0
	UPDATE #t
	SET Address = RIGHT(Address, LEN(Address) - 3)
	WHERE CHARINDEX(LEFT(Address, 3), RegionDesc) > 0
	AND LEN(Address) > 3 AND LEN(RegionDesc) > 0
	UPDATE #t
	SET Address = RIGHT(Address, LEN(Address) - 3)
	WHERE CHARINDEX(LEFT(Address, 3), RegionDesc) > 0
	AND LEN(Address) > 3 AND LEN(RegionDesc) > 0
	UPDATE #t
	SET Address = RIGHT(Address, LEN(Address) - 3)
	WHERE CHARINDEX(LEFT(Address, 3), RegionDesc) > 0
	AND LEN(Address) > 3 AND LEN(RegionDesc) > 0
	UPDATE #t SET Address = '' WHERE CHARINDEX(Address, RegionDesc) > 0 AND LEN(RegionDesc) > 0
	UPDATE #t SET Address = RegionDesc + Address WHERE LEN(RegionDesc) > 0

	UPDATE a SET a.RegionName = b.Description FROM #t a, dcRegion b WHERE LEFT(a.JobRegion, 4) = b.Id
	UPDATE #t SET RegionName2 = LEFT(RegionName, LEN(RegionName) - 1) WHERE LEN(RegionName) > 2
	UPDATE #t SET JobName = LEFT(RegionName + JobName, 50) WHERE CHARINDEX(RegionName2, JobName) = 0
	UPDATE #t SET JobName = LEFT(JobName + '招聘', 50) WHERE CHARINDEX('聘', JobName) = 0

	DECLARE @t AS TABLE(Id INT, Description NVARCHAR(110))
	INSERT INTO @t SELECT DetailId, REPLACE(Description, '以上', '') FROM dcOthers WHERE Category = '招聘人数' AND Description NOT LIKE '%~%'
	INSERT INTO @t SELECT DetailId, LEFT(Description, CHARINDEX('~', Description) - 1) + '人' FROM dcOthers WHERE Category = '招聘人数' AND Description LIKE '%~%'
	UPDATE a SET NeedNumber = b.Description FROM #t a, @t b WHERE a.NeedNumber = b.Id

	UPDATE #t SET EndDate = DATEADD(MONTH, DATEDIFF(MONTH, EndDate, GETDATE()) + 3, EndDate) WHERE EndDate < CONVERT(VARCHAR(10), GETDATE() + 2, 120)
	UPDATE #t SET EndDate = DATEADD(MONTH, 3, EndDate) WHERE EndDate < CONVERT(VARCHAR(10), GETDATE() + 2, 120)
	UPDATE #t SET EndDate = DATEADD(MONTH, 3, EndDate) WHERE EndDate < CONVERT(VARCHAR(10), GETDATE() + 2, 120)
	UPDATE #t SET AnnounceDate = DATEADD(MONTH, -3, AnnounceDate) WHERE AnnounceDate > GETDATE()
	UPDATE #t SET AnnounceDate = DATEADD(MONTH, -3, AnnounceDate) WHERE AnnounceDate > GETDATE()
	UPDATE #t SET AnnounceDate = DATEADD(MONTH, -3, AnnounceDate) WHERE AnnounceDate > GETDATE()

	DELETE FROM ShortDb..BaiduXMLJobOut WHERE Id IN(SELECT ID FROM #t WITH(NOLOCK))
	DECLARE @Mr INT
	SELECT @Mr = MAX(RowNo) FROM ShortDb..BaiduXMLJobOut
	INSERT INTO ShortDb..BaiduXMLJobOut(SiteId, id, JobName, JobDESC, JobDemand, Jobregion, companyName, eduLevel, IsDelete, 
		experienceLevel, AnnounceDate, dcSalaryID, dcJobtypeID, ShortName, Address, dcCompanySizeID, Brief, 
		EmployType, adddate, dcCompanyKindID, enddate, email, EnJobID, EncpMainID, 
		IndustryId, SubSiteUrl, SubSiteName, NeedNumber, Welfare1, Welfare2, Welfare3, Welfare4, Welfare5, 
		Welfare6, Welfare7, Welfare8, Welfare9, Welfare10, Welfare11, Welfare12, Welfare13, Welfare14, 
		Welfare15, Welfare16, Welfare17, Welfare18, crDate, RowNo)
	SELECT SiteId, id, JobName, JobDESC, JobDemand, Jobregion, companyName, eduLevel, IsDelete, 
		experienceLevel, AnnounceDate, dcSalaryID, dcJobtypeID, ShortName, Address, dcCompanySizeID, Brief, 
		EmployType, adddate, dcCompanyKindID, enddate, email, EnJobID, EncpMainID, 
		IndustryId, SubSiteUrl, SubSiteName, NeedNumber, Welfare1, Welfare2, Welfare3, Welfare4, Welfare5, 
		Welfare6, Welfare7, Welfare8, Welfare9, Welfare10, Welfare11, Welfare12, Welfare13, Welfare14, 
		Welfare15, Welfare16, Welfare17, Welfare18, GETDATE(), @Mr + RowNo
	FROM #t
	ORDER BY RowNo
END

GO
/****** Object:  StoredProcedure [dbo].[ProcBaiduXmlOutByQlrcSave]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ProcBaiduXmlOutByQlrcSave]
AS
SET NOCOUNT ON
IF (DATEPART(HOUR, GETDATE()) - 7) % 4 > 0
	RETURN
BEGIN
	DECLARE @SiteId INT
	SET @SiteId = 32
	SELECT TOP 0 * INTO #t FROM ShortDb..BaiduXMLJobTemp

	DECLARE @SubSiteUrl VARCHAR(100), @SubSiteName VARCHAR(100)
	SELECT @SubSiteUrl = SubSiteUrl, @SubSiteName = SubSiteName
	FROM dcsubsite WITH(NOLOCK)
	WHERE Id = @SiteId

	INSERT INTO #t
	SELECT @SiteId, a.id, a.name jobname, a.responsibility JobDESC, a.Demand JobDemand, 
		a.dcregionid jobregion, b.name companyname, a.dcEducationID edulevel, 
		a.MinExperience experiencelevel, a.IsDelete, a.EmployType, a.adddate, 
		a.IssueDate AnnounceDate, 
		a.dcSalaryID, a.dcjobtypeID, b.dcCompanyKindID, ISNULL(b.ShortName, b.Name) ShortName, b.Address, dcCompanySizeID, Brief, 
		a.IssueEnd enddate, c.email, a.SecondId EnJobID, b.SecondId EnCpMainID, 
		(SELECT TOP 1 dcIndustryId FROM cpindustry WITH(NOLOCK) WHERE cpindustry.cpMainID = b.ID) IndustryId, 
		@SubSiteUrl SubSiteUrl, @SubSiteName SubSiteName, a.RefreshDate RDate, a.NeedNumber, a.Welfare1, 
		a.Welfare2, a.Welfare3, a.Welfare4, a.Welfare5, a.Welfare6, a.Welfare7, a.Welfare8, a.Welfare9, 
		a.Welfare10, a.Welfare11, a.Welfare12, a.Welfare13, a.Welfare14, a.Welfare15, a.Welfare16, 
		a.Welfare17, a.Welfare18, '', '', '', b.dcRegionId
	FROM job a WITH(NOLOCK), cpmain b WITH(NOLOCK), camain c 
	WHERE a.camainid = c.id AND a.cpmainid = b.id AND a.valid = 1
	AND issueend>CONVERT(VARCHAR(10), GETDATE() + 1, 120)
	AND b.valid = 1 AND b.VerifyCount > 0 
	AND b.dcprovinceid = 32
	AND LEN(RTRIM(a.name)) > 1
	AND LEFT(a.dcRegionId, 2) = b.dcProvinceId
	ORDER BY a.Refreshdate DESC
 
	UPDATE #t
	SET Brief = REPLACE(REPLACE(REPLACE(REPLACE(Brief, '&nbsp;', ''), '&lt;', ''), '&gt;', ''), '&#', '')
	WHERE Brief LIKE '%&%'

	UPDATE #t SET Brief = REPLACE(Brief, '  ', '') WHERE Brief LIKE '%  %'

	UPDATE #t
	SET JobDesc = REPLACE(JobDesc, '', ''), 
		JobDemand = REPLACE(JobDemand, '', ''), 
		Brief = REPLACE(Brief, '', '')
	WHERE CHARINDEX('', JobDesc) > 0
	OR CHARINDEX('', JobDemand) > 0
	OR CHARINDEX('', Brief) > 0

	UPDATE a
	SET a.RegionDesc = b.FullName
	FROM #t a, MainDb..dcRegion b
	WHERE a.CompanyRegionId = b.Id

	UPDATE #t SET RegionDesc = '' WHERE CHARINDEX(RegionDesc, Address) > 0
	UPDATE #t
	SET Address = RIGHT(Address, LEN(Address) - 3)
	WHERE CHARINDEX(LEFT(Address, 3), RegionDesc) > 0
	AND LEN(Address) > 3 AND LEN(RegionDesc) > 0
	UPDATE #t
	SET Address = RIGHT(Address, LEN(Address) - 3)
	WHERE CHARINDEX(LEFT(Address, 3), RegionDesc) > 0
	AND LEN(Address) > 3 AND LEN(RegionDesc) > 0
	UPDATE #t
	SET Address = RIGHT(Address, LEN(Address) - 3)
	WHERE CHARINDEX(LEFT(Address, 3), RegionDesc) > 0
	AND LEN(Address) > 3 AND LEN(RegionDesc) > 0
	UPDATE #t SET Address = '' WHERE CHARINDEX(Address, RegionDesc) > 0 AND LEN(RegionDesc) > 0
	UPDATE #t SET Address = RegionDesc + Address WHERE LEN(RegionDesc) > 0

	UPDATE a SET a.RegionName = b.Description FROM #t a, dcRegion b WHERE LEFT(a.JobRegion, 4) = b.Id
	UPDATE #t SET RegionName2 = LEFT(RegionName, LEN(RegionName) - 1) WHERE LEN(RegionName) > 2
	UPDATE #t SET JobName = LEFT(RegionName + JobName, 50) WHERE CHARINDEX(RegionName2, JobName) = 0
	UPDATE #t SET JobName = LEFT(JobName + '招聘', 50) WHERE CHARINDEX('聘', JobName) = 0

	DECLARE @t AS TABLE(Id INT, Description NVARCHAR(110))
	INSERT INTO @t SELECT DetailId, REPLACE(Description, '以上', '') FROM dcOthers WHERE Category = '招聘人数' AND Description NOT LIKE '%~%'
	INSERT INTO @t SELECT DetailId, LEFT(Description, CHARINDEX('~', Description) - 1) + '人' FROM dcOthers WHERE Category = '招聘人数' AND Description LIKE '%~%'
	UPDATE a SET NeedNumber = b.Description FROM #t a, @t b WHERE a.NeedNumber = b.Id
	
	TRUNCATE TABLE ShortDb..BaiduXMLJobQlrcOut
	INSERT INTO ShortDb..BaiduXMLJobQlrcOut(SiteId, id, jobname, JobDESC, JobDemand, jobregion, companyname, edulevel, IsDelete, 
		experiencelevel, AnnounceDate, dcSalaryID, dcjobtypeID, ShortName, Address, dcCompanySizeID, Brief, 
		EmployType, adddate, dcCompanyKindID, enddate, email, EnJobID, EnCpMainID, 
		IndustryId, SubSiteUrl, SubSiteName, NeedNumber, Welfare1, Welfare2, Welfare3, Welfare4, Welfare5, 
		Welfare6, Welfare7, Welfare8, Welfare9, Welfare10, Welfare11, Welfare12, Welfare13, Welfare14, 
		Welfare15, Welfare16, Welfare17, Welfare18, crDate)
	SELECT @SiteId, id, jobname, JobDESC, JobDemand, jobregion, companyname, edulevel, IsDelete, 
		experiencelevel, AnnounceDate, dcSalaryID, dcjobtypeID, ShortName, Address, dcCompanySizeID, Brief, 
		EmployType, adddate, dcCompanyKindID, enddate, email, EnJobID, EnCpMainID, 
		IndustryId, SubSiteUrl, SubSiteName, NeedNumber, Welfare1, Welfare2, Welfare3, Welfare4, Welfare5, 
		Welfare6, Welfare7, Welfare8, Welfare9, Welfare10, Welfare11, Welfare12, Welfare13, Welfare14, 
		Welfare15, Welfare16, Welfare17, Welfare18, GETDATE()
	FROM #t 
	ORDER BY RDate DESC, Id DESC
END

GO
/****** Object:  StoredProcedure [dbo].[ProcBaiduXmlOutSave1026]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ProcBaiduXmlOutSave1026]
(
	@SiteId INT
)
AS
RETURN
SET NOCOUNT ON
BEGIN
	DECLARE @crDate DATETIME

	CREATE TABLE #t
	(
		RowNo INT IDENTITY(1, 1), 
		[Id] [int] NOT NULL, 
		[JobName] [nvarchar](80) NOT NULL, 
		[JobDESC] [varchar](max) NOT NULL, 
		[JobDemand] [varchar](max) NOT NULL, 
		[JobRegion] [varchar](6) NULL, 
		[CompanyName] [varchar](100) NOT NULL, 
		[EduLevel] [tinyint] NOT NULL, 
		[IsDelete] [bit] NOT NULL, 
		[ExperienceLevel] [tinyint] NOT NULL, 
		[Announcedate] [datetime] NOT NULL, 
		[dcSalaryID] [tinyint] NOT NULL, 
		[dcJobtypeID] [smallint] NOT NULL, 
		[ShortName] [varchar](40) NULL, 
		[Address] [nvarchar](100) NULL, 
		[dcCompanySizeID] [tinyint] NULL, 
		[Brief] [varchar](6000) NULL, 
		[EmployType] [tinyint] NOT NULL, 
		[AddDate] [smalldatetime] NOT NULL, 
		[dcCompanyKindID] [smallint] NULL, 
		[EndDate] [smalldatetime] NULL, 
		[Email] [varchar](50) NOT NULL, 
		[EnJobID] [varchar](12) NULL, 
		[EnCpMainID] [varchar](10) NULL, 
		[IndustryId] [smallint] NULL, 
		[SubSiteUrl] [varchar](50) NOT NULL, 
		[SubSiteName] [varchar](50) NOT NULL, 
		NeedNumber VARCHAR(10), 
		[Welfare1] [bit] NULL, 
		[Welfare2] [bit] NULL, 
		[Welfare3] [bit] NULL, 
		[Welfare4] [bit] NULL, 
		[Welfare5] [bit] NULL, 
		[Welfare6] [bit] NULL, 
		[Welfare7] [bit] NULL, 
		[Welfare8] [bit] NULL, 
		[Welfare9] [bit] NULL, 
		[Welfare10] [bit] NULL, 
		[Welfare11] [bit] NULL, 
		[Welfare12] [bit] NULL, 
		[Welfare13] [bit] NULL, 
		[Welfare14] [bit] NULL, 
		[Welfare15] [bit] NULL, 
		[Welfare16] [bit] NULL, 
		[Welfare17] [bit] NULL, 
		[Welfare18] [bit] NULL, 
		RegionDesc NVARCHAR(50)
	)

	DECLARE @SubSiteUrl VARCHAR(100), @SubSiteName VARCHAR(100)
	SELECT @SubSiteUrl = SubSiteUrl, @SubSiteName = SubSiteName
	FROM dcsubsite WITH(NOLOCK)
	WHERE Id = @SiteId

	TRUNCATE TABLE ShortDb..BaiduXMLJobTemp
	IF @SiteId = 32
		INSERT INTO ShortDb..BaiduXMLJobTemp
		SELECT @SiteId, a.id, a.name jobname, a.responsibility JobDESC, a.Demand JobDemand, 
			a.dcregionid jobregion, b.name companyname, a.dcEducationID edulevel, 
			a.MinExperience experiencelevel, a.IsDelete, a.EmployType, a.adddate,
			a.IssueDate AnnounceDate, 
			a.dcSalaryID, a.dcjobtypeID, b.dcCompanyKindID, ISNULL(b.ShortName, b.Name) ShortName, b.Address, dcCompanySizeID, Brief, 
			a.IssueEnd enddate, c.email, a.SecondId EnJobID, b.SecondId EnCpMainID, 
			(SELECT TOP 1 dcIndustryId FROM cpindustry WITH(NOLOCK) WHERE cpindustry.cpMainID = b.ID) IndustryId, 
			@SubSiteUrl SubSiteUrl, @SubSiteName SubSiteName, a.RefreshDate RDate, a.NeedNumber, a.Welfare1, 
			a.Welfare2, a.Welfare3, a.Welfare4, a.Welfare5, a.Welfare6, a.Welfare7, a.Welfare8, a.Welfare9, 
			a.Welfare10, a.Welfare11, a.Welfare12, a.Welfare13, a.Welfare14, a.Welfare15, a.Welfare16, 
			a.Welfare17, a.Welfare18, '', '', ''
		FROM job a WITH(NOLOCK), cpmain b WITH(NOLOCK), camain c 
		WHERE a.camainid = c.id AND a.cpmainid = b.id AND a.valid = 1
		AND issueend>CONVERT(VARCHAR(10), GETDATE()+1, 120)
		AND b.valid = 1 AND b.VerifyCount > 0 
		AND b.dcprovinceid = @SiteId
		AND LEN(RTRIM(a.name)) > 1 
		AND a.dcRegionId LIKE LTRIM(STR(@SiteId)) + '%'
		--AND a.Refreshdate>CONVERT(VARCHAR(10), GETDATE() - 1, 120) 
		ORDER BY a.Refreshdate DESC
	ELSE
		INSERT INTO ShortDb..BaiduXMLJobTemp
		SELECT @SiteId, a.id, a.name jobname, a.responsibility JobDESC, a.Demand JobDemand, 
			a.dcregionid jobregion, b.name companyname, a.dcEducationID edulevel, 
			a.MinExperience experiencelevel, a.IsDelete, a.EmployType, a.adddate, 
			a.IssueDate AnnounceDate, 
			a.dcSalaryID, a.dcjobtypeID, b.dcCompanyKindID, ISNULL(b.ShortName, b.Name) ShortName, b.Address, dcCompanySizeID, Brief, 
			a.IssueEnd enddate, c.email, a.SecondId EnJobID, b.SecondId EnCpMainID, 
			(SELECT TOP 1 dcIndustryId FROM cpindustry WITH(NOLOCK) WHERE cpindustry.cpMainID = b.ID) IndustryId, 
			@SubSiteUrl SubSiteUrl, @SubSiteName SubSiteName, a.RefreshDate RDate, a.NeedNumber, a.Welfare1, 
			a.Welfare2, a.Welfare3, a.Welfare4, a.Welfare5, a.Welfare6, a.Welfare7, a.Welfare8, a.Welfare9, 
			a.Welfare10, a.Welfare11, a.Welfare12, a.Welfare13, a.Welfare14, a.Welfare15, a.Welfare16, 
			a.Welfare17, a.Welfare18, '', '', ''
		FROM job a WITH(NOLOCK), cpmain b WITH(NOLOCK), camain c 
		WHERE a.camainid = c.id
		AND a.cpmainid = b.id
		AND b.dcprovinceid = @SiteId
		AND LEN(RTRIM(a.name)) > 1 
		AND a.dcRegionId LIKE LTRIM(STR(@SiteId)) + '%'
		--AND a.Refreshdate>CONVERT(VARCHAR(10), GETDATE() - 1, 120) 
		ORDER BY a.Refreshdate DESC

	UPDATE ShortDb..BaiduXMLJobTemp
	SET Brief = REPLACE(REPLACE(REPLACE(REPLACE(Brief, '&nbsp;', ''), '&lt;', ''), '&gt;', ''), '&#', '')
	WHERE Brief LIKE '%&%'

	UPDATE ShortDb..BaiduXMLJobTemp SET Brief = REPLACE(Brief, '  ', '') WHERE Brief LIKE '%  %'

	UPDATE ShortDb..BaiduXMLJobTemp
	SET JobDesc = REPLACE(JobDesc, '', ''), 
		JobDemand = REPLACE(JobDemand, '', ''), 
		Brief = REPLACE(Brief, '', '')
	WHERE CHARINDEX('', JobDesc) > 0
	OR CHARINDEX('', JobDemand) > 0
	OR CHARINDEX('', Brief) > 0

	UPDATE a
	SET a.RegionDesc = b.FullName
	FROM ShortDb..BaiduXMLJobTemp a, MainDb..dcRegion b
	WHERE a.JobREgion = b.Id

	UPDATE ShortDb..BaiduXMLJobTemp SET RegionDesc = '' WHERE CHARINDEX(RegionDesc, Address) > 0
	UPDATE ShortDb..BaiduXMLJobTemp
	SET Address = RIGHT(Address, LEN(Address) - 3)
	WHERE CHARINDEX(LEFT(Address, 3), RegionDesc) > 0
	AND LEN(Address) > 3 AND LEN(RegionDesc) > 0
	UPDATE ShortDb..BaiduXMLJobTemp
	SET Address = RIGHT(Address, LEN(Address) - 3)
	WHERE CHARINDEX(LEFT(Address, 3), RegionDesc) > 0
	AND LEN(Address) > 3 AND LEN(RegionDesc) > 0
	UPDATE ShortDb..BaiduXMLJobTemp
	SET Address = RIGHT(Address, LEN(Address) - 3)
	WHERE CHARINDEX(LEFT(Address, 3), RegionDesc) > 0
	AND LEN(Address) > 3 AND LEN(RegionDesc) > 0
	UPDATE ShortDb..BaiduXMLJobTemp SET Address = '' WHERE CHARINDEX(Address, RegionDesc) > 0 AND LEN(RegionDesc) > 0
	UPDATE ShortDb..BaiduXMLJobTemp SET Address = RegionDesc + Address WHERE LEN(RegionDesc) > 0

	UPDATE a SET a.RegionName = b.Description FROM ShortDb..BaiduXMLJobTemp a, dcRegion b WHERE LEFT(a.JobRegion, 4) = b.Id
	UPDATE ShortDb..BaiduXMLJobTemp SET RegionName2 = LEFT(RegionName, LEN(RegionName) - 1) WHERE LEN(RegionName) > 2
	UPDATE ShortDb..BaiduXMLJobTemp SET JobName = LEFT(RegionName + JobName, 50) WHERE CHARINDEX(RegionName2, JobName) = 0
	UPDATE ShortDb..BaiduXMLJobTemp SET JobName = LEFT(JobName + '招聘', 50) WHERE CHARINDEX('聘', JobName) = 0

	DECLARE @t AS TABLE(Id INT, Description NVARCHAR(110))
	INSERT INTO @t SELECT DetailId, REPLACE(Description, '以上', '') FROM dcOthers WHERE Category = '招聘人数' AND Description NOT LIKE '%~%'
	INSERT INTO @t SELECT DetailId, LEFT(Description, CHARINDEX('~', Description) - 1) + '人' FROM dcOthers WHERE Category = '招聘人数' AND Description LIKE '%~%'
	UPDATE a SET NeedNumber = b.Description FROM ShortDb..BaiduXMLJobTemp a, @t b WHERE a.NeedNumber = b.Id
			
	INSERT INTO #t
	SELECT id, jobname, JobDESC, JobDemand, jobregion, companyname, edulevel, IsDelete, 
		experiencelevel, AnnounceDate, dcSalaryID, dcjobtypeID, ShortName, Address, dcCompanySizeID, Brief, 
		EmployType, adddate, dcCompanyKindID, enddate, email, EnJobID, EnCpMainID, 
		IndustryId, SubSiteUrl, SubSiteName, NeedNumber, Welfare1, Welfare2, Welfare3, Welfare4, Welfare5, 
		Welfare6, Welfare7, Welfare8, Welfare9, Welfare10, Welfare11, Welfare12, Welfare13, Welfare14, 
		Welfare15, Welfare16, Welfare17, Welfare18, ''
	FROM ShortDb..BaiduXMLJobTemp ORDER BY RDate DESC, id

	IF (SELECT COUNT(*) FROM #t) % 500 = 0
		DELETE #t WHERE ID IN(SELECT TOP 2 ID FROM #t ORDER BY Announcedate)

	DELETE ShortDb..BaiduXMLJobOut WHERE SiteId = @SiteId
	INSERT INTO ShortDb..BaiduXMLJobOut(SiteId, id, jobname, JobDESC, JobDemand, jobregion, companyname, edulevel, IsDelete, 
		experiencelevel, AnnounceDate, dcSalaryID, dcjobtypeID, ShortName, Address, dcCompanySizeID, Brief, 
		EmployType, adddate, dcCompanyKindID, enddate, email, EnJobID, EnCpMainID, 
		IndustryId, SubSiteUrl, SubSiteName, NeedNumber, Welfare1, Welfare2, Welfare3, Welfare4, Welfare5, 
		Welfare6, Welfare7, Welfare8, Welfare9, Welfare10, Welfare11, Welfare12, Welfare13, Welfare14, 
		Welfare15, Welfare16, Welfare17, Welfare18, crDate)
	SELECT @SiteId, id, jobname, JobDESC, JobDemand, jobregion, companyname, edulevel, IsDelete, 
		experiencelevel, AnnounceDate, dcSalaryID, dcjobtypeID, ShortName, Address, dcCompanySizeID, Brief, 
		EmployType, adddate, dcCompanyKindID, enddate, email, EnJobID, EnCpMainID, 
		IndustryId, SubSiteUrl, SubSiteName, NeedNumber, Welfare1, Welfare2, Welfare3, Welfare4, Welfare5, 
		Welfare6, Welfare7, Welfare8, Welfare9, Welfare10, Welfare11, Welfare12, Welfare13, Welfare14, 
		Welfare15, Welfare16, Welfare17, Welfare18, GETDATE()
	FROM #t 
	ORDER BY RowNo
END

GO
/****** Object:  StoredProcedure [dbo].[ProcBaiduXmlRunLogBySuccesssUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ProcBaiduXmlRunLogBySuccesssUpdate]
(
	@ID INT
)
AS
SET NOCOUNT ON
BEGIN
	IF (SELECT CurrentStatus FROM LogDb..BaiduXmlRunLog WHERE Id = @Id) < 2
		UPDATE LogDb..BaiduXmlRunLog
		SET CurrentStatus = 1,
			BeginJobId = EndJobId
		WHERE Id = @Id
	ELSE
		UPDATE LogDb..BaiduXmlRunLog
		SET CurrentStatus = 10,
			BeginJobId = EndJobId
		WHERE Id = @Id
END
GO
/****** Object:  StoredProcedure [dbo].[ProcBaiduXmlSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ProcBaiduXmlSelect]
(
	@SiteId INT
)
AS
SET NOCOUNT ON
BEGIN
	IF @SiteId = 32
	BEGIN
		SELECT id, jobname, JobDESC, JobDemand, jobregion, companyname, edulevel, IsDelete,
			experiencelevel, AnnounceDate, dcSalaryID, dcjobtypeID, ShortName, Address, dcCompanySizeID, Brief,
			EmployType, adddate, dcCompanyKindID, enddate, email, EnJobID, EnCpMainID,
			IndustryId, SubSiteUrl, SubSiteName, NeedNumber, Welfare1, Welfare2, Welfare3, Welfare4, Welfare5,
			Welfare6, Welfare7, Welfare8, Welfare9, Welfare10, Welfare11, Welfare12, Welfare13, Welfare14,
			Welfare15, Welfare16, Welfare17, Welfare18
		FROM ShortDb..BaiduXMLJobQlrcOut WITH(NOLOCK)
		WHERE SiteId = 32
		ORDER BY RowNo

		RETURN
	END
	IF EXISTS(SELECT 'x' FROM ShortDb..BaiduXMLJobOut WHERE SiteId = @SiteID AND crDate > GETDATE() - 1)
	BEGIN
		SELECT id, jobname, JobDESC, JobDemand, jobregion, companyname, edulevel, IsDelete,
			experiencelevel, AnnounceDate, dcSalaryID, dcjobtypeID, ShortName, Address, dcCompanySizeID, Brief,
			EmployType, adddate, dcCompanyKindID, CASE WHEN EndDate < GETDATE() THEN GETDATE() + 10 ELSE EndDate END enddate, email, EnJobID, EnCpMainID,
			IndustryId, SubSiteUrl, SubSiteName, NeedNumber, Welfare1, Welfare2, Welfare3, Welfare4, Welfare5,
			Welfare6, Welfare7, Welfare8, Welfare9, Welfare10, Welfare11, Welfare12, Welfare13, Welfare14,
			Welfare15, Welfare16, Welfare17, Welfare18
		FROM ShortDb..BaiduXMLJobOut WITH(NOLOCK)
		WHERE SiteId = @SiteId
		ORDER BY RowNo

		RETURN
	END
	
	CREATE TABLE #t
	(
		RowNo INT IDENTITY(1, 1),
		[Id] [int] NOT NULL,
		[JobName] [nvarchar](80) NOT NULL,
		[JobDESC] [varchar](max) NOT NULL,
		[JobDemand] [varchar](max) NOT NULL,
		[JobRegion] [varchar](6) NULL,
		[CompanyName] [varchar](100) NOT NULL,
		[EduLevel] [tinyint] NOT NULL,
		[IsDelete] [bit] NOT NULL,
		[ExperienceLevel] [tinyint] NOT NULL,
		[Announcedate] [datetime] NOT NULL,
		[dcSalaryID] [tinyint] NOT NULL,
		[dcJobtypeID] [smallint] NOT NULL,
		[ShortName] [varchar](40) NULL,
		[Address] [nvarchar](100) NULL,
		[dcCompanySizeID] [tinyint] NULL,
		[Brief] [varchar](6000) NULL,
		[EmployType] [tinyint] NOT NULL,
		[AddDate] [smalldatetime] NOT NULL,
		[dcCompanyKindID] [smallint] NULL,
		[EndDate] [smalldatetime] NULL,
		[Email] [varchar](50) NOT NULL,
		[EnJobID] [varchar](12) NULL,
		[EnCpMainID] [varchar](10) NULL,
		[IndustryId] [smallint] NULL,
		[SubSiteUrl] [varchar](50) NOT NULL,
		[SubSiteName] [varchar](50) NOT NULL,
		NeedNumber VARCHAR(10),
		[Welfare1] [bit] NULL,
		[Welfare2] [bit] NULL,
		[Welfare3] [bit] NULL,
		[Welfare4] [bit] NULL,
		[Welfare5] [bit] NULL,
		[Welfare6] [bit] NULL,
		[Welfare7] [bit] NULL,
		[Welfare8] [bit] NULL,
		[Welfare9] [bit] NULL,
		[Welfare10] [bit] NULL,
		[Welfare11] [bit] NULL,
		[Welfare12] [bit] NULL,
		[Welfare13] [bit] NULL,
		[Welfare14] [bit] NULL,
		[Welfare15] [bit] NULL,
		[Welfare16] [bit] NULL,
		[Welfare17] [bit] NULL,
		[Welfare18] [bit] NULL,
		RegionDesc NVARCHAR(50)
	)

	DECLARE @SubSiteUrl VARCHAR(100), @SubSiteName VARCHAR(100)
	SELECT @SubSiteUrl = SubSiteUrl, @SubSiteName = SubSiteName
	FROM dcsubsite WITH(NOLOCK)
	WHERE Id = LEFT(@SiteId, 2)

	IF @SiteId > 99
		INSERT INTO #t
		SELECT a.Id, a.Name JobName, a.Responsibility JobDESC, a.Demand JobDemand,
			a.dcRegionId JobRegion, b.Name CompanyName, a.dcEducationID EduLevel, a.IsDelete,
			a.MinExperience ExperienceLevel, a.RefreshDate Announcedate,
			a.dcSalaryID, a.dcJobtypeID, ISNULL(b.ShortName, b.Name) ShortName, b.Address, dcCompanySizeID, Brief,
			a.EmployType, a.AddDate, b.dcCompanyKindID, a.IssueEnd EndDate, c.Email, a.SecondId EnJobID, b.SecondId EnCpMainID,
			(SELECT TOP 1 dcIndustryId FROM cpIndustry WITH(NOLOCK) WHERE cpIndustry.cpMainID = b.ID) IndustryId, 
			@SubSiteUrl SubSiteUrl, @SubSiteName SubSiteName, a.NeedNumber, a.Welfare1, a.Welfare2, a.Welfare3, a.Welfare4,
			a.Welfare5, a.Welfare6, a.Welfare7, a.Welfare8, a.Welfare9, a.Welfare10, a.Welfare11, a.Welfare12, a.Welfare13,
			a.Welfare14, a.Welfare15, a.Welfare16, a.Welfare17, a.Welfare18, ''
		FROM job a WITH(NOLOCK),cpmain b WITH(NOLOCK),camain c WITH(NOLOCK) 
		WHERE c.Id = a.caMainId AND a.cpMainId = b.Id 
		AND a.Valid = 1 AND b.Valid = 1 
		AND a.cpMainId NOT IN(select distinct cpMainId from  noshowoldjob WITH(NOLOCK) )--harry2016-11-29
		AND IssueEnd > CONVERT(VARCHAR(10), GETDATE() + 1, 120) AND b.VerifyCount > 0 
		--AND (b.dcSubsiteId = @SiteId OR b.dcRegionId = @SiteId) 
		AND a.dcRegionId LIKE LTRIM(STR(@SiteId)) + '%'
		AND LEN(RTRIM(a.Name)) > 1 
		AND a.Refreshdate > CONVERT(VARCHAR(10), GETDATE() - 1, 120) 
		ORDER BY a.RefreshDate DESC
	ELSE
	BEGIN
		IF @SiteId <> 32
		BEGIN
			INSERT INTO #t
			SELECT a.id, a.name jobname, a.responsibility JobDESC, a.Demand JobDemand, 
				a.dcregionid jobregion, b.name companyname, a.dcEducationID edulevel, a.IsDelete,
				a.MinExperience experiencelevel, a.RefreshDate announcedate,
				a.dcSalaryID, a.dcjobtypeID, ISNULL(b.ShortName, b.Name) ShortName, b.Address, dcCompanySizeID, Brief,
				a.EmployType, a.adddate, b.dcCompanyKindID, a.IssueEnd enddate, c.email, a.SecondId EnJobID, b.SecondId EnCpMainID,
				(SELECT TOP 1 dcIndustryId FROM cpindustry WITH(NOLOCK) WHERE cpindustry.cpMainID = b.ID) IndustryId, 
				@SubSiteUrl SubSiteUrl, @SubSiteName SubSiteName, a.NeedNumber, a.Welfare1, a.Welfare2, a.Welfare3, a.Welfare4,
				a.Welfare5, a.Welfare6, a.Welfare7, a.Welfare8, a.Welfare9, a.Welfare10, a.Welfare11, a.Welfare12, a.Welfare13,
				a.Welfare14, a.Welfare15, a.Welfare16, a.Welfare17, a.Welfare18, ''
			FROM job a WITH(NOLOCK),cpmain b WITH(NOLOCK),camain c 
			WHERE a.camainid=c.id AND a.cpmainid=b.id 
			 AND a.valid=1--harry2016-11-29
			 AND issueend>CONVERT(VARCHAR(10),GETDATE()+1,120)--harry2016-11-29
			 AND b.valid=1 AND b.VerifyCount > 0 --harry2016-11-29
			AND a.cpMainId NOT IN(select distinct cpMainId from  noshowoldjob WITH(NOLOCK) )--harry2016-11-29
			AND b.dcprovinceid = @SiteId AND LEN(RTRIM(a.name)) > 1
			AND a.dcRegionId LIKE LTRIM(STR(@SiteId)) + '%'
			--AND a.Refreshdate>CONVERT(VARCHAR(10), GETDATE()-1,120) 
			ORDER BY a.RefreshDate DESC
		END
	END

	ALTER TABLE #t ADD RegionName VARCHAR(50)
	ALTER TABLE #t ADD RegionName2 VARCHAR(50)
	UPDATE a SET a.RegionName = b.Description FROM #t a, dcRegion b WHERE LEFT(a.JobRegion, 4) = b.Id
	UPDATE #t SET RegionName2 = LEFT(RegionName, LEN(RegionName) - 1) WHERE LEN(RegionName) > 2
	UPDATE #t SET JobName = RegionName + JobName WHERE CHARINDEX(RegionName2, JobName) = 0
	UPDATE #t SET JobName = JobName + '招聘' WHERE CHARINDEX('聘', JobName) = 0

	DECLARE @t AS TABLE(Id INT, Description NVARCHAR(110))
	INSERT INTO @t SELECT DetailId, REPLACE(Description, '以上', '') FROM dcOthers WHERE Category = '招聘人数' AND Description NOT LIKE '%~%'
	INSERT INTO @t SELECT DetailId, LEFT(Description, CHARINDEX('~', Description) - 1) + '人' FROM dcOthers WHERE Category = '招聘人数' AND Description LIKE '%~%'
	UPDATE a SET NeedNumber = b.Description FROM #t a, @t b WHERE a.NeedNumber = b.Id

	UPDATE #t
	SET JobDesc = REPLACE(JobDesc, '',''),
		JobDemand = REPLACE(JobDemand, '',''),
		Brief = REPLACE(Brief, '','')
	WHERE CHARINDEX('', JobDesc) > 0
	OR CHARINDEX('', JobDemand) > 0
	OR CHARINDEX('', Brief) > 0

	UPDATE a
	SET a.RegionDesc = b.FullName
	FROM #t a, MainDb..dcRegion b
	WHERE a.JobREgion = b.Id

	UPDATE #t SET RegionDesc = '' WHERE CHARINDEX(RegionDesc, Address) > 0
	UPDATE #t
	SET Address = RIGHT(Address, LEN(Address) - 3)
	WHERE CHARINDEX(LEFT(Address, 3), RegionDesc) > 0
	AND LEN(Address) > 3 AND LEN(RegionDesc) > 0
	UPDATE #t
	SET Address = RIGHT(Address, LEN(Address) - 3)
	WHERE CHARINDEX(LEFT(Address, 3), RegionDesc) > 0
	AND LEN(Address) > 3 AND LEN(RegionDesc) > 0
	UPDATE #t
	SET Address = RIGHT(Address, LEN(Address) - 3)
	WHERE CHARINDEX(LEFT(Address, 3), RegionDesc) > 0
	AND LEN(Address) > 3 AND LEN(RegionDesc) > 0
	UPDATE #t SET Address = '' WHERE CHARINDEX(Address, RegionDesc) > 0 AND LEN(RegionDesc) > 0
	UPDATE #t SET Address = RegionDesc + Address WHERE LEN(RegionDesc) > 0

	SELECT id, jobname, JobDESC, JobDemand, jobregion, companyname, edulevel, IsDelete,
		experiencelevel, AnnounceDate, dcSalaryID, dcjobtypeID, ShortName, Address, dcCompanySizeID, Brief,
		EmployType, adddate, dcCompanyKindID, CASE WHEN EndDate < GETDATE() THEN GETDATE() + 10 ELSE EndDate END enddate, email, EnJobID, EnCpMainID,
		IndustryId, SubSiteUrl, SubSiteName, NeedNumber, Welfare1, Welfare2, Welfare3, Welfare4, Welfare5,
		Welfare6, Welfare7, Welfare8, Welfare9, Welfare10, Welfare11, Welfare12, Welfare13, Welfare14,
		Welfare15, Welfare16, Welfare17, Welfare18
	FROM #t ORDER BY RowNo
END
GO
/****** Object:  StoredProcedure [dbo].[ProcBaiduZhidaoProcess]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ProcBaiduZhidaoProcess]
AS
BEGIN
	UPDATE Marketdb..BaiduZhidaoAnswer SET AnswerKeyWord='伍亿人才网' WHERE CHARINDEX('伍亿人才网',Answer)>0 AND CheckDate>CONVERT(VARCHAR(10),GETDATE(),120)
	UPDATE Marketdb..BaiduZhidaoAnswer SET IsLink=1 WHERE CHARINDEX('www.51rc.com',Lower(Answer))>0 AND CheckDate>CONVERT(VARCHAR(10),GETDATE(),120)

	UPDATE a SET AnswerKeyWord=b.SubSiteName FROM Marketdb..BaiduZhidaoAnswer a,(
	SELECT (SELECT TOP 1 SubSiteName FROM dcSubSite WHERE CHARINDEX(SubSiteName,f.Answer)>0 AND IsMainSite=1) SubSiteName,ID 
	FROM Marketdb..BaiduZhidaoAnswer f WHERE EXISTS(SELECT 'x' FROM dcSubSite b WHERE CHARINDEX(SubSiteName ,f.Answer)>0 AND IsMainSite=1)
	) b
	WHERE a.ID=b.ID AND CheckDate>CONVERT(VARCHAR(10),GETDATE(),120)
	
	UPDATE Marketdb..BaiduZhidaoAnswer SET IsValid=0 WHERE LEN(ANSWER)<10 AND CheckDate>CONVERT(VARCHAR(10),GETDATE(),120)

	UPDATE a SET IsLink=1 FROM Marketdb..BaiduZhidaoAnswer a,(
	SELECT (SELECT TOP 1 Replace(SubSiteUrl,'www.','') FROM dcSubSite WHERE CHARINDEX(Replace(SubSiteUrl,'www.',''),f.Answer)>0 AND IsMainSite=1) ProvinceDomain,ID 
	FROM Marketdb..BaiduZhidaoAnswer f WHERE EXISTS(SELECT 'x' FROM dcSubSite b WHERE CHARINDEX(Replace(SubSiteUrl,'www.','') ,f.Answer)>0)
	) b
	WHERE a.ID=b.ID AND CheckDate>CONVERT(VARCHAR(10),GETDATE(),120)

	UPDATE Marketdb..BaiduZhidaoAnswer SET IsValid=0 WHERE AnswerKeyWord IS NULL AND CheckDate>CONVERT(VARCHAR(10),GETDATE(),120)

	UPDATE a SET IsValid=0 FROM Marketdb..BaiduZhidaoAnswer a,dcProvince b WHERE a.dcProvinceID=b.ID AND a.AnswerKeyWord<>b.WebSiteName
	AND CheckDate>CONVERT(VARCHAR(10),GETDATE(),120) AND a.AnswerKeyWord<>'伍亿人才网' AND NOT EXISTS(
		SELECT 'x' FROM dcSubSite WHERE IsMainSite=1 AND a.dcProvinceID=dcSubSite.ProvinceID AND a.AnswerKeyWord=dcSubSite.SubSiteName
	)

	UPDATE Marketdb..BaiduZhidaoAnswer SET IsValid=0 WHERE
	(SELECT Type FROM WorkDate WITH(NOLOCK) WHERE WorkDate = CONVERT(VARCHAR(8), AnswerDate, 112))=1 
	AND AnswerDate>CONVERT(VARCHAR(10), AnswerDate, 120)+' 7:00' AND AnswerDate<CONVERT(VARCHAR(10), AnswerDate, 120)+' 18:00'
	AND CheckDate>CONVERT(VARCHAR(10),GETDATE(),120)
END














GO
/****** Object:  StoredProcedure [dbo].[ProcBatchSms]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ProcBatchSms]
AS
BEGIN
	BEGIN TRY
		DROP Table a_00
	END TRY
	BEGIN CATCH
	END CATCH
	BEGIN TRY
		DROP Table A_01
	END TRY
	BEGIN CATCH
	END CATCH
	BEGIN TRY
		DROP Table A_02
	END TRY
	BEGIN CATCH
	END CATCH
	BEGIN TRY
		DROP Table A_03
	END TRY
	BEGIN CATCH
	END CATCH
	--个人：年前一个月注册且年后没登陆。（北京、上海、山东）
	--尊敬的会员，3月5日xxx人才x元宵节找工作送福利，多名就业导师为您求职答疑解惑，期待您的登录www.xxxxrc.com
	select DISTINCT dcProvinceId, space(50) SiteName, space(50) SiteUrl, Mobile, space(300) Msg, 0 Status
	INTO a_00
	from pamain
	where id between 25572640 and 25629133
	and mobile like '1%'
	and lastlogindate < '2015-2-18'
	and dcprovinceid in(10,30,32)
	delete a_00 where mobile in(select mobile from paMain where lastlogindate > '2015-2-18')
	INSERT INTO a_00 select 10, '', '', '13455496132', '', 0

	--单位：1个月内即将到期的付费会员
	--尊敬的会员，3月5日xxx人才x元宵节嗨聊全场，多种活动期待您的参与，www.xxxxrc.com
	select id cpMainId, id camainid, dcProvinceId, space(50) SiteName, space(50) SiteUrl, space(11) Mobile, space(300) Msg, 0 Status
	into A_01
	from cpmain 
	where membertype=3 
	and id not in(select cpmainid from caorder where enddate > getdate()+30 and ordertype=8 and isdeleted=0 and opendate > '')
	and dcprovinceid in(10,30,32)
	INSERT into A_01 SELECT 371108, 371108, 32,'','','','',0
	--单位：年后查看过资费标准的免费会员 5100
	--drop table A_02
	select DISTINCT caMainId cpMainId, caMainId, 999 dcProvinceId, space(50) SiteName, space(50) SiteUrl, space(11) Mobile, space(300) Msg
	into A_02
	from cafeepageviewlog 
	where adddate >'2015-2-18' 
	UPDATE A_01 SET caMainId = 0
	UPDATE A_02 SET cpMainId = 0
	UPDATE A_02 SET cpMainId = (SELECT cpMainId FROM caMain WHERE caMain.ID = A_02.caMainId)
	INSERT A_01(cpMainID, caMainId, dcProvinceId, status) SELECT DISTINCT cpMainID, 0, 0, 0 FROM A_02 WHERE cpMainId NOT IN(SELECT CpMainID FROM A_01) AND cpMainId > 0
	UPDATE a SET a.dcProvinceID = b.dcProvinceId FROM A_01 a, cpMain b WHERE a.cpMainId = b.Id
	UPDATE a SET a.caMainId = b.Id,
		a.Mobile = b.Mobile
	FROM A_01 a, caMain b
	WHERE b.AccountType = 1 AND a.cpMainId = b.cpMainId
	DELETE A_01 WHERE CaMainId = 0
	DELETE A_01 WHERE Mobile NOT LIKE '1%'
	DELETE A_01 WHERE LEN(Mobile) <> 11
	DELETE A_01 WHERE Mobile IS NULL
	DELETE A_01 WHERE Mobile = '13000000000'
	DELETE A_01 WHERE dcProvinceId NOT IN(10, 30, 32)

	UPDATE a SET a.SiteName = b.WebSiteName, a.SiteUrl = 'www.' + b.ProvinceDomain
	FROM A_01 a, dcProvince b
	WHERE a.dcProvinceID = b.Id

	UPDATE a SET a.SiteName = b.WebSiteName, a.SiteUrl = 'www.' + b.ProvinceDomain
	FROM a_00 a, dcProvince b
	WHERE a.dcProvinceID = b.Id

	UPDATE a_00 SET Msg = '尊敬的会员，3月5日' + SiteName + '元宵节找工作送福利，多名就业导师为您求职答疑解惑，期待您的登录' + SiteUrl
	UPDATE A_01 set Msg = '尊敬的会员，3月5日' + SiteName + '元宵节嗨聊全场，多种活动期待您的参与' + SiteUrl
	--drop table A_03
	SELECT DISTINCT dcProvinceID, Mobile, Msg, Status INTO A_03 FROM A_01
	
--	select * from a_00 where mobile='13455496132'
--	select * from A_03 where mobile='13455496132'
--	select mobile, count(*) from a_00 group by mobile having count(*) >1 order by count(*) DESC
--	select mobile, count(*) from A_03 group by mobile having count(*) >1 order by count(*) DESC
---must updated
	CREATE TABLE #t(Id INT IDENTITY(1, 1), ProvinceId INT, Cnt INT, Msg NVARCHAR(500))
	CREATE TABLE #m(Mobile VARCHAR(20))

	INSERT INTO #t(provinceid, cnt, msg)
	SELECT dcProvinceId, COUNT(*) Cnt, msg
	FROM a_00
	WHERE Status = 0
	GROUP BY dcProvinceId,msg
 
	DECLARE @Id INT, @MobileString VARCHAR(MAX), @Msg NVARCHAR(500), @ProvinceId INT
	SET @Id = 0
	WHILE EXISTS(SELECT Id FROM #t WHERE Id > @Id)
	BEGIN
		SELECT TOP 1 @MobileString = '', @Id = Id, @ProvinceId = ProvinceId, @Msg = Msg FROM #t WHERE Id >  @Id ORDER BY Id

		TRUNCATE TABLE #m
		INSERT INTO #m
		SELECT TOP 500 Mobile 
		FROM a_00
		WHERE dcProvinceId = @ProvinceId
		AND Status = 0
		ORDER BY Mobile

		SELECT TOP 500 @MobileString = @MobileString + ',' + Mobile
		FROM #m

		IF LEN(@MobileString) > 1
		BEGIN
			SET @MobileString = RIGHT(@MobileString, LEN(@MobileString) - 1)
			INSERT INTO a04(Mobile, Msg) SELECT @MobileString, @Msg
			UPDATE a_00 SET Status = 1 WHERE Mobile IN(SELECT Mobile FROM #m)
		END
	END
/*
insert smsBatchSend(mobile,msg) select   mobile,msg from a04
SELECT top 100 * 	FROM smsBatchSend 
--where sendstatus is null 
order by id desc
*/
/*
truncate table a04
drop table #t
	drop table #m
	CREATE TABLE #t(Id INT IDENTITY(1, 1), ProvinceId INT, Cnt INT, Msg NVARCHAR(500))
	CREATE TABLE #m(Mobile VARCHAR(20))
select * from #t
select * from #m
select * from A_03

	INSERT INTO #t(provinceid, cnt, msg)
	SELECT dcProvinceId, COUNT(*) Cnt, msg
	FROM A_03
	WHERE Status = 0
	GROUP BY dcProvinceId,msg

	DECLARE @Id INT, @MobileString VARCHAR(MAX), @Msg NVARCHAR(500), @ProvinceId INT
	SET @Id = 0
	WHILE EXISTS(SELECT Id FROM #t WHERE Id > @Id)
	BEGIN
		SELECT TOP 1 @MobileString = '', @Id = Id, @ProvinceId = ProvinceId, @Msg = Msg FROM #t WHERE Id >  @Id ORDER BY Id

		TRUNCATE TABLE #m
		INSERT INTO #m
		SELECT TOP 500 Mobile 
		FROM A_03
		WHERE dcProvinceId = @ProvinceId
		AND Status = 0
		ORDER BY Mobile

		SELECT TOP 500 @MobileString = @MobileString + ',' + Mobile
		FROM #m

		IF LEN(@MobileString) > 1
		BEGIN
			SET @MobileString = RIGHT(@MobileString, LEN(@MobileString) - 1)
			INSERT INTO a04(Mobile, Msg) SELECT @MobileString, @Msg
			UPDATE A_03 SET Status = 1 WHERE Mobile IN(SELECT Mobile FROM #m)
		END
	END

select len(mobile)/12,* from a04
-----
select * from a04
insert smsBatchSend(mobile,msg) select   mobile,msg from a04
SELECT top 100 * 	FROM smsBatchSend 
where sendstatus is null 
order by id desc
*/

END

GO
/****** Object:  StoredProcedure [dbo].[procbatchsms2]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE procedure [dbo].[procbatchsms2]
as
begin 
	BEGIN TRY
		DROP Table a_00
	END TRY
	BEGIN CATCH
	END CATCH
	BEGIN TRY
		DROP Table A_01
	END TRY
	BEGIN CATCH
	END CATCH
	BEGIN TRY
		DROP Table A_02
	END TRY
	BEGIN CATCH
	END CATCH
	BEGIN TRY
		DROP Table A_03
	END TRY
	BEGIN CATCH
	END CATCH
	BEGIN TRY
		DROP Table A_04
	END TRY
	BEGIN CATCH
	END CATCH
/*
	--1、一个月即将到期的（后续没有开通订单的）会员。
	select distinct id cpMainId, id camainid, dcProvinceId, space(50) SiteName, space(50) SiteUrl, space(11) Mobile, space(300) Msg, 0 Status
	into A_00
	from cpmain 
	where MemberType = 3
	AND Id IN(SELECT cpMainId FROM caorder 
		WHERE OrderType = 8 AND IsDeleted = 0 AND OpenDate > 0 
		AND EndDate BETWEEN getdate() and GETDATE() + 31)
	AND Id NOT IN(SELECT cpMainId FROM caorder WHERE OrderType = 8 AND IsDeleted = 0 AND EndDate > GETDATE()+ 31)

	--2、两个月内查看资费标准在三次以上的处于免费会员状态的。
	select id cpMainId, id camainid, dcProvinceId, space(50) SiteName, space(50) SiteUrl, space(11) Mobile, space(300) Msg, 0 Status
	into A_01
	from cpmain 
	where membertype=3 
	and id IN(
		SELECT a.cpMainId
		FROM caMain a, caFeePageViewLog b
		WHERE a.Id = b.caMainId
		AND b.AddDate > GETDATE() - 61
		GROUP BY a.cpMainId
		HAVING COUNT(*) > 2
	)
	AND ID NOT IN(SELECT cpMainId FROM A_00)
	INSERT into A_01 select * from a_00
	--3、到期后三个月内没有付费并处于免费会员状态的。
	insert into a_01
	select distinct id cpMainId, id camainid, dcProvinceId, space(50) SiteName, space(50) SiteUrl, space(11) Mobile, space(300) Msg, 0 Status
	from cpmain 
	where MemberType < 3
	AND Id IN(SELECT cpMainId FROM caorder 
		WHERE OrderType = 8 AND IsDeleted = 0 AND OpenDate > 0 
		AND EndDate > getdate() - 92)
	AND Id NOT IN(SELECT cpMainId FROM caorder WHERE OrderType = 8 AND IsDeleted = 0 AND EndDate > GETDATE() AND OpenDate > '')
	AND Id NOT IN(SELECT cpMainId FROM A_01)
	--4、本月提交订单未开通并处于免费会员状态的。
	insert into a_01
	select distinct id cpMainId, id camainid, dcProvinceId, space(50) SiteName, space(50) SiteUrl, space(11) Mobile, space(300) Msg, 0 Status
	from cpmain 
	where MemberType < 3
	AND Id IN(SELECT cpMainId FROM caorder 
		WHERE OrderType = 8 AND IsDeleted = 0 AND OpenDate IS NULL
		AND AddDate > '2016-5-26')
	AND Id NOT IN(SELECT cpMainId FROM caorder WHERE OrderType = 8 AND IsDeleted = 0 AND EndDate > GETDATE() AND OpenDate > '')
	AND Id NOT IN(SELECT cpMainId FROM A_01)


	--	INSERT into A_01 SELECT 371108, 371108, 32,'','','','',0 
	--UPDATE A_01 SET caMainId = 0
	--UPDATE A_02 SET cpMainId = 0
	--UPDATE A_02 SET cpMainId = ISNULL((SELECT cpMainId FROM caMain WHERE caMain.ID = A_02.caMainId), 0)
	--DELETE from a_02 where cpmainid=0

	--INSERT A_01(cpMainID, caMainId, dcProvinceId, status)
	--SELECT DISTINCT cpMainID, 0, 0, 0 FROM A_02 WHERE cpMainId NOT IN(SELECT CpMainID FROM A_01) AND cpMainId > 0
	---------------------------
	UPDATE a SET a.dcProvinceID = b.dcProvinceId FROM A_01 a, cpMain b WHERE a.cpMainId = b.Id
	UPDATE a SET a.caMainId = b.Id,
		a.Mobile = b.Mobile
	FROM A_01 a, caMain b
	WHERE b.AccountType = 1 AND a.cpMainId = b.cpMainId
	DELETE A_01 WHERE CaMainId = 0
	DELETE A_01 WHERE Mobile NOT LIKE '1%'
	DELETE A_01 WHERE LEN(Mobile) <> 11
	DELETE A_01 WHERE Mobile IS NULL
	DELETE A_01 WHERE Mobile = '13000000000'
	DELETE A_01 WHERE Mobile = '15000000000'
	DELETE A_01 WHERE Mobile = '15555555555'
	DELETE A_01 WHERE Mobile = '13222222222' 
	delete a_01 WHERE cpMainId NOT IN(select  max(cpMainId) cpMainId FROM a_01 group by Mobile)
	DELETE a_01 where mobile in(select mobile from marketdb..NoSendSms)
	--select mobile, count(*) from a_01 group by mobile order by count(*) desc

	UPDATE a SET a.SiteName = b.WebSiteName, a.SiteUrl = 'www.' + b.ProvinceDomain
	FROM A_01 a, dcProvince b
	WHERE a.dcProvinceID = b.Id
	
--	UPDATE a SET a.SiteName = b.WebSiteName, a.SiteUrl = 'www.' + b.ProvinceDomain
--	FROM a_00 a, dcProvince b
--	WHERE a.dcProvinceID = b.Id
--  select * from a_01 where subno > 7000
select * from a_01 where subno > 7900 or subno < 5600
	alter table a_01 add subno int
	update a set a.subno = b.consultantid from a_01 a, cpmain b where a.cpmainid= b.id
	update a_01 set subno = subno + 6000 where subno > 699
	update a_01 set subno = subno + 6000 where subno < 600
	update a_01 set subno = subno + 5000 where subno between 600 and 699

	--UPDATE a_00 SET Msg = '尊敬的会员，3月5日' + SiteName + '元宵节找工作送福利，多名就业导师为您求职答疑解惑，期待您的登录' + SiteUrl
	UPDATE A_01 set Msg = '亲爱的会员，' + SiteName + '粽情端午套餐优惠活动邀您参与，时间有限快来咨询吧！4006265151' 
		+ CASE WHEN SubNo IS NULL THEN '' ELSE '-' + LTRIM(STR(SubNo)) END + '。'
 
--select sitename, count(*) from a_01 group by sitename order by count(*)
	--select * from a_01
	alter table a_01 add id int identity(1,1)
	SELECT min(id) id, Mobile, Status INTO A_03 FROM A_01 group by Mobile, Status
	alter table a_03 add dcProvinceId int
	alter table a_03 add msg nvarchar(200)
	update a set a.dcProvinceId = b.dcProvinceId,a.msg=b.msg from a_03 a, a_01 b where a.id=b.id

	--select left(msg, 5), count(*) from a_03 group by left(msg, 5) order by count(*) Desc
--	select * from a_00 where mobile='13455496132'
--	select * from A_03 where mobile='13455496132'
--	select mobile, count(*) from a_00 group by mobile having count(*) >1 order by count(*) DESC
--	select mobile, count(*) from A_03 group by mobile having count(*) >1 order by count(*) DESC
---must updated

--delete a_03 where msg in(select msg from a_03 group by msg having count(*) < 120)
--select count(distinct mobile), count(*) from a_03
--select * from a_03
--drop table #t
--drop table #m
--drop table a_04
	CREATE TABLE #t(Id INT IDENTITY(1, 1), ProvinceId INT, Cnt INT, Msg NVARCHAR(500))
	CREATE TABLE #m(Mobile VARCHAR(20))

	INSERT INTO #t(provinceid, cnt, msg)
	SELECT dcProvinceId, COUNT(*) Cnt, msg
	FROM a_03
	WHERE Status = 0
	GROUP BY dcProvinceId, msg

	CREATE TABLE a_04(Id INT IDENTITY(1, 1), Mobile varchar(MAX), Msg NVARCHAR(300))
	--select * from a_03

	DECLARE @Id INT, @MobileString VARCHAR(MAX), @Msg NVARCHAR(500), @ProvinceId INT
	SET @Id = 0
	WHILE EXISTS(SELECT Id FROM #t WHERE Id > @Id)
	BEGIN
		SELECT TOP 1 @MobileString = '', @Id = Id, @ProvinceId = ProvinceId, @Msg = Msg FROM #t WHERE Id >  @Id ORDER BY Id

		TRUNCATE TABLE #m
		INSERT INTO #m
		SELECT TOP 500 Mobile 
		FROM a_03
		WHERE dcProvinceId = @ProvinceId
		AND Status = 0
		ORDER BY Mobile

		SELECT TOP 500 @MobileString = @MobileString + ',' + Mobile
		FROM #m

		IF LEN(@MobileString) > 1
		BEGIN
			SET @MobileString = RIGHT(@MobileString, LEN(@MobileString) - 1)
			INSERT INTO a_04(Mobile, Msg) SELECT @MobileString, @Msg
			UPDATE a_03 SET Status = 1 WHERE Mobile IN(SELECT Mobile FROM #m)
		END
	END
	--update a_04 set mobile='18363443519,' + mobile where id=2
	select sum((len(mobile)+1)/12.0) from a_04 
	select (len(mobile)+1)/12.0,* from a_04 order by id
	insert smsBatchSend(mobile,msg) select mobile,msg from a_04 WHERE ID <> 2
	SELECT top 35 * 	FROM smsBatchSend 
	where sendstatus is null 
	order by id desc
*/
end

GO
/****** Object:  StoredProcedure [dbo].[ProcBeisenAdsSave]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[ProcBeisenAdsSave]
(
	@Id INT,
	@TenantId VARCHAR(50),
	@JobAdId VARCHAR(50),
	@JobAdName NVARCHAR(500),
	@JobType NVARCHAR(500),
	@LocID NVARCHAR(500),
	@Salary NVARCHAR(500),
	@Degree NVARCHAR(500),
	@YearsofWorking NVARCHAR(50),
	@EndTime DATETIME,
	@Email VARCHAR,
	@Status NVARCHAR(100),
	@CreateDate DATETIME,
	@ModifiedDate DATETIME
)
AS
SET NOCOUNT ON
BEGIN
	IF NOT EXISTS (SELECT 'x' FROM BeisenAds WHERE Id = @Id)
	BEGIN
		INSERT INTO BeisenAds(Id, TenantId, JobAdId, JobAdName, JobType, LocID, Salary, Degree, YearsofWorking, EndTime, Email, Status, CreateDate, ModifiedDate, Adddate, LastGetDate)
		SELECT @Id, @TenantId, @JobAdId, @JobAdName, @JobType, @LocID, @Salary, @Degree, @YearsofWorking, @EndTime, @Email, @Status, @CreateDate, @ModifiedDate, GETDATE(), GETDATE()
	END
	ELSE
	BEGIN
		DECLARE @ModifiedDate2 AS DATETIME
		SELECT @ModifiedDate2 FROM BeisenAds WHERE Id = @Id
		IF @ModifiedDate2 < @ModifiedDate
		BEGIN
			UPDATE BeisenAds
			SET TenantId = @TenantId,
				JobAdId = @JobAdId,
				JobAdName = @JobAdName,
				JobType = @JobType,
				LocID = @LocID,
				Salary = @Salary,
				Degree = @Degree,
				YearsofWorking = @YearsofWorking,
				EndTime = @EndTime,
				Email = @Email,
				Status = @Status,
				CreateDate = @CreateDate,
				ModifiedDate = @ModifiedDate,
				LastGetDate = GETDATE()
			WHERE ID = @Id
			
			UPDATE BeisenAdsId SET IsModified = 1 WHERE BeisenAdsId = @Id
		END		
	END
	RETURN 1
END

GO
/****** Object:  StoredProcedure [dbo].[ProcBeiSenCompanySave]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[ProcBeiSenCompanySave]
(
	@TenantId VARCHAR(50),
	@Name NVARCHAR(500),
	@Domain NVARCHAR(500),
	@Abbreviation NVARCHAR(500),
	@Address NVARCHAR(500),
	@PostalCode NVARCHAR(500),
	@EmailHost NVARCHAR(500),
	@Logo VARCHAR(500)
)
AS
SET NOCOUNT ON
BEGIN
	IF NOT EXISTS (SELECT 'x' FROM BeiSenCompany WHERE TenantId = @TenantId)
	BEGIN
		INSERT INTO BeiSenCompany(TenantId, Name, Domain, Abbreviation, Address, PostalCode, EmailHost, Logo, AddDate)
		SELECT @TenantId, @Name, @Domain, @Abbreviation, @Address, @PostalCode, @EmailHost, @Logo, GETDATE()
	END
	ELSE
	BEGIN
		DECLARE @IsModified BIT
		
		IF EXISTS(SELECT 'x' FROM BeisenCompany 
			WHERE TenantId = @TenantId
			AND ISNULL(Name, '')  != ISNULL(@Name, '')
			AND ISNULL(Domain, '')  != ISNULL(@Domain, '')
			AND ISNULL(Abbreviation, '')  != ISNULL(@Abbreviation, '')
			AND ISNULL(Address, '')  != ISNULL(@Address, '')
			AND ISNULL(PostalCode, '')  != ISNULL(@PostalCode, '')
			AND ISNULL(EmailHost, '')  != ISNULL(@EmailHost, '')
			AND ISNULL(Logo, '')  != ISNULL(@Logo, ''))
		BEGIN
			UPDATE BeisenCompany
			SET Name= @Name,
				Domain= @Domain,
				Abbreviation= @Abbreviation,
				Address= @Address,
				PostalCode= @PostalCode,
				EmailHost= @EmailHost,
				Logo= @Logo
			WHERE TenantId = @TenantId
		END		
	END
	
	RETURN 1
END

GO
/****** Object:  StoredProcedure [dbo].[ProcBeisenJobApplyBySendSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[ProcBeisenJobApplyBySendSelect]
AS
SET NOCOUNT ON
BEGIN
	IF NOT EXISTS(SELECT '' FROM BeisenJobApply WHERE BeisenHasApply IS NULL)
	BEGIN
		SELECT TOP 0 'a' a
		RETURN
	END
	
	SELECT TOP 99 *
	INTO #t
	FROM BeisenJobApply
	WHERE BeisenHasApply IS NULL
	
	UPDATE #t SET cvText = dbo.GetBeiSenCvText(cvMainID) WHERE cvText IS NULL
	UPDATE a SET a.cvText = b.cvText FROM BeisenJobApply a, #t b WHERE a.Id = b.Id AND a.cvText = ''
	DELETE a FROM BeisenJobApply a, #t b WHERE a.Id = b.Id AND b.cvText = ''
	DELETE #t WHERE cvText = ''
	
	IF EXISTS(SELECT 'x' FROM #t)
	BEGIN
		SELECT a.Id, b.Name, d.TenantID, d.JobAdId, c.Id BeisenJobApplyId, c.cvText, b.Mobile, b.Email
		FROM cvMain a, paMain b, #t c, BeisenAds d
		WHERE a.paMainId = b.Id
		AND a.Id = c.cvMainId 
		AND c.BeisenHasApply IS NULL
		AND c.JobId = d.JobId
	END
	ELSE
		SELECT * FROM #t
END


GO
/****** Object:  StoredProcedure [dbo].[procBestEmployerByCpMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[procBestEmployerByCpMainIDSelect]
(
	@cpMainID INT
)
AS
BEGIN
SET NOCOUNT OFF
	SELECT * FROM BestEmployer WITH(NOLOCK) WHERE cpMainID = @cpMainID
SET NOCOUNT ON
END

GO
/****** Object:  StoredProcedure [dbo].[procBestEmployerInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[procBestEmployerInsert]
(
	@cpMainID INT
)
AS
BEGIN
SET NOCOUNT OFF
	IF EXISTS(SELECT 'X' FROM BestEmployer WITH(NOLOCK) WHERE cpMainID = @cpMainID)
		RETURN
	INSERT INTO BestEmployer(cpMainID, CompanyName)
	SELECT ID, [Name] FROM cpMain WITH(NOLOCK) WHERE ID = @cpMainID
SET NOCOUNT ON
END
GO
/****** Object:  StoredProcedure [dbo].[procBestEmployerSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[procBestEmployerSelect]
(
	@Where VARCHAR(500)
)
AS
BEGIN
SET NOCOUNT OFF
	DECLARE @SQL VARCHAR(2000)
	SET @SQL = 'SELECT * FROM BestEmployer WITH(NOLOCK) WHERE 1 = 1' + @Where + ' ORDER BY ID DESC'
	EXEC(@SQL)
SET NOCOUNT ON
END
GO
/****** Object:  StoredProcedure [dbo].[procBestEmployVoteInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[procBestEmployVoteInsert]
(
	@ID INT,
	@OpenID VARCHAR(50)
)
AS
BEGIN
SET NOCOUNT OFF
	IF EXISTS(SELECT 'X' FROM BestEmployerVote WHERE OpenID = @OpenID AND BestEmployerID = @ID AND CONVERT(VARCHAR(8), GETDATE(), 112) = CONVERT(VARCHAR(8), AddDate, 112))
		RETURN -1
	IF (SELECT COUNT(1) FROM BestEmployerVote WHERE OpenID = @OpenID AND CONVERT(VARCHAR(8), GETDATE(), 112) = CONVERT(VARCHAR(8), AddDate, 112)) >= 3
		RETURN -2

	INSERT INTO BestEmployerVote(BestEmployerID, OpenID) VALUES(@ID, @OpenID)
	RETURN 1
SET NOCOUNT ON
END

GO
/****** Object:  StoredProcedure [dbo].[ProcbsAskDetailSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ProcbsAskDetailSelect]
(
	@ID INT
)
AS
SET NOCOUNT ON
BEGIN
	--修改点击量
	UPDATE bsASKInfo SET ClickNumber = ClickNumber + 1 WHERE ID = @ID
	--记录每日点击
--	DECLARE @bsAskInfoDayReportId INT
--	SELECT @bsAskInfoDayReportId = ID FROM bsAskInfoDayReport WHERE CountDate = CONVERT(VARCHAR(8), GETDATE(), 112) AND bsAskInfoId = @Id
--	IF @bsAskInfoDayReportId &gt; 0
--		UPDATE bsAskInfoDayReport 
--		SET VisitNumber = VisitNumber + 1
--		WHERE Id =  @bsAskInfoDayReportId
--	ELSE
--		INSERT INTO bsAskInfoDayReport
--		SELECT CONVERT(VARCHAR(8), GETDATE(), 112), @id, 1

	SELECT ID, Title, Question, Answer, SolveDate, UpdateDate, UserName, Mark, ProvinceIDs, TypeID,
		(SELECT TypeName FROM bsAskTypeSet WITH(NOLOCK)  WHERE ID = bsaskinfo.TypeID) TypeName,ClickNumber
	FROM bsASKInfo WITH(NOLOCK) 
	WHERE ID = @ID
END
SET NOCOUNT OFF

GO
/****** Object:  StoredProcedure [dbo].[ProcbsASKInfoALLSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.28
--创建人：Nick
--说明：获取全部求职互助
--#####################################################
CREATE PROCEDURE [dbo].[ProcbsASKInfoALLSelect]
	@dcProvinceId INT,
	@PageNo INT
AS
BEGIN TRY
	SELECT * 
	FROM bsAskInfoTmp WITH(NOLOCK) 
	WHERE dcProvinceId=@dcProvinceId 
	AND PageNo=@PageNo ORDER BY OrderNo
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[ProcBsAskInfoByAdvicesSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--sean 2014-11-19
CREATE PROCEDURE [dbo].[ProcBsAskInfoByAdvicesSelect]
(
	@ProvinceId INT
)
AS
SET NOCOUNT ON
--INSERT INTO procLog SELECT 'ProcBsAskInfoByAdvicesSelect', @ProvinceId, GETDATE()
BEGIN
	SET @ProvinceId = LEFT(@ProvinceId, 2)
	DECLARE @p VARCHAR(10), @u VARCHAR(100), @s VARCHAR(50)
	SELECT @p = ',' + LTRIM(STR(@ProvinceId)), @s = SubSiteUrl, @u = 'http://' + SubSiteUrl + '/ask/' FROM dcSubSite WHERE Id = @ProvinceId

	CREATE TABLE #t(
		Title VARCHAR(300),
		Question NVARCHAR(MAX),
		Answer NVARCHAR(MAX),
		ID INT,
		Url VARCHAR(100),
		UserName VARCHAR(20),
		AddDate SMALLDATETIME,
		SubSiteUrl VARCHAR(50))

	INSERT INTO #t
	SELECT Title, Question, Answer, Id, SPACE(100) Url, UserName, AddDate, @s
	FROM bsAskInfo WITH(NOLOCK)
	WHERE CHARINDEX(@p, ProvinceIds) > 0
	
	UPDATE #t SET Url = @u + LTRIM(STR(ID)) + '.html'

	SELECT *, AddDate + 1 Replydate FROM #t ORDER BY ID DESC
END


GO
/****** Object:  StoredProcedure [dbo].[procBsAskInfoByProvinceIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.5
--创建人：NICK
--说明：求职互助
--#####################################################
CREATE PROCEDURE [dbo].[procBsAskInfoByProvinceIDSelect]
(
	@provinceID VARCHAR(20)
)
AS
BEGIN
	SELECT TOP 11 a.id, a.title, a.typeid, a.solvedate, a.updatedate, t.typename
	FROM bsaskinfo a WITH(NOLOCK), bsAskTypeSet t WITH(NOLOCK)
	WHERE a.typeid=t.id 
	AND a.isonline=1
	AND provinceids LIKE '%,'+@provinceID+',%'
	ORDER BY a.updatedate DESC
END


GO
/****** Object:  StoredProcedure [dbo].[ProcBsAskInfoByXmlSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[ProcBsAskInfoByXmlSelect]
(
	@ProvinceId INT
)
AS
--INSERT INTO procLog SELECT 'ProcBsAskInfoByXmlSelect', @ProvinceId, GETDATE()
BEGIN
	SELECT TOP 5000 '/ask/' + CONVERT(VARCHAR,ID) + '.html' link 
	FROM bsAskInfo WITH(NOLOCK)
	WHERE IsOnline = 1 
	AND ProvinceIds LIKE '%,' + LTRIM(STR(@ProvinceId)) + '%'
	AND SolveDate > GETDATE() - 14
END


GO
/****** Object:  StoredProcedure [dbo].[ProcbsASKInfoHotQuestionSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.28
--创建人：Nick
--说明：获取求职互助热门话题
--#####################################################
CREATE PROCEDURE [dbo].[ProcbsASKInfoHotQuestionSelect]
(
	@ProvinceID INT
)
AS
BEGIN TRY
	/*
	SELECT TOP 10 a.Id, a.Title 
	FROM bsAskInfo a WITH(NOLOCK) 
	WHERE a.IsOnline = 1 
	AND ProvinceIds LIKE '%'+CONVERT(VARCHAR(10),@ProvinceID)+'%' 
	AND AddDate > DATEADD(MONTH, -1, GETDATE()) 
	ORDER BY a.ClickNumber DESC
	*/
	SELECT TOP 10 ID, Title
	FROM SearchDb..bsAskInfoHot WITH(NOLOCK)
	WHERE ProvinceId = @ProvinceId
	ORDER BY ClickNumber DESC
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[ProcBsAskInfoIdByBatchUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--sean 2014-8-13
CREATE PROCEDURE [dbo].[ProcBsAskInfoIdByBatchUpdate]
AS
BEGIN
	SELECT TOP 1000 bsAskInfoId INTO #t FROM Marketdb..bsaskInfoInclude where checkdate > '' AND IncludeDate IS NULL ORDER BY bsAskInfoId
	INSERT INTO bsAskInfo(Title, Url, ClassID, Question, Answer, TypeID, Mark, UserName, AddUserID, AddDate, Comment, SolveDate, IsOnline, UpdateDate, ProvinceIds, GetWay, ReferUrl, ClickNumber)
	SELECT Title, Url, ClassID, Question, Answer, TypeID, Mark, UserName, AddUserID, AddDate + DATEDIFF(DAY, AddDate, GETDATE() -1 ),
		 Comment, SolveDate + DATEDIFF(DAY, SolveDate, GETDATE() -1 ), IsOnline, UpdateDate + DATEDIFF(DAY, UpdateDate, GETDATE() -1 ), ProvinceIds, GetWay, ReferUrl, ClickNumber
	FROM bsAskInfo
	WHERE ID IN(SELECT bsAskInfoId FROM #t)
	DELETE bsAskInfo WHERE ID IN(SELECT bsAskInfoId FROM #t)

	DELETE Marketdb..bsaskInfoInclude WHERE bsAskInfoId NOT IN (SELECT ID FROM bsAskInfo)
	--------------------------
	INSERT INTO Marketdb..bsaskInfoInclude
	SELECT Id, REPLACE(ProvinceIds, ',', ''), NULL, NULL
	FROM bsAskInfo WITH(NOLOCK)
	WHERE LEN(provinceids) < 10
	AND ID NOT IN(SELECT bsAskInfoId FROM Marketdb..bsaskInfoInclude)
/*
	INSERT INTO Marketdb..bsaskInfoInclude
	SELECT a.Id, b.Id, NULL, NULL
	FROM bsAskInfo a WITH(NOLOCK), dcProvince b
	WHERE LEN(a.provinceids) > 10
	AND a.ID NOT IN(SELECT bsAskInfoId FROM Marketdb..bsaskInfoInclude)
*/
END
 




GO
/****** Object:  StoredProcedure [dbo].[ProcBsAskInfoIncludeSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--sean 2014-8-13
CREATE PROCEDURE [dbo].[ProcBsAskInfoIncludeSelect]
AS
BEGIN
	SELECT TOP 100 id, ProvinceId, bsAskInfoId
	FROM MarketDb..bsAskInfoInclude
	ORDER BY ISNULL(CheckDate, '2000-1-1'), IncludeDate, BsAskInfoId
END





GO
/****** Object:  StoredProcedure [dbo].[ProcbsAskInfoNewSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.27
--创建人：Nick
--说明：得到最新5条求职互助
--#####################################################
CREATE PROCEDURE [dbo].[ProcbsAskInfoNewSelect]
(
	@ProvinceID INT,
	@SubSiteID INT
)
AS
BEGIN TRY
	SELECT TOP 5 ID,Title 
	FROM bsAskInfo WITH(NOLOCK)
	WHERE IsOnline = 1
	AND (Provinceids LIKE '%'+CONVERT(VARCHAR(10),@ProvinceID)+'%'
		OR Provinceids LIKE '%'+CONVERT(VARCHAR(10),@SubSiteID)+'%') 
	ORDER BY UpdateDate DESC 
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[ProcbsAskInfoSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.28
--创建人：Nick
--说明：求职互助列表 
--#####################################################
CREATE PROCEDURE [dbo].[ProcbsAskInfoSelect]
(
	@TypeId INT, 
	@ProvinceId INT, 
	@KeyWord VARCHAR(50)
)
AS
SET NOCOUNT ON
BEGIN
	DECLARE @SQL VARCHAR(1000)
	SET @SQL = 'SELECT TOP 1000 a.Id, a.title, a.TypeId, a.solvedate, a.updatedate, t.Typename 
		FROM bsAskInfo a WITH(NOLOCK), bsAskTypeSet t WITH(NOLOCK)
		WHERE a.TypeId = t.Id 
		AND a.isonline = 1
		AND ProvinceIds = '',' + CONVERT(VARCHAR(10), @ProvinceId) + ',''
	'
	IF @TypeId <> 0
	BEGIN
		SET @SQL = @SQL + ' AND a.TypeId = ' + CONVERT(VARCHAR(10), @TypeId)
	END
	IF @KeyWord <> ''
	BEGIN
		SET @SQL = @SQL + ' AND a.Title LIKE ''%' + dbo.SafeSql(@KeyWord) + '%'''
	END
	SET @SQL = @SQL + ' ORDER BY a.UpdateDate DESC '
	--print @sql
	EXEC(@SQL)
END

GO
/****** Object:  StoredProcedure [dbo].[ProcbsASKTagInfoByIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.28
--创建人：Nick
--说明：获取求职互助标签
--#####################################################
CREATE PROCEDURE [dbo].[ProcbsASKTagInfoByIDSelect]
	@ID INT
AS
BEGIN TRY
	SELECT * FROM bsASKTagInfo WHERE ID = @ID
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[procbsASKTypeSetAllSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.04
--创建人：Nick
--说明：select bsASKTypeSet
--#####################################################
CREATE PROCEDURE [dbo].[procbsASKTypeSetAllSelect]
AS
BEGIN TRY
	SELECT * FROM bsASKTypeSet WHERE id>0 AND typename<>'美通社' ORDER BY orderno
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[ProcbsAskTypeSetSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.27
--创建人：Nick
--说明：得到热门求职互助类别
--#####################################################
CREATE PROCEDURE [dbo].[ProcbsAskTypeSetSelect]
AS
BEGIN TRY
	SELECT TOP 14 * 
	FROM bsAskTypeSet WITH(NOLOCK)
	WHERE ID>0 
	ORDER BY Newid() 
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[ProcBsPageClickLogInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ProcBsPageClickLogInsert]
AS
BEGIN
	DECLARE @M AS VARCHAR(6)
	SET @m = CONVERT(VARCHAR(6), GETDATE(), 112)
	DELETE bsPageClickLog WHERE CountMonth = @M
	-- 职场资讯
	INSERT bsPageClickLog(PageType, PageId, ClickNumber, ClickNumberAll)
	SELECT 1, ID, ViewNumber, ViewNUmber_All FROM QlrcNews WITH(NOLOCK)
	--招聘会
	INSERT bsPageClickLog(PageType, PageId, ClickNumber)
	SELECT 2, ID, ViewNumber FROM recruitment WITH(NOLOCK)
	--文档下载
	INSERT bsPageClickLog(PageType, PageId, ClickNumber)
	SELECT 3, ID, dwnnum FROM dwndoc WITH(NOLOCK)

	DECLARE @ThisMonth AS VARCHAR(6), @PrevMonth AS VARCHAR(6)
	SELECT @ThisMonth = CONVERT(VARCHAR(6), GETDATE(), 112),
		@PrevMonth = CONVERT(VARCHAR(6), DATEADD(mm, -1, GETDATE()), 112)

	UPDATE a
	SET a.Increase = a.ClickNumber - b.ClickNumber,
		a.IncreaseAll = a.ClickNumberAll - b.ClickNumberAll
	FROM bsPageClickLog a, bsPageClickLog b
	WHERE a.CountMonth = @ThisMonth
	AND b.CountMonth = @PrevMonth
	AND a.PageID = b.PageID
	AND a.PageType = b.PageType

	UPDATE bsPageClickLog
	SET Increase = ClickNumber,
		IncreaseAll = ClickNumberAll
	FROM bsPageClickLog
	WHERE CountMonth = @ThisMonth
	AND PageID NOT IN(
		SELECT PageID FROM bsPageClickLog WITH(NOLOCK)
		WHERE CountMonth = @PrevMonth)
END














GO
/****** Object:  StoredProcedure [dbo].[procBsSourceDetailInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 

--创建人 Nick 20141015
--用于记录每个页面的来源访问情况
CREATE PROCEDURE [dbo].[procBsSourceDetailInsert]
(
	@SubSiteID INT,
	@SiteType SMALLINT,
	@SessionID VARCHAR(100),
	@Referer VARCHAR(200),
	@IP VARCHAR(15),
	@Url VARCHAR(200)
)
AS
return 0
BEGIN
	DECLARE @MaxID INT
	SELECT @MaxID = Id FROM BsSourceDetail WITH(NOLOCK) WHERE SessionId = @SessionID
	IF @MaxID IS NULL
	BEGIN
		INSERT INTO BsSourceDetail 
		VALUES (@SubSiteID, @SiteType, @SessionID, @IP, @Referer, 1, GETDATE(), GETDATE())
		SET @MaxID = @@IDENTITY
	END
	ELSE
	BEGIN
		UPDATE BsSourceDetail
		SET ViewNumber = ViewNumber+1, LastViewDate = GETDATE()
		WHERE ID = @MaxId
	END
	RETURN @MaxID
END





GO
/****** Object:  StoredProcedure [dbo].[procBsSourceDetailInsert2]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 

--创建人 Nick 20141015
--用于记录每个页面的来源访问情况
CREATE PROCEDURE [dbo].[procBsSourceDetailInsert2]
(
	@SubSiteID INT,
	@SiteType SMALLINT,
	@SessionID VARCHAR(100),
	@Referer VARCHAR(200),
	@IP VARCHAR(15),
	@Url VARCHAR(200)
)
AS
return 0
BEGIN
	DECLARE @MaxID INT
	SELECT @MaxID = Id FROM BsSourceDetail WITH(NOLOCK) WHERE SessionId = @SessionID
	IF @MaxID IS NULL
	BEGIN
		INSERT INTO BsSourceDetail 
		VALUES (@SubSiteID, @SiteType, @SessionID, @IP, @Referer, 1, GETDATE(), GETDATE())
		SET @MaxID = @@IDENTITY
	END
	ELSE
	BEGIN
		UPDATE BsSourceDetail
		SET ViewNumber = ViewNumber+1, LastViewDate = GETDATE()
		WHERE ID = @MaxId
	END
	RETURN @MaxID
END





GO
/****** Object:  StoredProcedure [dbo].[procBsSourceDetailUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/****** Object:  StoredProcedure [dbo].[procBsSourceDetailInsert]    Script Date: 10/20/2014 08:46:46 ******/
--创建人 Nick 20141015
--用于记录每个页面的来源访问情况
CREATE PROCEDURE [dbo].[procBsSourceDetailUpdate]
(
	@bsSourceDetailID INT,
	@url VARCHAR(200)
)
AS
return
BEGIN TRY
	UPDATE BsSourceDetail
	SET ViewNumber = ViewNumber+1, LastViewDate = GETDATE()
	WHERE ID = @bsSourceDetailID

	IF @@ROWCOUNT = 0
	BEGIN
		IF NOT EXISTS(SELECT 'x' FROM BsSourceDetail WITH(NOLOCK) WHERE ID = @bsSourceDetailID)
		BEGIN
			SET IDENTITY_INSERT LogDb..bsSourceDetail ON
			INSERT INTO BsSourceDetail(ID, SubSiteID, SiteType, SessionID, IP, Referer, ViewNumber, LastViewDate, AddDate)
			SELECT ID, SubSiteID, SiteType, SessionID, IP, Referer, ViewNumber, LastViewDate, AddDate
			FROM BsSourceDetailAll WITH(NOLOCK) WHERE Id = @bsSourceDetailID
			SET IDENTITY_INSERT LogDb..bsSourceDetail OFF

			DELETE FROM BsSourceDetailAll WHERE Id = @bsSourceDetailID

			UPDATE BsSourceDetail
			SET ViewNumber = ViewNumber+1, LastViewDate = GETDATE()
			WHERE ID = @bsSourceDetailID

		END
	END
END TRY
BEGIN CATCH
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[procBsSourceDetailUpdate2]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/****** Object:  StoredProcedure [dbo].[procBsSourceDetailInsert]    Script Date: 10/20/2014 08:46:46 ******/
--创建人 Nick 20141015
--用于记录每个页面的来源访问情况
CREATE PROCEDURE [dbo].[procBsSourceDetailUpdate2]
(
	@bsSourceDetailID INT,
	@url VARCHAR(200)
)
AS
return
BEGIN TRY
	UPDATE BsSourceDetail
	SET ViewNumber = ViewNumber+1, LastViewDate = GETDATE()
	WHERE ID = @bsSourceDetailID

	IF @@ROWCOUNT = 0
	BEGIN
		IF NOT EXISTS(SELECT 'x' FROM BsSourceDetail WITH(NOLOCK) WHERE ID = @bsSourceDetailID)
		BEGIN
			SET IDENTITY_INSERT LogDb..bsSourceDetail ON
			INSERT INTO BsSourceDetail(ID, SubSiteID, SiteType, SessionID, IP, Referer, ViewNumber, LastViewDate, AddDate)
			SELECT ID, SubSiteID, SiteType, SessionID, IP, Referer, ViewNumber, LastViewDate, AddDate
			FROM BsSourceDetailAll WITH(NOLOCK) WHERE Id = @bsSourceDetailID
			SET IDENTITY_INSERT LogDb..bsSourceDetail OFF

			DELETE FROM BsSourceDetailAll WHERE Id = @bsSourceDetailID

			UPDATE BsSourceDetail
			SET ViewNumber = ViewNumber+1, LastViewDate = GETDATE()
			WHERE ID = @bsSourceDetailID

		END
	END
END TRY
BEGIN CATCH
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[ProcBsSourceRefererCountUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--创建人 Nick 20141020
--生成推广每天的统计数据
CREATE PROCEDURE [dbo].[ProcBsSourceRefererCountUpdate]
AS
BEGIN
	DECLARE @Countdate VARCHAR(8), @Referer_AllNum INT, 
		@Referer_Ref VARCHAR(200), @dcSubSiteID INT, 
		@dcSubsiteDomain VARCHAR(50), @CountNumber AS INT, 
		@p INT, @StartTime DATETIME , @EndTime DATETIME
	
	SELECT @CountDate = CONVERT(VARCHAR(8), GETDATE() - 1, 112), 
		@StartTime = CONVERT(VARCHAR(10), GETDATE() - 1, 120), 
		@EndTime = CONVERT(VARCHAR(10), GETDATE(), 120)
	--select @CountDate, @StartTime, @EndTime
	--SET @CountDate = '20141020'
	--SET @StartTime = '2014-10-20'
	--SET @EndTime = '2014-10-20 23:59:00'

	--删除当前统计天数据
	DELETE FROM bsSourceRefererCount WHERE CountDate = @CountDate
	DELETE FROM bsSourceCount WHERE CountDate = @CountDate
	
	DECLARE @t AS TABLE(
		ID INT, 
		Domain VARCHAR(100), 
		CountNumber INT
	)
	 	
	INSERT INTO @t SELECT Id, SubSiteUrl, 200 FROM dcSubsite WITH(NOLOCK) ORDER BY Id

	DECLARE curSite CURSOR FOR 
		SELECT Id, Domain, CountNumber FROM @t ORDER BY Id
	FOR READ ONLY
	OPEN curSite

	FETCH NEXT FROM curSite INTO @dcSubSiteID, @dcSubsiteDomain, @CountNumber
	WHILE @@FETCH_STATUS = 0
	BEGIN
		INSERT INTO bsSourceRefererCount(subSiteID, CountDate, Referer, HowMany, SiteType)
		SELECT TOP (@CountNumber) @dcSubSiteID, @CountDate, LEFT(Referer, CHARINDEX('/', Referer, 8)) Ref, COUNT(*), 1
		FROM bsSourceDetailAll WITH(NOLOCK)
		WHERE CHARINDEX('/', Referer, 8) > 0
		AND SubSiteID = @dcSubSiteID
		AND SiteType = 1
		AND LastViewDate > @StartTime AND LastViewDate < @EndTime		
		AND CHARINDEX(SUBSTRING(@dcSubsiteDomain, CHARINDEX('.', @dcSubsiteDomain) + 1, LEN(@dcSubsiteDomain)), Referer, 0) = 0
		GROUP BY LEFT(Referer, CHARINDEX('/', Referer, 8))
		ORDER BY COUNT(*) DESC
		
		IF @dcSubSiteID > 0 AND LEN(@dcSubSiteID) = 2
		BEGIN
			--手机m站
			INSERT INTO bsSourceRefererCount(subSiteID, CountDate, Referer, HowMany, SiteType)
			SELECT TOP (@CountNumber) @dcSubSiteID, @CountDate, LEFT(Referer, CHARINDEX('/', Referer, 8)) Ref, COUNT(*), 2
			FROM bsSourceDetailAll WITH(NOLOCK)
			WHERE CHARINDEX('/', Referer, 8) > 0
			AND SubSiteID = @dcSubSiteID
			AND SiteType = 2
			AND LastViewDate > @StartTime AND LastViewDate < @EndTime		
			AND CHARINDEX(SUBSTRING(@dcSubsiteDomain, CHARINDEX('.', @dcSubsiteDomain) + 1, LEN(@dcSubsiteDomain)), Referer, 0) = 0
			GROUP BY LEFT(Referer, CHARINDEX('/', Referer, 8))
			ORDER BY COUNT(*) DESC
						
			--县级站
			INSERT INTO bsSourceRefererCount(subSiteID, CountDate, Referer, HowMany, SiteType)
			SELECT TOP (@CountNumber) CONVERT(VARCHAR(10), @dcSubSiteID) + '0000', @CountDate, LEFT(Referer, CHARINDEX('/', Referer, 8)) Ref, COUNT(*), 1
			FROM bsSourceDetailAll WITH(NOLOCK)
			WHERE CHARINDEX('/', Referer, 8) > 0
			AND SUBSTRING(CONVERT(VARCHAR(10), SubSiteID), 0, 2) = @dcSubSiteID
			AND LEN(SubSiteID) = 6
			AND LastViewDate > @StartTime AND LastViewDate < @EndTime		
			AND CHARINDEX(SUBSTRING(@dcSubsiteDomain, CHARINDEX('.', @dcSubsiteDomain) + 1, LEN(@dcSubsiteDomain)), Referer, 0) = 0
			GROUP BY LEFT(Referer, CHARINDEX('/', Referer, 8))
			ORDER BY COUNT(*) DESC
		END
		FETCH NEXT FROM curSite INTO @dcSubSiteID, @dcSubsiteDomain, @CountNumber
	END
	CLOSE curSite
	DEALLOCATE curSite

	--修改bsSourceRefererCount typeID 字段 
	--搜索引擎
	UPDATE a SET a.TypeID = 1, 
		a.Referer = c.Item_Name
	FROM bsSourceRefererCount a, Referer_Item_Keywords b, Referer_Item c
	WHERE b.Item_Id = c.ID
	AND CHARINDEX(b.Keywords, a.referer) > 0 
	AND C.ID IN (3, 8, 14, 11, 31, 45, 62, 74)
	AND CountDate = @CountDate
	
	--修改外部链接 typeid
	UPDATE bsSourceRefererCount 
	SET TypeID = 2, SiteType = 1
	WHERE (CHARINDEX('mail.qq.com', referer) > 0 
		OR CHARINDEX('mail.126.com', referer) > 0 
		OR CHARINDEX('mail.163.com', referer) > 0 
		OR CHARINDEX('mail.sina.com.cn', referer) > 0 
		OR CHARINDEX('mail.10086.cn', referer) > 0 
		OR CHARINDEX('mail.sohu.com', referer) > 0 
		OR CHARINDEX('mail.189.cn', referer) > 0 
		OR CHARINDEX('www.126.com', referer) > 0 
		OR CHARINDEX('www.2345.com', referer) > 0 
		OR CHARINDEX('www.hao123.com', referer) > 0 
		OR CHARINDEX('www.dn1234.com', referer) > 0 
		OR CHARINDEX('hao.360.com', referer) > 0 
		OR CHARINDEX('www.3600.com', referer) > 0 
	)
	AND TypeID IS NULL
	AND CountDate = @CountDate
	
	--修改外部链接其他
	UPDATE bsSourceRefererCount 
	SET TypeID = 2, SiteType = 1, Referer='外部链接其他'
	WHERE TypeID IS NULL
	AND CountDate = @CountDate
	
	--修改bssourcecount表数据--
	--省份、城市 访问的访客数、ip数
	INSERT INTO bsSourceCount (SubSiteID, CountDate, VisitorCount, IPCount, SiteType)
	SELECT SubSiteID, @CountDate, COUNT(DISTINCT SessionID), COUNT(DISTINCT IP), SiteType
	FROM bsSourceDetailAll WITH(NOLOCK)
	WHERE LastViewDate > @StartTime AND LastViewDate < @EndTime
	AND LEN(SubSiteID) < = 4
	GROUP BY SubSiteID, SiteType
	
	--县级市 访问的访客数、IP数
	INSERT INTO bsSourceCount (SubSiteID, CountDate, VisitorCount, IPCount, SiteType)
	SELECT SUBSTRING(CONVERT(VARCHAR(10), SubSiteID), 0, 2) + '0000', @CountDate, COUNT(DISTINCT SessionID), COUNT(DISTINCT IP), 1
	FROM bsSourceDetailAll
	WHERE LastViewDate > @StartTime AND LastViewDate < @EndTime
	AND LEN(SubSiteID)=6
	GROUP BY SUBSTRING(CONVERT(VARCHAR(10), SubSiteID), 0, 2) 
	
	--省份、城市、县级市 访问的来源总数
	UPDATE bsSourceCount
	SET RefererCount = VisitorCount
	WHERE CountDate = @CountDate
	
	--省份 城市 只访问一个页面的访客数量
	UPDATE a
	SET a.VisitOnePageCount = b.cnt
	FROM bsSourceCount a, 
	(	SELECT SubSiteID, SiteType , COUNT(*) cnt
		FROM bsSourceDetailAll WITH(NOLOCK) 
		WHERE LastViewDate > @StartTime AND LastViewDate < @EndTime
		AND LEN(SubSiteID) < = 4
		AND ViewNumber = 1
		GROUP BY SubSiteID, SiteType 
	) b
	WHERE a.SubSiteID = b.SubSiteID
	AND a.SiteType = b.SiteType
	AND a.CountDate = @CountDate
	
	
	--县级站 只访问一个页面的访客数量
	UPDATE a
	SET a.VisitOnePageCount = b.cnt
	FROM bsSourceCount a, 
		(SELECT SUBSTRING(CONVERT(VARCHAR(10), SubSiteID), 0, 2) + '0000' SubSiteID, SiteType , COUNT(*) cnt
		FROM bsSourceDetailAll WITH(NOLOCK) 
		WHERE LastViewDate > @StartTime AND LastViewDate < @EndTime
		AND LEN(SubSiteID)=6
		AND ViewNumber = 1
		GROUP BY SubSiteID, SiteType 
		) b
	WHERE a.SubSiteID = b.SubSiteID
	AND a.SiteType = b.SiteType
	AND a.CountDate = @CountDate

	--省份、城市 访问小时数合计 
	UPDATE a
	SET a.VisitTimeCount = b.tSum
	FROM bsSourceCount a, 
		(SELECT SubSiteID, SiteType, SUM(DATEDIFF(Second, AddDate, LastViewDate)) tSum
		FROM bsSourceDetailAll WITH(NOLOCK) 
		WHERE LastViewDate > @StartTime AND LastViewDate < @EndTime
		AND LEN(SubSiteID) < = 4
		GROUP BY SubSiteID, SiteType
		) b
	WHERE a.SubSiteID = b.SubSiteID
	AND a.SiteType = b.SiteType
	AND a.CountDate = @CountDate

	--县级市 访问小时数合计
	UPDATE a
	SET a.VisitTimeCount = b.tSum
	FROM bsSourceCount a, 
		(SELECT SUBSTRING(CONVERT(VARCHAR(10), SubSiteID), 0, 2) + '0000' AS SubSiteID, SiteType, 
			SUM(DATEDIFF(Second, AddDate, LastViewDate)) AS tSum
		FROM bsSourceDetailAll WITH(NOLOCK) 
		WHERE LastViewDate > @StartTime AND LastViewDate < @EndTime
		AND LEN(SubSiteID)=6 GROUP BY SUBSTRING(CONVERT(VARCHAR(10), SubSiteID), 0, 2) + '0000', SiteType
		) b
	WHERE a.SubSiteID = b.SubSiteID
	AND a.SiteType = b.SiteType
	AND a.CountDate = @CountDate
	
	--省份、城市 个人手机注册数	
	UPDATE A
	SET A.PersonRegisterCount = B.CNT
	FROM bsSourceCount A, 
		(SELECT dcSubSiteID, COUNT(*) CNT
		FROM PaMain
		WHERE (RegisterMode in (4, 5, 6) OR RegisterFrom > 1)
		AND AddDate > @StartTime 
		AND AddDate < @EndTime
		GROUP BY dcSubSiteID
		) b
	WHERE a.CountDate = @CountDate
	AND SiteType = 2
	AND A.SubSiteID = B.dcSubSiteID
	
	--省份、城市 个人电脑注册数
	UPDATE A
	SET A.PersonRegisterCount = B.CNT
	FROM bsSourceCount A, 
		(SELECT dcSubSiteID, COUNT(*) CNT
		FROM PaMain
		WHERE (RegisterMode = 1 OR RegisterType = 101)
		AND AddDate > @StartTime 
		AND AddDate < @EndTime
		GROUP BY dcSubSiteID
		) b
	WHERE a.CountDate = @CountDate
	AND SiteType = 1
	AND A.SubSiteID = B.dcSubSiteID
	
	--省份、城市 企业电脑注册数
	UPDATE A
	SET A.CompanyRegisterCount = B.CNT
	FROM bsSourceCount A, 
		(SELECT dcSubSiteID, COUNT(*) CNT
		FROM CpMain
		WHERE RegisterMode = 1
		AND RegDate > @StartTime 
		AND RegDate < @EndTime
		GROUP BY dcSubSiteID
		) b
	WHERE a.CountDate = @CountDate
	AND SiteType = 1
	AND A.SubSiteID = B.dcSubSiteID
	
	--搜索引擎数量
	UPDATE a
	SET a.SearchEngineCount = b.cnt
	FROM bsSourceCount a, 
		(SELECT SubSiteID, SiteType, SUM(HowMany) cnt
		FROM bsSourceRefererCount
		WHERE CountDate = @CountDate
		AND TypeID = 1
		Group By SubSiteID, SiteType
		) b
	WHERE a.SubSiteID = b.SubSiteID
	AND a.SiteType = b.SiteType
	AND a.CountDate = @CountDate
	
	--外部链接数量
	UPDATE a
	SET a.ExternalLinkCount = b.cnt
	FROM bsSourceCount a, 
		(SELECT SubSiteID, SiteType, SUM(HowMany) cnt
		FROM bsSourceRefererCount
		WHERE CountDate = @CountDate
		AND TypeID = 2
		Group By SubSiteID, SiteType
		) b
	WHERE a.SubSiteID = b.SubSiteID
	AND a.SiteType = b.SiteType
	AND a.CountDate = @CountDate
	
	--直接输入数量
	--省份、城市 访问的直接输入数量
	UPDATE a
	SET a.DirectInputCount = b.cnt
	FROM bsSourceCount a, 
		(SELECT SubSiteID, SiteType, COUNT(*) cnt
		FROM bsSourceDetailAll WITH(NOLOCK)
		WHERE LastViewDate > @StartTime 
		AND LastViewDate < @EndTime
		AND LEN(SubSiteID) < =4
		AND Referer = ''
		Group By SubSiteID, SiteType
		) b
	WHERE a.SubSiteID = b.SubSiteID
	AND a.SiteType = b.SiteType
	AND a.CountDate = @CountDate
	
	--县级市 访问的访直接输入数量
	UPDATE a
	SET a.DirectInputCount = b.cnt
	FROM bsSourceCount a, 
		(SELECT SUBSTRING(CONVERT(VARCHAR(10), SubSiteID), 0, 2) + '0000' AS SubSiteID, 1 AS SiteType, COUNT(*) cnt
		FROM bsSourceDetailAll WITH(NOLOCK)
		WHERE LastViewDate > @StartTime 
		AND LastViewDate < @EndTime
		AND LEN(SubSiteID)=6
		AND Referer = ''
		Group By SUBSTRING(CONVERT(VARCHAR(10), SubSiteID), 0, 2) + '0000', SiteType
		) b
	WHERE a.SubSiteID = b.SubSiteID
	AND a.SiteType = b.SiteType
	AND a.CountDate = @CountDate
	
	--百度竞价数量 BaiduBiddingCount
	--每天注册简历数
	UPDATE a
	SET BaiduBiddingResumeCount = B.resumeCnt
	FROM bsSourceCount a, 
		(SELECT province_Id, SUM(toDayResume) AS resumeCnt
		FROM Url
		WHERE BeginDate > @StartTime AND BeginDate < @EndTime
		GROUP BY province_Id
		) b
	WHERE a.SubSiteID = b.province_Id
	AND a.CountDate = @CountDate
	
	--每天注册单位数
	UPDATE a
	SET BaiduBiddingCompanyCount = B.companyCnt
	FROM bsSourceCount a, 
		(SELECT province_Id, SUM(toDayCompany) AS companyCnt
		FROM Url
		WHERE BeginDate > @StartTime AND BeginDate < @EndTime
		GROUP BY province_Id
		) b
	WHERE a.SubSiteID = b.province_Id
	AND a.CountDate = @CountDate
	
	--清空表数据 加入备份表
	--INSERT INTO bsSourceDetailBak SELECT * FROM bsSourceDetail 
	--TRUNCATE TABLE bsSourceDetail

	SELECT * INTO #t FROM bsSourceDetailAll WHERE LastViewDate > CONVERT(VARCHAR(10), GETDATE(), 120)
	TRUNCATE TABLE LogDb..bsSourceDetailAll
	INSERT INTO bsSourceDetailAll SELECT * FROM #t
END


GO
/****** Object:  StoredProcedure [dbo].[ProcCaActiveStatusByCaMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2014.10.30
--创建人：John
--说明：获取企业用户的当前状态
--#####################################################
CREATE PROCEDURE [dbo].[ProcCaActiveStatusByCaMainIDSelect]
(
	@caMainID INT
)
AS
BEGIN
	SELECT TOP 1 * FROM caActiveStatus WHERE camainid = @caMainID
END


GO
/****** Object:  StoredProcedure [dbo].[ProcCaActiveStatusUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ProcCaActiveStatusUpdate]
AS
BEGIN
	BEGIN TRY
		INSERT caActiveStatus(caMainId)
		SELECT DISTINCT caMainId FROM cpSession WHERE RefreshDate > DATEADD(MINUTE, -2, GETDATE())
		AND caMainId NOT IN(SELECT caMainId FROM caActiveStatus)
	END TRY
	BEGIN CATCH
	END CATCH

	DELETE caActiveStatus
	WHERE caMainId NOT IN(SELECT caMainId FROM cpSession WHERE RefreshDate > DATEADD(MINUTE, -2, GETDATE()))
	
	SELECT caMainId, MIN(Id) ID, MIN(InterviewDate) InterviewDate
	INTO #t
	FROM viPlan WHERE InterviewDate > GETDATE() AND IsCancel = 0
	GROUP BY caMainId

	UPDATE #t SET InterviewDate = (SELECT InterviewDate FROM viPlan WHERE ID= #t.Id)

	UPDATE caActiveStatus SET viPlanId = NULL, InterviewDate = NULL WHERE viPlanId > 0
	INSERT caActiveStatus(caMainId, IsOnline)
	SELECT caMainId, 0 FROM #t WHERE caMainId NOT IN(SELECT caMainId FROM caActiveStatus)
	
	UPDATE a
	SET a.viPlanId = b.Id,
		a.InterviewDate = b.InterviewDate
	FROM caActiveStatus a, #t b
	WHERE a.caMainId = b.caMainId

	UPDATE caActiveStatus SET IsVi = 0 WHERE caMainId NOT IN(SELECT caMainId FROM viRoom WHERE EndDate IS NULL) AND IsVi = 1
	UPDATE caActiveStatus SET IsVi = 1 WHERE caMainId IN(SELECT caMainId FROM viRoom WHERE EndDate IS NULL)
END









GO
/****** Object:  StoredProcedure [dbo].[procCaFavoratecaDailyGiftLogcaActiveLogSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--创建时间：2017-11-26
--创建人：harry
--说明：数据统计 --获取企业 收藏和下载的简历数量
--#####################################################
CREATE PROCEDURE [dbo].[procCaFavoratecaDailyGiftLogcaActiveLogSelect]
(
	@beginDate DATETIME,
	@endDate DATETIME,
	@caMainId INT,
	@cpMainId INT
)
AS
SET NOCOUNT ON
BEGIN
	CREATE TABLE #t(
	    viewInt INT NULL,
		downloadInt INT NULL,
        favourateInt INT NULL,
        intentionInt INT NULL,
        interviewInt INT NULL,
        addDate VARCHAR(10)
	)
     --生成数据表 
	IF @caMainId =0 
	BEGIN 
		--计算收藏的简历量 
	
		--更新#t
		INSERT INTO #t (favourateInt,addDate)
		SELECT COUNT (1) AS favourateInt, CONVERT(varchar(10),AddDate,23) AS addDate   
		FROM caFavorate 
		WHERE caMainId IN(select id FROM caMain WITH(NOLOCK) WHERE cpMainId = @cpMainId)
		AND AddDate BETWEEN @beginDate AND @endDate
		GROUP BY CONVERT(varchar(10),AddDate,23)   
		
		--计算下载的简历量 
		SELECT  CONVERT(varchar(10),AddDate,23) AS addDate, COUNT (1) AS downloadInt
		INTO #td11
		FROM caDailyGiftLog
		WHERE cpMainId = @cpMainId
		AND AddDate BETWEEN @beginDate AND @endDate
		GROUP BY CONVERT(varchar(10),AddDate,23) 
		
		SELECT  CONVERT(varchar(10),AddDate,23) AS addDate, COUNT (1) AS downloadInt
		INTO #td12
		FROM caActiveLog
		WHERE cpMainId = @cpMainId
		AND AddDate BETWEEN @beginDate AND @endDate
		GROUP BY CONVERT(varchar(10),AddDate,23)
		
		--更新#t,插入
		
        UPDATE #t
		SET downloadInt= ISNULL(#t.downloadInt,0)+#td11.downloadInt  
		FROM #td11
		WHERE #td11.addDate = #t.addDate
		
		INSERT INTO #t(downloadInt,addDate)
		SELECT downloadInt, addDate
		FROM #td11
		WHERE #td11.addDate NOT IN(SELECT addDate FROM #t WITH(NOLOCK))
                 
         DROP TABLE #td11
		--更新#t,插入
		UPDATE #t
		SET downloadInt= ISNULL(#t.downloadInt,0)+#td12.downloadInt  
		FROM #td12
		WHERE #td12.addDate = #t.addDate
		
		INSERT INTO #t(downloadInt,addDate)
		SELECT downloadInt, addDate
		FROM #td12
		WHERE #td12.addDate NOT IN(SELECT addDate FROM #t WITH(NOLOCK))
                 
         DROP TABLE #td12
         
         --计算浏览量
        SELECT  CONVERT(varchar(10),AddDate,23) AS addDate, COUNT (1) AS viewInt
		INTO #td13
		FROM CaCvViewLog
		WHERE caMainId IN(select id FROM caMain WITH(NOLOCK) WHERE cpMainId = @cpMainId)
		AND AddDate BETWEEN @beginDate AND @endDate
		GROUP BY CONVERT(varchar(10),AddDate,23) 
         --计算应聘邀请
         SELECT  CONVERT(varchar(10),AddDate,23) AS addDate, COUNT (1) AS viewInt
		INTO #td14
		FROM caCvIntention
		WHERE caMainId IN(select id FROM caMain WITH(NOLOCK) WHERE cpMainId = @cpMainId)
		AND AddDate BETWEEN @beginDate AND @endDate
		GROUP BY CONVERT(varchar(10),AddDate,23) 
         --计算面试通知
        SELECT  CONVERT(varchar(10),AddDate,23) AS addDate, COUNT (1) AS viewInt
		INTO #td15
		FROM exInterview
		WHERE JobID IN(
			SELECT ID FROM Job WITH(NOLOCK) 
			WHERE CpMainID = @cpMainID
			) 
		AND AddDate BETWEEN @beginDate AND @endDate
		GROUP BY CONVERT(varchar(10),AddDate,23) 
		--浏览，邀请，面试 数据更新插入
		UPDATE #t
		SET viewInt= ISNULL(#t.viewInt,0)+#td13.viewInt  
		FROM #td13
		WHERE #td13.addDate = #t.addDate
		
		INSERT INTO #t(viewInt,addDate)
		SELECT viewInt, addDate
		FROM #td13
		WHERE #td13.addDate NOT IN(SELECT addDate FROM #t WITH(NOLOCK))
		DROP TABLE #td13
		
		UPDATE #t
		SET intentionInt= ISNULL(#t.intentionInt,0)+#td14.viewInt  
		FROM #td14
		WHERE #td14.addDate = #t.addDate
		
		INSERT INTO #t(intentionInt,addDate)
		SELECT viewInt, addDate
		FROM #td14
		WHERE #td14.addDate NOT IN(SELECT addDate FROM #t WITH(NOLOCK))
		DROP TABLE #td14
		
		UPDATE #t
		SET interviewInt= ISNULL(#t.interviewInt,0)+#td15.viewInt  
		FROM #td15
		WHERE #td15.addDate = #t.addDate
		
		INSERT INTO #t(interviewInt,addDate)
		SELECT viewInt, addDate
		FROM #td15
		WHERE #td15.addDate NOT IN(SELECT addDate FROM #t WITH(NOLOCK))
		DROP TABLE #td15
		
	END
	ELSE 
	BEGIN 
		--计算收藏的简历量 
		INSERT INTO #t (favourateInt,addDate)
		SELECT COUNT (1) AS favourateInt, CONVERT(varchar(10),AddDate,23) AS addDate   
		FROM caFavorate  
		WHERE caMainId = @caMainId
		AND AddDate BETWEEN @beginDate AND @endDate
		GROUP BY CONVERT(varchar(10),AddDate,23) 
		  
		
		--计算下载的简历量 
		SELECT  CONVERT(varchar(10),AddDate,23) AS addDate, COUNT (1) AS downloadInt
		INTO #td21
		FROM caDailyGiftLog
		WHERE caMainId = @caMainId
		AND AddDate BETWEEN @beginDate AND @endDate
		GROUP BY CONVERT(varchar(10),AddDate,23) 
		
		SELECT  CONVERT(varchar(10),AddDate,23) AS addDate, COUNT (1) AS downloadInt
		INTO #td22
		FROM caActiveLog
		WHERE  caMainId = @caMainId
		AND AddDate BETWEEN @beginDate AND @endDate
		GROUP BY CONVERT(varchar(10),AddDate,23)
		
		--更新#t
		
        UPDATE #t
		SET downloadInt= ISNULL(#t.downloadInt,0)+#td21.downloadInt  
		FROM #td21
		WHERE #td21.addDate = #t.addDate
        
        INSERT INTO #t(downloadInt,addDate)
		SELECT downloadInt, addDate
		FROM #td21
		WHERE #td21.addDate NOT IN(SELECT addDate FROM #t WITH(NOLOCK))    
        
        DROP TABLE #td21
		--更新#t
		UPDATE #t
		SET downloadInt= ISNULL(#t.downloadInt,0)+#td22.downloadInt  
		FROM #td22
		WHERE #td22.addDate = #t.addDate
        
        INSERT INTO #t(downloadInt,addDate)
		SELECT downloadInt, addDate
		FROM #td22
		WHERE #td22.addDate NOT IN(SELECT addDate FROM #t WITH(NOLOCK))   
                
        DROP TABLE #td22
        
        --计算浏览量
        SELECT  CONVERT(varchar(10),AddDate,23) AS addDate, COUNT (1) AS viewInt
		INTO #td23
		FROM CaCvViewLog
		WHERE caMainId = @caMainId
		AND AddDate BETWEEN @beginDate AND @endDate
		GROUP BY CONVERT(varchar(10),AddDate,23) 
         --计算应聘邀请
         SELECT  CONVERT(varchar(10),AddDate,23) AS addDate, COUNT (1) AS viewInt
		INTO #td24
		FROM caCvIntention
		WHERE caMainId = @caMainId
		AND AddDate BETWEEN @beginDate AND @endDate
		GROUP BY CONVERT(varchar(10),AddDate,23) 
         --计算面试通知
        SELECT  CONVERT(varchar(10),AddDate,23) AS addDate, COUNT (1) AS viewInt
		INTO #td25
		FROM exInterview
		WHERE JobID IN(
			SELECT ID FROM Job WITH(NOLOCK) 
			WHERE CaMainID = @caMainId
			) 
		AND AddDate BETWEEN @beginDate AND @endDate
		GROUP BY CONVERT(varchar(10),AddDate,23) 
		--浏览，邀请，面试 数据更新插入
		UPDATE #t
		SET viewInt=  ISNULL(#t.viewInt,0)+#td23.viewInt  
		FROM #td23
		WHERE #td23.addDate = #t.addDate
		
		INSERT INTO #t(viewInt,addDate)
		SELECT viewInt, addDate
		FROM #td23
		WHERE #td23.addDate NOT IN(SELECT addDate FROM #t WITH(NOLOCK))
		DROP TABLE #td23
		
		UPDATE #t
		SET intentionInt=  ISNULL(#t.intentionInt,0)+#td24.viewInt  
		FROM #td24
		WHERE #td24.addDate = #t.addDate
		
		INSERT INTO #t(intentionInt,addDate)
		SELECT viewInt, addDate
		FROM #td24
		WHERE #td24.addDate NOT IN(SELECT addDate FROM #t WITH(NOLOCK))
		DROP TABLE #td24
		
		UPDATE #t
		SET interviewInt=  ISNULL(#t.interviewInt,0)+#td25.viewInt  
		FROM #td25
		WHERE #td25.addDate = #t.addDate
		
		INSERT INTO #t(interviewInt,addDate)
		SELECT viewInt, addDate
		FROM #td25
		WHERE #td25.addDate NOT IN(SELECT addDate FROM #t WITH(NOLOCK))
		DROP TABLE #td25
	END 
	
	SELECT * FROM #t ORDER BY addDate 
	DROP TABLE #t
END
SET NOCOUNT OFF
GO
/****** Object:  StoredProcedure [dbo].[procCaFeedbackHomepageSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--创建人 Lambo 20101010
--用于网站首页查询来信答复
CREATE PROCEDURE [dbo].[procCaFeedbackHomepageSelect]
(
	@dcProvinceID SMALLINT
)
AS
BEGIN
--	SELECT TOP 15 a.*, c.Name
--	FROM caFeedback a WITH(NOLOCK),
--	caMain b WITH(NOLOCK), 
--	cpMain c WITH(NOLOCK) 
--	WHERE a.caMainID = b.id 
--	AND b.cpMainID = c.id 
--	AND a.homepage = 1 
--	AND c.dcProvinceID = 32
--	AND c.Valid = 1 
--	AND b.IsDelete = 0
--	AND b.IsPAuse = 0
--	ORDER BY a.AddDate DESC

	SELECT TOP 15 ID newids,Preid ID,ProvinceID, Name, Message, AddDate, ReplyMan, ReplyMessage, ReplyDate
	FROM SearchDb..hpcaFeedbackDay WITH(NOLOCK)
	WHERE ProvinceID = @dcProvinceID
	ORDER BY newids
END














GO
/****** Object:  StoredProcedure [dbo].[procCaJobCvMatchInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
---------------------
--创建人 Peter
--时间 2016-10-13
--企业精确匹配数据插入
--peter 2018-4-2
CREATE PROCEDURE [dbo].[procCaJobCvMatchInsert]
AS
SET NOCOUNT ON
BEGIN
	DECLARE @Today DATETIME
	SET @Today = GETDATE()
	--将最近一个月内企业个人交互存放到临时表
	SELECT JobID, cvMainID 
	INTO #TCaJobCvOperateLog
	FROM caCvIntention WITH(NOLOCK) 
	WHERE Adddate > GETDATE() - 30 

	INSERT INTO #TCaJobCvOperateLog
	SELECT JobID, cvMainID 
	FROM exInterview WITH(NOLOCK)
	WHERE Adddate > GETDATE() - 30 
	AND NOT EXISTS(
		SELECT 'x' 
		FROM #TCaJobCvOperateLog 
		WHERE JobID = exInterview.JobID 
		AND cvMainID = exInterview.cvMainID
	)

	INSERT INTO #TCaJobCvOperateLog
	SELECT JobID, cvMainID 
	FROM exJobApply WITH(NOLOCK)
	WHERE Adddate > GETDATE() - 30 
	AND reply = 1
	AND NOT EXISTS(
		SELECT 'x' 
		FROM #TCaJobCvOperateLog 
		WHERE JobID = exJobApply.JobID 
		AND cvMainID = exJobApply.cvMainID
	)
	--排除海量操作
	DELETE FROM #TCaJobCvOperateLog
	WHERE JobID IN (
		SELECT JobID
		FROM #TCaJobCvOperateLog
		GROUP BY JobID
		HAVING COUNT(1) > 50
	)
	--排除受限制的企业操作
	DELETE FROM #TCaJobCvOperateLog
	WHERE JobID IN (
		SELECT ID
		FROM Job WHERE cpMainId IN(SELECT ID FROM cpMain WHERE IsLimitLogin = 9)
	)
	
	--需要推荐简历的职位
	CREATE TABLE #TJobNeedPush(JobID INT)
	
	--插入需要推送的职位
	
	DECLARE @t AS TABLE(EMailSendFreq INT)
	DECLARE @num INT
	SET @Num = 0
	WHILE @Num < 128
	BEGIN
		SET @Num = @Num + 1
		IF SUBSTRING(RIGHT('0000000' + dbo.Int2Bin(@Num), 7), DATEPART(WEEKDAY, GETDATE() - 1), 1) = '1'
			INSERT INTO @t SELECT @Num
	END
	
	INSERT INTO #TJobNeedPush
	SELECT ID 
	FROM Job a WITH(NOLOCK)
	WHERE EMailSendFreq IN(SELECT EMailSendFreq FROM @t)
	AND valid = 1
	
	SELECT CvMainID, COUNT(1) Cnt INTO #TCvOperateCount 
	FROM #TCaJobCvOperateLog 
	GROUP BY CvMainID

	--生成所有记录简历的近似简历
	CREATE TABLE #TCvSimilar1
	(
		MainCvID INT, 
		SimilarCvID INT, 
		MainCvCount INT, 
		SimilarCvCount INT, 
		Rate FLOAT
	)

	--按照操作简历记录分组
	INSERT INTO #TCvSimilar1(MainCvID, SimilarCvID, SimilarCvCount)
	SELECT b.CvMainID MainCvID, a.CvMainID SimilarCvID, COUNT(1) SimilarCvCount
	FROM #TCaJobCvOperateLog a, #TCaJobCvOperateLog b
	WHERE a.JobID = b.JobID
	GROUP BY a.CvMainID, b.CvMainID
	HAVING COUNT(1) > 1
	ORDER BY b.CvMainID, COUNT(1) DESC

	--删除无效的，以及自己的推荐
	DELETE FROM #TCvSimilar1 WHERE MainCvID = 0
	DELETE FROM #TCvSimilar1 WHERE MainCvID = SimilarCvID

	--修改总的简历操作次数
	UPDATE a SET a.MainCvCount = b.Cnt 
	FROM #TCvSimilar1 a, #TCvOperateCount b 
	WHERE a.MainCvID = b.CvMainID

	--排除无效简历 
	DELETE FROM #TCvSimilar1 WHERE Rate = 100
	DELETE FROM #TCvSimilar1 
	WHERE (
		SELECT Valid 
		FROM CvMain WITH(NOLOCK) 
		WHERE id = #TCvSimilar1.SimilarCvID
	) = 0

	--通过职位操作简历记录 匹配职位与简历
	SELECT a.JobID, b.SimilarCvID, b.MainCvCount, b.SimilarCvCount, b.Rate
	INTO #TCvSimilar2
	FROM #TCaJobCvOperateLog a, #TCvSimilar1 b
	WHERE a.CvMainID = b.MainCvID
	ORDER BY a.JobID, b.Rate DESC

	--删除已经操作的简历
	DELETE FROM a
	FROM #TCvSimilar2 a, #TCaJobCvOperateLog b
	WHERE a.JobID = b.JobID
	AND a.SimilarCvID = b.CvMainID

	--整理 一份简历被推荐给同一个职位的次数
	SELECT JobID, SimilarCvID, COUNT(1) Cnt
	INTO #TCvSimilar3
	FROM #TCvSimilar2
	GROUP BY JobID, SimilarCvID

	--排序整理  根据简历近似简历分析结束
	SELECT *, ROW_NUMBER() OVER(PARTITION BY JobID ORDER BY Cnt DESC) CvRank
	INTO #TJobSimilarCv
	FROM #TCvSimilar3

	--根据职位的近似职位推荐简历
	CREATE TABLE #TJobSimilar1
	(
		MainJobID INT, 
		SimilarJobID INT, 
		SimilarJobCount INT
	)

	--按照职位操作简历进行分组排序查询 分析职位近似职位
	INSERT INTO #TJobSimilar1(MainJobID, SimilarJobID, SimilarJobCount)
	SELECT a.JobID, b.JobID, COUNT(1)
	FROM #TCaJobCvOperateLog a, #TCaJobCvOperateLog b
	WHERE a.CvMainID = b.CvMainID
	AND a.JobID <> b.JobID
	GROUP BY a.JobID, b.JobID
	ORDER BY COUNT(1) DESC

	--按照近似的相同个数进行排序整理
	SELECT *, ROW_NUMBER() OVER(PARTITION BY MainJobID ORDER BY SimilarJobCount DESC) JobRank
	INTO #TJobSimilar2
	FROM #TJobSimilar1

	--DELETE FROM #TJobSimilar2 WHERE JobRank > 10
	--根据相似职位推荐 操作简历的相似推荐
	SELECT a.MainJobID, b.CvMainID, COUNT(1) Cnt
	INTO #TJobSimilar3
	FROM #TJobSimilar2 a, #TCaJobCvOperateLog b
	WHERE a.SimilarJobID = b.JobID
	GROUP BY a.MainJobID, b.CvMainID
	HAVING COUNT(1) > 1

	--插入到总的推荐列表
	INSERT INTO #TJobSimilarCv (JobID, SimilarCvID, Cnt)
	SELECT MainJobID, CvMainID, 1
	FROM #TJobSimilar3

	--删除曾经推荐过的
	DELETE FROM #TJobSimilarCv
	WHERE EXISTS(
		SELECT 'x' 
		FROM caJobCvMatch WITH(NOLOCK) 
		WHERE MatchCvMainID = #TJobSimilarCv.SimilarCvID
	)

	--删除已经操作的简历
	DELETE FROM a
	FROM #TJobSimilarCv a, #TCaJobCvOperateLog b
	WHERE a.JobID = b.JobID
	AND a.SimilarCvID = b.CvMainID

	--整理两种推荐方式推荐的所有简历
	SELECT JobID, SimilarCvID, SUM(Cnt) Cnt
	INTO #TJobSimilarCv1
	FROM #TJobSimilarCv
	GROUP BY JobID, SimilarCvID

	SELECT *, ROW_NUMBER() OVER(PARTITION BY JobID ORDER BY Cnt DESC) JobRank
	INTO #TJobSimilarCv2
	FROM #TJobSimilarCv1
	WHERE EXISTS(						--最后一次登录在一个月内，并且有效的简历
		SELECT 'x' 
		FROM cvMain a WITH(NOLOCK), paMain b WITH(NOLOCK)
		WHERE a.ID = #TJobSimilarCv1.SimilarCvID
		AND a.paMainID = b.ID
		AND b.LastLoginDate > GETDATE() - 30
		AND a.Valid = 1
	)

	--取10个推荐放到推荐表中
	INSERT INTO caJobCvMatch(JobID, MatchCvMainID, DataSource, AddDate)
	SELECT JobID, SimilarCvID, 1, GETDATE()
	FROM #TJobSimilarCv2
	WHERE JobID IN(SELECT JobID FROM #TJobNeedPush) --需要发送的职位
	AND JobRank <= 10
	GROUP BY JobID, SimilarCvID
	ORDER BY SUM(Cnt) DESC

	--为推荐不足10个的根据职位要求第一次匹配数据
	SELECT a.JobID, c.ResumeID CvMainID, ROW_NUMBER() OVER(PARTITION BY a.JobID ORDER BY COUNT(1) DESC) RowIndex
	INTO #TJobSimilarCvSearch
	FROM #TJobNeedPush a, JobPublish b WITH(NOLOCK), caJobResumePre c WITH(NOLOCK)
	WHERE a.JobID = b.ID
	AND (SELECT COUNT(1) FROM caJobCvMatch WHERE JobID = a.JobID AND AddDate > @Today) < 10
	AND b.dcRegionID = c.AtPlace
	AND c.Age BETWEEN b.MinAge AND b.MaxAge
	AND EXISTS(SELECT 'x' FROM cvJobType WHERE cvMainID = c.ResumeID AND dcJobTypeID = b.dcJobTypeID)
	GROUP BY a.JobID, c.ResumeID
	ORDER BY a.JobID

	DELETE FROM #TJobSimilarCvSearch
	WHERE EXISTS(
		SELECT 'x' 
		FROM caJobCvMatch WITH(NOLOCK) 
		WHERE JobID = #TJobSimilarCvSearch.JobID 
		AND MatchCvMainID = #TJobSimilarCvSearch.CvMainID
	)

	INSERT INTO caJobCvMatch (JobID, MatchCvMainID, DataSource, AddDate)
	SELECT JobID, CvMainID, 2, GETDATE()
	FROM #TJobSimilarCvSearch a
	WHERE RowIndex <= (SELECT (10 - COUNT(1)) FROM caJobCvMatch WHERE JobID = a.JobID AND AddDate > @Today)
	GROUP BY JobID, CvMainID

	--为推荐不足10个的根据职位要求第二次匹配数据 放宽地点要求 放宽职位类别
	SELECT a.JobID, c.ResumeID CvMainID, ROW_NUMBER() OVER(PARTITION BY a.JobID ORDER BY COUNT(1) DESC) RowIndex
	INTO #TJobSimilarCvSearch1
	FROM #TJobNeedPush a, JobPublish b WITH(NOLOCK), caJobResumePre c WITH(NOLOCK)
	WHERE a.JobID = b.ID
	AND (SELECT COUNT(1) FROM caJobCvMatch WHERE JobID = a.JobID AND AddDate > @Today) < 10
	AND LEFT(b.dcRegionID, 4) = LEFT(c.AtPlace, 4)
	AND c.Age BETWEEN b.MinAge AND b.MaxAge
	AND EXISTS(SELECT 'x' FROM cvJobType WHERE cvMainID = c.ResumeID AND LEFT(dcJobTypeID, 2) = LEFT(b.dcJobTypeID, 2))
	GROUP BY a.JobID, c.ResumeID
	ORDER BY a.JobID

	DELETE FROM #TJobSimilarCvSearch1
	WHERE EXISTS(
		SELECT 'x' 
		FROM caJobCvMatch WITH(NOLOCK) 
		WHERE JobID = #TJobSimilarCvSearch1.JobID 
		AND MatchCvMainID = #TJobSimilarCvSearch1.CvMainID
	)

	INSERT INTO caJobCvMatch(JobID, MatchCvMainID, DataSource, AddDate)
	SELECT JobID, CvMainID, 2, GETDATE()
	FROM #TJobSimilarCvSearch1 a
	WHERE RowIndex <= (SELECT (10 - COUNT(1)) FROM caJobCvMatch WHERE JobID = a.JobID)
	GROUP BY JobID, CvMainID
	
	--修改相关的推送信息
	UPDATE Job 
	SET LastEmailDate = GETDATE()
	WHERE ID IN(SELECT JobID FROM #TJobNeedPush)
	
	--papush 
	SELECT b.caMainId,count(1) cvcnt
	INTO #t
	FROM caJobCvMatch a LEFT JOIN job b ON a.jobId= b.Id 
	WHERE a.AddDate> @Today 
	GROUP BY b.caMainId
	
	DELETE FROM #t WHERE cvcnt=0

	INSERT INTO paPushLog(paMainID, PushMessage, PushType)
	SELECT a.caMainID, '今天给您推荐了'+CONVERT(char(5),a.cvcnt)+'个简历了解一下→', 12 
	FROM #t a,caIOSBind b
	WHERE a.caMainId=b.caMainId
	
	--删除所有临时表
	DROP TABLE #t
	DROP TABLE #TCaJobCvOperateLog
	DROP TABLE #TJobNeedPush
	DROP TABLE #TCvOperateCount
	DROP TABLE #TCvSimilar1
	DROP TABLE #TCvSimilar2
	DROP TABLE #TCvSimilar3
	DROP TABLE #TJobSimilarCv
	DROP TABLE #TJobSimilarCv1
	DROP TABLE #TJobSimilarCv2
	DROP TABLE #TJobSimilar1
	DROP TABLE #TJobSimilar2
	DROP TABLE #TJobSimilar3
	DROP TABLE #TJobSimilarCvSearch
	DROP TABLE #TJobSimilarCvSearch1
END



GO
/****** Object:  StoredProcedure [dbo].[ProcCaJobResumePreRebuild]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ProcCaJobResumePreRebuild]
AS
SET NOCOUNT ON
BEGIN
	TRUNCATE TABLE caJobResumePre

	INSERT INTO caJobResumePre(ResumeID, Name, Sex, Age, BirthDay, EduLevel, Experience, JobType, AtPlace, LastLoginDate, paMainId, SecondId)
	SELECT a.id resumeid, b.name name, b.gender sex, dbo.BirthToAge(b.birthday) age,
		b.birthday, a.degree edulevel, a.relatedworkyears experience, 
		dbo.GetCvJobType(a.id) jobtype, b.LivePlace AtPlace, b.LastLoginDate, a.paMainId, LOWER(a.SecondId)
	FROM cvMain a with(nolock), paMain b with(nolock)
	WHERE a.paMainID=b.ID 
		And b.lastlogindate>getdate()-30 
		And a.valid > 0 

	UPDATE a SET a.AtPlaceDesc = b.Description
	FROM caJobResumePre a WITH(NOLOCK), dcRegion b WITH(NOLOCK)
	WHERE LEFT(a.AtPlace, 2) = b.ID

	UPDATE a SET a.AtPlaceDesc = a.AtPlaceDesc + b.Description
	FROM caJobResumePre a WITH(NOLOCK), dcRegion b WITH(NOLOCK)
	WHERE a.AtPlace = b.ID
	AND Len(A.AtPlace) > 2
	AND LEFT(a.AtPlace, 4) = b.ID

	TRUNCATE TABLE caJobResumePreJobType
	INSERT INTO caJobResumePreJobType
	SELECT * FROM cvJobType WHERE cvMainID IN(SELECT ResumeID FROM caJobResumePre)
END














GO
/****** Object:  StoredProcedure [dbo].[ProcCaLoginLogByWeiXinInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ProcCaLoginLogByWeiXinInsert]
(
	@FromUserName VARCHAR(100)
)
AS
SET NOCOUNT ON
BEGIN
	DECLARE @caMainId INT
	SELECT @caMainId = caMainId FROM wxFans WITH(NOLOCK) WHERE OpenId = @FromUserName
	IF @caMainId IS NULL
	BEGIN
		SELECT @caMainId = paMainId FROM palogincontact WITH(NOLOCK) WHERE OpenId = @FromUserName AND ContactType = 101
		IF @caMainId IS NULL
		RETURN
	END

	DECLARE @Ip VARCHAR(31), @AddDate SMALLDATETIME, @Name NVARCHAR(100)
	SELECT TOP 1 @AddDate = AddDate, @ip = LoginIp FROM caLoginLog WITH(NOLOCK)
	WHERE caMainId = @caMainId ORDER BY Id DESC

	SELECT @Name = Name FROM cpMain WITH(NOLOCK) WHERE Id = (SELECT cpMainId FROM caMain WITH(NOLOCK) WHERE Id = @caMainId)

	IF @Ip IS NULL
	BEGIN
		INSERT INTO caLoginLog
		SELECT @caMainId, @Name, '', '', '', GETDATE(), 'weixin', 10
		RETURN
	END
	DECLARE @cpMainId INT, @LastLoginDate DATETIME
	SELECT @cpMainId = Id, @LastLoginDate = LastLoginDate FROM cpMain WITH(NOLOCK) WHERE Id = (SELECT cpMainId FROM caMain WITH(NOLOCK) WHERE id = @caMainId)
	IF @LastLoginDate < CONVERT(VARCHAR(10), GETDATE(), 120)
	BEGIN
		INSERT INTO caLoginLog
		SELECT @caMainId, @Name, '', '', '未记录', GETDATE(), 'weixin', 11
		UPDATE cpMaIn SET LastLoginDate = GETDATE(), RefreshDate = GETDATE() WHERE Id = @cpMainId
		UPDATE Job SET RefreshDate = GETDATE() WHERE caMainId = @caMainId AND Valid = 1
	END
END

GO
/****** Object:  StoredProcedure [dbo].[procCaMainByUserNameLowerSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.10
--创建人：NICK
--说明：
--#####################################################
CREATE PROCEDURE [dbo].[procCaMainByUserNameLowerSelect]
(
	@UserName VARCHAR(50)
)
AS
BEGIN
	SELECT TOP 1 cpMainID FROM camain WHERE UserNameLower = @UserName
END


GO
/****** Object:  StoredProcedure [dbo].[ProcCampusBrochure30Select]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.29
--创建人：Nick
--说明：获取最新校园招聘结束时间在30天内的，取120条，点击量前15的加hot
--#####################################################
CREATE PROCEDURE [dbo].[ProcCampusBrochure30Select]
(
	@ProvinceID INT
)
AS
BEGIN TRY
	SELECT TOP 120 a.id, a.CompanyID, a.Title,0 IsHot 
	FROM marketdb..CampusBrochure a WITH(NOLOCK),
	marketdb..CampusBrochureSite b WITH(NOLOCK) 
	WHERE a.EndDate>Getdate() 
	AND a.id = b.CampusBrochure 
	AND b.dcSubSiteID = @provinceID
	ORDER BY CASE a.id WHEN 7866 THEN 1 WHEN 7865 THEN 1 WHEN 7870 THEN 1 ELSE 2 END ,a.OrderBy ,AddDate DESC 
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[procCampusBrochureByConditionSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.10
--创建人：Nick
--说明：根据条件获取 校园招聘信息
--#####################################################
CREATE PROCEDURE [dbo].[procCampusBrochureByConditionSelect]
(
	@Condition VARCHAR(MAX)
)
AS
BEGIN
	DECLARE @SQL VARCHAR(MAX)
	SET @SQL  = '
	SELECT top 5 A.id, a.Title 
	FROM marketdb..CampusBrochure a WITH(nolock),marketdb..CampusBrochureSite b WITH(nolock)
	WHERE a.EndDate>Getdate() 
	AND a.id = b.CampusBrochure '+@Condition+'
	ORDER BY CASE a.id WHEN 7866 THEN 1 WHEN 7865 THEN 1 WHEN 7870 THEN 1 ELSE 2 END , AddDate DESC '
	EXEC(@SQL)
END


GO
/****** Object:  StoredProcedure [dbo].[ProcCampusBrochureByIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.28
--创建人：Nick
--说明：通过ID获取公司信息数据
--#####################################################
CREATE PROCEDURE [dbo].[ProcCampusBrochureByIDSelect]
(
	@ID INT
)
AS
BEGIN TRY
	
	--修改点击量
	UPDATE marketdb..CampusBrochure 
	SET ClickNumber=ClickNumber+1 
	WHERE id = @ID

	SELECT TOP 1 a.*,b.ID CompanyID,b.CompanyName,b.Description CompanyDescription,
	d.Description RegionName,e.Description Industry,b.Homepage 
	FROM marketdb..CampusBrochure a WITH(NOLOCK) ,marketdb..CampusCompany b WITH(NOLOCK) ,
	dcRegion d WITH(NOLOCK) ,dcIndustry e WITH(NOLOCK) 
	WHERE a.CompanyID = b.ID 
	AND b.dcRegionID = d.id 
	AND b.dcIndustryID = e.ID  
	AND a.ID = @ID
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[ProcCampusBrochureByIndustryIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Mice 123>
-- Create date:	<2014-11-25>
-- Description:	<按照industryids查询招聘简章>
-- Modify:harry
-- 修改取前210条，不再按照行业取,优先显示未过期，然后显现过期的
-- =============================================
CREATE PROCEDURE [dbo].[ProcCampusBrochureByIndustryIDSelect]
(
	@ProvinceID INT,
	@IndustryID VARCHAR(200)
)
AS
--INSERT INTO procLog SELECT 'ProcCampusBrochureByIndustryIDSelect', @ProvinceID, GETDATE()
BEGIN
	SELECT TOP 210 c.dcIndustryID, a.id, a.CompanyID, a.Title, 0 IsHot , a.ClickNumber
	FROM MarketDb..CampusBrochure a WITH(NOLOCK),
		MarketDb..CampusBrochureSite b WITH(NOLOCK) ,
		MarketDb..campuscompany c WITH(NOLOCK)
	WHERE  a.id = b.CampusBrochure  AND a.CompanyID = c.id
	AND b.dcSubSiteID = @ProvinceID 
	--AND c.dcIndustryID  IN ( SELECT a FROM dbo.fnsplit(@IndustryID,',')  )
	ORDER BY a.EndDate DESC, a.id, a.OrderBy , a.AddDate DESC
END

 
GO
/****** Object:  StoredProcedure [dbo].[procCampusBrochureByKeyWordSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.5
--创建人：NICK
--说明：
--#####################################################
CREATE PROCEDURE [dbo].[procCampusBrochureByKeyWordSelect]
(
	@keyword VARCHAR(50)
)
AS
BEGIN
	SELECT a.id,a.Title,a.addDate 
	FROM marketdb..CampusBrochure a WITH(NOLOCK) ,
	marketdb..CampusBrochureSite b WITH(NOLOCK) 
	WHERE a.EndDate>Getdate() and a.id = b.CampusBrochure
	AND a.Title LIKE '%'+@keyword+'%'
	ORDER BY a.AddDate DESC
END


GO
/****** Object:  StoredProcedure [dbo].[procCampusBrochureByProvinceIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.10
--创建人：Nick
--说明：根据省份获取校园招聘信息
--#####################################################
CREATE PROCEDURE [dbo].[procCampusBrochureByProvinceIDSelect]
(
	@ProvinceID INT
)
AS
BEGIN
	SELECT top 5 A.id, a.Title FROM marketdb..CampusBrochure a WITH(nolock),marketdb..CampusBrochureSite b WITH(nolock)
	WHERE a.EndDate>Getdate() 
	AND a.id = b.CampusBrochure 
	AND b.dcSubSiteID = @ProvinceID
	ORDER BY CASE a.id WHEN 7866 THEN 1 WHEN 7865 THEN 1 WHEN 7870 THEN 1 ELSE 2 END , AddDate DESC
END


GO
/****** Object:  StoredProcedure [dbo].[ProcCampusBrochureFamousSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.29
--创建人：Nick
--说明：获取64条名企招聘简章
--#####################################################
CREATE PROCEDURE [dbo].[ProcCampusBrochureFamousSelect]
(
	@ProvinceID INT
)
AS
BEGIN TRY
	SELECT TOP 64 a.id , a.CompanyID ,a.Title,0 IsHot 
	FROM marketdb..CampusBrochure a WITH(NOLOCK),
	marketdb..CampusBrochureSite b WITH(NOLOCK) 
	WHERE a.EndDate>Getdate() 
	AND a.id = b.CampusBrochure 
	AND b.dcSubSiteID = @provinceID
	ORDER BY CASE a.id WHEN 7866 THEN 1 WHEN 7865 THEN 1 WHEN 7870 THEN 1 ELSE 2 END ,a.OrderBy ,AddDate DESC 
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[ProcCampusBrochureHotSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.29
--创建人：Nick
--说明：获取热门企业招聘
--#####################################################
CREATE PROCEDURE [dbo].[ProcCampusBrochureHotSelect]
(
	@ProvinceID INT
)
AS
BEGIN TRY
	SELECT TOP 10 a.id,a.Title 
	FROM marketdb..CampusBrochure a WITH(NOLOCK),marketdb..CampusBrochureSite b WITH(NOLOCK)
	WHERE a.id = b.CampusBrochure 
	AND a.EndDate < GETDATE()+30 
	AND b.dcSubSiteID = @ProvinceID
	ORDER BY AddDate
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[ProcCampusBrochureListSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Mice 123>
-- Create date: <2014-11-26>
-- Description:	<查询该省份下符合行业的未举行的招聘简章>
-- =============================================
CREATE PROCEDURE [dbo].[ProcCampusBrochureListSelect]
(
	@ProvinceID INT,
	@IndustryID VARCHAR(200)
)
AS
BEGIN
	SELECT c.dcIndustryID, a.id, a.CompanyID, a.Title, 0 IsHot, a.ClickNumber
	FROM marketdb..CampusBrochure a WITH(NOLOCK),
		marketdb..CampusBrochureSite b WITH(NOLOCK) ,
		marketdb..campuscompany c WITH(NOLOCK)
	WHERE a.EndDate > Getdate() 
	AND a.id = b.CampusBrochure
	AND a.CompanyID = c.id
	AND b.dcSubSiteID = @ProvinceID 
	AND c.dcIndustryID IN(SELECT a FROM dbo.fnsplit(@IndustryID, ','))
	ORDER BY a.id , a.OrderBy , a.AddDate DESC
END


GO
/****** Object:  StoredProcedure [dbo].[ProcCampusBrochureOtherByIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.28
--创建人：Nick
--说明：通过公司ID获取公司其他招聘简章
--#####################################################
CREATE PROCEDURE [dbo].[ProcCampusBrochureOtherByIDSelect]
(
	@CompanyID INT
)
AS
BEGIN TRY
	SELECT TOP 8 a.*,b.Id CompanyID,a.Adddate,b.CompanyName,b.Description CompanyDescription,
	d.Description RegionName,e.Description Industry,b.Homepage 
	FROM marketdb..CampusBrochure a WITH(NOLOCK) ,marketdb..CampusCompany b WITH(NOLOCK) ,
	dcRegion d WITH(NOLOCK) ,dcIndustry e WITH(NOLOCK) 
	WHERE a.CompanyID = b.ID 
	AND b.dcRegionID = d.id 
	AND b.dcIndustryID = e.ID  
	AND a.CompanyID = @CompanyID 
	ORDER BY a.Adddate DESC
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[ProcCampusBrochurePeriodSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.29
--创建人：Nick
--说明：获取公司往期招聘简章
--#####################################################
CREATE PROCEDURE [dbo].[ProcCampusBrochurePeriodSelect]
(
	@ProvinceID INT,
	@CompanyID INT
)
AS
BEGIN TRY
	SELECT a.* 
	FROM marketdb..CampusBrochure a WITH(NOLOCK),marketdb..CampusBrochureSite b WITH(NOLOCK)
	WHERE a.ID = b.CampusBrochure 
	AND a.EndDate<Getdate() 
	AND b.dcSubSiteID = @ProvinceID 
	AND a.CompanyId = @CompanyID
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[procCampusByHomePageList]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################
--创建人： Lambo	
--创建时间：20120628
--用于首页校园招聘宣讲会
--######################################
CREATE PROCEDURE [dbo].[procCampusByHomePageList] 
(
	@ProvinceID SMALLINT
)
AS
BEGIN
	SET NOCOUNT ON
	SELECT TOP 1 ImageFile,alt FROM fpHomePageImage WITH(NOLOCK)
	WHERE ImageType = 5
	AND dcProvinceID = LEFT(@ProvinceID, 2)
	ORDER BY AddDate DESC

	SELECT TOP 5 * FROM SearchDb..HPCampus WITH(NOLOCK)
	WHERE provinceID = LEFT(@ProvinceID, 2)
	ORDER BY ID
	
	SET NOCOUNT OFF
END



GO
/****** Object:  StoredProcedure [dbo].[procCampusByHomePageListNew]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[procCampusByHomePageListNew] 
(
	@ProvinceID SMALLINT
)
AS
BEGIN
	SET NOCOUNT ON
	SELECT TOP 1 ImageFile,alt FROM fpHomePageImage WITH(NOLOCK)
	WHERE ImageType = 5
	AND dcProvinceID = LEFT(@ProvinceID, 2)
	ORDER BY AddDate DESC

	SELECT TOP 15 * FROM SearchDb..HPCampus WITH(NOLOCK)
	WHERE  provinceID =LEFT(@ProvinceID, 2)
	ORDER BY ID
	
	SET NOCOUNT OFF
END


GO
/****** Object:  StoredProcedure [dbo].[ProcCampusCollectInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ProcCampusCollectInsert]
(
	@InfoText NVARCHAR(Max)
)
AS
BEGIN
	DECLARE @SourceType VARCHAR(1),
		@HostDate VARCHAR(50),
		@HostTime VARCHAR(50),
		@CompanyName VARCHAR(50),
		@SchoolName VARCHAR(50),
		@HostAddress VARCHAR(50),
		@CityName VARCHAR(10),
		@i AS INT,
		@Sql VARCHAR(MAX)

	SET @SourceType = LEFT(@InfoText, 1)
	IF @SourceType NOT IN('1', '2', '3')
	BEGIN
		SELECT 0 [RowCount]
		RETURN
	END
	SET @InfoText = RIGHT(@InfoText, LEN(@InfoText) - 1)

	DECLARE @campus AS TABLE(
		Id INT,
		[SourceType] [tinyint],
		[HostDate] [nvarchar](50),
		[HostTime] [nvarchar](50),
		[CompanyName] [nvarchar](50),
		[SchoolName] [nvarchar](50),
		[HostAddress] [nvarchar](50),
		[CityName] [nvarchar](10),
		RowNo int identity(1,1)
	)

	DECLARE @campus1 AS TABLE(
		[SourceType] [tinyint],
		[HostDate] [nvarchar](50),
		[HostTime] [nvarchar](50),
		[CompanyName] [nvarchar](50),
		[SchoolName] [nvarchar](50),
		[HostAddress] [nvarchar](50),
		[CityName] [nvarchar](10),
		RowNo INT
	)

	DECLARE @t1 AS TABLE (ID INT Identity(1, 1), infoText NVARCHAR(MAX))
	CREATE TABLE #t2 (ID INT Identity(1, 1), infoText NVARCHAR(100))
	
	INSERT @t1(infoText)
	SELECT * FROM dbo.FnSplit(@InfoText, '^')
 
	SET @i = 0
	WHILE EXISTS(SELECT 'x' FROM @t1 WHERE @i < Id)
	BEGIN
		SET @I = @I + 1
		SELECT TOP 1 @Sql = infoText FROM @t1 WHERE Id = @i
		TRUNCATE TABLE #t2
		INSERT INTO #t2(infoText)
		SELECT * FROM Dbo.FnSplit(@Sql, '|')
	
		IF @@RowCount = 6
		BEGIN
			SELECT @HostDate = infoText FROM #t2 WHERE Id = 1
			SELECT @HostTime = CASE WHEN infoText = '-' THEN '' ELSE infoText END FROM #t2 WHERE Id = 2
			SELECT @CompanyName = infoText FROM #t2 WHERE Id = 3
			SELECT @SchoolName = infoText FROM #t2 WHERE Id = 4
			SELECT @HostAddress = infoText FROM #t2 WHERE Id = 5
			SELECT @CityName = infoText FROM #t2 WHERE Id = 6

			INSERT INTO @campus(Id, SourceType, HostDate, HostTime, CompanyName, SchoolName, HostAddress, CityName)
			SELECT 0, @SourceType, @HostDate, @HostTime, @CompanyName, @SchoolName, @HostAddress, @CityName
		END
	END

	UPDATE a
	SET a.Id = b.Id
	FROM @campus a, CampusCollect b
	WHERE a.SourceType = b.SourceType
	AND a.HostDate = b.HostDate
	AND a.HostTime = b.HostTime
	AND a.CompanyName = b.CompanyName
	AND a.SchoolName = b.SchoolName
	AND a.HostAddress = b.HostAddress
	AND a.CityName = b.CityName
 
	INSERT INTO @campus1
	SELECT SourceType, HostDate, HostTime, CompanyName, SchoolName, HostAddress, CityName, MIN(RowNo) RowNo
	FROM @Campus
	WHERE Id = 0
	GROUP BY SourceType, HostDate, HostTime, CompanyName, SchoolName, HostAddress, CityName

	INSERT INTO CampusCollect(SourceType, HostDate, HostTime, CompanyName, SchoolName, HostAddress, CityName)
	SELECT SourceType, HostDate, HostTime, CompanyName, SchoolName, HostAddress, CityName
	FROM @Campus1
	ORDER BY RowNo

	UPDATE CampusCollect SET CheckDate = GETDATE() WHERE Id IN(SELECT ID FROM @Campus WHERE Id > 0)

	SELECT 1 [RowCount]
END


GO
/****** Object:  StoredProcedure [dbo].[ProcCampusCompanyByCompanyIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.28
--创建人：Nick
--说明：通过公司ID获取公司信息的数据
--#####################################################
CREATE PROCEDURE [dbo].[ProcCampusCompanyByCompanyIDSelect]
(
	@CompanyID INT
)
AS
BEGIN TRY
	SELECT a.*,b.Id CompanyID,b.CompanyName,b.Description CompanyDescription,d.Description RegionName,
	e.Description Industry,b.Homepage 
	FROM marketdb..CampusCompany b WITH(NOLOCK) 
	INNER JOIN dcRegion d WITH(NOLOCK) ON b.dcRegionID = d.id 
	INNER JOIN dcIndustry e WITH(NOLOCK) ON  b.dcIndustryID = e.ID  
	LEFT JOIN marketdb..CampusBrochure a WITH(NOLOCK) ON a.CompanyID = b.ID And EndDate>Getdate() 
	WHERE b.ID = @CompanyID 
	ORDER BY EndDate DESC
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[ProcCampusCompanyByProvinceIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.28
--创建人：Nick
--说明：通过公司ID获取公司信息的数据
--#####################################################
CREATE PROCEDURE [dbo].[ProcCampusCompanyByProvinceIDSelect]
(
	@ProvinceID INT
)
AS
BEGIN TRY
	SELECT TOP 1 a.*,b.Id CompanyID,b.CompanyName,b.Description 
	CompanyDescription,d.Description RegionName,e.Description Industry,b.Homepage 
	FROM marketdb..CampusBrochure a WITH(NOLOCK) ,marketdb..CampusCompany b WITH(NOLOCK),
	marketdb..CampusBrochureSite c WITH(NOLOCK),dcRegion d WITH(NOLOCK),dcIndustry e WITH(NOLOCK)
	WHERE a.CompanyID = b.ID 
	AND a.ID = c.CampusBrochure 
	AND b.dcRegionID = d.id 
	AND b.dcIndustryID = e.ID 
	AND c.dcSubsiteID = @ProvinceID 
	ORDER BY addDate DESC 
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[ProcCampusListTmpInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.29
--创建人：Nick
--说明：生成宣讲会信息 每小时生成一次
--#####################################################
CREATE PROCEDURE [dbo].[ProcCampusListTmpInsert]
AS
BEGIN
	DECLARE @Ok INT, @MaxID INT
	SELECT TOP 1 @MaxId = ID, @Ok = 0 FROM MarketDb..CampusPresentation WITH(NOLOCK) ORDER BY Id DESC
	IF EXISTS(SELECT 'x' FROM SearchDb..CampusListTmp WITH(NOLOCK) WHERE CampusPresentationID > @MaxID)
		SET @Ok = 1
	IF @Ok = 0
		SELECT @Ok = 1
		FROM MarketDb..CampusPresentation WITH(NOLOCK)
		WHERE BeginTime BETWEEN DATEADD(MINUTE, -5, GETDATE()) AND GETDATE()
		OR EndTime BETWEEN DATEADD(MINUTE, -5, GETDATE()) AND GETDATE()
 
	IF @Ok = 0
		RETURN
	SELECT TOP 0 * INTO #t FROM SearchDb..CampusListTmp
	--插入数据
	INSERT INTO #t
	SELECT b.Homepage,b.dcRegionID, a.CompanyID, d.Description RegionName, b.id SchoolID, b.SchoolName, 
		a.Address, c.CompanyName, a.BeginTime, a.EndTime, a.Id
	FROM MarketDb..CampusPresentation a WITH(NOLOCK),
		MarketDb..CampusSchool b WITH(NOLOCK), 
		MarketDb..CampusCompany c WITH(NOLOCK),
		MainDb..dcRegion d WITH(NOLOCK)  
	WHERE a.CompanyID = c.id 
	AND a.SchoolID = b.ID 
	AND b.dcRegionID = d.id
	ORDER BY a.BeginTime

	--删除数据
	TRUNCATE TABLE SearchDb..CampusListTmp
	INSERT SearchDb..CampusListTmp(Homepage, dcRegionID, CompanyID, RegionName, SchoolID, SchoolName, 
		Address, CompanyName, BeginTime, EndTime, CampusPresentationId)
	SELECT Homepage, dcRegionID, CompanyID, RegionName, SchoolID, SchoolName, 
		Address, CompanyName, BeginTime, EndTime, CampusPresentationId
	FROM #t
	ORDER BY ID
END


GO
/****** Object:  StoredProcedure [dbo].[ProcCampusPresentation10Select]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.29
--创建人：Nick
--说明：获取前10条重点高校宣讲会
--#####################################################
CREATE PROCEDURE [dbo].[ProcCampusPresentation10Select]
AS
BEGIN TRY
	SELECT a.* , b.Homepage, b.SchoolName 
	FROM marketdb..CampusPresentation a WITH(NOLOCK),marketdb..CampusSchool b WITH(NOLOCK) 
	WHERE  a.SchoolID = b.ID 
	AND a.id IN ( 
		SELECT TOP 10 MAX(id) 
		FROM marketdb..CampusPresentation a  WITH(NOLOCK)  
		WHERE a.beginTime > GETDATE()
	GROUP BY a.SchoolID ) 
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[ProcCampusPresentationPeriodSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.29
--创建人：Nick
--说明：获取公司往期宣讲会
--#####################################################
CREATE PROCEDURE [dbo].[ProcCampusPresentationPeriodSelect]
(
	@CompanyID INT
)
AS
BEGIN TRY
	SELECT a.*,b.Homepage,b.SchoolName 
	FROM marketdb..CampusPresentation a WITH(NOLOCK),marketdb..CampusSchool b WITH(NOLOCK)
	WHERE a.SchoolID = b.ID 
	AND EndTime<Getdate() 
	AND a.CompanyId = @CompanyID
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[ProcCampusPresentationSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.28
--创建人：Nick
--说明：获取校园宣讲会数据
--#####################################################
CREATE PROCEDURE [dbo].[ProcCampusPresentationSelect]
	@ProvinceID INT
AS
BEGIN TRY
	SELECT TOP 8 a.ID,b.id SchoolID,b.dcRegionID, c.ID CompanyID, Replace(d.Description,'市','') 
	RegionName, b.SchoolName, a.Address, c.CompanyName, BeginTime, EndTime, b.Homepage 
	FROM marketdb..CampusPresentation a WITH(NOLOCK),
	marketdb..CampusSchool b WITH(NOLOCK), 
	marketdb..CampusCompany c WITH(NOLOCK),
	dcRegion d WITH(NOLOCK) 
	WHERE a.CompanyID = c.id 
	AND a.SchoolID = b.ID 
	AND b.dcRegionID = d.id 
	AND EndTime>GETDATE() 
	ORDER BY CASE CHARINDEX(CONVERT(VARCHAR(10),@ProvinceID),b.dcRegionID) 
			WHEN 1 THEN 1 ELSE 2 END , 
	a.BeginTime, a.AddDate DESC
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[ProcCampusRecruitmentListSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.29
--创建人：Nick
--说明：获取学校的校园招聘会
--#####################################################
CREATE PROCEDURE [dbo].[ProcCampusRecruitmentListSelect]
(
	@CampusID INT,
	@PaMainID INT
)
AS
--INSERT INTO procLog SELECT 'ProcCampusRecruitmentListSelect', @PaMAinId, GETDATE()
BEGIN TRY
	SELECT TOP 500 a.ID, a.RecruitmentName,a.BeginDate,a.EndDate,a.CityID,a.RecruitmentPlaceId , a.CanBook, b.PlaceName ,
	(
		SELECT COUNT(*) FROM marketdb..rmplacephoto m WITH(NOLOCK) ,marketdb..rmmyplace n WITH(NOLOCK) 
		WHERE m.rmmyplaceid=n.id 
		AND n.rmdeptid=a.RecruitmentDeptID 
		AND n.rmplaceid=a.RecruitmentPlaceId
	) AS  photoCount , 
	(
		SELECT c.AddDate 
		FROM  Marketdb..RmPerson c WITH(NOLOCK) 
		WHERE c.RecruitmentID=a.id and c.paMainID = @PaMainID  
	) AS AddDate 
	FROM recruitment a WITH(NOLOCK) , recruitmentPlace b WITH(NOLOCK)
	WHERE b.id= a.RecruitmentPlaceId 
	AND a.BeginDate > DATEADD(YEAR,-1,GETDATE())  
	AND b.CampusSchoolID = @CampusID
	order by a.BeginDate DESC
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[ProcCampusSchoolBydcRegionIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.28
--创建人：Nick
--说明：根据regionID 获取学校信息
--#####################################################
CREATE PROCEDURE [dbo].[ProcCampusSchoolBydcRegionIDSelect]
(
	@RegionID INT
)
AS
BEGIN
	SELECT * 
	FROM MarketDb..CampusSchool 
	WHERE dcRegionID LIKE CONVERT(VARCHAR(10), @RegionID) + '%'
	AND EXISTS(SELECT 'X' FROM CampusListTmp WHERE SchoolID = MarketDb..CampusSchool.ID)
	ORDER BY OrderBy
END


GO
/****** Object:  StoredProcedure [dbo].[ProcCampusSchoolByIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.29
--创建人：Nick
--说明：返回学校信息
--#####################################################
CREATE PROCEDURE [dbo].[ProcCampusSchoolByIDSelect]
(
	@campusID INT
)
AS
BEGIN TRY
	SELECT TOP 1 * 
	FROM MarketDB..CampusSchool WITH(NOLOCK)  
	WHERE ID=@campusID
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[ProcCampusSchoolPartner12Select]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--##################################################### 
--创建时间：2014.10.29  --创建人：Nick  
--说明：获取前12条合作院校 
--sean update 2015-3-19
 --##################################################### 
CREATE PROCEDURE [dbo].[ProcCampusSchoolPartner12Select]
(
	@ProvinceID INT
)
AS
BEGIN
	IF @ProvinceID > 9999
		SET @ProvinceID = LEFT(@ProvinceID, 4)
	SELECT *
	FROM SearchDb..CampusSchoolPartner12 WITH(NOLOCK)
	WHERE dcProvinceID = @ProvinceID
	ORDER BY RowNo
END

GO
/****** Object:  StoredProcedure [dbo].[ProcCampusSchoolPartnerSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.29
--创建人：Nick
--说明：获取合作院校
--#####################################################
CREATE PROCEDURE [dbo].[ProcCampusSchoolPartnerSelect]
(
	@ProvinceID INT
)
AS
BEGIN TRY
	SELECT  a.* 
	FROM MarketDB..CampusSchool a WITH(NOLOCK) 
	WHERE EXISTS(
		SELECT 'x' 
		FROM marketdb..CampusPresentation b WITH(NOLOCK) 
		WHERE SchoolID = a.id
	) AND dcRegionID LIKE ''+CONVERT(VARCHAR(4),@ProvinceID)+'%'
	ORDER BY OrderBy, AddDate DESC 
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[ProcCampusTalkByCompanyIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.28
--创建人：Nick
--说明：获取企业校园宣讲会数据
--#####################################################
CREATE PROCEDURE [dbo].[ProcCampusTalkByCompanyIDSelect]
	@CompanyID INT
AS
BEGIN TRY
	select top 4 a.ID,b.dcRegionID, c.ID CompanyID, Replace(d.Description,'市','')
	RegionName, b.SchoolName,a.schoolid, a.Address, c.CompanyName, BeginTime, EndTime, b.Homepage 
	FROM marketdb..CampusPresentation a WITH(NOLOCK),
	marketdb..CampusSchool b WITH(NOLOCK), 
	marketdb..CampusCompany c WITH(NOLOCK),
	dcRegion d WITH(NOLOCK) 
	WHERE a.CompanyID = c.id 
	AND a.SchoolID = b.ID 
	AND b.dcRegionID = d.id 
	AND a.CompanyID = @CompanyID
	ORDER BY a.BeginTime DESC, a.AddDate
END TRY
BEGIN CATCH
	RETURN 0
END CATCH

GO
/****** Object:  StoredProcedure [dbo].[ProcCampusTalkByProvinceIDCompanyIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.28
--创建人：Nick
--说明：通过省ID和公司ID获取该公司在页面所在省的校园宣讲会内容
--#####################################################
CREATE PROCEDURE [dbo].[ProcCampusTalkByProvinceIDCompanyIDSelect]
(
	@ProvinceID INT, 
	@CompanyID INT
)
AS
SET NOCOUNT ON
BEGIN
	SELECT TOP 8 ID, dcRegionID, CompanyID, RegionName, SchoolName, SchoolID, Address, CompanyName,
		BeginTime, EndTime, Homepage
	FROM SearchDb..cpPreachTmp WITH(NOLOCK)
	WHERE dcProvinceId = @ProvinceID
	ORDER BY RowNo
END 

GO
/****** Object:  StoredProcedure [dbo].[ProcCampusTalkByProvinceIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.29
--创建人：Nick
--说明：取校园宣讲会数据
--#####################################################
CREATE PROCEDURE [dbo].[ProcCampusTalkByProvinceIDSelect]
(
	@ProvinceID INT
)
AS
BEGIN
	SELECT TOP 10 a.ID,b.id SchoolID,b.dcRegionID, c.ID CompanyID, Replace(d.Description,'市','')
	RegionName, b.SchoolName, a.Address, c.CompanyName, BeginTime, EndTime, b.Homepage 
	FROM marketdb..CampusPresentation a WITH(NOLOCK), 
	marketdb..CampusSchool b WITH(NOLOCK), 
	marketdb..CampusCompany c WITH(NOLOCK),
	dcRegion d WITH(NOLOCK) 
	WHERE a.CompanyID = c.id 
	AND a.SchoolID = b.ID 
	AND b.dcRegionID = d.id 
	AND EndTime > GETDATE() 
	ORDER BY CASE CHARINDEX(CONVERT(VARCHAR(4),@ProvinceID),b.dcRegionID) WHEN 1 THEN 1 ELSE 2 END , 
		a.BeginTime, a.AddDate DESC
END

GO
/****** Object:  StoredProcedure [dbo].[ProcCampusTalkInfoOneYearSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.29
--创建人：Nick
--说明：获取校园宣讲会信息 一年之内
--#####################################################
CREATE PROCEDURE [dbo].[ProcCampusTalkInfoOneYearSelect]
(
	@RegionID INT,
	@SchoolID INT,
	@ProvinceID INT
)
AS
--INSERT INTO procLog SELECT 'ProcCampusTalkInfoOneYearSelect', @Regionid, GETDATE()
BEGIN
	DECLARE @SQL VARCHAR(2000)
	SET @SQL = 'SELECT * FROM (SELECT '
	IF(@RegionID>0)
	BEGIN
		SET @SQL = @SQL + ' ROW_NUMBER() OVER(ORDER BY CASE CHARINDEX('''+CONVERT(VARCHAR(10),@RegionID)+''',b.dcRegionID) when 1 then 1 else 2 end ,case 
b.dcRegionID when '''+CONVERT(VARCHAR(10),@RegionID)+''' then 1 else 2 end,  BeginTime) as tline,'
	END
	ELSE
	BEGIN
		SET @SQL = @SQL +' ROW_NUMBER() OVER(ORDER BY CASE CHARINDEX('''+CONVERT(VARCHAR(10),@ProvinceID)+''',b.dcRegionID) when 1 then 1 else 2 end , 
BeginTime) as tline,'
	END
	SET @SQL = @SQL +' b.Homepage,b.dcRegionID, a.CompanyID, d.Description RegionName,b.id SchoolID, b.SchoolName, a.Address, c.CompanyName, BeginTime, EndTime '
	SET @SQL = @SQL +' FROM marketdb..CampusPresentation a WITH(NOLOCK),'
	SET @SQL = @SQL +' marketdb..CampusSchool b WITH(NOLOCK),'
	SET @SQL = @SQL +' marketdb..CampusCompany c WITH(NOLOCK),'
	SET @SQL = @SQL +' dcRegion d WITH(NOLOCK) '
	SET @SQL = @SQL +' WHERE EndTime>getdate() AND a.CompanyID = c.id AND a.SchoolID = b.ID AND b.dcRegionID = d.id'
	IF @SchoolID>0
	BEGIN
		SET @SQL = @SQL+' AND (b.ID = ' + CONVERT(VARCHAR(10),@SchoolID)+')'
	END
	IF (@RegionID>0) 
	BEGIN
		SET @SQL = @SQL+ ' AND b.dcRegionID like '''+CONVERT(VARCHAR(10),@RegionID)+'%'''
	END
	SET @SQL = @SQL+ ') as t1 union '
	SET @SQL = @SQL+ 'SELECT 999 as tline,b.Homepage,b.dcRegionID, a.CompanyID, d.Description RegionName,b.id SchoolID, b.SchoolName, a.Address, c.CompanyName, 
BeginTime, EndTime '
	SET @SQL = @SQL +' FROM marketdb..CampusPresentation a WITH(NOLOCK),'
	SET @SQL = @SQL +' marketdb..CampusSchool b WITH(NOLOCK),'
	SET @SQL = @SQL +' marketdb..CampusCompany c with(NOLOCK),'
	SET @SQL = @SQL +' dcRegion d WITH(NOLOCK) '
	
	SET @SQL = @SQL +' WHERE EndTime<getdate() AND BeginTime>'''+CONVERT(VARCHAR(20),DATEADD(YEAR,-1,GETDATE())) +''' AND a.CompanyID = c.id AND a.SchoolID = b.ID AND b.dcRegionID = d.id'
	IF @SchoolID>0
	BEGIN
		SET @SQL = @SQL+' AND (b.ID = '+CONVERT(VARCHAR(10),@SchoolID)+')'
	END
	SET @SQL = @SQL + ' ORDER BY tline,BeginTime desc'
	PRINT(@SQL)
	EXEC(@SQL)
END


GO
/****** Object:  StoredProcedure [dbo].[ProcCampusTalkInfoSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.29
--创建人：Nick
--说明：获取校园宣讲会信息
--修改：默认优先显示本省的（按照举办时间正序显示），后面是邻近四个省份的（按照举办时间正序显示），再后面是其他省（按照举办时间正序显示），最后就是本省过期的（按举办时间倒叙显示）
--修改人：Lucifer 2014.12.1
--#####################################################
CREATE PROCEDURE [dbo].[ProcCampusTalkInfoSelect]
(
	@RegionID INT,
	@SchoolID INT,
	@PageNo INT
)
AS
--INSERT INTO procLog select 'ProcCampusTalkInfoSelect', LTRIM(STR(@RegionId)) + '|' + LTRIM(STR(@SchoolId)) + '|' + LTRIM(STR(@PageNo)), GETDATE()
BEGIN
	IF ISNULL(@PageNo, 1) < 1
		SET @PageNo = 1

	DECLARE @t AS TABLE(
		ID [int] IDENTITY(1, 1),
		[Homepage] [varchar](200),
		[dcRegionID] [int],
		[CompanyID] [varchar](20),
		[RegionName] [nvarchar](50),
		[SchoolID] [int],
		[SchoolName] [nvarchar](50),
		[Address] [nvarchar](100),
		[CompanyName] [nvarchar](50),
		[BeginTime] [smalldatetime],
		[EndTime] [smalldatetime],
		PageNo INT,
		AllNumber INT
	)

	IF @SchoolID > 0
	BEGIN
		INSERT @t(Homepage, dcRegionID, CompanyID, RegionName, SchoolID, SchoolName, Address, CompanyName, BeginTime, EndTime)
		SELECT Homepage, dcRegionID, CompanyID, RegionName, SchoolID, SchoolName, Address, CompanyName, BeginTime, EndTime
		FROM CampusListTmp WITH(NOLOCK)
		WHERE SchoolId = @schoolId
		AND EndTime > GETDATE()
		ORDER BY BeginTime

		INSERT @t(Homepage, dcRegionID, CompanyID, RegionName, SchoolID, SchoolName, Address, CompanyName, BeginTime, EndTime)
		SELECT Homepage, dcRegionID, CompanyID, RegionName, SchoolID, SchoolName, Address, CompanyName, BeginTime, EndTime
		FROM CampusListTmp WITH(NOLOCK)
		WHERE SchoolId = @schoolId
		AND EndTime < GETDATE()
		ORDER BY BeginTime DESC

		UPDATE @t SET PageNo = (ID - 1) / 20 + 1
		UPDATE @t SET AllNumber = (SELECT COUNT(*) FROM @t)
		SELECT * FROM @t WHERE PageNo = @PageNo ORDER BY ID
	END
	ELSE
	BEGIN
		IF NOT EXISTS(SELECT 'x' FROM ShortDb..campusRegionTmp WITH(NOLOCK) WHERE ProvinceId = @RegionId AND AddDate > DATEADD(MINUTE, -10, GETDATE()))
		BEGIN
			DELETE FROM ShortDb..campusRegionTmp WHERE ProvinceId = @RegionId

			INSERT @t(Homepage, dcRegionID, CompanyID, RegionName, SchoolID, SchoolName, Address, CompanyName, BeginTime, EndTime)
			SELECT Homepage, dcRegionID, CompanyID, RegionName, SchoolID, SchoolName, Address, CompanyName, BeginTime, EndTime
			FROM CampusListTmp WITH(NOLOCK)
			WHERE dcRegionID LIKE LTRIM(STR(@RegionID)) + '%'
			AND EndTime > GETDATE()
			ORDER BY CASE WHEN Companyid = 29247 THEN 0 ELSE 1 END, BeginTime

			IF LEN(@RegionID) = 2
			BEGIN
				INSERT @t(Homepage, dcRegionID, CompanyID, RegionName, SchoolID, SchoolName, Address, CompanyName, BeginTime, EndTime)
				SELECT Homepage, dcRegionID, CompanyID, RegionName, SchoolID, SchoolName, Address, CompanyName, BeginTime, EndTime
				FROM CampusListTmp WITH(NOLOCK)
				WHERE LEFT(dcRegionID,2) IN(SELECT NearProvinceID FROM dcProvinceNear WITH(NOLOCK) WHERE dcProvinceID = @RegionID)
				AND EndTime > GETDATE()
				ORDER BY CASE WHEN Companyid = 29247 THEN 0 ELSE 1 END, BeginTime

				INSERT @t(Homepage, dcRegionID, CompanyID, RegionName, SchoolID, SchoolName, Address, CompanyName, BeginTime, EndTime)
				SELECT Homepage, dcRegionID, CompanyID, RegionName, SchoolID, SchoolName, Address, CompanyName, BeginTime, EndTime
				FROM CampusListTmp WITH(NOLOCK)
				WHERE LEFT(dcRegionID,2) NOT IN(SELECT NearProvinceID FROM dcProvinceNear WITH(NOLOCK) WHERE dcProvinceID = @RegionID)
				AND LEFT(dcRegionID, 2) <> @RegionID
				AND EndTime > GETDATE()
				ORDER BY CASE WHEN Companyid = 29247 THEN 0 ELSE 1 END, BeginTime
			END
			
			INSERT @t(Homepage, dcRegionID, CompanyID, RegionName, SchoolID, SchoolName, Address, CompanyName, BeginTime, EndTime)
			SELECT Homepage, dcRegionID, CompanyID, RegionName, SchoolID, SchoolName, Address, CompanyName, BeginTime, EndTime
			FROM CampusListTmp WITH(NOLOCK)
			WHERE dcRegionID LIKE LTRIM(STR(@RegionID)) + '%'
			AND EndTime < GETDATE()
			ORDER BY BeginTime DESC
		
			UPDATE @t SET PageNo = (ID - 1) / 20 + 1
			UPDATE @t SET AllNumber = (SELECT COUNT(*) FROM @t)
			INSERT INTO ShortDb..campusRegionTmp(Homepage, dcRegionID, CompanyID, RegionName, SchoolID, SchoolName, Address, CompanyName, BeginTime, EndTime, ProvinceId, RowId, PageNo, AllNumber, AddDate)
			SELECT Homepage, dcRegionID, CompanyID, RegionName, SchoolID, SchoolName, Address, CompanyName, BeginTime, EndTime, @RegionID, Id, PageNo, AllNumber, GETDATE() FROM @t
		END
		SELECT * FROM ShortDb..campusRegionTmp WITH(NOLOCK)
		WHERE ProvinceId = @RegionId
		AND PageNo = @PageNo 
		ORDER BY RowID
	END
END

GO
/****** Object:  StoredProcedure [dbo].[ProcCampusTalkNewByProvinceIDCompanyIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.28
--创建人：Nick
--说明：通过省ID和公司ID获取该公司在页面所在省的校园宣讲会内容
--#####################################################
CREATE PROCEDURE [dbo].[ProcCampusTalkNewByProvinceIDCompanyIDSelect]
(
	@ProvinceID INT,
	@CompanyID INT
)
AS
BEGIN TRY
	SELECT TOP 8 b.dcRegionID, c.ID CompanyID, REPLACE(d.Description,'市','') 
	RegionName, b.SchoolName, a.Address, c.CompanyName,b.ID SchoolID, BeginTime, EndTime, b.Homepage 
	FROM marketdb..CampusPresentation a WITH(NOLOCK), 
	marketdb..CampusSchool b WITH(NOLOCK), 
	marketdb..CampusCompany c WITH(NOLOCK), 
	dcRegion d WITH(NOLOCK) 
	WHERE a.CompanyID = c.id 
	AND a.SchoolID = b.ID 
	AND b.dcRegionID = d.id
	AND c.ID = @CompanyID
	ORDER BY a.BeginTime, a.AddDate DESC 
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[ProcCampusTopBannerSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.29
--创建人：Nick
--说明：新版校园招聘 图片列表
--#####################################################
CREATE PROCEDURE [dbo].[ProcCampusTopBannerSelect]
(
	@ProvinceID INT,
	@TypeID INT
)
AS
BEGIN TRY
	DECLARE @SQL VARCHAR(1000)
	SET @SQL = 'SELECT '
	IF @TypeID = 26
	BEGIN
		SET @SQL = @SQL + ' TOP 3 '
	END
	ELSE IF @TypeID = 27
	BEGIN
		SET @SQL = @SQL + ' TOP 6 '
	END
	SET @SQL = @SQL + ' * FROM AdverProject WITH(NOLOCK) '
	SET @SQL = @SQL + ' WHERE Valid=''1'' AND BeginTime < GETDATE() '
	SET @SQL = @SQL + ' AND EndTime > GETDATE() AND Province_Id = ' + CONVERT(VARCHAR(4),@ProvinceID)
	SET @SQL = @SQL + ' AND Type = ' + CONVERT(VARCHAR(4),@TypeID)
	SET @SQL = @SQL + ' ORDER BY OrderBy ASC'
	print (@SQL)
	EXEC(@SQL)
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[ProcCaOnlineBycaMainIdUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ProcCaOnlineBycaMainIdUpdate]
(
	@caMainID INT,
    @Status VARCHAR(5)
)
AS
BEGIN
	DELETE FROM caOnline WHERE caMainID = @caMainID
	IF @Status = '1'
		INSERT INTO caOnline VALUES(@caMainID, 1, 0, NULL, NULL, GETDATE())
END

GO
/****** Object:  StoredProcedure [dbo].[ProcCaOnlineStatusUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ProcCaOnlineStatusUpdate]
(
	@caMainIDs VARCHAR(MAX)
)
AS
BEGIN
	SELECT a ID INTO #t FROM dbo.fnSplit(@caMainIDs,',')
	UPDATE CaOnline SET IsOnline=1, RefreshDate=GETDATE() WHERE caMainID IN(SELECT ID FROM #t)
	INSERT caOnline(caMainId, IsOnline, IsVi, RefreshDate)
	SELECT Id, 1, 0, GETDATE() FROM #t WHERE ID NOT IN(SELECT caMainId FROM caOnline)
	UPDATE caOnline SET IsOnline = 0 WHERE caMainID NOT IN(SELECT ID FROM #t)
END






GO
/****** Object:  StoredProcedure [dbo].[ProcCaOnlineUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ProcCaOnlineUpdate]
AS
BEGIN
	SELECT caMainId, MIN(Id) ID, MIN(InterviewDate) InterviewDate
	INTO #t
	FROM viPlan WHERE InterviewDate > GETDATE() AND IsCancel = 0
	GROUP BY caMainId

	UPDATE #t SET InterviewDate = (SELECT InterviewDate FROM viPlan WHERE ID= #t.Id)

	UPDATE caOnline SET viPlanId = NULL, InterviewDate = NULL WHERE viPlanId > 0
	INSERT caOnline(caMainId, IsOnline)
	SELECT caMainId, 0 FROM #t WHERE caMainId NOT IN(SELECT caMainId FROM caOnline)
	
	UPDATE a
	SET a.viPlanId = b.Id,
		a.InterviewDate = b.InterviewDate
	FROM caOnline a, #t b
	WHERE a.caMainId = b.caMainId

	UPDATE caOnline SET IsVi = 0 WHERE caMainId NOT IN(SELECT caMainId FROM viRoom WHERE EndDate IS NULL) AND IsVi = 1
	UPDATE caOnline SET IsVi = 1 WHERE caMainId IN(SELECT caMainId FROM viRoom WHERE EndDate IS NULL)

	UPDATE caOnline SET isOnline = 0 WHERE RefreshDate < DATEADD(MINUTE,-2, GETDATE())
	DELETE caOnline WHERE RefreshDate < DATEADD(MINUTE, -7, GETDATE()) AND IsVi = 0 AND ViPlanId IS NULL

	UPDATE paOnline SET isOnline = 0 WHERE RefreshDate < DATEADD(MINUTE,-2, GETDATE())
	DELETE paOnline WHERE RefreshDate < DATEADD(MINUTE, -7, GETDATE())
END







GO
/****** Object:  StoredProcedure [dbo].[procCaorderByBalanceUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--###################################################3
--2011-9-1 sean 用于知名企业招聘 点击数 balance=clickcount
--###################################################3
CREATE PROCEDURE [dbo].[procCaorderByBalanceUpdate]
(
	@Id INT,
	@CompanyID INT,
	@JobId INT
)
AS
BEGIN
	SELECT @CompanyID = ISNULL(@CompanyID, 0), @JobId = ISNULL(@JobId, 0)
	IF @CompanyID = 0 AND @JobID = 0
		RETURN

	IF @CompanyID = 0 AND @JobID > 0
		SELECT @CompanyID = cpMainID FROM Job WITH(NOLOCK) WHERE ID = @JobID

	IF @CompanyID > 0
		UPDATE caOrder SET Balance = ISNULL(Balance, 0) + 1
		WHERE ID = @ID
		AND cpMainId = @CompanyID
		AND OrderType = 7
END














GO
/****** Object:  StoredProcedure [dbo].[procCaPageViewLogUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[procCaPageViewLogUpdate]
(
	@caMainID INT,
	@ViewPageType TINYINT				--1.应聘的简历 2.推荐的简历，3.面试通知答复 4.聊天
)
AS
SET NOCOUNT ON
BEGIN
	IF NOT EXISTS(SELECT 'x' FROM caPageViewLog WITH(NOLOCK) WHERE caMainId = @caMainID)
	BEGIN
		INSERT INTO caPageViewLog(caMainId,addDate,ApplyCvDate,RecommendCvDate,InterviewReplyDate) 
		VALUES(@caMainID, DATEADD(MINUTE, -10, GETDATE()), DATEADD(MINUTE, -10, GETDATE()), DATEADD(MINUTE, -10, GETDATE()), DATEADD(MINUTE, -10, GETDATE()))
		RETURN
	END
	
	IF @ViewPageType = 1
		UPDATE caPageViewLog SET ApplyCvDate = GETDATE(), ApplyCvCount = 0 WHERE caMainId = @caMainID 
	
	IF @ViewPageType = 2
		UPDATE caPageViewLog SET RecommendCvDate = GETDATE(), RecommendCvCount = 0 WHERE caMainId = @caMainID 
	
	IF @ViewPageType = 3
		UPDATE caPageViewLog SET InterviewReplyDate = GETDATE(), InterviewReplyCount = 0 WHERE caMainId = @caMainID 
	
	IF @ViewPageType = 4
		UPDATE caPageViewLog SET ChatCount = 0 WHERE caMainId = @caMainID 
END

GO
/****** Object:  StoredProcedure [dbo].[ProcCaSMSWaitSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----------------
--创建日期：2012-4-17
--创建人：lambo
--功能说明：企业汇总类短信发送。将marketdb..caSMSWait里的数据转入SmsMessageLog 
-----------------
CREATE PROCEDURE [dbo].[ProcCaSMSWaitSelect]
AS
BEGIN TRY
	IF oadb.dbo.IsWorkDate(getdate())<>1
		RETURN
	
	--删除今天已经登录过的企业的记录
	If DATEPART(HOUR,GETDATE())*100 + DATEPART(MINUTE,GETDATE()) <= 905
		DELETE FROM marketdb..cpSmsWait WHERE cpMainID IN(SELECT ID FROM cpMain WITH(NOLOCK) WHERE LastLoginDate > GETDATE() - 1)
	ELSE
		DELETE FROM marketdb..cpSmsWait WHERE cpMainID IN(SELECT ID FROM cpMain WITH(NOLOCK) WHERE LastLoginDate > DATEADD(MINUTE, -10, GETDATE()))

	SELECT TOP 20 * INTO #T FROM marketdb..cpSmsWait WHERE LastLoginTime < DATEPART(HOUR, GETDATE()) * 100 + DATEPART(MINUTE, GETDATE()) AND Msg > '' ORDER BY CASE WHEN SmsType > 16 THEN 0 ELSE 1 END, LastLoginTime
	INSERT SmsMessageLog(SendMan, ManagerUSerId, paMainId, caMainId, Mobile, MsgType, IsCat, Msg)
		SELECT 0, NULL, NULL, caMainID, Mobile, SmsType-1, 0,Msg FROM #T
	DELETE FROM marketdb..cpSMSWait WHERE ID IN (select ID FROM #T)
END TRY
BEGIN CATCH

END CATCH














GO
/****** Object:  StoredProcedure [dbo].[ProcCategoryIdByJobTypeIdSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.4
--创建人：John
--说明：根据子类别获取上级职位类别
--#####################################################
CREATE PROCEDURE [dbo].[ProcCategoryIdByJobTypeIdSelect]
(
	@JobTypeId INT
)
AS
BEGIN
	SELECT CategoryId FROM dcJobTypeMap WITH(NOLOCK) WHERE JobTypeId = @JobTypeId
END


GO
/****** Object:  StoredProcedure [dbo].[ProcChatOnlineByEndDateUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ProcChatOnlineByEndDateUpdate]
(
    @EndType TINYINT,
    @Evaluate TINYINT,
    @cvMainID INT,
    @caMainID INT,
    @ManageruserID SMALLINT
)
AS
--INSERT INTO procLog SELECT 'ProcChatOnlineByEndDateUpdate', @caMainID, GETDATE()
BEGIN
	IF @ManageruserID > 0 AND @caMainID > 0 AND @Evaluate > 0
	BEGIN
		DECLARE @Evaluation NVARCHAR(10)
		IF @Evaluate = 1
			SET @Evaluation = '满意'
		ELSE IF @Evaluate = 2
			SET @Evaluation = '一般'
		ELSE IF @Evaluate = 3
			SET @Evaluation = '不满意'

		INSERT INTO RtxNotifyLog (Receiver, RtxTitle, RtxMessage, SendType, ShowType, DelayTime) 
		    VALUES(@ManageruserID, '在线客服评价', '有企业对您的在线客服服务做出了评价，“' + @Evaluation + '”', 1, 0, 0)
	END
	
	IF EXISTS(SELECT 'X' FROM ChatOnline WHERE cvMainID = @cvMainID
		AND caMainID = @caMainID
		AND ManageruserID = @ManageruserID
		AND EndDate IS NULL)
	BEGIN
		UPDATE ChatOnline SET EndDate = GETDATE(),EndType = @EndType,Evaluate = @Evaluate
			WHERE cvMainID = @cvMainID
			AND caMainID = @caMainID
			AND ManageruserID = @ManageruserID
			AND EndDate IS NULL

		IF @cvMainID > 0
		BEGIN
			DECLARE @paMainID INT
			SELECT @paMainID = paMainID FROM cvMain WITH(NOLOCK) WHERE ID = @cvMainID
			IF NOT EXISTS(SELECT 'X' FROM ChatOnlineExchange WHERE UserID = @paMainID AND UserType = 0)
				INSERT INTO ChatOnlineExchange VALUES(@paMainID,0)
		END
		
		IF @caMainID > 0
		BEGIN
			IF NOT EXISTS(SELECT 'X' FROM ChatOnlineExchange WHERE UserID = @caMainID AND UserType = 1)
				INSERT INTO ChatOnlineExchange VALUES(@caMainID,1)
		END

		IF @ManageruserID > 0
		BEGIN
			IF NOT EXISTS(SELECT 'X' FROM ChatOnlineExchange WHERE UserID = @ManageruserID AND UserType = 3)
				INSERT INTO ChatOnlineExchange VALUES(@ManageruserID,3)
		END
	END
	ELSE
	BEGIN
		UPDATE ChatOnline SET EndType = 0,Evaluate = @Evaluate
		WHERE ID IN
		(
			SELECT TOP 1 ID FROM ChatOnline WHERE cvMainID = @cvMainID
			AND caMainID = @caMainID
			AND ManageruserID = @ManageruserID
			ORDER BY EndDate DESC
		)
	END
END

GO
/****** Object:  StoredProcedure [dbo].[ProcChatOnLineByManagerUserIDNoEndSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--Andy.Yin 2014-06-26
--获取客服的15日内联系人列表，或者曾经有留言的的联系人
-------------------------------
CREATE PROCEDURE [dbo].[ProcChatOnLineByManagerUserIDNoEndSelect]
(
    @UserID INT		--客服的ID
)
AS
--INSERT INTO procLog SELECT 'ProcChatOnLineByManagerUserIDNoEndSelect', @UserID, GETDATE()
BEGIN
	--首先获取联系人列表中的企业-------------------
	CREATE TABLE #CpUserList
	(
		ChatOnlineID INT,
		CaMainID INT,
		CvMainID INT,
		ManagerUserID INT,
		LastChatDate SMALLDATETIME,
		SumUnRead INT,
		IsHidden BIT	
	)
	--客服的联系人企业列表，有留言的
	INSERT INTO #CpUserList
		SELECT 
			MAX(a.ID),
			a.CaMainID,
			a.CvMainID,
			a.ManagerUserID,
			MAX(b.Adddate),
			COUNT(1),
			0
		FROM ChatOnline a, ChatOnlineLog b
		WHERE a.id = b.ChatOnlineID
			AND b.IsViewed = 0
			AND b.SenderType <> 3 --不是自己发送的
			AND a.ManagerUserID = @UserID
		GROUP BY a.CaMainID,a.CvMainID, a.ManagerUserID
		
	--客服联系人企业列表，未结束的回话
	INSERT INTO #CpUserList	
		SELECT 
			MAX(ID),
			CaMainID,
			CvMainID,
			ManagerUserID,
			(SELECT MAX(Adddate) FROM ChatOnlineLog WHERE ChatOnlineLog.ChatOnlineID IN(SELECT ID FROM ChatOnline a WHERE a.cvMainID = ChatOnline.cvMainID AND a.caMainID = ChatOnline.caMainID)),
			0,
			0
		FROM ChatOnline
		WHERE ManagerUserID = @UserID 
			AND EndDate IS NULL
			AND NOT EXISTS(SELECT 'X' FROM #CpUserList b WHERE b.cvMainID = ChatOnline.cvMainID AND b.caMainID = ChatOnline.caMainID)
		GROUP BY CaMainID,CvMainID, ManagerUserID		

	--最终联系人中企业列表
	SELECT 
		a.*,
		b.Name CpName,
		b.SecondID,
		c.Name UserName,
		c.cpMainID,
		dbo.GetCaOnlineStatus(a.caMainID) IsOnline
	FROM #CpUserList a, cpMain b, caMain c
	WHERE a.caMainID = c.ID
		AND b.ID = c.cpMainID
	ORDER BY a.LastChatDate DESC
	DROP TABLE #CpUserList
		
---------------首先获取联系人列表中的个人-------------------
	CREATE TABLE #PaUserList
	(
		ChatOnlineID INT,
		CaMainID INT,
		CvMainID INT,
		ManagerUserID INT,
		LastChatDate SMALLDATETIME,
		SumUnRead INT,
		IsHidden BIT	
	)
	--客服的联系人求职者列表，有留言的
	INSERT INTO #PaUserList
		SELECT 
			MAX(a.ID),
			a.CaMainID,
			a.CvMainID,
			a.ManagerUserID,
			MAX(b.Adddate),
			COUNT(1),
			0
		FROM ChatOnline a, ChatOnlineLog b
		WHERE a.id = b.ChatOnlineID
			AND b.IsViewed = 0
			AND b.SenderType <> 3 --不是客服发送的
			AND a.ManagerUserID = @UserID 
		GROUP BY a.CaMainID, a.CvMainID, A.ManagerUserID
	
	--客服联系人求职者列表，未结束的回话
	INSERT INTO #PaUserList	
		SELECT 
			MAX(ID),
			CaMainID,
			CvMainID,
			ManagerUserID,
			(SELECT MAX(Adddate) FROM ChatOnlineLog WHERE ChatOnlineLog.ChatOnlineID IN(SELECT ID FROM ChatOnline a WHERE a.cvMainID = ChatOnline.cvMainID AND a.caMainID = ChatOnline.caMainID)),
			0,
			0
		FROM ChatOnline
		WHERE ManagerUserID = @UserID 
			AND EndDate IS NULL
			AND NOT EXISTS(SELECT 'X' FROM #PaUserList b WHERE b.cvMainID = ChatOnline.cvMainID AND b.caMainID = ChatOnline.caMainID)
		GROUP BY CaMainID,CvMainID, ManagerUserID	

	--最终结果
	SELECT 
		a.*,
		b.Name PaName,
		b.ID PaMainID,		
		c.Name UserName,
		dbo.GetPaOnlineStatus(a.cvMainID) IsOnline
	FROM #PaUserList a, PaMain b, cvMain c
	WHERE a.cvMainID = c.ID
		AND b.ID = c.paMainID
	ORDER BY a.LastChatDate DESC

	--检查数据库，把曾经已经结束但是还有unread的记录都设置为已读
	UPDATE ChatOnlineLog 
	SET IsViewed=1 
	WHERE IsViewed=0 AND chatOnlineID IN (SELECT ID FROM ChatOnline where ManagerUserID=@UserID and EndDate is not null) 
	
	DROP TABLE #PaUserList
END








GO
/****** Object:  StoredProcedure [dbo].[ProcChatOnlineByMoveDelete]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ProcChatOnlineByMoveDelete]
AS
BEGIN
	select id into #t from chatonline where startdate < convert(varchar(10), getdate() - 366)

	INSERT INTO LogDb..ChatOnline
	select * FROM chatonline WHERE ID IN(SELECT ID FROM #t)
	INSERT INTO LogDb..ChatOnlineLog 
	select * FROM ChatOnlineLog WHERE ChatOnlineId IN(SELECT ID FROM #t)

	DELETE FROM chatonline WHERE ID IN(SELECT ID FROM #t)
END
GO
/****** Object:  StoredProcedure [dbo].[procChatOnlineByRefreshDateUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[procChatOnlineByRefreshDateUpdate]
(
	@UserID INT,
	@UserType TINYINT
)
AS
--INSERT INTO procLog SELECT 'procChatOnlineByRefreshDateUpdate', @UserID, GETDATE()
BEGIN
	DELETE FROM ChatOnlineExchange WHERE UserID=@UserID AND UserType=@UserType
	IF @UserType = 0
	BEGIN
		IF EXISTS(SELECT 'X' FROM paOnline WITH(NOLOCK) WHERE paMainID=@UserID)
			UPDATE paOnline SET IsOnline=1,RefreshDate=GETDATE() WHERE paMainID=@UserID
		ELSE
			INSERT INTO paOnline (paMainID, IsOnline, RefreshDate) VALUES(@UserID, 1, GETDATE())
		END
	ELSE IF @UserType = 1
	BEGIN
		IF EXISTS(SELECT 'X' FROM caOnline  WITH(NOLOCK) WHERE caMainID=@UserID)
			UPDATE caOnline SET IsOnline=1,RefreshDate = GETDATE() WHERE caMainID=@UserID
		ELSE
			INSERT INTO caOnline (caMainID, IsOnline, IsVi, RefreshDate) VALUES(@UserID, 1, '0', GETDATE())
	END
	ELSE IF @UserType = 3
	BEGIN
		UPDATE Manageruser SET SOLStatus = 1,SOLTime = GETDATE() WHERE ID = @UserID
		UPDATE a SET IsOnline = b.SOLStatus FROM ChatService a  WITH(NOLOCK),Manageruser b  WITH(NOLOCK) WHERE a.ManageruserID = b.ID
	END
END

GO
/****** Object:  StoredProcedure [dbo].[ProcChatOnlineExchangeSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ProcChatOnlineExchangeSelect]
AS
--INSERT INTO procLog SELECT 'ProcChatOnlineExchangeSelect', '', GETDATE()
BEGIN
	SELECT * FROM ChatOnlineExchange WITH(NOLOCK)
END

GO
/****** Object:  StoredProcedure [dbo].[ProcChatOnlineLogByCaMainIDAndManageruserIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ProcChatOnlineLogByCaMainIDAndManageruserIDSelect]
(
	@caMainID INT,
	@ManageruserID INT,
	@userType TINYINT
)
AS
--INSERT INTO procLog SELECT 'ProcChatOnlineLogByCaMainIDAndManageruserIDSelect', @caMainID, GETDATE()
BEGIN
	IF @userType = 1
		UPDATE ChatOnlineLog SET IsViewed=1
		WHERE SenderType = 3 AND ChatOnlineID IN(
			SELECT ID FROM ChatOnline WHERE caMainID=@caMainID AND ManageruserID=@ManageruserID
		)
	ELSE
		UPDATE ChatOnlineLog SET IsViewed=1
		WHERE SenderType = 1 AND ChatOnlineID IN(
			SELECT ID FROM ChatOnline WHERE caMainID=@caMainID AND ManageruserID=@ManageruserID
		)
	
	SELECT * FROM ChatOnlineLog
	WHERE ChatOnlineID IN(
		SELECT ID FROM ChatOnline WHERE caMainID=@caMainID AND ManageruserID=@ManageruserID
	) AND (
		CheckResult=0 OR CheckResult IS NULL
	) ORDER BY AddDate
END

GO
/****** Object:  StoredProcedure [dbo].[ProcChatOnlineLogByCvMainIDAndCaMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ProcChatOnlineLogByCvMainIDAndCaMainIDSelect] 
(
	@cvMainID INT,
	@caMainID INT,
	@UserType TINYINT
)
AS
SET NOCOUNT ON
--INSERT INTO procLog SELECT 'ProcChatOnlineLogByCvMainIDAndCaMainIDSelect', LTRIM(STR(@cvMainID)) + ' ' + LTRIM(STR(@caMainID)) + ' ' + LTRIM(STR(@UserType)), GETDATE()  
BEGIN
	DECLARE @t AS TABLE(ID INT)
	DECLARE @n1 INT, @N2 INT
	INSERT INTO @t 
	SELECT ID 
	FROM ChatOnline WITH(NOLOCK INDEX(IX_ChatOnline_Complex)) 
	WHERE cvMainID = @cvMainID
	AND caMainID = @caMainID
	--AND AddDate > DATEADD(MONTH, -2, GETDATE())

	IF @@RowCount = 0
	BEGIN
		SELECT TOP 0 * FROM ChatOnlineLog WITH(NOLOCK)
		RETURN
	END
 
	IF @UserType = 0
	BEGIN
		UPDATE ChatOnlineLog     
		SET IsViewed = 1    
		WHERE SenderType = 1    
		AND ChatOnlineID IN(SELECT ID FROM @t)
		--AND AddDate > DATEADD(MONTH, -2, GETDATE())
		AND IsViewed = 0  
		SET @n1 = @@ROWCOUNT
 
		UPDATE ChatOnline	
		SET paUnViewed = 0
		WHERE Id IN(SELECT ID FROM @t)
		AND caUnViewed > 0
		SET @n2 = @@ROWCOUNT

		IF @n1 + @n2 > 0
			DELETE SearchDb..ChatOnlineListLog WHERE caMainId = @caMainId
	END
	ELSE
	BEGIN    
		UPDATE ChatOnlineLog   
		SET IsViewed = 1    
		WHERE SenderType = 2   
		AND ChatOnlineID IN(SELECT ID FROM ChatOnline WHERE cvMainID=@cvMainID AND caMainID=@caMainID)  
		--AND AddDate > DATEADD(MONTH, -2, GETDATE())
		AND IsViewed = 0
		SET @n1 = @@ROWCOUNT
	
		UPDATE ChatOnline	
		SET caUnViewed = 0
		WHERE Id IN(SELECT ID FROM ChatOnline WITH(NOLOCK) WHERE cvMainID=@cvMainID AND caMainID=@caMainID)
		AND caUnViewed > 0
		SET @n2 = @@ROWCOUNT

		IF @n1 + @n2 > 0
			DELETE SearchDb..ChatOnlineListLog WHERE caMainId = @caMainId
	END

	SELECT *
	FROM ChatOnlineLog WITH(NOLOCK)
	WHERE ChatOnlineID IN(SELECT ID FROM ChatOnline WITH(NOLOCK) WHERE cvMainID=@cvMainID AND caMainID=@caMainID)   
	AND (CheckResult=1 OR CheckResult IS NULL)
	ORDER BY AddDate  
END

GO
/****** Object:  StoredProcedure [dbo].[ProcChatOnlineLogByCvMainIDAndManageruserIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ProcChatOnlineLogByCvMainIDAndManageruserIDSelect]
(
	@cvMainID INT,
	@ManageruserID INT,
	@userType TINYINT
)
AS
--INSERT INTO procLog SELECT 'ProcChatOnlineLogByCvMainIDAndManageruserIDSelect', @cvMainID, GETDATE()
BEGIN
	IF @userType = 0
		UPDATE ChatOnlineLog SET IsViewed=1
		WHERE SenderType = 3 AND ChatOnlineID IN(
			SELECT ID FROM ChatOnline WHERE cvMainID=@cvMainID AND ManageruserID=@ManageruserID
		)
	ELSE
		UPDATE ChatOnlineLog SET IsViewed=1
		WHERE SenderType = 2 AND ChatOnlineID IN(
			SELECT ID FROM ChatOnline WHERE cvMainID=@cvMainID AND ManageruserID=@ManageruserID
		)
	SELECT * FROM ChatOnlineLog
	WHERE ChatOnlineID IN(
		SELECT ID FROM ChatOnline WHERE cvMainID=@cvMainID AND ManageruserID=@ManageruserID
	) AND (
		CheckResult=0 OR CheckResult IS NULL
	) ORDER BY AddDate
END


GO
/****** Object:  StoredProcedure [dbo].[ProcChatOnlineLogSave]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--在线客服
--修改人：Andy
--修改内容：修改客服自己首次给某其发送消息时，自己也收到rtx提醒的bug
--修改时间：2015-3-20
--修改人：harry 2015-7-7
--修改：增加与陌生人发起聊天，增加积分
---20160216 Lucifer 添加推送
---20160411 Lucifer 添加企业微信提醒
--修改Harry2017-4-17 修改积分
--修改Harry2018-06-12 修改企业推送
CREATE PROCEDURE [dbo].[ProcChatOnlineLogSave]
(
	@cvMainID INT,
	@caMainID INT,
	@ManageruserID INT,
	@Message VARCHAR(MAX),
	@UserType TINYINT,
	@ClientType TINYINT
)
AS
SET NOCOUNT ON
DECLARE @cpMainID INT
IF ISNULL(@cvMainID,0) <> 0 AND ISNULL(@caMainID,0) <> 0 AND @UserType = 1
BEGIN
	SELECT @cpMainID = cpMainID FROM caMain WITH(NOLOCK) WHERE ID = @caMainID
	IF dbo.GetChatPrivi(@cvMainID, @cpMainID) = 0
		RETURN -1
END
ELSE
BEGIN
	SELECT @cpMainID = cpMainID FROM caMain WITH(NOLOCK) WHERE ID = @caMainID
END
BEGIN 
	DECLARE @ChatOnlineID INT, @IsNew INT, @Initiative TINYINT, @SenderType TINYINT,
		@ChatToUserID INT, @ChatToUserType INT, @paMainID INT, @IsPaNew INT
	SELECT @ChatOnlineID = 0, @IsNew = 0
	IF @UserType = 0
		SET @SenderType = 2
	ELSE IF @UserType = 1
		SET @SenderType = 1
	ELSE
		SET @SenderType = 3

	IF ISNULL(@ManageruserID,0) = 0
	BEGIN
		SELECT @paMainID = paMainID FROM cvMain WITH(NOLOCK) WHERE ID = @cvMainID
		SELECT @ChatOnlineID = ID FROM ChatOnline WITH(NOLOCK)
		WHERE cvMainID = @cvMainID AND caMainID = @caMainID AND EndDate IS NULL
		IF @UserType = 0
		BEGIN
			SET @Initiative = 1
			SET @ChatToUserID = @caMainID
			SET @ChatToUserType = 1
		END
		ELSE
		BEGIN
			SET @Initiative = 2
			SET @ChatToUserID = @paMainID
			SET @ChatToUserType = 0
		END

	END
	ELSE IF ISNULL(@caMainID,0) = 0
	BEGIN
		SELECT @ChatOnlineID = ID FROM ChatOnline WITH(NOLOCK)
		WHERE cvMainID = @cvMainID AND ManageruserID = @ManageruserID AND EndDate IS NULL
		SET @Initiative = 3
		IF @UserType = 0
		BEGIN
			SET @ChatToUserID = @ManageruserID
			SET @ChatToUserType = 3
		END
		ELSE
		BEGIN
			SELECT @paMainID = paMainID FROM cvMain WITH(NOLOCK) WHERE ID = @cvMainID
			SET @ChatToUserID = @paMainID
			SET @ChatToUserType = 0
		END
	END
	ELSE IF ISNULL(@cvMainID,0) = 0
	BEGIN
		SELECT @ChatOnlineID = ID FROM ChatOnline WITH(NOLOCK)
		WHERE caMainID = @caMainID AND ManageruserID = @ManageruserID AND EndDate IS NULL
		IF @UserType = 1
		BEGIN
			SET @Initiative = 4
			SET @ChatToUserID = @ManageruserID
			SET @ChatToUserType = 3
		END
		ELSE
		BEGIN
			SET @Initiative = 5
			SET @ChatToUserID = @caMainID
			SET @ChatToUserType = 1
		END
	END
	
	IF @ChatOnlineID = 0
	BEGIN
		IF ISNULL(@cvMainID,0) = 0
			UPDATE ChatService SET ChatCount = ChatCount + 1 WHERE ManageruserID = @ManageruserID

		INSERT INTO ChatOnline(cvMainID,caMainID,ManagerUserID,Initiative,StartDate,AddDate,ClientType) 
        VALUES(@cvMainID,@caMainID,@ManagerUserID,@Initiative,GETDATE(),GETDATE(),@ClientType)

		SET @ChatOnlineID = @@IDENTITY
		IF ISNULL(@ManageruserID,0) <> 0
		BEGIN
			DECLARE @Status INT
			DECLARE @Superior INT 
			SET @Status=(SELECT Status FROM Maindb..Manageruser WHERE Id=@ManageruserID)
			IF(@Status=3)--如果为空岗，则将消息发给经理
				BEGIN
					SET @Superior = (SELECT Superior FROM Maindb..Manageruser WHERE Id=@ManageruserID)
					INSERT INTO RtxNotifyLog(Receiver,RtxTitle,RtxMessage,SendType,DelayTime,ShowType) 
					VALUES(@Superior,'新在线客服消息',CONVERT(VARCHAR(10),@ManageruserID)+'号顾问有新的在线客服消息，请及时查看',1,0,0)
				END			
			ELSE IF (@UserType <> 3)--不是客服自己发送的
				INSERT INTO RtxNotifyLog(Receiver,RtxTitle,RtxMessage,SendType,DelayTime,ShowType) 
				VALUES(@ManageruserID,'新在线客服消息','您有新的在线客服消息，请及时查看',1,0,0)
		END
		ELSE
		BEGIN
			IF @UserType = 1
				SET @IsNew = 1

			IF @UserType = 0
				SET @IsPaNew = 1
		END
	END
	IF NOT EXISTS(SELECT 'X' FROM ChatOnlineExchange WHERE UserID = @ChatToUserID AND UserType = @ChatToUserType)
		INSERT INTO ChatOnlineExchange VALUES(@ChatToUserID,@ChatToUserType)

	DECLARE @ChatOnlineLogId INT
	IF @UserType = 0
	BEGIN
		IF CHARINDEX('通讯录', @Message) > 0 OR CHARINDEX('名单', @Message) > 0 
			OR CHARINDEX('QQ群', UPPER(@Message)) > 0 OR CHARINDEX('招聘工作', @Message) > 0 OR CHARINDEX('近期招聘', @Message) > 0
			SET @Message = @Message + '<br /><p class="ChatWarning">涉及公司重要信息请一定电话确认！发现可疑，请马上反馈。</p>'
	END
	INSERT INTO ChatOnlineLog(ChatOnlineID,SenderType,IsViewed,[Message],AddDate) 
    VALUES(@ChatOnlineID,@SenderType,0,@Message,GETDATE())
	SET @ChatOnlineLogId = @@IDENTITY

	--插入积分 Harry
	--判断是否为初次聊天
	IF @IsNew = 1
	BEGIN
		DECLARE @Count AS INT
		SET @Count=0
		SELECT @Count=Count(1) FROM ChatOnline
		WHERE cvMainID=@cvMainID 
		AND caMainID=@caMainID
		AND ID < @ChatOnlineId

		IF @Count = 0 --从未聊过
		BEGIN
			DECLARE @TodayPoint AS INT
			DECLARE @TodayID AS INT
			SET @TodayPoint = 0
			SET @TodayID = 0
			SELECT TOP 1 @TodayPoint = ISNULL(Point,0), @TodayID = ISNULL(ID,0) 
			FROM cpPoint WITH(NOLOCK) 
			WHERE changeID = 6 
			AND LastModifyDate > CONVERT(VARCHAR(10), GETDATE(),120) 
			AND cpMainID = @cpMainID
			
			SET @TodayPoint = @TodayPoint + 10
			
			IF @TodayPoint <= 200
			BEGIN
				IF @TodayID = 0
					INSERT INTO cpPoint (cpMainID,ChangeID,Point,LastModifyDate) VALUES(@cpMainID,6,10,GETDATE())
				ELSE
					UPDATE cpPoint SET Point = @TodayPoint,LastModifyDate = GETDATE() WHERE ID = @TodayID 
			END	
		END
		IF @paMainID > 0
			INSERT INTO paPushLog(paMainID, PushMessage, PushType)
			SELECT @paMainID, '亲，收到一条HR发送的消息！', 5 WHERE EXISTS(SELECT 'X' FROM paIOSBind WHERE paMainID = @paMainID)
	 
			
	END

	IF @IsPaNew = 1
	BEGIN
		IF @paMainID > 0 AND @cpMainID > 0
		BEGIN
			INSERT wxMessageSend2(Templatetype, WxFansID, PaMainId, CvMainId, CpMainID, CaMainId, AddDate)
			SELECT 17, b.ID, @paMainID, @cvMainID, @cpMainID, a.paMainID, GETDATE()
			FROM paLoginContact a WITH(NOLOCK), wxFans b WITH(NOLOCK)
			WHERE a.OpenID = b.OpenID AND a.ContactType = 101 AND a.paMainID = @caMainID
			
			
		END
		INSERT INTO paPushLog(paMainID, PushMessage, PushType)
		SELECT @caMainID, '亲，收到一条求职者发送的消息！', 11 WHERE EXISTS(SELECT 'X' FROM caIOSBind WHERE caMainID = @caMainID)
	END
	--Harry
	SET NOCOUNT OFF
	RETURN @ChatOnlineLogId
END  


GO
/****** Object:  StoredProcedure [dbo].[ProcChatOnlineLogSave20170428]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--@MessageType 1 文本 2 表情 3 图片 4 职位 5 面试通知 6 相关职位 7 相关简历
--@Initiative 1 个人主动 2 企业主动
--@SenderType 1 企业 2 个人
--Carl 2018-05-08 企业黑名单中的用户无法给该企业发消息
--修改harry 增加企业app提醒2018-6-11
--修改harry 发送图片时增加提醒2018-8-17
--修改harry 增加一些关键词增加提醒2018-9-21
CREATE PROCEDURE [dbo].[ProcChatOnlineLogSave20170428]
(
	@cvMainID INT,
	@caMainID INT,
	@ManagerUserID INT,
	@Message VARCHAR(MAX),
	@MessageType TINYINT,
	@SenderType TINYINT
)
AS
SET NOCOUNT ON
BEGIN
	DECLARE @cpMainID INT, @paMainID INT, @ChatOnlineID INT
	SET @ChatOnlineID = 0
	SELECT @cpMainID = cpMainID FROM caMain WITH(NOLOCK) WHERE ID = @caMainID
	SELECT @paMainID = paMainID FROM cvMain WITH(NOLOCK) WHERE ID = @cvMainID
	IF @SenderType = 1 AND dbo.GetChatPrivi(@cvMainID, @cpMainID) = 0 --企业发起会话，检查是否有权限
		RETURN -1

	--新增的
	IF EXISTS(SELECT 'X' FROM cpCvShield a WITH(NOLOCK) WHERE a.cpMainId=@cpMainID 
		AND EXISTS(SELECT 'X' FROM cvMain c WHERE c.paMainId = @paMainID AND a.cvMainId = c.Id))
		RETURN -1

	SELECT @ChatOnlineID = ID FROM ChatOnline WITH(NOLOCK)
	WHERE cvMainID = @cvMainID AND caMainID = @caMainID AND ManagerUserID = @ManagerUserID
	IF @ChatOnlineID = 0 --第一次聊
	BEGIN
		DECLARE @Initiative TINYINT
		IF @SenderType = 1
			SET @Initiative = 2
		ELSE
			SET @Initiative = 1

		INSERT INTO ChatOnline(cvMainID, caMainID, ManagerUserID, Initiative, StartDate, AddDate) 
		VALUES(@cvMainID, @caMainID, @ManagerUserID, @Initiative, GETDATE(), GETDATE())
		SET @ChatOnlineID = @@IDENTITY
		IF @SenderType = 1
		BEGIN
			--如果是企业发起，添加积分
			EXEC ccCpPointByChatOnlineInsert @caMainID
			IF @ManagerUserID > 0
			INSERT INTO paPushLog(paMainID, PushMessage, PushType)
			SELECT @paMainID, '亲，收到一条HR发送的消息！', 5 WHERE EXISTS(SELECT 'X' FROM paIOSBind WHERE paMainID = @paMainID)
		END
		IF @SenderType = 2
		BEGIN
			--如果是个人发起，企业添加微信消息提醒
			INSERT wxMessageSend2(Templatetype, WxFansID, PaMainId, CvMainId, CpMainID, CaMainId, AddDate)
			SELECT 17, b.ID, @paMainID, @cvMainID, @cpMainID, a.paMainID, GETDATE()
			FROM paLoginContact a WITH(NOLOCK), wxFans b WITH(NOLOCK)
			WHERE a.OpenID = b.OpenID AND a.ContactType = 101 AND a.paMainID = @caMainID

			INSERT INTO paPushLog(paMainID, PushMessage, PushType)
			SELECT @caMainID, '亲，收到一条求职者发送的消息！', 11 WHERE EXISTS(SELECT 'X' FROM caIOSBind WHERE caMainID = @caMainID)
		END		
	END
	IF @MessageType=1 AND @SenderType=2
	BEGIN
		IF CHARINDEX('最近招聘', @Message) > 0 OR CHARINDEX('招聘效果', @Message) > 0 
			OR CHARINDEX('招聘进展', UPPER(@Message)) > 0 OR CHARINDEX('人员名单', @Message) > 0
			OR CHARINDEX('招聘', @Message) > 0 OR CHARINDEX('效果', @Message) > 0 OR CHARINDEX('进展', @Message) > 0
			OR CHARINDEX('开展', @Message) > 0 OR CHARINDEX('进度', @Message) > 0 OR CHARINDEX('情况', @Message) > 0
			OR CHARINDEX('事情', @Message) > 0 OR CHARINDEX('名单', @Message) > 0 OR CHARINDEX('工作', @Message) > 0
			OR CHARINDEX('事情', @Message) > 0 OR CHARINDEX('重要', @Message) > 0 OR CHARINDEX('要事', @Message) > 0
			OR CHARINDEX('有事', @Message) > 0 OR CHARINDEX('事情', @Message) > 0 OR CHARINDEX('急', @Message) > 0 
			OR CHARINDEX('安排', @Message) > 0 OR CHARINDEX('QQ', @Message) > 0 OR CHARINDEX('扣扣', @Message) > 0
			OR CHARINDEX('抠抠', @Message) > 0 OR CHARINDEX('叩叩', @Message) > 0 OR CHARINDEX('蔻蔻', @Message) > 0
			OR CHARINDEX('口口', @Message) > 0 OR CHARINDEX('微信', @Message) > 0 OR CHARINDEX('weixin', @Message) > 0
			OR CHARINDEX('qiuqiu', @Message) > 0 OR CHARINDEX('面试', @Message) > 0 OR CHARINDEX('手机', @Message) > 0
			OR CHARINDEX('qq', @Message) > 0 OR CHARINDEX('球球', @Message) > 0 OR CHARINDEX('求求', @Message) > 0 
		BEGIN
			SET @Message = @Message + '<br /><p class="ChatWarning">涉及公司重要信息请一定电话确认！发现可疑，请马上反馈。</p>'
		END
	END
	
	
	IF @MessageType = 5
	BEGIN
		SELECT TOP 1 @Message = ID FROM exInterview WITH(NOLOCK) WHERE cvMainID = @cvMainID ORDER BY ID DESC
	END
	IF LEN(@Message) = 0
		RETURN -1

	INSERT INTO ChatOnlineLog(ChatOnlineID, SenderType, IsViewed, [Message], MessageType, AddDate) 
    VALUES(@ChatOnlineID, @SenderType, 0, @Message, @MessageType, GETDATE())
	
	DECLARE @LogId INT
	SET @LogId = @@IDENTITY
	--rtx提醒审核 最近招聘  招聘效果  招聘进展  人员名单
	IF @MessageType=1 AND @SenderType=2
	BEGIN
		IF CHARINDEX('最近招聘', @Message) > 0 OR CHARINDEX('招聘效果', @Message) > 0 
		OR CHARINDEX('招聘进展', UPPER(@Message)) > 0 OR CHARINDEX('人员名单', @Message) > 0
		OR CHARINDEX('招聘', @Message) > 0 OR CHARINDEX('效果', @Message) > 0 OR CHARINDEX('进展', @Message) > 0
		OR CHARINDEX('开展', @Message) > 0 OR CHARINDEX('进度', @Message) > 0 OR CHARINDEX('情况', @Message) > 0
		OR CHARINDEX('事情', @Message) > 0 OR CHARINDEX('名单', @Message) > 0 OR CHARINDEX('工作', @Message) > 0
		OR CHARINDEX('事情', @Message) > 0 OR CHARINDEX('重要', @Message) > 0 OR CHARINDEX('要事', @Message) > 0
		OR CHARINDEX('有事', @Message) > 0 OR CHARINDEX('事情', @Message) > 0 OR CHARINDEX('急', @Message) > 0 
		OR CHARINDEX('安排', @Message) > 0 OR CHARINDEX('QQ', @Message) > 0 OR CHARINDEX('扣扣', @Message) > 0
		OR CHARINDEX('抠抠', @Message) > 0 OR CHARINDEX('叩叩', @Message) > 0 OR CHARINDEX('蔻蔻', @Message) > 0
		OR CHARINDEX('口口', @Message) > 0 OR CHARINDEX('微信', @Message) > 0 OR CHARINDEX('weixin', @Message) > 0
		OR CHARINDEX('qiuqiu', @Message) > 0 OR CHARINDEX('面试', @Message) > 0 OR CHARINDEX('手机', @Message) > 0
		OR CHARINDEX('qq', @Message) > 0 OR CHARINDEX('球球', @Message) > 0 OR CHARINDEX('求求', @Message) > 0 
		BEGIN
			INSERT INTO RtxNotifyLog(Receiver, RtxTitle, RtxMessage, SendType, DelayTime, ShowType) 
				   SELECT '155,180,216,222,223', '聊聊内容监控提醒','【公司id】'+CONVERT(CHAR(10),@cpMainID)+'【个人id】'+CONVERT(CHAR(10),@paMainID)+ 'http://sysback.51rc.com/newoa/operate/chatOnline/LogDetails?ID='+CONVERT(CHAR(10),@ChatOnlineID), 1, 0, 0
		END
	END
	IF CHARINDEX('相关职位：',@Message) > 0 OR CHARINDEX('相关简历：',@Message) > 0
	BEGIN
		UPDATE ChatOnlineLog SET CheckUserID = 182,CheckResult = 1 WHERE ID = @LogId
	END	

	UPDATE ChatOnline SET AddDate = GETDATE() WHERE ID = @ChatOnlineID
	IF @SenderType = 1
	BEGIN
		IF NOT EXISTS(SELECT 'X' FROM ChatOnlineExchange WHERE UserID = @paMainID AND UserType = 2)
		BEGIN
			INSERT INTO ChatOnlineExchange VALUES(@paMainID, 2)
		END
	END
	ELSE
	BEGIN
		IF NOT EXISTS(SELECT 'X' FROM ChatOnlineExchange WHERE UserID = @caMainID AND UserType = 1)
		BEGIN
			INSERT INTO ChatOnlineExchange VALUES(@caMainID, 1)
		END
	END

	RETURN @LogId
END






GO
/****** Object:  StoredProcedure [dbo].[procChatOnlineLogSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[procChatOnlineLogSelect]
(
	@caMainId INT,
	@cvMainId INT,
	@SenderType TINYINT
)
AS
SET NOCOUNT ON
BEGIN
	UPDATE a SET IsViewed = 1
	FROM ChatOnlineLog a WITH(NOLOCK), ChatOnline b WITH(NOLOCK)
    WHERE a.ChatOnlineID = b.ID AND b.caMainID = @caMainId AND b.cvMainID = @cvMainId AND SenderType <> @SenderType

	SELECT a.*
    FROM ChatOnlineLog a WITH(NOLOCK), ChatOnline b WITH(NOLOCK)
    WHERE a.ChatOnlineID = b.ID AND b.caMainID = @caMainId AND b.cvMainID = @cvMainId
END
GO
/****** Object:  StoredProcedure [dbo].[ProcChatOnlineSchedule]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ProcChatOnlineSchedule]
AS
--INSERT INTO procLog SELECT 'ProcChatOnlineSchedule', '', GETDATE()
BEGIN
    --删除离线的数据（1分钟不刷新）
    DELETE FROM caOnline WHERE RefreshDate < DATEADD(SECOND, -80, GETDATE())
    DELETE FROM paOnline WHERE RefreshDate < DATEADD(SECOND, -80, GETDATE())
    --DELETE FROM paOnline WHERE RefreshDate < DATEADD(Minute, -70, GETDATE())
    UPDATE Manageruser SET SOLStatus = 0 WHERE SOLTime < DATEADD(SECOND, -80, GETDATE())
    UPDATE a SET IsOnline = b.SOLStatus FROM ChatService a,Manageruser b WHERE a.ManageruserID = b.ID
    --删除交互表中的记录
    DELETE FROM ChatOnlineExchange WHERE UserID NOT IN(SELECT paMainID FROM paOnline) AND UserType = 2
    DELETE FROM ChatOnlineExchange WHERE UserID NOT IN(SELECT caMainID FROM caOnline) AND UserType = 1
    --结束两方都不在线的聊天记录
    UPDATE ChatOnline SET EndDate = GETDATE()
    WHERE ManageruserID = 0
        AND EndDate IS NULL
        AND caMainID NOT IN(SELECT caMainID FROM caOnline)
        AND cvMainID NOT IN(SELECT a.ID FROM cvMain a,paOnline b WHERE a.paMainID = b.paMainID)

    UPDATE ChatOnline SET EndDate = GETDATE()
    WHERE cvMainID = 0
        AND EndDate IS NULL
        AND caMainID NOT IN(SELECT caMainID FROM caOnline)
        AND ManageruserID NOT IN(SELECT ID FROM Manageruser WHERE SOLStatus = 1)

    UPDATE ChatOnline SET EndDate = GETDATE()
    WHERE caMainID = 0
        AND EndDate IS NULL
        AND ManageruserID NOT IN(SELECT ID FROM Manageruser WHERE SOLStatus = 1)
        AND cvMainID NOT IN(SELECT a.ID FROM cvMain a,paOnline b WHERE a.paMainID = b.paMainID)
END
GO
/****** Object:  StoredProcedure [dbo].[procChatOnlineSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--lucifer2018-4-27
CREATE PROCEDURE [dbo].[procChatOnlineSelect]
(
	@caMainId INT,
	@paMainId INT
)
AS
SET NOCOUNT ON
BEGIN
	CREATE TABLE #ChatList(
		cvMainID INT,
		caMainID INT,
		[Name] VARCHAR(100),
		[Message] VARCHAR(MAX),
		LastSendDate DATETIME,
		NoViewedNum INT,
		OnlineStatus INT,
		PhotoUrl VARCHAR(300),
		paMainId INT,
		SecondId VARCHAR(10),
		Gender BIT
	)

	IF @paMainId > 0
	BEGIN
		INSERT INTO #ChatList(cvMainID, caMainID, LastSendDate, OnlineStatus, [Message])
		SELECT cvMainID, caMainID, AddDate, dbo.GetCaOnlineStatus(caMainID),
			CASE MessageType
			WHEN 1 THEN [Message]
			WHEN 2 THEN '[表情]'
			WHEN 3 THEN '[图片]'
			WHEN 4 THEN '[职位]'
			WHEN 5 THEN '[面试通知]'
			ELSE '' END
		FROM (SELECT TOP 100000 a.cvMainID, a.caMainID, b.AddDate, b.Message, b.MessageType, ROW_NUMBER() OVER(PARTITION BY a.cvMainID, a.caMainID ORDER BY b.ID DESC) row
			FROM ChatOnline a WITH(NOLOCK), ChatOnlineLog b WITH(NOLOCK)
			WHERE a.ID = b.ChatOnlineID AND a.caMainID > 0 AND b.MessageType <> 6 AND a.cvMainID IN(
			SELECT ID FROM cvMain WITH(NOLOCK) WHERE paMainID = @paMainId
			)
		ORDER BY b.ID DESC
		) t WHERE row = 1

		UPDATE #ChatList SET NoViewedNum = (SELECT COUNT(1)
			FROM ChatOnlineLog WITH(NOLOCK)
			WHERE ChatOnlineID IN (SELECT ID FROM ChatOnline WITH(NOLOCK) WHERE cvMainID = #ChatList.cvMainID AND caMainID = #ChatList.caMainID)
			AND IsViewed = 0 AND SenderType = 1 AND MessageType NOT IN(6, 7))
		UPDATE a SET a.PhotoUrl = b.LogoFile, a.[Name] = c.[Name] + ' ' + b.[Name]
		FROM #ChatList a, cpMain b WITH(NOLOCK), caMain c WITH(NOLOCK)
		WHERE b.ID = c.cpMainID AND c.ID = a.caMainID
	END
	ELSE IF @caMainID > 0
	BEGIN
		INSERT INTO #ChatList(cvMainID, caMainID, LastSendDate, [Message])
		SELECT cvMainID, caMainID, AddDate,
			CASE MessageType
			WHEN 1 THEN [Message]
			WHEN 2 THEN '[表情]'
			WHEN 3 THEN '[图片]'
			WHEN 4 THEN '[职位]'
			WHEN 5 THEN '[面试通知]'
			ELSE '' END
		FROM (SELECT TOP 100000 a.cvMainID, a.caMainID, b.AddDate, b.Message, b.MessageType, ROW_NUMBER() OVER(PARTITION BY a.cvMainID, a.caMainID ORDER BY b.ID DESC) row
			FROM ChatOnline a WITH(NOLOCK), ChatOnlineLog b WITH(NOLOCK)
			WHERE a.ID = b.ChatOnlineID AND a.caMainID = @caMainId AND b.MessageType <> 7 AND a.cvMainID > 0
			ORDER BY b.ID DESC) t 
		WHERE row = 1

		UPDATE #ChatList
		SET NoViewedNum = (SELECT COUNT(1)
			FROM ChatOnlineLog WITH(NOLOCK)
			WHERE ChatOnlineID IN (SELECT ID FROM ChatOnline WITH(NOLOCK)
				WHERE cvMainID = #ChatList.cvMainID AND caMainID = #ChatList.caMainID)
			AND IsViewed = 0 AND SenderType = 2 AND MessageType NOT IN(6, 7))

		UPDATE #ChatList 
		SET PhotoUrl = (
			SELECT TOP 1 a.PhotoProcessed
			FROM paPhoto a WITH(NOLOCK), cvMain b WITH(NOLOCK)
			WHERE a.paMainID = b.paMainID AND b.ID = #ChatList.cvMainID)
		WHERE EXISTS(SELECT 'X' FROM cpMain a, caMain b WHERE a.ID = b.cpMainID AND b.ID = #ChatList.caMainID AND a.MemberType > 1)

		UPDATE #ChatList
		SET OnlineStatus = (SELECT TOP 1 dbo.GetPaOnlineStatus(paMainID)
			FROM cvMain WITH(NOLOCK)
			WHERE ID = #ChatList.cvMainID)

		UPDATE a SET a.paMainId = b.paMainId, a.SecondId = b.SecondId FROM #ChatList a, cvMAin b WHERE a.cvMainId = b.Id
		UPDATE a SET a.Gender = c.Gender FROM #ChatList a, cvMain b, paMain c WHERE a.cvMainId = b.Id AND b.paMainID = c.ID
		UPDATE #ChatList
		SET [Name] = (SELECT TOP 1 dbo.GetPaName(#ChatList.cvMainId, cpMainId)
			FROM caMain WITH(NOLOCK)
			WHERE ID = #ChatList.caMainId)
	END
	SELECT * FROM #ChatList
END
GO
/****** Object:  StoredProcedure [dbo].[ProcChatOnlineUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ProcChatOnlineUpdate]
AS
--INSERT INTO procLog SELECT 'ProcChatOnlineUpdate', '', GETDATE()
BEGIN
	UPDATE ChatOnline
	SET caUnViewed = 0
	WHERE caUnViewed > 0
	AND StartDate < DATEADD(MINUTE, -30, GETDATE())
	AND EndDate > DATEADD(MINUTE, -30, GETDATE())

	UPDATE a
	SET a.caUnViewed = b.Cnt
	FROM ChatOnline a, (
		SELECT MAX(a.ID) Id, COUNT(*) Cnt
		FROM ChatOnline a, ChatOnlineLog b
		WHERE a.id = b.ChatOnlineID
		AND b.IsViewed = 0
		AND b.SenderType <> 1 --不是企业发送的
		AND StartDate < DATEADD(MINUTE, -30, GETDATE())
		AND EndDate > DATEADD(MINUTE, -30, GETDATE())
		GROUP BY a.CaMainID, a.CvMainID
		) b
	WHERE a.Id = b.Id
	------------------
	UPDATE ChatOnline
	SET paUnViewed = 0
	WHERE paUnViewed > 0
	AND StartDate < DATEADD(MINUTE, -30, GETDATE())
	AND EndDate > DATEADD(MINUTE, -30, GETDATE())

	UPDATE a
	SET a.paUnViewed = b.Cnt
	FROM ChatOnline a, (
		SELECT MAX(a.ID) ID, COUNT(1) Cnt
		FROM ChatOnline a, ChatOnlineLog b
		WHERE a.id = b.ChatOnlineID
		AND b.IsViewed = 0
		AND b.SenderType <> 2 --不是自己发送的
		AND StartDate < DATEADD(MINUTE, -30, GETDATE())
		AND EndDate > DATEADD(MINUTE, -30, GETDATE())
		GROUP BY a.CaMainID, a.CvMainID
		) b
	WHERE a.Id = b.Id
END




GO
/****** Object:  StoredProcedure [dbo].[procChatRoomUserByUserIdDelete]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[procChatRoomUserByUserIdDelete]
(
	@UserID INT,
	@UserType INT,
	@RoomID INT,
	@IpAddress VARCHAR(50)
)
AS
BEGIN
	SET NOCOUNT ON
	--从用户列表中删除
	DELETE FROM Shortdb..ChatRoomUser WHERE ChatRoomID = @RoomID AND UserID = @UserID AND UserType = @UserType
	--加入黑名单
	INSERT INTO Shortdb..ChatRoomBlack( ChatRoomID, UserID, UserType, IP, AddDate )
	VALUES ( @RoomID ,@UserID, @UserType, @IpAddress , getDate() )
	SET NOCOUNT OFF	
END

GO
/****** Object:  StoredProcedure [dbo].[ProcCitySalaryRankByReginIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.3
--创建人：John
--说明：根据RegionID获取当前地区所在省级下属城市薪水排行
--#####################################################
CREATE PROCEDURE [dbo].[ProcCitySalaryRankByReginIDSelect]
(
	@dcRegionID VARCHAR(6)
)
AS
BEGIN
	IF LEN(@dcRegionID) > 4
		SET @dcRegionID = LEFT(@dcRegionID, LEN(@dcRegionId) - 2) + '__'
	ELSE
		SET @dcRegionID = @dcRegionId + '__'

	IF LEFT(@dcRegionID, 2) = '32'
		SELECT dcRegionID,AvgSalary 
		FROM reportdb..SalaryReportRegion 
		WHERE dcRegionid LIKE @dcRegionID AND LEN(dcRegionid) > 2 
		ORDER BY AvgSalary DESC
	ELSE
		SELECT TOP 10 dcRegionID,AvgSalary 
		FROM reportdb..SalaryReportRegion 
		WHERE dcRegionid LIKE @dcRegionID AND LEN(dcRegionid) > 2 
		ORDER BY AvgSalary DESC
END
GO
/****** Object:  StoredProcedure [dbo].[procColdCustomerInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--采集的冷客户分配
--harry
--2016-10-13
--修改harry 2018-1-25 增加推广
--harry 2018-1-26
CREATE PROCEDURE [dbo].[procColdCustomerInsert]
(
  @ManagerUserId INT,
  @Allocater INT,
  @SourceType INT,
  @AllocateNumber INT,
  @isSpread INT		
)
AS
SET NOCOUNT ON
BEGIN
	DECLARE @Id INT
	DECLARE @AllocateId INT
	DECLARE @cpName VARCHAR(200)
	DECLARE @ProvinceId INT
	SET @ProvinceId=32
	DECLARE @dtLastLoginDate DATETIME 
	DECLARE @dtLastContactDate DATETIME
	SET @dtLastLoginDate=dateAdd(month,-6,getdate())
	SET @dtLastContactDate=dateAdd(month,-6,getdate())
	IF(@ProvinceId=32)
		SET @dtLastContactDate=dateAdd(month,-3,getdate())
	--分配前，更新已被注册的信息
	CREATE TABLE #t(
		Id INT ,
		[state] INT,
		SourceType  INT, 
		RegType INT,
		CompanyName  VARCHAR(200),
		LinkMan varchar(50),
		Phone varchar(50),
		Tel varchar(50),
		Email varchar(50),
		SourceLink varchar(500),
		[Address] varchar(200),
		QQ char(15),
		IsNameRepeat BIT,
		IsEmailRepeat BIT,
		IsMobileRepeat BIT,
		IsAgree BIT,
		IsValid BIT,
		CheckDate DATETIME,
		AddDate DATETIME
	)
	INSERT #t(id,[state],sourceType,companyName,LinkMan,Phone,Tel,Email,SourceLink,[address],qq)
	SELECT id,[state],sourceType,companyName,linkMan,Phone,Tel,Email,SourceLink,[address],qq 
	FROM precoldCustomer
	WHERE [state]=0--未分配 
	AND ISNULL(isSpread,0) = @isSpread 
 
	IF EXISTS(SELECT 'x' FROM #t )
	BEGIN 
		--删除在coldcustomer表中的数据
		UPDATE #t SET [state]=2 
		WHERE  EXISTS(SELECT 'x' FROM Maindb..coldcustomer 
			WHERE companyName=#t.CompanyName AND ProvinceID=@ProvinceId) 
		 AND [state]=0
		
		IF @isSpread = 0 --冷客户部门的规则
		BEGIN
			--有顾问的（上次联系时间，和登录时间不为空的）
			--3（6）个月内未联系，删除3（6）个月内联系过的
			UPDATE #t SET [state]=2
			WHERE EXISTS
			(
				SELECT 'x' FROM cpMain  
				WHERE NAME=#t.CompanyName 
				AND dcProvinceID = @ProvinceId
				AND ISNULL(ConsultantID, -1) != -1
				AND id =(
					SELECT TOP 1 companyID 
					FROM MainDB..contact
					WHERE companyID = CpMain.ID 
					AND addDate>@dtLastContactDate 
					ORDER BY addDate DESC
				)
			)
			 AND [state]=0
		
			--6个月未登录，删除6个月内登录过的
			UPDATE #t SET [state]=2
			WHERE EXISTS(
				SELECT 'x'  FROM  cpMain  
				WHERE  NAME=#t.CompanyName 
				AND dcProvinceID=@ProvinceId
				AND  ISNULL(ConsultantID,-1)!=-1
				AND   LastLoginDate>@dtLastLoginDate 
			) 
			AND [state]=0

			--无顾问 
			--无执照且一个月未登录，删除一个月内登录的
			UPDATE #t SET [state]=2
			WHERE EXISTS(
				SELECT 'x' FROM cpMain 
				WHERE  NAME=#t.CompanyName 
				AND dcProvinceID=@ProvinceId
				AND	ISNULL(ConsultantID,-1)=-1
				AND HasLicence=0
				AND LastLoginDate>DateAdd(month,-1,getdate())
			) 
			AND [state]=0
		
			--有执照且三个月未登录，删除3个月内登录的
			UPDATE #t SET [state]=2
			WHERE EXISTS
			(
				SELECT 'x'  FROM  cpMain  
				WHERE  NAME=#t.CompanyName 
				AND dcProvinceID=@ProvinceId
				AND	ISNULL(ConsultantID,-1)=-1
				AND HasLicence=1
				AND LastLoginDate>DateAdd(month,-3,getdate())
			) 
			AND [state]=0
		END
		ELSE
		BEGIN
		--推广的规则
			--有顾问的，已认证的
			UPDATE #t SET [state]=2
			WHERE EXISTS
			(
				SELECT 'x' FROM cpMain  
				WHERE  NAME=#t.CompanyName 
				AND dcProvinceID=@ProvinceId
				AND	(ISNULL(ConsultantID,0)!=0 OR memberType>1)
			) 
			AND [state]=0
		END
	END
	--更新新结束，开始分配
	UPDATE precoldCustomer 
	SET [state]=2
	WHERE id in(select id FROM #t where [state]=2)
	
	TRUNCATE TABLE #t
	 
	INSERT INTO #t(id,sourceType,companyName,LinkMan,Phone,Tel,Email,SourceLink,[address],qq,IsAgree,IsValid,CheckDate,AddDate)
	SELECT TOP (@AllocateNumber) id,sourceType,companyName,
		REPLACE(linkMan,'_',''),
		REPLACE(Phone,'_',''),
		REPLACE(Tel,'_',''),
		REPLACE(Email,'_',''),
		REPLACE(SourceLink,'_',''),
		REPLACE([address],'_',''),
		REPLACE(qq,'_',''),1,1,GETDATE(),GETDATE() 
	FROM precoldCustomer 
	WHERE [state]=0
	AND SourceType=@SourceType
	AND ISNULL(isSpread,0) = @isSpread 
	--判断用户名，手机，邮箱等是否重复IsNameRepeat BIT,IsEmailRepeat BIT, IsMobileRepeat BIT,
	UPDATE #t
	SET IsNameRepeat=(CASE WHEN EXISTS(select 'x' from MainDB..CpMain where name =#t.CompanyName)
		THEN 1 
		ELSE 0 END),
		IsEmailRepeat=(
			CASE WHEN Email!=''
			THEN
				(CASE WHEN EXISTS(select 'x' from MainDB..CaMain a,MainDB..CpMain b where a.email =#t.Email and a.CpMainID=b.ID)
				THEN 1 
				ELSE 0 END)
			ELSE 0 END),
		IsMobileRepeat=(CASE WHEN #t.Phone!='' OR #t.Tel !=''
			THEN (CASE 
				WHEN #t.Phone!='' AND #t.Tel!='' AND EXISTS(select 'x' from MainDB..CaMain a,MainDB..cpmain b  
					where (a.telephone like #t.Tel+ '%' or a.mobile=#t.Phone)
					and a.CpMainID=b.ID)
				THEN 1
				WHEN #t.Phone!='' AND #t.Tel ='' AND EXISTS(select 'x' from MainDB..CaMain a,MainDB..cpmain b  
					where a.mobile=#t.Phone and a.CpMainID=b.ID)
				THEN 1
				WHEN #t.Phone ='' AND #t.Tel!='' AND EXISTS(select a.cpmainid,b.ConsultantID,b.LastLoginDate,b.HasLicence  
					 from MainDB..CaMain a,MainDB..cpmain b  
					where a.telephone like #t.Tel+'%' and a.CpMainID=b.ID)
				THEN 1
				ELSE 0
				END)
			ELSE 0
			END)

	--更新regtype 
	UPDATE #t SET regType=1 --无顾问的
	
	--有顾问的 regType=4,HasLicence=1 regtype=3 haslicence=0 regtype=2
	
	UPDATE #t 
	SET regType=4
	WHERE EXISTS(SELECT 'x'  FROM  cpMain  
		WHERE  NAME=#t.CompanyName 
		AND dcProvinceID=@ProvinceId
		AND  ISNULL(ConsultantID,-1)!=-1) 

	UPDATE #t 
	SET regType=3
	WHERE EXISTS(
		SELECT 'x'  FROM  cpMain  
		WHERE  NAME=#t.CompanyName 
		AND dcProvinceID=@ProvinceId
		AND HasLicence=1
		AND  ISNULL(ConsultantID,-1)!=-1) 
		
	UPDATE #t 
	SET regType=3
	WHERE EXISTS(
		SELECT 'x'  FROM  cpMain  
		WHERE  NAME=#t.CompanyName 
		AND dcProvinceID=@ProvinceId
		AND HasLicence=0
		AND  ISNULL(ConsultantID,-1)!=-1) 
			
	--#t
	IF EXISTS(SELECT 'x' FROM #t)
	BEGIN
		INSERT INTO ColdCustomerAllocateLog(ManagerUserId,SourceType,Allocater,AllocateNumber,Adddate)
		SELECT @ManagerUserId,@SourceType,@Allocater,(SELECT COUNT(*) FROM #t),GETDATE()
		
		SELECT @AllocateId=(SELECT @@IDENTITY) --赋值
		--插入冷客户表
		INSERT INTO coldCustomer(CompanyName, ProvinceId, Email, Phone, SourceLink, LinkMan, [Address], qq, AllocateLogID, AddWorkUserID,AddMan,IsNameRepeat,IsEmailRepeat,IsMobilerepeat,IsAgree,IsValid,CheckDate,addDate,regType)
		SELECT CompanyName,32,Email,Phone,SourceLink,LinkMan,[Address],qq,@AllocateId,(select TOP 1 id from oadb..workuser where manageruserid=@ManagerUserId and loginstatus=1 AND JobStatus<3 ),@ManagerUserId,IsNameRepeat, IsEmailRepeat,IsMobileRepeat,IsAgree,IsValid,CheckDate ,AddDate,regType
		FROM #t
		
		UPDATE precoldCustomer SET [state]=1,ColdCustomerAllocateLogID=@AllocateId  WHERE ID IN(SELECT id FROM #t)
		--释放顾问
		UPDATE Maindb..cpMain SET ConsultantID = NULL, ConsultantDate = NULL WHERE [Name] IN(SELECT CompanyName FROM #t) AND dcProvinceID=32
		--rtx 通知 操作人和分配人
        INSERT RtxNotifyLog SELECT @ManagerUserId, Convert(VARCHAR,@Allocater)+'分配给您'+Convert(VARCHAR,(SELECT COUNT(*) FROM #t))+'个新的冷客户', Convert(VARCHAR,@Allocater)+'分配给您'+Convert(VARCHAR,(SELECT COUNT(*) FROM #t))+'个新的冷客户，请及时处理', 0, 0, 0, Null, GETDATE()
		INSERT RtxNotifyLog SELECT @Allocater,  '分配冷客户成功通知', '成功分配'+Convert(VARCHAR,(SELECT COUNT(*) FROM #t))+'个新的冷客户给'+Convert(VARCHAR,@ManagerUserId), 0, 0, 0, Null, GETDATE()
	END
	
END
SET NOCOUNT OFF


GO
/****** Object:  StoredProcedure [dbo].[ProcColdCustomerSave]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--冷客户采集插入
--Harry
--2016-10-11
--修改harry2017-7-31 0库中的数据重新采集，同时删除存在的0库数据
--修改harry2017-10-12 删除vip用户
--修改harry 2018-1-24 增加推广采集 @ProvinceId len=4时为推广采集，推广采集原则：无顾问，未认证
CREATE PROCEDURE [dbo].[ProcColdCustomerSave]
( 
	@CompanyInfo VARCHAR(MAX),
	@ProvinceId INT 
)
AS
SET NOCOUNT ON
BEGIN
	DECLARE @dtLastLoginDate DATETIME 
	DECLARE @dtLastContactDate DATETIME
	DECLARE @cpName VARCHAR(200)
	SET @dtLastLoginDate=dateAdd(month,-6,getdate())
	SET @dtLastContactDate=dateAdd(month,-6,getdate())
	IF(LEFT(@ProvinceId,2)=32)
		SET @dtLastContactDate=dateAdd(month,-3,getdate())
	CREATE TABLE #t(
		Id INT IDENTITY,
		SeekInfo VARCHAR(MAX),
		SourceType  INT, 
		CompanyName  VARCHAR(200),
		LinkMan varchar(50),
		Phone varchar(50),
		Tel varchar(50),
		Email varchar(50),
		SourceLink varchar(500),
		[Address] varchar(200),
		QQ char(15),
	)
	INSERT INTO #t(SeekInfo)
	SELECT * FROM dbo.FnSplit(@CompanyInfo, '#')
	DECLARE @Id INT, @Info VARCHAR(MAX)
	CREATE TABLE #One(
		Id INT IDENTITY(1, 1),
		Info VARCHAR(1000)
	)
	
	SET @Id = 0
	WHILE EXISTS(SELECT 'x' FROM #t WHERE Id > @Id)
	BEGIN
		SELECT TOP 1 @Id = Id, @Info = SeekInfo FROM #t WHERE Id > @Id ORDER BY ID
		TRUNCATE TABLE #One
		INSERT INTO #One
		SELECT * FROM dbo.FnSplit(@Info, '|')
		IF(SELECT COUNT(*) FROM #One) = 9
		BEGIN
			UPDATE #t SET SourceType = convert(INT,b.Info) FROM #t a, #One b WHERE a.Id = @Id AND b.Id = 1
			UPDATE #t SET CompanyName = LEFT(b.Info, 200) FROM #t a, #One b WHERE a.Id = @Id AND b.Id = 2
			UPDATE #t SET LinkMan = LEFT(b.Info, 50) FROM #t a, #One b WHERE a.Id = @Id AND b.Id = 3
			UPDATE #t SET Phone = LEFT(b.Info, 50) FROM #t a, #One b WHERE a.Id = @Id AND b.Id = 4
			UPDATE #t SET Tel= LEFT(b.Info, 50) FROM #t a, #One b WHERE a.Id = @Id AND b.Id = 5
			UPDATE #t SET Email = LEFT(b.Info, 50) FROM #t a, #One b WHERE a.Id = @Id AND b.Id = 6
			UPDATE #t SET SourceLink = LEFT(b.Info, 500) FROM #t a, #One b WHERE a.Id = @Id AND b.Id = 7
			UPDATE #t SET [Address] = LEFT(b.Info,200) FROM #t a, #One b WHERE a.Id = @Id AND b.Id = 8
			UPDATE #t SET QQ = LEFT(b.Info,15) FROM #t a, #One b WHERE a.Id = @Id AND b.Id = 9 
		END
	END 
	--插入maindb..precoldcustomer表中 
	SET @Id = 0
	WHILE EXISTS(SELECT 'x' FROM #t WHERE Id > @Id)
	BEGIN
		SELECT TOP 1 @Id = Id, @cpName = CompanyName FROM #t WHERE Id > @Id ORDER BY ID
		--删除在maindb..precoldcustomer的数据
		DELETE FROM #t WHERE  EXISTS(SELECT 'x' FROM Maindb..precoldcustomer WHERE companyName=@cpName) AND companyName=@cpName 
		--删除在coldcustomer表中的数据,0库的保留，同时删除0库数据
		DELETE FROM #t WHERE  EXISTS(SELECT 'x' FROM Maindb..coldcustomer WHERE companyName=@cpName AND ProvinceID=LEFT(@ProvinceId,2) AND ISNULL(addMan,0)!=0) AND companyName=@cpName
		--删除0库数据
		DELETE FROM Maindb..coldcustomer WHERE companyName=@cpName AND ProvinceID=LEFT(@ProvinceId,2) AND ISNULL(addMan,0) =0
		
		DELETE FROM #t WHERE companyName LIKE '%保险%'
		
		IF LEN(@ProvinceId )=4
		BEGIN
			--删除有顾问的--删除已认证的
			DELETE FROM #t WHERE companyName=@cpName  AND EXISTS(SELECT 'X' FROM cpMain WHERE name =@cpName AND dcProvinceID=LEFT(@ProvinceId,2)  AND (ISNULL(ConsultantID,0)>0 OR ISNULL(MemberType,0)>1))
			
		END
		ELSE
		BEGIN
		--有顾问的（上次联系时间，和登录时间不为空的）
			--3（6）个月内未联系，删除3（6）个月内联系过的
			DELETE FROM #t 
			WHERE EXISTS
			(
				SELECT 'x'  FROM  cpMain  
				WHERE  NAME=@cpName 
				AND dcProvinceID=LEFT(@ProvinceId,2)
				AND  ISNULL(ConsultantID,-1)!=-1
				AND id =(
						SELECT TOP 1 companyID 
						FROM MainDB..contact
						WHERE companyID = CpMain.ID 
						AND addDate>@dtLastContactDate 
						ORDER BY addDate DESC
						)
			) AND companyName=@cpName
			--6个月未登录，删除6个月内登录过的
			DELETE FROM #t 
			WHERE EXISTS
			(
				SELECT 'x'  FROM  cpMain  
				WHERE  NAME=@cpName
				AND dcProvinceID=LEFT(@ProvinceId,2)
				AND  ISNULL(ConsultantID,-1)!=-1
				AND   LastLoginDate>@dtLastLoginDate 
			) AND companyName=@cpName
		--无顾问 
			--无执照且一个月未登录，删除一个月内登录的
 			DELETE FROM #t 
			WHERE EXISTS
			(
				SELECT 'x'  FROM  cpMain  
				WHERE  NAME=@cpName
				AND dcProvinceID=LEFT(@ProvinceId,2)
				AND	ISNULL(ConsultantID,-1)=-1
				AND HasLicence=0
				AND LastLoginDate>DateAdd(month,-1,getdate())
			) AND companyName=@cpName
			--有执照且三个月未登录，删除3个月内登录的
			DELETE FROM #t 
			WHERE EXISTS
			(
				SELECT 'x'  FROM  cpMain  
				 WHERE  NAME=@cpName
				AND dcProvinceID=LEFT(@ProvinceId,2)
				AND	ISNULL(ConsultantID,-1)=-1
				AND HasLicence=1
				AND LastLoginDate>DateAdd(month,-3,getdate())
			) AND companyName=@cpName 

			--删除vip			
			DELETE FROM #t 
			WHERE EXISTS
			(
				SELECT 'x'  FROM  cpMain  
				WHERE  NAME=@cpName
				AND dcProvinceID=LEFT(@ProvinceId,2)
				AND MemberType=3
			) AND companyName=@cpName
			
			END
	END
	--插入数据 
			IF EXISTS(SELECT 'x' FROM #t)
			BEGIN
				IF LEN(@ProvinceId)=4
				BEGIN
					INSERT INTO precoldcustomer(State,SourceType,CompanyName,LinkMan,Phone,Tel,Email,SourceLink,[Address],QQ, AddDate, IsSpread )
					SELECT 0,SourceType,CompanyName,LinkMan,Phone,Tel,Email,SourceLink,[Address],QQ, GETDATE(), 1  FROM #t
				END
				ELSE
				BEGIN
					INSERT INTO precoldcustomer(State,SourceType,CompanyName,LinkMan,Phone,Tel,Email,SourceLink,[Address],QQ, AddDate)
					SELECT 0,SourceType,CompanyName,LinkMan,Phone,Tel,Email,SourceLink,[Address],QQ, GETDATE()  FROM #t
				END
			END 		
END
SET NOCOUNT OFF
GO
/****** Object:  StoredProcedure [dbo].[proccoldcustomerUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--proccoldcustomerUpdate
--后台冷客户的手机号，邮箱重复校正，每天运行一次
--harry 
--2017-12-28
CREATE PROCEDURE [dbo].[proccoldcustomerUpdate]
AS
BEGIN
SET NOCOUNT ON 
    CREATE TABLE #t(
		Id INT , 
		coldId INT,
		CompanyName  VARCHAR(200), 
		Phone varchar(50),
		Tel varchar(50),
		Email varchar(50), 
		IsNameRepeat BIT,
		IsEmailRepeat BIT,
		IsMobileRepeat BIT  
	)
	INSERT INTO #t(id,coldId,companyName,Phone,Tel,Email,IsNameRepeat,IsEmailRepeat,IsMobileRepeat)
	select b.id,a.id, a.companyName, a.Phone, a.Phone, a.Email,a.IsNameRepeat,a.IsEmailRepeat,a.IsMobileRepeat
	from coldcustomer a, cpmain b
	WHERE (a.IsNameRepeat=1 OR a.isEmailRepeat =1 OR a.IsMobilerepeat=1 )
	and b.name =a.CompanyName
	and a.cpmainid  is NOT null


	UPDATE u
	SET u.IsNameRepeat=(
			CASE WHEN EXISTS(select 'x' from MainDB..CpMain a where a.name =#t.CompanyName AND a.id!=#t.id )
			THEN 1 
			ELSE 0 END),
		u.IsEmailRepeat=(
			CASE WHEN #t.Email!=''
			THEN
				(CASE WHEN EXISTS(select 'x' from MainDB..CaMain a where a.email =#t.Email and a.id=#t.id)
				THEN 1 
				ELSE 0 END)
			ELSE 0 END),
		u.IsMobileRepeat=(
			CASE WHEN ISNULL(#t.Phone,'')!=''
			THEN 
				(CASE WHEN ISNULL(#t.Phone,'')!='' AND EXISTS(select 'x' from MainDB..CaMain a 
					where (a.Telephone like #t.Phone+ '%' or a.mobile=#t.Phone)
					AND a.CpMainId !=#t.id)
				THEN 1
				WHEN ISNULL(#t.Phone,'')!='' AND EXISTS(select 'x' from MainDB..CaMain a
					where a.mobile=#t.Phone and a.cpMainID !=#t.id)
				THEN 1
				WHEN ISNULL(#t.Phone,'')!='' AND EXISTS(select 'x' from MainDB..CaMain a 
					where a.Telephone like #t.Phone+'%' and a.CpMainID!=#t.id)
				THEN 1
				ELSE 0
				END)
			ELSE 0
			END) 
	FROM coldcustomer u, #t
	WHERE u.id =#t.coldid
	
    DROP TABLE #t
SET NOCOUNT OFF
END
GO
/****** Object:  StoredProcedure [dbo].[ProcCommentCompanyListSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.27
--创建人：Nick
--说明：获取点评公司列表
--#####################################################
CREATE PROCEDURE [dbo].[ProcCommentCompanyListSelect]
(
	@dcRegionID VARCHAR(100),
	@PageNo INT,
	@KeyWord VARCHAR(50)
)
AS
BEGIN TRY
	DECLARE @WHERE VARCHAR(MAX),@JobPlace AS VARCHAR(2000)
	SET @JobPlace = ''
	SET @WHERE = ''
	
	IF CHARINDEX(',',@dcRegionID)>0
	BEGIN
		DECLARE @T_JobPlace AS TABLE(ID INT)
		INSERT INTO @T_JobPlace
		SELECT * FROM dbo.fnSplit(@dcRegionID, ',')
		
		SELECT @JobPlace = (@JobPlace + ' OR b.dcRegionID Like ''' + LTRIM(STR(ID) + '%''')) FROM @T_JobPlace
		
		IF LEN(@JobPlace) > 0
		SET @JobPlace = RIGHT(@JobPlace, LEN(@JobPlace) -4)
		SET @WHERE = @WHERE + '
			AND (' + @JobPlace + ')'
	END
	ELSE
	BEGIN
		SET @WHERE = ' AND (b.dcRegionID Like '''+@dcRegionID+'%'')'
	END
	
	SET @KeyWord = dbo.SafeSQL(ISNULL(@KeyWord, ''))
	
	IF @KeyWord <> ''
	BEGIN
		SET @WHERE = @WHERE + ' AND b.Name LIKE  ''%'+@KeyWord+'%'' '
	END
	
	DECLARE @PageSize INT
	SET @PageSize = 5
    DECLARE @PageLowerBound  INT --定义此页的底码
    DECLARE @PageUpperBound  INT --定义此页的顶码
    SET @PageLowerBound = (@PageNo -1) * @pagesize
    SET @PageUpperBound = @PageLowerBound + @pagesize
	
	DECLARE @AllCnt INT
	SET @AllCnt = 0
	DECLARE @SQL NVARCHAR(MAX)
	SET @SQL = N'
		SELECT @All = COUNT(DISTINCT CpMainID) 
		FROM  Comments a,Cpmain b
		WHERE (a.CommentType IN (1,2))
		AND a.id IN(SELECT MAX(id) FROM comments GROUP BY cpmainid)
		AND a.CpMainID = b.ID
	'+@WHERE
	exec sp_executesql @SQL,N'@All INT output',@AllCnt output
	
	IF @AllCnt>500
	BEGIN
		SET @AllCnt = 500
	END
	
	--SET @SQL = 'SELECT TOP 5000 rid=ROW_NUMBER() OVER(PARTITION BY CpmainID ORDER BY a.AddDate DESC),a.CpMainID,a.AddDate INTO ##Tmp
	--   FROM Comments a, CpMain b WHERE a.cpMainID=b.ID '+@WHERE
	----exec sp_executesql @SQL,N'#Tmp INT output',#Tmp2 output
	
	SET @SQL = '
		SELECT TOP 500 cpmainid,b.name,b.secondid,a.AddDate INTO ##T1
		FROM comments a,cpmain b
		WHERE a.id IN(SELECT MAX(id) FROM comments GROUP BY cpmainid)
		AND a.cpmainid = b.id AND a.CommentType IN(1,2) '+@WHERE+'
		ORDER BY a.adddate DESC	'
	EXEC(@SQL)
	
	SELECT * ,ROW_NUMBER() OVER( ORDER BY AddDate DESC) AS num INTO #T2 FROM ##T1
	
	SELECT *,0 AS cnt,0 AS Score INTO #T3 FROM #T2 WHERE NUM > @PageLowerBound AND NUM <= @PageUpperBound
	
	--修改评价数量
	UPDATE a
	SET a.cnt = b.Num
	FROM #T3 a,(
		SELECT COUNT(*) AS num,CpMainID
		FROM Comments
		WHERE (CommentType IN (1,2))
		AND CpMainID IN (SELECT CpMainID FROM #T3)
		GROUP BY CpMainID
	)b
	WHERE a.CpMainID = b.CpMainID
	
	--修改平均分数
	UPDATE a
	SET a.Score = b.Score
	FROM #T3 a,(
		SELECT CONVERT(DECIMAL(18,1),(SUM(GradeStar)*1.0)/(COUNT(*)*1.0)) AS Score,CpMainID
		FROM Comments
		WHERE CommentType IN (1,2)
		AND CpMainID IN (SELECT CpMainID FROM #T3)
		GROUP BY CpMainID
	)b
	WHERE a.CpMainID = b.CpMainID
	
	SELECT * FROM #T3
	
	SELECT @AllCnt
		
	SELECT * FROM 
	(
	   SELECT rid=ROW_NUMBER() OVER(PARTITION BY a.CpmainID ORDER BY a.AddDate DESC),*
	   FROM Comments a
	   WHERE  (a.CommentType IN (1,2))
	   AND CpMainID IN (SELECT CpMainID FROM #T3)
	) AS c
	WHERE c.rid<=2
	
	DROP TABLE ##T1
END TRY
BEGIN CATCH
	DROP TABLE ##T1
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[ProcCommentPraiseByIDUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.20
--创建人：Nick
--说明：根据点评ID 点赞
--修改：harry,修改登录用户未点击提示点击的bug20151224
--#####################################################
CREATE PROCEDURE [dbo].[ProcCommentPraiseByIDUpdate]
(
	@ID INT,
	@PaMainID INT,
	@CommentType INT --1 点评 2面试经历
)
AS
BEGIN 
	IF @PaMainID = 0
	BEGIN
		--只更新总数
		IF @CommentType = 1
		BEGIN
			UPDATE Comments 
			SET PraiseCount = PraiseCount+1
			WHERE ID = @ID
		END
		ELSE
		BEGIN
			UPDATE InterView 
			SET PraiseCount = PraiseCount+1
			WHERE ID = @ID
		END
		RETURN 1
	END
	ELSE 
	BEGIN
		--判断用户是否点过赞
		DECLARE @Tmp INT
		SELECT @Tmp = COUNT(*) FROM CommentPraise WHERE CommentID = @ID AND CommentType = @CommentType AND pamainId=@PaMainID
		IF @Tmp = 0 --没点过
		BEGIN
			INSERT INTO CommentPraise (CommentID,CommentType,AddDate,PamainID)
			VAlUES (@ID,@CommentType,GETDATE(),@PaMainID)
			
			IF @CommentType = 1 --更新点评 点赞总数
			BEGIN
				UPDATE Comments
				SET PraiseCount = PraiseCount+1,
					LoginPraiseCount = LoginPraiseCount+1
				WHERE ID = @ID
			END
			ELSE
			BEGIN
				UPDATE InterView
				SET PraiseCount = PraiseCount+1,
					LoginPraiseCount = LoginPraiseCount+1
				WHERE ID = @ID
			END
			RETURN 1
		END
		ELSE
			RETURN 0
	END
	RETURN 0
End

 
GO
/****** Object:  StoredProcedure [dbo].[ProcCommentsByCompanyIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.20
--创建人：Nick
--说明：根据公司ID获取 点评信息,以及平均分
--#####################################################
CREATE PROCEDURE [dbo].[ProcCommentsByCompanyIDSelect]
(
	@CpMainID INT,
	@SessionID VARCHAR(50),
	@paMainID INT
)
AS
SET NOCOUNT ON
--insert a2 select @cpmainid, @sessionId, @paMainID, GETDATE()
BEGIN 
	DECLARE @CommentCount INT --评论人数
	DECLARE @StarCount INT --星星数量
	DECLARE @StarScore DECIMAL(18,1)  --综合评分
	SELECT @CommentCount = COUNT(1),@StarCount = SUM(GradeStar) FROM Comments
	WHERE CpMainID = @CpMainID 
	AND CommentType<>3 
	AND VerifyDate IS NOT NULL
	
	IF @CommentCount>0
		SET @StarScore = @StarCount * 1.0 / @CommentCount
	ELSE
		SET @StarScore = 0
	
	IF @paMainID <> 0
	BEGIN
		SELECT * FROM Comments
		WHERE CpMainID = @CpMainID 
		AND CommentType<>3 
		AND (VerifyDate IS NOT NULL OR PaMainID = @paMainID)
		ORDER BY ADDDATE DESC
	END
	ELSE
	BEGIN
--		IF @SessionID<>''
--		BEGIN
--			SELECT * FROM Comments
--			WHERE CpMainID = @CpMainID 
--			AND CommentType<>3 
--			AND (VerifyDate IS NOT NULL OR (PaMainID = 0 AND SessionID = @SessionID))
--			ORDER BY ADDDATE DESC
--		END
--		ELSE
--		BEGIN
			SELECT * FROM Comments WITH(NOLOCK INDEX(IX_Comments_Complex))
			WHERE CpMainID = @CpMainID 
			AND CommentType <> 3 
			AND VerifyDate IS NOT NULL
			ORDER BY ADDDATE DESC
--		END
	END
	SELECT @StarScore AS Score
End


GO
/****** Object:  StoredProcedure [dbo].[ProcCommentsByID]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.24
--创建人：Nick
--说明：根据ID获取点评信息
--#####################################################
CREATE PROCEDURE [dbo].[ProcCommentsByID]
(
	@ID INT
)
AS
BEGIN 
	SELECT * FROM Comments WHERE ID = @ID AND CommentType <> 3
End


GO
/****** Object:  StoredProcedure [dbo].[ProcCommentsByIDUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.18
--创建人：Nick
--说明：根据ID修改点评信息
--#####################################################
CREATE PROCEDURE [dbo].[ProcCommentsByIDUpdate]
(
	@ID INT,
	@Relation INT,
	@GradeStar INT,
	@Remark1 NVARCHAR(MAX),
	@Remark2 NVARCHAR(MAX),
	@Remark3 NVARCHAR(MAX),
	@Title NVARCHAR(50),
	@Position NVARCHAR(50),
	@WorkRegionID INT,
	@EntryDate VARCHAR(6),
	@QuitDate VARCHAR(6),
	@CommentType INT,
	@VerifyMan INT
)
AS
BEGIN TRY
	DECLARE @AddDate DATETIME,@CpName NVARCHAR(100),@Title2 NVARCHAR(50)

	SELECT @AddDate = a.AddDate,@CpName = b.Name,@Title2 = a.Title
	FROM Comments a,Cpmain b
	WHERE a.ID =  @ID
	AND a.CpMainID = b.ID

	UPDATE Comments
	SET Relation = @Relation,
	GradeStar = @GradeStar,
	Remark1 = @Remark1,
	Remark2 = @Remark2,
	Remark3 = @Remark3,
	Title = @Title,
	Position = @Position,
	WorkRegionID = @WorkRegionID,
	EntryDate = @EntryDate,
	QuitDate = @QuitDate,
	CommentType = @CommentType,
	VerifyMan = @VerifyMan,
	VerifyDate = GETDATE()
	WHERE CpMainID IN (SELECT ID FROM CPMAIN WHERE Name = @CpName)
	AND AddDate = @AddDate
	AND Title = @Title2
END TRY
BEGIN CATCH
	RETURN 0
END CATCH



GO
/****** Object:  StoredProcedure [dbo].[ProcCommentsByKeyWordSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--###########################
--创建时间：2014.11.27
--创建人：Nick
--说明：获取点评公司列表
--###########################
CREATE PROCEDURE [dbo].[ProcCommentsByKeyWordSelect]
(
	@dcRegionID VARCHAR(100),
	@PageNo INT,
	@KeyWord VARCHAR(50)
)
AS
BEGIN 
	DECLARE @WHERE VARCHAR(MAX),@JobPlace AS VARCHAR(2000),@WHERE2 VARCHAR(MAX)
	SET @JobPlace = ''
	SET @WHERE = ''
	SET @WHERE2 = ''
	
	IF CHARINDEX(',',@dcRegionID)>0
	BEGIN
		DECLARE @T_JobPlace AS TABLE(ID INT)
		INSERT INTO @T_JobPlace
		SELECT * FROM dbo.fnSplit(@dcRegionID, ',')
		
		SELECT @JobPlace = (@JobPlace + ' OR b.dcRegionID Like ''' + LTRIM(STR(ID) + '%''')) FROM @T_JobPlace
		
		IF LEN(@JobPlace) > 0
		SET @JobPlace = RIGHT(@JobPlace, LEN(@JobPlace) -4)
		SET @WHERE = @WHERE + '
			AND (' + @JobPlace + ')'
		SET @WHERE2 = @WHERE2 + '
			AND (' + @JobPlace + ')'
	END
	ELSE
	BEGIN
		SET @WHERE = ' AND (b.dcRegionID Like '''+@dcRegionID+'%'')'
		SET @WHERE2 = ' AND (b.dcRegionID Like '''+@dcRegionID+'%'')'
	END
	
	SET @KeyWord = dbo.SafeSQL(ISNULL(@KeyWord, ''))
	
	IF @KeyWord <> ''
	BEGIN
		SET @WHERE = @WHERE + ' AND b.Name LIKE  ''%'+@KeyWord+'%'' '
	END
	
	DECLARE @PageSize INT
	SET @PageSize = 5
    DECLARE @PageLowerBound  INT --定义此页的底码
    DECLARE @PageUpperBound  INT --定义此页的顶码
    SET @PageLowerBound = (@PageNo -1) * @pagesize
    SET @PageUpperBound = @PageLowerBound + @pagesize
	
	DECLARE @AllCnt INT
	SET @AllCnt = 0
	DECLARE @SQL NVARCHAR(MAX)
	
	--创建临时表
	CREATE TABLE #T1(
		[cpmainid] [int] NOT NULL,
		[name] [varchar](100) NULL,
		[secondid] varchar(12) NULL,
		[AddDate] [datetime] NULL,
		[OrderBY] [int] NULL
	)	

	IF @KeyWord = ''
	BEGIN
		SET @SQL = '
			INSERT INTO #T1
			SELECT TOP 500 cpmainid,b.name,b.secondid,a.AddDate,1 AS OrderBY
			FROM comments a,cpmain b
			WHERE a.id IN(SELECT TOP 999 MAX(id) FROM comments GROUP BY cpmainid ORDER BY MAX(ID) DESC)
			AND a.cpmainid = b.id AND a.CommentType IN(1,2) '+@WHERE+'
			AND a.IsDirect = 1
			ORDER BY a.adddate DESC	'
		EXEC(@SQL)
	END
	ELSE
	BEGIN
		SET @SQL = '
			INSERT INTO #T1
			SELECT TOP 500 b.ID AS cpmainid,b.Name, b.SecondId, LastLoginDate AS AddDate,1 AS OrderBY 
			FROM cpMainPublish b WITH(NOLOCK),
			CONTAINSTABLE(cpMainPublish, Name, '''+@KeyWord+''', 100) AS a
			WHERE b.Id = a.[Key] '+@WHERE2+'
			ORDER BY b. LastLoginDate DESC '
		--PRINT(@SQL)
		EXEC(@SQL)

		IF NOT EXISTS(SELECT 'x' FROM #T1)
		BEGIN
			SET @SQL = '
				INSERT INTO #T1
				SELECT TOP 500 b.ID AS cpmainid,b.Name, b.SecondId, LastLoginDate AS AddDate,1 AS OrderBY 
				FROM cpMainPublish b WITH(NOLOCK INDEX(IX_cpMainPublish_Name))
				WHERE 1=1 '+@WHERE+'
				ORDER BY b. LastLoginDate DESC '
			--PRINT(@SQL)
			EXEC(@SQL)
		END
	END
	
	SELECT @AllCnt = COUNT(*) FROM #T1 
	
	IF @KeyWord <> '' --对临时表 #T1 进行排序 修改最后点评时间
	BEGIN
		UPDATE a 
		SET a.AddDate = b.AddDate,a.OrderBY = b.OrderBY
		FROM #T1 a,(
			SELECT AddDate,CpMainID,2 AS OrderBy 
			FROM  Comments
			WHERE ID IN(SELECT MAX(id) FROM comments GROUP BY cpmainid) 
		) b
		WHERE a.CpmainID = b.CpMainID
	END
	
	SELECT * ,ROW_NUMBER() OVER( ORDER BY OrderBY DESC,AddDate DESC) AS num INTO #T2 FROM #T1
	
		--创建临时表
	CREATE TABLE #T3(
		[cpmainid] [int] NOT NULL,
		[name] [varchar](100) NULL,
		[secondid] varchar(12) NULL,
		[AddDate] [datetime] NULL,
		[OrderBY] [int] NULL,
		[num] [int] null,
		cnt INT NULL,
		Score DECIMAL(18, 1) NULL
	)	

	INSERT INTO #T3
	SELECT *,0 AS cnt,1.0 AS Score FROM #T2 WHERE NUM > @PageLowerBound AND NUM <= @PageUpperBound
	
	--修改评价数量
	UPDATE a
	SET a.cnt = b.Num
	FROM #T3 a,(
		SELECT COUNT(*) AS num,CpMainID
		FROM Comments
		WHERE (CommentType IN (1,2))
		AND CpMainID IN (SELECT CpMainID FROM #T3)
		GROUP BY CpMainID
	)b
	WHERE a.CpMainID = b.CpMainID
	
	--修改平均分数
	UPDATE a
	SET a.Score = b.Score
	FROM #T3 a,(
		SELECT SUM(GradeStar)*1.0 AS Score,CpMainID
		FROM Comments
		WHERE CommentType IN (1,2)
		AND CpMainID IN (SELECT CpMainID FROM #T3)
		GROUP BY CpMainID
	)b
	WHERE a.CpMainID = b.CpMainID
	
	UPDATE #T3
	SET Score = CONVERT(DECIMAL(18,1),(Score*1.0)/(cnt*1.0))
	WHERE cnt>0
	
	UPDATE #T3 
	SET Score = 0
	WHERE cnt = 0
	
	--拷贝列
	CREATE TABLE #T5(
		[ID] [int] NOT NULL,
		[CpMainID] [int] NOT NULL,
		[PaMainID] [int] NOT NULL,
		[IP] [varchar](15) NULL,
		[SessionID] [varchar](50) NULL,
		[Relation] [tinyint] NOT NULL,
		[GradeStar] [tinyint] NOT NULL,
		[Remark1] [nvarchar](max) NOT NULL,
		[Remark2] [nvarchar](max) NOT NULL,
		[Remark3] [nvarchar](max) NOT NULL,
		[Title] [nvarchar](50) NOT NULL,
		[Position] [nvarchar](50) NULL,
		[WorkRegionID] [varchar](6) NULL,
		[EntryDate] [varchar](6) NULL,
		[QuitDate] [varchar](6) NULL,
		[AddDate] [smalldatetime] NOT NULL,
		[CommentType] [tinyint] NULL,
		[VerifyMan] [int] NULL,
		[VerifyDate] [smalldatetime] NULL,
		[ReplyDate] [smalldatetime] NULL,
		[ReplyContent] [nvarchar](max) NULL,
		[ReplyVerifyMan] [int] NULL,
		[ReplyVerifyDate] [smalldatetime] NULL,
		[PraiseCount] [int] NULL,
		[LoginPraiseCount] [int] NULL,
		[ReplyVerifyResult] [int] NULL,
		[IsDirect] [BIT] NULL,
		[rid] [int] NULL
	)
		
	DECLARE @CpCnt INT --公司数量
	SELECT @CpCnt = COUNT(*) FROM #T3
	IF @CpCnt = 1 
	BEGIN
		--取10条点评
		INSERT INTO #T5 
		SELECT * FROM 
		(
		   SELECT *,rid=ROW_NUMBER() OVER(PARTITION BY a.CpmainID ORDER BY a.AddDate DESC)
		   FROM Comments a
		   WHERE  (a.CommentType IN (1,2))
		   AND CpMainID IN (SELECT CpMainID FROM #T3)
		) AS c
		WHERE c.rid<=10
	END
	ELSE
	BEGIN
		--取2条点评
		INSERT INTO #T5  
		SELECT * FROM 
		(
		   SELECT *,rid=ROW_NUMBER() OVER(PARTITION BY a.CpmainID ORDER BY a.AddDate DESC)
		   FROM Comments a
		   WHERE  (a.CommentType IN (1,2))
		   AND CpMainID IN (SELECT CpMainID FROM #T3)
		) AS c
		WHERE c.rid<=2
	END
	
	SELECT * FROM #T3  --公司列表
	
	SELECT @AllCnt     --所有公司数
		
	SELECT * FROM #T5  --点评数
	
	--DROP TABLE #T1
	DROP TABLE #T5
END 


GO
/****** Object:  StoredProcedure [dbo].[ProcCommentsByPaMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.12
--创建人：Nick
--说明：判断用户是否发布过点评或面试经历
--#####################################################
CREATE PROCEDURE [dbo].[ProcCommentsByPaMainIDSelect]
(
	@PamainID INT,
	@Type INT --1点评 2面试经历
)
AS
BEGIN 
	IF @Type = 1
	BEGIN
		SELECT ID FROM Comments WHERE CommentType<>3 AND PamainID  = @PamainID
	END
	ELSE
	BEGIN
		SELECT ID FROM InterView WHERE InterviewType<>3 AND PamainID  = @PamainID
	END
End


GO
/****** Object:  StoredProcedure [dbo].[ProcCommentsByReplyUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.20
--创建人：Nick
--说明：点评回复
--#####################################################
CREATE PROCEDURE [dbo].[ProcCommentsByReplyUpdate]
(
	@ID INT,
	@ReplyContent NVARCHAR(MAX)
)
AS
BEGIN 
	UPDATE Comments 
	SET ReplyContent = @ReplyContent,
	ReplyDate = GETDATE() ,
	ReplyVerifyResult = NULL ,
	ReplyVerifyDate  = NULL
	WHERE ID = @ID
	AND (ReplyVerifyResult <> 1 OR ReplyVerifyResult IS NULL)
End


GO
/****** Object:  StoredProcedure [dbo].[ProcCommentsHotSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.27
--创建人：Nick
--说明：获取最多点评排行 最佳点评排行
--#####################################################
CREATE PROCEDURE [dbo].[ProcCommentsHotSelect]
(
	@ProvinceID INT
)
AS
BEGIN 
	--最多面经排行
	SELECT * FROM SearchDB..CommentsHot
	WHERE CommentType = 1
	AND TypeID = 1
	AND dcProvinceID = @ProvinceID
	ORDER BY Cnt DESC
	
	--最佳点评排行
	SELECT * FROM SearchDB..CommentsHot
	WHERE CommentType = 1
	AND TypeID = 2
	AND dcProvinceID = @ProvinceID
	ORDER BY Cnt DESC
END


GO
/****** Object:  StoredProcedure [dbo].[ProcCommentsInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.20
--创建人：Nick
--说明：插入点评
--#####################################################
CREATE PROCEDURE [dbo].[ProcCommentsInsert]
(
	@CpmainID INT,
	@PaMainID INT,
	@IP VARCHAR(15),
	@SessionID VARCHAR(50),
	@Relation INT,
	@GradeStar INT,
	@Remark1 NVARCHAR(MAX),
	@Remark2 NVARCHAR(MAX),
	@Remark3 NVARCHAR(MAX),
	@Title NVARCHAR(50),
	@Position NVARCHAR(50),
	@WorkRegionID INT,
	@EntryDate VARCHAR(6),
	@QuitDate VARCHAR(6)
)
AS
BEGIN 
	DECLARE @MemberType INT
	SELECT @MemberType = MemberType FROM CpMain WHERE ID  = @CpmainID
	IF @MemberType > 1
	BEGIN
		INSERT INTO Comments (CpmainID,PaMainID,IP,SessionID,Relation,GradeStar,Remark1,Remark2,Remark3,Title,
			Position,WorkRegionID,EntryDate,QuitDate,AddDate,PraiseCount,LoginPraiseCount,CommentType,IsDirect)
		SELECT ID,@PaMainID,@IP,@SessionID,@Relation,@GradeStar,@Remark1,@Remark2,@Remark3,@Title,
			@Position,@WorkRegionID,@EntryDate,@QuitDate,GETDATE(),0,0 ,0,0
		FROM CPMAIN 
		WHERE NAME = (
			SELECT Name FROM CpMain WHERE ID = @CpmainID)
		AND MemberType > 1
		AND ID <> @CpmainID
	END
	
	INSERT INTO Comments (CpmainID,PaMainID,IP,SessionID,Relation,GradeStar,Remark1,Remark2,Remark3,Title,
		Position,WorkRegionID,EntryDate,QuitDate,AddDate,PraiseCount,LoginPraiseCount,CommentType,IsDirect)
	VALUES(@CpmainID,@PaMainID,@IP,@SessionID,@Relation,@GradeStar,@Remark1,@Remark2,@Remark3,@Title,
		@Position,@WorkRegionID,@EntryDate,@QuitDate,GETDATE(),0,0 ,0,1 )
End


GO
/****** Object:  StoredProcedure [dbo].[ProcCommentsInterviewByHomePageSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.12.3
--创建人：John
--说明：前台首页根据省份ID获取点评与面经的最新5条记录
--#####################################################
CREATE PROCEDURE [dbo].[ProcCommentsInterviewByHomePageSelect]
(
	@dcProvinceID INT
)
AS
BEGIN
	SELECT TOP 0 * FROM SearchDb..Hp_Comments WITH(NOLOCK) --WHERE ProvinceId = @dcProvinceID ORDER BY AddDate DESC
	/*
	SELECT TOP 5 * FROM
		(
			SELECT * FROM 
				(
					SELECT TOP 5 a.ID,a.CpMainID,a.Title,a.AddDate,1 AS CIType, a.CommentType AS IsGood,b.Name,b.SecondID 
					FROM Comments a WITH(NOLOCK),CpMain b WITH(NOLOCK)
					WHERE a.CommentType IN (1,2) 
						AND a.CpMainID = b.ID 
						AND b.dcRegionID like ''+CONVERT(VARCHAR(6),@dcProvinceID)+'%'
						AND a.IsDirect = 1
					ORDER BY a.AddDate DESC
				) AS tempComment
			UNION 
			SELECT * FROM 
				(
					SELECT TOP 5 a.ID,a.CpMainID,a.Title,a.AddDate,2 AS CIType, a.InterviewType AS IsGood,b.Name,b.SecondID 
					FROM InterView a WITH(NOLOCK), cpmain b WITH(NOLOCK)
					WHERE a.InterviewType IN (1,2) 
						AND a.CpMainID = b.ID 
						AND b.dcRegionID like ''+CONVERT(VARCHAR(6),@dcProvinceID)+'%'
						AND a.IsDirect = 1
					ORDER BY a.AddDate DESC
				) AS tempInterview
		) AS CIResult ORDER BY AddDate DESC
	*/
END


GO
/****** Object:  StoredProcedure [dbo].[ProcCommentsReplyByIDUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.18
--创建人：Nick
--说明：根据ID修改点评回复信息
--#####################################################
CREATE PROCEDURE [dbo].[ProcCommentsReplyByIDUpdate]
(
	@ID INT,
	@ReplyContent NVARCHAR(MAX),
	@ReplyVerifyMan INT,
	@ReplyVerifyResult INT
)
AS
BEGIN
	UPDATE Comments
	SET ReplyContent = @ReplyContent,
		ReplyVerifyMan = @ReplyVerifyMan,
		ReplyVerifyDate = GETDATE(),
		ReplyVerifyResult = @ReplyVerifyResult
	WHERE ID = @ID
END


GO
/****** Object:  StoredProcedure [dbo].[ProcCommentsSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.18
--创建人：Nick
--说明：查询 点评信息 用于后台审核
--#####################################################
CREATE PROCEDURE [dbo].[ProcCommentsSelect]
(
	@Type INT, --1 待审核 点评 2 最近审核 点评 3待审核点评回复 4最近审核 点评回复
	@Where VARCHAR(MAX)
)
AS
BEGIN
	DECLARE @SQL VARCHAR(MAX)
	IF @Type = 1
	BEGIN
		SET @SQL = '
			SELECT a.*,b.name AS CpName,b.RegDate,
			CASE a.PamainID
			WHEN 0 THEN IP
			ELSE (SELECT Name FROM PaMain WHERE ID = a.PaMainID)
			END AS PaName
			FROM Comments a,CpMain b
			WHERE VerifyDate IS NULL
			AND a.IsDirect = 1
			AND a.CpMainID = b.ID '+@Where+'
			ORDER BY AddDate DESC '
	END
	ELSE IF @Type = 2
	BEGIN
		SET @SQL = '
			SELECT a.*,b.name AS CpName ,b.RegDate,
			CASE a.PamainID
			WHEN 0 THEN IP
			ELSE (SELECT Name FROM PaMain WHERE ID = a.PaMainID)
			END AS PaName
			FROM Comments a,CpMain b
			WHERE VerifyDate IS NOT NULL
			AND a.CpMainID = b.ID '+@Where+'
			ORDER BY VerifyDate DESC'
	END
	ELSE IF @Type = 3
	BEGIN
		SET @SQL = '
			SELECT a.*,b.name AS CpName ,b.RegDate,
			CASE a.PamainID
			WHEN 0 THEN IP
			ELSE (SELECT Name FROM PaMain WHERE ID = a.PaMainID)
			END AS PaName
			FROM Comments a,CpMain b
			WHERE ReplyVerifyDate IS NULL
			AND a.CpMainID = b.ID '+@Where+'
			ORDER BY ReplyDate DESC'
	END
	ELSE IF @Type = 4
	BEGIN
		SET @SQL = '
			SELECT a.*,b.name AS CpName ,b.RegDate,
			CASE a.PamainID
			WHEN 0 THEN IP
			ELSE (SELECT Name FROM PaMain WHERE ID = a.PaMainID)
			END AS PaName
			FROM Comments a,CpMain b
			WHERE ReplyVerifyDate IS NOT NULL
			AND a.CpMainID = b.ID '+@Where+'
			ORDER BY ReplyVerifyDate DESC'
	END
	EXEC(@SQL)
END


GO
/****** Object:  StoredProcedure [dbo].[ProcCommentsVerifyUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2014.11.19
--创建人：Nick
--说明：批量审核点评或面试信息
---增加审核记录,用于计算审核延误7
--#####################################################
CREATE PROCEDURE [dbo].[ProcCommentsVerifyUpdate]
(
	@ID INT,
	@Type INT , -- 1点评 2点评 回复 3 面试经历 4面试经历回复
	@VerifyMan INT,
	@VerifyResult INT
)
AS
SET NOCOUNT ON
BEGIN
	DECLARE @submitDate DATETIME
	IF @Type = 1
	BEGIN
		UPDATE Comments
		SET VerifyMan = @VerifyMan,
			VerifyDate = GETDATE(),
			CommentType = @VerifyResult
		WHERE ID =@ID
		
		SELECT @submitDate=AddDate 
		FROM Comments
		WHERE ID =@ID
	END
	ELSE IF @Type = 2
	BEGIN
		UPDATE Comments
		SET ReplyVerifyMan = @VerifyMan,
			ReplyVerifyDate = GETDATE(),
			ReplyVerifyResult = @VerifyResult
		WHERE ID =@ID
		
		SELECT @submitDate=ReplyDate 
		FROM Comments
		WHERE ID =@ID
		
	END
	ELSE IF @Type = 3
	BEGIN
		UPDATE Interview
		SET VerifyMan = @VerifyMan,
			VerifyDate = GETDATE(),
			InterviewType = @VerifyResult
		WHERE ID =@ID
		
		SELECT @submitDate=AddDate 
		FROM Interview
		WHERE ID =@ID
	END
	ELSE IF @Type = 4
	BEGIN
		UPDATE Interview
		SET ReplyVerifyMan = @VerifyMan,
			ReplyVerifyDate = GETDATE(),
			ReplyVerifyResult = @VerifyResult
		WHERE ID =@ID
		
		SELECT @submitDate=ReplyDate 
		FROM Interview
		WHERE ID =@ID
	END
	  --插入审核延误记录表  
	INSERT INTO logdb..VerifyDelayLog(verifyType, relationId, submitDate, verifyDate, verifyMan)
	SELECT 7,@ID,@submitDate, GETDATE(), @VerifyMan
END

GO
/****** Object:  StoredProcedure [dbo].[procCompanyByFixPositionIndustrySelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--创建人 sean
--20111121
--用于首页查询固定位置单位名称,按行业划分的
--###########################3
---知名企业招聘的hot 是按照 职位的最新增加日期， 加hot的大约是总数的1/5
---推荐职位 是在最新发布的职位上加new，数量平均6、7个
---热门职位是根据营业执照审核时间最新的加hot，数量是10个
--###########################3
CREATE PROCEDURE [dbo].[procCompanyByFixPositionIndustrySelect] 
(
	@subSiteID INT
)
AS
BEGIN
	DECLARE @t AS TABLE(
		ID int IDENTITY(1,1),
		cpMainID VARCHAR(10),
		Name varchar(100),
		JobID varchar(max),
		JobName nvarchar(max),
		Paid numeric(18, 2),
		OpenDate smalldatetime,
		NewXId VARCHAR(12),
		AddDate datetime,
		caORderID INT,
		IndustryCategory INT,
		NoFollow VARCHAR(1)
	)

	IF @subSiteID < 100		--省站
		INSERT @t(cpMainID, Name, Paid, OpenDate, JobID, JobName, NewXId, AddDate, caORderID, IndustryCategory, NoFollow)
		SELECT cpMainID, Name, Paid, OpenDate, JobID, JobName, NewXId, AddDate, caORderID, IndustryCategory, NoFollow
		FROM FpFixPosition
		WHERE dcProvinceId = @subSiteID
		ORDER BY AddDate DESC
	ELSE
		INSERT @t(cpMainID, Name, Paid, OpenDate, JobID, JobName, NewXId, AddDate, caORderID, IndustryCategory, NoFollow)
		SELECT cpMainID, Name, Paid, OpenDate, JobID, JobName, NewXId, AddDate, caORderID, IndustryCategory, NoFollow
 		FROM FpFixPosition
		WHERE dcRegionID LIKE LTRIM(STR(@subSiteID)) + '%'
		OR dcSubSiteID LIKE LTRIM(STR(@subSiteID)) + '%'
		ORDER BY AddDate DESC

	
	DECLARE @Num INT, @FlagNum INT, @Sql VARCHAR(MAX)
	SELECT @Num = COUNT(1) FROM @t
	IF @Num > 3
	BEGIN
		SELECT @FlagNum = @Num / 3 + 1
		UPDATE @t SET NewXId = NULL WHERE ID > @FlagNum
	END
	----加New图标

	SELECT ID, NoFollow + cpMainID cpMainID, Name, JobID, JobName, Paid, OpenDate, NewXId, AddDate, caORderID, IndustryCategory
	FROM @t
	ORDER BY IndustryCategory, CASE Paid WHEN 0 THEN 100 ELSE 0 END, OpenDate DESC
END











GO
/****** Object:  StoredProcedure [dbo].[procCompanyByFixPositionSecIndustrySelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--创建人 sean
--20111121
--用于首页查询固定位置单位名称,按行业划分的
--###########################3
---知名企业招聘的hot 是按照 职位的最新增加日期， 加hot的大约是总数的1/5
---推荐职位 是在最新发布的职位上加new，数量平均6、7个
---热门职位是根据营业执照审核时间最新的加hot，数量是10个
--###########################3
CREATE PROCEDURE [dbo].[procCompanyByFixPositionSecIndustrySelect] 
(
	@subSiteID INT
)
AS
BEGIN
	DECLARE @t AS TABLE(
		ID int IDENTITY(1,1),
		cpMainID VARCHAR(10),
		Name varchar(100),
		JobID varchar(max),
		JobName nvarchar(max),
		Paid numeric(18, 2),
		OpenDate smalldatetime,
		NewXId VARCHAR(12),
		AddDate datetime,
		caORderID INT,
		IndustryCategory INT,
		NoFollow VARCHAR(1)
	)

	IF @subSiteID < 100		--省站
		INSERT @t(cpMainID, Name, Paid, OpenDate, JobID, JobName, NewXId, AddDate, caORderID, IndustryCategory, NoFollow)
		SELECT cpMainID, Name, Paid, OpenDate, JobID, JobName, NewXId, AddDate, caORderID, IndustryCategory, NoFollow
		FROM FpFixPosition
		WHERE dcProvinceId = @subSiteID
		ORDER BY AddDate DESC
	ELSE
		INSERT @t(cpMainID, Name, Paid, OpenDate, JobID, JobName, NewXId, AddDate, caORderID, IndustryCategory, NoFollow)
		SELECT cpMainID, Name, Paid, OpenDate, JobID, JobName, NewXId, AddDate, caORderID, IndustryCategory, NoFollow
 		FROM FpFixPosition
		WHERE dcRegionID LIKE LTRIM(STR(@subSiteID)) + '%'
		OR dcSubSiteID LIKE LTRIM(STR(@subSiteID)) + '%'
		ORDER BY AddDate DESC

	
	DECLARE @Num INT, @FlagNum INT, @Sql VARCHAR(MAX)
	SELECT @Num = COUNT(1) FROM @t
	IF @Num > 3
	BEGIN
		SELECT @FlagNum = @Num / 3 + 1
		UPDATE @t SET NewXId = NULL WHERE ID > @FlagNum
	END
	----加New图标

	SELECT ID, NoFollow + cpMainID cpMainID, Name, JobID, JobName, Paid, OpenDate, NewXId, AddDate, caORderID, IndustryCategory
	FROM @t
	ORDER BY IndustryCategory, CASE Paid WHEN 0 THEN 100 ELSE 0 END, OpenDate DESC
END











GO
/****** Object:  StoredProcedure [dbo].[procCompanyByFixPositionSecSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--创建人 Lambo	
--20101009
--用于首页查询固定位置单位名称
--###########################3
---知名企业招聘的hot 是按照 职位的最新增加日期， 加hot的大约是总数的1/5
---推荐职位 是在最新发布的职位上加new，数量平均6、7个
---热门职位是根据营业执照审核时间最新的加hot，数量是10个
--###########################3
CREATE PROCEDURE [dbo].[procCompanyByFixPositionSecSelect] 
(
	@subSiteID INT
)
AS
BEGIN
	DECLARE @t AS TABLE(
		ID int IDENTITY(1,1),
		cpMainID varchar(10),
		Name varchar(100),
		JobID varchar(max),
		JobName nvarchar(max),
		Paid numeric(18, 2),
		OpenDate smalldatetime,
		NewXId VARCHAR(12),
		AddDate datetime,
		caORderID INT,
		NoFollow VARCHAR(1)
	)

	IF @subSiteID < 100		--省站
		INSERT @t(cpMainID, Name, Paid, OpenDate, JobID, JobName, NewXId, AddDate, caORderID, NoFollow)
		SELECT cpMainID, Name, Paid, OpenDate, JobID, JobName, NewXId, AddDate, caORderID, NoFollow
		FROM FpFixPosition WITH(NOLOCK)
		WHERE dcProvinceId = @subSiteID
		ORDER BY AddDate DESC
	ELSE
		INSERT @t(cpMainID, Name, Paid, OpenDate, JobID, JobName, NewXId, AddDate, caORderID, NoFollow)
		SELECT cpMainID, Name, Paid, OpenDate, JobID, JobName, NewXId, AddDate, caORderID, NoFollow
		FROM FpFixPosition WITH(NOLOCK)
		WHERE dcRegionID LIKE LTRIM(STR(@subSiteID)) + '%'
		OR dcSubSiteID LIKE LTRIM(STR(@subSiteID)) + '%'
		ORDER BY AddDate DESC

	
	DECLARE @Num INT, @FlagNum INT, @Sql VARCHAR(MAX)
	SELECT @Num = COUNT(1) FROM @t
	IF @Num > 3
	BEGIN
		SELECT @FlagNum = @Num / 3 + 1
		UPDATE @t SET NewXId = NULL WHERE ID > @FlagNum
	END
	----加New图标

	SELECT ID, NoFollow + cpMainID cpMainID, Name, JobID, JobName, Paid, OpenDate, NewXId, AddDate, caORderID
	FROM @t
	ORDER BY CASE Paid WHEN 0 THEN 100 ELSE 0 END, OpenDate DESC
END












GO
/****** Object:  StoredProcedure [dbo].[procCompanyByFixPositionSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--创建人 Lambo	
--20101009
--用于首页查询固定位置单位名称
--###########################3
---知名企业招聘的hot 是按照 职位的最新增加日期， 加hot的大约是总数的1/5
---推荐职位 是在最新发布的职位上加new，数量平均6、7个
---热门职位是根据营业执照审核时间最新的加hot，数量是10个
--###########################3
CREATE PROCEDURE [dbo].[procCompanyByFixPositionSelect] 
(
	@subSiteID INT
)
AS
BEGIN
	DECLARE @t AS TABLE(
		ID int IDENTITY(1,1),
		cpMainID varchar(10),
		Name varchar(100),
		JobID varchar(max),
		JobName nvarchar(max),
		Paid numeric(18, 2),
		OpenDate smalldatetime,
		NewXId VARCHAR(12),
		AddDate datetime,
		caORderID INT,
		NoFollow VARCHAR(1)
	)

	IF @subSiteID < 100		--省站
		INSERT @t(cpMainID, Name, Paid, OpenDate, JobID, JobName, NewXId, AddDate, caORderID, NoFollow)
		SELECT cpMainID, Name, Paid, OpenDate, JobID, JobName, NewXId, AddDate, caORderID, NoFollow
		FROM FpFixPosition WITH(NOLOCK)
		WHERE dcProvinceId = @subSiteID
		ORDER BY Paid DESC, AddDate DESC
	ELSE
	BEGIN
		IF @subSiteID = 3206 AND GETDATE() < '2017-4-29'
			INSERT @t(cpMainID, Name, Paid, OpenDate, JobID, JobName, NewXId, AddDate, caORderID, NoFollow)
			SELECT cpMainID, Name, Paid, OpenDate, JobID, JobName, NewXId, AddDate, caORderID, NoFollow
			FROM FpFixPosition WITH(NOLOCK)
			WHERE dcRegionID LIKE LTRIM(STR(@subSiteID)) + '%'
			OR dcSubSiteID LIKE LTRIM(STR(@subSiteID)) + '%'
			OR cpMainId = 'BFE74A5251'
			ORDER BY Paid DESC, AddDate DESC
		ELSE
			INSERT @t(cpMainID, Name, Paid, OpenDate, JobID, JobName, NewXId, AddDate, caORderID, NoFollow)
			SELECT cpMainID, Name, Paid, OpenDate, JobID, JobName, NewXId, AddDate, caORderID, NoFollow
			FROM FpFixPosition WITH(NOLOCK)
			WHERE dcRegionID LIKE LTRIM(STR(@subSiteID)) + '%'
			OR dcSubSiteID LIKE LTRIM(STR(@subSiteID)) + '%'
			ORDER BY Paid DESC, AddDate DESC
	END
	
	DECLARE @Num INT, @FlagNum INT, @Sql VARCHAR(MAX)
	SELECT @Num = COUNT(1) FROM @t
	IF @Num > 3
	BEGIN
		SELECT @FlagNum = @Num / 3 + 1
		UPDATE @t SET NewXId = NULL WHERE ID > @FlagNum
	END
	----加New图标

	SELECT ID, NoFollow + cpMainID cpMainID, Name, JobID, JobName, Paid, OpenDate, NewXId, AddDate, caORderID
	FROM @t
	ORDER BY CASE Paid WHEN 0 THEN 100 ELSE 0 END, OpenDate DESC
END














GO
/****** Object:  StoredProcedure [dbo].[procCompanyHomepageLogoSecSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[procCompanyHomepageLogoSecSelect] 
(
	@ProvinceID SMALLINT
)
AS
BEGIN
	SELECT ID, Name, ImgFile, JobIDs, JobNames
	FROM SearchDb..cpMainLogoShot
	WHERE dcProvinceID = @ProvinceID
	ORDER BY RowNo
END














GO
/****** Object:  StoredProcedure [dbo].[procCompanyHomepageLogoSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[procCompanyHomepageLogoSelect] 
(
	@ProvinceID SMALLINT
)
AS
BEGIN
	SELECT ID, Name, ImgFile, JobIDs, JobNames, RealCpMainId cpMainId
	FROM SearchDb..cpMainLogoShot
	WHERE dcProvinceID = @ProvinceID
	ORDER BY RowNo
END



GO
/****** Object:  StoredProcedure [dbo].[procCompanyHomepageLogoSelectNew]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[procCompanyHomepageLogoSelectNew] 
(
	@ProvinceID SMALLINT
)
AS
BEGIN
	SELECT ID, Name, ImgFile, JobIDs, JobNames
	FROM SEARCHDB..cpMainLogoShot
	WHERE dcProvinceID = @ProvinceID
	ORDER BY RowNo
END














GO
/****** Object:  StoredProcedure [dbo].[procCompanyHomepageSecSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[procCompanyHomepageSecSelect]
(
	@SubSiteId INT
)
AS
SET NOCOUNT ON
BEGIN
	DECLARE @ProvinceID AS INT,
		@RegionType AS INT,			----1:省站；2：二级站
		@RecommendNumber AS INT,		----推荐职位行数
		@HotNumber AS INT,		----热门职位行数
		@RowNumber AS INT,
		@Sql AS VARCHAR(MAX),
		@strRegion AS VARCHAR(100),
		@strMember AS VARCHAR(100)

	SELECT @RecommendNumber = 75, @RegionType = 1, @ProvinceID = @subSiteId
	IF @subSiteId > 100
	BEGIN
		SET @RegionType = 2
		SET @ProvinceID = LEFT(@subSiteId, 2)
	END
	
	---将推荐职位的和热门的企业都放在临时表中
	CREATE TABLE #t(
		ID int IDENTITY(1,1) NOT NULL,
		dcSubsiteID smallint NULL,
		dcRegionID varchar(6) COLLATE Chinese_PRC_CI_AS NULL,
		cpMainID VARCHAR(11) NULL,
		Name varchar(100) COLLATE Chinese_PRC_CI_AS NULL,
		IsAgent bit NULL,
		JobNumber int NULL,
		JobID varchar(max) COLLATE Chinese_PRC_CI_AS NULL,
		JobName nvarchar(max) COLLATE Chinese_PRC_CI_AS NULL,
		LastJobIssueDate smalldatetime NULL,
		LastJobId VARCHAR(12) NULL,
		cpLicenceDate smalldatetime NULL,
		RefreshDate smalldatetime NULL,
		MemberType tinyint NULL,
		NewXID VARCHAR(12),
		NoFollow VARCHAR(1),
		RealCpMainId INT
	)

	---向临时表中填入75行推荐职位的
AddRecommend:
	SELECT @RowNumber = COUNT(1) FROM #t
	IF @RowNumber = 0
		SET @RowNumber = @RecommendNumber
	ELSE
		SET @RowNumber = @RecommendNumber - @RowNumber

	IF @RegionType = 1  --省
		SET @strRegion = '
			AND dcSubsiteID LIKE ''' + LTRIM(STR(@ProvinceID)) + '%'''
	ELSE
		SET @strRegion = '
			AND (dcRegionID like ''' + LTRIM(STR(@subSiteId)) + '%''
				OR dcSubsiteID = ' + LTRIM(STR(@SubsiteID)) + ')'
	----再该市注测的企业

	SET @Sql = '
		INSERT #t(dcSubsiteID, dcRegionID, cpMainID, Name, IsAgent, JobNumber, JobID, JobName,  LastJobIssueDate, LastJobId, cpLicenceDate, RefreshDate, MemberType, NoFollow, RealCpMainId)
		SELECT TOP ' + LTRIM(STR(@RowNumber)) + ' dcSubsiteID, dcRegionID, cpMainID, Name, IsAgent, JobNumber, JobID, JobName,  LastJobIssueDate, LastJobId, cpLicenceDate, RefreshDate, MemberType, NoFollow, RealCpMainId
		FROM SearchDB..cpMainHomepageSnapshot WITH(NOLOCK)
		WHERE JobNumber > 0  
		AND MemberType > 2
		AND cpMainID Not IN(SELECT cpMainID FROM #t)'
	SET @Sql = @Sql + @strRegion + '
		ORDER BY RefreshDate DESC'

	EXEC(@SQL)

	SELECT @RowNumber = COUNT(1) FROM #t
	IF((@RowNumber < @RecommendNumber) AND (@RegionType = 2))
	BEGIN
		SELECT @RegionType = 1
		GOTO AddRecommend
	END

	---向临时表中填入热门职位，按照普通会员的刷新时间计算
	SELECT @HotNumber = 80, @RegionType = 1
	IF @subSiteId > 100
		SET @RegionType = 2

AddHot:
	SELECT @RowNumber = COUNT(1) FROM #t
	SET @RowNumber = @HotNumber + @RecommendNumber - @RowNumber
	IF @RowNumber < 1
		GOTO AddFlag

	IF @ProvinceID IN (32, 30, 31, 35, 10, 11, 12, 40)
		SET @strMember = '
		AND MemberType = 2'
	ELSE
	BEGIN
		SET @strMember = '
		AND MemberType IN(1, 2)'
	END
	SET @Sql = '
		INSERT #t(dcSubsiteID, dcRegionID, cpMainID, Name, IsAgent, JobNumber, JobID, JobName,  LastJobIssueDate, LastJobId, cpLicenceDate, RefreshDate, MemberType, NoFollow, RealCpMainId)
		SELECT TOP ' + LTRIM(STR(@RowNumber)) + ' dcSubsiteID, dcRegionID, cpMainID, Name, IsAgent, JobNumber, JobID, JobName,  LastJobIssueDate, LastJobId, cpLicenceDate, RefreshDate, MemberType, NoFollow, RealCpMainId
		FROM SearchDB..cpMainHomepageSnapshot WITH(NOLOCK)
		WHERE JobNumber > 0  
		AND cpMainID Not IN(SELECT cpMainID FROM #t)'
	SET @Sql = @Sql + @strRegion + @strMember + '
		ORDER BY RefreshDate DESC'
	EXEC(@SQL)
	SELECT @RowNumber = COUNT(1) FROM #t
	IF((@RowNumber < @RecommendNumber + @HotNumber) AND (@RegionType = 2))
	BEGIN
		SELECT @RegionType = 1
		GOTO AddHot
	END
AddFlag:
	DELETE FROM #t WHERE ID > @RecommendNumber + @HotNumber
	SELECT @RowNumber = 1 + COUNT(1) / 6 FROM #t WHERE MemberType > 2
	SELECT @SQL = 'UPDATE #t SET NewXId = LastJobID WHERE ID IN(SELECT TOP ' + LTRIM(STR(@RowNumber)) +' ID FROM #t WHERE MemberType > 2 ORDER BY LastJobIssueDate DESC)'
	EXEC(@SQL)

	SELECT @RowNumber = 1 + COUNT(1) / 8 FROM #t WHERE MemberType < 3
	SELECT @SQL = 'UPDATE #t SET NewXId = 1 WHERE ID IN(SELECT TOP ' + LTRIM(STR(@RowNumber)) +' ID FROM #t WHERE MemberType < 3 ORDER BY cpLicenceDate DESC)'
	EXEC(@SQL)

	UPDATE #t SET Name = LEFT(Name, 16) WHERE ID > @RecommendNumber AND NewXId = 1 AND LEN(Name) > 16
	UPDATE #t SET cpMainID = NoFollow + cpMainID

	SELECT ID, dcSubsiteID, dcRegionID, cpMainID, Name, IsAgent, JobNumber, JobID, JobName,
		LastJobIssueDate, LastJobId, cpLicenceDate, RefreshDate, MemberType, NewXID
	FROM #t WITH(NOLOCK)
	ORDER BY ID

	DROP TABLE #t
	SET NOCOUNT OFF
END

GO
/****** Object:  StoredProcedure [dbo].[procCompanyHomepageSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/***
*Peter 2014-02-20修改 添加修正热门职位的地区判断
*
*/
CREATE PROCEDURE [dbo].[procCompanyHomepageSelect]
(
	@SubSiteId INT
)
AS
SET NOCOUNT ON
--INSERT ProcLog SELECT 'procCompanyHomepageSelect', @SubSiteId, GETDATE()
IF @SubSiteId > 9999
BEGIN
	EXEC ProcCountyJobSelect @SubSiteId
	RETURN
END
BEGIN
	DECLARE @ProvinceID AS INT,
		@RegionType AS INT,			----1:省站；2：二级站
		@RecommendNumber AS INT,		----推荐职位行数
		@HotNumber AS INT,		----热门职位行数
		@RowNumber AS INT,
		@Sql AS VARCHAR(MAX),
		@strRegion AS VARCHAR(100),
		@strMember AS VARCHAR(100)

	SELECT @RecommendNumber = 75, @RegionType = 1, @ProvinceID = @subSiteId
	IF @subSiteId > 100
	BEGIN
		SET @RegionType = 2
		SET @ProvinceID = LEFT(@subSiteId, 2)
	END
	
	---将推荐职位的和热门的企业都放在临时表中
	CREATE TABLE #t(
		ID int IDENTITY(1,1) NOT NULL,
		dcSubsiteID smallint NULL,
		dcRegionID varchar(6) COLLATE Chinese_PRC_CI_AS NULL,
		cpMainID VARCHAR(11) NULL,
		Name varchar(100) COLLATE Chinese_PRC_CI_AS NULL,
		IsAgent bit NULL,
		JobNumber int NULL,
		JobID varchar(max) COLLATE Chinese_PRC_CI_AS NULL,
		JobName nvarchar(max) COLLATE Chinese_PRC_CI_AS NULL,
		LastJobIssueDate smalldatetime NULL,
		LastJobId VARCHAR(12) NULL,
		cpLicenceDate smalldatetime NULL,
		RefreshDate smalldatetime NULL,
		MemberType tinyint NULL,
		NewXID VARCHAR(12),
		NoFollow VARCHAR(1),
		RealCpMainId INT
	)

	---向临时表中填入75行推荐职位的
AddRecommend:
	SELECT @RowNumber = COUNT(1) FROM #t
	IF @RowNumber = 0
		SET @RowNumber = @RecommendNumber
	ELSE
		SET @RowNumber = @RecommendNumber - @RowNumber

	IF @RegionType = 1  --省
		SET @strRegion = '
			AND dcSubsiteID LIKE ''' + LTRIM(STR(@ProvinceID)) + '%'''
	ELSE
		SET @strRegion = '
			AND (dcRegionID like ''' + LTRIM(STR(@subSiteId)) + '%''
				OR dcSubsiteID = ' + LTRIM(STR(@SubsiteID)) + ')'
	----再该市注测的企业

	SET @Sql = '
		INSERT #t(dcSubsiteID, dcRegionID, cpMainID, Name, IsAgent, JobNumber, JobID, JobName,  LastJobIssueDate, LastJobId, cpLicenceDate, RefreshDate, MemberType, NoFollow, RealCpMainId)
		SELECT TOP ' + LTRIM(STR(@RowNumber)) + ' dcSubsiteID, dcRegionID, cpMainID, Name, IsAgent, JobNumber, JobID, JobName,  LastJobIssueDate, LastJobId, cpLicenceDate, RefreshDate, MemberType, NoFollow, RealCpMainId
		FROM SearchDB..cpMainHomepageSnapshot WITH(NOLOCK)
		WHERE JobNumber > 0  
		AND MemberType > 2
		AND cpMainID Not IN(SELECT cpMainID FROM #t)'
	SET @Sql = @Sql + @strRegion + '
		ORDER BY RefreshDate DESC'
	--print @sql
	EXEC(@SQL)

	SELECT @RowNumber = COUNT(1) FROM #t
	IF((@RowNumber < @RecommendNumber) AND (@RegionType = 2))
	BEGIN
		SELECT @RegionType = 1
		GOTO AddRecommend
	END

	---向临时表中填入热门职位，按照普通会员的刷新时间计算
	SELECT @HotNumber = 80, @RegionType = 1
	IF @subSiteId > 100
		SET @RegionType = 2

AddHot:
	SELECT @RowNumber = COUNT(1) FROM #t
	SET @RowNumber = @HotNumber + @RecommendNumber - @RowNumber
	IF @RowNumber < 1
		GOTO AddFlag

	IF @ProvinceID IN (32, 30, 31, 35, 10, 11, 12, 40)
		SET @strMember = '
		AND MemberType = 2'
	ELSE
	BEGIN
		SET @strMember = '
		AND MemberType IN(1, 2)'
	END
	IF @RegionType = 1  --省
		SET @strRegion = '
			AND dcSubsiteID LIKE ''' + LTRIM(STR(@ProvinceID)) + '%'''
	ELSE
		SET @strRegion = '
			AND (dcRegionID like ''' + LTRIM(STR(@subSiteId)) + '%''
				OR dcSubsiteID = ' + LTRIM(STR(@SubsiteID)) + ')'
	SET @Sql = '
		INSERT #t(dcSubsiteID, dcRegionID, cpMainID, Name, IsAgent, JobNumber, JobID, JobName,  LastJobIssueDate, LastJobId, cpLicenceDate, RefreshDate, MemberType, NoFollow, RealCpMainId)
		SELECT TOP ' + LTRIM(STR(@RowNumber)) + ' dcSubsiteID, dcRegionID, cpMainID, Name, IsAgent, JobNumber, JobID, JobName,  LastJobIssueDate, LastJobId, cpLicenceDate, RefreshDate, MemberType, NoFollow, RealCpMainId
		FROM SearchDB..cpMainHomepageSnapshot WITH(NOLOCK)
		WHERE JobNumber > 0  
		AND cpMainID Not IN(SELECT cpMainID FROM #t)'
	SET @Sql = @Sql + @strRegion + @strMember + '
		ORDER BY RefreshDate DESC'

	EXEC(@SQL)
	SELECT @RowNumber = COUNT(1) FROM #t
	IF((@RowNumber < @RecommendNumber + @HotNumber) AND (@RegionType = 2))
	BEGIN
		SELECT @RegionType = 1
		GOTO AddHot
	END
AddFlag:
	DELETE FROM #t WHERE ID > @RecommendNumber + @HotNumber
	SELECT @RowNumber = 1 + COUNT(1) / 6 FROM #t WHERE MemberType > 2
	SELECT @SQL = 'UPDATE #t SET NewXId = LastJobID WHERE ID IN(SELECT TOP ' + LTRIM(STR(@RowNumber)) +' ID FROM #t WHERE MemberType > 2 ORDER BY LastJobIssueDate DESC)'
	EXEC(@SQL)

	SELECT @RowNumber = 1 + COUNT(1) / 8 FROM #t WHERE MemberType < 3
	SELECT @SQL = 'UPDATE #t SET NewXId = 1 WHERE ID IN(SELECT TOP ' + LTRIM(STR(@RowNumber)) +' ID FROM #t WHERE MemberType < 3 ORDER BY cpLicenceDate DESC)'
	EXEC(@SQL)

	UPDATE #t SET Name = LEFT(Name, 16) WHERE ID > @RecommendNumber AND NewXId = 1 AND LEN(Name) > 16
	UPDATE #t SET cpMainID = NoFollow + cpMainID

	SELECT ID, dcSubsiteID, dcRegionID, cpMainID, Name, IsAgent, JobNumber, JobID, JobName,
		LastJobIssueDate, LastJobId, cpLicenceDate, RefreshDate, MemberType, NewXID
	FROM #t WITH(NOLOCK)
	ORDER BY ID

	DROP TABLE #t
	SET NOCOUNT OFF
END



GO
/****** Object:  StoredProcedure [dbo].[ProcCompanyListByCpIDsSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.3
--创建人：John
--说明：返回cpid在参数内的企业信息
--#####################################################
CREATE PROCEDURE [dbo].[ProcCompanyListByCpIDsSelect]
(
	@CpIDs VARCHAR(1000)
)
AS
BEGIN
	DECLARE @SQL VARCHAR(2000)
	SET @SQL = 'SELECT TOP 500 a.id AS cpid, a.Name AS companyName, b.id AS caid 
	FROM [MainDb]..[cpMain] a, [MainDb]..[caMain] b 
	WHERE a.id = b.cpMainID 
		AND b.IsPause = 0 
		AND b.IsDelete = 0 
		AND b.AccountType = 1 
		AND a.id IN ( ' + @CpIDs + ' )'
	EXEC(@SQL)
END


GO
/****** Object:  StoredProcedure [dbo].[procCoorperation8Select]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.10
--创建人：NICK
--说明：获取合作伙伴
--#####################################################
CREATE PROCEDURE [dbo].[procCoorperation8Select]
AS
BEGIN
	SELECT top 8 * FROM Maindb..Coorperation WITH(NOLOCK)
END


GO
/****** Object:  StoredProcedure [dbo].[procCounterByVersionIDUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[procCounterByVersionIDUpdate] 
(
	@VersionId SMALLINT,
	@VNumber INT,
	@SVNumber INT
)
AS
BEGIN
	SET NOCOUNT ON
	UPDATE Counter SET ViewNumber = ViewNumber + @VNumber,
		SpiderViewNumber = SpiderViewNumber + @SVNumber
	WHERE CountDate = CONVERT(VARCHAR(8), GETDATE(), 112)
	AND VersionId = @VersionId
END

GO
/****** Object:  StoredProcedure [dbo].[procCounterSpiderUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
CREATE PROCEDURE [dbo].[procCounterSpiderUpdate]
(
	@VersionId SMALLINT
)
AS
SET NOCOUNT ON
BEGIN
--	UPDATE Counter SET SpiderViewNumber = SpiderViewNumber + 1  
--	WHERE CountDate = CONVERT(VARCHAR(8), GETDATE(), 112)
--	AND VersionId = @VersionId
	INSERT INTO CounterSpider SELECT @VersionId, GETDATE()
END















GO
/****** Object:  StoredProcedure [dbo].[procCounterUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
CREATE PROCEDURE [dbo].[procCounterUpdate] 
(
	@VersionId SMALLINT
)
AS
BEGIN
	SET NOCOUNT ON
	UPDATE Counter SET ViewNumber = ViewNumber + 1  
	WHERE CountDate = CONVERT(VARCHAR(8), GETDATE(), 112)
	AND VersionId = @VersionId
	SET NOCOUNT OFF
END

GO
/****** Object:  StoredProcedure [dbo].[procCountyHotJobSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/***
*Peter 2014-02-20修改 添加修正热门职位的地区判断
*
*/
CREATE PROCEDURE [dbo].[procCountyHotJobSelect]
(
	@RegionId INT
)
AS
BEGIN
	SET NOCOUNT ON
	DECLARE @HotNumber AS INT,		----热门职位行数
		@ProvinceID AS INT,
		@RegionType AS INT,
		@RowNumber AS INT,
		@Sql AS VARCHAR(MAX),
		@strMember AS VARCHAR(100),
		@strRegion AS VARCHAR(100)
	
	---将推荐职位的和热门的企业都放在临时表中
	CREATE TABLE #t(
		ID int IDENTITY(1,1) NOT NULL,
		dcSubsiteID smallint NULL,
		dcRegionID varchar(6) COLLATE Chinese_PRC_CI_AS NULL,
		cpMainID VARCHAR(11) NULL,
		Name varchar(100) COLLATE Chinese_PRC_CI_AS NULL,
		IsAgent bit NULL,
		JobNumber int NULL,
		JobID varchar(max) COLLATE Chinese_PRC_CI_AS NULL,
		JobName nvarchar(max) COLLATE Chinese_PRC_CI_AS NULL,
		LastJobIssueDate smalldatetime NULL,
		LastJobId VARCHAR(12) NULL,
		cpLicenceDate smalldatetime NULL,
		RefreshDate smalldatetime NULL,
		MemberType tinyint NULL,
		NewXID VARCHAR(12),
		NoFollow VARCHAR(1),
		RealCpMainId INT
	)
	---向临时表中填入热门职位，按照普通会员的刷新时间计算
	SELECT @HotNumber = 60
	SET @ProvinceID = LEFT(@RegionId, 2)
	SET @RegionType=3--县级市
AddHot:
	SELECT @RowNumber = COUNT(1) FROM #t
	IF @RowNumber < 1
		GOTO AddFlag

	IF @ProvinceID IN (32, 30, 31, 35, 10, 11, 12, 40)
		SET @strMember = '
		AND MemberType = 2'
	ELSE
	BEGIN
		SET @strMember = '
		AND MemberType IN(1, 2)'
	END
	IF @RegionType = 1  --省
		SET @strRegion = '
			AND dcSubsiteID LIKE ''' + LTRIM(STR(@ProvinceID)) + '%'''
	IF  @RegionType = 2  --市
		SET @strRegion = '
			AND (dcRegionID like ''' + LTRIM(STR(@ProvinceID)) + '%''
				OR dcSubsiteID = ' + LTRIM(STR(@ProvinceID)) + ')'
	IF  @RegionType = 3  --县级
		SET @strRegion = '
			AND (dcRegionID = ''' + LTRIM(STR(@RegionId)) + '%''
				OR dcSubsiteID = ' + LTRIM(STR(@RegionId)) + ')'
	SET @Sql = '
		INSERT #t(dcSubsiteID, dcRegionID, cpMainID, Name, IsAgent, JobNumber, JobID, JobName,  LastJobIssueDate, LastJobId, cpLicenceDate, RefreshDate, MemberType, NoFollow, RealCpMainId)
		SELECT TOP ' + LTRIM(STR(@RowNumber)) + ' dcSubsiteID, dcRegionID, cpMainID, Name, IsAgent, JobNumber, JobID, JobName,  LastJobIssueDate, LastJobId, cpLicenceDate, RefreshDate, MemberType, NoFollow, RealCpMainId
		FROM SearchDB..cpMainHomepageSnapshot WITH(NOLOCK)
		WHERE JobNumber > 0  
		AND cpMainID Not IN(SELECT cpMainID FROM #t)'
	SET @Sql = @Sql + @strRegion + @strMember + '
		ORDER BY RefreshDate DESC'
print @sql
	EXEC(@SQL)
	SELECT @RowNumber = COUNT(1) FROM #t
	IF((@RowNumber <@HotNumber))
	BEGIN
		IF @RegionType = 3 
			SELECT @RegionType = 2
		ELSE IF @RegionType = 2
			SELECT @RegionType = 1
		GOTO AddHot
	END
AddFlag:
	DELETE FROM #t WHERE ID > @HotNumber
	SELECT @RowNumber = 1 + COUNT(1) / 6 FROM #t WHERE MemberType > 2
	SELECT @SQL = 'UPDATE #t SET NewXId = LastJobID WHERE ID IN(SELECT TOP ' + LTRIM(STR(@RowNumber)) +' ID FROM #t WHERE MemberType > 2 ORDER BY LastJobIssueDate DESC)'
	EXEC(@SQL)

	SELECT @RowNumber = 1 + COUNT(1) / 8 FROM #t WHERE MemberType < 3
	SELECT @SQL = 'UPDATE #t SET NewXId = 1 WHERE ID IN(SELECT TOP ' + LTRIM(STR(@RowNumber)) +' ID FROM #t WHERE MemberType < 3 ORDER BY cpLicenceDate DESC)'
	EXEC(@SQL)

	
	UPDATE #t SET cpMainID = NoFollow + cpMainID

	SELECT ID, dcSubsiteID, dcRegionID, cpMainID, Name, IsAgent, JobNumber, JobID, JobName,
		LastJobIssueDate, LastJobId, cpLicenceDate, RefreshDate, MemberType, NewXID
	FROM #t WITH(NOLOCK)
	ORDER BY ID

	DROP TABLE #t
	SET NOCOUNT OFF
END


GO
/****** Object:  StoredProcedure [dbo].[procCountyJobInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[procCountyJobInsert]
(
	@RegionId VARCHAR(6)
)
AS
SET NOCOUNT ON
INSERT INTO ProcLog SELECT 'procCountyJobInsert', @RegionId, GETDATE()
IF EXISTS(SELECT 'x' FROM SearchDb..CountyJob WHERE JobPlaceId = @RegionId AND crDate > DATEADD(MINUTE, -120, GETDATE()))
	RETURN
BEGIN TRY
	CREATE TABLE #t(
		RowID int IDENTITY(1, 1) NOT NULL, 
		PageId int NOT NULL DEFAULT ((0)), 
		ID int NOT NULL, 
		cpMainID int NOT NULL, 
		caMainID int NOT NULL, 
		JobName nvarchar(50) NOT NULL, 
		dcJobTypeID smallint NOT NULL, 
		dcJobTypeIDMinor smallint NULL, 
		NeedNumber tinyint NULL, 
		dcSalaryID tinyint NOT NULL, 
		EmployType tinyint NOT NULL, 
		dcRegionID varchar(6) NOT NULL, 
		Responsibility nvarchar(max) NULL, 
		Demand nvarchar(max) NULL, 
		dcEducationID tinyint NOT NULL, 
		MinExperience tinyint NOT NULL, 
		MinAge tinyint NULL, 
		MaxAge tinyint NULL, 
		IssueDate smalldatetime NULL, 
		IssueEND smalldatetime NULL, 
		IsDelete bit NOT NULL, 
		AddDate smalldatetime NOT NULL, 
		RefreshDate smalldatetime NULL, 
		Welfare1 bit NULL, 
		Welfare2 bit NULL, 
		Welfare3 bit NULL, 
		Welfare4 bit NULL, 
		Welfare5 bit NULL, 
		Welfare6 bit NULL, 
		Welfare7 bit NULL, 
		Welfare8 bit NULL, 
		Welfare9 bit NULL, 
		Welfare10 bit NULL, 
		Welfare11 bit NULL, 
		Welfare12 bit NULL, 
		Welfare13 bit NULL, 
		Welfare14 bit NULL, 
		Welfare15 bit NULL, 
		Welfare16 bit NULL, 
		Welfare17 bit NULL, 
		Welfare18 bit NULL, 
		EnJobID varchar(12) NULL, 
		EnCpMainID varchar(10) NULL, 
		LastModifyDate smalldatetime NOT NULL, 
		cpName nvarchar(100) NULL, 
		dcCompanySizeID tinyint NULL, 
		HasLicence bit NOT NULL, 
		UnLimitedDate smalldatetime NOT NULL, 
		BalanceDate smalldatetime NOT NULL, 
		Balance smallint NOT NULL, 
		MemberType tinyint NOT NULL, 
		cpIndustry nvarchar(max) NULL, 
		IsRefreshed bit NOT NULL
	)
 
	----建立临时表
	CREATE TABLE #Job(
		ID int NOT NULL, 
		cpMainID int NOT NULL, 
		caMainID int NOT NULL, 
		JobName nvarchar(50) NOT NULL, 
		dcJobTypeID smallint NOT NULL, 
		dcJobTypeIDMinor smallint NULL, 
		NeedNumber tinyint NULL, 
		dcSalaryID tinyint NOT NULL, 
		EmployType tinyint NOT NULL, 
		dcRegionID varchar(6) NOT NULL, 
		Responsibility nvarchar(max) NULL, 
		Demand nvarchar(max) NULL, 
		dcEducationID tinyint NOT NULL, 
		MinExperience tinyint NOT NULL, 
		MinAge tinyint NULL, 
		MaxAge tinyint NULL, 
		IssueDate smalldatetime NULL, 
		IssueEND smalldatetime NULL, 
		IsDelete bit NOT NULL, 
		AddDate smalldatetime NOT NULL, 
		RefreshDate smalldatetime NULL, 
		Welfare1 bit NULL, 
		Welfare2 bit NULL, 
		Welfare3 bit NULL, 
		Welfare4 bit NULL, 
		Welfare5 bit NULL, 
		Welfare6 bit NULL, 
		Welfare7 bit NULL, 
		Welfare8 bit NULL, 
		Welfare9 bit NULL, 
		Welfare10 bit NULL, 
		Welfare11 bit NULL, 
		Welfare12 bit NULL, 
		Welfare13 bit NULL, 
		Welfare14 bit NULL, 
		Welfare15 bit NULL, 
		Welfare16 bit NULL, 
		Welfare17 bit NULL, 
		Welfare18 bit NULL, 
		EnJobID varchar(12) NULL, 
		EnCpMainID varchar(10) NULL, 
		LastModifyDate smalldatetime NOT NULL, 
		cpName nvarchar(100) NULL, 
		dcCompanySizeID tinyint NULL, 
		HasLicence bit NOT NULL, 
		UnLimitedDate smalldatetime NOT NULL, 
		BalanceDate smalldatetime NOT NULL, 
		Balance smallint NOT NULL, 
		MemberType tinyint NOT NULL, 
		cpIndustry nvarchar(max) NULL, 
		IsRefreshed bit NOT NULL
	)

	INSERT INTO #Job
	SELECT TOP 2000 a.ID, a.cpMainID, a.caMainID, a.Name as JobName, a.dcJobTypeID, 
		a.dcJobTypeIDMinor, a.NeedNumber, a.dcSalaryID, a.EmployType, 
		a.dcRegionID, a.Responsibility, a.Demand, a.dcEducationID, 
		a.MinExperience, a.MinAge, a.MaxAge, a.IssueDate, a.IssueEND, 
		a.IsDelete, a.AddDate, a.RefreshDate, a.Welfare1, a.Welfare2, a.Welfare3, 
		a.Welfare4, a.Welfare5, a.Welfare6, a.Welfare7, a.Welfare8, 
		a.Welfare9, a.Welfare10, a.Welfare11, a.Welfare12, a.Welfare13, 
		a.Welfare14, a.Welfare15, a.Welfare16, a.Welfare17, a.Welfare18, a.SecondId EnJobID, b.SecondId EnCpMainID, 
		a.LastModifyDate, b.Name as cpName, b.dcCompanySizeID, 
		b.HasLicence, b.UnLimitedDate, b.BalanceDate, b.Balance, 
		b.MemberType, 
		STUFF(
			(SELECT ', ' + LTRIM(x.dcIndustryid) + ', c'+LTRIM(isnull(y.Category, 0)) 
			FROM cpIndustry x, dcIndustry y
			WHERE x.dcIndustryid = y.id 
			AND x.cpMainid = b.id 
			FOR XML PATH('')
			), 
			1, 1, '') cpIndustry, 
		b.IsRefreshed
	FROM JobPublish a WITH(NOLOCK), cpMainPublish b WITH(NOLOCK)
	WHERE a.cpMainID = b.ID
	AND a.dcRegionId LIKE LEFT(@RegionId, 2) + '%'
	AND a.Valid = 1
	AND b.Valid = 1
	ORDER BY a.RefreshDate DESC

	DELETE #Job WHERE dcRegionId = @RegionId

	INSERT INTO #Job
	SELECT TOP 2000 a.ID, a.cpMainID, a.caMainID, a.Name as JobName, a.dcJobTypeID, 
		a.dcJobTypeIDMinor, a.NeedNumber, a.dcSalaryID, a.EmployType, 
		a.dcRegionID, a.Responsibility, a.Demand, a.dcEducationID, 
		a.MinExperience, a.MinAge, a.MaxAge, a.IssueDate, a.IssueEND, 
		a.IsDelete, a.AddDate, a.RefreshDate, a.Welfare1, a.Welfare2, a.Welfare3, 
		a.Welfare4, a.Welfare5, a.Welfare6, a.Welfare7, a.Welfare8, 
		a.Welfare9, a.Welfare10, a.Welfare11, a.Welfare12, a.Welfare13, 
		a.Welfare14, a.Welfare15, a.Welfare16, a.Welfare17, a.Welfare18, a.SecondId EnJobID, b.SecondId EnCpMainID, 
		a.LastModifyDate, b.Name as cpName, b.dcCompanySizeID, 
		b.HasLicence, b.UnLimitedDate, b.BalanceDate, b.Balance, 
		b.MemberType, 
		STUFF(
			(SELECT ', ' + LTRIM(x.dcIndustryid) + ', c'+LTRIM(isnull(y.Category, 0)) 
			FROM cpIndustry x, dcIndustry y
			WHERE x.dcIndustryid = y.id 
			AND x.cpMainid = b.id 
			FOR XML PATH('')
			), 
			1, 1, '') cpIndustry, 
		b.IsRefreshed
	FROM JobPublish a WITH(NOLOCK), cpMainPublish b WITH(NOLOCK)
	WHERE a.cpMainID = b.ID
	AND a.dcRegionId = @RegionId
	AND a.Valid = 1
	AND b.Valid = 1
	ORDER BY a.RefreshDate DESC

	CREATE NONCLUSTERED INDEX [IX_#Job_dcRegionID] ON [dbo].[#Job](dcRegionId ASC)
	CREATE NONCLUSTERED INDEX [IX_#Job_RefreshDate] ON [dbo].[#Job](RefreshDate DESC)

	--DELETE SearchDb..CountyJobNumber WHERE ProvinceId = @ProvinceId
	--INSERT SearchDb..CountyJobNumber SELECT @ProvinceId, COUNT(*) FROM #Job

	INSERT #t
	SELECT TOP 2000 0, ID, cpMainID, caMainID, JobName, dcJobTypeID, 
		dcJobTypeIDMinor, NeedNumber, dcSalaryID, EmployType, 
		dcRegionID, Responsibility, Demand, dcEducationID, 
		MinExperience, MinAge, MaxAge, IssueDate, IssueEND, 
		IsDelete, AddDate, RefreshDate, Welfare1, Welfare2, Welfare3, 
		Welfare4, Welfare5, Welfare6, Welfare7, Welfare8, 
		Welfare9, Welfare10, Welfare11, Welfare12, Welfare13, 
		Welfare14, Welfare15, Welfare16, Welfare17, Welfare18, EnJobID, EnCpMainID, 
		LastModifyDate, cpName, dcCompanySizeID, 
		HasLicence, UnLimitedDate, BalanceDate, Balance, 
		MemberType, cpIndustry, IsRefreshed
	FROM #Job WITH(NOLOCK)
	ORDER BY CASE dcRegionID WHEN @RegionId THEN 1 ELSE 2 END, 
		RefreshDate DESC

	BEGIN TRY
		UPDATE #t SET PageId = (RowId + 19) / 20
		DELETE SearchDb..CountyJob WHERE JobPlaceId = @RegionID
		INSERT INTO SearchDb..CountyJob SELECT @RegionID, *, GETDATE() FROM #t
		TRUNCATE TABLE #t
	END TRY
	BEGIN CATCH
	END CATCH
END TRY
BEGIN CATCH
	---检查是否已经建立临时表，已经建立则删除
	PRINT 'error'
	PRINT error_Message()
	PRINT error_number()
	PRINT error_line()
END CATCH







GO
/****** Object:  StoredProcedure [dbo].[ProcCountyJobSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ProcCountyJobSelect]
(
	@SubSiteId INT
)
AS
SET NOCOUNT ON
--this proc is valid
BEGIN
	DECLARE @Refresh INT
	SET @Refresh = 0
	IF @SubSiteId LIKE '32%'
	BEGIN
		IF ISNULL((SELECT TOP 1 DATEDIFF(MINUTE, AddDate, GETDATE()) FROM ShortDb..CountyJob WHERE CountyId = @SubSiteId), 999) > 120
			SET @Refresh = 1
	END
	ELSE
	BEGIN
		IF ISNULL((SELECT TOP 1 DATEDIFF(MINUTE, AddDate, GETDATE()) FROM ShortDb..CountyJob WHERE CountyId = @SubSiteId), 999) > 480
			SET @Refresh = 1
	END

	IF @Refresh = 1	
	BEGIN
		DECLARE @RowNumber AS INT, @SiteId INT
		SELECT @SiteId = @SubSiteId, @RowNumber = 0
		---将推荐职位的和热门的企业都放在临时表中
		DECLARE @t AS TABLE(
			ID int IDENTITY(1, 1) NOT NULL,
			dcSubsiteID smallint NOT NULL,
			dcRegionID varchar(6) NULL,
			cpMainID varchar(11) NULL,
			Name varchar(100) NULL,
			IsAgent bit NULL,
			JobNumber int NULL,
			JobID varchar(max) NULL,
			JobName nvarchar(max) NULL,
			LastJobIssueDate smalldatetime NULL,
			LastJobId varchar(12) NULL,
			cpLicenceDate smalldatetime NULL,
			RefreshDate smalldatetime NULL,
			MemberType tinyint NULL,
			NewXID varchar(12) NULL,
			NoFollow varchar(1) NULL,
			RealCpMainId int NULL,
			AddDate smalldatetime NOT NULL DEFAULT (getdate())
		)

	---向临时表中填入75行推荐职位的
	AddRecommend:
		INSERT @t(cpMainId, dcSubsiteID, dcRegionID, Name, IsAgent, JobNumber, RefreshDate, MemberType, RealCpMainId)
		SELECT TOP (75 - @RowNumber) SecondId, dcSubsiteID, dcRegionID, Name, IsAgent, JobNumber, RefreshDate, MemberType, Id
		FROM MainDb..cpMain WITH(NOLOCK)
		WHERE JobNumber > 0  
		AND MemberType > 1		
		AND (dcRegionID = @SiteId
			OR dcSubsiteID = @SiteId)
		ORDER BY MemberType DESC, RefreshDate DESC
		
		SELECT @RowNumber = COUNT(1) FROM @t
		IF(@RowNumber < 75)
		BEGIN
			INSERT @t(cpMainId, dcSubsiteID, dcRegionID, Name, IsAgent, JobNumber, RefreshDate, MemberType, RealCpMainId)
			SELECT TOP (75 - @RowNumber) SecondId, dcSubsiteID, dcRegionID, Name, IsAgent, JobNumber, RefreshDate, MemberType, Id
			FROM MainDb..cpMain WITH(NOLOCK)
			WHERE JobNumber > 0  
			AND MemberType = 1		
			AND (dcRegionID = @SiteId
				OR dcSubsiteID = @SiteId)
			ORDER BY RefreshDate DESC
		END

		SELECT @RowNumber = COUNT(1) FROM @t
		IF(@RowNumber < 75 AND @SiteId > 99)
		BEGIN
			SET @SiteId = LEFT(@SiteId, LEN(@SiteId) - 2)
			GOTO AddRecommend
		END

		DELETE @t WHERE Id > 75
		UPDATE @t SET JobId = dbo.getJobSecondIds(RealCpMainid), JobName = dbo.getJobNames(RealCpMainid)
		UPDATE a SET a.cplicenceDate = b.checkDate
		FROM @t a, cpLicence b
		WHERE a.RealCpMainid = b.cpMainid
		AND a.MemberType < 3
		SELECT @RowNumber = COUNT(*) FROM @t WHERE MemberType = 3
		UPDATE a SET LastJobId = (SELECT TOP 1 ID FROM Job WITH(NOLOCK) WHERE Job.cpMainid = a.RealCpMainid AND Valid = 1 ORDER BY IssueDate DESC) FROM @t a
		UPDATE a SET LastJobIssueDate = (SELECT IssueDate FROM Job WHERE Job.id = a.LastJobid) FROM @t a WHERE MemberType > 2
		UPDATE @t SET NewXId = LastJobID WHERE Id IN(SELECT TOP (@RowNumber / 4) Id FROM @t WHERE MemberType = 3 ORDER BY LastJobIssueDate DESC)
		UPDATE @t SET NewXId = LastJobID WHERE Id IN(SELECT TOP (@RowNumber / 6) Id FROM @t WHERE MemberType < 3 ORDER BY cplicenceDate DESC)

		DELETE FROM ShortDb..CountyJob WHERE CountyId = @SubSiteId
		INSERT INTO ShortDb..CountyJob(ID, CountyId, dcSubsiteID, dcRegionID, cpMainID, Name, IsAgent, JobNumber, JobID, JobName,
			LastJobIssueDate, LastJobId, cpLicenceDate, RefreshDate, MemberType, NewXID)
		SELECT ID, @SubsiteID, dcSubsiteID, dcRegionID, cpMainID, Name, IsAgent, JobNumber, JobID, JobName,
			LastJobIssueDate, LastJobId, cpLicenceDate, RefreshDate, MemberType, NewXID
		FROM @t
		ORDER BY ID
	END
	SELECT * FROM ShortDb..CountyJob WHERE CountyId = @SubSiteId ORDER BY ID
END

GO
/****** Object:  StoredProcedure [dbo].[procCpImageSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--------------------------------------------------
--创建：Nick
--创建日期：2016-2-15
--获取环境照片企业列表
--------------------------------------------------
CREATE PROCEDURE [dbo].[procCpImageSelect] 
(
	@ProvinceID INT,
	@PageNo INT
)
AS
BEGIN 
	CREATE TABLE #indextable(
		[NUM] int identity(1,1),
		ID INT NULL,
		chDate DATETIME
	)
	INSERT INTO #indextable(ID,chDate)
	SELECT TOP 500 CpmainID,MAX(a.CheckDate) AS ChDate
	FROM CpImage a WITH(NOLOCK),CpMain b WITH(NOLOCK)
	WHERE a.Imgtype = 3 
	AND a.HasPassed=1 
	AND a.CheckDate IS NOT NULL 
	AND A.CpMainID = b.ID
	AND dcProvinceID = @ProvinceID
	AND a.AddDate > '2016-2-17'
	GROUP BY a.CpmainID
	ORDER BY ChDate DESC
	
	--分页
	DECLARE @PageSize INT
	SET @PageSize = 10
    DECLARE @PageLowerBound  INT --定义此页的底码
    DECLARE @PageUpperBound  INT --定义此页的顶码
    SET @PageLowerBound = (@PageNo -1) * @pagesize
    SET @PageUpperBound = @PageLowerBound + @pagesize

	DECLARE @Campus AS TABLE(
		[CpMainID] INT,
		SecondID VARCHAR(100),
		ImgFile VARCHAR(200),
		Name NVARCHAR(100),
		Content VARCHAR(200)
	)
	
	INSERT INTO @Campus (CpMainID,SecondID,Name)
	SELECT b.ID,b.SecondID,b.Name
	FROM (SELECT * FROM #indextable WHERE Num > @PageLowerBound AND Num <= @PageUpperBound)a,
	CpMain b WITH(NOLOCK)
	WHERE a.ID = b.ID
	
	UPDATE a
	SET ImgFile = (
		SELECT TOP 1 ImgFile 
		FROM CpImage WITH(NOLOCK)
		WHERE CpMainID = a.CpMainID
		AND Imgtype = 3
		AND HasPassed=1
		AND CheckDate IS NOT NULL
		ORDER BY CheckDate DESC
	) FROM @Campus a

	UPDATE a
	SET Content = (
		SELECT TOP 1 Description 
		FROM CpImage WITH(NOLOCK)
		WHERE CpMainID = a.CpMainID
		AND Imgtype = 3
		AND HasPassed=1
		AND CheckDate IS NOT NULL
		ORDER BY CheckDate DESC
	) FROM @Campus a

	SELECT COUNT(*) FROM #indextable
	SELECT * FROM @Campus
END

GO
/****** Object:  StoredProcedure [dbo].[proccpIndustryByJobIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.31
--创建人：Nick
--说明：获取职位信息 用于计算与简历的匹配度
--#####################################################
CREATE PROCEDURE [dbo].[proccpIndustryByJobIDSelect]
(
	@JobID INT
)
AS
BEGIN TRY
	SELECT x.*,','+STUFF((
		SELECT ','+LTRIM(a.dcIndustryid)+',c'+LTRIM(b.CateGory) 
		FROM cpIndustry a,dcIndustry b 
		WHERE a.dcIndustryid = b.ID AND cpMainid = x.cpMainID FOR XML PATH('')),1,1,'')+',' cpIndustry  
	FROM Job  x WITH(NOLOCK)
	WHERE ID = @JobID
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[procCpMainByCpImageSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--福利分享专题根据公司上传环境图获取公司列表
--创建时间 2016-02-15
--创建人  Peter

CREATE PROCEDURE [dbo].[procCpMainByCpImageSelect]
(
	@SqlWhere AS VARCHAR(500),
	@PageNo AS INT
)
AS
BEGIN
	CREATE TABLE #T(
		cpMainID INT,
		CheckDate DATETIME
	)
	SET @SqlWhere = dbo.SafeSql(@SqlWhere)
	DECLARE @SQL AS VARCHAR(1000)
	
	SET @SQL='INSERT INTO #T SELECT cpmainid,MAX(CheckDate) CheckDate
		FROM cpImage WITH(NOLOCK)
		WHERE HasPassed = 1 
		AND ImgType = 3 
		AND (SELECT TOP 1 Valid FROM CpMain WITH(NOLOCK) WHERE id = cpImage.cpMainID) = 1
		AND EXISTS(SELECT id FROM Job WITH(NOLOCK) WHERE cpMainID = cpimage.cpMainid AND IsDelete = 0 AND IssueEnd > GETDATE() AND IssueDate < GETDATE()) ' + @SqlWhere + '
		GROUP BY cpmainid '	
	EXEC(@SQL)	

	SELECT b.PageIndex,a.id,a.Name,a.SecondID
	FROM cpMain a WITH(NOLOCK),(
		SELECT TOP (@PageNo*12) ROW_NUMBER() OVER (ORDER BY CheckDate DESC) PageIndex,cpMainID
		FROM #T) b
	WHERE b.cpMainID=a.id
	AND b.PageIndex > (@PageNo-1)*12
	ORDER BY b.PageIndex ASC

	SELECT COUNT(1) FROM #T

	DROP TABLE #T
END
GO
/****** Object:  StoredProcedure [dbo].[ProcCpMainByEndDateSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ProcCpMainByEndDateSelect]
AS
BEGIN
	CREATE TABLE #t(ID INT, CompanyName NVARCHAR(60), ConsultantID INT, Superior INT, Code INT)
	INSERT INTO #t
	SELECT ID, Name, ConsultantID, 0, DATEPART(HOUR, RegDate) * 100 + DATEPART(MINUTE, RegDate) FROM cpMain WITH(NOLOCK) 
	WHERE UnlimitedDate BETWEEN GETDATE() AND GETDATE() + 7

	INSERT INTO #t
	SELECT ID, Name, ConsultantID, 0, DATEPART(HOUR, RegDate) * 100 + DATEPART(MINUTE, RegDate) FROM cpMain WITH(NOLOCK) 
	WHERE BalanceDate BETWEEN GETDATE() AND GETDATE() + 7

	INSERT INTO #t
	SELECT ID, Name, ConsultantID, 0, DATEPART(HOUR, RegDate) * 100 + DATEPART(MINUTE, RegDate) FROM cpMain WITH(NOLOCK) 
	WHERE MemberType = 3 AND id IN
	(
		SELECT cpmainid FROM caOrder WITH(NOLOCK)
		WHERE ORderType = 8
		GROUP BY cpMainid
		HAVING MAX(EndDate) BETWEEN GETDATE() AND GETDATE() + 7
	)

	--DELETE FROM #t WHERE ConsultantID IN(SELECT ID FROM ManagerUser WHERE Status<> 3)

	UPDATE #t SET Superior = ConsultantId WHERE ConsultantId IN(SELECT ID FROM ManagerUser WHERE Status<3 AND RtxStatus IN(1, 2))

	UPDATE #t SET Superior = (SELECT Superior FROM ManagerUser WHERE ManagerUser.Id = ConsultantID) WHERE ISNULL(Superior, 0) = 0

	UPDATE #t SET Superior = 180 + (ID % 4) WHERE ISNULL(Superior, 0) = 0

	--SELECT * FROM #t

	INSERT INTO OaDb..RtxSend(Receiver, RtxTitle, RtxMessage, SendType, DelayTime, ShowType, SendTime, AddTime)
	SELECT Superior, '订单到期通知', CompanyName + '(' + LTRIM(STR(ID)) + ') http://sysback.51rc.com/newoa/company/cp/cpMainInfo?id=' + LTRIM(STR(ID)) + '&code=' + LTRIM(STR(Code)) + ' 将在7天内到期，请关注。', 1, 0, 0, NULL, GETDATE()
	FROM #t

	DROP TABLE #t
END

 










GO
/****** Object:  StoredProcedure [dbo].[procCpMainByFewSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[procCpMainByFewSelect]
(
	@ID INT
)
AS
BEGIN
	SELECT RegisterIp
	FROM cpMain a WITH(NOLOCK)
	WHERE a.ID =@ID
END

GO
/****** Object:  StoredProcedure [dbo].[procCpMainByIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.10
--创建人：NICK
--说明：根据ID获取cpmain
--#####################################################
CREATE PROCEDURE [dbo].[procCpMainByIDSelect]
(
	@ID INT
)
AS
BEGIN
	SELECT TOP 1  * FROM cpmain WHERE ID = @ID
END


GO
/****** Object:  StoredProcedure [dbo].[procCpMainByKeyWordSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.25
--创建人：Nick
--说明：点评 搜索公司
--#####################################################
CREATE PROCEDURE [dbo].[procCpMainByKeyWordSelect] 
(
	@Name VARCHAR(25),
	@ProvinceID INT
)
AS
BEGIN
	DECLARE @t AS TABLE(ID INT,	
		SecondId VARCHAR(12),
		Name NVARCHAR(50)
	)

	INSERT INTO @t
	SELECT TOP 48 a.ID, a.SecondId, a.Name
	FROM cpMainPublish a WITH(NOLOCK),
		CONTAINSTABLE(cpMainPublish, Name, @Name, 100) AS b
	WHERE a.Id = b.[Key]
	AND a.dcRegionID LIKE LTRIM(STR(@ProvinceID)) + '%'

	IF NOT EXISTS(SELECT 'x' FROM @t)
	BEGIN
		INSERT @t	
		SELECT TOP 48 ID,SecondId, Name
		FROM cpMainPublish WITH(NOLOCK INDEX(IX_cpMainPublish_Name))
		WHERE Name LIKE @Name + '%'
		AND LEFT(cpMainPublish.dcRegionID, 2) = @ProvinceID
		ORDER BY RefreshDate DESC	
	END

	SELECT * FROM @t
END


GO
/****** Object:  StoredProcedure [dbo].[procCpMainByReplyRateUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--计算企业回复率
--20151126 nick
--修改harry，修改此方法只计算未确认自动答复的答复率2017-5-25,答复率小于0.6的也显示
CREATE PROCEDURE [dbo].[procCpMainByReplyRateUpdate]
AS
SET NOCOUNT ON
BEGIN
	UPDATE ExjobApply SET ReplyDate = CompanyDeleteDate WHERE ReplyDate IS NULL AND Reply  = 4
	UPDATE ExjobApply SET ReplyDate = CompanyDeleteDate WHERE ReplyDate IS NULL AND Reply  = 4
	UPDATE ExjobApply SET ReplyDate = ViewDate WHERE ReplyDate IS NULL AND Reply = 1 AND ViewDate IS NOT NULL
	UPDATE ExjobApply SET ReplyDate = CompanyDeleteDate WHERE ReplyDate IS NULL AND Reply  = 1 AND CompanyDeleteDate IS NOT NULL
	UPDATE ExjobApply SET ReplyDate = AddDate + 1 WHERE ReplyDate IS NULL AND Reply > 0 

	SELECT DISTINCT a.cpMainId
    INTO #t
    FROM Job a, ExJobApply b, cpMain c
    WHERE a.id  =  b.JobId
    AND b.ReplyDate > CONVERT(VARCHAR(10), GETDate() - 2, 120)
    AND c.id = a.cpMainId
	AND c.AutoReplyConfirm is NULL	--harry

    SELECT a.cpMainId, COUNT(*) Cnt, COUNT(ReplyDate) ReplyCnt
    INTO #1
    FROM #t a, ExjobApply b, Job c
    WHERE a.cpMainId  =  c.cpMainId
	AND c.Id  =  b.JobId
    AND b.AddDate > GETDate() - 183
    GROUP BY a.cpMainId
    --HAVING COUNT(*) > 9

    UPDATE a
    SET a.ReplyRate  =  b.ReplyCnt * 1.0 / b.Cnt
    FROM cpMain a, #1 b
    WHERE a.Id  =  b.cpMainId
    AND b.ReplyCnt * 1.0 / b.Cnt > =  0.1

    --UPDATE cpMain SET ReplyRate  =  NULL WHERE ReplyRate < 0.6

    SELECT a.id, a.ReplyRate rate1, b.ReplyRate rate2
    INTO #t2
    FROM cpMainpublish a, cpMain b
    WHERE a.id  =  b.id
    AND isNULL(a.ReplyRate,0) <> ISNULL(b.ReplyRate, 0)

    UPDATE a SET a.ReplyRate  =  b.rate2 FROM cpMainpublish a, #t2 b WHERE a.id = b.id --AND b.rate2> = 0.6

    UPDATE a
    SET a.ReplyRate  =  b.ReplyRate 
    FROM cpMainpublish a, cpMain b WHERE a.id = b.id AND ISNULL(a.ReplyRate, 0) <> ISNULL(b.ReplyRate, 0) 

    --UPDATE cpMainpublish SET ReplyRate  =  NULL WHERE ReplyRate <0.6
END

GO
/****** Object:  StoredProcedure [dbo].[procCpMainHomepageLogoSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--创建人 Lambo 20101014
--用于首页免费logo区查询单位logo
CREATE PROCEDURE [dbo].[procCpMainHomepageLogoSelect] 
(
	@province_id SMALLINT
)
AS
BEGIN
	SELECT TOP 24 a.id companyid, a.Name companyname, b.ImgFile filename
	FROM cpMain a, cpImage b WITH(nolock)
	WHERE a.Jobnumber > 0
	AND a.MemberType > 1
	AND a.Valid = 1
	AND a.HasLogo = 1 
	AND a.dcProvinceid = @province_id 
	ORDER BY RefreshDate DESC
	OPTION (KEEPFIXED PLAN)
END














GO
/****** Object:  StoredProcedure [dbo].[ProcCpMainHomepageSnapshotDelete]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ProcCpMainHomepageSnapshotDelete]
AS
BEGIN
 	CREATE TABLE #t(Id INT)
	CREATE TABLE #t1(Id INT)
	DELETE FROM SearchDB..CpMainHomepageSnapshot WHERE MemberType IS NULL
	UPDATE CpMainHomepageSnapshot SET dcRegionId = LEFT(dcRegionId, 4) WHERE Len(dcRegionId) > 4

	INSERT INTO #t
	SELECT ID FROM (SELECT dcRegionID, ID, ROW_NUMBER() over(PARTITION by dcRegionID order by RefreshDate desc) as num  
		FROM SearchDB..CpMainHomepageSnapshot WITH(NOLOCK)
		WHERE MemberType > 2) a
	WHERE Num <= 74

	INSERT INTO #t
	SELECT ID FROM (SELECT dcRegionID, ID, ROW_NUMBER() over(PARTITION by dcRegionID order by RefreshDate desc) as num  
		FROM SearchDB..CpMainHomepageSnapshot WITH(NOLOCK)
		WHERE MemberType < 3) a
	WHERE Num <= 80

	INSERT INTO #t
	SELECT ID FROM (SELECT dcSubSiteID, ID, ROW_NUMBER() over(PARTITION by dcSubSiteID order by RefreshDate desc) as num  
		FROM SearchDB..CpMainHomepageSnapshot WITH(NOLOCK)
		WHERE MemberType > 2) a
	WHERE Num <= 74

	INSERT INTO #t
	SELECT ID FROM (SELECT dcSubSiteID, ID, ROW_NUMBER() over(PARTITION by dcSubSiteID order by RefreshDate desc) as num  
		FROM SearchDB..CpMainHomepageSnapshot WITH(NOLOCK)
		WHERE MemberType < 3) a
	WHERE Num <= 80
 
	INSERT #t1 SELECT ID FROM SearchDB..CpMainHomepageSnapshot
	DELETE #t1 WHERE ID IN(SELECT ID FROM #t)
	DELETE FROM SearchDB..CpMainHomepageSnapshot WHERE ID IN(SELECT ID FROM #t1)
END










GO
/****** Object:  StoredProcedure [dbo].[ProcCpMainHomepageSnapShotFix]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
sean 2013-8-21
写一下注释，以便以后容易检查和阅读
*/
CREATE PROCEDURE [dbo].[ProcCpMainHomepageSnapShotFix]
AS
BEGIN
	--清空暂存表
	TRUNCATE TABLE SearchDB..cpMainHomepageSnapshotTmp
	DELETE CpMainHomepageSnapshot WHERE Name IS NULL OR RealCpMainId IS NULL Or RefreshDate IS NULL

	DECLARE @t AS TABLE(CpMainID INT)

	SELECT Id cpMainID
	INTO #t
	FROM cpMain WITH(NOLOCK)
	WHERE MemberType > 0
	AND (RefreshDate > DATEADD(MINUTE, -10, GETDATE())
		OR LastLoginDate > DATEADD(MINUTE, -10, GETDATE())
		)
	AND Valid = 1

	DELETE #t WHERE cpMainId IN(SELECT RealCpMainId FROM SearchDB..cpMainHomepageSnapshot WITH(NOLOCK))

	INSERT @t SELECT * FROM #t

	--加入cpmaintmp临时表
	INSERT INTO @t
	SELECT DISTINCT cpMainID
	FROM SearchDB..cpMainTmp WITH(NOLOCK)

	INSERT INTO @t
	SELECT a.Id
	FROM cpMain a WITH(NOLOCK), SearchDB..cpMainHomepageSnapshot b WITH(NOLOCK)
	WHERE a.Id = b.RealCpMainId
	AND a.RefreshDate <> b.RefreshDate
	
	--加入12分钟内修改过职位的企业
	INSERT INTO @t(CpMainID)
	SELECT DISTINCT cpMainID FROM Job WITH(NOLOCK) 
	WHERE LastModifyDate > DATEADD(MINUTE, -12, GETDATE())
	AND cpMainID NOT IN(SELECT cpMainID FROM @t)

	--把临时表的数据加入暂存表
	INSERT INTO SearchDB..cpMainHomepageSnapshotTmp(cpMainId, RefreshDate, MemberType, dcSubsiteId, dcRegionId, Name, IsAgent, RealCpMainId)
	SELECT SecondId, RefreshDate, MemberType, dcSubsiteId, dcRegionId, Name, IsAgent, Id
	FROM cpMain WITH(NOLOCK)
	WHERE ID IN(SELECT CpMainId FROM @t)
	AND MemberType > 0 AND Valid = 1

	--没有在百度上抓到的，设置nofollow="",就是要 follow
	UPDATE SearchDB..cpMainHomepageSnapshotTmp SET NoFollow = ''
	--WHERE cpMainId IN(SELECT PageID FROM PageBaiduInclude WHERE PageType = 1 AND IncludeDate IS NULL)

	--填充暂存表数据
	UPDATE a
	SET a.JobNumber = b.JobNumber, a.IsAgent = b.IsAgent, a.dcSubSiteID = b.dcSubSiteID, a.MemberType = b.MemberType, 
		a.Name = b.Name, a.dcRegionID = b.dcRegionID
	FROM SearchDB..cpMainHomepageSnapshotTmp a, cpMain b
	WHERE a.RealCpMainid = b.id

	--填充暂存表数据 jobids
	UPDATE SearchDB..cpMainHomepageSnapshotTmp
	SET JobId = dbo.getJobSecondIds(RealCpMainid), JobName = dbo.getJobNames(RealCpMainid)
	
	--填充暂存表数据  最新职位
--	UPDATE SearchDB..CpMainHomepageSnapshotTmp
--	SET LastJobId = (SELECT TOP 1 SecondID FROM Job WITH(NOLOCK) WHERE Job.cpMainid = SearchDB..CpMainHomepageSnapshotTmp.RealCpMainId
--					AND Valid = 1 ORDER BY IssueDate DESC)	
	UPDATE a
	SET a.LastJobId = (SELECT TOP 1 SecondID FROM Job WITH(NOLOCK) WHERE Job.cpMainid = a.RealCpMainId
					AND Valid = 1 AND CHARINDEX(Job.SecondId, LEFT(a.JobId, 21)) > 0 ORDER BY IssueDate DESC)
	FROM SearchDB..CpMainHomepageSnapshotTmp a
	WHERE MemberType > 2

	--填充暂存表数据最后发布时间
	UPDATE SearchDB..cpMainHomepageSnapshotTmp
	SET LastJobIssueDate = (SELECT IssueDate FROM Job WHERE Job.Secondid = SearchDB..cpMainHomepageSnapshotTmp.LastJobid)
	WHERE MemberType > 2

	--填充暂存表数据 营业执照审核时间
	UPDATE a SET a.cplicenceDate=b.checkDate
	FROM SearchDB..cpMainHomepageSnapshotTmp a, cpLicence b
	WHERE a.RealCpMainid = b.cpMainid
	AND a.MemberType < 3

	--先添加未增加的
	INSERT INTO SearchDB..cpMainHomepageSnapshot(cpMainId, NoFollow, RealCpMainid)
	SELECT cpMainId, NoFollow, RealCpMainid
	FROM SearchDB..cpMainHomepageSnapshotTmp WITH(NOLOCK)
	WHERE RealCpMainid NOT IN(SELECT RealCpMainid FROM SearchDB..cpMainHomepageSnapshot WITH(NOLOCK))

	--再更改数据
	UPDATE a
	SET a.dcSubsiteID = b.dcSubsiteID, 
		a.dcRegionID = b.dcRegionID, 
		a.MemberType = b.MemberType, 
		a.Name = b.Name, 
		a.IsAgent = b.IsAgent, 
		a.JobNumber = b.JobNumber, 
		a.JobID = b.JobID, 
		a.JobName = b.JobName, 
		a.LastJobIssueDate = b.LastJobIssueDate,
		a.LastJobId = b.LastJobId,
		a.cpLicenceDate = b.cpLicenceDate,
		a.RefreshDate = b.RefreshDate
	FROM SearchDb..cpMainHomepageSnapshot a WITH(NOLOCK), 
		SearchDb..cpMainHomepageSnapshotTmp b WITH(NOLOCK)
	WHERE a.RealCpMainid = b.RealCpMainid

	UPDATE a
	SET a.LastJobId = (SELECT TOP 1 SecondID FROM Job WITH(NOLOCK) WHERE Job.cpMainid = a.RealCpMainId
					AND Valid = 1 AND CHARINDEX(Job.SecondId, LEFT(a.JobId, 21)) > 0 ORDER BY IssueDate DESC)
	FROM SearchDB..CpMainHomepageSnapshot a
	WHERE MemberType > 2

	TRUNCATE TABLE SearchDB..cpMainTmp
END











GO
/****** Object:  StoredProcedure [dbo].[ProcCpMainHomepageSnapshotRebuild]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ProcCpMainHomepageSnapshotRebuild]
AS
BEGIN
	TRUNCATE TABLE SearchDB..CpMainHomepageSnapshotTmp
	--找出所有1天内刷新的，未认证的或普通或缴费的，并且有效的企业
	INSERT SearchDB..CpMainHomepageSnapshotTmp(cpMainId, RefreshDate, RealCpMainId, MemberType, dcRegionID, dcSubSiteId)
	SELECT SecondId, RefreshDate, Id, MemberType, dcRegionID, dcSubSiteId
	FROM cpMain WITH(NOLOCK)
	WHERE Refreshdate > GETDATE() - 1 AND MemberType > 0 AND Valid = 1

	EXEC ProcCpMainHomepageSnapshotTmpDelete
	--没有在百度上抓到的，设置nofollow="",就是要 follow
	UPDATE SearchDB..CpMainHomepageSnapshotTmp SET NoFollow = ''
	--WHERE CpMainId IN(SELECT PageID FROM PageBaiduInclude WHERE PageType = 1 AND IncludeDate IS NULL)
	
	--填写内容
	UPDATE a
	SET a.JobNumber = b.JobNumber, a.IsAgent = b.IsAgent, a.Name = b.Name
	FROM SearchDB..CpMainHomepageSnapshotTmp a, cpMain b
	WHERE a.RealCpMainId=b.id
	
	--填写jobids
	UPDATE SearchDB..CpMainHomepageSnapshotTmp
	SET JobId = dbo.GetJobSecondIds(RealCpMainId), JobName = dbo.GetJobNames(RealCpMainId)

	--找出收费用户的最新职位id
--	UPDATE SearchDB..CpMainHomepageSnapshotTmp
--	SET LastJobId = (SELECT TOP 1 SecondID FROM Job WITH(NOLOCK) WHERE Job.cpMainid = SearchDB..CpMainHomepageSnapshotTmp.RealCpMainId
--					AND Valid = 1 ORDER BY IssueDate DESC)	
	UPDATE a
	SET a.LastJobId = (SELECT TOP 1 SecondID FROM Job WITH(NOLOCK) WHERE Job.cpMainid = a.RealCpMainId
					AND Valid = 1 AND CHARINDEX(Job.SecondId, LEFT(a.JobId, 21)) > 0 ORDER BY IssueDate DESC)
	FROM SearchDB..CpMainHomepageSnapshotTmp a
	WHERE MemberType > 2

	--找出收费用户的最后发布日期
	UPDATE SearchDB..CpMainHomepageSnapshotTmp
	SET LastJobIssueDate = (SELECT IssueDate FROM Job WHERE Job.SecondId = SearchDB..CpMainHomepageSnapshotTmp.LastJobid)
	WHERE MemberType > 2

	--普通用户填写营业执照审核时间
	UPDATE a SET a.cplicenceDate=b.checkDate
	FROM SearchDB..CpMainHomepageSnapshotTmp a, cpLicence b
	WHERE a.RealCpMainId = b.cpMainid
	AND a.MemberType < 3

	--如果CpMainHomepageSnapshotTmp数量少于3000行就不更新了，因为很可能是出错了
	IF (SELECT COUNT(*) FROM SearchDB..CpMainHomepageSnapshotTmp WITH(NOLOCK)) > 3000
	BEGIN
		TRUNCATE TABLE SearchDB..CpMainHomepageSnapshot
		SET IDENTITY_INSERT SearchDB..CpMainHomepageSnapshot ON
		INSERT INTO SearchDB..CpMainHomepageSnapshot(ID, dcSubsiteID, dcRegionID, cpMainID, MemberType, Name, IsAgent, JobNumber, JobID,
			JobName, LastJobIssueDate, LastJobId, cpLicenceDate, RefreshDate, NoFollow, RealCpMainId)
		SELECT ID, dcSubsiteID, dcRegionID, cpMainID, MemberType, Name, IsAgent, JobNumber, JobID,
			JobName, LastJobIssueDate, LastJobId, cpLicenceDate, RefreshDate, NoFollow, RealCpMainId
		FROM SearchDB..CpMainHomepageSnapshotTmp
		SET IDENTITY_INSERT SearchDB..CpMainHomepageSnapshot OFF
	END
	ELSE
		RETURN

	--如果CpMainHomepageSnapshot数量少于3000行，尝试更新一次
	IF (SELECT COUNT(*) FROM SearchDB..CpMainHomepageSnapshot WITH(NOLOCK)) < 3000
	BEGIN
		TRUNCATE TABLE SearchDB..CpMainHomepageSnapshot
		SET IDENTITY_INSERT SearchDB..CpMainHomepageSnapshot ON
		INSERT INTO SearchDB..CpMainHomepageSnapshot(ID, dcSubsiteID, dcRegionID, cpMainID, MemberType, Name, IsAgent, JobNumber, JobID,
			JobName, LastJobIssueDate, LastJobId, cpLicenceDate, RefreshDate, NoFollow, RealCpMainId)
		SELECT ID, dcSubsiteID, dcRegionID, cpMainID, MemberType, Name, IsAgent, JobNumber, JobID,
			JobName, LastJobIssueDate, LastJobId, cpLicenceDate, RefreshDate, NoFollow, RealCpMainId
		FROM SearchDB..CpMainHomepageSnapshotTmp
		SET IDENTITY_INSERT SearchDB..CpMainHomepageSnapshot OFF
	END

	--如果CpMainHomepageSnapshot数量少于3000行，再尝试更新一次
	IF (SELECT COUNT(*) FROM SearchDB..CpMainHomepageSnapshot WITH(NOLOCK)) < 3000
	BEGIN
		TRUNCATE TABLE SearchDB..CpMainHomepageSnapshot
		SET IDENTITY_INSERT SearchDB..CpMainHomepageSnapshot ON
		INSERT INTO SearchDB..CpMainHomepageSnapshot(ID, dcSubsiteID, dcRegionID, cpMainID, MemberType, Name, IsAgent, JobNumber, JobID,
			JobName, LastJobIssueDate, LastJobId, cpLicenceDate, RefreshDate, NoFollow, RealCpMainId)
		SELECT ID, dcSubsiteID, dcRegionID, cpMainID, MemberType, Name, IsAgent, JobNumber, JobID,
			JobName, LastJobIssueDate, LastJobId, cpLicenceDate, RefreshDate, NoFollow, RealCpMainId
		FROM SearchDB..CpMainHomepageSnapshotTmp
		SET IDENTITY_INSERT SearchDB..CpMainHomepageSnapshot OFF
	END
END
 











GO
/****** Object:  StoredProcedure [dbo].[ProcCpMainHomepageSnapshotTmpDelete]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ProcCpMainHomepageSnapshotTmpDelete]
AS
BEGIN
 	CREATE TABLE #t(Id INT)
	CREATE TABLE #t1(Id INT)
	DELETE FROM SearchDB..CpMainHomepageSnapshotTmp WHERE MemberType IS NULL
	UPDATE SearchDb..CpMainHomepageSnapshotTmp SET dcRegionId = LEFT(dcRegionId, 4) WHERE Len(dcRegionId) > 4

	INSERT INTO #t
	SELECT RealcpMainID FROM (SELECT dcRegionID, RealcpMainID, ROW_NUMBER() over(PARTITION by dcRegionID order by RefreshDate desc) as num  
		FROM SearchDB..CpMainHomepageSnapshotTmp WITH(NOLOCK)
		WHERE MemberType > 2) a
	WHERE Num <= 74

	INSERT INTO #t
	SELECT RealcpMainID FROM (SELECT dcRegionID, RealcpMainID, ROW_NUMBER() over(PARTITION by dcRegionID order by RefreshDate desc) as num  
		FROM SearchDB..CpMainHomepageSnapshotTmp WITH(NOLOCK)
		WHERE MemberType < 3) a
	WHERE Num <= 80

	INSERT INTO #t
	SELECT RealcpMainID FROM (SELECT dcSubSiteID, RealcpMainID, ROW_NUMBER() over(PARTITION by dcSubSiteID order by RefreshDate desc) as num  
		FROM SearchDB..CpMainHomepageSnapshotTmp WITH(NOLOCK)
		WHERE MemberType > 2) a
	WHERE Num <= 74

	INSERT INTO #t
	SELECT RealcpMainID FROM (SELECT dcSubSiteID, RealcpMainID, ROW_NUMBER() over(PARTITION by dcSubSiteID order by RefreshDate desc) as num  
		FROM SearchDB..CpMainHomepageSnapshotTmp WITH(NOLOCK)
		WHERE MemberType < 3) a
	WHERE Num <= 80
  
	INSERT #t1 SELECT RealcpMainID FROM SearchDB..CpMainHomepageSnapshotTmp
	DELETE #t1 WHERE ID IN(SELECT ID FROM #t)
	DELETE FROM SearchDB..CpMainHomepageSnapshotTmp WHERE RealcpMainID IN(SELECT ID FROM #t1)
END










GO
/****** Object:  StoredProcedure [dbo].[procCpMainProvinceIDByCaMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.10
--创建人：John
--说明：获取公司所在地ID信息
--#####################################################
CREATE PROCEDURE [dbo].[procCpMainProvinceIDByCaMainIDSelect]
(
	@caMainID INT
)
AS
BEGIN
	SELECT b.dcProvinceID FROM caMain a WITH(NOLOCK),cpMain b WITH(NOLOCK) WHERE a.id = @caMainID AND a.cpMainID = b.id
END


GO
/****** Object:  StoredProcedure [dbo].[ProcCpMainSameIndustry32Insert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ProcCpMainSameIndustry32Insert]
AS
SET NOCOUNT ON
BEGIN
	SELECT 32 dcRegionId, dcIndustryID, ID RealId, SecondID, Name, Row
	INTO #t
	FROM (SELECT Left(a.dcRegionId, 4) dcRegionId, b.dcIndustryID, a.Id, a.SecondID, a.Name, a.LastLoginDate, 
			ROW_NUMBER() OVER(PARTITION BY b.dcIndustryId ORDER BY a.Id DESC) Row
		FROM cpMainPublish a WITH(NOLOCK)
		LEFT JOIN cpIndustry b ON a.id = b.CpmainID
		WHERE a.dcProvinceId = '30'	--temp modify
		 AND MemberType > 1
		) a
	WHERE a.Row < 11
	AND a.Id IN (SELECT cpMainId FROM JobPublish WITH(NOLOCK) WHERE Valid > 0)  
	ORDER BY dcRegionId, dcIndustryID, Row

	ALTER TABLE #t ADD LogoFile VARCHAR(90)
	UPDATE a SET A.LogoFile = b.LogoFile FROM #t a, cpMain b WHERE a.RealId = b.ID

	TRUNCATE TABLE SearchDb..CpMainSameIndustry32
	INSERT INTO SearchDb..CpMainSameIndustry32 SELECT * FROM #t 
END
GO
/****** Object:  StoredProcedure [dbo].[ProcCpMainSameIndustryInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ProcCpMainSameIndustryInsert]
AS
BEGIN
	SELECT dcRegionId, dcIndustryID, ID RealId, SecondID, Name, Row
	INTO #t
	FROM (SELECT Left(a.dcRegionId, 4) dcRegionId, b.dcIndustryID, a.Id, a.SecondID, a.Name, a.LastLoginDate, 
			ROW_NUMBER() OVER(PARTITION BY Left(a.dcRegionId, 4), b.dcIndustryId ORDER BY a.LastLoginDate DESC) Row
		FROM cpMainPublish a WITH(NOLOCK)
		LEFT JOIN cpIndustry b ON a.id = b.CpmainID
		WHERE a.dcRegionId NOT LIKE '32%'	--temp modify
		) a
	WHERE a.Row < 11
	AND a.Id IN (SELECT cpMainId FROM JobPublish WITH(NOLOCK) WHERE Valid > 0)  
	ORDER BY dcRegionId, dcIndustryID, Row

 	ALTER TABLE #t ADD LogoFile VARCHAR(90)
	UPDATE a SET A.LogoFile = b.LogoFile FROM #t a, cpMain b WHERE a.RealId = b.ID

	TRUNCATE TABLE SearchDb..CpMainSameIndustry
	INSERT INTO SearchDb..CpMainSameIndustry SELECT * FROM #t WHERE dcRegionId NOT LIKE '32%'
	--TRUNCATE TABLE SearchDb..CpMainSameIndustry32
	--INSERT INTO SearchDb..CpMainSameIndustry32 SELECT * FROM #t WHERE dcRegionId LIKE '32%'
	EXEC ProcCpMainSameIndustry32Insert
END

GO
/****** Object:  StoredProcedure [dbo].[ProcCpViPlanSmsMessageLogInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2014.10.29
--创建人：John
--说明：企业邀请个人视频面试添加短信通知
--#####################################################
CREATE PROCEDURE [dbo].[ProcCpViPlanSmsMessageLogInsert]
(
	@JobID INT,
	@CvMainID INT
)
AS
BEGIN
	DECLARE @cnt INT
	SELECT @cnt = COUNT(1) 
	FROM SmsMessageLog 
	WHERE msgtype = 121 
	AND camainid =
		(
			SELECT camainid 
			FROM job 
			WHERE id = @JobID
		 ) 
	AND adddate > CONVERT(VARCHAR(10), GETDATE(), 23)
	IF @cnt < 10
	BEGIN
		INSERT SmsMessageLog(SendMan, ManagerUserId, paMainId, caMainId, Mobile, MsgType, IsCat, Msg)
		SELECT TOP 1 0, NULL, a.ID, e.caMainID, b.Mobile, 121, 0, ISNULL(b.Name,'') +'，'+ d.Name +'在'+ c.SubSiteName + c.EmailSite +'上邀请您参加视频面试，请登录网站查看'
		FROM cvMain a WITH(NOLOCK), 
			paMain b WITH(NOLOCK), 
			dcSubSite c WITH(NOLOCK),
			cpMain d WITH(NOLOCK),
			job e WITH(NOLOCK)
		WHERE a.paMainID = b.ID 
		AND b.dcSubSiteID = c.ID 
		AND d.id = e.cpMainID 
		AND e.ID = @JobID 
		AND b.Mobile > '' 
		AND a.ID = @CvMainID 
		AND b.IsReceiveSms = 1
	END
END


GO
/****** Object:  StoredProcedure [dbo].[procCpwishByIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.5
--创建人：NICK
--说明：祝福墙数据
--#####################################################
CREATE PROCEDURE [dbo].[procCpwishByIDSelect]
(
	@ID INT
)
AS
BEGIN
	UPDATE ShortDB..cpwish SET ClickNumber=ClickNumber+1 WHERE ID=@ID
	SELECT * FROM ShortDB..cpwish WITH(NOLOCK) WHERE ID=@ID
END


GO
/****** Object:  StoredProcedure [dbo].[procCpwishInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.5
--创建人：NICK
--说明：祝福墙数据插入
--#####################################################
CREATE PROCEDURE [dbo].[procCpwishInsert]
(
	@Content VARCHAR(500),
	@cpMainID INT
)
AS
BEGIN
	INSERT INTO ShortDB..cpwish VALUES(@cpMainID,@Content,1,0,GETDATE())
	RETURN 1
END


GO
/****** Object:  StoredProcedure [dbo].[procCpwishSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.5
--创建人：NICK
--说明：祝福墙数据获取
--#####################################################
CREATE PROCEDURE [dbo].[procCpwishSelect]
AS
BEGIN
	SELECT TOP 200 a.*,b.Name cpName 
	FROM ShortDB..cpwish a WITH(NOLOCK),cpMain b WITH(NOLOCK) 
	WHERE b.ID=a.cpMainID 
	AND IsDesplay='1' 
	ORDER BY addDate DESC
END


GO
/****** Object:  StoredProcedure [dbo].[procCvDownDocByDowncountSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--type=1 首页/下载排行获取
--harry 
--2017-12-18
--Carl  2018-02-01
--Carl  2018-02-28
CREATE PROCEDURE [dbo].[procCvDownDocByDowncountSelect]
(
	@type INT
)
AS
BEGIN
SET NOCOUNT ON
	IF @type =1 --首页
	BEGIN
		SELECT TOP 10 *
		FROM cvdowndoc WITH(NOLOCK) 
		WHERE IsBeta=0 ORDER BY newid()
	END
	ELSE IF @type=2
	BEGIN
		SELECT * 
		FROM cvdowndoc WITH(NOLOCK)
		WHERE IsBeta=0 
		ORDER BY downcount DESC
	END
	ELSE--测试用的
	BEGIN
		SELECT * 
		FROM cvdowndoc WITH(NOLOCK) 
		ORDER BY downcount DESC
	END
SET NOCOUNT OFF
END
GO
/****** Object:  StoredProcedure [dbo].[procCvDownDocByIdSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--获取简历模板详情
--harry 
--2017-12-21
CREATE PROCEDURE [dbo].[procCvDownDocByIdSelect]
(
  @Id INT
)
AS
BEGIN
SET NOCOUNT ON 
	SELECT * 
	FROM cvdowndoc WITH(NOLOCK)
	WHERE id = @Id
SET NOCOUNT OFF
END

GO
/****** Object:  StoredProcedure [dbo].[procCvDownDocUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--更新简历模板的浏览量、下载量
--type 1浏览量 2下载量
--harry
--2017-12-21
CREATE PROCEDURE [dbo].[procCvDownDocUpdate]
(
	@type INT,
	@id INT
)
AS
BEGIN
	IF @type = 1
	BEGIN
		UPDATE cvdowndoc
		SET ViewCount = ISNULL(ViewCount,0) +1
		WHERE id = @id
	END
	ELSE
	BEGIN
		UPDATE cvdowndoc
		SET DownCount = ISNULL(DownCount,0) +1
		WHERE id = @id
	END
END
GO
/****** Object:  StoredProcedure [dbo].[ProcCvMainByHasVerifySelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create procedure [dbo].[ProcCvMainByHasVerifySelect]
(
	@cvMainId INT
)
AS
BEGIN
	IF EXISTS(SELECT 'x' FROM paMain a, cvMain b
		WHERE a.Id = b.paMainId
		AND a.VerifyCount > 0
		AND b.Id = @cvMAinId
		AND b.VerifyResult = 1
		)
		RETURN 1
	ELSE
		RETURN 0
END

GO
/****** Object:  StoredProcedure [dbo].[procCvMainByPaMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.10
--创建人：Nick
--说明：根据PaMianID来获取其简历的ID和AddDate
--#####################################################
CREATE PROCEDURE [dbo].[procCvMainByPaMainIDSelect]
(
	@paMainID INT
)
AS
BEGIN TRY
	SELECT * FROM  cvmain a WITH(NOLOCK),pamain b WITH(NOLOCK) 
	WHERE a.paMainID=b.ID 
	AND pamainid= @paMainID
	ORDER BY a.valid DESC,a.refreshdate DESC
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[proccvrExchangeByRecommendIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.31
--创建人：Nick
--说明：获取礼品列表
--#####################################################
CREATE PROCEDURE [dbo].[proccvrExchangeByRecommendIDSelect]
(
	@RecommendID INT
)
AS
BEGIN TRY
	SELECT (
		SELECT COUNT(*) cnt 
		FROM marketdb..cvrRecommend 
		WHERE RecommendID=@RecommendID 
		AND HasValid=3 
		AND HasReply=1
	)
	allIntegral,(
		SELECT SUM(Amount) 
		FROM marketdb..cvrExchange 
		WHERE RecommendID=@RecommendID AND HasVerify<>2
	) lastIntegral
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[ProcDcAutoEmailInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ProcDcAutoEmailInsert]
AS
BEGIN
    IF(SELECT COUNT(*) FROM dcAutoEmail) > 50000
        RETURN

    SELECT TOP 0 * INTO #t FROM dcAutoEmail
    INSERT #t 
    SELECT TOP 10000 LEFT(NEWID(), 3) + '_' + LEFT(NEWID(), 2) + '@your_email.com' FROM cpMain
    UPDATE #t SET Email = CHAR(65 + id % 26) + Email

    DELETE a
    FROM #t a, dcAutoEmail b
    WHERE a.Email = b.Email

    DELETE a
    FROM #t a, paMain b
    WHERE a.Email = b.Email

    DELETE a
    FROM #t a, Resume_XinXi b
    WHERE a.Email = b.Email

    INSERT INTO dcAutoEmail SELECT DISTINCT Email FROM #t
END
GO
/****** Object:  StoredProcedure [dbo].[procdcAutoEmailSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.12
--创建人：Nick
--说明：
--#####################################################
CREATE PROCEDURE [dbo].[procdcAutoEmailSelect]
AS
BEGIN
	SELECT top 1 *  FROM dcAutoEmail ORDER BY id
END


GO
/****** Object:  StoredProcedure [dbo].[procdcCollegeSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.31
--创建人：Nick
--说明：读取学校信息
--#####################################################
CREATE PROCEDURE [dbo].[procdcCollegeSelect]
(
	@CollegeName VARCHAR(50)
)
AS
BEGIN TRY
	SELECT TOP 10 COLNAME 
	FROM dccollege 
	WHERE COLNAME LIKE ''+@CollegeName+'%' 
	OR Pinyin LIKE ''+@CollegeName+'%'  
	OR Jianpin LIKE ''+@CollegeName+'%' 
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[procdcCvConvertMapSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.31
--创建人：Nick
--说明：获取对应的自己数据库中的ID
--修改：Mice 123 修改@type 的长度为50
--#####################################################
CREATE PROCEDURE [dbo].[procdcCvConvertMapSelect]
(
	@webName VARCHAR(100),
	@type VARCHAR(50),
	@description VARCHAR(500)
)
AS
BEGIN
	SELECT * 
	FROM dcCvConvertMap WITH(NOLOCK) 
	WHERE webName = @webName 
	AND type = @type 
	AND description = @description
END
GO
/****** Object:  StoredProcedure [dbo].[ProcDcFeeStandardByPriceCvSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ProcDcFeeStandardByPriceCvSelect]
(
	@dcProvinceID AS INT
)
AS
BEGIN
	SELECT PriceCv FROM DcFeeStandard WITH(NOLOCK)
	WHERE dcProvinceID = @dcProvinceID
END














GO
/****** Object:  StoredProcedure [dbo].[procDcFeeStandardByProvinceIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.03
--创建人：Nick
--说明：dcfeestandard
--#####################################################
CREATE PROCEDURE [dbo].[procDcFeeStandardByProvinceIDSelect]
(
	@ProvinceID INT
)
AS
BEGIN TRY
	SELECT NeedPoint FROM dcfeestandard With(Nolock) WHERE dcprovinceid=@ProvinceID
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[procDcIndustrySelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.5
--创建人：NICK
--说明：获取行业信息
--#####################################################
CREATE PROCEDURE [dbo].[procDcIndustrySelect]
AS
BEGIN
	SELECT * FROM dcindustry ORDER BY category,orderno
END


GO
/****** Object:  StoredProcedure [dbo].[procdcIpPlaceByIPMobileSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2018.6.11
--创建人：harry
--说明：根据ip或mobile得到dcIpPlace
--#####################################################
CREATE PROCEDURE [dbo].[procdcIpPlaceByIPMobileSelect]
(
	@IP INT,
	@Mobile CHAR(11)
)
AS
BEGIN
	DECLARE @regionId INT
	IF LEN(@Mobile)>0
	BEGIN
		SELECT TOP 1  @regionId=dcRegionId 
		FROM dcMobilearea WITH (NOLOCK)
		WHERE LEFT(@Mobile,7)=Num
	END	
	ELSE
	BEGIN
	SELECT TOP 1 @regionId=dcSubSiteId 
		FROM dcIpPlace a WITH(NOLOCK INDEX(IX_dcIpPlace_IpStart)) 
		WHERE IPStart <= @IP 
		ORDER BY IPStart DESC
		
        IF LEN(@regionId)<3
		BEGIN
			SELECT TOP 1  @regionId=dcRegionId 
			FROM dcMobilearea WITH (NOLOCK)
			WHERE LEFT(@Mobile,7)=Num	
		END
		
	END
	
	IF LEN(@regionId)<4
	BEGIN
		SELECT TOP 0 ID, Abbr
		FROM dcRegion
	END
	ELSE
	BEGIN
		SELECT ID, Abbr
		FROM dcRegion
		WHERE ID=LEFT(@regionId,4)
	END 
END

GO
/****** Object:  StoredProcedure [dbo].[procdcIpPlaceByIPSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.3
--创建人：NICK
--说明：根据ip得到dcIpPlace
--#####################################################
CREATE PROCEDURE [dbo].[procdcIpPlaceByIPSelect]
(
	@IP VARCHAR(20)
)
AS
BEGIN
	SELECT TOP 1 * 
	FROM dcIpPlace WITH(NOLOCK INDEX(IX_dcIpPlace_IpStart)) 
	WHERE IPStart <= @IP 
	ORDER BY IPStart DESC
END


GO
/****** Object:  StoredProcedure [dbo].[ProcDcIpPlaceInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ProcDcIpPlaceInsert]
AS
BEGIN
	IF (SELECT COUNT(*) FROM tmp_IpPlace) < 400000
		RETURN

	TRUNCATE TABLE dcIPPlace
	INSERT INTO dcIPPlace(ipstart, ipend, city, Provider, dcSubsiteId)
	SELECT ipStart, ipEnd, City, Provider, 0 FROM tmp_ipplace	--插入地址表
        
	update dcIpplace set international = 1 where city in(select distinct city from dcipplace 
	where provider not in('CZ88.NET')
	and provider not like ('%电信%')
	and provider not like ('%联通%')
	and left(city,2)not in(select left(description,2) from dcregion)
	and city not like '%大学%'
	and city not like '中%'
	and city not like '东北%'
	and city not like '华%'
	and city not like '%网络'
	and city not like '局域网'
	and city not like '联通'
	and city not like '全国通用'
	and city not like '本机地址'
)
    
	update dcipplace set provider='地址不详' where city='局域网'
	update dcipplace set provider='地址不详' where city='本机地址'

	UPDATE a SET a.dcSubSiteId = b.dcSubSiteID
	FROM dcIpPlace a, dcIpPlaceCity b
	WHERE a.City = b.City

	UPDATE a SET a.dcSubSiteId = b.dcSubSiteID
	FROM dcIpPlace a, dcIpPlaceCity b
	WHERE a.City LIKE b.City + '%'
	AND a.international IS NULL
	AND a.dcSubSiteId = 0
	AND LEN(b.dcSubSiteID) = 6

	UPDATE a SET a.dcSubSiteId = b.dcSubSiteID
	FROM dcIpPlace a, dcIpPlaceCity b
	WHERE a.City LIKE b.City + '%'
	AND a.international IS NULL
	AND a.dcSubSiteId = 0
	AND LEN(b.dcSubSiteID) = 4

	UPDATE a SET a.dcSubSiteId = b.dcSubSiteID
	FROM dcIpPlace a, dcIpPlaceCity b
	WHERE a.City LIKE b.City + '%'
	AND a.international IS NULL
	AND a.dcSubSiteId = 0
	AND LEN(b.dcSubSiteID) = 2

	UPDATE a SET a.dcSubSiteId = b.ID
	FROM dcIpPlace a, dcSubSite b
	WHERE a.City LIKE b.SubSiteCity + '%'
	AND a.international IS NULL
	AND a.dcSubSiteId = 0

	UPDATE dcIpPlace SET international = 1 WHERE international IS NULL AND dcSubSiteId = 0

	UPDATE dcIpPlace SET dcSubSiteId = 0 WHERE international IS NULL AND dcSubSiteId = 1

	DROP TABLE tmp_IpPlace
END














GO
/****** Object:  StoredProcedure [dbo].[ProcdcJobtypeByIdSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--根据jobtypeID查询jobtype
--Harry
--2015-7-24
CREATE PROCEDURE [dbo].[ProcdcJobtypeByIdSelect]
(
	@id INT
)
AS
BEGIN
	SELECT [Description] 
	FROM dcjobtype
	WHERE id=@id 
END
GO
/****** Object:  StoredProcedure [dbo].[procdcJobTypeByJobTypeID6Select]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.04
--创建人：Nick
--说明：根据职位id查询前6个感兴趣的职位
--#####################################################
CREATE PROCEDURE [dbo].[procdcJobTypeByJobTypeID6Select]
(
	@JobTypeID VARCHAR(20)
)
AS
BEGIN TRY
	Select TOP 6 id,description 
	FROM dcJobType
	WHERE ID LIKE LEFT(@JobTypeID, 2) + '%' AND ID <> @JobTypeID
	AND description NOT LIKE '其他%' ORDER BY NEWID()  
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[procdcJobTypeByKeyWordSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.03
--创建人：Nick
--说明：根据关键字获取职位类别
--#####################################################
CREATE PROCEDURE [dbo].[procdcJobTypeByKeyWordSelect]
(
	@KeyWord VARCHAR(100),
	@IsEnglish INT
)
AS
BEGIN TRY
	IF @IsEnglish = 1
	BEGIN
		SELECT * FROM dcJobType WITH(NOLOCK) WHERE dbo.GetPyFirst(Description) LIKE '%'+@KeyWord+'%'
	END
	ELSE 
	BEGIN
		SELECT * FROM dcJobType WITH(NOLOCK) WHERE Description LIKE '%'+@KeyWord+'%'
	END
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[ProcdcJobTypeHotNumberInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--生成M站热门职位关键词对应的职位数量，计划任务每天凌晨1点执行
CREATE PROCEDURE [dbo].[ProcdcJobTypeHotNumberInsert]
AS
BEGIN
	--清空dcJobTypeHotNumber
	TRUNCATE TABLE dcJobTypeHotNumber

	DECLARE DcProvince_Cursor CURSOR
	FOR SELECT ID FROM dcProvince

	OPEN DcProvince_Cursor
	DECLARE @ProvinceID sysname
	FETCH NEXT FROM DcProvince_Cursor INTO @ProvinceID
	WHILE (@@FETCH_STATUS <> -1)
	BEGIN
		IF (@@FETCH_STATUS <> -2)
		BEGIN 
			INSERT dcJobTypeHotNumber
			SELECT @ProvinceID, a.Id,
				CASE CHARINDEX(',', dcJobTypeId)
				WHEN 0
				THEN (
					SELECT SUM(JobNum)
					FROM hpJobTypeInfo 
					WHERE CONVERT(VARCHAR(8),dcJobTypeID) like ''+a.dcJobTypeId+'%'
					AND dcRegionId like ''+CONVERT(VARCHAR,@ProvinceID)+'%' 
				)
				ELSE(
					SELECT SUM(JobNum)
					FROM hpJobTypeInfo 
					WHERE CONVERT(VARCHAR(8),dcJobTypeID) IN (SELECT * FROM [fnSplit](a.dcJobTypeId,','))
					AND dcRegionId like ''+CONVERT(VARCHAR(8),@ProvinceID)+'%' 
				) 
				END
			FROM DcJobTypeHot a
		END
		FETCH NEXT FROM DcProvince_Cursor INTO @ProvinceID
	END
	CLOSE DcProvince_Cursor
	DEALLOCATE DcProvince_Cursor
END










GO
/****** Object:  StoredProcedure [dbo].[ProcDcJobTypeHotSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--M站获取热门职位关键词
--nick 20140539
CREATE PROCEDURE [dbo].[ProcDcJobTypeHotSelect]
(
	@ProvinceID INT
)
AS
BEGIN
	return
	DECLARE @t AS TABLE(ID INT, JobTypeName VARCHAR(100), dcJobTypeId VARCHAR(200), PinYin VARCHAR(20),  OrderBy INT,JobNum INT)
	INSERT @t
	SELECT *,
	CASE CHARINDEX(',', dcJobTypeId)
	WHEN 0
	THEN (
		SELECT SUM(JobNum)
		FROM hpJobTypeInfo 
		WHERE CONVERT(VARCHAR(8),dcJobTypeID) like ''+a.dcJobTypeId+'%'
		AND dcRegionID like ''+CONVERT(VARCHAR,@ProvinceID)+'%' 
	)
	ELSE(
		SELECT SUM(JobNum)
		FROM hpJobTypeInfo 
		WHERE CONVERT(VARCHAR(8),dcJobTypeID) IN (SELECT * FROM [fnSplit](a.dcJobTypeId,','))
		AND dcRegionID like ''+CONVERT(VARCHAR(8),@ProvinceID)+'%' 
	) 
	END
	FROM DcJobTypeHot A
	SELECT * FROM @t ORDER BY JobNum DESC
END










GO
/****** Object:  StoredProcedure [dbo].[procdcJobTypeMapByRegionIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.13
--创建人：Nick
--说明：获取各个站点下的热门职位类别
--#####################################################
CREATE PROCEDURE [dbo].[procdcJobTypeMapByRegionIDSelect]
(
	@RegionID INT
)
AS
BEGIN
	SELECT TOP 49 a.dcJobTypeId JobTypeID,a.JobNum JobNumber,b.CategoryId,c.parentID,c.grade,c.description,
	c.parentID2,c.parentID3 
	FROM hpjobtypeinfo a 
	LEFT JOIN dcJobTypeMap b ON b.JobTypeId=a.dcJobtypeid 
	LEFT JOIN dcJobType c ON c.id=a.dcJobTypeid 
	WHERE a.dcRegionID = @RegionID
	AND c.Grade = 3
	AND c.description IS NOT NULL
	ORDER BY JobNumber DESC
END


GO
/****** Object:  StoredProcedure [dbo].[procdcJobTypeMapSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.03
--创建人：Nick
--说明：获取职位地图的数据
--#####################################################
CREATE PROCEDURE [dbo].[procdcJobTypeMapSelect]
AS
BEGIN TRY
	SELECT a.id,a.description jobtypel0,c.description jobtypel1,b.* 
	FROM dcJobtypeCategory a,dcJobTypeMap b,dcjobtype c 
	WHERE a.id=b.categoryid and b.jobtypeid=c.id and len(b.jobtypeid)>2 
	ORDER BY a.id,b.orderby
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[procDcJobTypeSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.03
--创建人：Nick
--说明：获取职位类别
--#####################################################
CREATE PROCEDURE [dbo].[procDcJobTypeSelect]
AS
BEGIN TRY
	SELECT ID, ParentID, ParentID2, ParentId3 FROM dcjobtype WITH(NOLOCK) WHERE ID > 100 ORDER BY ID
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[procdcjobtypesimilarSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.31
--创建人：Nick
--说明：获取职位类别的匹配度
--#####################################################
CREATE PROCEDURE [dbo].[procdcjobtypesimilarSelect]
(
    @JobTypeID VARCHAR(20)
)
AS
BEGIN
    --SELECT * FROM dcjobtypesimilar WITH(NOLOCK) WHERE dcJobTypeId in (@JobTypeID) OR SimilarId IN (@JobTypeID)
	SELECT TOP 0 0 ID, 0 dcJobTypeId, 0 SimilarId, 0 Coefficient
END
GO
/****** Object:  StoredProcedure [dbo].[procdcJobTypeTemplateByJobTypeIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.04
--创建人：Nick
--说明：取职位模版和晋升机制
--#####################################################
CREATE PROCEDURE [dbo].[procdcJobTypeTemplateByJobTypeIDSelect]
(
	@dcJobTypeID INT
)
AS
BEGIN TRY
	SELECT TOP 1 * 
	FROM dcJobTypeTemplate WITH(NOLOCK) 
	WHERE dcJobTypeID = @dcJobTypeID
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[ProcDcJobTypeTop6Insert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ProcDcJobTypeTop6Insert]
AS
BEGIN
	SELECT Id, LEFT(ID, 2) Id2, Description, NewID() Seq, 999 RowNo
	INTO #t
	FROM dcJobType
	WHERE ID > 99
	AND Description NOT LIKE '其他%'

	UPDATE a 
	SET a.RowNo = b.RowNo
	FROM #t a, (SELECT ID, Row_Number() OVER(PARTITION BY ID2 ORDER BY Seq) RowNo FROM #t) b
	WHERE a.Id = b.Id

	DELETE FROM #t WHERE RowNo > 7

	TRUNCATE TABLE dcJobTypeTop6
	INSERT INTO dcJobTypeTop6 SELECT Id, Id2, Description, RowNo FROM #t ORDER BY id2, rowno
END









GO
/****** Object:  StoredProcedure [dbo].[procDcJobTypeTop6Select]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.03
--创建人：Nick
--说明：优化感兴趣的职位的搜索速度
--#####################################################
CREATE PROCEDURE [dbo].[procDcJobTypeTop6Select]

AS
BEGIN TRY
	SELECT * FROM dcJobTypeTop6 With(Nolock) ORDER BY ID2, RowNo
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[procdcLinkManagerBySubSiteIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.04
--创建人：Nick
--说明：根据subsiteid查询 dcLinkManager
--#####################################################
CREATE PROCEDURE [dbo].[procdcLinkManagerBySubSiteIDSelect]
(
	@SubSiteID INT
)
AS
BEGIN TRY
	SELECT a.ManagerUserId, b.Introduce
	FROM dcLinkManager a WItH(NOLOCK), ManagerUser b WITH(NOLOCK)
	WHERE a.ManagerUserId = b.Id AND a.SubSiteId = @SubSiteID
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[ProcDcMajorKeywordSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ProcDcMajorKeywordSelect]
(
    @Major NVARCHAR(20)
)
AS
SET NOCOUNT ON
BEGIN
    IF LEN(@Major) < 2
        SELECT TOP 10 MajorName, dcMajorId, b.Description Major
        FROM dcMajorKeyword a WITH(NOLOCK), dcMajor b WITH(NOLOCK)
        WHERE a.dcMajorId = b.ID AND (MajorName LIKE @Major + '%'
        OR PinYin LIKE @Major + '%'
        OR JianPin LIKE @Major + '%')
        ORDER BY MajorName
    ELSE
    BEGIN
        IF ASCII(LEFT(@Major, 1)) > 127
            SELECT TOP 10 MajorName, dcMajorId, b.Description Major
            FROM dcMajorKeyword a WITH(NOLOCK), dcMajor b WITH(NOLOCK)
            WHERE a.dcMajorId = b.ID AND CHARINDEX(@major, MajorName) > 0
            ORDER BY CHARINDEX(@major, MajorName), MajorName
        ELSE
            SELECT TOP 10 MajorName, dcMajorId, b.Description Major
            FROM dcMajorKeyword a WITH(NOLOCK), dcMajor b WITH(NOLOCK)
            WHERE a.dcMajorId = b.ID AND (CHARINDEX(@major, PinYin) > 0
            OR CHARINDEX(@major, JianPin) > 0)
            ORDER BY MajorName
    END
END
GO
/****** Object:  StoredProcedure [dbo].[procDcMapLineSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.03
--创建人：Nick
--说明：获取热门地标
--#####################################################
CREATE PROCEDURE [dbo].[procDcMapLineSelect]
AS
BEGIN TRY
	SELECT * FROM dcMapLine WITH(NOLOCK) ORDER BY dcRegionId,OrderNo
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[procdcMapPlaceSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.03
--创建人：Nick
--说明：dcMapPlace
--#####################################################
CREATE PROCEDURE [dbo].[procdcMapPlaceSelect]
AS
BEGIN TRY
	SELECT * FROM dcMapPlace WITH(NOLOCK) ORDER BY dcRegionID,OrderNo
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[procDcMapStationSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.03
--创建人：Nick
--说明：dcMapStation
--#####################################################
CREATE PROCEDURE [dbo].[procDcMapStationSelect]
AS
BEGIN TRY
	SELECT * FROM dcMapStation WITH(NOLOCK) ORDER BY dcMapLineId,OrderNo
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[procdcNewsTypeByCategorySelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.5
--创建人：NICK
--说明：获取资讯类别
--#####################################################
CREATE PROCEDURE [dbo].[procdcNewsTypeByCategorySelect]
(
	@Category INT
)
AS
BEGIN
	DECLARE @SQL VARCHAR(MAX)
	SET @SQL  = 'SELECT * FROM dcNewsType WITH(NOLOCK) '
	IF @Category > 0
	BEGIN
		SET @SQL  = @SQL + ' WHERE Category = '+CONVERT(VARCHAR(20),@Category)
	END
	SET @SQL  = @SQL + ' ORDER BY OrderNo'
	EXEC(@SQL)
END


GO
/****** Object:  StoredProcedure [dbo].[procdcNewsTypeByIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.5
--创建人：NICK
--说明：获取一行资讯类别
--#####################################################
CREATE PROCEDURE [dbo].[procdcNewsTypeByIDSelect]
(
	@ID INT
)
AS
BEGIN
	SELECT * FROM dcNewsType WITH(NOLOCK) WHERE id = @ID
END


GO
/****** Object:  StoredProcedure [dbo].[procDcProvinceByIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.10
--创建人：Nick
--说明：获取省份信息
--#####################################################
CREATE PROCEDURE [dbo].[procDcProvinceByIDSelect]
(
	@ID INT
)
AS
BEGIN
	SELECT * FROM dcProvince WITH(NOLOCK) WHERE ID=@ID
END


GO
/****** Object:  StoredProcedure [dbo].[procDcProvinceByPinyinSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.10
--创建人：Nick
--说明：获取省份信息
--#####################################################
CREATE PROCEDURE [dbo].[procDcProvinceByPinyinSelect]
AS
BEGIN TRY
	SELECT Id, ProvinceName, WebSiteName, dbo.ToPinYin(ProvinceName) PinYin,  
	ProvinceDomain 
	FROM dcProvince WITH(NOLOCK) 
	ORDER BY ID
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[ProcDcProvinceSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.3
--创建人：John
--说明：获取省份信息
--#####################################################
CREATE PROCEDURE [dbo].[ProcDcProvinceSelect]
AS
BEGIN
	SELECT * FROM dcProvince
END


GO
/****** Object:  StoredProcedure [dbo].[procDcRegionAllSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.03
--创建人：Nick
--说明：全部地区
--#####################################################
CREATE PROCEDURE [dbo].[procDcRegionAllSelect]
AS
BEGIN TRY
	SELECT *
	FROM dcRegion WITH(NOLOCK) 
	ORDER BY Id
END TRY
BEGIN CATCH
	RETURN 0
END CATCH
GO
/****** Object:  StoredProcedure [dbo].[procdcRegionByGradeParentIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.11
--创建人：NICK
--说明：根据provincieid得到dcregion
--#####################################################
CREATE PROCEDURE [dbo].[procdcRegionByGradeParentIDSelect]
(
	@ParentID INT,
	@Grade INT
)
AS
BEGIN
	IF @Grade = 1
	BEGIN
		SELECT TOP  100 * 
		FROM maindb..dcregion  
		WHERE  grade = @Grade
		ORDER BY id
	END
	ELSE 
	BEGIN
		SELECT TOP  100 * 
		FROM maindb..dcregion  
		WHERE  grade = @Grade
		AND ParentID = @ParentID
		ORDER BY id
	END
END


GO
/****** Object:  StoredProcedure [dbo].[procdcRegionByIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.03
--创建人：Nick
--说明：根据ID获取dcRegion
--#####################################################
CREATE PROCEDURE [dbo].[procdcRegionByIDSelect]
(
	@ID INT
)
AS
SET NOCOUNT ON
BEGIN
	--SELECT * FROM dcRegion WITH(NOLOCK) WHERE ID = @ID
	SELECT ID, Abbr Description, Abbr, TqPinyin, PinYin FROM dcRegion WITH(NOLOCK) WHERE ID = @ID
END
GO
/****** Object:  StoredProcedure [dbo].[procdcRegionByParentIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.3
--创建人：NICK
--说明：根据provincieid得到dcregion
--#####################################################
CREATE PROCEDURE [dbo].[procdcRegionByParentIDSelect]
(
	@ProvinceID INT
)
AS
BEGIN
	SELECT id,Description 
	FROM dcregion WHERE parentid=@ProvinceID 
	OR id=@ProvinceID 
	ORDER BY id
END


GO
/****** Object:  StoredProcedure [dbo].[procdcRegionByPinYinSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.03
--创建人：Nick
--说明：根据ProvinceID和pinyin获取dcRegion
--#####################################################
CREATE PROCEDURE [dbo].[procdcRegionByPinYinSelect]
(
	@ProvinceID INT,
	@PinYin1 VARCHAR(50),
	@PinYin2 VARCHAR(50)
)
AS
BEGIN TRY
	IF @PinYin2 = ''
	BEGIN
		SELECT * FROM dcRegion WITH(NOLOCK) WHERE Pinyin=@Pinyin1 AND LEN(ID)=4 AND LEFT(ID,2)=@ProvinceID
	END
	ELSE
	BEGIN
		SELECT a.*,b.Abbr UpperName 
		FROM dcRegion a,dcRegion b WITH(NOLOCK) 
		WHERE a.ParentID=b.ID 
		AND b.Pinyin=@Pinyin1 
		AND a.Pinyin=@Pinyin2 
		AND LEN(a.ID)=6 
		AND LEFT(a.ID,2)=@ProvinceID
	END
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[procdcRegionByProvinceIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.03
--创建人：Nick
--说明：根据ProvinceID获取dcRegion
--#####################################################
CREATE PROCEDURE [dbo].[procdcRegionByProvinceIDSelect]
(
	@ProvinceID INT
)
AS
BEGIN TRY
	SELECT * FROM dcRegion WITH(NOLOCK)  WHERE LEFT(ID,2)=@ProvinceID AND Pinyin IS NOT NULL
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[procdcRegionByRegionNameSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.31
--创建人：Nick
--说明：由地区名称获取地区ID
--#####################################################
CREATE PROCEDURE [dbo].[procdcRegionByRegionNameSelect]
(
	@RegionName VARCHAR(20)
)
AS
BEGIN TRY
	SELECT * FROM dcRegion WITH(NOLOCK) WHERE Description LIKE '%'+@RegionName+'%'
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[procDcRegionSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.03
--创建人：Nick
--说明：获取地区 
--#####################################################
CREATE PROCEDURE [dbo].[procDcRegionSelect]
AS
BEGIN TRY
	SELECT ID, Description, DescriptionEng, OrderNo,Lng,Lat FROM dcRegion WITH(NOLOCK)
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[ProcDcRegionTDKSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ProcDcRegionTDKSelect]
AS
BEGIN
	SELECT * FROM dcRegionTDK
END
GO
/****** Object:  StoredProcedure [dbo].[procDcRunParameterByNameSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.03
--创建人：Nick
--说明：获取不显示职位广告的企业id。 
--#####################################################
CREATE PROCEDURE [dbo].[procDcRunParameterByNameSelect]
AS
BEGIN TRY
	SELECT Value FROM dcRunParameter WITH(NOLOCK) WHERE System = 1 AND Name = 'do not show Job Ads'
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[procDcRunParameterSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.03
--创建人：Nick
--说明：获取iis运行参数，搜索职位和搜索简历使用数据库的信息。放在这里，便于数据库故障时及时调整 
--#####################################################
CREATE PROCEDURE [dbo].[procDcRunParameterSelect]
AS
insert proclog select 'procDcRunParameterSelect','',  getdate()
BEGIN
	SELECT Name, Value 
	FROM dcRunParameter WITH(NOLOCK) 
	--WHERE System = 1 
	--AND (Name LIKE 'JobSearchDb%' OR Name LIKE 'CvSearchDb%' OR Name LIKE 'ueolog%')
END
GO
/****** Object:  StoredProcedure [dbo].[procdcSubSiteByIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.10
--创建人：NICK
--说明：根据省份编号获取 subsite信息
--#####################################################
CREATE PROCEDURE [dbo].[procdcSubSiteByIDSelect]
(
	@ID INT
)
AS
BEGIN
	SELECT * FROM dcSubSite WHERE id=@ID
END


GO
/****** Object:  StoredProcedure [dbo].[ProcDcSubSiteByPinYinSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ProcDcSubSiteByPinYinSelect]  
(
   @Pinyin NVARCHAR(20),
   @dcProvinceID INT
)
AS
BEGIN
	SELECT TOP 1 SubSiteUrl
	FROM dcSubSite WITH(NOLOCK)
	WHERE Pinyin = @Pinyin
	AND ProvinceId = @dcProvinceID
	ORDER BY IsMainSite
	/*
	SELECT TOP 1 a.SubSiteUrl
	FROM dcSubSite a, dcRegion b
	WHERE A.ID = B.ID
	AND b.Pinyin = @Pinyin
	AND a.ProvinceId = @dcProvinceID
	AND b.Id < 9999
	ORDER BY a.IsMainSite
	*/
END

GO
/****** Object:  StoredProcedure [dbo].[procDcSubSiteByProvinceSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.10
--创建人：John
--说明：获取所有省份相应的站点
--#####################################################
CREATE PROCEDURE [dbo].[procDcSubSiteByProvinceSelect]
AS
BEGIN
	SELECT id, REPLACE(SubSiteUrl, 'www.', '') Domain,SubSiteName FROM dcSubSite WITH(NOLOCK) WHERE ismainsite = 1 AND LEN(ID)=2
END


GO
/****** Object:  StoredProcedure [dbo].[procDcSubSiteBySecondSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.5.06
--创建人： sean
--说明：获取网站PinYin信息
--#####################################################
CREATE  PROCEDURE [dbo].[procDcSubSiteBySecondSelect]
AS
BEGIN
	SELECT Id, SecondSite SubSiteUrl, PinYin
	FROM dcSubSite a WITH(NOLOCK) 
	WHERE ID > 99
	AND ProvinceId IN(10, 32, 13, 20, 21, 22, 30, 31, 33, 34, 35, 36, 40, 42, 62, 63, 70, 71, 83, 84, 12, 14, 41, 61, 72, 80)
	ORDER BY ID
END
GO
/****** Object:  StoredProcedure [dbo].[procDcSubSiteBySiteCitySelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.10
--创建人：Nick
--说明：根据城市名称获取省份编号
--#####################################################
CREATE PROCEDURE [dbo].[procDcSubSiteBySiteCitySelect]
(
	@City VARCHAR(50)
)
AS
BEGIN
	SELECT provinceID FROM dcsubsite WITH(NOLOCK) WHere subsitecity like '%'+@City+'%'
END


GO
/****** Object:  StoredProcedure [dbo].[procDcSubSiteSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.03
--创建人：Nick
--说明：获取所有网站信息
--#####################################################
CREATE PROCEDURE [dbo].[procDcSubSiteSelect]
AS
BEGIN
	SELECT * FROM dcSubSite a WITH(NOLOCK) ORDER BY ProvinceId, ID
END
GO
/****** Object:  StoredProcedure [dbo].[procDcSubSiteUrlByRegionNameSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.10
--创建人：John
--说明：根据地区名获取网站地址
--#####################################################
CREATE PROCEDURE [dbo].[procDcSubSiteUrlByRegionNameSelect]
(
	@RegionName NVARCHAR(12)
)
AS
BEGIN
	SELECT SubSiteUrl FROM dcSubSite WHERE SubSiteCity LIKE @RegionName ORDER BY ismainsite DESC ,id
END


GO
/****** Object:  StoredProcedure [dbo].[procDcSystemdataByIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.10
--创建人：Nick
--说明：
--#####################################################
CREATE PROCEDURE [dbo].[procDcSystemdataByIDSelect]
(
	@ID INT
)
AS
BEGIN TRY
	SELECT CONVERT(INT, Value) AS cnt FROM dcsystemdata WITH(NOLOCK) WHERE Id = @ID
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[ProcdcVipStandardByPriceCvSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ProcdcVipStandardByPriceCvSelect]
(
	@dcProvinceID AS INT
)
AS
BEGIN
	SELECT PriceCv FROM dcVipStandard WITH(NOLOCK)
	WHERE dcProvinceID = @dcProvinceID
END














GO
/****** Object:  StoredProcedure [dbo].[ProcDcWxTokenByJsApi_TicketUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.4
--创建人：John
--说明：根据id更新微信记录
--#####################################################
CREATE PROCEDURE [dbo].[ProcDcWxTokenByJsApi_TicketUpdate]
(
	@JsApi_Ticket VARCHAR(200),
	@ProvinceId TINYINT
)
AS
BEGIN
	UPDATE dcWxToken SET JsApi_Ticket = @JsApi_Ticket,
		JsApi_Ticket_adddate = GETDATE()
	WHERE dcProvinceId = @ProvinceId
END

GO
/****** Object:  StoredProcedure [dbo].[ProcDcWxTokenByProvinceIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.4
--创建人：John
--说明：根据id获取微信生成记录
--#####################################################
CREATE PROCEDURE [dbo].[ProcDcWxTokenByProvinceIDSelect]
(
	@ProvinceId TINYINT
)
AS
BEGIN
	SELECT TOP 1 * FROM dcWxToken WHERE adddate > DATEADD(MINUTE,-60,GETDATE()) AND dcProvinceId = @ProvinceId
END


GO
/****** Object:  StoredProcedure [dbo].[ProcDcWxTokenUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.4
--创建人：John
--说明：根据id更新微信记录
--#####################################################
CREATE PROCEDURE [dbo].[ProcDcWxTokenUpdate]
(
	@token VARCHAR(200),
	@ProvinceId TINYINT
)
AS
BEGIN
	UPDATE dcWxToken SET Token = @token,adddate = GETDATE() WHERE dcProvinceId = @ProvinceId
END


GO
/****** Object:  StoredProcedure [dbo].[ProcDeletedJobByRegionIdSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2014.10.28
--创建人：John
--说明：获取一天之内删除的职位
--@regionId 地区编号
--#####################################################
CREATE PROCEDURE [dbo].[ProcDeletedJobByRegionIdSelect]
(
	@regionId VARCHAR(6)
)
AS
BEGIN TRY
	SELECT a.JobId 
	FROM JobDeleted a, Job b 
	WHERE DATEADD(DAY,1,a.DeleteDate) > GETDATE() 
	  AND a.JobId = b.Id 
	  AND b.dcRegionID = @regionId
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[procDicSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.03
--创建人：Nick
--说明：获取字典信息
--#####################################################
CREATE PROCEDURE [dbo].[procDicSelect]
(
	@TableName VARCHAR(20),
	@queryCondition VARCHAR(200)
)
AS
SET NOCOUNT ON
BEGIN
	DECLARE @SQL VARCHAR(500)
	SET @SQL = 'Select ID, Description, Replace(DescriptionEng, '''', ''''''\'''''''''') FROM '+ @TableName + ' WITH(NOLOCK) ORDER BY ID'
	IF @TableName = 'dcIndustry'
	BEGIN
		SET @SQL = 'SELECT ID, Description, Replace(DescriptionEng, '''', ''''''\'''''''''') FROM ' + @TableName + ' WITH(NOLOCK) ORDER BY OrderNo'
	END
	IF @TableName = 'dcMajor'
	BEGIN
		SET @SQL = 'SELECT ID, Description, Replace(DescriptionEng, '''', ''''''\'''''''''') FROM ' + @TableName + ' WITH(NOLOCK) ORDER BY OrderNo, Id'
	END
	IF @TableName = 'dcSalary' 
	BEGIN
		SET @SQL = 'SELECT ID,Description,Replace(DescriptionEng, '''', ''''''\''''''''''), DescriptionCp FROM dcSalary' + ' WITH(NOLOCK) WHERE ID>1 ORDER BY OrderNo'	END
	IF @queryCondition <> ''
	BEGIN
		SET @SQL = 'SELECT DetailID, Description, Replace(DescriptionEng, '''', ''''''\'''''''''') FROM ' + @TableName + ' WITH(NOLOCK) WHERE '+ @queryCondition +' ORDER BY OrderNo'
	END
--	IF @queryCondition = 'major'
--	BEGIN
--		SET @SQL = 'SELECT ID, Description, Replace(DescriptionEng, '''', ''''''\'''''''''') FROM dcMajor WITH(NOLOCK)  WHERE Id NOT IN(1106, 1713) ORDER BY MajorCategoryId, OrderNo'
--	END
	EXEC (@SQL)
END
GO
/****** Object:  StoredProcedure [dbo].[ProcDouBanEmailUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.4
--创建人：John
--说明：更新豆瓣 邮件信息
--#####################################################
CREATE PROCEDURE [dbo].[ProcDouBanEmailUpdate]
(
	@PaMainID INT,
	@DouBanID INT
)
AS
BEGIN
	UPDATE doubanmail SET isregister = 1, pamainid = @PaMainID WHERE id = @DouBanID
END


GO
/****** Object:  StoredProcedure [dbo].[procDwnClass1ByDocIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.5
--创建人：NICK
--说明：根据docid获取doc所在的大类名称
--#####################################################
CREATE PROCEDURE [dbo].[procDwnClass1ByDocIDSelect]
(
	@ID INT
)
AS
BEGIN
	SELECT a.id,b.title,b.id as typeid 
	FROM maindb..dwndoc a WITH(NOLOCK),maindb..dwnclass1 b WITH(NOLOCK),maindb..dwnclass2 c WITH(NOLOCK) 
	WHERE a.classid=c.id 
	AND c.class1id=b.id 
	AND a.id=@ID
END


GO
/****** Object:  StoredProcedure [dbo].[procDwnClass1ByIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.5
--创建人：NICK
--说明：获取个人文档下载大类名稱
--#####################################################
CREATE PROCEDURE [dbo].[procDwnClass1ByIDSelect]
(
	@ID INT
)
AS
BEGIN
	SELECT * FROM dwnclass1  WITH(NOLOCK) WHERE id=@ID
END


GO
/****** Object:  StoredProcedure [dbo].[procDwnClass2ByIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.5
--创建人：NICK
--说明：获取文档下载二级类别
--#####################################################
CREATE PROCEDURE [dbo].[procDwnClass2ByIDSelect]
(
	@ID INT
)
AS
BEGIN
	SELECT TOP 18 * FROM dwnclass2  WITH(NOLOCK) WHERE class1id=@ID ORDER BY  power
END


GO
/****** Object:  StoredProcedure [dbo].[procDwnDoc44ByCompanySelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.5
--创建人：NICK
--说明：文档下载 企业
--#####################################################
CREATE PROCEDURE [dbo].[procDwnDoc44ByCompanySelect]
AS
BEGIN
	SELECT TOP 44 a.id,a.Name ,classid
	FROM dwndoc a WITH(NOLOCK)
	WHERE danwei=1
	ORDER BY updatedate DESC
END


GO
/****** Object:  StoredProcedure [dbo].[procDwnDoc44ByPersonSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.5
--创建人：NICK
--说明：文档下载 个人
--#####################################################
CREATE PROCEDURE [dbo].[procDwnDoc44ByPersonSelect]
AS
BEGIN
	SELECT TOP 44 a.id,a.Name ,classid
	FROM dwndoc a WITH(NOLOCK)
	WHERE geren=1
	ORDER BY updatedate DESC
END


GO
/****** Object:  StoredProcedure [dbo].[procDwnDoc51rcByIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.10
--创建人：NICK
--说明：随机得到一定数目的个人文档
--alen 2018-3-26
--#####################################################
CREATE PROCEDURE [dbo].[procDwnDoc51rcByIDSelect]
(
	@Second INT,
	@Number INT
)
AS
BEGIN
	DECLARE @SQL VARCHAR(MAX)
	SET @SQL = '
	SELECT TOP ' + CONVERT(VARCHAR(10), @Number)+' ID, Name, ClassId, Type 
	FROM Searchdb..DwnDoc51rc WITH(NOLOCK) 
	ORDER BY NEWID()'
	EXEC(@SQL)
END

GO
/****** Object:  StoredProcedure [dbo].[ProcDwnDocByClassIdSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ProcDwnDocByClassIdSelect]
(
	@ClassId INT,
	@DocId INT	
)
AS
BEGIN
	IF ISNULL(@DocId, 0) = 0
		SELECT Id, FileType, LEN(HtmlContent) HtmlContent, [Name], [Description]
		FROM DwnDoc WITH(NOLOCK)
		WHERE Classid = @ClassId
		ORDER BY Id DESC
	ELSE
		SELECT Id, FileType, LEN(HtmlContent) HtmlContent, [Name], [Description]
		FROM DwnDoc WITH(NOLOCK)
		WHERE Classid = @ClassId
		ORDER BY CASE Id WHEN @DocID THEN 1 ELSE 10 END, Id DESC
END


GO
/****** Object:  StoredProcedure [dbo].[procDwnDocByCompanySelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.03
--创建人：Nick
--说明：获取企业doc文档下载排行（top10）
--#####################################################
CREATE PROCEDURE [dbo].[procDwnDocByCompanySelect]

AS
BEGIN TRY
	SELECT TOP 10 id,name,dwnnum 
	FROM maindb..dwndoc 
	WHERE danwei=1 
	ORDER BY dwnnum DESC
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[procDwnDocByIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.5
--创建人：NICK
--说明：获取doc文档内容
--#####################################################
CREATE PROCEDURE [dbo].[procDwnDocByIDSelect]
(
	@ID INT
)
AS
BEGIN
	SELECT a.*, b.dir dir1, c.dir dir2 
	FROM Maindb..DwnDoc a, DwnClass1 b, DwnClass2 c
	WHERE a.ID = @ID
	AND a.ClassID = c.ID 
	AND c.Class1ID = b.ID
END


GO
/****** Object:  StoredProcedure [dbo].[procDwnDocByIDUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.5
--创建人：NICK
--说明：文档增加点击数
--#####################################################
CREATE PROCEDURE [dbo].[procDwnDocByIDUpdate]
(
	@ID INT
)
AS
BEGIN
	UPDATE dwndoc SET dwnnum=dwnnum+1 WHERE id=@ID
	RETURN 1
END


GO
/****** Object:  StoredProcedure [dbo].[procDwnDocByPersonSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.03
--创建人：Nick
--说明：获取个人doc文档下载排行（top10）
--#####################################################
CREATE PROCEDURE [dbo].[procDwnDocByPersonSelect]

AS
BEGIN TRY
	SELECT TOP 10 id,name,dwnnum 
	FROM maindb..dwndoc 
	WHERE geren=1 
	ORDER BY dwnnum DESC
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[ProcDwnDocByTop5Select]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--修改harry 2017-10-10
--may要求按照添加时间排序
CREATE PROCEDURE [dbo].[ProcDwnDocByTop5Select]
AS
SET NOCOUNT ON
BEGIN
	SELECT TOP 8 a.ID, a.Name, a.ClassID Class2ID, b.Title, c.ID Class1ID 
	FROM DwnDoc a WITH(NOLOCK),
		DwnClass2 b WITH(NOLOCK),
		DwnClass1 c WITH(NOLOCK)
	WHERE a.Geren = 1
	AND a.ClassID = b.ID
	AND b.Class1ID = c.ID
	ORDER BY  a.adddate desc
END
SET NOCOUNT OFF
GO
/****** Object:  StoredProcedure [dbo].[procDwnDocDetailByIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.5
--创建人：NICK
--说明：获取文档内容
--#####################################################
CREATE PROCEDURE [dbo].[procDwnDocDetailByIDSelect]
(
	@ID INT
)
AS
BEGIN
	SELECT a.id,a.name,a.lgg,a.adddate,a.filetype,a.description,a.authtype,a.dwnnum,b.dir dir1,c.dir dir2,a.filename 
	FROM dwndoc a WITH(NOLOCK),dwnclass1 b WITH(NOLOCK),dwnclass2 c WITH(NOLOCK) 
	WHERE a.classid=c.id 
	AND c.class1id=b.id 
	AND a.id=@ID
END


GO
/****** Object:  StoredProcedure [dbo].[ProcDwnDocSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.28
--创建人：Nick
--说明：获取文档下载数据 
--#####################################################
CREATE PROCEDURE [dbo].[ProcDwnDocSelect]
AS
BEGIN TRY
	SELECT TOP 14 a.ID,a.Name,ClassID
	FROM DwnDoc a WITH(NOLOCK)
	WHERE Geren = 1
	ORDER BY UpdateDate DESC 
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[procDwnDocUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.31
--创建人：Nick
--说明：修改下载文档
--#####################################################
CREATE PROCEDURE [dbo].[procDwnDocUpdate]
(
	@ID INT
)
AS
BEGIN TRY
	UPDATE dwndoc SET dwnnum=dwnnum+1 WHERE id = @ID
	RETURN 1
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[ProcEmailPrevSendInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.28
--创建人：John
--说明：即时邮件发送
--#####################################################
CREATE PROCEDURE [dbo].[ProcEmailPrevSendInsert]
(
	@cpMainID INT, 
	@paMainID INT, 
	@emailNo TINYINT, 
	@emailTitle NVARCHAR(50), 
	@jsonData NVARCHAR(MAX), 
	@email VARCHAR(100), 
	@subSiteID SMALLINT
)
AS
SET NOCOUNT ON
BEGIN
	INSERT INTO msEmailPrevSend(cpMainId, paMainId, EmailNo, EmailTitle, JsonData, Email, dcSubsiteId, IsSend)
	VALUES(@cpMainID, @paMainID, @emailNo, @emailTitle, @jsonData, @email, @subSiteID, 0) 
END
GO
/****** Object:  StoredProcedure [dbo].[procexInterviewByPamainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.10
--创建人：Nick
--说明：面试通知
--#####################################################
CREATE PROCEDURE [dbo].[procexInterviewByPamainIDSelect]
(
	@PamainID INT
)
AS
BEGIN
	SELECT TOP 5 a.*, b.Name as JobName, b.caMainID, b.dcRegionID, c.Name as cpName, c.ID as cpID,
	c.HasLicence, c.IsAgent, b.IssueDate, b.IssueEND, b.IsDelete, d.Name cvName
	FROM exInterview a WITH(NOLOCK)
	INNER JOIN Job b WITH(NOLOCK) On b.ID=a.JobID
	INNER JOIN cpMain c WITH(NOLOCK) ON b.cpMainID=c.ID
	INNER JOIN cvMain d WITH(NOLOCK) ON a.cvMainID = d.ID
	WHERE PersonDeleted=0 AND d.paMainID=@PamainID 
	ORDER BY a.adddate DESC
END


GO
/****** Object:  StoredProcedure [dbo].[procExJobApplyByCvMainIDCpMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.03
--创建人：Nick
--说明：
--#####################################################
CREATE PROCEDURE [dbo].[procExJobApplyByCvMainIDCpMainIDSelect]
(
	@IsManager INT,
	@CvMainID INT,
	@ID INT
)
AS
BEGIN TRY
	IF @IsManager = 1
	BEGIN
		SELECT TOP 1 JobID 
		FROM exJobApply a,Job b 
		WHERE a.JobID=b.ID 
		AND a.cvMainID=@CvMainID 
		AND b.cpMainID=@ID
		ORDER BY a.AddDate DESC
	END
	ELSE 
	BEGIN
		SELECT TOP 1 JobID 
		FROM exJobApply a,Job b 
		WHERE a.JobID=b.ID 
		AND a.cvMainID=@CvMainID 
		AND b.caMainID=@ID
		ORDER BY a.AddDate DESC
	END
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[procExJobApplyByCvMainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.03
--创建人：Nick
--说明：
--#####################################################
CREATE PROCEDURE [dbo].[procExJobApplyByCvMainIDSelect]
(
	@IsManager INT,
	@CvMainID INT,
	@ID INT
)
AS
BEGIN TRY
	IF @IsManager = 1
	BEGIN
		SELECT TOP 1 JobID 
		FROM exJobApply a,Job b 
		WHERE a.JobID=b.ID 
		AND a.cvMainID=@CvMainID 
		AND b.cpMainID=@ID
		ORDER BY a.AddDate DESC
	END
	ELSE 
	BEGIN
		SELECT TOP 1 JobID 
		FROM exJobApply a,Job b 
		WHERE a.JobID=b.ID 
		AND a.cvMainID=@CvMainID 
		AND b.caMainID=@ID
		ORDER BY a.AddDate DESC
	END
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[procexJobApplyByPamainIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.10
--创建人：Nick
--说明：获取职位申请信息
--#####################################################
CREATE PROCEDURE [dbo].[procexJobApplyByPamainIDSelect]
(
	@PamainID INT
)
AS
BEGIN
	SELECT TOP 5 a.ID, a.JobID, a.cvMainID, a.ApplyMessage, a.AddDate, a.CompanyDeleted, a.CompanyDeleteDate, 
	a.PersonDeleted, a.Reply, a.ReplyDate, b.Name as JobName, b.caMainID, b.dcRegionID, c.Name as cpName, c.ID as cpID,
	c.HasLicence, c.IsAgent, b.IssueDate, b.IssueEND, b.IsDelete, d.Name cvName
	FROM exJobApply a WITH(NOLOCK)
	INNER JOIN Job b WITH(NOLOCK) On b.ID=a.JobID 
	INNER JOIN cpMain c WITH(NOLOCK) ON b.cpMainID=c.ID
	INNER JOIN cvMain d WITH(NOLOCK) ON a.cvMainID = d.ID
	WHERE PersonDeleted=0 AND d.paMainID=@PamainID 
	ORDER BY a.AddDate DESC
END


GO
/****** Object:  StoredProcedure [dbo].[ProcFamousCompanyGroupSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.29
--创建人：Nick
--说明：获取名企导航Group
--#####################################################
CREATE PROCEDURE [dbo].[ProcFamousCompanyGroupSelect]
(
	@ProvinceID INT
)
AS
BEGIN TRY
	SELECT a.*,STUFF((SELECT ','+CONVERT(VARCHAR(10),dcRegionID) 
	FROM marketdb..CampusGroupRegion WITH(NOLOCK) 
	WHERE GroupID=a.id for xml path('')),1,1,'') RegionIDs FROM MarketDB..CampusGroup a WITH(NOLOCK)
	WHERE  EXISTS(
		SELECT TOP 1 'x' 
		FROM MarketDB..CampusGroupRegion WITH(NOLOCK) 
		WHERE  GroupID=a.ID 
		AND dcRegionID LIKE ''+CONVERT(VARCHAR(4),@ProvinceID)+'%'
	) 
	ORDER BY a.id 
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[ProcFamousCompanySelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.29
--创建人：Nick
--说明：获取名企导航
--#####################################################
CREATE PROCEDURE [dbo].[ProcFamousCompanySelect]
(
	@ProvinceID INT,
	@RegionIDs VARCHAR(100)
)
AS
BEGIN TRY
	SELECT a.* 
	FROM MarketDB..CampusCompany a WITH(NOLOCK) 
	WHERE 
	(
		dcRegionID  = @ProvinceID OR dcRegionID IN (SELECT  * FROM dbo.fnSplit(@RegionIDs,','))
   )  
   AND (
		EXISTS(
			SELECT TOP 1 'x' FROM MarketDB..CampusBrochure x 
            WITH(NOLOCK),MarketDB..CampusBrochureSite y WITH(NOLOCK)  
            WHERE x.ID = y.CampusBrochure 
            AND x.CompanyID=a.ID 
            AND x.EndDate>getdate() 
            AND y.dcSubSiteId = @ProvinceID
         ) 
         OR EXISTS(
			SELECT TOP 1 'x' 
			FROM MarketDB..CampusPresentation m WITH(NOLOCK),MarketDB..CampusSchool n WITH(NOLOCK)  
			WHERE m.SchoolID = n.ID 
			AND m.endtime>getdate()  
			AND m.CompanyID=a.ID  
			AND n.dcRegionID LIKE ''+CONVERT(VARCHAR(4),@ProvinceID)+'%'
			) 
	) ORDER BY AddDate DESC 
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[procFeedback_NoregInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.04
--创建人：Nick
--说明：插入 feedback_noreg
--#####################################################
CREATE PROCEDURE [dbo].[procFeedback_NoregInsert]
(
	@Content VARCHAR(400),
	@Name VARCHAR(50),
	@IP VARCHAR(20),
	@Tel VARCHAR(20),
	@Email VARCHAR(50),
	@SiteID INT
)
AS
BEGIN TRY
	INSERT INTO feedback_noreg (content,name,ip,telephone,email,province_id) 
	SELECT dbo.SafeSQL(@Content), dbo.SafeSQL(@Name), @IP, dbo.SafeSQL(@Tel), dbo.SafeSQL(@Email), @SiteID 

	RETURN 1
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[procFixCompanyByRecruitmentSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[procFixCompanyByRecruitmentSelect] 
(
	@SubSiteID VARCHAR(4)
)
AS
BEGIN
	CREATE TABLE #Tmp --创建临时表#Tmp
	(
		CpMainId INT,
		SecondId VARCHAR(50),
		Name NVARCHAR(50),
		DcCompanySizeId SMALLINT,
		Industry VARCHAR(100),
		Logo VARCHAR(200)
	)
	INSERT INTO #Tmp (CpMainId,SecondId,Name,DcCompanySizeId) 
	SELECT DISTINCT TOP 8 cp.Id, fp.CpMainId,fp.Name,cp.DcCompanySizeId
	FROM FpFixPosition fp LEFT JOIN cpMain cp ON fp.cpmainid = cp.SecondId
	WHERE LEFT(fp.dcSubSiteID,LEN(@SubSiteID)) = @SubSiteID
	ORDER BY DcCompanySizeID DESC

	DECLARE @Cnt INT
	SELECT @Cnt = COUNT(1) FROM #Tmp
		
	IF @Cnt < 3 AND LEN(@SubSiteID) > 2
		INSERT INTO #Tmp (CpMainId,SecondId,Name,DcCompanySizeId) 
		SELECT DISTINCT TOP 8 cp.Id, fp.CpMainId,fp.Name,cp.DcCompanySizeId 
		FROM FpFixPosition fp LEFT JOIN cpMain cp ON fp.cpmainid = cp.SecondId
		WHERE fp.DcProvinceId = LEFT(@SubSiteID,2)
		ORDER BY DcCompanySizeID DESC

	UPDATE #Tmp SET Industry = dbo.GetCpIndustry(#Tmp.CpMainId)
	UPDATE #Tmp SET Logo = dbo.GetCpLogo(#Tmp.CpMainId)
	SELECT TOP 8 * FROM #Tmp
END
GO
/****** Object:  StoredProcedure [dbo].[procFpcommonSearchByProvinceIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.03
--创建人：Nick
--说明：获取地区 
--#####################################################
CREATE PROCEDURE [dbo].[procFpcommonSearchByProvinceIDSelect]
(
	@ProvinceID INT
)
AS
BEGIN TRY
	SELECT SearchText, SearchValue, SearchType 
	FROM fpcommonsearch WITH(NOLOCK)
	WHERE dcProvinceID = @ProvinceID 
	ORDER BY SearchType, Sequence
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[ProcFpFixPositionReBuild]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ProcFpFixPositionReBuild]
AS
SET NOCOUNT ON;
IF NOT EXISTS(SELECT 'x' FROM caOrder WITH(NOLOCK)
	WHERE OrderType=7 AND BeginDate < GETDATE()
	AND EndDate > GETDATE()
	and (BeginDate > DaTEADD(MINUTE, -3, GETDATE())
		OR OpenDate > DaTEADD(MINUTE, -3, GETDATE())
		)
	)
BEGIN
	IF DATEPART(MINUTE, GETDATE()) % 10 > 20
		RETURN
END
BEGIN TRAN	
	TRUNCATE TABLE SearchDb..FpFixPosition

	INSERT FpFixPosition(RealCpMainID, cpMainID, Name, Paid, OpenDate, dcProvinceId, dcRegionID, dcSubsiteID, caOrderId, dcIndustryId)
	SELECT a.ID CompanyId, a.SecondId SecondCompanyId, a.Name, b.Paid, b.OpenDate, a.dcProvinceID, a.dcRegionID, a.dcSubsiteID, b.Id, c.dcIndustryId
	FROM cpMain a WITH(NOLOCK INDEX(IX_cpMain_HomepageFix))
	INNER JOIN caOrder b WITH(NOLOCK) ON b.cpMainID = a.id
	INNER JOIN cpIndustry c WITH(NOLOCK) ON a.id = c.cpMainId
	WHERE b.BeginDate < GETDATE()
	AND b.EndDate > GETDATE()
	AND b.OpenDate IS NOT NULL
	AND b.OrderType = 7
	AND a.JobNumber>0 
	AND a.Valid = 1
	AND b.IsDeleted = 0   --是否可被搜索

	--UPDATE a SET a.Name = b.ShortName
	--FROM FpFixPosition a, cpMain b 
	--WHERE a.RealCpMainID = b.Id
	--AND b.ShortName > ''
	UPDATE FpFixPosition SET Name = '日照天宁集团' WHERE RealCpMAinId = 10174411

	UPDATE FpFixPosition SET JobID = dbo.GetJobSecondIds(RealCpMainID),
		JobName = dbo.GetJobNames(RealCpMainID)

	UPDATE FpFixPosition SET ThreeIds = dbo.TruncJobIDs(JobID)

	UPDATE FpFixPosition
	SET AddDate = 
		(SELECT MAX(AddDate) FROM Job WITH(NOLOCK)
		WHERE Job.SecondID IN (SELECT REPLACE(ID, '_', '') FROM dbo.Get3JobSecondIds(FpFixPosition.ThreeIds))
		)
	UPDATE FpFixPosition SET NoFollow = '' 
	--WHERE CpMainId IN(SELECT PageId FROM MarketDb..PageBaiduInclude WITH(NOLOCK) WHERE PageType = 1 AND InCludeDate IS NULL)

	UPDATE FpFixPosition
	SET NewXId = 
		(SELECT TOP 1 SecondID FROM Job WITH(NOLOCK)
		WHERE Job.SecondID IN (SELECT ID FROM dbo.Get3JobSecondIds(FpFixPosition.ThreeIds))
		AND Job.AddDate = FpFixPosition.AddDate
		)
	--UPDATE FpFixPosition SET dcIndustryId =(SELECT TOP 1 dcIndustryID FROM cpIndustry WITH(NOLOCK) WHERE cpIndustry.cpMainID = FpFixPosition.RealCpMainID)

	UPDATE FpFixPosition SET IndustryCategory=(SELECT CategoryId FROM dcIndustryCategory WITH(NOLOCK) WHERE dcIndustryCategory.dcIndustryId = FpFixPosition.dcIndustryId)
	DELETE FpFixPosition WHERE Id IN(SELECT MAX(ID) ID FROM FpFixPosition GROUP BY cpMainId, INDustryCategory HAVING COUNT(*) > 1)
	DELETE FpFixPosition WHERE Id IN(SELECT MAX(ID) ID FROM FpFixPosition GROUP BY cpMainId, INDustryCategory HAVING COUNT(*) > 1)
	DELETE FpFixPosition WHERE Id IN(SELECT MAX(ID) ID FROM FpFixPosition GROUP BY cpMainId, INDustryCategory HAVING COUNT(*) > 1)

	UPDATE a SET a.IndustryCategory = 8
	FROM FpFixPosition a, (
		SELECT dcProvinceId, IndustryCategory
		FROM FpFixPosition WITH(NOLOCK)
		GROUP BY dcProvinceId, IndustryCategory
		HAVING COUNT(*) < 4) b
	WHERE a.dcProvinceId = b.dcProvinceId
	AND a.IndustryCategory = b.IndustryCategory
COMMIT







GO
/****** Object:  StoredProcedure [dbo].[procFpHomepageimage51RCSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.10
--创建人：NICK
--说明：
--#####################################################
CREATE PROCEDURE [dbo].[procFpHomepageimage51RCSelect]
AS
BEGIN
	SELECT TOP 1 * 
	FROM fphomepageimage 
	WHERE url is not null 
	AND ltrim(url)<>'' ORDER BY adddate DESC
END


GO
/****** Object:  StoredProcedure [dbo].[procfpHomepageImageByProvinceIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.5
--创建人：NICK
--说明：获取网站头条
--#####################################################
CREATE PROCEDURE [dbo].[procfpHomepageImageByProvinceIDSelect]
(
	@ProvinceID INT,
	@Num INT
)
AS
BEGIN
	DECLARE @SQL VARCHAR(MAX)
	SET @SQL = 'SELECT TOP '+CONVERT(VARCHAR(10),@Num)+' * 
	FROM fpHomepageImage 
	WHERE dcProvinceID='+CONVERT(VARCHAR(10),@ProvinceID)+' 
	AND imagetype=1 
	AND  url >''''  
	ORDER BY AddDate DESC '
	EXEC(@SQL)
END


GO
/****** Object:  StoredProcedure [dbo].[ProcGdFixedSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--创建人：lambo
--创建时间：2013-5-25
--用途：查询固定资产列表
CREATE PROCEDURE [dbo].[ProcGdFixedSelect]
(
	@WorkUserID INT,
	@Where NVARCHAR(MAX)
)
AS
BEGIN
	--待确认的
	SELECT a.*,0 OrderBY INTO #T FROM GdFixed a WITH(NOLOCK) 
	WHERE 
	EXISTS(SELECT 'x' FROM GdRepair x WITH(NOLOCK) WHERE x.GdFixedID = a.ID AND OwnerConfirmDate IS NULL AND Owner = @WorkUserID )
	OR
	EXISTS(SELECT 'x' FROM GdShift x WITH(NOLOCK) WHERE x.GdFixedID = a.ID AND ReceiverDate IS NULL AND Owner = @WorkUserID ) 
	OR
	EXISTS(SELECT 'x' FROM GdShift x WITH(NOLOCK) WHERE x.GdFixedID = a.ID AND ReceiverDate IS NULL AND GdHouseID IN (SELECT ID FROM GdHouse WITH(NOLOCK) WHERE HouseOwner = @WorkUserID )) 
	OR
	(ScrapMan in
		(
			SELECT ID FROM WorkUser WITH(NOLOCK) 
			WHERE ManagerUserID IN 
			(
				SELECT ID FROM ManagerUser WITH(NOLOCK)
				WHERE Superior=(
					SELECT ManagerUserID FROM WorkUser WITH(NOLOCK)
					WHERE ID = @WorkUserID 
				)
			)
		)
		AND ScrapConfirmdate IS NULL
	)
	SET IDENTITY_INSERT #t ON
	--自己发出 别人代办的
	INSERT INTO #t (ID,FixedName,Format,BarcodeText,BarcodeLabel,GdClassId,SourceType,Buyer,BuyDate,Price,UsedMonth,Warranty,AddMan,AddDate,PhotoFile,status,ScrapDate,ScrapMan,ScrapReason,ScrapConfirmor,ScrapConfirmDate,ScrapMemo,OrderBY)
	SELECT ID,FixedName,Format,BarcodeText,BarcodeLabel,GdClassId,SourceType,Buyer,BuyDate,Price,UsedMonth,Warranty,AddMan,AddDate,PhotoFile,status,ScrapDate,ScrapMan,ScrapReason,ScrapConfirmor,ScrapConfirmDate,ScrapMemo,1 OrderBY FROM GdFixed a WITH(NOLOCK)
	WHERE
	(
		EXISTS(SELECT 'x' FROM GdRepair x WITH(NOLOCK) WHERE x.GdFixedID = a.ID AND OwnerConfirmDate IS NULL AND AddMan = @WorkUserID )
		OR
		EXISTS(SELECT 'x' FROM GdShift x WITH(NOLOCK) WHERE x.GdFixedID = a.ID AND ReceiverDate IS NULL AND AddMan = @WorkUserID ) 		
		OR
		(ScrapMan = @WorkUserID AND ScrapConfirmdate IS NULL)
	)
	AND ID NOT IN (SELECT ID FROM #t)
	 
	--自己使用的
	INSERT INTO #t (ID,FixedName,Format,BarcodeText,BarcodeLabel,GdClassId,SourceType,Buyer,BuyDate,Price,UsedMonth,Warranty,AddMan,AddDate,PhotoFile,status,ScrapDate,ScrapMan,ScrapReason,ScrapConfirmor,ScrapConfirmDate,ScrapMemo,OrderBY)
	SELECT ID,FixedName,Format,BarcodeText,BarcodeLabel,GdClassId,SourceType,Buyer,BuyDate,Price,UsedMonth,Warranty,AddMan,AddDate,PhotoFile,status,ScrapDate,ScrapMan,ScrapReason,ScrapConfirmor,ScrapConfirmDate,ScrapMemo,2 OrderBY FROM GdFixed a WITH(NOLOCK)
	WHERE
	EXISTS (SELECT 'x' FROM GdShift WITH(NOLOCK) WHERE GdFixedID = a.id AND Owner IS NOT NULL AND id = (SELECT MAX(id) FROM GdShift WITH(NOLOCK) WHERE ReceiverDate IS NOT NULL AND GdFixedID = a.id) AND Owner = @WorkUserID )
	AND ID NOT IN (SELECT ID FROM #t)

	--自己负责的
	INSERT INTO #t (ID,FixedName,Format,BarcodeText,BarcodeLabel,GdClassId,SourceType,Buyer,BuyDate,Price,UsedMonth,Warranty,AddMan,AddDate,PhotoFile,status,ScrapDate,ScrapMan,ScrapReason,ScrapConfirmor,ScrapConfirmDate,ScrapMemo,OrderBY)
	SELECT ID,FixedName,Format,BarcodeText,BarcodeLabel,GdClassId,SourceType,Buyer,BuyDate,Price,UsedMonth,Warranty,AddMan,AddDate,PhotoFile,status,ScrapDate,ScrapMan,ScrapReason,ScrapConfirmor,ScrapConfirmDate,ScrapMemo,2 OrderBY FROM GdFixed a WITH(NOLOCK)
	WHERE
	EXISTS (SELECT 'x' FROM GdShift WITH(NOLOCK) WHERE GdFixedID = a.id AND Owner IS NULL AND id = (SELECT MAX(id) FROM GdShift WITH(NOLOCK) WHERE ReceiverDate IS NOT NULL AND GdFixedID = a.id) AND GdHouseID IN (SELECT ID FROM GdHouse WITH(NOLOCK) WHERE HouseOwner = @WorkUserID) )
	AND ID NOT IN (SELECT ID FROM #t)

	--其它
	INSERT INTO #t (ID,FixedName,Format,BarcodeText,BarcodeLabel,GdClassId,SourceType,Buyer,BuyDate,Price,UsedMonth,Warranty,AddMan,AddDate,PhotoFile,status,ScrapDate,ScrapMan,ScrapReason,ScrapConfirmor,ScrapConfirmDate,ScrapMemo,OrderBY)
	SELECT ID,FixedName,Format,BarcodeText,BarcodeLabel,GdClassId,SourceType,Buyer,BuyDate,Price,UsedMonth,Warranty,AddMan,AddDate,PhotoFile,status,ScrapDate,ScrapMan,ScrapReason,ScrapConfirmor,ScrapConfirmDate,ScrapMemo,2 OrderBY FROM GdFixed a WITH (NOLOCK) 
	WHERE ID NOT IN (SELECT ID FROM #t)
	
	SET @Where = dbo.SafeSql(@Where)
	EXEC('SELECT a.*,	b.ClassName,
	ISNULL((SELECT LTRIM(STR(ManagerUserID)) + '' '' + Name From WorkUser WHERE ID IN( SELECT TOP 1 ISNULL(owner,0) FROM gdshift WITH(NOLOCK) WHERE gdfixedid=a.id and ReceiverDate IS NOT NULL ORDER BY ID DESC)),'''') WorkUserName,
	ISNULL((SELECT HouseName+''(''+Ltrim(str(n.manageruserid))+n.Name+'')'' From GdHouse m with(nolock),workuser n with(nolock) WHERE m.HouseOwner=n.id and m.ID IN( SELECT TOP 1 ISNULL(GdHouseId,0) FROM gdshift WITH(NOLOCK) WHERE gdfixedid=a.id and ReceiverDate IS NOT NULL  ORDER BY ID DESC)),'''') GdHouseName,
	(SELECT count(1) FROM GdShift WITH(NOLOCK) WHERE gdFixedID=a.ID ) ShiftCount 
	FROM #t a WITH(NOLOCK) ,GdClass b WITH(NOLOCK) WHERE a.GdClassid = b.id ' + @Where)
END 











GO
/****** Object:  StoredProcedure [dbo].[procGetCvMatchSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.03
--创建人：Nick
--说明：获取简历和职位的匹配度
--#####################################################
CREATE PROCEDURE [dbo].[procGetCvMatchSelect]
(
	@CvMainID INT,
	@JobID INT
)
AS
BEGIN TRY
	SELECT dbo.GetCvMatch(@CvMainID,@JobID) MatchNo
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[ProcHotJobByRegionIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2014.10.31
--创建人：John
--说明：根据RegionID 获取当前地区热门招聘职位
--#####################################################
CREATE PROCEDURE [dbo].[ProcHotJobByRegionIDSelect]
(
	@dcRegionID VARCHAR(4)
)
AS
BEGIN
	SELECT TOP 10 dcJobTypeID,AvgSalary FROM reportdb..SalaryReportJobtype WHERE dcRegionid = @dcRegionID ORDER BY JobNumber DESC
END


GO
/****** Object:  StoredProcedure [dbo].[ProcHotRankingInsert]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--sean 2014-8-14
CREATE PROCEDURE [dbo].[ProcHotRankingInsert]
AS
BEGIN
	TRUNCATE TABLE SearchDb..HotRanking

	DECLARE @ProvinceId INT
	SET @ProvinceId = 0
	WHILE EXISTS(SELECT 'x' FROM dcProvince WHERE ID > @ProvinceId)
	BEGIN
		SELECT TOP 1 @ProvinceId = ID FROM dcProvince WHERE ID > @ProvinceId ORDER BY ID
		
		INSERT INTO SearchDb..HotRanking(Category, ProvinceId, ID, Title, ViewNumber_All, ResionOrder)
		--SELECT TOP 10 2, @ProvinceId, a.ID, a.Title, CASE CHARINDEX(@RegionName, Title) WHEN 0 THEN 0 ELSE 1 END AS ResionOrder
		SELECT TOP 10 2, @ProvinceId, a.ID, a.Title, ViewNumber_All, 0 ResionOrder
		FROM QlrcNews a WITH(NOLOCK)
		WHERE EXISTS(SELECT 'x' FROM fnSplit(DetailType, ',') b, dcNewsType c WITH(NOLOCK) WHERE b.a = c.id AND c.id = 2) 
		AND VersionID = @ProvinceId --OR VersionID = 0)
		AND Type = 1 
		AND RefreshDate > DATEADD(MONTH, -3, GETDATE()) 
		ORDER BY ResionOrder DESC, ViewNumber_All desc

		INSERT INTO SearchDb..HotRanking(Category, ProvinceId, ID, Title, ViewNumber_All, ResionOrder)
		SELECT TOP 10 1, @ProvinceId, ID, Title, ViewNumber_All, 0 ResionOrder
		FROM QlrcNews a WITH(NOLOCK)
		WHERE EXISTS(SELECT 'x' FROM fnSplit(DetailType, ',') b, dcNewsType c WITH(NOLOCK) WHERE b.a = c.id AND c.id <> 2)
		AND VersionID = @ProvinceID --OR VersionID = 0)
		AND Type = 1
		AND RefreshDate > DATEADD(MONTH, -3, GETDATE())  
		ORDER BY ViewNumber_All desc
	END
	----	'32__'
	DECLARE @RegionName NVARCHAR(5)
	SET @ProvinceId = 0
	WHILE EXISTS(SELECT 'x' FROM dcRegion WHERE ID LIKE '32__' AND ID > @ProvinceId)
	BEGIN
		SELECT TOP 1 @ProvinceId = ID, @RegionName = LEFT(Description, 2)
		FROM dcRegion WHERE ID LIKE '32__' AND ID > @ProvinceId ORDER BY ID

		INSERT INTO SearchDb..HotRanking(Category, ProvinceId, ID, Title, ViewNumber_All, ResionOrder)
		SELECT TOP 10 2, @ProvinceId, a.ID, a.Title, ViewNumber_All, CASE CHARINDEX(@RegionName, Title) WHEN 0 THEN 0 ELSE 1 END AS ResionOrder
		FROM QlrcNews a WITH(NOLOCK)
		WHERE EXISTS(SELECT 'x' FROM fnSplit(DetailType, ',') b, dcNewsType c WITH(NOLOCK) WHERE b.a = c.id AND c.id = 2) 
		AND (VersionID = 32 OR VersionID = 0)
		AND Type = 1 
		AND RefreshDate > DATEADD(MONTH, -3, GETDATE()) 
		ORDER BY ResionOrder DESC, ViewNumber_All desc

		INSERT INTO SearchDb..HotRanking(Category, ProvinceId, ID, Title, ViewNumber_All, ResionOrder)
		SELECT TOP 10 1, @ProvinceId, ID, Title, ViewNumber_All, 0 ResionOrder
		FROM QlrcNews a WITH(NOLOCK)
		WHERE EXISTS(SELECT 'x' FROM fnSplit(DetailType, ',') b, dcNewsType c WITH(NOLOCK) WHERE b.a = c.id AND c.id <> 2)
		AND (VersionID LIKE '32%' OR VersionID = 0)
		AND Type = 1
		AND RefreshDate > DATEADD(MONTH, -3, GETDATE())  
		ORDER BY ViewNumber_All desc
	END
END





GO
/****** Object:  StoredProcedure [dbo].[ProcHotRankingSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- sean 2014-8-14
CREATE PROCEDURE [dbo].[ProcHotRankingSelect]
(
	@ProvinceID INT,
	@Category INT
)
AS
BEGIN
	IF @ProvinceID > 99 AND LEFT(@ProvinceID, 2) < '32'
		SET @ProvinceID = LEFT(@ProvinceID, 2)

	IF @Category > 0
	BEGIN
		IF @Category <> 2
			SET @Category = 1

		SELECT ID, Title, ResionOrder 
		FROM SearchDb..HotRanking WITH(NOLOCK)
		WHERE ProvinceId = @ProvinceID
		AND Category = @Category
		ORDER BY ViewNumber_All DESC
	END
	ELSE
		SELECT TOP 10 ID, Title, ResionOrder 
		FROM SearchDb..HotRanking WITH(NOLOCK)
		WHERE ProvinceId = @ProvinceID
		ORDER BY ViewNumber_All DESC
END





GO
/****** Object:  StoredProcedure [dbo].[procHpHighSalaryJobNewSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


/***
*Peter 2016-9-1
*首页高薪职位查询
*
*/
CREATE PROCEDURE [dbo].[procHpHighSalaryJobNewSelect]
(
    @dcSubSiteID SMALLINT
)
AS
SET NOCOUNT ON
BEGIN
    SELECT TOP 10 a.*, b.dcRegionID JobRegionID, b.dcSalaryIdMax,b.Negotiable  
    FROM HpHighSalaryJobNew a WITH(NOLOCK), Job b WITH(NOLOCK)
    WHERE a.JobID = b.ID AND a.dcRegionID = @dcSubSiteID
    ORDER BY JobRefreshDate DESC, ID
END

GO
/****** Object:  StoredProcedure [dbo].[procHpHighSalaryJobNewUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[procHpHighSalaryJobNewUpdate]
AS
SET NOCOUNT ON
BEGIN
	UPDATE a SET a.RefreshDate = b.RefreshDate
	FROM hpHighSalaryCompanyNew a, cpMain b
	WHERE a.cpMainId = b.Id AND a.RefreshDate != b.RefreshDate

	UPDATE hpHighSalaryCompanyNew SET RowNo = 999 WHERE RowNo < 20

	UPDATE a
	SET a.RowNo = b.RowNo2
	FROM hpHighSalaryCompanyNew a,
		(SELECT Id, ROW_NUMBER() OVER(PARTITION BY dcRegionId ORDER BY RefreshDate DESC, cpMainId DESC) RowNo2 FROM hpHighSalaryCompanyNew WITH(NOLOCK) WHERE LogoUrl > '') b
	WHERE a.id = b.Id
	AND b.RowNo2 < 20

	TRUNCATE TABLE HpHighSalaryJobNew;

	INSERT INTO HpHighSalaryJobNew(dcRegionID, JobID, JobSecondID, JobName, CpMainID, CpSecondID, CpName, dcSalaryID, JobRefreshDate, LogoUrl)
	SELECT dcRegionID, JobId, JobSecondID, JobName, CpMainID, CpSecondID, CpName, dcSalaryID, RefreshDate, LogoUrl
	FROM hpHighSalaryCompanyNew
	WHERE RowNo < 19
	ORDER BY dcRegionId, RowNo;
	IF GETDATE() < CONVERT(DATETIME, '2018-04-25')
	BEGIN
		IF EXISTS(SELECT 'x' FROM HpHighSalaryJobNew WITH(NOLOCK) WHERE cpMainId = 5654050)
			UPDATE HpHighSalaryJobNew SET JobRefreshDate = GETDATE() + 1 WHERE cpMainId = 5654050
		ELSE
			INSERT INTO HpHighSalaryJobNew(dcRegionID, JobID, JobSecondID, JobName, CpMainID, CpSecondID, CpName, dcSalaryID, JobRefreshDate, LogoUrl)
			SELECT dcRegionID, JobId, JobSecondID, JobName, CpMainID, CpSecondID, CpName, dcSalaryID, GETDATE() + 1, LogoUrl
			FROM hpHighSalaryCompanyNew
			WHERE cpMainId = 5654050
	END
END

GO
/****** Object:  StoredProcedure [dbo].[procHpHighSalaryJobSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/***
*Peter 2016-9-1
*首页高薪职位查询
*
*/
CREATE PROCEDURE [dbo].[procHpHighSalaryJobSelect]
(
	@dcSubSiteID SMALLINT
)
AS
SET NOCOUNT ON
BEGIN
	SELECT a.*, b.dcRegionID JobRegionID 
	FROM HpHighSalaryJob a WITH(NOLOCK), Job b WITH(NOLOCK)
	WHERE a.JobID = b.ID AND a.dcRegionID = @dcSubSiteID
	ORDER BY ID
END
GO
/****** Object:  StoredProcedure [dbo].[procHpHighSalaryJobUpdate]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/***
*Peter 2016-9-1
*首页高薪职位更新
*
*/
CREATE PROCEDURE [dbo].[procHpHighSalaryJobUpdate]
AS
SET NOCOUNT ON
BEGIN
	UPDATE a SET a.RefreshDate = b.RefreshDate  FROM hpHighSalaryCompany a, cpMain b WHERE a.cpMainId = b.Id AND a.RefreshDate != b.RefreshDate
	UPDATE hpHighSalaryCompany SET RowNo = 0 WHERE RowNo < 20

	UPDATE a
	SET a.RowNo = b.RowNo2
	FROM hpHighSalaryCompany a,
		(SELECT Id, ROW_NUMBER() OVER(PARTITION BY dcRegionId ORDER BY RefreshDate DESC, cpMainId DESC) RowNo2 FROM hpHighSalaryCompany WITH(NOLOCK) WHERE LogoUrl > '') b
	WHERE a.id = b.Id
	AND b.RowNo2 < 7

	UPDATE a
	SET a.RowNo = 10 + b.RowNo2
	FROM hpHighSalaryCompany a,
		(SELECT Id, ROW_NUMBER() OVER(PARTITION BY dcRegionId ORDER BY RefreshDate DESC, cpMainId DESC) RowNo2 FROM hpHighSalaryCompany WITH(NOLOCK) WHERE RowNo = 0) b
	WHERE a.id = b.Id

	TRUNCATE TABLE HpHighSalaryJob
	INSERT INTO hpHighSalaryJob(dcRegionID, JobID, JobSecondID, JobName, CpMainID, CpSecondID, CpName, dcSalaryID, JobRefreshDate, LogoUrl)
	SELECT dcRegionID, JobId, JobSecondID, JobName, CpMainID, CpSecondID, CpName, dcSalaryID, RefreshDate, CASE WHEN RowNo < 10 THEN LogoUrl ELSE NULL END
	FROM hpHighSalaryCompany 
	WHERE RowNo < 19
	ORDER BY dcRegionId, RowNo
--	--=========================
--	CREATE TABLE #t2(
--		dcRegionId INT,
--		dcJobtypeId [varchar](4) NULL,
--		cpMainId INT,
--		cpSecondID [varchar](10) NULL,
--		ImgFile [varchar](50) NOT NULL
--	)
--	INSERT INTO #T2
--	SELECT dcRegionId, dcJobtypeId, cpMainId, cpSecondID, ImgFile
-- 	FROM (
--		SELECT a.dcProvinceid dcRegionId,
--			LEFT(b.dcJobTypeId, 2) dcJobtypeId,
--			a.Id cpMainId,
--			a.SecondID cpSecondID,
--			c.ImgFile,
--			ROW_NUMBER() OVER(PARTITION BY a.dcProvinceid, LEFT(b.dcJobTypeId, 2) ORDER BY a.RefreshDate DESC, a.Id DESC) Row
--		FROM cpMainPubLish a, JobPublish b, cpImage c
--		WHERE a.Id = b.cpMainId
--		AND a.Id = c.cpMainId
--		AND c.Imgtype = 1
--		AND b.RefreshDate > DATEADD(MINUTE, - 3, GETDATE())) a
--	WHERE a.Row = 1
--	ORDER BY dcRegionId, dcJobtypeId
--
--	DELETE a
--	FROM HpJobTypeCpLogo a, #T2 b
--	WHERE a.dcRegionId = b.dcRegionId AND a.dcJobtypeId = b.dcJobTypeId
--
--	INSERT INTO HpJobTypeCpLogo(dcRegionID,dcJobTypeID,CpMainID,CpSecondID,LogoUrl)
--	SELECT dcRegionID, dcJobtypeId, cpMainId,cpSecondID, ImgFile 
--	FROM #T2
END
GO
/****** Object:  StoredProcedure [dbo].[procHpJobNewsByDetailTypeSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.5
--创建人：NICK
--说明：获取某类N条资讯
--#####################################################
CREATE PROCEDURE [dbo].[procHpJobNewsByDetailTypeSelect]
(
	@newsNumber INT,
	@detailType INT,
	@provinceID INT
)
AS
BEGIN
	DECLARE @SQL VARCHAR(MAX)
	SET @SQL  = 'SELECT TOP ' + CONVERT(VARCHAR(20),@newsNumber) + ' * '
	SET @SQL  = @SQL+' FROM HpJobNews WITH(NOLOCK)'
	SET @SQL  = @SQL+' WHERE DetailType = '+CONVERT(VARCHAR(20),@detailType)
	SET @SQL  = @SQL+' AND VersionId = '+CONVERT(VARCHAR(20),@provinceID)
	SET @SQL  = @SQL+' ORDER BY RefreshDate DESC '
	EXEC(@SQL)
END


GO
/****** Object:  StoredProcedure [dbo].[procHpJobTypeCpLogoSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/***
*Peter 2016-9-1
*首页职位类别Logo查询
*
*/
CREATE PROCEDURE [dbo].[procHpJobTypeCpLogoSelect]
(
	@dcSubSiteID SMALLINT
)
AS
SET NOCOUNT ON
BEGIN
	SELECT * 
	FROM HpJobTypeCpLogo WITH(NOLOCK)
	WHERE dcRegionID = @dcSubSiteID
END
GO
/****** Object:  StoredProcedure [dbo].[procHpJobTypeinfoByRegionID24Select]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.03
--创建人：Nick
--说明：根据职位数量获取最多的职位类别
--#####################################################
CREATE PROCEDURE [dbo].[procHpJobTypeinfoByRegionID24Select]
(
	@dcRegionID INT
)
AS
BEGIN TRY
	SELECT TOP 24 dcJobTypeID,Description 
	FROM hpJobTypeInfo a, dcJobType b 
	WHERE a.dcJobTypeID=b.ID 
	AND a.dcRegionID=@dcRegionID 
	AND LEN(dcJobTypeID) = 4 
	ORDER BY JobNum DESC
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[procHpJobTypeinfoByRegionIDSelect]    Script Date: 2018/9/25 12:40:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.03
--创建人：Nick
--说明：添加获取职位类型左侧导航数据
--修改：harry2015-8-18
--增加c.orderNo
--#####################################################
CREATE PROCEDURE [dbo].[procHpJobTypeinfoByRegionIDSelect]
(
	@dcRegionID INT
)
AS
BEGIN
	SELECT TOP 1000 a.dcJobTypeId JobTypeID,a.JobNum JobNumber,b.CategoryId,c.parentID,c.grade,
		c.description,c.parentID2,c.parentID3,c.OrderNo
	FROM hpjobtypeinfo a 
	LEFT JOIN dcJobTypeMap b ON b.JobTypeId=a.dcJobtypeid 
	LEFT JOIN dcJobType c ON c.id=a.dcJobTypeid 
	WHERE a.dcRegionID = @dcRegionID 
	ORDER BY c.OrderNo,b.OrderBy
END
GO
/****** Object:  StoredProcedure [dbo].[procHpJobTypeInfoUpdate]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/**
*创建	Peter
*时间	2013-01-09 15:51
*作用	首页左侧职位索引区域职位数量更新
**/
CREATE PROCEDURE [dbo].[procHpJobTypeInfoUpdate]
AS
SET NOCOUNT ON
BEGIN
	TRUNCATE TABLE LogDb..hpJobTypeInfo
	CREATE TABLE #T(
		dcJobTypeID INT,
		dcRegionID INT,
		JobNum INT
	)

	DELETE hpJobTypeInfo WHERE dcRegionId NOT IN(SELECT ID FROM dcSubSite)
	DELETE hpJobTypeInfo WHERE dcJobTypeId NOT IN(SELECT ID FROM dcJobType)
	INSERT INTO #T  SELECT a.ID, b.Id, 0 FROM dcJobType a, dcSubSite b
	DELETE #t FROM hpJobTypeInfo a WHERE #t.dcJobTypeId = a.dcJobTypeId AND a.dcRegionId = #t.dcRegionId
	INSERT hpJobTypeInfo SELECT dcJobTypeID, dcRegionID, 0, GETDATE() FROM #t

	TRUNCATE TABLE #t

	INSERT INTO #T 
	SELECT dcJobTypeId, LEFT(dcRegionId, 4), COUNT(*)
	FROM JobPublish WITH(NOLOCK)
	WHERE Valid = 1
	GROUP BY dcJobTypeId, LEFT(dcRegionId, 4)

	SELECT LEFT(dcJobTypeId, 2) dcJobTypeID, dcRegionID, SUM(JobNum) JobNum
	INTO #tt
	FROM #t
	GROUP BY LEFT(dcJobTypeId, 2), dcRegionID

	DELETE #t WHERE dcJobTypeId < 99
	INSERT #t SELECT * FROM #tt
	
	TRUNCATE TABLE #tt

	INSERT INTO #tt
	SELECT dcJobTypeId, LEFT(dcRegionID, 2), SUM(JobNum) JobNum		
	FROM #t
	GROUP BY dcJobTypeId, LEFT(dcRegionID, 2)

	DELETE #t WHERE dcRegionId < 99
	INSERT #t SELECT * FROM #tt

	UPDATE hpJobTypeInfo SET JobNum = 0

	UPDATE a
	SET a.ModifyDate = GETDATE(), a.JobNum = b.JobNum
	FROM hpJobTypeInfo a, #t b
	WHERE a.dcRegionId = b.dcRegionId AND a.dcJobTypeId = b.dcJobTypeId

	DROP TABLE #T
	DROP TABLE #TT
END










GO
/****** Object:  StoredProcedure [dbo].[prochpNewsSetByProvinceIDSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.03
--创建人：Nick
--说明：取新首页职场新闻模块的显示
--#####################################################
CREATE PROCEDURE [dbo].[prochpNewsSetByProvinceIDSelect]
(
	@ProvinceID INT
)
AS
BEGIN TRY
	SELECT Section FROM hpNewsSet WHERE dcProvinceID=@ProvinceID
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[prociIvgt_AnswerSumByQuestionIDSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.10
--创建人：NICK
--说明：获得调查的点击总数
--#####################################################
CREATE PROCEDURE [dbo].[prociIvgt_AnswerSumByQuestionIDSelect]
(
	@QuesionID INT
)
AS
BEGIN
	SELECT SUM(clicknum) cnt FROM ivgt_answer WITH(NOLOCK) WHERE questionid=@QuesionID
END


GO
/****** Object:  StoredProcedure [dbo].[ProcIncludeRateSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ProcIncludeRateSelect]
(
	@ProvinceID INT,				----网站省份编号
	@CatalogID INT,					----目录编号（1、职位页面；2、公司页面；3、招聘会页面4、求职互助页面；5、职场新闻页面；6、职位地图页面；7、校园招聘页面）
	@GenerateStartDate DATETIME,	----生成开始时间
	@GenerateEndDate DATETIME,		----生成结束时间
	@FlashStartDate DATETIME,		----刷新开始时间
	@FlashEndDate DATETIME,			----刷新结束时间
	@Percentage DECIMAL(18, 4),		 ----百分比 （例0.1  百分之十）
	@SortID INT,					-----排序 （1、正序；2、倒序；3、随机）
	@Type INT						------0，存储过程返回页面的数量；1、返回页面信息
)
AS
BEGIN
	DECLARE @t AS TABLE(ID INT, Date DATETIME, Rnd VARCHAR(100))
	DECLARE @Cnt AS INT, @p AS VARCHAR(4)

	SELECT @GenerateStartDate = ISNULL(@GenerateStartDate, '2000-1-1'),
		@GenerateEndDate = ISNULL(@GenerateEndDate, GETDATE()),
		@FlashStartDate = ISNULL(@GenerateStartDate, '2000-1-1'),
		@FlashEndDate = ISNULL(@GenerateEndDate, GETDATE()),
		@p = CONVERT(VARCHAR, @ProvinceID)	
	
	IF (@CatalogID = 1)
	BEGIN
		INSERT INTO @t(ID, Date)
		SELECT ID, RefreshDate FROM Job WITH(NOLOCK)
		WHERE AddDate BETWEEN @GenerateStartDate AND @GenerateEndDate
		AND RefreshDate BETWEEN @FlashStartDate AND @FlashEndDate
		AND cpMainID IN(SELECT ID FROM cpMain WITH(NOLOCK) WHERE dcSUbSiteId LIKE @p + '%')
	END
	ELSE IF (@CatalogID = 2)
	BEGIN
		INSERT INTO @t(ID, Date)
		SELECT ID, RefreshDate FROM cpMain WITH(NOLOCK)
		WHERE RegDate BETWEEN @GenerateStartDate - 2 AND @GenerateEndDate - 2
		AND RefreshDate BETWEEN @FlashStartDate AND @FlashEndDate
		AND MemberType > 0
		AND dcSubSiteId LIKE @p + '%'
	END
	ELSE IF (@CatalogID = 3)
	BEGIN
		INSERT INTO @t(ID, Date)
		SELECT ID, AddDate FROM RecruitMent WITH(NOLOCK)
		WHERE AddDate BETWEEN @GenerateStartDate AND @GenerateEndDate
		AND CityId LIKE @p + '%'
	END
	ELSE IF (@CatalogID = 4)
	BEGIN
		INSERT INTO @t(ID, Date)
		SELECT ID, AddDate FROM bsAskInfo WITH(NOLOCK)
		WHERE AddDate BETWEEN @GenerateStartDate AND @GenerateEndDate
		AND ProvinceIds LIKE '%,%' + @p + ',%'
	END
	ELSE IF (@CatalogID = 5)
	BEGIN
		INSERT INTO @t(ID, Date)
		SELECT ID, AnnounceDate FROM QlrcNews WITH(NOLOCK)
		WHERE AnnounceDate BETWEEN @GenerateStartDate AND @GenerateEndDate
		AND VersionId LIKE @p + '%'
	END

	SELECT @Cnt = COUNT(*) FROM @t
	IF @Cnt = 0
	BEGIN
		SELECT 0
		RETURN
	END
	ELSE IF @Type = 0 OR @Percentage = 0
		SELECT @Cnt
	ELSE
	BEGIN
		DECLARE @FetchNumber AS INT
		SELECT @FetchNumber = @Cnt * @Percentage
		IF @FetchNumber = 0
		BEGIN
			SELECT 0
			RETURN
		END

		IF @SortID = 3			----随机
		BEGIN
			UPDATE @t SET Rnd = NewId()
			SELECT TOP (@FetchNumber) ID FROM @t ORDER BY Rnd
		END
		ELSE
		BEGIN
			IF @CatalogID IN(1, 2) AND @FlashStartDate > '2001-1-1'
			BEGIN
				IF @SortID = 1
					SELECT TOP (@FetchNumber) ID FROM @t ORDER BY Date
				IF @SortID = 2
					SELECT TOP (@FetchNumber) ID FROM @t ORDER BY Date DESC
			END
			ELSE
			BEGIN
				IF @SortID = 1 ----正序
					SELECT TOP (@FetchNumber) ID FROM @t ORDER BY ID
				IF @SortID = 2 ----倒序
					SELECT TOP (@FetchNumber) ID FROM @t ORDER BY ID DESC
			END
		END
	END
END














GO
/****** Object:  StoredProcedure [dbo].[procInfo_datereportUpdate]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[procInfo_datereportUpdate] 
(
	@province_id SMALLINT,
	@infomanager_id SMALLINT,
	@ip VARCHAR(15),
	@referer VARCHAR(100),
	@result SMALLINT OUTPUT
)
AS
BEGIN
	SET NOCOUNT ON
	SELECT TOP 1 countdate
	FROM info_datereport WITH(NOLOCK)
	WHERE countdate=YEAR(GETDATE())*10000+MONTH(GETDATE())*100+DAY(GETDATE())
	AND province_id = @province_id
	AND infomanager_id=@infomanager_id

	IF (@@ROWCOUNT=0)
	BEGIN
		INSERT INTO info_datereport (province_id,infomanager_id,countdate) 
		VALUES(@province_id,@infomanager_id,YEAR(GETDATE())*10000+MONTH(GETDATE())*100+day(GETDATE()))
	END

	SELECT TOP 1 adddate
	FROM infolog WITH(NOLOCK)
	WHERE adddate > GETDATE()-1
	AND infomanager_id = @infomanager_id
	AND ip = @ip
	AND Ip NOT LIKE '60.215.144%'

	IF (@@ROWCOUNT=0)
	BEGIN
		UPDATE info_datereport SET homepage = homepage + 1  
		WHERE countdate=YEAR(GETDATE())*10000+MONTH(GETDATE())*100+DAY(GETDATE())
		AND province_id = @province_id
		AND infomanager_id=@infomanager_id

		INSERT INTO infolog (infomanager_id,ip,referer) VALUES(@infomanager_id,@ip,@referer)
		SET @result=1
	END
	ELSE
	BEGIN
		SET @result=0
	END
	--PRINT @result
	SET NOCOUNT OFF
END














GO
/****** Object:  StoredProcedure [dbo].[ProcInfoLogInsert]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2014.10.31
--创建人：John
--说明：新增InfoLog
--#####################################################
CREATE PROCEDURE [dbo].[ProcInfoLogInsert]
(
	@InfoId SMALLINT,
	@IP VARCHAR(15),
	@Source VARCHAR(200),
	@SubSiteID SMALLINT
)
AS
BEGIN
	INSERT INTO reportdb..InfoLog(InfoId,IP,Source,SubSiteID,AddDate) VALUES(@InfoId,@IP,@Source,@SubSiteID,GETDATE())
END


GO
/****** Object:  StoredProcedure [dbo].[ProcInfoSetByKeySelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2014.10.31
--创建人：John
--说明：根据Key查InfoSet
--#####################################################
CREATE PROCEDURE [dbo].[ProcInfoSetByKeySelect]
(
	@InfoKey VARCHAR(200)
)
AS
BEGIN
	SELECT * FROM reportdb..InfoSet WITH(NOLOCK) WHERE InfoKey = @InfoKey
END


GO
/****** Object:  StoredProcedure [dbo].[procInnererInsert]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[procInnererInsert]
(
	@province_id SMALLINT,
	@VersionID SMALLINT,
	@referer VARCHAR(190),
	@ip VARCHAR(15),
	@keyve NVARCHAR(50),
	@innerpage SMALLINT
)
AS
BEGIN
	SET NOCOUNT ON
	SELECT TOP 1 ip
	FROM Innerer WITH(INDEX=IX_Innerer_VersionID, NOLOCK)
	WHERE VersionID = @VersionID 
	AND referer=@referer
	AND ip=@ip
	AND LoginDate > DATEADD(MINUTE, -10, GETDATE())

	IF (@@ROWCOUNT = 0) 
	BEGIN
		INSERT INTO Innerer(province_id,VersionID,referer,ip,keywords,innerpage)
		VALUES(ISNULL(@province_id, 0), ISNULL(@VersionID, 0),@referer,@ip,@keyve,@innerpage)
	END 
	SET NOCOUNT OFF
END





GO
/****** Object:  StoredProcedure [dbo].[ProcInterViewByCpMainIDSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.20
--创建人：Nick
--说明：根据公司ID获取 面试经历信息,以及平均分
--#####################################################
CREATE PROCEDURE [dbo].[ProcInterViewByCpMainIDSelect]
(
	@CpMainID INT,
	@SessionID VARCHAR(50),
	@PamainID INT
)
AS
BEGIN 
	IF @PamainID <> 0
	BEGIN
		SELECT * FROM InterView
		WHERE CpMainID = @CpMainID 
		AND InterViewType<>3 
		AND (VerifyDate IS NOT NULL OR PaMainID = @PamainID)
		ORDER BY ADDDATE DESC
	END
	ELSE
	BEGIN
--		IF @SessionID<>''
--		BEGIN
--			SELECT * FROM InterView
--			WHERE CpMainID = @CpMainID 
--			AND InterViewType<>3 
--			AND (VerifyDate IS NOT NULL OR (PaMainID = 0 AND SessionID = @SessionID))
--			ORDER BY ADDDATE DESC
--		END
--		ELSE
--		BEGIN
			SELECT * FROM InterView
			WHERE CpMainID = @CpMainID 
			AND InterViewType<>3 
			AND VerifyDate IS NOT NULL
			ORDER BY ADDDATE DESC
--		END
	END
End


GO
/****** Object:  StoredProcedure [dbo].[ProcInterViewByID]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.24
--创建人：Nick
--说明：根据ID获取面试经历信息
--#####################################################
CREATE PROCEDURE [dbo].[ProcInterViewByID]
(
	@ID INT
)
AS
BEGIN 
	SELECT * FROM InterView WHERE ID = @ID
End


GO
/****** Object:  StoredProcedure [dbo].[ProcInterviewByIDUpdate]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.19
--创建人：Nick
--说明：根据ID修改面试信息
--#####################################################
CREATE PROCEDURE [dbo].[ProcInterviewByIDUpdate]
(
	@ID INT,
	@JobName VARCHAR(50),
	@InterviewDate VARCHAR(6),
	@InterViewResult INT,
	@SalaryMonth INT,
	@InterViewExperience NVARCHAR(MAX),
	@InterviewFeeling NVARCHAR(MAX),
	@Title NVARCHAR(50),
	@VerifyMan INT,
	@InterviewType INT
)
AS
SET NOCOUNT ON
BEGIN TRY
	DECLARE @AddDate DATETIME,@CpName NVARCHAR(100),@Title2 NVARCHAR(50)
	SELECT @AddDate = a.AddDate,@CpName = b.Name,@Title2 = a.Title
	FROM Interview a,Cpmain b
	WHERE a.ID =  @ID
	AND a.CpMainID = b.ID

	UPDATE Interview
	SET JobName = @JobName,
		InterviewDate = @InterviewDate,
		InterViewResult = @InterViewResult,
		SalaryMonth = @SalaryMonth,
		InterViewExperience = @InterViewExperience,
		InterviewFeeling = @InterviewFeeling,
		Title = @Title,
		VerifyMan = @VerifyMan,
		VerifyDate = GETDATE(),
		InterviewType = @InterviewType
	WHERE CpMainID IN (SELECT ID FROM cpMain WITH(NOLOCK) WHERE Name = @CpName)
	AND AddDate = @AddDate
	AND Title = @Title2
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[ProcInterViewByKeyWordSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--###########################
--创建时间：2014.11.27
--创建人：Nick
--说明：获取面试经历公司列表
--###########################
CREATE PROCEDURE [dbo].[ProcInterViewByKeyWordSelect]
(
	@dcRegionID VARCHAR(100),
	@PageNo INT,
	@KeyWord VARCHAR(50)
)
AS
BEGIN 
	DECLARE @WHERE VARCHAR(MAX),@JobPlace AS VARCHAR(2000),@WHERE2 VARCHAR(MAX)
	SET @JobPlace = ''
	SET @WHERE = ''
	SET @WHERE2 = ''
	
	IF CHARINDEX(',',@dcRegionID)>0
	BEGIN
		DECLARE @T_JobPlace AS TABLE(ID INT)
		INSERT INTO @T_JobPlace
		SELECT * FROM dbo.fnSplit(@dcRegionID, ',')
		
		SELECT @JobPlace = (@JobPlace + ' OR b.dcRegionID Like ''' + LTRIM(STR(ID) + '%''')) FROM @T_JobPlace
		
		IF LEN(@JobPlace) > 0
		SET @JobPlace = RIGHT(@JobPlace, LEN(@JobPlace) -4)
		SET @WHERE = @WHERE + '
			AND (' + @JobPlace + ')'
		SET @WHERE2 = @WHERE2 + '
			AND (' + @JobPlace + ')'
	END
	ELSE
	BEGIN
		SET @WHERE = ' AND (b.dcRegionID Like '''+@dcRegionID+'%'')'
		SET @WHERE2 = ' AND (b.dcRegionID Like '''+@dcRegionID+'%'')'
	END
	
	SET @KeyWord = dbo.SafeSQL(ISNULL(@KeyWord, ''))
	
	IF @KeyWord <> ''
	BEGIN
		SET @WHERE = @WHERE + ' AND b.Name LIKE  ''%'+@KeyWord+'%'' '
	END
	
	DECLARE @PageSize INT
	SET @PageSize = 5
    DECLARE @PageLowerBound  INT --定义此页的底码
    DECLARE @PageUpperBound  INT --定义此页的顶码
    SET @PageLowerBound = (@PageNo -1) * @pagesize
    SET @PageUpperBound = @PageLowerBound + @pagesize
	
	DECLARE @AllCnt INT
	SET @AllCnt = 0
	DECLARE @SQL NVARCHAR(MAX)
	
	--创建临时表
	CREATE TABLE #T1(
		[cpmainid] [int] NOT NULL,
		[name] [varchar](100) NULL,
		[secondid] varchar(12) NULL,
		[AddDate] [datetime] NULL,
		[OrderBY] [int] NULL
	)	

	IF @KeyWord = ''
	BEGIN
		SET @SQL = '
			INSERT INTO #T1
			SELECT TOP 500 cpmainid,b.name,b.secondid,a.AddDate,1 AS OrderBY
			FROM InterView a,cpmain b
			WHERE a.id IN(SELECT MAX(id) FROM InterView GROUP BY cpmainid)
			AND b.valid=1
			AND IsDirect=1
			AND a.cpmainid = b.id AND a.InterViewType IN(1,2) '+@WHERE+'			
			ORDER BY a.adddate DESC	'
		EXEC(@SQL)
	END
	ELSE
	BEGIN
		SET @SQL = '
			INSERT INTO #T1
			SELECT TOP 500 b.ID AS cpmainid,b.Name, b.SecondId, LastLoginDate AS AddDate,1 AS OrderBY 
			FROM cpMainPublish b WITH(NOLOCK),
			CONTAINSTABLE(cpMainPublish, Name, '''+@KeyWord+''', 100) AS a
			WHERE b.Id = a.[Key] '+@WHERE2+'
			AND b.valid=1
			ORDER BY b. LastLoginDate DESC '
			PRINT(@SQL)
		EXEC(@SQL)
		IF NOT EXISTS(SELECT 'x' FROM #T1)
		BEGIN
			SET @SQL = '
				INSERT INTO #T1
				SELECT TOP 500 b.ID AS cpmainid,b.Name, b.SecondId, LastLoginDate AS AddDate,1 AS OrderBY 
				FROM cpMainPublish b WITH(NOLOCK INDEX(IX_cpMainPublish_Name))
				WHERE 1=1 '+@WHERE+'
				AND b.valid=1
				ORDER BY b. LastLoginDate DESC '
				PRINT(@SQL)
			EXEC(@SQL)
		END
	END
	
	DELETE FROM #T1 WHERE cpmainid NOT IN (SELECT Max(cpMainID) FROM #T1 GROUP BY name)
	SELECT @AllCnt = COUNT(*) FROM #T1 
	
	IF @KeyWord <> '' --对临时表 #T1 进行排序 修改最后点评时间
	BEGIN
		UPDATE a 
		SET a.AddDate = b.AddDate,a.OrderBY = b.OrderBY
		FROM #T1 a,(
			SELECT AddDate,CpMainID,2 AS OrderBy 
			FROM  InterView
			WHERE ID IN(SELECT MAX(id) FROM InterView GROUP BY cpmainid) 
		) b
		WHERE a.CpmainID = b.CpMainID
	END
	
	SELECT * ,ROW_NUMBER() OVER( ORDER BY OrderBY DESC,AddDate DESC) AS num INTO #T2 FROM #T1
	
	SELECT *,0 AS cnt,0 AS Score INTO #T3 FROM #T2 WHERE NUM > @PageLowerBound AND NUM <= @PageUpperBound
	
	--修改评价数量
	UPDATE a
	SET a.cnt = b.Num
	FROM #T3 a,(
		SELECT COUNT(*) AS num,CpMainID
		FROM InterView
		WHERE (InterViewType IN (1,2))
		AND CpMainID IN (SELECT CpMainID FROM #T3)
		GROUP BY CpMainID
	)b
	WHERE a.CpMainID = b.CpMainID
		
	--拷贝列
	CREATE TABLE #T5(
		[ID] [int] NOT NULL,
		[CpmainID] [int] NOT NULL,
		[PaMainID] [int] NOT NULL,
		[IP] [varchar](15) NOT NULL,
		[SessionID] [varchar](50) NULL,
		[JobName] [varchar](50) NOT NULL,
		[InterviewDate] [varchar](6) NOT NULL,
		[InterViewResult] [tinyint] NOT NULL,
		[SalaryMonth] [int] NULL,
		[InterViewExperience] [nvarchar](max) NOT NULL,
		[InterviewFeeling] [nvarchar](max) NOT NULL,
		[Title] [nvarchar](50) NOT NULL,
		[AddDate] [smalldatetime] NULL,
		[VerifyMan] [int] NULL,
		[VerifyDate] [smalldatetime] NULL,
		[InterviewType] [int] NULL,
		[ReplyDate] [smalldatetime] NULL,
		[ReplyContent] [nvarchar](max) NULL,
		[ReplyVerifyMan] [int] NULL,
		[ReplyVerifyDate] [smalldatetime] NULL,
		[ReplyVerifyResult] [tinyint] NULL,
		[PraiseCount] [int] NULL,
		[LoginPraiseCount] [int] NULL,
		[IsDirect] [BIT] NULL,
		[rid] [int] NULL
	)
		
	DECLARE @CpCnt INT --公司数量
	SELECT @CpCnt = COUNT(*) FROM #T3
	IF @CpCnt = 1 
	BEGIN
		--取10条点评
		INSERT INTO #T5 
		SELECT * FROM 
		(
		   SELECT *,rid=ROW_NUMBER() OVER(PARTITION BY a.CpmainID ORDER BY a.AddDate DESC)
		   FROM InterView a
		   WHERE  (a.InterViewType IN (1,2))
		   AND CpMainID IN (SELECT CpMainID FROM #T3)
		) AS c
		WHERE c.rid<=10
	END
	ELSE
	BEGIN
		--取2条点评
		INSERT INTO #T5  
		SELECT * FROM 
		(
		   SELECT *,rid=ROW_NUMBER() OVER(PARTITION BY a.CpmainID ORDER BY a.AddDate DESC)
		   FROM InterView a
		   WHERE  (a.InterViewType IN (1,2))
		   AND CpMainID IN (SELECT CpMainID FROM #T3)
		) AS c
		WHERE c.rid<=2
	END
	
	SELECT * FROM #T3  --公司列表
	
	SELECT @AllCnt     --所有公司数
		
	SELECT * FROM #T5  --点评数
	
	DROP TABLE #T5
END


GO
/****** Object:  StoredProcedure [dbo].[ProcInterViewByReplyUpdate]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.20
--创建人：Nick
--说明：面试经历回复
--#####################################################
CREATE PROCEDURE [dbo].[ProcInterViewByReplyUpdate]
(
	@ID INT,
	@ReplyContent NVARCHAR(MAX)
)
AS
BEGIN 
	UPDATE InterView 
	SET ReplyContent = @ReplyContent,
	ReplyDate = GETDATE() ,
	ReplyVerifyResult = NULL ,
	ReplyVerifyDate  = NULL
	WHERE ID = @ID
	AND (ReplyVerifyResult <> 1 OR ReplyVerifyResult IS NULL)
End


GO
/****** Object:  StoredProcedure [dbo].[ProcInterViewCompanyListSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.27
--创建人：Nick
--说明：获取面试经历公司列表
--#####################################################
CREATE PROCEDURE [dbo].[ProcInterViewCompanyListSelect]
(
	@dcRegionID VARCHAR(100),
	@PageNo INT,
	@KeyWord VARCHAR(50)
)
AS
BEGIN TRY
	DECLARE @WHERE VARCHAR(MAX),@JobPlace AS VARCHAR(2000)
	SET @JobPlace = ''
	SET @WHERE = ''
	
	IF CHARINDEX(',',@dcRegionID)>0
	BEGIN
		DECLARE @T_JobPlace AS TABLE(ID INT)
		INSERT INTO @T_JobPlace
		SELECT * FROM dbo.fnSplit(@dcRegionID, ',')
		
		SELECT @JobPlace = (@JobPlace + ' OR b.dcRegionID Like ''' + LTRIM(STR(ID) + '%''')) FROM @T_JobPlace
		
		IF LEN(@JobPlace) > 0
		SET @JobPlace = RIGHT(@JobPlace, LEN(@JobPlace) -4)
		SET @WHERE = @WHERE + '
			AND (' + @JobPlace + ')'
	END
	ELSE
	BEGIN
		SET @WHERE = ' AND (b.dcRegionID Like '''+@dcRegionID+'%'')'
	END
	
	SET @KeyWord = dbo.SafeSQL(ISNULL(@KeyWord, ''))
	
	IF @KeyWord <> ''
	BEGIN
		SET @WHERE = @WHERE+' AND b.Name LIKE  ''%'+@KeyWord+'%'' '
	END
	
	DECLARE @PageSize INT
	SET @PageSize = 5
    DECLARE @PageLowerBound  INT --定义此页的底码
    DECLARE @PageUpperBound  INT --定义此页的顶码
    SET @PageLowerBound = (@PageNo -1) * @pagesize
    SET @PageUpperBound = @PageLowerBound + @pagesize
	
	DECLARE @AllCnt INT
	SET @AllCnt = 0
	DECLARE @SQL NVARCHAR(MAX)
	SET @SQL = N'
		SELECT @All = COUNT(DISTINCT CpMainID) 
		FROM  InterView a,Cpmain b
		WHERE (a.InterViewType IN (1,2))
		AND a.id IN(SELECT MAX(id) FROM InterView GROUP BY cpmainid)
		AND a.CpMainID = b.ID
	'+@WHERE
	print('123')
	exec sp_executesql @SQL,N'@All INT output',@AllCnt output
	IF @AllCnt>500
	BEGIN
		SET @AllCnt = 500
	END
		
	SET @SQL = '
		SELECT TOP 500 cpmainid,b.name,b.secondid,a.AddDate INTO ##T1
		FROM InterView a,cpmain b
		WHERE a.id IN(SELECT MAX(id) FROM InterView GROUP BY cpmainid)
		AND a.cpmainid = b.id AND a.InterViewType IN (1,2)'+@WHERE+'
		ORDER BY a.adddate DESC	'
	print(@SQL)
	EXEC(@SQL)
	
	SELECT * ,ROW_NUMBER() OVER( ORDER BY AddDate DESC) AS num INTO #T2 FROM ##T1

	SELECT *,0 AS cnt INTO #T3 FROM #T2 WHERE NUM > @PageLowerBound AND NUM <= @PageUpperBound

	--修改评价数量
	UPDATE a
	SET a.cnt = b.Num
	FROM #T3 a,(
		SELECT COUNT(*) AS num,CpMainID
		FROM InterView
		WHERE (InterViewType IN (1,2))
		AND CpMainID IN (SELECT CpMainID FROM #T3)
		GROUP BY CpMainID
	)b
	WHERE a.CpMainID = b.CpMainID
		
	SELECT * FROM #T3
	
	SELECT @AllCnt
	SELECT * FROM 
	(
	   SELECT rid=ROW_NUMBER() OVER(PARTITION BY a.CpmainID ORDER BY a.AddDate DESC),*
	   FROM InterView a
	   WHERE  (a.InterViewType IN (1,2))
	   AND CpMainID IN (SELECT CpMainID FROM #T3)
	) AS c
	WHERE c.rid<=2
	
	DROP TABLE ##T1
END TRY
BEGIN CATCH
	DROP TABLE ##T1
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[ProcInterViewHotSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.27
--创建人：Nick
--说明：获取最多面经排行 最佳面经排行
--#####################################################
CREATE PROCEDURE [dbo].[ProcInterViewHotSelect]
(
	@ProvinceID INT
)
AS
BEGIN 
	--最多面经排行
	SELECT * FROM SearchDB..CommentsHot
	WHERE CommentType = 2
	AND TypeID = 1
	AND dcProvinceID = @ProvinceID
	ORDER BY Cnt DESC
	
	--最佳点评排行
	SELECT * FROM SearchDB..CommentsHot
	WHERE CommentType = 2
	AND TypeID = 2
	AND dcProvinceID = @ProvinceID
	ORDER BY Cnt DESC
END


GO
/****** Object:  StoredProcedure [dbo].[ProcInterViewInsert]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.20
--创建人：Nick
--说明：插入面试经历
--#####################################################
CREATE PROCEDURE [dbo].[ProcInterViewInsert]
(
	@CpmainID INT,
	@PaMainID INT,
	@IP VARCHAR(15),
	@SessionID VARCHAR(50),
	@JobName NVARCHAR(50),
	@InterviewDate VARCHAR(6),
	@InterViewResult INT,
	@SalaryMonth INT,
	@InterViewExperience NVARCHAR(MAX),
	@InterviewFeeling NVARCHAR(MAX),
	@Title NVARCHAR(50)
)
AS
BEGIN 
	DECLARE @MemberType INT
	SELECT @MemberType = MemberType FROM CpMain WHERE ID  = @CpmainID
	IF @MemberType > 1
	BEGIN
		INSERT INTO InterView (CpmainID,PaMainID,IP,SessionID,JobName,InterviewDate,InterViewResult,SalaryMonth,
			InterViewExperience,InterviewFeeling,Title,AddDate,PraiseCount,LoginPraiseCount,InterviewType,IsDirect)
		SELECT ID,@PaMainID,@IP,@SessionID,@JobName,@InterviewDate,@InterViewResult,@SalaryMonth,
			@InterViewExperience,@InterviewFeeling,@Title,GETDATE(),0,0,0,0
		FROM CPMAIN 
		WHERE NAME = (
			SELECT Name FROM CpMain WHERE ID = @CpmainID)
		AND MemberType > 1
		AND ID <> @CpmainID
	END
	
	INSERT INTO InterView (CpmainID,PaMainID,IP,SessionID,JobName,InterviewDate,InterViewResult,SalaryMonth,
		InterViewExperience,InterviewFeeling,Title,AddDate,PraiseCount,LoginPraiseCount,InterviewType,IsDirect)
	VALUES(@CpmainID,@PaMainID,@IP,@SessionID,@JobName,@InterviewDate,@InterViewResult,@SalaryMonth,
		@InterViewExperience,@InterviewFeeling,@Title,GETDATE(),0,0,0,1)
End


GO
/****** Object:  StoredProcedure [dbo].[ProcInterviewRecordByCaMainIDSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2014.10.29
--创建人：John
--说明：获取企业面试大厅的记录
--#####################################################
CREATE PROCEDURE [dbo].[ProcInterviewRecordByCaMainIDSelect]
(
	@caMainID INT
)
AS
BEGIN
	SELECT a.*,c.Name paName,d.Name caName 
	FROM ViInterviewRecord a 
		LEFT JOIN viRoom b ON b.ID = a.viRoomID 
		LEFT JOIN paMain c ON c.ID = a.paMainID 
		LEFT JOIN caMain d ON d.ID = b.caMainID 
	WHERE a.Begindate IS NOT NULL 
	AND b.caMainID = @caMainID 
	ORDER BY a.Id DESC
END


GO
/****** Object:  StoredProcedure [dbo].[ProcInterviewReplyByIDUpdate]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.18
--创建人：Nick
--说明：根据ID修改面试回复信息
--#####################################################
CREATE PROCEDURE [dbo].[ProcInterviewReplyByIDUpdate]
(
	@ID INT,
	@ReplyContent NVARCHAR(MAX),
	@ReplyVerifyMan INT,
	@ReplyVerifyResult INT
)
AS
BEGIN
	UPDATE Interview
	SET ReplyContent = @ReplyContent,
		ReplyVerifyMan = @ReplyVerifyMan,
		ReplyVerifyDate = GETDATE(),
		ReplyVerifyResult = @ReplyVerifyResult
	WHERE ID = @ID
END


GO
/****** Object:  StoredProcedure [dbo].[ProcInterviewSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.18
--创建人：Nick
--说明：查询 面试经历信息 用于后台审核
--#####################################################
CREATE PROCEDURE [dbo].[ProcInterviewSelect]
(
	@Type INT, --1 待审核 面试经历 2 最近审核 面试经历 3待审核面试经历回复 4最近审核 面试经历回复
	@Where VARCHAR(MAX)
)
AS
BEGIN 
	DECLARE @SQL VARCHAR(MAX)
	IF @Type = 1
	BEGIN
		SET @SQL = '
			SELECT a.*,b.name AS CpName ,b.RegDate,
			CASE a.PamainID
			WHEN 0 THEN IP
			ELSE (SELECT Name FROM PaMain WHERE ID = a.PaMainID)
			END AS PaName
			FROM Interview a,CpMain b
			WHERE VerifyDate IS NULL
			AND a.IsDirect = 1
			AND a.CpMainID = b.ID '+@Where+'
			ORDER BY AddDate DESC '
	END
	ELSE IF @Type = 2
	BEGIN
		SET @SQL = '
			SELECT TOP 200 a.*,b.name AS CpName ,b.RegDate,
			CASE a.PamainID
			WHEN 0 THEN IP
			ELSE (SELECT Name FROM PaMain WHERE ID = a.PaMainID)
			END AS PaName
			FROM Interview a,CpMain b
			WHERE VerifyDate IS NOT NULL
			AND a.CpMainID = b.ID '+@Where+'
			ORDER BY VerifyDate DESC '
	END
	ELSE IF @Type = 3
	BEGIN
		SET @SQL = '
				SELECT a.*,b.name AS CpName ,b.RegDate,
				CASE a.PamainID
				WHEN 0 THEN IP
				ELSE (SELECT Name FROM PaMain WHERE ID = a.PaMainID)
				END AS PaName
				FROM Interview a,CpMain b
				WHERE ReplyVerifyDate IS NULL
				AND a.CpMainID = b.ID '+@Where+'
				ORDER BY ReplyDate DESC '
	END
	ELSE IF @Type = 4
	BEGIN
		SET @SQL = '
			SELECT TOP 200 a.*,b.name AS CpName ,b.RegDate,
			CASE a.PamainID
			WHEN 0 THEN IP
			ELSE (SELECT Name FROM PaMain WHERE ID = a.PaMainID)
			END AS PaName
			FROM Interview a,CpMain b
			WHERE ReplyVerifyDate IS NOT NULL
			AND a.CpMainID = b.ID '+@Where+'
			ORDER BY ReplyVerifyDate DESC '
	END
	EXEC(@SQL)
END


GO
/****** Object:  StoredProcedure [dbo].[ProcIp_BlackInsert]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE procedure [dbo].[ProcIp_BlackInsert]
AS
BEGIN
	return
	SELECT top 0 * into #t from ip_black
	insert into #t
	select top 199 ip, 'sean add 0706', getdate(), 2, '大量访问' from synueolog with(nolock) where adddate > dateadd(minute, -60, getdate())  group by ip order by count(*) desc
	delete #t where ip in(select loginip from paloginlog where adddate > getdate() -1)
	delete #t where ip in(select loginip from caloginlog where adddate > getdate() -1)
	delete #t where ip in(select ip from ip_black)
	insert into ip_black
	select distinct ip,description,getdate(),type,remarks FROM #t order by ip
	delete a from ip_black a, ip_white b where charindex(b.ip, a.ip) > 0
	delete ip_black where ip in('218.201.144.184','111.16.244.80','27.204.87.36','223.96.158.225')
END

GO
/****** Object:  StoredProcedure [dbo].[procIp_BlackSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.03
--创建人：Nick
--说明：ip黑名单
--#####################################################
CREATE PROCEDURE [dbo].[procIp_BlackSelect]
AS
BEGIN TRY
	SELECT * FROM ip_Black With(Nolock) ORDER BY ID
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[ProcIp_WhiteByBatchUpdate]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [dbo].[ProcIp_WhiteByBatchUpdate]
AS
BEGIN
	SELECT ip, COUNT(*) cnt INTO #t FROM IpVisitAll GROUP BY ip
	TRUNCATE TABLE IpVisitAll

	SELECT b.ip, sum(a.cnt) Cnt
	INTO #1
	FROM #t a, ip_white b
	WHERE a.ip LIKE b.ip + '%'
	GROUP BY b.ip
	ORDER BY b.ip

	UPDATE a
	SET a.VisitNum = a.VisitNum + b.Cnt, 
		a.VisitNum_ThisMonth = a.VisitNum_ThisMonth + b.Cnt
	FROM Ip_White a, #1 b	
	WHERE a.ip = b.ip
END
GO
/****** Object:  StoredProcedure [dbo].[procIp_WhiteSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.03
--创建人：Nick
--说明：ip白名单
--#####################################################
CREATE PROCEDURE [dbo].[procIp_WhiteSelect]
AS
BEGIN TRY
	SELECT * FROM ip_White With(Nolock) 
	ORDER BY ID
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[ProcIp_WhiteUpdate]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[ProcIp_WhiteUpdate]
(
	@Ip VARCHAR(15)
)
AS
SET NOCOUNT ON
BEGIN
	INSERT INTO IpVisitAll(Ip) SELECT @Ip
	--UPDATE Ip_White SET VisitNum = VisitNum + 1, VisitNum_ThisMonth = VisitNum_ThisMonth + 1 
	--WHERE CHARINDEX(ip, @Ip) = 1
END	

GO
/****** Object:  StoredProcedure [dbo].[procIpJobViewInsert]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--*********************************************************
--sean 2015-10-12  职位页面频繁访问的不显示联系方式
--*********************************************************
CREATE PROCEDURE [dbo].[procIpJobViewInsert]
(
	@Ip VARCHAR(50),
	@JobId INT,
	@paMainId INT
)
AS
SET NOCOUNT ON
BEGIN
	INSERT INTO IpJobView(Ip, JobId, paMainId) SELECT @Ip, @JobId, @paMainId
	
	IF EXISTS(SELECT 'x' FROM IpJobViewRefuse WITH(NOLOCK) WHERE Ip = @Ip)
		SELECT 'x'
	ELSE
		SELECT 'x' FROM IpJobViewRefuse WITH(NOLOCK) WHERE paMainId = @paMainId
END

GO
/****** Object:  StoredProcedure [dbo].[procIpLogInsert]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.03
--创建人：Nick
--说明：插入iplog
--#####################################################
CREATE PROCEDURE [dbo].[procIpLogInsert]
	@RemoteAddr VARCHAR(50),
	@UserAgent VARCHAR(200),
	@ServerName VARCHAR(100)
AS
BEGIN TRY
	INSERT INTO iplog (ip,http_user_agent,type,path_info) 
	VALUES (@remoteAddr, @userAgent, 0, @ServerName)
	RETURN 1
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[ProcIpPlaceSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2014.10.31
--创建人：John
--说明：获取IP对应的地区
--#####################################################
CREATE PROCEDURE [dbo].[ProcIpPlaceSelect]
(
	@ip BIGINT
)
AS
BEGIN
	SELECT TOP 1 * FROM dcIpPlace WITH(NOLOCK INDEX(IX_dcIpPlace_IpStart)) WHERE IPStart <= @ip ORDER BY IPStart DESC
END


GO
/****** Object:  StoredProcedure [dbo].[procIpReportByIDUpdate]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.31
--创建人：Nick
--说明：更新ipreport
--#####################################################
CREATE PROCEDURE [dbo].[procIpReportByIDUpdate]
(
	@ID INT,
	@IP VARCHAR(20)
)
AS
BEGIN TRY
	UPDATE ipreport SET ip=@IP,refresh=getdate() WHERE id= @ID
	RETURN 1
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[procIsWorkDateSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.30
--创建人：Nick
--说明：判断是不是工作日
--#####################################################
CREATE PROCEDURE [dbo].[procIsWorkDateSelect]
AS
BEGIN TRY
	SELECT oadb.dbo.isworkdate(GETDATE()) IsWorkDate
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[procIvgt_AnswerByIDIpUpdate]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.10
--创建人：NICK
--说明：修改调查文档点击次数
--#####################################################
CREATE PROCEDURE [dbo].[procIvgt_AnswerByIDIpUpdate]
(
    @ID INT,
	@Ip VARCHAR(15)
)
AS
SET NOCOUNT ON
BEGIN
	INSERT INTO Ivgt_AnswerLog SELECT @ip, GETDATE()
	IF (SELECT COUNT(*) FROM Ivgt_AnswerLog WITH(NOLOCK) 
		WHERE Ip = @ip AND AddDate > DATEADD(MINUTE, -240, GETDATE())) > 50
		RETURN 1

	UPDATE ivgt_answer SET clicknum = clicknum + 1 WHERE id = @ID

	RETURN 1
END
GO
/****** Object:  StoredProcedure [dbo].[procIvgt_AnswerByIDUpdate]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.10
--创建人：NICK
--说明：修改调查文档点击次数
--#####################################################
CREATE PROCEDURE [dbo].[procIvgt_AnswerByIDUpdate]
(
	@ID INT
)
AS
BEGIN
	UPDATE ivgt_answer SET clicknum=clicknum+1 WHERE id=@ID
	RETURN 1
END


GO
/****** Object:  StoredProcedure [dbo].[procIvgt_AnswerByQuesionIDSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.10
--创建人：NICK
--说明：
--#####################################################
CREATE PROCEDURE [dbo].[procIvgt_AnswerByQuesionIDSelect]
(
	@IvgID INT
)
AS
BEGIN
	SELECT id,title,clicknum,showType 
	FROM ivgt_answer WITH(NOLOCK) 
	WHERE questionid=@IvgID 
	ORDER BY power
END


GO
/****** Object:  StoredProcedure [dbo].[procIvgt_AnswerTextInsert]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
--#####################################################
--创建时间：2014.11.10
--创建人：NICK
--说明：ivgt_answerText插入
--Harry:增加返回id 2015-12-11
--#####################################################
CREATE PROCEDURE [dbo].[procIvgt_AnswerTextInsert]
(
	@ID INT,
	@Text VARCHAR(500)
)
AS
SET NOCOUNT ON
BEGIN
	IF dbo.HaveChinese(@Text) = 0
		SET @Text = '无'

	INSERT INTO ivgt_answerText(answerid, answerText) VALUES(@ID, @Text)
	SELECT @@IDENTITY AS ID
END 

GO
/****** Object:  StoredProcedure [dbo].[procIvgt_InvestigationBy51rcSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.10
--创建人：Nick
--说明：51rc 调查
--#####################################################
CREATE PROCEDURE [dbo].[procIvgt_InvestigationBy51rcSelect]
AS
BEGIN TRY
	SELECT TOP 3 id,title,adddate,enddate,clicknum,reporturl,reporttitle,description 
	FROM ivgt_investigation WITH(NOLOCK) 
	WHERE homepagesee=1 
	ORDER BY adddate desc
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[procIvgt_investigationByHomePageList]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--创建人 Lambo	
--20101009
--用于首页用户调查
--修改：增加exlink harry 2017-8-5
CREATE  PROCEDURE [dbo].[procIvgt_investigationByHomePageList] 
(
	@ProvinceID SMALLINT
)
AS
BEGIN
	SET NOCOUNT ON
	SELECT TOP 1 ImageFile,alt FROM fpHomePageImage WITH(NOLOCK)
	WHERE ImageType = 3
	AND dcProvinceID = LEFT(@ProvinceID, 2)
	ORDER BY AddDate DESC

	SELECT TOP 15 id newIDs,PreID id, title, description, reporturl, type, reporturl, reporttitle, addDate, exlink
	FROM SearchDb..HPInvestigationDay WITH(NOLOCK)
	WHERE 
	 provinceID =LEFT(@ProvinceID, 2)
	ORDER BY newIDs
	
	SET NOCOUNT OFF
END

GO
/****** Object:  StoredProcedure [dbo].[procIvgt_investigationByHomepageSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--修改harry
--增加exlink harry 2017-8-5
CREATE PROCEDURE [dbo].[procIvgt_investigationByHomepageSelect] 
(
	@province_id SMALLINT
)
AS
BEGIN
	SELECT TOP 1 id, 99 ProvinceId, title, description, AddDate, exLink
	FROM SearchDb..ivgt_investigationDay WITH(NOLOCK)
	WHERE ProvinceID = @Province_ID
END


GO
/****** Object:  StoredProcedure [dbo].[procIvgt_InvestigationBYIDSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[procIvgt_InvestigationBYIDSelect] 
(
	@ID INT
)
AS
BEGIN
	SELECT * FROM Ivgt_Investigation WITH(NOLOCK)
	WHERE ID = @ID
	SELECT * FROM Ivgt_Question WITH(NOLOCK)
	WHERE InvestID = @ID
	ORDER BY ID
	SELECT a.* FROM Ivgt_Answer a WITH(NOLOCK), Ivgt_Question b WITH(NOLOCK)
	WHERE b.InvestID = @ID
	AND a.QuestionID = b.id
	ORDER BY a.QuestionID,a.ID
END














GO
/****** Object:  StoredProcedure [dbo].[procIvgt_investigationByIDUpdate]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.10
--创建人：NICK
--说明：ivgt_investigation修改点击次数
--#####################################################
CREATE PROCEDURE [dbo].[procIvgt_investigationByIDUpdate]
(
	@ID INT
)
AS
BEGIN
	UPDATE ivgt_investigation SET clicknum=clicknum+1 WHERE id = @ID
	RETURN 1
END


GO
/****** Object:  StoredProcedure [dbo].[procIvgt_InvestigationByProvinceIDSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.5
--创建人：NICK
--说明：根据省份ID得到用户调查列表
--修改：harry 2017-8-5 增加exlink
--#####################################################
CREATE PROCEDURE [dbo].[procIvgt_InvestigationByProvinceIDSelect]
(
	@ProvinceID VARCHAR(20)
)
AS
BEGIN
	IF @ProvinceID = '' OR @ProvinceID = '0'
	BEGIN
		SELECT id, title, reporturl, reporttitle, ReportType, exLink
		FROM ivgt_investigation WITH(NOLOCK)	
		WHERE ENDdate < GETDATE() 
		AND homepagesee = 1 
		ORDER BY ENDdate DESC
	END
	ELSE
	BEGIN
		SELECT id, title, reporturl, reporttitle, ReportType, exLink 
		FROM ivgt_investigation WITH(NOLOCK)	
		WHERE ENDdate < GETDATE() 
		AND province LIKE '%'+@ProvinceID+'%' 
		AND homepagesee = 1 
		ORDER BY ENDdate DESC
	END
END

 
GO
/****** Object:  StoredProcedure [dbo].[procIvgt_InvestigationNotEndSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[procIvgt_InvestigationNotEndSelect] 
(
	@ProvinceID VARCHAR(2),
	@Type SMALLINT
)
AS
BEGIN
	SELECT ID,Title FROM Ivgt_Investigation WITH(NOLOCK)
	WHERE ENDDate > GETDATE()
	AND Province LIKE '%' + @ProvinceID+'%' 
	AND Type=@Type
	ORDER BY ID DESC
END














GO
/****** Object:  StoredProcedure [dbo].[procIvgt_InvestigationSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[procIvgt_InvestigationSelect] 
(
	@province_id VARCHAR(2),
	@manid INTeger,
	@type SMALLINT
)
as
BEGIN
	SELECT id,title FROM Ivgt_investigation WITH(NOLOCK)
	WHERE ENDdate>GETDATE() 
	AND province like '%'+@province_id+'%' 
	AND type=@type
	ORDER BY adddate
END














GO
/****** Object:  StoredProcedure [dbo].[procIvgt_QuestionByInvestIDSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.10
--创建人：NICK
--说明：
--#####################################################
CREATE PROCEDURE [dbo].[procIvgt_QuestionByInvestIDSelect]
(
	@IvgID INT
)
AS
BEGIN
	SELECT id,title,type 
	FROM ivgt_question WITH(NOLOCK) 
	WHERE investid=@IvgID 
	ORDER BY power
END


GO
/****** Object:  StoredProcedure [dbo].[ProcIvrDayReportInsert]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--修改人：harry 2016-3-31
--修改冷客户顾问部deptid=42,时间按照all计算
CREATE PROCEDURE [dbo].[ProcIvrDayReportInsert]
AS
BEGIN
	DECLARE @YearMonth VARCHAR(8)
	IF DATEPART(DAY, GETDATE()) > 25
		SET @YearMonth = CONVERT(VARCHAR(6), GETDATE() + 10, 112)
	ELSE
		SET @YearMonth = CONVERT(VARCHAR(6), GETDATE(), 112)

	--IF NOT EXISTS(SELECT 'x' FROM Oadb..WorkDate WHERE WorkType = 1 AND Workdate = CONVERT(VARCHAR(8), GETDATE(), 112))
	--	RETURN
	INSERT IvrDayReport(CountDate, ManagerUserId, Status, Name, DeptID, RealWorkTime)
	SELECT CONVERT(VARCHAR(8), GETDATE(), 112), a.ConsultantId, 0, b.Name, b.DeptId,8
	FROM Consultant_Manageruser_Month a, ManagerUser b
	WHERE b.id = a.ConsultantId
	AND a.YearMonth = @YearMonth
	AND b.Id NOT IN(SELECT ManagerUserId FROM IvrDayReport WHERE CountDate =CONVERT(VARCHAR(8),  GETDATE(), 112))
	AND b.ID <> 762

	INSERT IvrDayReport(CountDate, ManagerUserId, Status, Name, DeptID, RealWorkTime)
	SELECT CONVERT(VARCHAR(8),  GETDATE(), 112), Id, 0, Name, DeptId, 8
	FROM ManagerUser 
	WHERE DeptID =42 AND STatus < 3
	AND LEN(Name) < 5
	AND  Id NOT IN(SELECT ManagerUserId FROM IvrDayReport WHERE CountDate =CONVERT(VARCHAR(8),  GETDATE(), 112))
	AND ID <> 762

	INSERT IvrDayReport(CountDate, ManagerUserId, Status, Name, DeptID, RealWorkTime)
	SELECT CONVERT(VARCHAR(8),  GETDATE(), 112), Id, 0, Name, DeptId, 8
	FROM ManagerUser 
	WHERE DeptID in (50,52) AND STatus < 3
	AND  Id NOT IN(SELECT ManagerUserId FROM IvrDayReport WHERE CountDate =CONVERT(VARCHAR(8),  GETDATE(), 112))

	INSERT IvrDayReport(CountDate, ManagerUserId, Status, Name, DeptID, RealWorkTime)
	SELECT CONVERT(VARCHAR(8),  GETDATE(), 112), Id, 0, Name, DeptId, 8
	FROM ManagerUser WHERE DeptID BETWEEN 180 AND 184 AND STatus < 3
	
	UPDATE a
	SET a.RealNumber = CallinNum_up40 + CalloutNum_up40,
		a.RealMinute = (CallinInterval_Up40 + CalloutInterval_Up40) / 60
	FROM IvrDayReport a, ivrList_Day b
	WHERE a.CountDate = b.CountDate
	AND a.ManagerUserId = b.ManagerUserId
	AND a.RealNumber = 0
	AND a.CountDate > CONVERT(VARCHAR(8), GETDATE() - 2, 112)
	AND a.DeptID!=42--Harry2016-3-30 
	AND a.DeptID != 50
	
	--Harry begin
	UPDATE a
	SET a.RealNumber = CallinNum_all + CalloutNum_all,
		a.RealMinute = (CallinInterval_all + CalloutInterval_all) / 60
	FROM IvrDayReport a, ivrList_Day b
	WHERE a.CountDate = b.CountDate
	AND a.ManagerUserId = b.ManagerUserId
	AND a.RealNumber = 0
	AND a.CountDate > CONVERT(VARCHAR(8), GETDATE() - 2, 112)
	AND (a.DeptID=42	OR a.DeptID = 50 )
	--Harry end

	UPDATE IvrDayReport
	SET RealNumber = 0, RealMinute = 0
	FROM IvrDayReport
	WHERE CountDate > CONVERT(VARCHAR(8), GETDATE() - 2, 112)
	AND RealNumber IS NULL
END

GO
/****** Object:  StoredProcedure [dbo].[ProcIvrList_DayInsert]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ProcIvrList_DayInsert]
AS
BEGIN
	DECLARE @begindate varchar(50), @enddate varchar(50),
		@id int, @name nvarchar(50), @status tinyint,
		@CallinNum_all smallint, @CallinInterval_all int,
		@CallinNum_up30 smallint, @CallinInterval_up30 int,
		@CallinNum_up40 smallint, @CallinInterval_up40 int,
		@CallinNum_up60 smallint, @CallinInterval_up60 int,
		@CallinNum_up180 smallint, @CallinInterval_up180 int,
		@CallinNum_up600 smallint, @CallinInterval_up600 int

	DECLARE @CalloutNum_all smallint, @CalloutInterval_all int,
		@CalloutNum_up30 smallint, @CalloutInterval_up30 int,
		@CalloutNum_up40 smallint, @CalloutInterval_up40 int,
		@CalloutNum_up60 smallint, @CalloutInterval_up60 int,
		@CalloutNum_up180 smallint, @CalloutInterval_up180 int,
		@CalloutNum_up600 smallint, @CalloutInterval_up600 int

	DECLARE @Callin_notdeal smallint, @Callin_leak smallint,
		@Callin_queueleak smallint, @Callin_blacklist smallint,
		@Callin_voicemail smallint, @Callout_notdeal smallint,
		@Callout_leak smallint, @Callout_queueleak smallint,
		@Callout_blacklist smallint, @Callout_voicemail smallint

	SET @begindate=ltrim(rtrim(str(year(getdate()))))+'-'+ltrim(rtrim(str(month(getdate()))))+'-'+ltrim(rtrim(str(day(getdate()))))+' 00:00:00'
	SET @enddate=ltrim(rtrim(str(year(getdate()))))+'-'+ltrim(rtrim(str(month(getdate()))))+'-'+ltrim(rtrim(str(day(getdate()))))+' 23:59:59'

	DECLARE manageruser CURSOR FOR 
	  SELECT id, name, status from manageruser with(nolock) where (status=1 or status=2) and (type=1 or type=5) order by id

	OPEN manageruser

	FETCH NEXT FROM  manageruser INTO @id, @name, @status

	WHILE @@FETCH_STATUS = 0
	BEGIN
	  BEGIN TRANSACTION
		SELECT @CallinNum_all=count(1) from IvrList with(nolock) 
		  where (CallType='normal'or CallType='transfer') and State='dealing' and endtime>@begindate and endtime<@enddate and exten=@id

		SELECT @CallinInterval_all=SUM(datediff(s, begintime, endtime)) from IvrList with(nolock) 
		  where (CallType='normal'or CallType='transfer') and State='dealing' and endtime>@begindate and endtime<@enddate and exten=@id
		if @CallinInterval_all is null 
		  set @CallinInterval_all=0

		SELECT @CallinNum_up30=count(1) from IvrList with(nolock) 
		  where (CallType='normal'or CallType='transfer') and State='dealing' and endtime>@begindate and endtime<@enddate 
		  and datediff(s, begintime, endtime)>=30 and exten=@id

		SELECT @CallinInterval_up30=SUM(datediff(s, begintime, endtime)) from IvrList with(nolock) 
		  where (CallType='normal'or CallType='transfer') and State='dealing' and endtime>@begindate and endtime<@enddate 
		  and datediff(s, begintime, endtime)>=30 and exten=@id

		if @CallinInterval_up30 is null 
		  set @CallinInterval_up30=0
		
		SELECT @CallinNum_up40=count(1) from IvrList with(nolock) 
		  where (CallType='normal'or CallType='transfer') and State='dealing' and endtime>@begindate and endtime<@enddate 
		  and datediff(s, begintime, endtime)>=40 and exten=@id

		SELECT @CallinInterval_up40=SUM(datediff(s, begintime, endtime)) from IvrList with(nolock) 
		  where (CallType='normal'or CallType='transfer') and State='dealing' and endtime>@begindate and endtime<@enddate 
		  and datediff(s, begintime, endtime)>=40 and exten=@id

		if @CallinInterval_up40 is null 
		  set @CallinInterval_up40=0

		SELECT @CallinNum_up60=count(1) from IvrList with(nolock) 
		  where (CallType='normal'or CallType='transfer') and State='dealing' and endtime>@begindate and endtime<@enddate 
		  and datediff(s, begintime, endtime)>=60 and exten=@id

		SELECT @CallinInterval_up60=SUM(datediff(s, begintime, endtime)) from IvrList with(nolock) 
		  where (CallType='normal'or CallType='transfer') and State='dealing' and endtime>@begindate and endtime<@enddate 
		  and datediff(s, begintime, endtime)>=60 and exten=@id

		if @CallinInterval_up60 is null 
		  set @CallinInterval_up60=0

		SELECT @CallinNum_up180=count(1) from IvrList with(nolock) 
		  where (CallType='normal'or CallType='transfer') and State='dealing' and endtime>@begindate and endtime<@enddate 
		  and datediff(s, begintime, endtime)>=180 and exten=@id

		SELECT @CallinInterval_up180=SUM(datediff(s, begintime, endtime)) from IvrList with(nolock) 
		  where (CallType='normal'or CallType='transfer') and State='dealing' and endtime>@begindate and endtime<@enddate 
		  and datediff(s, begintime, endtime)>=180 and exten=@id

		if @CallinInterval_up180 is null 
		  set @CallinInterval_up180=0

		SELECT @CallinNum_up600=count(1) from IvrList with(nolock) 
		  where (CallType='normal'or CallType='transfer') and State='dealing' and endtime>@begindate and endtime<@enddate 
		  and datediff(s, begintime, endtime)>=600 and exten=@id

		SELECT @CallinInterval_up600=SUM(datediff(s, begintime, endtime)) from IvrList with(nolock) 
		  where (CallType='normal'or CallType='transfer') and State='dealing' and endtime>@begindate and endtime<@enddate 
		  and datediff(s, begintime, endtime)>=600 and exten=@id

		if @CallinInterval_up600 is null 
		  set @CallinInterval_up600=0

		SELECT @CalloutNum_all=count(1) from IvrList with(nolock) 
		  where CallType='dialout' and State='dealing' and endtime>@begindate and endtime<@enddate and exten=@id

		SELECT @CalloutInterval_all=SUM(datediff(s, begintime, endtime)) from IvrList with(nolock) 
		  where CallType='dialout' and State='dealing' and endtime>@begindate and endtime<@enddate and exten=@id

		if @CalloutInterval_all is null 
		  set @CalloutInterval_all=0

		SELECT @CalloutNum_up30=count(1) from IvrList with(nolock) 
		  where CallType='dialout' and State='dealing' and endtime>@begindate and endtime<@enddate 
		  and datediff(s, begintime, endtime)>=30 and exten=@id

		SELECT @CalloutInterval_up30=SUM(datediff(s, begintime, endtime)) from IvrList with(nolock) 
		  where CallType='dialout' and State='dealing' and endtime>@begindate and endtime<@enddate 
		  and datediff(s, begintime, endtime)>=30 and exten=@id

		if @CalloutInterval_up30 is null 
		  set @CalloutInterval_up30=0

		SELECT @CalloutNum_up40=count(1) from IvrList with(nolock) 
		  where CallType='dialout' and State='dealing' and endtime>@begindate and endtime<@enddate 
		  and datediff(s, begintime, endtime)>=40 and exten=@id

		SELECT @CalloutInterval_up40=SUM(datediff(s, begintime, endtime)) from IvrList with(nolock) 
		  where CallType='dialout' and State='dealing' and endtime>@begindate and endtime<@enddate 
		  and datediff(s, begintime, endtime)>=40 and exten=@id

		if @CalloutInterval_up40 is null 
		  set @CalloutInterval_up40=0

		SELECT @CalloutNum_up60=count(1) from IvrList with(nolock) 
		  where CallType='dialout' and State='dealing' and endtime>@begindate and endtime<@enddate 
		  and datediff(s, begintime, endtime)>=60 and exten=@id

		SELECT @CalloutInterval_up60=SUM(datediff(s, begintime, endtime)) from IvrList with(nolock) 
		  where CallType='dialout' and State='dealing' and endtime>@begindate and endtime<@enddate 
		  and datediff(s, begintime, endtime)>=60 and exten=@id

		if @CalloutInterval_up60 is null 
		  set @CalloutInterval_up60=0

		SELECT @CalloutNum_up180=count(1) from IvrList with(nolock) 
		  where CallType='dialout' and State='dealing' and endtime>@begindate and endtime<@enddate 
		  and datediff(s, begintime, endtime)>=180 and exten=@id

		SELECT @CalloutInterval_up180=SUM(datediff(s, begintime, endtime)) from IvrList with(nolock) 
		  where CallType='dialout' and State='dealing' and endtime>@begindate and endtime<@enddate 
		  and datediff(s, begintime, endtime)>=180 and exten=@id

		if @CalloutInterval_up180 is null 
		  set @CalloutInterval_up180=0

		SELECT @CalloutNum_up600=count(1) from IvrList with(nolock) 
		  where CallType='dialout' and State='dealing' and endtime>@begindate and endtime<@enddate 
		  and datediff(s, begintime, endtime)>=600 and exten=@id

		SELECT @CalloutInterval_up600=SUM(datediff(s, begintime, endtime)) from IvrList with(nolock) 
		  where CallType='dialout' and State='dealing' and endtime>@begindate and endtime<@enddate 
		  and datediff(s, begintime, endtime)>=600 and exten=@id

		if @CalloutInterval_up600 is null 
		  set @CalloutInterval_up600=0

		SELECT @Callin_notdeal=count(1) from IvrList with(nolock) 
		  where CallType='normal' and State='notdeal' and endtime>@begindate and endtime<@enddate and exten=@id

		SELECT @Callin_leak=count(1) from IvrList with(nolock) 
		  where CallType='normal' and State='leak' and endtime>@begindate and endtime<@enddate and exten=@id

		SELECT @Callin_queueleak=count(1) from IvrList with(nolock) 
		  where CallType='normal' and State='queueleak' and endtime>@begindate and endtime<@enddate and exten=@id

		SELECT @Callin_blacklist=count(1) from IvrList with(nolock) 
		  where CallType='normal' and State='blacklist' and endtime>@begindate and endtime<@enddate and exten=@id

		SELECT @Callin_voicemail=count(1) from IvrList with(nolock) 
		  where CallType='normal' and State='voicemail' and endtime>@begindate and endtime<@enddate and exten=@id

		SELECT @Callout_notdeal=count(1) from IvrList with(nolock) 
		  where CallType='dialout' and State='notdeal' and endtime>@begindate and endtime<@enddate and exten=@id

		SELECT @Callout_leak=count(1) from IvrList with(nolock) 
		  where CallType='dialout' and State='leak' and endtime>@begindate and endtime<@enddate and exten=@id

		SELECT @Callout_queueleak=count(1) from IvrList with(nolock) 
		  where CallType='dialout' and State='queueleak' and endtime>@begindate and endtime<@enddate and exten=@id

		SELECT @Callout_blacklist=count(1) from IvrList with(nolock) 
		  where CallType='dialout' and State='blacklist' and endtime>@begindate and endtime<@enddate and exten=@id

		SELECT @Callout_voicemail=count(1) from IvrList with(nolock) 
		  where CallType='dialout' and State='voicemail' and endtime>@begindate and endtime<@enddate and exten=@id


		insert into Ivrlist_day (countdate, manageruserid, name, status, CallinNum_all, CallinInterval_all, 
		  CallinNum_up30, CallinInterval_up30, CallinNum_up40, CallinInterval_up40, CallinNum_up60, CallinInterval_up60, CallinNum_up180, CallinInterval_up180, 
		  CallinNum_up600, CallinInterval_up600, 
		  CalloutNum_all, CalloutInterval_all, 
		  CalloutNum_up30, CalloutInterval_up30, CalloutNum_up40, CalloutInterval_up40, CalloutNum_up60, CalloutInterval_up60, CalloutNum_up180, CalloutInterval_up180, 
		  CalloutNum_up600, CalloutInterval_up600, Callin_notdeal, Callin_leak, Callin_queueleak, Callin_blacklist, Callin_voicemail, 
		  Callout_notdeal, Callout_leak, Callout_queueleak, Callout_blacklist, Callout_voicemail) 
		  values ((year(getdate())*10000+month(getdate())*100+day(getdate())), @id, @name, @status, 
		  @CallinNum_all, @CallinInterval_all, 
		  @CallinNum_up30, @CallinInterval_up30, @CallinNum_up40, @CallinInterval_up40, @CallinNum_up60, @CallinInterval_up60, @CallinNum_up180, @CallinInterval_up180, 
		  @CallinNum_up600, @CallinInterval_up600, 
		  @CalloutNum_all, @CalloutInterval_all, 
		  @CalloutNum_up30, @CalloutInterval_up30, @CalloutNum_up40, @CalloutInterval_up40, @CalloutNum_up60, @CalloutInterval_up60, @CalloutNum_up180, 
		  @CalloutInterval_up180, 
		  @CalloutNum_up600, @CalloutInterval_up600, @Callin_notdeal, @Callin_leak, @Callin_queueleak, @Callin_blacklist, @Callin_voicemail, 
		  @Callout_notdeal, @Callout_leak, @Callout_queueleak, @Callout_blacklist, @Callout_voicemail)

	  COMMIT TRANSACTION
	  FETCH NEXT FROM  manageruser INTO @id, @name, @status
	END
	CLOSE manageruser
	DEALLOCATE manageruser
END

GO
/****** Object:  StoredProcedure [dbo].[ProcIvrList_DaySelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--Edit by 2014-12-17,修改Coefficient为：折算后个数/100+折算后时长/260
--修改：冷客户顾问部 电话量系数指标是80个，100分钟-harry2017-4-27
CREATE PROCEDURE [dbo].[ProcIvrList_DaySelect]
(
	@QueryType TINYINT,	--1：南北方个人；2：山东个人；3：客服个人；4：所有部门对比；5：部门查询
	@BeginDate DATETIME, --20140505
	@EndDate DATETIME,	--20140510
	@TimeType TINYINT,		--0:不选择； 1:30秒以上;2:1分钟以上;3:3分钟以上;4:10分钟以上;
	@CallType TINYINT,		--0:不选择；  1:呼入； 2：呼出
	--@Region TINYINT,		--0:不选择； 1：北方； 2：南方； 3：山东
	@DeptId INT			--0:不选择； 其他见dept
)
AS
SET NOCOUNT ON
--insert a2 select @QueryType, @BeginDate, @EndDate, @TimeType, @CallType, @DeptId
BEGIN
	--转换时间
	DECLARE @BDate VARCHAR(8), @EDate VARCHAR(8), 
		@Sql VARCHAR(MAX), @CallNumber VARCHAR(100), @CallInterval VARCHAR(100)

	SELECT @BDate = CONVERT(VARCHAR(8), @BeginDate, 112),
		@EDate = CONVERT(VARCHAR(8), @EndDate, 112)

	CREATE TABLE #t(
		DeptId BIGINT,
		DeptName NVARCHAR(20),
		ManagerUserId BIGINT,
		ManagerName NVARCHAR(20),
		AvgNumber BIGINT,
		AvgMinute BIGINT,
		AvgConvertNumber BIGINT,
		AvgConvertMinute BIGINT,
		SumNumber BIGINT,
		SumMinute BIGINT,
		SumConvertNumber BIGINT,
		SumConvertMinute BIGINT,
		RealWorkTime DECIMAL(9, 2),
		WorkDays BIGINT,
		Coefficient DECIMAL(9, 3))

	--@TimeType BIGINT,		--0:不选择； 1:30秒以上;2:1分钟以上;3:3分钟以上;4:5分钟以上;5:10分钟以上;6:30分钟以上
 
	IF @CallType = 1
		SELECT @CallNumber = 'CallInNum_All', @CallInterval = 'CallInInterval_All'
	ELSE IF @CallType = 2
		SELECT @CallNumber = 'CallOutNum_All', @CallInterval = 'CallOutInterval_All'
	ELSE
		SELECT @CallNumber = 'CallInNum_All + CallOutNum_All',
			 @CallInterval = 'CallInInterval_All + CallOutInterval_All'
	IF @TimeType = 1
		SELECT @CallNumber = REPLACE(@CallNumber, '_All', '_Up30'),
			@CallInterval = REPLACE(@CallInterval, '_All', '_Up30')
	ELSE IF @TimeType = 2
		SELECT @CallNumber = REPLACE(@CallNumber, '_All', '_Up60'),
			@CallInterval = REPLACE(@CallInterval, '_All', '_Up60')
	ELSE IF @TimeType = 3
		SELECT @CallNumber = REPLACE(@CallNumber, '_All', '_Up180'),
			@CallInterval = REPLACE(@CallInterval, '_All', '_Up180')
	ELSE IF @TimeType = 4
		SELECT @CallNumber = REPLACE(@CallNumber, '_All', '_Up600'),
			@CallInterval = REPLACE(@CallInterval, '_All', '_Up600')
	ELSE IF @TimeType = 5
		SELECT @CallNumber = REPLACE(@CallNumber, '_All', '_Up40'),
			@CallInterval = REPLACE(@CallInterval, '_All', '_Up40') 

	SET @Sql ='
	INSERT #t(ManagerUserId, AvgNumber, AvgMinute, SumNumber, SumMinute, Coefficient, RealWorkTime, WorkDays)
	SELECT a.ManagerUserId, AVG(' + @CallNumber + '), AVG(' + @CallInterval + '),
		SUM(' + @CallNumber + '), SUM(' + @CallInterval + '), AVG(b.Coefficient),
		SUM(b.RealWorkTime), COUNT(1)
	FROM IvrList_Day a, IvrDayReport b
	WHERE a.CountDate BETWEEN ' + @BDate + ' AND ' + @EDate + '
	AND a.CountDate = b.Countdate
	AND a.ManagerUserId = b.ManagerUserId
	AND b.IsCheck = 1
	GROUP BY a.ManagerUserId'
	PRINT @SQL
	EXEC(@SQL)

	UPDATE a
	Set a.ManagerName = b.Name,
		a.DeptId = b.DeptId
	FROM #t a, ManagerUser b
	WHERE a.ManagerUSerId = b.Id

	UPDATE a
	Set a.DeptName = b.DeptName
	FROM #t a, Dept b
	WHERE a.DeptId = b.Id

	--1：南北方个人；2：山东个人；3：客服个人；4：所有部门对比；5：部门查询
	IF @QueryType = 1
		DELETE #t WHERE DeptId NOT IN(4,19,25,28)
	IF @QueryType = 2
		DELETE #t WHERE DeptId NOT IN(31,34,36,37,39,42,54)
	IF @QueryType = 3
		DELETE #t WHERE DeptId <> 14
	IF @QueryType = 5
	BEGIN
		DELETE #t WHERE DeptId <> @DeptId
		INSERT #t(DeptId, DeptName, ManagerUserId, ManagerName, AvgNumber, AvgMinute, 
			SumNumber, SumMinute, RealWorkTime, WorkDays)
		SELECT DeptId, DeptName, NULL, '部门', AVG(AvgNumber), AVG(AvgMinute), 
			SUM(SumNumber), SUM(SumMinute), SUM(RealWorkTime), SUM(WorkDays)
		FROM #t
		GROUP BY DeptID, DeptName
	END
	IF @QueryType = 4
	BEGIN
		DELETE #t WHERE DeptId = 14
		INSERT #t(DeptId, DeptName, ManagerUserId, ManagerName, AvgNumber, AvgMinute, 
			SumNumber, SumMinute, RealWorkTime, WorkDays, Coefficient)
		SELECT DeptId, DeptName, NULL, '', AVG(AvgNumber), AVG(AvgMinute), 
			SUM(SumNumber), SUM(SumMinute), SUM(RealWorkTime), SUM(WorkDays), AVG(Coefficient)
		FROM #t
		GROUP BY DeptID, DeptName
		DELETE #t WHERE ManagerUserID < 1000
		INSERT #t(DeptId, DeptName, ManagerUserId, ManagerName, AvgNumber, AvgMinute, 
			SumNumber, SumMinute, RealWorkTime, WorkDays)
		SELECT 0, '体系', NULL, '', AVG(AvgNumber), AVG(AvgMinute), 
			SUM(SumNumber), SUM(SumMinute), SUM(RealWorkTime), SUM(WorkDays)
		FROM #t
	END

	UPDATE #t SET AvgConvertNumber = AvgNumber * (WorkDays * 8) / RealWorkTime,
		AvgConvertMinute = AvgMinute * (WorkDays * 8) / RealWorkTime,
		SumConvertNumber = SumNumber * (WorkDays * 8) / RealWorkTime,
		SumConvertMinute = SumMinute * (WorkDays * 8) / RealWorkTime

	UPDATE #t SET Coefficient = (AvgConvertNumber / 100.0 + AvgConvertMinute / (260.0 * 60)) 
	WHERE DeptId != 42

	UPDATE #t SET Coefficient = (AvgConvertNumber / 160.0 + AvgConvertMinute / (200.0  * 60))
	WHERE DeptId = 42  
	--WHERE ManagerUserId IS NULL

	DECLARE @t AS TABLE(
		DeptId BIGINT,
		DeptName NVARCHAR(20),
		ManagerUserId BIGINT,
		ManagerName NVARCHAR(20),
		CountType NVARCHAR(2),
		RealNumber BIGINT,
		RealMinute BIGINT,
		ConvertNumber BIGINT,
		ConvertMinute BIGINT,
		Coefficient DECIMAL(9, 2))
	INSERT @t(DeptId, DeptName, ManagerUserId, ManagerName, CountType,
		RealNumber, RealMinute, ConvertNumber, ConvertMinute, Coefficient)
	SELECT DeptId, DeptName, ManagerUserId, ManagerName, '平均',
		AvgNumber, AvgMinute / 60, AvgConvertNumber, AvgConvertMinute / 60, Coefficient
	FROM #t
	INSERT @t(DeptId, DeptName, ManagerUserId, ManagerName, CountType,
		RealNumber, RealMinute, ConvertNumber, ConvertMinute, Coefficient)
	SELECT DeptId, DeptName, ManagerUserId, ManagerName, '合计',
		SumNumber, SumMinute / 60, SumConvertNumber, SumConvertMinute / 60, Coefficient
	FROM #t

	DECLARE @d AS TABLE(DeptId BIGINT, OrderNo INT)
	INSERT @d SELECT 4, 1
	INSERT @d SELECT 28, 2
	INSERT @d SELECT 19, 3
	INSERT @d SELECT 25, 4
	INSERT @d SELECT 39, 5
	INSERT @d SELECT 31, 6
	INSERT @d SELECT 34, 7
	INSERT @d SELECT 36, 8
	INSERT @d SELECT 37, 9
	INSERT @d SELECT 42, 10
	INSERT @d SELECT 14, 11
INSERT @d SELECT 54, 12
	INSERT @d SELECT 0, 13

	SELECT a.* FROM @t a, @d b WHERE a.DeptId = b.DeptId
	ORDER BY b.OrderNo, CASE WHEN a.ManagerUserId IS NULL THEN 9999 ELSE a.ManagerUserId END, CASE CountType WHEN '平均' THEN 1 ELSE 2 END
	SELECT * FROM #t ORDER BY DeptName, ManagerUserId
END



GO
/****** Object:  StoredProcedure [dbo].[ProcIvrListByCaMainIdUpdate]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ProcIvrListByCaMainIdUpdate]
AS
BEGIN
	--DECLARE @ID INT
 	--SELECT TOP 1 @ID = ID FROM IvrList WHERE caMainId IS NOT NULL ORDER BY ID DESC

	DECLARE @t AS TABLE(ID INT,
		CallNo VARCHAR(50),
		CalledNo VARCHAR(50),
		CallType VARCHAR(10),
		Telephone VARCHAR(50),
		Telephone2 VARCHAR(50),
		Exten VARCHAR(10),
		caMainId INT,
		cpAccountID INT,
		cpLinkManID INT,
		IsWtg INT
	)

	INSERT INTO @t(ID, CallNo, CalledNo, CallType, Exten,cpAccountID,cpLinkManID, IsWtg)
	SELECT ID, CallNo, CalledNo, CallType, Exten, 0,0,0  FROM IvrList WHERE caMainId IS NULL
	IF (SELECT COUNT(*) FROM @t) = 0
		RETURN

	UPDATE a SET IsWtg = 1 FROM @t a WHERE Exten IN (SELECT LTRIM(STR(ID)) FROM Manageruser WITH(NOLOCK) WHERE DeptID IN (SELECT ID FROM Dept WITH(NOLOCK) WHERE Superior = 43)) 

	UPDATE a
	SET a.TelePhone = a.CallNo
	FROM @t a

	UPDATE a
	SET a.TelePhone = a.CalledNo
	FROM @t a
	WHERE a.CallType = 'dialout'
	
	UPDATE a
	SET a.TelePhone2 = LEFT(TelePhone, 3) + '-' + RIGHT(TelePhone, LEN(TelePhone) - 3)
	FROM @t a
	WHERE LEFT(TelePhone, 2) IN('01', '02')
	AND TelePhone NOT LIKE '1%'

	UPDATE a
	SET a.TelePhone2 = LEFT(TelePhone, 4) + '-' + RIGHT(TelePhone, LEN(TelePhone) - 4)
	FROM @t a
	WHERE TelePhone2 IS NULL
	AND TelePhone NOT LIKE '1%'

	--#############################判断是否是社招平台的联系方式
	UPDATE a
	SET a.caMainId = (SELECT TOP 1 Id FROM caMain WHERE caMain.Mobile = a.TelePhone AND cpMainId IN(SELECT id FROM cpMain WITH(NOLOCK) WHERE ConsultantId = a.Exten) ORDER BY Id DESc)
	FROM @t a
	WHERE a.TelePhone LIKE '1%'
	AND IsWtg = 0

	UPDATE a
	SET a.caMainId = (SELECT TOP 1 Id FROM caMain WHERE caMain.Mobile = a.TelePhone ORDER BY ID DESC)
	FROM @t a
	WHERE a.TelePhone LIKE '1%'
	AND a.CaMainId IS NULL
	AND IsWtg = 0

	UPDATE a
	SET a.caMainId = (SELECT TOP 1 Id FROM caMain WITH(NOLOCK INDEX(IX_CaMainID_TelePhone)) WHERE caMain.TelePhone LIKE a.TelePhone + '%' AND cpMainId IN(SELECT id FROM cpMain WITH(NOLOCK) WHERE ConsultantId = a.Exten) ORDER BY ID DESC)
	FROM @t a
	WHERE a.CaMainId IS NULL
	AND IsWtg = 0

	UPDATE a
	SET a.caMainId = (SELECT TOP 1 Id FROM caMain WITH(NOLOCK INDEX(IX_CaMainID_TelePhone)) WHERE caMain.TelePhone LIKE a.TelePhone + '%' ORDER BY ID DESC)
	FROM @t a
	WHERE a.CaMainId IS NULL
	AND IsWtg = 0

 	UPDATE a
	SET a.caMainId = (SELECT TOP 1 Id FROM caMain WITH(NOLOCK INDEX(IX_CaMainID_TelePhone))  WHERE caMain.TelePhone LIKE a.TelePhone2 + '%' AND cpMainId IN(SELECT id FROM cpMain WITH(NOLOCK) WHERE ConsultantId = a.Exten) ORDER BY ID DESC)
	FROM @t a
	WHERE a.CaMainId IS NULL
	AND IsWtg = 0

	UPDATE a
	SET a.caMainId = (SELECT TOP 1 Id FROM caMain WITH(NOLOCK INDEX(IX_CaMainID_TelePhone))  WHERE TelePhone LIKE a.TelePhone2 + '%' ORDER BY ID DESC)
	FROM @t a
	WHERE a.CaMainId IS NULL
	AND IsWtg = 0

	UPDATE a
	SET a.caMainId = 0
	FROM @t a
	WHERE a.CaMainId IS NULL
	--AND IsWtg = 0

	UPDATE a
	SET a.caMainId = b.caMainId
	FROM IvrList a, @t b
	WHERE a.Id = b.Id
	--AND IsWtg = 0
	--#############################判断是否是梧桐果校招平台的联系方式
	UPDATE a
	SET a.cpAccountID = (SELECT TOP 1 Id FROM Wutongguodb..cpAccount  WITH(NOLOCK) WHERE cpAccount.Mobile = a.TelePhone AND cpMainId IN(SELECT id FROM Wutongguodb..cpMain WITH(NOLOCK) WHERE ConsultantId = a.Exten) ORDER BY Id DESc)
	FROM @t a
	WHERE a.TelePhone LIKE '1%'
	AND cpAccountID = 0
	AND IsWtg = 1

	UPDATE a
	SET a.cpAccountID = (SELECT TOP 1 Id FROM Wutongguodb..cpAccount  WITH(NOLOCK) WHERE cpAccount.Mobile = a.TelePhone ORDER BY Id DESc)
	FROM @t a
	WHERE a.TelePhone LIKE '1%'
	AND cpAccountID = 0
	AND IsWtg = 1

	UPDATE a
	SET a.CpLinkManID = (SELECT TOP 1 Id FROM Wutongguodb..CpLinkMan WITH(NOLOCK) WHERE CpLinkMan.Mobile = a.TelePhone AND cpMainId IN(SELECT id FROM Wutongguodb..cpMain WITH(NOLOCK) WHERE ConsultantId = a.Exten) ORDER BY ID DESC)
	FROM @t a
	WHERE a.TelePhone LIKE '1%'	
	AND IsWtg = 1

	UPDATE a
	SET a.CpLinkManID = (SELECT TOP 1 Id FROM Wutongguodb..CpLinkMan WITH(NOLOCK) WHERE CpLinkMan.Mobile = a.TelePhone ORDER BY ID DESC)
	FROM @t a
	WHERE a.TelePhone LIKE '1%'	
	AND CpLinkManID = 0
	AND IsWtg = 1

	UPDATE a
	SET a.cpAccountID = (SELECT TOP 1 Id FROM Wutongguodb..cpAccount WITH(NOLOCK INDEX(IX_CpAccount_TelePhone)) WHERE cpAccount.TelePhone LIKE a.TelePhone + '%' AND cpMainId IN(SELECT id FROM Wutongguodb..cpMain WITH(NOLOCK) WHERE ConsultantId = a.Exten) ORDER BY ID DESC)
	FROM @t a
	WHERE cpAccountID = 0
	AND IsWtg = 1

	UPDATE a
	SET a.cpAccountID = (SELECT TOP 1 Id FROM Wutongguodb..cpAccount WITH(NOLOCK INDEX(IX_CpAccount_TelePhone)) WHERE cpAccount.TelePhone LIKE a.TelePhone + '%'  ORDER BY ID DESC)
	FROM @t a
	WHERE cpAccountID = 0
	AND IsWtg = 1

	UPDATE a
	SET a.CpLinkManID = (SELECT TOP 1 Id FROM Wutongguodb..CpLinkMan WITH(NOLOCK INDEX(IX_CpLinkMan_Tel)) WHERE CpLinkMan.Tel LIKE a.TelePhone + '%' AND cpMainId IN(SELECT id FROM Wutongguodb..cpMain WITH(NOLOCK) WHERE ConsultantId = a.Exten) ORDER BY ID DESC)
	FROM @t a
	WHERE CpLinkManID = 0
	AND IsWtg = 1

	UPDATE a
	SET a.CpLinkManID = (SELECT TOP 1 Id FROM Wutongguodb..CpLinkMan WITH(NOLOCK INDEX(IX_CpLinkMan_Tel)) WHERE CpLinkMan.Tel LIKE a.TelePhone + '%'  ORDER BY ID DESC)
	FROM @t a
	WHERE CpLinkManID = 0
	AND IsWtg = 1

	UPDATE a
	SET a.cpAccountID = (SELECT TOP 1 Id FROM Wutongguodb..cpAccount WITH(NOLOCK INDEX(IX_CpAccount_TelePhone)) WHERE cpAccount.TelePhone LIKE a.TelePhone2 + '%' AND cpMainId IN(SELECT id FROM Wutongguodb..cpMain WITH(NOLOCK) WHERE ConsultantId = a.Exten) ORDER BY ID DESC)
	FROM @t a
	WHERE cpAccountID = 0
	AND IsWtg = 1

	UPDATE a
	SET a.cpAccountID = (SELECT TOP 1 Id FROM Wutongguodb..cpAccount WITH(NOLOCK INDEX(IX_CpAccount_TelePhone)) WHERE cpAccount.TelePhone LIKE a.TelePhone2 + '%'  ORDER BY ID DESC)
	FROM @t a
	WHERE cpAccountID = 0
	AND IsWtg = 1

	UPDATE a
	SET a.CpLinkManID = (SELECT TOP 1 Id FROM Wutongguodb..CpLinkMan WITH(NOLOCK INDEX(IX_CpLinkMan_Tel)) WHERE CpLinkMan.Tel LIKE a.TelePhone2 + '%' AND cpMainId IN(SELECT id FROM Wutongguodb..cpMain WITH(NOLOCK) WHERE ConsultantId = a.Exten) ORDER BY ID DESC)
	FROM @t a
	WHERE CpLinkManID = 0
	AND IsWtg = 1

	UPDATE a
	SET a.CpLinkManID = (SELECT TOP 1 Id FROM Wutongguodb..CpLinkMan WITH(NOLOCK INDEX(IX_CpLinkMan_Tel)) WHERE CpLinkMan.Tel LIKE a.TelePhone2 + '%'  ORDER BY ID DESC)
	FROM @t a
	WHERE CpLinkManID = 0
	AND IsWtg = 1


	UPDATE a
	SET a.cpAccountID = b.cpAccountID
	FROM IvrList a, @t b
	WHERE a.Id = b.Id
	AND IsWtg = 1

	UPDATE a
	SET a.CpLinkManID = b.CpLinkManID
	FROM IvrList a, @t b
	WHERE a.Id = b.Id
	AND IsWtg = 1

	
--	INSERT INTO Wutongguodb..CpContactLog(CpMainID,IvrListID,CpLinkManID,CpAccountID,ContentText,ManageruserID,Name,Tel)
--    SELECT
--           ISNULL(b.CpMainID,c.CpMainID)
--           ,a.id
--           ,CpLinkManID
--           ,CpAccountID
--           ,''           
--           ,Exten,ISNULL(b.Name,c.Name),a.TelePhone
--		FROM @t a LEFT JOIN Wutongguodb..CpLinkMan b WITH(NOLOCK) ON a.CpLinkManID = b.ID
--			LEFT JOIN Wutongguodb..CpAccount c WITH(NOLOCK) ON a.CpAccountID = c.ID
--		WHERE a.IsWtg=1 AND (CpLinkManID >0 OR CpLinkManID>0) and a.CallType = 'dialout'
END



GO
/****** Object:  StoredProcedure [dbo].[ProcIvrListByCaMainIdUpdate2]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ProcIvrListByCaMainIdUpdate2]
AS
BEGIN
	--DECLARE @ID INT
 	--SELECT TOP 1 @ID = ID FROM IvrList WHERE caMainId IS NOT NULL ORDER BY ID DESC

	DECLARE @t AS TABLE(ID INT,
		CallNo VARCHAR(50),
		CalledNo VARCHAR(50),
		CallType VARCHAR(10),
		Telephone VARCHAR(50),
		Telephone2 VARCHAR(50),
		Exten VARCHAR(10),
		caMainId INT,
		cpAccountID INT,
		cpLinkManID INT,
		IsWtg INT
	)

	INSERT INTO @t(ID, CallNo, CalledNo, CallType, Exten,cpAccountID,cpLinkManID, IsWtg)
	SELECT ID, CallNo, CalledNo, CallType, Exten, 0,0,0  FROM IvrList WHERE caMainId IS NULL
	IF (SELECT COUNT(*) FROM @t) = 0
		RETURN

	UPDATE a SET IsWtg = 1 FROM @t a WHERE Exten IN (SELECT LTRIM(STR(ID)) FROM Manageruser WITH(NOLOCK) WHERE DeptID IN (SELECT ID FROM Dept WITH(NOLOCK) WHERE Superior = 43)) 

	UPDATE a
	SET a.TelePhone = a.CallNo
	FROM @t a

	UPDATE a
	SET a.TelePhone = a.CalledNo
	FROM @t a
	WHERE a.CallType = 'dialout'
	
	UPDATE a
	SET a.TelePhone2 = LEFT(TelePhone, 3) + '-' + RIGHT(TelePhone, LEN(TelePhone) - 3)
	FROM @t a
	WHERE LEFT(TelePhone, 2) IN('01', '02')
	AND TelePhone NOT LIKE '1%'

	UPDATE a
	SET a.TelePhone2 = LEFT(TelePhone, 4) + '-' + RIGHT(TelePhone, LEN(TelePhone) - 4)
	FROM @t a
	WHERE TelePhone2 IS NULL
	AND TelePhone NOT LIKE '1%'

	--#############################判断是否是社招平台的联系方式
	UPDATE a
	SET a.caMainId = (SELECT TOP 1 Id FROM caMain WHERE caMain.Mobile = a.TelePhone AND cpMainId IN(SELECT id FROM cpMain WITH(NOLOCK) WHERE ConsultantId = a.Exten) ORDER BY Id DESc)
	FROM @t a
	WHERE a.TelePhone LIKE '1%'
	AND IsWtg = 0

	UPDATE a
	SET a.caMainId = (SELECT TOP 1 Id FROM caMain WHERE caMain.Mobile = a.TelePhone ORDER BY ID DESC)
	FROM @t a
	WHERE a.TelePhone LIKE '1%'
	AND a.CaMainId IS NULL
	AND IsWtg = 0

	UPDATE a
	SET a.caMainId = (SELECT TOP 1 Id FROM caMain WITH(NOLOCK INDEX(IX_CaMainID_TelePhone)) WHERE caMain.TelePhone LIKE a.TelePhone + '%' AND cpMainId IN(SELECT id FROM cpMain WITH(NOLOCK) WHERE ConsultantId = a.Exten) ORDER BY ID DESC)
	FROM @t a
	WHERE a.CaMainId IS NULL
	AND IsWtg = 0

	UPDATE a
	SET a.caMainId = (SELECT TOP 1 Id FROM caMain WITH(NOLOCK INDEX(IX_CaMainID_TelePhone)) WHERE caMain.TelePhone LIKE a.TelePhone + '%' ORDER BY ID DESC)
	FROM @t a
	WHERE a.CaMainId IS NULL
	AND IsWtg = 0

 	UPDATE a
	SET a.caMainId = (SELECT TOP 1 Id FROM caMain WITH(NOLOCK INDEX(IX_CaMainID_TelePhone))  WHERE caMain.TelePhone LIKE a.TelePhone2 + '%' AND cpMainId IN(SELECT id FROM cpMain WITH(NOLOCK) WHERE ConsultantId = a.Exten) ORDER BY ID DESC)
	FROM @t a
	WHERE a.CaMainId IS NULL
	AND IsWtg = 0

	UPDATE a
	SET a.caMainId = (SELECT TOP 1 Id FROM caMain WITH(NOLOCK INDEX(IX_CaMainID_TelePhone))  WHERE TelePhone LIKE a.TelePhone2 + '%' ORDER BY ID DESC)
	FROM @t a
	WHERE a.CaMainId IS NULL
	AND IsWtg = 0

	UPDATE a
	SET a.caMainId = 0
	FROM @t a
	WHERE a.CaMainId IS NULL
	AND IsWtg = 0

	UPDATE a
	SET a.caMainId = b.caMainId
	FROM IvrList a, @t b
	WHERE a.Id = b.Id
	AND IsWtg = 0
	--#############################判断是否是梧桐果校招平台的联系方式
	UPDATE a
	SET a.cpAccountID = (SELECT TOP 1 Id FROM Wutongguodb..cpAccount  WITH(NOLOCK) WHERE cpAccount.Mobile = a.TelePhone AND cpMainId IN(SELECT id FROM Wutongguodb..cpMain WITH(NOLOCK) WHERE ConsultantId = a.Exten) ORDER BY Id DESc)
	FROM @t a
	WHERE a.TelePhone LIKE '1%'
	AND IsWtg = 1

	UPDATE a
	SET a.cpAccountID = (SELECT TOP 1 Id FROM Wutongguodb..cpAccount  WITH(NOLOCK) WHERE cpAccount.Mobile = a.TelePhone ORDER BY Id DESc)
	FROM @t a
	WHERE a.TelePhone LIKE '1%'
	AND cpAccountID = 0
	AND IsWtg = 1

	UPDATE a
	SET a.CpLinkManID = (SELECT TOP 1 Id FROM Wutongguodb..CpLinkMan WITH(NOLOCK) WHERE CpLinkMan.Mobile = a.TelePhone AND cpMainId IN(SELECT id FROM Wutongguodb..cpMain WITH(NOLOCK) WHERE ConsultantId = a.Exten) ORDER BY ID DESC)
	FROM @t a
	WHERE a.TelePhone LIKE '1%'	
	AND IsWtg = 1

	UPDATE a
	SET a.CpLinkManID = (SELECT TOP 1 Id FROM Wutongguodb..CpLinkMan WITH(NOLOCK) WHERE CpLinkMan.Mobile = a.TelePhone ORDER BY ID DESC)
	FROM @t a
	WHERE a.TelePhone LIKE '1%'	
	AND CpLinkManID = 0
	AND IsWtg = 1

	UPDATE a
	SET a.cpAccountID = (SELECT TOP 1 Id FROM Wutongguodb..cpAccount WITH(NOLOCK INDEX(IX_CpAccount_TelePhone)) WHERE cpAccount.TelePhone LIKE a.TelePhone + '%' AND cpMainId IN(SELECT id FROM Wutongguodb..cpMain WITH(NOLOCK) WHERE ConsultantId = a.Exten) ORDER BY ID DESC)
	FROM @t a
	WHERE cpAccountID = 0
	AND IsWtg = 1

	UPDATE a
	SET a.cpAccountID = (SELECT TOP 1 Id FROM Wutongguodb..cpAccount WITH(NOLOCK INDEX(IX_CpAccount_TelePhone)) WHERE cpAccount.TelePhone LIKE a.TelePhone + '%'  ORDER BY ID DESC)
	FROM @t a
	WHERE cpAccountID = 0
	AND IsWtg = 1

	UPDATE a
	SET a.CpLinkManID = (SELECT TOP 1 Id FROM Wutongguodb..CpLinkMan WITH(NOLOCK INDEX(IX_CpLinkMan_Tel)) WHERE CpLinkMan.Tel LIKE a.TelePhone + '%' AND cpMainId IN(SELECT id FROM Wutongguodb..cpMain WITH(NOLOCK) WHERE ConsultantId = a.Exten) ORDER BY ID DESC)
	FROM @t a
	WHERE CpLinkManID = 0
	AND IsWtg = 1

	UPDATE a
	SET a.CpLinkManID = (SELECT TOP 1 Id FROM Wutongguodb..CpLinkMan WITH(NOLOCK INDEX(IX_CpLinkMan_Tel)) WHERE CpLinkMan.Tel LIKE a.TelePhone + '%'  ORDER BY ID DESC)
	FROM @t a
	WHERE CpLinkManID = 0
	AND IsWtg = 1

	UPDATE a
	SET a.cpAccountID = (SELECT TOP 1 Id FROM Wutongguodb..cpAccount WITH(NOLOCK INDEX(IX_CpAccount_TelePhone)) WHERE cpAccount.TelePhone LIKE a.TelePhone2 + '%' AND cpMainId IN(SELECT id FROM Wutongguodb..cpMain WITH(NOLOCK) WHERE ConsultantId = a.Exten) ORDER BY ID DESC)
	FROM @t a
	WHERE cpAccountID = 0
	AND IsWtg = 1

	UPDATE a
	SET a.cpAccountID = (SELECT TOP 1 Id FROM Wutongguodb..cpAccount WITH(NOLOCK INDEX(IX_CpAccount_TelePhone)) WHERE cpAccount.TelePhone LIKE a.TelePhone2 + '%'  ORDER BY ID DESC)
	FROM @t a
	WHERE cpAccountID = 0
	AND IsWtg = 1

	UPDATE a
	SET a.CpLinkManID = (SELECT TOP 1 Id FROM Wutongguodb..CpLinkMan WITH(NOLOCK INDEX(IX_CpLinkMan_Tel)) WHERE CpLinkMan.Tel LIKE a.TelePhone2 + '%' AND cpMainId IN(SELECT id FROM Wutongguodb..cpMain WITH(NOLOCK) WHERE ConsultantId = a.Exten) ORDER BY ID DESC)
	FROM @t a
	WHERE CpLinkManID = 0
	AND IsWtg = 1

	UPDATE a
	SET a.CpLinkManID = (SELECT TOP 1 Id FROM Wutongguodb..CpLinkMan WITH(NOLOCK INDEX(IX_CpLinkMan_Tel)) WHERE CpLinkMan.Tel LIKE a.TelePhone2 + '%'  ORDER BY ID DESC)
	FROM @t a
	WHERE CpLinkManID = 0
	AND IsWtg = 1


	UPDATE a
	SET a.cpAccountID = b.cpAccountID
	FROM IvrList a, @t b
	WHERE a.Id = b.Id
	AND IsWtg = 1

	UPDATE a
	SET a.CpLinkManID = b.CpLinkManID
	FROM IvrList a, @t b
	WHERE a.Id = b.Id
	AND IsWtg = 1

	
	INSERT INTO Wutongguodb..CpContactLog(CpMainID,IvrListID,CpLinkManID,CpAccountID,ContentText,ManageruserID)
    SELECT
           ISNULL(b.CpMainID,c.CpMainID)
           ,a.id
           ,CpLinkManID
           ,CpAccountID
           ,''           
           ,Exten
		FROM @t a LEFT JOIN Wutongguodb..CpLinkMan b WITH(NOLOCK) ON a.CpLinkManID = b.ID
			LEFT JOIN Wutongguodb..CpAccount c WITH(NOLOCK) ON a.CpAccountID = c.ID
		WHERE a.IsWtg=1 AND (CpLinkManID >0 OR CpLinkManID>0)
END



GO
/****** Object:  StoredProcedure [dbo].[procJobByAlipayEndSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--职位下线存储过程
CREATE PROCEDURE [dbo].[procJobByAlipayEndSelect]
(
	@BeginDate VARCHAR(50)
)
AS
BEGIN
	SELECT ID
		FROM Job WITH(NOLOCK)
		WHERE IssueEnd BETWEEN @BeginDate AND GETDATE()

END
GO
/****** Object:  StoredProcedure [dbo].[procJobByAlipayPushSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[procJobByAlipayPushSelect]
AS
BEGIN
	CREATE TABLE #T(
		JobID INT,
		JobName NVARCHAR(128),
		JobDesc NVARCHAR(MAX),
		dcJobType INT,
		JobTypeLevel1ID VARCHAR(32),
		JobTypeLevel2ID VARCHAR(32),
		JobTypeLevel3ID VARCHAR(32),
		JobTypeLevel1Name NVARCHAR(50),
		JobTypeLevel2Name NVARCHAR(50),
		JobTypeLevel3Name NVARCHAR(50),
		JobTag NVARCHAR(1000),
		NeedNum INT,
		EmployType TINYINT,
		dcEducationID TINYINT,
		dcSalaryMin VARCHAR(20),
		dcSalaryMax VARCHAR(20),
		CpMainID INT,
		CpName NVARCHAR(256),
		CpLogo VARCHAR(256),
		dcRegionID VARCHAR(6),
		ProvinceID VARCHAR(6),
		ProvinceName NVARCHAR(20),
		CityID VARCHAR(6),
		CityName NVARCHAR(20),
		DistrictID VARCHAR(6),
		DistrictName NVARCHAR(20),
		IssueEnd SMALLDATETIME,
		IssueDate SMALLDATETIME,
		RefreshDate SMALLDATETIME ,
		industry_tier1_code VARCHAR(30),
		industry_tier1 NVARCHAR(50),
		industry_tier2_code VARCHAR(30),
		industry_tier2 NVARCHAR(50),
		homepage VARCHAR(256),
		CpAddress NVARCHAR(256),
		lng VARCHAR(20),
		lat VARCHAR(20),
		ApplyEmail VARCHAR(200)
	)

	INSERT INTO #T(JobID,JobName,JobDesc,dcJobType,NeedNum,EmployType,dcEducationID,CpMainID,dcRegionID,IssueEnd,IssueDate,RefreshDate,dcSalaryMin,dcSalaryMax)
	SELECT TOP 100 a.ID,a.Name,'岗位职责：'+a.Responsibility+'岗位要求：'+a.Demand,a.dcJobTypeID,a.NeedNumber,a.EmployType,a.dcEducationID,a.cpMainID,a.dcRegionID,a.IssueEnd,a.IssueDate,a.RefreshDate,REPLACE(b.DescriptionCp,'K',''),REPLACE(c.DescriptionCp,'K','')
	FROM Job a WITH(NOLOCK)
	LEFT JOIN dcSalary b WITH(NOLOCK) ON b.id = a.dcSalaryID
	LEFT JOIN dcSalary c WITH(NOLOCK) ON c.id = a.dcSalaryIdMax
	WHERE a.Valid = 1
	AND a.id > (SELECT ISNULL(MAX(JobID),0) FROM LogDb..AlipayJobPushLog WITH(NOLOCK))
	AND a.dcSalaryID <> 100
	ORDER BY a.ID ASC

	INSERT INTO LogDb..AlipayJobPushLog(JobId,PushStatus)
	SELECT JobID,0
	FROM #T

	--改为支付宝对应的职位类别信息
	UPDATE a
	SET a.JobTypeLevel3ID = c.alipayID,a.JobTypeLevel3Name = c.alipayDescription
	FROM #T a WITH(NOLOCK),dcAlipayDicConvert b WITH(NOLOCK),dcAlipayDic c WITH(NOLOCK)
	WHERE CONVERT(VARCHAR,a.dcJobType) = b.qlrcID
	AND c.id = b.dcAlipayDicID
	AND b.DataType = 3
	AND c.AlipayLevel = 3

	UPDATE #T 
	SET JobTypeLevel2ID = (SELECT TOP 1 alipayParentId FROM dcAlipayDic WITH(NOLOCK) WHERE alipayId = #T.JobTypeLevel3ID AND DataType = 3)
	WHERE JobTypeLevel3ID IS NOT NULL

	UPDATE #T 
	SET JobTypeLevel2Name = (SELECT TOP 1 alipayDescription FROM dcAlipayDic WITH(NOLOCK) WHERE alipayId = #T.JobTypeLevel2ID AND DataType = 3)
	WHERE JobTypeLevel2ID IS NOT NULL

	UPDATE a
	SET a.JobTypeLevel2ID = c.alipayID,a.JobTypeLevel2Name = c.alipayDescription
	FROM #T a WITH(NOLOCK),dcAlipayDicConvert b WITH(NOLOCK),dcAlipayDic c WITH(NOLOCK)
	WHERE CONVERT(VARCHAR,a.dcJobType) = b.qlrcID
	AND c.id = b.dcAlipayDicID
	AND b.DataType = 3
	AND c.AlipayLevel = 2

	UPDATE #T 
	SET JobTypeLevel1ID = (SELECT TOP 1 alipayParentId FROM dcAlipayDic WITH(NOLOCK) WHERE alipayId = #T.JobTypeLevel2ID AND DataType = 3)
	WHERE JobTypeLevel2ID IS NOT NULL

	UPDATE #T 
	SET JobTypeLevel1Name = (SELECT TOP 1 alipayDescription FROM dcAlipayDic WITH(NOLOCK) WHERE alipayId = #T.JobTypeLevel1ID AND DataType = 3)
	WHERE JobTypeLevel1ID IS NOT NULL

	UPDATE a
	SET a.JobTypeLevel1ID = c.alipayID,a.JobTypeLevel1Name = c.alipayDescription
	FROM #T a WITH(NOLOCK),dcAlipayDicConvert b WITH(NOLOCK),dcAlipayDic c WITH(NOLOCK)
	WHERE CONVERT(VARCHAR,a.dcJobType) = b.qlrcID
	AND c.id = b.dcAlipayDicID
	AND b.DataType = 3
	AND c.AlipayLevel = 1

	--改为支付宝对应的省份信息
	UPDATE a
	SET a.ProvinceID = c.alipayID,a.ProvinceName = c.alipayDescription
	FROM #T a WITH(NOLOCK),dcAlipayDicConvert b WITH(NOLOCK),dcAlipayDic c WITH(NOLOCK)
	WHERE LEFT(a.dcRegionID,2) = b.qlrcID
	AND c.id = b.dcAlipayDicID
	AND b.DataType = 1

	--改为支付宝对应的城市信息
	--修改直辖市的市与省对应
	UPDATE #T
	SET CityID = ProvinceID,CityName = ProvinceName
	WHERE CONVERT(INT,LEFT(dcRegionID,2)) IN(10,11,30,60,90,91,92)

	--非直辖市的并且可以查到城市信息的
	UPDATE a
	SET a.CityID = c.alipayID,a.CityName = c.alipayDescription
	FROM #T a WITH(NOLOCK),dcAlipayDicConvert b WITH(NOLOCK),dcAlipayDic c WITH(NOLOCK)
	WHERE LEFT(a.dcRegionID,4) = b.qlrcID
	AND c.id = b.dcAlipayDicID
	AND b.DataType = 1
	AND c.alipaylevel = 2
	AND a.CityID IS NULL
	AND LEN(a.dcRegionID) >=4

	--非直辖市，并且只有省份的修改为直辖市
	UPDATE a
	SET a.CityID = c.alipayID,a.CityName = c.alipayDescription
	FROM #T a WITH(NOLOCK),dcAlipayDicConvert b WITH(NOLOCK),dcAlipayDic c WITH(NOLOCK)
	WHERE a.dcRegionID+'01' = b.qlrcID
	AND c.id = b.dcAlipayDicID
	AND b.DataType = 1
	AND c.alipaylevel = 2
	AND a.CityID IS NULL
	AND LEN(a.dcRegionID) = 2

	--改为支付宝对应的区的信息
	UPDATE a
	SET a.DistrictID = c.alipayID,a.DistrictName = c.alipayDescription
	FROM #T a WITH(NOLOCK),dcAlipayDicConvert b WITH(NOLOCK),dcAlipayDic c WITH(NOLOCK)
	WHERE a.dcRegionID = b.qlrcID
	AND c.id = b.dcAlipayDicID
	AND b.DataType = 1
	AND c.alipaylevel = 3

	--修改企业名称字段
	UPDATE a
	SET cpName = b.Name
	FROM #T a WITH(NOLOCK),cpMain b WITH(NOLOCK)
	WHERE a.cpMainID = b.ID

	UPDATE #T
	SET CpLogo = (SELECT TOP 1 ImgFile FROM cpImage WITH(NOLOCK) WHERE cpMainID = #T.cpMainID AND ImgType = 1 ORDER BY AddDate DESC)

	UPDATE #T 
	SET JobTag = (
		SELECT STUFF((
			SELECT ',' + Tags 
			FROM JobTags WITH(NOLOCK) 
			WHERE JobID = #T.JobID 
			FOR XML PATH('')),1,1,'' )
	)

	--设置企业信息结构
	UPDATE a
	SET a.homepage = b.HomePage,a.CpAddress = b.Address,a.lng = b.Lng,a.lat = b.Lat,a.ApplyEmail = c.EMail
	FROM #T a WITH(NOLOCK),cpmain b WITH(NOLOCK),camain c WITH(NOLOCK)
	WHERE a.CpMainID = b.ID
	AND c.cpMainID = b.ID
	AND c.AccountType = 1

	--设置企业信息所属二级行业code
	UPDATE #T
	SET industry_tier2_code = (
		SELECT TOP 1 d.alipayid
		FROM #T a WITH(NOLOCK),cpIndustry b WITH(NOLOCK),dcAlipayDicConvert c WITH(NOLOCK),dcAlipayDic d WITH(NOLOCK)
		WHERE a.CpMainID = b.cpMainID
		AND c.qlrcId = b.dcIndustryID
		AND d.id = c.dcAlipayDicId
		AND c.DataType = 2
	)

	--设置企业信息所属二级行业
	UPDATE #T 
	SET industry_tier2 = (SELECT TOP 1 alipayDescription FROM dcAlipayDic WITH(NOLOCK) WHERE alipayId = #T.industry_tier2_code AND DataType = 2)
	WHERE industry_tier2_code IS NOT NULL

	--设置企业信息所属一级行业code
	UPDATE #T 
	SET industry_tier1_code = (SELECT TOP 1 alipayParentId FROM dcAlipayDic WITH(NOLOCK) WHERE alipayId = #T.industry_tier2_code AND DataType = 2)
	WHERE industry_tier2_code IS NOT NULL

	--设置企业信息所属一级行业
	UPDATE #T 
	SET industry_tier1 = (SELECT TOP 1 alipayDescription FROM dcAlipayDic WITH(NOLOCK) WHERE alipayId = #T.industry_tier1_code AND DataType = 2)
	WHERE industry_tier1_code IS NOT NULL

	SELECT a.*,b.Welfare1,b.Welfare2,b.Welfare3,b.Welfare4
		,b.Welfare5,b.Welfare6,b.Welfare7,b.Welfare8,b.Welfare9
		,b.Welfare10,b.Welfare11,b.Welfare12,b.Welfare13,b.Welfare14
		,b.Welfare15,b.Welfare16,b.Welfare17,b.Welfare18,b.Welfare19  
	FROM #T a
	LEFT JOIN Job b WITH(NOLOCK) ON b.id = a.JobID


	DROP TABLE #T
END
GO
/****** Object:  StoredProcedure [dbo].[procJobByAlipayRefreshSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--职位刷新存储过程
CREATE PROCEDURE [dbo].[procJobByAlipayRefreshSelect]
(
	@BeginDate VARCHAR(50)
)
AS
BEGIN
	SELECT ID,IssueEnd,RefreshDate
		FROM Job WITH(NOLOCK)
		WHERE Valid = 1
		AND RefreshDate > @BeginDate

END


GO
/****** Object:  StoredProcedure [dbo].[procJobByAlipaySelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[procJobByAlipaySelect]
(
	@BeginDate VARCHAR(50)
)
AS
BEGIN
	CREATE TABLE #T(
		JobID INT,
		JobName NVARCHAR(128),
		JobDesc NVARCHAR(MAX),
		dcJobType INT,
		JobTypeLevel1ID VARCHAR(32),
		JobTypeLevel2ID VARCHAR(32),
		JobTypeLevel3ID VARCHAR(32),
		JobTypeLevel1Name NVARCHAR(50),
		JobTypeLevel2Name NVARCHAR(50),
		JobTypeLevel3Name NVARCHAR(50),
		JobTag NVARCHAR(1000),
		NeedNum INT,
		EmployType TINYINT,
		dcEducationID TINYINT,
		dcSalaryMin VARCHAR(20),
		dcSalaryMax VARCHAR(20),
		CpMainID INT,
		CpName NVARCHAR(256),
		CpLogo VARCHAR(256),
		dcRegionID VARCHAR(6),
		ProvinceID VARCHAR(6),
		ProvinceName NVARCHAR(20),
		CityID VARCHAR(6),
		CityName NVARCHAR(20),
		DistrictID VARCHAR(6),
		DistrictName NVARCHAR(20),
		IssueEnd SMALLDATETIME,
		IssueDate SMALLDATETIME,
		RefreshDate SMALLDATETIME ,
		industry_tier1_code VARCHAR(30),
		industry_tier1 NVARCHAR(50),
		industry_tier2_code VARCHAR(30),
		industry_tier2 NVARCHAR(50),
		homepage VARCHAR(256),
		CpAddress NVARCHAR(256),
		lng VARCHAR(20),
		lat VARCHAR(20),
		ApplyEmail VARCHAR(200)
	)

	INSERT INTO #T(JobID,JobName,JobDesc,dcJobType,NeedNum,EmployType,dcEducationID,CpMainID,dcRegionID,IssueEnd,IssueDate,RefreshDate,dcSalaryMin,dcSalaryMax)
	SELECT a.ID,a.Name,'岗位职责：'+a.Responsibility+'岗位要求：'+a.Demand,a.dcJobTypeID,a.NeedNumber,a.EmployType,a.dcEducationID,a.cpMainID,a.dcRegionID,a.IssueEnd,a.IssueDate,a.RefreshDate,REPLACE(b.DescriptionCp,'K',''),REPLACE(c.DescriptionCp,'K','')
	FROM logdb..AlipayJobPushLog d WITH(NOLOCK)
	LEFT JOIN Job a WITH(NOLOCK) ON d.JobId = a.ID
	LEFT JOIN dcSalary b WITH(NOLOCK) ON b.id = a.dcSalaryID
	LEFT JOIN dcSalary c WITH(NOLOCK) ON c.id = a.dcSalaryIdMax
	WHERE a.dcSalaryID <> 100
	AND d.PushDate IS NULL
	
	UPDATE logdb..AlipayJobPushLog SET PushDate = GETDATE()
	WHERE JobID IN(SELECT JobID FROM #T)

	--改为支付宝对应的职位类别信息
	UPDATE a
	SET a.JobTypeLevel3ID = c.alipayID,a.JobTypeLevel3Name = c.alipayDescription
	FROM #T a WITH(NOLOCK),dcAlipayDicConvert b WITH(NOLOCK),dcAlipayDic c WITH(NOLOCK)
	WHERE CONVERT(VARCHAR,a.dcJobType) = b.qlrcID
	AND c.id = b.dcAlipayDicID
	AND b.DataType = 3
	AND c.AlipayLevel = 3

	UPDATE #T 
	SET JobTypeLevel2ID = (SELECT TOP 1 alipayParentId FROM dcAlipayDic WITH(NOLOCK) WHERE alipayId = #T.JobTypeLevel3ID AND DataType = 3)
	WHERE JobTypeLevel3ID IS NOT NULL

	UPDATE #T 
	SET JobTypeLevel2Name = (SELECT TOP 1 alipayDescription FROM dcAlipayDic WITH(NOLOCK) WHERE alipayId = #T.JobTypeLevel2ID AND DataType = 3)
	WHERE JobTypeLevel2ID IS NOT NULL

	UPDATE a
	SET a.JobTypeLevel2ID = c.alipayID,a.JobTypeLevel2Name = c.alipayDescription
	FROM #T a WITH(NOLOCK),dcAlipayDicConvert b WITH(NOLOCK),dcAlipayDic c WITH(NOLOCK)
	WHERE CONVERT(VARCHAR,a.dcJobType) = b.qlrcID
	AND c.id = b.dcAlipayDicID
	AND b.DataType = 3
	AND c.AlipayLevel = 2

	UPDATE #T 
	SET JobTypeLevel1ID = (SELECT TOP 1 alipayParentId FROM dcAlipayDic WITH(NOLOCK) WHERE alipayId = #T.JobTypeLevel2ID AND DataType = 3)
	WHERE JobTypeLevel2ID IS NOT NULL

	UPDATE #T 
	SET JobTypeLevel1Name = (SELECT TOP 1 alipayDescription FROM dcAlipayDic WITH(NOLOCK) WHERE alipayId = #T.JobTypeLevel1ID AND DataType = 3)
	WHERE JobTypeLevel1ID IS NOT NULL

	UPDATE a
	SET a.JobTypeLevel1ID = c.alipayID,a.JobTypeLevel1Name = c.alipayDescription
	FROM #T a WITH(NOLOCK),dcAlipayDicConvert b WITH(NOLOCK),dcAlipayDic c WITH(NOLOCK)
	WHERE CONVERT(VARCHAR,a.dcJobType) = b.qlrcID
	AND c.id = b.dcAlipayDicID
	AND b.DataType = 3
	AND c.AlipayLevel = 1

	--改为支付宝对应的省份信息
	UPDATE a
	SET a.ProvinceID = c.alipayID,a.ProvinceName = c.alipayDescription
	FROM #T a WITH(NOLOCK),dcAlipayDicConvert b WITH(NOLOCK),dcAlipayDic c WITH(NOLOCK)
	WHERE LEFT(a.dcRegionID,2) = b.qlrcID
	AND c.id = b.dcAlipayDicID
	AND b.DataType = 1

	--改为支付宝对应的城市信息
	--修改直辖市的市与省对应
	UPDATE #T
	SET CityID = ProvinceID,CityName = ProvinceName
	WHERE CONVERT(INT,LEFT(dcRegionID,2)) IN(10,11,30,60,90,91,92)

	--非直辖市的并且可以查到城市信息的
	UPDATE a
	SET a.CityID = c.alipayID,a.CityName = c.alipayDescription
	FROM #T a WITH(NOLOCK),dcAlipayDicConvert b WITH(NOLOCK),dcAlipayDic c WITH(NOLOCK)
	WHERE LEFT(a.dcRegionID,4) = b.qlrcID
	AND c.id = b.dcAlipayDicID
	AND b.DataType = 1
	AND c.alipaylevel = 2
	AND a.CityID IS NULL
	AND LEN(a.dcRegionID) >=4

	--非直辖市，并且只有省份的修改为直辖市
	UPDATE a
	SET a.CityID = c.alipayID,a.CityName = c.alipayDescription
	FROM #T a WITH(NOLOCK),dcAlipayDicConvert b WITH(NOLOCK),dcAlipayDic c WITH(NOLOCK)
	WHERE a.dcRegionID+'01' = b.qlrcID
	AND c.id = b.dcAlipayDicID
	AND b.DataType = 1
	AND c.alipaylevel = 2
	AND a.CityID IS NULL
	AND LEN(a.dcRegionID) = 2

	--改为支付宝对应的区的信息
	UPDATE a
	SET a.DistrictID = c.alipayID,a.DistrictName = c.alipayDescription
	FROM #T a WITH(NOLOCK),dcAlipayDicConvert b WITH(NOLOCK),dcAlipayDic c WITH(NOLOCK)
	WHERE a.dcRegionID = b.qlrcID
	AND c.id = b.dcAlipayDicID
	AND b.DataType = 1
	AND c.alipaylevel = 3

	--修改企业名称字段
	UPDATE a
	SET cpName = b.Name
	FROM #T a WITH(NOLOCK),cpMain b WITH(NOLOCK)
	WHERE a.cpMainID = b.ID

	UPDATE #T 
	SET JobTag = (
		SELECT STUFF((
			SELECT ',' + Tags 
			FROM JobTags WITH(NOLOCK) 
			WHERE JobID = #T.JobID 
			FOR XML PATH('')),1,1,'' )
	)

	--设置企业信息结构
	UPDATE a
	SET a.homepage = b.HomePage,a.CpAddress = b.Address,a.lng = b.Lng,a.lat = b.Lat,a.ApplyEmail = c.EMail,CpLogo = b.LogoFile
	FROM #T a WITH(NOLOCK),cpmain b WITH(NOLOCK),camain c WITH(NOLOCK)
	WHERE a.CpMainID = b.ID
	AND c.cpMainID = b.ID
	AND c.AccountType = 1

	--设置企业信息所属二级行业code
	UPDATE #T
	SET industry_tier2_code = (
		SELECT TOP 1 d.alipayid
		FROM #T a WITH(NOLOCK),cpIndustry b WITH(NOLOCK),dcAlipayDicConvert c WITH(NOLOCK),dcAlipayDic d WITH(NOLOCK)
		WHERE a.CpMainID = b.cpMainID
		AND c.qlrcId = b.dcIndustryID
		AND d.id = c.dcAlipayDicId
		AND c.DataType = 2
	)

	--设置企业信息所属二级行业
	UPDATE #T 
	SET industry_tier2 = (SELECT TOP 1 alipayDescription FROM dcAlipayDic WITH(NOLOCK) WHERE alipayId = #T.industry_tier2_code AND DataType = 2)
	WHERE industry_tier2_code IS NOT NULL

	--设置企业信息所属一级行业code
	UPDATE #T 
	SET industry_tier1_code = (SELECT TOP 1 alipayParentId FROM dcAlipayDic WITH(NOLOCK) WHERE alipayId = #T.industry_tier2_code AND DataType = 2)
	WHERE industry_tier2_code IS NOT NULL

	--设置企业信息所属一级行业
	UPDATE #T 
	SET industry_tier1 = (SELECT TOP 1 alipayDescription FROM dcAlipayDic WITH(NOLOCK) WHERE alipayId = #T.industry_tier1_code AND DataType = 2)
	WHERE industry_tier1_code IS NOT NULL

	SELECT a.*,b.Welfare1,b.Welfare2,b.Welfare3,b.Welfare4
		,b.Welfare5,b.Welfare6,b.Welfare7,b.Welfare8,b.Welfare9
		,b.Welfare10,b.Welfare11,b.Welfare12,b.Welfare13,b.Welfare14
		,b.Welfare15,b.Welfare16,b.Welfare17,b.Welfare18,b.Welfare19  
	FROM #T a
	LEFT JOIN Job b WITH(NOLOCK) ON b.id = a.JobID


	DROP TABLE #T
END
GO
/****** Object:  StoredProcedure [dbo].[procJobByCaMainIDSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.03
--创建人：Nick
--说明：本用户正在发布的职位列表
--修改：2015-01-15 Andy
--		1. 添加dcRegionID列
--		2. 去掉try catch
--#####################################################
CREATE PROCEDURE [dbo].[procJobByCaMainIDSelect]
(
	@caMainID INT
)
AS
BEGIN 
	SELECT ID, Name, dcRegionID FROM job WITH(NOLOCK) WHERE camainid = @caMainID AND Valid = 1
END 

GO
/****** Object:  StoredProcedure [dbo].[procJobByConditionCaMainIDSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.04
--创建人：Nick
--说明：
--修改harry 2017-10-19 修改status=1的显示定制刷新状态jobrefreshIng
--#####################################################
CREATE PROCEDURE [dbo].[procJobByConditionCaMainIDSelect]
(
	@CaMainID INT,
	@Condition VARCHAR(500),
	@Status INT
)
AS
BEGIN TRY
	IF CHARINDEX('@',@Condition)>0
	BEGIN
		IF @Status = 1
		BEGIN
			SELECT *,CASE WHEN EXISTS(SELECT 'X' FROM jobRefreshLog WHERE jobId = job.id AND runDateTime is NULL) THEN 1 ELSE 0 END AS jobrefreshIng
		 	FROM Job WITH(NOLOCK) 
			WHERE caMainID=@CaMainID 
			AND [ForwardEmail] LIKE '%'+@Condition+'%' 
			AND IsDelete=0 
			AND IssueEND > GETDATE() 
			ORDER BY DisplayNo, IssueEnd, ID DESC
		END
		ELSE 
		BEGIN
			SELECT * FROM Job WITH(NOLOCK) 
			WHERE caMainID=@CaMainID 
			AND [ForwardEmail] LIKE '%'+@Condition+'%' 
			AND IsDelete=0 
			AND IssueEND < GETDATE() 
			ORDER BY IssueEnd DESC
		END
	END
	ELSE
	BEGIN
		IF @Status = 1
		BEGIN
			SELECT *,CASE WHEN EXISTS(SELECT 'X' FROM jobRefreshLog WHERE jobId = job.id AND runDateTime is NULL) THEN 1 ELSE 0 END AS jobrefreshIng
			FROM Job WITH(NOLOCK) 
			WHERE caMainID=@CaMainID 
			AND [Name] LIKE '%'+@Condition+'%' 
			AND IsDelete=0 
			AND IssueEND > GETDATE() 
			ORDER BY DisplayNo, IssueEnd, ID DESC
		END
		ELSE 
		BEGIN
			SELECT * FROM Job WITH(NOLOCK) 
			WHERE caMainID=@CaMainID 
			AND [Name] LIKE '%'+@Condition+'%' 
			AND IsDelete=0 
			AND IssueEND < GETDATE() 
			ORDER BY IssueEnd DESC
		END
	END
END TRY
BEGIN CATCH
	RETURN 0
END CATCH

GO
/****** Object:  StoredProcedure [dbo].[procJobByConditionSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2014.11.04
--创建人：Nick
--说明：企业搜索发布的指定职位
--修改harry 2017-10-19 修改status=1的显示定制刷新状态jobrefreshIng
--#####################################################
CREATE PROCEDURE [dbo].[procJobByConditionSelect]
(
	@CpMainID INT,
	@Condition VARCHAR(500),
	@Status INT
)
AS
BEGIN TRY
	IF @Status = 1
	BEGIN
		SELECT * ,CASE WHEN EXISTS(SELECT 'X' FROM jobRefreshLog WHERE jobId = job.id AND runDateTime is NULL) THEN 1 ELSE 0 END AS jobrefreshIng
		FROM Job WITH(NOLOCK) 
		WHERE cpMainID=@CpMainID 
		AND [Name] LIKE '%'+@Condition+'%' 
		AND IsDelete=0 
		AND IssueEND > GETDATE() 
		ORDER BY DisplayNo, IssueEnd, ID DESC
	END
	ELSE 
	BEGIN
		SELECT * FROM Job WITH(NOLOCK) 
		WHERE cpMainID=@CpMainID 
		AND [Name] LIKE '%'+@Condition+'%' 
		AND IsDelete=0 
		AND IssueEND < GETDATE() 
		ORDER BY IssueEnd DESC
	END
END TRY
BEGIN CATCH
	RETURN 0
END CATCH

GO
/****** Object:  StoredProcedure [dbo].[ProcJobByCpMainID]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--创建人 Lambo	
--20101009
--用于首页根据单位编号查询职位名称
CREATE PROCEDURE [dbo].[ProcJobByCpMainID]
(
	@cpMainID INT
)
AS
BEGIN
	SELECT TOP 20 Id, Name 
	FROM Job WITH(NOLOCK) 
	WHERE cpMainID = @cpMainID AND valid=1 
	ORDER BY DisplayNo, dcJobTypeID
END














GO
/****** Object:  StoredProcedure [dbo].[procJobByCpMainIDSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.03
--创建人：Nick
--说明：得到公司正在发布的职位列表
--#####################################################
CREATE PROCEDURE [dbo].[procJobByCpMainIDSelect]
(
	@cpMainID INT
)
AS
BEGIN TRY
	SELECT a.ID,a.Name,a.IssueEnd
	FROM Job a WITH(NOLOCK)
	WHERE  a.cpMainID = @cpMainID AND  Valid=1
	ORDER BY a.Valid DESC,a.IssueEnd DESC
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[procJobByIDSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.03
--创建人：Nick
--说明：获取职位的过滤条件
--#####################################################
CREATE PROCEDURE [dbo].[procJobByIDSelect]
(
	@ID INT
)
AS
BEGIN
	SELECT * FROM Job WITH(NOLOCK) WHERE Id = @ID
END
GO
/****** Object:  StoredProcedure [dbo].[ProcJobByIndustryIdSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.3.31
--创建人：Andy
--说明：获取可能感兴趣的公司
--#####################################################
--ProcJobByIndustryIdSelect 1,1
CREATE PROCEDURE [dbo].[ProcJobByIndustryIdSelect]
(
	@RegionID INT,
	@IndustryID INT	
)
AS
BEGIN	
	SELECT TOP 10 
		a.cpMainID,
		a.RefreshDate,
		a.dcRegionID, 
		a.Name,
		a.dcSalaryID,
		a.SecondID,	
		b.Name cpName, 
		b.SecondID cpSecondID,
		b.LastLoginDate,
		(SELECT subSiteUrl FROM dcSubSite WHERE id = b.dcProvinceID) subSiteUrl
	FROM jobPublish a 
	LEFT JOIN cpMain b ON a.CpMainID = b.ID
	WHERE a.cpMainId IN
	(
		SELECT TOP 10 realid 
		FROM Searchdb..CpMainSameIndustry WITH(NOLOCK)
		WHERE dcIndustryID = @IndustryID AND dcRegionId = @RegionID
	) 
	ORDER BY RefreshDate DESC
END

GO
/****** Object:  StoredProcedure [dbo].[ProcJobByJobuiIndexSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [dbo].[ProcJobByJobuiIndexSelect]
AS
SET NOCOUNT ON
BEGIN
	SELECT DISTINCT dcProvinceId, PageNo 
	FROM ShortDb..JobuiJobXmlOut
	ORDER BY dcProvinceId, PageNo
END

GO
/****** Object:  StoredProcedure [dbo].[ProcJobByJobuiSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ProcJobByJobuiSelect]
(
	@ProvinceId INT,
	@PageNo INT
)
AS
SET NOCOUNT ON
BEGIN
	IF ISNULL(@ProvinceId, 0) < 10
		SELECT @ProvinceId = 10
	IF ISNULL(@PageNo, 0) < 1
		SELECT @PageNo = 1

	SELECT * FROM ShortDb..JobuiJobXmlOut WHERE dcProvinceId = @ProvinceId AND PageNo = @PageNo ORDER BY Id
END

GO
/****** Object:  StoredProcedure [dbo].[ProcJobByNewst30Select]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ProcJobByNewst30Select] 
(
	@dcProvinceID INT
)
AS
SET NOCOUNT ON
BEGIN
	SELECT TOP 30 a.ID, a.cpMainID, a.caMainID, a.Name as JobName, a.dcJobTypeID, 
		a.dcJobTypeIDMinor, a.NeedNumber, a.dcSalaryID, a.dcSalaryIDMax, a.EmployType, 
		a.dcRegionID, a.Responsibility, a.Demand, a.dcEducationID, 
		a.MinExperience, a.MinAge, a.MaxAge, a.IssueDate, a.IssueEND, 
		a.IsDelete, a.AddDate, a.RefreshDate, a.Welfare1, a.Welfare2, a.Welfare3,
		a.Welfare4, a.Welfare5, a.Welfare6, a.Welfare7, a.Welfare8,
		a.Welfare9, a.Welfare10, a.Welfare11, a.Welfare12, a.Welfare13,
		a.Welfare14, a.Welfare15, a.Welfare16, a.Welfare17, a.Welfare18, a.Welfare19,
		a.SecondId EnJobID, b.SecondId EnCpMainID, 
		a.LastModifyDate, b.Name cpName, b.dcCompanySizeID, 
		b.HasLicence, b.RealName, b.UnLimitedDate, b.BalanceDate, b.Balance, 
		b.MemberType, '' cpIndustry, --STUFF((SELECT ',' + LTRIM(x.dcIndustryid) + ',c' + LTRIM(isnull(y.Category,0)) FROM cpIndustry x,dcIndustry y WHERE x.dcIndustryid = y.id AND x.cpMainid = b.id FOR XML PATH('')),1,1,'') cpIndustry,
		0, b.IsRefreshed, ISNULL(d.IsOnline, 0) IsOnline, d.IsVi, d.ViPlanId, d.InterviewDate, CASE WHEN b.ReplyRate >= 0.6 THEN b.ReplyRate ELSE NULL END Replyrate,
		NULL AttentionId
	FROM JobPublish a WITH(NOLOCK)
	INNER JOIN cpMainPublish b WITH(NOLOCK) ON a.cpMainID = b.ID 
	LEFT JOIN caOnline d WITH(NOLOCK) ON a.caMainId = d.caMainId
	WHERE b.dcProvinceId = @dcProvinceID
	ORDER BY a.RefreshDate DESC
END



GO
/****** Object:  StoredProcedure [dbo].[procJobBySalarySelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[procJobBySalarySelect]
(
	@dcJobTypeId INT,
	@dcRegionId VARCHAR(6)
)
AS
SET NOCOUNT ON
BEGIN
	DECLARE @AddDate DATETIME
	SELECT TOP 1 @AddDate = AddDate FROM ShortDb..JobSalaryAnalysis QITH(NOLOCK) WHERE JobTypeId = @dcjobTypeId AND RegionId = @dcRegionId
	IF @AddDate > DATEADD(MINUTE, -10, GETDATE())
	BEGIN
		SELECT * FROM ShortDb..JobSalaryAnalysis WITH(NOLOCK) WHERE JobTypeId = @dcjobTypeId AND RegionId = @dcRegionId ORDER BY RowNo
		RETURN
	END
	ELSE
		DELETE FROM ShortDb..JobSalaryAnalysis WHERE JobTypeId = @dcjobTypeId AND RegionId = @dcRegionId

	DECLARE @SQL AS VARCHAR(MAX)
	SET @SQL = 'INSERT INTO ShortDb..JobSalaryAnalysis
		SELECT TOP 60 ' + @dcRegionId + ' RegionId, ' + LTRIM(STR(@dcJobTypeId)) + ' JobTypeId, GETDATE() AddDate, a.Id, a.SecondId, a.Name JobName, a.NeedNumber, a.DcSalaryID,
			dbo.GetCaOnlineStatus(a.caMainID) AS IsOnline, a.MinExperience,a.caMainId, b.LogoFile LogoUrl, a.SecondId enjobid,
			a.DcSalaryIdMax, a.DcRegionID, b.Name CpName, a.dcEducationID, b.SecondId cpSecondId,
			STUFF((SELECT ''、'' + Tags FROM JobTags WITH(NOLOCK) WHERE jobID = a.ID FOR XML PATH('''')),1,1,'''') JobTags
		FROM JobPublish a WITH(NOLOCK) INNER JOIN cpMainPublish b WITH(NOLOCK) ON a.cpMainId=b.Id 
		WHERE a.cpMainID = b.ID AND dcSalaryIDMax < 100 AND dcSalaryID < 100'

	IF ISNULL(@dcRegionId, '') <> ''
		SET @SQL = @SQL + ' AND a.dcRegionID LIKE ''' + CONVERT(VARCHAR(4), @dcRegionId) + '%'''

	IF @dcJobTypeId > 0
		SET @SQL = @SQL + ' AND a.dcJobTypeID LIKE ''' + CONVERT(VARCHAR(4), @dcJobTypeId) + '%'''

	SET @SQL = @SQL + ' ORDER BY (dcSalaryIDMax + dcSalaryID) DESC, a.RefreshDate DESC'
	--PRINT @SQL
	EXEC(@SQL)

	SELECT * FROM ShortDb..JobSalaryAnalysis WITH(NOLOCK) WHERE JobTypeId = @dcjobTypeId AND RegionId = @dcRegionId ORDER BY RowNo
END
SET NOCOUNT OFF
GO
/****** Object:  StoredProcedure [dbo].[procJobBySosoSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.10
--创建人：John
--说明：获取SosoXML数据
--#####################################################
CREATE PROCEDURE [dbo].[procJobBySosoSelect]
(
	@pid INT
)
AS
BEGIN
	SELECT a.id jobid,b.id cpid,a.name jobname,dbo.GetCpIndustry(b.id) industry,b.name cpname,a.dcSalaryID,g.DescriptionEng NeedNumber,
		f.description jobtypebig,b.dccompanykindid,e.description jobtypesmall,h.Description employtype,a.minexperience,c.fullname region,
		i.description education,a.issuedate,a.issueend,a.responsibility 
	FROM job a WITH(NOLOCK) INNER JOIN cpmain b WITH(NOLOCK) ON a.cpmainid = b.id 
		LEFT JOIN dcRegion c WITH(NOLOCK) ON c.id = a.dcRegionID 
		LEFT JOIN dcJobType e WITH(NOLOCK) ON e.id = a.dcJobTypeID 
		LEFT JOIN dcJobType f WITH(NOLOCK) ON f.id = left(a.dcJobTypeID,2) 
		LEFT JOIN dcothers g WITH(NOLOCK) ON g.Category = '招聘人数' AND g.detailid = a.NeedNumber 
		LEFT JOIN dcothers h WITH(NOLOCK) ON h.Category = '工作性质' AND h.detailid = a.employtype 
		LEFT JOIN dceducation i WITH(NOLOCK) ON i.id = a.dceducationID 
	WHERE a.valid = 1 AND b.valid = 1 AND dcprovinceid = @pid ORDER BY a.refreshdate DESC
END


GO
/****** Object:  StoredProcedure [dbo].[procJobCountByRegionIDSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.03
--创建人：Nick
--说明：根据职位列表和工作地点获取数量
--#####################################################
CREATE PROCEDURE [dbo].[procJobCountByRegionIDSelect]
(
	@RegionID VARCHAR(6),
	@JobTypeID VARCHAR(20)
)
AS
BEGIN TRY
	SELECT COUNT(1) cnt 
	FROM job a WITH(NOLOCK)
	WHERE a.dcjobtypeid LIKE ''+@JobTypeID+'%' 
	AND a.dcregionid like ''+@RegionID+'%' 
	AND a.Valid>0
	AND a.dcSalaryID IS NOT NULL
	AND a.dcSalaryID<>100
	AND a.RefreshDate>GetDate()-365
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[procJobEMailSendFreqByIDUpdate]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.04
--创建人：Nick
--说明：修改职位的订阅
--#####################################################
CREATE PROCEDURE [dbo].[procJobEMailSendFreqByIDUpdate]
(
	@eMailSendFreq INT,
	@eMailSendNumber INT,
	@ID INT
)
AS
BEGIN TRY
	UPDATE JOB SET EMailSendFreq=@eMailSendFreq, EMailSendNumber=@eMailSendNumber WHERE ID = @ID
	RETURN 1
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[procJobJobTypeIDSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.03
--创建人：Nick
--说明：获取职位列表、工作地点
--#####################################################
CREATE PROCEDURE [dbo].[procJobJobTypeIDSelect]
(
	@CpMainID VARCHAR(20),
	@JobID VARCHAR(20),
	@CaMainID VARCHAR(20),
	@IsManager INT
)
AS
BEGIN TRY
	IF @JobID = ''
	BEGIN
		IF  @IsManager = 1
		BEGIN
			SELECT TOP 1 dcJobtypeID,dcRegionID 
			FROM job WITH(NOLOCK) 
			WHERE issueEnd>getdate() 
			AND  isdelete=0 
			AND valid=1
			AND cpMainID= CONVERT(INT,@CpMainID)  
			ORDER BY AddDate DESC
		END
		ELSE 
		BEGIN
			SELECT TOP 1 dcJobtypeID,dcRegionID 
			FROM job WITH(NOLOCK) 
			WHERE issueEnd>getdate() AND  isdelete=0 AND valid=1
			AND caMainID = CONVERT(INT,@CaMainID) ORDER BY AddDate DESC
		END
	END
	ELSE
	BEGIN
		SELECT TOP 1 dcJobtypeID,dcRegionID 
		FROM job WITH(NOLOCK) 
		WHERE issueEnd>getdate() AND  isdelete=0 AND valid=1
		AND ID=CONVERT(INT,@JobID) AND cpMainID=CONVERT(INT,@CpMainID)
	END
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[ProcJobMapIdByProvinceIdSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2014.10.28
--创建人：John
--说明：根据省份得到JobMap信息
--@provinceId 省份编号
--#####################################################
CREATE PROCEDURE [dbo].[ProcJobMapIdByProvinceIdSelect]
(
	@provinceId VARCHAR(2)
)
AS
BEGIN TRY
	SELECT ID FROM marketdb..MapClass WHERE dcSubSiteId = @provinceId
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[ProcJobMatchDataByPaMainIDSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.4
--创建人：John
--说明：获取用于职位匹配的数据
--#####################################################
CREATE PROCEDURE [dbo].[ProcJobMatchDataByPaMainIDSelect]
(
	@paMainID INT
)
AS
BEGIN
	SELECT TOP 1 a.ID cvMainID,Degree,ISNULL(RelatedWorkYears,0) RelatedWorkYears,dcSalaryID,IsNegotiable,dbo.BirthToAge(b.Birthday) age,
		STUFF((SELECT ',' + LTRIM(dcJobTypeID) FROM cvJobType WHERE cvMainid = a.ID FOR XML PATH('')),1,1,'') JobTypeID,
		STUFF((SELECT ',' + LTRIM(dcRegionID) FROM cvJobPlace WHERE cvMainid = a.ID FOR XML PATH('')),1,1,'') RegionID,
		STUFF((
			SELECT ','+LTRIM(x.dcIndustryID)+',c'+LTRIM(y.CateGoryId) 
			FROM cvIndustry x WITH(NOLOCK),dcIndustryCategory y WITH(NOLOCK) 
			WHERE x.dcIndustryid = y.dcIndustryid AND x.cvMainid = a.ID FOR XML PATH('')),1,1,'') Industry
	From cvMain a WITH(NOLOCK), paMain b WITH(NOLOCK)
	WHERE a.paMainID = b.ID AND paMainID = @paMainID
	ORDER BY a.CvLevel DESC,a.RefreshDate DESC
END


GO
/****** Object:  StoredProcedure [dbo].[procJobPublishByRegionIdSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.7.3
--创建人：MICE
--说明：县级站获取5条最新职位
--#####################################################
CREATE PROCEDURE [dbo].[procJobPublishByRegionIdSelect]
(
	@regionId INT
)
AS
BEGIN
	SET NOCOUNT ON
	SELECT TOP 5 a.cpmainId, a.[Name] AS jobName, a.SecondId AS jobId, b.[Name] AS cpName 
	FROM Maindb..JobPublish a WITH(NOLOCK) ,Maindb..cpMainPublish b WITH(NOLOCK)
	WHERE a.dcregionId = @regionId AND a.valid = 1 AND a.cpmainId = b.id 
	ORDER BY a.LastModifyDate DESC
	SET NOCOUNT OFF
END
GO
/****** Object:  StoredProcedure [dbo].[ProcJobPublishMatch]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ProcJobPublishMatch]
AS
BEGIN
	SET NOCOUNT on
	delete jobpublish where id in(select top 100 id from JobPublish WITH(NOLOCK) where valid=0)

	SELECT a.ID cpMainId, b.Id JobId
	INTO #3
	FROM cpMain a WITH(NOLOCK), Job b WITH(NOLOCK)
	WHERE a.id = b.cpMainId AND a.Valid= 1 AND b.Valid = 1
	AND b.id NOT IN(SELECT b.Id JobId
		FROM cpMainPublish a WITH(NOLOCK), JobPublish b WITH(NOLOCK)
		WHERE a.id = b.cpMainId AND a.Valid= 1 AND b.Valid = 1)
	AND a.LastLoginDate > CONVERT(VARCHAR(10), GETDATE() - 183, 120)

	DECLARE @S VARCHAR(MAX)
	SET @s = ''
	select DISTINCT @s = @s + 'UPDATE cpMain SET RefreshDate=RefreshDate WHERE ID = ' + LTRIM(STR(cpMainId)) + '
	'
	from #3
	--print @s
	EXEC(@S)
	SET @s = ''
	select @s = @s + 'UPDATE Job SET RefreshDate=RefreshDate WHERE ID = ' + LTRIM(STR(JobId)) + '
	'
	from #3
	print @s
	EXEC(@S)
END

GO
/****** Object:  StoredProcedure [dbo].[ProcJobRecommendByPaMainIDUpdate]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ProcJobRecommendByPaMainIDUpdate] 
(
	@PaMainID INT,				
	@dcJobTypeID VARCHAR(100), 		--职位类别
	@dcRegionID VARCHAR(100), 		--求职地区
	@dcIndustryID VARCHAR(100), 	--求职行业
	@dcSalaryID TINYINT, 			--月薪
	@MinExperience TINYINT, 		--工作经验，100为未选择
	@dcEducationID TINYINT, 		--最低学历
	@EmployType VARCHAR(10), 		--工作性质，1全职；3兼职；4实习
	@RowCount SMALLINT,				--需要显示的行数
	@Type INT						--1猜你喜欢 2小伙伴们都在申请
)
AS
BEGIN
	IF @RowCount = 0
	BEGIN
		SET @RowCount = 20
	END
		--删除后重新生成数据
		DELETE FROM SHORTDB..JobRecommend WHERE PaMainID = @PaMainID AND Type = @Type
		IF @Type = 1
		BEGIN
			SELECT @dcJobTypeID = RTRIM(dbo.FormatIDS(@dcJobTypeID)),
			@dcRegionID = RTRIM(dbo.FormatIDS(@dcRegionID)),
			@dcIndustryID = RTRIM(dbo.FormatIDS(@dcIndustryID)),
			@dcSalaryID = ISNULL(@dcSalaryID, 0),
			@MinExperience = ISNULL(@MinExperience, 100),
			@dcEducationID = ISNULL(@dcEducationID, 0),
			@EmployType = CASE @EmployType WHEN '2' THEN '1,3' ELSE ISNULL(@EmployType, '') END

			IF @dcJobTypeID LIKE '%,%,%,%,%,%'
				SET @dcJobTypeID = LEFT(@dcJobTypeID, 2)
			IF @dcRegionID LIKE '%,%,%,%,%,%'
				SET @dcRegionID = LEFT(@dcRegionID, 2)

			IF RIGHT(@dcJobTypeID, 1) = ','
				SET @dcJobTypeID = LEFT(@dcJobTypeID, LEN(@dcJobTypeID) - 1)
			IF RIGHT(@dcRegionID, 1) = ','
				SET @dcRegionID = LEFT(@dcRegionID, LEN(@dcRegionID) - 1)
			IF RIGHT(@dcIndustryID, 1) = ','
				SET @dcIndustryID = LEFT(@dcIndustryID, LEN(@dcIndustryID) - 1)

			------生成职位类别的表变量，因为职位类别有包含（父子）关系
			DECLARE @T_JobPlace AS TABLE(ID INT)
			DECLARE @T_JobType AS TABLE(ID INT)
			DECLARE @JobType AS VARCHAR(3000)
			DECLARE @JobPlace AS VARCHAR(2000)
			DECLARE @SQL AS NVARCHAR(MAX)
			DECLARE @WHERE AS VARCHAR(8000)
			DECLARE @FROM AS VARCHAR(1000)

			SET @JobPlace = ''
			SET @JobType=''
			----生成工作地点的表变量
			IF LEN(@dcRegionID) > 0
			BEGIN
				INSERT INTO @T_JobPlace
				SELECT * FROM dbo.fnSplit(@dcRegionID, ',')
				SELECT @JobPlace = (@JobPlace + ' OR a.dcRegionID Like ''' + LTRIM(STR(ID) + '%''')) FROM @T_JobPlace
				IF LEN(@JobPlace) > 0
					SET @JobPlace = RIGHT(@JobPlace, LEN(@JobPlace) -4)
			END

			----生成求聘职位的表变量
			IF LEN(@dcJobTypeID) > 0
			BEGIN
				DECLARE @T_Temp AS TABLE(ID INT)		--临时表，用于构建组合查询语句
				INSERT INTO @T_Temp
				SELECT * FROM dbo.fnSplit(@dcJobTypeID, ',')

				INSERT INTO @T_JobType
				SELECT DISTINCT ID FROM dcJobType WITH(NOLOCK)
				WHERE ParentId IN(SELECT ID FROM @T_TEMP) 
				OR ParentId2 in(SELECT ID FROM @T_TEMP)
				OR ID IN(SELECT ID FROM @T_TEMP)
				----生成in字符串
				SELECT @JobType = (@JobType + LTRIM(STR(ID) + ',')) FROM @T_JobType                                              
				IF RIGHT(@JobType, 1) = ','
					SET @JobType = LEFT(@JobType, LEN(@JobType) - 1)
			END

			----建立临时表
			CREATE TABLE #Job(
				RowID INT IDENTITY(1, 1), 
				ID INT NOT NULL, 
				dcJobTypeID SMALLINT NOT NULL, 
				dcJobTypeIDMinor SMALLINT NULL, 
				dcSalaryID TINYINT NOT NULL, 
				dcRegionID VARCHAR(6) NULL, 
				dcEducationID TINYINT NOT NULL, 
				MinExperience TINYINT NOT NULL, 
				RefreshDate SMALLDATETIME NULL
			)

			----生成插入临时表的Sql语句
			SET @SQL = '
				INSERT INTO #Job
				SELECT TOP ' + CONVERT(VARCHAR(3),@RowCount) + ' a.ID, a.dcJobTypeID, 
					a.dcJobTypeIDMinor, a.dcSalaryID, 
					a.dcRegionID, a.dcEducationID, a.MinExperience, 
					a.IssueDate'
			SET @FROM = '
				FROM JobPublish a WITH(NOLOCK)
				INNER JOIN cpMainPublish b WITH(NOLOCK) ON a.cpMainID=b.ID'
			----职位有效，单位新有效
			IF LEN(@dcIndustryID) > 0
				SET @WHERE = '
				WHERE b.ID IN (SELECT cpMainID FROM cpIndustry WHERE dcIndustryId in(' + @dcIndustryID + '))
				AND a.Valid = 1
				AND b.Valid = 1'
			ELSE
				SET @WHERE = '
				WHERE a.Valid = 1
				AND b.Valid = 1'

			----职位类别
			IF LEN(@dcJobTypeID) > 0
				SET @WHERE = @WHERE + '
				AND (a.dcJobTypeID IN(' + @JobType +')
					OR a.dcJobTypeIDMinor IN(' +@JobType + '))'
			IF LEN(@JobPlace) > 0 
				SET @WHERE = @WHERE + '
				AND (' + @JobPlace + ')'

			IF @dcSalaryID > 0
			BEGIN
				IF @dcSalaryID < 100				----从form中搜索，月薪跨2个级别, 是本级和上级别的薪金
				BEGIN
					SET @WHERE = @WHERE + '
				AND a.dcSalaryID IN(' + LTRIM(STR(@dcSalaryID)) + ',' + LTRIM(STR(@dcSalaryID + 1))
					SET @WHERE = @WHERE + ')'
				END
				IF @dcSalaryID = 100	----从筛选结果中点击面议，值是100
				BEGIN
					SET @WHERE = @WHERE + '
				AND a.dcSalaryID = 100'
				END
				IF @dcSalaryID > 100	----从筛选结果中点击搜索，月薪只有1个级别，传值时增加100
					SET @WHERE = @WHERE + '
				AND a.dcSalaryID=' + LTRIM(STR(@dcSalaryID-100))
			END
			----工作经验要求
			IF @MinExperience < 100
			SET @WHERE = @WHERE + ' 
				AND a.MinExperience = ' + LTRIM(STR(@MinExperience))

			----学历要求
			----'1初中', '2\3\4高中、中技、中专', '5大专', '6本科', '7硕士', '8博士
			IF @dcEducationID > 0
				IF @dcEducationID = 2
					SET @WHERE = @WHERE + '
				AND a.dcEducationID IN(2, 3, 4)'
				ELSE
					SET @WHERE = @WHERE + '
				AND a.dcEducationID = ' + LTRIM(STR(@dcEducationID))
			----1、全职；3、兼职；4实习。	2、全职/兼职 职位中无此项
			IF LEN(@EmployType) > 0
				SET @WHERE = @WHERE + '
				AND a.EmployType IN (' + @EmployType + ')'

			SET @SQL = @SQL + @FROM + @WHERE
			SET @SQL = @SQL + ' ORDER BY a.RefreshDate DESC, a.ID'
			EXEC(@SQL)
			DECLARE @CurrentCount AS SMALLINT
			DECLARE @NeedCount AS SMALLINT
			SELECT @CurrentCount = COUNT(*) FROM #Job
			IF @CurrentCount < @RowCount
			BEGIN
				SET @NeedCount = @RowCount - @CurrentCount
				----生成插入临时表的Sql语句
				SET @SQL = '
					INSERT INTO #Job
					SELECT TOP ' + CONVERT(VARCHAR(3),@NeedCount) + ' a.ID, a.dcJobTypeID, 
						a.dcJobTypeIDMinor, a.dcSalaryID, 
						a.dcRegionID, a.dcEducationID, a.MinExperience, 
						a.IssueDate'
				SET @FROM = '
					FROM JobPublish a WITH(NOLOCK)
					INNER JOIN cpMainPublish b WITH(NOLOCK) ON a.cpMainID=b.ID'
				----职位有效，单位新有效
				SET @WHERE = '
				WHERE a.Valid = 1
				AND b.Valid = 1 AND a.ID NOT IN(SELECT ID FROM #Job)'

				----职位类别
				IF LEN(@dcJobTypeID) > 0
					SET @WHERE = @WHERE + '
					AND (a.dcJobTypeID IN(' + @JobType +')
						OR a.dcJobTypeIDMinor IN(' +@JobType + '))'
				IF LEN(@JobPlace) > 0 
					SET @WHERE = @WHERE + '
					AND (' + @JobPlace + ')'
				SET @SQL = @SQL + @FROM + @WHERE
				SET @SQL = @SQL + ' ORDER BY a.RefreshDate DESC, a.ID'
				EXEC(@SQL)
				SELECT @CurrentCount = COUNT(*) FROM #Job
				IF @CurrentCount < @RowCount
				BEGIN
					SET @NeedCount = @RowCount - @CurrentCount
					--将工作地点扩大一级
					DECLARE @T_JobPlaceDistinct AS TABLE(ID INT)
					UPDATE @T_JobPlace SET ID = LEFT(ID,LEN(ID)-2) WHERE LEN(ID) > 2
					INSERT INTO @T_JobPlaceDistinct SELECT DISTINCT ID FROM @T_JobPlace
					SELECT @JobPlace = ''
					SELECT @JobPlace = (@JobPlace + ' OR a.dcRegionID Like ''' + LTRIM(STR(ID) + '%''')) FROM @T_JobPlaceDistinct
					IF LEN(@JobPlace) > 0
						SET @JobPlace = RIGHT(@JobPlace, LEN(@JobPlace) -4)

					--将职位类别扩大一级
					UPDATE @T_TEMP SET ID = LEFT(ID,LEN(ID)-2) WHERE LEN(ID) > 2
					DELETE FROM @T_JobType
					INSERT INTO @T_JobType
						SELECT DISTINCT ID FROM dcJobType WITH(NOLOCK)
						WHERE ParentId IN(SELECT ID FROM @T_TEMP) 
						OR ParentId2 in(SELECT ID FROM @T_TEMP)
						OR ID IN(SELECT ID FROM @T_TEMP)

					SELECT @JobType = ''
					SELECT @JobType = (@JobType + LTRIM(STR(ID) + ',')) FROM @T_JobType

					IF RIGHT(@JobType, 1) = ','
						SET @JobType = LEFT(@JobType, LEN(@JobType) - 1)

					----生成插入临时表的Sql语句
					SET @SQL = '
						INSERT INTO #Job
						SELECT TOP ' + CONVERT(VARCHAR(3),@NeedCount) + ' a.ID, a.dcJobTypeID, 
							a.dcJobTypeIDMinor, a.dcSalaryID, 
							a.dcRegionID, a.dcEducationID, a.MinExperience, 
							a.IssueDate'
					SET @FROM = '
						FROM JobPublish a WITH(NOLOCK)
						INNER JOIN cpMainPublish b WITH(NOLOCK) ON a.cpMainID=b.ID'
					----职位有效，单位新有效
					SET @WHERE = '
					WHERE a.Valid = 1
					AND b.Valid = 1 AND a.ID NOT IN(SELECT ID FROM #Job)'

					----职位类别
					IF LEN(@dcJobTypeID) > 0
						SET @WHERE = @WHERE + '
						AND (a.dcJobTypeID IN(' + @JobType +')
							OR a.dcJobTypeIDMinor IN(' +@JobType + '))'
					IF LEN(@JobPlace) > 0 
						SET @WHERE = @WHERE + '
						AND (' + @JobPlace + ')'
					SET @SQL = @SQL + @FROM + @WHERE
					SET @SQL = @SQL + ' ORDER BY a.RefreshDate DESC, a.ID'
					EXEC(@SQL)
				END
			END
			--print '090909'
			INSERT INTO SHORTDB..JobRecommend 
			SELECT TOP 20 @PaMainID,a.SecondId EnJobID, a.Name as JobName,b.Name as cpName,a.dcSalaryID,
				a.EmployType,a.dcRegionID,a.dcEducationID,a.MinExperience,a.RefreshDate,b.SecondId EnCpMainID,
				b.dcCompanySizeID,a.Welfare1,a.Welfare2,a.Welfare3,a.Welfare4,a.Welfare5,a.Welfare6,a.Welfare7,a.Welfare8,
				a.Welfare9,a.Welfare10,a.Welfare11,a.Welfare12,a.Welfare13,a.Welfare14,a.Welfare15,a.Welfare16,
				a.Welfare17,a.Welfare18,
				ISNULL((SELECT IsOnline FROM caOnline WHERE caMainId =a.caMainID), 0) AS IsOnline,1,GETDATE(),b.HasLicence,a.ID,
				a.CaMainiD, b.ReplyRate
			FROM JobPublish a WITH(NOLOCK), cpMainPublish b WITH(NOLOCK), #Job c WITH(NOLOCK)
			WHERE a.cpMainID = b.ID AND a.ID = c.ID ORDER BY c.RowID
		END
		ELSE 
		BEGIN
			SET @dcJobTypeID = dbo.FormatIDS(@dcJobTypeID)
			DECLARE @T_JobType2 AS TABLE(ID INT)
			DECLARE @JobTypeExpect AS VARCHAR(3000)
			DECLARE @T_Temp1 AS TABLE(ID INT)		--临时表，用于构建组合查询语句
			INSERT INTO @T_Temp1
			SELECT * FROM dbo.fnSplit(@dcJobTypeID, ',')
			INSERT INTO @T_JobType2
			SELECT DISTINCT ID FROM dcJobType WITH(NOLOCK)
			WHERE ParentId IN(SELECT ID FROM @T_TEMP1) 
			OR ParentId2 in(SELECT ID FROM @T_TEMP1)
			OR ID IN(SELECT ID FROM @T_TEMP1)
			----生成in字符串
			SELECT @JobTypeExpect = ''
			SELECT @JobTypeExpect = (@JobTypeExpect + LTRIM(STR(ID) + ',')) FROM @T_JobType2
			IF RIGHT(@JobTypeExpect, 1) = ','
				SET @JobTypeExpect = LEFT(@JobTypeExpect, LEN(@JobTypeExpect) - 1)
	
			DECLARE @T_JobPlace2 AS TABLE(ID INT)
			DECLARE @JobPlace2 AS VARCHAR(3000)
			INSERT INTO @T_JobPlace2
			SELECT * FROM dbo.fnSplit(@dcRegionID, ',')
			SELECT @JobPlace2 = ''
			SELECT @JobPlace2 = (@JobPlace2 + ' OR c.dcRegionID Like ''' + LTRIM(STR(ID) + '%''')) FROM @T_JobPlace2
			SELECT @JobPlace2 = (@JobPlace2 + ' OR c.dcRegionID = ''' + LTRIM(STR(LEFT(ID,2)))+'''' )
			FROM @T_JobPlace2 WHERE LEN(ID) > 2
			SELECT @JobPlace2 = (@JobPlace2 + ' OR c.dcRegionID = ''' + LTRIM(STR(LEFT(ID,4)))+'''' )
			FROM @T_JobPlace2 WHERE LEN(ID) > 4
			SET @JobPlace2 = RIGHT(@JobPlace2, LEN(@JobPlace2) -4)
			DECLARE @SQL2 AS VARCHAR(max)
			SET @SQL2 = '
				INSERT INTO SHORTDB..JobRecommend 
				SELECT TOP ' + CONVERT(VARCHAR, @RowCount) + ' '+CONVERT(VARCHAR(20),@PaMainID)+',b.SecondID EnJobID, b.Name JobName, c.Name CpName,
					 b.dcSalaryID, b.EmployType,b.dcRegionID, b.dcEducationID,b.MinExperience, b.Refreshdate,c.SecondID EnCpMainID,
					 c.dcCompanySizeID,b.Welfare1,b.Welfare2,b.Welfare3,b.Welfare4,b.Welfare5,b.Welfare6,b.Welfare7,b.Welfare8,
					b.Welfare9,b.Welfare10,b.Welfare11,b.Welfare12,b.Welfare13,b.Welfare14,b.Welfare15,b.Welfare16,
					b.Welfare17,b.Welfare18,dbo.GetCaOnlineStatus(b.caMainID) AS IsOnline,2,'''+CONVERT(VARCHAR(30),GETDATE())+''',
					c.HasLicence, b.ID, b.CaMainID, c.ReplyRate
				FROM exJobApply a WITH(NOLOCK), JobPublish b WITH(NOLOCK), cpMainPublish c WITH(NOLOCK)
				WHERE a.JobID = b.ID AND b.cpMainID = c.ID AND a.cvMainID IN(
					SELECT a.ID FROM cvMainPublish a WITH(NOLOCK)
					INNER JOIN paMainPublish b WITH(NOLOCK) ON a.paMainID = b.ID
					INNER JOIN cvJobPlacePublish c ON a.ID = c.cvMainID
					INNER JOIN cvJobTypePublish d ON a.ID = d.cvMainID
					WHERE d.dcJobTypeID IN(' + @JobTypeExpect +') AND (' + @JobPlace2 + ')
				) ORDER BY a.AddDate DESC'
			EXEC (@SQL2)
		END
END

GO
/****** Object:  StoredProcedure [dbo].[ProcJobRecommendUpdate]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ProcJobRecommendUpdate] 
(
	@PaMainID INT,				
	@dcJobTypeID VARCHAR(100), 		--职位类别
	@dcRegionID VARCHAR(100), 		--求职地区
	@dcIndustryID VARCHAR(100), 	--求职行业
	@dcSalaryID TINYINT, 			--月薪
	@MinExperience TINYINT, 		--工作经验，100为未选择
	@dcEducationID TINYINT, 		--最低学历
	@EmployType VARCHAR(10), 		--工作性质，1全职；3兼职；4实习
	@RowCount SMALLINT,				--需要显示的行数
	@Type INT						--1猜你喜欢 2小伙伴们都在申请
)
AS
BEGIN
	IF @RowCount = 0
	BEGIN
		SET @RowCount = 20
	END
	DECLARE @UpdateDate DATETIME
	SELECT TOP 1 @UpdateDate = UpdateDate 
	FROM ShortDB..JobRecommend 
	WHERE PaMainID = @PaMainID 
	AND Type = @Type

	DECLARE @Minute INT --间隔分钟数
	SELECT @Minute = DATEDIFF(MINUTE, ISNULL(@UpdateDate, GETDATE() - 1), GETDATE())
	IF @Minute IS NULL OR @Minute <= 30
	BEGIN
		print '00'
		--直接查询
		SELECT TOP 20 * FROM SHORTDB..JobRecommend WHERE PaMainID = @PaMainID AND Type = @Type
	END
	ELSE
	BEGIN
		print '11'
		--删除后重新生成数据
		DELETE FROM SHORTDB..JobRecommend WHERE PaMainID = @PaMainID AND Type = @Type
		IF @Type = 1
		BEGIN
			SELECT @dcJobTypeID = RTRIM(dbo.FormatIDS(@dcJobTypeID)),
			@dcRegionID = RTRIM(dbo.FormatIDS(@dcRegionID)),
			@dcIndustryID = RTRIM(dbo.FormatIDS(@dcIndustryID)),
			@dcSalaryID = ISNULL(@dcSalaryID, 0),
			@MinExperience = ISNULL(@MinExperience, 100),
			@dcEducationID = ISNULL(@dcEducationID, 0),
			@EmployType = CASE @EmployType WHEN '2' THEN '1,3' ELSE ISNULL(@EmployType, '') END

			IF @dcJobTypeID LIKE '%,%,%,%,%,%'
				SET @dcJobTypeID = LEFT(@dcJobTypeID, 2)
			IF @dcRegionID LIKE '%,%,%,%,%,%'
				SET @dcRegionID = LEFT(@dcRegionID, 2)

			IF RIGHT(@dcJobTypeID, 1) = ','
				SET @dcJobTypeID = LEFT(@dcJobTypeID, LEN(@dcJobTypeID) - 1)
			IF RIGHT(@dcRegionID, 1) = ','
				SET @dcRegionID = LEFT(@dcRegionID, LEN(@dcRegionID) - 1)
			IF RIGHT(@dcIndustryID, 1) = ','
				SET @dcIndustryID = LEFT(@dcIndustryID, LEN(@dcIndustryID) - 1)

			------生成职位类别的表变量，因为职位类别有包含（父子）关系
			DECLARE @T_JobPlace AS TABLE(ID INT)
			DECLARE @T_JobType AS TABLE(ID INT)
			DECLARE @JobType AS VARCHAR(3000)
			DECLARE @JobPlace AS VARCHAR(2000)
			DECLARE @SQL AS NVARCHAR(MAX)
			DECLARE @WHERE AS VARCHAR(8000)
			DECLARE @FROM AS VARCHAR(1000)

			SET @JobPlace = ''
			SET @JobType=''
			----生成工作地点的表变量
			IF LEN(@dcRegionID) > 0
			BEGIN
				INSERT INTO @T_JobPlace
				SELECT * FROM dbo.fnSplit(@dcRegionID, ',')
				SELECT @JobPlace = (@JobPlace + ' OR a.dcRegionID Like ''' + LTRIM(STR(ID) + '%''')) FROM @T_JobPlace
				IF LEN(@JobPlace) > 0
					SET @JobPlace = RIGHT(@JobPlace, LEN(@JobPlace) -4)
			END

			----生成求聘职位的表变量
			IF LEN(@dcJobTypeID) > 0
			BEGIN
				DECLARE @T_Temp AS TABLE(ID INT)		--临时表，用于构建组合查询语句
				INSERT INTO @T_Temp
				SELECT * FROM dbo.fnSplit(@dcJobTypeID, ',')

				INSERT INTO @T_JobType
				SELECT DISTINCT ID FROM dcJobType WITH(NOLOCK)
				WHERE ParentId IN(SELECT ID FROM @T_TEMP) 
				OR ParentId2 in(SELECT ID FROM @T_TEMP)
				OR ID IN(SELECT ID FROM @T_TEMP)
				----生成in字符串
				SELECT @JobType = (@JobType + LTRIM(STR(ID) + ',')) FROM @T_JobType                                              
				IF RIGHT(@JobType, 1) = ','
					SET @JobType = LEFT(@JobType, LEN(@JobType) - 1)
			END

			----建立临时表
			CREATE TABLE #Job(
				RowID INT IDENTITY(1, 1), 
				ID INT NOT NULL, 
				dcJobTypeID SMALLINT NOT NULL, 
				dcJobTypeIDMinor SMALLINT NULL, 
				dcSalaryID TINYINT NOT NULL, 
				dcRegionID VARCHAR(6) NULL, 
				dcEducationID TINYINT NOT NULL, 
				MinExperience TINYINT NOT NULL, 
				RefreshDate SMALLDATETIME NULL
			)

			----生成插入临时表的Sql语句
			SET @SQL = '
				INSERT INTO #Job
				SELECT TOP ' + CONVERT(VARCHAR(3),@RowCount) + ' a.ID, a.dcJobTypeID, 
					a.dcJobTypeIDMinor, a.dcSalaryID, 
					a.dcRegionID, a.dcEducationID, a.MinExperience, 
					a.IssueDate'
			SET @FROM = '
				FROM JobPublish a WITH(NOLOCK)
				INNER JOIN cpMainPublish b WITH(NOLOCK) ON a.cpMainID=b.ID'
			----职位有效，单位新有效
			IF LEN(@dcIndustryID) > 0
				SET @WHERE = '
				WHERE b.ID IN (SELECT cpMainID FROM cpIndustry WHERE dcIndustryId in(' + @dcIndustryID + '))
				AND a.Valid = 1
				AND b.Valid = 1'
			ELSE
				SET @WHERE = '
				WHERE a.Valid = 1
				AND b.Valid = 1'

			----职位类别
			IF LEN(@dcJobTypeID) > 0
				SET @WHERE = @WHERE + '
				AND (a.dcJobTypeID IN(' + @JobType +')
					OR a.dcJobTypeIDMinor IN(' +@JobType + '))'
			IF LEN(@JobPlace) > 0 
				SET @WHERE = @WHERE + '
				AND (' + @JobPlace + ')'

			IF @dcSalaryID > 0
			BEGIN
				IF @dcSalaryID < 100				----从form中搜索，月薪跨2个级别, 是本级和上级别的薪金
				BEGIN
					SET @WHERE = @WHERE + '
				AND a.dcSalaryID IN(' + LTRIM(STR(@dcSalaryID)) + ',' + LTRIM(STR(@dcSalaryID + 1))
					SET @WHERE = @WHERE + ')'
				END
				IF @dcSalaryID = 100	----从筛选结果中点击面议，值是100
				BEGIN
					SET @WHERE = @WHERE + '
				AND a.dcSalaryID = 100'
				END
				IF @dcSalaryID > 100	----从筛选结果中点击搜索，月薪只有1个级别，传值时增加100
					SET @WHERE = @WHERE + '
				AND a.dcSalaryID=' + LTRIM(STR(@dcSalaryID-100))
			END
			----工作经验要求
			IF @MinExperience < 100
			SET @WHERE = @WHERE + ' 
				AND a.MinExperience = ' + LTRIM(STR(@MinExperience))

			----学历要求
			----'1初中', '2\3\4高中、中技、中专', '5大专', '6本科', '7硕士', '8博士
			IF @dcEducationID > 0
				IF @dcEducationID = 2
					SET @WHERE = @WHERE + '
				AND a.dcEducationID IN(2, 3, 4)'
				ELSE
					SET @WHERE = @WHERE + '
				AND a.dcEducationID = ' + LTRIM(STR(@dcEducationID))
			----1、全职；3、兼职；4实习。	2、全职/兼职 职位中无此项
			IF LEN(@EmployType) > 0
				SET @WHERE = @WHERE + '
				AND a.EmployType IN (' + @EmployType + ')'

			SET @SQL = @SQL + @FROM + @WHERE
			SET @SQL = @SQL + ' ORDER BY a.RefreshDate DESC, a.ID'
			EXEC(@SQL)
			DECLARE @CurrentCount AS SMALLINT
			DECLARE @NeedCount AS SMALLINT
			SELECT @CurrentCount = COUNT(*) FROM #Job
			IF @CurrentCount < @RowCount
			BEGIN
				SET @NeedCount = @RowCount - @CurrentCount
				----生成插入临时表的Sql语句
				SET @SQL = '
	
				INSERT INTO #Job
					SELECT TOP ' + CONVERT(VARCHAR(3),@NeedCount) + ' a.ID, a.dcJobTypeID, 
						a.dcJobTypeIDMinor, a.dcSalaryID, 
						a.dcRegionID, a.dcEducationID, a.MinExperience, 
						a.IssueDate'
				SET @FROM = '
					FROM JobPublish a WITH(NOLOCK)
					INNER JOIN cpMainPublish b WITH(NOLOCK) ON a.cpMainID=b.ID'
				----职位有效，单位新有效
				SET @WHERE = '
				WHERE a.Valid = 1
				AND b.Valid = 1 AND a.ID NOT IN(SELECT ID FROM #Job)'

				----职位类别
				IF LEN(@dcJobTypeID) > 0
					SET @WHERE = @WHERE + '
					AND (a.dcJobTypeID IN(' + @JobType +')
						OR a.dcJobTypeIDMinor IN(' +@JobType + '))'
				IF LEN(@JobPlace) > 0 
					SET @WHERE = @WHERE + '
					AND (' + @JobPlace + ')'
				SET @SQL = @SQL + @FROM + @WHERE
				SET @SQL = @SQL + ' ORDER BY a.RefreshDate DESC, a.ID'
				EXEC(@SQL)
				SELECT @CurrentCount = COUNT(*) FROM #Job
				IF @CurrentCount < @RowCount
				BEGIN
					SET @NeedCount = @RowCount - @CurrentCount
					--将工作地点扩大一级
					DECLARE @T_JobPlaceDistinct AS TABLE(ID INT)
					UPDATE @T_JobPlace SET ID = LEFT(ID,LEN(ID)-2) WHERE LEN(ID) > 2
					INSERT INTO @T_JobPlaceDistinct SELECT DISTINCT ID FROM @T_JobPlace
					SELECT @JobPlace = ''
					SELECT @JobPlace = (@JobPlace + ' OR a.dcRegionID Like ''' + LTRIM(STR(ID) + '%''')) FROM @T_JobPlaceDistinct
					IF LEN(@JobPlace) > 0
						SET @JobPlace = RIGHT(@JobPlace, LEN(@JobPlace) -4)

					--将职位类别扩大一级
					UPDATE @T_TEMP SET ID = LEFT(ID,LEN(ID)-2) WHERE LEN(ID) > 2
					DELETE FROM @T_JobType
					INSERT INTO @T_JobType
						SELECT DISTINCT ID FROM dcJobType WITH(NOLOCK)
						WHERE ParentId IN(SELECT ID FROM @T_TEMP) 
						OR ParentId2 in(SELECT ID FROM @T_TEMP)
						OR ID IN(SELECT ID FROM @T_TEMP)

					SELECT @JobType = ''
					SELECT @JobType = (@JobType + LTRIM(STR(ID) + ',')) FROM @T_JobType

					IF RIGHT(@JobType, 1) = ','
						SET @JobType = LEFT(@JobType, LEN(@JobType) - 1)

					----生成插入临时表的Sql语句
					SET @SQL = '
	
					INSERT INTO #Job
						SELECT TOP ' + CONVERT(VARCHAR(3),@NeedCount) + ' a.ID, a.dcJobTypeID, 
							a.dcJobTypeIDMinor, a.dcSalaryID, 
							a.dcRegionID, a.dcEducationID, a.MinExperience, 
							a.IssueDate'
					SET @FROM = '
						FROM JobPublish a WITH(NOLOCK)
						INNER JOIN cpMainPublish b WITH(NOLOCK) ON a.cpMainID=b.ID'
					----职位有效，单位新有效
					SET @WHERE = '
					WHERE a.Valid = 1
					AND b.Valid = 1 AND a.ID NOT IN(SELECT ID FROM #Job)'

					----职位类别
					IF LEN(@dcJobTypeID) > 0
						SET @WHERE = @WHERE + '
						AND (a.dcJobTypeID IN(' + @JobType +')
							OR a.dcJobTypeIDMinor IN(' +@JobType + '))'
					IF LEN(@JobPlace) > 0 
						SET @WHERE = @WHERE + '
						AND (' + @JobPlace + ')'
					SET @SQL = @SQL + @FROM + @WHERE
					SET @SQL = @SQL + ' ORDER BY a.RefreshDate DESC, a.ID'
					EXEC(@SQL)
				END
			END
			print '090909'
			INSERT INTO SHORTDB..JobRecommend 
			SELECT TOP 10 @PaMainID,a.SecondId EnJobID, a.Name as JobName,b.Name as cpName,a.dcSalaryID,
				a.EmployType,a.dcRegionID,a.dcEducationID,a.MinExperience,a.RefreshDate,b.SecondId EnCpMainID,
				b.dcCompanySizeID,a.Welfare1,a.Welfare2,a.Welfare3,a.Welfare4,a.Welfare5,a.Welfare6,a.Welfare7,a.Welfare8,
				a.Welfare9,a.Welfare10,a.Welfare11,a.Welfare12,a.Welfare13,a.Welfare14,a.Welfare15,a.Welfare16,
				a.Welfare17,a.Welfare18,
				ISNULL((SELECT IsOnline FROM caOnline WHERE caMainId =a.caMainID), 0) AS IsOnline,1,GETDATE(),b.HasLicence,a.ID,
				a.CaMainiD, b.ReplyRate
			FROM JobPublish a WITH(NOLOCK), cpMainPublish b WITH(NOLOCK), #Job c WITH(NOLOCK)
			WHERE a.cpMainID = b.ID AND a.ID = c.ID ORDER BY c.RowID
		END
		ELSE 
		BEGIN
			print '0909'
			SET @dcJobTypeID = dbo.FormatIDS(@dcJobTypeID)
			DECLARE @T_JobType2 AS TABLE(ID INT)
			DECLARE @JobTypeExpect AS VARCHAR(3000)
			DECLARE @T_Temp1 AS TABLE(ID INT)		--临时表，用于构建组合查询语句
			INSERT INTO @T_Temp1
			SELECT * FROM dbo.fnSplit(@dcJobTypeID, ',')
			INSERT INTO @T_JobType2
			SELECT DISTINCT ID FROM dcJobType WITH(NOLOCK)
			WHERE ParentId IN(SELECT ID FROM @T_TEMP1) 
			OR ParentId2 in(SELECT ID FROM @T_TEMP1)
			OR ID IN(SELECT ID FROM @T_TEMP1)
			----生成in字符串
			SELECT @JobTypeExpect = ''
			SELECT @JobTypeExpect = (@JobTypeExpect + LTRIM(STR(ID) + ',')) FROM @T_JobType2
			IF RIGHT(@JobTypeExpect, 1) = ','
				SET @JobTypeExpect = LEFT(@JobTypeExpect, LEN(@JobTypeExpect) - 1)
	
			DECLARE @T_JobPlace2 AS TABLE(ID INT)
			DECLARE @JobPlace2 AS VARCHAR(3000)
			INSERT INTO @T_JobPlace2
			SELECT * FROM dbo.fnSplit(@dcRegionID, ',')
			SELECT @JobPlace2 = ''
			SELECT @JobPlace2 = (@JobPlace2 + ' OR c.dcRegionID Like ''' + LTRIM(STR(ID) + '%''')) FROM @T_JobPlace2
			SELECT @JobPlace2 = (@JobPlace2 + ' OR c.dcRegionID = ''' + LTRIM(STR(LEFT(ID,2)))+'''' )
			FROM @T_JobPlace2 WHERE LEN(ID) > 2
			SELECT @JobPlace2 = (@JobPlace2 + ' OR c.dcRegionID = ''' + LTRIM(STR(LEFT(ID,4)))+'''' )
			FROM @T_JobPlace2 WHERE LEN(ID) > 4
			SET @JobPlace2 = RIGHT(@JobPlace2, LEN(@JobPlace2) -4)
			DECLARE @SQL2 AS VARCHAR(max)
			SET @SQL2 = '
				INSERT INTO SHORTDB..JobRecommend 
				SELECT TOP ' + CONVERT(VARCHAR, @RowCount) + ' '+CONVERT(VARCHAR(20),@PaMainID)+',b.SecondID EnJobID, b.Name JobName, c.Name CpName,
					 b.dcSalaryID, b.EmployType,b.dcRegionID, b.dcEducationID,b.MinExperience, b.Refreshdate,c.SecondID EnCpMainID,
					 c.dcCompanySizeID,b.Welfare1,b.Welfare2,b.Welfare3,b.Welfare4,b.Welfare5,b.Welfare6,b.Welfare7,b.Welfare8,
					b.Welfare9,b.Welfare10,b.Welfare11,b.Welfare12,b.Welfare13,b.Welfare14,b.Welfare15,b.Welfare16,
					b.Welfare17,b.Welfare18,dbo.GetCaOnlineStatus(b.caMainID) AS IsOnline,2,'''+CONVERT(VARCHAR(30),GETDATE())+''',
					c.HasLicence, b.ID, b.CaMainID, c.ReplyRate
				FROM exJobApply a WITH(NOLOCK), JobPublish b WITH(NOLOCK), cpMainPublish c WITH(NOLOCK)
				WHERE a.JobID = b.ID AND b.cpMainID = c.ID AND a.cvMainID IN(
					SELECT a.ID FROM cvMainPublish a WITH(NOLOCK)
					INNER JOIN paMainPublish b WITH(NOLOCK) ON a.paMainID = b.ID
					INNER JOIN cvJobPlacePublish c ON a.ID = c.cvMainID
					INNER JOIN cvJobTypePublish d ON a.ID = d.cvMainID
					WHERE d.dcJobTypeID IN(' + @JobTypeExpect +') AND (' + @JobPlace2 + ')
				) ORDER BY a.AddDate DESC'
			PRINT(@SQL2)
			EXEC (@SQL2)
		END
		SELECT TOP 20 * FROM SHORTDB..JobRecommend WHERE PaMainID = @PaMainID AND Type = @Type
	END
END
GO
/****** Object:  StoredProcedure [dbo].[procJobRefreshLog_tempSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
---职位刷新数预设置，获取可用的职位刷新数（定制刷新）
---harry
---2017-11-1
CREATE PROCEDURE [dbo].[procJobRefreshLog_tempSelect]
(  
	@beginDate SMALLDATETIME,
	@endDate SMALLDATETIME,
	@refreshType TINYINT,
	@weekDays CHAR(13),
	@hours VARCHAR(100),
	@minute	INT,
	@jobIds VARCHAR(200),
	@caMainId INT,
	@cpMainId INT 	
)
AS
SET NOCOUNT ON
BEGIN 
	--删除2分钟以上同一家企业的数据
	DELETE FROM JobRefreshLog_temp WHERE AddDate < DATEADD(MINUTE, -2, GETDATE()) AND cpMainId = @cpMainId

	DECLARE @sumRemain INT, @InsertRow INT
	SELECT @sumRemain = sum(remainJobRefreshQuota)
	FROM caOrder WITH(NOLOCK)
	WHERE cpMainID = @cpMainId
	AND openDate IS NOT NULL
	AND endDate > GETDATE()
	AND BeginDate < GETDATE()
	AND IsDeleted = 0
	AND OrderType IN(8, 15)	

	IF @sumRemain > 0
	BEGIN
		DELETE FROM JobRefreshLog_temp WHERE cpMainId = @cpMainId AND operateMan = @caMainId--清空数据,只能清除自己添加的
		--职位id
		DECLARE @TjobId AS TABLE(jobId INT, jobInfo NVARCHAR(200)) 
		--周
		DECLARE @Tweek AS TABLE(d INT) 
		--时间点
		DECLARE @Thour AS TABLE(hour VARCHAR(10)) 
		DECLARE @jobId INT, @jobinfo NVARCHAR(200), @hour VARCHAR(10), @weeknum TINYINT
		
		--插入所有数据
		INSERT INTO @TjobId (jobId)
		SELECT * FROM dbo.fnSplit(@jobIds, ',')
		WHERE a IN(SELECT ID FROM Job WITH(NOLOCK) WHERE cpMainId = @cpMainId AND Valid = 1)
		UPDATE @TjobId
		SET jobInfo= (
			SELECT name + ',' + b.FullName 
			FROM job a WITH(NOLOCK), dcRegion b WITH(NOLOCK)
			WHERE a.id = jobId AND a.dcregionid = b.id
		)
		 
		DECLARE @OneDay AS TABLE(RunDate DATETIME)
		DECLARE @AllDay AS TABLE(RunDate DATETIME)
		INSERT INTO @OneDay
		SELECT DATEADD(MINUTE, @Minute, DATEADD(HOUR, CONVERT(INT, a), @beginDate)) FROM dbo.FnSplit(@hours, ',')

		DECLARE @IntervalDay INT
		SET @IntervalDay = 0
		WHILE @IntervalDay <= DATEDIFF(DAY, @BeginDate, @endDate)
		BEGIN
			INSERT INTO @AllDay SELECT DATEADD(DAY, @IntervalDay, RunDate) FROM @OneDay
			SET @IntervalDay = @IntervalDay + 1
		END
		
		IF @refreshType= 2 --按周刷
		BEGIN
			INSERT INTO @Tweek
			SELECT * FROM dbo.fnSplit(@weekDays,',')---1,2,3,4,5,6,7
			--将@Tweek数据更改为sql对应的数据
			UPDATE @Tweek SET d= (
			CASE d
			WHEN 1 THEN 2
			WHEN 2 THEN 3
			WHEN 3 THEN 4
			WHEN 4 THEN 5
			WHEN 5 THEN 6
			WHEN 6 THEN 7
			ELSE 1 END  ) 
			
			--删除不在@Tweek中的数据
			DELETE FROM @AllDay WHERE DATEPART(weekday,RunDate) NOT IN(SELECT d FROM @Tweek) 
		END
		
		--每个职位，每天，每时刻
		INSERT INTO JobRefreshLog_temp(jobid, jobInfo, refreshType, preRefreshDateTime, operateMan, cpMainId, AddDate)
		SELECT a.jobId, a.jobinfo, 0, b.RunDate, @caMainId, @cpMainId, GETDATE()
		FROM @AllDay b, @TjobId a 
		SELECT @InsertRow = @@ROWCOUNT 

		DECLARE @NeedQuota INT, @remainJobRefreshQuota INT, @AllInsertRow INT
		 
		SELECT @AllInsertRow =count(*) from jobrefreshlog_temp where cpmainid = @cpmainid and runDateTime is null
		SELECT @NeedQuota = count(*) from jobrefreshlog where cpmainid = @cpmainid and runDateTime is null
		SELECT @remainJobRefreshQuota = sum(remainJobRefreshQuota) 
		FROM caorder WITH(NOLOCK) 
		WHERE cpmainid = @cpmainid 
		AND ordertype in(8, 15) AND isdeleted=0 AND opendate > '' AND getdate() BETWEEN begindate AND enddate 
		--计算可用数量
		IF (@NeedQuota +@AllInsertRow)> @remainJobRefreshQuota
		BEGIN 
			SELECT (@remainJobRefreshQuota-(@NeedQuota+@AllInsertRow-@InsertRow)) AS availableNumber
		END
		ELSE
		BEGIN
			SELECT (@remainJobRefreshQuota-@NeedQuota)  AS availableNumber
		END 
	END
	ELSE
	BEGIN
		SELECT 0 AS availableNumber	
	END
END 

GO
/****** Object:  StoredProcedure [dbo].[procJobRefreshLog_tempSelectSean]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
---职位刷新数预设置，获取可用的职位刷新数（定制刷新）
---harry
---2017-11-1
CREATE PROCEDURE [dbo].[procJobRefreshLog_tempSelectSean]
(  
	@beginDate SMALLDATETIME,
	@endDate SMALLDATETIME,
	@refreshType TINYINT,
	@weekDays CHAR(13),
	@hours VARCHAR(100),
	@minute	INT,
	@jobIds VARCHAR(200),
	@caMainId INT,
	@cpMainId INT 	
)
AS
SET NOCOUNT ON
BEGIN
	select 1, getdate()
	--删除2分钟以上同一家企业的数据
	DELETE FROM JobRefreshLog_temp WHERE AddDate < DATEADD(MINUTE, -2, GETDATE()) AND cpMainId = @cpMainId

	DECLARE @sumRemain INT
	SELECT @sumRemain = sum(remainJobRefreshQuota)
	FROM caOrder WITH(NOLOCK)
	WHERE cpMainID = @cpMainId
	AND openDate IS NOT NULL
	AND endDate > GETDATE()
	AND BeginDate < GETDATE()
	AND IsDeleted = 0
	AND OrderType IN(8, 15)	

	IF @sumRemain > 0
	BEGIN
		DELETE FROM JobRefreshLog_temp WHERE cpMainId = @cpMainId AND operateMan = @caMainId--清空数据,只能清除自己添加的
		--职位id
		DECLARE @TjobId AS TABLE(jobId INT, jobInfo NVARCHAR(200)) 
		--周
		DECLARE @Tweek AS TABLE(d INT) 
		--时间点
		DECLARE @Thour AS TABLE(hour VARCHAR(10)) 
		DECLARE @jobId INT, @jobinfo NVARCHAR(200), @hour VARCHAR(10), @weeknum TINYINT
		
		--插入所有数据
		INSERT INTO @TjobId (jobId)
		SELECT * FROM dbo.fnSplit(@jobIds, ',')
		WHERE a IN(SELECT ID FROM Job WITH(NOLOCK) WHERE cpMainId = @cpMainId AND Valid = 1)
		UPDATE @TjobId
		SET jobInfo= (
			SELECT name + ',' + b.FullName 
			FROM job a WITH(NOLOCK), dcRegion b WITH(NOLOCK)
			WHERE a.id = jobId AND a.dcregionid = b.id
		)
		IF @refreshType = 1		--按天刷
		BEGIN
			DECLARE @OneDay AS TABLE(RunDate DATETIME)
			DECLARE @AllDay AS TABLE(RunDate DATETIME)
			INSERT INTO @OneDay
			SELECT DATEADD(MINUTE, @Minute, DATEADD(HOUR, CONVERT(INT, a), @beginDate)) FROM dbo.FnSplit(@hours, ',')

			DECLARE @IntervalDay INT
			SET @IntervalDay = 0
			WHILE @IntervalDay <= DATEDIFF(DAY, @BeginDate, @endDate)
			BEGIN
				INSERT INTO @AllDay SELECT DATEADD(DAY, @IntervalDay, RunDate) FROM @OneDay
				SET @IntervalDay = @IntervalDay + 1
			END
			--每个职位，每天，每时刻
			INSERT INTO JobRefreshLog_temp(jobid, jobInfo, refreshType, preRefreshDateTime, operateMan, cpMainId, AddDate)
			SELECT a.jobId, a.jobinfo, 0, b.RunDate, @caMainId, @cpMainId, GETDATE()
			FROM @AllDay b, @TjobId a
		END
--		WHILE CONVERT(DATETIME, @beginDate, 101) <= CONVERT(DATETIME, @endDate, 101)
--		BEGIN
--			IF @refreshType = 1--按天刷
--			BEGIN
--				
--				--每个职位，每天，每时刻
--				WHILE EXISTS(SELECT TOP 1 jobId FROM @TjobId)
--				BEGIN
--					DELETE FROM @Thour 
--					INSERT INTO @Thour 
--					SELECT * FROM dbo.fnSplit(@hours, ',')
--					SELECT TOP 1 @jobId = jobid, @jobinfo = jobInfo FROM @TjobId
--					WHILE EXISTS (SELECT TOP 1 [hour] FROM @Thour)
--					BEGIN
--						SELECT TOP 1 @hour = [hour] FROM @Thour
--						INSERT INTO JobRefreshLog_temp( jobid, jobInfo, refreshType, preRefreshDateTime, operateMan, cpMainId, AddDate)
--						SELECT @jobId, @jobinfo, 0, CONVERT(DATETIME, CONVERT(VARCHAR(10),@beginDate,120)+' '+@hour+':'+ CONVERT(VARCHAR(10),@minute)), @caMainId, @cpMainId, GETDATE()
--						DELETE FROM @Thour WHERE hour = @hour
--					END
--					DELETE FROM @TjobId WHERE jobid = @jobId
--				END
--			END
--			ELSE
--			BEGIN  --按周刷				
--				INSERT INTO @Tweek
--				SELECT * FROM dbo.fnSplit(@weekDays,',')---1,2,3,4,5,6,7
--			
--				--判断时间是否在选择中
--				SELECT @weeknum =DATEPART(weekday,@beginDate)
--				SELECT @weeknum =(
--				CASE @weeknum 
--				WHEN 1 THEN 7
--				WHEN 2 THEN 1
--				WHEN 3 THEN 2
--				WHEN 4 THEN 3
--				WHEN 5 THEN 4
--				WHEN 6 THEN 5
--				ELSE 6 END )
--			
--				IF EXISTS(SELECT 'x' FROM @Tweek WHERE d = @weeknum )
--				BEGIN 
--					--每个职位，每天，每时刻
--					 DELETE FROM @TjobId
--					INSERT INTO @TjobId (jobId)
--					SELECT * FROM dbo.fnSplit(@jobIds, ',')
--					UPDATE @TjobId
--					SET jobInfo= (SELECT name+','+ b.FullName FROM job a WITH(NOLOCK), dcregion b WITH(NOLOCK) WHERE a.id = jobId AND a.dcregionid = b.id)
--			
--					WHILE EXISTS (SELECT TOP 1  jobid FROM @TjobId)
--					BEGIN
--						SELECT TOP 1 @jobId = jobid, @jobinfo = jobInfo FROM @TjobId
--						
--						DELETE FROM @Thour 
--						
--						INSERT INTO @Thour 
--						SELECT * FROM dbo.fnSplit(@hours, ',')
--						
--						WHILE EXISTS (SELECT TOP 1  [hour] FROM @Thour)
--						BEGIN
--							SELECT TOP 1 @hour = [hour] FROM @Thour
--							INSERT INTO JobRefreshLog_temp( jobid, jobInfo, refreshType, preRefreshDateTime, operateMan, cpMainId, AddDate)
--							SELECT @jobId, @jobinfo, 0, CONVERT(DATETIME, CONVERT(VARCHAR(10),@beginDate,120)+' '+@hour+':'+ CONVERT(VARCHAR(10),@minute)), @caMainId, @cpMainId, GETDATE()
--							DELETE FROM @Thour WHERE hour = @hour
--						END
--						DELETE FROM @TjobId WHERE jobid = @jobId
--					END 
--				END 
--			END 
--			SELECT @beginDate = DATEADD(DAY, 1, @beginDate)---天数+1
--		END
select 2, getdate()
		--获取占用的
		DECLARE @AllQuota INT, @InsertROw INT
		INSERT INTO JobRefreshLog_temp(jobRefreshSetId, jobid, jobInfo, refreshType, preRefreshDateTime, operateMan, cpMainId, AddDate)
		SELECT jobRefreshSetId,jobid, jobInfo, refreshType, preRefreshDateTime, operateMan, cpMainId, GETDATE() FROM jobRefreshLog 
		WHERE cpMainId = @cpMainId AND runDateTime IS NULL AND refreshType = 0
		SELECT @InsertROw = @@ROWCOUNT
select 3, getdate()
		---分配订单号，优先消耗订单结束时间早的，优分配占用时间早的刷新数
		--获取所有可用的订单
		SELECT ID, remainJobRefreshQuota, EndDate INTO #t FROM caOrder WITH(NOLOCK)
		WHERE cpMainID = @cpMainID
		AND openDate is NOT NULL
		AND endDate >GETDATE()
		AND OrderType IN(8,15)
		AND ISNULL(remainJobRefreshQuota,0) != 0
		ORDER BY endDate 
		SELECT @AllQuota = SUM(remainJobRefreshQuota) FROM #t
select 4, getdate()
		DECLARE @NeedQuota INT, @caoderId INT, @remainJobRefreshQuota INT
		SELECT @NeedQuota = COUNT(*) FROM JobRefreshLog_temp WHERE cpMainId = @CpMainId AND OrderId IS NULL
		WHILE EXISTS(SELECT TOP 1 id FROM #t)
		BEGIN
			SELECT TOP 1 @caoderId = id, @remainJobRefreshQuota = remainJobRefreshQuota FROM #t ORDER BY endDate
			IF @remainJobRefreshQuota >= @NeedQuota
			BEGIN
				UPDATE JobRefreshLog_temp SET orderId = @caoderId
				WHERE cpMainId = @cpMainId AND ISNULL(orderid, 0) = 0
				SET @NeedQuota = 0
				DELETE FROM #t
			END
			ELSE
			BEGIN
				UPDATE JobRefreshLog_temp SET orderId = @caoderId
				WHERE id IN(SELECT TOP (@remainJobRefreshQuota) Id FROM JobRefreshLog_temp
					WHERE cpMainId = @cpMainId AND ISNULL(orderid, 0) = 0
					ORDER BY preRefreshDateTime)
				SET @NeedQuota = @NeedQuota - @remainJobRefreshQuota
			END
			DELETE FROM #t WHERE id = @caoderId 
		END
		IF @NeedQuota > 0
		BEGIN
			SELECT 'zzz', getdate(), @NeedQuota
			RETURN
		END

select 5, getdate()
 		--计算可用的数据
		DECLARE @availableNumber INT, @needNumber INT, @OccupiedNumber INT,@preUsedNumber INT, @OtherUserNeedNumber INT
		SELECT @preUsedNumber=COUNT(1) FROM JobRefreshLog_temp WHERE jobid IN(SELECT jobid FROM @TjobId) AND ISNULL(orderid,0)!=0 AND ISNULL(jobRefreshSetId,0)=0 --本次成功的数量
		SELECT @needNumber=COUNT(1) FROM JobRefreshLog_temp WHERE jobid IN(SELECT jobid FROM @TjobId) AND ISNULL(jobRefreshSetId,0)=0 --本次需要的量
		SELECT @OtherUserNeedNumber=COUNT(1) FROM JobRefreshLog_temp WHERE ISNULL(jobRefreshSetId,0)=0 AND operateMan != @caMainId AND cpMainId = @cpMainId --其他人将要占用的
select 6, getdate()
		---计算已经占用的数量
		SELECT @OccupiedNumber= COUNT(1) 
		FROM jobRefreshLog 
		WHERE runDateTime IS NULL--占用
		AND refreshType= 0 --定制刷新
		AND jobid IN(SELECT id FROM job WHERE valid = 1 AND IsDelete=0 AND IssueEND>=GETDATE() AND cpMainId = @cpMainID)
select 7, getdate()
		SELECT @availableNumber = @sumRemain - @OccupiedNumber - @OtherUserNeedNumber
		--如果neednumber>preUsedNumber 则返回可用 preUsedNumber； 否则返回@availableNumber
		IF @needNumber> @preUsedNumber
		BEGIN
			SELECT @preUsedNumber AS availableNumber
		END
		ELSE
		BEGIN
			SELECT @availableNumber  AS availableNumber
		END
select 8, getdate()
	END
	ELSE
	BEGIN
		SELECT 0 AS availableNumber	
	END
select 'zzz', getdate()
END

GO
/****** Object:  StoredProcedure [dbo].[procJobRefreshOldCompanyInsert]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--职位刷新老用户数据表生成计划任务
--创建人：harry 2017-10-18
--规则 vip订单开通时间<刷新数上线时间同时订单未结束的 为老用户
CREATE PROCEDURE [dbo].[procJobRefreshOldCompanyInsert]
AS
BEGIN
	DECLARE @onLineTime DATETIME
	SET @onLineTime='2017-11-30 19:00'
	TRUNCATE TABLE jobRefreshOldCompany
	
	INSERT INTO jobRefreshOldCompany(cpMainId)
	SELECT DISTINCT cpMainId FROM caorder WHERE opendate < @onLineTime AND EndDate > GETDATE() AND ordertype = 8 AND IsDeleted=0
END

GO
/****** Object:  StoredProcedure [dbo].[procJobReportDataByCaMainIDSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.03
--创建人：Nick
--说明：获取当前6个月内统计过的职位ID和Name
--#####################################################
CREATE PROCEDURE [dbo].[procJobReportDataByCaMainIDSelect]
(
	@CaMainID INT,
	@AccoutType INT
)
AS
BEGIN TRY
	IF @AccoutType = 1
	BEGIN
		SELECT DISTINCT(jobid),b.* 
		FROM ReportDB..jobReportData a WITH(NOLOCK) 
		INNER JOIN (
			SELECT id,camainid,cpmainid,name,issuedate,issueend,null deletedate 
			FROM Job b WITH(NOLOCK) 
			WHERE b.cpmainid=@CaMainID 
			AND isdelete=0 
			AND issueend > GETDATE() 
		) b ON a.jobid=b.id  
		ORDER BY b.issuedate desc
		
		SELECT DISTINCT(jobid),b.* 
		FROM ReportDB..jobReportData a WITH(NOLOCK)  
		INNER JOIN (
			SELECT id,camainid,cpmainid,name,issuedate,issueend,null deletedate 
			FROM Job b WITH(NOLOCK) 
			WHERE b.cpmainid=@CaMainID 
			AND isdelete=0 
			AND issueend < GETDATE() ) b ON a.jobid=b.id 
			ORDER BY b.issueend DESC
			
		SELECT DISTINCT(jobid),b.* 
		FROM ReportDB..jobReportData a WITH(NOLOCK) 
		INNER JOIN (
			SELECT jobid id,camainid,cpmainid,jobname name,issuedate,issueend,deletedate 
			FROM JobDeleted b WITH(NOLOCK) 
			WHERE b.cpmainid=@CaMainID 
		) b ON  a.jobid =b.id  
		ORDER BY deletedate DESC	
	END
	ELSE IF @AccoutType = 2
	BEGIN
		SELECT DISTINCT(jobid),b.* 
		FROM ReportDB..jobReportData a WITH(NOLOCK) 
		INNER JOIN (
			SELECT id,camainid,cpmainid,name,issuedate,issueend,null deletedate 
			FROM Job b WITH(NOLOCK) 
			WHERE b.camainid=@CaMainID 
			AND isdelete=0 
			AND issueend > getdate() 
		) b ON a.jobid=b.id  
		ORDER BY b.issuedate DESC
		
		SELECT DISTINCT(jobid),b.* 
		FROM ReportDB..jobReportData a WITH(NOLOCK) 
		INNER JOIN (
			SELECT id,camainid,cpmainid,name,issuedate,issueend,null deletedate 
			FROM Job b WITH(NOLOCK) 
			WHERE b.camainid=@CaMainID 
			AND isdelete=0 
			AND issueend < GETDATE() 
		) b ON a.jobid=b.id 
		ORDER BY b.issueend DESC
		
		SELECT DISTINCT(jobid),b.* 
		FROM  ReportDB..jobReportData a WITH(NOLOCK) 
		INNER JOIN (
			SELECT jobid id,camainid,cpmainid,jobname name,issuedate,issueend,deletedate 
			FROM JobDeleted b WITH(NOLOCK) 
			WHERE b.camainid=@CaMainID 
		) b ON a.jobid =b.id  
		ORDER BY deletedate DESC
	END
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[procJobReportDataSumDetailSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.03
--创建人：Nick
--说明：根据参数从JobReportData表中取得详细数据
--修改：harry 增加jobidcount 2017-11-23
--#####################################################
CREATE PROCEDURE [dbo].[procJobReportDataSumDetailSelect]
(
	@beginDays INT,
	@endDays INT,
	@jobID INT,
	@cpMainID INT
)
AS
BEGIN TRY
	DECLARE @SQL VARCHAR(MAX)
	SET @SQL = 'SELECT countdate,SUM(applycount) applycount,SUM(viewcount) viewcount,SUM(interview) interview,
	SUM(interviewreply) interviewreply,SUM(interviewresult) interviewresult 
	FROM ReportDB..jobReportData Where countdate >= '+CONVERT(VARCHAR(20),@beginDays)+' 
	 AND countdate <= ' +CONVERT(VARCHAR(20),@endDays)
	IF @jobID > 0
	BEGIN
		SET @SQL = @SQL + ' AND jobID='+CONVERT(VARCHAR(20),@jobID)
	END
	ELSE 
	BEGIN
		SET @SQL = @SQL + '  AND jobid in (
			(
				SELECT id FROM Job with(nolock) 
				WHERE isdelete=0 
				AND cpmainid='+CONVERT(VARCHAR(20),@cpMainID)+'
			) union (
				SELECT jobid id 
				FROM JobDeleted WITH(NOLOCK)  
				WHERE cpmainid='+CONVERT(VARCHAR(20),@cpMainID)+'
			)
		)'
	END
	SET @SQL = @SQL + '  AND  countdate >= '+CONVERT(VARCHAR(20),@beginDays)+' AND countdate <= '+CONVERT(VARCHAR(20),@endDays)
	SET @SQL = @SQL + ' GROUP BY countdate'
	PRINT(@SQL)
	EXEC(@SQL)
	IF @jobID > 0
		SELECT 1 AS jobCount
	
	SELECT COUNT(distinct jobId) AS jobCount
	FROM ReportDB..jobReportData Where countdate >=  @beginDays 
	AND countdate <=  @endDays
        AND jobid in (
			(
				SELECT id FROM Job with(nolock) 
				WHERE isdelete=0 
				AND cpmainid= @cpMainID
			) union (
				SELECT jobid id 
				FROM JobDeleted WITH(NOLOCK)  
				WHERE cpmainid= @cpMainID
			))

END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[procJobReportDataSumSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.03
--创建人：Nick
--说明：根据参数从JobReportData表中取得汇总数据
--#####################################################
CREATE PROCEDURE [dbo].[procJobReportDataSumSelect]
(
	@beginDays INT,
	@endDays INT,
	@jobID INT,
	@orderBy INT,
	@caMainID INT,
	@AccoutType INT
)
AS
BEGIN TRY
	DECLARE @SQL VARCHAR(MAX)
	SET @SQL = 'SELECT a.jobid,SUM(ApplyCount) ApplyCount,SUM(ViewCount) ViewCount,SUM(interView) interView,
	SUM(interViewReply) interViewReply,SUM(interViewResult) interViewResult,b.id,camainid,cpmainid,name,
	issuedate,issueend,b.IsDelete 
	FROM ReportDB..jobReportData a with(nolock) 
	INNER JOIN (
		(
			SELECT id,camainid,cpmainid,name,issuedate,issueend,0 IsDelete 
			FROM Job with(nolock) 
			WHERE isdelete=0
		) UNION (
			SELECT jobid id,camainid,cpmainid,jobname  name,issuedate,issueend,1 IsDelete  
			FROM JobDeleted with(nolock)
		)
	) b ON a.jobid =b.id 
	WHERE a.countdate >= '+CONVERT(VARCHAR(20),@beginDays)+' AND a.countdate <= '+CONVERT(VARCHAR(20),@endDays)
	IF @jobID > 0
	BEGIN
		SET @SQL = @SQL + ' AND a.jobID='+CONVERT(VARCHAR(20),@jobID)
	END
	IF @AccoutType = 1
	BEGIN
		SET @SQL = @SQL + ' AND b.cpmainid='+CONVERT(VARCHAR(20),@caMainID)
	END
	ELSE IF @AccoutType = 2
	BEGIN
		SET @SQL = @SQL + ' AND b.camainid='+CONVERT(VARCHAR(20),@caMainID)
	END
	SET @SQL = @SQL + ' GROUP BY a.jobid,b.id,camainid,cpmainid,name,issuedate,issueend,IsDelete'
	IF @orderBy = 11
	BEGIN
		SET @SQL = @SQL + ' ORDER BY b.issuedate DESC'
	END
	ELSE IF @orderBy = 12
	BEGIN
		SET @SQL = @SQL + ' ORDER BY ApplyCount DESC'
	END
	ELSE IF @orderBy = 13
	BEGIN
		SET @SQL = @SQL + ' ORDER BY ViewCount DESC'
	END
	ELSE IF @orderBy = 14
	BEGIN
		SET @SQL = @SQL + ' ORDER BY interView DESC'
	END
	ELSE IF @orderBy = 15
	BEGIN
		SET @SQL = @SQL + ' ORDER BY interViewReply DESC'
	END
	ELSE IF @orderBy = 16
	BEGIN
		SET @SQL = @SQL + ' ORDER BY interViewResult DESC'
	END
	ELSE IF @orderBy = 21
	BEGIN
		SET @SQL = @SQL + ' ORDER BY b.issuedate'
	END
	ELSE IF @orderBy = 22
	BEGIN
		SET @SQL = @SQL + ' ORDER BY ApplyCount'
	END
	ELSE IF @orderBy = 23
	BEGIN
		SET @SQL = @SQL + ' ORDER BY ViewCount'
	END
	ELSE IF @orderBy = 24
	BEGIN
		SET @SQL = @SQL + ' ORDER BY interView'
	END
	ELSE IF @orderBy = 25
	BEGIN
		SET @SQL = @SQL + ' ORDER BY interViewReply'
	END
	ELSE IF @orderBy = 26
	BEGIN
		SET @SQL = @SQL + ' ORDER BY interViewResult'
	END
	PRINT(@SQL)
	EXEC(@SQL)
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[procJobReportDetailDataByCaMainIDSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.03
--创建人：Nick
--说明：根据参数从jobReportDetailData表中取得所有职位的详细数据
--#####################################################
CREATE PROCEDURE [dbo].[procJobReportDetailDataByCaMainIDSelect]
(
	@beginDays INT,
	@endDays INT,
	@caMainID INT,
	@AccoutType INT
)
AS
BEGIN TRY
	IF @AccoutType = 1
	BEGIN
		SELECT SUM(workyears1) workyears1,SUM(workyears2) workyears2,SUM(workyears3) workyears3,
		SUM(workyears4) workyears4,SUM(workyears5) workyears5,SUM(age1) age1,SUM(age2) age2,
		SUM(age3) age3,SUM(age4) age4,SUM(age5) age5,SUM(age6) age6,SUM(degree1) degree1,
		SUM(degree2) degree2,SUM(degree3) degree3,SUM(degree4) degree4,SUM(degree5) degree5,
		SUM(degree6) degree6,SUM(degree7) degree7,SUM(degree8) degree8,SUM(degree9) degree9,
		SUM(salary1) salary1,SUM(salary2) salary2,SUM(salary3) salary3,SUM(salary4) salary4,
		SUM(salary5) salary5,SUM(salary6) salary6,SUM(salary7) salary7,SUM(salary8) salary8,
		SUM(male) male,SUM(female) female,cpmainid 
		FROM ReportDB..jobReportDetailData a WITH(NOLOCK) 
		INNER JOIN (
			(
				SELECT  id,camainid,cpmainid,name,issuedate,issueend 
				FROM Job  WITH(NOLOCK) 
				WHERE isdelete=0
			) union (
				SELECT jobid id,camainid,cpmainid,jobname name,issuedate,issueend  
				FROM JobDeleted WITH(NOLOCK) 
			)
		) b  ON a.jobid =b.id 
		WHERE CpMainID=@caMainID 
		AND a.countdate >= @beginDays 
		AND a.countdate <= @endDays GROUP BY cpmainid
	END
	ELSE
	BEGIN
		SELECT SUM(workyears1) workyears1,SUM(workyears2) workyears2,SUM(workyears3) workyears3,
		SUM(workyears4) workyears4,SUM(workyears5) workyears5,SUM(age1) age1,SUM(age2) age2,
		SUM(age3) age3,SUM(age4) age4,SUM(age5) age5,SUM(age6) age6,SUM(degree1) degree1,
		SUM(degree2) degree2,SUM(degree3) degree3,SUM(degree4) degree4,SUM(degree5) degree5,
		SUM(degree6) degree6,SUM(degree7) degree7,SUM(degree8) degree8,SUM(degree9) degree9,
		SUM(salary1) salary1,SUM(salary2) salary2,SUM(salary3) salary3,SUM(salary4) salary4,
		SUM(salary5) salary5,SUM(salary6) salary6,SUM(salary7) salary7,SUM(salary8) salary8,
		SUM(male) male,SUM(female) female,camainid FROM ReportDB..jobReportDetailData a WITH(NOLOCK) 
		INNER JOIN (
			(
				SELECT id,camainid,cpmainid,name,issuedate,issueend 
				FROM Job WITH(NOLOCK) WHERE isdelete=0
			) UNION 
			(
				SELECT jobid id,camainid,cpmainid,jobname  name,issuedate,issueend  
				FROM JobDeleted with(nolock)
			)
		) b  ON a.jobid =b.id 
		WHERE CaMainID=@caMainID 
		AND a.countdate >= @beginDays 
		AND a.countdate <= @endDays GROUP BY CaMainID
	END
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[procjobReportDetailDataByJobIDSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.04
--创建人：Nick
--说明：根据参数从jobReportDetailData表中取得详细数据
--#####################################################
CREATE PROCEDURE [dbo].[procjobReportDetailDataByJobIDSelect]
(
	@BeginDays INT,
	@EndDays INT,
	@JobID iNT
)
AS
BEGIN TRY
	SELECT a.jobid,SUM(workyears1) workyears1,SUM(workyears2) workyears2,SUM(workyears3) workyears3,
	SUM(workyears4) workyears4,SUM(workyears5) workyears5,SUM(age1) age1,SUM(age2) age2,SUM(age3) age3,
	SUM(age4) age4,SUM(age5) age5,SUM(age6) age6,SUM(degree1) degree1,SUM(degree2) degree2,
	SUM(degree3) degree3,SUM(degree4) degree4,SUM(degree5) degree5,SUM(degree6) degree6,SUM(degree7) degree7,
	SUM(degree8) degree8,SUM(degree9) degree9,SUM(salary1) salary1,SUM(salary2) salary2,SUM(salary3) salary3,
	SUM(salary4) salary4,SUM(salary5) salary5,SUM(salary6) salary6,SUM(salary7) salary7,SUM(salary8) salary8,
	SUM(male) male,SUM(female) female,b.id,camainid,cpmainid,name,issuedate,issueend 
	FROM ReportDB..jobReportDetailData a WITH(NOLOCK) 
	INNER JOIN (
		(
			SELECT id,camainid,cpmainid,name,issuedate,issueend 
			FROM Job WITH(NOLOCK) 
			WHERE isdelete=0
		) UNION (
			SELECT jobid id,camainid,cpmainid,jobname  name,issuedate,issueend  
			FROM JobDeleted WITH(NOLOCK)
		) 
	) b  ON a.jobid =b.id 
	WHERE a.jobID=@JobID 
	AND a.countdate >= @BeginDays 
	AND a.countdate <= @EndDays 
	GROUP BY a.jobid,b.id,camainid,cpmainid,name,issuedate,issueend  
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[ProcJobSimilarCompareMonthInsert]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2016.8.1
--创建人：Peter
--说明：根据一个月内的投递情况，获取职位相似性
--#####################################################
CREATE PROCEDURE [dbo].[ProcJobSimilarCompareMonthInsert]
AS
BEGIN
	TRUNCATE TABLE exJobApplyMonthTemp
	
	INSERT INTO exJobApplyMonthTemp (JobId,CvMainID)
	SELECT jobID,CvMainID FROM exjobapply WITH(NOLOCK) WHERE addDate > GETDATE() - 30
	
	SELECT jobID,COUNT(1) cnt INTO #TJobSimilar FROM exJobApplyMonthTemp GROUP BY jobID having COUNT(1) > 1

	DECLARE @JobID INT,@JobCount INT
	
	WHILE EXISTS(SELECT jobID FROM #TJobSimilar)
	BEGIN
		SELECT TOP 1 @JobID = jobID,@JobCount = cnt 
		FROM #TJobSimilar
		
		INSERT INTO JobSimilarCompare (JobID,SimilarJobID,JobCount,Pecentage)
		SELECT TOP 3 @JobID,JobID,@JobCount,CAST(COUNT(1) AS FLOAT)*100/@JobCount 	
		FROM exJobApplyMonthTemp 	
		WHERE cvmainid IN(	
			SELECT cvMainID 
			FROM exJobApplyMonthTemp 
			WHERE jobid = @JobID) 
		AND jobid <> @JobID 	
		GROUP BY JobID 	
		ORDER BY COUNT(1) desc
		
		DELETE FROM #TJobSimilar WHERE jobID = @JobID
	END
	
	SELECT cvMainID,COUNT(1) cnt INTO #TCvLimite FROM exJobApplyMonthTemp GROUP BY cvMainID HAVING COUNT(1) > 1
	
	DECLARE @CvMainID INT,@CvAppplyCount INT

	WHILE EXISTS(SELECT CvMainID FROM #TCvLimite)
	BEGIN
		SELECT TOP 1 @CvMainID = cvMainID,@CvAppplyCount = cnt 
		FROM #TCvLimite
		
		INSERT INTO CvSimilarCompare (CvMainID,SimilarJobID,JobNum)
		SELECT TOP 10 @CvMainID,JobID,COUNT(1) 	
		FROM exJobApplyMonthTemp 	
		WHERE cvMainID IN(
			SELECT TOP 10 CvMainID 
			FROM exJobApplyMonthTemp
			WHERE JobID IN(	
				SELECT JobID 
				FROM exJobApplyMonthTemp 
				WHERE CvMainID = @CvMainID) 
			AND CvMainID <> @CvMainID 	
			GROUP BY CvMainID 	
			ORDER BY COUNT(1) DESC
		)
		AND CvMainID <> @CvMainID 	
		AND JobID NOT IN(
			SELECT SimilarJobID FROM CvSimilarCompare WITH(NOLOCK) WHERE cvMainID = @CvMainID --推荐过的就不再推荐了
		)
		GROUP BY JobID 	
		ORDER BY COUNT(1) desc
		
		DELETE FROM #TCvLimite WHERE CvMainID = @CvMainID
	END
END
GO
/****** Object:  StoredProcedure [dbo].[ProcJobSimilarCompareSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ProcJobSimilarCompareSelect]
(
	@CvMainID INT
)
AS
SET NOCOUNT ON
BEGIN
	SELECT jobID, COUNT(1) cnt 
	INTO #TJobSimilar 
	FROM exJobApplyMonthTemp
	WHERE JobID IN(
		SELECT JobID 
		FROM exJobApplyMonthTemp
		WHERE CvMainID = @CvMainID)
	GROUP BY jobID 
	HAVING COUNT(1) > 1
	
	DECLARE @T AS TABLE(
		JobID INT, 
		SimilarJobID INT, 
		JobCount INT, 
		Pecentage FLOAT, 
		SimilarCount INT
	)
	
	DECLARE @JobID INT, @JobCount INT
	
	WHILE EXISTS(SELECT jobID FROM #TJobSimilar)
	BEGIN
		SELECT TOP 1 @JobID = jobID, @JobCount = cnt 
		FROM #TJobSimilar
		
		INSERT INTO @T (JobID, SimilarJobID, JobCount, Pecentage, SimilarCount)
		SELECT @JobID, JobID, @JobCount, CAST(COUNT(1) AS FLOAT) * 100 / @JobCount, COUNT(1) 	
		FROM exJobApplyMonthTemp 	
		WHERE cvmainid IN(	
			SELECT cvMainID 
			FROM exJobApplyMonthTemp 
			WHERE jobid = @JobID) 
		AND jobid <> @JobID 
--		AND EXISTS(		--职位必须有效且没被删除
--			SELECT 'X' 
--			FROM Job WITH(NOLOCK) 
--			WHERE id = exJobApplyMonthTemp.JobID 
--			AND Valid = 1
--			AND IsDelete = 0
--			AND IssueEnd > GETDATE())
--		AND JobID NOT IN(	--已经申请过的不再推荐
--			SELECT JobID 
--			FROM exJobApply WITH(NOLOCK) 
--			WHERE CvMainID = @CvMainID
--		)
		GROUP BY JobID 	
		HAVING COUNT(1) > 1
		ORDER BY COUNT(1) desc
		
		DELETE FROM #TJobSimilar WHERE jobID = @JobID
	END	

	DELETE FROM @t
	WHERE SimilarJobID IN(		--职位必须有效且没被删除
		SELECT Id
		FROM Job WITH(NOLOCK) 
		WHERE Valid = 0)
	OR SimilarJobID IN(	--已经申请过的不再推荐
		SELECT JobID 
		FROM exJobApply WITH(NOLOCK) 
		WHERE CvMainID = @CvMainID)
 
	INSERT INTO @T (SimilarJobID, JobCount)
	SELECT TOP 10 JobID, COUNT(1) 	
	FROM exJobApplyMonthTemp
	WHERE cvMainID IN(
		SELECT TOP 100 CvMainID 
		FROM exJobApplyMonthTemp
		WHERE JobID IN(	
			SELECT JobID 
			FROM exJobApplyMonthTemp
			WHERE CvMainID = @CvMainID) 
		AND CvMainID <> @CvMainID 	
		GROUP BY CvMainID 	
		ORDER BY COUNT(1) DESC
	)
	AND CvMainID <> @CvMainID
	AND EXISTS(		--职位必须有效且没被删除
		SELECT 'X' 
		FROM Job WITH(NOLOCK) 
		WHERE id = exJobApplyMonthTemp.JobID  
		AND Valid = 1
		AND IsDelete = 0
		AND IssueEnd > GETDATE())
	AND JobID NOT IN(	--已经申请过的不再推荐
		SELECT JobID 
		FROM exJobApply WITH(NOLOCK) 
		WHERE CvMainID = @CvMainID
	)
	GROUP BY JobID 	
	HAVING COUNT(1) > 1
	ORDER BY COUNT(1) desc
	
	SELECT a.*, b.Name JobName, b.SecondID EnJobID, c.Name SimilarJobName, c.SecondID EnSimilarJobID, d.FullName JobRegion, e.FullName SimilarJobRegion 
	FROM @T a
	LEFT JOIN Job b WITH(NOLOCK) ON b.ID = a.JobID
	LEFT JOIN Job c WITH(NOLOCK) ON c.ID = a.SimilarJobID
	LEFT JOIN dcRegion d WITH(NOLOCK) ON d.ID = b.dcRegionID
	LEFT JOIN dcRegion e WITH(NOLOCK) ON e.ID = c.dcRegionID
	ORDER BY a.JobId, a.Pecentage DESC
	DROP TABLE #TJobSimilar
END
GO
/****** Object:  StoredProcedure [dbo].[procJobTagsBySaveInsert]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


--保存职位标签信息
CREATE PROCEDURE [dbo].[procJobTagsBySaveInsert]
(
	@JobID INT,
	@JobTags NVARCHAR(100)
)
AS
BEGIN
	IF (SELECT COUNT(1) FROM dbo.Split(@JobTags,'@')) > 5
	BEGIN
		RETURN -1
	END
	
	CREATE TABLE #T
	(
		Tags NVARCHAR(10),
		VerifyDate SMALLDATETIME
	)
	
	INSERT INTO #T(Tags)
	SELECT a 
	FROM dbo.Split(@JobTags,'@')
	
	DECLARE @ExistsTags NVARCHAR(MAX)
	SELECT @ExistsTags = 'A轮,水果零食,B轮,帅哥美女,C轮,定期团建,D轮,股权期权,13薪,国企控股,不出差,前瞻行业,扁平化,大厨三餐,寒暑假,朝十晚六,正能量,氛围融洽,不加班,弹性工作,下午茶,挑战高薪,牛人多,创新项目,大平台,环境优雅,健身房,季度加薪,台球桌,阳光团队,妹子多,CBD办公,高晋升,无需打卡,压力小,交通便利,自由互助,苹果电脑,领导Nice'
	
	UPDATE #T 
	SET VerifyDate = GETDATE()
	WHERE Tags IN(
		SELECT a 
		FROM dbo.Split(@ExistsTags,',')
	)
	OR EXISTS(
		SELECT TOP 1 'X' 
		FROM jobTags WITH(NOLOCK) 
		WHERE Tags = #T.Tags 
		AND VerifyDate IS NOT NULL
		ORDER BY ID
	)
	
	DELETE FROM jobTags
	WHERE JobID = @JobID
	
	INSERT INTO jobTags(JobID,Tags,VerifyDate,AddDate)
	SELECT @JobID,Tags,VerifyDate,GETDATE()
	FROM #T
	
	DROP TABLE #T
	
	RETURN 1
END


GO
/****** Object:  StoredProcedure [dbo].[procJobTagsByVerifyDelete]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--职位标签审核不通过
CREATE PROCEDURE [dbo].[procJobTagsByVerifyDelete]
(
	@TagsID INT
)
AS
BEGIN
	DELETE FROM jobTags
	WHERE id = @TagsID
END
GO
/****** Object:  StoredProcedure [dbo].[procJobTagsByVerifyUpdate]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 

--职位标签审核
CREATE PROCEDURE [dbo].[procJobTagsByVerifyUpdate]
(
	@JobID INT
)
AS
BEGIN
	UPDATE jobTags
	SET VerifyDate = GETDATE()
	WHERE JobID = @JobID
	AND VerifyDate IS NULL
END


GO
/****** Object:  StoredProcedure [dbo].[procJobTemplateWelfareByIDUpdate]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.04
--创建人：Nick
--说明：保存职位模版的薪酬福利
--修改：harry2016-3-29:修改job-jobtemplate 
--#####################################################
CREATE PROCEDURE [dbo].[procJobTemplateWelfareByIDUpdate]
(
	@Promotion VARCHAR(100),
	@Welfare1 INT,
	@Welfare2 INT,
	@Welfare3 INT,
	@Welfare4 INT,
	@Welfare5 INT,
	@Welfare6 INT,
	@Welfare7 INT,
	@Welfare8 INT,
	@Welfare9 INT,
	@Welfare10 INT,
	@Welfare11 INT,
	@Welfare12 INT,
	@Welfare13 INT,
	@Welfare14 INT,
	@Welfare15 INT,
	@Welfare16 INT,
	@Welfare17 INT,
	@Welfare18 INT,
	@Welfare19 INT,
	@ID INT
)
AS
BEGIN
	UPDATE jobtemplate  SET Promotion= @Promotion,
	Welfare1 = @Welfare1,
	Welfare2 = @Welfare2,
	Welfare3 = @Welfare3,
	Welfare4 = @Welfare4,
	Welfare5 = @Welfare5,
	Welfare6 = @Welfare6,
	Welfare7 = @Welfare7,
	Welfare8 = @Welfare8,
	Welfare9 = @Welfare9,
	Welfare10 = @Welfare10,
	Welfare11 = @Welfare11,
	Welfare12 = @Welfare12,
	Welfare13 = @Welfare13,
	Welfare14 = @Welfare14,
	Welfare15 = @Welfare15,
	Welfare16 = @Welfare16,
	Welfare17 = @Welfare17,
	Welfare18 = @Welfare18,
	Welfare19 = @Welfare19
	WHERE ID = @ID
	
	RETURN 1
END

GO
/****** Object:  StoredProcedure [dbo].[ProcJobToFriendInsert]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ProcJobToFriendInsert]
(
	@Email VARCHAR(50),
	@FriendName VARCHAR(20),
	@FromName VARCHAR(20),
	@IP VARCHAR(15),
	@JobId INT
)
AS
BEGIN
	INSERT INTO MarketDb..JobToFriend(Email, FriendName, FromName, IP, JobId)
	SELECT @Email, @FriendName, @FromName, @IP, @JobId

	RETURN 0
/*
	IF (SELECT COUNT(*) FROM MarketDb..JobToFriend WITH(NOLOCK)
		WHERE AddDate > GETDATE() - 1
		AND JobId = @JobID
		) > 20
		RETURN 0

	IF (SELECT COUNT(*) FROM MarketDb..JobToFriend WITH(NOLOCK)
		WHERE AddDate > GETDATE() - 1
		AND IP = @IP
		) > 30
		RETURN 0

	IF (SELECT COUNT(*) FROM MarketDb..JobToFriend WITH(NOLOCK)
		WHERE AddDate > GETDATE() - 1
		AND FriendName = @FriendName
		) > 10
		RETURN 0

	IF (SELECT COUNT(*) FROM MarketDb..JobToFriend WITH(NOLOCK)
		WHERE AddDate > GETDATE() - 1
		AND Email = @Email
		) > 10
		RETURN 0
	
	/*
	IF (SELECT COUNT(*) FROM MarketDb..JobToFriend WITH(NOLOCK)
		WHERE AddDate > GETDATE() - 1
		) > 2000
		RETURN 0
	*/

	RETURN 1
*/
END














GO
/****** Object:  StoredProcedure [dbo].[ProcJobTypeL1ByParentIdSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.28
--创建人：John
--说明：获取二级职位类别
--@parentId 一级职位类别编号
--修改记录：2014.11.04 增加查询字段
--#####################################################
CREATE PROCEDURE [dbo].[ProcJobTypeL1ByParentIdSelect]
(
	@parentId INT
)
AS
BEGIN TRY
	SELECT a.id,a.description jobtypel0,c.description jobtypel1,b.* 
	FROM dcJobTypeCategory a,dcJobTypeMap b,dcJobType c 
	WHERE a.Id = b.CategoryId 
	  AND b.JobTypeId = c.Id 
	  AND LEN(b.JobTypeId) > 2 
	  AND a.Id = @parentId 
	ORDER BY a.Id,b.OrderBy
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[ProcJobTypeSimilarByIDSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.4
--创建人：John
--说明：获取职位类别的匹配度范围
--#####################################################
CREATE PROCEDURE [dbo].[ProcJobTypeSimilarByIDSelect]
(
    @JobTypeID VARCHAR(1000)
)
AS
BEGIN
    --DECLARE @SQL AS VARCHAR(1000)
    --SET @SQL = 'SELECT * FROM dcjobtypesimilar WITH(NOLOCK) WHERE dcJobTypeId in (0' + @JobTypeID + '0) OR SimilarId in (0' + @JobTypeID + '0)'
    --EXEC(@SQL)
	SELECT TOP 0 0 ID, 0 dcJobTypeId, 0 SimilarId, 0 Coefficient
END

GO
/****** Object:  StoredProcedure [dbo].[ProcJobuiJobXmlOutSave]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ProcJobuiJobXmlOutSave]
AS
SET NOCOUNT ON
BEGIN
	CREATE TABLE #t(
		Id INT IDENTITY(1, 1),
		dcProvinceId TINYINT,
		JobId int NOT NULL,
		CompanyId int NOT NULL,
		EnJobID varchar(12) NULL,
		IssueDate smalldatetime NULL,
		IssueEnd smalldatetime NULL,
		Area nvarchar(20) NULL,
		JobName nvarchar(50) NOT NULL,
		CompanyName varchar(100) NOT NULL,
		JobDemand varchar(max) NULL,
		Brief varchar(6000) NULL,
		Email varchar(50) NOT NULL,
		Education nvarchar(10) NULL,
		Industry varchar(50) NULL,
		Telephone varchar(25) NULL,
		Fax varchar(20) NULL,
		Address nvarchar(60) NOT NULL,
		Zip char(6) NOT NULL,
		HomePage varchar(100) NOT NULL,
		LinkMan nvarchar(6) NULL,
		CompanySize varchar(10) NULL,
		Employtype varchar(6) NOT NULL,
		Experience varchar(7) NULL,
		Salary varchar(12) NOT NULL
	)

	INSERT INTO #t(dcProvinceId, JobId, CompanyId, EnJobID, IssueDate, IssueEnd, Area, JobName, CompanyName, JobDemand, Brief, Email, Education, Industry, Telephone, Fax, Address, Zip, HomePage, LinkMan, CompanySize, Employtype, Experience, Salary)
	SELECT b.dcProvinceID, a.Id JobId, b.Id CompanyId, a.SecondId EnJobID, a.IssueDate, a.IssueEnd + 3 + a.Id % 30,
		(SELECT MapBarName FROM dcRegion WHERE Id = a.dcRegionId) Area,
		a.Name JobName, b.Name CompanyName, a.Responsibility + CHAR(13) + a.Demand JobDemand,
		b.Brief, c.Email, (SELECT Description FROM dcEducation WHERE Id = dcEducationId) Education,
		SPACE(50) Industry,
		c.Telephone, c.Fax, ISNULL(b.Address, '') Address, ISNULL(b.Zip, '') Zip, ISNULL(b.HomePage, '') HomePage,
		CASE WHEN c.IsNameHide = 1 THEN LEFT(c.Name, 1) + CASE WHEN c.Gender = 1 THEN '女士' ELSE '先生' END
			ELSE c.Name
		END LinkMan,	
		CASE WHEN b.dcCompanySizeId = 1 THEN '1-49人'
			WHEN b.dcCompanySizeId = 2 THEN '50-99人'
			WHEN b.dcCompanySizeId IN(3, 4) THEN '100-499人'
			WHEN b.dcCompanySizeId = 5 THEN '500-999人'
			WHEN b.dcCompanySizeId = 6 THEN '1000人以上'
		END CompanySize,
		CASE WHEN Employtype = 1 THEN ' 全职'
			WHEN Employtype = 3 THEN '兼职'
			WHEN Employtype = 4 THEN '实习'
			ELSE '不限制'
		END Employtype,
		CASE WHEN MinExperience IN(1, 5) THEN '0-2年'
			WHEN MinExperience =  2 THEN '3-5年'
			WHEN MinExperience =  3 THEN '6-7年'
			WHEN MinExperience =  4 THEN '11-15年'
			WHEN MinExperience =  0 THEN '不限制'
		END Experience,
		CASE WHEN dcSalaryId < 3 THEN '2000以下'
			WHEN dcSalaryId IN(4, 5, 6, 7) THEN '2000-3999'
			WHEN dcSalaryId IN(8, 9) THEN '4000-5999'
			WHEN dcSalaryId IN(10) THEN '6000-7999'
			WHEN dcSalaryId IN(11) THEN '8000-9999'
			WHEN dcSalaryId IN(12) THEN ' 10000-14999'
			WHEN dcSalaryId IN(13) THEN '15000-19999'
			WHEN dcSalaryId IN(14) THEN '20000-29999'
			WHEN dcSalaryId IN(15) THEN '30000-49999'
			WHEN dcSalaryId IN(16, 17) THEN '50000以上'
			ELSE '面议'
		END Salary
	FROM Job a WITH(NOLOCK), cpMain b WITH(NOLOCK), caMain c WITH(NOLOCK)
	WHERE a.cpMainId = b.Id
	AND a.caMainId = c.Id
	AND a.IsDelete = 0
	AND a.Valid = 1
	AND b.Valid = 1
	AND a.IssueEnd > GETDATE()
	AND b.dcProvinceId = LEFT(a.dcRegionId, 2)
	ORDER BY b.dcProvinceId, a.IssueEnd, a.Id

	UPDATE #t SET Industry = (SELECT Description FROM dcIndustry WHERE Id IN(SELECT TOP 1 dcIndustryId FROM cpIndustry WHERE cpMainId = CompanyId))

	TRUNCATE TABLE ShortDb..JobuiJobXmlOut
	INSERT INTO ShortDb..JobuiJobXmlOut(dcProvinceId, JobId, CompanyId, EnJobID, IssueDate, IssueEnd, Area, JobName, CompanyName, JobDemand, Brief, Email, Education, Industry, Telephone, Fax, Address, Zip, HomePage, LinkMan, CompanySize, Employtype, Experience, Salary)
	SELECT dcProvinceId, JobId, CompanyId, EnJobID, IssueDate, IssueEnd, Area, JobName, CompanyName, JobDemand, Brief, Email, Education, Industry, Telephone, Fax, Address, Zip, HomePage, LinkMan, CompanySize, Employtype, Experience, Salary FROM #t ORDER BY ID

	UPDATE a SET a.PageNo = (b.Row + 2999) / 3000
	FROM ShortDb..JobuiJobXmlOut a, (SELECT id, dcProvinceId, ROW_NUMBER() OVER(PARTITION BY dcProvinceId ORDER BY Id) Row FROM ShortDb..JobuiJobXmlOut) b
	WHERE a.Id = b.Id

	DROP TABLE #t
END
GO
/****** Object:  StoredProcedure [dbo].[procJobWelfareByIDUpdate]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.04
--创建人：Nick
--说明：保存薪酬福利
--#####################################################
CREATE PROCEDURE [dbo].[procJobWelfareByIDUpdate]
(
	@Promotion VARCHAR(100),
	@Welfare1 INT,
	@Welfare2 INT,
	@Welfare3 INT,
	@Welfare4 INT,
	@Welfare5 INT,
	@Welfare6 INT,
	@Welfare7 INT,
	@Welfare8 INT,
	@Welfare9 INT,
	@Welfare10 INT,
	@Welfare11 INT,
	@Welfare12 INT,
	@Welfare13 INT,
	@Welfare14 INT,
	@Welfare15 INT,
	@Welfare16 INT,
	@Welfare17 INT,
	@Welfare18 INT,
	@Welfare19 INT,
	@ID INT
)
AS
SET NOCOUNT ON
DECLARE @p VARCHAR(100), @l INT, @L2 INT, @i INT
SELECT @p = LTRIM(RTRIM(@Promotion))
SET @L = LEN(@p)
IF @L > 6 AND CHARINDEX('$', @p) = 0 AND CHARINDEX(',', @p) = 0
	SET @Promotion = ''
ELSE IF @L > 4
BEGIN
	SELECT @I = 1, @L2 = 0
	WHILE @I <= @L
	BEGIN
		IF NOT EXISTS(SELECt 'x' FROM CommonChar WHERE CommonChar = SUBSTRING(@P, @i, 1))
			SET @L2 = @L2 + 1

		SET @I = @I + 1
	END
	IF @L2 > 4 OR @L2 * 2 > @L
		 SET @Promotion = ''
	IF @L2 * 2 > @L
		SET @Promotion = ''
END
------检查Promotion是否为正常汉字
BEGIN TRY
	UPDATE JOB 
	SET Promotion= @Promotion,
		Welfare1 = @Welfare1,
		Welfare2 = @Welfare2,
		Welfare3 = @Welfare3,
		Welfare4 = @Welfare4,
		Welfare5 = @Welfare5,
		Welfare6 = @Welfare6,
		Welfare7 = @Welfare7,
		Welfare8 = @Welfare8,
		Welfare9 = @Welfare9,
		Welfare10 = @Welfare10,
		Welfare11 = @Welfare11,
		Welfare12 = @Welfare12,
		Welfare13 = @Welfare13,
		Welfare14 = @Welfare14,
		Welfare15 = @Welfare15,
		Welfare16 = @Welfare16,
		Welfare17 = @Welfare17,
		Welfare18 = @Welfare18,
		Welfare19 = @Welfare19
	WHERE ID = @ID

	RETURN 1
END TRY
BEGIN CATCH
	RETURN 0
END CATCH

GO
/****** Object:  StoredProcedure [dbo].[procKpi_IeSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[procKpi_IeSelect]
AS
BEGIN
	INSERT INTO Kpi_IeToSales
	select id,title,present,improvement,effect,feasible,ApplyMeasure
	from kpi_ie
	where adddate > '2013-8-1'
	and receiver in(select id from manageruser where deptid=24)
	and (sender in(select id from manageruser where deptid in(3,4,5,19,25,27,28,31,34,36,37,39))
	 or sender between 180 and 190)
	AND ApplyMeasure>''
	AND ID NOT IN(select id from Kpi_IeToSales)
	ORDER BY ID
END










GO
/****** Object:  StoredProcedure [dbo].[procLinkByProvinceidSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[procLinkByProvinceidSelect]
(
	@Province_Id SMALLINT,
	@Type Smallint
)
AS
BEGIN
	SELECT Id, Text, Link, FileName, nofollow
	FROM Link WITH(NOLOCK)
	WHERE versionId  = @Province_Id 
	AND Type = @Type 
	AND Valid = 1
	AND Orderby >= 100
	AND Deleted = 0
	ORDER BY ORDERby
END














GO
/****** Object:  StoredProcedure [dbo].[procLinkByValidSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.10
--创建人：NICK
--说明：获取友情链接
--#####################################################
CREATE PROCEDURE [dbo].[procLinkByValidSelect]
AS
BEGIN
	SELECT * FROM Link WITH(NOLOCK) WHERE VersionID = 0 AND Valid = 1 AND Orderby >=100 AND Deleted = 0
END


GO
/****** Object:  StoredProcedure [dbo].[procLinkHomepageTextSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


--创建人 Lambo	
--20101009
--用于首页查询友情链接
CREATE PROCEDURE [dbo].[procLinkHomepageTextSelect]
(
	@province_id SMALLINT
)
AS
BEGIN
	SELECT id, text, link, nofollow FROM SearchDb..hplinkDay
	WHERE ProvinceID = @province_id
	AND Category IS NULL
	ORDER BY ID
/*
	IF @province_id < 100
		SELECT id, text, link, nofollow FROM SearchDb..hplinkDay
		WHERE ProvinceID = @province_id
		ORDER BY ID
	ELSE
	BEGIN
		IF EXISTS(SELECT 'x' FROM SearchDb..hplinkDay WHERE ProvinceID = @province_id)
			SELECT id, text, link, nofollow FROM SearchDb..hplinkDay
			WHERE ProvinceID = @province_id
			ORDER BY ID
		ELSE
			SELECT id, text, link, nofollow FROM SearchDb..hplinkDay
			WHERE ProvinceID = LEFT(@province_id, 2)
			ORDER BY ID
	END
*/
END














GO
/****** Object:  StoredProcedure [dbo].[procLinkInsert]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[procLinkInsert]
	@text NVARCHAR(50),
	@link VARCHAR(200),
	@versionid INT,
	@type TINYINT,
	@filename VARCHAR(1000),
	@valid SMALLINT,
	@linkman NVARCHAR(50),
	@telephone VARCHAR(50),
	@email VARCHAR(100),
	@nofollow bit
AS
INSERT INTO Link (text,link,versionid,type,filename,valid,linkman,telephone,email,nofollow) 
VALUES(@text,@link,@versionid,@type,@filename,@valid,@linkman,@telephone,@email,@nofollow)














GO
/****** Object:  StoredProcedure [dbo].[procLinkSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.10
--创建人：NICK
--说明：获取友情链接
--#####################################################
CREATE PROCEDURE [dbo].[procLinkSelect]
AS
BEGIN
	SELECT * FROM Link WITH(NOLOCK) WHERE VersionID = 0 AND Valid = 1 AND Orderby < 100 AND Deleted = 0
END


GO
/****** Object:  StoredProcedure [dbo].[procLinkSelectByProvinceid]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[procLinkSelectByProvinceid]
(
	@Province_Id SMALLINT,
	@Type Smallint
)
AS
BEGIN
	SELECT Id, Text, Link, FileName, nofollow
	FROM Link WITH(NOLOCK)
	WHERE versionId  = @Province_Id 
	AND Type = @Type 
	AND Valid = 1
	AND Orderby >= 100
	AND Deleted = 0
	ORDER BY ORDERby
END














GO
/****** Object:  StoredProcedure [dbo].[procLinkZhaopinTextSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--创建人 Lucifer	
--20120213
--用于分类搜索查询友情链接
CREATE PROCEDURE [dbo].[procLinkZhaopinTextSelect]
(
	@province_id SMALLINT,
	@category TINYINT
)
AS
BEGIN
	SELECT id, text, link, nofollow FROM SearchDb..hplinkDay
	WHERE ProvinceID = @province_id
	AND Category=@category
	ORDER BY ID
END














GO
/****** Object:  StoredProcedure [dbo].[procLotteryCompany50Select]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.5
--创建人：NICK
--说明：查询最新获奖的单位
--#####################################################
CREATE PROCEDURE [dbo].[procLotteryCompany50Select]
AS
BEGIN
	SELECT TOP 50 a.*,b.Name,(
		SELECT TOP 1 DetailName 
		FROM dcvipdetail 
		WHERE id IN (
			SELECT TOP 1 dcfeedetailid 
			FROM caOrder 
			WHERE id = a.caorderid
		)
	) ordername 
	FROM LotteryCompany a,cpmain b WITH(NOLOCK) 
	WHERE a.cpmainid = b.id 
	AND CaOrderID IS NOT NULL 
	AND Used=1 
	AND [Type] <> 9 
	AND CaOrderID IS NOT NULL
	ORDER BY a.ID DESC
END
GO
/****** Object:  StoredProcedure [dbo].[procLotteryCompanyByCpMainIDSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.5
--创建人：NICK
--说明：查询本单位获奖记录
--#####################################################
CREATE PROCEDURE [dbo].[procLotteryCompanyByCpMainIDSelect]
(
	@CpMainID INT
)
AS
BEGIN
	SELECT top 20 * FROM LotteryCompany WITH(NOLOCK) WHERE Used=1 AND cpMainID=@CpMainID
END


GO
/****** Object:  StoredProcedure [dbo].[procLotteryCompanyCountSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.5
--创建人：NICK
--说明：
--#####################################################
CREATE PROCEDURE [dbo].[procLotteryCompanyCountSelect]
(
	@CpMainID INT
)
AS
BEGIN
	SELECT COUNT(*) FROM LotteryCompany WHERE cpmainid=@CpMainID and used=0
END


GO
/****** Object:  StoredProcedure [dbo].[procLotteryCompanyLoginLogByCpMainIDSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.5
--创建人：NICK
--说明：
--#####################################################
CREATE PROCEDURE [dbo].[procLotteryCompanyLoginLogByCpMainIDSelect]
(
	@CpMainID INT
)
AS
BEGIN
	SELECT * FROM LotteryCompanyLoginLog WITH(NOLOCK) WHERE cpMainID=@CpMainID ORDER BY LoginDate
END


GO
/****** Object:  StoredProcedure [dbo].[procMajorClass1000Select]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.03
--创建人：Nick
--说明：根据字母得到专业信息
--#####################################################
CREATE PROCEDURE [dbo].[procMajorClass1000Select]
AS
BEGIN TRY
	SELECT * FROM MajorClass WITH(NOLOCK) WHERE istop1000=1 ORDER BY id
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[procMajorClass100Select]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.04
--创建人：Nick
--说明：获取专业分类
--#####################################################
CREATE PROCEDURE [dbo].[procMajorClass100Select]
AS
BEGIN TRY
	SELECT TOP 46 * FROM MajorClass WHERE IsTop100=1
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[ProcMajorClassByFirstLetterSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2014.10.28
--创建人：John
--说明：根据字母得到专业信息
--@ch 专业信息第一个字母
--#####################################################
CREATE PROCEDURE [dbo].[ProcMajorClassByFirstLetterSelect]
(
	@ch CHAR(1)
)
AS
BEGIN TRY
	SELECT * FROM MajorClass WHERE FirstLetter = @ch
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[procMajorClassNameByIDSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.03
--创建人：Nick
--说明：根据ID获得专业名称
--#####################################################
CREATE PROCEDURE [dbo].[procMajorClassNameByIDSelect]
(
	@ID INT
)
AS
BEGIN TRY
	SELECT majorname FROM MajorClass WITH(NOLOCK) WHERE id=@ID
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[ProcMajorClassSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2014.10.28
--创建人：John
--说明：专业信息分类的列表Xml
--#####################################################
CREATE PROCEDURE [dbo].[ProcMajorClassSelect]
AS
BEGIN TRY
	SELECT * FROM MajorClass WITH(NOLOCK) ORDER BY id
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[ProcManagerLogByAutoInsert]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ProcManagerLogByAutoInsert]
(
	@ManagerId INT,
	@Ip VARCHAR(15)
)
AS
BEGIN
	INSERT ManagerLog
	SELECT @ManagerId, GETDATE(), @ip, 'autoclick', '', NULL, NULL
END

GO
/****** Object:  StoredProcedure [dbo].[ProcManagerLogByIpUpdate]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ProcManagerLogByIpUpdate]
(
	@ManagerId INT,
	@Ip VARCHAR(15)
)
AS
SET NOCOUNT ON
BEGIN
	DECLARE @LoginDate DATETIME, @PrevIp VARCHAR(15)
	SELECT TOP 1 @LoginDate = LoginDate, @PrevIp = Ip FROM ManagerLog WHERE ManagerId = @ManagerId ORDER BY LoginDate DESC
	IF @LoginDate > DATEADD(MINUTE, -5, GETDATE()) AND @PrevIp <> @Ip
	BEGIN
		UPDATE ManagerLog SET Ip = @Ip, InternalIp = @PrevIp WHERE ManagerId = @ManagerId AND @LoginDate = LoginDate
	END
END
 
GO
/****** Object:  StoredProcedure [dbo].[procManagerUserAllSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.03
--创建人：Nick
--说明：获取全部公司用户
--#####################################################
CREATE PROCEDURE [dbo].[procManagerUserAllSelect]
AS
BEGIN TRY
	SELECT ID, Name, Name_Eng, Title, mobile, Email, Status, Type, Superior 
	FROM ManagerUser WITH(NOLOCK)
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[ProcManagerUserByIDSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.30
--创建人：Nick
--说明：获取工位信息
--#####################################################
CREATE PROCEDURE [dbo].[ProcManagerUserByIDSelect]
(
	@ID INT
)
AS
BEGIN TRY
	SELECT * FROM ManagerUser WHERE ID=@ID
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[ProcManagerUserByServiceStatusSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ProcManagerUserByServiceStatusSelect]
AS
BEGIN
SELECT Id, RtxStatus FROM Manageruser WITH(NOLOCK) WHERE ID BETWEEN 180 AND 182 OR ID = 222 OR ID = 223
END
GO
/****** Object:  StoredProcedure [dbo].[ProcManageruserBySOLStatusUpdate]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ProcManageruserBySOLStatusUpdate]
(
    @ManageruserID SMALLINT,
	@Online TINYINT
)
AS
BEGIN
	UPDATE Manageruser SET SOLStatus = @Online WHERE ID = @ManageruserID
	UPDATE a SET a.IsOnline = b.SOLStatus FROM ChatService a, Manageruser b WHERE a.ManagerUserID = b.ID
END


GO
/****** Object:  StoredProcedure [dbo].[procManagerUserDeptByIDSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[procManagerUserDeptByIDSelect]
(
	@id INT
)
AS
BEGIN
	SELECT a.id,a.name,b.DeptName FROM ManagerUser a WITH(NOLOCK),dept b WITH(NOLOCK) WHERE a.deptid = b.id AND a.id = @id
END


GO
/****** Object:  StoredProcedure [dbo].[ProcManageruserOnlineStatusUpdate]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ProcManageruserOnlineStatusUpdate]
	@ManageruserIDs VARCHAR(MAX)
AS
BEGIN
	UPDATE Manageruser SET SOLStatus=1,SOLTime=GETDATE() WHERE ID IN(SELECT a FROM dbo.fnSplit(@ManageruserIDs,','))
	UPDATE Manageruser SET SOLStatus=0 WHERE ID NOT IN(SELECT a FROM dbo.fnSplit(@ManageruserIDs,','))
	UPDATE ChatService SET IsOnline=1 WHERE ManageruserID IN(SELECT a FROM dbo.fnSplit(@ManageruserIDs,','))
	UPDATE ChatService SET IsOnline=0 WHERE ManageruserID NOT IN(SELECT a FROM dbo.fnSplit(@ManageruserIDs,','))
END






GO
/****** Object:  StoredProcedure [dbo].[ProcManagerUserRtxStatusSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.30
--创建人：Nick
--说明：获取状态
--#####################################################
CREATE PROCEDURE [dbo].[ProcManagerUserRtxStatusSelect]
(
	@ID INT
)
AS
BEGIN
	IF @ID = 0
		SELECT RtxStatus FROM Manageruser  WITH(NOLOCK) WHERE RtxStatus=1 AND type=5
	ELSE
		SELECT rtxstatus FROM ManagerUser WITH(NOLOCK) WHERE id=@ID
END

GO
/****** Object:  StoredProcedure [dbo].[procManagerUserSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.03
--创建人：Nick
--说明：获取公司用户
--#####################################################
CREATE PROCEDURE [dbo].[procManagerUserSelect]
AS
BEGIN TRY
	SELECT ID, Name, Name_Eng, Title, mobile, Email, Type, Superior 
	FROM ManagerUser WITH(NOLOCK) 
	WHERE Status < 3
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[ProcManagerUserStatusSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.30
--创建人：Nick
--说明：获取状态
--#####################################################
CREATE PROCEDURE [dbo].[ProcManagerUserStatusSelect]
(
	@ID INT
)
AS
BEGIN TRY
	SELECT ID
	FROM manageruser 
	WHERE Status < 3 
	AND ID=@ID
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[procManageruserSuperior]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
CREATE PROCEDURE [dbo].[procManageruserSuperior]
(
	@sender INT,
	@receiver INT
)
AS
--INSERT INTO procLog SELECT 'procManageruserSuperior', '', GETDATE()
BEGIN
	DECLARE @superior INT,@r1 INT,@r2 INT,@r3 INT,@s1 INT,@s2 INT,@s3 INT
	SELECT @s1=superior FROM manageruser WITH(nolock) WHERE id=@sender
	SELECT @r1=superior FROM manageruser WITH(nolock) WHERE id=@receiver

	SELECT @s2=superior FROM manageruser WITH(nolock) WHERE id=@s1
	SELECT @r2=superior FROM manageruser WITH(nolock) WHERE id=@r1

	SELECT @s3=superior FROM manageruser WITH(nolock) WHERE id=@s2
	SELECT @r3=superior FROM manageruser WITH(nolock) WHERE id=@r2

	IF @s1=@r1
		SET @superior=@s1
	ELSE IF @s1=@r2
		SET @superior=@s1
	ELSE IF @s2=@r1
		SET @superior=@r1
	ELSE IF @s1=@r3
		SET @superior=@s1
	ELSE IF @r1=@s3
		SET @superior=@r1
	ELSE IF @r2=@s2
		SET @superior=@s2
	ELSE IF @r2=@s3
		SET @superior=@r2
	ELSE IF @s2=@r3
		SET @superior=@s2
	ELSE IF @r3=@s3
		SET @superior=@s3
	ELSE
		SET @superior=1

	SELECT @superior AS superior
END














GO
/****** Object:  StoredProcedure [dbo].[procManagerUserSuperiorByIDSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.10
--创建人：John
--说明：获取顾问上级
--#####################################################
CREATE PROCEDURE [dbo].[procManagerUserSuperiorByIDSelect]
(
	@ManagerID INT
)
AS
BEGIN
	SELECT Superior FROM Manageruser WITH(NOLOCK) WHERE ID = @ManagerID
END


GO
/****** Object:  StoredProcedure [dbo].[procMapClassByIDSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.03
--创建人：Nick
--说明：根据ID获得专业名称
--#####################################################
CREATE PROCEDURE [dbo].[procMapClassByIDSelect]
(
	@ID INT
)
AS
BEGIN TRY
	SELECT MapName FROM MARKETDB..MapClass WHERE id=@ID
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[procMapClassBySubSiteIdSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.04
--创建人：Nick
--说明：获取职位列表
--#####################################################
CREATE PROCEDURE [dbo].[procMapClassBySubSiteIdSelect]
(
	@dcSubSiteId INT
)
AS
BEGIN TRY
	SELECT * FROM MARKETDB..MapClass WITH(NOLOCK) WHERE dcSubSiteId=@dcSubSiteId
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[procMarketMediaByProvinceIdSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2018.03.05
--创建人：Carl
--说明：获取最新的媒体动态
--#####################################################
CREATE PROCEDURE [dbo].[procMarketMediaByProvinceIdSelect]
(
	@ProvinceId INT
)
AS
BEGIN
	SELECT top 6 a.* FROM MarketDb..MarketMedia a, MarketDb..MarketProvince b
	 WHERE a.ID = b.MarketID
	 AND b.Type = 1 AND a.MediaType = 1
	 AND (b.ProvinceID = 0 OR b.ProvinceID = @ProvinceId)
	 ORDER BY a.AddDate DESC
END
GO
/****** Object:  StoredProcedure [dbo].[ProcMatchJobByRegionIDJobTypeIDSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.3
--创建人：John
--说明：根据Jobtype 获取当前地区相关招聘职位
--#####################################################
CREATE PROCEDURE [dbo].[ProcMatchJobByRegionIDJobTypeIDSelect]
(
	@dcRegionID VARCHAR(4),
	@dcJobTypeID VARCHAR(10)
)
AS
BEGIN
	SET @dcJobTypeID = SUBSTRING(@dcJobTypeID,1,2) + '%'
	SELECT TOP 20 dcJobTypeID,AvgSalary 
	FROM reportdb..SalaryReportJobtype 
	WHERE dcRegionid = @dcRegionID 
		AND dcJobTypeID LIKE @dcJobTypeID 
		AND LEN(dcJobTypeID) <> 2 
	ORDER BY JobNumber DESC
END


GO
/****** Object:  StoredProcedure [dbo].[ProcMblQlrcNewsInsert]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ProcMblQlrcNewsInsert]
AS
BEGIN
	IF NOT EXISTS(SELECT 'x' FROM QlrcNews WITH(NOLOCK) WHERE RefreshDate > DATEADD(MINUTE, -15, GETDATE()))
		RETURN
	
	DECLARE @COUNT INT, @ProvinceID INT
	SET @ProvinceID = 0
	WHILE EXISTS(SELECT 'x' FROM dcProvince WHERE ID > @ProvinceID AND Id <> 32)
	BEGIN
		SELECT TOP 1 @Count = 0, @ProvinceId = ID FROM dcProvince WHERE Id > @ProvinceId ORDER BY ID
		SELECT @COUNT = COUNT(1) 
		FROM QlrcNews WITH(NOLOCK) 
		WHERE 
		(
			EXISTS(SELECT 'x' FROM fnSplit(DetailType,',') b,dcNewsType c WITH(NOLOCK) WHERE b.a=c.ID AND c.Category=1) 
			OR 
			DetailType IS NULL
		) 
		AND VersionID = @ProvinceId
		AND NewsType = 2 
		AND DetailType NOT LIKE '%,2,%'

		IF @COUNT > 200
			SET @COUNT = 200
		
		DELETE SearchDb..mblQlrcNews WHERE ProvinceId = @ProvinceId
		INSERT INTO SearchDb..mblQlrcNews(ProvinceId, Rows, ID, Title, RefreshDate, Author, [Content], smallimg, ViewNumber_All, cnt)
		SELECT @ProvinceId, Rows, ID, Title, RefreshDate, Author, [Content], smallimg, ViewNumber_All, @COUNT AS cnt 
		FROM(
			SELECT TOP 200 ROW_NUMBER() OVER(ORDER BY RefreshDate DESC) AS Rows,
				ID, Title, RefreshDate, Author, [Content], smallimg, ViewNumber_All
			FROM QlrcNews WITH(NOLOCK) 
			WHERE 
			(
				EXISTS(SELECT 'x' FROM fnSplit(DetailType,',') b,dcNewsType c WITH(NOLOCK) WHERE b.a=c.ID AND c.Category=1) 
				OR 
				DetailType IS NULL
			) 
			AND VersionID = @ProvinceId
			AND NewsType = 2 
			AND DetailType NOT LIKE '%,2,%'
		) AS a 
		ORDER BY Rows
	END

	SET @ProvinceId = 32
	SELECT TOP 1 @Count = 0, @ProvinceId = ID FROM dcProvince WHERE Id > @ProvinceId ORDER BY ID
	SELECT @COUNT = COUNT(1) 
	FROM QlrcNews WITH(NOLOCK) 
	WHERE 
	(
		EXISTS(SELECT 'x' FROM fnSplit(DetailType,',') b,dcNewsType c WITH(NOLOCK) WHERE b.a=c.ID AND c.Category=1) 
		OR 
		DetailType IS NULL
	) 
	AND (VersionID = @ProvinceId OR VersionID=0) 
	AND NewsType = 2 
	AND DetailType NOT LIKE '%,2,%'

	IF @COUNT > 200
		SET @COUNT = 200
	
	DELETE SearchDb..mblQlrcNews WHERE ProvinceId = @ProvinceId
	INSERT INTO SearchDb..mblQlrcNews(ProvinceId, Rows, ID, Title, RefreshDate, Author, [Content], smallimg, ViewNumber_All, cnt)
	SELECT @ProvinceId, Rows, ID, Title, RefreshDate, Author, [Content], smallimg, ViewNumber_All, @COUNT AS cnt 
	FROM(
		SELECT TOP 200 ROW_NUMBER() OVER(ORDER BY RefreshDate DESC) AS Rows,
			ID, Title, RefreshDate, Author, [Content], smallimg, ViewNumber_All
		FROM QlrcNews WITH(NOLOCK) 
		WHERE 
		(
			EXISTS(SELECT 'x' FROM fnSplit(DetailType,',') b,dcNewsType c WITH(NOLOCK) WHERE b.a=c.ID AND c.Category=1) 
			OR 
			DetailType IS NULL
		) 
		AND (VersionID = @ProvinceId OR VersionID=0) 
		AND NewsType = 2 
		AND DetailType NOT LIKE '%,2,%'
	) AS a 
	ORDER BY Rows
END





GO
/****** Object:  StoredProcedure [dbo].[ProcMobileAreaSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2014.10.31
--创建人：John
--说明：获取手机号所在地
--#####################################################
CREATE PROCEDURE [dbo].[ProcMobileAreaSelect]
(
	@telNo VARCHAR(7)
)
AS
BEGIN
	SELECT TOP 1 City,CardType FROM dcMobileArea WITH(NOLOCK) WHERE Num = @telNo
END


GO
/****** Object:  StoredProcedure [dbo].[procMobileFollowUpInsert]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--20180322 CARL 手机号跟进
CREATE PROCEDURE [dbo].[procMobileFollowUpInsert](
	@Mobile VARCHAR(50),
	@SessionId VARCHAR(100)
)
AS
SET NOCOUNT ON
BEGIN
	IF EXISTS(SELECT TOP 1 'X' FROM paMobileFollowUp WHERE ContactDate IS NOT NULL AND Mobile=@Mobile)
		RETURN -1
	IF EXISTS(SELECT TOP 1 'X' FROM paMain WHERE Mobile=@Mobile)
		RETURN -2
	DELETE FROM paMobileFollowUp WHERE Mobile=@Mobile OR SessionId=@SessionId
	INSERT INTO paMobileFollowUp(Mobile,SessionId) VALUES (@Mobile,@SessionId)
END
SET NOCOUNT OFF
GO
/****** Object:  StoredProcedure [dbo].[procMobileFollowUpSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--20180322 Carl 手机号跟进查询
--20180323 Carl 修改
CREATE PROCEDURE [dbo].[procMobileFollowUpSelect](
	@Where VARCHAR(1000),
	@Page TINYINT
)
AS
SET NOCOUNT ON 
BEGIN
	SET @Where = dbo.SafeSQLBack(@Where)
	DECLARE @SQL VARCHAR(2000)
	CREATE TABLE #T(
		TitleID INT,
		Id INT,
		Mobile VARCHAR(50),
		PaMainId INT,
		ContactDate SMALLDATETIME,
		ContactMan INT,
		AddDate SMALLDATETIME
	)
	SET @SQL=' INSERT INTO #T
				(TitleID,Id,Mobile,PaMainId,ContactDate,ContactMan,AddDate)
			SELECT TOP 4000 ROW_NUMBER() OVER (ORDER BY a.AddDate DESC) AS TitleID,a.Id,
			a.Mobile,a.PaMainId,a.ContactDate,a.ContactMan,a.AddDate FROM paMobileFollowUp a WITH(NOLOCK) '
	IF LEN(@Where)>0
		SET @SQL = @SQL + ' WHERE 1=1 '+@Where
	--PRINT @SQL
	EXEC (@SQL)
	
	SELECT COUNT(*) FROM #T WITH(NOLOCK)
	SELECT * FROM #T WITH(NOLOCK) WHERE TitleID > (@Page-1)*20 AND TitleID <= @Page*20 ORDER BY TitleID
	DROP TABLE #T	
END
SET NOCOUNT OFF
GO
/****** Object:  StoredProcedure [dbo].[procMsEmailPrevSendByEmialNo84Insert]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--个人简历下载，浏览通知
--创建人：Harry2015-9-21
CREATE PROCEDURE [dbo].[procMsEmailPrevSendByEmialNo84Insert]
AS
SET NOCOUNT ON
BEGIN
	--取出1天内的简历浏览信息
	SELECT b.paMainId
	INTO #T1
	FROM caCvViewLog a WITH(NOLOCK), cvmain b WITH(NOLOCK)
	WHERE a.addDate BETWEEN CONVERT(VARCHAR(10), GETDATE() - 1, 120) AND  CONVERT(VARCHAR(10), GETDATE(), 120)
	AND a.cvMainId = b.id 
	
	 --取出1天内的简历下载信息插入到#T1
--	INSERT INTO #T1(paMainId, Name, Email, dcProvinceId)	
	INSERT INTO #T1(paMainId)
	SELECT b.paMainId
	FROM CaActiveLog a WITH(NOLOCK), CvMain b WITH(NOLOCK)
	WHERE a.addDate BETWEEN CONVERT(VARCHAR(10), GETDATE() - 1, 120) AND  CONVERT(VARCHAR(10), GETDATE(), 120)
	AND b.id = a.CvMainId	

	--将非重复内容插入到T2
	SELECT id PaMainId, Name, Email, dcProvinceId
	INTO #T2
	FROM paMain WITH(NOLOCK)
	WHERE ID IN(SELECT paMAinId FROM #T1 WITH(NOLOCK))
	
	---将msEmailSend中3天内没有的数据插入到msEmailPrevSend表中
	--取出3天内发送的数据 
	--将T1中删除3天内发送的数据
	DELETE FROM #T2 WHERE Email IN (SELECT Email FROM msEmailSend WITH(NOLOCK) WHERE addDate > CONVERT(VARCHAR(10), GETDATE() -3, 120))
	DELETE FROM #T2 WHERE Email LIKE '%@qq.com'
	--将T1中的数据插入到msEmailPrevSend
	INSERT INTO msEmailPrevSend(cpMainId, paMainId, EmailNo, EmailTitle, Email, dcSubsiteId, IsSend, JsonData)
	SELECT NULL, paMainId, 20, '企业关注通知', Email, dcProvinceId, 0, '"PaName":"' + Name + '"'
	FROM #T2 WITH(NOLOCK)	
END 

GO
/****** Object:  StoredProcedure [dbo].[ProcNewJobRelatedSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ProcNewJobRelatedSelect]
(
	@dcRegionId VARCHAR(6),
	@dcJobTypeId VARCHAR(4)
)
AS
SET NOCOUNT ON
BEGIN
	SELECT TOP 13 SecondId, Name
	FROM NewJobRelated WITH(NOLOCK) 
	WHERE dcRegionId = LEFT(@dcRegionId, 2) 
	AND dcJobTypeId = LEFT(@dcJobTypeId, 2)
	ORDER BY RowNo
END

GO
/****** Object:  StoredProcedure [dbo].[ProcNewJobSnapSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ProcNewJobSnapSelect]
(
	@dcProvinceId INT
)
AS
SET NOCOUNT ON
BEGIN
	DECLARE @PageId INT, @MaxPage INT
	SELECT @MaxPage = MaxPage FROM ShortDb..NewJobSnapIndex WHERE dcProvinceId = @dcProvinceId
	SET @PageId = RAND() * (@MaxPage - 1) + 1

	SELECT * FROM ShortDb..NewJobSnap WITH(NOLOCK) 
	WHERE dcProvinceId = @dcProvinceId
	AND PageId = @PageId
	ORDER BY Seq
END

GO
/****** Object:  StoredProcedure [dbo].[procNewsAnalysisByProvinceIdSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2018.03.05
--创建人：Carl
--说明：获取最新的就业大数据
--修改：harry IsDelete!=1 2018-5-23
--#####################################################
CREATE PROCEDURE [dbo].[procNewsAnalysisByProvinceIdSelect]
AS
BEGIN
 SELECT TOP 5 * FROM MainDb..NewsAnalysis WITH(NOLOCK) WHERE IsDelete!=1 ORDER BY AnnounceDate DESC
END
GO
/****** Object:  StoredProcedure [dbo].[ProcNewsAnalysisSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2017.03.17
--创建人：Harry
--说明：获取就业大数据 
--#####################################################
CREATE PROCEDURE [dbo].[ProcNewsAnalysisSelect]
(
	@PageNo INT
)
AS
BEGIN 
	SET NOCOUNT ON
	CREATE TABLE #WxNID
	(
		NID INT IDENTITY(1,1),
		ID INT
	)
	INSERT INTO #WxNID(ID) SELECT TOP (@PageNo * 8) ID 
	FROM NewsAnalysis WITH(NOLOCK) WHERE newstype=1 AND ISNULL(IsDelete,0) = 0 ORDER BY announcedate DESC
	DELETE FROM #WxNID WHERE NID < (@PageNo - 1) * 8 + 1
	--总条数
	SELECT COUNT(1) FROM NewsAnalysis WITH(NOLOCK) WHERE newstype=1 AND ISNULL(IsDelete,0)=0 
	--当前页
	SELECT * FROM NewsAnalysis WITH(NOLOCK) WHERE ID IN (SELECT ID FROM #WxNID)  ORDER BY announcedate desc
	--当前页详情
	SELECT * FROM NewsAnalysis WITH(NOLOCK) WHERE  newstype=2 and parentID IN (SELECT ID FROM #WxNID)  ORDER BY announcedate desc
	DROP TABLE #WxNID
	SET NOCOUNT OFF
END


GO
/****** Object:  StoredProcedure [dbo].[ProcNoSendSmsInsert]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ProcNoSendSmsInsert]
(
	@NoSend VARCHAR(MAX)
)
AS
BEGIN
	INSERT NoSendSms
	SELECT SUBSTRING(a, 2,11)
	FROM dbo.fnSplit(@NoSend,'||')
	WHERE a LIKE '%#N#%'
	AND SUBSTRING(a, 2,11) NOT IN(SELECT mobile FROM marketDb..NoSendSms)
END











GO
/****** Object:  StoredProcedure [dbo].[procOnlineByIDSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.03
--创建人：Nick
--说明：检查online=1
--#####################################################
CREATE PROCEDURE [dbo].[procOnlineByIDSelect]
(
	@UserID INT,
	@Type INT
)
AS
BEGIN TRY
	IF @Type = 0
	BEGIN
		SELECT 'x' FROM paOnline WITH(NOLOCK) WHERE IsOnline = 1 AND paMainId = @UserID
	END
	ELSE
	BEGIN
		SELECT 'x' FROM caOnline WITH(NOLOCK) WHERE IsOnline = 1 AND caMainId = @UserID
	END
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[procOvertimeDeptInsert]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----------------
--创建日期：20130725
--创建人：Nick
--功能说明：用于生成每月部门加班次数、签到时间、签退时间、登录后台次数、rtx登录次数、在线时间等
-----------------
CREATE PROCEDURE [dbo].[procOvertimeDeptInsert]
AS
BEGIN
	--Select CONVERT(varchar(100), GETDATE(), 112)
	DECLARE @begindate int,@enddate int
	DECLARE @deptid int,@deptname nvarchar(50),@cnt int
	DECLARE @a TABLE (manageruserid INT, cnt numeric(18,2))
	DECLARE @AttendanceCheckOut int, @AttendanceCheckIn int
	DECLARE @logindaysAfter18 numeric(18,2),@logindaysWeekend numeric(18,2)
	DECLARE @CheckMonth VARCHAR(8) 
	Select @CheckMonth = SUBSTRING(CONVERT(varchar(100),GETDATE(), 112),0,7)
	SET @enddate = @CheckMonth + '25'
	SET @begindate = CONVERT(VARCHAR(8), DATEADD(MONTH, -1, CONVERT(DATETIME, @CheckMonth + '26')), 112)
	--删除当月数据
	DELETE FROM OvertimeDept  WHERE YEARMONTH=@CheckMonth
	DECLARE c_manageruser CURSOR FOR 
	select id,deptname from dept with(nolock) where id in (3,5,11,23,24,26,14,29,36,27,4, 28, 30, 31, 34, 19, 25, 15, 16, 22, 35)  
	FOR READ ONLY

	OPEN c_manageruser
	FETCH NEXT FROM c_manageruser INTO @deptid,@deptname

	WHILE @@FETCH_STATUS = 0
	BEGIN

	  Delete from @a

		insert into @a (manageruserid, cnt)
		select manageruserid,
		avg(datepart(hh,AttendanceCheckOut)*60+datepart(mi,AttendanceCheckOut)) cnt
		from overtime with(nolock)
		where WordDate >=@begindate AND WordDate<=@enddate AND AttendanceCheckOut is not null
		and (datepart(hh,AttendanceCheckOut)*100+datepart(mi,AttendanceCheckOut))>1720
		group by manageruserid
		order by cnt desc

		select @AttendanceCheckOut= dbo.DateTo(avg(cnt)) from @a a where (select deptid from manageruser with(nolock) where id=a.manageruserid)=@deptid
		or 
		(select superior from dept with(nolock) 
		where  id=(select deptid from manageruser with(nolock) where id=a.manageruserid))=@deptid

		Delete from @a

		insert into @a (manageruserid, cnt)
		select manageruserid,
		avg(datepart(hh,AttendanceCheckIn)*60+datepart(mi,AttendanceCheckIn)) cnt
		from  overtime  with(nolock)
		where WordDate >=@begindate AND WordDate<=@enddate AND AttendanceCheckIn is not null
		and (datepart(hh,AttendanceCheckIn)*100+datepart(mi,AttendanceCheckIn))<900
		group by manageruserid
		order by cnt desc

		select @AttendanceCheckIn= dbo.DateTo(avg(cnt)) from @a a where (select deptid from manageruser with(nolock) where id=a.manageruserid)=@deptid
		or 
		(select superior from dept with(nolock) 
		where  id=(select deptid from manageruser with(nolock) where id=a.manageruserid))=@deptid

		Delete from @a

		insert into @a (manageruserid, cnt)
		select manageruserid,count(1) cnt
		from overtime with(nolock)
		where WordDate >=@begindate AND WordDate<=@enddate AND logincountafter1755>0
		group by manageruserid
		order by cnt desc

		insert into @a (manageruserid, cnt)
			select distinct manageruserid,0 from overtime with(nolock)
		where manageruserid not in 
		(select distinct manageruserid
		from overtime with(nolock)
		where WordDate >=@begindate AND WordDate<=@enddate AND logincountafter1755>0
		group by manageruserid)

		select @logindaysAfter18= avg(cnt) from @a a where (select deptid from manageruser with(nolock) where id=a.manageruserid)=@deptid
		or 
		(select superior from dept with(nolock) 
		where  id=(select deptid from manageruser with(nolock) where id=a.manageruserid))=@deptid

		Delete from @a

		insert into @a (manageruserid, cnt)
		select manageruserid,count(1) cnt
		from overtime with(nolock)
		where WordDate >=@begindate AND WordDate<=@enddate AND worktype=3 and (logincountafter1755+logincountbefore1755)>0
		group by manageruserid
		order by cnt desc

		insert into @a (manageruserid, cnt)
			select distinct manageruserid,0 from overtime with(nolock)
		where manageruserid not in 
		(select distinct manageruserid
		from overtime with(nolock)
		where WordDate >=@begindate AND WordDate<=@enddate AND worktype=3 and (logincountafter1755+logincountbefore1755)>0
		group by manageruserid
		)

		select @logindaysWeekend = avg(cnt) from @a a where (select deptid from manageruser with(nolock) where id=a.manageruserid)=@deptid
		or 
		(select superior from dept with(nolock) 
		where  id=(select deptid from manageruser with(nolock) where id=a.manageruserid))=@deptid

		insert into OvertimeDept (deptid,deptname,yearmonth,checkIn,checkOut,logindaysAfter18,logindaysWeekend)
		values (@deptid,@deptname,@CheckMonth,@AttendanceCheckIn,@AttendanceCheckOut, @logindaysAfter18,@logindaysWeekend)

		FETCH NEXT FROM c_manageruser INTO @deptid,@deptname
	END
	CLOSE c_manageruser
	DEALLOCATE c_manageruser

END

GO
/****** Object:  StoredProcedure [dbo].[procOverTimeInsert]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--[procOverTimeInsert] 201307
-----------------
--创建日期：20130725
--创建人：Nick
--功能说明：用于生成每月每人每天的加班次数、签到时间、签退时间、登录后台次数、rtx登录次数、在线时间等
-----------------
CREATE PROCEDURE [dbo].[procOverTimeInsert]
AS
BEGIN
	DECLARE @manageruserid int
	DECLARE @workdate int,@worktype tinyint,@LoginCountAfter1755 smallint
	DECLARE @LoginCountBefore1755 smallint
	DECLARE @AttendanceCheckOut datetime, @AttendanceCheckIn datetime
	DECLARE @CheckMonthDay VARCHAR(8) 
	Select @CheckMonthDay = CONVERT(varchar(100), dateadd(day,-3,GETDATE()), 112)
	--SET @enddate = @CheckMonth + '25'
	--SET @begindate = CONVERT(VARCHAR(8), DATEADD(MONTH, -1, CONVERT(DATETIME, @CheckMonth + '26')), 112)
	--删除当天数据
	DELETE FROM overtime WHERE WordDate =@CheckMonthDay
	DECLARE c_manageruser CURSOR FOR 
	SELECT id FROM manageruser with(nolock) where status<=2 and id<>146
	FOR READ ONLY

	OPEN c_manageruser
	FETCH NEXT FROM c_manageruser INTO @manageruserid

	WHILE @@FETCH_STATUS = 0
	BEGIN
		DECLARE c_WorkDate CURSOR FOR 
		select workdate,type from workdate with(nolock)
		where workdate = @CheckMonthDay
		order by workdate OPEN c_WorkDate

		FETCH NEXT FROM c_WorkDate INTO @workdate,@worktype

		WHILE @@FETCH_STATUS = 0
		BEGIN
			--1755之后 登录次数
			select @LoginCountAfter1755=count(1) from managerlog with(nolock) 
			where managerid=@manageruserid
			and year(logindate)*10000+month(logindate)*100+day(logindate)= @workdate
			and datepart(hh,logindate)*100+datepart(mi,logindate)>1755
			--1755之前 登录次数
			select @LoginCountBefore1755=count(1) from managerlog with(nolock) 
			where managerid=@manageruserid
			and year(logindate)*10000+month(logindate)*100+day(logindate)= @workdate
			and datepart(hh,logindate)*100+datepart(mi,logindate)<=1755

			set @AttendanceCheckOut=null
			set @AttendanceCheckIn=null
			select @AttendanceCheckOut=checkout, @AttendanceCheckin=checkin from OaDB..Attendance with(nolock)
			where manageruserid=@manageruserid and attendancedate=@workdate

			insert into overtime (ManagerUserid,WordDate,LoginCountAfter1755,LoginCountBefore1755,RTXonlineAfter1755,RTXonlineBeforer1755,AttendanceCheckOut,AttendanceCheckIn,WorkType) values
			(@manageruserid,@workdate,@LoginCountAfter1755,@LoginCountBefore1755,null,null,@AttendanceCheckOut,@AttendanceCheckIn,@worktype)

			FETCH NEXT FROM c_WorkDate INTO @workdate,@worktype
	END
	CLOSE c_WorkDate
	DEALLOCATE c_WorkDate
		FETCH NEXT FROM c_manageruser INTO @manageruserid
	END
	CLOSE c_manageruser
	DEALLOCATE c_manageruser
END











GO
/****** Object:  StoredProcedure [dbo].[procOverTimeInsertBAK]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--[procOverTimeInsert] 201307
-----------------
--创建日期：20130725
--创建人：Nick
--功能说明：用于生成每月每人每天的加班次数、签到时间、签退时间、登录后台次数、rtx登录次数、在线时间等
-----------------
CREATE PROCEDURE [dbo].[procOverTimeInsertBAK]
(
	@CheckMonth VARCHAR(6)
)
AS
BEGIN
	DECLARE @manageruserid int
	DECLARE @workdate int,@worktype tinyint,@LoginCountAfter1755 smallint,@begindate int,@enddate int
	DECLARE @LoginCountBefore1755 smallint
	DECLARE @AttendanceCheckOut datetime, @AttendanceCheckIn datetime

	SET @enddate = @CheckMonth + '25'
	SET @begindate = CONVERT(VARCHAR(8), DATEADD(MONTH, -1, CONVERT(DATETIME, @CheckMonth + '26')), 112)
	--删除当月数据
	DELETE FROM overtime WHERE WordDate >=@begindate AND WordDate<=@enddate
	DECLARE c_manageruser CURSOR FOR 
	SELECT id FROM manageruser with(nolock) where status<=2 and id<>146
	FOR READ ONLY

	OPEN c_manageruser
	FETCH NEXT FROM c_manageruser INTO @manageruserid

	WHILE @@FETCH_STATUS = 0
	BEGIN
		DECLARE c_WorkDate CURSOR FOR 
		select workdate,type from workdate with(nolock)
		where workdate>=@begindate and workdate<=@enddate
		order by workdate OPEN c_WorkDate

		FETCH NEXT FROM c_WorkDate INTO @workdate,@worktype

		WHILE @@FETCH_STATUS = 0
		BEGIN
			--1755之后 登录次数
			select @LoginCountAfter1755=count(1) from managerlog with(nolock) 
			where managerid=@manageruserid
			and year(logindate)*10000+month(logindate)*100+day(logindate)= @workdate
			and datepart(hh,logindate)*100+datepart(mi,logindate)>1755
			--1755之前 登录次数
			select @LoginCountBefore1755=count(1) from managerlog with(nolock) 
			where managerid=@manageruserid
			and year(logindate)*10000+month(logindate)*100+day(logindate)= @workdate
			and datepart(hh,logindate)*100+datepart(mi,logindate)<=1755

			set @AttendanceCheckOut=null
			set @AttendanceCheckIn=null
			select @AttendanceCheckOut=checkout, @AttendanceCheckin=checkin from OaDB..Attendance with(nolock)
			where manageruserid=@manageruserid and attendancedate=@workdate

			insert into overtime (ManagerUserid,WordDate,LoginCountAfter1755,LoginCountBefore1755,RTXonlineAfter1755,RTXonlineBeforer1755,AttendanceCheckOut,AttendanceCheckIn,WorkType) values
			(@manageruserid,@workdate,@LoginCountAfter1755,@LoginCountBefore1755,null,null,@AttendanceCheckOut,@AttendanceCheckIn,@worktype)

			FETCH NEXT FROM c_WorkDate INTO @workdate,@worktype
	END
	CLOSE c_WorkDate
	DEALLOCATE c_WorkDate
		FETCH NEXT FROM c_manageruser INTO @manageruserid
	END
	CLOSE c_manageruser
	DEALLOCATE c_manageruser
END











GO
/****** Object:  StoredProcedure [dbo].[procPaAttentionByIDSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--是否关注 Nick 20151120
CREATE PROCEDURE [dbo].[procPaAttentionByIDSelect]
(
	@ID INT,
	@AttentionType SMALLINT
)
AS
return 
BEGIN
	SELECT TOP 1 ID FROM PaAttention WITH(NOLOCK) WHERE AttentionID  = @ID AND @AttentionType = AttentionType
END

GO
/****** Object:  StoredProcedure [dbo].[procPaAttentionByPaMainIDSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--是否关注 Nick 20151120
CREATE PROCEDURE [dbo].[procPaAttentionByPaMainIDSelect]
(
	@ID INT,
	@AttentionType SMALLINT,
	@PaMainID INT
)
AS  
BEGIN   
	SELECT ID FROM PaAttention WITH(NOLOCK INDEX(IX_paAttention_Complex))
	WHERE AttentionID = @ID
	AND PaMainID = @PaMainID
	AND @AttentionType = AttentionType
END

GO
/****** Object:  StoredProcedure [dbo].[procpaCvAlipayRelationInsert]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--支付宝简历ID对应
CREATE PROCEDURE [dbo].[procpaCvAlipayRelationInsert]
(
	@cvMainID int,
	@alipayResumeID varchar(32)
)
AS
BEGIN
	INSERT INTO paCvAlipayRelation(cvMainID,alipayResumeID,AddDate) VALUES(@cvMainID,@alipayResumeID,GETDATE());
END
GO
/****** Object:  StoredProcedure [dbo].[ProcPageBaiduIncludeSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--sean 2014-8-13
CREATE PROCEDURE [dbo].[ProcPageBaiduIncludeSelect]
AS
BEGIN
	--SELECT TOP 100 *
	--FROM PageBaiduInclude
	--ORDER BY ISNULL(CheckDate, '2000-1-1'), PageID	--IncludeDate

	SELECT TOP 100 *
	INTO #t
	FROM PageBaiduInclude
	ORDER BY ISNULL(CheckDate, '2000-1-1'), PageID	--IncludeDate

	UPDATE a
	SET a.CheckDate = GETDATE()-200
	FROM PageBaiduInclude a, #t b
	WHERE a.PageId = b.PageId 

	SELECT * FROM #t ORDER BY PageID
END


GO
/****** Object:  StoredProcedure [dbo].[ProcPaGetPasswordLogByUniqueIDSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.4
--创建人：John
--说明：获取取回密码记录
--#####################################################
CREATE PROCEDURE [dbo].[ProcPaGetPasswordLogByUniqueIDSelect]
(
	@UniqueType INT,
	@UniqueId VARCHAR(40)
)
AS
BEGIN
	IF @UniqueType = 1
	BEGIN
		SELECT * FROM paGetPasswordLog WITH(NOLOCK) WHERE UniqueID = @UniqueId AND AddDate > DATEADD(MINUTE, -60, GETDATE()) AND IsReset IS NULL
	END
	ELSE
	BEGIN
		SELECT * FROM paGetPasswordLog WITH(NOLOCK) WHERE askno = @UniqueId AND AddDate > DATEADD(MINUTE, -60, GETDATE()) AND IsReset IS NULL
	END
END

GO
/****** Object:  StoredProcedure [dbo].[ProcPaGetPasswordLogIsResetUpdate]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.4
--创建人：John
--说明：修改取回密碼的状态 重置密码成功后就修改一下状态（IsReset）
--#####################################################
CREATE PROCEDURE [dbo].[ProcPaGetPasswordLogIsResetUpdate]
(
	@UniqueId VARCHAR(40)
)
AS
BEGIN
	UPDATE paGetPasswordLog SET IsReset=1 
	WHERE AskNo = ( SELECT TOP 1 AskNo FROM paGetPasswordLog WITH(NOLOCK) WHERE UniqueID = @UniqueId )
END


GO
/****** Object:  StoredProcedure [dbo].[ProcPaGUIDByRoomIDCvIDSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2014.10.29
--创建人：John
--说明：根据面试室编号和简历编号获取面试室的GUID
--#####################################################
CREATE PROCEDURE [dbo].[ProcPaGUIDByRoomIDCvIDSelect]
(
	@viRoomID INT,
	@cvMainID INT
)
AS
BEGIN
	SELECT TOP 1 GUID FROM ViInterviewRecord WHERE viRoomId = @viRoomID AND cvMainID = @cvMainID ORDER BY id DESC
END


GO
/****** Object:  StoredProcedure [dbo].[procPaJobClickLogInsert]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.03
--创建人：Nick
--说明：保存职位联系方式查看记录
--#####################################################
CREATE PROCEDURE [dbo].[procPaJobClickLogInsert]
(
	@paMainID INT,
	@JobID INT,
	@IP VARCHAR(15)
)
AS
SET NOCOUNT ON
BEGIN
	IF @paMainID = 0
		SET @paMainID = NULL
	IF NOT EXISTS(SELECT 'x' FROM MainDb..paJobClickLog WITH(NOLOCK) WHERE JobId = @JobId AND Ip = @ip AND AddDate > DATEADD(Second, -5, GETDATE()))
		INSERT INTO MainDb..paJobClickLog(JobId, paMainId, Ip, AddDate)
		VALUES(@JobID, @paMainID, @Ip, GETDATE())
	RETURN 1
END

GO
/****** Object:  StoredProcedure [dbo].[ProcPaJobCompareByPaMainIDInsert]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ProcPaJobCompareByPaMainIDInsert]
(
	@PaMainID INT
)
AS
SET NOCOUNT ON
BEGIN
	--今天推荐过了就不推荐了
	IF EXISTS(SELECT 'x' FROM PaJobCompare WITH(NOLOCK) WHERE PaMainID = @PaMainID AND AddDate > CONVERT(CHAR(10), GETDATE(), 120))
		RETURN
	
	CREATE TABLE #T(
		JobID INT, 
		SimilarJobID INT, 
		JobCount INT, 
		Pecentage FLOAT, 
		SimilarCount INT,
		Source VARCHAR(15)
	)

	DECLARE @BatchNo SMALLINT, @LastRecommenedNo TINYINT, @JobID INT, @JobCount INT, @PushCount INT, @Top INT
	
	SELECT @BatchNo = ISNULL(MAX(BatchNo), 0), @LastRecommenedNo = ISNULL(MIN(LastRecommenedNo), 6), @Top = 0
	FROM PaJobCompare WITH(NOLOCK)
	WHERE PaMainID = @PaMainID
	
	--如果最后一次登录时间为昨天那么剩余推送次数设置为6次
	IF (SELECT LastLoginDate FROM PaMain WITH(NOLOCK) WHERE ID = @PaMainID) > CONVERT(CHAR(10), GETDATE() - 1, 120)
	BEGIN
		SELECT @LastRecommenedNo = 6
	END
	IF ISNULL(@LastRecommenedNo, 0) = 0
		SET @LastRecommenedNo = 6

	SELECT jobID, COUNT(1) cnt 
	INTO #TJobSimilar 
	FROM exJobApplyMonthTemp WITH(NOLOCK)
	WHERE JobID IN(
		SELECT JobID 
		FROM exJobApplyMonthTemp
		WHERE CvMainID IN (
			SELECT ID 
			FROM CvMain WITH(NOLOCK)
			WHERE PaMainID = @PaMainID
		)
	) 
	GROUP BY jobID 
	HAVING COUNT(1) > 1
	
	WHILE EXISTS(SELECT jobID FROM #TJobSimilar)
	BEGIN
		SELECT TOP 1 @JobID = jobID, @JobCount = cnt 
		FROM #TJobSimilar
		
		INSERT INTO #T (JobID, SimilarJobID, JobCount, Pecentage, SimilarCount)
		SELECT @JobID, JobID, @JobCount, CAST(COUNT(1) AS FLOAT)*100/@JobCount, COUNT(1) 	
		FROM exJobApplyMonthTemp 	
		WHERE cvmainid IN(	
			SELECT cvMainID 
			FROM exJobApplyMonthTemp 
			WHERE jobid = @JobID) 
		AND jobid <> @JobID 
		AND EXISTS(		--职位必须有效且没被删除
			SELECT 'X' 
			FROM Job WITH(NOLOCK) 
			WHERE id = exJobApplyMonthTemp.JobID 
			AND Valid = 1
			AND IsDelete = 0
			AND IssueEnd > GETDATE())
			AND NOT EXISTS(--已经申请过的不再推荐
				SELECT 'X'
				FROM exJobApply WITH(NOLOCK)
				WHERE CvMainID IN (
					SELECT ID 
					FROM CvMain WITH(NOLOCK)
					WHERE PaMainID = @PaMainID
				)
				AND JobID = exJobApplyMonthTemp.JobID 
		)
		GROUP BY JobID 	
		HAVING COUNT(1) > 1
		ORDER BY COUNT(1) desc
		
		DELETE FROM #TJobSimilar WHERE jobID = @JobID
	END
	UPDATE #t SET Source = 'J' + LTRIM(STR(JobId))
	DROP TABLE #TJobSimilar
	
	INSERT INTO #T (SimilarJobID, JobCount)
	SELECT TOP 10 JobID, COUNT(1) 	
	FROM exJobApplyMonthTemp
	WHERE cvMainID IN(
		SELECT TOP 10 CvMainID 
		FROM exJobApplyMonthTemp
		WHERE JobID IN(	
			SELECT JobID 
			FROM exJobApplyMonthTemp
			WHERE CvMainID IN (
				SELECT ID 
				FROM CvMain WITH(NOLOCK)
				WHERE PaMainID = @PaMainID
			)
		) 
		AND NOT EXISTS(SELECT 'x' FROM CvMain WHERE PaMainID = @PaMainID AND id = exJobApplyMonthTemp.cvMainID)	
		GROUP BY CvMainID 	
		ORDER BY COUNT(1) DESC
	)
	AND NOT EXISTS(SELECT 'x' FROM CvMain WHERE PaMainID = @PaMainID AND id = exJobApplyMonthTemp.cvMainID)	
	AND EXISTS(		--职位必须有效且没被删除
		SELECT 'X' 
		FROM Job WITH(NOLOCK) 
		WHERE id = exJobApplyMonthTemp.JobID 
		AND Valid = 1
		AND IsDelete = 0
		AND IssueEnd > GETDATE())
	AND NOT EXISTS(--已经申请过的不再推荐
		SELECT 'X'
		FROM exJobApply WITH(NOLOCK)
		WHERE CvMainID IN (
			SELECT ID 
			FROM CvMain WITH(NOLOCK)
			WHERE PaMainID = @PaMainID
		)
		AND JobID = exJobApplyMonthTemp.JobID 
	) 
	GROUP BY JobID 	
	HAVING COUNT(1) > 1
	ORDER BY COUNT(1) desc
	UPDATE #t SET Source = 'from cvMain' WHERE Source IS NULL

	DECLARE @t AS TABLE(Id INT IDENTITY(1,1 ), SimilarJobID INT, Source VARCHAR(15))
	INSERT INTO @t(SimilarJobID)
	SELECT SimilarJobID
	FROM #T
	GROUP BY SimilarJobID
	ORDER BY COUNT(1) DESC

	UPDATE a SET a.Source = (SELECT TOP 1 Source FROM #t WHERE a.SimilarJobID = #t.SimilarJobID ORDER BY Source DESC)
	FROM @t a

	DELETE FROM @t WHERE SimilarJobID IN(SELECT a.SimilarJobID FROM @t a, Job b, cpMain c WHERE a.SimilarJobID = b.ID AND b.cpMainID = c.ID AND c.Name LIKE '%保险%')
	
	IF @BatchNo = 0
	BEGIN
		INSERT INTO PaJobCompare(BatchNo, PaMainID, CompareJobID, LastRecommenedNo, Source)
		SELECT TOP 10 @BatchNo + 1, @PaMainID, SimilarJobID, 5, Source
		FROM @t
		ORDER BY Id
		
		SELECT @PushCount = COUNT(1) 
		FROM PaJobCompare WITH(NOLOCK)
		WHERE PaMainID = @PaMainID
		AND BatchNO = @BatchNo + 1
		AND LastRecommenedNo = 5
		
		IF @PushCount < 10
			SET @Top = 10 - @PushCount
	END
	ELSE
	BEGIN
		INSERT INTO PaJobCompare(BatchNo, PaMainID, CompareJobID, LastRecommenedNo, Source)
		SELECT TOP 5 @BatchNo + 1, @PaMainID, SimilarJobID, @LastRecommenedNo-1, Source
		FROM @T a
		WHERE NOT EXISTS(			--推荐过的就不再推荐了
			SELECT 'X'
			FROM PaJobCompare WITH(NOLOCK)
			WHERE PaMainID = @PaMainID
			AND CompareJobID = a.SimilarJobID
		)
		ORDER BY Id

		--推荐不足10个 从原你的菜儿继续推荐
		SELECT @PushCount = COUNT(1) 
		FROM PaJobCompare WITH(NOLOCK)
		WHERE PaMainID = @PaMainID
		AND BatchNO = @BatchNo + 1
		AND LastRecommenedNo = @LastRecommenedNo-1
		
		IF @PushCount < 5
			SET @Top = 10 - @PushCount
	END

	IF @Top > 0
	BEGIN		 
		DECLARE @Job AS TABLE(
			Id INT,
			cpMainId INT,
			dcRegionId VARCHAR(6),
			dcJobTypeId VARCHAR(4),
			dcSalaryId INT,
			EmployType INT,
			dcEducationId INT,
			MinExperience INT,
			MinAge INT,
			MaxAge INT,
			AgeScore INT,
			EduScore INT,
			ExpScore INt,
			SizeScore INT
			)
		DECLARE @JobPlace AS TABLE(Id INT IDENTITY(1, 1), dcRegionId VARCHAR(6))
		DECLARE @JobType AS TABLE(Id INT IDENTITY(1, 1), dcJobTypeId VARCHAR(4))
		DECLARE @t1 AS TABLE(dcRegionId VARCHAR(6))
		DECLARE @t2 AS TABLE(dcJobTypeId VARCHAR(4))
		DECLARE @CvMainID INT, @dcSalaryId INT, @EmployType INT, @Degree INT, @Exp INT, @Age INT, @ThisMonth INT
		SET @ThisMonth = CONVERT(VARCHAR(6), GETDATE(), 112)

		SELECT TOP 1 @cvMainId = b.Id, @Age = (@ThisMonth - a.BirthDay) / 100,
			@dcSalaryId = dcSalaryID, @EmployType = EmployType, 
			@Degree = Degree, @Exp = RelatedWorkYears
		FROM paMain a WITH(NOLOCK), cvMain b WITH(NOLOCK)
		WHERE a.Id = b.paMainId
		AND a.Id = @paMainId
		
		INSERT INTO @JobPlace(dcRegionId)
		SELECT dcRegionId FROM cvJobPlace WITH(NOLOCK)
		WHERE cvMainId = @cvMainId

		INSERT INTO @JobType(dcJobTypeId)
		SELECT dcJobTypeId FROM cvJobType WITH(NOLOCK)
		WHERE cvMainId = @cvMainId

		DELETE a FROM @JobPlace a, @JobPlace b WHERE a.id <> b.Id AND a.dcRegionID <> b.dcRegionId AND b.dcRegionId LIKE a.dcRegionId + '%'
		DELETE a FROM @JobType a, @JobType b WHERE a.id <> b.Id AND a.dcJobTypeId <> b.dcJobTypeId AND b.dcJobTypeId LIKE a.dcJobTypeId + '%'
		INSERT INTO @t2 
		SELECT Id FROM dcJobType WHERE ID IN(SELECT dcJobTypeId FROM @JobType) OR ParentID IN(SELECT dcJobTypeId FROM @JobType)

		INSERT INTO @t1 SELECT Id FROM dcRegion WHERE ID IN(SELECT dcRegionId FROM @JobPlace) 
		INSERT INTO @t1 SELECT Id FROM dcRegion WHERE LEFT(ID, 4) IN(SELECT dcRegionId FROM @JobPlace)
		INSERT INTO @t1 SELECT Id FROM dcRegion WHERE LEFT(ID, 2) IN(SELECT dcRegionId FROM @JobPlace)
		--===========================================
		INSERT INTO @Job(Id, cpMainId, dcRegionId, dcJobTypeId, dcSalaryId, EmployType, dcEducationId, MinExperience, MinAge, MaxAge)
		SELECT TOP 200 Id, cpMainId, dcRegionId, dcJobTypeId, dcSalaryId, EmployType, dcEducationId, MinExperience, MinAge, MaxAge
		FROM jobPublish WITH(NOLOCK)
		WHERE EmployType = @EmployType
		AND dcRegionID IN(SELECT dcRegionId FROM @t1)
		AND dcJobTypeId IN(SELECT dcJobTypeId FROM @t2)
		AND dcSalaryId IN(100, @dcSalaryId)
		AND EXISTS(SELECT 'x' FROM cpMainPublish WITH(NOLOCK) WHERE LastLoginDate > GETDATE() - 31 AND cpMainPublish.Id = cpMainId)
		ORDER BY RefreshDate DESC

		DELETE @Job WHERE Id IN(SELECT CompareJobId FROM paJobCompare WITH(NOLOCK) WHERE paMainId = @pamainId)
		DELETE @Job WHERE Id IN(SELECT JobId FROM paYourFood WITH(NOLOCK) WHERE paMainId = @pamainId)
		DELETE @Job WHERE Id IN(SELECT JobId FROM ExJobApply WITH(NOLOCK) WHERE cvMainID IN(SELECT ID FROM cvMain WITH(NOLOCK) WHERE paMainId = @pamainId))
		IF(SELECT COUNT(*) FROM @Job) > 3
		BEGIN			
			UPDATE a SET a.SizeScore = b.dcCompanySizeId * -1, EduScore = 0, AgeScore = 0, ExpScore = 0  FROM @Job a, cpMainPublish b WHERE a.cpMainId = b.ID
			UPDATE @Job SET EduScore = dcEducationId - @Degree WHERE dcEducationId > @Degree AND dcEducationId < 100
			UPDATE @Job SET EduScore = @Degree - dcEducationId WHERE dcEducationId < @Degree AND dcEducationId < 100
			UPDATE @Job SET MinAge = 16 WHERE MinAge = 99
			UPDATE @Job SET MaxAge = 60 WHERE MaxAge = 99
			UPDATE @Job SET AgeScore = (MinAge - @Age) / 5 + 1 WHERE MinAge > @Age
			UPDATE @Job SET AgeScore = (@Age - MaxAge) / 5 + 1 WHERE MaxAge < @Age
			IF @Exp = 0
				SET @Exp = 1
			ELSE IF @Exp IN(1, 2)
				SET @Exp = 2
			ELSE IF @Exp IN(3,4,5)
				SET @Exp = 3
			ELSE IF @Exp IN(6,7,8,9,10)
				SET @Exp = 4
			ELSE IF @Exp > 10
				SET @Exp = 5
			ELSE
				SET @Exp = 0
			UPDATE @Job SET MinExperience = CASE WHEN MinExperience = 5 THEN 1 ELSE MinExperience + 1 END WHERE MinExperience > 0
			UPDATE @Job SET ExpScore = MinExperience - @Exp WHERE MinExperience > @Exp
			UPDATE @Job SET ExpScore = @Exp - MinExperience WHERE MinExperience < @Exp AND MinExperience > 0	
		END
		---SELECT TOP 3 'aaaaa' abc, Id, @paMainId, @cvMainId, id, GETDATE() FROM @Job ORDER BY EduScore, ExpScore + SizeScore + AgeScore
		INSERT INTO PaJobCompare(BatchNo, PaMainID, CompareJobID, LastRecommenedNo, Source)
		SELECT TOP (@Top) @BatchNo + 1, @PaMainID, Id, 5, 'Expect'
		FROM @Job ORDER BY EduScore, ExpScore + SizeScore + AgeScore
	END	

	DROP TABLE #T
END
GO
/****** Object:  StoredProcedure [dbo].[ProcPaJobCompareInsert]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--/****** 对象: StoredProcedure [dbo].[ProcPaJobCompareInsert]  脚本日期: 09/13/2016 15:26:30 ******/
--SET ANSI_NULLS ON
--GO
--SET QUOTED_IDENTIFIER ON
--GO
CREATE PROCEDURE [dbo].[ProcPaJobCompareInsert]
AS
SET NOCOUNT ON
IF DATEPART(HOUR, GETDATE()) > 17
	RETURN
BEGIN
	DECLARE @crDate DATETIME
	SELECT @CrDate = Value FROM dcRunParameter WHERE Name = 'exJobApplyMonthTemp create'
	IF @CrDate IS NULL
	BEGIN
		INSERT INTO dcRunParameter SELECT 'exJobApplyMonthTemp create', '', GETDATE() - 1, 1
		SELECT @CrDate = Value FROM dcRunParameter WHERE Name = 'exJobApplyMonthTemp create'
	END
	IF DATEDIFF(MINUTE, @CrDate, GETDATE()) > 480 OR (SELECT COUNT(*) FROM exJobApplyMonthTemp) < 10000
	BEGIN
		TRUNCATE TABLE exJobApplyMonthTemp
		--90天内的数据为样本
		INSERT INTO exJobApplyMonthTemp (JobId, CvMainID)
		SELECT jobID, CvMainID 
		FROM exjobapply WITH(NOLOCK) 
		WHERE addDate > GETDATE() - 30
		AND JobId > 0

		--排除海投
		DELETE FROM exJobApplyMonthTemp 
		WHERE CvMainID IN(
			SELECT CvMainID 
			FROM exJobApplyMonthTemp
			GROUP BY CvMainID
			HAVING COUNT(1) > 41		--if 30 then 26 if 90 then 41
		)

		UPDATE dcRunParameter SET Value = GETDATE() WHERE Name = 'exJobApplyMonthTemp create'
	END

	CREATE TABLE #TNP(paMainId INT)	--Table Need Push
	--一天之内登录过的 也推送
	INSERT INTO #TNP
	SELECT Id
	FROM PaMain WITH(NOLOCK)
	WHERE LastLoginDate > CONVERT(VARCHAR(10), GETDATE() - 1, 120) --一天之内登录的
	AND IsUseYourFood = 1

	--1天之前10天之后登陆的，也要推送
	INSERT INTO #TNP
	SELECT Id
	FROM paMain WITH(NOLOCK)
	WHERE LastLoginDate < GETDATE() - 1			 --一天之前登录的
	AND LastLoginDate >= CONVERT(VARCHAR(10), GETDATE() - 10 ,  120) --10天之内登录的
	AND NOT EXISTS(SELECT 'x' FROM #TNP WHERE PaMainID = PaMain.ID) --确定推送的就不再添加
	AND Id % 2 = DATEPART(DAY, GETDATE()) % 2
	AND IsUseYourFood = 1

	DELETE FROM #TNP WHERE paMainId IN(SELECT DISTINCT paMainId FROM PaJobCompare WITH(NOLOCK) WHERE AddDate > CONVERT(VARCHAR(10), GETDATE() , 120))
	SELECT * INTO #0 FROM #TNP
	DELETE a FROM #0 a, cvMain b WHERE a.paMainId = b.paMainId AND b.Degree > 0 AND b.EmployType > 0 AND RelatedWorkYears > -1
	DELETE #0 WHERE paMainId IN(SELECT paMainId FROM cvMain WHERE Id iN(SELECT cvMainId FROM ExJobApply WHERE AddDate > GETDATE() - 1))
	DELETE #TNP WHERE paMainId IN(SELECT paMainId FROM #0)
	IF EXISTS(SELECT 'x' FROM paJobCompareIndex WHERE AddDate < CONVERT(VARCHAR(10), GETDATE(), 120))
		TRUNCATE TABLE paJobCompareIndex
	DELETE #TNP WHERE paMainId IN(SELECT paMainId FROM paJobCompareIndex)

	INSERT INTO paJobCompareIndex(paMainId)
	SELECT paMainId FROM #Tnp
	DROP TABLE #TNP
	DROP TABLE #0
 	DECLARE @PaMainID INT,  @SQL AS VARCHAR(100)
	WHILE EXISTS(SELECT 'x' FROM paJobCompareIndex WITH(NOLOCK) WHERE RunDate IS NULL)
	BEGIN
		SELECT TOP 1 @PaMainID = PaMainID FROM paJobCompareIndex WITH(NOLOCK) WHERE RunStatus = 0 AND RunDate IS NULL ORDER BY ID
		SET @SQL = 'EXEC ProcPaJobCompareByPaMainIDInsert ' + LTRIM(STR(@PaMainID))
		--PRINT @SQL
		BEGIN TRY
			EXEC(@SQL)
			UPDATE paJobCompareIndex SET RunDate = GETDATE(), RunStatus = 1 WHERE paMainId = @paMainId
		END TRY
		BEGIN CATCH
			UPDATE paJobCompareIndex SET RunDate = GETDATE(), RunStatus = 101 WHERE paMainId = @paMainId
		END CATCH

		IF DATEPART(MINUTE, GETDATE()) BETWEEN 28 AND 31
		BEGIN
			UPDATE dcRunParameter SET Value = GETDATE() WHERE Name = 'exJobApplyMonthTemp create'
			RETURN
		END
	END
END

GO
/****** Object:  StoredProcedure [dbo].[procPaLoginContactByOpenIDDelete]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.10
--创建人：Nick
--说明：删除绑定信息
--#####################################################
CREATE PROCEDURE [dbo].[procPaLoginContactByOpenIDDelete]
(
	@OpenID VARCHAR(100)
)
AS
BEGIN
	DELETE FROM PaLoginContact where OpenID =@OpenID AND ContactType=4
END


GO
/****** Object:  StoredProcedure [dbo].[procpaLoginContactByOpenIDSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.10
--创建人：Nick
--说明：判断是否已绑定为信息账号
--#####################################################
CREATE PROCEDURE [dbo].[procpaLoginContactByOpenIDSelect]
(
	@OpenID VARCHAR(100)
)
AS
BEGIN
	SELECT * FROM paLoginContact WITH(NOLOCK) WHERE openid = @OpenID AND ContactType = 4
END


GO
/****** Object:  StoredProcedure [dbo].[ProcPaLoginContactInsert]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.4
--创建人：John
--说明：增加第三方登录的记录
--修改：2016-7-12日 来自微信的注册将RegisterFrom = 5 同时修改wxfans表中pamainID字段 Peter
--#####################################################
CREATE PROCEDURE [dbo].[ProcPaLoginContactInsert]
(
	@paMainID INT,
	@OpenID VARCHAR(100),
	@ContactType TINYINT,
	@LoginType TINYINT
)
AS
BEGIN
	IF @paMainID = 0
		RETURN
	IF @paMainID < 0
		SET @paMainId = @PaMainId * - 1

	DELETE FROM paLoginContact WHERE Openid=@OpenID AND ContactType = @ContactType
	INSERT INTO paLoginContact(paMainID,Openid,ContactType,LoginType,AddDate) VALUES(@paMainID,@OpenID,@ContactType,@LoginType,GETDATE())
	
	IF @ContactType = 4
	BEGIN
		--IF @LoginType = 2
			--UPDATE PaMain SET RegisterFrom = 5 WHERE ID = @PaMainID
		UPDATE wxfans SET PaMainID = @PaMainID WHERE OpenID = @OpenID
	END
END

GO
/****** Object:  StoredProcedure [dbo].[procPaloginlogByFirstLoginInsert]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[procPaloginlogByFirstLoginInsert]
(
	@PaMainID INT,
	@IP VARCHAR(31),
	@Browser VARCHAR(500),
	@LoginFrom TINYINT
)
AS
SET NOCOUNT ON
IF @PaMainID = 0
	RETURN
BEGIN
	IF NOT EXISTS(SELECT 'x' FROM PaLoginLog WITH(NOLOCK) WHERE LoginFrom = @LoginFrom AND PaMainID = @PaMainID AND AddDate > CONVERT(NVARCHAR, GETDATE(), 111))
	BEGIN
		UPDATE PaMain 
		SET LastLoginDate = GETDATE() 
		WHERE ID = @PaMainID
		
		IF @@ROWCOUNT > 0
			INSERT INTO PaLoginLog(paMainID,LoginIP,AddDate,Browser,LoginFrom) 
			VALUES(@PaMainID,@IP,GETDATE(),@Browser,@LoginFrom)		
	END
END
GO
/****** Object:  StoredProcedure [dbo].[ProcPaLoginLogByWeiXinInsert]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ProcPaLoginLogByWeiXinInsert]
(
    @FromUserName VARCHAR(100)
)
AS
RETURN
SET NOCOUNT ON
BEGIN
    DECLARE @paMainId INT
    SELECT @paMainId = paMainId FROM wxFans WITH(NOLOCK) WHERE OpenId = @FromUserName
    IF @paMainId IS NULL
    BEGIN
        SELECT @paMainId = paMainId FROM palogincontact WITH(NOLOCK) WHERE OpenId = @FromUserName AND ContactType = 4
        IF @paMainId IS NULL
        RETURN
    END
    DECLARE @Ip VARCHAR(31), @AddDate SMALLDATETIME
    SELECT TOP 1 @AddDate = AddDate, @ip = LoginIp FROM paLoginLog WITH(NOLOCK) WHERE paMainId = @paMainId ORDER BY Id DESC
    IF @Ip IS NULL
    BEGIN
        INSERT INTO paLoginLog
        SELECT @paMainId, '----', GETDATE(), 'weixin', 1    
        RETURN
    END
    IF @AddDate < DATEADD(HOUR, -10, GETDATE())
    BEGIN
        IF EXISTS(SELECT 'x' FROM paMain WITH(NOLOCK) WHERE id = @paMainId)
            INSERT INTO paLoginLog SELECT @paMainId, @ip, GETDATE(), 'weixin', 1
        --UPDATE paMaIn SET LastLoginDate = GETDATE() WHERE Id = @paMainId
    END
END
GO
/****** Object:  StoredProcedure [dbo].[ProcPaMainByCvMainIDSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.4
--创建人：John
--说明：根据cvmianid获取pamain基本信息
--#####################################################
CREATE PROCEDURE [dbo].[ProcPaMainByCvMainIDSelect]
(
	@cvMainID INT
)
AS
BEGIN
	SELECT a.id,a.mobile,a.name 
	FROM pamain a,cvmain b 
	WHERE b.pamainid = a.id AND b.id = @cvMainID
END


GO
/****** Object:  StoredProcedure [dbo].[ProcPaMainByRegisterFromUpdate]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ProcPaMainByRegisterFromUpdate]
AS
SET NOCOUNT ON
BEGIN
	UPDATE paMain SET RegisterMode = 12 
	WHERE Id IN(SELECT paMainId FROM MarketDb..RmInvitationCode WITH(NOLOCK) WHERE AddDate > GETDATE() - 5) 
	AND RegisterMode = 0
	AND AddDate > GETDATE() - 0.3

	UPDATE paMain SET RegisterMode = 13
	WHERE Id IN(SELECT paMainId FROM MarketDb..cvImportPrev WITH(NOLOCK) WHERE EntryDate > GETDATE() - 5) 
	AND RegisterMode = 0
	AND AddDate > GETDATE() - 0.3

	UPDATE a
	SET RegisterMode = 14
	FROM paMain a, bsMobileSpread b
	WHERE a.Mobile = b.MobileNo
	AND a.RegisterMode = 0
	AND a.AddDate BETWEEN DATEADD(MINUTE, -100, b.ReturnDate) AND b.ReturnDate
	AND b.ReturnDate > GETDATE() - 5

	UPDATE cvMain SET IsCvHidden = 1
	WHERE paMainId IN(SELECT paMainId FROM MarketDb..cvImportPrev WHERE contactresult=7 and paMainId>0 AND ContactDate > GETDATE() - 2)
	AND IsCvHidden = 0

	--Lucifer添加 市场部认证简历
	SET QUOTED_IDENTIFIER ON
	UPDATE paMain SET RegisterType = 151
	WHERE Id IN(SELECT paMainId FROM MarketDb..ptCvInvitation WITH(NOLOCK) WHERE AddDate > GETDATE() - 5) 
	AND ISNULL(RegisterType,0) < 100

	--Lucifer添加 市场部电话简历
	UPDATE paMain SET RegisterType = 152
	WHERE Id IN(SELECT paMainId FROM MarketDb..cvImportPrev WITH(NOLOCK) WHERE EntryDate > GETDATE() - 5) 
	AND ISNULL(RegisterType,0) < 100

	--Lucifer添加 信息员手机号注册
	UPDATE a
	SET RegisterType = 103
	FROM paMain a, bsMobileSpread b
	WHERE a.Mobile = b.MobileNo
	AND ISNULL(a.RegisterType, 0) < 100
	AND a.AddDate BETWEEN DATEADD(MINUTE, -100, b.ReturnDate) AND b.ReturnDate
	AND b.ReturnDate > GETDATE() - 5

	--Lucifer添加 信息员手机号注册 已审核
	UPDATE a
	SET RegisterType = 104
	FROM paMain a, bsMobileSpread b
	WHERE a.Mobile = b.MobileNo
	AND a.RegisterType = 103
	AND b.AccountDate IS NOT NULL

	IF DATEPART(HOUR, GETDATE()) BETWEEN 8 AND 18
	BEGIN
		UPDATE a
		SET a.ReturnDate = GETDATE(), a.RelatedId = b.Id
		FROM bsMobileSpread a, paMain b WITH(NOLOCK) 
		WHERE a.ReturnDate IS NULL
		AND a.AddDate > GETDATE() - 160
		AND a.UserType = 1
		AND a.MobileNo = b.Mobile
		AND ((b.RegisterMode = 0 AND b.ID < 25391426)
			OR 
			(b.ID >= 25391426 AND ISNULL(b.RegisterType, 0) < 100)
			)

		UPDATE a
		SET a.AccountDate = GETDATE()
		FROM bsMobileSpread a, paMain b WITH(NOLOCK), cvMain c WITH(NOLOCK)
		WHERE a.ReturnDate IS NOT NULL
		AND a.AccountDate IS NULL
		--AND a.AddDate > GETDATE() - 160
		AND a.UserType=1
		AND a.RelatedId = b.Id
		AND b.Id = c.paMainId
		AND c.Valid > 0
		AND (
				(b.RegisterMode = 0 AND b.ID < 25391426)
				OR 
				(b.ID >= 25391426 AND ISNULL(b.RegisterType,0) < 100)
				OR b.RegisterType = 103
			)
		AND b.VerifyCount > 0

		--Harry begin
		--更新关联企业id
--		UPDATE bsMobileSpread 
--		SET  RelatedId=(SELECT TOP 1 b.id FROM caMain a WITH(NOLOCK), cpMain b WITH(NOLOCK)
--			WHERE a.cpMainId = b.ID	AND b.RegisterMode = 0 AND a.Mobile=MobileNo ORDER BY b.RegDate DESC)
--		WHERE ReturnDate IS NULL
--		AND UserType=0 
--		AND ISNULL(RelatedId,0)=0
--		
--		--更新cpmain中的addman
--		UPDATE a  
--		SET a.addMan=(SELECT  addMan FROM bsMobileSpread WHERE MobileNo=(select mobile FROM caMain WHERE cpMainid=a.id))
--		FROM cpMain a
--		WHERE a.RegisterMode = 0  
--		AND ISNULL(a.addMan,0)=0
--		AND a.regdate > GETDATE()-5

		SELECT a.Id, a.AddMan, c.Id cpMainId
		INTO #t
		FROM bsMobileSpread a WITH(NOLOCK), caMain b WITH(NOLOCK), cpMain c WITH(NOLOCK)
		WHERE a.ReturnDate IS NULL
		AND a.AddDate > GETDATE() - 160
		AND a.UserType=0
		AND a.MobileNo = b.Mobile
		AND b.cpMainId = c.ID
		AND c.RegisterMode = 0
		--Harry end

		UPDATE a
		SET ReturnDate = GETDATE(), RelatedId = b.cpMainId
		FROM bsMobileSpread a, #t b 		
		WHERE a.Id = b.Id

		DECLARE @cpMainId int, @AddMan INT
		SELECT @cpMainId = 0
		WHILE EXISTS(SELECT 'x' FROM #t WHERE cpMainId > @cpMainId)
		BEGIN
			SELECT TOP 1 @cpMainId = cpMainId, @AddMan = AddMan FROM #t WHERE cpMAinId > @cpMainId ORDER By cpMainId
			UPDATE cpMain SET AddMan = @AddMan WHERE Id = @cpMainId
		END
		
		UPDATE a
		SET AccountDate = GETDATE()
		FROM bsMobileSpread a, cpMain b
		WHERE a.ReturnDate IS NOT NULL
		--AND a.AddDate > GETDATE() - 160
		AND a.AccountDate IS NULL
		AND a.UserType=0
		AND a.RelatedId = b.Id
		AND b.HasLicence = 1
		AND b.Valid = 1
		AND VerifyCount > 0
	END
END

GO
/****** Object:  StoredProcedure [dbo].[ProcPaMAinBySmsSpreadReSendSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ProcPaMAinBySmsSpreadReSendSelect]
AS
SET NOCOUNT ON
BEGIN
	DECLARE @p AS TABLE(
		Id INT,
		Name NVARCHAR(50),
		dcProvinceId INT,
		Mobile VARCHAR(20),
		HasIntention bit DEFAULT(0),
		HasEducation bit DEFAULT(0),
		HasExperience bit DEFAULT(0),
		Msg NVARCHAR(200) DEFAULT('')
	)
	INSERT INTO @p(Id, Name, Mobile, dcProvinceId)
	SELECT Id, Name, Mobile, dcProvinceId
	FROM paMain WITH(NOLOCK)
	WHERE Name > ''
	AND Id NOT IN(SELECT paMainId FROM cvMain WITH(NOLOCK) WHERE cvLevel LIKE '1111_1%' AND VerifyResult = 1)
	AND PerfectDate IS NULL
	AND Mobile >''
	--AND AddDate < CONVERT(VARCHAR(10), GETDATE() - 10, 120)
	AND AddDate BETWEEN CONVERT(VARCHAR(10), GETDATE() - 10, 120) AND CONVERT(VARCHAR(10), GETDATE() - 9, 120)
	ORDER BY ID

	UPDATE a
	SET HasIntention = 1
	FROM @p a, cvMain b WITH(NOLOCK)
	WHERE a.Id = b.paMainId
	AND b.Id IN(SELECT cvMainId FROM cvJobPlace)
	AND b.Id IN(SELECT cvMainId FROM cvJobtype)

	UPDATE a
	SET HasEducation = 1
	FROM @p a, cvMain b WITH(NOLOCK)
	WHERE a.Id = b.paMainId
	AND b.Id IN(SELECT cvMainId FROM cvEducation)

	UPDATE a
	SET HasExperience= 1
	FROM @p a, cvMain b WITH(NOLOCK)
	WHERE a.Id = b.paMainId
	AND b.Id IN(SELECT cvMainId FROM cvExperience)

	DELETE FROM @p WHERE HasExperience = 1 AND HasEducation = 1 AND HasIntention = 1

	UPDATE @p SET Msg = (SELECT SubSiteName FROM dcSubSite WHERE Id = dcProvinceId)
	UPDATE @p SET Msg = Name + '你好，欢迎登录' + Msg + '，你的简历缺少' + 
		CASE WHEN HasIntention = 0 THEN '求职意向、' ELSE '' END + 
		CASE WHEN HasEducation = 0 THEN '教育背景、' ELSE '' END + 
		CASE WHEN HasExperience = 0 THEN '工作经历、' ELSE '' END +
		'，请及时完善，以便免费为你推荐职位。'
	UPDATE @p SET Msg = REPLACE(Msg, '、，', '，')

	INSERT INTO SmsMessageLog(SendMan, Mobile, Msg, AddDate, MsgType)
	SELECT 0, Mobile, Msg, GETDATE(), 25 FROM @p
END

GO
/****** Object:  StoredProcedure [dbo].[procPaMainByUserNameLowerSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.10
--创建人：NICK
--说明：根据
--#####################################################
CREATE PROCEDURE [dbo].[procPaMainByUserNameLowerSelect]
(
	@UserName VARCHAR(50)
)
AS
BEGIN
	SELECT TOP 1 DcSubSiteID 
	FROM pamain WHERE UserNameLower = @UserName 
	union 
	SELECT TOP 1 DcSubSiteID 
	FROM PaMain WITH(INDEX(IX_paMain_Mobile)) 
	WHERE Mobile = @UserName 
	AND MobileVerifyDate IS NOT NULL
END


GO
/****** Object:  StoredProcedure [dbo].[procPaMainRegisterIpByProvinceIDSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.11
--创建人：John
--说明：根据身份获取个人用户注册IP
--#####################################################
CREATE PROCEDURE [dbo].[procPaMainRegisterIpByProvinceIDSelect]
(
	@dcProvinceID TINYINT
)
AS
BEGIN
	SELECT TOP 1 RegisterIp FROM (SELECT TOP 100 RegisterIp FROM paMain WHERE dcProvinceID = @dcProvinceID) t ORDER BY NEWID()
END


GO
/****** Object:  StoredProcedure [dbo].[ProcPaOnlineStatusUpdate]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ProcPaOnlineStatusUpdate]
(
	@paMainIDs VARCHAR(MAX)
)
AS
BEGIN
	return
	SELECT a ID INTO #t FROM dbo.fnSplit(@paMainIDs,',')
	UPDATE PaOnline SET IsOnline=1, RefreshDate=GETDATE() WHERE paMainID IN (SELECT Id FROM #t)
	INSERT paOnline(paMainId, IsOnline, RefreshDate)
	SELECT Id, 1, GETDATE() FROM #t WHERE ID NOT IN(SELECT paMainId FROM paOnline)
	UPDATE PaOnline SET IsOnline=0 WHERE paMainID NOT IN (SELECT Id FROM #t)
END





GO
/****** Object:  StoredProcedure [dbo].[procPaPageViewLogSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[procPaPageViewLogSelect]
(
	@PaMainID INT
)
AS
SET NOCOUNT ON
INSERT INTO a1 SELECT @paMainId, GETDATE()
BEGIN
	DECLARE @InterviewCnt INT,@IntentionCnt INT,@ViewLogCnt INT
	
	IF NOT EXISTS(SELECT 'x' FROM paPageViewLog WITH(NOLOCK) WHERE paMainId = @PaMainID)
	BEGIN
		INSERT INTO paPageViewLog(paMainId) VALUES(@PaMainID)
	END
	
	SELECT @InterviewCnt = COUNT(1)
	FROM exInterview WITH(NOLOCK)
	WHERE AddDate > (
		SELECT TOP 1 ISNULL(InterviewDate,(
			SELECT LastLoginDate FROM PaMain WITH(NOLOCK) WHERE ID = @PaMainID
		))
		FROM paPageViewLog WITH(NOLOCK)
		WHERE paMainId = @PaMainID
	)
	AND cvMainID IN(
		SELECT ID FROM cvMain WITH(NOLOCK) WHERE paMainID = @PaMainID
	)
	
	SELECT @IntentionCnt = COUNT(1)
	FROM caCvIntention WITH(NOLOCK)
	WHERE AddDate > (
		SELECT TOP 1 ISNULL(IntentionDate,(
			SELECT LastLoginDate FROM PaMain WITH(NOLOCK) WHERE ID = @PaMainID
		))
		FROM paPageViewLog WITH(NOLOCK)
		WHERE paMainId = @PaMainID
	)
	AND cvMainID IN(
		SELECT ID FROM cvMain WITH(NOLOCK) WHERE paMainID = @PaMainID
	)
	
	SELECT @ViewLogCnt = COUNT(1)
	FROM caCvViewLog WITH(NOLOCK)
	WHERE AddDate > (
		SELECT TOP 1 ISNULL(ViewLogDate,(
			SELECT LastLoginDate FROM PaMain WITH(NOLOCK) WHERE ID = @PaMainID
		))
		FROM paPageViewLog WITH(NOLOCK)
		WHERE paMainId = @PaMainID
	)
	AND cvMainID IN(
		SELECT ID FROM cvMain WITH(NOLOCK) WHERE paMainID = @PaMainID
	)
	
	SELECT @InterviewCnt InterviewCnt,@IntentionCnt IntentionCnt,@ViewLogCnt ViewLogCnt
END
GO
/****** Object:  StoredProcedure [dbo].[procPaPageViewLogUpdate]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[procPaPageViewLogUpdate]
(
	@PaMainID INT,
	@ViewPageType TINYINT				--1面试2应聘 3谁在关注 4关注 5 菜 6 申请的职位 7聊天记录
)
AS
SET NOCOUNT ON
BEGIN
	IF NOT EXISTS(SELECT 'x' FROM paPageViewLog WITH(NOLOCK) WHERE paMainId = @PaMainID)
		INSERT INTO paPageViewLog(paMainId, addDate, InterviewDate, IntentionDate, ViewLogDate, 
			AttentionDate, YourFoodDate, ApplyReplyDate) 
		VALUES(@PaMainID, GETDATE() - 10, GETDATE() - 10, GETDATE() - 10, GETDATE() - 10,
			GETDATE() - 10, GETDATE() - 10, GETDATE() - 10)
	
	IF @ViewPageType = 1
		UPDATE paPageViewLog SET InterviewDate = GETDATE(), InterviewCount=0 WHERE paMainId = @PaMainID 
	
	IF @ViewPageType = 2
		UPDATE paPageViewLog SET IntentionDate = GETDATE(), CpInvitationCount=0 WHERE paMainId = @PaMainID 
	
	IF @ViewPageType = 3
		UPDATE paPageViewLog SET ViewLogDate = GETDATE(), CvViewLogCount=0 WHERE paMainId = @PaMainID 
	
	IF @ViewPageType = 4
		UPDATE paPageViewLog SET AttentionDate = GETDATE(), MyAttentionCount=0 WHERE paMainId = @PaMainID 
	
	IF @ViewPageType = 5
		UPDATE paPageViewLog SET YourFoodDate = GETDATE(), YourFoodCount=0 WHERE paMainId = @PaMainID 
	
	IF @ViewPageType = 6
		UPDATE paPageViewLog SET ApplyReplyDate = GETDATE(), JobAppliedCount=0 WHERE paMainId = @PaMainID 
	
	IF @ViewPageType = 7
		UPDATE paPageViewLog SET ChatCount = 0 WHERE paMainId = @PaMainID 
END

GO
/****** Object:  StoredProcedure [dbo].[procParefererSelectByAddDate]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--分类统计个人注册来源数量
--harry
--2016-8-18
--2017-2-13 harry 增加省份选择
CREATE PROCEDURE [dbo].[procParefererSelectByAddDate]
(
	@begin CHAR(8),
	@end CHAR(8),
	@type INT,
	@provinceid INT	
)
AS
SET NOCOUNT ON
BEGIN	
	
	DECLARE @str CHAR(50)
	IF @provinceid =0
	BEGIN
		SET @str = ' 1=1 AND '
	END
	ELSE
	BEGIN
		SET @str = ' a.dcProvinceID='+CONVERT(char(8),@provinceid) +' AND  '
	END
	
    	DECLARE @sql VARCHAR(MAX)
	IF @type=1--日
	BEGIN 
		SET @sql='SELECT RegisterFrom,RegisterType,count(*) AS number,CONVERT(varchar(8), b.addDate, 112 ) AS [date]
		FROM maindb..pamain a left join maindb..pareferer b on a.id = b.pamainid 
		WHERE '+@str+' CONVERT(varchar(8), b.adddate, 112) >='''+ @begin+''' AND CONVERT(varchar(8), b.adddate, 112)<='''+@end+ 
		''' GROUP BY RegisterFrom,RegisterType,CONVERT(varchar(8), b.addDate,112) 
		 ORDER BY [date],registerfrom,registertype'
	END
	ELSE
	BEGIN--月 
		SET @sql='SELECT RegisterFrom,RegisterType,count(*) AS number,CONVERT(varchar(6), b.addDate, 112) AS [date]
		FROM maindb..pamain a left join maindb..pareferer b on a.id = b.pamainid 
		WHERE '+@str+' CONVERT(varchar(6), b.adddate, 112)>='''+ LEFT(@begin,6)+''' AND CONVERT(varchar(6), b.adddate, 112)<='''+ LEFT(@end,6)+'''  GROUP BY RegisterFrom,RegisterType,CONVERT(varchar(6), b.addDate, 112 )
		ORDER BY [date],registerfrom,registertype'
	END
	EXEC (@sql)
END 

GO
/****** Object:  StoredProcedure [dbo].[ProcParentRegionJobSalaryByRegionIDSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.3
--创建人：John
--说明：根据RegionID，Jobtype 获取其上级地区的平均月薪
--#####################################################
CREATE PROCEDURE [dbo].[ProcParentRegionJobSalaryByRegionIDSelect]
(
	@dcRegionID VARCHAR(4),
	@dcJobTypeID SMALLINT
)
AS
BEGIN
	IF LEN(@dcRegionID) = 4
	BEGIN
		SELECT TOP 10 dcRegionid,AvgSalary 
		FROM reportdb..SalaryReportJobtype 
		WHERE (dcRegionid = SUBSTRING(@dcRegionID,1,2) OR dcRegionid = 0) AND dcJobTypeID = @dcJobTypeID 
		ORDER BY dcRegionid DESC
	END
	ELSE
	BEGIN
		SELECT TOP 10 dcRegionid,AvgSalary 
		FROM reportdb..SalaryReportJobtype 
		WHERE dcRegionid = 0 AND dcJobTypeID = @dcJobTypeID
	END
END


GO
/****** Object:  StoredProcedure [dbo].[ProcParentRegionSalaryByRegionIDSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2014.10.31
--创建人：John
--说明：根据RegionID 获取其上级地区的平均月薪
--#####################################################
CREATE PROCEDURE [dbo].[ProcParentRegionSalaryByRegionIDSelect]
(
	@dcRegionID VARCHAR(4)
)
AS
BEGIN
	IF LEN(@dcRegionID) = 4
	BEGIN
		SELECT TOP 10 dcRegionid,AvgSalary 
		FROM reportdb..SalaryReportRegion 
		WHERE (dcRegionid = SUBSTRING(@dcRegionID,1,2) OR dcRegionid = 0) ORDER BY dcRegionid DESC
	END
	ELSE
	BEGIN
		SELECT TOP 10 dcRegionid,AvgSalary FROM reportdb..SalaryReportRegion WHERE dcRegionid = 0
	END
END


GO
/****** Object:  StoredProcedure [dbo].[ProcPaSearchKeywordSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ProcPaSearchKeywordSelect]
(
	@ProvinceId INT
)
AS
BEGIN
	SELECT '/s_' + LTRIM(RTRIM(Keyword)) Link FROM paSearchKeyword WHERE HasSubmit = 1 ORDER BY ID
END



GO
/****** Object:  StoredProcedure [dbo].[ProcPaSearchKeywordUpdate]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ProcPaSearchKeywordUpdate]
AS
BEGIN
	DELETE paSearchKeyword WHERE Keyword LIKE '%、%'
	DELETE paSearchKeyword WHERE Keyword LIKE '%。%'
	DELETE paSearchKeyword WHERE Keyword LIKE '%?%'
	DELETE paSearchKeyword WHERE Keyword LIKE '%/%'
	DELETE paSearchKeyword WHERE Keyword LIKE '%─%'
	DELETE paSearchKeyword WHERE LEN(Keyword) = 1
	DELETE paSearchKeyword WHERE LEN(Keyword) > 14
	IF DATEPART(WEEKDAY, GETDATE()) = 1
	BEGIN
		UPDATE paSearchKeyword SET HasSubMit = 9 WHERE HasSubMit = 1
		UPDATE paSearchKeyword SET HasSubMit = 1
		WHERE ID IN(SELECT TOP 3000 ID FROM paSearchKeyword WHERE ISNULL(HasSubmit, 0) = 0 ORDER BY ID)
	END
END




GO
/****** Object:  StoredProcedure [dbo].[ProcPaSMSWaitSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----------------
--创建日期：2012-4-17
--创建人：lambo
--功能说明：个人汇总类短信发送。将marketdb..paSMSWait里的数据转入SmsMessageLog 
-----------------
CREATE PROCEDURE [dbo].[ProcPaSMSWaitSelect]
AS
BEGIN TRY
	RETURN
	--删除今天已经登录过的个人的记录
	If DATEPART(HOUR,GETDATE())*100 + DATEPART(MINUTE,GETDATE()) <= 805
		DELETE FROM marketdb..paSMSWait WHERE paMainID IN(SELECT ID FROM paMain WITH(NOLOCK) WHERE LastLoginDate > GETDATE() - 1)
	ELSE
		DELETE FROM marketdb..paSMSWait WHERE paMainID IN(SELECT ID FROM paMain WITH(NOLOCK) WHERE LastLoginDate > DATEADD(MINUTE, -10, GETDATE()))

	SELECT TOP 20 * INTO #T FROM marketdb..paSMSWait WHERE LastLoginTime < DATEPART(HOUR, GETDATE())*100 + DATEPART(MINUTE, GETDATE()) AND Msg>''
	INSERT SmsMessageLog(SendMan, ManagerUSerId, paMainId, caMainId, Mobile, MsgType, IsCat, Msg)
		SELECT 0, NULL, paMainID, NULL, Mobile, 100+SmsType, 0,Msg FROM #T
	DELETE FROM marketdb..paSMSWait WHERE ID IN (select ID FROM #T)
END TRY
BEGIN CATCH

END CATCH














GO
/****** Object:  StoredProcedure [dbo].[procPaTagsMainByKeywordSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--根据输入获取关键词
CREATE PROCEDURE [dbo].[procPaTagsMainByKeywordSelect]
(
	@Keyword NVARCHAR(10)
)
AS
BEGIN
	SELECT DISTINCT TOP 10 Tag
	FROM PaTagsMain
	WHERE Tag LIKE @Keyword + '%'
END
GO
/****** Object:  StoredProcedure [dbo].[procPaTagsMainByTagsInsert]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--计划任务，定期将标签信息汇总插入到汇总表中  Peter 2017-1-19
CREATE PROCEDURE [dbo].[procPaTagsMainByTagsInsert]
AS
BEGIN
	INSERT INTO paTagsMain(Tag,dcJobTypeID,TagType,UseCount)
	SELECT TOP 20 a.Tags,b.dcJobTypeID,2,COUNT(1) Cnt 
	FROM cvTags a with(NOLOCK),cvJobType b WITH(NOLOCK)
	WHERE a.cvMainID=b.cvMainID
	GROUP BY a.Tags,b.dcJobTypeID
	HAVING COUNT(1) > 10
	AND NOT EXISTS(SELECT 'x' FROM paTagsMain WITH(NOLOCK) WHERE Tag=a.Tags AND dcJobTypeID = b.dcJobTypeID)
	ORDER BY COUNT(1) DESC
END
GO
/****** Object:  StoredProcedure [dbo].[procPaTagsMainByTagsUpdate]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--定期审核判断黑名单  Peter 2017-1-19
CREATE PROCEDURE [dbo].[procPaTagsMainByTagsUpdate] 
AS
BEGIN
	--删除黑名单中的词
	DELETE FROM cvTags
	WHERE Tags IN(
		SELECT Tag 
		FROM paTagsMain WITH(NOLOCK)
		WHERE TagType = 3
	)
	AND VerifyDate IS NULL
	
	UPDATE paTagsMain
	SET UseCount = (
		SELECT COUNT(1) 
		FROM cvTags a WITH(NOLOCK),cvJobType b WITH(NOLOCK)
		WHERE a.cvMainID=b.cvMainID
		AND a.Tags = paTagsMain.Tag
		AND b.dcJobTypeID = paTagsMain.dcJobTypeID
	)
	WHERE TagType <> 3
END



GO
/****** Object:  StoredProcedure [dbo].[procPaTagsMainByVerifyUpdate]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--审核  Peter 2017-1-13
CREATE PROCEDURE [dbo].[procPaTagsMainByVerifyUpdate]
(
	@TagsID VARCHAR(1000)
)
AS
BEGIN
	UPDATE cvTags
	SET VerifyDate = GETDATE()
	WHERE Tags IN(
		SELECT b.Tags FROM dbo.fnSplit(@TagsID,',') a
		LEFT JOIN cvTags b ON b.ID = a.a
	)
	AND VerifyDate IS NULL
END

GO
/****** Object:  StoredProcedure [dbo].[procPaTagsMainDelete]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--删除关键字  Peter 2017-1-13
CREATE PROCEDURE [dbo].[procPaTagsMainDelete]
(
	@TagsID INT
)
AS
BEGIN
	INSERT INTO paTagsMain(Tag,dcJobTypeID,TagType,UseCount)
	SELECT Tags,0,3,0
	FROM cvTags WITH(NOLOCK)
	WHERE id = @TagsID
	
	DELETE FROM cvTags 
	WHERE id = @TagsID
END
GO
/****** Object:  StoredProcedure [dbo].[procPersonReportInsert]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- 创建人:		Nick
-- 日期:		2013-11-12
-- 描述:		生成网站数据统计数据
-- 修改人:		Nick
-- 日期:		2013-12-6
-- 描述:		将手机注册加入个人注册量中

-- =============================================
CREATE PROCEDURE [dbo].[procPersonReportInsert]
AS
BEGIN
	DECLARE @ReportBeginDay VARCHAR(30),@ReportBeginMonth VARCHAR(30),@ReportEndDay VARCHAR(30),
			@ReportEndMonth VARCHAR(30),@ReportDate VARCHAR(8),@ReportDateMonth VARCHAR(8),@Now DATETIME--统计日期
	DECLARE @i INT ,@StrWhere VARCHAR(500), @Sql VARCHAR(1000),@isHaveMonthData int
	
	--统计日期赋值	
	SET @Now = GETDATE()
	--SET @Now = '2013-09-03'
	SET @ReportBeginDay = CONVERT(varchar(40),DATEADD(day,-1,@Now), 23)
	SET @ReportEndDay = CONVERT(varchar(30),@Now, 23)

	SET @ReportBeginMonth =  CONVERT(varchar(30),@NOW-1 - DAY(@NOW-1) + 1,23)
	SET @ReportEndMonth = CONVERT(varchar(30),DATEADD(MONTH, 1,@ReportBeginMonth),23)

	SET @ReportDate = CONVERT(varchar(30),DATEADD(day,-1,@Now), 112)
	SET @ReportDateMonth = SUBSTRING(@ReportDate,0,7)
		
	--删除当天日统计数据
	DELETE FROM PersonReport WHERE ReportDate = @ReportDate

	DECLARE @ProvinceID int	,@tmp int						--临时变量，用来保存省份编号

	--判断是否已存在月份数据
	IF EXISTS(SELECT 'x' FROM PersonReport WITH(NOLOCK) WHERE ReportDate = @ReportDateMonth)
	BEGIN
		SET @isHaveMonthData = 1  --已经存
	END
	ELSE 
	BEGIN
		SET @isHaveMonthData = 0  --不存在
	END

	--按照省份、状态 插入空数据
	DECLARE Province_curr CURSOR FOR				--申明游标
	SELECT ID FROM DcProvince						--查询省份编号
	OPEN Province_curr								--打开游标
	FETCH NEXT FROM Province_curr into @ProvinceID  --开始循环游标变量
	WHILE(@@fetch_status=0)							
	BEGIN
		SET @i = 0
	--================类型条件赋值============================================
		WHILE @i<12
		BEGIN
			--插入日报
			INSERT INTO PersonReport (ReportDate,ProvinceID,TypeID)
			VALUES (@ReportDate,@ProvinceID,@i)
			IF(@isHaveMonthData = 0)
			BEGIN
				--插入月报
				INSERT INTO PersonReport (ReportDate,ProvinceID,TypeID)
				VALUES (@ReportDateMonth,@ProvinceID,@i)
			END
			SET @i = @i + 1
		END
		FETCH NEXT FROM Province_curr into @ProvinceID --开始循环游标变量
	END
	CLOSE Province_curr--关闭游标
	DEALLOCATE Province_curr --释放游标

	--================创建临时表============================================
	CREATE TABLE #t1 -- 临时表 #t1  登陆过且未完善的pamainid 日报
	(
		PamainID   int,
		ProvinceID int
	)
	CREATE TABLE #t2 -- 临时表 #t2  登陆过且完善的pamainid 日报
	(
		PamainID   int ,
		ProvinceID int
	)
	CREATE TABLE #t3 -- 临时表 #t3  登陆过且未完善的pamainid 月报
	(
		PamainID   int ,
		ProvinceID int
	)
	CREATE TABLE #t4 -- 临时表 #t4  登陆过且完善的pamainid 月报
	(
		PamainID   int ,
		ProvinceID int
	)

	CREATE TABLE #Interview -- 临时表 #Interview  收到面试通知的账号 日报
	(
		PamainID   int,
		Adddate DateTime,
		ViewDate DateTime,
		ProvinceID int
	)

	CREATE TABLE #TmpInterview -- 临时表 #TmpInterview 
	(
		PamainID   int,
		Adddate DateTime,
		ViewDate DateTime,
		ProvinceID int
	)

	CREATE TABLE #Message -- 临时表 #Message  收到留言的账号 日报
	(
		PamainID   int,
		ProvinceID int
	)
	CREATE TABLE #Favorate -- 临时表 Favorate  收藏职位的账号 日报
	(
		PamainID   int,
		ProvinceID int
	)
	CREATE TABLE #Apply -- 临时表 #Apply  申请职位的账号 日报
	(
		PamainID   int,
		ProvinceID int
	)
	CREATE TABLE #Intention -- 临时表 #Intention	  收到应聘邀请的账号 日报
	(
		PamainID   int,
		ReplyDate DateTime,
		ProvinceID int
	)

	CREATE TABLE #TmpIntention -- 临时表 #TmpIntention
	(
		PamainID   int,
		ReplyDate DateTime,
		ProvinceID int
	)

	CREATE TABLE #Refresh -- 临时表 #Refresh	  刷新简历的账号 日报
	(
		PamainID   int,
		ProvinceID int
	)
	CREATE TABLE #Other -- 临时表 #Other	  
	(
		PamainID   int,
		ProvinceID int
	)
	CREATE TABLE #Rate -- 临时表 #Rate  频次
	(
		ProvinceID int,
		RateTmp   int,
		Cnt int
	)

	CREATE TABLE #InterviewMonth -- 临时表 #InterviewMonth  收到面试通知的账号 月报
	(
		PamainID   int,
		Adddate DateTime,
		ViewDate DateTime,
		ProvinceID int
	)
	CREATE TABLE #MessageMonth -- 临时表 #MessageMonth  收到留言的账号 月报
	(
		PamainID   int,
		ProvinceID int
	)
	CREATE TABLE #FavorateMonth -- 临时表 FavorateMonth  收藏职位的账号 月报
	(
		PamainID   int,
		ProvinceID int
	)
	CREATE TABLE #ApplyMonth -- 临时表 #ApplyMonth  申请职位的账号 月报
	(
		PamainID   int,
		ProvinceID int
	)
	CREATE TABLE #IntentionMonth -- 临时表 #IntentionMonth	  收到应聘邀请的账号 月报
	(
		PamainID   int,
		ReplyDate DateTime,
		ProvinceID int
	)
	CREATE TABLE #RefreshMonth -- 临时表 #RefreshMonth	  刷新简历的账号 月报
	(
		PamainID   int,
		ProvinceID int
	)
	CREATE TABLE #OtherMonth -- 临时表 #OtherMonth	  
	(
		PamainID   int,
		ProvinceID int
	)
	CREATE TABLE #RateMonth -- 临时表 #RateMonth  频次
	(
		ProvinceID int,
		RateTmp   int,
		Cnt int
	)

	--将收到面试通知的账号放入临时表 日报
	INSERT INTO #Interview
	SELECT b.PamainID,a.Adddate,a.ViewDate,c.dcProvinceID
	FROM exInterView a,CvMain b,PaMain c
	WHERE (a.AddDate BETWEEN @ReportBeginDay AND @ReportEndDay )
	AND a.CvMainID = b.ID
	AND b.PamainID = c.ID 

	--将发送留言的账号放入临时表 日报
	INSERT INTO #Message
	SELECT b.PamainID,c.dcProvinceID
	FROM exMessagep2c a,CvMain b,PaMain c
	WHERE (a.AddDate BETWEEN @ReportBeginDay AND @ReportEndDay )
	AND a.CvMainID = b.ID
	AND b.PamainID = c.ID 

	--将收藏职位的账号信息放入临时表 日报
	INSERT INTO #Favorate
	SELECT a.PamainID,b.dcProvinceID 
	FROM paFavorate a,PaMain b
	WHERE (a.AddDate BETWEEN @ReportBeginDay AND @ReportEndDay )
	AND a.PamainID = b.ID

	--将申请职位的账号放入临时表 日报
	INSERT INTO #Apply
	SELECT b.PamainID,c.dcProvinceID
	FROM exJobApply a,CvMain b,PaMain c
	WHERE (a.AddDate BETWEEN @ReportBeginDay AND @ReportEndDay )
	AND a.CvMainID = b.ID
	AND b.PamainID = c.ID 

	--将收到应聘邀请的账号放入临时表 日报
	INSERT INTO #Intention
	SELECT b.PamainID,a.ReplyDate,c.dcProvinceID
	FROM caCvIntention a,CvMain b,PaMain c
	WHERE (a.AddDate BETWEEN @ReportBeginDay AND @ReportEndDay )
	AND a.CvMainID = b.ID
	AND b.PamainID = c.ID 

	--将刷新简历的账号放入临时表 日报
	INSERT INTO #Refresh
	SELECT a.PamainID,b.dcProvinceID FROM CvMain a,PaMain b 
	WHERE (RefreshDate BETWEEN @ReportBeginDay AND @ReportEndDay )
	AND a.PamainID = b.ID 


	--将收到面试通知的账号放入临时表 月报
	INSERT INTO #InterviewMonth
	SELECT b.PamainID,a.Adddate,a.ViewDate,c.dcProvinceID
	FROM exInterView a,CvMain b,PaMain c
	WHERE (a.AddDate BETWEEN @ReportBeginMonth AND @ReportEndMonth )
	AND a.CvMainID = b.ID
	AND b.PamainID = c.ID 

	--将发送留言的账号放入临时表 月报
	INSERT INTO #MessageMonth
	SELECT b.PamainID,c.dcProvinceID
	FROM exMessagep2c a,CvMain b,PaMain c
	WHERE (a.AddDate BETWEEN @ReportBeginMonth AND @ReportEndMonth )
	AND a.CvMainID = b.ID
	AND b.PamainID = c.ID 

	--将收藏职位的账号信息放入临时表 月报
	INSERT INTO #FavorateMonth
	SELECT a.PamainID,b.dcProvinceID 
	FROM paFavorate a,PaMain b 
	WHERE (a.AddDate BETWEEN @ReportBeginMonth AND @ReportEndMonth )
	AND a.PamainID = b.ID

	--将申请职位的账号放入临时表 月报
	INSERT INTO #ApplyMonth
	SELECT b.PamainID,c.dcProvinceID
	FROM exJobApply a,CvMain b,PaMain c
	WHERE (a.AddDate BETWEEN @ReportBeginMonth AND @ReportEndMonth )
	AND a.CvMainID = b.ID
	AND b.PamainID = c.ID 

	--将收到应聘邀请的账号放入临时表 月报
	INSERT INTO #IntentionMonth
	SELECT b.PamainID,a.ReplyDate,c.dcProvinceID
	FROM caCvIntention a,CvMain b,PaMain c
	WHERE (a.AddDate BETWEEN @ReportBeginMonth AND @ReportEndMonth )
	AND a.CvMainID = b.ID
	AND b.PamainID = c.ID 

	--将刷新简历的账号放入临时表 日月报
	INSERT INTO #RefreshMonth
	SELECT a.PamainID,b.dcProvinceID FROM CvMain a,PaMain b 
	WHERE (RefreshDate BETWEEN @ReportBeginMonth AND @ReportEndMonth )
	AND a.PamainID = b.ID 

	SET @i = 0
	WHILE @i<12
	BEGIN
		IF @i = 1		--邮件推广
		BEGIN
			SET @StrWhere = ' AND (b.RegisterMode = 1 OR b.RegisterMode = 11 OR b.RegisterType = 101 OR b.RegisterType = 102) '
		END
		ELSE IF @i=2	--招聘会推广
		BEGIN
			SET @StrWhere = ' AND (b.RegisterMode = 12 OR b.RegisterType = 151)'
		END
		ELSE IF @i=3	--电话推广
		BEGIN
			SET @StrWhere = ' AND (b.RegisterMode = 13 OR b.RegisterType = 152)'
		END
		ELSE IF @i=4	--短信推广
		BEGIN
			SET @StrWhere = ' AND (b.RegisterMode = 14 OR b.RegisterType = 103 OR b.RegisterType = 104)'
		END
		ELSE IF @i=5	--本人注册
		BEGIN
			SET @StrWhere = ' AND ((b.RegisterMode<>1 AND b.RegisterMode<>11 AND b.RegisterMode<>12 AND b.RegisterMode<>13 AND b.RegisterMode<>14) OR b.RegisterType = 1)'
		END
		ELSE IF @i=6	--公开
		BEGIN
			SET @StrWhere = ' AND IscvHidden <> 1 '
		END
		ELSE IF @i=7	--隐藏
		BEGIN
			SET @StrWhere = ' AND IscvHidden = 1 '
		END
		ELSE IF @i=8	--手机认证
		BEGIN
			SET @StrWhere = ' AND MobileVerifyDate IS NOT NULL '
		END
		ELSE IF @i=9	--邮箱认证
		BEGIN
			SET @StrWhere = ' AND EmailVerifyDate IS NOT NULL '
		END
		ELSE IF @i=10	--未认证
		BEGIN
			SET @StrWhere = ' AND (MobileVerifyDate IS NULL AND EmailVerifyDate IS NULL) '
		END
		ELSE IF @i=11	--竞价推广
		BEGIN
			SET @StrWhere = ' AND b.ID IN (SELECT paMainID FROM UrlAccount) '
		END
		ELSE
		BEGIN			--全部
			SET @StrWhere = ''
		END

		--将登陆过且未完善的pamainid放入临时表 #t1 日报
		IF(@i=6 OR @i=7)
		BEGIN
			SET @Sql = 'SELECT a.PaMainID,b.dcProvinceID ProvinceID FROM PaLoginLog a,PaMain b
				WHERE (a.AddDate BETWEEN '''+@ReportBeginDay+''' AND '''+@ReportEndDay+''' )
				AND a.PamainID = b.ID 
				AND a.PamainID IN(
					SELECT PamainID FROM CvMain WHERE CvLevel NOT LIKE ''1111_1%'' AND Attachment is null
					'+@StrWhere+'
				)'
			INSERT INTO  #t1 EXEC(@Sql)
			print (@Sql)
			--将有完善简历的账户删除
			DELETE FROM #t1 WHERE PamainID IN (SELECT PamainID FROM CvMain WHERE CvLevel LIKE '1111_1%' or Attachment <>'') 
			IF @i=7
			BEGIN
				--将公开的简历删除
				DELETE FROM #t1 WHERE PamainID IN (SELECT PamainID FROM CvMain WHERE IscvHidden <> 1) 
			END

			--将登陆过且完善的pamainid放入临时表 #t2 日报
			SET @Sql = 'SELECT a.PaMainID,b.dcProvinceID ProvinceID FROM PaLoginLog a,PaMain b
				WHERE (a.AddDate BETWEEN '''+@ReportBeginDay+''' AND '''+@ReportEndDay+''' )
				AND a.PamainID = b.ID 
				AND a.PaMainID IN (SELECT PamainID FROM CvMain WHERE (CvLevel LIKE ''1111_1%'' or Attachment <>'''') '+@StrWhere+')
				' 
			INSERT INTO  #t2 EXEC(@Sql)
			IF @i=7
			BEGIN
				--将公开的简历删除
				DELETE FROM #t2 WHERE PamainID IN (SELECT PamainID FROM CvMain WHERE IscvHidden <> 1) 
			END

			--将登陆过且未完善的pamainid放入临时表 #t3 月报
			SET @Sql = 'SELECT a.PaMainID,b.dcProvinceID ProvinceID FROM PaLoginLog a,PaMain b
				WHERE (a.AddDate BETWEEN '''+@ReportBeginMonth+''' AND '''+@ReportEndMonth+''' )
				AND a.PamainID = b.ID  
				AND a.PaMainID IN (SELECT PamainID FROM CvMain WHERE CvLevel NOT LIKE ''1111_1%'' AND Attachment is null '+@StrWhere+')
			' 
			INSERT INTO #t3 EXEC(@Sql)
			--将有完善简历的账户删除
			DELETE FROM #t3 WHERE PamainID IN (SELECT PamainID FROM CvMain WHERE CvLevel LIKE '1111_1%' or Attachment <>'') 
			IF @i=7
			BEGIN
				--将公开的简历删除
				DELETE FROM #t3 WHERE PamainID IN (SELECT PamainID FROM CvMain WHERE IscvHidden <> 1) 
			END

			--将登陆过且完善的pamainid放入临时表 #t4 月报
			SET @Sql = 'SELECT a.PaMainID,b.dcProvinceID ProvinceID FROM PaLoginLog a,PaMain b
				WHERE (a.AddDate BETWEEN '''+@ReportBeginMonth+''' AND '''+@ReportEndMonth+''' )
				AND a.PamainID = b.ID  
				AND a.PaMainID IN (SELECT PamainID FROM CvMain WHERE (CvLevel LIKE ''1111_1%'' or Attachment <>'''') '+@StrWhere+')
				'
			INSERT INTO  #t4 EXEC(@Sql)
			IF @i=7
			BEGIN
				--将公开的简历删除
				DELETE FROM #t4 WHERE PamainID IN (SELECT PamainID FROM CvMain WHERE IscvHidden <> 1) 
			END

		END
		ELSE 
		BEGIN
			SET @Sql = 'SELECT a.PaMainID,b.dcProvinceID ProvinceID FROM PaLoginLog a,PaMain b
				WHERE (a.AddDate BETWEEN '''+@ReportBeginDay+''' AND '''+@ReportEndDay+''' )
				AND a.PamainID = b.ID 
				AND a.PamainID IN(SELECT PamainID FROM CvMain WHERE CvLevel NOT LIKE ''1111_1%'' AND Attachment is null)
			' + @StrWhere
			INSERT INTO  #t1 EXEC(@Sql)
			--将有完善简历的账户删除
			DELETE FROM #t1 WHERE PamainID IN (SELECT PamainID FROM CvMain WHERE CvLevel LIKE '1111_1%' or Attachment <>'') 

			--将登陆过且完善的pamainid放入临时表 #t2 日报
			SET @Sql = 'SELECT a.PaMainID,b.dcProvinceID ProvinceID FROM PaLoginLog a,PaMain b
				WHERE (a.AddDate BETWEEN '''+@ReportBeginDay+''' AND '''+@ReportEndDay+''' )
				AND a.PamainID = b.ID 
				AND a.PaMainID IN (SELECT PamainID FROM CvMain WHERE CvLevel LIKE ''1111_1%'' or Attachment <>'''')
				' + @StrWhere

			INSERT INTO  #t2 EXEC(@Sql)

			--将登陆过且未完善的pamainid放入临时表 #t3 月报
			SET @Sql = 'SELECT a.PaMainID,b.dcProvinceID ProvinceID FROM PaLoginLog a,PaMain b
				WHERE (a.AddDate BETWEEN '''+@ReportBeginMonth+''' AND '''+@ReportEndMonth+''' )
				AND a.PamainID = b.ID  
				AND a.PaMainID IN (SELECT PamainID FROM CvMain WHERE CvLevel NOT LIKE ''1111_1%'' AND Attachment is null)
			' + @StrWhere
			INSERT INTO #t3 EXEC(@Sql)
			--将有完善简历的账户删除
			DELETE FROM #t3 WHERE PamainID IN (SELECT PamainID FROM CvMain WHERE CvLevel LIKE '1111_1%' or Attachment <>'') 

			--将登陆过且完善的pamainid放入临时表 #t4 月报
			SET @Sql = 'SELECT a.PaMainID,b.dcProvinceID ProvinceID FROM PaLoginLog a,PaMain b
				WHERE (a.AddDate BETWEEN '''+@ReportBeginMonth+''' AND '''+@ReportEndMonth+''' )
				AND a.PamainID = b.ID  
				AND a.PaMainID IN (SELECT PamainID FROM CvMain WHERE CvLevel LIKE ''1111_1%'' or Attachment <>'''')
				' + @StrWhere
			INSERT INTO  #t4 EXEC(@Sql)
		END
 
		--未完善简历的账号数量 赋值 日报
		UPDATE a SET a.LoginNoPerfectAccount=b.cnt 
		FROM Personreport a ,(SELECT COUNT(DISTINCT PaMainID) cnt,ProvinceID FROM #t1 GROUP BY ProvinceID) b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDate

		--未完善账号的登录次数 日报
		UPDATE a SET a.LoginNoPerfectCount=b.cnt 
		FROM Personreport a ,(SELECT COUNT(PaMainID) cnt,ProvinceID FROM #t1 GROUP BY ProvinceID) b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDate

		--完善简历的账号数量 赋值 日报
		UPDATE a SET a.LoginPerfectAccount=b.cnt 
		FROM Personreport a ,(SELECT COUNT(DISTINCT PaMainID) cnt,ProvinceID FROM #t2 GROUP BY ProvinceID) b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDate

		--完善简历的账号登陆次数 赋值 日报
		UPDATE a SET a.LoginPerfectCount=b.cnt 
		FROM Personreport a ,(SELECT COUNT(PaMainID) cnt,ProvinceID FROM #t2 GROUP BY ProvinceID) b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDate

		--收到面试通知的账号数量 日报
		UPDATE a SET a.InterviewAccount=b.cnt 
		FROM Personreport a ,(
			SELECT COUNT(DISTINCT PaMainID) cnt,ProvinceID FROM #Interview
			WHERE PaMainID IN (SELECT PamainID FROM #t2)
			GROUP BY ProvinceID
		) b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDate

		--收到面试通知的条数 日报
		UPDATE a SET a.InterviewCount=b.cnt 
		FROM Personreport a ,(
			SELECT COUNT(*) cnt,ProvinceID FROM #Interview 	
			WHERE PaMainID in(SELECT PamainID FROM #t2)
			GROUP BY ProvinceID
		) b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND a.TypeID = @i AND a.ReportDate = @ReportDate

		--收到面试通知且已查看账号数量 日报
		UPDATE a SET a.InterviewViewAccount=b.cnt 
		FROM Personreport a ,(
			SELECT COUNT(DISTINCT PaMainID) cnt,ProvinceID FROM #Interview 
			WHERE (ViewDate BETWEEN @ReportBeginDay AND @ReportEndDay )
			AND PaMainID IN(SELECT PamainID FROM #t2)
			GROUP BY ProvinceID
		) b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDate

		--得到未查看的账号信息
		INSERT INTO #TmpInterview SELECT * FROM #Interview
		DELETE FROM #TmpInterview WHERE PaMainID IN (Select PaMainID FROM #Interview WHERE ViewDate BETWEEN @ReportBeginDay AND @ReportEndDay)
		--收到面试通知且未查看账号数量 日报
		UPDATE a SET a.InterviewNoViewAccount = b.cnt 
		FROM Personreport a ,(
			SELECT COUNT(DISTINCT PaMainID) cnt,ProvinceID FROM #TmpInterview 
			WHERE (ViewDate IS NULL )
			AND PaMainID IN(SELECT PamainID FROM #t2)
			GROUP BY ProvinceID
		) b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDate
		
		--收到面试通知且已查看的条数 日报
		UPDATE a SET a.InterviewViewCount=b.cnt 
		FROM Personreport a ,(
			SELECT COUNT(PaMainID) cnt,ProvinceID FROM #Interview 
			WHERE (ViewDate BETWEEN @ReportBeginDay AND @ReportEndDay )
			AND PaMainID IN(SELECT PamainID FROM #t2)
			GROUP BY ProvinceID
		) b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDate

		--收到面试通知且未查看的条数 日报
		UPDATE a SET a.InterviewNoViewCount=b.cnt 
		FROM Personreport a ,(
			SELECT COUNT(PaMainID) cnt,ProvinceID FROM #Interview 
			WHERE (ViewDate IS NULL )
			AND PaMainID IN(SELECT PamainID FROM #t2)
			GROUP BY ProvinceID
		) b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDate

		--留言的账号数量 日报
		UPDATE a SET a.MessageAccount=b.cnt 
		FROM Personreport a ,(
			SELECT COUNT(DISTINCT PaMainID) cnt,ProvinceID FROM #t2
			WHERE PaMainID IN ( SELECT PamainID FROM #Message )
			GROUP BY ProvinceID
		) b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDate

		--留言的条数 日报
		UPDATE a SET a.MessageCount=b.cnt 
		FROM Personreport a ,(
			SELECT COUNT(PaMainID) cnt,ProvinceID FROM #Message
			WHERE PaMainID IN ( SELECT PamainID FROM #t2 )
			GROUP BY ProvinceID
		) b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDate

		--收藏职位的账号数量 日报
		UPDATE a SET a.FavoriteAccount=b.cnt 
		FROM Personreport a ,(
			SELECT COUNT(DISTINCT PaMainID) cnt,ProvinceID FROM #t2
			WHERE PaMainID IN ( SELECT PamainID FROM #Favorate )
			GROUP BY ProvinceID
		) b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDate

		--收藏职位的条数 日报
		UPDATE a SET a.FavoriteCount=b.cnt 
		FROM Personreport a ,(
			SELECT COUNT(PaMainID) cnt,ProvinceID FROM #Favorate
			WHERE PaMainID IN ( SELECT PamainID FROM #t2 )
			GROUP BY ProvinceID
		) b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDate

		--申请职位的账号数量 日报
		UPDATE a SET a.ApplyAccount=b.cnt 
		FROM Personreport a ,(
			SELECT COUNT(DISTINCT PaMainID) cnt,ProvinceID FROM #Apply
			WHERE PaMainID IN ( SELECT PamainID FROM #t2 )
			GROUP BY ProvinceID
		)b
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDate

		--申请职位的条数 日报
		UPDATE a SET a.ApplyCount=b.cnt 
		FROM Personreport a ,(
			SELECT COUNT(PaMainID) cnt,ProvinceID FROM #Apply
			WHERE PaMainID IN ( SELECT PamainID FROM #t2 )
			GROUP BY ProvinceID
		) b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDate

		--收到应聘邀请的账号数量 日报
		UPDATE a SET a.IntentionAccount=b.cnt 
		FROM Personreport a ,(
			SELECT COUNT(DISTINCT PaMainID) cnt,ProvinceID FROM #Intention
			WHERE PaMainID IN (SELECT PamainID FROM #t2)
			GROUP BY ProvinceID
		) b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDate

		--收到应聘邀请的条数 日报
		UPDATE a SET a.IntentionCount=b.cnt 
		FROM Personreport a ,(
			SELECT COUNT(*) cnt,ProvinceID FROM #Intention 	
			WHERE PaMainID in(SELECT PamainID FROM #t2)
			GROUP BY ProvinceID
		) b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND a.TypeID = @i AND a.ReportDate = @ReportDate

		--收到应聘邀请且已查看账号数量 日报
		UPDATE a SET a.IntentionViewAccount=b.cnt 
		FROM Personreport a ,(
			SELECT COUNT(DISTINCT PaMainID) cnt,ProvinceID FROM #Intention	
			WHERE (ReplyDate BETWEEN @ReportBeginDay AND @ReportEndDay )
			AND PaMainID IN(SELECT PamainID FROM #t2)
			GROUP BY ProvinceID
		) b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDate

		--得到未查看的账号信息
		INSERT INTO #TmpIntention SELECT * FROM #Intention
		DELETE FROM #TmpIntention WHERE PaMainID IN (Select PaMainID FROM #Intention WHERE ReplyDate BETWEEN @ReportBeginDay AND @ReportEndDay)

		--收到应聘邀请且未查看账号数量 日报
		UPDATE a SET a.IntentionNoViewAccount = b.cnt 
		FROM Personreport a ,(
			SELECT COUNT(DISTINCT PaMainID) cnt,ProvinceID FROM #TmpIntention	
			WHERE (ReplyDate IS NULL )
			AND PaMainID IN(SELECT PamainID FROM #t2)
			GROUP BY ProvinceID
		) b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDate
		
		--收到应聘邀请且已查看的条数 日报
		UPDATE a SET a.IntentionViewCount=b.cnt 
		FROM Personreport a ,(
			SELECT COUNT(PaMainID) cnt,ProvinceID FROM #Intention	
			WHERE (ReplyDate BETWEEN @ReportBeginDay AND @ReportEndDay )
			AND PaMainID IN(SELECT PamainID FROM #t2)
			GROUP BY ProvinceID
		) b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDate

		--收到应聘邀请且未查看的条数 日报
		UPDATE a SET a.IntentionNoViewCount=b.cnt 
		FROM Personreport a ,(
			SELECT COUNT(PaMainID) cnt,ProvinceID FROM #Intention	
			WHERE (ReplyDate IS NULL )
			AND PaMainID IN(SELECT PamainID FROM #t2)
			GROUP BY ProvinceID
		) b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDate
		
		--刷新简历的账号数量 @RefreshAccount 日报
		UPDATE a SET a.RefreshAccount=b.cnt 
		FROM Personreport a ,(
			SELECT COUNT(DISTINCT PaMainID) cnt,ProvinceID FROM #Refresh
			WHERE PaMainID IN ( SELECT PamainID FROM #t2 )
			GROUP BY ProvinceID
		) b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDate

		--刷新简历的次数 日报
		UPDATE a SET a.RefreshCount=b.cnt 
		FROM Personreport a ,(
			SELECT COUNT(PaMainID) cnt,ProvinceID FROM #Refresh
			WHERE PaMainID IN ( SELECT PamainID FROM #t2 )
			GROUP BY ProvinceID
		) b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDate

		--临时表赋值
		INSERT INTO #Other SELECT * FROM #t2
		DELETE FROM #Other 
		WHERE PaMainID IN ( SELECT PamainID FROM #Interview)
		OR PaMainID IN ( SELECT PamainID FROM #Message)
		OR PaMainID IN ( SELECT PamainID FROM #Favorate)
		OR PaMainID IN ( SELECT PamainID FROM #Apply)
		OR PaMainID IN ( SELECT PamainID FROM #Intention)
		OR PaMainID IN ( SELECT PamainID FROM #Refresh )

		--其他账号数量、登录次数 日报
		UPDATE a SET OtherLoginAccount = b.cnt
		FROM Personreport a ,(
			SELECT COUNT(DISTINCT PaMainID) cnt,ProvinceID FROM #Other
			GROUP BY ProvinceID
		) b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDate
		
		UPDATE a SET OtherLoginCount = b.cnt
		FROM Personreport a ,(
			SELECT COUNT(1) cnt,ProvinceID FROM #Other
			GROUP BY ProvinceID
		) b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDate

		--频次 日报 begin-------------------------------
		INSERT INTO #Rate
		SELECT ProvinceID, Rate, Count(1) Cnt FROM (
			SELECT PamainID, ProvinceID, COUNT(1) Rate 
			FROM #t2 
			GROUP BY PamainID, ProvinceID
		) a 
		GROUP BY ProvinceId, Rate

		UPDATE a SET Rate1 = b.cnt
		FROM Personreport a ,#Rate b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDate AND b.RateTmp=1

		UPDATE a SET Rate2 = b.cnt
		FROM Personreport a ,#Rate b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDate AND b.RateTmp=2

		UPDATE a SET Rate3 = b.cnt
		FROM Personreport a ,#Rate b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDate AND b.RateTmp=3

		UPDATE a SET Rate4 = b.cnt
		FROM Personreport a ,#Rate b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDate AND b.RateTmp=4

		UPDATE a SET Rate5 = b.cnt
		FROM Personreport a ,#Rate b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDate AND b.RateTmp=5

		UPDATE a SET Rate6 = b.cnt
		FROM Personreport a ,#Rate b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDate AND b.RateTmp=6

		UPDATE a SET Rate7 = b.cnt
		FROM Personreport a ,#Rate b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDate AND b.RateTmp=7

		UPDATE a SET Rate8 = b.cnt
		FROM Personreport a ,#Rate b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDate AND b.RateTmp=8

		UPDATE a SET Rate9 = b.cnt
		FROM Personreport a ,#Rate b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDate AND b.RateTmp  BETWEEN 9 AND 14

		UPDATE a SET Rate15 = b.cnt
		FROM Personreport a ,#Rate b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDate AND b.RateTmp  BETWEEN 15 AND 25

		UPDATE a SET Rate15 = b.cnt
		FROM Personreport a ,#Rate b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDate AND b.RateTmp>25
		--频次 日报 end-------------------------------

		--未完善简历的账号数量 赋值 月报
		UPDATE a SET a.LoginNoPerfectAccount=b.cnt 
		FROM Personreport a ,(SELECT COUNT(DISTINCT PaMainID) cnt,ProvinceID FROM #t3 GROUP BY ProvinceID) b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDateMonth

		--未完善账号的登录次数 月报
		UPDATE a SET a.LoginNoPerfectCount=b.cnt 
		FROM Personreport a ,(SELECT COUNT(PaMainID) cnt,ProvinceID FROM #t3 GROUP BY ProvinceID) b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDateMonth

		--完善简历的账号数量 赋值 月报
		UPDATE a SET a.LoginPerfectAccount=b.cnt 
		FROM Personreport a ,(SELECT COUNT(DISTINCT PaMainID) cnt,ProvinceID FROM #t4 GROUP BY ProvinceID) b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDateMonth

		--完善简历的账号登陆次数 赋值 月报
		UPDATE a SET a.LoginPerfectCount=b.cnt 
		FROM Personreport a ,(SELECT COUNT(PaMainID) cnt,ProvinceID FROM #t4 GROUP BY ProvinceID) b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDateMonth

		--收到面试通知的账号数量 月报
		UPDATE a SET a.InterviewAccount=b.cnt 
		FROM Personreport a ,(
			SELECT COUNT(DISTINCT PaMainID) cnt,ProvinceID FROM #InterviewMonth
			WHERE PaMainID IN (SELECT PamainID FROM #t4)
			GROUP BY ProvinceID
		) b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDateMonth

		--收到面试通知的条数 月报
		UPDATE a SET a.InterviewCount=b.cnt 
		FROM Personreport a ,(
			SELECT COUNT(*) cnt,ProvinceID FROM #InterviewMonth 	
			WHERE PaMainID in(SELECT PamainID FROM #t4)
			GROUP BY ProvinceID
		) b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND a.TypeID = @i AND a.ReportDate = @ReportDateMonth

		--收到面试通知且已查看账号数量 月报
		UPDATE a SET a.InterviewViewAccount=b.cnt 
		FROM Personreport a ,(
			SELECT COUNT(DISTINCT PaMainID) cnt,ProvinceID FROM #InterviewMonth 
			WHERE (ViewDate BETWEEN @ReportBeginMonth AND @ReportEndMonth )
			AND PaMainID IN(SELECT PamainID FROM #t4)
			GROUP BY ProvinceID
		) b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDateMonth

		--清空临时表 #TmpInterview
		TRUNCATE TABLE #TmpInterview
		--得到未查看的账号信息
		INSERT INTO #TmpInterview SELECT *  FROM #InterviewMonth
		DELETE FROM #TmpInterview WHERE PaMainID IN (Select PaMainID FROM #InterviewMonth WHERE ViewDate BETWEEN @ReportBeginDay AND @ReportEndDay)

		--收到面试通知且未查看账号数量 月报
		UPDATE a SET a.InterviewNoViewAccount = b.cnt 
		FROM Personreport a ,(
			SELECT COUNT(DISTINCT PaMainID) cnt,ProvinceID FROM #TmpInterview 
			WHERE (ViewDate IS NULL )
			AND PaMainID IN(SELECT PamainID FROM #t4)
			GROUP BY ProvinceID
		) b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDateMonth
		
		--收到面试通知且已查看的条数 月报
		UPDATE a SET a.InterviewViewCount=b.cnt 
		FROM Personreport a ,(
			SELECT COUNT(PaMainID) cnt,ProvinceID FROM #InterviewMonth 
			WHERE (ViewDate BETWEEN @ReportBeginMonth AND @ReportEndMonth )
			AND PaMainID IN(SELECT PamainID FROM #t4)
			GROUP BY ProvinceID
		) b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDateMonth

		--收到面试通知且未查看的条数 月报
		UPDATE a SET a.InterviewNoViewCount=b.cnt 
		FROM Personreport a ,(
			SELECT COUNT(PaMainID) cnt,ProvinceID FROM #InterviewMonth 
			WHERE (ViewDate IS NULL )
			AND PaMainID IN(SELECT PamainID FROM #t4)
			GROUP BY ProvinceID
		) b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDateMonth

		--留言的账号数量 月报
		UPDATE a SET a.MessageAccount=b.cnt 
		FROM Personreport a ,(
			SELECT COUNT(DISTINCT PaMainID) cnt,ProvinceID FROM #t4
			WHERE PaMainID IN ( SELECT PamainID FROM #MessageMonth )
			GROUP BY ProvinceID
		) b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDateMonth

		--留言的条数 月报
		UPDATE a SET a.MessageCount=b.cnt 
		FROM Personreport a ,(
			SELECT COUNT(PaMainID) cnt,ProvinceID FROM #MessageMonth
			WHERE PaMainID IN ( SELECT PamainID FROM #t4)
			GROUP BY ProvinceID
		) b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDateMonth

		--收藏职位的账号数量 月报
		UPDATE a SET a.FavoriteAccount=b.cnt 
		FROM Personreport a ,(
			SELECT COUNT(DISTINCT PaMainID) cnt,ProvinceID FROM #t4
			WHERE PaMainID IN ( SELECT PamainID FROM #FavorateMonth )
			GROUP BY ProvinceID
		) b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDateMonth

		--收藏职位的条数 月报
		UPDATE a SET a.FavoriteCount=b.cnt 
		FROM Personreport a ,(
			SELECT COUNT(PaMainID) cnt,ProvinceID FROM #FavorateMonth
			WHERE PaMainID IN ( SELECT PamainID FROM #t4 )
			GROUP BY ProvinceID
		) b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDateMonth

		--申请职位的账号数量 月报
		UPDATE a SET a.ApplyAccount=b.cnt 
		FROM Personreport a ,(
			SELECT COUNT(DISTINCT PaMainID) cnt,ProvinceID FROM #ApplyMonth
			WHERE PaMainID IN ( SELECT PamainID FROM #t4 )
			GROUP BY ProvinceID
		)b
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDateMonth

		--申请职位的条数 月报
		UPDATE a SET a.ApplyCount=b.cnt 
		FROM Personreport a ,(
			SELECT COUNT(PaMainID) cnt,ProvinceID FROM #ApplyMonth
			WHERE PaMainID IN ( SELECT PamainID FROM #t4)
			GROUP BY ProvinceID
		) b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDateMonth

		--收到应聘邀请的账号数量 月报
		UPDATE a SET a.IntentionAccount=b.cnt 
		FROM Personreport a ,(
			SELECT COUNT(DISTINCT PaMainID) cnt,ProvinceID FROM #IntentionMonth
			WHERE PaMainID IN (SELECT PamainID FROM #t4)
			GROUP BY ProvinceID
		) b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDateMonth

		--收到应聘邀请的条数 月报
		UPDATE a SET a.IntentionCount=b.cnt 
		FROM Personreport a ,(
			SELECT COUNT(*) cnt,ProvinceID FROM #IntentionMonth
			WHERE PaMainID in(SELECT PamainID FROM #t4)
			GROUP BY ProvinceID
		) b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND a.TypeID = @i AND a.ReportDate = @ReportDateMonth

		--收到应聘邀请且已查看账号数量 月报
		UPDATE a SET a.IntentionViewAccount=b.cnt 
		FROM Personreport a ,(
			SELECT COUNT(DISTINCT PaMainID) cnt,ProvinceID FROM #IntentionMonth	
			WHERE (ReplyDate BETWEEN @ReportBeginMonth AND @ReportEndMonth )
			AND PaMainID IN(SELECT PamainID FROM #t4)
			GROUP BY ProvinceID
		) b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDateMonth

		--清空临时表 #TmpIntention
		TRUNCATE TABLE #TmpIntention
		--得到未查看的账号信息
		INSERT INTO #TmpIntention SELECT * FROM #IntentionMonth
		DELETE FROM #TmpIntention WHERE PaMainID IN (Select PaMainID FROM #IntentionMonth WHERE ReplyDate BETWEEN @ReportBeginDay AND @ReportEndDay)

		--收到应聘邀请且未查看账号数量 月报
		UPDATE a SET a.IntentionNoViewAccount = b.cnt 
		FROM Personreport a ,(
			SELECT COUNT(DISTINCT PaMainID) cnt,ProvinceID FROM #TmpIntention	
			WHERE (ReplyDate IS NULL )
			AND PaMainID IN(SELECT PamainID FROM #t4)
			GROUP BY ProvinceID
		) b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDateMonth
	
		--收到应聘邀请且已查看的条数 月报
		UPDATE a SET a.IntentionViewCount=b.cnt 
		FROM Personreport a ,(
			SELECT COUNT(PaMainID) cnt,ProvinceID FROM #IntentionMonth	
			WHERE (ReplyDate BETWEEN @ReportBeginMonth AND @ReportEndMonth)
			AND PaMainID IN(SELECT PamainID FROM #t4)
			GROUP BY ProvinceID
		) b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDateMonth

		--收到应聘邀请且未查看的条数 月报
		UPDATE a SET a.IntentionNoViewCount=b.cnt 
		FROM Personreport a ,(
			SELECT COUNT(PaMainID) cnt,ProvinceID FROM #IntentionMonth	
			WHERE (ReplyDate IS NULL )
			AND PaMainID IN(SELECT PamainID FROM #t4)
			GROUP BY ProvinceID
		) b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDateMonth
		
		--刷新简历的账号数量 @RefreshAccount 月报
		UPDATE a SET a.RefreshAccount=b.cnt 
		FROM Personreport a ,(
			SELECT COUNT(DISTINCT PaMainID) cnt,ProvinceID FROM #RefreshMonth
			WHERE PaMainID IN ( SELECT PamainID FROM #t4 )
			GROUP BY ProvinceID
		) b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDateMonth

		--刷新简历的次数 月报
		UPDATE a SET a.RefreshCount=b.cnt 
		FROM Personreport a ,(
			SELECT COUNT(PaMainID) cnt,ProvinceID FROM #RefreshMonth
			WHERE PaMainID IN ( SELECT PamainID FROM #t4)
			GROUP BY ProvinceID
		) b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDateMonth

		--临时表赋值
		INSERT INTO #OtherMonth SELECT * FROM #t4
		DELETE FROM #OtherMonth 
		WHERE PaMainID IN ( SELECT PamainID FROM #InterviewMonth)
		OR PaMainID IN ( SELECT PamainID FROM #MessageMonth)
		OR PaMainID IN ( SELECT PamainID FROM #FavorateMonth)
		OR PaMainID IN ( SELECT PamainID FROM #ApplyMonth)
		OR PaMainID IN ( SELECT PamainID FROM #IntentionMonth)
		OR PaMainID IN ( SELECT PamainID FROM #RefreshMonth)

		--其他账号数量、登录次数 月报
		UPDATE a SET OtherLoginAccount = b.cnt
		FROM Personreport a ,(
			SELECT COUNT(DISTINCT PaMainID) cnt,ProvinceID FROM #OtherMonth
			GROUP BY ProvinceID
		) b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDateMonth
		
		UPDATE a SET OtherLoginCount = b.cnt
		FROM Personreport a ,(
			SELECT COUNT(PaMainID) cnt,ProvinceID FROM #OtherMonth
			GROUP BY ProvinceID
		) b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDateMonth

		--频次 月报 begin-------------------------------
		INSERT INTO #RateMonth
		SELECT ProvinceID, Rate, Count(1) Cnt FROM (
			SELECT PamainID, ProvinceID, COUNT(1) Rate 
			FROM #t4 
			GROUP BY PamainID, ProvinceID
		) a 
		GROUP BY ProvinceId, Rate

		UPDATE a SET Rate1 = b.cnt
		FROM Personreport a ,#RateMonth b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDateMonth AND b.RateTmp=1

		UPDATE a SET Rate2 = b.cnt
		FROM Personreport a ,#RateMonth b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDateMonth AND b.RateTmp=2

		UPDATE a SET Rate3 = b.cnt
		FROM Personreport a ,#RateMonth b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDateMonth AND b.RateTmp=3

		UPDATE a SET Rate4 = b.cnt
		FROM Personreport a ,#RateMonth b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDateMonth AND b.RateTmp=4

		UPDATE a SET Rate5 = b.cnt
		FROM Personreport a ,#RateMonth b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDateMonth AND b.RateTmp=5

		UPDATE a SET Rate6 = b.cnt
		FROM Personreport a ,#RateMonth b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDateMonth AND b.RateTmp=6

		UPDATE a SET Rate7 = b.cnt
		FROM Personreport a ,#RateMonth b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDateMonth AND b.RateTmp=7

		UPDATE a SET Rate8 = b.cnt
		FROM Personreport a ,#RateMonth b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDateMonth AND b.RateTmp=8

		UPDATE a SET Rate9 = b.cnt
		FROM Personreport a ,#RateMonth b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDateMonth AND b.RateTmp BETWEEN 9 AND 14

		UPDATE a SET Rate15 = b.cnt
		FROM Personreport a ,#RateMonth b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDateMonth AND b.RateTmp BETWEEN 15 AND 25

		UPDATE a SET Rate15 = b.cnt
		FROM Personreport a ,#RateMonth b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDateMonth AND b.RateTmp >25

		--清空临时表
		TRUNCATE TABLE #T1
		TRUNCATE TABLE #T2
		TRUNCATE TABLE #T3
		TRUNCATE TABLE #T4
		TRUNCATE TABLE #Other
		TRUNCATE TABLE #OtherMonth
		TRUNCATE TABLE #Rate
		TRUNCATE TABLE #RateMonth
		TRUNCATE TABLE #TmpInterview
		TRUNCATE TABLE #TmpIntention
		SET @i = @i + 1
	END
	DROP TABLE #Interview
	DROP TABLE #Message
	DROP TABLE #Favorate
	DROP TABLE #Apply
	DROP TABLE #Intention
	DROP TABLE #Refresh
	DROP TABLE #InterviewMonth
	DROP TABLE #MessageMonth
	DROP TABLE #FavorateMonth
	DROP TABLE #ApplyMonth
	DROP TABLE #IntentionMonth
	DROP TABLE #RefreshMonth
	DROP TABLE #Other
	DROP TABLE #OtherMonth
	DROP TABLE #Rate
	DROP TABLE #RateMonth
END

GO
/****** Object:  StoredProcedure [dbo].[procPersonReportInsertTemp1110]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- 创建人:		Nick
-- 日期:		2013-11-12
-- 描述:		生成网站数据统计数据
-- =============================================
CREATE PROCEDURE [dbo].[procPersonReportInsertTemp1110]
(
	@d int
)
AS
BEGIN
	DECLARE @ReportBeginDay VARCHAR(30),@ReportBeginMonth VARCHAR(30),@ReportEndDay VARCHAR(30),
			@ReportEndMonth VARCHAR(30),@ReportDate VARCHAR(8),@ReportDateMonth VARCHAR(8),@Now DATETIME--统计日期
	DECLARE @i INT ,@StrWhere VARCHAR(500), @Sql VARCHAR(1000),@isHaveMonthData int
	
	--统计日期赋值	
	SET @Now = GETDATE() - @d
	--SET @Now = '2013-09-03'
	SET @ReportBeginDay = CONVERT(varchar(40),DATEADD(day,-1,@Now), 23)
	SET @ReportEndDay = CONVERT(varchar(30),@Now, 23)

	SET @ReportBeginMonth =  CONVERT(varchar(30),@NOW-1 - DAY(@NOW-1) + 1,23)
	SET @ReportEndMonth = CONVERT(varchar(30),DATEADD(MONTH, 1,@ReportBeginMonth),23)

	SET @ReportDate = CONVERT(varchar(30),DATEADD(day,-1,@Now), 112)
	SET @ReportDateMonth = SUBSTRING(@ReportDate,0,7)
		
	--删除当天日统计数据
	DELETE FROM PersonReport WHERE ReportDate = @ReportDate

	DECLARE @ProvinceID int	,@tmp int						--临时变量，用来保存省份编号

	--判断是否已存在月份数据
	IF EXISTS(SELECT 'x' FROM PersonReport WITH(NOLOCK) WHERE ReportDate = @ReportDateMonth)
	BEGIN
		SET @isHaveMonthData = 1  --已经存
	END
	ELSE 
	BEGIN
		SET @isHaveMonthData = 0  --不存在
	END

	--按照省份、状态 插入空数据
	DECLARE Province_curr CURSOR FOR				--申明游标
	SELECT ID FROM DcProvince						--查询省份编号
	OPEN Province_curr								--打开游标
	FETCH NEXT FROM Province_curr into @ProvinceID  --开始循环游标变量
	WHILE(@@fetch_status=0)							
	BEGIN
		SET @i = 0
	--================类型条件赋值============================================
		WHILE @i<11
		BEGIN
			--插入日报
			INSERT INTO PersonReport (ReportDate,ProvinceID,TypeID)
			VALUES (@ReportDate,@ProvinceID,@i)
			IF(@isHaveMonthData = 0)
			BEGIN
				--插入月报
				INSERT INTO PersonReport (ReportDate,ProvinceID,TypeID)
				VALUES (@ReportDateMonth,@ProvinceID,@i)
			END
			SET @i = @i + 1
		END
		FETCH NEXT FROM Province_curr into @ProvinceID --开始循环游标变量
	END
	CLOSE Province_curr--关闭游标
	DEALLOCATE Province_curr --释放游标

	--================创建临时表============================================
	CREATE TABLE #t1 -- 临时表 #t1  登陆过且未完善的pamainid 日报
	(
		PamainID   int,
		ProvinceID int
	)
	CREATE TABLE #t2 -- 临时表 #t2  登陆过且完善的pamainid 日报
	(
		PamainID   int ,
		ProvinceID int
	)
	CREATE TABLE #t3 -- 临时表 #t3  登陆过且未完善的pamainid 月报
	(
		PamainID   int ,
		ProvinceID int
	)
	CREATE TABLE #t4 -- 临时表 #t4  登陆过且完善的pamainid 月报
	(
		PamainID   int ,
		ProvinceID int
	)

	CREATE TABLE #Interview -- 临时表 #Interview  收到面试通知的账号 日报
	(
		PamainID   int,
		Adddate DateTime,
		ViewDate DateTime,
		ProvinceID int
	)

	CREATE TABLE #TmpInterview -- 临时表 #TmpInterview 
	(
		PamainID   int,
		Adddate DateTime,
		ViewDate DateTime,
		ProvinceID int
	)

	CREATE TABLE #Message -- 临时表 #Message  收到留言的账号 日报
	(
		PamainID   int,
		ProvinceID int
	)
	CREATE TABLE #Favorate -- 临时表 Favorate  收藏职位的账号 日报
	(
		PamainID   int,
		ProvinceID int
	)
	CREATE TABLE #Apply -- 临时表 #Apply  申请职位的账号 日报
	(
		PamainID   int,
		ProvinceID int
	)
	CREATE TABLE #Intention -- 临时表 #Intention	  收到应聘邀请的账号 日报
	(
		PamainID   int,
		ReplyDate DateTime,
		ProvinceID int
	)

	CREATE TABLE #TmpIntention -- 临时表 #TmpIntention
	(
		PamainID   int,
		ReplyDate DateTime,
		ProvinceID int
	)

	CREATE TABLE #Refresh -- 临时表 #Refresh	  刷新简历的账号 日报
	(
		PamainID   int,
		ProvinceID int
	)
	CREATE TABLE #Other -- 临时表 #Other	  
	(
		PamainID   int,
		ProvinceID int
	)
	CREATE TABLE #Rate -- 临时表 #Rate  频次
	(
		ProvinceID int,
		RateTmp   int,
		Cnt int
	)

	CREATE TABLE #InterviewMonth -- 临时表 #InterviewMonth  收到面试通知的账号 月报
	(
		PamainID   int,
		Adddate DateTime,
		ViewDate DateTime,
		ProvinceID int
	)
	CREATE TABLE #MessageMonth -- 临时表 #MessageMonth  收到留言的账号 月报
	(
		PamainID   int,
		ProvinceID int
	)
	CREATE TABLE #FavorateMonth -- 临时表 FavorateMonth  收藏职位的账号 月报
	(
		PamainID   int,
		ProvinceID int
	)
	CREATE TABLE #ApplyMonth -- 临时表 #ApplyMonth  申请职位的账号 月报
	(
		PamainID   int,
		ProvinceID int
	)
	CREATE TABLE #IntentionMonth -- 临时表 #IntentionMonth	  收到应聘邀请的账号 月报
	(
		PamainID   int,
		ReplyDate DateTime,
		ProvinceID int
	)
	CREATE TABLE #RefreshMonth -- 临时表 #RefreshMonth	  刷新简历的账号 月报
	(
		PamainID   int,
		ProvinceID int
	)
	CREATE TABLE #OtherMonth -- 临时表 #OtherMonth	  
	(
		PamainID   int,
		ProvinceID int
	)
	CREATE TABLE #RateMonth -- 临时表 #RateMonth  频次
	(
		ProvinceID int,
		RateTmp   int,
		Cnt int
	)

	--将收到面试通知的账号放入临时表 日报
	INSERT INTO #Interview
	SELECT b.PamainID,a.Adddate,a.ViewDate,c.dcProvinceID
	FROM exInterView a,CvMain b,PaMain c
	WHERE (a.AddDate BETWEEN @ReportBeginDay AND @ReportEndDay )
	AND a.CvMainID = b.ID
	AND b.PamainID = c.ID 

	--将发送留言的账号放入临时表 日报
	INSERT INTO #Message
	SELECT b.PamainID,c.dcProvinceID
	FROM exMessagep2c a,CvMain b,PaMain c
	WHERE (a.AddDate BETWEEN @ReportBeginDay AND @ReportEndDay )
	AND a.CvMainID = b.ID
	AND b.PamainID = c.ID 

	--将收藏职位的账号信息放入临时表 日报
	INSERT INTO #Favorate
	SELECT a.PamainID,b.dcProvinceID 
	FROM paFavorate a,PaMain b
	WHERE (a.AddDate BETWEEN @ReportBeginDay AND @ReportEndDay )
	AND a.PamainID = b.ID

	--将申请职位的账号放入临时表 日报
	INSERT INTO #Apply
	SELECT b.PamainID,c.dcProvinceID
	FROM exJobApply a,CvMain b,PaMain c
	WHERE (a.AddDate BETWEEN @ReportBeginDay AND @ReportEndDay )
	AND a.CvMainID = b.ID
	AND b.PamainID = c.ID 

	--将收到应聘邀请的账号放入临时表 日报
	INSERT INTO #Intention
	SELECT b.PamainID,a.ReplyDate,c.dcProvinceID
	FROM caCvIntention a,CvMain b,PaMain c
	WHERE (a.AddDate BETWEEN @ReportBeginDay AND @ReportEndDay )
	AND a.CvMainID = b.ID
	AND b.PamainID = c.ID 

	--将刷新简历的账号放入临时表 日报
	INSERT INTO #Refresh
	SELECT a.PamainID,b.dcProvinceID FROM CvMain a,PaMain b 
	WHERE (RefreshDate BETWEEN @ReportBeginDay AND @ReportEndDay )
	AND a.PamainID = b.ID 


	--将收到面试通知的账号放入临时表 月报
	INSERT INTO #InterviewMonth
	SELECT b.PamainID,a.Adddate,a.ViewDate,c.dcProvinceID
	FROM exInterView a,CvMain b,PaMain c
	WHERE (a.AddDate BETWEEN @ReportBeginMonth AND @ReportEndMonth )
	AND a.CvMainID = b.ID
	AND b.PamainID = c.ID 

	--将发送留言的账号放入临时表 月报
	INSERT INTO #MessageMonth
	SELECT b.PamainID,c.dcProvinceID
	FROM exMessagep2c a,CvMain b,PaMain c
	WHERE (a.AddDate BETWEEN @ReportBeginMonth AND @ReportEndMonth )
	AND a.CvMainID = b.ID
	AND b.PamainID = c.ID 

	--将收藏职位的账号信息放入临时表 月报
	INSERT INTO #FavorateMonth
	SELECT a.PamainID,b.dcProvinceID 
	FROM paFavorate a,PaMain b 
	WHERE (a.AddDate BETWEEN @ReportBeginMonth AND @ReportEndMonth )
	AND a.PamainID = b.ID

	--将申请职位的账号放入临时表 月报
	INSERT INTO #ApplyMonth
	SELECT b.PamainID,c.dcProvinceID
	FROM exJobApply a,CvMain b,PaMain c
	WHERE (a.AddDate BETWEEN @ReportBeginMonth AND @ReportEndMonth )
	AND a.CvMainID = b.ID
	AND b.PamainID = c.ID 

	--将收到应聘邀请的账号放入临时表 月报
	INSERT INTO #IntentionMonth
	SELECT b.PamainID,a.ReplyDate,c.dcProvinceID
	FROM caCvIntention a,CvMain b,PaMain c
	WHERE (a.AddDate BETWEEN @ReportBeginMonth AND @ReportEndMonth )
	AND a.CvMainID = b.ID
	AND b.PamainID = c.ID 

	--将刷新简历的账号放入临时表 日月报
	INSERT INTO #RefreshMonth
	SELECT a.PamainID,b.dcProvinceID FROM CvMain a,PaMain b 
	WHERE (RefreshDate BETWEEN @ReportBeginMonth AND @ReportEndMonth )
	AND a.PamainID = b.ID 

	SET @i = 0
	WHILE @i<11
	BEGIN
		IF @i = 1		--邮件推广
		BEGIN
			SET @StrWhere = ' AND (b.RegisterMode = 1 or b.RegisterMode = 11) '
		END
		ELSE IF @i=2	--招聘会推广
		BEGIN
			SET @StrWhere = ' AND b.RegisterMode=12 '
		END
		ELSE IF @i=3	--电话推广
		BEGIN
			SET @StrWhere = ' AND b.RegisterMode=13 '
		END
		ELSE IF @i=4	--短信推广
		BEGIN
			SET @StrWhere = ' AND b.RegisterMode=14 '
		END
		ELSE IF @i=5	--本人注册
		BEGIN
			SET @StrWhere = ' AND b.RegisterMode=0'
		END
		ELSE IF @i=6	--公开
		BEGIN
			SET @StrWhere = ' AND IscvHidden <> 1 '
		END
		ELSE IF @i=7	--隐藏
		BEGIN
			SET @StrWhere = ' AND IscvHidden = 1 '
		END
		ELSE IF @i=8	--手机认证
		BEGIN
			SET @StrWhere = ' AND MobileVerifyDate IS NOT NULL '
		END
		ELSE IF @i=9	--邮箱认证
		BEGIN
			SET @StrWhere = ' AND EmailVerifyDate IS NOT NULL '
		END
		ELSE IF @i=10	--未认证
		BEGIN
			SET @StrWhere = ' AND (MobileVerifyDate IS NULL AND EmailVerifyDate IS NULL) '
		END 
		ELSE
		BEGIN			--全部
			SET @StrWhere = ''
		END

		--将登陆过且未完善的pamainid放入临时表 #t1 日报
		IF(@i=6 OR @i=7)
		BEGIN
			SET @Sql = 'SELECT a.PaMainID,b.dcProvinceID ProvinceID FROM PaLoginLog a,PaMain b
				WHERE (a.AddDate BETWEEN '''+@ReportBeginDay+''' AND '''+@ReportEndDay+''' )
				AND a.PamainID = b.ID 
				AND a.PamainID IN(
					SELECT PamainID FROM CvMain WHERE CvLevel NOT LIKE ''1111_1%'' AND Attachment is null
					'+@StrWhere+'
				)'
			INSERT INTO  #t1 EXEC(@Sql)
			print (@Sql)
			--将有完善简历的账户删除
			DELETE FROM #t1 WHERE PamainID IN (SELECT PamainID FROM CvMain WHERE CvLevel LIKE '1111_1%' or Attachment <>'') 
			IF @i=7
			BEGIN
				--将公开的简历删除
				DELETE FROM #t1 WHERE PamainID IN (SELECT PamainID FROM CvMain WHERE IscvHidden <> 1) 
			END

			--将登陆过且完善的pamainid放入临时表 #t2 日报
			SET @Sql = 'SELECT a.PaMainID,b.dcProvinceID ProvinceID FROM PaLoginLog a,PaMain b
				WHERE (a.AddDate BETWEEN '''+@ReportBeginDay+''' AND '''+@ReportEndDay+''' )
				AND a.PamainID = b.ID 
				AND a.PaMainID IN (SELECT PamainID FROM CvMain WHERE (CvLevel LIKE ''1111_1%'' or Attachment <>'''') '+@StrWhere+')
				' 
			INSERT INTO  #t2 EXEC(@Sql)
			IF @i=7
			BEGIN
				--将公开的简历删除
				DELETE FROM #t2 WHERE PamainID IN (SELECT PamainID FROM CvMain WHERE IscvHidden <> 1) 
			END

			--将登陆过且未完善的pamainid放入临时表 #t3 月报
			SET @Sql = 'SELECT a.PaMainID,b.dcProvinceID ProvinceID FROM PaLoginLog a,PaMain b
				WHERE (a.AddDate BETWEEN '''+@ReportBeginMonth+''' AND '''+@ReportEndMonth+''' )
				AND a.PamainID = b.ID  
				AND a.PaMainID IN (SELECT PamainID FROM CvMain WHERE CvLevel NOT LIKE ''1111_1%'' AND Attachment is null '+@StrWhere+')
			' 
			INSERT INTO #t3 EXEC(@Sql)
			--将有完善简历的账户删除
			DELETE FROM #t3 WHERE PamainID IN (SELECT PamainID FROM CvMain WHERE CvLevel LIKE '1111_1%' or Attachment <>'') 
			IF @i=7
			BEGIN
				--将公开的简历删除
				DELETE FROM #t3 WHERE PamainID IN (SELECT PamainID FROM CvMain WHERE IscvHidden <> 1) 
			END

			--将登陆过且完善的pamainid放入临时表 #t4 月报
			SET @Sql = 'SELECT a.PaMainID,b.dcProvinceID ProvinceID FROM PaLoginLog a,PaMain b
				WHERE (a.AddDate BETWEEN '''+@ReportBeginMonth+''' AND '''+@ReportEndMonth+''' )
				AND a.PamainID = b.ID  
				AND a.PaMainID IN (SELECT PamainID FROM CvMain WHERE (CvLevel LIKE ''1111_1%'' or Attachment <>'''') '+@StrWhere+')
				'
			INSERT INTO  #t4 EXEC(@Sql)
			IF @i=7
			BEGIN
				--将公开的简历删除
				DELETE FROM #t4 WHERE PamainID IN (SELECT PamainID FROM CvMain WHERE IscvHidden <> 1) 
			END

		END
		ELSE 
		BEGIN
			SET @Sql = 'SELECT a.PaMainID,b.dcProvinceID ProvinceID FROM PaLoginLog a,PaMain b
				WHERE (a.AddDate BETWEEN '''+@ReportBeginDay+''' AND '''+@ReportEndDay+''' )
				AND a.PamainID = b.ID 
				AND a.PamainID IN(SELECT PamainID FROM CvMain WHERE CvLevel NOT LIKE ''1111_1%'' AND Attachment is null)
			' + @StrWhere
			INSERT INTO  #t1 EXEC(@Sql)

			--将登陆过且完善的pamainid放入临时表 #t2 日报
			SET @Sql = 'SELECT a.PaMainID,b.dcProvinceID ProvinceID FROM PaLoginLog a,PaMain b
				WHERE (a.AddDate BETWEEN '''+@ReportBeginDay+''' AND '''+@ReportEndDay+''' )
				AND a.PamainID = b.ID 
				AND a.PaMainID IN (SELECT PamainID FROM CvMain WHERE CvLevel LIKE ''1111_1%'' or Attachment <>'''')
				' + @StrWhere

			INSERT INTO  #t2 EXEC(@Sql)

			--将登陆过且未完善的pamainid放入临时表 #t3 月报
			SET @Sql = 'SELECT a.PaMainID,b.dcProvinceID ProvinceID FROM PaLoginLog a,PaMain b
				WHERE (a.AddDate BETWEEN '''+@ReportBeginMonth+''' AND '''+@ReportEndMonth+''' )
				AND a.PamainID = b.ID  
				AND a.PaMainID IN (SELECT PamainID FROM CvMain WHERE CvLevel NOT LIKE ''1111_1%'' AND Attachment is null)
			' + @StrWhere
			INSERT INTO #t3 EXEC(@Sql)

			--将登陆过且完善的pamainid放入临时表 #t4 月报
			SET @Sql = 'SELECT a.PaMainID,b.dcProvinceID ProvinceID FROM PaLoginLog a,PaMain b
				WHERE (a.AddDate BETWEEN '''+@ReportBeginMonth+''' AND '''+@ReportEndMonth+''' )
				AND a.PamainID = b.ID  
				AND a.PaMainID IN (SELECT PamainID FROM CvMain WHERE CvLevel LIKE ''1111_1%'' or Attachment <>'''')
				' + @StrWhere
			INSERT INTO  #t4 EXEC(@Sql)
		END
 
		--未完善简历的账号数量 赋值 日报
		UPDATE a SET a.LoginNoPerfectAccount=b.cnt 
		FROM Personreport a ,(SELECT COUNT(DISTINCT PaMainID) cnt,ProvinceID FROM #t1 GROUP BY ProvinceID) b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDate

		--未完善账号的登录次数 日报
		UPDATE a SET a.LoginNoPerfectCount=b.cnt 
		FROM Personreport a ,(SELECT COUNT(PaMainID) cnt,ProvinceID FROM #t1 GROUP BY ProvinceID) b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDate

		--完善简历的账号数量 赋值 日报
		UPDATE a SET a.LoginPerfectAccount=b.cnt 
		FROM Personreport a ,(SELECT COUNT(DISTINCT PaMainID) cnt,ProvinceID FROM #t2 GROUP BY ProvinceID) b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDate

		--完善简历的账号登陆次数 赋值 日报
		UPDATE a SET a.LoginPerfectCount=b.cnt 
		FROM Personreport a ,(SELECT COUNT(PaMainID) cnt,ProvinceID FROM #t2 GROUP BY ProvinceID) b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDate

		--收到面试通知的账号数量 日报
		UPDATE a SET a.InterviewAccount=b.cnt 
		FROM Personreport a ,(
			SELECT COUNT(DISTINCT PaMainID) cnt,ProvinceID FROM #Interview
			WHERE PaMainID IN (SELECT PamainID FROM #t2)
			GROUP BY ProvinceID
		) b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDate

		--收到面试通知的条数 日报
		UPDATE a SET a.InterviewCount=b.cnt 
		FROM Personreport a ,(
			SELECT COUNT(*) cnt,ProvinceID FROM #Interview 	
			WHERE PaMainID in(SELECT PamainID FROM #t2)
			GROUP BY ProvinceID
		) b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND a.TypeID = @i AND a.ReportDate = @ReportDate

		--收到面试通知且已查看账号数量 日报
		UPDATE a SET a.InterviewViewAccount=b.cnt 
		FROM Personreport a ,(
			SELECT COUNT(DISTINCT PaMainID) cnt,ProvinceID FROM #Interview 
			WHERE (ViewDate BETWEEN @ReportBeginDay AND @ReportEndDay )
			AND PaMainID IN(SELECT PamainID FROM #t2)
			GROUP BY ProvinceID
		) b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDate

		--得到未查看的账号信息
		INSERT INTO #TmpInterview SELECT * FROM #Interview
		DELETE FROM #TmpInterview WHERE PaMainID IN (Select PaMainID FROM #Interview WHERE ViewDate BETWEEN @ReportBeginDay AND @ReportEndDay)
		--收到面试通知且未查看账号数量 日报
		UPDATE a SET a.InterviewNoViewAccount = b.cnt 
		FROM Personreport a ,(
			SELECT COUNT(DISTINCT PaMainID) cnt,ProvinceID FROM #TmpInterview 
			WHERE (ViewDate IS NULL )
			AND PaMainID IN(SELECT PamainID FROM #t2)
			GROUP BY ProvinceID
		) b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDate
		
		--收到面试通知且已查看的条数 日报
		UPDATE a SET a.InterviewViewCount=b.cnt 
		FROM Personreport a ,(
			SELECT COUNT(PaMainID) cnt,ProvinceID FROM #Interview 
			WHERE (ViewDate BETWEEN @ReportBeginDay AND @ReportEndDay )
			AND PaMainID IN(SELECT PamainID FROM #t2)
			GROUP BY ProvinceID
		) b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDate

		--收到面试通知且未查看的条数 日报
		UPDATE a SET a.InterviewNoViewCount=b.cnt 
		FROM Personreport a ,(
			SELECT COUNT(PaMainID) cnt,ProvinceID FROM #Interview 
			WHERE (ViewDate IS NULL )
			AND PaMainID IN(SELECT PamainID FROM #t2)
			GROUP BY ProvinceID
		) b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDate

		--留言的账号数量 日报
		UPDATE a SET a.MessageAccount=b.cnt 
		FROM Personreport a ,(
			SELECT COUNT(DISTINCT PaMainID) cnt,ProvinceID FROM #t2
			WHERE PaMainID IN ( SELECT PamainID FROM #Message )
			GROUP BY ProvinceID
		) b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDate

		--留言的条数 日报
		UPDATE a SET a.MessageCount=b.cnt 
		FROM Personreport a ,(
			SELECT COUNT(PaMainID) cnt,ProvinceID FROM #Message
			WHERE PaMainID IN ( SELECT PamainID FROM #t2 )
			GROUP BY ProvinceID
		) b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDate

		--收藏职位的账号数量 日报
		UPDATE a SET a.FavoriteAccount=b.cnt 
		FROM Personreport a ,(
			SELECT COUNT(DISTINCT PaMainID) cnt,ProvinceID FROM #t2
			WHERE PaMainID IN ( SELECT PamainID FROM #Favorate )
			GROUP BY ProvinceID
		) b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDate

		--收藏职位的条数 日报
		UPDATE a SET a.FavoriteCount=b.cnt 
		FROM Personreport a ,(
			SELECT COUNT(PaMainID) cnt,ProvinceID FROM #Favorate
			WHERE PaMainID IN ( SELECT PamainID FROM #t2 )
			GROUP BY ProvinceID
		) b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDate

		--申请职位的账号数量 日报
		UPDATE a SET a.ApplyAccount=b.cnt 
		FROM Personreport a ,(
			SELECT COUNT(DISTINCT PaMainID) cnt,ProvinceID FROM #Apply
			WHERE PaMainID IN ( SELECT PamainID FROM #t2 )
			GROUP BY ProvinceID
		)b
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDate

		--申请职位的条数 日报
		UPDATE a SET a.ApplyCount=b.cnt 
		FROM Personreport a ,(
			SELECT COUNT(PaMainID) cnt,ProvinceID FROM #Apply
			WHERE PaMainID IN ( SELECT PamainID FROM #t2 )
			GROUP BY ProvinceID
		) b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDate

		--收到应聘邀请的账号数量 日报
		UPDATE a SET a.IntentionAccount=b.cnt 
		FROM Personreport a ,(
			SELECT COUNT(DISTINCT PaMainID) cnt,ProvinceID FROM #Intention
			WHERE PaMainID IN (SELECT PamainID FROM #t2)
			GROUP BY ProvinceID
		) b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDate

		--收到应聘邀请的条数 日报
		UPDATE a SET a.IntentionCount=b.cnt 
		FROM Personreport a ,(
			SELECT COUNT(*) cnt,ProvinceID FROM #Intention 	
			WHERE PaMainID in(SELECT PamainID FROM #t2)
			GROUP BY ProvinceID
		) b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND a.TypeID = @i AND a.ReportDate = @ReportDate

		--收到应聘邀请且已查看账号数量 日报
		UPDATE a SET a.IntentionViewAccount=b.cnt 
		FROM Personreport a ,(
			SELECT COUNT(DISTINCT PaMainID) cnt,ProvinceID FROM #Intention	
			WHERE (ReplyDate BETWEEN @ReportBeginDay AND @ReportEndDay )
			AND PaMainID IN(SELECT PamainID FROM #t2)
			GROUP BY ProvinceID
		) b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDate

		--得到未查看的账号信息
		INSERT INTO #TmpIntention SELECT * FROM #Intention
		DELETE FROM #TmpIntention WHERE PaMainID IN (Select PaMainID FROM #Intention WHERE ReplyDate BETWEEN @ReportBeginDay AND @ReportEndDay)

		--收到应聘邀请且未查看账号数量 日报
		UPDATE a SET a.IntentionNoViewAccount = b.cnt 
		FROM Personreport a ,(
			SELECT COUNT(DISTINCT PaMainID) cnt,ProvinceID FROM #TmpIntention	
			WHERE (ReplyDate IS NULL )
			AND PaMainID IN(SELECT PamainID FROM #t2)
			GROUP BY ProvinceID
		) b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDate
		
		--收到应聘邀请且已查看的条数 日报
		UPDATE a SET a.IntentionViewCount=b.cnt 
		FROM Personreport a ,(
			SELECT COUNT(PaMainID) cnt,ProvinceID FROM #Intention	
			WHERE (ReplyDate BETWEEN @ReportBeginDay AND @ReportEndDay )
			AND PaMainID IN(SELECT PamainID FROM #t2)
			GROUP BY ProvinceID
		) b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDate

		--收到应聘邀请且未查看的条数 日报
		UPDATE a SET a.IntentionNoViewCount=b.cnt 
		FROM Personreport a ,(
			SELECT COUNT(PaMainID) cnt,ProvinceID FROM #Intention	
			WHERE (ReplyDate IS NULL )
			AND PaMainID IN(SELECT PamainID FROM #t2)
			GROUP BY ProvinceID
		) b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDate
		
		--刷新简历的账号数量 @RefreshAccount 日报
		UPDATE a SET a.RefreshAccount=b.cnt 
		FROM Personreport a ,(
			SELECT COUNT(DISTINCT PaMainID) cnt,ProvinceID FROM #Refresh
			WHERE PaMainID IN ( SELECT PamainID FROM #t2 )
			GROUP BY ProvinceID
		) b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDate

		--刷新简历的次数 日报
		UPDATE a SET a.RefreshCount=b.cnt 
		FROM Personreport a ,(
			SELECT COUNT(PaMainID) cnt,ProvinceID FROM #Refresh
			WHERE PaMainID IN ( SELECT PamainID FROM #t2 )
			GROUP BY ProvinceID
		) b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDate

		--临时表赋值
		INSERT INTO #Other SELECT * FROM #t2
		DELETE FROM #Other 
		WHERE PaMainID IN ( SELECT PamainID FROM #Interview)
		OR PaMainID IN ( SELECT PamainID FROM #Message)
		OR PaMainID IN ( SELECT PamainID FROM #Favorate)
		OR PaMainID IN ( SELECT PamainID FROM #Apply)
		OR PaMainID IN ( SELECT PamainID FROM #Intention)
		OR PaMainID IN ( SELECT PamainID FROM #Refresh )

		--其他账号数量、登录次数 日报
		UPDATE a SET OtherLoginAccount = b.cnt
		FROM Personreport a ,(
			SELECT COUNT(DISTINCT PaMainID) cnt,ProvinceID FROM #Other
			GROUP BY ProvinceID
		) b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDate
		
		UPDATE a SET OtherLoginCount = b.cnt
		FROM Personreport a ,(
			SELECT COUNT(1) cnt,ProvinceID FROM #Other
			GROUP BY ProvinceID
		) b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDate

		--频次 日报 begin-------------------------------
		INSERT INTO #Rate
		SELECT ProvinceID, Rate, Count(1) Cnt FROM (
			SELECT PamainID, ProvinceID, COUNT(1) Rate 
			FROM #t2 
			GROUP BY PamainID, ProvinceID
		) a 
		GROUP BY ProvinceId, Rate

		UPDATE a SET Rate1 = b.cnt
		FROM Personreport a ,#Rate b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDate AND b.RateTmp=1

		UPDATE a SET Rate2 = b.cnt
		FROM Personreport a ,#Rate b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDate AND b.RateTmp=2

		UPDATE a SET Rate3 = b.cnt
		FROM Personreport a ,#Rate b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDate AND b.RateTmp=3

		UPDATE a SET Rate4 = b.cnt
		FROM Personreport a ,#Rate b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDate AND b.RateTmp=4

		UPDATE a SET Rate5 = b.cnt
		FROM Personreport a ,#Rate b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDate AND b.RateTmp=5

		UPDATE a SET Rate6 = b.cnt
		FROM Personreport a ,#Rate b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDate AND b.RateTmp=6

		UPDATE a SET Rate7 = b.cnt
		FROM Personreport a ,#Rate b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDate AND b.RateTmp=7

		UPDATE a SET Rate8 = b.cnt
		FROM Personreport a ,#Rate b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDate AND b.RateTmp=8

		UPDATE a SET Rate9 = b.cnt
		FROM Personreport a ,#Rate b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDate AND b.RateTmp  BETWEEN 9 AND 14

		UPDATE a SET Rate15 = b.cnt
		FROM Personreport a ,#Rate b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDate AND b.RateTmp  BETWEEN 15 AND 25

		UPDATE a SET Rate15 = b.cnt
		FROM Personreport a ,#Rate b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDate AND b.RateTmp>25
		--频次 日报 end-------------------------------

		--未完善简历的账号数量 赋值 月报
		UPDATE a SET a.LoginNoPerfectAccount=b.cnt 
		FROM Personreport a ,(SELECT COUNT(DISTINCT PaMainID) cnt,ProvinceID FROM #t3 GROUP BY ProvinceID) b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDateMonth

		--未完善账号的登录次数 月报
		UPDATE a SET a.LoginNoPerfectCount=b.cnt 
		FROM Personreport a ,(SELECT COUNT(PaMainID) cnt,ProvinceID FROM #t3 GROUP BY ProvinceID) b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDateMonth

		--完善简历的账号数量 赋值 月报
		UPDATE a SET a.LoginPerfectAccount=b.cnt 
		FROM Personreport a ,(SELECT COUNT(DISTINCT PaMainID) cnt,ProvinceID FROM #t4 GROUP BY ProvinceID) b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDateMonth

		--完善简历的账号登陆次数 赋值 月报
		UPDATE a SET a.LoginPerfectCount=b.cnt 
		FROM Personreport a ,(SELECT COUNT(PaMainID) cnt,ProvinceID FROM #t4 GROUP BY ProvinceID) b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDateMonth

		--收到面试通知的账号数量 月报
		UPDATE a SET a.InterviewAccount=b.cnt 
		FROM Personreport a ,(
			SELECT COUNT(DISTINCT PaMainID) cnt,ProvinceID FROM #InterviewMonth
			WHERE PaMainID IN (SELECT PamainID FROM #t4)
			GROUP BY ProvinceID
		) b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDateMonth

		--收到面试通知的条数 月报
		UPDATE a SET a.InterviewCount=b.cnt 
		FROM Personreport a ,(
			SELECT COUNT(*) cnt,ProvinceID FROM #InterviewMonth 	
			WHERE PaMainID in(SELECT PamainID FROM #t4)
			GROUP BY ProvinceID
		) b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND a.TypeID = @i AND a.ReportDate = @ReportDateMonth

		--收到面试通知且已查看账号数量 月报
		UPDATE a SET a.InterviewViewAccount=b.cnt 
		FROM Personreport a ,(
			SELECT COUNT(DISTINCT PaMainID) cnt,ProvinceID FROM #InterviewMonth 
			WHERE (ViewDate BETWEEN @ReportBeginMonth AND @ReportEndMonth )
			AND PaMainID IN(SELECT PamainID FROM #t4)
			GROUP BY ProvinceID
		) b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDateMonth

		--清空临时表 #TmpInterview
		TRUNCATE TABLE #TmpInterview
		--得到未查看的账号信息
		INSERT INTO #TmpInterview SELECT *  FROM #InterviewMonth
		DELETE FROM #TmpInterview WHERE PaMainID IN (Select PaMainID FROM #InterviewMonth WHERE ViewDate BETWEEN @ReportBeginDay AND @ReportEndDay)

		--收到面试通知且未查看账号数量 月报
		UPDATE a SET a.InterviewNoViewAccount = b.cnt 
		FROM Personreport a ,(
			SELECT COUNT(DISTINCT PaMainID) cnt,ProvinceID FROM #TmpInterview 
			WHERE (ViewDate IS NULL )
			AND PaMainID IN(SELECT PamainID FROM #t4)
			GROUP BY ProvinceID
		) b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDateMonth
		
		--收到面试通知且已查看的条数 月报
		UPDATE a SET a.InterviewViewCount=b.cnt 
		FROM Personreport a ,(
			SELECT COUNT(PaMainID) cnt,ProvinceID FROM #InterviewMonth 
			WHERE (ViewDate BETWEEN @ReportBeginMonth AND @ReportEndMonth )
			AND PaMainID IN(SELECT PamainID FROM #t4)
			GROUP BY ProvinceID
		) b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDateMonth

		--收到面试通知且未查看的条数 月报
		UPDATE a SET a.InterviewNoViewCount=b.cnt 
		FROM Personreport a ,(
			SELECT COUNT(PaMainID) cnt,ProvinceID FROM #InterviewMonth 
			WHERE (ViewDate IS NULL )
			AND PaMainID IN(SELECT PamainID FROM #t4)
			GROUP BY ProvinceID
		) b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDateMonth

		--留言的账号数量 月报
		UPDATE a SET a.MessageAccount=b.cnt 
		FROM Personreport a ,(
			SELECT COUNT(DISTINCT PaMainID) cnt,ProvinceID FROM #t4
			WHERE PaMainID IN ( SELECT PamainID FROM #MessageMonth )
			GROUP BY ProvinceID
		) b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDateMonth

		--留言的条数 月报
		UPDATE a SET a.MessageCount=b.cnt 
		FROM Personreport a ,(
			SELECT COUNT(PaMainID) cnt,ProvinceID FROM #MessageMonth
			WHERE PaMainID IN ( SELECT PamainID FROM #t4)
			GROUP BY ProvinceID
		) b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDateMonth

		--收藏职位的账号数量 月报
		UPDATE a SET a.FavoriteAccount=b.cnt 
		FROM Personreport a ,(
			SELECT COUNT(DISTINCT PaMainID) cnt,ProvinceID FROM #t4
			WHERE PaMainID IN ( SELECT PamainID FROM #FavorateMonth )
			GROUP BY ProvinceID
		) b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDateMonth

		--收藏职位的条数 月报
		UPDATE a SET a.FavoriteCount=b.cnt 
		FROM Personreport a ,(
			SELECT COUNT(PaMainID) cnt,ProvinceID FROM #FavorateMonth
			WHERE PaMainID IN ( SELECT PamainID FROM #t4 )
			GROUP BY ProvinceID
		) b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDateMonth

		--申请职位的账号数量 月报
		UPDATE a SET a.ApplyAccount=b.cnt 
		FROM Personreport a ,(
			SELECT COUNT(DISTINCT PaMainID) cnt,ProvinceID FROM #ApplyMonth
			WHERE PaMainID IN ( SELECT PamainID FROM #t4 )
			GROUP BY ProvinceID
		)b
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDateMonth

		--申请职位的条数 月报
		UPDATE a SET a.ApplyCount=b.cnt 
		FROM Personreport a ,(
			SELECT COUNT(PaMainID) cnt,ProvinceID FROM #ApplyMonth
			WHERE PaMainID IN ( SELECT PamainID FROM #t4)
			GROUP BY ProvinceID
		) b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDateMonth

		--收到应聘邀请的账号数量 月报
		UPDATE a SET a.IntentionAccount=b.cnt 
		FROM Personreport a ,(
			SELECT COUNT(DISTINCT PaMainID) cnt,ProvinceID FROM #IntentionMonth
			WHERE PaMainID IN (SELECT PamainID FROM #t4)
			GROUP BY ProvinceID
		) b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDateMonth

		--收到应聘邀请的条数 月报
		UPDATE a SET a.IntentionCount=b.cnt 
		FROM Personreport a ,(
			SELECT COUNT(*) cnt,ProvinceID FROM #IntentionMonth
			WHERE PaMainID in(SELECT PamainID FROM #t4)
			GROUP BY ProvinceID
		) b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND a.TypeID = @i AND a.ReportDate = @ReportDateMonth

		--收到应聘邀请且已查看账号数量 月报
		UPDATE a SET a.IntentionViewAccount=b.cnt 
		FROM Personreport a ,(
			SELECT COUNT(DISTINCT PaMainID) cnt,ProvinceID FROM #IntentionMonth	
			WHERE (ReplyDate BETWEEN @ReportBeginMonth AND @ReportEndMonth )
			AND PaMainID IN(SELECT PamainID FROM #t4)
			GROUP BY ProvinceID
		) b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDateMonth

		--清空临时表 #TmpIntention
		TRUNCATE TABLE #TmpIntention
		--得到未查看的账号信息
		INSERT INTO #TmpIntention SELECT * FROM #IntentionMonth
		DELETE FROM #TmpIntention WHERE PaMainID IN (Select PaMainID FROM #IntentionMonth WHERE ReplyDate BETWEEN @ReportBeginDay AND @ReportEndDay)

		--收到应聘邀请且未查看账号数量 月报
		UPDATE a SET a.IntentionNoViewAccount = b.cnt 
		FROM Personreport a ,(
			SELECT COUNT(DISTINCT PaMainID) cnt,ProvinceID FROM #TmpIntention	
			WHERE (ReplyDate IS NULL )
			AND PaMainID IN(SELECT PamainID FROM #t4)
			GROUP BY ProvinceID
		) b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDateMonth
	
		--收到应聘邀请且已查看的条数 月报
		UPDATE a SET a.IntentionViewCount=b.cnt 
		FROM Personreport a ,(
			SELECT COUNT(PaMainID) cnt,ProvinceID FROM #IntentionMonth	
			WHERE (ReplyDate BETWEEN @ReportBeginMonth AND @ReportEndMonth)
			AND PaMainID IN(SELECT PamainID FROM #t4)
			GROUP BY ProvinceID
		) b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDateMonth

		--收到应聘邀请且未查看的条数 月报
		UPDATE a SET a.IntentionNoViewCount=b.cnt 
		FROM Personreport a ,(
			SELECT COUNT(PaMainID) cnt,ProvinceID FROM #IntentionMonth	
			WHERE (ReplyDate IS NULL )
			AND PaMainID IN(SELECT PamainID FROM #t4)
			GROUP BY ProvinceID
		) b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDateMonth
		
		--刷新简历的账号数量 @RefreshAccount 月报
		UPDATE a SET a.RefreshAccount=b.cnt 
		FROM Personreport a ,(
			SELECT COUNT(DISTINCT PaMainID) cnt,ProvinceID FROM #RefreshMonth
			WHERE PaMainID IN ( SELECT PamainID FROM #t4 )
			GROUP BY ProvinceID
		) b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDateMonth

		--刷新简历的次数 月报
		UPDATE a SET a.RefreshCount=b.cnt 
		FROM Personreport a ,(
			SELECT COUNT(PaMainID) cnt,ProvinceID FROM #RefreshMonth
			WHERE PaMainID IN ( SELECT PamainID FROM #t4)
			GROUP BY ProvinceID
		) b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDateMonth

		--临时表赋值
		INSERT INTO #OtherMonth SELECT * FROM #t4
		DELETE FROM #OtherMonth 
		WHERE PaMainID IN ( SELECT PamainID FROM #InterviewMonth)
		OR PaMainID IN ( SELECT PamainID FROM #MessageMonth)
		OR PaMainID IN ( SELECT PamainID FROM #FavorateMonth)
		OR PaMainID IN ( SELECT PamainID FROM #ApplyMonth)
		OR PaMainID IN ( SELECT PamainID FROM #IntentionMonth)
		OR PaMainID IN ( SELECT PamainID FROM #RefreshMonth)

		--其他账号数量、登录次数 月报
		UPDATE a SET OtherLoginAccount = b.cnt
		FROM Personreport a ,(
			SELECT COUNT(DISTINCT PaMainID) cnt,ProvinceID FROM #OtherMonth
			GROUP BY ProvinceID
		) b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDateMonth
		
		UPDATE a SET OtherLoginCount = b.cnt
		FROM Personreport a ,(
			SELECT COUNT(PaMainID) cnt,ProvinceID FROM #OtherMonth
			GROUP BY ProvinceID
		) b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDateMonth

		--频次 月报 begin-------------------------------
		INSERT INTO #RateMonth
		SELECT ProvinceID, Rate, Count(1) Cnt FROM (
			SELECT PamainID, ProvinceID, COUNT(1) Rate 
			FROM #t4 
			GROUP BY PamainID, ProvinceID
		) a 
		GROUP BY ProvinceId, Rate

		UPDATE a SET Rate1 = b.cnt
		FROM Personreport a ,#RateMonth b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDateMonth AND b.RateTmp=1

		UPDATE a SET Rate2 = b.cnt
		FROM Personreport a ,#RateMonth b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDateMonth AND b.RateTmp=2

		UPDATE a SET Rate3 = b.cnt
		FROM Personreport a ,#RateMonth b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDateMonth AND b.RateTmp=3

		UPDATE a SET Rate4 = b.cnt
		FROM Personreport a ,#RateMonth b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDateMonth AND b.RateTmp=4

		UPDATE a SET Rate5 = b.cnt
		FROM Personreport a ,#RateMonth b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDateMonth AND b.RateTmp=5

		UPDATE a SET Rate6 = b.cnt
		FROM Personreport a ,#RateMonth b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDateMonth AND b.RateTmp=6

		UPDATE a SET Rate7 = b.cnt
		FROM Personreport a ,#RateMonth b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDateMonth AND b.RateTmp=7

		UPDATE a SET Rate8 = b.cnt
		FROM Personreport a ,#RateMonth b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDateMonth AND b.RateTmp=8

		UPDATE a SET Rate9 = b.cnt
		FROM Personreport a ,#RateMonth b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDateMonth AND b.RateTmp BETWEEN 9 AND 14

		UPDATE a SET Rate15 = b.cnt
		FROM Personreport a ,#RateMonth b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDateMonth AND b.RateTmp BETWEEN 15 AND 25

		UPDATE a SET Rate15 = b.cnt
		FROM Personreport a ,#RateMonth b 
		WHERE a.ProvinceID = b.ProvinceID 
		AND TypeID = @i AND ReportDate = @ReportDateMonth AND b.RateTmp >25

		--清空临时表
		TRUNCATE TABLE #T1
		TRUNCATE TABLE #T2
		TRUNCATE TABLE #T3
		TRUNCATE TABLE #T4
		TRUNCATE TABLE #Other
		TRUNCATE TABLE #OtherMonth
		TRUNCATE TABLE #Rate
		TRUNCATE TABLE #RateMonth
		TRUNCATE TABLE #TmpInterview
		TRUNCATE TABLE #TmpIntention
		SET @i = @i + 1
	END
	DROP TABLE #Interview
	DROP TABLE #Message
	DROP TABLE #Favorate
	DROP TABLE #Apply
	DROP TABLE #Intention
	DROP TABLE #Refresh
	DROP TABLE #InterviewMonth
	DROP TABLE #MessageMonth
	DROP TABLE #FavorateMonth
	DROP TABLE #ApplyMonth
	DROP TABLE #IntentionMonth
	DROP TABLE #RefreshMonth
	DROP TABLE #Other
	DROP TABLE #OtherMonth
	DROP TABLE #Rate
	DROP TABLE #RateMonth
END














GO
/****** Object:  StoredProcedure [dbo].[ProcPracticeJobSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.29
--创建人：Nick
--说明：获取最新实习职位
--#####################################################
CREATE PROCEDURE [dbo].[ProcPracticeJobSelect]
(
	@ProvinceID INT
)
AS
BEGIN TRY
	SELECT * 
	FROM PracticeJob WITH(NOLOCK) 
	WHERE ProvinceId = @ProvinceID 
	ORDER BY RowId
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[procPreColdcustomerSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--peter 2018-1-26
CREATE PROCEDURE [dbo].[procPreColdcustomerSelect]
(
	@isSpread INT
)
AS
SET NOCOUNT ON
BEGIN 
	CREATE TABLE #t
	(
		Id INT IDENTITY(1, 1),
		sourceType INT,
		Total INT,--总数
		AllocateNumber INT,--已分配数量
		WaitAllocateNumber INT,--待分配数量
		LostNumber INT,--被抢注数量
		TodayTotal INT,--今日采集总数
		TodayAllocateNumber INT --今日已分配数量
	)
	 
	CREATE TABLE #t1
	(
		Id INT IDENTITY(1, 1),
		ManagerUserId INT, 
		zhilianNumber INT,
		wyNumber INT,
		dazhongNumber INT,
		ganjiNumber INT,
		xinshijiNumber INT,
		kongziNumber INT,
		yancaiNumber INT
	)
	 
	CREATE TABLE #t2
	(
		Id INT IDENTITY(1, 1),
		ManagerUserId INT, 
		zhilianNumber INT,
		wyNumber INT,
		dazhongNumber INT,
		ganjiNumber INT,
		xinshijiNumber INT,
		kongziNumber INT,
		yancaiNumber INT
	)
	
	INSERT INTO #t(sourceType,Total,AllocateNumber,WaitAllocateNumber,LostNumber,TodayTotal,TodayAllocateNumber)
	SELECT sourceType,
	SUM(case WHEN [state]!=2 THEN 1 ELSE 0 END),
	SUM(case WHEN [state]=1 THEN 1 ELSE 0 END),
	SUM(case  WHEN [state]=0 THEN 1 ELSE 0 END),
	SUM(case WHEN [state]=2 THEN 1 ELSE 0 END),
	SUM(case WHEN (adddate>Convert(dateTime,Convert(char(10),getdate(),120),120) AND [state]!=2) THEN 1 ELSE 0 END),
	SUM(case WHEN (adddate>Convert(dateTime,Convert(char(10),getdate(),120),120) AND [state]=1 )THEN 1 ELSE 0 END) 
	FROM preColdCustomer  
	WHERE ISNULL(isSpread,0) = @isSpread
	GROUP BY sourceType
	
	IF @isSpread = 0
	BEGIN 
		INSERT INTO #t1(ManagerUserId)
		select id from manageruser where status IN (1,2) AND deptid=42
	END
	ELSE
	BEGIN
		INSERT INTO #t1(ManagerUserId)
		select id from manageruser where status=2 AND deptid=15
	END
	UPDATE #t1
	SET zhilianNumber=(SELECT sum(AllocateNumber) FROM ColdCustomerAllocateLog WHERE ManagerUserid=#t1.ManagerUserid AND sourceType=1),
	wyNumber=(SELECT sum(AllocateNumber) FROM ColdCustomerAllocateLog WHERE ManagerUserid=#t1.ManagerUserid AND sourceType=2),
	dazhongNumber=(SELECT sum(AllocateNumber) FROM ColdCustomerAllocateLog WHERE ManagerUserid=#t1.ManagerUserid AND sourceType=3),
	ganjiNumber=(SELECT sum(AllocateNumber) FROM ColdCustomerAllocateLog WHERE ManagerUserid=#t1.ManagerUserid AND sourceType=4),
	xinshijiNumber=(SELECT sum(AllocateNumber) FROM ColdCustomerAllocateLog WHERE ManagerUserid=#t1.ManagerUserid AND sourceType=5),
	kongziNumber=(SELECT sum(AllocateNumber) FROM ColdCustomerAllocateLog WHERE ManagerUserid=#t1.ManagerUserid AND sourceType=6),
	yancaiNumber=(SELECT sum(AllocateNumber) FROM ColdCustomerAllocateLog WHERE ManagerUserid=#t1.ManagerUserid AND sourceType=7)
	
	IF @isSpread = 0
	BEGIN 
		INSERT INTO #t2(ManagerUserId)
		select id from manageruser where status IN (1,2) AND deptid=42
	END
	ELSE
	BEGIN
		INSERT INTO #t2(ManagerUserId)
		select id from manageruser where status=2 AND deptid=15
	END
	
	UPDATE #t2
	SET zhilianNumber=(SELECT sum(AllocateNumber) FROM ColdCustomerAllocateLog WHERE ManagerUserid=#t2.ManagerUserid AND sourceType=1 AND addDate>Convert(dateTime,Convert(char(10),getdate(),120),120)),
	wyNumber=(SELECT sum(AllocateNumber) FROM ColdCustomerAllocateLog WHERE ManagerUserid=#t2.ManagerUserid AND sourceType=2 AND addDate>Convert(dateTime,Convert(char(10),getdate(),120),120)),
	dazhongNumber=(SELECT sum(AllocateNumber) FROM ColdCustomerAllocateLog WHERE ManagerUserid=#t2.ManagerUserid AND sourceType=3 AND addDate>Convert(dateTime,Convert(char(10),getdate(),120),120)),
	ganjiNumber=(SELECT sum(AllocateNumber) FROM ColdCustomerAllocateLog WHERE ManagerUserid=#t2.ManagerUserid AND sourceType=4 AND addDate>Convert(dateTime,Convert(char(10),getdate(),120),120)),
	xinshijiNumber=(SELECT sum(AllocateNumber) FROM ColdCustomerAllocateLog WHERE ManagerUserid=#t2.ManagerUserid AND sourceType=5 AND addDate>Convert(dateTime,Convert(char(10),getdate(),120),120)),
	kongziNumber=(SELECT sum(AllocateNumber) FROM ColdCustomerAllocateLog WHERE ManagerUserid=#t2.ManagerUserid AND sourceType=6 AND addDate>Convert(dateTime,Convert(char(10),getdate(),120) ,120)),
	yancaiNumber=(SELECT sum(AllocateNumber) FROM ColdCustomerAllocateLog WHERE ManagerUserid=#t2.ManagerUserid AND sourceType=7 AND addDate>Convert(dateTime,Convert(char(10),getdate(),120),120))
	 
	SELECT * FROM #t 
	SELECT * FROM #t1
	SELECT * FROM #t2
END
SET NOCOUNT OFF
GO
/****** Object:  StoredProcedure [dbo].[procProvinceSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.03
--创建人：Nick
--说明：获取省份信息
--#####################################################
CREATE PROCEDURE [dbo].[procProvinceSelect]
AS
BEGIN TRY
	Select *, (
		SELECT InternalIp 
		FROM dcSubSite WITH(NOLOCK)
		WHERE dcSubSite.ID = dcProvince.ID) InternalIp,
		(	SELECT EmailUser 
			FROM dcSubSite WITH(NOLOCK) 
			WHERE dcSubSite.ID = dcProvince.ID
		) EmailUser
	From dcProvince WITH(NOLOCK) 
	ORDER BY ID
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[ProcPtGiftLogInsert]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--sean 2014-5-12
CREATE PROCEDURE [dbo].[ProcPtGiftLogInsert]
(
	@AppointId INT,
	@Bi INT,
	@Ei INT,
	@Gift VARCHAR(40)
)
AS
BEGIN
	IF EXISTS(SELECT 'x' FROM Marketdb..ptGiftLog WHERE ptWorkAppointId = @AppointId AND LookDate > '2010-1-1')
		RETURN

	DECLARE @I INT
	DECLARE @t AS TABLE(Id INT)
	SELECT @I = @Bi

	WHILE @I <= @Ei
	BEGIN
		INSERT @t SELECT @i
		SET @i = @i + 1
	END
	DELETE Marketdb..ptGiftLog WHERE ptWorkAppointId = @AppointId
	INSERT Marketdb..ptGiftLog SELECT @AppointId, NULL, 0, Id, NULL, NULL, NULL, NULL FROM @t ORDER BY NEWID()
	------------------------------------
	DECLARE @Sql VARCHAR(MAX), @Gt VARCHAR(10), @GN VARCHAR(10)
	DECLARE @t1 AS TABLE(ID INT IDENTITY(1, 1), OneType VARCHAR(10), HasDone Bit)
 	INSERT @t1(OneType, HasDone)
	SELECT a, 0 FROM MainDb.dbo.FnSplit(@Gift, ';')

	WHILE EXISTS(SELECT 'x' FROM @t1 WHERE HasDone = 0)
	BEGIN
		SELECT TOP 1 @I = Id, @Sql = OneType FROM @t1 WHERE HasDone = 0
		SELECT @Gt = LEFT(@Sql, CHARINDEX(',', @Sql) - 1),
			@Gn = RIGHT(@Sql, LEN(@SQL) - CHARINDEX(',', @Sql))
		UPDATE @t1 SET HasDone = 1 WHERE ID = @i
		SET @Sql = 'UPDATE MarketDb..ptGiftLog SET ptGiftTypeId = ' + @Gt + ' WHERE ID IN(SELECT TOP ' + @Gn + ' ID FROM MarketDb..ptGiftLog
		WHERE ptWorkAppointId = ' + LTRIM(STR(@AppointId)) + ' AND ptGiftTypeId = 0 ORDER BY NEWID())'
		--PRINT @SQL		
		EXEC(@SQL)		
	END
END










GO
/****** Object:  StoredProcedure [dbo].[procPtPutInCountUpdate]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[procPtPutInCountUpdate]
(
	@ptPutInPlaceID INT,
	@ptWorkAppointID INT,
	@CurrentNumber INT,
	@Type TINYINT
)
AS
BEGIN
	DECLARE @OldNumber INT
	IF @Type = 0
	BEGIN
		SELECT @OldNumber = COUNT(*) FROM marketdb..ptPutIn WHERE ptPutInPlaceID = @ptPutInPlaceID
		DELETE FROM marketdb..ptPutIn WHERE ptPutInPlaceID = @ptPutInPlaceID
	END
	ELSE
	BEGIN
		SELECT @OldNumber = COUNT(*) FROM marketdb..ptPutInCheck WHERE ptPutInPlaceCheckID = @ptPutInPlaceID
		DELETE FROM marketdb..ptPutInCheck WHERE ptPutInPlaceCheckID = @ptPutInPlaceID
	END
	UPDATE marketdb..ptWorkAppoint SET CompleteNumber = ISNULL(CompleteNumber,0) - @OldNumber + @CurrentNumber WHERE ID = @ptWorkAppointID
	UPDATE marketdb..ptWorkAppoint SET DeliverySignDate = GETDATE() WHERE ID = @ptWorkAppointID AND DeliverySignDate IS NULL
END









GO
/****** Object:  StoredProcedure [dbo].[procPtPutInPlaceCheckSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[procPtPutInPlaceCheckSelect]
(
	@ptWorkAppointID INT,
    @CheckStatus TINYINT,
	@KeyWord NVARCHAR(20),
	@Lng DECIMAL(8,5),
	@Lat DECIMAL(8,5)
)
AS
BEGIN
	DECLARE @SQL VARCHAR(2000)
	SET @SQL = '
	SELECT
		a.ID,
		a.ptPutInPlaceID,
		b.PlaceName,
		b.HouseNumber,
		(SELECT COUNT(*) FROM marketdb..ptPutInCheck WHERE marketdb..ptPutInCheck.ptPutInPlaceCheckID=a.ID) SurvivingNumber,
		b.PutInNumber
	FROM
		marketdb..ptPutInPlaceCheck a,
		marketdb..ptPutInPlace b
	WHERE a.ptPutInPlaceID = b.ID AND a.ptWorkAppointID=' + CONVERT(VARCHAR,@ptWorkAppointID)
	IF @CheckStatus = '1'
		SET @SQL = @SQL + ' AND a.PhotoFile IS NULL'
	IF LEN(@KeyWord) > 0
		SET @SQL = @SQL + ' AND (b.PlaceName LIKE ''%' + @KeyWord + '%'' OR b.HouseNumber LIKE ''%' + @KeyWord + '%'')'
	IF @Lng > 0 AND @Lat > 0
	BEGIN
		DECLARE @Degree AS DECIMAL(8,5),@LBLng AS DECIMAL(8,5),@LBLat AS DECIMAL(8,5),
		@RTLng AS DECIMAL(8,5),@RTLat AS DECIMAL(8,5)
		SET @Degree = 200 / 100000.0;

		SET @LBLng = @Lng - @Degree
		SET @LBLat = @Lat - @Degree
		SET @RTLng = @Lng + @Degree
		SET @RTLat = @Lat + @Degree
		SET @SQL = @SQL + '
			AND b.Lng BETWEEN ' + CONVERT(VARCHAR,@LBLng) + ' AND ' + CONVERT(VARCHAR,@RTLng) + '
			AND b.Lat BETWEEN ' + CONVERT(VARCHAR,@LBLat) + ' AND ' + CONVERT(VARCHAR,@RTLat) + '
			AND (b.Lng-' + CONVERT(VARCHAR,@Lng) + ')*(b.Lng-' + CONVERT(VARCHAR,@Lng) + ')+
			(b.Lat-' + CONVERT(VARCHAR,@Lat) + ')*(b.Lat-' + CONVERT(VARCHAR,@Lat) + ')<' + CONVERT(VARCHAR,@Degree*@Degree)
	END
	--PRINT @SQL
	EXEC(@SQL)
END









GO
/****** Object:  StoredProcedure [dbo].[procPtPutInPlaceInsert]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[procPtPutInPlaceInsert]
(
	@ptWorkAppointID INT,
	@HouseNumber NVARCHAR(50),
	@PlaceName NVARCHAR(50),
	@Lng DECIMAL(8,5),
	@Lat DECIMAL(8,5),
	@PutInNumber INT
)
AS
BEGIN TRY
	DECLARE @DeliveryQuantity INT, @HasSentNumber INT
	SELECT @DeliveryQuantity = DeliveryQuantity FROM marketdb..ptWorkAppoint WHERE ID = @ptWorkAppointID
	SELECT @HasSentNumber = SUM(PutInNumber) FROM marketdb..ptPutInPlace WHERE ptWorkAppointID = @ptWorkAppointID
	IF @DeliveryQuantity <= @HasSentNumber
		RETURN -1 --未加上此次投放已超标
	IF @DeliveryQuantity < @HasSentNumber + @PutInNumber
		RETURN -2 --加上此次投放超标

	DECLARE @CityName NVARCHAR(20),@dcRegionID VARCHAR(6)
	SET @dcRegionID = ''
	IF CHARINDEX('市',@HouseNumber) > 0
		SET @CityName = SUBSTRING(@HouseNumber,0,CHARINDEX('市',@HouseNumber))
	ELSE IF CHARINDEX('区',@HouseNumber) > 0
		SET @CityName = SUBSTRING(@HouseNumber,0,CHARINDEX('区',@HouseNumber))
	ELSE
		SET @CityName = ''

	IF LEN(@CityName) > 0
		SELECT @dcRegionID = ID FROM dcRegion WHERE FullName LIKE '%' + @CityName + '%' AND LEN(ID) = 4

	INSERT INTO marketdb..ptPutInPlace(dcRegionID, HouseNumber, PlaceName, Lng, Lat, PutInNumber, ptWorkAppointID, CheckStatus) VALUES
		(@dcRegionID, @HouseNumber, @PlaceName, @Lng, @Lat, @PutInNumber, @ptWorkAppointID, 0)
	
	RETURN @@IDENTITY
END TRY
BEGIN CATCH
	RETURN 0
END CATCH









GO
/****** Object:  StoredProcedure [dbo].[procPtPutInPlaceUpdate]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[procPtPutInPlaceUpdate]
(
	@ID INT,
	@ptWorkAppointID INT,
	@HouseNumber NVARCHAR(50),
	@PlaceName NVARCHAR(50),
	@PutInNumber INT
)
AS
BEGIN TRY
	DECLARE @DeliveryQuantity INT, @HasSentNumber INT
	IF NOT EXISTS(SELECT 'X' FROM marketdb..ptPutInPlace WHERE ID = @ID AND ptWorkAppointID = @ptWorkAppointID)
		RETURN -3 --没有此条记录

	SELECT @DeliveryQuantity = DeliveryQuantity FROM marketdb..ptWorkAppoint WHERE ID = @ptWorkAppointID
	SELECT @HasSentNumber = SUM(PutInNumber) FROM marketdb..ptPutInPlace WHERE ptWorkAppointID = @ptWorkAppointID AND ID <> @ID
	IF @DeliveryQuantity < @HasSentNumber + @PutInNumber
		RETURN -2 --加上此次投放超标

	UPDATE marketdb..ptPutInPlace SET
		HouseNumber = @HouseNumber,
		PlaceName = @PlaceName,
		PutInNumber = @PutInNumber
	WHERE ID = @ID
	
	RETURN 1
END TRY
BEGIN CATCH
	RETURN 0
END CATCH









GO
/****** Object:  StoredProcedure [dbo].[ProcPtUserGiftRestSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		123
-- Create date: 2014-5-10
-- Description:	查询兼职剩余礼品概况
-- =============================================
CREATE PROCEDURE [dbo].[ProcPtUserGiftRestSelect] 
(
	@ptUserName NVARCHAR(5)
)
AS
BEGIN
	DECLARE @sql VARCHAR(2000)
	SET @sql = 'SELECT a.ptUserID, b.Name'
	SELECT @sql = @sql + ', LTRIM(STR(SUM(CASE ptGiftTypeId WHEN ' + LTRIM(STR(ptGiftTypeId)) + 
		' THEN RemainNumber ELSE 0 END))) + ''('' + LTRIM(STR(SUM(CASE ptGiftTypeId WHEN ' + LTRIM(STR(ptGiftTypeId)) + 
		' THEN RemainNumber ELSE 0 END))) + '')'' AS [' + (SELECT GiftName FROM MarketDb..ptGiftType WHERE Id = ptGiftTypeId) + ']
	'
	FROM (SELECT distinct ptGiftTypeId FROM Marketdb..ptUserGift WHERE RemainNumber > 0) AS a

	SET @sql = @sql + 'FROM Marketdb..ptUserGift a, MarketDb..ptUser b
WHERE a.ptUserId = b.Id 
AND RemainNumber > 0'

	IF @ptUserName > ''
	BEGIN
		SET @sql = @sql + '
AND ptUserID IN (SELECT ID FROM MArketDb..ptUser WHERE Name =''' + LTRIM(RTRIM(@ptUserName)) + ''')'
	END

	SET @sql = @sql + '
GROUP BY a.ptUserID, b.Name'
	EXEC(@sql)
	--PRINT @SQL
END










GO
/****** Object:  StoredProcedure [dbo].[procQlrcGovByHomepageSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[procQlrcGovByHomepageSelect]
(
	@ProvinceID SMALLINT
)
AS
BEGIN
	--IF @ProvinceID IN(1201, 1207, 1301, 1302, 1401, 2201, 3101, 3301, 3501, 3601, 4001, 4101, 4201, 6101, 6201, 7001, 7002, 7101, 7201, 8001, 8301)
	IF @ProvinceID IN(SELECT ID FROM dcSubSite WHERE IsMainSite = 0)
		SET @ProvinceId = LEFT(@ProvinceId, 2)

	SELECT TOP 1 ImageFile, alt 
	FROM fpHomePageImage WITH(NOLOCK)
	WHERE ImageType = 4
	AND dcProvinceID = @ProvinceID
	ORDER BY AddDate DESC

	SELECT TOP 15 id newIds ,PreID id, title, announcedate ,content,type,refreshdate,versionid
	FROM SearchDb..HpQlrcGovDay WITH(NOLOCK)
	WHERE versionid = @ProvinceID
	ORDER BY newIds
END

GO
/****** Object:  StoredProcedure [dbo].[procQlrcNews5ByConditionSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.10
--创建人：Nick
--说明：根据省份获取政府招考信息
--#####################################################
CREATE PROCEDURE [dbo].[procQlrcNews5ByConditionSelect]
(
	@Condition VARCHAR(MAX)
)
AS
BEGIN
	DECLARE @SQL VARCHAR(MAX)
	SET @SQL = '
	SELECT top 5 ID, Title, RefreshDate, Author 
	FROM QlrcNews WITH(NOLOCK) WHERE (
		EXISTS(
			SELECT ''x'' FROM fnSplit(DetailType, '', '') b, dcNewsType c WITH(NOLOCK) 
			WHERE b.a=c.ID 
			AND c.Category=1
		) 
		OR DetailType IS NULL
	) 
	AND NewsType = 2 
	AND DetailType like ''%, 2, %'' '+@Condition+'
	ORDER BY RefreshDate DESC '
	PRINT (@SQL)
	EXEC (@SQL)
END


GO
/****** Object:  StoredProcedure [dbo].[procQlrcNews5ByProvinceIDSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.10
--创建人：Nick
--说明：根据省份获取政府招考信息
--#####################################################
CREATE PROCEDURE [dbo].[procQlrcNews5ByProvinceIDSelect]
(
	@ProvinceID INT
)
AS
BEGIN
	IF @ProvinceID = 32
		SELECT top 5 ID, Title, RefreshDate, Author 
		FROM QlrcNews WITH(NOLOCK) WHERE (
			EXISTS(
				SELECT 'x' FROM fnSplit(DetailType, ',') b, dcNewsType c WITH(NOLOCK) 
				WHERE b.a=c.ID 
				AND c.Category=1
			) 
			OR DetailType IS NULL
		) 
		AND (VersionID=@ProvinceID OR VersionID=0) 
		AND NewsType = 2 
		AND DetailType like '%,2,%' 
		ORDER BY RefreshDate DESC
	ELSE
		SELECT top 5 ID, Title, RefreshDate, Author 
		FROM QlrcNews WITH(NOLOCK) WHERE (
			EXISTS(
				SELECT 'x' FROM fnSplit(DetailType, ',') b, dcNewsType c WITH(NOLOCK) 
				WHERE b.a=c.ID 
				AND c.Category=1
			) 
			OR DetailType IS NULL
		) 
		AND VersionID = @ProvinceID
		AND NewsType = 2 
		AND DetailType like '%,2,%' 
		ORDER BY RefreshDate DESC
END


GO
/****** Object:  StoredProcedure [dbo].[ProcQlrcNewsBy51RcRebuild]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ProcQlrcNewsBy51RcRebuild]
AS
BEGIN
	IF NOT EXISTS(SELECT 'x' FROM QlrcNews WITH(NOLOCK) WHERE RefreshDate > DATEADD(MI, -5, GETDATE()))
		RETURN
 
	DECLARE @q AS TABLE(
		Id int,
		title nvarchar(60),
		announcedate smalldatetime,
		content varchar(max),
		type smallint,
		refreshdate smalldatetime,
		versionid INT
	)

	DECLARE @t AS TABLE(title nvarchar(60), refreshdate smalldatetime)
	INSERT INTO @t(title, refreshdate)
	SELECT DISTINCT TOP 20 title, refreshdate
	FROM QlrcNews WITH(NOLOCK)
	WHERE NewsType = 2
	AND RefreshDate > GETDATE() - 2
	ORDER BY refreshdate DESC

	INSERT INTO @q(Title, Refreshdate)
	SELECT title, Max(RefreshDate) FROM @t GROUP BY Title ORDER BY Max(RefreshDate) DESC

	UPDATE a
	SET ID = (SELECT MAX(ID) FROM QlrcNews WITH(NOLOCK) WHERE QlrcNews.Title = a.Title)
	FROM @q a

	UPDATE a
	SET a.announcedate = b.announcedate,
		a.content = b.Content,
		a.type = b.Type,
		a.versionid = b.versionid
	FROM @q a, QlrcNews b WITH(NOLOCK)
	WHERE a.Id = b.Id

	TRUNCATE TABLE SearchDb..HpQlrcNews51Rc

	INSERT INTO SearchDb..HpQlrcNews51Rc
	SELECT TOP 15 id, title, announcedate ,content,type,refreshdate,versionid
	FROM @q
	ORDER BY refreshdate DESC
END














GO
/****** Object:  StoredProcedure [dbo].[procQlrcnewsBy51RCSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--创建人 Lambo	
--20101009
--用于首页查询固定位置右边的职场新闻
--2012-10-22 sean remove @provinceid=0 to procQlrcnewsBy51RCSelect
CREATE PROCEDURE [dbo].[procQlrcnewsBy51RCSelect]
AS
BEGIN
	SELECT TOP 0 null ImageFile, null alt 

	SELECT * FROM SearchDb..hpQlrcNews51Rc
END














GO
/****** Object:  StoredProcedure [dbo].[procQlrcNewsByCountryIDSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.5
--创建人：NICK
--说明：查询县级市的新闻，读取省份的新闻，优先县级市
--#####################################################
CREATE PROCEDURE [dbo].[procQlrcNewsByCountryIDSelect]
(
	@CountryID VARCHAR(6)
)
AS
BEGIN
	IF LEN(@CountryID) = 6
		SELECT TOP 400 Id, Title, RefreshDate, Author, Type, Content 
		FROM QlrcNews WITH(NOLOCK)
		WHERE VersionId = @CountryID
		AND NewsType = 2 
		ORDER BY Id DESC
	ELSE
		SELECT TOP 400 Id, Title, RefreshDate, Author, Type, Content 
		FROM QlrcNews WITH(NOLOCK)
		WHERE VersionId LIKE @CountryID + '%'
		AND NewsType = 2 
		ORDER BY CASE VersionId WHEN @CountryID THEN 0 ELSE 1 END,
			RefreshDate DESC
END


GO
/****** Object:  StoredProcedure [dbo].[procQlrcNewsByDetailTypeSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.10
--创建人：NICK
--说明：获取某类N条资讯
--#####################################################
CREATE PROCEDURE [dbo].[procQlrcNewsByDetailTypeSelect]
(
	@newsNumber INT,
	@detailType VARCHAR(10),
	@provinceID VARCHAR(6),
	@NewID INT
)
AS
BEGIN
	DECLARE @SQL VARCHAR(MAX)
	SET @SQL = '
	SELECT TOP '+CONVERT(VARCHAR(10),@newsNumber)+' *
	FROM qlrcNews WITH(NOLOCK)
	WHERE DetailType LIKE ''%,' + @detailType + ',%''
	AND VersionID = '+CONVERT(VARCHAR(10),@provinceID)
	
	IF @NewID <> 0
	BEGIN
		SET @SQL = @SQL + ' AND id<>' + CONVERT(VARCHAR(10),@NewID)
	END
	SET @SQL = @SQL + ' ORDER BY RefreshDate DESC '
	PRINT (@SQL)
	EXEC (@SQL)
END


GO
/****** Object:  StoredProcedure [dbo].[procQlrcnewsByHomepageSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--创建人 Lambo	
--20101009
--用于首页查询固定位置右边的职场新闻
--20121022 sean remove @provinceid=0 to [procQlrcnewsBy51rcSelect]
--20180301 Carl 就业大数据、媒体动态与就业咨询合并
--20180308 Carl
--20180524 harry 164jane要求 ql固定显示1篇微职场3篇动态
CREATE PROCEDURE [dbo].[procQlrcnewsByHomepageSelect]
(
	@ProvinceID SMALLINT
)
AS
SET NOCOUNT ON
BEGIN
	DECLARE @t AS TABLE(
		NewIds INT NOT NULL,
		Id INT NOT NULL,
		Title NVARCHAR(60) NOT NULL,
		AnnounceDate SMALLDATETIME NOT NULL,
		[Content] VARCHAR(MAX) NOT NULL,
		Url VARCHAR(2000), --新增的
		[Type] SMALLINT NOT NULL,
		RefreshDate SMALLDATETIME NOT NULL,
		Seq INT IDENTITY(1, 1)		
	)

	SELECT TOP 0 '' ImageFile, '' alt 

	IF @ProvinceID=32
	BEGIN
		/*INSERT INTO @t
		SELECT *
		FROM (SELECT DISTINCT TOP 14 Id NewIds, PreID Id, Title, Announcedate, [Content], '' Url,[Type], RefreshDate 
			FROM SearchDb..HpQlrcNewsDay WITH(NOLOCK)
			WHERE dcSubSiteId = @ProvinceID
			ORDER BY newIds) t1  
		UNION 
		SELECT *
		FROM (SELECT TOP 1 Id NewIds, Id, Title, Announcedate, [Content], '' Url,3 [Type], Refreshdate 
			FROM MainDb..NewsAnalysis WITH(NOLOCK)
			ORDER BY Id DESC) t2
		UNION
		SELECT *
		FROM (SELECT TOP 1 Id NewIds, Id, Title, AddDate AnnounceDate, Brief [Content],Url, 4 [Type], AddDate RefreshDate 
			FROM MarketDb..MarketMedia a, MarketDb..MarketProvince b
			WHERE a.ID = b.MarketID
			AND b.Type = 1 AND a.MediaType = 1
			AND (b.ProvinceID = 0 OR b.ProvinceID = @ProvinceID)
			ORDER BY a.Id DESC) t3
		*/
		INSERT INTO @t
		SELECT DISTINCT TOP 1 Id NewIds, PreID Id, Title, Announcedate, [Content], '' Url,[Type], RefreshDate 
			FROM SearchDb..HpQlrcNewsDay WITH(NOLOCK)
			WHERE dcSubSiteId = @ProvinceID
			ORDER BY newIds

		INSERT INTO @t
		SELECT TOP 3 Id NewIds, Id, Title, Announcedate, [Content], '' Url,3 [Type], Refreshdate 
			FROM MainDb..NewsAnalysis WITH(NOLOCK)
			ORDER BY Id DESC

		INSERT INTO @t
		SELECT TOP 1 Id NewIds, Id, Title, AddDate AnnounceDate, Brief [Content],Url, 4 [Type], AddDate RefreshDate 
			FROM MarketDb..MarketMedia a, MarketDb..MarketProvince b
			WHERE a.ID = b.MarketID
			AND b.Type = 1 AND a.MediaType = 1
			AND (b.ProvinceID = 0 OR b.ProvinceID = @ProvinceID)
			ORDER BY a.Id DESC
		
	END
	ELSE
	BEGIN
		INSERT INTO @t
		SELECT DISTINCT TOP 14 Id NewIds, PreID Id, Title, Announcedate, [Content], '' Url,[Type], RefreshDate
		FROM SearchDb..HpQlrcNewsDay WITH(NOLOCK)
		WHERE dcSubSiteId = @ProvinceID
		ORDER BY newIds
	END

	SELECT * FROM @t ORDER BY Announcedate DESC
END
SET NOCOUNT OFF



GO
/****** Object:  StoredProcedure [dbo].[procQlrcNewsByID51rcSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.10
--创建人：NICK
--说明：得到网站公告
--#####################################################
CREATE PROCEDURE [dbo].[procQlrcNewsByID51rcSelect]
(
	@ID INT
)
AS
BEGIN
	SELECT title, content, announcedate, author, ViewNumber_All, refreshdate, type
	FROM qlrcnews WITH(NOLOCK)
	WHERE newstype = 1
	AND Id = @ID
END


GO
/****** Object:  StoredProcedure [dbo].[procQlrcNewsByIDSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.5
--创建人：NICK
--说明：获取一行职场新闻
--#####################################################
CREATE PROCEDURE [dbo].[procQlrcNewsByIDSelect]
(
	@ID INT
)
AS
BEGIN
	SELECT id, Type, Title, newstype, Content, Announcedate, Author, Appendix, AppendixName,DetailType,
		Viewnumber_All, RefreshDate, Label, VersionID ,
		(SELECT TOP 1 NewsType FROM dcNewsType WITH(NOLOCK) WHERE QlrcNews.DetailType LIKE '%,' + LTRIM(Id) +',%') NewsDetailType,
		(SELECT TOP 1 ID FROM dcNewsType WITH(NOLOCK) WHERE QlrcNews.DetailType LIKE '%,' + LTRIM(Id) + ',%') NewsDetailID,
		(SELECT TOP 1 Category FROM dcNewsType WITH(NOLOCK) WHERE QlrcNews.DetailType LIKE '%,' + LTRIM(Id) + ',%') Category
	FROM QlrcNews WITH(NOLOCK)
	WHERE Id = @ID
END

GO
/****** Object:  StoredProcedure [dbo].[procQlrcNewsByIDUpdate]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.5
--创建人：NICK
--说明：记录职场新闻点击数
--#####################################################
CREATE PROCEDURE [dbo].[procQlrcNewsByIDUpdate]
(
	@ID INT,
	@IsWhite INT
)
AS
BEGIN
	DECLARE @SQL VARCHAR(MAX)
	SET @SQL = 'Update QlrcNews SET ViewNumber_All = ViewNumber_All + 1 '
	IF @IsWhite = 1
	BEGIN
		SET @SQL  = @SQL + ', ViewNumber = ViewNumber + 1'
	END
	SET @SQL  = @SQL + ' WHERE ID = '+CONVERT(VARCHAR(20),@ID)
	EXEC(@SQL)

	RETURN 1
END


GO
/****** Object:  StoredProcedure [dbo].[ProcQlrcNewsByNearSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ProcQlrcNewsByNearSelect]
(
	@CountryID VARCHAR(6),
	@ID INT
)
AS
SET NOCOUNT ON
BEGIN
	SELECT PageType, NearId, Id, NearTitle Title
	FROM ShortDb..QlrcNewsNear WITH(NOLOCK)
	WHERE ID = @Id

--	DECLARE @t AS TABLE(PageType INT, Id INT, Title NVARCHAR(100))
--	INSERT @t
--	SELECT TOP 1 1, Id, Title
--	FROM QlrcNews WITH(NOLOCK)
--	WHERE VersionId = @CountryID
--	AND NewsType = 2 
--	AND Id > @Id
--	ORDER BY Id
--
--	INSERT @t
--	SELECT TOP 1 2, Id, Title
--	FROM QlrcNews WITH(NOLOCK)
--	WHERE VersionId = @CountryID
--	AND NewsType = 2 
--	AND Id < @Id
--	ORDER BY Id DESC
--
--	SELECT * FROM @t ORDER BY Id
END

GO
/****** Object:  StoredProcedure [dbo].[procQlrcNewsByOther51rcSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.10
--创建人：NICK
--说明：得到其他网站公告
--#####################################################
CREATE PROCEDURE [dbo].[procQlrcNewsByOther51rcSelect]
AS
BEGIN
	SELECT TOP 200 * FROM QlrcNews WITH(NOLOCK) WHERE NewsType = 1 ORDER BY RefreshDate DESC
END


GO
/****** Object:  StoredProcedure [dbo].[procQlrcNewsByProvinceID51rcSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.10
--创建人：NICK
--说明：关注排行
--#####################################################
CREATE PROCEDURE [dbo].[procQlrcNewsByProvinceID51rcSelect]
(
    @ProvinceID INT
)
AS
BEGIN
    SELECT TOP 10 *
    FROM QlrcNews WITH(NOLOCK)
    WHERE RefreshDate > DateAdd(Month, -3, GETDATE())
    AND VersionID = @ProvinceID
    ORDER BY ViewNumber_All DESC
END
GO
/****** Object:  StoredProcedure [dbo].[procQlrcNewsByProvinceIDSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.5
--创建人：NICK
--说明：就业资讯
--#####################################################
CREATE PROCEDURE [dbo].[procQlrcNewsByProvinceIDSelect]
(
	@provinceID INT
)
AS
BEGIN
	SELECT TOP 7 a.ID, Title, content, RefreshDate,
	(
		SELECT TOP 1 NewsType 
		FROM dcNewsType WITH(NOLOCK)
		WHERE a.DetailType LIKE '%,'+Ltrim(str(id))+',%' 
		AND category=1
	) DetailType
	FROM qlrcnews a WITH(NOLOCK)
	where EXISTS(
		SELECT 'x' 
		FROM fnSplit(DetailType,',') b, dcNewsType c WITH(NOLOCK)
		WHERE b.a = c.id 
		AND c.category=1
	)
	AND VersionID=@provinceID
	AND type=1 
	ORDER BY ID DESC
END


GO
/****** Object:  StoredProcedure [dbo].[procQlrcNewsByTypeIDSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.5
--创建人：NICK
--说明：职场攻略
--#####################################################
CREATE PROCEDURE [dbo].[procQlrcNewsByTypeIDSelect]
(
	@ProvinceID INT
)
AS
BEGIN
	SELECT TOP 7 a.ID, Title, Content, RefreshDate
	FROM qlrcnews a WITH(NOLOCK)
	WHERE exists(
		SELECT 'x' FROM fnSplit(DetailType, ',') b, dcNewsType c WITH(NOLOCK)
		WHERE b.a = c.id 
		AND c.category=2
	)
	AND VersionID=@ProvinceID 
	AND type = 1
	ORDER BY id DESC
END


GO
/****** Object:  StoredProcedure [dbo].[procQlrcNewsByVersionIDSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.5
--创建人：NICK
--说明：根据类别和省份获取新闻
--#####################################################
CREATE PROCEDURE [dbo].[procQlrcNewsByVersionIDSelect]
(
	@ProvinceID INT,
	@Type VARCHAR(10)
)
AS
BEGIN
	SELECT TOP 8 ID,Title,RefreshDate 
	FROM qlrcNews WITH(NOLOCK) 
	WHERE DetailType LIKE '%,'+@Type+',%'  
	AND VersionID=@ProvinceID 
	ORDER BY RefreshDate DESC
END


GO
/****** Object:  StoredProcedure [dbo].[procQlrcNewsByVersionIdTop2Select]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.5
--创建人：NICK
--说明：获取新闻
--#####################################################
create PROCEDURE [dbo].[procQlrcNewsByVersionIdTop2Select]
(
	@VersionId INT
)
AS
BEGIN
	SELECT TOP 2 *
	FROM QlrcNews WITH(NOLOCK) 
	WHERE (
		EXISTS(
			SELECT 'x' 
			FROM fnSplit(DetailType, ',') b,
				dcNewsType c WITH(NOLOCK) 
			WHERE b.a = c.ID)
			OR DetailType IS NULL
		)
	AND VersionID = @VersionId
	AND NewsType = 2 
	AND DetailType NOT LIKE '%,2,%'
	ORDER BY RefreshDate DESC	
END


GO
/****** Object:  StoredProcedure [dbo].[ProcQlrcNewsExpertSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.28
--创建人：Nick
--说明：得到专家支招 
--#####################################################
CREATE PROCEDURE [dbo].[ProcQlrcNewsExpertSelect]
(
	@ProvinceID INT
)
AS
BEGIN TRY
	SELECT TOP 13 a.ID,Title
	FROM QlrcNews a WITH(NOLOCK)
	WHERE EXISTS(
		 SELECT 'x' FROM fnSplit(DetailType,',') b,dcNewsType c WITH(NOLOCK)
		 WHERE b.a = c.ID 
		 AND c.category=2
	)
	AND VersionID = @ProvinceID
	AND Type = 1
	And RefreshDate>DateAdd(Month,-1,GETDATE())
	ORDER BY ViewNumber DESC 
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[ProcQlrcNewsLinkSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.28
--创建人：John
--说明：获取职场新闻链接
--#####################################################
CREATE PROCEDURE [dbo].[ProcQlrcNewsLinkSelect]
AS
BEGIN TRY
	SELECT TOP 5000 '/news/' + CONVERT(VARCHAR, ID) + '.html' link 
	FROM QlrcNews WITH(NOLOCK) 
	WHERE NewsType = 2 
	  AND versionid = 0 
	  AND AnnounceDate > GETDATE()-7
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[procQlrcNewsListBy51rcSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.10
--创建人：NICK
--说明：根据类别和省份获取新闻
--#####################################################
CREATE PROCEDURE [dbo].[procQlrcNewsListBy51rcSelect]
AS
BEGIN
	SELECT ID,Title,Author,RefreshDate FROM qlrcNews WITH(NOLOCK) 
	WHERE VersionID=0 AND NewsType=2 
	ORDER BY RefreshDate DESC
END


GO
/****** Object:  StoredProcedure [dbo].[procQlrcNewsNumSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.5
--创建人：NICK
--说明：获取新闻
--#####################################################
CREATE PROCEDURE [dbo].[procQlrcNewsNumSelect]
(
	@Num INT
)
AS
BEGIN
	DECLARE @SQL VARCHAR(MAX)
	SET @SQL = 'SELECT TOP '+CONVERT(VARCHAR(10),@Num)+' * 
	FROM QlrcNews WITH(NOLOCK) 
	WHERE (EXISTS(SELECT ''x'' FROM fnSplit(DetailType,'','') b,
	dcNewsType c WITH(NOLOCK) WHERE b.a=c.ID ) OR DetailType IS NULL) AND 
	VersionID=0 AND NewsType = 2 AND DetailType NOT LIKE ''%,2,%''
	ORDER BY RefreshDate DESC' 
	EXEC(@SQL) 
END


GO
/****** Object:  StoredProcedure [dbo].[procQlrcnewsSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--创建人 Lambo
--时间 20101009
--用于网站首页查询网站公告
CREATE PROCEDURE [dbo].[procQlrcnewsSelect]
(
    @province_id SMALLINT
)
AS
BEGIN
    SELECT TOP 3 id, title, announcedate date, content, type, refreshdate
    FROM QlrcNews WITH(NOLOCK)
    WHERE (VersionId = @province_id OR VersionId = 0)
    AND NewsType = 1
    ORDER BY refreshdate DESC
    OPTION (KEEPFIXED PLAN)
END
GO
/****** Object:  StoredProcedure [dbo].[ProcQlrcNewsTop400Select]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ProcQlrcNewsTop400Select]
(
	@ProvinceID INT,
	@KeyWord NVARCHAR(100),
	@DetailType INT,
	@Type NVARCHAR(20)
)
AS
BEGIN
	IF (@DetailType <= 0)
		SET @DetailType = 0
	SET @keyWord = REPLACE(dbo.SafeSql(@keyWord), '''', '')
	IF (LEN(@keyWord) > 0)
	BEGIN
		DECLARE @Sql VARCHAR(MAX)
		SET @Sql = 'SELECT TOP 400 Id, Title, RefreshDate, Author, Type, Content
					FROM QlrcNews WITH(NOLOCK)
					WHERE VersionId = ' + LTRIM(STR(@ProvinceID)) + '
					AND NewsType = 2'
		IF (@Type = 'title')
			SET @Sql = @Sql + ' AND Title LIKE ''%' + @KeyWord + '%'''
		ELSE
		BEGIN
			DECLARE @t AS TABLE(ID INT IDENTITY(1, 1), k NVARCHAR(50))
			INSERT @t(k) SELECT a FROM dbo.FnSplit(@KeyWord, ' ')
			UPDATE @t SET k = REPLACE(k, ' ', '')
			UPDATE @t SET k = REPLACE(k, '''', '')
			DELETE @t WHERE ISNULL(k, '') = ''
			
			SELECT @Sql = @Sql + ' AND Id IN(SELECT [Key] FROM CONTAINSTABLE(QlrcNews, *, ''' + k + ''', 10000) AS KeyJob)'	
			FROM @t		
		END

		IF (@DetailType > 0)
			SET @Sql = @Sql + ' AND DetailType LIKE ''%,' + LTRIM(STR(@DetailType))  + ',%'''
		ELSE
			SET @Sql = @Sql + ' AND DetailType NOT LIKE ''%,2,%'''

		SET @Sql = @Sql + ' ORDER BY RefreshDate DESC'

		--PRINT @SQL 
		EXEC(@SQL)
	END		
	ELSE
	BEGIN
		SELECT Id, Title, RefreshDate, Author, Type
		FROM QlrcNewsTop400 WITH(NOLOCK)
		WHERE ProvinceId = @ProvinceID
		AND DetailType = @DetailType
		ORDER BY RowID
	END
END




GO
/****** Object:  StoredProcedure [dbo].[procQuotaLogUpdate]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--计划任务校正已经使用的配额量
--harry
--2017-12-8
CREATE PROCEDURE [dbo].[procQuotaLogUpdate]
AS
SET NOCOUNT ON
BEGIN
	create table #a
	(
	 id int,
	 caorderId INT,
	 caMainid INT,
	 download int
	)
	insert into #a(id,caorderId,caMainId)
	select id,caorderId,caMainId
	FROM  QuotaLog

	DECLARE @size INT,@id INT
	SET @id=0
	SELECT @size=count(1) from #a
	WHILE @size>0
	BEGIN
		SET @size=@size-1 
		SELECT TOP 1 @id =id FROM #a WHERE id> @id ORDER BY id  asc
		UPDATE #a
		set download=(select count(1) from  caactivelog where camainid=#a.caMainId AND caorderId= #a.caorderId)
		WHERE id= @id
	    
		UPDATE #a
		set download=ISNULL(download,0)+
		(select count(1) from  caactivelog 
			where camainid=#a.caMainId AND caorderId IN
			(select id from caorder 
				where  mainorderid= #a.caorderId AND isdeleted=0 AND ordertype in(8,9)  AND openDate   is NOT NULL
			)
		)
		 WHERE id= @id
	END
	UPDATE a
	SET a.remainQuota=(a.quota-b.download)
	FROM quotalog a, #a b
	WHERE a.id = b.id

	drop table #a
END
SET NOCOUNT OFF

GO
/****** Object:  StoredProcedure [dbo].[ProcRecommendedRecruitmentSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.29
--创建人：Nick
--说明：获取推荐招聘会内容
--#####################################################
CREATE PROCEDURE [dbo].[ProcRecommendedRecruitmentSelect]
(
	@ProvinceID INT
)
AS
BEGIN TRY
	SELECT TOP 10 a.ID,a.RecruitmentName 
	FROM Recruitment a,dcRegion b,RecruitmentPlace c,RecruitmentDept d 
	WHERE d.ID=a.RecruitmentDeptID 
	AND d.ID<>1767 
	AND b.ID=c.dcRegionID 
	AND a.RecruitmentPlaceId=c.id And c.dcRegionID LIKE ''+CONVERT(VARCHAR(4),@ProvinceID)+'%' 
	AND EndDate>GetDate() 
	AND a.IsPause=0 
	AND LEN(ManagerUserID)>0 
	ORDER BY orderby, a.EndDate
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[ProcRecruitByBaiduXmlSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ProcRecruitByBaiduXmlSelect]
(
	@ProvinceID INT
)
AS
insert into proclog select 'ProcRecruitByBaiduXmlSelect', @ProvinceId, GETDATE()
BEGIN
	DECLARE @pId VARCHAR(2)
	IF ISNULL(@ProvinceID, 0) = 0
		SET @Pid = ''
	ELSE
		SET @Pid = LTRIM(STR(@ProvinceId))

	Select a.ID, e.DeptName, a.RecruitmentName, a.EndDate, a.ModifyDate, a.BeginDate, a.Brief,
		c.PlaceName, c.Address, b.Description City, d.EmailSite, d.SubSiteName, OrderBy, MainId
	INTO #t
	From Recruitment a,
		dcRegion b,
		RecruitmentPlace c,
		dcSubSite d,
		RmDept e
	Where a.RecruitmentDeptId = e.Id
	AND Left(CityID, 2) = d.ID 
	AND b.ID = c.dcRegionID 
	AND a.RecruitmentPlaceId = c.id
	AND c.dcRegionID like @Pid + '%' 
	AND EndDate > GetDate() 
	AND RIGHT(CONVERT(VARCHAR(8), EndDate, 112), 4) <> '1231'
	AND a.ManagerUserId > 0 
	AND a.IsPause = 0
	AND a.MainId IS NULL

	IF @ProvinceID IN(10, 11, 30, 60)
		UPDATE #t SET City = (SELECT SubSiteCity FROM dcSubSite WHERE ID = @ProvinceId)

	INSERT INTO #t
	Select a.ID, e.DeptName, a.RecruitmentName, a.EndDate, a.ModifyDate, a.BeginDate, a.Brief,
		c.PlaceName, c.Address, b.Description City, d.EmailSite, d.SubSiteName, OrderBy, MainId
	FROM Recruitment a,
		dcRegion b,
		RecruitmentPlace c,
		dcSubSite d,
		RmDept e
	WHERE a.RecruitmentDeptId = e.Id
	AND LEFT(CityID, 2) = d.ID 
	AND b.ID = c.dcRegionID 
	AND a.RecruitmentPlaceId = c.id
	AND c.dcRegionID LIKE @Pid + '%' 
	AND a.MainId IN(SELECT ID FROM #t)

	SELECT * FROM #t
	--WHERE CHARINDEX(Left(City, 2), PlaceName) > 0 
	ORDER BY OrderBy, ID DESc
END

GO
/****** Object:  StoredProcedure [dbo].[procRecruitmeetingByHomepageSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--创建人 Lambo	
--20101009
--用于首页查询招聘会

CREATE PROCEDURE [dbo].[procRecruitmeetingByHomepageSelect] 
(
	@ProvinceID SMALLINT
)
AS
BEGIN
	/*
	SELECT TOP 1 ImageFile,alt FROM fpHomePageImage WITH(NOLOCK)
	WHERE ImageType = 2
	AND dcProvinceId = @ProvinceID
	ORDER BY AddDate DESC
	*/
	SELECT TOP 0 '' ImageFile, '' alt
--	IF @ProvinceID > 100
--		SELECT @ProvinceID = CONVERT(INT, LEFT(@ProvinceID, 2))

	SELECT TOP 15 ID newIDs,PreID Id, Title, AddDate, WeekDay, MonthDay, StartDate 
	FROM SearchDb..HpRecruitmeetingDay WITH(NOLOCK)
	WHERE ProvinceId = @ProvinceID
	ORDER BY newIDs
END










GO
/****** Object:  StoredProcedure [dbo].[procRecruitmeetingByHomepageSelectnew]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--############################################
--创建人 Lambo	
--20101009
--用于首页查询招聘会
--sean 2012-3-20
--增加ip所在地的判断
--############################################
CREATE PROCEDURE [dbo].[procRecruitmeetingByHomepageSelectnew] 
(
	@ProvinceID SMALLINT,
	@strIp VARCHAR(20)
)
AS
BEGIN
	SELECT TOP 1 ImageFile, alt FROM fpHomePageImage WITH(NOLOCK)
	WHERE ImageType = 2
	AND dcProvinceId = @ProvinceID
	ORDER BY AddDate DESC

--	IF @ProvinceID > 100
--		SELECT @ProvinceID = CONVERT(INT, LEFT(@ProvinceID, 2))
	DECLARE @dcSubSiteId AS INT, @Ip AS BIGINT

	SET @Ip = CONVERT(BIGINT, @strIp)

	SELECT TOP 1 @dcSubSiteId = CONVERT(INT, ISNULL(dcSubSiteId, 0))
	FROM dcIpPlace WITH(NOLOCK)
	WHERE IpStart <= @Ip 
	ORDER BY IpStart DESC

	IF LTRIM(STR(@dcSubSiteId)) LIKE LTRIM(STR(@ProvinceID)) + '%'
	BEGIN
		SELECT TOP 15 ID newIDs,PreID Id, Title, AddDate, WeekDay, MonthDay, StartDate 
		FROM SearchDb..HpRecruitmeetingDay WITH(NOLOCK)
		WHERE ProvinceId LIKE LTRIM(STR(@ProvinceID)) + '%'
		ORDER BY CASE ProvinceId WHEN @dcSubSiteId THEN 0 ELSE 1 END, newIDs
	--PRINT @dcSubSiteId
	END
	ELSE
	BEGIN
		SELECT TOP 15 ID newIDs,PreID Id, Title, AddDate, WeekDay, MonthDay, StartDate 
		FROM SearchDb..HpRecruitmeetingDay WITH(NOLOCK)
		WHERE ProvinceId = @ProvinceID
		ORDER BY newIDs
print 222222222
	END
END














GO
/****** Object:  StoredProcedure [dbo].[ProcRecruitMeetingLinkByProvinceIdSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2014.10.28
--创建人：John
--说明：获取招聘会链接
--@provinceId 省份编号
--#####################################################
CREATE PROCEDURE [dbo].[ProcRecruitMeetingLinkByProvinceIdSelect]
(
	@provinceId VARCHAR(4)
)
AS
BEGIN TRY
	SELECT TOP 5000 '/zhaopinhui/' + CONVERT(VARCHAR, ID) + '.html' link 
	FROM RecruitMeeting WITH(NOLOCK) 
	WHERE province_id = @provinceId
	 AND ((EndTime > GETDATE() AND type = 2) OR (status = 1 AND type = 1)) 
	 ORDER BY orderby, ID DESC
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[procRecruitment5ByConditionSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.10
--创建人：Nick
--说明：根据条件获取招聘会信息
--#####################################################
CREATE PROCEDURE [dbo].[procRecruitment5ByConditionSelect]
(
	@Condition VARCHAR(MAX)
)
AS
BEGIN
	DECLARE @SQL VARCHAR(MAX)
	SET @SQL = '
	SELECT top 5 a.ID, a.RecruitmentName, a.EndDate, a.BeginDate, c.PlaceName, c.Address, b.Description City 
	FROM Recruitment a, dcRegion b, RecruitmentPlace c, RecruitmentDept d 
	WHERE d.ID=a.RecruitmentDeptID 
	AND d.ID<>1767 
	AND b.ID=c.dcRegionID 
	AND a.RecruitmentPlaceId=c.id  
	AND EndDate>GetDate() 
	AND a.IsPause=0 
	AND Len(ManagerUserID)>0 '+@Condition+'
	ORDER BY OrderBy, a.EndDate '
	EXEC(@SQL)
END


GO
/****** Object:  StoredProcedure [dbo].[procRecruitmentByCondition51rcSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.10
--创建人：NICK
--说明：获取招聘会列表
--修改：Andy， 2014-12-22，修改显示个数为当天所有记录 
--#####################################################
CREATE PROCEDURE [dbo].[procRecruitmentByCondition51rcSelect]
(
	@RegionID INT,
	@PlaceID INT,
	@BeginDate VARCHAR(10)
)
AS
SET NOCOUNT ON
BEGIN
	DECLARE @EndDate VARCHAR(10)
	IF DATEPART(HOUR, GETDATE()) < 13
		SET @EndDate = CONVERT(VARCHAR(10), CONVERT(DATETIME, @BeginDate) + 1, 120)
	ELSE
		SET @EndDate = CONVERT(VARCHAR(10), CONVERT(DATETIME, @BeginDate) + 2, 120)

	DECLARE @SQL VARCHAR(MAX)
	SET @SQL = 'SELECT a.ID,a.RecruitmentName,c.id as PlaceID,c.BusLine,a.EndDate,a.BeginDate,c.PlaceName,c.Lng,c.Lat,c.Address,b.Description City,
		d.dcprovinceid,c.mapbarid,c.dcregionid,d.dcprovinceid,c.dcregionid 
		FROM SearchDb..RecruitmentTmp2 a WITH(NOLOCK),dcRegion b WITH(NOLOCK),RecruitmentPlace c WITH(NOLOCK),RecruitmentDept d WITH(NOLOCK)
		WHERE d.ID=a.RecruitmentDeptID
		AND d.ID<>1767
		AND b.ID=c.dcRegionID
		AND a.RecruitmentPlaceId=c.id '
	IF @PlaceID <> 0
	BEGIN
		SET @SQL = @SQL + ' AND c.ID = ' + CONVERT(VARCHAR(6), @PlaceID)
	END
	IF @RegionID <> 0
	BEGIN
		SET @SQL = @SQL +' AND c.dcRegionID like  '''+CONVERT(VARCHAR(6), @RegionID) + '%'' '
	END
	IF @BeginDate <> ''
	BEGIN
		SET @SQL = @SQL+' AND begindate > ''' + @BeginDate + ''' AND begindate <= ''' + @EndDate + ''''
	END
	SET @SQL = @SQL + ' ORDER BY CONVERT(char(10), a.begindate, 120) asc,
		case dcprovinceid when 32 then 1 when 30 then 2 when 10 then 3 when 12 then 4 when 72 then 5 when 31 then 6 when 11 then 7 when 61 then 8 when 20 then 9 when 40 then 10 when 35 then 11  else 20 end,
		a.begindate '
	--PRINT(@SQL)
	EXEC(@SQL)
END
SET NOCOUNT OFF

 
GO
/****** Object:  StoredProcedure [dbo].[procRecruitmentByCondition51rcSelect1111]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.10
--创建人：NICK
--说明：获取招聘会列表
--修改：Andy， 2014-12-22，修改显示个数为当天所有记录 
--#####################################################
create PROCEDURE [dbo].[procRecruitmentByCondition51rcSelect1111]
(
	@RegionID INT,
	@PlaceID INT,
	@BeginDate VARCHAR(10)
)
AS
SET NOCOUNT ON
BEGIN
	DECLARE @EndDate VARCHAR(10)
	IF DATEPART(HOUR, GETDATE()) < 13
		SET @EndDate = CONVERT(VARCHAR(10), CONVERT(DATETIME, @BeginDate) + 1, 120)
	ELSE
		SET @EndDate = CONVERT(VARCHAR(10), CONVERT(DATETIME, @BeginDate) + 2, 120)

	DECLARE @SQL VARCHAR(MAX)
	SET @SQL = 'SELECT a.ID,a.RecruitmentName,c.id as PlaceID,c.BusLine,a.EndDate,a.BeginDate,c.PlaceName,c.Lng,c.Lat,c.Address,b.Description City,
		d.dcprovinceid,c.mapbarid,c.dcregionid,d.dcprovinceid,c.dcregionid 
		FROM Recruitment a WITH(NOLOCK),dcRegion b WITH(NOLOCK),RecruitmentPlace c WITH(NOLOCK),RecruitmentDept d WITH(NOLOCK)
		WHERE d.ID=a.RecruitmentDeptID
		AND d.ID<>1767
		AND b.ID=c.dcRegionID
		AND EndDate > GETDATE()
		AND a.RecruitmentPlaceId=c.id
		And a.IsPause=0 And Len(ManagerUserID)>0 '
	IF @PlaceID <> 0
	BEGIN
		SET @SQL = @SQL + ' AND c.ID = ' + CONVERT(VARCHAR(6), @PlaceID)
	END
	IF @RegionID <> 0
	BEGIN
		SET @SQL = @SQL +' AND c.dcRegionID like  '''+CONVERT(VARCHAR(6), @RegionID) + '%'' '
	END
	IF @BeginDate <> ''
	BEGIN
		SET @SQL = @SQL+' AND begindate > ''' + @BeginDate + ''' AND begindate <= ''' + @EndDate + ''''
	END
	SET @SQL = @SQL + ' ORDER BY CONVERT(char(10), a.begindate, 120) asc,
		case dcprovinceid when 32 then 1 when 30 then 2 when 10 then 3 when 12 then 4 when 72 then 5 when 31 then 6 when 11 then 7 when 61 then 8 when 20 then 9 when 40 then 10 when 35 then 11  else 20 end '
	PRINT(@SQL)
	EXEC(@SQL)
END
SET NOCOUNT OFF

 
GO
/****** Object:  StoredProcedure [dbo].[procRecruitmentByCondition51rcSelect2]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.10
--创建人：NICK
--说明：获取招聘会列表
--修改：Andy， 2014-12-22，修改显示个数为当天所有记录 
--#####################################################
CREATE PROCEDURE [dbo].[procRecruitmentByCondition51rcSelect2]
(
	@RegionID INT,
	@PlaceID INT,
	@BeginDate VARCHAR(10)
)
AS
SET NOCOUNT ON
BEGIN
	DECLARE @EndDate VARCHAR(10)
	IF DATEPART(HOUR, GETDATE()) < 13
		SET @EndDate = CONVERT(VARCHAR(10), CONVERT(DATETIME, @BeginDate) + 1, 120)
	ELSE
		SET @EndDate = CONVERT(VARCHAR(10), CONVERT(DATETIME, @BeginDate) + 2, 120)

	IF NOT EXISTS(SELECT 'x' FROM SearchDb..SysObjects WHERE Name = 'RecruitmentTmp')
	BEGIN
		CREATE TABLE SearchDb..RecruitmentTmp2(
			ID int NOT NULL,
			RecruitmentName nvarchar(50) NOT NULL,
			RecruitmentDeptID int NOT NULL,
			RecruitmentPlaceId int NOT NULL,
			IsPause tinyint NOT NULL,
			ManagerUserID smallint NULL,
			EndDate smalldatetime NOT NULL,
			BeginDate smalldatetime NOT NULL
		) 
		INSERT INTO SearchDb..RecruitmentTmp2	
		SELECT ID, RecruitmentName, RecruitmentDeptID, RecruitmentPlaceId, IsPause, ManagerUserID, EndDate, BeginDate
		FROM Recruitment WITH(NOLOCK)
		WHERE EndDate > GETDATE()    
		And IsPause=0 
		And Len(ManagerUserID)>0  
	END
	IF EXISTS(SELECT 'x' FROM SearchDb..RecruitmentTmp2 WITH(NOLOCK) WHERE BeginDate < GETDATE())
	BEGIN
		TRUNCATE TABLE SearchDb..RecruitmentTmp2	
		INSERT INTO SearchDb..RecruitmentTmp2	
		SELECT ID, RecruitmentName, RecruitmentDeptID, RecruitmentPlaceId, IsPause, ManagerUserID, EndDate, BeginDate
		FROM Recruitment WITH(NOLOCK)
		WHERE EndDate > GETDATE()    
		And IsPause=0 
		And Len(ManagerUserID)>0  
	END

	DECLARE @SQL VARCHAR(MAX)
	SET @SQL = 'SELECT a.ID,a.RecruitmentName,c.id as PlaceID,c.BusLine,a.EndDate,a.BeginDate,c.PlaceName,c.Lng,c.Lat,c.Address,b.Description City,
		d.dcprovinceid,c.mapbarid,c.dcregionid,d.dcprovinceid,c.dcregionid 
		FROM SearchDb..RecruitmentTmp2 a WITH(NOLOCK),dcRegion b WITH(NOLOCK),RecruitmentPlace c WITH(NOLOCK),RecruitmentDept d WITH(NOLOCK)
		WHERE d.ID=a.RecruitmentDeptID
		AND d.ID<>1767
		AND b.ID=c.dcRegionID
		AND a.RecruitmentPlaceId=c.id '
	IF @PlaceID <> 0
	BEGIN
		SET @SQL = @SQL + ' AND c.ID = ' + CONVERT(VARCHAR(6), @PlaceID)
	END
	IF @RegionID <> 0
	BEGIN
		SET @SQL = @SQL +' AND c.dcRegionID like  '''+CONVERT(VARCHAR(6), @RegionID) + '%'' '
	END
	IF @BeginDate <> ''
	BEGIN
		SET @SQL = @SQL+' AND begindate > ''' + @BeginDate + ''' AND begindate <= ''' + @EndDate + ''''
	END
	SET @SQL = @SQL + ' ORDER BY CONVERT(char(10), a.begindate, 120) asc,
		case dcprovinceid when 32 then 1 when 30 then 2 when 10 then 3 when 12 then 4 when 72 then 5 when 31 then 6 when 11 then 7 when 61 then 8 when 20 then 9 when 40 then 10 when 35 then 11  else 20 end,
		a.begindate '
	--PRINT(@SQL)
	EXEC(@SQL)
END
SET NOCOUNT OFF

 
GO
/****** Object:  StoredProcedure [dbo].[procRecruitmentByID51RCSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.10
--创建人：NICK
--说明：通过招聘会id获取招聘会详细信息
--#####################################################
CREATE PROCEDURE [dbo].[procRecruitmentByID51RCSelect]
(
	@ID INT
)
AS
BEGIN
	SELECT a.*,c.PlaceName,c.Address,b.Description City,c.MapbarID,c.Lng,c.Lat,c.BusLine,CreditRating,
	case cityid when '3202' then 'www.daochengrc.com' else 'www.'+ProvinceDomain end SiteUrl,
	d.ID ProvinceID,a.RecruitmentDeptId From Recruitment a,dcRegion b,RecruitmentPlace c,dcProvince d,
	recruitmentdept e 
	WHERE e.id=a.recruitmentdeptid 
	AND b.ID=c.dcRegionID 
	AND a.RecruitmentPlaceId=c.id 
	AND d.ID=Left(a.CityID,2) And a.ID=@ID
END


GO
/****** Object:  StoredProcedure [dbo].[procRecruitmentByIDSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.30
--创建人：Nick
--说明：得到招聘会信息
--修改harry 增加校园招聘会2018-3-20 3-21
--#####################################################
CREATE PROCEDURE [dbo].[procRecruitmentByIDSelect]
(
	@ID INT
)
AS
BEGIN
	IF @ID>0
	BEGIN
		SELECT a.*,b.Lng,b.Lat 
		FROM Marketdb..Recruitment a,Marketdb..RmPlace b 
		WHERE a.RecruitmentPlaceID = b.id 
		AND a.ID=@ID
	END
	ELSE
	BEGIN
		SELECT a.*,a.Name AS RecruitmentName, b.Lng,b.Lat 
		FROM wutongguodb..RecruitmentSchool a,Marketdb..RmPlace b 
		WHERE a.RecruitmentPlaceID = b.id 
		AND a.ID=ABS(@ID)
	END
END

GO
/****** Object:  StoredProcedure [dbo].[procRecruitmentByProvinceIDSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.10
--创建人：Nick
--说明：根据省份获取招聘会信息
--#####################################################
CREATE PROCEDURE [dbo].[procRecruitmentByProvinceIDSelect]
(
	@ProvinceID VARCHAR(10)
)
AS
BEGIN
	SELECT top 5 a.ID, a.RecruitmentName, a.EndDate, a.BeginDate, c.PlaceName, c.Address, b.Description City 
	FROM Recruitment a, dcRegion b, RecruitmentPlace c, RecruitmentDept d 
	WHERE d.ID=a.RecruitmentDeptID 
	AND d.ID<>1767 
	AND b.ID=c.dcRegionID 
	AND a.RecruitmentPlaceId=c.id 
	AND LEFT(c.dcRegionID, 2)=@ProvinceID 
	AND EndDate>GetDate() 
	AND a.IsPause=0 
	AND Len(ManagerUserID)>0 
	ORDER BY OrderBy, a.EndDate
END


GO
/****** Object:  StoredProcedure [dbo].[procRecruitmentByQlrcTopicSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[procRecruitmentByQlrcTopicSelect]  
(
	@dcRegionID INT,	--地区编号 0表示全部 2位表示省份 4位表示城市
	@BeginDate VARCHAR(50),--开始时间 默认两年前数据
	@EndDate VARCHAR(50),	--结束时间
	@PageNo INT		--页码
)
AS
BEGIN
	SET NOCOUNT ON
	DECLARE @SQL VARCHAR(MAX)
	DECLARE @WHERE VARCHAR(MAX)	--查询条件
	DECLARE @TotalNum INT		--总量
	IF @PageNo = 0
	BEGIN
		SET @PageNo = 1
	END
	
	SET @SQL = ''
	SET @WHERE = ''
		
	--筛选条件
	SET @WHERE = @WHERE + ' AND a.IsSchool = 1'
	IF @dcRegionID<>0 --选择地区
	BEGIN
		SET @WHERE = @WHERE +' AND c.dcRegionID like  '''+CONVERT(VARCHAR(6),@dcRegionID)+'%'' '
	END
	IF @BeginDate<>'' AND @EndDate<>'' --选择时间
	BEGIN
		SET @WHERE = @WHERE + ' AND EndDate >= '''+@BeginDate +''' AND EndDate<'''+@EndDate+''''
	END
	ELSE
	BEGIN
		SET @WHERE = @WHERE + ' AND EndDate >= GETDATE() '
	END
	
	--创建临时表 存放招聘会
	CREATE TABLE #indextable(
		[NUM] int identity(1,1),
		ID INT NULL,
		Type INT NULL,
		DcRegionID INT
		
	)
	
	CREATE TABLE #indextable2(
		[NUM] int identity(1,1),
		ID INT NULL,
		Type INT NULL,
		dcRegionID INT
	)

	IF LEN(@dcRegionID)>=4
	BEGIN
		SET @SQL ='
		INSERT INTO #indextable2(ID,Type,dcRegionID)
		SELECT a.ID,a.IsSchool,b.ID 
		FROM MarketDB..Recruitment a WITH(NOLOCK),maindb..dcRegion b WITH(NOLOCK),MarketDB..RmPlace c WITH(NOLOCK),MarketDB..RmDept d WITH(NOLOCK)
		WHERE d.ID=a.RecruitmentDeptID
		AND b.ID=c.dcRegionID
		AND a.RecruitmentPlaceId=c.id
		And a.IsPause=0 and d.IsPause=0 '+@WHERE +'
		AND EndDate > GETDATE() ORDER BY a.orderby, a.BeginDate ASC'
		EXEC(@SQL)
		
		----------------------未过期
		--本城市			
		SET @SQL ='
		INSERT INTO #indextable(ID,Type,dcRegionID)
		SELECT a.ID,a.Type,a.dcRegionID 
		FROM #indextable2 a
		WHERE DcRegionID LIKE '''+LEFT(@dcRegionID,4)+'%'' 
		'
		EXEC(@SQL)			
		
		
	END
	ELSE IF LEN(@dcRegionID)=2
	BEGIN
		--本省份
		SET @SQL ='
		INSERT INTO #indextable(ID,Type,dcRegionID)
		SELECT a.ID,a.IsSchool,b.ID 
		FROM MarketDB..Recruitment a WITH(NOLOCK),maindb..dcRegion b WITH(NOLOCK),MarketDB..RmPlace c WITH(NOLOCK),MarketDB..RmDept d WITH(NOLOCK)
		WHERE d.ID=a.RecruitmentDeptID
		AND b.ID=c.dcRegionID
		AND a.RecruitmentPlaceId=c.id
		And a.IsPause=0  and d.IsPause=0 '+@WHERE +'
		AND c.DcRegionID LIKE '''+LTRIM(LEFT(@dcRegionID,2))+'%'' 
		AND EndDate > GETDATE() ORDER BY a.orderby,a.BeginDate '
		
		EXEC(@SQL)
		print '$$'+@SQL
		
	END

	
	DECLARE @SQLTmp VARCHAR(MAX)
	SET @SQLTmp = ''
	
	SET @SQLTmp =' FROM MarketDB..Recruitment a WITH(NOLOCK),MarketDB..RmPlace c WITH(NOLOCK)
		WHERE a.RecruitmentPlaceId=c.id
		AND a.ID IN (SELECT ID FROM #indextable) '
	
	
	--获取招聘会列表
	DECLARE @RecordCount INT
	DECLARE @PageSize INT
	SET @PageSize = 8
    DECLARE @PageLowerBound  INT --定义此页的底码
    DECLARE @PageUpperBound  INT --定义此页的顶码
    SET @PageLowerBound = (@PageNo -1) * @pagesize
    SET @PageUpperBound = @PageLowerBound + @pagesize
	SELECT @RecordCount = COUNT(*) FROM #indextable
	DELETE FROM #indextable WHERE Num <= @PageLowerBound Or Num > @PageUpperBound
	--创建临时表 存放招聘会
	CREATE TABLE #Rm(
		[ID] [int] NOT NULL,
		[RecruitmentName] NVARCHAR(100) NULL,
		[EndDate] SMALLDATETIME NULL,
		[BeginDate] SMALLDATETIME NULL,
		[PlaceID] INT NULL,
		[PlaceName] NVARCHAR(100) NULL,
		[Address] NVARCHAR(200) NULL,
		[City] NVARCHAR(200) NULL,
		[Lng] VARCHAR(20) NULL,
		[Lat] VARCHAR(20) NULL,
		[mapbarid] VARCHAR(100) NULL,
		[dcregionid] VARCHAR(10) NULL,
		[IsSchool] VARCHAR(20) NULL,
		[OrderNo] [INT] NULL,
		RecruitmentDeptID INT NULL,
		[PhotoNum] [INT] NULL,
		[IsAttention] [INT] NULL,
		BusLine NVARCHAR(500),
		Orderby INT
	)	
	
	INSERT INTO #Rm
	SELECT a.ID,a.RecruitmentName,a.EndDate,a.BeginDate,c.id as PlaceID,c.PlaceName,
	c.Address,b.Description City,c.Lng, c.Lat,c.mapbarid,c.dcregionid,a.IsSchool,
	b.OrderNo,a.RecruitmentDeptID,0 AS PhotoNum,0 AS IsAttention,c.BusLine,a.Orderby
	FROM #indextable e,MarketDB..Recruitment a WITH(NOLOCK),maindb..dcRegion b WITH(NOLOCK),MarketDB..RmPlace c WITH(NOLOCK),MarketDB..RmDept d WITH(NOLOCK)
	WHERE e.ID = a.ID
	AND d.ID=a.RecruitmentDeptID
	AND b.ID=c.dcRegionID
	AND a.RecruitmentPlaceId=c.id
	ORDER BY e.Num ASC
	
	SELECT @RecordCount CNT --总数
	SELECT * FROM #Rm		--招聘会列表
	SET NOCOUNT OFF	
END

GO
/****** Object:  StoredProcedure [dbo].[procRecruitmentCallbackSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--简历投递回调
--支付宝用
CREATE PROCEDURE [dbo].[procRecruitmentCallbackSelect]
(
	@BeginDate VARCHAR(50)
)
AS
SET NOCOUNT ON
BEGIN
	SELECT a.ID, a.JobID, a.InterviewDate, a.InterViewPlace, b.alipayResumeID, a.Remark
	INTO #T
	FROM exInterview a WITH(NOLOCK), paCvAlipayRelation b WITH(NOLOCK)
	WHERE a.cvMainID = b.cvMainID
	AND a.AddDate > @BeginDate 

	SELECT * FROM #T

	SELECT a.ViewDate, a.Reply, b.alipayResumeID, a.JobID
	FROM exjobapply a WITH(NOLOCK INDEX(IX_ExJobApply_Date)), paCvAlipayRelation b WITH(NOLOCK)
	WHERE a.cvMainID = b.cvMainID
	AND (a.AddDate > @BeginDate OR a.ViewDate > @BeginDate OR a.ReplyDate > @BeginDate)
	AND NOT EXISTS(SELECT 'x' FROM #T WHERE alipayResumeID = b.alipayResumeID AND JobID = a.JobID)

	DROP TABLE #T 
END

GO
/****** Object:  StoredProcedure [dbo].[procRecruitmentImageByRmIDSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.5
--创建人：NICK
--说明：获取招聘会图片
--#####################################################
CREATE PROCEDURE [dbo].[procRecruitmentImageByRmIDSelect]
(
	@RmID INT
)
AS
BEGIN
	SELECT * FROM RecruitmentImage 
	WHERE recruitmentid=@RmID 
	ORDER BY orderno ,adddate DESC
END


GO
/****** Object:  StoredProcedure [dbo].[ProcRecruitmentListInsert]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ProcRecruitmentListInsert]
AS
BEGIN
	DECLARE @ID INT, @Count INT
	SELECT TOP 0 * INTO #t fROM ShortDb..RecruitmentList
	SET @ID = 0
	WHILE EXISTS(SELECT 'x' FROM dcSubSite WHERE IsMainSite = 1 AND ID > @ID)
	BEGIN
		SELECT TOP 1 @ID = ID FROM dcSubSite WHERE IsMainSite = 1 AND ID > @ID ORDER BY ID

		SELECT @Count = COUNT(*)
		FROM Recruitment a, dcRegion b, RecruitmentPlace c, RecruitmentDept d 
		WHERE d.ID = a.RecruitmentDeptID 
		AND d.ID <> 1767 
		AND b.ID = c.dcRegionID
		AND a.RecruitmentPlaceId = c.id 
		AND LEFT(c.dcRegionID, 2) = @ID
		AND EndDate>GETDATE()
		AND a.IsPause = 0
		AND Len(ManagerUserID)>0 

		IF @COUNT > 200
			SET @COUNT  =  200

		INSERT INTO #T
		SELECT @ID Provinceid, *, @COUNT AS cnt
		FROM (SELECT TOP 200 ROW_NUMBER() OVER(ORDER BY OrderBy, a.EndDate) AS Rows, 
				a.ID, a.RecruitmentName, a.EndDate, a.BeginDate,
				c.PlaceName, c.Address, b.Description City 
			FROM Recruitment a, dcRegion b, RecruitmentPlace c, RecruitmentDept d 
			WHERE d.ID = a.RecruitmentDeptID
			AND d.ID<>1767
			AND b.ID = c.dcRegionID
			AND a.RecruitmentPlaceId = c.id 
			AND LEFT(c.dcRegionID, 2) = @ID
			AND EndDate>GETDATE()
			AND a.IsPause = 0
			AND LEN(ManagerUserID)>0
			) AS a 
	END
	TRUNCATE TABLE ShortDb..RecruitmentList
	INSERT ShortDb..RecruitmentList SELECT * FROM #t
END









GO
/****** Object:  StoredProcedure [dbo].[procRecruitmentPlaceByKeyWordSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.5
--创建人：NICK
--说明：根据关键词搜索招聘会
--#####################################################
CREATE PROCEDURE [dbo].[procRecruitmentPlaceByKeyWordSelect]
(
	@keyword VARCHAR(50)
)
AS
BEGIN
	SELECT TOP 10 a.ID,a.RecruitmentName,a.EndDate,a.BeginDate,c.PlaceName,c.Address,b.Description City 
	From Recruitment a,dcRegion b,RecruitmentPlace c,RecruitmentDept d
	Where d.ID=a.RecruitmentDeptID
	AND d.ID<>1767
	AND b.ID=c.dcRegionID
	AND a.RecruitmentPlaceId=c.id
	And EndDate>GetDate()
	And a.IsPause=0 And Len(ManagerUserID)>0
	And (a.RecruitmentName like '%'+@keyword+'%' OR c.PlaceName like '%'+@keyword+'%' OR c.Address like '%'+@keyword+'%')
	ORDER BY orderby, a.EndDate
END


GO
/****** Object:  StoredProcedure [dbo].[procRecruitmentPlaceByRegionID2Select]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.5
--创建人：NICK
--说明：获取场馆
--#####################################################
CREATE PROCEDURE [dbo].[procRecruitmentPlaceByRegionID2Select]
(
	@RegionID INT
)
AS
BEGIN
	SELECT * FROM RecruitmentPlace x 
	WHERE dcRegionID like ''+CONVERT(VARCHAR(6),@RegionID)+'%' 
	AND LEN(VerifyMan)>0 
	AND IsCampus=0 
	AND EXISTS(
		SELECT TOP 1 'x' 
		FROM cvMain a  WITH(NOLOCK) 
		INNER JOIN marketdb..RmInvitationCode b WITH(NOLOCK) 
		ON a.paMainID=b.paMainID 
		AND b.Valid=1 
		INNER JOIN marketdb..RmProject c WITH(NOLOCK) 
		ON b.RmProjectID=c.ID INNER JOIN Recruitment d WITH(NOLOCK) 
		ON c.RecruitmentID=d.ID INNER JOIN RecruitmentPlace e WITH(NOLOCK) 
		ON d.RecruitmentPlaceID=e.ID 
		AND e.ID=x.ID 
		AND b.AddDate>GETDATE()-90
	)
END


GO
/****** Object:  StoredProcedure [dbo].[procRecruitmentPlaceByRegionIDSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.31
--创建人：Nick
--说明：获取场馆
--#####################################################
CREATE PROCEDURE [dbo].[procRecruitmentPlaceByRegionIDSelect]
(
	@RegionID VARCHAR(6)
)
AS
BEGIN TRY
	SELECT * FROM RecruitmentPlace 
	WHERE dcRegionID LIKE @RegionID+'%' 
	AND LEN(VerifyMan)>0
	AND EXISTS(
		SELECT 'X' 
		FROM marketdb..RmInvitationCode a,marketdb..RmProject b,Recruitment c 
		WHERE a.RmProjectID=b.ID 
		AND b.RecruitmentID=c.ID 
		AND c.RecruitmentPlaceID=RecruitmentPlace.ID 
		AND a.Valid=1)
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[procRecruitmentPlaceMapBarIDSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.5
--创建人：NICK
--说明：获取招聘会的mapbarID
--#####################################################
CREATE PROCEDURE [dbo].[procRecruitmentPlaceMapBarIDSelect]
(
	@regionID VARCHAR(6)
)
AS
BEGIN
	SELECT DISTINCT MapBarId2 FROM RecruitmentPlace WHERE dcRegionID LIKE @regionID + '%'
END


GO
/****** Object:  StoredProcedure [dbo].[procRecruitmentSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[procRecruitmentSelect]  
(
	@Type INT,			--招聘会类型 0 全部 1 校园招聘会 2社会招聘会 
	@dcRegionID INT,	--地区编号 0表示全部 2位表示省份 4位表示城市
	@PlaceID INT,		--场馆ID
	@BeginDate VARCHAR(50),--开始时间 默认两年前数据
	@EndDate VARCHAR(50),	--结束时间
	@LocationRegionID VARCHAR(10), --求职者所在地区
	@PageNo INT		--页码
)
AS
BEGIN
	SET NOCOUNT ON
	IF LEN(LTRIM(@LocationRegionID))=0 OR @LocationRegionID = '0'
		SET @LocationRegionID = 10
	DECLARE @SQL VARCHAR(MAX)
	DECLARE @WHERE VARCHAR(MAX),@WHERE2 VARCHAR(MAX)	--查询条件
	DECLARE @TotalNum INT		--总量
	IF @PageNo = 0
	BEGIN
		SET @PageNo = 1
	END
	
	SET @SQL = ''
	SET @WHERE = ''
	SET @WHERE2 = ''
		
	--筛选条件
	IF @Type = 1	--校园招聘会
	BEGIN
		SET @WHERE = @WHERE + ' AND a.IsSchool = 1'
		SET @WHERE2 = @WHERE2 + ' AND a.IsSchool = 1'
	END
	IF @Type = 2	--社会招聘会
	BEGIN
		SET @WHERE = @WHERE + ' AND a.IsSchool <> 1'
		SET @WHERE2 = @WHERE2 + ' AND a.IsSchool <> 1'
	END
	IF @dcRegionID<>0 --选择地区
	BEGIN
		SET @WHERE = @WHERE +' AND c.dcRegionID like  '''+CONVERT(VARCHAR(6),@dcRegionID)+'%'' '
		SET @WHERE2 = @WHERE2 +' AND c.dcRegionID like  '''+CONVERT(VARCHAR(6),@dcRegionID)+'%'' '
	END
	IF @PlaceID<>0  --筛选场馆
	BEGIN
		SET @WHERE = @WHERE + ' AND c.ID = '+CONVERT(VARCHAR(20),@PlaceID)
		SET @WHERE2 = @WHERE2 + ' AND c.ID = '+CONVERT(VARCHAR(20),@PlaceID)
	END
	
	IF @BeginDate<>'' AND @EndDate<>'' --选择时间
	BEGIN
		SET @WHERE = @WHERE + ' AND EndDate >= '''+@BeginDate +''' AND EndDate<'''+@EndDate+''''
	END
	
	--创建临时表 存放招聘会
	CREATE TABLE #indextable(
		[NUM] int identity(1,1),
		ID INT NULL,
		Type INT NULL,
		DcRegionID INT
		
	)
	
	CREATE TABLE #indextable2(
		[NUM] int identity(1,1),
		ID INT NULL,
		Type INT NULL,
		dcRegionID INT
	)

	IF @dcRegionID = 0 AND @PlaceID = 0
	BEGIN
		IF LEN(@LocationRegionID)>=4
		BEGIN
			SET @SQL ='
			INSERT INTO #indextable2(ID,Type,dcRegionID)
			SELECT a.ID,a.IsSchool,b.ID 
			FROM MarketDB..Recruitment a WITH(NOLOCK),maindb..dcRegion b WITH(NOLOCK),MarketDB..RmPlace c WITH(NOLOCK),MarketDB..RmDept d WITH(NOLOCK)
			WHERE d.ID=a.RecruitmentDeptID
			AND b.ID=c.dcRegionID
			AND a.RecruitmentPlaceId=c.id
			AND a.ManagerUserID IS NOT NULL
			And a.IsPause=0 and d.IsPause=0 '+@WHERE +'
			AND EndDate > GETDATE() ORDER BY a.BeginDate ASC'
			EXEC(@SQL)
			
			----------------------未过期
			--本城市			
			SET @SQL ='
			INSERT INTO #indextable(ID,Type,dcRegionID)
			SELECT a.ID,a.Type,a.dcRegionID 
			FROM #indextable2 a
			WHERE DcRegionID LIKE '''+LEFT(@LocationRegionID,4)+'%'' 
			'
			EXEC(@SQL)			
			
			--本省份
			SET @SQL ='
			INSERT INTO #indextable(ID,Type,dcRegionID)
			SELECT a.ID,a.Type,a.dcRegionID 
			FROM #indextable2 a
			WHERE a.DcRegionID LIKE '''+LEFT(@LocationRegionID,2)+'%'' 
			AND a.DcRegionID NOT LIKE '''+LEFT(@LocationRegionID,4)+'%'' 
			'
			EXEC(@SQL)
			
			--临近省份
			SET @SQL ='
			INSERT INTO #indextable(ID,Type,dcRegionID)
			SELECT a.ID,a.Type,a.dcRegionID 
			FROM #indextable2 a
			WHERE LEFT(a.DcRegionID,2) IN (SELECT NearProvinceID FROM dcProvinceNear WITH(NOLOCK) WHERE dcProvinceID = '+LEFT(@LocationRegionID,2)+')
			'
			EXEC(@SQL)
			
			--其他省份
			SET @SQL ='
			INSERT INTO #indextable(ID,Type,dcRegionID)
			SELECT a.ID,a.Type,a.dcRegionID 
			FROM #indextable2 a
			WHERE LEFT(a.DcRegionID,2) NOT IN (SELECT NearProvinceID FROM dcProvinceNear WITH(NOLOCK) WHERE dcProvinceID = '+LEFT(@LocationRegionID,2)+')
			AND LEFT(DcRegionID,2)<>'+LEFT(@LocationRegionID,2)+'
			'
			EXEC(@SQL)
			------------------过期			
			SET @SQL ='
			INSERT INTO #indextable(ID,Type,dcRegionID)
			SELECT a.ID,a.IsSchool,b.ID 
			FROM MarketDB..Recruitment a WITH(NOLOCK),maindb..dcRegion b WITH(NOLOCK),MarketDB..RmPlace c WITH(NOLOCK),MarketDB..RmDept d WITH(NOLOCK)
			WHERE d.ID=a.RecruitmentDeptID
			AND b.ID=c.dcRegionID
			AND a.RecruitmentPlaceId=c.id
			AND a.ManagerUserID IS NOT NULL
			And a.IsPause=0 and d.IsPause=0 '+@WHERE +'
			AND EndDate < GETDATE() 
			AND EndDate>GetDate()-365
			ORDER BY EndDate DESC'
			EXEC(@SQL)
		END
		IF LEN(@LocationRegionID)=2
		BEGIN
			--本省份
			SET @SQL ='
			INSERT INTO #indextable(ID,Type,dcRegionID)
			SELECT a.ID,a.IsSchool,b.ID 
			FROM MarketDB..Recruitment a  WITH(NOLOCK),maindb..dcRegion b  WITH(NOLOCK),MarketDB..RmPlace c  WITH(NOLOCK),MarketDB..RmDept d  WITH(NOLOCK)
			WHERE d.ID=a.RecruitmentDeptID
			AND b.ID=c.dcRegionID
			AND a.RecruitmentPlaceId=c.id
			AND a.ManagerUserID IS NOT NULL
			And a.IsPause=0  and d.IsPause=0 '+@WHERE +'
			AND c.DcRegionID LIKE '''+LTRIM(LEFT(@LocationRegionID,2))+'%'' 
			AND EndDate > GETDATE() ORDER BY a.BeginDate '
			
			EXEC(@SQL)
			print '$$'+@SQL
			--临近省份
			SET @SQL ='
			INSERT INTO #indextable(ID,Type,dcRegionID)
			SELECT a.ID,a.IsSchool,b.ID 
			FROM MarketDB..Recruitment a  WITH(NOLOCK),maindb..dcRegion b  WITH(NOLOCK),MarketDB..RmPlace c  WITH(NOLOCK),MarketDB..RmDept d  WITH(NOLOCK)
			WHERE d.ID=a.RecruitmentDeptID
			AND b.ID=c.dcRegionID
			AND a.RecruitmentPlaceId=c.id
			AND a.ManagerUserID IS NOT NULL
			And a.IsPause=0 and d.IsPause=0 '+@WHERE +'
			AND LEFT(c.DcRegionID,2) IN (SELECT NearProvinceID FROM dcProvinceNear WHERE dcProvinceID = LEFT('+@LocationRegionID+',2))
			AND EndDate > GETDATE() ORDER BY a.EndDate'
			EXEC(@SQL)
			print '$$'+@SQL
			
			--其他省份
			SET @SQL ='
			INSERT INTO #indextable(ID,Type,dcRegionID)
			SELECT a.ID,a.IsSchool,b.ID 
			FROM MarketDB..Recruitment a  WITH(NOLOCK),maindb..dcRegion b  WITH(NOLOCK),MarketDB..RmPlace c  WITH(NOLOCK),MarketDB..RmDept d  WITH(NOLOCK)
			WHERE d.ID=a.RecruitmentDeptID
			AND b.ID=c.dcRegionID
			AND a.RecruitmentPlaceId=c.id
			AND a.ManagerUserID IS NOT NULL
			And a.IsPause=0 and d.IsPause=0 '+@WHERE +'
			AND LEFT(c.DcRegionID,2) NOT IN (SELECT NearProvinceID FROM dcProvinceNear WHERE dcProvinceID = LEFT('+@LocationRegionID+',2))
			AND LEFT(DcRegionID,2)<>'+@LocationRegionID+'
			AND EndDate > GETDATE() ORDER BY a.EndDate'
			EXEC(@SQL)
			print '$$'+@SQL
			------------------过期
			SET @SQL ='
			INSERT INTO #indextable(ID,Type,dcRegionID)
			SELECT a.ID,a.IsSchool,b.ID 
			FROM MarketDB..Recruitment a  WITH(NOLOCK),maindb..dcRegion b  WITH(NOLOCK),MarketDB..RmPlace c  WITH(NOLOCK),MarketDB..RmDept d  WITH(NOLOCK)
			WHERE d.ID=a.RecruitmentDeptID
			AND b.ID=c.dcRegionID
			AND a.RecruitmentPlaceId=c.id
			AND a.ManagerUserID IS NOT NULL
			And a.IsPause=0 and d.IsPause=0 '+@WHERE +'
			AND EndDate < GETDATE() 
			AND EndDate>GetDate()-365
			ORDER BY EndDate DESC'
			EXEC(@SQL)
			print '$$'+@SQL
		END
	END
	ELSE
	BEGIN
		IF @BeginDate<>'' AND @EndDate<>''
		BEGIN
			SET @SQL ='
			INSERT INTO #indextable(ID,Type,dcRegionID)
			SELECT a.ID,a.IsSchool,b.ID 
			FROM MarketDB..Recruitment a  WITH(NOLOCK),maindb..dcRegion b  WITH(NOLOCK),MarketDB..RmPlace c  WITH(NOLOCK),MarketDB..RmDept d  WITH(NOLOCK)
			WHERE d.ID=a.RecruitmentDeptID
			AND b.ID=c.dcRegionID
			AND a.RecruitmentPlaceId=c.id
			AND a.ManagerUserID IS NOT NULL
			And a.IsPause=0 and d.IsPause=0 '+@WHERE +' ORDER BY a.BeginDate '
			EXEC(@SQL)
		END
		ELSE
		BEGIN
			SET @SQL = '
			INSERT INTO #indextable(ID,Type,dcRegionID)
			SELECT a.ID,a.IsSchool,b.ID 
			FROM MarketDB..Recruitment a  WITH(NOLOCK),maindb..dcRegion b  WITH(NOLOCK),MarketDB..RmPlace c  WITH(NOLOCK),MarketDB..RmDept d  WITH(NOLOCK)
			WHERE d.ID=a.RecruitmentDeptID
			AND b.ID=c.dcRegionID
			AND a.RecruitmentPlaceId=c.id
			AND a.ManagerUserID IS NOT NULL
			And a.IsPause=0 and d.IsPause=0 '+@WHERE +
			' AND EndDate>GetDate() ORDER BY a.BeginDate ASC'
			EXEC(@SQL)
					
			SET @SQL ='
			INSERT INTO #indextable(ID,Type,dcRegionID)
			SELECT a.ID,a.IsSchool,b.ID 
			FROM MarketDB..Recruitment a  WITH(NOLOCK),maindb..dcRegion b  WITH(NOLOCK),MarketDB..RmPlace c  WITH(NOLOCK),MarketDB..RmDept d  WITH(NOLOCK)
			WHERE d.ID=a.RecruitmentDeptID
			AND b.ID=c.dcRegionID
			AND a.RecruitmentPlaceId=c.id
			AND a.ManagerUserID IS NOT NULL
			And a.IsPause=0 And d.IsPause=0 '+@WHERE +
			'  And EndDate < GetDate() and EndDate>GetDate()-365 ORDER BY a.BeginDate DESC '
			EXEC(@SQL)
		END
	END

	
	--INSERT INTO #RmTmp2 SELECT * ,ROW_NUMBER() OVER(ORDER BY (SELECT 0)) AS RowNum FROM #RmTmp1
		
	DECLARE @SQLTmp VARCHAR(MAX)
	SET @SQLTmp = ''
	
	SET @SQLTmp =' FROM MarketDB..Recruitment a WITH(NOLOCK),MarketDB..RmPlace c WITH(NOLOCK)
		WHERE a.RecruitmentPlaceId=c.id
		AND a.ID IN (SELECT ID FROM #indextable) '
	
	--创建临时表 存放招聘会类型
	CREATE TABLE #RType(
		[Type] [int] NOT NULL
	)	
		
	INSERT INTO #RType
	SELECT distinct Type FROM #indextable

	--创建临时表 存放地区信息
	CREATE TABLE #Region(
		[ID] [int] NOT NULL,
		[Description] NVARCHAR(50) NULL,
		[OrderNo] INT NULL
	)	
	IF @dcRegionID = 0 --取省份信息
	BEGIN		
		INSERT INTO #Region (ID)
		SELECT distinct LEFT(dcRegionID,2) FROM #indextable		
		
		UPDATE a SET OrderNo = b.OrderNo,a.Description = b.Description FROM #Region a, MainDB..DcRegion b	
		WHERE a.ID = b.ID
	END
	
	IF LEN(@dcRegionID)=2 AND @PlaceID=0	--取城市信息
	BEGIN
		SET @SQL = '
		INSERT INTO #Region (ID)
		SELECT SUBSTRING(dcRegionID,0,5) '+@SQLTmp +
		' GROUP BY SUBSTRING(dcRegionID,0,5)'
		print '$$'+@SQL
		
		EXEC(@SQL)
		DELETE FROM #Region WHERE LEN(ID)=2
		
		UPDATE a SET OrderNo = b.OrderNo FROM #Region a, MainDB..DcRegion b WITH(NOLOCK)
		WHERE a.ID = b.ID 
		
		UPDATE a 
		SET a.Description = b.Description
		FROM #Region a,MainDB..dcRegion b
		WHERE a.ID = b.ID
	END
	
	--创建临时表 存放场馆
	CREATE TABLE #RmPlace(
		[ID] [int] NOT NULL,
		[PlaceName] NVARCHAR(100) NOT NULL,
		[Lng] decimal(8,5) NULL,
		[Lat] decimal(8,5) NULL
	)	
	
	IF @dcRegionID<>0 AND @PlaceID=0
	BEGIN
	SET @SQL = '
		INSERT INTO #RmPlace
		SELECT e.ID,e.PlaceName,e.Lng,e.Lat
		FROM MarketDB..RmPlace e WITH(NOLOCK),
		(	SELECT c.ID,count(*) cnt '+@SQLTmp+' group by c.ID
		)f 
		WHERE e.ID = f.ID 
		ORDER BY e.dcregionid,f.cnt'
		
		--PRINT(@SQL)
		EXEC(@SQL)
		print '$$'+@SQL
	END
	--获取招聘会列表
	DECLARE @RecordCount INT
	DECLARE @PageSize INT
	SET @PageSize = 20
    DECLARE @PageLowerBound  INT --定义此页的底码
    DECLARE @PageUpperBound  INT --定义此页的顶码
    SET @PageLowerBound = (@PageNo -1) * @pagesize
    SET @PageUpperBound = @PageLowerBound + @pagesize
	SELECT @RecordCount = COUNT(*) FROM #indextable
	DELETE FROM #indextable WHERE Num <= @PageLowerBound Or Num > @PageUpperBound
	--创建临时表 存放招聘会
	CREATE TABLE #Rm(
		[ID] [int] NOT NULL,
		[RecruitmentName] NVARCHAR(100) NULL,
		[EndDate] SMALLDATETIME NULL,
		[BeginDate] SMALLDATETIME NULL,
		[PlaceID] INT NULL,
		[PlaceName] NVARCHAR(100) NULL,
		[Address] NVARCHAR(200) NULL,
		[City] NVARCHAR(200) NULL,
		[Lng] VARCHAR(20) NULL,
		[Lat] VARCHAR(20) NULL,
		[mapbarid] VARCHAR(100) NULL,
		[dcregionid] VARCHAR(10) NULL,
		[IsSchool] VARCHAR(20) NULL,
		[OrderNo] [INT] NULL,
		RecruitmentDeptID INT NULL,
		[PhotoNum] [INT] NULL,
		[IsAttention] [INT] NULL,
		BusLine NVARCHAR(500)
	)	
	
	INSERT INTO #Rm
	SELECT a.ID,a.RecruitmentName,a.EndDate,a.BeginDate,c.id as PlaceID,c.PlaceName,
	c.Address,b.Description City,c.Lng, c.Lat,c.mapbarid,c.dcregionid,a.IsSchool,
	b.OrderNo,a.RecruitmentDeptID,0 AS PhotoNum,0 AS IsAttention,c.BusLine
	FROM #indextable e,MarketDB..Recruitment a WITH(NOLOCK),maindb..dcRegion b WITH(NOLOCK),MarketDB..RmPlace c WITH(NOLOCK),MarketDB..RmDept d WITH(NOLOCK)
	WHERE e.ID = a.ID
	AND d.ID=a.RecruitmentDeptID
	AND b.ID=c.dcRegionID
	AND a.RecruitmentPlaceId=c.id
	AND a.ManagerUserID IS NOT NULL
	ORDER BY e.Num ASC
	
	--修改照片上传数量
	UPDATE a
	SET PhotoNum = 
	(
		SELECT COUNT(*) 
		FROM marketdb..rmplacephoto m WITH(NOLOCK),marketdb..rmmyplace n WITH(NOLOCK) 
		WHERE m.rmmyplaceid=n.id 
		AND n.rmdeptid=a.RecruitmentDeptID 
		AND n.rmplaceid=a.PlaceID
		AND m.verifyDate is NOT NULL
	) FROM #Rm a
	
	--有招聘会的日期 （一个月之内）
	CREATE TABLE #RmDate(
		[Date] VARCHAR(30) 
	)	
	
	SET @SQL = '
	INSERT INTO #RmDate
		SELECT CONVERT(VARCHAR(10), a.BeginDate,20) 
		 FROM MarketDB..Recruitment a WITH(NOLOCK),dcRegion b WITH(NOLOCK),MarketDB..RmPlace c WITH(NOLOCK),MarketDB..RmDept d WITH(NOLOCK)
		WHERE d.ID=a.RecruitmentDeptID
		AND b.ID=c.dcRegionID
		AND a.RecruitmentPlaceId=c.id
		And a.IsPause=0 and d.IsPause=0 '+@WHERE2+' 
		AND BeginDate > DATEADD(ms,0,DATEADD(dd, DATEDIFF(dd,0,GETDATE()), 0))
		AND BeginDate <DATEADD(mm,1,GETDATE()) 
		GROUP BY CONVERT(VARCHAR(10), a.BeginDate,20) 
		HAVING COUNT(1)>0
	'

	EXEC(@SQL)
	
	SELECT @RecordCount CNT --总数
	SELECT * FROM #RType	--招聘会类型
  	SELECT * FROM #Region ORDER BY OrderNo	--地区  	
	SELECT * FROM #RmPlace	--场馆
	SELECT * FROM #Rm		--招聘会列表
	--有招聘会的日期
	SELECT * FROM #RmDate
	SET NOCOUNT OFF	
END
GO
/****** Object:  StoredProcedure [dbo].[ProcRecruitmentTop9Select]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ProcRecruitmentTop9Select]
(
	@ProvinceId INT
)
AS
--INSERT INTO procLog select 'ProcRecruitmentTop9Seleect', '', getdate()
BEGIN
	SELECT * FROM RecruitmentTop9 WITH(NOLOCK) WHERE ProvinceId = @ProvinceID ORDER BY RowID
END




GO
/****** Object:  StoredProcedure [dbo].[procRefererInsert]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--创建人 Lambo 20101013
--用于首页记录访问记录
CREATE PROCEDURE [dbo].[procRefererInsert]
(
	@province_id SMALLINT,
	@versionid SMALLINT,
	@referer VARCHAR(190),
	@ip VARCHAR(15),
	@keyve NVARCHAR(50)
)
AS
SET NOCOUNT ON
IF CHARINDEX(',', @ip) > 0
	SET @Ip = LEFT(@Ip, CHARINDEX(',', @Ip) - 1)
BEGIN
	SET NOCOUNT ON
	SELECT TOP 1 ip 
	FROM referer WITH(NOLOCK)
	WHERE versionid=@versionid 
	AND referer=@referer
	AND ip=@ip
	AND LoginDate > DATEADD(MINUTE, -10, GETDATE())	

	IF (@@ROWCOUNT=0) 
	BEGIN
		INSERT INTO referer (province_id,versionid,referer,ip,keywords)
		VALUES(ISNULL(@province_id, 0), ISNULL(@versionid, 0),@referer,@ip,@keyve)
	END 
	SET NOCOUNT OFF
END














GO
/****** Object:  StoredProcedure [dbo].[procRefererInsert2]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--创建人 Lambo 20101013
--用于首页记录访问记录
--sean 20150324 sean add sessionid
CREATE ProCEDURE [dbo].[procRefererInsert2]
(
	@Province_id SMALLINT,
	@Versionid SMALLINT,
	@Referer VARCHAR(190),
	@Ip VARCHAR(15),
	@Keyve NVARCHAR(50),
	@SessionId VARCHAR(30)
)
AS
SET NOCOUNT ON
IF CHARINDEX(',', @ip) > 0
	SET @Ip = LEFT(@Ip, CHARINDEX(',', @Ip) - 1)
BEGIN
	SET NOCOUNT ON
	SELECT TOP 1 Ip 
	FROM Referer WITH(NOLOCK)
	WHERE Versionid = @Versionid 
	AND Referer = @Referer
	AND Ip = @Ip
	AND LoginDate > DATEADD(MINUTE, -10, GETDATE())	

	IF (@@ROWCOUNT=0) 
	BEGIN
		INSERT INTO Referer(Province_id, Versionid, Referer, Ip, Keywords, SessionId)
		VALUES(ISNULL(@Province_id, 0), ISNULL(@Versionid, 0), @Referer, @Ip, @Keyve, @SessionId)
	END
END

GO
/****** Object:  StoredProcedure [dbo].[ProcRefuseIpInsert]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ProcRefuseIpInsert]
AS
BEGIN
	SELECT Ip, COUNT(*) VisitNumber, DATEADD(HOUR, 6, GETDATE()) ReleaseTime
	INTO #t
	FROM Searchip
	--WHERE AddDate > DATEADD(MINUTE, -30, GETDATE())
	GROUP BY ip
	HAVING COUNT(*) > 250

	INSERT INTO #t
	SELECT Ip, COUNT(*) VisitNumber, DATEADD(HOUR, 2, GETDATE()) ReleaseTime
	FROM Searchip
	--WHERE AddDate > DATEADD(MINUTE, -30, GETDATE())
	GROUP BY ip
	HAVING COUNT(*) BETWEEN 151 AND 250

	INSERT INTO #t
	SELECT Ip, COUNT(*) VisitNumber, DATEADD(MINUTE, 30, GETDATE()) ReleaseTime
	FROM Searchip
	WHERE AddDate > DATEADD(MINUTE, -5, GETDATE())
	AND IP NOT IN(SELECT IP FROM #t)
	GROUP BY ip
	HAVING COUNT(*) > 80

	DELETE #t WHERE Ip NOT LIKE '%.%'

	DELETE a
	FROM RefuseIp a, #t b
	WHERE a.Ip = b.Ip
	AND a.ReleaseTime < b.ReleaseTime
	AND a.IsForever = 0

	DELETE #t WHERE Ip IN(SELECT Ip FROM RefuseIp)

	INSERT RefuseIp(Ip, VisitNumber, ReleaseTime) SELECT Ip, VisitNumber, ReleaseTime FROM #t

	DELETE RefuseIp WHERE ReleaseTime < GETDATE() AND IsForever = 0

	DECLARE @Cnt INT, @Cnt2 INT
	SELECT @Cnt = COUNT(*)
	FROM SearchDb..paSearchCondition WITH(NOLOCK)
	WHERE LogTime > DATEADD(MINUTE, -1, GETDATE())
	SELECT @Cnt2 = SUM(SearchCount) FROM SearchCountLog WHERE Id > (SELECT TOP 1 ID - 10 FROM SearchCountLog ORDER BY Id DESC)
	INSERT INTO SearchCountLog SELECT @Cnt, GETDATE()
	SET @Cnt = (@Cnt * 10 + @Cnt2) / 40
	SET @Cnt = @Cnt * 0.5 

	IF @Cnt > 3000
		DELETE a FROM RefuseIp a, Ip_White b WHERE CHARINDEX(b.ip, a.Ip) > 0 AND RIGHT(a.Ip, 1) = 'a'
	ELSE IF @Cnt > 2600
		DELETE a FROM RefuseIp a, Ip_White b WHERE CHARINDEX(b.ip, a.Ip) > 0 AND RIGHT(a.Ip, 1) IN(SELECT A FROM dbo.FnSplit('0', ','))
	ELSE IF @Cnt > 2500
		DELETE a FROM RefuseIp a, Ip_White b WHERE CHARINDEX(b.ip, a.Ip) > 0 AND RIGHT(a.Ip, 1) IN(SELECT A FROM dbo.FnSplit('0,1', ','))
	ELSE IF @Cnt > 2400
		DELETE a FROM RefuseIp a, Ip_White b WHERE CHARINDEX(b.ip, a.Ip) > 0 AND RIGHT(a.Ip, 1) IN(SELECT A FROM dbo.FnSplit('0,1,2', ','))
	ELSE IF @Cnt > 2300
		DELETE a FROM RefuseIp a, Ip_White b WHERE CHARINDEX(b.ip, a.Ip) > 0 AND RIGHT(a.Ip, 1) IN(SELECT A FROM dbo.FnSplit('0,1,2,3', ','))
	ELSE IF @Cnt > 2200
		DELETE a FROM RefuseIp a, Ip_White b WHERE CHARINDEX(b.ip, a.Ip) > 0 AND RIGHT(a.Ip, 1) IN(SELECT A FROM dbo.FnSplit('0,1,2,3,4', ','))
	ELSE IF @Cnt > 2100
		DELETE a FROM RefuseIp a, Ip_White b WHERE CHARINDEX(b.ip, a.Ip) > 0 AND RIGHT(a.Ip, 1) IN(SELECT A FROM dbo.FnSplit('0,1,2,3,4,5', ','))
	ELSE IF @Cnt > 2000
		DELETE a FROM RefuseIp a, Ip_White b WHERE CHARINDEX(b.ip, a.Ip) > 0 AND RIGHT(a.Ip, 1) IN(SELECT A FROM dbo.FnSplit('0,1,2,3,4,5,6', ','))
	ELSE IF @Cnt > 1900
		DELETE a FROM RefuseIp a, Ip_White b WHERE CHARINDEX(b.ip, a.Ip) > 0 AND RIGHT(a.Ip, 1) IN(SELECT A FROM dbo.FnSplit('0,1,2,3,4,5,6,7', ','))
	ELSE IF @Cnt > 1800
		DELETE a FROM RefuseIp a, Ip_White b WHERE CHARINDEX(b.ip, a.Ip) > 0 AND RIGHT(a.Ip, 1) IN(SELECT A FROM dbo.FnSplit('0,1,2,3,4,5,6,7,8', ','))
	ELSE
		DELETE a FROM RefuseIp a, Ip_White b WHERE CHARINDEX(b.ip, a.Ip) > 0

	DELETE SearchIp WHERE AddDate < DATEADD(MINUTE, -30, GETDATE())
	update refuseip set isforever=1 where ip like '42.62.%'
	update refuseip set isforever=1 where ip like '42.156.%'
	update refuseip set isforever=1 where ip like '42.120.%'
	update refuseip set isforever=1 where ip like '208.115.1%'
	update refuseip set isforever=1 where ip like '212.7.%'
	update refuseip set isforever=1 where ip like '122.80.60.226'
--
--	SELECT LEFT(ip, LEN(ip) - CHARINDEX('.', REVERSE(ip))) ip INTO #1 FROM Searchip
--	DELETE #1 WHERE Ip NOT LIKE '%.%.%'
--	SELECT ip, COUNT(*) Cnt INTO #2 FROM #1 GROUP BY Ip
--
--	SELECT Ip, Cnt VisitNumber, DATEADD(HOUR, 6, GETDATE()) ReleaseTime
--	INTO #tt
--	FROM #2
--	WHERE Cnt > 1000
-- 
--	INSERT RefuseIp SELECT *, GETDATE(), 0 FROM #tt WHERE IP NOT IN(SELECT IP FROM RefuseIp)
END

GO
/****** Object:  StoredProcedure [dbo].[ProcReSendSmsMessage]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.4
--创建人：John
--说明：重新发送忘记密码通知短信
--#####################################################
CREATE PROCEDURE [dbo].[ProcReSendSmsMessage]
(
	@askNo VARCHAR(40)
)
AS
BEGIN
	DECLARE @cnt INT
	SELECT @cnt = COUNT(1) 
	FROM SmsMessageLog 
	WHERE mobile =
		(
			SELECT TOP 1 mobile 
			FROM paGetPasswordLog WITH(NOLOCK)
			WHERE askno = @askNo AND mobile IS NOT NULL
		 ) 
		AND adddate > CONVERT(VARCHAR(10), GETDATE(), 23)
		AND MsgType=104 
	IF @cnt < 5
	BEGIN
		INSERT INTO SmsMessageLog(SendMan, ManagerUserId, paMainId, caMainId, Mobile, MsgType, IsCat, Msg)
			SELECT TOP 1 SendMan, ManagerUSerId, paMainId, caMainId, Mobile, MsgType, IsCat, Msg 
			FROM smsmessagelog 
			WHERE mobile = 
					(
						SELECT TOP 1 mobile 
						FROM paGetPasswordLog WITH(NOLOCK) 
						WHERE askno = @askNo AND mobile IS NOT NULL
					) 
				AND adddate > CONVERT(VARCHAR(10), GETDATE(), 23) 
				AND MsgType=104 ORDER BY id DESC
		RETURN @cnt
	END
	ELSE
	BEGIN
		RETURN -1
	END
END


GO
/****** Object:  StoredProcedure [dbo].[procRmCompanyCvByCvMainIDSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.31
--创建人：Nick
--说明：
--#####################################################
CREATE PROCEDURE [dbo].[procRmCompanyCvByCvMainIDSelect]
(
	@CvMainID INT,
	@CpMainID INT
)
AS
BEGIN TRY
	SELECT 'x' FROM RmCompanyCv WITH(NOLOCK)
	WHERE cvMainID=@CvMainID AND cpMainID=@CpMainID
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[procRmInvitationCodeByPaMainIDSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.31
--创建人：Nick
--说明：获取该简历在招聘会的认证信息
--#####################################################
CREATE PROCEDURE [dbo].[procRmInvitationCodeByPaMainIDSelect]
(
	@paMainID VARCHAR(20)
)
AS
BEGIN TRY
	SELECT AddDate
	FROM marketdb..RmInvitationCode WITH(NOLOCK)
	WHERE pamainid=@paMainID 
	AND valid=1 
	AND rmprojectid=1
	AND adddate > GETDATE()-90
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[ProcRtx_LogSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE procedure [dbo].[ProcRtx_LogSelect]
AS
BEGIN
	SELECT TOP 10 * FROM Rtx_Log WHERE AddDate > CONVERT(VARCHAR(10), GETDATE(), 120) ORDER BY ID DESC
END
GO
/****** Object:  StoredProcedure [dbo].[ProcRtxNotifyLogBycaPlaintInsert]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ProcRtxNotifyLogBycaPlaintInsert]
AS
BEGIN
	IF EXISTS(SELECT 'x' FROM caPlaint WHERE ReplyType = 0)
	BEGIN
		SELECT caMainId, 9999 cpMainId, SPACE(20) Consultantid, Plaint, cvMainId INTO #t FROM caPlaint WHERE ReplyType = 0
		UPDATE a SET a.cpMainID = b.cpMainId
		FROM #t a, caMain b
		WHERE a.caMainId = b.Id
 
		UPDATE a SET a.ConsultantId = b.ConsultantId
		FROM #t a, cpMain b
		WHERE a.cpMainId = b.Id

		UPDATE a SET a.ConsultantId = b.Superior
		FROM #t a, ManagerUser b
		WHERE a.ConsultantId = b.Id
		AND (b.Status > 2 OR b.RtxStatus = 0)

		DELETE #t WHERE ISNULL(ConsultantId, '') = ''
		
		INSERT RtxNotifyLog
		SELECT ConsultantId, '您有新的投诉，请及时处理', Plaint +
			'  企业编号=' + LTRIM(STR(cpMainID)) + ' 简历帐号' + LTRIM(STR(cvMainID)+' http://sysback.51rc.com/newoa/Operate/Complaint/CaPlaint'),
			0, 0, 0, Null, GETDATE()
		FROM #t 
	END
END


GO
/****** Object:  StoredProcedure [dbo].[ProcRtxNotifyLogInsert]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


--#####################################################
--创建时间：2014.10.28
--创建人：John
--说明：RTX通知日志新增
--#####################################################
CREATE PROCEDURE [dbo].[ProcRtxNotifyLogInsert]
(
	@Receiver VARCHAR(2000),
	@RtxTitle NVARCHAR(50),
	@RtxMessage VARCHAR(1000),
	@SendType TINYINT,
	@ShowType TINYINT,
	@DelayTime SMALLINT
)
AS
SET NOCOUNT ON
BEGIN TRY
	IF @Receiver NOT LIKE '1,%'
		INSERT INTO RtxNotifyLog (Receiver, RtxTitle, RtxMessage, SendType, ShowType, DelayTime)
		SELECT @Receiver, @RtxTitle, @RtxMessage, @SendType, @ShowType, @DelayTime
END TRY
BEGIN CATCH
	INSERT INTO RtxNotifyLog (Receiver, RtxTitle, RtxMessage, SendType, ShowType, DelayTime)
	SELECT '112', 'Error:' + @RtxTitle, @Receiver + '|' + @RtxMessage, 0, 0, 1
END CATCH
GO
/****** Object:  StoredProcedure [dbo].[ProcRtxNotifyLogSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ProcRtxNotifyLogSelect]
AS
BEGIN
	DECLARE @t AS TABLE(
		ID int,
		Receiver varchar(2000),
		RtxTitle nvarchar(50),
		RtxMessage varchar(1000),
		SendType tinyint,
		DelayTime smallint,
		ShowType TinyInt,
		SendTime smalldatetime,
		AddTime smalldatetime,
		IsDelete BIT,
		IsSms BIT
	)

	INSERT INTO @t
	SELECT TOP 100 *, 0 IsDelete, 0 IsSms FROM RtxNotifyLog WITH(NOLOCK) WHERE SendTime IS NULL
	
	UPDATE @t SET IsDelete = 1
	WHERE SendType = 0
	AND NOT EXISTS(
		SELECT 'x' FROM ManagerUser WITH(NOLOCK)
		WHERE ID IN(SELECT * FROM dbo.Split(Receiver, ','))
		AND RtxStatus IN(1, 2)
		)
	--
	UPDATE @t SET IsSms = 1
	WHERE SendType = 2 
	AND NOT EXISTS(
		SELECT 'x' FROM ManagerUSer WITH(NOLOCK)
		WHERE ID IN(SELECT * FROM dbo.Split(Receiver, ','))
		AND RtxStatus IN(1, 2)
		)

	UPDATE RtxNotifyLog SET SendType = 4 WHERE ID IN(SELECT ID FROM @t WHERE IsDelete = 1)
	UPDATE RtxNotifyLog SET SendType = 5 WHERE ID IN(SELECT ID FROM @t WHERE IsSms = 1)
	UPDATE RtxNotifyLog SET SendTime = GETDATE() WHERE ID IN(SELECT ID FROM @t)

	INSERT INTO SmsMessageLog(SendMan, ManagerUSerID, Mobile, Msg, IsCat, SmsType, MsgType)
	SELECT 0, a.Receiver, b.Mobile, LEFT(a.RtxTitle + ',' + RtxMessage, 70), 0, 1, 205
	FROM @t a, Oadb..WorkUSer b WITH(NOLOCK)
	WHERE a.Receiver = b.ManagerUserId
	AND b.JobStatus < 3
	AND b.Mobile > ''
	AND a.Receiver NOT LIKE '%,%'
	AND a.IsSms = 1

	UPDATE @t SET Receiver = REPLACE(',' + Receiver + ',', ',1,', ',001,')
	UPDATE @t SET Receiver = SUBSTRING(Receiver, 2, LEN(Receiver) - 1)

	SELECT * FROM @t WHERE IsDelete = 0	

	INSERT INTO ServiceRunLog(ServiceId, RunRows, RunId, RunStatus, RunMessage)
	SELECT 2, @@RowCount, 0, 1, '提取Rtx数据'
END














GO
/****** Object:  StoredProcedure [dbo].[ProcSalaryAnalysisByJobTypeSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.3
--创建人：John
--说明：根据Jobtype和Region获取薪酬分析
--#####################################################
CREATE PROCEDURE [dbo].[ProcSalaryAnalysisByJobTypeSelect]
(
	@dcRegionID VARCHAR(4),
	@dcJobTypeID SMALLINT
)
AS
BEGIN
	SELECT TOP 10 * FROM reportdb..SalaryReportJobtype WHERE dcRegionid = @dcRegionID AND dcJobTypeID = @dcJobTypeID
END


GO
/****** Object:  StoredProcedure [dbo].[ProcSalaryAnalysisByRegionIDSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2014.10.31
--创建人：John
--说明：根据RegionID获取该地区的各项数据
--#####################################################
CREATE PROCEDURE [dbo].[ProcSalaryAnalysisByRegionIDSelect]
(
	@dcRegionID VARCHAR(6)
)
AS
BEGIN
	SELECT TOP 10 * FROM reportdb..SalaryReportRegion WHERE dcRegionid = @dcRegionID
END

GO
/****** Object:  StoredProcedure [dbo].[ProcSalaryRankByRegionIDSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2014.10.31
--创建人：John
--说明：根据RegionID 获取该地区岗位薪酬排行
--#####################################################
CREATE PROCEDURE [dbo].[ProcSalaryRankByRegionIDSelect]
(
	@dcRegionID VARCHAR(4)
)
AS
BEGIN
	SELECT TOP 10 dcJobTypeID,AvgSalary FROM reportdb..SalaryReportJobType WHERE dcRegionid = @dcRegionID ORDER BY AvgSalary DESC
END


GO
/****** Object:  StoredProcedure [dbo].[ProcSalaryReportBydcRegionIdSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--一分钟自动生成期望月薪
--harry
--2018-6-22 
CREATE PROCEDURE [dbo].[ProcSalaryReportBydcRegionIdSelect]
(
	@dcRegionID INT, 
	@dcJobTypeID varchar(100)
)
AS
SET NOCOUNT ON
BEGIN
	DECLARE @T AS TABLE(id INT identity(1,1),data INT) 
	INSERT INTO @T(data) 
	SELECT * FROM dbo.fnSplit(@dcJobTypeID, ',') 
	
	IF @dcRegionID=0
		SET @dcRegionID=32
	DECLARE @avgsalary INT
	
	DECLARE @jobtypeid INT, @id INT
	WHILE EXISTS(SELECT 'x' FROM @T)
	BEGIN
		SELECT TOP 1 @id = id,@jobtypeid=data FROM @T
		SELECT @avgsalary=AVG(AvgSalary)
		FROM reportdb..SalaryReportJobtype	
		WHERE LEFT(dcregionId,LEN(@dcRegionID))=@dcRegionID
		AND LEFT(dcJobTypeId,LEN(@jobtypeid))=@jobtypeid
		
		IF @avgsalary>0
		BEGIN
			DELETE FROM @T
		END
		ELSE
		BEGIN
			DELETE FROM @T WHERE id=@id
		END
	END 
	SELECT @avgsalary AS avgsalary
END
SET NOCOUNT OFF


GO
/****** Object:  StoredProcedure [dbo].[procSalaryReportCvMajorSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
---根据专业查工资
---harry
---2018-3-2
--procSalaryReportCvMajorSelect '网络工程',11,32
CREATE PROCEDURE [dbo].[procSalaryReportCvMajorSelect]
(
	@MajorName NVARCHAR(40),
	@dcMajorId INT,
	@dcRegionId INT	
)
AS
SET NOCOUNT ON
BEGIN
	CREATE TABLE #T
	(
		dcMajorId INT,
		majorName NVARCHAR(40),
		livePlace INT,
		dcJobTypeId SMALLINT,
		jobTypeName NVARCHAR(40), 
		cvCnt INT, --数量
		allCnt INT --结果总数据
	)
	CREATE TABLE #Ttemp
	(
		dcRegionId INT, 
		dcjobtypeId INT,
		averageExpectSalary INT,
		averageJobTypeSalary INT 
	)
	CREATE TABLE #Tsalary
	(
		averageSalary INT,
		averageExpectSalary INT,
		salary0Number INT,--0-3k
		salary3Number INT,--3-5k
		salary5Number INT,--5-7k
		salary7Number INT,--7-9k
		salary9Number INT,--9-11k
		salary11Number INT,--11k+ 
		expectSalary0Number INT,--0-3k
		expectSalary3Number INT,--3-5k
		expectSalary5Number INT,--5-7k
		expectSalary7Number INT,--7-9k
		expectSalary9Number INT,--9-11k
		expectSalary11Number INT,--11k+
	)
	
	DECLARE @allcnt INT, @selectByMajorName INT --结果数量，查询标志
        IF @MajorName= ''
        BEGIN
            SET @allcnt =0
        END
        ELSE
        BEGIN
	SELECT @allcnt = COUNT(1) 
	FROM reportdb..SalaryReportCvMajor
	WHERE majorname=@MajorName 
	AND LEFT(liveplace,LEN(@dcRegionId))=@dcRegionId
	END
	IF @allcnt >5--少于5条数据的用专业id查询
	BEGIN
		SET @selectByMajorName =1 
		--优先根据majorname查询，无结果时根据dcmajorid查询
		INSERT INTO #T(dcMajorId, majorName, livePlace, dcJobTypeId,jobTypeName, cvCnt, allCnt)
		SELECT TOP 5 @dcMajorId, @MajorName, LEFT(liveplace,LEN(@dcRegionId)), dcjobtypeId, dcJobType.[Description], count(1) cnt, @allcnt  
		FROM reportdb..SalaryReportCvMajor, dcJobType 
		WHERE majorname=@MajorName 
		AND LEFT(liveplace,LEN(@dcRegionId))=@dcRegionId
		AND reportdb..SalaryReportCvMajor.dcJobTypeId = dcJobType.Id
		GROUP BY LEFT(liveplace,LEN(@dcRegionId)),dcjobtypeId , dcJobType.[Description] 
		ORDER BY cnt DESC
	END
	ELSE
	BEGIN
		SELECT @allcnt = COUNT(1) 
		FROM reportdb..SalaryReportCvMajor
		WHERE DcMajorId=@dcMajorId 
		AND LEFT(liveplace,LEN(@dcRegionId))=@dcRegionId
		
		SET @selectByMajorName =0
		--优先根据dcmajorId查询，无结果时根据dcmajorid查询
		INSERT INTO #T(dcMajorId, majorName, livePlace, dcJobTypeId,jobTypeName, cvCnt, allCnt) 
		SELECT TOP 5 dcmajorid, '', LEFT(liveplace,LEN(@dcRegionId)), dcjobtypeId,  dcJobType.[Description], count(1) cnt, @allcnt   
		FROM reportdb..SalaryReportCvMajor, dcJobType
		WHERE DcMajorId=@dcMajorId 
		AND LEFT(liveplace,LEN(@dcRegionId))=@dcRegionId
		AND reportdb..SalaryReportCvMajor.dcJobTypeId = dcJobType.Id
		GROUP BY LEFT(liveplace,LEN(@dcRegionId)),dcjobtypeId ,dcmajorid, dcJobType.[Description] 
		ORDER BY cnt DESC
	END
	SELECT * FROM #T 
	
	--生成期望以及职位类别工资分布表
	IF @selectByMajorName =1 
	BEGIN
		INSERT INTO #Ttemp(dcRegionId, dcjobtypeId, averageExpectSalary)
		SELECT LEFT(liveplace,LEN(@dcRegionId))AS dcRegionId, dcjobtypeId, AVG(expectSalary) 
		FROM reportdb..SalaryReportCvMajor
		WHERE majorname=@MajorName 
		AND LEFT(liveplace,LEN(@dcRegionId))=@dcRegionId 
		GROUP BY LEFT(liveplace,LEN(@dcRegionId)), dcjobtypeId
	END
	ELSE
	BEGIN
		INSERT INTO #Ttemp(dcRegionId, dcjobtypeId, averageExpectSalary)
		SELECT LEFT(liveplace,LEN(@dcRegionId))AS dcRegionId, dcjobtypeId, AVG(expectSalary)   
		FROM reportdb..SalaryReportCvMajor
		WHERE DcMajorId=@dcMajorId 
		AND LEFT(liveplace,LEN(@dcRegionId))=@dcRegionId
		GROUP BY LEFT(liveplace,LEN(@dcRegionId)), dcjobtypeId
	END
	--每个职位列表的数据获取平均工资
	UPDATE a
	SET a.averageJobTypeSalary = b.AvgSalary
	FROM #Ttemp a, reportdb..SalaryReportJobtype b
	WHERE a.dcRegionId = b.dcRegionId 
	AND a.dcJobTypeId = b.dcJobTypeId
	--生成#Tsalary数据
	INSERT INTO #Tsalary 
	SELECT AVG(averageExpectSalary), 
		AVG(averageJobTypeSalary),
		SUM(CASE WHEN averageExpectSalary<3000 THEN 1 ELSE 0 END),
		SUM(CASE WHEN averageExpectSalary >= 3000 AND  averageExpectSalary <5000 THEN 1 ELSE 0 END),
		SUM(CASE WHEN averageExpectSalary >= 5000 AND  averageExpectSalary <7000 THEN 1 ELSE 0 END),
		SUM(CASE WHEN averageExpectSalary >= 7000 AND  averageExpectSalary <9000 THEN 1 ELSE 0 END),
		SUM(CASE WHEN averageExpectSalary >= 9000 AND  averageExpectSalary <11000 THEN 1 ELSE 0 END),
		SUM(CASE WHEN averageExpectSalary >= 11000 THEN 1 ELSE 0 END),
		SUM(CASE WHEN averageJobTypeSalary<3000 THEN 1 ELSE 0 END),
		SUM(CASE WHEN averageJobTypeSalary >= 3000 AND  averageJobTypeSalary <5000 THEN 1 ELSE 0 END),
		SUM(CASE WHEN averageJobTypeSalary >= 5000 AND  averageJobTypeSalary <7000 THEN 1 ELSE 0 END),
		SUM(CASE WHEN averageJobTypeSalary >= 7000 AND  averageJobTypeSalary <9000 THEN 1 ELSE 0 END),
		SUM(CASE WHEN averageJobTypeSalary >= 9000 AND  averageJobTypeSalary <11000 THEN 1 ELSE 0 END),
		SUM(CASE WHEN averageJobTypeSalary >= 11000 THEN 1 ELSE 0 END) 
	FROM #Ttemp
	
	SELECT * FROM #Tsalary
	
	--生成top5职位类别数据
	CREATE TABLE #Top5
	(
		dcMajorId INT, 
		majorName VARCHAR(40),
		livePlace INT, 
		dcJobTypeId SMALLINT,
		jobTypeName VARCHAR(100),
		averageSalary INT,
		salary0Number INT,--0-3k
		salary3Number INT,--3-5k
		salary5Number INT,--5-7k
		salary7Number INT,--7-9k
		salary9Number INT,--9-11k
		salary11Number INT--11k+ 
	)
	INSERT INTO #Top5 
	SELECT a.dcMajorId, a.majorName, a.livePlace, a.dcJobTypeId, a.jobTypeName, AVG(b.AvgSalary),
		SUM(ISNULL(b.Salary2,0)+ISNULL(b.Salary3,0)+ISNULL(b.Salary4,0)+ISNULL(b.Salary5,0)),
		SUM(ISNULL(b.Salary6,0)+ISNULL(b.Salary7,0)+ISNULL(b.Salary8,0)),
		SUM(ISNULL(b.Salary9,0)+ISNULL(b.Salary10,0)),
		SUM(ISNULL(b.Salary11,0)),
		SUM(ISNULL(b.Salary12,0)),
		SUM(ISNULL(b.Salary13,0)+ISNULL(b.Salary14,0)+ISNULL(b.Salary15,0)+ISNULL(b.Salary16,0))
	FROM #T a, reportdb..SalaryReportJobtype b
	WHERE a.livePlace = b.dcRegionId AND a.dcJobTypeId = b.dcJobTypeId
	GROUP BY a.dcMajorId, a.majorName, a.livePlace, a.dcJobTypeId, a.jobTypeName
	
	SELECT * FROM #Top5 --5个职位类别数据
	--生成10个高薪职位，每个职位类别选取2个职位 
    SELECT a.id,a.name,a.secondid,a.dcSalaryID,a.dcSalaryIDMax,a.caMainID,a.dcRegionId,a.dcEducationID,a.MinExperience,a.NeedNumber, ISNULL(c.IsOnline, 0) IsOnline,d.LogoFile AS logourl, d.SecondId AS cpSecondId, d.Name AS cpName 
    FROM Job a WITH(NOLOCK)
	INNER JOIN dcRegion b WITH(NOLOCK) ON a.dcRegionID = b.ID
	LEFT JOIN caOnline c WITH(NOLOCK) ON a.caMainId = c.caMainId
    LEFT JOIN cpMain d WITH(NOLOCK) ON a.cpMainId =d.id 
    WHERE a.id IN(SELECT DISTINCT TOP 10 jobid FROM(
				SELECT jobId,dcSalaryId  FROM reportdb..HighSalaryJob
				WHERE dcjobTypeId IN(select dcJobTypeId FROM #Top5 )
				AND dcRegionId=@dcRegionId 
				)a) ORDER BY  dcSalaryId DESC
	IF @selectByMajorName =1
		SELECT  @MajorName AS majorName
	ELSE 
		select Description AS majorName from dcmajor where id= @dcMajorId
	DROP TABLE #Ttemp
	DROP TABLE #Tsalary
	DROP TABLE #T
	DROP TABLE #Top5
END
SET NOCOUNT OFF

GO
/****** Object:  StoredProcedure [dbo].[procSalaryReportCvMajorSelectByMajorname]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
---获取各个省份TOP1专业信息
---harry
---2018-2-28
--procSalaryReportCvMajorSelectByMajorname
CREATE PROCEDURE [dbo].[procSalaryReportCvMajorSelectByMajorname]
AS
SET NOCOUNT ON
BEGIN
    SELECT LEFT(LivePlace,2)AS dcProvinceId ,majorname ,DcMajorId,count(1)AS cnt
    INTO #t 
    FROM reportdb..SalaryReportCvMajor 
    WHERE majorname !='所学专业未填写' AND majorName !='无' AND majorname!='其他' 
    GROUP BY majorname,LEFT(LivePlace,2),DcMajorId 
    
    TRUNCATE TABLE reportdb..salaryReportProvinceTop1Major
    
    INSERT INTO reportdb..salaryReportProvinceTop1Major(dcProvinceId, majorName, dcMajorId, majorTypeName)
    SELECT a.dcProvinceId, a.majorName, a.dcMajorId, b.Description AS majorTypeName
    FROM(
        SELECT dcProvinceId,majorName,dcMajorId,cnt,ROW_NUMBER() over( partition by dcProvinceId order by cnt DESC) provinceId
        FROM #t
        )AS a, dcmajor b
    WHERE a.provinceId = 1
    AND a.dcMajorId = b.id
    
    DROP TABLE #t
END
SET NOCOUNT OFF

GO
/****** Object:  StoredProcedure [dbo].[procsalaryReportProvinceTop1MajorSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
---获取省份从事数量做多的一个专业信息
---harry
---2018-2-28 
CREATE PROCEDURE [dbo].[procsalaryReportProvinceTop1MajorSelect]
(
	@dcProvinceId INT
)
AS
SET NOCOUNT ON
BEGIN 
	SELECT * 
	FROM reportdb..salaryReportProvinceTop1Major WITH(NOLOCK)
	WHERE dcProvinceId= @dcProvinceId
END
SET NOCOUNT OFF

GO
/****** Object:  StoredProcedure [dbo].[ProcSalaryReportRegionLogSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ProcSalaryReportRegionLogSelect]
(
	@ProvinceId INT
)
AS
BEGIN
	CREATE TABLE #t(dcRegionId VARCHAR(4), Region NVARCHAR(10), SalaryNow INT, SalaryOld INT)
	IF @ProvinceId != 32
		INSERT INTO #t(dcRegionId, SalaryNow)
		SELECT dcRegionId, AvgSalary SalaryNow
		FROM ReportDb..SalaryReportRegion
		WHERE dcRegionId LIKE LTRIM(STR(@ProvinceId)) + '__'
	ELSE
		INSERT INTO #t(dcRegionId, SalaryNow)
		SELECT dcRegionId, AvgSalary SalaryNow
		FROM ReportDb..SalaryReportRegion
		WHERE dcRegionId LIKE LTRIM(STR(@ProvinceId)) + '__'
		AND dcRegionId != 3212

--	AND Salary5 + Salary6 + Salary7 > 0

	UPDATE a SET a.SalaryOld = b.AvgSalary
	FROM #t a, ReportDb..SalaryReportRegionLog b
	WHERE a.dcRegionId = b.dcRegionId
	AND b.YearMonth = CONVERT(VARCHAR(6), DATEADD(Year, -1, GETDATE()), 112)
--	AND Salary5 + Salary6 + Salary7 > 0

	UPDATE a SET a.Region = b.Abbr FROM #t a, MainDb..dcRegion b WHERE a.dcRegionId = b.Id

	SELECT LEFT(Region, 3) Region, SalaryNow, CONVERT(INT, ISNULL(SalaryOld, SalaryNow) * 0.9) SalaryOld FROM #t ORDER BY SalaryNow DESC
END

GO
/****** Object:  StoredProcedure [dbo].[ProcSalaryReportRegionMinSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.3
--创建人：John
--说明：获取各地最近三年最底工资标准新闻
--修改：harry 最新年份无数据时，取之前的年份2018-1-11
--#####################################################
CREATE PROCEDURE [dbo].[ProcSalaryReportRegionMinSelect]
(
	@SalaryYearA VARCHAR(4),
	@SalaryYearB VARCHAR(4),
	@SalaryYearC VARCHAR(4)
)
AS
BEGIN	
	IF EXISTS(SELECT 'X' FROM Reportdb..SalaryReportRegionMin 
	WHERE SalaryYear = @SalaryYearA)
	BEGIN
		SELECT * FROM Reportdb..SalaryReportRegionMin 
		WHERE SalaryYear IN(@SalaryYearA,@SalaryYearB,@SalaryYearC) 
		ORDER BY dcRegionid,SalaryYear DESC
	END
	ELSE
	BEGIN
		SELECT * FROM Reportdb..SalaryReportRegionMin 
		WHERE SalaryYear IN(Convert(VARCHAR(4),Convert(INT,@SalaryYearA)-3),@SalaryYearB,@SalaryYearC) 
		ORDER BY dcRegionid,SalaryYear DESC
	END
END

 
GO
/****** Object:  StoredProcedure [dbo].[ProcSalaryReportSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--新版查工资
--harry
--2018-3-2
--ProcSalaryAnalysis 32,11,1,'' 
CREATE PROCEDURE [dbo].[ProcSalaryReportSelect]
(
	@dcRegionID INT, 
	@dcJobTypeID SMALLINT,--0表示未选择
	@dcExperienceId CHAR(1),--''表示未选择
	@dcEducationId CHAR(1),--''表示未选择
	@inputSalary INT--输入的金额
)
AS
SET NOCOUNT ON
BEGIN
	--职位信息临时表
	SELECT TOP 0 * INTO #tSalaryReport FROM reportdb..salaryReport
	SELECT TOP 0 * INTO #temp FROM reportdb..SalaryReportEducation
	ALTER TABLE #temp Add dcJobTypeId SMALLINT NULL, dcExperienceId SMALLINT NULL
	ALTER TABLE #temp ALTER COLUMN dcEducationId SMALLINT  NULL
	DECLARE @JobTypeGrade INT --职位类别grade
	IF @dcJobTypeID !=0
		SELECT @JobTypeGrade = grade 
		FROM dcJobType 
		WHERE id = @dcJobTypeID
	IF @dcRegionID = 0
		SET @dcRegionID = 32
	SET @dcRegionID = LEFT(@dcRegionID,4)
	IF @dcJobTypeID =0 AND @dcExperienceId ='' AND @dcEducationId =''---地区
	BEGIN
		SELECT TOP 10 * 
		FROM reportdb..SalaryReportRegion 
		WHERE dcRegionid = @dcRegionID
	END
	ELSE IF @dcJobTypeID !=0 AND @dcExperienceId ='' AND @dcEducationId =''---地区+职位类别
	BEGIN
		SELECT TOP 10 * 
		FROM reportdb..SalaryReportJobtype 
		WHERE dcRegionid = @dcRegionID 
		AND dcJobTypeID = @dcJobTypeID
	END
	ELSE IF @dcJobTypeID =0 AND @dcExperienceId !='' AND @dcEducationId =''--地区+经验
	BEGIN
		IF LEN(@dcRegionID)=2
		BEGIN
			SELECT LEFT(dcRegionid,2)dcRegionid ,dcExperienceId,AVG(AvgSalary) AvgSalary,
					SUM(JobNumber)JobNumber,SUM(Salary2) Salary2,SUM(Salary3) Salary3,SUM(Salary4) Salary4,
					SUM(Salary5) Salary5, SUM(Salary6) Salary6,	SUM(Salary7) Salary7, SUM(Salary8) Salary8,
					SUM(Salary9) Salary9, SUM(Salary10) Salary10, SUM(Salary11) Salary11, SUM(Salary12) Salary12,
					SUM(Salary13) Salary13,	SUM(Salary14) Salary14,	SUM(Salary15) Salary15,	SUM(Salary16) Salary16,
					SUM(Salary100) Salary100, SUM(ExperienceNumber0) ExperienceNumber0,	SUM(ExperienceNumber1) ExperienceNumber1, 
					SUM(ExperienceNumber2) ExperienceNumber2, SUM(ExperienceNumber3) ExperienceNumber3,	SUM(ExperienceNumber4) ExperienceNumber4, SUM(ExperienceNumber5) ExperienceNumber5,
					AVG(ExperienceSalary0)ExperienceSalary0, AVG(ExperienceSalary1)ExperienceSalary1, AVG(ExperienceSalary2)ExperienceSalary2,
					AVG(ExperienceSalary3)ExperienceSalary3, AVG(ExperienceSalary4)ExperienceSalary4, AVG(ExperienceSalary5)ExperienceSalary5, SUM(EducationNumber1)EducationNumber1,
					SUM(EducationNumber2)EducationNumber2,	SUM(EducationNumber3)EducationNumber3,	SUM(EducationNumber4)EducationNumber4,
					SUM(EducationNumber5)EducationNumber5,	SUM(EducationNumber6)EducationNumber6,	SUM(EducationNumber7)EducationNumber7,
					SUM(EducationNumber8)EducationNumber8,	SUM(EducationNumber100)EducationNumber100,  AVG(EducationSalary1)EducationSalary1,	AVG(EducationSalary2)EducationSalary2,
					AVG(EducationSalary3)EducationSalary3,	AVG(EducationSalary4)EducationSalary4,	AVG(EducationSalary5)EducationSalary5,
					AVG(EducationSalary6)EducationSalary6,	AVG(EducationSalary7)EducationSalary7,	AVG(EducationSalary8)EducationSalary8,	AVG(EducationSalary100)EducationSalary100,
					SUM(CompanyKindNumber1)CompanyKindNumber1,	SUM(CompanyKindNumber2)CompanyKindNumber2,	SUM(CompanyKindNumber3)CompanyKindNumber3,
					SUM(CompanyKindNumber4)CompanyKindNumber4,	SUM(CompanyKindNumber5)CompanyKindNumber5,	SUM(CompanyKindNumber6)CompanyKindNumber6,
					SUM(CompanyKindNumber7)CompanyKindNumber7,	SUM(CompanyKindNumber8)CompanyKindNumber8,	SUM(CompanyKindNumber9)CompanyKindNumber9,
					SUM(CompanyKindNumber10)CompanyKindNumber10,	SUM(CompanyKindNumber100)CompanyKindNumber100,
					SUM(CompanySizeNumber1)CompanySizeNumber1,	SUM(CompanySizeNumber2)CompanySizeNumber2,	SUM(CompanySizeNumber3)CompanySizeNumber3,
					SUM(CompanySizeNumber4)CompanySizeNumber4,	SUM(CompanySizeNumber5)CompanySizeNumber5,	SUM(CompanySizeNumber6)CompanySizeNumber6 
			FROM reportdb..SalaryReportExperience  
			WHERE  dcExperienceId = @dcExperienceId and LEFT(dcRegionid,2) = @dcRegionID 
			GROUP BY LEFT(dcRegionid,2),dcExperienceId
		END
		ELSE
		BEGIN
			SELECT TOP 10 * 
			FROM reportdb..SalaryReportExperience  
			WHERE dcRegionid = @dcRegionID 
			AND dcExperienceId = CONVERT(INT,@dcExperienceId)
		END
	END
	ELSE IF @dcJobTypeID =0 AND @dcExperienceId ='' AND @dcEducationId !=''--地区+学历
	BEGIN
		IF LEN(@dcRegionID)=2
		BEGIN
			SELECT LEFT(dcRegionid,2)dcRegionid ,dcEducationId, AVG(AvgSalary) AvgSalary,
					SUM(JobNumber)JobNumber,SUM(Salary2) Salary2,SUM(Salary3) Salary3,SUM(Salary4) Salary4,
					SUM(Salary5) Salary5, SUM(Salary6) Salary6,	SUM(Salary7) Salary7, SUM(Salary8) Salary8,
					SUM(Salary9) Salary9, SUM(Salary10) Salary10, SUM(Salary11) Salary11, SUM(Salary12) Salary12,
					SUM(Salary13) Salary13,	SUM(Salary14) Salary14,	SUM(Salary15) Salary15,	SUM(Salary16) Salary16,
					SUM(Salary100) Salary100, SUM(ExperienceNumber0) ExperienceNumber0,	SUM(ExperienceNumber1) ExperienceNumber1, 
					SUM(ExperienceNumber2) ExperienceNumber2, SUM(ExperienceNumber3) ExperienceNumber3,	SUM(ExperienceNumber4) ExperienceNumber4, SUM(ExperienceNumber5) ExperienceNumber5,
					AVG(ExperienceSalary0)ExperienceSalary0, AVG(ExperienceSalary1)ExperienceSalary1, AVG(ExperienceSalary2)ExperienceSalary2,
					AVG(ExperienceSalary3)ExperienceSalary3, AVG(ExperienceSalary4)ExperienceSalary4,  AVG(ExperienceSalary5)ExperienceSalary5, SUM(EducationNumber1)EducationNumber1,
					SUM(EducationNumber2)EducationNumber2,	SUM(EducationNumber3)EducationNumber3,	SUM(EducationNumber4)EducationNumber4,
					SUM(EducationNumber5)EducationNumber5,	SUM(EducationNumber6)EducationNumber6,	SUM(EducationNumber7)EducationNumber7,
					SUM(EducationNumber8)EducationNumber8,	SUM(EducationNumber100)EducationNumber100,	AVG(EducationSalary1)EducationSalary1,	AVG(EducationSalary2)EducationSalary2,
					AVG(EducationSalary3)EducationSalary3,	AVG(EducationSalary4)EducationSalary4,	AVG(EducationSalary5)EducationSalary5,
					AVG(EducationSalary6)EducationSalary6,	AVG(EducationSalary7)EducationSalary7,	AVG(EducationSalary8)EducationSalary8,	AVG(EducationSalary100)EducationSalary100,
					SUM(CompanyKindNumber1)CompanyKindNumber1,	SUM(CompanyKindNumber2)CompanyKindNumber2,	SUM(CompanyKindNumber3)CompanyKindNumber3,
					SUM(CompanyKindNumber4)CompanyKindNumber4,	SUM(CompanyKindNumber5)CompanyKindNumber5,	SUM(CompanyKindNumber6)CompanyKindNumber6,
					SUM(CompanyKindNumber7)CompanyKindNumber7,	SUM(CompanyKindNumber8)CompanyKindNumber8,	SUM(CompanyKindNumber9)CompanyKindNumber9,
					SUM(CompanyKindNumber10)CompanyKindNumber10,	SUM(CompanyKindNumber100)CompanyKindNumber100,
					SUM(CompanySizeNumber1)CompanySizeNumber1,	SUM(CompanySizeNumber2)CompanySizeNumber2,	SUM(CompanySizeNumber3)CompanySizeNumber3,
					SUM(CompanySizeNumber4)CompanySizeNumber4,	SUM(CompanySizeNumber5)CompanySizeNumber5,	SUM(CompanySizeNumber6)CompanySizeNumber6 
			FROM reportdb..SalaryReportEducation  
			WHERE  dcEducationId = @dcEducationId and LEFT(dcRegionid,2) = @dcRegionID 
			GROUP BY LEFT(dcRegionid,2), dcEducationId
		END
		ELSE
		BEGIN
			SELECT TOP 10 * 
			FROM reportdb..SalaryReportEducation  
			WHERE dcRegionid = @dcRegionID 
			AND dcEducationId = CONVERT(INT,@dcEducationId)
		END
	END
	ELSE IF @dcJobTypeID =0 AND @dcExperienceId !='' AND @dcEducationId !=''--地区+学历+经验
	BEGIN
		IF LEN(@dcRegionID)=2
		BEGIN
			SELECT LEFT(dcRegionid,2)dcRegionid ,dcEducationId, dcExperienceId, AVG(AvgSalary) AvgSalary,
					SUM(JobNumber)JobNumber,SUM(Salary2) Salary2,SUM(Salary3) Salary3,SUM(Salary4) Salary4,
					SUM(Salary5) Salary5, SUM(Salary6) Salary6,	SUM(Salary7) Salary7, SUM(Salary8) Salary8,
					SUM(Salary9) Salary9, SUM(Salary10) Salary10, SUM(Salary11) Salary11, SUM(Salary12) Salary12,
					SUM(Salary13) Salary13,	SUM(Salary14) Salary14,	SUM(Salary15) Salary15,	SUM(Salary16) Salary16,
					SUM(Salary100) Salary100, SUM(ExperienceNumber0) ExperienceNumber0,	SUM(ExperienceNumber1) ExperienceNumber1, 
					SUM(ExperienceNumber2) ExperienceNumber2, SUM(ExperienceNumber3) ExperienceNumber3,	SUM(ExperienceNumber4) ExperienceNumber4,	SUM(ExperienceNumber5) ExperienceNumber5,
					AVG(ExperienceSalary0)ExperienceSalary0, AVG(ExperienceSalary1)ExperienceSalary1, AVG(ExperienceSalary2)ExperienceSalary2,
					AVG(ExperienceSalary3)ExperienceSalary3, AVG(ExperienceSalary4)ExperienceSalary4, AVG(ExperienceSalary5)ExperienceSalary5, SUM(EducationNumber1)EducationNumber1,
					SUM(EducationNumber2)EducationNumber2,	SUM(EducationNumber3)EducationNumber3,	SUM(EducationNumber4)EducationNumber4,
					SUM(EducationNumber5)EducationNumber5,	SUM(EducationNumber6)EducationNumber6,	SUM(EducationNumber7)EducationNumber7,
					SUM(EducationNumber8)EducationNumber8,	SUM(EducationNumber100)EducationNumber100, AVG(EducationSalary1)EducationSalary1,	AVG(EducationSalary2)EducationSalary2,
					AVG(EducationSalary3)EducationSalary3,	AVG(EducationSalary4)EducationSalary4,	AVG(EducationSalary5)EducationSalary5,
					AVG(EducationSalary6)EducationSalary6,	AVG(EducationSalary7)EducationSalary7,	AVG(EducationSalary8)EducationSalary8,	AVG(EducationSalary100)EducationSalary100,
					SUM(CompanyKindNumber1)CompanyKindNumber1,	SUM(CompanyKindNumber2)CompanyKindNumber2,	SUM(CompanyKindNumber3)CompanyKindNumber3,
					SUM(CompanyKindNumber4)CompanyKindNumber4,	SUM(CompanyKindNumber5)CompanyKindNumber5,	SUM(CompanyKindNumber6)CompanyKindNumber6,
					SUM(CompanyKindNumber7)CompanyKindNumber7,	SUM(CompanyKindNumber8)CompanyKindNumber8,	SUM(CompanyKindNumber9)CompanyKindNumber9,
					SUM(CompanyKindNumber10)CompanyKindNumber10,	SUM(CompanyKindNumber100)CompanyKindNumber100,
					SUM(CompanySizeNumber1)CompanySizeNumber1,	SUM(CompanySizeNumber2)CompanySizeNumber2,	SUM(CompanySizeNumber3)CompanySizeNumber3,
					SUM(CompanySizeNumber4)CompanySizeNumber4,	SUM(CompanySizeNumber5)CompanySizeNumber5,	SUM(CompanySizeNumber6)CompanySizeNumber6 
			FROM reportdb..SalaryReportEducationExperience  
			WHERE  dcEducationId = @dcEducationId and LEFT(dcRegionid,2) = @dcRegionID AND dcExperienceId =  CONVERT(INT,@dcExperienceId)
			GROUP BY LEFT(dcRegionid,2), dcEducationId, dcExperienceId
		END
		ELSE
		BEGIN
			SELECT TOP 10 * 
			FROM reportdb..SalaryReportEducationExperience  
			WHERE dcRegionid = @dcRegionID 
			AND dcEducationId = CONVERT(INT,@dcEducationId) 
			AND dcExperienceId = CONVERT(INT,@dcExperienceId)
		END
	END
	ELSE IF @dcJobTypeID !=0 AND @dcExperienceId !='' AND @dcEducationId =''--地区+职位类别+经验
	BEGIN
		IF @JobTypeGrade = 2--职位类别大类（全部）
		BEGIN
			INSERT INTO #tSalaryReport
			SELECT * FROM reportdb..salaryReport 
			WHERE LEFT(dcregionId,LEN(@dcRegionID)) = @dcRegionID 
			AND (dcJobTypeId = @dcJobTypeID OR dcJobTypeId IN(SELECT id FROM dcjobtype  where (id = @dcJobTypeID OR ID IN(select id from dcjobType where parentid= @dcJobTypeID))))
			AND MinExperience = CONVERT(INT,@dcExperienceId)
		END
		ELSE
		BEGIN
			INSERT INTO #tSalaryReport
			SELECT * FROM reportdb..salaryReport 
			WHERE LEFT(dcregionId,LEN(@dcRegionID)) = @dcRegionID 
			AND dcJobTypeId = @dcJobTypeID 
			AND MinExperience = CONVERT(INT,@dcExperienceId)
		END
	END
	ELSE IF @dcJobTypeID !=0 AND @dcExperienceId ='' AND @dcEducationId !=''--地区+职位类别+学历
	BEGIN
		IF @JobTypeGrade = 2--职位类别大类（全部）
		BEGIN
			INSERT INTO #tSalaryReport
			SELECT * FROM reportdb..salaryReport 
			WHERE LEFT(dcregionId,LEN(@dcRegionID)) = @dcRegionID 
			AND (dcJobTypeId = @dcJobTypeID OR dcJobTypeId IN(SELECT id FROM dcjobtype  where (id = @dcJobTypeID OR ID IN(select id from dcjobType where parentid= @dcJobTypeID))))
			AND dcEducationId = CONVERT(INT,@dcEducationId)
		END
		ELSE
		BEGIN
			INSERT INTO #tSalaryReport
			SELECT * FROM reportdb..salaryReport 
			WHERE LEFT(dcregionId,LEN(@dcRegionID)) = @dcRegionID 
			AND dcJobTypeId = @dcJobTypeID 
			AND dcEducationId = CONVERT(INT,@dcEducationId)
		END
	END
	ELSE IF @dcJobTypeID !=0 AND @dcExperienceId !='' AND @dcEducationId !=''--地区+职位类别+经验+学历
	BEGIN
		IF @JobTypeGrade = 2--职位类别大类（全部）
		BEGIN
			INSERT INTO #tSalaryReport
			SELECT * FROM reportdb..salaryReport 
			WHERE LEFT(dcregionId,LEN(@dcRegionID)) = @dcRegionID 
			AND (dcJobTypeId = @dcJobTypeID OR dcJobTypeId IN(SELECT id FROM dcjobtype  where (id = @dcJobTypeID OR ID IN(select id from dcjobType where parentid= @dcJobTypeID))))
			AND dcEducationId = CONVERT(INT,@dcEducationId) 
			AND MinExperience = CONVERT(INT,@dcExperienceId) 
		END
		ELSE
		BEGIN
			INSERT INTO #tSalaryReport
			SELECT * FROM reportdb..salaryReport 
			WHERE LEFT(dcregionId,LEN(@dcRegionID)) = @dcRegionID 
			AND dcJobTypeId = @dcJobTypeID 
			AND dcEducationId = CONVERT(INT,@dcEducationId) 
			AND MinExperience = CONVERT(INT,@dcExperienceId)
		END
	END
	
	IF @dcJobTypeID !=0
	BEGIN
		IF NOT EXISTS(SELECT 'X' FROM #tSalaryReport) AND(@dcExperienceId !='' OR @dcEducationId !='')
		BEGIN
			SELECT TOP 0 * FROM #tSalaryReport
		END
		ELSE
		BEGIN
			--汇总用的临时表
			CREATE TABLE #Sum(dcRegionId VARCHAR(4), dcJobTypeId INT, dcEducationId SMALLINT, dcExperienceId SMALLINT, Item INT, Cnt INt, Salary INT)
		 
			IF @dcJobTypeID !=0 AND @dcExperienceId !='' AND @dcEducationId =''--地区+职位类别+经验
			BEGIN
				---统计全部薪酬信息  
				SELECT LEFT(dcregionId,LEN(@dcRegionID)) AS dcRegionId,dcJobTypeId, MinExperience AS dcExperienceId, CASE WHEN dcSalaryId = 17 THEN 16 ELSE dcSalaryId END dcSalaryId, COUNT(*) Cnt 	
				INTO #t1
				FROM #tSalaryReport WITH(NOLOCK) 
				GROUP BY LEFT(dcregionId,LEN(@dcRegionID)),CASE WHEN dcSalaryId = 17 THEN 16 ELSE dcSalaryId END, dcJobTypeId, MinExperience

				SELECT dcJobTypeId, MinExperience AS  dcExperienceId, LEFT(dcregionId,LEN(@dcRegionID)) AS dcRegionId,AVG(Salary) Salary
				INTO #tj1
				FROM #tSalaryReport WITH(NOLOCK)
				GROUP BY dcJobTypeId, MinExperience,LEFT(dcregionId,LEN(@dcRegionID)) 
				
				----记录到SalaryReportEducationExperience
				INSERT INTO #temp(dcRegionId, dcJobTypeId, dcExperienceId, Salary2, Salary3, Salary4, Salary5, Salary6, Salary7, Salary8, Salary9, Salary10, Salary11, Salary12, Salary13, Salary14, Salary15, Salary16, Salary100)
				SELECT dcRegionId, dcJobTypeId, dcExperienceId, [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12], [13], [14], [15], [16], [100]
				FROM (
					SELECT LEFT(dcregionId,LEN(@dcRegionID)) AS dcRegionId, dcJobTypeId, dcExperienceId, dcSalaryId, Cnt 
					FROM #t1
					) AS SourceTable
				PIVOT
				(
					AVG(Cnt)
					FOR dcSalaryId IN ([2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12], [13], [14], [15], [16], [100])
				) AS PivotTable

				UPDATE a SET a.AvgSalary = b.Salary FROM #temp a, #tj1 b 
				WHERE a.dcJobTypeId = b.dcJobTypeId AND a.dcRegionId = b.dcRegionId AND a.dcExperienceId = b.dcExperienceId
				DROP TABLE #t1
				DROP TABLE #tj1 

				TRUNCATE TABLE #Sum	
		 
				----统计企业性质
				INSERT INTO #Sum
				SELECT LEFT(dcregionId,LEN(@dcRegionID)) AS dcRegionId, dcJobTypeId,NULL, MinExperience, ISNULL(dcCompanyKindId,0) dcCompanyKindId, COUNT(DISTINCT cpMainId) Cnt, 0
				FROM #tSalaryReport WITH(NOLOCK)
				GROUP BY LEFT(dcregionId,LEN(@dcRegionID)), dcJobTypeId, MinExperience, ISNULL(dcCompanyKindId,0) 

 				UPDATE a
				SET a.CompanyKindNumber1 = b.[1],
					a.CompanyKindNumber2 = b.[2],
					a.CompanyKindNumber3 = b.[3],
					a.CompanyKindNumber4 = b.[4],
					a.CompanyKindNumber5 = b.[5],
					a.CompanyKindNumber6 = b.[6],
					a.CompanyKindNumber7 = b.[7],
					a.CompanyKindNumber8 = b.[8],
					a.CompanyKindNumber9 = b.[9],
					a.CompanyKindNumber10 = b.[10],
					a.CompanyKindNumber100 = b.[100]
				FROM #temp a, (
					SELECT dcRegionId, dcJobTypeId, dcExperienceId, [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [100]
					FROM (
						SELECT dcRegionId, dcJobTypeId, dcExperienceId, Item, Cnt
						FROM #Sum
						) AS SourceTable
					PIVOT
					(
						AVG(Cnt)
						FOR Item IN ([1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [100])
					) AS PivotTable) b
				WHERE a.dcRegionId = b.dcRegionId
				AND a.dcJobTypeId = b.dcJobTypeId
				AND a.dcExperienceId = b.dcExperienceId

				TRUNCATE TABLE #Sum	
				----统计企业规模
				INSERT INTO #Sum
				SELECT LEFT(dcregionId,LEN(@dcRegionID)) AS dcRegionId, dcJobTypeId,NULL, MinExperience AS dcExperienceId, ISNULL(dcCompanySizeId,0) dcCompanySizeId, COUNT(DISTINCT cpMainId) Cnt, 0
				FROM #tSalaryReport WITH(NOLOCK)
				GROUP BY LEFT(dcregionId,LEN(@dcRegionID)), dcJobTypeId, MinExperience, ISNULL(dcCompanySizeId,0)  
				
 				UPDATE a
				SET a.CompanySizeNumber1 = b.[1],
					a.CompanySizeNumber2 = b.[2],
					a.CompanySizeNumber3 = b.[3],
					a.CompanySizeNumber4 = b.[4],
					a.CompanySizeNumber5 = b.[5],
					a.CompanySizeNumber6 = b.[6]
				FROM #temp a, (
					SELECT dcRegionId, dcJobTypeId, dcExperienceId, [1], [2], [3], [4], [5], [6]
					FROM (
						SELECT dcRegionId, dcJobTypeId, dcExperienceId, Item, Cnt
						FROM #Sum
						) AS SourceTable
					PIVOT
					(
						AVG(Cnt)
						FOR Item IN ([1], [2], [3], [4], [5], [6])
					) AS PivotTable) b
				WHERE a.dcRegionId = b.dcRegionId
				AND a.dcJobTypeId = b.dcJobTypeId
				AND a.dcExperienceId = b.dcExperienceId
				
				 
				----统计学历
				TRUNCATE TABLE #Sum	
				INSERT INTO #Sum
				SELECT LEFT(dcregionId,LEN(@dcRegionID)) AS dcRegionId, dcJobTypeId,ISNULL(dcEducationId,0), MinExperience, ISNULL(dcEducationId,0) dcEducationId, COUNT(DISTINCT cpMainId) Cnt, 0
				FROM #tSalaryReport WITH(NOLOCK)
				GROUP BY LEFT(dcregionId,LEN(@dcRegionID)), dcJobTypeId, MinExperience, ISNULL(dcEducationId,0)  

				UPDATE a
				SET a.EducationNumber1 = b.[1],
					a.EducationNumber2 = b.[2],
					a.EducationNumber3 = b.[3],
					a.EducationNumber4 = b.[4],
					a.EducationNumber5 = b.[5],
					a.EducationNumber6 = b.[6],
					a.EducationNumber7 = b.[7],
					a.EducationNumber8 = b.[8],
					a.EducationNumber100 = b.[100]
				FROM #temp a, (
					SELECT dcRegionId, dcExperienceId, dcJobTypeId,[1], [2], [3], [4], [5], [6], [7], [8], [100]
					FROM (
						SELECT dcRegionId, dcExperienceId, dcJobTypeId,Item, Cnt
						FROM #Sum
						) AS SourceTable
					PIVOT
					(
						AVG(Cnt)
						FOR Item IN ([1], [2], [3], [4], [5], [6], [7], [8], [100])
					) AS PivotTable) b
				WHERE a.dcRegionId = b.dcRegionId
				AND a.dcExperienceId = b.dcExperienceId
				AND a.dcJobTypeId =b.dcJobTypeId

				
				--更新经验月薪 
				UPDATE a
				SET a.ExperienceSalary0=b.ExperienceSalary0,
					a.ExperienceSalary1=b.ExperienceSalary1,
					a.ExperienceSalary2=b.ExperienceSalary2,
					a.ExperienceSalary3=b.ExperienceSalary3,
					a.ExperienceSalary4=b.ExperienceSalary4,
					a.ExperienceSalary5=b.ExperienceSalary5  
				FROM #temp a, reportdb..SalaryReportJobtype b
				WHERE a.dcRegionId = b.dcRegionId
				AND a.dcJobTypeID = b.dcJobTypeID 
				
				IF LEN(@dcRegionID)= 2 OR @JobTypeGrade = 2--全省数据或职位类别大类（全部）
				BEGIN 
					SELECT LEFT(dcRegionid,LEN(@dcRegionID))dcRegionid ,dcExperienceId,dcEducationId, LEFT(dcJobTypeID, LEN(@dcJobTypeID)) dcJobTypeID, AVG(AvgSalary) AvgSalary,
						SUM(JobNumber)JobNumber,SUM(Salary2) Salary2,SUM(Salary3) Salary3,SUM(Salary4) Salary4,
						SUM(Salary5) Salary5, SUM(Salary6) Salary6,	SUM(Salary7) Salary7, SUM(Salary8) Salary8,
						SUM(Salary9) Salary9, SUM(Salary10) Salary10, SUM(Salary11) Salary11, SUM(Salary12) Salary12,
						SUM(Salary13) Salary13,	SUM(Salary14) Salary14,	SUM(Salary15) Salary15,	SUM(Salary16) Salary16,
						SUM(Salary100) Salary100, SUM(ExperienceNumber0) ExperienceNumber0,	SUM(ExperienceNumber1) ExperienceNumber1, 
						SUM(ExperienceNumber2) ExperienceNumber2, SUM(ExperienceNumber3) ExperienceNumber3,	SUM(ExperienceNumber4) ExperienceNumber4, SUM(ExperienceNumber5) ExperienceNumber5,
						AVG(ExperienceSalary0)ExperienceSalary0, AVG(ExperienceSalary1)ExperienceSalary1, AVG(ExperienceSalary2)ExperienceSalary2,
						AVG(ExperienceSalary3)ExperienceSalary3, AVG(ExperienceSalary4)ExperienceSalary4,  AVG(ExperienceSalary5)ExperienceSalary5, SUM(EducationNumber1)EducationNumber1,
						SUM(EducationNumber2)EducationNumber2,	SUM(EducationNumber3)EducationNumber3,	SUM(EducationNumber4)EducationNumber4,
						SUM(EducationNumber5)EducationNumber5,	SUM(EducationNumber6)EducationNumber6,	SUM(EducationNumber7)EducationNumber7,
						SUM(EducationNumber8)EducationNumber8,	SUM(EducationNumber100)EducationNumber100, AVG(EducationSalary1)EducationSalary1,	AVG(EducationSalary2)EducationSalary2,
						AVG(EducationSalary3)EducationSalary3,	AVG(EducationSalary4)EducationSalary4,	AVG(EducationSalary5)EducationSalary5,
						AVG(EducationSalary6)EducationSalary6,	AVG(EducationSalary7)EducationSalary7,	AVG(EducationSalary8)EducationSalary8,	AVG(EducationSalary100)EducationSalary100,
						SUM(CompanyKindNumber1)CompanyKindNumber1,	SUM(CompanyKindNumber2)CompanyKindNumber2,	SUM(CompanyKindNumber3)CompanyKindNumber3,
						SUM(CompanyKindNumber4)CompanyKindNumber4,	SUM(CompanyKindNumber5)CompanyKindNumber5,	SUM(CompanyKindNumber6)CompanyKindNumber6,
						SUM(CompanyKindNumber7)CompanyKindNumber7,	SUM(CompanyKindNumber8)CompanyKindNumber8,	SUM(CompanyKindNumber9)CompanyKindNumber9,
						SUM(CompanyKindNumber10)CompanyKindNumber10,	SUM(CompanyKindNumber100)CompanyKindNumber100,
						SUM(CompanySizeNumber1)CompanySizeNumber1,	SUM(CompanySizeNumber2)CompanySizeNumber2,	SUM(CompanySizeNumber3)CompanySizeNumber3,
						SUM(CompanySizeNumber4)CompanySizeNumber4,	SUM(CompanySizeNumber5)CompanySizeNumber5,	SUM(CompanySizeNumber6)CompanySizeNumber6 
					FROM #temp   
					GROUP BY LEFT(dcRegionid,LEN(@dcRegionID)),dcExperienceId, dcEducationId,LEFT(dcJobTypeID, LEN(@dcJobTypeID))
				END
				ELSE
				BEGIN
					SELECT TOP 10 * FROM #temp
				END
				DROP TABLE #temp
				DROP TABLE #Sum	 
			END
			ELSE IF @dcJobTypeID !=0 AND @dcExperienceId ='' AND @dcEducationId !=''--地区+职位类别+学历
			BEGIN
					---统计全部薪酬信息   
				SELECT LEFT(dcregionId,LEN(@dcRegionID)) AS dcRegionId,dcJobTypeId, dcEducationId, CASE WHEN dcSalaryId = 17 THEN 16 ELSE dcSalaryId END dcSalaryId, COUNT(*) Cnt 	
				INTO #t2
				FROM #tSalaryReport 
				GROUP BY LEFT(dcregionId,LEN(@dcRegionID)),CASE WHEN dcSalaryId = 17 THEN 16 ELSE dcSalaryId END, dcJobTypeId, dcEducationId

				SELECT dcJobTypeId, dcEducationId, LEFT(dcregionId,LEN(@dcRegionID)) AS dcRegionId,AVG(Salary) Salary
				INTO #tj2
				FROM #tSalaryReport
				GROUP BY dcJobTypeId, dcEducationId,LEFT(dcregionId,LEN(@dcRegionID)) 
				
				----记录到SalaryReportEducationExperience
				INSERT INTO #temp(dcRegionId, dcJobTypeId, dcEducationId, Salary2, Salary3, Salary4, Salary5, Salary6, Salary7, Salary8, Salary9, Salary10, Salary11, Salary12, Salary13, Salary14, Salary15, Salary16, Salary100)
				SELECT dcRegionId, dcJobTypeId, dcEducationId, [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12], [13], [14], [15], [16], [100]
				FROM (
					SELECT LEFT(dcregionId,LEN(@dcRegionID)) AS dcRegionId, dcJobTypeId, dcEducationId, dcSalaryId, Cnt 
					FROM #t2
					) AS SourceTable
				PIVOT
				(
					AVG(Cnt)
					FOR dcSalaryId IN ([2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12], [13], [14], [15], [16], [100])
				) AS PivotTable

				UPDATE a SET a.AvgSalary = b.Salary FROM #temp a, #tj2 b 
				WHERE a.dcJobTypeId = b.dcJobTypeId AND a.dcRegionId = b.dcRegionId AND a.dcEducationId = b.dcEducationId
				DROP TABLE #t2
				DROP TABLE #tj2 

				TRUNCATE TABLE #Sum	
 		 
				----统计企业性质
				INSERT INTO #Sum
				SELECT LEFT(dcregionId,LEN(@dcRegionID)) AS dcRegionId, dcJobTypeId, dcEducationId,NULL, ISNULL(dcCompanyKindId,0) dcCompanyKindId, COUNT(DISTINCT cpMainId) Cnt, 0
				FROM #tSalaryReport WITH(NOLOCK)
				GROUP BY LEFT(dcregionId,LEN(@dcRegionID)), dcJobTypeId, dcEducationId, ISNULL(dcCompanyKindId,0) 

 				UPDATE a
				SET a.CompanyKindNumber1 = b.[1],
					a.CompanyKindNumber2 = b.[2],
					a.CompanyKindNumber3 = b.[3],
					a.CompanyKindNumber4 = b.[4],
					a.CompanyKindNumber5 = b.[5],
					a.CompanyKindNumber6 = b.[6],
					a.CompanyKindNumber7 = b.[7],
					a.CompanyKindNumber8 = b.[8],
					a.CompanyKindNumber9 = b.[9],
					a.CompanyKindNumber10 = b.[10],
					a.CompanyKindNumber100 = b.[100]
				FROM #temp a, (
					SELECT dcRegionId, dcJobTypeId, dcEducationId, [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [100]
					FROM (
						SELECT dcRegionId, dcJobTypeId, dcEducationId, Item, Cnt
						FROM #Sum
						) AS SourceTable
					PIVOT
					(
						AVG(Cnt)
						FOR Item IN ([1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [100])
					) AS PivotTable) b
				WHERE a.dcRegionId = b.dcRegionId
				AND a.dcJobTypeId = b.dcJobTypeId
				AND a.dcEducationId = b.dcEducationId

				TRUNCATE TABLE #Sum	
				----统计企业规模
				INSERT INTO #Sum
				SELECT LEFT(dcregionId,LEN(@dcRegionID)) AS dcRegionId, dcJobTypeId, dcEducationId,NULL, ISNULL(dcCompanySizeId,0) dcCompanySizeId, COUNT(DISTINCT cpMainId) Cnt, 0
				FROM #tSalaryReport WITH(NOLOCK)
				GROUP BY LEFT(dcregionId,LEN(@dcRegionID)), dcJobTypeId, dcEducationId, ISNULL(dcCompanySizeId,0)  
				
 				UPDATE a
				SET a.CompanySizeNumber1 = b.[1],
					a.CompanySizeNumber2 = b.[2],
					a.CompanySizeNumber3 = b.[3],
					a.CompanySizeNumber4 = b.[4],
					a.CompanySizeNumber5 = b.[5],
					a.CompanySizeNumber6 = b.[6]
				FROM #temp a, (
					SELECT dcRegionId, dcJobTypeId, dcEducationId, [1], [2], [3], [4], [5], [6]
					FROM (
						SELECT dcRegionId, dcJobTypeId, dcEducationId, Item, Cnt
						FROM #Sum
						) AS SourceTable
					PIVOT
					(
						AVG(Cnt)
						FOR Item IN ([1], [2], [3], [4], [5], [6])
					) AS PivotTable) b
				WHERE a.dcRegionId = b.dcRegionId
				AND a.dcJobTypeId = b.dcJobTypeId
				AND a.dcEducationId = b.dcEducationId
				
		
				----统计工作经历
				TRUNCATE TABLE #Sum	
				INSERT INTO #Sum
				SELECT LEFT(dcregionId,LEN(@dcRegionID)) AS dcRegionId, dcJobTypeId,ISNULL(dcEducationId,0), MinExperience, ISNULL(MinExperience,0) MinExperience, COUNT(DISTINCT cpMainId) Cnt, 0
				FROM #tSalaryReport WITH(NOLOCK)
				GROUP BY LEFT(dcregionId,LEN(@dcRegionID)), dcJobTypeId, MinExperience, ISNULL(dcEducationId,0)  
				 
				------工作经历数量 
		 
				UPDATE a
				SET a.ExperienceNumber0 = b.[0],
					a.ExperienceNumber1 = b.[1],
					a.ExperienceNumber2 = b.[2],
					a.ExperienceNumber3 = b.[3],
					a.ExperienceNumber4 = b.[4],
					a.ExperienceNumber5 = b.[5]
				FROM #temp a, (
					SELECT dcRegionId,dcJobTypeId, dcEducationId,[0], [1], [2], [3], [4], [5]
					FROM (
						SELECT dcRegionId, dcJobTypeId,dcEducationId, Item, Cnt
						FROM #Sum
						) AS SourceTable
					PIVOT
					(
						AVG(Cnt)
						FOR Item IN ([0], [1], [2], [3], [4], [5])
					) AS PivotTable) b
				WHERE a.dcRegionId = b.dcRegionId
				AND a.dcEducationId = b.dcEducationId
				AND a.dcJobTypeId = b.dcJobTypeId

				
				--更新学历月薪 
				UPDATE a
				SET a.EducationSalary1=b.EducationSalary1,
					a.EducationSalary2=b.EducationSalary2,
					a.EducationSalary3=b.EducationSalary3,
					a.EducationSalary4=b.EducationSalary4,
					a.EducationSalary5=b.EducationSalary5,
					a.EducationSalary6=b.EducationSalary6,
					a.EducationSalary7=b.EducationSalary7,
					a.EducationSalary8=b.EducationSalary8,
					a.EducationSalary100=b.EducationSalary100 
				FROM #temp a, reportdb..SalaryReportJobtype b
				WHERE a.dcRegionId = b.dcRegionId
				AND a.dcJobTypeId = b.dcJobTypeId 
				
				IF LEN(@dcRegionID)= 2 OR @JobTypeGrade = 2--全省数据或职位类别大类（全部）
				BEGIN 
					SELECT LEFT(dcRegionid,LEN(@dcRegionID))dcRegionid ,dcExperienceId,dcEducationId, LEFT(dcJobTypeID, LEN(@dcJobTypeID)) dcJobTypeID, AVG(AvgSalary) AvgSalary,
						SUM(JobNumber)JobNumber,SUM(Salary2) Salary2,SUM(Salary3) Salary3,SUM(Salary4) Salary4,
						SUM(Salary5) Salary5, SUM(Salary6) Salary6,	SUM(Salary7) Salary7, SUM(Salary8) Salary8,
						SUM(Salary9) Salary9, SUM(Salary10) Salary10, SUM(Salary11) Salary11, SUM(Salary12) Salary12,
						SUM(Salary13) Salary13,	SUM(Salary14) Salary14,	SUM(Salary15) Salary15,	SUM(Salary16) Salary16,
						SUM(Salary100) Salary100, SUM(ExperienceNumber0) ExperienceNumber0,	SUM(ExperienceNumber1) ExperienceNumber1, 
						SUM(ExperienceNumber2) ExperienceNumber2, SUM(ExperienceNumber3) ExperienceNumber3,	SUM(ExperienceNumber4) ExperienceNumber4,	SUM(ExperienceNumber5) ExperienceNumber5,
						AVG(ExperienceSalary0)ExperienceSalary0, AVG(ExperienceSalary1)ExperienceSalary1, AVG(ExperienceSalary2)ExperienceSalary2,
						AVG(ExperienceSalary3)ExperienceSalary3, AVG(ExperienceSalary4)ExperienceSalary4,  AVG(ExperienceSalary5)ExperienceSalary5, SUM(EducationNumber1)EducationNumber1,
						SUM(EducationNumber2)EducationNumber2,	SUM(EducationNumber3)EducationNumber3,	SUM(EducationNumber4)EducationNumber4,
						SUM(EducationNumber5)EducationNumber5,	SUM(EducationNumber6)EducationNumber6,	SUM(EducationNumber7)EducationNumber7,
						SUM(EducationNumber8)EducationNumber8,	SUM(EducationNumber100)EducationNumber100, AVG(EducationSalary1)EducationSalary1,	AVG(EducationSalary2)EducationSalary2,
						AVG(EducationSalary3)EducationSalary3,	AVG(EducationSalary4)EducationSalary4,	AVG(EducationSalary5)EducationSalary5,
						AVG(EducationSalary6)EducationSalary6,	AVG(EducationSalary7)EducationSalary7,	AVG(EducationSalary8)EducationSalary8,	AVG(EducationSalary100)EducationSalary100,
						SUM(CompanyKindNumber1)CompanyKindNumber1,	SUM(CompanyKindNumber2)CompanyKindNumber2,	SUM(CompanyKindNumber3)CompanyKindNumber3,
						SUM(CompanyKindNumber4)CompanyKindNumber4,	SUM(CompanyKindNumber5)CompanyKindNumber5,	SUM(CompanyKindNumber6)CompanyKindNumber6,
						SUM(CompanyKindNumber7)CompanyKindNumber7,	SUM(CompanyKindNumber8)CompanyKindNumber8,	SUM(CompanyKindNumber9)CompanyKindNumber9,
						SUM(CompanyKindNumber10)CompanyKindNumber10,	SUM(CompanyKindNumber100)CompanyKindNumber100,
						SUM(CompanySizeNumber1)CompanySizeNumber1,	SUM(CompanySizeNumber2)CompanySizeNumber2,	SUM(CompanySizeNumber3)CompanySizeNumber3,
						SUM(CompanySizeNumber4)CompanySizeNumber4,	SUM(CompanySizeNumber5)CompanySizeNumber5,	SUM(CompanySizeNumber6)CompanySizeNumber6 
					FROM #temp   
					GROUP BY LEFT(dcRegionid,LEN(@dcRegionID)),dcExperienceId, dcEducationId,LEFT(dcJobTypeID, LEN(@dcJobTypeID))
				END
				ELSE
				BEGIN
					SELECT TOP 10 * FROM #temp
				END
				DROP TABLE #temp
				DROP TABLE #Sum	 
			END
			ELSE IF @dcJobTypeID !=0 AND @dcExperienceId !='' AND @dcEducationId !=''--地区+职位类别+经验+学历
			BEGIN
				---统计全部薪酬信息  
				SELECT LEFT(dcregionId,LEN(@dcRegionID)) AS dcRegionId,dcJobTypeId, dcEducationId, MinExperience AS dcExperienceId, CASE WHEN dcSalaryId = 17 THEN 16 ELSE dcSalaryId END dcSalaryId, COUNT(*) Cnt 	
				INTO #t3
				FROM #tSalaryReport 
				GROUP BY LEFT(dcregionId,LEN(@dcRegionID)),CASE WHEN dcSalaryId = 17 THEN 16 ELSE dcSalaryId END, dcJobTypeId, dcEducationId, MinExperience

				SELECT dcJobTypeId, dcEducationId, MinExperience AS  dcExperienceId, LEFT(dcregionId,LEN(@dcRegionID)) AS dcRegionId,AVG(Salary) Salary
				INTO #tj3
				FROM #tSalaryReport
				GROUP BY dcJobTypeId, MinExperience,LEFT(dcregionId,LEN(@dcRegionID)), dcEducationId 
				
				----记录到SalaryReportEducationExperience
				INSERT INTO #temp(dcRegionId, dcJobTypeId, dcEducationId, dcExperienceId, Salary2, Salary3, Salary4, Salary5, Salary6, Salary7, Salary8, Salary9, Salary10, Salary11, Salary12, Salary13, Salary14, Salary15, Salary16, Salary100)
				SELECT dcRegionId, dcJobTypeId, dcEducationId, dcExperienceId, [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12], [13], [14], [15], [16], [100]
				FROM (
					SELECT LEFT(dcregionId,LEN(@dcRegionID)) AS dcRegionId, dcJobTypeId, dcEducationId, dcExperienceId, dcSalaryId, Cnt 
					FROM #t3
					) AS SourceTable
				PIVOT
				(
					AVG(Cnt)
					FOR dcSalaryId IN ([2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12], [13], [14], [15], [16], [100])
				) AS PivotTable

				UPDATE a SET a.AvgSalary = b.Salary FROM #temp a, #tj3 b 
				WHERE a.dcJobTypeId = b.dcJobTypeId AND a.dcRegionId = b.dcRegionId AND a.dcExperienceId = b.dcExperienceId AND a.dcEducationId = b.dcEducationId
				DROP TABLE #t3
				DROP TABLE #tj3 

				TRUNCATE TABLE #Sum	

				----统计企业性质
				INSERT INTO #Sum
				SELECT LEFT(dcregionId,LEN(@dcRegionID)) AS dcRegionId, dcJobTypeId, dcEducationId, MinExperience AS dcExperienceId, ISNULL(dcCompanyKindId,0) dcCompanyKindId, COUNT(DISTINCT cpMainId) Cnt, 0
				FROM #tSalaryReport WITH(NOLOCK)
				GROUP BY LEFT(dcregionId,LEN(@dcRegionID)), dcJobTypeId, dcEducationId, MinExperience, ISNULL(dcCompanyKindId,0) 

 				UPDATE a
				SET a.CompanyKindNumber1 = b.[1],
					a.CompanyKindNumber2 = b.[2],
					a.CompanyKindNumber3 = b.[3],
					a.CompanyKindNumber4 = b.[4],
					a.CompanyKindNumber5 = b.[5],
					a.CompanyKindNumber6 = b.[6],
					a.CompanyKindNumber7 = b.[7],
					a.CompanyKindNumber8 = b.[8],
					a.CompanyKindNumber9 = b.[9],
					a.CompanyKindNumber10 = b.[10],
					a.CompanyKindNumber100 = b.[100]
				FROM #temp a, (
					SELECT dcRegionId, dcJobTypeId, dcEducationId, dcExperienceId, [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [100]
					FROM (
						SELECT dcRegionId, dcJobTypeId, dcEducationId, dcExperienceId, Item, Cnt
						FROM #Sum
						) AS SourceTable
					PIVOT
					(
						AVG(Cnt)
						FOR Item IN ([1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [100])
					) AS PivotTable) b
				WHERE a.dcRegionId = b.dcRegionId
				AND a.dcJobTypeId = b.dcJobTypeId
				AND a.dcExperienceId = b.dcExperienceId
				AND a.dcEducationId = b.dcEducationId

				TRUNCATE TABLE #Sum	
				----统计企业规模
				INSERT INTO #Sum
				SELECT LEFT(dcregionId,LEN(@dcRegionID)) AS dcRegionId, dcJobTypeId, dcEducationId, MinExperience AS dcExperienceId, ISNULL(dcCompanySizeId,0) dcCompanySizeId, COUNT(DISTINCT cpMainId) Cnt, 0
				FROM #tSalaryReport WITH(NOLOCK)
				GROUP BY LEFT(dcregionId,LEN(@dcRegionID)), dcJobTypeId, dcEducationId, MinExperience, ISNULL(dcCompanySizeId,0)  
				
 				UPDATE a
				SET a.CompanySizeNumber1 = b.[1],
					a.CompanySizeNumber2 = b.[2],
					a.CompanySizeNumber3 = b.[3],
					a.CompanySizeNumber4 = b.[4],
					a.CompanySizeNumber5 = b.[5],
					a.CompanySizeNumber6 = b.[6]
				FROM #temp a, (
					SELECT dcRegionId, dcJobTypeId, dcEducationId, dcExperienceId, [1], [2], [3], [4], [5], [6]
					FROM (
						SELECT dcRegionId, dcJobTypeId, dcEducationId, dcExperienceId, Item, Cnt
						FROM #Sum
						) AS SourceTable
					PIVOT
					(
						AVG(Cnt)
						FOR Item IN ([1], [2], [3], [4], [5], [6])
					) AS PivotTable) b
				WHERE a.dcRegionId = b.dcRegionId
				AND a.dcJobTypeId = b.dcJobTypeId
				AND a.dcExperienceId = b.dcExperienceId
				AND a.dcEducationId = b.dcEducationId
				
				--更新经验月薪@dcExperienceId CHAR(1)@dcEducationId CHAR(1)  
				--更新experiencesalary
				SELECT * INTO #tExperiencesalary2 FROM (
					SELECT avg(Salary)salary,LEFT(dcregionId,LEN(@dcRegionID))dcRegionId,MinExperience, dcJobTypeID,dcEducationId 
					FROM reportdb..salaryReport 
					WHERE dcEducationId=@dcEducationId AND dcJobTypeId =@dcJobTypeID AND LEFT(dcregionId,LEN(@dcRegionID))=@dcRegionID
					GROUP BY LEFT(dcregionId,LEN(@dcRegionID)),MinExperience,dcJobTypeID,dcEducationId
					)AS p 
					PIVOT(AVG(salary)FOR MinExperience IN([0],[1],[2],[3],[4],[5]))AS T
				--更新
				UPDATE a
				SET a.ExperienceSalary0=b.[0],
					a.ExperienceSalary1=b.[1],
					a.ExperienceSalary2=b.[2],
					a.ExperienceSalary3=b.[3],
					a.ExperienceSalary4=b.[4],
					a.ExperienceSalary5=b.[5]  
				FROM #temp a, #tExperiencesalary2 b
				WHERE a.dcRegionId = b.dcRegionId
				AND a.dcJobTypeID = b.dcJobTypeID
				AND a.dcEducationId = b.dcEducationId
				DROP TABLE  #tExperiencesalary2
				
				--更新学历月薪
				SELECT * INTO #tEducationsalary2 FROM (
					SELECT avg(Salary)salary,LEFT(dcregionId,LEN(@dcRegionID))dcRegionId,dcEducationId, dcJobTypeId,MinExperience  
					FROM reportdb..salaryReport
					WHERE MinExperience=@dcExperienceId AND dcJobTypeId =@dcJobTypeID AND LEFT(dcregionId,LEN(@dcRegionID))=@dcRegionID
					GROUP BY LEFT(dcregionId,LEN(@dcRegionID)),dcEducationId,dcJobTypeId,MinExperience
					)AS p 
					PIVOT(AVG(salary)FOR dcEducationId IN([1],[2],[3],[4],[5],[6],[7],[8],[100]))AS T
				--更新
				UPDATE a
				SET a.EducationSalary1=b.[1],
					a.EducationSalary2=b.[2],
					a.EducationSalary3=b.[3],
					a.EducationSalary4=b.[4],
					a.EducationSalary5=b.[5],
					a.EducationSalary6=b.[6],
					a.EducationSalary7=b.[7],
					a.EducationSalary8=b.[8],
					a.EducationSalary100=b.[100] 
				FROM #temp a, #tEducationsalary2 b
				WHERE a.dcRegionId = b.dcRegionId
				AND a.dcJobTypeId = b.dcJobTypeId
				AND a.dcExperienceId = b.MinExperience
				DROP TABLE  #tEducationsalary2
				
				IF LEN(@dcRegionID)= 2 OR @JobTypeGrade = 2--全省数据或职位类别大类（全部）
				BEGIN 
					SELECT LEFT(dcRegionid,LEN(@dcRegionID))dcRegionid ,dcExperienceId,dcEducationId, LEFT(dcJobTypeID, LEN(@dcJobTypeID)) dcJobTypeID, AVG(AvgSalary) AvgSalary,
						SUM(JobNumber)JobNumber,SUM(Salary2) Salary2,SUM(Salary3) Salary3,SUM(Salary4) Salary4,
						SUM(Salary5) Salary5, SUM(Salary6) Salary6,	SUM(Salary7) Salary7, SUM(Salary8) Salary8,
						SUM(Salary9) Salary9, SUM(Salary10) Salary10, SUM(Salary11) Salary11, SUM(Salary12) Salary12,
						SUM(Salary13) Salary13,	SUM(Salary14) Salary14,	SUM(Salary15) Salary15,	SUM(Salary16) Salary16,
						SUM(Salary100) Salary100, SUM(ExperienceNumber0) ExperienceNumber0,	SUM(ExperienceNumber1) ExperienceNumber1, 
						SUM(ExperienceNumber2) ExperienceNumber2, SUM(ExperienceNumber3) ExperienceNumber3,	SUM(ExperienceNumber4) ExperienceNumber4,	SUM(ExperienceNumber5) ExperienceNumber5,
						AVG(ExperienceSalary0)ExperienceSalary0, AVG(ExperienceSalary1)ExperienceSalary1, AVG(ExperienceSalary2)ExperienceSalary2,
						AVG(ExperienceSalary3)ExperienceSalary3, AVG(ExperienceSalary4)ExperienceSalary4,  AVG(ExperienceSalary5)ExperienceSalary5, SUM(EducationNumber1)EducationNumber1,
						SUM(EducationNumber2)EducationNumber2,	SUM(EducationNumber3)EducationNumber3,	SUM(EducationNumber4)EducationNumber4,
						SUM(EducationNumber5)EducationNumber5,	SUM(EducationNumber6)EducationNumber6,	SUM(EducationNumber7)EducationNumber7,
						SUM(EducationNumber8)EducationNumber8,	SUM(EducationNumber100)EducationNumber100,	AVG(EducationSalary1)EducationSalary1,	AVG(EducationSalary2)EducationSalary2,
						AVG(EducationSalary3)EducationSalary3,	AVG(EducationSalary4)EducationSalary4,	AVG(EducationSalary5)EducationSalary5,
						AVG(EducationSalary6)EducationSalary6,	AVG(EducationSalary7)EducationSalary7,	AVG(EducationSalary8)EducationSalary8,	AVG(EducationSalary100)EducationSalary100,
						SUM(CompanyKindNumber1)CompanyKindNumber1,	SUM(CompanyKindNumber2)CompanyKindNumber2,	SUM(CompanyKindNumber3)CompanyKindNumber3,
						SUM(CompanyKindNumber4)CompanyKindNumber4,	SUM(CompanyKindNumber5)CompanyKindNumber5,	SUM(CompanyKindNumber6)CompanyKindNumber6,
						SUM(CompanyKindNumber7)CompanyKindNumber7,	SUM(CompanyKindNumber8)CompanyKindNumber8,	SUM(CompanyKindNumber9)CompanyKindNumber9,
						SUM(CompanyKindNumber10)CompanyKindNumber10,	SUM(CompanyKindNumber100)CompanyKindNumber100,
						SUM(CompanySizeNumber1)CompanySizeNumber1,	SUM(CompanySizeNumber2)CompanySizeNumber2,	SUM(CompanySizeNumber3)CompanySizeNumber3,
						SUM(CompanySizeNumber4)CompanySizeNumber4,	SUM(CompanySizeNumber5)CompanySizeNumber5,	SUM(CompanySizeNumber6)CompanySizeNumber6 
					FROM #temp   
					GROUP BY LEFT(dcRegionid,LEN(@dcRegionID)),dcExperienceId, dcEducationId,LEFT(dcJobTypeID, LEN(@dcJobTypeID))
				END
				ELSE
				BEGIN
					SELECT TOP 10 * FROM #temp
				END
				DROP TABLE #temp
				DROP TABLE #Sum	 
			END
		END
	END
	--查询输入的金额占据的百分比
	IF @inputSalary !=0
	BEGIN
		DECLARE @allcnt INT, @lesscnt INT
		IF @dcJobTypeID =0
		BEGIN
			IF @dcExperienceId=''
			BEGIN
				IF @dcEducationId=''
				BEGIN
					SELECT @allcnt=COUNT(1) FROM reportdb..salaryReport
					WHERE LEFT(dcregionId,LEN(@dcRegionID))=@dcRegionID
					
					SELECT @lesscnt=COUNT(1) FROM reportdb..salaryReport
					WHERE LEFT(dcregionId,LEN(@dcRegionID))=@dcRegionID
					AND Salary<@inputSalary
				END
				ELSE
				BEGIN
					SELECT @allcnt=COUNT(1) FROM reportdb..salaryReport
					WHERE LEFT(dcregionId,LEN(@dcRegionID))=@dcRegionID
					AND dcEducationId =@dcEducationId
					
					SELECT @lesscnt=COUNT(1) FROM reportdb..salaryReport
					WHERE LEFT(dcregionId,LEN(@dcRegionID))=@dcRegionID
					AND dcEducationId =@dcEducationId
					AND Salary<@inputSalary
				END
			END
			ELSE
			BEGIN
				IF @dcEducationId=''
				BEGIN
					SELECT @allcnt=COUNT(1) FROM reportdb..salaryReport
					WHERE LEFT(dcregionId,LEN(@dcRegionID))=@dcRegionID
					AND MinExperience =@dcExperienceId

					SELECT @lesscnt=COUNT(1) FROM reportdb..salaryReport
					WHERE LEFT(dcregionId,LEN(@dcRegionID))=@dcRegionID
					AND Salary<@inputSalary
					AND MinExperience =@dcExperienceId
				END
				ELSE
				BEGIN
					SELECT @allcnt=COUNT(1) FROM reportdb..salaryReport
					WHERE LEFT(dcregionId,LEN(@dcRegionID))=@dcRegionID
					AND dcEducationId =@dcEducationId
					AND MinExperience =@dcExperienceId

					SELECT @lesscnt=COUNT(1) FROM reportdb..salaryReport
					WHERE LEFT(dcregionId,LEN(@dcRegionID))=@dcRegionID
					AND dcEducationId =@dcEducationId
					AND Salary<@inputSalary
					AND MinExperience =@dcExperienceId
				END
			END
		END
		ELSE
		BEGIN
			IF @dcExperienceId=''
			BEGIN
				IF @dcEducationId=''
				BEGIN
					SELECT @allcnt=COUNT(1) FROM reportdb..salaryReport
					WHERE LEFT(dcregionId,LEN(@dcRegionID))=@dcRegionID
					AND LEFT(dcJobtypeId,LEN(@dcJobTypeId)) =@dcJobTypeId
					
					SELECT @lesscnt=COUNT(1) FROM reportdb..salaryReport
					WHERE LEFT(dcregionId,LEN(@dcRegionID))=@dcRegionID
					AND LEFT(dcJobtypeId,LEN(@dcJobTypeId))=@dcJobTypeId
					AND Salary<@inputSalary
				END
				ELSE
				BEGIN
					SELECT @allcnt=COUNT(1) FROM reportdb..salaryReport
					WHERE LEFT(dcregionId,LEN(@dcRegionID))=@dcRegionID
					AND dcEducationId =@dcEducationId
					AND LEFT(dcJobtypeId,LEN(@dcJobTypeId)) =@dcJobTypeId
					
					SELECT @lesscnt=COUNT(1) FROM reportdb..salaryReport
					WHERE LEFT(dcregionId,LEN(@dcRegionID))=@dcRegionID
					AND dcEducationId =@dcEducationId
					AND LEFT(dcJobtypeId,LEN(@dcJobTypeId)) =@dcJobTypeId
					AND Salary<@inputSalary
				END
			END
			ELSE
			BEGIN
				IF @dcEducationId=''
				BEGIN
					SELECT @allcnt=COUNT(1) FROM reportdb..salaryReport
					WHERE LEFT(dcregionId,LEN(@dcRegionID))=@dcRegionID
					AND MinExperience =@dcExperienceId
					AND LEFT(dcJobtypeId,LEN(@dcJobTypeId))=@dcJobTypeId

					SELECT @lesscnt=COUNT(1) FROM reportdb..salaryReport
					WHERE LEFT(dcregionId,LEN(@dcRegionID))=@dcRegionID
					AND Salary<@inputSalary
					AND MinExperience =@dcExperienceId
					AND LEFT(dcJobtypeId,LEN(@dcJobTypeId))=@dcJobTypeId
				END
				ELSE
				BEGIN
					SELECT @allcnt=COUNT(1) FROM reportdb..salaryReport
					WHERE LEFT(dcregionId,LEN(@dcRegionID))=@dcRegionID
					AND dcEducationId =@dcEducationId
					AND MinExperience =@dcExperienceId
					AND LEFT(dcJobtypeId,LEN(@dcJobTypeId))=@dcJobTypeId

					SELECT @lesscnt=COUNT(1) FROM reportdb..salaryReport
					WHERE LEFT(dcregionId,LEN(@dcRegionID))=@dcRegionID
					AND dcEducationId =@dcEducationId
					AND Salary<@inputSalary
					AND MinExperience =@dcExperienceId
					AND LEFT(dcJobtypeId,LEN(@dcJobTypeId))=@dcJobTypeId
				END
			END
		END
		IF @allcnt=0 OR @lesscnt =0
			SELECT ''AS lesspercent
		ELSE 
			SELECT CONVERT(VARCHAR(10),@lesscnt*100/@allcnt) +'%' AS lesspercent
	END
	ELSE
	BEGIN
		SELECT '' AS lesspercent
	END
	
END
SET NOCOUNT OFF

GO
/****** Object:  StoredProcedure [dbo].[procSales_WorkdateStatusSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.03
--创建人：Nick
--说明：判断今天是否是工作日
--#####################################################
CREATE PROCEDURE [dbo].[procSales_WorkdateStatusSelect]
(
	@WorkDate VARCHAR(20)
)
AS
INSERT INTO procLog select 'procSales_WorkdateStatusSelect', @workdate, getdate()
BEGIN TRY
	IF @WorkDate IS NULL
		SELECT status FROM sales_workdate WITH(NOLOCK) 
		WHERE workdate = CONVERT(VARCHAR(8), GETDATE(), 112)
		AND Status=1
	ELSE
		SELECT status FROM sales_workdate WITH(NOLOCK) 
		WHERE workdate = @WorkDate 
		AND Status=1
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[ProcSaleWorkDateStatusSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.30
--创建人：Nick
--说明：判断今天是否是工作日
--#####################################################
CREATE PROCEDURE [dbo].[ProcSaleWorkDateStatusSelect]
(
	@Day INT
)
AS
--INSERT INTO procLog select 'ProcSaleWorkDateStatusSelect', @Day, getdate()
BEGIN
	IF @Day IS NULL
		SELECT 1 FROM WorkDate WITH(NOLOCK) 
		WHERE WorkDate = CONVERT(VARCHAR(8), GETDATE(), 112)
		AND Type = 1
	ELSE
		SELECT 1 
		FROM WorkDate WITH(NOLOCK) 
		WHERE WorkDate = @Day 
		AND Type = 1
END

GO
/****** Object:  StoredProcedure [dbo].[procSearchKeywordByKeyWordPinYinSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.10
--创建人：NICK
--说明：关键词
--#####################################################
CREATE PROCEDURE [dbo].[procSearchKeywordByKeyWordPinYinSelect]
(
	@KeyWord VARCHAR(50)
)
AS
BEGIN
	SELECT TOP 10 KeyType,KeyWord,KeyWordPinYin,SearchResult,SearchType 
	FROM searchdb..SearchKeyword WITH(NOLOCK) 
	WHERE (KeyWord LIKE @KeyWord+'%' OR KeyWordPinYin LIKE @KeyWord+'%') 
	ORDER BY SearchNumber DESC
END


GO
/****** Object:  StoredProcedure [dbo].[procSearchKeywordByKeyWordSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.03
--创建人：Nick
--说明：获取关键词
--#####################################################
CREATE PROCEDURE [dbo].[procSearchKeywordByKeyWordSelect]
(
	@KeyWord VARCHAR(50),
	@Type INT
)
AS
BEGIN TRY
	IF @Type = 1
	BEGIN
		SELECT TOP 10 KeyType,KeyWord,KeyWordPinYin,SearchResult,SearchType 
		FROM searchdb..SearchKeyword WITH(NOLOCK INDEX(IX_SearchKeyword_Keyword)) 
		WHERE KeyWord LIKE ''+@KeyWord+'%' 
		ORDER BY SearchNumber DESC
	END
	ELSE 
	BEGIN
		SELECT TOP 10 KeyType,KeyWord,KeyWordPinYin,SearchResult,SearchType 
		FROM searchdb..SearchKeyword WITH(NOLOCK INDEX(IX_SearchKeyword_KeywordPinYin)) 
		WHERE KeyWordPinYin LIKE ''+@KeyWord+'%'
		ORDER BY SearchNumber DESC
	END
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[ProcSearchKeywordsPowerBtMergerUpdate]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#######################################################
--20111213 sean
--用于排名工具，断点续传
--#######################################################
CREATE PROCEDURE [dbo].[ProcSearchKeywordsPowerBtMergerUpdate]
AS
BEGIN
	SET NOCOUNT ON;
	DECLARE @DayInterval AS INT, @Week6 AS VARCHAR(8), @Day AS VARCHAR(8), @I AS INT, @Today AS VARCHAR(8)
	SET @DayInterval =DATEPART(W, GETDATE())
	IF @DayInterval = 7
		SET @DayInterval = 0

	SELECT @Week6 = CONVERT(VARCHAR(8), GETDATE() - @DayInterval, 112), @i = 0, @Today = CONVERT(VARCHAR(8), GETDATE(), 112)

	WHILE @I < @DayInterval
	BEGIN
		SET @i = @i + 1
		SET @Day = CONVERT(VARCHAR(8), GETDATE() - @i, 112)
		IF @Day >= @Week6
		BEGIN
			UPDATE a SET a.YearMonthDay = @Today
			FROM SearchKeywordsPower a
			WHERE a.YearMonthDay = @Day
			AND NOT EXISTS(SELECT 'x' FROM SearchKeywordsPower 
				WHERE SearchKeywords_Id = a.SearchKeywords_Id
				AND Engine = a.Engine
				AND YearMonthDay = @Today)
		END
	END
	DELETE SearchKeywordsPower WHERE YearMonthDay >= @Week6 AND YearMonthDay < @Today
	--update SearchKeywordsPower set YearMonthDay = @Week6 where YearMonthDay = @Today
END














GO
/****** Object:  StoredProcedure [dbo].[procSecondererInsert]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--创建人 Lambo 20101013
--用于首页记录访问记录
CREATE PROCEDURE [dbo].[procSecondererInsert]
(
	@province_id SMALLINT,
	@versionid INT,
	@referer VARCHAR(190),
	@ip VARCHAR(15),
	@keyve NVARCHAR(50)
)
AS
BEGIN
	SET NOCOUNT ON
	SELECT TOP 1 ip 
	FROM Seconderer WITH(NOLOCK)
	WHERE versionid=@versionid 
	AND referer=@referer
	AND ip=@ip
	AND LoginDate > DATEADD(MINUTE, -10, GETDATE())

	IF(@@rowcount=0) 
	BEGIN
		INSERT INTO seconderer (province_id,versionid,referer,ip,keywords)
		VALUES(@province_id,@versionid,@referer,@ip,@keyve)
	END

	SET NOCOUNT OFF
END














GO
/****** Object:  StoredProcedure [dbo].[procSecondererInsert2]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--创建人 Lambo 20101013
--用于首页记录访问记录
CREATE PROCEDURE [dbo].[procSecondererInsert2]
(
	@Province_ID SMALLINT,
	@VersionID INT,
	@Referer VARCHAR(190),
	@Ip VARCHAR(15),
	@Keyve NVARCHAR(50),
	@SessionID VARCHAR(30)
)
AS
BEGIN
	SET NOCOUNT ON
	SELECT TOP 1 Ip 
	FROM Seconderer WITH(NOLOCK)
	WHERE VersionID = @VersionID 
	AND Referer = @Referer
	AND Ip = @Ip
	AND LoginDate > DATEADD(MINUTE, -10, GETDATE())

	IF(@@ROWCOUNT = 0) 
	BEGIN
		INSERT INTO seconderer (Province_ID, VersionID, Referer, Ip, Keywords, Sessionid)
		VALUES(@Province_ID, @VersionID, @Referer, @Ip, @Keyve, @Sessionid)
	END
END














GO
/****** Object:  StoredProcedure [dbo].[ProcShareMainLogByClickCountUpdate]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.1.19 --创建人：Harry 
--说明：分享点击量增加
 --#####################################################
CREATE PROCEDURE [dbo].[ProcShareMainLogByClickCountUpdate]
( 
	@ShareID VARCHAR(50)
)
AS 
BEGIN
	UPDATE LogDB..ShareMainLog
	SET ClickCount=ClickCount+1 
	WHERE ShareID=@ShareID
END

GO
/****** Object:  StoredProcedure [dbo].[ProcShareMainLogInsert]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ProcShareMainLogInsert]
(
	@ShareID VARCHAR(20),
	@Url VARCHAR(200),
	@ShareMode TINYINT,
	@ShareWay TINYINT,
	@PageMark SMALLINT,
	@PageID VARCHAR(20),	--INT,
	@ShareBy TINYINT,
	@ShareMan INT
)
AS
SET NOCOUNT ON
IF EXISTS(SELECT 'x' FROM  Logdb..ShareMainLog WHERE AddDate > DATEADD(MINUTE, -2, GETDATE()) AND ShareID = @ShareID AND Url = @Url)
	RETURN

DECLARE @PageNo INT
BEGIN TRY
	SET @PageNo = CONVERT(INT, @PageID)
END TRY
BEGIN CATCH
	SET @PageNo = 0
END CATCH

BEGIN
	INSERT INTO Logdb..ShareMainLog(
		ShareID,
		Url,
		ShareMode,
		ShareWay,
		PageMark,
		PageID,
		ShareBy,
		ShareMan
	)
	VALUES(
		@ShareID,
		@Url,
		@ShareMode,
		@ShareWay,
		@PageMark,
		@PageNo,
		@ShareBy,
		@ShareMan
	)
END

GO
/****** Object:  StoredProcedure [dbo].[ProcSmsMessageLogByBatchSendSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ProcSmsMessageLogByBatchSendSelect]
AS
--return
SET NOCOUNT ON
BEGIN
	IF DATEPART(HOUR, GETDATE()) < 8 OR DATEPART(HOUR, GETDATE()) > 17
		RETURN

	CREATE TABLE #t(ProvinceId INT, Cnt INT)
	CREATE TABLE #m(id INT, Mobile VARCHAR(20))

	INSERT INTO #t(ProvinceId, Cnt)
	SELECT ProvinceId, COUNT(*) Cnt
	FROM bsMobileSpread
	WHERE UserType = 1
	AND SendStatus IS NULL
	AND BatchId IS NULL
	--AND AddDate > CONVERT(VARCHAR(10), GETDATE(), 120)
	GROUP BY ProvinceId
	HAVING COUNT(*) > 199
 
	IF (SELECT COUNT(*) FROM #t) = 0
		RETURN
	
	DECLARE @MobileString VARCHAR(MAX), @Msg NVARCHAR(500), @ProvinceId INT, @Cnt INT
	SET @ProvinceId = 0
	WHILE EXISTS(SELECT 'x' FROM #t WHERE ProvinceId > @ProvinceId)
	BEGIN
		SELECT TOP 1 @MobileString = '', @ProvinceId = ProvinceId, @Cnt = Cnt FROM #t WHERE ProvinceId > @ProvinceId ORDER BY ProvinceId
		SELECT TOP 1 @Msg = [Message] FROM bsMobileMessage WHERE dcProvinceId = @ProvinceId AND EndDate > GETDATE() AND BeginDate < GETDATE() ORDER BY ID DESC

		IF @Cnt > 500
			SET @Cnt = 300

		TRUNCATE TABLE #m
		INSERT INTO #m
		SELECT TOP (@Cnt) Id, MobileNo 
		FROM bsMobileSpread
		WHERE ProvinceId = @ProvinceId
		AND UserType = 1
		AND SendStatus IS NULL
		AND BatchID IS NULL
		--AND AddDate > CONVERT(VARCHAR(10), GETDATE() - 1, 120)
		ORDER BY ID

		SELECT TOP (@Cnt) @MobileString = @MobileString + ',' + Mobile
		FROM #m

		IF LEN(@MobileString) > 1
		BEGIN
			SET @MobileString = RIGHT(@MobileString, LEN(@MobileString) - 1)
			INSERT INTO smsBatchSend(Mobile, Msg) SELECT @MobileString, @Msg
			UPDATE bsMobileSpread SET BatchId = @@Identity WHERE ID IN(SELECT Id FROM #m)
		END
	END
END

GO
/****** Object:  StoredProcedure [dbo].[procSmsMessageLogByBirthDayInsert]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[procSmsMessageLogByBirthDayInsert]
AS
BEGIN
	DECLARE @t VARCHAR(4)
	SELECT @t = RIGHT(CONVERT(VARCHAR(8), GETDATE(), 112), 4)

	INSERT SmsMessageLog(SendMan, ManagerUserId, paMainId, caMainId, Mobile, MsgType, IsCat, Msg)
	SELECT 1, ManagerUserId, NULL, NULL, Mobile, 207, 0,
		'一份祝福，一份真诚，在这个特别的日子里，伍亿全体同仁给您送上生日最最真挚的祝福，祝您生日.快乐、家庭幸福！伍亿的发展倾注了您和您家人的支持、奉献，感谢您的辛勤工作，在此向您表示衷心感谢！愿我们在今后的工作中和谐、同心，共创美好的明天！'
	FROM OaDb..WorkUser 
	WHERE IDNumber LIKE '__________' + @t + '%'
	AND JobStatus <> 3
end










GO
/****** Object:  StoredProcedure [dbo].[ProcSmsMessageLogByCaSMSWaitInsert]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----------------
--创建日期：2012-4-17
--创建人：lambo
--功能说明：企业汇总类短信发送。将marketdb..caSMSWait里的数据转入SmsMessageLog 
-----------------
CREATE PROCEDURE [dbo].[ProcSmsMessageLogByCaSMSWaitInsert]
AS
BEGIN TRY
	IF oadb.dbo.IsWorkDate(getdate()) <> 1
		RETURN
	
	--删除今天已经登录过的企业的记录
	If DATEPART(HOUR,GETDATE())*100 + DATEPART(MINUTE,GETDATE()) <= 905
		DELETE FROM marketdb..cpSmsWait WHERE cpMainID IN(SELECT ID FROM cpMain WITH(NOLOCK) WHERE LastLoginDate > GETDATE() - 1)
	ELSE
		DELETE FROM marketdb..cpSmsWait WHERE cpMainID IN(SELECT ID FROM cpMain WITH(NOLOCK) WHERE LastLoginDate > DATEADD(MINUTE, -10, GETDATE()))

	DECLARE @t AS TABLE(
		ID int,
		CpMainID int,
		CaMainID int,
		SmsType tinyint,
		Msg nvarchar(100),
		Mobile varchar(11),
		LastLoginTime int,
		exMessageP2CCount int,
		exInterviewCount int,
		exJobApplyCount int,
		cacvIntentionCount int,
		LastDate datetime,
		LastLoginDate smalldatetime,
		IsSend Bit
	)

	INSERT INTO @t
	SELECT *, 0 FROM marketdb..cpSmsWait 
	WHERE LastLoginTime < DATEPART(HOUR, GETDATE()) * 100 + DATEPART(MINUTE, GETDATE()) 
	AND Msg > '' 
	ORDER BY CASE WHEN SmsType > 16 THEN 0 ELSE 1 END, LastLoginTime DESC

	--UPDATE @t SET IsSend = 1 WHERE ID % 7 = 1
	UPDATE @t SET IsSend = 1
	
	--INSERT INTO SmsWatch
	--SELECT *, CONVERT(VARCHAR(8), GETDATE(), 112), SmsType-1 FROM @t
		
	INSERT SmsMessageLog(SendMan, ManagerUSerId, paMainId, caMainId, Mobile, MsgType, IsCat, Msg)
		SELECT 0, NULL, NULL, caMainID, Mobile, SmsType-1, 0,Msg FROM @T WHERE IsSend = 1

	DELETE FROM marketdb..cpSMSWait WHERE ID IN (select ID FROM @T)
END TRY
BEGIN CATCH
END CATCH














GO
/****** Object:  StoredProcedure [dbo].[ProcSmsMessageLogByEmrtReceiveInsert]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ProcSmsMessageLogByEmrtReceiveInsert]
(
	@Mobile VARCHAR(20),
	@Msg NVARCHAR(200)
)
AS
BEGIN
	SET NOCOUNT ON

	SET @Mobile = LTRIM(RTRIM(REPLACE(@Mobile, '+', '')))
	IF(LEFT(@Mobile, 2) = '86')
		SET @Mobile = RIGHT(@Mobile, LEN(@Mobile) - 2)
	DECLARE @ReceiveDate VARCHAR(30)
		SET @ReceiveDate = CONVERT(VARCHAR(20), GETDATE(), 120)

	DECLARE @ID INT, @LeaveId AS INT, @WorkFlowID AS INT, @RunFlowId AS INT, @WorkStepId AS INT
	INSERT SmsMessageLog(SendMan, Mobile, Msg, IsCat, SendDate, SmsType, MsgType, PortNo)
	VALUES(-1, @Mobile, @Msg, 0, @ReceiveDate, 2, 255, 1)
	
	SET @ID = @@IDENTITY

	IF @Mobile LIKE '955%'
	BEGIN
		UPDATE SmsMessageLog SET SendMan = 140, MsgType = 245 WHERE ID = @ID	
		RETURN
	END

	IF LEFT(@Msg, 3) = '???'
		SET @Msg = RIGHT(@Msg, LEN(@Msg) - 3)

	--判断是不是内部的手机号
	DECLARE @MID INT
	SELECT TOP 1 @MID = ManagerUserID FROM OADB..WorkUser WITH(NOLOCK) WHERE Mobile = @Mobile AND JobStatus <> 3
	IF @MID = 1
	BEGIN
		IF LEFT(@Msg, 1) IN('y', 'n')
		BEGIN
			IF (dbo.IsINT(RIGHT(@Msg, LEN(@Msg) - 1)) = 1 AND LEN(@Msg) BETWEEN 4 AND 6)
			BEGIN
				SET @LeaveId = CONVERT(INT, RIGHT(@MSg, LEN(@Msg) - 1))
				SELECT @RunFlowId = ID, @WorkFlowID = WorkFlowId
				FROM OaDb..RunFlow
				WHERE BusinessId = @LeaveId AND WorkUserId IN(1, 10) AND ModuleId = 101
				IF @RunFlowId IS NULL
					RETURN

				IF LEFT(@Msg, 1) = 'y'
				BEGIN
					UPDATE OaDb..RunFlow SET ViewDate = GETDATE(),SendDate = GETDATE(), ExecutionType = 1
					WHERE ID = @RunFlowId
					SELECT @WorkStepId = CASE @WorkFlowId WHEN 6 THEN 17 ELSE 24 END

					INSERT INTO Oadb..RunFlow(WorkStepID, WorkUserID, BusinessID, Opinion, ReceiveDate, ViewDate, 
						SendDate, RemindNumber, NextRemindTime, ExecutionType, WorkFlowId, ModuleID)
					SELECT @WorkStepId, ID, @LeaveID, '', GETDATE(), NULL, NULL, 0, GETDATE(), 0, @WorkFlowId, 101
					FROM OADB..WorkUser WHERE ManagerUserID IN(101) AND JobStatus < 3				
				END
				IF LEFT(@Msg, 1) = 'n'
				BEGIN
					UPDATE OaDb..RunFlow SET Opinion='退回', ViewDate = GETDATE(),SendDate = GETDATE(), ExecutionType = 1
					WHERE ID = @RunFlowId
					SELECT @WorkStepId = ID FROM Oadb..WorkStep WHERE WorkFlowId = @WorkFlowId AND IsStart = 1
						
					INSERT INTO Oadb..RunFlow(WorkStepID, WorkUserID, BusinessID, Opinion, ReceiveDate, ViewDate, 
						SendDate, RemindNumber, NextRemindTime, ExecutionType, WorkFlowId, ModuleID)
					SELECT @WorkStepId, ApplicantID, @LeaveID, '', GETDATE(), NULL, NULL, 0, GETDATE(), 0, @WorkFlowId, 101
					FROM OADB..Leave WHERE ID = @LeaveId
				END				
			END
		END
	END

	IF @MID > 0
	BEGIN
		UPDATE SmsMessageLog SET SendMan = @MID, MsgType = 241 WHERE ID = @ID	
		----Rtx

		IF LEFT(@Msg, 2) = '请假'
		BEGIN
			EXEC OaDb..ProcLeaveBySmsInsert @Msg, @Mobile
		END
		ELSE
		BEGIN
			--IF(GETDATE() BETWEEN '2013-2-2 15:00' AND '2013-2-2 21:59' OR @Mobile IN('15318161005', '18663412806', '13455496132'))
				INSERT INTO nhSms VALUES(@MID, @Mobile, @Msg, 0, 0, 0, GETDATE())
		END
		RETURN
	END

	DECLARE @CaMainID INT, @CompanyName VARCHAR(100), @cpMainId INT, @PaMainID INT, @ManagerUserID INT, @SendMan INT, @ConsultantID INT
	SET @ConsultantID = 131 --先暂时给lulu
	
	SELECT TOP 1 @CaMainID = CaMainID, @PaMainID = PaMainID, @ManagerUserID = ManagerUserID, @SendMan = SendMan 
	FROM SmsMessageLog WITH(NOLOCK)
	WHERE Mobile = @Mobile 
	AND SmsType = 1
	ORDER BY ID DESC
	
	IF @CaMainID > 0
	BEGIN
		IF @SendMan > 0
			UPDATE SmsMessageLog SET SendMan = @SendMan, caMainId = @caMainId, MsgType = 242 WHERE ID = @ID
		ELSE
		BEGIN
			SELECT @ConsultantID = ConsultantID 
			FROM caMain a WITH(NOLOCK), cpMain b WITH(NOLOCK) 
			WHERE a.cpMainID = b.ID
			AND a.ID = @caMainID
		
			IF @ConsultantID IS NULL
			BEGIN
				SET @ConsultantID = 131
			END

			UPDATE SmsMessageLog SET SendMan = @ConsultantID, MsgType = 242, caMainId = @caMainId WHERE ID = @ID
		END
	END
	ELSE IF @paMainID > 0
	BEGIN
		IF @SendMan > 0
			UPDATE SmsMessageLog SET SendMan = @SendMan, MsgType = 243, paMainId = @paMainId WHERE ID = @ID
		ELSE
		BEGIN
			SET @ConsultantID = 131

			UPDATE SmsMessageLog SET SendMan = @ConsultantID, MsgType = 243, paMainId = @paMainId WHERE ID = @ID
		END
	END
	ELSE IF @ManagerUserID > 0 
		UPDATE SmsMessageLog SET SendMan = @ManagerUserID, MsgType =241 WHERE ID = @ID
	ELSE IF @SendMan > 0
		UPDATE SmsMessageLog SET SendMan = @SendMan WHERE ID = @ID
	ELSE
	BEGIN
		--是否企业用户的手机
		SELECT @caMainId = a.ID, @companyName = b.Name, @cpMainId = b.Id, @ConsultantID = b.ConsultantID
		FROM caMain a WITH(NOLOCK), cpMain b WITH(NOLOCK) 
		WHERE a.cpMainID = b.ID
		AND a.Mobile = @Mobile 

		IF @caMainId > 0
		BEGIN
			IF @ConsultantID > 0
			BEGIN
				UPDATE SmsMessageLog SET SendMan = @ConsultantID, caMainId = @caMainId, MsgType = 242 WHERE ID = @ID
					
				INSERT INTO rtxNotifyLog (Receiver, RtxTitle, RtxMessage, SendType, DelayTime, SendTime, AddTime)
				SELECT @ConsultantID, '您收到新的短信', 
					'您收到短信，发信人：' + @companyName + '(' + LTRIM(STR(@cpMainId)) + ')，时间：' + CONVERT(VARCHAR(20), GETDATE(), 120) +
					'，消息：' + @Msg + '。http://sysback.51rc.com/yehgiiaovbjkaie871/Others/mobilesend_list2.asp',
					0, 0, 0, GETDATE()
			END
			ELSE
			BEGIN
				SET @ConsultantID = 131
				UPDATE SmsMessageLog SET SendMan = @ConsultantID, MsgType = 242, caMainId = @caMainId WHERE ID = @ID
			END
			RETURN
		END
		--是否招聘会认证的手机
		DECLARE @RID AS INT
		SELECT @RID = ID, @paMainId = paMainID FROM MarketDB..RmGiftRequire WITH(NOLOCK) WHERE Mobile = @Mobile
		IF @@ROWCOUNT = 0
			SELECT @RID = ID, @paMainId = paMainID FROM MarketDB..MobileRegisterCode WITH(NOLOCK) WHERE Mobile = @Mobile

		IF @RID > 0
		BEGIN
			SET @ConsultantID = 160
			UPDATE SmsMessageLog SET SendMan = @ConsultantID, paMainId = @paMainId, MsgType = 244 WHERE ID = @ID
			RETURN
		END

		--是否个人用户的手机
		SELECT @paMainId = ID
		FROM paMain WITH(NOLOCK)
		WHERE Mobile = @Mobile 

		IF @paMainId > 0
		BEGIN
			SET @ConsultantID = 131
			UPDATE SmsMessageLog SET SendMan = @ConsultantID, paMainId = @paMainId, MsgType = 243 WHERE ID = @ID
			RETURN
		END
	END	
END
GO
/****** Object:  StoredProcedure [dbo].[ProcSmsMessageLogByPaSMSWaitInsert]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----------------
--创建日期：2012-4-17
--创建人：lambo
--功能说明：个人汇总类短信发送。将marketdb..paSMSWait里的数据转入SmsMessageLog 
--计划任务执行，8点至
-----------------
CREATE PROCEDURE [dbo].[ProcSmsMessageLogByPaSMSWaitInsert]
AS
BEGIN TRY
	--删除今天已经登录过的个人的记录
	If DATEPART(HOUR,GETDATE())*100 + DATEPART(MINUTE,GETDATE()) <= 805
		DELETE FROM marketdb..paSMSWait WHERE paMainID IN(SELECT ID FROM paMain WITH(NOLOCK) WHERE LastLoginDate > GETDATE() - 1)
	ELSE
		DELETE FROM marketdb..paSMSWait WHERE paMainID IN(SELECT ID FROM paMain WITH(NOLOCK) WHERE LastLoginDate > DATEADD(MINUTE, -10, GETDATE()))

	DECLARE @t AS TABLE(
		ID int,
		paMainID int,
		SmsType tinyint,
		Msg nvarchar(100),
		Mobile varchar(11),
		LastLoginTime int,
		LastDate datetime,
		IsSend Bit
	)

	INSERT INTO @t
	SELECT TOP 20 *, 1 FROM marketdb..paSMSWait WHERE LastLoginTime < DATEPART(HOUR, GETDATE())*100 + DATEPART(MINUTE, GETDATE()) AND Msg>''

	--UPDATE @t SET IsSend = 0 WHERE ID % 7 = 0
	--UPDATE @t SET IsSend = 1
	
	INSERT SmsMessageLog(SendMan, ManagerUSerId, paMainId, caMainId, Mobile, MsgType, IsCat, Msg)
	SELECT 0, NULL, paMainID, NULL, Mobile, 100 + SmsType, 0,Msg FROM @t --WHERE IsSend = 1

	--INSERT INTO SmsWatch(ID, cpMainId, caMainId, SmsType, MsgType, Msg, Mobile, LastLoginTime, LastDate, LastLoginDate, IsSend, WatchDate)
	--SELECT ID, paMainId, paMainId, smsType, 100 + SmsType, Msg, Mobile, LastLoginTime, LastDate, LastDate, IsSend, CONVERT(VARCHAR(8), GETDATE(), 112)
	--FROM @t

	DELETE FROM marketdb..paSMSWait WHERE ID IN (select ID FROM @t)
END TRY
BEGIN CATCH

END CATCH














GO
/****** Object:  StoredProcedure [dbo].[ProcSmsMessageLogByReceiveInsert]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
used by zhongxinjiahe port 2
sysback.51rc.com:81\.....\mobilereceived.asp
*/
CREATE PROCEDURE [dbo].[ProcSmsMessageLogByReceiveInsert]
(
	@Mobile VARCHAR(20),
	@Msg NVARCHAR(200),
	@ReceiveDate VARCHAR(30),
	@PortNo INT,
	@IsCat BIT	
)
AS
insert into proclog select 'ProcSmsMessageLogByReceiveInsert', @Mobile, getdate()
BEGIN
	SET NOCOUNT ON
	SET @Mobile = LTRIM(RTRIM(REPLACE(REPLACE(@Mobile, '+', ''), '''', '')))
	SET @Msg = dbo.SafeSql(@Msg)
	SET @ReceiveDate = dbo.SafeSql(@ReceiveDate)
	IF(LEFT(@Mobile, 2) = '86')
		SET @Mobile = RIGHT(@Mobile, LEN(@Mobile) - 2)
	IF (LEN(ISNULL(@ReceiveDate, '')) < 8)
		SET @ReceiveDate = CONVERT(VARCHAR(20), GETDATE(), 120)

	DECLARE @ID INT, @LeaveId AS INT, @WorkFlowID AS INT, @RunFlowId AS INT, @WorkStepId AS INT
	INSERT SmsMessageLog(SendMan, Mobile, Msg, IsCat, SendDate, SmsType, MsgType, PortNo)
	VALUES(-1, @Mobile, @Msg, @IsCat, @ReceiveDate, 2, 255, @PortNo)
	
	SET @ID = @@IDENTITY
	
	--校园认证短信
	IF LEFT(@Msg,2) = '认证'
	BEGIN
		DECLARE @UserName VARCHAR(50),@dcProvinceID VARCHAR(2),@SubSiteUrl VARCHAR(200)
		SET @Msg = REPLACE(REPLACE(@Msg,'+',''),'认证','')
		SET @dcProvinceID = LEFT(@Msg,2)
		SET @UserName = RIGHT(@Msg,LEN(@Msg)-2)
		IF dbo.IsINT(@dcProvinceID)=1
		BEGIN
			SELECT @SubSiteUrl=SubSiteUrl FROM dcSubSite WHERE ID=@dcProvinceID
			IF ISNULL(@SubSiteUrl,'') = ''
				RETURN
		END
		ELSE
			RETURN
			
		IF dbo.IsEmail(@UserName)=1
			EXEC RmPaMainByMobileInsert @UserName,@dcProvinceID,@Mobile,@SubSiteUrl

		RETURN
	END
	
	IF @Mobile LIKE '955%'
	BEGIN
		UPDATE SmsMessageLog SET SendMan = 140, MsgType = 245 WHERE ID = @ID	
		RETURN
	END

	IF LEFT(@Msg, 3) = '???'
		SET @Msg = RIGHT(@Msg, LEN(@Msg) - 3)

	--判断是不是内部的手机号
	DECLARE @MID INT
	SELECT TOP 1 @MID = ManagerUserID FROM OADB..WorkUser WITH(NOLOCK) WHERE Mobile = @Mobile AND JobStatus <> 3

	IF @MID = 1
	BEGIN
		IF LEFT(@Msg, 1) IN('y', 'n')
		BEGIN
			IF (dbo.IsINT(RIGHT(@Msg, LEN(@Msg) - 1)) = 1 AND LEN(@Msg) BETWEEN 4 AND 6)
			BEGIN
				SET @LeaveId = CONVERT(INT, RIGHT(@MSg, LEN(@Msg) - 1))
				SELECT @RunFlowId = ID, @WorkFlowID = WorkFlowId
				FROM OaDb..RunFlow
				WHERE BusinessId = @LeaveId AND WorkUserId IN(1, 10) AND ModuleId = 101
				IF @RunFlowId IS NULL
					RETURN

				IF LEFT(@Msg, 1) = 'y'
				BEGIN
					UPDATE OaDb..RunFlow SET ViewDate = GETDATE(),SendDate = GETDATE(), ExecutionType = 1
					WHERE ID = @RunFlowId
					SELECT @WorkStepId = CASE @WorkFlowId WHEN 6 THEN 17 ELSE 24 END

					INSERT INTO Oadb..RunFlow(WorkStepID, WorkUserID, BusinessID, Opinion, ReceiveDate, ViewDate, 
						SendDate, RemindNumber, NextRemindTime, ExecutionType, WorkFlowId, ModuleID)
					SELECT @WorkStepId, ID, @LeaveID, '', GETDATE(), NULL, NULL, 0, GETDATE(), 0, @WorkFlowId, 101
					FROM OADB..WorkUser WHERE ManagerUserID IN(105) AND JobStatus < 3				
				END
				IF LEFT(@Msg, 1) = 'n'
				BEGIN
					UPDATE OaDb..RunFlow SET Opinion='退回', ViewDate = GETDATE(),SendDate = GETDATE(), ExecutionType = 1
					WHERE ID = @RunFlowId
					SELECT @WorkStepId = ID FROM Oadb..WorkStep WHERE WorkFlowId = @WorkFlowId AND IsStart = 1
						
					INSERT INTO Oadb..RunFlow(WorkStepID, WorkUserID, BusinessID, Opinion, ReceiveDate, ViewDate, 
						SendDate, RemindNumber, NextRemindTime, ExecutionType, WorkFlowId, ModuleID)
					SELECT @WorkStepId, ApplicantID, @LeaveID, '', GETDATE(), NULL, NULL, 0, GETDATE(), 0, @WorkFlowId, 101
					FROM OADB..Leave WHERE ID = @LeaveId
				END				
			END
		END
	END

	IF @MID > 0
	BEGIN
		--UPDATE SmsMessageLog SET SendMan = @MID, MsgType = 241 WHERE ID = @ID
		IF LEFT(@Msg, 2) = '请假'
		BEGIN
			EXEC OaDb..ProcLeaveBySmsInsert @Msg, @Mobile
		END
		ELSE -- 年会时需要读取发送的手机号并保存到年会短信记录表里 2013-1-15 Lucifer
		BEGIN
			--IF(GETDATE() BETWEEN '2013-2-2 15:00' AND '2013-2-2 21:59' OR @Mobile IN('15318161005', '18663412806', '13455496132'))
				begin try
					INSERT INTO nhSms(ManageruserId) SELECT @MID
					--INSERT INTO nhSms VALUES(@MID, @Mobile, @Msg, 1, GETDATE())
				end try
				begin catch
					INSERT INTO nhSms(ManageruserId) SELECT @MID
				end catch
		END
		RETURN
	END

	DECLARE @CaMainID INT, @CompanyName VARCHAR(100), @cpMainId INT, @PaMainID INT, @ManagerUserID INT, @SendMan INT, @ConsultantID INT
	SET @ConsultantID = 131 --先暂时给lulu
	
	SELECT TOP 1 @CaMainID = CaMainID, @PaMainID = PaMainID, @ManagerUserID = ManagerUserID, @SendMan = SendMan 
	FROM SmsMessageLog WITH(NOLOCK)
	WHERE Mobile = @Mobile 
	AND SmsType = 2
	ORDER BY ID DESC
	
	IF @CaMainID > 0
	BEGIN
		IF @SendMan > 0
			UPDATE SmsMessageLog SET SendMan = @SendMan, caMainId = @caMainId, MsgType = 242 WHERE ID = @ID
		ELSE
		BEGIN
			SELECT @ConsultantID = ConsultantID 
			FROM caMain a WITH(NOLOCK), cpMain b WITH(NOLOCK) 
			WHERE a.cpMainID = b.ID
			AND a.ID = @caMainID
		
			IF @ConsultantID IS NULL
			BEGIN
				SET @ConsultantID = 131
			END

			UPDATE SmsMessageLog SET SendMan = @ConsultantID, MsgType = 242, caMainId = @caMainId WHERE ID = @ID
		END
	END
	ELSE IF @paMainID > 0
	BEGIN
		IF @SendMan > 0
			UPDATE SmsMessageLog SET SendMan = @SendMan, MsgType = 243, paMainId = @paMainId WHERE ID = @ID
		ELSE
		BEGIN
			SET @ConsultantID = 131

			UPDATE SmsMessageLog SET SendMan = @ConsultantID, MsgType = 243, paMainId = @paMainId WHERE ID = @ID
		END
	END
	ELSE IF @ManagerUserID > 0 
		UPDATE SmsMessageLog SET SendMan = @ManagerUserID, MsgType =241 WHERE ID = @ID
	ELSE IF @SendMan > 0
		UPDATE SmsMessageLog SET SendMan = @SendMan WHERE ID = @ID
	ELSE
	BEGIN
		--是否企业用户的手机
		SELECT @caMainId = a.ID, @companyName = b.Name, @cpMainId = b.Id, @ConsultantID = b.ConsultantID
		FROM caMain a WITH(NOLOCK), cpMain b WITH(NOLOCK) 
		WHERE a.cpMainID = b.ID
		AND a.Mobile = @Mobile 

		IF @caMainId > 0
		BEGIN
			IF @ConsultantID > 0
			BEGIN
				UPDATE SmsMessageLog SET SendMan = @ConsultantID, caMainId = @caMainId, MsgType = 242 WHERE ID = @ID
					
				INSERT INTO rtxNotifyLog (Receiver, RtxTitle, RtxMessage, SendType, DelayTime, SendTime, AddTime)
				SELECT @ConsultantID, '您收到新的短信', 
					'您收到短信，发信人：' + @companyName + '(' + LTRIM(STR(@cpMainId)) + ')，时间：' + CONVERT(VARCHAR(20), GETDATE(), 120) +
					'，消息：' + @Msg + '。http://sysback.51rc.com/newoa/desktop/MobileSendList2',
					0, 0, NULL, GETDATE()
			END
			ELSE
			BEGIN
				SET @ConsultantID = 131
				UPDATE SmsMessageLog SET SendMan = @ConsultantID, MsgType = 242, caMainId = @caMainId WHERE ID = @ID
			END
			RETURN
		END
		--是否招聘会认证的手机
/*		DECLARE @RID AS INT
		SELECT @RID = ID, @paMainId = paMainID FROM MarketDB..RmGiftRequire WITH(NOLOCK) WHERE Mobile = @Mobile
		IF @@ROWCOUNT = 0
			SELECT @RID = ID, @paMainId = paMainID FROM MarketDB..MobileRegisterCode WITH(NOLOCK) WHERE Mobile = @Mobile

		IF @RID > 0
		BEGIN
			SET @ConsultantID = 160
			UPDATE SmsMessageLog SET SendMan = @ConsultantID, paMainId = @paMainId, MsgType = 244 WHERE ID = @ID
			RETURN
		END
*/
		--是否个人用户的手机
		SELECT @paMainId = ID
		FROM paMain WITH(NOLOCK)
		WHERE Mobile = @Mobile 

		IF @paMainId > 0
		BEGIN
			SET @ConsultantID = 131
			UPDATE SmsMessageLog SET SendMan = @ConsultantID, paMainId = @paMainId, MsgType = 243 WHERE ID = @ID
			RETURN
		END
	END	
END














GO
/****** Object:  StoredProcedure [dbo].[ProcSmsMessageLogBySales0514Insert]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ProcSmsMessageLogBySales0514Insert]
AS
BEGIN
	/*
	1、2个月内已提交订单（免费会员） 11个
	2、5月12日--7月12日，这段时间到期的客户。 2978个
	3、3月12日--5月12日，这段时间已到期没有续费的客户。 1585个
	4、2个月内查看过资费标准（免费会员） 20576

	以上四种是要发的客户。--用优势（中嘉和信通道吧）
	xxxx（单位名称），会员套餐惊喜无限，xxx人才网期待您的参与！详情请咨询4006265151-工号（有顾问的话显示工号，没有顾问就直接显示为0）
	*/
	CREATE TABLE #t1(Id INT)
	--1、2个月内已提交订单（免费会员） 11个
	insert #t1
	select distinct cpmainid 
	FROM Caorder where adddate>getdate()-61 and adddate < getdate()- 7 
	and cpmainid in(select id from cpmain where membertype<3) and paid>0
	--2、5月12日--7月12日，这段时间到期的客户。
	insert #t1
	select distinct cpmainid 
	FROM Caorder where Enddate BETWEEN GETDATE() AND GETDATE() + 61
	AND OrderType = 8
	and cpmainid in(select id from cpmain where membertype=3)
	--3、3月12日--5月12日，这段时间已到期没有续费的客户。
	insert #t1
	select distinct cpmainid 
	FROM Caorder where Enddate BETWEEN GETDATE()-61 AND GETDATE()
	AND OrderType = 8
	and cpmainid in(select id from cpmain where membertype<3)
	--4、2个月内查看过资费标准（免费会员） 20576
	INSERT #t1
	SELECT a.Id
	FROM cpMain a, caMain b
	WHERE a.id= b.cpMainId
	AND b.Id IN(SELECT caMainId FROM caFeePageViewLog WHERE AddDate > GETDATE() - 61)
	AND a.MemberType < 3

	CREATE TABLE #t(ID INT, CompanyName NVARCHAR(100), ConsultantId INT, dcProvinceId INT, SiteName NVARCHAR(20), caMainId INT, Mobile VARCHAR(13))
	INSERT #t
	SELECT a.Id, a.Name, a.ConsultantId, a.dcProvinceId, '', b.Id, b.Mobile
	FROM cpMain a, caMain b
	WHERE a.Id = b.cpMainId
	AND b.AccountType = 1
	AND a.Id IN(SELECT ID FROM #t1)

	UPDATE a
	SET a.SiteName = b.SubSiteName
	FROM #t a, dcSubsite b
	WHERE a.dcProvinceId = b.Id

	UPDATE #t SET ConsultantId = 0 WHERE ConsultantId IS NULL OR ConsultantId IN(SELECT ID FROM ManagerUser WHERE Status > 2)
	DELETE FROM #t WHERE dbo.IsMobile(Mobile) = 0

	--	xxxx（单位名称），会员套餐惊喜无限，xxx人才网期待您的参与！详情请咨询4006265151-工号（有顾问的话显示工号，没有顾问就直接显示为0）
	INSERT SmsMessageLog(SendMan, Mobile, Msg, IsCat, AddDate, SmsType, MsgType)
	SELECT 112, Mobile, CompanyName + '，会员套餐惊喜无限，' + SiteName + '期待您的参与！详情请咨询4006265151-' + LTRIM(STR(ConsultantId)),
		0, GETDATE(), 1, 26
	FROM #t
END










GO
/****** Object:  StoredProcedure [dbo].[ProcSmsMessageLogBySendInsert]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ProcSmsMessageLogBySendInsert]
(
	@SendMan SMALLINT,
	@ManagerUserId SMALLINT,
	@paMainID INT,
	@caMainID INT,
	@Mobile VARCHAR(11),
	@Msg NVARCHAR(200),
	@MsgType TINYINT,
	@IsCat BIT	
)
AS
BEGIN
	INSERT SmsMessageLog(SendMan, ManagerUSerId, paMainId, caMainId, Mobile, Msg, MsgType, IsCat)
	VALUES(@SendMan, @ManagerUSerId, @paMainId, @caMainId, @Mobile, @Msg, @MsgType, @IsCat)
	
	RETURN @@IDENTITY
END














GO
/****** Object:  StoredProcedure [dbo].[procSmsmessageLogCountSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.30
--创建人：Nick
--说明：
--#####################################################
CREATE PROCEDURE [dbo].[procSmsmessageLogCountSelect]
(
	@AskNo VARCHAR(50),
	@AddDate DATETIME
)
AS
--BEGIN TRY
	DECLARE @CNT INT 
	SET @CNT = 0
	SELECT  @CNT = COUNT(*) 
	FROM smsmessagelog 
	WHERE mobile=(
		SELECT TOP 1 mobile 
		FROM caGetPasswordLog WITH(NOLOCK) 
		WHERE askno = @askNo 
		AND mobile IS NOT NULL
	) AND adddate > @AddDate 
	AND MsgType=9 
	
	IF @CNT < 5
	BEGIN
		INSERT INTO smsmessagelog(SendMan, ManagerUSerId, paMainId, caMainId, Mobile, MsgType, IsCat, Msg) 
		SELECT TOP 1 SendMan, ManagerUSerId, paMainId, caMainId, Mobile, MsgType, IsCat, Msg 
		FROM smsmessagelog 
		WHERE mobile=(
			SELECT TOP 1 mobile 
			FROM caGetPasswordLog WITH(NOLOCK) 
			WHERE askno = @AskNo 
			AND  mobile IS NOT NULL
		) AND adddate>@AddDate 
		AND MsgType=9 ORDER BY id desc
		RETURN @CNT
	END
	RETURN -1
--END TRY
--BEGIN CATCH
--	RETURN 0
--END CATCH


GO
/****** Object:  StoredProcedure [dbo].[ProcSmsMessageLogInsert]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2014.10.28
--创建人：John
--说明：短信通知日志新增
--#####################################################
CREATE PROCEDURE [dbo].[ProcSmsMessageLogInsert]
(
	@SendMan SMALLINT,
	@ManagerUserId SMALLINT,
	@paMainId INT,
	@caMainId INT,
	@Mobile VARCHAR(20),
	@Msg NVARCHAR(210),
	@MsgType TINYINT,
	@IsCat BIT
)
AS
SET NOCOUNT ON
BEGIN
	IF @MsgType IN(102, 105) AND @paMainId > 0
	BEGIN
		IF EXISTS(SELECT 'x' FROM wxFans WITH(NOLOCK) WHERE paMainId = @paMainId)
			RETURN
	END
--	IF @MsgType = 122 AND @Msg LIKE '%珠江%'
--	BEGIN
--		INSERT PROCLog SELECT 'ProcSmsMessageLogInsert', @Mobile, GETDATE()
--		RETURN
--	END
	IF EXISTS(SELECT 'x' FROM SmsMessageLog WITH(NOLOCK) WHERE Mobile = @Mobile AND Msg = @Msg AND AddDate > GETDATE() - 0.3)
		RETURN
 
	INSERT INTO SmsMessageLog (SendMan, ManagerUserId, paMainId, caMainId, Mobile, Msg, MsgType, IsCat)
	SELECT @SendMan, @ManagerUserId, @paMainId, @caMainId, @Mobile, @Msg, @MsgType, @IsCat
END

GO
/****** Object:  StoredProcedure [dbo].[ProcSmsMessageLogInsertBySendDate]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2018.4.26
--创建人：Harry
--说明：实时短信发送成功插入记录
--#####################################################
CREATE PROCEDURE [dbo].[ProcSmsMessageLogInsertBySendDate]
(
	@SendMan SMALLINT,
	@ManagerUserId SMALLINT,
	@paMainId INT,
	@caMainId INT,
	@Mobile VARCHAR(20),
	@Msg NVARCHAR(210),
	@PortNo INT,
	@MsgType TINYINT,
	@IsCat BIT
)
AS
SET NOCOUNT ON
BEGIN  
	INSERT INTO SmsMessageLog (SendMan, ManagerUserId, paMainId, caMainId, Mobile, Msg,PortNo, MsgType, IsCat,AddDate,SendDate,SendStatus)
	SELECT @SendMan, @ManagerUserId, @paMainId, @caMainId, @Mobile, @Msg, @PortNo, @MsgType, @IsCat,GETDATE(),GETDATE(),1
END
SET NOCOUNT OFF

GO
/****** Object:  StoredProcedure [dbo].[ProcSmsMessageLogSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--sean add
CREATE PROCEDURE [dbo].[ProcSmsMessageLogSelect]
AS
SET NOCOUNT ON
INSERT ProcLog SELECT 'ProcSmsMessageLogSelect', '', GETDATE()
BEGIN
	DECLARE @Day7 AS DATETIME, @Day1 AS DATETIME
	SET @Day7 = CONVERT(DATETIME, CONVERT(VARCHAR(10), GETDATE() - 7, 120))
	SET @Day1 = CONVERT(DATETIME, CONVERT(VARCHAR(10), GETDATE() - 1, 120))
	 
	DECLARE @t AS TABLE(
		ID int, 
		SendMan smallint, 
		ManagerUserId smallint, 
		paMainId int, 
		caMainId int, 
		Mobile varchar(max), 
		Msg nvarchar(210), 
		IsCat bit, 
		AddDate smalldatetime, 
		PortNo tinyint, 
		SendDate datetime, 
		SendStatus bit, 
		SmsType tinyint, 
		MsgType tinyint, 
		IsDelete BIT
	)

	DECLARE @c AS TABLE(
		Mobile VARCHAR(max), 
		MsgType tinyint, 
		AddDate DATETIME, 
		Cnt INT
		)

	IF DATEPART(Hour, GETDATE()) >= 8 AND DATEPART(MINUTE, GETDATE()) < 10
		INSERT INTO @t
		SELECT TOP 20 *, 0 FROM SmsMessageLog WITH(NOLOCK)
		WHERE SendDate IS NULL 
		AND SmsType = 1
		AND MsgType <> 116
		AND AddDate > DATEADD(MINUTE, -1200, GETDATE()) --@Day7
		ORDER BY Case Msgtype When 113 Then 1 ELSE 100 END, ID DESC
	ELSE
		INSERT INTO @t
		SELECT TOP 20 *, 0 FROM SmsMessageLog WITH(NOLOCK)
		WHERE SendDate IS NULL 
		AND SmsType = 1
		AND MsgType <> 116
		AND AddDate > DATEADD(MINUTE, -20, GETDATE()) --@Day7
		--AND MOBILE = '18363443519'
		ORDER BY Case Msgtype When 113 Then 1 ELSE 100 END, ID DESC

	IF @@ROWCOUNT = 0
	BEGIN
		SELECT * FROM @t
		RETURN
	END

	DELETE @t WHERE MsgType = 116	

	IF EXISTS(SELECT 'x' FROM @t WHERE paMainId > 0 OR caMainId > 0)
	BEGIN
		DECLARE @wx AS TABLE(Id INT, paMainId INT, caMainId INT, Msg NVARCHAR(210),
			WxFansId INT, OpenId VARCHAR(50), WxServiceNoID INT, paName NVARCHAR(6),
			WebsiteName NVARCHAR(10), WxTemplateNo VARCHAR(100),
			ParaValue VARCHAR(1000), JsonMessage VARCHAR(1000),
			UserType TINYINT, ProvinceDomain VARCHAR(100))

		INSERT INTO @wx(Id, paMainId, Msg, WxFansId, OpenId, wxServiceNoId, UserType)
		SELECT a.Id, a.paMainId, a.Msg, b.Id WxFansId, b.OpenId, b.wxServiceNoId, 1
		FROM @t a, WxFans b WITH(NOLOCK)
		WHERE a.paMainId = b.paMainId
		AND b.Status > 0
		AND a.PaMainId > 0
		AND MsgType NOT IN(9, 25, 104,	109, 110, 113, 117, 119, 122)
	
		INSERT INTO @wx(Id, caMainId, Msg, WxFansId, OpenId, wxServiceNoId, UserType)		--new add
		SELECT a.Id, a.caMainId, a.Msg, b.Id WxFansId, b.OpenId, b.wxServiceNoId, 2
		FROM @t a, WxFans b WITH(NOLOCK)
		WHERE a.caMainId = b.caMainId
		AND b.caBindCancelDate IS NULL
		AND ISNULL(a.PaMainId, 0) = 0
		AND MsgType NOT IN(9, 10, 21, 22, 23, 25, 104,	109, 110, 113, 117, 119, 122, 139)	

		UPDATE a SET a.paName = b.Name FROM @wx a, paMain b WITH(NOLOCK) WHERE a.paMainId = b.Id AND a.UserType = 1
		UPDATE a SET a.paName = b.Name FROM @wx a, caMain b WITH(NOLOCK) WHERE a.caMainId = b.Id AND a.UserType = 2
		UPDATE @Wx SET paName = '' WHERE paName IS NULL
		UPDATE a SET a.WebsiteName = c.WebsiteName, a.ProvinceDomain = c.ProvinceDomain
		FROM @wx a, WxServiceNo b WITH(NOLOCK), dcprovince c WITH(NOLOCK)
		WHERE a.WxServiceNoId = b.Id
		AND b.ProvinceID = c.Id

		UPDATE a SET a.WxTemplateNo = b.[no] FROM @wx a, WxTemplateNo b WITH(NOLOCK) WHERE a.WxServiceNoID = b.WxServiceNoID AND b.WxTemplateId = 13 
		--插入参数数据
		UPDATE @wx SET ParaValue = '"first":{    "value":"#PaName#您好",    "color":"#000000"},  "keyword1":{    "value":"网站消息",    "color":"#004694"},  "keyword2":{    "value":"请您查看",    "color":"#004694"},  "remark":{    "value":"#JobDesc# #WebsiteName#，找工作，更靠谱",    "color":"#004694"}'
		UPDATE @wx SET ParaValue = REPLACE(ParaValue, '#PaName#', PaName) 
		UPDATE @wx SET ParaValue = REPLACE(ParaValue, '#JobDesc#', Msg)
		UPDATE @wx SET ParaValue = REPLACE(ParaValue, '#WebsiteName#', WebsiteName)
		UPDATE @wx SET JsonMessage = '{"touser":"' + OpenId + '", "template_id":"' + WxTemplateNo + '", "url":"", "topcolor":"#000000", "data":{' + ParaValue + '}}' WHERE Msg NOT LIKE '%应聘简历未答复%'
		UPDATE @wx SET JsonMessage = '{"touser":"' + OpenId + '", "template_id":"' + WxTemplateNo + '", "url":"http://m.' + ProvinceDomain + '/library/WechatOauthCpLogin?opid=' + OpenId + '&urlfile=/company/cv/applycv", "topcolor":"#000000", "data":{' + ParaValue + '}}' WHERE Msg LIKE '%应聘简历未答复%'

		--更新wxmessagesend中的message
		INSERT INTO wxMessageSend2(TemplateType, WxfansId, paMainId, caMainId, MessageText, ErrorNumber, AddDate)
		SELECT 20, WxFansId, paMainId, caMAinId, JsonMessage, 0, GETDATE() FROM @wx

		--UPDATE @t SET IsDelete = 1 WHERE Id IN(SELECT Id FROM @Wx)
	END

	INSERT INTO @c
	SELECT Mobile, MsgType, MAX(AddDate), COUNT(*)
	FROM SmsMessageLog WITH(NOLOCK)
	WHERE SmsType = 1
	AND ID NOT IN(SELECT ID FROM @t)
	AND Mobile IN(SELECT Mobile FROM @t)
	--AND AddDate > @Day1
	GROUP BY Mobile, MsgType

	UPDATE @t SET IsDelete = 1
	WHERE MsgType IN(1, 3, 5)
	AND Mobile IN(SELECT Mobile FROM @c WHERE MsgType IN(1, 3, 5) AND AddDate > @Day1)
	--UPDATE @t SET IsDelete = 1 WHERE Msg like '%验证码是：'
 
	UPDATE @t SET IsDelete = 1
	WHERE MsgType IN(2, 4, 19)
	AND Mobile IN(SELECT Mobile FROM @c WHERE MsgType IN(2, 4, 19) AND AddDate > @Day1)

	UPDATE a SET a.IsDelete = 1
	FROM @t a, @c b
	WHERE a.MsgType = b.MsgType
	AND a.Mobile = b.Mobile
	AND b.AddDate > @Day1
	AND a.MsgType IN(7, 8, 20, 102)
	
	UPDATE a SET a.IsDelete = 1
	FROM @t a, @c b
	WHERE a.MsgType = b.MsgType
	AND a.Mobile = b.Mobile
	AND b.AddDate > @Day1
	AND a.MsgType IN(9, 10)
	AND b.Cnt > 2
	AND a.MsgType < 200

	UPDATE @t SET IsDelete = 1
	WHERE MsgType IN(12, 13, 14, 15)
	AND Mobile IN(SELECT Mobile FROM @c )

	UPDATE @t SET IsDelete = 1
	WHERE MsgType IN(11, 106, 107, 108)
	AND Mobile IN(SELECT Mobile FROM @c WHERE AddDate > @Day1)

	UPDATE @t SET IsDelete = 1
	WHERE MsgType IN(109, 111, 112)
	AND Mobile IN(SELECT Mobile FROM @c WHERE MsgType IN(109, 111, 112) AND AddDate > @Day7)

	UPDATE @t SET IsDelete = 1 WHERE dbo.IsMobile(Mobile) = 0 OR LEN(ISNULL(Msg, '')) < 4
	UPDATE @t SET IsDelete = 1 WHERE Mobile IN(SELECT Mobile FROM NoSendSms)

	UPDATE @t SET PortNo = 11
	--UPDATE @t SET PortNo = 11 WHERE MsgType IN(101)
	UPDATE @t SET PortNo = 12 WHERE MsgType IN(12, 25)
	--UPDATE @t SET PortNo = 13 WHERE MsgType IN(116)
	UPDATE @t SET PortNo = 12 WHERE MsgType IN(26, 220)
	UPDATE @t SET PortNo = 12 WHERE MsgType IN(9, 10, 17, 21, 22, 23, 104, 113, 117, 202, 204)
	--UPDATE @t SET PortNo = 1 WHERE MsgType IN(9, 10, 17, 21, 22, 23, 104, 113, 117, 202, 204)
	--UPDATE @t SET PortNo = 12 WHERE MsgType IN(9, 10, 17, 21, 22, 23, 104, 113, 117, 202, 204)
	--UPDATE @t SET PortNo = 1 WHERE MsgType IN(222)
	--UPDATE @t SET Msg = '【伍亿】' + msg WHERE PortNo = 1
	UPDATE @t SET Msg = REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(Msg, '发票', '发.票'), '银行', '银.行'), '开户', '开.户'), '..', '.'), '聘', '.聘'), '面试', '面.试')
	--WHERE PortNo = 2

	UPDATE @t SET Msg = REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(Msg, '求职', '求.职'), '房地产', '房.地.产'), '房产', '房.产'), '广告', '广.告'), '担保', '担.保')

	--WHERE PortNo = 2
	--UPDATE @t SET Msg = REPLACE(Msg, '@51rc_com', '@51rc.com')

--	UPDATE a
--	SET IsDelete = 1
--	FROM @t a, BlackWord b WITH(NOLOCK) 
--	WHERE CHARINDEX(b.KeyWord, a.Msg) > 0

	UPDATE a
	SET IsDelete = 0
	FROM @t a, BlackWord b WITH(NOLOCK) 
	WHERE MsgType = 113

	UPDATE SmsMessageLog SET SmsType = 3 WHERE ID IN(SELECT ID FROM @t WHERE IsDelete = 1)

	--INSERT @t 
	--SELECT Id, 0, 0, 0, 0, Mobile, Msg, 0, GETDATE(), 13, NULL, NULL, 1, 116, 0
	--FROM smsBatchSend
	--WHERE SendStatus IS NULL

	SELECT * FROM @t WHERE IsDelete = 0

	INSERT INTO ServiceRunLog(ServiceId, RunRows, RunId, RunStatus, RunMessage)
	SELECT 1, @@RowCount, 0, 1, '提取短信数据'
END
GO
/****** Object:  StoredProcedure [dbo].[ProcSmsMessageLogSelect2]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--portno 1 yimei;2zhongjia;3~10 mobile cat; 11~13 dxt
CREATE PROCEDURE [dbo].[ProcSmsMessageLogSelect2]
AS
SET NOCOUNT ON
INSERT ProcLog SELECT 'ProcSmsMessageLogSelect2', '', GETDATE()
BEGIN
	DECLARE @Day7 AS DATETIME, @Day1 AS DATETIME
	SET @Day7 = CONVERT(DATETIME, CONVERT(VARCHAR(10), GETDATE() - 7, 120))
	SET @Day1 = CONVERT(DATETIME, CONVERT(VARCHAR(10), GETDATE() - 1, 120))
	 
	DECLARE @t AS TABLE(
		ID int,
		SendMan smallint,
		ManagerUserId smallint,
		paMainId int,
		caMainId int,
		Mobile varchar(max),
		Msg nvarchar(210),
		IsCat bit,
		AddDate smalldatetime,
		PortNo tinyint,
		SendDate datetime,
		SendStatus bit,
		SmsType tinyint,
		MsgType tinyint,
		IsDelete BIT
	)

	DECLARE @c AS TABLE(
		Mobile VARCHAR(max),
		MsgType tinyint,
		AddDate DATETIME,
		Cnt INT
		)

/*	IF DatePArt(Hour, GETDATE()) < 7 OR  DatePArt(Hour, GETDATE()) >= 22
	BEGIN
		SELECT * FROM @t
		RETURN
	END
*/
	IF DatePArt(Hour, GETDATE()) > 7 OR  DatePArt(Hour, GETDATE()) <= 23
		INSERT INTO @t
		SELECT TOP 160 *, 0 FROM SmsMessageLog WITH(NOLOCK)
		WHERE SendDate IS NULL 
		AND SmsType = 1
		AND AddDate > DATEADD(MINUTE, -60, GETDATE()) --@Day7
		ORDER BY Case Msgtype When 113 Then 1 ELSE 100 END, ID DESC
	ELSE
		INSERT INTO @t
		SELECT TOP 160 *, 0 FROM SmsMessageLog WITH(NOLOCK)
		WHERE SendDate IS NULL 
		AND SmsType = 1
		AND AddDate > DATEADD(MINUTE, -60, GETDATE()) --@Day7
		AND MsgType = 139
		ORDER BY ID DESC

	IF @@RowCount = 0
	BEGIN
		SELECT * FROM @t
		RETURN
	END

	DELETE @t WHERE MsgType = 116	

	INSERT INTO @c
	SELECT Mobile, MsgType, Max(AddDate), COUNT(*)
	FROM SmsMessageLog WITH(NOLOCK)
	WHERE AddDate > @Day7
	AND SmsType = 1
	AND ID NOT IN(SELECT ID FROM @t)
	AND Mobile IN(SELECT Mobile FROM @t)
	GROUP BY Mobile, MsgType

	UPDATE @t SET IsDelete = 1
	WHERE MsgType IN(1,3,5)
	AND Mobile IN(SELECT Mobile FROM @c  WHERE MsgType IN(1,3,5) AND AddDate > @Day1)

	UPDATE @t SET IsDelete = 1
	WHERE MsgType IN(2,4,19)
	AND Mobile IN(SELECT Mobile FROM @c  WHERE MsgType IN(2,4,19) AND AddDate > @Day1)

	UPDATE @t SET IsDelete = 1
	WHERE MsgType = 7
	AND Mobile IN(SELECT Mobile FROM @c  WHERE MsgType = 7 AND AddDate > @Day1)

	UPDATE @t SET IsDelete = 1
	WHERE MsgType = 8
	AND Mobile IN(SELECT Mobile FROM @c  WHERE MsgType = 8 AND AddDate > @Day1)

	UPDATE @t SET IsDelete = 1
	WHERE MsgType = 9
	AND Mobile IN(SELECT Mobile FROM @c  WHERE MsgType = 9 AND AddDate > @Day1 AND Cnt > 2)

	UPDATE @t SET IsDelete = 1
	WHERE MsgType = 20
	AND Mobile IN(SELECT Mobile FROM @c  WHERE MsgType = 20 AND AddDate > @Day1)

	UPDATE @t SET IsDelete = 1
	WHERE MsgType = 10
	AND Mobile IN(SELECT Mobile FROM @c  WHERE MsgType = 9 AND AddDate > @Day1 AND Cnt > 2)

	UPDATE @t SET IsDelete = 1
	WHERE MsgType IN(12,13,14,15)
	AND Mobile IN(SELECT Mobile FROM @c )

	UPDATE @t SET IsDelete = 1
	WHERE MsgType = 11
	AND Mobile IN(SELECT Mobile FROM @c  WHERE AddDate > @Day1)

	UPDATE @t SET IsDelete = 1
	WHERE MsgType = 102
	AND Mobile IN(SELECT Mobile FROM @c WHERE MsgType = 102 AND AddDate > @Day1)

	UPDATE @t SET IsDelete = 1
	WHERE MsgType = 102
	AND Mobile IN(SELECT Mobile FROM @c WHERE MsgType = 102 AND AddDate > @Day1)

	UPDATE @t SET IsDelete = 1
	WHERE MsgType BETWEEN 106 AND 108
	AND Mobile IN(SELECT Mobile FROM @c WHERE AddDate > @Day1)

	UPDATE @t SET IsDelete = 1
	WHERE MsgType IN(109, 111, 112)
	AND Mobile IN(SELECT Mobile FROM @c WHERE MsgType IN(109, 111, 112) AND AddDate > @Day7)

	UPDATE @t SET IsDElete = 1 WHERE dbo.IsMobile(Mobile) = 0 OR LEN(ISNULL(Msg, '')) < 4
	UPDATE @t SET IsDElete = 1 WHERE Mobile IN(SELECT Mobile FROM NoSendSms)

	UPDATE @t SET PortNo = 11
	UPDATE @t SET PortNo = 12 WHERE MsgType IN(25)
	--UPDATE @t SET PortNo = 13 WHERE MsgType IN(116)
	UPDATE @t SET PortNo = 2 WHERE MsgType IN(26, 220)
	UPDATE @t SET PortNo = 1 WHERE MsgType IN(9,10,17,21,22,23,104,113,117,119,202,204)

	--UPDATE @t SET Msg = '【伍亿】'+msg
	--WHERE PortNo = 1
	UPDATE @t SET Msg = REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(Msg, '发票','发.票'), '银行', '银.行'), '开户', '开.户'), '..', '.'), '聘', '.聘'), '面试', '面.试'), 'www.', 'www_'), '.com', '_com')
	WHERE PortNo = 2
	UPDATE @t SET Msg = REPLACE(REPLACE(REPLACE(Msg, '求职', '求.职'), '房地产', '房.地.产'), '房产', '房.产')
	WHERE PortNo = 2
	UPDATE @t SET Msg = REPLACE(REPLACE(Msg, '广告', '广.告'), '发票', '发.票')

	UPDATE a
	SET IsDelete = 1
	FROM @t a, BlackWord b WITH(NOLOCK) 
	WHERE CHARINDEX(b.KeyWord, a.Msg) > 0

	UPDATE a
	SET IsDelete = 0
	FROM @t a, BlackWord b WITH(NOLOCK) 
	WHERE MsgType = 113

	UPDATE SmsMessageLog SET SmsType = 3 WHERE ID IN(SELECT ID FROM @t WHERE IsDelete = 1)

	--INSERT @t 
	--SELECT Id, 0, 0, 0, 0, Mobile, Msg, 0, GETDATE(), 13, NULL, NULL, 1, 116, 0
	--FROM smsBatchSend

	SELECT * FROM @t WHERE IsDelete = 0

	INSERT INTO ServiceRunLog(ServiceId, RunRows, RunId, RunStatus, RunMessage)
	SELECT 1, @@RowCount, 0, 1, '提取短信数据'
END





GO
/****** Object:  StoredProcedure [dbo].[ProcSmsMessageLogSelect3]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--portno 1 yimei;2zhongjia;3~10 mobile cat; 11~13 dxt
CREATE PROCEDURE [dbo].[ProcSmsMessageLogSelect3]
AS
BEGIN
	DECLARE @Day7 AS DATETIME, @Day1 AS DATETIME
	SET @Day7 = CONVERT(DATETIME, CONVERT(VARCHAR(10), GETDATE() - 7, 120))
	SET @Day1 = CONVERT(DATETIME, CONVERT(VARCHAR(10), GETDATE() - 1, 120))
	 
	DECLARE @t AS TABLE(
		ID int,
		SendMan smallint,
		ManagerUserId smallint,
		paMainId int,
		caMainId int,
		Mobile varchar(max),
		Msg nvarchar(210),
		IsCat bit,
		AddDate smalldatetime,
		PortNo tinyint,
		SendDate datetime,
		SendStatus bit,
		SmsType tinyint,
		MsgType tinyint,
		IsDelete BIT
	)

	DECLARE @c AS TABLE(
		Mobile VARCHAR(max),
		MsgType tinyint,
		AddDate DATETIME,
		Cnt INT
		)

/*	IF DATEPART(Hour, GETDATE()) < 7 OR  DATEPART(Hour, GETDATE()) >= 22
	BEGIN
		SELECT * FROM @t
		RETURN
	END
*/
	INSERT INTO @t
	SELECT TOP 10 *, 0 FROM SmsMessageLog WITH(NOLOCK)
	WHERE id = 8365770

	IF @@RowCount = 0
	BEGIN
		SELECT * FROM @t
		RETURN
	END

	DELETE @t WHERE MsgType = 116	

	INSERT INTO @c
	SELECT Mobile, MsgType, Max(AddDate), COUNT(*)
	FROM SmsMessageLog WITH(NOLOCK)
	WHERE AddDate > @Day7
	AND SmsType = 1
	AND ID NOT IN(SELECT ID FROM @t)
	AND Mobile IN(SELECT Mobile FROM @t)
	GROUP BY Mobile, MsgType

	UPDATE @t SET IsDelete = 1
	WHERE MsgType IN(1,3,5)
	AND Mobile IN(SELECT Mobile FROM @c WHERE MsgType IN(1,3,5) AND AddDate > @Day1)
	--UPDATE @t SET IsDelete = 1 WHERE Msg like '%验证码是：'

	UPDATE @t SET IsDelete = 1
	WHERE MsgType IN(2,4,19)
	AND Mobile IN(SELECT Mobile FROM @c WHERE MsgType IN(2,4,19) AND AddDate > @Day1)

	UPDATE @t SET IsDelete = 1
	WHERE MsgType = 7
	AND Mobile IN(SELECT Mobile FROM @c WHERE MsgType = 7 AND AddDate > @Day1)

	UPDATE @t SET IsDelete = 1
	WHERE MsgType = 8
	AND Mobile IN(SELECT Mobile FROM @c WHERE MsgType = 8 AND AddDate > @Day1)

	UPDATE @t SET IsDelete = 1
	WHERE MsgType = 9
	AND Mobile IN(SELECT Mobile FROM @c WHERE MsgType = 9 AND AddDate > @Day1 AND Cnt > 2)

	UPDATE @t SET IsDelete = 1
	WHERE MsgType = 20
	AND Mobile IN(SELECT Mobile FROM @c WHERE MsgType = 20 AND AddDate > @Day1)

	UPDATE @t SET IsDelete = 1
	WHERE MsgType = 10
	AND Mobile IN(SELECT Mobile FROM @c WHERE MsgType = 9 AND AddDate > @Day1 AND Cnt > 2)

	UPDATE @t SET IsDelete = 1
	WHERE MsgType IN(12,13,14,15)
	AND Mobile IN(SELECT Mobile FROM @c )

	UPDATE @t SET IsDelete = 1
	WHERE MsgType = 11
	AND Mobile IN(SELECT Mobile FROM @c WHERE AddDate > @Day1)

	UPDATE @t SET IsDelete = 1
	WHERE MsgType = 102
	AND Mobile IN(SELECT Mobile FROM @c WHERE MsgType = 102 AND AddDate > @Day1)

	UPDATE @t SET IsDelete = 1
	WHERE MsgType = 102
	AND Mobile IN(SELECT Mobile FROM @c WHERE MsgType = 102 AND AddDate > @Day1)

	UPDATE @t SET IsDelete = 1
	WHERE MsgType BETWEEN 106 AND 108
	AND Mobile IN(SELECT Mobile FROM @c WHERE AddDate > @Day1)

	UPDATE @t SET IsDelete = 1
	WHERE MsgType IN(109, 111, 112)
	AND Mobile IN(SELECT Mobile FROM @c WHERE MsgType IN(109, 111, 112) AND AddDate > @Day7)
select isdelete,1,* from @t
	UPDATE @t SET IsDElete = 1 WHERE dbo.IsMobile(Mobile) = 0 OR LEN(ISNULL(Msg, '')) < 4
	UPDATE @t SET IsDElete = 1 WHERE Mobile IN(SELECT Mobile FROM NoSendSms)

	UPDATE @t SET PortNo = 11
	--UPDATE @t SET PortNo = 11 WHERE MsgType IN(101)
	UPDATE @t SET PortNo = 12 WHERE MsgType IN(12,25)
	--UPDATE @t SET PortNo = 13 WHERE MsgType IN(116)
	UPDATE @t SET PortNo = 12 WHERE MsgType IN(26, 220)
	UPDATE @t SET PortNo = 12 WHERE MsgType IN(9,10,17,21,22,23,104,113,117,202,204)
	--UPDATE @t SET PortNo = 1 WHERE MsgType IN(9,10,17,21,22,23,104,113,117,202,204)
	--UPDATE @t SET PortNo = 12 WHERE MsgType IN(9,10,17,21,22,23,104,113,117,202,204)
	--UPDATE @t SET PortNo = 1 WHERE MsgType IN(222)
	--UPDATE @t SET Msg = '【伍亿】' + msg WHERE PortNo = 1
	UPDATE @t SET Msg = REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(Msg, '发票','发.票'), '银行', '银.行'), '开户', '开.户'), '..', '.'), '聘', '.聘'), '面试', '面.试')
	--WHERE PortNo = 2

	UPDATE @t SET Msg = REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(Msg, '求职', '求.职'), '房地产', '房.地.产'), '房产', '房.产'), '广告', '广.告'), '担保', '担.保')

	--WHERE PortNo = 2
	--UPDATE @t SET Msg = REPLACE(Msg, '@51rc_com', '@51rc.com')
select isdelete,2,* from @t
	UPDATE a
	SET IsDelete = 1
	FROM @t a, BlackWord b WITH(NOLOCK) 
	WHERE CHARINDEX(b.KeyWord, a.Msg) > 0
select isdelete,3,* from @t
	UPDATE a
	SET IsDelete = 0
	FROM @t a, BlackWord b WITH(NOLOCK) 
	WHERE MsgType = 113
select isdelete,4,* from @t
	UPDATE SmsMessageLog SET SmsType = 3 WHERE ID IN(SELECT ID FROM @t WHERE IsDelete = 1)

	--INSERT @t 
	--SELECT Id, 0, 0, 0, 0, Mobile, Msg, 0, GETDATE(), 13, NULL, NULL, 1, 116, 0
	--FROM smsBatchSend
	--WHERE SendStatus IS NULL

	SELECT * FROM @t WHERE IsDelete = 0

	INSERT INTO ServiceRunLog(ServiceId, RunRows, RunId, RunStatus, RunMessage)
	SELECT 1, @@RowCount, 0, 1, '提取短信数据'
END





GO
/****** Object:  StoredProcedure [dbo].[ProcSmsWatchLogInsert]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ProcSmsWatchLogInsert]
(
	@d VARCHAR(8)
)
AS
BEGIN
	UPDATE SmsWatch
	SET IsSend = 1
	WHERE IsSend = 0
	AND WatchDate = @d
	AND Mobile IN(SELECT Mobile FROM SmsMessageLog WHERE AddDate > @d)

	DECLARE @LoginNumber AS INT, @AllNumber AS INT, 
		@LoginNumberSend AS INT, @AllNumberSend AS INT, 
		@LoginNumberNotSend AS INT, @AllNumberNotSend AS INT, 
		@Now AS DATETIME, @MsgType TINYINT

	SET @Now = GETDATE()
	DECLARE curMsgType CURSOR FOR SELECT DISTINCT MsgType FROM SmsWatch WHERE MsgType < 50
	OPEN curMsgType
	FETCH NEXT FROM curMsgType INTO @MsgType

	WHILE @@FETCH_STATUS >= 0
	BEGIN
		SELECT @LoginNumberNotSend = COUNT(DISTINCT a.caMainId)
		FROM SmsWatch a, caLoginLog b
		WHERE a.caMainId = b.caMainId
		AND b.AddDate > @d
		AND a.IsSend = 0
		AND a.WatchDate = @d
		AND MsgType = @MsgType

		SELECT @LoginNumberSend = COUNT(DISTINCT a.caMainId)
		FROM SmsWatch a, caLoginLog b
		WHERE a.caMainId = b.caMainId
		AND b.AddDate > @d
		AND a.IsSend = 1
		AND a.WatchDate = @d
		AND MsgType = @MsgType

		SELECT @AllNumberSend = COUNT(DISTINCT caMainId)
		FROM SmsWatch
		WHERE WatchDate = @d
		AND IsSend = 1
		AND MsgType = @MsgType

		SELECT @AllNumberNotSend = COUNT(DISTINCT caMainId)
		FROM SmsWatch
		WHERE WatchDate = @d
		AND IsSend = 0
		AND MsgType = @MsgType

		SELECT @LoginNumber = @LoginNumberSend + @LoginNumberNotSend, @AllNumber = @AllNumberSend + @AllNumberNotSend
		IF @AllNumber > 0
			INSERT SmsWatchLog (WatchDate, SendDate, LoginNumber, AllNumber, LoginNumberSend, AllNumberSend, LoginNumberNotSend, AllNumberNotSend, MsgType)
			SELECT @Now, @d, @LoginNumber, @AllNumber, @LoginNumberSend, @AllNumberSend, @LoginNumberNotSend, @AllNumberNotSend, @MsgType

		FETCH NEXT FROM curMsgType INTO @MsgType
	END
	CLOSE curMsgType
	DEALLOCATE curMsgType

	------person summary
	DECLARE @t AS TABLE(ID INT, IsSend BIT, LastLoginDate SMALLDATETIME)
	DECLARE curMsgType2 CURSOR FOR SELECT DISTINCT MsgType FROM SmsWatch WHERE MsgType >100 AND MsgType < 200
	OPEN curMsgType2
	FETCH NEXT FROM curMsgType2 INTO @MsgType

	WHILE @@FETCH_STATUS >= 0
	BEGIN
		DELETE @t

		INSERT @t (ID, IsSend)
		SELECT caMainId, IsSend FROM SmsWatch
		WHERE WatchDate = @d
		AND MsgType = @MsgType

		UPDATE a SET a.LastLoginDate = b.LastLoginDate
		FROM @t a, paMain b
		WHERE a.id = b.Id

		SELECT @LoginNumberNotSend = COUNT(DISTINCT Id)
		FROM @t
		WHERE LastLoginDate > @d
		AND IsSend = 0

		SELECT @LoginNumberSend = COUNT(DISTINCT Id)
		FROM @t
		WHERE LastLoginDate > @d
		AND IsSend = 1

		SELECT @AllNumberSend = COUNT(DISTINCT caMainId)
		FROM SmsWatch
		WHERE WatchDate = @d
		AND IsSend = 1
		AND MsgType = @MsgType

		SELECT @AllNumberNotSend = COUNT(DISTINCT caMainId)
		FROM SmsWatch
		WHERE WatchDate = @d
		AND IsSend = 0
		AND MsgType = @MsgType

		SELECT @LoginNumber = @LoginNumberSend + @LoginNumberNotSend, @AllNumber = @AllNumberSend + @AllNumberNotSend
		IF @AllNumber > 0
			INSERT SmsWatchLog (WatchDate, SendDate, LoginNumber, AllNumber, LoginNumberSend, AllNumberSend, LoginNumberNotSend, AllNumberNotSend, MsgType)
			SELECT @Now, @d, @LoginNumber, @AllNumber, @LoginNumberSend, @AllNumberSend, @LoginNumberNotSend, @AllNumberNotSend, @MsgType

		FETCH NEXT FROM curMsgType2 INTO @MsgType
	END
	CLOSE curMsgType2
	DEALLOCATE curMsgType2
END














GO
/****** Object:  StoredProcedure [dbo].[ProcSourceAnalysis1]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ProcSourceAnalysis1]
AS
BEGIN
	DECLARE @CountDate INT, @ProvinceId INT,
		@Domain VARCHAR(50), @VersionId INT, @v INT

	SET @CountDate = CONVERT(VARCHAR(8), GETDATE() - 1, 112)

	DECLARE curVersion CURSOR FOR 
		SELECT Version.Id, Version.Province_Id, Province.Domain
		FROM Version WITH(NOLOCK), Province WITH(NOLOCK)
		WHERE Version.Id <> Version.Province_Id 
		AND Version.Province_Id = Province.Id
		ORDER BY Version.Id
	FOR READ ONLY

	OPEN curVersion
	FETCH NEXT FROM curVersion INTO @VersionId, @ProvinceId, @Domain

	WHILE @@FETCH_STATUS = 0
	BEGIN
		INSERT INTO Seconderer_Count(CountDate, Province_Id, Howmany, Referer, VersionId) 
		SELECT TOP 200 @CountDate, @ProvinceId, COUNT(1) AllNum, LEFT(Referer, CHARINDEX('/', Referer, 8)) Ref, @VersionId
		FROM Seconderer WITH(NOLOCK)
		WHERE CHARINDEX('/', Referer, 8) > 0
		AND VersionId = @VersionId
		AND CHARINDEX(@Domain, Referer, 0) NOT BETWEEN 1 AND 10
		GROUP BY left(Referer, CHARINDEX('/', Referer, 8))
		ORDER BY AllNum DESC

		SET @v = 10000 + @VersionId
		INSERT INTO Seconderer_Count(CountDate, Province_Id, Howmany, Referer, VersionId) 
		SELECT TOP 200 @CountDate, 100 + @ProvinceId, COUNT(1) AllNum, LEFT(Referer, CHARINDEX('/', Referer, 8)) Ref, @V
		FROM Seconderer WITH(NOLOCK)
		WHERE CHARINDEX('/', Referer, 8) > 0
		AND VersionId = @V
		AND CHARINDEX(@Domain, Referer, 0) NOT BETWEEN 1 AND 10
		GROUP BY left(Referer, CHARINDEX('/', Referer, 8))
		ORDER BY AllNum DESC
		
		SET @v = 20000 + @VersionId
		INSERT INTO Seconderer_Count(CountDate, Province_Id, Howmany, Referer, VersionId) 
		SELECT TOP 200 @CountDate, 200 + @ProvinceId, COUNT(1) AllNum, LEFT(Referer, CHARINDEX('/', Referer, 8)) Ref, @V
		FROM Seconderer WITH(NOLOCK)
		WHERE CHARINDEX('/', Referer, 8) > 0
		AND VersionId = @V
		AND CHARINDEX(@Domain, Referer, 0) NOT BETWEEN 1 AND 10
		GROUP BY left(Referer, CHARINDEX('/', Referer, 8))
		ORDER BY AllNum DESC

		SET @v = 30000 + @VersionId
		INSERT INTO Seconderer_Count(CountDate, Province_Id, Howmany, Referer, VersionId) 
		SELECT TOP 200 @CountDate, 100 + @ProvinceId, COUNT(1) AllNum, LEFT(Referer, CHARINDEX('/', Referer, 8)) Ref, @V
		FROM Seconderer WITH(NOLOCK)
		WHERE CHARINDEX('/', Referer, 8) > 0
		AND VersionId = @V
		AND CHARINDEX(@Domain, Referer, 0) NOT BETWEEN 1 AND 10
		GROUP BY left(Referer, CHARINDEX('/', Referer, 8))
		ORDER BY AllNum DESC
	
		FETCH NEXT FROM curVersion INTO @VersionId, @ProvinceId, @Domain
	END
	CLOSE curVersion
	DEALLOCATE curVersion
END

GO
/****** Object:  StoredProcedure [dbo].[ProcSourceAnalysis1_2]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ProcSourceAnalysis1_2]
AS
BEGIN
	DECLARE @CountDate INT, @ProvinceId INT,
		@Domain VARCHAR(50), @VersionId INT, @v INT

	SET @CountDate = CONVERT(VARCHAR(8), GETDATE() - 1, 112)

	
/*
	DECLARE curVersion CURSOR FOR 
		SELECT  a.Id, b.Id Province_Id, b.Domain
		FROM dcRegion a WITH(NOLOCK), Province b WITH(NOLOCK)
		WHERE Len(a.Id) = 6
		AND LEFT(a.Id, 2) = b.Id
		AND a.ID IN(320108,320109,320110,320111,320209,320210,320211,320213,320306,320307,320308,320309,320310,320311,320312,320313,320407,320408,320409,320504,320505,320506,320507,320606,320607,320608,320609,320610,320611,320612,320613,320704,320705,320706,320707,320708,320709,320710,320711,320712,320713,320807,320903,320904,320905,320906,320907,320908,320909,320910,320911,320912,321003,321004,321005,321104,321105,321303,321304,321305,321306,321307,321308,321404,321405,321406,321503,321504,321505,321506,321507,321508,321509,321603,321604,321605,321606,321607,321608,321609,321610,321705,321706,321707,321708,321709,321710,321711,321712,321713)
		ORDER BY a.Id
	FOR READ ONLY
*/
 	--2014-8-14 lambo  之前只是统计的山东的，现在统计所有省份的县级市
	DECLARE curVersion CURSOR FOR 
		SELECT  a.Id, b.Id Province_Id, b.Domain
		FROM (SELECT DISTINCT VersionId ID FROM Seconderer) a, Province b WITH(NOLOCK)
		WHERE Len(a.Id) = 6
		AND LEFT(a.Id, 2) = b.Id
		AND a.Id>100000 
		ORDER BY a.Id
	FOR READ ONLY

	OPEN curVersion
	FETCH NEXT FROM curVersion INTO @VersionId, @ProvinceId, @Domain

	WHILE @@FETCH_STATUS = 0
	BEGIN
		INSERT INTO Seconderer_Count(CountDate, Province_Id, Howmany, Referer, VersionId) 
		SELECT TOP 200 @CountDate, @ProvinceId, COUNT(1) AllNum, LEFT(Referer, CHARINDEX('/', Referer, 8)) Ref, @VersionId
		FROM Seconderer WITH(NOLOCK)
		WHERE CHARINDEX('/', Referer, 8)> 0
		AND VersionId = @VersionId
		AND CHARINDEX(@Domain, Referer, 0) NOT BETWEEN 1 AND 10
		GROUP BY left(Referer, CHARINDEX('/', Referer, 8))
		ORDER BY AllNum DESC

		SET @v = 10000 + @VersionId
		INSERT INTO Seconderer_Count(CountDate, Province_Id, Howmany, Referer, VersionId) 
		SELECT TOP 200 @CountDate, 100 + @ProvinceId, COUNT(1) AllNum, LEFT(Referer, CHARINDEX('/', Referer, 8)) Ref, @V
		FROM Seconderer WITH(NOLOCK)
		WHERE CHARINDEX('/', Referer, 8) > 0
		AND VersionId = @V
		AND CHARINDEX(@Domain, Referer, 0) NOT BETWEEN 1 AND 10
		GROUP BY left(Referer, CHARINDEX('/', Referer, 8))
		ORDER BY AllNum DESC
		
		SET @v = 20000 + @VersionId
		INSERT INTO Seconderer_Count(CountDate, Province_Id, Howmany, Referer, VersionId) 
		SELECT TOP 200 @CountDate, 200 + @ProvinceId, COUNT(1) AllNum, LEFT(Referer, CHARINDEX('/', Referer, 8)) Ref, @V
		FROM Seconderer WITH(NOLOCK)
		WHERE CHARINDEX('/', Referer, 8) > 0
		AND VersionId = @V
		AND CHARINDEX(@Domain, Referer, 0) NOT BETWEEN 1 AND 10
		GROUP BY left(Referer, CHARINDEX('/', Referer, 8))
		ORDER BY AllNum DESC
	
		FETCH NEXT FROM curVersion INTO @VersionId, @ProvinceId, @Domain
	END
	CLOSE curVersion
	DEALLOCATE curVersion
END





GO
/****** Object:  StoredProcedure [dbo].[ProcSourceAnalysis10]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ProcSourceAnalysis10]
AS
BEGIN
	SELECT Id, Pr, OutLink, Authority, Correlation, Deleted, Baidu, LinkOur, BaiduRank, Score
	INTO #t
	FROM Link WITH(NOLOCK)

	--UPDATE #t SET OutLink = 1 WHERE OutLink = 0
	UPDATE #t SET Score = 0 WHERE Deleted > 0 OR Baidu = 0 OR Linkour NOT IN(1, 2) OR OutLink = 0

	UPDATE #t SET Score = (0.15 + (0.85 * pr) / OutLink) * Authority * Correlation / 100
	WHERE Deleted = 0 AND Baidu = 1 AND Linkour IN(1, 2) AND OutLink > 0

	INSERT INTO Link_Score(Versionid, Score, Num)
	SELECT Versionid, SUM(Score) Score, COUNT(1) Cnt
	FROM Link WITH(NOLOCK) 
	WHERE Type = 1 
	AND Method = 1
	AND VaLid = 1 
	AND Deleted < 1
	GROUP BY Versionid 
	ORDER BY Versionid
END














GO
/****** Object:  StoredProcedure [dbo].[ProcSourceAnalysis2]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ProcSourceAnalysis2]
AS
BEGIN
	--1职位页面 2公司页面 3新闻页面 4招聘会页面 5求职互助页面 6职位地图 
	--7兼职招聘 8校园招聘 9专业分类 10 /jinan_job/zhangqiu/  15职位地图jobmap/1802.html 
	--20县级新闻列表/zhangqiu/news/ 21个人文档下载 100其它
	CREATE TABLE #t(ProvinceId INT, Referer VARCHAR(200), AllNum INT, InnerPage INT)
	SELECT *, SPACE(200) Ref, SPACE(50) Domain INTO #In FROM Innerer		--WHERE LoginDate < '2014-10-09 02:42:00'
	UPDATE #In SET Ref = LEFT(Referer, CHARINDEX('/', Referer, 8)) 
	DELETE #In WHERE Ref = ''
	UPDATE a SET a.Domain = b.ProvinceDomain FROM #In a, dcProvince b WHERE b.Id = a.Province_Id
	UPDATE a SET a.Domain = b.ProvinceDomain FROM #In a, dcProvince b WHERE b.Id + 100 = a.Province_Id
	UPDATE a SET a.Domain = b.ProvinceDomain FROM #In a, dcProvince b WHERE b.Id + 200 = a.Province_Id
	UPDATE #In SET Domain = '51rc.com' WHERE Domain IS NULL
	DELETE #In WHERE CHARINDEX(Domain, Referer, 0) > 0

	CREATE TABLE #p(ID INT, Domain VARCHAR(100))
	INSERT #p SELECT ID , ProvinceDomain FROM dcProvince
	INSERT #p SELECT 100 + ID , ProvinceDomain FROM dcProvince
	INSERT #p SELECT 200 + ID , ProvinceDomain FROM dcProvince
	INSERT #p SELECT 0, '51rc.com'

	CREATE TABLE #Ref(VersionId INT, Ref VARCHAR(500), Cnt INT)
	INSERT INTO #Ref
	SELECT Province_Id, Ref, COUNT(*) Cnt
	FROM #In WITH(NOLOCK)
	GROUP BY Province_Id, Ref
	ORDER BY Province_Id, COUNT(*) DESC, Ref

	INSERT INTO #Ref
	SELECT VersionId, Ref , COUNT(*) Cnt
	FROM #In
	WHERE LEN(VersionId) > 3
	GROUP BY VersionId, Ref
	ORDER BY VersionId, COUNT(*) DESC, Ref

	SELECT *, ROW_NUMBER() OVER(PARTITION BY VersionId ORDER BY Cnt DESC) RowNo INTO #r FROM #ref 
	DELETE #r WHERE RowNo > 200

	INSERT INTO #t(ProvinceId, Referer, AllNum, InnerPage)
	SELECT Province_Id, a.Ref, COUNT(1) AllNum, InnerPage
	FROM #In a WITH(NOLOCK), #r b
	WHERE a.Province_Id = b.VersionId
	AND a.Ref = b.Ref
	GROUP BY Province_Id, a.Ref, InnerPage
	ORDER BY Province_Id, a.Ref, COUNT(*) DESC

	INSERT INTO #t(ProvinceId, Referer, AllNum, InnerPage)
	SELECT a.VersionId, a.Ref, COUNT(1) AllNum, InnerPage
	FROM #In a WITH(NOLOCK), #r b
	WHERE a.VersionId = b.VersionId
	AND a.Ref = b.Ref
	AND a.VersionId > 999
	GROUP BY a.VersionId, a.Ref, InnerPage
	ORDER BY a.VersionId, a.Ref, COUNT(*) DESC
	---生成Innerer_Count的数据
	DECLARE @ProvinceId AS INT, @ProvinceDomain AS VARCHAR(100),
			@CountNumber AS INT, @CountDate AS VARCHAR(8),
			@AllNum AS INT, @InnerPage AS INT,
			@Referer AS VARCHAR(100), @HowMany AS INT,
			@ProvinceIdOld INT, @RefererOld VARCHAR(100),
			@p INT


	DECLARE @allCount INT
	SELECT @allCount =count(1) FROM #T 
	PRINT '#t中有'+Ltrim(str(@allCount))+'条数据'

	DECLARE @JobPage INT, @CompanyPage  INT, @NewsPage  INT, @RecruitmentPage  INT, @CountyPage INT, @RegionSearch INT,
		@JobHelpPage INT, @JobMapPage  INT, @OtherPage INT, @partTimePage INT, @SchoolPage INT, @MajorPage INT, 
		@JobNamePage INT, @NewJob INT, @paDownLoad INT, @sSearch INT

	SELECT @JobPage = 0, @CompanyPage = 0,
		@NewsPage = 0, @RecruitmentPage = 0,
		@JobHelpPage = 0, @JobMapPage = 0,
		@OtherPage = 0, @partTimePage = 0,
		@HowMany = 0, @SchoolPage = 0, 
		@MajorPage = 0, @JobNamePage = 0,
		@CountyPage = 0, @RegionSearch = 0,
		@NewJob = 0, @paDownLoad = 0,
		@sSearch = 0

	DECLARE curSummary CURSOR FOR 
		SELECT ProvinceId, Referer, AllNum, InnerPage FROM #t ORDER BY Provinceid, Referer, InnerPage DESC
	FOR READ ONLY
	OPEN curSummary

	FETCH NEXT FROM curSummary INTO @ProvinceId, @Referer, @AllNum, @InnerPage
	SELECT @CountDate = CONVERT(VARCHAR(8), GETDATE() - 1, 112), 
		@RefererOld = @Referer, @ProvinceIdOld = @ProvinceId

	PRINT '开始循环游标'
	WHILE @@FETCH_STATUS = 0
	BEGIN
		PRINT '循环游标'+LTRIM(str(@ProvinceId))
		IF NOT(@Referer = @RefererOld AND @ProvinceId = @ProvinceIdOld)
		BEGIN
			PRINT '向Innerer_Count插入数据'
			INSERT INTO Innerer_Count0331(CountDate, Province_Id, howmany, Referer,JobPage, CompanyPage, NewsPage, RecruitmentPage,
					JobHelpPage, JobMapPage, OtherPage, partTimePage, SchoolPage, MajorPage, JobNamePage, NewJob, sSearch, CountyPage, paDownLoad, RegionSearch) 
			VALUES (@CountDate, @ProvinceIdOld, @HowMany, @RefererOld, @JobPage, @CompanyPage, @NewsPage, @RecruitmentPage,
					@JobHelpPage, @JobMapPage, @OtherPage, @partTimePage, @SchoolPage, @MajorPage, @JobNamePage, @NewJob, @sSearch, @CountyPage, @paDownLoad, @RegionSearch)

			SELECT @RefererOld = @Referer, @ProvinceIdOld = @ProvinceId,
				@JobPage = 0, @CompanyPage = 0 ,
				@NewsPage = 0, @RecruitmentPage = 0,
				@JobHelpPage = 0, @JobMapPage = 0,
				@OtherPage = 0, @partTimePage = 0,
				@HowMany = 0, @SchoolPage = 0, 
				@MajorPage = 0, @JobNamePage = 0,
				@CountyPage = 0, @RegionSearch = 0,
				@NewJob = 0, @paDownLoad = 0,
				@sSearch = 0
		END

		IF @InnerPage = 1 
			SET @JobPage = @AllNum 
		ELSE IF @InnerPage = 2 
			SET @CompanyPage = @AllNum 
		ELSE IF @InnerPage = 3 
			SET @NewsPage = @AllNum 
		ELSE IF @InnerPage = 4 
			SET @RecruitmentPage = @AllNum 
		ELSE IF @InnerPage = 5 
			SET @JobHelpPage = @AllNum 
		ELSE IF @InnerPage = 6
			SET @JobMapPage = @AllNum 
		ELSE IF @InnerPage = 7
			SET @partTimePage = @AllNum
		ELSE IF @InnerPage = 8
			SET @SchoolPage = @AllNum
		ELSE IF @InnerPage = 9
			SET @MajorPage = @AllNum
		ELSE IF @InnerPage = 15
			SET @JobNamePage = @AllNum
		ELSE IF @InnerPage = 16
			SET @NewJob = @AllNum
		ELSE IF @InnerPage = 17
			SET @sSearch = @AllNum
		ELSE IF @InnerPage = 20
			SET @CountyPage = @AllNum
		ELSE IF @InnerPage = 21
			SET @paDownLoad = @AllNum
		ELSE IF @InnerPage = 10
			SET @RegionSearch = @AllNum
		ELSE --IF @InnerPage = 100
			SET @OtherPage = @AllNum
 
		SET @HowMany = @HowMany + @AllNum
		FETCH NEXT FROM curSummary INTO @ProvinceId, @Referer, @AllNum, @InnerPage
	END
	print '循环游标结束'

	IF NOT @AllNum IS NULL
	BEGIN
		INSERT INTO Innerer_Count0331(CountDate, Province_Id, howmany,Referer,JobPage, CompanyPage, NewsPage, RecruitmentPage,
				JobHelpPage, JobMapPage, partTimePage, OtherPage, SchoolPage, MajorPage, JobNamePage, NewJob, sSearch, CountyPage, RegionSearch) 
		VALUES (@CountDate, @ProvinceIdOld, @HowMany, @RefererOld, @JobPage, @CompanyPage, @NewsPage, @RecruitmentPage,
				@JobHelpPage, @JobMapPage, @partTimePage, @OtherPage, @SchoolPage, @MajorPage, @JobNamePage, @NewJob, @sSearch, @CountyPage, @RegionSearch)
	END
	CLOSE curSummary
	DEALLOCATE curSummary

	DROP TABLE #Ref
	DROP TABLE #p
	DROP TABLE #R
	DROP TABLE #In
	DROP TABLE #t

	UPDATE Innerer_Count0331 SET VersionId = Province_Id WHERE CountDate = @CountDate
	UPDATE Innerer_Count0331 SET VersionId = RIGHT(Province_Id, LEN(Province_Id) - 1)
	WHERE CountDate = @CountDate
	AND LEN(Province_Id) IN(3, 5)
END

GO
/****** Object:  StoredProcedure [dbo].[ProcSourceAnalysis2New]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ProcSourceAnalysis2New]
AS
BEGIN
	--1职位页面 2公司页面 3新闻页面 4招聘会页面 5求职互助页面 6职位地图 
	--7兼职招聘 8校园招聘 9专业分类 10 /jinan_job/zhangqiu/  15职位地图jobmap/1802.html 
	--20县级新闻列表/zhangqiu/news/ 21个人文档下载 100其它
	CREATE TABLE #t(ProvinceId INT, Referer VARCHAR(200), AllNum INT, InnerPage INT)
	SELECT *, SPACE(200) Ref, SPACE(50) Domain INTO #In FROM Innerer		--WHERE LoginDate < '2014-10-09 02:42:00'
	UPDATE #In SET Ref = LEFT(Referer, CHARINDEX('/', Referer, 8)) 
	DELETE #In WHERE Ref = ''
	UPDATE a SET a.Domain = b.ProvinceDomain FROM #In a, dcProvince b WHERE b.Id = a.Province_Id
	UPDATE a SET a.Domain = b.ProvinceDomain FROM #In a, dcProvince b WHERE b.Id + 100 = a.Province_Id
	UPDATE a SET a.Domain = b.ProvinceDomain FROM #In a, dcProvince b WHERE b.Id + 200 = a.Province_Id
	UPDATE #In SET Domain = '51rc.com' WHERE Domain IS NULL
	DELETE #In WHERE CHARINDEX(Domain, Referer, 0) BETWEEN 1 AND 10

	CREATE TABLE #p(ID INT, Domain VARCHAR(100))
	INSERT #p SELECT ID , ProvinceDomain FROM dcProvince
	INSERT #p SELECT 100 + ID , ProvinceDomain FROM dcProvince
	INSERT #p SELECT 200 + ID , ProvinceDomain FROM dcProvince
	INSERT #p SELECT 0, '51rc.com'

	CREATE TABLE #Ref(VersionId INT, Ref VARCHAR(500), Cnt INT)
	INSERT INTO #Ref
	SELECT Province_Id, Ref, COUNT(*) Cnt
	FROM #In WITH(NOLOCK)
	GROUP BY Province_Id, Ref
	ORDER BY Province_Id, COUNT(*) DESC, Ref

	INSERT INTO #Ref
	SELECT VersionId, Ref , COUNT(*) Cnt
	FROM #In
	WHERE LEN(VersionId) > 3
	GROUP BY VersionId, Ref
	ORDER BY VersionId, COUNT(*) DESC, Ref

	SELECT *, ROW_NUMBER() OVER(PARTITION BY VersionId ORDER BY Cnt DESC) RowNo INTO #r FROM #ref 
	DELETE #r WHERE RowNo > 200

	INSERT INTO #t(ProvinceId, Referer, AllNum, InnerPage)
	SELECT Province_Id, a.Ref, COUNT(1) AllNum, InnerPage
	FROM #In a WITH(NOLOCK), #r b
	WHERE a.Province_Id = b.VersionId
	AND a.Ref = b.Ref
	GROUP BY Province_Id, a.Ref, InnerPage
	ORDER BY Province_Id, a.Ref, COUNT(*) DESC

	INSERT INTO #t(ProvinceId, Referer, AllNum, InnerPage)
	SELECT a.VersionId, a.Ref, COUNT(1) AllNum, InnerPage
	FROM #In a WITH(NOLOCK), #r b
	WHERE a.VersionId = b.VersionId
	AND a.Ref = b.Ref
	AND a.VersionId > 999
	GROUP BY a.VersionId, a.Ref, InnerPage
	ORDER BY a.VersionId, a.Ref, COUNT(*) DESC

	DECLARE @CountDate AS VARCHAR(8)
	SET @CountDate = CONVERT(VARCHAR(8), GETDATE() - 1, 112)
	SELECT 0 ID, @CountDate CountDate, ProvinceId, Referer, SUM(AllNum) HowMany INTO #1 FROM #t GROUP BY ProvinceId, Referer
	INSERT INTO Innerer_CountNew(CountDate, Province_Id, HowMany, Referer) SELECT CountDate, ProvinceId, HowMany, Referer FROM #1
	UPDATE a SET A.Id = b.Id FROM #1 a, Innerer_CountNew b WHERE a.CountDate = b.CountDate AND a.ProvinceId = b.Province_Id AND a.Referer = b.Referer
	INSERT INTO Innerer_Count_Detail SELECT  a.ID, b.InnerPage, b.AllNum FROM #1 a, #t b WHERE a.ProvinceId= b.ProvinceId AND a.Referer = b.Referer ORDER BY A.Id, b.InnerPage

	UPDATE Innerer_CountNew SET VersionId = Province_Id WHERE CountDate = @CountDate
	UPDATE Innerer_CountNew SET VersionId = RIGHT(Province_Id, LEN(Province_Id) - 1)
	WHERE CountDate = @CountDate
	AND LEN(Province_Id) IN(3, 5)
END

GO
/****** Object:  StoredProcedure [dbo].[ProcSourceAnalysis3]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ProcSourceAnalysis3]
AS
BEGIN
	DECLARE @Countdate VARCHAR(8), @Referer_AllNum INT,
		@Referer_Ref VARCHAR(200), @ProvinceId INT,
		@ProvinceDomain VARCHAR(50), @CountNumber AS INT,
		@p INT

	SET @CountDate = CONVERT(VARCHAR(8), GETDATE() - 1, 112)

	DECLARE @t AS TABLE(
		ID INT,
		Domain VARCHAR(100),
		CountNumber INT
	) 	
	INSERT INTO @t SELECT 0, '51rc.com', 100
	INSERT INTO @t SELECT Id, Domain, 200 FROM Province WITH(NOLOCK) ORDER BY Id

	DECLARE curSite CURSOR FOR 
		SELECT Id, Domain, CountNumber FROM @t ORDER BY Id
	FOR READ ONLY
	OPEN curSite

	FETCH NEXT FROM curSite INTO @ProvinceId, @ProvinceDomain, @CountNumber
	WHILE @@FETCH_STATUS = 0
	BEGIN
		INSERT INTO Referer_Count(CountDate, Province_id, howmany, Referer) 
		SELECT TOP (@CountNumber) @CountDate, @ProvinceId, COUNT(1), LEFT(Referer, CHARINDEX('/', Referer, 8)) Ref 
		FROM Referer WITH(NOLOCK)
		WHERE CHARINDEX('/', Referer, 8) > 0
		AND Province_id = @ProvinceId
		AND CHARINDEX(@ProvinceDomain, Referer, 0) NOT BETWEEN 1 AND 10
		GROUP BY LEFT(Referer, CHARINDEX('/', Referer, 8))
		ORDER BY COUNT(1) DESC
		
		IF @ProvinceId > 0
		BEGIN
			SET @p = '1' + LTRIM(STR(@ProvinceId))
			INSERT INTO Referer_Count(CountDate, Province_id, howmany, Referer) 
			SELECT TOP (@CountNumber) @CountDate, @p, COUNT(1), LEFT(Referer, CHARINDEX('/', Referer, 8)) Ref 
			FROM Referer WITH(NOLOCK)
			WHERE CHARINDEX('/', Referer, 8) > 0
			AND Province_id = @p
			AND CHARINDEX(@ProvinceDomain, Referer, 0) NOT BETWEEN 1 AND 10
			GROUP BY LEFT(Referer, CHARINDEX('/', Referer, 8))
			ORDER BY COUNT(1) DESC

			SET @p = '2' + LTRIM(STR(@ProvinceId))
			INSERT INTO Referer_Count(CountDate, Province_id, howmany, Referer) 
			SELECT TOP (@CountNumber) @CountDate, @p, COUNT(1), LEFT(Referer, CHARINDEX('/', Referer, 8)) Ref 
			FROM Referer WITH(NOLOCK)
			WHERE CHARINDEX('/', Referer, 8) > 0
			AND Province_id = @p
			AND CHARINDEX(@ProvinceDomain, Referer, 0) NOT BETWEEN 1 AND 10
			GROUP BY LEFT(Referer, CHARINDEX('/', Referer, 8))
			ORDER BY COUNT(1) DESC
		END

		FETCH NEXT FROM curSite INTO @ProvinceId, @ProvinceDomain, @CountNumber
	END
	CLOSE curSite
	DEALLOCATE curSite
END










GO
/****** Object:  StoredProcedure [dbo].[ProcSourceAnalysis4]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ProcSourceAnalysis4]
AS
BEGIN
	DECLARE @Countdate VARCHAR(8), @Province_Id INT,
		@Referer VARCHAR(200), @Id INT,
		@VersionId INT

	SET @CountDate = CONVERT(VARCHAR(8), GETDATE() - 1, 112)

	DECLARE curSeconderer CURSOR FOR 
		SELECT Id, Province_Id, Referer, VersionId FROM Seconderer_Count WITH(NOLOCK) WHERE Countdate = @Countdate
	FOR READ ONLY

	OPEN curSeconderer
	FETCH NEXT FROM curSeconderer INTO @Id, @Province_Id, @Referer, @VersionId

	WHILE @@FETCH_STATUS = 0
	BEGIN
		INSERT INTO Seconderer_Count_keywords(Referer_Count_Id, keywords, howmany) 
		SELECT TOP 500 @Id, Keywords, COUNT(1) cnt 
		FROM Seconderer WITH(NOLOCK) 
		WHERE CHARINDEX(@Referer, Referer, 0) > 0 
		AND VersionId = @VersionId 
		AND LEN(keywords)>0 
		GROUP BY Keywords 
		ORDER BY cnt DESC

		FETCH NEXT FROM curSeconderer INTO @Id, @Province_Id, @Referer, @VersionId
	END
	CLOSE curSeconderer
	DEAllOCATE curSeconderer
END














GO
/****** Object:  StoredProcedure [dbo].[ProcSourceAnalysis5]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--修改Harry Innerer_Count改为Innerer_CountNew
--修改时间 2015/3/30
CREATE PROCEDURE [dbo].[ProcSourceAnalysis5]
AS
BEGIN
	DECLARE @Countdate AS VARCHAR(8), @Referer_Count_Id AS INT
	SET @CountDate = CONVERT(VARCHAR(8), GETDATE() - 1, 112)

	--从Innerer、Innerer_Count取数据插入#t表中
	SELECT TOP 0 * INTO #T FROM Innerer_Count_Keywords

	INSERT INTO #t(Referer_Count_id, Keywords, Howmany)
	SELECT b.Id, a.Keywords, COUNT(1) cnt
	FROM Innerer a WITH(NOLOCK), Innerer_CountNew b WITH(NOLOCK)
	WHERE a.Referer LIKE b.Referer + '%'
	AND a.Province_id = b.Province_id 
	AND LEN(a.Keywords) > 0
	AND b.CountDate = @CountDate
	GROUP BY b.Id, a.Keywords 
	ORDER BY Cnt DESC

	DECLARE @T TABLE (ID INT)
	--将数量超过500的Referer_Count_Id取出放入临时表
	INSERT INTO @T
	SELECT Referer_Count_Id
	FROM #t WITH(NOLOCK)
	GROUP BY Referer_Count_Id
	HAVING COUNT(*) > 500
	--将超过500的数量的去掉
	DECLARE curMoreThan500 CURSOR FOR 
		SELECT Id FROM @t
	FOR READ ONLY

	OPEN curMoreThan500
	FETCH NEXT FROM curMoreThan500 INTO @Referer_Count_Id

	WHILE @@FETCH_STATUS = 0
	BEGIN
		DELETE FROM #t
		WHERE Referer_Count_id = @Referer_Count_Id
		AND KeyWords NOT IN (
			SELECT TOP 500 KeyWords 
			FROM #t WITH(NOLOCK)
			WHERE Referer_Count_id = @Referer_Count_Id
			ORDER BY HowMany DESC
			)

		FETCH NEXT FROM curMoreThan500 INTO @Referer_Count_Id
	END
	CLOSE curMoreThan500
	DEALLOCATE curMoreThan500

	INSERT INTO Innerer_Count_Keywords SELECT * FROM #t
END


GO
/****** Object:  StoredProcedure [dbo].[ProcSourceAnalysis6]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ProcSourceAnalysis6]
AS
BEGIN
	DECLARE @Countdate VARCHAR(8), @Referer_Count_Id INT

	SET @CountDate = CONVERT(VARCHAR(8), GETDATE() - 1, 112)
	SELECT TOP 0 * INTO #t FROM Referer_Count_keywords

	INSERT INTO #t(Referer_Count_id, keywords, howmany) 
	SELECT b.ID, a.Keywords, COUNT(1) cnt
	FROM Referer a WITH(NOLOCK), Referer_Count b WITH(NOLOCK) 
	WHERE (a.Referer LIKE b.Referer + '%' OR a.Referer LIKE 'http://' + b.Referer + '%')
	AND a.Province_id = b.Province_id
	AND LEN(a.Keywords) > 0
	AND b.CountDate = @CountDate
	GROUP BY b.Id, a.Keywords 
	ORDER BY Cnt DESC

	DECLARE curCount CURSOR FOR 
		SELECT Referer_Count_Id
		FROM #t WITH(NOLOCK)
		GROUP BY Referer_Count_Id
		HAVING COUNT(*) > 500
	FOR READ ONLY

	OPEN curCount
	FETCH NEXT FROM curCount INTO @Referer_Count_Id

	WHILE @@FETCH_STATUS = 0
	BEGIN
		DELETE FROM #t
		WHERE Referer_Count_id = @Referer_Count_id
		AND KeyWords NOT IN (
			SELECT TOP 500 KeyWords FROM #t WITH(NOLOCK)
			WHERE Referer_Count_id = @Referer_Count_id
			ORDER BY HowMany DESC)

		FETCH NEXT FROM curCount INTO @Referer_Count_Id
	END

	CLOSE curCount
	DEAllOCATE curCount

	INSERT INTO Referer_Count_keywords(Referer_Count_id, keywords, howmany) 
	SELECT * FROM #t
END














GO
/****** Object:  StoredProcedure [dbo].[ProcSourceAnalysis7]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ProcSourceAnalysis7]
AS
BEGIN
	DECLARE @CountMonth VARCHAR(6)

	SET @CountMonth = CONVERT(VARCHAR(6), GETDATE(), 112)

	SELECT Id, Link, Versionid, 10000 Cnt1, 10000 Cnt2, Vision, PowerAll, Power INTO #t FROM Link WITH(NOLOCK) WHERE Valid = 1
	UPDATE #t SET Link = LTRIM(RTRIM(LOWER(Link)))
	UPDATE #t SET Link = LEFT(Link, LEN(Link) - 1) WHERE RIGHT(Link, 1) = '/'
	UPDATE #t SET Cnt1 = (SELECT COUNT(1) FROM Referer WITH(NOLOCK) 
		WHERE Referer LIKE #t.Link + '%'
		AND Referer.Versionid = #t.Versionid)
	UPDATE #t SET Cnt2 = (SELECT COUNT(1) FROM Seconderer WITH(NOLOCK) 
		WHERE Referer LIKE #t.Link + '%'
		AND Seconderer.Versionid = #t.Versionid)
	UPDATE #t SET Vision=0, PowerAll = PowerAll + Cnt1 + Cnt2, Power = Cnt1 + Cnt2 WHERE Cnt1 + Cnt2 > 0

	UPDATE a
	SET a.PowerAll = b.PowerAll, a.Power = b.Power, a.Vision = b.Vision
	FROM Link a WITH(NOLOCK), #t b WITH(NOLOCK)
	WHERE a.ID = b.Id
	AND b.Power > 0

	INSERT INTO Link_Count(LinkId, YearMonth, Power)
	SELECT ID, @CountMonth, 0 
	FROM Link WITH(NOLOCK) 
	WHERE ID NOT IN(
		SELECT LinkId FROM Link_count WITH(NOLOCK)
		WHERE YearMonth = @CountMonth
		)
	AND Power > 0

	UPDATE a
	SET a.Power = a.Power + b.Power
	FROM Link_Count a, #t b
	WHERE a.LinkId = b.Id
	AND a.YearMonth = @CountMonth
	AND b.Power > 0
	
END














GO
/****** Object:  StoredProcedure [dbo].[ProcSourceAnalysis8]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ProcSourceAnalysis8]
AS
BEGIN
	DECLARE @CountMonth AS VARCHAR(8)
	SELECT @CountMonth = CONVERT(VARCHAR(6), GETDATE(), 112)

	SELECT Id, OutUrl, 10000 Cnt1, 10000 Cnt2, Mth_ClickNum, Yst_ClickNum
	INTO #t
	FROM OutLink WITH(NOLOCK) 
	WHERE AddDate > GETDATE() - 30

	UPDATE #t SET OutUrl = LTRIM(RTRIM(LOWER(OutUrl)))
	UPDATE #t SET OutUrl = LEFT(OutUrl, LEN(OutUrl) - 1) WHERE RIGHT(OutUrl, 1) = '/'
	UPDATE #t SET Cnt1 = (SELECT COUNT(1) FROM Referer WITH(NOLOCK) WHERE Referer.Referer = #t.OutUrl)
	UPDATE #t SET Cnt2 = (SELECT COUNT(1) FROM Seconderer WITH(NOLOCK) WHERE Seconderer.Referer = #t.OutUrl)
	UPDATE #t SET Mth_ClickNum = Mth_ClickNum + Cnt1 + Cnt2, Yst_ClickNum = Yst_ClickNum + Cnt1 + Cnt2

	UPDATE a
	SET a.Yst_ClickNum = b.Yst_ClickNum, a.Mth_ClickNum = b.Mth_ClickNum
	FROM OutLink a WITH(NOLOCK), #t b WITH(NOLOCK)
	WHERE a.Id = b.Id

	INSERT INTO OutLink_Count(OutLinkid, YearMonth, Power)
	SELECT ID, @CountMonth, Cnt1 + Cnt2
	FROM #t
	WHERE Cnt1 + Cnt2 > 0
	AND ID NOT IN(
		SELECT OutLinkid FROM OutLink_Count WITH(NOLOCK)
		WHERE YearMonth = @CountMonth
		)

	UPDATE a
	SET a.Power = a.Power + b.Cnt1 + b.Cnt2
	FROM OutLink_Count a, #t b
	WHERE b.Yst_ClickNum > 0
	AND a.OutLinkid = b.Id 
	AND a.YearMonth = @CountMonth		
END














GO
/****** Object:  StoredProcedure [dbo].[ProcSourceAnalysis9]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--修改Harry Innerer_Count改为Innerer_CountNew
--修改时间 2015/3/30
CREATE PROCEDURE [dbo].[ProcSourceAnalysis9]
AS
BEGIN
	DELETE Referer_Count WHERE CountDate < CONVERT(VARCHAR(8), GETDATE() - 400, 112)
	DELETE Innerer_CountNew WHERE CountDate < CONVERT(VARCHAR(8), GETDATE() - 400, 112)
	DELETE Counter WHERE CountDate < CONVERT(VARCHAR(8), GETDATE() - 400, 112)
END
GO
/****** Object:  StoredProcedure [dbo].[procSpFamousCompanyByIdSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[procSpFamousCompanyByIdSelect] 
(
	@ID VARCHAR(10)
)
AS
BEGIN
	SELECT a.*,b.Description RegionName,c.Description Industry 
	FROM spFamousCompany a,dcRegion b with(nolock) ,dcIndustry c with(nolock) 
	WHERE a.ID = @ID
	AND a.dcIndustryID = c.ID
	AND a.dcRegionID = b.ID
END








GO
/****** Object:  StoredProcedure [dbo].[procSpFamousCompanySelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--根据站点、行业、关键字 查询名企信息 nick20140222
CREATE PROCEDURE [dbo].[procSpFamousCompanySelect] 
(
	@dcSubsiteId SMALLINT, 
	@dcIndustryID INT, 
	@KeyWord NVARCHAR(50)
)
AS
BEGIN
	IF(ISNULL(@KeyWord, '') > '' AND @dcIndustryID <> 0)
	BEGIN
		SELECT TOP 480 ID, CompanyName AS Title
		FROM spFamousCompany 
		WHERE (CompanyName LIKE '%' + @KeyWord + '%' OR Description LIKE '%' + @KeyWord + '%')
		AND dcIndustryID = @dcIndustryID 
		AND dcRegionID LIKE LTRIM(STR(@dcSubsiteId)) + '%'
		ORDER BY ID DESC
	END
	ELSE IF (@dcIndustryID <> 0 )
	BEGIN
		SELECT TOP 480 ID, CompanyName AS Title
		FROM spFamousCompany 
		WHERE dcIndustryID = @dcIndustryID 
		AND dcRegionID LIKE LTRIM(STR(@dcSubsiteId)) + '%'
		ORDER BY ID DESC
	END
	ELSE IF (ISNULL(@KeyWord, '') > '')
	BEGIN
		SELECT TOP 480 ID, CompanyName AS Title
		FROM spFamousCompany 
		WHERE (CompanyName LIKE '%' + @KeyWord + '%' OR Description LIKE '%' + @KeyWord + '%')
		AND dcRegionID LIKE LTRIM(STR(@dcSubsiteId)) + '%'
		ORDER BY ID DESC
	END
	ELSE 
	BEGIN
		SELECT TOP 480 ID, CompanyName AS Title
		FROM spFamousCompany 
		WHERE dcRegionID LIKE LTRIM(STR(@dcSubsiteId)) + '%'
		ORDER BY ID DESC
	END
END










GO
/****** Object:  StoredProcedure [dbo].[procspFamousCompanyUpdate]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.5
--创建人：NICK
--说明：记录知名企业点击数
--#####################################################
CREATE PROCEDURE [dbo].[procspFamousCompanyUpdate]
(
	@NewsID INT,
	@IsWhite INT
)
AS
BEGIN
	DECLARE @SQL VARCHAR(MAX)
	SET @SQL = 'UPDATE MainDB..spFamousCompany SET AllClickNumber = AllClickNumber + 1 '
	IF @IsWhite = 0
	BEGIN
		SET @SQL = @SQL +', ClickNumber = ClickNumber + 1 '
	END
	SET @SQL = @SQL +' WHERE ID = ' +CONVERT(VARCHAR(20),@NewsID)
	EXEC(@SQL)
	RETURN 1
END


GO
/****** Object:  StoredProcedure [dbo].[ProcSpreadKeywordAssignByAutoSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ProcSpreadKeywordAssignByAutoSelect]
(
	@ManagerUserId INT 
)
AS
BEGIN
	DECLARE @k VARCHAR(20), @TargetUrl VARCHAR(50), @IsValidTime INT, @SucceedCount INT
	SELECT @k = Keyword, @TargetUrl = SubSiteUrl
	FROM MarketDb..SpreadKeywordAssign WITH(NOLOCK)
	WHERE DEPTID IN(SELECT DeptId FROM ManagerUser WITH(NOLOCK) WHERE Id = @ManagerUserId)
	AND GETDATE() BETWEEN AddDate AND EndDate
	
	IF DATEPART(HOUR, GETDATE()) BETWEEN 7 AND 17
		SET @IsValidTime = 0
	ELSE
		SET @IsValidTime = 1

	IF EXISTS(SELECT 'x' FROM Oadb..WorkDate WHERE WorkDate = CONVERT(VARCHAR(8), GETDATE(), 112) AND WorkType <> 1)
		SET @IsValidTime = 1

	IF LEN(ISNULL(@k, '')) < 2
		SET @IsValidTime = 0
	--SET @IsValidTime = 1
	SELECT @SucceedCount = COUNT(*)
	FROM MarketDb..SpreadKeywordRefererLog WITH(NOLOCK)
	WHERE AddDate > CONVERT(VARCHAR(10), GETDATE(), 120) 
	AND IsValid = 1 
	AND ManagerUserId = @ManagerUserId 

	SELECT @IsValidTime IsValidTime, @k KeyWord, @TargetUrl TargetUrl,
		10 ActiveTime,			--运行时间
		20 SleepTime,			--间隔时间
		5 MinClickNumber,		--最小点击数
		@SucceedCount SucceedCount
END


GO
/****** Object:  StoredProcedure [dbo].[ProcSpreadKeywordRefererLogByBaiDuSave]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--sean 2014-4-3 baidu 点击自动统计，工作日19:00~7:00算业余时间 非工作日0：00～24：00， 点击到结束 超过10分钟算有效
CREATE PROCEDURE [dbo].[ProcSpreadKeywordRefererLogByBaiDuSave]
AS
RETURN
BEGIN
	SET NOCOUNT ON
	/*	Add Limit Condition*/
	--IF EXISTS(SELECT 'x' FROM Oadb..WorkDate WHERE WorkDate = CONVERT(VARCHAR(8), GETDATE(), 112) AND WorkType = 1)
	--	IF DATEPART(HOUR, GETDATE()) BETWEEN 7 AND 17	-- AND 1=2
	--		RETURN
	
	--Delete the login user in 10 Minutes 
	DELETE ManagerLogSnap WHERE LoginDate < DATEADD(MINUTE, -10, GETDATE())
	DELETE SynUeoLog WHERE IP IN(SELECT IP FROM Ip_White)
 
	IF(SELECT COUNT(*) FROM ManagerLogSnap) > 0		--have login user
	BEGIN
		--记录Refer的ip
		SELECT *
		INTO #R
		FROM Referer WITH(NOLOCK) 
		WHERE LoginDate > DATEADD(MINUTE, -10, GETDATE()) 
		AND Ip IN(SELECT IP FROM ManagerLogSnap) 
		AND Referer LIKE '%.baidu.%'
 
		--记录seconderer的ip
		INSERT INTO #R
		SELECT *
		FROM Seconderer WITH(NOLOCK) 
		WHERE LoginDate > DATEADD(MINUTE, -10, GETDATE()) 
		AND Ip IN(SELECT IP FROM ManagerLogSnap) 
		AND Referer LIKE '%.baidu.%'

		--登录和referer匹配
		DECLARE @t AS TABLE
		(
			ManagerUserId INT,
			VersionId INT,
			IP VARCHAR(15),
			Referer VARCHAR(200),
			RefererDate DATETIME,
			SessionId VARCHAR(30),
			Engine TINYINT,
			IsValid BIT
		)

		INSERT INTO @t
		SELECT b.ManagerId, a.VersionId, a.Ip, a.Referer, a.LoginDate RefererDate, a.SessionId, 0, 0
		FROM #r a, ManagerLogSnap b
		WHERE a.Ip = b.Ip
 
		UPDATE @t SET Engine = 1 WHERE Referer LIKE '%.baidu.%'
 
		--删除先点击后登录的
		DELETE a
		FROM @t a, Marketdb..SpreadKeywordRefererLog b
		WHERE a.Referer = b.Referer 
		AND a.Ip = b.Ip 
		AND a.SessionId = b.SessionId
		AND a.Engine = b.Engine
		AND b.RefererDate > DATEADD(MINUTE, -30, GETDATE())
 
		--检查关键词
		UPDATE a SET IsValid = 1
		FROM @t a, Marketdb..SpreadKeywordAssign b, ManagerUser c
		WHERE a.ManagerUserId = c.Id
		AND b.DeptId = c.DeptId
		AND b.EndDate > GETDATE()
 
		--删除不是关键词的
		DELETE @t WHERE IsValid = 0
		DELETE @t WHERE LEN(VersionId) IN(3, 5)
		UPDATE @t SET VersionId = LEFT(VersionId, 2) WHERE LEN(VersionId) = 6
 
		SELECT SessionId, Min(addDate) AddDate
		INTO #l1
		FROM SynUeoLog b
		WHERE SessionId IN(SELECT SessionId FROM @t)
		GROUP BY SessionId

		DELETE a
		FROM @t a
		WHERE EXISTS(SELECT 'x' FROM #l1 b
			WHERE a.SessionId = b.SessionId
			AND b.AddDate < DATEADD(MINUTE, -10, a.RefererDate))

		--插入refererlog
		INSERT INTO Marketdb..SpreadKeywordRefererLog(SessionId, dcSubSiteId, ManagerUserId, Engine, Keyword, Referer, RefererDate, Ip, LoginType, ViewPageNumber, AddDate)
		SELECT SessionId, VersionId, ManagerUserId, Engine, '', Referer, RefererDate, Ip, 1, 0, GETDATE()
		FROM @t
		WHERE LEN(VersionId) <= 4
	END

	--从ueolog中搜索sessionid的开始、结束时间
	SELECT SessionId, DATEADD(MINUTE, -1, AddDate) AddDate, Engine, 0 PageNumber, 0 IsValid, 0 MaxId , GETDATE() - 1 EndDate, SPACE(500) Url
	INTO #u
	FROM Marketdb..SpreadKeywordRefererLog
	WHERE AddDate > DATEADD(MINUTE, -120, GETDATE())
	UPDATE #u SET IsValid = 1 WHERE SessionId IN(SELECT SessionId FROM SynUeoLog WHERE AddDate > DATEADD(MINUTE, -2, GETDATE()))
	DELETE #u WHERE IsValid = 0

	IF (SELECT COUNT(*) FROM #u) > 0
	BEGIN
		SELECT ID, SessionId, AddDate INTO #l3 FROM SynUeoLog b WHERE SessionId IN(SELECT SessionId FROM #u)
		UPDATE #u SET PageNumber = (SELECT COUNT(*) FROM #l3 b WHERE #u.SessionId = b.SessionId AND b.AddDate > #u.AddDate)

		SELECT SessionId, MAX(Id) ID 
		INTO #l2
		FROM #l3 WITH(NOLOCK)
		GROUP BY SessionId

		UPDATE a SET a.MaxId = b.Id FROM #u a, #l2 b WHERE a.SessionId = b.SessionId

		UPDATE a
		SET a.EndDate = b.AddDate,
			a.Url = b.Url
		FROM #u a, SynUeoLog b
		WHERE a.MaxId = b.Id
	END
--	SELECT * FROM #u
	UPDATE a
	SET a.EndDate = b.EndDate,
		a.EndUrl = b.Url,
		ViewPageNumber = b.PageNumber
	FROM Marketdb..SpreadKeywordRefererLog a, #u b
	WHERE a.AddDate > DATEADD(MINUTE, -120, GETDATE())
	AND a.Engine = b.Engine
	AND a.SessionId = b.SessionId

	--记录pageminute
	UPDATE Marketdb..SpreadKeywordRefererLog 
	SET PageMinute = DATEDIFF(MINUTE, RefererDate, EndDate)
	WHERE EndDate > DATEADD(MINUTE, -5, GETDATE())	
	AND IsValid = 0

	--10分钟有效
	UPDATE Marketdb..SpreadKeywordRefererLog 
	SET IsValid = 1
	WHERE EndDate > DATEADD(MINUTE, -5, GETDATE()) 
	AND IsValid = 0 
	AND DATEDIFF(MINUTE, RefererDate, EndDate) >= 10	
END

GO
/****** Object:  StoredProcedure [dbo].[ProcSpreadKeywordRefererLogByFixUpdate]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--sean 2015-10-28 Used by baidu click.
CREATE PROCEDURE [dbo].[ProcSpreadKeywordRefererLogByFixUpdate]
(
	@ManagerId INt,
	@Ip VARCHAR(15),
	@SessionId VARCHAR(30)
)
AS
BEGIN
	DECLARE @LoginDate DATETIME
	SELECT TOP 1 @LoginDate = LoginDate FROM Referer WITH(NOLOCK) WHERE Ip = @Ip ORDER BY LoginDate DESC
	IF @LoginDate IS NULL
	BEGIN
		UPDATE Referer SET Ip = @ip WHERE SessionId = @SessionId AND LoginDate > DATEADD(MI, -3, GETDATE())
		SELECT TOP 1 @LoginDate = LoginDate FROM Referer WITH(NOLOCK) WHERE Ip = @Ip ORDER BY LoginDate DESC
	END
	IF @LoginDate IS NULL
		RETURN
	
	UPDATE Referer 
	SET SessionId = @SessionId
	WHERE Ip = @Ip
	AND LoginDate = @LoginDate

	UPDATE MarketDb..SpreadKeywordRefererLog 
	SET SessionId = @SessionId, Ip = @Ip
	WHERE ManagerUserId = @ManagerId
	--AND Ip = @Ip
	AND AddDate > DATEADD(MINUTE, -10, GETDATE())
	AND IsValid = 0

	UPDATE MainDb..ManagerLogSnap SET Ip = @Ip WHERE ManagerId = @ManagerId

	IF NOT EXISTS(SELECT 'x' FROM SynUeoLog WITH(NOLOCK) WHERE Ip = @Ip AND AddDate > DATEADD(MINUTE, -3, GETDATE()))
	BEGIN
		INSERT SynUeoLog(SubsiteId, SessionId, paMainId, caMainId, PageId, AddDate, Ip, Url, IsSpider)
		SELECT 32, @SessionId, 0, 0, 0, GETDATE(), @Ip, 'http://www.qlrc.com/', 0
	END
END

GO
/****** Object:  StoredProcedure [dbo].[ProcSpreadKeywordRefererLogByMonthPaySelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ProcSpreadKeywordRefererLogByMonthPaySelect]
(
	@Month VARCHAR(6)
)
AS
BEGIN
	DECLARE @Sd DATETIME, @Ed DATETIME
	BEGIN TRY
		SET @sd = DATEADD(MONTH, -1, CONVERT(DATETIME, @Month + '01')) + 25
		SET @Ed = DATEADD(MONTH, 1, @Sd)
	END TRY
	BEGIN CATCH
		SET @Month = CONVERT(VARCHAR(6), GETDATE(), 112)
		SET @sd = DATEADD(MONTH, -1, CONVERT(DATETIME, @Month + '01')) + 25
		SET @Ed = DATEADD(MONTH, 1, @Sd)
	END CATCH
		
	DECLARE @t AS TABLE(
		Type INT,
		DeptSuperior INT,
		DeptID INT,
		DeptName NVARCHAR(20),
		ManagerUserId INT,
		ManagerUserName  NVARCHAR(10),
		ValidNumber INT,
		PayNumber INT)
	
	INSERT @t(Type, ManagerUserId, ValidNumber, PayNumber)
	SELECT 2, ManagerUserID, 
		SUM(CONVERT(INT, IsValid)) ValidNumber, 
		SUM(CONVERT(INT, IsMore2Valid)) PayNumber
	FROM MarketDb..SpreadKeywordRefererLog
	WHERE AddDate BETWEEN @Sd AND @ED
	GROUP BY ManagerUserID

	UPDATE a
	SET a.ManagerUserName = b.Name,
		a.DeptID = b.DeptId
	FROM @t a, ManagerUser b
	WHERE b.id = a.ManagerUserId

	INSERT @t(Type, DeptId, ValidNumber, PayNumber)
	SELECT 1, DeptId, SUM(ValidNumber), SUM(PayNumber) FROM @t GROUP BY DeptId

	UPDATE a
	SET a.DeptName = b.DeptName,
		a.DeptSuperior = b.Superior
	FROM @t a, Dept b
	WHERE b.id = a.DeptId
	UPDATE @t SET DeptSuperior = DeptId WHERE DeptSuperior = 0
	SELECT Type, DeptName, LTRIM(STR(ManagerUserId)) + ' ' + ManagerUserName ManagerUserName, ValidNumber, PayNumber FROM @t ORDER BY Type, DeptSuperior, DeptId, ManagerUserId
END










GO
/****** Object:  StoredProcedure [dbo].[ProcSpreadKeywordRefererLogByWtgSave]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--sean 2014-4-3 baidu 点击自动统计，工作日19:00~7:00算业余时间 非工作日0：00～24：00， 点击到结束 超过10分钟算有效
CREATE PROCEDURE [dbo].[ProcSpreadKeywordRefererLogByWtgSave]
AS
return
BEGIN
	SET NOCOUNT ON
	/*	Add Limit Condition*/
	IF EXISTS(SELECT 'x' FROM Oadb..WorkDate WHERE WorkDate = CONVERT(VARCHAR(8), GETDATE(), 112) AND WorkType = 1)
		IF DATEPART(HOUR, GETDATE()) BETWEEN 7 AND 17	-- AND 1=2
			RETURN
	
	--Delete the login user in 10 Minutes 
	DELETE ManagerLogSnap WHERE LoginDate < DATEADD(MINUTE, -10, GETDATE())
	DELETE WuTongGuoDb..SynUeoLog WHERE IP IN(SELECT IP FROM Ip_White)
 
	IF(SELECT COUNT(*) FROM ManagerLogSnap) > 0		--have login user
	BEGIN
		--记录Refer的ip
		SELECT *
		INTO #R
		FROM WuTongGuoDb..Referer WITH(NOLOCK) 
		WHERE LoginDate > DATEADD(MINUTE, -10, GETDATE()) 
		AND Ip IN(SELECT IP FROM ManagerLogSnap) 
		AND ((Keywords > '' AND (Referer LIKE '%.haosou.%' OR Referer LIKE '%.sogou.%'))
			OR Referer LIKE '%.baidu.%')

		--记录seconderer的ip
		INSERT INTO #R
		SELECT *
		FROM WuTongGuoDb..Seconderer WITH(NOLOCK) 
		WHERE LoginDate > DATEADD(MINUTE, -10, GETDATE()) 
		AND Ip IN(SELECT IP FROM ManagerLogSnap) 
		AND ((Keywords > '' AND (Referer LIKE '%.haosou.%' OR Referer LIKE '%.sogou.%'))
			OR Referer LIKE '%.baidu.%')
 
		--登录和referer匹配
		DECLARE @t AS TABLE
		(
			ManagerUserId INT,
			VersionId INT,
			IP VARCHAR(15),
			Keywords NVARCHAR(50),
			Referer VARCHAR(200),
			RefererDate DATETIME,
			SessionId VARCHAR(30),
			Engine TINYINT,
			IsValid BIT
		)

		INSERT INTO @t
		SELECT b.ManagerId, a.VersionId, a.Ip, LTRIM(RTRIM(a.Keywords)), a.Referer, a.LoginDate RefererDate, a.SessionId, 0, 0
		FROM #r a, ManagerLogSnap b
		WHERE a.Ip = b.Ip
 
		UPDATE @t SET Engine = 2 WHERE Referer LIKE '%.haosou.%'
		UPDATE @t SET Engine = 3 WHERE Referer LIKE '%.sogou.%'
		UPDATE @t SET Engine = 1 WHERE Referer LIKE '%.baidu.%'

		--删除先点击后登录的
		DELETE a
		FROM @t a, Marketdb..SpreadKeywordRefererLog b
		WHERE a.Referer = b.Referer 
		AND a.Ip = b.Ip 
		AND a.SessionId = b.SessionId
		AND a.Engine = b.Engine
		AND b.RefererDate > DATEADD(MINUTE, -30, GETDATE())
 
		--检查关键词
		UPDATE a SET IsValid = 1
		FROM @t a, Marketdb..SpreadKeywordAssign b, ManagerUser c
		WHERE a.ManagerUserId = c.Id
		AND a.KeyWords = b.Keyword
		AND b.DeptId = c.DeptId
		AND b.EndDate > GETDATE()

		UPDATE a SET IsValid = 1
		FROM @t a, Marketdb..SpreadKeywordAssign b, ManagerUser c
		WHERE a.ManagerUserId = c.Id
		AND a.Referer LIKE '%www.baidu.com/%'
		AND b.DeptId = c.DeptId
		AND b.EndDate > GETDATE()
 
		--删除不是关键词的
		DELETE @t WHERE IsValid = 0

		DELETE @t WHERE LEN(VersionId) IN(3, 5)
		UPDATE @t SET VersionId = LEFT(VersionId, 2) WHERE LEN(VersionId) = 6
 		SELECT SessionId, Min(addDate) AddDate
		INTO #l1
		FROM WuTongGuoDb..SynUeoLog b
		WHERE SessionId IN(SELECT SessionId FROM @t)
		GROUP BY SessionId

		DELETE a
		FROM @t a
		WHERE EXISTS(SELECT 'x' FROM #l1 b
			WHERE a.SessionId = b.SessionId
			AND b.AddDate < DATEADD(MINUTE, -10, a.RefererDate))

		--插入refererlog
		INSERT INTO Marketdb..SpreadKeywordRefererLog(SessionId, dcSubSiteId, ManagerUserId, Engine, Keyword, Referer, RefererDate, Ip, LoginType, ViewPageNumber, AddDate)
		SELECT SessionId, VersionId, ManagerUserId, Engine, Keywords, Referer, RefererDate, Ip, 1, 0, GETDATE()
		FROM @t
		WHERE LEN(VersionId) <= 4
	END

	--从ueolog中搜索sessionid的开始、结束时间
	SELECT SessionId, DATEADD(MINUTE, -1, AddDate) AddDate, Engine, 0 PageNumber, 0 IsValid, 0 MaxId , GETDATE() - 1 EndDate, SPACE(500) Url
	INTO #u
	FROM Marketdb..SpreadKeywordRefererLog
	WHERE AddDate > DATEADD(MINUTE, -120, GETDATE())
	UPDATE #u SET IsValid = 1 WHERE SessionId IN(SELECT SessionId FROM WuTongGuoDb..SynUeoLog WHERE AddDate > DATEADD(MINUTE, -2, GETDATE()))
	DELETE #u WHERE IsValid = 0

	IF (SELECT COUNT(*) FROM #u) > 0
	BEGIN
		SELECT ID, SessionId, AddDate INTO #l3 FROM WuTongGuoDb..SynUeoLog b WHERE SessionId IN(SELECT SessionId FROM #u)
		UPDATE #u SET PageNumber = (SELECT COUNT(*) FROM #l3 b WHERE #u.SessionId = b.SessionId AND b.AddDate > #u.AddDate)

		SELECT SessionId, MAX(Id) ID 
		INTO #l2
		FROM #l3 WITH(NOLOCK)
		GROUP BY SessionId

		UPDATE a SET a.MaxId = b.Id FROM #u a, #l2 b WHERE a.SessionId = b.SessionId

		UPDATE a
		SET a.EndDate = b.AddDate,
			a.Url = b.Url
		FROM #u a, WuTongGuoDb..SynUeoLog b
		WHERE a.MaxId = b.Id
	END
--	SELECT * FROM #u
	UPDATE a
	SET a.EndDate = b.EndDate,
		a.EndUrl = b.Url,
		ViewPageNumber = b.PageNumber
	FROM Marketdb..SpreadKeywordRefererLog a, #u b
	WHERE a.AddDate > DATEADD(MINUTE, -120, GETDATE())
	AND a.Engine = b.Engine
	AND a.SessionId = b.SessionId

	--记录pageminute
	UPDATE Marketdb..SpreadKeywordRefererLog 
	SET PageMinute = DATEDIFF(MINUTE, RefererDate, EndDate)
	WHERE EndDate > DATEADD(MINUTE, -5, GETDATE())	
	AND IsValid = 0

	--10分钟有效
	UPDATE Marketdb..SpreadKeywordRefererLog 
	SET IsValid = 1
	WHERE EndDate > DATEADD(MINUTE, -5, GETDATE()) 
	AND IsValid = 0 
	AND DATEDIFF(MINUTE, RefererDate, EndDate) >= 10	
END

GO
/****** Object:  StoredProcedure [dbo].[ProcSpreadKeywordRefererLogByWtgUpdate]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--sean 2014-4-3 baidu 点击自动统计，工作日19:00~7:00算业余时间 非工作日0：00～24：00， 点击到结束 超过10分钟算有效
CREATE PROCEDURE [dbo].[ProcSpreadKeywordRefererLogByWtgUpdate]
AS
SET NOCOUNT ON
return
BEGIN
	DECLARE @Now DATETIME
	SET @Now = GETDATE()	--'2014-6-15 23:58'
	IF DATEPART(HOUR, @Now) BETWEEN 7 AND 17	-- AND 1=2
		IF EXISTS(SELECT 'x' FROM Oadb..WorkDate WHERE WorkDate = CONVERT(VARCHAR(8), @Now, 112) AND WorkType = 1)
			RETURN
	
	UPDATE Marketdb..SpreadKeywordRefererLog 
	SET PageMinute = DATEDIFF(MINUTE, RefererDate, EndDate)
	WHERE EndDate IS NOT NULL
	AND EndDate > DATEADD(MINUTE, -10, @Now)

	SELECT *, 0 HasDone INTO #t FROM Marketdb..SpreadKeywordRefererLog 
	WHERE RefererDate > CONVERT(VARCHAR(10), @Now, 120)
	AND PageMinute >= 10 AND IsRepeat = 0

	DECLARE @id INT, @Mid INT, @RDate DATETIME, @EDate DATETIME, 
		@PrevRDate DATETIME, @PrevEDate DATETIME, @Sid VARCHAR(30), 
		@N INT, @Ip VARCHAR(15), @IntervalMinute INT, @Engine INT

	WHILE EXISTS(SELECT 'x' FROM #t WHERE HasDone = 0 AND EndDate > DATEADD(MINUTE, -4, @Now))
	BEGIN
		SELECT @Id = Id, @MId = ManagerUSerId, @RDate = RefererDate, @EDate = EndDate,
			@Sid = SessionId, @ip = Ip, @Engine = Engine
		FROM #t
		WHERE HasDone = 0
		ORDER BY ManagerUserId, ID

		UPDATE #t SET HasDone = 1 WHERE ID = @Id

		IF EXISTS(SELECT 'x' FROM #t WHERE SessionId = @Sid AND @ip = IP AND Id < @ID AND Engine = @Engine)
			UPDATE #t SET IsRepeat = 1 WHERE ID = @ID
		ELSE
		BEGIN
			IF EXISTS(SELECT 'x' FROM #t WHERE @ip = IP AND Id < @ID AND Engine = @Engine)
				UPDATE #t SET IsIpRepeat = 1 WHERE ID = @ID

			SET @n = 0
			SELECT TOP 1 @N = 1, @PrevRDate = RefererDate, @PrevEDate = EndDate 
			FROM #t 
			WHERE ID < @ID AND ManagerUserId = @Mid 
			AND IsValid = 1
			AND Engine = @Engine
			--AND IntervalMinute > 19
			ORDER BY ID DESC

			IF(@n = 1)
				SET @IntervalMinute = DATEDIFF(MINUTE, @PrevEDate, @RDate)
			ELSE
				SET @IntervalMinute = 99

			UPDATE #t
			SET IntervalMinute = @IntervalMinute 
			WHERE ID = @ID
		END
	END

	DELETE #t WHERE ManagerUserid NOT IN(SELECT ManagerUserId FROM #t WHERE EndDate > DATEADD(MINUTE, -5, @Now))

	UPDATE a
	SET a.TodayNumber = b.Num
	FROM #t a, (
		SELECT Id, Engine, ManagerUserId, Row_Number() OVER(Partition BY ManagerUserId, Engine ORDER BY ID) Num
		FROM #t
		WHERE PageMinute>9 AND IntervalMinute > 19 AND IsRepeat = 0 AND dcSubSiteId = 90) b
	WHERE a.Id = b.Id
	AND a.Engine = b.Engine

	UPDATE #t SET IsValid = 0
	UPDATE #t SET IsValid = 1 WHERE PageMinute > 9 AND IntervalMinute > 19 AND TodayNumber < 3

--select * from #t where manageruserid =112 order by id desc
/*	IF EXISTS(SELECT 'x' FROM Oadb..WorkDate WHERE WorkDate = CONVERT(VARCHAR(8), @Now, 112) AND WorkType = 3)
		UPDATE #t
		SET IsMore2Valid = 1
		WHERE PageMinute > 9 AND IntervalMinute > 19 AND TodayNumber > 2
		AND DATEPART(HOUR, RefererDate) BETWEEN 7 AND 17
		AND IsIpRepeat = 0
*/
	UPDATE a
	SET a.IsRepeat = b.IsRepeat,
		a.IntervalMinute = b.IntervalMinute,
		a.IsMore2Valid = b.IsMore2Valid,
		a.TodayNumber = b.TodayNumber
	FROM Marketdb..SpreadKeywordRefererLog a, #t b
	WHERE a.Id = b.Id

	UPDATE Marketdb..SpreadKeywordRefererLog SET IsValid = 1
	WHERE TodayNumber < 3 AND IsValid = 0 AND EndDate > @Now - 0.5 AND PageMinute > 9 
		AND IntervalMinute > 19 AND IsValid = 0 AND IsRepeat = 0
	UPDATE Marketdb..SpreadKeywordRefererLog SET IsValid = 0 
	WHERE TodayNumber > 2 AND IsValid = 1 AND EndDate > @Now - 0.5 AND ViewPageNumber <= 1 AND IsRepeat = 1
	UPDATE Marketdb..SpreadKeywordRefererLog SET IsValid = 0 
	WHERE IntervalMinute < 20 AND PageMinute > 9 AND EndDate > @Now - 0.5 AND IsValid = 1 AND IsRepeat = 1
	UPDATE Marketdb..SpreadKeywordRefererLog SET IsValid = 0 WHERE EndDate > @Now - 0.5 AND IsValid = 1 AND IsRepeat = 1
END

GO
/****** Object:  StoredProcedure [dbo].[ProcSpreadKeywordRefererLogSave]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--sean 2014-4-3 baidu 点击自动统计，工作日19:00~7:00算业余时间 非工作日0：00～24：00， 点击到结束 超过10分钟算有效
CREATE PROCEDURE [dbo].[ProcSpreadKeywordRefererLogSave]
AS
--return
BEGIN
	SET NOCOUNT ON
	/*	Add Limit Condition*/
	IF EXISTS(SELECT 'x' FROM Oadb..WorkDate WHERE WorkDate = CONVERT(VARCHAR(8), GETDATE(), 112) AND WorkType = 1)
		IF DATEPART(HOUR, GETDATE()) BETWEEN 7 AND 17	-- AND 1=2
			RETURN
	
	--Delete the login user in 10 Minutes 
	DELETE ManagerLogSnap WHERE LoginDate < DATEADD(MINUTE, -10, GETDATE())
	DELETE SynUeoLog WHERE IP IN(SELECT IP FROM Ip_White)
 
	IF(SELECT COUNT(*) FROM ManagerLogSnap) > 0		--have login user
	BEGIN
		--记录Refer的ip
		SELECT *
		INTO #R
		FROM Referer WITH(NOLOCK) 
		WHERE LoginDate > DATEADD(MINUTE, -10, GETDATE()) 
		AND Ip IN(SELECT IP FROM ManagerLogSnap) 
		AND ((Keywords > '' AND (Referer LIKE '%.haosou.%' OR Referer LIKE '%.sogou.%'))
			OR Referer LIKE '%.baidu.%')

		--记录seconderer的ip
		INSERT INTO #R
		SELECT *
		FROM Seconderer WITH(NOLOCK) 
		WHERE LoginDate > DATEADD(MINUTE, -10, GETDATE()) 
		AND Ip IN(SELECT IP FROM ManagerLogSnap) 
		AND ((Keywords > '' AND (Referer LIKE '%.haosou.%' OR Referer LIKE '%.sogou.%'))
			OR Referer LIKE '%.baidu.%')
 
		--登录和referer匹配
		DECLARE @t AS TABLE
		(
			ManagerUserId INT,
			VersionId INT,
			IP VARCHAR(15),
			Keywords NVARCHAR(50),
			Referer VARCHAR(200),
			RefererDate DATETIME,
			SessionId VARCHAR(30),
			Engine TINYINT,
			IsValid BIT
		)

		INSERT INTO @t
		SELECT b.ManagerId, a.VersionId, a.Ip, LTRIM(RTRIM(a.Keywords)), a.Referer, a.LoginDate RefererDate, a.SessionId, 0, 0
		FROM #r a, ManagerLogSnap b
		WHERE a.Ip = b.Ip
 
		UPDATE @t SET Engine = 2 WHERE Referer LIKE '%.haosou.%'
		UPDATE @t SET Engine = 3 WHERE Referer LIKE '%.sogou.%'
		UPDATE @t SET Engine = 1 WHERE Referer LIKE '%.baidu.%'

		--删除先点击后登录的
		DELETE a
		FROM @t a, Marketdb..SpreadKeywordRefererLog b
		WHERE a.Referer = b.Referer 
		AND a.Ip = b.Ip 
		AND a.SessionId = b.SessionId
		AND a.Engine = b.Engine
		AND b.RefererDate > DATEADD(MINUTE, -30, GETDATE())
 
		--检查关键词
		UPDATE a SET IsValid = 1
		FROM @t a, Marketdb..SpreadKeywordAssign b, ManagerUser c
		WHERE a.ManagerUserId = c.Id
		AND a.KeyWords = b.Keyword
		AND b.DeptId = c.DeptId
		AND b.EndDate > GETDATE()

		UPDATE a SET IsValid = 1
		FROM @t a, Marketdb..SpreadKeywordAssign b, ManagerUser c
		WHERE a.ManagerUserId = c.Id
		AND a.Referer LIKE '%www.baidu.com/%'
		AND b.DeptId = c.DeptId
		AND b.EndDate > GETDATE()
 
		--删除不是关键词的
		DELETE @t WHERE IsValid = 0

		DELETE @t WHERE LEN(VersionId) IN(3, 5)
		UPDATE @t SET VersionId = LEFT(VersionId, 2) WHERE LEN(VersionId) = 6
 		SELECT SessionId, Min(addDate) AddDate
		INTO #l1
		FROM SynUeoLog b
		WHERE SessionId IN(SELECT SessionId FROM @t)
		GROUP BY SessionId

		DELETE a
		FROM @t a
		WHERE EXISTS(SELECT 'x' FROM #l1 b
			WHERE a.SessionId = b.SessionId
			AND b.AddDate < DATEADD(MINUTE, -10, a.RefererDate))

		--插入refererlog
		INSERT INTO Marketdb..SpreadKeywordRefererLog(SessionId, dcSubSiteId, ManagerUserId, Engine, Keyword, Referer, RefererDate, Ip, LoginType, ViewPageNumber, AddDate)
		SELECT SessionId, VersionId, ManagerUserId, Engine, Keywords, Referer, RefererDate, Ip, 1, 0, GETDATE()
		FROM @t
		WHERE LEN(VersionId) <= 4
	END

	--从ueolog中搜索sessionid的开始、结束时间
	SELECT SessionId, DATEADD(MINUTE, -1, AddDate) AddDate, Engine, 0 PageNumber, 0 IsValid, 0 MaxId , GETDATE() - 1 EndDate, SPACE(500) Url
	INTO #u
	FROM Marketdb..SpreadKeywordRefererLog
	WHERE AddDate > DATEADD(MINUTE, -120, GETDATE())
	UPDATE #u SET IsValid = 1 WHERE SessionId IN(SELECT SessionId FROM SynUeoLog WHERE AddDate > DATEADD(MINUTE, -2, GETDATE()))
	DELETE #u WHERE IsValid = 0

	IF (SELECT COUNT(*) FROM #u) > 0
	BEGIN
		SELECT ID, SessionId, AddDate INTO #l3 FROM SynUeoLog b WHERE SessionId IN(SELECT SessionId FROM #u)
		UPDATE #u SET PageNumber = (SELECT COUNT(*) FROM #l3 b WHERE #u.SessionId = b.SessionId AND b.AddDate > #u.AddDate)

		SELECT SessionId, MAX(Id) ID 
		INTO #l2
		FROM #l3 WITH(NOLOCK)
		GROUP BY SessionId

		UPDATE a SET a.MaxId = b.Id FROM #u a, #l2 b WHERE a.SessionId = b.SessionId

		UPDATE a
		SET a.EndDate = b.AddDate,
			a.Url = b.Url
		FROM #u a, SynUeoLog b
		WHERE a.MaxId = b.Id
	END
--	SELECT * FROM #u
	UPDATE a
	SET a.EndDate = b.EndDate,
		a.EndUrl = b.Url,
		ViewPageNumber = b.PageNumber
	FROM Marketdb..SpreadKeywordRefererLog a, #u b
	WHERE a.AddDate > DATEADD(MINUTE, -120, GETDATE())
	AND a.Engine = b.Engine
	AND a.SessionId = b.SessionId

	--记录pageminute
	UPDATE Marketdb..SpreadKeywordRefererLog 
	SET PageMinute = DATEDIFF(MINUTE, RefererDate, EndDate)
	WHERE EndDate > DATEADD(MINUTE, -5, GETDATE())	
	AND IsValid = 0

	--10分钟有效
	UPDATE Marketdb..SpreadKeywordRefererLog 
	SET IsValid = 1
	WHERE EndDate > DATEADD(MINUTE, -5, GETDATE()) 
	AND IsValid = 0 
	AND DATEDIFF(MINUTE, RefererDate, EndDate) >= 10	
END

GO
/****** Object:  StoredProcedure [dbo].[ProcSpreadKeywordRefererLogUpdate]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--sean 2014-4-3 baidu 点击自动统计，工作日19:00~7:00算业余时间 非工作日0：00～24：00， 点击到结束 超过10分钟算有效
CREATE PROCEDURE [dbo].[ProcSpreadKeywordRefererLogUpdate]
AS
--return
SET NOCOUNT ON
BEGIN
	DECLARE @Now DATETIME
	SET @Now = GETDATE()	--'2014-6-15 23:58'
	IF DATEPART(HOUR, @Now) BETWEEN 7 AND 17	-- AND 1=2
		IF EXISTS(SELECT 'x' FROM Oadb..WorkDate WHERE WorkDate = CONVERT(VARCHAR(8), @Now, 112) AND WorkType = 1)
			RETURN
	
	UPDATE Marketdb..SpreadKeywordRefererLog 
	SET PageMinute = DATEDIFF(MINUTE, RefererDate, EndDate)
	WHERE EndDate IS NOT NULL
	AND EndDate > DATEADD(MINUTE, -10, @Now)

	SELECT *, 0 HasDone INTO #t FROM Marketdb..SpreadKeywordRefererLog 
	WHERE RefererDate > CONVERT(VARCHAR(10), @Now, 120)
	AND PageMinute >= 10 AND IsRepeat = 0

	DECLARE @id INT, @Mid INT, @RDate DATETIME, @EDate DATETIME, 
		@PrevRDate DATETIME, @PrevEDate DATETIME, @Sid VARCHAR(30), 
		@N INT, @Ip VARCHAR(15), @IntervalMinute INT, @Engine INT

	WHILE EXISTS(SELECT 'x' FROM #t WHERE HasDone = 0 AND EndDate > DATEADD(MINUTE, -4, @Now))
	BEGIN
		SELECT @Id = Id, @MId = ManagerUSerId, @RDate = RefererDate, @EDate = EndDate,
			@Sid = SessionId, @ip = Ip, @Engine = Engine
		FROM #t
		WHERE HasDone = 0
		ORDER BY ManagerUserId, ID

		UPDATE #t SET HasDone = 1 WHERE ID = @Id

		IF EXISTS(SELECT 'x' FROM #t WHERE SessionId = @Sid AND @ip = IP AND Id < @ID AND Engine = @Engine)
			UPDATE #t SET IsRepeat = 1 WHERE ID = @ID
		ELSE
		BEGIN
			IF EXISTS(SELECT 'x' FROM #t WHERE @ip = IP AND Id < @ID AND Engine = @Engine)
				UPDATE #t SET IsIpRepeat = 1 WHERE ID = @ID

			SET @n = 0
			SELECT TOP 1 @N = 1, @PrevRDate = RefererDate, @PrevEDate = EndDate 
			FROM #t 
			WHERE ID < @ID AND ManagerUserId = @Mid 
			AND IsValid = 1
			AND Engine = @Engine
			AND IntervalMinute > 19
			ORDER BY ID DESC

			IF(@n = 1)
				SET @IntervalMinute = DATEDIFF(MINUTE, @PrevEDate, @RDate)
			ELSE
				SET @IntervalMinute = 99

			UPDATE #t
			SET IntervalMinute = @IntervalMinute 
			WHERE ID = @ID
		END
	END

	DELETE #t WHERE ManagerUserid NOT IN(SELECT ManagerUserId FROM #t WHERE EndDate > DATEADD(MINUTE, -5, @Now))

	UPDATE a
	SET a.TodayNumber = b.Num
	FROM #t a, (
		SELECT Id, Engine, ManagerUserId, Row_Number() OVER(Partition BY ManagerUserId, Engine ORDER BY ID) Num
		FROM #t
		WHERE PageMinute>9 AND IntervalMinute > 19 AND IsRepeat = 0) b
	WHERE a.Id = b.Id
	AND a.Engine = b.Engine

	UPDATE #t SET IsValid = 0
	UPDATE #t SET IsValid = 1 WHERE PageMinute > 9 AND IntervalMinute > 19 AND TodayNumber < 3

--select * from #t where manageruserid =112 order by id desc
/*	IF EXISTS(SELECT 'x' FROM Oadb..WorkDate WHERE WorkDate = CONVERT(VARCHAR(8), @Now, 112) AND WorkType = 3)
		UPDATE #t
		SET IsMore2Valid = 1
		WHERE PageMinute > 9 AND IntervalMinute > 19 AND TodayNumber > 2
		AND DATEPART(HOUR, RefererDate) BETWEEN 7 AND 17
		AND IsIpRepeat = 0
*/
	UPDATE a
	SET a.IsRepeat = b.IsRepeat,
		a.IntervalMinute = b.IntervalMinute,
		a.IsMore2Valid = b.IsMore2Valid,
		a.TodayNumber = b.TodayNumber
	FROM Marketdb..SpreadKeywordRefererLog a, #t b
	WHERE a.Id = b.Id

	UPDATE Marketdb..SpreadKeywordRefererLog SET IsValid = 1
	WHERE TodayNumber < 3 AND IsValid = 0 AND EndDate > @Now - 0.5 AND PageMinute > 9 
		AND IntervalMinute > 19 AND IsValid = 0 AND IsRepeat = 0
	UPDATE Marketdb..SpreadKeywordRefererLog SET IsValid = 0 
	WHERE TodayNumber > 2 AND IsValid = 1 AND EndDate > @Now - 0.5 AND ViewPageNumber <= 1 AND IsRepeat = 1
	UPDATE Marketdb..SpreadKeywordRefererLog SET IsValid = 0 
	WHERE IntervalMinute < 20 AND PageMinute > 9 AND EndDate > @Now - 0.5 AND IsValid = 1 AND IsRepeat = 1
	UPDATE Marketdb..SpreadKeywordRefererLog SET IsValid = 0 WHERE EndDate > @Now - 0.5 AND IsValid = 1 AND IsRepeat = 1
END

GO
/****** Object:  StoredProcedure [dbo].[ProcSpreadLoginLogIdByIpSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2014.10.28
--创建人：John
--说明：推广部百度点击相关， 获取当前ip是否是内部员工点击的
--#####################################################
CREATE PROCEDURE [dbo].[ProcSpreadLoginLogIdByIpSelect]
(
	@ip VARCHAR(15)
)
AS
BEGIN
	SELECT TOP 1 Id 
	FROM SpreadLoginLogsnap 
	WHERE Ip = @ip 
	ORDER BY AddDate DESC
END
GO
/****** Object:  StoredProcedure [dbo].[ProcSpreadLoginLogSnapByIpSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2014.10.28
--创建人：John
--说明：推广部百度点击相关， 获取当前ip是否是内部员工点击的
--#####################################################
CREATE PROCEDURE [dbo].[ProcSpreadLoginLogSnapByIpSelect]
(
	@ip VARCHAR(15)
)
AS
BEGIN
	SELECT TOP 1 Id, ManagerUserId, Ip, Cookies, AddDate, LoginNumber, Keyword	--LEFT(Keyword, 4) Keyword 
	FROM SpreadLoginLogsnap 
	WHERE Ip = @ip 
	ORDER BY AddDate DESC
END
GO
/****** Object:  StoredProcedure [dbo].[ProcSpreadRefererLogBySpreadLoginLogIdUpdate]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
sean 2014-6-19 used by spread 
spreader visstt page
*/
CREATE PROCEDURE [dbo].[ProcSpreadRefererLogBySpreadLoginLogIdUpdate]
(
	@SpreadLoginLogId varchar(8),
	@EndUrl varchar(200),
	@VisitType INT
)
AS
BEGIN
	UPDATE SpreadRefererLog
	SET EndUrl = @EndUrl, EndDate = GETDATE(), PageMinute = DATEDIFF(MINUTE, RefererDate, GETDATE())
	WHERE SpreadLoginLogId = @SpreadLoginLogId
	AND VisitType = @VisitType
	AND RefererDate > DATEADD(MINUTE, -100, GETDATE())
END










GO
/****** Object:  StoredProcedure [dbo].[ProcSpreadRefererLogInsert]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
sean 2014-6-19 used by spread 
spreader first visst first page
Updated by sean,at 2014-7-7. Can't more than 2 in one day. Can't be office ip
*/
CREATE PROCEDURE [dbo].[ProcSpreadRefererLogInsert]
(
	@SpreadLoginLogId int,
	@dcSubSiteId smallint,
	@Keyword nvarchar(50),
	@Referer varchar(200),
	@SessionID varchar(30),
	@BeginUrl varchar(200),
	@VisitType TINYINT
)
AS
SET NOCOUNT ON
--INSERT INTO a2 SELECT @SpreadLoginLogId, @dcSubSiteId, @Keyword, @Referer, @SessionID, @BeginUrl, @VisitType, GETDATE()
BEGIN
	--IF(@VisitType = 1)
	--	RETURN

	IF EXISTS(SELECT 'x' FROM SpreadRefererLog WHERE SessionId = @SessionId)
		RETURN  1

	IF EXISTS(SELECT 'x' FROM SpreadRefererLog 
		WHERE SpreadLoginLogId = @SpreadLoginLogId
		AND VisitType = @VisitType)
		RETURN  2

	INSERT INTO SpreadRefererLog(SpreadLoginLogId, dcSubSiteId, Keyword,
		Referer, RefererDate, SessionID, BeginUrl, EndUrl, EndDate, 
		PageMinute, VisitType)
	SELECT @SpreadLoginLogId, @dcSubSiteId, @Keyword,
		@Referer, GETDATE(), @SessionID, @BeginUrl, @BeginUrl, GETDATE(), 
		0, @VisitType
END
GO
/****** Object:  StoredProcedure [dbo].[ProcSpreadRefererLogUpdate]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
sean 2014-6-19 used by spread 
spreader visstt page
*/
CREATE PROCEDURE [dbo].[ProcSpreadRefererLogUpdate]
(
	@SessionID varchar(30),
	@EndUrl varchar(200)
)
AS
BEGIN
	UPDATE SpreadRefererLog
	SET EndUrl = @EndUrl, EndDate = GETDATE(), PageMinute = DATEDIFF(MINUTE, RefererDate, GETDATE())
	WHERE SessionId = @SessionId
	AND RefererDate > DATEADD(MINUTE, -100, GETDATE())
END










GO
/****** Object:  StoredProcedure [dbo].[procSubSiteByAllSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[procSubSiteByAllSelect]
AS
BEGIN
	SELECT 
		a.*,
		b.ProvinceName,
		b.WebsiteName,
		b.ProvinceDomain,
		b.SouthNorth,
		b.AssignConsultant,
		b.AdRemarks,
		(SELECT TOP 1 Keyword FROM Logdb..SpreadKeywordAssign c WITH(NOLOCK)
		WHERE c.dcSubSiteId = a.Id AND c.IsValid = 1) SpreadKeyword
	FROM dcSubSite a WITH(NOLOCK)
	INNER JOIN dcProvince b WITH(NOLOCK) ON a.ProvinceId= b.ID
	ORDER BY ProvinceId, ID
END










GO
/****** Object:  StoredProcedure [dbo].[procSubSiteByMainSiteSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[procSubSiteByMainSiteSelect]
AS
BEGIN
	SELECT 
		a.*,
		b.ProvinceName,
		b.WebsiteName,
		b.ProvinceDomain,
		b.SouthNorth,
		b.AssignConsultant,
		b.AdRemarks,
		(SELECT TOP 1 Keyword FROM Logdb..SpreadKeywordAssign c WITH(NOLOCK)
		WHERE LEFT(c.dcSubSiteId, 2) = a.Id AND c.IsValid = 1) SpreadKeyword
	FROM dcSubSite a WITH(NOLOCK)
	INNER JOIN dcProvince b WITH(NOLOCK) ON a.ProvinceId= b.ID
	WHERE a.IsMainSite = 1
	ORDER BY ProvinceId, ID
END









GO
/****** Object:  StoredProcedure [dbo].[procSubsiteByProvinceIDSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--创建人 Lambo 20101018
--用于首页根据省份编号查询改省的所有的地区

CREATE PROCEDURE [dbo].[procSubsiteByProvinceIDSelect]
(
	@provinceId INT
)
AS
BEGIN
	SELECT id,SubsiteCity,SubsiteUrl 
	FROM dcSubsite WITH(NOLOCK)
	WHERE provinceId = @provinceId
END














GO
/****** Object:  StoredProcedure [dbo].[ProcSubSiteByUrlSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2014.10.28
--创建人：John
--说明：获取网站站点数据
--@subSiteUrl 网站Url
--#####################################################
CREATE PROCEDURE [dbo].[ProcSubSiteByUrlSelect]
(
	@subSiteUrl VARCHAR(50)
)
AS
BEGIN TRY
	SELECT id, SubSiteName WebSite, Replace(SubSiteUrl, 'www.', '') Domain 
	FROM dcSubSite WITH(NOLOCK) 
	WHERE SubSiteUrl = @subSiteUrl
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[procSubSiteSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[procSubSiteSelect]
(
	@SubSiteUrl VARCHAR(50)
)
AS
BEGIN
	IF EXISTS(SELECT 'x' FROM dcSubSite WITH(NOLOCK) WHERE SubSiteUrl LIKE @SubSiteUrl)
		SELECT 
			a.*,
			b.ProvinceName,
			b.WebsiteName,
			b.ProvinceDomain,
			b.SouthNorth,
			b.AssignConsultant,
			b.AdRemarks
		FROM dcSubSite a WITH(NOLOCK)
		INNER JOIN dcProvince b WITH(NOLOCK) ON a.ProvinceId= b.ID
		WHERE a.SubSiteUrl = @SubSiteUrl
	ELSE
	BEGIN
		DECLARE @Url AS VARCHAR(50)
		IF CHARINDEX('/', @SubSiteUrl) = 0
		BEGIN 
			SELECT TOP 0 'x'
			RETURN
		END

		SELECT @Url = LEFT(@SubSiteUrl, CHARINDEX('/', @SubSiteUrl) - 1)
		SELECT 
			a.*,
			b.ProvinceName,
			b.WebsiteName,
			b.ProvinceDomain,
			b.SouthNorth,
			b.AssignConsultant,
			b.AdRemarks
		FROM dcSubSite a WITH(NOLOCK)
		INNER JOIN dcProvince b WITH(NOLOCK) ON a.ProvinceId = b.ID
		WHERE a.SubSiteUrl = @Url
	END
END














GO
/****** Object:  StoredProcedure [dbo].[ProcSynbsAskInfoClickNumberSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.28
--创建人：Nick
--说明：得到最新求职互助问题
--#####################################################
CREATE PROCEDURE [dbo].[ProcSynbsAskInfoClickNumberSelect]
(
	@ProvinceID INT,
	@SubSiteID INT
)
AS
BEGIN TRY
	SELECT ID,Title 
	FROM SynbsAskInfoClickNumber WITH(NOLOCK)
	WHERE ProvinceId = @ProvinceID
	ORDER BY ClickNumber DESC 
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[procSynUeoLogInsert]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[procSynUeoLogInsert]
(
	@SessionId VARCHAR(50),
	@paMainId INT,
	@caMainId INT,
	@PageId INT,
	@SubSiteId int
)
AS
RETURN
SET NOCOUNT ON
IF @SubSiteId = 9
	RETURN

BEGIN
	INSERT LogDb..UeoLog(SessionId, paMainId, caMainId, PageId, SubSiteId)
	SELECT @SessionId, @paMainId, @caMainId, @PageId, @SubSiteId
END










GO
/****** Object:  StoredProcedure [dbo].[procSynUeoLogInsertNew]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[procSynUeoLogInsertNew]
(
	@SessionId VARCHAR(50),
	@paMainId INT,
	@caMainId INT,
	@PageId INT,
	@SubSiteId INT,
	@IP VARCHAR(20),
	@Url VARCHAR(200),
	@IsSpider BIT
)
AS
RETURN
SET NOCOUNT ON
IF @SubSiteId = 9
	RETURN
BEGIN
	INSERT LogDb..UeoLog(SessionId, paMainId, caMainId, PageId, SubSiteId, IP, Url, IsSpider)
	SELECT @SessionId, @paMainId, @caMainId, @PageId, @SubSiteId, @IP, @Url, @IsSpider
END

GO
/****** Object:  StoredProcedure [dbo].[ProcTelAreaSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2014.10.31
--创建人：John
--说明：获取座机所在的省份城市
--#####################################################
CREATE PROCEDURE [dbo].[ProcTelAreaSelect]
(
	@telNo INT
)
AS
BEGIN
	SELECT TOP 1 Province, City FROM dcTelArea WITH(NOLOCK) WHERE AreaNo = @telNo
END


GO
/****** Object:  StoredProcedure [dbo].[ProcTmpWsLogInsert]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ProcTmpWsLogInsert]
(
    @Ip varchar(15),
    @PageId INT,
	@Para VARCHAR(100)
)
AS
SET NOCOUNT ON
BEGIN
    INSERT INTO tmpWSLog(ip, PageId, AddDate,para) SELECT @Ip, @PageID, GETDATE(),@Para

    RETURN @@IDENTITY
END
GO
/****** Object:  StoredProcedure [dbo].[procToolRunLogUpdate]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[procToolRunLogUpdate]
AS
truncate table toolrunlog
return
BEGIN
	DELETE FROM ToolRunLog WHERE RunStatus=1 AND ID IN(
		SELECT ID FROM(
			SELECT row_number() OVER (PARTITION BY ToolType ORDER BY AddDate DESC) TypeRow,ID
			FROM ToolRunLog
			WHERE RunStatus=1
		) t WHERE TypeRow > 1000
	)

	DELETE FROM ToolRunLog WHERE RunStatus = 0 AND ID IN(
		SELECT ID FROM(
			SELECT row_number() OVER (PARTITION BY ToolType ORDER BY AddDate DESC) TypeRow,ID
			FROM ToolRunLog
			WHERE RunStatus=0
		) t WHERE TypeRow > 2000
	)

	INSERT INTO RtxNotifyLog(Receiver,RtxTitle,RtxMessage)
	SELECT '112,116', '服务未未运行提醒', ToolType
	FROM (
		SELECT CASE ToolType
			WHEN 1 THEN 'RTX发送'
			WHEN 2 THEN '短信发送'
			WHEN 3 THEN '文件监视'
			WHEN 4 THEN '文件更新'
			WHEN 5 THEN '传真发送'
			WHEN 6 THEN 'RTX状态检测'
			WHEN 7 THEN 'RTX消息检测'
			WHEN 8 THEN '百度收录'
			ELSE ''
			END + '服务已经30分钟没有运行了，请及时查找原因' ToolType,
			MAX(EndTime) EndTime
		FROM ToolRunLog
		GROUP BY ToolType) a
	WHERE DATEDIFF(MINUTE, EndTime, GETDATE()) > 30
	
	INSERT INTO RtxNotifyLog(Receiver,RtxTitle,RtxMessage)
	SELECT '112,116','服务异常提醒', ToolType
	FROM (
		SELECT CASE ToolType
			WHEN 1 THEN 'RTX发送'
			WHEN 2 THEN '短信发送'
			WHEN 3 THEN '文件监视'
			WHEN 4 THEN '文件更新'
			WHEN 5 THEN '传真发送'
			WHEN 6 THEN 'RTX状态检测'
			WHEN 7 THEN 'RTX消息检测'
			WHEN 8 THEN '邮件发送'
			ELSE ''
		END + '服务已经30分钟内运行失败超过3次了，请及时查找原因' ToolType,
			MAX(EndTime) EndTime
		FROM ToolRunLog
		WHERE DATEDIFF(MINUTE, EndTime, GETDATE()) < 30 	
		AND RunStatus = 0 
		GROUP BY ToolType
		HAVING COUNT(1) >= 3) a

	DELETE ToolRunLog WHERE AddDate < GETDATE() - 1
END











GO
/****** Object:  StoredProcedure [dbo].[ProcTop10SalaryByJobTypeSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.3
--创建人：John
--说明：根据JobType 获取该职位全国各地区排行 从高到低
--#####################################################
CREATE PROCEDURE [dbo].[ProcTop10SalaryByJobTypeSelect]
(
	@dcJobTypeID SMALLINT
)
AS
BEGIN
	SELECT TOP 10 a.dcJobTypeID,a.AvgSalary,b.FullName RegionName 
	FROM reportdb..SalaryReportJobtype a LEFT JOIN dcRegion b ON b.id = a.dcRegionID 
	WHERE dcJobTypeid = @dcJobTypeID 
	ORDER BY AvgSalary DESC
END


GO
/****** Object:  StoredProcedure [dbo].[ProcTopicNewsSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ProcTopicNewsSelect]
(
	@ProvinceId INT
)
AS
BEGIN
	SELECT * FROM ShortDb..TopicNews WHERE ProvinceId = @ProvinceId
END

GO
/****** Object:  StoredProcedure [dbo].[procTopics100ByTypeSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.5
--创建人：NICK
--说明：根据类别获取经常专题
--#####################################################
CREATE PROCEDURE [dbo].[procTopics100ByTypeSelect]
(
	@Type INT
)
AS
BEGIN
	IF @Type = 1
	BEGIN
		SELECT TOP 100 * FROM Topics WITH(NOLOCK) WHERE type=1 AND ID >= 199 ORDER BY adddate DESC
	END
	ELSE 
	BEGIN
		SELECT TOP 100 * FROM Topics WITH(NOLOCK) WHERE type=2 AND ID >= 199 ORDER BY adddate DESC
	END
END


GO
/****** Object:  StoredProcedure [dbo].[procTopics10Select]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.5
--创建人：NICK
--说明：精彩专题
--#####################################################
CREATE PROCEDURE [dbo].[procTopics10Select]
AS
BEGIN
	SELECT TOP 10 * FROM Topics WITH(NOLOCK) WHERE ID >= 199 ORDER BY adddate DESC
END


GO
/****** Object:  StoredProcedure [dbo].[procTopics20Select]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.5
--创建人：NICK
--说明：精彩專題
--#####################################################
CREATE PROCEDURE [dbo].[procTopics20Select]
AS
BEGIN
	SELECT TOP 20 * FROM Topics WITH(NOLOCK) WHERE ID >= 199 ORDER BY adddate DESC
END


GO
/****** Object:  StoredProcedure [dbo].[ProcTopicsByTypeIDSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.28
--创建人：Nick
--说明：
--#####################################################
CREATE PROCEDURE [dbo].[ProcTopicsByTypeIDSelect]
	@TypeID VARCHAR(10)
AS
BEGIN TRY
	IF @TypeID = '1'
	BEGIN
		SELECT TOP 100 * 
		FROM Topics WITH(NOLOCK)  
		WHERE TYPE=1
		AND ID >= 199
		ORDER BY AddDate DESC
	END
	ELSE IF @TypeID = '2'
	BEGIN
		SELECT TOP 100 * 
		FROM Topics WITH(NOLOCK)  
		WHERE TYPE=1 
		AND ID >= 199
		ORDER BY AddDate DESC
	END
	ELSE 
	BEGIN
		SELECT TOP 100 * 
		FROM Topics WITH(NOLOCK)  
		WHERE ID >= 199
		ORDER BY AddDate DESC
	END
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[procTopicsByTypeSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.5
--创建人：NICK
--说明：根据类别获取经常专题
--#####################################################
CREATE PROCEDURE [dbo].[procTopicsByTypeSelect]
(
	@Type INT
)
AS
BEGIN
	IF @Type = 1
	BEGIN
		SELECT TOP 100 * FROM Topics WITH(NOLOCK) WHERE type=1 AND ID >= 199ORDER BY adddate DESC
	END
	ELSE IF @Type = 2
	BEGIN
		SELECT TOP 100 * FROM Topics WITH(NOLOCK) WHERE type=2 AND ID >= 199 ORDER BY adddate DESC
	END
	ELSE 
	BEGIN
		SELECT TOP 100 * FROM Topics WITH(NOLOCK) WHERE ID >= 199ORDER BY adddate DESC
	END
END

GO
/****** Object:  StoredProcedure [dbo].[procTopicsOneSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.5
--创建人：NICK
--说明：获取最新的一条精彩专题
--#####################################################
CREATE PROCEDURE [dbo].[procTopicsOneSelect]
AS
BEGIN
	SELECT TOP 1 * FROM Topics WITH(NOLOCK) WHERE ID >= 199 ORDER BY AddDate DESC
END


GO
/****** Object:  StoredProcedure [dbo].[ProcTrdLoginPaMainSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.4
--创建人：John
--说明：获取第三方登录的用户信息
--#####################################################
CREATE PROCEDURE [dbo].[ProcTrdLoginPaMainSelect]
(
	@contactType TINYINT,
	@Openid VARCHAR(100)
)
AS
BEGIN
	SELECT TOP 1 b.ID,b.UserName,b.PassWord 
	FROM paLoginContact a WITH(NOLOCK), paMain b WITH(NOLOCK) 
	WHERE contacttype = @contactType 
		AND a.paMainID = b.ID 
		AND a.OpenID = @Openid 
		AND a.OpenID > '' 
	ORDER BY a.AddDate DESC
END


GO
/****** Object:  StoredProcedure [dbo].[procttttttt]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE procedure [dbo].[procttttttt]
as
begin
	delete from exinterview where cvmainid=26171884

	declare	@JobID INT, 
		@cpMainID INT, 
		@cvMainID INT, 
		@InterviewDate VARCHAR(100), 
		@InterViewPlace VARCHAR(200), 
		@LinkMan VARCHAR(12), 
		@Telephone VARCHAR(20), 
		@Remark VARCHAR(1000)

	SELECT @JobID = 5338885, @cpMainID = 10025728, @cvMainID=26171884,
		@InterviewDate = '9:00-17:00', @InterViewPlace = '济南高新区舜风路齐鲁文化创意基地12号楼3单元西一层',
		@LinkMan ='靳总', @Telephone='18654514030', @Remark='携带个人简历'

		SET NOCOUNT ON
		DECLARE @InterviewPoint INT --直接发送面试通知 赠送积分
		DECLARE @ReplyInterviewPoint INT --答复后 发送面试通知 赠送积分
		SET @InterviewPoint = 7
		SET @ReplyInterviewPoint = 2

		DECLARE @caMainID INT, @paMainId INT, @ExInterViewID INT, @wxFansId INT, @MsgCount INT
		SELECT @caMainID = caMainId FROM Job WITH(NOLOCK) WHERE ID = @JobID AND cpMainID = @cpMainID
		IF ISNULL(@caMainID, 0) = 0
			RETURN -1

		SELECT @Remark = dbo.TrimNull(@Remark),
			@InterviewDate = dbo.Trim(@InterviewDate),
			@InterViewPlace = dbo.Trim(@InterViewPlace),
			@Telephone = dbo.Trim(@Telephone)

		INSERT INTO ExInterView(JobID, cvMainID, InterviewDate, InterViewPlace, LinkMan, Telephone, Remark)
		VALUES(@JobID, @cvMainID, @InterviewDate, @InterViewPlace, @LinkMan, @Telephone, @Remark)
		SET @ExInterViewID = @@IDENTITY
		print @ExInterViewID
		--未答复的修改答复状态
		UPDATE exJobApply SET Reply =1 WHERE JobID = @JobID AND CvMainID = @cvMainID

		BEGIN TRY
			SELECT @paMainId = paMainId FROM cvMain WITH(NOLOCK) WHERE Id = @cvMainId
			SELECT @wxFansId = id FROM wxFans WITH(NOLOCK) WHERE paMainId = @paMainId AND [Status] = 2
			IF @wxFansId IS NULL
			BEGIN
	print 'is null'
				SELECT @MsgCount = SUM(smsNumber) FROM ExInterView WITH(NOLOCK)
				WHERE JobId IN(SELECT ID FROM Job WITH(NOLOCK) WHERE cpMainId = @cpMainID)
				AND AddDate > CONVERT(VARCHAR(10), GETDATE() - 29, 120)
	 
				IF @MsgCount < 30
				BEGIN
print '< 30'
					INSERT SmsMessageLog(SendMan, ManagerUSerId, paMainId, caMainId, Mobile, MsgType, IsCat, Msg)
					SELECT  0, NULL, b.ID, @caMainID, b.Mobile, 101, 0, 
						ISNULL(b.Name,'') +'，'+ d.Name +'在'+ c.SubSiteName + c.EmailSite +'上邀请您面试，请登录网站查看'
					FROM cvMain a WITH(NOLOCK), paMain b WITH(NOLOCK), dcSubSite c WITH(NOLOCK),cpMain d WITH(NOLOCK)
					WHERE a.paMainID = b.ID
					AND b.dcSubSiteID = c.ID
					AND d.ID = @cpMainID
					AND b.Mobile > ''
					AND a.ID = @cvMainID
					AND b.IsReceiveSms = 1
print'
	INSERT SmsMessageLog(SendMan, ManagerUSerId, paMainId, caMainId, Mobile, MsgType, IsCat, Msg)
					SELECT  0, NULL, b.ID, ' + ltrim(str(@caMainID)) + ', b.Mobile, 101, 0, 
						ISNULL(b.Name,'''') + ''，'' + d.Name + ''在'' +  c.SubSiteName + c.EmailSite +''上邀请您面试，请登录网站查看''
					FROM cvMain a WITH(NOLOCK), paMain b WITH(NOLOCK), dcSubSite c WITH(NOLOCK),cpMain d WITH(NOLOCK)
					WHERE a.paMainID = b.ID
					AND b.dcSubSiteID = c.ID
					AND d.ID = ' + ltrim(str(@cpMainID)) + '
					AND b.Mobile > ''''
					AND a.ID = ' + ltrim(str(@cvMainID)) + '
					AND b.IsReceiveSms = 1
'
					UPDATE ExInterView SET SmsNumber = ISNULL(SmsNumber, 0) + 1 WHERE ID = @ExInterViewID
				END
			END
			ELSE		--关注的用户发送微信消息提醒
			BEGIN
				--插入到wxMessageSend表中
				INSERT WxMessageSend2(Templatetype, WxFansID, PaMainId, MainTableId, CpMainID, CvMainID, JobId, CaMainId, AddDate)
				SELECT 1, @wxFansId, @paMainId, @ExInterViewID, @cpMainId, @cvMainID, @JobId, @caMainID, GETDATE()
			END
			
			INSERT INTO paPushLog(paMainID, PushMessage, PushType)
			SELECT @paMainId, '亲，收到一份面试通知！', 2 WHERE EXISTS(SELECT 'X' FROM paIOSBind WHERE paMainID = @paMainId)
		END TRY
		BEGIN CATCH
		END CATCH
		
		--插入积分记录
		BEGIN TRY
		--插入积分记录
			DECLARE @TodayPoint AS INT
			DECLARE @TodayID AS INT
			SET @TodayPoint = 0
			SET @TodayID = 0
			SELECT TOP 1 @TodayPoint = ISNULL(Point,0),@TodayID = ISNULL(ID,0) FROM cpPoint WITH(NOLOCK) WHERE changeID = 4 AND LastModifyDate > CONVERT(VARCHAR(10), GETDATE(),120) AND cpMainID = @cpMainID
			
			--判断是否是应聘的简历
			DECLARE @JobApplyID INT,@Reply INT

			SELECT @JobApplyID = 0,@Reply = 0
			SELECT @JobApplyID = ID,@Reply = Reply 
			FROM ExJobApply WITH(NOLOCK)
			WHERE JobID = @JobID
			AND CvMainID = @cvMainID

			IF @JobApplyID = 0	--未应聘
			BEGIN
				SET @TodayPoint = @ReplyInterviewPoint
			END
			ELSE 
			BEGIN
				IF @Reply = 0
				BEGIN
					UPDATE ExJobApply 
					SET Reply = 1
					WHERE ID = @JobApplyID

					SET @TodayPoint = @InterviewPoint
				END
				ELSE
				BEGIN
					SET @TodayPoint = @ReplyInterviewPoint
				END
			END

			SET @TodayPoint = @TodayPoint + @ReplyInterviewPoint
			
			IF @TodayPoint <= 50
			BEGIN
				IF @TodayID = 0
				BEGIN
					INSERT INTO cpPoint (cpMainID,ChangeID,Point,LastModifyDate) VALUES(@cpMainID,4,@TodayPoint,GETDATE())
				END
				ELSE
				BEGIN
					UPDATE cpPoint SET Point = Point + @TodayPoint,LastModifyDate = GETDATE() WHERE ID = @TodayID 
				END
			END	
			
		END TRY
		BEGIN CATCH
		END CATCH
	
		print ISNULL(@MsgCount, 0)
end

GO
/****** Object:  StoredProcedure [dbo].[ProcUeoLogByOverViewSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ProcUeoLogByOverViewSelect]
(
	@IP VARCHAR(39),
	@PageID INT
)
AS
SET NOCOUNT ON
IF EXISTS(SELECT TOP 1 'X' FROM logDb..UeoLogShort
	WHERE PageID = @PageID
	AND IP = @IP)
	RETURN 1
ELSE
	RETURN 0
SET NOCOUNT OFF
GO
/****** Object:  StoredProcedure [dbo].[procUeoLogShortInsert]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[procUeoLogShortInsert]
AS
SET NOCOUNT ON
BEGIN
	TRUNCATE TABLE LogDb..UeoLogShort
	INSERT INTO LogDb..UeoLogShort
	SELECT IP, PageID, COUNT(1)
	FROM logdb..UeoLog WITH(NOLOCK)
	WHERE AddDate > DATEADD(mi, -10, GETDATE())
	AND HasChecked = 0
	GROUP BY IP, PageID
	HAVING COUNT(1) > 5
END
SET NOCOUNT OFF

GO
/****** Object:  StoredProcedure [dbo].[ProcUeoVerificationCodeInsert]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ProcUeoVerificationCodeInsert]
(
	@IP VARCHAR(39)
)
AS
SET NOCOUNT ON
INSERT INTO logDb..UeoVerificationCode(IP) VALUES(@IP)
RETURN @@IDENTITY

GO
/****** Object:  StoredProcedure [dbo].[ProcUeoVerificationCodeUpdate]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ProcUeoVerificationCodeUpdate]
(
	@ID INT,
	@Success BIT
)
AS
SET NOCOUNT ON
UPDATE logDb..UeoVerificationCode SET VerifyCount = ISNULL(VerifyCount, 0) + 1 WHERE ID = @ID
IF @Success = 1
BEGIN
	UPDATE logDb..UeoVerificationCode SET VerifyDate = GETDATE() WHERE ID = @ID
	UPDATE SynUeoLog SET HasChecked = 1 WHERE Ip = (SELECT IP FROM LogDb..UeoVerificationCode WHERE Id = @Id)
	DELETE FROM logDb..UeoLogShort WHERE IP = (SELECT IP FROM LogDb..UeoVerificationCode WHERE Id = @Id)
END
SET NOCOUNT OFF
GO
/****** Object:  StoredProcedure [dbo].[procUrl_click_logInsert]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--创建人 Lambo 20101013
--用于首页记录点击记录
CREATE PROCEDURE [dbo].[procUrl_click_logInsert] 
	@id SMALLINT,
	@ip VARCHAR(15)
AS
SET NOCOUNT ON
DECLARE @cnt SMALLINT
DECLARE @ip_repeat SMALLINT

SELECT @ip_repeat=ip_repeat FROM url WITH(NOLOCK) WHERE id=@id
SELECT @cnt=COUNT(1) FROM url_click_log WITH(NOLOCK)
WHERE ip=@ip AND url_id=@id AND adddate>GETDATE()-1

IF (@cnt=0 or @ip_repeat=2) 
BEGIN
	INSERT INTO url_click_log (url_id,ip)
	VALUES(@id,@ip)
UPDATE url SET allclick=allclick+1,todayclick=todayclick+1 WHERE id=@id
END

SET NOCOUNT OFF














GO
/****** Object:  StoredProcedure [dbo].[procUrlByIDSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.04
--创建人：Nick
--说明：select url
--#####################################################
CREATE PROCEDURE [dbo].[procUrlByIDSelect]
(
	@ID INT
)
AS
BEGIN TRY
	SELECT url FROM url WITH(NOLOCK) WHERE id=@ID
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[ProcViInterviewRecordInsert]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.29
--创建人：John
--说明：个人申请进入面试室/企业邀请个人进入面试室
--#####################################################
CREATE PROCEDURE [dbo].[ProcViInterviewRecordInsert]
(
	@viRoomId INT,
	@JobID INT,
	@CvMainID INT,
	@ApplyType TINYINT
)
AS
BEGIN
	INSERT INTO ViInterviewRecord(viRoomId, cvMainID, paMainID, JobId, ApplyDate, ApplyType) 
	SELECT @viRoomId, ID, paMainID, @JobId, GETDATE(), @ApplyType 
	FROM cvMain 
	WHERE ID = @cvMainID
END


GO
/****** Object:  StoredProcedure [dbo].[ProcViInterviewRecordUpdate]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2014.10.29
--创建人：John
--说明：个人进入面试室更新时间
--#####################################################
CREATE PROCEDURE [dbo].[ProcViInterviewRecordUpdate]
(
	@viRoomID INT,
	@cvMainID INT
)
AS
BEGIN
	UPDATE ViInterviewRecord 
	SET LastRefreshTime = GETDATE(), BeginDate = GETDATE() 
	WHERE viroomid = @viRoomID 
	AND cvMainID = @cvMainID 
	AND begindate IS NULL 
	AND ReplyResult = 1
END


GO
/****** Object:  StoredProcedure [dbo].[ProcVIPlanByHomePageSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#########################################
--lambo  2014-5-23
--用于首页和宣传页面 取正在面试的企业 如果数据不够再取有面试计划的企业
--#########################################
CREATE PROCEDURE [dbo].[ProcVIPlanByHomePageSelect] 
(
	@dcProvinceID INT,
	@RecordCount INT
)
AS
BEGIN
	BEGIN TRY
		CREATE TABLE #T(
			VIRoomID INT,
			VIPlanID INT,
			CpID VARCHAR(10),
			CpMainID VARCHAR(10),
			CompanyName NVARCHAR(50),
			JobIDs VARCHAR(50),
			JobNames NVARCHAR(200),
			InterviewDate SMALLDATETIME

		)
		--取@RecordCount条正在面试的企业
		INSERT INTO #T(VIRoomID, CpID, CpMainID, CompanyName)
		SELECT TOP(@RecordCount) a.ID, c.ID, ISNULL(c.SecondID,c.ID), c.Name
		FROM VIRoom a, caMain b, cpMain c 
		WHERE a.caMainID = b.id 
		AND b.cpMainID = c.ID
		AND a.EndDate IS NULL
		AND c.dcProvinceID LIKE LTRIM(STR(@dcProvinceID))+'%'
		AND c.IsLimitLogin<>9
		--如果不够@RecordCount条，从面试计划中补齐 
		DECLARE @CompanyCount INT
		SELECT @CompanyCount = COUNT(*) FROM #T
		
		INSERT INTO #T(VIPlanID, CpID, CpMainID, CompanyName, InterviewDate)
		SELECT TOP(@RecordCount-@CompanyCount) a.ID,  c.ID,ISNULL(c.SecondID,c.ID), c.Name, a.InterviewDate
		FROM VIPlan a, caMain b, cpMain c 
		WHERE a.caMainID = b.id 
		AND b.cpMainID = c.ID
		AND a.InterviewDate > GETDATE()
		AND a.IsCancel = 0
		AND c.dcProvinceID LIKE LTRIM(STR(@dcProvinceID))+'%'
                AND c.IsLimitLogin<>9
		ORDER BY InterviewDate		
		UPDATE a SET 
			JobIDs = STUFF(
			(
				SELECT TOP 3 ','+LTRIM(ISNULL(secondid,id)) 
				FROM Job WITH(NOLOCK)  
				WHERE cpMainID = a.CpID 
				AND Valid = 1
				ORDER BY DisplayNo, CONVERT(VARCHAR(4), dcJobtypeId),ID
				FOR XML PATH('')
			),1,1,'')
			,
			JobNames = STUFF(
			(
				SELECT TOP 3 ','+LTRIM(Name) 
				FROM Job WITH(NOLOCK)  
				WHERE cpMainID = a.CpID 
				AND Valid = 1
				ORDER BY DisplayNo, CONVERT(VARCHAR(4), dcJobtypeId),ID
				FOR XML PATH('')
			),1,1,'')
		FROM #T  a
		SELECT * FROM #T ORDER BY CASE WHEN  VIRoomID IS NULL THEN 1 ELSE 0 END,InterviewDate
		DROP TABLE #T
	END TRY
	BEGIN CATCH
		DROP TABLE #T
	END CATCH
END









GO
/****** Object:  StoredProcedure [dbo].[ProcViPlanByIDSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2014.10.30
--创建人：John
--说明：获取面试计划数据
--#####################################################
CREATE PROCEDURE [dbo].[ProcViPlanByIDSelect]
(
	@ID INT
)
AS
BEGIN
	SELECT * FROM VIPlan WHERE id = @ID
END


GO
/****** Object:  StoredProcedure [dbo].[ProcViPlanByRegionIDSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2014.10.29
--创建人：John
--说明：根据区域位置获取该位置下所有面试计划
--#####################################################
CREATE PROCEDURE [dbo].[ProcViPlanByRegionIDSelect]
(
	@RegionID VARCHAR(10),
	@KeyWords VARCHAR(100)
)
AS
BEGIN
	SELECT TOP 100 a.*,b.Name HrName,b.id caMainID,c.Name cpName,ISNULL(c.SecondID,c.ID) cpMainID,
		STUFF( 
				(
					SELECT TOP 3 ','+LTRIM(ISNULL(secondid,id)) 
					FROM Job WITH(NOLOCK)
					WHERE cpMainID = c.ID 
					AND Valid = 1 
					ORDER BY DisplayNo, CONVERT(VARCHAR(4), dcJobtypeId),ID 
					FOR XML PATH('') 
				),1,1,''
			) JobIDs,
		STUFF( 
				(
					SELECT TOP 3 ','+LTRIM(Name) 
					FROM Job WITH(NOLOCK)
					WHERE cpMainID = c.ID 
					AND Valid = 1 
					ORDER BY DisplayNo, CONVERT(VARCHAR(4), dcJobtypeId),ID 
					FOR XML PATH('') 
				),1,1,''
			) JobNames
	 FROM ViPlan a LEFT JOIN caMain b ON b.ID = a.caMainID LEFT JOIN cpMain c ON c.ID = b.cpMainID 
	 WHERE c.dcProvinceID LIKE @RegionID 
	 AND c.Name LIKE @KeyWords 
	 AND interviewdate > GETDATE()
	 And IsCancel = 0
	 AND c.IsLimitLogin <> 9 
	 ORDER BY interviewdate DESC 
END


GO
/****** Object:  StoredProcedure [dbo].[ProcViPlanInviteInsert]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2014.10.29
--创建人：John
--说明：增加个人预约记录/企业邀请记录
--#####################################################
CREATE PROCEDURE [dbo].[ProcViPlanInviteInsert]
(
	@VIPlanID INT,
	@JobID INT,
	@CvMainID INT,
	@AddType BIT
)
AS
BEGIN
	INSERT INTO ViPlanInviteLog(VIPlanID, JobID, CvMainID, AddType) 
	SELECT @VIPlanID, @JobID, @CvMainID, @AddType 
END

GO
/****** Object:  StoredProcedure [dbo].[ProcViRoomByRegionIDSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.29
--创建人：John
--说明：根据区域位置获取该位置下所有面试室
--#####################################################
CREATE PROCEDURE [dbo].[ProcViRoomByRegionIDSelect]
(
	@RegionID VARCHAR(10),
	@KeyWords VARCHAR(100)
)
AS
BEGIN
	SELECT TOP 100 a.*,b.Name HrName,b.id caMainID,c.Name cpName,IsNULL(c.SecondID,c.ID) cpMainID,
		STUFF( 
				(
					SELECT TOP 3 ','+LTRIM(ISNULL(secondid,id)) 
					FROM Job WITH(NOLOCK)
					WHERE cpMainID = c.ID 
					AND Valid = 1 
					ORDER BY DisplayNo, CONVERT(VARCHAR(4), dcJobtypeId),ID 
					FOR XML PATH('') 
				),1,1,''
			) JobIDs,
		STUFF( 
				(
					SELECT TOP 3 ','+LTRIM(Name) 
					FROM Job WITH(NOLOCK)
					WHERE cpMainID = c.ID 
					AND Valid = 1 
					ORDER BY DisplayNo, CONVERT(VARCHAR(4), dcJobtypeId),ID 
					FOR XML PATH('') 
				),1,1,''
			) JobNames
	 FROM ViRoom a LEFT JOIN caMain b ON b.ID = a.caMainID LEFT JOIN cpMain c ON c.ID = b.cpMainID 
	 WHERE c.dcProvinceID LIKE @RegionID 
	 AND c.Name LIKE @KeyWords 
	 AND EndDate IS NULL 
	 AND c.IsLimitLogin <> 9 
	 ORDER BY BeginDate DESC 
END


GO
/****** Object:  StoredProcedure [dbo].[ProcViRoomInsert]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2014.10.29
--创建人：John
--说明：企业创建房间
--#####################################################
CREATE PROCEDURE [dbo].[ProcViRoomInsert]
(
	@caMainID INT,
	@GUID VARCHAR(20)
)
AS
BEGIN
	INSERT INTO viRoom(caMainID, LastRefreshTime, BeginDate, [GUID]) VALUES(@caMainID, GETDATE(), GETDATE(), @GUID)
END


GO
/****** Object:  StoredProcedure [dbo].[ProcViRoomReplyResultUpdate]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2014.10.30
--创建人：John
--说明：修改邀请的答复状态
--#####################################################
CREATE PROCEDURE [dbo].[ProcViRoomReplyResultUpdate]
(
	@ID INT,
	@result INT,
	@caMainID INT,
	@paMainID INT
)
AS
BEGIN
	DECLARE @SQL VARCHAR(1000)
	SET @SQL = 'UPDATE viinterviewrecord SET ReplyDate = GETDATE(),ReplyResult = ' + CONVERT(VARCHAR(10), @result) + ' WHERE id = ' + CONVERT(VARCHAR(20), @ID)
	IF(@caMainID > 0)
	BEGIN
		SET @SQL = @SQL + ' AND viRoomId IN (SELECT id FROM viroom WHERE camainid = '+ CONVERT(VARCHAR(20), @caMainID) + ')'
	END
	IF(@paMainID > 0)
	BEGIN
		SET @SQL = @SQL + ' AND paMainID = ' + CONVERT(VARCHAR(20), @paMainID)
	END
	EXEC(@SQL)
END


GO
/****** Object:  StoredProcedure [dbo].[procVisitCountLogInsert]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[procVisitCountLogInsert]
AS
SET NOCOUNT ON
BEGIN
	INSERT INTO LogDb..VisitCountLog(IP, VisitCount)
	SELECT IP, COUNT(1) FROM logdb..VisitLog GROUP BY IP HAVING COUNT(1) > 10
	TRUNCATE TABLE LogDb..VisitLog
END
GO
/****** Object:  StoredProcedure [dbo].[procVisitLogInsert]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[procVisitLogInsert]
(
	@IP VARCHAR(31)
)
AS
SET NOCOUNT ON
BEGIN
	INSERT INTO logdb..VisitLog(IP) VALUES(@IP)
END
GO
/****** Object:  StoredProcedure [dbo].[procvrExchangeByRecommendIDSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.31
--创建人：Nick
--说明：得到兑换记录信息
--#####################################################
CREATE PROCEDURE [dbo].[procvrExchangeByRecommendIDSelect]
(
	@RecommendID INT
)
AS
BEGIN TRY
	SELECT a.*,b.GiftName 
	FROM marketDB..cvrExchange a WITH(NOLOCK),marketDB..cvrGift b WITH(NOLOCK) 
	WHERE a.cvrGift=b.ID  
	AND RecommendID=@RecommendID 
	ORDER BY a.ID DESC
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[procvrExchangeSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.31
--创建人：Nick
--说明：得到兑换记录信息
--#####################################################
CREATE PROCEDURE [dbo].[procvrExchangeSelect]
AS
BEGIN TRY
	SELECT TOP 20 a.ApplyTime,b.GiftName,c.Name paName,c.gender,c.ID 
	FROM marketDB..cvrExchange a with(nolock),marketDB..cvrGift b with(nolock),paMain c 
	WHERE a.cvrGift=b.ID 
	AND a.RecommendID=c.id 
	ORDER BY a.ID DESC
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[procvrGiftByIDSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.31
--创建人：Nick
--说明：得到礼品的详细信息
--#####################################################
CREATE PROCEDURE [dbo].[procvrGiftByIDSelect]
(
	@ID INT
)
AS
BEGIN TRY
	SELECT * FROM marketdb..cvrGift WHERE isonline = 1 AND ID = @ID
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[proCvrGiftSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.31
--创建人：Nick
--说明：获取礼品信息
--#####################################################
CREATE PROCEDURE [dbo].[proCvrGiftSelect]
AS
BEGIN TRY
	SELECT * FROM marketdb..cvrGift WHERE isonline = 1 AND Remainder>0 ORDER BY Cost
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[procvrRecommendByIDSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.31
--创建人：Nick
--说明：得到积分查询信息
--#####################################################
CREATE PROCEDURE [dbo].[procvrRecommendByIDSelect]
(
	@ID INT
)
AS
BEGIN TRY
	SELECT b.HasValid,b.mobile,HasReply,ReplyTime,b.DeductReason,p.id,p.name 
	FROM marketDb..cvrRecommend b WITH(NOLOCK),paMain p 
	WHERE b.UserID=p.id 
	AND b.RecommendID=@ID 
	ORDER BY b.id DESC
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[procvrRecommendRankingSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.31
--创建人：Nick
--说明：推荐排行榜
--#####################################################
CREATE PROCEDURE [dbo].[procvrRecommendRankingSelect]
AS
BEGIN TRY
	SELECT TOP 50 a.RecommendID,b.name,a.cnt,(
		SELECT TOP 1 ReplyTime 
		FROM marketdb..cvrRecommend WITH(NOLOCK)  
		WHERE RecommendID=a.RecommendID 
		AND hasvalid = 3 
		AND HasReply=1 
		ORDER BY ReplyTime 
	) ReplyTime,stuff((
		SELECT TOP 4 '，'+y.GiftName  
		FROM marketDB..cvrExchange x WITH(NOLOCK),marketDB..cvrGift y WITH(NOLOCK) 
		WHERE x.cvrGift=y.ID AND x.RecommendID=a.RecommendID  And x.HasVerify =1 
		ORDER BY x.ID DESC for xml path('')),1,1,'') gifts 
	FROM (SELECT TOP 100 RecommendID,count(*) cnt 
		FROM marketdb..cvrRecommend WITH(NOLOCK) 
		WHERE hasvalid = 3 
		AND HasReply=1 
		GROUP BY RecommendID 
		ORDER BY cnt DESC) a,paMain b 
	WHERE a.RecommendID = b.id
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[ProcWebSafePaInfoInsert]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ProcWebSafePaInfoInsert]
AS
BEGIN
	TRUNCATE TABLE ShortDb..WebSafePaInfoLog

	SELECT Id, paMainId, ROW_NUMBER() OVER(PARTITION BY paMainId ORDER BY cvLevel DESC, ID DESC) RowNo
	INTO #t
	FROM cvMain
	WHERE paMainId IN(SELECT Id FROM paMain WHERE AddDate > GETDATE() - 50 AND AddDate < GETDATE() - 10)
	
	DELETE #t WHERE paMainId IN(SELECT User_Id FROM ShortDb..WebSafePaInfo)
 
	INSERT INTO WebSafePaInfoLog(ICP_Code, DATA_TYPE, User_Id, User_Name, User_Password, STATUS, AddDate, Ip_Addr,
		MAC_ADDR, MOBILE_IMEI, BIND_EMAIL, BIND_TEL, CONTACT_TEL, REAL_NAME, SEX, BIRTHDAY, CERTIFICATE_CODE,
		PHOTO_FILE, RESUME_ID, DWELL_CITY, RESIDENCE, LIVE_CITY, JOB_CITY, JOB_POST, BLACKLIST, GRADUATE_SCHOOL,
		GRADUATE_TIME, QUALIFICATION, MAJOR, LAST_COMPANY)
	SELECT '10000013803693', 'JOB', a.ID, a.UserNameLower, a.Password, '新建', a.AddDate, LEFT(a.RegisterIp, 15),
		'', '', a.Email, a.Mobile, a.Mobile, a.Name, a.Gender, a.BIRTHDAY, '',
		'', b.Id, LivePlace, a.AccountPlace, a.GrowPlace, '', '', LEFT(a.HideConditions, 64), '',
		'', '', '', ''
	FROM paMain a, cvMain b
	WHERE a.Id = b.paMainId
	AND b.Id IN(SELECT Id FROM #t)
 
	UPDATE WebSafePaInfoLog SET PhotoId = User_Id WHERE User_Id IN(SELECT paMainId FROM paPhoto)
	UPDATE WebSafePaInfoLog SET PhotoPath = (PhotoId / 100000 + 1) * 100000
	UPDATE WebSafePaInfoLog SET PhotoPath = '000' + PhotoPath WHERE PhotoId < 1000000
	UPDATE WebSafePaInfoLog SET PhotoPath = '00' + PhotoPath WHERE PhotoId BETWEEN 1000000 AND 9999999
	UPDATE WebSafePaInfoLog SET PhotoPath = '0' + PhotoPath WHERE PhotoId > 9999999
	UPDATE WebSafePaInfoLog SET Photo_File = 'http://down.51rc.com/imagefolder/Photo/L' + PhotoPath + '/Processed/'

	UPDATE a
	SET a.Photo_File = 'http://down.51rc.com/imagefolder/Photo/L' + PhotoPath + '/Processed/' + b.PhotoProcessed
	FROM WebSafePaInfoLog a, paPhoto b
	WHERE a.User_Id = b.paMainId

	UPDATE WebSafePaInfoLog SET CREATE_TIME = REPLACE(REPLACE(REPLACE(CONVERT(VARCHAR(19), GETDATE(), 120), '-', ''), ' ', ''), ':', '')
	UPDATE WebSafePaInfoLog
	SET Ip_Addr = (SELECT TOP 1 LEFT(LoginIp, 15) FROM MainDb..paLoginLog b WHERE User_Id = b.paMainId ORDER BY ID DESC)
	WHERE Ip_Addr not LIKE '%.%'

	DELETE WebSafePaInfoLog WHERE Ip_Addr not LIKE '%.%'

	UPDATE WebSafePaInfoLog SET SEX = '男' WHERE Sex = '0'
	UPDATE WebSafePaInfoLog SET SEX = '女' WHERE Sex != '男'
	UPDATE WebSafePaInfoLog SET BirthDay = LEFT(BirthDay, 6) + '15120000'

	SELECT cvMainId, MAX(Id) ID, cvMainId JobId, SPACE(50) Region
	INTO #t1
	FROM MainDb..ExJobApply
	GROUP BY cvMainId

	UPDATE a
	SET a.JobId = b.JobId
	FROM #t1 a, MainDb..ExJobApply b
	WHERE a.Id = b.Id

	UPDATE a SET a.Region = c.Description
	FROM #t1 a, MainDb..Job b, MainDb..dcRegion c
	WHERE a.JobId = b.Id
	AND b.dcRegionId = c.Id

	UPDATE a
	SET a.REGISTER_CITY = b.Region
	FROM WebSafePaInfoLog a, #t1 b
	WHERE a.Resume_Id = b.cvMainId

	UPDATE a
	SET a.DWELL_CITY = b.FullName
	FROM WebSafePaInfoLog a, dcRegion b
	WHERE a.DWELL_CITY = b.Id

	UPDATE a
	SET a.RESIDENCE = b.FullName
	FROM WebSafePaInfoLog a, dcRegion b
	WHERE a.RESIDENCE = b.Id

	UPDATE a
	SET a.LIVE_CITY = b.FullName
	FROM WebSafePaInfoLog a, dcRegion b
	WHERE a.LIVE_CITY = b.Id

	SELECT cvMainId, dcRegionID, ROW_NUMBER() OVER(PARTITION BY cvMainId ORDER BY dcRegionId) RowNo
	INTO #t2
	FROM cvJobPlace
	WHERE cvMainId IN(SELECT Resume_Id FROM WebSafePaInfoLog)

	DELETE FROM #t2 WHERE RowNo > 1

	UPDATE a
	SET a.JOB_CITY = c.FullName
	FROM WebSafePaInfoLog a, #t2 b, dcRegion c
	WHERE a.Resume_Id = b.cvMainId
	AND b.dcRegionId = c.ID

	SELECT cvMainId, dcJobTypeID, ROW_NUMBER() OVER(PARTITION BY cvMainId ORDER BY dcJobTypeID) RowNo
	INTO #t3
	FROM cvJobType
	WHERE cvMainId IN(SELECT Resume_Id FROM WebSafePaInfoLog)

	DELETE FROM #t3 WHERE RowNo > 1

	UPDATE a
	SET a.JOB_Post= c.Description
	FROM WebSafePaInfoLog a, #t3 b, dcJobType c
	WHERE a.Resume_Id = b.cvMainId
	AND b.dcJobTypeID = c.ID

	UPDATE WebSafePaInfoLog SET BlackList = REPLACE(BlackList, '<>', '|') WHERE BlackList  > ''
	UPDATE WebSafePaInfoLog SET BlackList = REPLACE(REPLACE(BlackList, '<', ''), '>', '') WHERE BlackList  > ''

	SELECT cvMainId, GraduateCollage, Graduation, MajorName, Degree, SPACE(10) DegreeText, 
		ROW_NUMBER() OVER(PARTITION BY cvMainId ORDER BY Degree DESC) RowNo
	INTO #t4
	FROM cvEducation
	WHERE cvMainId IN(SELECT Id FROM #t)

	UPDATE #t4 SET DegreeText = (SELECT Description FROM dcEducation WHERE Id = Degree)
	DELETE #t4 WHERE RowNo > 1

	UPDATE a
	SET a.GRADUATE_SCHOOL = b.GraduateCollage,
		a.GRADUATE_TIME = LEFT(Graduation, 4),
		a.QUALIFICATION = b.DegreeText,
		a.Major = b.MajorName
	FROM WebSafePaInfoLog a, #t4 b
	WHERE a.Resume_Id = b.cvMainId

	SELECT cvMainId, CompanyName,
		ROW_NUMBER() OVER(PARTITION BY cvMainId ORDER BY BeginDate DESC) RowNo
	INTO #t5
	FROM cvExperience
	WHERE cvMainId IN(SELECT Id FROM #t)

	DELETE #t5 WHERE RowNo > 1

	UPDATE a
	SET a.LAST_COMPANY = b.CompanyName
	FROM WebSafePaInfoLog a, #t5 b
	WHERE a.Resume_Id = b.cvMainId

	UPDATE WebSafePaInfoLog SET Ip_Addr = LEFT(Ip_Addr, CHARINDEX(',', Ip_Addr) - 1) WHERE Ip_Addr LIKE '%,%'
	UPDATE WebSafePaInfoLog SET Ip_Addr = '101.41.69.195' WHERE Ip_Addr LIKE '%101.41.69.195%'
	UPDATE WebSafePaInfoLog SET Ip_Addr = '58.14.0.0' WHERE Ip_Addr LIKE '%58.14.0.0%'
	UPDATE WebSafePaInfoLog SET Ip_Addr = '117.136.5.11' WHERE Ip_Addr LIKE '辽宁 117.136.5.11'
	UPDATE WebSafePaInfoLog SET Ip_Addr = REPLACE(Ip_Addr, '#', '') WHERE Ip_Addr LIKE '%#%'
 
	UPDATE WebSafePaInfoLog SET Ip1 = LEFT(Ip_Addr, CHARINDEX('.', Ip_Addr) - 1) WHERE CHARINDEX('.', Ip_Addr) > 1
	UPDATE WebSafePaInfoLog SET Ip_Addr = RIGHT(Ip_Addr, LEN(Ip_Addr) - LEN(Ip1) -1) 

	UPDATE WebSafePaInfoLog SET Ip2 = LEFT(Ip_Addr, CHARINDEX('.', Ip_Addr) - 1) WHERE CHARINDEX('.', Ip_Addr) > 1
	UPDATE WebSafePaInfoLog SET Ip_Addr = RIGHT(Ip_Addr, LEN(Ip_Addr) - LEN(Ip2) -1) 
	
	UPDATE WebSafePaInfoLog SET Ip3 = LEFT(Ip_Addr, CHARINDEX('.', Ip_Addr) - 1) WHERE CHARINDEX('.', Ip_Addr) > 1
	UPDATE WebSafePaInfoLog SET Ip_Addr = RIGHT(Ip_Addr, LEN(Ip_Addr) - LEN(Ip3) -1) 

	UPDATE WebSafePaInfolog SET Ip_Addr = '255' WHERE Ip_Addr LIKE '%.%'
	UPDATE WebSafePaInfoLog SET Ip4 = Ip_Addr
	UPDATE WebSafePaInfoLog SET IpINT = Ip1
	UPDATE WebSafePaInfoLog SET Ip_Addr = IpINT * 256 * 256 * 256 + ip2 * 256 * 256 + ip3 * 256 + ip4
	DELETE WebSafePaInfoLog WHERE Ip1 IS NULL
	UPDATE WebSafePaInfoLog SET Ip2 = 0 WHERE Ip2 IS NULL
	UPDATE WebSafePaInfoLog SET Ip3 = 0 WHERE Ip3 IS NULL
	UPDATE WebSafePaInfoLog SET Ip4 = 0 WHERE Ip4 IS NULL
	UPDATE WebSafePaInfoLog SET Ip_Addr = IpINT * 256 * 256 * 256 + ip2 * 256 * 256 + ip3 * 256 + ip4
	WHERE Ip_Addr IS NULL
	DELETE WebSafePaInfoLog WHERE Ip_Addr IS NULL
	DELETE WebSafePaInfoLog WHERE Ip_Addr = '0'
	
	INSERT INTO WebSafePaInfo(ICP_CODE, DATA_TYPE, USER_ID, USER_NAME, USER_PASSWORD, STATUS, CREATE_TIME, 
		IP_ADDR, MAC_ADDR, MOBILE_IMEI, BIND_EMAIL, BIND_TEL, CONTACT_TEL, REAL_NAME, SEX, BIRTHDAY, 
		CERTIFICATE_CODE, PHOTO_FILE, RESUME_ID, REGISTER_CITY, DWELL_CITY, RESIDENCE, LIVE_CITY, JOB_CITY,
		JOB_POST, BLACKLIST, GRADUATE_SCHOOL, GRADUATE_TIME, QUALIFICATION, MAJOR, LAST_COMPANY, AddDate)
	SELECT ICP_CODE, DATA_TYPE, USER_ID, USER_NAME, USER_PASSWORD, STATUS, CREATE_TIME, 
		IP_ADDR, MAC_ADDR, MOBILE_IMEI, BIND_EMAIL, BIND_TEL, CONTACT_TEL, REAL_NAME, SEX, BIRTHDAY, 
		CERTIFICATE_CODE, PHOTO_FILE, RESUME_ID, REGISTER_CITY, DWELL_CITY, RESIDENCE, LIVE_CITY, JOB_CITY,
		JOB_POST, BLACKLIST, GRADUATE_SCHOOL, GRADUATE_TIME, QUALIFICATION, MAJOR, LAST_COMPANY, GETDATE()
	FROM WebSafePaInfoLog
END

GO
/****** Object:  StoredProcedure [dbo].[procWebSiteMonitorByIDUpdate]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE proc [dbo].[procWebSiteMonitorByIDUpdate]
(
	@Id int
)
as
return
GO
/****** Object:  StoredProcedure [dbo].[ProcWebVisitLogInsert]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [dbo].[ProcWebVisitLogInsert]
(
	@VisitId INT,
	@VisitType INT
)
AS
SET NOCOUNT ON
BEGIN
	INSERT INTO WebVisitLog(VisitId, VisitType, AddDate) SELECT @VisitId, @VisitType, GETDATE()
END
GO
/****** Object:  StoredProcedure [dbo].[ProcWenWenProcess]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ProcWenWenProcess]
AS
BEGIN
	UPDATE Marketdb..WenWenAnswer SET AnswerKeyWord='伍亿人才网' WHERE CHARINDEX('伍亿人才网',Answer)>0 AND CheckDate>CONVERT(VARCHAR(10),GETDATE(),120)
	UPDATE Marketdb..WenWenAnswer SET IsLink=1 WHERE CHARINDEX('www.51rc.com',Lower(Answer))>0 AND CheckDate>CONVERT(VARCHAR(10),GETDATE(),120)

	UPDATE a SET AnswerKeyWord=ISNULL(AnswerKeyWord,'')+','+b.SubSiteName FROM Marketdb..WenWenAnswer a,(
	SELECT (SELECT TOP 1 SubSiteName FROM dcSubSite WHERE CHARINDEX(SubSiteName,f.Answer)>0 AND IsMainSite=1) SubSiteName,ID 
	FROM Marketdb..WenWenAnswer f WHERE EXISTS(SELECT 'x' FROM dcSubSite b WHERE CHARINDEX(SubSiteName ,f.Answer)>0 AND IsMainSite=1)
	) b
	WHERE a.ID=b.ID AND CheckDate>CONVERT(VARCHAR(10),GETDATE(),120)

	UPDATE Marketdb..WenWenAnswer SET AnswerKeyWord = RIGHT(AnswerKeyWord,LEN(AnswerKeyWord)-1) WHERE LEN(AnswerKeyWord)>0 AND CheckDate>CONVERT(VARCHAR(10),GETDATE(),120)

	UPDATE a SET IsLink=1 FROM Marketdb..WenWenAnswer a,(
	SELECT (SELECT TOP 1 Replace(SubSiteUrl,'www.','') FROM dcSubSite WHERE CHARINDEX(Replace(SubSiteUrl,'www.',''),f.Answer)>0 AND IsMainSite=1) ProvinceDomain,ID 
	FROM Marketdb..WenWenAnswer f WHERE EXISTS(SELECT 'x' FROM dcSubSite b WHERE CHARINDEX(Replace(SubSiteUrl,'www.','') ,f.Answer)>0)
	) b
	WHERE a.ID=b.ID AND CheckDate>CONVERT(VARCHAR(10),GETDATE(),120)

	UPDATE Marketdb..WenWenAnswer SET IsValid=0 WHERE AnswerKeyWord IS NULL AND CheckDate>CONVERT(VARCHAR(10),GETDATE(),120)

	UPDATE a SET IsValid=0 FROM Marketdb..WenWenAnswer a WHERE 
	NOT EXISTS(SELECT b.a FROM dbo.FnSplit(a.AnswerKeyWord,',') b WHERE b.a IN(
		SELECT d.SubSiteName FROM dbo.FnSplit(a.dcProvinceID,',') c,dcSubSite d WHERE c.a=d.ID
	)) AND CheckDate>CONVERT(VARCHAR(10),GETDATE(),120) AND a.AnswerKeyWord<>'伍亿人才网' AND LEN(a.dcProvinceID)>0

	UPDATE Marketdb..WenWenAnswer SET IsValid=0 WHERE AnswerKeyWord='伍亿人才网' AND LEN(dcProvinceID)>0

	UPDATE Marketdb..WenWenAnswer SET IsValid=0 WHERE
	(SELECT Type FROM WorkDate WITH(NOLOCK) WHERE WorkDate = CONVERT(VARCHAR(8), AnswerDate, 112))=1 
	AND AnswerDate>CONVERT(VARCHAR(10), AnswerDate, 120)+' 7:00' AND AnswerDate<CONVERT(VARCHAR(10), AnswerDate, 120)+' 18:00'
	AND CheckDate>CONVERT(VARCHAR(10),GETDATE(),120) AND LEN(dcProvinceID)>0
END














GO
/****** Object:  StoredProcedure [dbo].[procWishWallByCpMainIDSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[procWishWallByCpMainIDSelect]
(
	@cpMainID INT
)
AS
SET NOCOUNT OFF
BEGIN
	SELECT * FROM ShortDB..WishWall WITH(NOLOCK)
	WHERE cpMainID = @cpMainID
END
SET NOCOUNT ON
GO
/****** Object:  StoredProcedure [dbo].[procWishWallInsert]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[procWishWallInsert]
(
	@cpMainID INT,
	@Content NVARCHAR(30)
)
AS
SET NOCOUNT OFF
BEGIN
	DECLARE @GiftType TINYINT
	SET @GiftType = ROUND((6 * RAND() + 1), 0)
	IF EXISTS(SELECT 'X' FROM ShortDB..WishWall WITH(NOLOCK) WHERE cpMainID = @cpMainID)
		RETURN 0
	INSERT INTO ShortDB..WishWall(cpMainID, WishContent, GiftType) VALUES(@cpMainID, @Content, @GiftType)
	
	IF @GiftType < 4
	BEGIN
		DECLARE @Balance INT, @Coin INT
		SELECT TOP 1 @Balance = Balance FROM cpCoin WHERE cpMainID = @cpMainID ORDER BY ID DESC
		IF @GiftType = 1
			SET @Coin = 10
		ELSE IF @GiftType = 2
			SET @Coin = 20
		ELSE IF @GiftType = 3
			SET @Coin = 30
		SET @Balance = ISNULL(@Balance, 0) + @Coin
		INSERT INTO cpCoin(cpMainID, caOrderID, Coin, Balance, AddDate)
			VALUES(@cpMainID, 0, @Coin, @Balance, GETDATE())
	END
	ELSE
	BEGIN
		DECLARE @Point INT
		IF @GiftType = 4
			SET @Point = 200
		ELSE IF @GiftType = 5
			SET @Point = 500
		ELSE IF @GiftType = 6
			SET @Point = 800
		ELSE IF @GiftType = 7
			SET @Point = 1000
		INSERT INTO cpPoint(cpMainID, ChangeID, Point, Remark, LastModifyDate)
			VALUES(@cpMainID, 18, @Point, '送祝福得积分', GETDATE())
	END
	RETURN @GiftType
END
SET NOCOUNT ON
GO
/****** Object:  StoredProcedure [dbo].[procWishWallSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[procWishWallSelect]
AS
SET NOCOUNT OFF
BEGIN
	SELECT TOP 60 a.*, b.Name CompanyName FROM ShortDB..WishWall a WITH(NOLOCK), cpMain b WITH(NOLOCK)
	WHERE a.cpMainID = b.ID AND a.Valid = 1 ORDER BY a.ID DESC
END
SET NOCOUNT ON
GO
/****** Object:  StoredProcedure [dbo].[procWishWallUpdate]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[procWishWallUpdate]
(
	@PassId VARCHAR(MAX),
	@NoPassId VARCHAR(MAX)
)
AS
SET NOCOUNT ON
BEGIN
	SET @PassId = dbo.SafeSQL(@PassId)
	SET @NoPassId = dbo.SafeSQL(@NoPassId)
	UPDATE shortdb..WishWall SET Valid = 1
	WHERE ID IN(SELECT a FROM dbo.FnSplit(@PassId, ','))

	UPDATE shortdb..WishWall SET Valid = 0
	WHERE ID IN(SELECT a FROM dbo.FnSplit(@NoPassId, ','))
END
GO
/****** Object:  StoredProcedure [dbo].[procWxAttenTionDelete]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.01.26
--创建人：Nick
--说明：删除WxAttenTion临时表
--#####################################################
CREATE PROCEDURE [dbo].[procWxAttenTionDelete]
AS
BEGIN
	DELETE FROM WxAttenTion
END 

GO
/****** Object:  StoredProcedure [dbo].[procWxAttenTionUpdate]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.01.26
--创建人：Nick
--说明：更新WxAttenTion临时表
--#####################################################
CREATE PROCEDURE [dbo].[procWxAttenTionUpdate]
(
	@WxServiceNo INT,
	@OpenIDs VARCHAR(MAX)
)
AS
BEGIN
	INSERT INTO WxAttention
	SELECT @WxServiceNo,*,GETDATE() FROM dbo.fnsplit(@OpenIDs,',')
END 

GO
/****** Object:  StoredProcedure [dbo].[procWxFansByCaMainIDSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2016.4.15
--创建人：Lucifer
--说明：查询企业账户是否已绑定微信
--#####################################################
CREATE PROCEDURE [dbo].[procWxFansByCaMainIDSelect]
(
	@CaMainID INT
)
AS
BEGIN
	SET NOCOUNT ON
	SELECT * FROM MainDB..WxFans WITH(NOLOCK) WHERE CaMainID = @CaMainID AND caBindCancelDate IS NULL
	SET NOCOUNT OFF
END

GO
/****** Object:  StoredProcedure [dbo].[procWxFansByPaMainIDSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.2.2
--创建人：John
--说明：查询个人账户是否已绑定微信
--#####################################################
CREATE PROCEDURE [dbo].[procWxFansByPaMainIDSelect]
(
	@PaMainID INT
)
AS
BEGIN
	SET NOCOUNT ON
	SELECT * FROM MainDB..WxFans WHERE PaMainID = @PaMainID AND Status = 2
	SET NOCOUNT OFF
END

GO
/****** Object:  StoredProcedure [dbo].[procWxFunsByStatusUpdate]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.01.26
--创建人：Nick
--说明：更新用户关注状态
--#####################################################
CREATE PROCEDURE [dbo].[procWxFunsByStatusUpdate]
AS
BEGIN
	--将取消关注的用户加入操作日志
	INSERT INTO WxMessageReceive 
	SELECT ID, GETDATE(), '取消关注', 6 
	FROM WxFans 
	WHERE Status <> 0 AND  OpenID NOT IN (
		SELECT Rtrim(Ltrim(OpenID)) FROM WxAttenTion
	)
	
	--更新用户的关注状态
	SELECT Status, OpenId INTO #t FROM WxFans WHERE Status <> 0 
	DELETE #t WHERE OpenID In(SELECT Rtrim(Ltrim(OpenID)) FROM WxAttenTion) AND Status <> 0 

	UPDATE WxFans SET Status=0, AttentionCancelDate = GETDATE() 
	WHERE OpenID In(SELECT OpenID FROM #t) AND Status <> 0 

	--UPDATE WxFans SET Status=0, AttentionCancelDate = GETDATE() 
	--WHERE OpenID Not In(SELECT Rtrim(Ltrim(OpenID)) FROM WxAttenTion) 
	--AND Status <> 0 

	--更新用户的关注状态
	--UPDATE WxFans SET Status=1,AttentionDate=GETDATE() WHERE OpenID In(SELECT Ltrim(OpenID) FROM WxAttenTion) AND Status = 0
	UPDATE a SET a.Status=1,a.AttentionDate=GETDATE(),a.WxServiceNoID = b.WxServiceNoID
	FROM  WxFans a,WxAttenTion b
	WHERE a.OpenID = Rtrim(Ltrim(b.OpenID))
	AND a.Status = 0
	

	--将关注用户插入数据表
	INSERT INTO WxFans (OpenID,AttentionDate,Status,WxServiceNoID)
	SELECT Ltrim(OpenID),getdate(),1,WxServiceNoID 
	FROM WxAttenTion 
	WHERE Rtrim(Ltrim(OpenID)) NOT IN (SELECT OpenID FROM WxFans)
END 

GO
/****** Object:  StoredProcedure [dbo].[procWXLocationByOpenIDSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.11
--创建人：NICK
--说明：绑定微信的openid
--#####################################################
CREATE PROCEDURE [dbo].[procWXLocationByOpenIDSelect]
(
	@OpenID VARCHAR(100)
)
AS
BEGIN
	SELECT TOP 1 * 
	FROM WXLocation 
	WHERE openid=@OpenID 
	AND adddate>DATEADD(hour,-1,getdate()) 
	ORDER BY id DESC
END


GO
/****** Object:  StoredProcedure [dbo].[procWXLocationInsert]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.11
--创建人：NICK
--说明：增加关注着的微信位置
--#####################################################
CREATE PROCEDURE [dbo].[procWXLocationInsert]
(
	@OpenId VARCHAR(100),
	@lng VARCHAR(20),
	@lat VARCHAR(20)
)
AS
BEGIN
	IF NOT EXISTS(SELECT 'x' FROM WXLocation WITH(NOLOCK) WHERE OpenId = @OpenId AND AddDate > DATEADD(MINUTE, -120, GETDATE()))
		INSERT INTO WXLocation(OpenId, lng, lat) SELECT @OpenId, @lng, @lat

	RETURN 1
END


GO
/****** Object:  StoredProcedure [dbo].[procwxMessageByFromUserNameSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.10
--创建人：Nick
--说明：获取wxMessage的内容
--#####################################################
CREATE PROCEDURE [dbo].[procwxMessageByFromUserNameSelect]
(
	@FromUserName VARCHAR(100),
	@type VARCHAR(10)
)
AS
BEGIN
	IF @type = '11'
	BEGIN
		SELECT * FROM wxMessage WITH(NOLOCK) WHERE FromUserName=@FromUserName and Content ='推荐职位'
	END
	ELSE
	BEGIN
		SELECT * FROM wxMessage WITH(NOLOCK) WHERE FromUserName=@FromUserName and Content <>'推荐职位'
	END
END


GO
/****** Object:  StoredProcedure [dbo].[procwxMessageByNameSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.10
--创建人：Nick
--说明：获取wxMessage的内容
--#####################################################
CREATE PROCEDURE [dbo].[procwxMessageByNameSelect]
(
	@FromUserName VARCHAR(100)
)
AS
BEGIN
	SELECT * FROM wxMessage WITH(NOLOCK) WHERE FromUserName=@FromUserName
END


GO
/****** Object:  StoredProcedure [dbo].[procWxMessageReceiveInsert]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.01.30
--创建人：Nick
--说明：记录粉丝操作日志
--修改harry2017-4-17 增加企业绑定，取消时200积分
--#####################################################
CREATE PROCEDURE [dbo].[procWxMessageReceiveInsert]
(
    @OpenID VARCHAR(100),
    @LogType INT,
    @ProvinceID INT,
    @Message VARCHAR(200),
    @PaMainID INT
)
AS
SET NOCOUNT ON
BEGIN
    DECLARE @WxServiceNoID INT
    --根据省份得到服务号id
    SELECT TOP 1 @WxServiceNoID = ID FROM WxServiceNO WHERE ProvinceID = @ProvinceID

    DECLARE @WxFansID INT
    SELECT TOP 1 @WxFansID = ID FROM WxFans WHERE OpenID = @OpenID
    IF @WxFansID IS NULL
    BEGIN
        --插入粉丝表
        INSERT INTO WxFans(OpenID, AttentionDate, Status, WxServiceNoID, paMainId)
        VALUES (@OpenID,GETDATE(),1,@WxServiceNoID, Null)
        SELECT @WxFansID = @@IDENTITY
    END
    
    DECLARE @Content VARCHAR(50)
    IF @LogType = 1 --关注
    BEGIN
        --更新粉丝表
        UPDATE WxFans SET Status = 1,AttentionDate = GETDATE(),WxServiceNoID = @WxServiceNoID 
        WHERE ID = @WxFansID        

        SET @Content = '关注'
    END
    ELSE IF @LogType = 2 --取消关注
    BEGIN
        --更新粉丝表
        UPDATE WxFans SET Status = 0,AttentionCancelDate=GETDATE() WHERE ID = @WxFansID

        --删除 palogincontact
        DELETE FROM PaLoginContact where OpenID = @OpenID AND ContactType=4

        SET @Content = '取消关注'
    END
    ELSE IF @LogType = 3 --发送文本
    BEGIN
        --更新粉丝表最后发送消息
        UPDATE WxFans SET LastSendMessage = @Message WHERE ID = @WxFansID
        SET @Content = '发送文本'
    END
    ELSE IF @LogType = 4 --定位
    BEGIN
        SET @Content = '发送地理位置'
    END
    ELSE IF @LogType = 5 --菜单
    BEGIN
        SET @Content = '点击菜单'
    END
    ELSE IF @LogType = 6 --点击链接
    BEGIN
        SET @Content = '点击链接'
    END
    ELSE IF @LogType = 7 
    BEGIN
        --更新粉丝表
        IF @PaMainID = 0
            UPDATE WxFans SET Status = 2, PaMainID = NULL WHERE ID = @WxFansID
        ELSE
            UPDATE WxFans SET Status = 2, PaMainID = @PaMainID WHERE ID = @WxFansID
        SET @Content = '绑定个人账号'
    END
    ELSE IF @LogType = 8 
    BEGIN
        --更新粉丝表
        UPDATE WxFans SET Status = 1 WHERE ID = @WxFansID
        
        --删除 palogincontact
        DELETE FROM PaLoginContact where OpenID =@OpenID AND ContactType=4
        
        SET @Content = '取消绑定个人账号'
    END
    ELSE IF @LogType = 10 
    BEGIN
        SET @Content = '发送语音'
    END
    ELSE IF @LogType = 11 
    BEGIN
        SET @Content = '发送视频'
    END
    ELSE IF @LogType = 12 
    BEGIN
        SET @Content = '发送图片'
    END
    ELSE IF @LogType = 13 
    BEGIN
        SET @Content = '扫描二维码'
    END
    ELSE IF @LogType = 14 
    BEGIN
        --更新粉丝表
        UPDATE WxFans SET caMainID = @PaMainID, caBindCancelDate = NULL WHERE ID = @WxFansID
        SET @Content = '绑定企业账号'
        --插入积分200
        DECLARE @cpMainid1 INT 
        select top 1 @cpMainid1=cpMainID from camain where id=@PaMainID
	INSERT INTO cpPoint (cpMainID,ChangeID,Point,LastModifyDate) VALUES(@cpMainid1 ,21,200,GETDATE())
    END
    ELSE IF @LogType = 15 
    BEGIN
        --更新粉丝表
        UPDATE WxFans SET caBindCancelDate = GETDATE() WHERE ID = @WxFansID
        --删除 palogincontact
        DELETE FROM PaLoginContact where OpenID =@OpenID AND ContactType=4 
        SET @Content = '取消绑定企业账号'
		--删除积分200
		DECLARE @cpMainid2 INT 
        select top 1 @cpMainid2=cpMainID from camain where id=@PaMainID
		INSERT INTO cpPoint (cpMainID,ChangeID,Point,LastModifyDate) VALUES(@cpMainid2,22,-200,GETDATE())
    END
    --插入日志表
    IF NOT EXISTS(SELECT 'x' FROM WxMessageReceive WITH(NOLOCK) WHERE AddDate > CONVERT(VARCHAR(10), GETDATE(), 120) AND WxFansId = @WxFansId) OR @Message > ''
        INSERT INTO WxMessageReceive VALUES(@WxFansID, GETDATE(), @Message, @LogType)
END
GO
/****** Object:  StoredProcedure [dbo].[procWxMessageSend2ByCaJobCvMatchInsert]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
------------------------------------------
---创建人：Peter
---创建时间：2016-10-19
---企业简历精确匹配的微信推送计划任务
-----------------------------------------
CREATE PROCEDURE [dbo].[procWxMessageSend2ByCaJobCvMatchInsert]
AS
SET NOCOUNT ON
BEGIN
	IF DATEPART(HOUR, GETDATE()) < 10
		RETURN
	IF DATEPART(HOUR, GETDATE()) > 11
		RETURN

	SELECT TOP 5000 b.caMainID,c.cpMainID
	INTO #T
	FROM caJobCvMatch a WITH(NOLOCK) 
	LEFT JOIN JobPublish b WITH(NOLOCK) ON b.ID = a.JobID 
	LEFT JOIN CaMain c WITH(NOLOCK) ON b.caMainID = c.ID
	WHERE a.WxPushDate IS NULL
	AND b.Valid = 1
	AND a.AddDate > CONVERT(VARCHAR(10), GETDATE(), 120)
	GROUP BY b.caMainID ,c.cpMainID

	INSERT WxMessageSend2(Templatetype, WxFansID, PaMainId, MainTableId, CpMainID, CvMainID, JobId, CaMainId, AddDate)
	SELECT 22, b.Id wxFansId, NULL, a.caMainID, a.cpMainID, NULL, NULL, a.caMainID, GETDATE()
	FROM #T a, wxFans b
	WHERE a.caMainID = b.caMainID
	--AND b.Status > 0
	AND caBindCancelDate IS NULL

	UPDATE caJobCvMatch 
	SET WxPushDate = GETDATE() 
	WHERE JobID IN(
		SELECT ID 
		FROM JobPublish WITH(NOLOCK)
		WHERE caMainID IN (SELECT caMainID FROM #T)
		)

	DROP TABLE #T
END

GO
/****** Object:  StoredProcedure [dbo].[ProcWxMessageSend2BySendSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ProcWxMessageSend2BySendSelect]
AS
BEGIN
	SELECT TOP 500 a.id, a.messagetext, a.ReturnResult, a.ErrorNumber, c.Token, e.ProvinceId, e.AppID, e.AppSecret
	FROM wxMessageSend2 a WITH(NOLOCK),
		dcWxtoken c WITH(NOLOCK), wxFans d, wxServiceNo e
	WHERE ISNULL(a.errornumber, 0) < 3
	AND a.SendDate IS NULL
	AND MessageText > ''
	AND a.wxFansId = d.Id
	AND d.wxServiceNoId = e.Id
	AND e.ProvinceId = c.dcProvinceId
--and a.templatetype <> 19
	ORDER BY a.Id DESC
END
GO
/****** Object:  StoredProcedure [dbo].[procWxMessageSendByChatOnlineInsert]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--功能：个人未读留言发送微信提醒
--创建人：harry
--2015-9-10
CREATE PROCEDURE [dbo].[procWxMessageSendByChatOnlineInsert]
AS
BEGIN
	--取出2分钟前未多的数据
	SELECT MAX(ID) ID, cvMainId, caMainId INTO #T FROM ChatOnline 
	WHERE ID > ISNULL((SELECT MAX(ChatOnineId) ID FROM wxChatOnlineTemp), 0)
	AND ID IN(SELECT DISTINCT ChatOnlineID
		FROM ChatOnlinelog 
		WHERE SenderType = 1 --企业给个人发送
		AND IsViewed = 0 --未查看
		AND AddDate BETWEEN DATEADD(MINUTE, -30, GETDATE())
		AND DATEADD(MINUTE, -5, GETDATE()))
	AND ID NOT IN(SELECT ChatOnineId FROM wxChatOnlineTemp) 
	GROUP BY cvMainId, caMainId

	--将chatonlineid 或（pamainid, camainid）不存在于wxchatonlinetemp的数据插入wxchatonlinetemp
	INSERT wxChatOnlineTemp(ChatOnineId, paMainId, cvMainid, caMainId)
	SELECT a.ID, b.PaMainId, a.cvMainId, a.caMainId
	FROM #T a, cvMain b, wxFans c
	WHERE a.cvMainId = b.Id
	AND NOT EXISTS(SELECT 'X' FROM wxChatOnlineTemp WHERE paMainId = b.PaMainId AND caMainId = a.caMainId)
	AND b.paMainId = c.PamainId 
	AND c.status>0
	
	--取出未发送的数据
	SELECT a.*, b.Id AS WxFansId 
	INTO #T1 
	FROM wxChatOnlineTemp a, wxFans b 
	WHERE a.IsSend = 0 
	AND a.paMainId = b.paMainId
	
	--插入WxMessageSend2
	INSERT WxMessageSend2(Templatetype, WxFansID, PaMainId, cpMainId, AddDate)
	SELECT 4, a.WxFansId, a.PamainId, b.cpMainId, GETDATE() FROM #T1 a, caMain b WHERE a.caMainId = b.Id 
	--SELECT 4, 178509, 25681483, 371108, GETDATE() FROM #T1 a, caMain b WHERE a.caMainId = b.Id 
	
	--更新wxchatonlinetemp
	UPDATE wxChatOnlineTemp 
	SET IsSend = 1 
	WHERE IsSend = 0
END

GO
/****** Object:  StoredProcedure [dbo].[procWxMessageSendByMessageUpdate]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/***********************
---微信json字符串组合--
---Harry 2015-8-27-----
---修改harry 271行：联系方式是否隐藏的处理
---修改harry 2018-4-10增加23校园招聘会审核
**********************/
CREATE PROCEDURE [dbo].[procWxMessageSendByMessageUpdate]
AS
SET NOCOUNT ON
BEGIN
	SET NOCOUNT OFF
	DECLARE @ParaValue VARCHAR(2000), 
		@JsonMessage VARCHAR(1000), 	--json字符串　
		@PaName VARCHAR(50), 
		@JobName VARCHAR(50), 
		@CpMainId INT, 
		@CompanyName NVARCHAR(100), 
		@InterviewDate NVARCHAR(100), 
		@InterviewPlace NVARCHAR(100), 
		@LinkMan NVARCHAR(25), 
		@Telephone VARCHAR(25), 
		@Url VARCHAR(1000), 
		@MinId INT

	UPDATE wxmessagesend2
	SET ErrorNumber = 9 
	WHERE AddDate > DATEADD(MINUTE, -10, GETDATE())
	AND WxFansId IN(
		SELECT Id FROM WxFans WITH(NOLOCK) WHERE WxServiceNoId IN(SELECT ID FROM WxServiceNo WITH(NOLOCK) WHERE Status = 2)
	)
	AND ErrorNumber < 3

	UPDATE wxmessagesend2
	SET ErrorNumber = 9 
	WHERE Id IN(SELECT ID FROM (SELECT Id, ROW_NUMBER() OVER(PARTITION BY PaMainId, TemplateType ORDER BY Id) RowNo
		FROM wxMessagesend2 WITH(NOLOCK)
		WHERE AddDate > CONVERT(VARCHAR(10), GETDATE(), 120)) a
		WHERE RowNo > 2
		AND TemplateType NOT IN(20, 22,23))
	AND ErrorNumber < 3
	AND Templatetype > 1

	SELECT TOP 1 @MinId = ID FROM wxMessagesend2 WITH(NOLOCK)
	WHERE Templatetype <> 8
	AND (JobID IS NULL OR caMainId IS NULL OR cpMainId IS NULL OR cpMainId = 0)
	AND AddDate > GETDATE() - 0.5
	ORDER BY ID

	IF @MinId > 0
	BEGIN
		UPDATE a SET a.caMainId = b.caMainId
		FROM wxMessagesend2 a WITH(NOLOCK), Job b WITH(NOLOCK)
		WHERE a.Jobid = b.Id
		AND a.caMainId IS NULL
		AND a.JobID > 0
		AND a.Id > @MinID

		UPDATE a SET a.cpMainId = b.cpMainId
		FROM WxMessageSend2 a WITH(NOLOCK), caMain b WITH(NOLOCK)
		WHERE a.caMainid = b.Id
		AND a.caMainId > 0
		AND ISNULL(a.cpMainId, 0) = 0
		AND a.Id > @MinID
		--AND a.TemplateType <> 20
	END

	--UPDATE WxMessageSend2 SET wxFansId = 178509 WHERE MessageText IS NULL 
	--UPDATE WxMessageSend2 SET wxFansId = 178509, MessageText = null --WHERE MessageText IS NULL 
	--取出待发送的数据
	SELECT a.*, b.Name paName, c.OpenId, c.WxServiceNoID, d.ProvinceDomain, d.WebsiteName INTO #T1 
	FROM WxMessageSend2 a WITH(NOLOCK)
	LEFT JOIN PaMain b WITH(NOLOCK) ON a.PaMainID = b.ID
	LEFT JOIN WxFans c WITH(NOLOCK) ON a.WxFansID = c.ID
	INNER JOIN WxServiceNo e WITH(NOLOCK) ON c.WxServiceNoId = e.Id
	INNER JOIN dcprovince d WITH(NOLOCK) ON d.id = e.ProvinceID
	WHERE a.MessageText IS NULL
	AND ErrorNumber < 3
	AND a.AddDate > DATEADD(MINUTE, - 10, GETDATE())

	IF @@RowCount = 0
		RETURN

	--------面试通知开始------ 1  
	SELECT a.*, b.[NO] AS WxTemplateNo , c.InterviewDate, c.InterViewPlace, c.LinkMan, c.Telephone, d.Name jobName, 
		d.dcSalaryID, e.Name CompanyName, SPACE(1000) ParaValue, SPACE(200) Url, SPACE(1000) JsonMessage
	INTO #T01
	FROM #T1 a, WxTemplateNo b WITH(NOLOCK), Exinterview c WITH(NOLOCK), Job d WITH(NOLOCK), CpMain e WITH(NOLOCK)
	WHERE a.Templatetype = 1 AND a.WxServiceNoID = b.WxServiceNoID AND b.WxTemplateId = 1 AND a.MainTableId = c.Id AND a.JobID = d.ID AND a.cpMainId = e.id--面试通知
	IF @@RowCount > 0
	BEGIN
		--插入参数数据
		SET @ParaValue = ''
		SELECT @ParaValue = @ParaValue + CASE WHEN @ParaValue > '' THEN ', ' ELSE '' END + ' "' + ParaName + '":{    "value":"' + ParaValue + '",    "color":"' + ParaColor + '"}' 
		FROM WxTemplatePara WITH(NOLOCK) WHERE WxTemplateID = 1 ORDER BY ID
		UPDATE #T01 SET ParaValue = @ParaValue			
		 
		UPDATE #T01 SET ParaValue = REPLACE(ParaValue, '#PaName#', PaName)
		UPDATE #T01 SET ParaValue = REPLACE(ParaValue, '#JobName#', JobName)
		UPDATE #T01 SET ParaValue = REPLACE(ParaValue, '#CompanyName#', CompanyName)	
		UPDATE #T01 SET ParaValue = REPLACE(ParaValue, '#InterviewDate#', CONVERT(varchar, InterviewDate, 120 ))
		UPDATE #T01 SET ParaValue = REPLACE(ParaValue, '#InterViewPlace#', InterViewPlace)
		UPDATE #T01 SET ParaValue = REPLACE(ParaValue, '#LinkMan#', LinkMan)
		UPDATE #T01 SET ParaValue = REPLACE(ParaValue, '#Telephone#', Telephone)
		UPDATE #T01 SET ParaValue = REPLACE(ParaValue, '#WebsiteName#', WebsiteName)
		UPDATE #T01 SET Url = 'http://m.' + ProvinceDomain + '/library/WechatOauthPaLogin?opid=' + OpenId + '&urlfile=/personal/jm/InterViewList'
		UPDATE #T01 SET	JsonMessage = '{"touser":"' + OpenId + '", "template_id":"' + WxTemplateNo + '", "url":"' + Url + '", "topcolor":"#FF0000", "data":{' + ParaValue + '}}'
	    --更新wxmessagesend中的message
	    UPDATE WxMessageSend2 
	    SET MessageText = a.JsonMessage FROM #T01 a WHERE a.id = WxMessageSend2.id  
	END
	--------面试通知结束------
	
	
	------应聘邀请提醒开始---- 2
	SELECT a.*, b.[NO] AS WxTemplateNo, d.Name jobName, d.dcSalaryID, c.Name CompanyName, e.FullName, 
		f.Adddate AS mainAddDate, SPACE(1000) ParaValue, SPACE(200) Url, SPACE(1000) JsonMessage
	INTO #T02
	FROM #T1 a, WxTemplateNo b WITH(NOLOCK), CpMain c WITH(NOLOCK), Job d WITH(NOLOCK), dcRegion e WITH(NOLOCK), cacvintention f WITH(NOLOCK)
	WHERE a.Templatetype = 2 
	AND a.WxServiceNoID = b.WxServiceNoID 
	AND b.WxTemplateId = 2 
	AND a.cpMainId = c.id 
	AND a.JobID = d.ID 
	AND d.dcRegionId = e.id
	AND f.id = a.MainTableId --应聘邀请
	IF @@RowCount > 0
	BEGIN
		--插入参数数据
		SELECT @ParaValue = ''
		SELECT @ParaValue = @ParaValue + CASE WHEN @ParaValue > '' THEN ', ' ELSE '' END + ' "' + ParaName + '":{    "value":"' + ParaValue + '",    "color":"' + ParaColor + '"}' FROM WxTemplatePara WITH(NOLOCK) WHERE WxTemplateID = 2 ORDER BY ID
		UPDATE #T02 SET ParaValue = @ParaValue
		 
		UPDATE #T02 SET ParaValue = REPLACE(ParaValue, '#PaName#', PaName)
		UPDATE #T02 SET ParaValue = REPLACE(ParaValue, '#Salary#', (SELECT [Description] FROM dcsalary WITH(NOLOCK) WHERE ID = dcSalaryID))
		UPDATE #T02 SET ParaValue = REPLACE(ParaValue, '#JobName#', JobName)	
		UPDATE #T02 SET ParaValue = REPLACE(ParaValue, '#companyname#', CompanyName)
		UPDATE #T02 SET ParaValue = REPLACE(ParaValue, '#address#', FullName)
		UPDATE #T02 SET ParaValue = REPLACE(ParaValue, '#adddate#', CONVERT(varchar, mainAddDate, 120)) 
		UPDATE #T02 SET ParaValue = REPLACE(ParaValue, '#WebsiteName#', WebsiteName)
		UPDATE #T02 SET Url = 'http://m.' + ProvinceDomain + '/library/WechatOauthPaLogin?opid=' + OpenId + '&urlfile=/personal/jm/CvIntention'
		UPDATE #T02 SET	JsonMessage = '{"touser":"' + OpenId + '", "template_id":"' + WxTemplateNo + '", "url":"' + Url + '", "topcolor":"#FF0000", "data":{' + ParaValue + '}}'
		--更新wxmessagesend中的message
		UPDATE WxMessageSend2 
		SET  MessageText = a.JsonMessage FROM #T02 a WHERE a.id = WxMessageSend2.id  
	END
	------应聘邀请提醒结束----	
	
	------收藏简历通知开始---- 3
	SELECT a.*, b.[NO] AS WxTemplateNo, c.Name jobName, d.Name CompanyName, SPACE(1000) ParaValue, SPACE(200) Url, SPACE(1000) JsonMessage
	INTO #T03
	FROM #T1 a, WxTemplateNo b WITH(NOLOCK), Job c WITH(NOLOCK), CpMain d WITH(NOLOCK)
	WHERE a.Templatetype = 3 AND a.WxServiceNoID = b.WxServiceNoID AND b.WxTemplateId = 3 AND a.JobID = c.ID AND a.cpMainId = d.id--简历收藏通知
	IF @@RowCount > 0
	BEGIN
		--插入参数数据
		SELECT @ParaValue = ''
		SELECT @ParaValue = @ParaValue + CASE WHEN @ParaValue > '' THEN ', ' ELSE '' END + ' "' + ParaName + '":{    "value":"' + ParaValue + '",    "color":"' + ParaColor + '"}' FROM WxTemplatePara WITH(NOLOCK) WHERE WxTemplateID = 3 ORDER BY ID
		UPDATE #T03 SET ParaValue = @ParaValue		
		 
		UPDATE #T03 SET ParaValue = REPLACE(ParaValue, '#PaName#', PaName) 
		UPDATE #T03 SET ParaValue = REPLACE(ParaValue, '#CompanyName#', CompanyName)	 
		UPDATE #T03 SET ParaValue = REPLACE(ParaValue, '#JobName#', JobName)	
		UPDATE #T03 SET ParaValue = REPLACE(ParaValue, '#WebsiteName#', WebsiteName)
		UPDATE #T03 SET Url = 'http://m.' + ProvinceDomain + '/library/WechatOauthPaLogin?opid=' + OpenId + '&urlfile=/Personal/jv/CompanyDetail?cpmainid=' + CONVERT(VARCHAR(30), CpMainId)
		UPDATE #T03 SET	JsonMessage = '{"touser":"' + OpenId + '", "template_id":"' + WxTemplateNo + '", "url":"' + Url + '", "topcolor":"#FF0000", "data":{' + ParaValue + '}}'
		--更新wxmessagesend中的message
		UPDATE WxMessageSend2 
		SET MessageText = a.JsonMessage FROM #T03 a WHERE a.id = WxMessageSend2.id   
	END
	------收藏简历通知结束----	
	
	-----企业留言开始----4
	SELECT a.*, b.[NO] AS WxTemplateNo, c.Name CompanyName, SPACE(1000) ParaValue, SPACE(200) Url, SPACE(1000) JsonMessage 
	INTO #T04
	FROM #T1 a, WxTemplateNo b WITH(NOLOCK), CpMain c WITH(NOLOCK)
	WHERE a.Templatetype = 4 AND a.WxServiceNoID = b.WxServiceNoID AND b.WxTemplateId = 4 AND a.cpMainId = c.id
	IF @@RowCount > 0
	BEGIN
	--插入参数数据
		SELECT @ParaValue = ''
		SELECT @ParaValue = @ParaValue + CASE WHEN @ParaValue > '' THEN ', ' ELSE '' END + ' "' + ParaName + '":{    "value":"' + ParaValue + '",    "color":"' + ParaColor + '"}' FROM WxTemplatePara WITH(NOLOCK) WHERE WxTemplateID = 4 ORDER BY ID
		UPDATE #T04 SET ParaValue = @ParaValue 
		UPDATE #T04 SET ParaValue = REPLACE(ParaValue, '#PaName#', PaName)
		UPDATE #T04 SET ParaValue = REPLACE(ParaValue, '#CompanyName#', CompanyName)
		UPDATE #T04 SET ParaValue = REPLACE(ParaValue, '#WebsiteName#', WebsiteName)
		UPDATE #T04 SET Url = 'http://m.' + ProvinceDomain + '/library/WechatOauthPaLogin?opid=' + OpenId + '&urlfile=/chatonline/palist'
		UPDATE #T04 SET	JsonMessage = '{"touser":"' + OpenId + '", "template_id":"' + WxTemplateNo + '", "url":"' + Url + '", "topcolor":"#FF0000", "data":{' + ParaValue + '}}'
		--更新wxmessagesend中的message
		UPDATE WxMessageSend2
		SET MessageText = a.JsonMessage FROM #T04 a WHERE a.id = WxMessageSend2.id
	END
	-----企业留言结束----
	------企业浏览开始----5
	SELECT a.*, b.[NO] AS WxTemplateNo, c.Name CompanyName, SPACE(1000) ParaValue, SPACE(200) Url, SPACE(1000) JsonMessage
	INTO #T05
	FROM #T1 a, WxTemplateNo b WITH(NOLOCK), CpMain c WITH(NOLOCK)
	WHERE a.Templatetype = 5 AND a.WxServiceNoID = b.WxServiceNoID AND b.WxTemplateId = 5 AND a.cpMainId = c.id
	IF @@RowCount > 0
	BEGIN
		--插入参数数据
		SELECT @ParaValue = ''
		SELECT @ParaValue = @ParaValue + CASE WHEN @ParaValue > '' THEN ', ' ELSE '' END + ' "' + ParaName + '":{    "value":"' + ParaValue + '",    "color":"' + ParaColor + '"}' FROM WxTemplatePara WITH(NOLOCK) WHERE WxTemplateID = 5 ORDER BY ID
		UPDATE #T05 SET ParaValue = @ParaValue	
		 
		UPDATE #T05 SET ParaValue = REPLACE(ParaValue, '#PaName#', PaName) 
		UPDATE #T05 SET ParaValue = REPLACE(ParaValue, '#CompanyName#', CompanyName) 
		UPDATE #T05 SET ParaValue = REPLACE(ParaValue, '#WebsiteName#', WebsiteName)
		UPDATE #T05 SET Url = 'http://m.' + ProvinceDomain + '/library/WechatOauthPaLogin?opid=' + OpenId + '&urlfile=/personal/jm/CpAttentionList'
		UPDATE #T05 SET	JsonMessage = '{"touser":"' + OpenId + '", "template_id":"' + WxTemplateNo + '", "url":"' + Url + '", "topcolor":"#FF0000", "data":{' + ParaValue + '}}'
		--更新wxmessagesend中的message
		UPDATE WxMessageSend2 
		SET  MessageText = a.JsonMessage FROM #T05 a WHERE a.id = WxMessageSend2.id   
	END
	------企业浏览结束----

	------企业下载简历开始----6
	SELECT a.*, b.[NO] AS WxTemplateNo, c.Name CompanyName,c.SecondId, SPACE(1000) ParaValue, SPACE(200) Url, SPACE(1000) JsonMessage
	INTO #T06
	FROM #T1 a, WxTemplateNo b WITH(NOLOCK), CpMain c WITH(NOLOCK)
	WHERE a.Templatetype = 6 AND a.WxServiceNoID = b.WxServiceNoID AND b.WxTemplateId = 6 AND a.cpMainId = c.id
	IF @@RowCount > 0
 	BEGIN
		--插入参数数据
		SELECT @ParaValue = ''
		SELECT @ParaValue = @ParaValue + CASE WHEN @ParaValue > '' THEN ', ' ELSE '' END + ' "' + ParaName + '":{    "value":"' + ParaValue + '",    "color":"' + ParaColor + '"}' FROM WxTemplatePara WITH(NOLOCK) WHERE WxTemplateID = 6 ORDER BY ID
		UPDATE #T06 SET ParaValue = @ParaValue	
		 
		UPDATE #T06 SET ParaValue = REPLACE(ParaValue, '#PaName#', PaName) 
		UPDATE #T06 SET ParaValue = REPLACE(ParaValue, '#CompanyName#', CompanyName) 
		UPDATE #T06 SET ParaValue = REPLACE(ParaValue, '#WebsiteName#', WebsiteName)
		UPDATE #T06 SET Url = 'http://m.' + ProvinceDomain + '/library/WechatOauthPaLogin?opid=' + OpenId + '&urlfile=/personal/cp' + CONVERT(VARCHAR(30), SecondId )+'.html'
		UPDATE #T06 SET	JsonMessage = '{"touser":"' + OpenId + '", "template_id":"' + WxTemplateNo + '", "url":"' + Url + '", "topcolor":"#FF0000", "data":{' + ParaValue + '}}'
		--更新wxmessagesend中的message
		UPDATE WxMessageSend2 
		SET  MessageText = a.JsonMessage FROM #T06 a WHERE a.id = WxMessageSend2.id   
	END
	------企业下载简历结束----
	
	------简历审核未通过------7
	SELECT a.*, b.[NO] AS WxTemplateNo, c.VerifyDate, d.Mobile, SPACE(1000) ParaValue, SPACE(200) Url, SPACE(1000) JsonMessage
	INTO #T07
	FROM #T1 a, WxTemplateNo b WITH(NOLOCK), bsCvVerify c WITH(NOLOCK), PaMain d WITH(NOLOCK)
	WHERE a.Templatetype = 7 AND a.WxServiceNoID = b.WxServiceNoID 
	AND b.WxTemplateId = 7 AND a.MainTableId = c.Id AND a.PaMainId = d.Id
	IF @@RowCount > 0
	BEGIN
		--插入参数数据
		SELECT @ParaValue = ''
		SELECT @ParaValue = @ParaValue + CASE WHEN @ParaValue > '' THEN ', ' ELSE '' END + ' "' + ParaName + '":{    "value":"' + ParaValue + '",    "color":"' + ParaColor + '"}' FROM WxTemplatePara WITH(NOLOCK) WHERE WxTemplateID = 7 ORDER BY ID
		UPDATE #T07 SET ParaValue = @ParaValue	
		 
		UPDATE #T07 SET ParaValue = REPLACE(ParaValue, '#PaName#', PaName) 
		UPDATE #T07 SET ParaValue = REPLACE(ParaValue, '#Tel#', Mobile)
		UPDATE #T07 SET ParaValue = REPLACE(ParaValue, '#AddDate#', CONVERT(varchar, VerifyDate, 120 )) 
		UPDATE #T07 SET ParaValue = REPLACE(ParaValue, '#WebsiteName#', WebsiteName)
		UPDATE #T07 SET Url = 'http://m.' + ProvinceDomain + '/library/WechatOauthPaLogin?opid=' + OpenId + '&urlfile=/personal/sys/index'
		UPDATE #T07 SET	JsonMessage = '{"touser":"' + OpenId + '", "template_id":"' + WxTemplateNo + '", "url":"' + Url + '", "topcolor":"#FF0000", "data":{' + ParaValue + '}}'
		--更新wxmessagesend中的message
		UPDATE WxMessageSend2 
		SET  MessageText = a.JsonMessage FROM #T07 a WHERE a.id = WxMessageSend2.id
	END
	------简历审核未通过结束--
	
	------照片审核未通过------8
	SELECT a.*, b.[NO] AS WxTemplateNo, c.CheckDate, d.Mobile, SPACE(1000) ParaValue, SPACE(200) Url, SPACE(1000) JsonMessage
	INTO #T08
	FROM #T1 a, WxTemplateNo b WITH(NOLOCK), paPhoto c WITH(NOLOCK), PaMain d WITH(NOLOCK)
	WHERE a.Templatetype = 8 AND a.WxServiceNoID = b.WxServiceNoID AND b.WxTemplateId = 8 AND a.PaMainId = c.paMainId AND a.PaMainId = d.Id
	IF @@RowCount > 0
	BEGIN
		--插入参数数据
		SELECT @ParaValue = ''
		SELECT @ParaValue = @ParaValue + CASE WHEN @ParaValue > '' THEN ', ' ELSE '' END + ' "' + ParaName + '":{    "value":"' + ParaValue + '",    "color":"' + ParaColor + '"}' FROM WxTemplatePara WITH(NOLOCK) WHERE WxTemplateID = 8 ORDER BY ID
		UPDATE #T08 SET ParaValue = @ParaValue	
		 
		UPDATE #T08 SET ParaValue = REPLACE(ParaValue, '#PaName#', PaName) 
		UPDATE #T08 SET ParaValue = REPLACE(ParaValue, '#Tel#', Mobile)
		UPDATE #T08 SET ParaValue = REPLACE(ParaValue, '#AddDate#', CONVERT(varchar, CheckDate, 120 )) 
		UPDATE #T08 SET ParaValue = REPLACE(ParaValue, '#WebsiteName#', WebsiteName)
		UPDATE #T08 SET Url = 'http://m.' + ProvinceDomain + '/library/WechatOauthPaLogin?opid=' + OpenId + '&urlfile=/personal/sys/index'
		UPDATE #T08 SET	JsonMessage = '{"touser":"' + OpenId + '", "template_id":"' + WxTemplateNo + '", "url":"' + Url + '", "topcolor":"#FF0000", "data":{' + ParaValue + '}}'
		--更新wxmessagesend中的message
		UPDATE WxMessageSend2 
		SET  MessageText = a.JsonMessage FROM #T08 a WHERE a.id = WxMessageSend2.id  
	END
	------照片审核未通过结束--
	
	------简历答复开始-------9
	SELECT a.*, b.[NO] AS WxTemplateNo, c.Name CompanyName, d.Name jobName, CASE WHEN e.IsPhoneHide = 1 THEN '' ELSE e.Telephone END Telephone, CASE WHEN e.IsMobileHide = 1 THEN  ''  ELSE e.Mobile END Mobile, f.Reply, 
		f.ReplyDate, f.IsPassed, f.AddDate AS ApplyAddDate, SPACE(1000) ParaValue, SPACE(200) Url, SPACE(1000) JsonMessage
	INTO #T09
	FROM #T1 a, WxTemplateNo b WITH(NOLOCK), CpMain c WITH(NOLOCK), Job d WITH(NOLOCK), caMain e WITH(NOLOCK), exJobApply f WITH(NOLOCK)
	WHERE a.Templatetype = 9 
	AND a.WxServiceNoID = b.WxServiceNoID 
	AND b.WxTemplateId = 9 
	AND a.cpMainId = c.id 
	AND a.JobID = d.ID 
	AND e.id = a.caMainId 
	AND a.MainTableId = f.id
	IF @@RowCount > 0
	BEGIN
		--插入参数数据
		UPDATE #T09
		SET ParaValue = 
			(
			SELECT ' "' + ParaName + '":{    "value":"' + ParaValue + '",    "color":"' + ParaColor + '"}, ' 
			FROM WxTemplatePara WITH(NOLOCK) WHERE WxTemplateID = 9 AND ParaName = 'first') + 
			(SELECT ' "' + ParaName + '":{    "value":"' + ParaValue + '",    "color":"' + ParaColor + '"}, ' 
			FROM WxTemplatePara WITH(NOLOCK) WHERE WxTemplateID = 9 AND ParaName = 'keyword1')	 + 
			(SELECT ' "' + ParaName + '":{    "value":"' + ParaValue + '",    "color":"' + ParaColor + '"}, ' 
			FROM WxTemplatePara WITH(NOLOCK) WHERE WxTemplateID = 9 AND ParaName = 'keyword2') + 	 
			(SELECT ' "' + ParaName + '":{    "value":"' + ParaValue + '",    "color":"' + ParaColor + '"}, ' 
			FROM WxTemplatePara WITH(NOLOCK) WHERE WxTemplateID = 9 AND ParaName = 'keyword3')	 + 
			(SELECT ' "' + ParaName + '":{    "value":"' + ParaValue + '",    "color":"' + ParaColor + '"}, ' 
			FROM WxTemplatePara WITH(NOLOCK) WHERE WxTemplateID = 9 AND ParaName = 'keyword4') + 	 
			(SELECT ' "' + ParaName + '":{    "value":"' + '#KeyWord4#' + ParaValue + '",    "color":"' + ParaColor + '"}, ' 
			FROM WxTemplatePara WITH(NOLOCK) WHERE WxTemplateID = 9 AND ParaName = 'keyword5') + 
			(SELECT ' "' + ParaName + '":{    "value":"' + ParaValue + '",    "color":"' + ParaColor + '"}' 
			FROM WxTemplatePara WITH(NOLOCK) WHERE WxTemplateID = 9 AND ParaName = 'remark'
			)

		UPDATE #T09 SET ParaValue = REPLACE(ParaValue, '#PaName#', PaName)
		UPDATE #T09 SET ParaValue = REPLACE(ParaValue, '#JobName#', JobName)
		UPDATE #T09 SET ParaValue = REPLACE(ParaValue, '#CompanyName#', CompanyName)
		UPDATE #T09 SET ParaValue = REPLACE(ParaValue, '#AddDate#', CONVERT(varchar, ApplyAddDate, 120))
		UPDATE #T09 SET ParaValue = REPLACE(ParaValue, '#VerifyResult#', CASE WHEN reply = 1 THEN '符合要求，近期会联系您' WHEN reply = 2 THEN '暂时不符合要求' ELSE '职位暂时满员，空缺时再联系！'END)
		--UPDATE #T09 SET ParaValue = REPLACE(ParaValue, '#KeyWord4#', CASE WHEN reply = 1 THEN '符合要求' WHEN reply = 2 THEN '不符合要求' ELSE '以后联系' END)	
		UPDATE #T09 SET ParaValue = REPLACE(ParaValue, '#KeyWord4#', '')	
		UPDATE #T09 SET ParaValue = REPLACE(ParaValue, '#tel#', CASE WHEN ISNULL(Telephone, '') = ''THEN Mobile ELSE Telephone END)
		UPDATE #T09 SET ParaValue = REPLACE(ParaValue, '#Remark#', CASE WHEN reply = 1 THEN '主动联系公司，效果更好，祝您求职顺利！' WHEN reply = 2 THEN '不怕路远，就怕志短，尽快申请其他岗位，获得更多求职机会！' ELSE '主动联系公司，效果更好，祝您求职顺利！' END)
		UPDATE #T09 SET ParaValue = REPLACE(ParaValue, '#WebsiteName#', WebsiteName)
		UPDATE #T09 SET Url = 'http://m.' + ProvinceDomain + '/library/WechatOauthPaLogin?opid=' + OpenId + '&urlfile=/personal/jm/JobApplyList'
		UPDATE #T09 SET	JsonMessage = '{"touser":"' + OpenId + '", "template_id":"' + WxTemplateNo + '", "url":"' + Url + '", "topcolor":"#FF0000", "data":{' + ParaValue + '}}'
		--更新wxmessagesend中的message
		UPDATE WxMessageSend2 
		SET MessageText = a.JsonMessage FROM #T09 a WHERE a.id = WxMessageSend2.id
	END
	------简历答复结束--------	
	/*
	----微信替代短信开始-------10
	SELECT a.*, b.[NO] AS WxTemplateNo, c.*, d.UserName, SPACE(1000) ParaValue, SPACE(200) Url, SPACE(1000) JsonMessage
	INTO #T10
	FROM #T1 a, WxTemplateNo b, ShortDb..wxMessageTemp c, paMain d
	WHERE a.Templatetype = 10 AND a.WxServiceNoID = b.WxServiceNoID AND b.WxTemplateId = 10 AND a.MainTableId = c.Id AND d.Id = a.MainTableId
	IF @@RowCount > 0
	BEGIN
		--插入参数数据
		UPDATE #T10
		SET ParaValue = 
			(
			SELECT ' "' + ParaName + '":{    "value":"' + ParaValue + '",    "color":"' + ParaColor + '"}, ' 
			FROM WxTemplatePara WITH(NOLOCK) WHERE WxTemplateID = 10 AND ParaName = 'first') + 
			(SELECT ' "' + ParaName + '":{    "value":"' + ParaValue + '",    "color":"' + ParaColor + '"}, ' 
			FROM WxTemplatePara WITH(NOLOCK) WHERE WxTemplateID = 10 AND ParaName = 'keyword1')	 + 
			(SELECT ' "' + ParaName + '":{    "value":"' + ParaValue + '",    "color":"' + ParaColor + '"}, ' 
			FROM WxTemplatePara WITH(NOLOCK) WHERE WxTemplateID = 10 AND ParaName = 'keyword2') + 
			(SELECT ' "' + ParaName + '":{    "value":"' + ParaValue + '",    "color":"' + ParaColor + '"}' 
			FROM WxTemplatePara WITH(NOLOCK) WHERE WxTemplateID = 10 AND ParaName = 'remark'
			)
			 --前10天注册，最后登陆日期在3天前的，发送登录提醒 6
			 --前3天注册，简历不完整，登录 = 一次的，发送用户名、密码 7
			 --前3天注册，简历不完整，登录>一次的，发送简历不完整提醒 8
		UPDATE #T10 
		SET ParaValue = REPLACE(ParaValue, '#InformationValue#', 
			CASE WHEN SmsType = 6 THEN '您好，您在' + WebsiteName + 'http://www.' + provincedomain + '的用户名:' + UserName + '，欢迎使用'
				WHEN SmsType = 7 THEN '您好，您在' + WebsiteName + 'http://www.' + provincedomain + '的用户名:' + UserName + '，欢迎使用'
				ELSE  '您好，您在' + WebsiteName + 'http://www.' + provincedomain + '的简历不完整，请及时补全。拥有一份完整的简历，您将会拥有更多的求职机会'
			END)
		UPDATE #T10 SET ParaValue = REPLACE(ParaValue, '#PaName#', PaName)
		UPDATE #T10 SET Url = 'http://m.' + ProvinceDomain + '/library/WechatOauthPaLogin?opid=' + OpenId
		UPDATE #T10 SET	JsonMessage = '{"touser":"' + OpenId + '", "template_id":"' + WxTemplateNo + '", "url":"' + Url + '", "topcolor":"#FF0000", "data":{' + ParaValue + '}}'
		--更新wxmessagesend中的message
		UPDATE WxMessageSend2 
		SET  MessageText = a.JsonMessage FROM #T10 a WHERE a.id = WxMessageSend2.id  
    END
	----微信替代短信结束-------
	*/
	--你的菜儿开始
	SELECT a.*, b.[NO] AS WxTemplateNo, SPACE(1000) ParaValue, c.JobDesc,c.BatchNo, SPACE(200) Url, SPACE(1000) JsonMessage
	INTO #T13
	FROM #T1 a, WxTemplateNo b WITH(NOLOCK), paYourFoodWeiXin c WITH(NOLOCK)
	WHERE a.Templatetype = 13 
	AND a.WxServiceNoID = b.WxServiceNoID 
	AND b.WxTemplateId = 13 
	AND a.paMainId = c.paMainId

	IF @@RowCount > 0
	BEGIN
		--插入参数数据
		SELECT @ParaValue = ''
		SELECT @ParaValue = @ParaValue + CASE WHEN @ParaValue > '' THEN ', ' ELSE '' END + ' "' + ParaName + '":{    "value":"' + ParaValue + '",    "color":"' + ParaColor + '"}' 
		FROM WxTemplatePara WITH(NOLOCK) WHERE WxTemplateID = 13 ORDER BY ID

		UPDATE #T13 SET ParaValue = @ParaValue		 
		UPDATE #T13 SET ParaValue = REPLACE(ParaValue, '#PaName#', PaName) 
		UPDATE #T13 SET ParaValue = REPLACE(ParaValue, '#JobDesc#', JobDesc)
		UPDATE #T13 SET ParaValue = REPLACE(ParaValue, '#WebsiteName#', WebsiteName)
		UPDATE #T13 SET Url = 'http://m.' + ProvinceDomain + '/library/WechatOauthPaLogin?opid=' + OpenId + '&urlfile=/personal/js/yourfood?BatchNo=' + CAST(BatchNo AS VARCHAR(10))
		UPDATE #T13 SET	JsonMessage = '{"touser":"' + OpenId + '", "template_id":"' + WxTemplateNo + '", "url":"' + Url + '", "topcolor":"#000000", "data":{' + ParaValue + '}}'
		--更新wxmessagesend中的message
		UPDATE WxMessageSend2 
		SET MessageText = a.JsonMessage FROM #T13 a WHERE a.id = WxMessageSend2.id   
	END

	------应聘的简历提醒---- 14
	SELECT a.*, b.[NO] AS WxTemplateNo, c.Name jobName, d.Name CompanyName, SPACE(1000) ParaValue, SPACE(200) Url, SPACE(1000) JsonMessage
	INTO #T14
	FROM #T1 a, WxTemplateNo b WITH(NOLOCK), Job c WITH(NOLOCK), CpMain d WITH(NOLOCK)
	WHERE a.Templatetype = 14 AND a.WxServiceNoID = b.WxServiceNoID AND b.WxTemplateId = 14 AND a.JobID = c.ID AND a.cpMainId = d.id
	IF @@RowCount > 0
	BEGIN
		--插入参数数据
		SELECT @ParaValue = ''
		SELECT @ParaValue = @ParaValue + CASE WHEN @ParaValue > '' THEN ', ' ELSE '' END + ' "' + ParaName + '":{    "value":"' + ParaValue + '",    "color":"' + ParaColor + '"}' FROM WxTemplatePara WITH(NOLOCK) WHERE WxTemplateID = 14 ORDER BY ID
		UPDATE #T14 SET ParaValue = @ParaValue		
		UPDATE #T14 SET ParaValue = REPLACE(ParaValue, '#CompanyName#', CompanyName)	 
		UPDATE #T14 SET ParaValue = REPLACE(ParaValue, '#JobName#', JobName)	
		UPDATE #T14 SET ParaValue = REPLACE(ParaValue, '#WebsiteName#', WebsiteName)
		UPDATE #T14 SET Url = 'http://m.' + ProvinceDomain + '/library/WechatOauthCpLogin?opid=' + OpenId + '&urlfile=/company/cv/applycv'
		UPDATE #T14 SET	JsonMessage = '{"touser":"' + OpenId + '", "template_id":"' + WxTemplateNo + '", "url":"' + Url + '", "topcolor":"#FF0000", "data":{' + ParaValue + '}}'
		--更新wxmessagesend中的message
		UPDATE WxMessageSend2 
		SET MessageText = a.JsonMessage FROM #T14 a WHERE a.id = WxMessageSend2.id   
	END
	------应聘的简历提醒----

	------面试通知答复提醒---- 15
	SELECT a.*, b.[NO] AS WxTemplateNo, c.Name jobName, d.Name CompanyName, SPACE(1000) ParaValue, SPACE(200) Url, SPACE(1000) JsonMessage
	INTO #T15
	FROM #T1 a, WxTemplateNo b WITH(NOLOCK), Job c WITH(NOLOCK), CpMain d WITH(NOLOCK)
	WHERE a.Templatetype = 15 AND a.WxServiceNoID = b.WxServiceNoID AND b.WxTemplateId = 15 AND a.JobID = c.ID AND a.cpMainId = d.id
	IF @@RowCount > 0
	BEGIN
		--插入参数数据
		SELECT @ParaValue = ''
		SELECT @ParaValue = @ParaValue + CASE WHEN @ParaValue > '' THEN ', ' ELSE '' END + ' "' + ParaName + '":{    "value":"' + ParaValue + '",    "color":"' + ParaColor + '"}' FROM WxTemplatePara WITH(NOLOCK) WHERE WxTemplateID = 15 ORDER BY ID
		UPDATE #T15 SET ParaValue = @ParaValue		
		UPDATE #T15 SET ParaValue = REPLACE(ParaValue, '#CompanyName#', CompanyName)	 
		UPDATE #T15 SET ParaValue = REPLACE(ParaValue, '#PaName', PaName)	
		UPDATE #T15 SET ParaValue = REPLACE(ParaValue, '#WebsiteName#', WebsiteName)
		UPDATE #T15 SET Url = 'http://m.' + ProvinceDomain + '/library/WechatOauthCpLogin?opid=' + OpenId + '&urlfile=/company/jm/interview'
		UPDATE #T15 SET	JsonMessage = '{"touser":"' + OpenId + '", "template_id":"' + WxTemplateNo + '", "url":"' + Url + '", "topcolor":"#FF0000", "data":{' + ParaValue + '}}'
		--更新wxmessagesend中的message
		UPDATE WxMessageSend2 
		SET MessageText = a.JsonMessage FROM #T15 a WHERE a.id = WxMessageSend2.id   
	END
	------面试通知答复提醒----

	------应聘邀请答复提醒---- 16
	SELECT a.*, b.[NO] AS WxTemplateNo, c.Name jobName, d.Name CompanyName, SPACE(1000) ParaValue, SPACE(200) Url, SPACE(1000) JsonMessage
	INTO #T16
	FROM #T1 a, WxTemplateNo b WITH(NOLOCK), Job c WITH(NOLOCK), CpMain d WITH(NOLOCK)
	WHERE a.Templatetype = 16 AND a.WxServiceNoID = b.WxServiceNoID AND b.WxTemplateId = 16 AND a.JobID = c.ID AND a.cpMainId = d.id
	IF @@RowCount > 0
	BEGIN
		--插入参数数据
		SELECT @ParaValue = ''
		SELECT @ParaValue = @ParaValue + CASE WHEN @ParaValue > '' THEN ', ' ELSE '' END + ' "' + ParaName + '":{    "value":"' + ParaValue + '",    "color":"' + ParaColor + '"}' FROM WxTemplatePara WITH(NOLOCK) WHERE WxTemplateID = 16 ORDER BY ID
		UPDATE #T16 SET ParaValue = @ParaValue		
		UPDATE #T16 SET ParaValue = REPLACE(ParaValue, '#CompanyName#', CompanyName)	 
		UPDATE #T16 SET ParaValue = REPLACE(ParaValue, '#PaName', PaName)	
		UPDATE #T16 SET ParaValue = REPLACE(ParaValue, '#WebsiteName#', WebsiteName)
		UPDATE #T16 SET Url = 'http://m.' + ProvinceDomain + '/library/WechatOauthCpLogin?opid=' + OpenId + '&urlfile=/company/jm/cvintention'
		UPDATE #T16 SET	JsonMessage = '{"touser":"' + OpenId + '", "template_id":"' + WxTemplateNo + '", "url":"' + Url + '", "topcolor":"#FF0000", "data":{' + ParaValue + '}}'
		--更新wxmessagesend中的message
		UPDATE WxMessageSend2 
		SET MessageText = a.JsonMessage FROM #T16 a WHERE a.id = WxMessageSend2.id   
	END
	------应聘邀请答复提醒----

	------文字在线沟通新消息提醒---- 17
	SELECT a.*, b.[NO] AS WxTemplateNo, d.Name CompanyName, SPACE(1000) ParaValue, SPACE(200) Url, SPACE(1000) JsonMessage
	INTO #T17
	FROM #T1 a, WxTemplateNo b WITH(NOLOCK), CpMain d WITH(NOLOCK)
	WHERE a.Templatetype = 17 AND a.WxServiceNoID = b.WxServiceNoID AND b.WxTemplateId = 17 AND a.cpMainId = d.id
	IF @@RowCount > 0
	BEGIN
		--插入参数数据
		SELECT @ParaValue = ''
		SELECT @ParaValue = @ParaValue + CASE WHEN @ParaValue > '' THEN ', ' ELSE '' END + ' "' + ParaName + '":{    "value":"' + ParaValue + '",    "color":"' + ParaColor + '"}' FROM WxTemplatePara WITH(NOLOCK) WHERE WxTemplateID = 17 ORDER BY ID
		UPDATE #T17 SET ParaValue = @ParaValue		
		UPDATE #T17 SET ParaValue = REPLACE(ParaValue, '#CompanyName#', CompanyName)	 
		UPDATE #T17 SET ParaValue = REPLACE(ParaValue, '#PaName', PaName)	
		UPDATE #T17 SET ParaValue = REPLACE(ParaValue, '#WebsiteName#', WebsiteName)
		UPDATE #T17 SET Url = 'http://m.' + ProvinceDomain + '/library/WechatOauthCpLogin?opid=' + OpenId + '&urlfile=/chatonline/cplist'
		UPDATE #T17 SET	JsonMessage = '{"touser":"' + OpenId + '", "template_id":"' + WxTemplateNo + '", "url":"' + Url + '", "topcolor":"#FF0000", "data":{' + ParaValue + '}}'
		--更新wxmessagesend中的message
		UPDATE WxMessageSend2 
		SET MessageText = a.JsonMessage FROM #T17 a WHERE a.id = WxMessageSend2.id   
	END
	------文字在线沟通新消息提醒----

	------职位过期提醒---- 18
	SELECT a.*, b.[NO] AS WxTemplateNo, c.Name jobName, d.Name CompanyName, SPACE(1000) ParaValue, SPACE(200) Url, SPACE(1000) JsonMessage
	INTO #T18
	FROM #T1 a, WxTemplateNo b WITH(NOLOCK), Job c WITH(NOLOCK), CpMain d WITH(NOLOCK)
	WHERE a.Templatetype = 18 AND a.WxServiceNoID = b.WxServiceNoID AND b.WxTemplateId = 18 AND a.JobID = c.ID AND a.cpMainId = d.id
	IF @@RowCount > 0
	BEGIN
		--插入参数数据
		SELECT @ParaValue = ''
		SELECT @ParaValue = @ParaValue + CASE WHEN @ParaValue > '' THEN ', ' ELSE '' END + ' "' + ParaName + '":{    "value":"' + ParaValue + '",    "color":"' + ParaColor + '"}' FROM WxTemplatePara WITH(NOLOCK) WHERE WxTemplateID = 18 ORDER BY ID
		UPDATE #T18 SET ParaValue = @ParaValue		
		UPDATE #T18 SET ParaValue = REPLACE(ParaValue, '#CompanyName#', CompanyName)	 
		UPDATE #T18 SET ParaValue = REPLACE(ParaValue, '#JobName', jobName)	
		UPDATE #T18 SET ParaValue = REPLACE(ParaValue, '#WebsiteName#', WebsiteName)
		UPDATE #T18 SET Url = 'http://m.' + ProvinceDomain + '/library/WechatOauthCpLogin?opid=' + OpenId + '&urlfile=/company/job/jobissue'
		UPDATE #T18 SET	JsonMessage = '{"touser":"' + OpenId + '", "template_id":"' + WxTemplateNo + '", "url":"' + Url + '", "topcolor":"#FF0000", "data":{' + ParaValue + '}}'
		--更新wxmessagesend中的message
		UPDATE WxMessageSend2 
		SET MessageText = a.JsonMessage FROM #T18 a WHERE a.id = WxMessageSend2.id   
	END
	------职位过期提醒----

	------营业执照审核结果提醒---- 19
	SELECT a.*, b.[NO] AS WxTemplateNo, d.HasLicence, d.Name CompanyName, SPACE(1000) ParaValue, SPACE(200) Url, SPACE(1000) JsonMessage
	INTO #T19
	FROM #T1 a, WxTemplateNo b WITH(NOLOCK), CpMain d WITH(NOLOCK)
	WHERE a.Templatetype = 19 AND a.WxServiceNoID = b.WxServiceNoID AND b.WxTemplateId = 19 AND a.cpMainId = d.id
	IF @@RowCount > 0
	BEGIN
		--插入参数数据
		SELECT @ParaValue = ''
		SELECT @ParaValue = @ParaValue + CASE WHEN @ParaValue > '' THEN ', ' ELSE '' END + ' "' + ParaName + '":{    "value":"' + ParaValue + '",    "color":"' + ParaColor + '"}' FROM WxTemplatePara WITH(NOLOCK) WHERE WxTemplateID = 19 ORDER BY ID
		UPDATE #T19 SET ParaValue = @ParaValue		
		UPDATE #T19 SET ParaValue = REPLACE(ParaValue, '#CompanyName#', CompanyName)	 
		UPDATE #T19 SET ParaValue = REPLACE(ParaValue, '#VerifyResult', CASE HasLicence WHEN 1 THEN '已通过' ELSE '未通过' END)	
		UPDATE #T19 SET ParaValue = REPLACE(ParaValue, '#WebsiteName#', WebsiteName)
		UPDATE #T19 SET Url = 'http://m.' + ProvinceDomain + '/library/WechatOauthCpLogin?opid=' + OpenId + '&urlfile=/company/cp/cplicence'
		UPDATE #T19 SET	JsonMessage = '{"touser":"' + OpenId + '", "template_id":"' + WxTemplateNo + '", "url":"' + Url + '", "topcolor":"#FF0000", "data":{' + ParaValue + '}}'
		--更新wxmessagesend中的message
		UPDATE WxMessageSend2 
		SET MessageText = a.JsonMessage FROM #T19 a WHERE a.id = WxMessageSend2.id   
	END
	------营业执照审核结果提醒----
	------企业精确匹配简历推送----
	SELECT a.*, b.[NO] AS WxTemplateNo, SPACE(1000) ParaValue, c.Name caName, SPACE(200) Url, SPACE(1000) JsonMessage,'精确匹配' PushFrequency
	INTO #T22
	FROM #T1 a, WxTemplateNo b WITH(NOLOCK), caMain c WITH(NOLOCK)
	WHERE a.Templatetype = 22 
	AND a.WxServiceNoID = b.WxServiceNoID 
	AND b.WxTemplateId = 22 
	AND c.ID = a.caMainID
	
	IF @@RowCount > 0
	BEGIN
		--插入参数数据
		SELECT @ParaValue = ''
		SELECT @ParaValue = @ParaValue + CASE WHEN @ParaValue > '' THEN ', ' ELSE '' END + ' "' + ParaName + '":{    "value":"' + ParaValue + '",    "color":"' + ParaColor + '"}' 
		FROM WxTemplatePara WITH(NOLOCK) WHERE WxTemplateID = 22 ORDER BY ID

		UPDATE #T22 SET ParaValue = @ParaValue		 
		UPDATE #T22 SET ParaValue = REPLACE(ParaValue, '#caName#', caName)
		UPDATE #T22 SET ParaValue = REPLACE(ParaValue, '#PushFrequency#', PushFrequency) 
		UPDATE #T22 SET ParaValue = REPLACE(ParaValue, '#WebsiteName#', WebsiteName)
		UPDATE #T22 SET Url = 'http://m.' + ProvinceDomain + '/library/WechatOauthCpLogin?opid=' + OpenId + '&urlfile=/company/cvsearch/Recommend?PushDate=' + CONVERT(VARCHAR(8), GETDATE(), 112)
		UPDATE #T22 SET	JsonMessage = '{"touser":"' + OpenId + '", "template_id":"' + WxTemplateNo + '", "url":"' + Url + '", "topcolor":"#000000", "data":{' + ParaValue + '}}'
		--更新wxmessagesend中的message
		UPDATE WxMessageSend2 
		SET MessageText = a.JsonMessage FROM #T22 a WHERE a.id = WxMessageSend2.id   
	END
	------企业精确匹配简历推送结束----
	
	
	------招聘会审核通知开始-------23
	SELECT a.*, b.[NO] AS WxTemplateNo, c.CompanyName, d.Name RecruitmentName, 
	(CONVERT(varchar(2), datepart(mm,d.BeginDate))+'月'+CONVERT(varchar(2), datepart(dd,d.BeginDate))+'日（'+replace(datename(weekday,d.BeginDate),'星期','周')+')'+CONVERT(varchar(2), datepart(hh,d.BeginDate))+':'+RIGHT('0'+CONVERT(varchar(2), datepart(mi,d.BeginDate)),2)+
	'~'+CONVERT(varchar(2), datepart(hh,d.EndDate))+':'+RIGHT('0'+CONVERT(varchar(2), datepart(mi,d.EndDate)),2)) AS RecruitMentTime,(e.Name+ISNULL(f.Name,'')+ISNULL(d.address,'')) AS RecruitMentAddress, 
	c.DeskNo AS RecruitMentDeskNo, c.Status AS checkStatus,SPACE(20) RecruitMentVerifyResult, c.description AS RecruitMentRemark,
	SPACE(1000) ParaValue, SPACE(1000) JsonMessage
	INTO #T23
	FROM #T1 a 
	LEFT JOIN  WxTemplateNo b WITH(NOLOCK) 
	ON a.WxServiceNoID = b.WxServiceNoID 
	LEFT JOIN marketdb..rmcompany c WITH(NOLOCK) 
	ON a.MainTableId = c.id 
	LEFT JOIN wutongguodb..recruitmentSchool d WITH(NOLOCK) 
	ON  c.recruitmentId= d.id*-1 
	LEFT JOIN  wutongguodb..dcSchool e WITH(NOLOCK) 
	ON d.dcSchoolId = e.id  
	LEFT JOIN wutongguodb..dcSchoolArea f WITH(NOLOCK) 
	ON d.dcSchoolAreaId = f.Id
	WHERE a.Templatetype = 23  
	AND b.WxTemplateId = 23
	
	IF @@RowCount > 0
	BEGIN
		--插入参数数据
		UPDATE #T23
		SET ParaValue = 
			(
			(SELECT ' "' + ParaName + '":{    "value":"' + ParaValue + '",    "color":"' + ParaColor + '"}, ' 
			FROM WxTemplatePara WITH(NOLOCK) WHERE WxTemplateID = 23 AND ParaName = 'first') + 
			(SELECT ' "' + ParaName + '":{    "value":"' + ParaValue + '",    "color":"' + ParaColor + '"}, ' 
			FROM WxTemplatePara WITH(NOLOCK) WHERE WxTemplateID = 23 AND ParaName = 'keyword1')	 + 
			(SELECT ' "' + ParaName + '":{    "value":"' + ParaValue + '",    "color":"' + ParaColor + '"}, ' 
			FROM WxTemplatePara WITH(NOLOCK) WHERE WxTemplateID = 23 AND ParaName = 'keyword2') + 	 
			(SELECT ' "' + ParaName + '":{    "value":"' + ParaValue + '",    "color":"' + ParaColor + '"}, ' 
			FROM WxTemplatePara WITH(NOLOCK) WHERE WxTemplateID = 23 AND ParaName = 'keyword3')	 + 
			(SELECT ' "' + ParaName + '":{    "value":"' + ParaValue + '",    "color":"' + ParaColor + '"}, ' 
			FROM WxTemplatePara WITH(NOLOCK) WHERE WxTemplateID = 23 AND ParaName = 'keyword4') + 	 
			(SELECT ' "' + ParaName + '":{    "value":"' + ParaValue + '",    "color":"' + ParaColor + '"}, ' 
			FROM WxTemplatePara WITH(NOLOCK) WHERE WxTemplateID = 23 AND ParaName = 'keyword5') + 
			(SELECT ' "' + ParaName + '":{    "value":"' + ParaValue + '",    "color":"' + ParaColor + '"}' 
			FROM WxTemplatePara WITH(NOLOCK) WHERE WxTemplateID = 23 AND ParaName = 'remark')
			)

		UPDATE #T23 SET ParaValue = REPLACE(ParaValue, '#CompanyName#', CompanyName)
		UPDATE #T23 SET ParaValue = REPLACE(ParaValue, '#RecruitMentName#', RecruitmentName)
		UPDATE #T23 SET ParaValue = REPLACE(ParaValue, '#RecruitMentTime#', RecruitMentTime)
		UPDATE #T23 SET ParaValue = REPLACE(ParaValue, '#RecruitMentAddress#', RecruitMentAddress)
		UPDATE #T23 SET ParaValue = REPLACE(ParaValue, '#RecruitMentVerifyResult#', CASE WHEN checkStatus = 1 THEN '通过' ELSE '不通过'END)
		UPDATE #T23 SET ParaValue = REPLACE(ParaValue, '#RecruitMentDeskNo#', CASE WHEN checkStatus = 1 THEN CASE WHEN ISNULL(RecruitMentDeskNo,'')='' THEN '待分配' ELSE  RecruitMentDeskNo END ELSE '不分配' END)	
		UPDATE #T23 SET ParaValue = REPLACE(ParaValue, '#RecruitMentRemark#', CASE WHEN checkStatus = 1 THEN CASE WHEN ISNULL(RecruitMentRemark,'')='' THEN '请准时到场，如不能到场参加，请提前3天告知校方联系人' ELSE ISNULL(RecruitMentRemark,'')+'。请准时到场，如不能到场参加，请提前3天告知校方联系人' END ELSE '原因：'+ISNULL(RecruitMentRemark,'') END)
		--UPDATE #T23 SET Url = 'http://m.' + ProvinceDomain + '/library/WechatOauthPaLogin?opid=' + OpenId + '&urlfile=/personal/jm/JobApplyList'
		UPDATE #T23 SET	JsonMessage = '{"touser":"' + OpenId + '", "template_id":"' + WxTemplateNo + '", "url":"", "topcolor":"#FF0000", "data":{' + ParaValue + '}}'
		--更新wxmessagesend中的message
		UPDATE WxMessageSend2 
		SET MessageText = a.JsonMessage FROM #T23 a WHERE a.id = WxMessageSend2.id
	END
	------招聘会审核通知结束--------	
	
	
	DELETE WxMessageSend2
	WHERE Id IN (SELECT MIN(Id) Id
		FROM WxMessageSend2 WITH(NOLOCK)
		--WHERE AddDate > GETDATE() - 0.1
		GROUP BY paMainId, MessageText
		HAVING COUNT(*) >1
	)

	UPDATE WxMessageSend2 SET MessageText = REPLACE(MessageText, '\', ' ')
	WHERE ErrorNumber = 0 AND SendDate IS NULL
END




GO
/****** Object:  StoredProcedure [dbo].[procWxMessageSendInsert]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
--#####################################################
--创建时间：2015.01.27
--创建人：Nick
--说明：插入消息发送表
--#####################################################
CREATE PROCEDURE [dbo].[procWxMessageSendInsert]
(
	@WxFansID INT,
	@cpMainID INT,
	@Message VARCHAR(1000),
	@Status INT,
	@MessageType INT,
	@WxTemplateNoID INT,
	@Remark VARCHAR(200)
)
AS
BEGIN
	INSERT INTO WxMessageSend (WxFansID,cpMainID,Message,SendDate,Status,MessageType,WxTemplateNoID,Remark)
	VALUES(@WxFansID,@cpMainID,@Message,GETDATE(),1,@MessageType,@WxTemplateNoID,@Remark)
	--修改最后接收消息时间
	UPDATE WxFans SET LastReceiveDate = GETDATE() WHERE ID = @WxFansID
END 

GO
/****** Object:  StoredProcedure [dbo].[procWxMessageTemplateBySiteNameSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Mice 123>
-- Create date: <2015-4-15>
-- Description:	<根据站点名称查询当前站点是否有消息模板>
-- 修改：Harry2017-5-22
-- =============================================
CREATE PROCEDURE [dbo].[procWxMessageTemplateBySiteNameSelect]
(
	@UseType INT,
	@SiteName VARCHAR(100)
)
AS
SET NOCOUNT ON
BEGIN
	SET NOCOUNT ON;
	DECLARE @WxServiceNoId INT 
	DECLARE @WxNo VARCHAR(10)
	DECLARE @CapitalCity VARCHAR(10)
	SET @WxServiceNoId = 0
	SELECT @WxServiceNoId = a.ID,@CapitalCity =b.Abbr  FROM Maindb..wxServiceNo a,dcRegion b  WHERE a.Name = @SiteName AND a.ProvinceID=b.ParentID AND b.grade=2 AND b.id like'%01'

	IF @WxServiceNoId > 0
	BEGIN
		SET @WxNo = '%,' + CONVERT( VARCHAR(5), @WxServiceNoId ) + ',%'
		SELECT TOP 1 * 
		INTO #t
		FROM Maindb..wxMessageTemplate
		WHERE  UseType = @UseType AND Enddate > GETDATE() AND wxServiceNoId LIKE @WxNo
		ORDER BY ID DESC
		IF @UseType=1 
		BEGIN
			UPDATE #t SET MessageText = REPLACE(MessageText,'济南', @CapitalCity)
		END
		SELECT * FROM #t
		DROP TABLE #t
	END
	SET NOCOUNT OFF;
END

GO
/****** Object:  StoredProcedure [dbo].[procWxMessageTemplateDelete]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Mice 123>
-- Create date: <2015-4-1>
-- Description:	<删除微信自定义消息>
-- =============================================
CREATE PROCEDURE [dbo].[procWxMessageTemplateDelete] 
(
	@ID INT
)
AS
BEGIN
	SET NOCOUNT ON;
	DECLARE @MsgType AS INT
	SELECT @MsgType = MessageType FROM WxMessageTemplate WHERE ID = @ID
	IF @MsgType = 2 
	BEGIN
		DELETE FROM Maindb..WxMessageTemplateDetail WHERE WxMessageTemplateId = @ID
	END
	DELETE FROM Maindb..WxMessageTemplate WHERE ID = @ID
	SET NOCOUNT OFF;
END

GO
/****** Object:  StoredProcedure [dbo].[procWxMessageTemplateDetailDelete]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Mice 123>
-- Create date: <2015-4-1>
-- Description:	<删除一条微信自定义消息--图文消息>
-- =============================================
CREATE PROCEDURE [dbo].[procWxMessageTemplateDetailDelete]
(
	@ID INT
)
AS
BEGIN
	SET NOCOUNT ON;
	DELETE FROM Maindb..WxMessageTemplateDetail WHERE ID = @ID
END

GO
/****** Object:  StoredProcedure [dbo].[procWxMessageTemplateDetailUpdate]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Mice 123>
-- Create date: <2015-4-1>
-- Description:	<保存一条微信自定义消息--图文消息>
-- =============================================
CREATE PROCEDURE [dbo].[procWxMessageTemplateDetailUpdate] 
(
	@ID INT,
	@WxMessageTemplateID INT,
	@Title NVARCHAR(50),
	@Description NVARCHAR(50),
	@PicUrl VARCHAR(300),
	@Url VARCHAR(300),
	@Sort INT
)
AS
BEGIN
	SET NOCOUNT ON;
	IF @ID > 0 
	BEGIN
		UPDATE WxMessageTemplateDetail
		SET WxMessageTemplateID = @WxMessageTemplateID, Title = @Title, Description = @Description ,
			PicUrl = @PicUrl ,Url = @Url ,Sort = @Sort , AddDate = GETDATE()
		WHERE ID = @ID
	END
	ELSE
	BEGIN
		INSERT INTO Maindb..WxMessageTemplateDetail( WxMessageTemplateID,Title, Description  ,PicUrl,Url ,Sort,AddDate )
		VALUES ( @WxMessageTemplateID, @Title, @Description, @PicUrl, @Url, @Sort,GETDATE()  )
	END
	SET NOCOUNT OFF;
END

GO
/****** Object:  StoredProcedure [dbo].[procWxMessageTemplateUpdate]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Mice 123>
-- Create date: <2015-4-1>
-- Description:	<微信自定义消息模版修改>
-- 修改： 返回ID值
-- =============================================
CREATE PROCEDURE [dbo].[procWxMessageTemplateUpdate] 
(
	@ID INT,
	@wxServiceNoId VARCHAR(100),
	@MsgType INT,
	@UseType INT,
	@msgText TEXT,
	@endDate SMALLDATETIME,
	@addMan INT
)
AS
BEGIN
	SET NOCOUNT ON;
	IF @ID > 0 
	BEGIN
		UPDATE Maindb..WxMessageTemplate SET wxServiceNoId = @wxServiceNoId ,MessageType = @MsgType,
			UseType = @UseType, MessageText = @msgText,Enddate = @endDate, AddMan = @addMan, AddDate = getDate()
		WHERE id = @ID
	END
	ELSE
	BEGIN
		INSERT INTO Maindb..WxMessageTemplate(wxServiceNoId ,MessageType,UseType,MessageText,Enddate,AddMan,AddDate )
		VALUES ( @wxServiceNoId ,@MsgType,@UseType,@msgText,@endDate,@addMan,getDate() )
		SELECT @ID = @@IDENTITY
	END
	RETURN @ID
	SET NOCOUNT OFF;
END
GO
/****** Object:  StoredProcedure [dbo].[procWXQrImageByIDSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.10
--创建人：NICK
--说明：根据id获取微信生成记录
--#####################################################
CREATE PROCEDURE [dbo].[procWXQrImageByIDSelect]
(
	@ID INT
)
AS
BEGIN
	SELECT * FROM WXQrImage WHERE id = @ID
END


GO
/****** Object:  StoredProcedure [dbo].[procWXQrImageByIDUpdate]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.10
--创建人：NICK
--说明：
--#####################################################
CREATE PROCEDURE [dbo].[procWXQrImageByIDUpdate]
(
	@ID INT,
	@Status INT,
	@OpenID VARCHAR(100)
)
AS
BEGIN
	UPDATE WXQrImage SET status=@Status,paMainID=(
		SELECT TOP 1 paMainID 
		FROM palogincontact WITH(NOLOCK) 
		WHERE ContactType=4 
		AND Openid=@OpenID 
		ORDER BY ID DESC)
	,openid=@OpenID 
	WHERE ID=@ID
END


GO
/****** Object:  StoredProcedure [dbo].[procWXQrImageByIDUpdateNew]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2016.4.7
--创建人：Lucifer
--说明：
--#####################################################
CREATE PROCEDURE [dbo].[procWXQrImageByIDUpdateNew]
(
	@ID INT,
	@Status INT,
	@OpenID VARCHAR(100),
	@ContactType INT
)
AS
BEGIN
	UPDATE WXQrImage SET status=@Status,paMainID=(
		SELECT TOP 1 paMainID 
		FROM palogincontact WITH(NOLOCK) 
		WHERE ContactType=@ContactType 
		AND Openid=@OpenID 
		ORDER BY ID DESC)
	,openid=@OpenID 
	WHERE ID=@ID
END

GO
/****** Object:  StoredProcedure [dbo].[ProcWXQrImageTicketUpdate]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.5
--创建人：John
--说明：更新/删除二维码记录
--#####################################################
CREATE PROCEDURE [dbo].[ProcWXQrImageTicketUpdate]
(
	@Ticket VARCHAR(150),
	@ID INT
)
AS
SET NOCOUNT ON
--INSERT INTO ProcLog SELECT 'ProcWXQrImageTicketUpdate', '', GETDATE()
--200tines one minute
BEGIN
	IF @Ticket <> ''
	BEGIN
		UPDATE WXQrImage SET Ticket = @Ticket WHERE ID = @ID 
	END
	ELSE
	BEGIN
		DELETE FROM WXQrImage WHERE ID=@ID
	END
END


GO
/****** Object:  StoredProcedure [dbo].[procWXQrImageUpdate]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2016.4.7
--创建人：Lucifer
--说明：修改 WXQrImage 状态
--#####################################################
CREATE PROCEDURE [dbo].[procWXQrImageUpdate]
(
	@ID INT,
	@Status INT,
	@OpenID VARCHAR(50),
	@ContactType INT
)
AS
SET NOCOUNT ON
BEGIN
	IF @ContactType > 0
	BEGIN
		UPDATE WXQrImage SET
			Status = @Status,
			OpenID = @OpenID,
			paMainID = (
				SELECT TOP 1 paMainID 
				FROM paLoginContact WITH(NOLOCK) 
				WHERE ContactType = @ContactType 
				AND OpenID = @OpenID 
				ORDER BY ID DESC
			)
		WHERE ID = @ID
	END
	ELSE
	BEGIN
		UPDATE WXQrImage SET
			Status = @Status,
			OpenID = @OpenID
		WHERE ID = @ID
	END
END
GO
/****** Object:  StoredProcedure [dbo].[procWxSendDataByTypeSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.01.26
--创建人：Nick
--说明：获取等待发送的消息
--修改：mice 123 2015-4-20 增加type=10（微信代替短息的消息）
--#####################################################
CREATE PROCEDURE [dbo].[procWxSendDataByTypeSelect]
(
	@Type INT   --1面试通知 , 2企业给求职者发送应聘邀请, 3 企业收藏简历 4 企业查看简历 5 企业下载简历
				-- 6企业答复求职者简历  7企业留言 8简历审核不通过 9 照片审核不通过
)
AS
BEGIN
	DECLARE @StartTime DATETIME, @EndTime DATETIME
	SELECT @StartTime = DATEADD(ms, 0, DATEADD(dd, DATEDIFF(dd, 0, GETDATE()), 0))
	SELECT @EndTime = DATEADD(ms, -3, DATEADD(dd, DATEDIFF(dd, -1, GETDATE()), 0))

	IF @Type = 1 --面试通知
	BEGIN
		SELECT * INTO #1 FROM ExInterView WHERE ID > (SELECT MaxID FROM WxMax WHERE TableName='exinterview')
		SELECT a.JobID, a.CvMainID, a.InterviewDate, a.InterViewPlace, a.LinkMan, a.Telephone, a.Remark, b.Name AS JobName, 
			f.Name AS PaName, b.CpMainID, e.Name AS CpName, d.WxServiceNoID, a.ID, g.ProvinceDomain, d.ID AS WxFansID, d.OpenID
		FROM #1 a WITH(NOLOCK), Job b WITH(NOLOCK), CvMain c WITH(NOLOCK), WxFans d WITH(NOLOCK), CpMain e WITH(NOLOCK), PaMain f WITH(NOLOCK), dcProvince g WITH(NOLOCK)
		WHERE a.Jobid = b.ID 
		AND a.CvmainID = c.ID 
		AND c.PaMainID = f.ID
		AND c.PaMainID = d.PaMainID 
		AND b.CpMainID = e.ID
		AND f.dcProvinceID = g.ID
		AND d.Status=2
		--更新WxMax表数据
		UPDATE WxMax SET MaxID = (SELECT MAX(ID) FROM Exinterview WITH(NOLOCK)), UpdateDate = GETDATE()
		WHERE TableName='exinterview' 
		RETURN
	END
	ELSE IF @Type = 2  --企业发送应聘邀请
	BEGIN
		SELECT * INTO #2 FROM caCvIntention WHERE ID > (SELECT MaxID FROM WxMax WHERE TableName='cacvintention')
		SELECT a.JobID, a.CvMainID, a.AddDate, b.Name AS JobName, d.OpenID, b.dcsalaryid, 
		f.Name AS PaName, b.CpMainID, e.Name AS CpName, d.WxServiceNoID, a.ID, g.ProvinceDomain, h.FullName, d.ID AS WxFansID
		FROM #2 a, Job b, CvMain c, WxFans d, CpMain e, PaMain  f, dcProvince g, dcRegion h
		WHERE a.Jobid = b.ID 
		AND a.CvmainID = c.ID 
		AND c.PaMainID = f.ID
		AND c.PaMainID = d.PaMainID 
		AND b.CpMainID = e.ID
		AND f.dcProvinceID = g.ID
		AND b.dcRegionID = h.ID
		AND d.Status=2 
		
		--更新WxMax表数据
		UPDATE WxMax SET MaxID = (SELECT MAX(ID) FROM CaCvIntention), UpdateDate = GETDATE()
		WHERE TableName='cacvintention'
		RETURN
	END
	ELSE IF @Type = 3  --企业收藏简历
	BEGIN
		SELECT * INTO #3 FROM caFavorate WHERE ID > (SELECT MaxID FROM WxMax WHERE TableName='cafavorate')
		SELECT a.JobID, a.CvMainID, a.AddDate, b.Name AS JobName, 
		f.Name AS PaName, b.CpMainID, e.Name AS CpName, d.WxServiceNoID, a.ID, g.ProvinceDomain, d.OpenID, d.ID AS WxFansID
		FROM #3 a, Job b, CvMain c, WxFans d, CpMain e, PaMain f, dcProvince g
		WHERE a.Jobid = b.ID 
		AND a.CvmainID = c.ID 
		AND c.PaMainID = f.ID
		AND c.PaMainID = d.PaMainID 
		AND b.CpMainID = e.ID
		AND f.dcProvinceID = g.ID
		AND d.Status=2 
		
		--更新WxMax表数据
		UPDATE WxMax SET MaxID = (SELECT MAX(ID) FROM caFavorate), UpdateDate = GETDATE()
		WHERE TableName='cafavorate'
		RETURN
	END
	ELSE IF @Type = 4  --企业查看简历
	BEGIN
		SELECT * INTO #4 FROM caCvViewlog
		WHERE AddDate > (SELECT MaxID FROM WxMax WHERE TableName='cacvviewlog')
		AND AddDate IN (SELECT MIN(AddDate) 
			FROM caCvViewlog 
			WHERE AddDate > @StartTime AND AddDate<@EndTime
			GROUP BY CaMainID)
		
		SELECT a.caMainID, a.CvMainID, a.AddDate, d.OpenID, 
		f.Name AS PaName, e.Name AS CpName, b.CpMainID, d.ID AS WxFunID, 0 AS IsDelete, d.WxServiceNoID, g.ProvinceDomain , d.ID AS WxFansID
		INTO #T2
		FROM #4 a, CaMain b, CvMain c, WxFans d, CpMain e, PaMain f, dcProvince g
		WHERE a.caMainID = b.ID 
		AND a.CvmainID = c.ID 
		AND c.PaMainID = f.ID
		AND c.PaMainID = d.PaMainID 
		AND b.CpMainID = e.ID
		AND f.dcProvinceID = g.ID
		AND d.Status=2 
			
		UPDATE a Set a.IsDelete = 1 
		FROM #T2 a, WxMessageSend b
		WHERE b.SendDate>@StartTime AND b.SendDate<@EndTime
		AND a.WxFunID = b.WxFansID
		AND a.cpMainID = b.cpMainID
		AND b.MessageType = 3
		AND b.WxTemplateNoID IN (SELECT ID FROM WxTemplateNo WHERE wxTemplateID = 5)
		
		DELETE FROM #T2 WHERE IsDelete = 1
		
		SELECT * FROM #T2
		
		--更新WxMax表数据
		UPDATE WxMax SET MaxID = (SELECT MAX(AddDate) FROM caFavorate), UpdateDate = GETDATE()
		WHERE TableName='cacvviewlog' 
		RETURN
	END	
	ELSE IF @Type = 5  --企业下载简历
	BEGIN
		SELECT * INTO #51 FROM caActiveLog WHERE ID > (SELECT MaxID FROM WxMax WHERE TableName='caactivelog')
		SELECT * INTO #52 FROM caDailyGiftLog WHERE AddDate > (SELECT MaxID FROM WxMax WHERE TableName='cadailygiftlog')

		SELECT a.cpMainID, a.CvMainID, a.AddDate, 
		e.Name AS PaName, b.Name AS CpName, b.ID AS CpMainID, d.WxServiceNoID, g.ProvinceDomain , d.OpenID, d.ID AS WxFansID
		FROM #51 a WITH(NOLOCK), CpMain b, CvMain c, WxFans d, PaMain e, dcProvince g
		WHERE a.cpMainID = b.ID 
		AND a.CvmainID = c.ID 
		AND c.PaMainID = e.ID
		AND e.dcProvinceID = g.ID
		AND c.PaMainID = d.PaMainID 
		AND d.Status=2
		UNION
		SELECT a.cpMainID, a.CvMainID, a.AddDate, 
		c.Name AS PaName, b.Name AS CpName, b.ID AS CpMainID, d.WxServiceNoID, g.ProvinceDomain , d.OpenID, d.ID AS WxFansID
		FROM #52 a, CpMain b, CvMain c, WxFans d, PaMain e, dcProvince g
		WHERE a.cpMainID = b.ID 
		AND a.CvmainID = c.ID 
		AND c.PaMainID = d.PaMainID 
		AND c.PaMainID = e.ID
		AND e.dcProvinceID = g.ID
		AND d.Status=2
		
		--更新WxMax表数据
		UPDATE WxMax SET MaxID = (SELECT MAX(ID) FROM caactivelog), UpdateDate = GETDATE()
		WHERE TableName='caactiveLog' 
		
		UPDATE WxMax SET MaxID = (SELECT MAX(AddDate) FROM cadailygiftlog), UpdateDate = GETDATE()
		WHERE TableName='cadailygiftlog' 
		RETURN
	END
	ELSE IF @Type = 6 --企业答复求职者简历
	BEGIN
		SELECT * INTO #6 FROM exJobApply WHERE ReplyDate > (SELECT MaxID FROM WxMax WHERE TableName='exjobapply')
		SELECT a.JobID, a.CvMainID, a.Reply, a.ReplyDate, a.IsPassed, b.Name AS JobName, a.AddDate, h.Telephone, h.Mobile, 
		f.Name AS PaName, b.CpMainID, e.Name AS CpName, d.WxServiceNoID, a.ID, g.ProvinceDomain, d.OpenID, d.ID AS WxFansID
		FROM #6 a, Job b, CvMain c, WxFans d, CpMain e, PaMain f, dcProvince g, caMain h
		WHERE a.Jobid = b.ID 
		AND a.CvmainID = c.ID 
		AND c.PaMainID = f.ID
		AND c.PaMainID = d.PaMainID 
		AND b.CpMainID = e.ID
		AND f.dcProvinceID = g.ID
		AND b.CaMainID = h.ID
		AND d.Status=2
		
		--更新WxMax表数据
		UPDATE WxMax 
		SET MaxID = (SELECT MAX(ReplyDate) FROM exJobApply), UpdateDate = GETDATE()
		WHERE TableName='exjobapply'
		RETURN
	END
	ELSE IF @Type = 7 --企业给求职者留言
	BEGIN
		SELECT * INTO #t7 FROM chatonline
		WHERE ID > (SELECT MaxID FROM WxMax WHERE TableName='chatonline') 
		AND ID IN (SELECT MIN(ID) 
			FROM chatonline 
			WHERE AddDate>@StartTime --AND AddDate<@EndTime
			GROUP BY CvMainID)

		SELECT ChatOnlineId id INTO #t71 FROM ChatOnlineLog
		WHERE ChatOnlineId IN(SELECT id FROM #t7)
		AND isviewed=0 AND sendertype=1
		AND AddDate < dateadd(minute, -2, getdate())

		DELETE #T7 WHERE ID NOT IN(SELECT ID FROM #T71)

		SELECT a.cvMainID, a.caMainID, a.AddDate, 
			f.Name AS PaName, b.CpMainID, e.Name AS CpName, d.ID AS WxFunID, 0 AS IsDelete, 
			d.WxServiceNoID, a.ID, g.ProvinceDomain, d.OpenID, d.ID AS WxFansID
		INTO #T
		FROM #t7 a, CaMain b, CvMain c, WxFans d, CpMain e, PaMain f, dcProvince g
		WHERE a.caMainID = b.ID 
		AND a.CvmainID = c.ID 
		AND c.PamainID = f.ID
		AND c.PaMainID = d.PaMainID 
		AND b.CpMainID = e.ID
		AND f.dcProvinceID = g.ID
		AND d.Status=2
		--AND e.ID NOT IN( SELECT CpMainID 
		--	FROM WxMessageSend 
		--	WHERE SendDate>@StartTime AND SendDate<@EndTime)
		
		UPDATE a Set a.IsDelete = 1 
		FROM #T a, WxMessageSend b
		WHERE b.SendDate>@StartTime AND b.SendDate<@EndTime
		AND a.WxFunID = b.WxFansID
		AND a.cpMainID = b.cpMainID
		AND b.MessageType = 3
		AND b.WxTemplateNoID IN (SELECT ID FROM WxTemplateNo WHERE wxTemplateID = 4)
		
		DELETE FROM #T WHERE IsDelete = 1
		
		SELECT * FROM #T
		
		--更新WxMax表数据
		UPDATE WxMax SET MaxID = (SELECT MAX(ID) FROM ChatOnline), UpdateDate = GETDATE()
		WHERE TableName='chatonline' 
		RETURN
	END
	ELSE IF @Type = 8 --简历审核不通过
	BEGIN
		SELECT * INTO #t8 FROM bsCvVerify WHERE ID > (SELECT MaxID FROM WxMax WHERE TableName='bscvverify') AND VerifyResult = 10
		SELECT a.cvMainID, c.Name AS PaName, d.WxServiceNoID, a.ID, g.ProvinceDomain, d.OpenID, c.Mobile, d.ID AS WxFansID, a.VerifyDate
		FROM #t8 a, CvMain b,PaMain c, WxFans d, dcProvince g
		WHERE a.cvMainID = b.ID 
		AND b.PaMainID = c.ID 
		AND b.PaMainID = d.PaMainID
		AND c.dcProvinceID = g.ID
		AND d.Status = 2
		
		--更新WxMax表数据
		UPDATE WxMax SET MaxID = (SELECT MAX(ID) FROM bsCvVerify), UpdateDate = GETDATE()
		WHERE TableName='bscvverify' 
		RETURN
	END
	ELSE IF @Type = 9 --照片审核不通过
	BEGIN
		--SELECT * INTO #t9 FROM PaPhoto WHERE CheckDate > (SELECT MaxID FROM WxMax WHERE TableName='paphoto')
		SELECT a.PaMainID, a.CheckDate, b.Name AS PaName, c.WxServiceNoID, g.ProvinceDomain, c.OpenID  , b.Mobile, c.ID AS WxFansID
		FROM PaPhoto a, PaMain b, WxFans c, dcProvince g
		WHERE a.PaMainID = b.ID
		AND b.HasPhoto = 2
		AND b.id = c.pamainid
		AND b.dcProvinceID = g.ID
		AND c.Status=2
		AND  CheckDate > (SELECT MaxID FROM WxMax WHERE TableName='paphoto')
		--更新WxMax表数据
		UPDATE WxMax SET MaxID = (SELECT MAX(CheckDate) FROM PaPhoto), UpdateDate = GETDATE()
		WHERE TableName='paphoto' 
		RETURN
	END
	ELSE IF @Type = 110 --代替短信的消息
	BEGIN
		SELECT  a.* , b.ID AS wxFansID, b.OpenID, b.PaMainID , b.WxServiceNoID , c.UserName, c.Name AS PaName , y.ProvinceDomain, y.WebsiteName
		FROM ShortDb..wxMessageTemp a, Maindb..WxFans b , Maindb..PaMain c, Maindb..wxServiceNo x , Maindb..dcProvince y 
		WHERE b.paMainID = a.paMainID AND c.id = a.paMainID AND b.WxServiceNoID = x.id AND x.ProvinceID = y.id
		RETURN
	END
	ELSE IF @Type = 12 --微简历消息
	BEGIN
		SELECT a.*, b.Name AS cvName, c.WxServiceNoID, c.id AS wxFansID
		FROM Shortdb..SmallCvNotify a
		LEFT JOIN Shortdb..SmallCv b ON b.id = a.SmallCvId
		LEFT JOIN Maindb..wxFans c ON c.OpenID = a.OpenID
		WHERE a.SendDate IS NULL
	END
END
GO
/****** Object:  StoredProcedure [dbo].[ProcWxServiceNoByProvinceIdSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ProcWxServiceNoByProvinceIdSelect]
(
	@ProvinceId INT
)
AS
BEGIN
	SELECT * FROM wxServiceNo WHERE ProvinceId = @ProvinceId
END

GO
/****** Object:  StoredProcedure [dbo].[procWxServiceNoByStatusSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.01.26
--创建人：Nick
--说明：获取微信服务号数据
--#####################################################
CREATE PROCEDURE [dbo].[procWxServiceNoByStatusSelect]
(
	@Status INT
)
AS
BEGIN
	IF @Status = 0
	BEGIN
		SELECT * FROM WxServiceNo WITH(NOLOCK)
	END
	ELSE
	BEGIN
		SELECT * FROM WxServiceNo WITH(NOLOCK) WHERE Status = @Status
	END
END 

GO
/****** Object:  StoredProcedure [dbo].[procWxShareByOpenIDSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


--2016-2-17 nick
--判断是否领取过红包
create PROCEDURE [dbo].[procWxShareByOpenIDSelect]
(
	@OpenID VARCHAR(50),
	@TypeID INT
)
AS
BEGIN
	SELECT * FROM wxShare WITH(NOLOCK)
	WHERE OpenID = @OpenID
	AND TypeID = @TypeID
	AND ReceiveDate IS NOT NULL
END

GO
/****** Object:  StoredProcedure [dbo].[procWxShareInsert]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--2016-2-17 nick
--微信分享
CREATE PROCEDURE [dbo].[procWxShareInsert]
(
	@OpenID VARCHAR(50),
	@TypeID INT, --1红包
	@SiteUrl VARCHAR(200)
)
AS
BEGIN
	DECLARE @Return INT
	DECLARE @DateTmp DATETIME
	DECLARE @ValidNum INT
	SET @DateTmp = '2016-2-17'
	--是否分享过
	IF EXISTS(SELECT * FROM WxShare WITH(NOLOCK) WHERE OpenID = @OpenID AND TypeID = @TypeID)
	BEGIN
		--判断是否发送过照片
		IF NOT EXISTS(SELECT * FROM WxWish WITH(NOLOCK) WHERE OpenID = @OpenID AND AddDate > @DateTmp)	--不存在
		BEGIN
			SET @Return = 1		--请上传照片
			INSERT INTO wxPhotoMsg(OpenID,Context,AddDate) VALUES(@OpenID,'请上传照片',GETDATE())
		END
		--ELSE 
		--BEGIN
			--SELECT TOP 1 @ValidNum = IsValid 
			--FROM WxWish WITH(NOLOCK) 
			--WHERE OpenID = @OpenID 
			--AND AddDate > @DateTmp
			--ORDER BY CASE WHEN IsValid = 1 THEN 3 END DESC
			
			--IF @ValidNum = 2	--审核不通过
			--BEGIN
			--	SET @Return = 2 --您的照片审核不通过，重新上传照片
			--END
			--IF @ValidNum IS NULL OR @ValidNum = 0
			--BEGIN
			--	SET @Return = 3 --您已上传照片，请耐心等待审核哦~
			--END
		--END
	END
	ELSE 
	BEGIN
		INSERT INTO WxShare(OpenID,TypeID,AddDate) VALUES(@OpenID,@TypeID,GETDATE())
		--判断是否发送过照片
		IF NOT EXISTS(SELECT * FROM WxWish WITH(NOLOCK) WHERE OpenID = @OpenID AND AddDate > @DateTmp)	--不存在
		BEGIN
			SET @Return = 1		-- 请上传照片
			INSERT INTO wxPhotoMsg(OpenID,Context,AddDate) VALUES(@OpenID,'请上传照片',GETDATE())
		END
		ELSE 
		BEGIN
			SELECT TOP 1 @ValidNum = IsValid 
			FROM WxWish WITH(NOLOCK) 
			WHERE OpenID = @OpenID 
			AND AddDate > @DateTmp
			ORDER BY CASE WHEN IsValid = 1 THEN 3 END DESC

			--IF @ValidNum = 2	--审核不通过
			--BEGIN
			--	SET @Return = 2 --您的照片审核不通过，重新上传照片
			--END
			--ELSE IF @ValidNum IS NULL OR @ValidNum = 0
			--BEGIN
			--	SET @Return = 3 --您已上传照片，请耐心等待审核哦~
			--END
		    IF @ValidNum = 1
			BEGIN
				SET @Return = 2--提醒抢红包
				INSERT INTO wxPhotoMsg(OpenID,Context,AddDate) VALUES(@OpenID,'点击开始<a href='''+@SiteUrl+'&red=1''>领取红包</a>吧',GETDATE())
			END
		END
	END
	RETURN 0
END

GO
/****** Object:  StoredProcedure [dbo].[procWxShareUpdate]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--2016-2-17 nick
--领取微信红包
CREATE PROCEDURE [dbo].[procWxShareUpdate]
(
	@OpenID VARCHAR(50),
	@TypeID INT, --1红包
	@ReceivePrice DECIMAL(18,2),--红包金额
	@SiteUrl VARCHAR(200)
)
AS
BEGIN
	DECLARE @Return INT
	--判断是否符合领取红包的条件
	--判断照片是否上传
	IF NOT EXISTS (SELECT * FROM WxWish WITH(NOLOCK) WHERE OpenID = @OpenID AND IsValid = 1)
	BEGIN
		SET @Return = 2 --请上传照片
		--INSERT INTO wxPhotoMsg(OpenID,Context,AddDate) VALUES(@OpenID,'照片未审核或未上传照片',GETDATE())
	END
	ELSE IF NOT EXISTS(SELECT * FROM WxShare WITH(NOLOCK) WHERE OpenID = @OpenID AND TypeID = 1)
	BEGIN
		SET @Return = 3 --请分享朋友圈 
		--INSERT INTO wxPhotoMsg(OpenID,Context,AddDate) VALUES(@OpenID,'照片审核通过，<a href='''+@SiteUrl+'''>分享到朋友圈</a>领红包吧',GETDATE())
	END
	ELSE IF EXISTS(SELECT * FROM WxShare WITH(NOLOCK) WHERE OpenID = @OpenID AND TypeID = 1 AND ReceiveDate IS NOT NULL)
	BEGIN
	    SET @Return = 4 --已经领取过红包 
	END
	ELSE 
	BEGIN
		SET @Return = 1 --领取红包
		--UPDATE WxShare SET ReceivePrice = @ReceivePrice WHERE OpenID = @OpenID AND TypeID = @TypeID
		--INSERT INTO wxPhotoMsg(OpenID,Context,AddDate) VALUES(@OpenID,'点击开始<a href='''+@SiteUrl+'&red=1''>领取红包</a>吧',GETDATE())
	END
	RETURN @Return
END

GO
/****** Object:  StoredProcedure [dbo].[procWxSmallPrograminfoByPaMainIdUpdate]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--微信小程序绑定个人账号id
--harry
--2018-3-7
CREATE PROCEDURE [dbo].[procWxSmallPrograminfoByPaMainIdUpdate]
(
    @paMainId INT,
    @thirdSessionId VARCHAR(200)    
)
AS
SET NOCOUNT ON
BEGIN 
    IF EXISTS(SELECT 'X' FROM wxSmallPrograminfo WITH(NOLOCK) WHERE thirdSessionId = @thirdSessionId)
    BEGIN
        UPDATE wxSmallPrograminfo 
        SET paMainId = @paMainId 
        WHERE thirdSessionId= @thirdSessionId 
	 
	--更新unionid
	UPDATE wxFans
    	SET unionid= (SELECT unionid FROM wxSmallPrograminfo  WHERE thirdSessionId= @thirdSessionId )
    	WHERE paMainId = @paMainId
        
    END
    ELSE
    BEGIN
        --多设备登录导致thirdsessionid丢失，此时根据pamainid进行绑定thirdsession
        IF EXISTS(SELECT 'X' FROM wxSmallPrograminfo WITH(NOLOCK) WHERE paMainId = @paMainId)
        BEGIN
            UPDATE wxSmallPrograminfo 
            SET thirdSessionId= @thirdSessionId 
            WHERE paMainId = @paMainId 
	    --更新unionid
	    UPDATE wxFans
    	    SET unionid= (SELECT unionid FROM wxSmallPrograminfo  WHERE thirdSessionId= @thirdSessionId )
    	    WHERE paMainId = @paMainId
        END
        ELSE
        BEGIN
            --多设备，但从来未登录的情况，插入一条
            INSERT INTO wxSmallPrograminfo(thirdSessionId,paMainId,adddate,sessionid)
    VALUES(@thirdSessionId,@paMainId,GETDATE(),'')

        END
    END
END
SET NOCOUNT OFF
GO
/****** Object:  StoredProcedure [dbo].[procwxSmallPrograminfoInsert]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--微信小程序插入openid,sessionId
--harry 2017-7-18
--harry 2018-3-7
CREATE PROCEDURE [dbo].[procwxSmallPrograminfoInsert]
(
    @thirdSessionId VARCHAR(200),
    @openId VARCHAR(50),
    @sessionId VARCHAR(50),
    @unionId VARCHAR(50)
)
AS
SET NOCOUNT ON
BEGIN
    DECLARE @paMainId INT 
    SELECT TOP 1 @paMainId=pamainId FROM wxFans WITH(NOLOCK)
    WHERE UnionId = @unionId 
    ORDER BY ID DESC
    
    
    IF NOT EXISTS(SELECT 'x' FROM paMain WITH(NOLOCK) WHERE id = @paMainId) 
    BEGIN
        SET @paMainId=null
    END 
        IF EXISTS(SELECT 'X' FROM wxSmallPrograminfo WITH(NOLOCK) WHERE openId = @openId)
            UPDATE wxSmallPrograminfo
            SET thirdSessionId=@thirdSessionId,
                paMainId = @paMainId,
                sessionId = @sessionId,
                Adddate = GETDATE(),
                unionId = @unionId
            WHERE openId = @openId
	  
        ELSE
            INSERT INTO wxSmallPrograminfo(thirdSessionId,openId,sessionId,paMainId,unionId,adddate)
            VALUES(@thirdSessionId, @openId, @sessionId, @paMainId,@unionId, GETDATE())
	IF @paMainId != null
	    UPDATE wxFans
	    SET unionid= @unionId
	    WHERE paMainId = @paMainId
END
SET NOCOUNT OFF 
GO
/****** Object:  StoredProcedure [dbo].[procwxSmallPrograminfoSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--微信小程序根据thirdsessionid获取用户信息
--获取信息的同时更新一下关联的pamainid
--harry 2017-7-19
CREATE PROCEDURE [dbo].[procwxSmallPrograminfoSelect]
(
	@thirdSessionId VARCHAR(200) 
)
AS
SET NOCOUNT ON
BEGIN
	DECLARE @paMainId INT
	DECLARE @tmppaMainId INT
	DECLARE @unionId VARCHAR(50)
	
	SELECT @unionId = unionId, @tmppaMainId=pamainId
	FROM wxSmallPrograminfo WITH(NOLOCK)
	WHERE thirdSessionId = @thirdSessionId

	SELECT @paMainId=PaMainID
	FROM wxFans WITH(NOLOCK)
	WHERE unionId= @unionId
	
	IF EXISTS(SELECT 'x' FROM paMain WITH(NOLOCK) WHERE id = @paMainId) 
	BEGIN
		UPDATE wxSmallPrograminfo 
		SET pamainId = @paMainId,
		unionId = @unionId
		WHERE thirdSessionId = @thirdSessionId 
	END
	ELSE IF EXISTS(SELECT 'x' FROM paMain WITH(NOLOCK) WHERE id = @tmppaMainId) 
	BEGIN
		UPDATE wxSmallPrograminfo 
		SET  unionId = @unionId
		WHERE thirdSessionId = @thirdSessionId 
	END
	ELSE 
	BEGIN
		UPDATE wxSmallPrograminfo 
		SET  unionId = @unionId, pamainId =null
		WHERE thirdSessionId = @thirdSessionId 
	END

	SELECT a.*
	FROM wxSmallPrograminfo a WITH(NOLOCK)  
	WHERE a.thirdSessionId = @thirdSessionId
END
SET NOCOUNT OFF 

GO
/****** Object:  StoredProcedure [dbo].[procwxSmallPrograminfoUpdate]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--微信小程序更新pamainid与unionid
--harry 2017-7-19
CREATE PROCEDURE [dbo].[procwxSmallPrograminfoUpdate]
(
	@thirdSessionId VARCHAR(200),
	@unionId VARCHAR(50),
	@openId VARCHAR(50) 
)
AS
SET NOCOUNT ON
BEGIN
	DECLARE @paMainId INT

	SELECT @paMainId=PaMainID
	FROM wxFans WITH(NOLOCK)
	WHERE unionId = @unionId

	IF ISNULL(@paMainId,0)>0
	BEGIN
		UPDATE wxSmallPrograminfo 
		SET pamainId = @paMainId,
		unionId = @unionId
		WHERE thirdSessionId = @thirdSessionId
		AND openId = @openId
	END
	ELSE
	BEGIN
		UPDATE wxSmallPrograminfo 
		SET unionId = @unionId
		WHERE thirdSessionId = @thirdSessionId
		AND openId = @openId
	END
	SELECT @paMainId AS paMainId
END
SET NOCOUNT OFF

GO
/****** Object:  StoredProcedure [dbo].[procWxTemplateByIDSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.01.26
--创建人：Nick
--说明：获取微信模板信息
--#####################################################
CREATE PROCEDURE [dbo].[procWxTemplateByIDSelect]
(
	@TemplateID INT
)
AS
BEGIN
	SELECT * FROM WxTemplate WHERE ID  = @TemplateID
	SELECT * FROM WxTemplatePara WHERE WxTemplateID = @TemplateID
END 

GO
/****** Object:  StoredProcedure [dbo].[procWxTemplateNoByWxTemplateIDSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.01.26
--创建人：Nick
--说明：获取微信模板编号信息
--#####################################################
CREATE PROCEDURE [dbo].[procWxTemplateNoByWxTemplateIDSelect]
(
	@TemplateID INT,
	@WxServiceNoID INT
)
AS
BEGIN
	IF @WxServiceNoID <> 0
	BEGIN
		SELECT * FROM WxTemplateNo WHERE WxTemplateID = @TemplateID AND WxServiceNoID = @WxServiceNoID
	END
	ELSE
	BEGIN
		SELECT * FROM WxTemplateNo WHERE WxTemplateID = @TemplateID 
	END
END 

GO
/****** Object:  StoredProcedure [dbo].[ProcZipPlaceSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2014.10.31
--创建人：John
--说明：获取邮编所在地
--#####################################################
CREATE PROCEDURE [dbo].[ProcZipPlaceSelect]
(
	@Zip VARCHAR(6)
)
AS
BEGIN
	SELECT Top 1 * FROM dcZip WHERE Zip <= @Zip ORDER BY ZIP DESC
END


GO
/****** Object:  StoredProcedure [dbo].[prodcIndustryCategoryByCvMainIDSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.31
--创建人：Nick
--说明：获取行业的类别匹配度
--#####################################################
CREATE PROCEDURE [dbo].[prodcIndustryCategoryByCvMainIDSelect]
(
	@CvMainID VARCHAR(20)
)
AS
BEGIN TRY
	SELECT STUFF((SELECT ',c'+LTRIM(b.CateGoryId) 
	FROM cvIndustry a WITH(NOLOCK),dcIndustryCategory b WITH(NOLOCK) 
	WHERE a.dcIndustryid = b.dcIndustryid 
	AND cvMainid = @CvMainID FOR XML PATH('')),1,1,'') cvIndustryCategory
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[proDoubanMailByIDUpdate]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.03
--创建人：Nick
--说明：修改豆瓣的访问状态
--#####################################################
CREATE PROCEDURE [dbo].[proDoubanMailByIDUpdate]
(
	@ID INT
)
AS
BEGIN TRY
	UPDATE doubanmail SET isclick=1 WHERE id = @ID
	RETURN 1
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[proFpHomepageImageByProvinceIDSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.03
--创建人：Nick
--说明：校园招聘的头条图片
--#####################################################
CREATE PROCEDURE [dbo].[proFpHomepageImageByProvinceIDSelect]
(
	@ProvinceID INT,
	@ImgType INT
)
AS
BEGIN TRY
	SELECT TOP 1 imagefile,imagetype,alt 
	FROM fpHomepageImage WITH(NOLOCK) 
	WHERE dcprovinceid=@ProvinceID 
	AND imagetype=@ImgType 
	ORDER BY AddDate DESC
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[proJobByCaMainIDSELECT]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--根据微信推送内容获取职位id
--harry
--2016-11-21
CREATE PROCEDURE [dbo].[proJobByCaMainIDSELECT]
(
 @pushdate CHAR(8),
 @caMainid INT
)
AS
SET NOCOUNT ON
BEGIN
	SELECT TOP 1 id 
	FROM job  WITH(NOLOCK)
	WHERE (
	SELECT COUNT(1) FROM CaJobCvMatch  WITH(NOLOCK) WHERE jobid=job.id AND Convert(char(8),adddate,112) = @pushdate
	) >0 
	AND camainid= @caMainid ORDER BY refreshdate
END
SET NOCOUNT OFF

GO
/****** Object:  StoredProcedure [dbo].[proLinkByCategorySelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.03
--创建人：Nick
--说明：取友情链接的数据(County IndexNew)
--#####################################################
CREATE PROCEDURE [dbo].[proLinkByCategorySelect]
(
	@ProvinceID INT,
	@Category INT
)
AS
BEGIN TRY
	SELECT TOP 50 * 
	FROM Link 
	WHERE Category = @Category 
	AND VersionId LIKE '' + ltrim(CONVERT(VARCHAR(6),@ProvinceID)) + '%' 
	ORDER BY Id DESC
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[proZhaopinRegionToOurIDSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.31
--创建人：Nick
--说明：由地区名称获取地区ID
--#####################################################
CREATE PROCEDURE [dbo].[proZhaopinRegionToOurIDSelect]
(
	@RegionNameFull VARCHAR(20)
)
AS
BEGIN TRY
	SELECT dbo.ZhaopinRegionToOurID(@RegionNameFull) ID
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[pTemp]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[pTemp]
(
	@d DATETIME
)
AS
BEGIN
	DECLARE @ManagerUserId SMALLINT, @YearMonth INT, @Cnt INT, @BeginTime VARCHAR(50), @EndTime VARCHAR(50),@BeginDay VARCHAR(50),@EndDay VARCHAR(50)
	DECLARE @All NUMERIC(18, 2), @Local NUMERIC(18, 2),@PaRepeat INT,@CpRepeat INT,@PaMobileNumSum INT,@CpMobileNumSum INT

	IF DAY(@D) >= 26 
	BEGIN
		SET @YearMonth = YEAR(DATEADD(m, 1, @D)) * 100 + MONTH(DATEADD(m, 1, @D))
		SET @BeginTime = LTRIM(RTRIM(STR(YEAR(@D)))) + '-' + LTRIM(RTRIM(STR(MONTH(@D)))) + '-26 00:00:00'
		SET @EndTime = LTRIM(RTRIM(STR(YEAR(DATEADD(m, 1, @D))))) + '-' + LTRIM(RTRIM(STR(MONTH(DATEADD(m, 1, @D))))) + '-25 23:59:59'
		SET @BeginDay = LTRIM(RTRIM(STR(YEAR(@D)))) + LTRIM(RTRIM(STR(MONTH(@D)))) + '26'
		SET @EndDay = LTRIM(RTRIM(STR(YEAR(DATEADD(m, 1, @D))))) + LTRIM(RTRIM(STR(MONTH(DATEADD(m, 1, @D))))) + '25'
	END
	ELSE
	BEGIN
		SET @YearMonth = YEAR(@D)*100 + MONTH(@D)  
		SET @BeginTime = LTRIM(RTRIM(STR(YEAR(DATEADD(m, -1, @D))))) + '-' + LTRIM(RTRIM(STR(MONTH(DATEADD(m, -1, @D))))) + '-26 00:00:00'
		SET @EndTime = LTRIM(RTRIM(STR(YEAR(@D)))) + '-' + LTRIM(RTRIM(STR(MONTH(@D)))) + '-25 23:59:59'
		SET @BeginDay = LTRIM(RTRIM(STR(YEAR(DATEADD(m, -1, @D))))) + LTRIM(RTRIM(STR(MONTH(DATEADD(m, -1, @D))))) + '26'
		SET @EndDay = LTRIM(RTRIM(STR(YEAR(@D)))) + LTRIM(RTRIM(STR(MONTH(@D)))) + '25'
	END

	IF LEN(@BeginDay) <> 8
		SET @BeginDay = LEFT(@BeginDay,4) + '0' + RIGHT(@BeginDay,3)
	IF LEN(@EndDay) <> 8
		SET @EndDay = LEFT(@EndDay,4) + '0' + RIGHT(@EndDay,3)

	DECLARE ManagerUser_Record CURSOR FOR 
		SELECT Id FROM ManagerUser WITH(NOLOCK) WHERE DeptId IN(14, 15, 16, 22, 35)
		FOR READ ONLY

	OPEN ManagerUser_Record FETCH NEXT FROM ManagerUser_Record INTO @ManagerUserId
	WHILE @@FETCH_STATUS = 0
	BEGIN
		print(@YearMonth)
		print(@ManagerUserId)
	--	SELECT @Cnt = COUNT(1) FROM InfoAchieve WITH(NOLOCK) WHERE YearMonth = @YearMonth AND infoManager_Id = @ManagerUserId
	--	IF @Cnt = 0
	--		INSERT INTO InfoAchieve(YearMonth, infoManager_Id) VALUES(@YearMonth, @ManagerUserId)

		SELECT @PaMobileNumSum = ISNULL(SUM(mobilenum),0),@CpMobileNumSum = ISNULL(SUM(cpmobilenum),0)
		FROM info_datereport WITH(NOLOCK)
		WHERE countdate >= @BeginDay 
		AND countdate <= @EndDay
		AND infomanager_id = @ManagerUserId 
		
		SELECT @PaRepeat = COUNT(1)
		FROM bsmobilespread WITH(NOLOCK)
		WHERE AddDate BETWEEN @BeginTime AND @EndTime
		AND userType = 1
		AND addman = @ManagerUserId
		AND mobileno IN(
			SELECT a.mobile
			FROM paMain a WITH(NOLOCK),cvMain b WITH(NOLOCK)
			WHERE (registermode = 1 or registermode = 11)
			AND a.ID = b.paMainID
			AND b.valid > 0
			AND AddDate BETWEEN @BeginTime AND @EndTime)
		
		SELECT @CpRepeat = COUNT(1)
		FROM bsmobilespread WITH(NOLOCK)
		WHERE AddDate BETWEEN @BeginTime AND @EndTime
		AND addman = @ManagerUserId
		AND usertype = 0
		AND mobileno IN(
			SELECT mobile 
			FROM caMain a WITH(NOLOCK),cpMain b WITH(NOLOCK)
			WHERE a.cpMainID = b.ID
			AND b.HasLicence = 1
			AND AddDate BETWEEN @BeginTime AND @EndTime) 

		UPDATE InfoAchieve 
		SET paMobileNumSum = @PaMobileNumSum,
			cpMobileNumSum = @CpMobileNumSum,
			paRepeatNum = @PaRepeat,
			cpRepeatNum = @CpRepeat
		WHERE YearMonth = @YearMonth AND infoManager_Id = @ManagerUserId

		FETCH NEXT FROM ManagerUser_Record INTO @ManagerUserId
	END
	CLOSE ManagerUser_Record
	DEALLOCATE ManagerUser_Record
END














GO
/****** Object:  StoredProcedure [dbo].[rmCooperationRecruitmentByProvinceIDSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2014.11.3
--创建人：John
--说明：随机获取既是合作的场馆又是合作的主办方的招聘会的场次,不显示自动生成的招聘会
--#####################################################
CREATE PROCEDURE [dbo].[rmCooperationRecruitmentByProvinceIDSelect]
(
	@ProvinceID VARCHAR(6),
	@intCount INT
)
AS
BEGIN
	SET @ProvinceID = @ProvinceID + '%'
	SELECT TOP (@intCount) * 
	FROM RecruitmentTmp 
	WHERE CityId LIKE @ProvinceID 
	ORDER BY RandNumber
END
GO
/****** Object:  StoredProcedure [dbo].[rmCpAttendByRmIDPaMainIDSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.3
--创建人：John
--说明：返回招聘会的参会企业
--#####################################################
CREATE PROCEDURE [dbo].[rmCpAttendByRmIDPaMainIDSelect]
(
	@RecruitmentID INT,
	@paMainId INT
)
AS
BEGIN
	SELECT TOP 500 a.AddDate, a.StatusDate, a.cpMainId, a.RecruitmentID, b.Name, b.Address, c.ID, b.secondid,
		( 
			SELECT TOP 1 AddDate 
			FROM [MarketDb]..[RmPersonInvitation] 
			WHERE paMainId = @paMainId 
				AND caMainID=c.ID 
				AND RecruitmentID = a.RecruitmentID 
		) AS InviteDate 
	FROM [MarketDb]..[RmCompany] a, [MainDb]..[cpMain] b, [MainDb]..[caMain] c 
	WHERE a.cpMainId = b.id 
		AND a.Status <= 1 
		AND b.id = c.cpMainId 
		AND c.IsPause = 0 
		AND c.IsDelete = 0 
		AND c.AccountType = 1 
		AND a.RecruitmentID = @RecruitmentID 
	ORDER BY a.AddDate DESC
END


GO
/****** Object:  StoredProcedure [dbo].[rmCpInvitedByRmIDPaMainIDSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.3
--创建人：John
--说明：返回招聘会的受邀企业
--#####################################################
CREATE PROCEDURE [dbo].[rmCpInvitedByRmIDPaMainIDSelect]
(
	@RecruitmentID INT,
	@paMainId INT
)
AS
BEGIN
	SELECT TOP 500 a.RecruitmentID, a.AddDate, b.Name AS JobName, y.name AS companyName, y.address, x.cpMainID, y.SecondId,  
		( 
			SELECT TOP 1 AddDate 
			FROM [MarketDb]..[RmPersonInvitation] 
			WHERE RecruitmentID = @RecruitmentID
				AND paMainId = @paMainId 
				AND caMainID = a.caMainID
		) AS myInviteDate 
	FROM [MarketDb]..[RmPersonInvitation] a, [MainDb]..[Job] b, [MainDb]..[caMain] x, [MainDb]..[cpMain] y
	WHERE a.JobID = b.id
		AND a.caMainID = x.id 
		AND x.cpMainID = y.id 
		AND RecruitmentID = @RecruitmentID 
		AND x.IsPause = 0 
		AND x.IsDelete = 0 
		AND x.AccountType = 1 
	ORDER BY a.AddDate DESC
END


GO
/****** Object:  StoredProcedure [dbo].[rmCpJobByCpMainIDSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.3
--创建人：John
--说明：获取企业的招聘职位列表
--#####################################################
CREATE PROCEDURE [dbo].[rmCpJobByCpMainIDSelect]
(
	@cpMainID INT
)
AS
BEGIN
	SELECT a.ID, a.caMainID, a.Name AS jobName, b.Name AS companyName
	FROM [MainDb]..[Job] a, [MainDb]..[cpMain] b
	WHERE a.cpMainID = b.id AND a.IsDelete = 0 AND IssueEND > GETDATE() AND cpMainID = @cpMainID
	ORDER BY a.DisplayNo
END


GO
/****** Object:  StoredProcedure [dbo].[rmCpViewLogByRmIDPaMainIDSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.3
--创建人：John
--说明：返回招聘会的企业浏览记录
--#####################################################
CREATE PROCEDURE [dbo].[rmCpViewLogByRmIDPaMainIDSelect]
(
	@RecruitmentID INT,
	@paMainId INT
)
AS
BEGIN
	SELECT TOP 500 a.AddDate, a.cpMainId, a.RecruitmentID, b.Name, b.Address, c.ID, b.SecondId, 
		( 
			SELECT TOP 1 AddDate 
			FROM [MarketDb]..[RmPersonInvitation] 
			WHERE paMainId = @paMainId 
				AND caMainID=c.ID 
				AND RecruitmentID = a.RecruitmentID 
		) AS InviteDate 
	FROM [MarketDb]..[RmCpViewLog] a, [MainDb]..[cpMain] b,[MainDb]..[caMain] c 
	WHERE a.cpMainId = b.id 
		AND a.RecruitmentID = @RecruitmentID 
		AND b.id = c.cpMainId 
		AND c.IsPause = 0 
		AND c.IsDelete = 0 
		AND c.AccountType=1
	ORDER BY a.AddDate DESC
END


GO
/****** Object:  StoredProcedure [dbo].[rmExJobApplyInsert]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[rmExJobApplyInsert]
(
	@JobID INT,
	@cvMainID INT,
	@Recruitment INT,
	@paMainID INT
)
AS
INSERT INTO ProcLog SELECT 'rmExJobApplyInsert', @cvMainID, GETDATE()
BEGIN
	DECLARE @MaxID AS INT, @IsFilter AS BIT, @cpMainId INT
	SELECT @cpMainId = cpMainId FROM Job WITH(NOLOCK) WHERE Id = @JobId
	
	IF (SELECT COUNT(*)
		FROM exJobApply WITH(NOLOCK)
		WHERE JobID IN(SELECT id FROM Job WITH(NOLOCK)WHERE cpMainId = @cpMainId)
		AND AddDate > GETDATE() - 1
		AND recruitmentid > 0) >	1
		RETURN -1	

	SET @IsFilter = dbo.IsJobApplyFilter(@JobID, @cvMainID)
	BEGIN TRY
		/*
		IF EXISTS(SELECT * FROM exJobApply a,Job b
			WHERE a.cvMainID = @cvMainID 
			AND a.JobID = b.ID 
			AND a.AddDate > GETDATE()-1 
			AND b.cpMainID IN(SELECT cpMainID FROM Job WHERE ID = @JobID))
		BEGIN
			SET @MaxID = -1
		END
		ELSE
		*/
		BEGIN
			IF EXISTS(SELECT ID FROM cvMain WITH(NOLOCK) WHERE paMainID = @paMainID AND ID = @cvMainID)		--是否是有效简历
			BEGIN
				IF EXISTS(SELECT ID FROM ExJobApply WITH(NOLOCK)
						WHERE JobID=@JobID AND cvMainID = @cvMainID AND AddDate > GETDATE()-30)	--是否在30天申请过
					SET @MaxID = -1
				ELSE
				BEGIN
					IF EXISTS(SELECT ID FROM JOB WITH(NOLOCK) WHERE ID = @JobID AND Valid = 0)	--是否是有效职位
						SET @MaxID = 0
					ELSE
					BEGIN
						INSERT INTO ExJobApply(JobID, cvMainID, RecruitmentID, IsFilter)
						VALUES(@JobID, @cvMainID, @Recruitment, @IsFilter)

						SET @MaxID = @@IDENTITY
						UPDATE Job SET ApplyNumber = ApplyNumber + 1 WHERE ID = @JobID

						--Harry Begin
						DECLARE @wxFansId INT
						SELECT @wxFansId = id FROM wxFans WITH(NOLOCK) WHERE paMainId = @paMainId AND [Status] = 2
						IF @wxFansId>0
						BEGIN
							--插入到wxMessageSend表中(6. --企业答复求职者简历)
							INSERT WxMessageSend2(Templatetype, WxFansID, PaMainId, MainTableId, CpMainID, CvMainID, JobId, AddDate)
							SELECT 6, @wxFansId, @paMainId, @MaxID, @cpMainId, @cvMainID, @JobID, GETDATE()
						END
						--Harry End
					END
				END
			END
		END
	END TRY
	BEGIN cATCH
		GOTO ERR
	END CATCH
	RETURN @MaxID
ENd
ERR:
BEGIN
	RETURN -2
END














GO
/****** Object:  StoredProcedure [dbo].[rmMyBespeakListByPaMainIDSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.3
--创建人：John
--说明：招聘会 我的预约列表
--修改：harry 2018-4-11
--增加校园招聘会 
--#####################################################
CREATE PROCEDURE [dbo].[rmMyBespeakListByPaMainIDSelect]
(
	@paMainId INT
)
AS
BEGIN
	CREATE TABLE #t
	(
		pamainId INT,
		recruitmentId INT,
		recruitmentName NVARCHAR(200),
		beginDate DATETIME,
		endDate DATETIME,
		PlaceName NVARCHAR(200),
		bmDate DATETIME,
		checkInDateTime DATETIME
	)
	/*SELECT TOP 500 a.paMainID, b.id, b.RecruitmentName, b.BeginDate, c.Description AS cityName, d.PlaceName,
		( SELECT COUNT(id) FROM [MarketDb]..[RmCompany] WHERE RecruitmentID = b.id AND [Status]<=1 ) AS cpNum, 
		( SELECT COUNT(id) FROM [MarketDb]..[RmPersonInvitation] WHERE RecruitmentID = b.id AND paMainID = @paMainID ) AS myInvitCpNum
	FROM [MarketDb]..[RmPerson] a, [MarketDb]..[Recruitment] b, [MainDb]..[dcRegion] c, [MarketDb]..[RmPlace] d
	WHERE a.RecruitmentID = b.id 
		AND b.CityID = c.id 
		AND b.RecruitmentPlaceId = d.id
		AND a.paMainID = @paMainID
	ORDER BY a.AddDate DESC*/
	
	INSERT INTO #t
	SELECT TOP 500 a.paMainID, b.id, b.RecruitmentName, b.BeginDate, b.EndDate, c.PlaceName, a.AddDate AS bmDate, a.checkInDateTime 
	FROM [MarketDb]..[RmPerson] a, [MarketDb]..[Recruitment] b, [MarketDb]..[RmPlace] c
	WHERE a.RecruitmentID = b.id  
		AND b.RecruitmentPlaceId = c.id
		AND a.paMainID = @paMainID
	ORDER BY a.AddDate DESC

	INSERT INTO #t
	SELECT TOP 500 a.paMainID, b.id*-1, b.Name, b.BeginDate, b.EndDate, (c.Name+ ISNULL(d.Name,'')) AS PlaceName, a.AddDate AS bmDate, a.checkInDateTime 
	FROM [MarketDb]..[RmPerson] a, [wutongguoDb]..[RecruitmentSchool] b LEFT JOIN wutongguodb..dcSchoolArea d 
	ON b.dcschoolAreaId = d.id ,wutongguodb..dcschool c
	WHERE a.RecruitmentID = (b.id*-1)   
		AND a.paMainID = @paMainID
		AND b.dcSchoolId = c.Id
	ORDER BY a.AddDate DESC

	SELECT TOP 500 * 
	FROM #t
	ORDER BY CASE WHEN bmDate is NULL THEN checkInDateTime  END  DESC
END


GO
/****** Object:  StoredProcedure [dbo].[rmMyInviteCpByRmIDPaMainIDSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.3
--创建人：John
--说明：招聘会 我的邀请企业记录
--#####################################################
CREATE PROCEDURE [dbo].[rmMyInviteCpByRmIDPaMainIDSelect]
(
	@RecruitmentID INT,
	@paMainId INT
)
AS
BEGIN
	SELECT TOP 500 a.RecruitmentID, a.ReplyDate, a.AddDate, a.Status, a.JobID, b.Name AS JobName, x.cpMainID, y.name AS companyName, y.SecondId, b.SecondId enjobid,
		( SELECT TOP 1 DeskNo FROM [MarketDb]..[RmCompany] WHERE RecruitmentID = a.RecruitmentID AND cpMainID = x.cpMainID ) AS DeskNo 
	FROM [MarketDb]..[RmPersonInvitation] a, [MainDb]..[Job] b, [MainDb]..[caMain] x, [MainDb]..[cpMain] y
	WHERE a.caMainID = x.id 
		AND x.cpMainID = y.id 
		AND a.JobID = b.ID
		AND a.RecruitmentID = @RecruitmentID 
		AND a.paMainID = @paMainId 
		AND x.IsPause = 0 
		AND x.IsDelete = 0 
		AND x.AccountType = 1
	ORDER BY a.ReplyDate DESC
END


GO
/****** Object:  StoredProcedure [dbo].[rmMyReceivedInvitationByPaMainIDSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.3
--创建人：John
--说明：招聘会 我收到的邀请
--#####################################################
CREATE PROCEDURE [dbo].[rmMyReceivedInvitationByPaMainIDSelect]
(
	@paMainId INT
)
AS
BEGIN
	SELECT TOP 500 b.IssueEnd JobEndDate,a.id, a.RecruitmentID, a.JobID, b.SecondId enjobid, b.Name AS JobName, c.linkman, c.Mobile, e.companyName, e.cpMainID, e.DeskNo,
		c.RecruitmentName, c.BeginDate, c.EndDate, d.PlaceName, d.Address, a.Description AS xdcl, a.AddDate, a.Status, a.ReplyDate ,f.secondid
	FROM [MarketDb]..[RmCompanyInvitation] a, [MainDb]..[Job] b, [MarketDb]..[Recruitment] c, [MarketDb]..[RmPlace] d, [MarketDb]..[RmCompany] e, maindb..cpmain f
	WHERE a.JobID = b.id 
		AND a.RecruitmentID = c.id 
		AND c.RecruitmentPlaceId = d.id 
		AND a.RecruitmentID = e.RecruitmentID 
		AND e.cpMainid = f.id 
		AND a.paMainID = @paMainID  
		AND a.caMainID = b.caMainID 
		AND e.cpMainID=b.cpMainID
	ORDER BY a.AddDate DESC
END


GO
/****** Object:  StoredProcedure [dbo].[rmMyReceivedInvitationNoViewByPaMainIDSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.3
--创建人：John
--说明：招聘会 我收到的邀请还未查看的
--#####################################################
CREATE PROCEDURE [dbo].[rmMyReceivedInvitationNoViewByPaMainIDSelect]
(
	@paMainId INT
)
AS
BEGIN
	SELECT TOP 1 a.id, a.RecruitmentID, a.JobID, b.SecondId enjobid, b.Name AS JobName, c.linkman, c.Mobile, e.companyName, e.cpMainID, e.DeskNo,
		c.RecruitmentName, c.BeginDate, c.EndDate, d.PlaceName, d.Address, a.Description AS xdcl, a.AddDate, a.Status, a.ReplyDate, f.secondid
	FROM [MarketDb]..[RmCompanyInvitation] a, [MainDb]..[Job] b,[MarketDb]..[Recruitment] c, [MarketDb]..[RmPlace] d, [MarketDb]..[RmCompany] e, maindb..cpmain f
	WHERE a.JobID = b.id 
		AND a.RecruitmentID = c.id 
		AND c.RecruitmentPlaceId = d.id 
		AND a.RecruitmentID = e.RecruitmentID 
		AND e.cpMainid = f.id 
		AND a.paMainID = @paMainID  
		AND a.caMainID = b.caMainID 
		AND e.cpMainID = b.cpMainID
		AND a.ViewDate IS NULL 
		AND c.begindate > GETDATE()
	ORDER BY a.AddDate DESC
END


GO
/****** Object:  StoredProcedure [dbo].[rmPaFavorateSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.3
--创建人：John
--说明：获取职位收藏夹列表
--#####################################################
CREATE PROCEDURE [dbo].[rmPaFavorateSelect]
(
	@StrWhere VARCHAR(500),
	@OrderBy VARCHAR(50)
)
AS
BEGIN
	DECLARE @SQL VARCHAR(2000)
	SET @SQL = 'SELECT a.ID,a.paMainID,a.JobID,a.AddDate,a.Remark,b.Name AS JobName,b.IssueDate,b.IssueEND,b.dcRegionID,b.IsDelete, b.caMainID, b.SecondId, 
		c.Name AS cpName,c.ID AS cpID,c.HasLicence,c.IsAgent, c.Membertype, b.dcSalaryID , d.Description AS SalaryCount ,
		ISNULL((SELECT IsOnline FROM caOnline WHERE caMainId =b.caMainID), 0) AS IsOnline
	FROM [MainDb]..[paFavorate] a WITH(NOLOCK) 
		Inner Join [MainDb]..[Job] b WITH(NOLOCK) ON a.JobID=b.ID 
		Inner Join [MainDb]..[cpMain] c WITH(NOLOCK) ON b.cpMainID=c.ID 
		Inner Join [MainDb]..[dcSalary] d WITH(NOLOCK) ON b.dcSalaryID = d.id
	WHERE '
	SET @SQL = @SQL + @StrWhere + ' ORDER BY ' + @OrderBy
	EXEC(@SQL)
END


GO
/****** Object:  StoredProcedure [dbo].[rmPaIsAttendRmSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.3
--创建人：John
--说明：paMainID 是否参加该场招聘会
--#####################################################
CREATE PROCEDURE [dbo].[rmPaIsAttendRmSelect]
(
	@RecruitmentID INT,
	@paMainId INT
)
AS
BEGIN
	SELECT ID FROM [MarketDb]..[RmPerson] WHERE RecruitmentID = @RecruitmentID AND paMainID = @paMainID
END


GO
/****** Object:  StoredProcedure [dbo].[RmPaMainByMobileInsert]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[RmPaMainByMobileInsert]
(
	@UserName VARCHAR(50),
	@dcProvinceID SMALLINT,
	@Mobile VARCHAR(20),
	@SubSiteUrl VARCHAR(200)
)
AS
BEGIN
	--判断90天内该手机号有无认证过
	IF EXISTS(SELECT 'X' FROM marketdb..RmInvitationCode WHERE Mobile=@Mobile AND AddDate>GETDATE()-90)
	BEGIN
		INSERT INTO SmsMessageLog(SendMan,Mobile,Msg,MsgType,IsCat) VALUES
		(1,@Mobile,'您在90天内参加过简历认证，不能重复参加',199,0)
		RETURN
	END
	
	--生成邀请码
	DECLARE @Code VARCHAR(6)
	WHILE 1=1
	BEGIN
		SET @Code=CONVERT(VARCHAR(6),RIGHT(CAST(RAND()*1000000 AS INT),6))
		SET @Code=LEFT(@Code,6)
		IF LEN(@Code) = 5
			SET @Code='0'+@Code
		ELSE IF LEN(@Code) = 4
			SET @Code='00'+@Code
		ELSE IF LEN(@Code) = 3
			SET @Code='000'+@Code
		ELSE IF LEN(@Code) = 2
			SET @Code='0000'+@Code
		
		IF EXISTS(SELECT 'X' FROM marketdb..RmInvitationCode WHERE Code=@Code)
			CONTINUE
		ELSE
			BREAK
	END
	
	--生成paMainID
	DECLARE @paMainID INT
	EXEC @paMainID=pcPaMainInsert @UserName,'$2a$08$wCjRdWcKgup74i.L3sk6OOlCAQ/qAPmAWE4ZMzpJL7K85N0.x/WIu',@dcProvinceID,'校园简历短信注册',0,0
	IF @paMainID=-2
		SELECT @paMainID=ID,@UserName=UserName FROM paMain WHERE Email=@UserName
		
	--插入到RmInvitationCode
	DECLARE @MaxId INT
	INSERT INTO marketdb..RmInvitationCode(Mobile,RmProjectID,Code,paMainID) VALUES(@Mobile,1,@Code,@paMainID)
	SET @MaxId = @@IDENTITY
	
	--更改paMain的信息
	UPDATE paMain Set Mobile=@Mobile,Password='$2a$08$wCjRdWcKgup74i.L3sk6OOlCAQ/qAPmAWE4ZMzpJL7K85N0.x/WIu' 
	WHERE ID=@paMainID
	
	--发送短信
	DECLARE @Msg VARCHAR(200)
	SET @Msg='用户名'+@UserName+'密码123456邀请码'+@Code+'。请登录'+@SubSiteUrl+'完善简历'
	INSERT INTO SmsMessageLog(SendMan,paMainId,Mobile,Msg,MsgType,IsCat) VALUES
		(1,@paMainID,@Mobile,@Msg,117,0)
END














GO
/****** Object:  StoredProcedure [dbo].[rmRecommendCvSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rmRecommendCvSelect]
(
	@RecruitmentID INT
)
AS
BEGIN
	SELECT a.ID cvMainID,d.*,a.Degree,a.dcMajorID,e.FullName AtPlace
	FROM cvMain a WITH(NOLOCK)
		INNER JOIN paMain d WITH(NOLOCK) ON a.paMainID=d.ID
		INNER JOIN marketdb..RmInvitationCode b WITH(NOLOCK) ON a.paMainID=b.paMainID AND b.Valid=1
		INNER JOIN marketdb..RmProject c WITH(NOLOCK) ON b.RmProjectID=c.ID
		INNER JOIN dcRegion e WITH(NOLOCK) ON d.LivePlace=e.ID
	WHERE c.RecruitmentID=@RecruitmentID AND a.Valid=1
END














GO
/****** Object:  StoredProcedure [dbo].[rmRecruitmentByCpMainIDSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.10.30
--创建人：Nick
--说明：获取个人会员中心首页的招聘会的数据
--#####################################################
CREATE PROCEDURE [dbo].[rmRecruitmentByCpMainIDSelect]
(
	@ProvinceID VARCHAR(4),
	@cpMainID VARCHAR(20)
)
AS
BEGIN TRY
	SELECT TOP 6 a.ID,RecruitmentName,BeginDate,PlaceName ,
	( 
		SELECT TOP 1 ltrim(str(status))+'$$'+isnull(deskno,'test')+'$$'+isnull(CONVERT(varchar,StatusDate,120),'test') 
		FROM marketdb..RmCompany 
		WHERE RecruitmentID = a.Id 
		AND cpMainID = @cpMainID 
	) IsAttend  
	From marketdb..Recruitment a WITH(NOLOCK),marketdb..RmPlace b WITH(NOLOCK) 
	WHERE RecruitmentPlaceID=b.ID 
	AND CityID LIKE @ProvinceID+'%' 
	AND EndDate > GetDate() 
	AND IsPause=0
	ORDER BY IsCompanyTop DESC,orderby, a.BeginDate
END TRY
BEGIN CATCH
	RETURN 0
END CATCH

GO
/****** Object:  StoredProcedure [dbo].[rmRecruitmentByIDSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.3
--创建人：John
--说明：通过招聘会id获取招聘会详细信息
--#####################################################
CREATE PROCEDURE [dbo].[rmRecruitmentByIDSelect]
(
	@RecruitmentID INT
)
AS
BEGIN
	SELECT a.*, c.PlaceName, c.[Address] ,b.[Description] City, c.MapbarID, c.Lng, c.Lat, c.BusLine, CreditRating,
	 'www.' + ProvinceDomain SiteUrl, d.ID ProvinceID, a.RecruitmentDeptId 
	 FROM Recruitment a, dcRegion b, RecruitmentPlace c ,dcProvince d, recruitmentdept e 
	 WHERE e.id = a.recruitmentdeptid 
		AND b.ID = c.dcRegionID 
		AND a.RecruitmentPlaceId = c.id 
		AND d.ID = LEFT(a.CityID,2) 
		AND a.ID = @RecruitmentID
END


GO
/****** Object:  StoredProcedure [dbo].[rmRecruitmentByIsSchoolUpdate]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rmRecruitmentByIsSchoolUpdate]
(
	@ID INT,
	@IsSchool BIT
)
AS
SET NOCOUNT ON
UPDATE marketdb..Recruitment SET IsSchool = @IsSchool WHERE ID=@ID
SET NOCOUNT OFF

GO
/****** Object:  StoredProcedure [dbo].[rmRecruitmentByPlaceIDAndDateSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.3
--创建人：John
--说明：判断当天招聘会是否重复
--#####################################################
CREATE PROCEDURE [dbo].[rmRecruitmentByPlaceIDAndDateSelect]
(
	@PlaceID INT,
	@rmDate1 VARCHAR(20),
	@rmDate2 VARCHAR(20)
)
AS
BEGIN
	SELECT * 
	FROM Recruitment WITH(NOLOCK)
	WHERE recruitmentplaceid = @PlaceID 
	AND enddate BETWEEN @rmDate1 AND @rmDate2
	AND EXISTS(SELECT 'x' FROM RecruitmentDept WITH(NOLOCK) WHERE id = Recruitment.RecruitmentDeptId)
END

GO
/****** Object:  StoredProcedure [dbo].[rmRecruitmentCpMainSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rmRecruitmentCpMainSelect]
(
	@RecruitmentID INT
)
AS
BEGIN
	select a.cpmainid,a.adddate,b.name,c.name caname,b.address,c.mobile,c.telephone from recruitmentcpmain a,cpmain b,camain c where a.cpmainid=b.id and b.id=c.cpmainid and c.AccountType=1 and RecruitmentID=@RecruitmentID ORDER BY a.AddDate DESC
END














GO
/****** Object:  StoredProcedure [dbo].[rmRecruitmentDelete]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.3
--创建人：John
--说明：删除招聘会信息
--#####################################################
CREATE PROCEDURE [dbo].[rmRecruitmentDelete]
(
	@strID INT,
	@strID2 INT,
	@rmID INT
)
AS
BEGIN
	DELETE FROM recruitment WHERE (id = @strID OR MainID = @strID2) AND recruitmentdeptid = @rmID
END


GO
/****** Object:  StoredProcedure [dbo].[RmRecruitmentDeptInsert]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[RmRecruitmentDeptInsert]
(
	@Username VARCHAR(20),
	@Password VARCHAR(20),
	@DeptName VARCHAR(100),
	@LinkMan VARCHAR(20),
	@Mobile VARCHAR(11),
	@Email VARCHAR(50),
	@QQ VARCHAR(10),
	@dcProvinceID SMALLINT
)
AS
BEGIN TRY
	SET @Username = dbo.TextTrim(@Username)
	SET @DeptName = dbo.TextTrim(@DeptName)
	SET @LinkMan = dbo.TextTrim(@LinkMan)
	SET @Mobile = dbo.TextTrim(@Mobile)
	SET @Email = dbo.TextTrim(@Email)
	SET @QQ = dbo.TextTrim(@QQ)
 
	IF EXISTS(SELECT 'X' FROM RecruitmentDept WITH(NOLOCK) WHERE Username = @Username)
		RETURN -2
	IF EXISTS(SELECT 'X' FROM RecruitmentDept WITH(NOLOCK) WHERE Email = @Email)
		RETURN -3
	IF EXISTS(SELECT 'X' FROM RecruitmentDept WITH(NOLOCK) WHERE Mobile = @Mobile)
		RETURN -4
	IF EXISTS(SELECT 'X' FROM RecruitmentDept WITH(NOLOCK) WHERE QQ = @QQ)
		RETURN -5
 
	DECLARE @MaxId AS INT
	INSERT INTO RecruitmentDept(dcProvinceID,Username, Password, DeptName, LinkMan, Mobile, Email, QQ)
			VALUES(@dcProvinceID, @Username, @Password, @DeptName, @LinkMan, @Mobile, @Email, @QQ)
	SET @MaxId = @@IDENTITY
	RETURN @MaxID
END TRY
BEGIN CATCH
	RETURN -1
END CATCH














GO
/****** Object:  StoredProcedure [dbo].[rmRecruitmentDeptIsExist]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rmRecruitmentDeptIsExist]
(
	@Account VARCHAR(100),
	@Type TINYINT,
	@ID INT
)
AS
BEGIN
	IF @ID = 0
	BEGIN
		IF @Type = 1
		BEGIN
			IF EXISTS(SELECT ID FROM RecruitmentDept WITH(NOLOCK) WHERE Username = @Account)
				RETURN 1
			ELSE
				RETURN 0
		END
		IF @Type = 2
		BEGIN
			IF EXISTS(SELECT ID FROM RecruitmentDept WITH(NOLOCK) WHERE DeptName = @Account)
				RETURN 1
			ELSE
				RETURN 0
		END
		IF @Type = 3
		BEGIN
			IF EXISTS(SELECT ID FROM RecruitmentDept WITH(NOLOCK) WHERE Email = @Account)
				RETURN 1
			ELSE
				RETURN 0
		END
		IF @Type = 4
		BEGIN
			IF EXISTS(SELECT ID FROM RecruitmentDept WITH(NOLOCK) WHERE Mobile = @Account)
				RETURN 1
			ELSE
				RETURN 0
		END
		IF @Type = 5
		BEGIN
			IF EXISTS(SELECT ID FROM RecruitmentDept WITH(NOLOCK) WHERE QQ = @Account)
				RETURN 1
			ELSE
				RETURN 0
		END
	END
	ELSE
	BEGIN
		IF @Type = 1
		BEGIN
			IF EXISTS(SELECT ID FROM RecruitmentDept WITH(NOLOCK) WHERE Username = @Account AND ID <> @ID)
				RETURN 1
			ELSE
				RETURN 0
		END
		IF @Type = 2
		BEGIN
			IF EXISTS(SELECT ID FROM RecruitmentDept WITH(NOLOCK) WHERE DeptName = @Account AND ID <> @ID)
				RETURN 1
			ELSE
				RETURN 0
		END
		IF @Type = 3
		BEGIN
			IF EXISTS(SELECT ID FROM RecruitmentDept WITH(NOLOCK) WHERE Email = @Account AND ID <> @ID)
				RETURN 1
			ELSE
				RETURN 0
		END
		IF @Type = 4
		BEGIN
			IF EXISTS(SELECT ID FROM RecruitmentDept WITH(NOLOCK) WHERE Mobile = @Account AND ID <> @ID)
				RETURN 1
			ELSE
				RETURN 0
		END
		IF @Type = 5
		BEGIN
			IF EXISTS(SELECT ID FROM RecruitmentDept WITH(NOLOCK) WHERE QQ = @Account AND ID <> @ID)
				RETURN 1
			ELSE
				RETURN 0
		END
	END
END














GO
/****** Object:  StoredProcedure [dbo].[rmRecruitmentDeptPasswordUpdate]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rmRecruitmentDeptPasswordUpdate]
(
	@ID INT,
	@Password VARCHAR(20),
	@Old VARCHAR(20)
)
AS
BEGIN TRY
	IF EXISTS(SELECT 'X' FROM rmDept WHERE ID=@ID)
	BEGIN
		DECLARE @OldPwd AS VARCHAR(20)
		SELECT @OldPwd=Password FROM rmDept WHERE ID=@ID
		IF @Old=@OldPwd
		BEGIN
			UPDATE rmDept SET Password=@Password WHERE ID=@ID
			RETURN 1
		END
		ELSE
			RETURN -1
	END
	ELSE
		RETURN -2
END TRY
BEGIN CATCH
	RETURN 0
END CATCH











GO
/****** Object:  StoredProcedure [dbo].[rmRecruitmentDeptSelectByID]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rmRecruitmentDeptSelectByID]
(
	@ID INT
)
AS
BEGIN
	SELECT * FROM RecruitmentDept WHERE ID=@ID
END














GO
/****** Object:  StoredProcedure [dbo].[rmRecruitmentDeptSelectByLogin]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rmRecruitmentDeptSelectByLogin]
(
	@Username VARCHAR(20),
	@Password VARCHAR(20)
)
AS
BEGIN
	SELECT * FROM RecruitmentDept WHERE Username=@Username AND Password=@Password AND IsPause=0
END














GO
/****** Object:  StoredProcedure [dbo].[rmRecruitmentDeptUpdate]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rmRecruitmentDeptUpdate]
(
	@ID INT,
	@DeptName VARCHAR(100),
	@LinkMan VARCHAR(20),
	@Mobile VARCHAR(11),
	@Telephone VARCHAR(20),
	@Fax VARCHAR(20),
	@Email VARCHAR(50),
	@QQ VARCHAR(10),
	@LinkAddress VARCHAR(50),
	@Brief NVARCHAR(2000)
)
AS
BEGIN TRY
	SET @DeptName = dbo.TextTrim(@DeptName)
	SET @LinkMan = dbo.TextTrim(@LinkMan)
	SET @Mobile = dbo.TextTrim(@Mobile)
	SET @Telephone = dbo.TextTrim(@Telephone)
	SET @Fax = dbo.TextTrim(@Fax)
	SET @Email = dbo.TextTrim(@Email)
	SET @QQ = dbo.TextTrim(@QQ)
	SET @LinkAddress = dbo.TextTrim(@LinkAddress)
	SET @Brief = dbo.TextTrim(@Brief)
 
	IF EXISTS(SELECT 'X' FROM RecruitmentDept WITH(NOLOCK) WHERE Email = @Email AND ID <> @ID)
		RETURN -3
	IF EXISTS(SELECT 'X' FROM RecruitmentDept WITH(NOLOCK) WHERE Mobile = @Mobile AND ID <> @ID)
		RETURN -4
	IF EXISTS(SELECT 'X' FROM RecruitmentDept WITH(NOLOCK) WHERE QQ = @QQ AND ID <> @ID)
		RETURN -5
 
	UPDATE RecruitmentDept SET DeptName=@DeptName,LinkMan=@LinkMan,Mobile=@Mobile,Telephone=@Telephone,
		Fax=@Fax,Email=@Email,QQ=@QQ,LinkAddress=@LinkAddress,Brief=@Brief
	WHERE ID=@ID

	--2013-05-13 Peter 添加如果修改联系人信息，联动修改现有的招聘会的联系人信息
	UPDATE Recruitment SET LinkMan=@LinkMan,Mobile=@Mobile,Telephone=@Telephone,
		Fax=@Fax,Email=@Email,QQ=@QQ
	WHERE RecruitmentDeptId=@ID

	RETURN @ID
END TRY
BEGIN CATCH
	RETURN -1
END CATCH








GO
/****** Object:  StoredProcedure [dbo].[rmRecruitmentDeptUsernameUpdate]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rmRecruitmentDeptUsernameUpdate]
(
	@ID INT,
	@Password VARCHAR(20),
	@Username VARCHAR(20)
)
AS
BEGIN TRY
	IF EXISTS(SELECT 'X' FROM rmDept WHERE ID=@ID)
	BEGIN
	        IF NOT EXISTS(SELECT 'X' FROM rmDept WHERE Username=@Username)
	        BEGIN
		         DECLARE @OldPwd AS VARCHAR(20)
		         SELECT @OldPwd=Password FROM rmDept WHERE ID=@ID
		         IF @Password=@OldPwd
		         BEGIN
			       UPDATE rmDept SET Username=@Username WHERE ID=@ID
			       RETURN 1
		         END
		ELSE
			 RETURN -1
	        END
	        ELSE
		         RETURN -2
	END
	ELSE
		RETURN -3
END TRY
BEGIN CATCH
	RETURN 0
END CATCH











GO
/****** Object:  StoredProcedure [dbo].[rmRecruitmentPaMainSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rmRecruitmentPaMainSelect]
(
	@RecruitmentID INT
)
AS
BEGIN
	SELECT b.BirthDay,a.paMainID,b.Name,b.Gender,a.AddDate,c.FullName AtPlace FROM RecruitmentPaMain a,PaMain b,dcRegion c WHERE a.paMainID=b.ID AND a.RecruitmentID=@RecruitmentID  AND b.LivePlace=c.ID ORDER BY a.AddDate DESC
END








GO
/****** Object:  StoredProcedure [dbo].[rmRecruitmentPlaceByRegionIDResumeSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--修改harry 修改ptworktypeid= 
--2018-4-9
--nick 2013-11-25
CREATE PROCEDURE [dbo].[rmRecruitmentPlaceByRegionIDResumeSelect] 
(
	@RegionID VARCHAR(6)  
)
AS 
BEGIN
	SELECT RecruitmentID INTO #t1 FROM MarketDb..ptWorkAppoint 
	WHERE ptWorkPriceId IN(select Id from MarketDb..ptworkprice where ptworktypeid IN(51,92))
	AND StartDate > GETDATE() - 90
	AND ValidNumber > 0

	SELECT DISTINCT c.Id, c.PlaceName
	FROM #t1 a,
		RecruitMent b,
		RecruitmentPlace c
	WHERE a.Recruitmentid = b.Id
	AND b.RecruitmentPlaceId = c.Id
	AND c.dcRegionId LIKE @RegionID + '%'
END

GO
/****** Object:  StoredProcedure [dbo].[rmRecruitmentPlaceByRegionIDResumeSelect0630]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--nick 2013-11-25
CREATE PROCEDURE [dbo].[rmRecruitmentPlaceByRegionIDResumeSelect0630] 
(
	@RegionID VARCHAR(6)  
)
AS 
BEGIN 
	SELECT DISTINCT RmProjectID INTO #t1
	FROM marketdb..RmInvitationCode 
	WHERE AddDate>GETDATE()-90 AND Valid = 1

	SELECT ID,RecruitmentPlaceId INTO #t2
	FROM Recruitment 
	WHERE CityID LIKE @RegionID+'%'

	SELECT ID,PlaceName 
	FROM RecruitmentPlace e,(
		SELECT d.id placeid
		FROM #t1 a,
		marketdb..RmProject b ,#t2 c ,RecruitmentPlace d
		WHERE a.RmProjectID=b.ID  
		AND b.RecruitmentID = c.ID 
		AND c.RecruitmentPlaceId = d.ID and d.dcRegionID LIKE @RegionID+'%' 
		GROUP BY d.id
	) f
	WHERE e.ID=f.Placeid
	AND LEN(e.VerifyMan)>0 AND e.IsCampus=0 
	AND (e.isBreak<>1 OR e.isBreak IS NULL) 
	ORDER BY e.dcRegionID,e.PlaceName 
END










GO
/****** Object:  StoredProcedure [dbo].[rmRecruitmentPlaceByRegionIDSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--修改：harry2018-4-16
--增加学校显示
--rmRecruitmentPlaceByRegionIDSelect 3201
CREATE PROCEDURE [dbo].[rmRecruitmentPlaceByRegionIDSelect] 
(
	@RegionID VARCHAR(6)
)
AS
BEGIN 
	/*SELECT * 
	FROM SynRecruitmentPlaceTmp WITH(NOLOCK) 
	WHERE dcRegionId LIKE @RegionID + '%'
	ORDER BY PlaceName*/
	CREATE TABLE #t
	(
		 id INT,
		placeName NVARCHAR(100),
		lng CHAR(20),
		lat CHAR(20),
		Address NVARCHAR(100),
		BusLine NVARCHAR(2000)
	)
	INSERT INTO #t
	SELECT Id,placeName,lng, lat, Address, BusLine
	FROM SynRecruitmentPlaceTmp WITH(NOLOCK) 
	WHERE dcRegionId LIKE Convert(varchar(6),@RegionID) + '%'

	INSERT INTO #t
	SELECT b.id*-1, b.Name+ISNULL(c.Name,''), CASE WHEN ISNULL(a.dcSchoolAreaId,0) =0 THEN  b.lng  ELSE c.Lng END AS lng,
CASE WHEN ISNULL(a.dcSchoolAreaId,0) =0 THEN  b.lat  ELSE c.lat END AS lat,  CASE WHEN ISNULL(a.dcSchoolAreaId,0)=0 THEN  b.address  ELSE c.address END AS address,''AS busline
	FROM marketdb..rmDept d WITH(NOLOCK)
        LEFT JOIN (SELECT DISTINCT dcSchoolId, dcSchoolAreaId,recruitmentDeptId FROm wutongguodb..recruitmentSchool GROUP BY dcSchoolId,dcSchoolAreaId,recruitmentDeptId)AS  a
        ON d.Id =a.recruitmentDeptId
	LEFT JOIN wutongguodb..dcSchool  b WITH(NOLOCK)
	ON a.dcSchoolId=b.Id
	LEFT  JOIN  wutongguodb..dcSchoolArea c WITH(NOLOCK)
	ON a.dcSchoolAreaId = c.Id
	WHERE d.isSchool =1 AND a.RecruitmentDeptid= d.ID 
	AND b.dcRegionId LIKE  Convert(varchar(6),@RegionID) + '%'
       SELECT * FROM #t
       drop table #t
END


GO
/****** Object:  StoredProcedure [dbo].[rmRecruitmentPlaceNameByIDSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.3
--创建人：John
--说明：根据场馆ID得到场馆名字
--#####################################################
CREATE PROCEDURE [dbo].[rmRecruitmentPlaceNameByIDSelect]
(
	@PlaceID INT
)
AS
BEGIN
	SELECT PlaceName FROM RecruitmentPlace WHERE ID = @PlaceID
END


GO
/****** Object:  StoredProcedure [dbo].[rmRecruitmentPlaceSave]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rmRecruitmentPlaceSave]
(
	@RegionID VARCHAR(6),
	@PlaceName NVARCHAR(50)
)
AS
BEGIN TRY
	DECLARE @MaxID AS INT
	INSERT INTO RecruitmentPlace(dcRegionID,PlaceName) VALUES(@RegionID,@PlaceName)
	SET @MaxId = @@IDENTITY
	RETURN @MaxId
END TRY
BEGIN CATCH
	RETURN 0
END CATCH














GO
/****** Object:  StoredProcedure [dbo].[rmRecruitmentPlaceSelectByID]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rmRecruitmentPlaceSelectByID]
(
	@ID INT
)
AS
BEGIN 
	SELECT * FROM RecruitmentPlace WHERE ID=@ID
END














GO
/****** Object:  StoredProcedure [dbo].[rmRecruitmentPlaceSelectByRegionID]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rmRecruitmentPlaceSelectByRegionID] 
(
	@RegionID VARCHAR(6)
)
AS
BEGIN
	SELECT * FROM marketdb..RmPlace 
	WHERE dcRegionID like @RegionID + '%' 
	AND LEN(VerifyMan) > 0 
	AND IsCampus = 0
	AND (isBreak<>1 or isBreak is null)
END










GO
/****** Object:  StoredProcedure [dbo].[rmRecruitmentProvinceScriptSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.3
--创建人：John
--说明：获取招聘会的那个Script
--#####################################################
CREATE PROCEDURE [dbo].[rmRecruitmentProvinceScriptSelect]
(
	@ProvinceID INT
)
AS
BEGIN
	SELECT ID, ProvinceName, ProvinceDomain 
	FROM dcprovince 
	ORDER BY 
	CASE id 
		WHEN @ProvinceID THEN 1 
		WHEN 32 THEN 2 
		WHEN 10 THEN 3 
		WHEN 30 THEN 4 
		WHEN 12 THEN 5 
		WHEN 11 THEN 6 
		WHEN 72 THEN 7 
		WHEN 31 THEN 8 
		WHEN 35 THEN 9 
		WHEN 64 THEN 1000 
		WHEN 81 THEN 1001 
	ELSE id
	END
END


GO
/****** Object:  StoredProcedure [dbo].[rmRecruitmentRecordByRmIDSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.3
--创建人：John
--说明：取招聘会标题信息
--#####################################################
CREATE PROCEDURE [dbo].[rmRecruitmentRecordByRmIDSelect]
(
	@RecruitmentID INT
)
AS
BEGIN
	SELECT TOP 1 a.RecruitmentName,a.BeginDate, a.RecruitmentPlaceId, b.PlaceName 
	FROM [MarketDb]..[Recruitment] a, [MarketDb]..[RmPlace] b 
	WHERE a.RecruitmentPlaceId = b.Id AND a.Id = @RecruitmentID 
END


GO
/****** Object:  StoredProcedure [dbo].[rmRecruitmentSave]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rmRecruitmentSave]
(
	@ID INT,
	@RecruitmentDeptId INT,
	@RecruitmentName NVARCHAR(100),
	@BeginDate SMALLDATETIME,
	@EndDate SMALLDATETIME,
	@CityID VARCHAR(4),
	@RecruitmentPlaceId INT,
	@LinkMan NVARCHAR(20),
	@Mobile VARCHAR(11),
	@Telephone VARCHAR(20),
	@Fax VARCHAR(20),
	@Email VARCHAR(50),
	@QQ VARCHAR(10),
	@Brief NVARCHAR(2000),
	@ManageruserID INT
)
AS
BEGIN TRY
	DECLARE @MaxId AS INT
	DECLARE @RmNameA AS NVARCHAR(100)
	DECLARE @RmNameB AS NVARCHAR(100)
	DECLARE @RmNameC AS NVARCHAR(100)
	DECLARE @RmNameD AS NVARCHAR(100)
	DECLARE @CityName AS NVARCHAR(100)
	DECLARE @PlaceName AS NVARCHAR(100)
	SET @RecruitmentName = dbo.TextTrim(@RecruitmentName)
	SET @CityID = dbo.TextTrim(@CityID)
	SET @LinkMan = dbo.TextTrim(@LinkMan)
	SET @Mobile = dbo.TextTrim(@Mobile)
	SET @Telephone = dbo.TextTrim(@Telephone)
	SET @Fax = dbo.TextTrim(@Fax)
	SET @Email = dbo.TextTrim(@Email)
	SET @QQ = dbo.TextTrim(@QQ)
	SET @Brief = dbo.TextTrim(@Brief)
	
	IF @ID = 0
	BEGIN
		IF @ManageruserID = 0
		BEGIN		
			INSERT INTO Recruitment(RecruitmentDeptId,RecruitmentName,BeginDate,EndDate,CityID,RecruitmentPlaceId,LinkMan,Mobile,Telephone,Fax,Email,QQ,Brief) 
			VALUES(@RecruitmentDeptId,@RecruitmentName,@BeginDate,@EndDate,@CityID,@RecruitmentPlaceId,@LinkMan,@Mobile,@Telephone,@Fax,@Email,@QQ,@Brief)
			SET @MaxId = @@IDENTITY
		END
		ELSE
		BEGIN
			INSERT INTO Recruitment(RecruitmentDeptId,RecruitmentName,BeginDate,EndDate,CityID,RecruitmentPlaceId,LinkMan,Mobile,Telephone,Fax,Email,QQ,Brief,ManageruserID) 
			VALUES(@RecruitmentDeptId,@RecruitmentName,@BeginDate,@EndDate,@CityID,@RecruitmentPlaceId,@LinkMan,@Mobile,@Telephone,@Fax,@Email,@QQ,@Brief,@ManageruserID)
			SET @MaxId = @@IDENTITY
		END
		-- Max 2013-06-03 添加两个别名招聘会
		SELECT @PlaceName = PlaceName FROM RecruitmentPlace WHERE ID = @RecruitmentPlaceId
		SELECT @CityName = Description FROM DcRegion WHERE ID = @CityID
		-- 组合名称
		SELECT @RmNameA = CONVERT(NVARCHAR(2),DATEPART(m,@BeginDate)) + '月' + CONVERT(NVARCHAR(2),DATEPART(d,@BeginDate))+ '日' + @PlaceName + '招聘会'
		SELECT @RmNameB = CONVERT(NVARCHAR(2),DATEPART(m,@BeginDate)) + '月' + CONVERT(NVARCHAR(2),DATEPART(d,@BeginDate))+ '日' + @CityName + '人才招聘会（' + @PlaceName + '）'
		SELECT @RmNameC = CONVERT(NVARCHAR(2),DATEPART(m,@BeginDate)) + '月' + CONVERT(NVARCHAR(2),DATEPART(d,@BeginDate))+ '日' + @PlaceName + '交流会'
		SELECT @RmNameD = CONVERT(NVARCHAR(2),DATEPART(m,@BeginDate)) + '月' + CONVERT(NVARCHAR(2),DATEPART(d,@BeginDate))+ '日' + @CityName + '人才交流会（' + @PlaceName + '）'
		/*
		-- 插入表 orderby 为500
		INSERT INTO Recruitment(RecruitmentDeptId,RecruitmentName,BeginDate,EndDate,CityID,RecruitmentPlaceId,LinkMan,Mobile,Telephone,Fax,Email,QQ,Brief,MainID,OrderBy,InnerOrderby,IsPause) 
		VALUES(@RecruitmentDeptId,@RmNameA,@BeginDate,@EndDate,@CityID,@RecruitmentPlaceId,@LinkMan,@Mobile,@Telephone,@Fax,@Email,@QQ,@Brief,@MaxId,500,500,1)

		INSERT INTO Recruitment(RecruitmentDeptId,RecruitmentName,BeginDate,EndDate,CityID,RecruitmentPlaceId,LinkMan,Mobile,Telephone,Fax,Email,QQ,Brief,MainID,OrderBy,InnerOrderby,IsPause) 
		VALUES(@RecruitmentDeptId,@RmNameA,@BeginDate,@EndDate,@CityID,@RecruitmentPlaceId,@LinkMan,@Mobile,@Telephone,@Fax,@Email,@QQ,@Brief,@MaxId,501,501,1)

		INSERT INTO Recruitment(RecruitmentDeptId,RecruitmentName,BeginDate,EndDate,CityID,RecruitmentPlaceId,LinkMan,Mobile,Telephone,Fax,Email,QQ,Brief,MainID,OrderBy,InnerOrderby,IsPause) 
		VALUES(@RecruitmentDeptId,@RmNameB,@BeginDate,@EndDate,@CityID,@RecruitmentPlaceId,@LinkMan,@Mobile,@Telephone,@Fax,@Email,@QQ,@Brief,@MaxId,500,500,1)

		INSERT INTO Recruitment(RecruitmentDeptId,RecruitmentName,BeginDate,EndDate,CityID,RecruitmentPlaceId,LinkMan,Mobile,Telephone,Fax,Email,QQ,Brief,MainID,OrderBy,InnerOrderby,IsPause) 
		VALUES(@RecruitmentDeptId,@RmNameB,@BeginDate,@EndDate,@CityID,@RecruitmentPlaceId,@LinkMan,@Mobile,@Telephone,@Fax,@Email,@QQ,@Brief,@MaxId,501,501,1)

		-- 插入表 orderby 为502
		INSERT INTO Recruitment(RecruitmentDeptId,RecruitmentName,BeginDate,EndDate,CityID,RecruitmentPlaceId,LinkMan,Mobile,Telephone,Fax,Email,QQ,Brief,MainID,OrderBy,InnerOrderby,IsPause) 
		VALUES(@RecruitmentDeptId,@RmNameC,@BeginDate,@EndDate,@CityID,@RecruitmentPlaceId,@LinkMan,@Mobile,@Telephone,@Fax,@Email,@QQ,@Brief,@MaxId,502,502,1)

		INSERT INTO Recruitment(RecruitmentDeptId,RecruitmentName,BeginDate,EndDate,CityID,RecruitmentPlaceId,LinkMan,Mobile,Telephone,Fax,Email,QQ,Brief,MainID,OrderBy,InnerOrderby,IsPause) 
		VALUES(@RecruitmentDeptId,@RmNameC,@BeginDate,@EndDate,@CityID,@RecruitmentPlaceId,@LinkMan,@Mobile,@Telephone,@Fax,@Email,@QQ,@Brief,@MaxId,501,501,1)

		INSERT INTO Recruitment(RecruitmentDeptId,RecruitmentName,BeginDate,EndDate,CityID,RecruitmentPlaceId,LinkMan,Mobile,Telephone,Fax,Email,QQ,Brief,MainID,OrderBy,InnerOrderby,IsPause) 
		VALUES(@RecruitmentDeptId,@RmNameD,@BeginDate,@EndDate,@CityID,@RecruitmentPlaceId,@LinkMan,@Mobile,@Telephone,@Fax,@Email,@QQ,@Brief,@MaxId,502,502,1)

		INSERT INTO Recruitment(RecruitmentDeptId,RecruitmentName,BeginDate,EndDate,CityID,RecruitmentPlaceId,LinkMan,Mobile,Telephone,Fax,Email,QQ,Brief,MainID,OrderBy,InnerOrderby,IsPause) 
		VALUES(@RecruitmentDeptId,@RmNameD,@BeginDate,@EndDate,@CityID,@RecruitmentPlaceId,@LinkMan,@Mobile,@Telephone,@Fax,@Email,@QQ,@Brief,@MaxId,501,501,1)
		*/
	END
	ELSE
	BEGIN
		IF @ManageruserID = 0
		BEGIN
			UPDATE Recruitment SET			
				BeginDate=@BeginDate,EndDate=@EndDate,
				CityID=@CityID,RecruitmentPlaceId=@RecruitmentPlaceId,
				LinkMan=@LinkMan,Mobile=@Mobile,
				Telephone=@Telephone,Fax=@Fax,
				Email=@Email,QQ=@QQ,Brief=@Brief,ManageruserID=NULL
			WHERE MainID = @ID  
			-- Max 2013-06-03 加入，与主表联动更改
			OR ID = @ID 
			SET @MaxId = @ID
		END
		ELSE
		BEGIN
			UPDATE Recruitment SET				
				BeginDate=@BeginDate,EndDate=@EndDate,
				CityID=@CityID,RecruitmentPlaceId=@RecruitmentPlaceId,
				LinkMan=@LinkMan,Mobile=@Mobile,
				Telephone=@Telephone,Fax=@Fax,
				Email=@Email,QQ=@QQ,Brief=@Brief,ManageruserID=@ManageruserID
			WHERE MainID = @ID 
			-- Max 2013-06-03 加入，与主表联动更改
			OR ID = @ID 
			SET @MaxId = @ID

		END
		UPDATE Recruitment SET RecruitmentName=@RecruitmentName WHERE ID = @ID 
	END
	RETURN @MaxId
END TRY
BEGIN CATCH
	RETURN -1
END CATCH











GO
/****** Object:  StoredProcedure [dbo].[rmRecruitmentSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rmRecruitmentSelect]
(
	@strWhere VARCHAR(1000)
)
AS
BEGIN
	DECLARE @SQL AS VARCHAR(MAX)
	SET @SQL = 'Select a.ID,a.*,b.Description City,c.* From Recruitment a,
		dcRegion b,RecruitmentPlace c 
	Where a.RecruitmentPlaceId=c.id and a.CityID=b.ID and ispause=0'
	IF LEN(@strWhere) > 0
		SET @SQL = @SQL + dbo.SafeSql(@strWhere)
	EXEC(@SQL)
END










GO
/****** Object:  StoredProcedure [dbo].[rmRecruitmentSelectByDeptID]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rmRecruitmentSelectByDeptID]
(
	@Where VARCHAR(300)
)
AS
BEGIN
	DECLARE @SQL AS VARCHAR(2000)
	SET @SQL = 'SELECT a.*,b.IsMainSite,b.SubSiteUrl,b.EmailSite FROM Recruitment a,dcSubSite b WHERE a.IsPause=0 AND b.ID=Left(a.CityID,2)'
	SET @SQL = @SQL + dbo.SafeSql(@Where)
	EXEC(@SQL)
END














GO
/****** Object:  StoredProcedure [dbo].[rmRecruitmentSelectByID]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rmRecruitmentSelectByID]
(
	@ID INT,
	@rmID INT
)
AS
BEGIN
	SELECT * FROM Recruitment WHERE ID=@ID AND RecruitmentDeptID=@rmID
END














GO
/****** Object:  StoredProcedure [dbo].[rmRmCompanyInvitationPaReplyUpdate]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.3
--创建人：John
--说明：修改个人答复企业的邀请结果
--#####################################################
CREATE PROCEDURE [dbo].[rmRmCompanyInvitationPaReplyUpdate]
(
	@flag INT,
	@id INT
)
AS
BEGIN
	UPDATE [MarketDb]..[RmCompanyInvitation] SET [Status] = @flag, [ReplyDate] = GETDATE() WHERE id = @id
END


GO
/****** Object:  StoredProcedure [dbo].[rmRmInvitationCodeByPaMainIDSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.03
--创建人：Nick
--说明：
--#####################################################
CREATE PROCEDURE [dbo].[rmRmInvitationCodeByPaMainIDSelect]
(
	@paMainID INT
)
AS
BEGIN TRY
	SELECT b.BeginDate,b.RecruitmentName
	FROM marketdb..RmInvitationCode a WITH(NOLOCK),recruitment b WITH(NOLOCK),
	marketdb..RmProject c WITH(NOLOCK)
	WHERE c.ID=a.rmProjectID 
	AND c.recruitmentid=b.id 
	AND a.pamainid=@paMainID 
	AND a.valid=1 
	AND a.adddate>getdate()-30
END TRY
BEGIN CATCH
	RETURN 0
END CATCH


GO
/****** Object:  StoredProcedure [dbo].[rmRmPaViewLogTopSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rmRmPaViewLogTopSelect] 
	@WHERE VARCHAR(1000),
    @cpMainID INT
AS
BEGIN
	--BEGIN TRY		
		CREATE TABLE #t(
			paMainID INT,				
			cvmainid INT,
			RecruitmentID INT,
			Name NVARCHAR(10),
			JobName NVARCHAR(50),
			AddDate SMALLDATETIME,
			Degree NVARCHAR(10),
			RelatedWorkYears TINYINT,
			LivePlace NVARCHAR(20) COLLATE Chinese_PRC_CI_AS,
			Gender BIT,
			paName NVARCHAR(20),
			BirthDay INT,
			HasPhoto TINYINT,
			Attachment VARCHAR(50) COLLATE Chinese_PRC_CI_AS,
			IsNameHidden BIT,
			Valid TINYINT,
			BeginDate  SMALLDATETIME,
			PlaceID INT,
			PlaceName NVARCHAR(100),
			InvitationDate SMALLDATETIME
		)
		DECLARE @SQL AS VARCHAR(2000)
		IF @cpMainID>0 
		BEGIN
			SET @SQL='
				INSERT INTO #t(paMainID,cvMainID,RecruitmentID,Name,JobName,AddDate,BeginDate,PlaceID,PlaceName,InvitationDate)
				SELECT TOP 10
					c.ID,d.ID,b.ID,c.Name,d.jobname,a.AddDate,b.BeginDate,e.ID,e.PlaceName,
					(SELECT top 1 AddDate FROM RmCompanyInvitation WITH(NOLOCK) WHERE RecruitmentID=b.id and pamainid=c.id and caMainID IN (SELECT id FROM caMain WITH(NOLOCK) WHERE cpMainID='+LTRIM(STR(@cpMainID))+'))
					From RmPaViewLog a WITH(NOLOCK)		
					INNER JOIN recruitment b WITH(NOLOCK) ON  a.recruitmentid=b.id	
					INNER JOIN paMain c WITH(NOLOCK) ON c.ID=a.paMainID
					INNER JOIN cvMain d WITH(NOLOCK) ON d.paMainID=c.ID
					INNER JOIN rmplace e WITH(NOLOCK) ON b.recruitmentplaceid=e.id 
				'
		END
		ELSE
		BEGIN
			SET @SQL='
				INSERT INTO #t(paMainID,cvMainID,RecruitmentID,Name,JobName,AddDate,BeginDate,PlaceID,PlaceName)
				SELECT top 10
					c.ID,d.ID,b.ID,c.Name,d.jobname,a.AddDate,b.BeginDate,e.ID,e.PlaceName
					From RmPaViewLog a WITH(NOLOCK)		
					INNER JOIN recruitment b WITH(NOLOCK) ON  a.recruitmentid=b.id	
					INNER JOIN paMain c WITH(NOLOCK) ON c.ID=a.paMainID
					INNER JOIN cvMain d WITH(NOLOCK) ON d.paMainID=c.ID
					INNER JOIN rmplace e WITH(NOLOCK) ON b.recruitmentplaceid=e.id 
				'
		END 
		SET @SQL=@SQL + '
			WHERE 1=1 '

		IF LEN(@WHERE)>0
			SET @SQL=@SQL + dbo.SafeSql(@WHERE)
		--PRINT @sql
		EXEC(@SQL)		
		
	
		UPDATE #t SET RelatedWorkYears = a.RelatedWorkYears,Attachment = a.Attachment,
			IsNameHidden = a.IsNameHidden,LivePlace = c.description,Gender = b.Gender,
			BirthDay = b.BirthDay,HasPhoto = b.HasPhoto,Valid = a.Valid,Degree=d.Description
		FROM cvMain a WITH(NOLOCK) 
		INNER JOIN paMain b  WITH(NOLOCK) ON a.paMainID = b.ID 
		INNER JOIN dcregion c WITH(NOLOCK) ON  b.liveplace=c.id 
		INNER JOIN dceducation d  WITH(NOLOCK)  ON a.Degree=d.id
		WHERE a.ID = #t.cvMainID 
		IF @cpMainID>0 
		BEGIN
		    UPDATE #t SET jobname= LEFT(maindb.dbo.GetPersonName(cvMainID, @cpMainID), 20)
		END
		SELECT * FROM #t WITH(NOLOCK)  ORDER BY AddDate DESC
		
		DROP TABLE #t
--	END TRY
--	BEGIN CATCH
--		
--		DROP TABLE #t
--	END CATCH
END










GO
/****** Object:  StoredProcedure [dbo].[rmRmPersonInvitationBatchInsert]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.3
--创建人：John
--说明：个人批量邀请企业参会
--#####################################################
CREATE PROCEDURE [dbo].[rmRmPersonInvitationBatchInsert]
(
	@StrColumns VARCHAR(100),
	@StrValues VARCHAR(500)
)
AS
BEGIN
	DECLARE @SQL VARCHAR(1000)
	SET @SQL = 'INSERT INTO [MarketDb]..[RmPersonInvitation] ' + @StrColumns + ' VALUES ' + @StrValues
	PRINT(@SQL)
	EXEC(@SQL)
END


GO
/****** Object:  StoredProcedure [dbo].[rmRmPlaceByBeginDateSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.3
--创建人：John
--说明：返回在指定日期内举办招聘会的场馆
--#####################################################
CREATE PROCEDURE [dbo].[rmRmPlaceByBeginDateSelect]
(
	@StrTime VARCHAR(200),
	@ProvinceID VARCHAR(10)
)
AS
BEGIN
	DECLARE @SQL VARCHAR(1000)
	SET @ProvinceID = @ProvinceID + '%'
	SET @SQL = 'SELECT TOP 500 a.id, b.PlaceName, b.id AS RMplaceID 
	FROM [MarketDb]..[Recruitment] a, [MarketDb]..[RmPlace] b 
	WHERE a.RecruitmentPlaceId = b.id 
		AND a.IsPause=0 
		AND b.dcRegionID LIKE ''' + @ProvinceID + '''' + @StrTime
	EXEC(@SQL)
END


GO
/****** Object:  StoredProcedure [dbo].[rmRmPlaceByProvinceIDSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.3
--创建人：John
--说明：根据省份ID场馆信息
--#####################################################
CREATE PROCEDURE [dbo].[rmRmPlaceByProvinceIDSelect]
(
	@ProvinceID VARCHAR(10)
)
AS
BEGIN
	SET @ProvinceID = @ProvinceID + '%'
	SELECT TOP 500 id, PlaceName, [Address], BusLine, lng, lat 
	FROM [MarketDb]..[RmPlace]
	WHERE dcRegionID LIKE @ProvinceID 
END


GO
/****** Object:  StoredProcedure [dbo].[rmRmPlaceNameByBeginDateSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2014.11.7
--创建人：John
--说明：返回在指定日期内举办招聘会的场馆
--#####################################################
CREATE PROCEDURE [dbo].[rmRmPlaceNameByBeginDateSelect]
(
	@StrTime VARCHAR(200),
	@ProvinceID VARCHAR(10)
)
AS
BEGIN
	DECLARE @SQL VARCHAR(1000)
	SET @ProvinceID = @ProvinceID + '%'
	SET @SQL = 'SELECT TOP 500 b.id as RMplaceID , b.placename FROM [MarketDb]..[RmPlace] b 
		WHERE b.dcRegionID LIKE ''' + @ProvinceID + '''' +
		' AND b.id IN ( SELECT RecruitmentPlaceId FROM [MarketDb]..[Recruitment] a WHERE a.IsPause=0 ' + @StrTime + ')'
	EXEC(@SQL)
END


GO
/****** Object:  StoredProcedure [dbo].[SOLLogInsert]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[SOLLogInsert]
(
	@ProcessID INT,
	@Message VARCHAR(5000),
	@Sender TINYINT
)
AS
BEGIN TRY
	INSERT INTO SOLLog(ProcessID,Message,Sender) VALUES(
		@ProcessID,@Message,@Sender)

	RETURN @@IDENTITY
END TRY
BEGIN CATCH
	RETURN 0
END CATCH














GO
/****** Object:  StoredProcedure [dbo].[SOLProcessInsert]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[SOLProcessInsert]
(
	@caMainID INT,
	@ManagerUserID SMALLINT,
	@OfflineType TINYINT
)
AS
BEGIN TRY
	INSERT INTO SOLProcess(caMainID,ManagerUserId,CompanyName,caName,OfflineType)
	SELECT @caMainID,@ManagerUserId,b.Name,a.Name,@OfflineType
		FROM caMain a WITH(NOLOCK),cpMain b WITH(NOLOCK)
	WHERE a.cpMainID=b.ID AND a.ID=@caMainID

	RETURN @@IDENTITY
END TRY
BEGIN CATCH
	RETURN 0
END CATCH














GO
/****** Object:  StoredProcedure [dbo].[spA_blockedInsert]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[spA_blockedInsert]
AS
BEGIN
	WHILE 1 = 1
	BEGIN
		INSERT INTO a_blocked
		SELECT SPID = p.spid, 
			DBName = convert(CHAR(20),d.name),
			ProgramName = program_name, 
			LoginName = convert(CHAR(20),l.name),
			HostName = convert(CHAR(20),hostname),
			Status = p.status, 
			BlockedBy = p.blocked, 
			LoginTime = login_time, 
			QUERY = CAST(TEXT AS VARCHAR(MAX)),
			GETDATE() AddDate
		FROM MASTER.dbo.sysprocesses p 
		INNER JOIN MASTER.dbo.sysdatabases d ON p.dbid = d.dbid 
		INNER JOIN MASTER.dbo.syslogins l ON p.sid = l.sid 
		CROSS APPLY sys.dm_exec_sql_text(sql_handle) 
		WHERE p.blocked = 0 
		AND EXISTS(SELECT 1 FROM MASTER..sysprocesses p1 WHERE p1.blocked = p.spid)
		
		WAITFOR DELAY '0:0:5'
	END
END
GO
/****** Object:  StoredProcedure [dbo].[spBaiduXmlRunLogSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[spBaiduXmlRunLogSelect]
AS
SET NOCOUNT ON
BEGIN
	DELETE FROM LogDb..BaiduXmlRunLog WHERE AddDate < DATEADD(HOUR, - 2, CONVERT(VARCHAR(10), GETDATE(), 120))
	SELECT Id, (SELECT SubSiteUrl FROM dcSubSite WHERE Id = dcProvinceId) SubSiteUrl,
		dcProvinceId, ServerId, PageCount, PageNo, CurrentStatus, LastRunDate, Adddate,
		CASE 
		WHEN PageCount > PageNo AND LastRunDate < DATEADD(MINUTe, -2, GETDATE())
		THEN '<a href="http://' + (SELECT SubSiteUrl FROM dcSubSite WHERE Id = dcProvinceId) + '/Xml/GenAllJobXml?ServerID=' + LTRIM(STR(ServerId)) + '" target="_bllank">立刻运行</a>'
		ELSE ''
		END
		RunNow
	INTO #t
	FROM LogDb..BaiduXmlRunLog

	SELECT * FROM #t ORDER BY RunNow DESC,  dcProvinceId, ID DESC
END

GO
/****** Object:  StoredProcedure [dbo].[spBsManagerMacByLoginDelete]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[spBsManagerMacByLoginDelete]
AS
BEGIN
	SELECT DISTINCT CONVERT(CHAR(3), ManagerId) + '-' + Mac Mac
	INTO #Log
	FROM ManagerLog
	WHERE LoginDate > GETDATE() - 90

	SELECT ID, CONVERT(CHAR(3), ManagerUserId) + '-' + Mac Mac
	INTO #Mac
	FROM BsManagerMac
	WHERE LEN(Mac) > 3

	DELETE FROM #Mac WHERE Mac IN(SELECT Mac FROM #log)

	DELETE FROM bsManagerMac WHERE ID IN(SELECT ID FROM #Mac)
END














GO
/****** Object:  StoredProcedure [dbo].[spcaOrderByCount32Select]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[spcaOrderByCount32Select]
AS
SET NOCOUNT ON
BEGIN
	SELECT CONVERT(VARCHAR(6), DATEADD(MONTH, 1, a.OpenDate - 25), 112) CountMonth,
		CASE WHEN b.dcRegionId LIKE '32%' THEN LEFT(b.dcRegionId, 4) ELSE 32 END dcRegion, 
		COUNT(*) Cnt,
		SUM(CASE WHEN Paid > 0 THEN 1 ELSE 0 END) CntPaid,
		SUM(Paid) Paid
	INTO #t
	FROM caOrder a, cpMain b
	WHERE a.cpMainId = b.Id
	AND b.dcProvinceId = 32
	AND a.OpenDate > '2017-12-26'
	GROUP BY CONVERT(VARCHAR(6), DATEADD(MONTH, 1, a.OpenDate - 25), 112),
		CASE WHEN b.dcRegionId LIKE '32%' THEN LEFT(b.dcRegionId, 4) ELSE 32 END
	ORDER BY CONVERT(VARCHAR(6), DATEADD(MONTH, 1, a.OpenDate - 25), 112),
		CASE WHEN b.dcRegionId LIKE '32%' THEN LEFT(b.dcRegionId, 4) ELSE 32 END

	SELECT b.Description, a.CountMonth, a.Cnt, a.CntPaid, a.Paid, b.Id INTO #1 FROM #t a, dcRegion b WHERE a.dcRegion = b.ID ORDER BY a.CountMonth, b.Id

	CREATE TABLE #v(
		CountMonth VARCHAR(6),
		Cnt32 INT,
		CntRate32 DECIMAL(9,4),
		Paid32 Decimal(18, 2), 
		PaidRate32 Decimal(9, 4),
		Cnt3201 INT,
		CntRate3201 DECIMAL(9,4),
		Paid3201 Decimal(18, 2), 
		PaidRate3201 Decimal(9, 4),
		Cnt3202 INT,
		CntRate3202 DECIMAL(9,4),
		Paid3202 Decimal(18, 2), 
		PaidRate3202 Decimal(9, 4),
		Cnt3203 INT,
		CntRate3203 DECIMAL(9,4),
		Paid3203 Decimal(18, 2), 
		PaidRate3203 Decimal(9, 4),
		Cnt3204 INT,
		CntRate3204 DECIMAL(9,4),
		Paid3204 Decimal(18, 2), 
		PaidRate3204 Decimal(9, 4),
		Cnt3205 INT,
		CntRate3205 DECIMAL(9,4),
		Paid3205 Decimal(18, 2), 
		PaidRate3205 Decimal(9, 4),
		Cnt3206 INT,
		CntRate3206 DECIMAL(9,4),
		Paid3206 Decimal(18, 2), 
		PaidRate3206 Decimal(9, 4),
		Cnt3207 INT,
		CntRate3207 DECIMAL(9,4),
		Paid3207 Decimal(18, 2), 
		PaidRate3207 Decimal(9, 4),
		Cnt3208 INT,
		CntRate3208 DECIMAL(9,4),
		Paid3208 Decimal(18, 2), 
		PaidRate3208 Decimal(9, 4),
		Cnt3209 INT,
		CntRate3209 DECIMAL(9,4),
		Paid3209 Decimal(18, 2), 
		PaidRate3209 Decimal(9, 4),
		Cnt3210 INT,
		CntRate3210 DECIMAL(9,4),
		Paid3210 Decimal(18, 2), 
		PaidRate3210 Decimal(9, 4),
		Cnt3211 INT,
		CntRate3211 DECIMAL(9,4),
		Paid3211 Decimal(18, 2), 
		PaidRate3211 Decimal(9, 4),
		Cnt3212 INT,
		CntRate3212 DECIMAL(9,4),
		Paid3212 Decimal(18, 2), 
		PaidRate3212 Decimal(9, 4),
		Cnt3213 INT,
		CntRate3213 DECIMAL(9,4),
		Paid3213 Decimal(18, 2), 
		PaidRate3213 Decimal(9, 4),
		Cnt3214 INT,
		CntRate3214 DECIMAL(9,4),
		Paid3214 Decimal(18, 2), 
		PaidRate3214 Decimal(9, 4),
		Cnt3215 INT,
		CntRate3215 DECIMAL(9,4),
		Paid3215 Decimal(18, 2), 
		PaidRate3215 Decimal(9, 4),
		Cnt3216 INT,
		CntRate3216 DECIMAL(9,4),
		Paid3216 Decimal(18, 2), 
		PaidRate3216 Decimal(9, 4),
		Cnt3217 INT,
		CntRate3217 DECIMAL(9,4),
		Paid3217 Decimal(18, 2), 
		PaidRate3217 Decimal(9, 4),
		CntAll INT,
		PaidAll Decimal(18, 2)
	)

	DECLARE @M INT, @Id INT, @CntAll INT, @paidAll DECIMAL(18, 2), @Cnt INT, @Paid DECIMAL(18, 2), @Sql VARCHAR(MAX)
	SELECT @M = 0, @Id = 0
	WHILE EXISTS(SELECT 'x' FROM #1 WHERE CountMonth > @m)
	BEGIN
		SELECT TOP 1 @M = CountMonth FROM #1 WHERE CountMonth > @m ORDER BY CountMonth, Id
		SELECT @CntAll = SUM(Cnt), @PaidAll = SUM(Paid) FROM #1 WHERE CountMonth = @m
		INSERT INTO #v(CountMonth, CntAll, PaidAll) SELECT @m, @CntAll, @PaidAll
		WHILE EXISTS(SELECT 'x' FROM #1 WHERE CountMonth = @m AND Id > @Id)
		BEGIN
			SELECT TOP 1 @Id = Id, @Cnt = Cnt, @Paid = Paid FROM #1 WHERE CountMonth = @m AND Id > @id ORDER BY Id
			SET @Sql = 'UPDATE #v SET Cnt' + LTRIM(STR(@Id)) + ' = ' + LTRIM(STR(@Cnt)) 
				+ ', CntRate' + LTRIM(STR(@Id)) + ' = ' + CONVERT(VARCHAR(20), @Cnt * 100.0 / @CntAll)
				+ ', Paid' + LTRIM(STR(@Id)) + ' = ' + CONVERT(VARCHAR(20), @Paid)
				+ ', PaidRate' + LTRIM(STR(@Id)) + ' = ' + CONVERT(VARCHAR(20), @Paid * 100.0 / @PaidAll)
				+ ' WHERE CountMonth = ' + LTRIM(STR(@m))
			EXEC(@Sql)
		END
		SET @Id = 0
	END

	SELECT * FROM #1
	SELECT * FROM #v
END

GO
/****** Object:  StoredProcedure [dbo].[spChangeInvoiceCompany]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create procedure [dbo].[spChangeInvoiceCompany]
(
	@caorderId INT,
	@invoiceCompanyId INT
)
AS
	update caorder set invoicecompany=@invoiceCompanyId where id = @caorderId
	 
GO
/****** Object:  StoredProcedure [dbo].[spChangeManagerUser]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create Procedure [dbo].[spChangeManagerUser]
(
	@OldId int,
	@NewId int
)
AS
BEGIN
	DECLARE @UserNAme VARCHAR(20), @Password VARCHAR(20), @Name VARCHAR(20), @Name_Eng VARCHAR(20), @Status INT, @LoginStatus INT
	SELECT @UserName = UserName,
		@Password = Password,
		@Name_Eng = Name_Eng,
		@Name = Name,
		@Status = Status,
		@LoginStatus = LoginStatus
	FROM ManagerUser
	WHERE Id = @OldId

	UPDATE ManagerUser SET UserName = @UserName + '##',
		Password = @Password + '##',
		Name_Eng = @Name_Eng + '##',
		Name = @Name + '##',
		Status = 3,
		LoginStatus = 2
	WHERE Id = @OldID

	UPDATE ManagerUser SET UserName = @UserName,
		Password = @Password,
		Name_Eng = @Name_Eng,
		Name = @Name,
		Status = @Status,
		LoginStatus = @LoginStatus
	WHERE Id = @NewID
END
GO
/****** Object:  StoredProcedure [dbo].[spCheckHomepageRefresh]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[spCheckHomepageRefresh]
AS
BEGIN
	begin try
	  drop table #t
	end try
	begin catch
	end catch

	select * 
	into #t
	from cpmain where membertype>0
	and refreshdate >getdate()-1
	and valid=1

	delete #t where id in (select cpmainid from searchdb..cpMainHomepageSnapshot)

	select refreshdate r,jobnumber,* from #t order by refreshdate
END










GO
/****** Object:  StoredProcedure [dbo].[spCommentsHotUpdate]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[spCommentsHotUpdate]
AS
SET NOCOUNT ON
BEGIN
	DECLARE curProvince CURSOR FOR 
		SELECT ID, IsMainSite FROM dcSubSite WITH(NOLOCK) WHERE IsMainSite = 1 OR ID LIKE '32%' ORDER BY ID
	OPEN curProvince
	DECLARE @dcProvinceID INT, @IsMainSite BIT
	FETCH NEXT FROM curProvince INTO @dcProvinceID, @IsMainSite

	WHILE @@FETCH_STATUS = 0
	BEGIN
		DELETE SearchDb..CommentsHot WHERE dcProvinceID = @dcProvinceID

		--点评最多排行
		INSERT INTO SearchDb..CommentsHot
		SELECT @dcProvinceID, a.SecondID, a.Name, b.CpMainID, 1, 1, b.cnt
		FROM CpMain a, (
			 SELECT TOP 10 COUNT(*) cnt, a.CpMainID
			 FROM Comments a, CpMain b
			 WHERE (a.CommentType = 1 OR a.CommentType = 2)
			 AND a.CpMainID = b.ID
			 AND b.dcRegionID like '' + CONVERT(VARCHAR(6), @dcProvinceID) + '%'
			 AND a.CpMainID IN(
				SELECT TOP 99999 MAX(a.CpmainID)
				FROM Comments a, Cpmain b
				WHERE a.CpMainID = b.ID
				AND IsDirect = 1
				GROUP BY b.Name	 
			 )
			 GROUP BY a.CpMainID
			 ORDER BY cnt DESC
			)b
			WHERE a.ID = b.CpMainID
			
		--最佳点评排行
		INSERT INTO SearchDb..CommentsHot
		SELECT @dcProvinceID, a.SecondID, a.Name, b.CpMainID, 1, 2, b.cnt
		FROM CpMain a, (
			SELECT TOP 10 COUNT(*) cnt, a.CpMainID
			FROM Comments a, CpMain b
			WHERE a.CommentType = 2
			AND a.CpMainID = b.ID
			AND b.dcRegionID like ''+CONVERT(VARCHAR(6), dcProvinceID)+'%'
			AND a.CpMainID IN(
				SELECT TOP 99999 MAX(a.CpmainID)
				FROM Comments a, Cpmain b
				WHERE a.CpMainID = b.ID
				AND IsDirect = 1
				GROUP BY b.Name	 
				)
			GROUP BY a.CpMainID
			ORDER BY cnt DESC
			)b
		WHERE a.ID = b.CpMainID
		
		--面经最多排行
		INSERT INTO SearchDb..CommentsHot
		SELECT @dcProvinceID, a.SecondID, a.Name, b.CpMainID, 2, 1, b.cnt
		FROM CpMain a, (
			SELECT TOP 10 COUNT(*) cnt, a.CpMainID
			FROM InterView a, CpMain b
			WHERE (a.InterViewType = 1 OR a.InterViewType = 2)
			AND a.CpMainID = b.ID
			AND b.dcRegionID like ''+CONVERT(VARCHAR(6), @dcProvinceID)+'%'
			AND a.CpMainID IN(
				SELECT TOP 99999 MAX(a.CpmainID)
				FROM InterView a, Cpmain b
				WHERE a.CpMainID = b.ID
				AND IsDirect = 1
				GROUP BY b.Name	 
				)
			GROUP BY a.CpMainID
			ORDER BY cnt DESC
			)b
		WHERE a.ID = b.CpMainID
		
		--最佳面经排行
		INSERT INTO SearchDb..CommentsHot
		SELECT @dcProvinceID, a.SecondID, a.Name, b.CpMainID, 2, 2, b.cnt 
		FROM CpMain a, (SELECT TOP 10 COUNT(*) cnt, a.CpMainID
			FROM InterView a, CpMain b
			WHERE a.InterViewType = 2
			AND a.CpMainID = b.ID
			AND b.dcRegionID like ''+CONVERT(VARCHAR(6), @dcProvinceID)+'%'
			AND a.CpMainID IN(
				SELECT TOP 99999 MAX(a.CpmainID)
				FROM InterView a, Cpmain b
				WHERE a.CpMainID = b.ID
				AND IsDirect = 1
				GROUP BY b.Name	 
				)
			GROUP BY a.CpMainID
			ORDER BY cnt DESC
			)b
		WHERE a.ID = b.CpMainID
	 
		DELETE SearchDb..Hp_Comments WHERE ProvinceId = @dcProvinceID
		
		INSERT INTO SearchDb..Hp_Comments
		SELECT TOP 8 @dcProvinceID, * 
		FROM (SELECT * 
			FROM (SELECT TOP 8 a.ID, a.CpMainID, LEFT(CASE WHEN Relation IN (1, 3) THEN Remark1 ELSE Remark2 END, 60) AS Title,
					a.AddDate, 1 AS CIType, a.CommentType AS IsGood, b.Name, b.SecondID, 1 CommentType
				FROM Comments a WITH(NOLOCK), CpMain b WITH(NOLOCK)
				WHERE a.CommentType IN (1, 2) 
				AND a.CpMainID = b.ID 
				AND b.dcRegionID like ''+CONVERT(VARCHAR(6), @dcProvinceID)+'%' 
				AND a.IsDirect = 1
				AND b.Valid = 1
				AND (SELECT COUNT(1) FROM Job WITH(NOLOCK) WHERE cpMainID = b.id AND Valid = 1) > 0
				ORDER BY a.AddDate DESC
				) AS tempComment
			UNION 
			SELECT * 
			FROM (SELECT TOP 8 a.ID, a.CpMainID, a.Title, a.AddDate, 2 AS CIType, 
					a.InterviewType AS IsGood, b.Name, b.SecondID, 2 CommentType
				FROM InterView a WITH(NOLOCK), cpmain b WITH(NOLOCK)
				WHERE a.InterviewType IN (1, 2) 
				AND a.CpMainID = b.ID 
				AND b.dcRegionID like ''+CONVERT(VARCHAR(6), @dcProvinceID)+'%'
				AND a.IsDirect = 1
				AND b.Valid = 1
				AND (SELECT COUNT(1) FROM Job WITH(NOLOCK) WHERE cpMainID = b.id AND Valid = 1) > 0
				ORDER BY a.AddDate DESC
				) AS tempInterview
			) AS CIResult 
		ORDER BY AddDate DESC
 
		FETCH NEXT FROM curProvince INTO @dcProvinceID, @IsMainSite
	END

	CLOSE curProvince
	DEALLOCATE curProvince
END
GO
/****** Object:  StoredProcedure [dbo].[SPCopyMainDBTOTestDb]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[SPCopyMainDBTOTestDb]
(
	@s varchar(10),
	@e varchar(10)
)
AS
BEGIN
	SET NOCOUNT ON
	PRINT 'SET NOCOUNT ON'
	PRINT '
BEGIN TRY 
	DROP TABLE #s
END TRY
BEGIN CATCH
END CATCH
BEGIN TRY 
	DROP TABLE #b
END TRY
BEGIN CATCH
END CATCH

CREATE TABLE #S(Name VARCHAR(100))
CREATE TABLE #b(Name VARCHAR(100))'
	SELECT ID, Name 
	INTO #t
	FROM testdb..sysObjects
	WHERe xType = 'u'
	AND Name NOT LIKE 'sys%'
	AND Name NOT LIKE 'ms%'
	and name >= @s
	and name < @e

	DECLARE @Name VARCHAR(100), @Id INT, @SQL VARCHAR(MAX), @ColName VARCHAR(MAX), @IIBegin VARCHAR(MAX), @IIEnd VARCHAR(MAX),
		@WHERE VARCHAR(MAX), @Order VARCHAR(MAX)
	
	SELECT TOP 1 @Name = Name, @Id = ID FROM #t order BY NAME
	WHILE @Name > ''
	BEGIN
		SELECT @ColName = ''
		SELECT @ColName =  @ColName + NAME + ', ' FROM SysColumns WHERE ID = @ID AND colstat <> 4
		SELECT @ColName = LTRIM(RTRIM(@ColName))
		SELECT @ColName = LEFT(@ColName, LEN(@ColName) - 1)

		SELECT @IIBegin = '', @IIEND = '', @WHERE = '', @Order = ''
		IF EXISTS(SELECT 'x' FROM sysColumns WHERE ID = @ID AND NAME = 'ID' AND ColStat = 1)
		BEGIN
			SELECT @IIBegin = 'SET IDENTITY_INSERT ' + @Name + ' ON', @IIEND = 'SET IDENTITY_INSERT ' + @Name + ' OFF', @Order = ' ORDER BY ID DESC'
		END
		IF EXISTS(SELECT 'x' FROM sysColumns WHERE ID = @ID AND NAME = 'paMainID')
			SET @WHERE = CASE WHEN @WHERE = '' THEN ' WHERE ' ELSE @WHERE + ' AND ' END + 'paMainID IN(SELECT ID FROM TestDb..TmpPaMain)'
		IF EXISTS(SELECT 'x' FROM sysColumns WHERE ID = @ID AND NAME = 'cvMainID')
			SET @WHERE = CASE WHEN @WHERE = '' THEN ' WHERE ' ELSE @WHERE + ' AND ' END + 'cvMainID IN(SELECT ID FROM TestDb..TmpcvMain)'
		IF EXISTS(SELECT 'x' FROM sysColumns WHERE ID = @ID AND NAME = 'cpMainID')
			SET @WHERE = CASE WHEN @WHERE = '' THEN ' WHERE ' ELSE @WHERE + ' AND ' END + 'cpMainID IN(SELECT ID FROM TestDb..TmpcpMain)'
		IF EXISTS(SELECT 'x' FROM sysColumns WHERE ID = @ID AND NAME = 'CompanyId')
			SET @WHERE = CASE WHEN @WHERE = '' THEN ' WHERE ' ELSE @WHERE + ' AND ' END + 'CompanyId IN(SELECT ID FROM TestDb..TmpcpMain)'
		IF EXISTS(SELECT 'x' FROM sysColumns WHERE ID = @ID AND NAME = 'caMainID')
			SET @WHERE = CASE WHEN @WHERE = '' THEN ' WHERE ' ELSE @WHERE + ' AND ' END + 'caMainID IN(SELECT ID FROM TestDb..TmpcaMain)'
		IF EXISTS(SELECT 'x' FROM sysColumns WHERE ID = @ID AND NAME = 'JobID')
			SET @WHERE = CASE WHEN @WHERE = '' THEN ' WHERE ' ELSE @WHERE + ' AND ' END + 'JobID IN(SELECT ID FROM TestDb..TmpJob)'

		SET @SQL = 
'IF ((SELECT COUNT(*) FROM ' + @NAME + ') > 0 AND (SELECT COUNT(*) FROM ' + @NAME + ') = 0)
BEGIN TRY
	' + @IIBegin + '
	INSERT INTO TestDb..' + @Name + '(' + @ColName + ') 
	SELECT TOP 10000 ' + @ColName + ' FROM ' + @Name + @Where + + @Order + '
	' + @IIEnd + '
	PRINT ''' + @Name + ' IS Sucessed!''
	INSERT #s SELECT ''' + @Name + '''
END TRY
BEGIN CATCH
	' + @IIEnd + '
	PRINT ''' + @Name + ' IS BAD!!!!!!!!!!!!!!!!!!!!''
	INSERT #b SELECT ''' + @Name + '''
END CATCH
GO

'
		--PRINT @SQL
		SELECT TOP 1 @Name = Name, @Id = ID FROM #t WHERE Name > @Name ORDER BY NAME
		IF @@ROWCOUNT = 0
			SELECT @Name = ''
	END
	DROP TABLE #t
	PRINT ' SELECT * FROM #b'
	PRINT ' SELECT * FROM #s'
END











GO
/****** Object:  StoredProcedure [dbo].[SPCopySearchDbTOTestDb]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[SPCopySearchDbTOTestDb]
AS
BEGIN
	SET NOCOUNT ON
	PRINT 'SET NOCOUNT ON'
	PRINT '
BEGIN TRY 
	DROP TABLE #s
END TRY
BEGIN CATCH
END CATCH
BEGIN TRY 
	DROP TABLE #b
END TRY
BEGIN CATCH
END CATCH

CREATE TABLE #S(Name VARCHAR(100))
CREATE TABLE #b(Name VARCHAR(100))'
	SELECT ID, Name 
	INTO #t
	FROM testdb..sysObjects
	WHERe xType = 'u'
	AND Name NOT LIKE 'sys%'
	AND Name NOT LIKE 'ms%'

	DECLARE @Name VARCHAR(100), @Id INT, @SQL VARCHAR(MAX), @ColName VARCHAR(MAX), @IIBegin VARCHAR(MAX), @IIEnd VARCHAR(MAX),
		@WHERE VARCHAR(MAX), @Order VARCHAR(MAX)
	
	SELECT TOP 1 @Name = Name, @Id = ID FROM #t order BY NAME
	WHILE @Name > ''
	BEGIN
		SELECT @ColName = ''
		SELECT @ColName =  @ColName + NAME + ', ' FROM SysColumns WHERE ID = @ID AND colstat <> 4
		SELECT @ColName = LTRIM(RTRIM(@ColName))
		SELECT @ColName = LEFT(@ColName, LEN(@ColName) - 1)

		SELECT @IIBegin = '', @IIEND = '', @WHERE = '', @Order = ''
		IF EXISTS(SELECT 'x' FROM sysColumns WHERE ID = @ID AND NAME = 'ID' AND ColStat = 1)
		BEGIN
			SELECT @IIBegin = 'SET IDENTITY_INSERT ' + @Name + ' ON', @IIEND = 'SET IDENTITY_INSERT ' + @Name + ' OFF', @Order = ' ORDER BY ID DESC'
		END
		IF EXISTS(SELECT 'x' FROM sysColumns WHERE ID = @ID AND NAME = 'paMainID')
			SET @WHERE = CASE WHEN @WHERE = '' THEN ' WHERE ' ELSE @WHERE + ' AND ' END + 'paMainID IN(SELECT ID FROM TestDb..TmpPaMain)'
		IF EXISTS(SELECT 'x' FROM sysColumns WHERE ID = @ID AND NAME = 'cvMainID')
			SET @WHERE = CASE WHEN @WHERE = '' THEN ' WHERE ' ELSE @WHERE + ' AND ' END + 'cvMainID IN(SELECT ID FROM TestDb..TmpcvMain)'
		IF EXISTS(SELECT 'x' FROM sysColumns WHERE ID = @ID AND NAME = 'cpMainID')
			SET @WHERE = CASE WHEN @WHERE = '' THEN ' WHERE ' ELSE @WHERE + ' AND ' END + 'cpMainID IN(SELECT ID FROM TestDb..TmpcpMain)'
		IF EXISTS(SELECT 'x' FROM sysColumns WHERE ID = @ID AND NAME = 'CompanyId')
			SET @WHERE = CASE WHEN @WHERE = '' THEN ' WHERE ' ELSE @WHERE + ' AND ' END + 'CompanyId IN(SELECT ID FROM TestDb..TmpcpMain)'
		IF EXISTS(SELECT 'x' FROM sysColumns WHERE ID = @ID AND NAME = 'caMainID')
			SET @WHERE = CASE WHEN @WHERE = '' THEN ' WHERE ' ELSE @WHERE + ' AND ' END + 'caMainID IN(SELECT ID FROM TestDb..TmpcaMain)'
		IF EXISTS(SELECT 'x' FROM sysColumns WHERE ID = @ID AND NAME = 'JobID')
			SET @WHERE = CASE WHEN @WHERE = '' THEN ' WHERE ' ELSE @WHERE + ' AND ' END + 'JobID IN(SELECT ID FROM TestDb..TmpJob)'

		SET @SQL = 
'IF ((SELECT COUNT(*) FROM searchdb..' + @NAME + ') > 0 AND (SELECT COUNT(*) FROM ' + @NAME + ') = 0)
BEGIN TRY
	' + @IIBegin + '
	INSERT INTO TestDb..' + @Name + '(' + @ColName + ') 
	SELECT TOP 10000 ' + @ColName + ' FROM searchdb..' + @Name + @Where + + @Order + '
	' + @IIEnd + '
	PRINT ''' + @Name + ' IS Sucessed!''
	INSERT #s SELECT ''' + @Name + '''
END TRY
BEGIN CATCH
	' + @IIEnd + '
	PRINT ''' + @Name + ' IS BAD!!!!!!!!!!!!!!!!!!!!''
	INSERT #b SELECT ''' + @Name + '''
END CATCH
GO

'
		--PRINT @SQL
		SELECT TOP 1 @Name = Name, @Id = ID FROM #t WHERE Name > @Name ORDER BY NAME
		IF @@ROWCOUNT = 0
			SELECT @Name = ''
	END
	DROP TABLE #t
	PRINT ' SELECT * FROM #b'
	PRINT ' SELECT * FROM #s'
END











GO
/****** Object:  StoredProcedure [dbo].[SPCountyJobRebuild]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[SPCountyJobRebuild]
AS
BEGIN
	IF DATEPART(HOUR, GETDATE()) < 10
		TRUNCATE TABLE SearchDb..CountyJob

	TRUNCATE TABLE SearchDb..CountyJobNumber
	INSERT INTO SearchDb..CountyJobNumber
	SELECT LEFT(dcRegionId, 2), COUNT(*) FROM JobPublish WITH(NOLOCK) WHERE Valid = 1 GROUP BY LEFT(dcRegionId, 2)
END







GO
/****** Object:  StoredProcedure [dbo].[SpCpCvPriviByFixSave]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[SpCpCvPriviByFixSave]
AS
SET NOCOUNT ON
BEGIN
	SELECT TOP 0 * INTO #p FROM cpCvPrivi
	SELECT Id INTO #cp FROM cpMain WHERE Membertype > 1 AND IsLimitLogin IN(0, 1) AND LastLoginDate > GETDATE() - 183

	CREATE TABLE #t(cpMainId INT, paMainId INT)

	INSERT INTO #t
	SELECT a.cpMainId, b.paMainId
	FROM caActiveLog a WITH(NOLOCK INDEX(IX_caActiveLog_cpMainID)),
		cvMain b WITH(NOLOCK)
	WHERE a.cpMainID IN(SELECT Id FROM #cp)
	AND a.AddDate > DATEADD(MINUTE, -120, GETDATE())
	AND a.cvMainId = b.Id

	INSERT INTO #t
	SELECT b.cpMainId, c.paMainId
	FROM ExJobApply a WITH(NOLOCK), Job b, cvMain c
	WHERE a.JobID = b.ID
	AND a.IsPassed = 1 
	AND a.cvMainID = c.Id
	AND a.AddDate > DATEADD(MINUTE, -120, GETDATE())

	INSERT INTO #p(cpMainId, cvMainId)
	SELECT DISTINCT a.cpMainId, b.Id
	FROM #t a, cvMain b
	WHERE a.paMainId = b.paMainId

	INSERT INTO #p(cpMainId, cvMainId)
	SELECT cpMainId, cvMainId
	FROM caDailyGiftLog WITH(NOLOCK INDEX(PK_caDailyGiftLog))
	WHERE cpMainID IN(SELECT ID FROM #Cp)
	AND AddDate > DATEADD(MINUTE, -120, GETDATE())
	AND NOT EXISTS(SELECT 'x' FROM #p WHERE #p.cpMainId = caDailyGiftLog.cpMainId AND #p.cvMainId = caDailyGiftLog.cvMainId)

	INSERT INTO #p(cpMainId, cvMainId)
	SELECT cpMainId, cvMainId
	FROM caDailyGiftLog WITH(NOLOCK INDEX(PK_caDailyGiftLog))
	WHERE cpMainID IN(SELECT ID FROM #Cp)
	AND AddDate > DATEADD(MINUTE, -120, GETDATE())
	AND NOT EXISTS(SELECT 'x' FROM #p WHERE #p.cpMainId = caDailyGiftLog.cpMainId AND #p.cvMainId = caDailyGiftLog.cvMainId)

	INSERT INTO cpCvPrivi
	SELECT cpMainId, cvMainId
	FROM #p
	WHERE NOT EXISTS(SELECT 'x' FROM cpCvPrivi WHERE #p.cpMainId = cpCvPrivi.cpMainId AND #p.cvMainId = cpCvPrivi.cvMainId)
END

GO
/****** Object:  StoredProcedure [dbo].[SpCpCvPriviSave]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[SpCpCvPriviSave]
AS
SET NOCOUNT ON
BEGIN
	SELECT Id INTO #cp FROM cpMain WHERE Membertype > 1 AND IsLimitLogin IN(0, 1) AND LastLoginDate > GETDATE() - 183

	CREATE TABLE #t(cpMainId INT, paMainId INT)

	INSERT INTO #t
	SELECT a.cpMainId, b.paMainId
	FROM caActiveLog a WITH(NOLOCK INDEX(IX_caActiveLog_cpMainID)),
		cvMain b WITH(NOLOCK)
	WHERE a.cpMainID IN(SELECT Id FROM #cp)
	AND a.AddDate > GETDATE() - 183
	AND a.cvMainId = b.Id

	INSERT INTO #t
	SELECT b.cpMainId, c.paMainId
	FROM ExJobApply a WITH(NOLOCK), Job b, cvMain c
	WHERE a.JobID = b.ID
	AND a.IsPassed = 1 
	AND a.cvMainID = c.Id
	AND a.AddDate > GETDATE() - 183

	TRUNCATE TABLE LogDb..cpCvPrivi

	INSERT INTO cpCvPrivi(cpMainId, cvMainId)
	SELECT DISTINCT a.cpMainId, b.Id
	FROM #t a, cvMain b
	WHERE a.paMainId = b.paMainId

	INSERT INTO cpCvPrivi(cpMainId, cvMainId)
	SELECT cpMainId, cvMainId
	FROM caDailyGiftLog WITH(NOLOCK INDEX(PK_caDailyGiftLog))
	WHERE cpMainID IN(SELECT ID FROM #Cp)
	AND AddDate > GETDATE() - 183
	AND NOT EXISTS(SELECT 'x' FROM cpCvPrivi WHERE cpCvPrivi.cpMainId = caDailyGiftLog.cpMainId AND cpCvPrivi.cvMainId = caDailyGiftLog.cvMainId)
END
GO
/****** Object:  StoredProcedure [dbo].[spCpMainByChar0Fix]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[spCpMainByChar0Fix]
AS
BEGIN
	create table #t(id int)
	create table #tt(id int)
--cpMain
	insert into #t Select id from cpMain where UNICODE(right(Name,1)) = 0
	update cpMain set name=SUBSTRING(name, 1, LEN(name) - 1) where id in (select id from #t)
	DELETE #t

	INSERT INTO #t Select id from cpMain where UNICODE(right(brief,1)) = 0
	update cpMain set brief=SUBSTRING(brief, 1, LEN(brief) - 1) where id in (select id from #t)
	DELETE #t
--job
	INSERT INTO #t Select id from Job where UNICODE(right(Responsibility,1)) = 0
	update Job set Responsibility=SUBSTRING(Responsibility, 1, LEN(Responsibility) - 1) where id in (select id from #t)
	DELETE #t

	INSERT INTO #t Select id from Job where UNICODE(right(Demand,1)) = 0
	update Job set Demand=SUBSTRING(Demand, 1, LEN(Demand) - 1) where id in (select id from #t)
	DELETE #t

	INSERT INTO #t Select id from Job where UNICODE(right(name,1)) = 0
	update Job set name=SUBSTRING(name, 1, LEN(name) - 1) where id in (select id from #t)
	DELETE #t
 	 
--////////////////////////
	drop table #t
	drop table #tt
end














GO
/****** Object:  StoredProcedure [dbo].[SpCpMainByCommentNumberFix]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[SpCpMainByCommentNumberFix]
AS
BEGIN
	UPDATE cpMain set CommentNumber =0 WHERE CommentNumber > 0
	UPDATE cpMain set InterViewNumber = 0 WHERE InterViewNumber > 0

	UPDATE a set a.InterViewNumber = b.Cnt
	from cpmain a,
	(select cpMainId, COUNT(*) Cnt
	from InterView
	where InterViewType <> 3
	group by cpMainId) b
	WHERE a.Id = b.cpMainId


	UPDATE a set a.CommentNumber = b.Cnt
	from cpmain a,
	(select cpMainId, COUNT(*) Cnt
	from Comments
	where CommentType <> 3
	group by cpMainId) b
	WHERE a.Id = b.cpMainId
END
GO
/****** Object:  StoredProcedure [dbo].[SpCpMainByConsultantIdFromColdCustomerUpdate]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--修改harry,增加顾问rtx提醒2017-5-17
--修改Peter，增加顾问RTX冷客户提醒
--修改：增加推广认证后分配2018-1-3 harry
--修改：harry 去掉冷客户部门，修改分配过程
/*
sean 2018-2-28
Vicky(762姜乐文) 02-28 08:41:16
公司名称：烟台德霖日化科技有限公司 公司编号：10683832 
765的客户已经产生二次续费，但是该客户是765的置顶广告，多次合作，到期依然要续约的客户，申请保留这个广告客户，谢谢
*/
CREATE PROCEDURE [dbo].[SpCpMainByConsultantIdFromColdCustomerUpdate]
AS
SET NOCOUNT ON
BEGIN
	CREATE TABLE #t(ConsultantId INT, ID INT, Name VARCHAR(100),RegDate DATETIME, DeptId INT)
	/*
 	INSERT INTO #t(ConsultantId, Id, Name,RegDate,DeptId) 
	SELECT ConsultantId, Id, Name,RegDate,42 AS DeptId  
	FROM cpMain WITH(NOLOCK) 
	WHERE MemberType = 3 
	AND ConsultantId IN(SELECT ID FROM ManagerUser WITH(NOLOCK) WHERE DeptId = 42)
	AND Id IN(SELECT cpMainId FROM caOrder WITH(NOLOCK) WHERE OrderType = 8 AND OpenDate < GETDATE() - 31 AND IsDeleted = 0 AND Paid > 0 )
	AND Id NOT IN(SELECT cpMainId FROM caOrder WHERE OpenDate > '' AND OrderType = 8 AND IsDeleted = 0 AND BeginDate > GETDATE() - 31)
	AND (select count(1) FROM caOrder  WITH(NOLOCK) WHERE OrderType = 8 AND OpenDate>'' AND ManagerUserId =cpMain.ConsultantId AND cpMainId=cpMain.id AND paid>0 )>1
	*/
	---推广的进行分配
	INSERT INTO #t(ConsultantId, Id, Name,RegDate,DeptId)
	SELECT ConsultantId, Id, Name,RegDate,15
	FROM cpMain WITH(NOLOCK)
	WHERE MemberType >1 --认证通过
	AND ConsultantId IN(SELECT ID FROM ManagerUser WITH(NOLOCK) WHERE DeptId = 15) --推广部

	--sean add 2018-2-28
	DELETE FROM #t WHERE Id = 10683832
	DECLARE @deptId INT, @dcProvinceID AS INT, @ManagerUserID AS INT, @ID AS INT, @Name VARCHAR(100), @cpMainId INT, @Sql AS VARCHAR(200), @ConsultantId INT, @RegDate DATETIME, @msg VARCHAR(50)
	SELECT @cpMainId = 0, @dcProvinceID = 32	
	WHILE EXISTS(SELECT 'x' FROM #t WHERE Id > @cpMainId)
	BEGIN
		SELECT TOP 1 @cpMainId = Id, @ConsultantId = ConsultantId, @Name = Name, @RegDate=RegDate, @deptId =deptId
		FROM #t WHERE Id > @cpMainId ORDER BY ID

		IF NOT EXISTS(SELECT 'x' FROM Cold_Consultant_Assign WHERE Current_Power < Power)
			UPDATE Cold_Consultant_Assign SET Current_Power = 0
		
		--提取第一个顾问
		SELECT TOP 1 @ID = ID, @ManagerUserID = ManagerUserID FROM Cold_Consultant_Assign WHERE Current_Power < Power
		IF @ManagerUserID IS NULL
			RETURN

		--修改顾问分配表
		UPDATE Cold_Consultant_Assign SET Current_Power = Current_Power + 1 WHERE ID = @ID
				
		IF @deptId =42
			SET @msg='冷客户第2次付费后31天重新分配'
		ELSE
			SET @msg='冷客户推广认证通过后重新分配'	
		SET @Sql = @msg+'顾问:从' + LTRIM(STR(ISNULL(@ConsultantId, 0))) + '到' + LTRIM(STR(@ManagerUserID))
		INSERT INTO bsManagerUserAction VALUES(@cpMainId, @Sql, '', 112, GETDATE()) 

		UPDATE cpMain SET ConsultantId = @ManagerUserID, ConsultantDate = GETDATE() WHERE Id = @cpMainId
		
		SELECT id INTO #company FROM cpmain WHERE Id <> @cpMainId AND Name = @Name AND ConsultantId = @ConsultantId
		DECLARE @cpid INT
		SET @cpid=0
		WHILE EXISTS(select 'x' FROM #company)
		BEGIN
			SELECT TOP 1 @cpid=id FROM #company ORDER BY id 
			UPDATE cpMain SET ConsultantId = @ManagerUserID, ConsultantDate = GETDATE() WHERE id = @cpid
			DELETE FROM #company WHERE id= @cpid
        		END     
		DROP TABLE #company 
		INSERT RtxNotifyLog SELECT LTRIM(STR(@ManagerUserID)) + ',' + LTRIM(STR(@ConsultantId)), @msg+'通知', 'http://sysback.51rc.com/newoa/company/cp/cpMainInfo?id=' + LTRIM(STR(@cpMainId))+ '&code=' + LTRIM(STR(DATEPART(HOUR, @RegDate) * 100 + DATEPART(MINUTE, @RegDate))), 0, 0, 0, Null, GETDATE()
		DELETE FROM #t where id=@cpMainId
		DELETE FROM #t where Name = @Name AND ConsultantId = @ConsultantId
	END
	DROP TABLE #t
END
SET NOCOUNT OFF
GO
/****** Object:  StoredProcedure [dbo].[spCpMainByIsprotectUpdate]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[spCpMainByIsprotectUpdate]
(
	@cpMainId INT
)
AS
BEGIN
	SET NOCOUNT ON
	UPDATE cpMain SET IsProtect = 0 WHERE Id = @cpMainId
	UPDATE caMain SET SecondPassword = NULL WHERE cpMainId = @cpMainId
END

GO
/****** Object:  StoredProcedure [dbo].[spCpMainByReplyrateUpdate]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--创建人harry
--2017-5-24
--自动答复应聘的简历计划任务
--cpCvShield中的简历手动答复为不合适2018-6-11 harry
CREATE PROCEDURE [dbo].[spCpMainByReplyrateUpdate] 
AS
SET NOCOUNT ON
BEGIN   
	
	UPDATE a
	SET a.reply=2,a.replydate=getdate()
	FROM exjobapply a,job b, cpCvShield c
        WHERE a.jobId=b.Id AND c.cpMainId= b.cpMainId AND c.cvMainId=a.cvMainId
	AND ISNULL(a.reply,0)=0
    
	UPDATE exjobapply
	SET reply=4
	WHERE reply=5 
	AND ISNULL(CompanyDeleted,0) = 1
	
	--vip用户超过20天的自动答复，非vip超过10天的自动答复
        --vip
 	UPDATE a
	SET a.reply=5, a.replydate=getdate() 
	FROM exjobapply a, job b, cpMain c 
	WHERE a.reply=0 
	AND c.AutoReplyConfirm < CONVERT(VARCHAR(10), getdate() - 20, 120) 
	AND c.MemberType = 3
	AND b.CpMainId = c.id
	AND b.id = a.jobid
	AND a.addDate < CONVERT(VARCHAR(10), getdate() - 20, 120)	--在申请20天后自动答复
	AND a.addDate > c.AutoReplyConfirm	--只自动答复我知道了之后的
        
	--非vip
	UPDATE a
	SET a.reply = 5, a.replydate = getdate() 
	FROM exjobapply a, job b, cpMain c 
	WHERE a.reply = 0 
	AND c.AutoReplyConfirm < CONVERT(VARCHAR(10), getdate()-10, 120) 
	AND c.MemberType < 3
	AND b.CpMainId = c.id
	AND b.id = a.jobid
	AND a.addDate < CONVERT(VARCHAR(10), getdate() - 10, 120)	--在申请10天后自动答复
	AND a.addDate > c.AutoReplyConfirm		--只自动答复我知道了之后的     

	SELECT a.id, SUM(CASE WHEN c.reply = 5 THEN 1 ELSE 0 END) AS autoreply, 
		COUNT(*) AS SumReply
	INTO #t
	FROM cpMain a
	inner join job b on a.id = b.cpmainid
	inner join exjobapply c on c.jobid = b.id AND c.AddDate > a.AutoReplyConfirm  
	WHERE a.MemberType = 3
	--AND a.AutoReplyConfirm < CONVERT(VARCHAR(10), getdate() - 20, 120) //跟这个时间无关harry
	AND b.IsDelete = 0
	AND c.Reply > 0
	GROUP BY a.Id

	INSERT INTO #t
	SELECT a.id, SUM(CASE WHEN c.reply = 5 THEN 1 ELSE 0 END) AS autoreply, 
		COUNT(*) AS SumReply
	FROM cpMain a
	inner join job b on a.id = b.cpmainid
	inner join exjobapply c on c.jobid = b.id AND c.AddDate > a.AutoReplyConfirm --AND c.AddDate < CONVERT(VARCHAR(10), GETDATE() - 10, 120)
	WHERE a.MemberType <> 3
	--AND a.AutoReplyConfirm < CONVERT(VARCHAR(10), getdate() - 10, 120)  //跟这个时间无关harry
	AND b.IsDelete = 0
	AND c.Reply > 0
	GROUP BY a.Id

	--计算更新答复率
         --更新SumReply为0的,有应聘的
	UPDATE cpMain
	SET replyrate = 0 
	WHERE id IN (SELECT id FROM #t WHERE SumReply = 0)

    ---无应聘的
	UPDATE cpMain
	SET replyrate = 1
	WHERE id NOT IN (SELECT id FROM #t)
	AND AutoReplyConfirm IS NOT NULL
	
	--删除
   	DELETE FROM #t WHERE SumReply = 0
	
	--更新其他的
	UPDATE cpMain
	SET replyrate = (b.SumReply - b.autoreply) * 1.0 / b.SumReply
	FROM cpMain a, #t b
	WHERE a.Id = b.Id
	
	UPDATE a
	SET a.replyrate = b.ReplyRate
	FROM cpMainPublish a, cpMain b
	WHERE a.Id = b.Id
	AND ISNULL(a.replyrate, 0) <> ISNULL(b.replyrate, 0)

	drop table #t 
END
SET NOCOUNT OFF


GO
/****** Object:  StoredProcedure [dbo].[SpcpMainPublishByHasEnvironmentUpdate]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[SpcpMainPublishByHasEnvironmentUpdate]
AS
BEGIN
	SET NOCOUNT ON
	SELECT DISTINCT cpMainId ID INTO #1 FROM cpImage WHERE ImgType = 3 AND HasPassed = 1
	SELECT Id, HasEnvironment INTO #2 FROM cpMainPublish WITH(NOLOCK) WHERE HasEnvironment = 1
	SELECT * INTO #3 FROM #2
	DELETE #2 WHERE ID IN(SELECT ID FROM #1)
	DELETE #1 WHERE ID IN(SELECT ID FROM #3)
	UPDATE cpMainPublish SET HasEnvironment = 0 WHERE ID IN(SELECT ID FROM #2)
	UPDATE cpMainPublish SET HasEnvironment = 1 WHERE ID IN(SELECT ID FROM #1)
END
GO
/****** Object:  StoredProcedure [dbo].[spCvInfoSave]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[spCvInfoSave]
AS
SET NOCOUNT ON
BEGIN
	IF DATEPART(HOUR, GETDATE()) = 6 AND (SELECT COUNT(*) FROM cvInfo WHERE ModifyDate > GETDATE() - 0.5) < 50000
	BEGIN
		SELECT TOP 0 * INTO #t1 FROM cvInfo	
	
		INSERT INTO #t1(cvMainId, JobName, Speciality, EduInfo, ExpInfo, ProjectInfo, TrainInfo, ModifyDate)
		SELECT Id cvMainId, JobName, Speciality,
			(
				STUFF(
					(SELECT ',' + GraduateCollage + '@@' + MajorName + '@@' + ISNULL(Details, '')
					FROM cvEducationPublish b
					WHERE b.cvMainId = a.ID
					FOR XML PATH('')),
					1,
					1,
					''
				)
			) EduInfo,
			(
				STUFF(
					(SELECT ',' + CompanyName + '@@' + JobName + '@@' + ISNULL(Description, '')
					FROM cvExperiencePublish b
					WHERE b.cvMainId = a.ID
					FOR XML PATH('')),
					1,
					1,
					''
				)
			) ExpInfo,
			(
				STUFF(
					(SELECT ',' + Name + '@@' + ISNULL(Description, '') + '@@' + ISNULL(Responsibilities, '')
					FROM cvProjectPublish b
					WHERE b.cvMainId = a.ID
					FOR XML PATH('')),
					1,
					1,
					''
				)
			) ProjectInfo,
			(
				STUFF(
					(SELECT ',' + Institution + '@@' + Course  + '@@' + ISNULL(Certificate, '') + '@@' + ISNULL(Details, '')
					FROM cvTrainingPublish b
					WHERE b.cvMainId = a.ID
					FOR XML PATH('')),
					1,
					1,
					''
				)
			) TrainInfo,
			GETDATE()
		FROM cvMainPublish a
		WHERE a.RefreshDate > CONVERT(VARCHAR(10), GETDATE() - 180, 120)
		AND a.Valid > 0

		CREATE TABLE #t2(cvMainId INT, IsDel BIT)
		INSERT INTO #t2 SELECT cvMainId, 0 FROM #T1

		DECLARE @i INT, @Page INT
		SELECT @i = 0, @Page = COUNT(*) / 10000 + 10 FROM #t1	

		TRUNCATE TABLE cvInfo

		WHILE @i < @Page
		BEGIN
			SET @i = @i + 1
			UPDATE #t2 SET IsDel = 1 WHERE cvMainId IN(SELECT TOP 10000 cvMainId FROM #t2)
			INSERT INTO cvInfo(cvMainId, JobName, Speciality, EduInfo, ExpInfo, ProjectInfo, TrainInfo, ModifyDate) 
			SELECT cvMainId, JobName, Speciality, EduInfo, ExpInfo, ProjectInfo, TrainInfo, GETDATE()
			FROM #t1
			WHERE cvMainId IN(SELECT cvMainId FROM #t2 WHERE IsDel = 1)
			AND cvMainId NOT IN(SELECT cvMainId FROM cvInfo)

			DELETE #t2 WHERE IsDel = 1
		END

		RETURN
	END		
	ELSE
	BEGIN
		CREATE TABLE #1(cvMainId INT)

		INSERT INTO #1
		SELECT cvMainId
		FROM bsCvVerify
		WHERE VerifyDate > DATEADD(MINUTE, -20, GETDATE())
		AND cvMainId IN(SELECT Id FROM cvMainPublish)
		AND NOT EXISTS(SELECT 'x' FROM cvInfo WHERE cvInfo.ModifyDate >= bsCvVerify.Verifydate)

		INSERT INTO #1		
		SELECT TOP 999 Id FROM cvMainPublish 
		WHERE RefreshDate > CONVERT(VARCHAR(10), GETDATE() - 180, 120)
		AND ID NOT IN(SELECT cvMainId FROM cvInfo)
		AND ID NOT IN(SELECT cvMainId FROM #1)
		AND Valid = 1

		SELECT Id cvMainId, JobName, Speciality,
			(
				STUFF(
					(SELECT ',' + GraduateCollage + '@@' + MajorName + '@@' + ISNULL(Details, '')
					FROM cvEducationPublish b
					WHERE b.cvMainId = a.ID
					FOR XML PATH('')),
					1,
					1,
					''
				)
			) EduInfo,
			(
				STUFF(
					(SELECT ',' + CompanyName + '@@' + JobName + '@@' + ISNULL(Description, '')
					FROM cvExperiencePublish b
					WHERE b.cvMainId = a.ID
					FOR XML PATH('')),
					1,
					1,
					''
				)
			) ExpInfo,
			(
				STUFF(
					(SELECT ',' + Name + '@@' + ISNULL(Description, '') + '@@' + ISNULL(Responsibilities, '')
					FROM cvProjectPublish b
					WHERE b.cvMainId = a.ID
					FOR XML PATH('')),
					1,
					1,
					''
				)
			) ProjectInfo,
			(
				STUFF(
					(SELECT ',' + Institution + '@@' + Course  + '@@' + ISNULL(Certificate, '') + '@@' + ISNULL(Details, '')
					FROM cvTrainingPublish b
					WHERE b.cvMainId = a.ID
					FOR XML PATH('')),
					1,
					1,
					''
				)
			) TrainInfo
		INTO #t
		FROM cvMainPublish a
		WHERE a.RefreshDate > CONVERT(VARCHAR(10), GETDATE() - 180, 120)
		AND a.Valid > 0
		AND ID IN(SELECT cvMainId FROM #1)

		DELETE FROM CvInfo WHERE cvMainID IN(SELECT cvMainId FROM #1)
		INSERT INTO cvInfo (cvMainId) SELECT DISTINCT cvMainId FROM #1
		
		UPDATE a SET a.JobName = b.JobName,
			a.Speciality = b.Speciality,
			a.EduInfo = b.EduInfo,
			a.ExpInfo = b.ExpInfo,
			a.ProjectInfo = b.ProjectInfo,
			a.TrainInfo = b.TrainInfo,
			a.ModifyDate = GETDATE()
		FROM cvInfo a, #t b
		WHERE a.cvMainId = b.cvMainId

		DELETE FROM cvInfo WHERE cvMainId NOT IN(SELECT Id FROM cvMainPublish WHERE RefreshDate > CONVERT(VARCHAR(10), GETDATE() - 180, 120) AND Valid = 1)
	END
END

GO
/****** Object:  StoredProcedure [dbo].[spCvMainByChar0Fix]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[spCvMainByChar0Fix]
AS
BEGIN
	create table #t(id int)
	create table #tt(id int)
--cveducation
	insert into #t Select id from cveducation where UNICODE(right(GraduateCollage,1)) = 0
	update cveducation set GraduateCollage=SUBSTRING(GraduateCollage, 1, LEN(GraduateCollage) - 1) where id in (select id from #t)
	DELETE #t

	INSERT INTO #t Select id from cveducation where UNICODE(right(MajorName,1)) = 0
	update cveducation set MajorName=SUBSTRING(MajorName, 1, LEN(MajorName) - 1) where id in (select id from #t)
	DELETE #t

	INSERT INTO #t Select id from cveducation where UNICODE(right(details,1)) = 0
	update cveducation set details=SUBSTRING(details, 1, LEN(details) - 1) where id in (select id from #t)
	DELETE #t
	--update cveducation set details=dbo.RemoveNullChars(details) where id in (select id from #t)
	--	select * from #t
	--	select * from cveducation where id=8030162

--cvexperience
	IF(SELECT COUNT(*) FROM #tt) =0
		INSERT INTO #t Select id from cvexperience where UNICODE(right(CompanyName,1)) = 0
	ELSE
		INSERT INTO #t Select id from cvexperience where UNICODE(right(CompanyName,1)) = 0 AND ID IN(SELECT ID FROM #tt)
	DELETE #tt
	INSERT #tt SELECT * FROM #t
	update cvexperience set CompanyName=SUBSTRING(CompanyName, 1, LEN(CompanyName) - 1) where id in (select id from #t)
	DELETE #t

	IF(SELECT COUNT(*) FROM #tt) =0
		INSERT INTO #t Select id from cvexperience where UNICODE(right(JobName,1)) = 0
	ELSE
		INSERT INTO #t Select id from cvexperience where UNICODE(right(JobName,1)) = 0 AND ID IN(SELECT ID FROM #tt)
	DELETE #tt
	INSERT #tt SELECT * FROM #t
	update cvexperience set JobName=SUBSTRING(JobName, 1, LEN(JobName) - 1) where id in (select id from #t)
	DELETE #t


	IF(SELECT COUNT(*) FROM #tt) =0
		INSERT INTO #t Select id from cvexperience where UNICODE(right(Description,1)) = 0
	ELSE
		INSERT INTO #t Select id from cvexperience where UNICODE(right(Description,1)) = 0 AND ID IN(SELECT ID FROM #tt)
	DELETE #tt
	INSERT #tt SELECT * FROM #t
	update cvexperience set Description=SUBSTRING(Description, 1, LEN(Description) - 1) where id in (select id from #t)
	--update cvexperience set Description=dbo.RemoveNullChars(Description) where id in (select id from #t)
	DELETE #t

	IF(SELECT COUNT(*) FROM #tt) =0
		INSERT INTO #t Select id from cvexperience where UNICODE(right(Dept,1)) = 0
	ELSE
		INSERT INTO #t Select id from cvexperience where UNICODE(right(Dept,1)) = 0 AND ID IN(SELECT ID FROM #tt)
	DELETE #tt
	INSERT #tt SELECT * FROM #t
	update cvexperience set Dept=SUBSTRING(Dept, 1, LEN(Dept) - 1) where id in (select id from #t)
	DELETE #t

	IF(SELECT COUNT(*) FROM #tt) =0
		INSERT INTO #t Select id from cvexperience where UNICODE(right(UpperPost,1)) = 0
	ELSE
		INSERT INTO #t Select id from cvexperience where UNICODE(right(UpperPost,1)) = 0 AND ID IN(SELECT ID FROM #tt)
	DELETE #tt
	INSERT #tt SELECT * FROM #t
	update cvexperience set UpperPost=SUBSTRING(UpperPost, 1, LEN(UpperPost) - 1) where id in (select id from #t)
	DELETE #t

--///////////////////////////
	IF(SELECT COUNT(*) FROM #tt) =0
		INSERT INTO #t Select id from cvmain where UNICODE(right(Speciality,1)) = 0
	ELSE
		INSERT INTO #t Select id from cvmain where UNICODE(right(Speciality,1)) = 0 AND ID IN(SELECT ID FROM #tt)
	DELETE #tt
	INSERT #tt SELECT * FROM #t
	update cvmain set Speciality=SUBSTRING(Speciality, 1, LEN(Speciality) - 1) where id in (select id from #t)
	--update cvmain set Speciality=dbo.RemoveNullChars(Speciality) where id in (select id from #t)
	DELETE #t
--////////////////////////
	drop table #t
	drop table #tt
end














GO
/****** Object:  StoredProcedure [dbo].[spCvMainByCvLevelCheck]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[spCvMainByCvLevelCheck]
AS
BEGIN
	select count(*) from cvmain with(nolock) where cvlevel like '1111_1%' and verifyresult=1 and iscvhidden=0 and valid=0
	select count(*) from cvmain with(nolock) where cvleveleng like '1111_1%' and verifyresulteng=1 and iscvhidden=0 and valid<2
	select count(*) from cvmain with(nolock) where iscvhidden=1 and valid>0
	select count(*) from cvmain with(nolock) where substring(cvlevel,3,1)='0' and id in(select cvmainid from cveducation with(nolock) where GraduateCollage>'')
	select count(*) from cvmain with(nolock) where substring(cvleveleng,3,1)='0' and id in(select cvmainid from cveducation with(nolock) where GraduateCollageeng>'')
	select count(*) from cvmain with(nolock) where substring(cvleveleng,4,1)='0' and id in(select cvmainid from cvexperience with(nolock) where companynameeng>'' and jobnameeng>'')
	select count(*) from cvmain with(nolock) where substring(cvlevel,4,1)='0' and id in(select cvmainid from cvexperience with(nolock) where companyname>'' and jobname>'')
	select count(*) from cvmain with(nolock) where substring(cvlevel,5,1)='0' and len(Speciality)>10 and refreshdate>getdate()-100
	select count(*) from cvmain with(nolock) where substring(cvleveleng,5,1)='0' and len(Specialityeng)>10 and refreshdate>getdate()-100
	select id,cvlevel,cvleveleng,refreshdate,dcsalaryid from cvmain with(nolock)
	where substring(cvlevel,6,1)='0' and left(cvlevel,2)='11'
	and dcsalaryid>0
	and id in(select cvmainid from cvjobtype with(nolock))
	and id in(select cvmainid from cvjobplace with(nolock))
	and refreshdate >getdate()-60
	order by refreshdate desc
END














GO
/****** Object:  StoredProcedure [dbo].[spcvMainByCvLevelFix]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[spcvMainByCvLevelFix]
AS
BEGIN
	CREATE TABLE #tt(ID INT)
	SELECT a.Id, a.cvLevel, a.cvLevelEng INTO #t 
	FROM cvMain a WITH(NOLOCK)
	INNER JOIN paMain b WITH(NOLOCK) ON a.paMainId = b.Id
	WHERE b.LastLoginDate > DATEADD(MINUTE, -120, GETDATE())
	OR a.RefreshDate > DATEADD(MINUTE, -120, GETDATE())

	INSERT INTO #tt(ID)
	SELECT ID FROM #T
	WHERE SUBSTRING(cvLevel, 2, 1) = 0
	AND ID IN(SELECT a.ID FROM cvMain a WITH(NOLOCK), paMain b WITH(NOLOCK) WHERE a.paMainId = b.ID AND b.Name > '' AND b.BirthDay > 0 AND Mobile >'')

	UPDATE cvMain SET cvLevel = '11' + RIGHT(cvLevel, 8)
	WHERE ID IN(SELECT ID FROM #tt)

	TRUNCATE TABLE #tt
	INSERT #tt SELECT ID FROM #T
	WHERE SUBSTRING(cvLevelEng, 2, 1) = 0
	AND ID IN(SELECT a.ID FROM cvMain a WITH(NOLOCK), paMain b WITH(NOLOCK) WHERE a.paMainId = b.ID AND b.NameEng > '' AND b.BirthDay > 0 AND Mobile >'')

	UPDATE cvMain SET cvLevelEng = '11' + RIGHT(cvLevelEng, 8)
	WHERE ID IN(SELECT ID FROM #tt)

	TRUNCATE TABLE #tt
	INSERT #tt SELECT ID FROM #T
	WHERE SUBSTRING(cvLevel, 3, 1) = 0
	AND ID IN(SELECT cvMainId FROM cvEducation WITH(NOLOCK) WHERE GraduateCollage>'')

	UPDATE cvMain SET cvLevel = LEFt(cvLevel, 2) + '1' + RIGHT(cvLevel, 7)
	WHERE Id IN(SELECT Id FROM #tt) 
	AND SUBSTRING(cvLevel, 3, 1) = '0'

	TRUNCATE TABLE #tt
	INSERT #tt SELECT ID FROM #T
	WHERE SUBSTRING(cvLevelEng, 3, 1) = 0
	AND ID IN(SELECT cvMainId FROM cvEducation WITH(NOLOCK) WHERE GraduateCollageEng>'')

	UPDATE cvMain SET cvLevelEng = LEFt(cvLevelEng, 2) + '1' + RIGHT(cvLevelEng, 7)
	WHERE Id IN(SELECT Id FROM #tt) 
	AND SUBSTRING(cvLevelEng, 3, 1) = '0'
	----------------
	TRUNCATE TABLE #tt
	INSERT #tt SELECT ID FROM #T
	WHERE SUBSTRING(cvLevel, 4, 1) = 0
	AND (ID IN(SELECT cvMainId FROM cvExperience WITH(NOLOCK) WHERE CompanyName>'')
		OR ID IN(SELECT ID FROM cvMain WITH(NOLOCK) WHERE cvType = 1)
		)

	UPDATE cvMain SET cvLevel = LEFt(cvLevel, 3) + '1' + RIGHT(cvLevel, 6)
	WHERE Id IN(SELECT Id FROM #tt) 
	AND SUBSTRING(cvLevel, 4, 1) = '0'

	TRUNCATE TABLE #tt
	INSERT #tt SELECT ID FROM #T
	WHERE SUBSTRING(cvLevelEng, 4, 1) = 0
	AND (ID IN(SELECT cvMainId FROM cvExperience WITH(NOLOCK) WHERE CompanyNameEng>'')
		OR (ID IN(SELECT ID FROM cvMain WITH(NOLOCK) WHERE cvType = 1)
			AND LEFT(cvLevelEng, 2) = '11')
		)

	UPDATE cvMain SET cvLevelEng = LEFt(cvLevelEng, 3) + '1' + RIGHT(cvLevelEng, 6)
	WHERE Id IN(SELECT Id FROM #tt) 
	AND SUBSTRING(cvLevelEng, 4, 1) = '0'

	-----------------
	TRUNCATE TABLE #tt
	INSERT #tt SELECT ID FROM #T
	WHERE SUBSTRING(cvLevel, 5, 1) = 0
	AND ID IN(SELECT Id FROM cvMain WITH(NOLOCK) WHERE LEN(Speciality)>4)

	UPDATE cvMain SET cvLevel = LEFt(cvLevel, 4) + '1' + RIGHT(cvLevel, 5)
	WHERE Id IN(SELECT Id FROM #tt)
	AND SUBSTRING(cvLevel, 5, 1) = '0'

	TRUNCATE TABLE #tt
	INSERT #tt SELECT ID FROM #T
	WHERE SUBSTRING(cvLevelEng, 5, 1) = 0
	AND ID IN(SELECT Id FROM cvMain WITH(NOLOCK) WHERE LEN(SpecialityEng)>4)

	UPDATE cvMain SET cvLevelEng = LEFt(cvLevelEng, 4) + '1' + RIGHT(cvLevelEng, 5)
	WHERE Id IN(SELECT Id FROM #tt)
	AND SUBSTRING(cvLevelEng, 5, 1) = '0'
	---------------------
	TRUNCATE TABLE #tt
	INSERT #tt SELECT ID FROM #T
	WHERE SUBSTRING(cvLevel, 6, 1) = 0
	AND ID IN(SELECT Id FROM cvMain WITH(NOLOCK) WHERE dcSalaryID>0)
	AND ID IN(SELECT cvMainID FROM cvJobType WITH(NOLOCK))
	AND ID IN(SELECT cvMainID FROM cvJobPlace WITH(NOLOCK))

	UPDATE cvMain SET cvLevel = LEFt(cvLevel, 5) + '1' + RIGHT(cvLevel, 4)
	WHERE Id IN(SELECT Id FROM #tt)
	AND SUBSTRING(cvLevel, 6, 1) = '0'

	TRUNCATE TABLE #tt
	INSERT #tt SELECT ID FROM #T
	WHERE SUBSTRING(cvLevelEng, 6, 1) = 0
	AND LEFT(cvLevelEng, 2) = '11'
	AND ID IN(SELECT Id FROM cvMain WITH(NOLOCK) WHERE dcSalaryID>0)
	AND ID IN(SELECT cvMainID FROM cvJobType WITH(NOLOCK))
	AND ID IN(SELECT cvMainID FROM cvJobPlace WITH(NOLOCK))

	UPDATE cvMain SET cvLevelEng = LEFT(cvLevelEng, 5) + '1' + RIGHT(cvLevelEng, 4)
	WHERE Id IN(SELECT Id FROM #tt)
	AND SUBSTRING(cvLevelEng, 6, 1) = '0'
	AND LEFT(cvLevelEng, 2) = '11'
	----------------
	TRUNCATE TABLE #tt
	INSERT #tt SELECT ID FROM #T
	WHERE SUBSTRING(cvLevel, 7, 1) = 0
	AND LEFT(cvLevel, 2) = '11'
	AND ID IN(SELECT cvMainId FROM cvLanguage WITH(NOLOCK))

	UPDATE cvMain SET cvLevel = LEFt(cvLevel, 6) + '1' + RIGHT(cvLevel, 3)
	WHERE Id IN(SELECT Id FROM #tt)
	AND SUBSTRING(cvLevel, 7, 1) = '0'

	TRUNCATE TABLE #tt
	INSERT #tt SELECT ID FROM #T
	WHERE SUBSTRING(cvLevelEng, 7, 1) = 0
	AND LEFT(cvLevelEng, 2) = '11'
	AND ID IN(SELECT cvMainId FROM cvLanguage WITH(NOLOCK))

	UPDATE cvMain SET cvLevelEng = LEFt(cvLevelEng, 6) + '1' + RIGHT(cvLevelEng, 3)
	WHERE Id IN(SELECT Id FROM #tt)
	AND SUBSTRING(cvLevelEng, 7, 1) = '0'

	----------------
	TRUNCATE TABLE #tt
	INSERT #tt SELECT ID FROM #T
	WHERE SUBSTRING(cvLevel, 8, 1) = 0
	AND ID IN(SELECT cvMainId FROM cvTraining WITH(NOLOCK) WHERE Institution > '')

	UPDATE cvMain SET cvLevel = LEFt(cvLevel, 7) + '1' + RIGHT(cvLevel, 2)
	WHERE Id IN(SELECT Id FROM #tt)
	AND SUBSTRING(cvLevel, 8, 1) = '0'

	TRUNCATE TABLE #tt
	INSERT #tt SELECT ID FROM #T
	WHERE SUBSTRING(cvLevelEng, 8, 1) = 0
	AND ID IN(SELECT cvMainId FROM cvTraining WITH(NOLOCK) WHERE InstitutionEng > '')

	UPDATE cvMain SET cvLevelEng = LEFt(cvLevelEng, 7) + '1' + RIGHT(cvLevelEng, 2)
	WHERE Id IN(SELECT Id FROM #tt)
	AND SUBSTRING(cvLevelEng, 8, 1) = '0'

	----------------
	TRUNCATE TABLE #tt
	INSERT #tt SELECT ID FROM #T
	WHERE SUBSTRING(cvLevel, 9, 1) = 0
	AND ID IN(SELECT cvMainId FROM cvProject WITH(NOLOCK) WHERE Name > '')

	UPDATE cvMain SET cvLevel = LEFt(cvLevel, 8) + '1' + RIGHT(cvLevel, 1)
	WHERE Id IN(SELECT Id FROM #tt)
	AND SUBSTRING(cvLevel, 9, 1) = '0'

	TRUNCATE TABLE #tt
	INSERT #tt SELECT ID FROM #T
	WHERE SUBSTRING(cvLevelEng, 9, 1) = 0
	AND ID IN(SELECT cvMainId FROM cvProject WITH(NOLOCK) WHERE NameEng > '')

	UPDATE cvMain SET cvLevelEng = LEFt(cvLevelEng, 8) + '1' + RIGHT(cvLevelEng, 1)
	WHERE Id IN(SELECT Id FROM #tt)
	AND SUBSTRING(cvLevelEng, 9, 1) = '0'

	----------------
	TRUNCATE TABLE #tt
	INSERT #tt SELECT ID FROM #T
	WHERE RIGHT(cvLevel, 1) = '0'
	AND LEFT(cvLevel, 2) = '11'
	AND ID IN(SELECT cvMainId FROM cvAppendix WITH(NOLOCK))

	UPDATE cvMain SET cvLevel = LEFt(cvLevel, 9) + '1'
	WHERE Id IN(SELECT Id FROM #tt)
	AND RIGHT(cvLevel, 1) = '0'
	AND LEFT(cvLevel, 2) = '11'

	TRUNCATE TABLE #tt
	INSERT #tt SELECT ID FROM #T
	WHERE RIGHT(cvLevelEng, 1) = '0'
	AND LEFT(cvLevelEng, 2) = '11'
	AND ID IN(SELECT cvMainId FROM cvAppendix WITH(NOLOCK))

	UPDATE cvMain SET cvLevelEng = LEFt(cvLevelEng, 9) + '1'
	WHERE Id IN(SELECT Id FROM #tt)
	AND RIGHT(cvLevelEng, 1) = '0'
	AND LEFT(cvLevelEng, 2) = '11'

	TRUNCATE TABLE #tt
	DROP TABLE #t
	-----------
	------------------
	UPDATE paMain SET RegisterType = 102 WHERE RegisterMode = 11 AND RegisterType = 101 AND LastLoginDate > GETDATE() - 1
 
	CREATE TABLE #1(id INT IDENTITY(1, 1), cvMainId INT)
	INSERT INTO #1(cvMainId)
	SELECT a.Id
	FROM cvMain a, paMain b
	WHERE a.paMainId  = b.Id
	AND b.BlockCount = 0
	AND b.VerifyCount > 0
	AND b.LastLoginDate > GETDATE() - 3
	AND (b.RegisterMode = 1 OR  b.RegisterType = 101)
	AND b.AddMan >= 112
	AND a.VerifyResult = 1
	AND a.cvLevel LIKE '1111_1%'

	DECLARE @Id INT, @cvMainId INT
	SET @Id = 0
	WHILE EXISTS(SELECT 'x' FROM #1 WHERE Id > @Id)
	BEGIN
		SELECT TOP 1 @Id = Id, @cvMainId = cvMainId FROM #1 WHERE Id > @id ORDER BY ID
		UPDATE cvMain SET VerifyResult = VerifyResult WHERE Id = @cvMainId
 	END
 	DROP TABLE #1
ENd


GO
/****** Object:  StoredProcedure [dbo].[spCvMainByIsOpenUpdate]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[spCvMainByIsOpenUpdate]
AS
BEGIN
	--1--按条件把状态改为开放
	UPDATE a SET a.IsOpen = 1 
	FROM cvMain a WITH(NOLOCK) 
	INNER JOIN paMain b WITH(NOLOCK) ON a.paMainId = b.Id AND b.LastLoginDate > GETDATE()-  2
	INNER JOIN dcCvOpenSET c WITH(NOLOCK) ON a.Degree = c.dcEducation
		AND b.LivePlace LIKE CONVERT(VARCHAR(2), c.dcProvinceId) + '%'
	WHERE (ISNULL(b.BirthDay, 999999) > dbo.AgeToBirth(c.Age))
	AND a.IsOpen = 0 
	AND (
		(a.VerifyResult = 1 AND a.cvLevel LIKE '111__1%')
		OR (a.VerifyResultEng = 1 AND a.cvLevelEng LIKE '111__1%')
		)
	--2--按条件把状态改为不开放
	UPDATE a SET a.IsOpen = 0
	FROM cvMain a WITH(NOLOCK)
	INNER JOIN paMain b WITH(NOLOCK) ON a.paMainId = b.Id AND b.LastLoginDate > GETDATE()-  2
	INNER JOIN dcCvOpenSET c WITH(NOLOCK) ON a.Degree = c.dcEducation
		AND b.LivePlace LIKE CONVERT(VARCHAR(2), c.dcProvinceId) + '%'
	WHERE b.BirthDay <= dbo.AgeToBirth(c.Age)
	AND a.IsOpen = 1
	AND IsNull(b.Mobile, '') <> '' --Richard 2011.8.21增加，避免反复修改
	AND (
		(a.VerifyResult = 1 AND a.cvLevel LIKE '111__1%')
		OR (a.VerifyResultEng = 1 AND a.cvLevelEng LIKE '111__1%')
		)
	--3--初中学历都是开放简历
	UPDATE cvMain SET IsOpen = 1
	WHERE degree = 1
	AND IsOpen = 0
	--4--没有手机的账号 一定是开放简历
	UPDATE cvMain SET IsOpen = 1
	WHERE IsOpen = 0
	AND Attachment IS NULL
	AND paMainID IN(
		SELECT ID FROM paMain a WITH(NOLOCK)
		WHERE IsNull(Mobile, '') = ''
		AND LastLoginDate > GETDATE()-  2
	)
	--5--附件简历都不开放
	UPDATE cvMain SET IsOpen = 0 
	WHERE IsOpen = 1
	AND NOT (
		(VerifyResult = 1 AND cvLevel LIKE '111__1%')
		OR (VerifyResultEng = 1 AND cvLevelEng LIKE '111__1%')
		)
	AND Attachment IS NOT NULL
	AND paMainID IN (SELECT ID FROM paMain WITH(NOLOCK) 
			WHERE LastLoginDate > GETDATE()-  2)
	--6--无效简历都是开放
	UPDATE cvMain SET IsOpen = 1 
	WHERE IsOpen = 0 
	AND NOT (
		(VerifyResult = 1 AND cvLevel LIKE '111__1%')
		OR (VerifyResultEng = 1 AND cvLevelEng LIKE '111__1%')
		)
	AND Attachment IS NULL
	AND paMainID IN (SELECT ID FROM paMain WITH(NOLOCK) 
			WHERE LastLoginDate > GETDATE()-  2)
END
GO
/****** Object:  StoredProcedure [dbo].[spCvMainByJobNameFix]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[spCvMainByJobNameFix]
AS
SET NOCOUNT ON
BEGIN
	CREATE TABLE #t(Id INT IDENTITY(1, 1), cvMainId INT, JobName VARCHAR(50))
	INSERT #t SELECT Id, NULL FROM cvMain WHERE SecondId = JobName AND Valid > 0
	UPDATE #t SET JobName = (SELECT TOP 1 Jobname FROM cvExperience WHERE cvExperience.cvMainId = #t.cvMainId ORDER BY BeginDate desc)

	UPDATE a SET a.JobName = b.JobName FROM cvMain a, #t b WHERE a.id = b.cvmainid AND b.JobName >''
	DELETE FROM #t WHERE JobName > ''

	DELETE FROM #t 

	INSERT #t SELECT Id, NULL FROM cvMain WHERE SecondId = JobName AND Valid > 0
	AND paMainId IN(SELECT id FROM paMain WHERE BirthDay > CONVERT(VARCHAR(6), DATEADD(YEAR, -25, GETDATE()), 112) AND LastLoginDate > GETDATE() - 3)

	------------------------------------

	CREATE TABLE #jn(cvMainId INT, dcJobTypeId INT, JobName NVARCHAR(20))

	INSERT INTO #jn(cvMainID)
	SELECT ID
	FROM cvMain
	WHERE JobName IS NULL
	AND Valid > 0
	AND paMainId IN(SELECT id FROM paMain WHERE BirthDay <= CONVERT(VARCHAR(6), DATEADD(YEAR, -25, GETDATE()), 112) AND LastLoginDate > GETDATE() - 3)

	INSERT INTO #jn(cvMainID) SELECT cvMainId FROM #t WHERE cvMainId NOT IN(SELECT cvMainId FROM #Jn)

	UPDATE #jn SET dcJobTypeId = (SELECT TOP 1 dcJobTypeId FROM cvJobType WHERE cvJobType.cvMainId = #jn.cvMainId)

	UPDATE a SET a.JobName = '期望' + b.Description FROM #jn a, dcJobType b WHERE a.dcjobTypeId = b.Id

	DELETE FROM #jn WHERE JobName IS NULL

	UPDATE a SET a.JobName = b.JobName FROM cvMain a, #jn b WHERE a.Id = b.cvMainId AND a.JobName IS NULL
	UPDATE a SET a.JobName = b.JobName FROM cvMain a, #jn b WHERE a.Id = b.cvMainId AND a.Secondid = a.JobName

	UPDATE a SET a.JobName = b.JobName FROM cvMainPublish a, #jn b WHERE a.Id = b.cvMainId AND a.JobName IS NULL
	AND a.Id IN(SELECT TOP 9999 a.ID FROM cvMainPublish a, #jn b WHERE a.Id = b.cvMainId AND a.JobName IS NULL)
 
	UPDATE a SET a.JobName = b.JobName FROM cvMainPublish a, cvMain b 
	WHERE a.Id = b.Id AND a.Id IN(SELECT TOP 3000 a.Id FROM cvMainPublish a WITH(NOLOCK), cvMain b WITH(NOLOCK) WHERE a.Id = b.Id AND ISNULL(a.JobName, '') <> b.JobName)
	-------------------------------

	SELECT a.Id paMainId, b.Id cvMainId
	INTO #pc
	FROM paMain a, cvMain b
	WHERE a.Id = b.paMainId
	AND a.LastLoginDate >= CONVERT(VARCHAR(10), GETDATE() -365, 120)
	AND b.Valid > 0

	CREATE TABLE #delp(id INT, HasDel BIT)
	INSERT INTO #Delp SELECT ID, 0 FROM paMainPublish WHERE Id NOT IN(SELECT paMainId FROM #pc)
	 
	UPDATE #delp SET HasDel = 1 WHERE Id IN(SELECT TOP 3999 ID FROM #Delp)
	DELETE FROM paMainPublish WHERE Id IN(SELECT ID FROM #delp WHERE HasDel = 1)
	DELETE #delp WHERE HasDel = 1

	INSERT INTO paMainPublish(ID, Gender, BirthDay, LivePlace, AccountPlace, GrowPlace, Height, HasPhoto, LastLoginDate, LastModifyDate, MobileRegion)
	SELECT TOP 2000 ID, Gender, BirthDay, LivePlace, AccountPlace, GrowPlace, Height, HasPhoto, LastLoginDate, LastModifyDate, MobileRegion
	FROM paMain WHERE ID IN(SELECT paMainId FROM #pc WHERE paMainId NOT IN(SELECT Id FROM paMainPublish))

	INSERT INTO cvMainPublish(ID, paMainID, Degree, dcMajorID, LastJobTypeID, LastIndustryID, JobName, SubNodeNum, 
		RelatedWorkYears, dcSalaryID, IsNegotiable, Speciality, SpecialityEng, Attachment, Valid, RefreshDate, EmployType)
	SELECT TOP 2000 ID, paMainID, Degree, dcMajorID, LastJobTypeID, LastIndustryID, JobName, SubNodeNum, 
		RelatedWorkYears, dcSalaryID, IsNegotiable, Speciality, SpecialityEng, Attachment, Valid, RefreshDate, EmployType
	FROM cvMain 
	WHERE ID IN(SELECT cvMainId FROM #pc WHERE cvMainId NOT IN(SELECT Id FROM cvMainPublish))
	ORDER BY ID

--	SELECT (SELECT COUNT(DISTINCT paMainId) FROM #pc) pnum,
--		(SELECT COUNT(DISTINCT cvMainId) FROM #pc) cnum,
--		(SELECT COUNT(*) FROM cvMainPublish WHERE Id NOT IN(SELECT cvMainId FROM #pc)) cnumnotin,
--		(SELECT COUNT(*) FROM cvMainPublish WHERE Id IN(SELECT cvMainId FROM #pc)) cnumin,
--		(SELECT COUNT(*) FROM paMainPublish WHERE Id NOT IN(SELECT paMainId FROM #pc)) pnumnotin,
--		(SELECT COUNT(*) FROM paMainPublish WHERE Id IN(SELECT paMainId FROM #pc)) pnumin
--	DROP TABLE #pc
--	DROP TABLE #Delp
END













GO
/****** Object:  StoredProcedure [dbo].[SpCvMainByJobNameUpdate]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[SpCvMainByJobNameUpdate]
AS
BEGIN
	create table #t(id int)
	insert into #t
	select id 
	from cvmain 
	where pamainid in (
		select id from pamain 
		where lastlogindate between getdate()-180 and getdate() - 0.2 
		and birthday<=convert(varchar(6), dateadd(year,-25,getdate()), 112))
	and valid = 0
	and cvlevel like '1110_1%'
	and cvtype=0
	--and pamainid not in(select pamainid from cvmain where valid>0)

	update cvmain set cvtype=1, cvlevel = '1111' + right(cvlevel, 6) where id in(select id from #t)
	update cvmain set jobname=id where id in(select id from #t) and jobname is null
	--------
	truncate table #t
	insert into #t
	select id 
	from cvmain 
	where pamainid in (
		select id from pamain 
		where lastlogindate between getdate()-180 and getdate() - 0.2 
		and birthday>convert(varchar(6), dateadd(year,-25,getdate()), 112))
	and valid = 0
	and cvlevel like '1110_1%'
	and cvtype=0
	--and pamainid not in(select pamainid from cvmain where valid>0)

	update cvmain set cvtype=1, cvlevel = '1111' + right(cvlevel, 6) where id in(select id from #t)
	update cvmain set jobname='应届毕业生' where id in(select id from #t) and jobname is null
	---------------

	update cvmain set jobname=id
	where pamainid in (select id from pamain where lastlogindate > getdate()-180 and birthday<=convert(varchar(6), dateadd(year,-25,getdate()), 112))
	and valid > 0
	and jobname='应届毕业生'

	update cvmain set jobname='应届毕业生'
	where pamainid in (select id from pamain where lastlogindate > getdate()-180 and birthday>convert(varchar(6), dateadd(year,-25,getdate()), 112))
	and valid > 0
	and jobname = SecondId
END
GO
/****** Object:  StoredProcedure [dbo].[spCvMainByNameFix]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[spCvMainByNameFix]
AS
BEGIN
	CREATE TABLE #t(
		ID INT,
		JobType SMALLINT,
		JobPlace VARCHAR(6),
		JobTypeDesc NVARCHAR(30),
		JobPlaceDesc NVARCHAR(20),
		cvName NVARCHAR(50)
		)

	INSERT INTO #t(ID)
	SELECT a.Id FROM cvMain a WITH(NOLOCK), paMain b WITH(NOLOCK)
		WHERE (a.RefreshDate > DATEADD(MINUTE, -70, GETDATE())
			OR b.LastLoginDate > DATEADD(MINUTE, -70, GETDATE()))
		AND a.paMainId = b.ID
		AND a.dcSalaryId > 0
		AND a.ID IN(SELECT cvMainID FROM cvJobType)
		AND a.ID IN(SELECT cvMainID FROM cvJobPlace)
		AND a.Name = '未完成简历'
	
	UPDATE #t SET JobType = (SELECT TOP 1 dcJobTypeID FROM cvJobType WITH(NOLOCK) WHERE cvJobType.cvMainId = #t.ID)
	UPDATE #t SET JobPlace = (SELECT TOP 1 dcRegionId FROM cvJobPlace WITH(NOLOCK) WHERE cvJobPlace.cvMainId = #t.ID)
	UPDATE #t SET JobTypeDesc = (SELECT TOP 1 Description FROM dcJobType WITH(NOLOCK) WHERE dcJobType.ID = #t.JobType)
	UPDATE #t SET JobPlaceDesc = (SELECT TOP 1 Description FROM dcRegion WITH(NOLOCK) WHERE dcRegion.ID = #t.JobPlace)
	UPDATE #t SET cvName = JobPlaceDesc + '+' + JobTypeDesc WHERE JobPlaceDesc IS NOT NULL AND JobTypeDesc IS NOT NULL
	DELETE FROM #t WHERE cvName IS NULL

	UPDATE a
	SET a.Name = b.cvName
	FROM cvMain a WITH(NOLOCK), #t b
	WHERE a.id = b.id

	DROP TABLE #t
END














GO
/****** Object:  StoredProcedure [dbo].[spCvMainByValidFix]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[spCvMainByValidFix]
AS
SET NOCOUNT ON
BEGIN
	SELECT a.ID INTO #t FROM cvMain a WITH(NOLOCK), paMain b WITH(NOLOCK) 
	WHERE a.paMainID = b.ID AND (b.LastLoginDate > GETDATE() - 2 OR a.RefreshDate > GETDATE() - 2)

	UPDATE cvMain SET Valid = 0 WHERE IsCvHidden = 1 AND Valid > 0 AND ID IN(SELECT ID FROM #T)
	UPDATE cvMain SET Attachment = NULL WHERE Attachment = '' AND ID IN(SELECT ID FROM #T)

	UPDATE cvMain SET Valid = 0
	WHERE NOT (cvLevel LIKE '1111_1%' AND VerifyResult = 1)
	AND NOT (cvLevelEng LIKE '1111_1%' AND VerifyResultEng = 1)
	AND Valid > 0
	AND IsCvHidden = 0
	AND Attachment IS NULL
	AND ID IN(SELECT ID FROM #T)

	UPDATE cvMain SET Valid = 1 
	WHERE cvLevel LIKE '1111_1%'
	AND VerifyResult = 1
	AND NOT (cvLevelEng LIKE '1111_1%' AND VerifyResultEng = 1)
	AND IsCvHidden = 0
	AND Valid <> 1
	AND ID IN(SELECT ID FROM #T)

	UPDATE cvMain SET Valid = 2 
	WHERE cvLevel LIKE '1111_1%' 
	AND VerifyResult = 1
	AND cvLevelEng LIKE '1111_1%'
	AND VerifyResultEng = 1
	AND Valid <> 2
	AND IsCvHidden = 0
	AND ID IN(SELECT ID FROM #T)

	UPDATE cvMain SET Valid = 3
	WHERE NOT (cvLevel LIKE '1111_1%' AND VerifyResult = 1)
	AND cvLevelEng LIKE '1111_1%'
	AND VerifyResultEng = 1
	AND Valid <> 3
	AND IsCvHidden = 0
	AND ID IN(SELECT ID FROM #T)

	UPDATE cvMain SET Valid = 1
	WHERE cvLevel NOT LIKE '1111_1%'
	AND cvLevelEng NOT LIKE '1111_1%'
	AND VerifyResult = 1
	AND VerifyResultEng = 1
	AND Attachment > ''
	AND Valid <> 1
	AND IsCvHidden = 0
	AND ID IN(SELECT ID FROM #T)

	-----------------------------------------------------------
	CREATE TABLE #t2(Seq INT IDENTITY(1, 1), Id INT)

	INSERT INTO #t2
	SELECT Id FROM cvMain WITH(NOLOCK)
	WHERE cvLevel LIKE '1111_1%' 
	AND VerifyResult = 1 
	AND IsCvHidden = 0 
	AND Valid=0 
	AND Id IN(SELECT ID FROM #t)
	ORDER BY ID DESC

	INSERT INTO #t2
	SELECT ID
	FROM cvMain WITH(NOLOCK)
	WHERE Attachment > '' 
	AND Valid = 0
	AND IsCvHidden = 0
	AND VerifyResult != 10
	AND VerifyResultEng != 10
	AND Id IN(SELECT ID FROM #t)

	DECLARE @S VARCHAR(MAX), @I INT, @All INT
	SELECT @All = MAX(Seq) FROM #t2
	SET @i = 1
	WHILE (@i < @All)
	BEGIN
		SELECT @s = 'UPDATE cvMain SET cvLevel = cvLevel WHERE Id = ' + LTRIM(STR(ID)) FROM #t2 WHERE Seq = @i
		EXEC(@s)
		SET @i = @i + 1
	END

	DROP TABLE #t2
	DROP TABLE #t
END

GO
/****** Object:  StoredProcedure [dbo].[SpCvMainByYingJieShengFix]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[SpCvMainByYingJieShengFix]
AS
SET NOCOUNT ON
BEGIN
	SELECT Id, LastJobTypeId JobTypeId, SPACE(6) RegionId, 
		SPACE(50) JobTypeName, SPACE(20) RegionName, JobName
	INTO #t
	FROM cvMain WITH(NOLOCK)
	WHERE (JobName = '应届毕业生' OR JobName = '附件简历' OR JobName = SecondId)
	AND paMainId IN(SELECT Id FROM paMain WITH(NOLOCK) WHERE LastLoginDate > GETDATE() - 3)
	AND cvLevel LIKE '1111_1%'
	ORDER BY ID DESC

	UPDATE #t SET JobTypeId = (SELECT TOP 1 dcJobTypeId FROM cvJobType WITH(NOLOCK) WHERE cvJobType.cvMainId = #t.Id)
	UPDATE #t SET RegionId = (SELECT TOP 1 dcRegionId FROM cvJobPlace WITH(NOLOCK) WHERE cvJobPlace.cvMainId = #t.Id)
	UPDATE #t SET JobTypeName = (SELECT Description FROM dcJobType WITH(NOLOCK) WHERE dcJobType.Id = JobTypeId)
	UPDATE #t SET JobTypeName = LEFT(JobTypeName, CHARINDEX('/', JobTypeName) -1) WHERE CHARINDEX('/', JobTypeName) > 2
	UPDATE #t SET RegionName = (SELECT Description FROM dcRegion WITH(NOLOCK) WHERE dcRegion.Id = RegionId)
	UPDATE #t SET RegionName = LEFT(RegionName, LEN(RegionName) - 1) WHERE LEN(RegionName) > 2 AND RIGHT(RegionName, 1) IN('省', '市', '县', '区', '旗')
	UPDATE #t SET JobName = LEFT(JobTypeName + ' ' + RegionName, 20)

	SELECT COUNT(*) FROM #t

	UPDATE a
	SET a.JobName = b.JobName
	FROM cvMain a, #t b
	WHERE a.id = b.id
	--AND a.JobName = '应届毕业生'

	UPDATE a
	SET a.JobName = b.JobName
	FROM cvMainPublish a, cvmain b
	WHERE ISNULL(a.JobName, '') <> ISNULL(b.JobName, '')
	AND a.Id = b.Id
END

GO
/****** Object:  StoredProcedure [dbo].[spcvMainClear]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[spcvMainClear]
AS
BEGIN
	DECLARE @ID AS INT, @PaMainID AS INT
	CREATE TABLE #Id(ID INT)
	SELECT @ID = MIN(ID) FROM paMain WITH(NOLOCK) WHERE AddDate > DATEADD(DAY, - 1, GETDATE())
	SELECT ID INTO #t FROM cvMain WITH(NOLOCK) WHERE paMainID IN(SELECT ID FROM PaMain WITH(NOLOCK) WHERE NAME = '王蓓' AND ID > @ID)

	IF (SELECT COUNT(*) FROM #t) > 0
	BEGIN
		INSERT #ID
		SELECT ID FROM cvMain WITH(NOLOCK) 
		WHERE ID IN(SELECT ID FROM #t)
		AND (Speciality LIKE '%冰毒%'
			OR Speciality LIKE '%戚慧丽%'
			OR Speciality LIKE '%58585528%'
			OR Speciality LIKE '%王敏昌%'
			)
		
		INSERT #Id
		SELECT cvMainID FROM cvExperience WITH(NOLOCK) 
		WHERE cvMainID IN(SELECT ID FROM #t)
		AND (DESCRIPTION LIKE '%冰毒%'
			OR DESCRIPTION LIKE '%戚慧丽%'
			OR DESCRIPTION LIKE '%58585528%'
			OR DESCRIPTION LIKE '%王敏昌%'
			)
		
		INSERT #Id
		SELECT cvMainID FROM cvEducation WITH(NOLOCK) 
		WHERE cvMainID IN(SELECT ID FROM #t)
		AND (DETAILS LIKE '%冰毒%'
			OR DETAILS LIKE '%戚慧丽%'
			OR DETAILS LIKE '%58585528%'
			OR DETAILS LIKE '%王敏昌%'
			)

		IF(SELECT COUNT(*) FROM #Id) > 0
		BEGIN
			DELETE ExJobApply WHERE cvMainID IN(SELECT ID FROM #ID)
			UPDATE cvMain SET IsCvHidden = 1 WHERE ID IN(SELECT ID FROM #t)
			UPDATE cvMain SET VerifyResult = 10 WHERE ID IN(SELECT ID FROM #t)
		END
	END
END











GO
/****** Object:  StoredProcedure [dbo].[spdcCpMainIdTempinsert]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[spdcCpMainIdTempinsert]
as
begin
	SELECT  a.LoginCookies, COUNT(DISTINCT b.CpMainId) Cnt
	INTO #t2
	FROM caLoginLog a, caMain b
	WHERE a.AddDate > GETDATE() - 130
	AND a.caMainId = b.Id
	AND LEN(a.LoginCookies) > 10
	GROUP BY a.LoginCookies
	HAVING COUNT(DISTINCT b.CpMainId) > 10

	SELECT CONVERT(varchar(10), a.adddate, 120) d,  a.Loginip, COUNT(DISTINCT b.CpMainId) Cnt
	INTO #t1
	FROM caLoginLog a, caMain b
	WHERE a.AddDate > GETDATE() - 130
	AND a.caMainId = b.Id
	AND LEN(a.LoginCookies) > 10
	GROUP BY CONVERT(varchar(10), a.adddate, 120), a.Loginip
	HAVING COUNT(DISTINCT b.CpMainId) > 10

	DELETE a
	from #t1 a, ip_white b
	where a.loginip like b.ip + '%'

	SELECT Distinct caMainId INTO #ca FROM caLoginLog WHERE LoginCookies IN(SELECT LoginCookies FROM #t2)
	insert into #ca
	SELECT Distinct caMainId FROM caLoginLog a, #t1 b
	WHERE a.Loginip=b.LoginIp
	and CONVERT(varchar(10), a.adddate, 120) = b.d

	SELECT DISTINCT cpMainId INTO #cp FROM caMain WHERE ID IN(SELECT caMainId FROM #ca)

	--select * from #t2 order by cnt desc
	--select * from #ca
	drop table dcCpMainIdTemp
	select * into dcCpMainIdTemp from #cp
end









GO
/****** Object:  StoredProcedure [dbo].[spDcIpPlaceByInternationalUpdate]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[spDcIpPlaceByInternationalUpdate]
AS
BEGIN
	SELECT DISTINCT City
	INTO #t
	FROM dcIpPlace WITH(NOLOCK)

	DELETE #t WHERE LEFT(City, 2) IN(SELECT LEFT(SubSiteCity, 2) FROM dcSubSite WITH(NOLOCK))
	OR LEFT(City, 2) IN('华南','全国','清华','东北','东华','华东','华中','西北','首都','长江','集美','纯真','黄河','西华','对外')
	OR City LIKE '中%'
	OR City LIKE '%中国%'
	OR City LIKE '%香港%'
	OR City LIKE '%台湾%'
	OR City LIKE '%澳门%'
	OR City LIKE '%大学%'
	OR City LIKE '%局域网%'
	OR City LIKE '%s246%'
	OR City LIKE '%本机%'
	OR City LIKE '%网络%'
	OR City LIKE '%UCWEB%'

	UPDATE dcIpPlace SET International = NULL WHERE International = 1
	UPDATE dcIpPlace SET International = 1 WHERE City NOT IN(SELECT City FROM #t)
END














GO
/****** Object:  StoredProcedure [dbo].[spdcJobTypeMajorMapUpdate]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[spdcJobTypeMajorMapUpdate]
AS
BEGIN
	CREATE TABLE #t(Id INT IDENTITY(1, 1), dcJobTypeId INT, MajorName NVARCHAR(50), Cnt INT)
	INSERT INTO #t
	SELECT y.dcJobTypeid, x.MajorName, COUNT(*) Cnt
	FROM cveducation x WITH(NOLOCK)
	INNER JOIN cvJobtype y WITH(NOLOCK) ON x.cvMainId = y.cvMainId
	WHERE EXISTS(SELECT 'x' FROM cvMain WHERE Id = x.cvMainId AND RefreshDate > '2016-1-1')
	GROUP BY y.dcJobTypeid, x.MajorName 
	ORDER BY y.dcJobTypeid, COUNT(*) DESC

	DELETE #t WHERE MajorName = '无'
	DELETE #t WHERE MajorName IS NULL
	DELETE #t WHERE MajorName = ''
	DELETE #t WHERE MajorName = '所学专业未填写'

	SELECT TOP 0 * INTO #1 FROM dcJobTypeMajorMap
	INSERT INTO #1
	SELECT *
	FROM (SELECT a.dcJobTypeId, a.MajorName, b.dcMajorId, ROW_NUMBER() OVER(PARTITION BY dcJobTypeId ORDER BY ID) RowNo,
			b.PinYin, b.JianPin
		FROM #t a, dcMajorKeyword b
		WHERE a.MajorName = b.MajorName) a
	WHERE RowNo = 1
	ORDER BY dcjobTypeId

	UPDATE a SET a.Description = b.Description FROM #1 a, dcMajor b WHERE a.dcMajorId = b.Id
	TRUNCATE TABLE ShortDb..dcJobTypeMajorMap

	INSERT INTO dcJobTypeMajorMap
	SELECT dcJobTypeID, MajorName, dcMajorId, Description, PinYin, JianPin
	FROM #1
END

GO
/****** Object:  StoredProcedure [dbo].[spDcRegionByNameUpdate]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[spDcRegionByNameUpdate](
	@ID VARCHAR(6),
	@OldName NVARCHAR(100),
	@NewName NVARCHAR(100)
)
AS
BEGIN
	UPDATE dcREgion 
	SET Description = REPLACE(Description, @OldName, @NewName),
	DescriptionEng = REPLACE(DescriptionEng, @OldName, @NewName),
	FullName = REPLACE(FullName, @OldName, @NewName)
	WHERE ID = @ID
END














GO
/****** Object:  StoredProcedure [dbo].[spDeleteCpImageFileSample]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--lambo 20110120
--删除logo，Visual的sql自动计划任务
--删除审核不通过的超过30天的logo，Visual。不用修改cpMain里的hasLog,hasVisual的值。因为未审核通过hasLog也是0
CREATE PROCEDURE [dbo].[spDeleteCpImageFileSample]
AS
BEGIN
	SET NOCOUNT ON
	DECLARE cur_cpImage CURSOR
    FOR
        SELECT cpMainID,ImgFile,ImgType FROM cpImage WHERE HasPassed=0 AND CheckDate < GETDATE()-30 
    OPEN cur_cpImage
    DECLARE @cpMainID INT,@ImgFile VARCHAR(150),@imgType INT,@cmdStr VARCHAR(500),@path VARCHAR(500)
    FETCH NEXT FROM cur_cpImage INTO @cpMainID,@imgFile,@imgType
	BEGIN TRY
		EXEC SP_CONFIGURE 'show advanced options', 1
		RECONFIGURE
		EXEC SP_CONFIGURE 'xp_cmdshell', 1
		RECONFIGURE
    
		WHILE @@FETCH_STATUS = 0
		BEGIN      
			IF @ImgType = 1
			BEGIN
				SET @path = (SELECT dbo.photoPath(@cpMainID,4))
				SET @cmdStr = 'del D:\hosting\qlrc.com\imagefolder\Logo\' + @path + '\' + @imgFile    --删除Logo目录
			END
			ELSE IF @ImgType = 2
			BEGIN
				SET @path = (SELECT dbo.photoPath(@cpMainID,4))
				SET @cmdStr = 'del D:\hosting\qlrc.com\imagefolder\Visual\' + @path + '\' + @imgFile    --删除Visual目录
			END
			EXEC master.dbo.xp_cmdshell @cmdStr 
			DELETE FROM cpImage WHERE cpMainID = @cpMainID AND ImgType = @ImgType
			FETCH NEXT FROM cur_cpImage INTO @cpMainID,@imgFile,@imgType
		END
		EXEC SP_CONFIGURE 'xp_cmdshell', 0
		RECONFIGURE
		EXEC SP_CONFIGURE 'show advanced options', 0
		RECONFIGURE
	END TRY
	BEGIN CATCH
	END CATCH
    CLOSE cur_cpImage 
    DEALLOCATE cur_cpImage
END














GO
/****** Object:  StoredProcedure [dbo].[spDeleteFileSample]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[spDeleteFileSample]
AS
BEGIN
	EXEC SP_CONFIGURE 'show advanced options', 1
	RECONFIGURE
	EXEC SP_CONFIGURE 'xp_cmdshell', 1
	RECONFIGURE
    DECLARE cur_paPhoto CURSOR
    FOR  
        SELECT p.paMainID, p.PhotoProcessed Photo FROM paPhoto AS p INNER JOIN paMain AS m ON m.ID = p.paMainID
        WHERE m.hasPhoto = 2 AND CheckDate < GETDATE()-30
    OPEN cur_paPhoto
    DECLARE @id INT,@photo VARCHAR(150),@cmdStr VARCHAR(500),@path VARCHAR(500)
    FETCH NEXT FROM cur_paPhoto INTO @id, @photo
	BEGIN TRY
		WHILE @@FETCH_STATUS = 0
		BEGIN      
	--      SET @path = '@echo del D:\hosting\qlrc.com\imagefolder\photo\'+@path+' >>d:\delfile.bat'
	--		EXEC master.dbo.xp_cmdshell @path
	--      SET @cmdStr = '@echo del D:\hosting\qlrc.com\imagefolder\photo\'+@cmdStr+' >>d:\delfile.bat'  --新建一个bat执行文件，点击删除	
	--      EXEC master.dbo.xp_cmdshell @cmdStr
			SET @path = (SELECT dbo.photoPath(@id,1))

			SET @cmdStr = 'del D:\hosting\qlrc.com\imagefolder\photo\' + @path + '\processed\' + @photo    --删除processed目录
			EXEC master.dbo.xp_cmdshell @cmdStr 

			SET @cmdStr = 'del D:\hosting\qlrc.com\imagefolder\photo\' + @path + '\photo\' + @photo    --删除phOTO目录
			EXEC master.dbo.xp_cmdshell @cmdStr 

			DELETE FROM paPhoto WHERE paMainID = @ID
			UPDATE paMain SET HasPhoto = NULL WHERE ID = @ID

			FETCH NEXT FROM cur_paPhoto INTO @id,@photo 
		END
	END TRY
	BEGIN CATCH
	END CATCH
    CLOSE cur_paPhoto 
    DEALLOCATE cur_paPhoto
	EXEC SP_CONFIGURE 'xp_cmdshell', 0
	RECONFIGURE
	EXEC SP_CONFIGURE 'show advanced options', 0
	RECONFIGURE
END














GO
/****** Object:  StoredProcedure [dbo].[spDeleteOrder]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[spDeleteOrder]
(
	@Id INT
)
AS
BEGIN
	DECLARE @OrderStatus INT
	SELECT @OrderStatus = OrderStatus FROM caOrder WHERE ID = @Id
	IF @OrderStatus > 6
		UPDATE caORder SET OrderStatus = 6 WHERE ID = @Id

	IF @OrderStatus = 6
		UPDATE caORder SET ReceiveDate = NULL WHERE ID = @Id

	UPDATE caORder SET OpenDate = NULL, IsDeleted = 1 WHERE ID = @Id
	UPDATE caORder SET OpenDate = NULL, IsDeleted = 1 WHERE MainOrderID = @Id

	SELECT isDeleted, * FROM caOrder WHERE Id = @id
END


GO
/****** Object:  StoredProcedure [dbo].[spEmailCheck]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[spEmailCheck]
(
	@DeptID AS INT
)
AS
BEGIN
	DECLARE @ManageruserId INT,
		@count INT,
		@RAND INT,
		@i INT,
		@time INT,
		@minute INT,
		@WorkDate int

	SELECT @WorkDate = COUNT(1)
	FROM Sales_WorkDate WITH(NOLOCK)
	WHERE WorkDate = CONVERT(VARCHAR(8), GETDate(), 112)

	IF @WorkDate = 1
	BEGIN
		----deptId=10 客户服务部
		SELECT TOP 1 @ManageruserId = ID
		FROM ManagerUser WITH(NOLOCK)
		WHERE DeptId = @DeptId
		AND Status IN (1, 2)
        AND Type IN (1, 5)
		AND LEN(LTRIM(RTRIM(Email))) > 0
		ORDER BY NEWID()

		SET @time = CAST(RAND() * 8 AS INT) + 9
		--PRINT @TIME
		SET @minute = CAST(RAND() * 60 AS INT)
		IF @time = 12
			SET @time=13
		IF @ManageruserId IS NOT NULL
		INSERT INTO emailcheck (testDate, planhour, planminute, ManageruserId)
		VALUES (CONVERT(VARCHAR(8), GETDate(), 112), @time, @minute, @ManageruserId)
	END
END














GO
/****** Object:  StoredProcedure [dbo].[spEndOrder]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[spEndOrder]
(
	@Id INT
)
AS
BEGIN
	UPDATE caOrder SET EndDate = GETDATE() WHERE Id = @Id
End

GO
/****** Object:  StoredProcedure [dbo].[spFindForeignCompany]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[spFindForeignCompany]
AS
BEGIN
	CREATE TABLE #t(
		ID int NOT NULL,
		RegisterIP varchar(31) NULL,
		r1 varchar(31) NULL,
		r2 varchar(31) NULL,
		ip1 varchar(31) NULL,
		ip2 varchar(31) NULL,
		ip3 varchar(31) NULL,
		ip4 varchar(31) NULL,
		IP bigint NULL,
		IsForeign tinyint NULL,
		LoginDate DATETIME
	)
	INSERT INTO #t
	SELECT ID, RegisterIP,RegisterIP r1, RegisterIP r2, SPACE(30) ip1, SPACE(30) ip2, SPACE(30) ip3, SPACE(30) ip4, CONVERT(BIGINT, 0) IP, CONVERT(TINYINT, 0) IsForeign, RegDate
	FROM cpMain WITH(NOLOCK)
	WHERE RegisterIp LIKE '%.%.%.%'
	AND RegDate > '2014-11-1' --GETDATE() - 730
	And dcProvinceId = 10
	AND id in(select cpmainid from cplicence where haspassed=1 and checkdate > '2014-11-1')

	INSERT INTO #t
	SELECT DISTINCT b.cpMainId, a.LoginIp, a.LoginIp, a.LoginIp, a.LoginIp, SPACE(30) ip2, SPACE(30) ip3, SPACE(30) ip4, CONVERT(BIGINT, 0) IP, CONVERT(TINYINT, 0) IsForeign, AddDate
	FROM caloginLog a WITH(NOLOCK), caMain b WITH(NOLOCK)
	WHERE a.caMainId = b.Id
	AND a.LoginIp LIKE '%.%.%.%'
	AND a.AddDate >  '2014-8-1' --GETDATE() - 730
	AND b.cpMainId IN(SELECT ID FROM cpMain WITH(NOLOCK) WHERE dcProvinceID = 10)
	AND b.cpmainid in(select cpmainid from cplicence where haspassed=1 and checkdate > '2014-11-1')

	UPDATE #t SET ip1 = LEFT(RegisterIp, CHARINDEX('.', RegisterIP)-1)
	UPDATE #t SET r1 = RIGHT(RegisterIp, LEN(RegisterIp) - CHARINDEX('.', RegisterIP))
	UPDATE #t SET ip2 = LEFT(r1, CHARINDEX('.', r1)-1)
	UPDATE #t SET r2 = RIGHT(r1, LEN(r1) - CHARINDEX('.', r1))
	UPDATE #t SET ip3 = LEFT(r2, CHARINDEX('.', r2)-1)
	UPDATE #t SET ip4 = RIGHT(r2, LEN(r2) - CHARINDEX('.', r2))
	UPDATE #t SET ip4 = 0 where Ip4 Like '%.%'
	DElete from #t where registerip like 'u%'

	UPDATE #t SET IP = CONVERT(BIGINT, Ip1) * 256 * 256 * 256 + CONVERT(BIGINT, Ip2) * 256 * 256 + CONVERT(BIGINT, Ip3) * 256 + CONVERT(BIGINT, Ip4)
	UPDATE a SET IsForeign = 1
	FROM #t a WITH(NOLOCK), dcIpPlace b WITH(NOLOCK)
	WHERE a.Ip >= b.IpStart AND a.Ip <= b.IpEnd
	AND b.InterNational = 1
	
	TRUNCATE TABLE bsForeign
	INSERT INTO bsForeign(id, LoginIp, LoginDate)
	SELECT DISTINCT ID, RegisterIP, LoginDate FROM #t WITH(NOLOCK) WHERE IsForeign = 1

	UPDATE a
	SET a.CompanyName = b.Name
	FROM bsForeign a WITH(NOLOCK), cpMain b WITH(NOLOCK)
	WHERE a.ID = b.Id

	UPDATE a
	SET a.LinkMan = b.Name, a.TelePhone = b.TelePhone, a.Mobile = b.Mobile
	FROM bsForeign a WITH(NOLOCK), caMain b WITH(NOLOCK)
	WHERE a.ID = b.cpMainId
	AND b.AccountType = 1

	UPDATE bsForeign SET ipAddress = dbo.IpPlace(LoginIp)

	SELECT * FROM bsForeign WITH(NOLOCK) ORDER BY Id, LoginDate DESC
END
GO
/****** Object:  StoredProcedure [dbo].[spGenInsert]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[spGenInsert]
(
	@tb varchar(100)
)
as
BEGIN
	declare @i int, @s varchar(max), @n varchar(100), @cn varchar(max), @objid int
	declare @t as table (name varchar(100), status int)
	select * into #t from sysobjects where xtype='u' and name like @tb + '%'
	set @s = ''
	set nocount on
	while (select count(*) from #t) > 0
	begin 
		select top 1 @n = name FROM #t
		select @objid = id, @cn='' from sysobjects where name=@n and xtype='u'
		insert @t select name,status FROM syscolumns where id = @objid
		select @cn=@cn + case when @cn='' then '' else ',' end + name from @t
		print 'if (select count(*) from ' + @n +') =0
begin'
		if (select count(*) FROM @t where name='id' and status=128 and status<>64)>0
			print 
'	set identity_insert ' + @n + ' on
	insert into ' + @n + '(' + @cn + ')
	select ' + @cn + ' from maindb..' + @n + ' with(nolock)
	set identity_insert ' + @n + ' off'
		else
			print 
'	insert into ' + @n + '(' + @cn + ')
	select ' + @cn + ' from maindb..' + @n + ' with(nolock)'
		print 'end
go

'
		delete #t where name=@n
		delete @t
	end
	drop table #t
	--PRINT @s
END














GO
/****** Object:  StoredProcedure [dbo].[spGenInsertSQL]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[spGenInsertSQL]
(
	@tablename varchar(256)
)
as
begin
	declare @sql varchar(max)
	declare @sqlValues varchar(max)
	set @sql =' ('
	set @sqlValues = 'values (''+'
	select @sqlValues = @sqlValues + cols + ' + '','' + ' ,@sql = @sql + '[' + name + '],'
	from
      (select case
                when xtype in (48,52,56,59,60,62,104,106,108,122,127)       

                     then 'case when '+ name +' is null then ''NULL'' else ' + 'cast('+ name + ' as varchar)'+' end'

                when xtype in (58,61)

                     then 'case when '+ name +' is null then ''NULL'' else '+''''''''' + ' + 'cast('+ name +' as varchar)'+ '+'''''''''+' end'

               when xtype in (167)

                     then 'case when '+ name +' is null then ''NULL'' else '+''''''''' + ' + 'replace('+ name+','''''''','''''''''''')' + '+'''''''''+' end'

                when xtype in (231)

                     then 'case when '+ name +' is null then ''NULL'' else '+'''N'''''' + ' + 'replace('+ name+','''''''','''''''''''')' + '+'''''''''+' end'

                when xtype in (175)

                     then 'case when '+ name +' is null then ''NULL'' else '+''''''''' + ' + 'cast(replace('+ name+','''''''','''''''''''') as Char(' + cast(length as varchar)  + '))+'''''''''+' end'

                when xtype in (239)

                     then 'case when '+ name +' is null then ''NULL'' else '+'''N'''''' + ' + 'cast(replace('+ name+','''''''','''''''''''') as Char(' + cast(length as varchar)  + '))+'''''''''+' end'

                else '''NULL'''

              end as Cols,name

         from syscolumns 

        where id = object_id(@tablename)

      ) T
create table #t(id int, s varchar(max))
	set @sql ='insert #t select 2,''INSERT INTO ['+ @tablename + ']' + left(@sql,len(@sql)-1)+') ' + left(@sqlValues,len(@sqlValues)-4) + ')'' from '+@tablename 
insert #t select 1,'set identity_insert ' + @tablename + ' on'
	--PRINT @sql
	exec (@sql)
insert #t select 3,'set identity_insert ' + @tablename + ' off'
	select * from #t	order by id
end














GO
/****** Object:  StoredProcedure [dbo].[spGenNormalPassword]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[spGenNormalPassword]
AS
BEGIN
	DECLARE @s VARCHAR(45), @r INT, @i INT, @Res VARCHAR(20)
	SET @s = '0123456789qwertyuioplkjhgfdsazxcvbnm.!@#$%*_+'

	SELECT @i = 0, @Res = ''
	WHILE @i < 20
	BEGIN
		SET @r = RAND() * 45
		IF @r < 1
			SET @r = 20
		IF @r > 44
			SET @r = 20

		SET @r = @r + 1
		SELECT @Res = @Res + SUBSTRING(@s, @r, 1), @i = @I + 1
	END
	SELECT @Res
END

GO
/****** Object:  StoredProcedure [dbo].[spGenPassword]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[spGenPassword]
AS
SET NOCOUNT ON
BEGIN
	DECLARE @Pass INT, @p VARCHAR(20)

	SELECT @Pass = CAST(FLOOR(RAND() * 10) AS INT)
	IF @Pass = 0
		SET @Pass = 1
	IF @Pass > 9
		SET @Pass = 9
	SET @p = LTRIM(STR(@Pass))

	SELECT @Pass = CAST(FLOOR(RAND() * 9000 + 1000) AS INT)
	IF @Pass > 9999
		SET @Pass = 9999
	SET @p = @p + LTRIM(STR(@Pass))

	SELECT @Pass = CAST(FLOOR(RAND() * 900 + 100) AS INT)
	IF @Pass > 999
		SET @Pass = 999
	SET @p = @p + LTRIM(STR(@Pass))

	SELECT @Pass = CAST(FLOOR(RAND() * 90000 + 10000) AS INT)
	IF @Pass > 99999
		SET @Pass = 99999
	SET @p = @p + LTRIM(STR(@Pass))

	SELECT @Pass = CAST(FLOOR(RAND() * 90 + 10) AS INT)
	IF @Pass > 99
		SET @Pass = 99
	SET @p = @p + LTRIM(STR(@Pass))

	SET @p = SUBSTRING(@p, 3, 8)
	
	IF LEFT(@p, 1) = '0'
		SET @P = '1' + LEFT(@p, 7)
	SELECT @p
END

GO
/****** Object:  StoredProcedure [dbo].[spGenRandChar]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[spGenRandChar]
(
	@Len INT = 12
)
AS
BEGIN
	DECLARE @i INT, @rnd INT, @Output VARCHAR(50), @c CHAR(1), @Text VARCHAR(118)
	SET @Text = '~!0123456789#$%abcdefghijklmnopqrstuvwxyz&()*+-.0123456789:;=@abcdefghijklmnopqrstuvwxyz^abcdefghijklmnopqrstuvwxyz{|}'
	SELECT @I = 0, @Output = ''
	WHILE @I < @Len
	BEGIN
		SET @Rnd = 117 * RAND() + 1
		SET @c = SUBSTRING(@Text, @Rnd, 1)
		SET @Output = @Output + @c
		SET @I = @I + 1
	END
	SELECT LOWER(@Output)
END

GO
/****** Object:  StoredProcedure [dbo].[spGenUserName]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--######################################3
--创建：Sean 2010-12-2
--生成推广时可用的企业用户名
--######################################3
create PROCEDURE [dbo].[spGenUserName]
(
	@UserName VARCHAR(50),
	@UserNameOut VARCHAR(50) OUTPUT
)
AS
BEGIN
	DECLARE @u AS VARCHAR(50)
	DECLARE @s AS VARCHAR(50)
	DECLARE @i AS INT
	DECLARE @r AS BIT
	
	SET @s = '2356789'
	SET @u = LTRIM(RTRIM(@UserName))	
	SET @r = dbo.ExistUserName(@u)

	WHILE @r = 1
	BEGIN
		SET @i = CAST(FLOOR(RAND() * 7) AS INT)		
		SET @u = @u + SUBSTRING(@s, @i + 1, 1)
		SET @r = dbo.ExistUserName(@u)
	END
	SET @UserNameOut = @u
END



GO
/****** Object:  StoredProcedure [dbo].[spGetCamainOld]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[spGetCamainOld]
(
	@dcProvinceID INT,
	@MemberType INT
)
AS

SELECT * FROM camain WHERE cpmainid in(
	SELECT top 100 id FROM cpmain 
	where Valid = 1
	And dcProvinceId = @dcProvinceID
	AND MemberType = @Membertype)














GO
/****** Object:  StoredProcedure [dbo].[spHomePageTableRebuild]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/**
*Peter 2014-02-19 修改，添加山东二级站数据
*2016-09-28 Peter修改，将点评title内容进行了修改
*/
CREATE PROCEDURE [dbo].[spHomePageTableRebuild]
AS
SET NOCOUNT ON
BEGIN
	IF DATEPART(HOUR, GETDATE())<8 OR DATEPART(HOUR, GETDATE()) > 17 --OR DATEPART(HOUR, GETDATE()) = 12
		RETURN

	DECLARE @t AS TABLE(ID INT, Num INT)
	DECLARE @i INT, @N INT
	INSERT @t SELECT 1, 5
	INSERT @t SELECT 3, 3
	INSERT @t SELECT 5, 3
	INSERT @t SELECT 7, 5
	INSERT @t SELECT 8, 3
	INSERT @t SELECT 9, 3
	INSERT @t SELECT 10, 3
	INSERT @t SELECT 11, 3
	INSERT @t SELECT 12, 3
	INSERT @t SELECT 13, 3

	SET NOCOUNT ON;
	DECLARE @D DATETIME, @UR BIT, @UN BIT, @UI BIT, @UL BIT, @Uc BIt, @csp BIT
	SELECT @D = MAX(ModifyDate) FROM RecruitMent WITH(NOLOCK)
	IF @D > DATEADD(MINUTE, -15, GETDATE())
		SET @UR = 1

	SELECT @D = MAX(RefreshDate) FROM QlrcNews WITH(NOLOCK)
	IF @D > DATEADD(MINUTE, -15, GETDATE())
		SET @UN = 1
		--SET @UN = 1
	SELECT @D = MAX(AddDate) FROM ivgt_investigation WITH(NOLOCK)
	IF @D > DATEADD(MINUTE, -15, GETDATE())
		SET @UI = 1

	SELECT @D = RefreshDate FROM LogDb..HomePageTableRefresh WITH(NOLOCK) WHERE TAbleName = 'link'
	IF @D > DATEADD(MINUTE, -15, GETDATE())
		SET @UL = 1

	SELECT @D = MAX(AddDate) FROM WutongguoDb..CpPreach WITH(NOLOCK)
	IF @D > DATEADD(MINUTE, -15, GETDATE())
		SET @Uc = 1

	IF (DATEPART(HOUR, GETDATE()) BETWEEN 8 AND 21) AND (DATEPART(MINUTE, GETDATE()) % 30 < 10)
	BEGIN
		SET @uc = 1
	END

	IF DATEPART(HOUR, GETDATE()) IN(3, 4, 8, 9, 10, 14, 15) AND DATEPART(MINUTE, GETDATE()) < 10
	BEGIN
		SELECT @Ur = 1, @Un = 1, @Ui = 1, @Ul = 1, @Uc = 1
	END

	SELECT @D = MAX(crDate) FROM SearchDb..CampusSchoolPartner12 WITH(NOLOCK)
	IF @D > DATEADD(MINUTE, -15, GETDATE())
		SET @csp = 1

	IF NOT EXISTS(SELECT 'x' FROM SearchDb..CampusSchoolPartner12 WITH(NOLOCK) WHERE crDate > DATEADD(HOUR, -3, GETDATE()))
	BEGIN
		 SELECT @csp = 1
	END

	DECLARE curProvince CURSOR FOR 
		SELECT ID, IsMainSite FROM dcSubSite WITH(NOLOCK) WHERE IsMainSite = 1 OR ID LIKE '32%' ORDER BY ID
	OPEN curProvince
	DECLARE @dcProvinceID INT, @IsMainSite BIT
	FETCH NEXT FROM curProvince INTO @dcProvinceID, @IsMainSite
	WHILE @@FETCH_STATUS = 0
	BEGIN
		--招聘会
		IF @UR = 1
		BEGIN
			DELETE SearchDb..HpRecruitmeetingDay WHERE ProvinceID LIKE LTRIM(STR(@dcProvinceID)) + '%'

			INSERT INTO SearchDb..HpRecruitmeetingDay (PreID,ProvinceID,Title,AddDate,WeekDay,MonthDay,startDate)
			SELECT TOP 15 a.Id,CASE @dcProvinceID WHEN 3202 THEN 3202 ELSE @dcProvinceID END,
			RecruitmentName, b.ModifyDate, '', '', Replace(CONVERT(VARCHAR(10),Begindate,102),'.','-')
			FROM RecruitMent a WITH(NOLOCK), RecruitMentDept b WITH(NOLOCK)
			WHERE a.RecruitMentDeptID=b.ID AND b.ID<>1767 AND CityID LIKE LTRIM(STR(@dcProvinceID)) + '%'
			AND EndDate > GETDATE() AND a.IsPause=0 AND b.IsPause=0
			AND LEN(ManagerUserId) > 0
			ORDER BY a.BeginDate
		END
		IF @IsMainSite = 1
		BEGIN
			IF @UN = 1
			BEGIN
				--政府招考
				DELETE SearchDb..HpQlrcGovDay WHERE VersionId = @dcProvinceID

				IF @dcProvinceID < 99
 				BEGIN
					INSERT INTO SearchDb..HpQlrcGovDay (PreID,versionid,Title,announcedate ,content,type,refreshdate)
					SELECT TOP 15 id, @dcProvinceID,title, announcedate ,content,type,refreshdate
					FROM QlrcNews WITH(NOLOCK)
					WHERE versionid = @dcProvinceID --or versionid=0)
					AND NewsType = 2
					AND detailtype like '%,2,%'
					ORDER BY refreshdate DESC
				END
				ELSE
				BEGIN
					INSERT INTO SearchDb..HpQlrcGovDay (PreID,versionid,Title,announcedate ,content,type,refreshdate)
 					SELECT TOP 15 id, @dcProvinceID,title, announcedate ,content,type,refreshdate
					FROM QlrcNews WITH(NOLOCK)
					WHERE Versionid = LEFT(@dcProvinceID, 2)-- OR Versionid = 0)
					AND CHARINDEX((SELECT Abbr FROM dcRegion WHERE ID = @dcProvinceID),Title) <> 0
					AND NewsType = 2
					AND detailtype like '%,2,%'
					ORDER BY refreshdate DESC
				END

				--职场新闻
				DELETE SearchDb..HpQlrcNewsDay WHERE dcSubSiteId = @dcProvinceID

				INSERT INTO SearchDb..HpQlrcNewsDay (PreID, dcSubSiteId, versionid,Title,announcedate ,content,type,refreshdate)
					SELECT TOP 15 id, @dcProvinceID, versionid, title, announcedate ,content,type,refreshdate
					FROM QlrcNews WITH(NOLOCK)
					WHERE versionid = @dcProvinceID --or versionid=0)
					AND NewsType = 2
					AND detailtype not like '%,2,%'
					ORDER BY refreshdate DESC
			END

			IF @dcProvinceID < 100
			BEGIN				
				--用户调查
				IF @UI = 1
				BEGIN
					DELETE SearchDb..HPInvestigationDay WHERE ProvinceID = @dcProvinceID

					INSERT INTO SearchDb..HPInvestigationDay (Preid,ProvinceID, title, description, reporturl, type, reporttitle, addDate, ExLink)
					SELECT TOP 15 id, @dcProvinceID, title, description, reporturl, type, reporttitle, addDate, ExLink
					FROM ivgt_investigation WITH(NOLOCK)
					WHERE EndDate < GETDATE() 
					AND province LIKE '%' + CAST(@dcProvinceID AS CHAR(2)) + '%'
					AND homepagesee = 1
					ORDER BY EndDate DESC

					DECLARE @HasOne INT, @Id INT, @Title NVARCHAR(50), @DescrIption NVARCHAR(MAX), @AddDate SMALLDATETIME, @Exlink VARCHAR(100)
 					SELECT TOP 1 @HasOne = 1, @Id = id, @Title = title, 
						@DescrIption = description, @AddDate = AddDate, @ExLink = ExLink
					FROM ivgt_investigation WITH(NOLOCK)
					WHERE Type = 2 
					AND ENDdate > GETDATE()
					AND Province LIKE '%' + LTRIM(STR(@dcProvinceID)) + '%'
					AND AnswerAfterLogin = 0
					ORDER BY Id DESC

					IF(@HasOne = 1)
					BEGIN
						DELETE SearchDb..ivgt_investigationDay WHERE ProvinceId = @dcProvinceID
						INSERT SearchDb..ivgt_investigationDay(Id, Provinceid, Title, Description, adddate,exLink)
						SELECT @Id, @dcProvinceID, @Title, @Description, @adddate, @ExLink
					END
				END
				---------------------------------------------
				IF @UN = 1
				BEGIN
					DELETE SearchDb..HpJobNews WHERE VersionId = @dcProvinceID

					SET @i = 0
					WHILE(@i < 13)
					BEGIN
						SELECT TOP 1 @I = Id, @n = Num FROM @t WHERE ID > @I
						INSERT INTO SearchDb..HpJobNews (ID, VersionId, DetailType, NewsType, Title, [Content], RefreshDate)
						SELECT TOP (@N) ID, @dcProvinceID, LTRIM(STR(@I)), NewsType, Title, [Content], RefreshDate
						FROM QlrcNews WITH(NOLOCK) 
						WHERE DetailType LIKE '%,' + LTRIM(STR(@I)) + ',%' AND VersionId = @dcProvinceID --Or VersionId = 0)
						ORDER BY RefreshDate DESC				
					END
				END
			END

			--友情连接
			IF @UL = 1
			BEGIN
				DELETE SearchDb..hplinkDay WHERE ProvinceID LIKE CONVERT(VARCHAR(2),@dcProvinceID) + '%'

				INSERT INTO SearchDb..hplinkDay (ProvinceID,text, link,nofollow, category)
				SELECT versionid,text, link, nofollow, category
				FROM link WITH(NOLOCK)
				WHERE versionid like CONVERT(VARCHAR(2), @dcProvinceID)+'%'
				AND type=1 
				AND valid=1
				AND orderby<100
				AND deleted=0
				ORDER BY orderby,ID
			END

			--校园招聘 宣讲会
			IF @Uc = 1
			BEGIN
				DELETE SearchDb..HpCampus WHERE ProvinceID = @dcProvinceID
				INSERT INTO SearchDb..HpCampus (ProvinceID, PresentationID, CompanyID, CompanyName, RegionName, SchoolName, BeginTime, HomePage, cpSecondId)
				SELECT TOP 15 @dcProvinceID, a.Id, b.ID, b.Name, d.Description, c.Name, a.BeginDate, '', b.SecondId
				FROM WutongguoDb..CpPreach a, WutongguoDb..cpMain b, WutongguoDb..dcSchool c, WutongguoDb..dcRegion d
				WHERE a.cpMainID = b.ID AND a.dcSchoolID = c.ID AND a.dcRegionID = d.ID AND a.EndDate > GETDATE() 
				ORDER BY CASE CHARINDEX(LTRIM(STR(@dcProvinceID)), a.dcRegionID) WHEN 1 THEN 1 ELSE 2 END , 
					a.BeginDate, a.AddDate DESC
			END
		END
		ELSE
		BEGIN
			--政府招考
			IF @Un = 1
			BEGIN
				DELETE SearchDb..HpQlrcGovDay WHERE versionid = @dcProvinceID

				INSERT INTO SearchDb..HpQlrcGovDay (PreID,versionid,Title,announcedate ,content,type,refreshdate)
				SELECT TOP 15 id, @dcProvinceID,title, announcedate ,content,type,refreshdate
				FROM QlrcNews WITH(NOLOCK)
  				WHERE (Versionid = 32 OR Versionid=0)
				AND CHARINDEX((SELECT Abbr FROM dcRegion WHERE ID = @dcProvinceID),Title) <> 0
				AND NewsType = 2
				AND detailtype like '%,2,%'
				ORDER BY refreshdate DESC
			END
		END
		
		FETCH NEXT FROM curProvince INTO @dcProvinceID, @IsMainSite
	END
	CLOSE curProvince
	DEALLOCATE curProvince

	IF @UN = 1
		UPDATE SearchDb..HpJobNews SET [CONTENT] = '' WHERE DetailType NOT IN(1, 7)

	IF @csp = 1
	BEGIN
		TRUNCATE TABLE SearchDb..CampusSchoolPartner12
		INSERT INTO SearchDb..CampusSchoolPartner12
		SELECT * 
		FROM (SELECT a.*, GETDATE() crDate, LEFT(dcRegionID, 2) dcProvinceId, ROW_NUMBER() OVER(PARTITION BY LEFT(dcRegionID, 2) ORDER BY OrderBy, AddDate DESC) RowNo
			FROM MarketDB..CampusSchool a WITH(NOLOCK)    
			WHERE EXISTS(SELECT 'x' FROM marketdb..CampusPresentation b WITH(NOLOCK) 
				WHERE SchoolID = a.id)) b
		WHERE b.RowNo < 13
	END

	IF @UN = 1
	BEGIN
		DELETE SearchDb..HpQlrcNewsDay WHERE VersionId = 0

		INSERT INTO SearchDb..HpQlrcNewsDay (PreID, dcSubSiteId, versionid, Title, announcedate, content, type, refreshdate)
		SELECT TOP 1 id, 0, versionid, title, announcedate, content, type, refreshdate
		FROM QlrcNews WITH(NOLOCK)
		WHERE versionid = 0
		AND NewsType = 2
		AND detailtype not like '%,2,%'
		ORDER BY refreshdate DESC
	END
END

GO
/****** Object:  StoredProcedure [dbo].[sphpHighSalaryCompanyNewRebuild]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[sphpHighSalaryCompanyNewRebuild]
AS
SET NOCOUNT ON
BEGIN
	SELECT TOP 0 * INTO #t FROM hpHighSalaryCompanyNew	

	INSERT INTO #t(dcRegionID, JobID, JobSecondID, JobName, CpMainID, CpSecondID, CpName, dcSalaryID, RefreshDate, LogoUrl, AddDate, RowNo)
	SELECT dcProvinceId, JobId, JobSecondID, JobName, CpMainID, CpSecondID, CpName, dcSalaryID, RefreshDate, LogoUrl, GETDATE(), RowNo
	FROM (SELECT b.dcProvinceId, a.ID JobId, a.SecondID JobSecondID, a.Name JobName, b.ID CpMainID,
			b.SecondID CpSecondID, b.Name CpName, a.dcSalaryID, b.RefreshDate, '' LogoUrl, 
			ROW_NUMBER() OVER(PARTITION BY b.Id ORDER BY a.dcSalaryId DESC) RowNo
		FROM JobPublish a WITH(NOLOCK)
		INNER JOIN CpMain b WITH(NOLOCK) ON b.id = a.CpMainID
		WHERE a.Valid = 1
		AND b.Valid = 1
		AND (
				(b.dcProvinceId IN(32, 30, 10, 31, 40, 71, 61) 
				AND a.DcSalaryID BETWEEN 11 AND 17
				)
			OR
				(b.dcProvinceId NOT IN(32, 30, 10, 31, 40, 71, 61)
				AND a.DcSalaryID BETWEEN 9 AND 17
				)
			)
		) a
	WHERE RowNo < 4
	--DELETE FROM #t WHERE JobId NOT IN(SELECT MAX(JobId) FROM #t GROUP BY cpMainId)
	DELETE FROM #t WHERE cpMainId IN(5654050) AND JobID NOT IN(3990967)
	UPDATE #t SET LogoUrl = (SELECT TOP 1 ImgFile FROM cpImage b WITH(NOLOCK) WHERE #t.cpMainId = b.cpMainId AND b.HasPassed = 1 AND b.ImgType = 1 AND b.AddDate > '2016-11-16')

	DELETE FROM #t WHERE LogoUrl IS NULL

	TRUNCATE TABLE hpHighSalaryCompanyNew

	INSERT INTO hpHighSalaryCompanyNew(dcRegionID, JobID, JobSecondID, JobName, CpMainID, CpSecondID, CpName, dcSalaryID, RefreshDate, LogoUrl, AddDate)
	SELECT dcRegionID, JobID, JobSecondID, JobName, CpMainID, CpSecondID, CpName, dcSalaryID, RefreshDate, LogoUrl, AddDate FROM #t
END

GO
/****** Object:  StoredProcedure [dbo].[spHpHighSalaryCompanyRebuild]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[spHpHighSalaryCompanyRebuild]
AS
SET NOCOUNT ON
BEGIN
	SELECT TOP 0 * INTO #t FROM hpHighSalaryCompany	

	INSERT INTO #t(dcRegionID, JobID, JobSecondID, JobName, CpMainID, CpSecondID, CpName, dcSalaryID, RefreshDate, LogoUrl, AddDate, RowNo)
	SELECT dcProvinceId, JobId, JobSecondID, JobName, CpMainID, CpSecondID, CpName, dcSalaryID, RefreshDate, LogoUrl, GETDATE(), 0
	FROM (SELECT b.dcProvinceId, a.ID JobId, a.SecondID JobSecondID, a.Name JobName, b.ID CpMainID,
			b.SecondID CpSecondID, b.Name CpName, a.dcSalaryID, b.RefreshDate, '' LogoUrl, 
			ROW_NUMBER() OVER(PARTITION BY b.dcProvinceId ORDER BY a.RefreshDate DESC, b.Id DESC, a.Id DESC) RowNo
		FROM JobPublish a WITH(NOLOCK)
		INNER JOIN CpMain b WITH(NOLOCK) ON b.id = a.CpMainID
		WHERE a.Valid = 1
		AND b.Valid = 1
		AND a.DcSalaryID BETWEEN 9 AND 12) a

	DELETE FROM #t WHERE JobId NOT IN(SELECT MAX(JobId) FROM #t GROUP BY cpMainId)

	UPDATE #t SET LogoUrl = (SELECT TOP 1 ImgFile FROM cpImage b WITH(NOLOCK) WHERE #t.cpMainId = b.cpMainId AND b.HasPassed = 1 AND b.ImgType = 1)
	TRUNCATE TABLE hpHighSalaryCompany
	INSERT INTO hpHighSalaryCompany(dcRegionID, JobID, JobSecondID, JobName, CpMainID, CpSecondID, CpName, dcSalaryID, RefreshDate, LogoUrl, AddDate)
	SELECT dcRegionID, JobID, JobSecondID, JobName, CpMainID, CpSecondID, CpName, dcSalaryID, RefreshDate, LogoUrl, AddDate FROM #t

END
GO
/****** Object:  StoredProcedure [dbo].[spJobByRefreshBatchUpdate]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[spJobByRefreshBatchUpdate]
AS
SET NOCOUNT ON
BEGIN
	DECLARE @d VARCHAR(14), @r varchar(20), @d2 VARCHAR(14)
	SET @d = CONVERT(VARCHAR(14), GETDATE(), 120)
	SET @d2 = CONVERT(VARCHAR(14), GETDATE() - 1, 120)
	SET @r = '2016-09-08 14:01:00'

	CREATE TABLE #t(Id INT IDENTITY(1, 1), RefreshDate DATETIME, Cnt INT)
	INSERT INTO #t
	SELECT TOP 5 a.Refreshdate, COUNT(*)
	FROM Job a, cpMain b
	WHERE a.cpMainId = b.id
	AND a.Refreshdate > GETDATE() - 1
	GROUP BY a.Refreshdate
	HAVING COUNT (*) > 900
	ORDER BY COUNT(*) DESC
	DECLARE @Id INT
	SET @Id = 0
	WHILE EXISTS(SELECT 'x' FROM #t WHERE Id > @Id)
	BEGIN
		SELECT TOP 1 @Id = Id, @r = RefreshDate FROM #t WHERE Id > @Id ORDER BY ID

		UPDATE a SET a.Refreshdate = @d + LTRIM(STR(DATEPART(MINUTE, b.LastLogindate)))
		FROM Job a, cpMain b
		WHERE a.cpMainId = b.Id
		AND a.RefreshDate = @r
		AND DATEPART(MINUTE, b.LastLogindate) < DATEPART(MINUTE, GETDATE())
		AND a.Valid = 1

		UPDATE a SET a.Refreshdate = @d + LTRIM(STR(DATEPART(MINUTE, b.LastLogindate)))
		FROM Job a, cpMain b
		WHERE a.cpMainId = b.Id
		AND a.RefreshDate = @r
		AND DATEPART(MINUTE, b.LastLogindate) >= DATEPART(MINUTE, GETDATE())
		AND a.Valid = 1
	END

	SELECT * FROM #t
END

GO
/****** Object:  StoredProcedure [dbo].[spJobDateReport]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--********************************************
--创建人：Lambo
--创建时间：2013-01-31
--用途：用于每日记录职位发布效果统计的数据
--********************************************
CREATE PROCEDURE [dbo].[spJobDateReport]
AS
BEGIN
	--取昨天
	DECLARE @yesterday VARCHAR(10)
	SET @yesterday = CONVERT(VARCHAR(10), GETDATE()-1, 120)

	-- 将昨天一天的数据填充到表里
	INSERT INTO Reportdb..jobReportData( JobID,CountDate,applyCount,viewCount,interview,interviewreply,interviewresult)
	SELECT id ,dbo.DateToReportDay(GETDATE()),
		(SELECT COUNT(1) FROM exjobapply WITH(NOLOCK) WHERE  JobID=a.id AND adddate >@yesterday AND adddate<@yesterday+' 23:59'  ),
		(SELECT COUNT(1) FROM pajobviewlog WITH(NOLOCK) WHERE  JobID=a.id AND adddate >@yesterday AND adddate<@yesterday+' 23:59' ),
		(SELECT COUNT(1) FROM exinterview WITH(NOLOCK) WHERE  JobID=a.id AND adddate >@yesterday AND adddate<@yesterday+' 23:59' ),
		(SELECT COUNT(1) FROM exinterview WITH(NOLOCK) WHERE  JobID=a.id AND replydate is not null AND adddate >@yesterday AND adddate<@yesterday+' 23:59' ),
		(SELECT COUNT(1) FROM exinterview WITH(NOLOCK) WHERE  JobID=a.id AND replydate is not null AND result=1 AND adddate >@yesterday AND adddate<@yesterday+' 23:59')
	FROM job a WITH(NOLOCK) 
	WHERE isdelete=0
	AND AddDate < @yesterday+' 23:59' 
	AND IssueEnd > @yesterday
	
	--删除全部是0的数据
	DELETE FROM Reportdb..JobReportData WHERE applyCount=0 AND viewCount=0 AND interview=0 AND interviewreply=0 AND interviewresult=0

	--vip删除780天以前的数据
	DELETE a FROM Reportdb..jobReportData a, Job b, cpMain c 
	WHERE a.JobId = b.ID AND b.cpMainID = c.ID AND a.CountDate < dbo.ReportDayToDate(780) AND MemberType>=3
	
	--普通会员以下的删除14个月前的数据
	DELETE a FROM Reportdb..jobReportData a, Job b, cpMain c 
	WHERE a.JobId = b.ID AND b.cpMainID = c.ID AND a.CountDate<  dbo.ReportDayToDate(440) AND MemberType<3 
	AND NOT EXISTS(SELECT 'x' FROM caOrder WHERE cpMainID = c.ID AND OrderType in (1,2,8) AND EndDate<GETDATE()-92 AND OpenDate IS NOT NULL AND IsDeleted=0)
		
	--过期收费会员删除780天前的数据
	DELETE a FROM Reportdb..jobReportData a, Job b, cpMain c 
	WHERE a.JobId = b.ID AND b.cpMainID = c.ID 
	AND a.CountDate<  dbo.ReportDayToDate(780) AND MemberType<3 
	AND EXISTS(SELECT 'x' FROM caOrder WHERE cpMainID = c.ID AND OrderType in (1,2,8) AND EndDate>=GETDATE()-92 AND OpenDate IS NOT NULL AND IsDeleted=0)
END 














GO
/****** Object:  StoredProcedure [dbo].[spJobDateReportDetail]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--********************************************
--创建人：Lambo
--创建时间：2013-01-31
--用途：用于每日记录应聘简历分析数据
--********************************************
CREATE PROCEDURE [dbo].[spJobDateReportDetail]
AS
BEGIN
	DECLARE @Yesterday VARCHAR(10)
	DECLARE @Today VARCHAR(8)
	SELECT @Yesterday = CONVERT(VARCHAR(10),GETDATE()-1,120),@Today = dbo.DateToReportDay(GETDATE())
	--首先填充表
	INSERT INTO Reportdb..JobReportDetailData	(JobId,CountDate) 
	SELECT id,@Today 
	FROM JOB a WITH(NOLOCK) 
	WHERE IsDelete=0
	AND EXISTS(SELECT 'x' FROM exJobapply x WITH(NOLOCK) WHERE x.JobID=a.ID  AND x.AddDate >@yesterday AND x.AddDate<@yesterday+' 23:59')

	DECLARE @t TABLE(
		JobID INT,
		cvMainID INT
	)
	INSERT INTO @t SELECT JobID,cvMainID FROM exJobapply WITH(NOLOCK) WHERE AddDate >@Yesterday AND AddDate<@Yesterday+' 23:59'

	--更新工作经验
	UPDATE a 
		SET WorkYears1 = (SELECT COUNT(1) FROM @t,cvMain y WITH(NOLOCK) WHERE JobID=a.JobID AND (RelatedWorkYears=0 OR EXISTS(SELECT 'x' FROM paMain WITH(NOLOCK) WHERE Name IS NOT NULL AND Mobile IS NULL AND Attachment IS NOT NULL AND ID = y.PaMainID )) AND cvMainID = y.id) ,
		WorkYears2 = (SELECT COUNT(1) FROM @t,cvMain y WITH(NOLOCK) WHERE JobID=a.JobID AND RelatedWorkYears>=1 AND RelatedWorkYears<=2  AND cvMainID = y.id) ,
		WorkYears3 = (SELECT COUNT(1) FROM @t,cvMain y WITH(NOLOCK) WHERE JobID=a.JobID AND RelatedWorkYears>=3 AND RelatedWorkYears<=5   AND cvMainID = y.id) ,
		WorkYears4 = (SELECT COUNT(1) FROM @t,cvMain y WITH(NOLOCK) WHERE JobID=a.JobID AND RelatedWorkYears>=6 AND RelatedWorkYears<=10  AND cvMainID = y.id) ,
		WorkYears5 = (SELECT COUNT(1) FROM @t,cvMain y WITH(NOLOCK) WHERE JobID=a.JobID AND RelatedWorkYears>10 AND cvMainID = y.id) 
	FROM Reportdb..JobReportDetailData a 
	WHERE a.CountDate=@Today
 

	--更新年龄
	UPDATE a 
		SET Age1 = (SELECT COUNT(1) FROM @t,cvMain y WITH(NOLOCK), paMain z WITH(NOLOCK) WHERE JobID=a.JobID AND dbo.birthtoage(z.birthday)<=22 AND z.birthday IS NOT NULL  AND cvMainID = y.id AND y.pamainid = z.id) ,
		Age2 = (SELECT COUNT(1) FROM @t,cvMain y WITH(NOLOCK), paMain z WITH(NOLOCK) WHERE JobID=a.JobID AND dbo.birthtoage(z.birthday)>=23 AND dbo.birthtoage(z.birthday)<=25  AND cvMainID = y.id AND y.pamainid = z.id) ,
		Age3 = (SELECT COUNT(1) FROM @t,cvMain y WITH(NOLOCK), paMain z WITH(NOLOCK) WHERE JobID=a.JobID AND dbo.birthtoage(z.birthday)>=26 AND dbo.birthtoage(z.birthday)<=29  AND cvMainID = y.id AND y.pamainid = z.id) ,
		Age4 = (SELECT COUNT(1) FROM @t,cvMain y WITH(NOLOCK), paMain z WITH(NOLOCK) WHERE JobID=a.JobID AND dbo.birthtoage(z.birthday)>=30 AND dbo.birthtoage(z.birthday)<=35  AND cvMainID = y.id AND y.pamainid = z.id) ,
		Age5 = (SELECT COUNT(1) FROM @t,cvMain y WITH(NOLOCK), paMain z WITH(NOLOCK) WHERE JobID=a.JobID AND dbo.birthtoage(z.birthday)>35  AND cvMainID = y.id AND y.pamainid = z.id) ,
		Age6 = (SELECT COUNT(1) FROM @t,cvMain y WITH(NOLOCK), paMain z WITH(NOLOCK) WHERE JobID=a.JobID AND z.birthday IS NULL AND cvMainID = y.id AND y.pamainid = z.id) 
	FROM Reportdb..JobReportDetailData a 
	WHERE a.CountDate=@Today

	--更新学历
	UPDATE a 
		SET Degree1 = (SELECT COUNT(1) FROM exJobapply x WITH(NOLOCK),cvMain y WITH(NOLOCK) WHERE JobID=a.JobID AND Degree=1 AND cvMainID = y.id) , 
		Degree2 = (SELECT COUNT(1) FROM @t,cvMain y WITH(NOLOCK) WHERE JobID=a.JobID AND Degree=2 AND cvMainID = y.id) ,
		Degree3 = (SELECT COUNT(1) FROM @t,cvMain y WITH(NOLOCK) WHERE JobID=a.JobID AND Degree=3 AND cvMainID = y.id) ,
		Degree4 = (SELECT COUNT(1) FROM @t,cvMain y WITH(NOLOCK) WHERE JobID=a.JobID AND Degree=4 AND cvMainID = y.id) ,
		Degree5 = (SELECT COUNT(1) FROM @t,cvMain y WITH(NOLOCK) WHERE JobID=a.JobID AND Degree=5 AND cvMainID = y.id) ,
		Degree6 = (SELECT COUNT(1) FROM @t,cvMain y WITH(NOLOCK) WHERE JobID=a.JobID AND Degree=6 AND cvMainID = y.id) ,
		Degree7 = (SELECT COUNT(1) FROM @t,cvMain y WITH(NOLOCK) WHERE JobID=a.JobID AND Degree=7 AND cvMainID = y.id) ,
		Degree8 = (SELECT COUNT(1) FROM @t,cvMain y WITH(NOLOCK) WHERE JobID=a.JobID AND Degree=8 AND cvMainID = y.id), 
		Degree9 = (SELECT COUNT(1) FROM @t,cvMain y WITH(NOLOCK) WHERE JobID=a.JobID AND (Degree=0 OR Degree IS NULL OR EXISTS(SELECT 'x' FROM paMain(NOLOCK) WHERE Name IS NOT NULL AND Mobile IS NULL AND Attachment IS NOT NULL AND ID = y.PaMainID )) AND cvMainID = y.id) 
	FROM Reportdb..JobReportDetailData a 
	WHERE a.CountDate=@Today

	--更新性别
	UPDATE a 
		SET Male = (SELECT COUNT(1) FROM @t,cvMain y WITH(NOLOCK), paMain z WITH(NOLOCK) WHERE JobID=a.JobID AND z.Gender=0 AND cvMainID = y.id AND y.pamainid = z.id),
		Female = (SELECT COUNT(1) FROM @t,cvMain y WITH(NOLOCK), paMain z WITH(NOLOCK) WHERE JobID=a.JobID AND z.Gender=1 AND cvMainID = y.id AND y.pamainid = z.id)
	FROM Reportdb..JobReportDetailData a 
	WHERE a.CountDate=@Today

	--更新期望月薪
	UPDATE a 
		SET Salary1 = (SELECT COUNT(1) FROM @t,cvMain y WITH(NOLOCK) WHERE JobID=a.JobID AND dcSalaryID=2 AND cvMainID = y.id) , 
		Salary2 = (SELECT COUNT(1) FROM @t,cvMain y WITH(NOLOCK) WHERE JobID=a.JobID AND dcSalaryID=3 AND cvMainID = y.id) , 
		Salary3 = (SELECT COUNT(1) FROM @t,cvMain y WITH(NOLOCK) WHERE JobID=a.JobID AND dcSalaryID=4 AND cvMainID = y.id) ,
		Salary4 = (SELECT COUNT(1) FROM @t,cvMain y WITH(NOLOCK) WHERE JobID=a.JobID AND dcSalaryID=5 AND cvMainID = y.id) ,
		Salary5 = (SELECT COUNT(1) FROM @t,cvMain y WITH(NOLOCK) WHERE JobID=a.JobID AND dcSalaryID=6 AND cvMainID = y.id) ,
		Salary6 = (SELECT COUNT(1) FROM @t,cvMain y WITH(NOLOCK) WHERE JobID=a.JobID AND dcSalaryID=7 AND cvMainID = y.id) ,
		Salary7 = (SELECT COUNT(1) FROM @t,cvMain y WITH(NOLOCK) WHERE JobID=a.JobID AND dcSalaryID>=8 AND cvMainID = y.id) ,
		Salary8 = (SELECT COUNT(1) FROM @t,cvMain y WITH(NOLOCK) WHERE JobID=a.JobID AND (dcSalaryID=0 OR dcSalaryID IS NULL OR EXISTS(SELECT 'x' FROM paMain(NOLOCK) WHERE Name IS NOT NULL AND Mobile IS NULL AND Attachment IS NOT NULL AND ID = y.PaMainID )) AND cvMainID = y.id)  
	FROM Reportdb..JobReportDetailData a 
	WHERE a.CountDate=@Today
 
	--删除过期数据
	--收费会员删除半年前的数据
	DELETE a FROM Reportdb..JobReportDetailData a, Job b, cpMain c 
	WHERE a.JobId = b.ID AND b.cpMainID = c.ID AND a.CountDate< dbo.ReportDayToDate(183) AND MemberType>=3
	
	--普通会员以下的删除2个月前的数据
	DELETE a FROM Reportdb..JobReportDetailData a, Job b, cpMain c 
	WHERE a.JobId = b.ID AND b.cpMainID = c.ID AND a.CountDate< dbo.ReportDayToDate(62) AND MemberType<2 
		AND NOT EXISTS(SELECT 'x' FROM caOrder WHERE cpMainID = c.ID AND OrderType in (1,2,8) AND EndDate<GETDATE()-62 AND OpenDate IS NOT NULL AND IsDeleted=0)
		
	--过期收费会员删除半年前的数据
	DELETE a FROM Reportdb..JobReportDetailData a, Job b, cpMain c 
	WHERE a.JobId = b.ID AND b.cpMainID = c.ID AND a.CountDate< dbo.ReportDayToDate(183) AND MemberType<3 
		AND EXISTS(SELECT 'x' FROM caOrder WHERE cpMainID = c.ID AND OrderType in (1,2,8) AND EndDate>=GETDATE()-62 AND OpenDate IS NOT NULL AND IsDeleted=0)
		
END














GO
/****** Object:  StoredProcedure [dbo].[spKpi_OcByTestSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[spKpi_OcByTestSelect]
(
	@SuperiorId int,
	@YearMonth VARCHAR(6)
)
AS
BEGIN
	SELECT DISTINCT ManagerUserID ID INTO #t
	FROM kpi_oc 
	WHERE yearmonth = @YearMonth
	AND ManagerUserId IN(SELECT Id FROM ManagerUser WHERE Superior = @SuperiorId)

	DECLARE @t AS TABLE(ID INT, AllScore INT, HasObjHigher INT, OrderRight INT, SignRight INT, FormatRight INT)
	DECLARE @Id INT, @AllScore INT, @HasObjHigher BIT, @OrderRight BIT, @SignRight BIT, @FormatRight BIT
	SET @Id = 0
	WHILE EXISTS(SELECT 'x' FROM #t WHERE ID > @Id)
	BEGIN
		SELECT TOP 1 @Id = ID FROM #t WHERE ID > @Id ORDER BY ID
		SELECT @AllScore = SUM(Score) FROM Kpi_Oc WHERE YearMonth = @YearMonth AND ManagerUserId = @Id
		SELECT @AllScore = ISNULL(@AllScore, 0), @HasObjHigher = 1, @OrderRight = 1, @SignRight = 1, @FormatRight = 1
		SELECT @HasObjHigher = 0 FROM Kpi_Oc WHERE YearMonth = @YearMonth AND ManagerUserId = @Id AND ISNULL(Obj_Higher, '') = ''

		IF EXISTS(SELECT 'x' FROM Kpi_Oc a, Kpi_Oc b WHERE a.YearMonth = @YearMonth AND a.ManagerUserId = @Id 
			AND b.YearMonth = @YearMonth AND b.ManagerUserId = @Id AND a.Score >  b.Score AND A.Kpi_Power > b.Kpi_Power)
			SET @OrderRight = 0
 
		IF EXISTS(SELECT 'x' FROM Kpi_Oc WHERE YearMonth = @YearMonth AND ManagerUserId = @Id 
			AND (CHARINDEX('《', [Standard]) > 0 OR CHARINDEX('》', [Standard]) > 0
				OR CHARINDEX('《', Obj_Self) > 0 OR CHARINDEX('》', Obj_Self) > 0
				OR CHARINDEX('《', Obj_Higher) > 0 OR CHARINDEX('》', Obj_Higher) > 0))
			SET @SignRight = 0

		IF EXISTS(SELECT 'x' FROM Kpi_Oc WHERE YearMonth = @YearMonth
			AND ManagerUserId = @Id AND WorkPlan NOT LIKE '完成%作业%')
			SET @FormatRight = 0

		IF @AllScore <>  91 OR @HasObjHigher = 0 OR @OrderRight = 0 OR @SignRight = 0 OR @FormatRight = 0
			INSERT INTO @t
			SELECT @ID, @AllScore, @HasObjHigher, @OrderRight, @SignRight, @FormatRight
	END
	SELECT * FROM @t
END


GO
/****** Object:  StoredProcedure [dbo].[spMakeVarJobTypeJs]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[spMakeVarJobTypeJs]
AS
SET NOCOUNT ON
BEGIN
	SELECT a.CategoryId, LEFT(b.Id, 2) JobTypeId, b.Id, b.Description, b.OrderNo
	INTO #t
	FROM dcJobTypeMap a, dcJobType b
	WHERE a.JobtypeId = LEFT(b.Id, 2)
	ORDER BY a.CategoryId, b.Id

	INSERT INTO #t
	SELECT a.CategoryId, b.ParentId2, b.Id, b.Description, b.OrderNo
	FROM dcJobTypeMap a, dcJobType b
	WHERE a.JobTypeId = b.ParentId2
	ORDER BY a.CategoryId, b.ParentId2
	UPDATE #t SET OrderNo = 10000 + OrderNo WHERE Description LIKE '其他%'
	UPDATE #t SET OrderNo = 1000 + OrderNo WHERE ID > 100 AND LEFT(Id, 2) <> JobTypeId
	--SELECT * FROM #t WHERE Id > 100 ORDER BY CategoryId, JobtypeID, OrderNo
	DELETE #t WHERE JobTypeId = 56
	---------------

	DECLARE @Id INT, @Sql VARCHAR(MAX), @CategoryId INT, @JobTypeId INT, @PreCategoryId INT
	SELECT @Id = 0, @Sql = '', @CategoryId = 0, @JobTypeId = 0, @PreCategoryId = 0
	WHILE EXISTS(SELECT 'x' FROM #t WHERE CategoryId > @CategoryId)
	BEGIN
		SELECT TOP 1 @CategoryId = CategoryId, @JobTypeId = 0 FROM #t WHERE CategoryId > @CategoryId ORDER BY CategoryId
		WHILE EXISTS(SELECT 'x' FROM #t WHERE CategoryId = @CategoryId AND JobTypeId > @JobTypeId AND JobTypeId < 100)
		BEGIN
			SELECT TOP 1 @JobTypeId = JobTypeId FROM #t WHERE CategoryId = @CategoryId AND JobTypeId > @JobTypeId AND JobTypeId < 100 ORDER BY JobTypeId
			PRINT 'jsJobTypeL2[' + LTRIM(STR(@Id)) + '] = new Array();'
			PRINT 'jsJobTypeL2ID[' + LTRIM(STR(@Id)) + '] = new Array();'
			SET @Sql = ''
			SELECT @SQl = @Sql + CASE WHEN @Sql = '' THEN '"' ELSE ',"' END + Description + '"' FROM #t WHERE JobTypeId = @JobTypeId AND Id > 99 ORDER BY OrderNo
			SET @Sql = 'jsJobTypeL2[' + LTRIM(STR(@Id)) + ']=[' + @Sql + '];'
			PRINT @sql
			SET @Sql = ''
			SELECT @SQl = @Sql + CASE WHEN @Sql = '' THEN '"' ELSE ',"' END + LTRIM(STR(ID)) + '"' FROM #t WHERE JobTypeId = @JobTypeId AND Id > 99 ORDER BY OrderNo
			SET @Sql = 'jsJobTypeL2ID[' + LTRIM(STR(@Id)) + ']=[' + @Sql + '];'
			PRINT @sql
			SET @Id = @Id + 1
		END
	END
	SET @Sql = ''
	SELECT @SQl = @Sql + CASE WHEN @Sql = '' THEN '"' ELSE ',"' END + b.Description + '"' 
	FROM dcJobTypeMap a, dcJobType b
	WHERE a.JobTypeId = b.ID
	AND b.Id < 99
	AND b.Id <> 56
	ORDER BY CategoryId, JobTypeID
	SET @Sql = 'jsJobTypeL1=[' + @Sql + '];'
	PRINT @sql

	SET @Sql = ''
	SELECT @SQl = @Sql + CASE WHEN @Sql = '' THEN '"' ELSE ',"' END + LTRIM(STR(b.Id)) + '"'
	FROM dcJobTypeMap a, dcJobType b
	WHERE a.JobTypeId = b.ID
	AND b.Id < 99
	AND b.Id <> 56
	ORDER BY CategoryId, JobTypeID
	SET @Sql = 'jsJobTypeL1ID=[' + @Sql + '];'
	PRINT @sql
END


GO
/****** Object:  StoredProcedure [dbo].[spMakeVarJobTypeJsLagre]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[spMakeVarJobTypeJsLagre]
AS
SET NOCOUNT ON
BEGIN
	SELECT a.CategoryId, LEFT(b.Id, 2) JobTypeId, b.Id, b.Description, b.OrderNo
	INTO #t
	FROM dcJobTypeMap a, dcJobType b
	WHERE a.JobtypeId = LEFT(b.Id, 2)
	AND b.Id < 100
	ORDER BY a.CategoryId, b.Id
	---------------

	DECLARE @Id INT, @Sql VARCHAR(MAX), @SqlId VARCHAR(MAX), @CategoryId INT, @JobTypeId INT, @PreCategoryId INT
	SELECT @Id = 0, @Sql = '', @CategoryId = 0, @JobTypeId = 0, @PreCategoryId = 0
	WHILE EXISTS(SELECT 'x' FROM #t WHERE CategoryId > @CategoryId)
	BEGIN
		SELECT TOP 1 @CategoryId = CategoryId, @JobTypeId = 0 FROM #t WHERE CategoryId > @CategoryId ORDER BY CategoryId
		PRINT 'jsJobTypeL2[' + LTRIM(STR(@CategoryId-1)) + '] = new Array();'
		PRINT 'jsJobTypeL2ID[' + LTRIM(STR(@CategoryId-1)) + '] = new Array();'

		SET @Sql = ''
		SELECT @SQl = @Sql + CASE WHEN @Sql = '' THEN '"' ELSE ',"' END + Description + '"' 
		FROM #t 
		WHERE CategoryId = @CategoryId
		ORDER BY JobtypeId
		PRINT 'jsJobTypeL2[' + LTRIM(STR(@CategoryId-1)) + ']=[' + @Sql + '];'
	
		SET @Sql = ''
		SELECT @SQl = @Sql + CASE WHEN @Sql = '' THEN '"' ELSE ',"' END + LTRIM(STR(ID)) + '"' 
		FROM #t 
		WHERE CategoryId = @CategoryId
		ORDER BY JobtypeId
		PRINT 'jsJobTypeL2ID[' + LTRIM(STR(@CategoryId-1)) + ']=[' + @Sql + '];'
		PRINT ''
	END
END

GO
/****** Object:  StoredProcedure [dbo].[spMakeVarJobTypeJson]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[spMakeVarJobTypeJson]
AS
SET NOCOUNT ON
BEGIN
	SELECT a.CategoryId, LEFT(b.Id, 2) JobTypeId, b.Id, b.Description, b.OrderNo
	INTO #t
	FROM dcJobTypeMap a, dcJobType b
	WHERE a.JobtypeId = LEFT(b.Id, 2)
	ORDER BY a.CategoryId, b.Id

	INSERT INTO #t
	SELECT a.CategoryId, b.ParentId2, b.Id, b.Description, b.OrderNo
	FROM dcJobTypeMap a, dcJobType b
	WHERE a.JobTypeId = b.ParentId2
	ORDER BY a.CategoryId, b.ParentId2
	UPDATE #t SET OrderNo = 10000 + OrderNo WHERE Description LIKE '其他%'
	UPDATE #t SET OrderNo = 1000 + OrderNo WHERE ID > 100 AND LEFT(Id, 2) <> JobTypeId
	DELETE #t WHERE JobTypeId = 56
	---------------
	Print 'var jobTypeData = ['
	DECLARE @Id INT, @Sql VARCHAR(MAX), @CategoryId INT, @JobTypeId INT, @PreCategoryId INT, @desc VARCHAR(50)
	SELECT @Id = 0, @Sql = '', @CategoryId = 0, @JobTypeId = 0, @PreCategoryId = 0
	WHILE EXISTS(SELECT 'x' FROM #t WHERE CategoryId > @CategoryId)
	BEGIN
		SELECT TOP 1 @CategoryId = CategoryId, @JobTypeId = 0 FROM #t WHERE CategoryId > @CategoryId ORDER BY CategoryId
		WHILE EXISTS(SELECT 'x' FROM #t WHERE CategoryId = @CategoryId AND JobTypeId > @JobTypeId AND JobTypeId < 100)
		BEGIN
			SELECT TOP 1 @desc = ''
			SELECT TOP 1 @JobTypeId = JobTypeId, @desc = Description FROM #t WHERE CategoryId = @CategoryId AND JobTypeId > @JobTypeId AND Id < 100 ORDER BY JobTypeId

			SET @Sql = '{"value": "' + LTRIM(STR(@JobTypeId)) + '", "text": "' + @desc + '", "children":['
			SELECT @SQl = @Sql + '{"value": "' + LTRIM(Str(Id)) + '", "text": "' + Description + '", "children": []},' FROM #t WHERE JobTypeId = @JobTypeId AND Id > 99 ORDER BY OrderNo
			SET @Sql = LEFT(@Sql, LEN(@sql) - 1) + ']},'
			PRINT @sql
			
			SET @Id = @Id + 1
		END
	END
	Print '{"value": "56", "text": "其他", "children": []}
]'
END

GO
/****** Object:  StoredProcedure [dbo].[spManageruserByLeaveUpdate]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE procedure [dbo].[spManageruserByLeaveUpdate]
as
BEGIN
	IF NOT EXISTS(SELECT 'x' FROM ManagerUser WHERE Name != '空岗' AND Status = 3)
		RETURN

	update manageruser set name='空岗', loginstatus=2,photo=null where status=3
	
	create table #t(id int identity(1, 1), p varchar(8))
	insert #t
	select top 999 substring(password, 10, 8) from pamain order by id desc

	update a set a.password=b.p
	from manageruser a, #t b
	where a.id = b.id
	and a.status=3
	and a.name = '空岗'
END
GO
/****** Object:  StoredProcedure [dbo].[spManageruserByPasswordUpdate]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[spManageruserByPasswordUpdate]
AS
BEGIN
	CREATE TABLE #t(id INT, Pass INT)
	DECLARE @Pass INT, @id INT
	SET @id = 0
	WHILE EXISTS(SELECT 'x' FROM ManagerUser WHERE id > @id)
	BEGIN
		SELECT TOP 1 @id = id FROM ManagerUser WHERE id > @id ORDER BY id
		SELECT @Pass = cASt( floor(rand()*89999999)+10000000 AS INT) 
		IF @Pass LIKE '%4%'
			SELECT @Pass = cASt( floor(rand()*89999999)+10000000 AS INT) 
		IF @Pass LIKE '%4%'
			SELECT @Pass = cASt( floor(rand()*89999999)+10000000 AS INT) 
		IF @Pass LIKE '%4%'
			SELECT @Pass = cASt( floor(rand()*89999999)+10000000 AS INT) 
		INSERT INTO #t SELECT @id, @Pass
	END
	UPDATE a SET a.Password = b.Pass FROM ManagerUser a, #t b WHERE a.id = b.id

	INSERT INTO rtxnotIFylog(receiver, rtxtitle, rtxmessage, sENDtype, delaytime, showtype)
	SELECT id, '后台密码修改通知', 
		'您的后台密码已经修改为' + LTRIM(STR(Pass)) + '，敬请注意。RTX、邮箱密码、呼叫中心密码没有修改，请你立刻自行修改RTX密码、邮箱密码、呼叫中心密码，与后台密码保持一致。邮箱密码修改可以通过“后台-->工作台-->公司邮箱”进行；RTX密码修改可以通过“RTX-->个人设置”进行；呼叫中心密码可以登录呼叫中心修改。', 1, 0, 0
	FROM #t
	WHERE Id IN(SELECT Id FROM ManagerUser WHERE Status <> 3)
END

GO
/****** Object:  StoredProcedure [dbo].[spManagerUserByRtxStateUpdate]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[spManagerUserByRtxStateUpdate]
(
	@UserData VARCHAR(MAX)
)
AS
SET NOCOUNT ON
BEGIN
	DECLARE @t AS TABLE(data VARCHAR(MAX))
	DECLARE @T_RtxState AS TABLE(Id INT, RtxName VARCHAR(20), CurState TINYINT, CrDate DATETIME, 
		PreStatus TINYINT, PreTime DateTime, StaySecond INT)

	INSERT INTO @t 
	SELECT REPLACE(a, '|', '') FROM dbo.fnSplit(@UserData, '||')

	DECLARE @online VARCHAR(MAX), @offline VARCHAR(MAX), @away VARCHAR(MAX)
	SELECT @Online = REPLACE(data, 'online=', '') FROM @t WHERE data LIKE 'online=%'
	SELECT @offline = REPLACE(data, 'offline=', '') FROM @t WHERE data LIKE 'offline=%'
	SELECT @away = REPLACE(data, 'away=', '') FROM @t WHERE data LIKE 'away=%'

	INSERT INTO @T_RtxState(Id, RtxName, CurState, CrDate, PreStatus, PreTime)
	SELECT ID, Name_Eng, 0, GETDATE(), RtxStatus, RtxTime
	FROM ManagerUser
	WHERE Status < 3

	UPDATE @T_RtxState SET CurState = 0 WHERE RtxName IN(SELECT a FROM dbo.fnsplit(@offline, ';'))
	UPDATE @T_RtxState SET CurState = 1 WHERE RtxName IN(SELECT a FROM dbo.fnsplit(@online, ';'))
	UPDATE @T_RtxState SET CurState = 2 WHERE RtxName IN(SELECT a FROM dbo.fnsplit(@away, ';'))

	UPDATE a SET a.PreStatus = b.RtxStatus, a.PreTime = b.RtxTime, a.Id = b.Id
	FROM @T_RtxState a, ManagerUser b
	WHERE a.RtxName = b.Name_Eng
	AND b.Status < 3

	UPDATE @T_RtxState SET PreTime = CrDate WHERE PreTime < DATEADD(MINUTE, -60, GETDATE())
	UPDATE @T_RtxState SET StaySecond = DATEDIFF(SECOND, PreTime, CrDate)

	DELETE FROM @T_RtxState WHERE Id IS NULL

	UPDATE a SET a.RtxStatus = b.CurState, a.RtxTime = b.crDate
	FROM ManagerUser a, @T_RtxState b
	WHERE a.Id = b.Id

	UPDATE a SET a.PreRtxStatus = b.PreStatus, a.RtxStatus = b.CurState,
		a.OnlineSecond = a.OnLineSecond + b.StaySecond * 1000,
		a.AllOnlineTime = a.AllOnlineTime + b.StaySecond * 1000,
		a.CheckTime = b.crDate
	FROM bsRtxStatus a, @T_RtxState b
	WHERE a.CheckDay = CONVERT(VARCHAR(8), GETDATE(), 112)
	AND a.ManagerUserId = b.Id
	AND b.PreStatus = 1

	UPDATE a SET a.PreRtxStatus = b.PreStatus, a.RtxStatus = b.CurState,
		a.OfflineSecond = a.OffLineSecond + b.StaySecond * 1000,
		a.CheckTime = b.crDate
	FROM bsRtxStatus a, @T_RtxState b
	WHERE a.CheckDay = CONVERT(VARCHAR(8), GETDATE(), 112)
	AND a.ManagerUserId = b.Id
	AND b.PreStatus = 0

	UPDATE a SET a.PreRtxStatus = b.PreStatus, a.RtxStatus = b.CurState,
		a.LeaveSecond = a.LeaveSecond + b.StaySecond * 1000,
		a.CheckTime = b.crDate
	FROM bsRtxStatus a, @T_RtxState b
	WHERE a.CheckDay = CONVERT(VARCHAR(8), GETDATE(), 112)
	AND a.ManagerUserId = b.Id
	AND b.PreStatus = 2

	INSERT bsRtxStatusLog(ManagerUserID, RtxStatus) 
	SELECT Id, CurState
	FROM @T_RtxState
	WHERE PreStatus <> CurState

	SELECT Id, CurState
	FROM @T_RtxState
	WHERE PreStatus <> CurState

	SELECT Count(*) FROM @T_RtxState
END

GO
/****** Object:  StoredProcedure [dbo].[spMarketNeedSave]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
1、山东省十七地市企业数量、发布岗位数量、求职简历数量，分季度。
2、按行业份，山东省各行业企业数量、发布岗位数量、求职简历数量，分季度。
3、山东省岗位薪酬排行，分季度
4、山东省热门岗位数量，分季度
5、山东省热门岗位薪酬，分季度
*/
CREATE PROCEDURE [dbo].[spMarketNeedSave]
AS
SET NOCOUNT ON
BEGIN
	DECLARE @Month AS VARCHAR(8), @BeginDate AS DATETIME
	SELECT @Month = CONVERT(VARCHAR(6), GETDATE(), 112), @BeginDate = GETDATE()
	DELETE FROM ReportDb..MarketData WHERE CountMonth = @Month
	--山东省十七地市
	--企业数量
	INSERT INTO ReportDb..MarketData(CountMonth, CountType, dcRegionId, CountNumber)
	SELECT @Month, 1, LEFT(dcRegionId, 4) dcRegionId, COUNT(*) Cnt FROM cpMain WHERE Regdate < @BeginDate GROUP BY Left(dcRegionId, 4)
	--发布岗位数量
	INSERT INTO ReportDb..MarketData(CountMonth, CountType, dcRegionId, CountNumber)	
	SELECT @Month, 2, LEFT(dcRegionId, 4) dcRegionId, COUNT(*) Cnt FROM Job WHERE IssueDate < @BeginDate GROUP BY Left(dcRegionId, 4)
	--求职简历数量
	INSERT INTO ReportDb..MarketData(CountMonth, CountType, dcRegionId, CountNumber)
	SELECT @Month, 3, LEFT(LivePlace, 4) dcRegionId, COUNT(*) * 1.1 Cnt FROM paMain WHERE AddDate < @BeginDate GROUP BY Left(LivePlace, 4)

	--按行业份，山东省各行业
	--企业数量
	INSERT INTO ReportDb..MarketData(CountMonth, CountType, dcRegionId, dcIndustryId, CountNumber)
	SELECT @Month, 11, LEFT(a.dcRegionId, 2), b.dcIndustryId, COUNT(*) Cnt FROM cpMain a, cpIndustry b WHERE a.Id = b.cpMainId AND a.RegDate < @BeginDate GROUP BY LEFT(a.dcRegionId, 2), b.dcIndustryId
	--发布岗位数量
	INSERT INTO ReportDb..MarketData(CountMonth, CountType, dcRegionId, dcIndustryId, CountNumber)
	SELECT @Month, 12, LEFT(a.dcRegionId, 2), b.dcIndustryId, COUNT(*) Cnt FROM cpMain a, cpIndustry b, Job c WHERE a.Id = b.cpMainId AND c.cpMainId = a.Id AND a.RegDate < @BeginDate GROUP BY LEFT(a.dcRegionId, 2), b.dcIndustryId
	--求职简历数量
	INSERT INTO ReportDb..MarketData(CountMonth, CountType, dcRegionId, dcIndustryId, CountNumber)
	SELECT @Month, 13, LEFT(a.LivePlace, 2), c.dcIndustryId, COUNT(*) Cnt FROM paMain a, cvMain b, cvIndustry c WHERE a.Id = b.paMainId AND b.Id = c.cvMainId AND a.AddDate < @BeginDate GROUP BY LEFT(a.LivePlace, 2), c.dcIndustryId
END

GO
/****** Object:  StoredProcedure [dbo].[spMergeJobType]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE procedure [dbo].[spMergeJobType]
(
	@OldJobtype VARCHAR(4),
	@NewJobtype VARCHAR(4)
)
AS
SET NOCOUNT ON
BEGIN
	print @OldJobtype
	--####################################33
	DELETE caJobResumePreJobType WHERE dcJobTypeId = @OldJobtype AND cvMainId IN(SELECT cvMainId FROM caJobResumePreJobType WHERE dcJobTypeId = @NewJobtype)
	UPDATE caJobResumePreJobType SET dcJobTypeId = @NewJobtype WHERE dcJobTypeId = @OldJobtype
	------------------------
	UPDATE cvExperience SET dcJobtypeID = @NewJobtype WHERE dcJobtypeID = @OldJobtype
	UPDATE cvExperiencePublish SET dcJobtypeID = @NewJobtype WHERE dcJobtypeID = @OldJobtype
	------------------------
	SELECT Distinct cvMainId INTO #t1 FROM cvJobType WITH(NOLOCK) WHERE dcJobTypeId = @OldJobtype OR dcJobTypeId = @NewJobtype
	DELETE FROM cvJobType WHERE (dcJobTypeId = @OldJobtype OR dcJobTypeId = @NewJobtype) AND cvMainId IN(SELECT cvMainId FROM #t1)
	INSERT cvJobType (cvMainId, dcJobTypeId) SELECT cvMainId, @NewJobtype FROM #t1
	SELECT Distinct cvMainId INTO #t2 FROM cvJobTypePublish WITH(NOLOCK) WHERE dcJobTypeId = @OldJobtype OR dcJobTypeId = @NewJobtype
	DELETE FROM cvJobTypePublish WHERE (dcJobTypeId = @OldJobtype OR dcJobTypeId = @NewJobtype) AND cvMainId IN(SELECT cvMainId FROM #t2)
	INSERT cvJobTypePublish (cvMainId, dcJobTypeId) SELECT cvMainId, @NewJobtype FROM #t2
	------------------------------------------
	UPDATE cvMain SET LastJobTypeID = @NewJobtype WHERE LastJobTypeID = @OldJobtype
	UPDATE cvMainPublish SET LastJobTypeID = @NewJobtype WHERE LastJobTypeID = @OldJobtype
	-------------------------------
	DELETE dcJobName WHERE dcJobTypeId = @OldJobtype AND Name IN(SELECT Name FROM dcJobName WHERE dcJobTypeId = @NewJobtype)
	UPDATE dcJobName SET dcJobTypeId = @NewJobtype WHERE dcJobTypeId = @OldJobtype
	-------------------------------------
	DELETE dcJobTypeMap WHERE JobTypeId = @OldJobtype
	-------------------------------------
	DELETE dcJobTypeTemplate WHERE dcJobTypeId = @OldJobtype
	-----------------------------
	UPDATE hpJobTypeCpLogo SET dcJobTypeId = @NewJobtype WHERE dcJobTypeId = @OldJobtype
	-----------------------------
 	UPDATE Job SET dcJobTypeId = @NewJobtype WHERE dcJobTypeId = @OldJobtype
	UPDATE Job SET dcJobTypeIDMinor = @NewJobtype WHERE dcJobTypeIDMinor = @OldJobtype
	UPDATE JobPublish SET dcJobTypeId = @NewJobtype WHERE dcJobTypeId = @OldJobtype
	UPDATE JobPublish SET dcJobTypeIDMinor = @NewJobtype WHERE dcJobTypeIDMinor = @OldJobtype
	UPDATE JobTemplate SET dcJobTypeId = @NewJobtype WHERE dcJobTypeId = @OldJobtype
	UPDATE JobTemplate SET dcJobTypeIDMinor = @NewJobtype WHERE dcJobTypeIDMinor = @OldJobtype	
	UPDATE JobSimilar SET dcJobTypeId = @NewJobtype WHERE dcJobTypeId = @OldJobtype

	UPDATE caCvFinder SET dcJobTypeId = REPLACE(dcJobTypeId, @OldJobtype, @NewJobtype) WHERE dcJobTypeId LIKE '%' + @OldJobtype + '%'

	UPDATE paJobFinder SET dcJobTypeId = REPLACE(dcJobTypeId, @OldJobtype, @NewJobtype) WHERE dcJobTypeId LIKE '%' + @OldJobtype + '%'

	DELETE FROM dcJobType WHERE id = @OldJobtype
	----dcJobTypeHot
END
GO
/****** Object:  StoredProcedure [dbo].[spMergeRegion]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--########################################
--转换数据，从@OldRegion转到@NewRegion
--########################################
CREATE PROCEDURE [dbo].[spMergeRegion]
(
	@OldRegion VARCHAR(6),
	@NewRegion VARCHAR(6)
)
AS
SET NOCOUNT OFF
BEGIN TRY
	BEGIN TRAN
		--####################################33
		UPDATE dcBusinessCircle SET dcRegionId = @NewRegion WHERE dcRegionId = @OldRegion
		UPDATE Job SET dcRegionId = @NewRegion WHERE dcRegionId = @OldRegion
		UPDATE JobPublish SET dcRegionId = @NewRegion WHERE dcRegionId = @OldRegion
		UPDATE JobTemplate SET dcRegionId = @NewRegion WHERE dcRegionId = @OldRegion
		UPDATE paMain SET LivePlace = @NewRegion WHERE LivePlace = @OldRegion
		UPDATE paMain SET GrowPlace = @NewRegion WHERE GrowPlace = @OldRegion
		UPDATE paMain SET AccountPlace = @NewRegion WHERE AccountPlace = @OldRegion
		UPDATE cvexperience SET WorkPlace = @NewRegion WHERE WorkPlace = @OldRegion

		UPDATE caCvFinder SET dcRegionId = REPLACE(dcRegionId, @OldRegion, @NewRegion) WHERE dcRegionId = @OldRegion
		UPDATE caCvFinder SET dcRegionId = REPLACE(dcRegionId, @OldRegion, @NewRegion) WHERE dcRegionId like @OldRegion + ',%'
		UPDATE caCvFinder SET dcRegionId = REPLACE(dcRegionId, @OldRegion, @NewRegion) WHERE dcRegionId like '%,' + @OldRegion + ',%'
		UPDATE caCvFinder SET dcRegionId = REPLACE(dcRegionId, @OldRegion, @NewRegion) WHERE dcRegionId like '%,' + @OldRegion

		UPDATE paJobFinder SET dcRegionId = REPLACE(dcRegionId, @OldRegion, @NewRegion) WHERE dcRegionId = @OldRegion
		UPDATE paJobFinder SET dcRegionId = REPLACE(dcRegionId, @OldRegion, @NewRegion) WHERE dcRegionId like @OldRegion + ',%'
		UPDATE paJobFinder SET dcRegionId = REPLACE(dcRegionId, @OldRegion, @NewRegion) WHERE dcRegionId like '%,' + @OldRegion + ',%'
		UPDATE paJobFinder SET dcRegionId = REPLACE(dcRegionId, @OldRegion, @NewRegion) WHERE dcRegionId like '%,' + @OldRegion

		--####################################33
		DECLARE curCpMain CURSOR FOR
			SELECT ID FROM cpMain WITH(NOLOCK)
			WHERE dcRegionId = @OldRegion
		OPEN curCpMain

		DECLARE @Id INT

		FETCH NEXT FROM curCpMain INTO @Id
		WHILE(@@FETCH_STATUS =0)
		BEGIN
			UPDATE cpMain SET dcRegionId = @NewRegion WHERE id = @Id
			FETCH NEXT FROM curCpMain INTO @Id
		END

		CLOSE curCpMain
		DEALLOCATE curCpMain
		--####################################33
		DECLARE curCpMainPublish CURSOR FOR
			SELECT ID FROM cpMainPublish WITH(NOLOCK)
			WHERE dcRegionId = @OldRegion
		OPEN curCpMainPublish

		FETCH NEXT FROM curCpMainPublish INTO @Id
		WHILE(@@FETCH_STATUS =0)
		BEGIN
			UPDATE cpMainPublish SET dcRegionId = @NewRegion WHERE id = @Id
			FETCH NEXT FROM curCpMainPublish INTO @Id
		END

		CLOSE curCpMainPublish
		DEALLOCATE curCpMainPublish

		--####################################33
		SELECT Distinct cvMainId INTO #t FROM cvJobplace WITH(NOLOCK) WHERE dcRegionId = @OldRegion OR dcRegionId = @NewRegion
		DELETE FROM cvJobplace WHERE (dcRegionId = @OldRegion OR dcRegionId = @NewRegion) AND cvMainId IN(SELECT cvMainId FROM #t)
		INSERT cvJobplace (cvMainId, dcRegionId) SELECT cvMainId, @NewRegion FROM #t
		--####################################33
		SELECT Distinct cvMainId INTO #tt FROM cvJobplacePublish WITH(NOLOCK) WHERE dcRegionId = @OldRegion OR dcRegionId = @NewRegion
		DELETE FROM cvJobplacePublish WHERE (dcRegionId = @OldRegion OR dcRegionId = @NewRegion) AND cvMainId IN(SELECT cvMainId FROM #tt)
		INSERT cvJobplacePublish (cvMainId, dcRegionId) SELECT cvMainId, @NewRegion FROM #tt
		--####################################33

		DELETE FROM dcregion WHERE id = @OldRegion
	COMMIT
END TRY
BEGIN CATCH
	PRINT ERROR_MESSAGE()
	ROLLBACK TRAN
END CATCH

GO
/****** Object:  StoredProcedure [dbo].[spNewJobRelatedInsert]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[spNewJobRelatedInsert]
AS
BEGIN
	SELECT a.id JobId, a.SecondId, a.Name, LEFT(a.dcRegionId, 2) dcRegionId, LEFT(a.dcJobTypeId, 2) dcJobTypeId,
		ROW_NUMBER() OVER(PARTITION BY LEFT(a.dcRegionId, 2), LEFT(a.dcJobTypeId, 2) ORDER BY a.RefreshDate) RowNo
	INTO #t
	FROM JobPublish a WITH(NOLOCK), 
		cpMain b WITH(NOLOCK)
	WHERE a.cpMainId = b.Id
	AND a.Valid = 1
	AND b.Valid = 1
	AND a.dcRegionId LIKE LTRIM(STR(b.dcProvinceId)) + '%'

	DELETE #t WHERE RowNo > 100

	CREATE TABLE #r(JobId INT, RowNo INT IDENTITY(1, 1))
	INSERT INTO #r SELECT JobId FROM #t ORDER BY NEWID()

	TRUNCATE TABLE ShortDb..NewJobRelated

	INSERT INTO NewJobRelated(JobId, SecondId, Name, dcRegionId, dcJobTypeId, RowNo)
	SELECT a.JobId, a.SecondId, a.Name, a.dcRegionId, a.dcJobTypeID, b.RowNo
	FROM #t a, #r b
	WHERE a.JobId = b.JobId
END

GO
/****** Object:  StoredProcedure [dbo].[spOrderAnalysis]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[spOrderAnalysis]
(
	@Year INT,
	@ProvinceId INT
)
AS
BEGIN
	IF @Year > DATEPART(Year, getdate())
		RETURN
	IF @Year < 2002
		SET @Year = 0
	IF @ProvinceId > 0 AND NOT EXISTS(SELECT 'x' FROM dcProvince WHERE ID=@ProvinceId)
		RETURN

	DECLARE @Sql AS VARCHAR(MAX)
	IF ISNULL((SELECT TOP 1 CountDate FROM OrderAnalysis), '') <> CONVERT(VARCHAR(10), GETDATE(), 120)
	BEGIN
		TRUNCATE TABLE OrderAnalysis

		SET @Sql = 'INSERT INTO OrderAnalysis SELECT Row_Number() OVER(order by cpMainid, begindate) ID, ID OrderId, cpMainid, ProvinceId, paid, opendate, begindate, enddate,
				Paid Paid2, OpenDate OpenDate2, BeginDate BeginDate2, EndDate EndDate2, ID NextId, Id DiffDay, Id DiffMonth, 0, '''', CONVERT(VARCHAR(10), GETDATE(), 120)
				from caorder with(nolock)
				where ordertype in(1,2,8) 
				and paid>0 
				and opendate IS NOT NULL
				and enddate IS NOT NULL'
		EXEC(@Sql)

		UPDATE OrderAnalysis SET Paid2 = NULL, OpenDate2 = NULL, BeginDate2 = NULL, EndDate2 = NULL, NextId = NULL, DiffDay = NULL, DiffMonth = NULL

		UPDATE a
		SET a.NextID = (SELECT Min(ID) FROM OrderAnalysis WHERE OrderAnalysis.cpMainID = a.cpMainId AND OrderAnalysis.Id > a.Id)
		FROM OrderAnalysis a

		UPDATE a
		SET a.BeginDate2 = (SELECT BeginDate FROM OrderAnalysis WHERE OrderAnalysis.ID = a.NextId),
			a.Paid2 = (SELECT Paid FROM OrderAnalysis WHERE OrderAnalysis.ID = a.NextId),
			a.EndDate2 = (SELECT EndDate FROM OrderAnalysis WHERE OrderAnalysis.ID = a.NextId),
			a.OpenDate2 = (SELECT OpenDate FROM OrderAnalysis WHERE OrderAnalysis.ID = a.NextId)
		FROM OrderAnalysis a
		WHERE NextId > 0


		UPDATE OrderAnalysis SET DiffDay = DATEDIFF(DAY, EndDate, OpenDate2), DiffMonth = DATEDIFF(MONTH, EndDate, OpenDate)
		UPDATE OrderAnalysis SET DiffDay = 0, DiffMonth = 0 WHERE DiffDay < 0

		UPDATE OrderAnalysis SET Interval = 1, IntervalRemark = '0~7天' WHERE DiffDay <=7
		UPDATE OrderAnalysis SET Interval = 2, IntervalRemark = '8~30天' WHERE DiffDay > 7 AND DiffDay <= 30
		UPDATE OrderAnalysis SET Interval = 3, IntervalRemark = '31~91天' WHERE DiffDay > 31 AND DiffDay <= 91
		UPDATE OrderAnalysis SET Interval = 4, IntervalRemark = '92~183天' WHERE DiffDay > 91 AND DiffDay <= 183
		UPDATE OrderAnalysis SET Interval = 5, IntervalRemark = '184~365天' WHERE DiffDay > 183 AND DiffDay <= 365
		UPDATE OrderAnalysis SET Interval = 6, IntervalRemark = '366~730天' WHERE DiffDay > 365 AND DiffDay <= 730
		UPDATE OrderAnalysis SET Interval = 7, IntervalRemark = '>730天' WHERE DiffDay > 731
	END

	SELECT TOP 0 * INTO #Order FROM OrderAnalysis WITH(NOLOCK)
	IF @Year = 0
		IF ISNULL(@ProvinceId, 0) = 0
			INSERT INTO #Order SELECT * FROM OrderAnalysis WITH(NOLOCK)
		ELSE
			INSERT INTO #Order SELECT * FROM OrderAnalysis WITH(NOLOCK) WHERE ProvinceId LIKE LTRIM(STR(@ProvinceID)) + '%'
	ELSE
		IF ISNULL(@ProvinceId, 0) = 0
			INSERT INTO #Order SELECT * FROM OrderAnalysis WITH(NOLOCK) WHERE DATEPART(YEAR, OpenDate) <> @Year
		ELSE
			INSERT INTO #Order SELECT * FROM OrderAnalysis WITH(NOLOCK) WHERE DATEPART(YEAR, OpenDate) <> @Year AND ProvinceId LIKE LTRIM(STR(@ProvinceID)) + '%'

	DECLARE @t AS TABLE(
		ID INT IDENTITY(1,1),
		Title VARCHAR(100),
		Cnt DECIMAL(18,2),
		Rate DECIMAL(18, 2)
	)

	DECLARE @S AS DECIMAL(18, 0)
	SELECT @S = COUNT(*) FROM #Order
	INSERT INTO @t VALUES('<font color=red>总订单数</font>', @S, 100.00)

	INSERT INTO @t
	SELECT '交费' + LTRIM(STR(Cnt)) + '次', COUNT(*), SUM(Cnt)*100.0 / @S
	FROM (SELECT cpMainId, COUNT(*) Cnt FROM #Order GROUP BY cpMainID) a
	GROUP BY Cnt
	ORDER BY Cnt

	DECLARE @Total AS INT
	SET @Total = @S
	SELECT @S = COUNT(*) FROM #Order WHERE NextID > 0
	INSERT INTO @t VALUES('<font color=red>续费订单数</font>', @S, @S * 100.00 / @Total)

	INSERT INTO @t
	SELECT IntervalRemark, COUNT(*), COUNT(*) * 100.0/@s 
	FROM #Order 
	WHERE Interval > 0
	GROUP BY Interval, IntervalRemark ORDER BY Interval

	SELECT ID 序号, Title 类型, Cnt 数量, Rate 比例 FROM @t
END














GO
/****** Object:  StoredProcedure [dbo].[spPaMainByRegisterModeFix]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[spPaMainByRegisterModeFix]
AS
BEGIN
	CREATE TABLE #t(Id INT)
	INSERT INTO #t
	SELECT a.id
	FROM cvMain a WITH(NOLOCK), paMain b WITH(NOLOCK)
	WHERE a.paMainId = b.ID 
	AND (
		((a.cvLevel LIKE '1111_1%' AND a.VerifyResult = 1)
			OR (a.cvLevelEng LIKE '1111_1%' AND a.VerifyResultEng = 1)
			)
		AND (b.RegisterMode = 1 OR b.RegisterType = 101)
		AND (b.addDate > GETDATE()-1.1
			OR a.RefreshDate > GETDATE()-1.1
			OR B.LastModifyDate > GETDATE()-1.1
			)
		AND b.AddMan > 1
		AND a.ID NOT IN(select cvMainID FROM bsCvModify WITH(NOLOCK) WHERE cvmainid>0)
		)

	INSERT INTO #t
	SELECT a.id
	FROM cvMain a WITH(NOLOCK), paMain b WITH(NOLOCK)
	WHERE a.paMainId = b.ID 
	AND b.RegisterMode = 1
	AND a.Valid > 0 
	AND (b.AddDate > GETDATE() - 90 OR b.LastLoginDate > GETDATE() - 3)

	DECLARE c CURSOR
	FOR SELECT id FROM #t
	FOR READ ONLY

	OPEN c
	IF @@FETCH_STATUS >= 0
	BEGIN
		DECLARE @cvMainID INT
		FETCH NEXT FROM c INTO @cvMainID
		WHILE(@@FETCH_STATUS = 0)
		BEGIN
			UPDATE cvMain SET VerifyResult = VerifyResult, VerifyResultEng = VerifyResultEng WHERE ID = @cvMainID
			--PRINT @cvMainID
			FETCH NEXT FROM c INTO @cvMainID
		END
	END
	CLOSE c
	DEALLOCATE c
END


GO
/****** Object:  StoredProcedure [dbo].[spPaPublishByFixUpdate]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--2013-3-22 sean fix pamainpublish cvmainpublish..................
CREATE PROCEDURE [dbo].[spPaPublishByFixUpdate]
AS
SET NOCOUNT ON
BEGIN
	SELECT a.id paMainId, b.Id cvMainId
	INTO #tmp
	FROM paMain a, cvMain b
	WHERE a.Id = b.paMainId
	AND a.Verifycount = 0
	AND b.VerifyResult = 1
	AND a.LastLogindate > GETDATE() - 183
	AND a.Id IN(SELECT Id FROM paMainPublish)
	AND b.Id IN(SELECT Id FROM cvMainPublish)
	DELETE cvMainPublish WHERE Id IN(SELECT cvMainId FROM #tmp)
	--------------------------------------
	CREATE TABLE #t(id INT, Col TINYINT)
	DECLARE @d AS DATETIME, @cn AS INT, @H AS INT, @i AS INT
	SELECT @D = CONVERT(VARCHAR(10), GETDATE() - 365, 120), @H = DATEPART(HOUR, GETDATE()), @cn = 6
	
	IF @h % 4 = 1    --OR 1=1
	BEGIN
		INSERT #t(id)
		SELECT id FROM cvmain WITH(NOLOCK) 
		WHERE EXISTS(SELECT 'x' FROM pamain WITH(NOLOCK) WHERE lastlogindate > @D AND pamain.id = cvmain.pamainid AND VerifyCount > 0)
		AND valid>0
		AND NOT EXISTS (SELECT id FROM cvmainpublish WITH(NOLOCK) WHERE cvmainpublish.id = cvmain.id)

		INSERT #t(id)
		SELECT id FROM cvMainPublish WITH(NOLOCK) 
		WHERE NOT EXISTS (SELECT id FROM cvMain WITH(NOLOCK) WHERE cvMain.id = cvMainPublish.id AND cvMain.valid = cvmainpublish.valid)

		DECLARE @id AS INT, @Mid AS INT
		SELECT @id = 0, @mid = max(id) FROM #t
		WHILE @id < @mid
		BEGIN
			SELECT @id = mIN(id) FROM #t WHERE id > @id
			UPDATE cvmain set refreshdate = refreshdate WHERE id = @id
		END

		TRUNCATE TABLE #t

		INSERT #t(ID)
		SELECT ID FROM paMain WHERE DATEADD(DAY, 1, LastLoginDate) < LastModifyDate AND LastLoginDate > GETDATE() - 365 AND VerifyCount > 0
		SELECT @id = 0, @mid = max(id) FROM #t
		WHILE @id < @mid
		BEGIN
			SELECT @id = mIN(id) FROM #t WHERE id > @id
			UPDATE pamain set LastLoginDate = LastModifyDate WHERE id = @id
		END

		TRUNCATE TABLE #t
	END

	INSERT #t SELECT a.id, 3 FROM cvmain a WITH(NOLOCK),cvmainpublish b WITH(NOLOCK) WHERE a.id = b.id AND a.JobName<> b.JobName
	INSERT #t SELECT a.id, 6 FROM cvmain a WITH(NOLOCK),cvmainpublish b WITH(NOLOCK) WHERE a.id = b.id AND a.RefreshDate<> b.RefreshDate	
	IF @h % @cn = 0    --OR 1=1
		INSERT #t SELECT a.id,1 FROM cvmain a WITH(NOLOCK),cvmainpublish b WITH(NOLOCK) WHERE a.id = b.id AND a.Degree<> b.Degree
	IF @h % @cn = 1    --OR 1=1
		INSERT #t SELECT a.id,2 FROM cvmain a WITH(NOLOCK),cvmainpublish b WITH(NOLOCK) WHERE a.id = b.id AND a.dcMajorID<> b.dcMajorID
	IF @h % @cn = 2    --OR 1=1
		INSERT #t SELECT a.id,4 FROM cvmain a WITH(NOLOCK),cvmainpublish b WITH(NOLOCK) WHERE a.id = b.id AND a.RelatedWorkYears<> b.RelatedWorkYears
	IF @h % @cn = 3    --OR 1=1
		INSERT #t SELECT a.id,5 FROM cvmain a WITH(NOLOCK),cvmainpublish b WITH(NOLOCK) WHERE a.id = b.id AND a.dcSalaryID<> b.dcSalaryID
	IF @h % @cn = 4    --OR 1=1
		INSERT #t SELECT a.id,7 FROM cvmain a WITH(NOLOCK),cvmainpublish b WITH(NOLOCK) WHERE a.id = b.id AND a.LastJobTypeID<> b.LastJobTypeID
	IF @h % @cn = 5    --OR 1=1
		INSERT #t SELECT a.id,8 FROM cvmain a WITH(NOLOCK),cvmainpublish b WITH(NOLOCK) WHERE a.id = b.id AND a.LastIndustryID<> b.LastIndustryID
	IF @h % @cn = 0    --OR 1=1
		INSERT #t SELECT a.id,9 FROM cvmain a WITH(NOLOCK),cvmainpublish b WITH(NOLOCK) WHERE a.id = b.id AND a.SubNodeNum<> b.SubNodeNum
	IF @h % @cn = 1    --OR 1=1
		INSERT #t SELECT a.id,10 FROM cvmain a WITH(NOLOCK),cvmainpublish b WITH(NOLOCK) WHERE a.id = b.id AND a.IsNegotiable<> b.IsNegotiable
	IF @h % @cn = 2    --OR 1=1
		INSERT #t SELECT a.id,11 FROM cvmain a WITH(NOLOCK),cvmainpublish b WITH(NOLOCK) WHERE a.id = b.id AND a.Attachment<> b.Attachment
	IF @h % @cn = 3    --OR 1=1
		INSERT #t SELECT a.id,12 FROM cvmain a WITH(NOLOCK),cvmainpublish b WITH(NOLOCK) WHERE a.id = b.id AND a.Valid<> b.Valid
	IF @h % @cn = 4    --OR 1=1
		INSERT #t SELECT a.id,13 FROM cvmain a WITH(NOLOCK),cvmainpublish b WITH(NOLOCK) WHERE a.id = b.id AND a.Speciality<> b.Speciality
	IF @h % @cn = 5    --OR 1=1
	BEGIN
		INSERT #t SELECT a.id,14 FROM cvmain a WITH(NOLOCK),cvmainpublish b WITH(NOLOCK) WHERE a.id = b.id AND a.SpecialityEng<> b.SpecialityEng
		INSERT #t SELECT a.id,15 FROM cvmain a WITH(NOLOCK),cvmainpublish b WITH(NOLOCK) WHERE a.id = b.id AND ISNULL(a.EmployType, 10) <> ISNULL(b.EmployType, 10)
	END

	UPDATE a set a.Degree = b.Degree FROM cvmainpublish a, cvmain b WHERE a.id = b.id AND a.id IN(SELECT id FROM #t WHERE col = 1)
	UPDATE a set a.dcMajorID = b.dcMajorID FROM cvmainpublish a, cvmain b WHERE a.id = b.id AND a.id IN(SELECT id FROM #t WHERE col = 2)
	UPDATE a set a.JobName = b.JobName FROM cvmainpublish a, cvmain b WHERE a.id = b.id AND a.id IN(SELECT id FROM #t WHERE col = 3)
	UPDATE a set a.RelatedWorkYears = b.RelatedWorkYears FROM cvmainpublish a, cvmain b WHERE a.id = b.id AND a.id IN(SELECT id FROM #t WHERE col = 4)
	UPDATE a set a.dcSalaryID = b.dcSalaryID FROM cvmainpublish a, cvmain b WHERE a.id = b.id AND a.id IN(SELECT id FROM #t WHERE col = 5)
	UPDATE a set a.RefreshDate = b.RefreshDate FROM cvmainpublish a, cvmain b WHERE a.id = b.id AND a.id IN(SELECT id FROM #t WHERE col = 6)
	UPDATE a set a.LastJobTypeID = b.LastJobTypeID FROM cvmainpublish a, cvmain b WHERE a.id = b.id AND a.id IN(SELECT id FROM #t WHERE col = 7)
	UPDATE a set a.LastIndustryID = b.LastIndustryID FROM cvmainpublish a, cvmain b WHERE a.id = b.id AND a.id IN(SELECT id FROM #t WHERE col = 8)
	UPDATE a set a.SubNodeNum = b.SubNodeNum FROM cvmainpublish a, cvmain b WHERE a.id = b.id AND a.id IN(SELECT id FROM #t WHERE col = 9)
	UPDATE a set a.IsNegotiable = b.IsNegotiable FROM cvmainpublish a, cvmain b WHERE a.id = b.id AND a.id IN(SELECT id FROM #t WHERE col = 10)
	UPDATE a set a.Attachment = b.Attachment FROM cvmainpublish a, cvmain b WHERE a.id = b.id AND a.id IN(SELECT id FROM #t WHERE col = 11)
	UPDATE a set a.Valid = b.Valid FROM cvmainpublish a, cvmain b WHERE a.id = b.id AND a.id IN(SELECT id FROM #t WHERE col = 12)
	UPDATE a set a.Speciality = b.Speciality FROM cvmainpublish a, cvmain b WHERE a.id = b.id AND a.id IN(SELECT id FROM #t WHERE col = 13)
	UPDATE a set a.SpecialityEng = b.SpecialityEng FROM cvmainpublish a, cvmain b WHERE a.id = b.id AND a.id IN(SELECT id FROM #t WHERE col = 14)
	UPDATE a set a.EmployType = b.EmployType FROM cvmainpublish a, cvmain b WHERE a.id = b.id AND a.id IN(SELECT id FROM #t WHERE col = 15)
	----SELECT a.id,c.lastlogindate,a.refreshdate,b.refreshdate FROM cvmain a,cvmainpublish b,pamain c WHERE a.pamainid = c.id AND a.id = b.id AND a.id IN(SELECT id FROM #t WHERE col = 6) order by c.lastlogindate
 
	IF @H = 7
	BEGIN
		TRUNCATE TABLE #t
		INSERT #t SELECT a.id,1 FROM cvappendix a WITH(NOLOCK), cvappendixpublish b WITH(NOLOCK) WHERE a.id = b.id AND a.Description <> b.Description
		INSERT #t SELECT a.id,2 FROM cvappendix a WITH(NOLOCK), cvappendixpublish b WITH(NOLOCK) WHERE a.id = b.id AND a.Name <> b.Name
		UPDATE a SET a.Description = b.Description FROM cvappendixpublish a, cvappendix b WHERE a.id = b.id AND a.id IN(SELECT id FROM #t WHERE col = 1)
		UPDATE a SET a.Name = b.Name FROM cvappendixpublish a, cvappendix b WHERE a.id = b.id AND a.id IN(SELECT id FROM #t WHERE col = 2)

		TRUNCATE TABLE #t
		INSERT #t SELECT a.id,1 FROM cvLanguage a WITH(NOLOCK), cvLanguagepublish b WITH(NOLOCK) WHERE a.id = b.id AND a.LanguageType <> b.LanguageType
		UPDATE a SET a.LanguageType = b.LanguageType FROM cvLanguagepublish a, cvLanguage b WHERE a.id = b.id AND a.id IN(SELECT id FROM #t WHERE col = 1)
		TRUNCATE TABLE #t
		INSERT #t SELECT a.id,1 FROM cvProject a WITH(NOLOCK), cvProjectpublish b WITH(NOLOCK) WHERE a.id = b.id AND a.Description <> b.Description
		INSERT #t SELECT a.id,2 FROM cvProject a WITH(NOLOCK), cvProjectpublish b WITH(NOLOCK) WHERE a.id = b.id AND a.Name <> b.Name
		INSERT #t SELECT a.id,3 FROM cvProject a WITH(NOLOCK), cvProjectpublish b WITH(NOLOCK) WHERE a.id = b.id AND a.Responsibilities <> b.Responsibilities
		UPDATE a SET a.Description = b.Description FROM cvProjectpublish a, cvProject b WHERE a.id = b.id AND a.id IN(SELECT id FROM #t WHERE col = 1)
		UPDATE a SET a.Name = b.Name FROM cvProjectpublish a, cvProject b WHERE a.id = b.id AND a.id IN(SELECT id FROM #t WHERE col = 2)
		UPDATE a SET a.Responsibilities = b.Responsibilities FROM cvProjectpublish a, cvProject b WHERE a.id = b.id AND a.id IN(SELECT id FROM #t WHERE col = 3)
		TRUNCATE TABLE #t
		INSERT #t SELECT a.id,1 FROM cvTraining a WITH(NOLOCK), cvTrainingpublish b WITH(NOLOCK) WHERE a.id = b.id AND a.Certificate <> b.Certificate
		INSERT #t SELECT a.id,2 FROM cvTraining a WITH(NOLOCK), cvTrainingpublish b WITH(NOLOCK) WHERE a.id = b.id AND a.Course <> b.Course
		INSERT #t SELECT a.id,3 FROM cvTraining a WITH(NOLOCK), cvTrainingpublish b WITH(NOLOCK) WHERE a.id = b.id AND a.Details <> b.Details
		INSERT #t SELECT a.id,4 FROM cvTraining a WITH(NOLOCK), cvTrainingpublish b WITH(NOLOCK) WHERE a.id = b.id AND a.Institution <> b.Institution
		UPDATE a SET a.Certificate = b.Certificate FROM cvTrainingpublish a, cvTraining b WHERE a.id = b.id AND a.id IN(SELECT id FROM #t WHERE col = 1)
		UPDATE a SET a.Course = b.Course FROM cvTrainingpublish a, cvTraining b WHERE a.id = b.id AND a.id IN(SELECT id FROM #t WHERE col = 2)
		UPDATE a SET a.Details = b.Details FROM cvTrainingpublish a, cvTraining b WHERE a.id = b.id AND a.id IN(SELECT id FROM #t WHERE col = 3)
		UPDATE a SET a.Institution = b.Institution FROM cvTrainingpublish a, cvTraining b WHERE a.id = b.id AND a.id IN(SELECT id FROM #t WHERE col = 4)

		TRUNCATE TABLE #t
		INSERT #t SELECT a.id,1 FROM cvEducation a WITH(NOLOCK), cvEducationpublish b WITH(NOLOCK) WHERE a.id = b.id AND a.dcMajorID <> b.dcMajorID
		INSERT #t SELECT a.id,2 FROM cvEducation a WITH(NOLOCK), cvEducationpublish b WITH(NOLOCK) WHERE a.id = b.id AND a.Degree <> b.Degree
		INSERT #t SELECT a.id,3 FROM cvEducation a WITH(NOLOCK), cvEducationpublish b WITH(NOLOCK) WHERE a.id = b.id AND a.Details <> b.Details
		INSERT #t SELECT a.id,4 FROM cvEducation a WITH(NOLOCK), cvEducationpublish b WITH(NOLOCK) WHERE a.id = b.id AND a.EduType <> b.EduType
		INSERT #t SELECT a.id,5 FROM cvEducation a WITH(NOLOCK), cvEducationpublish b WITH(NOLOCK) WHERE a.id = b.id AND a.GraduateCollage <> b.GraduateCollage
		INSERT #t SELECT a.id,6 FROM cvEducation a WITH(NOLOCK), cvEducationpublish b WITH(NOLOCK) WHERE a.id = b.id AND a.GraduateCollageEng <> b.GraduateCollageEng
		INSERT #t SELECT a.id,7 FROM cvEducation a WITH(NOLOCK), cvEducationpublish b WITH(NOLOCK) WHERE a.id = b.id AND a.Graduation <> b.Graduation
		INSERT #t SELECT a.id,8 FROM cvEducation a WITH(NOLOCK), cvEducationpublish b WITH(NOLOCK) WHERE a.id = b.id AND a.MajorName <> b.MajorName
		INSERT #t SELECT a.id,9 FROM cvEducation a WITH(NOLOCK), cvEducationpublish b WITH(NOLOCK) WHERE a.id = b.id AND a.MajorNameEng <> b.MajorNameEng
		UPDATE a SET a.dcMajorID = b.dcMajorID FROM cvEducationpublish a, cvEducation b WHERE a.id = b.id AND a.id IN(SELECT id FROM #t WHERE col = 1)
		UPDATE a SET a.Degree = b.Degree FROM cvEducationpublish a, cvEducation b WHERE a.id = b.id AND a.id IN(SELECT id FROM #t WHERE col = 2)
		UPDATE a SET a.Details = b.Details FROM cvEducationpublish a, cvEducation b WHERE a.id = b.id AND a.id IN(SELECT id FROM #t WHERE col = 3)
		UPDATE a SET a.EduType = b.EduType FROM cvEducationpublish a, cvEducation b WHERE a.id = b.id AND a.id IN(SELECT id FROM #t WHERE col = 4)
		UPDATE a SET a.GraduateCollage = b.GraduateCollage FROM cvEducationpublish a, cvEducation b WHERE a.id = b.id AND a.id IN(SELECT id FROM #t WHERE col = 5)
		UPDATE a SET a.GraduateCollageEng = b.GraduateCollageEng FROM cvEducationpublish a, cvEducation b WHERE a.id = b.id AND a.id IN(SELECT id FROM #t WHERE col = 6)
		UPDATE a SET a.Graduation = b.Graduation FROM cvEducationpublish a, cvEducation b WHERE a.id = b.id AND a.id IN(SELECT id FROM #t WHERE col = 7)
		UPDATE a SET a.MajorName = b.MajorName FROM cvEducationpublish a, cvEducation b WHERE a.id = b.id AND a.id IN(SELECT id FROM #t WHERE col = 8)
		UPDATE a SET a.MajorNameEng = b.MajorNameEng FROM cvEducationpublish a, cvEducation b WHERE a.id = b.id AND a.id IN(SELECT id FROM #t WHERE col = 9)

		TRUNCATE TABLE #t
		INSERT #t SELECT a.id,1 FROM cvExperience a WITH(NOLOCK), cvExperiencepublish b WITH(NOLOCK) WHERE a.id = b.id AND a.CompanyName <> b.CompanyName
		INSERT #t SELECT a.id,2 FROM cvExperience a WITH(NOLOCK), cvExperiencepublish b WITH(NOLOCK) WHERE a.id = b.id AND a.dcIndustryID <> b.dcIndustryID
		INSERT #t SELECT a.id,3 FROM cvExperience a WITH(NOLOCK), cvExperiencepublish b WITH(NOLOCK) WHERE a.id = b.id AND a.dcJobtypeID <> b.dcJobtypeID
		INSERT #t SELECT a.id,4 FROM cvExperience a WITH(NOLOCK), cvExperiencepublish b WITH(NOLOCK) WHERE a.id = b.id AND a.Description <> b.Description
		INSERT #t SELECT a.id,5 FROM cvExperience a WITH(NOLOCK), cvExperiencepublish b WITH(NOLOCK) WHERE a.id = b.id AND a.JobName <> b.JobName
		INSERT #t SELECT a.id,6 FROM cvExperience a WITH(NOLOCK), cvExperiencepublish b WITH(NOLOCK) WHERE a.id = b.id AND a.SubNodeNum <> b.SubNodeNum
		UPDATE a SET a.CompanyName = b.CompanyName FROM cvExperiencepublish a, cvExperience b WHERE a.id = b.id AND a.id IN(SELECT id FROM #t WHERE col = 1)
		UPDATE a SET a.dcIndustryID = b.dcIndustryID FROM cvExperiencepublish a, cvExperience b WHERE a.id = b.id AND a.id IN(SELECT id FROM #t WHERE col = 2)
		UPDATE a SET a.dcJobtypeID = b.dcJobtypeID FROM cvExperiencepublish a, cvExperience b WHERE a.id = b.id AND a.id IN(SELECT id FROM #t WHERE col = 3)
		UPDATE a SET a.Description = b.Description FROM cvExperiencepublish a, cvExperience b WHERE a.id = b.id AND a.id IN(SELECT id FROM #t WHERE col = 4)
		UPDATE a SET a.JobName = b.JobName FROM cvExperiencepublish a, cvExperience b WHERE a.id = b.id AND a.id IN(SELECT id FROM #t WHERE col = 5)
		UPDATE a SET a.SubNodeNum = b.SubNodeNum FROM cvExperiencepublish a, cvExperience b WHERE a.id = b.id AND a.id IN(SELECT id FROM #t WHERE col = 6)

		DELETE FROM cvIndustryPublish
		WHERE NOT EXISTS 
			(
			SELECT 'x' 
			FROM cvIndustry WITH(NOLOCK) 
			WHERE cvIndustry.cvMainID IN(SELECT ID FROM cvMainPublish WITH(NOLOCK))
			AND cvIndustry.cvMainID = cvIndustryPublish.cvMainID
			AND cvIndustry.dcIndustryId = cvIndustryPublish.dcIndustryId
			)

		INSERT cvIndustryPublish(cvMainId, dcIndustryID)
		SELECT cvMainId, dcIndustryID
		FROM cvIndustry WITH(NOLOCK)
		WHERE cvMainID IN(SELECT ID FROM cvMainPublish WITH(NOLOCK))
		AND NOT EXISTS 
			(
			SELECT 'x' 
			FROM cvIndustryPublish WITH(NOLOCK) 
			WHERE cvIndustry.cvMainID = cvIndustryPublish.cvMainID
			AND cvIndustry.dcIndustryId = cvIndustryPublish.dcIndustryId
			)

		DELETE FROM cvJobTypePublish
		WHERE NOT EXISTS 
			(
			SELECT 'x' 
			FROM cvJobType WITH(NOLOCK) 
			WHERE cvJobType.cvMainID IN(SELECT ID FROM cvMainPublish WITH(NOLOCK))
			AND cvJobType.cvMainID = cvJobTypePublish.cvMainID
			AND cvJobType.dcJobTypeId = cvJobTypePublish.dcJobTypeId
			)

		INSERT cvJobTypePublish(cvMainId, dcJobTypeId)
		SELECT * FROM cvJobType WITH(NOLOCK)
		WHERE cvMainID IN(SELECT ID FROM cvMainPublish WITH(NOLOCK))
		AND NOT EXISTS 
			(
			SELECT 'x' 
			FROM cvJobTypePublish WITH(NOLOCK) 
			WHERE cvJobType.cvMainID = cvJobTypePublish.cvMainID
			AND cvJobType.dcJobTypeId = cvJobTypePublish.dcJobTypeId
			)

		DELETE FROM cvJobPlacePublish
		WHERE NOT EXISTS 
			(
			SELECT 'x' 
			FROM cvJobPlace WITH(NOLOCK) 
			WHERE cvJobPlace.cvMainID IN(SELECT ID FROM cvMainPublish WITH(NOLOCK))
			AND cvJobPlace.cvMainID = cvJobPlacePublish.cvMainID
			AND cvJobPlace.dcRegionId = cvJobPlacePublish.dcRegionId
			)

		INSERT cvJobPlacePublish(cvMainId, dcRegionId)
		SELECT * FROM cvJobPlace WITH(NOLOCK)
		WHERE cvMainID IN(SELECT ID FROM cvMainPublish WITH(NOLOCK))
		AND NOT EXISTS 
			(
			SELECT 'x' 
			FROM cvJobPlacePublish WITH(NOLOCK) 
			WHERE cvJobPlace.cvMainID = cvJobPlacePublish.cvMainID
			AND cvJobPlace.dcRegionId = cvJobPlacePublish.dcRegionId
			)
	END
	
	DROP TABLE #t

	update b set b.secondid = a.secondid from cvmain a, cvmainpublish b where a.id=b.id and b.secondid is null
	update b set b.secondid = a.secondid from cvmain a, cvmainpublish b where a.id=b.id and b.secondid != a.secondid
END














GO
/****** Object:  StoredProcedure [dbo].[spPaRemindLogInsert]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2015.2.26
--创建人：Lambo
--说明：插入提醒信息
--#####################################################
CREATE PROCEDURE [dbo].[spPaRemindLogInsert]
AS
BEGIN 
	DELETE FROM PaAttention WHERE paMainid NOT IN(SELECT Id FROM paMain)
	--1 关注的企业新发布职位
	INSERT INTO PaRemindLog(PaMainID,Contenttext,RemindStatus,AddDate,RemainID,RemainType)
	SELECT PaMainID,'您关注的 '+b.Name+' 新发布'+(SELECT LTRIM(STR(COUNT(*))) FROM Job n WITH(NOLOCK) WHERE  n.CpMainID = b.ID AND n.IssueDate>a.AddDate AND n.IssueDate >GETDATE()-1 AND IsDelete=0)+'个职位，请及时登录查看…',
		0,GETDATE(),AttentionID,1
	FROM PaAttention a WITH(NOLOCK),CpMain b WITH(NOLOCK) 
	WHERE a.AttentionID = b.ID
	AND AttentionType =1 
	AND EXISTS(SELECT TOP 1 'x' FROM Job n WHERE  n.CpMainID = b.ID AND n.IssueEnd>a.AddDate AND n.IssueDate >GETDATE()-1 AND IsDelete=0)
	
	--2 关注的企业新发布点评
	INSERT INTO PaRemindLog(PaMainID,Contenttext,RemindStatus,AddDate,RemainID,RemainType)
	SELECT PaMainID,'您关注的 '+b.Name+' 新发布'+(SELECT LTRIM(STR(COUNT(*))) FROM comments m WITH(NOLOCK) 
		WHERE m.CpMainID = b.ID 
		AND m.VerifyDate>a.AddDate 
		AND m.CommentType <> 3
		AND m.VerifyDate >GETDATE()-1)+'条点评信息，请及时登录查看',
		0,GETDATE(),AttentionID,2
	FROM PaAttention a WITH(NOLOCK),CpMain b WITH(NOLOCK) 
	WHERE a.AttentionID = b.ID
	AND AttentionType =1 
	AND EXISTS(SELECT TOP 1 'x' FROM comments m WITH(NOLOCK) WHERE m.CpMainID = b.ID AND m.VerifyDate>a.AddDate AND m.CommentType <> 3 AND m.VerifyDate >GETDATE()-1)

	--3 关注的企业新发布面经
	INSERT INTO PaRemindLog(PaMainID,Contenttext,RemindStatus,AddDate,RemainID,RemainType)
	SELECT PaMainID,'您关注的 '+b.Name+' 新发布'+(SELECT LTRIM(STR(COUNT(*))) FROM InterView m WITH(NOLOCK) 
		WHERE m.CpMainID = b.ID 
		AND m.VerifyDate>a.AddDate 
		AND m.InterViewType <> 3
		AND m.VerifyDate >GETDATE()-1)+'条面经信息，请及时登录查看',
		0,GETDATE(),AttentionID,3
	FROM PaAttention a WITH(NOLOCK),CpMain b WITH(NOLOCK) 
	WHERE a.AttentionID = b.ID
	AND AttentionType =1 
	AND EXISTS(SELECT TOP 1 'x' FROM InterView m WITH(NOLOCK) WHERE m.CpMainID = b.ID AND m.InterViewType <> 3 AND m.VerifyDate>a.AddDate AND m.VerifyDate >GETDATE()-1)

	--4 职位24小时到期
	INSERT INTO PaRemindLog(PaMainID,Contenttext,RemindStatus,AddDate,RemainID,RemainType)
	SELECT a.ID,'您关注的职位中有'+(SELECT LTRIM(STR(COUNT(*))) FROM PaAttention m WITH(NOLOCK),Job n WITH(NOLOCK) WHERE m.AttentionID = n.ID AND m.AttentionType =2 AND m.PaMainID = a.ID AND n.IssueEnd BETWEEN GETDATE() AND GETDATE()+1 AND n.IsDelete = 0)+'职位即将截止，如果目前您还没有申请，请尽快完成申请。',
		0,GETDATE(),a.ID,4
	FROM PaMain a WITH(NOLOCK)
	WHERE EXISTS(SELECT TOP 1 'x' FROM PaAttention m WITH(NOLOCK),Job n WITH(NOLOCK) WHERE m.AttentionID = n.ID AND m.AttentionType =2 AND m.PaMainID = a.ID AND n.IssueEnd BETWEEN GETDATE() AND GETDATE()+1 AND n.IsDelete = 0)
END
GO
/****** Object:  StoredProcedure [dbo].[spPaYourFoodByPaJobCompareInsert]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：20160825
--创建人：Peter
--说明：新版你的菜儿推送
--#####################################################
CREATE PROCEDURE [dbo].[spPaYourFoodByPaJobCompareInsert]
AS
SET NOCOUNT ON
BEGIN
	INSERT INTO paYourFood(paMainId,cvMainId,JobId,AddDate)
	SELECT PaMainID,(
		SELECT TOP 1 ID 
		FROM CvMain WITH(NOLOCK) 
		WHERE PaMainID = PaJobCompare.PaMainID 
		ORDER BY Valid DESC),CompareJobID,GETDATE()
	FROM PaJobCompare WITH(NOLOCK)
	WHERE PushDate IS NULL
	AND BatchNo = (
		SELECT MAX(BatchNo) 
		FROM PaJobCompare WITH(NOLOCK) 
		WHERE PaMainID = PaJobCompare.PaMainID)
	
	UPDATE PaJobCompare
	SET PushDate = GETDATE()
	WHERE PushDate IS NULL
	AND BatchNo = (
		SELECT MAX(BatchNo) 
		FROM PaJobCompare WITH(NOLOCK) 
		WHERE PaMainID = PaJobCompare.PaMainID)
	
END
GO
/****** Object:  StoredProcedure [dbo].[sppaYourFoodInsert]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[sppaYourFoodInsert]
AS
RETURN
SET NOCOUNT ON
BEGIN
	IF EXISTS(SELECT 'x' FROM Oadb..WorkDate WHERE IsPaid = 1 AND WorkDate = CONVERT(VARCHAR(8), GETDATE(), 112))
		RETURN
	IF DATEPART(HOUR, GETDATE()) < 10
		RETURN
	DELETE FROM paYourFood WHERE AddDate < GETDATE() - 62
	DECLARE @ThisMonth INT
	SET @ThisMonth = CONVERT(VARCHAR(6), GETDATE(), 112)

	IF NOT EXISTS(SELECT 'x' FROM paYourFoodIndex WHERE AddDate > CONVERT(VARCHAR(10), GETDATE(), 120))
	BEGIN
		TRUNCATE TABLE paYourFoodIndex
		TRUNCATE TABLE paYourFoodWeiXin
		TRUNCATE TABLE ShortDB..paYourFoodEmail

		INSERT INTO paYourFoodIndex
		SELECT b.paMainId, b.Id cvMainId, a.LastLoginDate, (@ThisMonth - a.BirthDay) / 100 Age,
			b.dcSalaryID, b.EmployType, b.Degree, b.RelatedWorkYears, 0, GETDATE()
		FROM paMain a WITH(NOLOCK), cvMain b WITH(NOLOCK)
		WHERE a.LastLoginDate > CONVERT(VARCHAR(10),  GETDATE() - 14)
		AND a.Id = b.paMainId
		AND b.dcSalaryId IS NOT NULL
		AND a.BirthDay IS NOT NULL
		AND b.Degree IS NOT NULL
		AND b.RelatedWorkYears IS NOT NULL
		AND a.IsUseYourFood = 1
		AND (a.Id % 2 = DATEPART(Day, GETDATE()) % 2
			OR a.Id IN(SELECT paMainId FROM wxFans WHERE Status > 0)
			)
		ORDER BY b.paMainId DESC, b.Id DESC

		select distinct pamainid 
		into #tq from paloginlog
		where browser<>'weixin'
		and adddate > getdate() - 16
		delete from payourfoodindex where pamainid not in(select pamainid from #tq)
	END
	IF NOT EXISTS(SELECT 'x' FROM paYourFoodIndex WHERE AddDate > CONVERT(VARCHAR(10), GETDATE(), 120) AND HasRun = 0)
		RETURN
	CREATE TABLE #Job(
		Id INT,
		cpMainId INT,
		dcRegionId VARCHAR(6),
		dcJobTypeId VARCHAR(4),
		dcSalaryId INT,
		EmployType INT,
		dcEducationId INT,
		MinExperience INT,
		MinAge INT,
		MaxAge INT,
		AgeScore INT,
		EduScore INT,
		ExpScore INt,
		SizeScore INT
		)	
	DECLARE @paMainId INT, @CvMainID INT, @dcSalaryId INT, @EmployType INT, @Degree INT, @Exp INT, @Age INT, @Id INT
	DECLARE @JobPlace AS TABLE(Id INT IDENTITY(1, 1), dcRegionId VARCHAR(6))
	DECLARE @JobType AS TABLE(Id INT IDENTITY(1, 1), dcJobTypeId VARCHAR(4))
	DECLARE @t1 AS TABLE(dcRegionId VARCHAR(6))
	DECLARE @t2 AS TABLE(dcJobTypeId VARCHAR(4))

	SELECT @Id = 0
	WHILE EXISTS(SELECT 'x' FROM paYourFoodIndex WHERE HasRun = 0 AND Id > @Id)		--@id < 10
	BEGIN
		SELECT TOP 1 @id = Id, @cvMainId = cvMainId, @paMainId = paMainId, @Age = Age,
			 @dcSalaryId = dcSalaryID, @EmployType = EmployType, @Degree = Degree, @Exp = RelatedWorkYears
		FROM paYourFoodIndex 
		WHERE Id > @Id
		AND HasRun = 0
		ORDER BY Id
		
		DELETE FROM @JobPlace
		DELETE FROM @JobType
		DELETE FROM @t1
		DELETE FROM @t2

		INSERT INTO @JobPlace(dcRegionId)
		SELECT dcRegionId FROM cvJobPlace WITH(NOLOCK)
		WHERE cvMainId = @cvMainId

		INSERT INTO @JobType(dcJobTypeId)
		SELECT dcJobTypeId FROM cvJobType WITH(NOLOCK)
		WHERE cvMainId = @cvMainId

		DELETE a FROM @JobPlace a, @JobPlace b WHERE a.id <> b.Id AND a.dcRegionID <> b.dcRegionId AND b.dcRegionId LIKE a.dcRegionId + '%'
		DELETE a FROM @JobType a, @JobType b WHERE a.id <> b.Id AND a.dcJobTypeId <> b.dcJobTypeId AND b.dcJobTypeId LIKE a.dcJobTypeId + '%'
		INSERT INTO @t2 
		SELECT Id FROM dcJobType WHERE ID IN(SELECT dcJobTypeId FROM @JobType) OR ParentID IN(SELECT dcJobTypeId FROM @JobType)

		INSERT INTO @t1 SELECT Id FROM dcRegion WHERE ID IN(SELECT dcRegionId FROM @JobPlace) 
		INSERT INTO @t1 SELECT Id FROM dcRegion WHERE LEFT(ID, 4) IN(SELECT dcRegionId FROM @JobPlace)
		INSERT INTO @t1 SELECT Id FROM dcRegion WHERE LEFT(ID, 2) IN(SELECT dcRegionId FROM @JobPlace)
		--===========================================
		TRUNCATE TABLE #Job
		INSERT INTO #Job(Id, cpMainId, dcRegionId, dcJobTypeId, dcSalaryId, EmployType, dcEducationId, MinExperience, MinAge, MaxAge)
		SELECT TOP 200 Id, cpMainId, dcRegionId, dcJobTypeId, dcSalaryId, EmployType, dcEducationId, MinExperience, MinAge, MaxAge
		FROM jobPublish WITH(NOLOCK)
		WHERE EmployType = @EmployType
		AND dcRegionID IN(SELECT dcRegionId FROM @t1)
		AND dcJobTypeId IN(SELECT dcJobTypeId FROM @t2)
		AND dcSalaryId IN(100, @dcSalaryId)
		AND EXISTS(SELECT 'x' FROM cpMainPublish WITH(NOLOCK) WHERE LastLoginDate > GETDATE() - 31 AND cpMainPublish.Id = cpMainId)
		ORDER BY RefreshDate DESC

		DELETE #Job WHERE Id IN(SELECT JobId FROM paYourFood WITH(NOLOCK) WHERE paMainId = @pamainId)
		DELETE #Job WHERE Id IN(SELECT JobId FROM ExJobApply WITH(NOLOCK) WHERE cvMainID IN(SELECT ID FROM cvMain WITH(NOLOCK) WHERE paMainId = @pamainId))
		IF(SELECT COUNT(*) FROM #Job) > 3
		BEGIN			
			UPDATE a SET a.SizeScore = b.dcCompanySizeId * -1, EduScore = 0, AgeScore = 0, ExpScore = 0  FROM #Job a, cpMainPublish b WHERE a.cpMainId = b.ID
			UPDATE #Job SET EduScore = dcEducationId - @Degree WHERE dcEducationId > @Degree AND dcEducationId < 100
			UPDATE #Job SET EduScore = @Degree - dcEducationId WHERE dcEducationId < @Degree AND dcEducationId < 100
			UPDATE #Job SET MinAge = 16 WHERE MinAge = 99
			UPDATE #Job SET MaxAge = 60 WHERE MaxAge = 99
			UPDATE #Job SET AgeScore = (MinAge - @Age) / 5 + 1 WHERE MinAge > @Age
			UPDATE #Job SET AgeScore = (@Age - MaxAge) / 5 + 1 WHERE MaxAge < @Age
			IF @Exp = 0
				SET @Exp = 1
			ELSE IF @Exp IN(1, 2)
				SET @Exp = 2
			ELSE IF @Exp IN(3,4,5)
				SET @Exp = 3
			ELSE IF @Exp IN(6,7,8,9,10)
				SET @Exp = 4
			ELSE IF @Exp > 10
				SET @Exp = 5
			ELSE
				SET @Exp = 0
			UPDATE #Job SET MinExperience = CASE WHEN MinExperience = 5 THEN 1 ELSE MinExperience + 1 END WHERE MinExperience > 0
			UPDATE #Job SET ExpScore = MinExperience - @Exp WHERE MinExperience > @Exp
			UPDATE #Job SET ExpScore = @Exp - MinExperience WHERE MinExperience < @Exp AND MinExperience > 0	
		END
		INSERT INTO paYourFood(Jobid, paMainId, cvMainId, AddDate)
		SELECT TOP 3 Id, @paMainId, @cvMainId, GETDATE() FROM #job ORDER BY EduScore, ExpScore + SizeScore + AgeScore
		DELETE FROM paYourFood 
		WHERE paMainId = @PaMainId 
		AND AddDate > DATEADD(MINUTE, -10, GETDATE())
		AND Id NOT IN(SELECT TOP 3 ID FROM paYourFood WHERE paMainId = @PaMainId AND AddDate > DATEADD(MINUTE, -10, GETDATE()))

		UPDATE paYourFoodIndex SET HasRun = 1 WHERE Id = @Id
	END
	--=================================
	/*TRUNCATE TABLE paYourFoodWeiXin
	SELECT a.*, ROW_NUMBER() OVER(PARTITION BY paMainId ORDER BY JobId DESC) RowNo,
		b.Name JobName, c.Name CompanyName, b.caMainId, b.cpMainId
	INTO #t
	FROM paYourFood a, Job b, cpMain c
	WHERE a.AddDate > GETDATE() - 1
	AND a.JobId = b.Id
	AND b.cpMainid = c.Id
	AND a.paMainId IN(SELECT paMainId FROM wxFans WHERE Status > 0)

	INSERT INTO paYourFoodWeiXin(paMainId, cvMainId, JobDesc, cpMainId, caMainId)
	SELECT paMainId, cvMainId, '', cpMainId, caMainId
	FROM #t
	WHERE AddDate > GETDATE() - 1
	AND RowNo = 1

	UPDATE a
	SET a.JobDesc = b.JobName + '[' + b.CompanyName + ']'
	FROM paYourFoodWeiXin a, #t b
	WHERE a.paMainId = b.paMainId 
	AND b.RowNo = 1

	UPDATE a
	SET a.JobDesc = a.JobDesc + '、' + b.JobName + '[' + b.CompanyName + ']'
	FROM paYourFoodWeiXin a, #t b
	WHERE a.paMainId = b.paMainId 
	AND b.RowNo = 2

	UPDATE a
	SET a.JobDesc = a.JobDesc + '、' + b.JobName + '[' + b.CompanyName + ']'
	FROM paYourFoodWeiXin a, #t b
	WHERE a.paMainId = b.paMainId 
	AND b.RowNo = 3

	DELETE paYourFoodWeiXin WHERE ISNULL(JobDesc, '') = ''
	DROP TABLE #t
------------------------------
	TRUNCATE TABLE ShortDb..paYourFoodEmail
	SELECT a.*, ROW_NUMBER() OVER(PARTITION BY paMainId ORDER BY JobId DESC) RowNo,
		b.Name JobName, c.Name CompanyName, b.caMainId, b.cpMainId, b.SecondId JobId2, c.SecondId cpMainId2,
		(SELECT Description FROM dcRegion WHERE Id = b.dcRegionId) Region,
		ISNULL((SELECT Description FROM dcSalary WHERE Id = b.dcSalaryId), '面议') Salary,
		ISNULL((SELECT Description FROM dcEducation WHERE Id = b.dcEducationId), '不限') Education,
		(SELECT 'www.' + ProvinceDomain FROM dcProvince WHERE Id = LEFT(b.dcRegionId, 2)) SiteUrl
	INTO #TEmail
	FROM paYourFood a, Job b, cpMain c
	WHERE a.AddDate > GETDATE() - 1
	AND a.JobId = b.Id
	AND b.cpMainid = c.Id
 
	INSERT INTO paYourFoodEmail(paMainId, Email, paName, dcProvinceId, AddDate, UserName)
	SELECT b.Id, b.Email, b.Name, b.dcProvinceID, GETDATE(), b.UserNameLower
	FROM #TEmail a, paMain b
	WHERE a.RowNo = 1
	AND a.paMainId = b.Id
 
	SELECT paMainId, '
<table>
  <tr style="FONT-WEIGHT: bold; background-color:#f7b666;">
    <td>招聘职位</td>
    <td>公司名称</td>
    <td>工作地点</td>
    <td>职位月薪</td>
    <td>最低学历</td>
  </tr>
  <tr>
	<td><a target="_blank" href="http://' + SiteUrl + '/personal/jb' + JobId2 + '.html">' + JobName + '</a></td>
	<td><a target="_blank" href="http://' + SiteUrl + '/personal/cp' + cpMainId2 + '.html">' + CompanyName + '</a></td>
	<td>' + Region + '</td>
	<td>' + Salary + '</td>
	<td>' + Education + '</td>
  </tr>' JobList
	INTO #e1
	FROM #TEmail
	WHERE RowNo = 1

	SELECT paMainId, '
  <tr>
	<td><a target="_blank" href="http://' + SiteUrl + '/personal/jb' + JobId2 + '.html">' + JobName + '</a></td>
	<td><a target="_blank" href="http://' + SiteUrl + '/personal/cp' + cpMainId2 + '.html">' + CompanyName + '</a></td>
	<td>' + Region + '</td>
	<td>' + Salary + '</td>
	<td>' + Education + '</td>
  </tr>' JobList
	INTO #e2
	FROM #TEmail
	WHERE RowNo = 2

	SELECT paMainId, '
  <tr>
	<td><a target="_blank" href="http://' + SiteUrl + '/personal/jb' + JobId2 + '.html">' + JobName + '</a></td>
	<td><a target="_blank" href="http://' + SiteUrl + '/personal/cp' + cpMainId2 + '.html">' + CompanyName + '</a></td>
	<td>' + Region + '</td>
	<td>' + Salary + '</td>
	<td>' + Education + '</td>
  </tr>' JobList
	INTO #e3
	FROM #TEmail
	WHERE RowNo = 3

	SELECT a.paMainId, a.JobList + ISNULL(b.JobList, '') + ISNULL(c.JobList, '') + '
</table>' JobList
	INTO #e4
	FROM #e1 a
	LEFT JOIN #e2 b on a.pamainid = b.pamainid
	LEFT JOIN #e3 c on a.pamainid = c.pamainid

	UPDATE a
	SET a.JobList = b.JobList
	FROM paYourFoodEmail a, #e4 b
	WHERE a.paMainId = b.paMainId

	DROP TABLE #TEmail
*/
END

GO
/****** Object:  StoredProcedure [dbo].[spPaYourFoodWeixinInsert]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[spPaYourFoodWeixinInsert]
AS
SET NOCOUNT ON
BEGIN
	IF DATEPART(HOUR, GETDATE()) < 17
		RETURN

	IF NOT EXISTS(SELECT 'x' FROM paYourFoodWeiXin WHERE AddDate > CONVERT(VARCHAR(10), GETDATE(), 120))
		TRUNCATE TABLE paYourFoodWeiXin
	IF NOT EXISTS(SELECT 'x' FROM paYourFoodEmail WHERE AddDate > CONVERT(VARCHAR(10), GETDATE(), 120))
		TRUNCATE TABLE ShortDb..paYourFoodEmail

	SELECT a.*, ROW_NUMBER() OVER(PARTITION BY paMainId ORDER BY CompareJobId DESC) RowNo,
		b.Name JobName, c.Name CompanyName, b.caMainId, b.cpMainId
	INTO #t
	FROM PaJobCompare a, Job b, cpMain c
	WHERE a.AddDate > CONVERT(VARCHAR(10), GETDATE(), 120)
	AND a.PushDate IS NULL
	AND a.CompareJobId = b.Id
	AND b.cpMainid = c.Id
	AND a.paMainId IN(SELECT paMainId FROM wxFans WHERE Status > 0)
	AND a.paMainId IN(SELECT Id FROM paMain WHERE IsUseYourFood = 1)

	INSERT INTO paYourFoodWeiXin(paMainId, cvMainId, JobDesc, cpMainId, caMainId,BatchNo)
	SELECT paMainId,(
		SELECT TOP 1 ID 
		FROM CvMain WITH(NOLOCK) 
		WHERE PaMainID = #t.PaMainID 
		ORDER BY Valid DESC), '', cpMainId, caMainId,BatchNo
	FROM #t
	WHERE AddDate > CONVERT(VARCHAR(10), GETDATE(), 120)
	AND RowNo = 1
	
	UPDATE PaJobCompare
	SET PushDate = GETDATE()
	WHERE EXISTS(
		SELECT 'x' FROM #t WHERE ID = PaJobCompare.ID
	)

	UPDATE a
	SET a.JobDesc = b.JobName + '[' + b.CompanyName + ']'
	FROM paYourFoodWeiXin a, #t b
	WHERE a.paMainId = b.paMainId 
	AND b.RowNo = 1
	
	UPDATE a
	SET a.JobDesc = a.JobDesc + '、' + b.JobName + '[' + b.CompanyName + ']'
	FROM paYourFoodWeiXin a, #t b
	WHERE a.paMainId = b.paMainId 
	AND b.RowNo = 2

	UPDATE a
	SET a.JobDesc = a.JobDesc + '、' + b.JobName + '[' + b.CompanyName + ']'
	FROM paYourFoodWeiXin a, #t b
	WHERE a.paMainId = b.paMainId 
	AND b.RowNo = 3

	DELETE paYourFoodWeiXin WHERE ISNULL(JobDesc, '') = ''
	DROP TABLE #t

	------------------------------
	SELECT a.*, ROW_NUMBER() OVER(PARTITION BY paMainId ORDER BY CompareJobId DESC) RowNo,
		b.Name JobName, c.Name CompanyName, b.caMainId, b.cpMainId, b.SecondId JobId2, c.SecondId cpMainId2,
		(SELECT Description FROM dcRegion WHERE Id = b.dcRegionId) Region,
		ISNULL((SELECT Description FROM dcSalary WHERE Id = b.dcSalaryId), '面议') Salary,
		ISNULL((SELECT Description FROM dcEducation WHERE Id = b.dcEducationId), '不限') Education,
		(SELECT 'www.' + ProvinceDomain FROM dcProvince WHERE Id = LEFT(b.dcRegionId, 2)) SiteUrl
	INTO #TEmail
	FROM PaJobCompare a, Job b, cpMain c
	WHERE a.AddDate > CONVERT(VARCHAR(10), GETDATE(), 120)
	AND a.PushDate IS NULL
	AND a.CompareJobId = b.Id
	AND b.cpMainid = c.Id
 
	INSERT INTO paYourFoodEmail(paMainId, Email, paName, dcProvinceId, AddDate, UserName)
	SELECT b.Id, b.Email, b.Name, b.dcProvinceID, GETDATE(), b.UserNameLower
	FROM #TEmail a, paMain b
	WHERE a.RowNo = 1
	AND a.paMainId = b.Id
 
	UPDATE PaJobCompare
	SET PushDate = GETDATE()
	WHERE EXISTS(
		SELECT 'x' FROM #TEmail WHERE ID = PaJobCompare.ID
	)
	 
	SELECT paMainId, '
<table>
  <tr style="FONT-WEIGHT: bold; background-color:#f7b666;">
    <td>招聘职位</td>
    <td>公司名称</td>
    <td>工作地点</td>
    <td>职位月薪</td>
    <td>最低学历</td>
  </tr>
  <tr>
	<td><a target="_blank" href="http://' + SiteUrl + '/personal/jb' + JobId2 + '.html">' + JobName + '</a></td>
	<td><a target="_blank" href="http://' + SiteUrl + '/personal/cp' + cpMainId2 + '.html">' + CompanyName + '</a></td>
	<td>' + Region + '</td>
	<td>' + Salary + '</td>
	<td>' + Education + '</td>
  </tr>' JobList
	INTO #e1
	FROM #TEmail
	WHERE RowNo = 1

	SELECT paMainId, '
  <tr>
	<td><a target="_blank" href="http://' + SiteUrl + '/personal/jb' + JobId2 + '.html">' + JobName + '</a></td>
	<td><a target="_blank" href="http://' + SiteUrl + '/personal/cp' + cpMainId2 + '.html">' + CompanyName + '</a></td>
	<td>' + Region + '</td>
	<td>' + Salary + '</td>
	<td>' + Education + '</td>
  </tr>' JobList
	INTO #e2
	FROM #TEmail
	WHERE RowNo = 2

	SELECT paMainId, '
  <tr>
	<td><a target="_blank" href="http://' + SiteUrl + '/personal/jb' + JobId2 + '.html">' + JobName + '</a></td>
	<td><a target="_blank" href="http://' + SiteUrl + '/personal/cp' + cpMainId2 + '.html">' + CompanyName + '</a></td>
	<td>' + Region + '</td>
	<td>' + Salary + '</td>
	<td>' + Education + '</td>
  </tr>' JobList
	INTO #e3
	FROM #TEmail
	WHERE RowNo = 3

	SELECT a.paMainId, a.JobList + ISNULL(b.JobList, '') + ISNULL(c.JobList, '') + '
</table>' JobList
	INTO #e4
	FROM #e1 a
	LEFT JOIN #e2 b on a.pamainid = b.pamainid
	LEFT JOIN #e3 c on a.pamainid = c.pamainid

	UPDATE a
	SET a.JobList = b.JobList
	FROM paYourFoodEmail a, #e4 b
	WHERE a.paMainId = b.paMainId

	DROP TABLE #TEmail
END

GO
/****** Object:  StoredProcedure [dbo].[SpQlrcNewsNearSave]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[SpQlrcNewsNearSave]
AS
SET NOCOUNT ON
BEGIN
	SELECT VersionId, id, Title, ROW_NUMBER() OVER(PARTITION BY VersionId ORDER BY Id) RowNo
	INTO #t
	FROM QlrcNews WITH(NOLOCK)
	WHERE NewsType = 2 
	AND Id > 1

	CREATE TABLE #Tmp(VersionId INT, Id INT, NearId INT, NearTitle NVARCHAR(60), RowNo INT, NearRowNo INT, PageType INT)

	INSERT INTO #Tmp
	SELECT a.VersionId, a.Id, b.ID, b.Title, a.RowNo, b.RowNo, 2
	FROM #t a, #t b
	WHERE a.VersionId = b.VersionId
	AND a.RowNo = b.RowNo + 1

	INSERT INTO #Tmp
	SELECT a.VersionId, a.Id, b.ID, b.Title, a.RowNo, b.RowNo, 1
	FROM #t a, #t b
	WHERE a.VersionId = b.VersionId
	AND a.RowNo = b.RowNo - 1

	SELECT * INTO #Tmp1 FROM #Tmp

	DELETE a
	FROM #Tmp1 a, ShortDb..QlrcNewsNear b
	WHERE a.Id = b.Id
	AND a.NearId = b.NearId
	AND a.PageType = b.PageType

	SELECT * INTO #News FROM #Tmp WHERE ID IN(SELECT ID FROM #Tmp1)

	DELETE FROM ShortDb..QlrcNewsNear WHERE Id IN(SELECT ID FROM #News)

	INSERT INTO ShortDb..QlrcNewsNear
	SELECT Id, PageType, NearId, NearTitle FROM #News
END

GO
/****** Object:  StoredProcedure [dbo].[spReceiveOrder]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create proc [dbo].[spReceiveOrder]
(
	@caOrderID INT,
	@ReceiveMan INT
)
AS
SET NOCOUNT ON
BEGIN
	UPDATE caOrder SET ReceiveDate = GETDATE(), ReceiveMan = @receiveMan WHERE Id = @caOrderId
	SELECT ReceiveDate, REceiveMAn, * FROM caOrder WHERE Id = @caOrderId
END

GO
/****** Object:  StoredProcedure [dbo].[spReCheckVipMember]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[spReCheckVipMember]
AS
BEGIN
	DECLARE @ID AS INT
	DECLARE c CURSOR FOR
	SELECT id FROM cpMain WITH(NOLOCK)
	WHERE MemberType = 2
	AND Id IN(
		SELECT cpMainId FROM caORder WITH(NOLOCK)
		WHERE OpenDate > ''
		AND OrderType = 8
		AND IsDeleted = 0
		AND BeginDate < GETDATE()
		AND EndDate > GETDATE()
		)
	FOR READ ONLY

	OPEN c 
	FETCH c INTO @ID

	WHILE @@fetch_status >= 0
	BEGIN
		EXEC spRedifinePrivilage @ID
		FETCH NEXT FROM c INTO @ID
	END
	CLOSE c
	DEALLOCATE c
END














GO
/****** Object:  StoredProcedure [dbo].[spRedifinePrivilage]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--######################################################3
--cpMain权限检查
--1、JobNumber不超标
--2、Count(Valid caMain) 不超标
--3、修改MemberType， MaxJobNumber，MaxUserNumber
--说明：
--资料不完整	MemberType=0	职位数=0	用户数=1
--未认证会员	MemberType=1	职位数=5， 用户数=1
--普通会员		MemberType=2	职位数=10， 用户数=1
--贵宾会员		MemberType=3	职位数=SUM(caOrder.JobNumber)， 用户数=SUM(caOrder.UserNumber)
--无限制会员	MemberType=10	职位数=cpMain.MaxJobNumber， 用户数=cpMain.MaxUserNumber
--储值会员		MemberType=11	职位数=cpMain.MaxJobNumber， 用户数=cpMain.MaxUserNumber
--######################################################3
CREATE PROCEDURE [dbo].[spRedifinePrivilage]
(
	@cpMainID INT
)
AS
BEGIN TRY
	SET NOCOUNT ON;
	DECLARE @MemberType AS INT, @MaxJobNumber AS INT, @MaxUserNumber AS INT, @ExceedNumber AS INT, @JobNumber AS INT
	DECLARE @I AS INT, @ActiveUserNumber AS INT, @DailyGiftQuota AS INT
	
	SET @MemberType = dbo.GetMemberTypeWithRealName(@cpMainID)

	IF @MemberType = 0				--资料不完整	MemberType=0	职位数=0	用户数=1
	BEGIN
		SET @MaxJobNumber = 0
		SET @MaxUserNumber = 1
		SET @DailyGiftQuota = 0
	END
	ELSE IF @MemberType = 1			--未认证会员	MemberType=1	职位数=1， 用户数=1
	BEGIN
		SET @MaxJobNumber = 3
		SET @MaxUserNumber = 1
		SET @DailyGiftQuota = 0
	END
	ELSE IF @MemberType = 2			--普通会员	realname = 1	MemberType=2	职位数=3， 用户数=1
	BEGIN
		SET @MaxJobNumber = 5
		SET @MaxUserNumber = 1
		SET @DailyGiftQuota = 2
	END
	ELSE IF @MemberType = 21			--普通会员		MemberType=2	职位数=3， 用户数=1
	BEGIN
		SET @MaxJobNumber = 10
		SET @MaxUserNumber = 1
		SET @DailyGiftQuota = 4
	END
	ELSE IF @MemberType = 3			--贵宾会员		MemberType=3	职位数=SUM(caOrder.JobNumber)， 用户数=SUM(caOrder.UserNumber)
	BEGIN
		SET @MaxJobNumber = dbo.VipJobNumber(@cpMainID)
		SET @MaxUserNumber = dbo.VipUserNumber(@cpMainID)
		IF EXISTS (SELECT 'x' FROM caOrder WITH(NOLOCK) 
			WHERE cpMainId = @cpMainID AND OrderType = 8 
			AND ID < 412870
			AND GETDATE() BETWEEN BeginDate AND EndDate)
			SET @DailyGiftQuota = 5
		ELSE
			SET @DailyGiftQuota = 2
	END
	ELSE IF @MemberType = 31			--贵宾会员		MemberType=3	职位数=SUM(caOrder.JobNumber)， 用户数=SUM(caOrder.UserNumber)
	BEGIN
		SET @MaxJobNumber = dbo.VipJobNumber(@cpMainID)
		SET @MaxUserNumber = dbo.VipUserNumber(@cpMainID)
		IF EXISTS (SELECT 'x' FROM caOrder WITH(NOLOCK) 
			WHERE cpMainId = @cpMainID AND OrderType = 8 
			AND ID < 412870
			AND GETDATE() BETWEEN BeginDate AND EndDate)
			SET @DailyGiftQuota = 5
		ELSE
			SET @DailyGiftQuota = 4
	END
	/*ELSE		--无限制、储值会员	MemberType=10	职位数=cpMain.MaxJobNumber， 用户数=cpMain.MaxUserNumber
	BEGIN
		SELECT @MaxJobNumber = MaxJobNumber, @MaxUserNumber = MaxUserNumber
		FROM cpMain WITH(NOLOCK)
		WHERE ID = @cpMainID
		SET @DailyGiftQuota = 0
		IF @MaxJobNumber < 15
			SELECT @MaxJobNumber = 15
	END
	*/
	----如果活动的的用户数大于最大用户数量，则自动停止超出的用户，停止建立时间最晚的非管理员用户
	WHILE (SELECT COUNT(1) FROM caMain WITH(NOLOCK)
			WHERE cpMainID = @cpMainID AND IsDelete = 0 AND IsPause = 0) > @MaxUserNumber
	BEGIN
		UPDATE caMain SET IsPause = 1		--一个一个的停止
		WHERE ID IN(SELECT TOP 1 ID
			FROM caMain WITH(NOLOCK)
			WHERE cpMainID = @cpMainID
			AND IsPause = 0
			AND IsDelete = 0
			AND AccountType = 2
			ORDER BY ID DESC)
	END

	UPDATE Job SET Valid = 0, IssueEnd = DATEADD(MINUTE, -1, GETDATE())
	WHERE cpMainID = @cpMainID
	AND caMainID IN(SELECT Id FROM caMain WITH(NOLOCK) WHERE IsDelete = 1 OR IsPause =1 AND cpMainID = @cpMainID)
	AND (Valid = 1 OR IssueEnd > GETDATE())
	
	SELECT @ActiveUserNumber = COUNT(1)
	FROM caMain WITH(NOLOCK)
	WHERE cpMainID = @cpMainID AND IsDelete = 0 AND IsPause = 0

	----如果已经发布的职位数大于最大职位数量，则自动停止超出的职位数，停止发布时间最早的
	DECLARE @ID AS INT
	DECLARE @IssueEnd AS SMALLDATETIME
	DECLARE @IssueDate AS SMALLDATETIME

	WHILE (SELECT COUNT(1)
			FROM Job WITH(NOLOCK)
			WHERE cpMainID = @cpMainID AND IssueEnd > GETDATE() AND IsDelete = 0) > @MaxJobNumber
	BEGIN
		--一个一个的停止
		SELECT TOP 1 @ID = ID, @IssueDate = IssueDate, @IssueEnd = IssueEnd FROM Job WITH(NOLOCK)
		WHERE cpMainID = @cpMainID
		AND IssueEnd > GETDATE()
		AND IsDelete = 0
		ORDER BY IssueDate, ID

		UPDATE Job SET IssueDate = CASE WHEN IssueDate > DATEADD(MINUTE, -1, GETDATE()) THEN DATEADD(MINUTE, -1, GETDATE()) ELSE IssueDate END, 
			IssueEnd = DATEADD(MINUTE, -1, GETDATE()), Valid = 0
		WHERE ID = @ID
	END

	SELECT @JobNumber = COUNT(1)
	FROM Job WITH(NOLOCK)
	WHERE cpMainID = @cpMainID AND Valid = 1

	IF @MemberType = 21
		SET @MemberType = 2
	IF @MemberType = 31
		SET @MemberType = 3

	UPDATE cpMain
	SET MemberType = @MemberType, 
		MaxUserNumber = @MaxUserNumber,
		MaxJobNumber = @MaxJobNumber,
		JobNumber = @JobNumber,
		DailyGiftQuota = @DailyGiftQuota
	WHERE ID = @cpMainID
	AND (MemberType <> @MemberType
		OR MaxUserNumber <> @MaxUserNumber
		OR MaxJobNumber <> @MaxJobNumber
		OR JobNumber <> @JobNumber
	)

	UPDATE cpMainPublish
	SET MemberType = @MemberType
	WHERE ID = @cpMainID
	AND MemberType <> @MemberType
END TRY
BEGIN CATCH
END CATCH
GO
/****** Object:  StoredProcedure [dbo].[spRedifinePrivilage2]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[spRedifinePrivilage2]
(
	@cpMainID INT
)
AS
return
BEGIN TRY
	SET NOCOUNT ON;
	DECLARE @MemberType AS INT, @MaxJobNumber AS INT, @MaxUserNumber AS INT, @ExceedNumber AS INT, @JobNumber AS INT
	DECLARE @I AS INT, @ActiveUserNumber AS INT, @DailyGiftQuota AS INT
	
	SET @MemberType = dbo.MemberType(@cpMainID)

	IF @MemberType = 0				--资料不完整	MemberType=0	职位数=0	用户数=1
	BEGIN
		SET @MaxJobNumber = 0
		SET @MaxUserNumber = 1
		SET @DailyGiftQuota = 0
	END
	ELSE IF @MemberType = 1			--未认证会员	MemberType=1	职位数=1， 用户数=1
	BEGIN
		SET @MaxJobNumber = 5
		SET @MaxUserNumber = 1
		SET @DailyGiftQuota = 0
	END
	ELSE IF @MemberType = 2			--普通会员		MemberType=2	职位数=3， 用户数=1
	BEGIN
		SET @MaxJobNumber = 10
		SET @MaxUserNumber = 1
		SET @DailyGiftQuota = 2
	END
	ELSE IF @MemberType = 3			--贵宾会员		MemberType=3	职位数=SUM(caOrder.JobNumber)， 用户数=SUM(caOrder.UserNumber)
	BEGIN
		SET @MaxJobNumber = dbo.VipJobNumber(@cpMainID)
		SET @MaxUserNumber = dbo.VipUserNumber(@cpMainID)
		IF EXISTS (SELECT 'x' FROM caOrder WITH(NOLOCK) 
			WHERE cpMainId = @cpMainID AND OrderType = 8 
			AND ID < 412870
			AND GETDATE() BETWEEN BeginDate AND EndDate)
			SET @DailyGiftQuota = 5
		ELSE
			SET @DailyGiftQuota = 2
	END
	/*ELSE		--无限制、储值会员	MemberType=10	职位数=cpMain.MaxJobNumber， 用户数=cpMain.MaxUserNumber
	BEGIN
		SELECT @MaxJobNumber = MaxJobNumber, @MaxUserNumber = MaxUserNumber
		FROM cpMain WITH(NOLOCK)
		WHERE ID = @cpMainID
		SET @DailyGiftQuota = 0
		IF @MaxJobNumber < 15
			SELECT @MaxJobNumber = 15
	END
	*/
	----如果活动的的用户数大于最大用户数量，则自动停止超出的用户，停止建立时间最晚的非管理员用户
	WHILE (SELECT COUNT(1)	FROM caMain WITH(NOLOCK)
			WHERE cpMainID = @cpMainID AND IsDelete = 0 AND IsPause = 0) > @MaxUserNumber
	BEGIN
		UPDATE caMain SET IsPause = 1		--一个一个的停止
		WHERE ID IN(SELECT TOP 1 ID
			FROM caMain WITH(NOLOCK)
			WHERE cpMainID = @cpMainID
			AND IsPause = 0
			AND IsDelete = 0
			AND AccountType = 2
			ORDER BY ID DESC)

	END
	UPDATE Job SET Valid = 0, IssueEnd = DATEADD(MINUTE, -1, GETDATE())
	WHERE cpMainID = @cpMainID
	AND caMainID IN(SELECT Id FROM caMain WITH(NOLOCK) WHERE IsDelete = 1 OR IsPause =1 AND cpMainID = @cpMainID)
	
	SELECT @ActiveUserNumber = COUNT(1)
	FROM caMain WITH(NOLOCK)
	WHERE cpMainID = @cpMainID AND IsDelete = 0 AND IsPause = 0

	----如果已经发布的职位数大于最大职位数量，则自动停止超出的职位数，停止发布时间最早的
	DECLARE @ID AS INT
	DECLARE @IssueEnd AS SMALLDATETIME
	DECLARE @IssueDate AS SMALLDATETIME

	WHILE (SELECT COUNT(1)
			FROM Job WITH(NOLOCK)
			WHERE cpMainID = @cpMainID AND IssueEnd > GETDATE() AND IsDelete = 0) > @MaxJobNumber
	BEGIN
		--一个一个的停止
		SELECT TOP 1 @ID = ID, @IssueDate = IssueDate, @IssueEnd = IssueEnd FROM Job WITH(NOLOCK)
		WHERE cpMainID = @cpMainID
		AND IssueEnd > GETDATE()
		AND IsDelete = 0
		ORDER BY IssueDate, ID

		UPDATE Job SET IssueDate = CASE WHEN IssueDate > DATEADD(MINUTE, -1, GETDATE()) THEN DATEADD(MINUTE, -1, GETDATE()) ELSE IssueDate END, 
			IssueEnd = DATEADD(MINUTE, -1, GETDATE()), Valid = 0
		WHERE ID = @ID
	END

	SELECT @JobNumber = COUNT(1)
	FROM Job WITH(NOLOCK)
	WHERE cpMainID = @cpMainID AND Valid = 1

	UPDATE cpMain
	SET MemberType = @MemberType, 
		MaxUserNumber = @MaxUserNumber,
		MaxJobNumber = @MaxJobNumber,
		JobNumber = @JobNumber,
		DailyGiftQuota = @DailyGiftQuota
	WHERE ID = @cpMainID
	AND (MemberType <> @MemberType
		OR MaxUserNumber <> @MaxUserNumber
		OR MaxJobNumber <> @MaxJobNumber
		OR JobNumber <> @JobNumber
	)

	UPDATE cpMainPublish
	SET MemberType = @MemberType
	WHERE ID = @cpMainID
	AND MemberType <> @MemberType
END TRY
BEGIN CATCH
END CATCH














GO
/****** Object:  StoredProcedure [dbo].[spRemoveBr]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[spRemoveBr]
(
	@Table VARCHAR(100),
	@Column VARCHAR(100)
)
AS
BEGIN
	DECLARE @sql AS VARCHAR(MAX)
	SELECT @Sql = 'UPDATE ' + @Table + ' SET ' + @Column + ' = dbo.Removebr(' + @Column +')
WHERE ' + @Column + ' LIKE ''%<br>%''
OR ' + @Column + ' LIKE ''%&nbsp;%'''
	EXEC(@Sql)
END














GO
/****** Object:  StoredProcedure [dbo].[spSalaryByCountSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[spSalaryByCountSelect]
AS
SET NOCOUNT ON
BEGIN
	CREATE TABLE #s(Id int, Salary INT)
	INSERT INTO #s SELECT 1, 750
	INSERT INTO #s SELECT 2, 1250
	INSERT INTO #s SELECT 3, 1750
	INSERT INTO #s SELECT 4, 2500
	INSERT INTO #s SELECT 5, 3500
	INSERT INTO #s SELECT 6, 4500
	INSERT INTO #s SELECT 7, 5500
	INSERT INTO #s SELECT 8, 7000
	INSERT INTO #s SELECT 9, 9000
	INSERT INTO #s SELECT 10, 12500
	INSERT INTO #s SELECT 11, 17500
	INSERT INTO #s SELECT 12, 22500

	SELECT SPACE(60) Region, dcRegionId, dcSalaryID, 99999 Salary INTO #t FROM JobPublish WITH(NOLOCK) WHERE dcREgionId LIKE '32____'
	DELETE FROM #t WHERE dcSalaryId > 12
	UPDATE a SET a.Salary = b.Salary FROM #t a, #s b WHERE a.dcSalaryId = b.ID
	UPDATE a SET a.Region = b.FullName FROM #t a, dcRegion b WHERE a.dcRegionId = b.ID
	SELECT Region, Avg(Salary) FROM #t GROUP BY Region ORDER BY Avg(Salary) DESC

END

GO
/****** Object:  StoredProcedure [dbo].[spSchMailPrev3Insert]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
-- sean 2016-10-21
*/
CREATE PROCEDURE [dbo].[spSchMailPrev3Insert]
AS
SET NOCOUNT ON
BEGIN
	IF ISNULL((SELECT TOP 1 CONVERT(VARCHAR(8), AddDate, 112) FROM schMailPrev3), '') = CONVERT(VARCHAR(8), GETDATE(), 112)
		RETURN

	TRUNCATE TABLE schMailPrev3
	
	--需要推荐简历的职位
	CREATE TABLE #caSend(CaMainID INT)
	
	DECLARE @t AS TABLE(EMailSendFreq INT)
	DECLARE @num INT
	SET @Num = 0
	WHILE @Num < 128
	BEGIN
		SET @Num = @Num + 1
		IF SUBSTRING(RIGHT('0000000' + dbo.Int2Bin(@Num), 7), DATEPART(WEEKDAY, GETDATE() - 1), 1) = '1'
			INSERT INTO @t SELECT @Num
	END
	
	INSERT INTO #caSend
	SELECT DISTINCT caMainID 
	FROM Job WITH(NOLOCK)
	WHERE EMailSendFreq IN(SELECT EMailSendFreq FROM @t)
	AND valid = 1
	AND cpMainId IN(SELECT ID FROM cpMain WHERE IsLimitLogin < 9)
	
	INSERT INTO schMailPrev3
	SELECT 1,ISNULL(c.dcProvinceID,0),a.caMainID,ISNULL(b.Name,''),ISNULL(b.UserName,''),ISNULL(b.cpMainID,0),ISNULL(b.Name,'')+'您好，您发布的职位推荐简历',0,CASE LEN(c.dcsubsiteid) WHEN 2 THEN '' ELSE ISNULL(d.eMailsite,'') END,ISNULL(b.EMail,''),ISNULL(d.SubsiteName,''),NULL,0,GETDATE(),NULL,NULL,NULL,c.dcRegionID,NULL,NULL
	FROM #caSend a
	LEFT JOIN caMain b WITH(NOLOCK) ON b.id = a.caMainID
	LEFT JOIN cpMain c WITH(NOLOCK) ON c.id = b.cpMainID
	LEFT JOIN dcSubsite d WITH(NOLOCK) ON d.id = c.dcSubsiteID
	
	DELETE FROM schMailPrev3 WHERE EMail LIKE '%qq.com'

	SELECT ResumeId cvMainId, paMainId, SecondId, LastLoginDate, '
  <tr>
	<td>' + ISNULL( Name, ' ') + '[<a href="http://##SiteUrl##/Company/resume/cvview?id=##ResumeNo##" target="_blank">##ResumeNo##</a>]</td>
	<td>' + (CASE ISNULL( Sex, 0) WHEN 0 THEN '男' WHEN 1 THEN '女' END) + '</td>
	<td>' + CONVERT(VARCHAR, ISNULL( Age, 30)) + '</td>
	<td>' + ISNULL( JobType, ' ') + '</td>
	<td>' + ISNULL( AtPlaceDesc, ' ') + '</td>
  </tr>' MailText
	INTO #cvMail
	FROM caJobResumePre WITH(NOLOCK)
	WHERE ResumeId IN(SELECT MatchCvMainId FROM caJobCvMatch WITH(NOLOCK) WHERE PushDate IS NULL)
	AND AddDate > GETDATE() - 7

	--drop #JobMail
	CREATE TABLE #JobMail(caMainId INT, JobId INT, MailText NVARCHAR(MAX), JobName NVARCHAR(50), SecondId VARCHAR(12))
	CREATE TABLE #JobTemp(JobId INT, cvMainId INT, LastLoginDate DATETIME, JobName NVARCHAR(50), SecondId VARCHAR(12), cvText NVARCHAR(MAX), paMainId VARCHAR(10), cvSecondId VARCHAR(10), cpMainId VARCHAR(10), RegisterIp VARCHAR(39))
	CREATE TABLE #caMail(caMainId INT, MailBody NVARCHAR(MAX))

	INSERT INTO #JobTemp(JobId, cvMainId, LastLoginDate, cvText, paMainId, cvSecondId)
	SELECT a.JobId, b.cvMainId, b.LastLoginDate, b.MailText, b.paMainId, b.SecondId
	FROM caJobCvMatch a, #cvMail b
	WHERE a.MatchCvMainId = b.cvMainId	
	AND a.AddDate > GETDATE() - 7
	AND a.PushDate IS NULL

	DELETE #JobTemp WHERE JobId IN(SELECT Id FROM Job WHERE Valid = 0)
	DELETE #JobTemp WHERE JobId IN(SELECT Id FROM Job WHERE caMainId IN(SELECT ID FROM CaMain WHERE EMail LIKE '%qq.com'))
	UPDATE a SET a.cpMainId = b.cpMainId FROM #JobTemp a, Job b WHERE a.JobId = b.Id
	UPDATE a SET a.RegisterIp = b.RegisterIp FROM #JobTemp a, cpMain b WHERE a.cpMainId = b.Id
	UPDATE #JobTemp SET cvText = REPLACE(cvText, '##ResumeNo##', LOWER(cvSecondId + SUBSTRING(SYS.Fn_VarbinToHexStr(HASHBYTES('SHA1', paMainId + '-' + cpMainId + '#' + RegisterIp + '*')), 13, 10)))

	INSERT #JobMail(JobId, MailText)
	SELECT a.JobId, MailText = STUFF((SELECT '<aa>' + b.cvText + '<aa>' FROM #JobTemp b WHERE a.JobId = b.JobId ORDER BY b.LastLoginDate DESC FOR XML PATH('')), 1, 0, '')
	FROM #JobTemp a
	GROUP BY a.JobId

	--UPDATE #JobMail SET MailText = REPLACE(REPLACE(REPLACE(MailText, '&lt;aa&gt;', ''), '&lt;', '<'), '&gt;', '')
	UPDATE a SET a.caMainId = b.caMainId, a.JobName = b.Name, a.SecondId = b.SecondId FROM #JobMail a, Job b WHERE a.JobId = b.Id
	UPDATE #JobMail SET MailText = '
  <tr>
	<td colspan = "5" style="FONT-WEIGHT: bold; background-color:#ff6;"><a href="http://##SiteUrl##/personal/jb' + SecondID + '.html" target="_blank">' + JobName + '</a></td>
  </tr>' + MailText

	INSERT INTO #caMail
	SELECT a.caMainId, MailBody = STUFF((SELECT '<aa>' + b.MailText + '<aa>' FROM #JobMail b WHERE a.caMainId = b.caMainId FOR XML PATH('')), 1, 0, '')
	FROM #JobMail a
	GROUP BY a.caMainId

	UPDATE #caMail SET MailBody = REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(MailBody, '&amp;', '&'), '&lt;aa&gt;', ''), '&lt;', '<'), '&gt;', '>'), '&#x0D;', '')
	UPDATE #caMail SET MailBody = '以下是贵单位招聘职位推荐的部分简历。<br>
<table style="font-size:12px">
  <tr style="FONT-WEIGHT: bold; background-color:#f7b666;">
	<td>求职者</td>
	<td>性别</td>
	<td>年龄</td>
	<td>求职意向</td>
	<td>所在地</td>
  </tr>' + MailBody + '
</table>
详细情况请登录网站后使用“简历搜索”-->“<a href="http://##SiteUrl##/Company/cvSearch/Search" target="_blank">搜索简历</a>”-->点击“更多搜索条件”-->输入“简历编号”搜索。'

 	UPDATE a SET a.MailBody = b.MailBody FROM SchMailPrev3 a, #caMail b
	WHERE a.AccountId = b.caMainId

	--UPDATE schMailPrev3 SET MailBody = '<br>&nbsp; 符合您招聘职位的推荐简历已经全部发送，暂时没有新的简历出现。您可以登录网站后使用“职位管理”-->“发布中的职位”，修改给你推荐的频率。<br>&nbsp; ' 
	--WHERE MailBody IS NULL
	DELETE schMailPrev3 WHERE MailBody IS NULL
 
	UPDATE a
	SET a.MailBody = REPLACE(a.MailBody, '##SiteUrl##', 'www.' + b.ProvinceDomain)
	FROM schMailPrev3 a, dcProvince b
	WHERE a.dcProvinceId = b.Id

	UPDATE caJobCvMatch
	SET PushDate = GETDATE()
	WHERE JobId IN(SELECT Id FROM Job WHERE caMainId IN(SELECT caMainId FROM #caSend))
	AND PushDate IS NULL

	DROP TABLE #cvMail
	DROP TABLE #JobMail
	DROP TABLE #caMail
	DROP TABLE #JobTemp
	DROP TABLE #caSend
 END


GO
/****** Object:  StoredProcedure [dbo].[spShowForeignKeys]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[spShowForeignKeys]
(
	@Table VARCHAR(50)
)
AS
BEGIN
	IF dbo.TrimNull(@Table) IS NOT NULL
		SELECT DISTINCT	b.Name AS Key_Name, a.Name AS Name, d.Name AS f_Name, c.rKey
		FROM SysObjects a JOIN SysObjects b ON a.Id = b.Parent_Obj 
		JOIN SysForeignKeys c ON b.Id = c.constId 
		JOIN SysObjects d ON c.rKeyId = d.Id 
		JOIN SysIndexKeys e ON d.Id = e.Id 
		JOIN SysColumns f ON a.Id = f.Id
		AND e.colId = f.colId 
		WHERE b.xtype = 'F'
		AND d.Name = @Table
		ORDER BY Key_Name
	ELSE
		SELECT DISTINCT	b.Name AS Key_Name, a.Name AS Name, d.Name AS f_Name, c.rKey
		FROM SysObjects a JOIN SysObjects b ON a.Id = b.Parent_Obj 
		JOIN SysForeignKeys c ON b.Id = c.constId 
		JOIN SysObjects d ON c.rKeyId = d.Id 
		JOIN SysIndexKeys e ON d.Id = e.Id 
		JOIN SysColumns f ON a.Id = f.Id
		AND e.colId = f.colId 
		WHERE b.xtype = 'F'
		ORDER By f_Name
END














GO
/****** Object:  StoredProcedure [dbo].[spShowTableStruct]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[spShowTableStruct]
(
	@Table AS VARCHAR(50),
	@Column AS VARCHAR(50)
)
AS
BEGIN
	DECLARE @SQL AS VARCHAR(1000)
	SET @Table = dbo.TrimNull(@Table)
	SET @Column = dbo.TrimNull(@Column)

	SET @SQL = '
		SELECT SysObjects.Name AS TABLEName, 
			SysColumns.Name as ColName, 
			SysTypes.Name VType, 
			SysColumns.LENGTH, 
			SysColumns.XPREC, 
			SysColumns.XSCALE, 
			IsNullable, 
			cDefault
		FROM SysColumns, SysObjects, SysTypes 
		WHERE  SysColumns.Id = SysObjects.Id
		AND SysColumns.xType = SysTypes.xType
		AND SysObjects.Type = ''U'''

	IF @Table IS NOT NULL
		SET @SQL = @SQL + '
		AND SysObjects.Name = ''' + @Table + ''''

	IF @Column IS NOT NULL
		SET @SQL = @SQL + '
		AND SysColumns.Name = ''' + @Column + ''''

	SET @SQL = @SQL + '
		ORDER BY SysObjects.Name, SysColumns.Name'

	EXEC(@SQL)
END














GO
/****** Object:  StoredProcedure [dbo].[spSmsEmailCountInsert]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[spSmsEmailCountInsert]
AS
BEGIN
	DECLARE @d AS DATETIME
	SELECT @D = CONVERT(VARCHAR(10), GETDATE(), 120)

	INSERT SmsEmailCount
	SELECT CONVERT(VARCHAR(8), AddDate, 112), 1, MsgType, COUNT(*), SendStatus
	FROM SmsMessageLog 
	WHERE AddDate >= @d - 1 AND AddDate < @d
	GROUP BY CONVERT(VARCHAR(8), AddDate, 112), MsgType, SendStatus

	INSERT SmsEmailCount
	SELECT CONVERT(VARCHAR(8), AddDate, 112), 2, msEmailTypeId, COUNT(*), Status
	FROM msEmailSend
	WHERE AddDate >= @d - 1 AND AddDate < @d
	GROUP BY CONVERT(VARCHAR(8), AddDate, 112), msEmailTypeId, Status

	--select * from SmsEmailCount
	--sp_help SmsEmailCount
	--select * from #t where sendstatus>255
END














GO
/****** Object:  StoredProcedure [dbo].[spSmsMessageLogByReceiveUpdate]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[spSmsMessageLogByReceiveUpdate]
AS
BEGIN
	SELECT * INTO #1 FROM SmsMessageLog WHERE SmsType=2 AND SendMan = 0 AND Msg = 'n'
	IF (SELECT COUNT(*) FROM #1) > 0
	BEGIN
		INSERT INTO MarketDb..NoSendSms SELECT DISTINCT Mobile, GETDATE() FROM #1 WHERE Mobile NOT IN(SELECT Mobile FROM MarketDb..NoSendSms)
		UPDATE SmsMessageLog SET SendMan = 2 WHERE Id IN(SELECT Id FROM #1)
	END
	SELECT Id, Mobile, Msg, ManagerUserId, paMainId, caMainId, SendMan, MsgType
	INTO #2
	FROM SmsMessageLog WHERE SmsType = 2 AND SendMan = 0
	IF (SELECT COUNT(*) FROM #1) > 0
	BEGIN
		UPDATE #2 SET SendMan = ISNULL((SELECT TOP 1 SendMan FROM SmsMessageLog a WHERE a.Mobile = #2.Mobile AND SendMan > 2 ORDER BY ID DESC), 0)
		UPDATE #2 SET SendMan = ISNULL((SELECT TOP 1 a.ConsultantId FROM cpMain a WITH(NOLOCK), caMain b WITH(NOLOCK)
			WHERE a.Id = b.cpMainId AND b.Mobile = #2.Mobile AND a.ConsultantId  > 0 ORDER BY a.LastLoginDate DESC), 0)
		WHERE SendMan = 0

		UPDATE #2 SET SendMan = 180 WHERE SendMan = 0

		UPDATE a
		SET a.SendMan = b.SendMan
		FROM SmsMessageLog a, #2 b
		WHERE a.Id = b.Id

		INSERT INTO RtxNotifyLog(Receiver, RtxTitle, RtxMessage, SendType, DelayTime, ShowType)
		SELECT DISTINCT SendMan, '收到短信', 
			'您有新的短信，请及时处理！' + CASE SendMan WHEN 180 THEn '' ELSE '内容：' + Msg END,
			1, 0, 0
		From #2
	END
END

GO
/****** Object:  StoredProcedure [dbo].[spSmsMessageLogSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[spSmsMessageLogSelect]
AS
BEGIN
	DECLARE @Day7 AS DATETIME, @Day1 AS DATETIME
	SET @Day7 = CONVERT(DATETIME, CONVERT(VARCHAR(10), GETDATE() - 7, 120))
	SET @Day1 = CONVERT(DATETIME, CONVERT(VARCHAR(10), GETDATE() - 1, 120))
	 

	DECLARE @t AS TABLE(
		ID int,
		SendMan smallint,
		ManagerUserId smallint,
		paMainId int,
		caMainId int,
		Mobile varchar(20),
		Msg nvarchar(210),
		IsCat bit,
		AddDate smalldatetime,
		PortNo tinyint,
		SendDate datetime,
		SendStatus bit,
		SmsType tinyint,
		MsgType tinyint,
		IsDelete BIT
	)

	DECLARE @c AS TABLE(
		caMainId INT,
		MsgType tinyint,
		AddDate DATETIME,
		Cnt INT
		)

	INSERT INTO @t
	SELECT TOP 10 *, 0 FROM SmsMessageLog WITH(NOLOCK)
		WHERE SendDate IS NULL 
		AND IsCat = 0
		AND SmsType = 1
		AND AddDate > @Day7
		ORDER BY AddDate

	INSERT INTO @c
	SELECT caMainID, MsgType, Max(AddDate), COUNT(*)
	FROM SmsMessageLog WITH(NOLOCK)
	WHERE AddDate > @Day7
	AND SmsType = 1
	AND ID NOT IN(SELECT ID FROM @t)
	AND caMainID IN(SELECT caMainId FROM @t)
	GROUP BY caMainID, MsgType

	UPDATE @t SET IsDelete = 1
	WHERE MsgType IN(1,3,5)
	AND caMainId IN(SELECT caMainId FROM @c WHERE MsgType IN(1,3,5) AND AddDate > @Day1)

	UPDATE @t SET IsDelete = 1
	WHERE MsgType IN(2,4,19)
	AND caMainId IN(SELECT caMainId FROM @c WHERE MsgType IN(2,4,19) AND AddDate > @Day1)

	UPDATE @t SET IsDelete = 1
	WHERE MsgType = 7
	AND caMainId IN(SELECT caMainId FROM @c WHERE MsgType = 7 AND AddDate > @Day1)

	UPDATE @t SET IsDelete = 1
	WHERE MsgType = 8
	AND caMainId IN(SELECT caMainId FROM @c WHERE MsgType = 8 AND AddDate > @Day1)

	UPDATE @t SET IsDelete = 1
	WHERE MsgType = 9
	AND caMainId IN(SELECT caMainId FROM @c WHERE MsgType = 9 AND AddDate > @Day1 AND Cnt > 2)

	UPDATE @t SET IsDelete = 1
	WHERE MsgType = 20
	AND caMainId IN(SELECT caMainId FROM @c WHERE MsgType = 20 AND AddDate > @Day1)

	UPDATE @t SET IsDelete = 1
	WHERE MsgType = 10
	AND caMainId IN(SELECT caMainId FROM @c WHERE MsgType = 9 AND AddDate > @Day1 AND Cnt > 2)

	UPDATE @t SET IsDelete = 1
	WHERE MsgType IN(12,13,14,15)
	AND caMainId IN(SELECT caMainId FROM @c)

	UPDATE @t SET IsDelete = 1
	WHERE MsgType = 11
	AND caMainId IN(SELECT caMainId FROM @c WHERE AddDate > @Day1)

	UPDATE SmsMessageLog SET SmsType = 3 WHERE ID IN(SELECT ID FROM @t WHERE IsDelete = 1)

	SELECT * FROM @t WHERE IsDelete = 0

	INSERT INTO ServiceRunLog(ServiceId, RunRows, RunId, RunStatus, RunMessage)
	SELECT 1, @@RowCount, 0, 1, '提取短信数据'
END














GO
/****** Object:  StoredProcedure [dbo].[spStartOrder]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[spStartOrder]
(
	@Id INT
)
AS
BEGIN
	DECLARE @M INT
	SELECT @m = DATEDIFF(Month, Begindate, Enddate) FROM caOrder WHERE Id = @Id
	UPDATE caOrder SET BeginDate = GETDATE(), EndDate = DATEADD(MONTH, @m, GETDATE()) WHERE Id = @Id
	UPDATE caOrder SET BeginDate = GETDATE(), EndDate = DATEADD(MONTH, @m, GETDATE()) WHERE MainOrderId = @Id
	SELECT @m, BeginDate, EndDate, * FROM caORder WHERE Id = @Id
End

GO
/****** Object:  StoredProcedure [dbo].[spTableByRowNumberSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[spTableByRowNumberSelect]
AS
BEGIN
	SET NOCOUNT ON
	DECLARE @t as TABLE(Id INT IDENTITY(1, 1), dbId INT, tabName VARCHAR(50))
	INSERT INTO @t SELECT 3, 'BsCvVerifySnap'
	INSERT INTO @t SELECT 1, 'caCvRemark'
	INSERT INTO @t SELECT 1, 'caCvViewLog'
	INSERT INTO @t SELECT 1, 'CaOnline'
	INSERT INTO @t SELECT 1, 'cpIndustry'
	INSERT INTO @t SELECT 1, 'cpMainPublish'
	INSERT INTO @t SELECT 1, 'cvAppendixPublish'
	INSERT INTO @t SELECT 1, 'cvEducationPublish'
	INSERT INTO @t SELECT 1, 'cvExperiencePublish'
	INSERT INTO @t SELECT 1, 'cvIndustryPublish'
	INSERT INTO @t SELECT 1, 'cvInfo'
	INSERT INTO @t SELECT 1, 'cvJobPlacePublish'
	INSERT INTO @t SELECT 1, 'cvJobTypePublish'
	INSERT INTO @t SELECT 1, 'cvLanguagePublish'
	INSERT INTO @t SELECT 1, 'cvMainPublish'
	INSERT INTO @t SELECT 1, 'cvProjectPublish'
	INSERT INTO @t SELECT 1, 'cvTrainingPublish'
	INSERT INTO @t SELECT 1, 'dcCompanySize'
	INSERT INTO @t SELECT 1, 'dcEducation'
	INSERT INTO @t SELECT 1, 'dcIndustry'
	INSERT INTO @t SELECT 1, 'dcJobType'
	INSERT INTO @t SELECT 1, 'dcMapPlace'
	INSERT INTO @t SELECT 1, 'dcOthers'
	INSERT INTO @t SELECT 1, 'dcRegion'
	INSERT INTO @t SELECT 1, 'dcSalary'
	INSERT INTO @t SELECT 1, 'dcSubSite'
	INSERT INTO @t SELECT 1, 'Ip_Black'
	INSERT INTO @t SELECT 1, 'Ip_White'
	INSERT INTO @t SELECT 1, 'JobPublish'
	INSERT INTO @t SELECT 1, 'JobSimilar'
	INSERT INTO @t SELECT 1, 'PaAttention'
	INSERT INTO @t SELECT 1, 'paMainPublish'
	INSERT INTO @t SELECT 1, 'PaOnline'
	INSERT INTO @t SELECT 1, 'SearchJobTop'
	INSERT INTO @t SELECT 1, 'WxFans'
	INSERT INTO @t SELECT 2, 'CpBrandPublish'
	INSERT INTO @t SELECT 2, 'CpBrochurePublish'
	INSERT INTO @t SELECT 2, 'cpDeptPublish'
	INSERT INTO @t SELECT 2, 'CpImage'
	INSERT INTO @t SELECT 2, 'CpIndustry'
	INSERT INTO @t SELECT 2, 'CpMainPublish'
	INSERT INTO @t SELECT 2, 'CpOrder'
	INSERT INTO @t SELECT 2, 'CpPreach'
	INSERT INTO @t SELECT 2, 'DcCompanyKind'
	INSERT INTO @t SELECT 2, 'DcEducation'
	INSERT INTO @t SELECT 2, 'DcIndustry'
	INSERT INTO @t SELECT 2, 'DcMajor'
	INSERT INTO @t SELECT 2, 'DcRegion'
	INSERT INTO @t SELECT 2, 'JobMajor'
	INSERT INTO @t SELECT 2, 'JobMajorPublish'
	INSERT INTO @t SELECT 2, 'JobPublish'
	INSERT INTO @t SELECT 2, 'JobRegion'
	INSERT INTO @t SELECT 2, 'JobRegionPublish'
	INSERT INTO @t SELECT 2, 'JobRegionShot'

	DECLARE @r AS TABLE(
		[NAMEINFO] [varchar](50) NULL,
		[ROWSINFO] [int] NULL,
		[RESERVED] [varchar](20) NULL,
		[DATAINFO] [varchar](20) NULL,
		[INDEX_SIZE] [varchar](20) NULL,
		[UNUSED] [varchar](20) NULL,
		[AddDate] [smalldatetime] NULL
	)
	CREATE TABLE #t(id INT IDENTITY(1, 1), dbId INT, tabName VARCHAR(50), rowNum int)
	DECLARE @Id INT, @dbId INT, @tabName VARCHAR(50)
	SET @Id = 0
	WHILE EXISTS(SELECT 'x' FROM @t WHERE Id > @Id)
	BEGIN
		SELECT TOP 1 @Id = Id, @dbId = dbId, @tabName = tabName FROM @t WHERE Id > @Id ORDER BY Id
		IF @dbId = 1
			INSERT INTO @r(NAMEINFO, ROWSINFO, RESERVED, DATAINFO, INDEX_SIZE, UNUSED)
			EXEC SP_SPACEUSED @tabName
		IF @dbId = 2
			INSERT INTO @r(NAMEINFO, ROWSINFO, RESERVED, DATAINFO, INDEX_SIZE, UNUSED)
			EXEC WuTongGuoDb..SP_SPACEUSED @tabName
		IF @dbId = 3
			INSERT INTO @r(NAMEINFO, ROWSINFO, RESERVED, DATAINFO, INDEX_SIZE, UNUSED)
			EXEC ShortDb..SP_SPACEUSED @tabName
		INSERT INTO #t SELECT @dbId, @tabName, ROWSINFO FROM @r
		DELETE FROM @r
	END

	SELECT * FROM #t
END

GO
/****** Object:  StoredProcedure [dbo].[spTableSpaceInfoInsert]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[spTableSpaceInfoInsert]
AS
BEGIN
	DECLARE MYCURSOR CURSOR FOR
	SELECT NAME FROM SYSOBJECTS WHERE XTYPE='U'
	OPEN MYCURSOR

	DECLARE @NAME  VARCHAR(100)

	FETCH NEXT FROM MYCURSOR INTO @NAME
	WHILE(@@FETCH_STATUS =0)
	BEGIN
		INSERT INTO TABLESPACEINFO(NAMEINFO, ROWSINFO, RESERVED, DATAINFO, INDEX_SIZE, UNUSED)
		EXEC SP_SPACEUSED @NAME  
		FETCH NEXT FROM MYCURSOR INTO @NAME
	END

	CLOSE MYCURSOR
	DEALLOCATE MYCURSOR
END
 














GO
/****** Object:  StoredProcedure [dbo].[spTmpCheckFileByCanDeleteUpdate]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
1、照片；2、证书；3、word附件；4处理的照片；10、营业执照；11、logo；12、形象图；
20：order.RemittanceFile；21：Order.ContractFile；22：FaxFile
40:adverproject;
51、OaDb..LeaveAttchment；52：文档管理
*/
CREATE PROCEDURE [dbo].[spTmpCheckFileByCanDeleteUpdate]
AS
BEGIN
	declare @i int
	set @i = 0
	WHILE @I < 14673225
	BEGIN
		update tmpcheckfile set filetype=0, fileid=999 where id BETWEEN @i AND @i + 30000
		set @i = @i + 30000
	END

	CREATE TABLE #t(Id INT, FileName VARCHAR(200))	
	--UPDATE tmpCheckFile SET FileType = 0
	--delete from tmpcheckfile where fullname like 'D:\hosting\down.51rc.com\imagefolder\adimage\%'
	--100、照片；
	UPDATE tmpCheckFile SET FileType = 1
	WHERE fullName LIKE 'D:\hosting\down.51rc.com\imagefolder\photo\%\photo\%'

	UPDATE tmpCheckFile SET FileId = 1 WHERE FileType = 1 AND FileName IN(SELECT photo FROM paPhoto WHERE photo > '')
	UPDATE tmpCheckFile SET FileId = 1 WHERE FileType = 1 AND FileName IN(SELECT photoProcessed FROM paPhoto WHERE photoProcessed > '')

	--4处理的照片；
	UPDATE tmpCheckFile SET FileType = 4
	WHERE fullName LIKE 'D:\hosting\down.51rc.com\imagefolder\photo\%\processed\%'

	UPDATE tmpCheckFile SET FileId = 1 WHERE FileType = 4 AND FileName IN(SELECT photo FROM paPhoto WHERE photo > '')
	UPDATE tmpCheckFile SET FileId = 1 WHERE FileType = 4 AND FileName IN(SELECT photoProcessed FROM paPhoto WHERE photoProcessed > '')

	--2、证书
	--UPDATE tmpCheckFile SET FileType = 2 WHERE fullName LIKE 'D:\hosting\down.51rc.com\imagefolder\appendix\L%'
	--UPDATE tmpCheckFile SET FileId = 1 WHERE FileType = 2 AND FileName IN(SELECT FileName FROM cvAppendix WHERE FileName > '')

	--3、word附件；
	UPDATE tmpCheckFile SET FileType = 3 WHERE fullName LIKE 'D:\hosting\down.51rc.com\imagefolder\attachment\L%'
	UPDATE tmpCheckFile SET FileId = 1 WHERE FileType = 3 AND FileName IN(SELECT Attachment FROM cvMain WHERE Attachment > '')

	--10、营业执照；
	UPDATE tmpCheckFile SET FileType = 10 WHERE fullName LIKE 'D:\hosting\down.51rc.com\imagefolder\Licence\%'

	UPDATE tmpCheckFile SET FileId = 1 WHERE FileType = 10 AND FileName IN(SELECT ImgFile FROM cpLicence)
	UPDATE tmpCheckFile SET FileId = 1 WHERE FileType = 10 AND FileId= 0 AND FileName IN(SELECT FileNameOld FROM cpLicenceChangeLog)
	UPDATE tmpCheckFile SET FileId = 1 WHERE FileType = 10 AND FileId= 0 AND FileName IN(SELECT FileNameNew FROM cpLicenceChangeLog)
	UPDATE tmpCheckFile SET FileId = 1 WHERE FileType = 10 AND FileId= 0 AND FileName IN(SELECT OldFileName FROM cpLicenceLog)

	--11、logo；
	UPDATE tmpCheckFile SET FileType = 11 WHERE fullName LIKE 'D:\hosting\down.51rc.com\imagefolder\Logo\%'	
	--12、形象图；
	UPDATE tmpCheckFile SET FileType = 12 WHERE fullName LIKE 'D:\hosting\down.51rc.com\imagefolder\visual\%'	
	UPDATE tmpCheckFile SET FileType = 13 WHERE fullName LIKE 'D:\hosting\down.51rc.com\ImageFolder\operational\Environment\%'

	SELECT Id, cpMainId, ImgFile, ImgFile FileName INTO #i FROM cpImage
	UPDATE #i SET FileName = RIGHT(FileName, LEN(FileName) - CHARINDEX('/', FileName, 0)) WHERE FileName LIKE '%/%'
	UPDATE #i SET FileName = RIGHT(FileName, LEN(FileName) - CHARINDEX('/', FileName, 0)) WHERE FileName LIKE '%/%'
	UPDATE #i SET FileName = RIGHT(FileName, LEN(FileName) - CHARINDEX('/', FileName, 0)) WHERE FileName LIKE '%/%'
	UPDATE #i SET FileName = RIGHT(FileName, LEN(FileName) - CHARINDEX('/', FileName, 0)) WHERE FileName LIKE '%/%'
	UPDATE #i SET FileName = RIGHT(FileName, LEN(FileName) - CHARINDEX('/', FileName, 0)) WHERE FileName LIKE '%/%'

	TRUNCATE TABLE #t
	UPDATE tmpCheckFile SET FileId = 1 WHERE FileType = 11
	INSERT INTO #t SELECT Id, FileName FROM tmpCheckFile WHERE FileType = 11
	DELETE FROM #t WHERE FileName IN(SELECT FileName FROM #i WHERE FileName > '')
	UPDATE a SET a.FileId = 999 FROM tmpCheckFile a, #t b WHERE a.Id = b.Id

	TRUNCATE TABLE #t
	UPDATE tmpCheckFile SET FileId = 1 WHERE FileType = 12
	INSERT INTO #t SELECT Id, FileName FROM tmpCheckFile WHERE FileType = 12
	DELETE FROM #t WHERE FileName IN(SELECT FileName FROM #i WHERE FileName > '')
	UPDATE a SET a.FileId = 999 FROM tmpCheckFile a, #t b WHERE a.Id = b.Id

	TRUNCATE TABLE #t
	UPDATE tmpCheckFile SET FileId = 1 WHERE FileType = 13
	INSERT INTO #t SELECT Id, FileName FROM tmpCheckFile WHERE FileType = 13
	DELETE FROM #t WHERE FileName IN(SELECT FileName FROM #i WHERE FileName > '')
	UPDATE a SET a.FileId = 999 FROM tmpCheckFile a, #t b WHERE a.Id = b.Id

	UPDATE tmpCheckFile SET FileId = 1 WHERE fullName LIKE 'D:\hosting\down.51rc.com\imagefolder\Logo\Default\%'
	--20：order.RemittanceFile；
	UPDATE tmpCheckFile SET FileType = 20 WHERE fullName LIKE 'D:\hosting\down.51rc.com\imagefolder\Remit\%'

	TRUNCATE TABLE #t
	UPDATE tmpCheckFile SET FileId = 1 WHERE FileType = 20
	INSERT INTO #t SELECT Id, FileName FROM tmpCheckFile WHERE FileType = 20
	DELETE FROM #t WHERE FileName IN(SELECT RemittanceFile FROM caOrder WHERE RemittanceFile > '')
	UPDATE a SET a.FileId = 999 FROM tmpCheckFile a, #t b WHERE a.Id = b.Id

	update tmpCheckFile set pamainid = left(filename, charindex('_', filename) - 1) where charindex('_', filename) > 1 and filetype = 20 and FileId = 999
	update a set a.fileid = 1 from tmpCheckFile a, caorder b
	where a.filetype = 20 and a.FileId = 999 and a.pamainid = b.id and charindex(a.filename, b.remittancefile) > 0

	--21：Order.ContractFile；
	UPDATE tmpCheckFile SET FileType = 21 WHERE fullName LIKE 'D:\hosting\down.51rc.com\imagefolder\Sales\contract\L%'

	UPDATE tmpCheckFile SET FileId = 1 WHERE FileType = 21 AND FileName IN(SELECT ContractFile FROM caOrder WHERE ContractFile > '')

	--22：FaxFile
	UPDATE tmpCheckFile SET FileType = 22, FileId = 1 WHERE fullName LIKE 'D:\hosting\down.51rc.com\imagefolder\Fax%'

	--orderupload
	UPDATE tmpCheckFile SET FileType = 23, FileId = 1 WHERE fullName LIKE 'D:\hosting\down.51rc.com\imagefolder\orderupload%'

	--29:GdFixed
	UPDATE tmpCheckFile SET FileType = 29, FileId = 1WHERE fullName LIKE 'D:\hosting\down.51rc.com\imagefolder\OA\Goods\%' 

	--40:adverproject;
	UPDATE tmpCheckFile SET FileType = 40, FileId = 1 WHERE fullName LIKE 'D:\hosting\down.51rc.com\imagefolder\operational\hpimage\%'
	TRUNCATE TABLE #t
	--UPDATE tmpCheckFile SET FileId = 1 WHERE FileType = 40
	INSERT INTO #t SELECT Id, FileName FROM tmpCheckFile WHERE FileType = 40
	select id, imagefile FileName INTO #a from AdverProject WHERE imagefile > ''
	UPDATE #a SET FileName = RIGHT(FileName, LEN(FileName) - CHARINDEX('/', FileName, 0)) WHERE FileName LIKE '%/%'
	UPDATE #a SET FileName = RIGHT(FileName, LEN(FileName) - CHARINDEX('/', FileName, 0)) WHERE FileName LIKE '%/%'
	UPDATE #a SET FileName = RIGHT(FileName, LEN(FileName) - CHARINDEX('/', FileName, 0)) WHERE FileName LIKE '%/%'
	UPDATE #a SET FileName = RIGHT(FileName, LEN(FileName) - CHARINDEX('/', FileName, 0)) WHERE FileName LIKE '%/%'
	UPDATE #a SET FileName = RIGHT(FileName, LEN(FileName) - CHARINDEX('/', FileName, 0)) WHERE FileName LIKE '%/%'
	DELETE FROM #t WHERE FileName IN(select FileName from #a WHERE FileName > '')
--??	UPDATE a SET a.FileId = 999 FROM tmpCheckFile a, #t b WHERE a.Id = b.Id

	UPDATE tmpCheckFile SET FileType = 41 WHERE fullName LIKE 'D:\hosting\down.51rc.com\imagefolder\adimage\%'

	--45:manageruser_photo
	UPDATE tmpCheckFile SET FileType = 45, FileId = 1 WHERE fullName LIKE 'D:\hosting\down.51rc.com\imagefolder\manageruser_photo\%'

	--51、OaDb..LeaveAttchment；
	UPDATE tmpCheckFile SET FileType = 51, FileId = 1 WHERE fullName LIKE 'D:\hosting\down.51rc.com\imagefolder\Oa\Leave\%'

	--52：文档管理
	UPDATE tmpCheckFile SET FileType = 52, FileId = 1 WHERE fullName LIKE 'D:\hosting\down.51rc.com\imagefolder\Oa\Archive\%'
	UPDATE tmpCheckFile SET FileType = 52, FileId = 1 WHERE fullName LIKE 'D:\hosting\down.51rc.com\imagefolder\Oa\Doc\%'
	select id, FileName INTO #h from oadb..hrdoc
	UPDATE #h SET FileName = RIGHT(FileName, LEN(FileName) - CHARINDEX('\', FileName, 0)) WHERE FileName LIKE '%\%'
	UPDATE #h SET FileName = RIGHT(FileName, LEN(FileName) - CHARINDEX('\', FileName, 0)) WHERE FileName LIKE '%\%'
	UPDATE #h SET FileName = RIGHT(FileName, LEN(FileName) - CHARINDEX('\', FileName, 0)) WHERE FileName LIKE '%\%'
	UPDATE #h SET FileName = RIGHT(FileName, LEN(FileName) - CHARINDEX('\', FileName, 0)) WHERE FileName LIKE '%\%'
	UPDATE #h SET FileName = RIGHT(FileName, LEN(FileName) - CHARINDEX('\', FileName, 0)) WHERE FileName LIKE '%\%'

	TRUNCATE TABLE #t
	INSERT INTO #t SELECT Id, FileName FROM tmpCheckFile WHERE FileType = 52
	DELETE FROM #t WHERE FileName IN(SELECT FileName FROM #h)
	UPDATE tmpCheckFile SET FileId = 999 WHERE ID IN(SELECT Id FROM #t)

	--53:OaAdvertising
	UPDATE tmpCheckFile SET FileType = 53, FileId = 1 WHERE fullName LIKE 'D:\hosting\down.51rc.com\imagefolder\Oa\Advertising\%'
	TRUNCATE TABLE #t
	INSERT INTO #t SELECT Id, FileName FROM tmpCheckFile WHERE FileType = 53

	SELECT TOP 0 * INTO #adv FROM #t
	insert into #adv select Id, FileName1 from Oadb..Advertising WHERE FileName1 > ''
	insert into #adv select Id, FileName2 from Oadb..Advertising WHERE FileName2 > ''
	DELETE from #t WHERE FileName in (SELECT FileName FROM #Adv)
	UPDATE tmpCheckFile SET FileId = 999 WHERE ID IN(SELECT Id FROM #t)

	--55:OaAdvertising
	UPDATE tmpCheckFile SET FileType = 55, FileId = 1 WHERE fullName LIKE 'D:\hosting\down.51rc.com\imagefolder\Oa\Project\%'

	--56:OaAdvertising
	UPDATE tmpCheckFile SET FileType = 56, FileId = 1  WHERE fullName LIKE 'D:\hosting\down.51rc.com\imagefolder\Oa\TrainCourse\%'

	--57:OaAdvertising
	UPDATE tmpCheckFile SET FileType = 57, FileId = 1 WHERE fullName LIKE 'D:\hosting\down.51rc.com\imagefolder\Oa\TrainPlan\%'

	--61:Campus
	UPDATE tmpCheckFile SET FileType = 61, FileId = 1 WHERE fullName LIKE 'D:\hosting\down.51rc.com\imagefolder\operational\Campus\%'

	--62:Campus
	UPDATE tmpCheckFile SET FileType = 62, FileId = 1 WHERE fullName LIKE 'D:\hosting\down.51rc.com\imagefolder\operational\CampusNew\%'
	
	--63:ChongSoft
 
	--64:Coorperation
	UPDATE tmpCheckFile SET FileType = 64, FileId = 1 WHERE fullName LIKE 'D:\hosting\down.51rc.com\imagefolder\Market\Coorperation\%'

	--65:FnBankCheck
	UPDATE tmpCheckFile SET FileType = 65, FileId = 1 WHERE fullName LIKE 'D:\hosting\down.51rc.com\imagefolder\Finance\FnBankCheck\%'

	--66:FnBankCheck
	UPDATE tmpCheckFile SET FileType = 66, FileId = 1 WHERE fullName LIKE 'D:\hosting\down.51rc.com\imagefolder\Finance\FnBankDaybook\%'

	--67:FnCash
	UPDATE tmpCheckFile SET FileType = 67, FileId = 1 WHERE fullName LIKE 'D:\hosting\down.51rc.com\imagefolder\Finance\FnCash\%'

	--68:FnPICDaybook
	UPDATE tmpCheckFile SET FileType = 68, FileId = 1 WHERE fullName LIKE 'D:\hosting\down.51rc.com\imagefolder\Finance\FnPICDaybook\%'

	--69:门贴
	UPDATE tmpCheckFile SET FileType = 69, FileId = 1 WHERE fullName LIKE 'D:\hosting\down.51rc.com\imagefolder\Market\%'

	--70:KPI
	UPDATE tmpCheckFile SET FileType = 70, FileId = 1 WHERE fullName LIKE 'D:\hosting\down.51rc.com\imagefolder\KPI\%'

	--71:linkimage

	--72:music

	--73:newsimage
	UPDATE tmpCheckFile SET FileType = 73, FileId = 1 WHERE fullName LIKE 'D:\hosting\down.51rc.com\imagefolder\operational\newsimage\%'

	--74:nianhui
 
	--75:picture
	UPDATE tmpCheckFile SET FileType = 75, FileId = 1 WHERE fullName LIKE 'D:\hosting\down.51rc.com\imagefolder\picture\%'

	--76:productBulletin
	UPDATE tmpCheckFile SET FileType = 76, FileId = 1 WHERE fullName LIKE 'D:\hosting\down.51rc.com\imagefolder\operational\productBulletin\%'

	--77:qlrcnews

	--78:Recruitment
	UPDATE tmpCheckFile SET FileType = 78, FileId = 1 WHERE fullName LIKE 'D:\hosting\down.51rc.com\imagefolder\Recruitment\%'
	truncate table #t
	insert #t select id, fileName from tmpCheckFile where filetype = 78 order by crdate desc
	select id, uploadfile filename into #pcv from marketdb..ptCvInvitation
	UPDATE #pcv SET FileName = RIGHT(FileName, LEN(FileName) - CHARINDEX('\', FileName, 0)) WHERE FileName LIKE '%\%'
	UPDATE #pcv SET FileName = RIGHT(FileName, LEN(FileName) - CHARINDEX('\', FileName, 0)) WHERE FileName LIKE '%\%'
	UPDATE #pcv SET FileName = RIGHT(FileName, LEN(FileName) - CHARINDEX('\', FileName, 0)) WHERE FileName LIKE '%\%'
	DELETE FROM #t WHERE FileName IN(SELECT FileName FROM #pcv)
	DELETE #t WHERE FullName LIKE 'D:\hosting\down.51rc.com\ImageFolder\Recruitment\RmPlacePhoto%'
	UPDATE tmpCheckFile SET FileId = 999 WHERE ID IN(SELECT Id FROM #t) AND fullName LIKE'D:\hosting\down.51rc.com\ImageFolder\Recruitment\RmPlacePhoto%'
	--80:slide
	UPDATE tmpCheckFile SET FileType = 80, FileId = 1 WHERE fullName LIKE 'D:\hosting\down.51rc.com\imagefolder\operational\slide\%'

	--81:topics
	UPDATE tmpCheckFile SET FileType = 81, FileId = 1 WHERE fullName LIKE 'D:\hosting\down.51rc.com\imagefolder\operational\topics\%'

	--82:topics
	UPDATE tmpCheckFile SET FileType = 30 WHERE fullName LIKE 'D:\hosting\down.51rc.com\ImageFolder\RecordFile\%'
	update tmpCheckFile set pamainid = left(filename, 7) where filetype = 30
	update tmpCheckFile set fileid = 1 where filetype = 30 and pamainid in(select id from ivrlist)

 	select  * from tmpCheckFile where filetype = 30 and FileId = 999

	TRUNCATE TABLE #t
	UPDATE tmpCheckFile SET FileId = 1 WHERE FileType = 30
	INSERT INTO #t SELECT Id, FileName FROM tmpCheckFile WHERE FileType = 30
	UPDATE #t SET FileName = LEFT(FileName, 7)
	DELETE FROM #t WHERE FileName IN(SELECT Id FROM IvrList)
	UPDATE a SET a.FileId = 999 FROM tmpCheckFile a, #t b WHERE a.Id = b.Id

	--
	UPDATE tmpCheckFile SET FileType = 90, fileid = 1 WHERE fullName LIKE 'D:\hosting\down.51rc.com\ImageFolder\wutongguo\%'
	UPDATE tmpCheckFile SET FileType = 91, fileid = 1 WHERE filetype=0 AND fullName LIKE 'D:\hosting\down.51rc.com\ImageFolder\operational\%'
	UPDATE tmpCheckFile SET FileType = 92, fileid = 1 WHERE filetype=0 AND fullName LIKE 'D:\hosting\down.51rc.com\ImageFolder\OA\Spread\PicCheck\%'
	UPDATE tmpCheckFile SET FileType = 93, fileid = 1 WHERE filetype=0 AND fullName LIKE 'D:\hosting\down.51rc.com\ImageFolder\OA\Car\%'
	UPDATE tmpCheckFile SET FileType = 94, fileid = 1 WHERE filetype=0 AND fullName LIKE 'D:\hosting\down.51rc.com\ImageFolder\CHAT\%'

	SELECT ID, FileName, REPLACE(FullName, 'D:\hosting\down.51rc.com\ImageFolder\Chat\', '') FullName, 0 IsExists INTO #c FROM tmpCheckFile WHERE FileType = 94
	UPDATE #c SET FullName = REPLACE(Fullname, '\', '/')
	UPDATE #c SET IsExists = 1 WHERE EXISTS(SELECT 'x' FROM ChatOnlineLog b WHERE b.Message = #c.FileName)
	DELETE #c WHERE Isexists = 1
	UPDATE #c SET IsExists = 1 WHERE EXISTS(SELECT 'x' FROM ChatOnlineLog b WHERE b.Message = #c.FullName)
	DELETE #c WHERE Isexists = 1
	UPDATE tmpCheckFile SET FileId = 999 WHERE ID IN(SELECT ID FROM #c)
 
	UPDATE tmpCheckFile SET FileType = 95, fileid = 1 WHERE filetype=0 AND fullName LIKE 'D:\hosting\down.51rc.com\ImageFolder\spreadcall\%'
	SELECT ID, RIGHT(FileName, 18) FileName, 0 IsExists INTO #s FROM tmpCheckFile WHERE FileType = 95
	UPDATE #s SET IsExists = 1 WHERE EXISTS(SELECT 'x' FROM SpreadCallLog b WHERE b.FileName LIKE '%' + #s.FileName)
	DELETE #ｓ WHERE Isexists = 1
	UPDATE tmpCheckFile SET FileId = 999 WHERE ID IN(SELECT ID FROM #s)	
	UPDATE tmpCheckFile SET FileType = 96, fileid = 1 WHERE filetype=0 AND fullName LIKE 'D:\hosting\down.51rc.com\ImageFolder\OA\ColdCustomer\%'
	UPDATE tmpCheckFile SET FileType = 97, fileid = 1 WHERE filetype=0 AND fullName LIKE 'D:\hosting\down.51rc.com\ImageFolder\WxMessageTemplate\%'
	update tmpCheckFile set CanDelete = 1 where candelete = 0 and FileId = 999 and FileType > 0
END

GO
/****** Object:  StoredProcedure [dbo].[spTmpCheckFileInsert]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[spTmpCheckFileInsert]
AS
BEGIN
	delete from tmpcheckfile
	where filename in(select photofile from marketdb..RmInvitationCode 
		where uploaddate> getdate()-60
		or adddate > getdate() -60
		or verifydate > getdate()-60)
	or crdate > getdate()-60
END














GO
/****** Object:  StoredProcedure [dbo].[spTransCustom]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE proc [dbo].[spTransCustom]
(
	@from char(3),
	@to char(3)
)
as
begin
	select 'Update cpmain  set consultantid=' + @to + ' Where id = '+ltrim(str(id)) from cpmain where consultantid=@from
	select 'Update caorder set manageruserid=' + @to + '  Where id='+ltrim(str(id)) from caorder where manageruserid=@from and opendate is null
	select 'update contact set manageruserid=' + @to + '  where manageruserid=' + @from
end
GO
/****** Object:  StoredProcedure [dbo].[spWxmessageSendByTempInsert]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create procedure [dbo].[spWxmessageSendByTempInsert]
AS
BEGIN
	--DROP TABLE #t
	--drop table #wx

	SELECT DISTINCT b.Id paMainId INTO #t
	from maindb..wxfans a with(nolock),maindb..pamain b with(nolock) ,maindb..cvmain c with(nolock),
	maindb..cveducation d with(nolock)
	where a.pamainid=b.id and b.id=c.pamainid and c.id= d.cvmainid
	and status=2 
	and d.graduation>201606
	--AND b.dcProvinceId = 32

	--update #t SET pamainid = 26974069

	CREATE TABLE #wx(Id INT IDENTITY(1, 1), paMainId INT, Msg NVARCHAR(210),
		WxFansId INT, OpenId VARCHAR(50), WxServiceNoID INT, paName NVARCHAR(6),
		WebsiteName NVARCHAR(10), WxTemplateNo VARCHAR(100),
		ParaValue VARCHAR(1000), JsonMessage VARCHAR(1000))

	INSERT INTO #wx(paMainId, Msg, WxFansId, OpenId, wxServiceNoId)
	SELECT a.paMainId, '你好，今日软通动力正在发放终面名额，这是一个进名企的捷径，赶紧抓住机会吧。软通动力是上市公司，智慧城市与产业互联网建设的领导者，创新型技术服务提供商', b.Id WxFansId, b.OpenId, b.wxServiceNoId
	FROM #t a, WxFans b WITH(NOLOCK)
	WHERE a.paMainId = b.paMainId
	AND b.Status > 0
	AND a.PaMainId > 0

	UPDATE a SET a.paName = b.Name FROM #wx a, paMain b WITH(NOLOCK) WHERE a.paMainId = b.Id
	UPDATE a SET a.WebsiteName = c.WebsiteName FROM #wx a, WxServiceNo b WITH(NOLOCK), dcprovince c WITH(NOLOCK)  WHERE a.WxServiceNoId = b.Id AND b.ProvinceID = c.Id
	UPDATE a SET a.WxTemplateNo = b.[no] FROM #wx a, WxTemplateNo b WITH(NOLOCK) WHERE a.WxServiceNoID = b.WxServiceNoID AND b.WxTemplateId = 13 

	--插入参数数据
	UPDATE #wx SET ParaValue = '"first":{    "value":"软通动力正在发放2017校招终面名额",    "color":"#000000"},  "keyword1":{    "value":"直通终面",    "color":"#004694"},  "keyword2":{    "value":"终面提醒",    "color":"#004694"},  "remark":{    "value":"#JobDesc#",    "color":"#004694"}'
	--UPDATE #wx SET ParaValue = REPLACE(ParaValue, '#PaName#', PaName) 
	UPDATE #wx SET ParaValue = REPLACE(ParaValue, '#JobDesc#', Msg)
	--UPDATE #wx SET ParaValue = REPLACE(ParaValue, '#WebsiteName#', WebsiteName)
	UPDATE #wx SET JsonMessage = '{"touser":"' + OpenId + '", "template_id":"' + WxTemplateNo + '", "url":"http://zhaopin.baidu.com/m/ztzm", "topcolor":"#000000", "data":{' + ParaValue + '}}'

	--更新wxmessagesend中的message
--	INSERT INTO wxMessageSend2(TemplateType, WxfansId, paMainId, MessageText, ErrorNumber, AddDate)
	SELECT 10, WxFansId, paMainId, JsonMessage, 0, GETDATE() FROM #wx

--	select * from wxmessagesend2 where TemplateType = 10 order by id desc
--	select * from #wx
--	select count(*) from wxmessagesend2 where TemplateType = 10 and senddate is null
END
GO
/****** Object:  StoredProcedure [dbo].[synBeisenJobApplyByBeiSenResumeUpdate]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[synBeisenJobApplyByBeiSenResumeUpdate] 
(
	@id INT,
	@BeiSenResumeID VARCHAR(50),
	@BeiSenResumeSyncId VARCHAR(50)
)
AS
SET NOCOUNT ON
BEGIN
	UPDATE BeisenJobApply 
	SET BeiSenResumeID = @BeiSenResumeID, 
		BeiSenResumeSyncId = @BeiSenResumeSyncId,
		BeisenHasApply = 1,
		LastGetDate = GETDATE()
	WHERE ID = @id
END
SET NOCOUNT OFF


GO
/****** Object:  StoredProcedure [dbo].[tmpViewTableSIzeGrow]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[tmpViewTableSIzeGrow]
AS
BEGIN
	create table #t(
	Name varchar(100),
	Rows0810 int,
	Rows0811 int,
	Rows0812 int,
	Rows0813 int,
	Rows0814 int
	)
	INSERT #t(Name) SELECT DISTINCt TABLENAME FROM bsTableSizeLog

	DECLARE @I int, @SQL VARCHAR(1000)
	SET @i = 0
	WHILE @I<5
	BEGIN
	SET @Sql = '
	UPDATE a SET a.Rows081' + LTRIM(STR(@I)) + ' = b.Rows 
	FROM #t a, bsTableSizeLog b 
	WHERE a.Name=b.TableName
	And b.coutDate = 2011081' + LTRIM(STR(@I))

	Exec( @Sql)
	SET @I=@I+1
	END

	select *, rows0814*1.0/rows0810
	from #t 
	where rows0814>100000
	order by rows0814*1.0/rows0810 desc

	DROP TABle #t
END














GO
/****** Object:  StoredProcedure [dbo].[updateDeleteFile]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[updateDeleteFile]
@listID VARCHAR(1024)
as 
begin 
    declare @i INT,@ID VARCHAR(50)
    set @i = CHARINDEX(',',@listID)
    while @i > 0
    begin
        set @ID = substring(@listID,1,@i-1)
        update bsDeleteFile set IsDelete = 0
        set @listID = substring(@listID,@i+1,len(@listID))
        set @i = CHARINDEX(',',@listID)
    end
end 














GO
/****** Object:  StoredProcedure [dbo].[v2018_mblAssessTestAnswerUpdateByAnswer]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--####################################################
--添加人：Peter
--添加时间：2018-8-20
--描述：修改个人回答记录
--####################################################
CREATE PROCEDURE [dbo].[v2018_mblAssessTestAnswerUpdateByAnswer]
(
	@PaMainID INT,
	@AnswerID INT,
	@OptionsID INT,
	@AnswerChoice VARCHAR(5)
)
AS
BEGIN
	DECLARE @AssessTestLogID INT

	SELECT @AssessTestLogID = AssessTestLogID
	FROM AssessTestAnswer WITH(NOLOCK) 
	WHERE ID = @AnswerID

	IF NOT EXISTS(
		SELECT 'x' FROM AssessTestLog WITH(NOLOCK) 
		WHERE PaMainID = @PaMainID 
		AND ID = @AssessTestLogID
	)
	BEGIN
		RETURN -1
	END

	UPDATE AssessTestAnswer 
	SET AssessOptionsID = @OptionsID,AnswerDate = GETDATE(),Choice = @AnswerChoice
	WHERE ID = @AnswerID

	IF NOT EXISTS(
		SELECT 'x' FROM AssessTestAnswer WITH(NOLOCK) 
		WHERE AssessOptionsID IS NULL 
		AND AssessTestLogID = @AssessTestLogID
	) --测评问题全部回答完毕
	BEGIN
		EXEC v2018_mblAssessTestLogUpdateByFinish @AssessTestLogID
		RETURN 0
	END
	ELSE
	BEGIN
		RETURN @AssessTestLogID
	END
END

GO
/****** Object:  StoredProcedure [dbo].[v2018_mblAssessTestLogByAnalysisSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--####################################################
--添加人：Peter
--添加时间：2018-8-20
--描述：获取个人测评的详情
--####################################################
CREATE PROCEDURE [dbo].[v2018_mblAssessTestLogByAnalysisSelect]
(
	@PaMainID INT,
	@TestLogID INT
)
AS
BEGIN
	IF NOT EXISTS(SELECT 'x' FROM AssessTestLog WITH(NOLOCK) WHERE ID = @TestLogID AND PaMainID = @PaMainID AND(TextResult IS NOT NULL OR ScoreResult IS NOT NULL))
	BEGIN
		RETURN 
	END

	DECLARE @ResultType TINYINT

	SELECT @ResultType = ResultType
	FROM AssessType WITH(NOLOCK)
	WHERE ID = (
		SELECT AssessTypeID 
		FROM AssessTestLog WITH(NOLOCK)
		WHERE ID = @TestLogID
	)

	IF @ResultType = 1
	BEGIN
		SELECT a.*,b.ReportHtml,b.AttachmentFile,b.Title,c.NeedTime
		FROM AssessTestLog a WITH(NOLOCK)
		LEFT JOIN AssessTypeResult b WITH(NOLOCK) ON b.TextResult = a.TextResult
		LEFT JOIN AssessType c WITH(NOLOCK) ON c.id = a.AssessTypeID 
		WHERE a.ID = @TestLogID
	END
	
	SELECT a.*,c.ShortName,b.Score,d.AssessDimensionGroupID,e.Shortname GroupShortName,e.Name GroupName
	FROM AssessTestAnswer a WITH(NOLOCK)
	LEFT JOIN AssessOptions b WITH(NOLOCK) ON b.ID = a.AssessOptionsID
	LEFT JOIN AssessDimension c WITH(NOLOCK) ON c.ID = b.AssessDimensionID
	LEFT JOIN AssessQuestion d WITH(NOLOCK) ON d.ID = a.AssessQuestionID
	LEFT JOIN AssessDimensionGroup e WITH(NOLOCK) ON e.id = d.AssessDimensionGroupID
	WHERE a.AssessTestLogID = @TestLogID
END


GO
/****** Object:  StoredProcedure [dbo].[v2018_mblAssessTestLogInsert]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--####################################################
--添加人：Peter
--添加时间：2018-8-17
--描述：根据CpInviteID和AssessTypeID 插入一条测试记录
--####################################################
CREATE PROCEDURE [dbo].[v2018_mblAssessTestLogInsert]
(
	@PaMainID INT,
	@CpInviteID INT,
	@AssessTypeID INT
)
AS
BEGIN
	IF @PaMainID = 0
		RETURN 0

	DECLARE @AssessTestLogID INT
	IF @CpInviteID > 0
	BEGIN
		SELECT @AssessTestLogID = ISNULL(ID,0) 
		FROM AssessTestLog WITH(NOLOCK) 
		WHERE AssessCpInviteID = @CpInviteID 
		AND PaMainID = @PaMainID

		IF @AssessTestLogID > 0
		BEGIN
			RETURN @AssessTestLogID
		END
		
		SELECT @AssessTypeID = ISNULL(AssessTypeID,0)
		FROM AssessCpInvite WITH(NOLOCK)
		WHERE ID = @CpInviteID
		AND PaMainID = @PaMainID
	END
	ELSE
	BEGIN
		IF EXISTS(SELECT 'x' FROM AssessTestLog WITH(NOLOCK) WHERE PaMainID = @PaMainID AND AssessCpInviteID IS NULL AND AssessTypeID = @AssessTypeID) AND @CpInviteID = 0
		BEGIN
			DECLARE @ReMainDays INT,@Status TINYINT,@TestLogIDBefore INT
		
			SELECT TOP 1 @Status = Status,@ReMainDays = DATEDIFF(DAY,BeginTime,GETDATE()),@TestLogIDBefore=ID
			FROM AssessTestLog WITH(NOLOCK) 
			WHERE PaMainID = @PaMainID 
			AND AssessCpInviteID IS NULL
			AND AssessTypeID = @AssessTypeID
			ORDER BY BeginTime DESC

			IF @Status = 1
			BEGIN
				RETURN @TestLogIDBefore
			END

			IF @ReMainDays < (SELECT TOP 1 ReTestDay FROM AssessType WITH(NOLOCK) WHERE ID = @AssessTypeID)
			BEGIN
				RETURN -2
			END
		END
	END

	IF @AssessTypeID = 0
		RETURN -1

	--权限判断 是否可以进行测评。
	IF dbo.v2018_CheckHasCompleteCv(@PaMainID) = 0
		RETURN -3
	
	IF @CpInviteID = 0
		SET @CpInviteID = NULL

	INSERT INTO AssessTestLog(PaMainID,AssessTypeID,BeginTime,RemainSeconds,LeaveTimes,IsOpen,Status)
	SELECT @PaMainID,@AssessTypeID,GETDATE(),NeedTime*60,-1,1,1
	FROM AssessType WITH(NOLOCK)
	WHERE ID = @AssessTypeID

	SELECT @AssessTestLogID = @@IDENTITY

	CREATE TABLE #T(
		AssessQuestionID INT,
		AssessDimensionGroupID INT,
		AssessThemeID INT,
		SortNo INT,
		RowNo INT
	)

	DECLARE @AssessThemeID INT,@AssessThemeSortType INT
	DECLARE cur_AssessTheme CURSOR FOR
		SELECT ID,SortType
		FROM AssessTheme WITH(NOLOCK)
		WHERE AssessTypeID = @AssessTypeID
	FOR READ ONLY

	OPEN cur_AssessTheme

	FETCH NEXT FROM cur_AssessTheme INTO @AssessThemeID,@AssessThemeSortType

	WHILE @@FETCH_STATUS = 0
	BEGIN
		IF @AssessThemeSortType = 1 --随机排序
		BEGIN
			SELECT ID,AssessDimensionGroupID,AssessThemeID,SortNo
				,ROW_NUMBER () OVER (PARTITION BY AssessDimensionGroupID ORDER BY NEWID() ASC) RowNo
			INTO #TQuestion
			FROM AssessQuestion WITH(NOLOCK)
			WHERE AssessThemeID = @AssessThemeID

			IF @AssessTypeID = 1 --MBTI特殊处理，因为分组1数量少10个
			BEGIN
				UPDATE #TQuestion
				SET RowNo = RowNo*2-1
				WHERE AssessDimensionGroupID = 1 
			END

			INSERT INTO #T
			SELECT * FROM #TQuestion
			ORDER BY RowNo ASC,AssessDimensionGroupID ASC

			DROP TABLE #TQuestion
		END
		ELSE
		BEGIN
			INSERT INTO #T
			SELECT ID,AssessDimensionGroupID,AssessThemeID,SortNo
				,ROW_NUMBER () OVER (PARTITION BY AssessDimensionGroupID ORDER BY SortNo ASC,ID ASC)
			FROM AssessQuestion WITH(NOLOCK)
			WHERE AssessThemeID = @AssessThemeID
		END
		FETCH NEXT FROM cur_AssessTheme INTO @AssessThemeID,@AssessThemeSortType
	END

	CLOSE cur_AssessTheme
	DEALLOCATE cur_AssessTheme

	INSERT INTO AssessTestAnswer(AssessTestLogID,AssessQuestionID)
	SELECT @AssessTestLogID,AssessQuestionID
	FROM #T

	DROP TABLE #T

	RETURN @AssessTestLogID
END



GO
/****** Object:  StoredProcedure [dbo].[v2018_mblAssessTestLogUpdateByFinish]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--####################################################
--添加人：Peter
--添加时间：2018-8-20
--描述：结束测评并且打分
--####################################################
CREATE PROCEDURE [dbo].[v2018_mblAssessTestLogUpdateByFinish]
(
	@TestLogID INT
)
AS
BEGIN
	--根据不同的测评类型进行评分
	DECLARE @ResultType INT,@AssessTypeID INT
	DECLARE @FinishStatus TINYINT

	SELECT @AssessTypeID = AssessTypeID
	FROM AssessTestLog WITH(NOLOCK)
	WHERE ID = @TestLogID

	SELECT @ResultType = ResultType
	FROM AssessType WITH(NOLOCK)
	WHERE ID = @AssessTypeID

	IF @ResultType = 1  --文本式计分规则
	BEGIN
		IF EXISTS(	--是否正常完成了所有的问题
			SELECT 'x' FROM AssessTestAnswer a WITH(NOLOCK)
			LEFT JOIN AssessQuestion b WITH(NOLOCK) ON b.id = a.AssessquestionID
			LEFT JOIN AssessDimensionGroup c WITH(NOLOCK) ON c.id = b.AssessDimensionGroupid
			WHERE a.AssessOptionsID IS NOT NULL
			GROUP BY c.id
			HAVING COUNT(1) = 0
		)
		BEGIN
			SET @FinishStatus = 3
		END
		ELSE
		BEGIN
			SET @FinishStatus = 2

			DECLARE @Result VARCHAR(10)
			SET @Result = ''

			IF @AssessTypeID = 1 --MBTI计算规则。
			BEGIN
				--分组查询到临时表中
				SELECT AssessDimensionGroupID,ID DimensionID,ShortName,
					(	
						SELECT COUNT(1) 
						FROM AssessTestAnswer WITH(NOLOCK)
						WHERE AssessOptionsID IS NOT NULL
						AND AssessOptionsID IN(
							SELECT ID 
							FROM AssessOptions WITH(NOLOCK)
							WHERE AssessDimensionID = AssessDimension.ID
						)
						AND AssessTestLogID = @TestLogID
					) AnswerCount
				INTO #T
				FROM AssessDimension WITH(NOLOCK)
				WHERE AssessDimensionGroupID IN(
					SELECT ID 
					FROM AssessDimensionGroup WITH(NOLOCK)
					WHERE AssessTypeID = @AssessTypeID
				)

				SELECT *,ROW_NUMBER() OVER(PARTITION BY AssessDimensionGroupID ORDER BY AnswerCount DESC,DimensionID ASC) RowNum
				INTO #T2
				FROM #T

				--拼接结果
				SELECT @Result = @Result + ShortName
				FROM #T2
				WHERE RowNum = 1

				--修改结果
				UPDATE Assesstestlog
				SET TextResult = @Result
				WHERE ID = @TestLogID

				DROP TABLE #T
				DROP TABLE #T2
			END
			ELSE IF @AssessTypeID = 2  --霍兰德计分规则
			BEGIN
				SELECT a.*,b.Score,d.shortname 
				INTO #T3
				FROM AssessTestAnswer a WITH(NOLOCK) 
				LEFT JOIN AssessOptions b WITH(NOLOCK) ON b.id = a.AssessOptionsID 
				LEFT JOIN AssessQuestion c WITH(NOLOCK) ON c.id = a.AssessQuestionID 
				LEFT JOIN AssessDimensionGroup d WITH(NOLOCK) ON d.id = c.AssessDimensionGroupID 
				WHERE AssessTestLogID = @TestLogID

				SELECT ShortName,SUM(Score) Score,0 AScoreCnt,0 BScoreCnt,0 ShortOrder
				INTO #T4
				FROM #T3
				GROUP BY ShortName

				DELETE FROM #T4
				WHERE Score < (SELECT MAX(Score) FROM #T4)

				IF(SELECT COUNT(1) FROM #T4) = 1
				BEGIN
					SELECT @Result = ShortName
					FROM #T4
				END
				ELSE
				BEGIN
					UPDATE #T4
					SET AScoreCnt = (
						SELECT COUNT(1) 
						FROM #T3
						WHERE Choice = 'A'
						AND Score = 1
						AND shortname = #T4.ShortName
					),
					BScoreCnt = (
						SELECT COUNT(1) 
						FROM #T3
						WHERE Choice = 'B'
						AND Score = 1
						AND shortname = #T4.ShortName
					),
					ShortOrder = 
						CASE ShortName 
							WHEN 'C' THEN 0
							WHEN 'R' THEN 1
							WHEN 'I' THEN 2
							WHEN 'E' THEN 3
							WHEN 'S' THEN 4
							WHEN 'A' THEN 5
							ELSE 99
						END

					SELECT TOP 1 @Result = ShortName
					FROM #T4 
					ORDER BY AScoreCnt ASC,BScoreCnt DESC,ShortOrder ASC
				END

				UPDATE Assesstestlog
				SET TextResult = @Result
				WHERE ID = @TestLogID

				DROP TABLE #T3
				DROP TABLE #T4
			END
		END
	END
	
	--修改测评状态
	UPDATE Assesstestlog
	SET Status = @FinishStatus,EndTime = GETDATE()
	WHERE ID = @TestLogID

	RETURN 1
END


GO
/****** Object:  StoredProcedure [dbo].[v2018_pcCaCvIntentionSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--################################################################
--创建人：Lucifer
--创建时间：2018-7-23
--描述：获取个人应聘邀请列表
--################################################################
CREATE PROCEDURE [dbo].[v2018_pcCaCvIntentionSelect]
(
    @Where VARCHAR(1000), 
    @Order VARCHAR(100)
)
AS
SET NOCOUNT ON
BEGIN
    SET @Where = dbo.SafeSQL(@Where)
    SET @Order = dbo.SafeSQL(@Order)
    DECLARE @SQL AS VARCHAR(2000)
    SET @SQL = 'SELECT JobID, cvMainID, a.AddDate, b.Name as JobName, b.IssueDate, b.IssueEnd, Reply, ReplyDate, d.Name cvName, 
            b.dcRegionID, b.IsDelete, c.Name as cpName, c.ID as cpID, c.HasLicence, c.IsAgent, c.MemberType, a.ID, 
            b.dcSalaryId, b.dcSalaryIdMax, b.SecondId EnJobID, c.SecondId EnCpMainID, dbo.GetCaOnlineStatus(b.caMainID) AS IsOnline,
            b.Welfare1, b.Welfare2, b.Welfare3, b.Welfare4, b.Welfare5, b.Welfare6, b.Welfare7, b.Welfare8, 
            b.Welfare9, b.Welfare10, b.Welfare11, b.Welfare12, b.Welfare13, b.Welfare14, b.Welfare15, b.Welfare16, 
            b.Welfare17, b.Welfare18, b.Welfare19, c.ReplyRate, c.LogoFile LogoUrl, b.CaMainID, b.Valid JobValid,
			dbo.GetCvMatch(a.cvMainID, a.JobID) cvMatch,
			(SELECT COUNT(1) FROM exJobApply WHERE cvMainId = a.cvMainId AND JobId = a.JobId) IsApply
            FROM caCvIntention a WITH(NOLOCK)
            INNER JOIN Job b WITH(NOLOCK) ON a.JobID = b.ID 
            INNER JOIN cpMain c WITH(NOLOCK) ON b.cpMainID = c.ID
            INNER JOIN cvMain d WITH(NOLOCK) ON a.cvMainID = d.ID
        WHERE PersonDeleted = 0'

    IF LEN(@Where) > 0
        SET @SQL = @SQL + ' AND ' + @Where

    IF LEN(@Order) > 0
        SET @SQL = @SQL + ' ORDER BY '+@Order

    EXEC(@SQL)
END
SET NOCOUNT OFF

GO
/****** Object:  StoredProcedure [dbo].[v2018_pcCaCvViewLogSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--################################################################
--创建人：Lucifer
--创建时间：2018-7-23
--描述：谁在关注我
--################################################################
CREATE PROCEDURE [dbo].[v2018_pcCaCvViewLogSelect]
(
	@cvMainIds VARCHAR(1000),
	@Page SMALLINT
)
AS
SET NOCOUNT ON
BEGIN
	IF @cvMainIds = ''
		RETURN

	SET @cvMainIds = dbo.FormatIDS(@cvMainIds)

	SELECT ROW_NUMBER() OVER(ORDER BY AddDate DESC) TitleID, caMainId, cvMainId, AddDate, NULL JobId , 0 IsApply 
	INTO #1
	FROM caCvviewLog WITH(NOLOCK INDEX(IX_caCvViewLog_cvMainID))
	WHERE cvMainId IN(SELECT a FROM dbo.fnSplit(@cvMainIds, ','))
	AND EXISTS(SELECT TOP 1 'X' FROM JobPublish WITH(NOLOCK) WHERE caMainID = caCvviewLog.caMainID)

	SELECT * INTO #T
	FROM #1
	WHERE TitleID > (@Page - 1) * 20 AND TitleID <= @Page * 20
        
    UPDATE #T SET IsApply = 1
    WHERE EXISTS(
		SELECT TOP 1 'X' FROM exJobApply a WITH(NOLOCK), JobPublish b WITH(NOLOCK)
		WHERE a.JobID = b.ID AND a.cvMainID = #T.cvMainID AND b.caMainID = #T.caMainID
	)

	UPDATE #T SET JobId = (SELECT TOP 1 a.ID FROM JobPublish a WITH(NOLOCK), caMain b WITH(NOLOCK), cpMainPublish c WITH(NOLOCK)
	WHERE a.cpMainId = b.cpMainID AND b.cpMainID = c.ID AND a.dcJobTypeId IN(SELECT dcJobTypeID FROM cvJobType WITH(NOLOCK) WHERE cvMainId = #T.cvMainId)
		AND b.Id = #T.caMainID ORDER BY a.RefreshDate DESC)
		
	UPDATE #T SET JobId = (SELECT TOP 1 a.ID FROM JobPublish a WITH(NOLOCK), caMain b WITH(NOLOCK), cpMainPublish c WITH(NOLOCK)
	WHERE a.cpMainId = b.cpMainID AND b.cpMainID = c.ID AND LEFT(a.dcJobTypeId, 2) IN(SELECT dcJobTypeID FROM cvJobType WITH(NOLOCK) WHERE cvMainId = #T.cvMainId)
		AND b.Id = #T.caMainID ORDER BY a.RefreshDate DESC) WHERE JobId IS NULL
	
	UPDATE #T SET JobId = (SELECT TOP 1 a.ID FROM JobPublish a WITH(NOLOCK), caMain b WITH(NOLOCK), cpMainPublish c WITH(NOLOCK)
	WHERE a.cpMainId = b.cpMainID AND b.cpMainID = c.ID
		AND b.Id = #T.caMainID ORDER BY a.RefreshDate DESC) WHERE JobId IS NULL
	
	SELECT a.caMainId, a.cvMainId, a.AddDate, b.Name as caName, d.*, d.Id JobId, d.Name JobName, 
		d.SecondId EnJobId, d.Valid JobValid,
		b.Email, b.Mobile, b.Telephone, b.Gender, b.IsPhoneHide, b.IsNameHide, b.IsMobileHide, 
		c.Name cpName, c.Address, c.ID cpID, c.HasLicence, c.IsAgent, e.Name cvName, 
		c.Membertype, c.dcRegionId, c.SecondId EnCpMainID, c.LogoFile LogoUrl, dbo.GetCaOnlineStatus(b.ID) IsOnline,
		(SELECT COUNT(1) FROM exJobApply WHERE cvMainId = a.cvMainId AND JobId = a.JobId) IsApply
	FROM #T a WITH(NOLOCK)
	INNER JOIN caMain b WITH(NOLOCK) ON a.caMainID = b.ID
	INNER JOIN cpMain c WITH(NOLOCK) ON c.ID = b.cpMainId
	INNER JOIN cvMain e WITH(NOLOCK) ON a.cvMainId = e.Id
	INNER JOIN JobPublish d WITH(NOLOCK) ON a.JobId = d.Id
	
	SELECT COUNT(1) FROM #1
END 
SET NOCOUNT OFF
GO
/****** Object:  StoredProcedure [dbo].[v2018_pcChatOnLineByPaMainIDSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--####################################
--添加人：Lucifer
--添加时间：2018-7-12
--描述：获取个人聊天列表，显示最新聊天记录
--####################################
CREATE PROCEDURE [dbo].[v2018_pcChatOnLineByPaMainIDSelect]
(
    @PaMainID INT	--求职者的ID
)
AS
SET NOCOUNT ON
BEGIN	
	CREATE TABLE #ChatLog
	(
		caMainID INT,
		cvMainID INT,
		LastMessage VARCHAR(MAX),
		LastReceiverDate SMALLDATETIME,
		Initiative TINYINT
	)
	INSERT INTO #ChatLog
	SELECT 
		a.caMainID,
		a.cvMainID,
		(SELECT TOP 1 CASE MessageType
			WHEN 1 THEN [Message]
			WHEN 2 THEN '[表情]'
			WHEN 3 THEN '[图片]'
			WHEN 4 THEN '[职位]'
			WHEN 5 THEN '[面试通知]'
			ELSE '' END FROM ChatOnlineLog WITH(NOLOCK) WHERE ChatOnlineID = MAX(a.ID) ORDER BY ID DESC),
		MAX(b.Adddate),
		(SELECT Initiative FROM ChatOnline WITH(NOLOCK) WHERE ID = MIN(a.ID))
	FROM ChatOnline a WITH(NOLOCK), ChatOnlineLog b WITH(NOLOCK)
	WHERE a.ID = b.ChatOnlineID
		AND a.cvMainId IN (SELECT ID FROM cvMain WITH(NOLOCK) WHERE paMainID = @PaMainID) --当前个人用户
	GROUP BY a.caMainID, a.cvMainID

	SELECT
		a.*,
		dbo.GetCaName(b.ID) CaName,
		c.Name CpName,
		d.Name CvName,
		c.SecondID EnCpMainID,
		c.HasLicence,
		c.MemberType,
		c.IsAgent,
		dbo.GetCpLogo(c.ID) CpLogo
	FROM #ChatLog a WITH(NOLOCK), caMain b WITH(NOLOCK), cpMain c WITH(NOLOCK), cvMain d WITH(NOLOCK)
	WHERE a.caMainID = b.ID AND b.cpMainID = c.ID AND a.cvMainID = d.ID
	ORDER BY LastReceiverDate DESC
END
SET NOCOUNT OFF
GO
/****** Object:  StoredProcedure [dbo].[v2018_pcCvAppendixDelete]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2018.6.27
--创建人：Lucifer
--说明：删除证书
--#####################################################
CREATE PROCEDURE [dbo].[v2018_pcCvAppendixDelete] 
	@ID INT,
	@paMainID INT
AS
SET NOCOUNT ON
BEGIN TRAN
	BEGIN TRY
		DECLARE @cvMainID AS INT
		SELECT @cvMainID = cvMainID FROM cvAppendix WITH(NOLOCK INDEX(PK_cvAppendix)) WHERE ID = @ID
		IF NOT EXISTS(SELECT 'X' FROM cvMain WITH(NOLOCK) WHERE paMainID = @paMainID AND ID = @cvMainID)
			GOTO ERR

		DELETE FROM bsCvModify WHERE SubID = @ID AND Location LIKE 'c%'
		DELETE FROM cvAppendix WHERE ID = @ID

		IF (SELECT COUNT(1) FROM cvAppendix WITH(NOLOCK INDEX(PK_cvAppendix)) WHERE cvMainID = @cvMainID) = 0
		BEGIN
			EXEC v2018_pcCvMainByCvLevelUpdate 2, @cvMainID, 10, 0
		END
		ELSE
		BEGIN
			UPDATE cvMain SET cvLevel = cvLevel WHERE ID = @cvMainID
		END
	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH
COMMIT TRAN
RETURN 1
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END
SET NOCOUNT OFF
GO
/****** Object:  StoredProcedure [dbo].[v2018_pcCvAppendixSave]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--####################################################
--添加人：Lucifer
--添加时间：2018-6-27
--描述：保存证书
--返回值 0 失败 >0成功 -1超过最大限制
--####################################################
CREATE PROCEDURE [dbo].[v2018_pcCvAppendixSave]
(
	@ID INT,
	@cvMainID INT,
	@dcAppendixID INT,
	@Name VARCHAR(200),
	@NameEng VARCHAR(250),
	@Description NVARCHAR(200),
	@DescriptionEng VARCHAR(1000),
	@AccessDate SMALLINT,
	@paMainID INT,
	@IP VARCHAR(31)
)
AS
SET NOCOUNT ON
BEGIN TRAN
	--检查是否是该账号的简历
	IF NOT EXISTS(SELECT 'X' FROM cvMain WITH(NOLOCK) WHERE ID = @cvMainID AND paMainID = @paMainID)
		GOTO ERR
	--检查是否是该简历的证书
	IF @ID > 0
	BEGIN
		IF NOT EXISTS(SELECT 'X' FROM CvAppendix WITH(NOLOCK INDEX(PK_CvAppendix)) WHERE ID = @ID AND cvMainID = @cvMainID)
		BEGIN
			GOTO ERR
		END
	END
	
	IF EXISTS(SELECT 'X' FROM CvAppendix WITH(NOLOCK INDEX(PK_CvAppendix)) WHERE ID <> @ID AND cvMainID = @cvMainID AND dcAppendixID = @dcAppendixID AND @dcAppendixID <> 999)
		GOTO ERR

	BEGIN TRY
		SET @Name = dbo.v2018_SetVarcharNull(@Name)
		SET @NameEng = dbo.v2018_SetVarcharNull(@NameEng)
		SET @Description = dbo.v2018_SetVarcharNull(@Description)
		SET @DescriptionEng = dbo.v2018_SetVarcharNull(@DescriptionEng)

		DECLARE @NameOld VARCHAR(200)
		DECLARE @NameEngOld VARCHAR(250)
		DECLARE @DescriptionOld NVARCHAR(200)
		DECLARE @DescriptionEngOld VARCHAR(1000)

		IF @ID = 0
		BEGIN
			--证书最多10个
			IF (SELECT COUNT(1) FROM CvAppendix WITH(NOLOCK INDEX(PK_CvAppendix)) WHERE cvMainID = @cvMainID) >= 10
				GOTO ERRMAX

			INSERT INTO CvAppendix(cvMainID, dcAppendixID, [Name], NameEng, [Description], DescriptionEng, AccessDate)
			VALUES(@cvMainID, @dcAppendixID, @Name, @NameEng, @Description, @DescriptionEng, @AccessDate)

			SET @ID = @@IDENTITY
		END
		ELSE
		BEGIN
			SELECT @NameOld = [Name], @NameEngOld = NameEng,
				@DescriptionOld = [Description], @DescriptionEngOld = DescriptionEng
			FROM CvAppendix WITH(NOLOCK INDEX(PK_CvAppendix)) WHERE ID = @ID

			UPDATE CvAppendix SET
				dcAppendixID = @dcAppendixID,
				[Name] = @Name,
				NameEng = @NameEng,
				[Description] = @Description,
				DescriptionEng = @DescriptionEng,
				AccessDate = @AccessDate
			WHERE ID = @ID
		END

		--添加审核记录
		IF @dcAppendixID = 999
		BEGIN
			EXEC v2018_pcCvModifyInsert @paMainID, @cvMainID, @ID, @Name, @NameOld, 'cc1', @IP
			EXEC v2018_pcCvModifyInsert @paMainID, @cvMainID, @ID, @NameEng, @NameEngOld, 'ce1', @IP
		END		
		EXEC v2018_pcCvModifyInsert @paMainID, @cvMainID, @ID, @Description, @DescriptionOld, 'cc2', @IP
		EXEC v2018_pcCvModifyInsert @paMainID, @cvMainID, @ID, @DescriptionEng, @DescriptionEngOld, 'ce2', @IP

		--更新证书的CvLevel
		IF @Name IS NOT NULL
			EXEC v2018_pcCvMainByCvLevelUpdate 0, @cvMainID, 10, 1
	
		IF @NameEng IS NOT NULL
			EXEC v2018_pcCvMainByCvLevelUpdate 1, @cvMainID, 10, 1
	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH
COMMIT TRAN
RETURN @ID
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END
ERRMAX:
BEGIN
	ROLLBACK TRAN
	RETURN -1
END
SET NOCOUNT OFF
GO
/****** Object:  StoredProcedure [dbo].[v2018_pcCvEducationDelete]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2018.6.27
--创建人：Lucifer
--说明：删除教育背景
--#####################################################
CREATE PROCEDURE [dbo].[v2018_pcCvEducationDelete] 
	@ID INT,
	@paMainID INT
AS
SET NOCOUNT ON
BEGIN TRAN
	BEGIN TRY
		DECLARE @cvMainID AS INT
		SELECT @cvMainID = cvMainID FROM cvEducation WITH(NOLOCK INDEX(PK_cvEducation)) WHERE ID = @ID
		IF NOT EXISTS(SELECT 'X' FROM cvMain WITH(NOLOCK) WHERE paMainID = @paMainID AND ID = @cvMainID)
			GOTO ERR

		--教育背景至少保留一个，不能够全部删除
		IF (SELECT COUNT(1) FROM cvEducation WITH(NOLOCK INDEX(PK_cvEducation)) WHERE cvMainID = @cvMainID) = 1
			GOTO ERRNEED

		DELETE FROM bsCvModify WHERE SubID = @ID AND Location LIKE 'd%'
		DELETE FROM cvEducation WHERE ID = @ID

		--更新cvMain中的最高学历和专业
		EXEC v2018_pcCvMainByDegreeUpdate @cvMainID

		UPDATE cvMain SET cvLevel = cvLevel WHERE ID = @cvMainID
	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH
COMMIT TRAN
RETURN 1
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END
ERRNEED:
BEGIN
	ROLLBACK TRAN
	RETURN -1
END
SET NOCOUNT OFF

GO
/****** Object:  StoredProcedure [dbo].[v2018_pcCvEducationSave]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--####################################################
--添加人：Lucifer
--添加时间：2018-6-27
--描述：保存教育背景
--返回值 0 失败 >0成功 -1超过最大限制
--####################################################
CREATE PROCEDURE [dbo].[v2018_pcCvEducationSave]
(
	@ID INT,
	@cvMainID INT,
	@GraduateCollage NVARCHAR(50),
	@GraduateCollageEng VARCHAR(250),
	@Graduation INT,
	@dcMajorID SMALLINT,
	@MajorName NVARCHAR(20),
	@MajorNameEng VARCHAR(100),
	@Degree TINYINT,
	@EduType TINYINT,
	@Details NVARCHAR(1000),
	@DetailsEng VARCHAR(2000),
	@paMainID INT,
	@IP VARCHAR(31)
)
AS
SET NOCOUNT ON
BEGIN TRAN
	--检查是否是该账号的简历
	IF NOT EXISTS(SELECT 'X' FROM cvMain WITH(NOLOCK) WHERE ID = @cvMainID AND paMainID = @paMainID)
		GOTO ERR
	--检查是否是该简历的教育背景
	IF @ID > 0
		IF NOT EXISTS(SELECT 'X' FROM cvEducation WITH(NOLOCK INDEX(PK_cvEducation)) WHERE ID = @ID AND cvMainID = @cvMainID)
			GOTO ERR
	
	--BEGIN TRY
		SET @GraduateCollage = dbo.v2018_SetVarcharNull(@GraduateCollage)
		SET @GraduateCollageEng = dbo.v2018_SetVarcharNull(@GraduateCollageEng)
		SET	@MajorName = dbo.v2018_SetVarcharNull(@MajorName)
		SET	@MajorNameEng = dbo.v2018_SetVarcharNull(@MajorNameEng)
		SET @Details = dbo.v2018_SetVarcharNull(@Details)
		SET @DetailsEng = dbo.v2018_SetVarcharNull(@DetailsEng)

		DECLARE @GraduateCollageOld NVARCHAR(50)
		DECLARE @GraduateCollageEngOld VARCHAR(250)
		DECLARE @MajorNameOld NVARCHAR(20)
		DECLARE @MajorNameEngOld VARCHAR(100)
		DECLARE @DetailsOld NVARCHAR(1000)
		DECLARE @DetailsEngOld VARCHAR(2000)

		IF @ID = 0
		BEGIN
			--教育背景最多5个
			IF (SELECT COUNT(1) FROM cvEducation WITH(NOLOCK INDEX(PK_cvEducation)) WHERE cvMainID = @cvMainID) >= 5
				GOTO ERRMAX

			INSERT INTO cvEducation(cvMainID, GraduateCollage, GraduateCollageEng, Graduation, dcMajorID, MajorName, MajorNameEng, Degree, EduType, Details, DetailsEng)
			VALUES(@cvMainID, @GraduateCollage, @GraduateCollageEng, @Graduation, @dcMajorID, @MajorName, @MajorNameEng, @Degree, @EduType, @Details, @DetailsEng)

			SET @ID = @@IDENTITY
		END
		ELSE
		BEGIN
			SELECT @GraduateCollageOld = GraduateCollage, @GraduateCollageEngOld = GraduateCollageEng,
				@MajorNameOld = MajorName, @MajorNameEngOld = MajorNameEng,
				@DetailsOld = Details, @DetailsEngOld = DetailsEng
			FROM cvEducation WITH(NOLOCK INDEX(PK_cvEducation)) WHERE ID = @ID

			UPDATE cvEducation SET
				GraduateCollage = @GraduateCollage,
				GraduateCollageEng = @GraduateCollageEng,
				Graduation = @Graduation,
				dcMajorID = @dcMajorID,
				MajorName = @MajorName,
				MajorNameEng = @MajorNameEng,
				Degree = @Degree,
				EduType = @EduType,
				Details = @Details,
				DetailsEng = @DetailsEng
			WHERE ID = @ID
		END

		--添加审核记录
		EXEC v2018_pcCvModifyInsert @paMainID, @cvMainID, @ID, @GraduateCollage, @GraduateCollageOld, 'dc1', @IP
		EXEC v2018_pcCvModifyInsert @paMainID, @cvMainID, @ID, @GraduateCollageEng, @GraduateCollageEngOld, 'de1', @IP
		EXEC v2018_pcCvModifyInsert @paMainID, @cvMainID, @ID, @MajorName, @MajorNameOld, 'dc2', @IP
		EXEC v2018_pcCvModifyInsert @paMainID, @cvMainID, @ID, @MajorNameEng, @MajorNameEngOld, 'de2', @IP
		EXEC v2018_pcCvModifyInsert @paMainID, @cvMainID, @ID, @Details, @DetailsOld, 'dc3', @IP
		EXEC v2018_pcCvModifyInsert @paMainID, @cvMainID, @ID, @DetailsEng, @DetailsEngOld, 'de3', @IP
		
		--更新cvMain中的最高学历和专业
		EXEC v2018_pcCvMainByDegreeUpdate @cvMainID

		--更新教育背景的CvLevel
		IF @GraduateCollage IS NOT NULL
			EXEC v2018_pcCvMainByCvLevelUpdate 0, @cvMainID, 3, 1
	
		IF @GraduateCollageEng IS NOT NULL
			EXEC v2018_pcCvMainByCvLevelUpdate 1, @cvMainID, 3, 1

	--END TRY
	--BEGIN CATCH
	--	GOTO ERR
	--END CATCH
COMMIT TRAN
RETURN @ID
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END
ERRMAX:
BEGIN
	ROLLBACK TRAN
	RETURN -1
END
SET NOCOUNT OFF

GO
/****** Object:  StoredProcedure [dbo].[v2018_pcCvExperienceDelete]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2018.6.27
--创建人：Lucifer
--说明：删除工作经历
--#####################################################
CREATE PROCEDURE [dbo].[v2018_pcCvExperienceDelete] 
	@ID INT,
	@paMainID INT
AS
SET NOCOUNT ON
BEGIN TRAN
	BEGIN TRY
		DECLARE @cvMainID AS INT
		SELECT @cvMainID = cvMainID FROM cvExperience WITH(NOLOCK INDEX(PK_cvExperience)) WHERE ID = @ID
		IF NOT EXISTS(SELECT 'X' FROM cvMain WITH(NOLOCK) WHERE paMainID = @paMainID AND ID = @cvMainID)
			GOTO ERR

		DELETE FROM bsCvModify WHERE SubID = @ID AND Location LIKE 'e%'
		DELETE FROM cvExperience WHERE ID = @ID

		--如果没有工作经历，更新cvLevel
		IF (SELECT COUNT(1) FROM cvExperience WITH(NOLOCK INDEX(PK_cvExperience)) WHERE cvMainID = @cvMainID) = 0
		BEGIN
			EXEC v2018_pcCvMainByCvLevelUpdate 2, @cvMainID, 4, 0
		END
		ELSE
		BEGIN
			UPDATE cvMain SET cvLevel = cvLevel WHERE ID = @cvMainID
		END
	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH
COMMIT TRAN
RETURN 1
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END
SET NOCOUNT OFF

GO
/****** Object:  StoredProcedure [dbo].[v2018_pcCvExperienceSave]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--####################################################
--添加人：Lucifer
--添加时间：2018-6-27
--描述：保存工作经历
--返回值 0 失败 >0成功 -1超过最大限制
--####################################################
CREATE PROCEDURE [dbo].[v2018_pcCvExperienceSave]
(
	@ID INT,
	@cvMainID INT,
	@CompanyName NVARCHAR(30),
	@CompanyNameEng VARCHAR(100),
	@dcIndustryID SMALLINT,
	@dcCompanySizeID SMALLINT,
	@dcJobtypeID SMALLINT,
	@JobName NVARCHAR(20),
	@JobNameEng VARCHAR(100),
	@BeginDate INT,
	@EndDate INT,
	@SubNodeNum TINYINT,
	@Description VARCHAR(MAX),
	@DescriptionEng VARCHAR(MAX),
	@dcCompanyKindID SMALLINT,
	@WorkPlace VARCHAR(6),
	@Dept NVARCHAR(20),
	@DeptEng VARCHAR(100),
	@UpperPost NVARCHAR(20),
	@UpperPostEng VARCHAR(100),
	@dcLeaveResonID TINYINT,
	@paMainID INT,
	@IP VARCHAR(31)
)
AS
SET NOCOUNT ON
BEGIN TRAN
	----检查是否是该账号的简历
	IF NOT EXISTS(SELECT 'x' FROM cvMain WITH(NOLOCK) WHERE ID = @cvMainID AND paMainID = @paMainID)
		GOTO ERR
	----检查是否是该简历的工作经历
	IF @ID > 0
		IF NOT EXISTS(SELECT 'x' FROM cvExperience WITH(NOLOCK INDEX(PK_cvExperience)) WHERE ID = @ID AND cvMainID = @cvMainID)
			GOTO ERR

	BEGIN TRY
		SET @CompanyName = dbo.v2018_SetVarcharNull(@CompanyName)
		SET @CompanyNameEng = dbo.v2018_SetVarcharNull(@CompanyNameEng)
		SET	@JobName = dbo.v2018_SetVarcharNull(@JobName)
		SET	@JobNameEng = dbo.v2018_SetVarcharNull(@JobNameEng)
		SET @Description = dbo.v2018_SetVarcharNull(@Description)
		SET @DescriptionEng = dbo.v2018_SetVarcharNull(@DescriptionEng)
		SET @Dept = dbo.v2018_SetVarcharNull(@Dept)
		SET @DeptEng = dbo.v2018_SetVarcharNull(@DeptEng)
		SET @UpperPost = dbo.v2018_SetVarcharNull(@UpperPost)
		SET @UpperPostEng = dbo.v2018_SetVarcharNull(@UpperPostEng)
		SET @dcCompanyKindID = dbo.v2018_SetIntNull(@dcCompanyKindID)
		SET @WorkPlace = dbo.v2018_SetVarcharNull(@WorkPlace)
		SET @dcLeaveResonID = dbo.v2018_SetIntNull(@dcLeaveResonID)
		SET @dcCompanySizeID = dbo.v2018_SetIntNull(@dcCompanySizeID)

		DECLARE @CompanyNameOld NVARCHAR(30)
		DECLARE @CompanyNameEngOld VARCHAR(100)
		DECLARE @JobNameOld NVARCHAR(20)
		DECLARE @JobNameEngOld VARCHAR(100)
		DECLARE @DescriptionOld NVARCHAR(MAX)
		DECLARE @DescriptionEngOld VARCHAR(MAX)
		DECLARE @DeptOld NVARCHAR(20)
		DECLARE @DeptEngOld VARCHAR(100)
		DECLARE @UpperPostOld NVARCHAR(20)
		DECLARE @UpperPostEngOld VARCHAR(100)

		IF @ID = 0
		BEGIN
			--工作经历最多20个
			IF (SELECT COUNT(1) FROM cvExperience WITH(NOLOCK INDEX(PK_cvExperience)) WHERE cvMainID = @cvMainID) >= 20
				GOTO ERRMAX

			INSERT INTO cvExperience(cvMainID, CompanyName, CompanyNameEng, dcIndustryID, dcCompanySizeID, dcJobtypeID, JobName, JobNameEng, BeginDate, EndDate, SubNodeNum, [Description], DescriptionEng, dcCompanyKindID, WorkPlace, Dept, DeptEng, UpperPost, UpperPostEng, dcLeaveResonID)
			VALUES(@cvMainID, @CompanyName, @CompanyNameEng, @dcIndustryID, @dcCompanySizeID, @dcJobtypeID, @JobName, @JobNameEng, @BeginDate, @EndDate, @SubNodeNum, @Description, @DescriptionEng, @dcCompanyKindID, @WorkPlace, @Dept, @DeptEng, @UpperPost, @UpperPostEng, @dcLeaveResonID)

			SET @ID = @@IDENTITY
		END
		ELSE
		BEGIN
			SELECT @CompanyNameOld = CompanyName, @CompanyNameEngOld = CompanyNameEng,
				@JobNameOld = JobName, @JobNameEngOld = JobNameEng,
				@DescriptionOld = [Description], @DescriptionEngOld = DescriptionEng,
				@DeptOld = Dept, @DeptEngOld = DeptEng,
				@UpperPostOld = UpperPost, @UpperPostEngOld = UpperPostEng
			FROM cvExperience WITH(NOLOCK INDEX(PK_cvExperience)) WHERE ID = @ID

			UPDATE cvExperience SET
				CompanyName = @CompanyName,
				CompanyNameEng = @CompanyNameEng,
				dcIndustryID = @dcIndustryID,
				dcCompanySizeID = @dcCompanySizeID,
				dcJobtypeID = @dcJobtypeID,
				JobName = @JobName,
				JobNameEng = @JobNameEng,
				BeginDate = @BeginDate,
				EndDate = @EndDate,
				SubNodeNum = @SubNodeNum,
				[Description] = @Description,
				DescriptionEng = @DescriptionEng,
				dcCompanyKindID = @dcCompanyKindID,
				WorkPlace = @WorkPlace,
				Dept = @Dept,
				DeptEng = @DeptEng,
				UpperPost = @UpperPost,
				UpperPostEng = @UpperPostEng,
				dcLeaveResonID = @dcLeaveResonID
			WHERE ID = @ID
		END

		--添加审核记录
		EXEC v2018_pcCvModifyInsert @paMainID, @cvMainID, @ID, @CompanyName, @CompanyNameOld, 'ec1', @IP
		EXEC v2018_pcCvModifyInsert @paMainID, @cvMainID, @ID, @CompanyNameEng, @CompanyNameEngOld, 'ee1', @IP
		EXEC v2018_pcCvModifyInsert @paMainID, @cvMainID, @ID, @JobName, @JobNameOld, 'ec2', @IP
		EXEC v2018_pcCvModifyInsert @paMainID, @cvMainID, @ID, @JobNameEng, @JobNameEngOld, 'ee2', @IP
		EXEC v2018_pcCvModifyInsert @paMainID, @cvMainID, @ID, @Description, @DescriptionOld, 'ec3', @IP
		EXEC v2018_pcCvModifyInsert @paMainID, @cvMainID, @ID, @DescriptionEng, @DescriptionEngOld, 'ee3', @IP
		EXEC v2018_pcCvModifyInsert @paMainID, @cvMainID, @ID, @Dept, @DeptOld, 'ec4', @IP
		EXEC v2018_pcCvModifyInsert @paMainID, @cvMainID, @ID, @DeptEng, @DeptEngOld, 'ee4', @IP
		EXEC v2018_pcCvModifyInsert @paMainID, @cvMainID, @ID, @UpperPost, @UpperPostOld, 'ec5', @IP
		EXEC v2018_pcCvModifyInsert @paMainID, @cvMainID, @ID, @UpperPostEng, @UpperPostEngOld, 'ee5', @IP

		--更新工作经历的CvLevel
		IF @CompanyName IS NOT NULL
			EXEC v2018_pcCvMainByCvLevelUpdate 0, @cvMainID, 4, 1
	
		IF @CompanyNameEng IS NOT NULL
			EXEC v2018_pcCvMainByCvLevelUpdate 1, @cvMainID, 4, 1

		--更新简历类型
		UPDATE cvMain SET cvType = 0 WHERE ID = @cvMainID
	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH
COMMIT TRAN
RETURN @ID
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END
ERRMAX:
BEGIN
	ROLLBACK TRAN
	RETURN -1
END
SET NOCOUNT OFF
GO
/****** Object:  StoredProcedure [dbo].[v2018_pcCvLanguageDelete]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2018.6.27
--创建人：Lucifer
--说明：删除语言能力
--#####################################################
CREATE PROCEDURE [dbo].[v2018_pcCvLanguageDelete] 
	@ID INT,
	@paMainID INT
AS
SET NOCOUNT ON
BEGIN TRAN
	BEGIN TRY
		DECLARE @cvMainID AS INT
		SELECT @cvMainID = cvMainID FROM cvLanguage WITH(NOLOCK INDEX(PK_cvLanguage)) WHERE ID = @ID
		IF NOT EXISTS(SELECT 'X' FROM cvMain WITH(NOLOCK) WHERE paMainID = @paMainID AND ID = @cvMainID)
			GOTO ERR

		DELETE FROM bsCvModify WHERE SubID = @ID AND Location LIKE 'h%'
		DELETE FROM cvLanguage WHERE ID = @ID

		--如果没有语言能力，修改cvLevel
		IF (SELECT COUNT(1) FROM cvLanguage WITH(NOLOCK INDEX(PK_cvLanguage)) WHERE cvMainID = @cvMainID) = 0
		BEGIN
			EXEC v2018_pcCvMainByCvLevelUpdate 2, @cvMainID, 7, 0
		END
		ELSE
		BEGIN
			UPDATE cvMain SET cvLevel = cvLevel WHERE ID = @cvMainID
		END
	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH
COMMIT TRAN
RETURN 1
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END
SET NOCOUNT OFF

GO
/****** Object:  StoredProcedure [dbo].[v2018_pcCvLanguageSave]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--####################################################
--添加人：Lucifer
--添加时间：2018-6-27
--描述：保存语言能力
--返回值 0 失败 >0成功 -1超过最大限制
--####################################################
CREATE PROCEDURE [dbo].[v2018_pcCvLanguageSave]
(
	@ID INT,
	@cvMainID INT,
	@LanguageType TINYINT,
	@Mastery TINYINT,
	@ReadWrite TINYINT,
	@Spoken TINYINT,
	@Score NVARCHAR(30),
	@ScoreEng VARCHAR(100),
	@paMainID INT,
	@IP VARCHAR(31)
)
AS
SET NOCOUNT ON
BEGIN TRAN
	----检查是否是该账号的简历
	IF NOT EXISTS(SELECT 'X' FROM cvMain WITH(NOLOCK) WHERE ID = @cvMainID AND paMainID = @paMainID)
		GOTO ERR
	----检查是否是该简历的语言能力
	IF @ID > 0
		IF NOT EXISTS(SELECT 'X' FROM cvLanguage WITH(NOLOCK INDEX(PK_cvLanguage)) WHERE ID = @ID AND cvMainID = @cvMainID)
			GOTO ERR
	
	BEGIN TRY
		SET @Score = dbo.v2018_SetVarcharNull(@Score)
		SET @ScoreEng = dbo.v2018_SetVarcharNull(@ScoreEng)

		DECLARE @ScoreOld NVARCHAR(30)
		DECLARE @ScoreEngOld VARCHAR(100)

		IF @ID = 0
		BEGIN
			--语言能力最多5个
			IF (SELECT COUNT(1) FROM cvLanguage WITH(NOLOCK INDEX(PK_cvLanguage)) WHERE cvMainID = @cvMainID) >= 5
				GOTO ERRMAX

			INSERT INTO cvLanguage(cvMainID, LanguageType, Mastery, [ReadWrite], Spoken, Score, ScoreEng)
			VALUES(@cvMainID, @LanguageType, @Mastery, @ReadWrite, @Spoken, @Score, @ScoreEng)

			SET @ID = @@IDENTITY
		END
		ELSE
		BEGIN
			SELECT @ScoreOld = Score, @ScoreEngOld = ScoreEng
			FROM cvLanguage WITH(NOLOCK INDEX(PK_cvLanguage)) WHERE ID = @ID

			UPDATE cvLanguage SET
				LanguageType = @LanguageType,
				Mastery = @Mastery,
				[ReadWrite] = @ReadWrite,
				Spoken = @Spoken,
				Score = @Score,
				ScoreEng = @ScoreEng
			WHERE ID = @ID
		END

		--添加审核记录
		EXEC v2018_pcCvModifyInsert @paMainID, @cvMainID, @ID, @Score, @ScoreOld, 'hc1', @IP
		EXEC v2018_pcCvModifyInsert @paMainID, @cvMainID, @ID, @ScoreEng, @ScoreEngOld, 'he1', @IP

		--更新语言能力的CvLevel
		EXEC v2018_pcCvMainByCvLevelUpdate 2, @cvMainID, 7, 1
	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH
COMMIT TRAN
RETURN @ID
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END
ERRMAX:
BEGIN
	ROLLBACK TRAN
	RETURN -1
END
SET NOCOUNT OFF
GO
/****** Object:  StoredProcedure [dbo].[v2018_pcCvMainByCvLevelUpdate]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--##########################################
--添加人   Lucifer
--添加时间 2018-6-25
--用途     更新cvLevel
--备注     如果是修改基本信息，则该用户所有简历都更新cvLevel
--         @Type = 2 针对的是多份的无数据的，这样只执行一次该方法即可，不然要执行中英文两次，cvMain触发器也要执行两次
--##########################################
CREATE PROCEDURE [dbo].[v2018_pcCvMainByCvLevelUpdate]
(
	@Type INT,
	@cvMainID INT,
	@Pos INT,
	@cvLevel CHAR(1)
)
AS
SET NOCOUNT ON
BEGIN
	IF @Type = 0
	BEGIN
		IF @Pos = 1
			UPDATE a SET cvLevel = '11' + RIGHT(cvLevel, 8) FROM cvMain a, paMain b WHERE a.paMainID = b.ID AND a.ID = @cvMainID
		ELSE
			UPDATE cvMain SET cvLevel = LEFT(cvLevel, @Pos - 1) + @cvLevel + RIGHT(cvLevel, 10 - @Pos) WHERE ID = @cvMainID
	END
	ELSE IF @Type = 1
	BEGIN
		IF @Pos = 1
			UPDATE a SET cvLevelEng = '11' + RIGHT(cvLevelEng, 8) FROM cvMain a, paMain b WHERE a.paMainID = b.ID AND a.ID = @cvMainID
		ELSE
			UPDATE cvMain SET cvLevelEng = LEFT(cvLevelEng, @Pos - 1) + @cvLevel + RIGHT(cvLevelEng, 10 - @Pos) WHERE ID = @cvMainID
	END
	ELSE IF @Type = 2
	BEGIN
		UPDATE cvMain SET
			cvLevel = LEFT(cvLevel, @Pos - 1) + @cvLevel + RIGHT(cvLevel, 10 - @Pos),
			cvLevelEng = LEFT(cvLevelEng, @Pos - 1) + @cvLevel + RIGHT(cvLevelEng, 10 - @Pos)
		WHERE ID = @cvMainID
	END
		
	UPDATE cvMain SET RefreshDate = GETDATE() WHERE ID = @cvMainID AND DATEADD(HOUR, 1, RefreshDate) < GETDATE()
END
SET NOCOUNT OFF
GO
/****** Object:  StoredProcedure [dbo].[v2018_pcCvMainByDegreeUpdate]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2018.6.27
--创建人：Lucifer
--说明：更新cvMain中的最高学历
--#####################################################
CREATE PROCEDURE [dbo].[v2018_pcCvMainByDegreeUpdate] 
	@cvMainID INT
AS
SET NOCOUNT ON
BEGIN TRY
	DECLARE @dcMajorID SMALLINT
	DECLARE @Degree TINYINT
	SELECT TOP 1 @Degree = Degree, @dcMajorID = dcMajorID FROM cvEducation WITH(NOLOCK)
	WHERE cvMainID = @cvMainID AND Degree = (
		SELECT MAX(Degree) FROM cvEducation WITH(NOLOCK) WHERE cvMainID = @cvMainID
	) ORDER BY ID DESC

	UPDATE cvMain SET Degree = @Degree, dcMajorID = @dcMajorID WHERE ID = @cvMainID
END TRY
BEGIN CATCH

END CATCH
SET NOCOUNT OFF



GO
/****** Object:  StoredProcedure [dbo].[v2018_pcCvMainCreate]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--####################################################
--添加人：Lucifer
--添加时间：2018-7-11
--描述：新建简历
--####################################################
CREATE PROCEDURE [dbo].[v2018_pcCvMainCreate]
(
	@paMainID INT,
	@IP VARCHAR(39)
)
AS
SET NOCOUNT ON
BEGIN TRY
	--已经有3份简历
	IF (SELECT COUNT(*) FROM cvMain WITH(NOLOCK INDEX(IX_cvMain_paMainID)) WHERE paMainID = @paMainID) > 2
	BEGIN
		RETURN 0
	END
	ELSE
	BEGIN
		DECLARE @Mobile VARCHAR(13), @Name VARCHAR(20), @cvLevel AS CHAR(10), @cvLevelEng AS CHAR(10)
		SELECT @cvLevel = '1000000000', @cvLevelEng = '1000000000'

		SELECT @Name = ISNULL([Name], ''), @Mobile = ISNULL(Mobile, '') FROM paMain WITH(NOLOCK INDEX(PK_paMain)) WHERE ID = @paMainID
		IF (LEN(@Mobile) > 0 AND LEN(@Name) > 0)
		BEGIN
			SELECT @cvLevel = '1100000000', @cvLevelEng = '1100000000'	
		END
		BEGIN TRAN
			DECLARE @cvMainID AS INT
			INSERT INTO cvMain(paMainID, [Name], cvLevel, cvLevelEng)
			VALUES(@paMainID, '未完成简历', @cvLevel, @cvLevelEng)
			SET @cvMainID = @@IDENTITY

			INSERT INTO paOperationLog (paMainID,Operation,Details,IP)
			VALUES(@paMainID, 14, '创建简历，编号' + RTRIM(CONVERT(VARCHAR(10),@cvMainID)), @IP)

			UPDATE dcSystemData SET Value = Value + RAND() * 5.4 WHERE ID = 1
		COMMIT
		RETURN @cvMainID
	END	
END TRY
BEGIN CATCH
	PRINT ''
	ROLLBACK TRAN
	RETURN 0
END CATCH
GO
/****** Object:  StoredProcedure [dbo].[v2018_pcCvMainDelete]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--################################################################
--创建人：Lucifer
--创建时间：2018-7-30
--描述：删除简历
--################################################################
CREATE PROCEDURE [dbo].[v2018_pcCvMainDelete]
	@ID INT,
	@paMainID INT,
	@IP VARCHAR(30)
AS
SET NOCOUNT ON
BEGIN TRAN
	BEGIN TRY
		DELETE FROM cvMain WHERE ID = @ID AND paMainID = @paMainID
		IF @@ROWCOUNT > 0
		BEGIN
			INSERT INTO paOperationLog(paMainID, Operation, Details, [IP])
			VALUES(@paMainID, 15, '删除简历，编号' + RTRIM(CONVERT(VARCHAR(10), @ID)), @IP)
		END
	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH
COMMIT TRAN
RETURN 1
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END
GO
/****** Object:  StoredProcedure [dbo].[v2018_pcCvMainSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2018.6.21
--创建人：Lucifer
--说明：获取用户及简历信息
--#####################################################
CREATE PROCEDURE [dbo].[v2018_pcCvMainSelect]
(
	@paMainId INT,
	@cvMainId INT
)
AS
SET NOCOUNT ON
BEGIN
	SELECT a.*, b.[Name] MapPlace, dbo.BirthToAge(a.BirthDay) Age FROM paMain a WITH(NOLOCK)
	LEFT JOIN dcMapPlace b WITH(NOLOCK) ON a.dcMapPlaceID = b.ID
	WHERE a.ID = @paMainId
	SELECT * FROM paPhoto WITH(NOLOCK) WHERE paMainId = @paMainId
    SELECT a.*,
	(
		SELECT DISTINCT (SELECT CONVERT(VARCHAR(6), dcJobTypeID) + ' ' FROM cvJobType WHERE cvMainId = b.cvMainId FOR XML PATH(''))
		FROM cvJobType b WHERE b.cvMainId = a.Id
	) cvJobTypeId,
	(
		SELECT DISTINCT (SELECT CONVERT(VARCHAR(6), dcRegionID) + ' ' FROM cvJobPlace WHERE cvMainId = b.cvMainId FOR XML PATH(''))
		FROM cvJobPlace b WHERE b.cvMainId = a.Id
	) cvJobPlaceId,
	(
		SELECT DISTINCT (SELECT CONVERT(VARCHAR(6), dcIndustryID) + ' ' FROM cvIndustry WHERE cvMainId = b.cvMainId FOR XML PATH(''))
		FROM cvIndustry b WHERE b.cvMainId = a.Id
	) cvIndustryId
	FROM cvMain a WITH(NOLOCK) WHERE a.Id = @cvMainId
    SELECT * FROM cvEducation WITH(NOLOCK) WHERE cvMainId = @cvMainId
    SELECT * FROM cvExperience WITH(NOLOCK) WHERE cvMainId = @cvMainId
    SELECT * FROM cvLanguage WITH(NOLOCK) WHERE cvMainId = @cvMainId
    SELECT * FROM cvTraining WITH(NOLOCK) WHERE cvMainId = @cvMainId
    SELECT * FROM cvProject WITH(NOLOCK) WHERE cvMainId = @cvMainId
    SELECT * FROM cvAppendix WITH(NOLOCK) WHERE cvMainId = @cvMainId
    SELECT * FROM cvAttachment WITH(NOLOCK) WHERE cvMainId = @cvMainId
    SELECT * FROM cvTags WITH(NOLOCK) WHERE cvMainId = @cvMainId
END
SET NOCOUNT OFF
GO
/****** Object:  StoredProcedure [dbo].[v2018_pcCvMainUpdate]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2018.6.21
--创建人：Lucifer
--说明：保存简历信息
--@ModifyType 1、修改简历姓名 2、修改简历/姓名开放 3、修改工作能力 4、修改求职意向
--#####################################################
CREATE PROCEDURE [dbo].[v2018_pcCvMainUpdate]
(
	@cvMainID INT,
	@paMainID INT,
	@Name VARCHAR(30),
	@IsNameHidden BIT,
	@IsCvHidden BIT,
	@Speciality VARCHAR(MAX),
	@SpecialityEng VARCHAR(MAX),
	@RelatedWorkYears TINYINT, 
	@EmployType TINYINT, 
	@dcSalaryID TINYINT, 
	@IsNegotiable TINYINT, 
	@JobType VARCHAR(100), 
	@JobPlace VARCHAR(100), 
	@Industry VARCHAR(100), 
	@IP VARCHAR(39),
	@ModifyType TINYINT
)
AS
SET NOCOUNT ON
BEGIN TRAN
	IF NOT EXISTS(SELECT TOP 1 'X' FROM cvMain WITH(NOLOCK) WHERE ID = @cvMainID AND paMainID = @paMainID)
		GOTO ERR

	--BEGIN TRY
		SET @Name = dbo.v2018_SetVarcharNull(@Name)
		IF @ModifyType = 1 --修改简历姓名
		BEGIN
			UPDATE cvMain SET
				[Name] = @Name
			WHERE ID = @cvMainID
		END
		ELSE IF @ModifyType = 2 --修改简历/姓名开放
		BEGIN
			UPDATE cvMain SET
				IsCvHidden = @IsCvHidden,
				IsNameHidden = @IsNameHidden
			WHERE ID = @cvMainID
		END
		ELSE IF @ModifyType = 3 --修改工作能力
		BEGIN
			DECLARE @SpecialityOld VARCHAR(MAX)
			DECLARE @SpecialityEngOld VARCHAR(MAX)

			--获得原始数据
			SELECT @SpecialityOld = Speciality, @SpecialityEngOld = SpecialityEng
			FROM cvMain WITH(NOLOCK)
			WHERE ID = @cvMainID

			--选填没填置空
			SET @Speciality = dbo.v2018_SetVarcharNull(@Speciality)
			SET @SpecialityEng = dbo.v2018_SetVarcharNull(@SpecialityEng)

			UPDATE cvMain SET
				Speciality = @Speciality,
				SpecialityEng = @SpecialityEng
			WHERE ID = @cvMainID

			--添加审核记录
			EXEC v2018_pcCvModifyInsert @paMainID, @cvMainID, NULL, @Speciality, @SpecialityOld, 'bc2', @IP
			EXEC v2018_pcCvModifyInsert @paMainID, @cvMainID, NULL, @SpecialityEng, @SpecialityEngOld, 'be2', @IP
		END
		ELSE IF @ModifyType = 4 --修改求职意向
		BEGIN
			UPDATE cvMain SET
				RelatedWorkYears = @RelatedWorkYears, 
				EmployType = @EmployType, 
				dcSalaryID = @dcSalaryID, 
				IsNegotiable = @IsNegotiable
			WHERE ID = @cvMainID

			DELETE FROM cvJobPlace WHERE cvMainID = @cvMainID
			INSERT INTO cvJobPlace(cvMainID, dcRegionID)
			SELECT TOP 5 @cvMainID, a FROM dbo.fnSplit(@JobPlace, ' ')

			DELETE FROM cvJobType WHERE cvMainID = @cvMainID
			INSERT INTO cvJobType(cvMainID, dcJobTypeID)
			SELECT TOP 5 @cvMainID, a FROM dbo.fnSplit(@JobType, ' ')

			DELETE FROM cvIndustry WHERE cvMainID = @cvMainID
			INSERT INTO cvIndustry(cvMainID, dcIndustryID)
			SELECT @cvMainID, a FROM dbo.fnSplit(@Industry, ' ')

			IF ISNULL(@Name, '未完成简历') = '未完成简历'
			BEGIN
				SELECT TOP 1 @Name = [Description]
				FROM cvJobPlace a WITH(NOLOCK), dcRegion b WITH(NOLOCK)
				WHERE a.dcRegionID = b.ID AND a.cvMainID = @cvMainID

				SELECT TOP 1 @Name = @Name + '+' + [Description]
				FROM cvJobType a WITH(NOLOCK), dcJobType b WITH(NOLOCK)
				WHERE a.dcJobTypeID = b.ID AND a.cvMainID = @cvMainID

				UPDATE cvMain SET
					[Name] = @Name
				WHERE ID = @cvMainID
			END

			--更新求职意向的cvLevel
			EXEC v2018_pcCvMainByCvLevelUpdate 0, @cvMainID, 6, 1
			EXEC v2018_pcCvMainByCvLevelUpdate 1, @cvMainID, 6, 1

			IF @RelatedWorkYears = 0
			BEGIN
				EXEC v2018_pcCvMainByCvLevelUpdate 0, @cvMainID, 4, 1
				EXEC v2018_pcCvMainByCvLevelUpdate 1, @cvMainID, 4, 1
			END
			ELSE
			BEGIN
				IF NOT EXISTS(SELECT TOP 1 'X' FROM cvExperience WITH(NOLOCK) WHERE cvMainId = @cvMainID)
				BEGIN
					EXEC v2018_pcCvMainByCvLevelUpdate 0, @cvMainID, 4, 0
					EXEC v2018_pcCvMainByCvLevelUpdate 1, @cvMainID, 4, 0
				END
			END
		END
	--END TRY
	--BEGIN CATCH
	--	GOTO ERR
	--END CATCH
COMMIT TRAN
RETURN 1
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END
SET NOCOUNT OFF
GO
/****** Object:  StoredProcedure [dbo].[v2018_pcCvModifyInsert]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#########################################################
--添加人    Lucifer
--添加时间  2018-6-25
--用途      简历待审核数据插入
--#########################################################
CREATE PROCEDURE [dbo].[v2018_pcCvModifyInsert]
(
	@paMainID INT,
	@cvMainID INT,
	@SubID INT,
	@Value VARCHAR(MAX),
	@ValueOld VARCHAR(MAX),
	@ColType VARCHAR(5),
	@IP VARCHAR(31)
)
AS
SET NOCOUNT ON
BEGIN
	SET @Value = dbo.v2018_SetVarcharNull(@Value)
	SET @ValueOld = dbo.v2018_SetVarcharNull(@ValueOld)

	--修改的是paMain信息，将cvMainID置空
	IF LEFT(@ColType, 1) = 'a'
	BEGIN
		SET @cvMainID = NULL
	END
	
	--插入待审核记录
	DELETE FROM bsCvModify WHERE paMainID = @paMainID AND ISNULL(cvMainID, 0) = ISNULL(@cvMainID, 0) AND ISNULL(SubID, 0) = ISNULL(@SubID, 0) AND [Location] = @ColType
	IF @Value <> ISNULL(@ValueOld, '') AND @Value IS NOT NULL
	BEGIN
		INSERT INTO bsCvModify(paMainID, cvMainID, SubID, [Location], ColValue) VALUES(@paMainID, @cvMainID, @SubID, @ColType, @Value)

		IF @ColType = 'ac1'
		BEGIN
			INSERT INTO paOperationLog (paMainID, Operation, Details, [IP]) 
			VALUES(@paMainID, 30, '更新姓名，原姓名：<' + ISNULL(@ValueOld, '') + '>；新姓名：<' + @Value + '>', @IP)
		END
		ELSE IF @ColType = 'ae1'
		BEGIN
			INSERT INTO paOperationLog (paMainID, Operation, Details, [IP]) 
			VALUES(@paMainID, 30, '更新英文名，原英文名：<' + ISNULL(@ValueOld, '') + '>；新英文名：<' + @Value + '>', @IP)
		END
	END
END
SET NOCOUNT OFF



GO
/****** Object:  StoredProcedure [dbo].[v2018_pcCvProjectDelete]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2018.6.27
--创建人：Lucifer
--说明：删除项目经历
--#####################################################
CREATE PROCEDURE [dbo].[v2018_pcCvProjectDelete] 
	@ID INT,
	@paMainID INT
AS
SET NOCOUNT ON
BEGIN TRAN
	BEGIN TRY
		DECLARE @cvMainID AS INT
		SELECT @cvMainID = cvMainID FROM cvProject WITH(NOLOCK INDEX(PK_cvProject)) WHERE ID = @ID
		IF NOT EXISTS(SELECT 'X' FROM cvMain WITH(NOLOCK) WHERE paMainID = @paMainID AND ID = @cvMainID)
			GOTO ERR

		DELETE FROM bsCvModify WHERE SubID = @ID AND Location LIKE 'f%'
		DELETE FROM cvProject WHERE ID = @ID

		IF (SELECT COUNT(1) FROM cvProject WITH(NOLOCK INDEX(PK_cvProject)) WHERE cvMainID = @cvMainID) = 0
		BEGIN
			EXEC v2018_pcCvMainByCvLevelUpdate 2, @cvMainID, 9, 0
		END
		ELSE
		BEGIN
			UPDATE cvMain SET cvLevel = cvLevel WHERE ID = @cvMainID
		END
	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH
COMMIT TRAN
RETURN 1
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END
SET NOCOUNT OFF

GO
/****** Object:  StoredProcedure [dbo].[v2018_pcCvProjectSave]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--####################################################
--添加人：Lucifer
--添加时间：2018-6-27
--描述：保存项目经历
--返回值 0 失败 >0成功 -1超过最大限制
--####################################################
CREATE PROCEDURE [dbo].[v2018_pcCvProjectSave]
(
	@ID INT,
	@cvMainID INT,
	@Name NVARCHAR(50),
	@NameEng VARCHAR(250),
	@StartDate INT,
	@EndDate INT,
	@Description NVARCHAR(1000),
	@DescriptionEng VARCHAR(MAX),
	@Responsibilities NVARCHAR(200),
	@ResponsibilitiesEng VARCHAR(1000),
	@paMainID INT,
	@IP VARCHAR(31)
)
AS
SET NOCOUNT ON
BEGIN TRAN
	----检查是否是该账号的简历
	IF NOT EXISTS(SELECT 'X' FROM cvMain WITH(NOLOCK) WHERE ID = @cvMainID AND paMainID = @paMainID)
		GOTO ERR
	----检查是否是该简历的项目经历
	IF @ID > 0
		IF NOT EXISTS(SELECT 'X' FROM cvProject WITH(NOLOCK INDEX(PK_cvProject)) WHERE ID = @ID AND cvMainID = @cvMainID)
			GOTO ERR
	
	BEGIN TRY
		SET @Name = dbo.v2018_SetVarcharNull(@Name)
		SET @NameEng = dbo.v2018_SetVarcharNull(@NameEng)
		SET @Description = dbo.v2018_SetVarcharNull(@Description)
		SET @DescriptionEng = dbo.v2018_SetVarcharNull(@DescriptionEng)
		SET @Responsibilities = dbo.v2018_SetVarcharNull(@Responsibilities)
		SET @ResponsibilitiesEng = dbo.v2018_SetVarcharNull(@ResponsibilitiesEng)

		DECLARE @NameOld NVARCHAR(50)
		DECLARE @NameEngOld VARCHAR(250)
		DECLARE @DescriptionOld NVARCHAR(1000)
		DECLARE @DescriptionEngOld VARCHAR(MAX)
		DECLARE @ResponsibilitiesOld NVARCHAR(200)
		DECLARE @ResponsibilitiesEngOld VARCHAR(1000)

		IF @ID = 0
		BEGIN
			--项目经历最多10个
			IF (SELECT COUNT(1) FROM cvProject WITH(NOLOCK INDEX(PK_cvProject)) WHERE cvMainID = @cvMainID) >= 10
				GOTO ERRMAX

			INSERT INTO cvProject(cvMainID, [Name], NameEng, StartDate, EndDate, [Description], DescriptionEng, Responsibilities, ResponsibilitiesEng)
			VALUES(@cvMainID, @Name, @NameEng, @StartDate, @EndDate, @Description, @DescriptionEng, @Responsibilities, @ResponsibilitiesEng)

			SET @ID = @@IDENTITY
		END
		ELSE
		BEGIN
			SELECT @NameOld = [Name], @NameEngOld = NameEng,
				@DescriptionOld = [Description], @DescriptionEngOld = DescriptionEng,
				@ResponsibilitiesOld = Responsibilities, @ResponsibilitiesEngOld = ResponsibilitiesEng
			FROM cvProject WITH(NOLOCK INDEX(PK_cvProject)) WHERE ID = @ID

			UPDATE cvProject SET
				[Name] = @Name,
				NameEng = @NameEng,
				StartDate = @StartDate,
				EndDate = @EndDate,
				[Description] = @Description,
				DescriptionEng = @DescriptionEng,
				Responsibilities = @Responsibilities,
				ResponsibilitiesEng = @ResponsibilitiesEng
			WHERE ID = @ID
		END

		--添加审核记录
		EXEC v2018_pcCvModifyInsert @paMainID, @cvMainID, @ID, @Name, @NameOld, 'fc1', @IP
		EXEC v2018_pcCvModifyInsert @paMainID, @cvMainID, @ID, @NameEng, @NameEngOld, 'fe1', @IP
		EXEC v2018_pcCvModifyInsert @paMainID, @cvMainID, @ID, @Description, @DescriptionOld, 'fc2', @IP
		EXEC v2018_pcCvModifyInsert @paMainID, @cvMainID, @ID, @DescriptionEng, @DescriptionEngOld, 'fe2', @IP
		EXEC v2018_pcCvModifyInsert @paMainID, @cvMainID, @ID, @Responsibilities, @ResponsibilitiesOld, 'fc3', @IP
		EXEC v2018_pcCvModifyInsert @paMainID, @cvMainID, @ID, @ResponsibilitiesEng, @ResponsibilitiesEngOld, 'fe3', @IP

		--更新项目经历的CvLevel
		IF @Name IS NOT NULL
			EXEC v2018_pcCvMainByCvLevelUpdate 0, @cvMainID, 9, 1
	
		IF @NameEng IS NOT NULL
			EXEC v2018_pcCvMainByCvLevelUpdate 1, @cvMainID, 9, 1
	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH
COMMIT TRAN
RETURN @ID
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END
ERRMAX:
BEGIN
	ROLLBACK TRAN
	RETURN -1
END
SET NOCOUNT OFF
GO
/****** Object:  StoredProcedure [dbo].[v2018_pcCvTrainingDelete]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2018.6.27
--创建人：Lucifer
--说明：删除培训经历
--#####################################################
CREATE PROCEDURE [dbo].[v2018_pcCvTrainingDelete] 
	@ID INT,
	@paMainID INT
AS
SET NOCOUNT ON
BEGIN TRAN
	BEGIN TRY
		DECLARE @cvMainID AS INT
		SELECT @cvMainID = cvMainID FROM cvTraining WITH(NOLOCK INDEX(PK_cvTraining)) WHERE ID = @ID
		IF NOT EXISTS(SELECT 'X' FROM cvMain WITH(NOLOCK) WHERE paMainID = @paMainID AND ID = @cvMainID)
			GOTO ERR

		DELETE FROM bsCvModify WHERE SubID = @ID AND Location LIKE 'g%'
		DELETE FROM cvTraining WHERE ID = @ID

		IF (SELECT COUNT(1) FROM cvTraining WITH(NOLOCK INDEX(PK_cvTraining)) WHERE cvMainID = @cvMainID) = 0
		BEGIN
			EXEC v2018_pcCvMainByCvLevelUpdate 2, @cvMainID, 8, 0
		END
		ELSE
		BEGIN
			UPDATE cvMain SET cvLevel = cvLevel WHERE ID = @cvMainID
		END
	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH
COMMIT TRAN
RETURN 1
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END
SET NOCOUNT OFF

GO
/****** Object:  StoredProcedure [dbo].[v2018_pcCvTrainingSave]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--####################################################
--添加人：Lucifer
--添加时间：2018-6-27
--描述：保存培训经历
--返回值 0 失败 >0成功 -1超过最大限制
--####################################################
CREATE PROCEDURE [dbo].[v2018_pcCvTrainingSave]
(
	@ID INT,
	@cvMainID INT,
	@StartDate INT,
	@TimeLength TINYINT,
	@TimeUnit TINYINT,
	@Institution NVARCHAR(30),
	@InstitutionEng VARCHAR(150),
	@Course NVARCHAR(50),
	@CourseEng VARCHAR(250),
	@City NVARCHAR(10),
	@CityEng VARCHAR(50),
	@Certificate NVARCHAR(50),
	@CertificateEng VARCHAR(250),
	@Details NVARCHAR(500),
	@DetailsEng VARCHAR(2500),
	@paMainID INT,
	@IP VARCHAR(31)
)
AS
SET NOCOUNT ON
BEGIN TRAN
	----检查是否是该账号的简历
	IF NOT EXISTS(SELECT 'X' FROM cvMain WITH(NOLOCK) WHERE ID = @cvMainID AND paMainID = @paMainID)
		GOTO ERR
	----检查是否是该简历的培训经历
	IF @ID > 0
		IF NOT EXISTS(SELECT 'X' FROM cvTraining WITH(NOLOCK INDEX(PK_cvTraining)) WHERE ID = @ID AND cvMainID = @cvMainID)
			GOTO ERR
	
	BEGIN TRY
		SET @Institution = dbo.v2018_SetVarcharNull(@Institution)
		SET @InstitutionEng = dbo.v2018_SetVarcharNull(@InstitutionEng)
		SET	@Course = dbo.v2018_SetVarcharNull(@Course)
		SET	@CourseEng = dbo.v2018_SetVarcharNull(@CourseEng)
		SET @City = dbo.v2018_SetVarcharNull(@City)
		SET @CityEng = dbo.v2018_SetVarcharNull(@CityEng)
		SET	@Certificate = dbo.v2018_SetVarcharNull(@Certificate)
		SET	@CertificateEng = dbo.v2018_SetVarcharNull(@CertificateEng)
		SET @Details = dbo.v2018_SetVarcharNull(@Details)
		SET @DetailsEng = dbo.v2018_SetVarcharNull(@DetailsEng)

		DECLARE @InstitutionOld NVARCHAR(30)
		DECLARE @InstitutionEngOld VARCHAR(150)
		DECLARE @CourseOld NVARCHAR(50)
		DECLARE @CourseEngOld VARCHAR(250)
		DECLARE @CityOld NVARCHAR(10)
		DECLARE @CityEngOld VARCHAR(50)
		DECLARE @CertificateOld NVARCHAR(50)
		DECLARE @CertificateEngOld VARCHAR(250)
		DECLARE @DetailsOld NVARCHAR(500)
		DECLARE @DetailsEngOld VARCHAR(2500)

		IF @ID = 0
		BEGIN
			--培训经历最多10个
			IF (SELECT COUNT(1) FROM cvTraining WITH(NOLOCK INDEX(PK_cvTraining)) WHERE cvMainID = @cvMainID) >= 10
				GOTO ERRMAX

			INSERT INTO cvTraining(cvMainID, StartDate, TimeLength, TimeUnit, Institution, InstitutionEng, Course, CourseEng, City, CityEng, [Certificate], CertificateEng, Details, DetailsEng)
			VALUES(@cvMainID, @StartDate, @TimeLength, @TimeUnit, @Institution, @InstitutionEng, @Course, @CourseEng, @City, @CityEng, @Certificate, @CertificateEng, @Details, @DetailsEng)

			SET @ID = @@IDENTITY
		END
		ELSE
		BEGIN
			SELECT @InstitutionOld = Institution, @InstitutionEngOld = InstitutionEng,
				@CourseOld = Course, @CourseEngOld = CourseEng,
				@CityOld = City, @CityEngOld = CityEng,
				@CertificateOld = [Certificate], @CertificateEngOld = CertificateEng,
				@DetailsOld = Details, @DetailsEngOld = DetailsEng
			FROM cvTraining WITH(NOLOCK INDEX(PK_cvTraining)) WHERE ID = @ID

			UPDATE cvTraining SET
				StartDate = @StartDate,
				TimeLength = @TimeLength,
				TimeUnit = @TimeUnit,
				Institution = @Institution,
				InstitutionEng =InstitutionEng,
				Course = @Course,
				CourseEng = @CourseEng,
				City = @City,
				CityEng = @CityEng,
				[Certificate] = @Certificate,
				CertificateEng = @CertificateEng,
				Details = @Details,
				DetailsEng = @DetailsEng
			WHERE ID = @ID
		END

		--添加审核记录
		EXEC v2018_pcCvModifyInsert @paMainID, @cvMainID, @ID, @Institution, @InstitutionOld, 'gc1', @IP
		EXEC v2018_pcCvModifyInsert @paMainID, @cvMainID, @ID, @InstitutionEng, @InstitutionEngOld, 'ge1', @IP
		EXEC v2018_pcCvModifyInsert @paMainID, @cvMainID, @ID, @Course, @CourseOld, 'gc2', @IP
		EXEC v2018_pcCvModifyInsert @paMainID, @cvMainID, @ID, @CourseEng, @CourseEngOld, 'ge2', @IP
		EXEC v2018_pcCvModifyInsert @paMainID, @cvMainID, @ID, @City, @CityOld, 'gc3', @IP
		EXEC v2018_pcCvModifyInsert @paMainID, @cvMainID, @ID, @CityEng, @CityEngOld, 'ge3', @IP
		EXEC v2018_pcCvModifyInsert @paMainID, @cvMainID, @ID, @Certificate, @CertificateOld, 'gc4', @IP
		EXEC v2018_pcCvModifyInsert @paMainID, @cvMainID, @ID, @CertificateEng, @CertificateEngOld, 'ge4', @IP
		EXEC v2018_pcCvModifyInsert @paMainID, @cvMainID, @ID, @Details, @DetailsOld, 'gc5', @IP
		EXEC v2018_pcCvModifyInsert @paMainID, @cvMainID, @ID, @DetailsEng, @DetailsEngOld, 'ge5', @IP

		--更新培训经历的CvLevel
		IF @Institution IS NOT NULL
			EXEC v2018_pcCvMainByCvLevelUpdate 0, @cvMainID, 8, 1
	
		IF @InstitutionEng IS NOT NULL
			EXEC v2018_pcCvMainByCvLevelUpdate 1, @cvMainID, 8, 1

	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH
COMMIT TRAN
RETURN @ID
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END
ERRMAX:
BEGIN
	ROLLBACK TRAN
	RETURN -1
END
SET NOCOUNT OFF
GO
/****** Object:  StoredProcedure [dbo].[v2018_pcDcAutoEmailSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2018.6.21
--创建人：Lucifer
--说明：获取随机邮箱
--#####################################################
CREATE PROCEDURE [dbo].[v2018_pcDcAutoEmailSelect]
AS
BEGIN
	IF NOT EXISTS(SELECT TOP 1 'X' FROM dcAutoEmail WITH(NOLOCK) ORDER BY ID)
	BEGIN
		SELECT TOP 0 * INTO #t FROM dcAutoEmail
		INSERT #t 
		SELECT TOP 10000 LEFT(NEWID(), 3) + '_' + LEFT(NEWID(), 2) + '@your_email.com' FROM cpMain
		UPDATE #t SET Email = CHAR(65 + id % 26) + Email

		DELETE a
		FROM #t a, dcAutoEmail b
		WHERE a.Email = b.Email

		DELETE a
		FROM #t a, paMain b
		WHERE a.Email = b.Email

		DELETE a
		FROM #t a, Resume_XinXi b
		WHERE a.Email = b.Email

		INSERT INTO dcAutoEmail SELECT DISTINCT Email FROM #t
	END
	DECLARE @Email VARCHAR(50)
	SELECT TOP 1 @Email = Email FROM dcAutoEmail ORDER BY ID
	DELETE FROM dcAutoEmail WHERE Email = @Email
	SELECT @Email
END

GO
/****** Object:  StoredProcedure [dbo].[v2018_pcExImageInsert]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--####################################################
--添加人：Lucifer
--添加时间：2018-6-27
--描述：上传照片中转
--####################################################
CREATE PROCEDURE [dbo].[v2018_pcExImageInsert]
(
	@OutID INT,
	@OutType INT,
	@UID VARCHAR(20) OUTPUT
)
AS
BEGIN
	DECLARE @T AS VARCHAR(20)
	SET @T = CONVERT(VARCHAR(20), CONVERT(DECIMAL(18,12),GETDATE()))
	SET @T = RTRIM(CONVERT(VARCHAR(12), @OutID)) + '_' + RIGHT(@T,8)
	Insert Into exImage(OutID,OutType,UniqueID)
	Values(@OutID,@OutType,@T)
	SET @UID = @T
END
GO
/****** Object:  StoredProcedure [dbo].[v2018_pcExInterViewSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--################################################################
--创建人：Lucifer
--创建时间：2018-7-23
--描述：个人面试通知
CREATE PROCEDURE [dbo].[v2018_pcExInterViewSelect]
(
    @Where VARCHAR(1000),
    @Order VARCHAR(100)
)
AS
SET NOCOUNT ON
BEGIN
    SET @Where = dbo.SafeSQL(@Where)
    SET @Order = dbo.SafeSQL(@Order)
    DECLARE @SQL VARCHAR(2000)
    SET @SQL = 'SELECT a.ID, a.JobID, a.cvMainID, a.InterviewDate, a.InterViewPlace, a.LinkMan, a.Telephone, a.Remark, 
	a.AddDate, a.Reply, a.ReplyMessage, a.Replydate, a.Result, a.ResultDate, a.CompanyDeleted, a.CompanyDeleteDate,
	a.PersonDeleted, a.PersonDeleteDate, a.ViewDate, b.*, b.Name JobName, c.Name cpName, c.ID cpID, c.HasLicence, 
	c.IsAgent, d.Name cvName, c.Membertype, b.SecondId EnJobID, c.SecondId EnCpMainID, 
	dbo.GetCaOnlineStatus(b.caMainID) IsOnline, b.CaMainID, c.LogoFile LogoUrl, b.Valid JobValid
	FROM exInterView a WITH(NOLOCK)
	INNER JOIN Job b WITH(NOLOCK) ON b.ID = a.JobID
	INNER JOIN cpMain c WITH(NOLOCK) ON b.cpMainID = c.ID
	INNER JOIN cvMain d WITH(NOLOCK) ON a.cvMainID = d.ID
    WHERE PersonDeleted=0'
    IF LEN(@Where) > 0
        SET @SQL = @SQL + ' AND ' + @Where
    IF LEN(@Order) > 0
        SET @SQL = @SQL + ' ORDER BY ' + @Order
    EXEC(@SQL)
END
SET NOCOUNT OFF
GO
/****** Object:  StoredProcedure [dbo].[v2018_pcExInterViewUpdate]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--################################################################
--创建人：Lucifer
--创建时间：2018-7-23
--描述：答复面试通知
--################################################################
CREATE PROCEDURE [dbo].[v2018_pcExInterViewUpdate]
(
    @ID INT,
    @Reply TINYINT,
    @ReplyMessage VARCHAR(500),
    @paMainId INT
)
AS
SET NOCOUNT ON
BEGIN
    UPDATE exInterView SET
		Reply = @Reply,
		ReplyMessage = dbo.v2018_SetVarcharNull(@ReplyMessage),
		ReplyDate = GETDATE()
    WHERE ID = @ID
		AND cvMainId IN(SELECT ID FROM cvMain WITH(NOLOCK) WHERE paMainId = @paMainId)

	IF @@ROWCOUNT = 0
	BEGIN
		SELECT '0' Result
		RETURN
	END

	DECLARE @ReplyInfo NVARCHAR(20)
	IF @Reply = 1
	BEGIN
        SET @ReplyInfo = '赴约'
	END
    ELSE
	BEGIN
        SET @ReplyInfo = '不赴约'
	END

	INSERT INTO paPushLog(paMainID, PushMessage, PushType) 
    SELECT a.caMainID, e.[Name] + '回复' + @ReplyInfo, 13 
	FROM caIOSBind a WITH(NOLOCK)
	INNER JOIN Job b WITH(NOLOCK) ON a.caMainID = b.caMainID
	INNER JOIN exInterview c WITH(NOLOCK) ON b.ID = c.JobID
	INNER JOIN cvMain d WITH(NOLOCK) ON c.cvMainId = d.ID
	INNER JOIN paMain e WITH(NOLOCK) ON d.paMainId = e.ID
	WHERE c.ID = @ID

	INSERT wxMessageSend2(TemplateType, WxFansID, PaMainId, CvMainId, CpMainID, CaMainId, JobId, AddDate)
    SELECT 15, b.ID, @paMainID, d.cvMainID, c.cpMainID, c.caMainID, c.ID, GETDATE()
    FROM paLoginContact a WITH(NOLOCK)
	INNER JOIN wxFans b WITH(NOLOCK) ON a.OpenID = b.OpenID
	INNER JOIN Job c WITH(NOLOCK) ON c.caMainID = a.paMainID
	INNER JOIN exInterview d WITH(NOLOCK) ON d.JobID = c.ID
    WHERE a.ContactType = 101 AND d.ID = @ID
	
	SELECT TOP 1 '1' Result, a.[Name] CompanyName, b.[Name] JobName, a.ConsultantId, c.Email, a.ID, d.Reply, d.cvMainID
    FROM cpMain a WITH(NOLOCK), Job b WITH(NOLOCK), caMain c WITH(NOLOCK), exInterview d WITH(NOLOCK)
    WHERE a.ID = b.cpMainID
    AND b.caMainID = c.ID
	AND b.ID = d.JobId
    AND d.ID = @ID
END
SET NOCOUNT OFF
GO
/****** Object:  StoredProcedure [dbo].[v2018_pcExJobApplyByRemindDateUpdate]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2018.7.26
--创建人：Lucifer
--说明：申请的职位求答复
--#####################################################
CREATE PROCEDURE  [dbo].[v2018_pcExJobApplyByRemindDateUpdate]
(
	@ID INT,
	@paMainID INT
)
AS
SET NOCOUNT ON
BEGIN 
	UPDATE exJobApply SET
		RemindDate  = GETDATE()
	WHERE cvMainID IN (SELECT ID FROM cvMain WITH(NOLOCK) WHERE paMainID = @paMainID)
		AND ID = @ID
        
    INSERT INTO paPushLog(paMainID, PushMessage, PushType) 
	SELECT a.caMainid, '有求职者求答复TA的简历&#10084;',10
	FROM caIOSBind a WITH(NOLOCK), Job b WITH(NOLOCK), exJobApply c WITH(NOLOCK)
	WHERE a.caMainId = b.caMainId AND b.ID = c.JobID AND c.ID = @ID
END
SET NOCOUNT OFF
GO
/****** Object:  StoredProcedure [dbo].[v2018_pcExJobApplyInsert]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--################################################################
--创建人：Lucifer
--创建时间：2018-9-5
--描述：申请职位
--################################################################
CREATE PROCEDURE [dbo].[v2018_pcExJobApplyInsert]
(
	@JobId INT,
	@cvMainId INT,
	@paMainId INT
)
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
		IF NOT EXISTS(SELECT 'X' FROM cvMain WITH(NOLOCK) WHERE paMainID = @paMainId AND ID = @cvMainId)
		BEGIN
			RETURN 0
		END
		--30天内同一简历同一职位不能重复申请
		IF EXISTS(SELECT 'X' FROM exJobApply WITH(NOLOCK) WHERE JobID = @JobId AND cvMainID = @cvMainId AND AddDate > GETDATE() - 30)
		BEGIN
			RETURN 0
		END
		--职位无效
		IF NOT EXISTS(SELECT 'X' FROM Job WITH(NOLOCK) WHERE ID = @JobId AND Valid = 1)
		BEGIN
			RETURN 0
		END
		DECLARE @MaxID INT
		DECLARE @IsFilter BIT
		SET @IsFilter = dbo.IsJobApplyFilter(@JobId, @cvMainId)
		INSERT INTO exJobApply(JobID, cvMainID, IsTempInsert, IsFilter)
		VALUES(@JobId, @cvMainId, 1, @IsFilter)
		SET @MaxID = @@IDENTITY
		--批量申请的未浏览过该职位的，插入浏览记录
		IF NOT EXISTS(SELECT 'X' FROM paJobViewLog WITH(NOLOCK) WHERE paMainId = @paMainId AND JobId = @JobId)
		BEGIN
			INSERT INTO paJobViewLog(JobId, paMainId, AddDate) VALUES(@JobId, @paMainId, GETDATE())
			UPDATE Job SET ViewNumber = ISNULL(ViewNumber, 0) + 1 WHERE ID = @JobId
		END
		--有应聘邀请的，更新Reply = 1
		UPDATE caCvIntention SET Reply = 1, ReplyDate = GETDATE() WHERE cvMainID = @cvMainId AND JobId = @JobId
		--微信推送
		INSERT wxMessageSend2(Templatetype, WxFansID, PaMainId, CvMainId, CpMainID, CaMainId, JobId, AddDate)
		SELECT 14, b.ID, @paMainId, @cvMainId, c.cpMainID, c.caMainID, c.ID, GETDATE()
		FROM paLoginContact a WITH(NOLOCK), wxFans b WITH(NOLOCK), Job c WITH(NOLOCK)
		WHERE a.OpenID = b.OpenID AND c.caMainID = a.paMainID AND a.ContactType = 101 AND c.ID = @JobId
		--APP推送
		INSERT INTO paPushLog(paMainID, PushMessage, PushType)
		SELECT TOP 1 b.caMainID, '亲，有求职者投递简历啦', 9
		FROM exJobApply a WITH(NOLOCK), Job b WITH(NOLOCK), caIOSBind c WITH(NOLOCK)
		WHERE a.JobId = b.ID AND b.caMainId = c.caMainId AND a.ID = @MaxID
	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH
	RETURN @MaxID
END
ERR:
BEGIN
	RETURN 0
END
SET NOCOUNT OFF
GO
/****** Object:  StoredProcedure [dbo].[v2018_pcExJobApplySelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--################################################################
--创建人：Lucifer
--创建时间：2018-7-23
--描述：获取个人申请的职位列表
--################################################################
CREATE PROCEDURE [dbo].[v2018_pcExJobApplySelect]
(
	@Where VARCHAR(1000), 
	@Order VARCHAR(100)
)
AS
SET NOCOUNT ON
BEGIN
	SET @Where = REPLACE(dbo.SafeSQL(@Where), '''', '')
	SET @Order = REPLACE(dbo.SafeSQL(@Order), '''', '')
	SET @Where = REPLACE(@Where, 'LIKE %', 'LIKE ''%')
	SET @Where = REPLACE(@Where, '% OR ', '%'' OR ')
	SET @Where = REPLACE(@Where, '%)', '%'')')

	DECLARE @SQL VARCHAR(2000)
	SET @SQL='SELECT a.ID, a.JobID, b.SecondId EnJobID, c.SecondId EnCpMainID, a.cvMainID, a.ApplyMessage, a.AddDate, 
			a.CompanyDeleted, a.CompanyDeleteDate, a.PersonDeleted, a.Reply, a.ReplyDate, a.ViewDate, b.Name JobName, 
			b.caMainID, b.dcRegionID, c.Name cpName, c.ID cpID, b.Welfare1, b.Welfare2, b.Welfare3, b.Welfare4, 
			b.Welfare5, b.Welfare6, b.Welfare7, b.Welfare8, b.Welfare9, b.Welfare10, b.Welfare11, b.Welfare12, b.Welfare13, 
			b.Welfare14, b.Welfare15, b.Welfare16, b.Welfare17, b.Welfare18, b.Welfare19, b.Valid JobValid, c.LogoFile LogoUrl, 
			c.HasLicence, c.IsAgent, c.MemberType, b.IssueDate, b.IssueEND, b.IsDelete, d.Name cvName, 
			dbo.GetCvMatch(a.cvMainID, a.JobID) cvMatch, dbo.GetCaOnlineStatus(b.caMainID) IsOnline, a.RemindDate, 
			a.ReplyReason, c.ReplyRate, b.dcSalaryId, b.dcSalaryIdMax,
			(SELECT TOP 1 Adddate FROM exInterview WITH(NOLOCK) WHERE a.cvMainId = cvMainId AND b.ID = JobId) InterviewDate
			FROM exJobApply a WITH(NOLOCK) 
			INNER JOIN Job b WITH(NOLOCK) On b.ID = a.JobID 
			INNER JOIN cpMain c WITH(NOLOCK) ON b.cpMainID = c.ID 
			INNER JOIN cvMain d WITH(NOLOCK) ON a.cvMainID = d.ID 
			WHERE 1 = 1'

	IF LEN(@Where) > 0
		SET @SQL = @SQL + ' AND ' + @Where

	IF LEN(@Order) > 0
		SET @SQL = @SQL + ' ORDER BY ' + @Order

	EXEC(@SQL)
END
SET NOCOUNT OFF
GO
/****** Object:  StoredProcedure [dbo].[v2018_pcMobileFollowUpInsert]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--##############################################
--添加人：Lucifer
--添加时间：2018-8-5
--描述：追踪手机号，如果注册了，就删除
--##############################################
CREATE PROCEDURE [dbo].[v2018_pcMobileFollowUpInsert] (
	@Mobile VARCHAR(11),
	@SessionId VARCHAR(100)
)
AS
SET NOCOUNT ON
BEGIN
	IF EXISTS(SELECT TOP 1 'X' FROM paMobileFollowUp WITH(NOLOCK) WHERE ContactDate IS NOT NULL AND Mobile = @Mobile)
		RETURN

	IF EXISTS(SELECT TOP 1 'X' FROM paMain WITH(NOLOCK) WHERE Mobile = @Mobile)
		RETURN

	DELETE FROM paMobileFollowUp WHERE Mobile = @Mobile OR SessionId = @SessionId
	INSERT INTO paMobileFollowUp(Mobile, SessionId) VALUES (@Mobile, @SessionId)
END
SET NOCOUNT OFF
GO
/****** Object:  StoredProcedure [dbo].[v2018_pcPaAttentionSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--################################################################
--创建人：Lucifer
--创建时间：2018-7-23
--描述：获取个人关注列表
--@AttentionType 1、企业 2、职位
--################################################################
CREATE PROCEDURE [dbo].[v2018_pcPaAttentionSelect]
(
	@paMainID INT, 
	@AttentionType TINYINT
)
AS
SET NOCOUNT ON
BEGIN
	IF @AttentionType = 1 --企业
	BEGIN
		SELECT a.PaMainID, a.ID, a.AddDate, b.ID CpMainID, b.SecondID CpSecondID, b.Name, b.DcCompanyKindID, b.DcCompanySizeID, 
		a.AddDate SortDate, dbo.GetCpIndustry(b.ID) Industry, b.LogoFile LogoUrl, b.RealName, b.MemberType INTO #tcp
		FROM PaAttention a WITH(NOLOCK), CpMain b WITH(NOLOCK)
		WHERE a.AttentionType = 1
		AND a.AttentionID = b.ID
		AND a.PaMainID = @paMainID
		AND b.IsDelete = 0
		ORDER BY a.AddDate DESC

		--企业职位最近更新时间
		UPDATE d SET d.SortDate = c.JobAddDate
		FROM #tcp d, 
		(SELECT a.CpMainID, MAX(a.LastModifyDate) JobAddDate
		FROM Job a WITH(NOLOCK)
		WHERE a.CpMainID IN (SELECT CpMainID FROM #tcp)
		GROUP BY a.CpMainID) c 
		WHERE d.CpMainID = c.CpMainID AND d.SortDate < c.JobAddDate

		SELECT * FROM #tcp ORDER BY SortDate DESC

		SELECT TOP 200 a.*, a.Valid JobValid, a.ID JobID, a.[Name] JobName, a.SecondId EnJobId, dbo.GetCaOnlineStatus(a.caMainId) IsOnline,
		(SELECT COUNT(1) FROM exJobApply WITH(NOLOCK) WHERE CvMainID IN (
			SELECT ID FROM CvMain WITH(NOLOCK) WHERE PaMainID = @paMainID
		) AND JobId = a.ID) IsApply, a.IssueDate
		FROM Job a WITH(NOLOCK), #tcp b WITH(NOLOCK)
		WHERE a.cpMainID = b.cpMainId AND a.IssueDate > b.AddDate ORDER BY a.IssueDate DESC
	END
	ELSE IF @AttentionType = 2 --职位
		BEGIN
		SELECT a.PaMainID, a.ID AttentionId, a.AddDate AttentionDate, b.*, b.ID JobID, b.SecondID EnJobId, b.Name JobName, d.SecondID CpSecondID, d.Name CpName, 0 IsApply, b.Valid JobValid, dbo.GetCaOnlineStatus(b.caMainID) IsOnline, d.LogoFile
		INTO #TJob
		FROM paAttention a WITH(NOLOCK), Job b WITH(NOLOCK), CpMain d WITH(NOLOCK)
		WHERE a.AttentionType = 2 
		AND a.AttentionID = b.ID
		AND a.PaMainID = @paMainID
		AND b.CpMainID = d.ID
		ORDER BY a.AddDate DESC

		UPDATE #TJob
		SET IsApply = 1
		WHERE JobID IN(
			SELECT JobID
			FROM exJobApply WITH(NOLOCK)
			WHERE CvMainiD IN (
				SELECT ID FROM CvMain WITH(NOLOCK)
				WHERE PaMainID = @paMainID
			)
		)

		--职位
		SELECT * FROM #TJob
	END
END
SET NOCOUNT OFF
GO
/****** Object:  StoredProcedure [dbo].[v2018_pcPaCvTagsSave]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--###########################################
--添加人：Lucifer
--添加时间：2018-7-17
--描述：保存个人标签
--###########################################
CREATE PROCEDURE [dbo].[v2018_pcPaCvTagsSave] 
(	
	@paMainID INT,
	@cvMainID INT,
	@Tags NVARCHAR(1000)
)
AS
SET NOCOUNT OFF
BEGIN		
	IF NOT EXISTS(SELECT 'X' FROM cvMain WHERE paMainID = @paMainID AND ID = @cvMainID)
	BEGIN
		RETURN -1
	END
	CREATE TABLE #T (
		ID INT IDENTITY(1, 1),
		cvMainID INT,
		Tag NVARCHAR(20),
		VerifyDate SMALLDATETIME
	)
	INSERT INTO #T(cvMainID, Tag)
	SELECT @cvMainID, REPLACE(REPLACE(a, CHAR(10), ''), CHAR(13), '')
	FROM dbo.fnSplit(@Tags,'@')

	DELETE FROM #T WHERE ID > 10
	DELETE FROM cvTags WHERE cvMainID = @cvMainID
	
	UPDATE #T 
	SET VerifyDate = GETDATE()
	WHERE EXISTS(SELECT 'x' FROM paTagsMain WHERE Tag = #T.Tag)
	
	INSERT INTO cvTags(cvMainID, Tags, VerifyDate)
	SELECT cvMainID, Tag, VerifyDate
	FROM #T
	DROP TABLE #T
	--更新CvLevel
	EXEC v2018_pcCvMainByCvLevelUpdate 2, @cvMainID, 5, 1
	RETURN 1
END
SET NOCOUNT ON
GO
/****** Object:  StoredProcedure [dbo].[v2018_pcPaGetPasswordLogInsert]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--######################################
--添加人：Lucifer
--添加时间：2018-7-13
--描述：插入取回密码记录
--返回值：-1 同一IP找回不能超过20次
--        -2 手机号找回密码每天不超过3次
--	      -3 用户名/邮箱找回密码每天不超过5次
--         0 查无此号
--         1 成功
--######################################
CREATE PROCEDURE [dbo].[v2018_pcPaGetPasswordLogInsert]
(
	@Username VARCHAR(50),
	@IP VARCHAR(15)
)
AS
SET NOCOUNT ON
BEGIN
	--同一IP找回不能超过20次
	IF (SELECT COUNT(1) FROM paGetPasswordLog WITH(NOLOCK) WHERE IP = @IP AND AddDate > CONVERT(VARCHAR(10), GETDATE(), 120)) >= 20
	BEGIN
		SELECT -1 Result
		RETURN
	END

	DECLARE @AskNo AS VARCHAR(40)
	DECLARE @ActivateCode AS VARCHAR(6)
	SET @AskNo = REPLACE(NEWID(), '-', '')
	SET @ActivateCode = RAND() * 899999 + 100000

	DECLARE @T TABLE(
		ID INT,
		Username VARCHAR(50),
		Email VARCHAR(50),
		Mobile VARCHAR(11)
	)

	IF dbo.IsMobile(@Username) = 1
	BEGIN
		--手机号找回密码每天不超过3次
		IF (SELECT COUNT(1) FROM paGetPasswordLog WITH(NOLOCK) WHERE UserNameIn = @Username AND AddDate > CONVERT(VARCHAR(10), GETDATE(), 120)) >= 3
		BEGIN
			SELECT -2 Result
			RETURN
		END

		INSERT INTO @T
		SELECT ID, UserName, Email, Mobile
		FROM paMain WITH(NOLOCK INDEX(IX_PaMain_Mobile))
		WHERE Mobile = @Username
		AND MobileVerifyDate IS NOT NULL
		ORDER BY Lastlogindate DESC
	END
	ELSE
	BEGIN
		--用户名/邮箱找回密码每天不超过5次
		IF (SELECT COUNT(1) FROM paGetPasswordLog WITH(NOLOCK) WHERE UserNameIn = @Username AND AddDate > CONVERT(VARCHAR(10), GETDATE(), 120)) >= 5
		BEGIN
			SELECT -3 Result
			RETURN
		END

		IF dbo.IsEmail(@Username) = 1
		BEGIN
			INSERT INTO @T
			SELECT ID, UserName, Email, Mobile
			FROM paMain WITH(NOLOCK INDEX(IX_paMain_Email))
			WHERE Email = @Username
			ORDER BY LastLoginDate DESC
		END
		ELSE
		BEGIN
			INSERT INTO @T
			SELECT ID, UserName, Email, Mobile
			FROM paMain WITH(NOLOCK INDEX(IX_PaMain_UserNameLower))
			WHERE UserNameLower = @Username
			ORDER BY LastLoginDate DESC
		END
	END
	--插入找回密码记录
	IF (SELECT COUNT(1) FROM @T) = 0
	BEGIN
		SELECT 0 Result
	END
	ELSE
	BEGIN
		INSERT INTO paGetPasswordLog(paMainID, UserNameIn, [IP], VerifyCode, UserName, Email, Mobile, UniqueId, ActivateCode, AskNo)
		SELECT ID, @UserName, @IP, '0000', UserName, Email, Mobile, REPLACE(NEWID(), '-', ''), @ActivateCode, @AskNo
		FROM @T

		SELECT 1 Result, ActivateCode, UniqueId, AskNo, UserName, Email
		FROM paGetPasswordLog WITH(NOLOCK)
		WHERE AskNo = @AskNo
	END
END
SET NOCOUNT OFF

GO
/****** Object:  StoredProcedure [dbo].[v2018_pcPaHeaderInfoSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2018.6.29
--创建人：Lucifer
--说明：获取个人公告
--#####################################################
CREATE PROCEDURE [dbo].[v2018_pcPaHeaderInfoSelect]
(
    @paMainID INT
)
AS
SET NOCOUNT ON
BEGIN
	DECLARE @T AS TABLE(
	  [Type] INT,
	  [Count] INT
	)

	--取未答复的面试通知
	INSERT INTO @T
	SELECT 1, COUNT(1)
	FROM exInterView a WITH(NOLOCK) 
	INNER JOIN cvMain b WITH(NOLOCK) ON a.cvMainID = b.ID 
	WHERE a.PersonDeleted = 0 AND b.paMainID = @paMainID AND a.Reply = 0

	--取未答复的应聘邀请	
	INSERT INTO @T
	SELECT 2, COUNT(1)
	FROM caCvIntention a WITH(NOLOCK) 
	INNER JOIN cvMain b WITH(NOLOCK) ON a.cvMainID = b.ID 
	WHERE PersonDeleted = 0 AND paMainID = @paMainID AND Reply IS NULL

	--取未查看的网站消息
	INSERT INTO @T
	SELECT 3, COUNT(1)
	FROM PaNotify WITH(NOLOCK)
	WHERE paMainID = @paMainID 
	AND (
		(NotifyType = 1 AND IsViewed = 0) OR 	--一次性消息，看过就不再通知了
		(NotifyType = 2 AND EndDate > GETDATE())	--即时消息，到期前（EndDate）一直通知
	)

	--取未查看的投诉
	INSERT INTO @T
	SELECT 4, COUNT(1)
	FROM CaPlaint a WITH(NOLOCK INDEX(IX_caPlaint_cvMainID)), cvMain b WITH(NOLOCK INDEX(IX_cvMain_paMainID))
	WHERE a.cvMainID = b.ID AND b.PaMainID = @PaMainID	AND a.IsViewed = 0	AND a.ReplyType = 1

	SELECT * FROM @T

	SELECT TOP 1 ID, Title, AnnounceDate, Content, [Type], Refreshdate
	FROM QlrcNews WITH(NOLOCK)
	WHERE (VersionId = (SELECT dcProvinceId FROM paMain WITH(NOLOCK) WHERE ID = @paMainID) OR VersionId = 0)
	AND NewsType = 1
	ORDER BY refreshdate DESC
	OPTION (KEEPFIXED PLAN)
END
SET NOCOUNT OFF
GO
/****** Object:  StoredProcedure [dbo].[v2018_pcPaJobClickLogInsert]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2018.8.20
--创建人：Lucifer
--说明：插入查看联系方式记录
--#####################################################
CREATE PROCEDURE [dbo].[v2018_pcPaJobClickLogInsert]
(
	@paMainId INT,
	@JobId INT,
	@IP VARCHAR(31)
)
AS
SET NOCOUNT ON
BEGIN
	--在黑名单，不让看
	IF EXISTS(SELECT 'X' FROM paJobClickCount WITH(NOLOCK) WHERE [IP] = @IP)
	BEGIN
		RETURN 0
	END
	--未申请过该职位，不让看
	IF NOT EXISTS(
		SELECT TOP 1 'X' FROM exJobApply WITH(NOLOCK) WHERE JobId = @JobId AND cvMainId IN(
			SELECT ID FROM cvMain WITH(NOLOCK) WHERE paMainId = @paMainId
		)
	)
	BEGIN
		RETURN 0
	END
	
	IF NOT EXISTS(
		SELECT 'X' FROM paJobClickLog WITH(NOLOCK)
		WHERE JobId = @JobId AND [IP] = @IP AND AddDate > DATEADD(SECOND, -5, GETDATE())
	)
	BEGIN
		INSERT INTO paJobClickLog(JobId, paMainId, [IP], AddDate)
		VALUES(@JobId, @paMainId, @IP, GETDATE())
	END
	RETURN 1
END
GO
/****** Object:  StoredProcedure [dbo].[v2018_PcPaJobCompareInsert]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--####################################################
--添加人：Lucifer
--添加时间：2018-6-27
--描述：生成你的菜儿
--修改：将今天推荐过了就不推荐的判断去掉，因为新建简历完善后，都会推荐你的菜儿 Lucifer
--####################################################
CREATE PROCEDURE [dbo].[v2018_PcPaJobCompareInsert]
(
	@PaMainID INT
)
AS
SET NOCOUNT ON
BEGIN
	--今天推荐过了就不推荐了
	--IF EXISTS(SELECT 'x' FROM PaJobCompare WITH(NOLOCK) WHERE PaMainID = @PaMainID AND AddDate > CONVERT(CHAR(10), GETDATE(), 120))
	--	RETURN
	
	CREATE TABLE #T(
		JobID INT, 
		SimilarJobID INT, 
		JobCount INT, 
		Pecentage FLOAT, 
		SimilarCount INT,
		Source VARCHAR(15)
	)

	DECLARE @BatchNo SMALLINT, @LastRecommenedNo TINYINT, @JobID INT, @JobCount INT, @PushCount INT, @Top INT
	
	SELECT @BatchNo = ISNULL(MAX(BatchNo), 0), @LastRecommenedNo = ISNULL(MIN(LastRecommenedNo), 6), @Top = 0
	FROM PaJobCompare WITH(NOLOCK)
	WHERE PaMainID = @PaMainID
	
	--如果最后一次登录时间为昨天那么剩余推送次数设置为6次
	IF (SELECT LastLoginDate FROM PaMain WITH(NOLOCK) WHERE ID = @PaMainID) > CONVERT(CHAR(10), GETDATE() - 1, 120)
	BEGIN
		SELECT @LastRecommenedNo = 6
	END
	IF ISNULL(@LastRecommenedNo, 0) = 0
		SET @LastRecommenedNo = 6

	SELECT jobID, COUNT(1) cnt 
	INTO #TJobSimilar 
	FROM exJobApplyMonthTemp WITH(NOLOCK)
	WHERE JobID IN(
		SELECT JobID 
		FROM exJobApplyMonthTemp
		WHERE CvMainID IN (
			SELECT ID 
			FROM CvMain WITH(NOLOCK)
			WHERE PaMainID = @PaMainID
		)
	) 
	GROUP BY jobID 
	HAVING COUNT(1) > 1
	
	WHILE EXISTS(SELECT jobID FROM #TJobSimilar)
	BEGIN
		SELECT TOP 1 @JobID = jobID, @JobCount = cnt 
		FROM #TJobSimilar
		
		INSERT INTO #T (JobID, SimilarJobID, JobCount, Pecentage, SimilarCount)
		SELECT @JobID, JobID, @JobCount, CAST(COUNT(1) AS FLOAT)*100/@JobCount, COUNT(1) 	
		FROM exJobApplyMonthTemp 	
		WHERE cvmainid IN(	
			SELECT cvMainID 
			FROM exJobApplyMonthTemp 
			WHERE jobid = @JobID) 
		AND jobid <> @JobID 
		AND EXISTS(		--职位必须有效且没被删除
			SELECT 'X' 
			FROM Job WITH(NOLOCK) 
			WHERE id = exJobApplyMonthTemp.JobID 
			AND Valid = 1
			AND IsDelete = 0
			AND IssueEnd > GETDATE())
			AND NOT EXISTS(--已经申请过的不再推荐
				SELECT 'X'
				FROM exJobApply WITH(NOLOCK)
				WHERE CvMainID IN (
					SELECT ID 
					FROM CvMain WITH(NOLOCK)
					WHERE PaMainID = @PaMainID
				)
				AND JobID = exJobApplyMonthTemp.JobID 
		)
		GROUP BY JobID 	
		HAVING COUNT(1) > 1
		ORDER BY COUNT(1) desc
		
		DELETE FROM #TJobSimilar WHERE jobID = @JobID
	END
	UPDATE #t SET Source = 'J' + LTRIM(STR(JobId))
	DROP TABLE #TJobSimilar
	
	INSERT INTO #T (SimilarJobID, JobCount)
	SELECT TOP 10 JobID, COUNT(1) 	
	FROM exJobApplyMonthTemp
	WHERE cvMainID IN(
		SELECT TOP 10 CvMainID 
		FROM exJobApplyMonthTemp
		WHERE JobID IN(	
			SELECT JobID 
			FROM exJobApplyMonthTemp
			WHERE CvMainID IN (
				SELECT ID 
				FROM CvMain WITH(NOLOCK)
				WHERE PaMainID = @PaMainID
			)
		) 
		AND NOT EXISTS(SELECT 'x' FROM CvMain WHERE PaMainID = @PaMainID AND id = exJobApplyMonthTemp.cvMainID)	
		GROUP BY CvMainID 	
		ORDER BY COUNT(1) DESC
	)
	AND NOT EXISTS(SELECT 'x' FROM CvMain WHERE PaMainID = @PaMainID AND id = exJobApplyMonthTemp.cvMainID)	
	AND EXISTS(		--职位必须有效且没被删除
		SELECT 'X' 
		FROM Job WITH(NOLOCK) 
		WHERE id = exJobApplyMonthTemp.JobID 
		AND Valid = 1
		AND IsDelete = 0
		AND IssueEnd > GETDATE())
	AND NOT EXISTS(--已经申请过的不再推荐
		SELECT 'X'
		FROM exJobApply WITH(NOLOCK)
		WHERE CvMainID IN (
			SELECT ID 
			FROM CvMain WITH(NOLOCK)
			WHERE PaMainID = @PaMainID
		)
		AND JobID = exJobApplyMonthTemp.JobID 
	) 
	GROUP BY JobID 	
	HAVING COUNT(1) > 1
	ORDER BY COUNT(1) desc
	UPDATE #t SET Source = 'from cvMain' WHERE Source IS NULL

	DECLARE @t AS TABLE(Id INT IDENTITY(1,1 ), SimilarJobID INT, Source VARCHAR(15))
	INSERT INTO @t(SimilarJobID)
	SELECT SimilarJobID
	FROM #T
	GROUP BY SimilarJobID
	ORDER BY COUNT(1) DESC

	UPDATE a SET a.Source = (SELECT TOP 1 Source FROM #t WHERE a.SimilarJobID = #t.SimilarJobID ORDER BY Source DESC)
	FROM @t a

	DELETE FROM @t WHERE SimilarJobID IN(SELECT a.SimilarJobID FROM @t a, Job b, cpMain c WHERE a.SimilarJobID = b.ID AND b.cpMainID = c.ID AND c.Name LIKE '%保险%')
	
	IF @BatchNo = 0
	BEGIN
		INSERT INTO PaJobCompare(BatchNo, PaMainID, CompareJobID, LastRecommenedNo, Source)
		SELECT TOP 10 @BatchNo + 1, @PaMainID, SimilarJobID, 5, Source
		FROM @t
		ORDER BY Id
		
		SELECT @PushCount = COUNT(1) 
		FROM PaJobCompare WITH(NOLOCK)
		WHERE PaMainID = @PaMainID
		AND BatchNO = @BatchNo + 1
		AND LastRecommenedNo = 5
		
		IF @PushCount < 10
			SET @Top = 10 - @PushCount
	END
	ELSE
	BEGIN
		INSERT INTO PaJobCompare(BatchNo, PaMainID, CompareJobID, LastRecommenedNo, Source)
		SELECT TOP 5 @BatchNo + 1, @PaMainID, SimilarJobID, @LastRecommenedNo-1, Source
		FROM @T a
		WHERE NOT EXISTS(			--推荐过的就不再推荐了
			SELECT 'X'
			FROM PaJobCompare WITH(NOLOCK)
			WHERE PaMainID = @PaMainID
			AND CompareJobID = a.SimilarJobID
		)
		ORDER BY Id

		--推荐不足10个 从原你的菜儿继续推荐
		SELECT @PushCount = COUNT(1) 
		FROM PaJobCompare WITH(NOLOCK)
		WHERE PaMainID = @PaMainID
		AND BatchNO = @BatchNo + 1
		AND LastRecommenedNo = @LastRecommenedNo-1
		
		IF @PushCount < 5
			SET @Top = 10 - @PushCount
	END

	IF @Top > 0
	BEGIN		 
		DECLARE @Job AS TABLE(
			Id INT,
			cpMainId INT,
			dcRegionId VARCHAR(6),
			dcJobTypeId VARCHAR(4),
			dcSalaryId INT,
			EmployType INT,
			dcEducationId INT,
			MinExperience INT,
			MinAge INT,
			MaxAge INT,
			AgeScore INT,
			EduScore INT,
			ExpScore INt,
			SizeScore INT
			)
		DECLARE @JobPlace AS TABLE(Id INT IDENTITY(1, 1), dcRegionId VARCHAR(6))
		DECLARE @JobType AS TABLE(Id INT IDENTITY(1, 1), dcJobTypeId VARCHAR(4))
		DECLARE @t1 AS TABLE(dcRegionId VARCHAR(6))
		DECLARE @t2 AS TABLE(dcJobTypeId VARCHAR(4))
		DECLARE @CvMainID INT, @dcSalaryId INT, @EmployType INT, @Degree INT, @Exp INT, @Age INT, @ThisMonth INT
		SET @ThisMonth = CONVERT(VARCHAR(6), GETDATE(), 112)

		SELECT TOP 1 @cvMainId = b.Id, @Age = (@ThisMonth - a.BirthDay) / 100,
			@dcSalaryId = dcSalaryID, @EmployType = EmployType, 
			@Degree = Degree, @Exp = RelatedWorkYears
		FROM paMain a WITH(NOLOCK), cvMain b WITH(NOLOCK)
		WHERE a.Id = b.paMainId
		AND a.Id = @paMainId
		
		INSERT INTO @JobPlace(dcRegionId)
		SELECT dcRegionId FROM cvJobPlace WITH(NOLOCK)
		WHERE cvMainId = @cvMainId

		INSERT INTO @JobType(dcJobTypeId)
		SELECT dcJobTypeId FROM cvJobType WITH(NOLOCK)
		WHERE cvMainId = @cvMainId

		DELETE a FROM @JobPlace a, @JobPlace b WHERE a.id <> b.Id AND a.dcRegionID <> b.dcRegionId AND b.dcRegionId LIKE a.dcRegionId + '%'
		DELETE a FROM @JobType a, @JobType b WHERE a.id <> b.Id AND a.dcJobTypeId <> b.dcJobTypeId AND b.dcJobTypeId LIKE a.dcJobTypeId + '%'
		INSERT INTO @t2 
		SELECT Id FROM dcJobType WHERE ID IN(SELECT dcJobTypeId FROM @JobType) OR ParentID IN(SELECT dcJobTypeId FROM @JobType)

		INSERT INTO @t1 SELECT Id FROM dcRegion WHERE ID IN(SELECT dcRegionId FROM @JobPlace) 
		INSERT INTO @t1 SELECT Id FROM dcRegion WHERE LEFT(ID, 4) IN(SELECT dcRegionId FROM @JobPlace)
		INSERT INTO @t1 SELECT Id FROM dcRegion WHERE LEFT(ID, 2) IN(SELECT dcRegionId FROM @JobPlace)
		--===========================================
		INSERT INTO @Job(Id, cpMainId, dcRegionId, dcJobTypeId, dcSalaryId, EmployType, dcEducationId, MinExperience, MinAge, MaxAge)
		SELECT TOP 200 Id, cpMainId, dcRegionId, dcJobTypeId, dcSalaryId, EmployType, dcEducationId, MinExperience, MinAge, MaxAge
		FROM jobPublish WITH(NOLOCK)
		WHERE EmployType = @EmployType
		AND dcRegionID IN(SELECT dcRegionId FROM @t1)
		AND dcJobTypeId IN(SELECT dcJobTypeId FROM @t2)
		AND dcSalaryId IN(100, @dcSalaryId)
		AND EXISTS(SELECT 'x' FROM cpMainPublish WITH(NOLOCK) WHERE LastLoginDate > GETDATE() - 31 AND cpMainPublish.Id = cpMainId)
		ORDER BY RefreshDate DESC

		DELETE @Job WHERE Id IN(SELECT CompareJobId FROM paJobCompare WITH(NOLOCK) WHERE paMainId = @pamainId)
		DELETE @Job WHERE Id IN(SELECT JobId FROM paYourFood WITH(NOLOCK) WHERE paMainId = @pamainId)
		DELETE @Job WHERE Id IN(SELECT JobId FROM ExJobApply WITH(NOLOCK) WHERE cvMainID IN(SELECT ID FROM cvMain WITH(NOLOCK) WHERE paMainId = @pamainId))
		IF(SELECT COUNT(*) FROM @Job) > 3
		BEGIN			
			UPDATE a SET a.SizeScore = b.dcCompanySizeId * -1, EduScore = 0, AgeScore = 0, ExpScore = 0  FROM @Job a, cpMainPublish b WHERE a.cpMainId = b.ID
			UPDATE @Job SET EduScore = dcEducationId - @Degree WHERE dcEducationId > @Degree AND dcEducationId < 100
			UPDATE @Job SET EduScore = @Degree - dcEducationId WHERE dcEducationId < @Degree AND dcEducationId < 100
			UPDATE @Job SET MinAge = 16 WHERE MinAge = 99
			UPDATE @Job SET MaxAge = 60 WHERE MaxAge = 99
			UPDATE @Job SET AgeScore = (MinAge - @Age) / 5 + 1 WHERE MinAge > @Age
			UPDATE @Job SET AgeScore = (@Age - MaxAge) / 5 + 1 WHERE MaxAge < @Age
			IF @Exp = 0
				SET @Exp = 1
			ELSE IF @Exp IN(1, 2)
				SET @Exp = 2
			ELSE IF @Exp IN(3,4,5)
				SET @Exp = 3
			ELSE IF @Exp IN(6,7,8,9,10)
				SET @Exp = 4
			ELSE IF @Exp > 10
				SET @Exp = 5
			ELSE
				SET @Exp = 0
			UPDATE @Job SET MinExperience = CASE WHEN MinExperience = 5 THEN 1 ELSE MinExperience + 1 END WHERE MinExperience > 0
			UPDATE @Job SET ExpScore = MinExperience - @Exp WHERE MinExperience > @Exp
			UPDATE @Job SET ExpScore = @Exp - MinExperience WHERE MinExperience < @Exp AND MinExperience > 0	
		END
		INSERT INTO PaJobCompare(BatchNo, PaMainID, CompareJobID, LastRecommenedNo, Source)
		SELECT TOP (@Top) @BatchNo + 1, @PaMainID, Id, 5, 'Expect'
		FROM @Job ORDER BY EduScore, ExpScore + SizeScore + AgeScore
	END	

	DROP TABLE #T
END
SET NOCOUNT OFF
GO
/****** Object:  StoredProcedure [dbo].[v2018_pcPaJobCompareSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--################################################################
--创建人：Lucifer
--创建时间：2018-7-23
--描述：获取你的菜儿
--@BatchNo 推荐批次，0、最新 大于0、指定 -1、全部
--################################################################
CREATE PROCEDURE [dbo].[v2018_pcPaJobCompareSelect]
(
    @PaMainID INT,
    @BatchNo SMALLINT
)
AS
SET NOCOUNT ON
BEGIN
    IF @BatchNo > 0
    BEGIN
        SELECT a.*, b.*, c.Name CpName, c.HasLicence, c.SecondID EnCpMainID, b.ID JobID, b.SecondID EnJobID, 
            b.Name JobName, b.Valid JobValid, a.AddDate RecommenedDate, dbo.GetCaOnlineStatus(b.caMainID) IsOnline, 
            c.LogoFile LogoUrl, c.RealName, (SELECT COUNT(1) FROM exJobApply WITH(NOLOCK) WHERE CvMainID IN (
				SELECT ID FROM CvMain WITH(NOLOCK) WHERE PaMainID = @paMainID
			) AND JobId = a.CompareJobID) IsApply
        FROM PaJobCompare a WITH(NOLOCK)
        LEFT JOIN Job b WITH(NOLOCK) ON b.ID = a.CompareJobID
        LEFT JOIN CpMain c WITH(NOLOCK) ON c.ID = b.CpMainID
        WHERE PaMainID = @PaMainID
        AND BatchNo = @BatchNo
        ORDER BY a.AddDate DESC
    END
    ELSE IF @BatchNo = 0
    BEGIN
        SELECT a.*, b.*, c.Name CpName, c.HasLicence, c.SecondID EnCpMainID, b.ID JobID, b.SecondID EnJobID, 
            b.Name JobName, b.Valid JobValid, a.AddDate RecommenedDate, dbo.GetCaOnlineStatus(b.caMainID) IsOnline, 
            c.LogoFile LogoUrl, c.RealName, (SELECT COUNT(1) FROM exJobApply WITH(NOLOCK) WHERE CvMainID IN (
				SELECT ID FROM CvMain WITH(NOLOCK) WHERE PaMainID = @paMainID
			) AND JobId = a.CompareJobID) IsApply
        FROM PaJobCompare a WITH(NOLOCK)
        LEFT JOIN Job b WITH(NOLOCK) ON b.ID = a.CompareJobID
        LEFT JOIN CpMain c WITH(NOLOCK) ON c.ID = b.CpMainID
        WHERE PaMainID = @PaMainID
		AND b.Valid = 1
        AND BatchNo = (
            SELECT MAX(BatchNo) 
            FROM PaJobCompare WITH(NOLOCK)
            WHERE PaMainID = @PaMainID
        )
        ORDER BY a.AddDate DESC
    END
    ELSE
    BEGIN
        SELECT a.*, b.*, c.Name CpName, c.HasLicence, c.SecondID EnCpMainID, b.ID JobID, b.SecondID EnJobID, 
            b.Name JobName, b.Valid JobValid, a.AddDate RecommenedDate, dbo.GetCaOnlineStatus(b.caMainID) IsOnline, 
            c.LogoFile LogoUrl, c.RealName, (SELECT COUNT(1) FROM exJobApply WITH(NOLOCK) WHERE CvMainID IN (
				SELECT ID FROM CvMain WITH(NOLOCK) WHERE PaMainID = @paMainID
			) AND JobId = a.CompareJobID) IsApply
        FROM PaJobCompare a WITH(NOLOCK)
        LEFT JOIN Job b WITH(NOLOCK) ON b.ID = a.CompareJobID
        LEFT JOIN CpMain c WITH(NOLOCK) ON c.ID = b.CpMainID
		WHERE PaMainID = @PaMainID
			AND b.Valid = 1
		ORDER BY a.AddDate DESC
    END
END
SET NOCOUNT OFF
GO
/****** Object:  StoredProcedure [dbo].[v2018_pcPaLoginContactInsert]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2018.6.21
--创建人：Lucifer
--说明：关联第三方登陆
--ContactType 1、QQ登陆 2、人人登陆 3、微博登陆 4、微信登陆 5、百度登陆
--#####################################################
CREATE PROCEDURE [dbo].[v2018_pcPaLoginContactInsert]
(
	@paMainID INT,
	@OpenID VARCHAR(100),
	@ContactType TINYINT,
	@LoginType TINYINT
)
AS
BEGIN
	DELETE FROM paLoginContact WHERE Openid = @OpenID AND ContactType = @ContactType
	INSERT INTO paLoginContact(paMainID, Openid, ContactType, LoginType, AddDate)
	VALUES(@paMainID, @OpenID, @ContactType, @LoginType, GETDATE())
	
	IF @ContactType = 4
	BEGIN
		UPDATE wxFans SET PaMainID = @PaMainID WHERE OpenID = @OpenID
	END
END
GO
/****** Object:  StoredProcedure [dbo].[v2018_pcPaMainByLastLoginDateUpdate]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2018-6-5
--创建人：Lucifer
--说明：更新个人登陆时间
--当天第一次登陆，更新DateReport.PersonLoginNum_Net
--19是PC站回收，42是M站回收 如果不是当天第一次登陆，不记录登陆时间
--#####################################################
CREATE PROCEDURE [dbo].[v2018_pcPaMainByLastLoginDateUpdate]
(
	@paMainId INT,
	@dcProvinceId INT,
	@IP VARCHAR(31),
	@Browser VARCHAR(500),
	@LoginFrom TINYINT
)
AS
SET NOCOUNT ON
BEGIN
	SET @IP = dbo.SafeSQL(@IP)
	SET @Browser = dbo.SafeSQL(@Browser)
	UPDATE PaMain Set LastLoginDate = GETDATE(), TotalLoginNum = ISNULL(TotalLoginNum, 0) + 1 WHERE ID = @paMainId
	IF NOT EXISTS(SELECT 'x' FROM paLoginLog WITH(NOLOCK) WHERE paMainID = @paMainId AND AddDate >= CONVERT(VARCHAR(10), GETDATE(), 120))
	BEGIN
		UPDATE DateReport
		SET PersonLoginNum_Net = PersonLoginNum_Net + 1  
		WHERE CountDate = CONVERT(VARCHAR(8), GETDATE(), 112)
		AND Province_Id = @dcProvinceId

		INSERT INTO paLoginLog(paMainID, LoginIP, Browser, LoginFrom) VALUES(@paMainId, @IP, ISNULL(@Browser, 'Null'), @LoginFrom)
	END
	ELSE IF @LoginFrom NOT IN(19, 42) 
	BEGIN
		INSERT INTO paLoginLog(paMainID, LoginIP, Browser, LoginFrom) VALUES(@paMainId, @IP, ISNULL(@Browser, 'Null'), @LoginFrom)
	END
END
SET NOCOUNT OFF


GO
/****** Object:  StoredProcedure [dbo].[v2018_pcPaMainByLoginUpdate]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--------------------------------------------------
--添加人：Lucifer
--添加日期：2018-6-6
--说明：个人用户登陆
--------------------------------------------------
CREATE PROCEDURE [dbo].[v2018_pcPaMainByLoginUpdate]
(
	@IP VARCHAR(31),
	@dcProvinceId SMALLINT,
	@Browser VARCHAR(500),
	@paMainId INT,
	@LoginFrom TINYINT
)
AS
SET NOCOUNT ON
BEGIN
	--超过登陆次数,每天限制登录次数为20次
	IF (SELECT COUNT(1) FROM paLoginLog WITH(NOLOCK) WHERE paMainID = @paMainId AND AddDate > CONVERT(VARCHAR(10), GETDATE(), 120)) > 19
		RETURN -2
			
	--应届生网站抓取生成的个人用户，简历默认隐藏，第一次登陆的时候，将简历公开
	IF EXISTS (SELECT 'X' FROM paMain WITH(NOLOCK) WHERE RegisterType = 200 AND Id = @paMainId AND TotalLoginNum = 1)
	BEGIN
		UPDATE cvMain SET IsCvHidden = 0 WHERE paMainId = @paMainId
	END

	--登陆日志
	EXEC v2018_pcPaMainByLastLoginDateUpdate @paMainId, @dcProvinceId, @IP, @Browser, @LoginFrom
	RETURN @paMainId
END
SET NOCOUNT OFF


GO
/****** Object:  StoredProcedure [dbo].[v2018_pcPaMainByMobileUpdate]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--添加时间 20180622
--添加人   Lucifer
--用途     修改手机号+认证
--注意     当验证码为000000，是百度百聘注册账号的，百度过来的手机号默认为认证通过的--修改harry 出现号码为空，联系不到情况
--返回值   0  验证码错误
--         -1 邮箱黑名单
--#####################################################
CREATE PROCEDURE [dbo].[v2018_pcPaMainByMobileUpdate]
(
	@paMainId INT,
	@Mobile VARCHAR(13),
	@IP VARCHAR(31),
	@VerifyCode VARCHAR(6)
)
AS
BEGIN
	IF EXISTS(SELECT 'x' FROM Person_BLACK WITH(NOLOCK) WHERE Mobile = @Mobile)
	BEGIN
		----有黑名单，则增加拒绝次数
		UPDATE Person_Black SET RefuseCount = RefuseCount + 1 WHERE Mobile = @Mobile
		RETURN -1
	END

	----验证验证码是否正确
	DECLARE @paVerifyLogID INT
	SET @paVerifyLogID = 0
	SELECT @paVerifyLogID = ID FROM paVerifyLog WITH(NOLOCK)
	WHERE Mobile = @Mobile AND VerifyCode = @VerifyCode AND AddDate > DATEADD(HOUR, -1, GETDATE())
	
	IF @paVerifyLogID = 0 AND @VerifyCode <> '000000'
		RETURN 0

	DECLARE @MobileOld VARCHAR(13)
	SELECT @MobileOld = ISNULL(Mobile ,'') FROM paMain WITH(NOLOCK INDEX(PK_paMain))
	WHERE ID = @paMainId AND MobileVerifyDate IS NOT NULL

	IF NOT EXISTS(SELECT 'X' FROM PaMain WITH(NOLOCK) WHERE ID = @paMainId AND MobileVerifyDate IS NOT NULL AND Mobile = @Mobile)
	BEGIN
		UPDATE paVerifyLog SET VerifyDate = GETDATE() WHERE ID = @paVerifyLogID
		--把该手机号的其他账号状态修改为未认证
		UPDATE paMain SET MobileVerifyDate = NULL WHERE Mobile = @Mobile
		IF @VerifyCode <> '000000'
			UPDATE paMain SET Mobile = @Mobile, LastModifyDate = GETDATE(), MobileVerifyDate = GETDATE() WHERE ID = @paMainId
		IF LEN(ISNULL(@MobileOld, '')) > 0
		BEGIN
			INSERT INTO paOperationLog (paMainID, Operation, Details, [IP]) 
			VALUES(@paMainId, 35, '更新手机号码，原号码：<' + ISNULL(@MobileOld, '') + '>；新手机号码：<' + @Mobile + '>', @IP)
		END
	END

	RETURN 1
END

GO
/****** Object:  StoredProcedure [dbo].[v2018_pcPaMainByPasswordUpdate]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--###########################################
--添加人：Lucifer
--添加时间：2018-7-17
--描述：修改密码
--###########################################
CREATE PROCEDURE [dbo].[v2018_pcPaMainByPasswordUpdate]
(
	@ID INT,
	@Password VARCHAR(60),
	@PlainPassword VARCHAR(60),
	@IP VARCHAR(31)
)
AS
SET NOCOUNT OFF
BEGIN
	IF dbo.IsAccount(@PlainPassword) = 0
	BEGIN
		RETURN 0
	END
	UPDATE paMain SET [Password] = @Password, IsDefaultPassword = 0 WHERE ID = @ID
	--插入操作日志
	INSERT INTO paOperationLog (paMainID, Operation, Details, IP)
	VALUES(@ID, 21, '重置密码，新密码：<' + LEFT(@PlainPassword, 3) + '****>', @IP)
	--如果有找回密码记录，更新IsReset
	UPDATE paGetPasswordLog SET
		IsReset = 1
	WHERE AskNo IN(
		SELECT AskNo FROM paGetPasswordLog WITH(NOLOCK)
		WHERE paMainID = @ID
			AND AddDate > DATEADD(MINUTE, -60, GETDATE())
			AND IsReset IS NULL
	)
	RETURN 1
END
SET NOCOUNT ON
GO
/****** Object:  StoredProcedure [dbo].[v2018_pcPaMainByUsernameUpdate]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--###########################################
--添加人：Lucifer
--添加时间：2018-7-17
--描述：修改个人用户名
--返回值：-1 邮件黑名单
--        -2 邮件格式错误
--         0 邮箱重复
--###########################################
CREATE PROCEDURE  [dbo].[v2018_pcPaMainByUsernameUpdate]
(
	@ID INT,
	@Username VARCHAR(50),
	@IP VARCHAR(31)
)
AS
SET NOCOUNT OFF
--有黑名单，则增加拒绝次数
IF EXISTS(SELECT 'x' FROM Person_Black WITH(NOLOCK) WHERE Email = @Username)
BEGIN
	UPDATE Person_Black SET RefuseCount = ISNULL(RefuseCount, 0) + 1 WHERE Email = @Username
	RETURN -1
END
--用户名不是邮箱格式
IF dbo.IsEmail(@Username) = 0
BEGIN
	RETURN -2
END
--用户名重复
IF EXISTS(SELECT 'x' FROM paMain WITH(NOLOCK INDEX(IX_paMain_UserNameLower)) WHERE UserNameLower = @Username)
BEGIN
	RETURN 0
END
BEGIN TRY
	DECLARE @UsernameOld AS VARCHAR(50)
	SELECT @UsernameOld = UsernameLower
	FROM paMain WITH(NOLOCK INDEX(PK_paMain)) WHERE ID = @ID

	UPDATE paMain SET Username = @Username WHERE ID = @ID
	INSERT INTO paOperationLog (paMainID, Operation, Details, IP) 
	VALUES(@ID, 20, '更新用户名，原用户名：<' + @UsernameOld + '>；新用户名：<' + @Username + '>', @IP)

	RETURN 1
END TRY
BEGIN CATCH
	RETURN 0
END CATCH
SET NOCOUNT ON
GO
/****** Object:  StoredProcedure [dbo].[v2018_pcPaMainInsert]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--添加时间 20180614
--添加人   Lucifer
--用途     个人注册
--返回值   0  IP黑名单
--         -1 邮箱黑名单
--         -2 邮箱已存在
--         -3 注册失败
--         -4  10分钟之内注册超过10个（@RegisterType = 200的不考虑，属于应届生网站抓取的简历注册）
--#####################################################
CREATE PROCEDURE  [dbo].[v2018_pcPaMainInsert]
(
	@Email VARCHAR(50),
	@Password VARCHAR(60),
	@dcProvinceID SMALLINT,
	@RegisterIP VARCHAR(50),
	@RegisterFrom TINYINT,
	@RegisterType TINYINT,
	@UrlID INT,
	@InfoID INT,
	@Referer VARCHAR(500)
)
AS
SET NOCOUNT ON
BEGIN TRY
	--IP黑名单
	IF EXISTS(SELECT 'X' FROM IP_Black WITH(NOLOCK) WHERE [IP] = @RegisterIP)
	BEGIN
		RETURN 0
	END

	--10分钟之内注册超过10个（@RegisterType = 200的不考虑，属于应届生网站抓取的简历注册）
	IF (
		SELECT COUNT(*) FROM paMain WITH(NOLOCK)
		WHERE RegisterIp = @RegisterIp AND AddDate > DATEADD(MINUTE, -10, GETDATE()) AND @RegisterType <> 200
	) > 10
	BEGIN
		RETURN -4
	END

	--邮箱黑名单
	IF EXISTS(SELECT 'X' FROM Person_Black WITH(NOLOCK) WHERE Email = @Email)
	BEGIN
		UPDATE Person_black SET RefuseCount = ISNULL(RefuseCount, 0) + 1 WHERE Email = @Email
		RETURN -1
	END

	--邮箱已存在
	IF EXISTS(SELECT 'X' FROM paMain WITH(NOLOCK) WHERE Email = @Email)
	BEGIN
		RETURN -2
	END

	DECLARE @MaxId INT
	BEGIN TRAN
		INSERT INTO paMain
			(Username, [Password], dcProvinceID, dcSubSiteID, Email, RegisterIP, LastLoginDate, TotalLoginNum, RegisterFrom, RegisterType)
		VALUES(@Email, @Password, @dcProvinceID, @dcProvinceID, @Email, @RegisterIP, GETDATE(), 1, @RegisterFrom, @RegisterType)
		SET @MaxId = @@IDENTITY
		--应届生网站抓取的简历注册 不计入DateReport
		UPDATE DateReport SET PersonRegNum = ISNULL(PersonRegNum, 0) + 1, PersonLoginNum_Net = ISNULL(PersonLoginNum_Net, 0) + 1
		WHERE province_id = @dcProvinceID AND CountDate = CONVERT(VARCHAR(8), GETDATE(), 112) AND @RegisterType <> 200
		--操作日志
		INSERT INTO paOperationLog (paMainID, Operation, Details, [IP]) VALUES(@MaxID, 10, '注册个人账号成功。', @RegisterIP)
	COMMIT
END TRY
BEGIN CATCH
	ROLLBACK TRAN
	INSERT INTO LogDb..RegisterErrorLog SELECT @MaxId, '10|' + @RegisterIP+'|'+@RegisterFrom, @Email + ' ' + @Password, GETDATE()
	RETURN -3
END CATCH

BEGIN TRY
	IF @UrlID > 0
	BEGIN
		UPDATE [Url] SET AllResume = ISNULL(AllResume, 0) + 1, TodayResume = ISNULL(TodayResume, 0) + 1 WHERE ID = @UrlID
		IF EXISTS(SELECT 'X' FROM [Url] WHERE ID = @UrlID AND [Description] LIKE '%百度竞价%')
		BEGIN
			INSERT INTO UrlAccount VALUES(@UrlID, @MaxID, NULL, GETDATE())
		END
	END
	IF @InfoID > 0
	BEGIN
		IF NOT EXISTS(
			SELECT TOP 1 'X'
			FROM Info_DateReport WITH(NOLOCK)
			WHERE Countdate = CONVERT(VARCHAR(8), GETDATE(), 112)
			AND Province_Id = @dcProvinceID
			AND InfoManager_Id = @InfoID
		)
		BEGIN
			INSERT INTO Info_DateReport (Province_Id, InfoManager_Id, CountDate) 
			VALUES(@dcProvinceID, @InfoID, CONVERT(VARCHAR(8), GETDATE(), 112))
		END

		UPDATE Info_DateReport 
		SET AllResume = ISNULL(AllResume, 0) + 1
		WHERE CountDate = CONVERT(VARCHAR(8), GETDATE(), 112)
		AND Province_ID = @dcProvinceID
		AND InfoManager_ID = @InfoID

		INSERT INTO InfoLog(InfoManager_Id, [IP], Referer, paMainId) 
		VALUES(@InfoID, @RegisterIp, '', @MaxID)
	END
	IF LEN(@Referer) > 0
	BEGIN
		INSERT INTO paReferer(paMainId, Referer)
		VALUES(@MaxID, @Referer)
	END
END TRY
BEGIN CATCH
	
END CATCH
RETURN @MaxID
SET NOCOUNT OFF
GO
/****** Object:  StoredProcedure [dbo].[v2018_pcPaMainUpdate]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2018.6.21
--创建人：Lucifer
--说明：保存基本信息
--@ModifyType 1、修改基本信息 2、修改求职状态 3、修改屏蔽词
--#####################################################
CREATE PROCEDURE [dbo].[v2018_pcPaMainUpdate]
(
	@paMainID INT,
	@cvMainID INT,
	@Name NVARCHAR(6),
	@NameEng VARCHAR(30),
	@Gender BIT,
	@BirthDay INT,
	@LivePlace VARCHAR(6),
	@MapPlace INT,
	@AccountPlace VARCHAR(6),
	@GrowPlace VARCHAR(6),
	@OnlineContact TINYINT,
	@OnlineContactNo VARCHAR(50),
	@Homepage VARCHAR(200),
	@Marriage TINYINT,
	@Nation TINYINT,
	@Height TINYINT,
	@IsReceiveSms BIT,
	@CareerStatus TINYINT,
	@HideConditions NVARCHAR(500),
	@IP VARCHAR(39),
	@ModifyType TINYINT
)
AS
SET NOCOUNT ON
BEGIN TRAN
	IF NOT EXISTS(SELECT TOP 1 'X' FROM cvMain WITH(NOLOCK) WHERE ID = @cvMainID AND paMainID = @paMainID)
		GOTO ERR

	BEGIN TRY
		IF @ModifyType = 1 --修改基本信息
		BEGIN
			DECLARE @NameOld NVARCHAR(6)
			DECLARE @NameEngOld VARCHAR(30)
			DECLARE @OnlineContactNoOld VARCHAR(50)
			DECLARE @HomepageOld VARCHAR(200)
			DECLARE @IsReceiveSmsOld BIT

			--检查在线联系方式和号码
			IF @OnlineContact = 0
				SET @OnlineContactNo = NULL

			--取消不正确的主页格式
			SET @Homepage = REPLACE(@Homepage, 'http%3A//', 'http://')
			SET @Homepage = REPLACE(@Homepage, 'http://', '')

			--获得原始数据
			SELECT @NameOld = [Name], @NameEngOld = NameEng, @OnlineContactNoOld = OnlineContactNo,
				@HomepageOld = Homepage, @IsReceiveSmsOld = IsReceiveSms
			FROM paMain WITH(NOLOCK INDEX(PK_paMain))
			WHERE ID = @paMainID

			--选填没填置空
			SET @Name = dbo.v2018_SetVarcharNull(@Name)
			SET @NameEng = dbo.v2018_SetVarcharNull(@NameEng)
			SET @OnlineContact = dbo.v2018_SetIntNull(@OnlineContact)
			SET @Homepage = dbo.v2018_SetVarcharNull(@Homepage)
			SET @Marriage = dbo.v2018_SetIntNull(@Marriage)
			SET @Nation = dbo.v2018_SetIntNull(@Nation)
			SET @Height = dbo.v2018_SetIntNull(@Height)

			UPDATE paMain SET
				[Name] = @Name,
				NameEng = @NameEng,
				Gender = @Gender,
				BirthDay = @BirthDay,
				LivePlace = @LivePlace,
				AccountPlace = @AccountPlace,
				GrowPlace = @GrowPlace,
				OnlineContact = @OnlineContact,
				OnlineContactNo = @OnlineContactNo,
				Homepage = @Homepage,
				Marriage = @Marriage, 
				Nation = @Nation,
				Height = @Height,
				dcMapPlaceId = @MapPlace,
				IsReceiveSms = @IsReceiveSms,
				LastModifyDate = GETDATE()
			WHERE ID = @paMainID

			--添加审核记录
			EXEC v2018_pcCvModifyInsert @paMainID, @cvMainID, NULL, @Name, @NameOld, 'ac1', @IP
			EXEC v2018_pcCvModifyInsert @paMainID, @cvMainID, NULL, @NameEng, @NameEngOld, 'ae1', @IP
			EXEC v2018_pcCvModifyInsert @paMainID, @cvMainID, NULL, @OnlineContactNo, @OnlineContactNoOld, 'ac2', @IP
			EXEC v2018_pcCvModifyInsert @paMainID, @cvMainID, NULL, @Homepage, @HomepageOld, 'ac3', @IP

			--接收短信设置添加操作日志
			IF @IsReceiveSmsOld <> @IsReceiveSms
			BEGIN
				INSERT INTO paOperationLog(paMainID, Operation, Details, IP) 
				VALUES(@paMainID, 60, '更改接收短信设置为' + CASE @IsReceiveSms WHEN 1 THEN '<接收短信>' ELSE '<不接收短信>' END, @IP)
			END
		
			----修改cvMain.cvLevel
			IF @Name IS NOT NULL
			BEGIN
				EXEC v2018_pcCvMainByCvLevelUpdate 0, @cvMainID, 1, 1
			END

			IF @NameEng IS NOT NULL
			BEGIN
				EXEC v2018_pcCvMainByCvLevelUpdate 1, @cvMainID, 1, 1
			END

			----12小时内只保留一次修改记录
			DELETE FROM paOperationLog WHERE paMainID = @paMainID AND Operation = 11 AND AddDate > GETDATE() - 0.5
			INSERT INTO paOperationLog (paMainID, Operation, Details, IP) VALUES(@paMainID, 11, '更新基本信息成功。', @IP)
		END
		ELSE IF @ModifyType = 2 --修改求职状态
		BEGIN
			UPDATE paMain SET
				dcCareerStatus = @CareerStatus
			WHERE ID = @paMainID
		END
		ELSE IF @ModifyType = 3 --修改屏蔽词
		BEGIN
			UPDATE paMain SET
				HideConditions = @HideConditions
			WHERE ID = @paMainID
			INSERT INTO paOperationLog (paMainID, Operation, Details, IP) VALUES(@paMainID, 50, '更新屏蔽设置成功。', @IP)
		END
	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH

COMMIT TRAN
RETURN 1
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END
SET NOCOUNT OFF
GO
/****** Object:  StoredProcedure [dbo].[v2018_pcPaPageViewLogUpdate]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--################################################################
--创建人：Lucifer
--创建时间：2018-7-23
--描述：更新个人动态
--@ViewPageType 1、面试邀请 2、应聘邀请 3、谁在关注我 4、我的关注 5、你的菜 6、申请的职位 7、聊天记录
--################################################################
CREATE PROCEDURE [dbo].[v2018_pcPaPageViewLogUpdate]
(
	@paMainId INT,
	@ViewPageType TINYINT
)
AS
SET NOCOUNT ON
BEGIN
	IF NOT EXISTS(SELECT 'X' FROM paPageViewLog WITH(NOLOCK) WHERE paMainId = @paMainId)
	BEGIN
		INSERT INTO paPageViewLog(paMainId, addDate, InterviewDate, IntentionDate, ViewLogDate, 
			AttentionDate, YourFoodDate, ApplyReplyDate) 
		VALUES(@paMainId, GETDATE() - 10, GETDATE() - 10, GETDATE() - 10, GETDATE() - 10,
			GETDATE() - 10, GETDATE() - 10, GETDATE() - 10)
	END
	
	IF @ViewPageType = 1
		UPDATE paPageViewLog SET InterviewDate = GETDATE(), InterviewCount = 0 WHERE paMainId = @paMainId 
	
	IF @ViewPageType = 2
		UPDATE paPageViewLog SET IntentionDate = GETDATE(), CpInvitationCount = 0 WHERE paMainId = @paMainId 
	
	IF @ViewPageType = 3
		UPDATE paPageViewLog SET ViewLogDate = GETDATE(), CvViewLogCount = 0 WHERE paMainId = @paMainId 
	
	IF @ViewPageType = 4
		UPDATE paPageViewLog SET AttentionDate = GETDATE(), MyAttentionCount = 0 WHERE paMainId = @paMainId 
	
	IF @ViewPageType = 5
		UPDATE paPageViewLog SET YourFoodDate = GETDATE(), YourFoodCount = 0 WHERE paMainId = @paMainId 
	
	IF @ViewPageType = 6
		UPDATE paPageViewLog SET ApplyReplyDate = GETDATE(), JobAppliedCount = 0 WHERE paMainId = @paMainId 
	
	IF @ViewPageType = 7
		UPDATE paPageViewLog SET ChatCount = 0 WHERE paMainId = @paMainId 
END
SET NOCOUNT OFF
GO
/****** Object:  StoredProcedure [dbo].[v2018_pcPaPlaintSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--################################################################
--创建人：Lucifer
--创建时间：2018-7-23
--描述：获取企业投诉个人记录，更新为已查看
--################################################################
CREATE PROCEDURE [dbo].[v2018_pcPaPlaintSelect]
(
	@paMainID INT
)
AS
SET NOCOUNT ON
BEGIN
	UPDATE PaPlaint SET
		IsViewed = 1 
	WHERE paMainID = @paMainID

	SELECT a.*, c.Name CompanyName,c.SecondID
	FROM PaPlaint a WITH(NOLOCK)
	LEFT JOIN caMain b WITH(NOLOCK) ON a.caMainID = b.ID
	LEFT JOIN cpMain c WITH(NOLOCK) ON b.cpMainID = c.ID
	WHERE paMainID = @paMainID
	ORDER BY ID DESC
END
SET NOCOUNT OFF
GO
/****** Object:  StoredProcedure [dbo].[v2018_pcPaVerifyLogInsert]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--####################################################
--添加人：Lucifer
--添加时间：2018-6-27
--描述：获取短信/邮件验证码
--返回值 -1 邮件已认证
--       -2 一天同一IP验证超过10次
--       -3 一天同一手机号/邮件验证超过5次
--       -4 5分钟内同一手机号/邮件超过3次
--####################################################
CREATE PROCEDURE [dbo].[v2018_pcPaVerifyLogInsert] 
(
    @Mobile VARCHAR(11),
    @Email VARCHAR(50),
    @IP VARCHAR(31),
    @paMainID INT
)
AS
SET NOCOUNT ON
BEGIN
	SET @Mobile = dbo.v2018_SetVarcharNull(@Mobile)
	SET @Email = dbo.v2018_SetVarcharNull(@Email)

	IF @Mobile IS NOT NULL
	BEGIN
		IF LEFT(@Mobile, 7) = '1713075' --该号段都是骗子
		BEGIN
			RETURN -2
		END
	END

    IF CHARINDEX(', ', @IP) > 0
        SET @IP = RIGHT(@IP, LEN(@IP) - CHARINDEX(', ', @IP))

    DECLARE @VerifyCount SMALLINT
    SELECT @VerifyCount = COUNT(1) FROM paVerifyLog WITH(NOLOCK)
    WHERE [IP] = @IP
    AND AddDate > CONVERT(VARCHAR(10), GETDATE(), 120)

    IF @VerifyCount >= 10 AND @IP <> '60.215.144.163'  --一天同一IP验证超过10次
        RETURN -2

    SELECT @VerifyCount = COUNT(1) FROM paVerifyLog WITH(NOLOCK)
    WHERE (Mobile = @Mobile OR Email = @Email)
    AND AddDate > CONVERT(VARCHAR(10), GETDATE(), 120)

    IF @VerifyCount >= 5  --一天同一手机号或邮箱验证超过5次
        RETURN -3

    SELECT @VerifyCount = COUNT(1) FROM paVerifyLog WITH(NOLOCK)
    WHERE (Mobile = @Mobile OR Email = @Email)
    AND AddDate > DATEADD(MINUTE, -5, GETDATE())

    IF @VerifyCount >= 3  --5分钟内同一手机号或邮箱超过3次
        RETURN -4

	IF EXISTS(SELECT TOP 1 'X' FROM paMain WITH(NOLOCK) WHERE Username = @Email AND EmailVerifyDate IS NOT NULL)
		RETURN -1

    DECLARE @VerifyCode VARCHAR(6)
    SELECT @VerifyCode = RAND() * 899999 + 100000
    INSERT INTO paVerifyLog(paMainID, Email, Mobile, VerifyCode, VerifyDate, AddDate, [IP])
    VALUES(@paMainID, @Email, @Mobile, @VerifyCode, NULL, GETDATE(), @IP)

    RETURN @VerifyCode
END
SET NOCOUNT OFF
GO
/****** Object:  StoredProcedure [dbo].[v2018_pcPaVerifyLogUpdate]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--####################################################
--添加人：Lucifer
--添加时间：2018-6-27
--描述：验证个人认证码，并做相应操作
--CerType 1 邮箱认证 UPDATE paMain
--		  2 手机号认证 UPDATE paMain
--        3 手机号登陆
--        4 手机号注册
--返回值 -1  认证失败
--       >=0 返回paMainId
--####################################################
CREATE PROCEDURE [dbo].[v2018_pcPaVerifyLogUpdate] 
(
	@Mobile VARCHAR(11),
	@Email VARCHAR(50),
	@CerCode VARCHAR(6),
	@CerType TINYINT
)
AS
SET NOCOUNT ON
BEGIN
	SET @Mobile = dbo.v2018_SetVarcharNull(@Mobile)
	SET @Email = dbo.v2018_SetVarcharNull(@Email)

	DECLARE @paMainID INT
	DECLARE @paVerifyLogID INT

	SELECT TOP 1 @paMainID = paMainID, @paVerifyLogID = ID
	FROM paVerifyLog WITH(NOLOCK)
	WHERE (Mobile = @Mobile
        OR Email = @Email)
		AND VerifyCode = @CerCode
		AND VerifyDate IS NULL
        AND AddDate > DATEADD(HOUR, -1, GETDATE())
	ORDER BY ID DESC

	IF @paVerifyLogID IS NULL --验证码错误
	BEGIN
		RETURN -1
	END

	UPDATE paVerifyLog SET
		VerifyDate = GETDATE()
	WHERE ID = @paVerifyLogID

	IF @CerType = 1 AND @Email IS NOT NULL --邮箱认证
	BEGIN
		UPDATE paMain SET EmailVerifyDate = GETDATE() WHERE ID = @paMainID
	END
	ELSE IF @CerType = 2 AND @Mobile IS NOT NULL --手机号认证
	BEGIN
		UPDATE paMain SET MobileVerifyDate = NULL WHERE Mobile = @Mobile
		UPDATE paMain SET
			Mobile = @Mobile
		WHERE ID = @paMainID

		UPDATE paMain SET
			MobileVerifyDate = GETDATE()
		WHERE ID = @paMainID
	END
	RETURN @paMainID
END
SET NOCOUNT OFF
GO
/****** Object:  StoredProcedure [dbo].[v2018_ProcCaCvViewCntLogInsert]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--半小时检查一次，企业浏览下载的简历的数量
--如超过限定数量则禁止登录短信，rtx通知
--harry 2018-8-10
CREATE PROCEDURE [dbo].[v2018_ProcCaCvViewCntLogInsert] 
AS
BEGIN
	DECLARE @maxViewcnt INT 
	SET @maxViewcnt = 100
	CREATE TABLE #t
	(
		Id INT IDENTITY(1,1),
		cpMainId INT,
		caMainId INT,
		cvViewCnt INT,---浏览总数量
		downLoadCvViewCnt INT,---浏览下载简历数量
		exjobapplyViewCnt INT---申请的职位浏览量
	)
	--查询半小时内浏览简历的用户数据
	INSERT INTO #t(caMainId)
	SELECT DISTINCT caMainId
	FROM cacvviewlog WITH(NOLOCK)
	WHERE DATEDIFF(MINUTE ,adddate,GETDATE())<31 
        AND caMainId NOT IN(select id from camain WITH(NOLOCK) WHERE cpMainId=7269599)
	--更新企业信息
	UPDATE #t
	SET cpMainId=(SELECT cpMainId FROM caMain  WITH(NOLOCK) WHERE id=#t.caMainID) 
	--计算查看简历数量
	DECLARE @id INT, @cpMainId INT,@caMainId INT
	SET @id=0
	WHILE EXISTS(SELECT 'x' FROM #t WHERE id>@id)
	BEGIN
		SELECT TOP 1 @id = id, @cpMainId= cpMainId, @caMainId = camainId FROM #t WHERE id>@id ORDER by id 
		print @caMainId
		--计算浏览量
		UPDATE #t SET cvViewCnt=(
			SELECT COUNT(1) FROM cacvviewlog  WITH(NOLOCK)
			WHERE camainId= @caMainId 
			AND DATEDIFF(MINUTE ,adddate,GETDATE())<31
			)
		WHERE caMainId = @caMainId
		--计算浏览下载量
		UPDATE #t SET DownLoadCvViewCnt=(
			SELECT COUNT(1) FROM cacvviewlog  WITH(NOLOCK)
			WHERE camainId= @caMainId
			AND cvmainId IN(select cvMainID FROM caactivelog  WITH(NOLOCK) WHERE cpMainId= @cpMainId)
			AND DATEDIFF(MINUTE,adddate,GETDATE())<31
			)
		WHERE caMainId = @caMainId
		--计算查看应聘的简历数量
		UPDATE #t SET exjobapplyViewCnt=(
			SELECT COUNT(1) FROM cacvviewlog  WITH(NOLOCK) 
			WHERE camainId= @caMainId
			AND cvmainId IN(select cvMainID FROM exjobapply WITH(NOLOCK) WHERE jobId IN(select id FROM job WHERE cpMainID= @cpMainId))
			AND DATEDIFF(MINUTE,adddate,GETDATE())<31
			)
		WHERE caMainId = @caMainId

	END
	--处理查看超出数量的用户,限制用户登录
	SELECT * INTO #t0 FROM #t WHERE (ISNULL(downLoadCvViewCnt,0)+ISNULL(exjobapplyViewCnt,0))> @maxViewcnt
	
	INSERT INTO caCvviewCntLog(camainId, cpMainId, cvViewCnt, downLoadCvViewCnt,exjobapplyViewCnt, adddate)
	SELECT camainId, cpMainId, cvViewCnt, downLoadCvViewCnt,exjobapplyViewCnt, GETDATE()
	FROM #t0
	
	--限制登录，同时发短信，rtx
	SELECT @id=0,@cpMainId=0,@caMainId =0
	WHILE EXISTS(SELECT 'x' FROM #t0 WHERE id>@id)
	BEGIN
		SELECT TOP 1 @id = id, @cpMainId= cpMainId, @caMainId = camainId FROM #t0 WHERE id>@id ORDER by id 
		
		EXEC bpCpMainByIsLimitLoginUpdate @cpMainId, 9, 1, '短时间内浏览大量简历限制登录'
		INSERT INTO rtxnotifylog
		SELECT ISNULL(ConsultantID,0),'短时间内浏览大量简历限制登录通知',Name+'('+LTRIM(STR(ID))+')企业短时间内浏览大量简历，已限制登录！http://sysback.51rc.com/newoa/company/cp/cpMainInfo?id=' + LTRIM(STR(ID)) + '&code=' + LTRIM(STR(DATEPART(HOUR, RegDate) * 100 + DATEPART(MINUTE, RegDate))),1,0,0,null,getdate()
		FROM cpMain WITH(NOLOCK)
		WHERE ID =@cpMainId
	END
	
	DROP TABLE #t
	DROP TABLE #t0
END




GO
/****** Object:  StoredProcedure [dbo].[v2018_procCvVoiceJobTypeInsert]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--################################################################
--创建人：Allen
--创建时间：2018-7-23
--描述：职位类别关键词添加职位类别关联（后台审核用）
--################################################################
CREATE PROCEDURE [dbo].[v2018_procCvVoiceJobTypeInsert]
(
	@cvVoiceID INT, 
	@JobType VARCHAR(100)
)
AS
SET NOCOUNT ON
BEGIN
	IF @cvVoiceID IS NULL
		RETURN 0
	IF @JobType IS NULL
		RETURN 0

	IF NOT EXISTS(SELECT 'x' FROM cvVoiceText WITH(NOLOCK) WHERE ID = @cvVoiceID)
		RETURN 0

 
	DELETE FROM cvVoiceJobType WHERE cvVoiceID = @cvVoiceID
	INSERT cvVoiceJobType(cvVoiceID, dcJobTypeID)
	SELECT @cvVoiceID, a FROM dbo.FnSplit(@JobType, ' ')

	UPDATE CvVoiceText SET MatchDate = GETDATE() WHERE ID = @cvVoiceID
END
GO
/****** Object:  StoredProcedure [dbo].[v2018_procCvVoiceTextSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--##################################################################
--添加人：Allen
--添加时间：2018-7-20
--描述：智能匹配职位类别，如果没有，添加到数据库由人工添加
--##################################################################
CREATE PROCEDURE [dbo].[v2018_procCvVoiceTextSelect]
(
	@voiceText NVARCHAR(100)
)
AS
SET NOCOUNT ON
BEGIN
	CREATE TABLE #T(
		dcJobTypeID INT,
		[Description] NVARCHAR(20),
		ParentID NVARCHAR(20)
	)
	IF EXISTS(SELECT 'x' FROM CvVoiceText WITH(NOLOCK) WHERE voiceText = @voiceText AND MatchDate IS NOT NULL)
	BEGIN
		INSERT INTO #T
		SELECT b.dcJobTypeID, c.[Description],''
		FROM cvVoiceText a WITH(NOLOCK),cvVoiceJobType b WITH(NOLOCK),dcJobType c WITH(NOLOCK) 
		WHERE a.ID=b.cvVoiceID AND b.dcJobTypeID=c.ID AND a.MatchDate IS NOT NULL AND a.voiceText=@voiceText
	END
	ELSE 
	BEGIN
		--优先取完全匹配，包括/多个的
		INSERT INTO #T
		SELECT id,[Description],ParentID
		FROM dcJobType WITH(NOLOCK)
		WHERE [Description] LIKE '%/' + @voiceText OR [Description] LIKE @voiceText + '/%' OR  [Description] = @voiceText

		DELETE FROM #T WHERE ParentID IN (SELECT dcJobTypeID FROM #T)
		--取模糊匹配大类
		IF NOT EXISTS(SELECT TOP 1 'X' FROM #T)
		BEGIN
			INSERT INTO #T
			SELECT ID, [Description],''
			FROM dcJobType WITH(NOLOCK)
			WHERE [Description] LIKE '%' + @voiceText + '%' AND ParentID IS NULL
		END

		--取模糊匹配小类
		IF NOT EXISTS(SELECT TOP 1 'X' FROM #T)
		BEGIN
			INSERT INTO #T
			SELECT ID, [Description],''
			FROM dcJobType WITH(NOLOCK)
			WHERE [Description] LIKE '%' + @voiceText + '%' AND ParentID IS NOT NULL
		END

		--如果都匹配不到，插入CvVoiceText，等待审核补充
		IF NOT EXISTS(SELECT TOP 1 'X' FROM #T)
		BEGIN
			IF NOT EXISTS(SELECT 'x' FROM CvVoiceText WITH(NOLOCK) WHERE voiceText = @voiceText)
			BEGIN
				INSERT INTO CvVoiceText(voiceText) VALUES(@voiceText)
			END
		END
	END
	SELECT TOP 5 * FROM #T
	DROP TABLE #T
END
SET NOCOUNT OFF

GO
/****** Object:  StoredProcedure [dbo].[v2018_procInfoDateReportUpdate]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--添加时间 20180612
--添加人   Lucifer
--用途     Info_DateReport数据更新
--#####################################################
CREATE PROCEDURE [dbo].[v2018_procInfoDateReportUpdate] 
(
	@Province_Id SMALLINT,
	@InfoManager_Id SMALLINT,
	@IP VARCHAR(15),
	@Referer VARCHAR(100)
)
AS
SET NOCOUNT ON
BEGIN
	IF NOT EXISTS(
		SELECT TOP 1 'X'
		FROM Info_DateReport WITH(NOLOCK)
		WHERE Countdate = CONVERT(VARCHAR(8), GETDATE(), 112)
		AND Province_Id = @Province_Id
		AND InfoManager_Id = @InfoManager_Id
	)
	BEGIN
		INSERT INTO Info_DateReport (Province_Id, InfoManager_Id, CountDate) 
		VALUES(@Province_Id, @InfoManager_Id, CONVERT(VARCHAR(8), GETDATE(), 112))
	END

	IF NOT EXISTS(
		SELECT TOP 1 'X'
		FROM InfoLog WITH(NOLOCK)
		WHERE AddDate > GETDATE()-1
		AND InfoManager_Id = @InfoManager_Id
		AND [IP] = @IP
		AND [IP] NOT LIKE '60.215.144%'
	)
	BEGIN
		UPDATE Info_DateReport SET Homepage = Homepage + 1  
		WHERE CountDate = CONVERT(VARCHAR(8), GETDATE(), 112)
		AND Province_Id = @Province_Id
		AND InfoManager_Id = @InfoManager_Id

		INSERT INTO InfoLog(InfoManager_Id, [IP], Referer) VALUES(@InfoManager_Id, @IP, @Referer)
		RETURN 1
	END
	ELSE
	BEGIN
		RETURN 0
	END
END
SET NOCOUNT OFF


GO
/****** Object:  StoredProcedure [dbo].[v2018_procSmsMessageLogInsert]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2018.6.28
--创建人：John
--说明：短信通知日志新增
--@SendStatus = 1 实时发送成功，插入一条已完成的记录
--@SendStatus = 0 实时发送失败，插入一条待发送的记录
--#####################################################
CREATE PROCEDURE [dbo].[v2018_procSmsMessageLogInsert]
(
	@SendMan SMALLINT,
	@ManagerUserId SMALLINT,
	@paMainId INT,
	@caMainId INT,
	@Mobile VARCHAR(20),
	@Msg NVARCHAR(210),
	@MsgType TINYINT,
	@PortNo INT,
	@IsCat BIT,
	@SendStatus INT
)
AS
SET NOCOUNT ON
BEGIN TRY
	IF @SendStatus = 0
	BEGIN
		IF @MsgType IN(102, 105) AND @paMainId > 0
		BEGIN
			IF EXISTS(SELECT 'x' FROM wxFans WITH(NOLOCK) WHERE paMainId = @paMainId)
				RETURN 0
		END
		IF EXISTS(SELECT 'x' FROM SmsMessageLog WITH(NOLOCK) WHERE Mobile = @Mobile AND Msg = @Msg AND AddDate > GETDATE() - 0.3)
			RETURN 0
 
		INSERT INTO SmsMessageLog (SendMan, ManagerUserId, paMainId, caMainId, Mobile, Msg, MsgType, IsCat)
		SELECT @SendMan, @ManagerUserId, @paMainId, @caMainId, @Mobile, @Msg, @MsgType, @IsCat
	END
	ELSE
	BEGIN
		INSERT INTO SmsMessageLog (SendMan, ManagerUserId, paMainId, caMainId, Mobile, Msg, MsgType, IsCat, PortNo, SendDate, SendStatus)
		SELECT @SendMan, @ManagerUserId, @paMainId, @caMainId, @Mobile, @Msg, @MsgType, @IsCat, @PortNo, GETDATE(), 1
	END
	RETURN 1
END TRY
BEGIN CATCH
	RETURN 0
END CATCH
SET NOCOUNT OFF
GO
/****** Object:  StoredProcedure [dbo].[v2018_procUrlClickLogInsert]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--添加时间 20180612
--添加人   Lucifer
--用途     UrlClickLog添加
--#####################################################
CREATE PROCEDURE [dbo].[v2018_procUrlClickLogInsert] 
	@ID SMALLINT,
	@IP VARCHAR(15)
AS
SET NOCOUNT ON
BEGIN
	IF (
		(SELECT COUNT(1) FROM Url_Click_Log WITH(NOLOCK) WHERE [IP] = @IP AND Url_Id = @ID AND AddDate > GETDATE()-1) = 0
		OR
		(SELECT TOP 1 Ip_Repeat FROM [Url] WITH(NOLOCK) WHERE ID = @ID) = 2
	)
	BEGIN
		INSERT INTO Url_Click_Log (Url_Id,[IP]) VALUES(@ID, @IP)
		UPDATE [Url] SET AllClick = AllClick + 1,TodayClick = TodayClick + 1 WHERE ID = @ID
	END
END
SET NOCOUNT OFF


GO
/****** Object:  StoredProcedure [dbo].[v2018_procWxMessageReceiveInsert]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2018-7-11
--创建人：Lucifer
--说明：微信操作日志
--LogType 1、关注 2、取消关注 3、发送文本 4、发送地理位置 5、点击菜单
--        6、点击链接 7、绑定个人账号 8、取消绑定个人账号 10、发送语音
--        11、发送视频 12、发送图片 13、扫描二维码 14、绑定企业账号 15、取消绑定企业账号
--#####################################################
CREATE PROCEDURE [dbo].[v2018_procWxMessageReceiveInsert]
(
    @OpenID VARCHAR(100),
    @LogType INT,
    @ProvinceID INT,
    @Message VARCHAR(200),
    @paMainID INT
)
AS
SET NOCOUNT ON
BEGIN
    DECLARE @WxServiceNoID INT
    --根据省份得到服务号id
    SELECT TOP 1 @WxServiceNoID = ID FROM WxServiceNO WHERE ProvinceID = @ProvinceID

    DECLARE @WxFansID INT
    SELECT TOP 1 @WxFansID = ID FROM WxFans WHERE OpenID = @OpenID
    IF @WxFansID IS NULL
    BEGIN
        --插入粉丝表
        INSERT INTO WxFans(OpenID, AttentionDate, [Status], WxServiceNoID, paMainID)
        VALUES (@OpenID, GETDATE(), 1, @WxServiceNoID, NULL)
        SELECT @WxFansID = @@IDENTITY
    END
    
    DECLARE @Content VARCHAR(50)
    IF @LogType = 1
    BEGIN
        SET @Content = '关注'
        --更新粉丝表
        UPDATE WxFans SET
			[Status] = 1,
			AttentionDate = GETDATE(),
			WxServiceNoID = @WxServiceNoID 
        WHERE ID = @WxFansID
    END
    ELSE IF @LogType = 2
    BEGIN
        SET @Content = '取消关注'
        --更新粉丝表
        UPDATE WxFans SET
			[Status] = 0,
			AttentionCancelDate = GETDATE()
		WHERE ID = @WxFansID
        --删除 paLoginContact 暂时不删除，因为优先判断取消关注了，不会到paLoginContact查询
        --DELETE FROM paLoginContact WHERE OpenID = @OpenID AND ContactType = 4
		--DELETE FROM paLoginContact WHERE OpenID = @OpenID AND ContactType = 101
    END
    ELSE IF @LogType = 3
    BEGIN
        SET @Content = '发送文本'
        --更新粉丝表最后发送消息
        UPDATE WxFans SET LastSendMessage = @Message WHERE ID = @WxFansID
    END
    ELSE IF @LogType = 4
    BEGIN
        SET @Content = '发送地理位置'
    END
    ELSE IF @LogType = 5
    BEGIN
        SET @Content = '点击菜单'
    END
    ELSE IF @LogType = 6
    BEGIN
        SET @Content = '点击链接'
    END
    ELSE IF @LogType = 7
    BEGIN
        SET @Content = '绑定个人账号'
        --更新粉丝表
        UPDATE WxFans SET
			[Status] = 2,
			paMainID = @paMainID
		WHERE ID = @WxFansID
    END
    ELSE IF @LogType = 8
    BEGIN
        SET @Content = '取消绑定个人账号'
        --更新粉丝表
        UPDATE WxFans SET
			[Status] = 1
		WHERE ID = @WxFansID
        --删除paLoginContact
        DELETE FROM paLoginContact WHERE OpenID = @OpenID AND ContactType = 4
		--关闭你的菜
		--UPDATE paMain SET IsUseYourFood = 0 WHERE ID = @paMainID
    END
    ELSE IF @LogType = 10 
    BEGIN
        SET @Content = '发送语音'
    END
    ELSE IF @LogType = 11 
    BEGIN
        SET @Content = '发送视频'
    END
    ELSE IF @LogType = 12 
    BEGIN
        SET @Content = '发送图片'
    END
    ELSE IF @LogType = 13 
    BEGIN
        SET @Content = '扫描二维码'
    END
    ELSE IF @LogType = 14
    BEGIN
        SET @Content = '绑定企业账号'
        --更新粉丝表
        UPDATE WxFans SET
			caMainID = @paMainID,
			caBindCancelDate = NULL
		WHERE ID = @WxFansID
        --插入积分200        
		INSERT INTO cpPoint(cpMainID, ChangeID, Point, LastModifyDate)
		SELECT TOP 1 cpMainID, 21, 200, GETDATE() FROM caMain WHERE ID = @paMainID
    END
    ELSE IF @LogType = 15 
    BEGIN
        SET @Content = '取消绑定企业账号'
        --更新粉丝表
        UPDATE WxFans SET
			caBindCancelDate = GETDATE()
		WHERE ID = @WxFansID
        --删除paLoginContact
        DELETE FROM paLoginContact WHERE OpenID = @OpenID AND ContactType = 101
		--扣除积分200
		INSERT INTO cpPoint(cpMainID, ChangeID, Point, LastModifyDate)
		SELECT TOP 1 cpMainID, 22, -200, GETDATE() FROM caMain WHERE ID = @paMainID
    END
    --插入日志表
	IF dbo.v2018_SetVarcharNull(@Message) IS NULL
	BEGIN
        INSERT INTO WxMessageReceive VALUES(@WxFansID, GETDATE(), @Content, @LogType)
	END
	ELSE
	BEGIN
		INSERT INTO WxMessageReceive VALUES(@WxFansID, GETDATE(), @Message, @LogType)
	END
END
SET NOCOUNT OFF
GO
/****** Object:  StoredProcedure [dbo].[v2018_procWxQrImageInsert]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--Lucifer 2018-6-6
--插入一条微信二维码生成记录
CREATE PROCEDURE [dbo].[v2018_procWxQrImageInsert] 
(
	@PageType INT,
	@IP VARCHAR(31),
	@TypeID INT
)
AS
BEGIN
	INSERT INTO WxQrImage(Ticket, PageType, [IP], paMainId)
	SELECT '', @PageType, @Ip, @TypeID
	RETURN @@IDENTITY
END


GO
/****** Object:  StoredProcedure [dbo].[v2018_tvCongratulationSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--#####################################################
--创建时间：2018.8.20
--创建人：alen
--说明：销售记分牌开通订单实时播报
--#####################################################
CREATE PROCEDURE [dbo].[v2018_tvCongratulationSelect]
(
	@RtxNotifyLogID INT
)
AS
BEGIN
	IF @RtxNotifyLogID > 0
	BEGIN
		SELECT TOP 1 ID,RtxMessage 
		FROM RtxNotifyLog WITH (NOLOCK) 
		WHERE ID > @RtxNotifyLogID 
		AND RtxTitle LIKE '%祝贺%' 
		ORDER BY ID
	END
	ELSE
	BEGIN
		SELECT TOP 1 ID,'' RtxMessage
		FROM RtxNotifyLog WITH (NOLOCK) 
		WHERE RtxTitle LIKE '%祝贺%' 
		ORDER BY ID DESC
	END
END
GO
/****** Object:  StoredProcedure [dbo].[wpCvMainByRefreshDateUpdate]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--lambo 20111009
--手机站刷新简历
--返回值：
--	0	数据库错误
--	-1	手机号已经列入黑名单
--	-2	手机号或求职状态为空
--	-3	该简历不属于该账号
create PROCEDURE [dbo].[wpCvMainByRefreshDateUpdate]
(
    @paMainID INT,
    @cvMainID INT,
    @Mobile VARCHAR(13),
    @dcCareerStatus INT,
    @dcSalaryID INT,
    @RelatedWorkYears INT,
    @IsNegotiable BIT,
    @IP VARCHAR(30)
)
AS
SET NOCOUNT ON
SET @Mobile = dbo.TextTrim(@Mobile)
IF @Mobile IS NULL
	RETURN -2		--手机号空

IF EXISTS(SELECT 'x' FROM Person_BLACK WITH(NOLOCK) WHERE Mobile = @Mobile)
BEGIN
	----有黑名单，则增加拒绝次数
	UPDATE Person_Black SET RefuseCount = RefuseCount + 1 WHERE Mobile = @Mobile
	RETURN -1
END

IF NOT EXISTS(SELECT 'x' FROM cvMain WITH(NOLOCK) WHERE ID = @cvMainID AND paMainID = @paMainID)
	RETURN -3
BEGIN TRAN
	BEGIN TRY
		--如果新旧日志不相同，记录更新手机号的操作
		DECLARE @MobileOld AS VARCHAR(13)
		SELECT @MobileOld = Mobile FROM paMain WITH(NOLOCK) WHERE ID = @paMAinID
		IF ISNULL(@MobileOld, '') <> @Mobile
			INSERT INTO paOperationLog (paMainID, Operation, Details, IP) 
			VALUES(@paMainID, 35,'更新手机号，原手机号：<' + ISNULL(@MobileOld, '') + '>；新手机号：<' + @Mobile + '>', @IP)
	
		UPDATE CvMain SET 
			ReFreshDate = GETDATE(),
			dcSalaryID = @dcSalaryID,
			RelatedWorkYears = @RelatedWorkYears,
			IsNegotiable = @IsNegotiable
		WHERE ID = @cvMainID AND paMainID = @paMainID

		UPDATE paMain SET Mobile = @Mobile --, dcCareerStatus # @dcCareerStatus 
		WHERE ID = @paMainID
		
	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH
COMMIT TRAN
RETURN 1
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END














GO
/****** Object:  StoredProcedure [dbo].[wpCvMainBySendValidSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[wpCvMainBySendValidSelect]
(
	@paMainID INT
)
AS
BEGIN
	SELECT ID,Name FROM cvMain WITH(NOLOCK) 
		WHERE ((cvLevel like '1111_1%' AND VerifyResult=1) 
			OR (cvLevelEng like '1111_1%' AND VerifyResultEng=1)
			OR Attachment>'') AND paMainID = @paMainID
END














GO
/****** Object:  StoredProcedure [dbo].[wpdcSubSiteSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--lambo 20111011
--获取所有省份，当前省份在前
CREATE PROCEDURE [dbo].[wpdcSubSiteSelect]
(
	@ProvinceID INT
)
AS
BEGIN
	SELECT * FROM dcRegion WHERE grade=1
		ORDER BY 
			CASE 
				WHEN id=@ProvinceID THEN 1 
				ELSE id
			END
END














GO
/****** Object:  StoredProcedure [dbo].[wpExMessageLogSelect]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--lambo 20101008
--查询个人与企业的留言记录
CREATE PROCEDURE [dbo].[wpExMessageLogSelect]
(
    @paMainID INT,
    @PageSize INT,
    @SkipCount INT,
    @RowsCount INT OUTPUT
)
AS
BEGIN 
	SELECT @RowsCount = COUNT(1) FROM exMessageC2p a WITH(NOLOCK),
			caMain b WITH(NOLOCK),
			cpMain c WITH(NOLOCK)
			WHERE 
			a.caMainID = b.ID 
			AND b.cpMainID = c.ID
			AND cvMainID IN (SELECT ID FROM cvMain WITH(NOLOCK) WHERE paMainID=@paMainID)
			AND CompanyDeleted=0
			
	SELECT TOP (@PageSize) * INTO #wapMessage FROM
	(
		SELECT 
			a.ID,
			a.IsReply,
			c.ID CpMainID,
			c.SecondID EnCpMainID,
			c.Name CompanyName,
			Message,
			(SELECT top 1 CASE a.IsReply WHEN 1 THEN Message WHEN 0 THEN NULL  END
				FROM ExMessageP2C WITH(NOLOCK) 
				WHERE cvMainID IN (SELECT ID FROM cvMain WITH(NOLOCK) WHERE paMainID=@paMainID)
				AND AddDate>a.AddDate
				AND caMainID = a.caMainID
				ORDER BY ID) MessageReply,
			Row_number() OVER(ORDER BY a.ID DESC) rowNo
		FROM exMessageC2p a WITH(NOLOCK),
			caMain b WITH(NOLOCK),
			cpMain c WITH(NOLOCK)
			WHERE 
			a.caMainID = b.ID 
			AND b.cpMainID = c.ID
			AND cvMainID IN (SELECT ID FROM cvMain WITH(NOLOCK) WHERE paMainID=@paMainID)
			AND CompanyDeleted=0
		) a 
		WHERE a.rowNo >@SkipCount
		UPDATE ExMessageC2P SET IsViewed = 1 WHERE ID IN (SELECT ID FROM #wapMessage) AND IsViewed=0
		SELECT * FROM #wapMessage
END












GO
/****** Object:  StoredProcedure [dbo].[wpPaMainByLoginUpdate]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--------------------------------------------------
--lambo 20110928
--手机站个人用户登录，与pcPaMainByLoginUpdate不同的地方是增加paLoginlog是记录是从手机站登录的。
--LoginFrom%=%1 
--密码加密后的手机登陆
--------------------------------------------------
CREATE PROCEDURE [dbo].[wpPaMainByLoginUpdate]
(
	@UserName VARCHAR(50),
	@Password VARCHAR(50),
	@PasswordDe VARCHAR(60),
	@IP VARCHAR(31),
	@dcSubSiteId SMALLINT,
	@AutoLogin TINYINT,
	@browser VARCHAR(500),
	@ID INT,
	@IDType INT,
	@PaType INT OUTPUT,
	@loginFrom INT
)
AS
SET NOCOUNT ON
BEGIN TRY
	BEGIN TRAN
		DECLARE 
			@Resume_XinxiID AS INT,
			@AddMan AS INT,
			@AddDate AS DATETIME,
			@Email AS VARCHAR(50),
			@CountDate AS INT,
			@dcProvinceID AS TINYINT,
			@TotalLoginNum AS INT,
			@LastLoginDate AS SMALLDATETIME
		
		SELECT @CountDate = CONVERT(VARCHAR(8), GETDATE(), 112), @dcProvinceID = LEFT(@dcSubSiteId, 2)
		SELECT @PaType = @IDType, @UserName = REPLACE(@UserName, ' ', '')
		BEGIN TRY
			IF @PaType=3
			BEGIN
				SELECT @Resume_XinxiID = ID, @AddMan =AddMan, @AddDate = RegDate, @Email = Email
				FROM Resume_Xinxi WITH(NOLOCK INDEX(IX_Resume_Xinxi_UserName))
				WHERE UserName = @UserName AND Password = @Password
				IF @Resume_XinxiID IS NOT NULL
					SET @PaType=2
			END			
			ELSE IF @PaType=0
			BEGIN
				SELECT TOP 1 @Resume_XinxiID = ID, @AddMan =AddMan, @AddDate = RegDate, @Email = Email
				FROM Resume_Xinxi WITH(NOLOCK INDEX(IX_Resume_Xinxi_UserNameLower))
				WHERE UserNameLower = @UserName AND Password = @Password
				ORDER BY ID DESC

				IF @Resume_XinxiID IS NOT NULL
					SET @PaType=4
			END

			IF @PaType=0
				GOTO Err1

			IF @Resume_XinxiID > 0	----账号在Resume_xinxi
			BEGIN
				--lucifer添加，添加新的注册模式
				DECLARE @RegisterFrom AS TINYINT
				SELECT @RegisterFrom = 1
				IF CHARINDEX('ios', LOWER(@browser)) > 0
					SELECT @RegisterFrom = 3
				ELSE IF CHARINDEX('android', LOWER(@browser)) > 0
					SELECT @RegisterFrom = 2

				--把数据从Resume_Xini转换到paMain
				INSERT INTO paMain(RegisterMode, AddMan, UserName, Password, Email, dcProvinceID, dcSubSiteId, RegisterIP, IsDefaultPassword, AddDate, RegisterFrom, RegisterType, SpreadDate)
				VALUES(1, @AddMan, @UserName, @PasswordDe, @Email, @dcProvinceID, @dcSubSiteId, @IP, 1, GETDATE(), @RegisterFrom, 101, @AddDate)
				SET @ID = @@IDENTITY
				INSERT INTO paOperationLog (paMainID, Operation, Details, IP) VALUES(@ID, 10, '导入个人账号成功。', @IP)

				--记录日报
				UPDATE DateReport SET ValidResume = ValidResume + 1
				WHERE province_id = @dcProvinceID AND CountDate = @CountDate
				INSERT INTO pamainDatereport SELECT @ID, 9, GETDATE() -- SEAN 20130911
				--统计信息员注册数据
				SELECT TOP 1 CountDate
				FROM Info_Datereport WITH(NOLOCK)
				WHERE CountDate = @CountDate
				AND province_id = @dcProvinceID
				AND InfoManager_ID = @AddMan
				IF (@@ROWCOUNT=0)
					INSERT INTO Info_DateReport(province_id,infomanager_id,countdate) 
					VALUES(@dcProvinceID, @AddMan, @CountDate)
				
				UPDATE Info_Datereport 
				SET ValidResume=ValidResume + 1  
				WHERE CountDate=@CountDate
				AND province_id=@dcProvinceID
				AND InfoManager_ID = @AddMan
			END

			--超过登陆次数,每天限制登录次数位20次
			IF (SELECT COUNT(1) FROM paLoginLog WITH(NOLOCK) WHERE paMainID = @ID AND AddDate > CONVERT(VARCHAR(10), GETDATE(), 120)) > 19
				GOTO ERR2

			--登陆日志
			SELECT @LastLoginDate = LastLoginDate, @TotalLoginNum = TotalLoginNum FROM paMain WITH(NOLOCK) WHERE ID = @Id

			IF CONVERT(VARCHAR(8), @LastLoginDate, 112) = CONVERT(VARCHAR(8), GETDATE(), 112)	--今天已经登陆过
			BEGIN
				--IF @AutoLogin = 0			--首页的自动登录不计算在每日登陆次数
				--BEGIN
				INSERT INTO paLoginLog(paMainID, LoginIP, browser, loginFrom) VALUES(@ID, @IP, '6:' + ISNULL(@browser, 'Null'), @loginFrom)
				SELECT @TotalLoginNum = @TotalLoginNum + 1
				--END

				IF @LastLoginDate < DATEADD(HOUR, -1, GETDATE())	--登录间隔>1小时更新登录时间
					UPDATE paMain SET LastLoginDate = GETDATE(), TotalLoginNum = @TotalLoginNum WHERE ID = @ID
				ELSE
					UPDATE paMain SET TotalLoginNum = @TotalLoginNum WHERE ID = @ID
			END
			ELSE
			BEGIN
				----今天第一次登录
				INSERT INTO paLoginLog(paMainID, LoginIP, browser, loginFrom) VALUES(@ID, @IP, '7:' + ISNULL(@browser, 'Null'), @loginFrom)
				SELECT @TotalLoginNum = @TotalLoginNum + 1

				UPDATE paMain SET TotalLoginNum = @TotalLoginNum, LastLoginDate = GETDATE() WHERE ID = @ID

				UPDATE DateReport
				SET PersonLoginNum_Net = PersonLoginNum_Net + 1  
				WHERE CountDate = CONVERT(VARCHAR(8), GETDATE(), 112)
				AND Province_Id = @dcProvinceID

				--INSERT INTO PaMainDateReport SELECT @Id, 11, GETDATE()	--sean 20130708
			END
		END TRY
		BEGIN CATCH
			GOTO Err3
		END CATCH
	COMMIT
	RETURN @ID
	ERR1:
	BEGIN
		ROLLBACK TRAN
		INSERT INTO LogDb..RegisterErrorLog
		SELECT @ID, '21|' + LTRIM(STR(@IDType)) + '|' + @IP, @UserName + ' ' + @Password, GETDATE()
		RETURN 0
	END
	ERR2:
	BEGIN
		ROLLBACK TRAN
		INSERT INTO LogDb..RegisterErrorLog
		SELECT @ID, '22|' + LTRIM(STR(@IDType)) + '|' + @IP, @UserName + ' ' + @Password, GETDATE()
		RETURN -1
	END
	ERR3:
	BEGIN
		ROLLBACK TRAN
		INSERT INTO LogDb..RegisterErrorLog
		SELECT @ID, '23|' + LTRIM(STR(@IDType)) + '|' + @IP, @UserName + ' ' + @Password, GETDATE()
		RETURN -2
	END
END TRY
BEGIN CATCH
	ROLLBACK TRAN
	INSERT INTO LogDb..RegisterErrorLog
	SELECT @ID, '20|' + LTRIM(STR(@IDType)) + '|' + @IP, @UserName + ' ' + @Password, GETDATE()
END CATCH

GO
/****** Object:  StoredProcedure [dbo].[wpWapSessionUpdate]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[wpWapSessionUpdate]
(
	@SessionID VARCHAR(50)
)
AS
BEGIN
	DECLARE @paMainID INT, @ID INT
	SELECT Top 1 @paMainID = paMainID, @ID = ID FROM WapSession WITH(NOLOCK) 
		WHERE SessionID = @SessionID
		AND RefreshDate > DateAdd(HOUR,-1,GETDATE())
	ORDER BY ID DESC

	SET @paMainID = ISNULL(@paMainID, 0)
	IF @paMainID > 0
	BEGIN
		UPDATE WapSession SET RefreshDate = GETDATE() WHERE SessionID=@SessionID
		DELETE FROM WapSession WHERE ID <> @ID AND paMainID = @paMainID
	END
	RETURN @paMainID
END

GO
/****** Object:  Trigger [dbo].[Tri_AdverProject_Insert]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--Carl 2018-04-26
--插入之后触发
CREATE TRIGGER [dbo].[Tri_AdverProject_Insert]
ON [dbo].[AdverProject]
AFTER INSERT
AS
SET NOCOUNT ON
BEGIN
	DECLARE @InsertId INT --插入行的id
	DECLARE @InsertWidth INT --插入行宽度
	DECLARE @ProvinceId INT   --插入的省份id
	DECLARE @OrderId INT  ---订单id
	DECLARE @AddMan INT  --添加人
	DECLARE @IsSelf INT 
	DECLARE @BeginTime SMALLDATETIME
	DECLARE @Type INT ---广告类型=10 触发
	DECLARE @IsInsert INT
	DECLARE @MaxOrderBy INT 
	DECLARE @Paid INT 
	DECLARE @Id INT 
	DECLARE @Width INT 
	DECLARE @LineNum6 INT 
	DECLARE @LineNum3 INT 
	DECLARE @TotalWidth INT 

	DECLARE @MaxLineNum3 INT --3/6最大个数
	DECLARE @MaxLineNum6 INT --6/6最大个数

	DECLARE @AdminList VARCHAR(100)  --编辑人员
	DECLARE @SendList VARCHAR(100)  --信息接收人员

	SET @AdminList='153,155,158,212' 
	SET @SendList='153,158,212' 

	SET @LineNum6=0
	SET @LineNum3=0
	SET @TotalWidth=0
	SET @MaxLineNum6=3
	SET @MaxLineNum3=8

	--先判断是不是新增操作
	IF EXISTS(SELECT 1 FROM inserted) AND NOT EXISTS(SELECT 1 FROM deleted)
		SET @IsInsert = 1
	ELSE
		SET @IsInsert = 0

	IF @IsInsert=1
	BEGIN
		SELECT @InsertId=Id,@InsertWidth=Width,@ProvinceId=Province_Id,@OrderId=ISNULL(CaOrderID,0),
			@IsSelf=IsSelf,@AddMan=AddMan,@BeginTime=BeginTime,@Type=[Type] FROM INSERTED 
		--PRINT '插入操作' 

		IF @ProvinceId=0
		BEGIN
			--PRINT '51人才编辑自己操作'
			RETURN 
		END
		
		--IF @ProvinceId<>64 AND @ProvinceId<>83 
		--BEGIN
			----PRINT '非西藏、新疆地区'
			--RETURN
		--END

		IF @Type<>10
		BEGIN
			--PRINT '非首页横排广告'
			RETURN 
		END

		--IF @AddMan<>155 AND @BeginTime>GETDATE()
		--BEGIN
			----PRINT '请到投放时间投放'
			--RETURN
		--END
		
		--如果是编辑操作，非本网站的放入预备中 =即 begintime>getdate()的,同时更新开始时间为2年后的时间
		IF @BeginTime>GETDATE() AND @IsSelf=0 
		BEGIN
			--PRINT '编辑操作开始时间大放入预备'
			--获取最大的序号，更新序号和开始、结束时间
			SELECT @MaxOrderBy=MAX(ISNULL(Orderby,0)) FROM AdverProject WHERE Province_ID = @ProvinceId AND [Type]=10 AND Begintime>GETDATE() AND Valid=1
			
			IF @MaxOrderBy<100
				SET @MaxOrderBy=100
			ELSE
				SET @MaxOrderBy=@MaxOrderBy+1
			UPDATE AdverProject SET OrderBy=@MaxOrderBy,
				BeginTime=DATEADD(YEAR,2,BeginTime),EndTime=DATEADD(YEAR,2,EndTime) WHERE Id=@InsertId
			RETURN
		END
		
		IF @OrderId<>0
			SELECT @Paid=ISNULL(Paid,0) FROM CaOrder WITH(NOLOCK) WHERE ID=@OrderId
		--如果是自己的放到 valid=0 and IsSelf=1
		IF @IsSelf=1
		BEGIN
			UPDATE AdverProject SET Valid=0 WHERE Id=@InsertId
		END
		ELSE
		BEGIN
			IF @InsertWidth=948 OR @InsertWidth=986 OR @InsertWidth=1100 OR @InsertWidth=1098 
				SET @InsertWidth=6
			ELSE IF @InsertWidth=471 OR @InsertWidth=488 OR @InsertWidth=545 OR @InsertWidth=546
			BEGIN
				SET @InsertWidth=3 
			END
			ELSE IF @InsertWidth=312 OR @InsertWidth=322 OR @InsertWidth=360 OR @InsertWidth=362
				SET @InsertWidth=2
			ELSE IF @InsertWidth=153 OR @InsertWidth=156 OR @InsertWidth=175 OR @InsertWidth=178
				SET @InsertWidth=1

			IF CHARINDEX(CONVERT(VARCHAR,@AddMan),@AdminList)<=0
			BEGIN
				--PRINT '顾问操作，看下是否到总行数及6/6 3/6行数'
				--查询目前该省份展示的广告,遍历获取 总行数
				DECLARE CurrentInfo CURSOR FOR 
					SELECT Id,Width,IsSelf FROM AdverProject WHERE Province_ID = @ProvinceId
						AND [Type] = 10
						AND BeginTime <= CONVERT(SMALLDATETIME, GETDATE())
						AND EndTime > CONVERT(SMALLDATETIME, GETDATE())
						AND Valid = 1 

				OPEN CurrentInfo
				FETCH NEXT FROM CurrentInfo INTO @Id,@Width,@IsSelf 
				WHILE @@fetch_status<>-1
				BEGIN
					IF @Width=948 OR @Width=986 OR @Width=1100 OR @Width=1098
					BEGIN
						SET @Width=6
						SET @LineNum6=@LineNum6+1
					END
					ELSE IF @Width=471 OR @Width=488 OR @Width=545 OR @Width=546
					BEGIN
						SET @Width=3
						SET @LineNum3=@LineNum3+1
					END
					ELSE IF @Width=312 OR @Width=322 OR @Width=360 OR @Width=362
					BEGIN
						SET @Width=2
					END
					ELSE IF @Width=153 OR @Width=156 OR @Width=175 OR @Width=178
					BEGIN
						SET @Width=1
					END
					SET @TotalWidth=@TotalWidth+@Width 
					FETCH NEXT FROM CurrentInfo INTO @Id,@Width,@IsSelf 
				END
				CLOSE CurrentInfo
				DEALLOCATE CurrentInfo 

				IF @OrderId<>0 AND @Paid>0
				BEGIN
					--PRINT '付费的'
					IF EXISTS(SELECT 'X' FROM CaOrder WITH(NOLOCK) WHERE ID=@OrderId AND OpenDate IS NULL)
					BEGIN
						--PRINT '向顾问和编辑发送rtx提醒,还未开通'
						INSERT oadb..RtxSend (Receiver, RtxTitle, RtxMessage, SendType, DelayTime, SendTime, AddTime) 
							VALUES (CONVERT(VARCHAR,@AddMan)+','+@SendList, '广告订单', '该订单尚未开通,订单Id：'+CONVERT(VARCHAR,@OrderId)+',请核实!', 1, 0, null, getdate())
							
					END
					--执行上线存储过程
				END
				ELSE
				BEGIN
					--未付费的   判断总行数
					IF (@TotalWidth-@InsertWidth)/6>=14
					BEGIN
						--PRINT '已到最大行数订单未付费,放到预备里'
						SELECT @MaxOrderBy=MAX(ISNULL(Orderby,0)) FROM AdverProject WHERE Province_ID = @ProvinceId AND [Type]=10 AND Begintime>getdate() AND Valid=1
						
						IF @MaxOrderBy<100
							SET @MaxOrderBy=100
						ELSE
							SET @MaxOrderBy=@MaxOrderBy+1
						UPDATE AdverProject SET OrderBy=@MaxOrderBy,
							BeginTime=DATEADD(YEAR,2,BeginTime),EndTime=DATEADD(YEAR,2,EndTime) WHERE Id=@InsertId
						RETURN
					END
					ELSE
					BEGIN
						--未到总行数
						IF @InsertWidth=6
						BEGIN
							--PRINT '新增的为6/6的'
							IF @LineNum6-1>=@MaxLineNum6
							BEGIN
								--PRINT '6/6到达最大行数'
								--插入前已有3行，放入预备
								SELECT @MaxOrderBy=MAX(ISNULL(Orderby,0)) FROM AdverProject WITH(NOLOCK) WHERE Province_ID = @ProvinceId AND [Type]=10 AND Begintime>getdate() AND Valid=1

								IF @MaxOrderBy<100
									SET @MaxOrderBy=100
								ELSE
									SET @MaxOrderBy=@MaxOrderBy+1
								UPDATE AdverProject SET OrderBy=@MaxOrderBy,
									BeginTime=DATEADD(YEAR,2,BeginTime),EndTime=DATEADD(YEAR,2,EndTime) WHERE Id=@InsertId
								RETURN 
							END	
						END
						IF @InsertWidth=3
						BEGIN
							--PRINT '新增的3/6的'
							IF @LineNum3-1>=@MaxLineNum3
							BEGIN
								--PRINT '3/6已达最大行数,放入预备中'
								SELECT @MaxOrderBy=MAX(ISNULL(Orderby,0)) FROM AdverProject WHERE Province_ID = @ProvinceId AND [Type]=10 AND Begintime>getdate() AND Valid=1 
								IF @MaxOrderBy<100
									SET @MaxOrderBy=100
								ELSE
									SET @MaxOrderBy=@MaxOrderBy+1
								UPDATE AdverProject SET OrderBy=@MaxOrderBy,
									BeginTime=DATEADD(YEAR,2,BeginTime),EndTime=DATEADD(YEAR,2,EndTime) WHERE Id=@InsertId
								RETURN 
							END
						END
					END
				END
			END
			--执行存储过程，重新排序
			--PRINT '执行存储过程'
			EXEC procAdverProjectAutoSort 0,@ProvinceId,@Type
		END
	END
END
GO
ALTER TABLE [dbo].[AdverProject] ENABLE TRIGGER [Tri_AdverProject_Insert]
GO
/****** Object:  Trigger [dbo].[Tri_AdverProject_Update]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--Carl 2018-04-23
--更新之后触发 @Method INT, --0上线(新增，valid) 1手动暂停 2自动暂停
CREATE TRIGGER [dbo].[Tri_AdverProject_Update]
ON [dbo].[AdverProject]
AFTER UPDATE
AS

DECLARE @InsertId INT --更新行的id
DECLARE @InsertWidth INT --更新行宽度
DECLARE @ProvinceId INT   --更新行的省份id
DECLARE @OrderId INT  ---订单id
DECLARE @AddMan INT  --添加人 
DECLARE @IsSelf INT
DECLARE @BeginTime SMALLDATETIME
DECLARE @EndTime SMALLDATETIME 
DECLARE @Type INT ---广告类型=10 触发
DECLARE @CompanyId INT --公司id,放广告重复用
DECLARE @bValid INT --之前的
DECLARE @bBeginTime SMALLDATETIME --之前的开始时间
DECLARE @bEndTime SMALLDATETIME --之前的结束时间

DECLARE @aValid INT --之后的

DECLARE @MaxOrderBy INT 


DECLARE @IsUpdate INT ---是否是更新操作


--判断是否是更新操作
IF EXISTS(SELECT 1 FROM INSERTED) AND EXISTS(SELECT 1 FROM DELETED)
    SET @IsUpdate = 1
ELSE
    SET @IsUpdate = 0

IF @IsUpdate=1
BEGIN
	--PRINT '更新操作'

	--PRINT @IsSelf

	--之后的数据
	SELECT @InsertId=Id,@InsertWidth=Width,@ProvinceId=Province_Id,@OrderId=ISNULL(CaOrderID,0),
		@IsSelf=IsSelf,@AddMan=AddMan,@BeginTime=BeginTime,@EndTime=EndTime,@Type=[Type],@CompanyId=CompanyId,@aValid=Valid FROM INSERTED 
	--之前的数据
	SELECT @bValid=Valid,@bBeginTime=BeginTime,@bEndTime=EndTime FROM DELETED

	IF @ProvinceId=0
	BEGIN
		--PRINT '51人才不进行自动排序'
		RETURN 
	END

	--IF @ProvinceId<>64 AND @ProvinceId<>83 
	--BEGIN
		----PRINT '非西藏、新疆地区' 
		--RETURN
	--END

	IF @Type<>10
	BEGIN
		--PRINT '非首页横排广告'
		RETURN 
	END
	
	IF @IsSelf=1
	BEGIN
		--PRINT '自己的不触发'
		RETURN 
	END
	ELSE
	BEGIN
		--根据时间范围判断是手动还是自动 去掉
		--IF GETDATE()<CONVERT(VARCHAR(100), GETDATE(), 23)+' 23:50:00' AND GETDATE()>CONVERT(VARCHAR(100), GETDATE(), 23)+' 00:20:00' 
		--BEGIN
			--PRINT '手动的'

			IF @aValid<>@bValid
			BEGIN
				--PRINT '状态位变化'
				--执行存储过程
				IF @aValid=1
				BEGIN
					--PRINT '暂停状态发生变化了且要显示到前台,执行存储过程'
					
					EXEC procAdverProjectAutoSort 0,@ProvinceId,@Type
				END
				ELSE
				BEGIN
					/*
					IF NOT EXISTS(SELECT 'X' FROM AdverProject 
						WHERE Province_ID=64 AND Province_ID<>0 AND [Type] = 10 AND BeginTime <= CONVERT(SMALLDATETIME, GETDATE())
						AND EndTime > CONVERT(SMALLDATETIME, GETDATE())
						AND Valid = 1 AND ISNULL(IsSelf,0)<>1  
						AND CompanyId IS NOT NULL 
						AND NOT EXISTS(SELECT 'X' FROM Job WITH(NOLOCK) WHERE cpMainID =AdverProject.CompanyId 
						AND IsDelete = 0 AND IssueEnd> GETDATE() AND IssueDate < GETDATE()) 
						AND NOT EXISTS(SELECT 'X' FROM CaOrder WITH(NOLOCK) WHERE Id=AdverProject.CaOrderID AND Paid>0) AND ID=@InsertId) 
					*/
					
					IF GETDATE()<CONVERT(VARCHAR(100), GETDATE(), 23)+' 05:10:00' OR GETDATE()>CONVERT(VARCHAR(100), GETDATE(), 23)+' 05:30:00'
					BEGIN
						--PRINT '状态位发生变化，需要下线,手动下线'
						EXEC procAdverProjectAutoSort 1,@ProvinceId,@Type
					END
					
				END

					--PRINT '更新触发结束'
				RETURN 
			END
			
			--开始时间发生变化
			IF @bBeginTime<>@BeginTime
			BEGIN
				--PRINT '开始时间变化' 
				--PRINT @bBeginTime
				--PRINT @BeginTime
				IF @BeginTime>CONVERT(SMALLDATETIME,GETDATE()) AND @bBeginTime<=CONVERT(SMALLDATETIME,GETDATE()) AND @aValid=1
				BEGIN
					--PRINT '前台调入预备,放入预备,重新排序'
					--获取最大的序号，更新序号和开始、结束时间
					SELECT @MaxOrderBy=MAX(ISNULL(Orderby,0)) FROM AdverProject WHERE Province_ID = @ProvinceId AND [Type]=10 AND Begintime>GETDATE() AND Valid=1
					IF @MaxOrderBy<100
						SET @MaxOrderBy=100
					ELSE
						SET @MaxOrderBy=@MaxOrderBy+1
					UPDATE AdverProject SET OrderBy=@MaxOrderBy,
						BeginTime=DATEADD(YEAR,2,BeginTime),EndTime=DATEADD(YEAR,2,EndTime) WHERE Id=@InsertId

					--重新排序
					EXEC procAdverProjectAutoSort 1,@ProvinceId,@Type
				END
				ELSE IF @BeginTime<=CONVERT(SMALLDATETIME,GETDATE()) AND @bBeginTime>CONVERT(SMALLDATETIME,GETDATE()) AND @aValid=1
				BEGIN
					--PRINT '预备调到前台'
					
					EXEC procAdverProjectAutoSort 0,@ProvinceId,@Type
					--提醒顾问广告投放了
					INSERT INTO rtxnotIFylog(receiver, rtxtitle, rtxmessage, sENDtype, delaytime, showtype)
					SELECT consultantId, '订单号'+CONVERT(VARCHAR(100),@OrderId)+'广告投放了', '订单号'+CONVERT(VARCHAR(100),@OrderId)+'广告投放了', 1, 0, 0
					FROM cpMain WHERE id=@CompanyId
				END
				RETURN 
			END
			--结束时间发生变化，从过期中调出来
			IF @bEndTime<>@EndTime
			BEGIN
				IF @EndTime>CONVERT(SMALLDATETIME,GETDATE()) AND @bEndTime<=CONVERT(SMALLDATETIME,GETDATE()) AND @aValid=1
				BEGIN
					--PRINT '过期的修改前台显示'
					EXEC procAdverProjectAutoSort 0,@ProvinceId,@Type
				END 
				ELSE IF @EndTime<=CONVERT(SMALLDATETIME,GETDATE()) AND @bEndTime>CONVERT(SMALLDATETIME,GETDATE()) AND @aValid=1
				BEGIN
					--PRINT '前台修改,改为过期'
					EXEC procAdverProjectAutoSort 1,@ProvinceId,@Type
				END
			END
		--END
	END
END 



GO
ALTER TABLE [dbo].[AdverProject] ENABLE TRIGGER [Tri_AdverProject_Update]
GO
/****** Object:  Trigger [dbo].[Tri_Agent_Black_Update]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TRIGGER [dbo].[Tri_Agent_Black_Update]
   ON [dbo].[Agent_Black]
   AFTER INSERT, UPDATE
AS
BEGIN
	SET NOCOUNT ON;
	IF EXISTS(SELECT 'x' FROM Inserted WHERE LEN(Agent) < 4)
	BEGIN
		RAISERROR('The lenght of agent must lagre than 3.', 10, 1)
		ROLLBACK TRANSACTION
		RETURN
	END
END

GO
ALTER TABLE [dbo].[Agent_Black] ENABLE TRIGGER [Tri_Agent_Black_Update]
GO
/****** Object:  Trigger [dbo].[Tri_AssessTestLog_Insert]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TRIGGER [dbo].[Tri_AssessTestLog_Insert]
ON [dbo].[assessTestLog]
AFTER INSERT
AS
BEGIN
    DECLARE @AssessTypeID INT
	
	SELECT  @AssessTypeID = AssessTypeID
	FROM INSERTED

	UPDATE AssessType
	SET UseCount = UseCount + 1
	WHERE ID = @AssessTypeID
END



GO
ALTER TABLE [dbo].[assessTestLog] ENABLE TRIGGER [Tri_AssessTestLog_Insert]
GO
/****** Object:  Trigger [dbo].[Tri_bsCpBackLogin_Insert]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE TRIGGER [dbo].[Tri_bsCpBackLogin_Insert]
   ON [dbo].[bsCpBackLogin]
   AFTER INSERT
AS 
BEGIN
	SET NOCOUNT ON;
	INSERT INTO bsCpBackLoginLog SELECT * FROM Inserted
END

GO
ALTER TABLE [dbo].[bsCpBackLogin] ENABLE TRIGGER [Tri_bsCpBackLogin_Insert]
GO
/****** Object:  Trigger [dbo].[Tri_BsCpModify_INSERT]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TRIGGER [dbo].[Tri_BsCpModify_INSERT]
   ON [dbo].[bsCpModify]
   AFTER INSERT
AS 
BEGIN
	SET NOCOUNT ON;
	DECLARE @Id INT, @c NVARCHAR(MAX), @Word NVARCHAR(20)
    SELECT @id = Id, @c = ColValue FROM Inserted
	SELECT TOP 1 @WOrd = Word FROM dcFilterWord WHERE CHARINDEX(Word, @c) > 0
	IF @Word > ''
	BEGIN
		IF @Word = 'av'
		BEGIN
			SET @c = REPLACE(@c, 'java', '')
			IF CHARINDEX('av', @c) = 0
				RETURN
		END 
		UPDATE bsCpModify SET FilterWord = @Word WHERE ID = @ID
	END
END

GO
ALTER TABLE [dbo].[bsCpModify] ENABLE TRIGGER [Tri_BsCpModify_INSERT]
GO
/****** Object:  Trigger [dbo].[Tri_bsCpVerifyInsert]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TRIGGER [dbo].[Tri_bsCpVerifyInsert]
   ON [dbo].[bsCpVerify]
   AFTER INSERT
AS
BEGIN
	IF (SELECT COUNT(*) FROM Inserted) = 1
	BEGIN
		SET NOCOUNT ON;
		DECLARE @cpMainID AS INT,
			@VerifyResult AS INT,
			@VerifyMan AS INT,
			@CountDate INT

		SELECT @CountDate = YEAR(GETDATE()) * 10000 + MONTH(GETDATE()) * 100 + DAY(GETDATE())

		SELECT @cpMainID = a.ID, @VerifyResult = b.VerifyResult, @VerifyMan = b.VerifyMan
		FROM Inserted b
		INNER JOIN cpMain a WITH(NOLOCK) ON a.id = b.cpMainID
		
		IF NOT EXISTS(
			SELECT 'X' FROM BackData WITH(NOLOCK) WHERE managerid=@VerifyMan AND
				CountDate = @CountDate
		)
			INSERT INTO BackData(managerid,countdate) VALUES (@VerifyMan, @CountDate)

		UPDATE BackData SET Black = Black + 1  
			WHERE ManagerId = @VerifyMan AND
			CountDate = @CountDate

		IF @VerifyResult = 10
		BEGIN
			UPDATE cpMain SET BlockCount = BlockCount + 1,
				VerifyCount = VerifyCount + 1
			WHERE ID = @cpMainID
		END
		ELSE
			UPDATE cpMain SET VerifyCount = VerifyCount + 1
			WHERE ID = @cpMainID

		--短信发送
		IF @VerifyResult = 10
		BEGIN
			INSERT SmsMessageLog(SendMan, ManagerUSerId, paMainId, caMainId, Mobile, MsgType, IsCat, Msg)
			SELECT  @VerifyMan, NULL, NULL, a.ID, a.Mobile, 1, 0,
				IsNULL(a.Name,'') + '您好，您在' + c.subsitename + c.EmailSite + '上填写的企业信息没有审核通过，请及时登录网站修改，以免耽误使用'
			FROM caMain a WITH(NOLOCK), cpMain b WITH(NOLOCK), dcSubSite c WITH(NOLOCK)
			WHERE a.cpMainID = b.ID
			AND b.dcSubSiteID = c.ID
			AND a.AccountType = 1
			AND a.Mobile > ''
			AND b.ID = @cpMainID
			AND b.VerifyCount > 0 
			And b.VerifyResult = 1 
			AND a.IsReceiveSms = 1
		END
	END
END

GO
ALTER TABLE [dbo].[bsCpVerify] ENABLE TRIGGER [Tri_bsCpVerifyInsert]
GO
/****** Object:  Trigger [dbo].[Tri_BsCvVerify_Save]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TRIGGER [dbo].[Tri_BsCvVerify_Save]
   ON [dbo].[bsCvVerify]
   AFTER INSERT, UPDATE
AS 
BEGIN
	SET NOCOUNT ON;

    IF UPDATE(VerifyDate)
	BEGIN
		DELETE FROM ShortDb..BsCvVerifySnap WHERE Id IN(SELECT ID FROM Inserted)
		INSERT ShortDb..BsCvVerifySnap SELECT ID, cvMainId, VerifyDate FROM Inserted
	END

	SET NOCOUNT OFF;
END

GO
ALTER TABLE [dbo].[bsCvVerify] ENABLE TRIGGER [Tri_BsCvVerify_Save]
GO
/****** Object:  Trigger [dbo].[Tri_bsCvVerifyInsert]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TRIGGER [dbo].[Tri_bsCvVerifyInsert]
   ON [dbo].[bsCvVerify]
   AFTER INSERT
AS
BEGIN
	IF (SELECT COUNT(*) FROM Inserted) = 1
	BEGIN
		SET NOCOUNT ON;
		DECLARE @cvMainID AS INT,
			@paMainID AS INT,
			@VerifyResult AS INT,
			@VerifyMan AS INT
		SELECT @VerifyMan =VerifyMan, @cvMainID = cvMainID, @VerifyResult = VerifyResult FROM Inserted b
		SELECT @paMainID = paMainId FROM CvMain WITH(NOLOCK) WHERE ID = @cvMainId

		IF @VerifyResult = 10
		BEGIN
			UPDATE paMain SET BlockCount = BlockCount + 1, VerifyCount = VerifyCount + 1 WHERE ID = @paMainID
			
			--短信发送
			INSERT SmsMessageLog(SendMan, ManagerUSerId, paMainId, caMainId, Mobile, MsgType, IsCat, Msg)
			SELECT  @VerifyMan, NULL, a.ID, NULL, a.Mobile, 102 ,0, 
				IsNULL(a.Name,'') + '您好，您在' + b.subsitename + b.EmailSite + '上填写的简历未审核通过，请及时登录网站修正简历内容，以免影响您的求职'
			FROM paMain a WITH(NOLOCK), dcSubSite b WITH(NOLOCK)
			WHERE a.dcSubSiteID = b.ID
			AND a.Mobile > ''
			AND a.ID = @paMainID
			AND a.IsReceiveSms = 1

			UPDATE cvMain SET IsVerified = 0 WHERE ID = @cvMainID
		END
		ELSE
		BEGIN
			UPDATE paMain SET VerifyCount = VerifyCount + 1 WHERE ID = @paMainID
			UPDATE cvMain SET IsVerified = 1 WHERE ID = @cvMainID
		END
	END
END

GO
ALTER TABLE [dbo].[bsCvVerify] ENABLE TRIGGER [Tri_bsCvVerifyInsert]
GO
/****** Object:  Trigger [dbo].[Tri_bsRtxStatusInsert]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE TRIGGER [dbo].[Tri_bsRtxStatusInsert]
   ON  [dbo].[bsRtxStatus]
   AFTER INSERT
AS 
BEGIN
	SET NOCOUNT ON;
	INSERT bsRtxStatusLog(ManagerUserID, RtxStatus) 
	SELECT ManagerUserID, RtxStatus FROM Inserted
	SET NOCOUNT OFF;
END


GO
ALTER TABLE [dbo].[bsRtxStatus] DISABLE TRIGGER [Tri_bsRtxStatusInsert]
GO
/****** Object:  Trigger [dbo].[Tri_bsRtxStatusLogTime]    Script Date: 2018/9/25 12:40:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE TRIGGER [dbo].[Tri_bsRtxStatusLogTime]
   ON  [dbo].[bsRtxStatus]
   AFTER UPDATE
AS 
RETURN
BEGIN
	SET NOCOUNT ON;
	IF UPDATE(RtxStatus)
	BEGIN
		DECLARE @Now AS INT
		DECLARE @d AS VARCHAR(2)
		DECLARE @intCheckTime AS INT

		SET @D =DATEPART(Hour,GETDATE())
		SET @Now = CONVERT(INT, @D) * 100
		SET @D =DATEPART(MINUTE,GETDATE())
		SET @Now = @Now + CONVERT(INT, @D)

		DECLARE @ID AS INT
		DECLARE @RtxStatus AS TINYINT
		DECLARE @PreRtxStatus AS TINYINT
		DECLARE @OnlineSecond AS INT
		DECLARE @OfflineSecond AS INT
		DECLARE @LeaveSecond AS INT
		DECLARE @AllOnlineTime AS INT
		DECLARE @CheckTime AS DATETIME
		DECLARE @ManagerUserID AS SMALLINT
		DECLARE @TimeSpan AS INT

		SELECT @ID = ID,
			@RtxStatus = RtxStatus,
			@PreRtxStatus = PreRtxStatus,
			@OnlineSecond = OnlineSecond,
			@OfflineSecond = OfflineSecond,
			@LeaveSecond = LeaveSecond,
			@AllOnlineTime = AllOnlineTime,
			@CheckTime = CheckTime,
			@ManagerUserID = ManagerUserID
		FROM Inserted		

		IF @CheckTime > GETDATE()
			SET @CheckTime = DATEADD(s, -10, GETDATE())
		SET @TimeSpan = DATEDIFF(MilliSecond, @CheckTime, GetDate())

		--工作时间,8:30~12:00,13:00~17:30,在此时间段记录,@Now时间用数字表示,容易确定范围
		IF (@Now>=830 AND @Now<=1200) OR (@Now>=1300 AND @Now<=1730)
		BEGIN

			SET @D =DATEPART(Hour,@CheckTime)
			SET @intCheckTime = CONVERT(INT, @D) * 100
			SET @D =DATEPART(MINUTE,@CheckTime)
			SET @intCheckTime = @intCheckTime + CONVERT(INT, @D)

			--如果刚上班，上一个时间从8:30开始
			IF (@Now>=830 AND @Now<=1200) AND @intCheckTime<830
				SET @CheckTime = CONVERT(DATETIME,CONVERT(VARCHAR(10), GETDATE(),120) + ' 8:30:0')

			--午休后，从13:00开始计时,全部更新在先状态记录
			IF (@Now>=1300 AND @Now<=1730) AND @intCheckTime<1300
			BEGIN
				SET @CheckTime = CONVERT(DATETIME,CONVERT(VARCHAR(10), GETDATE(),120) + ' 13:0:0')
				INSERT bsRtxStatusLog(ManagerUserID,RtxStatus) 
				VALUES(@ManagerUserID, @RtxStatus)
			END

			IF @PreRtxStatus <> @RtxStatus
			BEGIN
				DELETE FROM bsRtxStatusLog
				WHERE LogTime > DATEADD(SECOND,-30,GETDATE())
				AND ManagerUserID = @ManagerUserID

				INSERT bsRtxStatusLog(ManagerUserID, RtxStatus)
				VALUES(@ManagerUserID, @RtxStatus)
			END

			IF @PreRtxStatus IN (1, 2)
				UPDATE bsRtxStatus SET AllOnlineTime = AllOnlineTime + @TimeSpan WHERE ID = @ID

			IF @PreRtxStatus = 1
				UPDATE bsRtxStatus 
				SET PreRtxStatus = RtxStatus, OnlineSecond = OnlineSecond + @TimeSpan, CheckTime = GETDATE()
				WHERE ID = @ID
				
			IF @PreRtxStatus = 2
				UPDATE bsRtxStatus 
				SET PreRtxStatus = @RtxStatus, LeaveSecond = LeaveSecond + @TimeSpan, CheckTime = GETDATE()
				WHERE ID = @ID
				
			IF @PreRtxStatus = 0 Or @PreRtxStatus = 11
				UPDATE bsRtxStatus 
				SET PreRtxStatus = @RtxStatus, OfflineSecond = OfflineSecond + @TimeSpan, CheckTime = GETDATE()
				WHERE ID = @ID
		END
		ELSE
			IF @PreRtxStatus IN (1, 2)
				UPDATE bsRtxStatus SET PreRtxStatus = @RtxStatus, AllOnlineTime = AllOnlineTime + @TimeSpan, CheckTime = GETDATE() WHERE ID = @ID
			ELSE
				UPDATE bsRtxStatus SET PreRtxStatus = @RtxStatus, CheckTime = GETDATE() WHERE ID = @ID
		
	END
END


GO
ALTER TABLE [dbo].[bsRtxStatus] ENABLE TRIGGER [Tri_bsRtxStatusLogTime]
GO
/****** Object:  Trigger [dbo].[Tri_bsRtxStatusUpdate]    Script Date: 2018/9/25 12:40:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE TRIGGER [dbo].[Tri_bsRtxStatusUpdate]
   ON  [dbo].[bsRtxStatus]
   AFTER UPDATE
AS
RETURN
BEGIN
	SET NOCOUNT ON;
	IF(SELECT COUNT(*) FROM Inserted) > 1
		RETURN

	DECLARE @RtxStatus AS TINYINT, @ManagerUserID AS SMALLINT, @RtxStatusOld AS TINYINT

	SELECT @RtxStatus = RtxStatus, @ManagerUserID = ManagerUserID FROM Inserted		
	SELECT @RtxStatusOld = RtxStatus FROM Deleted

	IF @RtxStatus <> @RtxStatusOld
	BEGIN
		INSERT bsRtxStatusLog(ManagerUserID,RtxStatus) 
		VALUES(@ManagerUserID, @RtxStatus)
	END
END


GO
ALTER TABLE [dbo].[bsRtxStatus] ENABLE TRIGGER [Tri_bsRtxStatusUpdate]
GO
/****** Object:  Trigger [dbo].[Tri_caDailyGiftLog_Insert]    Script Date: 2018/9/25 12:40:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TRIGGER [dbo].[Tri_caDailyGiftLog_Insert]
   ON [dbo].[caDailyGiftLog]
   AFTER INSERT
AS 
BEGIN
	SET NOCOUNT ON;
	DECLARE @cpMainId INT, @DailyGiftQuota INT
	SELECT @cpMainId = cpMainId FROM Inserted
	SELECT @DailyGiftQuota = DailyGiftQuota FROM cpMain WITH(NOLOCK) WHERE Id = @cpMainId
	IF (SELECT COUNT(*) FROM caDailyGiftLog WITH(NOLOCK) 
		WHERE ConsumeDate = CONVERT(VARCHAR(8), GETDATE(), 112)
		AND cpMainId = @cpMainId) > @DailyGiftQuota
	BEGIN
		RAISERROR('You have download too many resumes.', 10, 1)
		ROLLBACK TRANSACTION
		RETURN
    END
END

GO
ALTER TABLE [dbo].[caDailyGiftLog] ENABLE TRIGGER [Tri_caDailyGiftLog_Insert]
GO
/****** Object:  Trigger [dbo].[Tri_caMainInsert]    Script Date: 2018/9/25 12:40:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TRIGGER [dbo].[Tri_caMainInsert]
   ON [dbo].[caMain]
   AFTER INSERT
AS 
BEGIN
	SET NOCOUNT ON;
	DECLARE @Count AS INT, @cpMainID AS INT, @ID AS INT, @Username AS VARCHAR(50), @AccountType AS TINYINT
	DECLARE @cpName AS VARCHAR(100), @IP AS VARCHAR(31), @Details AS VARCHAR(1000)
	DECLARE @ManagerAccountID AS INT	--管理员用户的id

	SELECT @Count = COUNT(1) FROM Inserted
	
	IF @Count = 1
	BEGIN
		SELECT @ID = ID, @cpMainID = cpMainID, @AccountType = AccountType, @Username = Username FROM Inserted

		IF @AccountType = 1
		BEGIN
			IF EXISTS(SELECT 'x' FROM caMain WHERE AccountType = 1 AND ID <> @ID AND cpMainID = @cpMainID)
			BEGIN
				RAISERROR('用户类型错误！',10,1)
				ROLLBACK TRANSACTION
				RETURN
			END
	
			----操作日志
			SELECT @cpName = [Name], @Ip = RegisterIp FROM cpMain WITH(NOLOCK) WHERE ID = @cpMainID
			SET @Details = '注册企业会员，企业账号ID:' + LTRIM(STR(@cpMainID))
			SET @Details = @Details + '；管理员用户：' + LTRIM(STR(@ID)) + '；用户名：' 
			SET @Details = @Details + LEFT(@Username, 4)  + '*****；单位名称：' + @cpName

			INSERT INTO caOperationLog(caMainID, Operation, Details, IP)
			VALUES(@ID, 10, @Details, @IP)
		END
		ELSE
		BEGIN
			----操作日志			
			SELECT @ManagerAccountID = ID FROM caMain WITH(NOLOCK) WHERE cpMainID = @cpMainID AND AccountType = 1
			IF @ManagerAccountID IS NULL
			BEGIN
				RAISERROR('没有管理员用户！',10,1)
				ROLLBACK TRANSACTION
				RETURN
			END
			SELECT TOP 1 @IP = LoginIP from caLoginLog WITH(NOLOCK) WHERE caMainID = @ManagerAccountID ORDER BY ID DESC
			SET @Details = '创建普通用户：' + LTRIM(STR(@ID)) + '；用户名：' + @Username

			INSERT INTO caOperationLog(caMainID, Operation, Details, IP)
			VALUES(@ID, 10, @Details,	@IP)
		END

		IF EXISTS(SELECT 'x' FROM Company_Xinxi WITH(NOLOCK INDEX(IX_Company_Xinxi_Email))
				WHERE EMail IN(SELECT EMail FROM Inserted))
		BEGIN
			--Sean 2011.12.8 增加，临时纪录推广数据注册的数量，因为推广部说注册数据变少了，所以检查一下
			--INSERT INTO tmpCompany_Xinxi_Check(Email, AddMan, Province_Id, RegDate)
			--SELECT Email, AddMan, Province_Id, RegDate FROM Company_XInxi WITH(NOLOCK)
			--WHERE EMail IN(SELECT EMail FROM Inserted)
			INSERT INTO Logdb..Company_Xinxi_Log(Email, AddMan, Province_Id, RegDate, CompanyName)
			SELECT top 9 Email, AddMan, Province_Id, RegDate, CompanyName FROM maindb..Company_XInxi WITH(NOLOCK)
			WHERE EMail IN(SELECT EMail FROM Inserted)

			DELETE FROM Company_Xinxi WHERE EMail IN(SELECT EMail FROM Inserted)
		END

		DECLARE @RegisterMode AS TINYINT,
			@Password AS VARCHAR(60)			

		SELECT @UserName = UserName, @Password = Password, @cpMainId = cpMainId FROM Inserted
		IF (dbo.IsAccount(@UserName) = 0 OR dbo.IsPassword(@Password) = 0)
		BEGIN
			SELECT @RegisterMode = RegisterMode FROM cpMain WITH(NOLOCK) WHERE ID = @cpMainID
			IF @RegisterMode = 0
			BEGIN
				RAISERROR('用户名或密码格式不正确', 10, 1)
				ROLLBACK TRANSACTION
				RETURN
			END
		END
	END
END

GO
ALTER TABLE [dbo].[caMain] ENABLE TRIGGER [Tri_caMainInsert]
GO
/****** Object:  Trigger [dbo].[Tri_caMainUpdate]    Script Date: 2018/9/25 12:40:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TRIGGER [dbo].[Tri_caMainUpdate]
   ON [dbo].[caMain]
   AFTER UPDATE
AS 
BEGIN
	SET NOCOUNT ON;
	DECLARE @Count AS INT, @cpMainID AS INT, @caMainID AS INT, @tmpInt AS INT, @tmpString AS VARCHAR(1000)
	SELECT @Count = COUNT(1) FROM Inserted

	IF @Count = 1
	BEGIN
		DECLARE @AccountType AS TINYINT
		DECLARE @IsPause AS BIT, @Desc AS VARCHAR(100)
		SELECT @cpMainID = cpMainID, @caMainID = ID, @AccountType = AccountType FROM Inserted

		IF UPDATE(Name)
			IF @AccountType = 1
			BEGIN			
				--重新计算权限
				EXEC spRedifinePrivilage @cpMainID	
			END

		IF UPDATE(IsPause)
		BEGIN
			SELECT @IsPause = IsPause FROM Inserted
			IF @IsPause = 1
			BEGIN
				SET @Desc = '暂停企业用户，用户ID：' + LTRIM(STR(@caMainID))
				EXEC ccCaOperationLogInsert @caMainID, 15, @Desc

				UPDATE Job 
				SET IssueEnd = GETDATE(), 
					IssueDate = CASE WHEN IssueDate > GETDATE() THEN CONVERT(VARCHAR(10), GETDATE(), 23) ELSE IssueDate END,
					Valid = 0
				WHERE caMainID = @caMainID
				AND Valid = 1
			END
			ELSE
			BEGIN
				SET @Desc = '启用企业用户，用户ID：' + LTRIM(STR(@caMainID))
				EXEC ccCaOperationLogInsert @caMainID, 16, @Desc
			END
			
			--重新计算权限
			EXEC spRedifinePrivilage @cpMainID	
		END
	
		----禁止修改用户类型
		IF UPDATE(AccountType)
		BEGIN
			RAISERROR('Error',10,1)
			ROLLBACK TRANSACTION
			RETURN
		END
		----检查手机号是否正确格式
		IF UPDATE(Mobile)
		BEGIN
			DECLARE @Mobile AS VARCHAR(13)
			SELECT @Mobile = Mobile FROM Inserted
			IF LEN(ISNULL(@Mobile, '')) > 0
			BEGIN
				IF dbo.IsMobile(@Mobile) = 0
				BEGIN
					RAISERROR('Error',10,1)
					ROLLBACK TRANSACTION
					RETURN
				END
			END
		END

		----记录密码修改的相关操作
		IF UPDATE(Password)
		BEGIN
			IF dbo.IsPassword((SELECT Password FROM Inserted)) = 0
			BEGIN
				RAISERROR('密码格式不正确', 10, 1)
				ROLLBACK TRANSACTION
				RETURN
			END
			SET @Desc = '修改密码'
			EXEC ccCaOperationLogInsert @caMainID, 31, @Desc

			----如果是默认密码则修改
			IF @AccountType = 1
				IF EXISTS(SELECT 'x' FROM cpMain WITH(NOLOCK) WHERE ID = @cpMainID AND IsDefaultPassword = 1)
					UPDATE cpMain SET IsDefaultPassword = 0 WHERE ID = @cpMainID
		END

		IF UPDATE(UserName)
		BEGIN
			IF dbo.IsAccount((SELECT UserName FROM Inserted)) = 0
			BEGIN
				RAISERROR('用户名格式不正确', 10, 1)
				ROLLBACK TRANSACTION
				RETURN
			END
			DECLARE @UsernameOld AS VARCHAR(50), @Username AS VARCHAR(50)
			SELECT @UsernameOld = Username FROM Deleted
			SELECT @Username = Username FROM Inserted

			SET @Desc = '修改用户名：原用户名=' + @UsernameOld +'；新用户名=' + @Username
			EXEC ccCaOperationLogInsert @caMainID, 30, @Desc
		END

		IF UPDATE(IsDelete)
		BEGIN
			DECLARE @IsDelete AS BIT
			SELECT @IsDelete = IsDelete FROM Inserted
			IF @IsDelete = 1
			BEGIN
				UPDATE Job SET IsDelete = 1 
				WHERE caMainId IN(
						SELECT ID FROM Inserted WHERE IsDelete = 1)
				AND IsDelete = 0

				SET @Desc = '删除用户：用户ID:' + CONVERT(CHAR(10),@caMainID)
				EXEC ccCaOperationLogInsert @caMainID, 17, @desc

				DELETE FROM bsCpModify WHERE caMainID = @caMainID
				--删除非管理员，重新计算权限
				IF @AccountType = 2
					EXEC spRedifinePrivilage @cpMainID	
			END
		END

		IF UPDATE(EMail)
		BEGIN
			IF EXISTS(SELECT 'x' FROM Company_Xinxi WITH(NOLOCK INDEX(IX_Company_Xinxi_Email))
						WHERE EMail IN(SELECT EMail FROM Inserted))
				DELETE FROM Company_Xinxi WHERE EMail IN(SELECT EMail FROM Inserted)
		END
	END
END






GO
ALTER TABLE [dbo].[caMain] ENABLE TRIGGER [Tri_caMainUpdate]
GO
/****** Object:  Trigger [dbo].[Tri_CaOrderDelete]    Script Date: 2018/9/25 12:40:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TRIGGER [dbo].[Tri_CaOrderDelete]
   ON [dbo].[caOrder]
   AFTER DELETE
AS
BEGIN
	SET NOCOUNT ON;
	--IF EXISTS(SELECT 'x' FROM Deleted WHERE cpMainId = 10740056 )
	--	RETURN

	IF EXISTS(SELECT 'x' FROM Deleted WHERE OpenDate IS NOT NULL OR ReceiveDate IS NOT NULL)
	BEGIN
		RAISERROR('订单已经开通或到账，不能删除',10,1)
		ROLLBACK TRANSACTION
		RETURN
	END
	ELSE
	BEGIN
		IF (SELECT COUNT(1) FROM Deleted) = 1
		BEGIN
			----把删除的图像文件保存到bsdeletefile
			INSERT INTO bsDeleteFile(FileType, FileID, [FileName] )
			SELECT 21, ID, ContractFile FROM Deleted WHERE ISNULL(ContractFile, '') > ''

			INSERT INTO bsDeleteFile(FileType, FileID, [FileName] )
			SELECT 20, ID, RemittanceFile FROM Deleted WHERE ISNULL(RemittanceFile, '') > ''

			INSERT INTO bsDeleteFile(FileType, FileID, [FileName] )
			SELECT 22, ID, FaxFile FROM Deleted WHERE ISNULL(FaxFile, '') > ''
			----把删除的图像文件保存到bsdeletefile 结束
		END
		ELSE
		BEGIN
			RAISERROR('不能批量删除订单', 10, 1)
			ROLLBACK TRANSACTION
			RETURN
		END
	END
END




GO
ALTER TABLE [dbo].[caOrder] ENABLE TRIGGER [Tri_CaOrderDelete]
GO
/****** Object:  Trigger [dbo].[Tri_caOrderInsert]    Script Date: 2018/9/25 12:40:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TRIGGER [dbo].[Tri_caOrderInsert]
   ON  [dbo].[caOrder]
   AFTER INSERT
AS 
BEGIN
	SET NOCOUNT ON;
	DECLARE @COUNT AS INT
	SELECT @COUNT = COUNT(1) FROM Inserted
	IF @COUNT = 1
	BEGIN
		DECLARE @OrderType AS TINYINT
		DECLARE @MainOrderID AS INT

		SELECT @OrderType = OrderType, @MainOrderID = MainOrderID
		FROM Inserted

		IF @OrderType IN (9, 10, 11)
		BEGIN
			IF @MainOrderID IS NULL
			BEGIN
				RAISERROR('Error：附属合同必须有主合同',10,1)
				ROLLBACK TRANSACTION
				RETURN
			END
			IF EXISTS(SELECT 'x' FROM caOrder WITH(NOLOCK) WHERE ID = @MainOrderID AND OpenDate IS NULL)
			BEGIN
				RAISERROR('Error：主合同尚未开通，不能提交附属合同',10,1)
				ROLLBACK TRANSACTION
				RETURN
			END
		END
	END
END

GO
ALTER TABLE [dbo].[caOrder] ENABLE TRIGGER [Tri_caOrderInsert]
GO
/****** Object:  Trigger [dbo].[Tri_caOrderUpdate]    Script Date: 2018/9/25 12:40:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TRIGGER [dbo].[Tri_caOrderUpdate]
   ON  [dbo].[caOrder]
   AFTER UPDATE
AS
BEGIN
	SET NOCOUNT ON;
	DECLARE @COUNT AS INT
	SELECT @COUNT = COUNT(1) FROM Inserted
	IF @COUNT = 1
	BEGIN
		DECLARE @OrderId AS INT,
			@OrderType AS TINYINT,
			@cpMainID AS INT,
			@BeginDate AS DateTime,
			@EndDate AS DateTime,
			@MainOrderID AS INT,
			@PaidCoin INT

		SELECT @OrderId = ID, @OrderType = OrderType, @cpMainID = cpMainID,
			@BeginDate = BeginDate, @EndDate = EndDate, @PaidCoin = PaidCoin
		FROM Inserted
		--IF @orderId IN(584741)
		--	return
		IF @EndDate < @BeginDate
		BEGIN
			RAISERROR('EndDate must be after the BeginDate.', 10, 1)
			ROLLBACK TRANSACTION
			RETURN
		END
		IF UPDATE(IsDeleted)
		BEGIN
			IF EXISTS(SELECT 'x' FROM Inserted WHERE (ReceiveDate IS NOT NULL OR OpenDate IS NOT NULL) AND IsDeleted = 1 AND Paid > 0)
			BEGIN
				RAISERROR('已经开通的定单不能删除', 10, 1)
				ROLLBACK TRANSACTION
				RETURN
			END
			/*IF EXISTS(SELECT 'x' FROM Inserted a, Deleted b WHERE a.IsDeleted = 1 AND b.IsDeleted = 0)
			BEGIN
				IF @PaidCoin > 0
				BEGIN
					IF (SELECT COUNT(*) FROM cpCoin WITH(NOLOCK) WHERE caOrderId = @OrderId) = 1
					BEGIN
						DECLARE @Balance INT
						SELECT @Balance = Balance FROM cpCoin WITH(NOLOCK) WHERE caOrderId = @OrderId

						INSERT INTO cpCoin(cpMainId, caOrderId, Coin, IsCancel, Balance, AddDate)
						SELECT @cpMainId, @OrderId, @PaidCoin, 1, @PaidCoin + @Balance, GETDATE()
					END
					--UPDATE cpMain SET RemainCoin = ISNULL(RemainCoin, 0) + @PaidCoin WHERE id = @cpMainId
				END
				ELSE
				BEGIN
					IF (SELECT COUNT(*) FROM cpCoin WITH(NOLOCK) WHERE caOrderId = @OrderId) = 1
					BEGIN
						DECLARE @Balance INT
						SELECT @Balance = Balance FROM cpCoin WITH(NOLOCK) WHERE caOrderId = @OrderId
						
						IF @Balance>0
						BEGIN
							INSERT INTO cpCoin(cpMainId, caOrderId, Coin, IsCancel, Balance, AddDate)
							SELECT @cpMainId, @OrderId, @PaidCoin, 1, -@Balance, GETDATE()
						END
					END
				END
			END
			*/
		END
		IF UPDATE(OpenDate) --AND EXISTS(SELECT 'x' FROM Inserted WHERE OpenDate IS NOT NULL)
		BEGIN
			IF @OrderType = 8
			BEGIN
				----检查不能时间重复
				IF EXISTS(SELECT 'x' FROM caOrder WITH(NOLOCK)
					WHERE cpMainID= @cpMainID
					AND @OrderId <> ID
					AND OrderType = 8
					AND OpenDate IS NOT NULL
					AND IsDeleted = 0
					AND (
							(
							@BeginDate <= BeginDate
							AND @EndDate >= BeginDate
							)
						OR
							(
							@BeginDate <= EndDate
							AND @EndDate >= EndDate
							)
						)
					)
				BEGIN
					RAISERROR('订单的有效期内已经开通了其他订单',10,1)
					ROLLBACK TRANSACTION
					RETURN
                END
				------80hang 
                IF NOT EXISTS(SELECT 'x' FROM bsCpModify WITH(NOLOCK)
							WHERE cpMainID = @cpMainID AND Location='a5')
				BEGIN
					DECLARE @caMainID AS INT
					SELECT @caMainID = ID FROM caMain WITH(NOLOCK) WHERE cpMainId = @cpMainID AND AccountType = 1

					INSERT INTO bsCpModify(cpMainId, caMainId, Location, ColValue, AddDate)
					SELECT @cpMainId, @caMainID, 'a5', LEFT(Brief, 200), DATEADD(MINUTE, -20, GETDATE())
					FROM cpMain WITH(NOLOCK)
					WHERE ID = @cpMainID

				END
				ELSE
					UPDATE bsCpModify SET VerifyInfo = NULL
					WHERE cpMainID = @cpMainID
					AND Location = 'a5'	
			END

--			IF @OrderType IN (1, 2)
--			BEGIN
--				UPDATE cpMain SET MaxUserNumber = 5, MaxJobNumber = JobNumber + 100
--				WHERE Id = @cpMainID
--			END
			--			--2017-7-1 前有效
			--			UPDATE caOrder
			--			SET SmsQuota = DATEDIFF(DAY, BeginDate, EndDate),
			--				RemainSmsQuota = DATEDIFF(DAY, BeginDate, EndDate)
			--			WHERE Id = @OrderID
			--			AND SmsQuota IS NULL
			--			AND OrderType = 8
			--			--2017-7-1 前有效

			--重新计算企业权限
			EXEC spRedifinePrivilage @cpMainID
		END

		IF UPDATE(EndDate)
		BEGIN
			IF @OrderType = 8
			BEGIN
				UPDATE caOrder SET EndDate= @EndDate WHERE MainOrderID = @OrderId AND ID <> @OrderID
			END
			ELSE IF @OrderType IN(9, 10, 11)
			BEGIN
				SELECT @MainOrderID = MainOrderID FROM Inserted
				IF @MainOrderID IS NULL
				BEGIN
					RAISERROR('附属订单没有主合同',10,1)
					ROLLBACK TRANSACTION
					RETURN
				END
				SELECT @EndDate = EndDate FROM caOrder WITH(NOLOCK) WHERE ID = @MainOrderID
				UPDATE caOrder SET EndDate = @EndDate WHERE ID = @OrderId
			END
		END
		----订单状态修改，0,订单添加;3,已上传汇款凭证;5,已开通;7,款已到帐;9,不索要发票，流程结束;
		----11,已索要发票;13,发票已确认;15,已开票;17,发票已邮寄;19,发票已收到，流程结束 

		IF UPDATE(RemittanceDate) OR UPDATE(OpenDate) OR UPDATE(ReceiveDate) OR UPDATE(NeedInvoice) OR UPDATE(InvoiceConfirmDate)
		BEGIN
			DECLARE @OrderStatus TINYINT,
				@NeedInvoice AS BIT, 
				@RemittanceDate AS DATETIME,
				@OpenDate AS DATETIME, 
				@ReceiveDate AS DATETIME,
				@InvoiceConfirmDate AS DATETIME,
				@OldNeedInvoice AS BIT,
				@IsBackSubmit AS BIT,
				@IsReceived AS BIT,
				@Status AS TINYINT,
				@PayMethod AS INT,
				@Paid AS DECIMAL(18,2),
				@isCvAllocate AS BIT 

			SELECT @OrderStatus = OrderStatus,
				@RemittanceDate = RemittanceDate,
				@OpenDate = OpenDate,
				@ReceiveDate = ReceiveDate,
				@NeedInvoice = NeedInvoice,
				@InvoiceConfirmDate = InvoiceConfirmDate,
				@IsBackSubmit = IsBackSubmit,
				@PayMethod = PayMethod,
				@IsReceived = 0,
				@Paid = Paid,
				@MainOrderID = MainOrderID
			FROM Inserted
		
			SELECT @OldNeedInvoice = NeedInvoice
			FROM DELETED

			IF UPDATE(RemittanceDate)
				IF @RemittanceDate IS NOT NULL	----上传汇款凭证
					UPDATE caOrder SET OrderStatus = 2 WHERE ID = @OrderID AND OrderStatus = 0
				ELSE		----汇款凭证改为 Null
					IF @OrderStatus <> 2
					BEGIN
						RAISERROR('已经开通的订单不能删除汇款凭证', 10, 1)
						ROLLBACK TRANSACTION
						RETURN
					END
					ELSE
						UPDATE caOrder SET OrderStatus = 0 WHERE ID = @OrderID

			IF UPDATE(OpenDate)
				IF @OpenDate IS NOT NULL		--订单开通
					IF @OrderStatus < 2 AND @PayMethod <> 19 AND @Paid > 0
					BEGIN
						RAISERROR('未上传汇款凭证不能开通订单', 10, 1)
						ROLLBACK TRANSACTION
						RETURN
					END
					ELSE
					BEGIN
						UPDATE caOrder SET OrderStatus = 4 WHERE ID = @OrderID
						SELECT @OrderStatus = 4
						IF @ReceiveDate IS NOT NULL
							SELECT @IsReceived = 1
						IF @OrderType = 13
							UPDATE cpMainPublish SET IsRefreshed = 1 WHERE ID = @cpMainId
						IF @OrderType = 9 --harry 简历配额项目
						BEGIN	
							DECLARE @ActiveQuota INT
							SELECT  @isCvAllocate = isCvAllocate FROM  caOrder WITH(NOLOCK) WHERE id = @MainOrderID
							IF @isCvAllocate =1
							BEGIN
								SELECT  @ActiveQuota = ActiveQuota FROM  caOrder WITH(NOLOCK) WHERE id = @OrderID
								UPDATE quotalog SET Quota=ISNULL(Quota,0)+@ActiveQuota,	RemainQuota = ISNULL(RemainQuota,0)+  @ActiveQuota WHERE QuotaType =1 AND CaOrderId = @MainOrderID AND CaMainId =(SELECT id FROM caMain WHERE cpMainid = @cpMainId AND AccountType=1 )											
							END
						END
					END
				ELSE
					IF @OrderStatus <> 4
					BEGIN
						RAISERROR('已经到账的订单不能取消开通', 10, 1)
						ROLLBACK TRANSACTION
						RETURN
					END
					ELSE
						UPDATE caOrder SET OrderStatus = 2 WHERE ID = @OrderID

			IF UPDATE(ReceiveDate) OR @IsReceived = 1
				IF @ReceiveDate IS NOT NULL
				BEGIN
					--IF EXISTS(SELECT 'x' FROM Deleted WHERE ReceiveDate IS NULL)	--款到张日期 从Null 改为有值
					IF @OrderStatus < 4
					BEGIN
						RAISERROR('未开通订单不能款到账', 10, 1)
						ROLLBACK TRANSACTION
						RETURN
					END
					ELSE IF @OrderStatus = 4
					BEGIN
						SELECT @Status = 6
						IF @NeedInvoice = 0
							SELECT @Status = 8
						ELSE IF @NeedInvoice = 1
						BEGIN
							IF @InvoiceConfirmDate IS NOT NULL
								SELECT @Status = 12
							ELSE
								SELECT @Status = 10
						END
						UPDATE caOrder SET OrderStatus = @Status WHERE ID = @OrderID
					END
					IF EXISTS(SELECT 'x' FROM Deleted WHERE ReceiveDate IS NULL)
					BEGIN
						INSERT INTO RtxNotifyLog(Receiver, RtxTitle, RtxMessage, SendType, DelayTime, ShowType) 
						SELECT ConsultantId, '款到账通知', Name + '(' + LTRIM(STR(b.Id)) + ')提交的订单[' + LTRIM(STR(a.Id)) + ']款已到账，金额' + LTRIM(STR(a.Paid)) + '元。http://sysback.51rc.com/newoa/sales/order/OrderConfirm?id=' + LTRIM(STR(a.Id)) + '&code=' + LTRIM(STR(DATEPART(HOUR, a.AddDate))) + RIGHT('0'+LTRIM(STR(DATEPART(MINUTE, a.AddDate))),2), 0, 0, 1
						FROM Inserted a, cpMain b WHERE a.cpMainId = b.Id AND a.Paid > 0 AND a.Isdeleted = 0 AND b.ConsultantId > 0
					END
				END
				ELSE
					IF @OrderStatus <> 6
					BEGIN
						RAISERROR('已经索取发票的订单不能取消到账', 10, 1)
					    ROLLBACK TRANSACTION
						RETURN
					END
					ELSE
					BEGIN
						IF @OpenDate IS NOT NULL
							UPDATE caOrder SET OrderStatus = 4 WHERE ID = @OrderID
						ELSE IF @RemittanceDate IS NOT NULL
							UPDATE caOrder SET OrderStatus = 2 WHERE ID = @OrderID
						ELSE
							UPDATE caOrder SET OrderStatus = 0 WHERE ID = @OrderID
					END

			IF UPDATE(NeedInvoice)
			BEGIN
				IF @OrderStatus IN (6, 8, 10, 12)
				BEGIN
					IF @NeedInvoice = 1
						UPDATE caOrder SET OrderStatus = 10 WHERE ID = @OrderID AND OrderStatus < 10

					IF @NeedInvoice = 0
						UPDATE caOrder SET OrderStatus = 8 WHERE ID = @OrderID

					IF @NeedInvoice IS NULL AND @OldNeedInvoice IS NOT NULL
					BEGIN
						RAISERROR('已经处理发票不能退回款到账', 10, 1)
						ROLLBACK TRANSACTION
						RETURN
					END
				END
			END

			IF UPDATE(InvoiceConfirmDate) AND @ReceiveDate IS NOT NULL AND @NeedInvoice = 1 AND @OrderStatus >= 10
				IF @InvoiceConfirmDate IS NOT NULL
				BEGIN
					IF @OrderStatus NOT IN( 10, 12)
					BEGIN
						RAISERROR('没有索取发票的订单不能确认', 10, 1)
						ROLLBACK TRANSACTION
						RETURN
					END
					ELSE
						UPDATE caOrder SET OrderStatus = 12 WHERE ID = @OrderID
				END
				ELSE
				BEGIN
					IF @OrderStatus <> 12
					BEGIN
						RAISERROR('已邮寄的发票不能取消确认', 10, 1)
						ROLLBACK TRANSACTION
						RETURN
					END
					ELSE
						UPDATE caOrder SET OrderStatus = 10 WHERE ID = @OrderID
				END
		END

		----把删除的图像文件保存到bsdeletefile
		IF UPDATE(ContractFile)
			INSERT INTO bsDeleteFile(FileType, FileID, [FileName] )
			SELECT 21, ID, ContractFile FROM Deleted WHERE ISNULL(ContractFile, '') > ''
		IF UPDATE(RemittanceFile)
			INSERT INTO bsDeleteFile(FileType, FileID, [FileName] )
			SELECT 20, ID, RemittanceFile FROM Deleted WHERE ISNULL(RemittanceFile, '') > ''
		IF UPDATE(FaxFile)
			INSERT INTO bsDeleteFile(FileType, FileID, [FileName] )
			SELECT 22, ID, FaxFile FROM Deleted WHERE ISNULL(FaxFile, '') > ''
		----把删除的图像文件保存到bsdeletefile 结束
	END
	ELSE IF @COUNT = 0
		RETURN
	ELSE
	BEGIN
		----IF NOT(UPDATE(smsquota) OR UPDATE(remainsmsquota))
		----BEGIN
		
        RAISERROR('不能批量修改订单', 10, 1)
		ROLLBACK TRANSACTION
		RETURN
		----END
	END
END
  
GO
ALTER TABLE [dbo].[caOrder] ENABLE TRIGGER [Tri_caOrderUpdate]
GO
/****** Object:  Trigger [dbo].[Tri_coldcustomer_Update]    Script Date: 2018/9/25 12:40:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--冷客户修改添加人修改认证记录里的添加人（限一个月内的）
CREATE TRIGGER  [dbo].[Tri_coldcustomer_Update]
	ON  [dbo].[ColdCustomer]
	FOR UPDATE
AS
BEGIN
	DECLARE @coldcustomerId INT,@addMan INT
	IF UPDATE(addMan)
	BEGIN
		SELECT @coldcustomerId = ID,@addMan = addMan
		FROM Inserted
		
		UPDATE logdb..coldcustomerCerLog
		SET addMan=@addMan
		WHERE cerDate >(CONVERT(DATETIME,CONVERT(VARCHAR(8),DATEADD(DAY, -25, GETDATE()),21)+'26'))
		AND coldcustomerId=@coldcustomerId
	END
END
GO
ALTER TABLE [dbo].[ColdCustomer] ENABLE TRIGGER [Tri_coldcustomer_Update]
GO
/****** Object:  Trigger [dbo].[TRI_CommentInterView_Insert]    Script Date: 2018/9/25 12:40:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TRIGGER [dbo].[TRI_CommentInterView_Insert]
   ON [dbo].[CommentInterview]
   AFTER INSERT
AS 
BEGIN
	SET NOCOUNT ON;
	IF (SELECT COUNT(*) FROM Inserted) > 1
		RETURN
	DECLARE @IdOld INT, @Id INT, @cpMainId INT, @PaMainId INT, @JobName VARCHAR(100), @Title VARCHAR(100)
	SELECT @Id = Id, @cpMainId = cpMainId, @paMainId = paMainId,
		@JobName = JobName, @Title = Title
	FROM Inserted

	SELECT @IdOld = Id 
	FROM CommentInterView WITH(NOLOCK)
	WHERE Id <> @Id
	AND cpMainId = @cpMainId
	AND ISNULL(paMainId, 0) = ISNULL(@paMainId, 0)
	AND JobName = @JobName
	AND Title = @Title

	IF @IdOld > 0
		DELETE FROM CommentInterView
		WHERE Id < @Id
		AND cpMainId = @cpMainId
		AND ISNULL(paMainId, 0) = ISNULL(@paMainId, 0)
		AND JobName = @JobName
		AND Title = @Title
END

GO
ALTER TABLE [dbo].[CommentInterview] ENABLE TRIGGER [TRI_CommentInterView_Insert]
GO
/****** Object:  Trigger [dbo].[Tri_cpCertification_Update]    Script Date: 2018/9/25 12:40:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--认证记录标记成功后续操作
--修改harry 2018-8-1
CREATE TRIGGER [dbo].[Tri_cpCertification_Update]
	ON [dbo].[cpCertification]
	FOR UPDATE
AS
BEGIN
	SET NOCOUNT ON
	IF(SELECT COUNT(*) FROM Inserted) > 1
	BEGIN
		RAISERROR('不能批量修改cpCertification信息', 10, 1)
		ROLLBACK TRANSACTION
		RETURN
	END

	DECLARE @CerStatus TINYINT,@CpMainID INT,
		@Mobile VARCHAR(12),@MemberType TINYINT,
		@CompanyName NVARCHAR(50),@CerType TINYINT,
		@CpCertificationID INT, @coldCustomerId INT, @addMan INT, @consultantDate DATETIME
	IF UPDATE(CerStatus)
	BEGIN
		SELECT @CpCertificationID = ID,@CpMainID = CpMainID,@CompanyName = CompanyName,
			@Mobile = Mobile,@MemberType = MemberType,
			@CerType = CerType,@CerStatus = CerStatus
		FROM INSERTED

		IF @CerStatus = 1
		BEGIN
			
			IF @MemberType = 1  --实名认证
			BEGIN
				IF @CerType = 1 --对公打款
					AND NOT EXISTS(  --没有对公打款信息
						SELECT 'x' 
						FROM cpCorporationAccount WITH(NOLOCK)
						WHERE cpCertificationID = @CpCertificationID
					)
				BEGIN
					RAISERROR('没有对公打款信息', 10, 1)
					ROLLBACK
					RETURN
				END
				ELSE IF @CerType = 2  --个人认证
					AND NOT EXISTS(  --没有个人账户认证信息
						SELECT 'x' 
						FROM cpPersonalAccount WITH(NOLOCK) 
						WHERE cpCertificationID = @CpCertificationID
						AND CheckResult = 1
					) 
				BEGIN
					RAISERROR('没有个人账户认证信息', 10, 1)
					ROLLBACK
					RETURN
				END

				IF NOT EXISTS(SELECT 'x' FROM cpLicence WITH(NOLOCK) WHERE cpMainID = @CpMainID AND HasPassed = 1)
				BEGIN
					INSERT INTO cpLicence(cpMainID,ImgFile,FileSource,Ip,AddDate,HasPassed,CheckDate,cpCertificationID)
					VALUES(@CpMainID,'',0,'1.1.1.1',GETDATE(),1,GETDATE(),@CpCertificationID)
				END

				IF EXISTS(SELECT 'x' FROM cpMain WITH(NOLOCK) WHERE HasLicence = 1 AND ID = @CpMainID)
					UPDATE CpMain 
					SET RealName = 1, Name = @CompanyName
					WHERE ID = @CpMainID
				ELSE
					UPDATE CpMain 
					SET RealName = 1,Name = @CompanyName, HasLicence = 1
					WHERE ID = @CpMainID

				UPDATE CpMain
				SET MemberType = 2
				WHERE ID = @CpMainID
				AND MemberType <> 3

				UPDATE cpCertification
				SET CerDate = GETDATE()
				WHERE ID = @CpCertificationID
				
				INSERT SmsMessageLog(SendMan, ManagerUSerId, paMainId, caMainId, Mobile, MsgType, IsCat, Msg)
				SELECT  0, NULL, NULL, a.ID, @Mobile, 27, 0,
					'您的企业认证已通过，请登录' + c.subsitename + '(' + c.EmailSite + ')正常使用，感谢您对我们的支持！客服电话：400-626-5151'
				FROM caMain a WITH(NOLOCK), cpMain b WITH(NOLOCK), dcSubSite c WITH(NOLOCK)
				WHERE a.cpMainID = b.ID
				AND b.dcSubSiteID = c.ID 
				AND b.ID = @CpMainID 

				INSERT INTO rtxnotifylog
				SELECT ISNULL(ConsultantID,0),'审核通过提醒',Name+'('+LTRIM(STR(@CpMainID))+')的企业实名认证已经通过审核！http://sysback.51rc.com/newoa/company/cp/cpMainInfo?id=' + LTRIM(STR(ID)) + '&code=' + LTRIM(STR(DATEPART(HOUR, RegDate) * 100 + DATEPART(MINUTE, RegDate))),1,0,0,null,getdate()
				FROM cpMain WITH(NOLOCK)
				WHERE ID = @CpMainID
			END
			ELSE	--普通认证
			BEGIN
				IF @CerType = 2  --个人认证
				BEGIN
					IF NOT EXISTS(
						SELECT 'x' 
						FROM cpLicence WITH(NOLOCK)
						WHERE HasPassed = 1 
						AND cpMainId = @CpMainID AND cpCertificationID = @CpCertificationID) 
					OR NOT EXISTS(
						SELECT 'x'
						FROM cpPersonalAccount WITH(NOLOCK) 
						WHERE cpCertificationID = @CpCertificationID
						AND CheckResult = 1
					)
					BEGIN
						RAISERROR('个人认证Error', 10, 1)
						ROLLBACK
						RETURN
					END
				END
				ELSE IF @CerType = 3	--企业邮箱认证
					AND NOT EXISTS(
						SELECT 'x'
						FROM cpCompanyEmail WITH(NOLOCK)
						WHERE cpCertificationID = @CpCertificationID
						AND CheckResult = 1
					)
				BEGIN
					RAISERROR('企业邮箱认证Error', 10, 1)
					ROLLBACK
					RETURN
				END

				IF NOT EXISTS(SELECT 'x' FROM cpLicence WITH(NOLOCK) WHERE cpMainID = @CpMainID AND HasPassed = 1)
				BEGIN
					INSERT INTO cpLicence(cpMainID,ImgFile,FileSource,Ip,AddDate,HasPassed,CheckDate,cpCertificationID)
					VALUES(@CpMainID,'',0,'1.1.1.1',GETDATE(),1,GETDATE(),@CpCertificationID)
				END

				IF EXISTS(SELECT 'x' FROM cpMain WITH(NOLOCK) WHERE HasLicence = 1 AND ID = @CpMainID)
					UPDATE CpMain
					SET Name = @CompanyName
					WHERE ID = @CpMainID 
				ELSE
					UPDATE CpMain
					SET Name = @CompanyName,HasLicence = 1
					WHERE ID = @CpMainID 
				
				UPDATE cpCertification
				SET CerDate = GETDATE()
				WHERE ID = @CpCertificationID

				INSERT SmsMessageLog(SendMan, ManagerUSerId, paMainId, caMainId, Mobile, MsgType, IsCat, Msg)
				SELECT  0, NULL, NULL, a.ID, @Mobile, 27, 0,
					'您的企业认证已通过，请登录' + c.subsitename + '(' + c.EmailSite + ')正常使用，感谢您对我们的支持！客服电话：400-626-5151'
				FROM caMain a WITH(NOLOCK), cpMain b WITH(NOLOCK), dcSubSite c WITH(NOLOCK)
				WHERE a.cpMainID = b.ID
				AND b.dcSubSiteID = c.ID 
				AND b.ID = @CpMainID

				INSERT INTO rtxnotifylog
				SELECT ISNULL(ConsultantID,0),'审核通过提醒',Name+'('+LTRIM(STR(@CpMainID))+')的企业普通认证已经通过审核！http://sysback.51rc.com/newoa/company/cp/cpMainInfo?id=' + LTRIM(STR(ID)) + '&code=' + LTRIM(STR(DATEPART(HOUR, RegDate) * 100 + DATEPART(MINUTE, RegDate))),1,0,0,null,getdate()
				FROM cpMain WITH(NOLOCK)
				WHERE ID = @CpMainID
			END
--插入到logdb..coldcustomerCerLog
			--查询是否存在log表中,一个月内认证过
			IF NOT EXISTS(SELECT 'x' FROM logdb..coldcustomerCerLog WHERE  cpMainId = @CpMainID AND cerDate>(CONVERT(DATETIME,CONVERT(VARCHAR(8),DATEADD(DAY, -25, GETDATE()),21)+'26')) )
			BEGIN
				--是否在冷客户里
				IF EXISTS(SELECT 'x' FROM coldcustomer 
				WHERE (CompanyName =@CompanyName  OR CpMainID=@CpMainID) AND ISNULL(addMan,0)!=0 )
				BEGIN
					SELECT TOP 1 
					@coldCustomerId = id, @addMan = addMan 
					FROM  coldcustomer 
					WHERE  (CompanyName =@CompanyName  OR CpMainID=@CpMainID)
					ORDER By adddate
					
					INSERT INTO logdb..coldcustomerCerLog (cpCertificationId,cpMainId,coldcustomerId,addMan,cerDate)
					SELECT @CpCertificationID, @CpMainID, @coldCustomerId, @addMan,GETDATE()
				END
                                ELSE
				BEGIN
					SELECT @consultantDate= consultantDate FROM cpMain where id= @CpMainID --当前企业的顾问分配时间

					IF EXISTS(SELECT 'X' FROM maindb..cpMain WHERE  name= @CompanyName AND ConsultantID IN(select id from manageruser where deptid=15) AND consultantDate<@consultantDate)
					BEGIN
						INSERT INTO logdb..coldcustomerCerLog (cpCertificationId,cpMainId,coldcustomerId,addMan,cerDate)
						SELECT @CpCertificationID, @CpMainID, 0, (select top 1 ConsultantID FROM maindb..cpMain WHERE  name= @CompanyName AND ConsultantID IN(select id from manageruser where deptid=15) AND consultantDate<@consultantDate ORDER BY consultantDate DESC),GETDATE()
					END 
				END
			END
			IF (SELECT COUNT(1) FROM cpCertification WITH(NOLOCK) WHERE MemberType = @MemberType AND CpMainID = @CpMainID AND CerStatus = 1) = 1
			BEGIN
				IF @MemberType = 1
					INSERT INTO cpPoint (cpMainID, ChangeID, Point, LastModifyDate) VALUES (@CpMainID, 2, 100, GETDATE())
				ELSE
					INSERT INTO cpPoint (cpMainID, ChangeID, Point, LastModifyDate) VALUES (@CpMainID, 2, 80, GETDATE())
			END
			IF @MemberType = 1 AND @CerType = 1
			BEGIN
				INSERT INTO LogDB..UserActionDetail(ActionType, ActionID, dcProvinceID)
				SELECT TOP 1 202, @CpMainID, dcProvinceID FROM cpMain WITH(NOLOCK) WHERE ID = @CpMainID
			END
			ELSE IF @MemberType = 1 AND @CerType = 2
			BEGIN
				INSERT INTO LogDB..UserActionDetail(ActionType, ActionID, dcProvinceID)
				SELECT TOP 1 203, @CpMainID, dcProvinceID FROM cpMain WITH(NOLOCK) WHERE ID = @CpMainID
			END
			ELSE IF @MemberType = 2 AND @CerType = 2
			BEGIN
				INSERT INTO LogDB..UserActionDetail(ActionType, ActionID, dcProvinceID)
				SELECT TOP 1 200, @CpMainID, dcProvinceID FROM cpMain WITH(NOLOCK) WHERE ID = @CpMainID
			END
			ELSE IF @MemberType = 2 AND @CerType = 3
			BEGIN
				INSERT INTO LogDB..UserActionDetail(ActionType, ActionID, dcProvinceID)
				SELECT TOP 1 201, @CpMainID, dcProvinceID FROM cpMain WITH(NOLOCK) WHERE ID = @CpMainID
			END
		END
		ELSE
		BEGIN
			INSERT SmsMessageLog(SendMan, ManagerUSerId, paMainId, caMainId, Mobile, MsgType, IsCat, Msg)
			SELECT  0, NULL, NULL, a.ID, @Mobile, 27, 0,
				'您的企业认证没有通过审核，请登录' + c.subsitename + '(' + c.EmailSite + ')正常使用，感谢您对我们的支持！客服电话：400-626-5151'
			FROM caMain a WITH(NOLOCK), cpMain b WITH(NOLOCK), dcSubSite c WITH(NOLOCK)
			WHERE a.cpMainID = b.ID
			AND b.dcSubSiteID = c.ID 
			AND b.ID = @CpMainID 
		END
	END
END











GO
ALTER TABLE [dbo].[cpCertification] ENABLE TRIGGER [Tri_cpCertification_Update]
GO
/****** Object:  Trigger [dbo].[Tri_cpCoinInsert]    Script Date: 2018/9/25 12:40:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Peter
-- Create date: 2014-08-20 09:55
-- Description:	CpCoin表添加数据触发修改CpMain RemainCoin字段
-- =============================================
CREATE TRIGGER [dbo].[Tri_cpCoinInsert] 
   ON  [dbo].[cpCoin] 
   AFTER INSERT
AS 
BEGIN
	DECLARE @CoinInserted AS INT
	DECLARE @cpMainID AS INT
	DECLARE @ID AS INT
	SELECT @ID = ID,@CoinInserted = Coin,@cpMainID = cpMainID FROM Inserted

	UPDATE cpMain SET RemainCoin = ISNULL(RemainCoin,0) + @CoinInserted WHERE ID = @cpMainID
	UPDATE cpCoin SET Balance = (SELECT TOP 1 RemainCoin FROM cpMain WHERE ID = @cpMainID)  WHERE ID = @ID
	--只保存前200条数据
	DECLARE @cpCoinLogCount AS INT
	SELECT @cpCoinLogCount = COUNT(1) FROM cpCoin WHERE cpMainID = @cpMainID
	IF @cpCoinLogCount > 200
	BEGIN
		DELETE FROM cpCoin WHERE ID = (SELECT TOP 1 ID FROM cpCoin WHERE cpMainID = @cpMainID ORDER BY ID)
	END
END

GO
ALTER TABLE [dbo].[cpCoin] ENABLE TRIGGER [Tri_cpCoinInsert]
GO
/****** Object:  Trigger [dbo].[Tri_CpImageDelete]    Script Date: 2018/9/25 12:40:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE TRIGGER [dbo].[Tri_CpImageDelete]
	ON [dbo].[cpImage]
	AFTER DELETE
AS
BEGIN
	SET NOCOUNT ON;
	DECLARE @FileNameOld AS VARCHAR(50),
		@FileName AS VARCHAR(50)

	INSERT INTO bsDeleteFile(FileType, FileID, [FileName] )
	SELECT 10 + ImgType, cpMainID, ImgFile FROM Deleted
END


GO
ALTER TABLE [dbo].[cpImage] ENABLE TRIGGER [Tri_CpImageDelete]
GO
/****** Object:  Trigger [dbo].[Tri_CpLicenceDelete]    Script Date: 2018/9/25 12:40:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE TRIGGER [dbo].[Tri_CpLicenceDelete]
	ON [dbo].[cpLicence]
	AFTER DELETE
AS
BEGIN
	SET NOCOUNT ON;
	INSERT INTO bsDeleteFile(FileType, FileID, [FileName] )
	SELECT 10, cpMainID, ImgFile FROM Deleted
END


GO
ALTER TABLE [dbo].[cpLicence] ENABLE TRIGGER [Tri_CpLicenceDelete]
GO
/****** Object:  Trigger [dbo].[Tri_CpLicenceUpdate]    Script Date: 2018/9/25 12:40:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE TRIGGER [dbo].[Tri_CpLicenceUpdate]
	ON [dbo].[cpLicence]
	AFTER UPDATE
AS
BEGIN
	SET NOCOUNT ON;
	IF UPDATE(ImgFile)
		INSERT INTO bsDeleteFile(FileType, FileID, [FileName] )
		SELECT 10, cpMainID, ImgFile FROM Deleted
END



GO
ALTER TABLE [dbo].[cpLicence] ENABLE TRIGGER [Tri_CpLicenceUpdate]
GO
/****** Object:  Trigger [dbo].[Tri_cpMainDelete]    Script Date: 2018/9/25 12:40:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TRIGGER [dbo].[Tri_cpMainDelete]
   ON [dbo].[cpMain]
   AFTER DELETE
AS 
BEGIN
	DELETE FROM cpMainPublish WHERE ID IN(SELECT ID FROM Deleted)

	RETURN
	SET NOCOUNT ON;
	IF EXISTS(SELECT 'x' FROM Deleted WHERE IsDelete = 0)
	BEGIN
		RAISERROR('不能直接删除企业', 10, 1)
		ROLLBACK TRANSACTION
		RETURN
	END
	
END


GO
ALTER TABLE [dbo].[cpMain] ENABLE TRIGGER [Tri_cpMainDelete]
GO
/****** Object:  Trigger [dbo].[Tri_cpMainInsert]    Script Date: 2018/9/25 12:40:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TRIGGER [dbo].[Tri_cpMainInsert]
	ON [dbo].[cpMain]
	AFTER INSERT
AS 
BEGIN
	SET NOCOUNT ON;
	DECLARE @cpMainID AS INT, @Count AS INT, @ProvinceID AS INT, @Name AS VARCHAR(100), @SecondId VARCHAR(10)
	--, @IP AS VARCHAR(31), @caMainID AS INT
	SELECT @Count = COUNT(1) FROM Inserted

	IF @Count = 1
	BEGIN
		SELECT @cpMainID = ID, @Name = [Name] FROM Inserted
		----强制企业名称使用全角()
		IF @Name LIKE '%(%' OR @Name LIKE '%)%'
			UPDATE cpMain SET Name = REPLACE(REPLACE([Name], '(', '（'), ')', '）')
			WHERE ID = @cpMainID
		
		SET @SecondId = LEFT(REPLACE(NEWID(), '-', ''), 10)
		WHILE EXISTS(SELECT 'x' FROM cpMain WITH(NOLOCK) WHERE SecondId = @SecondId)
			SET @SecondId = LEFT(REPLACE(NEWID(), '-', ''), 10)

		UPDATE cpMain SET SecondId = @SecondId WHERE Id = @cpMainID

		IF CHARINDEX('保险', @Name) > 0 AND GETDATE() > '2017-8-26'
			UPDATE cpMain SET RealName = 6 WHERE Id = @cpMainID
	END
END

GO
ALTER TABLE [dbo].[cpMain] ENABLE TRIGGER [Tri_cpMainInsert]
GO
/****** Object:  Trigger [dbo].[Tri_cpMainUpdate]    Script Date: 2018/9/25 12:40:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--修改harry2018-6-8 重分顾问extendlink顾问同步修改
CREATE TRIGGER [dbo].[Tri_cpMainUpdate]
	ON  [dbo].[cpMain]
	AFTER UPDATE
AS
BEGIN
    --return 
	SET NOCOUNT ON;
	DECLARE @cpMainID AS INT, 
		@caMainID AS INT, 
		@Count AS INT, 
		@Balance AS INT, 
		@ProvinceID AS INT,
		@IsDelete AS BIT,
		@ConsultantIDOld AS INT,
		@ConsultantIDNew AS INT,
		@HasAssign AS BIT,
		@Valid INT

	IF UPDATE(dcProvinceID)
		UPDATE cpMain SET dcSubsiteID = dcProvinceID
		WHERE ID IN(SELECT ID FROM Inserted)

	SELECT @Count = COUNT(1), @HasAssign = 0 FROM Inserted
	IF @Count = 1
	BEGIN
		IF UPDATE(Lng) OR UPDATE(Lat)
		BEGIN
			DECLARE @LngOld Float, @LatOld FLOAT, @Lng FLOAT, @Lat FLOAT
			SELECT @LngOld = Lng, @LatOld = lat FROM Deleted
			SELECT @cpMainID = ID, @Lng = Lng, @Lat = lat FROM Inserted
			IF @LngOld IS NULL
				UPDATE Job SET Lng = @Lng, Lat = @Lat
				WHERE cpMainId = @cpMainId AND Lng IS NULL
			ELSE
				UPDATE Job SET Lng = @Lng, Lat = @Lat
				WHERE cpMainId = @cpMainId AND ISNULL(Lng, @LngOld) = @LngOld
		END

		IF UPDATE(Name)
		BEGIN
			DECLARE @dcProvinceId AS INT, @Name AS VARCHAR(100), @NameOld AS VARCHAR(100), @HasLicence INT
			SELECT @NameOld = ISNULL(Name, ''), @HasLicence = ISNULL(HasLicence, 0) FROM Deleted
			SELECT @Name = ISNULL(Name, ''), @dcProvinceId = dcProvinceId, @cpMainID = ID FROM Inserted
			IF @Name = ''
			BEGIN
				RAISERROR('企业名称不能为空', 10, 1)
				ROLLBACK TRANSACTION
				RETURN
			END
			IF @Name <> @NameOld --AND @HasLicence = 0
			BEGIN
				UPDATE cpMain SET ConsultantDate = GETDATE() WHERE Id = @cpMainId AND ConsultantId > 0
				EXEC ccCpMainByConsultantAssignUpdate @cpMainID, @dcProvinceId
				SET @HasAssign = 1
			END
		END
		
		IF UPDATE(RealName)
		BEGIN
			DECLARE @MemberType TINYINT, @RealName TINYINT, @MaxJobNumber INT
			SELECT @MemberType = MemberType, @RealName = RealName, @MaxJobNumber = MaxJobNumber, @cpMainID = Id FROM Inserted
			IF @RealName = 1 AND @Membertype = 2 AND @MaxJobNumber <> 10
				UPDATE cpMain SET MaxJobNumber = 10 WHERE Id = @cpMainId
			--IF @RealName = 0 AND @Membertype = 2 AND @MaxJobNumber <> 5
			--	UPDATE cpMain SET MaxJobNumber = 5 WHERE Id = @cpMainId
		END

		IF UPDATE(Balance)
		BEGIN
			SELECT @Balance = Balance, @cpMainID = ID FROM Inserted
			IF @Balance < 1
			BEGIN
				IF @Balance < 0
					UPDATE cpMain SET Balance = 0 WHERE ID = @cpMainID

				SELECT @caMainID = id FROM caMain WITH(NOLOCK) WHERE cpMainID = @cpMainID				
				IF NOT EXISTS(SELECT 'x' FROM bsCpModify WITH(NOLOCK)
						WHERE cpMainID = @cpMainID AND Location='a5')
				
					INSERT INTO bsCpModify(cpMainId, caMainID, Location, ColValue, AddDate)
					SELECT Id, @caMainID, 'a5', LEFT(Brief, 200), DATEADD(MINUTE, -20, GETDATE())
					FROM Inserted
				ELSE
					UPDATE bsCpModify SET VerifyInfo = NULL
					WHERE cpMainID = @cpMainID
					AND Location = 'a5'
				--重新计算权限

				UPDATE cpMain SET BalanceDate = CONVERT(VARCHAR(10), GETDATE(), 120) + ' 23:50:00'
				WHERE ID = @cpMainID AND BalanceDate > GETDATE()

				EXEC spRedifinePrivilage @cpMainID
			END
		END
		IF UPDATE(IsDelete)
		BEGIN
			SELECT @cpMainID = ID, @IsDelete = IsDelete, @ProvinceId = dcProvinceID, @ConsultantIDNew = ConsultantID FROM Inserted
			IF @IsDelete = 1
			BEGIN
				----8点到18点删除企业记录到datereport。其他时间段认为是计划任务，系统自己删除的
				IF DATEPART(HOUR, GETDATE()) BETWEEN 8 AND 18
					UPDATE DateReport SET DeleteCompanyNum = DeleteCompanyNum + 1
					WHERE Province_Id = @ProvinceID AND CountDate = CONVERT(VARCHAR(8), GETDATE(), 112)
	
				UPDATE Job SET IsDelete = 1 WHERE cpMainID = @cpMainID AND IsDelete = 0
				UPDATE caMain SET IsDelete = 1 WHERE cpMainID = @cpMainID AND IsDelete = 0
				UPDATE cpMain SET MemberType = 0, ResumeQuota = 0, MaxUserNumber = 1, MaxJobNumber = 0 WHERE ID = @cpMainID 

				UPDATE ManagerUser SET ConsultantNum = ISNULL(ConsultantNum, 1) - 1 WHERE Id = @ConsultantIDNew
			END
			IF @IsDelete = 0
			BEGIN
				UPDATE caMain SET IsDelete = 0 WHERE cpMainID = @cpMainID AND AccountType = 1
				UPDATE Job SET IsDelete = 0
				WHERE cpMainID = @cpMainID
				AND IssueDate < GETDATE()
				AND IssueEnd > GETDATE()
				AND caMainID IN(SELECT ID FROM caMain WITH(NOLOCK) WHERE cpMainID = @cpMainID AND AccountType = 1)

				UPDATE ManagerUser SET ConsultantNum = ConsultantNum + 1 WHERE Id = @ConsultantIDNew
				--重新计算权限
				EXEC spRedifinePrivilage @cpMainID
			END
		END
		IF UPDATE(Address) OR UPDATE(RealName)
		BEGIN
			SELECT @cpMainID = ID FROM Inserted
			----Address更新则企业信息已经填写，重新计算权限
			EXEC spRedifinePrivilage @cpMainID
		END

		IF UPDATE(HasLicence) Or UPDATE(IsLimitLogin)	-- OR UPDATE(MaxJobNumber)
		BEGIN
			DECLARE @RegisterMode AS TINYINT,
			@AddMan AS SMALLINT,
			@CountDate AS VARCHAR(8),
			@HasLicenceOld AS INT,
			@RegDate SMALLDATETIME

			IF UPDATE(HasLicence)
			BEGIN
				SELECT @RegisterMode = RegisterMode,
					@AddMan = AddMan,
					@dcProvinceID = dcProvinceID,
					@HasLicence = HasLicence,
					@cpMainID = ID,
					@RegDate = RegDate
				FROM Inserted
				
				SELECT @HasLicenceOld = HasLicence FROM Deleted
				IF @RegisterMode = 1 AND @HasLicence = 1 AND ISNULL(@HasLicenceOld, 0) = 0
				BEGIN
					UPDATE cpMain SET RegisterMode = 11 WHERE ID = @cpMainID
					INSERT INTO infoCpVerifyLog(cpMainId, AddMan, AddDate, CheckDate, dcProvinceId)
					SELECT @cpMainId, @AddMan, @RegDate, GETDATE(), @dcProvinceID

					SELECT @CountDate = CONVERT(VARCHAR(8), GETDATE(), 112)

					UPDATE DateReport SET CompanyPassed = CompanyPassed + 1
					WHERE Province_Id = @dcProvinceId
					AND CountDate = @CountDate

					IF NOT EXISTS(SELECT 'x' FROM Info_DateReport WITH(NOLOCK)
									WHERE InfoManager_Id = @AddMan
									AND Province_Id = @dcProvinceId
									AND CountDate = @CountDate)
						INSERT INTO Info_DateReport(Province_Id, InfoManager_Id, countdate)
						VALUES(@dcProvinceId, @AddMan, @CountDate)

					UPDATE Info_DateReport SET RealCompany = RealCompany + 1
					WHERE InfoManager_Id = @AddMan
					AND Province_Id = @dcProvinceId
					AND CountDate = @CountDate
				END

				IF @HasLicence = 1 AND @HasAssign = 0
				BEGIN
					EXEC ccCpMainByConsultantAssignUpdate @cpMainID, @dcProvinceId
				END
	
				INSERT wxMessageSend2(Templatetype, WxFansID, CpMainID, AddDate)
				SELECT 19, b.ID, @cpMainID, GETDATE()
				FROM paLoginContact a WITH(NOLOCK), wxFans b WITH(NOLOCK)
				WHERE a.OpenID = b.OpenID 
				AND a.ContactType = 101 
				AND a.paMainID IN(SELECT Id FROM caMain WITH(NOLOCK) WHERE cpMainID = @cpMainID)
			END
			SELECT @cpMainID = ID FROM Inserted
			--重新计算权限
			EXEC spRedifinePrivilage @cpMainID
		END

--		IF UPDATE(ConsultantID)
--		BEGIN
--			SELECT @ConsultantIDNew = ISNULL(ConsultantID, 0) FROM Inserted
--			SELECT @ConsultantIDOld = ISNULL(ConsultantID, 0) FROM Deleted
--			IF @ConsultantIDNew <> @ConsultantIDOld
--			BEGIN
--				UPDATE ManagerUser SET ConsultantNum = ConsultantNum + 1 WHERE Id = @ConsultantIDNew
--				UPDATE ManagerUser SET ConsultantNum = ConsultantNum - 1 WHERE Id = @ConsultantIDOld
--
----				INSERT INTO bsManagerUserAction 
----				SELECT Id, '记录招聘顾问改变:从' + LTRIM(STR(@ConsultantIDOld)) + ' 至 ' + LTRIM(STR(@ConsultantIDNew)), '', 112, GETDATE()
----				FROM Inserted
--			END
--		END

		SELECT @cpMainId = ID, 
			@Valid = CASE WHEN ISNULL(Address, '')='' OR IsDelete = 1 OR IsLimitLogin = 9 OR VerifyResult = 10 OR VerifyCount = 0
					 THEN 0 ELSE 1 
					 END 
		FROM Inserted

		IF @Valid = 1 OR UPDATE(MemBerType) OR UPDATE(HasLicence)
		BEGIN
			IF NOT EXISTS(SELECT 'x' FROM cpMainPublish WITH(NOLOCK) WHERE ID  = @cpMainId)
				INSERT INTO cpMainPublish(ID, Name, ShortName, dcCompanyKindID, dcCompanySizeID, dcRegionID, Brief, HasLicence, LogoFile,
					UnlimitedDate, BalanceDate, Balance, MemberType, RefreshDate,LastModifyDate, LastLoginDate, Valid, Lng, Lat, SecondId, dcProvinceId, RealName, ReplyRate)
				SELECT ID, Name, ShortName, dcCompanyKindID, dcCompanySizeID, dcRegionID, Brief, HasLicence, LogoFile,
					UnlimitedDate, BalanceDate, Balance, MemberType, RefreshDate,LastModifyDate, LastLoginDate, Valid, Lng, Lat, SecondId, dcProvinceId, RealName, ReplyRate
				FROM Inserted
			ELSE
			BEGIN
				IF UPDATE(ReplyRate)
					UPDATE a SET a.ReplyRate = b.ReplyRate FROM cpMainPublish a, Inserted b WHERE a.ID = b.ID

				IF UPDATE(RealName)
					UPDATE a SET a.RealName = b.RealName FROM cpMainPublish a, Inserted b WHERE a.ID = b.ID

				IF UPDATE(LastLoginDate)
					UPDATE a SET a.RefreshDate = b.RefreshDate, a.LastLoginDate = b.LastLoginDate FROM cpMainPublish a, Inserted b WHERE a.ID = b.ID

				ELSE IF UPDATE(RefreshDate)
					UPDATE a SET a.RefreshDate = b.RefreshDate FROM cpMainPublish a, Inserted b WHERE a.ID = b.ID

				IF UPDATE(Name) OR UPDATE(ShortName) OR UPDATE(Brief) OR UPDATE(LastModifyDate)
					UPDATE a
					SET a.Name = b.Name, 
						a.ShortName = b.ShortName, 
						a.dcCompanyKindID = b.dcCompanyKindID, 
						a.dcCompanySizeID = b.dcCompanySizeID, 
						a.dcRegionID = b.dcRegionID, 
						a.Brief = b.Brief, 
						a.HasLicence = b.HasLicence, 
						a.UnlimitedDate = b.UnlimitedDate, 
						a.BalanceDate = b.BalanceDate, 
						a.Balance = b.Balance, 
						a.MemberType = b.MemberType, 
						a.RefreshDate = b.RefreshDate, 
						a.LastModifyDate = b.LastModifyDate, 
						a.LastLoginDate = b.LastLoginDate, 
						a.Valid = b.Valid,
						a.Lng = b.Lng,
						a.Lat = b.Lat,
						a.SecondId = b.SecondId,
						a.dcProvinceId = b.dcProvinceId,
						a.LogoFile = b.LogoFile
					FROM cpMainPublish a, Inserted b
					WHERE a.Id = b.ID
				ELSE IF UPDATE(HasLicence) OR UPDATE(UnlimitedDate) OR UPDATE(BalanceDate) OR UPDATE(Balance) OR UPDATE(MemberType) OR UPDATE(Address) OR UPDATE(IsLimitLogin) OR UPDATE(VerifyResult) OR UPDATE(HasLicence)
					UPDATE a
					SET a.HasLicence = b.HasLicence, 
						a.UnlimitedDate = b.UnlimitedDate, 
						a.BalanceDate = b.BalanceDate, 
						a.Balance = b.Balance, 
						a.MemberType = b.MemberType, 
						a.RefreshDate = b.RefreshDate, 
						a.LastModifyDate = b.LastModifyDate, 
						a.LastLoginDate = b.LastLoginDate, 
						a.Valid = b.Valid
					FROM cpMainPublish a, Inserted b
					WHERE a.Id = b.ID
			END
		END
		ELSE
		BEGIN
			DELETE cpMainPublish WHERE ID IN(SELECT ID FROM Inserted)
		END
	END
	ELSE
	BEGIN
		DECLARE @Ok AS BIT
		SELECT @OK = 0

		IF UPDATE(RefreshDate) OR UPDATE(MemberType) OR UPDATE(LastLoginDate) OR UPDATE(HasLicence)
		BEGIN
			SELECT @OK = 1

			UPDATE a
			SET a.RefreshDate = b.RefreshDate, a.MemberType = b.MemberType, a.LastLoginDate = b.LastLoginDate
			FROM cpMainPublish a, Inserted b
			WHERE a.id =b.id
		END
		ELSE IF UPDATE(DailyGiftQuota)
			SELECT @OK = 1
		ELSE IF UPDATE(UnlimitedDate)
			SELECT @OK = 1
		ELSE IF UPDATE(BalanceDate)
			SELECT @OK = 1
		ELSE IF UPDATE(Balance)
			SELECT @OK = 1
		ELSE IF UPDATE(MaxUserNumber)
			SELECT @OK = 1
		ELSE IF UPDATE(MaxJobNumber)
			SELECT @OK = 1
		ELSE IF UPDATE(IsAgent)
			SELECT @OK = 1
		ELSE IF UPDATE(IsLimitLogin)
			SELECT @OK = 1
		ELSE IF UPDATE(Islock)
			SELECT @OK = 1
		ELSE IF UPDATE(VerifyResult)
			SELECT @OK = 1
		ELSE IF UPDATE(JobNumber)
			SELECT @OK = 1
		ELSE IF UPDATE(dcSubSiteID)
			SELECT @OK = 1
		ELSE IF UPDATE(ResumeQuota)
			SELECT @OK = 1
		ELSE IF UPDATE(ConsultantID)
			SELECT @OK = 1
		ELSE IF UPDATE(ConsultantDate)
			SELECT @OK = 1
		ELSE IF UPDATE(LastLoginIP)
			SELECT @OK = 1
		ELSE IF UPDATE(PerfectDate)
			SELECT @OK = 1
		ELSE IF UPDATE(RemainPoint)
			SELECT @OK = 1
		ELSE IF UPDATE(MemberDate)
			SELECT @OK = 1
		ELSE IF UPDATE(ReplyRate)
			SELECT @OK = 1
		IF UPDATE(IsDelete)
			SELECT @OK = 0
		IF UPDATE(dcCompanyKindId)
			SELECT @OK = 1
		IF UPDATE(RealName)
			SELECT @OK = 1
		IF UPDATE(InterViewNumber)
			SELECT @Ok = 1
		IF UPDATE(CommentNumber)
			SELECT @Ok = 1
		IF UPDATE(LogoFile)
			SELECT @Ok = 1
		--IF UPDATE(brief)
		--	SELECT @OK = 1

		IF @Ok = 0
		BEGIN
			RAISERROR('不能批量修改企业信息', 10, 1)
			ROLLBACK TRANSACTION
			RETURN
		END
	END
	
	IF UPDATE(ConsultantID)
	BEGIN
		INSERT INTO bsManagerUserAction 
		SELECT Id, '招聘顾问变为=' + LTRIM(STR(ISNULL(ConsultantID, 0))), '', 112, GETDATE()
		FROM Inserted
		 
                UPDATE extendlink 
		SET manageruserId=(SELECT ConsultantID FROM Inserted)
		WHERE cpMainId=(SELECT ID FROM Inserted)
		---AND RunStatus!=4
	END
END



GO
ALTER TABLE [dbo].[cpMain] ENABLE TRIGGER [Tri_cpMainUpdate]
GO
/****** Object:  Trigger [dbo].[Tri_cpMainPublish_Insert]    Script Date: 2018/9/25 12:40:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TRIGGER [dbo].[Tri_cpMainPublish_Insert]
   ON [dbo].[cpMainPublish]
   AFTER INSERT
AS 
BEGIN
	SET NOCOUNT ON;
	SET XACT_ABORT OFF

	INSERT INTO JobPublish(ID, cpMainID, caMainId, Name, dcJobTypeID, dcJobTypeIDMinor, NeedNumber, dcSalaryID, dcSalaryIDMax, 
		EmployType, dcRegionID, Responsibility, Demand, dcEducationID, MinExperience, MinAge, MaxAge, IssueDate,
		IssueEnd, IsDelete, AddDate, RefreshDate, LastModifyDate, Valid, Lng, Lat, SecondId, Welfare1, Welfare2,
		Welfare3, Welfare4, Welfare5, Welfare6, Welfare7, Welfare8, Welfare9, Welfare10, Welfare11, Welfare12,
		Welfare13, Welfare14, Welfare15, Welfare16, Welfare17, Welfare18, Welfare19)
	SELECT ID, cpMainID, caMainId, Name, dcJobTypeID, dcJobTypeIDMinor, NeedNumber, dcSalaryID, dcSalaryIDMax, 
		EmployType, dcRegionID, Responsibility, Demand, dcEducationID, MinExperience, MinAge, MaxAge, IssueDate,
		IssueEnd, IsDelete, AddDate, RefreshDate, LastModifyDate, Valid, Lng, Lat, SecondId, Welfare1, Welfare2,
		Welfare3, Welfare4, Welfare5, Welfare6, Welfare7, Welfare8, Welfare9, Welfare10, Welfare11, Welfare12,
		Welfare13, Welfare14, Welfare15, Welfare16, Welfare17, Welfare18, Welfare19
	FROM Job WITH(NOLOCK)
	WHERE cpMainId IN(SELECT ID FROM Inserted)
	AND Valid = 1
END

GO
ALTER TABLE [dbo].[cpMainPublish] ENABLE TRIGGER [Tri_cpMainPublish_Insert]
GO
/****** Object:  Trigger [dbo].[Tri_cpPointSave]    Script Date: 2018/9/25 12:40:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Peter
-- Create date: 2014-08-20 09:55
-- Description:	CpPoint表修改数据触发修改CpMain RemainPoint字段
-- =============================================
CREATE TRIGGER [dbo].[Tri_cpPointSave]
   ON  [dbo].[cpPoint] 
   AFTER UPDATE, INSERT
AS 
BEGIN
	DECLARE @PointDeleted AS INT
	DECLARE @PointInserted AS INT
	DECLARE @cpMainID AS INT

	IF (SELECT COUNT(*) FROM Inserted) = 1
	BEGIN	
		IF EXISTS (SELECT 'x' FROM Deleted)  --UPDATE
		BEGIN
			SELECT @PointDeleted = Point, @cpMainID = cpMainID FROM Deleted
			SELECT @PointInserted = Point FROM Inserted

			UPDATE cpMain SET RemainPoint = ISNULL(RemainPoint, 0) + @PointInserted - ISNULL(@PointDeleted, 0) WHERE ID = @cpMainID
		END
		ELSE								--INSERT
		BEGIN
			SELECT @PointInserted = Point, @cpMainID = cpMainID FROM Inserted
			UPDATE cpMain SET RemainPoint = ISNULL(RemainPoint, 0) + @PointInserted WHERE ID = @cpMainID
		END
	END
END

GO
ALTER TABLE [dbo].[cpPoint] ENABLE TRIGGER [Tri_cpPointSave]
GO
/****** Object:  Trigger [dbo].[Tri_cpProductBulletinSave]    Script Date: 2018/9/25 12:40:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TRIGGER [dbo].[Tri_cpProductBulletinSave]
   ON [dbo].[cpProductBulletin]
   AFTER INSERT, UPDATE
AS 
BEGIN
	DECLARE @Count INT
	DECLARE @ID INT
	DECLARE @EndDate SMALLDATETIME
	SELECT @Count = COUNT(1) FROM Inserted
	IF @Count = 1
	BEGIN
		IF UPDATE(EndDate) 
		BEGIN
			SELECT @ID = ID , @EndDate = CONVERT(VARCHAR(20),EndDate,23) + ' 23:59:00' FROM Inserted
			UPDATE cpProductBulletin SET EndDate = @EndDate WHERE ID = @ID
		END
	END
END






GO
ALTER TABLE [dbo].[cpProductBulletin] ENABLE TRIGGER [Tri_cpProductBulletinSave]
GO
/****** Object:  Trigger [dbo].[Tri_CvAppendix_Delete]    Script Date: 2018/9/25 12:40:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE TRIGGER [dbo].[Tri_CvAppendix_Delete]
	ON [dbo].[cvAppendix]
	AFTER DELETE
AS
BEGIN
	SET NOCOUNT ON;
	INSERT INTO bsDeleteFile(FileType, FileID, [FileName] )
	SELECT 2, cvMainID, [FileName] FROM Deleted WHERE ISNULL([FileName], '') > ''

	DELETE FROM cvAppendixPublish WHERE ID IN(SELECT ID FROM Deleted)
END


GO
ALTER TABLE [dbo].[cvAppendix] ENABLE TRIGGER [Tri_CvAppendix_Delete]
GO
/****** Object:  Trigger [dbo].[Tri_CvAppendix_Save]    Script Date: 2018/9/25 12:40:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE TRIGGER [dbo].[Tri_CvAppendix_Save]
	ON [dbo].[cvAppendix]
	AFTER INSERT,UPDATE
AS
BEGIN
	SET NOCOUNT ON;
	IF(SELECT COUNT(*) FROM Inserted) > 1
		RETURN

	--个人publish相关
	IF NOT EXISTS(SELECT 'x' FROM cvMainPublish WITH(NOLOCK) WHERE ID IN (SELECT cvMainID FROM Inserted))
		RETURN

	IF NOT EXISTS(SELECT 'x' FROM cvAppendixPublish WITH(NOLOCK) WHERE ID IN(SELECT ID FROM Inserted))
		INSERT cvAppendixPublish(ID, cvMainID, Name, Description)
		SELECT ID, cvMainID, Name, Description FROM Inserted
	ELSE
		UPDATE a SET a.Name = b.Name, a.Description = b.Description FROM cvAppendixPublish a, Inserted b WHERE a.Id = b.ID

/*
	IF NOT EXISTS(SELECT 'x' FROM cvMainPublish WITH(NOLOCK) WHERE ID IN (SELECT cvMainID FROM Inserted))
		RETURN

	IF NOT EXISTS(SELECT 'x' FROM cvAppendixPublish WITH(NOLOCK) WHERE ID IN(SELECT ID FROM Inserted))
		INSERT cvAppendixPublish(ID, cvMainID, Name, Description)
		SELECT ID, cvMainID, Name, Description FROM Inserted
	ELSE
		UPDATE a SET a.Name = b.Name, a.Description = b.Description FROM cvAppendixPublish a, Inserted b WHERE a.Id = b.ID
*/
END

GO
ALTER TABLE [dbo].[cvAppendix] ENABLE TRIGGER [Tri_CvAppendix_Save]
GO
/****** Object:  Trigger [dbo].[Tri_CvAttachment_Delete]    Script Date: 2018/9/25 12:40:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--简历附件触发器，更新简历表中的附件字段
CREATE TRIGGER [dbo].[Tri_CvAttachment_Delete]
    ON [dbo].[cvAttachment]
    AFTER DELETE
AS
BEGIN
    SET NOCOUNT ON
    DECLARE @CvMainID INT
    
    SELECT @CvMainID = CvMainID FROM Deleted
	
	IF NOT EXISTS(SELECT 'x' FROM CvAttachment WITH(NOLOCK) WHERE cvMainID = @CvMainID)
		UPDATE CvMain SET Attachment = NULL, WordFilename = NULL WHERE ID = @CvMainID
END

GO
ALTER TABLE [dbo].[cvAttachment] ENABLE TRIGGER [Tri_CvAttachment_Delete]
GO
/****** Object:  Trigger [dbo].[Tri_cvEducation_Delete]    Script Date: 2018/9/25 12:40:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TRIGGER [dbo].[Tri_cvEducation_Delete]
   ON [dbo].[cvEducation]
   AFTER DELETE
AS 
BEGIN
	SET NOCOUNT ON;
	--RETURN
	DELETE FROM cvEducationPublish WHERE ID IN(SELECT ID FROM Deleted)
END

GO
ALTER TABLE [dbo].[cvEducation] ENABLE TRIGGER [Tri_cvEducation_Delete]
GO
/****** Object:  Trigger [dbo].[Tri_cvEducation_Save]    Script Date: 2018/9/25 12:40:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TRIGGER [dbo].[Tri_cvEducation_Save]
   ON [dbo].[cvEducation]
   AFTER INSERT, UPDATE
AS 
BEGIN
	SET NOCOUNT ON;

	IF(SELECT COUNT(*) FROM Inserted) > 1
		RETURN

	--个人publish相关
	IF NOT EXISTS(SELECT 'x' FROM cvMainPublish WITH(NOLOCK) WHERE ID IN (SELECT cvMainID FROM Inserted))
		RETURN

	IF NOT EXISTS(SELECT 'x' FROM cvEducationPublish WITH(NOLOCK) WHERE ID IN(SELECT ID FROM Inserted))
		INSERT INTO cvEducationPublish(ID, cvMainID, GraduateCollage, GraduateCollageEng, Graduation,
			dcMajorID, MajorName, MajorNameEng, Degree, EduType, Details)
		SELECT ID, cvMainID, GraduateCollage, GraduateCollageEng, Graduation,
			dcMajorID, MajorName, MajorNameEng, Degree, EduType, Details 
		FROM Inserted
	ELSE
		UPDATE a 
		SET a.GraduateCollage = b.GraduateCollage, a.GraduateCollageEng = b.GraduateCollageEng, a.Graduation = b.Graduation,
			a.dcMajorID = b.dcMajorID, a.MajorName = b.MajorName, a.MajorNameEng = b.MajorNameEng, a.Degree = b.Degree,
			a.EduType = b.EduType, a.Details = b.Details
		FROM cvEducationPublish a, Inserted b
		WHERE a.Id = b.ID

/*
	IF NOT EXISTS(SELECT 'x' FROM cvMainPublish WITH(NOLOCK) WHERE ID IN (SELECT cvMainID FROM Inserted))
		RETURN

	IF NOT EXISTS(SELECT 'x' FROM cvEducationPublish WITH(NOLOCK) WHERE ID IN(SELECT ID FROM Inserted))
		INSERT INTO cvEducationPublish(ID, cvMainID, GraduateCollage, GraduateCollageEng, Graduation,
			dcMajorID, MajorName, MajorNameEng, Degree, EduType, Details)
		SELECT ID, cvMainID, GraduateCollage, GraduateCollageEng, Graduation,
			dcMajorID, MajorName, MajorNameEng, Degree, EduType, Details 
		FROM Inserted
	ELSE
		UPDATE a 
		SET a.GraduateCollage = b.GraduateCollage, a.GraduateCollageEng = b.GraduateCollageEng, a.Graduation = b.Graduation,
			a.dcMajorID = b.dcMajorID, a.MajorName = b.MajorName, a.MajorNameEng = b.MajorNameEng, a.Degree = b.Degree,
			a.EduType = b.EduType, a.Details = b.Details
		FROM cvEducationPublish a, Inserted b
		WHERE a.Id = b.ID
*/
END

GO
ALTER TABLE [dbo].[cvEducation] ENABLE TRIGGER [Tri_cvEducation_Save]
GO
/****** Object:  Trigger [dbo].[Tri_cvExperienceDelete]    Script Date: 2018/9/25 12:40:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE TRIGGER [dbo].[Tri_cvExperienceDelete]
   ON [dbo].[cvExperience]
   AFTER DELETE
AS 
BEGIN
	DECLARE @Cnt AS INT,
		@RETURN AS INT
	SELECT @Cnt = COUNT(*) FROM Deleted
	IF @Cnt = 1
	BEGIN
		DECLARE @SQL AS VARCHAR(100),
			@NoCareer AS INT,
			@JobName AS VARCHAR(50),
			@LastJobTypeID AS INT,
			@LastIndustryID AS INT,
			@cvMainID AS INT,
			@SubNodeNum AS INT

		SELECT @cvMainID = cvMainID FROM Deleted
		DELETE FROM cvExperiencePublish WHERE ID IN(SELECT ID FROM Deleted)

		IF EXISTS(SELECT 'x' FROM cvExperience WITH(NOLOCK INDEX(IX_cvExperience_cvMainId)) WHERE cvMainId = @cvMainId)
		BEGIN
			SELECT @SubNodeNum = MAX(SubNodeNum) FROM cvExperience WITH(NOLOCK)	WHERE cvMainID = @cvMainID

			UPDATE cvMain SET SubNodeNum = @SubNodeNum WHERE ID = @cvMainId AND ISNULL(SubNodeNum, 100) <> @SubNodeNum
			
			SELECT TOP 1 @JobName = ISNULL(JobName, JobNameEng),
				@LastJobTypeID = dcJobTypeID,
				@LastIndustryID = dcIndustryID
			FROM cvExperience WITH(NOLOCK)
			WHERE cvMainId = @cvMainId
			ORDER BY BeginDate DESC

			IF dbo.IsEnglish(REPLACE(@JobName, ' ', '')) = 0
				SELECT @JobName = LEFT(@JobName, 10)

			UPDATE cvMain SET JobName = @JobName,
				LastJobTypeID = @LastJobTypeID,
				LastIndustryID = @LastIndustryID
			WHERE ID = @cvMainId
			AND NOT (
				JobName = @JobName
				AND LastJobTypeID = @LastJobTypeID
				AND LastIndustryID = @LastIndustryID)
		END
		ELSE
		BEGIN
			UPDATE cvMain SET JobName = 
					CASE
					WHEN Attachment > '' THEN '附件简历'
					ELSE SecondId
					END
			WHERE ID = @cvMainId

			EXEC @RETURN = pcCvMainByCvLevelCheck @cvMainID, 4
		END
	END
END




GO
ALTER TABLE [dbo].[cvExperience] ENABLE TRIGGER [Tri_cvExperienceDelete]
GO
/****** Object:  Trigger [dbo].[Tri_cvExperienceUpdate]    Script Date: 2018/9/25 12:40:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE TRIGGER [dbo].[Tri_cvExperienceUpdate]
   ON [dbo].[cvExperience]
   AFTER INSERT,UPDATE
AS 
BEGIN
	DECLARE @Cnt AS INT,
		@RETURN AS INT
	SELECT @Cnt = COUNT(*) FROM Inserted
	IF @Cnt = 1
	BEGIN
		DECLARE @SQL AS VARCHAR(100),
			@NoCareer AS INT,
			@JobName AS VARCHAR(50),
			@LastJobTypeID AS INT,
			@LastIndustryID AS INT,
			@cvMainID AS INT,
			@SubNodeNum AS INT

		SELECT @cvMainID = cvMainID FROM Inserted

		SELECT @SubNodeNum = MAX(SubNodeNum) FROM cvExperience WITH(NOLOCK)	WHERE cvMainID = @cvMainID

		UPDATE cvMain SET SubNodeNum = @SubNodeNum WHERE ID = @cvMainId AND ISNULL(SubNodeNum, 100) <> @SubNodeNum
		
		SELECT TOP 1 @JobName = ISNULL(JobName, JobNameEng),
			@LastJobTypeID = dcJobTypeID,
			@LastIndustryID = dcIndustryID
		FROM cvExperience WITH(NOLOCK)
		WHERE cvMainId = @cvMainId
		ORDER BY BeginDate DESC

		IF dbo.IsEnglish(REPLACE(@JobName, ' ', '')) = 0
			SELECT @JobName = LEFT(@JobName, 10)

		IF CHARINDEX(',', @JobName) > 0
		BEGIN
			SET @JobName = REPLACE(@JobName, ',', '，')
		END

		UPDATE cvMain SET JobName = @JobName,
			LastJobTypeID = @LastJobTypeID,
			LastIndustryID = @LastIndustryID
		WHERE ID = @cvMainId

		--个人publish相关
		IF EXISTS(SELECT 'x' FROM cvMainPublish WITH(NOLOCK) WHERE ID IN (SELECT cvMainID FROM Inserted))
		BEGIN
			IF EXISTS(SELECT 'x' FROM cvExperiencePublish WITH(NOLOCK) WHERE ID IN(SELECT ID FROM Inserted))
				UPDATE a
				SET	a.CompanyName = b.CompanyName, a.dcIndustryID = b.dcIndustryID,
					a.dcJobtypeID = b.dcJobtypeID, a.JobName = b.JobName,
					a.SubNodeNum = b.SubNodeNum, a.Description = b.Description
				FROM cvExperiencePublish a, Inserted b
				WHERE a.ID = b.ID
			ELSE
				INSERT INTO cvExperiencePublish(ID, cvMainID, CompanyName, dcIndustryID, dcJobtypeID, JobName, SubNodeNum, Description)
				SELECT ID, cvMainID, CompanyName, dcIndustryID, dcJobtypeID, JobName, SubNodeNum, Description
				FROM Inserted
		END
	END
END



GO
ALTER TABLE [dbo].[cvExperience] ENABLE TRIGGER [Tri_cvExperienceUpdate]
GO
/****** Object:  Trigger [dbo].[Tri_cvLanguage_Delete]    Script Date: 2018/9/25 12:40:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TRIGGER [dbo].[Tri_cvLanguage_Delete]
   ON [dbo].[cvLanguage]
   AFTER DELETE
AS 
BEGIN
	SET NOCOUNT ON;
	DELETE FROM cvLanguagePublish WHERE ID IN(SELECT ID FROM Deleted)
END

GO
ALTER TABLE [dbo].[cvLanguage] ENABLE TRIGGER [Tri_cvLanguage_Delete]
GO
/****** Object:  Trigger [dbo].[Tri_cvLanguage_Save]    Script Date: 2018/9/25 12:40:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TRIGGER [dbo].[Tri_cvLanguage_Save]
   ON [dbo].[cvLanguage]
   AFTER INSERT, UPDATE
AS 
BEGIN
	SET NOCOUNT ON;

	IF(SELECT COUNT(*) FROM Inserted) > 1
		RETURN

	--个人publish相关
	IF NOT EXISTS(SELECT 'x' FROM cvMainPublish WITH(NOLOCK) WHERE ID IN (SELECT cvMainID FROM Inserted))
		RETURN

	IF EXISTS(SELECT 'x' FROM cvLanguagePublish WITH(NOLOCK) WHERE ID IN(SELECT ID FROM Inserted))
		UPDATE a 
		SET a.LanguageType = b.LanguageType
		FROM cvLanguagePublish a, Inserted b
		WHERE a.Id = b.ID
	ELSE
		INSERT INTO cvLanguagePublish(ID, cvMainID, LanguageType)
		SELECT ID, cvMainID, LanguageType FROM Inserted
END

GO
ALTER TABLE [dbo].[cvLanguage] ENABLE TRIGGER [Tri_cvLanguage_Save]
GO
/****** Object:  Trigger [dbo].[Tri_CvMainByAttachMentUpdate]    Script Date: 2018/9/25 12:40:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE TRIGGER [dbo].[Tri_CvMainByAttachMentUpdate]
   ON  [dbo].[cvMain]
   AFTER UPDATE
AS 
BEGIN
	SET NOCOUNT ON;

	DECLARE @COUNT AS INT

	SELECT @COUNT = COUNT(1) FROM Inserted
	IF @COUNT = 1
	BEGIN
		----上传附件，记录应该删除的附件
		IF UPDATE(Attachment)
		BEGIN
			INSERT INTO bsDeleteFile(FileType, FileID, [FileName] )
			SELECT 3, ID, Attachment FROM Deleted WHERE ISNULL(Attachment, '') > ''

			UPDATE cvMain SET JobName = '附件简历'
			WHERE ID =(SELECT ID FROM Inserted)
			AND Attachment > ''
			AND ISNULL(JobName, SecondId) = SecondId

			UPDATE cvMain SET JobName = SecondId
			WHERE ID =(SELECT ID FROM Inserted)
			AND Attachment IS NULL
			AND JobName = '附件简历'
		END
	END
END










GO
ALTER TABLE [dbo].[cvMain] ENABLE TRIGGER [Tri_CvMainByAttachMentUpdate]
GO
/****** Object:  Trigger [dbo].[Tri_CvMainDelete]    Script Date: 2018/9/25 12:40:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE TRIGGER [dbo].[Tri_CvMainDelete]
	ON [dbo].[cvMain]
	AFTER DELETE
AS
BEGIN
	SET NOCOUNT ON;
	INSERT INTO bsDeleteFile(FileType, FileID, [FileName] )
	SELECT 3, ID, Attachment FROM Deleted WHERE ISNULL(Attachment, '') > ''

	DELETE FROM cvMainPublish WHERE Id IN(SELECT ID FROM Deleted)	
	UPDATE CaCvApplyDeleted SET cvDeleted = 1 WHERE cvMainId IN(SELECT Id FROM Deleted)

	DECLARE @t AS TABLE(ID INT)
	INSERT INTO @t
	SELECT id FROM ChatOnline WHERE cvMainId IN(SELECT ID FROM Deleted)
	IF(SELECT COUNT(*) FROM @t) > 0
	BEGIN
		BEGIN TRY
			INSERT INTO cvMainDel SELECT * FROM Deleted
			INSERT INTO ChatOnlineLogDel SELECT * FROM ChatOnlineLog WHERE ChatOnlineId IN(SELECT id FROM @t)
			INSERT INTO ChatOnlineDel SELECT * FROM ChatOnline WHERE Id IN(SELECT ID FROM @t)

			DELETE FROM ChatOnlineLog WHERE ChatOnlineId IN(SELECT id FROM @t)
			DELETE FROM ChatOnline WHERE Id IN(SELECT ID FROM @t)
		END TRY
		BEGIN CATCH
		END CATCH
	END
END


GO
ALTER TABLE [dbo].[cvMain] ENABLE TRIGGER [Tri_CvMainDelete]
GO
/****** Object:  Trigger [dbo].[Tri_CvMainInsert]    Script Date: 2018/9/25 12:40:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--***************************
--创建完简历后，程序自动默认开启推送“你的菜儿”的功能。
-- 2016 1 18 sean
--***************************
CREATE TRIGGER [dbo].[Tri_CvMainInsert]
   ON  [dbo].[cvMain]
   AFTER INSERT
AS 
BEGIN
	SET NOCOUNT ON;

	DECLARE @paMainId INT

	IF (SELECT COUNT(*) FROM Inserted) = 1
	BEGIN
		SELECT @paMainId = paMainId FROM Inserted
		IF EXISTS(SELECT 'x' FROM paMain WITH(NOLOCK) WHERE id = @paMainId AND isUseYourFood IS NULL)
			UPDATE paMain SET isUseYourFood = 1 WHERE id = @paMainId

		DECLARE @SecondId VARCHAR(10)
		SET @SecondId = LEFT(REPLACE(NEWID(), '-', ''), 10)
		WHILE EXISTS(SELECT 'x' FROM cvMain WITH(NOLOCK) WHERE SecondId = @SecondId)
			SET @SecondId = LEFT(REPLACE(NEWID(), '-', ''), 10)

		UPDATE cvMain SET SecondId = LOWER(@SecondId) WHERE ID IN(SELECT Id FROM Inserted)
	END
END

GO
ALTER TABLE [dbo].[cvMain] ENABLE TRIGGER [Tri_CvMainInsert]
GO
/****** Object:  Trigger [dbo].[Tri_CvMainUpdate]    Script Date: 2018/9/25 12:40:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TRIGGER [dbo].[Tri_CvMainUpdate]
   ON  [dbo].[cvMain]
   AFTER UPDATE
AS 
BEGIN
	SET NOCOUNT ON;

	DECLARE @COUNT AS INT, @ID AS INT, @Valid AS TINYINT, @ValidOld AS TINYINT, @HasAttachment AS BIT, @SpreadDate DATETIME

	SELECT @COUNT = COUNT(1) FROM Inserted
	IF @COUNT = 1
	BEGIN
		IF UPDATE(CvType)
		BEGIN
			DECLARE @OldCvtype AS TINYINT,
				@NewCvtype AS TINYINT
			SELECT @oldCvtype = cvType FROM Deleted
			SELECT @NewCvtype = cvType FROM Inserted

			IF @oldCvtype = 0 AND @NewCvtype = 1
			BEGIN
				DECLARE @Age INT, @JobTypeID INT, @JobName VARCHAR(100)
				SELECT @JobName = JobName FROM Inserted
				IF @JobName IS NULL OR @JobName = '' OR @JobName = '应届毕业生'
				BEGIN
					SELECT @JobName = '应届毕业生', @Age = BirthDay FROM paMain WITH(NOLOCK) WHERE id = (SELECT paMainId FROM Inserted)
					SET @Age = CONVERT(VARCHAR(6), GETDATE(), 112) - @age
					IF @Age > 2600	
					BEGIN
						SELECT TOP 1 @JobTypeID = dcJobTypeId FROM cvJobType WITH(NOLOCK) 
						WHERE cvMainId = (SELECT Id FROM Inserted)
						IF @JobTypeID IS NULL
							SET @JobName = '未填写工作经历'
						ELSE
							SELECT @JobName = '期望' + Description FROM dcJobType WITH(NOLOCK) WHERE Id = @JobTypeID
					END

					UPDATE cvMain SET JobName = @JobName WHERE ID =(SELECT ID FROM Inserted)
				END
			END

			IF @oldCvtype = 1 AND @NewCvtype = 0
				UPDATE cvMain SET JobName = CASE WHEN Attachment > '' THEN '附件简历' ELSE SecondId END
				WHERE ID =(SELECT ID FROM Inserted)
		END

		----触发器生成Valid
		IF UPDATE(IsCvHidden) OR UPDATE(cvLevel) OR UPDATE(cvLevelEng) OR UPDATE(VerifyResult) OR UPDATE(VerifyResultEng) OR UPDATE(Attachment) OR UPDATE(Degree)
		BEGIN
			DECLARE @IsCvHidden AS BIT, @cvLevel AS CHAR(10), @cvLevelEng AS CHAR(10), @VerifyResult AS TINYINT, @VerifyResultEng AS TINYINT
			DECLARE @chsValid AS BIT, @engValid AS BIT, @cvMainId INT, @paMainID INT

			SELECT @ID = ID, @ValidOld = Valid, 
				@IsCvHidden = IsCvHidden, @cvLevel = cvLevel,
				@cvLevelEng = cvLevelEng, @VerifyResult = VerifyResult,
				@VerifyResultEng = VerifyResultEng, @HasAttachment = CASE LEN(ISNULL(Attachment, '')) WHEN 0 THEN 0 ELSE 1 END
			FROM Inserted
 
			SET @Valid = 0
			IF @IsCvHidden = 0
			BEGIN
				SET @chsValid = 0
				SET @engValid = 0
				IF (LEFT(@cvLevel, 6) LIKE '111__1') AND @VerifyResult = 1
					SET @chsValid = 1
				IF (LEFT(@cvLevelEng, 6) LIKE '111__1') AND @VerifyResultEng = 1
					SET @engValid = 1

				IF @chsValid = 1 AND @engValid = 1
					SET @Valid = 2
				ELSE IF @chsValid = 1
					SET @Valid = 1
				ELSE IF @engValid = 1
					SET @Valid = 3
				ELSE IF @HasAttachment = 1 AND @VerifyResult = 1 AND @VerifyResultEng = 1 --AND (LEFT(@cvLevel, 2) = '11' OR LEFT(@cvLevelEng, 2) = '11')
					SET @Valid = 1
				ELSE
					SET @Valid = 0
			END

			IF @Valid <> @ValidOld
				UPDATE cvMain SET Valid = @Valid WHERE Id = @ID

			--Update IsOpen,sean 2012-8-21
			IF @chsValid = 1 OR @engValid = 1
			BEGIN
				DECLARE @IsOpenOld AS BIT, @IsOpen AS BIT, @Degree AS TINYINT, @LivePlace AS VARCHAR(2), @BirthDay AS INT
				SELECT @IsOpenOld = IsOpen, @Degree = Degree, @paMainID = paMainID FROM Inserted WITH(NOLOCK)
				SELECT @LivePlace = LEFT(LivePlace, 2), @BirthDay = BirthDay FROM paMain WITH(NOLOCK) WHERE ID= @paMainID
				SELECT @IsOpen = 0
				IF @Degree = 1
					SELECT @IsOpen = 1
				ELSE
					SELECT @IsOpen = 1 FROM dcCvOpenSET WITH(NOLOCK)
					WHERE dcEducation = @Degree AND dcProvinceId = @LivePlace
					AND ISNULL(@BirthDay, 999999) > dbo.AgeToBirth(Age)
				
				IF @IsOpen <> @IsOpenOld 
					UPDATE cvMain SET IsOpen = @IsOpen WHERE ID = @ID			
			END

			IF UPDATE(VerifyResult) OR UPDATE(VerifyResultEng)
			BEGIN
				SELECT @cvMainId = ID,
					@Cvlevel = cvLevel,
					@CvlevelEng = cvLevelEng,
					@VerifyResult = VerifyResult,
					@VerifyResultEng = VerifyResultEng,
					@paMainID = paMainID
				FROM Inserted

				IF (@Cvlevel LIKE '111__1%' AND @VerifyResult = 1) OR (@CvlevelEng LIKE '111__1%' AND @VerifyResultEng = 1)
				BEGIN
					DECLARE @RegisterMode AS TINYINT,
						@RegisterType AS TINYINT,
						@ProvinceId AS TINYINT, 
						@Email AS VARCHAR(50), 
						@AddMan AS SMALLINT,
						@Name AS NVARCHAR(10),
						@AddDate SMALLDATETIME

					SELECT @Name = ISNULL(Name, NameEng), @AddDate = AddDate, @addMan = AddMan, @RegisterMode = RegisterMode, 
						@RegisterType = RegisterType, @ProvinceId = dcProvinceID, @Email = EMail, @SpreadDate = SpreadDate
					FROM paMain WITH(NOLOCK)
					WHERE ID = @paMainID

					IF (@RegisterMode = 1 OR @RegisterType = 101) AND @Name > '' AND @AddMan > 0
					BEGIN
						UPDATE paMain SET RegisterMode = 11, RegisterType = 102 WHERE Id = @paMainId
						INSERT INTO infoCvVerifyLog(paMainId, cvMainId, AddMan, AddDate, CheckDate, dcProvinceId)
						SELECT @paMainId, @cvMainId, @addMan, ISNULL(@SpreadDate, @AddDate), GETDATE(), @ProvinceId
 
						IF NOT EXISTS(SELECT 'x' FROM  paInfoEmailVerifyLog WITH(NOLOCK) WHERE paMainId = @paMainId)
							INSERT INTO paInfoEmailVerifyLog(paMainId, Email, AddMan)
							VALUES(@paMainId, @Email, @AddMan)
						
						IF NOT EXISTS(SELECT 'x' FROM Info_DateReport WITH(NOLOCK)
										WHERE InfoManager_Id = @AddMan
										AND Province_Id = @ProvinceId
										AND CountDate = CONVERT(VARCHAR(8), GETDATE(), 112))
							INSERT INTO Info_DateReport(Province_Id, InfoManager_Id, countdate)
							VALUES(@ProvinceId, @AddMan, CONVERT(VARCHAR(8), GETDATE(), 112))

						UPDATE Info_DateReport SET RealResume = RealResume + 1
						WHERE InfoManager_Id = @AddMan
						AND Province_Id = @ProvinceId
						AND CountDate = CONVERT(VARCHAR(8), GETDATE(), 112)
					END
				END
			END
		END

		--个人提取publish相关
		IF UPDATE(Degree) OR UPDATE(dcMajorID) OR UPDATE(LastJobTypeID) OR UPDATE(LastIndustryID) OR UPDATE(JobName) 
			OR UPDATE(SubNodeNum) OR UPDATE(RelatedWorkYears) OR UPDATE(dcSalaryID) OR UPDATE(IsNegotiable) 
			OR UPDATE(Speciality) OR UPDATE(SpecialityEng) OR UPDATE(Attachment) OR UPDATE(RefreshDate) OR UPDATE(Valid)
			OR @Valid IS NOT NULL	
		BEGIN
			IF @Valid IS NULL
				SELECT @Valid = Valid FROM Inserted
			IF NOT EXISTS(SELECT 'x' FROM paMain WITH(NOLOCK) WHERE VerifyCount > 0 AND id IN(SELECT paMainId FROM Inserted))
				SET @Valid = 0
			IF @Valid > 0
			BEGIN
				IF NOT EXISTS(SELECT 'x' FROM paMainPublish WITH(NOLOCK) WHERE ID IN(SELECT paMainId FROM Inserted))
					INSERT INTO paMainPublish(ID, Gender, BirthDay, LivePlace, AccountPlace, GrowPlace, Height, HasPhoto, LastLoginDate, LastModifyDate, MobileRegion)
					SELECT ID, Gender, BirthDay, LivePlace, AccountPlace, GrowPlace, Height, HasPhoto, LastLoginDate, LastModifyDate, MobileRegion
					FROM paMain WITH(NOLOCK) WHERE ID IN(SELECT paMainID FROM Inserted)	

				IF EXISTS(SELECT 'x' FROM cvMainPublish WITH(NOLOCK) WHERE ID IN(SELECT ID FROM Inserted))
					UPDATE a
					SET a.Degree = b.Degree, a.dcMajorID = b.dcMajorID, a.LastJobTypeID = b.LastJobTypeID, a.LastIndustryID = b.LastIndustryID,
						a.JobName = b.JobName, a.SubNodeNum = b.SubNodeNum, a.RelatedWorkYears = b.RelatedWorkYears, a.dcSalaryID = b.dcSalaryID,
						a.IsNegotiable = b.IsNegotiable, a.Speciality = b.Speciality, a.SpecialityEng = b.SpecialityEng,
						a.Attachment = b.Attachment, a.Valid = @Valid, a.RefreshDate = b.RefreshDate, a.EmployType = b.EmployType, a.SecondId = b.SecondId
					FROM cvMainPublish a, Inserted b
					WHERE a.Id = b.Id
				ELSE
					INSERT INTO cvMainPublish(ID, paMainID, Degree, dcMajorID, LastJobTypeID, LastIndustryID, JobName, SubNodeNum, 
						RelatedWorkYears, dcSalaryID, IsNegotiable, Speciality, SpecialityEng, Attachment, Valid, RefreshDate, EmployType, SecondId)
					SELECT ID, paMainID, Degree, dcMajorID, LastJobTypeID, LastIndustryID, JobName, SubNodeNum, 
						RelatedWorkYears, dcSalaryID, IsNegotiable, Speciality, SpecialityEng, Attachment, @Valid, RefreshDate, EmployType, SecondId
					FROM Inserted

				IF UPDATE(dcSalaryID) OR UPDATE(IsNegotiable)
				BEGIN
					DELETE FROM cvIndustryPublish WHERE cvMainId IN(SELECT ID FROM Inserted)
					DELETE FROM cvJobTypePublish WHERE cvMainId IN(SELECT ID FROM Inserted)
					DELETE FROM cvJobPlacePublish WHERE cvMainId IN(SELECT ID FROM Inserted)

					INSERT INTO cvIndustryPublish(cvMainID, dcIndustryID)
					SELECT cvMainID, dcIndustryID FROM cvIndustry WITH(NOLOCK) WHERE cvMainId IN(SELECT ID FROM Inserted)

					INSERT INTO cvJobTypePublish(cvMainID, dcJobTypeID)
					SELECT cvMainID, dcJobTypeID FROM cvJobType WITH(NOLOCK) WHERE cvMainId IN(SELECT ID FROM Inserted)

					INSERT INTO cvJobPlacePublish(cvMainID, dcRegionID)
					SELECT cvMainID, dcRegionID FROM cvJobPlace WITH(NOLOCK) WHERE cvMainId IN(SELECT ID FROM Inserted)
				END
			END
			ELSE
				DELETE FROM CvMainPublish WHERE ID IN(SELECT ID FROM Inserted)
		END
	END
END
GO
ALTER TABLE [dbo].[cvMain] ENABLE TRIGGER [Tri_CvMainUpdate]
GO
/****** Object:  Trigger [dbo].[Tri_cvMainPublish_Insert]    Script Date: 2018/9/25 12:40:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TRIGGER [dbo].[Tri_cvMainPublish_Insert]
   ON [dbo].[cvMainPublish]
   AFTER INSERT
AS 
BEGIN
	SET NOCOUNT ON;
	SET XACT_ABORT OFF
	BEGIN TRY
		INSERT cvAppendixPublish(ID, cvMainID, Name, Description)
		SELECT ID, cvMainID, Name, Description FROM cvAppendix WITH(NOLOCK) WHERE cvMainId IN(SELECT ID FROM Inserted)

		INSERT INTO cvEducationPublish(ID, cvMainID, GraduateCollage, GraduateCollageEng, Graduation,
			dcMajorID, MajorName, MajorNameEng, Degree, EduType, Details)
		SELECT ID, cvMainID, GraduateCollage, GraduateCollageEng, Graduation,
			dcMajorID, MajorName, MajorNameEng, Degree, EduType, Details FROM cvEducation WITH(NOLOCK) WHERE cvMainId IN(SELECT ID FROM Inserted)

		INSERT INTO cvExperiencePublish(ID, cvMainID, CompanyName, dcIndustryID, dcJobtypeID, JobName, SubNodeNum, Description)
		SELECT ID, cvMainID, CompanyName, dcIndustryID, dcJobtypeID, JobName, SubNodeNum, Description
		FROM cvExperience WITH(NOLOCK) WHERE cvMainId IN(SELECT ID FROM Inserted)

		INSERT INTO cvIndustryPublish(cvMainID, dcIndustryID)
		SELECT cvMainID, dcIndustryID FROM cvIndustry WITH(NOLOCK) WHERE cvMainId IN(SELECT ID FROM Inserted)

		INSERT INTO cvJobTypePublish(cvMainID, dcJobTypeID)
		SELECT cvMainID, dcJobTypeID FROM cvJobType WITH(NOLOCK) WHERE cvMainId IN(SELECT ID FROM Inserted)

		INSERT INTO cvJobPlacePublish(cvMainID, dcRegionID)
		SELECT cvMainID, dcRegionID FROM cvJobPlace WITH(NOLOCK) WHERE cvMainId IN(SELECT ID FROM Inserted)

		INSERT INTO cvLanguagePublish(ID, cvMainID, LanguageType)
		SELECT ID, cvMainID, LanguageType FROM cvLanguage WITH(NOLOCK) WHERE cvMainId IN(SELECT ID FROM Inserted)

		INSERT INTO cvProjectPublish(ID, cvMainID, Name, Description, Responsibilities)
		SELECT ID, cvMainID, Name, Description, Responsibilities FROM cvProject WITH(NOLOCK) WHERE cvMainId IN(SELECT ID FROM Inserted)

		INSERT INTO cvTrainingPublish(ID, cvMainID, Institution, Course, Certificate, Details)
		SELECT ID, cvMainID, Institution, Course, Certificate, Details 
		FROM cvTraining WITH(NOLOCK) WHERE cvMainId IN(SELECT ID FROM Inserted)
	END TRY
	BEGIN CATCH
	END CATCH
END

GO
ALTER TABLE [dbo].[cvMainPublish] ENABLE TRIGGER [Tri_cvMainPublish_Insert]
GO
/****** Object:  Trigger [dbo].[Tri_cvProject_Delete]    Script Date: 2018/9/25 12:40:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create TRIGGER [dbo].[Tri_cvProject_Delete]
   ON [dbo].[cvProject]
   AFTER DELETE
AS 
BEGIN
	SET NOCOUNT ON;

	DELETE FROM cvProjectPublish WHERE ID IN(SELECT ID FROM Deleted)
END

GO
ALTER TABLE [dbo].[cvProject] ENABLE TRIGGER [Tri_cvProject_Delete]
GO
/****** Object:  Trigger [dbo].[Tri_cvProject_Save]    Script Date: 2018/9/25 12:40:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TRIGGER [dbo].[Tri_cvProject_Save]
   ON [dbo].[cvProject]
   AFTER INSERT, UPDATE
AS 
BEGIN
	SET NOCOUNT ON;

	IF(SELECT COUNT(*) FROM Inserted) > 1
		RETURN

	IF NOT EXISTS(SELECT 'x' FROM cvMainPublish WITH(NOLOCK) WHERE ID IN (SELECT cvMainID FROM Inserted))
		RETURN

	IF NOT EXISTS(SELECT 'x' FROM cvProjectPublish WITH(NOLOCK) WHERE ID IN(SELECT ID FROM Inserted))
		INSERT INTO cvProjectPublish(ID, cvMainID, Name, Description, Responsibilities)
		SELECT ID, cvMainID, Name, Description, Responsibilities FROM Inserted
	ELSE
		UPDATE a 
		SET a.Name = b.Name, a.Description = b.Description, a.Responsibilities = b.Responsibilities
		FROM cvProjectPublish a, Inserted b
		WHERE a.Id = b.ID	
END

GO
ALTER TABLE [dbo].[cvProject] ENABLE TRIGGER [Tri_cvProject_Save]
GO
/****** Object:  Trigger [dbo].[Tri_cvTraining_Delete]    Script Date: 2018/9/25 12:40:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create TRIGGER [dbo].[Tri_cvTraining_Delete]
   ON [dbo].[cvTraining]
   AFTER DELETE
AS 
BEGIN
	SET NOCOUNT ON;

	DELETE FROM cvTrainingPublish WHERE ID IN(SELECT ID FROM Deleted)
END

GO
ALTER TABLE [dbo].[cvTraining] ENABLE TRIGGER [Tri_cvTraining_Delete]
GO
/****** Object:  Trigger [dbo].[Tri_cvTraining_Save]    Script Date: 2018/9/25 12:40:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TRIGGER [dbo].[Tri_cvTraining_Save]
   ON [dbo].[cvTraining]
   AFTER INSERT, UPDATE
AS 
BEGIN
	SET NOCOUNT ON;

	IF(SELECT COUNT(*) FROM Inserted) > 1
		RETURN

	IF NOT EXISTS(SELECT 'x' FROM cvMainPublish WITH(NOLOCK) WHERE ID IN (SELECT cvMainID FROM Inserted))
		RETURN

	IF NOT EXISTS(SELECT 'x' FROM cvTrainingPublish WITH(NOLOCK) WHERE ID IN(SELECT ID FROM Inserted))
		INSERT INTO cvTrainingPublish(ID, cvMainID, Institution, Course, Certificate, Details)
		SELECT ID, cvMainID, Institution, Course, Certificate, Details FROM Inserted
	ELSE
		UPDATE a 
		SET a.Institution = b.Institution, a.Course = b.Course, a.Certificate = b.Certificate, a.Details = b.Details
		FROM cvTrainingPublish a, Inserted b
		WHERE a.Id = b.ID	
END

GO
ALTER TABLE [dbo].[cvTraining] ENABLE TRIGGER [Tri_cvTraining_Save]
GO
/****** Object:  Trigger [dbo].[Tri_dcFeeDelete]    Script Date: 2018/9/25 12:40:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TRIGGER [dbo].[Tri_dcFeeDelete]
   ON [dbo].[dcFee]
   AFTER DELETE
AS 
BEGIN
	SET NOCOUNT ON;
	IF EXISTS(SELECT 'x' FROM Deleted WHERE StartDate < GETDATE())
	BEGIN
		RAISERROR('该类型已经生效，不能删除', 10, 1)
		ROLLBACK TRANSACTION
		RETURN
	END
END





GO
ALTER TABLE [dbo].[dcFee] ENABLE TRIGGER [Tri_dcFeeDelete]
GO
/****** Object:  Trigger [dbo].[Tri_dcFeeSave]    Script Date: 2018/9/25 12:40:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TRIGGER [dbo].[Tri_dcFeeSave]
   ON [dbo].[dcFee]
   AFTER INSERT, UPDATE
AS 
BEGIN
	SET NOCOUNT ON;
/*
	IF EXISTS(SELECT 'x' FROM Inserted WHERE StartDate < GETDATE())
		AND EXISTS(SELECT 'x' FROM Deleted)
	BEGIN
		RAISERROR('该类型已经生效，不能修改', 10, 1)
		ROLLBACK TRANSACTION
		RETURN
	END
*/
	IF EXISTS(SELECT a.id FROM dcFee a WITH(NOLOCK), Inserted b
				WHERE a.ID <> b.ID
				AND a.Type = b.Type
				AND a.dcProvinceID = b.dcProvinceID
				AND (
						(a.startDate <= b.startDate 
						AND a.endDate > b.startDate)
					OR
						(a.startDate < b.endDate
						AND a.endDate >= b.endDate)
					)
				)
	BEGIN
		RAISERROR('该类型时间交叉，不能修改', 10, 1)
		ROLLBACK TRANSACTION
		RETURN
	END

	DECLARE @Count AS INT
	DECLARE @ID AS INT
	DECLARE @StartDate AS VARCHAR(30)
	DECLARE @EndDate AS VARCHAR(30)
	SELECT @Count = COUNT(1) FROM Inserted
	IF @Count = 1
	BEGIN
		IF UPDATE(EndDate) 
		BEGIN
			SELECT @ID = ID ,@StartDate =CONVERT(VARCHAR(10), StartDate, 23) + ' 00:00:00', @EndDate = CONVERT(VARCHAR(20),EndDate,23) + ' 23:59:00' FROM Inserted
			UPDATE dcFee SET EndDate = @EndDate WHERE ID = @ID
		END
	END
END













GO
ALTER TABLE [dbo].[dcFee] ENABLE TRIGGER [Tri_dcFeeSave]
GO
/****** Object:  Trigger [dbo].[Tri_dcFeeDetailDelete]    Script Date: 2018/9/25 12:40:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE TRIGGER [dbo].[Tri_dcFeeDetailDelete]
   ON [dbo].[dcFeeDetail]
   AFTER Delete
AS 
BEGIN
	RETURN
	SET NOCOUNT ON;

	IF EXISTS(SELECT 'x' FROM dcFee WITH(NOLOCK)
			WHERE ID IN	(SELECT dcFeeID FROM Deleted)
			AND startDate < GETDATE())
	BEGIN
		RAISERROR('该类型已经生效，不能删除', 10, 1)
		ROLLBACK TRANSACTION
		RETURN
	END
END





GO
ALTER TABLE [dbo].[dcFeeDetail] ENABLE TRIGGER [Tri_dcFeeDetailDelete]
GO
/****** Object:  Trigger [dbo].[Tri_dcFeeDetailSave]    Script Date: 2018/9/25 12:40:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TRIGGER [dbo].[Tri_dcFeeDetailSave]
   ON [dbo].[dcFeeDetail]
   AFTER UPDATE
AS 
BEGIN
	RETURN
	SET NOCOUNT ON;

	IF EXISTS(SELECT 'x' FROM dcFee WITH(NOLOCK)
			WHERE ID IN	(SELECT dcFeeID FROM Inserted)
			AND startDate < GETDATE())
	BEGIN
		RAISERROR('该类型已经生效，不能修改', 10, 1)
		ROLLBACK TRANSACTION
		RETURN
	END
END







GO
ALTER TABLE [dbo].[dcFeeDetail] ENABLE TRIGGER [Tri_dcFeeDetailSave]
GO
/****** Object:  Trigger [dbo].[Tri_dcVipDelete]    Script Date: 2018/9/25 12:40:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TRIGGER [dbo].[Tri_dcVipDelete]
   ON [dbo].[dcVip]
   AFTER DELETE
AS 
BEGIN
	SET NOCOUNT ON;
	IF EXISTS(SELECT 'x' FROM Deleted WHERE StartDate < GETDATE())
	BEGIN
		RAISERROR('该套餐类型已经生效，不能删除', 10, 1)
		ROLLBACK TRANSACTION
		RETURN
	END
END




GO
ALTER TABLE [dbo].[dcVip] ENABLE TRIGGER [Tri_dcVipDelete]
GO
/****** Object:  Trigger [dbo].[Tri_DcVipSave]    Script Date: 2018/9/25 12:40:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TRIGGER [dbo].[Tri_DcVipSave]
   ON [dbo].[dcVip]
   AFTER INSERT, UPDATE
AS 
BEGIN
	SET NOCOUNT ON;
/*
	IF EXISTS(SELECT 'x' FROM Inserted WHERE StartDate < GETDATE())
		AND EXISTS(SELECT 'x' FROM Deleted)
	BEGIN
		RAISERROR('该套餐类型已经生效，不能修改', 10, 1)
		ROLLBACK TRANSACTION
		RETURN
	END
*/
	IF EXISTS(SELECT 'x' FROM dcVip a WITH(NOLOCK), Inserted b
				WHERE a.ID <> b.ID
				AND a.dcProvinceID = b.dcProvinceID
				AND (
						(a.startDate <= b.startDate 
						AND a.endDate > b.startDate)
					OR
						(a.startDate < b.endDate
						AND a.endDate >= b.endDate)
					)
				)
	BEGIN
		RAISERROR('该套餐类型时间交叉，不能修改', 10, 1)
		ROLLBACK TRANSACTION
		RETURN
	END

	DECLARE @Count AS INT
	DECLARE @ID AS INT
	DECLARE @StartDate AS VARCHAR(30)
	DECLARE @EndDate AS VARCHAR(30)
	SELECT @Count = COUNT(1) FROM Inserted
	IF @Count = 1
	BEGIN
		IF UPDATE(EndDate) 
		BEGIN
			SELECT @ID = ID ,@StartDate =CONVERT(VARCHAR(10), StartDate, 23) + ' 00:00:00', @EndDate = CONVERT(VARCHAR(20),EndDate,23) + ' 23:59:00' FROM Inserted
			UPDATE dcVip SET EndDate = @EndDate WHERE ID = @ID
		END
	END
END







GO
ALTER TABLE [dbo].[dcVip] ENABLE TRIGGER [Tri_DcVipSave]
GO
/****** Object:  Trigger [dbo].[Tri_dcVipDetailDelete]    Script Date: 2018/9/25 12:40:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TRIGGER [dbo].[Tri_dcVipDetailDelete]
   ON [dbo].[dcVipDetail]
   AFTER Delete
AS 
BEGIN
	RETURN
	SET NOCOUNT ON;

	IF EXISTS(SELECT 'x' FROM dcVip WITH(NOLOCK)
			WHERE ID IN	(SELECT dcVipID FROM Deleted)
			AND startDate < GETDATE())
	BEGIN
		RAISERROR('该套餐类型已经生效，不能删除', 10, 1)
		ROLLBACK TRANSACTION		
		RETURN
	END
END

GO
ALTER TABLE [dbo].[dcVipDetail] ENABLE TRIGGER [Tri_dcVipDetailDelete]
GO
/****** Object:  Trigger [dbo].[Tri_dcVipDetailSave]    Script Date: 2018/9/25 12:40:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TRIGGER [dbo].[Tri_dcVipDetailSave]
   ON [dbo].[dcVipDetail]
   AFTER UPDATE
AS 
BEGIN
	RETURN
	SET NOCOUNT ON;

	IF EXISTS(SELECT 'x' FROM dcVip WITH(NOLOCK)
			WHERE ID IN	(SELECT dcVipID FROM Inserted)
			AND startDate < GETDATE())
	BEGIN
		RAISERROR('该套餐类型已经生效，不能修改', 10, 1)
		ROLLBACK TRANSACTION
		RETURN
	END
END

GO
ALTER TABLE [dbo].[dcVipDetail] ENABLE TRIGGER [Tri_dcVipDetailSave]
GO
/****** Object:  Trigger [dbo].[Tri_Email_SentTest_Log_UPDATE]    Script Date: 2018/9/25 12:40:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create trigger [dbo].[Tri_Email_SentTest_Log_UPDATE]
	ON [dbo].[Email_SentTest_Log]
	AFTER UPDATE
AS
BEGIN
	SET NOCOUNT ON;
	IF UPDATE(Body)
		UPDATE Email_SentTest_Log SET Body = REPLACE(Body, Code, '----') WHERE ID IN(SELECT ID FROM Inserted)
END
GO
ALTER TABLE [dbo].[Email_SentTest_Log] ENABLE TRIGGER [Tri_Email_SentTest_Log_UPDATE]
GO
/****** Object:  Trigger [dbo].[Tri_ExjobApplyDelete]    Script Date: 2018/9/25 12:40:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TRIGGER [dbo].[Tri_ExjobApplyDelete]
   ON [dbo].[exJobApply]
   AFTER DELETE
AS 
BEGIN
	SET NOCOUNT ON;

	IF (SELECT COUNT(*) FROM Deleted) > 50
		RETURN

	DECLARE @cpMainID INT, @ReplyCnt INT, @ReplyRate DECIMAL(9, 3), 
		@AutoReplyConfirm DATETIME, @MemberType INT,
		@AutoReply INT, @AllReply INT
	SELECT TOP 1 @cpMainId = b.cpMainId FROM Deleted a, Job b WHERE a.JobId = b.Id
	SELECT @AutoReplyConfirm = AutoReplyConfirm, @MemberType = MemberType FROM cpMain WHERE Id = @cpMainId 

	SELECT @AutoReply = SUM(CASE WHEN reply = 5 THEN 1 ELSE 0 END), @AllReply = COUNT(*)			
	FROM ExjobApply
	WHERE JobId IN(SELECT Id FROM Job WHERE cpMainId = @cpMainId AND IsDelete = 0)
	AND Reply > 0
	AND ISNULL(CompanyDeleted,0) = 0
	AND Adddate > @AutoReplyConfirm
	--AND AddDate < @EndDate
	
	IF @AllReply = 0
		SET @ReplyRate = 1
	ELSE
		SET @ReplyRate = (@AllReply - @AutoReply) * 1.0 / @AllReply

	UPDATE cpMain SET ReplyRate = @ReplyRate WHERE Id = @cpMainId
	UPDATE cpMainPublish SET ReplyRate = @ReplyRate WHERE Id = @cpMainId 
END

GO
ALTER TABLE [dbo].[exJobApply] ENABLE TRIGGER [Tri_ExjobApplyDelete]
GO
/****** Object:  Trigger [dbo].[Tri_ExJobApplyInsert]    Script Date: 2018/9/25 12:40:16 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE TRIGGER [dbo].[Tri_ExJobApplyInsert]
   ON  [dbo].[exJobApply]
   AFTER INSERT
AS 
BEGIN
	SET NOCOUNT ON;
	DECLARE @COUNT AS INT
	SELECT @COUNT = COUNT(1) FROM Inserted
	IF @COUNT = 1
	BEGIN
		DECLARE @IsPassed AS BIT, @IsFilter AS BIT, @ID AS INT, @JobID AS INT, @cvMainID AS INT, @paMainID AS INT, @Speciality VARCHAR(Max)
		SELECT @ID = ID, @JobID = JobID, @cvMainID = cvMainID FROM Inserted
		--Delete 王蓓
		SELECT @paMainID = paMainID, @Speciality = Speciality FROM cvMain WITH(NOLOCK) WHERE ID = @cvMainId
		IF @Speciality LIKE '%冰毒%' OR @Speciality LIKE '%戚慧丽%'	OR @Speciality LIKE '%58585528%' OR @Speciality LIKE '%王敏昌%'
		BEGIN
			IF EXISTS(SELECT 'x' FROM paMain WITH(NOLOCK) WHERE id = @paMainID AND Name LIKE '王蓓%')
			BEGIN
				DELETE exJobApply WHERE ID = @ID
				RETURN
			END
		END
		----申请职位时的状态，企业能否直接查看？？
		SET @IsPassed = dbo.IsJobApplyPassed(@JobID, @cvMainID)
		SET @IsFilter = dbo.IsJobApplyFilter(@JobID, @cvMainID)

		IF @IsPassed = 1 AND @IsFilter = 1
			UPDATE exJobApply SET IsPassed = 1, IsFilter = 1 WHERE ID = @ID
		ELSE
		BEGIN
			IF @IsPassed = 1
				UPDATE exJobApply SET IsPassed = 1 WHERE ID = @ID
			IF @IsFilter = 1
				UPDATE exJobApply SET IsFilter = 1 WHERE ID = @ID
		END
	END
	--修改推荐职位的申请时间
	UPDATE PaJobCompare 
	SET ApplyDate = GETDATE()
	WHERE CompareJobID IN(
		SELECT JobID
		FROM INSERTED
	)
	AND PaMainID = (
		SELECT TOP 1 PaMainID
		FROM CvMain WITH(NOLOCK)
		WHERE ID IN(
			SELECT CvMainID
			FROM INSERTED
		)
	)

	IF EXISTS(SELECT 'x' FROM Inserted a, BeisenAds b WHERE a.JobId = b.JobId AND b.EndTime > GETDATE() AND b.Status = '广告发布中')
	BEGIN
		INSERT INTO BeisenJobApply(ExJobApplyId, cvMainId, JobId)
		SELECT a.Id, a.cvMainId, a.JobId
		FROM Inserted a, BeisenAds b
		WHERE a.JobId = b.JobId
	END
END



GO
ALTER TABLE [dbo].[exJobApply] ENABLE TRIGGER [Tri_ExJobApplyInsert]
GO
/****** Object:  Trigger [dbo].[Tri_ExjobApplyUpdate]    Script Date: 2018/9/25 12:40:16 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TRIGGER [dbo].[Tri_ExjobApplyUpdate]
   ON [dbo].[exJobApply]
   AFTER UPDATE
AS 
BEGIN
	SET NOCOUNT ON;
	IF UPDATE(Reply)
	BEGIN
		IF (SELECT COUNT(*) FROM Inserted) > 50
			RETURN

		DECLARE @cpMainID INT, @ReplyCnt INT, @ReplyRate DECIMAL(9, 3), 
			@AutoReplyConfirm DATETIME, @MemberType INT,
			@AutoReply INT, @AllReply INT
		SELECT TOP 1 @cpMainId = b.cpMainId FROM Inserted a, Job b WHERE a.JobId = b.Id
		SELECT @AutoReplyConfirm = AutoReplyConfirm, @MemberType = MemberType FROM cpMain WHERE Id = @cpMainId 

		SELECT @AutoReply = SUM(CASE WHEN reply = 5 THEN 1 ELSE 0 END), @AllReply = COUNT(*)			
		FROM ExjobApply
		WHERE JobId IN(SELECT Id FROM Job WHERE cpMainId = @cpMainId AND IsDelete = 0)
		AND Reply > 0
		AND ISNULL(CompanyDeleted,0) = 0
		AND Adddate > @AutoReplyConfirm
		--AND AddDate < @EndDate
		
		IF @AllReply = 0
			SET @ReplyRate = 1
		ELSE
			SET @ReplyRate = (@AllReply - @AutoReply) * 1.0 / @AllReply

		UPDATE cpMain SET ReplyRate = @ReplyRate WHERE Id = @cpMainId
   		UPDATE cpMainPublish SET ReplyRate = @ReplyRate WHERE Id = @cpMainId 
		
		UPDATE ExJobApply
		SET IsFilter = 0
		WHERE Id IN(
			SELECT id 
			FROM Inserted 
			WHERE IsFilter = 1
			AND (Reply = 1 OR Reply = 2)
		)
		
		
	END
END
 
GO
ALTER TABLE [dbo].[exJobApply] ENABLE TRIGGER [Tri_ExjobApplyUpdate]
GO
/****** Object:  Trigger [dbo].[TRI_ExtendLink_DELETE]    Script Date: 2018/9/25 12:40:16 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TRIGGER [dbo].[TRI_ExtendLink_DELETE]
   ON [dbo].[ExtendLink]
   AFTER DELETE
AS 
BEGIN
	SET NOCOUNT ON;

	DELETE FROM ExtendLinkCheckLog WHERE ExtendLinkId IN(SELECT Id FROM Deleted)
	--DELETE FROM ExtendLinkRunLog WHERE cpMainId IN(SELECT cpMainId FROM Deleted)
END

GO
ALTER TABLE [dbo].[ExtendLink] ENABLE TRIGGER [TRI_ExtendLink_DELETE]
GO
/****** Object:  Trigger [dbo].[Tri_Feedback_NoReg_Insert]    Script Date: 2018/9/25 12:40:16 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TRIGGER [dbo].[Tri_Feedback_NoReg_Insert]
   ON [dbo].[Feedback_NoReg]
   AFTER INSERT
AS 
BEGIN
	IF (SELECT COUNT(*) FROM Feedback_NoReg WITH(NOLOCK) 
		WHERE IP IN(seLECT IP FROM INserted)
		AND AddDate > gETDATE()-0.5
		) > 3
	BEGIN
		DELETE FROM Feedback_NoReg WHERE ID =(
			SELECT MIN(ID) FROM Feedback_NoReg WITH(NOLOCK)
			WHERE IP IN(seLECT IP FROM INserted)
			AND AddDate > gETDATE()-0.5)
	END
END

GO
ALTER TABLE [dbo].[Feedback_NoReg] ENABLE TRIGGER [Tri_Feedback_NoReg_Insert]
GO
/****** Object:  Trigger [dbo].[Tri_FnBankDaybook_Insert]    Script Date: 2018/9/25 12:40:16 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--银行日记账插入触发器，Peter，检测实名认证。
CREATE TRIGGER [dbo].[Tri_FnBankDaybook_Insert]
    ON [dbo].[FnBankDaybook]
    AFTER INSERT
AS
BEGIN
    SET NOCOUNT ON
    DECLARE @FnBankDaybookID AS INT, @Debit AS NUMERIC(18, 2), 
		@OppositeCompany AS NVARCHAR(500),@OppositeAccount AS VARCHAR(50),
        @Summary AS NVARCHAR(200),@CpMainID AS INT,@cpCertificationID AS INT,
		@Mobile AS VARCHAR(12)
    
    SELECT @FnBankDaybookID = ID, @Debit = Debit, 
		@OppositeCompany = OppositeCompany, 
		@OppositeAccount = OppositeAccount,
		@Summary = Summary
	FROM Inserted

    IF @Debit BETWEEN 0 AND 1
    BEGIN
		IF @Summary LIKE '会员编号%' AND ISNUMERIC(REPLACE(@Summary, '会员编号', '')) = 1
		BEGIN
			BEGIN TRY
				--SET @CpMainID = ISNULL(CONVERT(INT, REPLACE(@Summary, '会员编号', '')), 0)
				SET @CpMainID = dbo.getnumber(@Summary)
			END TRY
			BEGIN CATCH
				SET @CpMainID = 0
				RETURN
			END CATCH
			
			IF EXISTS(SELECT 'x' FROM cpMain WHERE Id = @cpMainId AND RealName = 1)
				RETURN
			DECLARE @Money VARCHAR(4)
			IF RIGHT(@CpMainID, 2) = '00'
				SET @Money = '0.' + LEFT(@cpMainId, 2)
			ELSE 
				SET @Money = '0.' + RIGHT(@cpMainId, 2)

			IF @Debit = CONVERT(NUMERIC(18, 2), @Money) 
				AND (SELECT TOP 1 Name FROM cpMain WITH(NOLOCK) WHERE ID = @CpMainID) = @OppositeCompany
			BEGIN
				UPDATE CpMain SET RealName = 1 WHERE id = @CpMainID
				
			--短信提示
			INSERT SmsMessageLog(SendMan, ManagerUSerId, paMainId, caMainId, Mobile, MsgType, IsCat, Msg)
			SELECT  0, NULL, NULL, a.ID, a.Mobile, 1, 0,ISNULL(a.Name,'') + '您好，'+b.Name+'在' + c.subsitename + c.EmailSite + '上已通过实名认证'
			FROM caMain a WITH(NOLOCK), cpMain b WITH(NOLOCK), dcSubSite c WITH(NOLOCK)
			WHERE a.cpMainID = b.ID
			AND b.dcSubSiteID = c.ID 
			AND a.Mobile > ''
			AND b.ID = @CpMainID 
			AND a.IsReceiveSms = 1

			INSERT INTO CpRealNameLog(CpMainID, CertificationType, FnBankDaybookID, AddDate)
			VALUES (@CpMainID, 1, @FnBankDaybookID, GETDATE())

			INSERT INTO cpPoint (cpMainID, ChangeID, Point, LastModifyDate)
			VALUES (@cpMainID, 18, 200, GETDATE())
			END   
		END
		ELSE
		BEGIN
			IF LEN(ISNULL(@OppositeCompany,'')) = 0  --没有来源账户名称
			BEGIN
				RETURN
			END
			ELSE  --是打款的信息
			BEGIN
				SELECT @cpCertificationID = ID,@Mobile = Mobile,@CpMainID = cpMainID
				FROM cpCertification WITH(NOLOCK)
				WHERE CompanyName = @OppositeCompany
				AND CerType = 1
				AND CerStatus IS NULL
				AND (@Debit = CONVERT(NUMERIC(18, 2), '0.' + RIGHT(cpMainId, 2)) OR @Debit = CONVERT(NUMERIC(18, 2), '0.' + LEFT(cpMainId, 2)))
				
				IF @CpMainID > 0 --找到了对应打款金额和 公司名称的企业（实名认证）
				BEGIN
					INSERT INTO CpRealNameLog(CpMainID, CertificationType, FnBankDaybookID, AddDate)
					VALUES (@CpMainID, 1, @FnBankDaybookID, GETDATE())
					
					INSERT INTO cpCorporationAccount (cpCertificationID, CertificationType, FnBankDayBookID, AddDate)
					VALUES (@cpCertificationID, 1, @FnBankDaybookID, GETDATE())
					
					INSERT INTO cpPoint (cpMainID, ChangeID, Point, LastModifyDate)
					VALUES (@cpMainID, 18, 200, GETDATE())
					
					UPDATE cpCertification 
					SET CerStatus = 1 
					WHERE ID = @cpCertificationID
					
				END
				ELSE  --尝试去找个人账户认证
				BEGIN
					DECLARE @CerType AS TINYINT
					
					SELECT @cpCertificationID = b.ID,@Mobile = b.Mobile,@CpMainID = b.cpMainID,@CerType = MemberType
					FROM cpPersonalAccount a WITH(NOLOCK)
					LEFT JOIN cpCertification b WITH(NOLOCK) ON b.ID = a.cpCertificationID 
					WHERE a.Name = @OppositeCompany
					AND a.BankNo = RIGHT(@OppositeAccount,6)
					AND b.CerStatus IS NULL
					
					IF @cpCertificationID > 0
					BEGIN
						IF @CerType = 1 --实名认证
						BEGIN
							UPDATE cpPersonalAccount 
							SET CheckResult = 2
							WHERE cpCertificationID = @cpCertificationID
						END
						ELSE
						BEGIN
							UPDATE cpPersonalAccount 
							SET CheckResult = 1,FnBankDaybookID=@FnBankDaybookID,CheckDate=GETDATE()
							WHERE cpCertificationID = @cpCertificationID

							Commit

							UPDATE cpCertification 
							SET CerStatus = 1 
							WHERE ID = @cpCertificationID
						END
					END
				END
			END
		END
    END    
END

GO
ALTER TABLE [dbo].[FnBankDaybook] ENABLE TRIGGER [Tri_FnBankDaybook_Insert]
GO
/****** Object:  Trigger [dbo].[Tri_FnInvoiceUpdate]    Script Date: 2018/9/25 12:40:16 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TRIGGER [dbo].[Tri_FnInvoiceUpdate]
   ON  [dbo].[FnInvoice]
   AFTER UPDATE
AS 
BEGIN
	DECLARE @COUNT AS INT
	SELECT @COUNT = COUNT(1) FROM Inserted
	IF @COUNT = 1
	BEGIN
		IF EXISTS(SELECT 'x' FROM Inserted WHERE orderid = 65526461 )
			RETURN

		IF UPDATE([Status])
		BEGIN
			DECLARE	@OrderStatus TINYINT,
				@OrderID INT,
				@Status TINYINT,
				@ID INT
				
			SELECT @ID = ID, @OrderId = OrderID, @Status = [Status]
			FROM Inserted

			SELECT @OrderStatus = OrderStatus
			FROM caOrder WITH(NOLOCK)
			WHERE ID = @OrderID

			IF @Status = 1
			BEGIN
				IF EXISTS(SELECT 'x' FROM FnInvoice WITH(NOLOCK)
					WHERE OrderId = @OrderID AND @ID <> ID AND Status = 1)
				BEGIN
				    RAISERROR('该订单已经开出发票，不能重复开票', 10, 1)
					ROLLBACK TRANSACTION
					RETURN
				END
				
				--IF @OrderStatus <> 12
			    --BEGIN
					--RAISERROR('未确认发票的订单不能开出发票', 10, 1)
					--ROLLBACK TRANSACTION
					--RETURN
				--END
				--ELSE
					UPDATE caOrder SET OrderStatus = 14 WHERE ID = @OrderID
			END
			ELSE IF @Status = 10 --作废
			BEGIN
				IF @OrderStatus <> 14
				BEGIN
					RAISERROR('没有开票的订单不能作废发票', 10, 1)
					ROLLBACK TRANSACTION
					RETURN
				END
				ELSE
					UPDATE caOrder SET OrderStatus = 12, InvoiceMonth = NULL WHERE ID = @OrderID
			END
            ELSE IF @Status = 11 --退票
			BEGIN
                UPDATE caOrder SET OrderStatus = 12 WHERE ID = @OrderID
                --UPDATE caOrder SET OrderStatus = 12, InvoiceMonth = NULL WHERE ID = @OrderID
                --Richard 2012年5月2日修改
			END
		END
	END
	ELSE
	BEGIN
		IF UPDATE(Money) OR UPDATE(makeoutdate) OR UPDATE(Head)
		BEGIN
			RAISERROR('不能批量修改发票', 10, 1)
			ROLLBACK TRANSACTION
			RETURN
		END
	END
END

GO
ALTER TABLE [dbo].[FnInvoice] ENABLE TRIGGER [Tri_FnInvoiceUpdate]
GO
/****** Object:  Trigger [dbo].[Tri_FnLetterUpdate]    Script Date: 2018/9/25 12:40:16 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE TRIGGER [dbo].[Tri_FnLetterUpdate]
   ON  [dbo].[FnLetter]
   AFTER UPDATE,INSERT
AS 
BEGIN

	--SET NOCOUNT ON;
	DECLARE @COUNT AS INT
	SELECT @COUNT = COUNT(1) FROM Inserted
	IF @COUNT = 1
	BEGIN
		IF UPDATE([Status])
		BEGIN
			DECLARE @FnInvoiceID AS INT,
				@OrderId AS INT,
				@Status AS INT,
				@ID AS INT,
				@OrderStatus AS TINYINT,
				@WtgOrderID INT

			SELECT @FnInvoiceID = FnInvoiceID, @Status = [Status]
			FROM Inserted
			
			SELECT @OrderId = OrderID,@WtgOrderID = WtgOrderID FROM FnInvoice WITH(NOLOCK) WHERE ID = @FnInvoiceID
			IF @OrderId>0
			BEGIN
				SELECT @OrderStatus = OrderStatus FROM caOrder WITH(NOLOCK) WHERE ID = @OrderID

				IF @Status = 1
				BEGIN
					IF @OrderStatus <> 14
					BEGIN
						RAISERROR('未开的发票不能邮寄', 10, 1)
						ROLLBACK TRANSACTION
						RETURN
					END
					ELSE
						UPDATE caOrder SET OrderStatus = 16 WHERE ID = @OrderID
				END

				IF @Status = 2
				BEGIN
					IF @OrderStatus <> 16
					BEGIN
						RAISERROR('未邮寄的发票不能确认收到', 10, 1)
						ROLLBACK TRANSACTION
						RETURN
					END
					ELSE
						UPDATE caOrder SET OrderStatus = 18 WHERE ID = @OrderID
				END

				IF @Status = 3 OR @Status = 4
				BEGIN
					IF @OrderStatus <> 16
					BEGIN
						RAISERROR('未邮寄的挂号信不能退件或作废', 10, 1)
						ROLLBACK TRANSACTION
						RETURN
					END
					ELSE
						UPDATE caOrder SET OrderStatus = 14 WHERE ID = @OrderID
				END
			END
			ELSE IF @WtgOrderID > 0 
			BEGIN
				SELECT @OrderStatus = OrderStatus FROM wutongguodb..cpOrder WITH(NOLOCK) WHERE ID = @WtgOrderID

				IF @Status = 1
				BEGIN
					IF @OrderStatus = 14
						UPDATE  wutongguodb..cpOrder SET OrderStatus = 16 WHERE ID = @WtgOrderID
				END

				IF @Status = 2
				BEGIN
					IF @OrderStatus = 16
						UPDATE  wutongguodb..cpOrder SET OrderStatus = 18 WHERE ID = @WtgOrderID
				END

				IF @Status = 3 OR @Status = 4
				BEGIN
					IF @OrderStatus = 16	
						UPDATE  wutongguodb..cpOrder SET OrderStatus = 14 WHERE ID = @WtgOrderID
				END
			END
		END
	END
END

GO
ALTER TABLE [dbo].[FnLetter] ENABLE TRIGGER [Tri_FnLetterUpdate]
GO
/****** Object:  Trigger [dbo].[Tri_FtpFileUpdate_Insert]    Script Date: 2018/9/25 12:40:16 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TRIGGER [dbo].[Tri_FtpFileUpdate_Insert]
   ON [dbo].[ftpFileUpDate]
   AFTER INSERT
AS 
BEGIN
	SET NOCOUNT ON;
	BEGIN TRY
		INSERT INTO LogDb..ftpFileUpDateLog(FileDir, Oper, AddDate, isFolder)
		SELECT FileDir, Oper, AddDate, isFolder FROM Inserted
	END TRY
	BEGIN CATCH
	END CATCH
END

GO
ALTER TABLE [dbo].[ftpFileUpDate] ENABLE TRIGGER [Tri_FtpFileUpdate_Insert]
GO
/****** Object:  Trigger [dbo].[Tri_IvrList_Insert]    Script Date: 2018/9/25 12:40:16 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE TRIGGER [dbo].[Tri_IvrList_Insert]
   ON [dbo].[IvrList]
   AFTER INSERT
AS 
BEGIN
	SET NOCOUNT ON;

	DECLARE @PrevId INT, @Id INT, @CalledNo varchar(50), @CallType varchar(10), @Ring datetime, @Endtime datetime,
		@CallState varchar(10), @CallsheetId varchar(100), @Exten varchar(10), @FileServer VARCHAR(50)
	
	SELECT @Id = Id, @CalledNo = CalledNo, @CallType = CallType, @Ring = Ring,
		@Endtime = EndTime, @CallState = CallState, @CallsheetId = CallsheetId,
		@Exten = Exten, @FileServer = FileServer
	FROM Inserted

	IF @FileServer = 'http://192.168.0.200:8990'
		UPDATE IvrList SET FileServer = 'http://58.59.17.86:8990' WHERE ID = @Id

	SELECT @PrevId = Id 
	FROM IvrList with(index(ix_ivrlist_callsheetid))
	WHERE Id < @ID 
	AND CallsheetId = @CallsheetId 
	AND @CalledNo = CalledNo
	AND @CallType = CallType
	AND @Ring = Ring
	AND @Exten = Exten
	AND ISNULL(@CallState, '') = ISNULL(CallState, '')

	IF @PrevID > 0
		DELETE IvrList WHERE Id = @PrevId

	DECLARE @t AS TABLE(ID INT,
		CallNo VARCHAR(50),
		CalledNo VARCHAR(50),
		CallType VARCHAR(10),
		Telephone VARCHAR(50),
		Telephone2 VARCHAR(50),
		Exten VARCHAR(10),
		caMainId INT,
		cpAccountID INT,
		cpLinkManID INT,
		IsWtg INT
	)

	INSERT INTO @t(ID, CallNo, CalledNo, CallType, Exten,cpAccountID,cpLinkManID, IsWtg)
	SELECT ID, CallNo, CalledNo, CallType, Exten, 0,0,0  FROM Inserted
	IF (SELECT COUNT(*) FROM @t) = 0
		RETURN

	UPDATE a SET IsWtg = 1 FROM @t a WHERE Exten IN (SELECT LTRIM(STR(ID)) FROM Manageruser WITH(NOLOCK) WHERE DeptID IN (SELECT ID FROM Dept WITH(NOLOCK) WHERE Superior = 43)) 

	UPDATE a
	SET a.TelePhone = a.CallNo
	FROM @t a

	UPDATE a
	SET a.TelePhone = a.CalledNo
	FROM @t a
	WHERE a.CallType = 'dialout'
	
	UPDATE a
	SET a.TelePhone2 = LEFT(TelePhone, 3) + '-' + RIGHT(TelePhone, LEN(TelePhone) - 3)
	FROM @t a
	WHERE LEFT(TelePhone, 2) IN('01', '02')
	AND TelePhone NOT LIKE '1%'

	UPDATE a
	SET a.TelePhone2 = LEFT(TelePhone, 4) + '-' + RIGHT(TelePhone, LEN(TelePhone) - 4)
	FROM @t a
	WHERE TelePhone2 IS NULL
	AND TelePhone NOT LIKE '1%'

	--#############################判断是否是梧桐果校招平台的联系方式
	UPDATE a
	SET a.cpAccountID = 
		(
			SELECT TOP 1 cpAccount.Id FROM Wutongguodb..cpAccount  WITH(NOLOCK) ,Wutongguodb..cpMain WITH(NOLOCK)
			WHERE cpAccount.CpMainID = cpMain.ID AND cpAccount.Mobile = a.TelePhone AND cpMain.IsDelete=0
			AND CpMain.ConsultantId = a.Exten			
			ORDER BY BsViewDate Desc, cpAccount.Id DESC
		)
	FROM @t a
	WHERE a.TelePhone LIKE '1%'
	AND IsWtg = 1

	UPDATE a
	SET a.cpAccountID = 
		(
			SELECT TOP 1 cpAccount.Id FROM Wutongguodb..cpAccount  WITH(NOLOCK) ,Wutongguodb..cpMain WITH(NOLOCK)
			WHERE cpAccount.CpMainID = cpMain.ID AND cpAccount.Mobile = a.TelePhone 			 AND cpMain.IsDelete=0
			ORDER BY BsViewDate Desc, cpAccount.Id DESC
		)
	FROM @t a
	WHERE a.TelePhone LIKE '1%'
	AND ISNULL(cpAccountID,0) = 0
	AND IsWtg = 1

	UPDATE a
	SET a.CpLinkManID = 
		(
			SELECT TOP 1 CpLinkMan.Id FROM Wutongguodb..CpLinkMan WITH(NOLOCK) ,Wutongguodb..cpMain WITH(NOLOCK)
			WHERE CpLinkMan.CpMainID = CpMain.ID AND CpLinkMan.Mobile = a.TelePhone  AND cpMain.IsDelete=0
			AND ConsultantId = a.Exten
			ORDER BY BsViewDate Desc, CpLinkMan.Id DESC
		)
	FROM @t a
	WHERE a.TelePhone LIKE '1%'	
	AND IsWtg = 1

	UPDATE a
	SET a.CpLinkManID = 
		(
			SELECT TOP 1 CpLinkMan.Id FROM Wutongguodb..CpLinkMan WITH(NOLOCK) ,Wutongguodb..cpMain WITH(NOLOCK)
			WHERE CpLinkMan.CpMainID = CpMain.ID AND CpLinkMan.Mobile = a.TelePhone 	 AND cpMain.IsDelete=0	
			ORDER BY BsViewDate Desc, CpLinkMan.Id DESC
		)
	FROM @t a
	WHERE a.TelePhone LIKE '1%'	
	AND ISNULL(CpLinkManID ,0)= 0
	AND IsWtg = 1

	UPDATE a
	SET a.cpAccountID = 
		(
			SELECT TOP 1 cpAccount.Id  FROM Wutongguodb..cpAccount WITH(NOLOCK INDEX(IX_CpAccount_TelePhone)) ,Wutongguodb..cpMain WITH(NOLOCK)
			WHERE cpAccount.CpMainID = CpMain.ID AND cpAccount.TelePhone LIKE a.TelePhone + '%' AND cpMain.IsDelete=0
				AND ConsultantId = a.Exten
			ORDER BY BsViewDate Desc, cpAccount.Id DESC
		)
	FROM @t a
	WHERE ISNULL(cpAccountID,0) = 0
	AND IsWtg = 1

	UPDATE a
	SET a.cpAccountID = 
		(
			SELECT TOP 1 cpAccount.Id FROM Wutongguodb..cpAccount WITH(NOLOCK INDEX(IX_CpAccount_TelePhone)) ,Wutongguodb..cpMain WITH(NOLOCK)
			WHERE cpAccount.CpMainID = CpMain.ID AND cpAccount.TelePhone LIKE a.TelePhone + '%'			 AND cpMain.IsDelete=0
			ORDER BY BsViewDate Desc, cpAccount.Id DESC
		)
	FROM @t a
	WHERE ISNULL(cpAccountID,0) = 0
	AND IsWtg = 1

	UPDATE a
	SET a.CpLinkManID = 
		(
			SELECT TOP 1 CpLinkMan.Id FROM Wutongguodb..CpLinkMan WITH(NOLOCK INDEX(IX_CpLinkMan_Tel)),Wutongguodb..cpMain WITH(NOLOCK)  
			WHERE CpLinkMan.CpMainID = CpMain.ID AND CpLinkMan.Tel LIKE a.TelePhone + '%'  AND cpMain.IsDelete=0
			AND  ConsultantId = a.Exten
			ORDER BY BsViewDate Desc, CpLinkMan.Id DESC
		)
	FROM @t a
	WHERE ISNULL(CpLinkManID ,0) = 0
	AND IsWtg = 1

	UPDATE a
	SET a.CpLinkManID = 
		(
			SELECT TOP 1 CpLinkMan.Id FROM Wutongguodb..CpLinkMan WITH(NOLOCK INDEX(IX_CpLinkMan_Tel)),Wutongguodb..cpMain WITH(NOLOCK)  
			WHERE CpLinkMan.CpMainID = CpMain.ID AND CpLinkMan.Tel LIKE a.TelePhone + '%' 			 AND cpMain.IsDelete=0
			ORDER BY BsViewDate Desc, CpLinkMan.Id DESC
		)
	FROM @t a
	WHERE ISNULL(CpLinkManID ,0) = 0
	AND IsWtg = 1

	UPDATE a
	SET a.cpAccountID = 
		(
			SELECT TOP 1 cpAccount.Id FROM Wutongguodb..cpAccount WITH(NOLOCK INDEX(IX_CpAccount_TelePhone)) , Wutongguodb..cpMain WITH(NOLOCK)
			WHERE cpAccount.CpMainID = cpMain.ID AND cpAccount.TelePhone LIKE a.TelePhone2 + '%'  AND cpMain.IsDelete=0
			AND ConsultantId = a.Exten
			ORDER BY BsViewDate Desc, cpAccount.Id DESC
		)
	FROM @t a
	WHERE ISNULL(cpAccountID,0) = 0
	AND IsWtg = 1

	UPDATE a
	SET a.cpAccountID = 
		(
			SELECT TOP 1 cpAccount.Id FROM Wutongguodb..cpAccount WITH(NOLOCK INDEX(IX_CpAccount_TelePhone)) , Wutongguodb..cpMain WITH(NOLOCK)
			WHERE cpAccount.CpMainID = cpMain.ID AND cpAccount.TelePhone LIKE a.TelePhone2 + '%'  AND cpMain.IsDelete=0
			AND ConsultantId = a.Exten
			ORDER BY BsViewDate Desc, cpAccount.Id DESC
		)
	FROM @t a
	WHERE ISNULL(cpAccountID,0) = 0
	AND IsWtg = 1

	UPDATE a
	SET a.CpLinkManID = 
		(
			SELECT TOP 1 CpLinkMan.Id FROM Wutongguodb..CpLinkMan WITH(NOLOCK INDEX(IX_CpLinkMan_Tel)) ,Wutongguodb..CpMain  WITH(NOLOCK) 
			WHERE CpLinkMan.CpMainID = cpMain.ID AND CpLinkMan.Tel LIKE a.TelePhone2 + '%'  AND cpMain.IsDelete=0
			AND ConsultantId = a.Exten
			ORDER BY BsViewDate Desc, CpLinkMan.Id DESC
		)
	FROM @t a
	WHERE ISNULL(CpLinkManID ,0) = 0
	AND IsWtg = 1

	UPDATE a
	SET a.CpLinkManID = 
		(
			SELECT TOP 1 CpLinkMan.Id FROM Wutongguodb..CpLinkMan WITH(NOLOCK INDEX(IX_CpLinkMan_Tel)) ,Wutongguodb..CpMain  WITH(NOLOCK) 
			WHERE CpLinkMan.CpMainID = cpMain.ID AND CpLinkMan.Tel LIKE a.TelePhone2 + '%' 		 AND cpMain.IsDelete=0
			ORDER BY BsViewDate Desc, CpLinkMan.Id DESC
		)
	FROM @t a
	WHERE ISNULL(CpLinkManID ,0) = 0
	AND IsWtg = 1


	UPDATE a
	SET a.cpAccountID = b.cpAccountID
	FROM IvrList a, @t b
	WHERE a.Id = b.Id
	AND IsWtg = 1

	UPDATE a
	SET a.CpLinkManID = b.CpLinkManID
	FROM IvrList a, @t b
	WHERE a.Id = b.Id
	AND IsWtg = 1

	DECLARE @CpContactLogID INT
	SET @CpContactLogID = 0
	IF (SELECT COUNT(*) FROM @t)=1 
	BEGIN		
		SELECT TOP 1 @CpContactLogID = a.ID 
		FROM Wutongguodb..CpContactLog a WITH(NOLOCK),@t b
		WHERE (a.CpAccountID = b.CpAccountID OR a.CpLinkManID =b.CpLinkManID)
		AND a.IvrListID IS NULL
		AND a.AddDate>DATEADD(MINUTE,-10,GETDATE())
		AND b.IsWtg=1 and b.CallType = 'dialout'
		IF @CpContactLogID>0
		BEGIN
			UPDATE Wutongguodb..CpContactLog SET IvrListID = (SELECT ID FROM @t) WHERE ID = @CpContactLogID
		END			
	END
	IF @CpContactLogID=0
	BEGIN
		INSERT INTO Wutongguodb..CpContactLog(CpMainID,IvrListID,CpLinkManID,CpAccountID,ContentText,ManageruserID,Name,Tel)
		SELECT
			   ISNULL(b.CpMainID,c.CpMainID)
			   ,a.id
			   ,CpLinkManID
			   ,CpAccountID
			   ,''           
			   ,Exten,ISNULL(b.Name,c.Name),a.TelePhone
			FROM @t a LEFT JOIN Wutongguodb..CpLinkMan b WITH(NOLOCK) ON a.CpLinkManID = b.ID
				LEFT JOIN Wutongguodb..CpAccount c WITH(NOLOCK) ON a.CpAccountID = c.ID
			WHERE a.IsWtg=1 AND (CpLinkManID >0 OR CpAccountID>0) and a.CallType = 'dialout'
	END
END

GO
ALTER TABLE [dbo].[IvrList] ENABLE TRIGGER [Tri_IvrList_Insert]
GO
/****** Object:  Trigger [dbo].[Tri_Job_Delete]    Script Date: 2018/9/25 12:40:16 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE TRIGGER [dbo].[Tri_Job_Delete]
   ON [dbo].[Job]
   AFTER DELETE
AS 
BEGIN
	SET NOCOUNT ON;
    DELETE JobPublish WHERE ID IN(SELECT ID FROM Deleted)
	DELETE ExJobApply WHERE JobID IN(SELECT ID FROM Deleted)
	UPDATE CaCvApplyDeleted SET JobDeleted = 1 WHERE JobId IN(SELECT Id FROM Deleted)
	
	DELETE FROM jobrefreshLog 
	WHERE refreshType =0 AND runDateTime IS NULL 
	AND jobid IN (SELECT ID FROM Deleted)--harry 职位刷新数2017-11-8
	
	UPDATE jobrefreshSet
	SET runState =0 
	WHERE runState =1
	AND jobid IN (SELECT ID FROM Deleted)--harry 职位刷新数2017-11-8
			
	IF NOT EXISTS(SELECT 'x' FROM JobDeleted WITH(NOLOCK) WHERE JobId IN(SELECT ID FROM Deleted))
		INSERT INTO JobDeleted(JobID,caMainID,cpMainID,JobName,HasIssued,IssueDate,IssueEnd,DeleteDate, Secondid, ProvinceId)
		SELECT a.ID, a.caMainID, a.cpMainID, a.Name, CASE a.IssueEnd WHEN NULL THEN 0 ELSE 1 END,
			a.IssueDate, a.IssueEnd, GETDATE(), a.SecondId, b.dcProvinceID
		FROM Deleted a, cpMain b WITH(NOLOCK)
		WHERE a.cpMainId = b.Id
		AND a.Id NOT IN(SELECT JobId FROM JobDeleted WITH(NOLOCK))
END


GO
ALTER TABLE [dbo].[Job] ENABLE TRIGGER [Tri_Job_Delete]
GO
/****** Object:  Trigger [dbo].[Tri_Job_DeleteInsteadOf]    Script Date: 2018/9/25 12:40:16 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE TRIGGER [dbo].[Tri_Job_DeleteInsteadOf]
   ON [dbo].[Job]
   INSTEAD OF DELETE
AS 
BEGIN
	SET NOCOUNT ON;
	
	DELETE FROM jobrefreshLog 
	WHERE refreshType =0 AND runDateTime IS NULL 
	AND jobid IN (SELECT ID FROM Deleted)--harry 职位刷新数2017-11-8
	
	UPDATE jobrefreshSet
	SET runState =0 
	WHERE runState =1
	AND jobid IN (SELECT ID FROM Deleted)--harry 职位刷新数2017-11-8
	
	--职位删除后将部分数据保存到jobIssuedDeleted
	DECLARE @JobID INT	
	SELECT @JobID = ID FROM Deleted WHERE IssueEnd IS NOT NULL 
	IF @JobID IS NOT NULL
	BEGIN
		--将职位的发布效果的相关数据插入jobReportData
		DECLARE @yesterday VARCHAR(10)
		SET @yesterday = CONVERT(VARCHAR(10),GETDATE()-1,120)
		INSERT INTO Reportdb..jobReportData( JobID,CountDate,applyCOUNT,viewCOUNT,interview,interviewreply,interviewresult)
		SELECT @JobID ,dbo.DateToReportDay(GETDATE()),
			(SELECT COUNT(1) FROM exjobapply WITH(NOLOCK) WHERE  JobID=@JobID AND adddate >@yesterday AND adddate<@yesterday+' 23:59'  ),
			(SELECT COUNT(1) FROM pajobviewlog WITH(NOLOCK) WHERE  JobID=@JobID AND adddate >@yesterday AND adddate<@yesterday+' 23:59' ),
			(SELECT COUNT(1) FROM exinterview WITH(NOLOCK) WHERE  JobID=@JobID AND adddate >@yesterday AND adddate<@yesterday+' 23:59' ),
			(SELECT COUNT(1) FROM exinterview WITH(NOLOCK) WHERE  JobID=@JobID AND replydate is not null AND adddate >@yesterday AND adddate<@yesterday+' 23:59' ),
			(SELECT COUNT(1) FROM exinterview WITH(NOLOCK) WHERE  JobID=@JobID AND replydate is not null AND result=1 AND adddate >@yesterday AND adddate<@yesterday+' 23:59')
		DELETE FROM ReportDB..JobReportData WHERE applyCount=0 AND viewCount=0 AND interview=0 AND interviewreply=0 AND interviewresult=0 AND JobID=@JobID 
		
		--简历分析数据
		IF(EXISTS(SELECT 'x' FROM exJobapply x WITH(NOLOCK) WHERE x.JobID=@JobID  AND x.AddDate >@yesterday AND x.AddDate<@yesterday+' 23:59'))
		BEGIN
			INSERT INTO Reportdb..jobReportDetailData	(JobId,CountDate,WorkYears1,WorkYears2,WorkYears3,WorkYears4,WorkYears5,Age1,Age2,Age3,Age4,Age5,Age6,Degree1,Degree2,Degree3,Degree4,Degree5,Degree6,Degree7,Degree8,Degree9,Male,Female,Salary1,Salary2,Salary3,Salary4,Salary5,Salary6,Salary7,Salary8)
			SELECT @JobID ,dbo.DateToReportDay(GETDATE()),
				WorkYears1 = (SELECT COUNT(1) FROM exJobapply x WITH(NOLOCK),cvMain y WITH(NOLOCK) WHERE x.JobID=@JobID AND (RelatedWorkYears=0 OR EXISTS(SELECT 'x' FROM paMain(NOLOCK) WHERE Name IS NOT NULL AND Mobile IS NULL AND Attachment IS NOT NULL AND ID = y.PaMainID )) AND x.AddDate >@yesterday AND x.AddDate<@yesterday+' 23:59' AND x.cvMainID = y.id) ,
				WorkYears2 = (SELECT COUNT(1) FROM exJobapply x WITH(NOLOCK),cvMain y WITH(NOLOCK) WHERE x.JobID=@JobID AND RelatedWorkYears>=1 AND RelatedWorkYears<=2  AND x.AddDate >@yesterday AND x.AddDate<@yesterday+' 23:59' AND x.cvMainID = y.id) ,
				WorkYears3 = (SELECT COUNT(1) FROM exJobapply x WITH(NOLOCK),cvMain y WITH(NOLOCK) WHERE x.JobID=@JobID AND RelatedWorkYears>=3 AND RelatedWorkYears<=5  AND x.AddDate >@yesterday AND x.AddDate<@yesterday+' 23:59' AND x.cvMainID = y.id) ,
				WorkYears4 = (SELECT COUNT(1) FROM exJobapply x WITH(NOLOCK),cvMain y WITH(NOLOCK) WHERE x.JobID=@JobID AND RelatedWorkYears>=6 AND RelatedWorkYears<=10  AND x.AddDate >@yesterday AND x.AddDate<@yesterday+' 23:59' AND x.cvMainID = y.id) ,
				WorkYears5 = (SELECT COUNT(1) FROM exJobapply x WITH(NOLOCK),cvMain y WITH(NOLOCK) WHERE x.JobID=@JobID AND RelatedWorkYears>10  AND x.AddDate >@yesterday AND x.AddDate<@yesterday+' 23:59' AND x.cvMainID = y.id) ,
				Age1 = (SELECT COUNT(1) FROM exJobapply x WITH(NOLOCK),cvMain y WITH(NOLOCK), paMain z WITH(NOLOCK) WHERE x.JobID=@JobID AND (dbo.birthtoage(z.birthday)<=22  OR EXISTS(SELECT 'x' FROM paMain(NOLOCK) WHERE Name IS NOT NULL AND Mobile IS NULL AND Attachment IS NOT NULL AND ID = y.PaMainID )) AND x.AddDate >@yesterday AND x.AddDate<@yesterday+' 23:59' AND x.cvMainID = y.id AND y.pamainid = z.id) ,
				Age2 = (SELECT COUNT(1) FROM exJobapply x WITH(NOLOCK),cvMain y WITH(NOLOCK), paMain z WITH(NOLOCK) WHERE x.JobID=@JobID AND dbo.birthtoage(z.birthday)>=23 AND dbo.birthtoage(z.birthday)<=24  AND x.AddDate >@yesterday AND x.AddDate<@yesterday+' 23:59' AND x.cvMainID = y.id AND y.pamainid = z.id) ,
				Age3 = (SELECT COUNT(1) FROM exJobapply x WITH(NOLOCK),cvMain y WITH(NOLOCK), paMain z WITH(NOLOCK) WHERE x.JobID=@JobID AND dbo.birthtoage(z.birthday)>=25 AND dbo.birthtoage(z.birthday)<=26  AND x.AddDate >@yesterday AND x.AddDate<@yesterday+' 23:59' AND x.cvMainID = y.id AND y.pamainid = z.id) ,
				Age4 = (SELECT COUNT(1) FROM exJobapply x WITH(NOLOCK),cvMain y WITH(NOLOCK), paMain z WITH(NOLOCK) WHERE x.JobID=@JobID AND dbo.birthtoage(z.birthday)>=27 AND dbo.birthtoage(z.birthday)<=29  AND x.AddDate >@yesterday AND x.AddDate<@yesterday+' 23:59' AND x.cvMainID = y.id AND y.pamainid = z.id) ,
				Age5 = (SELECT COUNT(1) FROM exJobapply x WITH(NOLOCK),cvMain y WITH(NOLOCK), paMain z WITH(NOLOCK) WHERE x.JobID=@JobID AND dbo.birthtoage(z.birthday)>10 AND dbo.birthtoage(z.birthday)<=29 AND x.AddDate >@yesterday AND x.AddDate<@yesterday+' 23:59' AND x.cvMainID = y.id AND y.pamainid = z.id) ,
				Age6 = (SELECT COUNT(1) FROM exJobapply x WITH(NOLOCK),cvMain y WITH(NOLOCK), paMain z WITH(NOLOCK) WHERE x.JobID=@JobID AND dbo.birthtoage(z.birthday)>35  AND x.AddDate >@yesterday AND x.AddDate<@yesterday+' 23:59' AND x.cvMainID = y.id AND y.pamainid = z.id) ,
				Degree1 = (SELECT COUNT(1) FROM exJobapply x WITH(NOLOCK),cvMain y WITH(NOLOCK) WHERE x.JobID=@JobID AND Degree=1 AND x.AddDate >@yesterday AND x.AddDate<@yesterday+' 23:59' AND x.cvMainID = y.id) , 
				Degree2 = (SELECT COUNT(1) FROM exJobapply x WITH(NOLOCK),cvMain y WITH(NOLOCK) WHERE x.JobID=@JobID AND Degree=2 AND x.AddDate >@yesterday AND x.AddDate<@yesterday+' 23:59' AND x.cvMainID = y.id) ,
				Degree3 = (SELECT COUNT(1) FROM exJobapply x WITH(NOLOCK),cvMain y WITH(NOLOCK) WHERE x.JobID=@JobID AND Degree=3 AND x.AddDate >@yesterday AND x.AddDate<@yesterday+' 23:59' AND x.cvMainID = y.id) ,
				Degree4 = (SELECT COUNT(1) FROM exJobapply x WITH(NOLOCK),cvMain y WITH(NOLOCK) WHERE x.JobID=@JobID AND Degree=4 AND x.AddDate >@yesterday AND x.AddDate<@yesterday+' 23:59' AND x.cvMainID = y.id) ,
				Degree5 = (SELECT COUNT(1) FROM exJobapply x WITH(NOLOCK),cvMain y WITH(NOLOCK) WHERE x.JobID=@JobID AND Degree=5 AND x.AddDate >@yesterday AND x.AddDate<@yesterday+' 23:59' AND x.cvMainID = y.id) ,
				Degree6 = (SELECT COUNT(1) FROM exJobapply x WITH(NOLOCK),cvMain y WITH(NOLOCK) WHERE x.JobID=@JobID AND Degree=6 AND x.AddDate >@yesterday AND x.AddDate<@yesterday+' 23:59' AND x.cvMainID = y.id) ,
				Degree7 = (SELECT COUNT(1) FROM exJobapply x WITH(NOLOCK),cvMain y WITH(NOLOCK) WHERE x.JobID=@JobID AND Degree=7 AND x.AddDate >@yesterday AND x.AddDate<@yesterday+' 23:59' AND x.cvMainID = y.id) ,
				Degree8 = (SELECT COUNT(1) FROM exJobapply x WITH(NOLOCK),cvMain y WITH(NOLOCK) WHERE x.JobID=@JobID AND Degree=8 AND x.AddDate >@yesterday AND x.AddDate<@yesterday+' 23:59' AND x.cvMainID = y.id) ,
				Degree9 = (SELECT COUNT(1) FROM exJobapply x WITH(NOLOCK),cvMain y WITH(NOLOCK) WHERE x.JobID=@JobID AND (Degree=0 OR Degree IS NULL OR EXISTS(SELECT 'x' FROM paMain(NOLOCK) WHERE Name IS NOT NULL AND Mobile IS NULL AND Attachment IS NOT NULL AND ID = y.PaMainID )) AND x.AddDate >@yesterday AND x.AddDate<@yesterday+' 23:59' AND x.cvMainID = y.id) ,
				Male = (SELECT COUNT(1) FROM exJobapply x WITH(NOLOCK),cvMain y WITH(NOLOCK), paMain z WITH(NOLOCK) WHERE x.JobID=@JobID AND z.Gender=0 AND x.AddDate >@yesterday AND x.AddDate<@yesterday+' 23:59' AND x.cvMainID = y.id AND y.pamainid = z.id),
				Female = (SELECT COUNT(1) FROM exJobapply x WITH(NOLOCK),cvMain y WITH(NOLOCK), paMain z WITH(NOLOCK) WHERE x.JobID=@JobID AND z.Gender=1 AND x.AddDate >@yesterday AND x.AddDate<@yesterday+' 23:59' AND x.cvMainID = y.id AND y.pamainid = z.id),
				Salary1 = (SELECT COUNT(1) FROM exJobapply x WITH(NOLOCK),cvMain y WITH(NOLOCK) WHERE x.JobID=@JobID AND dcSalaryID=2 AND x.AddDate >@yesterday AND x.AddDate<@yesterday+' 23:59' AND x.cvMainID = y.id) , 
				Salary2 = (SELECT COUNT(1) FROM exJobapply x WITH(NOLOCK),cvMain y WITH(NOLOCK) WHERE x.JobID=@JobID AND dcSalaryID=3 AND x.AddDate >@yesterday AND x.AddDate<@yesterday+' 23:59' AND x.cvMainID = y.id) , 
				Salary3 = (SELECT COUNT(1) FROM exJobapply x WITH(NOLOCK),cvMain y WITH(NOLOCK) WHERE x.JobID=@JobID AND dcSalaryID=4 AND x.AddDate >@yesterday AND x.AddDate<@yesterday+' 23:59' AND x.cvMainID = y.id) ,
				Salary4 = (SELECT COUNT(1) FROM exJobapply x WITH(NOLOCK),cvMain y WITH(NOLOCK) WHERE x.JobID=@JobID AND dcSalaryID=5 AND x.AddDate >@yesterday AND x.AddDate<@yesterday+' 23:59' AND x.cvMainID = y.id) ,
				Salary5 = (SELECT COUNT(1) FROM exJobapply x WITH(NOLOCK),cvMain y WITH(NOLOCK) WHERE x.JobID=@JobID AND dcSalaryID=6 AND x.AddDate >@yesterday AND x.AddDate<@yesterday+' 23:59' AND x.cvMainID = y.id) ,
				Salary6 = (SELECT COUNT(1) FROM exJobapply x WITH(NOLOCK),cvMain y WITH(NOLOCK) WHERE x.JobID=@JobID AND dcSalaryID=7 AND x.AddDate >@yesterday AND x.AddDate<@yesterday+' 23:59' AND x.cvMainID = y.id) ,
				Salary7 = (SELECT COUNT(1) FROM exJobapply x WITH(NOLOCK),cvMain y WITH(NOLOCK) WHERE x.JobID=@JobID AND dcSalaryID>=8 AND x.AddDate >@yesterday AND x.AddDate<@yesterday+' 23:59' AND x.cvMainID = y.id) ,
				Salary8 = (SELECT COUNT(1) FROM exJobapply x WITH(NOLOCK),cvMain y WITH(NOLOCK) WHERE x.JobID=@JobID AND (dcSalaryID=0 OR dcSalaryID IS NULL OR EXISTS(SELECT 'x' FROM paMain(NOLOCK) WHERE Name IS NOT NULL AND Mobile IS NULL AND Attachment IS NOT NULL AND ID = y.PaMainID )) AND x.AddDate >@yesterday AND x.AddDate<@yesterday+' 23:59' AND x.cvMainID = y.id) 
		END
		DELETE FROM Job WHERE id IN(SELECT id FROM deleted) 
	END
END


GO
ALTER TABLE [dbo].[Job] ENABLE TRIGGER [Tri_Job_DeleteInsteadOf]
GO
/****** Object:  Trigger [dbo].[Tri_JobInsert]    Script Date: 2018/9/25 12:40:16 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TRIGGER [dbo].[Tri_JobInsert]
   ON [dbo].[Job]
   AFTER INSERT
AS 
BEGIN
	SET NOCOUNT ON;
	DECLARE @JobID AS INT, @Count AS INT, @SecondId VARCHAR(10), @cpMainId INT, @Name NVARCHAR(50), @dcRegionId VARCHAR(6)
	SELECT @Count = COUNT(1) FROM Inserted
	IF @Count = 1
	BEGIN
		SELECT @JobID = ID, @Name = Name, @cpMainId = cpMainId, @dcRegionId = dcRegionId FROM Inserted
		SET @SecondId = LEFT(REPLACE(NEWID(), '-', ''), 12)
		WHILE EXISTS(SELECT 'x' FROM Job WITH(NOLOCK) WHERE SecondId = @SecondId)
			SET @SecondId = LEFT(REPLACE(NEWID(), '-', ''), 12)

		UPDATE Job SET SecondId = @SecondId WHERE Id = @JobID

		--Can Not Name Repeat
		IF @cpMainId <> 10576676
		BEGIN
			IF EXISTS(SELECT 'x' FROM Job WITH(NOLOCK) WHERE Name = @Name
				AND cpMainId = @cpMainId
				AND Id < @jobId
				AND IsDelete = 0
				AND dcRegionId = @dcRegionId)
			BEGIN
				RAISERROR('Job''s name has repeated!', 10, 1)
				ROLLBACK TRANSACTION
				RETURN
			END
		END
	END
END

GO
ALTER TABLE [dbo].[Job] ENABLE TRIGGER [Tri_JobInsert]
GO
/****** Object:  Trigger [dbo].[Tri_JobSave]    Script Date: 2018/9/25 12:40:16 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--20180921 sunshine 添加  修改职位名称的同时更新职位刷新记录里边的职位名称
CREATE TRIGGER [dbo].[Tri_JobSave]
   ON [dbo].[Job]
   AFTER INSERT, UPDATE
AS
BEGIN
	SET NOCOUNT ON;
	IF UPDATE(ViewNumber)
		RETURN

	DECLARE @Count AS INT, @cpMainID AS INT, @caMainID AS INT, @MaxJobNumber AS INT, @Valid AS BIT,
		@IssueEndOld AS SMALLDATETIME, @IssueEnd AS SMALLDATETIME, @IssueDate AS SMALLDATETIME,
		@IsDelete AS BIT, @JobID AS INT, @dcProvinceID AS INT, @ID AS INT, @MaxID AS INT

	SELECT @Count = COUNT(DISTINCT cpMainId) FROM Inserted

	IF @Count = 1
	BEGIN
		SELECT TOP 1 @JobId = Id FROM Inserted

		IF UPDATE(IssueDate) OR UPDATE(IssueEnd) OR UPDATE(IsDelete)
		BEGIN
			SELECT @ID = ID, @IssueDate = IssueDate, @IssueEnd = IssueEnd, @JobId = ID,
				@cpMainID = cpMainID, @IsDelete = IsDelete, @caMainID = caMainID
			FROM Inserted
			
			DELETE t1
			FROM jobrefreshLog t1, job t2 
			WHERE t1.refreshType =0 AND t1.runDateTime IS NULL 
			AND t2.id IN (SELECT ID FROM Inserted)
			AND t1.jobid =t2.Id
			AND (t1.preRefreshDateTime< t2.IssueDate OR t1.preRefreshDateTime>t2.IssueEnd)  --harry删除时间超过范围的 职位刷新数 2017-11-8
			
			DELETE FROM jobrefreshLog 
			WHERE refreshType =0 AND runDateTime IS NULL 
			AND jobid IN (SELECT ID FROM Inserted WHERE (IsDelete = 1 OR valid = 0))--harry 职位刷新数2017-11-8
			
			UPDATE jobrefreshSet
			SET runState =0 
			WHERE runState =1
			AND jobid IN (SELECT ID fROM Inserted WHERE (IsDelete = 1 OR valid =0) )--harry 职位刷新数2017-11-8
		
			INSERT INTO SearchDB..cpMainTmp(cpMainID) VALUES(@cpMainID)
		END		

		IF UPDATE(IssueDate) OR UPDATE(IssueEnd)
		BEGIN
			----检查是否超出JobNumber
			IF @IssueEnd > GETDATE()
			BEGIN
--				SELECT @Count = COUNT(1) FROM Job WITH(NOLOCK)
--				WHERE cpMainID = @cpMainID AND IsDelete = 0 AND IssueEnd > GETDATE()
--				AND ID <> @ID
--
--				IF @Count >= @MaxJobNumber
--				BEGIN
--					RAISERROR('职位数超出最大值', 10, 1)
--					ROLLBACK TRANSACTION
--					RETURN
--				END
				DECLARE @Membertype INT, @RealName INT
				SELECT @MaxJobNumber = MaxJobNumber, @Membertype = Membertype, @RealName = realName FROM cpMain WITH(NOLOCK) WHERE ID = @cpMainID
				IF @MemberType = 2 AND @RealName <> 1 AND @Count > 5 AND @IssueEnd > GETDATE() + 1
				BEGIN
					RAISERROR('您没有实名认证，职位数最多5个', 10, 1)
					ROLLBACK TRANSACTION
					RETURN				
				END

				IF EXISTS(SELECT 'x' FROM caMain WITH(NOLOCK) WHERE ID = @caMainID AND (IsPause = 1 OR IsDelete = 1))
				BEGIN
					RAISERROR('用户已经暂停，职位不能发布', 10, 1)
					ROLLBACK TRANSACTION
					RETURN
				END
			END

			SELECT @MaxID = MAX(ID) FROM Job WITH(NOLOCK)
		
			IF @MaxId < @JobId + 100
			BEGIN
				SELECT @dcProvinceID = dcProvinceID FROM cpMain WITH(NOLOCK) WHERE ID = @cpMainID
				UPDATE DateReport SET NewJobNum = NewJobNum + 1
				WHERE Province_ID = @dcProvinceID
				AND CountDate = CONVERT(VARCHAR(8), GETDATE(), 112)
			END

			IF @IssueEnd < @IssueDate AND @IssueEnd <= GETDATE()
				UPDATE Job SET IssueDate = @IssueEnd, IssueEnd = @IssueEnd WHERE ID = @ID
		END

		----计算DateReport的删除职位数, 只计算发布过的
		IF UPDATE(IsDelete)
		BEGIN
			DELETE FROM jobrefreshLog 
			WHERE refreshType =0 AND runDateTime IS NULL 
			AND jobid IN (SELECT ID fROM Inserted WHERE (IsDelete = 1 OR valid =0))--harry 职位刷新数2017-11-8
			
			UPDATE jobrefreshSet
			SET runState =0 
			WHERE runState =1
			AND jobid IN (SELECT ID fROM Inserted WHERE (IsDelete = 1 OR valid =0) )--harry 职位刷新数2017-11-8
		
		
			SELECT @dcProvinceID = dcProvinceID
			FROM cpMain WITH(NOLOCK)
			INNER JOIN Inserted ON cpMain.ID = Inserted.cpMainID

			IF @IssueEnd > '2000-1-1' AND @IsDelete = 1
			BEGIN	
				UPDATE DateReport SET DeleteJobNum = DeleteJobNum + 1
				WHERE Province_ID = @dcProvinceID
				AND CountDate = CONVERT(VARCHAR(8), GETDATE(), 112)
			END
			IF @IsDelete = 0
				DELETE FROM JobDeleted WHERE JobID IN(SELECT ID FROM Inserted)
			ELSE
				IF NOT EXISTS(SELECT 'x' FROM JobDeleted WITH(NOLOCK)
					WHERE JobId IN(SELECT ID FROM Inserted))
				BEGIN
					INSERT INTO JobDeleted(JobID,caMainID,cpMainID,JobName,HasIssued,IssueDate,IssueEnd,DeleteDate, Secondid, ProvinceId)
					SELECT ID, caMainID, cpMainID, Name, CASE IssueEnd WHEN NULL THEN 0 ELSE 1 END,IssueDate, IssueEnd, GETDATE(), SecondId, @dcProvinceID
					FROM Inserted

					UPDATE CaCvApplyDeleted SET JobDeleted = 1 WHERE JobId IN(SELECT Id FROM Inserted)
				END
		END

		----职位的valid属性		
		IF UPDATE(IssueDate) OR UPDATE(IssueEnd) OR UPDATE(IsDelete)
		BEGIN
			SET @Valid = 0
			IF @IssueDate < GETDATE() AND @IssueEnd > GETDATE() AND @IsDelete = 0
				SET @Valid = 1

			UPDATE Job SET Valid = @Valid WHERE ID = @ID AND Valid <> @Valid

			--UPDATE Job SET Valid = 1 WHERE ID IN(SELECT Id FROM Inserted) AND IssueDate < GETDATE() AND IssueEnd > GETDATE() AND IsDelete = 0

			IF @Valid = 0
				DELETE FROM ReportDb..HighSalaryJob WHERE JobId = @Id
		END

                --Sunshine 若是修改职位名称一块更新职位刷新记录中的职位名称
                IF UPDATE(name)
		BEGIN
                        UPDATE jobRefreshLog
		        SET jobInfo= (
			SELECT name + ',' + b.FullName 
			FROM job a WITH(NOLOCK), dcRegion b WITH(NOLOCK)
			WHERE a.id = @Id  AND a.dcregionid = b.id
		        ) WHERE jobId=@Id AND runDateTime is null
		END

		--Can Not Name Repeat
		IF NOT EXISTS(SELECT 'x' FROM Inserted WHERE cpMainId = 10576676)
		BEGIN
			IF (UPDATE(Name) OR UPDATE(dcRegionId))
			BEGIN
				IF EXISTS(SELECT 'x' 
					FROM Job a WITH(NOLOCK), 
						Inserted b 
					WHERE a.Name = b.Name 
					AND a.cpMainId = b.cpMainId 
					AND a.Id <> b.Id 
					AND a.IsDelete = 0
					AND a.dcRegionId = b.dcRegionId)
				BEGIN
					RAISERROR('Job''s name111 has repeated!', 10, 1)
					ROLLBACK TRANSACTION
					RETURN
				END
			END
		END

		--重新计算企业的职位数
		--EXEC spRedifinePrivilage @cpMainID

		IF UPDATE(caMainId) OR UPDATE(Name) OR UPDATE(dcJobTypeID) OR UPDATE(dcJobTypeIDMinor) OR UPDATE(NeedNumber) OR UPDATE(dcSalaryID) OR UPDATE(dcSalaryIDMax)
			OR UPDATE(EmployType) OR UPDATE(dcRegionID) OR UPDATE(Responsibility) OR UPDATE(Demand) OR UPDATE(dcEducationID)
			OR UPDATE(MinExperience) OR UPDATE(MinAge) OR UPDATE(MaxAge) OR UPDATE(IssueDate) OR UPDATE(IssueEnd)
			OR UPDATE(IsDelete) OR UPDATE(RefreshDate) OR UPDATE(Valid) OR UPDATE(Lng) OR UPDATE(Lng)
		BEGIN
			IF @Valid IS NULL
				SELECT @Valid = Valid FROM Inserted	
			IF @Valid = 1
			BEGIN
				IF EXISTS(SELECT 'x' FROM JobPublish WITH(NOLOCK) WHERE ID IN(SELECT ID FROM Inserted))
					UPDATE a
					SET a.caMainId = b.caMainId, a.Name = b.Name, a.dcJobTypeID = b.dcJobTypeID, a.dcJobTypeIDMinor = b.dcJobTypeIDMinor,
						a.NeedNumber = b.NeedNumber, a.dcSalaryID = b.dcSalaryID, a.dcSalaryIDMax = b.dcSalaryIDMax, a.EmployType = b.EmployType, a.dcRegionID = b.dcRegionID,
						a.Responsibility = b.Responsibility, a.Demand = b.Demand, a.dcEducationID = b.dcEducationID,
						a.MinExperience = b.MinExperience, a.MinAge = b.MinAge, a.MaxAge = b.MaxAge, a.IssueDate = b.IssueDate,
						a.IssueEnd = b.IssueEnd, a.IsDelete = b.IsDelete, a.AddDate = b.AddDate,
						a.RefreshDate = b.RefreshDate, a.LastModifyDate = b.LastModifyDate, a.Valid = b.Valid,
						a.Lng = b.Lng, a.Lat = b.Lat, a.SecondId = b.SecondId, a.Welfare1 = b.Welfare1, a.Welfare2 = b.Welfare2, a.Welfare3 = b.Welfare3,
						a.Welfare4 = b.Welfare4, a.Welfare5 = b.Welfare5, a.Welfare6 = b.Welfare6,
						a.Welfare7 = b.Welfare7, a.Welfare8 = b.Welfare8, a.Welfare9 = b.Welfare9,
						a.Welfare10 = b.Welfare10, a.Welfare11 = b.Welfare11, a.Welfare12 = b.Welfare12,
						a.Welfare13 = b.Welfare13, a.Welfare14 = b.Welfare14, a.Welfare15 = b.Welfare15,
						a.Welfare16 = b.Welfare16, a.Welfare17 = b.Welfare17, a.Welfare18 = b.Welfare18, a.Welfare19 = b.Welfare19
					FROM JobPublish a, Inserted b
					WHERE a.Id = b.Id
				ELSE
					IF EXISTS(SELECT 'x' FROM cpMainPublish WITH(NOLOCK) WHERE ID IN(SELECT cpMainID FROM Inserted))
						INSERT INTO JobPublish(ID, cpMainID, caMainId, Name, dcJobTypeID, dcJobTypeIDMinor, NeedNumber, dcSalaryID, dcSalaryIDMax,
							EmployType, dcRegionID, Responsibility, Demand, dcEducationID, MinExperience, MinAge, MaxAge, IssueDate,
							IssueEnd, IsDelete, AddDate, RefreshDate, LastModifyDate, Valid, Lng, Lat, SecondId, Welfare1, Welfare2,
							Welfare3, Welfare4, Welfare5, Welfare6, Welfare7, Welfare8, Welfare9, Welfare10, Welfare11, Welfare12,
							Welfare13, Welfare14, Welfare15, Welfare16, Welfare17, Welfare18, Welfare19)
						SELECT ID, cpMainID, caMainId, Name, dcJobTypeID, dcJobTypeIDMinor, NeedNumber, dcSalaryID, dcSalaryIDMax,
							EmployType, dcRegionID, Responsibility, Demand, dcEducationID, MinExperience, MinAge, MaxAge, IssueDate,
							IssueEnd, IsDelete, AddDate, RefreshDate, LastModifyDate, Valid, Lng, Lat, SecondId, Welfare1, Welfare2,
							Welfare3, Welfare4, Welfare5, Welfare6, Welfare7, Welfare8, Welfare9, Welfare10, Welfare11, Welfare12,
							Welfare13, Welfare14, Welfare15, Welfare16, Welfare17, Welfare18, Welfare19
						FROM Inserted
			END
			ELSE
				DELETE FROM JobPublish WHERE ID IN(SELECT ID FROM Inserted)
		END

		IF UPDATE(dcSalaryId)
		BEGIN
			IF EXISTS(SELECT 'x' FROM Inserted WHERE dcSalaryId = 0)
				UPDATE Job SET dcSalaryId = 100 WHERE id IN(SELECT id FROM Inserted WHERE dcSalaryId = 0)
		END
	END
	ELSE
	BEGIN
		IF UPDATE(IsDelete)
		BEGIN
			UPDATE Job
			SET Valid = CASE 
				WHEN IssueEnd > GETDATE() AND IssueDate < GETDATE() AND IsDelete = 0 THEN 1 
				ELSE 0
				END
			WHERE ID IN(SELECT ID FROM Inserted)

			UPDATE Job SET Valid = 0 WHERE ID IN(SELECT ID fROM Inserted WHERE IsDelete = 1 AND Valid = 1)
			
			DELETE FROM jobrefreshLog 
			WHERE refreshType =0 AND runDateTime IS NULL 
			AND jobid IN (SELECT ID fROM Inserted WHERE (IsDelete = 1 OR valid =0))--harry 职位刷新数2017-11-8
			
			UPDATE jobrefreshSet
			SET runState =0 
			WHERE runState =1
			AND jobid IN (SELECT ID fROM Inserted WHERE (IsDelete = 1 OR valid =0) )--harry 职位刷新数2017-11-8
		END
		IF UPDATE(RefreshDate)
			UPDATE a
			SET a.RefreshDate = b.RefreshDate
			FROM JobPublish a, Job b
			WHERE a.id = b.Id
			AND a.Id IN(SELECT ID FROM Inserted)

--		IF (UPDATE(IssueEnd) OR UPDATE(IssueDate) OR UPDATE(IsDelete)) AND NOT UPDATE(Valid)
--		BEGIN
--			UPDATE Job
--			SET Valid = 1 
--			WHERE Valid = 0 
--			AND IssueEnd > GETDATE() 
--			AND IssueDate < GETDATE()
--			AND IsDelete = 0
--			AND Id IN(SELECT ID FROM Inserted)
--		END

		IF UPDATE(IssueEnd) OR UPDATE(IssueDate) OR UPDATE(IsDelete) OR UPDATE(Valid)
		BEGIN			
			UPDATE a
			SET a.IssueEnd = b.IssueEnd, a.IssueDate = b.IssueDate, a.IsDelete = b.IsDelete, a.Valid = b.Valid
			FROM JobPublish a, Job b
			WHERE a.id = b.Id
			AND a.Id IN(SELECT ID FROM Inserted)
			
			DELETE t1
			FROM  jobrefreshLog t1,job t2 
			WHERE t1.refreshType =0 AND t1.runDateTime IS NULL 
			AND t2.id IN (SELECT ID FROM Inserted)
			AND t1.jobid =t2.Id
			AND (t1.preRefreshDateTime< t2.IssueDate OR t1.preRefreshDateTime>t2.IssueEnd)  --harry删除时间超过范围的 职位刷新数 2017-11-8
			
			DELETE FROM jobrefreshLog 
			WHERE refreshType =0 AND runDateTime IS NULL 
			AND jobid IN (SELECT ID fROM Inserted WHERE (IsDelete = 1 OR valid =0))--harry 职位刷新数2017-11-8
			
			UPDATE jobrefreshSet
			SET runState =0 
			WHERE runState =1
			AND jobid IN (SELECT ID fROM Inserted WHERE (IsDelete = 1 OR valid =0) )--harry 职位刷新数2017-11-8
		END	

/*		DECLARE @IsBan AS BIT, @IsMulti AS BIT
		SELECT @IsBan = 0, @IsMulti = 0
		IF (SELECT COUNT(DISTINCT cpMAinId) FROM Inserted) > 1
			SET @IsMulti = 1

		IF (@IsMulti = 1)
		BEGIN
		
		END
*/
	END

	--重新计算企业的职位数
	SELECT TOP 1 @cpMainID = cpMainId FROM Inserted
	----检查是否超出JobNumber
	IF UPDATE(IssueEnd)
	BEGIN
		SELECT @Count = COUNT(1) FROM Job WITH(NOLOCK)
		WHERE cpMainID = @cpMainID AND IsDelete = 0 AND IssueEnd > GETDATE()

		IF @Count > @MaxJobNumber
		BEGIN
			RAISERROR('职位数超出最大值', 10, 1)
			ROLLBACK TRANSACTION
			RETURN
		END
	END

	IF @cpMainId IS NOT NULL
		EXEC spRedifinePrivilage @cpMainID

	IF EXISTS(SELECT 'x' FROM Inserted WHERE ISNULL(dcSalaryidMax, 0) = 0)
	BEGIN
		UPDATE Job SET dcSalaryidMax = dcSalaryid + 1 WHERE dcSalaryid < 17 AND ID IN(SELECT Id FROM Inserted WHERE ISNULL(dcSalaryidMax, 0) = 0)
		UPDATE Job SET dcSalaryidMax = dcSalaryid WHERE dcSalaryid >= 17 AND ID IN(SELECT Id FROM Inserted WHERE ISNULL(dcSalaryidMax, 0) = 0)
	END
END


GO
ALTER TABLE [dbo].[Job] ENABLE TRIGGER [Tri_JobSave]
GO
/****** Object:  Trigger [dbo].[Tri_JobPublish_Delete]    Script Date: 2018/9/25 12:40:16 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TRIGGER [dbo].[Tri_JobPublish_Delete]
   ON [dbo].[JobPublish]
   AFTER DELETE
AS 
BEGIN
	SET NOCOUNT ON;

    INSERT tmp_jobPublishLog(id, cpMainId, DeleteDate)
	SELECT Id, cpMainId, GETDATE()
	FROM Deleted

	IF EXISTS(SELECT 'x' FROM Deleted WHERE cpMainId = 10241726)
	BEGIN
		UPDATE Job SET RefreshDate = RefreshDate WHERE ID = 4643425
		UPDATE Job SET RefreshDate = RefreshDate WHERE ID = 4808554
		UPDATE Job SET RefreshDate = RefreshDate WHERE ID = 4848456
	END
END

GO
ALTER TABLE [dbo].[JobPublish] ENABLE TRIGGER [Tri_JobPublish_Delete]
GO
/****** Object:  Trigger [dbo].[Tri_JobPublish_Save]    Script Date: 2018/9/25 12:40:16 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create TRIGGER [dbo].[Tri_JobPublish_Save]
   ON [dbo].[JobPublish]
   AFTER INSERT, UPDATE
AS 
BEGIN
	SET NOCOUNT ON;

    UPDATE JobPublish
	SET SycDate = GETDATE()
	WHERE Id IN(SELECT Id FROM Inserted)
END

 
GO
ALTER TABLE [dbo].[JobPublish] ENABLE TRIGGER [Tri_JobPublish_Save]
GO
/****** Object:  Trigger [dbo].[Tri_Kpi_ec_Insert]    Script Date: 2018/9/25 12:40:16 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create TRIGGER [dbo].[Tri_Kpi_ec_Insert]
   ON  [dbo].[KPI_EC]
   AFTER INSERT
AS 
BEGIN
	SET NOCOUNT ON;
	DECLARE @Sender AS INT,@Receiver as int
	SELECT @Sender=Sender,@Receiver=Receiver FROM Inserted
	IF @Sender=@Receiver
	BEGIN
        RAISERROR('Error：不能给自己开单',10,1)
		ROLLBACK TRANSACTION
		RETURN
	END
END

GO
ALTER TABLE [dbo].[KPI_EC] ENABLE TRIGGER [Tri_Kpi_ec_Insert]
GO
/****** Object:  Trigger [dbo].[Tri_Kpi_Ie_Insert]    Script Date: 2018/9/25 12:40:16 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TRIGGER [dbo].[Tri_Kpi_Ie_Insert]
   ON [dbo].[KPI_IE]
   AFTER INSERT
AS 
BEGIN
	SET NOCOUNT ON;
	IF (SELECT COUNT(*) FROM Inserted) > 1
		RETURN

	IF EXISTS(SELECT 'x' FROM Inserted WHERE Sender IN(152, 114))
		RETURN

	DECLARE @Sender INT
	SELECT @Sender = Sender FROM Inserted
	IF(SELECT COUNT(*) FROM Kpi_Ie WITH(NOLOCK) WHERE CreateDate > CONVERT(VARCHAR(10), GETDATE(), 120) AND Sender = @Sender) > 1
	BEGIN
		RAISERROR('今天您已经提交IE了，请明天继续提交！', 10, 1)
		ROLLBACK TRANSACTION
		RETURN
	END
END

GO
ALTER TABLE [dbo].[KPI_IE] ENABLE TRIGGER [Tri_Kpi_Ie_Insert]
GO
/****** Object:  Trigger [dbo].[Tri_Kpi_Ie_Save]    Script Date: 2018/9/25 12:40:16 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TRIGGER [dbo].[Tri_Kpi_Ie_Save]
   ON [dbo].[KPI_IE]
   AFTER INSERT, UPDATE
AS 
BEGIN
	SET NOCOUNT ON;

	IF UPDATE(Sender) OR UPDATE(Receiver)
		UPDATE Kpi_Ie
		SET OldSender = ISNULL(dbo.GetOldManagerUserName(Sender, AddDate), ''), 
			OldReceiver = ISNULL(dbo.GetOldManagerUserName(Receiver, AddDate), '')
		WHERE ID IN(SELECT ID FROM Inserted)
END

GO
ALTER TABLE [dbo].[KPI_IE] ENABLE TRIGGER [Tri_Kpi_Ie_Save]
GO
/****** Object:  Trigger [dbo].[Tri_Kpi_Km_Delete]    Script Date: 2018/9/25 12:40:16 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE TRIGGER [dbo].[Tri_Kpi_Km_Delete]
   ON [dbo].[KPI_KM]
   AFTER DELETE
AS 
BEGIN
	SET NOCOUNT ON;

    INSERT INTO LogDb..Kpi_Km_Log
	SELECT *, GETDATE() FROM deleted

END

GO
ALTER TABLE [dbo].[KPI_KM] ENABLE TRIGGER [Tri_Kpi_Km_Delete]
GO
/****** Object:  Trigger [dbo].[Tri_Kpi_km_Insert]    Script Date: 2018/9/25 12:40:16 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TRIGGER [dbo].[Tri_Kpi_km_Insert]
   ON  [dbo].[KPI_KM]
   AFTER INSERT
AS 
BEGIN
	SET NOCOUNT ON;
	DECLARE @Sender AS INT, @Receiver as int
	SELECT @Sender=Sender, @Receiver=Receiver FROM Inserted
	IF((@Sender = @Receiver) AND (@Receiver > 1))
	BEGIN
        RAISERROR('Error：不能给自己开单',10,1)
		ROLLBACK TRANSACTION
		RETURN
	END
END

GO
ALTER TABLE [dbo].[KPI_KM] ENABLE TRIGGER [Tri_Kpi_km_Insert]
GO
/****** Object:  Trigger [dbo].[Tri_Link_Insert]    Script Date: 2018/9/25 12:40:16 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE TRIGGER [dbo].[Tri_Link_Insert]
   ON [dbo].[Link]
   AFTER INSERT
AS 
BEGIN
	SET NOCOUNT ON;
	DECLARE @Link AS varchar(100), @Text AS VARCHAR(100)
    SELECT @Link = Link, @Text = Text FROM Inserted
	IF LEN(@link) < 10 OR @Link NOT LIKE 'http://%' OR dbo.haveChinese(@text) = 0
	BEGIN
		--RAISERROR('You''re killed.', 10, 1)
		--ROLLBACK TRANSACTION
		DELETE Link WHERE ID = (SELECT ID FROM Inserted)
		RETURN
	END
END

GO
ALTER TABLE [dbo].[Link] ENABLE TRIGGER [Tri_Link_Insert]
GO
/****** Object:  Trigger [dbo].[Tri_Link_Update]    Script Date: 2018/9/25 12:40:17 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE TRIGGER [dbo].[Tri_Link_Update]
   ON [dbo].[Link]
   AFTER INSERT, UPDATE
AS 
BEGIN
	SET NOCOUNT ON;
	UPDATE LogDb..HomePageTableRefresh SET RefreshDate = GETDATE() WHERE TableName = 'link'
END

GO
ALTER TABLE [dbo].[Link] ENABLE TRIGGER [Tri_Link_Update]
GO
/****** Object:  Trigger [dbo].[Tri_ManagerLog_Insert]    Script Date: 2018/9/25 12:40:17 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TRIGGER [dbo].[Tri_ManagerLog_Insert]
   ON [dbo].[ManagerLog]
   AFTER INSERT
AS 
BEGIN
	SET NOCOUNT ON;

	IF EXISTS(SELECT 'x' FROM Oadb..WorkDate WHERE WorkDate = CONVERT(VARCHAR(8), GETDATE(), 112) AND WorkType = 1)
		IF DATEPART(HOUR, GETDATE()) BETWEEN 7 AND 17	-- AND 1=2
			RETURN

	DECLARE @ip VARCHAR(15), @ManagerId INT
	SELECT @Ip = Ip, @ManagerId = ManagerId FROM Inserted

	DELETE ManagerLogSnap WHERE Ip = @ip Or ManagerId = @ManagerId

    INSERT INTO ManagerLogSnap(ManagerId, LoginDate, Ip)
	SELECT ManagerId, GETDATE(), Ip FROM Inserted
	WHERE ComputerName IS NULL
END

GO
ALTER TABLE [dbo].[ManagerLog] ENABLE TRIGGER [Tri_ManagerLog_Insert]
GO
/****** Object:  Trigger [dbo].[Tri_ManagerLog_UPDATE]    Script Date: 2018/9/25 12:40:17 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TRIGGER [dbo].[Tri_ManagerLog_UPDATE]
   ON [dbo].[ManagerLog]
   AFTER UPDATE
AS 
BEGIN
	SET NOCOUNT ON;

	IF EXISTS(SELECT 'x' FROM Oadb..WorkDate WHERE WorkDate = CONVERT(VARCHAR(8), GETDATE(), 112) AND WorkType = 1)
		IF DATEPART(HOUR, GETDATE()) BETWEEN 7 AND 17	-- AND 1=2
			RETURN

	DECLARE @ip VARCHAR(15), @ManagerId INT
	SELECT @Ip = Ip, @ManagerId = ManagerId FROM Inserted

	DELETE ManagerLogSnap WHERE Ip = @ip Or ManagerId = @ManagerId

    INSERT INTO ManagerLogSnap(ManagerId, LoginDate, Ip)
	SELECT ManagerId, GETDATE(), Ip FROM Inserted
	WHERE ComputerName IS NULL
END

GO
ALTER TABLE [dbo].[ManagerLog] ENABLE TRIGGER [Tri_ManagerLog_UPDATE]
GO
/****** Object:  Trigger [dbo].[Tri_ManagerUserUpdate]    Script Date: 2018/9/25 12:40:17 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TRIGGER [dbo].[Tri_ManagerUserUpdate]
   ON  [dbo].[ManagerUser]
   AFTER UPDATE
AS 
BEGIN
	IF UPDATE(Status)
	BEGIN
		DECLARE @ManagerUserId INT, @StatusOld INT, @StatusNew INT

		SELECT @ManagerUserId = Id, @StatusOld = Status FROM Deleted
		SELECT @StatusNew = Status FROM Inserted
		IF @StatusOld <> @StatusNew AND @StatusNew >= 3
			UPDATE cpMain SET IsLock = 0 WHERE ConsultantID = @ManagerUserId

		EXEC OaDb..ProcManagerUserSnapInsert	
	END
--	IF UPDATE(RtxStatus)
--	BEGIN
--		UPDATE ManagerUser SET RtxTime = GETDATE() WHERE ID IN(SELECT ID FROM Inserted)
--	END
END

GO
ALTER TABLE [dbo].[ManagerUser] ENABLE TRIGGER [Tri_ManagerUserUpdate]
GO
/****** Object:  Trigger [dbo].[Tri_msEmailprevSend_Delete]    Script Date: 2018/9/25 12:40:17 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE TRIGGER [dbo].[Tri_msEmailprevSend_Delete]
   ON  [dbo].[msEmailPrevSend]
   AFTER DELETE
AS 
BEGIN
	SET NOCOUNT ON;

    INSERT INTO Logdb..msEmailprevSendLog
	SELECT * FROM Deleted
END

GO
ALTER TABLE [dbo].[msEmailPrevSend] ENABLE TRIGGER [Tri_msEmailprevSend_Delete]
GO
/****** Object:  Trigger [dbo].[Tri_msEmailPrevSend_Insert]    Script Date: 2018/9/25 12:40:17 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE trigger [dbo].[Tri_msEmailPrevSend_Insert]
	On [dbo].[msEmailPrevSend]
	AFTER INSERT
AS
SET NOCOUNT ON
BEGIN
	/*DECLARE @EmailNo TINYINT, @ID INT, @cpMainId INT, @Email VARCHAR(50), @JsonData NVARCHAR(100)
	SELECT @EMailNo = Emailno, @Id = ID, @cpMainID = cpMainId, @Email = EMail, @JsonData = LEFT(ISNULL(JsonData, ''), 100) FROM Inserted
	IF(@EmailNo IN(95))		--, 53))
	BEGIN
		IF EXISTS(SELECT 'x' FROM msEmailPrevSend WITH(NOLOCK)
			WHERE Id < @Id AND ID > @ID - 3000
			AND cpMainId = @cpMainId
			AND Email = @Email AND EmailNo = @EmailNo
			AND LEFT(JsonData, 100) <> @JsonData)
		BEGIN
			DELETE msEmailPrevSend WHERE Id = @Id
			RETURN
		END
	END
	*/
	IF EXISTS(SELECT 'x' FROM Inserted WHERE JsonData IS NULL)
		UPDATE msEmailPrevSend
		SET JsonData = JasonData
		WHERE ID IN(SELECT ID FROM Inserted WHERE JsonData IS NULL)

	IF EXISTS (SELECT 'x' FROM Inserted WHERE EMAIL COLLATE Chinese_PRC_CI_AS_WS LIKE '%＠%')
		UPDATE MsEmailPrevSend
		SET Email = REPLACE(Email, '＠', '@')
		WHERE ID IN(SELECT ID FROM Inserted)

	IF EXISTS (SELECT 'x' FROM Inserted WHERE EMAIL LIKE '%@your_email.com')
		DELETE msEmailPrevSend WHERE ID IN(SELECT ID FROM Inserted WHERE EMAIL LIKE '%@your_email.com')

	IF EXISTS(SELECT 'x' FROM Inserted WHERE EmailNo IN(86, 53))
	BEGIN
		DECLARE @Email VARCHAR(50), @EmailNo TINYINT, @JsonData VARCHAR(MAX)
		SELECT @Email = Email, @Emailno = EmailNo, @JsonData = JsonData FROM Inserted
		IF EXISTS(SELECT 'x' FROM MsEmailPrevSend WHERE Email = @Email AND @Emailno = @EmailNo AND JsonData = @JsonData AND AddDate > DATEADD(MINUTE, -5, GETDATE()))
			DELETE msEmailPrevSend WHERE ID IN(SELECT ID FROM Inserted)
	END
	--UPDATE MsEmailPrevSend
	--SET JsonData = JsonData + ',"utm_campaign":"Email_' + LTRIM(STR(EmailNo)) + '&utm_medium=Email","utm_source":"Mail_' +
	--	RIGHT(LTRIM(LOWER(Email)), LEN(LTRIM(Email)) - CHARINDEX('@', LTRIM(Email)))+'"'
	--WHERE Email LIKE '%@%'
	--AND ID IN(select Id FROM Inserted)
END

GO
ALTER TABLE [dbo].[msEmailPrevSend] ENABLE TRIGGER [Tri_msEmailPrevSend_Insert]
GO
/****** Object:  Trigger [dbo].[Tri_MsEmailSend_Delete]    Script Date: 2018/9/25 12:40:17 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE TRIGGER [dbo].[Tri_MsEmailSend_Delete]
   ON  [dbo].[msEmailSend]
   AFTER DELETE
AS 
BEGIN
	SET NOCOUNT ON;

    INSERT INTO Logdb..MsEmailSendLog
	SELECT * FROM Deleted
END

GO
ALTER TABLE [dbo].[msEmailSend] ENABLE TRIGGER [Tri_MsEmailSend_Delete]
GO
/****** Object:  Trigger [dbo].[Tri_MsSql_UPDATE]    Script Date: 2018/9/25 12:40:17 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE TRIGGER [dbo].[Tri_MsSql_UPDATE]
   ON [dbo].[msSql]
   AFTER INSERT, UPDATE
AS 
BEGIN
	SET NOCOUNT ON;

    IF NOT UPDATE(AddDate)
	BEGIN
		UPDATE MsSql SET AddDate = GETDATE() WHERE ID IN(SELECT ID FROM Inserted)
	END

END

GO
ALTER TABLE [dbo].[msSql] ENABLE TRIGGER [Tri_MsSql_UPDATE]
GO
/****** Object:  Trigger [dbo].[Tri_Mt_Plan_Save]    Script Date: 2018/9/25 12:40:17 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TRIGGER [dbo].[Tri_Mt_Plan_Save]
   ON [dbo].[MT_plan]
   AFTER INSERT, UPDATE
AS 
BEGIN
	SET NOCOUNT ON;
	DECLARE @BeginTime DateTime, @EndTime DATETIME, @ID INT, @Mt_Id INT
	SELECT @BeginTime = BeginTime, @EndTime = EndTime, @ID = ID, @Mt_Id = Mt_ID FROM Inserted
	IF EXISTS(SELECT 'x' FROM Mt_Plan WITH(NOLOCK)
		WHERE (BeginTime BETWEEN @BeginTime AND @EndTime OR EndTime BETWEEN @BeginTime AND @EndTime)
		AND ID <> @ID
		AND Mt_Id = @Mt_ID
		)
	BEGIN
		RAISERROR('会议室已经在你的时间段被别人占用!', 10, 1)
		ROLLBACK TRANSACTION
		RETURN
	END
END

GO
ALTER TABLE [dbo].[MT_plan] ENABLE TRIGGER [Tri_Mt_Plan_Save]
GO
/****** Object:  Trigger [dbo].[Tri_paFavorateInsert]    Script Date: 2018/9/25 12:40:17 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE TRIGGER [dbo].[Tri_paFavorateInsert]
   ON  [dbo].[paFavorate]
   INSTEAD OF INSERT
AS 
BEGIN
	SET NOCOUNT ON;
	DELETE paFavorate FROM Inserted
	WHERE paFavorate.JobId = Inserted.JobId
	AND paFavorate.paMainID = Inserted.paMainID
	
	INSERT INTO paFavorate(paMainID,JobId,Remark) 
	SELECT paMainID,JobId,Remark FROM Inserted
END


GO
ALTER TABLE [dbo].[paFavorate] ENABLE TRIGGER [Tri_paFavorateInsert]
GO
/****** Object:  Trigger [dbo].[Tri_paLoginLog_Delete]    Script Date: 2018/9/25 12:40:17 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TRIGGER [dbo].[Tri_paLoginLog_Delete]
   ON [dbo].[paLoginLog]
   AFTER Delete
AS 
BEGIN
	SET NOCOUNT ON;

	IF DATEPART(HOUR, GETDATE()) > 17 OR DATEPART(HOUR, GETDATE()) < 8
		RETURN

	INSERT INTO paLoginLogDel(ID, paMainID, LoginIP, AddDate, Browser, LoginFrom)
	SELECT ID, paMainID, LoginIP, AddDate, Browser, LoginFrom FROM Deleted
END

GO
ALTER TABLE [dbo].[paLoginLog] ENABLE TRIGGER [Tri_paLoginLog_Delete]
GO
/****** Object:  Trigger [dbo].[Tri_PaLoginLog_Insert]    Script Date: 2018/9/25 12:40:17 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--登录日志触发器，更新个人登录时间
CREATE TRIGGER [dbo].[Tri_PaLoginLog_Insert]
    ON [dbo].[paLoginLog]
    AFTER INSERT
AS
BEGIN    
	UPDATE PaMain 
	SET LastLoginDate = GETDATE()
	WHERE ID = (SELECT TOP 1 PaMainID FROM Inserted)
END

GO
ALTER TABLE [dbo].[paLoginLog] ENABLE TRIGGER [Tri_PaLoginLog_Insert]
GO
/****** Object:  Trigger [dbo].[Tri_paMainDelete]    Script Date: 2018/9/25 12:40:17 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE TRIGGER [dbo].[Tri_paMainDelete]
   ON [dbo].[paMain]
   AFTER DELETE
AS 
BEGIN
	SET NOCOUNT ON;
	IF (SELECT COUNT(1) FROM Deleted) = 1
	BEGIN 
		DECLARE @ID AS INT
		SELECT @ID = ID FROM Deleted
		DELETE FROM MarketDb..cvrRecommend WHERE UserID = @Id OR RecommendID = @ID
		DELETE FROM paMainPublish WHERE ID = @ID
		DELETE FROM PaAttention where pamainid = @ID
		DELETE wxFans WHERE paMainId = @ID
		DELETE FROM Marketdb..rmperson WHERE paMainId = @ID
		DELETE FROM Marketdb..pastudentid WHERE paMainId= @ID
			
		BEGIN TRY
			INSERT INTO paMainDel(ID, UserName, UserNameLower, Password, IsDefaultPassword, dcProvinceID, RegisterIP, RegisterMode, AddMan, Name, NameEng, Email, Gender, BirthDay, LivePlace, AccountPlace, GrowPlace, Mobile, OnlineContact, OnlineContactNo, Homepage, Marriage, Nation, Height, dcCareerStatus, HasPhoto, HideConditions, BlockCount, VerifyCount, LastLoginDate, TotalLoginNum, LastModifyDate, AddDate, dcSubSiteID, MobileRegion, IsReceiveSms, PerfectDate, PlainPassword, MobileVerifyDate, EmailVerifyDate, RegisterFrom, SpreadDate, RegisterType, IsAppNotice, IsEmailNotice, IsWeixinNotice, IsAppJobFinder, IsEmailJobFinder, IsWeiXinJobFinder, IsUseYourFood)
			SELECT ID, UserName, UserNameLower, Password, IsDefaultPassword, dcProvinceID, RegisterIP, RegisterMode, AddMan, Name, NameEng, Email, Gender, BirthDay, LivePlace, AccountPlace, GrowPlace, Mobile, OnlineContact, OnlineContactNo, Homepage, Marriage, Nation, Height, dcCareerStatus, HasPhoto, HideConditions, BlockCount, VerifyCount, LastLoginDate, TotalLoginNum, LastModifyDate, AddDate, dcSubSiteID, MobileRegion, IsReceiveSms, PerfectDate, PlainPassword, MobileVerifyDate, EmailVerifyDate, RegisterFrom, SpreadDate, RegisterType, IsAppNotice, IsEmailNotice, IsWeixinNotice, IsAppJobFinder, IsEmailJobFinder, IsWeiXinJobFinder, IsUseYourFood FROM Deleted
		END TRY
		BEGIN CATCH
		END CATCH
	END
	ELSE
	BEGIN
		DELETE FROM paMainPublish WHERE ID IN(SELECT ID FROM Deleted)
	END
	
	DELETE FROM wxSmallPrograminfo WHERE pamainid IN(SELECT ID FROM Deleted)	

	INSERT INTO paMainDeleted(ID, UserNameLower, Password, Mobile, AddDate)
	SELECT ID, UserNameLower, EMail, Mobile, GETDATE() FROM Deleted
END

GO
ALTER TABLE [dbo].[paMain] ENABLE TRIGGER [Tri_paMainDelete]
GO
/****** Object:  Trigger [dbo].[Tri_paMainInsert]    Script Date: 2018/9/25 12:40:17 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TRIGGER [dbo].[Tri_paMainInsert]
   ON [dbo].[paMain]
   AFTER INSERT
AS 
BEGIN
	SET NOCOUNT ON;
	IF (SELECT COUNT(1) FROM Inserted) = 1
	BEGIN
		DECLARE @EMail AS VARCHAR(50), @ID AS INT

		SELECT @Email = Email, @Id = ID FROM Inserted
		IF EXISTS(SELECT 'x' FROM paMain WITH(NOLOCK INDEX(Ix_paMain_Email)) WHERE ID <> @ID AND Email = @Email)
		BEGIN
			INSERT paMainDeleted
			SELECT ID, UserNameLower, Password, GETDATE(), Mobile FROM Inserted

			RAISERROR('注册的邮箱不能和现有邮箱重复', 10, 1)
			ROLLBACK TRANSACTION
			RETURN
		END

		IF @Email LIKE '%@your_email.com'
			DELETE FROM dcAutoEmail WHERE EMail = @Email

		IF EXISTS(SELECT 'x' FROM Resume_Xinxi WITH(NOLOCK INDEX(Ix_Resume_Xinxi_Email)) WHERE Email = @Email)
		BEGIN
			--Sean 2011.12.8 增加，临时纪录推广数据注册的数量，因为推广部说注册数据变少了，所以检查一下
			INSERT INTO tmpResume_Xinxi_Check(paMainId, Email, AddMan, Province_Id, RegDate, DeleteDate)
			SELECT @Id, Email, AddMan, Province_Id, RegDate, GETDATE()
			FROM Resume_XInxi WITH(NOLOCK)
			WHERE EMail = @Email
			DELETE FROM Resume_Xinxi WHERE Email = @Email
		END

		IF UPDATE(UserName)
		BEGIN
			IF ((dbo.IsEmail((SELECT UserName FROM Inserted)) = 0 OR dbo.IsPassword((SELECT Password FROM Inserted)) = 0) AND ((SELECT RegisterMode FROM Inserted) = 0 OR (SELECT RegisterType FROM Inserted) = 0))
			BEGIN
				INSERT paMainDeleted
				SELECT ID, UserNameLower, Password, GETDATE(), Mobile FROM Inserted

				RAISERROR('用户名或密码格式不正确', 10, 1)
				ROLLBACK TRANSACTION
				RETURN
			END
		END

		IF UPDATE(Password)
		BEGIN
			IF dbo.IsPassword((SELECT Password FROM Inserted)) = 0
			BEGIN
				INSERT paMainDeleted
				SELECT ID, UserNameLower, Password, GETDATE(), Mobile FROM Inserted

				RAISERROR('密码格式不正确', 10, 1)
				ROLLBACK TRANSACTION
				RETURN
			END
		END
	END
END
GO
ALTER TABLE [dbo].[paMain] ENABLE TRIGGER [Tri_paMainInsert]
GO
/****** Object:  Trigger [dbo].[Tri_PaMainUpdate]    Script Date: 2018/9/25 12:40:17 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TRIGGER [dbo].[Tri_PaMainUpdate]
   ON [dbo].[paMain]
   AFTER UPDATE
AS 
BEGIN
	SET NOCOUNT ON;
	IF (SELECT COUNT(1) FROM Inserted) = 1
	BEGIN
		DECLARE @Mobile VARCHAR(11), @ID AS INT, @UserName AS VARCHAR(50), @Name NVARCHAR(6)
		SELECT @ID = ID, @UserName = UserNameLower, @Mobile = Mobile, @Name = [Name] FROM Inserted

		IF UPDATE(UserName)
		BEGIN
			IF dbo.IsEmail((SELECT Username FROM Inserted)) = 0
			BEGIN
				RAISERROR('用户名不是邮箱格式', 10, 1)
				ROLLBACK TRANSACTION
				RETURN
			END
			ELSE
			BEGIN
/*
				IF EXISTS(SELECT 'x' FROM paMain WITH(NOLOCK INDEX(IX_paMain_UserNameLower))
							WHERE ID <> @ID AND UserNameLower = @UserName)
				BEGIN
					RAISERROR('用户名不能和现有用户名重复', 10, 1)
					ROLLBACK TRANSACTION
					RETURN
				END
*/				
				IF EXISTS (SELECT 'x' FROM Deleted WHERE UserNameLower <> @UserName)
					UPDATE PaMain SET EMail = UserName, EmailVerifyDate = NULL WHERE ID = @ID
			END
		END

		IF UPDATE(Password)
		BEGIN
			IF dbo.IsPassword((SELECT Password FROM Inserted)) = 0
			BEGIN
				RAISERROR('密码格式不正确', 10, 1)
				ROLLBACK TRANSACTION
				RETURN
			END
		END
		
		IF UPDATE(Email)
		BEGIN
			RAISERROR('不允许修改个人邮箱', 10, 1)
			ROLLBACK TRANSACTION
			RETURN
		END

		IF UPDATE(Mobile)
		BEGIN
			IF LEN(ISNULL(@Mobile, '')) > 0 AND dbo.IsMobile(@Mobile) = 0
			BEGIN
				RAISERROR('手机号不正确', 10, 1)
				ROLLBACK TRANSACTION
				RETURN
			END
			IF EXISTS (SELECT 'x' FROM Deleted WHERE Mobile <> @Mobile)
				UPDATE PaMain SET MobileVerifyDate = NULL WHERE ID = @ID
			
			IF LEN(ISNULL(@Mobile, '')) = 0 AND EXISTS(SELECT 'x' FROM Deleted WHERE Mobile > '')
			BEGIN
				IF EXISTS(SELECT 'x' FROM cvMain WITH(NOLOCK) WHERE paMainId = @Id AND cvLevel LIKE '11%')
					UPDATE cvMain SET cvLevel = '10' + RIGHT(cvLevel, 8) WHERE paMainId = @Id AND cvLevel LIKE '11%'
			END		
		END

		IF UPDATE(Name) AND dbo.IsChinese(@Name) = 0
		BEGIN
			DECLARE @E NVARCHAR(100)
			SET @E = '不允许修改姓名:' + @Name
			RAISERROR(@E, 10, 1)
			ROLLBACK TRANSACTION
			RETURN
		END

		IF EXISTS(SELECT 'x' FROM Inserted WHERE Verifycount > 0)
		BEGIN
			IF UPDATE(HasPhoto) OR UPDATE(LastLoginDate) OR UPDATE(LastModifyDate) OR UPDATE(Name) OR UPDATE(VerifyCount)
			BEGIN
				IF EXISTS(SELECT 'x' FROM PaMainPublish WITH(NOLOCK) WHERE ID IN(SELECT ID FROM Inserted))
					UPDATE a
					SET a.Gender = b.Gender,
						a.BirthDay = b.BirthDay,
						a.LivePlace = b.LivePlace,
						a.AccountPlace = b.AccountPlace,
						a.GrowPlace = b.GrowPlace,
						a.Height = b.Height,
						a.HasPhoto = b.HasPhoto,
						a.LastLoginDate = b.LastLoginDate,
						a.LastModifyDate = b.LastModifyDate
					FROM paMainPublish a, Inserted b
					WHERE a.Id = b.Id
				ELSE
					INSERT INTO paMainPublish(ID, Gender, BirthDay, LivePlace, AccountPlace, GrowPlace, Height, HasPhoto, LastLoginDate, LastModifyDate, MobileRegion)
					SELECT ID, Gender, BirthDay, LivePlace, AccountPlace, GrowPlace, Height, HasPhoto, LastLoginDate, LastModifyDate, MobileRegion FROM Inserted			
			END
		END
	END
END
GO
ALTER TABLE [dbo].[paMain] ENABLE TRIGGER [Tri_PaMainUpdate]
GO
/****** Object:  Trigger [dbo].[Tri_PaMainPublish_Insert]    Script Date: 2018/9/25 12:40:17 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TRIGGER [dbo].[Tri_PaMainPublish_Insert]
   ON [dbo].[paMainPublish]
   AFTER INSERT
AS 
BEGIN
	SET NOCOUNT ON;
	SET XACT_ABORT OFF
	INSERT INTO cvMainPublish(ID, paMainID, Degree, dcMajorID, LastJobTypeID, LastIndustryID, JobName, SubNodeNum, 
		RelatedWorkYears, dcSalaryID, IsNegotiable, Speciality, SpecialityEng, Attachment, Valid, RefreshDate, EmployType, SecondId)
	SELECT ID, paMainID, Degree, dcMajorID, LastJobTypeID, LastIndustryID, JobName, SubNodeNum, 
		RelatedWorkYears, dcSalaryID, IsNegotiable, Speciality, SpecialityEng, Attachment, Valid, RefreshDate, EmployType, SecondId
	FROM cvMain WITH(NOLOCK) WHERE paMainId IN(SELECT ID FROM Inserted) AND Valid > 0
END

GO
ALTER TABLE [dbo].[paMainPublish] ENABLE TRIGGER [Tri_PaMainPublish_Insert]
GO
/****** Object:  Trigger [dbo].[Tri_PaPhotoDelete]    Script Date: 2018/9/25 12:40:17 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE TRIGGER [dbo].[Tri_PaPhotoDelete]
	ON [dbo].[paPhoto]
	AFTER DELETE
AS
BEGIN
	SET NOCOUNT ON;
	
	INSERT INTO bsDeleteFile(FileType, FileID, [FileName] )
	SELECT 1, paMainID, Photo FROM Deleted WHERE Photo > ''
	
	INSERT INTO bsDeleteFile(FileType, FileID, [FileName])
	SELECT 4, paMainID, PhotoProcessed FROM Deleted WHERE PhotoProcessed > ''

	UPDATE paMain SET HasPhoto = NULL
	WHERE HasPhoto IS NOT NULL
	AND ID IN (SELECT paMainID FROM Inserted)
END


GO
ALTER TABLE [dbo].[paPhoto] ENABLE TRIGGER [Tri_PaPhotoDelete]
GO
/****** Object:  Trigger [dbo].[Tri_PaPhotoUpdate]    Script Date: 2018/9/25 12:40:17 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE TRIGGER [dbo].[Tri_PaPhotoUpdate]
	ON [dbo].[paPhoto]
	AFTER UPDATE
AS
BEGIN
	SET NOCOUNT ON;
	IF (SELECT COUNT(1) FROM Inserted) = 1
	BEGIN
		IF UPDATE(Photo)
			IF (SELECT photo FROM Deleted) IS NOT NULL
				INSERT INTO bsDeleteFile(FileType, FileID, [FileName] )
				SELECT 1, paMainID, Photo FROM Deleted

		IF UPDATE(PhotoProcessed)
			IF (SELECT PhotoProcessed FROM Deleted) IS NOT NULL
				INSERT INTO bsDeleteFile(FileType, FileID, [FileName] )
				SELECT 4, paMainID, PhotoProcessed FROM Deleted

		IF UPDATE(CheckMan)
		BEGIN
			IF EXISTS(SELECT 'x' FROM Inserted WHERE CheckMessage > '')
			BEGIN
				UPDATE paMain SET HasPhoto = 2
				WHERE HasPhoto = 0
				AND ID = (SELECT paMainID FROM Inserted)
			END
			ELSE
			BEGIN
				UPDATE paMain SET HasPhoto = 1
				WHERE HasPhoto = 0
				AND ID = (SELECT paMainID FROM Inserted)
			END
		END
	END
END


GO
ALTER TABLE [dbo].[paPhoto] ENABLE TRIGGER [Tri_PaPhotoUpdate]
GO
/****** Object:  Trigger [dbo].[Tri_PaRemindLog]    Script Date: 2018/9/25 12:40:17 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TRIGGER [dbo].[Tri_PaRemindLog]
   ON [dbo].[PaRemindLog]
   AFTER INSERT
AS 
BEGIN
	SET NOCOUNT ON;
	INSERT INTO WxMessageSend
	SELECT b.ID, a.ContentText, null, 0, 1, d.ID, '', null, GETDATE()
	FROM Inserted a WITH(NOLOCK), WxFans b WITH(NOLOCK), PaMain c WITH(NOLOCK), WxTemplateno d WITH(NOLOCK)
	WHERE a.WxRemindDate IS NULL
	AND a.PaMainID = b.PaMainID
	AND b.Status = 2
	AND a.PaMainID = c.ID
	AND c.IsWeiXinNotice = 1
	AND b.WxServiceNoID = d.WxServiceNoID
	AND d.WxTemplateId = 3

	UPDATE PaRemindLog SET WxRemindDate = GETDATE() WHERE ID  IN (SELECT ID FROM Inserted)
	
	UPDATE a SET ViewDate = NULL FROM PaAttention a WITH(NOLOCK),Inserted b WITH(NOLOCK)
	WHERE a.PaMainID = b.paMainID
	AND a.AttentionID = b.RemainID
	AND b.RemainType IN (1,2,3,4)

	UPDATE PaAttention SET ViewDate = NULL 
	WHERE ID  IN (SELECT TOP 1 a.ID FROM PaAttention a WITH(NOLOCK)
		,Inserted b WITH(NOLOCK)
		WHERE a.PaMainID = b.paMainID
		AND b.RemainType NOT IN (1,2,3,4)
	)
END



GO
ALTER TABLE [dbo].[PaRemindLog] ENABLE TRIGGER [Tri_PaRemindLog]
GO
/****** Object:  Trigger [dbo].[Tri_QlrcNews_Update]    Script Date: 2018/9/25 12:40:17 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE TRIGGER [dbo].[Tri_QlrcNews_Update]
   ON [dbo].[QlrcNews]
   AFTER INSERT, UPDATE
AS 
BEGIN
	SET NOCOUNT ON;
	DECLARE @Title NVARCHAR(60), @Id INT
	SELECT TOP 1 @Id = Id, @Title = Title FROM Inserted
	IF @Title LIKE '&#65279;%'
		UPDATE QlrcNews
		SET Title = REPLACE(Title, '&#65279;', '')
		WHERE Id = @Id
END

GO
ALTER TABLE [dbo].[QlrcNews] ENABLE TRIGGER [Tri_QlrcNews_Update]
GO
/****** Object:  Trigger [dbo].[Resume_Xinxi_Delete]    Script Date: 2018/9/25 12:40:17 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE TRIGGER [dbo].[Resume_Xinxi_Delete]
   ON [dbo].[Resume_Xinxi]
   AFTER DELETE
AS 
BEGIN
	SET NOCOUNT ON;
	DECLARE @Email VARCHAR(50), @UserNameLower VARCHAR(50), @id INT
	SELECT @Email = EMail, @UserNameLower = UserNameLower FROM Deleted
	SELECT @Id = Id FROM paMain WITH(NOLOCK) WHERE EMail = @Email
	IF @Id IS NULL
		SELECT @Id = Id FROM paMain WITH(NOLOCK) WHERE UserNameLower = @UserNameLower

	INSERT INTO LogDb..Resume_XinXi_Log(Id, UserName, PassWord, Email, RegDate, AddMan,
		Province_Id, Name, IsHistory, UserNameLower, paMainId, DeleteDate)
	SELECT Id, UserName, PassWord, Email, RegDate, AddMan,
		Province_Id, Name, IsHistory, UserNameLower, @Id, GETDATE()
	FROM Deleted
END

GO
ALTER TABLE [dbo].[Resume_Xinxi] ENABLE TRIGGER [Resume_Xinxi_Delete]
GO
/****** Object:  Trigger [dbo].[Tri_Rtx_Log_Insert]    Script Date: 2018/9/25 12:40:17 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TRIGGER [dbo].[Tri_Rtx_Log_Insert]
   ON [dbo].[rtx_log]
   AFTER INSERT
AS 
BEGIN
	SET NOCOUNT ON;
	
	IF EXISTS(SELECT 'x' FROM Inserted WHERE Recipient LIKE '%1112%' AND Addresser LIKE '%1001%')
	BEGIN
		DECLARE @Now INT
		IF EXISTS(SELECT 'x' FROM Oadb..WorkDate WHERE WorkDate = CONVERT(VARCHAR(8), GETDATE(), 112) AND WorkType = 1)
		BEGIN
			SET @Now = DATEPART(HOUR, GETDATE()) * 100 + DATEPART(MINUTE, GETDATE())
			IF @Now BETWEEN 830 AND 1735
				RETURN
			IF @Now BETWEEN 1300 AND 1735
				RETURN
		END		

	--IF EXISTS(SELECT 'x' FROM Inserted WHERE Recipient LIKE '%1112%')-- AND Addresser LIKE '%1001%')
		IF NOT EXISTS(SELECT 'x' FROM SmsMessageLog WHERE Mobile = '13455496132' AND Msg LIKE '企业微信有新消息%' AND AddDate > DATEADD(MINUTE, -2, GETDATE()))
			INSERT INTO SmsMessageLog(SendMan, Mobile, Msg, AddDate, SmsType, MsgType)
			SELECT TOP 1 112, '13455496132', '企业微信有新消息:"' + LEFT(Rtx_Content, 20) + '"'-- + CONVERT(VARCHAR(20), GETDATE(), 120)
				, GETDATE(), 1, 25
			FROM Inserted
	END
END

GO
ALTER TABLE [dbo].[rtx_log] ENABLE TRIGGER [Tri_Rtx_Log_Insert]
GO
/****** Object:  Trigger [dbo].[Tri_SeatStatusInsert]    Script Date: 2018/9/25 12:40:18 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--######################################33
--			Type=1	Type=0
--Status=1	登录1	置忙2
--Status=0	登出0	置闲3
--Sean 2010-11-29
--######################################33
CREATE TRIGGER [dbo].[Tri_SeatStatusInsert]
   ON  [dbo].[SeatStatus]
   AFTER INSERT
AS 
BEGIN
	IF (DATEPART(HOUR, GETDATE()) * 100 + DATEPART(MINUTE, GETDATE()) > 1730) OR (DATEPART(HOUR, GETDATE()) * 100 + DATEPART(MINUTE, GETDATE()) < 830)
		RETURN

	SET NOCOUNT ON;
	DECLARE @StatusType AS VARCHAR(10),
		@State AS TINYINT,
		@Exten AS VARCHAR(10),
		@StatusTime AS DATETIME,
		@Status AS TINYINT,
		@PreStatus AS TINYINT,
		@PreTime AS DATETIME,
		@T AS INT,
		@Today AS VARCHAR(8),
		@ID INT

	SET @Today = CONVERT(VARCHAR(8), GETDATE(), 112)

	SELECT @StatusType = StatusType,
		@State = State,
		@EXten = EXten,
		@StatusTime = StatusTime
	FROM Inserted

	--sean update 2014-11-19
	IF EXISTS(SELECT 'x' FROM SeatStatus WITH(NOLOCK) WHERE Exten = @Exten AND StatusTime > @StatusTime)
		RETURN

	--取得本次状态
	SET @Status =	CASE @StatusType
					WHEN 'login' THEN 
						CASE @State
						WHEN 1 THEN 1
						ELSE 0 END
					ELSE
						CASE @State
						WHEN 1 THEN 2
						ELSE 3 END
					END
	--取得上一次状态
	SELECT @PreStatus = PreStatus, @PreTime = PreTime
	FROM SeatStatusCount WITH(NOLOCK)
	WHERE CountDate = @Today
	AND Exten = @Exten

	IF @PreStatus IS NULL
	BEGIN
		INSERT INTO SeatStatusCount(Exten) VALUES(@Exten)
		SET @PreStatus = 0
		SET @PreTime = GETDATE()
	END
	--去的时间间隔
	SET @T = DATEDIFF(MilliSecond, @PreTime, GETDATE())
	--统计上次状态持续了多长时间
	--0登出
	IF @PreStatus = 0
	BEGIN
		DECLARE @Now AS DATETIME
		SET @Now = GETDATE()
		IF DATEPART(Hour, @PreTime) = 12	--上次时间是在12点
		BEGIN
			IF DATEPART(Hour, @Now) = 12	--当前也是12点，不计算
				SET @PreTime = @Now
			ELSE
				SET @PreTime = CONVERT(VARCHAR(10), @Now, 120) + ' 13:0:0'	--当前>12点，以13点为开始计算
		END
		
		IF DATEPART(Hour, @Now) = 12		--当前是12点
		BEGIN
			IF DATEPART(Hour, @PreTime) = 12	--上次是12点，不计算
				SET @PreTime = @Now
			ELSe
				SET @Now = CONVERT(VARCHAR(10), @Now, 120) + ' 12:0:0'	--上次<12点，计算到12点
		END
		--上次小于12点，本次>12点，则-1小时
		IF DATEPART(Hour, @PreTime) < 12 AND DATEPART(Hour, @Now) > 12
			SET @PreTime = DATEADD(HOUR, 1, @PreTime)

		SET @T = DATEDIFF(MilliSecond, @PreTime, @Now)
		UPDATE SeatStatusCount SET LogoutSecond = LogoutSecond + @T, PreTime = GETDATE(), PreStatus = @Status
		WHERE CountDate = @Today AND Exten = @Exten
	END
	--1登入
	IF @PreStatus = 1
		UPDATE SeatStatusCount SET LoginSecond = LoginSecond + @T, PreTime = GETDATE(), PreStatus = @Status
		WHERE CountDate = @Today AND Exten = @Exten
	--置忙
	ELSE IF @PreStatus = 2
		UPDATE SeatStatusCount SET BusySecond = BusySecond + @T, PreTime = GETDATE(), PreStatus = @Status
		WHERE CountDate = @Today AND Exten = @Exten
	--置闲
	ELSE IF @PreStatus = 3
		UPDATE SeatStatusCount SET IdleSecond = IdleSecond + @T, PreTime = GETDATE(), PreStatus = @Status
		WHERE CountDate = @Today AND Exten = @Exten
END


GO
ALTER TABLE [dbo].[SeatStatus] ENABLE TRIGGER [Tri_SeatStatusInsert]
GO
/****** Object:  Trigger [dbo].[Tri_Servi_Process_Insert]    Script Date: 2018/9/25 12:40:18 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TRIGGER [dbo].[Tri_Servi_Process_Insert]
   ON [dbo].[servi_process]
   AFTER INSERT
AS 
BEGIN
	SET NOCOUNT ON;
	DECLARE @CpMainId INT, @ID INT

	SELECT @cpMainId = CompanyId, @ID = ID FROM Inserted

	UPDATE bsCpOnlineServi SET ServiProcessId = @ID
	WHERE cpMainID = @cpMainID
	AND AddDate > DATEADD(MINUTE, -12, GETDATE())

	UPDATE bsCpOnlineServiLog SET ServiProcessId = @ID
	WHERE cpMainID = @cpMainID
	AND AddDate > DATEADD(MINUTE, -12, GETDATE())
END

GO
ALTER TABLE [dbo].[servi_process] ENABLE TRIGGER [Tri_Servi_Process_Insert]
GO
/****** Object:  Trigger [dbo].[Tri_SmsMessageLog_Update]    Script Date: 2018/9/25 12:40:18 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE TRIGGER [dbo].[Tri_SmsMessageLog_Update]
   ON [dbo].[SmsMessageLog]
   AFTER UPDATE
AS 
BEGIN
	SET NOCOUNT ON;
	IF(SELECT COUNT(*) FROM Inserted) <> 1
		RETURN

	IF EXISTS(SELECT 'x' FROM Inserted WHERE MsgType = 101)
	IF UPDATE(SendStatus)
	BEGIN
		UPDATE a
		SET a.SendStatus = b.SendStatus, a.SendDate = b.SendDate
		FROM caSmsLog a, Inserted b
		WHERE a.SmsMessageLogId = b.Id
	END	
END

GO
ALTER TABLE [dbo].[SmsMessageLog] ENABLE TRIGGER [Tri_SmsMessageLog_Update]
GO
/****** Object:  DdlTrigger [DDL_DatabaseLog]    Script Date: 2018/9/25 12:40:18 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:        <听风吹雨>
-- Create date:    <2013.05.03>
-- Description:    <记录数据库DDL操作>
-- Blog:        <http://www.cnblogs.com/gaizai/>
-- =============================================
CREATE TRIGGER [DDL_DatabaseLog]
ON DATABASE 
FOR DDL_DATABASE_LEVEL_EVENTS AS 
BEGIN
    SET NOCOUNT ON
    DECLARE @data XML, @schema sysname, @object sysname, @eventType sysname
    SET @data = EVENTDATA();
    SELECT @eventType = @data.value('(/EVENT_INSTANCE/EventType)[1]', 'sysname'),
		@schema = @data.value('(/EVENT_INSTANCE/SchemaName)[1]', 'sysname'),
		@object = @data.value('(/EVENT_INSTANCE/ObjectName)[1]', 'sysname') 
    
    /*
	IF @object IS NOT NULL
        PRINT '  ' + @eventType + ' - ' + @schema + '.' + @object;
    ELSE
        PRINT '  ' + @eventType + ' - ' + @schema;
    IF @eventType IS NULL
        PRINT CONVERT(nvarchar(max), @data);
	*/
    INSERT INTO LogDb..DatabaseLog(PostTime, ServerName, LoginName, DatabaseUser, DatabaseName, [Schema], [Object], [TSQL], [Event], XmlEvent)
    VALUES(
        GETDATE(), 
        @data.value('(/EVENT_INSTANCE/ServerName)[1]', 'sysname'), 
        @data.value('(/EVENT_INSTANCE/LoginName)[1]', 'sysname'), 
        CONVERT(sysname, CURRENT_USER),
        @data.value('(/EVENT_INSTANCE/DatabaseName)[1]', 'sysname'),  
        CONVERT(sysname, @schema), 
        CONVERT(sysname, @object), 
        @data.value('(/EVENT_INSTANCE/TSQLCommand)[1]', 'nvarchar(max)'),
        @eventType,  
        @data
        )
END




GO
DISABLE TRIGGER [DDL_DatabaseLog] ON DATABASE
GO
/****** Object:  DdlTrigger [DDL_TableTrigger]    Script Date: 2018/9/25 12:40:18 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--创建DDL触发器：禁止修改或者删除数据表
create TRIGGER [DDL_TableTrigger]
ON DATABASE
FOR CREATE_TABLE, DROP_TABLE, ALTER_TABLE, CREATE_PROCEDURE, ALTER_PROCEDURE, DROP_PROCEDURE,
	CREATE_VIEW, ALTER_VIEW, DROP_VIEW, DROP_SYNONYM, CREATE_SYNONYM, ALTER_FUNCTION, CREATE_FUNCTION, DROP_FUNCTION,
	CREATE_TRIGGER, ALTER_TRIGGER, DROP_TRIGGER
AS
BEGIN
	DECLARE @data XML, @object sysname
    SET @data = EVENTDATA();
    SELECT @object = @data.value('(/EVENT_INSTANCE/ObjectName)[1]', 'sysname') 
	IF CONVERT(sysname, @object) = 'a_tmp'
		RETURN

	PRINT '对不起，您不能对数据表进行操作，请联系DBA'
	ROLLBACK ;
END




GO
DISABLE TRIGGER [DDL_TableTrigger] ON DATABASE
GO
ENABLE TRIGGER [DDL_TableTrigger] ON DATABASE
GO
EXEC [MainDB].sys.sp_addextendedproperty @name=N'MS_Description', @value=N'1 关注的企业新发布职位
	--2 关注的企业新发布点评
	--3 关注的企业新发布面经 
	--4 关注的职位24小时截止
	' 
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'1首页banner；2首页大通体广告；3漂浮广告；4页面两侧广告位；5首页小通体广告；6首页弹出窗口；7背景音乐；8首页LOGO固定；9切换图片广告；10首页横排图片；11首页顶部横排广告;12公司职位页面广告;13置顶浮动广告;14左侧浮动广告;15右下角浮动广告' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'AdverProject', @level2type=N'COLUMN',@level2name=N'Type'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'省份' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'AdverProject', @level2type=N'COLUMN',@level2name=N'Province_Id'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'图像文件名，可以是swf,jpg,gif格式，自动判断格式' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'AdverProject', @level2type=N'COLUMN',@level2name=N'ImageFile'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'边框厚度' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'AdverProject', @level2type=N'COLUMN',@level2name=N'BOrder'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'链接地址' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'AdverProject', @level2type=N'COLUMN',@level2name=N'Url'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'像素宽度' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'AdverProject', @level2type=N'COLUMN',@level2name=N'Width'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'像素高度' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'AdverProject', @level2type=N'COLUMN',@level2name=N'Height'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'是否出现滚动条。0不出现；1出现' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'AdverProject', @level2type=N'COLUMN',@level2name=N'ScrollBar'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'距左距离' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'AdverProject', @level2type=N'COLUMN',@level2name=N'LeftMargin'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'距上距离' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'AdverProject', @level2type=N'COLUMN',@level2name=N'TopMargin'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'点击数' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'AdverProject', @level2type=N'COLUMN',@level2name=N'ClickCount'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'是否有关闭按钮。0，没有；1，有' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'AdverProject', @level2type=N'COLUMN',@level2name=N'CloseButton'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'是否跟屏。0，不跟；1，跟' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'AdverProject', @level2type=N'COLUMN',@level2name=N'FollowScreen'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'关闭按钮位置。0，在上方；1，在下方。' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'AdverProject', @level2type=N'COLUMN',@level2name=N'CloseButtonPosition'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'是否正常。1，正常；0，暂停' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'AdverProject', @level2type=N'COLUMN',@level2name=N'Valid'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'背景音乐循环播放次数' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'AdverProject', @level2type=N'COLUMN',@level2name=N'Loop'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'显示序号' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'AdverProject', @level2type=N'COLUMN',@level2name=N'Orderby'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'广告计划' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'AdverProject'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'答案' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Answer', @level2type=N'COLUMN',@level2name=N'Answer'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'辅助答案' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Answer', @level2type=N'COLUMN',@level2name=N'Assist'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'回答人ID,有可能是个人,也有可能是单位' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Answer', @level2type=N'COLUMN',@level2name=N'ManId'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'1南方，2北方，3山东，4上海' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'ass_consultant', @level2type=N'COLUMN',@level2name=N'dcgroup'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'邀请的邮箱' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'assessCpInvite', @level2type=N'COLUMN',@level2name=N'Email'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'当前测评状态 0 等待测评 1过期 2重新启动的测评' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'assessCpInvite', @level2type=N'COLUMN',@level2name=N'Status'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'关联属于哪个测评分组的维度信息' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'assessDimension', @level2type=N'COLUMN',@level2name=N'AssessDimensionGroupID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'添加人' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'assessDimension', @level2type=N'COLUMN',@level2name=N'AddMan'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'属于哪个测评' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'assessDimensionGroup', @level2type=N'COLUMN',@level2name=N'AssessTypeID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'题目ID 关联assessQuestion 的ID' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'assessOptions', @level2type=N'COLUMN',@level2name=N'AssessQuestionID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'选项（回答）' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'assessOptions', @level2type=N'COLUMN',@level2name=N'Options'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'选项得分' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'assessOptions', @level2type=N'COLUMN',@level2name=N'Score'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'排序' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'assessOptions', @level2type=N'COLUMN',@level2name=N'SortNo'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'添加人' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'assessOptions', @level2type=N'COLUMN',@level2name=N'AddMan'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'从属于哪个大题' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'assessQuestion', @level2type=N'COLUMN',@level2name=N'AssessThemeID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'问题内容' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'assessQuestion', @level2type=N'COLUMN',@level2name=N'Question'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'附属文件' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'assessQuestion', @level2type=N'COLUMN',@level2name=N'AttachmentFile'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'排序' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'assessQuestion', @level2type=N'COLUMN',@level2name=N'SortNo'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'0 示例问题 1 普通问题' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'assessQuestion', @level2type=N'COLUMN',@level2name=N'QuestionType'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'选项排序方式 0 默认排序 1 随机排序' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'assessQuestion', @level2type=N'COLUMN',@level2name=N'OptionsSort'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'若为维度性的问题，关联维度分组' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'assessQuestion', @level2type=N'COLUMN',@level2name=N'AssessDimensionGroupID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'添加人' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'assessQuestion', @level2type=N'COLUMN',@level2name=N'AddMan'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'测评类型' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'assessTestLog', @level2type=N'COLUMN',@level2name=N'AssessTypeID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'如果是邀请的话 关联的邀请ID' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'assessTestLog', @level2type=N'COLUMN',@level2name=N'AssessCpInviteID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'剩余测评时间，单位秒' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'assessTestLog', @level2type=N'COLUMN',@level2name=N'RemainSeconds'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'离开次数' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'assessTestLog', @level2type=N'COLUMN',@level2name=N'LeaveTimes'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'当前状态： 0未结束   1正常结束 2.异常结束' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'assessTestLog', @level2type=N'COLUMN',@level2name=N'Status'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'关联assessType中的ID列 评测类型ID' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'assessTheme', @level2type=N'COLUMN',@level2name=N'AssessTypeID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'题目标题' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'assessTheme', @level2type=N'COLUMN',@level2name=N'Title'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'题目简介' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'assessTheme', @level2type=N'COLUMN',@level2name=N'Summary'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'额外材料，譬如材料理解' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'assessTheme', @level2type=N'COLUMN',@level2name=N'Material'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'提示信息' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'assessTheme', @level2type=N'COLUMN',@level2name=N'Notice'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'问题类型，单选，多选，判断等等 关联assessThemeType列 决定问题回答方式' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'assessTheme', @level2type=N'COLUMN',@level2name=N'AssessThemeTypeID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'排序' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'assessTheme', @level2type=N'COLUMN',@level2name=N'SortNo'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'子问题排序方式 0 默认排序 1 随机排序' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'assessTheme', @level2type=N'COLUMN',@level2name=N'SortType'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'添加人' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'assessTheme', @level2type=N'COLUMN',@level2name=N'AddMan'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'添加时间' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'assessTheme', @level2type=N'COLUMN',@level2name=N'AddDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'问题类型名称' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'assessThemeType', @level2type=N'COLUMN',@level2name=N'Name'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'默认名称  在后台添加问题大题的时候选择好题目类型，会将此标题默认填入' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'assessThemeType', @level2type=N'COLUMN',@level2name=N'DefaultTitle'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'默认名称  在后台添加问题大题的时候选择好题目类型，会将此简介默认填入' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'assessThemeType', @level2type=N'COLUMN',@level2name=N'DefaultSummary'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'默认名称  在后台添加问题大题的时候选择好题目类型，会将此简介默认填入' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'assessThemeType', @level2type=N'COLUMN',@level2name=N'DefaultNotice'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'问题类型说明' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'assessThemeType', @level2type=N'COLUMN',@level2name=N'Summary'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'添加人' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'assessThemeType', @level2type=N'COLUMN',@level2name=N'AddMan'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'测评结果评分标准' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'assessThemeType'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'测评类型名称' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'assessType', @level2type=N'COLUMN',@level2name=N'Name'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'对应的图片文件名' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'assessType', @level2type=N'COLUMN',@level2name=N'ImgUrl'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'测评需要时间 单位分钟' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'assessType', @level2type=N'COLUMN',@level2name=N'NeedTime'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'多久后可再次测评。 单位天 默认30' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'assessType', @level2type=N'COLUMN',@level2name=N'ReTestDay'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'测评说明' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'assessType', @level2type=N'COLUMN',@level2name=N'Summary'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'测评提示内容 ' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'assessType', @level2type=N'COLUMN',@level2name=N'Notice'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'测评次数' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'assessType', @level2type=N'COLUMN',@level2name=N'UseCount'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'排序顺序' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'assessType', @level2type=N'COLUMN',@level2name=N'SortNo'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'结果类型 0 计分式，1文本式' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'assessType', @level2type=N'COLUMN',@level2name=N'ResultType'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'添加人' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'assessType', @level2type=N'COLUMN',@level2name=N'AddMan'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'添加时间' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'assessType', @level2type=N'COLUMN',@level2name=N'AddDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'关联的的测评类型' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'assessTypeResult', @level2type=N'COLUMN',@level2name=N'AssessTypeID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'测试结果标题' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'assessTypeResult', @level2type=N'COLUMN',@level2name=N'Title'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'测评结果最低分' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'assessTypeResult', @level2type=N'COLUMN',@level2name=N'MinScore'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'如果测评结果为分数 则分数的最高分' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'assessTypeResult', @level2type=N'COLUMN',@level2name=N'MaxScore'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'文字类型的测评结果 标准' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'assessTypeResult', @level2type=N'COLUMN',@level2name=N'TextResult'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'测评结果附件' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'assessTypeResult', @level2type=N'COLUMN',@level2name=N'AttachmentFile'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'添加人' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'assessTypeResult', @level2type=N'COLUMN',@level2name=N'AddMan'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'null,新加未处理；1，email重复；2，已增加；3，email错误' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'b_resume', @level2type=N'COLUMN',@level2name=N'deleted'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'审核通过的简历数' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'BackData', @level2type=N'COLUMN',@level2name=N'Resume_Pass'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'删除的简历数' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'BackData', @level2type=N'COLUMN',@level2name=N'Resume_Delete'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'审核不通过的简历数' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'BackData', @level2type=N'COLUMN',@level2name=N'Resume_NoPass'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'修改的简历数' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'BackData', @level2type=N'COLUMN',@level2name=N'Resume_Modify'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'修改的照片数' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'BackData', @level2type=N'COLUMN',@level2name=N'Photo_Modify'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'删除的照片数' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'BackData', @level2type=N'COLUMN',@level2name=N'Photo_Delete'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'修改的证书数' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'BackData', @level2type=N'COLUMN',@level2name=N'Appendix_Modify'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'删除的证书数' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'BackData', @level2type=N'COLUMN',@level2name=N'Appendix_Delete'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'审核通过的LogO' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'BackData', @level2type=N'COLUMN',@level2name=N'CompanyLogo_Pass'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'删除的公司LogO' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'BackData', @level2type=N'COLUMN',@level2name=N'CompanyLogo_Delete'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'审核通过的高级简历' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'BackData', @level2type=N'COLUMN',@level2name=N'High_Resume_Pass'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'高级人才审核不通过' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'BackData', @level2type=N'COLUMN',@level2name=N'High_Resume_NoPass'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'处理黑名单' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'BackData', @level2type=N'COLUMN',@level2name=N'Black'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'租户id' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'BeiSenAds', @level2type=N'COLUMN',@level2name=N'TenantId'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'职位广告id' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'BeiSenAds', @level2type=N'COLUMN',@level2name=N'JobAdId'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'职位名称' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'BeiSenAds', @level2type=N'COLUMN',@level2name=N'JobAdName'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'职位类别' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'BeiSenAds', @level2type=N'COLUMN',@level2name=N'JobType'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'工作地区' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'BeiSenAds', @level2type=N'COLUMN',@level2name=N'LocID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'薪资范围' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'BeiSenAds', @level2type=N'COLUMN',@level2name=N'Salary'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'学历 ' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'BeiSenAds', @level2type=N'COLUMN',@level2name=N'Degree'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'工作年限' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'BeiSenAds', @level2type=N'COLUMN',@level2name=N'YearsofWorking'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'广告截止日期' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'BeiSenAds', @level2type=N'COLUMN',@level2name=N'EndTime'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'转发邮箱' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'BeiSenAds', @level2type=N'COLUMN',@level2name=N'Email'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'广告状态' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'BeiSenAds', @level2type=N'COLUMN',@level2name=N'Status'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'广告创建时间' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'BeiSenAds', @level2type=N'COLUMN',@level2name=N'CreateDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'广告修改时间' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'BeiSenAds', @level2type=N'COLUMN',@level2name=N'ModifiedDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'租户id' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'BeiSenCompany', @level2type=N'COLUMN',@level2name=N'TenantId'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'问题' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'bsASKInfo', @level2type=N'COLUMN',@level2name=N'Question'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'最佳答案' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'bsASKInfo', @level2type=N'COLUMN',@level2name=N'Answer'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'所属分类' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'bsASKInfo', @level2type=N'COLUMN',@level2name=N'TypeID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'标签' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'bsASKInfo', @level2type=N'COLUMN',@level2name=N'Mark'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'备注' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'bsASKInfo', @level2type=N'COLUMN',@level2name=N'Comment'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'最后解决时间' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'bsASKInfo', @level2type=N'COLUMN',@level2name=N'SolveDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'是否上线' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'bsASKInfo', @level2type=N'COLUMN',@level2name=N'IsOnline'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'工作人员的修改时间' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'bsASKInfo', @level2type=N'COLUMN',@level2name=N'UpdateDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'上线线的省份：,10,11,12,32,' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'bsASKInfo', @level2type=N'COLUMN',@level2name=N'ProvinceIds'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'1手工录入；0 采集获得' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'bsASKInfo', @level2type=N'COLUMN',@level2name=N'GetWay'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'参考网址' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'bsASKInfo', @level2type=N'COLUMN',@level2name=N'ReferUrl'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'所属站点url' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'bsASKSiteClass', @level2type=N'COLUMN',@level2name=N'Weburl'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'站点名称' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'bsASKSiteClass', @level2type=N'COLUMN',@level2name=N'ClassName'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N' 所取栏目url地址' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'bsASKSiteClass', @level2type=N'COLUMN',@level2name=N'ClassUrl'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'列表开始标签' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'bsASKSiteClass', @level2type=N'COLUMN',@level2name=N'startHtml'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'1:百度问答；' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'bsBackLogin', @level2type=N'COLUMN',@level2name=N'funType'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'公司ID 对应cpMain.ID' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'bsConsultantList', @level2type=N'COLUMN',@level2name=N'cpMainID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Vip类型 汉字' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'bsConsultantList', @level2type=N'COLUMN',@level2name=N'VipType'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'服务到期时间（VIP  储值  正式）' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'bsConsultantList', @level2type=N'COLUMN',@level2name=N'ServiceEndDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'下载简历数（VIP）' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'bsConsultantList', @level2type=N'COLUMN',@level2name=N'RemainQuotaSum'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Vip套餐余额  剩余月数' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'bsConsultantList', @level2type=N'COLUMN',@level2name=N'VipMonth'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'最后一次订单开通时间' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'bsConsultantList', @level2type=N'COLUMN',@level2name=N'caOrderLastOpenDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'最后一次联系时间' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'bsConsultantList', @level2type=N'COLUMN',@level2name=N'ContactLastCloseDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'营业执照审核时间' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'bsConsultantList', @level2type=N'COLUMN',@level2name=N'LicenceVerifyDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'今天简历消费 （正式）（储值）' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'bsConsultantList', @level2type=N'COLUMN',@level2name=N'caCvQuotaCount'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'限制登录时间' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'bsConsultantList', @level2type=N'COLUMN',@level2name=N'bsCpStatusAddDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'最后一次完成联系时间' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'bsConsultantList', @level2type=N'COLUMN',@level2name=N'LastContactDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'今天简历下载数VIP' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'bsConsultantList', @level2type=N'COLUMN',@level2name=N'caActiveCount'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'单位点击资费标准时间' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'bsConsultantList', @level2type=N'COLUMN',@level2name=N'caFeePageViewAddDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'后台登录唯一码' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'bsCpBackLogin', @level2type=N'COLUMN',@level2name=N'UnqueID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'是否已登录' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'bsCpBackLogin', @level2type=N'COLUMN',@level2name=N'HasLogin'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'后台企业登录表，用于验证身份' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'bsCpBackLogin'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'审核位置编号，详见《个人企业审核、状态、操作编号.xls》' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'bsCpModify', @level2type=N'COLUMN',@level2name=N'Location'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'字段内容' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'bsCpModify', @level2type=N'COLUMN',@level2name=N'ColValue'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'审核信息，不通过时填写' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'bsCpModify', @level2type=N'COLUMN',@level2name=N'VerifyInfo'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'状态编号，详见《个人企业审核、状态、操作编号.xls》' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'bsCpStatus', @level2type=N'COLUMN',@level2name=N'StatusID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'申请信息，改变状态的原因' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'bsCpStatus', @level2type=N'COLUMN',@level2name=N'ApplyInfo'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'审核通过，null-未审核；0-未通过；1-通过审核' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'bsCpStatus', @level2type=N'COLUMN',@level2name=N'HasPassed'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'审核人' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'bsCpStatus', @level2type=N'COLUMN',@level2name=N'VerifyMan'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'审核信息，不通过时填写' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'bsCpStatus', @level2type=N'COLUMN',@level2name=N'VerifyInfo'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'审核日期' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'bsCpStatus', @level2type=N'COLUMN',@level2name=N'VerifyDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'审核人' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'bsCpVerify', @level2type=N'COLUMN',@level2name=N'VerifyMan'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'审核时间' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'bsCpVerify', @level2type=N'COLUMN',@level2name=N'VerifyDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'10 审核不通过，1审核通过' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'bsCpVerify', @level2type=N'COLUMN',@level2name=N'VerifyResult'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'详细' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'bsCpVerify', @level2type=N'COLUMN',@level2name=N'VerifyInfo'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'字段内容' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'bsCpVerifyLog', @level2type=N'COLUMN',@level2name=N'OldValue'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'审核结果， 1 通过 0 不通过' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'bsCpVerifyLog', @level2type=N'COLUMN',@level2name=N'VerifyResult'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'不通过原因' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'bsCpVerifyLog', @level2type=N'COLUMN',@level2name=N'VerifyInfo'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'字段内容' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'bsCvModify', @level2type=N'COLUMN',@level2name=N'ColValue'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'审核信息，不通过时填写' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'bsCvModify', @level2type=N'COLUMN',@level2name=N'VerifyInfo'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'提交人' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'bsCvReview', @level2type=N'COLUMN',@level2name=N'VerifyMan'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'原因' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'bsCvReview', @level2type=N'COLUMN',@level2name=N'VerifyInfo'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'后台，简历审核，提交上级查看表' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'bsCvReview'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'审核人' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'bsCvVerify', @level2type=N'COLUMN',@level2name=N'VerifyMan'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'审核时间' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'bsCvVerify', @level2type=N'COLUMN',@level2name=N'VerifyDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'审核结果　1 审核通过，10 审核不通过，8 有问题' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'bsCvVerify', @level2type=N'COLUMN',@level2name=N'VerifyResult'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'审核不通过原因' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'bsCvVerify', @level2type=N'COLUMN',@level2name=N'VerifyInfo'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'后台，简历审核表' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'bsCvVerify'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'审核字段' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'bsCvVerifyLog', @level2type=N'COLUMN',@level2name=N'OldValue'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'审核结果，1 审核通过，2 审核不通过' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'bsCvVerifyLog', @level2type=N'COLUMN',@level2name=N'VerifyResult'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'审核不通过原因' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'bsCvVerifyLog', @level2type=N'COLUMN',@level2name=N'VerifyInfo'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'后台，简历审核记录表' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'bsCvVerifyLog'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'0.未联系，1.有效，2无效，3.空号，4.关机，5挂机，6.稍后联系' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'bsDeadCompany', @level2type=N'COLUMN',@level2name=N'ContactResult'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'1、照片；2、证书；3、word附件；4处理的照片；10、营业执照；11、logo；12、形象图；20：order.RemittanceFile；21：Order.ContractFile；22：FaxFile
40:adverproject;
51、OaDb..LeaveAttchment；52：文档管理' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'bsDeleteFile', @level2type=N'COLUMN',@level2name=N'FileType'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'问题原因' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'bsJobProblem', @level2type=N'COLUMN',@level2name=N'Reason'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'后台，职位审核，问题职位' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'bsJobProblem'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'操作内容' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'bsManagerUserAction', @level2type=N'COLUMN',@level2name=N'Action'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'操作原因' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'bsManagerUserAction', @level2type=N'COLUMN',@level2name=N'Reason'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'后台，员工对企业的操作记录表' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'bsManagerUserAction'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'短信内容' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'bsMobileMessage', @level2type=N'COLUMN',@level2name=N'Message'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'生效时间' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'bsMobileMessage', @level2type=N'COLUMN',@level2name=N'BeginDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'失效时间' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'bsMobileMessage', @level2type=N'COLUMN',@level2name=N'EndDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'添加人' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'bsMobileMessage', @level2type=N'COLUMN',@level2name=N'AddMan'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'添加时间' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'bsMobileMessage', @level2type=N'COLUMN',@level2name=N'AddDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'fasongcishu' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'bsMobileSpread', @level2type=N'COLUMN',@level2name=N'SendTime'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'唯一码' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'bsPaBackLogin', @level2type=N'COLUMN',@level2name=N'UnqueID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'是否登录过' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'bsPaBackLogin', @level2type=N'COLUMN',@level2name=N'HasLogin'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'后台，登录个人用户表，用于验证身份' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'bsPaBackLogin'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'1百度搜索 2 google搜索 3live搜索 4 sogou搜索 5 网易有道搜索、6soso、	7  360搜索、8 神马搜索、9  bing搜索  10 外部链接 11 外部链接其他' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'bsSourceRefererCount', @level2type=N'COLUMN',@level2name=N'TypeID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'1电脑 2手机' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'bsSourceRefererCount', @level2type=N'COLUMN',@level2name=N'SiteType'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'正数是简历id；负数时系统自动扣除，因为唯一索引所以使用负数' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caActiveLog', @level2type=N'COLUMN',@level2name=N'cvMainID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'使用的订单编号' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caActiveLog', @level2type=N'COLUMN',@level2name=N'caOrderId'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'如果=“每月扣除”，则是计划任务自动扣除的' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caActiveLog', @level2type=N'COLUMN',@level2name=N'IP'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'剩余可用的简历下载' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caActiveLog', @level2type=N'COLUMN',@level2name=N'RemainQuota'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'前台，企业，简历下载消费记录' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caActiveLog'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'是否是代理招聘单位,0不是代理，1代理' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caBalanceLog', @level2type=N'COLUMN',@level2name=N'IsAgent'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'消费的钱数' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caBalanceLog', @level2type=N'COLUMN',@level2name=N'ReduceMoney'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'余额' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caBalanceLog', @level2type=N'COLUMN',@level2name=N'Balance'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'1,看简历联系方式；2,看照片；5,看留言；6,发留言;7,下载文档;8,面试通知;9,查看求职信' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caBalanceLog', @level2type=N'COLUMN',@level2name=N'BalanceType'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'前台，企业，储值会员消费记录表' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caBalanceLog'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'期望职位类别编号' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caCvFinder', @level2type=N'COLUMN',@level2name=N'dcJobTypeID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'期望工作地点编号' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caCvFinder', @level2type=N'COLUMN',@level2name=N'dcRegionID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'期望从事行业' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caCvFinder', @level2type=N'COLUMN',@level2name=N'dcIndustryID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'期望月薪' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caCvFinder', @level2type=N'COLUMN',@level2name=N'dcSalaryID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'曾从事职位' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caCvFinder', @level2type=N'COLUMN',@level2name=N'dcJobTypeIDOld'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'曾从事行业' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caCvFinder', @level2type=N'COLUMN',@level2name=N'dcIndustryIDOld'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'工作经验' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caCvFinder', @level2type=N'COLUMN',@level2name=N'MinExperience'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'关键字' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caCvFinder', @level2type=N'COLUMN',@level2name=N'KeyWord'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'下属人数' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caCvFinder', @level2type=N'COLUMN',@level2name=N'SubNodeNum'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'学历' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caCvFinder', @level2type=N'COLUMN',@level2name=N'Education'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'是否统招' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caCvFinder', @level2type=N'COLUMN',@level2name=N'Standard'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'学校名称' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caCvFinder', @level2type=N'COLUMN',@level2name=N'EducationName'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'所学专业' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caCvFinder', @level2type=N'COLUMN',@level2name=N'dcMajorID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'语种' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caCvFinder', @level2type=N'COLUMN',@level2name=N'LanguageType'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'性别' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caCvFinder', @level2type=N'COLUMN',@level2name=N'Gender'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'年龄限制－最低' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caCvFinder', @level2type=N'COLUMN',@level2name=N'MinAge'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'年龄限制－最高' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caCvFinder', @level2type=N'COLUMN',@level2name=N'MaxAge'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'当前居住地' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caCvFinder', @level2type=N'COLUMN',@level2name=N'LivePlace'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'户口所在地' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caCvFinder', @level2type=N'COLUMN',@level2name=N'AccountPlace'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'0 更新时间 1 登录时间' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caCvFinder', @level2type=N'COLUMN',@level2name=N'SortType'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'简历编号' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caCvFinder', @level2type=N'COLUMN',@level2name=N'cvMainID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'前台，企业用户搜索器表' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caCvFinder'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'NULL未回复 0 不感兴趣 1 感兴趣 2个人没回复直接删除' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caCvIntention', @level2type=N'COLUMN',@level2name=N'Reply'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'前台，企业使用配额记录' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caCvQuotaLog'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'评语' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caCvRemark', @level2type=N'COLUMN',@level2name=N'Remark'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'前台，企业用户对简历的评语' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caCvRemark'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'前台，企业查看简历记录' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caCvViewLog'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'前台，企业使用每日赠送的简历下载记录' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caDailyGiftLog'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'企业用户对简历的标签的编号' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caFavorate', @level2type=N'COLUMN',@level2name=N'caFavorateMarkID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'收藏时间' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caFavorate', @level2type=N'COLUMN',@level2name=N'AddDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'前台 企业用户对简历的收藏记录' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caFavorate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'标签名称' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caFavorateMark', @level2type=N'COLUMN',@level2name=N'Mark'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'前台，企业的标签表，可以为收藏的简历添加标签' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caFavorateMark'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'反馈人姓名' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caFeedback', @level2type=N'COLUMN',@level2name=N'Name'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'反馈人电话' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caFeedback', @level2type=N'COLUMN',@level2name=N'Telephone'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'反馈信息' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caFeedback', @level2type=N'COLUMN',@level2name=N'Message'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'是否答复' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caFeedback', @level2type=N'COLUMN',@level2name=N'IsReply'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'答复信息' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caFeedback', @level2type=N'COLUMN',@level2name=N'ReplyMessage'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'答复时间' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caFeedback', @level2type=N'COLUMN',@level2name=N'ReplyDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'答复人' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caFeedback', @level2type=N'COLUMN',@level2name=N'ReplyMan'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'用户是否查看' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caFeedback', @level2type=N'COLUMN',@level2name=N'ViewDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'是否放到首页' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caFeedback', @level2type=N'COLUMN',@level2name=N'HomePage'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'前台，企业对网站的反馈信息表' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caFeedback'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'申请VIP套餐页面:1;购买简历下载页面:2;购买职位发布页面:3;购买用户数页面:4;申请名企招聘页面:5;购买广告位页面:6;资费标准:7' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caFeePageViewLog', @level2type=N'COLUMN',@level2name=N'FeePageID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'取回密码使用的用户名' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caGetPasswordLog', @level2type=N'COLUMN',@level2name=N'UserNameIn'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'取回密码使用的邮箱' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caGetPasswordLog', @level2type=N'COLUMN',@level2name=N'EmailIn'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'前台，企业用户取回密码记录表' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caGetPasswordLog'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'模版标题' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caInterviewTemplate', @level2type=N'COLUMN',@level2name=N'Title'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'面试时间' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caInterviewTemplate', @level2type=N'COLUMN',@level2name=N'InterviewDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'面试地点' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caInterviewTemplate', @level2type=N'COLUMN',@level2name=N'InterViewPlace'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'联系人' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caInterviewTemplate', @level2type=N'COLUMN',@level2name=N'LinkMan'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'联系电话' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caInterviewTemplate', @level2type=N'COLUMN',@level2name=N'Telephone'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'通知备注' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caInterviewTemplate', @level2type=N'COLUMN',@level2name=N'Remark'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'前台，企业用户的面试通知模版表，发送面试通知时可以选择模版' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caInterviewTemplate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'企业名称' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caLoginLog', @level2type=N'COLUMN',@level2name=N'cpMainName'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'用户名称' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caLoginLog', @level2type=N'COLUMN',@level2name=N'caMainName'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'唯一码' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caLoginLog', @level2type=N'COLUMN',@level2name=N'LoginCookies'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'浏览器的版本' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caLoginLog', @level2type=N'COLUMN',@level2name=N'Browser'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'前台，企业用户登录日志表' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caLoginLog'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'注册日期' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caMain', @level2type=N'COLUMN',@level2name=N'RegDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'外键' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caMain', @level2type=N'COLUMN',@level2name=N'cpMainID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'1系统管理员；2普通会员' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caMain', @level2type=N'COLUMN',@level2name=N'AccountType'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'用户名,区分大小写' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caMain', @level2type=N'COLUMN',@level2name=N'UserName'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'用户名,不区分大小写,不做转换' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caMain', @level2type=N'COLUMN',@level2name=N'UserNameLower'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'密码,不区分大小写' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caMain', @level2type=N'COLUMN',@level2name=N'Password'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'姓名' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caMain', @level2type=N'COLUMN',@level2name=N'Name'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'性别,0男，1女' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caMain', @level2type=N'COLUMN',@level2name=N'Gender'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'职务' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caMain', @level2type=N'COLUMN',@level2name=N'Title'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'部门' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caMain', @level2type=N'COLUMN',@level2name=N'Dept'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'电话' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caMain', @level2type=N'COLUMN',@level2name=N'Telephone'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'手机号' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caMain', @level2type=N'COLUMN',@level2name=N'Mobile'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'传真' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caMain', @level2type=N'COLUMN',@level2name=N'Fax'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Email' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caMain', @level2type=N'COLUMN',@level2name=N'EMail'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'是否隐藏电话,0不隐藏，1隐藏' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caMain', @level2type=N'COLUMN',@level2name=N'IsPhoneHide'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'是否隐藏姓名,0不隐藏，1隐藏' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caMain', @level2type=N'COLUMN',@level2name=N'IsNameHide'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'是否隐藏手机,0不隐藏，1隐藏' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caMain', @level2type=N'COLUMN',@level2name=N'IsMobileHide'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'邮件订阅。0,不发送;1,每天发送;2,每周发送 ' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caMain', @level2type=N'COLUMN',@level2name=N'EmailSentType'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'是否暂停，0-正常；1-暂停' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caMain', @level2type=N'COLUMN',@level2name=N'IsPause'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'是否删除，0否，1是。晚上批量删除' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caMain', @level2type=N'COLUMN',@level2name=N'IsDelete'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'最后修改日期,用户信息修改' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caMain', @level2type=N'COLUMN',@level2name=N'LastModifyDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'0全职 1 兼职' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'CampusRecruitold', @level2type=N'COLUMN',@level2name=N'type'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'是否在面试室' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'CaOnline', @level2type=N'COLUMN',@level2name=N'IsVi'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'是否有面试计划' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'CaOnline', @level2type=N'COLUMN',@level2name=N'ViPlanId'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'面试时间' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'CaOnline', @level2type=N'COLUMN',@level2name=N'InterviewDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'操作类型，见附件<个人会员操作表>' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caOperationLog', @level2type=N'COLUMN',@level2name=N'Operation'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'操作说明' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caOperationLog', @level2type=N'COLUMN',@level2name=N'Details'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'前台，企业用户操作记录表' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caOperationLog'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'省份ID，在统计各地区销售额时用到' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caOrder', @level2type=N'COLUMN',@level2name=N'ProvinceID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'0,订单添加;2,已上传汇款凭证未开通;4,已开通未到帐;6,款已到帐未索取发票;8,确认不需要发票，流程结束;10,已索要发票未确认;12,发票已确认未开出;14,已开票未邮寄;16,发票已邮寄未签收;18,发票已签收，流程结束' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caOrder', @level2type=N'COLUMN',@level2name=N'OrderStatus'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'购买订单时，套餐相关编号。旧的定单为空。ordertype=8(VIP) 跟dcVipDetail关联，ordertype<>8(不是VIP) 跟dcFeeDetail关联' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caOrder', @level2type=N'COLUMN',@level2name=N'dcFeeDetailID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'服务类型(原howlong)，和OrderType相关。如果OrderType=1（正式会员），ServiceType=1：月度会员、2：季度会员、3：半年度、4：年度、100：1周会员（免费赠送）；OrderType=4（图片广告），ServiceType=1-5（A-E类广告）、6：1/6、7：2/6、8：3/6、9：6/6、10：2/6 × 2' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caOrder', @level2type=N'COLUMN',@level2name=N'ServiceType'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'放置周数，图片广告、固定位置。原getresume' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caOrder', @level2type=N'COLUMN',@level2name=N'PlaceWeek'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'付款方式，dcPayMethod' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caOrder', @level2type=N'COLUMN',@level2name=N'PayMethod'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'订单类型，原（OrderType）。1-无限制；2储值；3:单个简历（无）；4图片广告；5：高级企业会员（无）；6：单个高级人才（无）；7：固定位置；8：vip套餐；9：主动下载；10：职位发布；11：用户数量；12：职位置顶' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caOrder', @level2type=N'COLUMN',@level2name=N'OrderType'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'应收金额，原premoney' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caOrder', @level2type=N'COLUMN',@level2name=N'Accounts'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'实收金额，原DisCount' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caOrder', @level2type=N'COLUMN',@level2name=N'Paid'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'储值会员加值后当时余额。全部到期后可以删除该字段' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caOrder', @level2type=N'COLUMN',@level2name=N'Balance'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'ordertype为VIP或简历下载有效。该订单总的简历主动下载配额，新版有效。值不变。' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caOrder', @level2type=N'COLUMN',@level2name=N'ActiveQuota'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'ordertype为VIP或简历下载有效。该订单剩余简历主动下载配额。每次减1。初始值=ActiveQuota' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caOrder', @level2type=N'COLUMN',@level2name=N'RemainQuota'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'ordertype为VIP或购买用户数有效。新版有效。值不变。' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caOrder', @level2type=N'COLUMN',@level2name=N'UserNumber'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'ordertype为VIP或购买职位有效。新版有效。值不变。' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caOrder', @level2type=N'COLUMN',@level2name=N'JobNumber'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'主合同ID，购买简历下载、用户数、职位数三种定单有效。其他为Null' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caOrder', @level2type=N'COLUMN',@level2name=N'MainOrderID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'联系人，提交定单时生成' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caOrder', @level2type=N'COLUMN',@level2name=N'LinkMan'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'联系人手机号，提交定单时生成' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caOrder', @level2type=N'COLUMN',@level2name=N'Telephone'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'联系备注，提交定单时生成' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caOrder', @level2type=N'COLUMN',@level2name=N'LinkRemark'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'null 未索取；0 确定不要发票；1 要发票（invoice,0-->null,1-->1，2-->0）' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caOrder', @level2type=N'COLUMN',@level2name=N'NeedInvoice'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'发票邮寄地址(索取发票时填充)' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caOrder', @level2type=N'COLUMN',@level2name=N'MailAddress'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'发票抬头(索取发票时填充)' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caOrder', @level2type=N'COLUMN',@level2name=N'InvoiceTitle'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'发票邮寄接收人(索取发票时填充)' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caOrder', @level2type=N'COLUMN',@level2name=N'Recipient'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'邮编(索取发票时填充)' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caOrder', @level2type=N'COLUMN',@level2name=N'Zip'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'邮寄时对方的电话(索取发票时填充)' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caOrder', @level2type=N'COLUMN',@level2name=N'PostTelephone'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'汇款单传真的图像文件(客户前台上传汇款单文件)' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caOrder', @level2type=N'COLUMN',@level2name=N'FaxFile'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'公司名称（提交定单时生成，与发票抬头无关）' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caOrder', @level2type=N'COLUMN',@level2name=N'CompanyName'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'汇款凭证图像文件，与RemittanceDate成对出现' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caOrder', @level2type=N'COLUMN',@level2name=N'RemittanceFile'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'汇款凭证处理时间' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caOrder', @level2type=N'COLUMN',@level2name=N'RemittanceDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'款到张确认人，与ReceiveDate成对出现' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caOrder', @level2type=N'COLUMN',@level2name=N'ReceiveMan'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'款到张日期' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caOrder', @level2type=N'COLUMN',@level2name=N'ReceiveDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'发送汇款方式短信次数，最多3次' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caOrder', @level2type=N'COLUMN',@level2name=N'SmsMobileNumber'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'结算月份,201106，' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caOrder', @level2type=N'COLUMN',@level2name=N'InvoiceMonth'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'开发票的公司，1-伯乐；2-网聚；3-良禽；4-助择' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caOrder', @level2type=N'COLUMN',@level2name=N'InvoiceCompany'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'发票信息确认时间' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caOrder', @level2type=N'COLUMN',@level2name=N'InvoiceConfirmDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'发票信息确认人' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caOrder', @level2type=N'COLUMN',@level2name=N'InvoiceConfirmMan'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'索取发票时间' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caOrder', @level2type=N'COLUMN',@level2name=N'InvoiceAskDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'合同文件,签定合同后上传扫描件' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caOrder', @level2type=N'COLUMN',@level2name=N'ContractFile'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'招聘顾问' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caOrder', @level2type=N'COLUMN',@level2name=N'Manageruserid'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'已删除,0未删除，1已删除' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caOrder', @level2type=N'COLUMN',@level2name=N'IsDeleted'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'删除人' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caOrder', @level2type=N'COLUMN',@level2name=N'DeletedMan'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'删除时间' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caOrder', @level2type=N'COLUMN',@level2name=N'DeletedDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'开通人' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caOrder', @level2type=N'COLUMN',@level2name=N'OpenMan'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'开通时间' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caOrder', @level2type=N'COLUMN',@level2name=N'OpenDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'订单开始日期，无限制储值与此无关' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caOrder', @level2type=N'COLUMN',@level2name=N'BeginDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'订单终止日期，无限制储值与此无关' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caOrder', @level2type=N'COLUMN',@level2name=N'EndDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'添加日期,定单提交日期，永不变' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caOrder', @level2type=N'COLUMN',@level2name=N'AddDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'有纳税人识别号的是增值税专用发票；没有内容的，网聚是国税普通发票，助择是增值税普通发票。' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caOrder', @level2type=N'COLUMN',@level2name=N'Tariff'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'前台，企业用户订单表' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caOrder'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'说明' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caOrderRemarks', @level2type=N'COLUMN',@level2name=N'Remarks'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'招聘顾问ID' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caOrderRemarks', @level2type=N'COLUMN',@level2name=N'ManagerId'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'投诉内容' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caPlaint', @level2type=N'COLUMN',@level2name=N'Plaint'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'联系人' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caPlaint', @level2type=N'COLUMN',@level2name=N'LinkMan'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'联系电话' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caPlaint', @level2type=N'COLUMN',@level2name=N'Telephone'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'处理类型 ：0未处理，1 已处理并通知求职者 ，2无效投诉' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caPlaint', @level2type=N'COLUMN',@level2name=N'ReplyType'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'处理人' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caPlaint', @level2type=N'COLUMN',@level2name=N'ReplyMan'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'求职者是否查看' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caPlaint', @level2type=N'COLUMN',@level2name=N'IsViewed'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'处理意见' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caPlaint', @level2type=N'COLUMN',@level2name=N'ProcessMessage'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'处理时间' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caPlaint', @level2type=N'COLUMN',@level2name=N'ProcessDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'前台，企业用户对求职者投诉记录表' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'caPlaint'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'简历ID' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'ChatOnline', @level2type=N'COLUMN',@level2name=N'cvMainID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'企业用户ID' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'ChatOnline', @level2type=N'COLUMN',@level2name=N'caMainID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'顾问或客服ID' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'ChatOnline', @level2type=N'COLUMN',@level2name=N'ManageruserID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'1、个人对企业
2、企业对个人
3、个人对客服
4、企业对客服,顾问
5、顾问对企业' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'ChatOnline', @level2type=N'COLUMN',@level2name=N'Initiative'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'null 未审核 0 审核不通过 1 审核通过' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'ChatOnline', @level2type=N'COLUMN',@level2name=N'Valid'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'chattype=3/4/5时有用' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'ChatOnline', @level2type=N'COLUMN',@level2name=N'Evaluate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'1 camainid 2 cvmainid 3 manageruserid' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'ChatOnlineExchange', @level2type=N'COLUMN',@level2name=N'UserType'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'1、企业用户发送
2、个人用户发送
3、客服或顾问发送' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'ChatOnlineLog', @level2type=N'COLUMN',@level2name=N'SenderType'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'对应冷客户编号' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'ColdContact', @level2type=N'COLUMN',@level2name=N'CustomerID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'联系时间' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'ColdContact', @level2type=N'COLUMN',@level2name=N'BeginTime'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'详细信息' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'ColdContact', @level2type=N'COLUMN',@level2name=N'Description'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'来源地址' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'ColdCustomer', @level2type=N'COLUMN',@level2name=N'SourceLink'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'1 未注册 2 单位名称有注册，无顾问，无执照，1个月以上没有登录过 3 单位名称有注册，无顾问，有执照，3个月以上没有登录过。 4 有注册，有顾问，有执照，1年以上没有登录过。' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'ColdCustomer', @level2type=N'COLUMN',@level2name=N'RegType'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'注册用户名' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'ColdCustomer', @level2type=N'COLUMN',@level2name=N'RegUserName'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'单位名称是否重复' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'ColdCustomer', @level2type=N'COLUMN',@level2name=N'IsNameRepeat'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'邮箱是否重复' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'ColdCustomer', @level2type=N'COLUMN',@level2name=N'IsEmailRepeat'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'是否同意注册' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'ColdCustomer', @level2type=N'COLUMN',@level2name=N'IsAgree'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'不同意注册理由' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'ColdCustomer', @level2type=N'COLUMN',@level2name=N'DisAgreeReason'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'注册时间' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'ColdCustomer', @level2type=N'COLUMN',@level2name=N'RegisterDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'最近一次登录时间' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'ColdCustomer', @level2type=N'COLUMN',@level2name=N'LastLoginDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'1未注册 2 已注册 3 已上传营业执照 4 已付费 5 已注册一月未上传 6 已注册三月未登陆' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'ColdCustomer', @level2type=N'COLUMN',@level2name=N'Status'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'是否有效' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'ColdCustomer', @level2type=N'COLUMN',@level2name=N'IsValid'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'审核人工号' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'ColdCustomer', @level2type=N'COLUMN',@level2name=N'CheckMan'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'审核理由' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'ColdCustomer', @level2type=N'COLUMN',@level2name=N'CheckReason'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'审核日期' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'ColdCustomer', @level2type=N'COLUMN',@level2name=N'CheckDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'添加日期' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'ColdCustomer', @level2type=N'COLUMN',@level2name=N'AddDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'添加人' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'ColdCustomer', @level2type=N'COLUMN',@level2name=N'AddMan'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'释放人工号' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'coldCustomerRelease', @level2type=N'COLUMN',@level2name=N'allotman'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'释放时间' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'coldCustomerRelease', @level2type=N'COLUMN',@level2name=N'AddDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'试用开始时间' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'ColdCustomerTry', @level2type=N'COLUMN',@level2name=N'AddDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'评论的公司ID' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'CommentInterview', @level2type=N'COLUMN',@level2name=N'CpmainID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'评论个人ID，未登陆用户默认0' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'CommentInterview', @level2type=N'COLUMN',@level2name=N'PaMainID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'面试职位' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'CommentInterview', @level2type=N'COLUMN',@level2name=N'JobName'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'面试日期' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'CommentInterview', @level2type=N'COLUMN',@level2name=N'InterviewDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'面试结果
1、	确定通过
2、	感觉靠谱
3、	感觉没戏
4、	确定不通过
' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'CommentInterview', @level2type=N'COLUMN',@level2name=N'InterViewResult'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'面试经历' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'CommentInterview', @level2type=N'COLUMN',@level2name=N'InterViewExperience'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'面试感受' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'CommentInterview', @level2type=N'COLUMN',@level2name=N'InterviewFeeling'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'一句话概括' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'CommentInterview', @level2type=N'COLUMN',@level2name=N'Title'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'getdate()' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'CommentInterview', @level2type=N'COLUMN',@level2name=N'AddDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'审核人工号' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'CommentInterview', @level2type=N'COLUMN',@level2name=N'VerifyMan'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'审核日期' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'CommentInterview', @level2type=N'COLUMN',@level2name=N'VerifyDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'1一般评论 2 优质评论 3 无效评论' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'CommentInterview', @level2type=N'COLUMN',@level2name=N'InterviewType'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'1点评 2面试' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'CommentPraise', @level2type=N'COLUMN',@level2name=N'CommentType'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'评论个人ID，未登陆用户默认0' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Comments', @level2type=N'COLUMN',@level2name=N'PaMainID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'与公司关系，1在职，2离职，3非员工' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Comments', @level2type=N'COLUMN',@level2name=N'Relation'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'评级 1一星 2 二星 3 三星 4 四星 5五星' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Comments', @level2type=N'COLUMN',@level2name=N'GradeStar'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'1、	在职 吸引在这里工作的原因 2、	离职 哪些因素让你选择离开 3、	非员工 欣赏这家公司的哪些方面' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Comments', @level2type=N'COLUMN',@level2name=N'Remark1'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'1、在职 对哪些方面感到失望  2、离职 哪些地方值得留恋   3、非员工 这家公司还有哪些不足' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Comments', @level2type=N'COLUMN',@level2name=N'Remark2'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'对公司的意见或建议' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Comments', @level2type=N'COLUMN',@level2name=N'Remark3'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'一句话概括' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Comments', @level2type=N'COLUMN',@level2name=N'Title'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'岗位名称，选填' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Comments', @level2type=N'COLUMN',@level2name=N'Position'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'工作地点编号，选填' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Comments', @level2type=N'COLUMN',@level2name=N'WorkRegionID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'入职日期' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Comments', @level2type=N'COLUMN',@level2name=N'EntryDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'离职日期' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Comments', @level2type=N'COLUMN',@level2name=N'QuitDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'点评日期' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Comments', @level2type=N'COLUMN',@level2name=N'AddDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'1一般评论 2 优质评论 3 无效评论' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Comments', @level2type=N'COLUMN',@level2name=N'CommentType'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'点赞总量' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Comments', @level2type=N'COLUMN',@level2name=N'PraiseCount'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'已登陆用户点赞总量' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Comments', @level2type=N'COLUMN',@level2name=N'LoginPraiseCount'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'1,一次性通知;2,限时通知' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'CompanyNotify', @level2type=N'COLUMN',@level2name=N'Type'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'网站消息内容' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'CompanyNotify', @level2type=N'COLUMN',@level2name=N'Content'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'管理员是否查看' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'CompanyNotify', @level2type=N'COLUMN',@level2name=N'Received'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'后台，企业网站消息' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'CompanyNotify'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'1,试用;2,正式;3,离职;4,长假;' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Consultant_ManagerUser_Month', @level2type=N'COLUMN',@level2name=N'status'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'1、实名认证 2、普通认证' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cpCertification', @level2type=N'COLUMN',@level2name=N'MemberType'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'1、对公 2、个人认证 3、企业邮箱认证' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cpCertification', @level2type=N'COLUMN',@level2name=N'CerType'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'公司ID' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cpCoin', @level2type=N'COLUMN',@level2name=N'cpMainID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'相关订单ID' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cpCoin', @level2type=N'COLUMN',@level2name=N'caOrderID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'减少、增加金币数量' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cpCoin', @level2type=N'COLUMN',@level2name=N'Coin'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'金币余额' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cpCoin', @level2type=N'COLUMN',@level2name=N'Balance'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'记录添加日期' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cpCoin', @level2type=N'COLUMN',@level2name=N'AddDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'1、成功 2、邮箱认证成功，等待审核域名 3、不是该企业' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cpCompanyEmail', @level2type=N'COLUMN',@level2name=N'CheckResult'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'图片类型。1-logo图；2-形象图' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cpImage', @level2type=N'COLUMN',@level2name=N'ImgType'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'上传的原始图片' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cpImage', @level2type=N'COLUMN',@level2name=N'ImgFile'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'增加日期' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cpImage', @level2type=N'COLUMN',@level2name=N'AddDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'审核通过。null待审核，1审核通过，0审核不通过' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cpImage', @level2type=N'COLUMN',@level2name=N'HasPassed'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'审核人' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cpImage', @level2type=N'COLUMN',@level2name=N'CheckMan'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'审核时间' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cpImage', @level2type=N'COLUMN',@level2name=N'CheckDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'审核不通过原因' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cpImage', @level2type=N'COLUMN',@level2name=N'CheckMessage'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'企业用户的logo、形象图记录表' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cpImage'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'所属行业' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cpIndustry', @level2type=N'COLUMN',@level2name=N'dcIndustryID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'前台，企业所属行业表' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cpIndustry'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'上传的原始图片' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cpLicence', @level2type=N'COLUMN',@level2name=N'ImgFile'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'图片文件来源。0-以前上传的没有记录；1-用户自己上传的；2-传真；3-QQ或者邮件' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cpLicence', @level2type=N'COLUMN',@level2name=N'FileSource'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'上传IP' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cpLicence', @level2type=N'COLUMN',@level2name=N'Ip'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'上传营业执照时间,不变化' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cpLicence', @level2type=N'COLUMN',@level2name=N'AddDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'审核通过。null待审核，1审核通过，0审核不通过' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cpLicence', @level2type=N'COLUMN',@level2name=N'HasPassed'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'审核人' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cpLicence', @level2type=N'COLUMN',@level2name=N'CheckMan'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'审核时间' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cpLicence', @level2type=N'COLUMN',@level2name=N'CheckDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'审核不通过原因' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cpLicence', @level2type=N'COLUMN',@level2name=N'CheckMessage'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'前台，企业的营业执照表' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cpLicence'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'原名' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cpLicenceChangeLog', @level2type=N'COLUMN',@level2name=N'NameOld'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'新名' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cpLicenceChangeLog', @level2type=N'COLUMN',@level2name=N'NameNew'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'原文件' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cpLicenceChangeLog', @level2type=N'COLUMN',@level2name=N'FilenameOld'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'新文件' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cpLicenceChangeLog', @level2type=N'COLUMN',@level2name=N'FilenameNew'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'前台，企业更名记录' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cpLicenceChangeLog'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'审核不通过的原因' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cpLicenceLog', @level2type=N'COLUMN',@level2name=N'Description'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'文件来源：0 以前没有上传记录，1 用户自己上传的，2 传真，3 QQ或邮件' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cpLicenceLog', @level2type=N'COLUMN',@level2name=N'FileSource'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'后台，企业营业执照审核不通过记录' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cpLicenceLog'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'注册主站（省、直辖市编号）' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cpMain', @level2type=N'COLUMN',@level2name=N'dcProvinceID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'注册日期' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cpMain', @level2type=N'COLUMN',@level2name=N'RegDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'注册ip' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cpMain', @level2type=N'COLUMN',@level2name=N'RegisterIP'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'注册方式：0，单位自己注册；1，信息员注册（未统计）；11，信息员注册（已统计）' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cpMain', @level2type=N'COLUMN',@level2name=N'RegisterMode'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'信息员id' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cpMain', @level2type=N'COLUMN',@level2name=N'AddMan'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'信息员推广的账号，密码没有修改过(1需要提醒修改,0不提醒)' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cpMain', @level2type=N'COLUMN',@level2name=N'IsDefaultPassword'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'企业名称' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cpMain', @level2type=N'COLUMN',@level2name=N'Name'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'企业简称' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cpMain', @level2type=N'COLUMN',@level2name=N'ShortName'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'企业性质，事业单位、政府机构、股份公司。。。。dcCompanyKind' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cpMain', @level2type=N'COLUMN',@level2name=N'dcCompanyKindID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'企业规模,dcCompanySize' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cpMain', @level2type=N'COLUMN',@level2name=N'dcCompanySizeID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'所在地区,dcRegion' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cpMain', @level2type=N'COLUMN',@level2name=N'dcRegionID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'企业地址' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cpMain', @level2type=N'COLUMN',@level2name=N'Address'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'邮编' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cpMain', @level2type=N'COLUMN',@level2name=N'Zip'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'mapBarID' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cpMain', @level2type=N'COLUMN',@level2name=N'MapBarID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'公司主页' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cpMain', @level2type=N'COLUMN',@level2name=N'HomePage'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'公司简介,格式字符显示的时候过滤' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cpMain', @level2type=N'COLUMN',@level2name=N'Brief'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'是否有营业执照：0,无或者未审核；1,有已审' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cpMain', @level2type=N'COLUMN',@level2name=N'HasLicence'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'是否有logo,0没有或者未审,1审核通过' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cpMain', @level2type=N'COLUMN',@level2name=N'HasLogo'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'是否有形象图,0没有或者未审,1审核通过' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cpMain', @level2type=N'COLUMN',@level2name=N'HasVisual'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'招聘顾问' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cpMain', @level2type=N'COLUMN',@level2name=N'ConsultantID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'招聘顾问分配日期' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cpMain', @level2type=N'COLUMN',@level2name=N'ConsultantDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'每日赠送主动下载数量,默认为0,营业执照审核通过后,则修改为5,触发器修改' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cpMain', @level2type=N'COLUMN',@level2name=N'DailyGiftQuota'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'无限制会员，兼容老版validdate' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cpMain', @level2type=N'COLUMN',@level2name=N'UnlimitedDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'储值会员截止日期，兼容老版' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cpMain', @level2type=N'COLUMN',@level2name=N'BalanceDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'储值会员余额，兼容老版' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cpMain', @level2type=N'COLUMN',@level2name=N'Balance'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'标准配额，兼容老版, 简历每日配额,新版不用' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cpMain', @level2type=N'COLUMN',@level2name=N'ResumeQuota'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'最大用户数量。老版：用户职位的Email自动生成，规则是用户名_1,密码=管理员密码。新版：默认为1，开通订单后：购买数+1。spRedifinePrivilage定义。定单开通,balance,isdelete,address,name,haslisence,limitlogin触发' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cpMain', @level2type=N'COLUMN',@level2name=N'MaxUserNumber'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'最大职位并发数。老版：用户发布的职位数+10。新版：信息不完整0，未认证1，普通3，vip按订单。spRedifinePrivilage定义。定单开通,balance,isdelete,address,name,haslisence,limitlogin触发' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cpMain', @level2type=N'COLUMN',@level2name=N'MaxJobNumber'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'招聘顾问对单位的评价。1,非常重要;2,重要;3,一般;4,差;5,非常差;null,未分级 ' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cpMain', @level2type=N'COLUMN',@level2name=N'Quality'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'储值型会员余额太少后，通知发送次数' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cpMain', @level2type=N'COLUMN',@level2name=N'SendFeeCount'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'是否中介。0,普通公司；1，中介公司；' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cpMain', @level2type=N'COLUMN',@level2name=N'IsAgent'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'是否限制登陆：0,正常;9,限制;1,永不受限制。暂停使用限制登录替换操作，解除限制时手工延长订单时间' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cpMain', @level2type=N'COLUMN',@level2name=N'IsLimitLogin'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'是否被锁定,锁定为1,否则为空。登录时自动提醒招聘顾问，如果无招聘顾问通知112' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cpMain', @level2type=N'COLUMN',@level2name=N'Islock'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'是否删除，0-正常;1-待删除' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cpMain', @level2type=N'COLUMN',@level2name=N'IsDelete'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'0:资料不完整；1未认证；2：普通会员；3：贵宾会员；10:无限制；11储值。spRedifinePrivilage定义。定单开通,balance,isdelete,address,name,haslisence,limitlogin触发。计划任务也修改。' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cpMain', @level2type=N'COLUMN',@level2name=N'MemberType'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'后台备注' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cpMain', @level2type=N'COLUMN',@level2name=N'Description'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'后台审核情况，1-通过审核；10-未通过审核。严重情况审核不通过。影响valid，不影响登陆，会员中心弹屏提示' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cpMain', @level2type=N'COLUMN',@level2name=N'VerifyResult'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'该企业及所有子表审核不通过次数,VerifyResult变成10的次数' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cpMain', @level2type=N'COLUMN',@level2name=N'BlockCount'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'该企业及所有子表审核次数' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cpMain', @level2type=N'COLUMN',@level2name=N'VerifyCount'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'总登录次数' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cpMain', @level2type=N'COLUMN',@level2name=N'LoginCount'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'正在发布中的职位数' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cpMain', @level2type=N'COLUMN',@level2name=N'JobNumber'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'企业信息被查看次数' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cpMain', @level2type=N'COLUMN',@level2name=N'ViewNumber'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'首页刷新日期,登录后更新(1小时以上间隔),自动刷新' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cpMain', @level2type=N'COLUMN',@level2name=N'RefreshDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'最后修改日期,企业信息页面修改' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cpMain', @level2type=N'COLUMN',@level2name=N'LastModifyDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'注册资本（万元） 50,130等' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cpMain', @level2type=N'COLUMN',@level2name=N'RegCapital'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'注册站点 省站 市站' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cpMain', @level2type=N'COLUMN',@level2name=N'dcSubSiteID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'企业表，记录企业的基本信息' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cpMain'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'企业名称' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cpMainPublish', @level2type=N'COLUMN',@level2name=N'Name'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'企业简称' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cpMainPublish', @level2type=N'COLUMN',@level2name=N'ShortName'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'企业性质，事业单位、政府机构、股份公司。。。。dcCompanyKind' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cpMainPublish', @level2type=N'COLUMN',@level2name=N'dcCompanyKindID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'企业规模,dcCompanySize' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cpMainPublish', @level2type=N'COLUMN',@level2name=N'dcCompanySizeID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'所在地区,dcRegion' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cpMainPublish', @level2type=N'COLUMN',@level2name=N'dcRegionID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'公司简介,格式字符显示的时候过滤' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cpMainPublish', @level2type=N'COLUMN',@level2name=N'Brief'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'是否有营业执照：0,无或者未审核；1,有已审' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cpMainPublish', @level2type=N'COLUMN',@level2name=N'HasLicence'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'无限制会员，兼容老版validdate' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cpMainPublish', @level2type=N'COLUMN',@level2name=N'UnlimitedDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'储值会员截止日期，兼容老版' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cpMainPublish', @level2type=N'COLUMN',@level2name=N'BalanceDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'储值会员余额，兼容老版' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cpMainPublish', @level2type=N'COLUMN',@level2name=N'Balance'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'0:资料不完整；1未认证；2：普通会员；3：贵宾会员；10:无限制；11储值。spRedifinePrivilage定义。定单开通,balance,isdelete,address,name,haslisence,limitlogin触发。计划任务也修改。' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cpMainPublish', @level2type=N'COLUMN',@level2name=N'MemberType'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'首页刷新日期,登录后更新(1小时以上间隔),自动刷新' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cpMainPublish', @level2type=N'COLUMN',@level2name=N'RefreshDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'最后修改日期,企业信息页面修改' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cpMainPublish', @level2type=N'COLUMN',@level2name=N'LastModifyDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'企业表，记录企业的基本信息' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cpMainPublish'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'释放人工号' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cpMainRelease', @level2type=N'COLUMN',@level2name=N'allotman'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'释放时间' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cpMainRelease', @level2type=N'COLUMN',@level2name=N'AddDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'1、成功 2、姓名认证成功，等待审核法人 3、不是法人 ' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cpPersonalAccount', @level2type=N'COLUMN',@level2name=N'CheckResult'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'企业ID' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cpPoint', @level2type=N'COLUMN',@level2name=N'cpMainID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'扣、加分原因：1.每天第一次登陆。2.上传营业执照通过审核。3.搜索简历。4.发送面试通知。5.发送应聘邀请。6.与陌生简历发起沟通。7.上传企业Logo并通过审核。8.删除已审核通过的企业Logo图。9.上传企业形象图并通过审核10.删除已审核通过的企业形象图11.有有效职位。12.无有效职位。13.进行视频面试。14.回复一周内应聘的简历。15.开通订单。16.取消订单。17.下载简历。100.测试' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cpPoint', @level2type=N'COLUMN',@level2name=N'ChangeID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'扣、加分值' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cpPoint', @level2type=N'COLUMN',@level2name=N'Point'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'相关ID' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cpPoint', @level2type=N'COLUMN',@level2name=N'relativeID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'最后更改日期' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cpPoint', @level2type=N'COLUMN',@level2name=N'LastModifyDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Session.ID' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cpSession', @level2type=N'COLUMN',@level2name=N'SessionID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'刷新时间' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cpSession', @level2type=N'COLUMN',@level2name=N'RefreshDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'前台，记录企业的登录状态，用于企业单点登录' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cpSession'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'证书类型ID,dcAppendix' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvAppendix', @level2type=N'COLUMN',@level2name=N'dcAppendixID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'证书名称,dcAppendixID=999' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvAppendix', @level2type=N'COLUMN',@level2name=N'Name'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'英文证书名称,dcAppendixID=999' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvAppendix', @level2type=N'COLUMN',@level2name=N'NameEng'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'证书说明' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvAppendix', @level2type=N'COLUMN',@level2name=N'Description'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'英文证书说明' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvAppendix', @level2type=N'COLUMN',@level2name=N'DescriptionEng'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'获得时间，到年即可' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvAppendix', @level2type=N'COLUMN',@level2name=N'AccessDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'服务器上保存的文件名称' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvAppendix', @level2type=N'COLUMN',@level2name=N'Filename'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'证书名称,dcAppendixID=999' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvAppendixPublish', @level2type=N'COLUMN',@level2name=N'Name'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'证书说明' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvAppendixPublish', @level2type=N'COLUMN',@level2name=N'Description'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'学校名称' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvEducation', @level2type=N'COLUMN',@level2name=N'GraduateCollage'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'毕业时间。精确到月' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvEducation', @level2type=N'COLUMN',@level2name=N'Graduation'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'专业类别，代码' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvEducation', @level2type=N'COLUMN',@level2name=N'dcMajorID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'专业名称' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvEducation', @level2type=N'COLUMN',@level2name=N'MajorName'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'学    历' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvEducation', @level2type=N'COLUMN',@level2name=N'Degree'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'统招、委培....' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvEducation', @level2type=N'COLUMN',@level2name=N'EduType'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'学习经历' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvEducation', @level2type=N'COLUMN',@level2name=N'Details'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'学校名称' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvEducationPublish', @level2type=N'COLUMN',@level2name=N'GraduateCollage'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'毕业时间。精确到月' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvEducationPublish', @level2type=N'COLUMN',@level2name=N'Graduation'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'专业类别，代码' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvEducationPublish', @level2type=N'COLUMN',@level2name=N'dcMajorID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'专业名称' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvEducationPublish', @level2type=N'COLUMN',@level2name=N'MajorName'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'学    历' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvEducationPublish', @level2type=N'COLUMN',@level2name=N'Degree'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'统招、委培....' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvEducationPublish', @level2type=N'COLUMN',@level2name=N'EduType'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'学习经历' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvEducationPublish', @level2type=N'COLUMN',@level2name=N'Details'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'工作单位名称' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvExperience', @level2type=N'COLUMN',@level2name=N'CompanyName'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'英文工作单位名称' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvExperience', @level2type=N'COLUMN',@level2name=N'CompanyNameEng'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'工作单位所属行业' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvExperience', @level2type=N'COLUMN',@level2name=N'dcIndustryID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'工作单位人数规模' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvExperience', @level2type=N'COLUMN',@level2name=N'dcCompanySizeID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'从事职位类别' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvExperience', @level2type=N'COLUMN',@level2name=N'dcJobtypeID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'岗位名称' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvExperience', @level2type=N'COLUMN',@level2name=N'JobName'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'英文岗位名称' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvExperience', @level2type=N'COLUMN',@level2name=N'JobNameEng'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'开始时间，精确到月' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvExperience', @level2type=N'COLUMN',@level2name=N'BeginDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'结束时间，精确到月。至今999999' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvExperience', @level2type=N'COLUMN',@level2name=N'EndDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'下属总人数' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvExperience', @level2type=N'COLUMN',@level2name=N'SubNodeNum'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'工作描述' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvExperience', @level2type=N'COLUMN',@level2name=N'Description'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'英文工作描述' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvExperience', @level2type=N'COLUMN',@level2name=N'DescriptionEng'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'公司性质' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvExperience', @level2type=N'COLUMN',@level2name=N'dcCompanyKindID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'工作地点' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvExperience', @level2type=N'COLUMN',@level2name=N'WorkPlace'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'所在部门' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvExperience', @level2type=N'COLUMN',@level2name=N'Dept'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'英文所在部门' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvExperience', @level2type=N'COLUMN',@level2name=N'DeptEng'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'上级职位' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvExperience', @level2type=N'COLUMN',@level2name=N'UpperPost'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'英文上级职位' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvExperience', @level2type=N'COLUMN',@level2name=N'UpperPostEng'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'离职原因代码' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvExperience', @level2type=N'COLUMN',@level2name=N'dcLeaveResonID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'工作单位名称' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvExperiencePublish', @level2type=N'COLUMN',@level2name=N'CompanyName'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'工作单位所属行业' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvExperiencePublish', @level2type=N'COLUMN',@level2name=N'dcIndustryID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'从事职位类别' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvExperiencePublish', @level2type=N'COLUMN',@level2name=N'dcJobtypeID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'岗位名称' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvExperiencePublish', @level2type=N'COLUMN',@level2name=N'JobName'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'下属总人数' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvExperiencePublish', @level2type=N'COLUMN',@level2name=N'SubNodeNum'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'工作描述' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvExperiencePublish', @level2type=N'COLUMN',@level2name=N'Description'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'行业代码,dcIndustry' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvIndustry', @level2type=N'COLUMN',@level2name=N'dcIndustryID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'行业代码,dcIndustry' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvIndustryPublish', @level2type=N'COLUMN',@level2name=N'dcIndustryID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'期望工作地点代码,dcRegin' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvJobPlace', @level2type=N'COLUMN',@level2name=N'dcRegionID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'期望工作地点代码,dcRegin' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvJobPlacePublish', @level2type=N'COLUMN',@level2name=N'dcRegionID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'职位代码,dcJoytype' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvJobType', @level2type=N'COLUMN',@level2name=N'dcJobTypeID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'职位代码,dcJoytype' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvJobTypePublish', @level2type=N'COLUMN',@level2name=N'dcJobTypeID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'语种,见dcLanguage' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvLanguage', @level2type=N'COLUMN',@level2name=N'LanguageType'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'掌握程度,1初级,2一般,3良好,4熟练,5母语' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvLanguage', @level2type=N'COLUMN',@level2name=N'Mastery'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'读写能力,1一般,2熟练,3精通' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvLanguage', @level2type=N'COLUMN',@level2name=N'ReadWrite'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'听说能力,1一般,2熟练,3精通' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvLanguage', @level2type=N'COLUMN',@level2name=N'Spoken'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'等级考试分数，描述' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvLanguage', @level2type=N'COLUMN',@level2name=N'Score'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'等级考试分数，描述(英文)' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvLanguage', @level2type=N'COLUMN',@level2name=N'ScoreEng'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'语种,见dcLanguage' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvLanguagePublish', @level2type=N'COLUMN',@level2name=N'LanguageType'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'关键字' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvMain', @level2type=N'COLUMN',@level2name=N'ID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'个人账号id
' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvMain', @level2type=N'COLUMN',@level2name=N'paMainID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'简历名称' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvMain', @level2type=N'COLUMN',@level2name=N'Name'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'最高学历(来源于子表教育背景)，用于查询' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvMain', @level2type=N'COLUMN',@level2name=N'Degree'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'最高学历对应的专业类别代码(来源于子表教育背景)，用于查询' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvMain', @level2type=N'COLUMN',@level2name=N'dcMajorID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'开始时间最晚的一份工作的职位类别(来源于子表工作经历)，用于查询' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvMain', @level2type=N'COLUMN',@level2name=N'LastJobTypeID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'开始时间最晚的一份工作的行业(来源于子表工作经历)，用于查询' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvMain', @level2type=N'COLUMN',@level2name=N'LastIndustryID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'开始时间最晚的一份工作的职位名称(来源于子表工作经历)，用于查询后的列表显示' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvMain', @level2type=N'COLUMN',@level2name=N'JobName'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'最大的下属人数(来源于子表工作经历)，用于查询
1    无下属
2    1~5人
3    6~10人
4    11~20人
5    21~50人
6    51~100人
7    101~200人
8    200人以上' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvMain', @level2type=N'COLUMN',@level2name=N'SubNodeNum'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'相关工作经验
0-10 0到10年
11 10年以上' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvMain', @level2type=N'COLUMN',@level2name=N'RelatedWorkYears'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'期望工作性质。全职：1 全职/兼职：2 兼职：3 实习：4' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvMain', @level2type=N'COLUMN',@level2name=N'EmployType'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'期望月薪，具体见salary表' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvMain', @level2type=N'COLUMN',@level2name=N'dcSalaryID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'是否可面议，0-否；1-是' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvMain', @level2type=N'COLUMN',@level2name=N'IsNegotiable'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'工作能力' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvMain', @level2type=N'COLUMN',@level2name=N'Speciality'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'工作能力（英）' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvMain', @level2type=N'COLUMN',@level2name=N'SpecialityEng'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'附件简历（存储在硬盘上的物理文件名）' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvMain', @level2type=N'COLUMN',@level2name=N'Attachment'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'原文件名，只用于显示' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvMain', @level2type=N'COLUMN',@level2name=N'WordFilename'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'简历类型；0-正常简历；1-应届生简历' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvMain', @level2type=N'COLUMN',@level2name=N'cvType'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'是否隐藏姓名，1隐藏；0不隐藏' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvMain', @level2type=N'COLUMN',@level2name=N'IsNameHidden'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'是否隐藏简历,1隐藏；0不隐藏' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvMain', @level2type=N'COLUMN',@level2name=N'IscvHidden'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'是否开放简历，老版本的high。1-开放；0-非开放' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvMain', @level2type=N'COLUMN',@level2name=N'isOpen'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'简历等级，显示在简历列表等位置(1存在简历，2基本信息，3教育背景，4工作经历，5工作能力，6求职意向，7语言能力，8培训经历，9项目经历，10证书附件)前6个1表示完整' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvMain', @level2type=N'COLUMN',@level2name=N'cvLevel'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'英文简历等级，显示在简历列表等位置(1存在简历，2基本信息，3教育背景，4工作经历，5求职意向，6工作能力，7语言能力，8培训经历，9项目经历，10证书附件)前6个1表示完整' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvMain', @level2type=N'COLUMN',@level2name=N'cvLevelEng'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'必填项审核情况，1通过；10不通过；' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvMain', @level2type=N'COLUMN',@level2name=N'VerifyResult'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'必填项英文审核情况，1通过；10不通过；' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvMain', @level2type=N'COLUMN',@level2name=N'VerifyResultEng'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'（完整 审核通过 不隐藏）或者 word简历
0 不通过
1、中文简历有效，或者有Word简历
(cvLevel like ''111111%'' or attachment >'''') and not cvLevelEng like ''111111%''
2、中英文都有效
cvLevel like ''111111%'' and cvLevelEng like ''111111%''
3、英文简历有效
not cvLevel like ''111111%'' and cvLevelEng like ''111111%''
用于简历搜索' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvMain', @level2type=N'COLUMN',@level2name=N'Valid'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'简历被查看总次数' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvMain', @level2type=N'COLUMN',@level2name=N'ViewNumber'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'简历更新日期，用于简历搜索排序。手动更新或者修改简历更新。' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvMain', @level2type=N'COLUMN',@level2name=N'RefreshDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'关键字' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvMainPublish', @level2type=N'COLUMN',@level2name=N'ID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'个人账号id
' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvMainPublish', @level2type=N'COLUMN',@level2name=N'paMainID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'最高学历(来源于子表教育背景)，用于查询' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvMainPublish', @level2type=N'COLUMN',@level2name=N'Degree'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'最高学历对应的专业类别代码(来源于子表教育背景)，用于查询' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvMainPublish', @level2type=N'COLUMN',@level2name=N'dcMajorID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'开始时间最晚的一份工作的职位类别(来源于子表工作经历)，用于查询' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvMainPublish', @level2type=N'COLUMN',@level2name=N'LastJobTypeID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'开始时间最晚的一份工作的行业(来源于子表工作经历)，用于查询' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvMainPublish', @level2type=N'COLUMN',@level2name=N'LastIndustryID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'开始时间最晚的一份工作的职位名称(来源于子表工作经历)，用于查询后的列表显示' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvMainPublish', @level2type=N'COLUMN',@level2name=N'JobName'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'最大的下属人数(来源于子表工作经历)，用于查询
1    无下属
2    1~5人
3    6~10人
4    11~20人
5    21~50人
6    51~100人
7    101~200人
8    200人以上' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvMainPublish', @level2type=N'COLUMN',@level2name=N'SubNodeNum'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'相关工作经验
0-10 0到10年
11 10年以上' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvMainPublish', @level2type=N'COLUMN',@level2name=N'RelatedWorkYears'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'期望月薪，具体见salary表' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvMainPublish', @level2type=N'COLUMN',@level2name=N'dcSalaryID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'是否可面议，0-否；1-是' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvMainPublish', @level2type=N'COLUMN',@level2name=N'IsNegotiable'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'工作能力' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvMainPublish', @level2type=N'COLUMN',@level2name=N'Speciality'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'工作能力（英）' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvMainPublish', @level2type=N'COLUMN',@level2name=N'SpecialityEng'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'附件简历（存储在硬盘上的物理文件名）' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvMainPublish', @level2type=N'COLUMN',@level2name=N'Attachment'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'（完整 审核通过 不隐藏）或者 word简历
0 不通过
1、中文简历有效，或者有Word简历
(cvLevel like ''111111%'' or attachment >'''') and not cvLevelEng like ''111111%''
2、中英文都有效
cvLevel like ''111111%'' and cvLevelEng like ''111111%''
3、英文简历有效
not cvLevel like ''111111%'' and cvLevelEng like ''111111%''
用于简历搜索' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvMainPublish', @level2type=N'COLUMN',@level2name=N'Valid'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'简历更新日期，用于简历搜索排序。手动更新或者修改简历更新。' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvMainPublish', @level2type=N'COLUMN',@level2name=N'RefreshDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'项目名称' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvProject', @level2type=N'COLUMN',@level2name=N'Name'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'英文项目名称' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvProject', @level2type=N'COLUMN',@level2name=N'NameEng'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'开始日期。精确到月' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvProject', @level2type=N'COLUMN',@level2name=N'StartDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'结束日期。精确到月' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvProject', @level2type=N'COLUMN',@level2name=N'EndDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'项目描述' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvProject', @level2type=N'COLUMN',@level2name=N'Description'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'英文项目描述' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvProject', @level2type=N'COLUMN',@level2name=N'DescriptionEng'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'项目中的职责' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvProject', @level2type=N'COLUMN',@level2name=N'Responsibilities'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'英文项目中的职责' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvProject', @level2type=N'COLUMN',@level2name=N'ResponsibilitiesEng'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'项目名称' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvProjectPublish', @level2type=N'COLUMN',@level2name=N'Name'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'项目描述' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvProjectPublish', @level2type=N'COLUMN',@level2name=N'Description'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'项目中的职责' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvProjectPublish', @level2type=N'COLUMN',@level2name=N'Responsibilities'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'培训时间' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvTraining', @level2type=N'COLUMN',@level2name=N'StartDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'时长' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvTraining', @level2type=N'COLUMN',@level2name=N'TimeLength'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'1课时;2日；3周；4月' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvTraining', @level2type=N'COLUMN',@level2name=N'TimeUnit'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'培训机构' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvTraining', @level2type=N'COLUMN',@level2name=N'Institution'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'课程' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvTraining', @level2type=N'COLUMN',@level2name=N'Course'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'培训地点' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvTraining', @level2type=N'COLUMN',@level2name=N'City'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'证书' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvTraining', @level2type=N'COLUMN',@level2name=N'Certificate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'课程描述' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvTraining', @level2type=N'COLUMN',@level2name=N'Details'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'培训机构' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvTrainingPublish', @level2type=N'COLUMN',@level2name=N'Institution'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'课程' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvTrainingPublish', @level2type=N'COLUMN',@level2name=N'Course'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'证书' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvTrainingPublish', @level2type=N'COLUMN',@level2name=N'Certificate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'课程描述' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'cvTrainingPublish', @level2type=N'COLUMN',@level2name=N'Details'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'数据源名字' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'DataSource', @level2type=N'COLUMN',@level2name=N'DataSourceName'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'XXXXXXXXXX,分别为读取，创建，修改，删除，分配，自定义1，自定义2，自定义3，自定义4，自定义5。0表示具备，x表示不具备' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'DataSource', @level2type=N'COLUMN',@level2name=N'Privi'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'1、地区  2、行业 3、职位类别 4、学科分类' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'dcAlipayDic', @level2type=N'COLUMN',@level2name=N'DataType'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'1、地区  2、行业 3、职位类别 4、学科分类' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'dcAlipayDicConvert', @level2type=N'COLUMN',@level2name=N'DataType'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'1-外语证书；2-计算机证书；3-会计证书；4-职称证书；5-其他证书；99-其他' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'dcAppendix', @level2type=N'COLUMN',@level2name=N'Category'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'1为51job；2为智联招聘' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'dcCvConvertMap', @level2type=N'COLUMN',@level2name=N'WebName'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'优惠项目名称（齐鲁人才网 初夏6月 优惠活动大酬宾）' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'dcFee', @level2type=N'COLUMN',@level2name=N'Name'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'活动开始日期 2011-6-1 0：0' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'dcFee', @level2type=N'COLUMN',@level2name=N'StartDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'活动结束日期 2011-6-30 23：59：00' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'dcFee', @level2type=N'COLUMN',@level2name=N'EndDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'4:1/6图片广告；5：2/6图片广告（caOrder.OrderType=4）；7：知名企业；9：主动下载；10：职位发布；11：用户数量；14：短信；20:3/6图片广告;21:6/6图片广告;22：职位置顶' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'dcFee', @level2type=N'COLUMN',@level2name=N'Type'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'标准单价' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'dcFee', @level2type=N'COLUMN',@level2name=N'Price'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'说明' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'dcFee', @level2type=N'COLUMN',@level2name=N'Remark'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'最小值' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'dcFeeDetail', @level2type=N'COLUMN',@level2name=N'MinValue'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'最大值' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'dcFeeDetail', @level2type=N'COLUMN',@level2name=N'MaxValue'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'折扣价（15元等）' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'dcFeeDetail', @level2type=N'COLUMN',@level2name=N'Price'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'说明' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'dcFeeDetail', @level2type=N'COLUMN',@level2name=N'Remark'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'一个职位发布的标准价格' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'dcFeeStandard', @level2type=N'COLUMN',@level2name=N'PriceJob'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'一个用户数的标准价格' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'dcFeeStandard', @level2type=N'COLUMN',@level2name=N'PriceUser'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'一个简历下载的标准价格' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'dcFeeStandard', @level2type=N'COLUMN',@level2name=N'PriceResume'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'最少购买职位数' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'dcFeeStandard', @level2type=N'COLUMN',@level2name=N'MinJobNumber'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'最少购买用户数' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'dcFeeStandard', @level2type=N'COLUMN',@level2name=N'MinUserNumber'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'最少购买简历下载' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'dcFeeStandard', @level2type=N'COLUMN',@level2name=N'MinResumeNumber'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'月度会员的标准价' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'dcFeeStandard', @level2type=N'COLUMN',@level2name=N'PriceMonth'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'广告1/6的标准价格/每周' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'dcFeeStandard', @level2type=N'COLUMN',@level2name=N'PriceAd1'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'广告2/6的标准价格/每周' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'dcFeeStandard', @level2type=N'COLUMN',@level2name=N'PriceAd2'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'固定位置的标准价格/每周' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'dcFeeStandard', @level2type=N'COLUMN',@level2name=N'PriceFixed'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'储值会员下载1份简历的价格' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'dcFeeStandard', @level2type=N'COLUMN',@level2name=N'PriceCv'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'1,中国；NULL,未划分' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'dcIPPlace', @level2type=N'COLUMN',@level2name=N'International'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'1-9' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'dcJobTypeSimilar', @level2type=N'COLUMN',@level2name=N'Coefficient'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'显示顺序' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'dcMajor', @level2type=N'COLUMN',@level2name=N'OrderNo'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'1:就业资讯;2:职场攻略' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'dcNewsType', @level2type=N'COLUMN',@level2name=N'Category'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'招聘人数的具体数量，用于大数据计算' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'dcOthers', @level2type=N'COLUMN',@level2name=N'Number'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'省名，山东' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'dcProvince', @level2type=N'COLUMN',@level2name=N'ProvinceName'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'网站名称，齐鲁人才网' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'dcProvince', @level2type=N'COLUMN',@level2name=N'WebsiteName'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'网站域名，qlrc.com' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'dcProvince', @level2type=N'COLUMN',@level2name=N'ProvinceDomain'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'1,南方;2北方' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'dcProvince', @level2type=N'COLUMN',@level2name=N'SouthNorth'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'1、前台网站
2、后台网站
3、oa;4:wap' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'dcRunParameter', @level2type=N'COLUMN',@level2name=N'System'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'薪水的具体金额，用于大数据计算' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'dcSalary', @level2type=N'COLUMN',@level2name=N'Salary'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'天山人才网' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'dcSubSite', @level2type=N'COLUMN',@level2name=N'SubSiteName'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'乌鲁木齐' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'dcSubSite', @level2type=N'COLUMN',@level2name=N'SubSIteCity'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'umqi.tianshanrc.com' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'dcSubSite', @level2type=N'COLUMN',@level2name=N'SubSiteUrl'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'页面的title' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'dcSubSite', @level2type=N'COLUMN',@level2name=N'Title'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'首页页脚显示的关键词，优化用' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'dcSubSite', @level2type=N'COLUMN',@level2name=N'SeoBottom'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'原来的SMTP，用来识别发邮件的服务器' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'dcSubSite', @level2type=N'COLUMN',@level2name=N'InternalIp'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'邮件测试人' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'dcSubSite', @level2type=N'COLUMN',@level2name=N'EmailTester'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'最小推广比例' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'dcSubSite', @level2type=N'COLUMN',@level2name=N'MinInfoAmount'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'最高推广比例' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'dcSubSite', @level2type=N'COLUMN',@level2name=N'MaxInfoAmount'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'默认的邮件发送用户' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'dcSubSite', @level2type=N'COLUMN',@level2name=N'EmailUser'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'默认的邮件标题（单位）' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'dcSubSite', @level2type=N'COLUMN',@level2name=N'EmailTitle_Company'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'默认的邮件标题（个人）' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'dcSubSite', @level2type=N'COLUMN',@level2name=N'EmailTitle_Person'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'邮件Profile（SQLSERVER MAIL）' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'dcSubSite', @level2type=N'COLUMN',@level2name=N'EmailProfile'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'是否是独立站，1是，0不是。青岛、山东是1，莱芜是0' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'dcSubSite', @level2type=N'COLUMN',@level2name=N'IsMainSite'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'标题' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'dcVip', @level2type=N'COLUMN',@level2name=N'name'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'开始时间' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'dcVip', @level2type=N'COLUMN',@level2name=N'startDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'结束时间' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'dcVip', @level2type=N'COLUMN',@level2name=N'endDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'职位价格' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'dcVip', @level2type=N'COLUMN',@level2name=N'PriceJob'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'用户数的价格' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'dcVip', @level2type=N'COLUMN',@level2name=N'PriceUser'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'一份简历下载的价格' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'dcVip', @level2type=N'COLUMN',@level2name=N'PriceResume'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'月度会员的标准价' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'dcVip', @level2type=N'COLUMN',@level2name=N'PriceMonth'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'备注' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'dcVip', @level2type=N'COLUMN',@level2name=N'Remark'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'标题' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'dcVipDetail', @level2type=N'COLUMN',@level2name=N'DetailName'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'套餐有效期的标题' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'dcVipDetail', @level2type=N'COLUMN',@level2name=N'TimeTitle'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'几个月' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'dcVipDetail', @level2type=N'COLUMN',@level2name=N'Month'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'职位数' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'dcVipDetail', @level2type=N'COLUMN',@level2name=N'JobNumber'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'用户数' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'dcVipDetail', @level2type=N'COLUMN',@level2name=N'UserNumber'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'简历下载数' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'dcVipDetail', @level2type=N'COLUMN',@level2name=N'ResumeNumber'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'总价格' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'dcVipDetail', @level2type=N'COLUMN',@level2name=N'Price'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'备注' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'dcVipDetail', @level2type=N'COLUMN',@level2name=N'Remark'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'部门名称' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Dept', @level2type=N'COLUMN',@level2name=N'DeptName'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'部门级别，1级，2级，3级' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Dept', @level2type=N'COLUMN',@level2name=N'Grade'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'上级部门，0表示没有上级' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Dept', @level2type=N'COLUMN',@level2name=N'Superior'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'满员数量' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Dept', @level2type=N'COLUMN',@level2name=N'FullNumber'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'文档名称' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'dwndoc', @level2type=N'COLUMN',@level2name=N'name'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'语言。1中文；2英文' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'dwndoc', @level2type=N'COLUMN',@level2name=N'lgg'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'文档类型。1WORD；2PDF；3XLS；4PPT' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'dwndoc', @level2type=N'COLUMN',@level2name=N'filetype'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'文档简介' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'dwndoc', @level2type=N'COLUMN',@level2name=N'description'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'授权方式。1免费；2收费' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'dwndoc', @level2type=N'COLUMN',@level2name=N'authtype'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'下载次数' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'dwndoc', @level2type=N'COLUMN',@level2name=N'dwnnum'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'文档所属类' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'dwndoc', @level2type=N'COLUMN',@level2name=N'classid'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'0,未检查;1,已收到;2,未收到;3,被列入垃圾邮件' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Email_SentTest_Log', @level2type=N'COLUMN',@level2name=N'status'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'1,个人常规;2,单位常规;3,个人群发;4,单位群发' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Email_SentTest_Log', @level2type=N'COLUMN',@level2name=N'type'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'1，订阅的简历' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'EmailCompany', @level2type=N'COLUMN',@level2name=N'Type'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'面试时间' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'exInterview', @level2type=N'COLUMN',@level2name=N'InterviewDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'面试地点' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'exInterview', @level2type=N'COLUMN',@level2name=N'InterViewPlace'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'联系人' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'exInterview', @level2type=N'COLUMN',@level2name=N'LinkMan'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'联系电话' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'exInterview', @level2type=N'COLUMN',@level2name=N'Telephone'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'面试备注' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'exInterview', @level2type=N'COLUMN',@level2name=N'Remark'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'回复状态　0：未回复 ，1：赴约，2：不赴约 ' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'exInterview', @level2type=N'COLUMN',@level2name=N'Reply'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'不赴约的原因' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'exInterview', @level2type=N'COLUMN',@level2name=N'ReplyMessage'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'回复时间' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'exInterview', @level2type=N'COLUMN',@level2name=N'Replydate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'单位是否删除' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'exInterview', @level2type=N'COLUMN',@level2name=N'CompanyDeleted'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'单位删除时间' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'exInterview', @level2type=N'COLUMN',@level2name=N'CompanyDeleteDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'个人是否删除' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'exInterview', @level2type=N'COLUMN',@level2name=N'PersonDeleted'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'个人删除时间' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'exInterview', @level2type=N'COLUMN',@level2name=N'PersonDeleteDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'个人是否查看' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'exInterview', @level2type=N'COLUMN',@level2name=N'ViewDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'前台面试通知记录表' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'exInterview'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'求职信,paCoverLetter.MainText' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'exJobApply', @level2type=N'COLUMN',@level2name=N'ApplyMessage'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'企业删除,0未删除,1删除' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'exJobApply', @level2type=N'COLUMN',@level2name=N'CompanyDeleted'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'企业删除日期,在个人会员中心有提示' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'exJobApply', @level2type=N'COLUMN',@level2name=N'CompanyDeleteDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'个人删除,0未删除,1删除' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'exJobApply', @level2type=N'COLUMN',@level2name=N'PersonDeleted'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'0未答复 1符合要求 2不合适' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'exJobApply', @level2type=N'COLUMN',@level2name=N'Reply'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'回复时间' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'exJobApply', @level2type=N'COLUMN',@level2name=N'ReplyDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'申请职位时，企业对该简历的查看权限。根据简历是否开放，企业权限等计算。自申请时间起不再修改。
0：未通过，需要检查；1：通过了，不需要检查
与VIP、普通会员有关。与无限制、储值无关。' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'exJobApply', @level2type=N'COLUMN',@level2name=N'IsPassed'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'前台，申请职位记录表' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'exJobApply'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'留言内容' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'exMessageC2P', @level2type=N'COLUMN',@level2name=N'Message'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'个人是否查看,0未查看，1已查看' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'exMessageC2P', @level2type=N'COLUMN',@level2name=N'IsViewed'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'个人是否回复,0未回复，1已回复' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'exMessageC2P', @level2type=N'COLUMN',@level2name=N'IsReply'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'企业是否删除,0未删除，1已删除' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'exMessageC2P', @level2type=N'COLUMN',@level2name=N'CompanyDeleted'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'个人是否删除,0未删除，1已删除' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'exMessageC2P', @level2type=N'COLUMN',@level2name=N'PersonDeleted'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'前台，企业对个人留言记录表' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'exMessageC2P'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'留言内容' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'exMessageP2C', @level2type=N'COLUMN',@level2name=N'Message'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'留言时间' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'exMessageP2C', @level2type=N'COLUMN',@level2name=N'AddDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'企业是否查看,0未查看，1已查看' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'exMessageP2C', @level2type=N'COLUMN',@level2name=N'IsViewed'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'企业是否回复,0未回复，1已回复' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'exMessageP2C', @level2type=N'COLUMN',@level2name=N'IsReply'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'企业是否删除,0未删除，1已删除' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'exMessageP2C', @level2type=N'COLUMN',@level2name=N'CompanyDeleted'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'个人是否删除,0未删除，1已删除' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'exMessageP2C', @level2type=N'COLUMN',@level2name=N'PersonDeleted'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'前台，个人对企业留言表' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'exMessageP2C'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'企业ID' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'ExtendLink', @level2type=N'COLUMN',@level2name=N'CpMainID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'申请时间' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'ExtendLink', @level2type=N'COLUMN',@level2name=N'AddDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'关键字' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'ExtendLink', @level2type=N'COLUMN',@level2name=N'Keyword'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'外链的URL' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'ExtendLink', @level2type=N'COLUMN',@level2name=N'KeywordUrl'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'企业的网站URL' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'ExtendLink', @level2type=N'COLUMN',@level2name=N'CustomLink'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'1即将运行，2正在运行，3历史的，4客户要求撤销的。
' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'ExtendLink', @level2type=N'COLUMN',@level2name=N'RunStatus'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'1、正在审核
2、无链接
3、正常
4、已撤链
5、贵公司网址添加错误   
6、黑名单
7、贵公司网站打不开   
8、关键词错误 
9、贵网站不符合要求
' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'ExtendLink', @level2type=N'COLUMN',@level2name=N'LinkStatus'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'优惠类型，1-职位置顶，2-职位刷新，3赠送简历' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'ExtendLink', @level2type=N'COLUMN',@level2name=N'ShowType'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'开始日期的天数部分' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'ExtendLink', @level2type=N'COLUMN',@level2name=N'ShowDay'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'如果是职位置顶，所选择的置顶的职位' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'ExtendLink', @level2type=N'COLUMN',@level2name=N'IDs'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'加入黑名单原因' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'ExtendLink', @level2type=N'COLUMN',@level2name=N'BlackReason'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'如果是机器检查=0' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'ExtendLinkCheckLog', @level2type=N'COLUMN',@level2name=N'ID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'2未加链接 3正常 4撤链 5异常 6黑名单' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'ExtendLinkCheckLog', @level2type=N'COLUMN',@level2name=N'CheckResult'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'企业ID' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'ExtendLinkRunLog', @level2type=N'COLUMN',@level2name=N'CpMainID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'优惠类型，1-职位置顶，2-职位刷新，3赠送简历' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'ExtendLinkRunLog', @level2type=N'COLUMN',@level2name=N'ShowType'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'开始时间' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'ExtendLinkRunLog', @level2type=N'COLUMN',@level2name=N'BeginDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'结束时间' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'ExtendLinkRunLog', @level2type=N'COLUMN',@level2name=N'EndDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'如果是职位置顶，所选择的置顶的职位' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'ExtendLinkRunLog', @level2type=N'COLUMN',@level2name=N'IDs'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'1 转账支票
2 现金支票
3 贷记凭证
4 银行电汇单
5 网银支付' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'FnBankCheck', @level2type=N'COLUMN',@level2name=N'Kind'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'1网聚精英中行,2上海助择农行,3网聚莱芜工行,4网聚精英支付宝,5上海助择支付宝,6助择莱芜工行,7网聚浦发,8助择浦发' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'FnBankCheck', @level2type=N'COLUMN',@level2name=N'Concern'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'2等待审批,3已审批,4审批不通过,5付讫未对账,8已对账未核销,6已核销,7作废' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'FnBankCheck', @level2type=N'COLUMN',@level2name=N'Status'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'1网聚精英中行,2上海助择农行,3网聚莱芜工行,4网聚精英支付宝,5上海助择支付宝,6助择莱芜工行,7网聚浦发,8助择浦发' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'FnBankDaybook', @level2type=N'COLUMN',@level2name=N'Concern'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'关联类型 1梧桐果 null齐鲁 ' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'FnBankDaybook', @level2type=N'COLUMN',@level2name=N'RelationType'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'1借款,2还款,3报销,11增加备用金,20盘存' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'FnCash', @level2type=N'COLUMN',@level2name=N'kind'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'经手人ID' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'FnCash', @level2type=N'COLUMN',@level2name=N'handleMan'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'经手人' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'FnCash', @level2type=N'COLUMN',@level2name=N'handleManname'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'1，等待审批；2，审批通过等待会计审核；3，审批不通过；4，会计审核通过等待付讫；5，会计审核不通过；6，付讫未核销；7，已核销未记账；8，作废；9，已记账' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'FnCash', @level2type=N'COLUMN',@level2name=N'status'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'申请人ID' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'FnCash', @level2type=N'COLUMN',@level2name=N'Drawer'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'申请人' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'FnCash', @level2type=N'COLUMN',@level2name=N'DrawerMan'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'1,网聚精英;2,上海助择;3,网聚莱芜;4,助择莱芜' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'FnCash', @level2type=N'COLUMN',@level2name=N'Concern'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'记账日期' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'FnCash', @level2type=N'COLUMN',@level2name=N'BKDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'2网聚精英，4上海助择' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'FnInvoice', @level2type=N'COLUMN',@level2name=N'Concern'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'0未开；1已开出；10已作废；11已退票' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'FnInvoice', @level2type=N'COLUMN',@level2name=N'Status'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'退票对应的发票号码' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'FnInvoice', @level2type=N'COLUMN',@level2name=N'ReturnFnInvoiceId'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'1、增值税普通发票；2、增值税专用发票；3、国税普通发票' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'FnInvoice', @level2type=N'COLUMN',@level2name=N'FnInvoiceType'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'挂号信或者快递单编号' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'FnLetter', @level2type=N'COLUMN',@level2name=N'PostNumber'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'写在信封上的手机号' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'FnLetter', @level2type=N'COLUMN',@level2name=N'PostTelephone'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'收信人地址' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'FnLetter', @level2type=N'COLUMN',@level2name=N'PostAddress'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'收信人' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'FnLetter', @level2type=N'COLUMN',@level2name=N'Recipient'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'发票ID' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'FnLetter', @level2type=N'COLUMN',@level2name=N'FnInvoiceID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'收信人邮政编码' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'FnLetter', @level2type=N'COLUMN',@level2name=N'Zip'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'邮寄人工号' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'FnLetter', @level2type=N'COLUMN',@level2name=N'Postman'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'邮寄人姓名' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'FnLetter', @level2type=N'COLUMN',@level2name=N'PostmanName'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'备注' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'FnLetter', @level2type=N'COLUMN',@level2name=N'Remarks'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'0，已封装未邮寄；1，已邮寄未签收；2，客户已签收；3，已退件；4，已作废' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'FnLetter', @level2type=N'COLUMN',@level2name=N'Status'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'邮寄时间' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'FnLetter', @level2type=N'COLUMN',@level2name=N'PostDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'退回原因' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'FnLetter', @level2type=N'COLUMN',@level2name=N'ReturnReason'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'公司名称' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'FnLetter', @level2type=N'COLUMN',@level2name=N'Companyname'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'退回时间' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'FnLetter', @level2type=N'COLUMN',@level2name=N'ReturnDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'退回操作人' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'FnLetter', @level2type=N'COLUMN',@level2name=N'ReturnMan'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'退回操作人姓名' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'FnLetter', @level2type=N'COLUMN',@level2name=N'ReturnManName'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'签收人（客户）' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'FnLetter', @level2type=N'COLUMN',@level2name=N'ReceivedManName'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'签收时间' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'FnLetter', @level2type=N'COLUMN',@level2name=N'ReceivedDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'作废时间' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'FnLetter', @level2type=N'COLUMN',@level2name=N'InvalidDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'作废操作人工号' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'FnLetter', @level2type=N'COLUMN',@level2name=N'InvalidMan'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'作废操作人姓名' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'FnLetter', @level2type=N'COLUMN',@level2name=N'InvalidManName'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'邮资' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'FnLetter', @level2type=N'COLUMN',@level2name=N'Fee'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'1北京  2上海  3共用' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'FnPICDaybook', @level2type=N'COLUMN',@level2name=N'Concern'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'7工商银行，9招商银行，10农业银行，12建设银行，21微信' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'FnPICDaybook', @level2type=N'COLUMN',@level2name=N'Paymethod'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'关联类型 1 梧桐果  null齐鲁' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'FnPICDaybook', @level2type=N'COLUMN',@level2name=N'RelationType'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'1:首页热门搜索；2：快速搜索；3：常用搜索' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'fpCommonSearch', @level2type=N'COLUMN',@level2name=N'SearchType'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'1：职场新闻；2：招聘会；3：用户调查' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'fpHomepageImage', @level2type=N'COLUMN',@level2name=N'ImageType'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'1，大省，每天单独做。2，小省，每天合并做。' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'group_province', @level2type=N'COLUMN',@level2name=N'bigsmall'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'1招聘会、2政府招考、3校园招聘、4就业咨询、5用户调查；格式为1,2,3,4,5 以,分割' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'hpNewsSet', @level2type=N'COLUMN',@level2name=N'Section'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'信息员每天注册的手机号数量' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'info_Datereport', @level2type=N'COLUMN',@level2name=N'MobileNum'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'信息员每天反回的手机号数量' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'info_Datereport', @level2type=N'COLUMN',@level2name=N'MobileReturn'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'信息员每天审核同过的手机号数量' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'info_Datereport', @level2type=N'COLUMN',@level2name=N'MobileAccount'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'1职位页面 2公司页面 3新闻页面 4招聘会页面 5求职互助页面 6职位地图 7兼职招聘 8校园招聘 9专业分类 10 /jinan_job/zhangqiu/  15职位地图jobmap/1802.html 20县级新闻列表/zhangqiu/news/ 21个人文档下载 100其它' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'innerer', @level2type=N'COLUMN',@level2name=N'Innerpage'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'调查题目' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Investigation', @level2type=N'COLUMN',@level2name=N'Title'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'调查介绍' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Investigation', @level2type=N'COLUMN',@level2name=N'Description'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'增加日期' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Investigation', @level2type=N'COLUMN',@level2name=N'AddDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'截止日期' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Investigation', @level2type=N'COLUMN',@level2name=N'EndDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'1,临时性黑名单;2,固定黑名单' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Ip_Black', @level2type=N'COLUMN',@level2name=N'type'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'1,蜘蛛白名单，2用户白名单' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Ip_White', @level2type=N'COLUMN',@level2name=N'Kind'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'1 只显示标题，2，只显示文本，3，都显示' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'ivgt_answer', @level2type=N'COLUMN',@level2name=N'showType'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'1调查报告  2专家点评' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'ivgt_investigation', @level2type=N'COLUMN',@level2name=N'ReportType'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'日报日期' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'ivrDayReport', @level2type=N'COLUMN',@level2name=N'CountDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'部门id' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'ivrDayReport', @level2type=N'COLUMN',@level2name=N'DeptId'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'工号' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'ivrDayReport', @level2type=N'COLUMN',@level2name=N'ManagerUserId'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'员工姓名' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'ivrDayReport', @level2type=N'COLUMN',@level2name=N'Name'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'参加考核' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'ivrDayReport', @level2type=N'COLUMN',@level2name=N'IsCheck'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'电话个数' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'ivrDayReport', @level2type=N'COLUMN',@level2name=N'RealNumber'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'电话时长' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'ivrDayReport', @level2type=N'COLUMN',@level2name=N'RealMinute'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'工时' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'ivrDayReport', @level2type=N'COLUMN',@level2name=N'RealWorkTime'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'折算后个数' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'ivrDayReport', @level2type=N'COLUMN',@level2name=N'ConvertNumber'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'折算后时长' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'ivrDayReport', @level2type=N'COLUMN',@level2name=N'ConvertMinute'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'备注' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'ivrDayReport', @level2type=N'COLUMN',@level2name=N'Remark'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'状态 1部门经理提交；2质管部确认' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'ivrDayReport', @level2type=N'COLUMN',@level2name=N'Status'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'1空岗；2请假' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'ivrDayReport', @level2type=N'COLUMN',@level2name=N'ManagerStatus'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'1，抽查;Null 不抽查' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Ivrlist_Day', @level2type=N'COLUMN',@level2name=N'selective'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'职位名称' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Job', @level2type=N'COLUMN',@level2name=N'Name'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'主要职位类型' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Job', @level2type=N'COLUMN',@level2name=N'dcJobTypeID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'次要职位类型' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Job', @level2type=N'COLUMN',@level2name=N'dcJobTypeIDMinor'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'招聘人数代码，见dcOthers字典表' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Job', @level2type=N'COLUMN',@level2name=N'NeedNumber'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'最低月薪代码，见dcSalary字典表' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Job', @level2type=N'COLUMN',@level2name=N'dcSalaryID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'工作性质,1全职，3兼职，4实习' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Job', @level2type=N'COLUMN',@level2name=N'EmployType'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'工作地区,dcRegin' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Job', @level2type=N'COLUMN',@level2name=N'dcRegionID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'地图标注,公司名称·职位名称' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Job', @level2type=N'COLUMN',@level2name=N'MapBarID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'职位描述，包括岗位职责、工作环境、福利待遇等。转换的时候，过滤掉&nbsp; <br>' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Job', @level2type=N'COLUMN',@level2name=N'Responsibility'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'职位要求，包括工作经验、职业技能等对求职者的要求。转换的时候，过滤掉&nbsp; <br>' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Job', @level2type=N'COLUMN',@level2name=N'Demand'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'学历，dcEducationID' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Job', @level2type=N'COLUMN',@level2name=N'dcEducationID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'最低工作经验代码,dcOthers字典表' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Job', @level2type=N'COLUMN',@level2name=N'MinExperience'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'最低年龄' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Job', @level2type=N'COLUMN',@level2name=N'MinAge'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'最大年龄' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Job', @level2type=N'COLUMN',@level2name=N'MaxAge'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'邮件订阅频率(0,不订阅  1,每天1次  2,每2天1次  3,每3天1次  7,每周1次  14,每2周1次' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Job', @level2type=N'COLUMN',@level2name=N'EMailSendFreq'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'电子邮件每次发送数量' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Job', @level2type=N'COLUMN',@level2name=N'EMailSendNumber'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'最后一次发送邮件时间' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Job', @level2type=N'COLUMN',@level2name=N'LastEmailDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'显示顺序' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Job', @level2type=N'COLUMN',@level2name=N'DisplayNo'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'发布日期，计划发布从00:00开始，立即发布当前日期减10分钟' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Job', @level2type=N'COLUMN',@level2name=N'IssueDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'发布结束日期，计划结束的到23:59，立即结束到当前日期' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Job', @level2type=N'COLUMN',@level2name=N'IssueEnd'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'删除标记，1-统一删除,60天以后删除，jobdeleted' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Job', @level2type=N'COLUMN',@level2name=N'IsDelete'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'申请职位累计数,一直增长，永不清零' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Job', @level2type=N'COLUMN',@level2name=N'ApplyNumber'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'职位被查看次数' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Job', @level2type=N'COLUMN',@level2name=N'ViewNumber'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'添加日期,永不变化' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Job', @level2type=N'COLUMN',@level2name=N'AddDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'刷新日期,每次登陆自动刷新(1个小时内不更新)，计划任务自动刷新' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Job', @level2type=N'COLUMN',@level2name=N'RefreshDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'最后修改时间' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Job', @level2type=N'COLUMN',@level2name=N'LastModifyDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'发布中的职位,IssueData,IssueEnd,IsDelete,触发器保证' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Job', @level2type=N'COLUMN',@level2name=N'Valid'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'保险' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Job', @level2type=N'COLUMN',@level2name=N'Welfare1'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'公积金' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Job', @level2type=N'COLUMN',@level2name=N'Welfare2'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'双休' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Job', @level2type=N'COLUMN',@level2name=N'Welfare3'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'年终奖' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Job', @level2type=N'COLUMN',@level2name=N'Welfare4'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'带薪年假' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Job', @level2type=N'COLUMN',@level2name=N'Welfare5'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'公费旅游' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Job', @level2type=N'COLUMN',@level2name=N'Welfare6'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'餐补' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Job', @level2type=N'COLUMN',@level2name=N'Welfare7'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'交通补贴' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Job', @level2type=N'COLUMN',@level2name=N'Welfare8'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'8小时工作制' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Job', @level2type=N'COLUMN',@level2name=N'Welfare9'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'提供住宿' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Job', @level2type=N'COLUMN',@level2name=N'Welfare10'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'节日福利' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Job', @level2type=N'COLUMN',@level2name=N'Welfare11'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'公费培训' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Job', @level2type=N'COLUMN',@level2name=N'Welfare12'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'奖金提成' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Job', @level2type=N'COLUMN',@level2name=N'Welfare13'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'全勤奖' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Job', @level2type=N'COLUMN',@level2name=N'Welfare14'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'班车接送' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Job', @level2type=N'COLUMN',@level2name=N'Welfare15'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'健康体检' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Job', @level2type=N'COLUMN',@level2name=N'Welfare16'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'通讯补贴' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Job', @level2type=N'COLUMN',@level2name=N'Welfare17'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'住房补贴' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Job', @level2type=N'COLUMN',@level2name=N'Welfare18'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'职位名称' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'JobPublish', @level2type=N'COLUMN',@level2name=N'Name'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'招聘人数代码，见dcOthers字典表' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'JobPublish', @level2type=N'COLUMN',@level2name=N'NeedNumber'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'最低月薪代码，见dcSalary字典表' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'JobPublish', @level2type=N'COLUMN',@level2name=N'dcSalaryID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'工作性质,1全职，3兼职，4实习' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'JobPublish', @level2type=N'COLUMN',@level2name=N'EmployType'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'工作地区,dcRegin' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'JobPublish', @level2type=N'COLUMN',@level2name=N'dcRegionID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'职位描述，包括岗位职责、工作环境、福利待遇等。转换的时候，过滤掉&nbsp; <br>' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'JobPublish', @level2type=N'COLUMN',@level2name=N'Responsibility'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'职位要求，包括工作经验、职业技能等对求职者的要求。转换的时候，过滤掉&nbsp; <br>' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'JobPublish', @level2type=N'COLUMN',@level2name=N'Demand'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'学历，dcEducationID' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'JobPublish', @level2type=N'COLUMN',@level2name=N'dcEducationID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'最低工作经验代码,dcOthers字典表' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'JobPublish', @level2type=N'COLUMN',@level2name=N'MinExperience'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'最低年龄' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'JobPublish', @level2type=N'COLUMN',@level2name=N'MinAge'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'最大年龄' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'JobPublish', @level2type=N'COLUMN',@level2name=N'MaxAge'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'发布日期，计划发布从00:00开始，立即发布当前日期减10分钟' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'JobPublish', @level2type=N'COLUMN',@level2name=N'IssueDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'发布结束日期，计划结束的到23:59，立即结束到当前日期' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'JobPublish', @level2type=N'COLUMN',@level2name=N'IssueEnd'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'删除标记，1-统一删除,60天以后删除，jobdeleted' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'JobPublish', @level2type=N'COLUMN',@level2name=N'IsDelete'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'添加日期,永不变化' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'JobPublish', @level2type=N'COLUMN',@level2name=N'AddDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'刷新日期,每次登陆自动刷新(1个小时内不更新)，计划任务自动刷新' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'JobPublish', @level2type=N'COLUMN',@level2name=N'RefreshDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'最后修改时间' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'JobPublish', @level2type=N'COLUMN',@level2name=N'LastModifyDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'发布中的职位,IssueData,IssueEnd,IsDelete,触发器保证' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'JobPublish', @level2type=N'COLUMN',@level2name=N'Valid'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'空为手动刷新' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'jobRefreshLog', @level2type=N'COLUMN',@level2name=N'jobRefreshSetId'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'执行刷新时，更新该字段' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'jobRefreshLog', @level2type=N'COLUMN',@level2name=N'orderId'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'职位名称；地区' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'jobRefreshLog', @level2type=N'COLUMN',@level2name=N'jobInfo'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'0 定时刷新 1手动刷新' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'jobRefreshLog', @level2type=N'COLUMN',@level2name=N'refreshType'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'定时刷新中预定的刷新时间' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'jobRefreshLog', @level2type=N'COLUMN',@level2name=N'preRefreshDateTime'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'执行刷新的时间' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'jobRefreshLog', @level2type=N'COLUMN',@level2name=N'runDateTime'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'执行人' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'jobRefreshLog', @level2type=N'COLUMN',@level2name=N'operateMan'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'刷新开始时间' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'jobRefreshSet', @level2type=N'COLUMN',@level2name=N'beginDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'刷新结束时间' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'jobRefreshSet', @level2type=N'COLUMN',@level2name=N'endDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'1每天2每周' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'jobRefreshSet', @level2type=N'COLUMN',@level2name=N'refreshType'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'周几刷新如1,2,3,4' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'jobRefreshSet', @level2type=N'COLUMN',@level2name=N'weekDays'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'刷新的时刻 0,1,2,8,11,' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'jobRefreshSet', @level2type=N'COLUMN',@level2name=N'hours'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'刷新分钟' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'jobRefreshSet', @level2type=N'COLUMN',@level2name=N'minute'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'运行状态0 停止 1运行' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'jobRefreshSet', @level2type=N'COLUMN',@level2name=N'runState'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'添加时间' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'jobRefreshSet', @level2type=N'COLUMN',@level2name=N'addDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'保险' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'JobTemplate', @level2type=N'COLUMN',@level2name=N'Welfare1'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'公积金' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'JobTemplate', @level2type=N'COLUMN',@level2name=N'Welfare2'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'双休' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'JobTemplate', @level2type=N'COLUMN',@level2name=N'Welfare3'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'年终奖' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'JobTemplate', @level2type=N'COLUMN',@level2name=N'Welfare4'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'带薪年假' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'JobTemplate', @level2type=N'COLUMN',@level2name=N'Welfare5'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'公费旅游' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'JobTemplate', @level2type=N'COLUMN',@level2name=N'Welfare6'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'餐补' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'JobTemplate', @level2type=N'COLUMN',@level2name=N'Welfare7'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'交通补贴' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'JobTemplate', @level2type=N'COLUMN',@level2name=N'Welfare8'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'8小时工作制' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'JobTemplate', @level2type=N'COLUMN',@level2name=N'Welfare9'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'提供住宿' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'JobTemplate', @level2type=N'COLUMN',@level2name=N'Welfare10'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'节日福利' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'JobTemplate', @level2type=N'COLUMN',@level2name=N'Welfare11'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'奖金提成' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'JobTemplate', @level2type=N'COLUMN',@level2name=N'Welfare13'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'全勤奖' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'JobTemplate', @level2type=N'COLUMN',@level2name=N'Welfare14'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'班车接送' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'JobTemplate', @level2type=N'COLUMN',@level2name=N'Welfare15'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'健康体检' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'JobTemplate', @level2type=N'COLUMN',@level2name=N'Welfare16'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'通讯补贴' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'JobTemplate', @level2type=N'COLUMN',@level2name=N'Welfare17'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'住房补贴' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'JobTemplate', @level2type=N'COLUMN',@level2name=N'Welfare18'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'0等待确认,1确认有效,2申诉中,3确认无效,4改善完成,6无法完成' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'KPI_IE', @level2type=N'COLUMN',@level2name=N'status'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'1，技术类；2，管理类；3，行政综合类；4，市场推广类；5，财务类；6，内部工作流程优化类；11，技术类BUG' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'KPI_IE', @level2type=N'COLUMN',@level2name=N'kind'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'0,等待确认;1,确认有效;2,申诉中;3,确认无效;4,验收通过;5,验收不通过' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'KPI_KM', @level2type=N'COLUMN',@level2name=N'Status'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'0,等待签收;1,已签收，未完成;2,已完成，等待验收;3,无法完成;4,已验收，完成得很好;5,已验收，基本完成' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'KPI_LP', @level2type=N'COLUMN',@level2name=N'Status'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'验收评语' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'KPI_LP', @level2type=N'COLUMN',@level2name=N'CheckComment'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'最近一次自看时间' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'KPI_OC', @level2type=N'COLUMN',@level2name=N'Last_Date'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'真实姓名' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'ManagerUser', @level2type=N'COLUMN',@level2name=N'name'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'是否显示招聘顾问的姓名0不显示，1显示' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'ManagerUser', @level2type=N'COLUMN',@level2name=N'OpenName'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'直接上级，0表示没有上级' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'ManagerUser', @level2type=N'COLUMN',@level2name=N'superior'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'职务' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'ManagerUser', @level2type=N'COLUMN',@level2name=N'title'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'所属角色' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'ManagerUser', @level2type=N'COLUMN',@level2name=N'roleid'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'所属部门' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'ManagerUser', @level2type=N'COLUMN',@level2name=N'deptid'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'1,HunterI;2,Farmer;3,HunterO;4,信息员;5,客服;6,猎头顾问' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'ManagerUser', @level2type=N'COLUMN',@level2name=N'type'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'1,试用;2,正式;3,离职;4,长假;' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'ManagerUser', @level2type=N'COLUMN',@level2name=N'status'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'1,正常;2,暂停' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'ManagerUser', @level2type=N'COLUMN',@level2name=N'loginstatus'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'信息员本地化分析' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'ManagerUser', @level2type=N'COLUMN',@level2name=N'localrate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'1，主管人员；2，非主管人员' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'ManagerUser', @level2type=N'COLUMN',@level2name=N'kpi_manager'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'KPI考核KM最少数量' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'ManagerUser', @level2type=N'COLUMN',@level2name=N'km'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'IE单要求' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'ManagerUser', @level2type=N'COLUMN',@level2name=N'km_score'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'手机号码' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'ManagerUser', @level2type=N'COLUMN',@level2name=N'mobile'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'0-离线；1-在线；2-离开；10-没有该账号' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'ManagerUser', @level2type=N'COLUMN',@level2name=N'rtxstatus'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'客户数量上限（有营业执照的非死客户）' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'ManagerUser', @level2type=N'COLUMN',@level2name=N'consultantnum_up'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'当前客户数（有营业执照的非死客户）' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'ManagerUser', @level2type=N'COLUMN',@level2name=N'consultantnum'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'客户数量上限（最新上传的营业执照）' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'ManagerUser', @level2type=N'COLUMN',@level2name=N'consultantnum_up_new'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'当前客户数（最新上传的营业执照）' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'ManagerUser', @level2type=N'COLUMN',@level2name=N'consultantnum_new'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'每月释放配额' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'ManagerUser', @level2type=N'COLUMN',@level2name=N'consultantnum_quota'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'当月释放' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'ManagerUser', @level2type=N'COLUMN',@level2name=N'consultantnum_release'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'上个月释放' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'ManagerUser', @level2type=N'COLUMN',@level2name=N'consultantnum_release_lastmonth'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'5初级顾问；10中级顾问；15高级顾问；20金牌顾问；25资深顾问；30客户经理；35高级客户经理' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'ManagerUser', @level2type=N'COLUMN',@level2name=N'SalesLevel'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Min:5,max:10' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'msEmailPrevSend', @level2type=N'COLUMN',@level2name=N'JasonData'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'发邮件的服务器，mail.qlrc.com' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'msEmailSend', @level2type=N'COLUMN',@level2name=N'Host'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'发件人，serve@qlrc.com' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'msEmailSend', @level2type=N'COLUMN',@level2name=N'UserName'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'对方的email，sdlgyxl@163.com' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'msEmailSend', @level2type=N'COLUMN',@level2name=N'Email'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'邮件标题' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'msEmailSend', @level2type=N'COLUMN',@level2name=N'Title'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'邮件正文' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'msEmailSend', @level2type=N'COLUMN',@level2name=N'EmailBody'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'jmail的返回值，1成功；0 不成功' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'msEmailSend', @level2type=N'COLUMN',@level2name=N'Status'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'添加时间' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'msEmailSend', @level2type=N'COLUMN',@level2name=N'AddDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'1普通邮件；2订阅l类的，主从结构' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'msEmailTemplete', @level2type=N'COLUMN',@level2name=N'msSqlID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'邮件模板名称' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'msEmailTemplete', @level2type=N'COLUMN',@level2name=N'Name'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'邮件的标题，支持变量，#sitename#个人用户注册通知' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'msEmailTemplete', @level2type=N'COLUMN',@level2name=N'Title'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'邮件正文的模板' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'msEmailTemplete', @level2type=N'COLUMN',@level2name=N'MailBody'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'和Sql一致，子查询的模板' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'msEmailTemplete', @level2type=N'COLUMN',@level2name=N'SubMailBody'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'emailtype=2时，子查询无数据时的正文模板，如果无内容则使用mailbody' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'msEmailTemplete', @level2type=N'COLUMN',@level2name=N'NoDataBody'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'0正在修改；1已提交' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'msEmailTemplete', @level2type=N'COLUMN',@level2name=N'Status'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'1普通邮件；2订阅l类的，主从结构' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'msEmailTempleteEdit', @level2type=N'COLUMN',@level2name=N'msSqlID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'邮件模板名称' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'msEmailTempleteEdit', @level2type=N'COLUMN',@level2name=N'Name'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'邮件的标题，支持变量，#sitename#个人用户注册通知' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'msEmailTempleteEdit', @level2type=N'COLUMN',@level2name=N'Title'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'邮件正文的模板' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'msEmailTempleteEdit', @level2type=N'COLUMN',@level2name=N'MailBody'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'和Sql一致，子查询的模板' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'msEmailTempleteEdit', @level2type=N'COLUMN',@level2name=N'SubMailBody'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'emailtype=2时，子查询无数据时的正文模板，如果无内容则使用mailbody' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'msEmailTempleteEdit', @level2type=N'COLUMN',@level2name=N'NoDataBody'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'邮件类型的名称  长时间不登陆的个人用户提醒' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'msEmailType', @level2type=N'COLUMN',@level2name=N'Name'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'只允许对某些邮件服务器发送邮件，以逗号间隔。@163.com,@sina.com' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'msEmailType', @level2type=N'COLUMN',@level2name=N'AllowedSite'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'不只允许对某些邮件服务器发送邮件，以逗号间隔。@163.com,@sina.com' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'msEmailType', @level2type=N'COLUMN',@level2name=N'BannedSite'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'该类型对应的省份，以逗号间隔' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'msEmailType', @level2type=N'COLUMN',@level2name=N'ProvinceIds'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'发送人' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'msEmailType', @level2type=N'COLUMN',@level2name=N'Sender'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'对Sql、emailtemplete的参数的确定直，比如：max=37&min30&long=一个月' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'msEmailType', @level2type=N'COLUMN',@level2name=N'ParamValue'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'0未提交；2审核通过；' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'msEmailType', @level2type=N'COLUMN',@level2name=N'Status'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'是否暂停' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'msEmailType', @level2type=N'COLUMN',@level2name=N'IsPause'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'邮件类型的名称  长时间不登陆的个人用户提醒' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'msEmailTypeEdit', @level2type=N'COLUMN',@level2name=N'Name'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'只允许对某些邮件服务器发送邮件，以逗号间隔。@163.com,@sina.com' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'msEmailTypeEdit', @level2type=N'COLUMN',@level2name=N'AllowedSite'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'不只允许对某些邮件服务器发送邮件，以逗号间隔。@163.com,@sina.com' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'msEmailTypeEdit', @level2type=N'COLUMN',@level2name=N'BannedSite'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'该类型对应的省份，以逗号间隔' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'msEmailTypeEdit', @level2type=N'COLUMN',@level2name=N'ProvinceIds'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'对Sql、emailtemplete的参数的确定直，比如：max=37&min30&long=一个月' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'msEmailTypeEdit', @level2type=N'COLUMN',@level2name=N'ParamValue'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'0未提交；1待审核；2审核通过；' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'msEmailTypeEdit', @level2type=N'COLUMN',@level2name=N'Status'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'站点编号' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'msProcess', @level2type=N'COLUMN',@level2name=N'dcSubSiteId'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'最大运行时间（分钟），超过自动停止进程' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'msProcess', @level2type=N'COLUMN',@level2name=N'MaxRunMinute'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'发送间隔，秒' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'msProcess', @level2type=N'COLUMN',@level2name=N'SendInterval'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'下一次的运行时间，每次启动该类进程的哦是计算' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'msProcess', @level2type=N'COLUMN',@level2name=N'NextRunTime'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'进程的运行状态。0未运行过，1运行，2正常运行结束；3异常结束' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'msProcess', @level2type=N'COLUMN',@level2name=N'RunStatus'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'最近一次运行的发送数量' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'msProcess', @level2type=N'COLUMN',@level2name=N'SendNumber'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'抄送地址' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'msProcess', @level2type=N'COLUMN',@level2name=N'ccMail'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'多少封邮件中抄送一封，应该10～100之间' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'msProcess', @level2type=N'COLUMN',@level2name=N'ccRate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'计划名称，周一至周五5:10' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'msSchedule', @level2type=N'COLUMN',@level2name=N'Name'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'是否可用' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'msSchedule', @level2type=N'COLUMN',@level2name=N'Enabled'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'每天 每周等' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'msSchedule', @level2type=N'COLUMN',@level2name=N'FreqType'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'如果是周的话，进行位运算' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'msSchedule', @level2type=N'COLUMN',@level2name=N'FreqInterval'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'0执行1次，1间隔内不循环，4分钟 8小时' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'msSchedule', @level2type=N'COLUMN',@level2name=N'FreqSubdayType'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'格式20110101' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'msSchedule', @level2type=N'COLUMN',@level2name=N'ActiveStartDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'sql语句的标题' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'msSql', @level2type=N'COLUMN',@level2name=N'Name'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'主sql语句' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'msSql', @level2type=N'COLUMN',@level2name=N'Sql'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'输入参数，类似（Min：最小时间：数字，比如28；max：最大时间；）' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'msSql', @level2type=N'COLUMN',@level2name=N'ParamIn'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'输出参数' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'msSql', @level2type=N'COLUMN',@level2name=N'ParamOut'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'子Sql语句，用于订阅类的邮件' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'msSql', @level2type=N'COLUMN',@level2name=N'SubSql'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'发送一个邮件后执行的sql语句' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'msSql', @level2type=N'COLUMN',@level2name=N'AfterSendSql'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'一个邮件进程运行完毕后徐执行的sql语句' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'msSql', @level2type=N'COLUMN',@level2name=N'FinishedSql'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'备注' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'msSql', @level2type=N'COLUMN',@level2name=N'Remark'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'操作员' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'msSql', @level2type=N'COLUMN',@level2name=N'ManagerUserId'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'1运行；0暂停' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'msSql', @level2type=N'COLUMN',@level2name=N'Status'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'添加人' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'msSql', @level2type=N'COLUMN',@level2name=N'AddMan'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'添加时间' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'msSql', @level2type=N'COLUMN',@level2name=N'AddDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'关注的类型 1.企业 2.职位' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'PaAttention', @level2type=N'COLUMN',@level2name=N'AttentionType'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'是否默认求职信，0-否；1-是' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'paCoverLetter', @level2type=N'COLUMN',@level2name=N'IsDefault'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'标题' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'paCoverLetter', @level2type=N'COLUMN',@level2name=N'Title'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'内容' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'paCoverLetter', @level2type=N'COLUMN',@level2name=N'MainText'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'创建日期' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'paCoverLetter', @level2type=N'COLUMN',@level2name=N'AddDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'前台，个人求职信模版表' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'paCoverLetter'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'备注' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'paFavorate', @level2type=N'COLUMN',@level2name=N'Remark'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'前台，个人收藏夹' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'paFavorate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'反馈人姓名' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'paFeedback', @level2type=N'COLUMN',@level2name=N'Name'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'电话' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'paFeedback', @level2type=N'COLUMN',@level2name=N'Telephone'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'反馈信息' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'paFeedback', @level2type=N'COLUMN',@level2name=N'Message'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'客服是否回复' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'paFeedback', @level2type=N'COLUMN',@level2name=N'IsReply'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'回复信息' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'paFeedback', @level2type=N'COLUMN',@level2name=N'ReplyMessage'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'回复时间' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'paFeedback', @level2type=N'COLUMN',@level2name=N'ReplyDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'回复人' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'paFeedback', @level2type=N'COLUMN',@level2name=N'ReplyMan'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'个人查看时间' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'paFeedback', @level2type=N'COLUMN',@level2name=N'ViewDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'前台，个人对网站的反馈表' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'paFeedback'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'前台，个人取回密码记录表' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'paGetPasswordLog'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'职位类别' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'paJobFinder', @level2type=N'COLUMN',@level2name=N'dcJobTypeID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'行业类别' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'paJobFinder', @level2type=N'COLUMN',@level2name=N'dcIndustryID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'工作地点' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'paJobFinder', @level2type=N'COLUMN',@level2name=N'dcRegionID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'关键字类型 : 1 全文，2 职位名，3 公司名' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'paJobFinder', @level2type=N'COLUMN',@level2name=N'KeyType'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'关键字' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'paJobFinder', @level2type=N'COLUMN',@level2name=N'KeyWord'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'学历要求' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'paJobFinder', @level2type=N'COLUMN',@level2name=N'Education'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'招聘方式 ：1 全职 ，3 兼职 ，4 实习' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'paJobFinder', @level2type=N'COLUMN',@level2name=N'EmployType'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'最低工作经验' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'paJobFinder', @level2type=N'COLUMN',@level2name=N'MinExperience'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'月薪' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'paJobFinder', @level2type=N'COLUMN',@level2name=N'Salary'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'邮件订阅频率(0,不订阅;1,每天1次;2-每两天一次；3-每三天一次；7,每周1次；14-每两周一次' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'paJobFinder', @level2type=N'COLUMN',@level2name=N'EmailSent'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'邮件发送截止时间，过期不发送' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'paJobFinder', @level2type=N'COLUMN',@level2name=N'EmailEndDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'上次邮件订阅发送时间' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'paJobFinder', @level2type=N'COLUMN',@level2name=N'LastEmailDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'邮件订阅记录数，10,20,50,100' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'paJobFinder', @level2type=N'COLUMN',@level2name=N'EmailNumber'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'邮件订阅电子邮件' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'paJobFinder', @level2type=N'COLUMN',@level2name=N'Email'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'前台，个人职位搜索器表' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'paJobFinder'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'第三方给的唯一号' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'paLoginContact', @level2type=N'COLUMN',@level2name=N'Openid'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'第三方类型 1.腾讯' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'paLoginContact', @level2type=N'COLUMN',@level2name=N'ContactType'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'登陆类型。1 注册账号  2 现有绑定' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'paLoginContact', @level2type=N'COLUMN',@level2name=N'LoginType'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'浏览器版本' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'paLoginLog', @level2type=N'COLUMN',@level2name=N'Browser'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'1:计算机；2：手机;3:android' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'paLoginLog', @level2type=N'COLUMN',@level2name=N'LoginFrom'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'登陆时的用户名' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'paMain', @level2type=N'COLUMN',@level2name=N'UserName'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'小写的用户名，计算列，用于登录时判断是否有小写重复的用户名' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'paMain', @level2type=N'COLUMN',@level2name=N'UserNameLower'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'密码，新版最长20，原版有36位的' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'paMain', @level2type=N'COLUMN',@level2name=N'Password'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'0-非默认；1默认。用于推广注册，提示用户修改密码' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'paMain', @level2type=N'COLUMN',@level2name=N'IsDefaultPassword'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'账号注册时所在的省编号' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'paMain', @level2type=N'COLUMN',@level2name=N'dcProvinceID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'个人账号注册时或手册登录时的ip' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'paMain', @level2type=N'COLUMN',@level2name=N'RegisterIP'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'简历的注册方式的（0用户自己注册，1信息员注册，2离线简历注册（已废弃)，3、手机站注册，4、手机应用，5,apple app register,11，信息员注册，已统计） 。类型2 已经取消' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'paMain', @level2type=N'COLUMN',@level2name=N'RegisterMode'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'外键。注册该个人账号的信息员' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'paMain', @level2type=N'COLUMN',@level2name=N'AddMan'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'个人用户的姓名' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'paMain', @level2type=N'COLUMN',@level2name=N'Name'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'个人用户的英文名' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'paMain', @level2type=N'COLUMN',@level2name=N'NameEng'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'账号邮箱，非空' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'paMain', @level2type=N'COLUMN',@level2name=N'Email'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'性别，null-未填写；0-男；1-女' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'paMain', @level2type=N'COLUMN',@level2name=N'Gender'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'出生日期，精确到月，日都用1填充。例如：1986-12-1;1976-4-1' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'paMain', @level2type=N'COLUMN',@level2name=N'BirthDay'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'居住地，到县一级' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'paMain', @level2type=N'COLUMN',@level2name=N'LivePlace'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'户口所在地，县一级' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'paMain', @level2type=N'COLUMN',@level2name=N'AccountPlace'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'成长地，市级' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'paMain', @level2type=N'COLUMN',@level2name=N'GrowPlace'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'手机' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'paMain', @level2type=N'COLUMN',@level2name=N'Mobile'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'在线联系方式' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'paMain', @level2type=N'COLUMN',@level2name=N'OnlineContact'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'在线联系号码' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'paMain', @level2type=N'COLUMN',@level2name=N'OnlineContactNo'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'个人主页/博客' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'paMain', @level2type=N'COLUMN',@level2name=N'Homepage'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'婚姻状况。null 未填写
 0未选择　2 未婚 3 已婚 1 错误数据（可能是以前的未婚）
' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'paMain', @level2type=N'COLUMN',@level2name=N'Marriage'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'民族' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'paMain', @level2type=N'COLUMN',@level2name=N'Nation'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'身高，厘米' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'paMain', @level2type=N'COLUMN',@level2name=N'Height'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'求职状态' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'paMain', @level2type=N'COLUMN',@level2name=N'dcCareerStatus'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'null未上传，0上传，未审核；1-审核通过；2-审核不通过' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'paMain', @level2type=N'COLUMN',@level2name=N'HasPhoto'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'屏蔽公司，用<>区分' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'paMain', @level2type=N'COLUMN',@level2name=N'HideConditions'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'审核不通过次数' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'paMain', @level2type=N'COLUMN',@level2name=N'BlockCount'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'审核次数' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'paMain', @level2type=N'COLUMN',@level2name=N'VerifyCount'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'最近一次登录时间' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'paMain', @level2type=N'COLUMN',@level2name=N'LastLoginDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'总登录次数' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'paMain', @level2type=N'COLUMN',@level2name=N'TotalLoginNum'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'paMain表最后修改的时间(修改基本信息的时候更新)' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'paMain', @level2type=N'COLUMN',@level2name=N'LastModifyDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'帐号建立时间,一经建立不再改变' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'paMain', @level2type=N'COLUMN',@level2name=N'AddDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'32（山东），32（莱芜），3202（青岛）' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'paMain', @level2type=N'COLUMN',@level2name=N'dcSubSiteID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'性别，null-未填写；0-男；1-女' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'paMainPublish', @level2type=N'COLUMN',@level2name=N'Gender'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'出生日期，精确到月，日都用1填充。例如：1986-12-1;1976-4-1' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'paMainPublish', @level2type=N'COLUMN',@level2name=N'BirthDay'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'居住地，到县一级' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'paMainPublish', @level2type=N'COLUMN',@level2name=N'LivePlace'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'户口所在地，县一级' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'paMainPublish', @level2type=N'COLUMN',@level2name=N'AccountPlace'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'成长地，市级' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'paMainPublish', @level2type=N'COLUMN',@level2name=N'GrowPlace'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'身高，厘米' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'paMainPublish', @level2type=N'COLUMN',@level2name=N'Height'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'null未上传，0上传，未审核；1-审核通过；2-审核不通过' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'paMainPublish', @level2type=N'COLUMN',@level2name=N'HasPhoto'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'最近一次登录时间' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'paMainPublish', @level2type=N'COLUMN',@level2name=N'LastLoginDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'paMainPublish表最后修改的时间(修改基本信息的时候更新)' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'paMainPublish', @level2type=N'COLUMN',@level2name=N'LastModifyDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'消息内容' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'paNotify', @level2type=N'COLUMN',@level2name=N'Message'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'类别　1 一次性消息，其它限时消息' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'paNotify', @level2type=N'COLUMN',@level2name=N'NotifyType'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'个人是否查看' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'paNotify', @level2type=N'COLUMN',@level2name=N'IsViewed'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'前台，个人网站消息记录' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'paNotify'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'操作类型，见附件<个人会员操作表>' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'paOperationLog', @level2type=N'COLUMN',@level2name=N'Operation'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'操作说明' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'paOperationLog', @level2type=N'COLUMN',@level2name=N'Details'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'前台，个人操作记录表' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'paOperationLog'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'数据审核处理后的照片' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'paPhoto', @level2type=N'COLUMN',@level2name=N'PhotoProcessed'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'上传时间' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'paPhoto', @level2type=N'COLUMN',@level2name=N'AddDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'审核人' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'paPhoto', @level2type=N'COLUMN',@level2name=N'CheckMan'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'审核时间' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'paPhoto', @level2type=N'COLUMN',@level2name=N'CheckDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'审核不通过原因' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'paPhoto', @level2type=N'COLUMN',@level2name=N'CheckMessage'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'原始照片,审核完之后清空,原始文件进入待删除文件表,每天晚上批量删除(asp)' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'paPhoto', @level2type=N'COLUMN',@level2name=N'Photo'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'投诉内容' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'paPlaint', @level2type=N'COLUMN',@level2name=N'Plaint'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'0-未处理；1-有效；2-无效' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'paPlaint', @level2type=N'COLUMN',@level2name=N'ReplyType'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'企业是否查看' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'paPlaint', @level2type=N'COLUMN',@level2name=N'IsViewed'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'处理意见' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'paPlaint', @level2type=N'COLUMN',@level2name=N'ProcessMessage'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'处理时间' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'paPlaint', @level2type=N'COLUMN',@level2name=N'ProcessDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'前台，个人投诉企业记录表' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'paPlaint'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'发送给哪个个人的' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'PaRemindLog', @level2type=N'COLUMN',@level2name=N'PaMainID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'提醒内容' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'PaRemindLog', @level2type=N'COLUMN',@level2name=N'ContentText'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'邮箱提醒时间' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'PaRemindLog', @level2type=N'COLUMN',@level2name=N'RemindDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'提醒当前状态 0.未提醒，1.未读，2.已读，3.已删除' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'PaRemindLog', @level2type=N'COLUMN',@level2name=N'RemindStatus'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'添加日期' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'PaRemindLog', @level2type=N'COLUMN',@level2name=N'AddDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'提醒相关联的id' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'PaRemindLog', @level2type=N'COLUMN',@level2name=N'RemainID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'个人提醒记录' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'PaRemindLog'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'0：未提交；1：待提交；9：已提交' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'paSearchKeyword', @level2type=N'COLUMN',@level2name=N'HasSubmit'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'1：智联招聘2：前程无忧3：大众人才网 4：赶集5：新世纪人才网6：孔子人才' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'PrecoldCustomer', @level2type=N'COLUMN',@level2name=N'SourceType'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'0:未分配1：已分配2:已删除' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'PrecoldCustomer', @level2type=N'COLUMN',@level2name=N'State'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'1 一般新闻 2 插图新闻 3 链接新闻' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'QlrcNews', @level2type=N'COLUMN',@level2name=N'kindID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'问题标题' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Question', @level2type=N'COLUMN',@level2name=N'Title'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'1文本；2多选一；3多选多；4多选一带文本；5多选多带文本' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Question', @level2type=N'COLUMN',@level2name=N'Type'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'答案数量' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Question', @level2type=N'COLUMN',@level2name=N'AnswerNum'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'侯选答案([满意][不满意]' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Question', @level2type=N'COLUMN',@level2name=N'Options'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'文本提示' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Question', @level2type=N'COLUMN',@level2name=N'Prompt'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'顺序码' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Question', @level2type=N'COLUMN',@level2name=N'Power'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'1:简历' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'QuotaLog', @level2type=N'COLUMN',@level2name=N'QuotaType'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'分配的数量' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'QuotaLog', @level2type=N'COLUMN',@level2name=N'Quota'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'是否是历史数据，1是，0不是' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Resume_Xinxi', @level2type=N'COLUMN',@level2name=N'IsHistory'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'角色名称' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Role', @level2type=N'COLUMN',@level2name=N'rolename'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'组织级别 1,2,3,4' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Role', @level2type=N'COLUMN',@level2name=N'grade'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'XXXXXXXXXX,分别为读取，创建，修改，删除，分配，自定义1，自定义2，自定义3，自定义4，自定义5。x，禁用；0，空；1，本人；2，本部门；3，本部门及下级部门；4，全体部门' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Role_DataSource', @level2type=N'COLUMN',@level2name=N'Privi'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'1:职位订阅简历;2:个人搜索器订阅职位' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'schMailPrev', @level2type=N'COLUMN',@level2name=N'MailType'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'MailType=1为cpMainID；MailType=2为paMainID' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'schMailPrev', @level2type=N'COLUMN',@level2name=N'AccountID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'MailType=1时为JobID，MailType=2时为paSearchID' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'schMailPrev', @level2type=N'COLUMN',@level2name=N'SubID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'职位刷新表' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SearchJobRefresh'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'职位置顶表' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SearchJobTop'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'0系统发送；否则是工号;如果是收到的企业短信，则是招聘顾问编号' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SmsMessageLog', @level2type=N'COLUMN',@level2name=N'SendMan'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'收信人的工号' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SmsMessageLog', @level2type=N'COLUMN',@level2name=N'ManagerUserId'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'收短信的求职者账号' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SmsMessageLog', @level2type=N'COLUMN',@level2name=N'paMainId'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'收短信的企业用户帐号' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SmsMessageLog', @level2type=N'COLUMN',@level2name=N'caMainId'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'接收短信的手机号' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SmsMessageLog', @level2type=N'COLUMN',@level2name=N'Mobile'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'短信息内容' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SmsMessageLog', @level2type=N'COLUMN',@level2name=N'Msg'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'通过短信猫发送，0否；1是' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SmsMessageLog', @level2type=N'COLUMN',@level2name=N'IsCat'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'端口号' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SmsMessageLog', @level2type=N'COLUMN',@level2name=N'PortNo'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'发送状态，null待发送，1：发送成功；2：发送失败' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SmsMessageLog', @level2type=N'COLUMN',@level2name=N'SendStatus'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'短信类型，1：发送；2：接收' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SmsMessageLog', @level2type=N'COLUMN',@level2name=N'SmsType'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'发送人：1、公司 2、客服、顾问 3、系统' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SOLLog', @level2type=N'COLUMN',@level2name=N'Sender'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'1 已查看 0 未查看' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SOLLog', @level2type=N'COLUMN',@level2name=N'IsViewed'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'是否有效' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SOLProcess', @level2type=N'COLUMN',@level2name=N'IsActive'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'评价' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SOLProcess', @level2type=N'COLUMN',@level2name=N'Evaluate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'离线方式：1、点击退出 2、意外退出 3、长时间退出 4、踢出 5、留言' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'SOLProcess', @level2type=N'COLUMN',@level2name=N'OfflineType'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'1、RTX发送 2、短信发送 3、文件监视 4、文件更新 5、传真发送 6、RTX状态检测 7、RTX消息检测' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'ToolRunLog', @level2type=N'COLUMN',@level2name=N'ToolType'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'专题的标题' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Topics', @level2type=N'COLUMN',@level2name=N'Title'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'描述' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Topics', @level2type=N'COLUMN',@level2name=N'Description'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'图片名称' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Topics', @level2type=N'COLUMN',@level2name=N'FileName'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'专题地址' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Topics', @level2type=N'COLUMN',@level2name=N'Url'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'专题类型 ： 1员工风采  2职场专题' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Topics', @level2type=N'COLUMN',@level2name=N'type'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'1工作日，3休息日，2半天工作日' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'workDate', @level2type=N'COLUMN',@level2name=N'Type'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'关注时间' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'WxFans', @level2type=N'COLUMN',@level2name=N'AttentionDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'关注取消时间' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'WxFans', @level2type=N'COLUMN',@level2name=N'AttentionCancelDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'最后一次接收消息日期' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'WxFans', @level2type=N'COLUMN',@level2name=N'LastReceiveDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'最后一次消息内容' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'WxFans', @level2type=N'COLUMN',@level2name=N'LastSendMessage'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'0已取消关注 1 正在关注 2 已绑定账号' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'WxFans', @level2type=N'COLUMN',@level2name=N'Status'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'粉丝发送的消息或者关注日期或者定位信息等' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'WxMessageReceive', @level2type=N'COLUMN',@level2name=N'Message'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'1关注 2发送文本 3 定位 4点击菜单 5点击链接 6取消关注 ' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'WxMessageReceive', @level2type=N'COLUMN',@level2name=N'LogType'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'用户ID' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'WxMessageSend', @level2type=N'COLUMN',@level2name=N'WxFansID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'0未发送 1已成功发送 2发送失败' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'WxMessageSend', @level2type=N'COLUMN',@level2name=N'Status'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'1 模板消息' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'WxMessageSend', @level2type=N'COLUMN',@level2name=N'MessageType'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'存放发送失败时的错误代码' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'WxMessageSend', @level2type=N'COLUMN',@level2name=N'Remark'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'企业ID' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'WxMessageSend', @level2type=N'COLUMN',@level2name=N'CpMainID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'1 登陆页面 2注册页面' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'WXQrImage', @level2type=N'COLUMN',@level2name=N'PageType'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'0默认 1用户已关注 2用户已确认' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'WXQrImage', @level2type=N'COLUMN',@level2name=N'Status'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'服务号名称' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'WxServiceNo', @level2type=N'COLUMN',@level2name=N'Name'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'应用ID' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'WxServiceNo', @level2type=N'COLUMN',@level2name=N'AppID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'应用密钥' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'WxServiceNo', @level2type=N'COLUMN',@level2name=N'AppSecret'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'用户名' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'WxServiceNo', @level2type=N'COLUMN',@level2name=N'UserName'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'密码' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'WxServiceNo', @level2type=N'COLUMN',@level2name=N'Password'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'1正常 2已停用' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'WxServiceNo', @level2type=N'COLUMN',@level2name=N'Status'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'模板标题' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'WxTemplate', @level2type=N'COLUMN',@level2name=N'Title'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'模板标题' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'WxTemplate', @level2type=N'COLUMN',@level2name=N'TemplateTitle'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'详细内容' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'WxTemplate', @level2type=N'COLUMN',@level2name=N'Detail'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'点击跳转路径' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'WxTemplate', @level2type=N'COLUMN',@level2name=N'Url'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'1个人 2 企业' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'WxTemplate', @level2type=N'COLUMN',@level2name=N'Type'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'备注' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'WxTemplate', @level2type=N'COLUMN',@level2name=N'Remark'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'1正常 2 已停用' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'WxTemplate', @level2type=N'COLUMN',@level2name=N'Status'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'所属模板编号' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'WxTemplatePara', @level2type=N'COLUMN',@level2name=N'WxTemplateID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'参数名称' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'WxTemplatePara', @level2type=N'COLUMN',@level2name=N'ParaName'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'参数值' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'WxTemplatePara', @level2type=N'COLUMN',@level2name=N'ParaValue'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'参数文本颜色' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'WxTemplatePara', @level2type=N'COLUMN',@level2name=N'ParaColor'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_DiagramPane1', @value=N'[0E232FF0-B466-11cf-A24F-00AA00A3EFFF, 1.00]
Begin DesignProperties = 
   Begin PaneConfigurations = 
      Begin PaneConfiguration = 0
         NumPanes = 4
         Configuration = "(H (1[40] 4[21] 2[17] 3) )"
      End
      Begin PaneConfiguration = 1
         NumPanes = 3
         Configuration = "(H (1 [50] 4 [25] 3))"
      End
      Begin PaneConfiguration = 2
         NumPanes = 3
         Configuration = "(H (1 [50] 2 [25] 3))"
      End
      Begin PaneConfiguration = 3
         NumPanes = 3
         Configuration = "(H (4 [30] 2 [40] 3))"
      End
      Begin PaneConfiguration = 4
         NumPanes = 2
         Configuration = "(H (1 [56] 3))"
      End
      Begin PaneConfiguration = 5
         NumPanes = 2
         Configuration = "(H (2 [66] 3))"
      End
      Begin PaneConfiguration = 6
         NumPanes = 2
         Configuration = "(H (4 [50] 3))"
      End
      Begin PaneConfiguration = 7
         NumPanes = 1
         Configuration = "(V (3))"
      End
      Begin PaneConfiguration = 8
         NumPanes = 3
         Configuration = "(H (1[56] 4[18] 2) )"
      End
      Begin PaneConfiguration = 9
         NumPanes = 2
         Configuration = "(H (1 [75] 4))"
      End
      Begin PaneConfiguration = 10
         NumPanes = 2
         Configuration = "(H (1[66] 2) )"
      End
      Begin PaneConfiguration = 11
         NumPanes = 2
         Configuration = "(H (4 [60] 2))"
      End
      Begin PaneConfiguration = 12
         NumPanes = 1
         Configuration = "(H (1) )"
      End
      Begin PaneConfiguration = 13
         NumPanes = 1
         Configuration = "(V (4))"
      End
      Begin PaneConfiguration = 14
         NumPanes = 1
         Configuration = "(V (2))"
      End
      ActivePaneConfig = 0
   End
   Begin DiagramPane = 
      Begin Origin = 
         Top = -96
         Left = 0
      End
      Begin Tables = 
         Begin Table = "a"
            Begin Extent = 
               Top = 6
               Left = 38
               Bottom = 192
               Right = 218
            End
            DisplayFlags = 280
            TopColumn = 0
         End
         Begin Table = "b"
            Begin Extent = 
               Top = 102
               Left = 256
               Bottom = 221
               Right = 440
            End
            DisplayFlags = 280
            TopColumn = 0
         End
      End
   End
   Begin SQLPane = 
   End
   Begin DataPane = 
      Begin ParameterDefaults = ""
      End
      Begin ColumnWidths = 15
         Width = 284
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
      End
   End
   Begin CriteriaPane = 
      Begin ColumnWidths = 11
         Column = 2655
         Alias = 900
         Table = 1170
         Output = 720
         Append = 1400
         NewValue = 1170
         SortType = 1350
         SortOrder = 1410
         GroupBy = 1350
         Filter = 1350
         Or = 1350
         Or = 1350
         Or = 1350
      End
   End
End
' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'VIEW',@level1name=N'province'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_DiagramPaneCount', @value=1 , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'VIEW',@level1name=N'province'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_DiagramPane1', @value=N'[0E232FF0-B466-11cf-A24F-00AA00A3EFFF, 1.00]
Begin DesignProperties = 
   Begin PaneConfigurations = 
      Begin PaneConfiguration = 0
         NumPanes = 4
         Configuration = "(H (1[24] 4[39] 2[20] 3) )"
      End
      Begin PaneConfiguration = 1
         NumPanes = 3
         Configuration = "(H (1 [50] 4 [25] 3))"
      End
      Begin PaneConfiguration = 2
         NumPanes = 3
         Configuration = "(H (1 [50] 2 [25] 3))"
      End
      Begin PaneConfiguration = 3
         NumPanes = 3
         Configuration = "(H (4 [30] 2 [40] 3))"
      End
      Begin PaneConfiguration = 4
         NumPanes = 2
         Configuration = "(H (1 [56] 3))"
      End
      Begin PaneConfiguration = 5
         NumPanes = 2
         Configuration = "(H (2 [66] 3))"
      End
      Begin PaneConfiguration = 6
         NumPanes = 2
         Configuration = "(H (4 [50] 3))"
      End
      Begin PaneConfiguration = 7
         NumPanes = 1
         Configuration = "(V (3))"
      End
      Begin PaneConfiguration = 8
         NumPanes = 3
         Configuration = "(H (1[56] 4[18] 2) )"
      End
      Begin PaneConfiguration = 9
         NumPanes = 2
         Configuration = "(H (1 [75] 4))"
      End
      Begin PaneConfiguration = 10
         NumPanes = 2
         Configuration = "(H (1[66] 2) )"
      End
      Begin PaneConfiguration = 11
         NumPanes = 2
         Configuration = "(H (4 [60] 2))"
      End
      Begin PaneConfiguration = 12
         NumPanes = 1
         Configuration = "(H (1) )"
      End
      Begin PaneConfiguration = 13
         NumPanes = 1
         Configuration = "(V (4))"
      End
      Begin PaneConfiguration = 14
         NumPanes = 1
         Configuration = "(V (2))"
      End
      ActivePaneConfig = 0
   End
   Begin DiagramPane = 
      Begin Origin = 
         Top = 0
         Left = 0
      End
      Begin Tables = 
         Begin Table = "cpMain"
            Begin Extent = 
               Top = 6
               Left = 38
               Bottom = 114
               Right = 208
            End
            DisplayFlags = 280
            TopColumn = 0
         End
      End
   End
   Begin SQLPane = 
   End
   Begin DataPane = 
      Begin ParameterDefaults = ""
      End
   End
   Begin CriteriaPane = 
      Begin ColumnWidths = 11
         Column = 11595
         Alias = 1845
         Table = 1170
         Output = 720
         Append = 1400
         NewValue = 1170
         SortType = 1350
         SortOrder = 1410
         GroupBy = 1350
         Filter = 1350
         Or = 1350
         Or = 1350
         Or = 1350
      End
   End
End
' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'VIEW',@level1name=N'vCpmain'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_DiagramPaneCount', @value=1 , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'VIEW',@level1name=N'vCpmain'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_DiagramPane1', @value=N'[0E232FF0-B466-11cf-A24F-00AA00A3EFFF, 1.00]
Begin DesignProperties = 
   Begin PaneConfigurations = 
      Begin PaneConfiguration = 0
         NumPanes = 4
         Configuration = "(H (1[41] 4[21] 2[11] 3) )"
      End
      Begin PaneConfiguration = 1
         NumPanes = 3
         Configuration = "(H (1 [50] 4 [25] 3))"
      End
      Begin PaneConfiguration = 2
         NumPanes = 3
         Configuration = "(H (1 [50] 2 [25] 3))"
      End
      Begin PaneConfiguration = 3
         NumPanes = 3
         Configuration = "(H (4 [30] 2 [40] 3))"
      End
      Begin PaneConfiguration = 4
         NumPanes = 2
         Configuration = "(H (1 [56] 3))"
      End
      Begin PaneConfiguration = 5
         NumPanes = 2
         Configuration = "(H (2 [66] 3))"
      End
      Begin PaneConfiguration = 6
         NumPanes = 2
         Configuration = "(H (4 [50] 3))"
      End
      Begin PaneConfiguration = 7
         NumPanes = 1
         Configuration = "(V (3))"
      End
      Begin PaneConfiguration = 8
         NumPanes = 3
         Configuration = "(H (1[56] 4[18] 2) )"
      End
      Begin PaneConfiguration = 9
         NumPanes = 2
         Configuration = "(H (1 [75] 4))"
      End
      Begin PaneConfiguration = 10
         NumPanes = 2
         Configuration = "(H (1[66] 2) )"
      End
      Begin PaneConfiguration = 11
         NumPanes = 2
         Configuration = "(H (4 [60] 2))"
      End
      Begin PaneConfiguration = 12
         NumPanes = 1
         Configuration = "(H (1) )"
      End
      Begin PaneConfiguration = 13
         NumPanes = 1
         Configuration = "(V (4))"
      End
      Begin PaneConfiguration = 14
         NumPanes = 1
         Configuration = "(V (2))"
      End
      ActivePaneConfig = 0
   End
   Begin DiagramPane = 
      Begin Origin = 
         Top = 0
         Left = 0
      End
      Begin Tables = 
         Begin Table = "dcSubSite"
            Begin Extent = 
               Top = 6
               Left = 38
               Bottom = 121
               Right = 196
            End
            DisplayFlags = 280
            TopColumn = 8
         End
      End
   End
   Begin SQLPane = 
   End
   Begin DataPane = 
      Begin ParameterDefaults = ""
      End
      Begin ColumnWidths = 22
         Width = 284
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
      End
   End
   Begin CriteriaPane = 
      Begin ColumnWidths = 11
         Column = 1440
         Alias = 900
         Table = 1170
         Output = 720
         Append = 1400
         NewValue = 1170
         SortType = 1350
         SortOrder = 1410
         GroupBy = 1350
         Filter = 1350
         Or = 1350
         Or = 1350
         Or = 1350
      End
   End
End
' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'VIEW',@level1name=N'version'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_DiagramPaneCount', @value=1 , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'VIEW',@level1name=N'version'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_DiagramPane1', @value=N'[0E232FF0-B466-11cf-A24F-00AA00A3EFFF, 1.00]
Begin DesignProperties = 
   Begin PaneConfigurations = 
      Begin PaneConfiguration = 0
         NumPanes = 4
         Configuration = "(H (1[40] 4[20] 2[20] 3) )"
      End
      Begin PaneConfiguration = 1
         NumPanes = 3
         Configuration = "(H (1 [50] 4 [25] 3))"
      End
      Begin PaneConfiguration = 2
         NumPanes = 3
         Configuration = "(H (1 [50] 2 [25] 3))"
      End
      Begin PaneConfiguration = 3
         NumPanes = 3
         Configuration = "(H (4 [30] 2 [40] 3))"
      End
      Begin PaneConfiguration = 4
         NumPanes = 2
         Configuration = "(H (1 [56] 3))"
      End
      Begin PaneConfiguration = 5
         NumPanes = 2
         Configuration = "(H (2 [66] 3))"
      End
      Begin PaneConfiguration = 6
         NumPanes = 2
         Configuration = "(H (4 [50] 3))"
      End
      Begin PaneConfiguration = 7
         NumPanes = 1
         Configuration = "(V (3))"
      End
      Begin PaneConfiguration = 8
         NumPanes = 3
         Configuration = "(H (1[56] 4[18] 2) )"
      End
      Begin PaneConfiguration = 9
         NumPanes = 2
         Configuration = "(H (1 [75] 4))"
      End
      Begin PaneConfiguration = 10
         NumPanes = 2
         Configuration = "(H (1[66] 2) )"
      End
      Begin PaneConfiguration = 11
         NumPanes = 2
         Configuration = "(H (4 [60] 2))"
      End
      Begin PaneConfiguration = 12
         NumPanes = 1
         Configuration = "(H (1) )"
      End
      Begin PaneConfiguration = 13
         NumPanes = 1
         Configuration = "(V (4))"
      End
      Begin PaneConfiguration = 14
         NumPanes = 1
         Configuration = "(V (2))"
      End
      ActivePaneConfig = 0
   End
   Begin DiagramPane = 
      Begin Origin = 
         Top = 0
         Left = 0
      End
      Begin Tables = 
         Begin Table = "ManagerUser"
            Begin Extent = 
               Top = 6
               Left = 38
               Bottom = 121
               Right = 283
            End
            DisplayFlags = 280
            TopColumn = 0
         End
      End
   End
   Begin SQLPane = 
   End
   Begin DataPane = 
      Begin ParameterDefaults = ""
      End
   End
   Begin CriteriaPane = 
      Begin ColumnWidths = 11
         Column = 1440
         Alias = 900
         Table = 1170
         Output = 720
         Append = 1400
         NewValue = 1170
         SortType = 1350
         SortOrder = 1410
         GroupBy = 1350
         Filter = 1350
         Or = 1350
         Or = 1350
         Or = 1350
      End
   End
End
' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'VIEW',@level1name=N'viewBsAskUSer'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_DiagramPaneCount', @value=1 , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'VIEW',@level1name=N'viewBsAskUSer'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_DiagramPane1', @value=N'[0E232FF0-B466-11cf-A24F-00AA00A3EFFF, 1.00]
Begin DesignProperties = 
   Begin PaneConfigurations = 
      Begin PaneConfiguration = 0
         NumPanes = 4
         Configuration = "(H (1[43] 4[38] 2[10] 3) )"
      End
      Begin PaneConfiguration = 1
         NumPanes = 3
         Configuration = "(H (1 [50] 4 [25] 3))"
      End
      Begin PaneConfiguration = 2
         NumPanes = 3
         Configuration = "(H (1 [50] 2 [25] 3))"
      End
      Begin PaneConfiguration = 3
         NumPanes = 3
         Configuration = "(H (4 [30] 2 [40] 3))"
      End
      Begin PaneConfiguration = 4
         NumPanes = 2
         Configuration = "(H (1 [56] 3))"
      End
      Begin PaneConfiguration = 5
         NumPanes = 2
         Configuration = "(H (2 [66] 3))"
      End
      Begin PaneConfiguration = 6
         NumPanes = 2
         Configuration = "(H (4 [50] 3))"
      End
      Begin PaneConfiguration = 7
         NumPanes = 1
         Configuration = "(V (3))"
      End
      Begin PaneConfiguration = 8
         NumPanes = 3
         Configuration = "(H (1[56] 4[18] 2) )"
      End
      Begin PaneConfiguration = 9
         NumPanes = 2
         Configuration = "(H (1 [75] 4))"
      End
      Begin PaneConfiguration = 10
         NumPanes = 2
         Configuration = "(H (1[66] 2) )"
      End
      Begin PaneConfiguration = 11
         NumPanes = 2
         Configuration = "(H (4 [60] 2))"
      End
      Begin PaneConfiguration = 12
         NumPanes = 1
         Configuration = "(H (1) )"
      End
      Begin PaneConfiguration = 13
         NumPanes = 1
         Configuration = "(V (4))"
      End
      Begin PaneConfiguration = 14
         NumPanes = 1
         Configuration = "(V (2))"
      End
      ActivePaneConfig = 0
   End
   Begin DiagramPane = 
      Begin Origin = 
         Top = 0
         Left = -985
      End
      Begin Tables = 
         Begin Table = "exJobApply"
            Begin Extent = 
               Top = 0
               Left = 296
               Bottom = 206
               Right = 475
            End
            DisplayFlags = 280
            TopColumn = 5
         End
         Begin Table = "cvMain"
            Begin Extent = 
               Top = 8
               Left = 488
               Bottom = 215
               Right = 637
            End
            DisplayFlags = 280
            TopColumn = 25
         End
         Begin Table = "paMain"
            Begin Extent = 
               Top = 6
               Left = 697
               Bottom = 209
               Right = 864
            End
            DisplayFlags = 280
            TopColumn = 1
         End
         Begin Table = "Job"
            Begin Extent = 
               Top = 24
               Left = 188
               Bottom = 218
               Right = 357
            End
            DisplayFlags = 280
            TopColumn = 5
         End
         Begin Table = "caMain"
            Begin Extent = 
               Top = 0
               Left = 0
               Bottom = 223
               Right = 192
            End
            DisplayFlags = 280
            TopColumn = 13
         End
      End
   End
   Begin SQLPane = 
   End
   Begin DataPane = 
      Begin ParameterDefaults = ""
      End
      Begin ColumnWidths = 21
         Width = 284
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'VIEW',@level1name=N'viewExJobApply'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_DiagramPane2', @value=N'500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
         Width = 1500
      End
   End
   Begin CriteriaPane = 
      Begin ColumnWidths = 11
         Column = 3525
         Alias = 2775
         Table = 1170
         Output = 720
         Append = 1400
         NewValue = 1170
         SortType = 1350
         SortOrder = 1410
         GroupBy = 1350
         Filter = 1350
         Or = 1350
         Or = 1350
         Or = 1350
      End
   End
End
' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'VIEW',@level1name=N'viewExJobApply'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_DiagramPaneCount', @value=2 , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'VIEW',@level1name=N'viewExJobApply'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_DiagramPane1', @value=N'[0E232FF0-B466-11cf-A24F-00AA00A3EFFF, 1.00]
Begin DesignProperties = 
   Begin PaneConfigurations = 
      Begin PaneConfiguration = 0
         NumPanes = 4
         Configuration = "(H (1[41] 4[44] 2[4] 3) )"
      End
      Begin PaneConfiguration = 1
         NumPanes = 3
         Configuration = "(H (1 [50] 4 [25] 3))"
      End
      Begin PaneConfiguration = 2
         NumPanes = 3
         Configuration = "(H (1 [50] 2 [25] 3))"
      End
      Begin PaneConfiguration = 3
         NumPanes = 3
         Configuration = "(H (4 [30] 2 [40] 3))"
      End
      Begin PaneConfiguration = 4
         NumPanes = 2
         Configuration = "(H (1 [56] 3))"
      End
      Begin PaneConfiguration = 5
         NumPanes = 2
         Configuration = "(H (2 [66] 3))"
      End
      Begin PaneConfiguration = 6
         NumPanes = 2
         Configuration = "(H (4 [50] 3))"
      End
      Begin PaneConfiguration = 7
         NumPanes = 1
         Configuration = "(V (3))"
      End
      Begin PaneConfiguration = 8
         NumPanes = 3
         Configuration = "(H (1[56] 4[18] 2) )"
      End
      Begin PaneConfiguration = 9
         NumPanes = 2
         Configuration = "(H (1 [75] 4))"
      End
      Begin PaneConfiguration = 10
         NumPanes = 2
         Configuration = "(H (1[66] 2) )"
      End
      Begin PaneConfiguration = 11
         NumPanes = 2
         Configuration = "(H (4 [60] 2))"
      End
      Begin PaneConfiguration = 12
         NumPanes = 1
         Configuration = "(H (1) )"
      End
      Begin PaneConfiguration = 13
         NumPanes = 1
         Configuration = "(V (4))"
      End
      Begin PaneConfiguration = 14
         NumPanes = 1
         Configuration = "(V (2))"
      End
      ActivePaneConfig = 0
   End
   Begin DiagramPane = 
      Begin Origin = 
         Top = 0
         Left = 0
      End
      Begin Tables = 
         Begin Table = "Job"
            Begin Extent = 
               Top = 6
               Left = 38
               Bottom = 233
               Right = 208
            End
            DisplayFlags = 280
            TopColumn = 3
         End
         Begin Table = "cpMain"
            Begin Extent = 
               Top = 3
               Left = 407
               Bottom = 221
               Right = 600
            End
            DisplayFlags = 280
            TopColumn = 0
         End
      End
   End
   Begin SQLPane = 
   End
   Begin DataPane = 
      Begin ParameterDefaults = ""
      End
   End
   Begin CriteriaPane = 
      Begin ColumnWidths = 11
         Column = 3705
         Alias = 900
         Table = 1170
         Output = 720
         Append = 1400
         NewValue = 1170
         SortType = 1350
         SortOrder = 1410
         GroupBy = 1350
         Filter = 1350
         Or = 1350
         Or = 1350
         Or = 1350
      End
   End
End
' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'VIEW',@level1name=N'viewJob'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_DiagramPaneCount', @value=1 , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'VIEW',@level1name=N'viewJob'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_DiagramPane1', @value=N'[0E232FF0-B466-11cf-A24F-00AA00A3EFFF, 1.00]
Begin DesignProperties = 
   Begin PaneConfigurations = 
      Begin PaneConfiguration = 0
         NumPanes = 4
         Configuration = "(H (1[40] 4[20] 2[20] 3) )"
      End
      Begin PaneConfiguration = 1
         NumPanes = 3
         Configuration = "(H (1 [50] 4 [25] 3))"
      End
      Begin PaneConfiguration = 2
         NumPanes = 3
         Configuration = "(H (1 [50] 2 [25] 3))"
      End
      Begin PaneConfiguration = 3
         NumPanes = 3
         Configuration = "(H (4 [30] 2 [40] 3))"
      End
      Begin PaneConfiguration = 4
         NumPanes = 2
         Configuration = "(H (1 [56] 3))"
      End
      Begin PaneConfiguration = 5
         NumPanes = 2
         Configuration = "(H (2 [66] 3))"
      End
      Begin PaneConfiguration = 6
         NumPanes = 2
         Configuration = "(H (4 [50] 3))"
      End
      Begin PaneConfiguration = 7
         NumPanes = 1
         Configuration = "(V (3))"
      End
      Begin PaneConfiguration = 8
         NumPanes = 3
         Configuration = "(H (1[56] 4[18] 2) )"
      End
      Begin PaneConfiguration = 9
         NumPanes = 2
         Configuration = "(H (1 [75] 4))"
      End
      Begin PaneConfiguration = 10
         NumPanes = 2
         Configuration = "(H (1[66] 2) )"
      End
      Begin PaneConfiguration = 11
         NumPanes = 2
         Configuration = "(H (4 [60] 2))"
      End
      Begin PaneConfiguration = 12
         NumPanes = 1
         Configuration = "(H (1) )"
      End
      Begin PaneConfiguration = 13
         NumPanes = 1
         Configuration = "(V (4))"
      End
      Begin PaneConfiguration = 14
         NumPanes = 1
         Configuration = "(V (2))"
      End
      ActivePaneConfig = 0
   End
   Begin DiagramPane = 
      Begin Origin = 
         Top = 0
         Left = 0
      End
      Begin Tables = 
         Begin Table = "a"
            Begin Extent = 
               Top = 6
               Left = 38
               Bottom = 238
               Right = 192
            End
            DisplayFlags = 280
            TopColumn = 0
         End
         Begin Table = "b"
            Begin Extent = 
               Top = 8
               Left = 289
               Bottom = 116
               Right = 452
            End
            DisplayFlags = 280
            TopColumn = 0
         End
      End
   End
   Begin SQLPane = 
   End
   Begin DataPane = 
      Begin ParameterDefaults = ""
      End
   End
   Begin CriteriaPane = 
      Begin ColumnWidths = 11
         Column = 1440
         Alias = 900
         Table = 1170
         Output = 720
         Append = 1400
         NewValue = 1170
         SortType = 1350
         SortOrder = 1410
         GroupBy = 1350
         Filter = 1350
         Or = 1350
         Or = 1350
         Or = 1350
      End
   End
End
' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'VIEW',@level1name=N'viewLink'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_DiagramPaneCount', @value=1 , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'VIEW',@level1name=N'viewLink'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_DiagramPane1', @value=N'[0E232FF0-B466-11cf-A24F-00AA00A3EFFF, 1.00]
Begin DesignProperties = 
   Begin PaneConfigurations = 
      Begin PaneConfiguration = 0
         NumPanes = 4
         Configuration = "(H (1[34] 4[28] 2[20] 3) )"
      End
      Begin PaneConfiguration = 1
         NumPanes = 3
         Configuration = "(H (1 [50] 4 [25] 3))"
      End
      Begin PaneConfiguration = 2
         NumPanes = 3
         Configuration = "(H (1 [50] 2 [25] 3))"
      End
      Begin PaneConfiguration = 3
         NumPanes = 3
         Configuration = "(H (4 [30] 2 [40] 3))"
      End
      Begin PaneConfiguration = 4
         NumPanes = 2
         Configuration = "(H (1 [56] 3))"
      End
      Begin PaneConfiguration = 5
         NumPanes = 2
         Configuration = "(H (2 [66] 3))"
      End
      Begin PaneConfiguration = 6
         NumPanes = 2
         Configuration = "(H (4 [50] 3))"
      End
      Begin PaneConfiguration = 7
         NumPanes = 1
         Configuration = "(V (3))"
      End
      Begin PaneConfiguration = 8
         NumPanes = 3
         Configuration = "(H (1[56] 4[18] 2) )"
      End
      Begin PaneConfiguration = 9
         NumPanes = 2
         Configuration = "(H (1 [75] 4))"
      End
      Begin PaneConfiguration = 10
         NumPanes = 2
         Configuration = "(H (1[66] 2) )"
      End
      Begin PaneConfiguration = 11
         NumPanes = 2
         Configuration = "(H (4 [60] 2))"
      End
      Begin PaneConfiguration = 12
         NumPanes = 1
         Configuration = "(H (1) )"
      End
      Begin PaneConfiguration = 13
         NumPanes = 1
         Configuration = "(V (4))"
      End
      Begin PaneConfiguration = 14
         NumPanes = 1
         Configuration = "(V (2))"
      End
      ActivePaneConfig = 0
   End
   Begin DiagramPane = 
      Begin Origin = 
         Top = 0
         Left = 0
      End
      Begin Tables = 
         Begin Table = "a"
            Begin Extent = 
               Top = 6
               Left = 38
               Bottom = 210
               Right = 192
            End
            DisplayFlags = 280
            TopColumn = 26
         End
         Begin Table = "b"
            Begin Extent = 
               Top = 6
               Left = 230
               Bottom = 114
               Right = 393
            End
            DisplayFlags = 280
            TopColumn = 0
         End
      End
   End
   Begin SQLPane = 
   End
   Begin DataPane = 
      Begin ParameterDefaults = ""
      End
   End
   Begin CriteriaPane = 
      Begin ColumnWidths = 14
         Column = 1440
         Alias = 900
         Table = 1170
         Output = 720
         Append = 1400
         NewValue = 1170
         SortType = 1350
         SortOrder = 1410
         GroupBy = 1350
         Filter = 1350
         Or = 1350
         Or = 1350
         Or = 1350
         Or = 1350
         Or = 1350
         Or = 1350
      End
   End
End
' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'VIEW',@level1name=N'viewLinkAbnormal'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_DiagramPaneCount', @value=1 , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'VIEW',@level1name=N'viewLinkAbnormal'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_DiagramPane1', @value=N'[0E232FF0-B466-11cf-A24F-00AA00A3EFFF, 1.00]
Begin DesignProperties = 
   Begin PaneConfigurations = 
      Begin PaneConfiguration = 0
         NumPanes = 4
         Configuration = "(H (1[28] 4[4] 2[49] 3) )"
      End
      Begin PaneConfiguration = 1
         NumPanes = 3
         Configuration = "(H (1 [50] 4 [25] 3))"
      End
      Begin PaneConfiguration = 2
         NumPanes = 3
         Configuration = "(H (1 [50] 2 [25] 3))"
      End
      Begin PaneConfiguration = 3
         NumPanes = 3
         Configuration = "(H (4 [30] 2 [40] 3))"
      End
      Begin PaneConfiguration = 4
         NumPanes = 2
         Configuration = "(H (1 [56] 3))"
      End
      Begin PaneConfiguration = 5
         NumPanes = 2
         Configuration = "(H (2 [66] 3))"
      End
      Begin PaneConfiguration = 6
         NumPanes = 2
         Configuration = "(H (4 [50] 3))"
      End
      Begin PaneConfiguration = 7
         NumPanes = 1
         Configuration = "(V (3))"
      End
      Begin PaneConfiguration = 8
         NumPanes = 3
         Configuration = "(H (1[56] 4[18] 2) )"
      End
      Begin PaneConfiguration = 9
         NumPanes = 2
         Configuration = "(H (1 [75] 4))"
      End
      Begin PaneConfiguration = 10
         NumPanes = 2
         Configuration = "(H (1[66] 2) )"
      End
      Begin PaneConfiguration = 11
         NumPanes = 2
         Configuration = "(H (4 [60] 2))"
      End
      Begin PaneConfiguration = 12
         NumPanes = 1
         Configuration = "(H (1) )"
      End
      Begin PaneConfiguration = 13
         NumPanes = 1
         Configuration = "(V (4))"
      End
      Begin PaneConfiguration = 14
         NumPanes = 1
         Configuration = "(V (2))"
      End
      ActivePaneConfig = 0
   End
   Begin DiagramPane = 
      Begin Origin = 
         Top = 0
         Left = 0
      End
      Begin Tables = 
         Begin Table = "a"
            Begin Extent = 
               Top = 6
               Left = 38
               Bottom = 222
               Right = 192
            End
            DisplayFlags = 280
            TopColumn = 22
         End
         Begin Table = "b"
            Begin Extent = 
               Top = 6
               Left = 230
               Bottom = 114
               Right = 393
            End
            DisplayFlags = 280
            TopColumn = 0
         End
      End
   End
   Begin SQLPane = 
   End
   Begin DataPane = 
      Begin ParameterDefaults = ""
      End
   End
   Begin CriteriaPane = 
      Begin ColumnWidths = 15
         Column = 1440
         Alias = 900
         Table = 1170
         Output = 720
         Append = 1400
         NewValue = 1170
         SortType = 1350
         SortOrder = 1410
         GroupBy = 1350
         Filter = 1350
         Or = 1350
         Or = 1350
         Or = 1350
         Or = 1350
         Or = 1350
         Or = 1350
         Or = 1350
      End
   End
End
' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'VIEW',@level1name=N'viewLinkAbnormalAll'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_DiagramPaneCount', @value=1 , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'VIEW',@level1name=N'viewLinkAbnormalAll'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_DiagramPane1', @value=N'[0E232FF0-B466-11cf-A24F-00AA00A3EFFF, 1.00]
Begin DesignProperties = 
   Begin PaneConfigurations = 
      Begin PaneConfiguration = 0
         NumPanes = 4
         Configuration = "(H (1[40] 4[20] 2[20] 3) )"
      End
      Begin PaneConfiguration = 1
         NumPanes = 3
         Configuration = "(H (1 [50] 4 [25] 3))"
      End
      Begin PaneConfiguration = 2
         NumPanes = 3
         Configuration = "(H (1 [50] 2 [25] 3))"
      End
      Begin PaneConfiguration = 3
         NumPanes = 3
         Configuration = "(H (4 [30] 2 [40] 3))"
      End
      Begin PaneConfiguration = 4
         NumPanes = 2
         Configuration = "(H (1 [56] 3))"
      End
      Begin PaneConfiguration = 5
         NumPanes = 2
         Configuration = "(H (2 [66] 3))"
      End
      Begin PaneConfiguration = 6
         NumPanes = 2
         Configuration = "(H (4 [50] 3))"
      End
      Begin PaneConfiguration = 7
         NumPanes = 1
         Configuration = "(V (3))"
      End
      Begin PaneConfiguration = 8
         NumPanes = 3
         Configuration = "(H (1[56] 4[18] 2) )"
      End
      Begin PaneConfiguration = 9
         NumPanes = 2
         Configuration = "(H (1 [75] 4))"
      End
      Begin PaneConfiguration = 10
         NumPanes = 2
         Configuration = "(H (1[66] 2) )"
      End
      Begin PaneConfiguration = 11
         NumPanes = 2
         Configuration = "(H (4 [60] 2))"
      End
      Begin PaneConfiguration = 12
         NumPanes = 1
         Configuration = "(H (1) )"
      End
      Begin PaneConfiguration = 13
         NumPanes = 1
         Configuration = "(V (4))"
      End
      Begin PaneConfiguration = 14
         NumPanes = 1
         Configuration = "(V (2))"
      End
      ActivePaneConfig = 0
   End
   Begin DiagramPane = 
      Begin Origin = 
         Top = 0
         Left = 0
      End
      Begin Tables = 
         Begin Table = "paMain"
            Begin Extent = 
               Top = 6
               Left = 38
               Bottom = 121
               Right = 209
            End
            DisplayFlags = 280
            TopColumn = 0
         End
         Begin Table = "cvMain"
            Begin Extent = 
               Top = 6
               Left = 247
               Bottom = 121
               Right = 417
            End
            DisplayFlags = 280
            TopColumn = 0
         End
         Begin Table = "cvJobPlace"
            Begin Extent = 
               Top = 6
               Left = 455
               Bottom = 106
               Right = 591
            End
            DisplayFlags = 280
            TopColumn = 0
         End
      End
   End
   Begin SQLPane = 
   End
   Begin DataPane = 
      Begin ParameterDefaults = ""
      End
   End
   Begin CriteriaPane = 
      Begin ColumnWidths = 11
         Column = 1440
         Alias = 900
         Table = 1170
         Output = 720
         Append = 1400
         NewValue = 1170
         SortType = 1350
         SortOrder = 1410
         GroupBy = 1350
         Filter = 1350
         Or = 1350
         Or = 1350
         Or = 1350
      End
   End
End
' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'VIEW',@level1name=N'viewPaJobPlace'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_DiagramPaneCount', @value=1 , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'VIEW',@level1name=N'viewPaJobPlace'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_DiagramPane1', @value=N'[0E232FF0-B466-11cf-A24F-00AA00A3EFFF, 1.00]
Begin DesignProperties = 
   Begin PaneConfigurations = 
      Begin PaneConfiguration = 0
         NumPanes = 4
         Configuration = "(H (1[40] 4[20] 2[20] 3) )"
      End
      Begin PaneConfiguration = 1
         NumPanes = 3
         Configuration = "(H (1 [50] 4 [25] 3))"
      End
      Begin PaneConfiguration = 2
         NumPanes = 3
         Configuration = "(H (1 [50] 2 [25] 3))"
      End
      Begin PaneConfiguration = 3
         NumPanes = 3
         Configuration = "(H (4 [30] 2 [40] 3))"
      End
      Begin PaneConfiguration = 4
         NumPanes = 2
         Configuration = "(H (1 [56] 3))"
      End
      Begin PaneConfiguration = 5
         NumPanes = 2
         Configuration = "(H (2 [66] 3))"
      End
      Begin PaneConfiguration = 6
         NumPanes = 2
         Configuration = "(H (4 [50] 3))"
      End
      Begin PaneConfiguration = 7
         NumPanes = 1
         Configuration = "(V (3))"
      End
      Begin PaneConfiguration = 8
         NumPanes = 3
         Configuration = "(H (1[56] 4[18] 2) )"
      End
      Begin PaneConfiguration = 9
         NumPanes = 2
         Configuration = "(H (1 [75] 4))"
      End
      Begin PaneConfiguration = 10
         NumPanes = 2
         Configuration = "(H (1[66] 2) )"
      End
      Begin PaneConfiguration = 11
         NumPanes = 2
         Configuration = "(H (4 [60] 2))"
      End
      Begin PaneConfiguration = 12
         NumPanes = 1
         Configuration = "(H (1) )"
      End
      Begin PaneConfiguration = 13
         NumPanes = 1
         Configuration = "(V (4))"
      End
      Begin PaneConfiguration = 14
         NumPanes = 1
         Configuration = "(V (2))"
      End
      ActivePaneConfig = 0
   End
   Begin DiagramPane = 
      Begin Origin = 
         Top = 0
         Left = 0
      End
      Begin Tables = 
         Begin Table = "paLoginLog"
            Begin Extent = 
               Top = 6
               Left = 38
               Bottom = 188
               Right = 313
            End
            DisplayFlags = 280
            TopColumn = 0
         End
      End
   End
   Begin SQLPane = 
   End
   Begin DataPane = 
      Begin ParameterDefaults = ""
      End
   End
   Begin CriteriaPane = 
      Begin ColumnWidths = 11
         Column = 1440
         Alias = 900
         Table = 1170
         Output = 720
         Append = 1400
         NewValue = 1170
         SortType = 1350
         SortOrder = 1410
         GroupBy = 1350
         Filter = 1350
         Or = 1350
         Or = 1350
         Or = 1350
      End
   End
End
' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'VIEW',@level1name=N'ViewPaLoginlog1'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_DiagramPaneCount', @value=1 , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'VIEW',@level1name=N'ViewPaLoginlog1'
GO
USE [master]
GO
ALTER DATABASE [MainDB] SET  READ_WRITE 
GO
