Results 1 to 5 of 5

Thread: Searching via IN clause

  1. #1

    Thread Starter
    Hyperactive Member
    Join Date
    Apr 2012
    Posts
    423

    Searching via IN clause

    I have a textbox which a user will enter states into, CA, NV etc. I want to replace the space between states and add a common between them so I can do a where IN clause.

    vb.net Code:
    1. s = States.Text.Replace(" ", ", ")
    2.  
    3. SELECT * FROM Users WHERE State IN (@States)
    4. command.Parameters.AddWithValue("@States", s)

    I do it in SQL management studio and it works, in vb.net it gives no errors and no results where I should.

    What's is wrong?

  2. #2
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,344

    Re: Searching via IN clause

    I assume from your code that this is in VB.NET but you really should have stated that.

    You can't use a single parameter to insert multiple values. You should add one parameter for each value. Follow the CodeBank link in my signature and check out my thread on Using Parameters With An IN Clause to learn how. To get the individual values you should Split the user input on the spaces.

  3. #3
    King of sapila
    Join Date
    Oct 2006
    Location
    Greece
    Posts
    6,605

    Re: Searching via IN clause

    What is the exact code you use on management studio to put nvarchar-varchar states in one @variable using "IN" and is working for you?
    Oh, JMC beat me to it.
    ἄνδρα μοι ἔννεπε, μοῦσα, πολύτροπον, ὃς μάλα πολλὰ
    πλάγχθη, ἐπεὶ Τροίης ἱερὸν πτολίεθρον ἔπερσεν·

  4. #4
    King of sapila
    Join Date
    Oct 2006
    Location
    Greece
    Posts
    6,605

    Re: Searching via IN clause

    Actually u can sort of use a single parameter to insert multiple values but is tricky. Using TVC or in 2005 SQL versions and below "http://www.sommarskog.se/arrays-in-sql-2005.html" or you can use at trick with "Like"
    ἄνδρα μοι ἔννεπε, μοῦσα, πολύτροπον, ὃς μάλα πολλὰ
    πλάγχθη, ἐπεὶ Τροίης ἱερὸν πτολίεθρον ἔπερσεν·

  5. #5
    Serge's Avatar
    Join Date
    Feb 1999
    Location
    Scottsdale, Arizona, USA
    Posts
    2,744

    Re: Searching via IN clause

    Or you can just execute a dynamic sql passing your variable with "IN" values.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width