I want to perform a small SQL server search in my ASP.NET web project. My database is not big so I think it's better not to use full-text-search.
I want to perform a simple search like this:
select * from mytable where columnA LIKE '%something%'
I can use = in the following way:
select * from mytable where columnA='"+myVariable+"'
but how can I use a variable instead of %something% in the LIKE phrase?
Is this correct:
LIKE '"+%myVariable%+"'?
Use:
where columnA LIKE '%' + myVariable + '%'
WHERE
columnName LIKE '%' + myVarCharVariable +'%'
Try this query:
select * from tablename where colname like '%' + #varname + '%'
Hope it helps.
I just tried this and found you can do as below:
SELECT * FROM whatever WHERE column LIKE '%'+#var+'%'
DECLARE #myVariable varchar(MAX)
SET #myVariable = 'WhatYouAreLookingFor'
SELECT * FROM mytable
WHERE columnA LIKE '%' + #myVariable + '%'
In case someone else stumbles into this post like I did. On SSMS 2012 with a SQL 2012 Server back end I was able to use code as follows without issues.
Declare #MyVariable
Set #MyVariable = '%DesiredString%'
Select *
From Table_A
Where Field_A like #MyVariable
Then each time you want to change the Desired String just change it at the Set statement.
I know this post was made prior to 2012 that is why I am mentioning it in case someone with a newer setup looks up this post.
Well you could do something like:
var query = "SELECT * FROM MyTable WHERE columnA LIKE '%" + myVariable + "%'";
If you are worried about sql injection, try something like this instead. It's more complex, but it works and should satisfy security requirements. Let's say someone passed a value into your stored procedure using a parameter called "#searchstring".
DECLARE #searchString nvarchar(100) = 'test',
#SQL nvarchar(max),
#foundSearchHit bit,
#paramdef nvarchar(max) = '#foundSearchHit bit OUTPUT'
SET #searchstring = '%' + #searchString + '%'
SET #SQL = '
SELECT TOP 1 #foundSearchHit = 1
FROM sys.databases WHERE [name] like ' +
QUOTENAME(#searchString,'''')
EXEC sp_executeSQL #SQL, #paramdef, #foundSearchHit = #foundSearchHit OUTPUT
SELECT #foundSearchHit
That should do the trick.
Related
I'm trying to use AND operator in a variable and use it in the WHERE clause. I'm trying to do this without using Dynamic SQL. i.e without assigning the whole query to a variable.
DECLARE #v_Criteria varchar(500)
DECLARE #jobtype varchar(500) = 'test Job'
IF #inparam ='Report1'
BEGIN
SET #v_Criteria= ''
END
ELSE IF #inparam='Report2'
BEGIN
SET #v_Criteria= ' AND InvoiceValue IS NOT NULL'
END
SELECT *
FROM tblJobs
WHERE JobID NOT IN (63,87,469)
AND JobType LIKE '%' + #jobtype + '%'
+ #v_Criteria
I used + operator before the #v_Criteria and then I get no results. If I use & opertor before #v_Criteria, I get a error. Any help would be greatly appreciated
You can't append a "string" to a query and it become part of the code. It's still just a string. Essentially you're trying to do Dynamic SQL, but then say you don't want Dynamic SQL?
One option is to build the logic for both cases in SQL...
SELECT *
FROM tblJobs
WHERE JobID NOT IN (63,87,469)
AND JobType LIKE '%' + #jobtype + '%'
AND (
(#inparam ='Report1')
OR
(#inparam ='Report2' AND InvoiceValue IS NOT NULL)
)
This means that the query planner has to cope with both cases all the time. One plan to solve both cases. That saves you typing, but can mean that you get a poor execution plan and waste resources or execution time.
To get around that you need two queries...
IF (#inparam = 'Report1')
BEGIN
SELECT *
FROM tblJobs
WHERE JobID NOT IN (63,87,469)
AND JobType LIKE '%' + #jobtype + '%'
END
ELSE IF (#inparam = 'Report2')
BEGIN
SELECT *
FROM tblJobs
WHERE JobID NOT IN (63,87,469)
AND JobType LIKE '%' + #jobtype + '%'
AND InvoiceValue IS NOT NULL
END
Or just use Dynamic SQL...
SET #sql= 'SELECT *
FROM tblJobs
WHERE JobID NOT IN (63,87,469)
AND JobType LIKE ''%''' + #jobtype + '%''' + #v_Criteria
EXEC sp_executesql #sql
Or...
SET #sql= 'SELECT *
FROM tblJobs
WHERE JobID NOT IN (63,87,469)
AND JobType LIKE ''%'' + #jobtype_param + ''%''' + #v_Criteria
EXEC sp_executesql
#sql,
N'#jobtype_param varchar(500)',
#jobtype_param = #jobtype
(The benefit here is that you won't make a new cached query plan for every #jopbtype. Instead it makes a parameterised query plan and re-uses it.)
EDIT:
Basically what you're investigating is Dynamic Search.
If it ever gets more complex than this example, I strongly recommend reading this article : http://www.sommarskog.se/dyn-search.html
It's complicated, and in depth, and you'll learn a lot of valuable lessons.
Before adding " AND " if you check if #v_Criteria is not empty string then you will not get any error.
So split AND from for example " AND InvoiceValue IS NOT NULL"
Then add AND or not according to the value of the #v_Criteria
What about this solution?
DECLARE #v_Criteria varchar(500)
DECLARE #jobtype varchar(500) = 'test Job'
IF #inparam ='Report1'
BEGIN
SET #v_Criteria= ''
END
ELSE IF #inparam='Report2'
BEGIN
SET #v_Criteria= ' AND InvoiceValue IS NOT NULL'
END
SELECT *
FROM tblJobs
WHERE JobID NOT IN (63,87,469)
AND JobType LIKE '%' + #jobtype + '%'
AND ISNULL(InvoiceValue, '') NOT LIKE CASE
WHEN #inparam = 'Report2'
THEN ''
ELSE 'SOMEIMPOSSIBLEVALUE'
END
why this work :
SELECT * FROM Companies WHERE CompanyCode LIKE '%' AND BusinessUnitShortName LIKE 'CO%'
while mean this not work :
DECLARE #WHERECondition NVARCHAR(200) = ''
SET #WHERECondition = '''%'' AND BusinessUnitShortName LIKE ''CO%'''
SELECT * FROM Companies WHERE CompanyCode LIKE #WHERECondition
SELECT #WHERECondition
To make that work you need to use the dynamic sql like
DECLARE #WHERECondition NVARCHAR(200) = ''
SET #WHERECondition = '''%'' AND BusinessUnitShortName LIKE ''CO%'''
declare #sql nvarchar(Max)
Set #sql='SELECT * FROM Companies WHERE CompanyCode LIKE'+#WHERECondition
exec sp_executesql #sql
If you are not using the dynamic sql then you need to provide the column names as the SQL parser will look for the columns at the time when it is parsing the query and if not found will result in error.
You'd need to use dynamic SQL to achieve what you want. Your current method gets evaluated to something like this:
SELECT *
FROM Companies
WHERE CompanyCode LIKE '''%'' AND BusinessUnitShortName LIKE ''CO%'''
What you actually want is more like this:
DECLARE #sql NVARCHAR(MAX) = ''
DECLARE #WHERECondition = '''%'' AND BusinessUnitShortName LIKE ''CO%'''
SET #sql = 'SELECT * FROM Companies WHERE CompanyCode LIKE ' + #WHERECondition
EXEC(#sql);
which would evalute to:
SELECT * FROM Companies WHERE CompanyCode LIKE '%' AND BusinessUnitShortName LIKE 'CO%'
Dont know whether we can add if or case inside where condition .
I am trying to convert a dynamic query in to simple query
Declare #sQuery varchar(20000)
set #sQuery=''
set #sQuery ='select * from #tb_user ud'
if(#Number<>'')
set #sQuery = #sQuery + 'and upper(ud.ID) like ''' + upper(#Number) + '%'''
if(#Name<>'')
set #sQuery = #sQuery + 'and upper(ud.FName) like ''' + upper(#Name) + '%'''
Exec(#sQuery )
Note :
The below given query is just an example i have put off where i am not getting how to handle the if condition in simple query.(Actual query has a lot of things)
Thanks in advance for any help
Seems that you only want to use a specific filter (#Number or #Name) if it's not empty:
SELECT
*
FROM
#tb_user ud
WHERE
(#Number = '' OR upper(ud.ID) like upper(#Number) + '%')
AND
(#Name = '' OR upper(ud.FName) like upper(#Name) + '%')
You will have to group each test in a OR construct with the parameter being empty (or whatever check -inverted- you do in the if)..
SELECT
*
FROM
#tb_user ud
WHERE
(#Number = '' OR upper(ud.ID) like upper(#Number) + '%')
AND
(#Name = '' OR upper(ud.FName) like upper(#Name) + '%')
thanks go to #bartosz for spotting an error in the initial answer logic
Im using Microsoft SQL Server which I think is T-SQL or ANSI SQL.
I want to search a database with a string. The matches that fit the begging of the string should come first then sort alphabetically.
I.e. If the table contains FOO, BAR and RAP
a search for the string 'R' should yield:
RAP
BAR
In that order.
Here is my attempt:
SELECT Name
FROM MyTable
WHERE (Name LIKE '%' + #name + '%')
ORDER BY (IF(Name LIKE #name + '%',1,0))
The error message is: "must declare scalar variable #name"
declare #name varchar(10)
set #name='R'
SELECT Name
FROM (select 'foo' as name union select 'RAP' union select 'BAR') MyTable
WHERE (Name LIKE '%' + #name + '%')
ORDER BY charindex(#name ,name)
.
DECLARE #name VARCHAR(MAX);
SET #name = 'foo';
SELECT Name
FROM MyTable
WHERE Name LIKE '%' + #name + '%'
ORDER BY CASE WHEN Name LIKE #name + '%' THEN 1 ELSE 0 END;
Other solutions seem to miss the "sort alphabetically" part:
DECLARE #Search VARCHAR(MAX)
SET #Search = 'R'
SELECT 0, Name
FROM MyTable
WHERE Name LIKE #Search + '%'
UNION ALL
SELECT 1, Name
FROM MyTable
WHERE Name like '%_' + #Search + '%'
ORDER BY 1, 2
Seems that you missed variable declaration:
DECALRE #name varchar(50) -- adjust type and length of variable
SET #name = 'phrase' -- for MSSQL 2008 you can do it in one line
Hi I want to create a simple stored proecudre which does the following:
Psudocode
#tempSelect = "SELECT * FROM Table"
if (#Param is NULL) then
exec #tempSelect
else
exec #tempSelect + ' WHERE id = ' + #Param + '
Is this method efficent? Thank you.
Try
select *
from table
where id=isnull(#param, id)
Select * from Table
Where (ID = #Param or #Param is null)
Or
Select * from Table
Where ID=Coalesce(#Param, ID)
[And if you are aiming for efficiency, replace * with the specific field you want to return.]
Yes - I certainly see nothing wrong with it. You could make it even simpler though:
Set NOCOUNT On;
if (#Param is NULL)
Select * From Table;
else
Select * From Table Where (ID=#Param);
Note: I'd probably spell out the fields, though.
Depending on the case, I would probably use dynamic SQL.
However you need to remember about SQL injection in case #param originates from a user, thats why you should never add a parameter directly to your sql.
In t-sql it would look something like (out of my head and untested ;):
DECLARE #SQL NVARCHAR(MAX)
SET #SQL = N'
SELECT ...
FROM table t
WHERE 1 = 1' (
IF(#param IS NOT NULL)
SET #SQL = #SQL + '
AND t.id = #id'
... possibly more things added to the query ...
EXEC sp_executesql
#SQL
, '#id AS INT'
, #id = #Param
By doing this, you will get an optimized query plan for each case (and by using sp_executesql, the query cache will be used as well)
I would especially avoid the OR solution, if you check the query plans generated with the OR compared to one without, you will understand why.
Try this code:
CREATE PROCEDURE [dbo].[ProcedureName]
#Param varchar(50)
AS
BEGIN
declare #tempSelect nvarchar(max)
SET NOCOUNT ON;
set #tempSelect = 'SELECT Col1, Col2 FROM Table where Col1 <> '' '
if #Param <> ''
begin
set #resultSet = #resultSet + ''' and Col1='''+#Param1
end
EXEC(#resultSet)
END