This returns 110 results:
select *
from regions
where sponsor like '%'
This returns zero results and should return 110 records:
declare #sponsor char(4)
set #sponsor = '%'
select *
from regions
where sponsor like #sponsor
You are using a CHAR(4), it means that when you do:
declare #sponsor char(4)
set #sponsor = '%'
The actual value of sponsor is '% '. Either use CHAR(1) or VARCHAR(4)
char types are padded with whitespace. Your second query is actually equivalent to this:
select * from regions where sponsor like '% '
Make #sponsor a char(1) or a varchar(4).
Related
declare #Datos Varchar(80)
set #Datos='Llactas'
Select IdCliente,DNI,ApellidoPat,ApellidoMat,Nombre1,Nombre2,Direccion,Telefono
From Cliente Where ApellidoPat like '%#Datos%'
After run show that result
Use
declare #Datos Varchar(80)
set #Datos='Llactas'
Select IdCliente,DNI,ApellidoPat,ApellidoMat,Nombre1,Nombre2,Direccion,Telefono
From Cliente Where ApellidoPat LIKE '%' + #Datos + '%'
Your
like '%#Datos%'
is trying to search "#Datos" in your table
I want to write a stored procedure in order to filter some columns in which some of them might be NULL or not. code below is mine, but it does not work.
procedure .[s p_organization](#expert nvarchar(100),
#name nvarchar(100), #last_name nvarchar(200),
#organization n varchar(200) )
where
((Person.expert LIKE #expert or Person.expert LIKE #expert)
and (is null(l trim(r trim #last_name)),'')=''
or person.last_name like #last_name + '%'
and Person.Name LIKE #name
or #name is null
and Organization.Name LIKE N'%'+#organization +'%' )
Add ( ) when using or and and mixed:
A AND B OR C will return C totally independent of A AND B.
A AND (B OR C) will returnA AND BorA AND C` (depending on the content of the data
In your case:
((Person.expert LIKE #expert or Person.expert LIKE #expert)
and ((is null(l trim(r trim #last_name)),")="
or person.last_name like #last_name + '%')
and (Person.Name LIKE #name
or #name is null )
and Organization.Name LIKE N'%'+#organization +'%' )
might work better (you need to tune it for your own purposes and results
I want to make a search sql query to find a name where contain the string that users input. It is something like the query below, but I don't know how to make the 'where' part. I have been looking in google but I still can't find the right one.
DECLARE #string varchar(20)
SELECT #string = 'test complete name'
SELECT complete_name from users
where complete_name like '%test%'
or complete_name like '%complete%'
or complete_name like '%name%'
or complete_name like '%test complete%'
or complete_name like '%test name%'
or complete_name like '%complete name%'
or complete_name like '%test complete name%'
Create a function like below that splits the given string and returns the individual words from given input
Create function fn_stringSplit(#StringSplit varchar(max))
returns #table table(SplitValue varchar(10) not null)
as
begin
Declare #StartVal int
Declare #endVal int
set #StringSplit = #StringSplit + ' '
set #StartVal = 1
set #endVal = 1
while #endVal >= 0
begin
set #endVal = charindex(' ',#StringSplit,#StartVal);
insert into #table select SUBSTRING(#StringSplit,#StartVal,#endVal-1)
set #StringSplit= SUBSTRING(#StringSplit,#endVal+1, LEN(#StringSplit))
if #StringSplit = '' set #endVal= -1
end
return
end
Now call our function in the main query by passing the input
DECLARE #string varchar(20)
SELECT #string = 'Marketing tool designer'
SELECT JobTitle from Employee e
where JobTitle in (select e.JobTitle from fn_stringSplit(#string) ss
where e.JobTitle like '%'+SplitValue+'%') --Here Splitvalue is the column name in the table that is returned by fn_stringSplitfunction
in SQL SERVER 2016 we have a function String_Split we can write query as
DECLARE #string varchar(20)
SELECT #string = 'Marketing tool designer'
SELECT JobTitle from Employee e
where JobTitle in (select e.JobTitle from String_Split(#string) ss
where e.JobTitle like '%'+Value+'%') --Here **value** is the column name in the table that is returned by **String_Split**
you can create function to split you string into temp table of word. then then use in query.
To create function you can follow the link T-SQL split string
DECLARE #string varchar(20)
SELECT #string = 'test complete name'
SELECT complete_name from users
where complete_name in (dbo.splitstring(#string))
Take care of two things
1) Reference link uses comma separator, you will need space
2) in query will do exact search. You will need to write some more logic for like query. e.g. Pass your column value "complete_name" in created function. use like comparison inside function and return 1 Or 0. So, where will become
DECLARE #string varchar(20)
SELECT #string = 'test complete name'
SELECT complete_name from users
where 1 = dbo.test_complete_name(#string,complete_name)
Below is a method, which won't require any hard coding or creation of any additional function. I have tried describing it in different steps for easier understanding.
DECLARE #string varchar(20) ,#stringxml xml,#rowvalue varchar(20)
SELECT #string = 'test complete name'
--Convert the string to an xml
Select #stringxml=CAST(('<a>'+replace(#string,' ','</a><a>')+'</a>' )as xml)
--Split the xml to rows based on each word.i.e. each word to one row using nodes()
select Row_values.value('.' ,'varchar(max)')
AS StringValues
FROM
#stringxml.nodes('/a') As StrXml(Row_values)
The above query returns a table with rows having each word.This table can joined with your table to do the required search.
The below query is what you need as a final answer
DECLARE #string varchar(20) ,#stringxml xml,#rowvalue varchar(20)
SELECT #string = 'test complete name'
--convert string to xml
Select #stringxml=CAST(('<a>'+replace(#string,' ','</a><a>')+'</a>' )as xml)
--Inner join your table to the value from nodes
Select DISTINCT Urtbl.[ColName] from [YourTableName] Urtbl inner join(
select Row_values.value('.' ,'varchar(max)')
AS StringValues
FROM
#stringxml.nodes('/a') As StrXml(Row_values)) newtbl
on Urtbl.[ColName] like '%'+newtbl.StringValues+'%'
In table, 2 fields ID as int and Number as small int and i want to concatenate the two fields and display as string
eg: ID = 101 and Number = 9
output : 101.9
Dot to be added in between ID and Number?
How to query in SQL?
You can CAST your integer field to varchar and then concatenate them as you want.
DECLARE #ID INT
DECLARE #Number INT
SET #ID = 101
SET #Number = 9
SELECT CAST(#ID AS VARCHAR(10) ) +'.'+ CAST(#Number AS VARCHAR(10) )
In SQL 2012 (and later) I now find this easier using CONCAT (better performance too)
SELECT CONCAT(#ID, '.', #Number)
any NULL elements are converted to empty-strings preventing NULL propagation, which saves having to do the even more complex:
SELECT ISNULL(CAST(#ID AS VARCHAR(10) ), '') +'.'+ ISNULL(CAST(#Number AS VARCHAR(10) ) , '')
I am building a query for a search in MS SQL 05
i have 4 things the user can select, and i want to use AND logic on it.
but i can't seem to get it to work when NULLs are being passed in.
this is what i have:
ALTER PROCEDURE [dbo].[sp_FindSource]
-- Add the parameters for the stored procedure here
#Code varchar(500),
#ssid varchar(50),
#serialNo varchar(50),
#category decimal(10,5)
as begin
SELECT *
FROM tblSource
WHERE Code IN (
SELECT Value
FROM funcListToTableInt(#Code,',')
)
and SSID LIKE '%' + #ssID + '%'
and serialNo LIKE '%' + #serialNo + '%'
and category = #category
end
NOTE: funcListToTableInt function, parses comma seporated values passed in (it works by itself, if i take the other where statements out)
The above search never returns anything, how can i ignore values if they are passed in black and only query the ones that have something in them? uuggh, it's been killing me.
You just have to wrap some OR #param IS NULL checks around your WHERE conditions:
ALTER PROCEDURE [dbo].[sp_FindSource]
-- Add the parameters for the stored procedure here
#Code varchar(500),
#ssid varchar(50),
#serialNo varchar(50),
#category decimal(10,5)
as begin
SELECT *
FROM tblSource
WHERE (Code IN (SELECT Value FROM funcListToTableInt(#Code,',')) OR #Code IS NULL)
AND (SiteSourceID LIKE '%' + #ssID + '%' OR #ssID IS NULL)
AND (serialNo LIKE '%' + #serialNo + '%' OR #serialNo IS NULL)
AND (category = #category OR #category IS NULL)
end
This looks very strange at first glance, since it is checking the parameters for IS NULL, but it works.
Try adding OR clauses for the nulls. SO for example change 'and category = #category' to 'and ((category = #category) or (category is null)).
Do this for all the items for whiuch you want to have a null imput essectially disable that particular test.
There are two ways:
Way 1, ADD OR Clause: It can kill the performance ....
SELECT *
FROM tblSource
WHERE (Code IN (
SELECT Value
FROM funcListToTableInt(#Code,',')
) OR #Code IS NULL)
and (SiteSourceID LIKE '%' + #ssID + '%' OR #SSID IS NULL)
and (serialNo LIKE '%' + #serialNo + '%' OR #serialNo IS NULL)
and (category = #category OR #category)
Way 2: Conditional logic
Considering you have 4 parameters and each may have a value or may not have a value, So you have 2*2*2*2 , 16 different cases. You can write something like:
IF (#SSID IS NULL AND #Code IS NULL AND #serialNo IS NULL AND #category IS NOT NULL) THEN
-- SEARCH only of category
ELSE IF (#SSID IS NULL AND #Code IS NULL AND #serialNo IS NOT NULL AND #category IS NULL) THEN
-- SEARCH only on Serial Number
.
.
.
.
.
As in SQL Server each If block cache its own plan, it will be more performing but based on parameter and there possible combinations this approach may or may not be desired ...