SQL Server store multiple values in sql variable

后端 未结 6 897
春和景丽
春和景丽 2020-12-29 15:02

I have the following query:

select * 
from cars 
where make in (\'BMW\', \'Toyota\', \'Nissan\')

What I want to do is store the where param

相关标签:
6条回答
  • 2020-12-29 15:05

    I wrote about this here if you want to see it in detail. In the mean time, you can't do it exactly how you are thinking.

    Your choices are:

    Using the LIKE command:

    DECLARE @CarOptions varchar(100)
    SET @CarOptions = 'Ford, Nisan, Toyota'
    
    SELECT *
    FROM Cars
    WHERE ','+@CarOptions+',' LIKE ',%'+CAST(Make AS varchar)+',%'
    

    A spliter function

    DECLARE @CarOptions varchar(100)
    SET @CarOptions = 'Ford, Nisan, Toyota'
    
    SELECT Cars.*
    FROM Cars
    JOIN DelimitedSplit8K (@CarOptions,',') SplitString
        ON Cars.Make = SplitString.Item
    

    Dyanmic SQL

    DECLARE @CarOptions varchar(100)
    SET @CarOptions = 'Ford, Nisan, Toyota'
    
    DECLARE @sql nvarchar(1000)
    
    SET @sql = 'SELECT * ' + 
                'FROM Cars ' + 
                'WHERE Make IN ('+@CarOptions+') '
    
    EXEC sp_executesql @sql
    

    In the mean time your best option is going to be to get rid of the variable completely.

    SELECT * FROM cars WHERE make IN (SELECT make FROM carsforsale );
    
    0 讨论(0)
  • 2020-12-29 15:11

    You can use a table variable:

    declare @caroptions table
    (
        car varchar(1000)
    )
    
    insert into @caroptions values ('BMW')
    insert into @caroptions values ('Toyota')
    insert into @caroptions values ('Nissan')
    
    select * from cars where make in (select car from @caroptions)
    
    0 讨论(0)
  • 2020-12-29 15:12

    why not?

    SELECT * FROM cars WHERE make IN (SELECT DISTINCT(make) FROM carsforsale)
    
    0 讨论(0)
  • 2020-12-29 15:16

    you can use JOIN statement.

    SELECT distinct c.*
    FROM cars c
    JOIN carsfrosale s
    ON s.id = c.fk_s
    

    If you want filter your list of carsforsale you can add

    WHERE s.id in (....)
    
    0 讨论(0)
  • 2020-12-29 15:27
    Fetch 1 value in table and store in variable    
    =======================================================================================
    
    Declare @query int
    
        select @query = p.ProductID From Product p inner join ReOrdering as r on 
        p.ProductID = r.ProductID and r.MinQty >= p.Qty_Available
    
        print @query
    
    0 讨论(0)
  • 2020-12-29 15:29

    Use CTE for storing multiple values into a single variable.

    ;WITH DATA1 AS 
    (
        select car_name
        from cars 
        where make in ('BMW', 'Toyota', 'Nissan')
    )
    SELECT @car_name = CONCAT(@car_name,',',car_name)
    FROM DATA1
    
    select @car_name
    
    0 讨论(0)
提交回复
热议问题