首页 文章

每次where子句返回true时更改where子句中使用的变量

提问于
浏览
0

我有一个大约有3百万条记录的数据库,每条记录都有id(int,主键),uniqueNumber(int)和updateTime(string) .

uniqueNumber可以属于多个记录 . updateTime表示记录更新的时间,如14:33:42

编辑:记录按更新时间排序 .

我想让用户定义uniqueNumber和interval . 然后我想查询数据库以获取属于该uniqueNumber的所有记录,其中updateTime等于一个变量,每次where条件为真时,它的值都按间隔增加 .

例如,我想要这样的东西:(在这个例子中没有使用DB)

string currentTime = "12:25:00";
    int interval = 2;

    public void LinqExample()
    {
        string[] arr = new string[4] { "12:23:00", "12:26:00", "12:27:00", "12:28:00"};

        var query = from c in arr
                    where c.Replace(":", "").CompareTo(currentTime.Replace(":", "")) > 0 && Inc()
                    select c;

        // query's output is: "12:26:00", "12:28:00"
    }

    private bool Inc()
    {
        currentTime = DateTime.Parse(currentTime).AddMinutes(interval).ToLongTimeString();
        return true;
    }

我的代码是正确的方法吗?

谢谢!

2 回答

  • 1

    看起来你想要的代码如果存在则需要通过EF在你的表上使用 CURSOR 生成SQL查询 . 但是,由于我无法使用游标生成代码,因此无法使用LINQ解决问题 . 恕我直言,这样做的唯一方法是编写像这样的表值函数

    CREATE FUNCTION GetTimesByUniqueNumberWithIntervalAndCondition
    (
        @interval int, @uniqueNumber int,@currentTime time
    )
    RETURNS 
    @Times TABLE 
    (
        t char(10)
    )
    AS
    BEGIN
        DECLARE timeCursor CURSOR LOCAL FAST_FORWARD READ_ONLY FOR
        SELECT updateTime FROM Table2 WHERE uniqueNumber = @uniqueNumber
        ORDER BY updateTime 
    
        DECLARE @t char(10);
    
        OPEN timeCursor
        FETCH NEXT FROM timeCursor INTO @t;
    
        WHILE @@FETCH_STATUS = 0
        BEGIN
            IF 
                1 = 1 -- place your condition here
            BEGIN
                INSERT @Times(t) VALUES(@t)
                SET @currentTime = DATEADD(MINUTE,@interval,CAST(@t AS time))
            END
    
            FETCH NEXT FROM timeCursor INTO @t;
        END
    
        CLOSE timeCursor
        DEALLOCATE timeCursor
    
        RETURN 
    END
    GO
    

    并在每次需要选择时查询此功能 .

  • 1

    你想要的是带有偏移量的modulo operation . 当前时间与记录时间之间的分钟差异是整数 . 如果该整数可以被区间值整除,那么你就得到了一个匹配:

    (假设实体框架,使用linq-to-sql使用SqlMethods)

    var now = DateTime.Now;
    var curr = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute, 0);
    
    var query = context.Table
    .Where(t => t.uniqueNumber == uniqueNumber
    .Where(t => t.updateTime > curr) 
    .Where (t => EntityFunctions.DiffMinutes(curr, t.updateTime) % interval == 0)
    .Select (t => new { t.updateTime, .... } )
    

相关问题