Query is successfully executed in SQL Server but not in .NET - asp.net

I wrote a query which is working fine in both .NET app and SQL Server.
But, when I was testing with wide parameters, I found that for that particular, it is not showing anything in .NET app but showing result in SQL Server.
I tried to google, no results with little strange. So, I am asking here.
This is my query:
SELECT DISTINCT
tblCustomers.customerID AS Customer#,
tblCustomers.firstName + ' ' + tblCustomers.surname AS Name,
tblCustomers.street AS Street,
tblCustomers.suburb AS Suburb,
tblCustomers.postCode AS Postcode,
tblCustomers.state AS State,
tblCustomers.country AS Country,
tblCustomers.phone AS [Phone No.],
tblCustomers.fax AS Fax,
tblCustomers.mobilePhone AS [Mobile Phone],
tblCustomers.email AS [E-mail]
FROM
tblCustomers
INNER JOIN
tblProduct_Backorder ON tblCustomers.customerID = tblProduct_Backorder.customerId
WHERE
(tblCustomers.customerID IN
(SELECT
customerId
FROM
tblProduct_Backorder AS tblProduct_Backorder_1
WHERE
(productId IN
(SELECT
productID
FROM
tblProducts
WHERE
(skuCode = 76761)
)
)
)
)
This query is not working for skuCode = 76761, but this one working fine in SQL Server.
Thanks.

You have really not enough information in you question for us to even start guessing what caused the problem. In the mean-time try this instead of your query:
SELECT c.customerID AS [Customer#],
c.firstName + ' ' + tblCustomers.surname AS Name,
c.street AS Street,
c.suburb AS Suburb,
c.postCode AS Postcode,
c.state AS State,
c.country AS Country,
c.phone AS [Phone No.],
c.fax AS Fax,
c.mobilePhone AS [Mobile Phone],
c.email AS [E-mail]
FROM dbo.tblCustomers c
WHERE EXISTS ( SELECT 1
FROM dbo.tblProduct_Backorder b
JOIN dbo.tblProduct p
ON b.productId = p.productId
WHERE p.skuCode = 76761
AND b.customerId = c.customerId );
If I understand your table relationships correctly, it will produce the same result while doing a lot less work.
For your original question you should also post the .net code. Also, what does "no results" mean? An empty result? A timeout? An error?

I found solution by help of xQbert's Comment. I took time and and saw how query is executed in SQL Profiler. skuCode in Table tblProduts is nvarchar(6) and in Table tblProduct_BackOrder its Integer. So, I converted into Integer for same Parameter using Convert() function.

Related

Getting Data from SQL Statement that is Null along with Data that isn't from a Query String

Here is my SQL Statement :
SELECT machine,
fixedassets.[serial no],
[date]
FROM fixedassets
LEFT OUTER JOIN maintenancerecord
ON fixedassets.id = maintenancerecord.id
WHERE areaid = #AreaID
AND [record type] = 'Service History'
It's Currently being used by one of my tables in a GridView(ASP.NET) to show the Machines , Serial No of the Machines & the Date they was last serviced ( From Maintenance Record Where Record Type = Service History ) When I execute this through my Datasource attached to the GridView , it doesn't display the machines , for Example if the Area ID = 4 Then i know that at least 4 machines should appear even though they haven't yet received a Service History ( From a insert in a diff table but that's not the point it should still return them ) ... So my actual question is : Even If the machines have no Service History they should still be Returned in the table because that's what a Left Outer Join does right?
Any more code that needs to be provided can / will do , just ask in the comments.
Thanks you in advance!
[record type] should be check in the ON clause of the LEFT JOIN.
SELECT machine,
fixedassets.[serial no],
[date]
FROM fixedassets
LEFT OUTER JOIN maintenancerecord
ON fixedassets.id = maintenancerecord.id
AND maintenancerecord.[record type] = 'Service History'
WHERE areaid = #AreaID

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

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.

SELECT MAX() contained within a DATEDIFF()

I am writing a report for the desktop support team in the company where I work. The report needs to produce a set of new starters within a specified time frame passed in from an ASP.NET application. Currently there is a one to many relationship between our Worker table and Contract table. We hire a lot of contractors and they sometimes come back after a number of months but are still treated like new starters as new machines need to be configured along with desk space.
A new contract is added for every pay review, job title change and new starter. We need to filter out all but the new starter. The newest contract that is added for job changes and pay reviews is always one day after the end date of the previous contract naturally. As I am only still a fresher in the grand scheme of things I am struggling with a set of functions I am trying to use to achieve my goal.
WHERE
(dbo.[Contract].StartDate BETWEEN #StartDateF AND #EndDateF) AND DATEDIFF(day, SELECT MAX(StartDate)FROM dbo.[Contract] WHERE dbo.[Contract].Worker_ID = w1.Worker_ID, SELECT MAX(EndDate)FROM dbo.[Contract] WHERE dbo.[Contract].Worker_ID = w1.Worker_ID)> 1
I basically want to find out in the instance an employee has more than one contract, regardless of leaving and coming back or pay review, if the current active contract is one day different to the previous contract. This should by my thinking give me all new starters only.
Trouble is I am still trying to get my head around when to use aggregate functions not in a select and when to apply the HAVING clause.
Any help would be appreciated to help me understand why my lack of understanding is causing this query/logic to fail.
Thanks
EDIT
Ok I am still bashing away at this solution and this is syntactically incorrect. In an attempt to remove some of the ambiguity here is the query, with an update;
Declare #StartDateF varchar(10)
Set #StartDateF = '2012-08-03'
Declare #EndDateF varchar(10)
Set #EndDateF = '2012-09-04'
SELECT w1.Worker_ID, w1.Title, w1.FirstName, w1.Surname,w1.Gender, w1.DateofBirth,
dbo.[Contract].StartDate, (select w2.surname + ',' + w2.firstname from worker w2 WITH (NOLOCK) where w2.worker_ID = w1.manager)as Manager, dbo.Grade.GradeDescription AS JobTitle, dbo.Grade.Discipline,
CASE WHEN dbo.[Contract].ContractType_ID = 1 OR dbo.[Contract].ContractType_ID = 2 OR dbo.[Contract].ContractType_ID = 5 OR dbo.[Contract].ContractType_ID = 6
THEN 'Staff' ELSE 'Contractor' END AS ContractType
FROM dbo.Worker w1 WITH (NOLOCK) inner join
dbo.[Contract] WITH (NOLOCK) ON dbo.[Contract].Worker_ID = w1.Worker_ID inner join
dbo.Grade WITH (NOLOCK) ON dbo.Grade.Grade_ID = dbo.[Contract].Grade_ID
WHERE
(dbo.[Contract].StartDate BETWEEN #StartDateF AND #EndDateF AND EndDate IS NULL)
group by
w1.Worker_ID, w1.Title, w1.FirstName, w1.Surname,w1.Gender, w1.DateofBirth,
dbo.[Contract].StartDate, manager, dbo.Grade.Discipline,dbo.Grade.GradeDescription, dbo.[Contract].ContractType_ID
Having DATEDIFF(day, SELECT MAX(StartDate)FROM dbo.[Contract] WHERE dbo.[Contract].Worker_ID = w1.Worker_ID, SELECT MAX(EndDate)FROM dbo.[Contract] WHERE dbo.[Contract].Worker_ID = w1.Worker_ID)
I have added the group by and the having clause but now I am getting the following errors
Msg 156, Level 15, State 1, Line 24
Incorrect syntax near the keyword 'SELECT'.
Msg 102, Level 15, State 1, Line 24
Incorrect syntax near ','.
Msg 102, Level 15, State 1, Line 24
Incorrect syntax near ')'.
These all relate the the functions in the having clause no doubt you can see. But I cannot understand what is wrong with this query and this is mainly the question. I need to understand the SQL functions enough so that I can implement th correct solution.
I have followed up the DATEDIFF() function here http://msdn.microsoft.com/en-us/library/ms189794.aspx
I can see that using functions within this function is acceptable according to the MS documentation.
EDIT
Commenting out the Having clause gives me the result set I expect. It is showing people with changes to contracts(pay rise) but this is information that no one should be seeing, these are now the only records that need filtering out
EDIT
I have made some improvements and overcome the error messages now, but I am still getting people where pay rises have occured. Here is the amended query from the group by
group by
w1.Worker_ID, w1.Title, w1.FirstName, w1.Surname,w1.Gender, w1.DateofBirth,
dbo.[Contract].StartDate, manager, dbo.Grade.Discipline,dbo.Grade.GradeDescription, dbo.[Contract].ContractType_ID, w1.Worker_ID
Having
(((dbo.[Contract].StartDate BETWEEN #StartDateF AND #EndDateF)
AND COUNT(dbo.[Contract].Worker_ID) = 1)
OR
((dbo.[Contract].StartDate BETWEEN #StartDateF AND #EndDateF)
AND DATEDIFF(day, (SELECT MAX(EndDate)FROM dbo.[Contract] WHERE dbo.[Contract].Worker_ID = w1.Worker_ID), (SELECT MAX(StartDate)FROM dbo.[Contract] WHERE dbo.[Contract].Worker_ID = w1.Worker_ID))>1))
To get workers with more than one contract, you would use:
select c.workerID
from Contract c
group by c.workerID
having count(distinct contractID) > 1
It sounds, though, like you only want to count everything but the new start ones. You can do this with something like:
select w.workerID
from Contract c
where c.ContractType = 'New'
group by w.workerID
having count(distinct contractID) > 1
Because you didn't provide the details of what the tables look like, what sample input data looks like, and the results you want to achieve, this is about the best that can be done.
WHERE ( (dbo.[Contract].StartDate BETWEEN #StartDateF AND #EndDateF)AND dbo.[Contract].Worker_ID
IN (select worker_id from dbo.[Contract]
group by worker_id
having count(worker_id) = 1))
OR
((dbo.[Contract].StartDate BETWEEN #StartDateF AND #EndDateF)
AND DATEDIFF(day, (SELECT MAX(EndDate)FROM dbo.[Contract] WHERE dbo.[Contract].Worker_ID = w1.Worker_ID), (SELECT MAX(StartDate)FROM dbo.[Contract] WHERE dbo.[Contract].Worker_ID = w1.Worker_ID))>1
AND dbo.[Contract].Worker_ID = w1.Worker_ID )
Now works for me :)

SQLite/JDBC inner join

I have found what appears to be a bug in the SQLite JDBC driver, but I thought I'd see if someone could spot any boneheaded errors on my part. I have the following query:
SELECT
SKU_ATTR_VALUE.*,
Product.ProductID
FROM
SKU_ATTR_VALUE
INNER JOIN SKU
ON SKU_ATTR_VALUE.SkuID=SKU.SkuID
INNER JOIN Product
ON SKU.ProductID=Product.ProductID
WHERE Product.ProductID=?
Pretty simple. I can run this in the SQLite database browser, replacing the ? with 1, and it returns 18 rows, which is just what it should do. Only 18 rows match the condition. But when I run this in Java, and pass in the value 1, I get 817 values back. And that's not a Cartesian join; there are 864 possible values in SKU_ATTR_VALUE. The results I get back have at least one value for each record in Product too...so I really can't imagine what is happening.
I've been looking at this a while and I'm completely stumped. Googling it doesn't seem to turn anything up. Yes, I'm sure that I'm running the Java query against the same SQLite database as in the SQLite browser.
The name of the SQLite jar is sqlitejdbc-v056.jar. It is based on SQLite 3.6.14.2.
Here is the Java code that sets up the query:
String sql = "SELECT SKU_ATTR_VALUE.*, Product.ProductID " +
"FROM SKU_ATTR_VALUE " +
" INNER JOIN SKU ON SKU_ATTR_VALUE.SkuID=SKU.SkuID " +
" INNER JOIN Product ON SKU.ProductID=Product.ProductID " +
"WHERE Product.ProductID=?";
ps = conn.prepareStatement(sql);
ps.setInt(1, productID);
ResultSet rs = ps.executeQuery();
According to this document section "5.0 Joins" : you can try to rewrite your query like this :
SELECT
SKU_ATTR_VALUE.*,
Product.ProductID
FROM
Product, SKU, SKU_ATTR_VALUE
WHERE
Product.ProductID=?
AND SKU.ProductID=Product.ProductID
AND SKU_ATTR_VALUE.SkuID=SKU.SkuID

ASP.NET DataAdapter Query Not Valid While The Query Works

I started to use DataSet in my ASP.net web app like 6 months ago. It is a beautiful tool, allow me to rapidly develop MVC application without having to do all the dirty works in DB connection/queries.
But today I faced some weird problem. It started with this query:
select a.MR_PART_CODE as PART_CODE,
b.PART_DESC as PART_DESC,
b.PM_MAD_CAT_CODE as CATEGORY,
c.MPC_MIN_QTY as CAT_SS,
a.MR_MAX_LEAD_TIME as LEAD_TIME,
a.MR_MAD as MAD,
ROUND((a.MR_MAD * a.MR_MAX_LEAD_TIME)) as CAL_SS,
greatest(ROUND((a.MR_MAD * a.MR_MAX_LEAD_TIME)),c.MPC_MIN_QTY) as SS,
d.SOH as SOH,
d.SOO as SOO,
(select sum(back_order) from STK_REQUEST where part_code=b.part_code) as BO,
(d.SOH+a.MR_SOO) as AVAIL,
((d.SOH + a.MR_SOO)-greatest(ROUND((a.MR_MAD * a.MR_MAX_LEAD_TIME)),c.MPC_MIN_QTY)) as ROQ,
(d.SOH - greatest(ROUND((a.MR_MAD * a.MR_MAX_LEAD_TIME)),c.MPC_MIN_QTY) ) as VAR,
a.MR_REMARKS as REMARKS
from ROQ a, PART_MASTER b, MAD_PARTS_CATEGORY c, PART_STATS d
where a.MR_PART_CODE = b.PART_CODE
and d.PART_CODE = b.PART_CODE
and b.PM_MAD_CAT_CODE = c.MPC_CAT_CODE
and b.RETIRE_FLAG = 'N'
and a.mr_year = (select max(mr_year) from roq)
and a.mr_month = (select max(mr_month) from roq where mr_year= (select max(mr_year) from roq))
and a.mr_period = (select max(mr_period) from roq where mr_month=(select max(mr_month) from roq where mr_year= (select max(mr_year) from roq)) and mr_year= (select max(mr_year) from roq))
and greatest(ROUND((a.MR_MAD * a.MR_MAX_LEAD_TIME)),c.MPC_MIN_QTY) > d.SOH`
The query ran fine in Toad for Oracle, but apparently it fails when I tried to setup as a new query in DataAdapter object. It says something like "Error in list of function arguments: SELECT not recognized" to this line:
(select sum(back_order) from STK_REQUEST where part_code=b.part_code) as BO
What did I do wrong?
FYI, the database is Oracle.
It seems to be an exception from some ASP class trying to parse your SQL. There would be an ORA-xxxxx error number if the message came from Oracle.
You shouldn't put SQL like that in ASP. Create a view instead, perhaps it's ok then.

Resources