Return an integer if nothing is found (TSQL ASP.NET VB) - asp.net

I need to return a value (0) if nothing is found in an SQL call.
Here is what i have (edited/simplified to make more sense out of context), this is baing called from the codebehind.
sql1 = "INSERT INTO [Xtr_MenuItems]([menu_order])
values(1 + (select max(menu_order) from [Xtr_MenuItems]))
SO into database i insert the max number found in [menu_order] + 1. this works fine, assuming something is found.
However, if (select max(menu_order) from [Xtr_MenuItems])) fails (nothing found) then i want to return 0 (as 1 + nothing = nothing, and sql explodes)
How can i do this? I have tried 'IF EXISTS', 'OUTPUT' in various ways but cant get it to work...

Try this:
sql1 = "INSERT INTO [Xtr_MenuItems]([menu_order])
values(1 + ISNULL((select max(menu_order) from [Xtr_MenuItems]),0))
I used ISNULL function where if the result of query is null returns 0

Instead of values, you could use select straight away:
insert Xtr_MenuItems
(menu_order)
select 1 + isnull(max(menu_order),0)
from Xtr_MenuItems

COALESCE is the standards compliant way to provides alternatives for null values:
sql1 = "INSERT INTO [Xtr_MenuItems]([menu_order])
values(1 + COALESCE((select max(menu_order) from [Xtr_MenuItems]),0))
It has similar syntax to the ISNULL function provided by Microsoft, but will work across multiple db platforms and can handle multiple fallbacks.
W3Schools privides a great introduction to null handling here.

Related

SQLite SELECT statement where column equals zero

I'm preety new to SQLite.
I have a preety basic question.. Why can't I select rows where specific column equals zero?
The is_unwanted column is type TINYINT (which I see in SQLite basically means INTEGER)
So, I have only one record in the database (for testing).
When I try
SELECT is_unwanted FROM 'urls'
I get a result of "0" (zero), which is fine because that column contains the actual number 0.
I tried =>
SELECT * FROM 'urls' WHERE is_unwanted = 0
And got NO result, but
SELECT * FROM 'urls' WHERE is_unwanted <> 0
gives me result.
What am I doing wrong??
Try running
select '{' || is_unwanted || '}' from urls
to see if the value in the database is really a string containing spaces.
SQLite is a dynamically typed database; when you specify TINYINT is is a hint (SQLite uses the term "affinity") for the column. You can use
select is_unwanted, typeof(is_unwanted) from urls
to see the values with their types.
You could try:
SELECT * FROM urls WHERE coalesce(is_unwanted,'') = ''

LINQ - 'Could not translate expression' with previously used and proven query condition

I am fairly new to LINQ and can't get my head around some inconsistency in behaviour. Any knowledgeable input would be much appreciated. I see similar issues on SO and elsewhere but they don't seem to help.
I have a very simple setup - a company table and an addresses table. Each company can have 0 or more addresses, and if > 0 one must be specified as the main address. I'm trying to handle the cases where there are 0 addresses, using an outer join and altering the select statement accordingly.
Please note I'm currently binding the output straight to a GridView so I would like to keep all processing within the query.
The following DOES work
IQueryable query =
from comp in context.Companies
join addr in context.Addresses on comp.CompanyID equals addr.CompanyID into outer // outer join companies to addresses table to include companies with no address
from addr in outer.DefaultIfEmpty()
where (addr.IsMain == null ? true : addr.IsMain) == true // if a company has no address ensure it is not ruled out by the IsMain condition - default to true if null
select new {
comp.CompanyID,
comp.Name,
AddressID = (addr.AddressID == null ? -1 : addr.AddressID), // use -1 to represent a company that has no addresses
MainAddress = String.Format("{0}, {1}, {2} {3} ({4})", addr.Address1, addr.City, addr.Region, addr.PostalCode, addr.Country)
};
but this displays an empty address in the GridView as ", , ()"
So I updated the MainAddress field to be
MainAddress = (addr.AddressID == null ? "" : String.Format("{0}, {1}, {2} {3} ({4})", addr.Address1, addr.City, addr.Region, addr.PostalCode, addr.Country))
and now I'm getting the Could not translate expression error and a bunch of spewey auto-generated code in the error which means very little to me.
The condition I added to MainAddress is no different to the working condition on AddressID, so can anybody tell me what's going on here?
Any help is greatly appreciated.
The error you are getting is telling you that LinqToSql cannot translate your null check and then string.Format expression into SQL. If you look at the SQL your first query is generating (using either LinqPad or SQL Profiler), you'll see something like:
SELECT [t0].[CompanyID], [t0].[Name],
(CASE
WHEN [t1].[AddressID] IS NULL THEN #p0
ELSE [t1].[AddressID]
END) AS [AddressID],
[t1].[Address1] AS [value],
[t1].[City] AS [value2],
[t1].[Region] AS [value3],
[t1].[PostalCode] AS [value4],
[t1].[Country] AS [value5]
FROM [Company] AS [t0]
LEFT OUTER JOIN [Address] AS [t1] ON [t0].[CompanyID] = [t1].[CompanyID]
WHERE ([t1].[IsMain] IS NULL) OR ([t1].[IsMain] = 1)
For your AddressID field, you can see that it uses a CASE-WHEN to handle the condition when AddressID is null. When you add a CASE-WHEN for MainAddress, it's trying to do the same thing for that field, but there is no SQL equivalent to string.Format it can use for the ELSE clause, so it blows up.
An easy way around this problem is to use a method to format the string. By calling a private method, LinqToSql won't try to translate the string.Format to SQL, and will instead return all of the fields necessary to populate the Address object. The method can then take care of the formatting.
For example:
LINQ:
....
select new {
comp.CompanyID,
comp.Name,
AddressID = (addr.AddressID == null ? -1 : addr.AddressID),
MainAddress = FormatAddress(addr)
};
Method:
private static string FormatAddress(Address addr)
{
return (addr == null ? "" :
string.Format("{0}, {1}, {2} {3} ({4})",
addr.Address1, addr.City,
addr.Region, addr.PostalCode, addr.Country));
}

SQL: Not equal operator Problem

I am using a not equal operator <> in my sql statement but it doesn't retrieve any record which is not equal to the selected date.
CODE:
Command = New SqlCommand("SELECT * FROM [Products] WHERE [ParkingStartDate] <> #StartDate", myConn)
Command.Parameters.AddWithValue("#StartDate", StartDate1)
This won't return anything if either of the following is true:
StartDate1 is a NULL
ParkingStartDate for all values is a NULL or equal to StartDate1 (obvious one)
Check that you are passing a non-NULL value in StartDate1 and there are records satisfying your condition.
If the values are null you would have to do
Command = New SqlCommand("SELECT * FROM [Products] WHERE [ParkingStartDate] <> #StartDate OR ParkingStartDate is null", myConn)
Command.Parameters.AddWithValue("#StartDate", StartDate1)
First stop using that <> operator.
Use instead != (NOT EQUAL)
run this statement in sql. it will return zero results. to illustrate my point.
select '1' where NULL <> 0
instead use
where columname != #startdate or columnname is null
One important thing to take into consideration when dealing with querying based on date is that the date in SQL Server is treated as exact as the date you send in. So, if you pass in a full date/time, like 2011-10-24 14:35:29, it will return all dates that are not that exact date. If you are looking for a particular portion of that date to be selected against, you need to only give that portion of the date. Using the DATEPART command will help here also.
If the value is undefined, it is not included in <> or != clause.
Along with these you can use sql function 'COALESCE()' to include rows having undefined cells.
"SELECT * FROM [Products] WHERE COALESCE([ParkingStartDate],'') <> #StartDate OR ParkingStartDate is null"
Hope it will help you.
My recommendation would be to try with NULLIF operator. Modify your query to be like :
SELECT * FROM [Products] WHERE NULLIF([ParkingStartDate], #StartDate) IS NOT NULL OR ParkingStartDate is NULL
Hope this helps.

ASP.NET query substring

I've got this field in my database year_start_1 and it is an integer field and an example of an ouput is 20100827 I'm trying to create a substring to create year, week, day and change the format to be 27/08/2010
Here's what i'm trying
Dim query as String = "Select * from openquery (devbook, 'SELECT cast(year_start_1 as varchar(8)) as year_start_1, DATENAME(DAY, substring(CAST(year_start_1 AS VARCHAR(8)),6,2) + DATENAME(MONTH, substring(CAST(year_start_1 AS VARCHAR(8)),4,2) + DATENAME(YEAR, substring(CAST(year_start_1 AS VARCHAR(8)),1,4))) FROM web_statements')"
It's just throwing up an error and I not sure why:
Server was unable to process request
I have tried using convert but it doesn't work.
Any ideas?
UPDATE
with Chris's suggestion
Dim query as String = "Select * from openquery (devbook, 'SELECT year_start_1, cast(year_start_1 as varchar(8)) as year_start_1, substring(CAST(year_start_1 AS VARCHAR(8)),7,2)+''/''+substring(CAST(year_start_1 AS VARCHAR(8)),5,2)+''/''+substring(CAST(year_start_1 AS VARCHAR(8)),1,4) FROM web_statements')"
Still getting the error
Thanks
UPDATE
Couldn't seem to get it to work within the query so had to do a work around in the ASP.Net code
'POINTS END DATE YEAR
Dim strPointsDateEndYear = Mid(drv.Row("year_end_1"), 3, 2)
Dim strPointsDateEndMonth = Mid(drv.Row("year_end_1"), 5,2)
Dim strPointsDateEndDay = Right(drv.Row("year_end_1"), 2)
Dim strPointsDateEnd As String = strPointsDateEndDay + "/" + strPointsDateEndMonth + "/" + strPointsDateEndYear
Thanks for the help though
Your first DATENAME doesn't seem to close all its brackets before the next DATENAME starts:
DATENAME(DAY, substring(CAST(year_start_1 AS VARCHAR(8)),6,2) + DATENAME[...]
Should I assume be:
DATENAME(DAY, substring(CAST(year_start_1 AS VARCHAR(8)),6,2)) + DATENAME[...]
Edit: Though having fixed that minor error (and converted it to debug) I'm getting errors about casting strings to dates. I'm not sure what the datename stuff is meant to do but how about this:
DECLARE #year_start_1 int
SET #year_start_1 = 20100827
SELECT cast(#year_start_1 as varchar(8)) as year_start_1,
substring(CAST(#year_start_1 AS VARCHAR(8)),7,2)+'/'+substring(CAST(#year_start_1 AS VARCHAR(8)),5,2)+'/'+substring(CAST(#year_start_1 AS VARCHAR(8)),1,4)
(converted to a non table based select for test/debug purposes)
So what you would want for your final line of sql would be (untested):
Select * from openquery (devbook, 'SELECT cast(year_start_1 as varchar(8)) as year_start_1, substring(CAST(year_start_1 AS VARCHAR(8)),7,2)+'/'+substring(CAST(year_start_1 AS VARCHAR(8)),5,2)+'/'+substring(CAST(year_start_1 AS VARCHAR(8)),1,4) FROM web_statements')
Second Edit for debug notes:
I thought it might also be worth suggesting how to debug this sort of problem. The error message suggested that the linked server you were sending the sub-statement to was unable to process the request. The first thing to try in this case would be to run the request directly on the server to see what happens. In this case in fact just parsing it on its own would have revealed the first errors I got.
Once you have your statement running form management studio or whatever directly on the server you can try converting it back into the "openquery" style statement and see if ti still works. Bascially break down your complicated scenario into lots of smaller bits to test each one individually.
select convert(varchar(10),convert(smalldatetime,'20100827'),103) will return 08/27/2010
so, your solution is:
select convert(varchar(10),convert(smalldatetime,convert(varchar,year_start_1)),103) will return 27/08/2010
You are using the datename function on strings, but it should be used on a datetime value. They are nested inside each other so you would end up with just the day, and besided it doesn't even do what you are looking for.
To get the format that you asked for, you can just use string operations to split it up in it's components and add slashes between them:
substring(CAST(year_start_1 AS VARCHAR(8)),7,2) + '/' +
substring(CAST(year_start_1 AS VARCHAR(8)),5,2) + '/' +
substring(CAST(year_start_1 AS VARCHAR(8)),1,4)

Linq to Sql - Only select certain information (w/ Predicate Builder)

I am using Linq to Sql with Predicate Builder and am trying to optimize how much information is retrieved from the database. I would like to select only certain fields to display them in a gridview. When I select only what I want, the search parameters I add (see below) don't work, and neither does PredicateBuilder. Here's what I'm currently doing (that works, but gets EVERYTHING which is way too much info)
' Initial Setup '
Dim db As New MyDataContext()
Dim results = From p In db.Products _
Select p
' Search '
If (testCase) Then
results = results.Where(Function(p) p.SomeAttribute = 123)
End If
If I change that to only select what I need, like this:
Dim results = From p In db.Products _
Select p.Name, p.SomethingElse
then I've noticed if the information is selected (ie I select p.SomeAttribute) then I can search (add the where clause) on that attribute, but if its not, I can't. And with predicate builder it only works if I select the entire item (ie select p). All this should be doing is creating SQL statements which don't have to select the attribute to search by it. How can I get this to work and select only what I need, but search by anything and keep prediate builder working? Any help MUCH APPRECIATED! Thanks
You could try to initially do a "select p" at the beginning, then add all your where clauses, and at the very end, select just what you need from it.
' Initial Setup '
Dim db As New MyDataContext()
Dim results = From p In db.Products _
Select p
' Search '
If (testCase) Then
results = results.Where(Function(p) p.SomeAttribute = 123)
End If
' trim down the columns after you've added the wheres...
Dim results2 = from p in results
Select p.Name, p.SomethingElse
You can't modify the "select list" (this is how I understood your question. I might have misunderstood it) with predicate builder (which builds boolean expressions). You should manually use stuff in System.Linq.Expressions namespace to do that but I suggest using Dynamic LINQ instead.
Sounds like you are doing the where on the projection and not the original Product. Do the projection Select p.Name, p.SomethingElse at the end after all the search criteria has been applied.

Resources