473,701 Members | 2,676 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

ExecuteScalar returns null

js
I am using the following C# code and T-SQL to get result object from a
SQL Server database. When my application runs, the ExecuteScalar
returns "10/24/2006 2:00:00 PM" if inserting a duplicated record. It
returns null for all other conditions. Does anyone know why? Does
anyone know how to get the output value? Thanks.

------ C# -----
aryParams = {'10/24/2006 2pm', '10/26/2006 3pm', 2821077, null};
object oRtnObject = null;
StoredProcComma ndWrapper =
myDb.GetStoredP rocCommandWrapp er(strStoredPro cName,aryParams );
oRtnObject = myDb.ExecuteSca lar(StoredProcC ommandWrapper);

------ T-SQL ---
ALTER PROCEDURE [dbo].[procmyCalendarI nsert]
@pBegin datetime,
@pEnd datetime,
@pUserId int,
@pOutput varchar(200) output
AS
BEGIN
SET NOCOUNT ON;

select * from myCalendar
where beginTime >= @pBegin and endTime <= @pEnd and userId = @pUserId

if @@rowcount <0
begin
print 'Path 1'
set @pOutput = 'Duplicated reservation'
select @pOutput as 'Result'
return -1
end
else
begin
print 'Path 2'
-- check if upperlimit (2) is reached
select rtrim(cast(begi nTime as varchar(30))) + ', ' +
rtrim(cast(endT ime as varchar(30)))
,count(rtrim(ca st(beginTime as varchar(30))) + ', ' +
rtrim(cast(endT ime as varchar(30))))
from myCalendar
group by rtrim(cast(begi nTime as varchar(30))) + ', ' +
rtrim(cast(endT ime as varchar(30)))
having count(rtrim(cas t(beginTime as varchar(30))) + ', ' +
rtrim(cast(endT ime as varchar(30)))) =2
and (rtrim(cast(beg inTime as varchar(30))) + ', ' +
rtrim(cast(endT ime as varchar(30))) =
rtrim(cast(@pBe gin as varchar(20)))+ ', ' + rtrim(cast(@pEn d as
varchar(20))))

-- If the @@rowcount is not equal to 0 then
-- at the time between @pBegin and @pEnd the maximum count of 2 is
reached

if @@rowcount <0
begin
print 'Path 3'
set @pOutput = '2 reservations are already taken for the hours'
select @pOutput as 'Result'
return -1
end
else
begin
print 'Path 4'
--safe to insert
insert dbo.myCalendar( beginTime, endTime,userId)
values (@pBegin, @pEnd, @pUserId)
if @@error = 0
begin
print 'Path 4:1 @@error=' + cast(@@error as varchar(1))
print 'Path 4:1 @@rowcount=' + cast(@@rowcount as varchar(1))
set @pOutput = 'Reservation succeeded'
select @pOutput as 'Result'
return 0
end
else
begin
print 'Path 4:2 @@rowcount=' + cast(@@rowcount as varchar(1))
set @pOutput = 'Failed to make reservation'
select @pOutput as 'Result'
return -1
end
end
end
END

Oct 24 '06 #1
1 14515
js wrote:
I am using the following C# code
There was no way for you to know it (except maybe by browsing through some
of the previous questions in this newsgroup before posting yours - always a
recommended practice) , but this is a classic ADO newsgroup. ADO.Net bears
very little resemblance to classic ADO so, while you may be lucky enough to
find a dotnet-knowledgeable person here who can answer your question, you
can eliminate the luck factor by posting your question to a group where
those dotnet-knowledgeable people hang out. I suggest
microsoft.publi c.dotnet.framew ork.adonet.

But read on:

and T-SQL to get result object from a
SQL Server database. When my application runs, the ExecuteScalar
returns "10/24/2006 2:00:00 PM" if inserting a duplicated record. It
returns null for all other conditions. Does anyone know why? Does
anyone know how to get the output value? Thanks.

------ C# -----
aryParams = {'10/24/2006 2pm', '10/26/2006 3pm', 2821077, null};
object oRtnObject = null;
StoredProcComma ndWrapper =
myDb.GetStoredP rocCommandWrapp er(strStoredPro cName,aryParams );
oRtnObject = myDb.ExecuteSca lar(StoredProcC ommandWrapper);

------ T-SQL ---
ALTER PROCEDURE [dbo].[procmyCalendarI nsert]
@pBegin datetime,
@pEnd datetime,
@pUserId int,
@pOutput varchar(200) output
AS
BEGIN
SET NOCOUNT ON;

select * from myCalendar
where beginTime >= @pBegin and endTime <= @pEnd and userId = @pUserId

if @@rowcount <0
This is extremely misguided. Not only is it grossly inefficient, retrieving
all the records that meet the requirements, it is also preventing you from
retrieving your output value. SQL Server does not send RETURN and OUTPUT
parameter values to the client until all resultsets are sent. The above
select statement is creating a resultset that wwill be sent to the client.

If you want to verify if records exist, use IF EXISTS, as in

IF EXISTS (select * from myCalendar
where beginTime >= @pBegin and endTime <= @pEnd and userId = @pUserId)

This is more efficient because it does not retrieve a resultset, it only
verifies that the records meeting therequirements exist. If you really want
a count of the records that meet the requirements (which does not seem to be
te case here) you should use:

declare @cnt int
Set @cnt= (select count(*) from myCalendar
where beginTime >= @pBegin and endTime <= @pEnd and userId = @pUserId)

Because the result is assigned to a variable, no resultset is created that
needs to be sent to the client.
begin
print 'Path 1'
set @pOutput = 'Duplicated reservation'
select @pOutput as 'Result'
return -1
end
else
begin
print 'Path 2'
-- check if upperlimit (2) is reached
select rtrim(cast(begi nTime as varchar(30))) + ', ' +
rtrim(cast(endT ime as varchar(30)))
,count(rtrim(ca st(beginTime as varchar(30))) + ', ' +
rtrim(cast(endT ime as varchar(30))))
from myCalendar
group by rtrim(cast(begi nTime as varchar(30))) + ', ' +
rtrim(cast(endT ime as varchar(30)))
having count(rtrim(cas t(beginTime as varchar(30))) + ', ' +
rtrim(cast(endT ime as varchar(30)))) =2
and (rtrim(cast(beg inTime as varchar(30))) + ', ' +
rtrim(cast(endT ime as varchar(30))) =
rtrim(cast(@pBe gin as varchar(20)))+ ', ' + rtrim(cast(@pEn d as
varchar(20))))
I'm not sure what the point of the above concatenation is: are you trying to
present a datetime in a particular format? If so, are you aware that
>
-- If the @@rowcount is not equal to 0 then
-- at the time between @pBegin and @pEnd the maximum count of 2 is
reached
You do realize that because of the intervening statements, the @@rowcount
function returns a different value than was returned the first time you used
it ... ? @@error and @@rowcount are only useful if used immediately after
the statement you wish to test. New statements cause these functions to
return new values.

Anyways, you already determined above that the records exist. Why bother
checking again?
>
if @@rowcount <0

Bob Barrows

--
Microsoft MVP - ASP/ASP.NET
Please reply to the newsgroup. This email account is my spam trap so I
don't check it very often. If you must reply off-line, then remove the
"NO SPAM"
Oct 25 '06 #2

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
3499
by: Max | last post by:
Anyone know why I'm always getting 0 returned? My stored procedure returns -1. Dim iErrorCode As Int32 iErrorCode = Convert.ToInt32(SqlHelper.ExecuteScalar(AppVars.strConn, _ "gpUpdateMember", _ Convert.ToInt32(lblMember_id.Text), _ -snip- -Max
7
12015
by: Neven Klofutar | last post by:
Hi, I have a problem with SqlHelper.ExecuteScalar ... When I try to execute SqlHelper.ExecuteScalar I get this message: "System.InvalidCastException: Object must implement IConvertible.". Help ... Thanx, Neven
3
10147
by: charliewest | last post by:
Hi - I need to detect when the ExecuteScalar() method of the cmd object returns NULL. I have tried the below code, however, it always returns false (this is to say, that ExecuteScalar never returns NULL when in fact it does): cmd.CommandText = "...SQL String goes here..."; cmd.CommandType = CommandType.Text; if (cmd.ExecuteScalar() == System.DBNull.Value) iScorecardId = 1;
2
2939
by: Julio Allegue | last post by:
I am getting the wrong Count(*) on vb.net using the ExecuteScalar . It returns all the rows. It doesn't seem to look at the WHERE clause. At the same time, I am getting the correct count on "SQL Enterprise Manager" or "SQL Query Analyser" using the same SQL statement. Thanks in advance. Julio. Here is the SQL statement plus the source to the GetNumOfRow sub.
8
22321
by: Earl | last post by:
What's the best way to check for null on an ExecuteScalar? The following would fire the command twice: if (cmd.ExecuteScalar() != null) { intContactID = Convert.ToInt32(cmd.ExecuteScalar()); }
2
5113
by: Randy Smith | last post by:
Hi, I've got some weird behavior happening within one of the datamappers. It all has to do with inserting a new row, and returning the Id of the row being entered. Here is what the code looks like that is getting "Object reference not set to an instance ..." run-time error:
2
3344
by: Manikandan | last post by:
Hi, I have a table with following data Tablename:details No(varchar) Name(varchar) Updated(Datetime) 1 mm 10/10/2006 2 nn 02/12/2005 3 kk NULL I'm using executescalar to get the updated values from the table
1
5725
by: Manikandan | last post by:
Hi, I have a table with following data Tablename:details No(varchar) Name(varchar) Updated(Datetime) 1 mm 10/10/2006 2 nn 02/12/2005 3 kk NULL I'm using executescalar to get the updated values from the table
2
3067
by: MDB | last post by:
Hello All, what is the correct / proper way to check for null values in the ExecuteScalar. System.DBNull.Value, Null or both?
0
8649
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9221
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9082
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8975
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8933
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
4410
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4661
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3102
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2398
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.