Tracking Forums, Newsgroups, Maling Lists
Home Scripts Tutorials Tracker Forums
  Advanced Search
  HOME    TRACKER    MS SQL Server


SuperbHosting.net have generously sponsored dedicated servers to ensure a reliable and scalable dedicated hosting solution for BigResource.com.





Get Primary Key Of Last Inserted Record


 Ok I know this might not be the most accurate place to post this but I know someone here has an answer for me on it.
I need to get the product_ID of the new record that is created by this insert statement 
 INSERT
INTO products
     ( class_ID,category_ID,product_name,product_desc,product_image,product_dimension,product_o1,product_o2,product_o3,product_ac,product_ph,product_photo )
SELECT  class_ID,category_ID,product_name,product_desc,product_image,product_dimension,product_o1,product_o2,product_o3,product_ac,product_ph,product_photo  
FROM products
WHERE product_ID = @productID




View Complete Forum Thread with Replies

Related Forum Messages:
Getting Identity Of Inserted Record Using Inserted Event????
is there any way of getting the identity without using the "@@idemtity" in sql??? I'm trying to use the inserted event of ObjectDataSource, with Outputparameters, can anybody help me???

View Replies !
SqlCommand Get The Inserted Primary Key
Hi,
I would like to know how I can retrieve the ID (Primary key) of the row I just inserted with a sqlcommand(text not stored procedure).
Thx

View Replies !
How To Get The Primary Key From The Field Of The Row I've Just Inserted
I need to insert a row of data and return the value of the primary key id of the row.
I thought that something like this would work


int Key = (int)command.ExecuteScalar();


where command is SqlCommand object.

It doesn't work, maybe I've misunderstood the usage of ExecuteScalar.

View Replies !
Setting Primary Key Of New Row Being Inserted
Not sure if this is the right place for this post or not, but I'll give it a try...

If I am inserting a record into a table that uses a Primary Key, but not an Identity column, how do I insert the new primary key value?  I started out with SQL just letting the Identity column increment itself for primary keys, but I cannot do that for this particular situation.

If 'AddressID' is the primary key in the 'Address' table, could I do something like this:

INSERT INTO Address (AddressID, Field1, Field2, ...)
VALUES (**max value of primary key in Address table, plus 1**, 'field1data', 'field2data', ...);

If that works, how would I make this part of the insert query:
**max value of primary key in Address table, plus 1** ?

I hope this question is clear and makes sense. If it's not, please let me know.

View Replies !
How To Prevent A Second Entry Being Inserted With Primary Key Value? (C#)
Ok, this is a really stupid question, but I can't seem to find an answer I understand. In my SQL database I have a a table called MasterSkillList, to which the user can write by using a little web form with a text box and a drop down list. The table has 2 fields, Skill and Attribute. Skill is the primary key, as no skill can appear twice. What I want to do is prevent just that, I don't want people to enter the same skill more than once. So how do I tell the user that the entry allready exists in the database?
 My C#  Code is as follows:1 protected void btnSubmit_Click(object sender, EventArgs e)
2 {
3 srcAddSkill.InsertParameters["Skill"].DefaultValue = txtSkillName.Text;
4 srcAddSkill.InsertParameters["Attribute"].DefaultValue = ddlAbility.SelectedValue;
5 try
6 {
7 srcAddSkill.Insert();
8 lblErrorMessage.Text = "The skill '" + txtSkillName.Text + "' has been added. It is based on a character's " + ddlAbility.SelectedItem + " score.";
9 lblErrorMessage.Visible = true;
10 txtSkillName.Text = "";
11 }
12 catch (Exception ex)
13 {
14 lblErrorMessage.Text = "An exception has occurred. " + ex.Message;
15 lblErrorMessage.Visible = true;
16 }
 

View Replies !
Need To Get The ID Of The Last Record That Was Inserted
I've seen a lot of info on how to do this with @@IDENTITY and SCOPE_IDENTITY(), but can't  get this to work in my situation.
I am inserting a record into a table.  The first field is a GUID (UNIQUEIDENTIFIER) that uses newid() to generate a unique GUID.  Since I am not using an int, I can't set the IsIdentity property of the field.  Without IsIdentity set, @@IDENTITY and SCOPE_IDENTITY() do not work.
How can I get the ID (or whole record) of the last record that I inserted into a SQL database?  Note that I am doing this in C#.
As a last resort, I could generatate the GUID myself before the insert, but I can't find C# code on how to to this.

View Replies !
Getting An Int Id From An Inserted Record
Hello,I would like do an insert into a table. The table has an autoincrimenting unique int id. After I do the insert how do i get theunique int id of the record that I just inserted? Is there a straightforward way of accomplishing this?Thanks,Billy

View Replies !
How To Read Just Inserted Auto Incremented Primary Key To Use It As Parameter?
Hi. After inserting data (new row) by using DetailsView control, how to read auto incremented primary key (identity) of this new row from sql database to use it as parameter passed to stored procedure?

View Replies !
Duplicate Inserted Record
Hi EverybodyThis Code duplicate the record in the database, can somebody help me understand why that happen. Thanks a LOT    CompanyName:    <asp:textbox id="txtCompanyName" runat="server" /><br />Phone:<asp:textbox id="txtPhone" runat="server" /><br /><br /><asp:button id="btnSubmit" runat="server" text="Submit" onclick="btnSubmit_Click" /><asp:sqldatasource id="SqlDataSource1" runat="server" connectionstring="<%$ ConnectionStrings:dsn %>"    insertcommand="INSERT INTO [items] ([smId], [iTitleSP]) VALUES (@CompanyName, @Phone)"    selectcommand="SELECT * FROM [items]">    <insertparameters>        <asp:controlparameter controlid="txtCompanyName" name="CompanyName" />        <asp:controlparameter controlid="txtPhone" name="Phone" />    </insertparameters></asp:sqldatasource> VBPartial Class Default2    Inherits System.Web.UI.Page    Protected Sub btnSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSubmit.Click        SqlDataSource1.Insert()    End SubEnd Class ----------------------------------------------Yes is an Identity the Primary Key of the Table items   

View Replies !
Retriving The ID Of The Last Record Inserted
 I would appreciate help with retriving the ID of the last record inserted. Have spent considerable time in forums and google but can't find anything that works for me.
Here is my VB Code
   Dim queryString As String = "INSERT INTO [DUALML] ([UseriD], [Company]) VALUES (@UseriD, @Company)"        Dim dbCommand As System.Data.IDbCommand = New System.Data.SqlClient.SqlCommand        dbCommand.CommandText = queryString        dbCommand.Connection = dbConnection
        Dim dbParam_useriD As System.Data.IDataParameter = New System.Data.SqlClient.SqlParameter        dbParam_useriD.ParameterName = "@UseriD"        dbParam_useriD.Value = useriD        dbParam_useriD.DbType = System.Data.DbType.Int32        dbCommand.Parameters.Add(dbParam_useriD)        Dim dbParam_company As System.Data.IDataParameter = New System.Data.SqlClient.SqlParameter        dbParam_company.ParameterName = "@Company"        dbParam_company.Value = company        dbParam_company.DbType = System.Data.DbType.[String]        dbCommand.Parameters.Add(dbParam_company)            
        Dim rowsAffected As Integer = 0        dbConnection.Open        Try            rowsAffected = dbCommand.ExecuteNonQuery        Finally            dbConnection.Close        End Try
        Return rowsAffected    End Function
 

View Replies !
Get PK For Inserted Record In SQLdatasource
I have a table named invoice that contains the following columns-invoiceno - Primary key and is set to autonumber-customerno-incoicedateand on my VB code i did the following InsertCommandSqlDataSource1.InsertCommand = "INSERT INTO invoice(customerno, invoicedate) VALUES('" & Session("UID") & "', GetDate()) "SqlDataSource1.Insert()My Question is how do i get the Primary Key Value it generated during the insert operation(invoice['incoiceno'])? Besides the creationg a stored procedere like the one in the MSDN Library

View Replies !
Get @@IDENTITY Of New Inserted Record,
I am using VS.net (2003) SQLcommand TEXT. with input params.
SQL server 2000


Can anyone tell me how to get the Identity value (field value, Idenity col) when you do an insert? I want to get the Identity value, then redirect the user to another page and use this identity value so they can update more (other) fields that are on that page.

My code so far that works... but Where do I put @@IDENTITY ?
How do I call or assign the @@IDENTITY value to a value in my aspx.vb code page?

Question: how do I get the Identity value from the ID column.
Question: How do I assign that value to some variable in code, say, assign it to (Session("App_ID")) = IdentityValueOrSomething?Help...
---------------------
INSERT INTO App
(AppName, Acronym, Description,bla bla bla bla........)
VALUES (@AppName, @Acronym, @Description, bla bla bla bla........)

-----------------------------

Private Sub btnAddApp_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAddApp.Click
With cmdAddApp
'.Parameters("@app_id").Value = Session("App_ID")
.Parameters("@AppName").Value = txtAppName.Text
.Parameters( bla bla bla.............
.Parameters( bla bla bla.............
.Parameters( bla bla bla.............

End With
Try
cnAppKBdata.Open()
cmdAddApp.ExecuteNonQuery()
cnAppKBdata.Close()
''''''''''''''Session("App_ID") = whatever the @@IDENTITY is....'''''''''''''''''''''''''''??
Response.Redirect("AppUpdate.asp")
Catch ex As Exception

End Try
End Sub


Anyone have the lines of code that does this?

Any advise or examples :) thanks you.

View Replies !
Get Last 7 Days Inserted Record
Hi All,
i have a database, and every time when any row enter , it capture the date and time of insertation,
then does any function or query available, which help to investigate me, today inserted record,yesterday inserted record,last 7 days inserted record,last 30 days inserted record and last year inserted record..
i am using asp.net and MS Access...
Any idea
thanx in advance...
sajjad

View Replies !
How Do I Trace Who Inserted A Particular Record?
Is it possible to retrieve the user name or host name of the user that inserted or updated a particular record? Is this information stored in the database's log file, in hidden fields, or anywhere else? I know I can easily add a user_name field and use triggers to add this information for new records, but I need this information for records already existing in the table. Thanks.

Jason

View Replies !
Cannot Read A Record Just Inserted
Hi,

I have a small app which has the following statements:

Insert into tableA (ID, Name) Values (iID, vName)
Select * from tableA where ID = iID

where iID and vName are variables.

If I run 100 instances of this app, each inseting mutually exclusive IDs,
the second statement may occasionally return no record. Why ?

By the way, I use OLEDB command object and didn't specify any transaction
isolation level (use the default in OLEDB).

Any feedback would be greatly appreciated. Thanks. Ray

View Replies !
Cannot Read A Record Just Inserted
Hi,

I have a small app which has the following statements:

Insert into tableA (ID, Name) Values (iID, vName)
Select * from tableA where ID = iID

where iID and vName are variables.

If I run 100 instances of this app, each inseting mutually exclusive IDs,
the second statement may occasionally return no record. Why ?

By the way, I use OLEDB command object and didn't specify any transaction
isolation level (use the default in OLEDB).

Any feedback would be greatly appreciated. Thanks. Ray

View Replies !
Gettting Last Inserted Record
hi,i need to select last inserted record in my table,can any one show some example query for that please

View Replies !
How To Retrieve Identity Of Just Inserted Record???
Ok I've been researching this for a day now and I'm not coming up with much. I want to store the auto-incrementing ID of the last inserted record in a session variable, so that I may put it in a foreign key column in another table, if the user wishes to fill out a form on another page. I think my stored procedure is correct. But don't know what code to add to my aspx page. Any help will be greatly appreciated.
 
Here is my VB ScriptProtected Sub submitButton_Click(ByVal sender As Object, ByVal e As System.EventArgs)
 
 
 
Dim personalContactDataSource As New SqlDataSource()personalContactDataSource.ConnectionString = ConfigurationManager.ConnectionStrings("DataConnectionString1").ToString()
 
 
personalContactDataSource.InsertCommandType = SqlDataSourceCommandType.StoredProcedure
personalContactDataSource.InsertCommand = "PersonalContactInsert"
 
 personalContactDataSource.InsertParameters.Add("FirstName", FirstName.Text)
personalContactDataSource.InsertParameters.Add("LastName", LastName.Text)personalContactDataSource.InsertParameters.Add("KeyPerson", KeyPerson.Checked)
personalContactDataSource.InsertParameters.Add("DayPhone", DayPhone.Text)personalContactDataSource.InsertParameters.Add("EveningPhone", EveningPhone.Text)
personalContactDataSource.InsertParameters.Add("Fax", Fax.Text)personalContactDataSource.InsertParameters.Add("Email", Email.Text)
personalContactDataSource.InsertParameters.Add("HomeAddress", HomeAddress.Text)personalContactDataSource.InsertParameters.Add("City", City.Text)
personalContactDataSource.InsertParameters.Add("State", State.Text)personalContactDataSource.InsertParameters.Add("Zip", Zip.Text)
personalContactDataSource.InsertParameters.Add("ReqEffectDate", ReqEffectDate.Text)personalContactDataSource.InsertParameters.Add("MRID", MRID.Text)
personalContactDataSource.InsertParameters.Add("CurrentPremium", CurrentPremium.Text)personalContactDataSource.InsertParameters.Add("CurrentCarrier", CurrentCarrier.Text)
personalContactDataSource.InsertParameters.Add("CurrentDeductible", CurrentDeductible.Text)personalContactDataSource.InsertParameters.Add("CurrentCoins", CurrentCoins.Text)personalContactDataSource.InsertParameters.Add("ReasonForQuote", ReasonForQuote.Text)
 
 
End Sub
 
 
And here is my Stored ProcALTER PROCEDURE dbo.PersonalContactInsert

@FirstName varchar(30),@LastName varchar(30),
@DayPhone varchar(14),@EveningPhone varchar(14),
@Fax varchar(14),@Email varchar(60),
@HomeAddress varchar(80),@City varchar(30),
@State char(2),@Zip char(5),
@KeyPerson bit,@ReqEffectDate smalldatetime,
@CurrentCarrier varchar(30),@CurrentPremium smallmoney,
@CurrentDeductible smallmoney,@CurrentCoins smallmoney,
@ReasonForQuote varchar(150),@MRID int,
@ClientNumber int OUT
 
AS
 
INSERT INTO PersonalContact(FirstName, LastName, DayPhone, EveningPhone, Fax, Email, HomeAddress, City, State, Zip, KeyPerson, ReqEffectDate, CurrentCarrier, CurrentPremium, CurrentDeductible, CurrentCoins, ReasonForQuote, MRID, DateTimeStamp)
VALUES(@FirstName,@LastName,@DayPhone,@EveningPhone,@Fax,@Email,@HomeAddress,@City,@State,@Zip,@KeyPerson,@ReqEffectDate,@CurrentCarrier,@CurrentPremium,@CurrentDeductible,@CurrentCoins,@ReasonForQuote,@MRID, GetDate())
SET @ClientNumber = SCOPE_IDENTITY()
RETURN
 

View Replies !
Retrieve Last Inserted Or Updated Record
Hi
I have an application which get any change from database using sql dependency. When a record is inserted or updated it will fire an event and my application get that event and perform required operation.
On the event handler I am usin select ID,Name from my [table];
this will return all record from database.
I just want to get the record which is inserted or updated.
Can u help me in that.
Take care
Bye

View Replies !
Duplicate Record Inserted. Weird.........
1 Protected Sub btnSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSubmit.Click
2 Dim sqlStr As String
3 Dim sqlStr2 As String
4 Dim myConnection As MySqlConnection = Nothing
5 Dim myCommand As MySqlCommand = Nothing
6 Dim myConnection2 As MySqlConnection = Nothing
7 Dim myCommand2 As MySqlCommand = Nothing
8 Dim myReader As MySqlDataReader = Nothing
9 Dim IC As String
10
11 IC = txtIC1.Text + "-" + txtIC2.Text + "-" + txtIC3.Text
12
13
14 Try
15 sqlStr2 = "SELECT * FROM User WHERE uLogin='" & txtUserName.Text.Trim() & "'"
16
17 ' Connection
18 myConnection2 = New MySqlConnection(ConfigurationManager.ConnectionStrings("dbConnection").ToString())
19 myConnection2.Open()
20 ' Command
21 myCommand2 = New MySqlCommand(sqlStr2, myConnection2)
22 ' Reader
23 myReader = myCommand2.ExecuteReader()
24 Catch ex As Exception
25 ' Exception Error Here
26 Response.Write(Err.Number & " - " & Err.Description)
27
28 End Try
29 ' Checking
30 If myReader.Read() Then
31
32
33 Label2.Text = "Username already exist. Please choose another username"
34 Label3.Text = "*"
35
36 Else
37
38 Try
39
40
41 sqlStr = "INSERT INTO userapplication(uaName,uaIC,) VALUE (?uName,?uIC )"
42
43
44
45 ' Connection
46 myConnection = New MySqlConnection(ConfigurationManager.ConnectionStrings("dbConnection").ToString())
47 myConnection.Open()
48 'Command
49 myCommand = New MySqlCommand(sqlStr, myConnection)
50
51 myCommand.Parameters.AddWithValue("?uName", txtName.Text)
52 myCommand.Parameters.AddWithValue("?uIC", IC)
53
54
55 myCommand.ExecuteNonQuery()
56 myConnection.Close()
57 Response.Redirect("Register.aspx", False)
58
59 Catch ex As Exception
60 ' Exception Error Here
61 Response.Write(Err.Number & " - " & Err.Description)
62 Finally
63 ' Clean Up
64 If Not IsNothing(myCommand) Then
65 myCommand.Dispose()
66 End If
67 '
68 If Not IsNothing(myConnection) Then
69 If myConnection.State = Data.ConnectionState.Open Then myConnection.Close()
70 myConnection.Dispose()
71 End If
72 End Try
73
74
75 End If
76
77 End Sub
78
79
 
 above is my code for the user registration page.the code that i bold,which with number 55,56 and 57,are where the problem occur.
when it run,it run 55, then 57,then back to 55, then 57 again
means that my db hav duplicate record being insert
anyone know how to solve this problem?

View Replies !
Get The Number Of Days It Has Been Since A Record Was Inserted
Hiwhen inserting records into a table one of the fields is a date field.  I am using the GETDATE() function to insert the date as the record is being inserted.when i retrieve an entire record from the table i want to be able to select this date, but also to get the number of days it has been since that record was inserted.eg: 3 daysif the record was inserted less than one day ago (<24 hrs ago) i would like it to return the number of hours. e.g. 22 hrsi dont want hours to be displayed if the days is >= 1.please can anyone guide me with this?thanks!

View Replies !
Problems Viewing Last Inserted Record
Basically, I'm creating a blog for fun. I have a formview, and I have several sqlDataSource objects inside the formview's ItemTemplate. Due to peculiarities with the way I plan to implement my blog, I have to programmatically update those sqlDataSource objects.
But I've run into a problem: after I insert a record and change my formview's mode to ReadOnly, I can get the last inserted record, but I can't update any of the sqlDataSource objects inside my ItemTemplate, those sqlDataSource objects are simply invisible.
Here is my markup:<%@ Page Language="VB" MasterPageFile="~/layout/mysite.master" AutoEventWireup="false" CodeFile="folder.aspx.vb" Inherits="mysite_blog_folder" title="Untitled Page" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<asp:FormView ID="FormView1" runat="server" DataKeyNames="ID_Global" DataSourceID="sqlFolder">
<InsertItemTemplate>
Title:<br />
<asp:TextBox ID="TitleTextBox" runat="server" Text="<%# Bind('Title') %>"></asp:TextBox><br />
<br />
Parent:<br />
<asp:DropDownList ID="DropDownList1" runat="server" DataSourceID="sqlAllFolders"
DataTextField="Title" DataValueField="ID_Global" SelectedValue='<%# Bind("ID_Parent", "{0:N}") %>'>
</asp:DropDownList><br />
<br />
Keywords:<br />
<asp:TextBox ID="TextBox2" runat="server" Text="<%# Bind('Keywords') %>"></asp:TextBox><br />
<br />
<asp:LinkButton ID="InsertButton" runat="server" CausesValidation="True" CommandName="Insert"
Text="Insert"></asp:LinkButton>
<asp:LinkButton ID="InsertCancelButton" runat="server" CausesValidation="False" CommandName="Cancel"
Text="Cancel"></asp:LinkButton>
</InsertItemTemplate>
<ItemTemplate>
<asp:Label ID="TitleLabel" runat="server" Text='<%# Bind("Title") %>' Font-Bold="True"></asp:Label><br />
<br />
<asp:Repeater ID="repeatBreadcrumb" runat="server" DataSourceID="sqlBreadCrumb">
<HeaderTemplate>
<asp:Repeater ID="repeatBlogInfo" runat="server" DataSourceID="sqlBlogInfo">
<ItemTemplate>
<asp:HyperLink runat="server" Text='<%# Eval("Title") %>' NavigateUrl='<%# String.Format("~/mysite/blog/blog.aspx?b={0}", Eval("id_blog")) %>' />
</ItemTemplate>
<FooterTemplate>
&gt;
</FooterTemplate>
</asp:Repeater>
</HeaderTemplate>
<SeparatorTemplate>
&gt;
</SeparatorTemplate>
<ItemTemplate>
<asp:HyperLink runat="server" Text='<%# Eval("Title") %>' NavigateUrl='<%# String.Format("~/mysite/blog/folder.aspx?f={0}", Eval("id_folder")) %>' />
</ItemTemplate>
</asp:Repeater>
<asp:SqlDataSource ID="sqlBreadCrumb" runat="server" ConnectionString="<%$ ConnectionStrings:ASPNetConnectionString %>"
SelectCommand="blog_Get_Folder_Breadcrumb" SelectCommandType="StoredProcedure">
<SelectParameters>
<asp:Parameter DefaultValue="0" Name="id_global" Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
<asp:SqlDataSource ID="sqlBlogInfo" runat="server" ConnectionString="<%$ ConnectionStrings:ASPNetConnectionString %>"
SelectCommand="Select ID_Global, ID_Blog, Title FROM blog_blogs WHERE id_global = (select id_blog from blog_folders where id_global = @id_global)">
<SelectParameters>
<asp:Parameter DefaultValue="0" Name="id_global" />
</SelectParameters>
</asp:SqlDataSource>
<br />
<asp:GridView ID="gridSubFolders" runat="server" AutoGenerateColumns="False" DataKeyNames="ID_Global"
DataSourceID="sqlFolderChildren" Width="100%" AllowPaging="True" AllowSorting="True" CellPadding="4" ForeColor="#333333" GridLines="None">
<Columns>
<asp:BoundField DataField="ID_Folder" HeaderText="Folder #" SortExpression="ID_Folder">
<ItemStyle Width="10%" />
</asp:BoundField>
<asp:HyperLinkField DataNavigateUrlFields="ID_Folder" DataNavigateUrlFormatString="~/mysite/blog/folder.aspx?f={0}"
DataTextField="Title" DataTextFormatString="{0}" HeaderText="Subfolders" SortExpression="Title">
<ItemStyle Width="90%" />
</asp:HyperLinkField>
</Columns>
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<EditRowStyle BackColor="#999999" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
</asp:GridView>
<asp:SqlDataSource ID="sqlFolderChildren" runat="server" ConnectionString="<%$ ConnectionStrings:ASPNetConnectionString %>"
SelectCommand="blog_Get_Folder_Children" SelectCommandType="StoredProcedure">
<SelectParameters>
<asp:Parameter DefaultValue="0" Name="id_global" Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
<br />
<br />
<asp:GridView ID="gridArticles" runat="server" AutoGenerateColumns="False" CellPadding="4"
DataKeyNames="id_global" DataSourceID="sqlFolderArticles" ForeColor="#333333"
GridLines="None" AllowPaging="True" AllowSorting="True">
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<Columns>
<asp:BoundField DataField="id_Article" HeaderText="Article #" SortExpression="id_Article">
<ItemStyle Width="10%" />
</asp:BoundField>
<asp:HyperLinkField DataNavigateUrlFields="id_Article" DataNavigateUrlFormatString="~/mysite/blog/article.aspx?a={0}&amp;do=edit"
DataTextField="Title" DataTextFormatString="{0}" HeaderText="Article" SortExpression="Title" />
</Columns>
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<EditRowStyle BackColor="#999999" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<EmptyDataTemplate>
There are no articles in this folder.
</EmptyDataTemplate>
</asp:GridView>
<asp:SqlDataSource ID="sqlFolderArticles" runat="server" ConnectionString="<%$ ConnectionStrings:ASPNetConnectionString %>"
SelectCommand="blog_get_folder_articles" SelectCommandType="StoredProcedure">
<SelectParameters>
<asp:Parameter DefaultValue="0" Name="id_global" Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
<br />
</ItemTemplate>
</asp:FormView>
<asp:SqlDataSource ID="sqlFolder" runat="server" ConnectionString="<%$ ConnectionStrings:ASPNetConnectionString %>"
InsertCommand="blog_new_folder" InsertCommandType="StoredProcedure" SelectCommand="select ID_Global, ID_Folder, Title FROM blog_folders where ID_Global = @id_global"
UpdateCommand="blog_edit_folder" UpdateCommandType="StoredProcedure">
<UpdateParameters>
<asp:Parameter Name="id_global" Type="Int32" />
<asp:Parameter Name="status" Type="Byte" />
<asp:Parameter Name="Title" Type="String" />
<asp:Parameter Name="article" Type="String" />
</UpdateParameters>
<SelectParameters>
<asp:Parameter DefaultValue="0" Name="id_global" />
</SelectParameters>
<InsertParameters>
<asp:ProfileParameter DefaultValue="0" Name="id_blog" PropertyName="editingblogid"
Type="Int32" />
<asp:Parameter Name="id_parent" Type="Int32" />
<asp:Parameter Name="Title" Type="String" />
<asp:Parameter Name="Keywords" Type="String" />
<asp:Parameter Direction="Output" Name="RETURN_VALUE" Type="Int32" />
</InsertParameters>
</asp:SqlDataSource>
<asp:SqlDataSource ID="sqlAllFolders" runat="server" ConnectionString="<%$ ConnectionStrings:ASPNetConnectionString %>"
SelectCommand="blog_Get_Folder_Tree_ALL_Condensed" SelectCommandType="StoredProcedure">
<SelectParameters>
<asp:Parameter DefaultValue="0" Name="id_global" Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
<br />
</asp:Content> 
Here is my code behind:1 Imports System.Data.SqlClient
2
3 Partial Class mysite_blog_folder
4 Inherits System.Web.UI.Page
5
6 Dim ID_Global_Folder As Integer = 0
7
8 Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
9 If Not Page.IsPostBack Then
10 If Request.QueryString("f") IsNot Nothing Then
11 ID_Global_Folder = New globalid("blog_Get_GlobalID_Folder", _
12 "id_blog", _
13 Profile.editingblogID, _
14 "id_folder", _
15 Request.QueryString("f")).ReturnValue
16 Else
17 ID_Global_Folder = 0
18 End If
19
20 If Request.QueryString("do") IsNot Nothing Then
21 Select Case LCase(Request.QueryString("do"))
22 Case "new"
23 FormView1.ChangeMode(FormViewMode.Insert)
24 End Select
25 End If
26 End If
27 End Sub
28
29 Protected Sub sqlFolder_Inserted(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.SqlDataSourceStatusEventArgs) Handles sqlFolder.Inserted
30 ID_Global_Folder = Convert.ToInt32(e.Command.Parameters("@RETURN_VALUE").Value)
31 FormView1.ChangeMode(FormViewMode.ReadOnly)
32 End Sub
33
34 Private Sub Reset_Default_Parameters()
35 sqlFolder.UpdateParameters.Item("id_global").DefaultValue = ID_Global_Folder
36 sqlFolder.SelectParameters.Item("id_global").DefaultValue = ID_Global_Folder
37
38 Select Case FormView1.CurrentMode
39 Case FormViewMode.ReadOnly
40 InitializeSQLControl("sqlFolderChildren", ID_Global_Folder)
41 InitializeSQLControl("sqlFolderArticles", ID_Global_Folder)
42 InitializeSQLControl("sqlBreadCrumb", ID_Global_Folder)
43 InitializeSQLControl("sqlBlogInfo", ID_Global_Folder)
44 Case FormViewMode.Insert
45 sqlAllFolders.SelectParameters.Item("id_global").DefaultValue = Profile.editingblogID
46 Case FormViewMode.Edit
47 End Select
48 End Sub
49
50 Private Sub InitializeSQLControl(ByVal strName As String, ByVal iValue As Integer)
51 Dim mySQLControl As SqlDataSource
52 mySQLControl = FormView1.FindControl(strName)
53 If mySQLControl IsNot Nothing Then
54 mySQLControl.SelectParameters.Item("id_global").DefaultValue = iValue
55 End If
56 End Sub
57
58 Protected Sub Page_LoadComplete(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.LoadComplete
59 Call Reset_Default_Parameters()
60 End Sub
61 End Class
 
Here is whats happening:
1) After inserting a new record, the event sqlFolder_Inserted gets called. I get the uniqueID of the last inserted folder and save that for later use.2) The page finishes loading up, then the event Page_LoadComplete gets called. I call Reset_Default_Parameters to update my sqlDataSource objects.2.1) sqlDataSource sqlFolder, which is datasource used by the formview, is updated just fine.2.2) I update my formview's child sqlDataSource objects by calling InitializeSQLControl.2.2.1) I use Formview1.Findcontrol to reference the sqlDatasource in my formview's ItemTemplate, I store the referenced control in a variable called mySQLControl.2.2.2) However, mySQLControl is Nothing. ASP.net simply doesn't "see" that control on the page, even though the formview is in ReadOnly mode.
I've tried calling InitializeSQLControl in different places in my code, including the Page_Load, sqlFolder_Inserted, but it doesn't make a difference.
That problem *only* happens after I insert a new record. Otherwise, I can browse through my folder hierarchy without a problem, and all of my child sqlDataSource objects update just fine.
So, how do I update my child sqlDataSource controls in my ItemTemplate after I insert a new record?

View Replies !
Dataset And Identity Of New Record Inserted
Hi, I have 2 tables in my database PrescriptionHeader and PrescriptionDetails.My PrescriptionHeader table has the following fields:PrescriptionID -identity fieldPatientID PatientfNamePatientlname PrescriptionDetails table has the following fields:PrescriptionDetailID -identityPrescriptionID -from PrescriptionHeader table MedicineDosage The function InsertPrescription inserts values into the table PrescriptionHeader. I want the same function to then insert the value of MedicineDosage  into PrescriptionDetails with the same PrescriptionID inserted into PrescriptionHeader. How do I tell the function to insert the PrescriptionID that was automatically inserted into PrescriptionHeader also into table PrescriptionDetails . How do I return the identity before proceeding to insert into PrescriptionDetails table?ThanksFunction InsertPrescription(ByVal PatientID As String, _ByVal PatientFname As String, _ByVal Patientlname As String, ByVal MedicineDosage as String)Dim DBAdapter As SqlDataAdapterDim DBDataSet As DataSetDim SQLString As StringDim DBCommandBuilder As SqlCommandBuilderSQLString = "SELECT * FROM PrescriptionHeader WHERE PrescriptionId = ''"DBAdapter = New SqlDataAdapter(SQLString, DBConnection)DBDataSet = New DataSetDBAdapter.Fill(DBDataSet)Dim AddedRow As DataRow = DBDataSet.Tables(0).NewRow()AddedRow("PatientID") = PatientIDAddedRow("PatientfName") = PatientFnameAddedRow("Patientlname") = PatientlnameDBDataSet.Tables(0).Rows.Add(AddedRow)DBCommandBuilder = New SqlCommandBuilder(DBAdapter)DBAdapter.Update(DBDataSet) End Function

View Replies !
SCOPE_IDENTITY() Returning The ID Value Of An Inserted Record.
There are loads of postings on the net about this problem but none I have found explain the cause.
Whenever returning a value from a TableAdapter.Insert method followed by a SELECT SCOPE_IDENTITY() , the value returned is always 1. I have run the same select in SQL management studion and the correct value is returned but with a 1 showing in the column selector (just to the left of the first column. The column selector column is not data column. This must be the reason that issuing a SELECT after an INSERT does not work when using a TableAdapter isert method.
Has anyone come across the solution for this issue?
Thanks
 

View Replies !
Retrieve The GUID For Inserted Record
I am using this code to insert a record in my table where i have assigned a guid datatype field to generate an automatic guid for each record. but now i need to retrieve the guid to use it to send a confirmation email to the user.
 
SqlConnection sql_connection = new SqlConnection("Server=xxx.xxx.xx.xxx;uid=xxxxxxxx;password=xxxxxxx;database=xxxxxxx;");SqlCommand sql_command = new SqlCommand("INSERT INTO members (member_sex, member_cpr, member_nationality, member_block, member_gov, member_daaera, member_email, member_mobile, member_created_ip) Values (@member_sex, @member_cpr, @member_nationality, @member_block, @member_gov, @member_daaera, @member_email, @member_mobile, @member_created_ip)", sql_connection);
sql_command.Parameters.Add(new SqlParameter("@member_sex", Session["member_sex"].ToString()));sql_command.Parameters.Add(new SqlParameter("@member_cpr", Session["member_cpr"]));sql_command.Parameters.Add(new SqlParameter("@member_nationality", Session["member_nationality"].ToString()));sql_command.Parameters.Add(new SqlParameter("@member_block", Session["member_block"].ToString()));sql_command.Parameters.Add(new SqlParameter("@member_gov", "GOV"));sql_command.Parameters.Add(new SqlParameter("@member_daaera", 6));sql_command.Parameters.Add(new SqlParameter("@member_email", Session["member_email"].ToString().ToLower()));sql_command.Parameters.Add(new SqlParameter("@member_mobile", Session["member_mobile"].ToString()));sql_command.Parameters.Add(new SqlParameter("@member_created_ip", Request.UserHostAddress.ToString()));
sql_connection.Open();sql_command.ExecuteNonQuery();sql_connection.Close();
 

View Replies !
Inserted Records Missing In Sql Table Yet Tables' Primary Key Field Has Been Incremented.
I have a sql sever 2005 express table with an automatically incremented primary key field. I use a Detailsview to insert new records and on the Detailsview itemInserted event, i send out automated notification emails.
I then received two automated emails(indicating two records have been inserted) but looking at the database, the records are not there. Whats confusing me is that even the tables primary key field had been incremented by two, an indication that indeed the two records should actually be in table.  Recovering these records is not abig deal because i can re-enter them but iam wondering what the possible cause is. How come the id field was even incremented and the records are not there yet iam 100% sure no one deleted them. Its only me who can delete a record.
And then how come i insert new records now and they are all there in the database but now with two id numbers for those missing records skipped. Its not crucial data but for my learning, i feel i deserve understanding why it happened because next time, it might be costly.

View Replies !
Help Getting An ID, Back From A Record, That Has Just Been Inserted With A Stored Procedure
Hi,
I was wondering if anyone could offer me some advice. I am currently using a stored procedure to insert records into a database. I want to be able to retrieve the ID (primar key) from the item that has just been inserted using the stored procedure. The ID I want to get back is Meter_ID
This is my stored procedure:ALTER PROCEDURE dbo.quote
 
(@Business_Name nvarchar(50),
@Business_Type nvarchar(50),@Contact_Title nchar(10),
@Contact_First_Name nvarchar(50),@Contact_Last_Name nvarchar(50),
@Address_Line_1 nvarchar(MAX),@Address_Line_2 nvarchar(MAX),
@City nvarchar(MAX),@Postcode nchar(7),
@Tel_No nchar(11),@E_mail_Address nvarchar(50),
@Distributor_ID int,@Profile_Class int,
@Meter_Time_Code int,@Line_Loss_Factor int,
@Unique_Identifier1 int,@Unique_Identifier2 int,
@Check_Digit int,@Tariff nchar(20),
@UnitRate1AnnualUsage nchar(10),@UnitRate2AnnualUsage nchar(10),
@UnitRate1SubTotal money,@UnitRate2SubTotal money,
@QuoteTotal money
)
ASINSERT INTO client_details (Business_Name, Business_Type, Contact_Title, Contact_First_Name, Contact_Last_Name, Address_Line_1, Address_Line_2, City, Postcode, Tel_No, email_Address)VALUES (@Business_Name, @Business_Type,@Contact_Title, @Contact_First_Name, @Contact_Last_Name, @Address_Line_1, @Address_Line_2, @City, @Postcode, @Tel_No, @E_mail_Address)
 
DECLARE @Client_ID INTSET @Client_ID = scope_identity()
 INSERT INTO meter_quote (Client_ID, Tariff, Meter_Distributor_ID, Meter_Profile_Class, Meter_Time_Code, Meter_Line_Loss_Factor, Unique_Identifier1, Unique_Identifier2, Check_Digit, UnitRate1AnnualUsage, UnitRate2AnnualUsage, UnitRate1SubTotal, UnitRate2SubTotal, QuoteTotal)VALUES (@Client_ID, @Tariff, @Distributor_ID, @Profile_Class, @Meter_Time_Code, @Line_Loss_Factor, @Unique_Identifier1, @Unique_Identifier2, @Check_Digit, @UnitRate1AnnualUsage, @UnitRate2AnnualUsage, @UnitRate1SubTotal, @UnitRate2SubTotal, @QuoteTotal)
 
RETURN
And this is the code I have in my asp page:<asp:SqlDataSource ID="SqlDataSource3" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
InsertCommand="quote" InsertCommandType="StoredProcedure">
<InsertParameters><asp:ControlParameter ControlID="TextBoxBusinessName" DefaultValue=""
Name="Business_Name" PropertyName="Text" Type="String" /><asp:ControlParameter ControlID="DropDownBusinessType" Name="Business_Type"
PropertyName="SelectedValue" Type="String" /><asp:ControlParameter ControlID="DropDownListTitle" Name="Contact_Title"
PropertyName="SelectedValue" Type="String" /><asp:ControlParameter ControlID="TextBoxFirstName" Name="Contact_First_Name"
PropertyName="Text" Type="String" /><asp:ControlParameter ControlID="TextBoxLastName" Name="Contact_Last_Name"
PropertyName="Text" Type="String" /><asp:ControlParameter ControlID="TextBoxAddressLine1" Name="Address_Line_1"
PropertyName="Text" Type="String" /><asp:ControlParameter ControlID="TextBoxAddressLine2" Name="Address_Line_2"
PropertyName="Text" Type="String" /><asp:ControlParameter ControlID="TextBoxAddressLine3" Name="City"
PropertyName="Text" Type="String" /><asp:ControlParameter ControlID="TextBoxPostcode" Name="Postcode"
PropertyName="Text" Type="String" /><asp:ControlParameter ControlID="TextBoxTelNo" Name="Tel_No"
PropertyName="Text" Type="String" /><asp:ControlParameter ControlID="TextBoxEmail" Name="E_mail_Address"
PropertyName="Text" Type="String" /><asp:ControlParameter ControlID="TextBoxDistributorID" Name="Distributor_ID"
PropertyName="Text" Type="String" /><asp:ControlParameter ControlID="TextBoxProfileClass" Name="Profile_Class"
PropertyName="Text" Type="String" /><asp:ControlParameter ControlID="TextBoxMeterTimeCode" Name="Meter_Time_Code"
PropertyName="Text" Type="String" /><asp:ControlParameter ControlID="TextBoxLineLossFactor" Name="Line_Loss_Factor"
PropertyName="Text" Type="String" /><asp:ControlParameter ControlID="TextBoxUniqueIdentifier1" Name="Unique_Identifier1"
PropertyName="Text" Type="String" /> <asp:ControlParameter ControlID="TextBoxUniqueIdentifier2" Name="Unique_Identifier2"
PropertyName="Text" Type="String" /><asp:ControlParameter ControlID="TextBoxCheckDigit" Name="Check_Digit"
PropertyName="Text" Type="String" /> <asp:ControlParameter ControlID="LabelTariff2" Name="Tariff"
PropertyName="Text" Type="String" /> <asp:ControlParameter ControlID="TextBoxUnitRate1Usage" Name="UnitRate1AnnualUsage"
PropertyName="Text" Type="String" /><asp:ControlParameter ControlID="LabelUnitRate2Usage" Name="UnitRate2AnnualUsage"
PropertyName="Text" Type="String" /><asp:ControlParameter ControlID="LabelUnitRate1Total" Name="UnitRate1SubTotal"
PropertyName="Text" Type="Decimal" /><asp:ControlParameter ControlID="LabelUnitRate2Total" Name="UnitRate2SubTotal"
PropertyName="Text" Type="Decimal" /><asp:ControlParameter ControlID="LabelQuoteTotal" Name="QuoteTotal"
PropertyName="Text" Type="Decimal" />
</InsertParameters>
</asp:SqlDataSource>
And the following in the C# code:
try
{
SqlDataSource3.Insert();//Insert quote details into the database using a stored procedure
}catch (Exception ex)
{LabelInsertException.Text = "Failed" + ex.Message;
}
Any help would be much appreciated
Thanks, Hayley
 
 

View Replies !
Duplicate Record Inserted With Stored Procedure
I'm calling the stored procedure below to insert a record but every record is inserted into my table twice. I can't figure out why. I'm using Sql Server 2000.  Thanks.CREATE PROCEDURE sp_AddUserLog(@Username varchar(100),@IP varchar(50))AS SET NOCOUNT ONINSERT INTO TUserLogs (Username, IP) VALUES (@Username, @IP)GO  Sub AddUserLog(ByVal Username As String)
Dim SqlText As String
Dim cmd As SqlCommand
Dim strIPAddress As String

'Get the users IP address
strIPAddress = Request.UserHostAddress

Dim con As New SqlConnection(ConfigurationManager.ConnectionStrings("MyConnectionString").ConnectionString)
SqlText = "sp_AddUserLog"
cmd = New SqlCommand(SqlText)
cmd.CommandType = CommandType.StoredProcedure
cmd.Connection = con

cmd.Parameters.Add("@Username", SqlDbType.VarChar, 100).Value = Username
cmd.Parameters.Add("@IP", SqlDbType.VarChar, 100).Value = strIPAddress

Try
con.Open()
cmd.ExecuteNonQuery()
Finally
con.Close()
End Try

End Sub 

View Replies !
SQLDataSource - How To Retreive The New GUID Value Of A New Inserted Record?
I am using ASP.NET 3.5 with SQLDataSource, when a record is inserted is there a way to retreive the newly created GUID value in a field?
I am currently using SELECT @NewID = SCOPE_IDENTITY() to retreive the newly created record unique ID field, but I need the secondary field GUID field's value instead in this case.
Thank you.

View Replies !
Can Insert Trigger Update Record Being Inserted
I think a trigger is the way to go on this but let me try to explain the confusion. I have a table with an id field. Based upon this ID field I need to have a character stripped out of the ID and placed in another column on the same table/same record(Sorry, because of the development env I can't use a computer column). The question is how to do this with an insert trigger. My understanding is the trigger will fire on the insert, but the record isn't there yet. Is there a way to handle this? My code below does not error but also does not update?

create TRIGGER test_Ins_tr
ON table1
FOR update
AS
DECLARE @oid char(1)
declare @actid char(10)
SELECT @oid = SUBSTRING(right(col1,2),1,1), @actid = col1
FROM inserted
update table1
set col2 = @oid where table1.col1 = @actid

View Replies !
Returning Timestamp From Inserted Record Using @@Identity
i recently found a little error in a stored procedure that was included in a project handed over to me....

the sp was rather simple. it just inserted a record into a table and returned the identity and the timestamp as follows

IF @@ERROR>0
 BEGIN
 SELECT @int_InterventionID = 0
 RETURN @@ERROR
 END
ELSE
 BEGIN 
 SELECT @int_InterventionIDReturned = MAX(InterventionID) FROM tblIntervention
 SELECT @ts_TimestampReturned = [Timestamp] FROM tblIntervention WHERE InterventionID = @int_InterventionIDReturned
 SELECT @int_InterventionID = @int_InterventionIDReturned, @ts_Timestamp = @ts_TimestampReturned
 RETURN 0
 END

i figured that it should be using @@Identity for the interventionIdentity rather than max(InterventionID)

so i changed to...

IF @@ERROR>0
 BEGIN
 SELECT @int_InterventionID = 0
 RETURN @@ERROR
 END
ELSE
 BEGIN 
 SELECT @int_InterventionIDReturned = @@IDENTITY
 SELECT @ts_TimestampReturned = [Timestamp] FROM tblIntervention WHERE InterventionID = @int_InterventionIDReturned
 SELECT @int_InterventionID = @int_InterventionIDReturned, @ts_Timestamp = @ts_TimestampReturned
 RETURN 0
 END

it returns the @int_InterventionIDReturned but the timestamp now comes back as null??? why??

how can i ensure that i always get the timestamp of the record it has just inserted

any help greatly appreciated,
Cheers,
Craig

 

 

View Replies !
Newly Inserted Record RowID To A Label Control
Greetings all,
I am tring to capture the ID of a newly inserted record from a form to a label that I will reference in a reciept page.  I intend to pass the rowid to retrieve record information on other pages.
The insert suceeds... I just need to capture the auto generated ID for the new row to a label on the page post onclick.  Any thoughts?
 
 
 
Dim MySQL As String = "Insert into dropkick (name, status, payroll, unit, contactnumber, email, equipment, issue, timein) values (@name, @status, @payroll, @unit, @contactnumber, @email, @equipment, @issue, @timein)"Dim myConn As SqlConnection = New SqlConnection(SqlDataSource1.ConnectionString)
Dim Cmd As New SqlCommand(MySQL, myConn)Cmd.Parameters.Add(New SqlParameter("@payroll", txt_payroll.Text))
Cmd.Parameters.Add(New SqlParameter("@name", txt_name.Text))Cmd.Parameters.Add(New SqlParameter("@status", "W"))
Cmd.Parameters.Add(New SqlParameter("@unit", txt_dept.Text))Cmd.Parameters.Add(New SqlParameter("@contactnumber", txt_cell.Text))
Cmd.Parameters.Add(New SqlParameter("@email", txt_email.Text))Cmd.Parameters.Add(New SqlParameter("@equipment", txt_equipment.Text))
Cmd.Parameters.Add(New SqlParameter("@issue", txt_issue.Text))Cmd.Parameters.Add(New SqlParameter("@timein", lbl_datetime.Text))
myConn.Open()
Cmd.ExecuteNonQuery()
Label1.Visible = "true"
Page.DataBind()
myConn.Close()
Label1.Text = "Your data has been received!"
''LABEL TO BE POPULATED WITH ID OF NEW RECORD
lbl_id.Text = ID

View Replies !
Set Default DateTime To A Newly Inserted Record Question?
I am using SQL Express database and where can I set the default value to my Data field to auto insert the current date-time value?  I tried to find the setting but can't seem to find it.  Any help is much appriciated.  Thanks in advance. 
 
 
 

View Replies !
How To Excute Stored Procedure That Insert Record And Return Last Inserted Value
Dear all,
I am using C# , asp.net and sql server 2005.
Let me explain the situation.
I have written procedure to insert data into the table and return last inserted value by @@identity variable. Now my question is how do I execute this process so that I can
Get last inserted variable values      
Please help 
thanks 
 

View Replies !
Insert New Record - Primary Key
Hi
I have a table in sql server with a numeric field as Primary Key. When i insert a new record i need that primary key increments automatic (like access  auto increment) because i want avoid the possibility of duplicate Primary Keys.
Is that possible?
Thank you

View Replies !
How Do I Retrieve A Record By Primary Key?
Visual Basic 2005 Express:

I want to retrieve an SQL DataBase table record whose primary key is 4.

How do I read in that record and how do I pick up data from it?

View Replies !
Primary Key Record Inserts
I'm performing an insert on a table that has a relationship, but I also want to update the other table that has a foreign key relationship. How do I go about this? Thanks :)

View Replies !
Check For Primary Key Before Inserting New Record
Hi,
Can someone please tell me the best practices for checking the primary key field before inserting a record into my database?
As an example I have created an asp.net page using VB with an SQL server database.  The web page will just insert two fields into a table (Name & Surname into the Names table).  The primary key or the Names table is "Name".   When I click the Submit button I would like to check to ensure there is not a duplicate primary key.  If there is return a user friendly message i.e. A record already exisits, if there no duplicate, add the record.
I guess I could use try, catch within the .APSX page or would a stored procedure be better?
Thanks
Brett

View Replies !
Inserting A Record Into The Database ..problem With Primary Key..
hii I have to insert some data into a table from the webpage. For that I need to know the last occurred value in the primary key and increment this by one and then insert the new record into the table. I am working with SQL Server 2005. I am coding in VB and ASP.NET 2.0.  How will I go about this?? Is there some easy way for me to knw the last value of the primary key n then insert the record. It would be great if I get the idea more clear with the help of some code... Thanks

View Replies !
Avoid Repetition Of Primary Tables's Record
hi all,can you tell me how to avoid repetition of main records when one main(Primary table) record have more than one child(secondry table) records. I am using DataList to show records.For example I want to show the following



Tools & Equipment



http://www.mobmasti.com

MobMasti

Mobile Portal

Manufactures



http://www.manu.com

Manufacturer

desc manufactur

Rental Companies



http://www.rentit.com

Rent It

rent it desc

Buy & Sell



http://www.mobmasti2.com

MT

desc

Manufactures



http://www.allofuse.com

all stff

desc

Employment



http://www.mobmasti.com/

MobMasti

Mobile PortalAS(I want to show in the following way)



Tools & Equipment



http://www.mobmasti.com

MobMasti

Mobile Portal

Manufactures



http://www.manu.com

Manufacturer

desc manufacturhttp://www.allofuse.com  all stff  desc

Rental Companies



http://www.rentit.com

Rent It

rent it desc

Buy & Sell



http://www.mobmasti2.com

MT

desc











Employment



http://www.mobmasti.com/

MobMasti

Mobile PortalMy query is as followsSELECT     DirectoryMainCat.CategoryName, DirectoryMainCat.CategoryId, DirectoryLinks.LinkId, DirectoryLinks.Title, DirectoryLinks.Url,                       '(Hits: ' + LTRIM(STR(DirectoryLinks.HitCount)) + ')' AS total, DirectoryLinks.DescriptionFROM         DirectoryMainCat INNER JOIN                      DirectoryLinks ON DirectoryMainCat.CategoryId = DirectoryLinks.CategoryIdWHERE DirectoryLinks.Hitcount > 0ORDER BY DirectoryLinks.HitCount DESCwhere 'DirectoryMainCat' is the main table and 'DirectoryLinks' is the child table.thanks in advance.

View Replies !
Concurrent Access - New Record, Primary Key Problem....
Can someone explain what happens when two users concurrently attempt tocreate a new record in a table with an autonumber primary key? For example,user 1 creates a new record and manipulates it within a transaction makinguse (perhaps) of the @@IDENTITY value when creating other, related records.Before this transaction is complete, user 2 creates a new record and doesthe same thing. Presumably they will both have the same @@IDENTITY? Ifthis is the case, how is it possible to manage such a situation?Thanks.

View Replies !
Fuzzy Grouping Primary Record Selection
I am using a fuzzy grouping to de-dupe some data.  In this case, it is address data.

 

One issue that I am running into is that i have a set of 4 records where 3 of them are identical, and the 4th has NULL for the state. however, the fuzzy grouping insists on making this record the primary record (_key_in = _key_out).

 

I have tried sorting the source data in different ways, and as expected, this does not change the outcome.

 

First, why does it think this record is the primary, and is there anyway to "force" the data requirements for the primary record?

 

Thanks!!

View Replies !
How To Reference The Primary Key Of A Newly Added Record In Trigger?
Please help me somebody solve my problem with my first :o trigger: ALTER TRIGGER partner_update ON dbo.partner FOR UPDATE AS INSERT INTO partner (name) SELECT name FROM deleted UPDATE invoice SET id_partner= *** WHERE id_partner = (SELECT id_partner FROM deleted) *** - here I want to add a "reference" to the newly added record's automatically generated primary key (not to the updated!) Is it possible?

View Replies !
How To Set Null To Foreign Key Automatically When Primary Record Is Deleted
Is it possible to create a FOREIGN KEY in MS SQL so that
its value is assigned to Null automatically in case if record from referrred table is deleted? SQL-92 standard allows it but I don't see any oprion in transact SQL reference. I wouldn't like to use trigger here.

View Replies !
Computing The CPU Usage ,memory Usage For An Inserted Record
 
 

 I have a client program that writes to sql server database 10 records per second . i want to compute the CPU usage and the memory usage for the whole program  or CPU usage,memory usage  for the insert statement in the program .
 
Can anybody help me with this?
 
 
 

View Replies !
Fix Legacy Data - Missing Primary Key + Duplication Record + Large Table
We have a large table which is very old and not much ppl take care about, recently there is a performance problem from the report need to query to this table. Eventally we find that this table have primary key missing and there is duplicate data which make "alter table add primary key" don't work

Besides the data size of this table require unacceptable time to execute something like "insert into new_table_with_pk from select distinct * from old table"

Do you have any recommendation of fixing this? As the application run on oracle , sybase and sql server, is that cross database approace will work?

View Replies !
How To Solve &"Tables Or Functions 'inserted' And 'inserted' Have The Same Exposed Names. &"
Hi all!In a insert-trigger I have two joins on the table named inserted.Obviously this construction gives a name collition beetween the twojoins (since both joins starts from the same table)Ofcourse I thougt the usingbla JOIN bla ON bla bla bla AS a_different_name would work, but itdoes not. Is there a nice solution to this problem?Any help appriciated

View Replies !
Convert Composite Primary Key Into Simple Primary Key
Uma writes "Hi Dear,
I have A Table , Which Primary key consists of 6 columns.
total Number of Columns in the table are 16. Now i Want to Convert my Composite Primary key into simple primary key.there are already 2200 records in the table and no referential integrity (foriegn key ) exist.

may i convert Composite Primary key into simple primary key in thr table like this.



Thanks,
Uma"

View Replies !
Adding Primary Key To A Table Which Has Already A Primary Key
Hi all,
Can anyone suggest me on Adding primary key to a table which has already a primary key.

Thanks,
Jeyam

View Replies !

Copyright © 2005-08 www.BigResource.com, All rights reserved