如何使用 And-Or 作为变量

How to use an And-Or as a variable

我实际上是在尝试从 table 中获取数据,但我希望 "And/Or" 基于 table 进行更改。我正在使用 SQL 服务器。

我喜欢这样的事情:

DECLARE @TURNOS TABLE (ID INT IDENTITY(1, 1),
                       INITURNO INT, 
                       ENDTURNO INT, 
                       ANDOR VARCHAR(3)
                      );

INSERT INTO @TURNOS 
VALUES (23, 7, 'OR'), (7, 15, 'AND'), (15, 23, 'AND')

我正在尝试做这样的事情:

WHILE (@count <= (SELECT COUNT(ID) FROM @TURNOS))
BEGIN
    SET @initurno = SELECT INITURNO FROM @TURNOS WHERE ID = @count
    SET @endturno = SELECT ENDTURNO FROM @TURNOS WHERE ID = @count
    SET @andor = SELECT ANDOR FROM @TURNOS WHERE ID = @count

    INSERT INTO @AnotherTable
        SELECT * 
        FROM dbo.TableA 
        WHERE DATES BETWEEN DATEPART(hh, DATES) >= @initurno @andor DATEPART(hh, DATES) < @enturno
END

有没有什么方法可以像我尝试使用 @andor 那样使用变量 And/Or?

提前致谢:)

您正在寻找动态 SQL。你可以这样试试;

declare @query nvarchar(max)
while(@count <= (select count(ID) from @TURNOS))
begin
    SET @num1 = select INITURNO from @TURNOS  where ID = @count
    SET @num2 = select ENDTURNO from @TURNOS  where ID = @count
    SET @andor = select ANDOR  from @TURNOS where ID = @count

    set @query = 'insert into @AnotherTable
    select * from dbo.TableA where DATES between Datepart(hh,DATES)>= '+cast(@INITURNO as nvarchar(5))+' '+@andor+' Datepart(hh,DATES)< '+cast(@ENDTURNO as nvarchar(5))+''
    EXECUTE sp_executesql @query
end

如果您确实需要将运算符作为变量,则可以使用动态 SQL。但是,如果您只需要有条件的查询,则只需包含这两个条件并根据变量切换它们。

insert into @AnotherTable
select * from dbo.TableA 
where 
/*First condition */
(
@andor = 'AND'
AND DATES between Datepart(hh,DATES)>= @INITURNO 
AND Datepart(hh,DATES)< @ENDTURNO
)

OR
/* Second condition */
(
@andor = 'OR'
AND (
     DATES between Datepart(hh,DATES)>= @INITURNO 
     OR Datepart(hh,DATES)< @ENDTURNO
     )
)

我不是 Dynamic 的忠实粉丝 SQL,但即使我是,我相信这不是 BETWEEN 关键字的正确语法?

这就是我的解决方案,我不会复制整个查询,而只会复制其中的 select 部分:

    select * from dbo.TableA 
    where (@andor = 'AND' AND Datepart(hh,DATES) BETWEEN @initurno AND @enturno) 
    OR (@andor = 'OR' AND (Datepart(hh,DATES) >= @initurno OR Datepart(hh,DATES) <= @enturno))

请注意,我将 <=@enturno 一起使用,因为这就是 BETWEEN 的工作方式,它包含右极限。如果您不想包含 @enturno,则需要重写上面的查询以在两种情况下都使用 >=<

    select * from dbo.TableA 
    where (@andor = 'AND' AND Datepart(hh,DATES) >= @initurno AND Datepart(hh,DATES) < @enturno) 
    OR (@andor = 'OR' AND (Datepart(hh,DATES) >= @initurno OR Datepart(hh,DATES) < @enturno))