Question : Help using SQL IN statement as an "AND"

I have a feeling there is no way to do this, but figured I would ask anyway.  I'm passing a set of tags to my sproc (SQL Server) in CSV format.  Something like this:

sp_articlesByTag 'books, cars'

The parameter is passed to my (simplified) SQL code -

SELECT * from articles WHERE tags IN ( @tagparam )

Unfortunately it returns results containing books OR cars.  I want it to return books and cars.  I'm just looking for something a bit more elegant than parsing the CSV and building a WHERE statement in the sproc.

Thanks in advance for any help.

PS - Just so I give a complete picture, my calling code is classic ASP and I'm using a stacked Querystring to get the tags.  (ie:  search.asp?tag=books&tag=cars which returns 'books, cars' to me)

Answer : Help using SQL IN statement as an "AND"

IF all the columns in the SELECT are from "view_publicstories", something like below should do it.

If not, you may have to re-join to tbl_taglink.

Either way, it should give you a good idea of what you need to do.

Btw, when dealing with multiple tables in a query, your code will be much easier to write and to follow if you follow there guidelines:

1) ALWAYS alias all tables
2) If there is more than one table in a query, use the table alias on EVERY column in the SELECT.  This makes it easy to tell what column comes from what table.
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[sp_getStoriesByTag]
	@tagname varchar(2000),
	@sort int
AS
BEGIN
	SET NOCOUNT ON;
	DECLARE @sql as varchar(2000)
    DECLARE @tagcount as int
    SET @tagcount = LEN(@tagname) - LEN(REPLACE(@tagname, ',', '')) + 1

    SET @sql = 'SELECT DISTINCT recid, author, view_publicstories.recdate, title, storycodes, rating, ranking, views, pages
			FROM view_publicstories INNER JOIN (
                SELECT storyid
                FROM tbl_taglink
                WHERE tagid IN (
                    SELECT tagid
                    FROM tbl_tags
                    WHERE ( tagname in (' + @tagname + ') ) )
                GROUP BY storyid
                HAVING COUNT(*) = ' + CAST(@tagcount AS varchar(10)) + ') AS matches
            ON (view_publicstories.recid = matches.storyid) 
				ORDER BY ' + CASE @sort 
                    WHEN 1 THEN 'view_publicstories.ranking'
                    WHEN 2 THEN 'view_publicstories.rating'
                    WHEN 3 THEN 'view_publicstories.title'
                    ELSE '0'
                    END
        EXEC(@sql)
Random Solutions  
 
programming4us programming4us