Query a database from a search with empty values - sql-server

I am using asp .net web form search in c#, for example with fields:
- name
- fruit
I want to write a sproc that can search name or fruit. If I knew that both would have values, I would pass two parameters into the sproc and would write:
Select * from myTable where name =#name and fruit = #fruit
However sometimes, either name or fruit could be empty. Without writing a separate search for fruit and name. How would I achieve this?
I would prefer not to create a dynamic query if possible, but if this is the only way how would I write it?

You'll need to make sure that empty strings aren't passed as arguments instead of null, but the following should work. I'm pretty sure, though, that if the user doesn't input anything the form value will be null.
select * from myTable
where (#name is null or name = #name) and (#fruit is null or fruit = #fruit)

maybe:
SELECT * FROM myTable WHERE name Like '%' + #name AND fruit LIKE '%' + #fruit

select * from myTable
where
(name = #name and fruit = #fruit)
or (name = #name and #fruit is null)
or (fruit = #fruit and #name = is null )

select * from myTable where name = isnull(#name, name) and fruit = isnull(#fruit, fruit)
Will return the entire table if both #name and #fruit is null. If that is a problem, you better add some additional logic to the SP.

Related

Grab the first 3 characters from a parameter, and make a new parameter from that then you it to find items that are LIKE it?

The first 3 characters of an Item is the Price Group. This is for a stored procedure so I need it to find all items within the price group based on the item itself.
DECLARE #ItemNumber VARCHAR(30) = 'ABC1234'
DECLARE #PG VARCHAR(3) = SUBSTRING(#ItemNumber, 1, 3)
SELECT *
FROM Coupons (NOLOCK)
WHERE CouponType = 'PriceGroup'
and Description like (#PG)
Since you are using LIKE I can only assume you are looking for the first 3 characters anywhere in the Description. Something like this will work.
DECLARE #ItemNumber VARCHAR(30) = 'ABC1234'
SELECT *
FROM Coupons
WHERE CouponType = 'PriceGroup'
and Description like '%' + LEFT(#ItemNumber, 3) + '%'
Also, NOLOCK is very rarely a good idea. https://blogs.sentryone.com/aaronbertrand/bad-habits-nolock-everywhere/ But if you insist on using it, you need to include the WITH keyword for query hints. Omitting them is deprecated.

I want my stored procedure to only populate one instance of a name

I'm creating a stored procedure that populates two tables tblAirport and tblCountry. tblCountry gets its country names from tblAirport but I only want one instance of the country name to show up in `tblCountry. So far for my stored procedure I have this
DECLARE #PK INT = (SELECT PK FROM tblAirport WHERE strName = #strName)
IF #PK IS NULL
INSERT INTO tblAirport (ICAOCode,IATACode,strName,strCity,strCountry,degLat,minLat,secLat,Equator,degLong,minLong,secLong,Meridian,strElevation)
VALUES (#ICAOCode,#IATACode,#strName,#strCity,#strCountry,#degLat,#minLat,#secLat,#Equator,#degLong,#minLong,#secLong,#Meridian,#strElevation)
SET #PK = (SELECT PK FROM tblAirport WHERE strName = #strName);
IF EXISTS (SELECT * FROM tblCountry WHERE strCountry = #strCountry)
SET #strCountry = #strCountry + 'x'
INSERT INTO tblCountry (strCountry)
VALUES (#strCountry)
I tried using IF EXISTS (SELECT * FROM tblCountry WHERE strCountry = #strCountry)
SET #strCountry = #strCountry + 'x' just to show any duplicate countries but I don't know how to eliminate the duplicates from my table. I'm new to SQL and I've only learned the IF EXISTS function. Any suggestions would be great. Thank you!
This is how to handle a multiline IF ELSE (https://technet.microsoft.com/en-us/library/ms182717(v=sql.110).aspx)
IF NOT EXISTS (SELECT * FROM tblCountry WHERE strCountry = #strCountry)
BEGIN
INSERT INTO tblCountry (strCountry) VALUES (#strCountry)
END;
In general though, I'd be concerned about a procedure that uses the data to drive the possible values in a lookup list, especially something like countries that should probably be pre-defined up front. You'd hate for them to enter free-form duplicates that are really the same country with a slightly different spelling.

How to add column dynamically in where clause

I want to include column in where clause depending on the condition.
e.g
select * From emp
where id=7,
and if(code is not null) then code=8;
how can i do this in sql server
If I understand you correct, you could make use of COALESCE.
COALESCE()
Returns the first nonnull expression
among its arguments.
SQL Statement
SELECT *
FROM emp
WHERE id=7
AND code = COALESCE(#code, code)
If code is a column rather than a variable the query in your question would be rewritten as follows.
SELECT *
FROM emp
WHERE id=7 AND (code IS NULL OR code=8)
You'll probably have to create a query dynamically, as a string, and then use the Execute method to actually execute it. This approach has some potentially optimization issues, but it's commonly done. You might wan to Google T-SQL Dynamic Query, or something like that.
Also use this in case of Null value in #var1.
Select * from ABC where Column1 = isNull(#var1, Column1)
here is the example:
declare #SQL varchar(500)
declare #var1 int
set int = 1
set #SQL = 'Select * from ABC Where 1 = 1'
if(#var1 = 1)
set #SQL + #SQL ' And column1 = ' #var1
exec(#SQL)
You can use COALESCE function.
Well,
I don't know if i understood your question, but i guess that you want to include the value of the code column in the results.
If i'm right it can be done in the select part instead of the where clause. i. e.
Select ..., case when code is not null then 8 else code end as code from emp where id = 7
The other interpretation is that you want to filter rows where code <> 8,that would be
Select * from emp where id = 7 and (code is null OR code = 8)

Using variable in SQL LIKE statement

I've got a sproc (MSSQL 2k5) that will take a variable for a LIKE claus like so:
DECLARE #SearchLetter2 char(1)
SET #SearchLetter = 't'
SET #SearchLetter2 = #SearchLetter + '%'
SELECT *
FROM BrandNames
WHERE [Name] LIKE #SearchLetter2 and IsVisible = 1
--WHERE [Name] LIKE 't%' and IsVisible = 1
ORDER BY [Name]
Unfortunately, the line currently running throws a syntax error, while the commented where clause runs just fine. Can anyone help me get the un-commented line working?
If you are using a Stored Procedure:
ALTER PROCEDURE <Name>
(
#PartialName VARCHAR(50) = NULL
)
SELECT Name
FROM <table>
WHERE Name LIKE '%' + #PartialName + '%'
Joel is it that #SearchLetter hasn't been declared yet? Also the length of #SearchLetter2 isn't long enough for 't%'. Try a varchar of a longer length.
As Andrew Brower says, but adding a trim
ALTER PROCEDURE <Name>
(
#PartialName VARCHAR(50) = NULL
)
SELECT Name
FROM <table>
WHERE Name LIKE '%' + LTRIM(RTRIM(#PartialName)) + '%'
But in my opinion one important thing.
The "char(number)" it's lenght of variable.
If we've got table with "Names" like for example [Test1..Test200] and we declare char(5) in SELECT like:
DECLARE #variable char(5)
SET #variable = 'Test1%'
SELECT * FROM table WHERE Name like #variable
the result will be only - "Test1"! (char(5) - 5 chars in lenght; Test11 is 6 )
The rest of potential interested data like [Test11..Test200] will not be returned in the result.
It's ok if we want to limit the SELECT by this way.
But if it's not intentional way of doing it could return incorrect results from planned
( Like "all Names begining with Test1..." ).
In my opinion if we don't know the precise lenght of a SELECTed value, a better solution could be something like this one:
DECLARE #variable varchar(max)
SET #variable = 'Test1%'
SELECT * FROM <table> WHERE variable1 like #variable
This returns (Test1 but also Test11..Test19 and Test100..Test199).
This works for me on the Northwind sample DB, note that SearchLetter has 2 characters to it and SearchLetter also has to be declared for this to run:
declare #SearchLetter2 char(2)
declare #SearchLetter char(1)
Set #SearchLetter = 'A'
Set #SearchLetter2 = #SearchLetter+'%'
select * from Customers where ContactName like #SearchLetter2 and Region='WY'
DECLARE #SearchLetter2 char(1)
Set this to a longer char.
We can write directly too...
DECLARE #SearchLetter CHAR(1)
SET #SearchLetter = 'A'
SELECT *
FROM CUSTOMERS
WHERE CONTACTNAME LIKE #SearchLetter + '%'
AND REGION = 'WY'
or the following way as well if we have to append all the search characters then,
DECLARE #SearchLetter CHAR(1)
SET #SearchLetter = 'A' + '%'
SELECT *
FROM CUSTOMERS
WHERE CONTACTNAME LIKE #SearchLetter
AND REGION = 'WY'
Both these will work
I had also problem using local variables in LIKE.
Important is to know: how long is variable.
Below, ORDER_NO is 50 characters long, so You can not use: LIKE #ORDER_NO, because in the end will be spaces.
You need to trim right side of the variable first.
Like this:
DECLARE #ORDER_NO char(50)
SELECT #ORDER_NO = 'OR/201910/0012%'
SELECT * FROM orders WHERE ord_no LIKE RTRIM(#ORDER_NO)
It may be as simple as LIKE '%%[%3]%%' being [%3] the input variable.
This works for me with SAP B1 9.1
I ran into a similar problem. I needed to use just a small piece of a URL saved in my database where the front and ends were irrelevant.
I first attempted to use:
DECLARE #variable VARCHAR(250) = %x%;
SELECT * FROM tblone WHERE column1 LIKE '#variable'
However, this returned the error:
Arithmetic overflow error converting numeric to data type varchar
My working query was formatted:
DECLARE #variable VARCHAR(1000) = x;
SELECT * FROM tblone WHERE column1 LIKE '%'+#variable+'%'

How do I check if a SQL Server text column is empty?

I am using SQL Server 2005. I have a table with a text column and I have many rows in the table where the value of this column is not null, but it is empty. Trying to compare against '' yields this response:
The data types text and varchar are incompatible in the not equal to operator.
Is there a special function to determine whether the value of a text column is not null but empty?
where datalength(mytextfield)=0
ISNULL(
case textcolum1
WHEN '' THEN NULL
ELSE textcolum1
END
,textcolum2) textcolum1
Actually, you just have to use the LIKE operator.
SELECT * FROM mytable WHERE mytextfield LIKE ''
To get only empty values (and not null values):
SELECT * FROM myTable WHERE myColumn = ''
To get both null and empty values:
SELECT * FROM myTable WHERE myColumn IS NULL OR myColumn = ''
To get only null values:
SELECT * FROM myTable WHERE myColumn IS NULL
To get values other than null and empty:
SELECT * FROM myTable WHERE myColumn <> ''
And remember use LIKE phrases only when necessary because they will degrade performance compared to other types of searches.
SELECT * FROM TABLE
WHERE ISNULL(FIELD, '')=''
Use the IS NULL operator:
Select * from tb_Employee where ename is null
I know this post is ancient but, I found it useful.
It didn't resolve my issue of returning the record with a non empty text field so I thought I would add my solution.
This is the where clause that worked for me.
WHERE xyz LIKE CAST('% %' as text)
Use DATALENGTH method, for example:
SELECT length = DATALENGTH(myField)
FROM myTABLE
Instead of using isnull use a case, because of performance it is better the case.
case when campo is null then '' else campo end
In your issue you need to do this:
case when campo is null then '' else
case when len(campo) = 0 then '' else campo en
end
Code like this:
create table #tabla(
id int,
campo varchar(10)
)
insert into #tabla
values(1,null)
insert into #tabla
values(2,'')
insert into #tabla
values(3,null)
insert into #tabla
values(4,'dato4')
insert into #tabla
values(5,'dato5')
select id, case when campo is null then 'DATA NULL' else
case when len(campo) = 0 then 'DATA EMPTY' else campo end
end
from #tabla
drop table #tabla
I would test against SUBSTRING(textColumn, 0, 1)
Are null and an empty string equivalent? If they are, I would include logic in my application (or maybe a trigger if the app is "out-of-the-box"?) to force the field to be either null or '', but not the other. If you went with '', then you could set the column to NOT NULL as well. Just a data-cleanliness thing.
I wanted to have a predefined text("No Labs Available") to be displayed if the value was null or empty and my friend helped me with this:
StrengthInfo = CASE WHEN ((SELECT COUNT(UnitsOrdered) FROM [Data_Sub_orders].[dbo].[Snappy_Orders_Sub] WHERE IdPatient = #PatientId and IdDrugService = 226)> 0)
THEN cast((S.UnitsOrdered) as varchar(50))
ELSE 'No Labs Available'
END
You have to do both:
SELECT * FROM Table WHERE Text IS NULL or Text LIKE ''
I know there are plenty answers with alternatives to this problem, but I just would like to put together what I found as the best solution by #Eric Z Beard & #Tim Cooper with #Enrique Garcia & #Uli Köhler.
If needed to deal with the fact that space-only could be the same as empty in your use-case scenario, because the query below will return 1, not 0.
SELECT datalength(' ')
Therefore, I would go for something like:
SELECT datalength(RTRIM(LTRIM(ISNULL([TextColumn], ''))))
try this:
select * from mytable where convert(varchar, mycolumn) = ''
i hope help u!
DECLARE #temp as nvarchar(20)
SET #temp = NULL
--SET #temp = ''
--SET #temp = 'Test'
SELECT IIF(ISNULL(#temp,'')='','[Empty]',#temp)
It will do two things:
Null check and string null check
Replace empty value to default value eg NA.
SELECT coalesce(NULLIF(column_name,''),'NA') as 'desired_name') from table;

Resources