473,379 Members | 1,530 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,379 software developers and data experts.

SQL problem: scope_identity() returning dbnull in insert statement.

INSERT INTO dbo.Transmission
(TransmissionDate, TransmissionDirection,
Filename, TransmittedData)
VALUES
(@TransmissionDate,@TransmissionDirection,@Filenam e,@TransmittedData);
SELECT @retVal = SCOPE_IDENTITY();

Pretty simple. There is an additional TransmissionID column that is
an autonumber and primary key. @retVal is always null in my table
adapter function, where I'm setting @retval (in the Parameters
collection of the typed dataset tableadapter) to be an output
parameter of type in.

Mar 21 '07 #1
8 13912
hi Martin,

Martin Z wrote:
INSERT INTO dbo.Transmission
(TransmissionDate, TransmissionDirection,
Filename, TransmittedData)
VALUES
(@TransmissionDate,@TransmissionDirection,@Filenam e,@TransmittedData);
SELECT @retVal = SCOPE_IDENTITY();

Pretty simple. There is an additional TransmissionID column that is
an autonumber and primary key. @retVal is always null in my table
adapter function, where I'm setting @retval (in the Parameters
collection of the typed dataset tableadapter) to be an output
parameter of type in.
Why not sending this as a SQL batch?
Otherwise how is your function/procedure defined?
Are you using SET NOCOUNT ON?
How do you call this function?
mfG
--stefan <--
Mar 21 '07 #2
On Mar 21, 11:13 am, Stefan Hoffmann <stefan.hoffm...@explido.de>
wrote:
hi Martin,

Martin Z wrote:
INSERT INTO dbo.Transmission
(TransmissionDate, TransmissionDirection,
Filename, TransmittedData)
VALUES
(@TransmissionDate,@TransmissionDirection,@Filenam e,@TransmittedData);
SELECT @retVal = SCOPE_IDENTITY();
Pretty simple. There is an additional TransmissionID column that is
an autonumber and primary key. @retVal is always null in my table
adapter function, where I'm setting @retval (in the Parameters
collection of the typed dataset tableadapter) to be an output
parameter of type in.

Why not sending this as a SQL batch?
Otherwise how is your function/procedure defined?
Are you using SET NOCOUNT ON?
How do you call this function?

mfG
--stefan <--
As I said, it's an SQL Query procedure defined in the Typed
TableAdapter for the Transmission table. It's being used in several
different places in my app, which is a thick-client that talks
directly to the database. And no, I'm not using SET NOCOUNT ON.

Mar 21 '07 #3
hi Martin,

Martin Z wrote:
>Otherwise how is your function/procedure defined?
As I said, it's an SQL Query procedure defined in the Typed
TableAdapter for the Transmission table.
Which still leaves the question above unanswered. Can you post the
complete defintitions (SQL, C#) that are involved?
mfG
--stefan <--
Mar 21 '07 #4
On Mar 21, 11:58 am, Stefan Hoffmann <stefan.hoffm...@explido.de>
wrote:
hi Martin,

Martin Z wrote:
Otherwise how is your function/procedure defined?
As I said, it's an SQL Query procedure defined in the Typed
TableAdapter for the Transmission table.

Which still leaves the question above unanswered. Can you post the
complete defintitions (SQL, C#) that are involved?

mfG
--stefan <--
>From the XSD, the InsertReturnCommand XSD
<DbSource ConnectionRef="DmtConnectionString (Settings)"
DbObjectName="" DbObjectType="Unknown" GenerateShortCommands="True"
GeneratorSourceName="InsertReturnTransmissionID" Modifier="Public"
Name="InsertReturnTransmissionID" QueryType="NoData"
ScalarCallRetval="System.Object, mscorlib, Version=2.0.0.0,
Culture=neutral, PublicKeyToken=b77a5c561934e089"
UseOptimisticConcurrency="True" UserGetMethodName="GetDataBy"
UserSourceName="InsertReturnTransmissionID">
<InsertCommand>
<DbCommand CommandType="Text" ModifiedByUser="True">
<CommandText>INSERT INTO dbo.Transmission
(TransmissionDate, TransmissionDirection,
Filename, TransmittedData)
VALUES
(@TransmissionDate,@TransmissionDirection,@Filenam e,@TransmittedData);
SELECT @retVal = SCOPE_IDENTITY();</CommandText>
<Parameters>
<Parameter AllowDbNull="True"
AutogeneratedName="TransmissionDate" ColumnName="TransmissionDate"
DataSourceName="Dmt.dbo.Transmission" DataTypeServer="datetime"
DbType="DateTime" Direction="Input" ParameterName="@TransmissionDate"
Precision="0" ProviderType="DateTime" Scale="0" Size="8"
SourceColumn="TransmissionDate" SourceColumnNullMapping="False"
SourceVersion="Current">
</Parameter>
<Parameter AllowDbNull="False"
AutogeneratedName="TransmissionDirection"
ColumnName="TransmissionDirection"
DataSourceName="Dmt.dbo.Transmission" DataTypeServer="int"
DbType="Int32" Direction="Input"
ParameterName="@TransmissionDirection" Precision="0"
ProviderType="Int" Scale="0" Size="4"
SourceColumn="TransmissionDirection" SourceColumnNullMapping="False"
SourceVersion="Current">
</Parameter>
<Parameter AllowDbNull="True"
AutogeneratedName="Filename" ColumnName="Filename"
DataSourceName="Dmt.dbo.Transmission" DataTypeServer="varchar(128)"
DbType="AnsiString" Direction="Input" ParameterName="@Filename"
Precision="0" ProviderType="VarChar" Scale="0" Size="128"
SourceColumn="Filename" SourceColumnNullMapping="False"
SourceVersion="Current">
</Parameter>
<Parameter AllowDbNull="False"
AutogeneratedName="TransmittedData" ColumnName="TransmittedData"
DataSourceName="Dmt.dbo.Transmission" DataTypeServer="text"
DbType="AnsiString" Direction="Input" ParameterName="@TransmittedData"
Precision="0" ProviderType="Text" Scale="0" Size="2147483647"
SourceColumn="TransmittedData" SourceColumnNullMapping="False"
SourceVersion="Current">
</Parameter>
<Parameter AllowDbNull="False"
AutogeneratedName="" DataSourceName="" DbType="Int32"
Direction="Output" ParameterName="@retVal" Precision="0"
ProviderType="Int" Scale="0" Size="0" SourceColumnNullMapping="False"
SourceVersion="Current">
</Parameter>
</Parameters>
</DbCommand>
</InsertCommand>
</DbSource>

which autogenerates the code:

[System.Diagnostics.DebuggerNonUserCodeAttribute()]

[System.ComponentModel.Design.HelpKeywordAttribute( "vs.data.TableAdapter")]

[System.ComponentModel.DataObjectMethodAttribute(Sy stem.ComponentModel.DataObjectMethodType.Insert,
false)]
public virtual int
InsertReturnTransmissionID(System.Nullable<System. DateTime>
TransmissionDate, int TransmissionDirection, string Filename, string
TransmittedData, out int retVal) {
System.Data.SqlClient.SqlCommand command =
this.CommandCollection[2];
if ((TransmissionDate.HasValue == true)) {
command.Parameters[0].Value = ((System.DateTime)
(TransmissionDate.Value));
}
else {
command.Parameters[0].Value = System.DBNull.Value;
}
command.Parameters[1].Value = ((int)
(TransmissionDirection));
if ((Filename == null)) {
command.Parameters[2].Value = System.DBNull.Value;
}
else {
command.Parameters[2].Value = ((string)(Filename));
}
if ((TransmittedData == null)) {
throw new
System.ArgumentNullException("TransmittedData");
}
else {
command.Parameters[3].Value = ((string)
(TransmittedData));
}
System.Data.ConnectionState previousConnectionState =
command.Connection.State;
if (((command.Connection.State &
System.Data.ConnectionState.Open)
!= System.Data.ConnectionState.Open)) {
command.Connection.Open();
}
int returnValue;
try {
returnValue = command.ExecuteNonQuery();
}
finally {
if ((previousConnectionState ==
System.Data.ConnectionState.Closed)) {
command.Connection.Close();
}
}
if (((command.Parameters[4].Value == null)
|| (command.Parameters[4].Value.GetType() ==
typeof(System.DBNull)))) {
throw new System.Data.StrongTypingException("The value
for parameter \'retVal\' is DBNull.", null);
}
else {
retVal = ((int)(command.Parameters[4].Value));
}
return returnValue;
}

for the table

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].
[FK_Request_TransmissionResponse]') and OBJECTPROPERTY(id,
N'IsForeignKey') = 1)
ALTER TABLE [dbo].[Request] DROP CONSTRAINT
FK_Request_TransmissionResponse
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].
[FK_Request_TransmissionSent]') and OBJECTPROPERTY(id,
N'IsForeignKey') = 1)
ALTER TABLE [dbo].[Request] DROP CONSTRAINT
FK_Request_TransmissionSent
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].
[Transmission]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[Transmission]
GO

CREATE TABLE [dbo].[Transmission] (
[TransmissionID] [int] IDENTITY (1, 1) NOT NULL ,
[TransmissionDate] [datetime] NULL ,
[TransmissionDirection] [int] NOT NULL ,
[Filename] [varchar] (128) COLLATE SQL_Latin1_General_CP1_CI_AS
NULL ,
[TransmittedData] [text] COLLATE SQL_Latin1_General_CP1_CI_AS NOT
NULL ,
[CreatedBy] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS
NULL ,
[CreatedMoment] [datetime] NULL ,
[ModifiedBy] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS
NULL ,
[ModifiedMoment] [datetime] NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO

I'm always hitting the " throw new
System.Data.StrongTypingException("The value for parameter \'retVal\'
is DBNull.", null);" problem.

Is there any case where a SCOPE_IDENTITY(); will return null just
after an insert?

Mar 21 '07 #5
hi Martin,

Martin Z wrote:
Is there any case where a SCOPE_IDENTITY(); will return null just
after an insert?
Yes, when no IDENTITY value was generated in your current scope.

Are there any constraints active on your table? Try to execute your SQL
manually in the Query Analyzer. Does it work?

mfG
--stefan <--
Mar 21 '07 #6
On Mar 21, 12:33 pm, Stefan Hoffmann <stefan.hoffm...@explido.de>
wrote:
hi Martin,

Martin Z wrote:
Is there any case where a SCOPE_IDENTITY(); will return null just
after an insert?

Yes, when no IDENTITY value was generated in your current scope.

Are there any constraints active on your table? Try to execute your SQL
manually in the Query Analyzer. Does it work?

mfG
--stefan <--
I can execute manually in the Query Analyzer after replacing all the
variables with immediate data and converting the "select @reval =
SCOPE_IDENTITY()" into "select SCOPE_IDENTITY()", which inserts the
row but returns an empty resultset.

Mar 21 '07 #7
hi Martin,

Martin Z wrote:
>>Is there any case where a SCOPE_IDENTITY(); will return null just
after an insert?
Yes, when no IDENTITY value was generated in your current scope.
Are there any constraints active on your table? Try to execute your SQL
manually in the Query Analyzer. Does it work?
I can execute manually in the Query Analyzer after replacing all the
variables with immediate data and converting the "select @reval =
SCOPE_IDENTITY()" into "select SCOPE_IDENTITY()", which inserts the
row but returns an empty resultset.
This is odd. When there is no instead of trigger active, then you must
have an error somewhere in your TableAdapter. But i can't see it right
now, sorry.
mfG
--stefan <--
Mar 22 '07 #8
On Mar 22, 5:48 am, Stefan Hoffmann <stefan.hoffm...@explido.de>
wrote:
hi Martin,

Martin Z wrote:
>Is there any case where a SCOPE_IDENTITY(); will return null just
after an insert?
Yes, when no IDENTITY value was generated in your current scope.
Are there any constraints active on your table? Try to execute your SQL
manually in the Query Analyzer. Does it work?
I can execute manually in the Query Analyzer after replacing all the
variables with immediate data and converting the "select @reval =
SCOPE_IDENTITY()" into "select SCOPE_IDENTITY()", which inserts the
row but returns an empty resultset.

This is odd. When there is no instead of trigger active, then you must
have an error somewhere in your TableAdapter. But i can't see it right
now, sorry.

mfG
--stefan <--
Well, I foudn a work around (used IDENT_CURRENT and did it as two
seperate actions within a transaction)... but I just found out my DBA
had some cruel-and-unusual auditing triggers involved anyways that may
have been contributing to it (and other) bugs.

Thanks for all your help and suggestions.

-- Martin

Mar 22 '07 #9

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

Similar topics

3
by: J. Muenchbourg | last post by:
The block of code below shows how I am inserting field values into my dbase table: strSQLStatement = "INSERT INTO tblArticles (handid,ArticleDate,sport,articleheader, fpick,articleText) "_ &...
2
by: mvr | last post by:
Hi all I are using IIS 5.0, Oracle 8.1. I am having problem with the following Insert Statement when used on Production Web server with SSL(https://...., Verisign). This doesn't occur...
4
by: fip | last post by:
Hi, On DB2 7.1.2 on MVS OS 390, when I tried to do an insert with multiple row contents in the values clause: insert into table11 values('aaaa', 'fa'), ('bbbb', 'fb') I got the error: ...
10
by: Mike | last post by:
I know this sounds strange but I am at a loss. I am calling a simple funtion that opens a connection to a SQL Server 2000 database and executes an Insert Statement. private void...
3
by: alexmaster_2004 | last post by:
hi i have made an application using C# that access sql2000. this application is just used to insert data to the database. i use something like this in my code: // string colmnA = TextBox1.Text;...
4
by: kd | last post by:
Hi All, I have a datetime column in a table on the SQL database. I need to insert values into the datetime column from vb.net code. Here is my code: dim nameval, str, qry as string nameval =...
7
by: Cindy H | last post by:
Hi I'm having a problem getting the insert statement correct for an Access table I'm using. The Access table uses an autonumber for the primary key. I have tried this: INSERT INTO Tournaments...
3
by: rhaazy | last post by:
Using ms sql 2000 I have 2 tables. I have a table which has information regarding a computer scan. Each record in this table has a column called MAC which is the unique ID for each Scan. The...
0
by: macupryk | last post by:
{System.Data.SqlClient.SqlException: The INSERT statement conflicted with the FOREIGN KEY constraint "FK_ProjectResponse__ProjectQuestionId". The conflict occurred in database "RG_ProjectData", table...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

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.