Stored Procedure - Advanced Search
Oct 9, 2006
HI
i want to create a procedure, basically i'll have 4 input parametres (Title, Category, ReleaseClass and BuyPrice)
title will come from a textbox, the rest from dropdownlists
if a user enters a title, selects a ReleaseClass and BuyPrice, But doesnt select a category, all categories should be returned - You know what i mean
how do i go about this - Any Ideas??
Cheers!!!
View 7 Replies
ADVERTISEMENT
May 25, 2004
Hello,
(Excuse my english, i'm a french man)
I want to make a stored procedure on that model :
CREATE Procedure SGCP_GetEleveArgs
(
@Arg1 nVarChar,
@Val1 nVarChar
)
AS
SELECT *
FROM Eleve
WHERE @Arg1 = @Val1
So you understand that i want to pass my argument (@Arg1) as a field of a column.
but it gives :
WHERE 'Nom' = 'Dupont'
but i want to have :
WHERE Nom = Dupont
for it to work.
Have you an idea to solve that problem ?
Thanx
View 5 Replies
View Related
Mar 29, 2008
Hi - I'm short of SQL experience and hacking my way through creating a simple search feature for a personal project. I would be very grateful if anyone could help me out with writing a stored procedure. Problem: I have two tables with three columns indexed for full-text search. So far I have been able to successfully execute the following query returning matching row ids: dbo.Search_Articles @searchText varchar(150) AS SELECT ArticleID FROM articles WHERE CONTAINS(Description, @searchText) OR CONTAINS(Title, @searchText) UNION SELECT ArticleID FROM article_pages WHERE CONTAINS(Text, @searchText); RETURN This returns the ArticleID for any articles or article_pages records where there is a text match. I ultimately need the stored procedure to return all columns from the articles table for matches and not just the StoryID. Seems like maybe I should try using some kind of JOIN on the result of the UNION above and the articles table? But I have so far been unable to figure out how to do this as I can't seem to declare a name for the result table of the UNION above. Perhaps there is another more eloquent solution? Thanks! Peter
View 3 Replies
View Related
Oct 7, 2004
Well, I think it's an advanced question.
We've got two SQL servers on the same network.
Is it possible for one machine to execute a stored procedure on the other machine?
If so, how...or would it be better to write a quick C# application that does the job?
Basically, I want to scan my orders table on SQL box A for new orders every x seconds and as they as received post them off to SQL box B for processing and return the OrderID generated from box B back to SQL box A and update the record that has just been processed.
View 1 Replies
View Related
May 10, 2004
Hiya,
This is a fairly detailed problem, so this will be a long post... I do appologize. I have been agonizing over this now for over a week and cannot find a viable solution. Hopefully one of you can help.
First off, I work for a realestate company, and this query will display a list of properties based on a number of different criteria and criteria types. There are multiple tables involved:
dbo.Prop:
Property Database. Holds basic info about each property
dbo.Prop_Features:
holds all the features (such as Pool, Carpet, Drapes etc) for each property. The only information stored in this table are PropID and FeatureID (PropID being the Identity of the Prop table, FeatureID being the Identity of the Features Table)
dbo.Features
Holds information on each possable "feature" in the system.
dbo.Members
Holds basic information and criteria for each of our members.
dbo.Members_Features
This table holds the MemberID and FeatureID where members have chosen one ore more features to be used for criteria when searching for a property.
Ok, now... That said, here is my problem. The query I had written (by a professional hired thru Robert Half Technologies) takes over 30 seconds to execute. I will post a copy of that SP below. This is unacceptable. We have to process thousands of these per hour, and a 30 second process time is very bad. Can any of you give me a idea of how to better approach this problem?
In the code below, you will notice there are other tables I did not mention - they are not important. The Speed problem is surrounding a single function, which I will mention below.
CREATE PROCEDURE dbo.Member_Get_List
(
@MemberID Int,
@UpdatesOnly Bit
)
AS
Declare
@RentMin FLoat,
@RentMax Float,
@BedMin SmallInt,
@BedMax SmallInt,
@MinBaths Float,
@MinGarage Float,
@Acreage SmallInt,
@PropCount int,
@LastUpdate SmallDateTime
BEGIN
Select @Rentmin = Rentmin,
@RentMax = Rentmax,
@BedMin = BedMin,
@BedMax = BedMax,
@MinBaths = MinBaths,
@MinGarage = MinGarage,
@Acreage = Acreage,
@LastUpdate = LastUpdate
FROM
Members
WHERE
MemberID = @MemberID
END
BEGIN
SET @PropCount = (SELECT Count(*)
FROM Members_Features
WHERE MemberID = @MemberID )
END
IF @PropCount = 0
BEGIN
SELECT Top 100
P.PropID,
P.Bedrooms,
P.Baths,
P.Garage,
PT.PropName,
P.Rent,
P.Address,
P.Xstreets,
'DateAvailable' = CASE
WHEN DateDiff(Day, P.DateAvailable, GETDATE()) < 0 THEN 'NOW!'
ELSE CONVERT(varchar(10), P.DateAvailable, 101)
End,
P.Lease,
dbo.Prop_Get_Feature_List_Fun(P.PropID) + CASE Len(P.CustomFeatures)
WHEN 0 THEN ''
ELSE ', ' + P.CustomFeatures
End
+ CASE Len(P.Comments)
WHEN 0 THEN ''
ELSE ', ' + P.Comments
End
as 'Features',
P.Deposit,
Phone1 = SUBSTRING(L.Phone1, 1, 3) + '-' + SUBSTRING(L.Phone1, 4, 3) + '-' + SUBSTRING(L.Phone1, 7, 4),
A.AreaName,
Z.County,
Z.City,
Z.State
FROM Prop P
INNER JOIN Area_Zipcode AZ
ON P.Zip = AZ.Zipcode
INNER JOIN Area_Areas A
ON AZ.AreaID = A.AreaID
INNER JOIN Members_Areas MA
ON A.AreaID = MA.AreaID
INNER JOIN Members_PropTypes MP
ON P.PropType = MP.PropType
INNER JOIN Prop_Types PT
ON P.PropType = PT.PropType
INNER JOIN LandLords L
ON P.LandLordID = L.LandLordID
INNER JOIN ZipCode Z
ON P.ZIP = Z.ZipCode
WHERE
P.Active = 1
AND
P.Rent BETWEEN @RentMin AND @RentMax
AND
P.Bedrooms BETWEEN @BedMin AND @BedMax
AND
P.Baths >= @MinBaths
AND
P.Garage >= @MinGarage
AND
P.Acreage >= @Acreage
AND
MA.MemberID = @MemberID
AND
MP.MemberID = @MemberID
AND P.ListDate >
Case @UpdatesOnly
When 0 then '01/01/1900'
When 1 then @LastUpdate
End
END
ELSE
BEGIN
DECLARE @Flag int,
@FeatureID int,
@PropID int,
@Bedrooms tinyint,
@Baths float,
@Garage float,
@DisplayText varchar(75),
@Rent float,
@Address varchar(100),
@Xstreets varchar(100),
@DateAvailable varchar(10),
@Lease tinyint,
@Features Varchar(3500),
@Deposit float,
@Phone1 varchar(12),
@AreaName Varchar(50),
@County Varchar(30),
@City varchar(30),
@State varchar(75)
CREATE TABLE #Prop
(
PropID int,
Bedrooms tinyint,
Baths float,
Garage float,
DisplayText varchar(75),
Rent float,
Address varchar(100),
Xstreets varchar(100),
DateAvailable varchar(10),
Lease tinyint,
Features Varchar(3500),
Deposit float,
Phone1 varchar(12),
AreaName Varchar(50),
County Varchar(30),
City Varchar(30),
State Varchar(75)
)
DECLARE curProp Cursor FORWARD_ONLY for
SELECT Top 100
P.PropID,
P.Bedrooms,
P.Baths,
P.Garage,
PT.PropName,
P.Rent,
P.Address,
P.Xstreets,
'DateAvailable' = CASE
WHEN DateDiff(Day, P.DateAvailable, GETDATE()) < 0 THEN 'NOW!'
ELSE CONVERT(varchar(10),P.DateAvailable, 101)
End,
P.Lease,
dbo.Prop_Get_Feature_List_Fun(P.PropID) + CASE Len(P.CustomFeatures)
WHEN 0 THEN ''
ELSE ', ' + P.CustomFeatures
End
+ CASE Len(P.Comments)
WHEN 0 THEN ''
ELSE ', ' + P.Comments
End
AS 'Features',
P.Deposit,
Phone1 = SUBSTRING(L.Phone1, 1, 3) + '-' + SUBSTRING(L.Phone1, 4, 3) + '-' + SUBSTRING(L.Phone1, 7, 4),
A.AreaName,
Z.County,
Z.City,
Z.State
FROM Prop P
INNER JOIN Area_Zipcode AZ
ON P.Zip = AZ.Zipcode
INNER JOIN Area_Areas A
ON AZ.AreaID = A.AreaID
INNER JOIN Members_Areas MA
ON A.AreaID = MA.AreaID
INNER JOIN Members_PropTypes MP
ON P.PropType = MP.PropType
INNER JOIN Prop_Types PT
ON P.PropType = PT.PropType
INNER JOIN LandLords L
ON P.LandLordID = L.LandLordID
INNER JOIN ZipCode Z
ON P.ZIP = Z.ZipCode
WHERE
P.Active = 1
AND
P.Rent BETWEEN @RentMin AND @RentMax
AND
P.Bedrooms BETWEEN @BedMin AND @BedMax
AND
P.Baths >= @MinBaths
AND
P.Garage >= @MinGarage
AND
P.Acreage >= @Acreage
AND
MA.MemberID = @MemberID
AND
MP.MemberID = @MemberID
AND P.ListDate >
Case @UpdatesOnly
When 0 then '01/01/1900'
When 1 then @LastUpdate
End
OPEN curProp
FETCH NEXT
FROM curProp
INTO @PropID,
@Bedrooms,
@Baths,
@Garage,
@DisplayText,
@Rent,
@Address,
@Xstreets,
@DateAvailable,
@Lease,
@Features,
@Deposit,
@Phone1,
@AreaName,
@County,
@City,
@State
WHILE @@FETCH_STATUS = 0
BEGIN
SET @Flag = 1
-- print 'PropID = ' + convert(varchar(20),@propID)
DECLARE curMembers Cursor FORWARD_ONLY FOR
SELECT MF.FeatureID
FROM Members_Features as MF
INNER JOIN Members as M
ON MF.MemberID = M.MemberID
WHERE M.MemberID = @MemberID
OPEN curMembers
FETCH NEXT FROM curMembers into @FeatureID
WHILE @@FETCH_STATUS = 0
BEGIN
--print 'FeatureID = ' + convert(varchar(20),@FeatureID)
IF (EXISTS(
SELECT *
FROM Prop_Features
WHERE FeatureID = @FeatureID
AND PropID = @PropID))
FETCH NEXT FROM curMembers INTO @FeatureID
ELSE
BEGIN
SET @Flag = 0
BREAK
END
END -- While
CLOSE curMembers
DEALLOCATE curMembers
IF (@Flag = 1)
-- PRINT 'Success!!! PropID = ' + convert(varchar(20),@PropID)
--PRINT @PropID
INSERT INTO #Prop
VALUES (
@PropID,
@Bedrooms,
@Baths,
@Garage,
@DisplayText,
@Rent,
@Address,
@Xstreets,
@DateAvailable,
@Lease,
@Features,
@Deposit,
@Phone1,
@AreaName,
@County,
@City,
@State
)
FETCH NEXT
FROM curProp
INTO @PropID,
@Bedrooms,
@Baths,
@Garage,
@DisplayText,
@Rent,
@Address,
@Xstreets,
@DateAvailable,
@Lease,
@Features,
@Deposit,
@Phone1,
@AreaName,
@County,
@City,
@State
END -- While
CLOSE curProp
DEALLOCATE curProp
SELECT * FROM #Prop
DROP TABLE #Prop
END
Okey, now. Please notice this part of that code:
dbo.Prop_Get_Feature_List_Fun(P.PropID) + CASE Len(P.CustomFeatures)
WHEN 0 THEN ''
ELSE ', ' + P.CustomFeatures
End
+ CASE Len(P.Comments)
WHEN 0 THEN ''
ELSE ', ' + P.Comments
End
AS 'Features',
This function is the cause of the speed problem, methinks. When run alone, it takes 29 seconds to process with the same MemberID that takes about 33 seconds to process completely (the whole Proc). This function simply returns a list of comma delimited features for each property, for displaying on a customer list. Here is that function:
CREATE Function dbo.Prop_Get_Feature_List_Fun (@PropID int)
RETURNS Varchar(3500)
AS
BEGIN
Declare @FeatureList Varchar(3500)
select @FeatureList = Coalesce(@FeatureList + ', ', '' ) + F.FeatureName
FROM
Prop P
INNER JOIN
Prop_Features PF
ON
P.PropID = PF.PropID
INNER JOIN
Features F
ON
PF.FeatureID = F.FeatureID
WHERE
P.PropID = @PropID
ORDER BY
F.FeatureName
Set @FeatureList = isnull(@FeatureList,'Please call for features.')
RETURN @FeatureList
END
Now, I know I probably gave lots more information then needed to solve this issue - but its better to have too much then not enough.
Any help at all in speeding up this function or describing another way to do this would be most appreciative.
Dave
View 5 Replies
View Related
May 18, 2007
This is the Stored Procedure below ->
SET QUOTED_IDENTIFIER ON GOSET ANSI_NULLS ON GO
/****** Object: Stored Procedure dbo.BPI_SearchArchivedBatches Script Date: 5/18/2007 11:28:41 AM ******/if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[BPI_SearchArchivedBatches]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)drop procedure [dbo].[BPI_SearchArchivedBatches]GO
/****** Object: Stored Procedure dbo.BPI_SearchArchivedBatches Script Date: 4/3/2007 4:50:23 PM ******/
/****** Object: Stored Procedure dbo.BPI_SearchArchivedBatches Script Date: 4/2/2007 4:52:19 PM ******/
CREATE PROCEDURE BPI_SearchArchivedBatches( @V_BatchStatus Varchar(30)= NULL, @V_BatchType VARCHAR(50) = NULL, @V_BatchID NUMERIC(9) = NULL, @V_UserID CHAR(8) = NULL, @V_FromDateTime DATETIME = '01/01/1900', @V_ToDateTime DATETIME = '01/01/3000', @SSS varchar(500) = null, @i_WildCardFlag INT)
AS
DECLARE @SQLString NVARCHAR(4000)DECLARE @ParmDefinition NVARCHAR (4000)
IF (@i_WildCardFlag=0)BEGIN
SET @SQLString='SELECT Batch.BatchID, Batch.Created_By, Batch.RequestSuccessfulRecord_Count, Batch.ResponseFailedRecord_Count, Batch.RequestTotalRecord_Count, Batch.Request_Filename, Batch.Response_Filename, Batch.LastUpdated_By, Batch.LastUpdated, Batch.Submitted_By, Batch.Submitted_On, Batch.CheckedOut_By, Batch.Checked_Out_Status, Batch.Batch_Description, Batch.Status_Code, Batch.Created_On, Batch.Source, Batch.Archived_Status, Batch.Archived_By, Batch.Archived_On, Batch.Processing_Mode, Batch.Batch_TemplateID, Batch.WindowID,Batch.WindowDetails, BatchTemplate.Batch_Type, BatchTemplate.Batch_SubType FROM Batch INNER JOIN BatchTemplate ON Batch.Batch_TemplateID = BatchTemplate.Batch_TemplateID WHERE ((@V_BatchID IS NULL) OR (Batch.BatchID = @V_BatchID )) AND ((@V_UserID IS NULL) OR (Batch.Created_By = @V_UserID )) AND ((Batch.Created_On >= @V_FromDateTime ) AND (Batch.Created_On <= @V_ToDateTime )) AND Batch.Archived_Status = 1 '
if (@V_BatchStatus IS not null) begin set @SQLString=@SQLString + ' AND (Batch.Status_Code in ('+@V_BatchStatus+'))' end
if (@V_BatchType IS not null) begin set @SQLString=@SQLString + ' AND (BatchTemplate.Batch_Type in ('+@V_BatchType+'))' end END
ELSEBEGIN SET @SQLString='SELECT Batch.BatchID, Batch.Created_By, Batch.RequestSuccessfulRecord_Count, Batch.ResponseFailedRecord_Count, Batch.RequestTotalRecord_Count, Batch.Request_Filename, Batch.Response_Filename, Batch.LastUpdated_By, Batch.LastUpdated, Batch.Submitted_By, Batch.Submitted_On, Batch.CheckedOut_By, Batch.Checked_Out_Status, Batch.Batch_Description, Batch.Status_Code, Batch.Created_On, Batch.Source, Batch.Archived_Status, Batch.Archived_By, Batch.Archived_On, Batch.Processing_Mode, Batch.Batch_TemplateID, Batch.WindowID,Batch.WindowDetails, BatchTemplate.Batch_Type, BatchTemplate.Batch_SubType FROM Batch INNER JOIN BatchTemplate ON Batch.Batch_TemplateID = BatchTemplate.Batch_TemplateID WHERE ((@V_BatchID IS NULL) OR (isnull (Batch.BatchID, '''') LIKE @SSS )) AND ((@V_UserID IS NULL) OR (isnull (Batch.Created_By , '''') LIKE @V_UserID )) AND ((Batch.Created_On >= @V_FromDateTime ) AND (Batch.Created_On <= @V_ToDateTime )) AND Batch.Archived_Status = 1 '
if (@V_BatchStatus IS not null) begin set @SQLString=@SQLString + ' AND (Batch.Status_Code in ('+@V_BatchStatus+'))' end
if (@V_BatchType IS not null) begin set @SQLString=@SQLString + ' AND (BatchTemplate.Batch_Type in ('+@V_BatchType+'))' end
END
PRINT @SQLString
SET @ParmDefinition = N' @V_BatchStatus Varchar(30), @V_BatchType VARCHAR(50), @V_BatchID NUMERIC(9), @V_UserID CHAR(8), @V_FromDateTime DATETIME , @V_ToDateTime DATETIME, @SSS varchar(500)'
EXECUTE sp_executesql @SQLString, @ParmDefinition, @V_BatchStatus , @V_BatchType , @V_BatchID, @V_UserID , @V_FromDateTime , @V_ToDateTime , @SSS
GO
SET QUOTED_IDENTIFIER OFF GOSET ANSI_NULLS ON GO
The above stored procedure is related to a search screen where in User is able to search from a variety of fields that include userID (corresponding column Batch.Created_By) and batchID (corresponding column Batch.BatchID). The column UserID is a varchar whereas batchID is a numeric.
REQUIREMENT:
The stored procedure should cater to a typical search where any of the fields can be entered. meanwhile it also should be able to do a partial search on BatchID and UserID.
Please help me regarding the same.
Thanks in advance.
Sandeep Kumar
View 2 Replies
View Related
Aug 15, 2006
Hi, Using Visual Web Developer and SQL Express, (coding in Csharp) I want to add a
advanced search facility to my site. Problem is I do not know how to begin.
The website is a business directory and displays company names and services that they provide.
Here is where I am at....
So far I have made one query which allows users to search the database by "town" such as if they enter "London" in the text box, it returns the relevant records into a gridview.
Rather than have a seperate text box for each query, I want to provide an advanced search box option so users can define their search and query the database by various criterias, such as geography, sector, name, number of employees in companies etc.
I have seen compact advanced search boxes on many sites!.
Replies greatly appreciated.
prontonet
View 8 Replies
View Related
Dec 14, 2007
Hi..I am working With Asp.net using Vb for a Music Project.i have the requirment for serach songs according to catagory wise(Singer,Actor,Music Director, etc)
i have code like this...
If Not Page.IsPostBack Then searchword.Text = Request.QueryString("SearchWord") Response.Write(Request.QueryString("SearchWord")) Response.Write(Request.QueryString("Language")) Response.Write(Request.QueryString("SelectedCategory")) 'Response.Write(Request.QueryString("Query"))
Dim str As String = "select * from Music_SongDetails where Music_Clip_Id>0 and Music_Clip_Lang='" & Request.QueryString("Language") & "'"
If Request.QueryString("SelectedCategory") = "Song" Then str = str & " and Music_Clip_Name like '%" & Request.QueryString("SearchWord") & "%'" ElseIf Request.QueryString("SelectedCategory") = "Movie" Then str = str & " and Music_Folder_Name='" & Request.QueryString("SearchWord") & "'" ElseIf Request.QueryString("SelectedCategory") = "Actor" Then str = str & " and Music_Clip_Actor='" & Request.QueryString("SearchWord") & "'" ElseIf Request.QueryString("SelectedCategory") = "Actress" Then str = str & " and Music_Clip_Actress='" & Request.QueryString("SearchWord") & "'" ElseIf Request.QueryString("SelectedCategory") = "Music Director" Then str = str & " and Music_Clip_MusicDir='" & Request.QueryString("SearchWord") & "'" ElseIf Request.QueryString("SelectedCategory") = "Singer" Then str = str & " and Music_Clip_Singer='" & Request.QueryString("SearchWord") & "'" ElseIf Request.QueryString("SelectedCategory") = "All" Then str = str End If...........
I need to write this code using Store Procedure....
Kindly Help me out
Thanks in Advance
View 3 Replies
View Related
Mar 29, 2008
hi iam working with search for the first time,in the GUI i have 3 fields Audit Name,Year,Audit ID.After enetering any or all these details and pressing submit i must show the gridview with complete details.
I have problem with the procedure for searching depending on the details given,here is the procedure:
Select Aud.Ad_ID_PK,Aud.Audit_Name,Ind.Industry_Name,Cmp.Company_Name,Pla.Plant_Name,Reg.Login_Uname,Aud.Audit_Started_On,Aud.Audit_Scheduledto,Aud.Audit_Created_On from
Industry Ind,
Company Cmp,
Plant Pla,
RegistrationDetails Reg,
Audits Audwhere Ind.Ind_Id_PK =Aud.Audit_Industry and
Cmp.Cmp_ID_PK =Aud.Audit_Company and
Pla.Pl_ID_PK =Aud.Audit_Plant and
Reg.UID_PK =Aud.Audit_Engineer and
Ad_ID_PK in (select Ad_ID_PK from Pcra_Audits) and
year(Audit_Created_On)=year(@YrofAudit)
order by Audit_Created_On DESC
iam getting the data when the user enters year but i want the procedure where i can check for the three fields(Audit Name,Year,Audit ID) which user is entering.If he enters only one field it must check which field is enetered and must get the data.if more than one field is entered then all the conditions must be checked and must get the details.please help me..........
Its very urgent..Plz...
View 2 Replies
View Related
Aug 27, 2002
I am an inexperienced SQL programmer and need to write a SP which will be used to search a Call table within a Call Logging System used to log support calls for my company. The search criteria are fields like Call Reference No, Logged By, Call Status etc
The problem I have is that individual or a combination of these criteria may be used to search on -can anyone advise how I can write a SP which will take account of the possible different combinations of parameters which may be passed to the Stored Procedure
i.e. if 2 fields are populated during the search and 4 are empty
Thanks,
Stephen
View 1 Replies
View Related
Nov 27, 2007
Hi to All,
I am new to Prpgramming, I need to create a Stored Procedure for my requirement here is my requirement,I have two tables from those I need to get data. Table_One consists UserID,Name,Address,ContactInfo,EmailID, and Table_two consists UserID,CitizenShip,HieghestEducation,ExpectedJob
But I need get data search report Name,EmailID,HiehestEducation,ExpectedJob. User should able to wile card search. Pls help me in this regards.
Thanks in Advance..
View 1 Replies
View Related
Oct 9, 2006
Hi,
Could anybody please tell me how I can search for a stored procedure in SQL Server 2005? I know the name of the stored procedure and I want to find in which database that stored proc is located/stored and I want to see the code of it. (I have all the necessaary previleges.) Please tell me how I can I do this.
Thanks in advance.
Regards,
Ram.
View 7 Replies
View Related
Apr 30, 2008
Hello
I have a text box on my web form where the user can enter multiple comma delimited search words. The value from this text box goes to my search stored procedure in the form of a search string.
I am able to parse this comma delimited search string and get the words into a temp table.
If there are 2 words in the temp table then this is the sql that I want
select * from Items
where (description like word1 or tagnumber like word1 or user like word1)
and (description like word2 or tagnumber like word2 or user like word2)
description,tagnumber, user or the fields of the Items table.There could be any number of words in the search string.
Any ideas of how to get this done with any number of search words being matched against number of column/s.
Any help regarding this is appreciated.
Thank you.
View 4 Replies
View Related
Jul 25, 2006
Hi query-experts,
I have an application that connects to a db running on SQL server 2000. I want the user to be able to do a google-like search, which returns all records containing all given keywords specified by the user in any of the fields, example:
Table has the fields: id, fruit, color
User enters: apple pear green
The query should return all records that contain apple AND pear AND green in any of the fields.
Now I do it like this:
SELECT * FROM table WHERE (fruit LIKE '%apple%' OR fruit LIKE '%pear%' OR fruit LIKE '%green%') AND (color LIKE '%apple%' OR color LIKE '%pear%' OR color LIKE '%green%')
this query works fine, but since my actual table contains about 10 fields that have to be searched, the query get's quite huge, especially when 2 or more keywords are given.
Question: is there an easier way to achieve this?
(this is what my query actually looks like, using the keywords dekker warmenhuizen 0226:)
SELECT
tKlant.nKlant AS nKlant,
MAX(sAchternaam) AS sAchternaam,
MAX(sVoornaam) AS sVoornaam,
MAX(sVoorletters) AS sVoorletters,
MAX(sBedrijfsnaam) AS sBedrijfsnaam,
MAX(sPlaats) AS sPlaats,
MAX(sStraat + ' ' + sHuisnummer) AS sAdres,
MAX(sPostcode) AS sPostcode,
MAX(sCommunicatie) AS sCommunicatie,
(CASE DATALENGTH(mOverig) WHEN 0 THEN 0 ELSE 1 END) AS HasOverig,
MAX(sKlantGroep) AS sKlantGroep
FROM tKlant
LEFT JOIN tKlantGroep ON tKlant.nKlantGroep = tKlantGroep.nKlantGroep
LEFT JOIN tCommunicatie ON tKlant.nKlant = tCommunicatie.nKlant
LEFT JOIN tAdres ON tKlant.nKlant = tAdres.nKlant
WHERE (tKlant.sAchternaam LIKE '%dekker%' OR tKlant.sBedrijfsnaam LIKE '%dekker%' OR tKlant.sKlant LIKE '%dekker%' OR tKlant.sVoornaam LIKE '%dekker%' OR tKlant.mOverig LIKE '%dekker%' OR tCommunicatie.sCommunicatie LIKE '%dekker%' OR tAdres.sStraat + ' ' + tAdres.sHuisnummer LIKE '%dekker%' OR tAdres.sPostcode LIKE '%dekker%' OR tAdres.sPlaats LIKE '%dekker%' OR tKlantGroep.sKlantGroep LIKE '%dekker%')
AND (tKlant.sAchternaam LIKE '%warmenhuizen%' OR tKlant.sBedrijfsnaam LIKE '%warmenhuizen%' OR tKlant.sKlant LIKE '%warmenhuizen%' OR tKlant.sVoornaam LIKE '%warmenhuizen%' OR tKlant.mOverig LIKE '%warmenhuizen%' OR tCommunicatie.sCommunicatie LIKE '%warmenhuizen%' OR tAdres.sStraat + ' ' + tAdres.sHuisnummer LIKE '%warmenhuizen%' OR tAdres.sPostcode LIKE '%warmenhuizen%' OR tAdres.sPlaats LIKE '%warmenhuizen%' OR tKlantGroep.sKlantGroep LIKE '%warmenhuizen%')
AND (tKlant.sAchternaam LIKE '%0226%' OR tKlant.sBedrijfsnaam LIKE '%0226%' OR tKlant.sKlant LIKE '%0226%' OR tKlant.sVoornaam LIKE '%0226%' OR tKlant.mOverig LIKE '%0226%' OR tCommunicatie.sCommunicatie LIKE '%0226%' OR tAdres.sStraat + ' ' + tAdres.sHuisnummer LIKE '%0226%' OR tAdres.sPostcode LIKE '%0226%' OR tAdres.sPlaats LIKE '%0226%' OR tKlantGroep.sKlantGroep LIKE '%0226%')
GROUP BY tKlant.nKlant, DATALENGTH(mOverig)
ORDER BY sAchternaam, sPlaats, sAdres;
View 3 Replies
View Related
Feb 21, 2007
I have a few textboxes on a page that I would like to use as a search page and have clients shown in a gridview that meet the users entry into one or more of the textboxes.
I have ClientID, LastName, FirstName, Address, and Keywords. How would I build a stored procedure to allow me to do this?
View 5 Replies
View Related
Mar 7, 2008
Hello,
Is it possible to search in two tables, let's say table # 1 in specific field e.g. (age). If that field is empty then retrieve the data from table #1, if not retrieve the data from table # 2.
Is it possible to do it by using SQL Stored Procedure??
Thank you
View 4 Replies
View Related
Apr 7, 2015
I have a store procedure that search by Firstname and Lastname. I want it search by either both (Firstname and Lastname) or any of them. For example if only FirstName passes to it shows all the record with that Fistname. Currently I have to pass both Firstname and Lastname to my store proc to get the result.
This is my stor proc:
USE [CustomerPortal]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[CSA_Search_Customer_By_Name]
[Code] ....
View 4 Replies
View Related
May 5, 2008
hi
can i search a word in my all stored procedure
not in system stored procedure
only in my stored procedure
like i need to search ' Getdate() ' in my all stored procedure
TNX
View 8 Replies
View Related
Jan 15, 2013
KEYIDGROUP
1 1 a
2 1 b
3 2 a
4 2 b
5 3 a
6 3 b
7 4 a
8 5 a
This is my simple table I need a query that will identity the ID's that are missing the group "b" but I don't want ID 1,2,3 to come up because they are part of a and b. I just need to see anything missing only "b" but not if it's part of a and b.
query should reveal answer should be missing the group b
KEYID
7 4
8 5
I tried the NULL search but since the records don't exist it cant find a null. I am writing a query to identify the missing ID without B but exclude ID that are part of A and B
View 3 Replies
View Related
Sep 8, 2006
Hi Guys, I hope someone here can help me. I am writing a stored procedure that simply searches for a given value across multiple databases on the same server. So far all well and good.Now, the problem is if the user types in more than one word into the search field.I have put a partial section of code here, there is obviously more, but most of it you wouldn't need to see. SELECT @sql = N'SELECT @count = COUNT('+ @dbname +'.dbo.orders.order_id) FROM '+ @dbname +'.dbo.orders '+
N' INNER JOIN '+ @dbname +'.dbo.customer ON '+ @dbname +'.dbo.orders.cust_id = '+ @dbname +'.dbo.customer.cust_id '+
N' WHERE '+ @dbname +'.dbo.customer.forename LIKE ''%'+ @SearchStr + '%'' OR '+ @dbname +'.dbo.customer.Surname LIKE ''%'+ @SearchStr + '%'''
EXEC sp_executesql @sql, N'@count int OUTPUT', @count = @results OUTPUT Now this code works perfectly well if the user only enters one word, however i need to make sure that the Stored procedure will function if the user enters 2 words, such as John Smith. I need the procedure to search the forename for 'john' & 'Smith' and the same for the surname. It should also work if the user type 'John Michael Smith' - if you understand.I am really struggling with this one.Thanks in advance.Darren
View 2 Replies
View Related
Jun 7, 2007
I am trying to inject dynamically generated text into a Sql2000 stored procedure. What am I doing wrong?A code behind routine generates the following string value based on a visitor entering 'sail boats' in TextBox1. The routine splits the entry and creates the below string.Companies.L_Keywords LIKE '%sail%' AND Companies.L_Keywords LIKE '%boats%'
I am trying to place this string result in the WHERE statement of a Sql2000 Stored Procedure using parameter @VisitorKeywords.
PROCEDURE dbo.KWsearchAS SELECT DISTINCT Companies.L_Name, Companies.L_ID, Companies.L_EnabledWHERE ( @visitorKeywords ) AND (Companies.L_Enabled = 1)ORDER BY Companies.L_Name
I am wanting the resulting WHERE portion to be:
WHERE ( Companies.L_Keywords LIKE '%sail%' AND Companies.L_Keywords LIKE '%boats%' ) AND (Companies.L_Enabled = 1)
Thank you
View 10 Replies
View Related
May 18, 2008
Hi I want to give the user the ability to search based on a number of criteria, however i do not know how to build my statement properly this is what i have so far;
ALTER PROCEDURE [dbo].[stream_StoreFind]
-- Add the parameters for the stored procedure here
@StoreName varchar(250),@subCategoryID INT
AS
SELECT Stores.StoreName ,StoreCategories.storeIDFROM Stores INNER JOIN
StoreCategoriesON
Stores.storeID = StoreCategories.storeID INNER JOIN
SubCategories ON
StoreCategories.subCategoryID = SubCategories.subCategoryID WHERE
My problem is how will i pass the parameters into the statement, taking into fact that sometimes they may be optional. Thank you
View 12 Replies
View Related
Apr 21, 2005
Hi,
I have a MSDE datatable which containes Documents and a link to thet document.
Is there any way i can search the doument name colunm using a search box from my web site and display the results. I have seen all these "stored procedure" discussions and just wonder whether it would be easy to search using the stored procedure?
I haven't got much experience using MSDE and it seems really a big task for me.
Any help/suggestions would be highly appreciated.
Thanks, RAJESH
View 4 Replies
View Related
Oct 6, 2005
My scenario is I have a web form with a textbox and a button.Once I enter a string and hit submit button, my stored procedure will have to return the result set.So if my search string is "text book title", then I have to execute the query like :select * from tab1 where col1 like '%text%" or col1 like '%book%" or col1 like '%title%"The problem here is I will never know how many words will be entered to search. So I have to make the statement dynamic.How can I do this in a stored procedure? Any help will be appreciated.Thanks.
View 6 Replies
View Related
Nov 6, 2012
sp_MSforeachdb 'Select ''?'' as Dbname, SPECIFIC_SCHEMA, ROUTINE_NAME
From ?.INFORMATION_SCHEMA.ROUTINES
where ROUTINE_NAME like ''%YourSPName%'''
View 1 Replies
View Related
Jun 25, 2015
I would like to search for a particular stored procedure written by a developer. I know the name of the procedure but in which db is it residing in. There are 40 databases in this SQL 2008 instance. I search on the name column in sys.all_objects table and it does not return anything. I end up querying sys.procedures on each database to locate the procedure. Is there a system table/view that I can query to look for a procedure, instead of querying sys.procedures on each database one by one?
View 1 Replies
View Related
Jun 14, 2006
Hi I am new to this forum. I have a stored proc that conducts a search based on a number of parameters entered by the user. The way I am currently building the procedure is the following, this is one segment of the if/else structure:------------------------------------------------------------------------------------------------------------------------------
--If latitude, longitude or distance are null and ProjectID and AnalysisTypeID are not NULL
ELSE IF (@i_Latitude IS NULL OR @i_Longitude IS NULL OR @i_distance IS NULL) AND @i_ProjectID IS NOT NULL AND @i_AnalysisTypeID IS NOT NULL
BEGIN
SELECT Distinct Projects.ProjectName,
Projects.ProjectNumber,
Projects.ProjectID,
Tasks.TaskID,
Tasks.TaskDesc,
Tasks.TaskName,
Locations.LocationID,
Locations.LocationName,
Locations.LocationLatitude,
Locations.LocationLongitude,
Locations.LocationComments,
AnalysisType.AnalysisTypeName
FROM Projects INNER JOIN
Tasks ON Projects.ProjectID = Tasks.ProjectID INNER JOIN
Locations ON Tasks.TaskID = Locations.TaskID INNER JOIN
Analysis ON Tasks.TaskID = Analysis.TaskID INNER JOIN
AnalysisType ON Analysis.AnalysisTypeID = AnalysisType.AnalysisTypeID
WHERE Analysis.AnalysisTypeID=@i_AnalysisTypeID AND Analysis.AnalysisIsDeleted='False'
AND Tasks.TaskIsDeleted='False' AND Locations.LocationIsDeleted='False' AND Projects.ProjectID=@i_ProjectID AND Tasks.TaskIsComplete='True'
ORDER BY Locations.LocationID
END
-------------------------------------------------------------------------------------------
So basically I have the parameters being passed in as having a value or null. I have an if/else structured that determines which code to execute based on the parameters value. As you can imagine the stored procedure is getting very large and hard to maintain because every new parameter doubles the if else structure, but I am not sure how to redesign it to be more manageable. Any help with this would be extremely appreciated.
Thanks,
Tony.
View 6 Replies
View Related
Jun 10, 2015
Few users are getting ‘could not find stored procedure error’ for several SPs in SQL 2012 even these SPs exist in DBs. if it’s a bug in SQL 2012 and its suggested workaround.
View 12 Replies
View Related
Jun 8, 2007
Hi,
I'm working on a new site with a big number of future concurrent visitors so performance is very important. We're working on a search function with which users can search for multiple keywords in a single table. My .NET application consults a SQL Server 2005 Stored Procedure to lookup the information. The stored procedure builds up a dynamic SQL string with which the table is queried.
An example:
User searches for 'car airco'. Alle records with the words car and/or airco in specified columns should show up. This works. The query would be
SELECT Col1, Col2 FROM Table1 WHERE (Col1 LIKE '%car%' OR Col2 LIKE '%car%')OR (Col1 LIKE '%airco%' OR Col2 LIKE '%airco%')
As I mentioned before performance is a hot issue in this project. The problem with the stored procedure is that it can't be precompiled by SQL Server (dynamic SQL string). Is there a way to search for multiple keywords without losing the precompile behaviour of SQL Server Stored Procedures?
Kind regards,
ThaYoung1!
View 11 Replies
View Related
Dec 4, 2003
Hi,
I have a repeater control which I populate with search results from SQL Server.
But I can't figure out how to cope with users who submit multiple search items and still use my stored procedure. Is this possible or do you have to build the query with a StringBuilder and execute it manually?
I'm using a stored procedure with parameters:
input parameters <-- PageSize & CurrentPage
output parameter --> TotalRecords
Am using a temporary table to store all records before Select-ing those required for the particular page.
If I compose the query manually then I can't figure out how to get TotalRecords back as a return parameter. Would appreciate help on this one.
Am hoping that stored procedures can cope with an unknown number of parameters.
View 3 Replies
View Related
Nov 7, 2007
Hello
I wonder if someone could suggest a way to obtain the following. Using SQL Server 2005 I want to create some stored procedures. I want to query the DB with various filter arguments and combinations of these. One way would be to create one stored procedure for each function signature. However, as the number of combinations of filter is large, if possible I'd rather have a generic input to the each stored procedure that corresponds to the entire WHERE clause' search condition.
The stereotype behavior I'm looking for is:
SELECT myField
FROM myTable
WHERE @mySearchCondition
Does any one have some good suggestion, code samples and/or links?
Kind regards
Jens Ivar
View 2 Replies
View Related
Oct 12, 2006
i have more tables
exmaple:
table1(id,title,content,date)
table2(did,type,title,text1,text2,requestdate)
table3(subid,value1,value2,value3,value4)
.......................15 tables left,some exmaple
now i want use stored procedure do search for asp.net
asp.net send search keyword to sql server,sql server get keywords execute search and return results to web application(asp.net)
i don't konw how what write t-sql,please friends help me.
because table colums is different,so need write t-sql put the temp DATA TO Temp DataTable,last return Temp DataTable to asp.net,asp.net execute split pager display data,eventable colums is different,so on asp.net links is different,need t-sql programming,hope friends can help me complete this effect(i need code,C#/VB.NET +T-SQL).
i at ago like this do.
<%@ Page Language="C#" ValidateRequest="false"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
private void page_init()
{
if (!IsSecure())
{
Response.Redirect("/sitemap/default.mspx?request=error&code=1065");
}
}
private void page_load(object sender, EventArgs e)
{
string CurrentPageValue = "";
string Qu = "";
Double PageValue = 0;
CurrentPageValue = Request.QueryString["PageN"];
Qu = Request.QueryString["QuKey"];
Qu = ReplaceStr(Qu);
if (Qu != null)
{
if (IsNumber(CurrentPageValue))
{
PageValue = Convert.ToDouble(CurrentPageValue.Trim());
Init_Data(PageValue,Qu);
}
else
{
PageValue = 1;
Init_Data(PageValue,Qu);
}
}
else
{
ExecuteError();
}
}
private void Init_Data(Double CurrentPage,string QuKey)
{
try
{
string ConStr = GetConnectionString();
string sql1 = "select id,title,date from table1 where title like '%" + QuKey + "%' order by date desc";
string sql2 = "select sid,type,title,content,date from table2 where type like '%" + QuKey + "%' or title like '%"+QuKey+"%' or content like '%"+QuKey+"%' order by date desc";
string sql3 = "select subid,text1,text2,date from table3 where text1 like '%" + QuKey + "%' or text2 like '%" + QuKey + "%' order by date desc";
string sql4 = "select RequestId,headIntro,HeadInfo,HeadCode,Text1,Text2,Text3,ItemText From table4 where headintro like '%" + QuKey + "%' or HeadInfo like '%" + QuKey + "%' or HeadCode like '%" + QuKey + "%' or text1 like '%" + QuKey + "%' or text2 like '%" + QuKey + "%' or text3 like '%" + QuKey + "%' or itemtext like '%" + QuKey + "%' order by date desc";
//expmale for test,i have 17 tables,so write some table do test
System.Data.DataTable ResultsTable = new System.Data.DataTable();
ResultsTable.Columns.Add("id", System.Type.GetType("Int32"));
ResultsTable.Columns.Add("title", System.Type.GetType("String"));
ResultsTable.Columns.Add("linkurl", System.Type.GetType("String"));
ResultsTable.Columns.Add("someIntro", System.Type.GetType("String"));
ResultsTable.Columns.Add("date", System.Type.GetType("DateTime"));
ResultsTable.Columns[0].Unique = true;
ResultsTable.Columns[0].AutoIncrement = true;
ResultsTable.Columns[0].AutoIncrementStep = 1;
ResultsTable.PrimaryKey = new System.Data.DataColumn[] { ResultsTable.Columns[0] };
System.Data.SqlClient.SqlConnection SearchConnect = new System.Data.SqlClient.SqlConnection(ConStr);
System.Data.SqlClient.SqlDataAdapter ada1 = new System.Data.SqlClient.SqlDataAdapter(sql1,SearchConnect);
System.Data.SqlClient.SqlDataAdapter ada2 = new System.Data.SqlClient.SqlDataAdapter(sql2, SearchConnect);
System.Data.SqlClient.SqlDataAdapter ada3 = new System.Data.SqlClient.SqlDataAdapter(sql3, SearchConnect);
System.Data.SqlClient.SqlDataAdapter ada4 = new System.Data.SqlClient.SqlDataAdapter(sql4, SearchConnect);
System.Data.DataSet Ds = new System.Data.DataSet();
SearchConnect.Open();
ada1.Fill(Ds, "table1");
ada2.Fill(Ds, "table2");
ada3.Fill(Ds, "table3");
ada4.Fill(Ds, "table4");
string ReTitle = "";
string ReUrl = "";
string ReIntro = "";
DateTime ReDate = System.DateTime.Now;
if (Ds.Tables[0].Rows.Count > 0)
{
for (int i = 0; i < Ds.Tables[0].Rows.Count; i++)
{
System.Data.DataRow TempRow;
TempRow = ResultsTable.NewRow();
ReTitle = Ds.Tables[0].Rows[1].ToString();
//url need check before count get detail
//for test temp defined
ReUrl = "url1";
ReIntro = Ds.Tables[0].Rows[1].ToString();
ReDate = Convert.ToDateTime(Ds.Tables[0].Rows[2]);
TempRow[1] = ReTitle;
TempRow[2] = ReUrl;
TempRow[3] = ReIntro;
TempRow[4] = ReDate;
ResultsTable.Rows.Add(TempRow);
}
}
if (Ds.Tables[1].Rows.Count > 0)
{
for (int i = 0; i < Ds.Tables[1].Rows.Count; i++)
{
System.Data.DataRow TempRow;
TempRow = ResultsTable.NewRow();
ReTitle = Ds.Tables[1].Rows[1].ToString();
//url need check before count get detail
//for test temp defined
ReUrl = "url2";
ReIntro = Ds.Tables[1].Rows[1].ToString();
ReDate = Convert.ToDateTime(Ds.Tables[0].Rows[2]);
TempRow[1] = ReTitle;
TempRow[2] = ReUrl;
TempRow[3] = ReIntro;
TempRow[4] = ReDate;
ResultsTable.Rows.Add(TempRow);
}
}
//........loop to table end
//................................
Ds.Dispose();
ada1.Dispose();
ada2.Dispose();
ada3.Dispose();
ada4.Dispose();
SearchConnect.Dispose();
if (SearchResults.Rows.Count > 1)
{
DisplayData(CurrentPage, QuKey, SearchResults);
}
else
{
SearchResults.Dispose();
ExecuteError();
}
}
catch
{
ExecuteError();
}
}
private void DisplayData(Double PageNumber, string Keywords, System.Data.DataTable CurrentData)
{
Double TotalPage = 0;
Double TotalRow = 0;
Double TempPage1 = 0;
decimal TempPage2 = 0;
int StartValue = 0;
int EndValue = 0;
int PageSize = 30;
TotalRow = CurrentData.Rows.Count;
TempPage1 = TotalRow/PageSize;
TempPage2 = Convert.ToDecimal(TotalRow / PageSize);
if (Convert.ToDouble(TempPage2 - TempPage1) > 0)
{
TotalPage = TotalRow / PageSize + 1;
}
else
{
TotalPage = TotalRow / PageSize;
}
if (TotalPage < 1) { TotalPage = 1; }
if (PageNumber > TotalPage) { PageNumber = TotalPage; }
if (PageNumber == TotalPage)
{
EndValue = TotalRow;
}
else
{
EndValue = PageNumber * PageSize;
}
StartValue = PageNumber * PageSize - PageNumber;
for (int j = StartValue; j < EndValue; j++)
{
System.Web.UI.WebControls.TableRow Tr = new TableRow();
System.Web.UI.WebControls.TableCell Td1 = new TableCell();
System.Web.UI.WebControls.TableCell Td2 = new TableCell();
System.Web.UI.WebControls.TableCell Td3 = new TableCell();
Td1.Controls.Add(new LiteralControl(CurrentData.Rows[j][1].ToString()));
Td2.Controls.Add(new LiteralControl(CurrentData.Rows[j][2].ToString()));
Td3.Controls.Add(new LiteralControl(CurrentData.Rows[j][3].ToString()));
Tr.Cells.Add(Td1);
Tr.Cells.Add(Td2);
Tr.Cells.Add(Td3);
SearchResults.Rows.Add(Tr);
}
System.Web.UI.WebControls.TableRow StateTr = new TableRow();
System.Web.UI.WebControls.TableCell StateTd = new TableCell();
StateTd.ColumnSpan = 3;
if (PageNumber - 1 > 0)
{
StateTd.Controls.Add(new LiteralControl("<a href=default.aspx?page=" + Convert.ToString(PageNumber - 1) + "&qu="+Keywords+">prev</a>"));
}
if (PageNumber !=TotalPage)
{
StateTd.Controls.Add(new LiteralControl("<a href=default.aspx?page=" + Convert.ToString(PageNumber + 1) + "&qu="+Keywords+">Next</a>"));
}
StateTr.Cells.Add(StateTd);
SearchResults.Rows.Add(StateTr);
CurrentData.Dispose();
SearchResults.Dispose();
//rows count > 200,runtime at 1.6 seconds left,
//rows count > 1000,runtime at 8 seconds left,
//rows count >10000,runtime at 12 seconds left
//execute speed is very bad,so i want use sql stored procedure search,but i don't write t-sql,hope friends hope me,thanks
}
private void ExecuteError()
{
SearchResults.Controls.Add(new LiteralControl("we're sorry,we unable find even contain your key data,please try other keywords.suppot to ...."));
SearchResults.Dispose();
}
private bool IsSecure()
{
if (!Page.Request.IsSecureConnection)
{
return true;
}
else
{
return false;
}
}
private bool IsNumber(string Restr)
{
try
{
if (Restr != null)
{
string TempStr = Restr.Trim();
if (TempStr != "")
{
System.Text.RegularExpressions.Regex MyTry = new Regex("@[0-9]*$");
if (MyTry.IsMatch(TempStr))
{
Double valueR;
Double = Convert.ToDouble(TempStr);
if (valueR >= 1 && valueR <= 10000)
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
else
{
return false;
}
}
else
{
return false;
}
}
catch
{
return false;
}
}
private string GetConnectionString()
{
try
{
string ConnectionString = "datasource=......,initial catalog=databasename,trusted_connection=yes;integrate security info=true;";
return ConnectionString;
}
catch
{
return "!";
}
}
private string ReplaceStr(string k)
{
try
{
if (k != null)
{
string r = k.Trim();
if (r != "")
{
r = r.Replace("~", "");
r = r.Replace("!", "");
r = r.Replace("@", "");
r = r.Replace("#", "");
r = r.Replace("$", "");
r = r.Replace("%", "");
r = r.Replace("^", "");
r = r.Replace("&", "");
r = r.Replace("*", "");
r = r.Replace("(", "");
r = r.Replace(")", "");
r = r.Replace("\", "");
r = r.Replace("|", "");
r = r.Replace("[", "");
r = r.Replace("]", "");
r = r.Replace("{", "");
r = r.Replace("}", "");
r = r.Replace(":", "");
r = r.Replace(";", "");
r = r.Replace("'", "");
r = r.Replace("", "");
r = r.Replace("<", "");
r = r.Replace(">", "");
r = r.Replace("!", "");
r = r.Replace(",", "");
r = r.Replace(".", "");
r = r.Replace("?", "");
r = r.Replace("/", "");
r = r.Trim();
return r;
}
}
else
{
return "";
}
}
catch
{
return "";
}
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Do Search SQL Server Page</title>
</head>
<body>
<asp:Table runat="server" ID="SearchResults">
</asp:Table>
</body>
</html>
MyTest:
SQL SERVER 2005+WINDOWS SERVER 2003+.NET 2.0
View 3 Replies
View Related
Sep 7, 2007
I need to create a stored procedure that allows a full text search with multiple filters. The FTS is a three variable proximity (x near y near z) drawing from three textboxes which works fine in my VB application:
WHERE CONTAINS(SectionText, ' """ & SearchTerm1 & """ NEAR """ & SearchTerm2 & """ NEAR """ & SearchTerm3 & """ ')
The filters consist of 4 comboboxes and 2 textboxes. I am trying to use the dynamic SQL approach found here:
http://www.sommarskog.se/dyn-search.html
The dynamic SQL in the stored procedure that I have created based on this model works fine for filtering, but I have not been able to get my FTS query integrated with it. I have tried various ways of declaring the SearchTerms as parameters, etc. but no luck.
Any help in getting this to work (or advice for using a different approach that is more appropriate) would be greatly appreciated.
Code Snippet
CREATE PROCEDURE ECR_Advanced_Search2
@fulldocno nvarchar(10) = NULL,
@doctype nvarchar(10) = NULL,
@year nvarchar(6) = NULL,
@sex nvarchar(7) = NULL,
@category nvarchar(10) = NULL,
@agenum smallint = NULL,
@agecat nvarchar(10) = NULL,
@debug bit = 0 AS
DECLARE @sql nvarchar(4000),
@paramlist nvarchar(4000),
@searchterm1 nvarchar(100),
@searchterm2 nvarchar(100),
@searchterm3 nvarchar(100)
SELECT @sql =
'SELECT FullDocuments.FullDocNo, FullDocuments.DocType, Details.Year
FROM FullDocuments
INNER JOIN Details ON FullDocuments.FullDocNo = Details.FullDocNo
WHERE 1 = 1 AND CONTAINS(SectionText, @searchterm1 NEAR @searchterm2 NEAR @searchterm3)'
IF @fulldocno IS NOT NULL
SELECT @sql = @sql + ' AND FullDocuments.fulldocno = @xfulldocno'
IF @DocType IS NOT NULL
SELECT @sql = @sql + ' AND FullDocuments.DocType = @xDocType'
IF @year IS NOT NULL
SELECT @sql = @sql + ' AND Details.year = @xyear'
IF @sex IS NOT NULL
SELECT @sql = @sql + ' AND Details.sex = @xsex'
IF @category IS NOT NULL
SELECT @sql = @sql + ' AND Details.category = @xcategory'
IF @agenum IS NOT NULL
SELECT @sql = @sql + ' AND Details.agenum = @xagenum'
SELECT @sql = @sql + ' ORDER BY FullDocuments.FullDocumentID'
IF @debug = 1
PRINT @sql
SELECT @paramlist =
'@xfulldocno nvarchar(10),
@xdoctype nvarchar(10),
@xyear smallint,
@xsex nvarchar(7),
@xcategory nvarchar(10),
@xagenum smallint,
@xagecat nvarchar(10)'
EXEC sp_executesql @sql, @paramlist, @doctype,
@fulldocno, @year, @sex,
@category, @agenum, @agecat
View 7 Replies
View Related