在SQL 2008中更改查询中的变量值

时间:2014-07-16 17:07:54

标签: sql sql-server-2008

如果有人可以帮助我,我会很感激。

我在sql 2008中有2个表:

[users]
  [userId] uniqueidentifier
  [beginningDate] datetime
and [items]
  [userId] uniqueidentifier
  [itemDate] datetime

我想计算在任何给定年份的1月到12月期间[items]中至少有一个项目的用户数量,我这样做:

DECLARE @Year int = 2014, @Month int = 1 --January
SELECT ISNULL(Count(*), 0)
FROM [users]
WHERE 
(
SELECT ISNULL(Count(*), 0) FROM [items] 
WHERE [users].[userId] =  [items].[userId] 
AND YEAR([itemDate]) = @Year
AND ( MONTH([itemDate]) >=  @Month AND MONTH([itemDate]) <=  12 ) 
) > 0

它工作正常,问题是我要检查(并相应地更改),如果[beginningDate]@Month /@Year更新(它将始终是同一年),那么更改@Month变量为[beginningDate]月份值。

1 个答案:

答案 0 :(得分:0)

感谢Allan S. Hansen的回复。

我通过创建一个函数并从我的查询中调用它来解决问题:

CREATE FUNCTION [dbo].[GetMonth]
(
    @UserId uniqueidentifier
    , @Year int
)
RETURNS int
AS
BEGIN
    DECLARE @Month int = 1; --January
    DECLARE @DateValue DateTime
    DECLARE @DateFrom DateTime = CONVERT(nvarchar(4), @Year) +'-03-01' --de mar
    SELECT @DateValue =
    CASE 
        WHEN [beginningDate] > @DateFrom THEN [beginningDate]
        ELSE @DateFrom
    END
    FROM [users]
    WHERE [userId] = @UserId
    IF(@DateValue IS NULL)
        SET @Month = 1;
    ELSE
        IF(@DateValue > @DateFrom) SET @Month = MONTH(@DateValue)
    return @Month;
END

这是新查询:

DECLARE @Year int = 2014, @Month int = 1 --January
SELECT ISNULL(Count(*), 0)
FROM [users]
WHERE 
(
    SELECT ISNULL(Count(*), 0) FROM [items] 
    WHERE [users].[userId] =  [items].[userId] 
    AND YEAR([itemDate]) = @Year
    AND ( MONTH([itemDate]) >=  [dbo].[GetMonth] ([users].[userId], @Year) 
    AND MONTH([itemDate]) <=  12 ) 
) > 0

非常感谢所有

Saludos

rubenc