.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
Gaurav Pal
Post New Web Links

Inserting foreign key value using subquery

Posted By:      Posted Date: October 04, 2010    Points: 0   Category :Sql Server



I'm playing around with a training-wheel database.  I have a table that stores magazine subscription info.  I have a lookup table that stores the delivery period, ie. 'weekly', 'monthly', etc.  I have a primary key ID field in tblPeriods and a foreign key field in the main table, tblMags.  I want to insert data into tblMags without having to memorize the correlation between the period key and the period itself.  Here's what I tried first:


 ( vcName,
  fkPeriodID )
 ( 'The New Yorker',
  (SELECT  tblPeriods_ID FROM tblPeriods
   WHERE vcPeriod = 'Weekly'));


This gives the following message:


Server: Msg 1046, Level 15, State 1, Line 6
Subqueries are not allowed in this context. Only scalar expressions are allowed.


I'm thinking there must be a way to insert data like this and take advantage of a foreign key relationship without looking up a value each time.  Any ideas?






View Complete Post

More Related Resource Links

Inserting Foreign Key Value if it doesn't exist?

I am inserting a record and want to set the value for a foreign key but I am getting an error - I initally thought that it would insert it if it didn't exist but I must be wrong and want to confirm that I need to check all values and make a record for them if they don't exist... here's what I am trying to do - does his make sense?var newAllPart = new Part();                newAllPart.PartNumber = partNumber;                newAllPart.Manufacturer.ManufacturerName = partManufacturer; // error here if the Manufacturer doesn't exists already                newAllPart.PartType.PartTypeName = partType;                newAllPart.Category.CategoryName = partCategory;                newAllPart.DateCreated = DateTime.Now;                newAllPart.UserCreated = userCreated;                newAllPart.Package.PackageName = partPackage;    

Inserting null value into foreign key table with allow null enabled


Hey guys, 

I have 2 table Table A, Table B.

Table A - Parent Table

ID - Uniqueidentifier not null(PK)

Table B -Child Table              

ID - uniqueidentifier null(FK, TableA)

I have a stored procedure to insert data into Table B, but when I tried to insert a null value into column ID of table B, this error came up:

The INSERT statement conflicted with the FOREIGN KEY constraint "FK_tableB_tableA". The conflict occurred in database "database name", table "table A", column 'ID'.

The statement has been terminated.

The insert statement in asp.net is like so:

sqlcommand.parameter.add(New Sqlparameter("ID", Nothing))

I am guessing adding nothing to the null value column is the problem, but i don't know how to fix it... can any1 help me?


The INSERT statement conflicted with the FOREIGN KEY constraint "FK_tableB_tableA". The co

Inserting InvoiceID "Key" field from Grid into Payment ListDetails "Foreign Key" field


Setup: A Grid called InvoiceGrid

            A ListDetails called DetailsView1 (for editing existing payments for the selected invoice)

            A ListDetails called DetailsView2 (in DetailsView1's EmptyDataTemplate for inserting new payments for the selected invoice) 

            A foreign Key restraint setup between the two tables



1) When I select an invoice that does not have a payment associated with it, the DetailsView2 displays as it should,  how do I auto-populate the DetailsView2 "InvoiceID" field with the InvoiceID field selected in the InvoiceGrid ?

2) How do I make the InvoiceID field in DetailsView2 "ReadOnly" so the user cannot accidentaly change it.

3) Is there any kind of Insert conformation that I can display if the payment is successfully inserted ?





Inserting new row in GridView in ASP.NET 2.0

The GridView was not designed to insert new rows, but there is a way to accomplish this with very little code. This article shows how to do that. The GridView was not designed to insert new rows, but there is a way to accomplish this with very little code.

Inserting personal error message in ValidationSummary



I am creating a web form that requires a lot of validation. I use many of the validation control in asp.net already like RequiredFieldValidator and CompareValidator. 

My Problem: after my custom validation for the value entered return an error message, and I pressed enter key when the field is empty, my custom error message is overlapped by my ValidationSummary. 

Setting my custom error to visible = false on button click also does not seem to work as it requires for me to enter the value first.

This made me think, is there a way to insert my custom validation inside the ValidationSummary as an error message like for other validation control?

Thanks in advance

Inserting rows via stored procedure and under certain conditions


I'm using Dynamic Data with Entity Framework in VS2010.

Let's say my table has these fields:

PersonID (FK)
LocationID (FK)

Hypothetical scenario (it's easier for me to explain this way, so just bear with me for now)... But let's say each row in the table represents "how many items were sold by such-and-such employee at such-and-such location," where location and person are foreign keys which are referencing other tables.  Basically, there should be no more than a ONE row which has a particular combination of Person and Location.  Makes sense?

So, when inserting new rows using my Dynamic Data app, the insert form displays editable fields for Person (dropdown), Location (dropdown), and Items Sold (textbox).  How do I prevent users from inserting another row into the table containing an already-existing combination of Person and Location?   How do I displaying useful feedback to them in the event that they DO attempt to do this?

I have several thoughts about this, but since I'm new to Dynamic Data, I'm not sure which way to go.  For example:

Option 1:  Use "cascading dropdowns" approach in the insert form and only pull in the "allowed" combinations of the two dropd

LINQ to SQL - Validating if item is in Database, but if item is not items not inserting into databas



I am new to this, so bear with me.  I am writing an application in C# that uses LINQ to validate a datacontext off a textbox to see if the record exists already.  If the record does exist I inserted an if statement to advise the user that the record exists, if the record does not exist I would like to allow the record to be added to the database.  If I take out my else statement everything works fine as far as inserting goes, but I do not want to allow inserts in this scenario.  I have tried moving the if and else statement to different parts of the code but can't quite figure this one out.  Any help would be apprecaited, attached is the code.  This code is set to a button press.  As a matter of fact, if you see any other errors along the way please feel free to point them out. 



    protected void enterBTN_Click(object sender, EventArgs e)
        //make new data context

        SHCDataContext insNewAll = new SHCDataContext();
        //LINQ to check if customer exists in database
        var checkExisting = from c in insNewAll.Customers
                            where c.custLastName.Contains(custLastNameTB.Text.ToString())
                            select c.custLastName;
        //make list to store values

Linq Subquery



I have a query that looks like this in SQL:

FROM StockMateriaPrima SMP
WHERE SMP.Fecha = (SELECT Max(Fecha)
                    FROM StockMateriaPrima SMP2
                    WHERE SMP2.Id = SMP.Id )

Can anyone tell me how to write this query using LINQ in VB.Net ?

Thanks !

inserting from gridview footer


I have been following the tutorials from Scott Mitchell on this site.  I am trying to insert a new record from the gridview footer.  I have my BLL set up as a .cs class in the App Code folder.  When I fill in the fields and click add, nothing happens.  The page refreshes and the text boxes empty, but nothing is added to the database.  The edit and delete functions work fine.  Have I put something in the wrong spot?


I have the rowcommand and the datasource_inserting on the code page as below.

protected void Oems_RowCommand(object sender, GridViewCommandEventArgs e)
    // Insert data if the CommandName == "Insert" 
    // and the validation controls indicate valid data...
    if (e.CommandName == "Insert" && Page.IsValid)
        // TODO: Insert new record...

protected void OemsDataSource1_Inserting
(object sender, ObjectDataSourceMethodEventArgs e)
    // Programmatically reference Web controls in the inserting interface...
    TextBox txtOem = (TextBox)GridView1.FooterRow.FindControl("txtOem");
    TextBox txtOemStreet = (TextBox)GridView1.FooterRow.FindControl("txtOemStreet");
    TextBox txtOemCity = (TextBox)GridView1.FooterRow.FindControl("txtOemCity");

Inserting data to ExcelSheet


Hi all,

I have a web form, in that i'll enter daily expense details.

After i press save button, the data i entered are saved into an excel sheet.

I don't have idea how to save the data to excel sheet, so your help for this greatly welcome. 

Reading data from .doc or .docx and inserting into db



A vendor is providing content which needs to be inserted into the db. The content is basically questions with options and explanations. An example is below.


Cast error when inserting record with Linq (to Sql)



I'm getting  the following error message: 

Unable to cast object of type 'System.Data.Linq.DataQuery`1[Username]' to type 'Username'.

I've been searching but can't find a solution.  This particular table has 4 columns. The first column is the int indentifier.  Column 2 is "username" (varchar50) and is the primary key.  Column3 is "userID" (uniqueidentifier) and column 4 is "active" (varchar5) .

            Dim dc As New DataClassesDataContext
            Dim c3 As New Username With {.userID = userGuid, _
                                    .username = userCustomName, _
                                    .active = "False"}


        Catch ex As Exception
            Throw ex
        End Try


>>>Check duplicate while inserting record from Texbox.

Hi, On inserting record, I want to check that for example if a user enters a telephone number for any record is already in the database then it should validate that the number already exists in table and you cannot enter a duplicate value. Then if user will provide some other telephone number then he allows to insert record. For insertion of record I used ObjectdataSource. User will enter telephone number in a simple textbox. I may want to inform that I am working in asp.net2.0 and also not allowed to use any third party control or ajaxtoolkit. Any idea would be appreciated.

Inserting a row on an extract flat file

Hi, I want to add in a header row to an extracted file. The file contains 5 columns of data but I only want to add in a 5chr id (stored in a variable) in the very first line of the extracted flat file.. please can you assit and tell me the best way of doing this..

Subquery returned more than 1 value.

Hello, I need a gander at this query to figure out what i'm doing wrong. update Performance set pmpg = (select PMPG from Performance_Calculator where EFFDT_Converted = (select CAST(FLOOR(CAST(getdate() AS FLOAT)) AS DATETIME)) and Performance.DR_CODE = Performance_Calculator.FW_OWN group by Performance_Calculator.FW_OWN, Performance_Calculator.PMPG); basically the performance calculator, in the subquery, does return around 320 rows of data.  I thought the where clause would match up the rows of data and insert the pmpg into the performance table but instead I get subquery returned more than  1 value.  This is true but only if the performance_calculator.fw_own = performance.dr_code wasn't there.  I'm confused on this... any suggestions?

Problem inserting into XML column

I have a C# application that inserts XML into Sql Server 2005.  When the message is more than 300 lines or so, it doesn't make it there.  The data shows in the application variables (stringWriter) but doesn't get inserted and that's confirmed looking in Profiler. The stored procedure is simply:          usp_WS_OrderEntry_InsertWSOrder @doc=@p1,@WSOrderId=@p2 output       INSERT INTO WS_OrderEntry_Order (OrderXML)       VALUES(@doc)  ..... C# .....             tableAdapter.usp_WS_OrderEntry_InsertWSOrder(stringWriter.ToString(), ref wsOrderId); .... In any cases, the variable "stringWriter" contains the data (as text). In profiler for a successfull call: declare @p1 xml set @p1=convert(xml,N'<OrderHeader><CustomerNumber>1234</CustomerNumber><Pr.....</PO></ShipToName> declare @p2 int set @p2=1077 exec dbo.usp_WS_OrderEntry_InsertWSOrder @doc=@p1,@WSOrderId=@p2 output select @p2 In unsuccessfull call: It shokes on the convert part and doesn't display any data (and doesn't insert as well).  I looked in LOGs, events and didn't find anything. Any help appreciated.  Thanks.

Foreign key constraint not replicating

We have a merge replication setup with one publisher/distributor and several subscribers.  Several of the tables being replicated have foreign key constraints and these replicate without issue.  However, some foreign key constraints that utilize cascading do not replicate.  To make matters worse, some tables with these cascading fk constraints replicate fine while others do not.  Has anyone run across this behavior and is there a fix for it?  The cascades will dramatically reduce our merge conflicts and help maintain the integrity of the data so we need to keep them in place.
ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend