Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
243 views
in Technique[技术] by (71.8m points)

sql server - Create a sql query that can handle multiple check box selections

I have a form with 3 check box dropdown lists enabling multiple selection from each control.

Lets say for talking sake its an accommodation table I am querying and the check box dropdown lists are 'AccommodationName', 'Company', and 'Nights'.

So potentially I could be passing in multiple values from each control and I want to return an aggregated query relevant to all data input.

How should I be going about this query?

Is the query going to have to be dynamic sql?

Please note, I am using sql server 2005.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You will need to create a split function inside you database,

Definition Of Split Function

CREATE FUNCTION [dbo].[split]
    (
      @delimited NVARCHAR(MAX),
      @delimiter NVARCHAR(100)
    ) 
 RETURNS @t TABLE (id INT IDENTITY(1,1), val NVARCHAR(MAX))
AS
BEGIN
  DECLARE @xml XML
  SET @xml = N'<t>' + REPLACE(@delimited,@delimiter,'</t><t>') + '</t>'

  INSERT INTO @t(val)
  SELECT  r.value('.','varchar(MAX)') as item
  FROM  @xml.nodes('/t') as records(r)
  RETURN
END

Stored Procedure

Then you need to create a stored procedure which will build sql query dynamically and use this split function to handle multiple values passed as a comma deliminated list.

CREATE PROCEDURE GetData
    @AccommodationName  VARCHAR(1000) = NULL,
    @Company            VARCHAR(1000) = NULL,
    @Nights             VARCHAR(1000) = NULL
AS
BEGIN
 SET NOCOUNT ON;

 DECLARE @SQL NVARCHAR(MAX);

 SET @SQL = N' SELECT * FROM TableName WHERE 1 = 1 '
            + CASE WHEN @AccommodationName IS NOT NULL 
                THEN N' AND AccommodationName IN (SELECT Val FROM dbo.split(@AccommodationName )) '
                    ELSE N'' END
            + CASE WHEN @Company IS NOT NULL 
                THEN N' AND Company IN (SELECT Val FROM dbo.split(@Company)) '
                    ELSE N'' END
            + CASE WHEN @Nights IS NOT NULL 
                THEN N' AND Nights IN (SELECT Val FROM dbo.split(@Nights)) '
                    ELSE N'' END

  EXECUTE sp_executesql @SQL
                       ,N'@AccommodationName VARCHAR(1000), @Company VARCHAR(1000), @Nights VARCHAR(1000)'
                       ,@AccommodationName 
                       ,@Company 
                       ,@Nights 
END 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...