SQL: like and variable couldn't show results - sql

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

Related

Stored procedure ignoring Nulls and fetch result for only entered parameters

I am creating a stored procedure to do a search through a table. I have many different search columns, all of which are optional. Is there a way to create a stored procedure that will handle this? Let's say I have a table with four columns ID, N1, N2 and N3. I could do something like this:
Table:
INSERT INTO [dbo].[Sample]
VALUES ('1', 'A,B,C', 'A,B,C', 'A,B,C'),
('2', 'B,D,N', 'B,D,N', 'B,D,N'),
('3', 'A,N,S', 'A,N,S', 'A,N,S'),
('4', 'S,F,G', 'S,F,G', 'S,F,G'),
('5', 'D,F,K', 'D,F,K', 'D,F,K'),
('6', 'S,H,Y', 'S,H,Y', 'S,H,Y'),
('7', 'Z,B,C', 'Z,B,C', 'Z,B,C')
Stored procedure:
CREATE PROCEDURE dbo.Sample2
#n11 varchar(max) = null,
#n12 varchar(max) = null,
#n21 varchar(max) = null,
#n22 varchar(max) = null,
#n31 varchar(max) = null,
#n32 varchar(max) = null
AS
BEGIN
SELECT COUNT(*)
FROM Sample
WHERE
(#n11 IS NULL OR Sample.N1 LIKE '%' + #n11 + '%'
OR #n12 IS NULL OR Sample.N1 LIKE '%' + #n12 + '%')
AND (#n21 IS NULL OR Sample.N2 LIKE '%' + #n21 + '%'
OR #n22 IS NULL OR Sample.N2 LIKE '%' + #n22 + '%')
AND (#n31 IS NULL OR Sample.N3 LIKE '%' + #n31 + '%'
OR #n32 IS NULL OR Sample.N3 LIKE '%' + #n32 + '%')
END
If user enters #n11 as A and leave the rest, since N1 contains A in 2 rows, output should be 2 but above query is providing 7. If a parameter is not specified, I need that to be ignored and pass the rest to where condition.
I think you need to AND every separate input condition e.g.
SELECT count(*)
FROM [Sample] S
WHERE (#n11 IS NULL OR S.N1 LIKE '%'+#n11+'%')
AND (#n12 IS NULL OR S.N1 LIKE '%'+#n12+'%')
AND (#n21 IS NULL OR S.N2 LIKE '%'+#n21+'%')
AND (#n22 IS NULL OR S.N2 LIKE '%'+#n22+'%')
AND (#n31 IS NULL OR S.N3 LIKE '%'+#n31+'%')
AND (#n32 IS NULL OR S.N3 LIKE '%'+#n32+'%')
Note the alias, which is the best practice way to avoid having to repeat a long table name all over the query.
Try to remove the next conditions from your stored procedure query:
#n12 IS NULL
#n22 IS NULL
#n32 IS NULL
As the above conditions are returning always true while there were sent when calling the procedure.
Stored procedure code after modified:
Alter Procedure dbo.Sample2
#n11 varchar(max) = null,
#n12 varchar(max) = null,
#n21 varchar(max) = null,
#n22 varchar(max) = null,
#n31 varchar(max) = null,
#n32 varchar(max) = null
AS
BEGIN
select count(*)
from Sample
where (#n11 IS NULL OR Sample.N1 LIKE '%'+#n11+'%' OR Sample.N1 LIKE '%'+#n12+'%')
AND (#n21 IS NULL OR Sample.N2 LIKE '%'+#n21+'%' OR Sample.N2 LIKE '%'+#n22+'%')
AND (#n31 IS NULL OR Sample.N3 LIKE '%'+#n31+'%' OR Sample.N3 LIKE '%'+#n32+'%')
END
Now while executing exec dbo.Sample2 #n11 = 'A' the output will be 2 instead of 7
select
sum(iif(N1 like '%'+#N11+'%',1,0)
+ iif(N1 like '%'+#N12+'%',1,0)
+ iif(N2 like '%'+#N21+'%',1,0)
+ iif(N2 like '%'+#N22+'%',1,0)
+ iif(N3 like '%'+#N31+'%',1,0)
+ iif(N3 like '%'+#N32+'%',1,0)
)
from Sample
Any NULL variables will be ignored.

How to make a search query where contain each words of string in SQL Server?

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+'%'

T-SQL wild card brings back no results

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).

Using Stored Procedure variable in Like statement

I can't seem to properly use the LIKE statement using a variable from a stored procedure. I want to find all the rows from a table that start with the variable passed.
I am currently using the following query where #id is the value passed to the stored procedure as nvarchar(20). This works fine when the IDs completely match, but does not properly use the '%' appended. What is the proper way to complete this task?
SELECT * FROM Table WHERE id LIKE #id + '%'
This works for me:
declare #id nvarchar(20)
select #id = '1'
SELECT * FROM tab WHERE id LIKE #id + '%'
Sql Fiddle DEMO
The query doesn't work if #id is null. So what you can do is set it to empty string if #id is null. Please try the following:
begin
declare #id nvarchar(20)
set #id = isnull(#id, '')
select * from table where id like #id + '%'
end
So in your procedure, adding the following line should work for your query:
set #id = isnull(#id, '')
Simple solution:
$search_q = '%' . $this_search_q. '%';
$stmt = $db->prepare("SELECT * FROM tbl_tablename WHERE tablecollumn LIKE :id");
$stmt ->bindParam(":id", $search_q );
$stmt->execute();
OR
$search_q = '%' . $this_search_q. '%';
$stmt = $db->prepare("SELECT * FROM tbl_tablename WHERE tablecollumn LIKE $search_q");
$stmt->execute();
CREATE PROCEDURE `SP_GENRE_SELECT`(
IN _Id INTEGER,
IN _Name VARCHAR(50),
IN _account VARCHAR (50),
IN _Password VARCHAR (50),
IN _LastConnexionDate DATETIME,
IN _CreatedDate DATETIME,
IN _UpdatedDate DATETIME,
IN _CreatedUserId INTEGER,
IN _UpdatedUserId INTEGER,
IN _Status TINYINT
)
BEGIN
SELECT *
FROM user
WHERE Id LIKE _id IS NULL + '%',CAST(_Id AS VARCHAR)
AND
WHERE Name LIKE _Name IS NULL + '%' ,'%',CONCAT('%',_Name,'%')
AND
WHERE Account LIKE _Account IS NULL + '%' ,'%',CONCAT('%',_Account,'%')
AND
WHERE LastConnexionDate LIKE _LastConnexionDate IS NULL + '%' ,'%',CONCAT('%',CAST(LastConnexionDate AS VARCHAR(50),'%'))
AND
WHERE CreatedDate LIKE _CreatedDate IS NULL + '%' ,'%',CONCAT('%',CAST(_CreatedDate AS VARCHAR(50),'%'))
AND
WHERE UpdatedDate LIKE _UpdatedDate IS NULL + '%' ,'%',CONCAT('%',CAST(_UpdatedDate AS VARCHAR(50),'%'))
AND
WHERE CreatedUserID LIKE _CreatedUserID IS NULL +'%' ,'%',CONCAT('%',CAST(_CreatedUserID AS VARCHAR(50),'%'))
AND
WHERE UpdatedUserID LIKE _UpdatedUserID IS NULL +'%' ,'%',CONCAT('%',CAST(_UpdatedUserID AS VARCHAR(50),'%'))
AND
WHERE Status LIKE _Status IS NULL + '%' ,'%',CAST(_Status AS VARCHAR(50),'%');
END

T-SQL: How to do this: select * from xy where uid in (#parameter)

Question:
How to do this:
DECLARE #StateUID varchar(max)
SET #StateUID = 'E8812237-2F3B-445E-8EEF-020E0B6F6A53, 66E57225-642F-45B5-8E5D-070F2D1CF99D, 751C615B-EB9C-4D25-955D-0E0EB3CD05A2'
SELECT StateFullName, StateAbbrv, StateID
FROM tblStates
WHERE StateUID IN ( #StateID )
Doing string.join as shown below doesn't help as well:
SET #StateUID = '''E8812237-2F3B-445E-8EEF-020E0B6F6A53'', ''66E57225-642F-45B5-8E5D-070F2D1CF99D'', ''751C615B-EB9C-4D25-955D-0E0EB3CD05A2'''
I've now moved it into dynamic SQL, where it works.
But this is extremely error-prone, annoying and time-consuming, so I wanted to ask whether there is any non-insane way of doing this (without temp tables, functions etc.) ?
In this case it seems you can use 'like'
DECLARE #QueryUIDs varchar(MAX)
SET #QueryUIDs = '''E8812237-2F3B-445E-8EEF-020E0B6F6A53'', ''66E57225-642F-45B5-8E5D-070F2D1CF99D'', ''751C615B-EB9C-4D25-955D-0E0EB3CD05A2'''
SELECT StateFullName, StateAbbrv, StateUID
FROM tblStates
WHERE #QueryUIDs LIKE '%' + CAST(StateUID AS CHAR(36)) + '%'
One option is to parse the comma delimited string into a subquery. The code below assumes that you can remove spaces from the #StateUID string and that StateID is a unique identifier:
DECLARE #StateUID varchar(max), #xml xml
SET #StateUID = 'E8812237-2F3B-445E-8EEF-020E0B6F6A53,' +
'66E57225-642F-45B5-8E5D-070F2D1CF99D,' +
'751C615B-EB9C-4D25-955D-0E0EB3CD05A2'
SET #xml = '<root><r>' + replace(#StateUID,',','</r><r>') + '</r></root>'
SELECT StateFullName, StateAbbrv, StateID
FROM tblStates
WHERE StateID IN (
SELECT
CONVERT(uniqueidentifier, t.value('.','varchar(36)')) as [id]
FROM #xml.nodes('//root/r') as a(t)
)
There are many great string splitting functions but using XML is my favorite.
if you don't like temp tables and arrays, you can use more than one variable:
DECLARE #StateUID_1 varchar(max)
DECLARE #StateUID_2 varchar(max)
DECLARE #StateUID_3 varchar(max)
SET #StateUID_1 = 'E8812237-2F3B-445E-8EEF-020E0B6F6A53'
SET #StateUID_2 = '66E57225-642F-45B5-8E5D-070F2D1CF99D'
SET #StateUID_3 = '751C615B-EB9C-4D25-955D-0E0EB3CD05A2'
SELECT StateFullName, StateAbbrv, StateID
FROM tblStates
WHERE StateUID IN ( #StateUID_1, #StateUID_2, #StateUID_3 )