简体   繁体   中英

How to assign Column Results to Parameters of a Query

I have a table "Values" The data looks like this:

    ID     Label     Value

    1     StartDate  1/1/17
    2     EndDate    1/15/17
    3     Dept         6

What I'd like to do is load the values of the "Label" column to the corresponding Parameters in my Query:

    Declare 
    @startdate Datetime,
    @enddate Datetime,
    @DepartmentID int

Select * 
From Customers 
Where created between @startdate and @enddate and @DepartmentID

How can I assign @Startdate to the 'Startdate' 'value' in the value table? Additionally, Since i'm using different datatypes in my query, than what they are stored in the Values table (Values are 'nvarchar' in values table) Will I run into potential problems?

You could try to do something like this:

SELECT 
    * 
FROM 
    CUSTOMERS
WHERE
    CREATED BETWEEN 
        (SELECT TOP 1 [Value] FROM Values WHERE Label = 'StartDate') --perform casts here if necessary
        AND
        (SELECT TOP 1 [Value] FROM Values WHERE Label = 'EndDate')   --perform casts here if necessary
Declare 
@startdate Datetime,
@enddate Datetime,
@DepartmentID int

set @startdate = (Select convert(datetime,[Value]) from dbo.Values where Label='StartDate')
set @enddate = (Select convert(datetime,[Value]) from dbo.Values where Label='EndDate')
set @DepartmentID =(Select convert(int,[Value]) from dbo.Values where Label='Dept')

Select * 
From Customers 
Where created between @startdate and @enddate and DepartmentId = @DepartmentID

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM