Wildcard Column Selection?
Sep 21, 2007Is it possible to have some thing like:
SELECT columns beginning with 'a' from mytable
kinda thing?
Is it possible to have some thing like:
SELECT columns beginning with 'a' from mytable
kinda thing?
I was looking for a way to use a wild card on a date column, but could only convert the file first then use the wildcard Is there another way of conducting the wild card search on a date column without conducting a conversion on the specified column? Sybase has the ability to use a wildcard on the datetime column so I would assume SQL SERVER does too.... Right? I can see that there are some workaround to get the information I need . I have conducted multiple searches and I still cannot find a suitable answer. Anyway, below is some links where I received some of the information:
[URL] ....
Hi All,
I have a company table with CompanyName and Address details.
In the Company Name field - I have got companies with names like - 'The 1% Club', '99% Pure Water', 'The 1% Golfer' etc...
I want to search for Companies with % using the LIKE clause - Say for ex.
SELECT CompanyName from Company WHERE CompanyName LIKE 'The 1%%'
I was expecting the above query to return - All Companies starting with 'The 1%' - So from the above list - I expected it to return - 'The 1% Club' and 'The 1% Golfer'.
Unfortunately the query isn;t accepting % in the WHERE LIKE clause except for the wildcard character.
Is there a way out to escape the Wildcard Characters present in the Field Values while searching.
Thanks,
Loonysan
Is it possible to do a wildcard search on an encrypted column?
Many thanks!
I have a table containing records of criminal convictions. There are over 1M records and the only change is additions to the table on a monthly basis. The two columns I need to deal with are convicted.NAME and convicted.DOB
I have a second table that has 2 columns. One is the name of the defendant and the other is the birth date. This would be monitor.NAME and monitor.DOB
There are no primary keys or any other way to join the tables for this search I want to do.
I would like to be able to put a name in the "monitor" table and run a query to see if there is a match in the convicted table.
The problem I am having is middle initials or names. If I want to monitor.name = 'SMITH JOHN' it will return the results fine. The problem I am having is if the conviction is in the database as 'SMITH JOHN T', or 'SMITH JOHN THOMAS'.
How can I use the monitor table with a 'LASTNAME FIRSTNAME' and return results if the convicted table has a middle initial. I tried with a JOIN:
select distinct convicted.*
from convicted
join monitor
on monitor.name like convicted.defendant
and monitor.birthdate = convicted.dob
suppose i have a table penalties with
ticket_number, ticket_start_date datetime, ticket_end_date datetime
There are many records of same ticket_number.example:
ticket_number ticket_start_date ticket_end_date
75 2/1/03 3/2/03
75 2/4/03 5/4/03
34 2/1/03 3/3/04
34 3/4/04 3/3/05
I want to write a query which will:
1. select the ticket_number which is not active as of today
in case of ticket_number 75 it is closed so I want to print it in report
in case of 34 it was closed but now opened, so i don't want in my report.
Could anybody suggest a query how to do it?
I was trying with stored procedure and cursor :
-------------------------------------
CREATE PROCEDURE simpleTest
AS
declare @Today datetime
set @Today = '10/04/2004'
declare @colA varchar(38)
declare @colB datetime
declare @colC datetime
declare @myCursor CURSOR
set @myCursor = CURSOR FAST_FORWARD
for
select distinct ticket_number, ticket_start_date, ticket_end_date
from penalties
where ticket_end_date <= @Today
open @myCursor
fetch next from @myCursor
into @colA, @colB, @colC
while @@fetch_status=0
begin
print @colA
print @colB
print @colC
fetch next from @myCursor
into @colA, @colB, @colC
end
close @myCursor
deallocate @myCursor
GO
-- =============================================
-- example to execute the store procedure
-- =============================================
EXECUTE simpleTest
GO
-------------
however this gives closed tickets but multiple records. I want only the last record details of the ticket_number.
I tried last(ticket_number) in my query, but it doesn't affect.
Please suggest! thanks.
I am using MS SQL server.
I have one table with 6 columns (Entrance1,Exit1,Entrance2,Exit2,Entrance3,Exit3).
This columns can take null values.
I want to select just the last one of this columns that is not null.
Hi,
I have to choose a particular column from a table whenever a condition met. That means i have to use the column in the select query whenever the condition met otherwise i have to create a dummy column with the same column name.
I tried to use the following sample query.
Eg:
Create table temp
(test_id int,
test varchar(100))
Declare @var varchar(100)
Set @Var='Hi'
Select
case when @Var='HI' then "None" else Test_new End as Test
from Temp
But it throw error as "Invalid column 'Test_new' "
As per my situation the Test_new column will be available in temp table whenever the condition is not met.So when @var<>'HI' i have to get the details of the test_new column otherwise i have to create a dummy column with the same name.
Hey, I have a search form with a selectbox. This selectbox contains the columnnames.I want when I put a text in a textbox and select a value in the selectbox and click submit that it search database.The Columnnames I put in a session.
If you see I have put in the querystring as columnname @sescolumn which I have initialised as asp:sessionparameter.But it gives no results. When I put @sescolumn between [] like normal columnnames are it doesn't work also.
Can someon put my on the right path?
<asp:SqlDataSource ID="Database_ecars" runat="server" ConnectionString="<%$ ConnectionStrings:connectionstring %>"
SelectCommand="SELECT [AutoID], [Merk], [Kleur], [Type], [Autotype], [prijs], [Zitplaatsen], [Afbeelding1], [Afbeelding2], [Afbeelding3], [Afbeelding4] FROM [Auto] where @sescolumn like @seskeyword and [AutoID] not in (select [AutoID] from [verhuring] where [StartVerhuur] >= @sesdatefrom and [Eindeverhuur] <= @sesdatetill)" >
<SelectParameters>
<asp:SessionParameter Name="sesdatefrom" SessionField="datefrom" Type="Decimal" />
<asp:SessionParameter Name="sesdatetill" SessionField="datetill" Type="Decimal" />
<asp:SessionParameter Name="seskeyword" SessionField="keyword" Type="string" />
<asp:SessionParameter Name="sescolumn" SessionField="columnname" Type="string" />
</SelectParameters>
</asp:SqlDataSource>
Hey Guys,
Here is the issue I'm having. I am writing a stored procedure that takes a couple of parameters. Each one is the value within a specific column in one table (i.e., @part = 'o-ring' or @sub_assembly = 'hydraulic ram'). Needless to say, the columns form a hierarchy. What I am trying to achieve is to allow the user to specify one of the parameters and get a count for all records where the specified value is in the corresponding column. So, if the user puts in the parameter @part = 'o-ring', I want it to know that the where clause for the select statement should look for o-ring in the part column and not the sub_assembly column. Here is what I am trying to do, which isn't working.
DECLARE @querycolumn varchar(20),
@queryvalue varchar(35)
SET @querycolumn = ''
SET @queryvalue = ''
IF(@sub_assembly = NULL)
BEGIN
IF(@part = NULL)
BEGIN
PRINT 'This is an error. You must have at least a part'
END
ELSE
BEGIN
SET @querycolumn = 'Part'
SET @queryvalue = @part
END
END
ELSE
BEGIN
SET @querycolumn = 'SubAssembly'
SET @queryvalue = @sub_assembly
END
SELECT SubAssembly, Part, COUNT(RecordID)
FROM Table
WHERE @querycolumn = @queryvalue
GROUP BY SubAssembly, Part
ORDER BY SubAssembly, Part
The problem is that I'm getting an error when I try to use @querycolumn to supply the column name to the WHERE clause. Any ideas or suggestions?
Consider the below code: I am trying to find a way so that my select statement (which will actually be used to insert records) can randomly place values in the Source and Type columns that it selects from a list which in this case is records in a table variable. I dont really want to perform the insert inside a loop since the production version will work with millions of records. Anyone have any suggestions of how to change the subqueries that constitute these columns so that they are randomized?
SET NOCOUNT ON
Declare @RandomRecordCount as int, @Counter as int
Select @RandomRecordCount = 1000
Declare @Type table (Name nvarchar(200) NOT NULL)
Declare @Source table (Name nvarchar(200) NOT NULL)
Declare @Users table (Name nvarchar(200) NOT NULL)
Declare @NumericBase table (Number int not null)
Set @Counter = 0
while @Counter < @RandomRecordCount
begin
Insert into @NumericBase(Number)Values(@Counter)
set @Counter = @Counter + 1
end
Insert into @Type(Name)
Select 'Type: Buick' UNION ALL
Select 'Type: Cadillac' UNION ALL
Select 'Type: Chevrolet' UNION ALL
Select 'Type: GMC'
Insert into @Source(Name)
Select 'Source: Japan' UNION ALL
Select 'Source: China' UNION ALL
Select 'Source: Spain' UNION ALL
Select 'Source: India' UNION ALL
Select 'Source: USA'
Insert into @Users(Name)
Select 'keith' UNION ALL
Select 'kevin' UNION ALL
Select 'chris' UNION ALL
Select 'chad' UNION ALL
Select 'brian'
select
1 ProviderId, -- static value
'' Identifier,
'' ClassificationCode,
(select TOP 1 Name from @Source order by newid()) Source,
(select TOP 1 Name from @Type order by newid()) Type
from @NumericBase
SET NOCOUNT OFF
Hello everyone and thanks for your help in advance. I am working on an application that does a property search off of a database that contains approximately 40000 records. The search criteria allows the use to specify a minimum and maximum price, subdivision name, number of bedrooms, etc. I set up a stored procedure to query the databse. if one of the parameters is not specified, i simply pass it a "%". However, when i execute this sproc in Query Analyzer, it takes in excess of 10 seconds to return the records, even if only one or two are returned. I am assuming this is due to the use of the wildcard character when the user does not have a preference, but I am not sure of any other way to do this. Any help on this topic would be grealy appreciated.
View 3 Replies View Relatedhi,i have an sqldatasource a gridview and dropdownlistthe gridview is updated on the selectedIndexChanged Event of the dropdownlistmy goal is to add an item in the dropdownlist with the name ALLwhich should matches all the records in the databasei tried to put the value of the all item = * and % but neither seems to workany help on what could be going wrong would be appreciated
View 7 Replies View Relatedhi,
how do i contsruct a SQL query to search for the % character in a data field?
thanks
Is it a good idea to have multiple contains? I have this query:Select * from myTable where contains (Col1, 'Africa') or (Col2, 'Africa')Also, I tried this, didn't return anything:Select * from myTable where contains (Col1, 'Africa*') or (Col2, 'Africa')Both Col1 and Col2 has the string 'Africa' and 'African' in it.--sharif
View 2 Replies View Related
alter procedure sp_ADsearch @tbname varchar(1000),@searchproduct nvarchar(500)
as
declare @sqlstr nvarchar(1000)
set @sqlstr='select * from '
set @sqlstr= @sqlstr + @tbname
set @sqlstr= @sqlstr + ' where name like '
set @sqlstr= @sqlstr + '%' + @searchproduct + '%'
exec sp_executesql @sqlstr
--
exec sp_ADsearch product,ee
when executing the procedure i am getting an error "Incorrect syntax near 'ee'.".
whats wrong with the syntax? how to use % along with variables
I am trying to control how users view records. I want to create a solution that would, for instance permit:user A to view Store 1user B to view store 2 and store 3user C to view store 5 and store 6and User D to view all stores even if more stores were added in the future (in other words user D would have access to all records)
I want to create an 'authorization table' so that different users can see different records. I think the easiest way to do this is to pass a parameter to the where clause, but the problem that I face is the how can I use a wildcard in a SQL 'IN' clause? Does anyone have any suggestions. Perhaps I am taking the wrong approach. I would appreciate any guidance.
Hello,
I'm trying to pull some data from a table with the option to filter on 2 columns.
I've set up my sql statement to accept 2 parameters and I'd like to be able to send 1 or 2 wildcards if needed. My statement looks like this:SELECT *
FROM City WHERE CityName= @CityName AND State= @State
ORDER BY CityName
For example, if you wanted all of the cities in all of the states I would pass (*,*) as parameters.
Or if I wanted to see all of the states that have a city named Richmond, I'd pass (Richmond,*) as the parameters.
The wildcards are not returning anything and I don't know why. It works fine if I pass something like (Indianapolis,Indiana) as parameters so I think it's in my use of the wildcards that is wrong.
Thanks.
I'm writing a stored procedure where one of the arguments (WHERE area) really only needs to be used in some circumstances. I.e., when the procedure is passed a USER_ID it needs to check that against the database, but in some instances I'll send 0 instead of a real USER_ID, and in those cases it should return all records regardless of the ID.
Here's what I've got:
...
and b.user_ID = CASE @user_ID WHEN 0 THEN '%'
ELSE @user_ID
...
...the problem being the '%' part. That won't work on an integer column.
Does anyone have any ideas here?
Thanks,
Al
I've got a text field with a list of dates in this format:
10/31/2006
11/2/2006
11/4/2006
11/5/2006
The field can contain multiple dates (as listed above). I need to query the db and retrieve dates by month and year. For example, all fields containing 10/%/06 or 11/%/%06.
My query:
SELECT * FROM tblCalData WHERE visible='1' and approved='1' and eventDates LIKE '11%06%' ORDER BY eventDates DESC
so even though a field contains dates in October and November, selecting all November dates, in this example, don't appear. The query seems to be looking only at the first date.
Is this possible? Is there another/better way to do this?
Thanks!
:grimey
to reference columns.
i have a table that has a column that is repeated 25 times, sort of.
table_1
tbl_ID (PK)
tbl_c_1 char 5
tbl_c_2 char 5
tbl_c_3 char 5
tbl_c_4 char 5
tbl_c_5 char 5
....
tbl_c_25 char 5
everytime i want to query for any of tbl_c_? that contain a specific value i have to reference all 25 in my query. is there a better way?
I cannot change the table.
HI Guys, I have a question.
I am converting Access SQL to SQL Server. One of the statements calls for a wildcard if the user does not select a value for the designated parm field. The value is selected from a cbolist (of names).
Current Statement:
And tblRetailer_Contact.faxcontact LIKE *
I substituted:
And tblRetailer_Contact.faxcontact LIKE ‘%@faxContacts%’
This might work if the User selects a name but if the User leaves it blank it will not work. Any ideas on how I go about establishing a wildcard if not name is selected?
DECLARE @FaxContact as varchar (50)
SET @H_Date = (SELECT StartDate FROM tblRpt_Params WHERE RptID = 5)
SET @Start_Date = (REPLACE(REPLACE(CONVERT(VARCHAR (8), @H_Date, 112), '-', ''), ' ', ''))
SET @H_Date = (SELECT EndDate FROM tblRpt_Params WHERE RptID = 5)
SET @End_Date = (REPLACE(REPLACE(CONVERT(VARCHAR (8), @H_Date, 112), '-', ''), ' ', ''))
SET @FaxContact = (SELECT FaxContact FROM tblRpt_Params WHERE RptID = 5)
SELECT tblEData.Timestamp As [TimeStamp],
LTRIM(RTrim([ResultsCustName])) AS CustName,
LTRIM(RTrim([ResultsPH])) AS Phone, Status As [Status],
FaxContact AS FaxContact,
ResultsPKey As ResultsKey
INTO tmpE_Callbacks
FROM tblEData
LEFT JOIN tblContact
ON tblEData.RetailerPrefix = tblContact.Prefix
WHERE tblEData.Timestamp BETWEEN @Start_Date And @End_Date
AND FaxContact Like '%@FaxContact%'
Thanx so much,
Trudye
I screwed up my database and double added data to a text field.
For example I need made this:
'http://192.168.200.1/images/' +PATH+ '.jpg'
Look like this:
'http://192.168.200.1/images/http://192.168.200.1/images/12345.jpg'
How can I query to reset this?
update perimage
set PERIMAGE_PATH = 'http://192.168.200.1/images/' +PATH+ '.jpg'
WHERE PERIMAGE_PATH <> 'http://192.168.200.1/images/' +PATH+ '.jpg'
That just makes the problem worse
I want to update data only where the value of the 'image_path' column is NOT = 192.168.150.12/images/*
Im basically trying to exclude creating duplicates, where this path already exists.
Here is my code:
INSERT INTO IMAGE (FCN, IMAGE_NAME2)
SELECT FCN, Col066
FROM GRAB where Col066 <> ' '
update IMAGE
Set PERIMAGE_PATH = 'http://192.168.150.12/images/' +IMAGE_NAME2+ '.jpg'
FROM IMAGE WHERE image_name2 IS NOT NULL and perimage_path is NOT = 192.168.150.12/images/*
What is the proper code to do this. I know the last line does not work. Thanks
The where statement on my stored proc is as follows:
Where actv.ProjID + '-' + actv.Activity = @project
@project is something the user provides in the form of "xxxx-xx-xx-xx". I would like to use a wildcard, so I changed my where statement to the following:
Where actv.ProjID + '-' + actv.Activity = @project + '%'
But this returns nothing and I am not sure why. I don't get any errors, just no results. Anyone got any ideas as to why?
Thanks in advance!
Does SQL Server support wildcard Certificates. When you install the wild cert in the certificate store, the sql configuration manager does not see it in its drop down list. Id it does, what are the steps or please point me to the right direction. Does the cert need to be specifically for that particular hostname. Thanks
View 1 Replies View RelatedHi,
I have a problem with SQL CE 3.5 and VS 2005. When I execute query with parameters and wildcard, I have an error : FormatException.
Here is my query with parameters :
Query: SELECT "PARAGRAPHES"."PARA_ID" AS "Numero","PARAGRAPHES"."PARA_SECT_ID" AS "Section","PARAGRAPHES"."PARA_NUMERO" AS "Rang","PARAGRAPHES"."PARA_GROUPE" AS "Groupe","PARAGRAPHES"."PARA_ENTITES" AS "Entites","PARAGRAPHES"."PARA_LBL_COURT" AS "Court","PARAGRAPHES"."PARA_LBL_LONG" AS "Long","PARAGRAPHES"."PARA_ACTIVE" AS "Active","PARAGRAPHES"."PARA_CONDITIONS" AS "Conditions","PARAGRAPHES"."PARA_PARENTS" AS "Parents","PARAGRAPHES"."PARA_QUESTIONS" AS "QuestionsConditions" FROM "PARAGRAPHES" WHERE ( ( ( ( "PARAGRAPHES"."PARA_SECT_ID" = ? AND ( ( "PARAGRAPHES"."PARA_ENTITES" LIKE ?) OR "PARAGRAPHES"."PARA_ENTITES" IS NULL))) AND "PARAGRAPHES"."PARA_ID" IN (SELECT "DOSSIER_LINKS"."DOLI_PARA_ID" AS "Paragraphe" FROM "DOSSIER_LINKS" WHERE "DOSSIER_LINKS"."DOLI_DOSS_ID" = ?) AND "PARAGRAPHES"."PARA_NUMERO" = ?))
Parameter: @Section1 : Int32. Length: 0. Precision: 0. Scale: 0. Direction: Input. Value: 52.
Parameter: @Entites2 : String. Length: 3. Precision: 0. Scale: 0. Direction: Input. Value: "%D%".
Parameter: @Dossier3 : Int32. Length: 0. Precision: 0. Scale: 0. Direction: Input. Value: 1.
Parameter: @Rang4 : Int32. Length: 0. Precision: 0. Scale: 0. Direction: Input. Value: 2.
and my error :
[System.FormatException] = {"@Entites2 : %D% - FormatException"}
If I execute query in Query Analyzer (without parameter : values directly on query) there is no errors.
ThanksFabien
I have a number of functions that require the input of parameters in order to ultimatly create a report under Reporting Services by making use of a Stored Procedure.
All the functions etc work as does the stored procedure, but it only works if I specify data that I know exists e.g.
DECLARE @return_value int
EXEC @return_value = [dbo].[spWTRalldatareportsummary]
@dt_src_date = N'04/28/2006',
@chr_div = N'NE',
@vch_portfolio_no = 3,
@vch_prop_cat = N'core'
SELECT 'Return Value' = @return_value
GO
How can I set this so that it will wild card the value. For example rather than having to specify
@chr_div = N'NE', I could specify something like
@chr_div = N *, so it would show both NE and SW values in the result set.
Anybody point me in a direction here. I have tried % but that does not seem to work, I get a
Msg 102, Level 15, State 1, Line 7
Incorrect syntax near '%'.
Thank in Advance
I'm very new to SQL so please forgive my ignorance...
I've made a simple .net search page which queries an sql database with the following query, (in a stored procedure):
SELECT Category, Number, RegisteredUser, DeptName, Surname, Forename, Site, IDFROM tblTelephonesWHERE (@surname IS NULL OR Surname LIKE @surname) AND (@site IS NULL OR Site = @site) AND (@deptname IS NULL OR DeptName LIKE @deptname)
This works fine, as expected if i leave fields null or enter an exact match, but I (of course) have to add a wildcard in my search string for a wildcard search. For example, looking for 'duncan' i need to enter 'du%' or 'duncan'.
What I really want is for all searches to have wildcards behind them so only the first few characters need be inputted, and I could just search for 'd' or 'dun' without adding the '%' to get 'duncan'. I think I am aware of the implications of this approach and do want to go ahead as there are only about 850 records.
Any help or links to useful articles would really be greatly appreciated.
Hi all, I am currently using SQL Server 2000and am having some issues when searching a CHAR column and using the WildCard character '%'. The problem is that when I use this WildCard character, the results returned (if any!) are incorrect. For example, I know that there are many rows in the DB that have the following data in a column, 'ABERYSTWYTH CEREDIGION', but when I using the following SQL...'(WHERE (UPPER(AddrLine3) = 'ABERYSTWYTH%')' I get no results returned.Is there a known issue with the WildCard character in SQL Server 2000?ThanksTryst
View 3 Replies View RelatedI have a query with 4 parameters:
Name
Location
Employee Number
Officer Code
There are no null values in Name, location and Employee Number. However, all employees do not have an officer code. So in my query I use a where clause that says WHERE OfficerCode LIKE '%'+@Param4+'%'. I use a % for the default value in my ASP.net data control. The only problem is that the only records returned have non-null values in the OfficerCode field. How can I use a wildcard for a default value and return all records (null and non-null)?
Hi,
I have a problem using the LIKE operator in a stored procedure. I have simplified the script so that it runs in query analyser and still have the same problem. The script is:
DECLARE@FirstName varchar (50)
SELECT @FirstName = 'B%'
SELECT * FROM PhoneList
WHERE PhoneList.FirstName LIKE CASE @FirstName WHEN '' THEN PhoneList.FirstName ELSE @FirstName END
This code produces no rows in the result. However if I change the second line to:
SELECT @FirstName = 'Ben'
Then I get all of the rows with 'Ben' as the first name. If I change it to:
SELECT @FirstName = 'Be%'
Then I get all of the rows with three character first names beginning with 'Be'. If I change it to:
SELECT @FirstName = 'B%%'
Then I get all of the three character first names beginning with 'B'.
I need the conditional where so that if an empty string is passed it returns every row, which works fine as it is.
The % wildcard appears to be operating the same way as the _ wildcard. Has anyone seen this before?
This is SQL Server 2k SP3 on Win2003 server.
thanks
Ben
Hi,
I am writing a stored procedure to pull records from a table of personal data related to jobs applied for.
There are 3 tables involved, the jobs, the applicants and the applications.
I need to search on job title, job ref from the jobs table and on forename, surname and applicant ID from the applicants table.
There are some quirks here, if the user enters an applicant ID then we can simply scan the jobs table for that id where it also matches the job title wildcards, so that is quite easy to manage.
My own idea for the more complicated searches was to gather the unique ID's from the jobs table into a var, then do similar with the applicants and then search the applications table where both these ID's matched? I think that wouldn't work so well if using the 'WHERE IN()' clause for the main query?
So what approach would be best here to perform the second part of the SP if the client hasn't passed an ApplicantID?
Obviously the applications table has both JobID and ClientID's to relate back to the applicants table.
So can anyone help here, it seems a fairly complicated statement or set of statements would be required here.
Thanks in advance.