
/****** Object:  StoredProcedure [dbo].[procWxMessageSend2ByCaJobCvMatchInsert]    Script Date: 2018/12/13 19:12:33 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

------------------------------------------
---创建人：Peter
---创建时间：2016-10-19
---企业简历精确匹配的微信推送计划任务
-----------------------------------------
CREATE PROCEDURE [dbo].[procWxMessageSend2ByCaJobCvMatchInsert]
AS
SET NOCOUNT ON
BEGIN
	IF DATEPART(HOUR, GETDATE()) < 10
		RETURN
	IF DATEPART(HOUR, GETDATE()) > 11
		RETURN

	SELECT TOP 5000 b.caMainID,c.cpMainID
	INTO #T
	FROM caJobCvMatch a WITH(NOLOCK) 
	LEFT JOIN JobPublish b WITH(NOLOCK) ON b.ID = a.JobID 
	LEFT JOIN CaMain c WITH(NOLOCK) ON b.caMainID = c.ID
	WHERE a.WxPushDate IS NULL
	AND b.Valid = 1
	AND a.AddDate > CONVERT(VARCHAR(10), GETDATE(), 120)
	GROUP BY b.caMainID ,c.cpMainID

	INSERT WxMessageSend2(Templatetype, WxFansID, PaMainId, MainTableId, CpMainID, CvMainID, JobId, CaMainId, AddDate)
	SELECT 22, b.Id wxFansId, NULL, a.caMainID, a.cpMainID, NULL, NULL, a.caMainID, GETDATE()
	FROM #T a, wxFans b
	WHERE a.caMainID = b.caMainID
	--AND b.Status > 0
	AND caBindCancelDate IS NULL

	UPDATE caJobCvMatch 
	SET WxPushDate = GETDATE() 
	WHERE JobID IN(
		SELECT ID 
		FROM JobPublish WITH(NOLOCK)
		WHERE caMainID IN (SELECT caMainID FROM #T)
		)

	DROP TABLE #T
END
GO

/****** Object:  StoredProcedure [dbo].[ProcWxMessageSend2BySendSelect]    Script Date: 2018/12/13 19:12:34 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[ProcWxMessageSend2BySendSelect]
AS
BEGIN
	SELECT TOP 500 a.id, a.messagetext, a.ReturnResult, a.ErrorNumber, c.Token, e.ProvinceId, e.AppID, e.AppSecret
	FROM wxMessageSend2 a WITH(NOLOCK),
		dcWxtoken c WITH(NOLOCK), wxFans d, wxServiceNo e
	WHERE ISNULL(a.errornumber, 0) < 3
	AND a.SendDate IS NULL
	AND MessageText > ''
	AND a.wxFansId = d.Id
	AND d.wxServiceNoId = e.Id
	AND e.ProvinceId = c.dcProvinceId
--and a.templatetype <> 19
	ORDER BY a.Id DESC
END
GO

/****** Object:  StoredProcedure [dbo].[procWxMessageSendByChatOnlineInsert]    Script Date: 2018/12/13 19:12:34 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--功能：个人未读留言发送微信提醒
--创建人：harry
--2015-9-10
CREATE PROCEDURE [dbo].[procWxMessageSendByChatOnlineInsert]
AS
BEGIN
	--取出2分钟前未多的数据
	SELECT MAX(ID) ID, cvMainId, caMainId INTO #T FROM ChatOnline 
	WHERE ID > ISNULL((SELECT MAX(ChatOnineId) ID FROM wxChatOnlineTemp), 0)
	AND ID IN(SELECT DISTINCT ChatOnlineID
		FROM ChatOnlinelog 
		WHERE SenderType = 1 --企业给个人发送
		AND IsViewed = 0 --未查看
		AND AddDate BETWEEN DATEADD(MINUTE, -30, GETDATE())
		AND DATEADD(MINUTE, -5, GETDATE()))
	AND ID NOT IN(SELECT ChatOnineId FROM wxChatOnlineTemp) 
	GROUP BY cvMainId, caMainId

	--将chatonlineid 或（pamainid, camainid）不存在于wxchatonlinetemp的数据插入wxchatonlinetemp
	INSERT wxChatOnlineTemp(ChatOnineId, paMainId, cvMainid, caMainId)
	SELECT a.ID, b.PaMainId, a.cvMainId, a.caMainId
	FROM #T a, cvMain b, wxFans c
	WHERE a.cvMainId = b.Id
	AND NOT EXISTS(SELECT 'X' FROM wxChatOnlineTemp WHERE paMainId = b.PaMainId AND caMainId = a.caMainId)
	AND b.paMainId = c.PamainId 
	AND c.status>0
	
	--取出未发送的数据
	SELECT a.*, b.Id AS WxFansId 
	INTO #T1 
	FROM wxChatOnlineTemp a, wxFans b 
	WHERE a.IsSend = 0 
	AND a.paMainId = b.paMainId
	
	--插入WxMessageSend2
	INSERT WxMessageSend2(Templatetype, WxFansID, PaMainId, cpMainId, AddDate)
	SELECT 4, a.WxFansId, a.PamainId, b.cpMainId, GETDATE() FROM #T1 a, caMain b WHERE a.caMainId = b.Id 
	--SELECT 4, 178509, 25681483, 371108, GETDATE() FROM #T1 a, caMain b WHERE a.caMainId = b.Id 
	
	--更新wxchatonlinetemp
	UPDATE wxChatOnlineTemp 
	SET IsSend = 1 
	WHERE IsSend = 0
END
GO

/****** Object:  StoredProcedure [dbo].[procWxMessageSendByMessageUpdate]    Script Date: 2018/12/13 19:12:34 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

/***********************
---微信json字符串组合--
---Harry 2015-8-27-----
---修改harry 271行：联系方式是否隐藏的处理
---修改harry 2018-4-10增加23校园招聘会审核
**********************/
CREATE PROCEDURE [dbo].[procWxMessageSendByMessageUpdate]
AS
SET NOCOUNT ON
BEGIN
	SET NOCOUNT OFF
	DECLARE @ParaValue VARCHAR(2000), 
		@JsonMessage VARCHAR(1000), 	--json字符串　
		@PaName VARCHAR(50), 
		@JobName VARCHAR(50), 
		@CpMainId INT, 
		@CompanyName NVARCHAR(100), 
		@InterviewDate NVARCHAR(100), 
		@InterviewPlace NVARCHAR(100), 
		@LinkMan NVARCHAR(25), 
		@Telephone VARCHAR(25), 
		@Url VARCHAR(1000), 
		@MinId INT

	UPDATE wxmessagesend2
	SET ErrorNumber = 9 
	WHERE AddDate > DATEADD(MINUTE, -10, GETDATE())
	AND WxFansId IN(
		SELECT Id FROM WxFans WITH(NOLOCK) WHERE WxServiceNoId IN(SELECT ID FROM WxServiceNo WITH(NOLOCK) WHERE Status = 2)
	)
	AND ErrorNumber < 3

	UPDATE wxmessagesend2
	SET ErrorNumber = 9 
	WHERE Id IN(SELECT ID FROM (SELECT Id, ROW_NUMBER() OVER(PARTITION BY PaMainId, TemplateType ORDER BY Id) RowNo
		FROM wxMessagesend2 WITH(NOLOCK)
		WHERE AddDate > CONVERT(VARCHAR(10), GETDATE(), 120)) a
		WHERE RowNo > 2
		AND TemplateType NOT IN(20, 22,23))
	AND ErrorNumber < 3
	AND Templatetype > 1

	SELECT TOP 1 @MinId = ID FROM wxMessagesend2 WITH(NOLOCK)
	WHERE Templatetype <> 8
	AND (JobID IS NULL OR caMainId IS NULL OR cpMainId IS NULL OR cpMainId = 0)
	AND AddDate > GETDATE() - 0.5
	ORDER BY ID

	IF @MinId > 0
	BEGIN
		UPDATE a SET a.caMainId = b.caMainId
		FROM wxMessagesend2 a WITH(NOLOCK), Job b WITH(NOLOCK)
		WHERE a.Jobid = b.Id
		AND a.caMainId IS NULL
		AND a.JobID > 0
		AND a.Id > @MinID

		UPDATE a SET a.cpMainId = b.cpMainId
		FROM WxMessageSend2 a WITH(NOLOCK), caMain b WITH(NOLOCK)
		WHERE a.caMainid = b.Id
		AND a.caMainId > 0
		AND ISNULL(a.cpMainId, 0) = 0
		AND a.Id > @MinID
		--AND a.TemplateType <> 20
	END

	--UPDATE WxMessageSend2 SET wxFansId = 178509 WHERE MessageText IS NULL 
	--UPDATE WxMessageSend2 SET wxFansId = 178509, MessageText = null --WHERE MessageText IS NULL 
	--取出待发送的数据
	SELECT a.*, b.Name paName, c.OpenId, c.WxServiceNoID, d.ProvinceDomain, d.WebsiteName INTO #T1 
	FROM WxMessageSend2 a WITH(NOLOCK)
	LEFT JOIN PaMain b WITH(NOLOCK) ON a.PaMainID = b.ID
	LEFT JOIN WxFans c WITH(NOLOCK) ON a.WxFansID = c.ID
	INNER JOIN WxServiceNo e WITH(NOLOCK) ON c.WxServiceNoId = e.Id
	INNER JOIN dcprovince d WITH(NOLOCK) ON d.id = e.ProvinceID
	WHERE a.MessageText IS NULL
	AND ErrorNumber < 3
	AND a.AddDate > DATEADD(MINUTE, - 10, GETDATE())

	IF @@RowCount = 0
		RETURN

	--------面试通知开始------ 1  
	SELECT a.*, b.[NO] AS WxTemplateNo , c.InterviewDate, c.InterViewPlace, c.LinkMan, c.Telephone, d.Name jobName, 
		d.dcSalaryID, e.Name CompanyName, SPACE(1000) ParaValue, SPACE(200) Url, SPACE(1000) JsonMessage
	INTO #T01
	FROM #T1 a, WxTemplateNo b WITH(NOLOCK), Exinterview c WITH(NOLOCK), Job d WITH(NOLOCK), CpMain e WITH(NOLOCK)
	WHERE a.Templatetype = 1 AND a.WxServiceNoID = b.WxServiceNoID AND b.WxTemplateId = 1 AND a.MainTableId = c.Id AND a.JobID = d.ID AND a.cpMainId = e.id--面试通知
	IF @@RowCount > 0
	BEGIN
		--插入参数数据
		SET @ParaValue = ''
		SELECT @ParaValue = @ParaValue + CASE WHEN @ParaValue > '' THEN ', ' ELSE '' END + ' "' + ParaName + '":{    "value":"' + ParaValue + '",    "color":"' + ParaColor + '"}' 
		FROM WxTemplatePara WITH(NOLOCK) WHERE WxTemplateID = 1 ORDER BY ID
		UPDATE #T01 SET ParaValue = @ParaValue			
		 
		UPDATE #T01 SET ParaValue = REPLACE(ParaValue, '#PaName#', PaName)
		UPDATE #T01 SET ParaValue = REPLACE(ParaValue, '#JobName#', JobName)
		UPDATE #T01 SET ParaValue = REPLACE(ParaValue, '#CompanyName#', CompanyName)	
		UPDATE #T01 SET ParaValue = REPLACE(ParaValue, '#InterviewDate#', CONVERT(varchar, InterviewDate, 120 ))
		UPDATE #T01 SET ParaValue = REPLACE(ParaValue, '#InterViewPlace#', InterViewPlace)
		UPDATE #T01 SET ParaValue = REPLACE(ParaValue, '#LinkMan#', LinkMan)
		UPDATE #T01 SET ParaValue = REPLACE(ParaValue, '#Telephone#', Telephone)
		UPDATE #T01 SET ParaValue = REPLACE(ParaValue, '#WebsiteName#', WebsiteName)
		UPDATE #T01 SET Url = 'http://m.' + ProvinceDomain + '/library/WechatOauthPaLogin?opid=' + OpenId + '&urlfile=/personal/jm/InterViewList'
		UPDATE #T01 SET	JsonMessage = '{"touser":"' + OpenId + '", "template_id":"' + WxTemplateNo + '", "url":"' + Url + '", "topcolor":"#FF0000", "data":{' + ParaValue + '}}'
	    --更新wxmessagesend中的message
	    UPDATE WxMessageSend2 
	    SET MessageText = a.JsonMessage FROM #T01 a WHERE a.id = WxMessageSend2.id  
	END
	--------面试通知结束------
	
	
	------应聘邀请提醒开始---- 2
	SELECT a.*, b.[NO] AS WxTemplateNo, d.Name jobName, d.dcSalaryID, c.Name CompanyName, e.FullName, 
		f.Adddate AS mainAddDate, SPACE(1000) ParaValue, SPACE(200) Url, SPACE(1000) JsonMessage
	INTO #T02
	FROM #T1 a, WxTemplateNo b WITH(NOLOCK), CpMain c WITH(NOLOCK), Job d WITH(NOLOCK), dcRegion e WITH(NOLOCK), cacvintention f WITH(NOLOCK)
	WHERE a.Templatetype = 2 
	AND a.WxServiceNoID = b.WxServiceNoID 
	AND b.WxTemplateId = 2 
	AND a.cpMainId = c.id 
	AND a.JobID = d.ID 
	AND d.dcRegionId = e.id
	AND f.id = a.MainTableId --应聘邀请
	IF @@RowCount > 0
	BEGIN
		--插入参数数据
		SELECT @ParaValue = ''
		SELECT @ParaValue = @ParaValue + CASE WHEN @ParaValue > '' THEN ', ' ELSE '' END + ' "' + ParaName + '":{    "value":"' + ParaValue + '",    "color":"' + ParaColor + '"}' FROM WxTemplatePara WITH(NOLOCK) WHERE WxTemplateID = 2 ORDER BY ID
		UPDATE #T02 SET ParaValue = @ParaValue
		 
		UPDATE #T02 SET ParaValue = REPLACE(ParaValue, '#PaName#', PaName)
		UPDATE #T02 SET ParaValue = REPLACE(ParaValue, '#Salary#', (SELECT [Description] FROM dcsalary WITH(NOLOCK) WHERE ID = dcSalaryID))
		UPDATE #T02 SET ParaValue = REPLACE(ParaValue, '#JobName#', JobName)	
		UPDATE #T02 SET ParaValue = REPLACE(ParaValue, '#companyname#', CompanyName)
		UPDATE #T02 SET ParaValue = REPLACE(ParaValue, '#address#', FullName)
		UPDATE #T02 SET ParaValue = REPLACE(ParaValue, '#adddate#', CONVERT(varchar, mainAddDate, 120)) 
		UPDATE #T02 SET ParaValue = REPLACE(ParaValue, '#WebsiteName#', WebsiteName)
		UPDATE #T02 SET Url = 'http://m.' + ProvinceDomain + '/library/WechatOauthPaLogin?opid=' + OpenId + '&urlfile=/personal/jm/CvIntention'
		UPDATE #T02 SET	JsonMessage = '{"touser":"' + OpenId + '", "template_id":"' + WxTemplateNo + '", "url":"' + Url + '", "topcolor":"#FF0000", "data":{' + ParaValue + '}}'
		--更新wxmessagesend中的message
		UPDATE WxMessageSend2 
		SET  MessageText = a.JsonMessage FROM #T02 a WHERE a.id = WxMessageSend2.id  
	END
	------应聘邀请提醒结束----	
	
	------收藏简历通知开始---- 3
	SELECT a.*, b.[NO] AS WxTemplateNo, c.Name jobName, d.Name CompanyName, SPACE(1000) ParaValue, SPACE(200) Url, SPACE(1000) JsonMessage
	INTO #T03
	FROM #T1 a, WxTemplateNo b WITH(NOLOCK), Job c WITH(NOLOCK), CpMain d WITH(NOLOCK)
	WHERE a.Templatetype = 3 AND a.WxServiceNoID = b.WxServiceNoID AND b.WxTemplateId = 3 AND a.JobID = c.ID AND a.cpMainId = d.id--简历收藏通知
	IF @@RowCount > 0
	BEGIN
		--插入参数数据
		SELECT @ParaValue = ''
		SELECT @ParaValue = @ParaValue + CASE WHEN @ParaValue > '' THEN ', ' ELSE '' END + ' "' + ParaName + '":{    "value":"' + ParaValue + '",    "color":"' + ParaColor + '"}' FROM WxTemplatePara WITH(NOLOCK) WHERE WxTemplateID = 3 ORDER BY ID
		UPDATE #T03 SET ParaValue = @ParaValue		
		 
		UPDATE #T03 SET ParaValue = REPLACE(ParaValue, '#PaName#', PaName) 
		UPDATE #T03 SET ParaValue = REPLACE(ParaValue, '#CompanyName#', CompanyName)	 
		UPDATE #T03 SET ParaValue = REPLACE(ParaValue, '#JobName#', JobName)	
		UPDATE #T03 SET ParaValue = REPLACE(ParaValue, '#WebsiteName#', WebsiteName)
		UPDATE #T03 SET Url = 'http://m.' + ProvinceDomain + '/library/WechatOauthPaLogin?opid=' + OpenId + '&urlfile=/Personal/jv/CompanyDetail?cpmainid=' + CONVERT(VARCHAR(30), CpMainId)
		UPDATE #T03 SET	JsonMessage = '{"touser":"' + OpenId + '", "template_id":"' + WxTemplateNo + '", "url":"' + Url + '", "topcolor":"#FF0000", "data":{' + ParaValue + '}}'
		--更新wxmessagesend中的message
		UPDATE WxMessageSend2 
		SET MessageText = a.JsonMessage FROM #T03 a WHERE a.id = WxMessageSend2.id   
	END
	------收藏简历通知结束----	
	
	-----企业留言开始----4
	SELECT a.*, b.[NO] AS WxTemplateNo, c.Name CompanyName, SPACE(1000) ParaValue, SPACE(200) Url, SPACE(1000) JsonMessage 
	INTO #T04
	FROM #T1 a, WxTemplateNo b WITH(NOLOCK), CpMain c WITH(NOLOCK)
	WHERE a.Templatetype = 4 AND a.WxServiceNoID = b.WxServiceNoID AND b.WxTemplateId = 4 AND a.cpMainId = c.id
	IF @@RowCount > 0
	BEGIN
	--插入参数数据
		SELECT @ParaValue = ''
		SELECT @ParaValue = @ParaValue + CASE WHEN @ParaValue > '' THEN ', ' ELSE '' END + ' "' + ParaName + '":{    "value":"' + ParaValue + '",    "color":"' + ParaColor + '"}' FROM WxTemplatePara WITH(NOLOCK) WHERE WxTemplateID = 4 ORDER BY ID
		UPDATE #T04 SET ParaValue = @ParaValue 
		UPDATE #T04 SET ParaValue = REPLACE(ParaValue, '#PaName#', PaName)
		UPDATE #T04 SET ParaValue = REPLACE(ParaValue, '#CompanyName#', CompanyName)
		UPDATE #T04 SET ParaValue = REPLACE(ParaValue, '#WebsiteName#', WebsiteName)
		UPDATE #T04 SET Url = 'http://m.' + ProvinceDomain + '/library/WechatOauthPaLogin?opid=' + OpenId + '&urlfile=/chatonline/palist'
		UPDATE #T04 SET	JsonMessage = '{"touser":"' + OpenId + '", "template_id":"' + WxTemplateNo + '", "url":"' + Url + '", "topcolor":"#FF0000", "data":{' + ParaValue + '}}'
		--更新wxmessagesend中的message
		UPDATE WxMessageSend2
		SET MessageText = a.JsonMessage FROM #T04 a WHERE a.id = WxMessageSend2.id
	END
	-----企业留言结束----
	------企业浏览开始----5
	SELECT a.*, b.[NO] AS WxTemplateNo, c.Name CompanyName, SPACE(1000) ParaValue, SPACE(200) Url, SPACE(1000) JsonMessage
	INTO #T05
	FROM #T1 a, WxTemplateNo b WITH(NOLOCK), CpMain c WITH(NOLOCK)
	WHERE a.Templatetype = 5 AND a.WxServiceNoID = b.WxServiceNoID AND b.WxTemplateId = 5 AND a.cpMainId = c.id
	IF @@RowCount > 0
	BEGIN
		--插入参数数据
		SELECT @ParaValue = ''
		SELECT @ParaValue = @ParaValue + CASE WHEN @ParaValue > '' THEN ', ' ELSE '' END + ' "' + ParaName + '":{    "value":"' + ParaValue + '",    "color":"' + ParaColor + '"}' FROM WxTemplatePara WITH(NOLOCK) WHERE WxTemplateID = 5 ORDER BY ID
		UPDATE #T05 SET ParaValue = @ParaValue	
		 
		UPDATE #T05 SET ParaValue = REPLACE(ParaValue, '#PaName#', PaName) 
		UPDATE #T05 SET ParaValue = REPLACE(ParaValue, '#CompanyName#', CompanyName) 
		UPDATE #T05 SET ParaValue = REPLACE(ParaValue, '#WebsiteName#', WebsiteName)
		UPDATE #T05 SET Url = 'http://m.' + ProvinceDomain + '/library/WechatOauthPaLogin?opid=' + OpenId + '&urlfile=/personal/jm/CpAttentionList'
		UPDATE #T05 SET	JsonMessage = '{"touser":"' + OpenId + '", "template_id":"' + WxTemplateNo + '", "url":"' + Url + '", "topcolor":"#FF0000", "data":{' + ParaValue + '}}'
		--更新wxmessagesend中的message
		UPDATE WxMessageSend2 
		SET  MessageText = a.JsonMessage FROM #T05 a WHERE a.id = WxMessageSend2.id   
	END
	------企业浏览结束----

	------企业下载简历开始----6
	SELECT a.*, b.[NO] AS WxTemplateNo, c.Name CompanyName,c.SecondId, SPACE(1000) ParaValue, SPACE(200) Url, SPACE(1000) JsonMessage
	INTO #T06
	FROM #T1 a, WxTemplateNo b WITH(NOLOCK), CpMain c WITH(NOLOCK)
	WHERE a.Templatetype = 6 AND a.WxServiceNoID = b.WxServiceNoID AND b.WxTemplateId = 6 AND a.cpMainId = c.id
	IF @@RowCount > 0
 	BEGIN
		--插入参数数据
		SELECT @ParaValue = ''
		SELECT @ParaValue = @ParaValue + CASE WHEN @ParaValue > '' THEN ', ' ELSE '' END + ' "' + ParaName + '":{    "value":"' + ParaValue + '",    "color":"' + ParaColor + '"}' FROM WxTemplatePara WITH(NOLOCK) WHERE WxTemplateID = 6 ORDER BY ID
		UPDATE #T06 SET ParaValue = @ParaValue	
		 
		UPDATE #T06 SET ParaValue = REPLACE(ParaValue, '#PaName#', PaName) 
		UPDATE #T06 SET ParaValue = REPLACE(ParaValue, '#CompanyName#', CompanyName) 
		UPDATE #T06 SET ParaValue = REPLACE(ParaValue, '#WebsiteName#', WebsiteName)
		UPDATE #T06 SET Url = 'http://m.' + ProvinceDomain + '/library/WechatOauthPaLogin?opid=' + OpenId + '&urlfile=/personal/cp' + CONVERT(VARCHAR(30), SecondId )+'.html'
		UPDATE #T06 SET	JsonMessage = '{"touser":"' + OpenId + '", "template_id":"' + WxTemplateNo + '", "url":"' + Url + '", "topcolor":"#FF0000", "data":{' + ParaValue + '}}'
		--更新wxmessagesend中的message
		UPDATE WxMessageSend2 
		SET  MessageText = a.JsonMessage FROM #T06 a WHERE a.id = WxMessageSend2.id   
	END
	------企业下载简历结束----
	
	------简历审核未通过------7
	SELECT a.*, b.[NO] AS WxTemplateNo, c.VerifyDate, d.Mobile, SPACE(1000) ParaValue, SPACE(200) Url, SPACE(1000) JsonMessage
	INTO #T07
	FROM #T1 a, WxTemplateNo b WITH(NOLOCK), bsCvVerify c WITH(NOLOCK), PaMain d WITH(NOLOCK)
	WHERE a.Templatetype = 7 AND a.WxServiceNoID = b.WxServiceNoID 
	AND b.WxTemplateId = 7 AND a.MainTableId = c.Id AND a.PaMainId = d.Id
	IF @@RowCount > 0
	BEGIN
		--插入参数数据
		SELECT @ParaValue = ''
		SELECT @ParaValue = @ParaValue + CASE WHEN @ParaValue > '' THEN ', ' ELSE '' END + ' "' + ParaName + '":{    "value":"' + ParaValue + '",    "color":"' + ParaColor + '"}' FROM WxTemplatePara WITH(NOLOCK) WHERE WxTemplateID = 7 ORDER BY ID
		UPDATE #T07 SET ParaValue = @ParaValue	
		 
		UPDATE #T07 SET ParaValue = REPLACE(ParaValue, '#PaName#', PaName) 
		UPDATE #T07 SET ParaValue = REPLACE(ParaValue, '#Tel#', Mobile)
		UPDATE #T07 SET ParaValue = REPLACE(ParaValue, '#AddDate#', CONVERT(varchar, VerifyDate, 120 )) 
		UPDATE #T07 SET ParaValue = REPLACE(ParaValue, '#WebsiteName#', WebsiteName)
		UPDATE #T07 SET Url = 'http://m.' + ProvinceDomain + '/library/WechatOauthPaLogin?opid=' + OpenId + '&urlfile=/personal/sys/index'
		UPDATE #T07 SET	JsonMessage = '{"touser":"' + OpenId + '", "template_id":"' + WxTemplateNo + '", "url":"' + Url + '", "topcolor":"#FF0000", "data":{' + ParaValue + '}}'
		--更新wxmessagesend中的message
		UPDATE WxMessageSend2 
		SET  MessageText = a.JsonMessage FROM #T07 a WHERE a.id = WxMessageSend2.id
	END
	------简历审核未通过结束--
	
	------照片审核未通过------8
	SELECT a.*, b.[NO] AS WxTemplateNo, c.CheckDate, d.Mobile, SPACE(1000) ParaValue, SPACE(200) Url, SPACE(1000) JsonMessage
	INTO #T08
	FROM #T1 a, WxTemplateNo b WITH(NOLOCK), paPhoto c WITH(NOLOCK), PaMain d WITH(NOLOCK)
	WHERE a.Templatetype = 8 AND a.WxServiceNoID = b.WxServiceNoID AND b.WxTemplateId = 8 AND a.PaMainId = c.paMainId AND a.PaMainId = d.Id
	IF @@RowCount > 0
	BEGIN
		--插入参数数据
		SELECT @ParaValue = ''
		SELECT @ParaValue = @ParaValue + CASE WHEN @ParaValue > '' THEN ', ' ELSE '' END + ' "' + ParaName + '":{    "value":"' + ParaValue + '",    "color":"' + ParaColor + '"}' FROM WxTemplatePara WITH(NOLOCK) WHERE WxTemplateID = 8 ORDER BY ID
		UPDATE #T08 SET ParaValue = @ParaValue	
		 
		UPDATE #T08 SET ParaValue = REPLACE(ParaValue, '#PaName#', PaName) 
		UPDATE #T08 SET ParaValue = REPLACE(ParaValue, '#Tel#', Mobile)
		UPDATE #T08 SET ParaValue = REPLACE(ParaValue, '#AddDate#', CONVERT(varchar, CheckDate, 120 )) 
		UPDATE #T08 SET ParaValue = REPLACE(ParaValue, '#WebsiteName#', WebsiteName)
		UPDATE #T08 SET Url = 'http://m.' + ProvinceDomain + '/library/WechatOauthPaLogin?opid=' + OpenId + '&urlfile=/personal/sys/index'
		UPDATE #T08 SET	JsonMessage = '{"touser":"' + OpenId + '", "template_id":"' + WxTemplateNo + '", "url":"' + Url + '", "topcolor":"#FF0000", "data":{' + ParaValue + '}}'
		--更新wxmessagesend中的message
		UPDATE WxMessageSend2 
		SET  MessageText = a.JsonMessage FROM #T08 a WHERE a.id = WxMessageSend2.id  
	END
	------照片审核未通过结束--
	
	------简历答复开始-------9
	SELECT a.*, b.[NO] AS WxTemplateNo, c.Name CompanyName, d.Name jobName, CASE WHEN e.IsPhoneHide = 1 THEN '' ELSE e.Telephone END Telephone, CASE WHEN e.IsMobileHide = 1 THEN  ''  ELSE e.Mobile END Mobile, f.Reply, 
		f.ReplyDate, f.IsPassed, f.AddDate AS ApplyAddDate, SPACE(1000) ParaValue, SPACE(200) Url, SPACE(1000) JsonMessage
	INTO #T09
	FROM #T1 a, WxTemplateNo b WITH(NOLOCK), CpMain c WITH(NOLOCK), Job d WITH(NOLOCK), caMain e WITH(NOLOCK), exJobApply f WITH(NOLOCK)
	WHERE a.Templatetype = 9 
	AND a.WxServiceNoID = b.WxServiceNoID 
	AND b.WxTemplateId = 9 
	AND a.cpMainId = c.id 
	AND a.JobID = d.ID 
	AND e.id = a.caMainId 
	AND a.MainTableId = f.id
	IF @@RowCount > 0
	BEGIN
		--插入参数数据
		UPDATE #T09
		SET ParaValue = 
			(
			SELECT ' "' + ParaName + '":{    "value":"' + ParaValue + '",    "color":"' + ParaColor + '"}, ' 
			FROM WxTemplatePara WITH(NOLOCK) WHERE WxTemplateID = 9 AND ParaName = 'first') + 
			(SELECT ' "' + ParaName + '":{    "value":"' + ParaValue + '",    "color":"' + ParaColor + '"}, ' 
			FROM WxTemplatePara WITH(NOLOCK) WHERE WxTemplateID = 9 AND ParaName = 'keyword1')	 + 
			(SELECT ' "' + ParaName + '":{    "value":"' + ParaValue + '",    "color":"' + ParaColor + '"}, ' 
			FROM WxTemplatePara WITH(NOLOCK) WHERE WxTemplateID = 9 AND ParaName = 'keyword2') + 	 
			(SELECT ' "' + ParaName + '":{    "value":"' + ParaValue + '",    "color":"' + ParaColor + '"}, ' 
			FROM WxTemplatePara WITH(NOLOCK) WHERE WxTemplateID = 9 AND ParaName = 'keyword3')	 + 
			(SELECT ' "' + ParaName + '":{    "value":"' + ParaValue + '",    "color":"' + ParaColor + '"}, ' 
			FROM WxTemplatePara WITH(NOLOCK) WHERE WxTemplateID = 9 AND ParaName = 'keyword4') + 	 
			(SELECT ' "' + ParaName + '":{    "value":"' + '#KeyWord4#' + ParaValue + '",    "color":"' + ParaColor + '"}, ' 
			FROM WxTemplatePara WITH(NOLOCK) WHERE WxTemplateID = 9 AND ParaName = 'keyword5') + 
			(SELECT ' "' + ParaName + '":{    "value":"' + ParaValue + '",    "color":"' + ParaColor + '"}' 
			FROM WxTemplatePara WITH(NOLOCK) WHERE WxTemplateID = 9 AND ParaName = 'remark'
			)

		UPDATE #T09 SET ParaValue = REPLACE(ParaValue, '#PaName#', PaName)
		UPDATE #T09 SET ParaValue = REPLACE(ParaValue, '#JobName#', JobName)
		UPDATE #T09 SET ParaValue = REPLACE(ParaValue, '#CompanyName#', CompanyName)
		UPDATE #T09 SET ParaValue = REPLACE(ParaValue, '#AddDate#', CONVERT(varchar, ApplyAddDate, 120))
		UPDATE #T09 SET ParaValue = REPLACE(ParaValue, '#VerifyResult#', CASE WHEN reply = 1 THEN '符合要求，近期会联系您' WHEN reply = 2 THEN '暂时不符合要求' ELSE '职位暂时满员，空缺时再联系！'END)
		--UPDATE #T09 SET ParaValue = REPLACE(ParaValue, '#KeyWord4#', CASE WHEN reply = 1 THEN '符合要求' WHEN reply = 2 THEN '不符合要求' ELSE '以后联系' END)	
		UPDATE #T09 SET ParaValue = REPLACE(ParaValue, '#KeyWord4#', '')	
		UPDATE #T09 SET ParaValue = REPLACE(ParaValue, '#tel#', CASE WHEN ISNULL(Telephone, '') = ''THEN Mobile ELSE Telephone END)
		UPDATE #T09 SET ParaValue = REPLACE(ParaValue, '#Remark#', CASE WHEN reply = 1 THEN '主动联系公司，效果更好，祝您求职顺利！' WHEN reply = 2 THEN '不怕路远，就怕志短，尽快申请其他岗位，获得更多求职机会！' ELSE '主动联系公司，效果更好，祝您求职顺利！' END)
		UPDATE #T09 SET ParaValue = REPLACE(ParaValue, '#WebsiteName#', WebsiteName)
		UPDATE #T09 SET Url = 'http://m.' + ProvinceDomain + '/library/WechatOauthPaLogin?opid=' + OpenId + '&urlfile=/personal/jm/JobApplyList'
		UPDATE #T09 SET	JsonMessage = '{"touser":"' + OpenId + '", "template_id":"' + WxTemplateNo + '", "url":"' + Url + '", "topcolor":"#FF0000", "data":{' + ParaValue + '}}'
		--更新wxmessagesend中的message
		UPDATE WxMessageSend2 
		SET MessageText = a.JsonMessage FROM #T09 a WHERE a.id = WxMessageSend2.id
	END
	------简历答复结束--------	
	/*
	----微信替代短信开始-------10
	SELECT a.*, b.[NO] AS WxTemplateNo, c.*, d.UserName, SPACE(1000) ParaValue, SPACE(200) Url, SPACE(1000) JsonMessage
	INTO #T10
	FROM #T1 a, WxTemplateNo b, ShortDb..wxMessageTemp c, paMain d
	WHERE a.Templatetype = 10 AND a.WxServiceNoID = b.WxServiceNoID AND b.WxTemplateId = 10 AND a.MainTableId = c.Id AND d.Id = a.MainTableId
	IF @@RowCount > 0
	BEGIN
		--插入参数数据
		UPDATE #T10
		SET ParaValue = 
			(
			SELECT ' "' + ParaName + '":{    "value":"' + ParaValue + '",    "color":"' + ParaColor + '"}, ' 
			FROM WxTemplatePara WITH(NOLOCK) WHERE WxTemplateID = 10 AND ParaName = 'first') + 
			(SELECT ' "' + ParaName + '":{    "value":"' + ParaValue + '",    "color":"' + ParaColor + '"}, ' 
			FROM WxTemplatePara WITH(NOLOCK) WHERE WxTemplateID = 10 AND ParaName = 'keyword1')	 + 
			(SELECT ' "' + ParaName + '":{    "value":"' + ParaValue + '",    "color":"' + ParaColor + '"}, ' 
			FROM WxTemplatePara WITH(NOLOCK) WHERE WxTemplateID = 10 AND ParaName = 'keyword2') + 
			(SELECT ' "' + ParaName + '":{    "value":"' + ParaValue + '",    "color":"' + ParaColor + '"}' 
			FROM WxTemplatePara WITH(NOLOCK) WHERE WxTemplateID = 10 AND ParaName = 'remark'
			)
			 --前10天注册，最后登陆日期在3天前的，发送登录提醒 6
			 --前3天注册，简历不完整，登录 = 一次的，发送用户名、密码 7
			 --前3天注册，简历不完整，登录>一次的，发送简历不完整提醒 8
		UPDATE #T10 
		SET ParaValue = REPLACE(ParaValue, '#InformationValue#', 
			CASE WHEN SmsType = 6 THEN '您好，您在' + WebsiteName + 'http://www.' + provincedomain + '的用户名:' + UserName + '，欢迎使用'
				WHEN SmsType = 7 THEN '您好，您在' + WebsiteName + 'http://www.' + provincedomain + '的用户名:' + UserName + '，欢迎使用'
				ELSE  '您好，您在' + WebsiteName + 'http://www.' + provincedomain + '的简历不完整，请及时补全。拥有一份完整的简历，您将会拥有更多的求职机会'
			END)
		UPDATE #T10 SET ParaValue = REPLACE(ParaValue, '#PaName#', PaName)
		UPDATE #T10 SET Url = 'http://m.' + ProvinceDomain + '/library/WechatOauthPaLogin?opid=' + OpenId
		UPDATE #T10 SET	JsonMessage = '{"touser":"' + OpenId + '", "template_id":"' + WxTemplateNo + '", "url":"' + Url + '", "topcolor":"#FF0000", "data":{' + ParaValue + '}}'
		--更新wxmessagesend中的message
		UPDATE WxMessageSend2 
		SET  MessageText = a.JsonMessage FROM #T10 a WHERE a.id = WxMessageSend2.id  
    END
	----微信替代短信结束-------
	*/
	--你的菜儿开始
	SELECT a.*, b.[NO] AS WxTemplateNo, SPACE(1000) ParaValue, c.JobDesc,c.BatchNo, SPACE(200) Url, SPACE(1000) JsonMessage
	INTO #T13
	FROM #T1 a, WxTemplateNo b WITH(NOLOCK), paYourFoodWeiXin c WITH(NOLOCK)
	WHERE a.Templatetype = 13 
	AND a.WxServiceNoID = b.WxServiceNoID 
	AND b.WxTemplateId = 13 
	AND a.paMainId = c.paMainId

	IF @@RowCount > 0
	BEGIN
		--插入参数数据
		SELECT @ParaValue = ''
		SELECT @ParaValue = @ParaValue + CASE WHEN @ParaValue > '' THEN ', ' ELSE '' END + ' "' + ParaName + '":{    "value":"' + ParaValue + '",    "color":"' + ParaColor + '"}' 
		FROM WxTemplatePara WITH(NOLOCK) WHERE WxTemplateID = 13 ORDER BY ID

		UPDATE #T13 SET ParaValue = @ParaValue		 
		UPDATE #T13 SET ParaValue = REPLACE(ParaValue, '#PaName#', PaName) 
		UPDATE #T13 SET ParaValue = REPLACE(ParaValue, '#JobDesc#', JobDesc)
		UPDATE #T13 SET ParaValue = REPLACE(ParaValue, '#WebsiteName#', WebsiteName)
		UPDATE #T13 SET Url = 'http://m.' + ProvinceDomain + '/library/WechatOauthPaLogin?opid=' + OpenId + '&urlfile=/personal/js/yourfood?BatchNo=' + CAST(BatchNo AS VARCHAR(10))
		UPDATE #T13 SET	JsonMessage = '{"touser":"' + OpenId + '", "template_id":"' + WxTemplateNo + '", "url":"' + Url + '", "topcolor":"#000000", "data":{' + ParaValue + '}}'
		--更新wxmessagesend中的message
		UPDATE WxMessageSend2 
		SET MessageText = a.JsonMessage FROM #T13 a WHERE a.id = WxMessageSend2.id   
	END

	------应聘的简历提醒---- 14
	SELECT a.*, b.[NO] AS WxTemplateNo, c.Name jobName, d.Name CompanyName, SPACE(1000) ParaValue, SPACE(200) Url, SPACE(1000) JsonMessage
	INTO #T14
	FROM #T1 a, WxTemplateNo b WITH(NOLOCK), Job c WITH(NOLOCK), CpMain d WITH(NOLOCK)
	WHERE a.Templatetype = 14 AND a.WxServiceNoID = b.WxServiceNoID AND b.WxTemplateId = 14 AND a.JobID = c.ID AND a.cpMainId = d.id
	IF @@RowCount > 0
	BEGIN
		--插入参数数据
		SELECT @ParaValue = ''
		SELECT @ParaValue = @ParaValue + CASE WHEN @ParaValue > '' THEN ', ' ELSE '' END + ' "' + ParaName + '":{    "value":"' + ParaValue + '",    "color":"' + ParaColor + '"}' FROM WxTemplatePara WITH(NOLOCK) WHERE WxTemplateID = 14 ORDER BY ID
		UPDATE #T14 SET ParaValue = @ParaValue		
		UPDATE #T14 SET ParaValue = REPLACE(ParaValue, '#CompanyName#', CompanyName)	 
		UPDATE #T14 SET ParaValue = REPLACE(ParaValue, '#JobName#', JobName)	
		UPDATE #T14 SET ParaValue = REPLACE(ParaValue, '#WebsiteName#', WebsiteName)
		UPDATE #T14 SET Url = 'http://m.' + ProvinceDomain + '/library/WechatOauthCpLogin?opid=' + OpenId + '&urlfile=/company/cv/applycv'
		UPDATE #T14 SET	JsonMessage = '{"touser":"' + OpenId + '", "template_id":"' + WxTemplateNo + '", "url":"' + Url + '", "topcolor":"#FF0000", "data":{' + ParaValue + '}}'
		--更新wxmessagesend中的message
		UPDATE WxMessageSend2 
		SET MessageText = a.JsonMessage FROM #T14 a WHERE a.id = WxMessageSend2.id   
	END
	------应聘的简历提醒----

	------面试通知答复提醒---- 15
	SELECT a.*, b.[NO] AS WxTemplateNo, c.Name jobName, d.Name CompanyName, SPACE(1000) ParaValue, SPACE(200) Url, SPACE(1000) JsonMessage
	INTO #T15
	FROM #T1 a, WxTemplateNo b WITH(NOLOCK), Job c WITH(NOLOCK), CpMain d WITH(NOLOCK)
	WHERE a.Templatetype = 15 AND a.WxServiceNoID = b.WxServiceNoID AND b.WxTemplateId = 15 AND a.JobID = c.ID AND a.cpMainId = d.id
	IF @@RowCount > 0
	BEGIN
		--插入参数数据
		SELECT @ParaValue = ''
		SELECT @ParaValue = @ParaValue + CASE WHEN @ParaValue > '' THEN ', ' ELSE '' END + ' "' + ParaName + '":{    "value":"' + ParaValue + '",    "color":"' + ParaColor + '"}' FROM WxTemplatePara WITH(NOLOCK) WHERE WxTemplateID = 15 ORDER BY ID
		UPDATE #T15 SET ParaValue = @ParaValue		
		UPDATE #T15 SET ParaValue = REPLACE(ParaValue, '#CompanyName#', CompanyName)	 
		UPDATE #T15 SET ParaValue = REPLACE(ParaValue, '#PaName', PaName)	
		UPDATE #T15 SET ParaValue = REPLACE(ParaValue, '#WebsiteName#', WebsiteName)
		UPDATE #T15 SET Url = 'http://m.' + ProvinceDomain + '/library/WechatOauthCpLogin?opid=' + OpenId + '&urlfile=/company/jm/interview'
		UPDATE #T15 SET	JsonMessage = '{"touser":"' + OpenId + '", "template_id":"' + WxTemplateNo + '", "url":"' + Url + '", "topcolor":"#FF0000", "data":{' + ParaValue + '}}'
		--更新wxmessagesend中的message
		UPDATE WxMessageSend2 
		SET MessageText = a.JsonMessage FROM #T15 a WHERE a.id = WxMessageSend2.id   
	END
	------面试通知答复提醒----

	------应聘邀请答复提醒---- 16
	SELECT a.*, b.[NO] AS WxTemplateNo, c.Name jobName, d.Name CompanyName, SPACE(1000) ParaValue, SPACE(200) Url, SPACE(1000) JsonMessage
	INTO #T16
	FROM #T1 a, WxTemplateNo b WITH(NOLOCK), Job c WITH(NOLOCK), CpMain d WITH(NOLOCK)
	WHERE a.Templatetype = 16 AND a.WxServiceNoID = b.WxServiceNoID AND b.WxTemplateId = 16 AND a.JobID = c.ID AND a.cpMainId = d.id
	IF @@RowCount > 0
	BEGIN
		--插入参数数据
		SELECT @ParaValue = ''
		SELECT @ParaValue = @ParaValue + CASE WHEN @ParaValue > '' THEN ', ' ELSE '' END + ' "' + ParaName + '":{    "value":"' + ParaValue + '",    "color":"' + ParaColor + '"}' FROM WxTemplatePara WITH(NOLOCK) WHERE WxTemplateID = 16 ORDER BY ID
		UPDATE #T16 SET ParaValue = @ParaValue		
		UPDATE #T16 SET ParaValue = REPLACE(ParaValue, '#CompanyName#', CompanyName)	 
		UPDATE #T16 SET ParaValue = REPLACE(ParaValue, '#PaName', PaName)	
		UPDATE #T16 SET ParaValue = REPLACE(ParaValue, '#WebsiteName#', WebsiteName)
		UPDATE #T16 SET Url = 'http://m.' + ProvinceDomain + '/library/WechatOauthCpLogin?opid=' + OpenId + '&urlfile=/company/jm/cvintention'
		UPDATE #T16 SET	JsonMessage = '{"touser":"' + OpenId + '", "template_id":"' + WxTemplateNo + '", "url":"' + Url + '", "topcolor":"#FF0000", "data":{' + ParaValue + '}}'
		--更新wxmessagesend中的message
		UPDATE WxMessageSend2 
		SET MessageText = a.JsonMessage FROM #T16 a WHERE a.id = WxMessageSend2.id   
	END
	------应聘邀请答复提醒----

	------文字在线沟通新消息提醒---- 17
	SELECT a.*, b.[NO] AS WxTemplateNo, d.Name CompanyName, SPACE(1000) ParaValue, SPACE(200) Url, SPACE(1000) JsonMessage
	INTO #T17
	FROM #T1 a, WxTemplateNo b WITH(NOLOCK), CpMain d WITH(NOLOCK)
	WHERE a.Templatetype = 17 AND a.WxServiceNoID = b.WxServiceNoID AND b.WxTemplateId = 17 AND a.cpMainId = d.id
	IF @@RowCount > 0
	BEGIN
		--插入参数数据
		SELECT @ParaValue = ''
		SELECT @ParaValue = @ParaValue + CASE WHEN @ParaValue > '' THEN ', ' ELSE '' END + ' "' + ParaName + '":{    "value":"' + ParaValue + '",    "color":"' + ParaColor + '"}' FROM WxTemplatePara WITH(NOLOCK) WHERE WxTemplateID = 17 ORDER BY ID
		UPDATE #T17 SET ParaValue = @ParaValue		
		UPDATE #T17 SET ParaValue = REPLACE(ParaValue, '#CompanyName#', CompanyName)	 
		UPDATE #T17 SET ParaValue = REPLACE(ParaValue, '#PaName', PaName)	
		UPDATE #T17 SET ParaValue = REPLACE(ParaValue, '#WebsiteName#', WebsiteName)
		UPDATE #T17 SET Url = 'http://m.' + ProvinceDomain + '/library/WechatOauthCpLogin?opid=' + OpenId + '&urlfile=/chatonline/cplist'
		UPDATE #T17 SET	JsonMessage = '{"touser":"' + OpenId + '", "template_id":"' + WxTemplateNo + '", "url":"' + Url + '", "topcolor":"#FF0000", "data":{' + ParaValue + '}}'
		--更新wxmessagesend中的message
		UPDATE WxMessageSend2 
		SET MessageText = a.JsonMessage FROM #T17 a WHERE a.id = WxMessageSend2.id   
	END
	------文字在线沟通新消息提醒----

	------职位过期提醒---- 18
	SELECT a.*, b.[NO] AS WxTemplateNo, c.Name jobName, d.Name CompanyName, SPACE(1000) ParaValue, SPACE(200) Url, SPACE(1000) JsonMessage
	INTO #T18
	FROM #T1 a, WxTemplateNo b WITH(NOLOCK), Job c WITH(NOLOCK), CpMain d WITH(NOLOCK)
	WHERE a.Templatetype = 18 AND a.WxServiceNoID = b.WxServiceNoID AND b.WxTemplateId = 18 AND a.JobID = c.ID AND a.cpMainId = d.id
	IF @@RowCount > 0
	BEGIN
		--插入参数数据
		SELECT @ParaValue = ''
		SELECT @ParaValue = @ParaValue + CASE WHEN @ParaValue > '' THEN ', ' ELSE '' END + ' "' + ParaName + '":{    "value":"' + ParaValue + '",    "color":"' + ParaColor + '"}' FROM WxTemplatePara WITH(NOLOCK) WHERE WxTemplateID = 18 ORDER BY ID
		UPDATE #T18 SET ParaValue = @ParaValue		
		UPDATE #T18 SET ParaValue = REPLACE(ParaValue, '#CompanyName#', CompanyName)	 
		UPDATE #T18 SET ParaValue = REPLACE(ParaValue, '#JobName', jobName)	
		UPDATE #T18 SET ParaValue = REPLACE(ParaValue, '#WebsiteName#', WebsiteName)
		UPDATE #T18 SET Url = 'http://m.' + ProvinceDomain + '/library/WechatOauthCpLogin?opid=' + OpenId + '&urlfile=/company/job/jobissue'
		UPDATE #T18 SET	JsonMessage = '{"touser":"' + OpenId + '", "template_id":"' + WxTemplateNo + '", "url":"' + Url + '", "topcolor":"#FF0000", "data":{' + ParaValue + '}}'
		--更新wxmessagesend中的message
		UPDATE WxMessageSend2 
		SET MessageText = a.JsonMessage FROM #T18 a WHERE a.id = WxMessageSend2.id   
	END
	------职位过期提醒----

	------营业执照审核结果提醒---- 19
	SELECT a.*, b.[NO] AS WxTemplateNo, d.HasLicence, d.Name CompanyName, SPACE(1000) ParaValue, SPACE(200) Url, SPACE(1000) JsonMessage
	INTO #T19
	FROM #T1 a, WxTemplateNo b WITH(NOLOCK), CpMain d WITH(NOLOCK)
	WHERE a.Templatetype = 19 AND a.WxServiceNoID = b.WxServiceNoID AND b.WxTemplateId = 19 AND a.cpMainId = d.id
	IF @@RowCount > 0
	BEGIN
		--插入参数数据
		SELECT @ParaValue = ''
		SELECT @ParaValue = @ParaValue + CASE WHEN @ParaValue > '' THEN ', ' ELSE '' END + ' "' + ParaName + '":{    "value":"' + ParaValue + '",    "color":"' + ParaColor + '"}' FROM WxTemplatePara WITH(NOLOCK) WHERE WxTemplateID = 19 ORDER BY ID
		UPDATE #T19 SET ParaValue = @ParaValue		
		UPDATE #T19 SET ParaValue = REPLACE(ParaValue, '#CompanyName#', CompanyName)	 
		UPDATE #T19 SET ParaValue = REPLACE(ParaValue, '#VerifyResult', CASE HasLicence WHEN 1 THEN '已通过' ELSE '未通过' END)	
		UPDATE #T19 SET ParaValue = REPLACE(ParaValue, '#WebsiteName#', WebsiteName)
		UPDATE #T19 SET Url = 'http://m.' + ProvinceDomain + '/library/WechatOauthCpLogin?opid=' + OpenId + '&urlfile=/company/cp/cplicence'
		UPDATE #T19 SET	JsonMessage = '{"touser":"' + OpenId + '", "template_id":"' + WxTemplateNo + '", "url":"' + Url + '", "topcolor":"#FF0000", "data":{' + ParaValue + '}}'
		--更新wxmessagesend中的message
		UPDATE WxMessageSend2 
		SET MessageText = a.JsonMessage FROM #T19 a WHERE a.id = WxMessageSend2.id   
	END
	------营业执照审核结果提醒----
	------企业精确匹配简历推送----
	SELECT a.*, b.[NO] AS WxTemplateNo, SPACE(1000) ParaValue, c.Name caName, SPACE(200) Url, SPACE(1000) JsonMessage,'精确匹配' PushFrequency
	INTO #T22
	FROM #T1 a, WxTemplateNo b WITH(NOLOCK), caMain c WITH(NOLOCK)
	WHERE a.Templatetype = 22 
	AND a.WxServiceNoID = b.WxServiceNoID 
	AND b.WxTemplateId = 22 
	AND c.ID = a.caMainID
	
	IF @@RowCount > 0
	BEGIN
		--插入参数数据
		SELECT @ParaValue = ''
		SELECT @ParaValue = @ParaValue + CASE WHEN @ParaValue > '' THEN ', ' ELSE '' END + ' "' + ParaName + '":{    "value":"' + ParaValue + '",    "color":"' + ParaColor + '"}' 
		FROM WxTemplatePara WITH(NOLOCK) WHERE WxTemplateID = 22 ORDER BY ID

		UPDATE #T22 SET ParaValue = @ParaValue		 
		UPDATE #T22 SET ParaValue = REPLACE(ParaValue, '#caName#', caName)
		UPDATE #T22 SET ParaValue = REPLACE(ParaValue, '#PushFrequency#', PushFrequency) 
		UPDATE #T22 SET ParaValue = REPLACE(ParaValue, '#WebsiteName#', WebsiteName)
		UPDATE #T22 SET Url = 'http://m.' + ProvinceDomain + '/library/WechatOauthCpLogin?opid=' + OpenId + '&urlfile=/company/cvsearch/Recommend?PushDate=' + CONVERT(VARCHAR(8), GETDATE(), 112)
		UPDATE #T22 SET	JsonMessage = '{"touser":"' + OpenId + '", "template_id":"' + WxTemplateNo + '", "url":"' + Url + '", "topcolor":"#000000", "data":{' + ParaValue + '}}'
		--更新wxmessagesend中的message
		UPDATE WxMessageSend2 
		SET MessageText = a.JsonMessage FROM #T22 a WHERE a.id = WxMessageSend2.id   
	END
	------企业精确匹配简历推送结束----
	
	
	------招聘会审核通知开始-------23
	SELECT a.*, b.[NO] AS WxTemplateNo, c.CompanyName, d.Name RecruitmentName, 
	(CONVERT(varchar(2), datepart(mm,d.BeginDate))+'月'+CONVERT(varchar(2), datepart(dd,d.BeginDate))+'日（'+replace(datename(weekday,d.BeginDate),'星期','周')+')'+CONVERT(varchar(2), datepart(hh,d.BeginDate))+':'+RIGHT('0'+CONVERT(varchar(2), datepart(mi,d.BeginDate)),2)+
	'~'+CONVERT(varchar(2), datepart(hh,d.EndDate))+':'+RIGHT('0'+CONVERT(varchar(2), datepart(mi,d.EndDate)),2)) AS RecruitMentTime,(e.Name+ISNULL(f.Name,'')+ISNULL(d.address,'')) AS RecruitMentAddress, 
	c.DeskNo AS RecruitMentDeskNo, c.Status AS checkStatus,SPACE(20) RecruitMentVerifyResult, c.description AS RecruitMentRemark,
	SPACE(1000) ParaValue, SPACE(1000) JsonMessage
	INTO #T23
	FROM #T1 a 
	LEFT JOIN  WxTemplateNo b WITH(NOLOCK) 
	ON a.WxServiceNoID = b.WxServiceNoID 
	LEFT JOIN marketdb..rmcompany c WITH(NOLOCK) 
	ON a.MainTableId = c.id 
	LEFT JOIN wutongguodb..recruitmentSchool d WITH(NOLOCK) 
	ON  c.recruitmentId= d.id*-1 
	LEFT JOIN  wutongguodb..dcSchool e WITH(NOLOCK) 
	ON d.dcSchoolId = e.id  
	LEFT JOIN wutongguodb..dcSchoolArea f WITH(NOLOCK) 
	ON d.dcSchoolAreaId = f.Id
	WHERE a.Templatetype = 23  
	AND b.WxTemplateId = 23
	
	IF @@RowCount > 0
	BEGIN
		--插入参数数据
		UPDATE #T23
		SET ParaValue = 
			(
			(SELECT ' "' + ParaName + '":{    "value":"' + ParaValue + '",    "color":"' + ParaColor + '"}, ' 
			FROM WxTemplatePara WITH(NOLOCK) WHERE WxTemplateID = 23 AND ParaName = 'first') + 
			(SELECT ' "' + ParaName + '":{    "value":"' + ParaValue + '",    "color":"' + ParaColor + '"}, ' 
			FROM WxTemplatePara WITH(NOLOCK) WHERE WxTemplateID = 23 AND ParaName = 'keyword1')	 + 
			(SELECT ' "' + ParaName + '":{    "value":"' + ParaValue + '",    "color":"' + ParaColor + '"}, ' 
			FROM WxTemplatePara WITH(NOLOCK) WHERE WxTemplateID = 23 AND ParaName = 'keyword2') + 	 
			(SELECT ' "' + ParaName + '":{    "value":"' + ParaValue + '",    "color":"' + ParaColor + '"}, ' 
			FROM WxTemplatePara WITH(NOLOCK) WHERE WxTemplateID = 23 AND ParaName = 'keyword3')	 + 
			(SELECT ' "' + ParaName + '":{    "value":"' + ParaValue + '",    "color":"' + ParaColor + '"}, ' 
			FROM WxTemplatePara WITH(NOLOCK) WHERE WxTemplateID = 23 AND ParaName = 'keyword4') + 	 
			(SELECT ' "' + ParaName + '":{    "value":"' + ParaValue + '",    "color":"' + ParaColor + '"}, ' 
			FROM WxTemplatePara WITH(NOLOCK) WHERE WxTemplateID = 23 AND ParaName = 'keyword5') + 
			(SELECT ' "' + ParaName + '":{    "value":"' + ParaValue + '",    "color":"' + ParaColor + '"}' 
			FROM WxTemplatePara WITH(NOLOCK) WHERE WxTemplateID = 23 AND ParaName = 'remark')
			)

		UPDATE #T23 SET ParaValue = REPLACE(ParaValue, '#CompanyName#', CompanyName)
		UPDATE #T23 SET ParaValue = REPLACE(ParaValue, '#RecruitMentName#', RecruitmentName)
		UPDATE #T23 SET ParaValue = REPLACE(ParaValue, '#RecruitMentTime#', RecruitMentTime)
		UPDATE #T23 SET ParaValue = REPLACE(ParaValue, '#RecruitMentAddress#', RecruitMentAddress)
		UPDATE #T23 SET ParaValue = REPLACE(ParaValue, '#RecruitMentVerifyResult#', CASE WHEN checkStatus = 1 THEN '通过' ELSE '不通过'END)
		UPDATE #T23 SET ParaValue = REPLACE(ParaValue, '#RecruitMentDeskNo#', CASE WHEN checkStatus = 1 THEN CASE WHEN ISNULL(RecruitMentDeskNo,'')='' THEN '待分配' ELSE  RecruitMentDeskNo END ELSE '不分配' END)	
		UPDATE #T23 SET ParaValue = REPLACE(ParaValue, '#RecruitMentRemark#', CASE WHEN checkStatus = 1 THEN CASE WHEN ISNULL(RecruitMentRemark,'')='' THEN '请准时到场，如不能到场参加，请提前3天告知校方联系人' ELSE ISNULL(RecruitMentRemark,'')+'。请准时到场，如不能到场参加，请提前3天告知校方联系人' END ELSE '原因：'+ISNULL(RecruitMentRemark,'') END)
		--UPDATE #T23 SET Url = 'http://m.' + ProvinceDomain + '/library/WechatOauthPaLogin?opid=' + OpenId + '&urlfile=/personal/jm/JobApplyList'
		UPDATE #T23 SET	JsonMessage = '{"touser":"' + OpenId + '", "template_id":"' + WxTemplateNo + '", "url":"", "topcolor":"#FF0000", "data":{' + ParaValue + '}}'
		--更新wxmessagesend中的message
		UPDATE WxMessageSend2 
		SET MessageText = a.JsonMessage FROM #T23 a WHERE a.id = WxMessageSend2.id
	END
	------招聘会审核通知结束--------	
	
	------企业邀请个人测评开始--------
	SELECT a.*, b.[NO] AS WxTemplateNo,e.Name AssessTypeName,e.NeedTime,c.EndDate, d.Name CompanyName, SPACE(1000) ParaValue, SPACE(200) Url, SPACE(1000) JsonMessage
	INTO #T24
	FROM #T1 a, WxTemplateNo b WITH(NOLOCK), AssessCpInvite c WITH(NOLOCK), CpMain d WITH(NOLOCK),AssessType e WITH(NOLOCK)
	WHERE a.Templatetype = 24 
	AND a.WxServiceNoID = b.WxServiceNoID 
	AND b.WxTemplateId = 24 
	AND a.MainTableId = c.ID 
	AND a.cpMainId = d.id
	AND c.AssessTypeID = e.ID

	IF @@RowCount > 0
	BEGIN
		--插入参数数据
		SELECT @ParaValue = ''
		SELECT @ParaValue = @ParaValue + CASE WHEN @ParaValue > '' THEN ', ' ELSE '' END + ' "' + ParaName + '":{    "value":"' + ParaValue + '",    "color":"' + ParaColor + '"}' FROM WxTemplatePara WITH(NOLOCK) WHERE WxTemplateID = 24 ORDER BY ID
		UPDATE #T24 SET ParaValue = @ParaValue		
		UPDATE #T24 SET ParaValue = REPLACE(ParaValue, '#CompanyName#', CompanyName)	 
		UPDATE #T24 SET ParaValue = REPLACE(ParaValue, '#PaName#', PaName)	
		UPDATE #T24 SET ParaValue = REPLACE(ParaValue, '#NeedTime#', CONVERT(VARCHAR,NeedTime) + '分')
		UPDATE #T24 SET ParaValue = REPLACE(ParaValue, '#EndDate#', CONVERT(VARCHAR(100), EndDate, 23))
		UPDATE #T24 SET Url = 'http://m.' + ProvinceDomain + '/library/WechatOauthPaLogin?opid=' + OpenId + '&urlfile=/personal/assess/cpinvittest'
		UPDATE #T24 SET	JsonMessage = '{"touser":"' + OpenId + '", "template_id":"' + WxTemplateNo + '", "url":"' + Url + '", "topcolor":"#FF0000", "data":{' + ParaValue + '}}'
		--更新wxmessagesend中的message
		UPDATE WxMessageSend2 
		SET MessageText = a.JsonMessage FROM #T24 a WHERE a.id = WxMessageSend2.id   
	END
	------企业邀请个人测评结束--------
	
	DELETE WxMessageSend2
	WHERE Id IN (SELECT MIN(Id) Id
		FROM WxMessageSend2 WITH(NOLOCK)
		--WHERE AddDate > GETDATE() - 0.1
		GROUP BY paMainId, MessageText
		HAVING COUNT(*) >1
	)

	UPDATE WxMessageSend2 SET MessageText = REPLACE(MessageText, '\', ' ')
	WHERE ErrorNumber = 0 AND SendDate IS NULL
END
GO

/****** Object:  StoredProcedure [dbo].[procWxMessageSendInsert]    Script Date: 2018/12/13 19:12:35 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

 
--#####################################################
--创建时间：2015.01.27
--创建人：Nick
--说明：插入消息发送表
--#####################################################
CREATE PROCEDURE [dbo].[procWxMessageSendInsert]
(
	@WxFansID INT,
	@cpMainID INT,
	@Message VARCHAR(1000),
	@Status INT,
	@MessageType INT,
	@WxTemplateNoID INT,
	@Remark VARCHAR(200)
)
AS
BEGIN
	INSERT INTO WxMessageSend (WxFansID,cpMainID,Message,SendDate,Status,MessageType,WxTemplateNoID,Remark)
	VALUES(@WxFansID,@cpMainID,@Message,GETDATE(),1,@MessageType,@WxTemplateNoID,@Remark)
	--修改最后接收消息时间
	UPDATE WxFans SET LastReceiveDate = GETDATE() WHERE ID = @WxFansID
END 
GO

/****** Object:  StoredProcedure [dbo].[procWxMessageTemplateBySiteNameSelect]    Script Date: 2018/12/13 19:12:35 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Mice 123>
-- Create date: <2015-4-15>
-- Description:	<根据站点名称查询当前站点是否有消息模板>
-- 修改：Harry2017-5-22
-- =============================================
CREATE PROCEDURE [dbo].[procWxMessageTemplateBySiteNameSelect]
(
	@UseType INT,
	@SiteName VARCHAR(100)
)
AS
SET NOCOUNT ON
BEGIN
	SET NOCOUNT ON;
	DECLARE @WxServiceNoId INT 
	DECLARE @WxNo VARCHAR(10)
	DECLARE @CapitalCity VARCHAR(10)
	SET @WxServiceNoId = 0
	SELECT @WxServiceNoId = a.ID,@CapitalCity =b.Abbr  FROM Maindb..wxServiceNo a,dcRegion b  WHERE a.Name = @SiteName AND a.ProvinceID=b.ParentID AND b.grade=2 AND b.id like'%01'

	IF @WxServiceNoId > 0
	BEGIN
		SET @WxNo = '%,' + CONVERT( VARCHAR(5), @WxServiceNoId ) + ',%'
		SELECT TOP 1 * 
		INTO #t
		FROM Maindb..wxMessageTemplate
		WHERE  UseType = @UseType AND Enddate > GETDATE() AND wxServiceNoId LIKE @WxNo
		ORDER BY ID DESC
		IF @UseType=1 
		BEGIN
			UPDATE #t SET MessageText = REPLACE(MessageText,'济南', @CapitalCity)
		END
		SELECT * FROM #t
		DROP TABLE #t
	END
	SET NOCOUNT OFF;
END
GO

/****** Object:  StoredProcedure [dbo].[procWxMessageTemplateDelete]    Script Date: 2018/12/13 19:12:36 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Mice 123>
-- Create date: <2015-4-1>
-- Description:	<删除微信自定义消息>
-- =============================================
CREATE PROCEDURE [dbo].[procWxMessageTemplateDelete] 
(
	@ID INT
)
AS
BEGIN
	SET NOCOUNT ON;
	DECLARE @MsgType AS INT
	SELECT @MsgType = MessageType FROM WxMessageTemplate WHERE ID = @ID
	IF @MsgType = 2 
	BEGIN
		DELETE FROM Maindb..WxMessageTemplateDetail WHERE WxMessageTemplateId = @ID
	END
	DELETE FROM Maindb..WxMessageTemplate WHERE ID = @ID
	SET NOCOUNT OFF;
END
GO

/****** Object:  StoredProcedure [dbo].[procWxMessageTemplateDetailDelete]    Script Date: 2018/12/13 19:12:36 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Mice 123>
-- Create date: <2015-4-1>
-- Description:	<删除一条微信自定义消息--图文消息>
-- =============================================
CREATE PROCEDURE [dbo].[procWxMessageTemplateDetailDelete]
(
	@ID INT
)
AS
BEGIN
	SET NOCOUNT ON;
	DELETE FROM Maindb..WxMessageTemplateDetail WHERE ID = @ID
END
GO

/****** Object:  StoredProcedure [dbo].[procWxMessageTemplateDetailUpdate]    Script Date: 2018/12/13 19:12:36 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Mice 123>
-- Create date: <2015-4-1>
-- Description:	<保存一条微信自定义消息--图文消息>
-- =============================================
CREATE PROCEDURE [dbo].[procWxMessageTemplateDetailUpdate] 
(
	@ID INT,
	@WxMessageTemplateID INT,
	@Title NVARCHAR(50),
	@Description NVARCHAR(50),
	@PicUrl VARCHAR(300),
	@Url VARCHAR(300),
	@Sort INT
)
AS
BEGIN
	SET NOCOUNT ON;
	IF @ID > 0 
	BEGIN
		UPDATE WxMessageTemplateDetail
		SET WxMessageTemplateID = @WxMessageTemplateID, Title = @Title, Description = @Description ,
			PicUrl = @PicUrl ,Url = @Url ,Sort = @Sort , AddDate = GETDATE()
		WHERE ID = @ID
	END
	ELSE
	BEGIN
		INSERT INTO Maindb..WxMessageTemplateDetail( WxMessageTemplateID,Title, Description  ,PicUrl,Url ,Sort,AddDate )
		VALUES ( @WxMessageTemplateID, @Title, @Description, @PicUrl, @Url, @Sort,GETDATE()  )
	END
	SET NOCOUNT OFF;
END
GO

/****** Object:  StoredProcedure [dbo].[procWxMessageTemplateUpdate]    Script Date: 2018/12/13 19:12:36 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Mice 123>
-- Create date: <2015-4-1>
-- Description:	<微信自定义消息模版修改>
-- 修改： 返回ID值
-- =============================================
CREATE PROCEDURE [dbo].[procWxMessageTemplateUpdate] 
(
	@ID INT,
	@wxServiceNoId VARCHAR(100),
	@MsgType INT,
	@UseType INT,
	@msgText TEXT,
	@endDate SMALLDATETIME,
	@addMan INT
)
AS
BEGIN
	SET NOCOUNT ON;
	IF @ID > 0 
	BEGIN
		UPDATE Maindb..WxMessageTemplate SET wxServiceNoId = @wxServiceNoId ,MessageType = @MsgType,
			UseType = @UseType, MessageText = @msgText,Enddate = @endDate, AddMan = @addMan, AddDate = getDate()
		WHERE id = @ID
	END
	ELSE
	BEGIN
		INSERT INTO Maindb..WxMessageTemplate(wxServiceNoId ,MessageType,UseType,MessageText,Enddate,AddMan,AddDate )
		VALUES ( @wxServiceNoId ,@MsgType,@UseType,@msgText,@endDate,@addMan,getDate() )
		SELECT @ID = @@IDENTITY
	END
	RETURN @ID
	SET NOCOUNT OFF;
END
GO

/****** Object:  StoredProcedure [dbo].[procWXQrImageByIDSelect]    Script Date: 2018/12/13 19:12:37 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2014.11.10
--创建人：NICK
--说明：根据id获取微信生成记录
--#####################################################
CREATE PROCEDURE [dbo].[procWXQrImageByIDSelect]
(
	@ID INT
)
AS
BEGIN
	SELECT * FROM WXQrImage WHERE id = @ID
END

GO

/****** Object:  StoredProcedure [dbo].[procWXQrImageByIDUpdate]    Script Date: 2018/12/13 19:12:37 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2014.11.10
--创建人：NICK
--说明：
--#####################################################
CREATE PROCEDURE [dbo].[procWXQrImageByIDUpdate]
(
	@ID INT,
	@Status INT,
	@OpenID VARCHAR(100)
)
AS
BEGIN
	UPDATE WXQrImage SET status=@Status,paMainID=(
		SELECT TOP 1 paMainID 
		FROM palogincontact WITH(NOLOCK) 
		WHERE ContactType=4 
		AND Openid=@OpenID 
		ORDER BY ID DESC)
	,openid=@OpenID 
	WHERE ID=@ID
END

GO

/****** Object:  StoredProcedure [dbo].[procWXQrImageByIDUpdateNew]    Script Date: 2018/12/13 19:12:37 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2016.4.7
--创建人：Lucifer
--说明：
--#####################################################
CREATE PROCEDURE [dbo].[procWXQrImageByIDUpdateNew]
(
	@ID INT,
	@Status INT,
	@OpenID VARCHAR(100),
	@ContactType INT
)
AS
BEGIN
	UPDATE WXQrImage SET status=@Status,paMainID=(
		SELECT TOP 1 paMainID 
		FROM palogincontact WITH(NOLOCK) 
		WHERE ContactType=@ContactType 
		AND Openid=@OpenID 
		ORDER BY ID DESC)
	,openid=@OpenID 
	WHERE ID=@ID
END
GO

/****** Object:  StoredProcedure [dbo].[ProcWXQrImageTicketUpdate]    Script Date: 2018/12/13 19:12:38 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2014.11.5
--创建人：John
--说明：更新/删除二维码记录
--#####################################################
CREATE PROCEDURE [dbo].[ProcWXQrImageTicketUpdate]
(
	@Ticket VARCHAR(150),
	@ID INT
)
AS
SET NOCOUNT ON
--INSERT INTO ProcLog SELECT 'ProcWXQrImageTicketUpdate', '', GETDATE()
--200tines one minute
BEGIN
	IF @Ticket <> ''
	BEGIN
		UPDATE WXQrImage SET Ticket = @Ticket WHERE ID = @ID 
	END
	ELSE
	BEGIN
		DELETE FROM WXQrImage WHERE ID=@ID
	END
END

GO

/****** Object:  StoredProcedure [dbo].[procWXQrImageUpdate]    Script Date: 2018/12/13 19:12:38 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2016.4.7
--创建人：Lucifer
--说明：修改 WXQrImage 状态
--#####################################################
CREATE PROCEDURE [dbo].[procWXQrImageUpdate]
(
	@ID INT,
	@Status INT,
	@OpenID VARCHAR(50),
	@ContactType INT
)
AS
SET NOCOUNT ON
BEGIN
	IF @ContactType > 0
	BEGIN
		UPDATE WXQrImage SET
			Status = @Status,
			OpenID = @OpenID,
			paMainID = (
				SELECT TOP 1 paMainID 
				FROM paLoginContact WITH(NOLOCK) 
				WHERE ContactType = @ContactType 
				AND OpenID = @OpenID 
				ORDER BY ID DESC
			)
		WHERE ID = @ID
	END
	ELSE
	BEGIN
		UPDATE WXQrImage SET
			Status = @Status,
			OpenID = @OpenID
		WHERE ID = @ID
	END
END
GO

/****** Object:  StoredProcedure [dbo].[procWxSendDataByTypeSelect]    Script Date: 2018/12/13 19:12:38 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2015.01.26
--创建人：Nick
--说明：获取等待发送的消息
--修改：mice 123 2015-4-20 增加type=10（微信代替短息的消息）
--#####################################################
CREATE PROCEDURE [dbo].[procWxSendDataByTypeSelect]
(
	@Type INT   --1面试通知 , 2企业给求职者发送应聘邀请, 3 企业收藏简历 4 企业查看简历 5 企业下载简历
				-- 6企业答复求职者简历  7企业留言 8简历审核不通过 9 照片审核不通过
)
AS
BEGIN
	DECLARE @StartTime DATETIME, @EndTime DATETIME
	SELECT @StartTime = DATEADD(ms, 0, DATEADD(dd, DATEDIFF(dd, 0, GETDATE()), 0))
	SELECT @EndTime = DATEADD(ms, -3, DATEADD(dd, DATEDIFF(dd, -1, GETDATE()), 0))

	IF @Type = 1 --面试通知
	BEGIN
		SELECT * INTO #1 FROM ExInterView WHERE ID > (SELECT MaxID FROM WxMax WHERE TableName='exinterview')
		SELECT a.JobID, a.CvMainID, a.InterviewDate, a.InterViewPlace, a.LinkMan, a.Telephone, a.Remark, b.Name AS JobName, 
			f.Name AS PaName, b.CpMainID, e.Name AS CpName, d.WxServiceNoID, a.ID, g.ProvinceDomain, d.ID AS WxFansID, d.OpenID
		FROM #1 a WITH(NOLOCK), Job b WITH(NOLOCK), CvMain c WITH(NOLOCK), WxFans d WITH(NOLOCK), CpMain e WITH(NOLOCK), PaMain f WITH(NOLOCK), dcProvince g WITH(NOLOCK)
		WHERE a.Jobid = b.ID 
		AND a.CvmainID = c.ID 
		AND c.PaMainID = f.ID
		AND c.PaMainID = d.PaMainID 
		AND b.CpMainID = e.ID
		AND f.dcProvinceID = g.ID
		AND d.Status=2
		--更新WxMax表数据
		UPDATE WxMax SET MaxID = (SELECT MAX(ID) FROM Exinterview WITH(NOLOCK)), UpdateDate = GETDATE()
		WHERE TableName='exinterview' 
		RETURN
	END
	ELSE IF @Type = 2  --企业发送应聘邀请
	BEGIN
		SELECT * INTO #2 FROM caCvIntention WHERE ID > (SELECT MaxID FROM WxMax WHERE TableName='cacvintention')
		SELECT a.JobID, a.CvMainID, a.AddDate, b.Name AS JobName, d.OpenID, b.dcsalaryid, 
		f.Name AS PaName, b.CpMainID, e.Name AS CpName, d.WxServiceNoID, a.ID, g.ProvinceDomain, h.FullName, d.ID AS WxFansID
		FROM #2 a, Job b, CvMain c, WxFans d, CpMain e, PaMain  f, dcProvince g, dcRegion h
		WHERE a.Jobid = b.ID 
		AND a.CvmainID = c.ID 
		AND c.PaMainID = f.ID
		AND c.PaMainID = d.PaMainID 
		AND b.CpMainID = e.ID
		AND f.dcProvinceID = g.ID
		AND b.dcRegionID = h.ID
		AND d.Status=2 
		
		--更新WxMax表数据
		UPDATE WxMax SET MaxID = (SELECT MAX(ID) FROM CaCvIntention), UpdateDate = GETDATE()
		WHERE TableName='cacvintention'
		RETURN
	END
	ELSE IF @Type = 3  --企业收藏简历
	BEGIN
		SELECT * INTO #3 FROM caFavorate WHERE ID > (SELECT MaxID FROM WxMax WHERE TableName='cafavorate')
		SELECT a.JobID, a.CvMainID, a.AddDate, b.Name AS JobName, 
		f.Name AS PaName, b.CpMainID, e.Name AS CpName, d.WxServiceNoID, a.ID, g.ProvinceDomain, d.OpenID, d.ID AS WxFansID
		FROM #3 a, Job b, CvMain c, WxFans d, CpMain e, PaMain f, dcProvince g
		WHERE a.Jobid = b.ID 
		AND a.CvmainID = c.ID 
		AND c.PaMainID = f.ID
		AND c.PaMainID = d.PaMainID 
		AND b.CpMainID = e.ID
		AND f.dcProvinceID = g.ID
		AND d.Status=2 
		
		--更新WxMax表数据
		UPDATE WxMax SET MaxID = (SELECT MAX(ID) FROM caFavorate), UpdateDate = GETDATE()
		WHERE TableName='cafavorate'
		RETURN
	END
	ELSE IF @Type = 4  --企业查看简历
	BEGIN
		SELECT * INTO #4 FROM caCvViewlog
		WHERE AddDate > (SELECT MaxID FROM WxMax WHERE TableName='cacvviewlog')
		AND AddDate IN (SELECT MIN(AddDate) 
			FROM caCvViewlog 
			WHERE AddDate > @StartTime AND AddDate<@EndTime
			GROUP BY CaMainID)
		
		SELECT a.caMainID, a.CvMainID, a.AddDate, d.OpenID, 
		f.Name AS PaName, e.Name AS CpName, b.CpMainID, d.ID AS WxFunID, 0 AS IsDelete, d.WxServiceNoID, g.ProvinceDomain , d.ID AS WxFansID
		INTO #T2
		FROM #4 a, CaMain b, CvMain c, WxFans d, CpMain e, PaMain f, dcProvince g
		WHERE a.caMainID = b.ID 
		AND a.CvmainID = c.ID 
		AND c.PaMainID = f.ID
		AND c.PaMainID = d.PaMainID 
		AND b.CpMainID = e.ID
		AND f.dcProvinceID = g.ID
		AND d.Status=2 
			
		UPDATE a Set a.IsDelete = 1 
		FROM #T2 a, WxMessageSend b
		WHERE b.SendDate>@StartTime AND b.SendDate<@EndTime
		AND a.WxFunID = b.WxFansID
		AND a.cpMainID = b.cpMainID
		AND b.MessageType = 3
		AND b.WxTemplateNoID IN (SELECT ID FROM WxTemplateNo WHERE wxTemplateID = 5)
		
		DELETE FROM #T2 WHERE IsDelete = 1
		
		SELECT * FROM #T2
		
		--更新WxMax表数据
		UPDATE WxMax SET MaxID = (SELECT MAX(AddDate) FROM caFavorate), UpdateDate = GETDATE()
		WHERE TableName='cacvviewlog' 
		RETURN
	END	
	ELSE IF @Type = 5  --企业下载简历
	BEGIN
		SELECT * INTO #51 FROM caActiveLog WHERE ID > (SELECT MaxID FROM WxMax WHERE TableName='caactivelog')
		SELECT * INTO #52 FROM caDailyGiftLog WHERE AddDate > (SELECT MaxID FROM WxMax WHERE TableName='cadailygiftlog')

		SELECT a.cpMainID, a.CvMainID, a.AddDate, 
		e.Name AS PaName, b.Name AS CpName, b.ID AS CpMainID, d.WxServiceNoID, g.ProvinceDomain , d.OpenID, d.ID AS WxFansID
		FROM #51 a WITH(NOLOCK), CpMain b, CvMain c, WxFans d, PaMain e, dcProvince g
		WHERE a.cpMainID = b.ID 
		AND a.CvmainID = c.ID 
		AND c.PaMainID = e.ID
		AND e.dcProvinceID = g.ID
		AND c.PaMainID = d.PaMainID 
		AND d.Status=2
		UNION
		SELECT a.cpMainID, a.CvMainID, a.AddDate, 
		c.Name AS PaName, b.Name AS CpName, b.ID AS CpMainID, d.WxServiceNoID, g.ProvinceDomain , d.OpenID, d.ID AS WxFansID
		FROM #52 a, CpMain b, CvMain c, WxFans d, PaMain e, dcProvince g
		WHERE a.cpMainID = b.ID 
		AND a.CvmainID = c.ID 
		AND c.PaMainID = d.PaMainID 
		AND c.PaMainID = e.ID
		AND e.dcProvinceID = g.ID
		AND d.Status=2
		
		--更新WxMax表数据
		UPDATE WxMax SET MaxID = (SELECT MAX(ID) FROM caactivelog), UpdateDate = GETDATE()
		WHERE TableName='caactiveLog' 
		
		UPDATE WxMax SET MaxID = (SELECT MAX(AddDate) FROM cadailygiftlog), UpdateDate = GETDATE()
		WHERE TableName='cadailygiftlog' 
		RETURN
	END
	ELSE IF @Type = 6 --企业答复求职者简历
	BEGIN
		SELECT * INTO #6 FROM exJobApply WHERE ReplyDate > (SELECT MaxID FROM WxMax WHERE TableName='exjobapply')
		SELECT a.JobID, a.CvMainID, a.Reply, a.ReplyDate, a.IsPassed, b.Name AS JobName, a.AddDate, h.Telephone, h.Mobile, 
		f.Name AS PaName, b.CpMainID, e.Name AS CpName, d.WxServiceNoID, a.ID, g.ProvinceDomain, d.OpenID, d.ID AS WxFansID
		FROM #6 a, Job b, CvMain c, WxFans d, CpMain e, PaMain f, dcProvince g, caMain h
		WHERE a.Jobid = b.ID 
		AND a.CvmainID = c.ID 
		AND c.PaMainID = f.ID
		AND c.PaMainID = d.PaMainID 
		AND b.CpMainID = e.ID
		AND f.dcProvinceID = g.ID
		AND b.CaMainID = h.ID
		AND d.Status=2
		
		--更新WxMax表数据
		UPDATE WxMax 
		SET MaxID = (SELECT MAX(ReplyDate) FROM exJobApply), UpdateDate = GETDATE()
		WHERE TableName='exjobapply'
		RETURN
	END
	ELSE IF @Type = 7 --企业给求职者留言
	BEGIN
		SELECT * INTO #t7 FROM chatonline
		WHERE ID > (SELECT MaxID FROM WxMax WHERE TableName='chatonline') 
		AND ID IN (SELECT MIN(ID) 
			FROM chatonline 
			WHERE AddDate>@StartTime --AND AddDate<@EndTime
			GROUP BY CvMainID)

		SELECT ChatOnlineId id INTO #t71 FROM ChatOnlineLog
		WHERE ChatOnlineId IN(SELECT id FROM #t7)
		AND isviewed=0 AND sendertype=1
		AND AddDate < dateadd(minute, -2, getdate())

		DELETE #T7 WHERE ID NOT IN(SELECT ID FROM #T71)

		SELECT a.cvMainID, a.caMainID, a.AddDate, 
			f.Name AS PaName, b.CpMainID, e.Name AS CpName, d.ID AS WxFunID, 0 AS IsDelete, 
			d.WxServiceNoID, a.ID, g.ProvinceDomain, d.OpenID, d.ID AS WxFansID
		INTO #T
		FROM #t7 a, CaMain b, CvMain c, WxFans d, CpMain e, PaMain f, dcProvince g
		WHERE a.caMainID = b.ID 
		AND a.CvmainID = c.ID 
		AND c.PamainID = f.ID
		AND c.PaMainID = d.PaMainID 
		AND b.CpMainID = e.ID
		AND f.dcProvinceID = g.ID
		AND d.Status=2
		--AND e.ID NOT IN( SELECT CpMainID 
		--	FROM WxMessageSend 
		--	WHERE SendDate>@StartTime AND SendDate<@EndTime)
		
		UPDATE a Set a.IsDelete = 1 
		FROM #T a, WxMessageSend b
		WHERE b.SendDate>@StartTime AND b.SendDate<@EndTime
		AND a.WxFunID = b.WxFansID
		AND a.cpMainID = b.cpMainID
		AND b.MessageType = 3
		AND b.WxTemplateNoID IN (SELECT ID FROM WxTemplateNo WHERE wxTemplateID = 4)
		
		DELETE FROM #T WHERE IsDelete = 1
		
		SELECT * FROM #T
		
		--更新WxMax表数据
		UPDATE WxMax SET MaxID = (SELECT MAX(ID) FROM ChatOnline), UpdateDate = GETDATE()
		WHERE TableName='chatonline' 
		RETURN
	END
	ELSE IF @Type = 8 --简历审核不通过
	BEGIN
		SELECT * INTO #t8 FROM bsCvVerify WHERE ID > (SELECT MaxID FROM WxMax WHERE TableName='bscvverify') AND VerifyResult = 10
		SELECT a.cvMainID, c.Name AS PaName, d.WxServiceNoID, a.ID, g.ProvinceDomain, d.OpenID, c.Mobile, d.ID AS WxFansID, a.VerifyDate
		FROM #t8 a, CvMain b,PaMain c, WxFans d, dcProvince g
		WHERE a.cvMainID = b.ID 
		AND b.PaMainID = c.ID 
		AND b.PaMainID = d.PaMainID
		AND c.dcProvinceID = g.ID
		AND d.Status = 2
		
		--更新WxMax表数据
		UPDATE WxMax SET MaxID = (SELECT MAX(ID) FROM bsCvVerify), UpdateDate = GETDATE()
		WHERE TableName='bscvverify' 
		RETURN
	END
	ELSE IF @Type = 9 --照片审核不通过
	BEGIN
		--SELECT * INTO #t9 FROM PaPhoto WHERE CheckDate > (SELECT MaxID FROM WxMax WHERE TableName='paphoto')
		SELECT a.PaMainID, a.CheckDate, b.Name AS PaName, c.WxServiceNoID, g.ProvinceDomain, c.OpenID  , b.Mobile, c.ID AS WxFansID
		FROM PaPhoto a, PaMain b, WxFans c, dcProvince g
		WHERE a.PaMainID = b.ID
		AND b.HasPhoto = 2
		AND b.id = c.pamainid
		AND b.dcProvinceID = g.ID
		AND c.Status=2
		AND  CheckDate > (SELECT MaxID FROM WxMax WHERE TableName='paphoto')
		--更新WxMax表数据
		UPDATE WxMax SET MaxID = (SELECT MAX(CheckDate) FROM PaPhoto), UpdateDate = GETDATE()
		WHERE TableName='paphoto' 
		RETURN
	END
	ELSE IF @Type = 110 --代替短信的消息
	BEGIN
		SELECT  a.* , b.ID AS wxFansID, b.OpenID, b.PaMainID , b.WxServiceNoID , c.UserName, c.Name AS PaName , y.ProvinceDomain, y.WebsiteName
		FROM ShortDb..wxMessageTemp a, Maindb..WxFans b , Maindb..PaMain c, Maindb..wxServiceNo x , Maindb..dcProvince y 
		WHERE b.paMainID = a.paMainID AND c.id = a.paMainID AND b.WxServiceNoID = x.id AND x.ProvinceID = y.id
		RETURN
	END
	ELSE IF @Type = 12 --微简历消息
	BEGIN
		SELECT a.*, b.Name AS cvName, c.WxServiceNoID, c.id AS wxFansID
		FROM Shortdb..SmallCvNotify a
		LEFT JOIN Shortdb..SmallCv b ON b.id = a.SmallCvId
		LEFT JOIN Maindb..wxFans c ON c.OpenID = a.OpenID
		WHERE a.SendDate IS NULL
	END
END
GO

/****** Object:  StoredProcedure [dbo].[ProcWxServiceNoByProvinceIdSelect]    Script Date: 2018/12/13 19:12:39 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[ProcWxServiceNoByProvinceIdSelect]
(
	@ProvinceId INT
)
AS
BEGIN
	SELECT * FROM wxServiceNo WHERE ProvinceId = @ProvinceId
END
GO

/****** Object:  StoredProcedure [dbo].[procWxServiceNoByStatusSelect]    Script Date: 2018/12/13 19:12:39 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2015.01.26
--创建人：Nick
--说明：获取微信服务号数据
--#####################################################
CREATE PROCEDURE [dbo].[procWxServiceNoByStatusSelect]
(
	@Status INT
)
AS
BEGIN
	IF @Status = 0
	BEGIN
		SELECT * FROM WxServiceNo WITH(NOLOCK)
	END
	ELSE
	BEGIN
		SELECT * FROM WxServiceNo WITH(NOLOCK) WHERE Status = @Status
	END
END 
GO

/****** Object:  StoredProcedure [dbo].[procWxShareByOpenIDSelect]    Script Date: 2018/12/13 19:12:39 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO



--2016-2-17 nick
--判断是否领取过红包
create PROCEDURE [dbo].[procWxShareByOpenIDSelect]
(
	@OpenID VARCHAR(50),
	@TypeID INT
)
AS
BEGIN
	SELECT * FROM wxShare WITH(NOLOCK)
	WHERE OpenID = @OpenID
	AND TypeID = @TypeID
	AND ReceiveDate IS NOT NULL
END
GO

/****** Object:  StoredProcedure [dbo].[procWxShareInsert]    Script Date: 2018/12/13 19:12:39 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--2016-2-17 nick
--微信分享
CREATE PROCEDURE [dbo].[procWxShareInsert]
(
	@OpenID VARCHAR(50),
	@TypeID INT, --1红包
	@SiteUrl VARCHAR(200)
)
AS
BEGIN
	DECLARE @Return INT
	DECLARE @DateTmp DATETIME
	DECLARE @ValidNum INT
	SET @DateTmp = '2016-2-17'
	--是否分享过
	IF EXISTS(SELECT * FROM WxShare WITH(NOLOCK) WHERE OpenID = @OpenID AND TypeID = @TypeID)
	BEGIN
		--判断是否发送过照片
		IF NOT EXISTS(SELECT * FROM WxWish WITH(NOLOCK) WHERE OpenID = @OpenID AND AddDate > @DateTmp)	--不存在
		BEGIN
			SET @Return = 1		--请上传照片
			INSERT INTO wxPhotoMsg(OpenID,Context,AddDate) VALUES(@OpenID,'请上传照片',GETDATE())
		END
		--ELSE 
		--BEGIN
			--SELECT TOP 1 @ValidNum = IsValid 
			--FROM WxWish WITH(NOLOCK) 
			--WHERE OpenID = @OpenID 
			--AND AddDate > @DateTmp
			--ORDER BY CASE WHEN IsValid = 1 THEN 3 END DESC
			
			--IF @ValidNum = 2	--审核不通过
			--BEGIN
			--	SET @Return = 2 --您的照片审核不通过，重新上传照片
			--END
			--IF @ValidNum IS NULL OR @ValidNum = 0
			--BEGIN
			--	SET @Return = 3 --您已上传照片，请耐心等待审核哦~
			--END
		--END
	END
	ELSE 
	BEGIN
		INSERT INTO WxShare(OpenID,TypeID,AddDate) VALUES(@OpenID,@TypeID,GETDATE())
		--判断是否发送过照片
		IF NOT EXISTS(SELECT * FROM WxWish WITH(NOLOCK) WHERE OpenID = @OpenID AND AddDate > @DateTmp)	--不存在
		BEGIN
			SET @Return = 1		-- 请上传照片
			INSERT INTO wxPhotoMsg(OpenID,Context,AddDate) VALUES(@OpenID,'请上传照片',GETDATE())
		END
		ELSE 
		BEGIN
			SELECT TOP 1 @ValidNum = IsValid 
			FROM WxWish WITH(NOLOCK) 
			WHERE OpenID = @OpenID 
			AND AddDate > @DateTmp
			ORDER BY CASE WHEN IsValid = 1 THEN 3 END DESC

			--IF @ValidNum = 2	--审核不通过
			--BEGIN
			--	SET @Return = 2 --您的照片审核不通过，重新上传照片
			--END
			--ELSE IF @ValidNum IS NULL OR @ValidNum = 0
			--BEGIN
			--	SET @Return = 3 --您已上传照片，请耐心等待审核哦~
			--END
		    IF @ValidNum = 1
			BEGIN
				SET @Return = 2--提醒抢红包
				INSERT INTO wxPhotoMsg(OpenID,Context,AddDate) VALUES(@OpenID,'点击开始<a href='''+@SiteUrl+'&red=1''>领取红包</a>吧',GETDATE())
			END
		END
	END
	RETURN 0
END
GO

/****** Object:  StoredProcedure [dbo].[procWxShareUpdate]    Script Date: 2018/12/13 19:12:39 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--2016-2-17 nick
--领取微信红包
CREATE PROCEDURE [dbo].[procWxShareUpdate]
(
	@OpenID VARCHAR(50),
	@TypeID INT, --1红包
	@ReceivePrice DECIMAL(18,2),--红包金额
	@SiteUrl VARCHAR(200)
)
AS
BEGIN
	DECLARE @Return INT
	--判断是否符合领取红包的条件
	--判断照片是否上传
	IF NOT EXISTS (SELECT * FROM WxWish WITH(NOLOCK) WHERE OpenID = @OpenID AND IsValid = 1)
	BEGIN
		SET @Return = 2 --请上传照片
		--INSERT INTO wxPhotoMsg(OpenID,Context,AddDate) VALUES(@OpenID,'照片未审核或未上传照片',GETDATE())
	END
	ELSE IF NOT EXISTS(SELECT * FROM WxShare WITH(NOLOCK) WHERE OpenID = @OpenID AND TypeID = 1)
	BEGIN
		SET @Return = 3 --请分享朋友圈 
		--INSERT INTO wxPhotoMsg(OpenID,Context,AddDate) VALUES(@OpenID,'照片审核通过，<a href='''+@SiteUrl+'''>分享到朋友圈</a>领红包吧',GETDATE())
	END
	ELSE IF EXISTS(SELECT * FROM WxShare WITH(NOLOCK) WHERE OpenID = @OpenID AND TypeID = 1 AND ReceiveDate IS NOT NULL)
	BEGIN
	    SET @Return = 4 --已经领取过红包 
	END
	ELSE 
	BEGIN
		SET @Return = 1 --领取红包
		--UPDATE WxShare SET ReceivePrice = @ReceivePrice WHERE OpenID = @OpenID AND TypeID = @TypeID
		--INSERT INTO wxPhotoMsg(OpenID,Context,AddDate) VALUES(@OpenID,'点击开始<a href='''+@SiteUrl+'&red=1''>领取红包</a>吧',GETDATE())
	END
	RETURN @Return
END

GO

/****** Object:  StoredProcedure [dbo].[procWxSmallPrograminfoByPaMainIdUpdate]    Script Date: 2018/12/13 19:12:40 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


--微信小程序绑定个人账号id
--harry
--2018-3-7
CREATE PROCEDURE [dbo].[procWxSmallPrograminfoByPaMainIdUpdate]
(
    @paMainId INT,
    @thirdSessionId VARCHAR(200)    
)
AS
SET NOCOUNT ON
BEGIN 
    IF EXISTS(SELECT 'X' FROM wxSmallPrograminfo WITH(NOLOCK) WHERE thirdSessionId = @thirdSessionId)
    BEGIN
        UPDATE wxSmallPrograminfo 
        SET paMainId = @paMainId 
        WHERE thirdSessionId= @thirdSessionId 
	 
	--更新unionid
	UPDATE wxFans
    	SET unionid= (SELECT unionid FROM wxSmallPrograminfo  WHERE thirdSessionId= @thirdSessionId )
    	WHERE paMainId = @paMainId
        
    END
    ELSE
    BEGIN
        --多设备登录导致thirdsessionid丢失，此时根据pamainid进行绑定thirdsession
        IF EXISTS(SELECT 'X' FROM wxSmallPrograminfo WITH(NOLOCK) WHERE paMainId = @paMainId)
        BEGIN
            UPDATE wxSmallPrograminfo 
            SET thirdSessionId= @thirdSessionId 
            WHERE paMainId = @paMainId 
	    --更新unionid
	    UPDATE wxFans
    	    SET unionid= (SELECT unionid FROM wxSmallPrograminfo  WHERE thirdSessionId= @thirdSessionId )
    	    WHERE paMainId = @paMainId
        END
        ELSE
        BEGIN
            --多设备，但从来未登录的情况，插入一条
            INSERT INTO wxSmallPrograminfo(thirdSessionId,paMainId,adddate,sessionid)
    VALUES(@thirdSessionId,@paMainId,GETDATE(),'')

        END
    END
END
SET NOCOUNT OFF
GO

/****** Object:  StoredProcedure [dbo].[procwxSmallPrograminfoInsert]    Script Date: 2018/12/13 19:12:40 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--微信小程序插入openid,sessionId
--harry 2017-7-18
--harry 2018-3-7
CREATE PROCEDURE [dbo].[procwxSmallPrograminfoInsert]
(
    @thirdSessionId VARCHAR(200),
    @openId VARCHAR(50),
    @sessionId VARCHAR(50),
    @unionId VARCHAR(50)
)
AS
SET NOCOUNT ON
BEGIN
    DECLARE @paMainId INT 
    SELECT TOP 1 @paMainId=pamainId FROM wxFans WITH(NOLOCK)
    WHERE UnionId = @unionId 
    ORDER BY ID DESC
    
    
    IF NOT EXISTS(SELECT 'x' FROM paMain WITH(NOLOCK) WHERE id = @paMainId) 
    BEGIN
        SET @paMainId=null
    END 
        IF EXISTS(SELECT 'X' FROM wxSmallPrograminfo WITH(NOLOCK) WHERE openId = @openId)
            UPDATE wxSmallPrograminfo
            SET thirdSessionId=@thirdSessionId,
                paMainId = @paMainId,
                sessionId = @sessionId,
                Adddate = GETDATE(),
                unionId = @unionId
            WHERE openId = @openId
	  
        ELSE
            INSERT INTO wxSmallPrograminfo(thirdSessionId,openId,sessionId,paMainId,unionId,adddate)
            VALUES(@thirdSessionId, @openId, @sessionId, @paMainId,@unionId, GETDATE())
	IF @paMainId != null
	    UPDATE wxFans
	    SET unionid= @unionId
	    WHERE paMainId = @paMainId
END
SET NOCOUNT OFF 
GO

/****** Object:  StoredProcedure [dbo].[procwxSmallPrograminfoSelect]    Script Date: 2018/12/13 19:12:40 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


--微信小程序根据thirdsessionid获取用户信息
--获取信息的同时更新一下关联的pamainid
--harry 2017-7-19
CREATE PROCEDURE [dbo].[procwxSmallPrograminfoSelect]
(
	@thirdSessionId VARCHAR(200) 
)
AS
SET NOCOUNT ON
BEGIN
	DECLARE @paMainId INT
	DECLARE @tmppaMainId INT
	DECLARE @unionId VARCHAR(50)
	
	SELECT @unionId = unionId, @tmppaMainId=pamainId
	FROM wxSmallPrograminfo WITH(NOLOCK)
	WHERE thirdSessionId = @thirdSessionId

	SELECT @paMainId=PaMainID
	FROM wxFans WITH(NOLOCK)
	WHERE unionId= @unionId
	
	IF EXISTS(SELECT 'x' FROM paMain WITH(NOLOCK) WHERE id = @paMainId) 
	BEGIN
		UPDATE wxSmallPrograminfo 
		SET pamainId = @paMainId,
		unionId = @unionId
		WHERE thirdSessionId = @thirdSessionId 
	END
	ELSE IF EXISTS(SELECT 'x' FROM paMain WITH(NOLOCK) WHERE id = @tmppaMainId) 
	BEGIN
		UPDATE wxSmallPrograminfo 
		SET  unionId = @unionId
		WHERE thirdSessionId = @thirdSessionId 
	END
	ELSE 
	BEGIN
		UPDATE wxSmallPrograminfo 
		SET  unionId = @unionId, pamainId =null
		WHERE thirdSessionId = @thirdSessionId 
	END

	SELECT a.*
	FROM wxSmallPrograminfo a WITH(NOLOCK)  
	WHERE a.thirdSessionId = @thirdSessionId
END
SET NOCOUNT OFF 
GO

/****** Object:  StoredProcedure [dbo].[procwxSmallPrograminfoUpdate]    Script Date: 2018/12/13 19:12:41 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--微信小程序更新pamainid与unionid
--harry 2017-7-19
CREATE PROCEDURE [dbo].[procwxSmallPrograminfoUpdate]
(
	@thirdSessionId VARCHAR(200),
	@unionId VARCHAR(50),
	@openId VARCHAR(50) 
)
AS
SET NOCOUNT ON
BEGIN
	DECLARE @paMainId INT

	SELECT @paMainId=PaMainID
	FROM wxFans WITH(NOLOCK)
	WHERE unionId = @unionId

	IF ISNULL(@paMainId,0)>0
	BEGIN
		UPDATE wxSmallPrograminfo 
		SET pamainId = @paMainId,
		unionId = @unionId
		WHERE thirdSessionId = @thirdSessionId
		AND openId = @openId
	END
	ELSE
	BEGIN
		UPDATE wxSmallPrograminfo 
		SET unionId = @unionId
		WHERE thirdSessionId = @thirdSessionId
		AND openId = @openId
	END
	SELECT @paMainId AS paMainId
END
SET NOCOUNT OFF
GO

/****** Object:  StoredProcedure [dbo].[procWxTemplateByIDSelect]    Script Date: 2018/12/13 19:12:41 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2015.01.26
--创建人：Nick
--说明：获取微信模板信息
--#####################################################
CREATE PROCEDURE [dbo].[procWxTemplateByIDSelect]
(
	@TemplateID INT
)
AS
BEGIN
	SELECT * FROM WxTemplate WHERE ID  = @TemplateID
	SELECT * FROM WxTemplatePara WHERE WxTemplateID = @TemplateID
END 
GO

/****** Object:  StoredProcedure [dbo].[procWxTemplateNoByWxTemplateIDSelect]    Script Date: 2018/12/13 19:12:42 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2015.01.26
--创建人：Nick
--说明：获取微信模板编号信息
--#####################################################
CREATE PROCEDURE [dbo].[procWxTemplateNoByWxTemplateIDSelect]
(
	@TemplateID INT,
	@WxServiceNoID INT
)
AS
BEGIN
	IF @WxServiceNoID <> 0
	BEGIN
		SELECT * FROM WxTemplateNo WHERE WxTemplateID = @TemplateID AND WxServiceNoID = @WxServiceNoID
	END
	ELSE
	BEGIN
		SELECT * FROM WxTemplateNo WHERE WxTemplateID = @TemplateID 
	END
END 
GO

/****** Object:  StoredProcedure [dbo].[ProcZipPlaceSelect]    Script Date: 2018/12/13 19:12:42 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


--#####################################################
--创建时间：2014.10.31
--创建人：John
--说明：获取邮编所在地
--#####################################################
CREATE PROCEDURE [dbo].[ProcZipPlaceSelect]
(
	@Zip VARCHAR(6)
)
AS
BEGIN
	SELECT Top 1 * FROM dcZip WHERE Zip <= @Zip ORDER BY ZIP DESC
END

GO

/****** Object:  StoredProcedure [dbo].[prodcIndustryCategoryByCvMainIDSelect]    Script Date: 2018/12/13 19:12:42 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2014.10.31
--创建人：Nick
--说明：获取行业的类别匹配度
--#####################################################
CREATE PROCEDURE [dbo].[prodcIndustryCategoryByCvMainIDSelect]
(
	@CvMainID VARCHAR(20)
)
AS
BEGIN TRY
	SELECT STUFF((SELECT ',c'+LTRIM(b.CateGoryId) 
	FROM cvIndustry a WITH(NOLOCK),dcIndustryCategory b WITH(NOLOCK) 
	WHERE a.dcIndustryid = b.dcIndustryid 
	AND cvMainid = @CvMainID FOR XML PATH('')),1,1,'') cvIndustryCategory
END TRY
BEGIN CATCH
	RETURN 0
END CATCH

GO

/****** Object:  StoredProcedure [dbo].[proDoubanMailByIDUpdate]    Script Date: 2018/12/13 19:12:42 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2014.11.03
--创建人：Nick
--说明：修改豆瓣的访问状态
--#####################################################
CREATE PROCEDURE [dbo].[proDoubanMailByIDUpdate]
(
	@ID INT
)
AS
BEGIN TRY
	UPDATE doubanmail SET isclick=1 WHERE id = @ID
	RETURN 1
END TRY
BEGIN CATCH
	RETURN 0
END CATCH

GO

/****** Object:  StoredProcedure [dbo].[proFpHomepageImageByProvinceIDSelect]    Script Date: 2018/12/13 19:12:43 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2014.11.03
--创建人：Nick
--说明：校园招聘的头条图片
--#####################################################
CREATE PROCEDURE [dbo].[proFpHomepageImageByProvinceIDSelect]
(
	@ProvinceID INT,
	@ImgType INT
)
AS
BEGIN TRY
	SELECT TOP 1 imagefile,imagetype,alt 
	FROM fpHomepageImage WITH(NOLOCK) 
	WHERE dcprovinceid=@ProvinceID 
	AND imagetype=@ImgType 
	ORDER BY AddDate DESC
END TRY
BEGIN CATCH
	RETURN 0
END CATCH

GO

/****** Object:  StoredProcedure [dbo].[proJobByCaMainIDSELECT]    Script Date: 2018/12/13 19:12:43 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--根据微信推送内容获取职位id
--harry
--2016-11-21
CREATE PROCEDURE [dbo].[proJobByCaMainIDSELECT]
(
 @pushdate CHAR(8),
 @caMainid INT
)
AS
SET NOCOUNT ON
BEGIN
	SELECT TOP 1 id 
	FROM job  WITH(NOLOCK)
	WHERE (
	SELECT COUNT(1) FROM CaJobCvMatch  WITH(NOLOCK) WHERE jobid=job.id AND Convert(char(8),adddate,112) = @pushdate
	) >0 
	AND camainid= @caMainid ORDER BY refreshdate
END
SET NOCOUNT OFF
GO

/****** Object:  StoredProcedure [dbo].[proLinkByCategorySelect]    Script Date: 2018/12/13 19:12:43 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2014.11.03
--创建人：Nick
--说明：取友情链接的数据(County IndexNew)
--#####################################################
CREATE PROCEDURE [dbo].[proLinkByCategorySelect]
(
	@ProvinceID INT,
	@Category INT
)
AS
BEGIN TRY
	SELECT TOP 50 * 
	FROM Link 
	WHERE Category = @Category 
	AND VersionId LIKE '' + ltrim(CONVERT(VARCHAR(6),@ProvinceID)) + '%' 
	ORDER BY Id DESC
END TRY
BEGIN CATCH
	RETURN 0
END CATCH

GO

/****** Object:  StoredProcedure [dbo].[proZhaopinRegionToOurIDSelect]    Script Date: 2018/12/13 19:12:43 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2014.10.31
--创建人：Nick
--说明：由地区名称获取地区ID
--#####################################################
CREATE PROCEDURE [dbo].[proZhaopinRegionToOurIDSelect]
(
	@RegionNameFull VARCHAR(20)
)
AS
BEGIN TRY
	SELECT dbo.ZhaopinRegionToOurID(@RegionNameFull) ID
END TRY
BEGIN CATCH
	RETURN 0
END CATCH

GO

/****** Object:  StoredProcedure [dbo].[pTemp]    Script Date: 2018/12/13 19:12:43 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO



CREATE PROCEDURE [dbo].[pTemp]
(
	@d DATETIME
)
AS
BEGIN
	DECLARE @ManagerUserId SMALLINT, @YearMonth INT, @Cnt INT, @BeginTime VARCHAR(50), @EndTime VARCHAR(50),@BeginDay VARCHAR(50),@EndDay VARCHAR(50)
	DECLARE @All NUMERIC(18, 2), @Local NUMERIC(18, 2),@PaRepeat INT,@CpRepeat INT,@PaMobileNumSum INT,@CpMobileNumSum INT

	IF DAY(@D) >= 26 
	BEGIN
		SET @YearMonth = YEAR(DATEADD(m, 1, @D)) * 100 + MONTH(DATEADD(m, 1, @D))
		SET @BeginTime = LTRIM(RTRIM(STR(YEAR(@D)))) + '-' + LTRIM(RTRIM(STR(MONTH(@D)))) + '-26 00:00:00'
		SET @EndTime = LTRIM(RTRIM(STR(YEAR(DATEADD(m, 1, @D))))) + '-' + LTRIM(RTRIM(STR(MONTH(DATEADD(m, 1, @D))))) + '-25 23:59:59'
		SET @BeginDay = LTRIM(RTRIM(STR(YEAR(@D)))) + LTRIM(RTRIM(STR(MONTH(@D)))) + '26'
		SET @EndDay = LTRIM(RTRIM(STR(YEAR(DATEADD(m, 1, @D))))) + LTRIM(RTRIM(STR(MONTH(DATEADD(m, 1, @D))))) + '25'
	END
	ELSE
	BEGIN
		SET @YearMonth = YEAR(@D)*100 + MONTH(@D)  
		SET @BeginTime = LTRIM(RTRIM(STR(YEAR(DATEADD(m, -1, @D))))) + '-' + LTRIM(RTRIM(STR(MONTH(DATEADD(m, -1, @D))))) + '-26 00:00:00'
		SET @EndTime = LTRIM(RTRIM(STR(YEAR(@D)))) + '-' + LTRIM(RTRIM(STR(MONTH(@D)))) + '-25 23:59:59'
		SET @BeginDay = LTRIM(RTRIM(STR(YEAR(DATEADD(m, -1, @D))))) + LTRIM(RTRIM(STR(MONTH(DATEADD(m, -1, @D))))) + '26'
		SET @EndDay = LTRIM(RTRIM(STR(YEAR(@D)))) + LTRIM(RTRIM(STR(MONTH(@D)))) + '25'
	END

	IF LEN(@BeginDay) <> 8
		SET @BeginDay = LEFT(@BeginDay,4) + '0' + RIGHT(@BeginDay,3)
	IF LEN(@EndDay) <> 8
		SET @EndDay = LEFT(@EndDay,4) + '0' + RIGHT(@EndDay,3)

	DECLARE ManagerUser_Record CURSOR FOR 
		SELECT Id FROM ManagerUser WITH(NOLOCK) WHERE DeptId IN(14, 15, 16, 22, 35)
		FOR READ ONLY

	OPEN ManagerUser_Record FETCH NEXT FROM ManagerUser_Record INTO @ManagerUserId
	WHILE @@FETCH_STATUS = 0
	BEGIN
		print(@YearMonth)
		print(@ManagerUserId)
	--	SELECT @Cnt = COUNT(1) FROM InfoAchieve WITH(NOLOCK) WHERE YearMonth = @YearMonth AND infoManager_Id = @ManagerUserId
	--	IF @Cnt = 0
	--		INSERT INTO InfoAchieve(YearMonth, infoManager_Id) VALUES(@YearMonth, @ManagerUserId)

		SELECT @PaMobileNumSum = ISNULL(SUM(mobilenum),0),@CpMobileNumSum = ISNULL(SUM(cpmobilenum),0)
		FROM info_datereport WITH(NOLOCK)
		WHERE countdate >= @BeginDay 
		AND countdate <= @EndDay
		AND infomanager_id = @ManagerUserId 
		
		SELECT @PaRepeat = COUNT(1)
		FROM bsmobilespread WITH(NOLOCK)
		WHERE AddDate BETWEEN @BeginTime AND @EndTime
		AND userType = 1
		AND addman = @ManagerUserId
		AND mobileno IN(
			SELECT a.mobile
			FROM paMain a WITH(NOLOCK),cvMain b WITH(NOLOCK)
			WHERE (registermode = 1 or registermode = 11)
			AND a.ID = b.paMainID
			AND b.valid > 0
			AND AddDate BETWEEN @BeginTime AND @EndTime)
		
		SELECT @CpRepeat = COUNT(1)
		FROM bsmobilespread WITH(NOLOCK)
		WHERE AddDate BETWEEN @BeginTime AND @EndTime
		AND addman = @ManagerUserId
		AND usertype = 0
		AND mobileno IN(
			SELECT mobile 
			FROM caMain a WITH(NOLOCK),cpMain b WITH(NOLOCK)
			WHERE a.cpMainID = b.ID
			AND b.HasLicence = 1
			AND AddDate BETWEEN @BeginTime AND @EndTime) 

		UPDATE InfoAchieve 
		SET paMobileNumSum = @PaMobileNumSum,
			cpMobileNumSum = @CpMobileNumSum,
			paRepeatNum = @PaRepeat,
			cpRepeatNum = @CpRepeat
		WHERE YearMonth = @YearMonth AND infoManager_Id = @ManagerUserId

		FETCH NEXT FROM ManagerUser_Record INTO @ManagerUserId
	END
	CLOSE ManagerUser_Record
	DEALLOCATE ManagerUser_Record
END













GO

/****** Object:  StoredProcedure [dbo].[rmCooperationRecruitmentByProvinceIDSelect]    Script Date: 2018/12/13 19:12:44 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


--#####################################################
--创建时间：2014.11.3
--创建人：John
--说明：随机获取既是合作的场馆又是合作的主办方的招聘会的场次,不显示自动生成的招聘会
--#####################################################
CREATE PROCEDURE [dbo].[rmCooperationRecruitmentByProvinceIDSelect]
(
	@ProvinceID VARCHAR(6),
	@intCount INT
)
AS
BEGIN
	SET @ProvinceID = @ProvinceID + '%'
	SELECT TOP (@intCount) * 
	FROM RecruitmentTmp 
	WHERE CityId LIKE @ProvinceID 
	ORDER BY RandNumber
END
GO

/****** Object:  StoredProcedure [dbo].[rmCpAttendByRmIDPaMainIDSelect]    Script Date: 2018/12/13 19:12:44 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2014.11.3
--创建人：John
--说明：返回招聘会的参会企业
--#####################################################
CREATE PROCEDURE [dbo].[rmCpAttendByRmIDPaMainIDSelect]
(
	@RecruitmentID INT,
	@paMainId INT
)
AS
BEGIN
	SELECT TOP 500 a.AddDate, a.StatusDate, a.cpMainId, a.RecruitmentID, b.Name, b.Address, c.ID, b.secondid,
		( 
			SELECT TOP 1 AddDate 
			FROM [MarketDb]..[RmPersonInvitation] 
			WHERE paMainId = @paMainId 
				AND caMainID=c.ID 
				AND RecruitmentID = a.RecruitmentID 
		) AS InviteDate 
	FROM [MarketDb]..[RmCompany] a, [MainDb]..[cpMain] b, [MainDb]..[caMain] c 
	WHERE a.cpMainId = b.id 
		AND a.Status <= 1 
		AND b.id = c.cpMainId 
		AND c.IsPause = 0 
		AND c.IsDelete = 0 
		AND c.AccountType = 1 
		AND a.RecruitmentID = @RecruitmentID 
	ORDER BY a.AddDate DESC
END

GO

/****** Object:  StoredProcedure [dbo].[rmCpInvitedByRmIDPaMainIDSelect]    Script Date: 2018/12/13 19:12:44 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2014.11.3
--创建人：John
--说明：返回招聘会的受邀企业
--#####################################################
CREATE PROCEDURE [dbo].[rmCpInvitedByRmIDPaMainIDSelect]
(
	@RecruitmentID INT,
	@paMainId INT
)
AS
BEGIN
	SELECT TOP 500 a.RecruitmentID, a.AddDate, b.Name AS JobName, y.name AS companyName, y.address, x.cpMainID, y.SecondId,  
		( 
			SELECT TOP 1 AddDate 
			FROM [MarketDb]..[RmPersonInvitation] 
			WHERE RecruitmentID = @RecruitmentID
				AND paMainId = @paMainId 
				AND caMainID = a.caMainID
		) AS myInviteDate 
	FROM [MarketDb]..[RmPersonInvitation] a, [MainDb]..[Job] b, [MainDb]..[caMain] x, [MainDb]..[cpMain] y
	WHERE a.JobID = b.id
		AND a.caMainID = x.id 
		AND x.cpMainID = y.id 
		AND RecruitmentID = @RecruitmentID 
		AND x.IsPause = 0 
		AND x.IsDelete = 0 
		AND x.AccountType = 1 
	ORDER BY a.AddDate DESC
END

GO

/****** Object:  StoredProcedure [dbo].[rmCpJobByCpMainIDSelect]    Script Date: 2018/12/13 19:12:44 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2014.11.3
--创建人：John
--说明：获取企业的招聘职位列表
--#####################################################
CREATE PROCEDURE [dbo].[rmCpJobByCpMainIDSelect]
(
	@cpMainID INT
)
AS
BEGIN
	SELECT a.ID, a.caMainID, a.Name AS jobName, b.Name AS companyName
	FROM [MainDb]..[Job] a, [MainDb]..[cpMain] b
	WHERE a.cpMainID = b.id AND a.IsDelete = 0 AND IssueEND > GETDATE() AND cpMainID = @cpMainID
	ORDER BY a.DisplayNo
END

GO

/****** Object:  StoredProcedure [dbo].[rmCpViewLogByRmIDPaMainIDSelect]    Script Date: 2018/12/13 19:12:45 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2014.11.3
--创建人：John
--说明：返回招聘会的企业浏览记录
--#####################################################
CREATE PROCEDURE [dbo].[rmCpViewLogByRmIDPaMainIDSelect]
(
	@RecruitmentID INT,
	@paMainId INT
)
AS
BEGIN
	SELECT TOP 500 a.AddDate, a.cpMainId, a.RecruitmentID, b.Name, b.Address, c.ID, b.SecondId, 
		( 
			SELECT TOP 1 AddDate 
			FROM [MarketDb]..[RmPersonInvitation] 
			WHERE paMainId = @paMainId 
				AND caMainID=c.ID 
				AND RecruitmentID = a.RecruitmentID 
		) AS InviteDate 
	FROM [MarketDb]..[RmCpViewLog] a, [MainDb]..[cpMain] b,[MainDb]..[caMain] c 
	WHERE a.cpMainId = b.id 
		AND a.RecruitmentID = @RecruitmentID 
		AND b.id = c.cpMainId 
		AND c.IsPause = 0 
		AND c.IsDelete = 0 
		AND c.AccountType=1
	ORDER BY a.AddDate DESC
END

GO

/****** Object:  StoredProcedure [dbo].[rmExJobApplyInsert]    Script Date: 2018/12/13 19:12:45 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[rmExJobApplyInsert]
(
	@JobID INT,
	@cvMainID INT,
	@Recruitment INT,
	@paMainID INT
)
AS
INSERT INTO ProcLog SELECT 'rmExJobApplyInsert', @cvMainID, GETDATE()
BEGIN
	DECLARE @MaxID AS INT, @IsFilter AS BIT, @cpMainId INT
	SELECT @cpMainId = cpMainId FROM Job WITH(NOLOCK) WHERE Id = @JobId
	
	IF (SELECT COUNT(*)
		FROM exJobApply WITH(NOLOCK)
		WHERE JobID IN(SELECT id FROM Job WITH(NOLOCK)WHERE cpMainId = @cpMainId)
		AND AddDate > GETDATE() - 1
		AND recruitmentid > 0) >	1
		RETURN -1	

	SET @IsFilter = dbo.IsJobApplyFilter(@JobID, @cvMainID)
	BEGIN TRY
		/*
		IF EXISTS(SELECT * FROM exJobApply a,Job b
			WHERE a.cvMainID = @cvMainID 
			AND a.JobID = b.ID 
			AND a.AddDate > GETDATE()-1 
			AND b.cpMainID IN(SELECT cpMainID FROM Job WHERE ID = @JobID))
		BEGIN
			SET @MaxID = -1
		END
		ELSE
		*/
		BEGIN
			IF EXISTS(SELECT ID FROM cvMain WITH(NOLOCK) WHERE paMainID = @paMainID AND ID = @cvMainID)		--是否是有效简历
			BEGIN
				IF EXISTS(SELECT ID FROM ExJobApply WITH(NOLOCK)
						WHERE JobID=@JobID AND cvMainID = @cvMainID AND AddDate > GETDATE()-30)	--是否在30天申请过
					SET @MaxID = -1
				ELSE
				BEGIN
					IF EXISTS(SELECT ID FROM JOB WITH(NOLOCK) WHERE ID = @JobID AND Valid = 0)	--是否是有效职位
						SET @MaxID = 0
					ELSE
					BEGIN
						INSERT INTO ExJobApply(JobID, cvMainID, RecruitmentID, IsFilter)
						VALUES(@JobID, @cvMainID, @Recruitment, @IsFilter)

						SET @MaxID = @@IDENTITY
						UPDATE Job SET ApplyNumber = ApplyNumber + 1 WHERE ID = @JobID

						--Harry Begin
						DECLARE @wxFansId INT
						SELECT @wxFansId = id FROM wxFans WITH(NOLOCK) WHERE paMainId = @paMainId AND [Status] = 2
						IF @wxFansId>0
						BEGIN
							--插入到wxMessageSend表中(6. --企业答复求职者简历)
							INSERT WxMessageSend2(Templatetype, WxFansID, PaMainId, MainTableId, CpMainID, CvMainID, JobId, AddDate)
							SELECT 6, @wxFansId, @paMainId, @MaxID, @cpMainId, @cvMainID, @JobID, GETDATE()
						END
						--Harry End
					END
				END
			END
		END
	END TRY
	BEGIN cATCH
		GOTO ERR
	END CATCH
	RETURN @MaxID
ENd
ERR:
BEGIN
	RETURN -2
END













GO

/****** Object:  StoredProcedure [dbo].[rmMyBespeakListByPaMainIDSelect]    Script Date: 2018/12/13 19:12:46 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2014.11.3
--创建人：John
--说明：招聘会 我的预约列表
--修改：harry 2018-4-11
--增加校园招聘会 
--#####################################################
CREATE PROCEDURE [dbo].[rmMyBespeakListByPaMainIDSelect]
(
	@paMainId INT
)
AS
BEGIN
	CREATE TABLE #t
	(
		pamainId INT,
		recruitmentId INT,
		recruitmentName NVARCHAR(200),
		beginDate DATETIME,
		endDate DATETIME,
		PlaceName NVARCHAR(200),
		bmDate DATETIME,
		checkInDateTime DATETIME
	)
	/*SELECT TOP 500 a.paMainID, b.id, b.RecruitmentName, b.BeginDate, c.Description AS cityName, d.PlaceName,
		( SELECT COUNT(id) FROM [MarketDb]..[RmCompany] WHERE RecruitmentID = b.id AND [Status]<=1 ) AS cpNum, 
		( SELECT COUNT(id) FROM [MarketDb]..[RmPersonInvitation] WHERE RecruitmentID = b.id AND paMainID = @paMainID ) AS myInvitCpNum
	FROM [MarketDb]..[RmPerson] a, [MarketDb]..[Recruitment] b, [MainDb]..[dcRegion] c, [MarketDb]..[RmPlace] d
	WHERE a.RecruitmentID = b.id 
		AND b.CityID = c.id 
		AND b.RecruitmentPlaceId = d.id
		AND a.paMainID = @paMainID
	ORDER BY a.AddDate DESC*/
	
	INSERT INTO #t
	SELECT TOP 500 a.paMainID, b.id, b.RecruitmentName, b.BeginDate, b.EndDate, c.PlaceName, a.AddDate AS bmDate, a.checkInDateTime 
	FROM [MarketDb]..[RmPerson] a, [MarketDb]..[Recruitment] b, [MarketDb]..[RmPlace] c
	WHERE a.RecruitmentID = b.id  
		AND b.RecruitmentPlaceId = c.id
		AND a.paMainID = @paMainID
	ORDER BY a.AddDate DESC

	INSERT INTO #t
	SELECT TOP 500 a.paMainID, b.id*-1, b.Name, b.BeginDate, b.EndDate, (c.Name+ ISNULL(d.Name,'')) AS PlaceName, a.AddDate AS bmDate, a.checkInDateTime 
	FROM [MarketDb]..[RmPerson] a, [wutongguoDb]..[RecruitmentSchool] b LEFT JOIN wutongguodb..dcSchoolArea d 
	ON b.dcschoolAreaId = d.id ,wutongguodb..dcschool c
	WHERE a.RecruitmentID = (b.id*-1)   
		AND a.paMainID = @paMainID
		AND b.dcSchoolId = c.Id
	ORDER BY a.AddDate DESC

	SELECT TOP 500 * 
	FROM #t
	ORDER BY CASE WHEN bmDate is NULL THEN checkInDateTime  END  DESC
END

GO

/****** Object:  StoredProcedure [dbo].[rmMyInviteCpByRmIDPaMainIDSelect]    Script Date: 2018/12/13 19:12:46 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2014.11.3
--创建人：John
--说明：招聘会 我的邀请企业记录
--#####################################################
CREATE PROCEDURE [dbo].[rmMyInviteCpByRmIDPaMainIDSelect]
(
	@RecruitmentID INT,
	@paMainId INT
)
AS
BEGIN
	SELECT TOP 500 a.RecruitmentID, a.ReplyDate, a.AddDate, a.Status, a.JobID, b.Name AS JobName, x.cpMainID, y.name AS companyName, y.SecondId, b.SecondId enjobid,
		( SELECT TOP 1 DeskNo FROM [MarketDb]..[RmCompany] WHERE RecruitmentID = a.RecruitmentID AND cpMainID = x.cpMainID ) AS DeskNo 
	FROM [MarketDb]..[RmPersonInvitation] a, [MainDb]..[Job] b, [MainDb]..[caMain] x, [MainDb]..[cpMain] y
	WHERE a.caMainID = x.id 
		AND x.cpMainID = y.id 
		AND a.JobID = b.ID
		AND a.RecruitmentID = @RecruitmentID 
		AND a.paMainID = @paMainId 
		AND x.IsPause = 0 
		AND x.IsDelete = 0 
		AND x.AccountType = 1
	ORDER BY a.ReplyDate DESC
END

GO

/****** Object:  StoredProcedure [dbo].[rmMyReceivedInvitationByPaMainIDSelect]    Script Date: 2018/12/13 19:12:46 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2014.11.3
--创建人：John
--说明：招聘会 我收到的邀请
--#####################################################
CREATE PROCEDURE [dbo].[rmMyReceivedInvitationByPaMainIDSelect]
(
	@paMainId INT
)
AS
BEGIN
	SELECT TOP 500 b.IssueEnd JobEndDate,a.id, a.RecruitmentID, a.JobID, b.SecondId enjobid, b.Name AS JobName, c.linkman, c.Mobile, e.companyName, e.cpMainID, e.DeskNo,
		c.RecruitmentName, c.BeginDate, c.EndDate, d.PlaceName, d.Address, a.Description AS xdcl, a.AddDate, a.Status, a.ReplyDate ,f.secondid
	FROM [MarketDb]..[RmCompanyInvitation] a, [MainDb]..[Job] b, [MarketDb]..[Recruitment] c, [MarketDb]..[RmPlace] d, [MarketDb]..[RmCompany] e, maindb..cpmain f
	WHERE a.JobID = b.id 
		AND a.RecruitmentID = c.id 
		AND c.RecruitmentPlaceId = d.id 
		AND a.RecruitmentID = e.RecruitmentID 
		AND e.cpMainid = f.id 
		AND a.paMainID = @paMainID  
		AND a.caMainID = b.caMainID 
		AND e.cpMainID=b.cpMainID
	ORDER BY a.AddDate DESC
END

GO

/****** Object:  StoredProcedure [dbo].[rmMyReceivedInvitationNoViewByPaMainIDSelect]    Script Date: 2018/12/13 19:12:47 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2014.11.3
--创建人：John
--说明：招聘会 我收到的邀请还未查看的
--#####################################################
CREATE PROCEDURE [dbo].[rmMyReceivedInvitationNoViewByPaMainIDSelect]
(
	@paMainId INT
)
AS
BEGIN
	SELECT TOP 1 a.id, a.RecruitmentID, a.JobID, b.SecondId enjobid, b.Name AS JobName, c.linkman, c.Mobile, e.companyName, e.cpMainID, e.DeskNo,
		c.RecruitmentName, c.BeginDate, c.EndDate, d.PlaceName, d.Address, a.Description AS xdcl, a.AddDate, a.Status, a.ReplyDate, f.secondid
	FROM [MarketDb]..[RmCompanyInvitation] a, [MainDb]..[Job] b,[MarketDb]..[Recruitment] c, [MarketDb]..[RmPlace] d, [MarketDb]..[RmCompany] e, maindb..cpmain f
	WHERE a.JobID = b.id 
		AND a.RecruitmentID = c.id 
		AND c.RecruitmentPlaceId = d.id 
		AND a.RecruitmentID = e.RecruitmentID 
		AND e.cpMainid = f.id 
		AND a.paMainID = @paMainID  
		AND a.caMainID = b.caMainID 
		AND e.cpMainID = b.cpMainID
		AND a.ViewDate IS NULL 
		AND c.begindate > GETDATE()
	ORDER BY a.AddDate DESC
END

GO

/****** Object:  StoredProcedure [dbo].[rmPaFavorateSelect]    Script Date: 2018/12/13 19:12:47 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2014.11.3
--创建人：John
--说明：获取职位收藏夹列表
--#####################################################
CREATE PROCEDURE [dbo].[rmPaFavorateSelect]
(
	@StrWhere VARCHAR(500),
	@OrderBy VARCHAR(50)
)
AS
BEGIN
	DECLARE @SQL VARCHAR(2000)
	SET @SQL = 'SELECT a.ID,a.paMainID,a.JobID,a.AddDate,a.Remark,b.Name AS JobName,b.IssueDate,b.IssueEND,b.dcRegionID,b.IsDelete, b.caMainID, b.SecondId, 
		c.Name AS cpName,c.ID AS cpID,c.HasLicence,c.IsAgent, c.Membertype, b.dcSalaryID , d.Description AS SalaryCount ,
		ISNULL((SELECT IsOnline FROM caOnline WHERE caMainId =b.caMainID), 0) AS IsOnline
	FROM [MainDb]..[paFavorate] a WITH(NOLOCK) 
		Inner Join [MainDb]..[Job] b WITH(NOLOCK) ON a.JobID=b.ID 
		Inner Join [MainDb]..[cpMain] c WITH(NOLOCK) ON b.cpMainID=c.ID 
		Inner Join [MainDb]..[dcSalary] d WITH(NOLOCK) ON b.dcSalaryID = d.id
	WHERE '
	SET @SQL = @SQL + @StrWhere + ' ORDER BY ' + @OrderBy
	EXEC(@SQL)
END

GO

/****** Object:  StoredProcedure [dbo].[rmPaIsAttendRmSelect]    Script Date: 2018/12/13 19:12:47 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2014.11.3
--创建人：John
--说明：paMainID 是否参加该场招聘会
--#####################################################
CREATE PROCEDURE [dbo].[rmPaIsAttendRmSelect]
(
	@RecruitmentID INT,
	@paMainId INT
)
AS
BEGIN
	SELECT ID FROM [MarketDb]..[RmPerson] WHERE RecruitmentID = @RecruitmentID AND paMainID = @paMainID
END

GO

/****** Object:  StoredProcedure [dbo].[RmPaMainByMobileInsert]    Script Date: 2018/12/13 19:12:47 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[RmPaMainByMobileInsert]
(
	@UserName VARCHAR(50),
	@dcProvinceID SMALLINT,
	@Mobile VARCHAR(20),
	@SubSiteUrl VARCHAR(200)
)
AS
BEGIN
	--判断90天内该手机号有无认证过
	IF EXISTS(SELECT 'X' FROM marketdb..RmInvitationCode WHERE Mobile=@Mobile AND AddDate>GETDATE()-90)
	BEGIN
		INSERT INTO SmsMessageLog(SendMan,Mobile,Msg,MsgType,IsCat) VALUES
		(1,@Mobile,'您在90天内参加过简历认证，不能重复参加',199,0)
		RETURN
	END
	
	--生成邀请码
	DECLARE @Code VARCHAR(6)
	WHILE 1=1
	BEGIN
		SET @Code=CONVERT(VARCHAR(6),RIGHT(CAST(RAND()*1000000 AS INT),6))
		SET @Code=LEFT(@Code,6)
		IF LEN(@Code) = 5
			SET @Code='0'+@Code
		ELSE IF LEN(@Code) = 4
			SET @Code='00'+@Code
		ELSE IF LEN(@Code) = 3
			SET @Code='000'+@Code
		ELSE IF LEN(@Code) = 2
			SET @Code='0000'+@Code
		
		IF EXISTS(SELECT 'X' FROM marketdb..RmInvitationCode WHERE Code=@Code)
			CONTINUE
		ELSE
			BREAK
	END
	
	--生成paMainID
	DECLARE @paMainID INT
	EXEC @paMainID=pcPaMainInsert @UserName,'$2a$08$wCjRdWcKgup74i.L3sk6OOlCAQ/qAPmAWE4ZMzpJL7K85N0.x/WIu',@dcProvinceID,'校园简历短信注册',0,0
	IF @paMainID=-2
		SELECT @paMainID=ID,@UserName=UserName FROM paMain WHERE Email=@UserName
		
	--插入到RmInvitationCode
	DECLARE @MaxId INT
	INSERT INTO marketdb..RmInvitationCode(Mobile,RmProjectID,Code,paMainID) VALUES(@Mobile,1,@Code,@paMainID)
	SET @MaxId = @@IDENTITY
	
	--更改paMain的信息
	UPDATE paMain Set Mobile=@Mobile,Password='$2a$08$[REDACTED]' 
	WHERE ID=@paMainID
	
	--发送短信
	DECLARE @Msg VARCHAR(200)
	SET @Msg='用户名'+@UserName+'密码123456邀请码'+@Code+'。请登录'+@SubSiteUrl+'完善简历'
	INSERT INTO SmsMessageLog(SendMan,paMainId,Mobile,Msg,MsgType,IsCat) VALUES
		(1,@paMainID,@Mobile,@Msg,117,0)
END













GO

/****** Object:  StoredProcedure [dbo].[rmRecommendCvSelect]    Script Date: 2018/12/13 19:12:48 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[rmRecommendCvSelect]
(
	@RecruitmentID INT
)
AS
BEGIN
	SELECT a.ID cvMainID,d.*,a.Degree,a.dcMajorID,e.FullName AtPlace
	FROM cvMain a WITH(NOLOCK)
		INNER JOIN paMain d WITH(NOLOCK) ON a.paMainID=d.ID
		INNER JOIN marketdb..RmInvitationCode b WITH(NOLOCK) ON a.paMainID=b.paMainID AND b.Valid=1
		INNER JOIN marketdb..RmProject c WITH(NOLOCK) ON b.RmProjectID=c.ID
		INNER JOIN dcRegion e WITH(NOLOCK) ON d.LivePlace=e.ID
	WHERE c.RecruitmentID=@RecruitmentID AND a.Valid=1
END













GO

/****** Object:  StoredProcedure [dbo].[rmRecruitmentByCpMainIDSelect]    Script Date: 2018/12/13 19:12:48 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2014.10.30
--创建人：Nick
--说明：获取个人会员中心首页的招聘会的数据
--#####################################################
CREATE PROCEDURE [dbo].[rmRecruitmentByCpMainIDSelect]
(
	@ProvinceID VARCHAR(4),
	@cpMainID VARCHAR(20)
)
AS
BEGIN TRY
	SELECT TOP 6 a.ID,RecruitmentName,BeginDate,PlaceName ,
	( 
		SELECT TOP 1 ltrim(str(status))+'$$'+isnull(deskno,'test')+'$$'+isnull(CONVERT(varchar,StatusDate,120),'test') 
		FROM marketdb..RmCompany 
		WHERE RecruitmentID = a.Id 
		AND cpMainID = @cpMainID 
	) IsAttend  
	From marketdb..Recruitment a WITH(NOLOCK),marketdb..RmPlace b WITH(NOLOCK) 
	WHERE RecruitmentPlaceID=b.ID 
	AND CityID LIKE @ProvinceID+'%' 
	AND EndDate > GetDate() 
	AND IsPause=0
	ORDER BY IsCompanyTop DESC,orderby, a.BeginDate
END TRY
BEGIN CATCH
	RETURN 0
END CATCH
GO

/****** Object:  StoredProcedure [dbo].[rmRecruitmentByIDSelect]    Script Date: 2018/12/13 19:12:48 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2014.11.3
--创建人：John
--说明：通过招聘会id获取招聘会详细信息
--#####################################################
CREATE PROCEDURE [dbo].[rmRecruitmentByIDSelect]
(
	@RecruitmentID INT
)
AS
BEGIN
	SELECT a.*, c.PlaceName, c.[Address] ,b.[Description] City, c.MapbarID, c.Lng, c.Lat, c.BusLine, CreditRating,
	 'www.' + ProvinceDomain SiteUrl, d.ID ProvinceID, a.RecruitmentDeptId 
	 FROM Recruitment a, dcRegion b, RecruitmentPlace c ,dcProvince d, recruitmentdept e 
	 WHERE e.id = a.recruitmentdeptid 
		AND b.ID = c.dcRegionID 
		AND a.RecruitmentPlaceId = c.id 
		AND d.ID = LEFT(a.CityID,2) 
		AND a.ID = @RecruitmentID
END

GO

/****** Object:  StoredProcedure [dbo].[rmRecruitmentByIsSchoolUpdate]    Script Date: 2018/12/13 19:12:49 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[rmRecruitmentByIsSchoolUpdate]
(
	@ID INT,
	@IsSchool BIT
)
AS
SET NOCOUNT ON
UPDATE marketdb..Recruitment SET IsSchool = @IsSchool WHERE ID=@ID
SET NOCOUNT OFF
GO

/****** Object:  StoredProcedure [dbo].[rmRecruitmentByPlaceIDAndDateSelect]    Script Date: 2018/12/13 19:12:49 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2014.11.3
--创建人：John
--说明：判断当天招聘会是否重复
--#####################################################
CREATE PROCEDURE [dbo].[rmRecruitmentByPlaceIDAndDateSelect]
(
	@PlaceID INT,
	@rmDate1 VARCHAR(20),
	@rmDate2 VARCHAR(20)
)
AS
BEGIN
	SELECT * 
	FROM Recruitment WITH(NOLOCK)
	WHERE recruitmentplaceid = @PlaceID 
	AND enddate BETWEEN @rmDate1 AND @rmDate2
	AND EXISTS(SELECT 'x' FROM RecruitmentDept WITH(NOLOCK) WHERE id = Recruitment.RecruitmentDeptId)
END
GO

/****** Object:  StoredProcedure [dbo].[rmRecruitmentCpMainSelect]    Script Date: 2018/12/13 19:12:49 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[rmRecruitmentCpMainSelect]
(
	@RecruitmentID INT
)
AS
BEGIN
	select a.cpmainid,a.adddate,b.name,c.name caname,b.address,c.mobile,c.telephone from recruitmentcpmain a,cpmain b,camain c where a.cpmainid=b.id and b.id=c.cpmainid and c.AccountType=1 and RecruitmentID=@RecruitmentID ORDER BY a.AddDate DESC
END













GO

/****** Object:  StoredProcedure [dbo].[rmRecruitmentDelete]    Script Date: 2018/12/13 19:12:49 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2014.11.3
--创建人：John
--说明：删除招聘会信息
--#####################################################
CREATE PROCEDURE [dbo].[rmRecruitmentDelete]
(
	@strID INT,
	@strID2 INT,
	@rmID INT
)
AS
BEGIN
	DELETE FROM recruitment WHERE (id = @strID OR MainID = @strID2) AND recruitmentdeptid = @rmID
END

GO

/****** Object:  StoredProcedure [dbo].[RmRecruitmentDeptInsert]    Script Date: 2018/12/13 19:12:50 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[RmRecruitmentDeptInsert]
(
	@Username VARCHAR(20),
	@Password VARCHAR(20),
	@DeptName VARCHAR(100),
	@LinkMan VARCHAR(20),
	@Mobile VARCHAR(11),
	@Email VARCHAR(50),
	@QQ VARCHAR(10),
	@dcProvinceID SMALLINT
)
AS
BEGIN TRY
	SET @Username = dbo.TextTrim(@Username)
	SET @DeptName = dbo.TextTrim(@DeptName)
	SET @LinkMan = dbo.TextTrim(@LinkMan)
	SET @Mobile = dbo.TextTrim(@Mobile)
	SET @Email = dbo.TextTrim(@Email)
	SET @QQ = dbo.TextTrim(@QQ)
 
	IF EXISTS(SELECT 'X' FROM RecruitmentDept WITH(NOLOCK) WHERE Username = @Username)
		RETURN -2
	IF EXISTS(SELECT 'X' FROM RecruitmentDept WITH(NOLOCK) WHERE Email = @Email)
		RETURN -3
	IF EXISTS(SELECT 'X' FROM RecruitmentDept WITH(NOLOCK) WHERE Mobile = @Mobile)
		RETURN -4
	IF EXISTS(SELECT 'X' FROM RecruitmentDept WITH(NOLOCK) WHERE QQ = @QQ)
		RETURN -5
 
	DECLARE @MaxId AS INT
	INSERT INTO RecruitmentDept(dcProvinceID,Username, Password, DeptName, LinkMan, Mobile, Email, QQ)
			VALUES(@dcProvinceID, @Username, @Password, @DeptName, @LinkMan, @Mobile, @Email, @QQ)
	SET @MaxId = @@IDENTITY
	RETURN @MaxID
END TRY
BEGIN CATCH
	RETURN -1
END CATCH













GO

/****** Object:  StoredProcedure [dbo].[rmRecruitmentDeptIsExist]    Script Date: 2018/12/13 19:12:50 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[rmRecruitmentDeptIsExist]
(
	@Account VARCHAR(100),
	@Type TINYINT,
	@ID INT
)
AS
BEGIN
	IF @ID = 0
	BEGIN
		IF @Type = 1
		BEGIN
			IF EXISTS(SELECT ID FROM RecruitmentDept WITH(NOLOCK) WHERE Username = @Account)
				RETURN 1
			ELSE
				RETURN 0
		END
		IF @Type = 2
		BEGIN
			IF EXISTS(SELECT ID FROM RecruitmentDept WITH(NOLOCK) WHERE DeptName = @Account)
				RETURN 1
			ELSE
				RETURN 0
		END
		IF @Type = 3
		BEGIN
			IF EXISTS(SELECT ID FROM RecruitmentDept WITH(NOLOCK) WHERE Email = @Account)
				RETURN 1
			ELSE
				RETURN 0
		END
		IF @Type = 4
		BEGIN
			IF EXISTS(SELECT ID FROM RecruitmentDept WITH(NOLOCK) WHERE Mobile = @Account)
				RETURN 1
			ELSE
				RETURN 0
		END
		IF @Type = 5
		BEGIN
			IF EXISTS(SELECT ID FROM RecruitmentDept WITH(NOLOCK) WHERE QQ = @Account)
				RETURN 1
			ELSE
				RETURN 0
		END
	END
	ELSE
	BEGIN
		IF @Type = 1
		BEGIN
			IF EXISTS(SELECT ID FROM RecruitmentDept WITH(NOLOCK) WHERE Username = @Account AND ID <> @ID)
				RETURN 1
			ELSE
				RETURN 0
		END
		IF @Type = 2
		BEGIN
			IF EXISTS(SELECT ID FROM RecruitmentDept WITH(NOLOCK) WHERE DeptName = @Account AND ID <> @ID)
				RETURN 1
			ELSE
				RETURN 0
		END
		IF @Type = 3
		BEGIN
			IF EXISTS(SELECT ID FROM RecruitmentDept WITH(NOLOCK) WHERE Email = @Account AND ID <> @ID)
				RETURN 1
			ELSE
				RETURN 0
		END
		IF @Type = 4
		BEGIN
			IF EXISTS(SELECT ID FROM RecruitmentDept WITH(NOLOCK) WHERE Mobile = @Account AND ID <> @ID)
				RETURN 1
			ELSE
				RETURN 0
		END
		IF @Type = 5
		BEGIN
			IF EXISTS(SELECT ID FROM RecruitmentDept WITH(NOLOCK) WHERE QQ = @Account AND ID <> @ID)
				RETURN 1
			ELSE
				RETURN 0
		END
	END
END













GO

/****** Object:  StoredProcedure [dbo].[rmRecruitmentDeptPasswordUpdate]    Script Date: 2018/12/13 19:12:50 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[rmRecruitmentDeptPasswordUpdate]
(
	@ID INT,
	@Password VARCHAR(20),
	@Old VARCHAR(20)
)
AS
BEGIN TRY
	IF EXISTS(SELECT 'X' FROM rmDept WHERE ID=@ID)
	BEGIN
		DECLARE @OldPwd AS VARCHAR(20)
		SELECT @OldPwd=Password FROM rmDept WHERE ID=@ID
		IF @Old=@OldPwd
		BEGIN
			UPDATE rmDept SET Password=[REDACTED] WHERE ID=@ID
			RETURN 1
		END
		ELSE
			RETURN -1
	END
	ELSE
		RETURN -2
END TRY
BEGIN CATCH
	RETURN 0
END CATCH










GO

/****** Object:  StoredProcedure [dbo].[rmRecruitmentDeptSelectByID]    Script Date: 2018/12/13 19:12:51 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[rmRecruitmentDeptSelectByID]
(
	@ID INT
)
AS
BEGIN
	SELECT * FROM RecruitmentDept WHERE ID=@ID
END













GO

/****** Object:  StoredProcedure [dbo].[rmRecruitmentDeptSelectByLogin]    Script Date: 2018/12/13 19:12:51 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[rmRecruitmentDeptSelectByLogin]
(
	@Username VARCHAR(20),
	@Password VARCHAR(20)
)
AS
BEGIN
	SELECT * FROM RecruitmentDept WHERE Username=@Username AND Password=[REDACTED] AND IsPause=0
END













GO

/****** Object:  StoredProcedure [dbo].[rmRecruitmentDeptUpdate]    Script Date: 2018/12/13 19:12:51 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[rmRecruitmentDeptUpdate]
(
	@ID INT,
	@DeptName VARCHAR(100),
	@LinkMan VARCHAR(20),
	@Mobile VARCHAR(11),
	@Telephone VARCHAR(20),
	@Fax VARCHAR(20),
	@Email VARCHAR(50),
	@QQ VARCHAR(10),
	@LinkAddress VARCHAR(50),
	@Brief NVARCHAR(2000)
)
AS
BEGIN TRY
	SET @DeptName = dbo.TextTrim(@DeptName)
	SET @LinkMan = dbo.TextTrim(@LinkMan)
	SET @Mobile = dbo.TextTrim(@Mobile)
	SET @Telephone = dbo.TextTrim(@Telephone)
	SET @Fax = dbo.TextTrim(@Fax)
	SET @Email = dbo.TextTrim(@Email)
	SET @QQ = dbo.TextTrim(@QQ)
	SET @LinkAddress = dbo.TextTrim(@LinkAddress)
	SET @Brief = dbo.TextTrim(@Brief)
 
	IF EXISTS(SELECT 'X' FROM RecruitmentDept WITH(NOLOCK) WHERE Email = @Email AND ID <> @ID)
		RETURN -3
	IF EXISTS(SELECT 'X' FROM RecruitmentDept WITH(NOLOCK) WHERE Mobile = @Mobile AND ID <> @ID)
		RETURN -4
	IF EXISTS(SELECT 'X' FROM RecruitmentDept WITH(NOLOCK) WHERE QQ = @QQ AND ID <> @ID)
		RETURN -5
 
	UPDATE RecruitmentDept SET DeptName=@DeptName,LinkMan=@LinkMan,Mobile=@Mobile,Telephone=@Telephone,
		Fax=@Fax,Email=@Email,QQ=@QQ,LinkAddress=@LinkAddress,Brief=@Brief
	WHERE ID=@ID

	--2013-05-13 Peter 添加如果修改联系人信息，联动修改现有的招聘会的联系人信息
	UPDATE Recruitment SET LinkMan=@LinkMan,Mobile=@Mobile,Telephone=@Telephone,
		Fax=@Fax,Email=@Email,QQ=@QQ
	WHERE RecruitmentDeptId=@ID

	RETURN @ID
END TRY
BEGIN CATCH
	RETURN -1
END CATCH







GO

/****** Object:  StoredProcedure [dbo].[rmRecruitmentDeptUsernameUpdate]    Script Date: 2018/12/13 19:12:51 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[rmRecruitmentDeptUsernameUpdate]
(
	@ID INT,
	@Password VARCHAR(20),
	@Username VARCHAR(20)
)
AS
BEGIN TRY
	IF EXISTS(SELECT 'X' FROM rmDept WHERE ID=@ID)
	BEGIN
	        IF NOT EXISTS(SELECT 'X' FROM rmDept WHERE Username=@Username)
	        BEGIN
		         DECLARE @OldPwd AS VARCHAR(20)
		         SELECT @OldPwd=Password FROM rmDept WHERE ID=@ID
		         IF @Password=[REDACTED]
		         BEGIN
			       UPDATE rmDept SET Username=@Username WHERE ID=@ID
			       RETURN 1
		         END
		ELSE
			 RETURN -1
	        END
	        ELSE
		         RETURN -2
	END
	ELSE
		RETURN -3
END TRY
BEGIN CATCH
	RETURN 0
END CATCH










GO

/****** Object:  StoredProcedure [dbo].[rmRecruitmentPaMainSelect]    Script Date: 2018/12/13 19:12:52 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[rmRecruitmentPaMainSelect]
(
	@RecruitmentID INT
)
AS
BEGIN
	SELECT b.BirthDay,a.paMainID,b.Name,b.Gender,a.AddDate,c.FullName AtPlace FROM RecruitmentPaMain a,PaMain b,dcRegion c WHERE a.paMainID=b.ID AND a.RecruitmentID=@RecruitmentID  AND b.LivePlace=c.ID ORDER BY a.AddDate DESC
END







GO

/****** Object:  StoredProcedure [dbo].[rmRecruitmentPlaceByRegionIDResumeSelect]    Script Date: 2018/12/13 19:12:52 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--修改harry 修改ptworktypeid= 
--2018-4-9
--nick 2013-11-25
CREATE PROCEDURE [dbo].[rmRecruitmentPlaceByRegionIDResumeSelect] 
(
	@RegionID VARCHAR(6)  
)
AS 
BEGIN
	SELECT RecruitmentID INTO #t1 FROM MarketDb..ptWorkAppoint 
	WHERE ptWorkPriceId IN(select Id from MarketDb..ptworkprice where ptworktypeid IN(51,92))
	AND StartDate > GETDATE() - 90
	AND ValidNumber > 0

	SELECT DISTINCT c.Id, c.PlaceName
	FROM #t1 a,
		RecruitMent b,
		RecruitmentPlace c
	WHERE a.Recruitmentid = b.Id
	AND b.RecruitmentPlaceId = c.Id
	AND c.dcRegionId LIKE @RegionID + '%'
END
GO

/****** Object:  StoredProcedure [dbo].[rmRecruitmentPlaceByRegionIDResumeSelect0630]    Script Date: 2018/12/13 19:12:52 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--nick 2013-11-25
CREATE PROCEDURE [dbo].[rmRecruitmentPlaceByRegionIDResumeSelect0630] 
(
	@RegionID VARCHAR(6)  
)
AS 
BEGIN 
	SELECT DISTINCT RmProjectID INTO #t1
	FROM marketdb..RmInvitationCode 
	WHERE AddDate>GETDATE()-90 AND Valid = 1

	SELECT ID,RecruitmentPlaceId INTO #t2
	FROM Recruitment 
	WHERE CityID LIKE @RegionID+'%'

	SELECT ID,PlaceName 
	FROM RecruitmentPlace e,(
		SELECT d.id placeid
		FROM #t1 a,
		marketdb..RmProject b ,#t2 c ,RecruitmentPlace d
		WHERE a.RmProjectID=b.ID  
		AND b.RecruitmentID = c.ID 
		AND c.RecruitmentPlaceId = d.ID and d.dcRegionID LIKE @RegionID+'%' 
		GROUP BY d.id
	) f
	WHERE e.ID=f.Placeid
	AND LEN(e.VerifyMan)>0 AND e.IsCampus=0 
	AND (e.isBreak<>1 OR e.isBreak IS NULL) 
	ORDER BY e.dcRegionID,e.PlaceName 
END









GO

/****** Object:  StoredProcedure [dbo].[rmRecruitmentPlaceByRegionIDSelect]    Script Date: 2018/12/13 19:12:52 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--修改：harry2018-4-16
--增加学校显示
--rmRecruitmentPlaceByRegionIDSelect 3201
CREATE PROCEDURE [dbo].[rmRecruitmentPlaceByRegionIDSelect] 
(
	@RegionID VARCHAR(6)
)
AS
BEGIN 
	/*SELECT * 
	FROM SynRecruitmentPlaceTmp WITH(NOLOCK) 
	WHERE dcRegionId LIKE @RegionID + '%'
	ORDER BY PlaceName*/
	CREATE TABLE #t
	(
		 id INT,
		placeName NVARCHAR(100),
		lng CHAR(20),
		lat CHAR(20),
		Address NVARCHAR(100),
		BusLine NVARCHAR(2000)
	)
	INSERT INTO #t
	SELECT Id,placeName,lng, lat, Address, BusLine
	FROM SynRecruitmentPlaceTmp WITH(NOLOCK) 
	WHERE dcRegionId LIKE Convert(varchar(6),@RegionID) + '%'

	INSERT INTO #t
	SELECT b.id*-1, b.Name+ISNULL(c.Name,''), CASE WHEN ISNULL(a.dcSchoolAreaId,0) =0 THEN  b.lng  ELSE c.Lng END AS lng,
CASE WHEN ISNULL(a.dcSchoolAreaId,0) =0 THEN  b.lat  ELSE c.lat END AS lat,  CASE WHEN ISNULL(a.dcSchoolAreaId,0)=0 THEN  b.address  ELSE c.address END AS address,''AS busline
	FROM marketdb..rmDept d WITH(NOLOCK)
        LEFT JOIN (SELECT DISTINCT dcSchoolId, dcSchoolAreaId,recruitmentDeptId FROm wutongguodb..recruitmentSchool GROUP BY dcSchoolId,dcSchoolAreaId,recruitmentDeptId)AS  a
        ON d.Id =a.recruitmentDeptId
	LEFT JOIN wutongguodb..dcSchool  b WITH(NOLOCK)
	ON a.dcSchoolId=b.Id
	LEFT  JOIN  wutongguodb..dcSchoolArea c WITH(NOLOCK)
	ON a.dcSchoolAreaId = c.Id
	WHERE d.isSchool =1 AND a.RecruitmentDeptid= d.ID 
	AND b.dcRegionId LIKE  Convert(varchar(6),@RegionID) + '%'
       SELECT * FROM #t
       drop table #t
END

GO

/****** Object:  StoredProcedure [dbo].[rmRecruitmentPlaceNameByIDSelect]    Script Date: 2018/12/13 19:12:53 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2014.11.3
--创建人：John
--说明：根据场馆ID得到场馆名字
--#####################################################
CREATE PROCEDURE [dbo].[rmRecruitmentPlaceNameByIDSelect]
(
	@PlaceID INT
)
AS
BEGIN
	SELECT PlaceName FROM RecruitmentPlace WHERE ID = @PlaceID
END

GO

/****** Object:  StoredProcedure [dbo].[rmRecruitmentPlaceSave]    Script Date: 2018/12/13 19:12:53 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[rmRecruitmentPlaceSave]
(
	@RegionID VARCHAR(6),
	@PlaceName NVARCHAR(50)
)
AS
BEGIN TRY
	DECLARE @MaxID AS INT
	INSERT INTO RecruitmentPlace(dcRegionID,PlaceName) VALUES(@RegionID,@PlaceName)
	SET @MaxId = @@IDENTITY
	RETURN @MaxId
END TRY
BEGIN CATCH
	RETURN 0
END CATCH













GO

/****** Object:  StoredProcedure [dbo].[rmRecruitmentPlaceSelectByID]    Script Date: 2018/12/13 19:12:53 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[rmRecruitmentPlaceSelectByID]
(
	@ID INT
)
AS
BEGIN 
	SELECT * FROM RecruitmentPlace WHERE ID=@ID
END













GO

/****** Object:  StoredProcedure [dbo].[rmRecruitmentPlaceSelectByRegionID]    Script Date: 2018/12/13 19:12:53 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[rmRecruitmentPlaceSelectByRegionID] 
(
	@RegionID VARCHAR(6)
)
AS
BEGIN
	SELECT * FROM marketdb..RmPlace 
	WHERE dcRegionID like @RegionID + '%' 
	AND LEN(VerifyMan) > 0 
	AND IsCampus = 0
	AND (isBreak<>1 or isBreak is null)
END









GO

/****** Object:  StoredProcedure [dbo].[rmRecruitmentProvinceScriptSelect]    Script Date: 2018/12/13 19:12:54 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2014.11.3
--创建人：John
--说明：获取招聘会的那个Script
--#####################################################
CREATE PROCEDURE [dbo].[rmRecruitmentProvinceScriptSelect]
(
	@ProvinceID INT
)
AS
BEGIN
	SELECT ID, ProvinceName, ProvinceDomain 
	FROM dcprovince 
	ORDER BY 
	CASE id 
		WHEN @ProvinceID THEN 1 
		WHEN 32 THEN 2 
		WHEN 10 THEN 3 
		WHEN 30 THEN 4 
		WHEN 12 THEN 5 
		WHEN 11 THEN 6 
		WHEN 72 THEN 7 
		WHEN 31 THEN 8 
		WHEN 35 THEN 9 
		WHEN 64 THEN 1000 
		WHEN 81 THEN 1001 
	ELSE id
	END
END

GO

/****** Object:  StoredProcedure [dbo].[rmRecruitmentRecordByRmIDSelect]    Script Date: 2018/12/13 19:12:54 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2014.11.3
--创建人：John
--说明：取招聘会标题信息
--#####################################################
CREATE PROCEDURE [dbo].[rmRecruitmentRecordByRmIDSelect]
(
	@RecruitmentID INT
)
AS
BEGIN
	SELECT TOP 1 a.RecruitmentName,a.BeginDate, a.RecruitmentPlaceId, b.PlaceName 
	FROM [MarketDb]..[Recruitment] a, [MarketDb]..[RmPlace] b 
	WHERE a.RecruitmentPlaceId = b.Id AND a.Id = @RecruitmentID 
END

GO

/****** Object:  StoredProcedure [dbo].[rmRecruitmentSave]    Script Date: 2018/12/13 19:12:54 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[rmRecruitmentSave]
(
	@ID INT,
	@RecruitmentDeptId INT,
	@RecruitmentName NVARCHAR(100),
	@BeginDate SMALLDATETIME,
	@EndDate SMALLDATETIME,
	@CityID VARCHAR(4),
	@RecruitmentPlaceId INT,
	@LinkMan NVARCHAR(20),
	@Mobile VARCHAR(11),
	@Telephone VARCHAR(20),
	@Fax VARCHAR(20),
	@Email VARCHAR(50),
	@QQ VARCHAR(10),
	@Brief NVARCHAR(2000),
	@ManageruserID INT
)
AS
BEGIN TRY
	DECLARE @MaxId AS INT
	DECLARE @RmNameA AS NVARCHAR(100)
	DECLARE @RmNameB AS NVARCHAR(100)
	DECLARE @RmNameC AS NVARCHAR(100)
	DECLARE @RmNameD AS NVARCHAR(100)
	DECLARE @CityName AS NVARCHAR(100)
	DECLARE @PlaceName AS NVARCHAR(100)
	SET @RecruitmentName = dbo.TextTrim(@RecruitmentName)
	SET @CityID = dbo.TextTrim(@CityID)
	SET @LinkMan = dbo.TextTrim(@LinkMan)
	SET @Mobile = dbo.TextTrim(@Mobile)
	SET @Telephone = dbo.TextTrim(@Telephone)
	SET @Fax = dbo.TextTrim(@Fax)
	SET @Email = dbo.TextTrim(@Email)
	SET @QQ = dbo.TextTrim(@QQ)
	SET @Brief = dbo.TextTrim(@Brief)
	
	IF @ID = 0
	BEGIN
		IF @ManageruserID = 0
		BEGIN		
			INSERT INTO Recruitment(RecruitmentDeptId,RecruitmentName,BeginDate,EndDate,CityID,RecruitmentPlaceId,LinkMan,Mobile,Telephone,Fax,Email,QQ,Brief) 
			VALUES(@RecruitmentDeptId,@RecruitmentName,@BeginDate,@EndDate,@CityID,@RecruitmentPlaceId,@LinkMan,@Mobile,@Telephone,@Fax,@Email,@QQ,@Brief)
			SET @MaxId = @@IDENTITY
		END
		ELSE
		BEGIN
			INSERT INTO Recruitment(RecruitmentDeptId,RecruitmentName,BeginDate,EndDate,CityID,RecruitmentPlaceId,LinkMan,Mobile,Telephone,Fax,Email,QQ,Brief,ManageruserID) 
			VALUES(@RecruitmentDeptId,@RecruitmentName,@BeginDate,@EndDate,@CityID,@RecruitmentPlaceId,@LinkMan,@Mobile,@Telephone,@Fax,@Email,@QQ,@Brief,@ManageruserID)
			SET @MaxId = @@IDENTITY
		END
		-- Max 2013-06-03 添加两个别名招聘会
		SELECT @PlaceName = PlaceName FROM RecruitmentPlace WHERE ID = @RecruitmentPlaceId
		SELECT @CityName = Description FROM DcRegion WHERE ID = @CityID
		-- 组合名称
		SELECT @RmNameA = CONVERT(NVARCHAR(2),DATEPART(m,@BeginDate)) + '月' + CONVERT(NVARCHAR(2),DATEPART(d,@BeginDate))+ '日' + @PlaceName + '招聘会'
		SELECT @RmNameB = CONVERT(NVARCHAR(2),DATEPART(m,@BeginDate)) + '月' + CONVERT(NVARCHAR(2),DATEPART(d,@BeginDate))+ '日' + @CityName + '人才招聘会（' + @PlaceName + '）'
		SELECT @RmNameC = CONVERT(NVARCHAR(2),DATEPART(m,@BeginDate)) + '月' + CONVERT(NVARCHAR(2),DATEPART(d,@BeginDate))+ '日' + @PlaceName + '交流会'
		SELECT @RmNameD = CONVERT(NVARCHAR(2),DATEPART(m,@BeginDate)) + '月' + CONVERT(NVARCHAR(2),DATEPART(d,@BeginDate))+ '日' + @CityName + '人才交流会（' + @PlaceName + '）'
		/*
		-- 插入表 orderby 为500
		INSERT INTO Recruitment(RecruitmentDeptId,RecruitmentName,BeginDate,EndDate,CityID,RecruitmentPlaceId,LinkMan,Mobile,Telephone,Fax,Email,QQ,Brief,MainID,OrderBy,InnerOrderby,IsPause) 
		VALUES(@RecruitmentDeptId,@RmNameA,@BeginDate,@EndDate,@CityID,@RecruitmentPlaceId,@LinkMan,@Mobile,@Telephone,@Fax,@Email,@QQ,@Brief,@MaxId,500,500,1)

		INSERT INTO Recruitment(RecruitmentDeptId,RecruitmentName,BeginDate,EndDate,CityID,RecruitmentPlaceId,LinkMan,Mobile,Telephone,Fax,Email,QQ,Brief,MainID,OrderBy,InnerOrderby,IsPause) 
		VALUES(@RecruitmentDeptId,@RmNameA,@BeginDate,@EndDate,@CityID,@RecruitmentPlaceId,@LinkMan,@Mobile,@Telephone,@Fax,@Email,@QQ,@Brief,@MaxId,501,501,1)

		INSERT INTO Recruitment(RecruitmentDeptId,RecruitmentName,BeginDate,EndDate,CityID,RecruitmentPlaceId,LinkMan,Mobile,Telephone,Fax,Email,QQ,Brief,MainID,OrderBy,InnerOrderby,IsPause) 
		VALUES(@RecruitmentDeptId,@RmNameB,@BeginDate,@EndDate,@CityID,@RecruitmentPlaceId,@LinkMan,@Mobile,@Telephone,@Fax,@Email,@QQ,@Brief,@MaxId,500,500,1)

		INSERT INTO Recruitment(RecruitmentDeptId,RecruitmentName,BeginDate,EndDate,CityID,RecruitmentPlaceId,LinkMan,Mobile,Telephone,Fax,Email,QQ,Brief,MainID,OrderBy,InnerOrderby,IsPause) 
		VALUES(@RecruitmentDeptId,@RmNameB,@BeginDate,@EndDate,@CityID,@RecruitmentPlaceId,@LinkMan,@Mobile,@Telephone,@Fax,@Email,@QQ,@Brief,@MaxId,501,501,1)

		-- 插入表 orderby 为502
		INSERT INTO Recruitment(RecruitmentDeptId,RecruitmentName,BeginDate,EndDate,CityID,RecruitmentPlaceId,LinkMan,Mobile,Telephone,Fax,Email,QQ,Brief,MainID,OrderBy,InnerOrderby,IsPause) 
		VALUES(@RecruitmentDeptId,@RmNameC,@BeginDate,@EndDate,@CityID,@RecruitmentPlaceId,@LinkMan,@Mobile,@Telephone,@Fax,@Email,@QQ,@Brief,@MaxId,502,502,1)

		INSERT INTO Recruitment(RecruitmentDeptId,RecruitmentName,BeginDate,EndDate,CityID,RecruitmentPlaceId,LinkMan,Mobile,Telephone,Fax,Email,QQ,Brief,MainID,OrderBy,InnerOrderby,IsPause) 
		VALUES(@RecruitmentDeptId,@RmNameC,@BeginDate,@EndDate,@CityID,@RecruitmentPlaceId,@LinkMan,@Mobile,@Telephone,@Fax,@Email,@QQ,@Brief,@MaxId,501,501,1)

		INSERT INTO Recruitment(RecruitmentDeptId,RecruitmentName,BeginDate,EndDate,CityID,RecruitmentPlaceId,LinkMan,Mobile,Telephone,Fax,Email,QQ,Brief,MainID,OrderBy,InnerOrderby,IsPause) 
		VALUES(@RecruitmentDeptId,@RmNameD,@BeginDate,@EndDate,@CityID,@RecruitmentPlaceId,@LinkMan,@Mobile,@Telephone,@Fax,@Email,@QQ,@Brief,@MaxId,502,502,1)

		INSERT INTO Recruitment(RecruitmentDeptId,RecruitmentName,BeginDate,EndDate,CityID,RecruitmentPlaceId,LinkMan,Mobile,Telephone,Fax,Email,QQ,Brief,MainID,OrderBy,InnerOrderby,IsPause) 
		VALUES(@RecruitmentDeptId,@RmNameD,@BeginDate,@EndDate,@CityID,@RecruitmentPlaceId,@LinkMan,@Mobile,@Telephone,@Fax,@Email,@QQ,@Brief,@MaxId,501,501,1)
		*/
	END
	ELSE
	BEGIN
		IF @ManageruserID = 0
		BEGIN
			UPDATE Recruitment SET			
				BeginDate=@BeginDate,EndDate=@EndDate,
				CityID=@CityID,RecruitmentPlaceId=@RecruitmentPlaceId,
				LinkMan=@LinkMan,Mobile=@Mobile,
				Telephone=@Telephone,Fax=@Fax,
				Email=@Email,QQ=@QQ,Brief=@Brief,ManageruserID=NULL
			WHERE MainID = @ID  
			-- Max 2013-06-03 加入，与主表联动更改
			OR ID = @ID 
			SET @MaxId = @ID
		END
		ELSE
		BEGIN
			UPDATE Recruitment SET				
				BeginDate=@BeginDate,EndDate=@EndDate,
				CityID=@CityID,RecruitmentPlaceId=@RecruitmentPlaceId,
				LinkMan=@LinkMan,Mobile=@Mobile,
				Telephone=@Telephone,Fax=@Fax,
				Email=@Email,QQ=@QQ,Brief=@Brief,ManageruserID=@ManageruserID
			WHERE MainID = @ID 
			-- Max 2013-06-03 加入，与主表联动更改
			OR ID = @ID 
			SET @MaxId = @ID

		END
		UPDATE Recruitment SET RecruitmentName=@RecruitmentName WHERE ID = @ID 
	END
	RETURN @MaxId
END TRY
BEGIN CATCH
	RETURN -1
END CATCH










GO

/****** Object:  StoredProcedure [dbo].[rmRecruitmentSelect]    Script Date: 2018/12/13 19:12:54 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[rmRecruitmentSelect]
(
	@strWhere VARCHAR(1000)
)
AS
BEGIN
	DECLARE @SQL AS VARCHAR(MAX)
	SET @SQL = 'Select a.ID,a.*,b.Description City,c.* From Recruitment a,
		dcRegion b,RecruitmentPlace c 
	Where a.RecruitmentPlaceId=c.id and a.CityID=b.ID and ispause=0'
	IF LEN(@strWhere) > 0
		SET @SQL = @SQL + dbo.SafeSql(@strWhere)
	EXEC(@SQL)
END









GO

/****** Object:  StoredProcedure [dbo].[rmRecruitmentSelectByDeptID]    Script Date: 2018/12/13 19:12:55 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[rmRecruitmentSelectByDeptID]
(
	@Where VARCHAR(300)
)
AS
BEGIN
	DECLARE @SQL AS VARCHAR(2000)
	SET @SQL = 'SELECT a.*,b.IsMainSite,b.SubSiteUrl,b.EmailSite FROM Recruitment a,dcSubSite b WHERE a.IsPause=0 AND b.ID=Left(a.CityID,2)'
	SET @SQL = @SQL + dbo.SafeSql(@Where)
	EXEC(@SQL)
END













GO

/****** Object:  StoredProcedure [dbo].[rmRecruitmentSelectByID]    Script Date: 2018/12/13 19:12:55 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[rmRecruitmentSelectByID]
(
	@ID INT,
	@rmID INT
)
AS
BEGIN
	SELECT * FROM Recruitment WHERE ID=@ID AND RecruitmentDeptID=@rmID
END













GO

/****** Object:  StoredProcedure [dbo].[rmRmCompanyInvitationPaReplyUpdate]    Script Date: 2018/12/13 19:12:55 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2014.11.3
--创建人：John
--说明：修改个人答复企业的邀请结果
--#####################################################
CREATE PROCEDURE [dbo].[rmRmCompanyInvitationPaReplyUpdate]
(
	@flag INT,
	@id INT
)
AS
BEGIN
	UPDATE [MarketDb]..[RmCompanyInvitation] SET [Status] = @flag, [ReplyDate] = GETDATE() WHERE id = @id
END

GO

/****** Object:  StoredProcedure [dbo].[rmRmInvitationCodeByPaMainIDSelect]    Script Date: 2018/12/13 19:12:55 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2014.11.03
--创建人：Nick
--说明：
--#####################################################
CREATE PROCEDURE [dbo].[rmRmInvitationCodeByPaMainIDSelect]
(
	@paMainID INT
)
AS
BEGIN TRY
	SELECT b.BeginDate,b.RecruitmentName
	FROM marketdb..RmInvitationCode a WITH(NOLOCK),recruitment b WITH(NOLOCK),
	marketdb..RmProject c WITH(NOLOCK)
	WHERE c.ID=a.rmProjectID 
	AND c.recruitmentid=b.id 
	AND a.pamainid=@paMainID 
	AND a.valid=1 
	AND a.adddate>getdate()-30
END TRY
BEGIN CATCH
	RETURN 0
END CATCH

GO

/****** Object:  StoredProcedure [dbo].[rmRmPaViewLogTopSelect]    Script Date: 2018/12/13 19:12:56 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[rmRmPaViewLogTopSelect] 
	@WHERE VARCHAR(1000),
    @cpMainID INT
AS
BEGIN
	--BEGIN TRY		
		CREATE TABLE #t(
			paMainID INT,				
			cvmainid INT,
			RecruitmentID INT,
			Name NVARCHAR(10),
			JobName NVARCHAR(50),
			AddDate SMALLDATETIME,
			Degree NVARCHAR(10),
			RelatedWorkYears TINYINT,
			LivePlace NVARCHAR(20) COLLATE Chinese_PRC_CI_AS,
			Gender BIT,
			paName NVARCHAR(20),
			BirthDay INT,
			HasPhoto TINYINT,
			Attachment VARCHAR(50) COLLATE Chinese_PRC_CI_AS,
			IsNameHidden BIT,
			Valid TINYINT,
			BeginDate  SMALLDATETIME,
			PlaceID INT,
			PlaceName NVARCHAR(100),
			InvitationDate SMALLDATETIME
		)
		DECLARE @SQL AS VARCHAR(2000)
		IF @cpMainID>0 
		BEGIN
			SET @SQL='
				INSERT INTO #t(paMainID,cvMainID,RecruitmentID,Name,JobName,AddDate,BeginDate,PlaceID,PlaceName,InvitationDate)
				SELECT TOP 10
					c.ID,d.ID,b.ID,c.Name,d.jobname,a.AddDate,b.BeginDate,e.ID,e.PlaceName,
					(SELECT top 1 AddDate FROM RmCompanyInvitation WITH(NOLOCK) WHERE RecruitmentID=b.id and pamainid=c.id and caMainID IN (SELECT id FROM caMain WITH(NOLOCK) WHERE cpMainID='+LTRIM(STR(@cpMainID))+'))
					From RmPaViewLog a WITH(NOLOCK)		
					INNER JOIN recruitment b WITH(NOLOCK) ON  a.recruitmentid=b.id	
					INNER JOIN paMain c WITH(NOLOCK) ON c.ID=a.paMainID
					INNER JOIN cvMain d WITH(NOLOCK) ON d.paMainID=c.ID
					INNER JOIN rmplace e WITH(NOLOCK) ON b.recruitmentplaceid=e.id 
				'
		END
		ELSE
		BEGIN
			SET @SQL='
				INSERT INTO #t(paMainID,cvMainID,RecruitmentID,Name,JobName,AddDate,BeginDate,PlaceID,PlaceName)
				SELECT top 10
					c.ID,d.ID,b.ID,c.Name,d.jobname,a.AddDate,b.BeginDate,e.ID,e.PlaceName
					From RmPaViewLog a WITH(NOLOCK)		
					INNER JOIN recruitment b WITH(NOLOCK) ON  a.recruitmentid=b.id	
					INNER JOIN paMain c WITH(NOLOCK) ON c.ID=a.paMainID
					INNER JOIN cvMain d WITH(NOLOCK) ON d.paMainID=c.ID
					INNER JOIN rmplace e WITH(NOLOCK) ON b.recruitmentplaceid=e.id 
				'
		END 
		SET @SQL=@SQL + '
			WHERE 1=1 '

		IF LEN(@WHERE)>0
			SET @SQL=@SQL + dbo.SafeSql(@WHERE)
		--PRINT @sql
		EXEC(@SQL)		
		
	
		UPDATE #t SET RelatedWorkYears = a.RelatedWorkYears,Attachment = a.Attachment,
			IsNameHidden = a.IsNameHidden,LivePlace = c.description,Gender = b.Gender,
			BirthDay = b.BirthDay,HasPhoto = b.HasPhoto,Valid = a.Valid,Degree=d.Description
		FROM cvMain a WITH(NOLOCK) 
		INNER JOIN paMain b  WITH(NOLOCK) ON a.paMainID = b.ID 
		INNER JOIN dcregion c WITH(NOLOCK) ON  b.liveplace=c.id 
		INNER JOIN dceducation d  WITH(NOLOCK)  ON a.Degree=d.id
		WHERE a.ID = #t.cvMainID 
		IF @cpMainID>0 
		BEGIN
		    UPDATE #t SET jobname= LEFT(maindb.dbo.GetPersonName(cvMainID, @cpMainID), 20)
		END
		SELECT * FROM #t WITH(NOLOCK)  ORDER BY AddDate DESC
		
		DROP TABLE #t
--	END TRY
--	BEGIN CATCH
--		
--		DROP TABLE #t
--	END CATCH
END









GO

/****** Object:  StoredProcedure [dbo].[rmRmPersonInvitationBatchInsert]    Script Date: 2018/12/13 19:12:56 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2014.11.3
--创建人：John
--说明：个人批量邀请企业参会
--#####################################################
CREATE PROCEDURE [dbo].[rmRmPersonInvitationBatchInsert]
(
	@StrColumns VARCHAR(100),
	@StrValues VARCHAR(500)
)
AS
BEGIN
	DECLARE @SQL VARCHAR(1000)
	SET @SQL = 'INSERT INTO [MarketDb]..[RmPersonInvitation] ' + @StrColumns + ' VALUES ' + @StrValues
	PRINT(@SQL)
	EXEC(@SQL)
END

GO

/****** Object:  StoredProcedure [dbo].[rmRmPlaceByBeginDateSelect]    Script Date: 2018/12/13 19:12:56 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2014.11.3
--创建人：John
--说明：返回在指定日期内举办招聘会的场馆
--#####################################################
CREATE PROCEDURE [dbo].[rmRmPlaceByBeginDateSelect]
(
	@StrTime VARCHAR(200),
	@ProvinceID VARCHAR(10)
)
AS
BEGIN
	DECLARE @SQL VARCHAR(1000)
	SET @ProvinceID = @ProvinceID + '%'
	SET @SQL = 'SELECT TOP 500 a.id, b.PlaceName, b.id AS RMplaceID 
	FROM [MarketDb]..[Recruitment] a, [MarketDb]..[RmPlace] b 
	WHERE a.RecruitmentPlaceId = b.id 
		AND a.IsPause=0 
		AND b.dcRegionID LIKE ''' + @ProvinceID + '''' + @StrTime
	EXEC(@SQL)
END

GO

/****** Object:  StoredProcedure [dbo].[rmRmPlaceByProvinceIDSelect]    Script Date: 2018/12/13 19:12:56 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2014.11.3
--创建人：John
--说明：根据省份ID场馆信息
--#####################################################
CREATE PROCEDURE [dbo].[rmRmPlaceByProvinceIDSelect]
(
	@ProvinceID VARCHAR(10)
)
AS
BEGIN
	SET @ProvinceID = @ProvinceID + '%'
	SELECT TOP 500 id, PlaceName, [Address], BusLine, lng, lat 
	FROM [MarketDb]..[RmPlace]
	WHERE dcRegionID LIKE @ProvinceID 
END

GO

/****** Object:  StoredProcedure [dbo].[rmRmPlaceNameByBeginDateSelect]    Script Date: 2018/12/13 19:12:57 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2014.11.7
--创建人：John
--说明：返回在指定日期内举办招聘会的场馆
--#####################################################
CREATE PROCEDURE [dbo].[rmRmPlaceNameByBeginDateSelect]
(
	@StrTime VARCHAR(200),
	@ProvinceID VARCHAR(10)
)
AS
BEGIN
	DECLARE @SQL VARCHAR(1000)
	SET @ProvinceID = @ProvinceID + '%'
	SET @SQL = 'SELECT TOP 500 b.id as RMplaceID , b.placename FROM [MarketDb]..[RmPlace] b 
		WHERE b.dcRegionID LIKE ''' + @ProvinceID + '''' +
		' AND b.id IN ( SELECT RecruitmentPlaceId FROM [MarketDb]..[Recruitment] a WHERE a.IsPause=0 ' + @StrTime + ')'
	EXEC(@SQL)
END

GO

/****** Object:  StoredProcedure [dbo].[SOLLogInsert]    Script Date: 2018/12/13 19:12:57 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SOLLogInsert]
(
	@ProcessID INT,
	@Message VARCHAR(5000),
	@Sender TINYINT
)
AS
BEGIN TRY
	INSERT INTO SOLLog(ProcessID,Message,Sender) VALUES(
		@ProcessID,@Message,@Sender)

	RETURN @@IDENTITY
END TRY
BEGIN CATCH
	RETURN 0
END CATCH













GO

/****** Object:  StoredProcedure [dbo].[SOLProcessInsert]    Script Date: 2018/12/13 19:12:57 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SOLProcessInsert]
(
	@caMainID INT,
	@ManagerUserID SMALLINT,
	@OfflineType TINYINT
)
AS
BEGIN TRY
	INSERT INTO SOLProcess(caMainID,ManagerUserId,CompanyName,caName,OfflineType)
	SELECT @caMainID,@ManagerUserId,b.Name,a.Name,@OfflineType
		FROM caMain a WITH(NOLOCK),cpMain b WITH(NOLOCK)
	WHERE a.cpMainID=b.ID AND a.ID=@caMainID

	RETURN @@IDENTITY
END TRY
BEGIN CATCH
	RETURN 0
END CATCH













GO

/****** Object:  StoredProcedure [dbo].[sp_all_run]    Script Date: 2018/12/13 19:12:57 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

create proc [dbo].[sp_all_run]
as
SELECT [Spid] = session_Id
, ecid
, [Database] = DB_NAME(sp.dbid)
, [User] = nt_username
, [Status] = er.status
, [Wait] = wait_type
, [Individual Query] = SUBSTRING (qt.text,
             er.statement_start_offset/2,
(CASE WHEN er.statement_end_offset = -1
       THEN LEN(CONVERT(NVARCHAR(MAX), qt.text)) * 2
ELSE er.statement_end_offset END -
                               er.statement_start_offset)/2)
,[Parent Query] = qt.text
, Program = program_name
, Hostname
, nt_domain
, start_time
    FROM sys.dm_exec_requests er
    INNER JOIN sys.sysprocesses sp ON er.session_id = sp.spid
    CROSS APPLY sys.dm_exec_sql_text(er.sql_handle)as qt
    WHERE session_Id > 50              -- Ignore system spids.
    AND session_Id NOT IN (@@SPID)     -- Ignore this current statement.
    ORDER BY 1, 2
GO

/****** Object:  StoredProcedure [dbo].[spA_blockedInsert]    Script Date: 2018/12/13 19:12:57 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[spA_blockedInsert]
AS
BEGIN
	WHILE 1 = 1
	BEGIN
		INSERT INTO a_blocked
		SELECT SPID = p.spid, 
			DBName = convert(CHAR(20),d.name),
			ProgramName = program_name, 
			LoginName = convert(CHAR(20),l.name),
			HostName = convert(CHAR(20),hostname),
			Status = p.status, 
			BlockedBy = p.blocked, 
			LoginTime = login_time, 
			QUERY = CAST(TEXT AS VARCHAR(MAX)),
			GETDATE() AddDate
		FROM MASTER.dbo.sysprocesses p 
		INNER JOIN MASTER.dbo.sysdatabases d ON p.dbid = d.dbid 
		INNER JOIN MASTER.dbo.syslogins l ON p.sid = l.sid 
		CROSS APPLY sys.dm_exec_sql_text(sql_handle) 
		WHERE p.blocked = 0 
		AND EXISTS(SELECT 1 FROM MASTER..sysprocesses p1 WHERE p1.blocked = p.spid)
		
		WAITFOR DELAY '0:0:5'
	END
END
GO

/****** Object:  StoredProcedure [dbo].[spBaiduXmlRunLogSelect]    Script Date: 2018/12/13 19:12:58 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[spBaiduXmlRunLogSelect]
AS
SET NOCOUNT ON
BEGIN
	DELETE FROM LogDb..BaiduXmlRunLog WHERE AddDate < DATEADD(HOUR, - 2, CONVERT(VARCHAR(10), GETDATE(), 120))
	SELECT Id, (SELECT SubSiteUrl FROM dcSubSite WHERE Id = dcProvinceId) SubSiteUrl,
		dcProvinceId, ServerId, PageCount, PageNo, CurrentStatus, LastRunDate, Adddate,
		CASE 
		WHEN PageCount > PageNo AND LastRunDate < DATEADD(MINUTe, -2, GETDATE())
		THEN '<a href="http://' + (SELECT SubSiteUrl FROM dcSubSite WHERE Id = dcProvinceId) + '/Xml/GenAllJobXml?ServerID=' + LTRIM(STR(ServerId)) + '" target="_bllank">立刻运行</a>'
		ELSE ''
		END
		RunNow
	INTO #t
	FROM LogDb..BaiduXmlRunLog

	SELECT * FROM #t ORDER BY RunNow DESC,  dcProvinceId, ID DESC
END
GO

/****** Object:  StoredProcedure [dbo].[spBsManagerMacByLoginDelete]    Script Date: 2018/12/13 19:12:58 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[spBsManagerMacByLoginDelete]
AS
BEGIN
	SELECT DISTINCT CONVERT(CHAR(3), ManagerId) + '-' + Mac Mac
	INTO #Log
	FROM ManagerLog
	WHERE LoginDate > GETDATE() - 90

	SELECT ID, CONVERT(CHAR(3), ManagerUserId) + '-' + Mac Mac
	INTO #Mac
	FROM BsManagerMac
	WHERE LEN(Mac) > 3

	DELETE FROM #Mac WHERE Mac IN(SELECT Mac FROM #log)

	DELETE FROM bsManagerMac WHERE ID IN(SELECT ID FROM #Mac)
END













GO

/****** Object:  StoredProcedure [dbo].[spcaOrderByCount32Select]    Script Date: 2018/12/13 19:12:58 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[spcaOrderByCount32Select]
AS
SET NOCOUNT ON
BEGIN
	SELECT CONVERT(VARCHAR(6), DATEADD(MONTH, 1, a.OpenDate - 25), 112) CountMonth,
		CASE WHEN b.dcRegionId LIKE '32%' THEN LEFT(b.dcRegionId, 4) ELSE 32 END dcRegion, 
		COUNT(*) Cnt,
		SUM(CASE WHEN Paid > 0 THEN 1 ELSE 0 END) CntPaid,
		SUM(Paid) Paid
	INTO #t
	FROM caOrder a, cpMain b
	WHERE a.cpMainId = b.Id
	AND b.dcProvinceId = 32
	AND a.OpenDate > '2017-12-26'
	GROUP BY CONVERT(VARCHAR(6), DATEADD(MONTH, 1, a.OpenDate - 25), 112),
		CASE WHEN b.dcRegionId LIKE '32%' THEN LEFT(b.dcRegionId, 4) ELSE 32 END
	ORDER BY CONVERT(VARCHAR(6), DATEADD(MONTH, 1, a.OpenDate - 25), 112),
		CASE WHEN b.dcRegionId LIKE '32%' THEN LEFT(b.dcRegionId, 4) ELSE 32 END

	SELECT b.Description, a.CountMonth, a.Cnt, a.CntPaid, a.Paid, b.Id INTO #1 FROM #t a, dcRegion b WHERE a.dcRegion = b.ID ORDER BY a.CountMonth, b.Id

	CREATE TABLE #v(
		CountMonth VARCHAR(6),
		Cnt32 INT,
		CntRate32 DECIMAL(9,4),
		Paid32 Decimal(18, 2), 
		PaidRate32 Decimal(9, 4),
		Cnt3201 INT,
		CntRate3201 DECIMAL(9,4),
		Paid3201 Decimal(18, 2), 
		PaidRate3201 Decimal(9, 4),
		Cnt3202 INT,
		CntRate3202 DECIMAL(9,4),
		Paid3202 Decimal(18, 2), 
		PaidRate3202 Decimal(9, 4),
		Cnt3203 INT,
		CntRate3203 DECIMAL(9,4),
		Paid3203 Decimal(18, 2), 
		PaidRate3203 Decimal(9, 4),
		Cnt3204 INT,
		CntRate3204 DECIMAL(9,4),
		Paid3204 Decimal(18, 2), 
		PaidRate3204 Decimal(9, 4),
		Cnt3205 INT,
		CntRate3205 DECIMAL(9,4),
		Paid3205 Decimal(18, 2), 
		PaidRate3205 Decimal(9, 4),
		Cnt3206 INT,
		CntRate3206 DECIMAL(9,4),
		Paid3206 Decimal(18, 2), 
		PaidRate3206 Decimal(9, 4),
		Cnt3207 INT,
		CntRate3207 DECIMAL(9,4),
		Paid3207 Decimal(18, 2), 
		PaidRate3207 Decimal(9, 4),
		Cnt3208 INT,
		CntRate3208 DECIMAL(9,4),
		Paid3208 Decimal(18, 2), 
		PaidRate3208 Decimal(9, 4),
		Cnt3209 INT,
		CntRate3209 DECIMAL(9,4),
		Paid3209 Decimal(18, 2), 
		PaidRate3209 Decimal(9, 4),
		Cnt3210 INT,
		CntRate3210 DECIMAL(9,4),
		Paid3210 Decimal(18, 2), 
		PaidRate3210 Decimal(9, 4),
		Cnt3211 INT,
		CntRate3211 DECIMAL(9,4),
		Paid3211 Decimal(18, 2), 
		PaidRate3211 Decimal(9, 4),
		Cnt3212 INT,
		CntRate3212 DECIMAL(9,4),
		Paid3212 Decimal(18, 2), 
		PaidRate3212 Decimal(9, 4),
		Cnt3213 INT,
		CntRate3213 DECIMAL(9,4),
		Paid3213 Decimal(18, 2), 
		PaidRate3213 Decimal(9, 4),
		Cnt3214 INT,
		CntRate3214 DECIMAL(9,4),
		Paid3214 Decimal(18, 2), 
		PaidRate3214 Decimal(9, 4),
		Cnt3215 INT,
		CntRate3215 DECIMAL(9,4),
		Paid3215 Decimal(18, 2), 
		PaidRate3215 Decimal(9, 4),
		Cnt3216 INT,
		CntRate3216 DECIMAL(9,4),
		Paid3216 Decimal(18, 2), 
		PaidRate3216 Decimal(9, 4),
		Cnt3217 INT,
		CntRate3217 DECIMAL(9,4),
		Paid3217 Decimal(18, 2), 
		PaidRate3217 Decimal(9, 4),
		CntAll INT,
		PaidAll Decimal(18, 2)
	)

	DECLARE @M INT, @Id INT, @CntAll INT, @paidAll DECIMAL(18, 2), @Cnt INT, @Paid DECIMAL(18, 2), @Sql VARCHAR(MAX)
	SELECT @M = 0, @Id = 0
	WHILE EXISTS(SELECT 'x' FROM #1 WHERE CountMonth > @m)
	BEGIN
		SELECT TOP 1 @M = CountMonth FROM #1 WHERE CountMonth > @m ORDER BY CountMonth, Id
		SELECT @CntAll = SUM(Cnt), @PaidAll = SUM(Paid) FROM #1 WHERE CountMonth = @m
		INSERT INTO #v(CountMonth, CntAll, PaidAll) SELECT @m, @CntAll, @PaidAll
		WHILE EXISTS(SELECT 'x' FROM #1 WHERE CountMonth = @m AND Id > @Id)
		BEGIN
			SELECT TOP 1 @Id = Id, @Cnt = Cnt, @Paid = Paid FROM #1 WHERE CountMonth = @m AND Id > @id ORDER BY Id
			SET @Sql = 'UPDATE #v SET Cnt' + LTRIM(STR(@Id)) + ' = ' + LTRIM(STR(@Cnt)) 
				+ ', CntRate' + LTRIM(STR(@Id)) + ' = ' + CONVERT(VARCHAR(20), @Cnt * 100.0 / @CntAll)
				+ ', Paid' + LTRIM(STR(@Id)) + ' = ' + CONVERT(VARCHAR(20), @Paid)
				+ ', PaidRate' + LTRIM(STR(@Id)) + ' = ' + CONVERT(VARCHAR(20), @Paid * 100.0 / @PaidAll)
				+ ' WHERE CountMonth = ' + LTRIM(STR(@m))
			EXEC(@Sql)
		END
		SET @Id = 0
	END

	SELECT * FROM #1
	SELECT * FROM #v
END
GO

/****** Object:  StoredProcedure [dbo].[spcaOrderByCountProvinceSelect]    Script Date: 2018/12/13 19:12:59 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[spcaOrderByCountProvinceSelect]
AS
SET NOCOUNT ON
BEGIN
	SELECT CONVERT(VARCHAR(6), DATEADD(MONTH, 1, a.OpenDate - 25), 112) CountMonth,
		b.dcProvinceID dcRegion, 
		COUNT(*) Cnt,
		SUM(CASE WHEN Paid > 0 THEN 1 ELSE 0 END) CntPaid,
		SUM(Paid) Paid
	INTO #t
	FROM caOrder a, cpMain b
	WHERE a.cpMainId = b.Id	
	AND a.OpenDate > '2017-12-26'
	GROUP BY CONVERT(VARCHAR(6), DATEADD(MONTH, 1, a.OpenDate - 25), 112), b.dcProvinceID		
	ORDER BY CONVERT(VARCHAR(6), DATEADD(MONTH, 1, a.OpenDate - 25), 112), b.dcProvinceID

	SELECT b.Description, a.CountMonth, a.Cnt, a.CntPaid, a.Paid, b.Id INTO #1 FROM #t a, dcRegion b WHERE a.dcRegion = b.ID AND b.Id < 99  ORDER BY a.CountMonth, b.Id

	CREATE TABLE #v(
		CountMonth VARCHAR(6),
		Cnt10 INT, CntRate10 DECIMAL(9,4), Paid10 Decimal(18, 2), PaidRate10 Decimal(9, 4), 
		Cnt11 INT, CntRate11 DECIMAL(9,4), Paid11 Decimal(18, 2), PaidRate11 Decimal(9, 4), 
		Cnt12 INT, CntRate12 DECIMAL(9,4), Paid12 Decimal(18, 2), PaidRate12 Decimal(9, 4), 
		Cnt13 INT, CntRate13 DECIMAL(9,4), Paid13 Decimal(18, 2), PaidRate13 Decimal(9, 4), 
		Cnt14 INT, CntRate14 DECIMAL(9,4), Paid14 Decimal(18, 2), PaidRate14 Decimal(9, 4), 
		Cnt20 INT, CntRate20 DECIMAL(9,4), Paid20 Decimal(18, 2), PaidRate20 Decimal(9, 4), 
		Cnt21 INT, CntRate21 DECIMAL(9,4), Paid21 Decimal(18, 2), PaidRate21 Decimal(9, 4), 
		Cnt22 INT, CntRate22 DECIMAL(9,4), Paid22 Decimal(18, 2), PaidRate22 Decimal(9, 4), 
		Cnt30 INT, CntRate30 DECIMAL(9,4), Paid30 Decimal(18, 2), PaidRate30 Decimal(9, 4), 
		Cnt31 INT, CntRate31 DECIMAL(9,4), Paid31 Decimal(18, 2), PaidRate31 Decimal(9, 4), 
		Cnt32 INT, CntRate32 DECIMAL(9,4), Paid32 Decimal(18, 2), PaidRate32 Decimal(9, 4), 
		Cnt33 INT, CntRate33 DECIMAL(9,4), Paid33 Decimal(18, 2), PaidRate33 Decimal(9, 4), 
		Cnt34 INT, CntRate34 DECIMAL(9,4), Paid34 Decimal(18, 2), PaidRate34 Decimal(9, 4), 
		Cnt35 INT, CntRate35 DECIMAL(9,4), Paid35 Decimal(18, 2), PaidRate35 Decimal(9, 4), 
		Cnt36 INT, CntRate36 DECIMAL(9,4), Paid36 Decimal(18, 2), PaidRate36 Decimal(9, 4), 
		Cnt40 INT, CntRate40 DECIMAL(9,4), Paid40 Decimal(18, 2), PaidRate40 Decimal(9, 4), 
		Cnt41 INT, CntRate41 DECIMAL(9,4), Paid41 Decimal(18, 2), PaidRate41 Decimal(9, 4), 
		Cnt42 INT, CntRate42 DECIMAL(9,4), Paid42 Decimal(18, 2), PaidRate42 Decimal(9, 4), 
		Cnt60 INT, CntRate60 DECIMAL(9,4), Paid60 Decimal(18, 2), PaidRate60 Decimal(9, 4), 
		Cnt61 INT, CntRate61 DECIMAL(9,4), Paid61 Decimal(18, 2), PaidRate61 Decimal(9, 4), 
		Cnt62 INT, CntRate62 DECIMAL(9,4), Paid62 Decimal(18, 2), PaidRate62 Decimal(9, 4), 
		Cnt63 INT, CntRate63 DECIMAL(9,4), Paid63 Decimal(18, 2), PaidRate63 Decimal(9, 4), 
		Cnt64 INT, CntRate64 DECIMAL(9,4), Paid64 Decimal(18, 2), PaidRate64 Decimal(9, 4), 
		Cnt70 INT, CntRate70 DECIMAL(9,4), Paid70 Decimal(18, 2), PaidRate70 Decimal(9, 4), 
		Cnt71 INT, CntRate71 DECIMAL(9,4), Paid71 Decimal(18, 2), PaidRate71 Decimal(9, 4), 
		Cnt72 INT, CntRate72 DECIMAL(9,4), Paid72 Decimal(18, 2), PaidRate72 Decimal(9, 4), 
		Cnt80 INT, CntRate80 DECIMAL(9,4), Paid80 Decimal(18, 2), PaidRate80 Decimal(9, 4), 
		Cnt81 INT, CntRate81 DECIMAL(9,4), Paid81 Decimal(18, 2), PaidRate81 Decimal(9, 4), 
		Cnt82 INT, CntRate82 DECIMAL(9,4), Paid82 Decimal(18, 2), PaidRate82 Decimal(9, 4), 
		Cnt83 INT, CntRate83 DECIMAL(9,4), Paid83 Decimal(18, 2), PaidRate83 Decimal(9, 4), 
		Cnt84 INT, CntRate84 DECIMAL(9,4), Paid84 Decimal(18, 2), PaidRate84 Decimal(9, 4), 
		CntAll INT,
		PaidAll Decimal(18, 2)
	)
	
	DECLARE @M INT, @Id INT, @CntAll INT, @paidAll DECIMAL(18, 2), @Cnt INT, @Paid DECIMAL(18, 2), @Sql VARCHAR(MAX)
	SELECT @M = 0, @Id = 0
	WHILE EXISTS(SELECT 'x' FROM #1 WHERE CountMonth > @m)
	BEGIN
		SELECT TOP 1 @M = CountMonth FROM #1 WHERE CountMonth > @m ORDER BY CountMonth, Id
		SELECT @CntAll = SUM(Cnt), @PaidAll = SUM(Paid) FROM #1 WHERE CountMonth = @m
		INSERT INTO #v(CountMonth, CntAll, PaidAll) SELECT @m, @CntAll, @PaidAll
		WHILE EXISTS(SELECT 'x' FROM #1 WHERE CountMonth = @m AND Id > @Id)
		BEGIN
			SELECT TOP 1 @Id = Id, @Cnt = Cnt, @Paid = Paid FROM #1 WHERE CountMonth = @m AND Id > @id ORDER BY Id
			SET @Sql = 'UPDATE #v SET Cnt' + LTRIM(STR(@Id)) + ' = ' + LTRIM(STR(@Cnt)) 
				+ ', CntRate' + LTRIM(STR(@Id)) + ' = ' + CONVERT(VARCHAR(20), @Cnt * 100.0 / @CntAll)
				+ ', Paid' + LTRIM(STR(@Id)) + ' = ' + CONVERT(VARCHAR(20), @Paid)
				+ ', PaidRate' + LTRIM(STR(@Id)) + ' = ' + CONVERT(VARCHAR(20), @Paid * 100.0 / @PaidAll)
				+ ' WHERE CountMonth = ' + LTRIM(STR(@m))
			EXEC(@Sql)
		END
		SET @Id = 0
	END

	SELECT * FROM #1
	SELECT '月份', '北京', '北京', '北京', '北京', '天津', '天津', '天津', '天津', '河北', '河北', '河北', '河北', '内蒙古', '内蒙古', '内蒙古', '内蒙古', '山西', '山西', '山西', '山西', '辽宁', '辽宁', '辽宁', '辽宁', '吉林', '吉林', '吉林', '吉林', '黑龙江', '黑龙江', '黑龙江', '黑龙江', '上海', '上海', '上海', '上海', '江苏', '江苏', '江苏', '江苏', '山东', '山东', '山东', '山东', '安徽', '安徽', '安徽', '安徽', '福建', '福建', '福建', '福建', '浙江', '浙江', '浙江', '浙江', '江西', '江西', '江西', '江西', '广东', '广东', '广东', '广东', '广西', '广西', '广西', '广西', '海南', '海南', '海南', '海南', '重庆', '重庆', '重庆', '重庆', '四川', '四川', '四川', '四川', '云南', '云南', '云南', '云南', '贵州', '贵州', '贵州', '贵州', '西藏', '西藏', '西藏', '西藏', '河南', '河南', '河南', '河南', '湖北', '湖北', '湖北', '湖北', '湖南', '湖南', '湖南', '湖南', '陕西', '陕西', '陕西', '陕西', '青海', '青海', '青海', '青海', '宁夏', '宁夏', '宁夏', '宁夏', '新疆', '新疆', '新疆', '新疆', '甘肃', '甘肃', '甘肃', '甘肃', '总数量', '总金额'
	SELECT * FROM #v
END
GO

/****** Object:  StoredProcedure [dbo].[spChangeInvoiceCompany]    Script Date: 2018/12/13 19:12:59 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

create procedure [dbo].[spChangeInvoiceCompany]
(
	@caorderId INT,
	@invoiceCompanyId INT
)
AS
	update caorder set invoicecompany=@invoiceCompanyId where id = @caorderId
	 
GO

/****** Object:  StoredProcedure [dbo].[spChangeManagerUser]    Script Date: 2018/12/13 19:13:00 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

create Procedure [dbo].[spChangeManagerUser]
(
	@OldId int,
	@NewId int
)
AS
BEGIN
	DECLARE @UserNAme VARCHAR(20), @Password VARCHAR(20), @Name VARCHAR(20), @Name_Eng VARCHAR(20), @Status INT, @LoginStatus INT
	SELECT @UserName = UserName,
		@Password = [REDACTED]
		@Name_Eng = Name_Eng,
		@Name = Name,
		@Status = Status,
		@LoginStatus = LoginStatus
	FROM ManagerUser
	WHERE Id = @OldId

	UPDATE ManagerUser SET UserName = @UserName + '##',
		Password = [REDACTED] + '##',
		Name_Eng = @Name_Eng + '##',
		Name = @Name + '##',
		Status = 3,
		LoginStatus = 2
	WHERE Id = @OldID

	UPDATE ManagerUser SET UserName = @UserName,
		Password = [REDACTED] = @Name_Eng,
		Name = @Name,
		Status = @Status,
		LoginStatus = @LoginStatus
	WHERE Id = @NewID
END
GO

/****** Object:  StoredProcedure [dbo].[spCheckHomepageRefresh]    Script Date: 2018/12/13 19:13:00 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[spCheckHomepageRefresh]
AS
BEGIN
	begin try
	  drop table #t
	end try
	begin catch
	end catch

	select * 
	into #t
	from cpmain where membertype>0
	and refreshdate >getdate()-1
	and valid=1

	delete #t where id in (select cpmainid from searchdb..cpMainHomepageSnapshot)

	select refreshdate r,jobnumber,* from #t order by refreshdate
END









GO

/****** Object:  StoredProcedure [dbo].[spCommentsHotUpdate]    Script Date: 2018/12/13 19:13:00 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[spCommentsHotUpdate]
AS
SET NOCOUNT ON
BEGIN
	DECLARE curProvince CURSOR FOR 
		SELECT ID, IsMainSite FROM dcSubSite WITH(NOLOCK) WHERE IsMainSite = 1 OR ID LIKE '32%' ORDER BY ID
	OPEN curProvince
	DECLARE @dcProvinceID INT, @IsMainSite BIT
	FETCH NEXT FROM curProvince INTO @dcProvinceID, @IsMainSite

	WHILE @@FETCH_STATUS = 0
	BEGIN
		DELETE SearchDb..CommentsHot WHERE dcProvinceID = @dcProvinceID

		--点评最多排行
		INSERT INTO SearchDb..CommentsHot
		SELECT @dcProvinceID, a.SecondID, a.Name, b.CpMainID, 1, 1, b.cnt
		FROM CpMain a, (
			 SELECT TOP 10 COUNT(*) cnt, a.CpMainID
			 FROM Comments a, CpMain b
			 WHERE (a.CommentType = 1 OR a.CommentType = 2)
			 AND a.CpMainID = b.ID
			 AND b.dcRegionID like '' + CONVERT(VARCHAR(6), @dcProvinceID) + '%'
			 AND a.CpMainID IN(
				SELECT TOP 99999 MAX(a.CpmainID)
				FROM Comments a, Cpmain b
				WHERE a.CpMainID = b.ID
				AND IsDirect = 1
				GROUP BY b.Name	 
			 )
			 GROUP BY a.CpMainID
			 ORDER BY cnt DESC
			)b
			WHERE a.ID = b.CpMainID
			
		--最佳点评排行
		INSERT INTO SearchDb..CommentsHot
		SELECT @dcProvinceID, a.SecondID, a.Name, b.CpMainID, 1, 2, b.cnt
		FROM CpMain a, (
			SELECT TOP 10 COUNT(*) cnt, a.CpMainID
			FROM Comments a, CpMain b
			WHERE a.CommentType = 2
			AND a.CpMainID = b.ID
			AND b.dcRegionID like ''+CONVERT(VARCHAR(6), dcProvinceID)+'%'
			AND a.CpMainID IN(
				SELECT TOP 99999 MAX(a.CpmainID)
				FROM Comments a, Cpmain b
				WHERE a.CpMainID = b.ID
				AND IsDirect = 1
				GROUP BY b.Name	 
				)
			GROUP BY a.CpMainID
			ORDER BY cnt DESC
			)b
		WHERE a.ID = b.CpMainID
		
		--面经最多排行
		INSERT INTO SearchDb..CommentsHot
		SELECT @dcProvinceID, a.SecondID, a.Name, b.CpMainID, 2, 1, b.cnt
		FROM CpMain a, (
			SELECT TOP 10 COUNT(*) cnt, a.CpMainID
			FROM InterView a, CpMain b
			WHERE (a.InterViewType = 1 OR a.InterViewType = 2)
			AND a.CpMainID = b.ID
			AND b.dcRegionID like ''+CONVERT(VARCHAR(6), @dcProvinceID)+'%'
			AND a.CpMainID IN(
				SELECT TOP 99999 MAX(a.CpmainID)
				FROM InterView a, Cpmain b
				WHERE a.CpMainID = b.ID
				AND IsDirect = 1
				GROUP BY b.Name	 
				)
			GROUP BY a.CpMainID
			ORDER BY cnt DESC
			)b
		WHERE a.ID = b.CpMainID
		
		--最佳面经排行
		INSERT INTO SearchDb..CommentsHot
		SELECT @dcProvinceID, a.SecondID, a.Name, b.CpMainID, 2, 2, b.cnt 
		FROM CpMain a, (SELECT TOP 10 COUNT(*) cnt, a.CpMainID
			FROM InterView a, CpMain b
			WHERE a.InterViewType = 2
			AND a.CpMainID = b.ID
			AND b.dcRegionID like ''+CONVERT(VARCHAR(6), @dcProvinceID)+'%'
			AND a.CpMainID IN(
				SELECT TOP 99999 MAX(a.CpmainID)
				FROM InterView a, Cpmain b
				WHERE a.CpMainID = b.ID
				AND IsDirect = 1
				GROUP BY b.Name	 
				)
			GROUP BY a.CpMainID
			ORDER BY cnt DESC
			)b
		WHERE a.ID = b.CpMainID
	 
		DELETE SearchDb..Hp_Comments WHERE ProvinceId = @dcProvinceID
		
		INSERT INTO SearchDb..Hp_Comments
		SELECT TOP 8 @dcProvinceID, * 
		FROM (SELECT * 
			FROM (SELECT TOP 8 a.ID, a.CpMainID, LEFT(CASE WHEN Relation IN (1, 3) THEN Remark1 ELSE Remark2 END, 60) AS Title,
					a.AddDate, 1 AS CIType, a.CommentType AS IsGood, b.Name, b.SecondID, 1 CommentType
				FROM Comments a WITH(NOLOCK), CpMain b WITH(NOLOCK)
				WHERE a.CommentType IN (1, 2) 
				AND a.CpMainID = b.ID 
				AND b.dcRegionID like ''+CONVERT(VARCHAR(6), @dcProvinceID)+'%' 
				AND a.IsDirect = 1
				AND b.Valid = 1
				AND (SELECT COUNT(1) FROM Job WITH(NOLOCK) WHERE cpMainID = b.id AND Valid = 1) > 0
				ORDER BY a.AddDate DESC
				) AS tempComment
			UNION 
			SELECT * 
			FROM (SELECT TOP 8 a.ID, a.CpMainID, a.Title, a.AddDate, 2 AS CIType, 
					a.InterviewType AS IsGood, b.Name, b.SecondID, 2 CommentType
				FROM InterView a WITH(NOLOCK), cpmain b WITH(NOLOCK)
				WHERE a.InterviewType IN (1, 2) 
				AND a.CpMainID = b.ID 
				AND b.dcRegionID like ''+CONVERT(VARCHAR(6), @dcProvinceID)+'%'
				AND a.IsDirect = 1
				AND b.Valid = 1
				AND (SELECT COUNT(1) FROM Job WITH(NOLOCK) WHERE cpMainID = b.id AND Valid = 1) > 0
				ORDER BY a.AddDate DESC
				) AS tempInterview
			) AS CIResult 
		ORDER BY AddDate DESC
 
		FETCH NEXT FROM curProvince INTO @dcProvinceID, @IsMainSite
	END

	CLOSE curProvince
	DEALLOCATE curProvince
END
GO

/****** Object:  StoredProcedure [dbo].[SPCopyMainDBTOTestDb]    Script Date: 2018/12/13 19:13:01 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SPCopyMainDBTOTestDb]
(
	@s varchar(10),
	@e varchar(10)
)
AS
BEGIN
	SET NOCOUNT ON
	PRINT 'SET NOCOUNT ON'
	PRINT '
BEGIN TRY 
	DROP TABLE #s
END TRY
BEGIN CATCH
END CATCH
BEGIN TRY 
	DROP TABLE #b
END TRY
BEGIN CATCH
END CATCH

CREATE TABLE #S(Name VARCHAR(100))
CREATE TABLE #b(Name VARCHAR(100))'
	SELECT ID, Name 
	INTO #t
	FROM testdb..sysObjects
	WHERe xType = 'u'
	AND Name NOT LIKE 'sys%'
	AND Name NOT LIKE 'ms%'
	and name >= @s
	and name < @e

	DECLARE @Name VARCHAR(100), @Id INT, @SQL VARCHAR(MAX), @ColName VARCHAR(MAX), @IIBegin VARCHAR(MAX), @IIEnd VARCHAR(MAX),
		@WHERE VARCHAR(MAX), @Order VARCHAR(MAX)
	
	SELECT TOP 1 @Name = Name, @Id = ID FROM #t order BY NAME
	WHILE @Name > ''
	BEGIN
		SELECT @ColName = ''
		SELECT @ColName =  @ColName + NAME + ', ' FROM SysColumns WHERE ID = @ID AND colstat <> 4
		SELECT @ColName = LTRIM(RTRIM(@ColName))
		SELECT @ColName = LEFT(@ColName, LEN(@ColName) - 1)

		SELECT @IIBegin = '', @IIEND = '', @WHERE = '', @Order = ''
		IF EXISTS(SELECT 'x' FROM sysColumns WHERE ID = @ID AND NAME = 'ID' AND ColStat = 1)
		BEGIN
			SELECT @IIBegin = 'SET IDENTITY_INSERT ' + @Name + ' ON', @IIEND = 'SET IDENTITY_INSERT ' + @Name + ' OFF', @Order = ' ORDER BY ID DESC'
		END
		IF EXISTS(SELECT 'x' FROM sysColumns WHERE ID = @ID AND NAME = 'paMainID')
			SET @WHERE = CASE WHEN @WHERE = '' THEN ' WHERE ' ELSE @WHERE + ' AND ' END + 'paMainID IN(SELECT ID FROM TestDb..TmpPaMain)'
		IF EXISTS(SELECT 'x' FROM sysColumns WHERE ID = @ID AND NAME = 'cvMainID')
			SET @WHERE = CASE WHEN @WHERE = '' THEN ' WHERE ' ELSE @WHERE + ' AND ' END + 'cvMainID IN(SELECT ID FROM TestDb..TmpcvMain)'
		IF EXISTS(SELECT 'x' FROM sysColumns WHERE ID = @ID AND NAME = 'cpMainID')
			SET @WHERE = CASE WHEN @WHERE = '' THEN ' WHERE ' ELSE @WHERE + ' AND ' END + 'cpMainID IN(SELECT ID FROM TestDb..TmpcpMain)'
		IF EXISTS(SELECT 'x' FROM sysColumns WHERE ID = @ID AND NAME = 'CompanyId')
			SET @WHERE = CASE WHEN @WHERE = '' THEN ' WHERE ' ELSE @WHERE + ' AND ' END + 'CompanyId IN(SELECT ID FROM TestDb..TmpcpMain)'
		IF EXISTS(SELECT 'x' FROM sysColumns WHERE ID = @ID AND NAME = 'caMainID')
			SET @WHERE = CASE WHEN @WHERE = '' THEN ' WHERE ' ELSE @WHERE + ' AND ' END + 'caMainID IN(SELECT ID FROM TestDb..TmpcaMain)'
		IF EXISTS(SELECT 'x' FROM sysColumns WHERE ID = @ID AND NAME = 'JobID')
			SET @WHERE = CASE WHEN @WHERE = '' THEN ' WHERE ' ELSE @WHERE + ' AND ' END + 'JobID IN(SELECT ID FROM TestDb..TmpJob)'

		SET @SQL = 
'IF ((SELECT COUNT(*) FROM ' + @NAME + ') > 0 AND (SELECT COUNT(*) FROM ' + @NAME + ') = 0)
BEGIN TRY
	' + @IIBegin + '
	INSERT INTO TestDb..' + @Name + '(' + @ColName + ') 
	SELECT TOP 10000 ' + @ColName + ' FROM ' + @Name + @Where + + @Order + '
	' + @IIEnd + '
	PRINT ''' + @Name + ' IS Sucessed!''
	INSERT #s SELECT ''' + @Name + '''
END TRY
BEGIN CATCH
	' + @IIEnd + '
	PRINT ''' + @Name + ' IS BAD!!!!!!!!!!!!!!!!!!!!''
	INSERT #b SELECT ''' + @Name + '''
END CATCH
GO

'
		--PRINT @SQL
		SELECT TOP 1 @Name = Name, @Id = ID FROM #t WHERE Name > @Name ORDER BY NAME
		IF @@ROWCOUNT = 0
			SELECT @Name = ''
	END
	DROP TABLE #t
	PRINT ' SELECT * FROM #b'
	PRINT ' SELECT * FROM #s'
END










GO

/****** Object:  StoredProcedure [dbo].[SPCopySearchDbTOTestDb]    Script Date: 2018/12/13 19:13:01 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SPCopySearchDbTOTestDb]
AS
BEGIN
	SET NOCOUNT ON
	PRINT 'SET NOCOUNT ON'
	PRINT '
BEGIN TRY 
	DROP TABLE #s
END TRY
BEGIN CATCH
END CATCH
BEGIN TRY 
	DROP TABLE #b
END TRY
BEGIN CATCH
END CATCH

CREATE TABLE #S(Name VARCHAR(100))
CREATE TABLE #b(Name VARCHAR(100))'
	SELECT ID, Name 
	INTO #t
	FROM testdb..sysObjects
	WHERe xType = 'u'
	AND Name NOT LIKE 'sys%'
	AND Name NOT LIKE 'ms%'

	DECLARE @Name VARCHAR(100), @Id INT, @SQL VARCHAR(MAX), @ColName VARCHAR(MAX), @IIBegin VARCHAR(MAX), @IIEnd VARCHAR(MAX),
		@WHERE VARCHAR(MAX), @Order VARCHAR(MAX)
	
	SELECT TOP 1 @Name = Name, @Id = ID FROM #t order BY NAME
	WHILE @Name > ''
	BEGIN
		SELECT @ColName = ''
		SELECT @ColName =  @ColName + NAME + ', ' FROM SysColumns WHERE ID = @ID AND colstat <> 4
		SELECT @ColName = LTRIM(RTRIM(@ColName))
		SELECT @ColName = LEFT(@ColName, LEN(@ColName) - 1)

		SELECT @IIBegin = '', @IIEND = '', @WHERE = '', @Order = ''
		IF EXISTS(SELECT 'x' FROM sysColumns WHERE ID = @ID AND NAME = 'ID' AND ColStat = 1)
		BEGIN
			SELECT @IIBegin = 'SET IDENTITY_INSERT ' + @Name + ' ON', @IIEND = 'SET IDENTITY_INSERT ' + @Name + ' OFF', @Order = ' ORDER BY ID DESC'
		END
		IF EXISTS(SELECT 'x' FROM sysColumns WHERE ID = @ID AND NAME = 'paMainID')
			SET @WHERE = CASE WHEN @WHERE = '' THEN ' WHERE ' ELSE @WHERE + ' AND ' END + 'paMainID IN(SELECT ID FROM TestDb..TmpPaMain)'
		IF EXISTS(SELECT 'x' FROM sysColumns WHERE ID = @ID AND NAME = 'cvMainID')
			SET @WHERE = CASE WHEN @WHERE = '' THEN ' WHERE ' ELSE @WHERE + ' AND ' END + 'cvMainID IN(SELECT ID FROM TestDb..TmpcvMain)'
		IF EXISTS(SELECT 'x' FROM sysColumns WHERE ID = @ID AND NAME = 'cpMainID')
			SET @WHERE = CASE WHEN @WHERE = '' THEN ' WHERE ' ELSE @WHERE + ' AND ' END + 'cpMainID IN(SELECT ID FROM TestDb..TmpcpMain)'
		IF EXISTS(SELECT 'x' FROM sysColumns WHERE ID = @ID AND NAME = 'CompanyId')
			SET @WHERE = CASE WHEN @WHERE = '' THEN ' WHERE ' ELSE @WHERE + ' AND ' END + 'CompanyId IN(SELECT ID FROM TestDb..TmpcpMain)'
		IF EXISTS(SELECT 'x' FROM sysColumns WHERE ID = @ID AND NAME = 'caMainID')
			SET @WHERE = CASE WHEN @WHERE = '' THEN ' WHERE ' ELSE @WHERE + ' AND ' END + 'caMainID IN(SELECT ID FROM TestDb..TmpcaMain)'
		IF EXISTS(SELECT 'x' FROM sysColumns WHERE ID = @ID AND NAME = 'JobID')
			SET @WHERE = CASE WHEN @WHERE = '' THEN ' WHERE ' ELSE @WHERE + ' AND ' END + 'JobID IN(SELECT ID FROM TestDb..TmpJob)'

		SET @SQL = 
'IF ((SELECT COUNT(*) FROM searchdb..' + @NAME + ') > 0 AND (SELECT COUNT(*) FROM ' + @NAME + ') = 0)
BEGIN TRY
	' + @IIBegin + '
	INSERT INTO TestDb..' + @Name + '(' + @ColName + ') 
	SELECT TOP 10000 ' + @ColName + ' FROM searchdb..' + @Name + @Where + + @Order + '
	' + @IIEnd + '
	PRINT ''' + @Name + ' IS Sucessed!''
	INSERT #s SELECT ''' + @Name + '''
END TRY
BEGIN CATCH
	' + @IIEnd + '
	PRINT ''' + @Name + ' IS BAD!!!!!!!!!!!!!!!!!!!!''
	INSERT #b SELECT ''' + @Name + '''
END CATCH
GO

'
		--PRINT @SQL
		SELECT TOP 1 @Name = Name, @Id = ID FROM #t WHERE Name > @Name ORDER BY NAME
		IF @@ROWCOUNT = 0
			SELECT @Name = ''
	END
	DROP TABLE #t
	PRINT ' SELECT * FROM #b'
	PRINT ' SELECT * FROM #s'
END










GO

/****** Object:  StoredProcedure [dbo].[SPCountyJobRebuild]    Script Date: 2018/12/13 19:13:02 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SPCountyJobRebuild]
AS
BEGIN
	IF DATEPART(HOUR, GETDATE()) < 10
		TRUNCATE TABLE SearchDb..CountyJob

	TRUNCATE TABLE SearchDb..CountyJobNumber
	INSERT INTO SearchDb..CountyJobNumber
	SELECT LEFT(dcRegionId, 2), COUNT(*) FROM JobPublish WITH(NOLOCK) WHERE Valid = 1 GROUP BY LEFT(dcRegionId, 2)
END






GO

/****** Object:  StoredProcedure [dbo].[SpCpCvPriviByFixSave]    Script Date: 2018/12/13 19:13:02 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SpCpCvPriviByFixSave]
AS
SET NOCOUNT ON
BEGIN
	SELECT TOP 0 * INTO #p FROM cpCvPrivi
	SELECT Id INTO #cp FROM cpMain WHERE Membertype > 1 AND IsLimitLogin IN(0, 1) AND LastLoginDate > GETDATE() - 183

	CREATE TABLE #t(cpMainId INT, paMainId INT)

	INSERT INTO #t
	SELECT a.cpMainId, b.paMainId
	FROM caActiveLog a WITH(NOLOCK INDEX(IX_caActiveLog_cpMainID)),
		cvMain b WITH(NOLOCK)
	WHERE a.cpMainID IN(SELECT Id FROM #cp)
	AND a.AddDate > DATEADD(MINUTE, -120, GETDATE())
	AND a.cvMainId = b.Id

	INSERT INTO #t
	SELECT b.cpMainId, c.paMainId
	FROM ExJobApply a WITH(NOLOCK), Job b, cvMain c
	WHERE a.JobID = b.ID
	AND a.IsPassed = 1 
	AND a.cvMainID = c.Id
	AND a.AddDate > DATEADD(MINUTE, -120, GETDATE())

	INSERT INTO #p(cpMainId, cvMainId)
	SELECT DISTINCT a.cpMainId, b.Id
	FROM #t a, cvMain b
	WHERE a.paMainId = b.paMainId

	INSERT INTO #p(cpMainId, cvMainId)
	SELECT cpMainId, cvMainId
	FROM caDailyGiftLog WITH(NOLOCK INDEX(PK_caDailyGiftLog))
	WHERE cpMainID IN(SELECT ID FROM #Cp)
	AND AddDate > DATEADD(MINUTE, -120, GETDATE())
	AND NOT EXISTS(SELECT 'x' FROM #p WHERE #p.cpMainId = caDailyGiftLog.cpMainId AND #p.cvMainId = caDailyGiftLog.cvMainId)

	INSERT INTO #p(cpMainId, cvMainId)
	SELECT cpMainId, cvMainId
	FROM caDailyGiftLog WITH(NOLOCK INDEX(PK_caDailyGiftLog))
	WHERE cpMainID IN(SELECT ID FROM #Cp)
	AND AddDate > DATEADD(MINUTE, -120, GETDATE())
	AND NOT EXISTS(SELECT 'x' FROM #p WHERE #p.cpMainId = caDailyGiftLog.cpMainId AND #p.cvMainId = caDailyGiftLog.cvMainId)

	INSERT INTO cpCvPrivi
	SELECT cpMainId, cvMainId
	FROM #p
	WHERE NOT EXISTS(SELECT 'x' FROM cpCvPrivi WHERE #p.cpMainId = cpCvPrivi.cpMainId AND #p.cvMainId = cpCvPrivi.cvMainId)
END
GO

/****** Object:  StoredProcedure [dbo].[SpCpCvPriviSave]    Script Date: 2018/12/13 19:13:02 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SpCpCvPriviSave]
AS
SET NOCOUNT ON
BEGIN
	SELECT Id INTO #cp FROM cpMain WHERE Membertype > 1 AND IsLimitLogin IN(0, 1) AND LastLoginDate > GETDATE() - 183

	CREATE TABLE #t(cpMainId INT, paMainId INT)

	INSERT INTO #t
	SELECT a.cpMainId, b.paMainId
	FROM caActiveLog a WITH(NOLOCK INDEX(IX_caActiveLog_cpMainID)),
		cvMain b WITH(NOLOCK)
	WHERE a.cpMainID IN(SELECT Id FROM #cp)
	AND a.AddDate > GETDATE() - 183
	AND a.cvMainId = b.Id

	INSERT INTO #t
	SELECT b.cpMainId, c.paMainId
	FROM ExJobApply a WITH(NOLOCK), Job b, cvMain c
	WHERE a.JobID = b.ID
	AND a.IsPassed = 1 
	AND a.cvMainID = c.Id
	AND a.AddDate > GETDATE() - 183

	TRUNCATE TABLE LogDb..cpCvPrivi

	INSERT INTO cpCvPrivi(cpMainId, cvMainId)
	SELECT DISTINCT a.cpMainId, b.Id
	FROM #t a, cvMain b
	WHERE a.paMainId = b.paMainId

	INSERT INTO cpCvPrivi(cpMainId, cvMainId)
	SELECT cpMainId, cvMainId
	FROM caDailyGiftLog WITH(NOLOCK INDEX(PK_caDailyGiftLog))
	WHERE cpMainID IN(SELECT ID FROM #Cp)
	AND AddDate > GETDATE() - 183
	AND NOT EXISTS(SELECT 'x' FROM cpCvPrivi WHERE cpCvPrivi.cpMainId = caDailyGiftLog.cpMainId AND cpCvPrivi.cvMainId = caDailyGiftLog.cvMainId)
END
GO

/****** Object:  StoredProcedure [dbo].[spCpMainByChar0Fix]    Script Date: 2018/12/13 19:13:02 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[spCpMainByChar0Fix]
AS
BEGIN
	create table #t(id int)
	create table #tt(id int)
--cpMain
	insert into #t Select id from cpMain where UNICODE(right(Name,1)) = 0
	update cpMain set name=SUBSTRING(name, 1, LEN(name) - 1) where id in (select id from #t)
	DELETE #t

	INSERT INTO #t Select id from cpMain where UNICODE(right(brief,1)) = 0
	update cpMain set brief=SUBSTRING(brief, 1, LEN(brief) - 1) where id in (select id from #t)
	DELETE #t
--job
	INSERT INTO #t Select id from Job where UNICODE(right(Responsibility,1)) = 0
	update Job set Responsibility=SUBSTRING(Responsibility, 1, LEN(Responsibility) - 1) where id in (select id from #t)
	DELETE #t

	INSERT INTO #t Select id from Job where UNICODE(right(Demand,1)) = 0
	update Job set Demand=SUBSTRING(Demand, 1, LEN(Demand) - 1) where id in (select id from #t)
	DELETE #t

	INSERT INTO #t Select id from Job where UNICODE(right(name,1)) = 0
	update Job set name=SUBSTRING(name, 1, LEN(name) - 1) where id in (select id from #t)
	DELETE #t
 	 
--////////////////////////
	drop table #t
	drop table #tt
end













GO

/****** Object:  StoredProcedure [dbo].[SpCpMainByCommentNumberFix]    Script Date: 2018/12/13 19:13:03 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SpCpMainByCommentNumberFix]
AS
BEGIN
	UPDATE cpMain set CommentNumber =0 WHERE CommentNumber > 0
	UPDATE cpMain set InterViewNumber = 0 WHERE InterViewNumber > 0

	UPDATE a set a.InterViewNumber = b.Cnt
	from cpmain a,
	(select cpMainId, COUNT(*) Cnt
	from InterView
	where InterViewType <> 3
	group by cpMainId) b
	WHERE a.Id = b.cpMainId


	UPDATE a set a.CommentNumber = b.Cnt
	from cpmain a,
	(select cpMainId, COUNT(*) Cnt
	from Comments
	where CommentType <> 3
	group by cpMainId) b
	WHERE a.Id = b.cpMainId
END
GO

/****** Object:  StoredProcedure [dbo].[SpCpMainByConsultantIdFromColdCustomerUpdate]    Script Date: 2018/12/13 19:13:03 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--修改harry,增加顾问rtx提醒2017-5-17
--修改Peter，增加顾问RTX冷客户提醒
--修改：增加推广认证后分配2018-1-3 harry
--修改：harry 去掉冷客户部门，修改分配过程
/*
sean 2018-2-28
Vicky(762姜乐文) 02-28 08:41:16
公司名称：烟台德霖日化科技有限公司 公司编号：10683832 
765的客户已经产生二次续费，但是该客户是765的置顶广告，多次合作，到期依然要续约的客户，申请保留这个广告客户，谢谢
*/
CREATE PROCEDURE [dbo].[SpCpMainByConsultantIdFromColdCustomerUpdate]
AS
SET NOCOUNT ON
BEGIN
	CREATE TABLE #t(ConsultantId INT, ID INT, Name VARCHAR(100),RegDate DATETIME, DeptId INT)
	/*
 	INSERT INTO #t(ConsultantId, Id, Name,RegDate,DeptId) 
	SELECT ConsultantId, Id, Name,RegDate,42 AS DeptId  
	FROM cpMain WITH(NOLOCK) 
	WHERE MemberType = 3 
	AND ConsultantId IN(SELECT ID FROM ManagerUser WITH(NOLOCK) WHERE DeptId = 42)
	AND Id IN(SELECT cpMainId FROM caOrder WITH(NOLOCK) WHERE OrderType = 8 AND OpenDate < GETDATE() - 31 AND IsDeleted = 0 AND Paid > 0 )
	AND Id NOT IN(SELECT cpMainId FROM caOrder WHERE OpenDate > '' AND OrderType = 8 AND IsDeleted = 0 AND BeginDate > GETDATE() - 31)
	AND (select count(1) FROM caOrder  WITH(NOLOCK) WHERE OrderType = 8 AND OpenDate>'' AND ManagerUserId =cpMain.ConsultantId AND cpMainId=cpMain.id AND paid>0 )>1
	*/
	---推广的进行分配
	INSERT INTO #t(ConsultantId, Id, Name,RegDate,DeptId)
	SELECT ConsultantId, Id, Name,RegDate,15
	FROM cpMain WITH(NOLOCK)
	WHERE MemberType >1 --认证通过
	AND ConsultantId IN(SELECT ID FROM ManagerUser WITH(NOLOCK) WHERE DeptId = 15) --推广部

	--sean add 2018-2-28
	DELETE FROM #t WHERE Id = 10683832
	DECLARE @deptId INT, @dcProvinceID AS INT, @ManagerUserID AS INT, @ID AS INT, @Name VARCHAR(100), @cpMainId INT, @Sql AS VARCHAR(200), @ConsultantId INT, @RegDate DATETIME, @msg VARCHAR(50)
	SELECT @cpMainId = 0, @dcProvinceID = 32	
	WHILE EXISTS(SELECT 'x' FROM #t WHERE Id > @cpMainId)
	BEGIN
		SELECT TOP 1 @cpMainId = Id, @ConsultantId = ConsultantId, @Name = Name, @RegDate=RegDate, @deptId =deptId
		FROM #t WHERE Id > @cpMainId ORDER BY ID

		IF NOT EXISTS(SELECT 'x' FROM Cold_Consultant_Assign WHERE Current_Power < Power)
			UPDATE Cold_Consultant_Assign SET Current_Power = 0
		
		--提取第一个顾问
		SELECT TOP 1 @ID = ID, @ManagerUserID = ManagerUserID FROM Cold_Consultant_Assign WHERE Current_Power < Power
		IF @ManagerUserID IS NULL
			RETURN

		--修改顾问分配表
		UPDATE Cold_Consultant_Assign SET Current_Power = Current_Power + 1 WHERE ID = @ID
				
		IF @deptId =42
			SET @msg='冷客户第2次付费后31天重新分配'
		ELSE
			SET @msg='冷客户推广认证通过后重新分配'	
		SET @Sql = @msg+'顾问:从' + LTRIM(STR(ISNULL(@ConsultantId, 0))) + '到' + LTRIM(STR(@ManagerUserID))
		INSERT INTO bsManagerUserAction VALUES(@cpMainId, @Sql, '', 112, GETDATE()) 

		UPDATE cpMain SET ConsultantId = @ManagerUserID, ConsultantDate = GETDATE() WHERE Id = @cpMainId
		
		SELECT id INTO #company FROM cpmain WHERE Id <> @cpMainId AND Name = @Name AND ConsultantId = @ConsultantId
		DECLARE @cpid INT
		SET @cpid=0
		WHILE EXISTS(select 'x' FROM #company)
		BEGIN
			SELECT TOP 1 @cpid=id FROM #company ORDER BY id 
			UPDATE cpMain SET ConsultantId = @ManagerUserID, ConsultantDate = GETDATE() WHERE id = @cpid
			DELETE FROM #company WHERE id= @cpid
        		END     
		DROP TABLE #company 
		INSERT RtxNotifyLog SELECT LTRIM(STR(@ManagerUserID)) + ',' + LTRIM(STR(@ConsultantId)), @msg+'通知', 'http://sysback.51rc.com/newoa/company/cp/cpMainInfo?id=' + LTRIM(STR(@cpMainId))+ '&code=' + LTRIM(STR(DATEPART(HOUR, @RegDate) * 100 + DATEPART(MINUTE, @RegDate))), 0, 0, 0, Null, GETDATE()
		DELETE FROM #t where id=@cpMainId
		DELETE FROM #t where Name = @Name AND ConsultantId = @ConsultantId
	END
	DROP TABLE #t
END
SET NOCOUNT OFF
GO

/****** Object:  StoredProcedure [dbo].[spCpMainByIsprotectUpdate]    Script Date: 2018/12/13 19:13:04 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[spCpMainByIsprotectUpdate]
(
	@cpMainId INT
)
AS
BEGIN
	SET NOCOUNT ON
	UPDATE cpMain SET IsProtect = 0 WHERE Id = @cpMainId
	UPDATE caMain SET SecondPassword = [REDACTED] WHERE cpMainId = @cpMainId
END
GO

/****** Object:  StoredProcedure [dbo].[spCpMainByReplyrateUpdate]    Script Date: 2018/12/13 19:13:04 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


--创建人harry
--2017-5-24
--自动答复应聘的简历计划任务
--cpCvShield中的简历手动答复为不合适2018-6-11 harry
CREATE PROCEDURE [dbo].[spCpMainByReplyrateUpdate] 
AS
SET NOCOUNT ON
BEGIN   
	
	UPDATE a
	SET a.reply=2,a.replydate=getdate()
	FROM exjobapply a,job b, cpCvShield c
        WHERE a.jobId=b.Id AND c.cpMainId= b.cpMainId AND c.cvMainId=a.cvMainId
	AND ISNULL(a.reply,0)=0
    
	UPDATE exjobapply
	SET reply=4
	WHERE reply=5 
	AND ISNULL(CompanyDeleted,0) = 1
	
	--vip用户超过20天的自动答复，非vip超过10天的自动答复
        --vip
 	UPDATE a
	SET a.reply=5, a.replydate=getdate() 
	FROM exjobapply a, job b, cpMain c 
	WHERE a.reply=0 
	AND c.AutoReplyConfirm < CONVERT(VARCHAR(10), getdate() - 20, 120) 
	AND c.MemberType = 3
	AND b.CpMainId = c.id
	AND b.id = a.jobid
	AND a.addDate < CONVERT(VARCHAR(10), getdate() - 20, 120)	--在申请20天后自动答复
	AND a.addDate > c.AutoReplyConfirm	--只自动答复我知道了之后的
        
	--非vip
	UPDATE a
	SET a.reply = 5, a.replydate = getdate() 
	FROM exjobapply a, job b, cpMain c 
	WHERE a.reply = 0 
	AND c.AutoReplyConfirm < CONVERT(VARCHAR(10), getdate()-10, 120) 
	AND c.MemberType < 3
	AND b.CpMainId = c.id
	AND b.id = a.jobid
	AND a.addDate < CONVERT(VARCHAR(10), getdate() - 10, 120)	--在申请10天后自动答复
	AND a.addDate > c.AutoReplyConfirm		--只自动答复我知道了之后的     

	SELECT a.id, SUM(CASE WHEN c.reply = 5 THEN 1 ELSE 0 END) AS autoreply, 
		COUNT(*) AS SumReply
	INTO #t
	FROM cpMain a
	inner join job b on a.id = b.cpmainid
	inner join exjobapply c on c.jobid = b.id AND c.AddDate > a.AutoReplyConfirm  
	WHERE a.MemberType = 3
	--AND a.AutoReplyConfirm < CONVERT(VARCHAR(10), getdate() - 20, 120) //跟这个时间无关harry
	AND b.IsDelete = 0
	AND c.Reply > 0
	GROUP BY a.Id

	INSERT INTO #t
	SELECT a.id, SUM(CASE WHEN c.reply = 5 THEN 1 ELSE 0 END) AS autoreply, 
		COUNT(*) AS SumReply
	FROM cpMain a
	inner join job b on a.id = b.cpmainid
	inner join exjobapply c on c.jobid = b.id AND c.AddDate > a.AutoReplyConfirm --AND c.AddDate < CONVERT(VARCHAR(10), GETDATE() - 10, 120)
	WHERE a.MemberType <> 3
	--AND a.AutoReplyConfirm < CONVERT(VARCHAR(10), getdate() - 10, 120)  //跟这个时间无关harry
	AND b.IsDelete = 0
	AND c.Reply > 0
	GROUP BY a.Id

	--计算更新答复率
         --更新SumReply为0的,有应聘的
	UPDATE cpMain
	SET replyrate = 0 
	WHERE id IN (SELECT id FROM #t WHERE SumReply = 0)

    ---无应聘的
	UPDATE cpMain
	SET replyrate = 1
	WHERE id NOT IN (SELECT id FROM #t)
	AND AutoReplyConfirm IS NOT NULL
	
	--删除
   	DELETE FROM #t WHERE SumReply = 0
	
	--更新其他的
	UPDATE cpMain
	SET replyrate = (b.SumReply - b.autoreply) * 1.0 / b.SumReply
	FROM cpMain a, #t b
	WHERE a.Id = b.Id
	
	UPDATE a
	SET a.replyrate = b.ReplyRate
	FROM cpMainPublish a, cpMain b
	WHERE a.Id = b.Id
	AND ISNULL(a.replyrate, 0) <> ISNULL(b.replyrate, 0)

	drop table #t 
END
SET NOCOUNT OFF

GO

/****** Object:  StoredProcedure [dbo].[SpcpMainPublishByHasEnvironmentUpdate]    Script Date: 2018/12/13 19:13:04 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SpcpMainPublishByHasEnvironmentUpdate]
AS
BEGIN
	SET NOCOUNT ON
	SELECT DISTINCT cpMainId ID INTO #1 FROM cpImage WHERE ImgType = 3 AND HasPassed = 1
	SELECT Id, HasEnvironment INTO #2 FROM cpMainPublish WITH(NOLOCK) WHERE HasEnvironment = 1
	SELECT * INTO #3 FROM #2
	DELETE #2 WHERE ID IN(SELECT ID FROM #1)
	DELETE #1 WHERE ID IN(SELECT ID FROM #3)
	UPDATE cpMainPublish SET HasEnvironment = 0 WHERE ID IN(SELECT ID FROM #2)
	UPDATE cpMainPublish SET HasEnvironment = 1 WHERE ID IN(SELECT ID FROM #1)
END
GO

/****** Object:  StoredProcedure [dbo].[spCvInfoSave]    Script Date: 2018/12/13 19:13:04 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[spCvInfoSave]
AS
SET NOCOUNT ON
BEGIN
	IF DATEPART(HOUR, GETDATE()) = 6 AND (SELECT COUNT(*) FROM cvInfo WHERE ModifyDate > GETDATE() - 0.5) < 50000
	BEGIN
		SELECT TOP 0 * INTO #t1 FROM cvInfo	
	
		INSERT INTO #t1(cvMainId, JobName, Speciality, EduInfo, ExpInfo, ProjectInfo, TrainInfo, ModifyDate)
		SELECT Id cvMainId, JobName, Speciality,
			(
				STUFF(
					(SELECT ',' + GraduateCollage + '@@' + MajorName + '@@' + ISNULL(Details, '')
					FROM cvEducationPublish b
					WHERE b.cvMainId = a.ID
					FOR XML PATH('')),
					1,
					1,
					''
				)
			) EduInfo,
			(
				STUFF(
					(SELECT ',' + CompanyName + '@@' + JobName + '@@' + ISNULL(Description, '')
					FROM cvExperiencePublish b
					WHERE b.cvMainId = a.ID
					FOR XML PATH('')),
					1,
					1,
					''
				)
			) ExpInfo,
			(
				STUFF(
					(SELECT ',' + Name + '@@' + ISNULL(Description, '') + '@@' + ISNULL(Responsibilities, '')
					FROM cvProjectPublish b
					WHERE b.cvMainId = a.ID
					FOR XML PATH('')),
					1,
					1,
					''
				)
			) ProjectInfo,
			(
				STUFF(
					(SELECT ',' + Institution + '@@' + Course  + '@@' + ISNULL(Certificate, '') + '@@' + ISNULL(Details, '')
					FROM cvTrainingPublish b
					WHERE b.cvMainId = a.ID
					FOR XML PATH('')),
					1,
					1,
					''
				)
			) TrainInfo,
			GETDATE()
		FROM cvMainPublish a
		WHERE a.RefreshDate > CONVERT(VARCHAR(10), GETDATE() - 180, 120)
		AND a.Valid > 0

		CREATE TABLE #t2(cvMainId INT, IsDel BIT)
		INSERT INTO #t2 SELECT cvMainId, 0 FROM #T1

		DECLARE @i INT, @Page INT
		SELECT @i = 0, @Page = COUNT(*) / 10000 + 10 FROM #t1	

		TRUNCATE TABLE cvInfo

		WHILE @i < @Page
		BEGIN
			SET @i = @i + 1
			UPDATE #t2 SET IsDel = 1 WHERE cvMainId IN(SELECT TOP 10000 cvMainId FROM #t2)
			INSERT INTO cvInfo(cvMainId, JobName, Speciality, EduInfo, ExpInfo, ProjectInfo, TrainInfo, ModifyDate) 
			SELECT cvMainId, JobName, Speciality, EduInfo, ExpInfo, ProjectInfo, TrainInfo, GETDATE()
			FROM #t1
			WHERE cvMainId IN(SELECT cvMainId FROM #t2 WHERE IsDel = 1)
			AND cvMainId NOT IN(SELECT cvMainId FROM cvInfo)

			DELETE #t2 WHERE IsDel = 1
		END

		RETURN
	END		
	ELSE
	BEGIN
		CREATE TABLE #1(cvMainId INT)

		INSERT INTO #1
		SELECT cvMainId
		FROM bsCvVerify
		WHERE VerifyDate > DATEADD(MINUTE, -20, GETDATE())
		AND cvMainId IN(SELECT Id FROM cvMainPublish)
		AND NOT EXISTS(SELECT 'x' FROM cvInfo WHERE cvInfo.ModifyDate >= bsCvVerify.Verifydate)

		INSERT INTO #1		
		SELECT TOP 999 Id FROM cvMainPublish 
		WHERE RefreshDate > CONVERT(VARCHAR(10), GETDATE() - 180, 120)
		AND ID NOT IN(SELECT cvMainId FROM cvInfo)
		AND ID NOT IN(SELECT cvMainId FROM #1)
		AND Valid = 1

		SELECT Id cvMainId, JobName, Speciality,
			(
				STUFF(
					(SELECT ',' + GraduateCollage + '@@' + MajorName + '@@' + ISNULL(Details, '')
					FROM cvEducationPublish b
					WHERE b.cvMainId = a.ID
					FOR XML PATH('')),
					1,
					1,
					''
				)
			) EduInfo,
			(
				STUFF(
					(SELECT ',' + CompanyName + '@@' + JobName + '@@' + ISNULL(Description, '')
					FROM cvExperiencePublish b
					WHERE b.cvMainId = a.ID
					FOR XML PATH('')),
					1,
					1,
					''
				)
			) ExpInfo,
			(
				STUFF(
					(SELECT ',' + Name + '@@' + ISNULL(Description, '') + '@@' + ISNULL(Responsibilities, '')
					FROM cvProjectPublish b
					WHERE b.cvMainId = a.ID
					FOR XML PATH('')),
					1,
					1,
					''
				)
			) ProjectInfo,
			(
				STUFF(
					(SELECT ',' + Institution + '@@' + Course  + '@@' + ISNULL(Certificate, '') + '@@' + ISNULL(Details, '')
					FROM cvTrainingPublish b
					WHERE b.cvMainId = a.ID
					FOR XML PATH('')),
					1,
					1,
					''
				)
			) TrainInfo
		INTO #t
		FROM cvMainPublish a
		WHERE a.RefreshDate > CONVERT(VARCHAR(10), GETDATE() - 180, 120)
		AND a.Valid > 0
		AND ID IN(SELECT cvMainId FROM #1)

		DELETE FROM CvInfo WHERE cvMainID IN(SELECT cvMainId FROM #1)
		INSERT INTO cvInfo (cvMainId) SELECT DISTINCT cvMainId FROM #1
		
		UPDATE a SET a.JobName = b.JobName,
			a.Speciality = b.Speciality,
			a.EduInfo = b.EduInfo,
			a.ExpInfo = b.ExpInfo,
			a.ProjectInfo = b.ProjectInfo,
			a.TrainInfo = b.TrainInfo,
			a.ModifyDate = GETDATE()
		FROM cvInfo a, #t b
		WHERE a.cvMainId = b.cvMainId

		DELETE FROM cvInfo WHERE cvMainId NOT IN(SELECT Id FROM cvMainPublish WHERE RefreshDate > CONVERT(VARCHAR(10), GETDATE() - 180, 120) AND Valid = 1)
	END
END
GO

/****** Object:  StoredProcedure [dbo].[spCvMainByChar0Fix]    Script Date: 2018/12/13 19:13:05 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[spCvMainByChar0Fix]
AS
BEGIN
	create table #t(id int)
	create table #tt(id int)
--cveducation
	insert into #t Select id from cveducation where UNICODE(right(GraduateCollage,1)) = 0
	update cveducation set GraduateCollage=SUBSTRING(GraduateCollage, 1, LEN(GraduateCollage) - 1) where id in (select id from #t)
	DELETE #t

	INSERT INTO #t Select id from cveducation where UNICODE(right(MajorName,1)) = 0
	update cveducation set MajorName=SUBSTRING(MajorName, 1, LEN(MajorName) - 1) where id in (select id from #t)
	DELETE #t

	INSERT INTO #t Select id from cveducation where UNICODE(right(details,1)) = 0
	update cveducation set details=SUBSTRING(details, 1, LEN(details) - 1) where id in (select id from #t)
	DELETE #t
	--update cveducation set details=dbo.RemoveNullChars(details) where id in (select id from #t)
	--	select * from #t
	--	select * from cveducation where id=8030162

--cvexperience
	IF(SELECT COUNT(*) FROM #tt) =0
		INSERT INTO #t Select id from cvexperience where UNICODE(right(CompanyName,1)) = 0
	ELSE
		INSERT INTO #t Select id from cvexperience where UNICODE(right(CompanyName,1)) = 0 AND ID IN(SELECT ID FROM #tt)
	DELETE #tt
	INSERT #tt SELECT * FROM #t
	update cvexperience set CompanyName=SUBSTRING(CompanyName, 1, LEN(CompanyName) - 1) where id in (select id from #t)
	DELETE #t

	IF(SELECT COUNT(*) FROM #tt) =0
		INSERT INTO #t Select id from cvexperience where UNICODE(right(JobName,1)) = 0
	ELSE
		INSERT INTO #t Select id from cvexperience where UNICODE(right(JobName,1)) = 0 AND ID IN(SELECT ID FROM #tt)
	DELETE #tt
	INSERT #tt SELECT * FROM #t
	update cvexperience set JobName=SUBSTRING(JobName, 1, LEN(JobName) - 1) where id in (select id from #t)
	DELETE #t


	IF(SELECT COUNT(*) FROM #tt) =0
		INSERT INTO #t Select id from cvexperience where UNICODE(right(Description,1)) = 0
	ELSE
		INSERT INTO #t Select id from cvexperience where UNICODE(right(Description,1)) = 0 AND ID IN(SELECT ID FROM #tt)
	DELETE #tt
	INSERT #tt SELECT * FROM #t
	update cvexperience set Description=SUBSTRING(Description, 1, LEN(Description) - 1) where id in (select id from #t)
	--update cvexperience set Description=dbo.RemoveNullChars(Description) where id in (select id from #t)
	DELETE #t

	IF(SELECT COUNT(*) FROM #tt) =0
		INSERT INTO #t Select id from cvexperience where UNICODE(right(Dept,1)) = 0
	ELSE
		INSERT INTO #t Select id from cvexperience where UNICODE(right(Dept,1)) = 0 AND ID IN(SELECT ID FROM #tt)
	DELETE #tt
	INSERT #tt SELECT * FROM #t
	update cvexperience set Dept=SUBSTRING(Dept, 1, LEN(Dept) - 1) where id in (select id from #t)
	DELETE #t

	IF(SELECT COUNT(*) FROM #tt) =0
		INSERT INTO #t Select id from cvexperience where UNICODE(right(UpperPost,1)) = 0
	ELSE
		INSERT INTO #t Select id from cvexperience where UNICODE(right(UpperPost,1)) = 0 AND ID IN(SELECT ID FROM #tt)
	DELETE #tt
	INSERT #tt SELECT * FROM #t
	update cvexperience set UpperPost=SUBSTRING(UpperPost, 1, LEN(UpperPost) - 1) where id in (select id from #t)
	DELETE #t

--///////////////////////////
	IF(SELECT COUNT(*) FROM #tt) =0
		INSERT INTO #t Select id from cvmain where UNICODE(right(Speciality,1)) = 0
	ELSE
		INSERT INTO #t Select id from cvmain where UNICODE(right(Speciality,1)) = 0 AND ID IN(SELECT ID FROM #tt)
	DELETE #tt
	INSERT #tt SELECT * FROM #t
	update cvmain set Speciality=SUBSTRING(Speciality, 1, LEN(Speciality) - 1) where id in (select id from #t)
	--update cvmain set Speciality=dbo.RemoveNullChars(Speciality) where id in (select id from #t)
	DELETE #t
--////////////////////////
	drop table #t
	drop table #tt
end













GO

/****** Object:  StoredProcedure [dbo].[spCvMainByCvLevelCheck]    Script Date: 2018/12/13 19:13:05 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[spCvMainByCvLevelCheck]
AS
BEGIN
	select count(*) from cvmain with(nolock) where cvlevel like '1111_1%' and verifyresult=1 and iscvhidden=0 and valid=0
	select count(*) from cvmain with(nolock) where cvleveleng like '1111_1%' and verifyresulteng=1 and iscvhidden=0 and valid<2
	select count(*) from cvmain with(nolock) where iscvhidden=1 and valid>0
	select count(*) from cvmain with(nolock) where substring(cvlevel,3,1)='0' and id in(select cvmainid from cveducation with(nolock) where GraduateCollage>'')
	select count(*) from cvmain with(nolock) where substring(cvleveleng,3,1)='0' and id in(select cvmainid from cveducation with(nolock) where GraduateCollageeng>'')
	select count(*) from cvmain with(nolock) where substring(cvleveleng,4,1)='0' and id in(select cvmainid from cvexperience with(nolock) where companynameeng>'' and jobnameeng>'')
	select count(*) from cvmain with(nolock) where substring(cvlevel,4,1)='0' and id in(select cvmainid from cvexperience with(nolock) where companyname>'' and jobname>'')
	select count(*) from cvmain with(nolock) where substring(cvlevel,5,1)='0' and len(Speciality)>10 and refreshdate>getdate()-100
	select count(*) from cvmain with(nolock) where substring(cvleveleng,5,1)='0' and len(Specialityeng)>10 and refreshdate>getdate()-100
	select id,cvlevel,cvleveleng,refreshdate,dcsalaryid from cvmain with(nolock)
	where substring(cvlevel,6,1)='0' and left(cvlevel,2)='11'
	and dcsalaryid>0
	and id in(select cvmainid from cvjobtype with(nolock))
	and id in(select cvmainid from cvjobplace with(nolock))
	and refreshdate >getdate()-60
	order by refreshdate desc
END













GO

/****** Object:  StoredProcedure [dbo].[spcvMainByCvLevelFix]    Script Date: 2018/12/13 19:13:06 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[spcvMainByCvLevelFix]
AS
BEGIN
	CREATE TABLE #tt(ID INT)
	SELECT a.Id, a.cvLevel, a.cvLevelEng INTO #t 
	FROM cvMain a WITH(NOLOCK)
	INNER JOIN paMain b WITH(NOLOCK) ON a.paMainId = b.Id
	WHERE b.LastLoginDate > DATEADD(MINUTE, -120, GETDATE())
	OR a.RefreshDate > DATEADD(MINUTE, -120, GETDATE())

	INSERT INTO #tt(ID)
	SELECT ID FROM #T
	WHERE SUBSTRING(cvLevel, 2, 1) = 0
	AND ID IN(SELECT a.ID FROM cvMain a WITH(NOLOCK), paMain b WITH(NOLOCK) WHERE a.paMainId = b.ID AND b.Name > '' AND b.BirthDay > 0 AND Mobile >'')

	UPDATE cvMain SET cvLevel = '11' + RIGHT(cvLevel, 8)
	WHERE ID IN(SELECT ID FROM #tt)

	TRUNCATE TABLE #tt
	INSERT #tt SELECT ID FROM #T
	WHERE SUBSTRING(cvLevelEng, 2, 1) = 0
	AND ID IN(SELECT a.ID FROM cvMain a WITH(NOLOCK), paMain b WITH(NOLOCK) WHERE a.paMainId = b.ID AND b.NameEng > '' AND b.BirthDay > 0 AND Mobile >'')

	UPDATE cvMain SET cvLevelEng = '11' + RIGHT(cvLevelEng, 8)
	WHERE ID IN(SELECT ID FROM #tt)

	TRUNCATE TABLE #tt
	INSERT #tt SELECT ID FROM #T
	WHERE SUBSTRING(cvLevel, 3, 1) = 0
	AND ID IN(SELECT cvMainId FROM cvEducation WITH(NOLOCK) WHERE GraduateCollage>'')

	UPDATE cvMain SET cvLevel = LEFt(cvLevel, 2) + '1' + RIGHT(cvLevel, 7)
	WHERE Id IN(SELECT Id FROM #tt) 
	AND SUBSTRING(cvLevel, 3, 1) = '0'

	TRUNCATE TABLE #tt
	INSERT #tt SELECT ID FROM #T
	WHERE SUBSTRING(cvLevelEng, 3, 1) = 0
	AND ID IN(SELECT cvMainId FROM cvEducation WITH(NOLOCK) WHERE GraduateCollageEng>'')

	UPDATE cvMain SET cvLevelEng = LEFt(cvLevelEng, 2) + '1' + RIGHT(cvLevelEng, 7)
	WHERE Id IN(SELECT Id FROM #tt) 
	AND SUBSTRING(cvLevelEng, 3, 1) = '0'
	----------------
	TRUNCATE TABLE #tt
	INSERT #tt SELECT ID FROM #T
	WHERE SUBSTRING(cvLevel, 4, 1) = 0
	AND (ID IN(SELECT cvMainId FROM cvExperience WITH(NOLOCK) WHERE CompanyName>'')
		OR ID IN(SELECT ID FROM cvMain WITH(NOLOCK) WHERE cvType = 1)
		)

	UPDATE cvMain SET cvLevel = LEFt(cvLevel, 3) + '1' + RIGHT(cvLevel, 6)
	WHERE Id IN(SELECT Id FROM #tt) 
	AND SUBSTRING(cvLevel, 4, 1) = '0'

	TRUNCATE TABLE #tt
	INSERT #tt SELECT ID FROM #T
	WHERE SUBSTRING(cvLevelEng, 4, 1) = 0
	AND (ID IN(SELECT cvMainId FROM cvExperience WITH(NOLOCK) WHERE CompanyNameEng>'')
		OR (ID IN(SELECT ID FROM cvMain WITH(NOLOCK) WHERE cvType = 1)
			AND LEFT(cvLevelEng, 2) = '11')
		)

	UPDATE cvMain SET cvLevelEng = LEFt(cvLevelEng, 3) + '1' + RIGHT(cvLevelEng, 6)
	WHERE Id IN(SELECT Id FROM #tt) 
	AND SUBSTRING(cvLevelEng, 4, 1) = '0'

	-----------------
	TRUNCATE TABLE #tt
	INSERT #tt SELECT ID FROM #T
	WHERE SUBSTRING(cvLevel, 5, 1) = 0
	AND ID IN(SELECT Id FROM cvMain WITH(NOLOCK) WHERE LEN(Speciality)>4)

	UPDATE cvMain SET cvLevel = LEFt(cvLevel, 4) + '1' + RIGHT(cvLevel, 5)
	WHERE Id IN(SELECT Id FROM #tt)
	AND SUBSTRING(cvLevel, 5, 1) = '0'

	TRUNCATE TABLE #tt
	INSERT #tt SELECT ID FROM #T
	WHERE SUBSTRING(cvLevelEng, 5, 1) = 0
	AND ID IN(SELECT Id FROM cvMain WITH(NOLOCK) WHERE LEN(SpecialityEng)>4)

	UPDATE cvMain SET cvLevelEng = LEFt(cvLevelEng, 4) + '1' + RIGHT(cvLevelEng, 5)
	WHERE Id IN(SELECT Id FROM #tt)
	AND SUBSTRING(cvLevelEng, 5, 1) = '0'
	---------------------
	TRUNCATE TABLE #tt
	INSERT #tt SELECT ID FROM #T
	WHERE SUBSTRING(cvLevel, 6, 1) = 0
	AND ID IN(SELECT Id FROM cvMain WITH(NOLOCK) WHERE dcSalaryID>0)
	AND ID IN(SELECT cvMainID FROM cvJobType WITH(NOLOCK))
	AND ID IN(SELECT cvMainID FROM cvJobPlace WITH(NOLOCK))

	UPDATE cvMain SET cvLevel = LEFt(cvLevel, 5) + '1' + RIGHT(cvLevel, 4)
	WHERE Id IN(SELECT Id FROM #tt)
	AND SUBSTRING(cvLevel, 6, 1) = '0'

	TRUNCATE TABLE #tt
	INSERT #tt SELECT ID FROM #T
	WHERE SUBSTRING(cvLevelEng, 6, 1) = 0
	AND LEFT(cvLevelEng, 2) = '11'
	AND ID IN(SELECT Id FROM cvMain WITH(NOLOCK) WHERE dcSalaryID>0)
	AND ID IN(SELECT cvMainID FROM cvJobType WITH(NOLOCK))
	AND ID IN(SELECT cvMainID FROM cvJobPlace WITH(NOLOCK))

	UPDATE cvMain SET cvLevelEng = LEFT(cvLevelEng, 5) + '1' + RIGHT(cvLevelEng, 4)
	WHERE Id IN(SELECT Id FROM #tt)
	AND SUBSTRING(cvLevelEng, 6, 1) = '0'
	AND LEFT(cvLevelEng, 2) = '11'
	----------------
	TRUNCATE TABLE #tt
	INSERT #tt SELECT ID FROM #T
	WHERE SUBSTRING(cvLevel, 7, 1) = 0
	AND LEFT(cvLevel, 2) = '11'
	AND ID IN(SELECT cvMainId FROM cvLanguage WITH(NOLOCK))

	UPDATE cvMain SET cvLevel = LEFt(cvLevel, 6) + '1' + RIGHT(cvLevel, 3)
	WHERE Id IN(SELECT Id FROM #tt)
	AND SUBSTRING(cvLevel, 7, 1) = '0'

	TRUNCATE TABLE #tt
	INSERT #tt SELECT ID FROM #T
	WHERE SUBSTRING(cvLevelEng, 7, 1) = 0
	AND LEFT(cvLevelEng, 2) = '11'
	AND ID IN(SELECT cvMainId FROM cvLanguage WITH(NOLOCK))

	UPDATE cvMain SET cvLevelEng = LEFt(cvLevelEng, 6) + '1' + RIGHT(cvLevelEng, 3)
	WHERE Id IN(SELECT Id FROM #tt)
	AND SUBSTRING(cvLevelEng, 7, 1) = '0'

	----------------
	TRUNCATE TABLE #tt
	INSERT #tt SELECT ID FROM #T
	WHERE SUBSTRING(cvLevel, 8, 1) = 0
	AND ID IN(SELECT cvMainId FROM cvTraining WITH(NOLOCK) WHERE Institution > '')

	UPDATE cvMain SET cvLevel = LEFt(cvLevel, 7) + '1' + RIGHT(cvLevel, 2)
	WHERE Id IN(SELECT Id FROM #tt)
	AND SUBSTRING(cvLevel, 8, 1) = '0'

	TRUNCATE TABLE #tt
	INSERT #tt SELECT ID FROM #T
	WHERE SUBSTRING(cvLevelEng, 8, 1) = 0
	AND ID IN(SELECT cvMainId FROM cvTraining WITH(NOLOCK) WHERE InstitutionEng > '')

	UPDATE cvMain SET cvLevelEng = LEFt(cvLevelEng, 7) + '1' + RIGHT(cvLevelEng, 2)
	WHERE Id IN(SELECT Id FROM #tt)
	AND SUBSTRING(cvLevelEng, 8, 1) = '0'

	----------------
	TRUNCATE TABLE #tt
	INSERT #tt SELECT ID FROM #T
	WHERE SUBSTRING(cvLevel, 9, 1) = 0
	AND ID IN(SELECT cvMainId FROM cvProject WITH(NOLOCK) WHERE Name > '')

	UPDATE cvMain SET cvLevel = LEFt(cvLevel, 8) + '1' + RIGHT(cvLevel, 1)
	WHERE Id IN(SELECT Id FROM #tt)
	AND SUBSTRING(cvLevel, 9, 1) = '0'

	TRUNCATE TABLE #tt
	INSERT #tt SELECT ID FROM #T
	WHERE SUBSTRING(cvLevelEng, 9, 1) = 0
	AND ID IN(SELECT cvMainId FROM cvProject WITH(NOLOCK) WHERE NameEng > '')

	UPDATE cvMain SET cvLevelEng = LEFt(cvLevelEng, 8) + '1' + RIGHT(cvLevelEng, 1)
	WHERE Id IN(SELECT Id FROM #tt)
	AND SUBSTRING(cvLevelEng, 9, 1) = '0'

	----------------
	TRUNCATE TABLE #tt
	INSERT #tt SELECT ID FROM #T
	WHERE RIGHT(cvLevel, 1) = '0'
	AND LEFT(cvLevel, 2) = '11'
	AND ID IN(SELECT cvMainId FROM cvAppendix WITH(NOLOCK))

	UPDATE cvMain SET cvLevel = LEFt(cvLevel, 9) + '1'
	WHERE Id IN(SELECT Id FROM #tt)
	AND RIGHT(cvLevel, 1) = '0'
	AND LEFT(cvLevel, 2) = '11'

	TRUNCATE TABLE #tt
	INSERT #tt SELECT ID FROM #T
	WHERE RIGHT(cvLevelEng, 1) = '0'
	AND LEFT(cvLevelEng, 2) = '11'
	AND ID IN(SELECT cvMainId FROM cvAppendix WITH(NOLOCK))

	UPDATE cvMain SET cvLevelEng = LEFt(cvLevelEng, 9) + '1'
	WHERE Id IN(SELECT Id FROM #tt)
	AND RIGHT(cvLevelEng, 1) = '0'
	AND LEFT(cvLevelEng, 2) = '11'

	TRUNCATE TABLE #tt
	DROP TABLE #t
	-----------
	------------------
	UPDATE paMain SET RegisterType = 102 WHERE RegisterMode = 11 AND RegisterType = 101 AND LastLoginDate > GETDATE() - 1
 
	CREATE TABLE #1(id INT IDENTITY(1, 1), cvMainId INT)
	INSERT INTO #1(cvMainId)
	SELECT a.Id
	FROM cvMain a, paMain b
	WHERE a.paMainId  = b.Id
	AND b.BlockCount = 0
	AND b.VerifyCount > 0
	AND b.LastLoginDate > GETDATE() - 3
	AND (b.RegisterMode = 1 OR  b.RegisterType = 101)
	AND b.AddMan >= 112
	AND a.VerifyResult = 1
	AND a.cvLevel LIKE '1111_1%'

	DECLARE @Id INT, @cvMainId INT
	SET @Id = 0
	WHILE EXISTS(SELECT 'x' FROM #1 WHERE Id > @Id)
	BEGIN
		SELECT TOP 1 @Id = Id, @cvMainId = cvMainId FROM #1 WHERE Id > @id ORDER BY ID
		UPDATE cvMain SET VerifyResult = VerifyResult WHERE Id = @cvMainId
 	END
 	DROP TABLE #1
ENd

GO

/****** Object:  StoredProcedure [dbo].[spCvMainByIsOpenUpdate]    Script Date: 2018/12/13 19:13:06 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[spCvMainByIsOpenUpdate]
AS
BEGIN
	--1--按条件把状态改为开放
	UPDATE a SET a.IsOpen = 1 
	FROM cvMain a WITH(NOLOCK) 
	INNER JOIN paMain b WITH(NOLOCK) ON a.paMainId = b.Id AND b.LastLoginDate > GETDATE()-  2
	INNER JOIN dcCvOpenSET c WITH(NOLOCK) ON a.Degree = c.dcEducation
		AND b.LivePlace LIKE CONVERT(VARCHAR(2), c.dcProvinceId) + '%'
	WHERE (ISNULL(b.BirthDay, 999999) > dbo.AgeToBirth(c.Age))
	AND a.IsOpen = 0 
	AND (
		(a.VerifyResult = 1 AND a.cvLevel LIKE '111__1%')
		OR (a.VerifyResultEng = 1 AND a.cvLevelEng LIKE '111__1%')
		)
	--2--按条件把状态改为不开放
	UPDATE a SET a.IsOpen = 0
	FROM cvMain a WITH(NOLOCK)
	INNER JOIN paMain b WITH(NOLOCK) ON a.paMainId = b.Id AND b.LastLoginDate > GETDATE()-  2
	INNER JOIN dcCvOpenSET c WITH(NOLOCK) ON a.Degree = c.dcEducation
		AND b.LivePlace LIKE CONVERT(VARCHAR(2), c.dcProvinceId) + '%'
	WHERE b.BirthDay <= dbo.AgeToBirth(c.Age)
	AND a.IsOpen = 1
	AND IsNull(b.Mobile, '') <> '' --Richard 2011.8.21增加，避免反复修改
	AND (
		(a.VerifyResult = 1 AND a.cvLevel LIKE '111__1%')
		OR (a.VerifyResultEng = 1 AND a.cvLevelEng LIKE '111__1%')
		)
	--3--初中学历都是开放简历
	UPDATE cvMain SET IsOpen = 1
	WHERE degree = 1
	AND IsOpen = 0
	--4--没有手机的账号 一定是开放简历
	UPDATE cvMain SET IsOpen = 1
	WHERE IsOpen = 0
	AND Attachment IS NULL
	AND paMainID IN(
		SELECT ID FROM paMain a WITH(NOLOCK)
		WHERE IsNull(Mobile, '') = ''
		AND LastLoginDate > GETDATE()-  2
	)
	--5--附件简历都不开放
	UPDATE cvMain SET IsOpen = 0 
	WHERE IsOpen = 1
	AND NOT (
		(VerifyResult = 1 AND cvLevel LIKE '111__1%')
		OR (VerifyResultEng = 1 AND cvLevelEng LIKE '111__1%')
		)
	AND Attachment IS NOT NULL
	AND paMainID IN (SELECT ID FROM paMain WITH(NOLOCK) 
			WHERE LastLoginDate > GETDATE()-  2)
	--6--无效简历都是开放
	UPDATE cvMain SET IsOpen = 1 
	WHERE IsOpen = 0 
	AND NOT (
		(VerifyResult = 1 AND cvLevel LIKE '111__1%')
		OR (VerifyResultEng = 1 AND cvLevelEng LIKE '111__1%')
		)
	AND Attachment IS NULL
	AND paMainID IN (SELECT ID FROM paMain WITH(NOLOCK) 
			WHERE LastLoginDate > GETDATE()-  2)
END
GO

/****** Object:  StoredProcedure [dbo].[spCvMainByJobNameFix]    Script Date: 2018/12/13 19:13:07 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[spCvMainByJobNameFix]
AS
SET NOCOUNT ON
BEGIN
	CREATE TABLE #t(Id INT IDENTITY(1, 1), cvMainId INT, JobName VARCHAR(50))
	INSERT #t SELECT Id, NULL FROM cvMain WHERE SecondId = JobName AND Valid > 0
	UPDATE #t SET JobName = (SELECT TOP 1 Jobname FROM cvExperience WHERE cvExperience.cvMainId = #t.cvMainId ORDER BY BeginDate desc)

	UPDATE a SET a.JobName = b.JobName FROM cvMain a, #t b WHERE a.id = b.cvmainid AND b.JobName >''
	DELETE FROM #t WHERE JobName > ''

	DELETE FROM #t 

	INSERT #t SELECT Id, NULL FROM cvMain WHERE SecondId = JobName AND Valid > 0
	AND paMainId IN(SELECT id FROM paMain WHERE BirthDay > CONVERT(VARCHAR(6), DATEADD(YEAR, -25, GETDATE()), 112) AND LastLoginDate > GETDATE() - 3)

	------------------------------------

	CREATE TABLE #jn(cvMainId INT, dcJobTypeId INT, JobName NVARCHAR(20))

	INSERT INTO #jn(cvMainID)
	SELECT ID
	FROM cvMain
	WHERE JobName IS NULL
	AND Valid > 0
	AND paMainId IN(SELECT id FROM paMain WHERE BirthDay <= CONVERT(VARCHAR(6), DATEADD(YEAR, -25, GETDATE()), 112) AND LastLoginDate > GETDATE() - 3)

	INSERT INTO #jn(cvMainID) SELECT cvMainId FROM #t WHERE cvMainId NOT IN(SELECT cvMainId FROM #Jn)

	UPDATE #jn SET dcJobTypeId = (SELECT TOP 1 dcJobTypeId FROM cvJobType WHERE cvJobType.cvMainId = #jn.cvMainId)

	UPDATE a SET a.JobName = '期望' + b.Description FROM #jn a, dcJobType b WHERE a.dcjobTypeId = b.Id

	DELETE FROM #jn WHERE JobName IS NULL

	UPDATE a SET a.JobName = b.JobName FROM cvMain a, #jn b WHERE a.Id = b.cvMainId AND a.JobName IS NULL
	UPDATE a SET a.JobName = b.JobName FROM cvMain a, #jn b WHERE a.Id = b.cvMainId AND a.Secondid = a.JobName

	UPDATE a SET a.JobName = b.JobName FROM cvMainPublish a, #jn b WHERE a.Id = b.cvMainId AND a.JobName IS NULL
	AND a.Id IN(SELECT TOP 9999 a.ID FROM cvMainPublish a, #jn b WHERE a.Id = b.cvMainId AND a.JobName IS NULL)
 
	UPDATE a SET a.JobName = b.JobName FROM cvMainPublish a, cvMain b 
	WHERE a.Id = b.Id AND a.Id IN(SELECT TOP 3000 a.Id FROM cvMainPublish a WITH(NOLOCK), cvMain b WITH(NOLOCK) WHERE a.Id = b.Id AND ISNULL(a.JobName, '') <> b.JobName)
	-------------------------------

	SELECT a.Id paMainId, b.Id cvMainId
	INTO #pc
	FROM paMain a, cvMain b
	WHERE a.Id = b.paMainId
	AND a.LastLoginDate >= CONVERT(VARCHAR(10), GETDATE() -365, 120)
	AND b.Valid > 0

	CREATE TABLE #delp(id INT, HasDel BIT)
	INSERT INTO #Delp SELECT ID, 0 FROM paMainPublish WHERE Id NOT IN(SELECT paMainId FROM #pc)
	 
	UPDATE #delp SET HasDel = 1 WHERE Id IN(SELECT TOP 3999 ID FROM #Delp)
	DELETE FROM paMainPublish WHERE Id IN(SELECT ID FROM #delp WHERE HasDel = 1)
	DELETE #delp WHERE HasDel = 1

	INSERT INTO paMainPublish(ID, Gender, BirthDay, LivePlace, AccountPlace, GrowPlace, Height, HasPhoto, LastLoginDate, LastModifyDate, MobileRegion, dcProvinceID)
	SELECT TOP 2000 ID, Gender, BirthDay, LivePlace, AccountPlace, GrowPlace, Height, HasPhoto, LastLoginDate, LastModifyDate, MobileRegion, dcProvinceID
	FROM paMain WHERE ID IN(SELECT paMainId FROM #pc WHERE paMainId NOT IN(SELECT Id FROM paMainPublish))

	INSERT INTO cvMainPublish(ID, paMainID, Degree, dcMajorID, LastJobTypeID, LastIndustryID, JobName, SubNodeNum, 
		RelatedWorkYears, dcSalaryID, IsNegotiable, Speciality, SpecialityEng, Attachment, Valid, RefreshDate, EmployType)
	SELECT TOP 2000 ID, paMainID, Degree, dcMajorID, LastJobTypeID, LastIndustryID, JobName, SubNodeNum, 
		RelatedWorkYears, dcSalaryID, IsNegotiable, Speciality, SpecialityEng, Attachment, Valid, RefreshDate, EmployType
	FROM cvMain 
	WHERE ID IN(SELECT cvMainId FROM #pc WHERE cvMainId NOT IN(SELECT Id FROM cvMainPublish))
	ORDER BY ID

--	SELECT (SELECT COUNT(DISTINCT paMainId) FROM #pc) pnum,
--		(SELECT COUNT(DISTINCT cvMainId) FROM #pc) cnum,
--		(SELECT COUNT(*) FROM cvMainPublish WHERE Id NOT IN(SELECT cvMainId FROM #pc)) cnumnotin,
--		(SELECT COUNT(*) FROM cvMainPublish WHERE Id IN(SELECT cvMainId FROM #pc)) cnumin,
--		(SELECT COUNT(*) FROM paMainPublish WHERE Id NOT IN(SELECT paMainId FROM #pc)) pnumnotin,
--		(SELECT COUNT(*) FROM paMainPublish WHERE Id IN(SELECT paMainId FROM #pc)) pnumin
--	DROP TABLE #pc
--	DROP TABLE #Delp
END












GO

/****** Object:  StoredProcedure [dbo].[SpCvMainByJobNameUpdate]    Script Date: 2018/12/13 19:13:07 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SpCvMainByJobNameUpdate]
AS
BEGIN
	create table #t(id int)
	insert into #t
	select id 
	from cvmain 
	where pamainid in (
		select id from pamain 
		where lastlogindate between getdate()-180 and getdate() - 0.2 
		and birthday<=convert(varchar(6), dateadd(year,-25,getdate()), 112))
	and valid = 0
	and cvlevel like '1110_1%'
	and cvtype=0
	--and pamainid not in(select pamainid from cvmain where valid>0)

	update cvmain set cvtype=1, cvlevel = '1111' + right(cvlevel, 6) where id in(select id from #t)
	update cvmain set jobname=id where id in(select id from #t) and jobname is null
	--------
	truncate table #t
	insert into #t
	select id 
	from cvmain 
	where pamainid in (
		select id from pamain 
		where lastlogindate between getdate()-180 and getdate() - 0.2 
		and birthday>convert(varchar(6), dateadd(year,-25,getdate()), 112))
	and valid = 0
	and cvlevel like '1110_1%'
	and cvtype=0
	--and pamainid not in(select pamainid from cvmain where valid>0)

	update cvmain set cvtype=1, cvlevel = '1111' + right(cvlevel, 6) where id in(select id from #t)
	update cvmain set jobname='应届毕业生' where id in(select id from #t) and jobname is null
	---------------

	update cvmain set jobname=id
	where pamainid in (select id from pamain where lastlogindate > getdate()-180 and birthday<=convert(varchar(6), dateadd(year,-25,getdate()), 112))
	and valid > 0
	and jobname='应届毕业生'

	update cvmain set jobname='应届毕业生'
	where pamainid in (select id from pamain where lastlogindate > getdate()-180 and birthday>convert(varchar(6), dateadd(year,-25,getdate()), 112))
	and valid > 0
	and jobname = SecondId
END
GO

/****** Object:  StoredProcedure [dbo].[spCvMainByNameFix]    Script Date: 2018/12/13 19:13:07 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[spCvMainByNameFix]
AS
BEGIN
	CREATE TABLE #t(
		ID INT,
		JobType SMALLINT,
		JobPlace VARCHAR(6),
		JobTypeDesc NVARCHAR(30),
		JobPlaceDesc NVARCHAR(20),
		cvName NVARCHAR(50)
		)

	INSERT INTO #t(ID)
	SELECT a.Id FROM cvMain a WITH(NOLOCK), paMain b WITH(NOLOCK)
		WHERE (a.RefreshDate > DATEADD(MINUTE, -70, GETDATE())
			OR b.LastLoginDate > DATEADD(MINUTE, -70, GETDATE()))
		AND a.paMainId = b.ID
		AND a.dcSalaryId > 0
		AND a.ID IN(SELECT cvMainID FROM cvJobType)
		AND a.ID IN(SELECT cvMainID FROM cvJobPlace)
		AND a.Name = '未完成简历'
	
	UPDATE #t SET JobType = (SELECT TOP 1 dcJobTypeID FROM cvJobType WITH(NOLOCK) WHERE cvJobType.cvMainId = #t.ID)
	UPDATE #t SET JobPlace = (SELECT TOP 1 dcRegionId FROM cvJobPlace WITH(NOLOCK) WHERE cvJobPlace.cvMainId = #t.ID)
	UPDATE #t SET JobTypeDesc = (SELECT TOP 1 Description FROM dcJobType WITH(NOLOCK) WHERE dcJobType.ID = #t.JobType)
	UPDATE #t SET JobPlaceDesc = (SELECT TOP 1 Description FROM dcRegion WITH(NOLOCK) WHERE dcRegion.ID = #t.JobPlace)
	UPDATE #t SET cvName = JobPlaceDesc + '+' + JobTypeDesc WHERE JobPlaceDesc IS NOT NULL AND JobTypeDesc IS NOT NULL
	DELETE FROM #t WHERE cvName IS NULL

	UPDATE a
	SET a.Name = b.cvName
	FROM cvMain a WITH(NOLOCK), #t b
	WHERE a.id = b.id

	DROP TABLE #t
END













GO

/****** Object:  StoredProcedure [dbo].[spCvMainByValidFix]    Script Date: 2018/12/13 19:13:07 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[spCvMainByValidFix]
AS
SET NOCOUNT ON
BEGIN
	SELECT a.ID INTO #t FROM cvMain a WITH(NOLOCK), paMain b WITH(NOLOCK) 
	WHERE a.paMainID = b.ID AND (b.LastLoginDate > GETDATE() - 2 OR a.RefreshDate > GETDATE() - 2)

	UPDATE cvMain SET Valid = 0 WHERE IsCvHidden = 1 AND Valid > 0 AND ID IN(SELECT ID FROM #T)
	UPDATE cvMain SET Attachment = NULL WHERE Attachment = '' AND ID IN(SELECT ID FROM #T)

	UPDATE cvMain SET Valid = 0
	WHERE NOT (cvLevel LIKE '1111_1%' AND VerifyResult = 1)
	AND NOT (cvLevelEng LIKE '1111_1%' AND VerifyResultEng = 1)
	AND Valid > 0
	AND IsCvHidden = 0
	AND Attachment IS NULL
	AND ID IN(SELECT ID FROM #T)

	UPDATE cvMain SET Valid = 1 
	WHERE cvLevel LIKE '1111_1%'
	AND VerifyResult = 1
	AND NOT (cvLevelEng LIKE '1111_1%' AND VerifyResultEng = 1)
	AND IsCvHidden = 0
	AND Valid <> 1
	AND ID IN(SELECT ID FROM #T)

	UPDATE cvMain SET Valid = 2 
	WHERE cvLevel LIKE '1111_1%' 
	AND VerifyResult = 1
	AND cvLevelEng LIKE '1111_1%'
	AND VerifyResultEng = 1
	AND Valid <> 2
	AND IsCvHidden = 0
	AND ID IN(SELECT ID FROM #T)

	UPDATE cvMain SET Valid = 3
	WHERE NOT (cvLevel LIKE '1111_1%' AND VerifyResult = 1)
	AND cvLevelEng LIKE '1111_1%'
	AND VerifyResultEng = 1
	AND Valid <> 3
	AND IsCvHidden = 0
	AND ID IN(SELECT ID FROM #T)

	UPDATE cvMain SET Valid = 1
	WHERE cvLevel NOT LIKE '1111_1%'
	AND cvLevelEng NOT LIKE '1111_1%'
	AND VerifyResult = 1
	AND VerifyResultEng = 1
	AND Attachment > ''
	AND Valid <> 1
	AND IsCvHidden = 0
	AND ID IN(SELECT ID FROM #T)

	-----------------------------------------------------------
	CREATE TABLE #t2(Seq INT IDENTITY(1, 1), Id INT)

	INSERT INTO #t2
	SELECT Id FROM cvMain WITH(NOLOCK)
	WHERE cvLevel LIKE '1111_1%' 
	AND VerifyResult = 1 
	AND IsCvHidden = 0 
	AND Valid=0 
	AND Id IN(SELECT ID FROM #t)
	ORDER BY ID DESC

	INSERT INTO #t2
	SELECT ID
	FROM cvMain WITH(NOLOCK)
	WHERE Attachment > '' 
	AND Valid = 0
	AND IsCvHidden = 0
	AND VerifyResult != 10
	AND VerifyResultEng != 10
	AND Id IN(SELECT ID FROM #t)

	DECLARE @S VARCHAR(MAX), @I INT, @All INT
	SELECT @All = MAX(Seq) FROM #t2
	SET @i = 1
	WHILE (@i < @All)
	BEGIN
		SELECT @s = 'UPDATE cvMain SET cvLevel = cvLevel WHERE Id = ' + LTRIM(STR(ID)) FROM #t2 WHERE Seq = @i
		EXEC(@s)
		SET @i = @i + 1
	END

	DROP TABLE #t2
	DROP TABLE #t
END
GO

/****** Object:  StoredProcedure [dbo].[SpCvMainByYingJieShengFix]    Script Date: 2018/12/13 19:13:08 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SpCvMainByYingJieShengFix]
AS
SET NOCOUNT ON
BEGIN
	SELECT Id, LastJobTypeId JobTypeId, SPACE(6) RegionId, 
		SPACE(50) JobTypeName, SPACE(20) RegionName, JobName
	INTO #t
	FROM cvMain WITH(NOLOCK)
	WHERE (JobName = '应届毕业生' OR JobName = '附件简历' OR JobName = SecondId)
	AND paMainId IN(SELECT Id FROM paMain WITH(NOLOCK) WHERE LastLoginDate > GETDATE() - 3)
	AND cvLevel LIKE '1111_1%'
	ORDER BY ID DESC

	UPDATE #t SET JobTypeId = (SELECT TOP 1 dcJobTypeId FROM cvJobType WITH(NOLOCK) WHERE cvJobType.cvMainId = #t.Id)
	UPDATE #t SET RegionId = (SELECT TOP 1 dcRegionId FROM cvJobPlace WITH(NOLOCK) WHERE cvJobPlace.cvMainId = #t.Id)
	UPDATE #t SET JobTypeName = (SELECT Description FROM dcJobType WITH(NOLOCK) WHERE dcJobType.Id = JobTypeId)
	UPDATE #t SET JobTypeName = LEFT(JobTypeName, CHARINDEX('/', JobTypeName) -1) WHERE CHARINDEX('/', JobTypeName) > 2
	UPDATE #t SET RegionName = (SELECT Description FROM dcRegion WITH(NOLOCK) WHERE dcRegion.Id = RegionId)
	UPDATE #t SET RegionName = LEFT(RegionName, LEN(RegionName) - 1) WHERE LEN(RegionName) > 2 AND RIGHT(RegionName, 1) IN('省', '市', '县', '区', '旗')
	UPDATE #t SET JobName = LEFT(JobTypeName + ' ' + RegionName, 20)

	SELECT COUNT(*) FROM #t

	UPDATE a
	SET a.JobName = b.JobName
	FROM cvMain a, #t b
	WHERE a.id = b.id
	--AND a.JobName = '应届毕业生'

	UPDATE a
	SET a.JobName = b.JobName
	FROM cvMainPublish a, cvmain b
	WHERE ISNULL(a.JobName, '') <> ISNULL(b.JobName, '')
	AND a.Id = b.Id
END
GO

/****** Object:  StoredProcedure [dbo].[spcvMainClear]    Script Date: 2018/12/13 19:13:08 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[spcvMainClear]
AS
BEGIN
	DECLARE @ID AS INT, @PaMainID AS INT
	CREATE TABLE #Id(ID INT)
	SELECT @ID = MIN(ID) FROM paMain WITH(NOLOCK) WHERE AddDate > DATEADD(DAY, - 1, GETDATE())
	SELECT ID INTO #t FROM cvMain WITH(NOLOCK) WHERE paMainID IN(SELECT ID FROM PaMain WITH(NOLOCK) WHERE NAME = '王蓓' AND ID > @ID)

	IF (SELECT COUNT(*) FROM #t) > 0
	BEGIN
		INSERT #ID
		SELECT ID FROM cvMain WITH(NOLOCK) 
		WHERE ID IN(SELECT ID FROM #t)
		AND (Speciality LIKE '%冰毒%'
			OR Speciality LIKE '%戚慧丽%'
			OR Speciality LIKE '%58585528%'
			OR Speciality LIKE '%王敏昌%'
			)
		
		INSERT #Id
		SELECT cvMainID FROM cvExperience WITH(NOLOCK) 
		WHERE cvMainID IN(SELECT ID FROM #t)
		AND (DESCRIPTION LIKE '%冰毒%'
			OR DESCRIPTION LIKE '%戚慧丽%'
			OR DESCRIPTION LIKE '%58585528%'
			OR DESCRIPTION LIKE '%王敏昌%'
			)
		
		INSERT #Id
		SELECT cvMainID FROM cvEducation WITH(NOLOCK) 
		WHERE cvMainID IN(SELECT ID FROM #t)
		AND (DETAILS LIKE '%冰毒%'
			OR DETAILS LIKE '%戚慧丽%'
			OR DETAILS LIKE '%58585528%'
			OR DETAILS LIKE '%王敏昌%'
			)

		IF(SELECT COUNT(*) FROM #Id) > 0
		BEGIN
			DELETE ExJobApply WHERE cvMainID IN(SELECT ID FROM #ID)
			UPDATE cvMain SET IsCvHidden = 1 WHERE ID IN(SELECT ID FROM #t)
			UPDATE cvMain SET VerifyResult = 10 WHERE ID IN(SELECT ID FROM #t)
		END
	END
END










GO

/****** Object:  StoredProcedure [dbo].[spdcCpMainIdTempinsert]    Script Date: 2018/12/13 19:13:08 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[spdcCpMainIdTempinsert]
as
begin
	SELECT  a.LoginCookies, COUNT(DISTINCT b.CpMainId) Cnt
	INTO #t2
	FROM caLoginLog a, caMain b
	WHERE a.AddDate > GETDATE() - 130
	AND a.caMainId = b.Id
	AND LEN(a.LoginCookies) > 10
	GROUP BY a.LoginCookies
	HAVING COUNT(DISTINCT b.CpMainId) > 10

	SELECT CONVERT(varchar(10), a.adddate, 120) d,  a.Loginip, COUNT(DISTINCT b.CpMainId) Cnt
	INTO #t1
	FROM caLoginLog a, caMain b
	WHERE a.AddDate > GETDATE() - 130
	AND a.caMainId = b.Id
	AND LEN(a.LoginCookies) > 10
	GROUP BY CONVERT(varchar(10), a.adddate, 120), a.Loginip
	HAVING COUNT(DISTINCT b.CpMainId) > 10

	DELETE a
	from #t1 a, ip_white b
	where a.loginip like b.ip + '%'

	SELECT Distinct caMainId INTO #ca FROM caLoginLog WHERE LoginCookies IN(SELECT LoginCookies FROM #t2)
	insert into #ca
	SELECT Distinct caMainId FROM caLoginLog a, #t1 b
	WHERE a.Loginip=b.LoginIp
	and CONVERT(varchar(10), a.adddate, 120) = b.d

	SELECT DISTINCT cpMainId INTO #cp FROM caMain WHERE ID IN(SELECT caMainId FROM #ca)

	--select * from #t2 order by cnt desc
	--select * from #ca
	drop table dcCpMainIdTemp
	select * into dcCpMainIdTemp from #cp
end








GO

/****** Object:  StoredProcedure [dbo].[spDcIpPlaceByInternationalUpdate]    Script Date: 2018/12/13 19:13:09 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[spDcIpPlaceByInternationalUpdate]
AS
BEGIN
	SELECT DISTINCT City
	INTO #t
	FROM dcIpPlace WITH(NOLOCK)

	DELETE #t WHERE LEFT(City, 2) IN(SELECT LEFT(SubSiteCity, 2) FROM dcSubSite WITH(NOLOCK))
	OR LEFT(City, 2) IN('华南','全国','清华','东北','东华','华东','华中','西北','首都','长江','集美','纯真','黄河','西华','对外')
	OR City LIKE '中%'
	OR City LIKE '%中国%'
	OR City LIKE '%香港%'
	OR City LIKE '%台湾%'
	OR City LIKE '%澳门%'
	OR City LIKE '%大学%'
	OR City LIKE '%局域网%'
	OR City LIKE '%s246%'
	OR City LIKE '%本机%'
	OR City LIKE '%网络%'
	OR City LIKE '%UCWEB%'

	UPDATE dcIpPlace SET International = NULL WHERE International = 1
	UPDATE dcIpPlace SET International = 1 WHERE City NOT IN(SELECT City FROM #t)
END













GO

/****** Object:  StoredProcedure [dbo].[spdcJobTypeMajorMapUpdate]    Script Date: 2018/12/13 19:13:09 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[spdcJobTypeMajorMapUpdate]
AS
BEGIN
	CREATE TABLE #t(Id INT IDENTITY(1, 1), dcJobTypeId INT, MajorName NVARCHAR(50), Cnt INT)
	INSERT INTO #t
	SELECT y.dcJobTypeid, x.MajorName, COUNT(*) Cnt
	FROM cveducation x WITH(NOLOCK)
	INNER JOIN cvJobtype y WITH(NOLOCK) ON x.cvMainId = y.cvMainId
	WHERE EXISTS(SELECT 'x' FROM cvMain WHERE Id = x.cvMainId AND RefreshDate > '2016-1-1')
	GROUP BY y.dcJobTypeid, x.MajorName 
	ORDER BY y.dcJobTypeid, COUNT(*) DESC

	DELETE #t WHERE MajorName = '无'
	DELETE #t WHERE MajorName IS NULL
	DELETE #t WHERE MajorName = ''
	DELETE #t WHERE MajorName = '所学专业未填写'

	SELECT TOP 0 * INTO #1 FROM dcJobTypeMajorMap
	INSERT INTO #1
	SELECT *
	FROM (SELECT a.dcJobTypeId, a.MajorName, b.dcMajorId, ROW_NUMBER() OVER(PARTITION BY dcJobTypeId ORDER BY ID) RowNo,
			b.PinYin, b.JianPin
		FROM #t a, dcMajorKeyword b
		WHERE a.MajorName = b.MajorName) a
	WHERE RowNo = 1
	ORDER BY dcjobTypeId

	UPDATE a SET a.Description = b.Description FROM #1 a, dcMajor b WHERE a.dcMajorId = b.Id
	TRUNCATE TABLE ShortDb..dcJobTypeMajorMap

	INSERT INTO dcJobTypeMajorMap
	SELECT dcJobTypeID, MajorName, dcMajorId, Description, PinYin, JianPin
	FROM #1
END
GO

/****** Object:  StoredProcedure [dbo].[spDcRegionByNameUpdate]    Script Date: 2018/12/13 19:13:09 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[spDcRegionByNameUpdate](
	@ID VARCHAR(6),
	@OldName NVARCHAR(100),
	@NewName NVARCHAR(100)
)
AS
BEGIN
	UPDATE dcREgion 
	SET Description = REPLACE(Description, @OldName, @NewName),
	DescriptionEng = REPLACE(DescriptionEng, @OldName, @NewName),
	FullName = REPLACE(FullName, @OldName, @NewName)
	WHERE ID = @ID
END













GO

/****** Object:  StoredProcedure [dbo].[spDeleteCpImageFileSample]    Script Date: 2018/12/13 19:13:09 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--lambo 20110120
--删除logo，Visual的sql自动计划任务
--删除审核不通过的超过30天的logo，Visual。不用修改cpMain里的hasLog,hasVisual的值。因为未审核通过hasLog也是0
CREATE PROCEDURE [dbo].[spDeleteCpImageFileSample]
AS
BEGIN
	SET NOCOUNT ON
	DECLARE cur_cpImage CURSOR
    FOR
        SELECT cpMainID,ImgFile,ImgType FROM cpImage WHERE HasPassed=0 AND CheckDate < GETDATE()-30 
    OPEN cur_cpImage
    DECLARE @cpMainID INT,@ImgFile VARCHAR(150),@imgType INT,@cmdStr VARCHAR(500),@path VARCHAR(500)
    FETCH NEXT FROM cur_cpImage INTO @cpMainID,@imgFile,@imgType
	BEGIN TRY
		EXEC SP_CONFIGURE 'show advanced options', 1
		RECONFIGURE
		EXEC SP_CONFIGURE 'xp_cmdshell', 1
		RECONFIGURE
    
		WHILE @@FETCH_STATUS = 0
		BEGIN      
			IF @ImgType = 1
			BEGIN
				SET @path = (SELECT dbo.photoPath(@cpMainID,4))
				SET @cmdStr = 'del D:\hosting\qlrc.com\imagefolder\Logo\' + @path + '\' + @imgFile    --删除Logo目录
			END
			ELSE IF @ImgType = 2
			BEGIN
				SET @path = (SELECT dbo.photoPath(@cpMainID,4))
				SET @cmdStr = 'del D:\hosting\qlrc.com\imagefolder\Visual\' + @path + '\' + @imgFile    --删除Visual目录
			END
			EXEC master.dbo.xp_cmdshell @cmdStr 
			DELETE FROM cpImage WHERE cpMainID = @cpMainID AND ImgType = @ImgType
			FETCH NEXT FROM cur_cpImage INTO @cpMainID,@imgFile,@imgType
		END
		EXEC SP_CONFIGURE 'xp_cmdshell', 0
		RECONFIGURE
		EXEC SP_CONFIGURE 'show advanced options', 0
		RECONFIGURE
	END TRY
	BEGIN CATCH
	END CATCH
    CLOSE cur_cpImage 
    DEALLOCATE cur_cpImage
END













GO

/****** Object:  StoredProcedure [dbo].[spDeleteFileSample]    Script Date: 2018/12/13 19:13:10 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[spDeleteFileSample]
AS
BEGIN
	EXEC SP_CONFIGURE 'show advanced options', 1
	RECONFIGURE
	EXEC SP_CONFIGURE 'xp_cmdshell', 1
	RECONFIGURE
    DECLARE cur_paPhoto CURSOR
    FOR  
        SELECT p.paMainID, p.PhotoProcessed Photo FROM paPhoto AS p INNER JOIN paMain AS m ON m.ID = p.paMainID
        WHERE m.hasPhoto = 2 AND CheckDate < GETDATE()-30
    OPEN cur_paPhoto
    DECLARE @id INT,@photo VARCHAR(150),@cmdStr VARCHAR(500),@path VARCHAR(500)
    FETCH NEXT FROM cur_paPhoto INTO @id, @photo
	BEGIN TRY
		WHILE @@FETCH_STATUS = 0
		BEGIN      
	--      SET @path = '@echo del D:\hosting\qlrc.com\imagefolder\photo\'+@path+' >>d:\delfile.bat'
	--		EXEC master.dbo.xp_cmdshell @path
	--      SET @cmdStr = '@echo del D:\hosting\qlrc.com\imagefolder\photo\'+@cmdStr+' >>d:\delfile.bat'  --新建一个bat执行文件，点击删除	
	--      EXEC master.dbo.xp_cmdshell @cmdStr
			SET @path = (SELECT dbo.photoPath(@id,1))

			SET @cmdStr = 'del D:\hosting\qlrc.com\imagefolder\photo\' + @path + '\processed\' + @photo    --删除processed目录
			EXEC master.dbo.xp_cmdshell @cmdStr 

			SET @cmdStr = 'del D:\hosting\qlrc.com\imagefolder\photo\' + @path + '\photo\' + @photo    --删除phOTO目录
			EXEC master.dbo.xp_cmdshell @cmdStr 

			DELETE FROM paPhoto WHERE paMainID = @ID
			UPDATE paMain SET HasPhoto = NULL WHERE ID = @ID

			FETCH NEXT FROM cur_paPhoto INTO @id,@photo 
		END
	END TRY
	BEGIN CATCH
	END CATCH
    CLOSE cur_paPhoto 
    DEALLOCATE cur_paPhoto
	EXEC SP_CONFIGURE 'xp_cmdshell', 0
	RECONFIGURE
	EXEC SP_CONFIGURE 'show advanced options', 0
	RECONFIGURE
END













GO

/****** Object:  StoredProcedure [dbo].[spDeleteOrder]    Script Date: 2018/12/13 19:13:10 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[spDeleteOrder]
(
	@Id INT
)
AS
BEGIN
	DECLARE @OrderStatus INT
	SELECT @OrderStatus = OrderStatus FROM caOrder WHERE ID = @Id
	IF @OrderStatus > 6
		UPDATE caORder SET OrderStatus = 6 WHERE ID = @Id

	IF @OrderStatus = 6
		UPDATE caORder SET ReceiveDate = NULL WHERE ID = @Id

	UPDATE caORder SET OpenDate = NULL, IsDeleted = 1 WHERE ID = @Id
	UPDATE caORder SET OpenDate = NULL, IsDeleted = 1 WHERE MainOrderID = @Id

	SELECT isDeleted, * FROM caOrder WHERE Id = @id
END

GO

/****** Object:  StoredProcedure [dbo].[spEmailCheck]    Script Date: 2018/12/13 19:13:10 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[spEmailCheck]
(
	@DeptID AS INT
)
AS
BEGIN
	DECLARE @ManageruserId INT,
		@count INT,
		@RAND INT,
		@i INT,
		@time INT,
		@minute INT,
		@WorkDate int

	SELECT @WorkDate = COUNT(1)
	FROM Sales_WorkDate WITH(NOLOCK)
	WHERE WorkDate = CONVERT(VARCHAR(8), GETDate(), 112)

	IF @WorkDate = 1
	BEGIN
		----deptId=10 客户服务部
		SELECT TOP 1 @ManageruserId = ID
		FROM ManagerUser WITH(NOLOCK)
		WHERE DeptId = @DeptId
		AND Status IN (1, 2)
        AND Type IN (1, 5)
		AND LEN(LTRIM(RTRIM(Email))) > 0
		ORDER BY NEWID()

		SET @time = CAST(RAND() * 8 AS INT) + 9
		--PRINT @TIME
		SET @minute = CAST(RAND() * 60 AS INT)
		IF @time = 12
			SET @time=13
		IF @ManageruserId IS NOT NULL
		INSERT INTO emailcheck (testDate, planhour, planminute, ManageruserId)
		VALUES (CONVERT(VARCHAR(8), GETDate(), 112), @time, @minute, @ManageruserId)
	END
END













GO

/****** Object:  StoredProcedure [dbo].[spEndOrder]    Script Date: 2018/12/13 19:13:10 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[spEndOrder]
(
	@Id INT
)
AS
BEGIN
	UPDATE caOrder SET EndDate = GETDATE() WHERE Id = @Id
End
GO

/****** Object:  StoredProcedure [dbo].[spFindForeignCompany]    Script Date: 2018/12/13 19:13:11 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[spFindForeignCompany]
AS
BEGIN
	CREATE TABLE #t(
		ID int NOT NULL,
		RegisterIP varchar(31) NULL,
		r1 varchar(31) NULL,
		r2 varchar(31) NULL,
		ip1 varchar(31) NULL,
		ip2 varchar(31) NULL,
		ip3 varchar(31) NULL,
		ip4 varchar(31) NULL,
		IP bigint NULL,
		IsForeign tinyint NULL,
		LoginDate DATETIME
	)
	INSERT INTO #t
	SELECT ID, RegisterIP,RegisterIP r1, RegisterIP r2, SPACE(30) ip1, SPACE(30) ip2, SPACE(30) ip3, SPACE(30) ip4, CONVERT(BIGINT, 0) IP, CONVERT(TINYINT, 0) IsForeign, RegDate
	FROM cpMain WITH(NOLOCK)
	WHERE RegisterIp LIKE '%.%.%.%'
	AND RegDate > '2014-11-1' --GETDATE() - 730
	And dcProvinceId = 10
	AND id in(select cpmainid from cplicence where haspassed=1 and checkdate > '2014-11-1')

	INSERT INTO #t
	SELECT DISTINCT b.cpMainId, a.LoginIp, a.LoginIp, a.LoginIp, a.LoginIp, SPACE(30) ip2, SPACE(30) ip3, SPACE(30) ip4, CONVERT(BIGINT, 0) IP, CONVERT(TINYINT, 0) IsForeign, AddDate
	FROM caloginLog a WITH(NOLOCK), caMain b WITH(NOLOCK)
	WHERE a.caMainId = b.Id
	AND a.LoginIp LIKE '%.%.%.%'
	AND a.AddDate >  '2014-8-1' --GETDATE() - 730
	AND b.cpMainId IN(SELECT ID FROM cpMain WITH(NOLOCK) WHERE dcProvinceID = 10)
	AND b.cpmainid in(select cpmainid from cplicence where haspassed=1 and checkdate > '2014-11-1')

	UPDATE #t SET ip1 = LEFT(RegisterIp, CHARINDEX('.', RegisterIP)-1)
	UPDATE #t SET r1 = RIGHT(RegisterIp, LEN(RegisterIp) - CHARINDEX('.', RegisterIP))
	UPDATE #t SET ip2 = LEFT(r1, CHARINDEX('.', r1)-1)
	UPDATE #t SET r2 = RIGHT(r1, LEN(r1) - CHARINDEX('.', r1))
	UPDATE #t SET ip3 = LEFT(r2, CHARINDEX('.', r2)-1)
	UPDATE #t SET ip4 = RIGHT(r2, LEN(r2) - CHARINDEX('.', r2))
	UPDATE #t SET ip4 = 0 where Ip4 Like '%.%'
	DElete from #t where registerip like 'u%'

	UPDATE #t SET IP = CONVERT(BIGINT, Ip1) * 256 * 256 * 256 + CONVERT(BIGINT, Ip2) * 256 * 256 + CONVERT(BIGINT, Ip3) * 256 + CONVERT(BIGINT, Ip4)
	UPDATE a SET IsForeign = 1
	FROM #t a WITH(NOLOCK), dcIpPlace b WITH(NOLOCK)
	WHERE a.Ip >= b.IpStart AND a.Ip <= b.IpEnd
	AND b.InterNational = 1
	
	TRUNCATE TABLE bsForeign
	INSERT INTO bsForeign(id, LoginIp, LoginDate)
	SELECT DISTINCT ID, RegisterIP, LoginDate FROM #t WITH(NOLOCK) WHERE IsForeign = 1

	UPDATE a
	SET a.CompanyName = b.Name
	FROM bsForeign a WITH(NOLOCK), cpMain b WITH(NOLOCK)
	WHERE a.ID = b.Id

	UPDATE a
	SET a.LinkMan = b.Name, a.TelePhone = b.TelePhone, a.Mobile = b.Mobile
	FROM bsForeign a WITH(NOLOCK), caMain b WITH(NOLOCK)
	WHERE a.ID = b.cpMainId
	AND b.AccountType = 1

	UPDATE bsForeign SET ipAddress = dbo.IpPlace(LoginIp)

	SELECT * FROM bsForeign WITH(NOLOCK) ORDER BY Id, LoginDate DESC
END
GO

/****** Object:  StoredProcedure [dbo].[spGenInsert]    Script Date: 2018/12/13 19:13:11 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[spGenInsert]
(
	@tb varchar(100)
)
as
BEGIN
	declare @i int, @s varchar(max), @n varchar(100), @cn varchar(max), @objid int
	declare @t as table (name varchar(100), status int)
	select * into #t from sysobjects where xtype='u' and name like @tb + '%'
	set @s = ''
	set nocount on
	while (select count(*) from #t) > 0
	begin 
		select top 1 @n = name FROM #t
		select @objid = id, @cn='' from sysobjects where name=@n and xtype='u'
		insert @t select name,status FROM syscolumns where id = @objid
		select @cn=@cn + case when @cn='' then '' else ',' end + name from @t
		print 'if (select count(*) from ' + @n +') =0
begin'
		if (select count(*) FROM @t where name='id' and status=128 and status<>64)>0
			print 
'	set identity_insert ' + @n + ' on
	insert into ' + @n + '(' + @cn + ')
	select ' + @cn + ' from maindb..' + @n + ' with(nolock)
	set identity_insert ' + @n + ' off'
		else
			print 
'	insert into ' + @n + '(' + @cn + ')
	select ' + @cn + ' from maindb..' + @n + ' with(nolock)'
		print 'end
go

'
		delete #t where name=@n
		delete @t
	end
	drop table #t
	--PRINT @s
END













GO

/****** Object:  StoredProcedure [dbo].[spGenInsertSQL]    Script Date: 2018/12/13 19:13:11 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[spGenInsertSQL]
(
	@tablename varchar(256)
)
as
begin
	declare @sql varchar(max)
	declare @sqlValues varchar(max)
	set @sql =' ('
	set @sqlValues = 'values (''+'
	select @sqlValues = @sqlValues + cols + ' + '','' + ' ,@sql = @sql + '[' + name + '],'
	from
      (select case
                when xtype in (48,52,56,59,60,62,104,106,108,122,127)       

                     then 'case when '+ name +' is null then ''NULL'' else ' + 'cast('+ name + ' as varchar)'+' end'

                when xtype in (58,61)

                     then 'case when '+ name +' is null then ''NULL'' else '+''''''''' + ' + 'cast('+ name +' as varchar)'+ '+'''''''''+' end'

               when xtype in (167)

                     then 'case when '+ name +' is null then ''NULL'' else '+''''''''' + ' + 'replace('+ name+','''''''','''''''''''')' + '+'''''''''+' end'

                when xtype in (231)

                     then 'case when '+ name +' is null then ''NULL'' else '+'''N'''''' + ' + 'replace('+ name+','''''''','''''''''''')' + '+'''''''''+' end'

                when xtype in (175)

                     then 'case when '+ name +' is null then ''NULL'' else '+''''''''' + ' + 'cast(replace('+ name+','''''''','''''''''''') as Char(' + cast(length as varchar)  + '))+'''''''''+' end'

                when xtype in (239)

                     then 'case when '+ name +' is null then ''NULL'' else '+'''N'''''' + ' + 'cast(replace('+ name+','''''''','''''''''''') as Char(' + cast(length as varchar)  + '))+'''''''''+' end'

                else '''NULL'''

              end as Cols,name

         from syscolumns 

        where id = object_id(@tablename)

      ) T
create table #t(id int, s varchar(max))
	set @sql ='insert #t select 2,''INSERT INTO ['+ @tablename + ']' + left(@sql,len(@sql)-1)+') ' + left(@sqlValues,len(@sqlValues)-4) + ')'' from '+@tablename 
insert #t select 1,'set identity_insert ' + @tablename + ' on'
	--PRINT @sql
	exec (@sql)
insert #t select 3,'set identity_insert ' + @tablename + ' off'
	select * from #t	order by id
end













GO

/****** Object:  StoredProcedure [dbo].[spGenNormalPassword]    Script Date: 2018/12/13 19:13:12 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[spGenNormalPassword]
AS
BEGIN
	DECLARE @s VARCHAR(45), @r INT, @i INT, @Res VARCHAR(20)
	SET @s = '0123456789qwertyuioplkjhgfdsazxcvbnm.!@#$%*_+'

	SELECT @i = 0, @Res = ''
	WHILE @i < 20
	BEGIN
		SET @r = RAND() * 45
		IF @r < 1
			SET @r = 20
		IF @r > 44
			SET @r = 20

		SET @r = @r + 1
		SELECT @Res = @Res + SUBSTRING(@s, @r, 1), @i = @I + 1
	END
	SELECT @Res
END
GO

/****** Object:  StoredProcedure [dbo].[spGenPassword]    Script Date: 2018/12/13 19:13:12 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[spGenPassword]
AS
SET NOCOUNT ON
BEGIN
	DECLARE @Pass INT, @p VARCHAR(20)

	SELECT @Pass = CAST(FLOOR(RAND() * 10) AS INT)
	IF @Pass = 0
		SET @Pass = 1
	IF @Pass > 9
		SET @Pass = 9
	SET @p = LTRIM(STR(@Pass))

	SELECT @Pass = CAST(FLOOR(RAND() * 9000 + 1000) AS INT)
	IF @Pass > 9999
		SET @Pass = 9999
	SET @p = @p + LTRIM(STR(@Pass))

	SELECT @Pass = CAST(FLOOR(RAND() * 900 + 100) AS INT)
	IF @Pass > 999
		SET @Pass = 999
	SET @p = @p + LTRIM(STR(@Pass))

	SELECT @Pass = CAST(FLOOR(RAND() * 90000 + 10000) AS INT)
	IF @Pass > 99999
		SET @Pass = 99999
	SET @p = @p + LTRIM(STR(@Pass))

	SELECT @Pass = CAST(FLOOR(RAND() * 90 + 10) AS INT)
	IF @Pass > 99
		SET @Pass = 99
	SET @p = @p + LTRIM(STR(@Pass))

	SET @p = SUBSTRING(@p, 3, 8)
	
	IF LEFT(@p, 1) = '0'
		SET @P = '1' + LEFT(@p, 7)
	SELECT @p
END
GO

/****** Object:  StoredProcedure [dbo].[spGenRandChar]    Script Date: 2018/12/13 19:13:12 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[spGenRandChar]
(
	@Len INT = 12
)
AS
BEGIN
	DECLARE @i INT, @rnd INT, @Output VARCHAR(50), @c CHAR(1), @Text VARCHAR(118)
	SET @Text = '~!0123456789#$%abcdefghijklmnopqrstuvwxyz&()*+-.0123456789:;=@abcdefghijklmnopqrstuvwxyz^abcdefghijklmnopqrstuvwxyz{|}'
	SELECT @I = 0, @Output = ''
	WHILE @I < @Len
	BEGIN
		SET @Rnd = 117 * RAND() + 1
		SET @c = SUBSTRING(@Text, @Rnd, 1)
		SET @Output = @Output + @c
		SET @I = @I + 1
	END
	SELECT LOWER(@Output)
END
GO

/****** Object:  StoredProcedure [dbo].[spGenUserName]    Script Date: 2018/12/13 19:13:12 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


--######################################3
--创建：Sean 2010-12-2
--生成推广时可用的企业用户名
--######################################3
create PROCEDURE [dbo].[spGenUserName]
(
	@UserName VARCHAR(50),
	@UserNameOut VARCHAR(50) OUTPUT
)
AS
BEGIN
	DECLARE @u AS VARCHAR(50)
	DECLARE @s AS VARCHAR(50)
	DECLARE @i AS INT
	DECLARE @r AS BIT
	
	SET @s = '2356789'
	SET @u = LTRIM(RTRIM(@UserName))	
	SET @r = dbo.ExistUserName(@u)

	WHILE @r = 1
	BEGIN
		SET @i = CAST(FLOOR(RAND() * 7) AS INT)		
		SET @u = @u + SUBSTRING(@s, @i + 1, 1)
		SET @r = dbo.ExistUserName(@u)
	END
	SET @UserNameOut = @u
END


GO

/****** Object:  StoredProcedure [dbo].[spGetCamainOld]    Script Date: 2018/12/13 19:13:13 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[spGetCamainOld]
(
	@dcProvinceID INT,
	@MemberType INT
)
AS

SELECT * FROM camain WHERE cpmainid in(
	SELECT top 100 id FROM cpmain 
	where Valid = 1
	And dcProvinceId = @dcProvinceID
	AND MemberType = @Membertype)













GO

/****** Object:  StoredProcedure [dbo].[spHomePageTableRebuild]    Script Date: 2018/12/13 19:13:13 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

/**
*Peter 2014-02-19 修改，添加山东二级站数据
*2016-09-28 Peter修改，将点评title内容进行了修改
*/
CREATE PROCEDURE [dbo].[spHomePageTableRebuild]
AS
SET NOCOUNT ON
BEGIN
	IF DATEPART(HOUR, GETDATE())<8 OR DATEPART(HOUR, GETDATE()) > 17 --OR DATEPART(HOUR, GETDATE()) = 12
		RETURN

	DECLARE @t AS TABLE(ID INT, Num INT)
	DECLARE @i INT, @N INT
	INSERT @t SELECT 1, 5
	INSERT @t SELECT 3, 3
	INSERT @t SELECT 5, 3
	INSERT @t SELECT 7, 5
	INSERT @t SELECT 8, 3
	INSERT @t SELECT 9, 3
	INSERT @t SELECT 10, 3
	INSERT @t SELECT 11, 3
	INSERT @t SELECT 12, 3
	INSERT @t SELECT 13, 3

	SET NOCOUNT ON;
	DECLARE @D DATETIME, @UR BIT, @UN BIT, @UI BIT, @UL BIT, @Uc BIt, @csp BIT
	SELECT @D = MAX(ModifyDate) FROM RecruitMent WITH(NOLOCK)
	IF @D > DATEADD(MINUTE, -15, GETDATE())
		SET @UR = 1

	SELECT @D = MAX(RefreshDate) FROM QlrcNews WITH(NOLOCK)
	IF @D > DATEADD(MINUTE, -15, GETDATE())
		SET @UN = 1
		--SET @UN = 1
	SELECT @D = MAX(AddDate) FROM ivgt_investigation WITH(NOLOCK)
	IF @D > DATEADD(MINUTE, -15, GETDATE())
		SET @UI = 1

	SELECT @D = RefreshDate FROM LogDb..HomePageTableRefresh WITH(NOLOCK) WHERE TAbleName = 'link'
	IF @D > DATEADD(MINUTE, -15, GETDATE())
		SET @UL = 1

	SELECT @D = MAX(AddDate) FROM WutongguoDb..CpPreach WITH(NOLOCK)
	IF @D > DATEADD(MINUTE, -15, GETDATE())
		SET @Uc = 1

	IF (DATEPART(HOUR, GETDATE()) BETWEEN 8 AND 21) AND (DATEPART(MINUTE, GETDATE()) % 30 < 10)
	BEGIN
		SET @uc = 1
	END

	IF DATEPART(HOUR, GETDATE()) IN(3, 4, 8, 9, 10, 14, 15) AND DATEPART(MINUTE, GETDATE()) < 10
	BEGIN
		SELECT @Ur = 1, @Un = 1, @Ui = 1, @Ul = 1, @Uc = 1
	END

	SELECT @D = MAX(crDate) FROM SearchDb..CampusSchoolPartner12 WITH(NOLOCK)
	IF @D > DATEADD(MINUTE, -15, GETDATE())
		SET @csp = 1

	IF NOT EXISTS(SELECT 'x' FROM SearchDb..CampusSchoolPartner12 WITH(NOLOCK) WHERE crDate > DATEADD(HOUR, -3, GETDATE()))
	BEGIN
		 SELECT @csp = 1
	END

	DECLARE curProvince CURSOR FOR 
		SELECT ID, IsMainSite FROM dcSubSite WITH(NOLOCK) WHERE IsMainSite = 1 OR ID LIKE '32%' ORDER BY ID
	OPEN curProvince
	DECLARE @dcProvinceID INT, @IsMainSite BIT
	FETCH NEXT FROM curProvince INTO @dcProvinceID, @IsMainSite
	WHILE @@FETCH_STATUS = 0
	BEGIN
		--招聘会
		IF @UR = 1
		BEGIN
			DELETE SearchDb..HpRecruitmeetingDay WHERE ProvinceID LIKE LTRIM(STR(@dcProvinceID)) + '%'

			INSERT INTO SearchDb..HpRecruitmeetingDay (PreID,ProvinceID,Title,AddDate,WeekDay,MonthDay,startDate)
			SELECT TOP 15 a.Id,CASE @dcProvinceID WHEN 3202 THEN 3202 ELSE @dcProvinceID END,
			RecruitmentName, b.ModifyDate, '', '', Replace(CONVERT(VARCHAR(10),Begindate,102),'.','-')
			FROM RecruitMent a WITH(NOLOCK), RecruitMentDept b WITH(NOLOCK)
			WHERE a.RecruitMentDeptID=b.ID AND b.ID<>1767 AND CityID LIKE LTRIM(STR(@dcProvinceID)) + '%'
			AND EndDate > GETDATE() AND a.IsPause=0 AND b.IsPause=0
			AND LEN(ManagerUserId) > 0
			ORDER BY a.BeginDate
		END
		IF @IsMainSite = 1
		BEGIN
			IF @UN = 1
			BEGIN
				--政府招考
				DELETE SearchDb..HpQlrcGovDay WHERE VersionId = @dcProvinceID

				IF @dcProvinceID < 99
 				BEGIN
					INSERT INTO SearchDb..HpQlrcGovDay (PreID,versionid,Title,announcedate ,content,type,refreshdate)
					SELECT TOP 15 id, @dcProvinceID,title, announcedate ,content,type,refreshdate
					FROM QlrcNews WITH(NOLOCK)
					WHERE versionid = @dcProvinceID --or versionid=0)
					AND NewsType = 2
					AND detailtype like '%,2,%'
					ORDER BY refreshdate DESC
				END
				ELSE
				BEGIN
					INSERT INTO SearchDb..HpQlrcGovDay (PreID,versionid,Title,announcedate ,content,type,refreshdate)
 					SELECT TOP 15 id, @dcProvinceID,title, announcedate ,content,type,refreshdate
					FROM QlrcNews WITH(NOLOCK)
					WHERE Versionid = LEFT(@dcProvinceID, 2)-- OR Versionid = 0)
					AND CHARINDEX((SELECT Abbr FROM dcRegion WHERE ID = @dcProvinceID),Title) <> 0
					AND NewsType = 2
					AND detailtype like '%,2,%'
					ORDER BY refreshdate DESC
				END

				--职场新闻
				DELETE SearchDb..HpQlrcNewsDay WHERE dcSubSiteId = @dcProvinceID

				INSERT INTO SearchDb..HpQlrcNewsDay (PreID, dcSubSiteId, versionid,Title,announcedate ,content,type,refreshdate)
					SELECT TOP 15 id, @dcProvinceID, versionid, title, announcedate ,content,type,refreshdate
					FROM QlrcNews WITH(NOLOCK)
					WHERE versionid = @dcProvinceID --or versionid=0)
					AND NewsType = 2
					AND detailtype not like '%,2,%'
					ORDER BY refreshdate DESC
			END

			IF @dcProvinceID < 100
			BEGIN				
				--用户调查
				IF @UI = 1
				BEGIN
					DELETE SearchDb..HPInvestigationDay WHERE ProvinceID = @dcProvinceID

					INSERT INTO SearchDb..HPInvestigationDay (Preid,ProvinceID, title, description, reporturl, type, reporttitle, addDate, ExLink)
					SELECT TOP 15 id, @dcProvinceID, title, description, reporturl, type, reporttitle, addDate, ExLink
					FROM ivgt_investigation WITH(NOLOCK)
					WHERE EndDate < GETDATE() 
					AND province LIKE '%' + CAST(@dcProvinceID AS CHAR(2)) + '%'
					AND homepagesee = 1
					ORDER BY EndDate DESC

					DECLARE @HasOne INT, @Id INT, @Title NVARCHAR(50), @DescrIption NVARCHAR(MAX), @AddDate SMALLDATETIME, @Exlink VARCHAR(100)
 					SELECT TOP 1 @HasOne = 1, @Id = id, @Title = title, 
						@DescrIption = description, @AddDate = AddDate, @ExLink = ExLink
					FROM ivgt_investigation WITH(NOLOCK)
					WHERE Type = 2 
					AND ENDdate > GETDATE()
					AND Province LIKE '%' + LTRIM(STR(@dcProvinceID)) + '%'
					AND AnswerAfterLogin = 0
					ORDER BY Id DESC

					IF(@HasOne = 1)
					BEGIN
						DELETE SearchDb..ivgt_investigationDay WHERE ProvinceId = @dcProvinceID
						INSERT SearchDb..ivgt_investigationDay(Id, Provinceid, Title, Description, adddate,exLink)
						SELECT @Id, @dcProvinceID, @Title, @Description, @adddate, @ExLink
					END
				END
				---------------------------------------------
				IF @UN = 1
				BEGIN
					DELETE SearchDb..HpJobNews WHERE VersionId = @dcProvinceID

					SET @i = 0
					WHILE(@i < 13)
					BEGIN
						SELECT TOP 1 @I = Id, @n = Num FROM @t WHERE ID > @I
						INSERT INTO SearchDb..HpJobNews (ID, VersionId, DetailType, NewsType, Title, [Content], RefreshDate)
						SELECT TOP (@N) ID, @dcProvinceID, LTRIM(STR(@I)), NewsType, Title, [Content], RefreshDate
						FROM QlrcNews WITH(NOLOCK) 
						WHERE DetailType LIKE '%,' + LTRIM(STR(@I)) + ',%' AND VersionId = @dcProvinceID --Or VersionId = 0)
						ORDER BY RefreshDate DESC				
					END
				END
			END

			--友情连接
			IF @UL = 1
			BEGIN
				DELETE SearchDb..hplinkDay WHERE ProvinceID LIKE CONVERT(VARCHAR(2),@dcProvinceID) + '%'

				INSERT INTO SearchDb..hplinkDay (ProvinceID,text, link,nofollow, category)
				SELECT versionid,text, link, nofollow, category
				FROM link WITH(NOLOCK)
				WHERE versionid like CONVERT(VARCHAR(2), @dcProvinceID)+'%'
				AND type=1 
				AND valid=1
				AND orderby<100
				AND deleted=0
				ORDER BY orderby,ID
			END

			--校园招聘 宣讲会
			IF @Uc = 1
			BEGIN
				DELETE SearchDb..HpCampus WHERE ProvinceID = @dcProvinceID
				INSERT INTO SearchDb..HpCampus (ProvinceID, PresentationID, CompanyID, CompanyName, RegionName, SchoolName, BeginTime, HomePage, cpSecondId)
				SELECT TOP 15 @dcProvinceID, a.Id, b.ID, b.Name, d.Description, c.Name, a.BeginDate, '', b.SecondId
				FROM WutongguoDb..CpPreach a, WutongguoDb..cpMain b, WutongguoDb..dcSchool c, WutongguoDb..dcRegion d
				WHERE a.cpMainID = b.ID AND a.dcSchoolID = c.ID AND a.dcRegionID = d.ID AND a.EndDate > GETDATE() 
				ORDER BY CASE CHARINDEX(LTRIM(STR(@dcProvinceID)), a.dcRegionID) WHEN 1 THEN 1 ELSE 2 END , 
					a.BeginDate, a.AddDate DESC
			END
		END
		ELSE
		BEGIN
			--政府招考
			IF @Un = 1
			BEGIN
				DELETE SearchDb..HpQlrcGovDay WHERE versionid = @dcProvinceID

				INSERT INTO SearchDb..HpQlrcGovDay (PreID,versionid,Title,announcedate ,content,type,refreshdate)
				SELECT TOP 15 id, @dcProvinceID,title, announcedate ,content,type,refreshdate
				FROM QlrcNews WITH(NOLOCK)
  				WHERE (Versionid = 32 OR Versionid=0)
				AND CHARINDEX((SELECT Abbr FROM dcRegion WHERE ID = @dcProvinceID),Title) <> 0
				AND NewsType = 2
				AND detailtype like '%,2,%'
				ORDER BY refreshdate DESC
			END
		END
		
		FETCH NEXT FROM curProvince INTO @dcProvinceID, @IsMainSite
	END
	CLOSE curProvince
	DEALLOCATE curProvince

	IF @UN = 1
		UPDATE SearchDb..HpJobNews SET [CONTENT] = '' WHERE DetailType NOT IN(1, 7)

	IF @csp = 1
	BEGIN
		TRUNCATE TABLE SearchDb..CampusSchoolPartner12
		INSERT INTO SearchDb..CampusSchoolPartner12
		SELECT * 
		FROM (SELECT a.*, GETDATE() crDate, LEFT(dcRegionID, 2) dcProvinceId, ROW_NUMBER() OVER(PARTITION BY LEFT(dcRegionID, 2) ORDER BY OrderBy, AddDate DESC) RowNo
			FROM MarketDB..CampusSchool a WITH(NOLOCK)    
			WHERE EXISTS(SELECT 'x' FROM marketdb..CampusPresentation b WITH(NOLOCK) 
				WHERE SchoolID = a.id)) b
		WHERE b.RowNo < 13
	END

	IF @UN = 1
	BEGIN
		DELETE SearchDb..HpQlrcNewsDay WHERE VersionId = 0

		INSERT INTO SearchDb..HpQlrcNewsDay (PreID, dcSubSiteId, versionid, Title, announcedate, content, type, refreshdate)
		SELECT TOP 1 id, 0, versionid, title, announcedate, content, type, refreshdate
		FROM QlrcNews WITH(NOLOCK)
		WHERE versionid = 0
		AND NewsType = 2
		AND detailtype not like '%,2,%'
		ORDER BY refreshdate DESC
	END
END
GO

/****** Object:  StoredProcedure [dbo].[sphpHighSalaryCompanyNewRebuild]    Script Date: 2018/12/13 19:13:13 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[sphpHighSalaryCompanyNewRebuild]
AS
SET NOCOUNT ON
BEGIN
	SELECT TOP 0 * INTO #t FROM hpHighSalaryCompanyNew	

	INSERT INTO #t(dcRegionID, JobID, JobSecondID, JobName, CpMainID, CpSecondID, CpName, dcSalaryID, RefreshDate, LogoUrl, AddDate, RowNo)
	SELECT dcProvinceId, JobId, JobSecondID, JobName, CpMainID, CpSecondID, CpName, dcSalaryID, RefreshDate, LogoUrl, GETDATE(), RowNo
	FROM (SELECT b.dcProvinceId, a.ID JobId, a.SecondID JobSecondID, a.Name JobName, b.ID CpMainID,
			b.SecondID CpSecondID, b.Name CpName, a.dcSalaryID, b.RefreshDate, '' LogoUrl, 
			ROW_NUMBER() OVER(PARTITION BY b.Id ORDER BY a.dcSalaryId DESC) RowNo
		FROM JobPublish a WITH(NOLOCK)
		INNER JOIN CpMain b WITH(NOLOCK) ON b.id = a.CpMainID
		WHERE a.Valid = 1
		AND b.Valid = 1
		AND (
				(b.dcProvinceId IN(32, 30, 10, 31, 40, 71, 61) 
				AND a.DcSalaryID BETWEEN 11 AND 17
				)
			OR
				(b.dcProvinceId NOT IN(32, 30, 10, 31, 40, 71, 61)
				AND a.DcSalaryID BETWEEN 9 AND 17
				)
			)
		) a
	WHERE RowNo < 4
	--DELETE FROM #t WHERE JobId NOT IN(SELECT MAX(JobId) FROM #t GROUP BY cpMainId)
	DELETE FROM #t WHERE cpMainId IN(5654050) AND JobID NOT IN(3990967)
	UPDATE #t SET LogoUrl = (SELECT TOP 1 ImgFile FROM cpImage b WITH(NOLOCK) WHERE #t.cpMainId = b.cpMainId AND b.HasPassed = 1 AND b.ImgType = 1 AND b.AddDate > '2016-11-16')

	DELETE FROM #t WHERE LogoUrl IS NULL

	TRUNCATE TABLE hpHighSalaryCompanyNew

	INSERT INTO hpHighSalaryCompanyNew(dcRegionID, JobID, JobSecondID, JobName, CpMainID, CpSecondID, CpName, dcSalaryID, RefreshDate, LogoUrl, AddDate)
	SELECT dcRegionID, JobID, JobSecondID, JobName, CpMainID, CpSecondID, CpName, dcSalaryID, RefreshDate, LogoUrl, AddDate FROM #t
END
GO

/****** Object:  StoredProcedure [dbo].[spHpHighSalaryCompanyRebuild]    Script Date: 2018/12/13 19:13:14 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[spHpHighSalaryCompanyRebuild]
AS
SET NOCOUNT ON
BEGIN
	SELECT TOP 0 * INTO #t FROM hpHighSalaryCompany	

	INSERT INTO #t(dcRegionID, JobID, JobSecondID, JobName, CpMainID, CpSecondID, CpName, dcSalaryID, RefreshDate, LogoUrl, AddDate, RowNo)
	SELECT dcProvinceId, JobId, JobSecondID, JobName, CpMainID, CpSecondID, CpName, dcSalaryID, RefreshDate, LogoUrl, GETDATE(), 0
	FROM (SELECT b.dcProvinceId, a.ID JobId, a.SecondID JobSecondID, a.Name JobName, b.ID CpMainID,
			b.SecondID CpSecondID, b.Name CpName, a.dcSalaryID, b.RefreshDate, '' LogoUrl, 
			ROW_NUMBER() OVER(PARTITION BY b.dcProvinceId ORDER BY a.RefreshDate DESC, b.Id DESC, a.Id DESC) RowNo
		FROM JobPublish a WITH(NOLOCK)
		INNER JOIN CpMain b WITH(NOLOCK) ON b.id = a.CpMainID
		WHERE a.Valid = 1
		AND b.Valid = 1
		AND a.DcSalaryID BETWEEN 9 AND 12) a

	DELETE FROM #t WHERE JobId NOT IN(SELECT MAX(JobId) FROM #t GROUP BY cpMainId)

	UPDATE #t SET LogoUrl = (SELECT TOP 1 ImgFile FROM cpImage b WITH(NOLOCK) WHERE #t.cpMainId = b.cpMainId AND b.HasPassed = 1 AND b.ImgType = 1)
	TRUNCATE TABLE hpHighSalaryCompany
	INSERT INTO hpHighSalaryCompany(dcRegionID, JobID, JobSecondID, JobName, CpMainID, CpSecondID, CpName, dcSalaryID, RefreshDate, LogoUrl, AddDate)
	SELECT dcRegionID, JobID, JobSecondID, JobName, CpMainID, CpSecondID, CpName, dcSalaryID, RefreshDate, LogoUrl, AddDate FROM #t

END
GO

/****** Object:  StoredProcedure [dbo].[spJobByRefreshBatchUpdate]    Script Date: 2018/12/13 19:13:14 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[spJobByRefreshBatchUpdate]
AS
SET NOCOUNT ON
BEGIN
	DECLARE @d VARCHAR(14), @r varchar(20), @d2 VARCHAR(14)
	SET @d = CONVERT(VARCHAR(14), GETDATE(), 120)
	SET @d2 = CONVERT(VARCHAR(14), GETDATE() - 1, 120)
	SET @r = '2016-09-08 14:01:00'

	CREATE TABLE #t(Id INT IDENTITY(1, 1), RefreshDate DATETIME, Cnt INT)
	INSERT INTO #t
	SELECT TOP 5 a.Refreshdate, COUNT(*)
	FROM Job a, cpMain b
	WHERE a.cpMainId = b.id
	AND a.Refreshdate > GETDATE() - 1
	GROUP BY a.Refreshdate
	HAVING COUNT (*) > 900
	ORDER BY COUNT(*) DESC
	DECLARE @Id INT
	SET @Id = 0
	WHILE EXISTS(SELECT 'x' FROM #t WHERE Id > @Id)
	BEGIN
		SELECT TOP 1 @Id = Id, @r = RefreshDate FROM #t WHERE Id > @Id ORDER BY ID

		UPDATE a SET a.Refreshdate = @d + LTRIM(STR(DATEPART(MINUTE, b.LastLogindate)))
		FROM Job a, cpMain b
		WHERE a.cpMainId = b.Id
		AND a.RefreshDate = @r
		AND DATEPART(MINUTE, b.LastLogindate) < DATEPART(MINUTE, GETDATE())
		AND a.Valid = 1

		UPDATE a SET a.Refreshdate = @d + LTRIM(STR(DATEPART(MINUTE, b.LastLogindate)))
		FROM Job a, cpMain b
		WHERE a.cpMainId = b.Id
		AND a.RefreshDate = @r
		AND DATEPART(MINUTE, b.LastLogindate) >= DATEPART(MINUTE, GETDATE())
		AND a.Valid = 1
	END

	SELECT * FROM #t
END
GO

/****** Object:  StoredProcedure [dbo].[spJobDateReport]    Script Date: 2018/12/13 19:13:14 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


--********************************************
--创建人：Lambo
--创建时间：2013-01-31
--用途：用于每日记录职位发布效果统计的数据
--********************************************
CREATE PROCEDURE [dbo].[spJobDateReport]
AS
BEGIN
	--取昨天
	DECLARE @yesterday VARCHAR(10)
	SET @yesterday = CONVERT(VARCHAR(10), GETDATE()-1, 120)

	-- 将昨天一天的数据填充到表里
	INSERT INTO Reportdb..jobReportData( JobID,CountDate,applyCount,viewCount,interview,interviewreply,interviewresult)
	SELECT id ,dbo.DateToReportDay(GETDATE()),
		(SELECT COUNT(1) FROM exjobapply WITH(NOLOCK) WHERE  JobID=a.id AND adddate >@yesterday AND adddate<@yesterday+' 23:59'  ),
		(SELECT COUNT(1) FROM pajobviewlog WITH(NOLOCK) WHERE  JobID=a.id AND adddate >@yesterday AND adddate<@yesterday+' 23:59' ),
		(SELECT COUNT(1) FROM exinterview WITH(NOLOCK) WHERE  JobID=a.id AND adddate >@yesterday AND adddate<@yesterday+' 23:59' ),
		(SELECT COUNT(1) FROM exinterview WITH(NOLOCK) WHERE  JobID=a.id AND replydate is not null AND adddate >@yesterday AND adddate<@yesterday+' 23:59' ),
		(SELECT COUNT(1) FROM exinterview WITH(NOLOCK) WHERE  JobID=a.id AND replydate is not null AND result=1 AND adddate >@yesterday AND adddate<@yesterday+' 23:59')
	FROM job a WITH(NOLOCK) 
	WHERE isdelete=0
	AND AddDate < @yesterday+' 23:59' 
	AND IssueEnd > @yesterday
	
	--删除全部是0的数据
	DELETE FROM Reportdb..JobReportData WHERE applyCount=0 AND viewCount=0 AND interview=0 AND interviewreply=0 AND interviewresult=0

	--vip删除780天以前的数据
	DELETE a FROM Reportdb..jobReportData a, Job b, cpMain c 
	WHERE a.JobId = b.ID AND b.cpMainID = c.ID AND a.CountDate < dbo.ReportDayToDate(780) AND MemberType>=3
	
	--普通会员以下的删除14个月前的数据
	DELETE a FROM Reportdb..jobReportData a, Job b, cpMain c 
	WHERE a.JobId = b.ID AND b.cpMainID = c.ID AND a.CountDate<  dbo.ReportDayToDate(440) AND MemberType<3 
	AND NOT EXISTS(SELECT 'x' FROM caOrder WHERE cpMainID = c.ID AND OrderType in (1,2,8) AND EndDate<GETDATE()-92 AND OpenDate IS NOT NULL AND IsDeleted=0)
		
	--过期收费会员删除780天前的数据
	DELETE a FROM Reportdb..jobReportData a, Job b, cpMain c 
	WHERE a.JobId = b.ID AND b.cpMainID = c.ID 
	AND a.CountDate<  dbo.ReportDayToDate(780) AND MemberType<3 
	AND EXISTS(SELECT 'x' FROM caOrder WHERE cpMainID = c.ID AND OrderType in (1,2,8) AND EndDate>=GETDATE()-92 AND OpenDate IS NOT NULL AND IsDeleted=0)
END 













GO

/****** Object:  StoredProcedure [dbo].[spJobDateReportDetail]    Script Date: 2018/12/13 19:13:14 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


--********************************************
--创建人：Lambo
--创建时间：2013-01-31
--用途：用于每日记录应聘简历分析数据
--********************************************
CREATE PROCEDURE [dbo].[spJobDateReportDetail]
AS
BEGIN
	DECLARE @Yesterday VARCHAR(10)
	DECLARE @Today VARCHAR(8)
	SELECT @Yesterday = CONVERT(VARCHAR(10),GETDATE()-1,120),@Today = dbo.DateToReportDay(GETDATE())
	--首先填充表
	INSERT INTO Reportdb..JobReportDetailData	(JobId,CountDate) 
	SELECT id,@Today 
	FROM JOB a WITH(NOLOCK) 
	WHERE IsDelete=0
	AND EXISTS(SELECT 'x' FROM exJobapply x WITH(NOLOCK) WHERE x.JobID=a.ID  AND x.AddDate >@yesterday AND x.AddDate<@yesterday+' 23:59')

	DECLARE @t TABLE(
		JobID INT,
		cvMainID INT
	)
	INSERT INTO @t SELECT JobID,cvMainID FROM exJobapply WITH(NOLOCK) WHERE AddDate >@Yesterday AND AddDate<@Yesterday+' 23:59'

	--更新工作经验
	UPDATE a 
		SET WorkYears1 = (SELECT COUNT(1) FROM @t,cvMain y WITH(NOLOCK) WHERE JobID=a.JobID AND (RelatedWorkYears=0 OR EXISTS(SELECT 'x' FROM paMain WITH(NOLOCK) WHERE Name IS NOT NULL AND Mobile IS NULL AND Attachment IS NOT NULL AND ID = y.PaMainID )) AND cvMainID = y.id) ,
		WorkYears2 = (SELECT COUNT(1) FROM @t,cvMain y WITH(NOLOCK) WHERE JobID=a.JobID AND RelatedWorkYears>=1 AND RelatedWorkYears<=2  AND cvMainID = y.id) ,
		WorkYears3 = (SELECT COUNT(1) FROM @t,cvMain y WITH(NOLOCK) WHERE JobID=a.JobID AND RelatedWorkYears>=3 AND RelatedWorkYears<=5   AND cvMainID = y.id) ,
		WorkYears4 = (SELECT COUNT(1) FROM @t,cvMain y WITH(NOLOCK) WHERE JobID=a.JobID AND RelatedWorkYears>=6 AND RelatedWorkYears<=10  AND cvMainID = y.id) ,
		WorkYears5 = (SELECT COUNT(1) FROM @t,cvMain y WITH(NOLOCK) WHERE JobID=a.JobID AND RelatedWorkYears>10 AND cvMainID = y.id) 
	FROM Reportdb..JobReportDetailData a 
	WHERE a.CountDate=@Today
 

	--更新年龄
	UPDATE a 
		SET Age1 = (SELECT COUNT(1) FROM @t,cvMain y WITH(NOLOCK), paMain z WITH(NOLOCK) WHERE JobID=a.JobID AND dbo.birthtoage(z.birthday)<=22 AND z.birthday IS NOT NULL  AND cvMainID = y.id AND y.pamainid = z.id) ,
		Age2 = (SELECT COUNT(1) FROM @t,cvMain y WITH(NOLOCK), paMain z WITH(NOLOCK) WHERE JobID=a.JobID AND dbo.birthtoage(z.birthday)>=23 AND dbo.birthtoage(z.birthday)<=25  AND cvMainID = y.id AND y.pamainid = z.id) ,
		Age3 = (SELECT COUNT(1) FROM @t,cvMain y WITH(NOLOCK), paMain z WITH(NOLOCK) WHERE JobID=a.JobID AND dbo.birthtoage(z.birthday)>=26 AND dbo.birthtoage(z.birthday)<=29  AND cvMainID = y.id AND y.pamainid = z.id) ,
		Age4 = (SELECT COUNT(1) FROM @t,cvMain y WITH(NOLOCK), paMain z WITH(NOLOCK) WHERE JobID=a.JobID AND dbo.birthtoage(z.birthday)>=30 AND dbo.birthtoage(z.birthday)<=35  AND cvMainID = y.id AND y.pamainid = z.id) ,
		Age5 = (SELECT COUNT(1) FROM @t,cvMain y WITH(NOLOCK), paMain z WITH(NOLOCK) WHERE JobID=a.JobID AND dbo.birthtoage(z.birthday)>35  AND cvMainID = y.id AND y.pamainid = z.id) ,
		Age6 = (SELECT COUNT(1) FROM @t,cvMain y WITH(NOLOCK), paMain z WITH(NOLOCK) WHERE JobID=a.JobID AND z.birthday IS NULL AND cvMainID = y.id AND y.pamainid = z.id) 
	FROM Reportdb..JobReportDetailData a 
	WHERE a.CountDate=@Today

	--更新学历
	UPDATE a 
		SET Degree1 = (SELECT COUNT(1) FROM exJobapply x WITH(NOLOCK),cvMain y WITH(NOLOCK) WHERE JobID=a.JobID AND Degree=1 AND cvMainID = y.id) , 
		Degree2 = (SELECT COUNT(1) FROM @t,cvMain y WITH(NOLOCK) WHERE JobID=a.JobID AND Degree=2 AND cvMainID = y.id) ,
		Degree3 = (SELECT COUNT(1) FROM @t,cvMain y WITH(NOLOCK) WHERE JobID=a.JobID AND Degree=3 AND cvMainID = y.id) ,
		Degree4 = (SELECT COUNT(1) FROM @t,cvMain y WITH(NOLOCK) WHERE JobID=a.JobID AND Degree=4 AND cvMainID = y.id) ,
		Degree5 = (SELECT COUNT(1) FROM @t,cvMain y WITH(NOLOCK) WHERE JobID=a.JobID AND Degree=5 AND cvMainID = y.id) ,
		Degree6 = (SELECT COUNT(1) FROM @t,cvMain y WITH(NOLOCK) WHERE JobID=a.JobID AND Degree=6 AND cvMainID = y.id) ,
		Degree7 = (SELECT COUNT(1) FROM @t,cvMain y WITH(NOLOCK) WHERE JobID=a.JobID AND Degree=7 AND cvMainID = y.id) ,
		Degree8 = (SELECT COUNT(1) FROM @t,cvMain y WITH(NOLOCK) WHERE JobID=a.JobID AND Degree=8 AND cvMainID = y.id), 
		Degree9 = (SELECT COUNT(1) FROM @t,cvMain y WITH(NOLOCK) WHERE JobID=a.JobID AND (Degree=0 OR Degree IS NULL OR EXISTS(SELECT 'x' FROM paMain(NOLOCK) WHERE Name IS NOT NULL AND Mobile IS NULL AND Attachment IS NOT NULL AND ID = y.PaMainID )) AND cvMainID = y.id) 
	FROM Reportdb..JobReportDetailData a 
	WHERE a.CountDate=@Today

	--更新性别
	UPDATE a 
		SET Male = (SELECT COUNT(1) FROM @t,cvMain y WITH(NOLOCK), paMain z WITH(NOLOCK) WHERE JobID=a.JobID AND z.Gender=0 AND cvMainID = y.id AND y.pamainid = z.id),
		Female = (SELECT COUNT(1) FROM @t,cvMain y WITH(NOLOCK), paMain z WITH(NOLOCK) WHERE JobID=a.JobID AND z.Gender=1 AND cvMainID = y.id AND y.pamainid = z.id)
	FROM Reportdb..JobReportDetailData a 
	WHERE a.CountDate=@Today

	--更新期望月薪
	UPDATE a 
		SET Salary1 = (SELECT COUNT(1) FROM @t,cvMain y WITH(NOLOCK) WHERE JobID=a.JobID AND dcSalaryID=2 AND cvMainID = y.id) , 
		Salary2 = (SELECT COUNT(1) FROM @t,cvMain y WITH(NOLOCK) WHERE JobID=a.JobID AND dcSalaryID=3 AND cvMainID = y.id) , 
		Salary3 = (SELECT COUNT(1) FROM @t,cvMain y WITH(NOLOCK) WHERE JobID=a.JobID AND dcSalaryID=4 AND cvMainID = y.id) ,
		Salary4 = (SELECT COUNT(1) FROM @t,cvMain y WITH(NOLOCK) WHERE JobID=a.JobID AND dcSalaryID=5 AND cvMainID = y.id) ,
		Salary5 = (SELECT COUNT(1) FROM @t,cvMain y WITH(NOLOCK) WHERE JobID=a.JobID AND dcSalaryID=6 AND cvMainID = y.id) ,
		Salary6 = (SELECT COUNT(1) FROM @t,cvMain y WITH(NOLOCK) WHERE JobID=a.JobID AND dcSalaryID=7 AND cvMainID = y.id) ,
		Salary7 = (SELECT COUNT(1) FROM @t,cvMain y WITH(NOLOCK) WHERE JobID=a.JobID AND dcSalaryID>=8 AND cvMainID = y.id) ,
		Salary8 = (SELECT COUNT(1) FROM @t,cvMain y WITH(NOLOCK) WHERE JobID=a.JobID AND (dcSalaryID=0 OR dcSalaryID IS NULL OR EXISTS(SELECT 'x' FROM paMain(NOLOCK) WHERE Name IS NOT NULL AND Mobile IS NULL AND Attachment IS NOT NULL AND ID = y.PaMainID )) AND cvMainID = y.id)  
	FROM Reportdb..JobReportDetailData a 
	WHERE a.CountDate=@Today
 
	--删除过期数据
	--收费会员删除半年前的数据
	DELETE a FROM Reportdb..JobReportDetailData a, Job b, cpMain c 
	WHERE a.JobId = b.ID AND b.cpMainID = c.ID AND a.CountDate< dbo.ReportDayToDate(183) AND MemberType>=3
	
	--普通会员以下的删除2个月前的数据
	DELETE a FROM Reportdb..JobReportDetailData a, Job b, cpMain c 
	WHERE a.JobId = b.ID AND b.cpMainID = c.ID AND a.CountDate< dbo.ReportDayToDate(62) AND MemberType<2 
		AND NOT EXISTS(SELECT 'x' FROM caOrder WHERE cpMainID = c.ID AND OrderType in (1,2,8) AND EndDate<GETDATE()-62 AND OpenDate IS NOT NULL AND IsDeleted=0)
		
	--过期收费会员删除半年前的数据
	DELETE a FROM Reportdb..JobReportDetailData a, Job b, cpMain c 
	WHERE a.JobId = b.ID AND b.cpMainID = c.ID AND a.CountDate< dbo.ReportDayToDate(183) AND MemberType<3 
		AND EXISTS(SELECT 'x' FROM caOrder WHERE cpMainID = c.ID AND OrderType in (1,2,8) AND EndDate>=GETDATE()-62 AND OpenDate IS NOT NULL AND IsDeleted=0)
		
END













GO

/****** Object:  StoredProcedure [dbo].[spJobNameCopySave]    Script Date: 2018/12/13 19:13:16 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[spJobNameCopySave]
AS
BEGIN
	TRUNCATE TABLE JobNameCopy

	INSERT INTO JobNameCopy
	SELECT a.dcProvinceId, b.Name, '', COUNT(*), GETDATE()
	FROM cpMainPublish a WITH(NOLOCK), jobPublish b WITH(NOLOCK)
	WHERE a.Id = b.cpMainId
	AND a.Valid = 1
	AND b.Valid = 1
	GROUP BY a.dcProvinceId, b.Name

	UPDATE JobNameCopy SET Pinyin = dbo.ToPinYin(JobName)
END
GO

/****** Object:  StoredProcedure [dbo].[spKpi_OcByTestSelect]    Script Date: 2018/12/13 19:13:16 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[spKpi_OcByTestSelect]
(
	@SuperiorId int,
	@YearMonth VARCHAR(6)
)
AS
BEGIN
	SELECT DISTINCT ManagerUserID ID INTO #t
	FROM kpi_oc 
	WHERE yearmonth = @YearMonth
	AND ManagerUserId IN(SELECT Id FROM ManagerUser WHERE Superior = @SuperiorId)

	DECLARE @t AS TABLE(ID INT, AllScore INT, HasObjHigher INT, OrderRight INT, SignRight INT, FormatRight INT)
	DECLARE @Id INT, @AllScore INT, @HasObjHigher BIT, @OrderRight BIT, @SignRight BIT, @FormatRight BIT
	SET @Id = 0
	WHILE EXISTS(SELECT 'x' FROM #t WHERE ID > @Id)
	BEGIN
		SELECT TOP 1 @Id = ID FROM #t WHERE ID > @Id ORDER BY ID
		SELECT @AllScore = SUM(Score) FROM Kpi_Oc WHERE YearMonth = @YearMonth AND ManagerUserId = @Id
		SELECT @AllScore = ISNULL(@AllScore, 0), @HasObjHigher = 1, @OrderRight = 1, @SignRight = 1, @FormatRight = 1
		SELECT @HasObjHigher = 0 FROM Kpi_Oc WHERE YearMonth = @YearMonth AND ManagerUserId = @Id AND ISNULL(Obj_Higher, '') = ''

		IF EXISTS(SELECT 'x' FROM Kpi_Oc a, Kpi_Oc b WHERE a.YearMonth = @YearMonth AND a.ManagerUserId = @Id 
			AND b.YearMonth = @YearMonth AND b.ManagerUserId = @Id AND a.Score >  b.Score AND A.Kpi_Power > b.Kpi_Power)
			SET @OrderRight = 0
 
		IF EXISTS(SELECT 'x' FROM Kpi_Oc WHERE YearMonth = @YearMonth AND ManagerUserId = @Id 
			AND (CHARINDEX('《', [Standard]) > 0 OR CHARINDEX('》', [Standard]) > 0
				OR CHARINDEX('《', Obj_Self) > 0 OR CHARINDEX('》', Obj_Self) > 0
				OR CHARINDEX('《', Obj_Higher) > 0 OR CHARINDEX('》', Obj_Higher) > 0))
			SET @SignRight = 0

		IF EXISTS(SELECT 'x' FROM Kpi_Oc WHERE YearMonth = @YearMonth
			AND ManagerUserId = @Id AND WorkPlan NOT LIKE '完成%作业%')
			SET @FormatRight = 0

		IF @AllScore <>  91 OR @HasObjHigher = 0 OR @OrderRight = 0 OR @SignRight = 0 OR @FormatRight = 0
			INSERT INTO @t
			SELECT @ID, @AllScore, @HasObjHigher, @OrderRight, @SignRight, @FormatRight
	END
	SELECT * FROM @t
END

GO

/****** Object:  StoredProcedure [dbo].[spMakeVarJobTypeJs]    Script Date: 2018/12/13 19:13:17 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[spMakeVarJobTypeJs]
AS
SET NOCOUNT ON
BEGIN
	SELECT a.CategoryId, LEFT(b.Id, 2) JobTypeId, b.Id, b.Description, b.OrderNo
	INTO #t
	FROM dcJobTypeMap a, dcJobType b
	WHERE a.JobtypeId = LEFT(b.Id, 2)
	ORDER BY a.CategoryId, b.Id

	INSERT INTO #t
	SELECT a.CategoryId, b.ParentId2, b.Id, b.Description, b.OrderNo
	FROM dcJobTypeMap a, dcJobType b
	WHERE a.JobTypeId = b.ParentId2
	ORDER BY a.CategoryId, b.ParentId2
	UPDATE #t SET OrderNo = 10000 + OrderNo WHERE Description LIKE '其他%'
	UPDATE #t SET OrderNo = 1000 + OrderNo WHERE ID > 100 AND LEFT(Id, 2) <> JobTypeId
	--SELECT * FROM #t WHERE Id > 100 ORDER BY CategoryId, JobtypeID, OrderNo
	DELETE #t WHERE JobTypeId = 56
	---------------

	DECLARE @Id INT, @Sql VARCHAR(MAX), @CategoryId INT, @JobTypeId INT, @PreCategoryId INT
	SELECT @Id = 0, @Sql = '', @CategoryId = 0, @JobTypeId = 0, @PreCategoryId = 0
	WHILE EXISTS(SELECT 'x' FROM #t WHERE CategoryId > @CategoryId)
	BEGIN
		SELECT TOP 1 @CategoryId = CategoryId, @JobTypeId = 0 FROM #t WHERE CategoryId > @CategoryId ORDER BY CategoryId
		WHILE EXISTS(SELECT 'x' FROM #t WHERE CategoryId = @CategoryId AND JobTypeId > @JobTypeId AND JobTypeId < 100)
		BEGIN
			SELECT TOP 1 @JobTypeId = JobTypeId FROM #t WHERE CategoryId = @CategoryId AND JobTypeId > @JobTypeId AND JobTypeId < 100 ORDER BY JobTypeId
			PRINT 'jsJobTypeL2[' + LTRIM(STR(@Id)) + '] = new Array();'
			PRINT 'jsJobTypeL2ID[' + LTRIM(STR(@Id)) + '] = new Array();'
			SET @Sql = ''
			SELECT @SQl = @Sql + CASE WHEN @Sql = '' THEN '"' ELSE ',"' END + Description + '"' FROM #t WHERE JobTypeId = @JobTypeId AND Id > 99 ORDER BY OrderNo
			SET @Sql = 'jsJobTypeL2[' + LTRIM(STR(@Id)) + ']=[' + @Sql + '];'
			PRINT @sql
			SET @Sql = ''
			SELECT @SQl = @Sql + CASE WHEN @Sql = '' THEN '"' ELSE ',"' END + LTRIM(STR(ID)) + '"' FROM #t WHERE JobTypeId = @JobTypeId AND Id > 99 ORDER BY OrderNo
			SET @Sql = 'jsJobTypeL2ID[' + LTRIM(STR(@Id)) + ']=[' + @Sql + '];'
			PRINT @sql
			SET @Id = @Id + 1
		END
	END
	SET @Sql = ''
	SELECT @SQl = @Sql + CASE WHEN @Sql = '' THEN '"' ELSE ',"' END + b.Description + '"' 
	FROM dcJobTypeMap a, dcJobType b
	WHERE a.JobTypeId = b.ID
	AND b.Id < 99
	AND b.Id <> 56
	ORDER BY CategoryId, JobTypeID
	SET @Sql = 'jsJobTypeL1=[' + @Sql + '];'
	PRINT @sql

	SET @Sql = ''
	SELECT @SQl = @Sql + CASE WHEN @Sql = '' THEN '"' ELSE ',"' END + LTRIM(STR(b.Id)) + '"'
	FROM dcJobTypeMap a, dcJobType b
	WHERE a.JobTypeId = b.ID
	AND b.Id < 99
	AND b.Id <> 56
	ORDER BY CategoryId, JobTypeID
	SET @Sql = 'jsJobTypeL1ID=[' + @Sql + '];'
	PRINT @sql
END

GO

/****** Object:  StoredProcedure [dbo].[spMakeVarJobTypeJsLagre]    Script Date: 2018/12/13 19:13:17 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[spMakeVarJobTypeJsLagre]
AS
SET NOCOUNT ON
BEGIN
	SELECT a.CategoryId, LEFT(b.Id, 2) JobTypeId, b.Id, b.Description, b.OrderNo
	INTO #t
	FROM dcJobTypeMap a, dcJobType b
	WHERE a.JobtypeId = LEFT(b.Id, 2)
	AND b.Id < 100
	ORDER BY a.CategoryId, b.Id
	---------------

	DECLARE @Id INT, @Sql VARCHAR(MAX), @SqlId VARCHAR(MAX), @CategoryId INT, @JobTypeId INT, @PreCategoryId INT
	SELECT @Id = 0, @Sql = '', @CategoryId = 0, @JobTypeId = 0, @PreCategoryId = 0
	WHILE EXISTS(SELECT 'x' FROM #t WHERE CategoryId > @CategoryId)
	BEGIN
		SELECT TOP 1 @CategoryId = CategoryId, @JobTypeId = 0 FROM #t WHERE CategoryId > @CategoryId ORDER BY CategoryId
		PRINT 'jsJobTypeL2[' + LTRIM(STR(@CategoryId-1)) + '] = new Array();'
		PRINT 'jsJobTypeL2ID[' + LTRIM(STR(@CategoryId-1)) + '] = new Array();'

		SET @Sql = ''
		SELECT @SQl = @Sql + CASE WHEN @Sql = '' THEN '"' ELSE ',"' END + Description + '"' 
		FROM #t 
		WHERE CategoryId = @CategoryId
		ORDER BY JobtypeId
		PRINT 'jsJobTypeL2[' + LTRIM(STR(@CategoryId-1)) + ']=[' + @Sql + '];'
	
		SET @Sql = ''
		SELECT @SQl = @Sql + CASE WHEN @Sql = '' THEN '"' ELSE ',"' END + LTRIM(STR(ID)) + '"' 
		FROM #t 
		WHERE CategoryId = @CategoryId
		ORDER BY JobtypeId
		PRINT 'jsJobTypeL2ID[' + LTRIM(STR(@CategoryId-1)) + ']=[' + @Sql + '];'
		PRINT ''
	END
END
GO

/****** Object:  StoredProcedure [dbo].[spMakeVarJobTypeJson]    Script Date: 2018/12/13 19:13:17 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[spMakeVarJobTypeJson]
AS
SET NOCOUNT ON
BEGIN
	SELECT a.CategoryId, LEFT(b.Id, 2) JobTypeId, b.Id, b.Description, b.OrderNo
	INTO #t
	FROM dcJobTypeMap a, dcJobType b
	WHERE a.JobtypeId = LEFT(b.Id, 2)
	ORDER BY a.CategoryId, b.Id

	INSERT INTO #t
	SELECT a.CategoryId, b.ParentId2, b.Id, b.Description, b.OrderNo
	FROM dcJobTypeMap a, dcJobType b
	WHERE a.JobTypeId = b.ParentId2
	ORDER BY a.CategoryId, b.ParentId2
	UPDATE #t SET OrderNo = 10000 + OrderNo WHERE Description LIKE '其他%'
	UPDATE #t SET OrderNo = 1000 + OrderNo WHERE ID > 100 AND LEFT(Id, 2) <> JobTypeId
	DELETE #t WHERE JobTypeId = 56
	---------------
	Print 'var jobTypeData = ['
	DECLARE @Id INT, @Sql VARCHAR(MAX), @CategoryId INT, @JobTypeId INT, @PreCategoryId INT, @desc VARCHAR(50)
	SELECT @Id = 0, @Sql = '', @CategoryId = 0, @JobTypeId = 0, @PreCategoryId = 0
	WHILE EXISTS(SELECT 'x' FROM #t WHERE CategoryId > @CategoryId)
	BEGIN
		SELECT TOP 1 @CategoryId = CategoryId, @JobTypeId = 0 FROM #t WHERE CategoryId > @CategoryId ORDER BY CategoryId
		WHILE EXISTS(SELECT 'x' FROM #t WHERE CategoryId = @CategoryId AND JobTypeId > @JobTypeId AND JobTypeId < 100)
		BEGIN
			SELECT TOP 1 @desc = ''
			SELECT TOP 1 @JobTypeId = JobTypeId, @desc = Description FROM #t WHERE CategoryId = @CategoryId AND JobTypeId > @JobTypeId AND Id < 100 ORDER BY JobTypeId

			SET @Sql = '{"value": "' + LTRIM(STR(@JobTypeId)) + '", "text": "' + @desc + '", "children":['
			SELECT @SQl = @Sql + '{"value": "' + LTRIM(Str(Id)) + '", "text": "' + Description + '", "children": []},' FROM #t WHERE JobTypeId = @JobTypeId AND Id > 99 ORDER BY OrderNo
			SET @Sql = LEFT(@Sql, LEN(@sql) - 1) + ']},'
			PRINT @sql
			
			SET @Id = @Id + 1
		END
	END
	Print '{"value": "56", "text": "其他", "children": []}
]'
END
GO

/****** Object:  StoredProcedure [dbo].[spManageruserByLeaveUpdate]    Script Date: 2018/12/13 19:13:17 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE procedure [dbo].[spManageruserByLeaveUpdate]
as
BEGIN
	IF NOT EXISTS(SELECT 'x' FROM ManagerUser WHERE Name != '空岗' AND Status = 3)
		RETURN

	update manageruser set name='空岗', loginstatus=2,photo=null where status=3
	
	create table #t(id int identity(1, 1), p varchar(8))
	insert #t
	select top 999 substring(password, 10, 8) from pamain order by id desc

	update a set a.password=b.p
	from manageruser a, #t b
	where a.id = b.id
	and a.status=3
	and a.name = '空岗'
END
GO

/****** Object:  StoredProcedure [dbo].[spManageruserByMoveUpdate]    Script Date: 2018/12/13 19:13:17 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--spManageruserByMoveUpdate 601, 104
create procedure [dbo].[spManageruserByMoveUpdate]
(
	@oldId INT, 
	@NewId INT
)
AS
BEGIN
	print 'UPDATE LoginOtpInfo SET ManagerUSerId = 0 where ManagerUserId = ' + LTRIM(STR(@NewID))
	print 'UPDATE LoginOtpInfo SET ManagerUSerId = ' + LTRIM(STR(@NewID)) + ' where ManagerUserId = ' + LTRIM(STR(@OldId))
	SELECT * FROM LoginOtpInfo WHERE ManagerUserId IN(@OldId, @NewId)

	select id, UserName, Password, name, name_eng, OpenName, superior,
		title, roleid, deptid, adddate, logincount, lastlogindate, type, email,
		status, loginstatus, localrate, kpi_manager, km, km_score, ie, mobile, ec,
		HRKpiPostId, HRKpiPostGrade, office, CompanyQQ, SalesLevel, WeiXinNo
	INTO #t
	FROM Manageruser
	WHERE ID = @OldId

	UPDATE ManagerUser SET UserName = LEFT(NEWID(), 10), Password = [REDACTED] 10),
		Name = LEFT(NEWID(), 10), Name_Eng = LEFT(NEWID(), 10), Status = 3, LoginStatus = 2
	WHERE ID = @OldId

	UPDATE a
	SET a.UserName = b.UserName, 
		a. Password = b. Password, 
		a. name = b. name, 
		a. name_eng = b. name_eng, 
		a. OpenName = b. OpenName, 
		a. superior = b. superior, 
		a.title = b.title, 
		a. roleid = b. roleid, 
		a. deptid = b. deptid, 
		a. adddate = b. adddate, 
		a. logincount = b. logincount, 
		a. lastlogindate = b. lastlogindate, 
		a. type = b. type, 
		a. email = b. email, 
		a.status = b.status, 
		a. loginstatus = b. loginstatus, 
		a. localrate = b. localrate, 
		a. kpi_manager = b. kpi_manager, 
		a. km = b. km, 
		a. km_score = b. km_score, 
		a. ie = b. ie, 
		a. mobile = b. mobile, 
		a. ec = b. ec, 
		a.HRKpiPostId = b.HRKpiPostId, 
		a. HRKpiPostGrade = b. HRKpiPostGrade, 
		a. office = b. office, 
		a. CompanyQQ = b. CompanyQQ, 
		a. SalesLevel = b. SalesLevel, 
		a. WeiXinNo = b. WeiXinNo
	FROM ManagerUser a,
		#t b
	WHERE a.Id = @NewId
	AND b.ID = @OldId

	SELECT * FROM ManagerUser WHERE Id IN(@OldId, @NewId)
END
GO

/****** Object:  StoredProcedure [dbo].[spManageruserByPasswordUpdate]    Script Date: 2018/12/13 19:13:18 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[spManageruserByPasswordUpdate]
AS
BEGIN
	CREATE TABLE #t(id INT, Pass INT)
	DECLARE @Pass INT, @id INT
	SET @id = 0
	WHILE EXISTS(SELECT 'x' FROM ManagerUser WHERE id > @id)
	BEGIN
		SELECT TOP 1 @id = id FROM ManagerUser WHERE id > @id ORDER BY id
		SELECT @Pass = cASt( floor(rand()*89999999)+10000000 AS INT) 
		IF @Pass LIKE '%4%'
			SELECT @Pass = cASt( floor(rand()*89999999)+10000000 AS INT) 
		IF @Pass LIKE '%4%'
			SELECT @Pass = cASt( floor(rand()*89999999)+10000000 AS INT) 
		IF @Pass LIKE '%4%'
			SELECT @Pass = cASt( floor(rand()*89999999)+10000000 AS INT) 
		INSERT INTO #t SELECT @id, @Pass
	END
	UPDATE a SET a.Password = [REDACTED] FROM ManagerUser a, #t b WHERE a.id = b.id

	INSERT INTO rtxnotIFylog(receiver, rtxtitle, rtxmessage, sENDtype, delaytime, showtype)
	SELECT id, '后台密码修改通知', 
		'您的后台密码已经修改为' + LTRIM(STR(Pass)) + '，敬请注意。RTX、邮箱密码、呼叫中心密码没有修改，请你立刻自行修改RTX密码、邮箱密码、呼叫中心密码，与后台密码保持一致。邮箱密码修改可以通过“后台-->工作台-->公司邮箱”进行；RTX密码修改可以通过“RTX-->个人设置”进行；呼叫中心密码可以登录呼叫中心修改。', 1, 0, 0
	FROM #t
	WHERE Id IN(SELECT Id FROM ManagerUser WHERE Status <> 3)
END
GO

/****** Object:  StoredProcedure [dbo].[spManagerUserByRtxStateUpdate]    Script Date: 2018/12/13 19:13:18 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[spManagerUserByRtxStateUpdate]
(
	@UserData VARCHAR(MAX)
)
AS
SET NOCOUNT ON
BEGIN
	DECLARE @t AS TABLE(data VARCHAR(MAX))
	DECLARE @T_RtxState AS TABLE(Id INT, RtxName VARCHAR(20), CurState TINYINT, CrDate DATETIME, 
		PreStatus TINYINT, PreTime DateTime, StaySecond INT)

	INSERT INTO @t 
	SELECT REPLACE(a, '|', '') FROM dbo.fnSplit(@UserData, '||')

	DECLARE @online VARCHAR(MAX), @offline VARCHAR(MAX), @away VARCHAR(MAX)
	SELECT @Online = REPLACE(data, 'online=', '') FROM @t WHERE data LIKE 'online=%'
	SELECT @offline = REPLACE(data, 'offline=', '') FROM @t WHERE data LIKE 'offline=%'
	SELECT @away = REPLACE(data, 'away=', '') FROM @t WHERE data LIKE 'away=%'

	INSERT INTO @T_RtxState(Id, RtxName, CurState, CrDate, PreStatus, PreTime)
	SELECT ID, Name_Eng, 0, GETDATE(), RtxStatus, RtxTime
	FROM ManagerUser
	WHERE Status < 3

	UPDATE @T_RtxState SET CurState = 0 WHERE RtxName IN(SELECT a FROM dbo.fnsplit(@offline, ';'))
	UPDATE @T_RtxState SET CurState = 1 WHERE RtxName IN(SELECT a FROM dbo.fnsplit(@online, ';'))
	UPDATE @T_RtxState SET CurState = 2 WHERE RtxName IN(SELECT a FROM dbo.fnsplit(@away, ';'))

	UPDATE a SET a.PreStatus = b.RtxStatus, a.PreTime = b.RtxTime, a.Id = b.Id
	FROM @T_RtxState a, ManagerUser b
	WHERE a.RtxName = b.Name_Eng
	AND b.Status < 3

	UPDATE @T_RtxState SET PreTime = CrDate WHERE PreTime < DATEADD(MINUTE, -60, GETDATE())
	UPDATE @T_RtxState SET StaySecond = DATEDIFF(SECOND, PreTime, CrDate)

	DELETE FROM @T_RtxState WHERE Id IS NULL

	UPDATE a SET a.RtxStatus = b.CurState, a.RtxTime = b.crDate
	FROM ManagerUser a, @T_RtxState b
	WHERE a.Id = b.Id

	UPDATE a SET a.PreRtxStatus = b.PreStatus, a.RtxStatus = b.CurState,
		a.OnlineSecond = a.OnLineSecond + b.StaySecond * 1000,
		a.AllOnlineTime = a.AllOnlineTime + b.StaySecond * 1000,
		a.CheckTime = b.crDate
	FROM bsRtxStatus a, @T_RtxState b
	WHERE a.CheckDay = CONVERT(VARCHAR(8), GETDATE(), 112)
	AND a.ManagerUserId = b.Id
	AND b.PreStatus = 1

	UPDATE a SET a.PreRtxStatus = b.PreStatus, a.RtxStatus = b.CurState,
		a.OfflineSecond = a.OffLineSecond + b.StaySecond * 1000,
		a.CheckTime = b.crDate
	FROM bsRtxStatus a, @T_RtxState b
	WHERE a.CheckDay = CONVERT(VARCHAR(8), GETDATE(), 112)
	AND a.ManagerUserId = b.Id
	AND b.PreStatus = 0

	UPDATE a SET a.PreRtxStatus = b.PreStatus, a.RtxStatus = b.CurState,
		a.LeaveSecond = a.LeaveSecond + b.StaySecond * 1000,
		a.CheckTime = b.crDate
	FROM bsRtxStatus a, @T_RtxState b
	WHERE a.CheckDay = CONVERT(VARCHAR(8), GETDATE(), 112)
	AND a.ManagerUserId = b.Id
	AND b.PreStatus = 2

	INSERT bsRtxStatusLog(ManagerUserID, RtxStatus) 
	SELECT Id, CurState
	FROM @T_RtxState
	WHERE PreStatus <> CurState

	SELECT Id, CurState
	FROM @T_RtxState
	WHERE PreStatus <> CurState

	SELECT Count(*) FROM @T_RtxState
END
GO

/****** Object:  StoredProcedure [dbo].[spMarketNeedSave]    Script Date: 2018/12/13 19:13:18 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

/*
1、山东省十七地市企业数量、发布岗位数量、求职简历数量，分季度。
2、按行业份，山东省各行业企业数量、发布岗位数量、求职简历数量，分季度。
3、山东省岗位薪酬排行，分季度
4、山东省热门岗位数量，分季度
5、山东省热门岗位薪酬，分季度
*/
CREATE PROCEDURE [dbo].[spMarketNeedSave]
AS
SET NOCOUNT ON
BEGIN
	DECLARE @Month AS VARCHAR(8), @BeginDate AS DATETIME
	SELECT @Month = CONVERT(VARCHAR(6), GETDATE(), 112), @BeginDate = GETDATE()
	DELETE FROM ReportDb..MarketData WHERE CountMonth = @Month
	--山东省十七地市
	--企业数量
	INSERT INTO ReportDb..MarketData(CountMonth, CountType, dcRegionId, CountNumber)
	SELECT @Month, 1, LEFT(dcRegionId, 4) dcRegionId, COUNT(*) Cnt FROM cpMain WHERE Regdate < @BeginDate GROUP BY Left(dcRegionId, 4)
	--发布岗位数量
	INSERT INTO ReportDb..MarketData(CountMonth, CountType, dcRegionId, CountNumber)	
	SELECT @Month, 2, LEFT(dcRegionId, 4) dcRegionId, COUNT(*) Cnt FROM Job WHERE IssueDate < @BeginDate GROUP BY Left(dcRegionId, 4)
	--求职简历数量
	INSERT INTO ReportDb..MarketData(CountMonth, CountType, dcRegionId, CountNumber)
	SELECT @Month, 3, LEFT(LivePlace, 4) dcRegionId, COUNT(*) * 1.1 Cnt FROM paMain WHERE AddDate < @BeginDate GROUP BY Left(LivePlace, 4)

	--按行业份，山东省各行业
	--企业数量
	INSERT INTO ReportDb..MarketData(CountMonth, CountType, dcRegionId, dcIndustryId, CountNumber)
	SELECT @Month, 11, LEFT(a.dcRegionId, 2), b.dcIndustryId, COUNT(*) Cnt FROM cpMain a, cpIndustry b WHERE a.Id = b.cpMainId AND a.RegDate < @BeginDate GROUP BY LEFT(a.dcRegionId, 2), b.dcIndustryId
	--发布岗位数量
	INSERT INTO ReportDb..MarketData(CountMonth, CountType, dcRegionId, dcIndustryId, CountNumber)
	SELECT @Month, 12, LEFT(a.dcRegionId, 2), b.dcIndustryId, COUNT(*) Cnt FROM cpMain a, cpIndustry b, Job c WHERE a.Id = b.cpMainId AND c.cpMainId = a.Id AND a.RegDate < @BeginDate GROUP BY LEFT(a.dcRegionId, 2), b.dcIndustryId
	--求职简历数量
	INSERT INTO ReportDb..MarketData(CountMonth, CountType, dcRegionId, dcIndustryId, CountNumber)
	SELECT @Month, 13, LEFT(a.LivePlace, 2), c.dcIndustryId, COUNT(*) Cnt FROM paMain a, cvMain b, cvIndustry c WHERE a.Id = b.paMainId AND b.Id = c.cvMainId AND a.AddDate < @BeginDate GROUP BY LEFT(a.LivePlace, 2), c.dcIndustryId
END
GO

/****** Object:  StoredProcedure [dbo].[spMergeJobType]    Script Date: 2018/12/13 19:13:18 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE procedure [dbo].[spMergeJobType]
(
	@OldJobtype VARCHAR(4),
	@NewJobtype VARCHAR(4)
)
AS
SET NOCOUNT ON
BEGIN
	print @OldJobtype
	--####################################33
	DELETE caJobResumePreJobType WHERE dcJobTypeId = @OldJobtype AND cvMainId IN(SELECT cvMainId FROM caJobResumePreJobType WHERE dcJobTypeId = @NewJobtype)
	UPDATE caJobResumePreJobType SET dcJobTypeId = @NewJobtype WHERE dcJobTypeId = @OldJobtype
	------------------------
	UPDATE cvExperience SET dcJobtypeID = @NewJobtype WHERE dcJobtypeID = @OldJobtype
	UPDATE cvExperiencePublish SET dcJobtypeID = @NewJobtype WHERE dcJobtypeID = @OldJobtype
	------------------------
	SELECT Distinct cvMainId INTO #t1 FROM cvJobType WITH(NOLOCK) WHERE dcJobTypeId = @OldJobtype OR dcJobTypeId = @NewJobtype
	DELETE FROM cvJobType WHERE (dcJobTypeId = @OldJobtype OR dcJobTypeId = @NewJobtype) AND cvMainId IN(SELECT cvMainId FROM #t1)
	INSERT cvJobType (cvMainId, dcJobTypeId) SELECT cvMainId, @NewJobtype FROM #t1
	SELECT Distinct cvMainId INTO #t2 FROM cvJobTypePublish WITH(NOLOCK) WHERE dcJobTypeId = @OldJobtype OR dcJobTypeId = @NewJobtype
	DELETE FROM cvJobTypePublish WHERE (dcJobTypeId = @OldJobtype OR dcJobTypeId = @NewJobtype) AND cvMainId IN(SELECT cvMainId FROM #t2)
	INSERT cvJobTypePublish (cvMainId, dcJobTypeId) SELECT cvMainId, @NewJobtype FROM #t2
	------------------------------------------
	UPDATE cvMain SET LastJobTypeID = @NewJobtype WHERE LastJobTypeID = @OldJobtype
	UPDATE cvMainPublish SET LastJobTypeID = @NewJobtype WHERE LastJobTypeID = @OldJobtype
	-------------------------------
	DELETE dcJobName WHERE dcJobTypeId = @OldJobtype AND Name IN(SELECT Name FROM dcJobName WHERE dcJobTypeId = @NewJobtype)
	UPDATE dcJobName SET dcJobTypeId = @NewJobtype WHERE dcJobTypeId = @OldJobtype
	-------------------------------------
	DELETE dcJobTypeMap WHERE JobTypeId = @OldJobtype
	-------------------------------------
	DELETE dcJobTypeTemplate WHERE dcJobTypeId = @OldJobtype
	-----------------------------
	UPDATE hpJobTypeCpLogo SET dcJobTypeId = @NewJobtype WHERE dcJobTypeId = @OldJobtype
	-----------------------------
 	UPDATE Job SET dcJobTypeId = @NewJobtype WHERE dcJobTypeId = @OldJobtype
	UPDATE Job SET dcJobTypeIDMinor = @NewJobtype WHERE dcJobTypeIDMinor = @OldJobtype
	UPDATE JobPublish SET dcJobTypeId = @NewJobtype WHERE dcJobTypeId = @OldJobtype
	UPDATE JobPublish SET dcJobTypeIDMinor = @NewJobtype WHERE dcJobTypeIDMinor = @OldJobtype
	UPDATE JobTemplate SET dcJobTypeId = @NewJobtype WHERE dcJobTypeId = @OldJobtype
	UPDATE JobTemplate SET dcJobTypeIDMinor = @NewJobtype WHERE dcJobTypeIDMinor = @OldJobtype	
	UPDATE JobSimilar SET dcJobTypeId = @NewJobtype WHERE dcJobTypeId = @OldJobtype

	UPDATE caCvFinder SET dcJobTypeId = REPLACE(dcJobTypeId, @OldJobtype, @NewJobtype) WHERE dcJobTypeId LIKE '%' + @OldJobtype + '%'

	UPDATE paJobFinder SET dcJobTypeId = REPLACE(dcJobTypeId, @OldJobtype, @NewJobtype) WHERE dcJobTypeId LIKE '%' + @OldJobtype + '%'

	DELETE FROM dcJobType WHERE id = @OldJobtype
	----dcJobTypeHot
END
GO

/****** Object:  StoredProcedure [dbo].[spMergeRegion]    Script Date: 2018/12/13 19:13:18 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


--########################################
--转换数据，从@OldRegion转到@NewRegion
--########################################
CREATE PROCEDURE [dbo].[spMergeRegion]
(
	@OldRegion VARCHAR(6),
	@NewRegion VARCHAR(6)
)
AS
SET NOCOUNT OFF
BEGIN TRY
	BEGIN TRAN
		--####################################33
		UPDATE dcBusinessCircle SET dcRegionId = @NewRegion WHERE dcRegionId = @OldRegion
		UPDATE Job SET dcRegionId = @NewRegion WHERE dcRegionId = @OldRegion
		UPDATE JobPublish SET dcRegionId = @NewRegion WHERE dcRegionId = @OldRegion
		UPDATE JobTemplate SET dcRegionId = @NewRegion WHERE dcRegionId = @OldRegion
		UPDATE paMain SET LivePlace = @NewRegion WHERE LivePlace = @OldRegion
		UPDATE paMain SET GrowPlace = @NewRegion WHERE GrowPlace = @OldRegion
		UPDATE paMain SET AccountPlace = @NewRegion WHERE AccountPlace = @OldRegion
		UPDATE cvexperience SET WorkPlace = @NewRegion WHERE WorkPlace = @OldRegion

		UPDATE caCvFinder SET dcRegionId = REPLACE(dcRegionId, @OldRegion, @NewRegion) WHERE dcRegionId = @OldRegion
		UPDATE caCvFinder SET dcRegionId = REPLACE(dcRegionId, @OldRegion, @NewRegion) WHERE dcRegionId like @OldRegion + ',%'
		UPDATE caCvFinder SET dcRegionId = REPLACE(dcRegionId, @OldRegion, @NewRegion) WHERE dcRegionId like '%,' + @OldRegion + ',%'
		UPDATE caCvFinder SET dcRegionId = REPLACE(dcRegionId, @OldRegion, @NewRegion) WHERE dcRegionId like '%,' + @OldRegion

		UPDATE paJobFinder SET dcRegionId = REPLACE(dcRegionId, @OldRegion, @NewRegion) WHERE dcRegionId = @OldRegion
		UPDATE paJobFinder SET dcRegionId = REPLACE(dcRegionId, @OldRegion, @NewRegion) WHERE dcRegionId like @OldRegion + ',%'
		UPDATE paJobFinder SET dcRegionId = REPLACE(dcRegionId, @OldRegion, @NewRegion) WHERE dcRegionId like '%,' + @OldRegion + ',%'
		UPDATE paJobFinder SET dcRegionId = REPLACE(dcRegionId, @OldRegion, @NewRegion) WHERE dcRegionId like '%,' + @OldRegion

		--####################################33
		DECLARE curCpMain CURSOR FOR
			SELECT ID FROM cpMain WITH(NOLOCK)
			WHERE dcRegionId = @OldRegion
		OPEN curCpMain

		DECLARE @Id INT

		FETCH NEXT FROM curCpMain INTO @Id
		WHILE(@@FETCH_STATUS =0)
		BEGIN
			UPDATE cpMain SET dcRegionId = @NewRegion WHERE id = @Id
			FETCH NEXT FROM curCpMain INTO @Id
		END

		CLOSE curCpMain
		DEALLOCATE curCpMain
		--####################################33
		DECLARE curCpMainPublish CURSOR FOR
			SELECT ID FROM cpMainPublish WITH(NOLOCK)
			WHERE dcRegionId = @OldRegion
		OPEN curCpMainPublish

		FETCH NEXT FROM curCpMainPublish INTO @Id
		WHILE(@@FETCH_STATUS =0)
		BEGIN
			UPDATE cpMainPublish SET dcRegionId = @NewRegion WHERE id = @Id
			FETCH NEXT FROM curCpMainPublish INTO @Id
		END

		CLOSE curCpMainPublish
		DEALLOCATE curCpMainPublish

		--####################################33
		SELECT Distinct cvMainId INTO #t FROM cvJobplace WITH(NOLOCK) WHERE dcRegionId = @OldRegion OR dcRegionId = @NewRegion
		DELETE FROM cvJobplace WHERE (dcRegionId = @OldRegion OR dcRegionId = @NewRegion) AND cvMainId IN(SELECT cvMainId FROM #t)
		INSERT cvJobplace (cvMainId, dcRegionId) SELECT cvMainId, @NewRegion FROM #t
		--####################################33
		SELECT Distinct cvMainId INTO #tt FROM cvJobplacePublish WITH(NOLOCK) WHERE dcRegionId = @OldRegion OR dcRegionId = @NewRegion
		DELETE FROM cvJobplacePublish WHERE (dcRegionId = @OldRegion OR dcRegionId = @NewRegion) AND cvMainId IN(SELECT cvMainId FROM #tt)
		INSERT cvJobplacePublish (cvMainId, dcRegionId) SELECT cvMainId, @NewRegion FROM #tt
		--####################################33

		DELETE FROM dcregion WHERE id = @OldRegion
	COMMIT
END TRY
BEGIN CATCH
	PRINT ERROR_MESSAGE()
	ROLLBACK TRAN
END CATCH
GO

/****** Object:  StoredProcedure [dbo].[spNewJobRelatedInsert]    Script Date: 2018/12/13 19:13:19 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[spNewJobRelatedInsert]
AS
BEGIN
	SELECT a.id JobId, a.SecondId, a.Name, LEFT(a.dcRegionId, 2) dcRegionId, LEFT(a.dcJobTypeId, 2) dcJobTypeId,
		ROW_NUMBER() OVER(PARTITION BY LEFT(a.dcRegionId, 2), LEFT(a.dcJobTypeId, 2) ORDER BY a.RefreshDate) RowNo
	INTO #t
	FROM JobPublish a WITH(NOLOCK), 
		cpMain b WITH(NOLOCK)
	WHERE a.cpMainId = b.Id
	AND a.Valid = 1
	AND b.Valid = 1
	AND a.dcRegionId LIKE LTRIM(STR(b.dcProvinceId)) + '%'

	DELETE #t WHERE RowNo > 100

	CREATE TABLE #r(JobId INT, RowNo INT IDENTITY(1, 1))
	INSERT INTO #r SELECT JobId FROM #t ORDER BY NEWID()

	TRUNCATE TABLE ShortDb..NewJobRelated

	INSERT INTO NewJobRelated(JobId, SecondId, Name, dcRegionId, dcJobTypeId, RowNo)
	SELECT a.JobId, a.SecondId, a.Name, a.dcRegionId, a.dcJobTypeID, b.RowNo
	FROM #t a, #r b
	WHERE a.JobId = b.JobId
END
GO

/****** Object:  StoredProcedure [dbo].[spOrderAnalysis]    Script Date: 2018/12/13 19:13:19 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[spOrderAnalysis]
(
	@Year INT,
	@ProvinceId INT
)
AS
BEGIN
	IF @Year > DATEPART(Year, getdate())
		RETURN
	IF @Year < 2002
		SET @Year = 0
	IF @ProvinceId > 0 AND NOT EXISTS(SELECT 'x' FROM dcProvince WHERE ID=@ProvinceId)
		RETURN

	DECLARE @Sql AS VARCHAR(MAX)
	IF ISNULL((SELECT TOP 1 CountDate FROM OrderAnalysis), '') <> CONVERT(VARCHAR(10), GETDATE(), 120)
	BEGIN
		TRUNCATE TABLE OrderAnalysis

		SET @Sql = 'INSERT INTO OrderAnalysis SELECT Row_Number() OVER(order by cpMainid, begindate) ID, ID OrderId, cpMainid, ProvinceId, paid, opendate, begindate, enddate,
				Paid Paid2, OpenDate OpenDate2, BeginDate BeginDate2, EndDate EndDate2, ID NextId, Id DiffDay, Id DiffMonth, 0, '''', CONVERT(VARCHAR(10), GETDATE(), 120)
				from caorder with(nolock)
				where ordertype in(1,2,8) 
				and paid>0 
				and opendate IS NOT NULL
				and enddate IS NOT NULL'
		EXEC(@Sql)

		UPDATE OrderAnalysis SET Paid2 = NULL, OpenDate2 = NULL, BeginDate2 = NULL, EndDate2 = NULL, NextId = NULL, DiffDay = NULL, DiffMonth = NULL

		UPDATE a
		SET a.NextID = (SELECT Min(ID) FROM OrderAnalysis WHERE OrderAnalysis.cpMainID = a.cpMainId AND OrderAnalysis.Id > a.Id)
		FROM OrderAnalysis a

		UPDATE a
		SET a.BeginDate2 = (SELECT BeginDate FROM OrderAnalysis WHERE OrderAnalysis.ID = a.NextId),
			a.Paid2 = (SELECT Paid FROM OrderAnalysis WHERE OrderAnalysis.ID = a.NextId),
			a.EndDate2 = (SELECT EndDate FROM OrderAnalysis WHERE OrderAnalysis.ID = a.NextId),
			a.OpenDate2 = (SELECT OpenDate FROM OrderAnalysis WHERE OrderAnalysis.ID = a.NextId)
		FROM OrderAnalysis a
		WHERE NextId > 0


		UPDATE OrderAnalysis SET DiffDay = DATEDIFF(DAY, EndDate, OpenDate2), DiffMonth = DATEDIFF(MONTH, EndDate, OpenDate)
		UPDATE OrderAnalysis SET DiffDay = 0, DiffMonth = 0 WHERE DiffDay < 0

		UPDATE OrderAnalysis SET Interval = 1, IntervalRemark = '0~7天' WHERE DiffDay <=7
		UPDATE OrderAnalysis SET Interval = 2, IntervalRemark = '8~30天' WHERE DiffDay > 7 AND DiffDay <= 30
		UPDATE OrderAnalysis SET Interval = 3, IntervalRemark = '31~91天' WHERE DiffDay > 31 AND DiffDay <= 91
		UPDATE OrderAnalysis SET Interval = 4, IntervalRemark = '92~183天' WHERE DiffDay > 91 AND DiffDay <= 183
		UPDATE OrderAnalysis SET Interval = 5, IntervalRemark = '184~365天' WHERE DiffDay > 183 AND DiffDay <= 365
		UPDATE OrderAnalysis SET Interval = 6, IntervalRemark = '366~730天' WHERE DiffDay > 365 AND DiffDay <= 730
		UPDATE OrderAnalysis SET Interval = 7, IntervalRemark = '>730天' WHERE DiffDay > 731
	END

	SELECT TOP 0 * INTO #Order FROM OrderAnalysis WITH(NOLOCK)
	IF @Year = 0
		IF ISNULL(@ProvinceId, 0) = 0
			INSERT INTO #Order SELECT * FROM OrderAnalysis WITH(NOLOCK)
		ELSE
			INSERT INTO #Order SELECT * FROM OrderAnalysis WITH(NOLOCK) WHERE ProvinceId LIKE LTRIM(STR(@ProvinceID)) + '%'
	ELSE
		IF ISNULL(@ProvinceId, 0) = 0
			INSERT INTO #Order SELECT * FROM OrderAnalysis WITH(NOLOCK) WHERE DATEPART(YEAR, OpenDate) <> @Year
		ELSE
			INSERT INTO #Order SELECT * FROM OrderAnalysis WITH(NOLOCK) WHERE DATEPART(YEAR, OpenDate) <> @Year AND ProvinceId LIKE LTRIM(STR(@ProvinceID)) + '%'

	DECLARE @t AS TABLE(
		ID INT IDENTITY(1,1),
		Title VARCHAR(100),
		Cnt DECIMAL(18,2),
		Rate DECIMAL(18, 2)
	)

	DECLARE @S AS DECIMAL(18, 0)
	SELECT @S = COUNT(*) FROM #Order
	INSERT INTO @t VALUES('<font color=red>总订单数</font>', @S, 100.00)

	INSERT INTO @t
	SELECT '交费' + LTRIM(STR(Cnt)) + '次', COUNT(*), SUM(Cnt)*100.0 / @S
	FROM (SELECT cpMainId, COUNT(*) Cnt FROM #Order GROUP BY cpMainID) a
	GROUP BY Cnt
	ORDER BY Cnt

	DECLARE @Total AS INT
	SET @Total = @S
	SELECT @S = COUNT(*) FROM #Order WHERE NextID > 0
	INSERT INTO @t VALUES('<font color=red>续费订单数</font>', @S, @S * 100.00 / @Total)

	INSERT INTO @t
	SELECT IntervalRemark, COUNT(*), COUNT(*) * 100.0/@s 
	FROM #Order 
	WHERE Interval > 0
	GROUP BY Interval, IntervalRemark ORDER BY Interval

	SELECT ID 序号, Title 类型, Cnt 数量, Rate 比例 FROM @t
END













GO

/****** Object:  StoredProcedure [dbo].[spPaMainByRegisterModeFix]    Script Date: 2018/12/13 19:13:19 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[spPaMainByRegisterModeFix]
AS
BEGIN
	CREATE TABLE #t(Id INT)
	INSERT INTO #t
	SELECT a.id
	FROM cvMain a WITH(NOLOCK), paMain b WITH(NOLOCK)
	WHERE a.paMainId = b.ID 
	AND (
		((a.cvLevel LIKE '1111_1%' AND a.VerifyResult = 1)
			OR (a.cvLevelEng LIKE '1111_1%' AND a.VerifyResultEng = 1)
			)
		AND (b.RegisterMode = 1 OR b.RegisterType = 101)
		AND (b.addDate > GETDATE()-1.1
			OR a.RefreshDate > GETDATE()-1.1
			OR B.LastModifyDate > GETDATE()-1.1
			)
		AND b.AddMan > 1
		AND a.ID NOT IN(select cvMainID FROM bsCvModify WITH(NOLOCK) WHERE cvmainid>0)
		)

	INSERT INTO #t
	SELECT a.id
	FROM cvMain a WITH(NOLOCK), paMain b WITH(NOLOCK)
	WHERE a.paMainId = b.ID 
	AND b.RegisterMode = 1
	AND a.Valid > 0 
	AND (b.AddDate > GETDATE() - 90 OR b.LastLoginDate > GETDATE() - 3)

	DECLARE c CURSOR
	FOR SELECT id FROM #t
	FOR READ ONLY

	OPEN c
	IF @@FETCH_STATUS >= 0
	BEGIN
		DECLARE @cvMainID INT
		FETCH NEXT FROM c INTO @cvMainID
		WHILE(@@FETCH_STATUS = 0)
		BEGIN
			UPDATE cvMain SET VerifyResult = VerifyResult, VerifyResultEng = VerifyResultEng WHERE ID = @cvMainID
			--PRINT @cvMainID
			FETCH NEXT FROM c INTO @cvMainID
		END
	END
	CLOSE c
	DEALLOCATE c
END

GO

/****** Object:  StoredProcedure [dbo].[spPaPublishByFixUpdate]    Script Date: 2018/12/13 19:13:20 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--2013-3-22 sean fix pamainpublish cvmainpublish..................
CREATE PROCEDURE [dbo].[spPaPublishByFixUpdate]
AS
SET NOCOUNT ON
BEGIN
	SELECT a.id paMainId, b.Id cvMainId
	INTO #tmp
	FROM paMain a, cvMain b
	WHERE a.Id = b.paMainId
	AND a.Verifycount = 0
	AND b.VerifyResult = 1
	AND a.LastLogindate > GETDATE() - 183
	AND a.Id IN(SELECT Id FROM paMainPublish)
	AND b.Id IN(SELECT Id FROM cvMainPublish)
	DELETE cvMainPublish WHERE Id IN(SELECT cvMainId FROM #tmp)
	--------------------------------------
	CREATE TABLE #t(id INT, Col TINYINT)
	DECLARE @d AS DATETIME, @cn AS INT, @H AS INT, @i AS INT
	SELECT @D = CONVERT(VARCHAR(10), GETDATE() - 365, 120), @H = DATEPART(HOUR, GETDATE()), @cn = 6
	
	IF @h % 4 = 1    --OR 1=1
	BEGIN
		INSERT #t(id)
		SELECT id FROM cvmain WITH(NOLOCK) 
		WHERE EXISTS(SELECT 'x' FROM pamain WITH(NOLOCK) WHERE lastlogindate > @D AND pamain.id = cvmain.pamainid AND VerifyCount > 0)
		AND valid>0
		AND NOT EXISTS (SELECT id FROM cvmainpublish WITH(NOLOCK) WHERE cvmainpublish.id = cvmain.id)

		INSERT #t(id)
		SELECT id FROM cvMainPublish WITH(NOLOCK) 
		WHERE NOT EXISTS (SELECT id FROM cvMain WITH(NOLOCK) WHERE cvMain.id = cvMainPublish.id AND cvMain.valid = cvmainpublish.valid)

		DECLARE @id AS INT, @Mid AS INT
		SELECT @id = 0, @mid = max(id) FROM #t
		WHILE @id < @mid
		BEGIN
			SELECT @id = mIN(id) FROM #t WHERE id > @id
			UPDATE cvmain set refreshdate = refreshdate WHERE id = @id
		END

		TRUNCATE TABLE #t

		INSERT #t(ID)
		SELECT ID FROM paMain WHERE DATEADD(DAY, 1, LastLoginDate) < LastModifyDate AND LastLoginDate > GETDATE() - 365 AND VerifyCount > 0
		SELECT @id = 0, @mid = max(id) FROM #t
		WHILE @id < @mid
		BEGIN
			SELECT @id = mIN(id) FROM #t WHERE id > @id
			UPDATE pamain set LastLoginDate = LastModifyDate WHERE id = @id
		END

		TRUNCATE TABLE #t
	END

	INSERT #t SELECT a.id, 3 FROM cvmain a WITH(NOLOCK),cvmainpublish b WITH(NOLOCK) WHERE a.id = b.id AND a.JobName<> b.JobName
	INSERT #t SELECT a.id, 6 FROM cvmain a WITH(NOLOCK),cvmainpublish b WITH(NOLOCK) WHERE a.id = b.id AND a.RefreshDate<> b.RefreshDate	
	IF @h % @cn = 0    --OR 1=1
		INSERT #t SELECT a.id,1 FROM cvmain a WITH(NOLOCK),cvmainpublish b WITH(NOLOCK) WHERE a.id = b.id AND a.Degree<> b.Degree
	IF @h % @cn = 1    --OR 1=1
		INSERT #t SELECT a.id,2 FROM cvmain a WITH(NOLOCK),cvmainpublish b WITH(NOLOCK) WHERE a.id = b.id AND a.dcMajorID<> b.dcMajorID
	IF @h % @cn = 2    --OR 1=1
		INSERT #t SELECT a.id,4 FROM cvmain a WITH(NOLOCK),cvmainpublish b WITH(NOLOCK) WHERE a.id = b.id AND a.RelatedWorkYears<> b.RelatedWorkYears
	IF @h % @cn = 3    --OR 1=1
		INSERT #t SELECT a.id,5 FROM cvmain a WITH(NOLOCK),cvmainpublish b WITH(NOLOCK) WHERE a.id = b.id AND a.dcSalaryID<> b.dcSalaryID
	IF @h % @cn = 4    --OR 1=1
		INSERT #t SELECT a.id,7 FROM cvmain a WITH(NOLOCK),cvmainpublish b WITH(NOLOCK) WHERE a.id = b.id AND a.LastJobTypeID<> b.LastJobTypeID
	IF @h % @cn = 5    --OR 1=1
		INSERT #t SELECT a.id,8 FROM cvmain a WITH(NOLOCK),cvmainpublish b WITH(NOLOCK) WHERE a.id = b.id AND a.LastIndustryID<> b.LastIndustryID
	IF @h % @cn = 0    --OR 1=1
		INSERT #t SELECT a.id,9 FROM cvmain a WITH(NOLOCK),cvmainpublish b WITH(NOLOCK) WHERE a.id = b.id AND a.SubNodeNum<> b.SubNodeNum
	IF @h % @cn = 1    --OR 1=1
		INSERT #t SELECT a.id,10 FROM cvmain a WITH(NOLOCK),cvmainpublish b WITH(NOLOCK) WHERE a.id = b.id AND a.IsNegotiable<> b.IsNegotiable
	IF @h % @cn = 2    --OR 1=1
		INSERT #t SELECT a.id,11 FROM cvmain a WITH(NOLOCK),cvmainpublish b WITH(NOLOCK) WHERE a.id = b.id AND a.Attachment<> b.Attachment
	IF @h % @cn = 3    --OR 1=1
		INSERT #t SELECT a.id,12 FROM cvmain a WITH(NOLOCK),cvmainpublish b WITH(NOLOCK) WHERE a.id = b.id AND a.Valid<> b.Valid
	IF @h % @cn = 4    --OR 1=1
		INSERT #t SELECT a.id,13 FROM cvmain a WITH(NOLOCK),cvmainpublish b WITH(NOLOCK) WHERE a.id = b.id AND a.Speciality<> b.Speciality
	IF @h % @cn = 5    --OR 1=1
	BEGIN
		INSERT #t SELECT a.id,14 FROM cvmain a WITH(NOLOCK),cvmainpublish b WITH(NOLOCK) WHERE a.id = b.id AND a.SpecialityEng<> b.SpecialityEng
		INSERT #t SELECT a.id,15 FROM cvmain a WITH(NOLOCK),cvmainpublish b WITH(NOLOCK) WHERE a.id = b.id AND ISNULL(a.EmployType, 10) <> ISNULL(b.EmployType, 10)
	END

	UPDATE a set a.Degree = b.Degree FROM cvmainpublish a, cvmain b WHERE a.id = b.id AND a.id IN(SELECT id FROM #t WHERE col = 1)
	UPDATE a set a.dcMajorID = b.dcMajorID FROM cvmainpublish a, cvmain b WHERE a.id = b.id AND a.id IN(SELECT id FROM #t WHERE col = 2)
	UPDATE a set a.JobName = b.JobName FROM cvmainpublish a, cvmain b WHERE a.id = b.id AND a.id IN(SELECT id FROM #t WHERE col = 3)
	UPDATE a set a.RelatedWorkYears = b.RelatedWorkYears FROM cvmainpublish a, cvmain b WHERE a.id = b.id AND a.id IN(SELECT id FROM #t WHERE col = 4)
	UPDATE a set a.dcSalaryID = b.dcSalaryID FROM cvmainpublish a, cvmain b WHERE a.id = b.id AND a.id IN(SELECT id FROM #t WHERE col = 5)
	UPDATE a set a.RefreshDate = b.RefreshDate FROM cvmainpublish a, cvmain b WHERE a.id = b.id AND a.id IN(SELECT id FROM #t WHERE col = 6)
	UPDATE a set a.LastJobTypeID = b.LastJobTypeID FROM cvmainpublish a, cvmain b WHERE a.id = b.id AND a.id IN(SELECT id FROM #t WHERE col = 7)
	UPDATE a set a.LastIndustryID = b.LastIndustryID FROM cvmainpublish a, cvmain b WHERE a.id = b.id AND a.id IN(SELECT id FROM #t WHERE col = 8)
	UPDATE a set a.SubNodeNum = b.SubNodeNum FROM cvmainpublish a, cvmain b WHERE a.id = b.id AND a.id IN(SELECT id FROM #t WHERE col = 9)
	UPDATE a set a.IsNegotiable = b.IsNegotiable FROM cvmainpublish a, cvmain b WHERE a.id = b.id AND a.id IN(SELECT id FROM #t WHERE col = 10)
	UPDATE a set a.Attachment = b.Attachment FROM cvmainpublish a, cvmain b WHERE a.id = b.id AND a.id IN(SELECT id FROM #t WHERE col = 11)
	UPDATE a set a.Valid = b.Valid FROM cvmainpublish a, cvmain b WHERE a.id = b.id AND a.id IN(SELECT id FROM #t WHERE col = 12)
	UPDATE a set a.Speciality = b.Speciality FROM cvmainpublish a, cvmain b WHERE a.id = b.id AND a.id IN(SELECT id FROM #t WHERE col = 13)
	UPDATE a set a.SpecialityEng = b.SpecialityEng FROM cvmainpublish a, cvmain b WHERE a.id = b.id AND a.id IN(SELECT id FROM #t WHERE col = 14)
	UPDATE a set a.EmployType = b.EmployType FROM cvmainpublish a, cvmain b WHERE a.id = b.id AND a.id IN(SELECT id FROM #t WHERE col = 15)
	----SELECT a.id,c.lastlogindate,a.refreshdate,b.refreshdate FROM cvmain a,cvmainpublish b,pamain c WHERE a.pamainid = c.id AND a.id = b.id AND a.id IN(SELECT id FROM #t WHERE col = 6) order by c.lastlogindate
 
	IF @H = 7
	BEGIN
		TRUNCATE TABLE #t
		INSERT #t SELECT a.id,1 FROM cvappendix a WITH(NOLOCK), cvappendixpublish b WITH(NOLOCK) WHERE a.id = b.id AND a.Description <> b.Description
		INSERT #t SELECT a.id,2 FROM cvappendix a WITH(NOLOCK), cvappendixpublish b WITH(NOLOCK) WHERE a.id = b.id AND a.Name <> b.Name
		UPDATE a SET a.Description = b.Description FROM cvappendixpublish a, cvappendix b WHERE a.id = b.id AND a.id IN(SELECT id FROM #t WHERE col = 1)
		UPDATE a SET a.Name = b.Name FROM cvappendixpublish a, cvappendix b WHERE a.id = b.id AND a.id IN(SELECT id FROM #t WHERE col = 2)

		TRUNCATE TABLE #t
		INSERT #t SELECT a.id,1 FROM cvLanguage a WITH(NOLOCK), cvLanguagepublish b WITH(NOLOCK) WHERE a.id = b.id AND a.LanguageType <> b.LanguageType
		UPDATE a SET a.LanguageType = b.LanguageType FROM cvLanguagepublish a, cvLanguage b WHERE a.id = b.id AND a.id IN(SELECT id FROM #t WHERE col = 1)
		TRUNCATE TABLE #t
		INSERT #t SELECT a.id,1 FROM cvProject a WITH(NOLOCK), cvProjectpublish b WITH(NOLOCK) WHERE a.id = b.id AND a.Description <> b.Description
		INSERT #t SELECT a.id,2 FROM cvProject a WITH(NOLOCK), cvProjectpublish b WITH(NOLOCK) WHERE a.id = b.id AND a.Name <> b.Name
		INSERT #t SELECT a.id,3 FROM cvProject a WITH(NOLOCK), cvProjectpublish b WITH(NOLOCK) WHERE a.id = b.id AND a.Responsibilities <> b.Responsibilities
		UPDATE a SET a.Description = b.Description FROM cvProjectpublish a, cvProject b WHERE a.id = b.id AND a.id IN(SELECT id FROM #t WHERE col = 1)
		UPDATE a SET a.Name = b.Name FROM cvProjectpublish a, cvProject b WHERE a.id = b.id AND a.id IN(SELECT id FROM #t WHERE col = 2)
		UPDATE a SET a.Responsibilities = b.Responsibilities FROM cvProjectpublish a, cvProject b WHERE a.id = b.id AND a.id IN(SELECT id FROM #t WHERE col = 3)
		TRUNCATE TABLE #t
		INSERT #t SELECT a.id,1 FROM cvTraining a WITH(NOLOCK), cvTrainingpublish b WITH(NOLOCK) WHERE a.id = b.id AND a.Certificate <> b.Certificate
		INSERT #t SELECT a.id,2 FROM cvTraining a WITH(NOLOCK), cvTrainingpublish b WITH(NOLOCK) WHERE a.id = b.id AND a.Course <> b.Course
		INSERT #t SELECT a.id,3 FROM cvTraining a WITH(NOLOCK), cvTrainingpublish b WITH(NOLOCK) WHERE a.id = b.id AND a.Details <> b.Details
		INSERT #t SELECT a.id,4 FROM cvTraining a WITH(NOLOCK), cvTrainingpublish b WITH(NOLOCK) WHERE a.id = b.id AND a.Institution <> b.Institution
		UPDATE a SET a.Certificate = b.Certificate FROM cvTrainingpublish a, cvTraining b WHERE a.id = b.id AND a.id IN(SELECT id FROM #t WHERE col = 1)
		UPDATE a SET a.Course = b.Course FROM cvTrainingpublish a, cvTraining b WHERE a.id = b.id AND a.id IN(SELECT id FROM #t WHERE col = 2)
		UPDATE a SET a.Details = b.Details FROM cvTrainingpublish a, cvTraining b WHERE a.id = b.id AND a.id IN(SELECT id FROM #t WHERE col = 3)
		UPDATE a SET a.Institution = b.Institution FROM cvTrainingpublish a, cvTraining b WHERE a.id = b.id AND a.id IN(SELECT id FROM #t WHERE col = 4)

		TRUNCATE TABLE #t
		INSERT #t SELECT a.id,1 FROM cvEducation a WITH(NOLOCK), cvEducationpublish b WITH(NOLOCK) WHERE a.id = b.id AND a.dcMajorID <> b.dcMajorID
		INSERT #t SELECT a.id,2 FROM cvEducation a WITH(NOLOCK), cvEducationpublish b WITH(NOLOCK) WHERE a.id = b.id AND a.Degree <> b.Degree
		INSERT #t SELECT a.id,3 FROM cvEducation a WITH(NOLOCK), cvEducationpublish b WITH(NOLOCK) WHERE a.id = b.id AND a.Details <> b.Details
		INSERT #t SELECT a.id,4 FROM cvEducation a WITH(NOLOCK), cvEducationpublish b WITH(NOLOCK) WHERE a.id = b.id AND a.EduType <> b.EduType
		INSERT #t SELECT a.id,5 FROM cvEducation a WITH(NOLOCK), cvEducationpublish b WITH(NOLOCK) WHERE a.id = b.id AND a.GraduateCollage <> b.GraduateCollage
		INSERT #t SELECT a.id,6 FROM cvEducation a WITH(NOLOCK), cvEducationpublish b WITH(NOLOCK) WHERE a.id = b.id AND a.GraduateCollageEng <> b.GraduateCollageEng
		INSERT #t SELECT a.id,7 FROM cvEducation a WITH(NOLOCK), cvEducationpublish b WITH(NOLOCK) WHERE a.id = b.id AND a.Graduation <> b.Graduation
		INSERT #t SELECT a.id,8 FROM cvEducation a WITH(NOLOCK), cvEducationpublish b WITH(NOLOCK) WHERE a.id = b.id AND a.MajorName <> b.MajorName
		INSERT #t SELECT a.id,9 FROM cvEducation a WITH(NOLOCK), cvEducationpublish b WITH(NOLOCK) WHERE a.id = b.id AND a.MajorNameEng <> b.MajorNameEng
		UPDATE a SET a.dcMajorID = b.dcMajorID FROM cvEducationpublish a, cvEducation b WHERE a.id = b.id AND a.id IN(SELECT id FROM #t WHERE col = 1)
		UPDATE a SET a.Degree = b.Degree FROM cvEducationpublish a, cvEducation b WHERE a.id = b.id AND a.id IN(SELECT id FROM #t WHERE col = 2)
		UPDATE a SET a.Details = b.Details FROM cvEducationpublish a, cvEducation b WHERE a.id = b.id AND a.id IN(SELECT id FROM #t WHERE col = 3)
		UPDATE a SET a.EduType = b.EduType FROM cvEducationpublish a, cvEducation b WHERE a.id = b.id AND a.id IN(SELECT id FROM #t WHERE col = 4)
		UPDATE a SET a.GraduateCollage = b.GraduateCollage FROM cvEducationpublish a, cvEducation b WHERE a.id = b.id AND a.id IN(SELECT id FROM #t WHERE col = 5)
		UPDATE a SET a.GraduateCollageEng = b.GraduateCollageEng FROM cvEducationpublish a, cvEducation b WHERE a.id = b.id AND a.id IN(SELECT id FROM #t WHERE col = 6)
		UPDATE a SET a.Graduation = b.Graduation FROM cvEducationpublish a, cvEducation b WHERE a.id = b.id AND a.id IN(SELECT id FROM #t WHERE col = 7)
		UPDATE a SET a.MajorName = b.MajorName FROM cvEducationpublish a, cvEducation b WHERE a.id = b.id AND a.id IN(SELECT id FROM #t WHERE col = 8)
		UPDATE a SET a.MajorNameEng = b.MajorNameEng FROM cvEducationpublish a, cvEducation b WHERE a.id = b.id AND a.id IN(SELECT id FROM #t WHERE col = 9)

		TRUNCATE TABLE #t
		INSERT #t SELECT a.id,1 FROM cvExperience a WITH(NOLOCK), cvExperiencepublish b WITH(NOLOCK) WHERE a.id = b.id AND a.CompanyName <> b.CompanyName
		INSERT #t SELECT a.id,2 FROM cvExperience a WITH(NOLOCK), cvExperiencepublish b WITH(NOLOCK) WHERE a.id = b.id AND a.dcIndustryID <> b.dcIndustryID
		INSERT #t SELECT a.id,3 FROM cvExperience a WITH(NOLOCK), cvExperiencepublish b WITH(NOLOCK) WHERE a.id = b.id AND a.dcJobtypeID <> b.dcJobtypeID
		INSERT #t SELECT a.id,4 FROM cvExperience a WITH(NOLOCK), cvExperiencepublish b WITH(NOLOCK) WHERE a.id = b.id AND a.Description <> b.Description
		INSERT #t SELECT a.id,5 FROM cvExperience a WITH(NOLOCK), cvExperiencepublish b WITH(NOLOCK) WHERE a.id = b.id AND a.JobName <> b.JobName
		INSERT #t SELECT a.id,6 FROM cvExperience a WITH(NOLOCK), cvExperiencepublish b WITH(NOLOCK) WHERE a.id = b.id AND a.SubNodeNum <> b.SubNodeNum
		UPDATE a SET a.CompanyName = b.CompanyName FROM cvExperiencepublish a, cvExperience b WHERE a.id = b.id AND a.id IN(SELECT id FROM #t WHERE col = 1)
		UPDATE a SET a.dcIndustryID = b.dcIndustryID FROM cvExperiencepublish a, cvExperience b WHERE a.id = b.id AND a.id IN(SELECT id FROM #t WHERE col = 2)
		UPDATE a SET a.dcJobtypeID = b.dcJobtypeID FROM cvExperiencepublish a, cvExperience b WHERE a.id = b.id AND a.id IN(SELECT id FROM #t WHERE col = 3)
		UPDATE a SET a.Description = b.Description FROM cvExperiencepublish a, cvExperience b WHERE a.id = b.id AND a.id IN(SELECT id FROM #t WHERE col = 4)
		UPDATE a SET a.JobName = b.JobName FROM cvExperiencepublish a, cvExperience b WHERE a.id = b.id AND a.id IN(SELECT id FROM #t WHERE col = 5)
		UPDATE a SET a.SubNodeNum = b.SubNodeNum FROM cvExperiencepublish a, cvExperience b WHERE a.id = b.id AND a.id IN(SELECT id FROM #t WHERE col = 6)

		DELETE FROM cvIndustryPublish
		WHERE NOT EXISTS 
			(
			SELECT 'x' 
			FROM cvIndustry WITH(NOLOCK) 
			WHERE cvIndustry.cvMainID IN(SELECT ID FROM cvMainPublish WITH(NOLOCK))
			AND cvIndustry.cvMainID = cvIndustryPublish.cvMainID
			AND cvIndustry.dcIndustryId = cvIndustryPublish.dcIndustryId
			)

		INSERT cvIndustryPublish(cvMainId, dcIndustryID)
		SELECT cvMainId, dcIndustryID
		FROM cvIndustry WITH(NOLOCK)
		WHERE cvMainID IN(SELECT ID FROM cvMainPublish WITH(NOLOCK))
		AND NOT EXISTS 
			(
			SELECT 'x' 
			FROM cvIndustryPublish WITH(NOLOCK) 
			WHERE cvIndustry.cvMainID = cvIndustryPublish.cvMainID
			AND cvIndustry.dcIndustryId = cvIndustryPublish.dcIndustryId
			)

		DELETE FROM cvJobTypePublish
		WHERE NOT EXISTS 
			(
			SELECT 'x' 
			FROM cvJobType WITH(NOLOCK) 
			WHERE cvJobType.cvMainID IN(SELECT ID FROM cvMainPublish WITH(NOLOCK))
			AND cvJobType.cvMainID = cvJobTypePublish.cvMainID
			AND cvJobType.dcJobTypeId = cvJobTypePublish.dcJobTypeId
			)

		INSERT cvJobTypePublish(cvMainId, dcJobTypeId)
		SELECT * FROM cvJobType WITH(NOLOCK)
		WHERE cvMainID IN(SELECT ID FROM cvMainPublish WITH(NOLOCK))
		AND NOT EXISTS 
			(
			SELECT 'x' 
			FROM cvJobTypePublish WITH(NOLOCK) 
			WHERE cvJobType.cvMainID = cvJobTypePublish.cvMainID
			AND cvJobType.dcJobTypeId = cvJobTypePublish.dcJobTypeId
			)

		DELETE FROM cvJobPlacePublish
		WHERE NOT EXISTS 
			(
			SELECT 'x' 
			FROM cvJobPlace WITH(NOLOCK) 
			WHERE cvJobPlace.cvMainID IN(SELECT ID FROM cvMainPublish WITH(NOLOCK))
			AND cvJobPlace.cvMainID = cvJobPlacePublish.cvMainID
			AND cvJobPlace.dcRegionId = cvJobPlacePublish.dcRegionId
			)

		INSERT cvJobPlacePublish(cvMainId, dcRegionId)
		SELECT * FROM cvJobPlace WITH(NOLOCK)
		WHERE cvMainID IN(SELECT ID FROM cvMainPublish WITH(NOLOCK))
		AND NOT EXISTS 
			(
			SELECT 'x' 
			FROM cvJobPlacePublish WITH(NOLOCK) 
			WHERE cvJobPlace.cvMainID = cvJobPlacePublish.cvMainID
			AND cvJobPlace.dcRegionId = cvJobPlacePublish.dcRegionId
			)
	END
	
	DROP TABLE #t

	update b set b.secondid = a.secondid from cvmain a, cvmainpublish b where a.id=b.id and b.secondid is null
	update b set b.secondid = a.secondid from cvmain a, cvmainpublish b where a.id=b.id and b.secondid != a.secondid
END













GO

/****** Object:  StoredProcedure [dbo].[spPaRemindLogInsert]    Script Date: 2018/12/13 19:13:21 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2015.2.26
--创建人：Lambo
--说明：插入提醒信息
--#####################################################
CREATE PROCEDURE [dbo].[spPaRemindLogInsert]
AS
BEGIN 
	DELETE FROM PaAttention WHERE paMainid NOT IN(SELECT Id FROM paMain)
	--1 关注的企业新发布职位
	INSERT INTO PaRemindLog(PaMainID,Contenttext,RemindStatus,AddDate,RemainID,RemainType)
	SELECT PaMainID,'您关注的 '+b.Name+' 新发布'+(SELECT LTRIM(STR(COUNT(*))) FROM Job n WITH(NOLOCK) WHERE  n.CpMainID = b.ID AND n.IssueDate>a.AddDate AND n.IssueDate >GETDATE()-1 AND IsDelete=0)+'个职位，请及时登录查看…',
		0,GETDATE(),AttentionID,1
	FROM PaAttention a WITH(NOLOCK),CpMain b WITH(NOLOCK) 
	WHERE a.AttentionID = b.ID
	AND AttentionType =1 
	AND EXISTS(SELECT TOP 1 'x' FROM Job n WHERE  n.CpMainID = b.ID AND n.IssueEnd>a.AddDate AND n.IssueDate >GETDATE()-1 AND IsDelete=0)
	
	--2 关注的企业新发布点评
	INSERT INTO PaRemindLog(PaMainID,Contenttext,RemindStatus,AddDate,RemainID,RemainType)
	SELECT PaMainID,'您关注的 '+b.Name+' 新发布'+(SELECT LTRIM(STR(COUNT(*))) FROM comments m WITH(NOLOCK) 
		WHERE m.CpMainID = b.ID 
		AND m.VerifyDate>a.AddDate 
		AND m.CommentType <> 3
		AND m.VerifyDate >GETDATE()-1)+'条点评信息，请及时登录查看',
		0,GETDATE(),AttentionID,2
	FROM PaAttention a WITH(NOLOCK),CpMain b WITH(NOLOCK) 
	WHERE a.AttentionID = b.ID
	AND AttentionType =1 
	AND EXISTS(SELECT TOP 1 'x' FROM comments m WITH(NOLOCK) WHERE m.CpMainID = b.ID AND m.VerifyDate>a.AddDate AND m.CommentType <> 3 AND m.VerifyDate >GETDATE()-1)

	--3 关注的企业新发布面经
	INSERT INTO PaRemindLog(PaMainID,Contenttext,RemindStatus,AddDate,RemainID,RemainType)
	SELECT PaMainID,'您关注的 '+b.Name+' 新发布'+(SELECT LTRIM(STR(COUNT(*))) FROM InterView m WITH(NOLOCK) 
		WHERE m.CpMainID = b.ID 
		AND m.VerifyDate>a.AddDate 
		AND m.InterViewType <> 3
		AND m.VerifyDate >GETDATE()-1)+'条面经信息，请及时登录查看',
		0,GETDATE(),AttentionID,3
	FROM PaAttention a WITH(NOLOCK),CpMain b WITH(NOLOCK) 
	WHERE a.AttentionID = b.ID
	AND AttentionType =1 
	AND EXISTS(SELECT TOP 1 'x' FROM InterView m WITH(NOLOCK) WHERE m.CpMainID = b.ID AND m.InterViewType <> 3 AND m.VerifyDate>a.AddDate AND m.VerifyDate >GETDATE()-1)

	--4 职位24小时到期
	INSERT INTO PaRemindLog(PaMainID,Contenttext,RemindStatus,AddDate,RemainID,RemainType)
	SELECT a.ID,'您关注的职位中有'+(SELECT LTRIM(STR(COUNT(*))) FROM PaAttention m WITH(NOLOCK),Job n WITH(NOLOCK) WHERE m.AttentionID = n.ID AND m.AttentionType =2 AND m.PaMainID = a.ID AND n.IssueEnd BETWEEN GETDATE() AND GETDATE()+1 AND n.IsDelete = 0)+'职位即将截止，如果目前您还没有申请，请尽快完成申请。',
		0,GETDATE(),a.ID,4
	FROM PaMain a WITH(NOLOCK)
	WHERE EXISTS(SELECT TOP 1 'x' FROM PaAttention m WITH(NOLOCK),Job n WITH(NOLOCK) WHERE m.AttentionID = n.ID AND m.AttentionType =2 AND m.PaMainID = a.ID AND n.IssueEnd BETWEEN GETDATE() AND GETDATE()+1 AND n.IsDelete = 0)
END
GO

/****** Object:  StoredProcedure [dbo].[spPaYourFoodByPaJobCompareInsert]    Script Date: 2018/12/13 19:13:21 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：20160825
--创建人：Peter
--说明：新版你的菜儿推送
--#####################################################
CREATE PROCEDURE [dbo].[spPaYourFoodByPaJobCompareInsert]
AS
SET NOCOUNT ON
BEGIN
	INSERT INTO paYourFood(paMainId,cvMainId,JobId,AddDate)
	SELECT PaMainID,(
		SELECT TOP 1 ID 
		FROM CvMain WITH(NOLOCK) 
		WHERE PaMainID = PaJobCompare.PaMainID 
		ORDER BY Valid DESC),CompareJobID,GETDATE()
	FROM PaJobCompare WITH(NOLOCK)
	WHERE PushDate IS NULL
	AND BatchNo = (
		SELECT MAX(BatchNo) 
		FROM PaJobCompare WITH(NOLOCK) 
		WHERE PaMainID = PaJobCompare.PaMainID)
	
	UPDATE PaJobCompare
	SET PushDate = GETDATE()
	WHERE PushDate IS NULL
	AND BatchNo = (
		SELECT MAX(BatchNo) 
		FROM PaJobCompare WITH(NOLOCK) 
		WHERE PaMainID = PaJobCompare.PaMainID)
	
END
GO

/****** Object:  StoredProcedure [dbo].[sppaYourFoodInsert]    Script Date: 2018/12/13 19:13:21 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[sppaYourFoodInsert]
AS
RETURN
SET NOCOUNT ON
BEGIN
	IF EXISTS(SELECT 'x' FROM Oadb..WorkDate WHERE IsPaid = 1 AND WorkDate = CONVERT(VARCHAR(8), GETDATE(), 112))
		RETURN
	IF DATEPART(HOUR, GETDATE()) < 10
		RETURN
	DELETE FROM paYourFood WHERE AddDate < GETDATE() - 62
	DECLARE @ThisMonth INT
	SET @ThisMonth = CONVERT(VARCHAR(6), GETDATE(), 112)

	IF NOT EXISTS(SELECT 'x' FROM paYourFoodIndex WHERE AddDate > CONVERT(VARCHAR(10), GETDATE(), 120))
	BEGIN
		TRUNCATE TABLE paYourFoodIndex
		TRUNCATE TABLE paYourFoodWeiXin
		TRUNCATE TABLE ShortDB..paYourFoodEmail

		INSERT INTO paYourFoodIndex
		SELECT b.paMainId, b.Id cvMainId, a.LastLoginDate, (@ThisMonth - a.BirthDay) / 100 Age,
			b.dcSalaryID, b.EmployType, b.Degree, b.RelatedWorkYears, 0, GETDATE()
		FROM paMain a WITH(NOLOCK), cvMain b WITH(NOLOCK)
		WHERE a.LastLoginDate > CONVERT(VARCHAR(10),  GETDATE() - 14)
		AND a.Id = b.paMainId
		AND b.dcSalaryId IS NOT NULL
		AND a.BirthDay IS NOT NULL
		AND b.Degree IS NOT NULL
		AND b.RelatedWorkYears IS NOT NULL
		AND a.IsUseYourFood = 1
		AND (a.Id % 2 = DATEPART(Day, GETDATE()) % 2
			OR a.Id IN(SELECT paMainId FROM wxFans WHERE Status > 0)
			)
		ORDER BY b.paMainId DESC, b.Id DESC

		select distinct pamainid 
		into #tq from paloginlog
		where browser<>'weixin'
		and adddate > getdate() - 16
		delete from payourfoodindex where pamainid not in(select pamainid from #tq)
	END
	IF NOT EXISTS(SELECT 'x' FROM paYourFoodIndex WHERE AddDate > CONVERT(VARCHAR(10), GETDATE(), 120) AND HasRun = 0)
		RETURN
	CREATE TABLE #Job(
		Id INT,
		cpMainId INT,
		dcRegionId VARCHAR(6),
		dcJobTypeId VARCHAR(4),
		dcSalaryId INT,
		EmployType INT,
		dcEducationId INT,
		MinExperience INT,
		MinAge INT,
		MaxAge INT,
		AgeScore INT,
		EduScore INT,
		ExpScore INt,
		SizeScore INT
		)	
	DECLARE @paMainId INT, @CvMainID INT, @dcSalaryId INT, @EmployType INT, @Degree INT, @Exp INT, @Age INT, @Id INT
	DECLARE @JobPlace AS TABLE(Id INT IDENTITY(1, 1), dcRegionId VARCHAR(6))
	DECLARE @JobType AS TABLE(Id INT IDENTITY(1, 1), dcJobTypeId VARCHAR(4))
	DECLARE @t1 AS TABLE(dcRegionId VARCHAR(6))
	DECLARE @t2 AS TABLE(dcJobTypeId VARCHAR(4))

	SELECT @Id = 0
	WHILE EXISTS(SELECT 'x' FROM paYourFoodIndex WHERE HasRun = 0 AND Id > @Id)		--@id < 10
	BEGIN
		SELECT TOP 1 @id = Id, @cvMainId = cvMainId, @paMainId = paMainId, @Age = Age,
			 @dcSalaryId = dcSalaryID, @EmployType = EmployType, @Degree = Degree, @Exp = RelatedWorkYears
		FROM paYourFoodIndex 
		WHERE Id > @Id
		AND HasRun = 0
		ORDER BY Id
		
		DELETE FROM @JobPlace
		DELETE FROM @JobType
		DELETE FROM @t1
		DELETE FROM @t2

		INSERT INTO @JobPlace(dcRegionId)
		SELECT dcRegionId FROM cvJobPlace WITH(NOLOCK)
		WHERE cvMainId = @cvMainId

		INSERT INTO @JobType(dcJobTypeId)
		SELECT dcJobTypeId FROM cvJobType WITH(NOLOCK)
		WHERE cvMainId = @cvMainId

		DELETE a FROM @JobPlace a, @JobPlace b WHERE a.id <> b.Id AND a.dcRegionID <> b.dcRegionId AND b.dcRegionId LIKE a.dcRegionId + '%'
		DELETE a FROM @JobType a, @JobType b WHERE a.id <> b.Id AND a.dcJobTypeId <> b.dcJobTypeId AND b.dcJobTypeId LIKE a.dcJobTypeId + '%'
		INSERT INTO @t2 
		SELECT Id FROM dcJobType WHERE ID IN(SELECT dcJobTypeId FROM @JobType) OR ParentID IN(SELECT dcJobTypeId FROM @JobType)

		INSERT INTO @t1 SELECT Id FROM dcRegion WHERE ID IN(SELECT dcRegionId FROM @JobPlace) 
		INSERT INTO @t1 SELECT Id FROM dcRegion WHERE LEFT(ID, 4) IN(SELECT dcRegionId FROM @JobPlace)
		INSERT INTO @t1 SELECT Id FROM dcRegion WHERE LEFT(ID, 2) IN(SELECT dcRegionId FROM @JobPlace)
		--===========================================
		TRUNCATE TABLE #Job
		INSERT INTO #Job(Id, cpMainId, dcRegionId, dcJobTypeId, dcSalaryId, EmployType, dcEducationId, MinExperience, MinAge, MaxAge)
		SELECT TOP 200 Id, cpMainId, dcRegionId, dcJobTypeId, dcSalaryId, EmployType, dcEducationId, MinExperience, MinAge, MaxAge
		FROM jobPublish WITH(NOLOCK)
		WHERE EmployType = @EmployType
		AND dcRegionID IN(SELECT dcRegionId FROM @t1)
		AND dcJobTypeId IN(SELECT dcJobTypeId FROM @t2)
		AND dcSalaryId IN(100, @dcSalaryId)
		AND EXISTS(SELECT 'x' FROM cpMainPublish WITH(NOLOCK) WHERE LastLoginDate > GETDATE() - 31 AND cpMainPublish.Id = cpMainId)
		ORDER BY RefreshDate DESC

		DELETE #Job WHERE Id IN(SELECT JobId FROM paYourFood WITH(NOLOCK) WHERE paMainId = @pamainId)
		DELETE #Job WHERE Id IN(SELECT JobId FROM ExJobApply WITH(NOLOCK) WHERE cvMainID IN(SELECT ID FROM cvMain WITH(NOLOCK) WHERE paMainId = @pamainId))
		IF(SELECT COUNT(*) FROM #Job) > 3
		BEGIN			
			UPDATE a SET a.SizeScore = b.dcCompanySizeId * -1, EduScore = 0, AgeScore = 0, ExpScore = 0  FROM #Job a, cpMainPublish b WHERE a.cpMainId = b.ID
			UPDATE #Job SET EduScore = dcEducationId - @Degree WHERE dcEducationId > @Degree AND dcEducationId < 100
			UPDATE #Job SET EduScore = @Degree - dcEducationId WHERE dcEducationId < @Degree AND dcEducationId < 100
			UPDATE #Job SET MinAge = 16 WHERE MinAge = 99
			UPDATE #Job SET MaxAge = 60 WHERE MaxAge = 99
			UPDATE #Job SET AgeScore = (MinAge - @Age) / 5 + 1 WHERE MinAge > @Age
			UPDATE #Job SET AgeScore = (@Age - MaxAge) / 5 + 1 WHERE MaxAge < @Age
			IF @Exp = 0
				SET @Exp = 1
			ELSE IF @Exp IN(1, 2)
				SET @Exp = 2
			ELSE IF @Exp IN(3,4,5)
				SET @Exp = 3
			ELSE IF @Exp IN(6,7,8,9,10)
				SET @Exp = 4
			ELSE IF @Exp > 10
				SET @Exp = 5
			ELSE
				SET @Exp = 0
			UPDATE #Job SET MinExperience = CASE WHEN MinExperience = 5 THEN 1 ELSE MinExperience + 1 END WHERE MinExperience > 0
			UPDATE #Job SET ExpScore = MinExperience - @Exp WHERE MinExperience > @Exp
			UPDATE #Job SET ExpScore = @Exp - MinExperience WHERE MinExperience < @Exp AND MinExperience > 0	
		END
		INSERT INTO paYourFood(Jobid, paMainId, cvMainId, AddDate)
		SELECT TOP 3 Id, @paMainId, @cvMainId, GETDATE() FROM #job ORDER BY EduScore, ExpScore + SizeScore + AgeScore
		DELETE FROM paYourFood 
		WHERE paMainId = @PaMainId 
		AND AddDate > DATEADD(MINUTE, -10, GETDATE())
		AND Id NOT IN(SELECT TOP 3 ID FROM paYourFood WHERE paMainId = @PaMainId AND AddDate > DATEADD(MINUTE, -10, GETDATE()))

		UPDATE paYourFoodIndex SET HasRun = 1 WHERE Id = @Id
	END
	--=================================
	/*TRUNCATE TABLE paYourFoodWeiXin
	SELECT a.*, ROW_NUMBER() OVER(PARTITION BY paMainId ORDER BY JobId DESC) RowNo,
		b.Name JobName, c.Name CompanyName, b.caMainId, b.cpMainId
	INTO #t
	FROM paYourFood a, Job b, cpMain c
	WHERE a.AddDate > GETDATE() - 1
	AND a.JobId = b.Id
	AND b.cpMainid = c.Id
	AND a.paMainId IN(SELECT paMainId FROM wxFans WHERE Status > 0)

	INSERT INTO paYourFoodWeiXin(paMainId, cvMainId, JobDesc, cpMainId, caMainId)
	SELECT paMainId, cvMainId, '', cpMainId, caMainId
	FROM #t
	WHERE AddDate > GETDATE() - 1
	AND RowNo = 1

	UPDATE a
	SET a.JobDesc = b.JobName + '[' + b.CompanyName + ']'
	FROM paYourFoodWeiXin a, #t b
	WHERE a.paMainId = b.paMainId 
	AND b.RowNo = 1

	UPDATE a
	SET a.JobDesc = a.JobDesc + '、' + b.JobName + '[' + b.CompanyName + ']'
	FROM paYourFoodWeiXin a, #t b
	WHERE a.paMainId = b.paMainId 
	AND b.RowNo = 2

	UPDATE a
	SET a.JobDesc = a.JobDesc + '、' + b.JobName + '[' + b.CompanyName + ']'
	FROM paYourFoodWeiXin a, #t b
	WHERE a.paMainId = b.paMainId 
	AND b.RowNo = 3

	DELETE paYourFoodWeiXin WHERE ISNULL(JobDesc, '') = ''
	DROP TABLE #t
------------------------------
	TRUNCATE TABLE ShortDb..paYourFoodEmail
	SELECT a.*, ROW_NUMBER() OVER(PARTITION BY paMainId ORDER BY JobId DESC) RowNo,
		b.Name JobName, c.Name CompanyName, b.caMainId, b.cpMainId, b.SecondId JobId2, c.SecondId cpMainId2,
		(SELECT Description FROM dcRegion WHERE Id = b.dcRegionId) Region,
		ISNULL((SELECT Description FROM dcSalary WHERE Id = b.dcSalaryId), '面议') Salary,
		ISNULL((SELECT Description FROM dcEducation WHERE Id = b.dcEducationId), '不限') Education,
		(SELECT 'www.' + ProvinceDomain FROM dcProvince WHERE Id = LEFT(b.dcRegionId, 2)) SiteUrl
	INTO #TEmail
	FROM paYourFood a, Job b, cpMain c
	WHERE a.AddDate > GETDATE() - 1
	AND a.JobId = b.Id
	AND b.cpMainid = c.Id
 
	INSERT INTO paYourFoodEmail(paMainId, Email, paName, dcProvinceId, AddDate, UserName)
	SELECT b.Id, b.Email, b.Name, b.dcProvinceID, GETDATE(), b.UserNameLower
	FROM #TEmail a, paMain b
	WHERE a.RowNo = 1
	AND a.paMainId = b.Id
 
	SELECT paMainId, '
<table>
  <tr style="FONT-WEIGHT: bold; background-color:#f7b666;">
    <td>招聘职位</td>
    <td>公司名称</td>
    <td>工作地点</td>
    <td>职位月薪</td>
    <td>最低学历</td>
  </tr>
  <tr>
	<td><a target="_blank" href="http://' + SiteUrl + '/personal/jb' + JobId2 + '.html">' + JobName + '</a></td>
	<td><a target="_blank" href="http://' + SiteUrl + '/personal/cp' + cpMainId2 + '.html">' + CompanyName + '</a></td>
	<td>' + Region + '</td>
	<td>' + Salary + '</td>
	<td>' + Education + '</td>
  </tr>' JobList
	INTO #e1
	FROM #TEmail
	WHERE RowNo = 1

	SELECT paMainId, '
  <tr>
	<td><a target="_blank" href="http://' + SiteUrl + '/personal/jb' + JobId2 + '.html">' + JobName + '</a></td>
	<td><a target="_blank" href="http://' + SiteUrl + '/personal/cp' + cpMainId2 + '.html">' + CompanyName + '</a></td>
	<td>' + Region + '</td>
	<td>' + Salary + '</td>
	<td>' + Education + '</td>
  </tr>' JobList
	INTO #e2
	FROM #TEmail
	WHERE RowNo = 2

	SELECT paMainId, '
  <tr>
	<td><a target="_blank" href="http://' + SiteUrl + '/personal/jb' + JobId2 + '.html">' + JobName + '</a></td>
	<td><a target="_blank" href="http://' + SiteUrl + '/personal/cp' + cpMainId2 + '.html">' + CompanyName + '</a></td>
	<td>' + Region + '</td>
	<td>' + Salary + '</td>
	<td>' + Education + '</td>
  </tr>' JobList
	INTO #e3
	FROM #TEmail
	WHERE RowNo = 3

	SELECT a.paMainId, a.JobList + ISNULL(b.JobList, '') + ISNULL(c.JobList, '') + '
</table>' JobList
	INTO #e4
	FROM #e1 a
	LEFT JOIN #e2 b on a.pamainid = b.pamainid
	LEFT JOIN #e3 c on a.pamainid = c.pamainid

	UPDATE a
	SET a.JobList = b.JobList
	FROM paYourFoodEmail a, #e4 b
	WHERE a.paMainId = b.paMainId

	DROP TABLE #TEmail
*/
END
GO

/****** Object:  StoredProcedure [dbo].[spPaYourFoodWeixinInsert]    Script Date: 2018/12/13 19:13:21 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[spPaYourFoodWeixinInsert]
AS
SET NOCOUNT ON
BEGIN
	IF DATEPART(HOUR, GETDATE()) < 17
		RETURN

	IF NOT EXISTS(SELECT 'x' FROM paYourFoodWeiXin WHERE AddDate > CONVERT(VARCHAR(10), GETDATE(), 120))
		TRUNCATE TABLE paYourFoodWeiXin
	IF NOT EXISTS(SELECT 'x' FROM paYourFoodEmail WHERE AddDate > CONVERT(VARCHAR(10), GETDATE(), 120))
		TRUNCATE TABLE ShortDb..paYourFoodEmail

	SELECT a.*, ROW_NUMBER() OVER(PARTITION BY paMainId ORDER BY CompareJobId DESC) RowNo,
		b.Name JobName, c.Name CompanyName, b.caMainId, b.cpMainId
	INTO #t
	FROM PaJobCompare a, Job b, cpMain c
	WHERE a.AddDate > CONVERT(VARCHAR(10), GETDATE(), 120)
	AND a.PushDate IS NULL
	AND a.CompareJobId = b.Id
	AND b.cpMainid = c.Id
	AND a.paMainId IN(SELECT paMainId FROM wxFans WHERE Status > 0)
	AND a.paMainId IN(SELECT Id FROM paMain WHERE IsUseYourFood = 1)

	INSERT INTO paYourFoodWeiXin(paMainId, cvMainId, JobDesc, cpMainId, caMainId,BatchNo)
	SELECT paMainId,(
		SELECT TOP 1 ID 
		FROM CvMain WITH(NOLOCK) 
		WHERE PaMainID = #t.PaMainID 
		ORDER BY Valid DESC), '', cpMainId, caMainId,BatchNo
	FROM #t
	WHERE AddDate > CONVERT(VARCHAR(10), GETDATE(), 120)
	AND RowNo = 1
	
	UPDATE PaJobCompare
	SET PushDate = GETDATE()
	WHERE EXISTS(
		SELECT 'x' FROM #t WHERE ID = PaJobCompare.ID
	)

	UPDATE a
	SET a.JobDesc = b.JobName + '[' + b.CompanyName + ']'
	FROM paYourFoodWeiXin a, #t b
	WHERE a.paMainId = b.paMainId 
	AND b.RowNo = 1
	
	UPDATE a
	SET a.JobDesc = a.JobDesc + '、' + b.JobName + '[' + b.CompanyName + ']'
	FROM paYourFoodWeiXin a, #t b
	WHERE a.paMainId = b.paMainId 
	AND b.RowNo = 2

	UPDATE a
	SET a.JobDesc = a.JobDesc + '、' + b.JobName + '[' + b.CompanyName + ']'
	FROM paYourFoodWeiXin a, #t b
	WHERE a.paMainId = b.paMainId 
	AND b.RowNo = 3

	DELETE paYourFoodWeiXin WHERE ISNULL(JobDesc, '') = ''
	DROP TABLE #t

	------------------------------
	SELECT a.*, ROW_NUMBER() OVER(PARTITION BY paMainId ORDER BY CompareJobId DESC) RowNo,
		b.Name JobName, c.Name CompanyName, b.caMainId, b.cpMainId, b.SecondId JobId2, c.SecondId cpMainId2,
		(SELECT Description FROM dcRegion WHERE Id = b.dcRegionId) Region,
		ISNULL((SELECT Description FROM dcSalary WHERE Id = b.dcSalaryId), '面议') Salary,
		ISNULL((SELECT Description FROM dcEducation WHERE Id = b.dcEducationId), '不限') Education,
		(SELECT 'www.' + ProvinceDomain FROM dcProvince WHERE Id = LEFT(b.dcRegionId, 2)) SiteUrl
	INTO #TEmail
	FROM PaJobCompare a, Job b, cpMain c
	WHERE a.AddDate > CONVERT(VARCHAR(10), GETDATE(), 120)
	AND a.PushDate IS NULL
	AND a.CompareJobId = b.Id
	AND b.cpMainid = c.Id
 
	INSERT INTO paYourFoodEmail(paMainId, Email, paName, dcProvinceId, AddDate, UserName)
	SELECT b.Id, b.Email, b.Name, b.dcProvinceID, GETDATE(), b.UserNameLower
	FROM #TEmail a, paMain b
	WHERE a.RowNo = 1
	AND a.paMainId = b.Id
 
	UPDATE PaJobCompare
	SET PushDate = GETDATE()
	WHERE EXISTS(
		SELECT 'x' FROM #TEmail WHERE ID = PaJobCompare.ID
	)
	 
	SELECT paMainId, '
<table>
  <tr style="FONT-WEIGHT: bold; background-color:#f7b666;">
    <td>招聘职位</td>
    <td>公司名称</td>
    <td>工作地点</td>
    <td>职位月薪</td>
    <td>最低学历</td>
  </tr>
  <tr>
	<td><a target="_blank" href="http://' + SiteUrl + '/personal/jb' + JobId2 + '.html">' + JobName + '</a></td>
	<td><a target="_blank" href="http://' + SiteUrl + '/personal/cp' + cpMainId2 + '.html">' + CompanyName + '</a></td>
	<td>' + Region + '</td>
	<td>' + Salary + '</td>
	<td>' + Education + '</td>
  </tr>' JobList
	INTO #e1
	FROM #TEmail
	WHERE RowNo = 1

	SELECT paMainId, '
  <tr>
	<td><a target="_blank" href="http://' + SiteUrl + '/personal/jb' + JobId2 + '.html">' + JobName + '</a></td>
	<td><a target="_blank" href="http://' + SiteUrl + '/personal/cp' + cpMainId2 + '.html">' + CompanyName + '</a></td>
	<td>' + Region + '</td>
	<td>' + Salary + '</td>
	<td>' + Education + '</td>
  </tr>' JobList
	INTO #e2
	FROM #TEmail
	WHERE RowNo = 2

	SELECT paMainId, '
  <tr>
	<td><a target="_blank" href="http://' + SiteUrl + '/personal/jb' + JobId2 + '.html">' + JobName + '</a></td>
	<td><a target="_blank" href="http://' + SiteUrl + '/personal/cp' + cpMainId2 + '.html">' + CompanyName + '</a></td>
	<td>' + Region + '</td>
	<td>' + Salary + '</td>
	<td>' + Education + '</td>
  </tr>' JobList
	INTO #e3
	FROM #TEmail
	WHERE RowNo = 3

	SELECT a.paMainId, a.JobList + ISNULL(b.JobList, '') + ISNULL(c.JobList, '') + '
</table>' JobList
	INTO #e4
	FROM #e1 a
	LEFT JOIN #e2 b on a.pamainid = b.pamainid
	LEFT JOIN #e3 c on a.pamainid = c.pamainid

	UPDATE a
	SET a.JobList = b.JobList
	FROM paYourFoodEmail a, #e4 b
	WHERE a.paMainId = b.paMainId

	DROP TABLE #TEmail
END
GO

/****** Object:  StoredProcedure [dbo].[SpQlrcNewsNearSave]    Script Date: 2018/12/13 19:13:22 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SpQlrcNewsNearSave]
AS
SET NOCOUNT ON
BEGIN
	SELECT VersionId, id, Title, ROW_NUMBER() OVER(PARTITION BY VersionId ORDER BY Id) RowNo
	INTO #t
	FROM QlrcNews WITH(NOLOCK)
	WHERE NewsType = 2 
	AND Id > 1

	CREATE TABLE #Tmp(VersionId INT, Id INT, NearId INT, NearTitle NVARCHAR(60), RowNo INT, NearRowNo INT, PageType INT)

	INSERT INTO #Tmp
	SELECT a.VersionId, a.Id, b.ID, b.Title, a.RowNo, b.RowNo, 2
	FROM #t a, #t b
	WHERE a.VersionId = b.VersionId
	AND a.RowNo = b.RowNo + 1

	INSERT INTO #Tmp
	SELECT a.VersionId, a.Id, b.ID, b.Title, a.RowNo, b.RowNo, 1
	FROM #t a, #t b
	WHERE a.VersionId = b.VersionId
	AND a.RowNo = b.RowNo - 1

	SELECT * INTO #Tmp1 FROM #Tmp

	DELETE a
	FROM #Tmp1 a, ShortDb..QlrcNewsNear b
	WHERE a.Id = b.Id
	AND a.NearId = b.NearId
	AND a.PageType = b.PageType

	SELECT * INTO #News FROM #Tmp WHERE ID IN(SELECT ID FROM #Tmp1)

	DELETE FROM ShortDb..QlrcNewsNear WHERE Id IN(SELECT ID FROM #News)

	INSERT INTO ShortDb..QlrcNewsNear
	SELECT Id, PageType, NearId, NearTitle FROM #News
END
GO

/****** Object:  StoredProcedure [dbo].[spReceiveOrder]    Script Date: 2018/12/13 19:13:22 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

create proc [dbo].[spReceiveOrder]
(
	@caOrderID INT,
	@ReceiveMan INT
)
AS
SET NOCOUNT ON
BEGIN
	UPDATE caOrder SET ReceiveDate = GETDATE(), ReceiveMan = @receiveMan WHERE Id = @caOrderId
	SELECT ReceiveDate, REceiveMAn, * FROM caOrder WHERE Id = @caOrderId
END
GO

/****** Object:  StoredProcedure [dbo].[spReCheckVipMember]    Script Date: 2018/12/13 19:13:22 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[spReCheckVipMember]
AS
BEGIN
	DECLARE @ID AS INT
	DECLARE c CURSOR FOR
	SELECT id FROM cpMain WITH(NOLOCK)
	WHERE MemberType = 2
	AND Id IN(
		SELECT cpMainId FROM caORder WITH(NOLOCK)
		WHERE OpenDate > ''
		AND OrderType = 8
		AND IsDeleted = 0
		AND BeginDate < GETDATE()
		AND EndDate > GETDATE()
		)
	FOR READ ONLY

	OPEN c 
	FETCH c INTO @ID

	WHILE @@fetch_status >= 0
	BEGIN
		EXEC spRedifinePrivilage @ID
		FETCH NEXT FROM c INTO @ID
	END
	CLOSE c
	DEALLOCATE c
END













GO

/****** Object:  StoredProcedure [dbo].[spRedifinePrivilage]    Script Date: 2018/12/13 19:13:22 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--######################################################3
--cpMain权限检查
--1、JobNumber不超标
--2、Count(Valid caMain) 不超标
--3、修改MemberType， MaxJobNumber，MaxUserNumber
--说明：
--资料不完整	MemberType=0	职位数=0	用户数=1
--未认证会员	MemberType=1	职位数=5， 用户数=1
--普通会员		MemberType=2	职位数=10， 用户数=1
--贵宾会员		MemberType=3	职位数=SUM(caOrder.JobNumber)， 用户数=SUM(caOrder.UserNumber)
--无限制会员	MemberType=10	职位数=cpMain.MaxJobNumber， 用户数=cpMain.MaxUserNumber
--储值会员		MemberType=11	职位数=cpMain.MaxJobNumber， 用户数=cpMain.MaxUserNumber
--######################################################3
CREATE PROCEDURE [dbo].[spRedifinePrivilage]
(
	@cpMainID INT
)
AS
BEGIN TRY
	SET NOCOUNT ON;
	DECLARE @MemberType AS INT, @MaxJobNumber AS INT, @MaxUserNumber AS INT, @ExceedNumber AS INT, @JobNumber AS INT
	DECLARE @I AS INT, @ActiveUserNumber AS INT, @DailyGiftQuota AS INT
	
	SET @MemberType = dbo.GetMemberTypeWithRealName(@cpMainID)

	IF @MemberType = 0				--资料不完整	MemberType=0	职位数=0	用户数=1
	BEGIN
		SET @MaxJobNumber = 0
		SET @MaxUserNumber = 1
		SET @DailyGiftQuota = 0
	END
	ELSE IF @MemberType = 1			--未认证会员	MemberType=1	职位数=1， 用户数=1
	BEGIN
		SET @MaxJobNumber = 3
		SET @MaxUserNumber = 1
		SET @DailyGiftQuota = 0
	END
	ELSE IF @MemberType = 2			--普通会员	realname = 1	MemberType=2	职位数=3， 用户数=1
	BEGIN
		SET @MaxJobNumber = 5
		SET @MaxUserNumber = 1
		SET @DailyGiftQuota = 2
	END
	ELSE IF @MemberType = 21			--普通会员		MemberType=2	职位数=3， 用户数=1
	BEGIN
		SET @MaxJobNumber = 10
		SET @MaxUserNumber = 1
		SET @DailyGiftQuota = 4
	END
	ELSE IF @MemberType = 3			--贵宾会员		MemberType=3	职位数=SUM(caOrder.JobNumber)， 用户数=SUM(caOrder.UserNumber)
	BEGIN
		SET @MaxJobNumber = dbo.VipJobNumber(@cpMainID)
		SET @MaxUserNumber = dbo.VipUserNumber(@cpMainID)
		IF EXISTS (SELECT 'x' FROM caOrder WITH(NOLOCK) 
			WHERE cpMainId = @cpMainID AND OrderType = 8 
			AND ID < 412870
			AND GETDATE() BETWEEN BeginDate AND EndDate)
			SET @DailyGiftQuota = 5
		ELSE
			SET @DailyGiftQuota = 2
	END
	ELSE IF @MemberType = 31			--贵宾会员		MemberType=3	职位数=SUM(caOrder.JobNumber)， 用户数=SUM(caOrder.UserNumber)
	BEGIN
		SET @MaxJobNumber = dbo.VipJobNumber(@cpMainID)
		SET @MaxUserNumber = dbo.VipUserNumber(@cpMainID)
		IF EXISTS (SELECT 'x' FROM caOrder WITH(NOLOCK) 
			WHERE cpMainId = @cpMainID AND OrderType = 8 
			AND ID < 412870
			AND GETDATE() BETWEEN BeginDate AND EndDate)
			SET @DailyGiftQuota = 5
		ELSE
			SET @DailyGiftQuota = 4
	END
	/*ELSE		--无限制、储值会员	MemberType=10	职位数=cpMain.MaxJobNumber， 用户数=cpMain.MaxUserNumber
	BEGIN
		SELECT @MaxJobNumber = MaxJobNumber, @MaxUserNumber = MaxUserNumber
		FROM cpMain WITH(NOLOCK)
		WHERE ID = @cpMainID
		SET @DailyGiftQuota = 0
		IF @MaxJobNumber < 15
			SELECT @MaxJobNumber = 15
	END
	*/
	----如果活动的的用户数大于最大用户数量，则自动停止超出的用户，停止建立时间最晚的非管理员用户
	WHILE (SELECT COUNT(1) FROM caMain WITH(NOLOCK)
			WHERE cpMainID = @cpMainID AND IsDelete = 0 AND IsPause = 0) > @MaxUserNumber
	BEGIN
		UPDATE caMain SET IsPause = 1		--一个一个的停止
		WHERE ID IN(SELECT TOP 1 ID
			FROM caMain WITH(NOLOCK)
			WHERE cpMainID = @cpMainID
			AND IsPause = 0
			AND IsDelete = 0
			AND AccountType = 2
			ORDER BY ID DESC)
	END

	UPDATE Job SET Valid = 0, IssueEnd = DATEADD(MINUTE, -1, GETDATE())
	WHERE cpMainID = @cpMainID
	AND caMainID IN(SELECT Id FROM caMain WITH(NOLOCK) WHERE IsDelete = 1 OR IsPause =1 AND cpMainID = @cpMainID)
	AND (Valid = 1 OR IssueEnd > GETDATE())
	
	SELECT @ActiveUserNumber = COUNT(1)
	FROM caMain WITH(NOLOCK)
	WHERE cpMainID = @cpMainID AND IsDelete = 0 AND IsPause = 0

	----如果已经发布的职位数大于最大职位数量，则自动停止超出的职位数，停止发布时间最早的
	DECLARE @ID AS INT
	DECLARE @IssueEnd AS SMALLDATETIME
	DECLARE @IssueDate AS SMALLDATETIME

	WHILE (SELECT COUNT(1)
			FROM Job WITH(NOLOCK)
			WHERE cpMainID = @cpMainID AND IssueEnd > GETDATE() AND IsDelete = 0) > @MaxJobNumber
	BEGIN
		--一个一个的停止
		SELECT TOP 1 @ID = ID, @IssueDate = IssueDate, @IssueEnd = IssueEnd FROM Job WITH(NOLOCK)
		WHERE cpMainID = @cpMainID
		AND IssueEnd > GETDATE()
		AND IsDelete = 0
		ORDER BY IssueDate, ID

		UPDATE Job SET IssueDate = CASE WHEN IssueDate > DATEADD(MINUTE, -1, GETDATE()) THEN DATEADD(MINUTE, -1, GETDATE()) ELSE IssueDate END, 
			IssueEnd = DATEADD(MINUTE, -1, GETDATE()), Valid = 0
		WHERE ID = @ID
	END

	SELECT @JobNumber = COUNT(1)
	FROM Job WITH(NOLOCK)
	WHERE cpMainID = @cpMainID AND Valid = 1

	IF @MemberType = 21
		SET @MemberType = 2
	IF @MemberType = 31
		SET @MemberType = 3

	UPDATE cpMain
	SET MemberType = @MemberType, 
		MaxUserNumber = @MaxUserNumber,
		MaxJobNumber = @MaxJobNumber,
		JobNumber = @JobNumber,
		DailyGiftQuota = @DailyGiftQuota
	WHERE ID = @cpMainID
	AND (MemberType <> @MemberType
		OR MaxUserNumber <> @MaxUserNumber
		OR MaxJobNumber <> @MaxJobNumber
		OR JobNumber <> @JobNumber
	)

	UPDATE cpMainPublish
	SET MemberType = @MemberType
	WHERE ID = @cpMainID
	AND MemberType <> @MemberType
END TRY
BEGIN CATCH
END CATCH
GO

/****** Object:  StoredProcedure [dbo].[spRedifinePrivilage2]    Script Date: 2018/12/13 19:13:23 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[spRedifinePrivilage2]
(
	@cpMainID INT
)
AS
return
BEGIN TRY
	SET NOCOUNT ON;
	DECLARE @MemberType AS INT, @MaxJobNumber AS INT, @MaxUserNumber AS INT, @ExceedNumber AS INT, @JobNumber AS INT
	DECLARE @I AS INT, @ActiveUserNumber AS INT, @DailyGiftQuota AS INT
	
	SET @MemberType = dbo.MemberType(@cpMainID)

	IF @MemberType = 0				--资料不完整	MemberType=0	职位数=0	用户数=1
	BEGIN
		SET @MaxJobNumber = 0
		SET @MaxUserNumber = 1
		SET @DailyGiftQuota = 0
	END
	ELSE IF @MemberType = 1			--未认证会员	MemberType=1	职位数=1， 用户数=1
	BEGIN
		SET @MaxJobNumber = 5
		SET @MaxUserNumber = 1
		SET @DailyGiftQuota = 0
	END
	ELSE IF @MemberType = 2			--普通会员		MemberType=2	职位数=3， 用户数=1
	BEGIN
		SET @MaxJobNumber = 10
		SET @MaxUserNumber = 1
		SET @DailyGiftQuota = 2
	END
	ELSE IF @MemberType = 3			--贵宾会员		MemberType=3	职位数=SUM(caOrder.JobNumber)， 用户数=SUM(caOrder.UserNumber)
	BEGIN
		SET @MaxJobNumber = dbo.VipJobNumber(@cpMainID)
		SET @MaxUserNumber = dbo.VipUserNumber(@cpMainID)
		IF EXISTS (SELECT 'x' FROM caOrder WITH(NOLOCK) 
			WHERE cpMainId = @cpMainID AND OrderType = 8 
			AND ID < 412870
			AND GETDATE() BETWEEN BeginDate AND EndDate)
			SET @DailyGiftQuota = 5
		ELSE
			SET @DailyGiftQuota = 2
	END
	/*ELSE		--无限制、储值会员	MemberType=10	职位数=cpMain.MaxJobNumber， 用户数=cpMain.MaxUserNumber
	BEGIN
		SELECT @MaxJobNumber = MaxJobNumber, @MaxUserNumber = MaxUserNumber
		FROM cpMain WITH(NOLOCK)
		WHERE ID = @cpMainID
		SET @DailyGiftQuota = 0
		IF @MaxJobNumber < 15
			SELECT @MaxJobNumber = 15
	END
	*/
	----如果活动的的用户数大于最大用户数量，则自动停止超出的用户，停止建立时间最晚的非管理员用户
	WHILE (SELECT COUNT(1)	FROM caMain WITH(NOLOCK)
			WHERE cpMainID = @cpMainID AND IsDelete = 0 AND IsPause = 0) > @MaxUserNumber
	BEGIN
		UPDATE caMain SET IsPause = 1		--一个一个的停止
		WHERE ID IN(SELECT TOP 1 ID
			FROM caMain WITH(NOLOCK)
			WHERE cpMainID = @cpMainID
			AND IsPause = 0
			AND IsDelete = 0
			AND AccountType = 2
			ORDER BY ID DESC)

	END
	UPDATE Job SET Valid = 0, IssueEnd = DATEADD(MINUTE, -1, GETDATE())
	WHERE cpMainID = @cpMainID
	AND caMainID IN(SELECT Id FROM caMain WITH(NOLOCK) WHERE IsDelete = 1 OR IsPause =1 AND cpMainID = @cpMainID)
	
	SELECT @ActiveUserNumber = COUNT(1)
	FROM caMain WITH(NOLOCK)
	WHERE cpMainID = @cpMainID AND IsDelete = 0 AND IsPause = 0

	----如果已经发布的职位数大于最大职位数量，则自动停止超出的职位数，停止发布时间最早的
	DECLARE @ID AS INT
	DECLARE @IssueEnd AS SMALLDATETIME
	DECLARE @IssueDate AS SMALLDATETIME

	WHILE (SELECT COUNT(1)
			FROM Job WITH(NOLOCK)
			WHERE cpMainID = @cpMainID AND IssueEnd > GETDATE() AND IsDelete = 0) > @MaxJobNumber
	BEGIN
		--一个一个的停止
		SELECT TOP 1 @ID = ID, @IssueDate = IssueDate, @IssueEnd = IssueEnd FROM Job WITH(NOLOCK)
		WHERE cpMainID = @cpMainID
		AND IssueEnd > GETDATE()
		AND IsDelete = 0
		ORDER BY IssueDate, ID

		UPDATE Job SET IssueDate = CASE WHEN IssueDate > DATEADD(MINUTE, -1, GETDATE()) THEN DATEADD(MINUTE, -1, GETDATE()) ELSE IssueDate END, 
			IssueEnd = DATEADD(MINUTE, -1, GETDATE()), Valid = 0
		WHERE ID = @ID
	END

	SELECT @JobNumber = COUNT(1)
	FROM Job WITH(NOLOCK)
	WHERE cpMainID = @cpMainID AND Valid = 1

	UPDATE cpMain
	SET MemberType = @MemberType, 
		MaxUserNumber = @MaxUserNumber,
		MaxJobNumber = @MaxJobNumber,
		JobNumber = @JobNumber,
		DailyGiftQuota = @DailyGiftQuota
	WHERE ID = @cpMainID
	AND (MemberType <> @MemberType
		OR MaxUserNumber <> @MaxUserNumber
		OR MaxJobNumber <> @MaxJobNumber
		OR JobNumber <> @JobNumber
	)

	UPDATE cpMainPublish
	SET MemberType = @MemberType
	WHERE ID = @cpMainID
	AND MemberType <> @MemberType
END TRY
BEGIN CATCH
END CATCH













GO

/****** Object:  StoredProcedure [dbo].[spRemoveBr]    Script Date: 2018/12/13 19:13:23 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[spRemoveBr]
(
	@Table VARCHAR(100),
	@Column VARCHAR(100)
)
AS
BEGIN
	DECLARE @sql AS VARCHAR(MAX)
	SELECT @Sql = 'UPDATE ' + @Table + ' SET ' + @Column + ' = dbo.Removebr(' + @Column +')
WHERE ' + @Column + ' LIKE ''%<br>%''
OR ' + @Column + ' LIKE ''%&nbsp;%'''
	EXEC(@Sql)
END













GO

/****** Object:  StoredProcedure [dbo].[spSalaryByCountSelect]    Script Date: 2018/12/13 19:13:24 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[spSalaryByCountSelect]
AS
SET NOCOUNT ON
BEGIN
	CREATE TABLE #s(Id int, Salary INT)
	INSERT INTO #s SELECT 1, 750
	INSERT INTO #s SELECT 2, 1250
	INSERT INTO #s SELECT 3, 1750
	INSERT INTO #s SELECT 4, 2500
	INSERT INTO #s SELECT 5, 3500
	INSERT INTO #s SELECT 6, 4500
	INSERT INTO #s SELECT 7, 5500
	INSERT INTO #s SELECT 8, 7000
	INSERT INTO #s SELECT 9, 9000
	INSERT INTO #s SELECT 10, 12500
	INSERT INTO #s SELECT 11, 17500
	INSERT INTO #s SELECT 12, 22500

	SELECT SPACE(60) Region, dcRegionId, dcSalaryID, 99999 Salary INTO #t FROM JobPublish WITH(NOLOCK) WHERE dcREgionId LIKE '32____'
	DELETE FROM #t WHERE dcSalaryId > 12
	UPDATE a SET a.Salary = b.Salary FROM #t a, #s b WHERE a.dcSalaryId = b.ID
	UPDATE a SET a.Region = b.FullName FROM #t a, dcRegion b WHERE a.dcRegionId = b.ID
	SELECT Region, Avg(Salary) FROM #t GROUP BY Region ORDER BY Avg(Salary) DESC

END
GO

/****** Object:  StoredProcedure [dbo].[spSchMailPrev3Insert]    Script Date: 2018/12/13 19:13:24 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

/*
-- sean 2016-10-21
*/
CREATE PROCEDURE [dbo].[spSchMailPrev3Insert]
AS
SET NOCOUNT ON
BEGIN
	IF ISNULL((SELECT TOP 1 CONVERT(VARCHAR(8), AddDate, 112) FROM schMailPrev3), '') = CONVERT(VARCHAR(8), GETDATE(), 112)
		RETURN

	TRUNCATE TABLE schMailPrev3
	
	--需要推荐简历的职位
	CREATE TABLE #caSend(CaMainID INT)
	
	DECLARE @t AS TABLE(EMailSendFreq INT)
	DECLARE @num INT
	SET @Num = 0
	WHILE @Num < 128
	BEGIN
		SET @Num = @Num + 1
		IF SUBSTRING(RIGHT('0000000' + dbo.Int2Bin(@Num), 7), DATEPART(WEEKDAY, GETDATE() - 1), 1) = '1'
			INSERT INTO @t SELECT @Num
	END
	
	INSERT INTO #caSend
	SELECT DISTINCT caMainID 
	FROM Job WITH(NOLOCK)
	WHERE EMailSendFreq IN(SELECT EMailSendFreq FROM @t)
	AND valid = 1
	AND cpMainId IN(SELECT ID FROM cpMain WHERE IsLimitLogin < 9)
	
	INSERT INTO schMailPrev3
	SELECT 1,ISNULL(c.dcProvinceID,0),a.caMainID,ISNULL(b.Name,''),ISNULL(b.UserName,''),ISNULL(b.cpMainID,0),ISNULL(b.Name,'')+'您好，您发布的职位推荐简历',0,CASE LEN(c.dcsubsiteid) WHEN 2 THEN '' ELSE ISNULL(d.eMailsite,'') END,ISNULL(b.EMail,''),ISNULL(d.SubsiteName,''),NULL,0,GETDATE(),NULL,NULL,NULL,c.dcRegionID,NULL,NULL
	FROM #caSend a
	LEFT JOIN caMain b WITH(NOLOCK) ON b.id = a.caMainID
	LEFT JOIN cpMain c WITH(NOLOCK) ON c.id = b.cpMainID
	LEFT JOIN dcSubsite d WITH(NOLOCK) ON d.id = c.dcSubsiteID
	
	DELETE FROM schMailPrev3 WHERE EMail LIKE '%qq.com'

	SELECT ResumeId cvMainId, paMainId, SecondId, LastLoginDate, '
  <tr>
	<td>' + ISNULL( Name, ' ') + '[<a href="http://##SiteUrl##/Company/resume/cvview?id=##ResumeNo##" target="_blank">##ResumeNo##</a>]</td>
	<td>' + (CASE ISNULL( Sex, 0) WHEN 0 THEN '男' WHEN 1 THEN '女' END) + '</td>
	<td>' + CONVERT(VARCHAR, ISNULL( Age, 30)) + '</td>
	<td>' + ISNULL( JobType, ' ') + '</td>
	<td>' + ISNULL( AtPlaceDesc, ' ') + '</td>
  </tr>' MailText
	INTO #cvMail
	FROM caJobResumePre WITH(NOLOCK)
	WHERE ResumeId IN(SELECT MatchCvMainId FROM caJobCvMatch WITH(NOLOCK) WHERE PushDate IS NULL)
	AND AddDate > GETDATE() - 7

	--drop #JobMail
	CREATE TABLE #JobMail(caMainId INT, JobId INT, MailText NVARCHAR(MAX), JobName NVARCHAR(50), SecondId VARCHAR(12))
	CREATE TABLE #JobTemp(JobId INT, cvMainId INT, LastLoginDate DATETIME, JobName NVARCHAR(50), SecondId VARCHAR(12), cvText NVARCHAR(MAX), paMainId VARCHAR(10), cvSecondId VARCHAR(10), cpMainId VARCHAR(10), RegisterIp VARCHAR(39))
	CREATE TABLE #caMail(caMainId INT, MailBody NVARCHAR(MAX))

	INSERT INTO #JobTemp(JobId, cvMainId, LastLoginDate, cvText, paMainId, cvSecondId)
	SELECT a.JobId, b.cvMainId, b.LastLoginDate, b.MailText, b.paMainId, b.SecondId
	FROM caJobCvMatch a, #cvMail b
	WHERE a.MatchCvMainId = b.cvMainId	
	AND a.AddDate > GETDATE() - 7
	AND a.PushDate IS NULL

	DELETE #JobTemp WHERE JobId IN(SELECT Id FROM Job WHERE Valid = 0)
	DELETE #JobTemp WHERE JobId IN(SELECT Id FROM Job WHERE caMainId IN(SELECT ID FROM CaMain WHERE EMail LIKE '%qq.com'))
	UPDATE a SET a.cpMainId = b.cpMainId FROM #JobTemp a, Job b WHERE a.JobId = b.Id
	UPDATE a SET a.RegisterIp = b.RegisterIp FROM #JobTemp a, cpMain b WHERE a.cpMainId = b.Id
	UPDATE #JobTemp SET cvText = REPLACE(cvText, '##ResumeNo##', LOWER(cvSecondId + SUBSTRING(SYS.Fn_VarbinToHexStr(HASHBYTES('SHA1', paMainId + '-' + cpMainId + '#' + RegisterIp + '*')), 13, 10)))

	INSERT #JobMail(JobId, MailText)
	SELECT a.JobId, MailText = STUFF((SELECT '<aa>' + b.cvText + '<aa>' FROM #JobTemp b WHERE a.JobId = b.JobId ORDER BY b.LastLoginDate DESC FOR XML PATH('')), 1, 0, '')
	FROM #JobTemp a
	GROUP BY a.JobId

	--UPDATE #JobMail SET MailText = REPLACE(REPLACE(REPLACE(MailText, '&lt;aa&gt;', ''), '&lt;', '<'), '&gt;', '')
	UPDATE a SET a.caMainId = b.caMainId, a.JobName = b.Name, a.SecondId = b.SecondId FROM #JobMail a, Job b WHERE a.JobId = b.Id
	UPDATE #JobMail SET MailText = '
  <tr>
	<td colspan = "5" style="FONT-WEIGHT: bold; background-color:#ff6;"><a href="http://##SiteUrl##/personal/jb' + SecondID + '.html" target="_blank">' + JobName + '</a></td>
  </tr>' + MailText

	INSERT INTO #caMail
	SELECT a.caMainId, MailBody = STUFF((SELECT '<aa>' + b.MailText + '<aa>' FROM #JobMail b WHERE a.caMainId = b.caMainId FOR XML PATH('')), 1, 0, '')
	FROM #JobMail a
	GROUP BY a.caMainId

	UPDATE #caMail SET MailBody = REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(MailBody, '&amp;', '&'), '&lt;aa&gt;', ''), '&lt;', '<'), '&gt;', '>'), '&#x0D;', '')
	UPDATE #caMail SET MailBody = '以下是贵单位招聘职位推荐的部分简历。<br>
<table style="font-size:12px">
  <tr style="FONT-WEIGHT: bold; background-color:#f7b666;">
	<td>求职者</td>
	<td>性别</td>
	<td>年龄</td>
	<td>求职意向</td>
	<td>所在地</td>
  </tr>' + MailBody + '
</table>
详细情况请登录网站后使用“简历搜索”-->“<a href="http://##SiteUrl##/Company/cvSearch/Search" target="_blank">搜索简历</a>”-->点击“更多搜索条件”-->输入“简历编号”搜索。'

 	UPDATE a SET a.MailBody = b.MailBody FROM SchMailPrev3 a, #caMail b
	WHERE a.AccountId = b.caMainId

	--UPDATE schMailPrev3 SET MailBody = '<br>&nbsp; 符合您招聘职位的推荐简历已经全部发送，暂时没有新的简历出现。您可以登录网站后使用“职位管理”-->“发布中的职位”，修改给你推荐的频率。<br>&nbsp; ' 
	--WHERE MailBody IS NULL
	DELETE schMailPrev3 WHERE MailBody IS NULL
 
	UPDATE a
	SET a.MailBody = REPLACE(a.MailBody, '##SiteUrl##', 'www.' + b.ProvinceDomain)
	FROM schMailPrev3 a, dcProvince b
	WHERE a.dcProvinceId = b.Id

	UPDATE caJobCvMatch
	SET PushDate = GETDATE()
	WHERE JobId IN(SELECT Id FROM Job WHERE caMainId IN(SELECT caMainId FROM #caSend))
	AND PushDate IS NULL

	DROP TABLE #cvMail
	DROP TABLE #JobMail
	DROP TABLE #caMail
	DROP TABLE #JobTemp
	DROP TABLE #caSend
 END

GO

/****** Object:  StoredProcedure [dbo].[spShowForeignKeys]    Script Date: 2018/12/13 19:13:25 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[spShowForeignKeys]
(
	@Table VARCHAR(50)
)
AS
BEGIN
	IF dbo.TrimNull(@Table) IS NOT NULL
		SELECT DISTINCT	b.Name AS Key_Name, a.Name AS Name, d.Name AS f_Name, c.rKey
		FROM SysObjects a JOIN SysObjects b ON a.Id = b.Parent_Obj 
		JOIN SysForeignKeys c ON b.Id = c.constId 
		JOIN SysObjects d ON c.rKeyId = d.Id 
		JOIN SysIndexKeys e ON d.Id = e.Id 
		JOIN SysColumns f ON a.Id = f.Id
		AND e.colId = f.colId 
		WHERE b.xtype = 'F'
		AND d.Name = @Table
		ORDER BY Key_Name
	ELSE
		SELECT DISTINCT	b.Name AS Key_Name, a.Name AS Name, d.Name AS f_Name, c.rKey
		FROM SysObjects a JOIN SysObjects b ON a.Id = b.Parent_Obj 
		JOIN SysForeignKeys c ON b.Id = c.constId 
		JOIN SysObjects d ON c.rKeyId = d.Id 
		JOIN SysIndexKeys e ON d.Id = e.Id 
		JOIN SysColumns f ON a.Id = f.Id
		AND e.colId = f.colId 
		WHERE b.xtype = 'F'
		ORDER By f_Name
END













GO

/****** Object:  StoredProcedure [dbo].[spShowTableStruct]    Script Date: 2018/12/13 19:13:25 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[spShowTableStruct]
(
	@Table AS VARCHAR(50),
	@Column AS VARCHAR(50)
)
AS
BEGIN
	DECLARE @SQL AS VARCHAR(1000)
	SET @Table = dbo.TrimNull(@Table)
	SET @Column = dbo.TrimNull(@Column)

	SET @SQL = '
		SELECT SysObjects.Name AS TABLEName, 
			SysColumns.Name as ColName, 
			SysTypes.Name VType, 
			SysColumns.LENGTH, 
			SysColumns.XPREC, 
			SysColumns.XSCALE, 
			IsNullable, 
			cDefault
		FROM SysColumns, SysObjects, SysTypes 
		WHERE  SysColumns.Id = SysObjects.Id
		AND SysColumns.xType = SysTypes.xType
		AND SysObjects.Type = ''U'''

	IF @Table IS NOT NULL
		SET @SQL = @SQL + '
		AND SysObjects.Name = ''' + @Table + ''''

	IF @Column IS NOT NULL
		SET @SQL = @SQL + '
		AND SysColumns.Name = ''' + @Column + ''''

	SET @SQL = @SQL + '
		ORDER BY SysObjects.Name, SysColumns.Name'

	EXEC(@SQL)
END













GO

/****** Object:  StoredProcedure [dbo].[spSmsEmailCountInsert]    Script Date: 2018/12/13 19:13:25 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[spSmsEmailCountInsert]
AS
BEGIN
	DECLARE @d AS DATETIME
	SELECT @D = CONVERT(VARCHAR(10), GETDATE(), 120)

	INSERT SmsEmailCount
	SELECT CONVERT(VARCHAR(8), AddDate, 112), 1, MsgType, COUNT(*), SendStatus
	FROM SmsMessageLog 
	WHERE AddDate >= @d - 1 AND AddDate < @d
	GROUP BY CONVERT(VARCHAR(8), AddDate, 112), MsgType, SendStatus

	INSERT SmsEmailCount
	SELECT CONVERT(VARCHAR(8), AddDate, 112), 2, msEmailTypeId, COUNT(*), Status
	FROM msEmailSend
	WHERE AddDate >= @d - 1 AND AddDate < @d
	GROUP BY CONVERT(VARCHAR(8), AddDate, 112), msEmailTypeId, Status

	--select * from SmsEmailCount
	--sp_help SmsEmailCount
	--select * from #t where sendstatus>255
END













GO

/****** Object:  StoredProcedure [dbo].[spSmsMessageLogByReceiveUpdate]    Script Date: 2018/12/13 19:13:25 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[spSmsMessageLogByReceiveUpdate]
AS
BEGIN
	SELECT * INTO #1 FROM SmsMessageLog WHERE SmsType=2 AND SendMan = 0 AND Msg = 'n'
	IF (SELECT COUNT(*) FROM #1) > 0
	BEGIN
		INSERT INTO MarketDb..NoSendSms SELECT DISTINCT Mobile, GETDATE() FROM #1 WHERE Mobile NOT IN(SELECT Mobile FROM MarketDb..NoSendSms)
		UPDATE SmsMessageLog SET SendMan = 2 WHERE Id IN(SELECT Id FROM #1)
	END
	SELECT Id, Mobile, Msg, ManagerUserId, paMainId, caMainId, SendMan, MsgType
	INTO #2
	FROM SmsMessageLog WHERE SmsType = 2 AND SendMan = 0
	IF (SELECT COUNT(*) FROM #1) > 0
	BEGIN
		UPDATE #2 SET SendMan = ISNULL((SELECT TOP 1 SendMan FROM SmsMessageLog a WHERE a.Mobile = #2.Mobile AND SendMan > 2 ORDER BY ID DESC), 0)
		UPDATE #2 SET SendMan = ISNULL((SELECT TOP 1 a.ConsultantId FROM cpMain a WITH(NOLOCK), caMain b WITH(NOLOCK)
			WHERE a.Id = b.cpMainId AND b.Mobile = #2.Mobile AND a.ConsultantId  > 0 ORDER BY a.LastLoginDate DESC), 0)
		WHERE SendMan = 0

		UPDATE #2 SET SendMan = 180 WHERE SendMan = 0

		UPDATE a
		SET a.SendMan = b.SendMan
		FROM SmsMessageLog a, #2 b
		WHERE a.Id = b.Id

		INSERT INTO RtxNotifyLog(Receiver, RtxTitle, RtxMessage, SendType, DelayTime, ShowType)
		SELECT DISTINCT SendMan, '收到短信', 
			'您有新的短信，请及时处理！' + CASE SendMan WHEN 180 THEn '' ELSE '内容：' + Msg END,
			1, 0, 0
		From #2
	END
END
GO

/****** Object:  StoredProcedure [dbo].[spSmsMessageLogSelect]    Script Date: 2018/12/13 19:13:25 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[spSmsMessageLogSelect]
AS
BEGIN
	DECLARE @Day7 AS DATETIME, @Day1 AS DATETIME
	SET @Day7 = CONVERT(DATETIME, CONVERT(VARCHAR(10), GETDATE() - 7, 120))
	SET @Day1 = CONVERT(DATETIME, CONVERT(VARCHAR(10), GETDATE() - 1, 120))
	 

	DECLARE @t AS TABLE(
		ID int,
		SendMan smallint,
		ManagerUserId smallint,
		paMainId int,
		caMainId int,
		Mobile varchar(20),
		Msg nvarchar(210),
		IsCat bit,
		AddDate smalldatetime,
		PortNo tinyint,
		SendDate datetime,
		SendStatus bit,
		SmsType tinyint,
		MsgType tinyint,
		IsDelete BIT
	)

	DECLARE @c AS TABLE(
		caMainId INT,
		MsgType tinyint,
		AddDate DATETIME,
		Cnt INT
		)

	INSERT INTO @t
	SELECT TOP 10 *, 0 FROM SmsMessageLog WITH(NOLOCK)
		WHERE SendDate IS NULL 
		AND IsCat = 0
		AND SmsType = 1
		AND AddDate > @Day7
		ORDER BY AddDate

	INSERT INTO @c
	SELECT caMainID, MsgType, Max(AddDate), COUNT(*)
	FROM SmsMessageLog WITH(NOLOCK)
	WHERE AddDate > @Day7
	AND SmsType = 1
	AND ID NOT IN(SELECT ID FROM @t)
	AND caMainID IN(SELECT caMainId FROM @t)
	GROUP BY caMainID, MsgType

	UPDATE @t SET IsDelete = 1
	WHERE MsgType IN(1,3,5)
	AND caMainId IN(SELECT caMainId FROM @c WHERE MsgType IN(1,3,5) AND AddDate > @Day1)

	UPDATE @t SET IsDelete = 1
	WHERE MsgType IN(2,4,19)
	AND caMainId IN(SELECT caMainId FROM @c WHERE MsgType IN(2,4,19) AND AddDate > @Day1)

	UPDATE @t SET IsDelete = 1
	WHERE MsgType = 7
	AND caMainId IN(SELECT caMainId FROM @c WHERE MsgType = 7 AND AddDate > @Day1)

	UPDATE @t SET IsDelete = 1
	WHERE MsgType = 8
	AND caMainId IN(SELECT caMainId FROM @c WHERE MsgType = 8 AND AddDate > @Day1)

	UPDATE @t SET IsDelete = 1
	WHERE MsgType = 9
	AND caMainId IN(SELECT caMainId FROM @c WHERE MsgType = 9 AND AddDate > @Day1 AND Cnt > 2)

	UPDATE @t SET IsDelete = 1
	WHERE MsgType = 20
	AND caMainId IN(SELECT caMainId FROM @c WHERE MsgType = 20 AND AddDate > @Day1)

	UPDATE @t SET IsDelete = 1
	WHERE MsgType = 10
	AND caMainId IN(SELECT caMainId FROM @c WHERE MsgType = 9 AND AddDate > @Day1 AND Cnt > 2)

	UPDATE @t SET IsDelete = 1
	WHERE MsgType IN(12,13,14,15)
	AND caMainId IN(SELECT caMainId FROM @c)

	UPDATE @t SET IsDelete = 1
	WHERE MsgType = 11
	AND caMainId IN(SELECT caMainId FROM @c WHERE AddDate > @Day1)

	UPDATE SmsMessageLog SET SmsType = 3 WHERE ID IN(SELECT ID FROM @t WHERE IsDelete = 1)

	SELECT * FROM @t WHERE IsDelete = 0

	INSERT INTO ServiceRunLog(ServiceId, RunRows, RunId, RunStatus, RunMessage)
	SELECT 1, @@RowCount, 0, 1, '提取短信数据'
END













GO

/****** Object:  StoredProcedure [dbo].[spStartOrder]    Script Date: 2018/12/13 19:13:26 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[spStartOrder]
(
	@Id INT
)
AS
BEGIN
	DECLARE @M INT
	SELECT @m = DATEDIFF(Month, Begindate, Enddate) FROM caOrder WHERE Id = @Id
	UPDATE caOrder SET BeginDate = GETDATE(), EndDate = DATEADD(MONTH, @m, GETDATE()) WHERE Id = @Id
	UPDATE caOrder SET BeginDate = GETDATE(), EndDate = DATEADD(MONTH, @m, GETDATE()) WHERE MainOrderId = @Id
	SELECT @m, BeginDate, EndDate, * FROM caORder WHERE Id = @Id
End
GO

/****** Object:  StoredProcedure [dbo].[spTableByRowNumberSelect]    Script Date: 2018/12/13 19:13:26 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[spTableByRowNumberSelect]
AS
BEGIN
	SET NOCOUNT ON
	DECLARE @t as TABLE(Id INT IDENTITY(1, 1), dbId INT, tabName VARCHAR(50))
	INSERT INTO @t SELECT 3, 'BsCvVerifySnap'
	INSERT INTO @t SELECT 1, 'caCvRemark'
	INSERT INTO @t SELECT 1, 'caCvViewLog'
	INSERT INTO @t SELECT 1, 'CaOnline'
	INSERT INTO @t SELECT 1, 'cpIndustry'
	INSERT INTO @t SELECT 1, 'cpMainPublish'
	INSERT INTO @t SELECT 1, 'cvAppendixPublish'
	INSERT INTO @t SELECT 1, 'cvEducationPublish'
	INSERT INTO @t SELECT 1, 'cvExperiencePublish'
	INSERT INTO @t SELECT 1, 'cvIndustryPublish'
	INSERT INTO @t SELECT 1, 'cvInfo'
	INSERT INTO @t SELECT 1, 'cvJobPlacePublish'
	INSERT INTO @t SELECT 1, 'cvJobTypePublish'
	INSERT INTO @t SELECT 1, 'cvLanguagePublish'
	INSERT INTO @t SELECT 1, 'cvMainPublish'
	INSERT INTO @t SELECT 1, 'cvProjectPublish'
	INSERT INTO @t SELECT 1, 'cvTrainingPublish'
	INSERT INTO @t SELECT 1, 'dcCompanySize'
	INSERT INTO @t SELECT 1, 'dcEducation'
	INSERT INTO @t SELECT 1, 'dcIndustry'
	INSERT INTO @t SELECT 1, 'dcJobType'
	INSERT INTO @t SELECT 1, 'dcMapPlace'
	INSERT INTO @t SELECT 1, 'dcOthers'
	INSERT INTO @t SELECT 1, 'dcRegion'
	INSERT INTO @t SELECT 1, 'dcSalary'
	INSERT INTO @t SELECT 1, 'dcSubSite'
	INSERT INTO @t SELECT 1, 'Ip_Black'
	INSERT INTO @t SELECT 1, 'Ip_White'
	INSERT INTO @t SELECT 1, 'JobPublish'
	INSERT INTO @t SELECT 1, 'JobSimilar'
	INSERT INTO @t SELECT 1, 'PaAttention'
	INSERT INTO @t SELECT 1, 'paMainPublish'
	INSERT INTO @t SELECT 1, 'PaOnline'
	INSERT INTO @t SELECT 1, 'SearchJobTop'
	INSERT INTO @t SELECT 1, 'WxFans'
	INSERT INTO @t SELECT 2, 'CpBrandPublish'
	INSERT INTO @t SELECT 2, 'CpBrochurePublish'
	INSERT INTO @t SELECT 2, 'cpDeptPublish'
	INSERT INTO @t SELECT 2, 'CpImage'
	INSERT INTO @t SELECT 2, 'CpIndustry'
	INSERT INTO @t SELECT 2, 'CpMainPublish'
	INSERT INTO @t SELECT 2, 'CpOrder'
	INSERT INTO @t SELECT 2, 'CpPreach'
	INSERT INTO @t SELECT 2, 'DcCompanyKind'
	INSERT INTO @t SELECT 2, 'DcEducation'
	INSERT INTO @t SELECT 2, 'DcIndustry'
	INSERT INTO @t SELECT 2, 'DcMajor'
	INSERT INTO @t SELECT 2, 'DcRegion'
	INSERT INTO @t SELECT 2, 'JobMajor'
	INSERT INTO @t SELECT 2, 'JobMajorPublish'
	INSERT INTO @t SELECT 2, 'JobPublish'
	INSERT INTO @t SELECT 2, 'JobRegion'
	INSERT INTO @t SELECT 2, 'JobRegionPublish'
	INSERT INTO @t SELECT 2, 'JobRegionShot'

	DECLARE @r AS TABLE(
		[NAMEINFO] [varchar](50) NULL,
		[ROWSINFO] [int] NULL,
		[RESERVED] [varchar](20) NULL,
		[DATAINFO] [varchar](20) NULL,
		[INDEX_SIZE] [varchar](20) NULL,
		[UNUSED] [varchar](20) NULL,
		[AddDate] [smalldatetime] NULL
	)
	CREATE TABLE #t(id INT IDENTITY(1, 1), dbId INT, tabName VARCHAR(50), rowNum int)
	DECLARE @Id INT, @dbId INT, @tabName VARCHAR(50)
	SET @Id = 0
	WHILE EXISTS(SELECT 'x' FROM @t WHERE Id > @Id)
	BEGIN
		SELECT TOP 1 @Id = Id, @dbId = dbId, @tabName = tabName FROM @t WHERE Id > @Id ORDER BY Id
		IF @dbId = 1
			INSERT INTO @r(NAMEINFO, ROWSINFO, RESERVED, DATAINFO, INDEX_SIZE, UNUSED)
			EXEC SP_SPACEUSED @tabName
		IF @dbId = 2
			INSERT INTO @r(NAMEINFO, ROWSINFO, RESERVED, DATAINFO, INDEX_SIZE, UNUSED)
			EXEC WuTongGuoDb..SP_SPACEUSED @tabName
		IF @dbId = 3
			INSERT INTO @r(NAMEINFO, ROWSINFO, RESERVED, DATAINFO, INDEX_SIZE, UNUSED)
			EXEC ShortDb..SP_SPACEUSED @tabName
		INSERT INTO #t SELECT @dbId, @tabName, ROWSINFO FROM @r
		DELETE FROM @r
	END

	SELECT * FROM #t
END
GO

/****** Object:  StoredProcedure [dbo].[spTableSpaceInfoInsert]    Script Date: 2018/12/13 19:13:26 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[spTableSpaceInfoInsert]
AS
BEGIN
	DECLARE MYCURSOR CURSOR FOR
	SELECT NAME FROM SYSOBJECTS WHERE XTYPE='U'
	OPEN MYCURSOR

	DECLARE @NAME  VARCHAR(100)

	FETCH NEXT FROM MYCURSOR INTO @NAME
	WHILE(@@FETCH_STATUS =0)
	BEGIN
		INSERT INTO TABLESPACEINFO(NAMEINFO, ROWSINFO, RESERVED, DATAINFO, INDEX_SIZE, UNUSED)
		EXEC SP_SPACEUSED @NAME  
		FETCH NEXT FROM MYCURSOR INTO @NAME
	END

	CLOSE MYCURSOR
	DEALLOCATE MYCURSOR
END
 













GO

/****** Object:  StoredProcedure [dbo].[spTmpCheckFileByCanDeleteUpdate]    Script Date: 2018/12/13 19:13:27 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

/*
1、照片；2、证书；3、word附件；4处理的照片；10、营业执照；11、logo；12、形象图；
20：order.RemittanceFile；21：Order.ContractFile；22：FaxFile
40:adverproject;
51、OaDb..LeaveAttchment；52：文档管理
*/
CREATE PROCEDURE [dbo].[spTmpCheckFileByCanDeleteUpdate]
AS
BEGIN
	declare @i int
	set @i = 0
	WHILE @I < 14673225
	BEGIN
		update tmpcheckfile set filetype=0, fileid=999 where id BETWEEN @i AND @i + 30000
		set @i = @i + 30000
	END

	CREATE TABLE #t(Id INT, FileName VARCHAR(200))	
	--UPDATE tmpCheckFile SET FileType = 0
	--delete from tmpcheckfile where fullname like 'D:\hosting\down.51rc.com\imagefolder\adimage\%'
	--100、照片；
	UPDATE tmpCheckFile SET FileType = 1
	WHERE fullName LIKE 'D:\hosting\down.51rc.com\imagefolder\photo\%\photo\%'

	UPDATE tmpCheckFile SET FileId = 1 WHERE FileType = 1 AND FileName IN(SELECT photo FROM paPhoto WHERE photo > '')
	UPDATE tmpCheckFile SET FileId = 1 WHERE FileType = 1 AND FileName IN(SELECT photoProcessed FROM paPhoto WHERE photoProcessed > '')

	--4处理的照片；
	UPDATE tmpCheckFile SET FileType = 4
	WHERE fullName LIKE 'D:\hosting\down.51rc.com\imagefolder\photo\%\processed\%'

	UPDATE tmpCheckFile SET FileId = 1 WHERE FileType = 4 AND FileName IN(SELECT photo FROM paPhoto WHERE photo > '')
	UPDATE tmpCheckFile SET FileId = 1 WHERE FileType = 4 AND FileName IN(SELECT photoProcessed FROM paPhoto WHERE photoProcessed > '')

	--2、证书
	--UPDATE tmpCheckFile SET FileType = 2 WHERE fullName LIKE 'D:\hosting\down.51rc.com\imagefolder\appendix\L%'
	--UPDATE tmpCheckFile SET FileId = 1 WHERE FileType = 2 AND FileName IN(SELECT FileName FROM cvAppendix WHERE FileName > '')

	--3、word附件；
	UPDATE tmpCheckFile SET FileType = 3 WHERE fullName LIKE 'D:\hosting\down.51rc.com\imagefolder\attachment\L%'
	UPDATE tmpCheckFile SET FileId = 1 WHERE FileType = 3 AND FileName IN(SELECT Attachment FROM cvMain WHERE Attachment > '')

	--10、营业执照；
	UPDATE tmpCheckFile SET FileType = 10 WHERE fullName LIKE 'D:\hosting\down.51rc.com\imagefolder\Licence\%'

	UPDATE tmpCheckFile SET FileId = 1 WHERE FileType = 10 AND FileName IN(SELECT ImgFile FROM cpLicence)
	UPDATE tmpCheckFile SET FileId = 1 WHERE FileType = 10 AND FileId= 0 AND FileName IN(SELECT FileNameOld FROM cpLicenceChangeLog)
	UPDATE tmpCheckFile SET FileId = 1 WHERE FileType = 10 AND FileId= 0 AND FileName IN(SELECT FileNameNew FROM cpLicenceChangeLog)
	UPDATE tmpCheckFile SET FileId = 1 WHERE FileType = 10 AND FileId= 0 AND FileName IN(SELECT OldFileName FROM cpLicenceLog)

	--11、logo；
	UPDATE tmpCheckFile SET FileType = 11 WHERE fullName LIKE 'D:\hosting\down.51rc.com\imagefolder\Logo\%'	
	--12、形象图；
	UPDATE tmpCheckFile SET FileType = 12 WHERE fullName LIKE 'D:\hosting\down.51rc.com\imagefolder\visual\%'	
	UPDATE tmpCheckFile SET FileType = 13 WHERE fullName LIKE 'D:\hosting\down.51rc.com\ImageFolder\operational\Environment\%'

	SELECT Id, cpMainId, ImgFile, ImgFile FileName INTO #i FROM cpImage
	UPDATE #i SET FileName = RIGHT(FileName, LEN(FileName) - CHARINDEX('/', FileName, 0)) WHERE FileName LIKE '%/%'
	UPDATE #i SET FileName = RIGHT(FileName, LEN(FileName) - CHARINDEX('/', FileName, 0)) WHERE FileName LIKE '%/%'
	UPDATE #i SET FileName = RIGHT(FileName, LEN(FileName) - CHARINDEX('/', FileName, 0)) WHERE FileName LIKE '%/%'
	UPDATE #i SET FileName = RIGHT(FileName, LEN(FileName) - CHARINDEX('/', FileName, 0)) WHERE FileName LIKE '%/%'
	UPDATE #i SET FileName = RIGHT(FileName, LEN(FileName) - CHARINDEX('/', FileName, 0)) WHERE FileName LIKE '%/%'

	TRUNCATE TABLE #t
	UPDATE tmpCheckFile SET FileId = 1 WHERE FileType = 11
	INSERT INTO #t SELECT Id, FileName FROM tmpCheckFile WHERE FileType = 11
	DELETE FROM #t WHERE FileName IN(SELECT FileName FROM #i WHERE FileName > '')
	UPDATE a SET a.FileId = 999 FROM tmpCheckFile a, #t b WHERE a.Id = b.Id

	TRUNCATE TABLE #t
	UPDATE tmpCheckFile SET FileId = 1 WHERE FileType = 12
	INSERT INTO #t SELECT Id, FileName FROM tmpCheckFile WHERE FileType = 12
	DELETE FROM #t WHERE FileName IN(SELECT FileName FROM #i WHERE FileName > '')
	UPDATE a SET a.FileId = 999 FROM tmpCheckFile a, #t b WHERE a.Id = b.Id

	TRUNCATE TABLE #t
	UPDATE tmpCheckFile SET FileId = 1 WHERE FileType = 13
	INSERT INTO #t SELECT Id, FileName FROM tmpCheckFile WHERE FileType = 13
	DELETE FROM #t WHERE FileName IN(SELECT FileName FROM #i WHERE FileName > '')
	UPDATE a SET a.FileId = 999 FROM tmpCheckFile a, #t b WHERE a.Id = b.Id

	UPDATE tmpCheckFile SET FileId = 1 WHERE fullName LIKE 'D:\hosting\down.51rc.com\imagefolder\Logo\Default\%'
	--20：order.RemittanceFile；
	UPDATE tmpCheckFile SET FileType = 20 WHERE fullName LIKE 'D:\hosting\down.51rc.com\imagefolder\Remit\%'

	TRUNCATE TABLE #t
	UPDATE tmpCheckFile SET FileId = 1 WHERE FileType = 20
	INSERT INTO #t SELECT Id, FileName FROM tmpCheckFile WHERE FileType = 20
	DELETE FROM #t WHERE FileName IN(SELECT RemittanceFile FROM caOrder WHERE RemittanceFile > '')
	UPDATE a SET a.FileId = 999 FROM tmpCheckFile a, #t b WHERE a.Id = b.Id

	update tmpCheckFile set pamainid = left(filename, charindex('_', filename) - 1) where charindex('_', filename) > 1 and filetype = 20 and FileId = 999
	update a set a.fileid = 1 from tmpCheckFile a, caorder b
	where a.filetype = 20 and a.FileId = 999 and a.pamainid = b.id and charindex(a.filename, b.remittancefile) > 0

	--21：Order.ContractFile；
	UPDATE tmpCheckFile SET FileType = 21 WHERE fullName LIKE 'D:\hosting\down.51rc.com\imagefolder\Sales\contract\L%'

	UPDATE tmpCheckFile SET FileId = 1 WHERE FileType = 21 AND FileName IN(SELECT ContractFile FROM caOrder WHERE ContractFile > '')

	--22：FaxFile
	UPDATE tmpCheckFile SET FileType = 22, FileId = 1 WHERE fullName LIKE 'D:\hosting\down.51rc.com\imagefolder\Fax%'

	--orderupload
	UPDATE tmpCheckFile SET FileType = 23, FileId = 1 WHERE fullName LIKE 'D:\hosting\down.51rc.com\imagefolder\orderupload%'

	--29:GdFixed
	UPDATE tmpCheckFile SET FileType = 29, FileId = 1WHERE fullName LIKE 'D:\hosting\down.51rc.com\imagefolder\OA\Goods\%' 

	--40:adverproject;
	UPDATE tmpCheckFile SET FileType = 40, FileId = 1 WHERE fullName LIKE 'D:\hosting\down.51rc.com\imagefolder\operational\hpimage\%'
	TRUNCATE TABLE #t
	--UPDATE tmpCheckFile SET FileId = 1 WHERE FileType = 40
	INSERT INTO #t SELECT Id, FileName FROM tmpCheckFile WHERE FileType = 40
	select id, imagefile FileName INTO #a from AdverProject WHERE imagefile > ''
	UPDATE #a SET FileName = RIGHT(FileName, LEN(FileName) - CHARINDEX('/', FileName, 0)) WHERE FileName LIKE '%/%'
	UPDATE #a SET FileName = RIGHT(FileName, LEN(FileName) - CHARINDEX('/', FileName, 0)) WHERE FileName LIKE '%/%'
	UPDATE #a SET FileName = RIGHT(FileName, LEN(FileName) - CHARINDEX('/', FileName, 0)) WHERE FileName LIKE '%/%'
	UPDATE #a SET FileName = RIGHT(FileName, LEN(FileName) - CHARINDEX('/', FileName, 0)) WHERE FileName LIKE '%/%'
	UPDATE #a SET FileName = RIGHT(FileName, LEN(FileName) - CHARINDEX('/', FileName, 0)) WHERE FileName LIKE '%/%'
	DELETE FROM #t WHERE FileName IN(select FileName from #a WHERE FileName > '')
--??	UPDATE a SET a.FileId = 999 FROM tmpCheckFile a, #t b WHERE a.Id = b.Id

	UPDATE tmpCheckFile SET FileType = 41 WHERE fullName LIKE 'D:\hosting\down.51rc.com\imagefolder\adimage\%'

	--45:manageruser_photo
	UPDATE tmpCheckFile SET FileType = 45, FileId = 1 WHERE fullName LIKE 'D:\hosting\down.51rc.com\imagefolder\manageruser_photo\%'

	--51、OaDb..LeaveAttchment；
	UPDATE tmpCheckFile SET FileType = 51, FileId = 1 WHERE fullName LIKE 'D:\hosting\down.51rc.com\imagefolder\Oa\Leave\%'

	--52：文档管理
	UPDATE tmpCheckFile SET FileType = 52, FileId = 1 WHERE fullName LIKE 'D:\hosting\down.51rc.com\imagefolder\Oa\Archive\%'
	UPDATE tmpCheckFile SET FileType = 52, FileId = 1 WHERE fullName LIKE 'D:\hosting\down.51rc.com\imagefolder\Oa\Doc\%'
	select id, FileName INTO #h from oadb..hrdoc
	UPDATE #h SET FileName = RIGHT(FileName, LEN(FileName) - CHARINDEX('\', FileName, 0)) WHERE FileName LIKE '%\%'
	UPDATE #h SET FileName = RIGHT(FileName, LEN(FileName) - CHARINDEX('\', FileName, 0)) WHERE FileName LIKE '%\%'
	UPDATE #h SET FileName = RIGHT(FileName, LEN(FileName) - CHARINDEX('\', FileName, 0)) WHERE FileName LIKE '%\%'
	UPDATE #h SET FileName = RIGHT(FileName, LEN(FileName) - CHARINDEX('\', FileName, 0)) WHERE FileName LIKE '%\%'
	UPDATE #h SET FileName = RIGHT(FileName, LEN(FileName) - CHARINDEX('\', FileName, 0)) WHERE FileName LIKE '%\%'

	TRUNCATE TABLE #t
	INSERT INTO #t SELECT Id, FileName FROM tmpCheckFile WHERE FileType = 52
	DELETE FROM #t WHERE FileName IN(SELECT FileName FROM #h)
	UPDATE tmpCheckFile SET FileId = 999 WHERE ID IN(SELECT Id FROM #t)

	--53:OaAdvertising
	UPDATE tmpCheckFile SET FileType = 53, FileId = 1 WHERE fullName LIKE 'D:\hosting\down.51rc.com\imagefolder\Oa\Advertising\%'
	TRUNCATE TABLE #t
	INSERT INTO #t SELECT Id, FileName FROM tmpCheckFile WHERE FileType = 53

	SELECT TOP 0 * INTO #adv FROM #t
	insert into #adv select Id, FileName1 from Oadb..Advertising WHERE FileName1 > ''
	insert into #adv select Id, FileName2 from Oadb..Advertising WHERE FileName2 > ''
	DELETE from #t WHERE FileName in (SELECT FileName FROM #Adv)
	UPDATE tmpCheckFile SET FileId = 999 WHERE ID IN(SELECT Id FROM #t)

	--55:OaAdvertising
	UPDATE tmpCheckFile SET FileType = 55, FileId = 1 WHERE fullName LIKE 'D:\hosting\down.51rc.com\imagefolder\Oa\Project\%'

	--56:OaAdvertising
	UPDATE tmpCheckFile SET FileType = 56, FileId = 1  WHERE fullName LIKE 'D:\hosting\down.51rc.com\imagefolder\Oa\TrainCourse\%'

	--57:OaAdvertising
	UPDATE tmpCheckFile SET FileType = 57, FileId = 1 WHERE fullName LIKE 'D:\hosting\down.51rc.com\imagefolder\Oa\TrainPlan\%'

	--61:Campus
	UPDATE tmpCheckFile SET FileType = 61, FileId = 1 WHERE fullName LIKE 'D:\hosting\down.51rc.com\imagefolder\operational\Campus\%'

	--62:Campus
	UPDATE tmpCheckFile SET FileType = 62, FileId = 1 WHERE fullName LIKE 'D:\hosting\down.51rc.com\imagefolder\operational\CampusNew\%'
	
	--63:ChongSoft
 
	--64:Coorperation
	UPDATE tmpCheckFile SET FileType = 64, FileId = 1 WHERE fullName LIKE 'D:\hosting\down.51rc.com\imagefolder\Market\Coorperation\%'

	--65:FnBankCheck
	UPDATE tmpCheckFile SET FileType = 65, FileId = 1 WHERE fullName LIKE 'D:\hosting\down.51rc.com\imagefolder\Finance\FnBankCheck\%'

	--66:FnBankCheck
	UPDATE tmpCheckFile SET FileType = 66, FileId = 1 WHERE fullName LIKE 'D:\hosting\down.51rc.com\imagefolder\Finance\FnBankDaybook\%'

	--67:FnCash
	UPDATE tmpCheckFile SET FileType = 67, FileId = 1 WHERE fullName LIKE 'D:\hosting\down.51rc.com\imagefolder\Finance\FnCash\%'

	--68:FnPICDaybook
	UPDATE tmpCheckFile SET FileType = 68, FileId = 1 WHERE fullName LIKE 'D:\hosting\down.51rc.com\imagefolder\Finance\FnPICDaybook\%'

	--69:门贴
	UPDATE tmpCheckFile SET FileType = 69, FileId = 1 WHERE fullName LIKE 'D:\hosting\down.51rc.com\imagefolder\Market\%'

	--70:KPI
	UPDATE tmpCheckFile SET FileType = 70, FileId = 1 WHERE fullName LIKE 'D:\hosting\down.51rc.com\imagefolder\KPI\%'

	--71:linkimage

	--72:music

	--73:newsimage
	UPDATE tmpCheckFile SET FileType = 73, FileId = 1 WHERE fullName LIKE 'D:\hosting\down.51rc.com\imagefolder\operational\newsimage\%'

	--74:nianhui
 
	--75:picture
	UPDATE tmpCheckFile SET FileType = 75, FileId = 1 WHERE fullName LIKE 'D:\hosting\down.51rc.com\imagefolder\picture\%'

	--76:productBulletin
	UPDATE tmpCheckFile SET FileType = 76, FileId = 1 WHERE fullName LIKE 'D:\hosting\down.51rc.com\imagefolder\operational\productBulletin\%'

	--77:qlrcnews

	--78:Recruitment
	UPDATE tmpCheckFile SET FileType = 78, FileId = 1 WHERE fullName LIKE 'D:\hosting\down.51rc.com\imagefolder\Recruitment\%'
	truncate table #t
	insert #t select id, fileName from tmpCheckFile where filetype = 78 order by crdate desc
	select id, uploadfile filename into #pcv from marketdb..ptCvInvitation
	UPDATE #pcv SET FileName = RIGHT(FileName, LEN(FileName) - CHARINDEX('\', FileName, 0)) WHERE FileName LIKE '%\%'
	UPDATE #pcv SET FileName = RIGHT(FileName, LEN(FileName) - CHARINDEX('\', FileName, 0)) WHERE FileName LIKE '%\%'
	UPDATE #pcv SET FileName = RIGHT(FileName, LEN(FileName) - CHARINDEX('\', FileName, 0)) WHERE FileName LIKE '%\%'
	DELETE FROM #t WHERE FileName IN(SELECT FileName FROM #pcv)
	DELETE #t WHERE FullName LIKE 'D:\hosting\down.51rc.com\ImageFolder\Recruitment\RmPlacePhoto%'
	UPDATE tmpCheckFile SET FileId = 999 WHERE ID IN(SELECT Id FROM #t) AND fullName LIKE'D:\hosting\down.51rc.com\ImageFolder\Recruitment\RmPlacePhoto%'
	--80:slide
	UPDATE tmpCheckFile SET FileType = 80, FileId = 1 WHERE fullName LIKE 'D:\hosting\down.51rc.com\imagefolder\operational\slide\%'

	--81:topics
	UPDATE tmpCheckFile SET FileType = 81, FileId = 1 WHERE fullName LIKE 'D:\hosting\down.51rc.com\imagefolder\operational\topics\%'

	--82:topics
	UPDATE tmpCheckFile SET FileType = 30 WHERE fullName LIKE 'D:\hosting\down.51rc.com\ImageFolder\RecordFile\%'
	update tmpCheckFile set pamainid = left(filename, 7) where filetype = 30
	update tmpCheckFile set fileid = 1 where filetype = 30 and pamainid in(select id from ivrlist)

 	select  * from tmpCheckFile where filetype = 30 and FileId = 999

	TRUNCATE TABLE #t
	UPDATE tmpCheckFile SET FileId = 1 WHERE FileType = 30
	INSERT INTO #t SELECT Id, FileName FROM tmpCheckFile WHERE FileType = 30
	UPDATE #t SET FileName = LEFT(FileName, 7)
	DELETE FROM #t WHERE FileName IN(SELECT Id FROM IvrList)
	UPDATE a SET a.FileId = 999 FROM tmpCheckFile a, #t b WHERE a.Id = b.Id

	--
	UPDATE tmpCheckFile SET FileType = 90, fileid = 1 WHERE fullName LIKE 'D:\hosting\down.51rc.com\ImageFolder\wutongguo\%'
	UPDATE tmpCheckFile SET FileType = 91, fileid = 1 WHERE filetype=0 AND fullName LIKE 'D:\hosting\down.51rc.com\ImageFolder\operational\%'
	UPDATE tmpCheckFile SET FileType = 92, fileid = 1 WHERE filetype=0 AND fullName LIKE 'D:\hosting\down.51rc.com\ImageFolder\OA\Spread\PicCheck\%'
	UPDATE tmpCheckFile SET FileType = 93, fileid = 1 WHERE filetype=0 AND fullName LIKE 'D:\hosting\down.51rc.com\ImageFolder\OA\Car\%'
	UPDATE tmpCheckFile SET FileType = 94, fileid = 1 WHERE filetype=0 AND fullName LIKE 'D:\hosting\down.51rc.com\ImageFolder\CHAT\%'

	SELECT ID, FileName, REPLACE(FullName, 'D:\hosting\down.51rc.com\ImageFolder\Chat\', '') FullName, 0 IsExists INTO #c FROM tmpCheckFile WHERE FileType = 94
	UPDATE #c SET FullName = REPLACE(Fullname, '\', '/')
	UPDATE #c SET IsExists = 1 WHERE EXISTS(SELECT 'x' FROM ChatOnlineLog b WHERE b.Message = #c.FileName)
	DELETE #c WHERE Isexists = 1
	UPDATE #c SET IsExists = 1 WHERE EXISTS(SELECT 'x' FROM ChatOnlineLog b WHERE b.Message = #c.FullName)
	DELETE #c WHERE Isexists = 1
	UPDATE tmpCheckFile SET FileId = 999 WHERE ID IN(SELECT ID FROM #c)
 
	UPDATE tmpCheckFile SET FileType = 95, fileid = 1 WHERE filetype=0 AND fullName LIKE 'D:\hosting\down.51rc.com\ImageFolder\spreadcall\%'
	SELECT ID, RIGHT(FileName, 18) FileName, 0 IsExists INTO #s FROM tmpCheckFile WHERE FileType = 95
	UPDATE #s SET IsExists = 1 WHERE EXISTS(SELECT 'x' FROM SpreadCallLog b WHERE b.FileName LIKE '%' + #s.FileName)
	DELETE #ｓ WHERE Isexists = 1
	UPDATE tmpCheckFile SET FileId = 999 WHERE ID IN(SELECT ID FROM #s)	
	UPDATE tmpCheckFile SET FileType = 96, fileid = 1 WHERE filetype=0 AND fullName LIKE 'D:\hosting\down.51rc.com\ImageFolder\OA\ColdCustomer\%'
	UPDATE tmpCheckFile SET FileType = 97, fileid = 1 WHERE filetype=0 AND fullName LIKE 'D:\hosting\down.51rc.com\ImageFolder\WxMessageTemplate\%'
	update tmpCheckFile set CanDelete = 1 where candelete = 0 and FileId = 999 and FileType > 0
END
GO

/****** Object:  StoredProcedure [dbo].[spTmpCheckFileInsert]    Script Date: 2018/12/13 19:13:27 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[spTmpCheckFileInsert]
AS
BEGIN
	delete from tmpcheckfile
	where filename in(select photofile from marketdb..RmInvitationCode 
		where uploaddate> getdate()-60
		or adddate > getdate() -60
		or verifydate > getdate()-60)
	or crdate > getdate()-60
END













GO

/****** Object:  StoredProcedure [dbo].[spTransCustom]    Script Date: 2018/12/13 19:13:28 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE proc [dbo].[spTransCustom]
(
	@from char(3),
	@to char(3)
)
as
begin
	select 'Update cpmain  set consultantid=' + @to + ' Where id = '+ltrim(str(id)) from cpmain where consultantid=@from
	select 'Update caorder set manageruserid=' + @to + '  Where id='+ltrim(str(id)) from caorder where manageruserid=@from and opendate is null
	select 'update contact set manageruserid=' + @to + '  where manageruserid=' + @from
end
GO

/****** Object:  StoredProcedure [dbo].[spWxmessageSendByTempInsert]    Script Date: 2018/12/13 19:13:28 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

create procedure [dbo].[spWxmessageSendByTempInsert]
AS
BEGIN
	--DROP TABLE #t
	--drop table #wx

	SELECT DISTINCT b.Id paMainId INTO #t
	from maindb..wxfans a with(nolock),maindb..pamain b with(nolock) ,maindb..cvmain c with(nolock),
	maindb..cveducation d with(nolock)
	where a.pamainid=b.id and b.id=c.pamainid and c.id= d.cvmainid
	and status=2 
	and d.graduation>201606
	--AND b.dcProvinceId = 32

	--update #t SET pamainid = 26974069

	CREATE TABLE #wx(Id INT IDENTITY(1, 1), paMainId INT, Msg NVARCHAR(210),
		WxFansId INT, OpenId VARCHAR(50), WxServiceNoID INT, paName NVARCHAR(6),
		WebsiteName NVARCHAR(10), WxTemplateNo VARCHAR(100),
		ParaValue VARCHAR(1000), JsonMessage VARCHAR(1000))

	INSERT INTO #wx(paMainId, Msg, WxFansId, OpenId, wxServiceNoId)
	SELECT a.paMainId, '你好，今日软通动力正在发放终面名额，这是一个进名企的捷径，赶紧抓住机会吧。软通动力是上市公司，智慧城市与产业互联网建设的领导者，创新型技术服务提供商', b.Id WxFansId, b.OpenId, b.wxServiceNoId
	FROM #t a, WxFans b WITH(NOLOCK)
	WHERE a.paMainId = b.paMainId
	AND b.Status > 0
	AND a.PaMainId > 0

	UPDATE a SET a.paName = b.Name FROM #wx a, paMain b WITH(NOLOCK) WHERE a.paMainId = b.Id
	UPDATE a SET a.WebsiteName = c.WebsiteName FROM #wx a, WxServiceNo b WITH(NOLOCK), dcprovince c WITH(NOLOCK)  WHERE a.WxServiceNoId = b.Id AND b.ProvinceID = c.Id
	UPDATE a SET a.WxTemplateNo = b.[no] FROM #wx a, WxTemplateNo b WITH(NOLOCK) WHERE a.WxServiceNoID = b.WxServiceNoID AND b.WxTemplateId = 13 

	--插入参数数据
	UPDATE #wx SET ParaValue = '"first":{    "value":"软通动力正在发放2017校招终面名额",    "color":"#000000"},  "keyword1":{    "value":"直通终面",    "color":"#004694"},  "keyword2":{    "value":"终面提醒",    "color":"#004694"},  "remark":{    "value":"#JobDesc#",    "color":"#004694"}'
	--UPDATE #wx SET ParaValue = REPLACE(ParaValue, '#PaName#', PaName) 
	UPDATE #wx SET ParaValue = REPLACE(ParaValue, '#JobDesc#', Msg)
	--UPDATE #wx SET ParaValue = REPLACE(ParaValue, '#WebsiteName#', WebsiteName)
	UPDATE #wx SET JsonMessage = '{"touser":"' + OpenId + '", "template_id":"' + WxTemplateNo + '", "url":"http://zhaopin.baidu.com/m/ztzm", "topcolor":"#000000", "data":{' + ParaValue + '}}'

	--更新wxmessagesend中的message
--	INSERT INTO wxMessageSend2(TemplateType, WxfansId, paMainId, MessageText, ErrorNumber, AddDate)
	SELECT 10, WxFansId, paMainId, JsonMessage, 0, GETDATE() FROM #wx

--	select * from wxmessagesend2 where TemplateType = 10 order by id desc
--	select * from #wx
--	select count(*) from wxmessagesend2 where TemplateType = 10 and senddate is null
END
GO

/****** Object:  StoredProcedure [dbo].[synBeisenJobApplyByBeiSenResumeUpdate]    Script Date: 2018/12/13 19:13:28 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[synBeisenJobApplyByBeiSenResumeUpdate] 
(
	@id INT,
	@BeiSenResumeID VARCHAR(50),
	@BeiSenResumeSyncId VARCHAR(50)
)
AS
SET NOCOUNT ON
BEGIN
	UPDATE BeisenJobApply 
	SET BeiSenResumeID = @BeiSenResumeID, 
		BeiSenResumeSyncId = @BeiSenResumeSyncId,
		BeisenHasApply = 1,
		LastGetDate = GETDATE()
	WHERE ID = @id
END
SET NOCOUNT OFF

GO

/****** Object:  StoredProcedure [dbo].[tmpViewTableSIzeGrow]    Script Date: 2018/12/13 19:13:29 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[tmpViewTableSIzeGrow]
AS
BEGIN
	create table #t(
	Name varchar(100),
	Rows0810 int,
	Rows0811 int,
	Rows0812 int,
	Rows0813 int,
	Rows0814 int
	)
	INSERT #t(Name) SELECT DISTINCt TABLENAME FROM bsTableSizeLog

	DECLARE @I int, @SQL VARCHAR(1000)
	SET @i = 0
	WHILE @I<5
	BEGIN
	SET @Sql = '
	UPDATE a SET a.Rows081' + LTRIM(STR(@I)) + ' = b.Rows 
	FROM #t a, bsTableSizeLog b 
	WHERE a.Name=b.TableName
	And b.coutDate = 2011081' + LTRIM(STR(@I))

	Exec( @Sql)
	SET @I=@I+1
	END

	select *, rows0814*1.0/rows0810
	from #t 
	where rows0814>100000
	order by rows0814*1.0/rows0810 desc

	DROP TABle #t
END













GO

/****** Object:  StoredProcedure [dbo].[updateDeleteFile]    Script Date: 2018/12/13 19:13:29 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[updateDeleteFile]
@listID VARCHAR(1024)
as 
begin 
    declare @i INT,@ID VARCHAR(50)
    set @i = CHARINDEX(',',@listID)
    while @i > 0
    begin
        set @ID = substring(@listID,1,@i-1)
        update bsDeleteFile set IsDelete = 0
        set @listID = substring(@listID,@i+1,len(@listID))
        set @i = CHARINDEX(',',@listID)
    end
end 













GO

/****** Object:  StoredProcedure [dbo].[v2018_ccCaMainByLastLoginDateUpdate]    Script Date: 2018/12/13 19:13:29 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2018-10-15
--创建人：Lucifer
--说明：更新企业登陆时间
--当天第一次登陆，更新DateReport.CompanyLoginNum_Net
--20是PC站回收 如果不是当天第一次登陆，不记录登陆时间
--#####################################################
CREATE PROCEDURE [dbo].[v2018_ccCaMainByLastLoginDateUpdate]
(
	@caMainId INT,
	@dcProvinceId INT,
	@IP VARCHAR(31),
	@LoginCookies VARCHAR(16),
	@Browser VARCHAR(500),
	@LoginFrom TINYINT
)
AS
SET NOCOUNT ON
BEGIN
	DECLARE @cpMainId INT
	SELECT @cpMainId = b.ID FROM cpMain a WITH(NOLOCK), caMain b WITH(NOLOCK) WHERE a.ID = b.cpMainId AND b.ID = @caMainId
	IF @cpMainId IS NULL
		RETURN

	SET @IP = dbo.SafeSQL(@IP)
	SET @Browser = dbo.SafeSQL(@Browser)

	DECLARE @LoginTodayFirst BIT
	SET @LoginTodayFirst = 0
	--当天第一次登陆，更新DateReport.CompanyLoginNum_Net
	IF NOT EXISTS(SELECT 'X' FROM caLoginLog WITH(NOLOCK) WHERE caMainID = @caMainID AND AddDate >= CONVERT(VARCHAR(10), GETDATE(), 120))
	BEGIN
		UPDATE DateReport
		SET CompanyLoginNum_Net = CompanyLoginNum_Net + 1  
		WHERE CountDate = CONVERT(VARCHAR(8), GETDATE(), 112)
		AND Province_Id = @dcProvinceId

		SET @LoginTodayFirst = 1
	END

	--不是回收的或者第一次登陆的，插入登陆记录
	IF @LoginFrom NOT IN(20) OR @LoginTodayFirst = 1
	BEGIN
		INSERT INTO caLoginLog(caMainID, cpMainName, caMainName, LoginIP, LoginCookies, Browser, LoginFrom)
		SELECT b.ID, a.[Name], b.[Name], @IP, @LoginCookies, @Browser, @LoginFrom FROM cpMain a WITH(NOLOCK), caMain b WITH(NOLOCK)
		WHERE a.ID = b.cpMainID AND b.ID = @caMainID
		--更新cpMain的登陆时间
		UPDATE cpMain SET
			LastLoginDate = GETDATE(),
			LastLoginIp = @IP,
			LoginCount = ISNULL(LoginCount, 0) + 1
		WHERE ID = @cpMainId
	END
END
SET NOCOUNT OFF

GO

/****** Object:  StoredProcedure [dbo].[v2018_ccCaMainByLoginUpdate]    Script Date: 2018/12/13 19:13:29 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2018.9.25
--创建人：Lucifer
--说明：企业用户登陆
--      -1 登陆次数超过限制
--       0 数据错误
--#####################################################
CREATE PROCEDURE [dbo].[v2018_ccCaMainByLoginUpdate]
(
	@caMainID INT,
	@IP VARCHAR(31), 
	@LoginCookies VARCHAR(16),
	@Browser VARCHAR(500),
	@LoginFrom INT
)
AS
SET NOCOUNT ON
BEGIN TRAN
	DECLARE 
		@cpMainID INT,
		@dcProvinceID SMALLINT,
		@DayLoginNumber INT,
		@RefreshDate SMALLDATETIME,
		@MemberType TINYINT,
		@TodayLoginNumber INT

	BEGIN TRY
		IF @caMainID <>0
		BEGIN
			SELECT
				@cpMainID = a.cpMainID,
				@MemberType = b.MemberType,
				@RefreshDate = b.RefreshDate,
				@dcProvinceID = b.dcProvinceID
			FROM caMain a WITH(NOLOCK), cpMain b WITH(NOLOCK)
			WHERE a.ID = @caMainID AND a.cpMainID = b.ID
		END
		
		--判断是否为死客户，如果为死客户，则激活
		UPDATE bsDeadCompany SET ActiveDate = GETDATE() WHERE cpMainID = @cpMainID AND ActiveDate IS NULL

		--VIP每天最大登陆次数30次，普通用户15次
		IF @MemberType = 3
			SET @DayLoginNumber = 30
		ELSE
			SET @DayLoginNumber = 15

		SELECT @TodayLoginNumber = COUNT(1)
		FROM caLoginLog WITH(NOLOCK)
		WHERE caMainID = @caMainID
		AND AddDate >= CONVERT(VARCHAR(10), GETDATE(), 120)
		
		IF @TodayLoginNumber >= @DayLoginNumber
			GOTO ERRMAX

		--刷新今天未刷新的职位
		UPDATE Job SET
			RefreshDate = GETDATE() 
		WHERE caMainID = @caMainID
			AND RefreshDate < CONVERT(VARCHAR(10), GETDATE(), 120)
			AND Valid = 1
		
		UPDATE cpMain SET
			LoginCount = LoginCount + 1,
			LastLoginDate = GETDATE(),
			LastLoginIp = @IP
		WHERE ID = @cpMainID

 		--更新企业刷新时间，间隔时间1小时
		IF DATEDIFF(MINUTE, @RefreshDate, GETDATE()) > 59 --刷新时间如果超过1个小时，更新为当前时间
		BEGIN TRY
			UPDATE cpMain SET RefreshDate = GETDATE() WHERE ID = @cpMainID
			IF @MemberType >= 2 OR (
				@dcProvinceID NOT IN(32, 30, 31, 35, 10, 11, 12, 40) AND @MemberType = 1
			)
			BEGIN
				--删除旧的，添加新的Snapshot
				DELETE FROM SearchDB..cpMainHomepageSnapshot WHERE RealCpMainID = @cpMainID

				DECLARE @LastJobIssueDate SMALLDATETIME, @LastJobId VARCHAR(20)
				--获取最新发布的职位信息
				SELECT TOP 1 @LastJobIssueDate = IssueDate, @LastJobId = SecondId
				FROM Job WITH(NOLOCK)
				WHERE cpMainID = @cpMainID AND Valid = 1
				ORDER BY IssueDate DESC

				INSERT SearchDB..cpMainHomepageSnapshot(dcSubsiteID, dcRegionID, cpMainID, [Name], IsAgent, JobNumber, JobID, JobName, LastJobIssueDate, LastJobId, MemberType, RealCpMainId, RefreshDate)
				SELECT dcProvinceId, LEFT(dcRegionId, 4), SecondId, [Name], IsAgent, JobNumber, dbo.GetJobSecondIds(ID), dbo.GetJobNames(ID), @LastJobIssueDate, @LastJobId, MemberType, ID, RefreshDate
				FROM cpMain WITH(NOLOCK)
				WHERE ID = @cpMainID
			END
		END TRY
		BEGIN CATCH
		END CATCH
		--记录每日登录数据
		IF @TodayLoginNumber = 0
		BEGIN
			UPDATE DateReport SET
				CompanyLoginNum_Net = CompanyLoginNum_Net + 1
			WHERE Province_ID = @dcProvinceID
				AND CountDate = CONVERT(VARCHAR(10), GETDATE(), 112)
		END
		--插入登陆日志
		INSERT INTO caLoginLog(caMainID, cpMainName, caMainName, LoginIP, LoginCookies, Browser, LoginFrom)
		SELECT b.ID, a.[Name], b.[Name], @IP, @LoginCookies, @Browser, @LoginFrom FROM cpMain a WITH(NOLOCK), caMain b WITH(NOLOCK)
		WHERE a.ID = b.cpMainID AND b.ID = @caMainID
	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH
COMMIT TRAN
RETURN 1
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END
ERRMAX:
BEGIN
	ROLLBACK TRAN
	RETURN -1
END
SET NOCOUNT OFF
GO

/****** Object:  StoredProcedure [dbo].[v2018_ccCaMainEmailCheck]    Script Date: 2018/12/13 19:13:29 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建：	Lucifer
--检查：	2018-10-16
--检查邮箱是否可以注册
--0: 可以注册
--1: 重复
--2: 黑名单
--#####################################################
CREATE PROCEDURE  [dbo].[v2018_ccCaMainEmailCheck]
(
	@Email VARCHAR(50)
)
AS
SET NOCOUNT ON
BEGIN
	UPDATE Company_Black SET
		RefuseCount = RefuseCount + 1
	WHERE Email = @Email

	IF @@ROWCOUNT > 0
		RETURN 2		--邮件在黑名单

	--Email不可以和主用户的Email重复
	IF EXISTS(
		SELECT 'X' FROM caMain a WITH(NOLOCK), cpMain b WITH(NOLOCK)
		WHERE (b.RegisterMode = 0 Or b.RegisterMode = 11)
			AND a.cpMainID = b.ID AND a.Email = @Email 
			AND b.IsDelete = 0 AND a.IsDelete = 0 AND a.AccountType = 1
	)
	BEGIN
		RETURN 1
	END
	RETURN 0
END
GO

/****** Object:  StoredProcedure [dbo].[v2018_ccCaMainUsernameCheck]    Script Date: 2018/12/13 19:13:30 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建：	Lucifer
--检查：	2018-10-16
--检查用户名是否可以注册
--0: 可以注册
--1: 重复
--#####################################################
CREATE PROCEDURE  [dbo].[v2018_ccCaMainUsernameCheck]
(
	@Username VARCHAR(20)
)
AS
SET NOCOUNT ON
BEGIN
	IF EXISTS(SELECT 'X' FROM caMain WITH(NOLOCK) WHERE UserNameLower = @Username)
		RETURN 1

	IF EXISTS(SELECT 'X' FROM Company_Xinxi WITH(NOLOCK) WHERE UserNameLower = @Username)
		RETURN 1

	RETURN 0
END
GO

/****** Object:  StoredProcedure [dbo].[v2018_ccCaVerifyLogInsert]    Script Date: 2018/12/13 19:13:30 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--####################################################
--添加人：Lucifer
--添加时间：2018-6-27
--描述：获取短信/邮件验证码
--返回值 -1 一天同一IP验证超过10次
--       -2 一天同一手机号验证超过5次
--       -3 5分钟内同一手机号超过3次
--       -4 手机号黑名单
--####################################################
CREATE PROCEDURE [dbo].[v2018_ccCaVerifyLogInsert] 
(
    @Mobile VARCHAR(11),
    @IP VARCHAR(31),
    @caMainID INT
)
AS
SET NOCOUNT ON
BEGIN
	SET @Mobile = dbo.v2018_SetVarcharNull(@Mobile)
	IF EXISTS(SELECT 'X' FROM Company_Black WITH(NOLOCK) WHERE Mobile = @Mobile)
		RETURN -4

	IF EXISTS(SELECT 'X' FROM tmp_LimitMobile WITH(NOLOCK) WHERE Mobile = @Mobile)
		RETURN -4

    IF CHARINDEX(', ', @IP) > 0
        SET @IP = RIGHT(@IP, LEN(@IP) - CHARINDEX(', ', @IP))

    DECLARE @VerifyCount SMALLINT
    SELECT @VerifyCount = COUNT(1) FROM caVerifyLog WITH(NOLOCK)
    WHERE [IP] = @IP
    AND AddDate > CONVERT(VARCHAR(10), GETDATE(), 120)

    IF @VerifyCount >= 10 AND @IP <> '60.215.144.163'  --一天同一IP验证超过10次
        RETURN -1

    SELECT @VerifyCount = COUNT(1) FROM caVerifyLog WITH(NOLOCK)
    WHERE Mobile = @Mobile
    AND AddDate > CONVERT(VARCHAR(10), GETDATE(), 120)

    IF @VerifyCount >= 5  --一天同一手机号验证超过5次
        RETURN -2

    SELECT @VerifyCount = COUNT(1) FROM caVerifyLog WITH(NOLOCK)
    WHERE Mobile = @Mobile
    AND AddDate > DATEADD(MINUTE, -5, GETDATE())

    IF @VerifyCount >= 3  --5分钟内同一手机号超过3次
        RETURN -3

    DECLARE @VerifyCode VARCHAR(6)
    SELECT @VerifyCode = RAND() * 899999 + 100000
    INSERT INTO caVerifyLog(caMainID, Mobile, VerifyCode, VerifyDate, AddDate, [IP])
    VALUES(@caMainID, @Mobile, @VerifyCode, NULL, GETDATE(), @IP)

    RETURN @VerifyCode
END
SET NOCOUNT OFF
GO

/****** Object:  StoredProcedure [dbo].[v2018_ccCaVerifyLogUpdate]    Script Date: 2018/12/13 19:13:30 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--####################################################
--添加人：Lucifer
--添加时间：2018-10-16
--描述：验证企业认证码，并做相应操作
--CerType 1 手机号认证 UPDATE caMain
--        2 手机号注册
--返回值 -1  认证失败
--       >=0 返回caMainID
--####################################################
CREATE PROCEDURE [dbo].[v2018_ccCaVerifyLogUpdate] 
(
	@Mobile VARCHAR(11),
	@CerCode VARCHAR(6),
	@CerType TINYINT
)
AS
SET NOCOUNT ON
BEGIN
	SET @Mobile = dbo.v2018_SetVarcharNull(@Mobile)
	IF @Mobile IS NULL
	BEGIN
		RETURN -1
	END

	DECLARE @caMainID INT
	DECLARE @caVerifyLogID INT

	SELECT TOP 1 @caMainID = caMainID, @caVerifyLogID = ID
	FROM caVerifyLog WITH(NOLOCK)
	WHERE Mobile = @Mobile
		AND VerifyCode = @CerCode
		AND VerifyDate IS NULL
        AND AddDate > DATEADD(HOUR, -1, GETDATE())
	ORDER BY ID DESC

	IF @caVerifyLogID IS NULL --验证码错误
	BEGIN
		RETURN -1
	END

	UPDATE caVerifyLog SET
		VerifyDate = GETDATE()
	WHERE ID = @caVerifyLogID

	IF @CerType = 1 --手机号认证
	BEGIN
		UPDATE caMain SET
			Mobile = @Mobile,
			MobileVerifyDate = GETDATE()
		WHERE ID = @caMainID
	END
	RETURN @caMainID
END
SET NOCOUNT OFF
GO

/****** Object:  StoredProcedure [dbo].[v2018_ccCpMainInsert]    Script Date: 2018/12/13 19:13:30 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建：	Lucifer
--检查：	2018-10-16
--注册企业用户
--ERR: IP在黑名单
--ERR1:企业名称在黑名单
--ERR2:邮箱在黑名单
--ERR3:用户名重复
--ERR4:注册频繁
--ERR5:邮箱不可以和主用户的邮箱重复
--#####################################################
CREATE PROCEDURE  [dbo].[v2018_ccCpMainInsert]
(
	@Name VARCHAR(100),
	@Email VARCHAR(50),
	@Username VARCHAR(20),
	@Password VARCHAR(60),
	@PlainPassword VARCHAR(20),
	@CaName NVARCHAR(6),
	@Mobile VARCHAR(11),
	@Telephone VARCHAR(25),
	@dcProvinceID TINYINT,
	@RegisterIP VARCHAR(31),
	@Url_ID INT,
	@cpMainID INT OUTPUT,
	@caMainID INT OUTPUT
)
AS
SET NOCOUNT ON
BEGIN
	SET @cpMainID = 0
	SET @caMainID = 0
	
	--IP在黑名单
	IF EXISTS(SELECT 'X' FROM Ip_Black WITH(NOLOCK) WHERE [IP] = @RegisterIP)
		GOTO ERR
	
	--在IP限制名单里
	IF EXISTS(SELECT 'X' FROM Tmp_LimitIP WITH(NOLOCK) WHERE LastLoginIp = @RegisterIP)
		GOTO ERR

	UPDATE Company_Black SET
		RefuseCount = RefuseCount + 1
	WHERE CHARINDEX(LTRIM(RTRIM(CompanyName)), @Name) > 0

	IF @@ROWCOUNT > 0
		GOTO ERR1		--企业名称在黑名单

	DECLARE @Return INT
	EXEC @Return = v2018_ccCaMainEmailCheck @Email

	IF @Return = 2
		GOTO ERR2		--邮箱在黑名单
	ELSE IF @Return = 1
		GOTO ERR5		--邮箱不可以和主用户的邮箱重复

	EXEC @Return = v2018_ccCaMainUsernameCheck @Username
	IF @Return = 1
		GOTO ERR3		--用户名重复

	--如果是非工作时间，则检查是否有重复注册
	IF(DATEPART(HOUR, GETDATE()) > 17 OR DATEPART(HOUR, GETDATE()) < 8)
	BEGIN
		--10分钟内企业名称重复，认为是恶意注册
		IF EXISTS(SELECT 'X' FROM cpMain WITH(NOLOCK) WHERE RegDate > DATEADD(MINUTE, -10, GETDATE()) AND [Name] LIKE '%' + @Name + '%')
			GOTO ERR4

		--3分钟内注册Ip重复，认为是恶意注册
		IF EXISTS(SELECT 'X' FROM cpMain WITH(NOLOCK) WHERE RegDate > DATEADD(MINUTE, -3, GETDATE()) AND LastLoginIp = @RegisterIP)
			GOTO ERR4
	END

	--3分钟内同一IP注册数量超过3个
	IF (SELECT COUNT(*) FROM cpMain WITH(NOLOCK) WHERE RegDate > DATEADD(MINUTE, -3, GETDATE()) AND LastLoginIp = @RegisterIP) > 3
		GOTO ERR4

	--检查通过，增加到企业表
	BEGIN TRAN
		--企业表
		INSERT INTO cpMain(dcProvinceID, dcRegionID, dcSubSiteID, RegisterIP, [Name], RegDate, RegisterMode, RefreshDate, LoginCount, LastLoginDate, LastLoginIP)
		VALUES(@dcProvinceID, @dcProvinceID, @dcProvinceID, @RegisterIP, @Name, GETDATE(), 0 , GETDATE(), 1, GETDATE(), @RegisterIP)
		SET @cpMainID = SCOPE_IDENTITY()

		--账号表
		INSERT INTO caMain(cpMainID, Email, AccountType, UserName, [Password], [Name], Mobile, Telephone)
		VALUES(@cpMainID, @Email, 1, @UserName, @Password, @CaName, @Mobile, @Telephone)
		SET @caMainID = SCOPE_IDENTITY()

		--记录原密码
		INSERT INTO caPlainPassword(caMainId, PlainPassWord) SELECT @caMainID, @PlainPassword

		--更新手机号认证
		UPDATE caMain SET
			MobileVerifyDate = GETDATE()
		WHERE ID = @caMainID AND EXISTS(SELECT TOP 1 'X' FROM caVerifyLog WHERE VerifyDate > DATEAdd(n, -1, GETDATE()) AND Mobile = caMain.Mobile)
			
		----Company_Xinxi处理, 160天内计算工作量，超过160天不计算工作量
		DECLARE @Company_XinxiID INT,
			@AddMan SMALLINT,
			@RegDate SMALLDATETIME,
			@Resume_Xinxi_ProvinceID TINYINT,
			@IsHistory BIT

		SELECT @Company_XinxiID = ID, @AddMan = AddMan, @RegDate = RegDate,
			@IsHistory = IsHistory
			FROM Company_Xinxi WITH(NOLOCK)
		WHERE Email = @Email
		AND Province_ID = @dcProvinceID
		ORDER BY IsHistory, RegDate DESC

		--日报表, 信息员推广注册，IsHistory = 0的作为推广ValidCompany
		IF @Company_XinxiID IS NOT NULL AND @AddMan > 1 AND @Ishistory = 0
		BEGIN
			UPDATE cpMain SET AddMan = @AddMan, RegisterMode = 1 WHERE ID = @cpMainID
			--记录信息员工作量
			--判断是否有该行记录，没有则增加
			IF NOT EXISTS(
				SELECT 'X' FROM Info_DateReport WITH(NOLOCK)
				WHERE CountDate = CONVERT(VARCHAR(8), GETDATE(), 112) AND Province_ID = @dcProvinceID AND InfoManager_ID = @AddMan
			)
			BEGIN
				INSERT INTO Info_DateReport(Province_ID, InfoManager_ID, CountDate)
				VALUES(@dcProvinceID, @AddMan, CONVERT(VARCHAR(8), GETDATE(), 112))
			END
			--记录数据，信息员工作量 + 1
			UPDATE Info_DateReport SET
				ValidCompany = ValidCompany + 1  
			WHERE CountDate = CONVERT(VARCHAR(8), GETDATE(), 112)
				AND Province_ID = @dcProvinceID
				AND InfoManager_ID = @AddMan
			--推广的企业数量+1
			UPDATE DateReport SET
				ValidCompany = ValidCompany + 1
			WHERE CountDate = CONVERT(VARCHAR(8), GETDATE(), 112)
				AND Province_ID = @dcProvinceID
		END
		ELSE
		BEGIN
			--企业注册数量+1
			UPDATE DateReport SET
				CompanyRegNum = CompanyRegNum + 1
			WHERE CountDate = CONVERT(VARCHAR(8), GETDATE(), 112)
				AND Province_ID = @dcProvinceID
		END
		--来源注册
		IF @Url_ID > 0
		BEGIN
			UPDATE Url
			SET AllCompany = AllCompany + 1, TodayCompany = TodayCompany + 1 
			WHERE ID = @Url_ID
			UPDATE cpMain SET RegisterSourceId = @Url_Id WHERE ID = @cpMainID
		END
		--后台审核
		INSERT INTO bsCpModify (cpMainID, caMainID, [Location], ColValue) VALUES(@cpMainID, @caMainID, 'a1', @Name)
		--顾问分配
		EXEC ccCpMainByConsultantAssignUpdate @cpMainID, @dcProvinceID
	COMMIT TRAN
	RETURN 1
END
ERR:				--IP在黑名单
BEGIN
	RETURN 0
END
ERR1:				--企业名称在黑名单
BEGIN
	RETURN -1
END
ERR2:				--邮箱在黑名单
BEGIN
	RETURN -2
END
ERR3:				--用户名重复
BEGIN
	RETURN -3
END
ERR4:				--注册频繁
BEGIN
	RETURN -4
END
ERR5:				--邮箱不可以和主用户的邮箱重复
BEGIN
	RETURN -5
END
GO

/****** Object:  StoredProcedure [dbo].[v2018_ccCpModifyInsert]    Script Date: 2018/12/13 19:13:31 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--#########################################################
--添加人    Lucifer
--添加时间  2018-6-25
--用途      企业待审核数据插入
--#########################################################
CREATE PROCEDURE [dbo].[v2018_ccCpModifyInsert]
(
	@cpMainID INT,
	@caMainID INT,
	@SubID INT,
	@Value VARCHAR(MAX),
	@ValueOld VARCHAR(MAX),
	@ColType VARCHAR(5)
)
AS
SET NOCOUNT ON
BEGIN
	SET @Value = dbo.v2018_SetVarcharNull(@Value)
	SET @ValueOld = dbo.v2018_SetVarcharNull(@ValueOld)	
	--插入待审核记录
	DELETE FROM bsCpModify WHERE cpMainID = @cpMainID AND caMainID = @caMainID AND ISNULL(SubID, 0) = ISNULL(@SubID, 0) AND [Location] = @ColType
	IF @Value <> ISNULL(@ValueOld, '') AND @Value IS NOT NULL
	BEGIN
		INSERT INTO bsCpModify(cpMainID, caMainID, SubID, [Location], ColValue) VALUES(@cpMainID, @caMainID, @SubID, @ColType, @Value)
	END
END
SET NOCOUNT OFF
GO

/****** Object:  StoredProcedure [dbo].[v2018_ccJobIssue]    Script Date: 2018/12/13 19:13:31 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--#########################################################
--添加人    Lucifer
--添加时间  2018-11-6
--用途      职位发布
--返回      0 发布成功
--			1 发布失败
--#########################################################
CREATE PROCEDURE [dbo].[v2018_ccJobIssue]
(
	@cpMainID INT,
	@JobID INT,
	@IssueEnd SMALLDATETIME,
	@IP VARCHAR(50)
)
AS
SET NOCOUNT ON
--BEGIN TRAN	
	--BEGIN TRY
		IF NOT EXISTS(SELECT 'X' FROM Job WITH(NOLOCK) WHERE ID = @JobID AND cpMainID = @cpMainID)
			GOTO ERR

		DECLARE @IssueDate SMALLDATETIME
		SET @IssueDate = DATEADD(MINUTE, -1, GETDATE())
		IF @IssueEnd < GETDATE()
		BEGIN
			SET @IssueEnd = DATEADD(MONTH, 2, GETDATE())
		END
		SET @IssueEnd = CONVERT(VARCHAR(10), @IssueEnd, 120) + ' 23:59'

		DECLARE @CurrentIssueEnd SMALLDATETIME
		SELECT @CurrentIssueEnd = ISNULL(IssueEnd, @IssueDate) FROM Job WITH(NOLOCK) WHERE ID = @JobID
		--现在正在发布的，直接修改不用判断
		IF @CurrentIssueEnd > GETDATE()
		BEGIN
			UPDATE Job SET
				IssueDate = @IssueDate,
				IssueEnd = @IssueEnd
			WHERE ID = @JobID
		END
		ELSE
		BEGIN
			--不是正在发布的，需要先判断是否超过最大职位数
			IF EXISTS(SELECT 'X' FROM cpMain WITH(NOLOCK) WHERE ID = @cpMainID AND MaxJobNumber <= JobNumber)
			BEGIN
				RETURN 0
			END
			UPDATE Job SET
				IssueDate = @IssueDate,
				IssueEnd = @IssueEnd
			WHERE ID = @JobID
			--插入发布的操作日志
			INSERT INTO caOperationLog(caMainID, Operation, Details, [IP])
			SELECT TOP 1 caMainID, 40, '发布职位：编号<' + LTRIM(STR(ID)) + '>职位名称<' + [Name] +'>，有效期至' + CONVERT(VARCHAR(19), @IssueEnd, 120) + '。', @IP
			FROM Job WITH(NOLOCK)
			WHERE ID = @JobID
			--插入APP推送日志
			INSERT INTO paPushLog(paMainID, PushMessage, PushType, DetailID)
			SELECT PaMainID, '亲，您关注的企业发布新职位啦！', 6, @JobID FROM paAttention
			WHERE AttentionType = 1 AND AttentionID = @cpMainId AND EXISTS(
				SELECT 'X' FROM paIosBind WHERE paMainID = paAttention.paMainID
			)
		END
	--END TRY
	--BEGIN CATCH
	--	GOTO ERR
	--END CATCH
--COMMIT TRAN
RETURN 1
ERR:
BEGIN
	--ROLLBACK TRAN
	RETURN 0
END
SET NOCOUNT OFF
GO

/****** Object:  StoredProcedure [dbo].[v2018_ccJobSave]    Script Date: 2018/12/13 19:13:31 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2018.11.6
--创建人：Lucifer
--说明：保存职位信息
--返回值： -1 职位名称重复
--         -2 发布失败
--          0 操作人不是自己或管理员
--         >0 保存成功 
--#####################################################
CREATE PROCEDURE [dbo].[v2018_ccJobSave]
(
	@OperatorID INT,
	@ID INT,
	@cpMainID INT,
	@caMainID INT,
	@Name VARCHAR(50),
	@dcJobTypeID INT,
	@dcJobTypeIDMinor INT,
	@NeedNumber SMALLINT,
	@dcSalaryID TINYINT,
	@dcSalaryMaxID TINYINT,
	@Negotiable BIT,
	@EmployType TINYINT,
	@dcRegionID VARCHAR(6),
	@Lng DECIMAL(8, 5),
	@Lat DECIMAL(8, 5),
	@Responsibility VARCHAR(MAX),
	@Demand VARCHAR(MAX),
	@dcEducationID TINYINT,
	@MinExperience TINYINT,
	@MinAge TINYINT,
	@MaxAge TINYINT,
	@EMailSendFreq INT,
	@EMailSendNumber TINYINT,
	@IssueEnd SMALLDATETIME,
	@FilterMaxDegree TINYINT,
	@FilterMinDegree TINYINT,
	@FilterMaxWorkYear TINYINT,
	@FilterMinWorkYear TINYINT,
	@FilterMaxAge TINYINT,
	@FilterMinAge TINYINT,
	@FilterGender VARCHAR(1),
	@FilterJobRegion VARCHAR(6),
	@ForwardEmail VARCHAR(100),
	@JobTags VARCHAR(MAX),
	@Promotion NVARCHAR(100),
	@Welfare VARCHAR(100),
	@IP VARCHAR(50)
)
AS
SET NOCOUNT ON
--BEGIN TRAN
	--操作人不是自己或管理员
	IF @OperatorID <> (SELECT ID FROM caMain WITH(NOLOCK) WHERE cpMainID = @cpMainID AND AccountType = 1) AND @OperatorID <> @caMainID
		RETURN 0

	SET @Name = dbo.v2018_SetVarcharNull(@Name)
	--同一公司同一地区 职位名称不能重复
	IF EXISTS(SELECT TOP 1 'X' FROM Job WITH(NOLOCK) 
		WHERE [Name] = @Name 
		AND dcRegionId = @dcRegionID
		AND cpMainId = @cpMainID 
		AND ID <> @ID 
		AND IsDelete = 0
	)
	BEGIN
		RETURN -1
	END
	SET @Demand = dbo.v2018_SetVarcharNull(@Demand)
	SET @Responsibility = dbo.v2018_SetVarcharNull(@Responsibility)
	SET @FilterJobRegion = dbo.v2018_SetVarcharNull(@FilterJobRegion)
	SET @ForwardEmail = dbo.v2018_SetVarcharNull(@ForwardEmail)
	SET @JobTags = dbo.v2018_SetVarcharNull(@JobTags)
	SET @Promotion = dbo.v2018_SetVarcharNull(@Promotion)
	SET @Welfare = dbo.v2018_SetVarcharNull(@Welfare)

	SET @dcJobTypeIDMinor = dbo.v2018_SetIntNull(@dcJobTypeIDMinor)
	SET @MinAge = dbo.v2018_SetIntNull(@MinAge)
	SET @MaxAge = dbo.v2018_SetIntNull(@MaxAge)
	SET @EMailSendNumber = dbo.v2018_SetIntNull(@EMailSendNumber)
	SET @FilterMaxDegree = dbo.v2018_SetIntNull(@FilterMaxDegree)
	SET @FilterMinDegree = dbo.v2018_SetIntNull(@FilterMinDegree)
	SET @FilterMaxWorkYear = dbo.v2018_SetIntNull(@FilterMaxWorkYear)
	SET @FilterMinWorkYear = dbo.v2018_SetIntNull(@FilterMinWorkYear)
	SET @FilterMaxAge = dbo.v2018_SetIntNull(@FilterMaxAge)
	SET @FilterMinAge = dbo.v2018_SetIntNull(@FilterMinAge)
	SET @FilterGender = dbo.v2018_SetIntNull(@FilterGender)

	DECLARE @NameOld NVARCHAR(60), @ResponsibilityOld VARCHAR(MAX), @DemandOld VARCHAR(MAX)
	--BEGIN TRY
		IF @ID > 0
		BEGIN
			SELECT 
				@NameOld = [Name],
				@ResponsibilityOld = Responsibility, 
				@DemandOld = Demand
			FROM Job WITH(NOLOCK)
			WHERE ID = @ID

			UPDATE Job SET
				[Name] = @Name,
				dcJobTypeID = @dcJobTypeID,
				dcJobTypeIDMinor = @dcJobTypeIDMinor,
				NeedNumber = @NeedNumber,
				dcSalaryID = @dcSalaryID,
				dcSalaryIdMax = @dcSalaryMaxID,
				Negotiable = @Negotiable,
				EmployType = @EmployType,
				dcRegionID = @dcRegionID,
				Lng = @Lng,
				Lat = @Lat,
				Responsibility = @Responsibility,
				Demand = @Demand,
				dcEducationID = @dcEducationID,
				MinExperience = @MinExperience,
				MinAge = @MinAge,
				MaxAge = @MaxAge,
				EMailSendFreq = @EMailSendFreq,
				RefreshDate = GETDATE(),
				LastModifyDate = GETDATE(),
				FilterMaxDegree = @FilterMaxDegree,
				FilterMinDegree = @FilterMinDegree,
				FilterMaxWorkYear = @FilterMaxWorkYear,
				FilterMinWorkYear = @FilterMinWorkYear,
				FilterMaxAge = @FilterMaxAge,
				FilterMinAge = @FilterMinAge,
				FilterGender = @FilterGender,
				FilterJobRegion = @FilterJobRegion,
				ForwardEmail = @ForwardEmail,
				Promotion = @Promotion
			WHERE ID = @ID
		END
		ELSE
		BEGIN
			INSERT INTO Job
			(
				cpMainID, caMainID, Name, dcJobTypeID, dcJobTypeIDMinor, 
				NeedNumber, dcSalaryID, EmployType, dcRegionID, Lng, Lat, 
				Responsibility, Demand, dcEducationID, MinExperience, 
				MinAge, MaxAge, EMailSendFreq, 
				AddDate, LastModifyDate, RefreshDate, IssueDate, IssueEnd,
				FilterMaxDegree, FilterMinDegree, FilterMaxWorkYear, FilterMinWorkYear, 
				FilterMaxAge, FilterMinAge, FilterGender, FilterJobRegion, 
				ForwardEmail, dcSalaryIdMax, Negotiable, Promotion
			)
			VALUES
			(
				@cpMainID, @caMainID, @Name, @dcJobTypeID, @dcJobTypeIDMinor, 
				@NeedNumber, @dcSalaryID, @EmployType, @dcRegionID, @Lng, @Lat, 
				@Responsibility, @Demand, @dcEducationID, @MinExperience, 
				@MinAge, @MaxAge, dbo.BinToINT(@EMailSendFreq), 
				GETDATE(), GETDATE(), GETDATE(), DATEADD(MINUTE, -1, GETDATE()), DATEADD(MINUTE, -1, GETDATE()),
				@FilterMaxDegree, @FilterMinDegree, @FilterMaxWorkYear, @FilterMinWorkYear, 
				@FilterMaxAge, @FilterMinAge, @FilterGender, @FilterJobRegion, 
				@ForwardEmail, @dcSalaryMaxID, @Negotiable, @Promotion
			)
			SET @ID = SCOPE_IDENTITY()
		END
		--添加审核记录
		EXEC v2018_ccCpModifyInsert @cpMainID, @caMainID, @ID, @Name, @NameOld, 'c1'
		EXEC v2018_ccCpModifyInsert @cpMainID, @caMainID, @ID, @Responsibility, @ResponsibilityOld, 'c2'
		EXEC v2018_ccCpModifyInsert @cpMainID, @caMainID, @ID, @Demand, @DemandOld, 'c3'
		--更新福利待遇
		CREATE TABLE #Welfare
		(
			ID INT IDENTITY,
			Welfare CHAR(1)
		)
		INSERT INTO #Welfare(Welfare)
		SELECT a FROM dbo.Split(@Welfare,'@')
		UPDATE Job SET
			Welfare1 = (SELECT Welfare FROM #Welfare WHERE ID = 1),
			Welfare2 = (SELECT Welfare FROM #Welfare WHERE ID = 2),
			Welfare3 = (SELECT Welfare FROM #Welfare WHERE ID = 3),
			Welfare4 = (SELECT Welfare FROM #Welfare WHERE ID = 4),
			Welfare5 = (SELECT Welfare FROM #Welfare WHERE ID = 5),
			Welfare6 = (SELECT Welfare FROM #Welfare WHERE ID = 6),
			Welfare7 = (SELECT Welfare FROM #Welfare WHERE ID = 7),
			Welfare8 = (SELECT Welfare FROM #Welfare WHERE ID = 8),
			Welfare9 = (SELECT Welfare FROM #Welfare WHERE ID = 9),
			Welfare10 = (SELECT Welfare FROM #Welfare WHERE ID = 10),
			Welfare11 = (SELECT Welfare FROM #Welfare WHERE ID = 11),
			Welfare12 = (SELECT Welfare FROM #Welfare WHERE ID = 12),
			Welfare13 = (SELECT Welfare FROM #Welfare WHERE ID = 13),
			Welfare14 = (SELECT Welfare FROM #Welfare WHERE ID = 14),
			Welfare15 = (SELECT Welfare FROM #Welfare WHERE ID = 15),
			Welfare16 = (SELECT Welfare FROM #Welfare WHERE ID = 16),
			Welfare17 = (SELECT Welfare FROM #Welfare WHERE ID = 17),
			Welfare18 = (SELECT Welfare FROM #Welfare WHERE ID = 18),
			Welfare19 = (SELECT Welfare FROM #Welfare WHERE ID = 19)
		WHERE ID = @ID
		DROP TABLE #Welfare
		--更新职位诱惑
		DELETE FROM JobTags WHERE JobID = @ID
		IF LEN(@JobTags) > 0
		BEGIN
			CREATE TABLE #Tags
			(
				ID INT IDENTITY,
				Tags NVARCHAR(10),
				VerifyDate SMALLDATETIME
			)
			INSERT INTO #Tags(Tags)
			SELECT a FROM dbo.Split(@JobTags,'@')
			--最多5个
			DELETE FROM #Tags WHERE ID > 5
			--审核过的不再重新审核
			UPDATE #Tags SET
				VerifyDate = GETDATE()
			WHERE EXISTS(
				SELECT TOP 1 'X' 
				FROM JobTags WITH(NOLOCK) 
				WHERE Tags = #Tags.Tags 
					AND VerifyDate IS NOT NULL
				ORDER BY ID
			)
			--插入
			INSERT INTO JobTags(JobID, Tags, VerifyDate)
			SELECT @ID, Tags, VerifyDate FROM #Tags
			DROP TABLE #Tags
		END

	--END TRY
	--BEGIN CATCH
	--	GOTO ERR
	--END CATCH
--COMMIT TRAN

--发布职位
BEGIN
	DECLARE @Return INT
	EXEC @Return = v2018_ccJobIssue @cpMainID, @ID, @IssueEnd, @IP
	IF @Return = 0
		RETURN -2
END
RETURN @ID
ERR:
BEGIN
	--ROLLBACK TRAN
	RETURN 0
END
SET NOCOUNT OFF

GO

/****** Object:  StoredProcedure [dbo].[v2018_ccJobTemplateSave]    Script Date: 2018/12/13 19:13:31 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2018.11.6
--创建人：Lucifer
--说明：保存职位模板
--返回值：  0 保存失败
--         >0 保存成功
--#####################################################
CREATE PROCEDURE [dbo].[v2018_ccJobTemplateSave]
(
	@ID INT,
	@cpMainID INT,
	@caMainID INT,
	@Name VARCHAR(50),
	@dcJobTypeID INT,
	@dcJobTypeIDMinor INT,
	@NeedNumber SMALLINT,
	@dcSalaryID TINYINT,
	@dcSalaryMaxID TINYINT,
	@Negotiable BIT,
	@EmployType TINYINT,
	@dcRegionID VARCHAR(6),
	@Lng DECIMAL(8, 5),
	@Lat DECIMAL(8, 5),
	@Responsibility VARCHAR(MAX),
	@Demand VARCHAR(MAX),
	@dcEducationID TINYINT,
	@MinExperience TINYINT,
	@MinAge TINYINT,
	@MaxAge TINYINT,
	@EMailSendFreq INT,
	@EMailSendNumber TINYINT,
	@Promotion NVARCHAR(100),
	@JobTags VARCHAR(MAX),
	@Welfare VARCHAR(100)
)
AS
SET NOCOUNT ON
--BEGIN TRAN
	SET @Name = dbo.v2018_SetVarcharNull(@Name)
	SET @Demand = dbo.v2018_SetVarcharNull(@Demand)
	SET @Responsibility = dbo.v2018_SetVarcharNull(@Responsibility)
	SET @Promotion = dbo.v2018_SetVarcharNull(@Promotion)
	SET @Welfare = dbo.v2018_SetVarcharNull(@Welfare)

	SET @dcJobTypeIDMinor = dbo.v2018_SetIntNull(@dcJobTypeIDMinor)
	SET @MinAge = dbo.v2018_SetIntNull(@MinAge)
	SET @MaxAge = dbo.v2018_SetIntNull(@MaxAge)
	SET @EMailSendNumber = dbo.v2018_SetIntNull(@EMailSendNumber)

	--BEGIN TRY
		IF @ID > 0
		BEGIN
			UPDATE JobTemplate SET
				[Name] = @Name,
				dcJobTypeID = @dcJobTypeID,
				dcJobTypeIDMinor = @dcJobTypeIDMinor,
				NeedNumber = @NeedNumber,
				dcSalaryID = @dcSalaryID,
				dcSalaryIdMax = @dcSalaryMaxID,
				Negotiable = @Negotiable,
				EmployType = @EmployType,
				dcRegionID = @dcRegionID,
				Lng = @Lng,
				Lat = @Lat,
				Responsibility = @Responsibility,
				Demand = @Demand,
				dcEducationID = @dcEducationID,
				MinExperience = @MinExperience,
				MinAge = @MinAge,
				MaxAge = @MaxAge,
				EMailSendFreq = @EMailSendFreq,
				LastModifyDate = GETDATE(),
				Promotion = @Promotion,
				JobTags = @JobTags
			WHERE ID = @ID
		END
		ELSE
		BEGIN
			INSERT INTO JobTemplate
			(
				cpMainID, caMainID, Name, dcJobTypeID, dcJobTypeIDMinor, 
				NeedNumber, dcSalaryID, EmployType, dcRegionID, Lng, Lat, 
				Responsibility, Demand, dcEducationID, MinExperience, 
				MinAge, MaxAge, EMailSendFreq, 
				AddDate, LastModifyDate,
				dcSalaryIdMax, Negotiable, Promotion, JobTags
			)
			VALUES
			(
				@cpMainID, @caMainID, @Name, @dcJobTypeID, @dcJobTypeIDMinor, 
				@NeedNumber, @dcSalaryID, @EmployType, @dcRegionID, @Lng, @Lat, 
				@Responsibility, @Demand, @dcEducationID, @MinExperience, 
				@MinAge, @MaxAge, dbo.BinToINT(@EMailSendFreq), 
				GETDATE(), GETDATE(),
				@dcSalaryMaxID, @Negotiable, @Promotion, @JobTags
			)
			SET @ID = SCOPE_IDENTITY()
		END
		--更新福利待遇
		CREATE TABLE #Welfare
		(
			ID INT IDENTITY,
			Welfare CHAR(1)
		)
		INSERT INTO #Welfare(Welfare)
		SELECT a FROM dbo.Split(@Welfare,'@')
		UPDATE JobTemplate SET
			Welfare1 = (SELECT Welfare FROM #Welfare WHERE ID = 1),
			Welfare2 = (SELECT Welfare FROM #Welfare WHERE ID = 2),
			Welfare3 = (SELECT Welfare FROM #Welfare WHERE ID = 3),
			Welfare4 = (SELECT Welfare FROM #Welfare WHERE ID = 4),
			Welfare5 = (SELECT Welfare FROM #Welfare WHERE ID = 5),
			Welfare6 = (SELECT Welfare FROM #Welfare WHERE ID = 6),
			Welfare7 = (SELECT Welfare FROM #Welfare WHERE ID = 7),
			Welfare8 = (SELECT Welfare FROM #Welfare WHERE ID = 8),
			Welfare9 = (SELECT Welfare FROM #Welfare WHERE ID = 9),
			Welfare10 = (SELECT Welfare FROM #Welfare WHERE ID = 10),
			Welfare11 = (SELECT Welfare FROM #Welfare WHERE ID = 11),
			Welfare12 = (SELECT Welfare FROM #Welfare WHERE ID = 12),
			Welfare13 = (SELECT Welfare FROM #Welfare WHERE ID = 13),
			Welfare14 = (SELECT Welfare FROM #Welfare WHERE ID = 14),
			Welfare15 = (SELECT Welfare FROM #Welfare WHERE ID = 15),
			Welfare16 = (SELECT Welfare FROM #Welfare WHERE ID = 16),
			Welfare17 = (SELECT Welfare FROM #Welfare WHERE ID = 17),
			Welfare18 = (SELECT Welfare FROM #Welfare WHERE ID = 18),
			Welfare19 = (SELECT Welfare FROM #Welfare WHERE ID = 19)
		WHERE ID = @ID
		DROP TABLE #Welfare
	--END TRY
	--BEGIN CATCH
	--	GOTO ERR
	--END CATCH
--COMMIT TRAN
RETURN 1
ERR:
BEGIN
	--ROLLBACK TRAN
	RETURN 0
END
SET NOCOUNT OFF
GO

/****** Object:  StoredProcedure [dbo].[v2018_ColdCustomerSaveQlrc]    Script Date: 2018/12/13 19:13:32 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--###############################################
--添加人：Alen
--添加时间：2018-10-9
--描述：插入冷客户采集（齐鲁人才网 2年未登录、已上传营业执照、无顾问）
--1周执行1次
--###############################################
CREATE PROCEDURE [dbo].[v2018_ColdCustomerSaveQlrc]  
AS
BEGIN
	INSERT INTO precoldcustomer(SourceType,State,CompanyName,LinkMan,Phone,Email,SourceLink,[Address],QQ, AddDate,Tel,IsSpread)
	SELECT 8,0,a.name,b.Name,b.Mobile,b.EMail, LTRIM(STR(a.id)),a.Address,b.qq,getdate(),b.Telephone,1 
	FROM cpmain a WITH(NOLOCK),camain b WITH(NOLOCK) 
	WHERE a.id=b.cpmainid AND a.id IN(
		SELECT TOP 2500 id FROM (
			SELECT *,ROW_NUMBER() over( partition by Name order by LastLoginDate desc) row 
			FROM cpmain b WITH(NOLOCK) 
			WHERE HasLicence=1 
			AND ConsultantID IS NULL 
			AND LastLoginDate < dateadd(year,-2,getdate()) 
			AND NOT EXISTS (
				SELECT 'X'
				 FROM cpmain WITH(NOLOCK) 
				 WHERE dcProvinceID=b.dcProvinceID 
				 AND name = b.name 
				 AND LastLoginDate > dateadd(year,-2,getdate())
			) 
			AND NOT EXISTS(
				SELECT 'X'
				FROM preColdCustomer WITH(NOLOCK) 
				WHERE SourceType=8 
				AND CompanyName=b.Name 
			)
			AND dcprovinceid=32
		) t WHERE row=1
	)
	AND b.AccountType = 1
END
GO

/****** Object:  StoredProcedure [dbo].[v2018_mblAssessTestAnswerUpdateByAnswer]    Script Date: 2018/12/13 19:13:32 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--####################################################
--添加人：Peter
--添加时间：2018-8-20
--描述：修改个人回答记录
--####################################################
CREATE PROCEDURE [dbo].[v2018_mblAssessTestAnswerUpdateByAnswer]
(
	@PaMainID INT,
	@AnswerID INT,
	@OptionsID INT,
	@AnswerChoice VARCHAR(5)
)
AS
BEGIN
	DECLARE @AssessTestLogID INT

	SELECT @AssessTestLogID = AssessTestLogID
	FROM AssessTestAnswer WITH(NOLOCK) 
	WHERE ID = @AnswerID

	IF NOT EXISTS(
		SELECT 'x' FROM AssessTestLog WITH(NOLOCK) 
		WHERE PaMainID = @PaMainID 
		AND ID = @AssessTestLogID
	)
	BEGIN
		RETURN -1
	END

	UPDATE AssessTestAnswer 
	SET AssessOptionsID = @OptionsID,AnswerDate = GETDATE(),Choice = @AnswerChoice
	WHERE ID = @AnswerID

	IF NOT EXISTS(
		SELECT 'x' FROM AssessTestAnswer WITH(NOLOCK) 
		WHERE AssessOptionsID IS NULL 
		AND AssessTestLogID = @AssessTestLogID
	) --测评问题全部回答完毕
	BEGIN
		EXEC v2018_mblAssessTestLogUpdateByFinish @AssessTestLogID
		RETURN 0
	END
	ELSE
	BEGIN
		RETURN @AssessTestLogID
	END
END
GO

/****** Object:  StoredProcedure [dbo].[v2018_mblAssessTestLogByAnalysisSelect]    Script Date: 2018/12/13 19:13:32 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--####################################################
--添加人：Peter
--添加时间：2018-8-20
--描述：获取个人测评的详情
--####################################################
CREATE PROCEDURE [dbo].[v2018_mblAssessTestLogByAnalysisSelect]
(
	@PaMainID INT,
	@TestLogID INT
)
AS
BEGIN
	IF NOT EXISTS(SELECT 'x' FROM AssessTestLog WITH(NOLOCK) WHERE ID = @TestLogID AND PaMainID = @PaMainID AND(TextResult IS NOT NULL OR ScoreResult IS NOT NULL))
	BEGIN
		RETURN 
	END

	DECLARE @ResultType TINYINT

	SELECT @ResultType = ResultType
	FROM AssessType WITH(NOLOCK)
	WHERE ID = (
		SELECT AssessTypeID 
		FROM AssessTestLog WITH(NOLOCK)
		WHERE ID = @TestLogID
	)

	IF @ResultType = 1
	BEGIN
		SELECT a.*,b.ReportHtml,CONVERT(NVARCHAR(MAX),'') ReportHtmlSecond,b.AttachmentFile,b.Title,c.NeedTime
		INTO #T
		FROM AssessTestLog a WITH(NOLOCK)
		LEFT JOIN AssessTypeResult b WITH(NOLOCK) ON b.TextResult = a.TextResult AND b.AssessTypeID = a.AssessTypeID
		LEFT JOIN AssessType c WITH(NOLOCK) ON c.id = a.AssessTypeID 
		WHERE a.ID = @TestLogID

		UPDATE a
		SET a.ReportHtmlSecond = b.ReportHtml
		FROM #T a,AssessTypeResult b WITH(NOLOCK)
		WHERE b.TextResult = LEFT(a.TextResult,1) 
		AND b.AssessTypeID = a.AssessTypeID
		AND a.AssessTypeID = 3
		AND LEN(a.TextResult)>1

		SELECT * FROM #T

		DROP TABLE #T
	END
	
	SELECT a.*,c.ShortName,b.Score,d.AssessDimensionGroupID,e.Shortname GroupShortName,e.Name GroupName
	FROM AssessTestAnswer a WITH(NOLOCK)
	LEFT JOIN AssessOptions b WITH(NOLOCK) ON b.ID = a.AssessOptionsID
	LEFT JOIN AssessDimension c WITH(NOLOCK) ON c.ID = b.AssessDimensionID
	LEFT JOIN AssessQuestion d WITH(NOLOCK) ON d.ID = a.AssessQuestionID
	LEFT JOIN AssessDimensionGroup e WITH(NOLOCK) ON e.id = d.AssessDimensionGroupID
	WHERE a.AssessTestLogID = @TestLogID
END
GO

/****** Object:  StoredProcedure [dbo].[v2018_mblAssessTestLogInsert]    Script Date: 2018/12/13 19:13:33 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--####################################################
--添加人：Peter
--添加时间：2018-8-17
--描述：根据CpInviteID和AssessTypeID 插入一条测试记录
--####################################################
CREATE PROCEDURE [dbo].[v2018_mblAssessTestLogInsert]
(
	@PaMainID INT,
	@CpInviteID INT,
	@AssessTypeID INT
)
AS
BEGIN
	IF @PaMainID = 0
		RETURN 0

	DECLARE @AssessTestLogID INT
	IF @CpInviteID > 0
	BEGIN
		SELECT @AssessTestLogID = ISNULL(ID,0) 
		FROM AssessTestLog WITH(NOLOCK) 
		WHERE AssessCpInviteID = @CpInviteID 
		AND PaMainID = @PaMainID

		IF @AssessTestLogID > 0
		BEGIN
			RETURN @AssessTestLogID
		END
		
		SELECT @AssessTypeID = ISNULL(AssessTypeID,0)
		FROM AssessCpInvite WITH(NOLOCK)
		WHERE ID = @CpInviteID
		AND PaMainID = @PaMainID
	END
	ELSE
	BEGIN
		IF EXISTS(SELECT 'x' FROM AssessTestLog WITH(NOLOCK) WHERE PaMainID = @PaMainID AND AssessCpInviteID IS NULL AND AssessTypeID = @AssessTypeID) AND @CpInviteID = 0
		BEGIN
			DECLARE @ReMainDays INT,@Status TINYINT,@TestLogIDBefore INT
		
			SELECT TOP 1 @Status = Status,@ReMainDays = DATEDIFF(DAY,BeginTime,GETDATE()),@TestLogIDBefore=ID
			FROM AssessTestLog WITH(NOLOCK) 
			WHERE PaMainID = @PaMainID 
			AND AssessCpInviteID IS NULL
			AND AssessTypeID = @AssessTypeID
			ORDER BY BeginTime DESC

			IF @Status = 1
			BEGIN
				RETURN @TestLogIDBefore
			END

			IF @ReMainDays < (SELECT TOP 1 ReTestDay FROM AssessType WITH(NOLOCK) WHERE ID = @AssessTypeID)
			BEGIN
				RETURN -2
			END
		END
	END

	IF @AssessTypeID = 0
		RETURN -1

	--权限判断 是否可以进行测评。
	IF dbo.v2018_CheckHasCompleteCv(@PaMainID) = 0
		RETURN -3
	
	IF @CpInviteID = 0
		SET @CpInviteID = NULL

	INSERT INTO AssessTestLog(PaMainID,AssessTypeID,AssessCpInviteID,BeginTime,RemainSeconds,LeaveTimes,IsOpen,Status)
	SELECT @PaMainID,@AssessTypeID,@CpInviteID,GETDATE(),NeedTime*60,-1,1,1
	FROM AssessType WITH(NOLOCK)
	WHERE ID = @AssessTypeID

	SELECT @AssessTestLogID = @@IDENTITY

	CREATE TABLE #T(
		AssessQuestionID INT,
		AssessDimensionGroupID INT,
		AssessThemeID INT,
		SortNo INT,
		RowNo INT
	)

	DECLARE @AssessThemeID INT,@AssessThemeSortType INT
	DECLARE cur_AssessTheme CURSOR FOR
		SELECT ID,SortType
		FROM AssessTheme WITH(NOLOCK)
		WHERE AssessTypeID = @AssessTypeID
	FOR READ ONLY

	OPEN cur_AssessTheme

	FETCH NEXT FROM cur_AssessTheme INTO @AssessThemeID,@AssessThemeSortType

	WHILE @@FETCH_STATUS = 0
	BEGIN
		IF @AssessThemeSortType = 1 --随机排序
		BEGIN
			SELECT ID,AssessDimensionGroupID,AssessThemeID,SortNo
				,ROW_NUMBER () OVER (PARTITION BY AssessDimensionGroupID ORDER BY NEWID() ASC) RowNo
			INTO #TQuestion
			FROM AssessQuestion WITH(NOLOCK)
			WHERE AssessThemeID = @AssessThemeID

			IF @AssessTypeID = 1 --MBTI特殊处理，因为分组1数量少10个
			BEGIN
				UPDATE #TQuestion
				SET RowNo = RowNo*2-1
				WHERE AssessDimensionGroupID = 1 
			END

			INSERT INTO #T
			SELECT * FROM #TQuestion
			ORDER BY RowNo ASC,AssessDimensionGroupID ASC

			DROP TABLE #TQuestion
		END
		ELSE
		BEGIN
			INSERT INTO #T
			SELECT ID,AssessDimensionGroupID,AssessThemeID,SortNo
				,ROW_NUMBER () OVER (PARTITION BY AssessDimensionGroupID ORDER BY SortNo ASC,ID ASC)
			FROM AssessQuestion WITH(NOLOCK)
			WHERE AssessThemeID = @AssessThemeID
		END
		FETCH NEXT FROM cur_AssessTheme INTO @AssessThemeID,@AssessThemeSortType
	END

	CLOSE cur_AssessTheme
	DEALLOCATE cur_AssessTheme

	INSERT INTO AssessTestAnswer(AssessTestLogID,AssessQuestionID)
	SELECT @AssessTestLogID,AssessQuestionID
	FROM #T

	DROP TABLE #T

	RETURN @AssessTestLogID
END
GO

/****** Object:  StoredProcedure [dbo].[v2018_mblAssessTestLogUpdateByFinish]    Script Date: 2018/12/13 19:13:33 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--####################################################
--添加人：Peter
--添加时间：2018-8-20
--描述：结束测评并且打分
--####################################################
CREATE PROCEDURE [dbo].[v2018_mblAssessTestLogUpdateByFinish]
(
	@TestLogID INT
)
AS
BEGIN
	--根据不同的测评类型进行评分
	DECLARE @ResultType INT,@AssessTypeID INT
	DECLARE @FinishStatus TINYINT

	SELECT @AssessTypeID = AssessTypeID
	FROM AssessTestLog WITH(NOLOCK)
	WHERE ID = @TestLogID

	SELECT @ResultType = ResultType
	FROM AssessType WITH(NOLOCK)
	WHERE ID = @AssessTypeID

	IF @ResultType = 1  --文本式计分规则
	BEGIN
		IF EXISTS(	--是否正常完成了所有的问题
			SELECT 'x' FROM AssessTestAnswer a WITH(NOLOCK)
			LEFT JOIN AssessQuestion b WITH(NOLOCK) ON b.id = a.AssessquestionID
			LEFT JOIN AssessDimensionGroup c WITH(NOLOCK) ON c.id = b.AssessDimensionGroupid
			WHERE a.AssessOptionsID IS NOT NULL
			GROUP BY c.id
			HAVING COUNT(1) = 0
		)
		BEGIN
			SET @FinishStatus = 3
		END
		ELSE
		BEGIN
			SET @FinishStatus = 2

			DECLARE @Result VARCHAR(10)
			SET @Result = ''

			IF @AssessTypeID = 1 --MBTI计算规则。
			BEGIN
				--分组查询到临时表中
				SELECT AssessDimensionGroupID,ID DimensionID,ShortName,
					(	
						SELECT COUNT(1) 
						FROM AssessTestAnswer WITH(NOLOCK)
						WHERE AssessOptionsID IS NOT NULL
						AND AssessOptionsID IN(
							SELECT ID 
							FROM AssessOptions WITH(NOLOCK)
							WHERE AssessDimensionID = AssessDimension.ID
						)
						AND AssessTestLogID = @TestLogID
					) AnswerCount
				INTO #T
				FROM AssessDimension WITH(NOLOCK)
				WHERE AssessDimensionGroupID IN(
					SELECT ID 
					FROM AssessDimensionGroup WITH(NOLOCK)
					WHERE AssessTypeID = @AssessTypeID
				)

				SELECT *,ROW_NUMBER() OVER(PARTITION BY AssessDimensionGroupID ORDER BY AnswerCount DESC,DimensionID ASC) RowNum
				INTO #T2
				FROM #T

				--拼接结果
				SELECT @Result = @Result + ShortName
				FROM #T2
				WHERE RowNum = 1

				DROP TABLE #T
				DROP TABLE #T2
			END
			ELSE IF @AssessTypeID = 2  --霍兰德计分规则
			BEGIN
				SELECT a.*,b.Score,d.shortname 
				INTO #T3
				FROM AssessTestAnswer a WITH(NOLOCK) 
				LEFT JOIN AssessOptions b WITH(NOLOCK) ON b.id = a.AssessOptionsID 
				LEFT JOIN AssessQuestion c WITH(NOLOCK) ON c.id = a.AssessQuestionID 
				LEFT JOIN AssessDimensionGroup d WITH(NOLOCK) ON d.id = c.AssessDimensionGroupID 
				WHERE AssessTestLogID = @TestLogID

				SELECT ShortName,SUM(Score) Score,0 AScoreCnt,0 BScoreCnt,0 ShortOrder
				INTO #T4
				FROM #T3
				GROUP BY ShortName

				DELETE FROM #T4
				WHERE Score < (SELECT MAX(Score) FROM #T4)

				IF(SELECT COUNT(1) FROM #T4) = 1
				BEGIN
					SELECT @Result = ShortName
					FROM #T4
				END
				ELSE
				BEGIN
					UPDATE #T4
					SET AScoreCnt = (
						SELECT COUNT(1) 
						FROM #T3
						WHERE Choice = 'A'
						AND Score = 1
						AND shortname = #T4.ShortName
					),
					BScoreCnt = (
						SELECT COUNT(1) 
						FROM #T3
						WHERE Choice = 'B'
						AND Score = 1
						AND shortname = #T4.ShortName
					),
					ShortOrder = 
						CASE ShortName 
							WHEN 'C' THEN 0
							WHEN 'R' THEN 1
							WHEN 'I' THEN 2
							WHEN 'E' THEN 3
							WHEN 'S' THEN 4
							WHEN 'A' THEN 5
							ELSE 99
						END

					SELECT TOP 1 @Result = ShortName
					FROM #T4 
					ORDER BY AScoreCnt ASC,BScoreCnt DESC,ShortOrder ASC
				END

				DROP TABLE #T3
				DROP TABLE #T4
			END
			ELSE IF @AssessTypeID = 3  --DISC计分规则
			BEGIN
				SELECT a.*,c.ShortName
				INTO #T5
				FROM AssessTestAnswer a WITH(NOLOCK) 
				LEFT JOIN AssessOptions b WITH(NOLOCK) ON b.id = a.AssessOptionsID 
				LEFT JOIN AssessDimension c WITH(NOLOCK) ON c.id = b.AssessDimensionID 
				WHERE AssessTestLogID = @TestLogID
				AND a.AssessOptionsID IS NOT NULL

				SELECT ShortName,COUNT(1) Cnt
				INTO #T6
				FROM #T5
				GROUP BY ShortName
				
				SELECT TOP 1 @Result = a.ShortName
				FROM #T6 a
				LEFT JOIN AssessDimension b WITH(NOLOCK) ON b.ShortName = a.ShortName AND AssessDimensionGroupID = 11
				ORDER BY Cnt DESC,b.ID ASC

				IF NOT EXISTS(SELECT 'x' FROM #T6 WHERE Cnt >= 10)
				BEGIN
					SET @FinishStatus = 3
				END
				ELSE
				BEGIN
					DELETE FROM #T6
					WHERE Cnt < 10 OR ShortName = @Result

					SELECT @Result = @Result + a.ShortName
					FROM #T6 a
					LEFT JOIN AssessDimension b WITH(NOLOCK) ON b.ShortName = a.ShortName AND AssessDimensionGroupID = 11
					ORDER BY b.ID ASC
				END

				DROP TABLE #T5
				DROP TABLE #T6
			END

			UPDATE Assesstestlog
			SET TextResult = @Result
			WHERE ID = @TestLogID
		END
	END
	
	--修改测评状态
	UPDATE Assesstestlog
	SET Status = @FinishStatus,EndTime = GETDATE()
	WHERE ID = @TestLogID

	RETURN 1
END
GO

/****** Object:  StoredProcedure [dbo].[v2018_pcCaCvIntentionSelect]    Script Date: 2018/12/13 19:13:34 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--################################################################
--创建人：Lucifer
--创建时间：2018-7-23
--描述：获取个人应聘邀请列表
--################################################################
CREATE PROCEDURE [dbo].[v2018_pcCaCvIntentionSelect]
(
    @Where VARCHAR(1000), 
    @Order VARCHAR(100)
)
AS
SET NOCOUNT ON
BEGIN
    SET @Where = dbo.SafeSQL(@Where)
    SET @Order = dbo.SafeSQL(@Order)
    DECLARE @SQL AS VARCHAR(2000)
    SET @SQL = 'SELECT JobID, cvMainID, a.AddDate, b.Name as JobName, b.IssueDate, b.IssueEnd, Reply, ReplyDate, d.Name cvName, 
            b.dcRegionID, b.IsDelete, c.Name as cpName, c.ID as cpID, c.HasLicence, c.IsAgent, c.MemberType, a.ID, 
            b.dcSalaryId, b.dcSalaryIdMax, b.SecondId EnJobID, c.SecondId EnCpMainID, dbo.GetCaOnlineStatus(b.caMainID) AS IsOnline,
            b.Welfare1, b.Welfare2, b.Welfare3, b.Welfare4, b.Welfare5, b.Welfare6, b.Welfare7, b.Welfare8, 
            b.Welfare9, b.Welfare10, b.Welfare11, b.Welfare12, b.Welfare13, b.Welfare14, b.Welfare15, b.Welfare16, 
            b.Welfare17, b.Welfare18, b.Welfare19, c.ReplyRate, c.LogoFile LogoUrl, b.CaMainID, b.Valid JobValid,
			dbo.GetCvMatch(a.cvMainID, a.JobID) cvMatch,
			(SELECT COUNT(1) FROM exJobApply WHERE cvMainId = a.cvMainId AND JobId = a.JobId) IsApply
            FROM caCvIntention a WITH(NOLOCK)
            INNER JOIN Job b WITH(NOLOCK) ON a.JobID = b.ID 
            INNER JOIN cpMain c WITH(NOLOCK) ON b.cpMainID = c.ID
            INNER JOIN cvMain d WITH(NOLOCK) ON a.cvMainID = d.ID
        WHERE PersonDeleted = 0'

    IF LEN(@Where) > 0
        SET @SQL = @SQL + ' AND ' + @Where

    IF LEN(@Order) > 0
        SET @SQL = @SQL + ' ORDER BY '+@Order

    EXEC(@SQL)
END
SET NOCOUNT OFF
GO

/****** Object:  StoredProcedure [dbo].[v2018_pcCaCvViewLogSelect]    Script Date: 2018/12/13 19:13:34 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--################################################################
--创建人：Lucifer
--创建时间：2018-7-23
--描述：谁在关注我
--################################################################
CREATE PROCEDURE [dbo].[v2018_pcCaCvViewLogSelect]
(
	@cvMainIds VARCHAR(1000),
	@Page SMALLINT
)
AS
SET NOCOUNT ON
BEGIN
	IF @cvMainIds = ''
		RETURN

	SET @cvMainIds = dbo.FormatIDS(@cvMainIds)

	SELECT ROW_NUMBER() OVER(ORDER BY AddDate DESC) TitleID, caMainId, cvMainId, AddDate, NULL JobId , 0 IsApply 
	INTO #1
	FROM caCvviewLog WITH(NOLOCK INDEX(IX_caCvViewLog_cvMainID))
	WHERE cvMainId IN(SELECT a FROM dbo.fnSplit(@cvMainIds, ','))
	AND EXISTS(SELECT TOP 1 'X' FROM JobPublish WITH(NOLOCK) WHERE caMainID = caCvviewLog.caMainID)

	SELECT * INTO #T
	FROM #1
	WHERE TitleID > (@Page - 1) * 20 AND TitleID <= @Page * 20
        
    UPDATE #T SET IsApply = 1
    WHERE EXISTS(
		SELECT TOP 1 'X' FROM exJobApply a WITH(NOLOCK), JobPublish b WITH(NOLOCK)
		WHERE a.JobID = b.ID AND a.cvMainID = #T.cvMainID AND b.caMainID = #T.caMainID
	)

	UPDATE #T SET JobId = (SELECT TOP 1 a.ID FROM JobPublish a WITH(NOLOCK), caMain b WITH(NOLOCK), cpMainPublish c WITH(NOLOCK)
	WHERE a.cpMainId = b.cpMainID AND b.cpMainID = c.ID AND a.dcJobTypeId IN(SELECT dcJobTypeID FROM cvJobType WITH(NOLOCK) WHERE cvMainId = #T.cvMainId)
		AND b.Id = #T.caMainID ORDER BY a.RefreshDate DESC)
		
	UPDATE #T SET JobId = (SELECT TOP 1 a.ID FROM JobPublish a WITH(NOLOCK), caMain b WITH(NOLOCK), cpMainPublish c WITH(NOLOCK)
	WHERE a.cpMainId = b.cpMainID AND b.cpMainID = c.ID AND LEFT(a.dcJobTypeId, 2) IN(SELECT dcJobTypeID FROM cvJobType WITH(NOLOCK) WHERE cvMainId = #T.cvMainId)
		AND b.Id = #T.caMainID ORDER BY a.RefreshDate DESC) WHERE JobId IS NULL
	
	UPDATE #T SET JobId = (SELECT TOP 1 a.ID FROM JobPublish a WITH(NOLOCK), caMain b WITH(NOLOCK), cpMainPublish c WITH(NOLOCK)
	WHERE a.cpMainId = b.cpMainID AND b.cpMainID = c.ID
		AND b.Id = #T.caMainID ORDER BY a.RefreshDate DESC) WHERE JobId IS NULL
	
	SELECT a.caMainId, a.cvMainId, a.AddDate, b.Name as caName, d.*, d.Id JobId, d.Name JobName, 
		d.SecondId EnJobId, d.Valid JobValid,
		b.Email, b.Mobile, b.Telephone, b.Gender, b.IsPhoneHide, b.IsNameHide, b.IsMobileHide, 
		c.Name cpName, c.Address, c.ID cpID, c.HasLicence, c.IsAgent, e.Name cvName, 
		c.Membertype, c.dcRegionId, c.SecondId EnCpMainID, c.LogoFile LogoUrl, dbo.GetCaOnlineStatus(b.ID) IsOnline,
		(SELECT COUNT(1) FROM exJobApply WHERE cvMainId = a.cvMainId AND JobId = a.JobId) IsApply
	FROM #T a WITH(NOLOCK)
	INNER JOIN caMain b WITH(NOLOCK) ON a.caMainID = b.ID
	INNER JOIN cpMain c WITH(NOLOCK) ON c.ID = b.cpMainId
	INNER JOIN cvMain e WITH(NOLOCK) ON a.cvMainId = e.Id
	INNER JOIN JobPublish d WITH(NOLOCK) ON a.JobId = d.Id
	
	SELECT COUNT(1) FROM #1
END 
SET NOCOUNT OFF
GO

/****** Object:  StoredProcedure [dbo].[v2018_pcChatOnLineByPaMainIDSelect]    Script Date: 2018/12/13 19:13:34 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--####################################
--添加人：Lucifer
--添加时间：2018-7-12
--描述：获取个人聊天列表，显示最新聊天记录
--####################################
CREATE PROCEDURE [dbo].[v2018_pcChatOnLineByPaMainIDSelect]
(
    @PaMainID INT	--求职者的ID
)
AS
SET NOCOUNT ON
BEGIN	
	CREATE TABLE #ChatLog
	(
		caMainID INT,
		cvMainID INT,
		LastMessage VARCHAR(MAX),
		LastReceiverDate SMALLDATETIME,
		Initiative TINYINT
	)
	INSERT INTO #ChatLog
	SELECT 
		a.caMainID,
		a.cvMainID,
		(SELECT TOP 1 CASE MessageType
			WHEN 1 THEN [Message]
			WHEN 2 THEN '[表情]'
			WHEN 3 THEN '[图片]'
			WHEN 4 THEN '[职位]'
			WHEN 5 THEN '[面试通知]'
			ELSE '' END FROM ChatOnlineLog WITH(NOLOCK) WHERE ChatOnlineID = MAX(a.ID) ORDER BY ID DESC),
		MAX(b.Adddate),
		(SELECT Initiative FROM ChatOnline WITH(NOLOCK) WHERE ID = MIN(a.ID))
	FROM ChatOnline a WITH(NOLOCK), ChatOnlineLog b WITH(NOLOCK)
	WHERE a.ID = b.ChatOnlineID
		AND a.cvMainId IN (SELECT ID FROM cvMain WITH(NOLOCK) WHERE paMainID = @PaMainID) --当前个人用户
	GROUP BY a.caMainID, a.cvMainID

	SELECT
		a.*,
		dbo.GetCaName(b.ID) CaName,
		c.Name CpName,
		d.Name CvName,
		c.SecondID EnCpMainID,
		c.HasLicence,
		c.MemberType,
		c.IsAgent,
		dbo.GetCpLogo(c.ID) CpLogo
	FROM #ChatLog a WITH(NOLOCK), caMain b WITH(NOLOCK), cpMain c WITH(NOLOCK), cvMain d WITH(NOLOCK)
	WHERE a.caMainID = b.ID AND b.cpMainID = c.ID AND a.cvMainID = d.ID
	ORDER BY LastReceiverDate DESC
END
SET NOCOUNT OFF
GO

/****** Object:  StoredProcedure [dbo].[v2018_pcCvAppendixDelete]    Script Date: 2018/12/13 19:13:34 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2018.6.27
--创建人：Lucifer
--说明：删除证书
--#####################################################
CREATE PROCEDURE [dbo].[v2018_pcCvAppendixDelete] 
	@ID INT,
	@paMainID INT
AS
SET NOCOUNT ON
BEGIN TRAN
	BEGIN TRY
		DECLARE @cvMainID AS INT
		SELECT @cvMainID = cvMainID FROM cvAppendix WITH(NOLOCK INDEX(PK_cvAppendix)) WHERE ID = @ID
		IF NOT EXISTS(SELECT 'X' FROM cvMain WITH(NOLOCK) WHERE paMainID = @paMainID AND ID = @cvMainID)
			GOTO ERR

		DELETE FROM bsCvModify WHERE SubID = @ID AND Location LIKE 'c%'
		DELETE FROM cvAppendix WHERE ID = @ID

		IF (SELECT COUNT(1) FROM cvAppendix WITH(NOLOCK INDEX(PK_cvAppendix)) WHERE cvMainID = @cvMainID) = 0
		BEGIN
			EXEC v2018_pcCvMainByCvLevelUpdate 2, @cvMainID, 10, 0
		END
		ELSE
		BEGIN
			UPDATE cvMain SET cvLevel = cvLevel WHERE ID = @cvMainID
		END
	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH
COMMIT TRAN
RETURN 1
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END
SET NOCOUNT OFF
GO

/****** Object:  StoredProcedure [dbo].[v2018_pcCvAppendixSave]    Script Date: 2018/12/13 19:13:35 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--####################################################
--添加人：Lucifer
--添加时间：2018-6-27
--描述：保存证书
--返回值 0 失败 >0成功 -1超过最大限制
--####################################################
CREATE PROCEDURE [dbo].[v2018_pcCvAppendixSave]
(
	@ID INT,
	@cvMainID INT,
	@dcAppendixID INT,
	@Name VARCHAR(200),
	@NameEng VARCHAR(250),
	@Description NVARCHAR(200),
	@DescriptionEng VARCHAR(1000),
	@AccessDate SMALLINT,
	@paMainID INT,
	@IP VARCHAR(31)
)
AS
SET NOCOUNT ON
BEGIN TRAN
	--检查是否是该账号的简历
	IF NOT EXISTS(SELECT 'X' FROM cvMain WITH(NOLOCK) WHERE ID = @cvMainID AND paMainID = @paMainID)
		GOTO ERR
	--检查是否是该简历的证书
	IF @ID > 0
	BEGIN
		IF NOT EXISTS(SELECT 'X' FROM CvAppendix WITH(NOLOCK INDEX(PK_CvAppendix)) WHERE ID = @ID AND cvMainID = @cvMainID)
		BEGIN
			GOTO ERR
		END
	END
	
	IF EXISTS(SELECT 'X' FROM CvAppendix WITH(NOLOCK INDEX(PK_CvAppendix)) WHERE ID <> @ID AND cvMainID = @cvMainID AND dcAppendixID = @dcAppendixID AND @dcAppendixID <> 999)
		GOTO ERR

	BEGIN TRY
		SET @Name = dbo.v2018_SetVarcharNull(@Name)
		SET @NameEng = dbo.v2018_SetVarcharNull(@NameEng)
		SET @Description = dbo.v2018_SetVarcharNull(@Description)
		SET @DescriptionEng = dbo.v2018_SetVarcharNull(@DescriptionEng)

		DECLARE @NameOld VARCHAR(200)
		DECLARE @NameEngOld VARCHAR(250)
		DECLARE @DescriptionOld NVARCHAR(200)
		DECLARE @DescriptionEngOld VARCHAR(1000)

		IF @ID = 0
		BEGIN
			--证书最多10个
			IF (SELECT COUNT(1) FROM CvAppendix WITH(NOLOCK INDEX(PK_CvAppendix)) WHERE cvMainID = @cvMainID) >= 10
				GOTO ERRMAX

			INSERT INTO CvAppendix(cvMainID, dcAppendixID, [Name], NameEng, [Description], DescriptionEng, AccessDate)
			VALUES(@cvMainID, @dcAppendixID, @Name, @NameEng, @Description, @DescriptionEng, @AccessDate)

			SET @ID = @@IDENTITY
		END
		ELSE
		BEGIN
			SELECT @NameOld = [Name], @NameEngOld = NameEng,
				@DescriptionOld = [Description], @DescriptionEngOld = DescriptionEng
			FROM CvAppendix WITH(NOLOCK INDEX(PK_CvAppendix)) WHERE ID = @ID

			UPDATE CvAppendix SET
				dcAppendixID = @dcAppendixID,
				[Name] = @Name,
				NameEng = @NameEng,
				[Description] = @Description,
				DescriptionEng = @DescriptionEng,
				AccessDate = @AccessDate
			WHERE ID = @ID
		END

		--添加审核记录
		IF @dcAppendixID = 999
		BEGIN
			EXEC v2018_pcCvModifyInsert @paMainID, @cvMainID, @ID, @Name, @NameOld, 'cc1', @IP
			EXEC v2018_pcCvModifyInsert @paMainID, @cvMainID, @ID, @NameEng, @NameEngOld, 'ce1', @IP
		END		
		EXEC v2018_pcCvModifyInsert @paMainID, @cvMainID, @ID, @Description, @DescriptionOld, 'cc2', @IP
		EXEC v2018_pcCvModifyInsert @paMainID, @cvMainID, @ID, @DescriptionEng, @DescriptionEngOld, 'ce2', @IP

		--更新证书的CvLevel
		IF @Name IS NOT NULL
			EXEC v2018_pcCvMainByCvLevelUpdate 0, @cvMainID, 10, 1
	
		IF @NameEng IS NOT NULL
			EXEC v2018_pcCvMainByCvLevelUpdate 1, @cvMainID, 10, 1
	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH
COMMIT TRAN
RETURN @ID
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END
ERRMAX:
BEGIN
	ROLLBACK TRAN
	RETURN -1
END
SET NOCOUNT OFF
GO

/****** Object:  StoredProcedure [dbo].[v2018_pcCvEducationDelete]    Script Date: 2018/12/13 19:13:35 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2018.6.27
--创建人：Lucifer
--说明：删除教育背景
--#####################################################
CREATE PROCEDURE [dbo].[v2018_pcCvEducationDelete] 
	@ID INT,
	@paMainID INT
AS
SET NOCOUNT ON
BEGIN TRAN
	BEGIN TRY
		DECLARE @cvMainID AS INT
		SELECT @cvMainID = cvMainID FROM cvEducation WITH(NOLOCK INDEX(PK_cvEducation)) WHERE ID = @ID
		IF NOT EXISTS(SELECT 'X' FROM cvMain WITH(NOLOCK) WHERE paMainID = @paMainID AND ID = @cvMainID)
			GOTO ERR

		--教育背景至少保留一个，不能够全部删除
		IF (SELECT COUNT(1) FROM cvEducation WITH(NOLOCK INDEX(PK_cvEducation)) WHERE cvMainID = @cvMainID) = 1
			GOTO ERRNEED

		DELETE FROM bsCvModify WHERE SubID = @ID AND Location LIKE 'd%'
		DELETE FROM cvEducation WHERE ID = @ID

		--更新cvMain中的最高学历和专业
		EXEC v2018_pcCvMainByDegreeUpdate @cvMainID

		UPDATE cvMain SET cvLevel = cvLevel WHERE ID = @cvMainID
	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH
COMMIT TRAN
RETURN 1
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END
ERRNEED:
BEGIN
	ROLLBACK TRAN
	RETURN -1
END
SET NOCOUNT OFF
GO

/****** Object:  StoredProcedure [dbo].[v2018_pcCvEducationSave]    Script Date: 2018/12/13 19:13:35 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--####################################################
--添加人：Lucifer
--添加时间：2018-6-27
--描述：保存教育背景
--返回值 0 失败 >0成功 -1超过最大限制
--####################################################
CREATE PROCEDURE [dbo].[v2018_pcCvEducationSave]
(
	@ID INT,
	@cvMainID INT,
	@GraduateCollage NVARCHAR(50),
	@GraduateCollageEng VARCHAR(250),
	@Graduation INT,
	@dcMajorID SMALLINT,
	@MajorName NVARCHAR(20),
	@MajorNameEng VARCHAR(100),
	@Degree TINYINT,
	@EduType TINYINT,
	@Details NVARCHAR(1000),
	@DetailsEng VARCHAR(2000),
	@paMainID INT,
	@IP VARCHAR(31)
)
AS
SET NOCOUNT ON
BEGIN TRAN
	--检查是否是该账号的简历
	IF NOT EXISTS(SELECT 'X' FROM cvMain WITH(NOLOCK) WHERE ID = @cvMainID AND paMainID = @paMainID)
		GOTO ERR
	--检查是否是该简历的教育背景
	IF @ID > 0
		IF NOT EXISTS(SELECT 'X' FROM cvEducation WITH(NOLOCK INDEX(PK_cvEducation)) WHERE ID = @ID AND cvMainID = @cvMainID)
			GOTO ERR
	
	--BEGIN TRY
		SET @GraduateCollage = dbo.v2018_SetVarcharNull(@GraduateCollage)
		SET @GraduateCollageEng = dbo.v2018_SetVarcharNull(@GraduateCollageEng)
		SET	@MajorName = dbo.v2018_SetVarcharNull(@MajorName)
		SET	@MajorNameEng = dbo.v2018_SetVarcharNull(@MajorNameEng)
		SET @Details = dbo.v2018_SetVarcharNull(@Details)
		SET @DetailsEng = dbo.v2018_SetVarcharNull(@DetailsEng)

		DECLARE @GraduateCollageOld NVARCHAR(50)
		DECLARE @GraduateCollageEngOld VARCHAR(250)
		DECLARE @MajorNameOld NVARCHAR(20)
		DECLARE @MajorNameEngOld VARCHAR(100)
		DECLARE @DetailsOld NVARCHAR(1000)
		DECLARE @DetailsEngOld VARCHAR(2000)

		IF @ID = 0
		BEGIN
			--教育背景最多5个
			IF (SELECT COUNT(1) FROM cvEducation WITH(NOLOCK INDEX(PK_cvEducation)) WHERE cvMainID = @cvMainID) >= 5
				GOTO ERRMAX

			INSERT INTO cvEducation(cvMainID, GraduateCollage, GraduateCollageEng, Graduation, dcMajorID, MajorName, MajorNameEng, Degree, EduType, Details, DetailsEng)
			VALUES(@cvMainID, @GraduateCollage, @GraduateCollageEng, @Graduation, @dcMajorID, @MajorName, @MajorNameEng, @Degree, @EduType, @Details, @DetailsEng)

			SET @ID = @@IDENTITY
		END
		ELSE
		BEGIN
			SELECT @GraduateCollageOld = GraduateCollage, @GraduateCollageEngOld = GraduateCollageEng,
				@MajorNameOld = MajorName, @MajorNameEngOld = MajorNameEng,
				@DetailsOld = Details, @DetailsEngOld = DetailsEng
			FROM cvEducation WITH(NOLOCK INDEX(PK_cvEducation)) WHERE ID = @ID

			UPDATE cvEducation SET
				GraduateCollage = @GraduateCollage,
				GraduateCollageEng = @GraduateCollageEng,
				Graduation = @Graduation,
				dcMajorID = @dcMajorID,
				MajorName = @MajorName,
				MajorNameEng = @MajorNameEng,
				Degree = @Degree,
				EduType = @EduType,
				Details = @Details,
				DetailsEng = @DetailsEng
			WHERE ID = @ID
		END

		--添加审核记录
		EXEC v2018_pcCvModifyInsert @paMainID, @cvMainID, @ID, @GraduateCollage, @GraduateCollageOld, 'dc1', @IP
		EXEC v2018_pcCvModifyInsert @paMainID, @cvMainID, @ID, @GraduateCollageEng, @GraduateCollageEngOld, 'de1', @IP
		EXEC v2018_pcCvModifyInsert @paMainID, @cvMainID, @ID, @MajorName, @MajorNameOld, 'dc2', @IP
		EXEC v2018_pcCvModifyInsert @paMainID, @cvMainID, @ID, @MajorNameEng, @MajorNameEngOld, 'de2', @IP
		EXEC v2018_pcCvModifyInsert @paMainID, @cvMainID, @ID, @Details, @DetailsOld, 'dc3', @IP
		EXEC v2018_pcCvModifyInsert @paMainID, @cvMainID, @ID, @DetailsEng, @DetailsEngOld, 'de3', @IP
		
		--更新cvMain中的最高学历和专业
		EXEC v2018_pcCvMainByDegreeUpdate @cvMainID

		--更新教育背景的CvLevel
		IF @GraduateCollage IS NOT NULL
			EXEC v2018_pcCvMainByCvLevelUpdate 0, @cvMainID, 3, 1
	
		IF @GraduateCollageEng IS NOT NULL
			EXEC v2018_pcCvMainByCvLevelUpdate 1, @cvMainID, 3, 1

	--END TRY
	--BEGIN CATCH
	--	GOTO ERR
	--END CATCH
COMMIT TRAN
RETURN @ID
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END
ERRMAX:
BEGIN
	ROLLBACK TRAN
	RETURN -1
END
SET NOCOUNT OFF
GO

/****** Object:  StoredProcedure [dbo].[v2018_pcCvExperienceDelete]    Script Date: 2018/12/13 19:13:35 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2018.6.27
--创建人：Lucifer
--说明：删除工作经历
--#####################################################
CREATE PROCEDURE [dbo].[v2018_pcCvExperienceDelete] 
	@ID INT,
	@paMainID INT
AS
SET NOCOUNT ON
BEGIN TRAN
	BEGIN TRY
		DECLARE @cvMainID AS INT
		SELECT @cvMainID = cvMainID FROM cvExperience WITH(NOLOCK INDEX(PK_cvExperience)) WHERE ID = @ID
		IF NOT EXISTS(SELECT 'X' FROM cvMain WITH(NOLOCK) WHERE paMainID = @paMainID AND ID = @cvMainID)
			GOTO ERR

		DELETE FROM bsCvModify WHERE SubID = @ID AND Location LIKE 'e%'
		DELETE FROM cvExperience WHERE ID = @ID

		--如果没有工作经历，更新cvLevel
		IF (SELECT COUNT(1) FROM cvExperience WITH(NOLOCK INDEX(PK_cvExperience)) WHERE cvMainID = @cvMainID) = 0
		BEGIN
			EXEC v2018_pcCvMainByCvLevelUpdate 2, @cvMainID, 4, 0
		END
		ELSE
		BEGIN
			UPDATE cvMain SET cvLevel = cvLevel WHERE ID = @cvMainID
		END
	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH
COMMIT TRAN
RETURN 1
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END
SET NOCOUNT OFF
GO

/****** Object:  StoredProcedure [dbo].[v2018_pcCvExperienceSave]    Script Date: 2018/12/13 19:13:35 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--####################################################
--添加人：Lucifer
--添加时间：2018-6-27
--描述：保存工作经历
--返回值 0 失败 >0成功 -1超过最大限制
--####################################################
CREATE PROCEDURE [dbo].[v2018_pcCvExperienceSave]
(
	@ID INT,
	@cvMainID INT,
	@CompanyName NVARCHAR(30),
	@CompanyNameEng VARCHAR(100),
	@dcIndustryID SMALLINT,
	@dcCompanySizeID SMALLINT,
	@dcJobtypeID SMALLINT,
	@JobName NVARCHAR(20),
	@JobNameEng VARCHAR(100),
	@BeginDate INT,
	@EndDate INT,
	@SubNodeNum TINYINT,
	@Description VARCHAR(MAX),
	@DescriptionEng VARCHAR(MAX),
	@dcCompanyKindID SMALLINT,
	@WorkPlace VARCHAR(6),
	@Dept NVARCHAR(20),
	@DeptEng VARCHAR(100),
	@UpperPost NVARCHAR(20),
	@UpperPostEng VARCHAR(100),
	@dcLeaveResonID TINYINT,
	@paMainID INT,
	@IP VARCHAR(31)
)
AS
SET NOCOUNT ON
BEGIN TRAN
	----检查是否是该账号的简历
	IF NOT EXISTS(SELECT 'x' FROM cvMain WITH(NOLOCK) WHERE ID = @cvMainID AND paMainID = @paMainID)
		GOTO ERR
	----检查是否是该简历的工作经历
	IF @ID > 0
		IF NOT EXISTS(SELECT 'x' FROM cvExperience WITH(NOLOCK INDEX(PK_cvExperience)) WHERE ID = @ID AND cvMainID = @cvMainID)
			GOTO ERR

	BEGIN TRY
		SET @CompanyName = dbo.v2018_SetVarcharNull(@CompanyName)
		SET @CompanyNameEng = dbo.v2018_SetVarcharNull(@CompanyNameEng)
		SET	@JobName = dbo.v2018_SetVarcharNull(@JobName)
		SET	@JobNameEng = dbo.v2018_SetVarcharNull(@JobNameEng)
		SET @Description = dbo.v2018_SetVarcharNull(@Description)
		SET @DescriptionEng = dbo.v2018_SetVarcharNull(@DescriptionEng)
		SET @Dept = dbo.v2018_SetVarcharNull(@Dept)
		SET @DeptEng = dbo.v2018_SetVarcharNull(@DeptEng)
		SET @UpperPost = dbo.v2018_SetVarcharNull(@UpperPost)
		SET @UpperPostEng = dbo.v2018_SetVarcharNull(@UpperPostEng)
		SET @dcCompanyKindID = dbo.v2018_SetIntNull(@dcCompanyKindID)
		SET @WorkPlace = dbo.v2018_SetVarcharNull(@WorkPlace)
		SET @dcLeaveResonID = dbo.v2018_SetIntNull(@dcLeaveResonID)
		SET @dcCompanySizeID = dbo.v2018_SetIntNull(@dcCompanySizeID)

		DECLARE @CompanyNameOld NVARCHAR(30)
		DECLARE @CompanyNameEngOld VARCHAR(100)
		DECLARE @JobNameOld NVARCHAR(20)
		DECLARE @JobNameEngOld VARCHAR(100)
		DECLARE @DescriptionOld NVARCHAR(MAX)
		DECLARE @DescriptionEngOld VARCHAR(MAX)
		DECLARE @DeptOld NVARCHAR(20)
		DECLARE @DeptEngOld VARCHAR(100)
		DECLARE @UpperPostOld NVARCHAR(20)
		DECLARE @UpperPostEngOld VARCHAR(100)

		IF @ID = 0
		BEGIN
			--工作经历最多20个
			IF (SELECT COUNT(1) FROM cvExperience WITH(NOLOCK INDEX(PK_cvExperience)) WHERE cvMainID = @cvMainID) >= 20
				GOTO ERRMAX

			INSERT INTO cvExperience(cvMainID, CompanyName, CompanyNameEng, dcIndustryID, dcCompanySizeID, dcJobtypeID, JobName, JobNameEng, BeginDate, EndDate, SubNodeNum, [Description], DescriptionEng, dcCompanyKindID, WorkPlace, Dept, DeptEng, UpperPost, UpperPostEng, dcLeaveResonID)
			VALUES(@cvMainID, @CompanyName, @CompanyNameEng, @dcIndustryID, @dcCompanySizeID, @dcJobtypeID, @JobName, @JobNameEng, @BeginDate, @EndDate, @SubNodeNum, @Description, @DescriptionEng, @dcCompanyKindID, @WorkPlace, @Dept, @DeptEng, @UpperPost, @UpperPostEng, @dcLeaveResonID)

			SET @ID = @@IDENTITY
		END
		ELSE
		BEGIN
			SELECT @CompanyNameOld = CompanyName, @CompanyNameEngOld = CompanyNameEng,
				@JobNameOld = JobName, @JobNameEngOld = JobNameEng,
				@DescriptionOld = [Description], @DescriptionEngOld = DescriptionEng,
				@DeptOld = Dept, @DeptEngOld = DeptEng,
				@UpperPostOld = UpperPost, @UpperPostEngOld = UpperPostEng
			FROM cvExperience WITH(NOLOCK INDEX(PK_cvExperience)) WHERE ID = @ID

			UPDATE cvExperience SET
				CompanyName = @CompanyName,
				CompanyNameEng = @CompanyNameEng,
				dcIndustryID = @dcIndustryID,
				dcCompanySizeID = @dcCompanySizeID,
				dcJobtypeID = @dcJobtypeID,
				JobName = @JobName,
				JobNameEng = @JobNameEng,
				BeginDate = @BeginDate,
				EndDate = @EndDate,
				SubNodeNum = @SubNodeNum,
				[Description] = @Description,
				DescriptionEng = @DescriptionEng,
				dcCompanyKindID = @dcCompanyKindID,
				WorkPlace = @WorkPlace,
				Dept = @Dept,
				DeptEng = @DeptEng,
				UpperPost = @UpperPost,
				UpperPostEng = @UpperPostEng,
				dcLeaveResonID = @dcLeaveResonID
			WHERE ID = @ID
		END

		--添加审核记录
		EXEC v2018_pcCvModifyInsert @paMainID, @cvMainID, @ID, @CompanyName, @CompanyNameOld, 'ec1', @IP
		EXEC v2018_pcCvModifyInsert @paMainID, @cvMainID, @ID, @CompanyNameEng, @CompanyNameEngOld, 'ee1', @IP
		EXEC v2018_pcCvModifyInsert @paMainID, @cvMainID, @ID, @JobName, @JobNameOld, 'ec2', @IP
		EXEC v2018_pcCvModifyInsert @paMainID, @cvMainID, @ID, @JobNameEng, @JobNameEngOld, 'ee2', @IP
		EXEC v2018_pcCvModifyInsert @paMainID, @cvMainID, @ID, @Description, @DescriptionOld, 'ec3', @IP
		EXEC v2018_pcCvModifyInsert @paMainID, @cvMainID, @ID, @DescriptionEng, @DescriptionEngOld, 'ee3', @IP
		EXEC v2018_pcCvModifyInsert @paMainID, @cvMainID, @ID, @Dept, @DeptOld, 'ec4', @IP
		EXEC v2018_pcCvModifyInsert @paMainID, @cvMainID, @ID, @DeptEng, @DeptEngOld, 'ee4', @IP
		EXEC v2018_pcCvModifyInsert @paMainID, @cvMainID, @ID, @UpperPost, @UpperPostOld, 'ec5', @IP
		EXEC v2018_pcCvModifyInsert @paMainID, @cvMainID, @ID, @UpperPostEng, @UpperPostEngOld, 'ee5', @IP

		--更新工作经历的CvLevel
		IF @CompanyName IS NOT NULL
			EXEC v2018_pcCvMainByCvLevelUpdate 0, @cvMainID, 4, 1
	
		IF @CompanyNameEng IS NOT NULL
			EXEC v2018_pcCvMainByCvLevelUpdate 1, @cvMainID, 4, 1

		--更新简历类型
		UPDATE cvMain SET cvType = 0 WHERE ID = @cvMainID
	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH
COMMIT TRAN
RETURN @ID
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END
ERRMAX:
BEGIN
	ROLLBACK TRAN
	RETURN -1
END
SET NOCOUNT OFF
GO

/****** Object:  StoredProcedure [dbo].[v2018_pcCvLanguageDelete]    Script Date: 2018/12/13 19:13:36 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2018.6.27
--创建人：Lucifer
--说明：删除语言能力
--#####################################################
CREATE PROCEDURE [dbo].[v2018_pcCvLanguageDelete] 
	@ID INT,
	@paMainID INT
AS
SET NOCOUNT ON
BEGIN TRAN
	BEGIN TRY
		DECLARE @cvMainID AS INT
		SELECT @cvMainID = cvMainID FROM cvLanguage WITH(NOLOCK INDEX(PK_cvLanguage)) WHERE ID = @ID
		IF NOT EXISTS(SELECT 'X' FROM cvMain WITH(NOLOCK) WHERE paMainID = @paMainID AND ID = @cvMainID)
			GOTO ERR

		DELETE FROM bsCvModify WHERE SubID = @ID AND Location LIKE 'h%'
		DELETE FROM cvLanguage WHERE ID = @ID

		--如果没有语言能力，修改cvLevel
		IF (SELECT COUNT(1) FROM cvLanguage WITH(NOLOCK INDEX(PK_cvLanguage)) WHERE cvMainID = @cvMainID) = 0
		BEGIN
			EXEC v2018_pcCvMainByCvLevelUpdate 2, @cvMainID, 7, 0
		END
		ELSE
		BEGIN
			UPDATE cvMain SET cvLevel = cvLevel WHERE ID = @cvMainID
		END
	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH
COMMIT TRAN
RETURN 1
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END
SET NOCOUNT OFF
GO

/****** Object:  StoredProcedure [dbo].[v2018_pcCvLanguageSave]    Script Date: 2018/12/13 19:13:36 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--####################################################
--添加人：Lucifer
--添加时间：2018-6-27
--描述：保存语言能力
--返回值 0 失败 >0成功 -1超过最大限制
--####################################################
CREATE PROCEDURE [dbo].[v2018_pcCvLanguageSave]
(
	@ID INT,
	@cvMainID INT,
	@LanguageType TINYINT,
	@Mastery TINYINT,
	@ReadWrite TINYINT,
	@Spoken TINYINT,
	@Score NVARCHAR(30),
	@ScoreEng VARCHAR(100),
	@paMainID INT,
	@IP VARCHAR(31)
)
AS
SET NOCOUNT ON
BEGIN TRAN
	----检查是否是该账号的简历
	IF NOT EXISTS(SELECT 'X' FROM cvMain WITH(NOLOCK) WHERE ID = @cvMainID AND paMainID = @paMainID)
		GOTO ERR
	----检查是否是该简历的语言能力
	IF @ID > 0
		IF NOT EXISTS(SELECT 'X' FROM cvLanguage WITH(NOLOCK INDEX(PK_cvLanguage)) WHERE ID = @ID AND cvMainID = @cvMainID)
			GOTO ERR
	
	BEGIN TRY
		SET @Score = dbo.v2018_SetVarcharNull(@Score)
		SET @ScoreEng = dbo.v2018_SetVarcharNull(@ScoreEng)

		DECLARE @ScoreOld NVARCHAR(30)
		DECLARE @ScoreEngOld VARCHAR(100)

		IF @ID = 0
		BEGIN
			--语言能力最多5个
			IF (SELECT COUNT(1) FROM cvLanguage WITH(NOLOCK INDEX(PK_cvLanguage)) WHERE cvMainID = @cvMainID) >= 5
				GOTO ERRMAX

			INSERT INTO cvLanguage(cvMainID, LanguageType, Mastery, [ReadWrite], Spoken, Score, ScoreEng)
			VALUES(@cvMainID, @LanguageType, @Mastery, @ReadWrite, @Spoken, @Score, @ScoreEng)

			SET @ID = @@IDENTITY
		END
		ELSE
		BEGIN
			SELECT @ScoreOld = Score, @ScoreEngOld = ScoreEng
			FROM cvLanguage WITH(NOLOCK INDEX(PK_cvLanguage)) WHERE ID = @ID

			UPDATE cvLanguage SET
				LanguageType = @LanguageType,
				Mastery = @Mastery,
				[ReadWrite] = @ReadWrite,
				Spoken = @Spoken,
				Score = @Score,
				ScoreEng = @ScoreEng
			WHERE ID = @ID
		END

		--添加审核记录
		EXEC v2018_pcCvModifyInsert @paMainID, @cvMainID, @ID, @Score, @ScoreOld, 'hc1', @IP
		EXEC v2018_pcCvModifyInsert @paMainID, @cvMainID, @ID, @ScoreEng, @ScoreEngOld, 'he1', @IP

		--更新语言能力的CvLevel
		EXEC v2018_pcCvMainByCvLevelUpdate 2, @cvMainID, 7, 1
	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH
COMMIT TRAN
RETURN @ID
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END
ERRMAX:
BEGIN
	ROLLBACK TRAN
	RETURN -1
END
SET NOCOUNT OFF
GO

/****** Object:  StoredProcedure [dbo].[v2018_pcCvMainByCvLevelUpdate]    Script Date: 2018/12/13 19:13:37 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--##########################################
--添加人   Lucifer
--添加时间 2018-6-25
--用途     更新cvLevel
--备注     如果是修改基本信息，则该用户所有简历都更新cvLevel
--         @Type = 2 针对的是多份的无数据的，这样只执行一次该方法即可，不然要执行中英文两次，cvMain触发器也要执行两次
--##########################################
CREATE PROCEDURE [dbo].[v2018_pcCvMainByCvLevelUpdate]
(
	@Type INT,
	@cvMainID INT,
	@Pos INT,
	@cvLevel CHAR(1)
)
AS
SET NOCOUNT ON
BEGIN
	IF @Type = 0
	BEGIN
		IF @Pos = 1
			UPDATE a SET cvLevel = '11' + RIGHT(cvLevel, 8) FROM cvMain a, paMain b WHERE a.paMainID = b.ID AND a.ID = @cvMainID
		ELSE
			UPDATE cvMain SET cvLevel = LEFT(cvLevel, @Pos - 1) + @cvLevel + RIGHT(cvLevel, 10 - @Pos) WHERE ID = @cvMainID
	END
	ELSE IF @Type = 1
	BEGIN
		IF @Pos = 1
			UPDATE a SET cvLevelEng = '11' + RIGHT(cvLevelEng, 8) FROM cvMain a, paMain b WHERE a.paMainID = b.ID AND a.ID = @cvMainID
		ELSE
			UPDATE cvMain SET cvLevelEng = LEFT(cvLevelEng, @Pos - 1) + @cvLevel + RIGHT(cvLevelEng, 10 - @Pos) WHERE ID = @cvMainID
	END
	ELSE IF @Type = 2
	BEGIN
		UPDATE cvMain SET
			cvLevel = LEFT(cvLevel, @Pos - 1) + @cvLevel + RIGHT(cvLevel, 10 - @Pos),
			cvLevelEng = LEFT(cvLevelEng, @Pos - 1) + @cvLevel + RIGHT(cvLevelEng, 10 - @Pos)
		WHERE ID = @cvMainID
	END
		
	UPDATE cvMain SET RefreshDate = GETDATE() WHERE ID = @cvMainID AND DATEADD(HOUR, 1, RefreshDate) < GETDATE()
END
SET NOCOUNT OFF
GO

/****** Object:  StoredProcedure [dbo].[v2018_pcCvMainByDegreeUpdate]    Script Date: 2018/12/13 19:13:37 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2018.6.27
--创建人：Lucifer
--说明：更新cvMain中的最高学历
--#####################################################
CREATE PROCEDURE [dbo].[v2018_pcCvMainByDegreeUpdate] 
	@cvMainID INT
AS
SET NOCOUNT ON
BEGIN TRY
	DECLARE @dcMajorID SMALLINT
	DECLARE @Degree TINYINT
	SELECT TOP 1 @Degree = Degree, @dcMajorID = dcMajorID FROM cvEducation WITH(NOLOCK)
	WHERE cvMainID = @cvMainID AND Degree = (
		SELECT MAX(Degree) FROM cvEducation WITH(NOLOCK) WHERE cvMainID = @cvMainID
	) ORDER BY ID DESC

	UPDATE cvMain SET Degree = @Degree, dcMajorID = @dcMajorID WHERE ID = @cvMainID
END TRY
BEGIN CATCH

END CATCH
SET NOCOUNT OFF


GO

/****** Object:  StoredProcedure [dbo].[v2018_pcCvMainCreate]    Script Date: 2018/12/13 19:13:37 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--####################################################
--添加人：Lucifer
--添加时间：2018-7-11
--描述：新建简历
--####################################################
CREATE PROCEDURE [dbo].[v2018_pcCvMainCreate]
(
	@paMainID INT,
	@IP VARCHAR(39)
)
AS
SET NOCOUNT ON
BEGIN TRY
	--已经有3份简历
	IF (SELECT COUNT(*) FROM cvMain WITH(NOLOCK INDEX(IX_cvMain_paMainID)) WHERE paMainID = @paMainID) > 2
	BEGIN
		RETURN 0
	END
	ELSE
	BEGIN
		DECLARE @Mobile VARCHAR(13), @Name VARCHAR(20), @cvLevel AS CHAR(10), @cvLevelEng AS CHAR(10)
		SELECT @cvLevel = '1000000000', @cvLevelEng = '1000000000'

		SELECT @Name = ISNULL([Name], ''), @Mobile = ISNULL(Mobile, '') FROM paMain WITH(NOLOCK INDEX(PK_paMain)) WHERE ID = @paMainID
		IF (LEN(@Mobile) > 0 AND LEN(@Name) > 0)
		BEGIN
			SELECT @cvLevel = '1100000000', @cvLevelEng = '1100000000'	
		END
		BEGIN TRAN
			DECLARE @cvMainID AS INT
			INSERT INTO cvMain(paMainID, [Name], cvLevel, cvLevelEng)
			VALUES(@paMainID, '未完成简历', @cvLevel, @cvLevelEng)
			SET @cvMainID = @@IDENTITY

			INSERT INTO paOperationLog (paMainID,Operation,Details,IP)
			VALUES(@paMainID, 14, '创建简历，编号' + RTRIM(CONVERT(VARCHAR(10),@cvMainID)), @IP)

			UPDATE dcSystemData SET Value = Value + RAND() * 5.4 WHERE ID = 1
		COMMIT
		RETURN @cvMainID
	END	
END TRY
BEGIN CATCH
	PRINT ''
	ROLLBACK TRAN
	RETURN 0
END CATCH
GO

/****** Object:  StoredProcedure [dbo].[v2018_pcCvMainDelete]    Script Date: 2018/12/13 19:13:37 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--################################################################
--创建人：Lucifer
--创建时间：2018-7-30
--描述：删除简历
--################################################################
CREATE PROCEDURE [dbo].[v2018_pcCvMainDelete]
	@ID INT,
	@paMainID INT,
	@IP VARCHAR(30)
AS
SET NOCOUNT ON
BEGIN TRAN
	BEGIN TRY
		DELETE FROM cvMain WHERE ID = @ID AND paMainID = @paMainID
		IF @@ROWCOUNT > 0
		BEGIN
			INSERT INTO paOperationLog(paMainID, Operation, Details, [IP])
			VALUES(@paMainID, 15, '删除简历，编号' + RTRIM(CONVERT(VARCHAR(10), @ID)), @IP)
		END
	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH
COMMIT TRAN
RETURN 1
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END
GO

/****** Object:  StoredProcedure [dbo].[v2018_pcCvMainSelect]    Script Date: 2018/12/13 19:13:37 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2018.6.21
--创建人：Lucifer
--说明：获取用户及简历信息
--#####################################################
CREATE PROCEDURE [dbo].[v2018_pcCvMainSelect]
(
	@paMainId INT,
	@cvMainId INT
)
AS
SET NOCOUNT ON
BEGIN
	SELECT a.*, b.[Name] MapPlace, dbo.BirthToAge(a.BirthDay) Age FROM paMain a WITH(NOLOCK)
	LEFT JOIN dcMapPlace b WITH(NOLOCK) ON a.dcMapPlaceID = b.ID
	WHERE a.ID = @paMainId
	SELECT * FROM paPhoto WITH(NOLOCK) WHERE paMainId = @paMainId
    SELECT a.*,
	(
		SELECT DISTINCT (SELECT CONVERT(VARCHAR(6), dcJobTypeID) + ' ' FROM cvJobType WHERE cvMainId = b.cvMainId FOR XML PATH(''))
		FROM cvJobType b WHERE b.cvMainId = a.Id
	) cvJobTypeId,
	(
		SELECT DISTINCT (SELECT CONVERT(VARCHAR(6), dcRegionID) + ' ' FROM cvJobPlace WHERE cvMainId = b.cvMainId FOR XML PATH(''))
		FROM cvJobPlace b WHERE b.cvMainId = a.Id
	) cvJobPlaceId,
	(
		SELECT DISTINCT (SELECT CONVERT(VARCHAR(6), dcIndustryID) + ' ' FROM cvIndustry WHERE cvMainId = b.cvMainId FOR XML PATH(''))
		FROM cvIndustry b WHERE b.cvMainId = a.Id
	) cvIndustryId
	FROM cvMain a WITH(NOLOCK) WHERE a.Id = @cvMainId
    SELECT * FROM cvEducation WITH(NOLOCK) WHERE cvMainId = @cvMainId
    SELECT * FROM cvExperience WITH(NOLOCK) WHERE cvMainId = @cvMainId
    SELECT * FROM cvLanguage WITH(NOLOCK) WHERE cvMainId = @cvMainId
    SELECT * FROM cvTraining WITH(NOLOCK) WHERE cvMainId = @cvMainId
    SELECT * FROM cvProject WITH(NOLOCK) WHERE cvMainId = @cvMainId
    SELECT * FROM cvAppendix WITH(NOLOCK) WHERE cvMainId = @cvMainId
    SELECT * FROM cvAttachment WITH(NOLOCK) WHERE cvMainId = @cvMainId
    SELECT * FROM cvTags WITH(NOLOCK) WHERE cvMainId = @cvMainId
END
SET NOCOUNT OFF
GO

/****** Object:  StoredProcedure [dbo].[v2018_pcCvMainUpdate]    Script Date: 2018/12/13 19:13:38 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2018.6.21
--创建人：Lucifer
--说明：保存简历信息
--@ModifyType 1、修改简历姓名 2、修改简历/姓名开放 3、修改工作能力 4、修改求职意向
--#####################################################
CREATE PROCEDURE [dbo].[v2018_pcCvMainUpdate]
(
	@cvMainID INT,
	@paMainID INT,
	@Name VARCHAR(30),
	@IsNameHidden BIT,
	@IsCvHidden BIT,
	@Speciality VARCHAR(MAX),
	@SpecialityEng VARCHAR(MAX),
	@RelatedWorkYears TINYINT, 
	@EmployType TINYINT, 
	@dcSalaryID TINYINT, 
	@IsNegotiable TINYINT, 
	@JobType VARCHAR(100), 
	@JobPlace VARCHAR(100), 
	@Industry VARCHAR(100), 
	@IP VARCHAR(39),
	@ModifyType TINYINT
)
AS
SET NOCOUNT ON
BEGIN TRAN
	IF NOT EXISTS(SELECT TOP 1 'X' FROM cvMain WITH(NOLOCK) WHERE ID = @cvMainID AND paMainID = @paMainID)
		GOTO ERR

	--BEGIN TRY
		SET @Name = dbo.v2018_SetVarcharNull(@Name)
		IF @ModifyType = 1 --修改简历姓名
		BEGIN
			UPDATE cvMain SET
				[Name] = @Name
			WHERE ID = @cvMainID
		END
		ELSE IF @ModifyType = 2 --修改简历/姓名开放
		BEGIN
			UPDATE cvMain SET
				IsCvHidden = @IsCvHidden,
				IsNameHidden = @IsNameHidden
			WHERE ID = @cvMainID
		END
		ELSE IF @ModifyType = 3 --修改工作能力
		BEGIN
			DECLARE @SpecialityOld VARCHAR(MAX)
			DECLARE @SpecialityEngOld VARCHAR(MAX)

			--获得原始数据
			SELECT @SpecialityOld = Speciality, @SpecialityEngOld = SpecialityEng
			FROM cvMain WITH(NOLOCK)
			WHERE ID = @cvMainID

			--选填没填置空
			SET @Speciality = dbo.v2018_SetVarcharNull(@Speciality)
			SET @SpecialityEng = dbo.v2018_SetVarcharNull(@SpecialityEng)

			UPDATE cvMain SET
				Speciality = @Speciality,
				SpecialityEng = @SpecialityEng
			WHERE ID = @cvMainID

			--添加审核记录
			EXEC v2018_pcCvModifyInsert @paMainID, @cvMainID, NULL, @Speciality, @SpecialityOld, 'bc2', @IP
			EXEC v2018_pcCvModifyInsert @paMainID, @cvMainID, NULL, @SpecialityEng, @SpecialityEngOld, 'be2', @IP
		END
		ELSE IF @ModifyType = 4 --修改求职意向
		BEGIN
			UPDATE cvMain SET
				RelatedWorkYears = @RelatedWorkYears, 
				EmployType = @EmployType, 
				dcSalaryID = @dcSalaryID, 
				IsNegotiable = @IsNegotiable
			WHERE ID = @cvMainID

			DELETE FROM cvJobPlace WHERE cvMainID = @cvMainID
			INSERT INTO cvJobPlace(cvMainID, dcRegionID)
			SELECT TOP 5 @cvMainID, a FROM dbo.fnSplit(@JobPlace, ' ')

			DELETE FROM cvJobType WHERE cvMainID = @cvMainID
			INSERT INTO cvJobType(cvMainID, dcJobTypeID)
			SELECT TOP 5 @cvMainID, a FROM dbo.fnSplit(@JobType, ' ')

			DELETE FROM cvIndustry WHERE cvMainID = @cvMainID
			INSERT INTO cvIndustry(cvMainID, dcIndustryID)
			SELECT @cvMainID, a FROM dbo.fnSplit(@Industry, ' ')

			IF ISNULL(@Name, '未完成简历') = '未完成简历'
			BEGIN
				SELECT TOP 1 @Name = [Description]
				FROM cvJobPlace a WITH(NOLOCK), dcRegion b WITH(NOLOCK)
				WHERE a.dcRegionID = b.ID AND a.cvMainID = @cvMainID

				SELECT TOP 1 @Name = @Name + '+' + [Description]
				FROM cvJobType a WITH(NOLOCK), dcJobType b WITH(NOLOCK)
				WHERE a.dcJobTypeID = b.ID AND a.cvMainID = @cvMainID

				UPDATE cvMain SET
					[Name] = @Name
				WHERE ID = @cvMainID
			END

			--更新求职意向的cvLevel
			EXEC v2018_pcCvMainByCvLevelUpdate 0, @cvMainID, 6, 1
			EXEC v2018_pcCvMainByCvLevelUpdate 1, @cvMainID, 6, 1

			IF @RelatedWorkYears = 0
			BEGIN
				EXEC v2018_pcCvMainByCvLevelUpdate 0, @cvMainID, 4, 1
				EXEC v2018_pcCvMainByCvLevelUpdate 1, @cvMainID, 4, 1
			END
			ELSE
			BEGIN
				IF NOT EXISTS(SELECT TOP 1 'X' FROM cvExperience WITH(NOLOCK) WHERE cvMainId = @cvMainID)
				BEGIN
					EXEC v2018_pcCvMainByCvLevelUpdate 0, @cvMainID, 4, 0
					EXEC v2018_pcCvMainByCvLevelUpdate 1, @cvMainID, 4, 0
				END
			END
		END
	--END TRY
	--BEGIN CATCH
	--	GOTO ERR
	--END CATCH
COMMIT TRAN
RETURN 1
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END
SET NOCOUNT OFF
GO

/****** Object:  StoredProcedure [dbo].[v2018_pcCvModifyInsert]    Script Date: 2018/12/13 19:13:38 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--#########################################################
--添加人    Lucifer
--添加时间  2018-6-25
--用途      简历待审核数据插入
--#########################################################
CREATE PROCEDURE [dbo].[v2018_pcCvModifyInsert]
(
	@paMainID INT,
	@cvMainID INT,
	@SubID INT,
	@Value VARCHAR(MAX),
	@ValueOld VARCHAR(MAX),
	@ColType VARCHAR(5),
	@IP VARCHAR(31)
)
AS
SET NOCOUNT ON
BEGIN
	SET @Value = dbo.v2018_SetVarcharNull(@Value)
	SET @ValueOld = dbo.v2018_SetVarcharNull(@ValueOld)

	--修改的是paMain信息，将cvMainID置空
	IF LEFT(@ColType, 1) = 'a'
	BEGIN
		SET @cvMainID = NULL
	END
	
	--插入待审核记录
	DELETE FROM bsCvModify WHERE paMainID = @paMainID AND ISNULL(cvMainID, 0) = ISNULL(@cvMainID, 0) AND ISNULL(SubID, 0) = ISNULL(@SubID, 0) AND [Location] = @ColType
	IF @Value <> ISNULL(@ValueOld, '') AND @Value IS NOT NULL
	BEGIN
		INSERT INTO bsCvModify(paMainID, cvMainID, SubID, [Location], ColValue) VALUES(@paMainID, @cvMainID, @SubID, @ColType, @Value)

		IF @ColType = 'ac1'
		BEGIN
			INSERT INTO paOperationLog (paMainID, Operation, Details, [IP]) 
			VALUES(@paMainID, 30, '更新姓名，原姓名：<' + ISNULL(@ValueOld, '') + '>；新姓名：<' + @Value + '>', @IP)
		END
		ELSE IF @ColType = 'ae1'
		BEGIN
			INSERT INTO paOperationLog (paMainID, Operation, Details, [IP]) 
			VALUES(@paMainID, 30, '更新英文名，原英文名：<' + ISNULL(@ValueOld, '') + '>；新英文名：<' + @Value + '>', @IP)
		END
	END
END
SET NOCOUNT OFF


GO

/****** Object:  StoredProcedure [dbo].[v2018_pcCvProjectDelete]    Script Date: 2018/12/13 19:13:38 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2018.6.27
--创建人：Lucifer
--说明：删除项目经历
--#####################################################
CREATE PROCEDURE [dbo].[v2018_pcCvProjectDelete] 
	@ID INT,
	@paMainID INT
AS
SET NOCOUNT ON
BEGIN TRAN
	BEGIN TRY
		DECLARE @cvMainID AS INT
		SELECT @cvMainID = cvMainID FROM cvProject WITH(NOLOCK INDEX(PK_cvProject)) WHERE ID = @ID
		IF NOT EXISTS(SELECT 'X' FROM cvMain WITH(NOLOCK) WHERE paMainID = @paMainID AND ID = @cvMainID)
			GOTO ERR

		DELETE FROM bsCvModify WHERE SubID = @ID AND Location LIKE 'f%'
		DELETE FROM cvProject WHERE ID = @ID

		IF (SELECT COUNT(1) FROM cvProject WITH(NOLOCK INDEX(PK_cvProject)) WHERE cvMainID = @cvMainID) = 0
		BEGIN
			EXEC v2018_pcCvMainByCvLevelUpdate 2, @cvMainID, 9, 0
		END
		ELSE
		BEGIN
			UPDATE cvMain SET cvLevel = cvLevel WHERE ID = @cvMainID
		END
	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH
COMMIT TRAN
RETURN 1
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END
SET NOCOUNT OFF
GO

/****** Object:  StoredProcedure [dbo].[v2018_pcCvProjectSave]    Script Date: 2018/12/13 19:13:38 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


--####################################################
--添加人：Lucifer
--添加时间：2018-6-27
--描述：保存项目经历
--返回值 0 失败 >0成功 -1超过最大限制
--####################################################
CREATE PROCEDURE [dbo].[v2018_pcCvProjectSave]
(
	@ID INT,
	@cvMainID INT,
	@Name NVARCHAR(50),
	@NameEng VARCHAR(250),
	@StartDate INT,
	@EndDate INT,
	@Description NVARCHAR(1000),
	@DescriptionEng VARCHAR(MAX),
	@Responsibilities NVARCHAR(200),
	@ResponsibilitiesEng VARCHAR(1000),
	@paMainID INT,
	@IP VARCHAR(31)
)
AS
SET NOCOUNT ON
BEGIN TRAN
	----检查是否是该账号的简历
	IF NOT EXISTS(SELECT 'X' FROM cvMain WITH(NOLOCK) WHERE ID = @cvMainID AND paMainID = @paMainID)
		GOTO ERR
	----检查是否是该简历的项目经历
	IF @ID > 0
		IF NOT EXISTS(SELECT 'X' FROM cvProject WITH(NOLOCK INDEX(PK_cvProject)) WHERE ID = @ID AND cvMainID = @cvMainID)
			GOTO ERR
	
	BEGIN TRY
		SET @Name = dbo.v2018_SetVarcharNull(@Name)
		SET @NameEng = dbo.v2018_SetVarcharNull(@NameEng)
		SET @Description = dbo.v2018_SetVarcharNull(@Description)
		SET @DescriptionEng = dbo.v2018_SetVarcharNull(@DescriptionEng)
		SET @Responsibilities = dbo.v2018_SetVarcharNull(@Responsibilities)
		SET @ResponsibilitiesEng = dbo.v2018_SetVarcharNull(@ResponsibilitiesEng)

		DECLARE @NameOld NVARCHAR(50)
		DECLARE @NameEngOld VARCHAR(250)
		DECLARE @DescriptionOld NVARCHAR(1000)
		DECLARE @DescriptionEngOld VARCHAR(MAX)
		DECLARE @ResponsibilitiesOld NVARCHAR(200)
		DECLARE @ResponsibilitiesEngOld VARCHAR(1000)

		IF @ID = 0
		BEGIN
			--项目经历最多10个
			IF (SELECT COUNT(1) FROM cvProject WITH(NOLOCK INDEX(PK_cvProject)) WHERE cvMainID = @cvMainID) >= 10
				GOTO ERRMAX

			INSERT INTO cvProject(cvMainID, [Name], NameEng, StartDate, EndDate, [Description], DescriptionEng, Responsibilities, ResponsibilitiesEng)
			VALUES(@cvMainID, @Name, @NameEng, @StartDate, @EndDate, @Description, @DescriptionEng, @Responsibilities, @ResponsibilitiesEng)

			SET @ID = @@IDENTITY
		END
		ELSE
		BEGIN
			SELECT @NameOld = [Name], @NameEngOld = NameEng,
				@DescriptionOld = [Description], @DescriptionEngOld = DescriptionEng,
				@ResponsibilitiesOld = Responsibilities, @ResponsibilitiesEngOld = ResponsibilitiesEng
			FROM cvProject WITH(NOLOCK INDEX(PK_cvProject)) WHERE ID = @ID

			UPDATE cvProject SET
				[Name] = @Name,
				NameEng = @NameEng,
				StartDate = @StartDate,
				EndDate = @EndDate,
				[Description] = @Description,
				DescriptionEng = @DescriptionEng,
				Responsibilities = @Responsibilities,
				ResponsibilitiesEng = @ResponsibilitiesEng
			WHERE ID = @ID
		END

		--添加审核记录
		EXEC v2018_pcCvModifyInsert @paMainID, @cvMainID, @ID, @Name, @NameOld, 'fc1', @IP
		EXEC v2018_pcCvModifyInsert @paMainID, @cvMainID, @ID, @NameEng, @NameEngOld, 'fe1', @IP
		EXEC v2018_pcCvModifyInsert @paMainID, @cvMainID, @ID, @Description, @DescriptionOld, 'fc2', @IP
		EXEC v2018_pcCvModifyInsert @paMainID, @cvMainID, @ID, @DescriptionEng, @DescriptionEngOld, 'fe2', @IP
		EXEC v2018_pcCvModifyInsert @paMainID, @cvMainID, @ID, @Responsibilities, @ResponsibilitiesOld, 'fc3', @IP
		EXEC v2018_pcCvModifyInsert @paMainID, @cvMainID, @ID, @ResponsibilitiesEng, @ResponsibilitiesEngOld, 'fe3', @IP

		--更新项目经历的CvLevel
		IF @Name IS NOT NULL
			EXEC v2018_pcCvMainByCvLevelUpdate 0, @cvMainID, 9, 1
	
		IF @NameEng IS NOT NULL
			EXEC v2018_pcCvMainByCvLevelUpdate 1, @cvMainID, 9, 1
	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH
COMMIT TRAN
RETURN @ID
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END
ERRMAX:
BEGIN
	ROLLBACK TRAN
	RETURN -1
END
SET NOCOUNT OFF
GO

/****** Object:  StoredProcedure [dbo].[v2018_pcCvTrainingDelete]    Script Date: 2018/12/13 19:13:39 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2018.6.27
--创建人：Lucifer
--说明：删除培训经历
--#####################################################
CREATE PROCEDURE [dbo].[v2018_pcCvTrainingDelete] 
	@ID INT,
	@paMainID INT
AS
SET NOCOUNT ON
BEGIN TRAN
	BEGIN TRY
		DECLARE @cvMainID AS INT
		SELECT @cvMainID = cvMainID FROM cvTraining WITH(NOLOCK INDEX(PK_cvTraining)) WHERE ID = @ID
		IF NOT EXISTS(SELECT 'X' FROM cvMain WITH(NOLOCK) WHERE paMainID = @paMainID AND ID = @cvMainID)
			GOTO ERR

		DELETE FROM bsCvModify WHERE SubID = @ID AND Location LIKE 'g%'
		DELETE FROM cvTraining WHERE ID = @ID

		IF (SELECT COUNT(1) FROM cvTraining WITH(NOLOCK INDEX(PK_cvTraining)) WHERE cvMainID = @cvMainID) = 0
		BEGIN
			EXEC v2018_pcCvMainByCvLevelUpdate 2, @cvMainID, 8, 0
		END
		ELSE
		BEGIN
			UPDATE cvMain SET cvLevel = cvLevel WHERE ID = @cvMainID
		END
	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH
COMMIT TRAN
RETURN 1
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END
SET NOCOUNT OFF
GO

/****** Object:  StoredProcedure [dbo].[v2018_pcCvTrainingSave]    Script Date: 2018/12/13 19:13:39 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


--####################################################
--添加人：Lucifer
--添加时间：2018-6-27
--描述：保存培训经历
--返回值 0 失败 >0成功 -1超过最大限制
--####################################################
CREATE PROCEDURE [dbo].[v2018_pcCvTrainingSave]
(
	@ID INT,
	@cvMainID INT,
	@StartDate INT,
	@TimeLength TINYINT,
	@TimeUnit TINYINT,
	@Institution NVARCHAR(30),
	@InstitutionEng VARCHAR(150),
	@Course NVARCHAR(50),
	@CourseEng VARCHAR(250),
	@City NVARCHAR(10),
	@CityEng VARCHAR(50),
	@Certificate NVARCHAR(50),
	@CertificateEng VARCHAR(250),
	@Details NVARCHAR(500),
	@DetailsEng VARCHAR(2500),
	@paMainID INT,
	@IP VARCHAR(31)
)
AS
SET NOCOUNT ON
BEGIN TRAN
	----检查是否是该账号的简历
	IF NOT EXISTS(SELECT 'X' FROM cvMain WITH(NOLOCK) WHERE ID = @cvMainID AND paMainID = @paMainID)
		GOTO ERR
	----检查是否是该简历的培训经历
	IF @ID > 0
		IF NOT EXISTS(SELECT 'X' FROM cvTraining WITH(NOLOCK INDEX(PK_cvTraining)) WHERE ID = @ID AND cvMainID = @cvMainID)
			GOTO ERR
	
	BEGIN TRY
		SET @Institution = dbo.v2018_SetVarcharNull(@Institution)
		SET @InstitutionEng = dbo.v2018_SetVarcharNull(@InstitutionEng)
		SET	@Course = dbo.v2018_SetVarcharNull(@Course)
		SET	@CourseEng = dbo.v2018_SetVarcharNull(@CourseEng)
		SET @City = dbo.v2018_SetVarcharNull(@City)
		SET @CityEng = dbo.v2018_SetVarcharNull(@CityEng)
		SET	@Certificate = dbo.v2018_SetVarcharNull(@Certificate)
		SET	@CertificateEng = dbo.v2018_SetVarcharNull(@CertificateEng)
		SET @Details = dbo.v2018_SetVarcharNull(@Details)
		SET @DetailsEng = dbo.v2018_SetVarcharNull(@DetailsEng)

		DECLARE @InstitutionOld NVARCHAR(30)
		DECLARE @InstitutionEngOld VARCHAR(150)
		DECLARE @CourseOld NVARCHAR(50)
		DECLARE @CourseEngOld VARCHAR(250)
		DECLARE @CityOld NVARCHAR(10)
		DECLARE @CityEngOld VARCHAR(50)
		DECLARE @CertificateOld NVARCHAR(50)
		DECLARE @CertificateEngOld VARCHAR(250)
		DECLARE @DetailsOld NVARCHAR(500)
		DECLARE @DetailsEngOld VARCHAR(2500)

		IF @ID = 0
		BEGIN
			--培训经历最多10个
			IF (SELECT COUNT(1) FROM cvTraining WITH(NOLOCK INDEX(PK_cvTraining)) WHERE cvMainID = @cvMainID) >= 10
				GOTO ERRMAX

			INSERT INTO cvTraining(cvMainID, StartDate, TimeLength, TimeUnit, Institution, InstitutionEng, Course, CourseEng, City, CityEng, [Certificate], CertificateEng, Details, DetailsEng)
			VALUES(@cvMainID, @StartDate, @TimeLength, @TimeUnit, @Institution, @InstitutionEng, @Course, @CourseEng, @City, @CityEng, @Certificate, @CertificateEng, @Details, @DetailsEng)

			SET @ID = @@IDENTITY
		END
		ELSE
		BEGIN
			SELECT @InstitutionOld = Institution, @InstitutionEngOld = InstitutionEng,
				@CourseOld = Course, @CourseEngOld = CourseEng,
				@CityOld = City, @CityEngOld = CityEng,
				@CertificateOld = [Certificate], @CertificateEngOld = CertificateEng,
				@DetailsOld = Details, @DetailsEngOld = DetailsEng
			FROM cvTraining WITH(NOLOCK INDEX(PK_cvTraining)) WHERE ID = @ID

			UPDATE cvTraining SET
				StartDate = @StartDate,
				TimeLength = @TimeLength,
				TimeUnit = @TimeUnit,
				Institution = @Institution,
				InstitutionEng =InstitutionEng,
				Course = @Course,
				CourseEng = @CourseEng,
				City = @City,
				CityEng = @CityEng,
				[Certificate] = @Certificate,
				CertificateEng = @CertificateEng,
				Details = @Details,
				DetailsEng = @DetailsEng
			WHERE ID = @ID
		END

		--添加审核记录
		EXEC v2018_pcCvModifyInsert @paMainID, @cvMainID, @ID, @Institution, @InstitutionOld, 'gc1', @IP
		EXEC v2018_pcCvModifyInsert @paMainID, @cvMainID, @ID, @InstitutionEng, @InstitutionEngOld, 'ge1', @IP
		EXEC v2018_pcCvModifyInsert @paMainID, @cvMainID, @ID, @Course, @CourseOld, 'gc2', @IP
		EXEC v2018_pcCvModifyInsert @paMainID, @cvMainID, @ID, @CourseEng, @CourseEngOld, 'ge2', @IP
		EXEC v2018_pcCvModifyInsert @paMainID, @cvMainID, @ID, @City, @CityOld, 'gc3', @IP
		EXEC v2018_pcCvModifyInsert @paMainID, @cvMainID, @ID, @CityEng, @CityEngOld, 'ge3', @IP
		EXEC v2018_pcCvModifyInsert @paMainID, @cvMainID, @ID, @Certificate, @CertificateOld, 'gc4', @IP
		EXEC v2018_pcCvModifyInsert @paMainID, @cvMainID, @ID, @CertificateEng, @CertificateEngOld, 'ge4', @IP
		EXEC v2018_pcCvModifyInsert @paMainID, @cvMainID, @ID, @Details, @DetailsOld, 'gc5', @IP
		EXEC v2018_pcCvModifyInsert @paMainID, @cvMainID, @ID, @DetailsEng, @DetailsEngOld, 'ge5', @IP

		--更新培训经历的CvLevel
		IF @Institution IS NOT NULL
			EXEC v2018_pcCvMainByCvLevelUpdate 0, @cvMainID, 8, 1
	
		IF @InstitutionEng IS NOT NULL
			EXEC v2018_pcCvMainByCvLevelUpdate 1, @cvMainID, 8, 1

	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH
COMMIT TRAN
RETURN @ID
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END
ERRMAX:
BEGIN
	ROLLBACK TRAN
	RETURN -1
END
SET NOCOUNT OFF
GO

/****** Object:  StoredProcedure [dbo].[v2018_pcDcAutoEmailSelect]    Script Date: 2018/12/13 19:13:39 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2018.6.21
--创建人：Lucifer
--说明：获取随机邮箱
--#####################################################
CREATE PROCEDURE [dbo].[v2018_pcDcAutoEmailSelect]
AS
BEGIN
	IF NOT EXISTS(SELECT TOP 1 'X' FROM dcAutoEmail WITH(NOLOCK) ORDER BY ID)
	BEGIN
		SELECT TOP 0 * INTO #t FROM dcAutoEmail
		INSERT #t 
		SELECT TOP 10000 LEFT(NEWID(), 3) + '_' + LEFT(NEWID(), 2) + '@your_email.com' FROM cpMain
		UPDATE #t SET Email = CHAR(65 + id % 26) + Email

		DELETE a
		FROM #t a, dcAutoEmail b
		WHERE a.Email = b.Email

		DELETE a
		FROM #t a, paMain b
		WHERE a.Email = b.Email

		DELETE a
		FROM #t a, Resume_XinXi b
		WHERE a.Email = b.Email

		INSERT INTO dcAutoEmail SELECT DISTINCT Email FROM #t
	END
	DECLARE @Email VARCHAR(50)
	SELECT TOP 1 @Email = Email FROM dcAutoEmail ORDER BY ID
	DELETE FROM dcAutoEmail WHERE Email = @Email
	SELECT @Email
END
GO

/****** Object:  StoredProcedure [dbo].[v2018_pcExImageInsert]    Script Date: 2018/12/13 19:13:40 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--####################################################
--添加人：Lucifer
--添加时间：2018-6-27
--描述：上传照片中转
--####################################################
CREATE PROCEDURE [dbo].[v2018_pcExImageInsert]
(
	@OutID INT,
	@OutType INT,
	@UID VARCHAR(20) OUTPUT
)
AS
BEGIN
	DECLARE @T AS VARCHAR(20)
	SET @T = CONVERT(VARCHAR(20), CONVERT(DECIMAL(18,12),GETDATE()))
	SET @T = RTRIM(CONVERT(VARCHAR(12), @OutID)) + '_' + RIGHT(@T,8)
	Insert Into exImage(OutID,OutType,UniqueID)
	Values(@OutID,@OutType,@T)
	SET @UID = @T
END
GO

/****** Object:  StoredProcedure [dbo].[v2018_pcExInterViewSelect]    Script Date: 2018/12/13 19:13:40 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--################################################################
--创建人：Lucifer
--创建时间：2018-7-23
--描述：个人面试通知
CREATE PROCEDURE [dbo].[v2018_pcExInterViewSelect]
(
    @Where VARCHAR(1000),
    @Order VARCHAR(100)
)
AS
SET NOCOUNT ON
BEGIN
    SET @Where = dbo.SafeSQL(@Where)
    SET @Order = dbo.SafeSQL(@Order)
    DECLARE @SQL VARCHAR(2000)
    SET @SQL = 'SELECT a.ID, a.JobID, a.cvMainID, a.InterviewDate, a.InterViewPlace, a.LinkMan, a.Telephone, a.Remark, 
	a.AddDate, a.Reply, a.ReplyMessage, a.Replydate, a.Result, a.ResultDate, a.CompanyDeleted, a.CompanyDeleteDate,
	a.PersonDeleted, a.PersonDeleteDate, a.ViewDate, b.*, b.Name JobName, c.Name cpName, c.ID cpID, c.HasLicence, 
	c.IsAgent, d.Name cvName, c.Membertype, b.SecondId EnJobID, c.SecondId EnCpMainID, 
	dbo.GetCaOnlineStatus(b.caMainID) IsOnline, b.CaMainID, c.LogoFile LogoUrl, b.Valid JobValid
	FROM exInterView a WITH(NOLOCK)
	INNER JOIN Job b WITH(NOLOCK) ON b.ID = a.JobID
	INNER JOIN cpMain c WITH(NOLOCK) ON b.cpMainID = c.ID
	INNER JOIN cvMain d WITH(NOLOCK) ON a.cvMainID = d.ID
    WHERE PersonDeleted=0'
    IF LEN(@Where) > 0
        SET @SQL = @SQL + ' AND ' + @Where
    IF LEN(@Order) > 0
        SET @SQL = @SQL + ' ORDER BY ' + @Order
    EXEC(@SQL)
END
SET NOCOUNT OFF
GO

/****** Object:  StoredProcedure [dbo].[v2018_pcExInterViewUpdate]    Script Date: 2018/12/13 19:13:40 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--################################################################
--创建人：Lucifer
--创建时间：2018-7-23
--描述：答复面试通知
--################################################################
CREATE PROCEDURE [dbo].[v2018_pcExInterViewUpdate]
(
    @ID INT,
    @Reply TINYINT,
    @ReplyMessage VARCHAR(500),
    @paMainId INT
)
AS
SET NOCOUNT ON
BEGIN
    UPDATE exInterView SET
		Reply = @Reply,
		ReplyMessage = dbo.v2018_SetVarcharNull(@ReplyMessage),
		ReplyDate = GETDATE()
    WHERE ID = @ID
		AND cvMainId IN(SELECT ID FROM cvMain WITH(NOLOCK) WHERE paMainId = @paMainId)

	IF @@ROWCOUNT = 0
	BEGIN
		SELECT '0' Result
		RETURN
	END

	DECLARE @ReplyInfo NVARCHAR(20)
	IF @Reply = 1
	BEGIN
        SET @ReplyInfo = '赴约'
	END
    ELSE
	BEGIN
        SET @ReplyInfo = '不赴约'
	END

	INSERT INTO paPushLog(paMainID, PushMessage, PushType) 
    SELECT a.caMainID, e.[Name] + '回复' + @ReplyInfo, 13 
	FROM caIOSBind a WITH(NOLOCK)
	INNER JOIN Job b WITH(NOLOCK) ON a.caMainID = b.caMainID
	INNER JOIN exInterview c WITH(NOLOCK) ON b.ID = c.JobID
	INNER JOIN cvMain d WITH(NOLOCK) ON c.cvMainId = d.ID
	INNER JOIN paMain e WITH(NOLOCK) ON d.paMainId = e.ID
	WHERE c.ID = @ID

	INSERT wxMessageSend2(TemplateType, WxFansID, PaMainId, CvMainId, CpMainID, CaMainId, JobId, AddDate)
    SELECT 15, b.ID, @paMainID, d.cvMainID, c.cpMainID, c.caMainID, c.ID, GETDATE()
    FROM paLoginContact a WITH(NOLOCK)
	INNER JOIN wxFans b WITH(NOLOCK) ON a.OpenID = b.OpenID
	INNER JOIN Job c WITH(NOLOCK) ON c.caMainID = a.paMainID
	INNER JOIN exInterview d WITH(NOLOCK) ON d.JobID = c.ID
    WHERE a.ContactType = 101 AND d.ID = @ID
	
	SELECT TOP 1 '1' Result, a.[Name] CompanyName, b.[Name] JobName, a.ConsultantId, c.Email, a.ID, d.Reply, d.cvMainID
    FROM cpMain a WITH(NOLOCK), Job b WITH(NOLOCK), caMain c WITH(NOLOCK), exInterview d WITH(NOLOCK)
    WHERE a.ID = b.cpMainID
    AND b.caMainID = c.ID
	AND b.ID = d.JobId
    AND d.ID = @ID
END
SET NOCOUNT OFF
GO

/****** Object:  StoredProcedure [dbo].[v2018_pcExJobApplyByRemindDateUpdate]    Script Date: 2018/12/13 19:13:41 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2018.7.26
--创建人：Lucifer
--说明：申请的职位求答复
--#####################################################
CREATE PROCEDURE  [dbo].[v2018_pcExJobApplyByRemindDateUpdate]
(
	@ID INT,
	@paMainID INT
)
AS
SET NOCOUNT ON
BEGIN 
	UPDATE exJobApply SET
		RemindDate  = GETDATE()
	WHERE cvMainID IN (SELECT ID FROM cvMain WITH(NOLOCK) WHERE paMainID = @paMainID)
		AND ID = @ID
        
    INSERT INTO paPushLog(paMainID, PushMessage, PushType) 
	SELECT a.caMainid, '有求职者求答复TA的简历&#10084;',10
	FROM caIOSBind a WITH(NOLOCK), Job b WITH(NOLOCK), exJobApply c WITH(NOLOCK)
	WHERE a.caMainId = b.caMainId AND b.ID = c.JobID AND c.ID = @ID
END
SET NOCOUNT OFF
GO

/****** Object:  StoredProcedure [dbo].[v2018_pcExJobApplyInsert]    Script Date: 2018/12/13 19:13:41 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--################################################################
--创建人：Lucifer
--创建时间：2018-9-5
--描述：申请职位
--################################################################
CREATE PROCEDURE [dbo].[v2018_pcExJobApplyInsert]
(
	@JobId INT,
	@cvMainId INT,
	@paMainId INT
)
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
		IF NOT EXISTS(SELECT 'X' FROM cvMain WITH(NOLOCK) WHERE paMainID = @paMainId AND ID = @cvMainId)
		BEGIN
			RETURN 0
		END
		--30天内同一简历同一职位不能重复申请
		IF EXISTS(SELECT 'X' FROM exJobApply WITH(NOLOCK) WHERE JobID = @JobId AND cvMainID = @cvMainId AND AddDate > GETDATE() - 30)
		BEGIN
			RETURN 0
		END
		--职位无效
		IF NOT EXISTS(SELECT 'X' FROM Job WITH(NOLOCK) WHERE ID = @JobId AND Valid = 1)
		BEGIN
			RETURN 0
		END
		DECLARE @MaxID INT
		DECLARE @IsFilter BIT
		SET @IsFilter = dbo.IsJobApplyFilter(@JobId, @cvMainId)
		INSERT INTO exJobApply(JobID, cvMainID, IsTempInsert, IsFilter)
		VALUES(@JobId, @cvMainId, 1, @IsFilter)
		SET @MaxID = @@IDENTITY
		--批量申请的未浏览过该职位的，插入浏览记录
		IF NOT EXISTS(SELECT 'X' FROM paJobViewLog WITH(NOLOCK) WHERE paMainId = @paMainId AND JobId = @JobId)
		BEGIN
			INSERT INTO paJobViewLog(JobId, paMainId, AddDate) VALUES(@JobId, @paMainId, GETDATE())
			UPDATE Job SET ViewNumber = ISNULL(ViewNumber, 0) + 1 WHERE ID = @JobId
		END
		--有应聘邀请的，更新Reply = 1
		UPDATE caCvIntention SET Reply = 1, ReplyDate = GETDATE() WHERE cvMainID = @cvMainId AND JobId = @JobId
		--微信推送
		INSERT wxMessageSend2(Templatetype, WxFansID, PaMainId, CvMainId, CpMainID, CaMainId, JobId, AddDate)
		SELECT 14, b.ID, @paMainId, @cvMainId, c.cpMainID, c.caMainID, c.ID, GETDATE()
		FROM paLoginContact a WITH(NOLOCK), wxFans b WITH(NOLOCK), Job c WITH(NOLOCK)
		WHERE a.OpenID = b.OpenID AND c.caMainID = a.paMainID AND a.ContactType = 101 AND c.ID = @JobId
		--APP推送
		INSERT INTO paPushLog(paMainID, PushMessage, PushType)
		SELECT TOP 1 b.caMainID, '亲，有求职者投递简历啦', 9
		FROM exJobApply a WITH(NOLOCK), Job b WITH(NOLOCK), caIOSBind c WITH(NOLOCK)
		WHERE a.JobId = b.ID AND b.caMainId = c.caMainId AND a.ID = @MaxID
	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH
	RETURN @MaxID
END
ERR:
BEGIN
	RETURN 0
END
SET NOCOUNT OFF
GO

/****** Object:  StoredProcedure [dbo].[v2018_pcExJobApplySelect]    Script Date: 2018/12/13 19:13:41 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--################################################################
--创建人：Lucifer
--创建时间：2018-7-23
--描述：获取个人申请的职位列表
--################################################################
CREATE PROCEDURE [dbo].[v2018_pcExJobApplySelect]
(
	@Where VARCHAR(1000), 
	@Order VARCHAR(100)
)
AS
SET NOCOUNT ON
BEGIN
	SET @Where = REPLACE(dbo.SafeSQL(@Where), '''', '')
	SET @Order = REPLACE(dbo.SafeSQL(@Order), '''', '')
	SET @Where = REPLACE(@Where, 'LIKE %', 'LIKE ''%')
	SET @Where = REPLACE(@Where, '% OR ', '%'' OR ')
	SET @Where = REPLACE(@Where, '%)', '%'')')

	DECLARE @SQL VARCHAR(2000)
	SET @SQL='SELECT a.ID, a.JobID, b.SecondId EnJobID, c.SecondId EnCpMainID, a.cvMainID, a.ApplyMessage, a.AddDate, 
			a.CompanyDeleted, a.CompanyDeleteDate, a.PersonDeleted, a.Reply, a.ReplyDate, a.ViewDate, b.Name JobName, 
			b.caMainID, b.dcRegionID, c.Name cpName, c.ID cpID, b.Welfare1, b.Welfare2, b.Welfare3, b.Welfare4, 
			b.Welfare5, b.Welfare6, b.Welfare7, b.Welfare8, b.Welfare9, b.Welfare10, b.Welfare11, b.Welfare12, b.Welfare13, 
			b.Welfare14, b.Welfare15, b.Welfare16, b.Welfare17, b.Welfare18, b.Welfare19, b.Valid JobValid, c.LogoFile LogoUrl, 
			c.HasLicence, c.IsAgent, c.MemberType, b.IssueDate, b.IssueEND, b.IsDelete, d.Name cvName, 
			dbo.GetCvMatch(a.cvMainID, a.JobID) cvMatch, dbo.GetCaOnlineStatus(b.caMainID) IsOnline, a.RemindDate, 
			a.ReplyReason, c.ReplyRate, b.dcSalaryId, b.dcSalaryIdMax,
			(SELECT TOP 1 Adddate FROM exInterview WITH(NOLOCK) WHERE a.cvMainId = cvMainId AND b.ID = JobId) InterviewDate
			FROM exJobApply a WITH(NOLOCK) 
			INNER JOIN Job b WITH(NOLOCK) On b.ID = a.JobID 
			INNER JOIN cpMain c WITH(NOLOCK) ON b.cpMainID = c.ID 
			INNER JOIN cvMain d WITH(NOLOCK) ON a.cvMainID = d.ID 
			WHERE 1 = 1'

	IF LEN(@Where) > 0
		SET @SQL = @SQL + ' AND ' + @Where

	IF LEN(@Order) > 0
		SET @SQL = @SQL + ' ORDER BY ' + @Order

	EXEC(@SQL)
END
SET NOCOUNT OFF
GO

/****** Object:  StoredProcedure [dbo].[v2018_pcJobSearchByPaSpread]    Script Date: 2018/12/13 19:13:41 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--###########################################
--添加人：Lucifer
--添加时间：2018-10-22
--备注：用于推广竞价页面RegisterSpread
--###########################################
CREATE PROCEDURE [dbo].[v2018_pcJobSearchByPaSpread]
(
	@Keyword NVARCHAR(50)
)
AS
BEGIN
	CREATE TABLE #T
	(
		ID INT IDENTITY(1,1),
		JobId INT
	)
	INSERT INTO #T(JobId)
	SELECT a.ID FROM JobPublish a WITH(NOLOCK), cpMainPublish b WITH(NOLOCK)
	WHERE a.cpMainId = b.ID
		AND b.dcProvinceId = 32
		AND a.dcSalaryIdMax != 100
		AND CHARINDEX(@Keyword, a.Name) > 0
	ORDER BY a.RefreshDate DESC, a.dcSalaryIdMax DESC

	IF NOT EXISTS(SELECT TOP 1 'X' FROM #T)
	BEGIN
		INSERT INTO #T(JobId)
		SELECT TOP 10 a.ID FROM JobPublish a WITH(NOLOCK), cpMainPublish b WITH(NOLOCK)
		WHERE a.cpMainId = b.ID
			AND b.dcProvinceId = 32
			AND a.dcSalaryIdMax != 100
		ORDER BY a.dcSalaryIdMax DESC, a.RefreshDate DESC
	END

	SELECT TOP 10 b.[Name] JobName, b.dcSalaryId, b.dcSalaryIdMax, c.[Name] CompanyName
	FROM #T a WITH(NOLOCK), JobPublish b WITH(NOLOCK), cpMainPublish c WITH(NOLOCK)
	WHERE a.JobId = b.ID AND b.cpMainId = c.ID
	ORDER BY a.ID

	SELECT COUNT(1) FROM #T
END
GO

/****** Object:  StoredProcedure [dbo].[v2018_pcMobileFollowUpInsert]    Script Date: 2018/12/13 19:13:42 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--##############################################
--添加人：Lucifer
--添加时间：2018-8-5
--描述：追踪手机号，如果注册了，就删除
--##############################################
CREATE PROCEDURE [dbo].[v2018_pcMobileFollowUpInsert] (
	@Mobile VARCHAR(11),
	@SessionId VARCHAR(100)
)
AS
SET NOCOUNT ON
BEGIN
	IF EXISTS(SELECT TOP 1 'X' FROM paMobileFollowUp WITH(NOLOCK) WHERE ContactDate IS NOT NULL AND Mobile = @Mobile)
		RETURN

	IF EXISTS(SELECT TOP 1 'X' FROM paMain WITH(NOLOCK) WHERE Mobile = @Mobile)
		RETURN

	DELETE FROM paMobileFollowUp WHERE Mobile = @Mobile OR SessionId = @SessionId
	INSERT INTO paMobileFollowUp(Mobile, SessionId) VALUES (@Mobile, @SessionId)
END
SET NOCOUNT OFF
GO

/****** Object:  StoredProcedure [dbo].[v2018_pcPaAttentionSelect]    Script Date: 2018/12/13 19:13:42 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--################################################################
--创建人：Lucifer
--创建时间：2018-7-23
--描述：获取个人关注列表
--@AttentionType 1、企业 2、职位
--################################################################
CREATE PROCEDURE [dbo].[v2018_pcPaAttentionSelect]
(
	@paMainID INT, 
	@AttentionType TINYINT
)
AS
SET NOCOUNT ON
BEGIN
	IF @AttentionType = 1 --企业
	BEGIN
		SELECT a.PaMainID, a.ID, a.AddDate, b.ID CpMainID, b.SecondID CpSecondID, b.Name, b.DcCompanyKindID, b.DcCompanySizeID, 
		a.AddDate SortDate, dbo.GetCpIndustry(b.ID) Industry, b.LogoFile LogoUrl, b.RealName, b.MemberType INTO #tcp
		FROM PaAttention a WITH(NOLOCK), CpMain b WITH(NOLOCK)
		WHERE a.AttentionType = 1
		AND a.AttentionID = b.ID
		AND a.PaMainID = @paMainID
		AND b.IsDelete = 0
		ORDER BY a.AddDate DESC

		--企业职位最近更新时间
		UPDATE d SET d.SortDate = c.JobAddDate
		FROM #tcp d, 
		(SELECT a.CpMainID, MAX(a.LastModifyDate) JobAddDate
		FROM Job a WITH(NOLOCK)
		WHERE a.CpMainID IN (SELECT CpMainID FROM #tcp)
		GROUP BY a.CpMainID) c 
		WHERE d.CpMainID = c.CpMainID AND d.SortDate < c.JobAddDate

		SELECT * FROM #tcp ORDER BY SortDate DESC

		SELECT TOP 200 a.*, a.Valid JobValid, a.ID JobID, a.[Name] JobName, a.SecondId EnJobId, dbo.GetCaOnlineStatus(a.caMainId) IsOnline,
		(SELECT COUNT(1) FROM exJobApply WITH(NOLOCK) WHERE CvMainID IN (
			SELECT ID FROM CvMain WITH(NOLOCK) WHERE PaMainID = @paMainID
		) AND JobId = a.ID) IsApply, a.IssueDate
		FROM Job a WITH(NOLOCK), #tcp b WITH(NOLOCK)
		WHERE a.cpMainID = b.cpMainId AND a.IssueDate > b.AddDate ORDER BY a.IssueDate DESC
	END
	ELSE IF @AttentionType = 2 --职位
		BEGIN
		SELECT a.PaMainID, a.ID AttentionId, a.AddDate AttentionDate, b.*, b.ID JobID, b.SecondID EnJobId, b.Name JobName, d.SecondID CpSecondID, d.Name CpName, 0 IsApply, b.Valid JobValid, dbo.GetCaOnlineStatus(b.caMainID) IsOnline, d.LogoFile
		INTO #TJob
		FROM paAttention a WITH(NOLOCK), Job b WITH(NOLOCK), CpMain d WITH(NOLOCK)
		WHERE a.AttentionType = 2 
		AND a.AttentionID = b.ID
		AND a.PaMainID = @paMainID
		AND b.CpMainID = d.ID
		ORDER BY a.AddDate DESC

		UPDATE #TJob
		SET IsApply = 1
		WHERE JobID IN(
			SELECT JobID
			FROM exJobApply WITH(NOLOCK)
			WHERE CvMainiD IN (
				SELECT ID FROM CvMain WITH(NOLOCK)
				WHERE PaMainID = @paMainID
			)
		)

		--职位
		SELECT * FROM #TJob
	END
END
SET NOCOUNT OFF
GO

/****** Object:  StoredProcedure [dbo].[v2018_pcPaCvTagsSave]    Script Date: 2018/12/13 19:13:42 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--###########################################
--添加人：Lucifer
--添加时间：2018-7-17
--描述：保存个人标签
--###########################################
CREATE PROCEDURE [dbo].[v2018_pcPaCvTagsSave] 
(	
	@paMainID INT,
	@cvMainID INT,
	@Tags NVARCHAR(1000)
)
AS
SET NOCOUNT OFF
BEGIN		
	IF NOT EXISTS(SELECT 'X' FROM cvMain WHERE paMainID = @paMainID AND ID = @cvMainID)
	BEGIN
		RETURN -1
	END
	CREATE TABLE #T (
		ID INT IDENTITY(1, 1),
		cvMainID INT,
		Tag NVARCHAR(20),
		VerifyDate SMALLDATETIME
	)
	INSERT INTO #T(cvMainID, Tag)
	SELECT @cvMainID, REPLACE(REPLACE(a, CHAR(10), ''), CHAR(13), '')
	FROM dbo.fnSplit(@Tags,'@')

	DELETE FROM #T WHERE ID > 10
	DELETE FROM cvTags WHERE cvMainID = @cvMainID
	
	UPDATE #T 
	SET VerifyDate = GETDATE()
	WHERE EXISTS(SELECT 'x' FROM paTagsMain WHERE Tag = #T.Tag)
	
	INSERT INTO cvTags(cvMainID, Tags, VerifyDate)
	SELECT cvMainID, Tag, VerifyDate
	FROM #T
	DROP TABLE #T
	--更新CvLevel
	EXEC v2018_pcCvMainByCvLevelUpdate 2, @cvMainID, 5, 1
	RETURN 1
END
SET NOCOUNT ON
GO

/****** Object:  StoredProcedure [dbo].[v2018_pcPaGetPasswordLogInsert]    Script Date: 2018/12/13 19:13:42 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--######################################
--添加人：Lucifer
--添加时间：2018-7-13
--描述：插入取回密码记录
--返回值：-1 同一IP找回不能超过20次
--        -2 手机号找回密码每天不超过3次
--	      -3 用户名/邮箱找回密码每天不超过5次
--         0 查无此号
--         1 成功
--######################################
CREATE PROCEDURE [dbo].[v2018_pcPaGetPasswordLogInsert]
(
	@Username VARCHAR(50),
	@IP VARCHAR(15)
)
AS
SET NOCOUNT ON
BEGIN
	--同一IP找回不能超过20次
	IF (SELECT COUNT(1) FROM paGetPasswordLog WITH(NOLOCK) WHERE IP = @IP AND AddDate > CONVERT(VARCHAR(10), GETDATE(), 120)) >= 20
	BEGIN
		SELECT -1 Result
		RETURN
	END

	DECLARE @AskNo AS VARCHAR(40)
	DECLARE @ActivateCode AS VARCHAR(6)
	SET @AskNo = REPLACE(NEWID(), '-', '')
	SET @ActivateCode = RAND() * 899999 + 100000

	DECLARE @T TABLE(
		ID INT,
		Username VARCHAR(50),
		Email VARCHAR(50),
		Mobile VARCHAR(11)
	)

	IF dbo.IsMobile(@Username) = 1
	BEGIN
		--手机号找回密码每天不超过3次
		IF (SELECT COUNT(1) FROM paGetPasswordLog WITH(NOLOCK) WHERE UserNameIn = @Username AND AddDate > CONVERT(VARCHAR(10), GETDATE(), 120)) >= 3
		BEGIN
			SELECT -2 Result
			RETURN
		END

		INSERT INTO @T
		SELECT ID, UserName, Email, Mobile
		FROM paMain WITH(NOLOCK INDEX(IX_PaMain_Mobile))
		WHERE Mobile = @Username
		AND MobileVerifyDate IS NOT NULL
		ORDER BY Lastlogindate DESC
	END
	ELSE
	BEGIN
		--用户名/邮箱找回密码每天不超过5次
		IF (SELECT COUNT(1) FROM paGetPasswordLog WITH(NOLOCK) WHERE UserNameIn = @Username AND AddDate > CONVERT(VARCHAR(10), GETDATE(), 120)) >= 5
		BEGIN
			SELECT -3 Result
			RETURN
		END

		IF dbo.IsEmail(@Username) = 1
		BEGIN
			INSERT INTO @T
			SELECT ID, UserName, Email, Mobile
			FROM paMain WITH(NOLOCK INDEX(IX_paMain_Email))
			WHERE Email = @Username
			ORDER BY LastLoginDate DESC
		END
		ELSE
		BEGIN
			INSERT INTO @T
			SELECT ID, UserName, Email, Mobile
			FROM paMain WITH(NOLOCK INDEX(IX_PaMain_UserNameLower))
			WHERE UserNameLower = @Username
			ORDER BY LastLoginDate DESC
		END
	END
	--插入找回密码记录
	IF (SELECT COUNT(1) FROM @T) = 0
	BEGIN
		SELECT 0 Result
	END
	ELSE
	BEGIN
		INSERT INTO paGetPasswordLog(paMainID, UserNameIn, [IP], VerifyCode, UserName, Email, Mobile, UniqueId, ActivateCode, AskNo)
		SELECT ID, @UserName, @IP, '0000', UserName, Email, Mobile, REPLACE(NEWID(), '-', ''), @ActivateCode, @AskNo
		FROM @T

		SELECT 1 Result, ActivateCode, UniqueId, AskNo, UserName, Email
		FROM paGetPasswordLog WITH(NOLOCK)
		WHERE AskNo = @AskNo
	END
END
SET NOCOUNT OFF
GO

/****** Object:  StoredProcedure [dbo].[v2018_pcPaHeaderInfoSelect]    Script Date: 2018/12/13 19:13:43 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2018.6.29
--创建人：Lucifer
--说明：获取个人公告
--#####################################################
CREATE PROCEDURE [dbo].[v2018_pcPaHeaderInfoSelect]
(
    @paMainID INT
)
AS
SET NOCOUNT ON
BEGIN
	DECLARE @T AS TABLE(
	  [Type] INT,
	  [Count] INT
	)

	--取未答复的面试通知
	INSERT INTO @T
	SELECT 1, COUNT(1)
	FROM exInterView a WITH(NOLOCK) 
	INNER JOIN cvMain b WITH(NOLOCK) ON a.cvMainID = b.ID 
	WHERE a.PersonDeleted = 0 AND b.paMainID = @paMainID AND a.Reply = 0

	--取未答复的应聘邀请	
	INSERT INTO @T
	SELECT 2, COUNT(1)
	FROM caCvIntention a WITH(NOLOCK) 
	INNER JOIN cvMain b WITH(NOLOCK) ON a.cvMainID = b.ID 
	WHERE PersonDeleted = 0 AND paMainID = @paMainID AND Reply IS NULL

	--取未查看的网站消息
	INSERT INTO @T
	SELECT 3, COUNT(1)
	FROM PaNotify WITH(NOLOCK)
	WHERE paMainID = @paMainID 
	AND (
		(NotifyType = 1 AND IsViewed = 0) OR 	--一次性消息，看过就不再通知了
		(NotifyType = 2 AND EndDate > GETDATE())	--即时消息，到期前（EndDate）一直通知
	)

	--取未查看的投诉
	INSERT INTO @T
	SELECT 4, COUNT(1)
	FROM CaPlaint a WITH(NOLOCK INDEX(IX_caPlaint_cvMainID)), cvMain b WITH(NOLOCK INDEX(IX_cvMain_paMainID))
	WHERE a.cvMainID = b.ID AND b.PaMainID = @PaMainID	AND a.IsViewed = 0	AND a.ReplyType = 1

	SELECT * FROM @T

	SELECT TOP 1 ID, Title, AnnounceDate, Content, [Type], Refreshdate
	FROM QlrcNews WITH(NOLOCK)
	WHERE (VersionId = (SELECT dcProvinceId FROM paMain WITH(NOLOCK) WHERE ID = @paMainID) OR VersionId = 0)
	AND NewsType = 1
	ORDER BY refreshdate DESC
	OPTION (KEEPFIXED PLAN)
END
SET NOCOUNT OFF
GO

/****** Object:  StoredProcedure [dbo].[v2018_pcPaJobClickLogInsert]    Script Date: 2018/12/13 19:13:43 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2018.8.20
--创建人：Lucifer
--说明：插入查看联系方式记录
--#####################################################
CREATE PROCEDURE [dbo].[v2018_pcPaJobClickLogInsert]
(
	@paMainId INT,
	@JobId INT,
	@IP VARCHAR(31)
)
AS
SET NOCOUNT ON
BEGIN
	--在黑名单，不让看
	IF EXISTS(SELECT 'X' FROM paJobClickCount WITH(NOLOCK) WHERE [IP] = @IP)
	BEGIN
		RETURN 0
	END
	--未申请过该职位，不让看
	IF NOT EXISTS(
		SELECT TOP 1 'X' FROM exJobApply WITH(NOLOCK) WHERE JobId = @JobId AND cvMainId IN(
			SELECT ID FROM cvMain WITH(NOLOCK) WHERE paMainId = @paMainId
		)
	)
	BEGIN
		RETURN 0
	END
	
	IF NOT EXISTS(
		SELECT 'X' FROM paJobClickLog WITH(NOLOCK)
		WHERE JobId = @JobId AND [IP] = @IP AND AddDate > DATEADD(SECOND, -5, GETDATE())
	)
	BEGIN
		INSERT INTO paJobClickLog(JobId, paMainId, [IP], AddDate)
		VALUES(@JobId, @paMainId, @IP, GETDATE())
	END
	RETURN 1
END
GO

/****** Object:  StoredProcedure [dbo].[v2018_PcPaJobCompareInsert]    Script Date: 2018/12/13 19:13:43 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--####################################################
--添加人：Lucifer
--添加时间：2018-6-27
--描述：生成你的菜儿
--修改：将今天推荐过了就不推荐的判断去掉，因为新建简历完善后，都会推荐你的菜儿 Lucifer
--####################################################
CREATE PROCEDURE [dbo].[v2018_PcPaJobCompareInsert]
(
	@PaMainID INT
)
AS
SET NOCOUNT ON
BEGIN
	--今天推荐过了就不推荐了
	--IF EXISTS(SELECT 'x' FROM PaJobCompare WITH(NOLOCK) WHERE PaMainID = @PaMainID AND AddDate > CONVERT(CHAR(10), GETDATE(), 120))
	--	RETURN
	
	CREATE TABLE #T(
		JobID INT, 
		SimilarJobID INT, 
		JobCount INT, 
		Pecentage FLOAT, 
		SimilarCount INT,
		Source VARCHAR(15)
	)

	DECLARE @BatchNo SMALLINT, @LastRecommenedNo TINYINT, @JobID INT, @JobCount INT, @PushCount INT, @Top INT
	
	SELECT @BatchNo = ISNULL(MAX(BatchNo), 0), @LastRecommenedNo = ISNULL(MIN(LastRecommenedNo), 6), @Top = 0
	FROM PaJobCompare WITH(NOLOCK)
	WHERE PaMainID = @PaMainID
	
	--如果最后一次登录时间为昨天那么剩余推送次数设置为6次
	IF (SELECT LastLoginDate FROM PaMain WITH(NOLOCK) WHERE ID = @PaMainID) > CONVERT(CHAR(10), GETDATE() - 1, 120)
	BEGIN
		SELECT @LastRecommenedNo = 6
	END
	IF ISNULL(@LastRecommenedNo, 0) = 0
		SET @LastRecommenedNo = 6

	SELECT jobID, COUNT(1) cnt 
	INTO #TJobSimilar 
	FROM exJobApplyMonthTemp WITH(NOLOCK)
	WHERE JobID IN(
		SELECT JobID 
		FROM exJobApplyMonthTemp
		WHERE CvMainID IN (
			SELECT ID 
			FROM CvMain WITH(NOLOCK)
			WHERE PaMainID = @PaMainID
		)
	) 
	GROUP BY jobID 
	HAVING COUNT(1) > 1
	
	WHILE EXISTS(SELECT jobID FROM #TJobSimilar)
	BEGIN
		SELECT TOP 1 @JobID = jobID, @JobCount = cnt 
		FROM #TJobSimilar
		
		INSERT INTO #T (JobID, SimilarJobID, JobCount, Pecentage, SimilarCount)
		SELECT @JobID, JobID, @JobCount, CAST(COUNT(1) AS FLOAT)*100/@JobCount, COUNT(1) 	
		FROM exJobApplyMonthTemp 	
		WHERE cvmainid IN(	
			SELECT cvMainID 
			FROM exJobApplyMonthTemp 
			WHERE jobid = @JobID) 
		AND jobid <> @JobID 
		AND EXISTS(		--职位必须有效且没被删除
			SELECT 'X' 
			FROM Job WITH(NOLOCK) 
			WHERE id = exJobApplyMonthTemp.JobID 
			AND Valid = 1
			AND IsDelete = 0
			AND IssueEnd > GETDATE())
			AND NOT EXISTS(--已经申请过的不再推荐
				SELECT 'X'
				FROM exJobApply WITH(NOLOCK)
				WHERE CvMainID IN (
					SELECT ID 
					FROM CvMain WITH(NOLOCK)
					WHERE PaMainID = @PaMainID
				)
				AND JobID = exJobApplyMonthTemp.JobID 
		)
		GROUP BY JobID 	
		HAVING COUNT(1) > 1
		ORDER BY COUNT(1) desc
		
		DELETE FROM #TJobSimilar WHERE jobID = @JobID
	END
	UPDATE #t SET Source = 'J' + LTRIM(STR(JobId))
	DROP TABLE #TJobSimilar
	
	INSERT INTO #T (SimilarJobID, JobCount)
	SELECT TOP 10 JobID, COUNT(1) 	
	FROM exJobApplyMonthTemp
	WHERE cvMainID IN(
		SELECT TOP 10 CvMainID 
		FROM exJobApplyMonthTemp
		WHERE JobID IN(	
			SELECT JobID 
			FROM exJobApplyMonthTemp
			WHERE CvMainID IN (
				SELECT ID 
				FROM CvMain WITH(NOLOCK)
				WHERE PaMainID = @PaMainID
			)
		) 
		AND NOT EXISTS(SELECT 'x' FROM CvMain WHERE PaMainID = @PaMainID AND id = exJobApplyMonthTemp.cvMainID)	
		GROUP BY CvMainID 	
		ORDER BY COUNT(1) DESC
	)
	AND NOT EXISTS(SELECT 'x' FROM CvMain WHERE PaMainID = @PaMainID AND id = exJobApplyMonthTemp.cvMainID)	
	AND EXISTS(		--职位必须有效且没被删除
		SELECT 'X' 
		FROM Job WITH(NOLOCK) 
		WHERE id = exJobApplyMonthTemp.JobID 
		AND Valid = 1
		AND IsDelete = 0
		AND IssueEnd > GETDATE())
	AND NOT EXISTS(--已经申请过的不再推荐
		SELECT 'X'
		FROM exJobApply WITH(NOLOCK)
		WHERE CvMainID IN (
			SELECT ID 
			FROM CvMain WITH(NOLOCK)
			WHERE PaMainID = @PaMainID
		)
		AND JobID = exJobApplyMonthTemp.JobID 
	) 
	GROUP BY JobID 	
	HAVING COUNT(1) > 1
	ORDER BY COUNT(1) desc
	UPDATE #t SET Source = 'from cvMain' WHERE Source IS NULL

	DECLARE @t AS TABLE(Id INT IDENTITY(1,1 ), SimilarJobID INT, Source VARCHAR(15))
	INSERT INTO @t(SimilarJobID)
	SELECT SimilarJobID
	FROM #T
	GROUP BY SimilarJobID
	ORDER BY COUNT(1) DESC

	UPDATE a SET a.Source = (SELECT TOP 1 Source FROM #t WHERE a.SimilarJobID = #t.SimilarJobID ORDER BY Source DESC)
	FROM @t a

	DELETE FROM @t WHERE SimilarJobID IN(SELECT a.SimilarJobID FROM @t a, Job b, cpMain c WHERE a.SimilarJobID = b.ID AND b.cpMainID = c.ID AND c.Name LIKE '%保险%')
	
	IF @BatchNo = 0
	BEGIN
		INSERT INTO PaJobCompare(BatchNo, PaMainID, CompareJobID, LastRecommenedNo, Source)
		SELECT TOP 10 @BatchNo + 1, @PaMainID, SimilarJobID, 5, Source
		FROM @t
		ORDER BY Id
		
		SELECT @PushCount = COUNT(1) 
		FROM PaJobCompare WITH(NOLOCK)
		WHERE PaMainID = @PaMainID
		AND BatchNO = @BatchNo + 1
		AND LastRecommenedNo = 5
		
		IF @PushCount < 10
			SET @Top = 10 - @PushCount
	END
	ELSE
	BEGIN
		INSERT INTO PaJobCompare(BatchNo, PaMainID, CompareJobID, LastRecommenedNo, Source)
		SELECT TOP 5 @BatchNo + 1, @PaMainID, SimilarJobID, @LastRecommenedNo-1, Source
		FROM @T a
		WHERE NOT EXISTS(			--推荐过的就不再推荐了
			SELECT 'X'
			FROM PaJobCompare WITH(NOLOCK)
			WHERE PaMainID = @PaMainID
			AND CompareJobID = a.SimilarJobID
		)
		ORDER BY Id

		--推荐不足10个 从原你的菜儿继续推荐
		SELECT @PushCount = COUNT(1) 
		FROM PaJobCompare WITH(NOLOCK)
		WHERE PaMainID = @PaMainID
		AND BatchNO = @BatchNo + 1
		AND LastRecommenedNo = @LastRecommenedNo-1
		
		IF @PushCount < 5
			SET @Top = 10 - @PushCount
	END

	IF @Top > 0
	BEGIN		 
		DECLARE @Job AS TABLE(
			Id INT,
			cpMainId INT,
			dcRegionId VARCHAR(6),
			dcJobTypeId VARCHAR(4),
			dcSalaryId INT,
			EmployType INT,
			dcEducationId INT,
			MinExperience INT,
			MinAge INT,
			MaxAge INT,
			AgeScore INT,
			EduScore INT,
			ExpScore INt,
			SizeScore INT
			)
		DECLARE @JobPlace AS TABLE(Id INT IDENTITY(1, 1), dcRegionId VARCHAR(6))
		DECLARE @JobType AS TABLE(Id INT IDENTITY(1, 1), dcJobTypeId VARCHAR(4))
		DECLARE @t1 AS TABLE(dcRegionId VARCHAR(6))
		DECLARE @t2 AS TABLE(dcJobTypeId VARCHAR(4))
		DECLARE @CvMainID INT, @dcSalaryId INT, @EmployType INT, @Degree INT, @Exp INT, @Age INT, @ThisMonth INT
		SET @ThisMonth = CONVERT(VARCHAR(6), GETDATE(), 112)

		SELECT TOP 1 @cvMainId = b.Id, @Age = (@ThisMonth - a.BirthDay) / 100,
			@dcSalaryId = dcSalaryID, @EmployType = EmployType, 
			@Degree = Degree, @Exp = RelatedWorkYears
		FROM paMain a WITH(NOLOCK), cvMain b WITH(NOLOCK)
		WHERE a.Id = b.paMainId
		AND a.Id = @paMainId
		
		INSERT INTO @JobPlace(dcRegionId)
		SELECT dcRegionId FROM cvJobPlace WITH(NOLOCK)
		WHERE cvMainId = @cvMainId

		INSERT INTO @JobType(dcJobTypeId)
		SELECT dcJobTypeId FROM cvJobType WITH(NOLOCK)
		WHERE cvMainId = @cvMainId

		DELETE a FROM @JobPlace a, @JobPlace b WHERE a.id <> b.Id AND a.dcRegionID <> b.dcRegionId AND b.dcRegionId LIKE a.dcRegionId + '%'
		DELETE a FROM @JobType a, @JobType b WHERE a.id <> b.Id AND a.dcJobTypeId <> b.dcJobTypeId AND b.dcJobTypeId LIKE a.dcJobTypeId + '%'
		INSERT INTO @t2 
		SELECT Id FROM dcJobType WHERE ID IN(SELECT dcJobTypeId FROM @JobType) OR ParentID IN(SELECT dcJobTypeId FROM @JobType)

		INSERT INTO @t1 SELECT Id FROM dcRegion WHERE ID IN(SELECT dcRegionId FROM @JobPlace) 
		INSERT INTO @t1 SELECT Id FROM dcRegion WHERE LEFT(ID, 4) IN(SELECT dcRegionId FROM @JobPlace)
		INSERT INTO @t1 SELECT Id FROM dcRegion WHERE LEFT(ID, 2) IN(SELECT dcRegionId FROM @JobPlace)
		--===========================================
		INSERT INTO @Job(Id, cpMainId, dcRegionId, dcJobTypeId, dcSalaryId, EmployType, dcEducationId, MinExperience, MinAge, MaxAge)
		SELECT TOP 200 Id, cpMainId, dcRegionId, dcJobTypeId, dcSalaryId, EmployType, dcEducationId, MinExperience, MinAge, MaxAge
		FROM jobPublish WITH(NOLOCK)
		WHERE EmployType = @EmployType
		AND dcRegionID IN(SELECT dcRegionId FROM @t1)
		AND dcJobTypeId IN(SELECT dcJobTypeId FROM @t2)
		AND dcSalaryId IN(100, @dcSalaryId)
		AND EXISTS(SELECT 'x' FROM cpMainPublish WITH(NOLOCK) WHERE LastLoginDate > GETDATE() - 31 AND cpMainPublish.Id = cpMainId)
		ORDER BY RefreshDate DESC

		DELETE @Job WHERE Id IN(SELECT CompareJobId FROM paJobCompare WITH(NOLOCK) WHERE paMainId = @pamainId)
		DELETE @Job WHERE Id IN(SELECT JobId FROM paYourFood WITH(NOLOCK) WHERE paMainId = @pamainId)
		DELETE @Job WHERE Id IN(SELECT JobId FROM ExJobApply WITH(NOLOCK) WHERE cvMainID IN(SELECT ID FROM cvMain WITH(NOLOCK) WHERE paMainId = @pamainId))
		IF(SELECT COUNT(*) FROM @Job) > 3
		BEGIN			
			UPDATE a SET a.SizeScore = b.dcCompanySizeId * -1, EduScore = 0, AgeScore = 0, ExpScore = 0  FROM @Job a, cpMainPublish b WHERE a.cpMainId = b.ID
			UPDATE @Job SET EduScore = dcEducationId - @Degree WHERE dcEducationId > @Degree AND dcEducationId < 100
			UPDATE @Job SET EduScore = @Degree - dcEducationId WHERE dcEducationId < @Degree AND dcEducationId < 100
			UPDATE @Job SET MinAge = 16 WHERE MinAge = 99
			UPDATE @Job SET MaxAge = 60 WHERE MaxAge = 99
			UPDATE @Job SET AgeScore = (MinAge - @Age) / 5 + 1 WHERE MinAge > @Age
			UPDATE @Job SET AgeScore = (@Age - MaxAge) / 5 + 1 WHERE MaxAge < @Age
			IF @Exp = 0
				SET @Exp = 1
			ELSE IF @Exp IN(1, 2)
				SET @Exp = 2
			ELSE IF @Exp IN(3,4,5)
				SET @Exp = 3
			ELSE IF @Exp IN(6,7,8,9,10)
				SET @Exp = 4
			ELSE IF @Exp > 10
				SET @Exp = 5
			ELSE
				SET @Exp = 0
			UPDATE @Job SET MinExperience = CASE WHEN MinExperience = 5 THEN 1 ELSE MinExperience + 1 END WHERE MinExperience > 0
			UPDATE @Job SET ExpScore = MinExperience - @Exp WHERE MinExperience > @Exp
			UPDATE @Job SET ExpScore = @Exp - MinExperience WHERE MinExperience < @Exp AND MinExperience > 0	
		END
		INSERT INTO PaJobCompare(BatchNo, PaMainID, CompareJobID, LastRecommenedNo, Source)
		SELECT TOP (@Top) @BatchNo + 1, @PaMainID, Id, 5, 'Expect'
		FROM @Job ORDER BY EduScore, ExpScore + SizeScore + AgeScore
	END	

	DROP TABLE #T
END
SET NOCOUNT OFF
GO

/****** Object:  StoredProcedure [dbo].[v2018_pcPaJobCompareSelect]    Script Date: 2018/12/13 19:13:44 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--################################################################
--创建人：Lucifer
--创建时间：2018-7-23
--描述：获取你的菜儿
--@BatchNo 推荐批次，0、最新 大于0、指定 -1、全部
--################################################################
CREATE PROCEDURE [dbo].[v2018_pcPaJobCompareSelect]
(
    @PaMainID INT,
    @BatchNo SMALLINT
)
AS
SET NOCOUNT ON
BEGIN
    IF @BatchNo > 0
    BEGIN
        SELECT a.*, b.*, c.Name CpName, c.HasLicence, c.SecondID EnCpMainID, b.ID JobID, b.SecondID EnJobID, 
            b.Name JobName, b.Valid JobValid, a.AddDate RecommenedDate, dbo.GetCaOnlineStatus(b.caMainID) IsOnline, 
            c.LogoFile LogoUrl, c.RealName, (SELECT COUNT(1) FROM exJobApply WITH(NOLOCK) WHERE CvMainID IN (
				SELECT ID FROM CvMain WITH(NOLOCK) WHERE PaMainID = @paMainID
			) AND JobId = a.CompareJobID) IsApply
        FROM PaJobCompare a WITH(NOLOCK)
        LEFT JOIN Job b WITH(NOLOCK) ON b.ID = a.CompareJobID
        LEFT JOIN CpMain c WITH(NOLOCK) ON c.ID = b.CpMainID
        WHERE PaMainID = @PaMainID
        AND BatchNo = @BatchNo
        ORDER BY a.AddDate DESC
    END
    ELSE IF @BatchNo = 0
    BEGIN
        SELECT a.*, b.*, c.Name CpName, c.HasLicence, c.SecondID EnCpMainID, b.ID JobID, b.SecondID EnJobID, 
            b.Name JobName, b.Valid JobValid, a.AddDate RecommenedDate, dbo.GetCaOnlineStatus(b.caMainID) IsOnline, 
            c.LogoFile LogoUrl, c.RealName, (SELECT COUNT(1) FROM exJobApply WITH(NOLOCK) WHERE CvMainID IN (
				SELECT ID FROM CvMain WITH(NOLOCK) WHERE PaMainID = @paMainID
			) AND JobId = a.CompareJobID) IsApply
        FROM PaJobCompare a WITH(NOLOCK)
        LEFT JOIN Job b WITH(NOLOCK) ON b.ID = a.CompareJobID
        LEFT JOIN CpMain c WITH(NOLOCK) ON c.ID = b.CpMainID
        WHERE PaMainID = @PaMainID
		AND b.Valid = 1
        AND BatchNo = (
            SELECT MAX(BatchNo) 
            FROM PaJobCompare WITH(NOLOCK)
            WHERE PaMainID = @PaMainID
        )
        ORDER BY a.AddDate DESC
    END
    ELSE
    BEGIN
        SELECT a.*, b.*, c.Name CpName, c.HasLicence, c.SecondID EnCpMainID, b.ID JobID, b.SecondID EnJobID, 
            b.Name JobName, b.Valid JobValid, a.AddDate RecommenedDate, dbo.GetCaOnlineStatus(b.caMainID) IsOnline, 
            c.LogoFile LogoUrl, c.RealName, (SELECT COUNT(1) FROM exJobApply WITH(NOLOCK) WHERE CvMainID IN (
				SELECT ID FROM CvMain WITH(NOLOCK) WHERE PaMainID = @paMainID
			) AND JobId = a.CompareJobID) IsApply
        FROM PaJobCompare a WITH(NOLOCK)
        LEFT JOIN Job b WITH(NOLOCK) ON b.ID = a.CompareJobID
        LEFT JOIN CpMain c WITH(NOLOCK) ON c.ID = b.CpMainID
		WHERE PaMainID = @PaMainID
			AND b.Valid = 1
		ORDER BY a.AddDate DESC
    END
END
SET NOCOUNT OFF
GO

/****** Object:  StoredProcedure [dbo].[v2018_pcPaLoginContactInsert]    Script Date: 2018/12/13 19:13:44 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2018.6.21
--创建人：Lucifer
--说明：关联第三方登陆
--ContactType 1、QQ登陆 2、人人登陆 3、微博登陆 4、微信登陆 5、百度登陆
--#####################################################
CREATE PROCEDURE [dbo].[v2018_pcPaLoginContactInsert]
(
	@paMainID INT,
	@OpenID VARCHAR(100),
	@ContactType TINYINT,
	@LoginType TINYINT
)
AS
BEGIN
	DELETE FROM paLoginContact WHERE Openid = @OpenID AND ContactType = @ContactType
	INSERT INTO paLoginContact(paMainID, Openid, ContactType, LoginType, AddDate)
	VALUES(@paMainID, @OpenID, @ContactType, @LoginType, GETDATE())
	
	IF @ContactType = 4
	BEGIN
		UPDATE wxFans SET PaMainID = @PaMainID WHERE OpenID = @OpenID
	END
END
GO

/****** Object:  StoredProcedure [dbo].[v2018_pcPaMainByLastLoginDateUpdate]    Script Date: 2018/12/13 19:13:44 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


--#####################################################
--创建时间：2018-6-5
--创建人：Lucifer
--说明：更新个人登陆时间
--当天第一次登陆，更新DateReport.PersonLoginNum_Net
--19是PC站回收，42是M站回收 如果不是当天第一次登陆，不记录登陆时间
--#####################################################
CREATE PROCEDURE [dbo].[v2018_pcPaMainByLastLoginDateUpdate]
(
	@paMainId INT,
	@dcProvinceId INT,
	@IP VARCHAR(31),
	@Browser VARCHAR(500),
	@LoginFrom TINYINT
)
AS
SET NOCOUNT ON
BEGIN
	SET @IP = dbo.SafeSQL(@IP)
	SET @Browser = dbo.SafeSQL(@Browser)

	DECLARE @LoginTodayFirst BIT
	SET @LoginTodayFirst = 0
	--当天第一次登陆，更新DateReport.PersonLoginNum_Net
	IF NOT EXISTS(SELECT 'x' FROM paLoginLog WITH(NOLOCK) WHERE paMainID = @paMainId AND AddDate >= CONVERT(VARCHAR(10), GETDATE(), 120))
	BEGIN
		UPDATE DateReport
		SET PersonLoginNum_Net = PersonLoginNum_Net + 1  
		WHERE CountDate = CONVERT(VARCHAR(8), GETDATE(), 112)
		AND Province_Id = @dcProvinceId

		SET @LoginTodayFirst = 1
	END
	--不是回收的或者第一次登陆的，插入登陆记录
	IF @LoginFrom NOT IN(19, 42) OR @LoginTodayFirst = 1
	BEGIN
		INSERT INTO paLoginLog(paMainID, LoginIP, Browser, LoginFrom) VALUES(@paMainId, @IP, ISNULL(@Browser, 'Null'), @LoginFrom)
		UPDATE PaMain SET
			LastLoginDate = GETDATE(),
			TotalLoginNum = ISNULL(TotalLoginNum, 0) + 1
		WHERE ID = @paMainId
	END
END
SET NOCOUNT OFF
GO

/****** Object:  StoredProcedure [dbo].[v2018_pcPaMainByLoginUpdate]    Script Date: 2018/12/13 19:13:45 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--------------------------------------------------
--添加人：Lucifer
--添加日期：2018-6-6
--说明：个人用户登陆
--------------------------------------------------
CREATE PROCEDURE [dbo].[v2018_pcPaMainByLoginUpdate]
(
	@IP VARCHAR(31),
	@dcProvinceId SMALLINT,
	@Browser VARCHAR(500),
	@paMainId INT,
	@LoginFrom TINYINT
)
AS
SET NOCOUNT ON
BEGIN
	--超过登陆次数,每天限制登录次数为20次
	IF (SELECT COUNT(1) FROM paLoginLog WITH(NOLOCK) WHERE paMainID = @paMainId AND AddDate > CONVERT(VARCHAR(10), GETDATE(), 120)) > 19
		RETURN -2
			
	--应届生网站抓取生成的个人用户，简历默认隐藏，第一次登陆的时候，将简历公开
	IF EXISTS (SELECT 'X' FROM paMain WITH(NOLOCK) WHERE RegisterType = 200 AND Id = @paMainId AND TotalLoginNum = 1)
	BEGIN
		UPDATE cvMain SET IsCvHidden = 0 WHERE paMainId = @paMainId
	END

	--登陆日志
	EXEC v2018_pcPaMainByLastLoginDateUpdate @paMainId, @dcProvinceId, @IP, @Browser, @LoginFrom
	RETURN @paMainId
END
SET NOCOUNT OFF

GO

/****** Object:  StoredProcedure [dbo].[v2018_pcPaMainByMobileUpdate]    Script Date: 2018/12/13 19:13:45 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--添加时间 20180622
--添加人   Lucifer
--用途     修改手机号+认证
--注意     当验证码为000000，是百度百聘注册账号的，百度过来的手机号默认为认证通过的--修改harry 出现号码为空，联系不到情况
--返回值   0  验证码错误
--         -1 邮箱黑名单
--#####################################################
CREATE PROCEDURE [dbo].[v2018_pcPaMainByMobileUpdate]
(
	@paMainId INT,
	@Mobile VARCHAR(13),
	@IP VARCHAR(31),
	@VerifyCode VARCHAR(6)
)
AS
BEGIN
	IF EXISTS(SELECT 'x' FROM Person_BLACK WITH(NOLOCK) WHERE Mobile = @Mobile)
	BEGIN
		----有黑名单，则增加拒绝次数
		UPDATE Person_Black SET RefuseCount = RefuseCount + 1 WHERE Mobile = @Mobile
		RETURN -1
	END

	----验证验证码是否正确
	DECLARE @paVerifyLogID INT
	SET @paVerifyLogID = 0
	SELECT @paVerifyLogID = ID FROM paVerifyLog WITH(NOLOCK)
	WHERE Mobile = @Mobile AND VerifyCode = @VerifyCode AND AddDate > DATEADD(HOUR, -1, GETDATE())
	
	IF @paVerifyLogID = 0 AND @VerifyCode <> '000000'
		RETURN 0

	DECLARE @MobileOld VARCHAR(13)
	SELECT @MobileOld = ISNULL(Mobile ,'') FROM paMain WITH(NOLOCK INDEX(PK_paMain))
	WHERE ID = @paMainId AND MobileVerifyDate IS NOT NULL

	IF NOT EXISTS(SELECT 'X' FROM PaMain WITH(NOLOCK) WHERE ID = @paMainId AND MobileVerifyDate IS NOT NULL AND Mobile = @Mobile)
	BEGIN
		UPDATE paVerifyLog SET VerifyDate = GETDATE() WHERE ID = @paVerifyLogID
		--把该手机号的其他账号状态修改为未认证
		UPDATE paMain SET MobileVerifyDate = NULL WHERE Mobile = @Mobile
		IF @VerifyCode <> '000000'
			UPDATE paMain SET Mobile = @Mobile, LastModifyDate = GETDATE(), MobileVerifyDate = GETDATE() WHERE ID = @paMainId
		IF LEN(ISNULL(@MobileOld, '')) > 0
		BEGIN
			INSERT INTO paOperationLog (paMainID, Operation, Details, [IP]) 
			VALUES(@paMainId, 35, '更新手机号码，原号码：<' + ISNULL(@MobileOld, '') + '>；新手机号码：<' + @Mobile + '>', @IP)
		END
	END

	RETURN 1
END
GO

/****** Object:  StoredProcedure [dbo].[v2018_pcPaMainByPasswordUpdate]    Script Date: 2018/12/13 19:13:45 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--###########################################
--添加人：Lucifer
--添加时间：2018-7-17
--描述：修改密码
--###########################################
CREATE PROCEDURE [dbo].[v2018_pcPaMainByPasswordUpdate]
(
	@ID INT,
	@Password VARCHAR(60),
	@PlainPassword VARCHAR(60),
	@IP VARCHAR(31)
)
AS
SET NOCOUNT OFF
BEGIN
	IF dbo.IsAccount(@PlainPassword) = 0
	BEGIN
		RETURN 0
	END
	UPDATE paMain SET [Password] = @Password, IsDefaultPassword = 0 WHERE ID = @ID
	--插入操作日志
	INSERT INTO paOperationLog (paMainID, Operation, Details, IP)
	VALUES(@ID, 21, '重置密码，新密码：<' + LEFT(@PlainPassword, 3) + '****>', @IP)
	--如果有找回密码记录，更新IsReset
	UPDATE paGetPasswordLog SET
		IsReset = 1
	WHERE AskNo IN(
		SELECT AskNo FROM paGetPasswordLog WITH(NOLOCK)
		WHERE paMainID = @ID
			AND AddDate > DATEADD(MINUTE, -60, GETDATE())
			AND IsReset IS NULL
	)
	RETURN 1
END
SET NOCOUNT ON
GO

/****** Object:  StoredProcedure [dbo].[v2018_pcPaMainByUsernameUpdate]    Script Date: 2018/12/13 19:13:46 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--###########################################
--添加人：Lucifer
--添加时间：2018-7-17
--描述：修改个人用户名
--返回值：-1 邮件黑名单
--        -2 邮件格式错误
--         0 邮箱重复
--###########################################
CREATE PROCEDURE  [dbo].[v2018_pcPaMainByUsernameUpdate]
(
	@ID INT,
	@Username VARCHAR(50),
	@IP VARCHAR(31)
)
AS
SET NOCOUNT OFF
--有黑名单，则增加拒绝次数
IF EXISTS(SELECT 'x' FROM Person_Black WITH(NOLOCK) WHERE Email = @Username)
BEGIN
	UPDATE Person_Black SET RefuseCount = ISNULL(RefuseCount, 0) + 1 WHERE Email = @Username
	RETURN -1
END
--用户名不是邮箱格式
IF dbo.IsEmail(@Username) = 0
BEGIN
	RETURN -2
END
--用户名重复
IF EXISTS(SELECT 'x' FROM paMain WITH(NOLOCK INDEX(IX_paMain_UserNameLower)) WHERE UserNameLower = @Username)
BEGIN
	RETURN 0
END
BEGIN TRY
	DECLARE @UsernameOld AS VARCHAR(50)
	SELECT @UsernameOld = UsernameLower
	FROM paMain WITH(NOLOCK INDEX(PK_paMain)) WHERE ID = @ID

	UPDATE paMain SET Username = @Username WHERE ID = @ID
	INSERT INTO paOperationLog (paMainID, Operation, Details, IP) 
	VALUES(@ID, 20, '更新用户名，原用户名：<' + @UsernameOld + '>；新用户名：<' + @Username + '>', @IP)

	RETURN 1
END TRY
BEGIN CATCH
	RETURN 0
END CATCH
SET NOCOUNT ON
GO

/****** Object:  StoredProcedure [dbo].[v2018_pcPaMainInsert]    Script Date: 2018/12/13 19:13:46 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--添加时间 20180614
--添加人   Lucifer
--用途     个人注册
--返回值   0  IP黑名单
--         -1 邮箱黑名单
--         -2 邮箱已存在
--         -3 注册失败
--         -4  10分钟之内注册超过10个（@RegisterType = 200的不考虑，属于应届生网站抓取的简历注册）
--#####################################################
CREATE PROCEDURE  [dbo].[v2018_pcPaMainInsert]
(
	@Email VARCHAR(50),
	@Password VARCHAR(60),
	@dcProvinceID SMALLINT,
	@RegisterIP VARCHAR(50),
	@RegisterFrom TINYINT,
	@RegisterType TINYINT,
	@UrlID INT,
	@InfoID INT,
	@Referer VARCHAR(500)
)
AS
SET NOCOUNT ON
BEGIN TRY
	--IP黑名单
	IF EXISTS(SELECT 'X' FROM IP_Black WITH(NOLOCK) WHERE [IP] = @RegisterIP)
	BEGIN
		RETURN 0
	END

	--10分钟之内注册超过10个（@RegisterType = 200的不考虑，属于应届生网站抓取的简历注册）
	IF (
		SELECT COUNT(*) FROM paMain WITH(NOLOCK)
		WHERE RegisterIp = @RegisterIp AND AddDate > DATEADD(MINUTE, -10, GETDATE()) AND @RegisterType <> 200
	) > 10
	BEGIN
		RETURN -4
	END

	--邮箱黑名单
	IF EXISTS(SELECT 'X' FROM Person_Black WITH(NOLOCK) WHERE Email = @Email)
	BEGIN
		UPDATE Person_black SET RefuseCount = ISNULL(RefuseCount, 0) + 1 WHERE Email = @Email
		RETURN -1
	END

	--邮箱已存在
	IF EXISTS(SELECT 'X' FROM paMain WITH(NOLOCK) WHERE Email = @Email)
	BEGIN
		RETURN -2
	END

	DECLARE @MaxId INT
	BEGIN TRAN
		INSERT INTO paMain
			(Username, [Password], dcProvinceID, dcSubSiteID, Email, RegisterIP, LastLoginDate, TotalLoginNum, RegisterFrom, RegisterType)
		VALUES(@Email, @Password, @dcProvinceID, @dcProvinceID, @Email, @RegisterIP, GETDATE(), 1, @RegisterFrom, @RegisterType)
		SET @MaxId = @@IDENTITY
		--应届生网站抓取的简历注册 不计入DateReport
		UPDATE DateReport SET PersonRegNum = ISNULL(PersonRegNum, 0) + 1, PersonLoginNum_Net = ISNULL(PersonLoginNum_Net, 0) + 1
		WHERE province_id = @dcProvinceID AND CountDate = CONVERT(VARCHAR(8), GETDATE(), 112) AND @RegisterType <> 200
		--操作日志
		INSERT INTO paOperationLog (paMainID, Operation, Details, [IP]) VALUES(@MaxID, 10, '注册个人账号成功。', @RegisterIP)
	COMMIT
END TRY
BEGIN CATCH
	ROLLBACK TRAN
	INSERT INTO LogDb..RegisterErrorLog SELECT @MaxId, '10|' + @RegisterIP+'|'+@RegisterFrom, @Email + ' ' + @Password, GETDATE()
	RETURN -3
END CATCH

BEGIN TRY
	IF @UrlID > 0
	BEGIN
		UPDATE [Url] SET AllResume = ISNULL(AllResume, 0) + 1, TodayResume = ISNULL(TodayResume, 0) + 1 WHERE ID = @UrlID
		IF EXISTS(SELECT 'X' FROM [Url] WHERE ID = @UrlID AND [Description] LIKE '%百度竞价%')
		BEGIN
			INSERT INTO UrlAccount VALUES(@UrlID, @MaxID, NULL, GETDATE())
		END
	END
	IF @InfoID > 0
	BEGIN
		IF NOT EXISTS(
			SELECT TOP 1 'X'
			FROM Info_DateReport WITH(NOLOCK)
			WHERE Countdate = CONVERT(VARCHAR(8), GETDATE(), 112)
			AND Province_Id = @dcProvinceID
			AND InfoManager_Id = @InfoID
		)
		BEGIN
			INSERT INTO Info_DateReport (Province_Id, InfoManager_Id, CountDate) 
			VALUES(@dcProvinceID, @InfoID, CONVERT(VARCHAR(8), GETDATE(), 112))
		END

		UPDATE Info_DateReport 
		SET AllResume = ISNULL(AllResume, 0) + 1
		WHERE CountDate = CONVERT(VARCHAR(8), GETDATE(), 112)
		AND Province_ID = @dcProvinceID
		AND InfoManager_ID = @InfoID

		INSERT INTO InfoLog(InfoManager_Id, [IP], Referer, paMainId) 
		VALUES(@InfoID, @RegisterIp, '', @MaxID)
	END
	IF LEN(@Referer) > 0
	BEGIN
		INSERT INTO paReferer(paMainId, Referer)
		VALUES(@MaxID, @Referer)
	END
END TRY
BEGIN CATCH
	
END CATCH
RETURN @MaxID
SET NOCOUNT OFF
GO

/****** Object:  StoredProcedure [dbo].[v2018_pcPaMainUpdate]    Script Date: 2018/12/13 19:13:46 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2018.6.21
--创建人：Lucifer
--说明：保存基本信息
--@ModifyType 1、修改基本信息 2、修改求职状态 3、修改屏蔽词
--#####################################################
CREATE PROCEDURE [dbo].[v2018_pcPaMainUpdate]
(
	@paMainID INT,
	@cvMainID INT,
	@Name NVARCHAR(6),
	@NameEng VARCHAR(30),
	@Gender BIT,
	@BirthDay INT,
	@LivePlace VARCHAR(6),
	@MapPlace INT,
	@AccountPlace VARCHAR(6),
	@GrowPlace VARCHAR(6),
	@OnlineContact TINYINT,
	@OnlineContactNo VARCHAR(50),
	@Homepage VARCHAR(200),
	@Marriage TINYINT,
	@Nation TINYINT,
	@Height TINYINT,
	@IsReceiveSms BIT,
	@CareerStatus TINYINT,
	@HideConditions NVARCHAR(500),
	@IP VARCHAR(39),
	@ModifyType TINYINT
)
AS
SET NOCOUNT ON
BEGIN TRAN
	IF NOT EXISTS(SELECT TOP 1 'X' FROM cvMain WITH(NOLOCK) WHERE ID = @cvMainID AND paMainID = @paMainID)
		GOTO ERR

	BEGIN TRY
		IF @ModifyType = 1 --修改基本信息
		BEGIN
			DECLARE @NameOld NVARCHAR(6)
			DECLARE @NameEngOld VARCHAR(30)
			DECLARE @OnlineContactNoOld VARCHAR(50)
			DECLARE @HomepageOld VARCHAR(200)
			DECLARE @IsReceiveSmsOld BIT

			--检查在线联系方式和号码
			IF @OnlineContact = 0
				SET @OnlineContactNo = NULL

			--取消不正确的主页格式
			SET @Homepage = REPLACE(@Homepage, 'http%3A//', 'http://')
			SET @Homepage = REPLACE(@Homepage, 'http://', '')

			--获得原始数据
			SELECT @NameOld = [Name], @NameEngOld = NameEng, @OnlineContactNoOld = OnlineContactNo,
				@HomepageOld = Homepage, @IsReceiveSmsOld = IsReceiveSms
			FROM paMain WITH(NOLOCK INDEX(PK_paMain))
			WHERE ID = @paMainID

			--选填没填置空
			SET @Name = dbo.v2018_SetVarcharNull(@Name)
			SET @NameEng = dbo.v2018_SetVarcharNull(@NameEng)
			SET @OnlineContact = dbo.v2018_SetIntNull(@OnlineContact)
			SET @Homepage = dbo.v2018_SetVarcharNull(@Homepage)
			SET @Marriage = dbo.v2018_SetIntNull(@Marriage)
			SET @Nation = dbo.v2018_SetIntNull(@Nation)
			SET @Height = dbo.v2018_SetIntNull(@Height)

			UPDATE paMain SET
				[Name] = @Name,
				NameEng = @NameEng,
				Gender = @Gender,
				BirthDay = @BirthDay,
				LivePlace = @LivePlace,
				AccountPlace = @AccountPlace,
				GrowPlace = @GrowPlace,
				OnlineContact = @OnlineContact,
				OnlineContactNo = @OnlineContactNo,
				Homepage = @Homepage,
				Marriage = @Marriage, 
				Nation = @Nation,
				Height = @Height,
				dcMapPlaceId = @MapPlace,
				IsReceiveSms = @IsReceiveSms,
				LastModifyDate = GETDATE()
			WHERE ID = @paMainID

			--添加审核记录
			EXEC v2018_pcCvModifyInsert @paMainID, @cvMainID, NULL, @Name, @NameOld, 'ac1', @IP
			EXEC v2018_pcCvModifyInsert @paMainID, @cvMainID, NULL, @NameEng, @NameEngOld, 'ae1', @IP
			EXEC v2018_pcCvModifyInsert @paMainID, @cvMainID, NULL, @OnlineContactNo, @OnlineContactNoOld, 'ac2', @IP
			EXEC v2018_pcCvModifyInsert @paMainID, @cvMainID, NULL, @Homepage, @HomepageOld, 'ac3', @IP

			--接收短信设置添加操作日志
			IF @IsReceiveSmsOld <> @IsReceiveSms
			BEGIN
				INSERT INTO paOperationLog(paMainID, Operation, Details, IP) 
				VALUES(@paMainID, 60, '更改接收短信设置为' + CASE @IsReceiveSms WHEN 1 THEN '<接收短信>' ELSE '<不接收短信>' END, @IP)
			END
		
			----修改cvMain.cvLevel
			IF @Name IS NOT NULL
			BEGIN
				EXEC v2018_pcCvMainByCvLevelUpdate 0, @cvMainID, 1, 1
			END

			IF @NameEng IS NOT NULL
			BEGIN
				EXEC v2018_pcCvMainByCvLevelUpdate 1, @cvMainID, 1, 1
			END

			----12小时内只保留一次修改记录
			DELETE FROM paOperationLog WHERE paMainID = @paMainID AND Operation = 11 AND AddDate > GETDATE() - 0.5
			INSERT INTO paOperationLog (paMainID, Operation, Details, IP) VALUES(@paMainID, 11, '更新基本信息成功。', @IP)
		END
		ELSE IF @ModifyType = 2 --修改求职状态
		BEGIN
			UPDATE paMain SET
				dcCareerStatus = @CareerStatus
			WHERE ID = @paMainID

			UPDATE cvMain SET
				RefreshDate = GETDATE()
			WHERE ID = @cvMainID AND DATEADD(HOUR, 1, RefreshDate) < GETDATE()
		END
		ELSE IF @ModifyType = 3 --修改屏蔽词
		BEGIN
			UPDATE paMain SET
				HideConditions = @HideConditions
			WHERE ID = @paMainID
			INSERT INTO paOperationLog (paMainID, Operation, Details, IP) VALUES(@paMainID, 50, '更新屏蔽设置成功。', @IP)
		END
	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH

COMMIT TRAN
RETURN 1
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END
SET NOCOUNT OFF
GO

/****** Object:  StoredProcedure [dbo].[v2018_pcPaPageViewLogUpdate]    Script Date: 2018/12/13 19:13:47 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--################################################################
--创建人：Lucifer
--创建时间：2018-7-23
--描述：更新个人动态
--@ViewPageType 1、面试邀请 2、应聘邀请 3、谁在关注我 4、我的关注 5、你的菜 6、申请的职位 7、聊天记录
--################################################################
CREATE PROCEDURE [dbo].[v2018_pcPaPageViewLogUpdate]
(
	@paMainId INT,
	@ViewPageType TINYINT
)
AS
SET NOCOUNT ON
BEGIN
	IF NOT EXISTS(SELECT 'X' FROM paPageViewLog WITH(NOLOCK) WHERE paMainId = @paMainId)
	BEGIN
		INSERT INTO paPageViewLog(paMainId, addDate, InterviewDate, IntentionDate, ViewLogDate, 
			AttentionDate, YourFoodDate, ApplyReplyDate) 
		VALUES(@paMainId, GETDATE() - 10, GETDATE() - 10, GETDATE() - 10, GETDATE() - 10,
			GETDATE() - 10, GETDATE() - 10, GETDATE() - 10)
	END
	
	IF @ViewPageType = 1
		UPDATE paPageViewLog SET InterviewDate = GETDATE(), InterviewCount = 0 WHERE paMainId = @paMainId 
	
	IF @ViewPageType = 2
		UPDATE paPageViewLog SET IntentionDate = GETDATE(), CpInvitationCount = 0 WHERE paMainId = @paMainId 
	
	IF @ViewPageType = 3
		UPDATE paPageViewLog SET ViewLogDate = GETDATE(), CvViewLogCount = 0 WHERE paMainId = @paMainId 
	
	IF @ViewPageType = 4
		UPDATE paPageViewLog SET AttentionDate = GETDATE(), MyAttentionCount = 0 WHERE paMainId = @paMainId 
	
	IF @ViewPageType = 5
		UPDATE paPageViewLog SET YourFoodDate = GETDATE(), YourFoodCount = 0 WHERE paMainId = @paMainId 
	
	IF @ViewPageType = 6
		UPDATE paPageViewLog SET ApplyReplyDate = GETDATE(), JobAppliedCount = 0 WHERE paMainId = @paMainId 
	
	IF @ViewPageType = 7
		UPDATE paPageViewLog SET ChatCount = 0 WHERE paMainId = @paMainId 
END
SET NOCOUNT OFF
GO

/****** Object:  StoredProcedure [dbo].[v2018_pcPaPlaintSelect]    Script Date: 2018/12/13 19:13:47 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--################################################################
--创建人：Lucifer
--创建时间：2018-7-23
--描述：获取企业投诉个人记录，更新为已查看
--################################################################
CREATE PROCEDURE [dbo].[v2018_pcPaPlaintSelect]
(
	@paMainID INT
)
AS
SET NOCOUNT ON
BEGIN
	UPDATE PaPlaint SET
		IsViewed = 1 
	WHERE paMainID = @paMainID

	SELECT a.*, c.Name CompanyName,c.SecondID
	FROM PaPlaint a WITH(NOLOCK)
	LEFT JOIN caMain b WITH(NOLOCK) ON a.caMainID = b.ID
	LEFT JOIN cpMain c WITH(NOLOCK) ON b.cpMainID = c.ID
	WHERE paMainID = @paMainID
	ORDER BY ID DESC
END
SET NOCOUNT OFF
GO

/****** Object:  StoredProcedure [dbo].[v2018_pcPaVerifyLogInsert]    Script Date: 2018/12/13 19:13:47 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--####################################################
--添加人：Lucifer
--添加时间：2018-6-27
--描述：获取短信/邮件验证码
--返回值 -1 邮件已认证
--       -2 一天同一IP验证超过10次
--       -3 一天同一手机号/邮件验证超过5次
--       -4 5分钟内同一手机号/邮件超过3次
--       -5 手机号黑名单
--####################################################
CREATE PROCEDURE [dbo].[v2018_pcPaVerifyLogInsert] 
(
    @Mobile VARCHAR(11),
    @Email VARCHAR(50),
    @IP VARCHAR(31),
    @paMainID INT
)
AS
SET NOCOUNT ON
BEGIN
	SET @Mobile = dbo.v2018_SetVarcharNull(@Mobile)
	SET @Email = dbo.v2018_SetVarcharNull(@Email)

	IF @Mobile IS NOT NULL
	BEGIN
		IF LEFT(@Mobile, 7) = '1713075' --该号段都是骗子
			RETURN -2

		IF EXISTS(SELECT 'X' FROM Person_Black WITH(NOLOCK) WHERE Mobile = @Mobile)
			RETURN -5

		IF EXISTS(SELECT 'X' FROM tmp_LimitMobile WITH(NOLOCK) WHERE Mobile = @Mobile)
			RETURN -5
	END
	ELSE
	BEGIN
		IF EXISTS(SELECT 'X' FROM Person_Black WITH(NOLOCK) WHERE Email = @Email)
			RETURN -5
	END

    IF CHARINDEX(', ', @IP) > 0
        SET @IP = RIGHT(@IP, LEN(@IP) - CHARINDEX(', ', @IP))

    DECLARE @VerifyCount SMALLINT
    SELECT @VerifyCount = COUNT(1) FROM paVerifyLog WITH(NOLOCK)
    WHERE [IP] = @IP
    AND AddDate > CONVERT(VARCHAR(10), GETDATE(), 120)

    IF @VerifyCount >= 10 AND @IP <> '60.215.144.163'  --一天同一IP验证超过10次
        RETURN -2

    SELECT @VerifyCount = COUNT(1) FROM paVerifyLog WITH(NOLOCK)
    WHERE (Mobile = @Mobile OR Email = @Email)
    AND AddDate > CONVERT(VARCHAR(10), GETDATE(), 120)

    IF @VerifyCount >= 5  --一天同一手机号或邮箱验证超过5次
        RETURN -3

    SELECT @VerifyCount = COUNT(1) FROM paVerifyLog WITH(NOLOCK)
    WHERE (Mobile = @Mobile OR Email = @Email)
    AND AddDate > DATEADD(MINUTE, -5, GETDATE())

    IF @VerifyCount >= 3  --5分钟内同一手机号或邮箱超过3次
        RETURN -4

	IF EXISTS(SELECT TOP 1 'X' FROM paMain WITH(NOLOCK) WHERE Username = @Email AND EmailVerifyDate IS NOT NULL)
		RETURN -1

    DECLARE @VerifyCode VARCHAR(6)
    SELECT @VerifyCode = RAND() * 899999 + 100000
    INSERT INTO paVerifyLog(paMainID, Email, Mobile, VerifyCode, VerifyDate, AddDate, [IP])
    VALUES(@paMainID, @Email, @Mobile, @VerifyCode, NULL, GETDATE(), @IP)

    RETURN @VerifyCode
END
SET NOCOUNT OFF
GO

/****** Object:  StoredProcedure [dbo].[v2018_pcPaVerifyLogUpdate]    Script Date: 2018/12/13 19:13:48 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--####################################################
--添加人：Lucifer
--添加时间：2018-6-27
--描述：验证个人认证码，并做相应操作
--CerType 1 邮箱认证 UPDATE paMain
--		  2 手机号认证 UPDATE paMain
--        3 手机号登陆
--        4 手机号注册
--返回值 -1  认证失败
--       >=0 返回paMainId
--####################################################
CREATE PROCEDURE [dbo].[v2018_pcPaVerifyLogUpdate] 
(
	@Mobile VARCHAR(11),
	@Email VARCHAR(50),
	@CerCode VARCHAR(6),
	@CerType TINYINT
)
AS
SET NOCOUNT ON
BEGIN
	SET @Mobile = dbo.v2018_SetVarcharNull(@Mobile)
	SET @Email = dbo.v2018_SetVarcharNull(@Email)

	DECLARE @paMainID INT
	DECLARE @paVerifyLogID INT

	SELECT TOP 1 @paMainID = paMainID, @paVerifyLogID = ID
	FROM paVerifyLog WITH(NOLOCK)
	WHERE (Mobile = @Mobile
        OR Email = @Email)
		AND VerifyCode = @CerCode
		AND VerifyDate IS NULL
        AND AddDate > DATEADD(HOUR, -1, GETDATE())
	ORDER BY ID DESC

	IF @paVerifyLogID IS NULL --验证码错误
	BEGIN
		RETURN -1
	END

	UPDATE paVerifyLog SET
		VerifyDate = GETDATE()
	WHERE ID = @paVerifyLogID

	IF @CerType = 1 AND @Email IS NOT NULL --邮箱认证
	BEGIN
		UPDATE paMain SET EmailVerifyDate = GETDATE() WHERE ID = @paMainID
	END
	ELSE IF @CerType = 2 AND @Mobile IS NOT NULL --手机号认证
	BEGIN
		UPDATE paMain SET MobileVerifyDate = NULL WHERE Mobile = @Mobile
		UPDATE paMain SET
			Mobile = @Mobile
		WHERE ID = @paMainID

		UPDATE paMain SET
			MobileVerifyDate = GETDATE()
		WHERE ID = @paMainID
	END
	RETURN @paMainID
END
SET NOCOUNT OFF
GO

/****** Object:  StoredProcedure [dbo].[v2018_ProcCaCvViewCntLogInsert]    Script Date: 2018/12/13 19:13:48 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--半小时检查一次，企业浏览下载的简历的数量
--如超过限定数量则禁止登录短信，rtx通知
--harry 2018-8-10
CREATE PROCEDURE [dbo].[v2018_ProcCaCvViewCntLogInsert] 
AS
BEGIN
	DECLARE @maxViewcnt INT 
	SET @maxViewcnt = 100
	CREATE TABLE #t
	(
		Id INT IDENTITY(1,1),
		cpMainId INT,
		caMainId INT,
		cvViewCnt INT,---浏览总数量
		downLoadCvViewCnt INT,---浏览下载简历数量
		exjobapplyViewCnt INT---申请的职位浏览量
	)
	--查询半小时内浏览简历的用户数据
	INSERT INTO #t(caMainId)
	SELECT DISTINCT caMainId
	FROM cacvviewlog WITH(NOLOCK)
	WHERE DATEDIFF(MINUTE ,adddate,GETDATE())<31 
        AND caMainId NOT IN(select id from camain WITH(NOLOCK) WHERE cpMainId=7269599)
	--更新企业信息
	UPDATE #t
	SET cpMainId=(SELECT cpMainId FROM caMain  WITH(NOLOCK) WHERE id=#t.caMainID) 
	--计算查看简历数量
	DECLARE @id INT, @cpMainId INT,@caMainId INT
	SET @id=0
	WHILE EXISTS(SELECT 'x' FROM #t WHERE id>@id)
	BEGIN
		SELECT TOP 1 @id = id, @cpMainId= cpMainId, @caMainId = camainId FROM #t WHERE id>@id ORDER by id 
		print @caMainId
		--计算浏览量
		UPDATE #t SET cvViewCnt=(
			SELECT COUNT(1) FROM cacvviewlog  WITH(NOLOCK)
			WHERE camainId= @caMainId 
			AND DATEDIFF(MINUTE ,adddate,GETDATE())<31
			)
		WHERE caMainId = @caMainId
		--计算浏览下载量
		UPDATE #t SET DownLoadCvViewCnt=(
			SELECT COUNT(1) FROM cacvviewlog  WITH(NOLOCK)
			WHERE camainId= @caMainId
			AND cvmainId IN(select cvMainID FROM caactivelog  WITH(NOLOCK) WHERE cpMainId= @cpMainId)
			AND DATEDIFF(MINUTE,adddate,GETDATE())<31
			)
		WHERE caMainId = @caMainId
		--计算查看应聘的简历数量
		UPDATE #t SET exjobapplyViewCnt=(
			SELECT COUNT(1) FROM cacvviewlog  WITH(NOLOCK) 
			WHERE camainId= @caMainId
			AND cvmainId IN(select cvMainID FROM exjobapply WITH(NOLOCK) WHERE jobId IN(select id FROM job WHERE cpMainID= @cpMainId))
			AND DATEDIFF(MINUTE,adddate,GETDATE())<31
			)
		WHERE caMainId = @caMainId

	END
	--处理查看超出数量的用户,限制用户登录
	SELECT * INTO #t0 FROM #t WHERE (ISNULL(downLoadCvViewCnt,0)+ISNULL(exjobapplyViewCnt,0))> @maxViewcnt
	
	INSERT INTO caCvviewCntLog(camainId, cpMainId, cvViewCnt, downLoadCvViewCnt,exjobapplyViewCnt, adddate)
	SELECT camainId, cpMainId, cvViewCnt, downLoadCvViewCnt,exjobapplyViewCnt, GETDATE()
	FROM #t0
	
	--限制登录，同时发短信，rtx
	SELECT @id=0,@cpMainId=0,@caMainId =0
	WHILE EXISTS(SELECT 'x' FROM #t0 WHERE id>@id)
	BEGIN
		SELECT TOP 1 @id = id, @cpMainId= cpMainId, @caMainId = camainId FROM #t0 WHERE id>@id ORDER by id 
		
		EXEC bpCpMainByIsLimitLoginUpdate @cpMainId, 9, 1, '短时间内浏览大量简历限制登录'
		INSERT INTO rtxnotifylog
		SELECT ISNULL(ConsultantID,0),'短时间内浏览大量简历限制登录通知',Name+'('+LTRIM(STR(ID))+')企业短时间内浏览大量简历，已限制登录！http://sysback.51rc.com/newoa/company/cp/cpMainInfo?id=' + LTRIM(STR(ID)) + '&code=' + LTRIM(STR(DATEPART(HOUR, RegDate) * 100 + DATEPART(MINUTE, RegDate))),1,0,0,null,getdate()
		FROM cpMain WITH(NOLOCK)
		WHERE ID =@cpMainId
	END
	
	DROP TABLE #t
	DROP TABLE #t0
END



GO

/****** Object:  StoredProcedure [dbo].[v2018_procColdCustomerInsert]    Script Date: 2018/12/13 19:13:48 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--采集的冷客户分配
--alen
--2018-10-09
CREATE PROCEDURE [dbo].[v2018_procColdCustomerInsert]
(
  @ManagerUserId INT,
  @Allocater INT,
  @SourceType INT,
  @AllocateNumber INT,
  @isSpread INT		
)
AS
SET NOCOUNT ON
BEGIN
	DECLARE @Id INT
	DECLARE @AllocateId INT
	DECLARE @cpName VARCHAR(200)
	DECLARE @ProvinceId INT
	SET @ProvinceId=32
	DECLARE @dtLastLoginDate DATETIME 
	DECLARE @dtLastContactDate DATETIME
	SET @dtLastLoginDate=dateAdd(month,-6,getdate())
	SET @dtLastContactDate=dateAdd(month,-6,getdate())
	IF(@ProvinceId=32)
		SET @dtLastContactDate=dateAdd(month,-3,getdate())
	--分配前，更新已被注册的信息
	CREATE TABLE #t(
		Id INT ,
		[state] INT,
		SourceType  INT, 
		RegType INT,
		CompanyName  VARCHAR(200),
		LinkMan varchar(50),
		Phone varchar(50),
		Tel varchar(50),
		Email varchar(50),
		SourceLink varchar(500),
		[Address] varchar(200),
		QQ char(15),
		IsNameRepeat BIT,
		IsEmailRepeat BIT,
		IsMobileRepeat BIT,
		IsAgree BIT,
		IsValid BIT,
		CheckDate DATETIME,
		AddDate DATETIME
	)

	CREATE TABLE #d(
		cpmainid INT,
		cppersonalaccountid INT,
		cpCertificationid INT
	)
	INSERT #t(id,[state],sourceType,companyName,LinkMan,Phone,Tel,Email,SourceLink,[address],qq)
	SELECT id,[state],sourceType,companyName,linkMan,Phone,Tel,Email,SourceLink,[address],qq 
	FROM precoldCustomer
	WHERE [state]=0--未分配 
	AND ISNULL(isSpread,0) = @isSpread 
 
	IF EXISTS(SELECT 'x' FROM #t)
	BEGIN 
		--2018-10-09 ALEN采集规则添加(更改齐鲁人才网采集到公司的实名状态)
		INSERT #d(cpmainid,cppersonalaccountid,cpCertificationid)
		SELECT b.cpMainID,a.id,b.id
		FROM cppersonalaccount a,cpCertification b
		WHERE a.cpCertificationID=b.id
		AND b.cpMainID IN(
			SELECT SourceLink 
			FROM #t 
			WHERE SourceType=8
		)
		AND a.Name='XXX'

		DECLARE @cpmainid varchar(20),@cppersonalaccountid varchar(20),@cpCertificationid varchar(20)
		DECLARE cursor_name CURSOR FOR --定义游标
			SELECT cpmainid,cppersonalaccountid,cpCertificationid FROM #d
		OPEN cursor_name --打开游标
		FETCH NEXT FROM cursor_name INTO  @cpmainid,@cppersonalaccountid,@cpCertificationid  --抓取下一行游标数据
		WHILE @@FETCH_STATUS = 0
		BEGIN
			DELETE FROM cppersonalaccount WHERE id =@cppersonalaccountid
			UPDATE cpCertification  SET CerStatus=null,CerDate=null 
			WHERE id =@cpCertificationid
			UPDATE cpmain SET MemberType=1 
			WHERE id =@cpmainid
			FETCH NEXT FROM cursor_name INTO @cpmainid,@cppersonalaccountid,@cpCertificationid
		END
		CLOSE cursor_name --关闭游标
		DEALLOCATE cursor_name --释放游标	

		--删除在coldcustomer表中的数据 2018-10-09 ALEN采集规则添加
		UPDATE #t SET [state]=2 
		WHERE  EXISTS(SELECT 'x' FROM Maindb..coldcustomer 
			WHERE companyName=#t.CompanyName AND ProvinceID=@ProvinceId AND AddMan IS NOT NULL) 
		 AND [state]=0
		
		IF @isSpread = 0 --冷客户部门的规则
		BEGIN
			--有顾问的（上次联系时间，和登录时间不为空的）
			--3（6）个月内未联系，删除3（6）个月内联系过的
			UPDATE #t SET [state]=2
			WHERE EXISTS
			(
				SELECT 'x' FROM cpMain  
				WHERE NAME=#t.CompanyName 
				AND dcProvinceID = @ProvinceId
				AND ISNULL(ConsultantID, -1) != -1
				AND id =(
					SELECT TOP 1 companyID 
					FROM MainDB..contact
					WHERE companyID = CpMain.ID 
					AND addDate>@dtLastContactDate 
					ORDER BY addDate DESC
				)
			)
			 AND [state]=0
		
			--6个月未登录，删除6个月内登录过的
			UPDATE #t SET [state]=2
			WHERE EXISTS(
				SELECT 'x'  FROM  cpMain  
				WHERE  NAME=#t.CompanyName 
				AND dcProvinceID=@ProvinceId
				AND  ISNULL(ConsultantID,-1)!=-1
				AND   LastLoginDate>@dtLastLoginDate 
			) 
			AND [state]=0

			--无顾问 
			--无执照且一个月未登录，删除一个月内登录的
			UPDATE #t SET [state]=2
			WHERE EXISTS(
				SELECT 'x' FROM cpMain 
				WHERE  NAME=#t.CompanyName 
				AND dcProvinceID=@ProvinceId
				AND	ISNULL(ConsultantID,-1)=-1
				AND HasLicence=0
				AND LastLoginDate>DateAdd(month,-1,getdate())
			) 
			AND [state]=0
		
			--有执照且三个月未登录，删除3个月内登录的
			UPDATE #t SET [state]=2
			WHERE EXISTS
			(
				SELECT 'x'  FROM  cpMain  
				WHERE  NAME=#t.CompanyName 
				AND dcProvinceID=@ProvinceId
				AND	ISNULL(ConsultantID,-1)=-1
				AND HasLicence=1
				AND LastLoginDate>DateAdd(month,-3,getdate())
			) 
			AND [state]=0
		END
		ELSE
		BEGIN
		--推广的规则
			--有顾问的，已认证的
			UPDATE #t SET [state]=2
			WHERE EXISTS
			(
				SELECT 'x' FROM cpMain  
				WHERE  NAME=#t.CompanyName 
				AND dcProvinceID=@ProvinceId
				AND	(ISNULL(ConsultantID,0)!=0 OR memberType>1)
			) 
			AND [state]=0
		END
	END
	--更新新结束，开始分配
	UPDATE precoldCustomer 
	SET [state]=2
	WHERE id in(select id FROM #t where [state]=2)
	
	TRUNCATE TABLE #t
	 
	INSERT INTO #t(id,sourceType,companyName,LinkMan,Phone,Tel,Email,SourceLink,[address],qq,IsAgree,IsValid,CheckDate,AddDate)
	SELECT TOP (@AllocateNumber) id,sourceType,companyName,
		REPLACE(linkMan,'_',''),
		REPLACE(Phone,'_',''),
		REPLACE(Tel,'_',''),
		REPLACE(Email,'_',''),
		REPLACE(SourceLink,'_',''),
		REPLACE([address],'_',''),
		REPLACE(qq,'_',''),1,1,GETDATE(),GETDATE() 
	FROM precoldCustomer 
	WHERE [state]=0
	AND SourceType=@SourceType
	AND ISNULL(isSpread,0) = @isSpread 
	--判断用户名，手机，邮箱等是否重复IsNameRepeat BIT,IsEmailRepeat BIT, IsMobileRepeat BIT,
	UPDATE #t
	SET IsNameRepeat=(CASE WHEN EXISTS(select 'x' from MainDB..CpMain where name =#t.CompanyName)
		THEN 1 
		ELSE 0 END),
		IsEmailRepeat=(
			CASE WHEN Email!=''
			THEN
				(CASE WHEN EXISTS(select 'x' from MainDB..CaMain a,MainDB..CpMain b where a.email =#t.Email and a.CpMainID=b.ID)
				THEN 1 
				ELSE 0 END)
			ELSE 0 END),
		IsMobileRepeat=(CASE WHEN #t.Phone!='' OR #t.Tel !=''
			THEN (CASE 
				WHEN #t.Phone!='' AND #t.Tel!='' AND EXISTS(select 'x' from MainDB..CaMain a,MainDB..cpmain b  
					where (a.telephone like #t.Tel+ '%' or a.mobile=#t.Phone)
					and a.CpMainID=b.ID)
				THEN 1
				WHEN #t.Phone!='' AND #t.Tel ='' AND EXISTS(select 'x' from MainDB..CaMain a,MainDB..cpmain b  
					where a.mobile=#t.Phone and a.CpMainID=b.ID)
				THEN 1
				WHEN #t.Phone ='' AND #t.Tel!='' AND EXISTS(select a.cpmainid,b.ConsultantID,b.LastLoginDate,b.HasLicence  
					 from MainDB..CaMain a,MainDB..cpmain b  
					where a.telephone like #t.Tel+'%' and a.CpMainID=b.ID)
				THEN 1
				ELSE 0
				END)
			ELSE 0
			END)

	--更新regtype 
	UPDATE #t SET regType=1 --无顾问的
	
	--有顾问的 regType=4,HasLicence=1 regtype=3 haslicence=0 regtype=2
	
	UPDATE #t 
	SET regType=4
	WHERE EXISTS(SELECT 'x'  FROM  cpMain  
		WHERE  NAME=#t.CompanyName 
		AND dcProvinceID=@ProvinceId
		AND  ISNULL(ConsultantID,-1)!=-1) 

	UPDATE #t 
	SET regType=3
	WHERE EXISTS(
		SELECT 'x'  FROM  cpMain  
		WHERE  NAME=#t.CompanyName 
		AND dcProvinceID=@ProvinceId
		AND HasLicence=1
		AND  ISNULL(ConsultantID,-1)!=-1) 
		
	UPDATE #t 
	SET regType=3
	WHERE EXISTS(
		SELECT 'x'  FROM  cpMain  
		WHERE  NAME=#t.CompanyName 
		AND dcProvinceID=@ProvinceId
		AND HasLicence=0
		AND  ISNULL(ConsultantID,-1)!=-1) 
			
	--#t
	IF EXISTS(SELECT 'x' FROM #t)
	BEGIN
		INSERT INTO ColdCustomerAllocateLog(ManagerUserId,SourceType,Allocater,AllocateNumber,Adddate)
		SELECT @ManagerUserId,@SourceType,@Allocater,(SELECT COUNT(*) FROM #t),GETDATE()
		
		SELECT @AllocateId=(SELECT @@IDENTITY) --赋值

		--2018-10-09 ALEN采集规则添加
		DELETE FROM coldCustomer WHERE companyName in(SELECT CompanyName FROM #t) AND ProvinceID=@ProvinceId AND AddMan IS NULL
		--不存在零库插入冷客户表
		INSERT INTO coldCustomer(CompanyName, ProvinceId, Email, Phone, SourceLink, LinkMan, [Address], qq, AllocateLogID, AddWorkUserID,AddMan,IsNameRepeat,IsEmailRepeat,IsMobilerepeat,IsAgree,IsValid,CheckDate,addDate,regType)
		SELECT CompanyName,32,Email,Phone,SourceLink,LinkMan,[Address],qq,@AllocateId,(select TOP 1 id from oadb..workuser where manageruserid=@ManagerUserId and loginstatus=1 AND JobStatus<3 ),@ManagerUserId,IsNameRepeat, IsEmailRepeat,IsMobileRepeat,IsAgree,IsValid,CheckDate ,AddDate,regType
		FROM #t
		
		UPDATE precoldCustomer SET [state]=1,ColdCustomerAllocateLogID=@AllocateId  WHERE ID IN(SELECT id FROM #t)
		--释放顾问
		DECLARE @CompanyName varchar(100)
		DECLARE cursor_name CURSOR FOR --定义游标
			SELECT CompanyName FROM #t
		OPEN cursor_name --打开游标
		FETCH NEXT FROM cursor_name INTO  @CompanyName  --抓取下一行游标数据
		WHILE @@FETCH_STATUS = 0
		BEGIN
			UPDATE Maindb..cpMain SET ConsultantID = NULL, ConsultantDate = NULL WHERE [Name] =@CompanyName AND dcProvinceID=32
			FETCH NEXT FROM cursor_name INTO @CompanyName
		END
		CLOSE cursor_name --关闭游标
		DEALLOCATE cursor_name --释放游标

		--UPDATE Maindb..cpMain SET ConsultantID = NULL, ConsultantDate = NULL WHERE [Name] IN(SELECT CompanyName FROM #t) AND dcProvinceID=32
		--rtx 通知 操作人和分配人
        INSERT RtxNotifyLog SELECT @ManagerUserId, Convert(VARCHAR,@Allocater)+'分配给您'+Convert(VARCHAR,(SELECT COUNT(*) FROM #t))+'个新的冷客户', Convert(VARCHAR,@Allocater)+'分配给您'+Convert(VARCHAR,(SELECT COUNT(*) FROM #t))+'个新的冷客户，请及时处理', 0, 0, 0, Null, GETDATE()
		INSERT RtxNotifyLog SELECT @Allocater,  '分配冷客户成功通知', '成功分配'+Convert(VARCHAR,(SELECT COUNT(*) FROM #t))+'个新的冷客户给'+Convert(VARCHAR,@ManagerUserId), 0, 0, 0, Null, GETDATE()
	END
	
END
SET NOCOUNT OFF

GO

/****** Object:  StoredProcedure [dbo].[v2018_procCvVoiceJobTypeInsert]    Script Date: 2018/12/13 19:13:49 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--################################################################
--创建人：Allen
--创建时间：2018-7-23
--描述：职位类别关键词添加职位类别关联（后台审核用）
--################################################################
CREATE PROCEDURE [dbo].[v2018_procCvVoiceJobTypeInsert]
(
	@cvVoiceID INT, 
	@JobType VARCHAR(100)
)
AS
SET NOCOUNT ON
BEGIN
	IF @cvVoiceID IS NULL
		RETURN 0
	IF @JobType IS NULL
		RETURN 0

	IF NOT EXISTS(SELECT 'x' FROM cvVoiceText WITH(NOLOCK) WHERE ID = @cvVoiceID)
		RETURN 0

 
	DELETE FROM cvVoiceJobType WHERE cvVoiceID = @cvVoiceID
	INSERT cvVoiceJobType(cvVoiceID, dcJobTypeID)
	SELECT @cvVoiceID, a FROM dbo.FnSplit(@JobType, ' ')

	UPDATE CvVoiceText SET MatchDate = GETDATE() WHERE ID = @cvVoiceID
END
GO

/****** Object:  StoredProcedure [dbo].[v2018_procCvVoiceTextSelect]    Script Date: 2018/12/13 19:13:49 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--##################################################################
--添加人：Allen
--添加时间：2018-7-20
--描述：智能匹配职位类别，如果没有，添加到数据库由人工添加
--##################################################################
CREATE PROCEDURE [dbo].[v2018_procCvVoiceTextSelect]
(
	@voiceText NVARCHAR(100)
)
AS
SET NOCOUNT ON
BEGIN
	CREATE TABLE #T(
		dcJobTypeID INT,
		[Description] NVARCHAR(20),
		ParentID NVARCHAR(20)
	)
	IF EXISTS(SELECT 'x' FROM CvVoiceText WITH(NOLOCK) WHERE voiceText = @voiceText AND MatchDate IS NOT NULL)
	BEGIN
		INSERT INTO #T
		SELECT b.dcJobTypeID, c.[Description],''
		FROM cvVoiceText a WITH(NOLOCK),cvVoiceJobType b WITH(NOLOCK),dcJobType c WITH(NOLOCK) 
		WHERE a.ID=b.cvVoiceID AND b.dcJobTypeID=c.ID AND a.MatchDate IS NOT NULL AND a.voiceText=@voiceText
	END
	ELSE 
	BEGIN
		--优先取完全匹配，包括/多个的
		INSERT INTO #T
		SELECT id,[Description],ParentID
		FROM dcJobType WITH(NOLOCK)
		WHERE [Description] LIKE '%/' + @voiceText OR [Description] LIKE @voiceText + '/%' OR  [Description] = @voiceText

		DELETE FROM #T WHERE ParentID IN (SELECT dcJobTypeID FROM #T)
		--取模糊匹配大类
		IF NOT EXISTS(SELECT TOP 1 'X' FROM #T)
		BEGIN
			INSERT INTO #T
			SELECT ID, [Description],''
			FROM dcJobType WITH(NOLOCK)
			WHERE [Description] LIKE '%' + @voiceText + '%' AND ParentID IS NULL
		END

		--取模糊匹配小类
		IF NOT EXISTS(SELECT TOP 1 'X' FROM #T)
		BEGIN
			INSERT INTO #T
			SELECT ID, [Description],''
			FROM dcJobType WITH(NOLOCK)
			WHERE [Description] LIKE '%' + @voiceText + '%' AND ParentID IS NOT NULL
		END

		--如果都匹配不到，插入CvVoiceText，等待审核补充
		IF NOT EXISTS(SELECT TOP 1 'X' FROM #T)
		BEGIN
			IF NOT EXISTS(SELECT 'x' FROM CvVoiceText WITH(NOLOCK) WHERE voiceText = @voiceText)
			BEGIN
				INSERT INTO CvVoiceText(voiceText) VALUES(@voiceText)
			END
		END
	END
	SELECT TOP 5 * FROM #T
	DROP TABLE #T
END
SET NOCOUNT OFF

GO

/****** Object:  StoredProcedure [dbo].[v2018_ProcdcIndustryByKeyWordSelect]    Script Date: 2018/12/13 19:13:49 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2018.09.30
--创建人：Alen
--说明：根据关键字获取行业类别
--#####################################################
CREATE PROCEDURE [dbo].[v2018_ProcdcIndustryByKeyWordSelect]
(
	@KeyWord VARCHAR(100),
	@IsEnglish TINYINT
)
AS
BEGIN
	IF @IsEnglish = 1
	BEGIN
		SELECT * 
		FROM dcIndustry WITH(NOLOCK) 
		WHERE dbo.GetPyFirst(Description) LIKE '%'+@KeyWord+'%'
	END
	ELSE 
	BEGIN
		SELECT * 
		FROM dcIndustry WITH(NOLOCK) 
		WHERE Description LIKE '%'+@KeyWord+'%'
	END
END
GO

/****** Object:  StoredProcedure [dbo].[v2018_procInfoDateReportUpdate]    Script Date: 2018/12/13 19:13:50 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


--#####################################################
--添加时间 20180612
--添加人   Lucifer
--用途     Info_DateReport数据更新
--#####################################################
CREATE PROCEDURE [dbo].[v2018_procInfoDateReportUpdate] 
(
	@Province_Id SMALLINT,
	@InfoManager_Id SMALLINT,
	@IP VARCHAR(15),
	@Referer VARCHAR(100)
)
AS
SET NOCOUNT ON
BEGIN
	IF NOT EXISTS(
		SELECT TOP 1 'X'
		FROM Info_DateReport WITH(NOLOCK)
		WHERE Countdate = CONVERT(VARCHAR(8), GETDATE(), 112)
		AND Province_Id = @Province_Id
		AND InfoManager_Id = @InfoManager_Id
	)
	BEGIN
		INSERT INTO Info_DateReport (Province_Id, InfoManager_Id, CountDate) 
		VALUES(@Province_Id, @InfoManager_Id, CONVERT(VARCHAR(8), GETDATE(), 112))
	END

	IF NOT EXISTS(
		SELECT TOP 1 'X'
		FROM InfoLog WITH(NOLOCK)
		WHERE AddDate > GETDATE()-1
		AND InfoManager_Id = @InfoManager_Id
		AND [IP] = @IP
		AND [IP] NOT LIKE '60.215.144%'
	)
	BEGIN
		UPDATE Info_DateReport SET Homepage = Homepage + 1  
		WHERE CountDate = CONVERT(VARCHAR(8), GETDATE(), 112)
		AND Province_Id = @Province_Id
		AND InfoManager_Id = @InfoManager_Id

		INSERT INTO InfoLog(InfoManager_Id, [IP], Referer) VALUES(@InfoManager_Id, @IP, @Referer)
		RETURN 1
	END
	ELSE
	BEGIN
		RETURN 0
	END
END
SET NOCOUNT OFF

GO

/****** Object:  StoredProcedure [dbo].[v2018_procParefererSelectByPcBaiDu]    Script Date: 2018/12/13 19:13:50 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--分类统计个人注册来源数量(前台百度直聘单纯统计)
--alen
--2018-10-16
CREATE PROCEDURE [dbo].[v2018_procParefererSelectByPcBaiDu]
(
	@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 = ' 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), addDate, 112 ) AS [date]
		FROM maindb..pamain 
		WHERE '+@str+' CONVERT(varchar(8), adddate, 112) >='''+ @begin+''' AND CONVERT(varchar(8), adddate, 112)<='''+@end+ 
		''' AND RegisterFrom=1 AND RegisterType=7 GROUP BY RegisterFrom,RegisterType,CONVERT(varchar(8), addDate,112) 
		 ORDER BY [date],registerfrom,registertype'
	END
	ELSE
	BEGIN--月 
		SET @sql='SELECT RegisterFrom,RegisterType,count(*) AS number,CONVERT(varchar(6), addDate, 112) AS [date]
		FROM maindb..pamain 
		WHERE '+@str+' CONVERT(varchar(6), adddate, 112)>='''+ LEFT(@begin,6)+''' AND CONVERT(varchar(6), adddate, 112)<='''+ LEFT(@end,6)+''' AND RegisterFrom=1 AND RegisterType=7 GROUP BY RegisterFrom,RegisterType,CONVERT(varchar(6), addDate, 112 )
		ORDER BY [date],registerfrom,registertype'
	END
	EXEC (@sql)
END 
GO

/****** Object:  StoredProcedure [dbo].[v2018_procSmsMessageLogInsert]    Script Date: 2018/12/13 19:13:50 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2018.6.28
--创建人：John
--说明：短信通知日志新增
--@SendStatus = 1 实时发送成功，插入一条已完成的记录
--@SendStatus = 0 实时发送失败，插入一条待发送的记录
--#####################################################
CREATE PROCEDURE [dbo].[v2018_procSmsMessageLogInsert]
(
	@SendMan SMALLINT,
	@ManagerUserId SMALLINT,
	@paMainId INT,
	@caMainId INT,
	@Mobile VARCHAR(20),
	@Msg NVARCHAR(210),
	@MsgType TINYINT,
	@PortNo INT,
	@IsCat BIT,
	@SendStatus INT
)
AS
SET NOCOUNT ON
BEGIN TRY
	IF @SendStatus = 0
	BEGIN
		IF @MsgType IN(102, 105) AND @paMainId > 0
		BEGIN
			IF EXISTS(SELECT 'x' FROM wxFans WITH(NOLOCK) WHERE paMainId = @paMainId)
				RETURN 0
		END
		IF EXISTS(SELECT 'x' FROM SmsMessageLog WITH(NOLOCK) WHERE Mobile = @Mobile AND Msg = @Msg AND AddDate > GETDATE() - 0.3)
			RETURN 0
 
		INSERT INTO SmsMessageLog (SendMan, ManagerUserId, paMainId, caMainId, Mobile, Msg, MsgType, IsCat)
		SELECT @SendMan, @ManagerUserId, @paMainId, @caMainId, @Mobile, @Msg, @MsgType, @IsCat
	END
	ELSE
	BEGIN
		INSERT INTO SmsMessageLog (SendMan, ManagerUserId, paMainId, caMainId, Mobile, Msg, MsgType, IsCat, PortNo, SendDate, SendStatus)
		SELECT @SendMan, @ManagerUserId, @paMainId, @caMainId, @Mobile, @Msg, @MsgType, @IsCat, @PortNo, GETDATE(), 1
	END
	RETURN 1
END TRY
BEGIN CATCH
	RETURN 0
END CATCH
SET NOCOUNT OFF
GO

/****** Object:  StoredProcedure [dbo].[v2018_procUrlClickLogInsert]    Script Date: 2018/12/13 19:13:50 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--添加时间 20180612
--添加人   Lucifer
--用途     UrlClickLog添加
--#####################################################
CREATE PROCEDURE [dbo].[v2018_procUrlClickLogInsert] 
	@ID SMALLINT,
	@IP VARCHAR(15)
AS
SET NOCOUNT ON
BEGIN
	IF (
		(SELECT COUNT(1) FROM Url_Click_Log WITH(NOLOCK) WHERE [IP] = @IP AND Url_Id = @ID AND AddDate > GETDATE()-1) = 0
		OR
		(SELECT TOP 1 Ip_Repeat FROM [Url] WITH(NOLOCK) WHERE ID = @ID) = 2
	)
	BEGIN
		INSERT INTO Url_Click_Log (Url_Id,[IP]) VALUES(@ID, @IP)
		UPDATE [Url] SET AllClick = AllClick + 1,TodayClick = TodayClick + 1 WHERE ID = @ID
	END
END
SET NOCOUNT OFF

GO

/****** Object:  StoredProcedure [dbo].[v2018_procWxMessageReceiveInsert]    Script Date: 2018/12/13 19:13:51 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2018-7-11
--创建人：Lucifer
--说明：微信操作日志
--LogType 1、关注 2、取消关注 3、发送文本 4、发送地理位置 5、点击菜单
--        6、点击链接 7、绑定个人账号 8、取消绑定个人账号 10、发送语音
--        11、发送视频 12、发送图片 13、扫描二维码 14、绑定企业账号 15、取消绑定企业账号
--#####################################################
CREATE PROCEDURE [dbo].[v2018_procWxMessageReceiveInsert]
(
    @OpenID VARCHAR(100),
    @LogType INT,
    @ProvinceID INT,
    @Message VARCHAR(200),
    @paMainID INT
)
AS
SET NOCOUNT ON
BEGIN
    DECLARE @WxServiceNoID INT
    --根据省份得到服务号id
    SELECT TOP 1 @WxServiceNoID = ID FROM WxServiceNO WHERE ProvinceID = @ProvinceID

    DECLARE @WxFansID INT
    SELECT TOP 1 @WxFansID = ID FROM WxFans WHERE OpenID = @OpenID
    IF @WxFansID IS NULL
    BEGIN
        --插入粉丝表
        INSERT INTO WxFans(OpenID, AttentionDate, [Status], WxServiceNoID, paMainID)
        VALUES (@OpenID, GETDATE(), 1, @WxServiceNoID, NULL)
        SELECT @WxFansID = @@IDENTITY
    END
    
    DECLARE @Content VARCHAR(50)
    IF @LogType = 1
    BEGIN
        SET @Content = '关注'
        --更新粉丝表
        UPDATE WxFans SET
			[Status] = 1,
			AttentionDate = GETDATE(),
			WxServiceNoID = @WxServiceNoID 
        WHERE ID = @WxFansID
    END
    ELSE IF @LogType = 2
    BEGIN
        SET @Content = '取消关注'
        --更新粉丝表
        UPDATE WxFans SET
			[Status] = 0,
			AttentionCancelDate = GETDATE()
		WHERE ID = @WxFansID
        --删除 paLoginContact 暂时不删除，因为优先判断取消关注了，不会到paLoginContact查询
        --DELETE FROM paLoginContact WHERE OpenID = @OpenID AND ContactType = 4
		--DELETE FROM paLoginContact WHERE OpenID = @OpenID AND ContactType = 101
    END
    ELSE IF @LogType = 3
    BEGIN
        SET @Content = '发送文本'
        --更新粉丝表最后发送消息
        UPDATE WxFans SET LastSendMessage = @Message WHERE ID = @WxFansID
    END
    ELSE IF @LogType = 4
    BEGIN
        SET @Content = '发送地理位置'
    END
    ELSE IF @LogType = 5
    BEGIN
        SET @Content = '点击菜单'
    END
    ELSE IF @LogType = 6
    BEGIN
        SET @Content = '点击链接'
    END
    ELSE IF @LogType = 7
    BEGIN
        SET @Content = '绑定个人账号'
        --更新粉丝表
        UPDATE WxFans SET
			[Status] = 2,
			paMainID = @paMainID
		WHERE ID = @WxFansID
    END
    ELSE IF @LogType = 8
    BEGIN
        SET @Content = '取消绑定个人账号'
        --更新粉丝表
        UPDATE WxFans SET
			[Status] = 1
		WHERE ID = @WxFansID
        --删除paLoginContact
        DELETE FROM paLoginContact WHERE OpenID = @OpenID AND ContactType = 4
		--关闭你的菜
		--UPDATE paMain SET IsUseYourFood = 0 WHERE ID = @paMainID
    END
    ELSE IF @LogType = 10 
    BEGIN
        SET @Content = '发送语音'
    END
    ELSE IF @LogType = 11 
    BEGIN
        SET @Content = '发送视频'
    END
    ELSE IF @LogType = 12 
    BEGIN
        SET @Content = '发送图片'
    END
    ELSE IF @LogType = 13 
    BEGIN
        SET @Content = '扫描二维码'
    END
    ELSE IF @LogType = 14
    BEGIN
        SET @Content = '绑定企业账号'
        --更新粉丝表
        UPDATE WxFans SET
			caMainID = @paMainID,
			caBindCancelDate = NULL
		WHERE ID = @WxFansID
        --插入积分200        
		INSERT INTO cpPoint(cpMainID, ChangeID, Point, LastModifyDate)
		SELECT TOP 1 cpMainID, 21, 200, GETDATE() FROM caMain WHERE ID = @paMainID
    END
    ELSE IF @LogType = 15 
    BEGIN
        SET @Content = '取消绑定企业账号'
        --更新粉丝表
        UPDATE WxFans SET
			caBindCancelDate = GETDATE()
		WHERE ID = @WxFansID
        --删除paLoginContact
        DELETE FROM paLoginContact WHERE OpenID = @OpenID AND ContactType = 101
		--扣除积分200
		INSERT INTO cpPoint(cpMainID, ChangeID, Point, LastModifyDate)
		SELECT TOP 1 cpMainID, 22, -200, GETDATE() FROM caMain WHERE ID = @paMainID
    END
    --插入日志表
	IF dbo.v2018_SetVarcharNull(@Message) IS NULL
	BEGIN
        INSERT INTO WxMessageReceive VALUES(@WxFansID, GETDATE(), @Content, @LogType)
	END
	ELSE
	BEGIN
		INSERT INTO WxMessageReceive VALUES(@WxFansID, GETDATE(), @Message, @LogType)
	END
END
SET NOCOUNT OFF
GO

/****** Object:  StoredProcedure [dbo].[v2018_procWxQrImageInsert]    Script Date: 2018/12/13 19:13:51 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--#################################################
--添加人：Lucifer
--添加时间：2018-6-6
--说明：插入一条微信二维码生成记录
--#################################################
CREATE PROCEDURE [dbo].[v2018_procWxQrImageInsert] 
(
	@PageType INT,
	@IP VARCHAR(31),
	@TypeID INT
)
AS
BEGIN
	INSERT INTO WxQrImage(Ticket, PageType, [IP], paMainId)
	SELECT '', @PageType, @Ip, @TypeID
	RETURN SCOPE_IDENTITY()
END
GO

/****** Object:  StoredProcedure [dbo].[v2018_PromotionCerStatistics]    Script Date: 2018/12/13 19:13:51 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--###############################################
--添加人：Alen
--添加时间：2018-10-10
--描述：推广记分牌统计月认证进度和日认证进度
--###############################################
CREATE PROCEDURE [dbo].[v2018_PromotionCerStatistics]
(
@beginDate VARCHAR(8),
@endDate VARCHAR(8)
)
AS
BEGIN 
	CREATE TABLE #t
	(
		workDayCnt INT,
		currentDayCnt INT
	)
	CREATE TABLE #t1
	(
		groupName NVARCHAR(6),
		monthlyTaskCnt INT,
		monthlyCerCnt INT
	)
	CREATE TABLE #t2
	(
		groupName NVARCHAR(6),
		todayTaskCnt INT,
		todayCerCnt INT
	)

	INSERT INTO #t(workDayCnt)
	SELECT COUNT(1) FROM maindb..workdate WITH(NOLOCK) where workDate>@beginDate and workdate<@endDate and Type=1

	UPDATE #t SET currentDayCnt=(
	SELECT COUNT(1) FROM maindb..workdate WITH(NOLOCK) where workDate>@beginDate and workdate<CONVERT (nvarchar(12),GETDATE(),112) and Type=1)

	INSERT INTO #t1(groupName,monthlyTaskCnt)
	SELECT CASE (CASE superior WHEN 201 THEN b.id ELSE superior END) WHEN 302 THEN '二组' ELSE '一组' END,COUNT(1) 
		FROM maindb..manageruser b WITH(NOLOCK),logdb..coldcustomerCerLog c WITH(NOLOCK) 
		WHERE  b.id=c.addMan 
		AND b.deptid=15
		AND c.cerDate<(LEFT(@endDate,4)+'-'+substring(@endDate,5,2)+'-26')
		AND c.cerDate>(LEFT(@beginDate,4)+'-'+substring(@beginDate,5,2)+'-26')
		GROUP BY (CASE superior WHEN 201 THEN b.id ELSE superior END)
		ORDER BY COUNT(1) DESC

	UPDATE #t1 SET monthlyCerCnt=(
		SELECT SUM(a.TaskCount) 
		FROM OADB..MonthlyCerTask a WITH(NOLOCK),maindb..manageruser b WITH(NOLOCK) 
		WHERE a.Manageruserid=b.id 
		AND b.deptid=15 
		AND YearMonth=LEFT(@endDate,6) 
		AND CASE (CASE superior WHEN 201 THEN b.id ELSE superior END) WHEN 302 THEN '二组' ELSE '一组' END=#t1.groupName
	)

	INSERT INTO #t1(groupName,monthlyTaskCnt,monthlyCerCnt)
	SELECT '部门合计',SUM(monthlyTaskCnt),SUM(monthlyCerCnt) 
	FROM #t1

	INSERT INTO #t2(groupName,todayTaskCnt)
	SELECT CASE (CASE superior WHEN 201 THEN b.id ELSE superior END) WHEN 302 THEN '二组' ELSE '一组' END,COUNT(1) 
	FROM maindb..manageruser b WITH(NOLOCK),logdb..coldcustomerCerLog c WITH(NOLOCK) 
	WHERE  b.id=c.addMan 
	AND b.deptid=15
	AND c.cerDate<Datename(year,GetDate())+'-'+Datename(month,GetDate())+'-'+Datename(day,GetDate()+1)
	AND c.cerDate>Datename(year,GetDate())+'-'+Datename(month,GetDate())+'-'+Datename(day,GetDate())
	GROUP BY (CASE superior WHEN 201 THEN b.id ELSE superior END)
	ORDER BY COUNT(1) DESC	
	
	UPDATE #t2 SET todayCerCnt=(
		SELECT CEILING(SUM(a.TaskCount)/30.0) 
		FROM OADB..MonthlyCerTask a WITH(NOLOCK),maindb..manageruser b WITH(NOLOCK) 
		WHERE a.Manageruserid=b.id 
		AND b.deptid=15 
		AND YearMonth=LEFT(@endDate,6)
		AND CASE (CASE superior WHEN 201 THEN b.id ELSE superior END) WHEN 302 THEN '二组' ELSE '一组' END=#t2.groupName
	)
	INSERT INTO #t2(groupName,todayTaskCnt,todayCerCnt)
	SELECT '部门合计',SUM(todayTaskCnt),SUM(todayCerCnt) 
	FROM #t2

	SELECT * FROM #t
	SELECT * FROM #t1
	SELECT * FROM #t2

	DROP TABLE #t
	DROP TABLE #t1
	DROP TABLE #t2
END
GO

/****** Object:  StoredProcedure [dbo].[v2018_tvCerBroadcastSelect]    Script Date: 2018/12/13 19:13:52 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2018.10.11
--创建人：alen
--说明：推广记分牌单位认证成功实时播报
--#####################################################
CREATE PROCEDURE [dbo].[v2018_tvCerBroadcastSelect]
(
	@ColdcustomerCerLogID INT
)
AS
BEGIN
	IF @ColdcustomerCerLogID > 0
	BEGIN
		SELECT TOP 1 a.id,b.name,c.name AS companyName 
		FROM logdb..coldcustomerCerLog a WITH(NOLOCK),manageruser b WITH(NOLOCK),cpMain c WITH(NOLOCK) 
		WHERE a.addman=b.id 
		AND a.cpmainid=c.id 
		AND a.id > @ColdcustomerCerLogID 
		ORDER BY a.ID
	END
	ELSE
	BEGIN
		SELECT TOP 1 a.id,b.name ,'' AS companyName 
		FROM logdb..coldcustomerCerLog a WITH(NOLOCK),manageruser b WITH(NOLOCK),cpMain c WITH(NOLOCK) 
		WHERE a.addman=b.id 
		AND a.cpmainid=c.id 
		ORDER BY a.ID DESC
	END
END
GO

/****** Object:  StoredProcedure [dbo].[v2018_tvCongratulationSelect]    Script Date: 2018/12/13 19:13:52 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--#####################################################
--创建时间：2018.8.20
--创建人：alen
--说明：销售记分牌开通订单实时播报
--#####################################################
CREATE PROCEDURE [dbo].[v2018_tvCongratulationSelect]
(
	@RtxNotifyLogID INT
)
AS
BEGIN
	IF @RtxNotifyLogID > 0
	BEGIN
		SELECT TOP 1 ID,RtxMessage 
		FROM RtxNotifyLog WITH (NOLOCK) 
		WHERE ID > @RtxNotifyLogID 
		AND RtxTitle LIKE '%祝贺%' 
		ORDER BY ID
	END
	ELSE
	BEGIN
		SELECT TOP 1 ID,'' RtxMessage
		FROM RtxNotifyLog WITH (NOLOCK) 
		WHERE RtxTitle LIKE '%祝贺%' 
		ORDER BY ID DESC
	END
END
GO

/****** Object:  StoredProcedure [dbo].[wpCvMainByRefreshDateUpdate]    Script Date: 2018/12/13 19:13:52 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


--lambo 20111009
--手机站刷新简历
--返回值：
--	0	数据库错误
--	-1	手机号已经列入黑名单
--	-2	手机号或求职状态为空
--	-3	该简历不属于该账号
create PROCEDURE [dbo].[wpCvMainByRefreshDateUpdate]
(
    @paMainID INT,
    @cvMainID INT,
    @Mobile VARCHAR(13),
    @dcCareerStatus INT,
    @dcSalaryID INT,
    @RelatedWorkYears INT,
    @IsNegotiable BIT,
    @IP VARCHAR(30)
)
AS
SET NOCOUNT ON
SET @Mobile = dbo.TextTrim(@Mobile)
IF @Mobile IS NULL
	RETURN -2		--手机号空

IF EXISTS(SELECT 'x' FROM Person_BLACK WITH(NOLOCK) WHERE Mobile = @Mobile)
BEGIN
	----有黑名单，则增加拒绝次数
	UPDATE Person_Black SET RefuseCount = RefuseCount + 1 WHERE Mobile = @Mobile
	RETURN -1
END

IF NOT EXISTS(SELECT 'x' FROM cvMain WITH(NOLOCK) WHERE ID = @cvMainID AND paMainID = @paMainID)
	RETURN -3
BEGIN TRAN
	BEGIN TRY
		--如果新旧日志不相同，记录更新手机号的操作
		DECLARE @MobileOld AS VARCHAR(13)
		SELECT @MobileOld = Mobile FROM paMain WITH(NOLOCK) WHERE ID = @paMAinID
		IF ISNULL(@MobileOld, '') <> @Mobile
			INSERT INTO paOperationLog (paMainID, Operation, Details, IP) 
			VALUES(@paMainID, 35,'更新手机号，原手机号：<' + ISNULL(@MobileOld, '') + '>；新手机号：<' + @Mobile + '>', @IP)
	
		UPDATE CvMain SET 
			ReFreshDate = GETDATE(),
			dcSalaryID = @dcSalaryID,
			RelatedWorkYears = @RelatedWorkYears,
			IsNegotiable = @IsNegotiable
		WHERE ID = @cvMainID AND paMainID = @paMainID

		UPDATE paMain SET Mobile = @Mobile --, dcCareerStatus # @dcCareerStatus 
		WHERE ID = @paMainID
		
	END TRY
	BEGIN CATCH
		GOTO ERR
	END CATCH
COMMIT TRAN
RETURN 1
ERR:
BEGIN
	ROLLBACK TRAN
	RETURN 0
END













GO

/****** Object:  StoredProcedure [dbo].[wpCvMainBySendValidSelect]    Script Date: 2018/12/13 19:13:52 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[wpCvMainBySendValidSelect]
(
	@paMainID INT
)
AS
BEGIN
	SELECT ID,Name FROM cvMain WITH(NOLOCK) 
		WHERE ((cvLevel like '1111_1%' AND VerifyResult=1) 
			OR (cvLevelEng like '1111_1%' AND VerifyResultEng=1)
			OR Attachment>'') AND paMainID = @paMainID
END













GO

/****** Object:  StoredProcedure [dbo].[wpdcSubSiteSelect]    Script Date: 2018/12/13 19:13:52 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--lambo 20111011
--获取所有省份，当前省份在前
CREATE PROCEDURE [dbo].[wpdcSubSiteSelect]
(
	@ProvinceID INT
)
AS
BEGIN
	SELECT * FROM dcRegion WHERE grade=1
		ORDER BY 
			CASE 
				WHEN id=@ProvinceID THEN 1 
				ELSE id
			END
END













GO

/****** Object:  StoredProcedure [dbo].[wpExMessageLogSelect]    Script Date: 2018/12/13 19:13:53 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--lambo 20101008
--查询个人与企业的留言记录
CREATE PROCEDURE [dbo].[wpExMessageLogSelect]
(
    @paMainID INT,
    @PageSize INT,
    @SkipCount INT,
    @RowsCount INT OUTPUT
)
AS
BEGIN 
	SELECT @RowsCount = COUNT(1) FROM exMessageC2p a WITH(NOLOCK),
			caMain b WITH(NOLOCK),
			cpMain c WITH(NOLOCK)
			WHERE 
			a.caMainID = b.ID 
			AND b.cpMainID = c.ID
			AND cvMainID IN (SELECT ID FROM cvMain WITH(NOLOCK) WHERE paMainID=@paMainID)
			AND CompanyDeleted=0
			
	SELECT TOP (@PageSize) * INTO #wapMessage FROM
	(
		SELECT 
			a.ID,
			a.IsReply,
			c.ID CpMainID,
			c.SecondID EnCpMainID,
			c.Name CompanyName,
			Message,
			(SELECT top 1 CASE a.IsReply WHEN 1 THEN Message WHEN 0 THEN NULL  END
				FROM ExMessageP2C WITH(NOLOCK) 
				WHERE cvMainID IN (SELECT ID FROM cvMain WITH(NOLOCK) WHERE paMainID=@paMainID)
				AND AddDate>a.AddDate
				AND caMainID = a.caMainID
				ORDER BY ID) MessageReply,
			Row_number() OVER(ORDER BY a.ID DESC) rowNo
		FROM exMessageC2p a WITH(NOLOCK),
			caMain b WITH(NOLOCK),
			cpMain c WITH(NOLOCK)
			WHERE 
			a.caMainID = b.ID 
			AND b.cpMainID = c.ID
			AND cvMainID IN (SELECT ID FROM cvMain WITH(NOLOCK) WHERE paMainID=@paMainID)
			AND CompanyDeleted=0
		) a 
		WHERE a.rowNo >@SkipCount
		UPDATE ExMessageC2P SET IsViewed = 1 WHERE ID IN (SELECT ID FROM #wapMessage) AND IsViewed=0
		SELECT * FROM #wapMessage
END











GO

/****** Object:  StoredProcedure [dbo].[wpPaMainByLoginUpdate]    Script Date: 2018/12/13 19:13:53 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--------------------------------------------------
--lambo 20110928
--手机站个人用户登录，与pcPaMainByLoginUpdate不同的地方是增加paLoginlog是记录是从手机站登录的。
--LoginFrom%=%1 
--密码加密后的手机登陆
--------------------------------------------------
CREATE PROCEDURE [dbo].[wpPaMainByLoginUpdate]
(
	@UserName VARCHAR(50),
	@Password VARCHAR(50),
	@PasswordDe VARCHAR(60),
	@IP VARCHAR(31),
	@dcSubSiteId SMALLINT,
	@AutoLogin TINYINT,
	@browser VARCHAR(500),
	@ID INT,
	@IDType INT,
	@PaType INT OUTPUT,
	@loginFrom INT
)
AS
SET NOCOUNT ON
BEGIN TRY
	BEGIN TRAN
		DECLARE 
			@Resume_XinxiID AS INT,
			@AddMan AS INT,
			@AddDate AS DATETIME,
			@Email AS VARCHAR(50),
			@CountDate AS INT,
			@dcProvinceID AS TINYINT,
			@TotalLoginNum AS INT,
			@LastLoginDate AS SMALLDATETIME
		
		SELECT @CountDate = CONVERT(VARCHAR(8), GETDATE(), 112), @dcProvinceID = LEFT(@dcSubSiteId, 2)
		SELECT @PaType = @IDType, @UserName = REPLACE(@UserName, ' ', '')
		BEGIN TRY
			IF @PaType=3
			BEGIN
				SELECT @Resume_XinxiID = ID, @AddMan =AddMan, @AddDate = RegDate, @Email = Email
				FROM Resume_Xinxi WITH(NOLOCK INDEX(IX_Resume_Xinxi_UserName))
				WHERE UserName = @UserName AND Password = [REDACTED]
				IF @Resume_XinxiID IS NOT NULL
					SET @PaType=2
			END			
			ELSE IF @PaType=0
			BEGIN
				SELECT TOP 1 @Resume_XinxiID = ID, @AddMan =AddMan, @AddDate = RegDate, @Email = Email
				FROM Resume_Xinxi WITH(NOLOCK INDEX(IX_Resume_Xinxi_UserNameLower))
				WHERE UserNameLower = @UserName AND Password = [REDACTED]
				ORDER BY ID DESC

				IF @Resume_XinxiID IS NOT NULL
					SET @PaType=4
			END

			IF @PaType=0
				GOTO Err1

			IF @Resume_XinxiID > 0	----账号在Resume_xinxi
			BEGIN
				--lucifer添加，添加新的注册模式
				DECLARE @RegisterFrom AS TINYINT
				SELECT @RegisterFrom = 1
				IF CHARINDEX('ios', LOWER(@browser)) > 0
					SELECT @RegisterFrom = 3
				ELSE IF CHARINDEX('android', LOWER(@browser)) > 0
					SELECT @RegisterFrom = 2

				--把数据从Resume_Xini转换到paMain
				INSERT INTO paMain(RegisterMode, AddMan, UserName, Password, Email, dcProvinceID, dcSubSiteId, RegisterIP, IsDefaultPassword, AddDate, RegisterFrom, RegisterType, SpreadDate)
				VALUES(1, @AddMan, @UserName, @PasswordDe, @Email, @dcProvinceID, @dcSubSiteId, @IP, 1, GETDATE(), @RegisterFrom, 101, @AddDate)
				SET @ID = @@IDENTITY
				INSERT INTO paOperationLog (paMainID, Operation, Details, IP) VALUES(@ID, 10, '导入个人账号成功。', @IP)

				--记录日报
				UPDATE DateReport SET ValidResume = ValidResume + 1
				WHERE province_id = @dcProvinceID AND CountDate = @CountDate
				INSERT INTO pamainDatereport SELECT @ID, 9, GETDATE() -- SEAN 20130911
				--统计信息员注册数据
				SELECT TOP 1 CountDate
				FROM Info_Datereport WITH(NOLOCK)
				WHERE CountDate = @CountDate
				AND province_id = @dcProvinceID
				AND InfoManager_ID = @AddMan
				IF (@@ROWCOUNT=0)
					INSERT INTO Info_DateReport(province_id,infomanager_id,countdate) 
					VALUES(@dcProvinceID, @AddMan, @CountDate)
				
				UPDATE Info_Datereport 
				SET ValidResume=ValidResume + 1  
				WHERE CountDate=@CountDate
				AND province_id=@dcProvinceID
				AND InfoManager_ID = @AddMan
			END

			--超过登陆次数,每天限制登录次数位20次
			IF (SELECT COUNT(1) FROM paLoginLog WITH(NOLOCK) WHERE paMainID = @ID AND AddDate > CONVERT(VARCHAR(10), GETDATE(), 120)) > 19
				GOTO ERR2

			--登陆日志
			SELECT @LastLoginDate = LastLoginDate, @TotalLoginNum = TotalLoginNum FROM paMain WITH(NOLOCK) WHERE ID = @Id

			IF CONVERT(VARCHAR(8), @LastLoginDate, 112) = CONVERT(VARCHAR(8), GETDATE(), 112)	--今天已经登陆过
			BEGIN
				--IF @AutoLogin = 0			--首页的自动登录不计算在每日登陆次数
				--BEGIN
				INSERT INTO paLoginLog(paMainID, LoginIP, browser, loginFrom) VALUES(@ID, @IP, '6:' + ISNULL(@browser, 'Null'), @loginFrom)
				SELECT @TotalLoginNum = @TotalLoginNum + 1
				--END

				IF @LastLoginDate < DATEADD(HOUR, -1, GETDATE())	--登录间隔>1小时更新登录时间
					UPDATE paMain SET LastLoginDate = GETDATE(), TotalLoginNum = @TotalLoginNum WHERE ID = @ID
				ELSE
					UPDATE paMain SET TotalLoginNum = @TotalLoginNum WHERE ID = @ID
			END
			ELSE
			BEGIN
				----今天第一次登录
				INSERT INTO paLoginLog(paMainID, LoginIP, browser, loginFrom) VALUES(@ID, @IP, '7:' + ISNULL(@browser, 'Null'), @loginFrom)
				SELECT @TotalLoginNum = @TotalLoginNum + 1

				UPDATE paMain SET TotalLoginNum = @TotalLoginNum, LastLoginDate = GETDATE() WHERE ID = @ID

				UPDATE DateReport
				SET PersonLoginNum_Net = PersonLoginNum_Net + 1  
				WHERE CountDate = CONVERT(VARCHAR(8), GETDATE(), 112)
				AND Province_Id = @dcProvinceID

				--INSERT INTO PaMainDateReport SELECT @Id, 11, GETDATE()	--sean 20130708
			END
		END TRY
		BEGIN CATCH
			GOTO Err3
		END CATCH
	COMMIT
	RETURN @ID
	ERR1:
	BEGIN
		ROLLBACK TRAN
		INSERT INTO LogDb..RegisterErrorLog
		SELECT @ID, '21|' + LTRIM(STR(@IDType)) + '|' + @IP, @UserName + ' ' + @Password, GETDATE()
		RETURN 0
	END
	ERR2:
	BEGIN
		ROLLBACK TRAN
		INSERT INTO LogDb..RegisterErrorLog
		SELECT @ID, '22|' + LTRIM(STR(@IDType)) + '|' + @IP, @UserName + ' ' + @Password, GETDATE()
		RETURN -1
	END
	ERR3:
	BEGIN
		ROLLBACK TRAN
		INSERT INTO LogDb..RegisterErrorLog
		SELECT @ID, '23|' + LTRIM(STR(@IDType)) + '|' + @IP, @UserName + ' ' + @Password, GETDATE()
		RETURN -2
	END
END TRY
BEGIN CATCH
	ROLLBACK TRAN
	INSERT INTO LogDb..RegisterErrorLog
	SELECT @ID, '20|' + LTRIM(STR(@IDType)) + '|' + @IP, @UserName + ' ' + @Password, GETDATE()
END CATCH
GO

/****** Object:  StoredProcedure [dbo].[wpWapSessionUpdate]    Script Date: 2018/12/13 19:13:54 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[wpWapSessionUpdate]
(
	@SessionID VARCHAR(50)
)
AS
BEGIN
	DECLARE @paMainID INT, @ID INT
	SELECT Top 1 @paMainID = paMainID, @ID = ID FROM WapSession WITH(NOLOCK) 
		WHERE SessionID = @SessionID
		AND RefreshDate > DateAdd(HOUR,-1,GETDATE())
	ORDER BY ID DESC

	SET @paMainID = ISNULL(@paMainID, 0)
	IF @paMainID > 0
	BEGIN
		UPDATE WapSession SET RefreshDate = GETDATE() WHERE SessionID=@SessionID
		DELETE FROM WapSession WHERE ID <> @ID AND paMainID = @paMainID
	END
	RETURN @paMainID
END
GO

