如何使用And-Or作为变量

时间:2017-11-30 18:25:51

标签: sql sql-server variables table-variable

我实际上是想从表中获取数据,但我希望“And / Or”根据表格进行更改。我正在使用SQL Server。

我是这样的:

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一样?

提前致谢:)

3 个答案:

答案 0 :(得分:1)

您正在寻找动态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

答案 1 :(得分:1)

如果您确实需要运算符作为变量,则可以使用动态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
     )
)

答案 2 :(得分:0)

我不是动态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))