SQL Server传递列名作为where子句参数

时间:2018-07-12 08:24:50

标签: sql sql-server

如何将列名作为where子句参数传递。

SELECT RP.Saturday,
       RP.Sunday,
       RP.Monday,
       RP.Tuesday,
       RP.Wednesday,
       RP.Thursday,
       RP.Friday,
       RP.SalesMan,
       MC.CustomerID,
       MC.CustomerName
FROM RoutePlan RP
     FULL JOIN MasterCustomer MC ON RP.CustomerID = MC.CustomerID
WHERE MC.CreatedBy = 'abc'
  AND RP.Thursday = 1;

我可以从此查询中获取名称

(Select DATENAME(DW,GETDATE()))

但是如何将日期名称作为参数(列名称)传递。因为日期名称是一个字符串,而搜索变量数据格式是一个整数,所以查询显示为

  

将nvarchar值“星期四”转换为数据类型int时转换失败。”

3 个答案:

答案 0 :(得分:2)

您可以在逻辑上将参数应​​用于日期名称,例如:

DECLARE @day VARCHAR(10) = DATENAME(DW, GETDATE())

SELECT RP.Saturday,
       RP.Sunday,
       RP.Monday,
       RP.Tuesday,
       RP.Wednesday,
       RP.Thursday,
       RP.Friday,
       RP.SalesMan,
       MC.CustomerID,
       MC.CustomerName
FROM RoutePlan RP
     FULL JOIN MasterCustomer MC ON RP.CustomerID = MC.CustomerID
WHERE MC.CreatedBy = 'abc'
  AND (
    (@day = 'Saturday' and RP.Saturday = 1) OR
    (@day = 'Sunday' and RP.Sunday = 1) OR
    (@day = 'Monday' and RP.Monday = 1) OR
    (@day = 'Tuesday' and RP.Tuesday = 1) OR
    (@day = 'Wednesday' and RP.Wednesday = 1) OR
    (@day = 'Thursday' and RP.Thursday = 1) OR
    (@day = 'Friday' and RP.Friday = 1)
  )

使用此示例数据:

CREATE TABLE MasterCustomer(CustomerID int, CustomerName varchar(25), CreatedBy varchar(25))
CREATE TABLE RoutePlan(CustomerID int, Saturday bit, Sunday bit, Monday bit, Tuesday bit, Wednesday bit, Thursday bit, Friday bit, SalesMan varchar(25))

INSERT INTO MasterCustomer (CustomerID, CustomerName, CreatedBy) VALUES (1, 'Customer1', 'abc')
INSERT INTO RoutePlan (CustomerID, Saturday, SalesMan) VALUES (1, 1, 'John')
INSERT INTO RoutePlan (CustomerID, Thursday, SalesMan) VALUES (1, 1, 'Joe')

在星期四运行此命令将返回1行,其中RP.Thursday = 1:

Saturday    Sunday  Monday  Tuesday Wednesday   Thursday    Friday  SalesMan    CustomerID  CustomerName
NULL        NULL    NULL    NULL    NULL        1           NULL    Joe         1           Customer1

答案 1 :(得分:0)

还有另一种方法,但这取决于服务器上的本地设置,因此您想使用Set DateFirst到7:

SET DATEFIRST 7;

SELECT RP.Saturday,
       RP.Sunday,
       RP.Monday,
       RP.Tuesday,
       RP.Wednesday,
       RP.Thursday,
       RP.Friday,
       RP.SalesMan,
       MC.CustomerID,
       MC.CustomerName
FROM RoutePlan RP
     FULL JOIN MasterCustomer MC ON RP.CustomerID = MC.CustomerID
WHERE MC.CreatedBy = 'abc'
AND (ISNULL(RP.Saturday, 0) * 1) +
    (ISNULL(RP.Sunday, 0) * 2) +
    (ISNULL(RP.Monday, 0) * 3) +
    (ISNULL(RP.Tuesday, 0) * 4) + 
    (ISNULL(RP.Wednesday, 0) * 5) + 
    (ISNULL(RP.Thursday, 0) * 6) + 
    (ISNULL(RP.Friday, 0) * 7) = DATEPART((weekday,GETDATE());

答案 2 :(得分:0)

恕我直言。根据RDBMS的哲学,最好的方法是为实例DayOfWeek(dayNum int not null, dayName nvarchar (16) not null)创建一个引用表 然后,您只需在其中插入所有值,即可在join部分

的main子句中使用它

以防万一-请记住,并非所有国家/地区的计数天数都相同。