SQL Server 2012:DateDiff,其中where子句中不包括周末

时间:2018-07-23 07:49:28

标签: sql sql-server sql-server-2012 dynamic-sql datediff

我有一个动态SQL查询,该查询对在特定办公室签署的文档在创建日期后的1个工作日内进行计数。

以下是查询:

set @strsql = '(select @cnt = COUNT(*) from '+@TableNameDocs+' D
                inner join dbo.Signatures S on D.id = S.TableId
                where S.cityid = '+str(@Cityid)+' and S.OfficeId = '+str(@Officeid)+' and S.isValid = 1 and D.cityid = '+str(@Cityid)+' and D.OfficeId = '+str(@Officeid)+' and DATEDIFF(day,D.CreatedDate,COALESCE(S.SignedDate, GETDATE())) > 1)'

但是我想更改它,因此如果office是在周末是周六和周日的国家还是在某个国家,则只检查工作日期 周末是星期五和星期六。我可以从Offices表中获得办公室的国家。这些办公室可以在黎巴嫩(星期六至星期日周末)或沙特阿拉伯(星期五至星期六周末)

1 个答案:

答案 0 :(得分:1)

也许您可以尝试执行以下操作: 首先从Country表中找到@Officeid中的Offices

-- GET OFFICE'S COUNTRY
    SELECT @country = [Country] from dbo.Offices
    where officeid = @Officeid

然后根据国家/地区:

IF @country = 'SAUDI ARABIA' --Weekend in Saudi Arabia is Fri-Sat
    BEGIN
        set @strsql = '(select @cnt=COUNT(*) from '+@TableNameDocs+' D
                        inner join dbo.Signatures S on D.id = S.TableId
                        where S.cityid = '+str(@Cityid)+' and S.OfficeId = '+str(@Officeid)+' and S.isValid = 1 and D.cityid = '+str(@Cityid)+' and D.OfficeId = '+str(@Officeid)+' and 
                        ((DATEDIFF(dd, D.CreatedDate, COALESCE(S.SignedDate, GETDATE())))
                        -(DATEDIFF(wk, D.CreatedDate, COALESCE(S.SignedDate, GETDATE())) * 2)
                        -(CASE WHEN DATENAME(dw, D.CreatedDate) = ''Saturday'' THEN 1 ELSE 0 END)
                        -(CASE WHEN DATENAME(dw, COALESCE(S.SignedDate, GETDATE())) = ''Friday'' THEN 1 ELSE 0 END))>1)'

    END
    else
    BEGIN
        set @strsql = '(select @cnt=COUNT(*) from '+@TableNameDocs+' D
                        inner join dbo.Signatures S on D.id = S.TableId
                        where S.cityid = '+str(@Cityid)+' and S.OfficeId = '+str(@Officeid)+' and S.isValid = 1 and D.cityid = '+str(@Cityid)+' and D.OfficeId = '+str(@Officeid)+' and 
                            ((DATEDIFF(dd, D.CreatedDate, COALESCE(S.SignedDate, GETDATE())))
                            -(DATEDIFF(wk, D.CreatedDate, COALESCE(S.SignedDate, GETDATE())) * 2)
                            -(CASE WHEN DATENAME(dw, D.CreatedDate) = ''Sunday'' THEN 1 ELSE 0 END)
                            -(CASE WHEN DATENAME(dw, COALESCE(S.SignedDate, GETDATE())) = ''Saturday'' THEN 1 ELSE 0 END))>1)'
    END

积分 Jeff Moden