
--#####################################################
--创建时间：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/12/13 19:11:21 ******/
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/12/13 19:11:21 ******/
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/12/13 19:11:22 ******/
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/12/13 19:11:23 ******/
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/12/13 19:11:23 ******/
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/12/13 19:11:24 ******/
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/12/13 19:11:24 ******/
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/12/13 19:11:24 ******/
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/12/13 19:11:24 ******/
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/12/13 19:11:25 ******/
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/12/13 19:11:25 ******/
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/12/13 19:11:25 ******/
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/12/13 19:11:25 ******/
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/12/13 19:11:26 ******/
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/12/13 19:11:26 ******/
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/12/13 19:11:26 ******/
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/12/13 19:11:26 ******/
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/12/13 19:11:26 ******/
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/12/13 19:11:27 ******/
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/12/13 19:11:27 ******/
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/12/13 19:11:27 ******/
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/12/13 19:11:27 ******/
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/12/13 19:11:27 ******/
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/12/13 19:11:28 ******/
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/12/13 19:11:28 ******/
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/12/13 19:11:28 ******/
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/12/13 19:11:29 ******/
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/12/13 19:11:29 ******/
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/12/13 19:11:29 ******/
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/12/13 19:11:30 ******/
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/12/13 19:11:30 ******/
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/12/13 19:11:30 ******/
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/12/13 19:11:30 ******/
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/12/13 19:11:31 ******/
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/12/13 19:11:31 ******/
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/12/13 19:11:31 ******/
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/12/13 19:11:31 ******/
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/12/13 19:11:31 ******/
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/12/13 19:11:32 ******/
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/12/13 19:11:32 ******/
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/12/13 19:11:32 ******/
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/12/13 19:11:32 ******/
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/12/13 19:11:32 ******/
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/12/13 19:11:33 ******/
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/12/13 19:11:33 ******/
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/12/13 19:11:33 ******/
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/12/13 19:11:33 ******/
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/12/13 19:11:34 ******/
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/12/13 19:11:34 ******/
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/12/13 19:11:34 ******/
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/12/13 19:11:36 ******/
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/12/13 19:11:37 ******/
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/12/13 19:11:37 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--peter 2018-1-26
--修改 ：Alen 2018-10-23 添加58和齐鲁人才网分配数统计
--修改：Sunshien 2018-11-16 修改推广人员
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,
		qiluNumber INT,
		tongchengNumber 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,
		qiluNumber INT,
		tongchengNumber 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 IN (1,2) AND deptid=15 --20181116Sunshien添加status=1
	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),
	qiluNumber=(SELECT sum(AllocateNumber) FROM ColdCustomerAllocateLog WHERE ManagerUserid=#t1.ManagerUserid AND sourceType=8),
	tongchengNumber=(SELECT sum(AllocateNumber) FROM ColdCustomerAllocateLog WHERE ManagerUserid=#t1.ManagerUserid AND sourceType=9)
	
	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 IN (1,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)),
	qiluNumber=(SELECT sum(AllocateNumber) FROM ColdCustomerAllocateLog WHERE ManagerUserid=#t2.ManagerUserid AND sourceType=8 AND addDate>Convert(dateTime,Convert(char(10),getdate(),120),120)),
	tongchengNumber=(SELECT sum(AllocateNumber) FROM ColdCustomerAllocateLog WHERE ManagerUserid=#t2.ManagerUserid AND sourceType=9 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/12/13 19:11:38 ******/
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/12/13 19:11:38 ******/
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/12/13 19:11:38 ******/
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/12/13 19:11:38 ******/
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/12/13 19:11:38 ******/
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/12/13 19:11:39 ******/
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/12/13 19:11:39 ******/
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/12/13 19:11:40 ******/
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/12/13 19:11:40 ******/
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/12/13 19:11:41 ******/
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/12/13 19:11:41 ******/
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/12/13 19:11:41 ******/
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/12/13 19:11:41 ******/
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/12/13 19:11:41 ******/
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/12/13 19:11:41 ******/
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/12/13 19:11:42 ******/
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/12/13 19:11:42 ******/
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/12/13 19:11:42 ******/
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/12/13 19:11:42 ******/
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/12/13 19:11:42 ******/
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/12/13 19:11:42 ******/
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/12/13 19:11:43 ******/
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/12/13 19:11:43 ******/
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/12/13 19:11:43 ******/
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/12/13 19:11:43 ******/
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/12/13 19:11:44 ******/
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/12/13 19:11:44 ******/
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/12/13 19:11:44 ******/
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/12/13 19:11:44 ******/
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/12/13 19:11:44 ******/
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/12/13 19:11:45 ******/
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/12/13 19:11:45 ******/
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/12/13 19:11:45 ******/
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/12/13 19:11:45 ******/
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/12/13 19:11:45 ******/
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/12/13 19:11:45 ******/
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/12/13 19:11:46 ******/
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/12/13 19:11:46 ******/
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/12/13 19:11:46 ******/
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/12/13 19:11:46 ******/
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/12/13 19:11:47 ******/
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/12/13 19:11:47 ******/
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/12/13 19:11:47 ******/
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/12/13 19:11:47 ******/
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/12/13 19:11:47 ******/
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/12/13 19:11:48 ******/
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/12/13 19:11:48 ******/
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/12/13 19:11:48 ******/
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/12/13 19:11:48 ******/
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/12/13 19:11:49 ******/
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/12/13 19:11:49 ******/
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/12/13 19:11:49 ******/
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/12/13 19:11:50 ******/
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/12/13 19:11:50 ******/
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/12/13 19:11:50 ******/
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/12/13 19:11:51 ******/
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/12/13 19:11:52 ******/
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/12/13 19:11:52 ******/
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/12/13 19:11:53 ******/
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/12/13 19:11:53 ******/
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/12/13 19:11:53 ******/
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/12/13 19:11:53 ******/
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/12/13 19:11:54 ******/
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/12/13 19:11:54 ******/
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/12/13 19:11:54 ******/
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/12/13 19:11:54 ******/
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/12/13 19:11:54 ******/
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/12/13 19:11:54 ******/
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/12/13 19:11:55 ******/
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/12/13 19:11:55 ******/
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/12/13 19:11:55 ******/
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/12/13 19:11:55 ******/
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/12/13 19:11:55 ******/
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/12/13 19:11:56 ******/
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/12/13 19:11:58 ******/
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/12/13 19:11:58 ******/
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/12/13 19:11:58 ******/
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/12/13 19:11:58 ******/
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/12/13 19:11:58 ******/
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/12/13 19:11:59 ******/
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/12/13 19:11:59 ******/
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/12/13 19:11:59 ******/
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/12/13 19:12:00 ******/
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/12/13 19:12:00 ******/
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/12/13 19:12:00 ******/
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/12/13 19:12:00 ******/
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/12/13 19:12:01 ******/
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/12/13 19:12:01 ******/
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/12/13 19:12:02 ******/
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/12/13 19:12:03 ******/
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/12/13 19:12:03 ******/
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/12/13 19:12:03 ******/
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/12/13 19:12:03 ******/
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/12/13 19:12:03 ******/
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/12/13 19:12:04 ******/
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 30 *, 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 30 *, 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/12/13 19:12:05 ******/
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/12/13 19:12:06 ******/
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/12/13 19:12:06 ******/
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/12/13 19:12:06 ******/
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/12/13 19:12:07 ******/
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/12/13 19:12:07 ******/
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/12/13 19:12:07 ******/
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/12/13 19:12:09 ******/
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/12/13 19:12:10 ******/
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/12/13 19:12:10 ******/
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/12/13 19:12:10 ******/
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/12/13 19:12:10 ******/
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/12/13 19:12:10 ******/
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/12/13 19:12:11 ******/
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/12/13 19:12:11 ******/
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/12/13 19:12:11 ******/
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/12/13 19:12:12 ******/
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/12/13 19:12:12 ******/
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/12/13 19:12:12 ******/
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/12/13 19:12:12 ******/
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/12/13 19:12: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/12/13 19:12: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/12/13 19:12:14 ******/
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/12/13 19:12:14 ******/
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/12/13 19:12:15 ******/
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/12/13 19:12:15 ******/
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/12/13 19:12:15 ******/
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/12/13 19:12:15 ******/
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/12/13 19:12:15 ******/
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/12/13 19:12:16 ******/
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/12/13 19:12:16 ******/
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/12/13 19:12:17 ******/
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/12/13 19:12:17 ******/
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/12/13 19:12:17 ******/
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/12/13 19:12:18 ******/
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/12/13 19:12:18 ******/
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/12/13 19:12:18 ******/
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/12/13 19:12:18 ******/
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/12/13 19:12:18 ******/
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/12/13 19:12:19 ******/
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/12/13 19:12:19 ******/
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/12/13 19:12:19 ******/
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/12/13 19:12:19 ******/
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/12/13 19:12:20 ******/
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/12/13 19:12:20 ******/
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/12/13 19:12:20 ******/
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/12/13 19:12:20 ******/
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/12/13 19:12:21 ******/
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/12/13 19:12:21 ******/
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/12/13 19:12:21 ******/
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/12/13 19:12:22 ******/
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/12/13 19:12:22 ******/
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/12/13 19:12:22 ******/
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/12/13 19:12:23 ******/
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/12/13 19:12:23 ******/
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/12/13 19:12:23 ******/
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/12/13 19:12:23 ******/
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/12/13 19:12:24 ******/
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/12/13 19:12:24 ******/
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/12/13 19:12:24 ******/
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/12/13 19:12:24 ******/
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/12/13 19:12:25 ******/
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/12/13 19:12:25 ******/
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/12/13 19:12:25 ******/
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/12/13 19:12:26 ******/
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/12/13 19:12:26 ******/
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/12/13 19:12:26 ******/
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/12/13 19:12:26 ******/
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/12/13 19:12:26 ******/
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/12/13 19:12:27 ******/
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/12/13 19:12:27 ******/
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/12/13 19:12:27 ******/
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/12/13 19:12:27 ******/
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/12/13 19:12:27 ******/
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/12/13 19:12:28 ******/
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/12/13 19:12:28 ******/
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/12/13 19:12:28 ******/
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/12/13 19:12:28 ******/
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/12/13 19:12:29 ******/
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/12/13 19:12:29 ******/
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/12/13 19:12:29 ******/
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/12/13 19:12:29 ******/
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/12/13 19:12:30 ******/
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/12/13 19:12:30 ******/
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/12/13 19:12:31 ******/
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/12/13 19:12:31 ******/
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/12/13 19:12:31 ******/
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/12/13 19:12:31 ******/
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/12/13 19:12:31 ******/
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/12/13 19:12:32 ******/
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/12/13 19:12:32 ******/
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/12/13 19:12:32 ******/
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/12/13 19:12:32 ******/
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
