473,623 Members | 2,790 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How can I INSERT w/Constraints in other tables?

This:

string strSQL2 = "INSERT INTO tblTravelDetail Member(memberId , " +
" TravelDetailUpl ineId, " +
" rankId, " +
" TravelDetailId, " +
" CreatedDateTime , " +
" Operator) " +
"VALUES ('" + insertString2 + "', " +
" '" + insertString3 + "', " +
" '" + insertString4 + "', " +
" '" + insertString5 + "', " +
" '" + insertString6 + "', " +
" '" + insertString7 + "')";

Here is the tblTravelDetail Member:
CREATE TABLE [tblTravelDetail Member] (
[TravelDetailUpl ineId] [int] NOT NULL ,
[TravelDetailId] [int] NOT NULL ,
[TravelDetailMem berTypeId] [int] NOT NULL ,
[memberId] [bigint] NOT NULL ,
[rankId] [int] NOT NULL ,
[CreatedDateTime] [datetime] NOT NULL ,
[Operator] [nvarchar] (100) COLLATE SQL_Latin1_Gene ral_CP1_CI_AS NOT
NULL ,
CONSTRAINT [PK_tblTravelDet ailMember] PRIMARY KEY CLUSTERED
(
[TravelDetailUpl ineId]
) ON [PRIMARY] ,
CONSTRAINT [FK_tblTravelDet ailMember_tblTr avelDetail] FOREIGN KEY
(
[TravelDetailId]
) REFERENCES [tblTravelDetail] (
[TravelDetailId]
),
CONSTRAINT [FK_tblTravelDet ailMember_tblTr avelDetailMembe rType]
FOREIGN KEY
(
[TravelDetailMem berTypeId]
) REFERENCES [tblTravelDetail MemberType] (
[TravelDetailMem berTypeId]
)
) ON [PRIMARY]
GO

I get these errors:

Additional information: INSERT statement conflicted with COLUMN FOREIGN
KEY
constraint 'FK_tblTravelDe tailMember_tblT ravelDetailMemb erType'. The
conflict
occurred in database 'tsNess', table 'tblTravelDetai lMemberType',
column
'TravelDetailMe mberTypeId'.

Additional information: Cannot insert the value NULL into column
'TravelDetailMe mberTypeId', table 'tsNess.dbo.tbl TravelDetailMem ber';
column does not allow nulls. INSERT fails.

Here is the table I am not doing an entry on:
CREATE TABLE [tblTravelDetail MemberType] (
[TravelDetailMem berTypeId] [int] NOT NULL ,
[Description] [nvarchar] (100) COLLATE SQL_Latin1_Gene ral_CP1_CI_AS
NOT NULL ,
[CreatedDateTime] [datetime] NOT NULL ,
[Operator] [nvarchar] (100) COLLATE SQL_Latin1_Gene ral_CP1_CI_AS NOT
NULL ,
CONSTRAINT [PK_tblTravelDet ailMemberType] PRIMARY KEY CLUSTERED
(
[TravelDetailMem berTypeId]
) ON [PRIMARY]
) ON [PRIMARY]
GO

How can I do an INSERT into the tblTravelDetail Member table if it won't
let me and what will I have to do in order to do this please?
Thanks,
Trint

Nov 17 '05 #1
7 1937
trint wrote:
This would probably be better on one of the SQL groups but

See In-line
This:

string strSQL2 = "INSERT INTO tblTravelDetail Member(memberId , " +
" TravelDetailUpl ineId, " +
" rankId, " +
" TravelDetailId, " +
" CreatedDateTime , " +
" Operator) " +
"VALUES ('" + insertString2 + "', " +
" '" + insertString3 + "', " +
" '" + insertString4 + "', " +
" '" + insertString5 + "', " +
" '" + insertString6 + "', " +
" '" + insertString7 + "')";

You have a constraint that says that the
tblTravelDetail Member.TravelDe tailMemberTypeI d must exist in the
tblTravelDetail MemberType.Trav elDetailMemberT ypeId column.
You are not specifying a value for this column in your insert statement
therefore it will use the default value or null if no default is defined.

Either specify a value for TravelDetailMem berTypeId (recommended) in
your insert statement or define a default for this column.

HTH
JB
Here is the tblTravelDetail Member:
CREATE TABLE [tblTravelDetail Member] (
[TravelDetailUpl ineId] [int] NOT NULL ,
[TravelDetailId] [int] NOT NULL ,
[TravelDetailMem berTypeId] [int] NOT NULL ,
[memberId] [bigint] NOT NULL ,
[rankId] [int] NOT NULL ,
[CreatedDateTime] [datetime] NOT NULL ,
[Operator] [nvarchar] (100) COLLATE SQL_Latin1_Gene ral_CP1_CI_AS NOT
NULL ,
CONSTRAINT [PK_tblTravelDet ailMember] PRIMARY KEY CLUSTERED
(
[TravelDetailUpl ineId]
) ON [PRIMARY] ,
CONSTRAINT [FK_tblTravelDet ailMember_tblTr avelDetail] FOREIGN KEY
(
[TravelDetailId]
) REFERENCES [tblTravelDetail] (
[TravelDetailId]
),
CONSTRAINT [FK_tblTravelDet ailMember_tblTr avelDetailMembe rType]
FOREIGN KEY
(
[TravelDetailMem berTypeId]
) REFERENCES [tblTravelDetail MemberType] (
[TravelDetailMem berTypeId]
)
) ON [PRIMARY]
GO

I get these errors:

Additional information: INSERT statement conflicted with COLUMN FOREIGN
KEY
constraint 'FK_tblTravelDe tailMember_tblT ravelDetailMemb erType'. The
conflict
occurred in database 'tsNess', table 'tblTravelDetai lMemberType',
column
'TravelDetailMe mberTypeId'.

Additional information: Cannot insert the value NULL into column
'TravelDetailMe mberTypeId', table 'tsNess.dbo.tbl TravelDetailMem ber';
column does not allow nulls. INSERT fails.

Here is the table I am not doing an entry on:
CREATE TABLE [tblTravelDetail MemberType] (
[TravelDetailMem berTypeId] [int] NOT NULL ,
[Description] [nvarchar] (100) COLLATE SQL_Latin1_Gene ral_CP1_CI_AS
NOT NULL ,
[CreatedDateTime] [datetime] NOT NULL ,
[Operator] [nvarchar] (100) COLLATE SQL_Latin1_Gene ral_CP1_CI_AS NOT
NULL ,
CONSTRAINT [PK_tblTravelDet ailMemberType] PRIMARY KEY CLUSTERED
(
[TravelDetailMem berTypeId]
) ON [PRIMARY]
) ON [PRIMARY]
GO

How can I do an INSERT into the tblTravelDetail Member table if it won't
let me and what will I have to do in order to do this please?
Thanks,
Trint

Nov 17 '05 #2
John,
I've got most of it figured out now except this:

@@IDENTITY AS 'Identity'
How do I get the 'Identity' into a string?
Thanks,
Trint

.Net programmer
tr***********@g mail.com

*** Sent via Developersdex http://www.developersdex.com ***
Nov 17 '05 #3
Trint Smith wrote:
John,
I've got most of it figured out now except this:

@@IDENTITY AS 'Identity'
How do I get the 'Identity' into a string?
Thanks,
Trint


@@IDENTITY will select the last identity (this is database wide and not
limited to a specific table (AFAIK).
Why do you need this?
What you want is a TravelDetailMem berTypeId from the
tblTravelDetail MemberType table.

Lets say you are filling these details out on a form.
You create controls for all the values.
You will probably have a combo box that lists all the
TravelDetailMem berType names from the tblTravelDetail MemberType table.

Then when the user presses save, you will want to get the
TravelDetailMem berTypeId from the combo box and pass that as part of
your insert statement so it saves the correct TravelDetailMem berType value.

Also, TravelDetailMem berTypeId is not defined as an IDENTITY column
(AutoIncrement) so @@IDENTITY will have no bearing on this.

JB
Nov 17 '05 #4
John,
It is defined in another table:
CREATE TABLE [tblTravelDetail] (
[TravelDetailId] [int] IDENTITY (1, 1) NOT NULL ,
[MemberId] [bigint] NOT NULL ,
[Comments] [nvarchar] (100) COLLATE SQL_Latin1_Gene ral_CP1_CI_AS NULL ,
[TravelEventId] [int] NOT NULL ,
[OrderId] [int] NULL ,
[ItemID] [nvarchar] (15) COLLATE SQL_Latin1_Gene ral_CP1_CI_AS NULL ,
[PeriodID] [int] NULL ,
[CreatedDateTime] [datetime] NOT NULL ,
[Operator] [nvarchar] (100) COLLATE SQL_Latin1_Gene ral_CP1_CI_AS NOT
NULL ,
CONSTRAINT [PK_tblTravelDet ail] PRIMARY KEY CLUSTERED
(
[TravelDetailId]
) ON [PRIMARY] ,
CONSTRAINT [FK_tblTravelDet ail_tblTravelEv ent] FOREIGN KEY
(
[TravelEventId]
) REFERENCES [tblTravelEvent] (
[TravelEventId]
)
) ON [PRIMARY]
GO

And here is my code on this table so far (That don't get the identity I
might add):

string strSQL5 = "INSERT INTO tblTravelDetail (MemberId, " +
" Comments, " +
" TravelEventId, " +
" OrderId, " +
" ItemID, " +
" PeriodID, " + //here is where we do the PeriodID lookup
calculation
" CreatedDateTime , " +
" Operator) " +
"VALUES ('" + deiinsertString 2 + "', " +
" '" + deiinsertString 3 + "', " +
" '" + eiinsertString1 + "', " +
" '" + deiinsertString 5 + "', " +
" '" + deiinsertString 6 + "', " +
" '" + deiinsertString 7 + "', " +
" '" + deiinsertString 8 + "', " +
" '" + insertString7 + "') " +
"SELECT @@IDENTITY AS 'Identity' ";

displayIdentity = Convert.ToStrin g(rs5.Fields["Identity"].Value);

Thanks,
Trint

..Net programmer
tr***********@g mail.com

*** Sent via Developersdex http://www.developersdex.com ***
Nov 17 '05 #5
Trint Smith wrote:

This is a totally different table definition from your first post.
What is the question?

If it is the same error as earlier,
You must supply a value that exists in your foreign key table/column for
any foreign key columns.
tblTravelDetail .TravelEventId is your foreign key column.
You must supply a value for this column that exists in the
tblTravelEvent. TravelEventId column.

JB

John,
It is defined in another table:
CREATE TABLE [tblTravelDetail] (
[TravelDetailId] [int] IDENTITY (1, 1) NOT NULL ,
[MemberId] [bigint] NOT NULL ,
[Comments] [nvarchar] (100) COLLATE SQL_Latin1_Gene ral_CP1_CI_AS NULL ,
[TravelEventId] [int] NOT NULL ,
[OrderId] [int] NULL ,
[ItemID] [nvarchar] (15) COLLATE SQL_Latin1_Gene ral_CP1_CI_AS NULL ,
[PeriodID] [int] NULL ,
[CreatedDateTime] [datetime] NOT NULL ,
[Operator] [nvarchar] (100) COLLATE SQL_Latin1_Gene ral_CP1_CI_AS NOT
NULL ,
CONSTRAINT [PK_tblTravelDet ail] PRIMARY KEY CLUSTERED
(
[TravelDetailId]
) ON [PRIMARY] ,
CONSTRAINT [FK_tblTravelDet ail_tblTravelEv ent] FOREIGN KEY
(
[TravelEventId]
) REFERENCES [tblTravelEvent] (
[TravelEventId]
)
) ON [PRIMARY]
GO

And here is my code on this table so far (That don't get the identity I
might add):

string strSQL5 = "INSERT INTO tblTravelDetail (MemberId, " +
" Comments, " +
" TravelEventId, " +
" OrderId, " +
" ItemID, " +
" PeriodID, " + //here is where we do the PeriodID lookup
calculation
" CreatedDateTime , " +
" Operator) " +
"VALUES ('" + deiinsertString 2 + "', " +
" '" + deiinsertString 3 + "', " +
" '" + eiinsertString1 + "', " +
" '" + deiinsertString 5 + "', " +
" '" + deiinsertString 6 + "', " +
" '" + deiinsertString 7 + "', " +
" '" + deiinsertString 8 + "', " +
" '" + insertString7 + "') " +
"SELECT @@IDENTITY AS 'Identity' ";

displayIdentity = Convert.ToStrin g(rs5.Fields["Identity"].Value);

Thanks,
Trint

.Net programmer
tr***********@g mail.com

*** Sent via Developersdex http://www.developersdex.com ***

Nov 17 '05 #6
This doesn't answer your immediate question, but it'll make your life a
whole lot easier when embedding SQL Statements into your CSharp code:

string strSQL5 = @"INSERT INTO tblTravelDetail
(
MemberID
, Comments
, TravelEventID
, ...
)
VALUES
(
@MemberID
, @Comments
, @TravelEventID
)";
cmd.Parameters. Add("@MemberID" , deiinsertString 2);
cmd.Parameters. Add("@Comments" , deiinsertString 3);
cmd.Parameters. Add("@TravelEve ntID", deiinsertString 3);

The @ literal string operator prefix allows you to write multiline
strings. Very useful if you must embed SQL statements in your C# code.
Also, using parameterized SQL Statements is very important, not only
for security (it prevents SQL injection), but also for performance as
it increases the chance of your execution plan being reused by SQL
Server. See SQL Server's Books Online for sp_executesql, which is what
ADO.NET uses behind the scenes.

-Alan

Nov 17 '05 #7
Thanks Alan,
The only thing I need though at this point, is how can I get the last
Identity after an insert, using my c# app?
Thanks,
Trint

Alan Samet wrote:
This doesn't answer your immediate question, but it'll make your life a whole lot easier when embedding SQL Statements into your CSharp code:

string strSQL5 = @"INSERT INTO tblTravelDetail
(
MemberID
, Comments
, TravelEventID
, ...
)
VALUES
(
@MemberID
, @Comments
, @TravelEventID
)";
cmd.Parameters. Add("@MemberID" , deiinsertString 2);
cmd.Parameters. Add("@Comments" , deiinsertString 3);
cmd.Parameters. Add("@TravelEve ntID", deiinsertString 3);

The @ literal string operator prefix allows you to write multiline
strings. Very useful if you must embed SQL statements in your C# code. Also, using parameterized SQL Statements is very important, not only
for security (it prevents SQL injection), but also for performance as
it increases the chance of your execution plan being reused by SQL
Server. See SQL Server's Books Online for sp_executesql, which is what ADO.NET uses behind the scenes.

-Alan


Nov 17 '05 #8

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

Similar topics

2
1779
by: Tom Gao | last post by:
I have a problem. The project that I'm working on requires me to duplicate records. As in a series of records are entered into the system the user then click on a button to make these as 'Templates' so that they would not have to re-enter alot of the information. So from a db perspective I would have to re-insert these records into the database. The problem is there're over 20 tables and the relationship is complex. Is there a way to copy...
3
1391
by: trint | last post by:
Three tables (all new, no data) will receive data from dBase and be transposed into them...All three have auto generated IDENTITY columns and pk and fk constraints. Can someone provide me with an understandible sample? Thanks, Trint
10
6961
by: serge | last post by:
I am doing a little research on Google about this topic and I ran into this thread: http://groups.google.com/group/microsoft.public.sqlserver.programming/browse_thread/thread/63cce060ff152dcc/1dc13d4ee6758966?lnk=st&q=difference+constraint+sql+defaults&rnum=14#1dc13d4ee6758966 I read SQL Server MVP Louis Davidson's post saying: "Actually they are more likely to drop the concept of bound defaults. Constraints are the standard way to do...
2
1637
by: trint | last post by:
I am trying to insert a record, but I have to get an automatically created identity field at the same time to do this. string strSQL2 = "INSERT INTO tblTravelDetail(MemberID, " + " TravelEventID, " + " CreatedDateTime, " + " Operator) " + "VALUES ('" + TxtMLV.Text.Trim() + "', " + " '" + TxtEventID+ "', " + " '" + TxtDATE.Text.Trim() + "', " +
1
1756
by: Philippe Lang | last post by:
Hello, What is the best method to debug a database that *sometimes* gets locked in the INSERT mode? ('ps -afx | grep postgres' shows me a process that is freezed in INSERT mode.) Thanks Philippe
20
6086
by: John Bailo | last post by:
I have a c# program that loops through a table on a DB2 database. On each iteration it assigns data to values in the SqlParameter collection. The command text is an INSERT statement to a Sql Server database, run with an .ExecuteQuery I enclosed the loop in a SqlTransaction and commit it at the end. I timed the program and it inserts about 70 records a second...which I think is sort of slow...so I set up some Debug.WriteLines to...
8
3506
by: nano2k | last post by:
Hi Shortly, I keep invoices in a table. Occasionally, someone will fire the execution of a stored procedure (SP) that performs several UPDATEs against (potentially) all invoices OLDER than a date that is supplied to the SP as a parameter. The SP is usually a lengthy process (it takes at least 30 mins). The problem is that SQL server 2000 Dev Edition doesn't allow me to insert new invoices that are "younger", while the SP is executing....
7
14599
by: annecarterfredi | last post by:
I need to increase the length of CD column from char(5) to char(7) in DB2 V8.2. I am doing it this way: 1. create new_table with CD char(7) 2. do 'insert into new_table select * from Original_table' 3. drop all constraints/dependent objects on the Original_table 4. rename Original_table to Original_table_Old 5. rename new_table to Original_table 6. create all constraints and dependent objects on the Original_table
10
8206
by: teddysnips | last post by:
SQL Server 2000 (DDL below) If I try to run this code in QA: SET IDENTITY_INSERT tblAdminUsers ON INSERT INTO tblAdminUsers (fldUserID, fldUsername, fldPassword, fldFullname,
2
45863
by: mivey4 | last post by:
Okay I have 2 tables: Table A - holds a list of new hardware serial numbers and their corresponding model (no constraints or indexes) Table B - holds a distinct list of current serial numbers and the corresponding model numbers (primary key on serial_numbers) Since Table A has no constraints duplicates may exist. Additionally, table A is actually an Excel spreadsheet that is maintained by an employee that records new hardware as...
0
8163
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
8667
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...
1
8324
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
8469
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...
1
6104
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5561
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
2597
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
1
1775
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1471
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.