INSERT Command - Retrieve PK While Inserting To Table

Sep 16, 2009

I have a primary key named pk, name and surname fields. I need to insert to my table names and surnames.

INSERT INTO People (name,surname) VALUES ('john','black');

I'm not giving pks database gives is auto. But my problem is i need to know the pk that my database gave. Because i have lots of duplicate records. Is there any way to retrieve pk while inserting to table.

View 7 Replies


ADVERTISEMENT

I Have Created A Table Table With Name As Varchar And Id As Int. Now I Have Started Inserting The Rows Like, Insert Into Table Values ('arun',20).

Jan 31, 2008

I have created a table Table with name as Varchar and id as int. Now i have started inserting the rows like, insert into Table values ('arun',20).Yes i have inserted a row in the table. Now i have got the values " arun's ", 50.                 insert into Table values('arun's',20)  My sqlserver is giving me an error instead of inserting the row. How will you solve this problem? 
 

View 3 Replies View Related

Insert Command Fails When I Want To Insert Records In Data Table

Apr 20, 2008

On my site users can register using ASP Membership Create user Wizard control.
I am also using the wizard control to design a simple question and answer  form that logged in users have access to.
it has 2 questions including a text box for Q1 and  dropdown list for Q2.
I have a table in my database called "Players" which has 3 Columns
UserId Primary Key of type Unique Identifyer
PlayerName Type String
PlayerGenre Type Sting
 
On completing the wizard and clicking the finish button, I want the data to be inserted into the SQl express Players table.
I am having problems getting this to work and keep getting exceptions.
 Be very helpful if somebody could check the code and advise where the problem is??
 
 
<asp:Wizard ID="Wizard1" runat="server" BackColor="#F7F6F3"
BorderColor="#CCCCCC" BorderStyle="Solid" BorderWidth="1px"
DisplaySideBar="False" Font-Names="Verdana" Font-Size="0.8em" Height="354px"
onfinishbuttonclick="Wizard1_FinishButtonClick" Width="631px">
<SideBarTemplate>
<asp:DataList ID="SideBarList" runat="server">
<ItemTemplate>
<asp:LinkButton ID="SideBarButton" runat="server" BorderWidth="0px"
Font-Names="Verdana" ForeColor="White"></asp:LinkButton>
</ItemTemplate>
<SelectedItemStyle Font-Bold="True" />
</asp:DataList>
</SideBarTemplate>
<StepStyle BackColor="#669999" BorderWidth="0px" ForeColor="#5D7B9D" />
<NavigationStyle VerticalAlign="Top" />
<WizardSteps>
<asp:WizardStep runat="server">
<table class="style1">
<tr>
<td class="style4">
A<span class="style6">Player Name</span></td>
<td class="style3">
<asp:TextBox ID="PlayerName" runat="server"></asp:TextBox>
</td>
<td>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
ControlToValidate="PlayerName" ErrorMessage="RequiredFieldValidator"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td class="style5">
 
<td class="style3">
<asp:DropDownList ID="PlayerGenre" runat="server" Width="128px">
<asp:ListItem Value="-1">Select Genre</asp:ListItem>
<asp:ListItem>Male</asp:ListItem>
<asp:ListItem>Female</asp:ListItem>
</asp:DropDownList>
</td>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server"
ControlToValidate="PlayerGenre" ErrorMessage="RequiredFieldValidator"></asp:RequiredFieldValidator>
</td>
 
</tr>
</table>
  Sql Data Source
<asp:SqlDataSource ID="InsertArtist1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" InsertCommand="INSERT INTO [Playerst] ([UserId], [PlayerName], [PlayerGenre]) VALUES (@UserId, @PlayerName, @PlayerGenre)"
 
ProviderName="<%$ ConnectionStrings:ConnectionString.ProviderName %>">
<InsertParameters>
<asp:Parameter Name="UserId" Type="Object" />
<asp:Parameter Name="PlayerName" Type="String" />
<asp:Parameter Name="PlayerGenre" Type="String" />
</InsertParameters>
 
 
</asp:SqlDataSource>
</asp:WizardStep>
 
 Event Handler
 
To match the answers to the user I get the UserId and insert this into the database to.protected void Wizard1_FinishButtonClick(object sender, WizardNavigationEventArgs e)
{
 SqlDataSource DataSource = (SqlDataSource)Wizard1.FindControl("InsertArtist1");
MembershipUser myUser = Membership.GetUser(this.User.Identity.Name);
Guid UserId = (Guid)myUser.ProviderUserKey;String Gender = ((DropDownList)Wizard1.FindControl("PlayerGenre")).SelectedValue;
DataSource.InsertParameters.Add("UserId", UserId.ToString());DataSource.InsertParameters.Add("PlayerGenre", Gender.ToString());
DataSource.Insert();
 
}
 

View 1 Replies View Related

How Can I Insert, Retrieve Date From ASPX Page In Table ??

Mar 2, 2006

hello all
pls tell me
how can i insert, retrieve  date from ASPX(vs2003)  page in table in sql server 2000??
i m in trouble
pls help me
 
 
 

View 1 Replies View Related

Insert Information And To Database And Retrieve The ID Created For That Row Of Data In The Table

May 4, 2007

Hi,
 I am working on inserting information into a DB and then retrieving the ID created for that Data to use elsewhere in my code. I have the code below but I do not know how to get toOutput parameter. Can anyone please help?
  
CREATE PROCEDURE dbo.InsertProduction
@DATEOUT datetime(8),
@DATEREQUIRED datetime(8),
@PREPAREDBY varchar,
@COMMENTID INteger,
@TOTALQUANTITY INteger,
@VENDORID INteger,
@WPO varchar,
@TCAPONUMBER INteger,
@APPROVEDBY varchar,
@Identity int OUT
 
AS
INSERT INTO PRODUCTION (DATEOUT,DATEREQUIRED, PREPAREDBY, COMMENTID, TOTALQUANTITY, VENDORID, WPO, TCAPONUMBER, APPROVEDBY) VALUES( @DATEOUT, @DATEREQUIRED, @PREPAREDBY, @COMMENTID, @TOTALQUANTITY, @VENDORID, @WPO, @TCAPONUMBER, @APPROVEDBY)
SET @Identity = SCOPE_IDENTITY()
 
 
'collect all the information from the form and then apply all and then update
'Get a reference to the Production table.
Dim dtProduction As DataTable = DS.Tables("Production")
Dim dtLineItem As DataTable = DS.Tables("LineItems")
' Create the SqlCommand to execute the stored procedure.
Production.InsertCommand = New SqlCommand("dbo.InsertProduction", connection)
Production.InsertCommand.CommandType = CommandType.StoredProcedure
' Add the parameter for the CategoryName. Specifying the
' ParameterDirection for an input parameter is not required.
'Production.InsertCommand.Parameters.Add("@CategoryName", SqlDbType.NVarChar, 15, "CategoryName")
Production.InsertCommand.Parameters.Add("@DATEOUT", SqlDbType.DateTime, 8, "CategoryName")
Production.InsertCommand.Parameters.Add("@DATEREQUIRED", SqlDbType.DateTime, 8, "CategoryName")
Production.InsertCommand.Parameters.Add("@PREPAREDBY", SqlDbType.VarChar, 50, "CategoryName")
Production.InsertCommand.Parameters.Add("@COMMENTID", SqlDbType.Int, 4, "CategoryName")
Production.InsertCommand.Parameters.Add("@TOTALQUANTITY", SqlDbType.Int, 4, "CategoryName")
Production.InsertCommand.Parameters.Add("@VENDORID", SqlDbType.Int, 4, "CategoryName")
Production.InsertCommand.Parameters.Add("@WPO", SqlDbType.VarChar, 50, "CategoryName")
Production.InsertCommand.Parameters.Add("@TCAPONUMBER", SqlDbType.Int, 4, "CategoryName")
Production.InsertCommand.Parameters.Add("@APPROVEDBY", SqlDbType.VarChar, 50, "CategoryName")
' Add the SqlParameter to retrieve the new identity value.
' Specify the ParameterDirection as Output.
Dim parameter As SqlParameter = Production.InsertCommand.Parameters.Add("@Identity", SqlDbType.Int, 0, "ProductionID")
parameter.Direction = ParameterDirection.Output
' Create a new row with the same schema.
Dim dr As DataRow = dtProduction.NewRow()
'you need the ID from this to insert into the Production DB
' Set the value of all the columns.
dr("DateOut") = CDate(DateTimePicker1.Text)
dr("DateRequired") = CDate(DateTimePicker2.Text)
dr("VendorID") = CInt(vendorbox.SelectedValue)
dr("HomeAddress") = txtApproved.Text.ToString
dr("ApprovedBy") = txtPrepared.Text.ToString
dr("TCAPO") = CInt(txtTCAPO.Text.Trim)
dr("CommentID") = CommentID
dr("TotalCost") = CDec(txtTotals.Text)
dr("TotalQuantity") = CInt(txtQtyTotal.Text)
' Add to the Rows collection or table .
dtProduction.Rows.Add(dr)
'Update the Production Table and then retrieve the ID created in this case
Production.Update(dtProduction)
 
 
Dollarjunkie

View 2 Replies View Related

SQL INSERT Command From One Table To Another?

Dec 19, 2007

i have a question if anyone can help please..
i have need to create a database table as a go-between, where users will upload info.  then on a backend page admin will make some data settings, then transfer it to the proper, permanent tables.(all this to avoid expecting users themselves to upload files to proper places).
can i use a basic SQL INSERT statement to move from one table directly to another without the use of parameters? for example,
INSERT INTO tblOne (fieldOne,fieldTwo,fieldThree) VALUES (tblTwo(fieldOne,fieldTwo,fieldThree)
if so, what is the syntax? and if not, then what would i have to do, just use some go between variables or objects? perhaps a DataSet to pull the values, then use same DataSet to load the values into new table, then a simple DELETE statement on the intermediate table?
i mean, i can work my way through this, but if anybody has gone through a similar situation i sure could use any pointers or tips to keep it as clean and simple as possible.
thanks all!

View 3 Replies View Related

Inserting Domain Username Into Table On Insert

Apr 7, 2006

Hi there
I have a book and I'm learning now, but I really want to get this working as soon as possible as it will convince the boss to give me more time to study as it will blow him away. (I started this 2 hours ago and it's all working except for this bit). He's used to me building apps in weeks not hours.
I have an online application form that inserts data to a sql 2k5 db and then displays it in another administrators web form. I have used login views which work great with Active Directory (Tokens) to display correct information. (It's not a highly secure app so relax).
All the simple stuff works a treat, but I am trying to write the Domain/Username to the database with an update command.
I can display this information on the form using Page.User.Identity.Name, but how can I add it to the update command to insert it to the DB?
Here is the code for the entire page, and code behind at bottom. I want the Domain/Username to be inserted into the @ByUSername field.
Many thanks
=======aspx code====================
<%@ Page Language="VB" Debug="true" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>NURF</title>
</head>
<body bgcolor="#f3f5fa">
<form id="form1" runat="server">
<div>
<asp:SqlDataSource ID="SqlWinUserRequests" runat="server" ConnectionString="<%$ ConnectionStrings:IM&TSystems on BOHWEB1 %>"
InsertCommand="INSERT INTO WinUsers (ByFullName, ByPosition, ByInternalTel, ByEmail, NewTitle, NewForename, NewSurname, NewPositionHeld, NewLocation, AccDateOfRequest, AccDateRequired, AccAccountToCopy, NewInternalTel, ByUsername) VALUES (@ByFullName,@ByPosition,@ByInternalTel,@ByEmail,@NewTitle,@NewForename,@NewSurname,@NewPositionHeld,@NewLocation, { fn NOW() },@AccDateRequired,@AccAccountToCopy,@NewInternalTel, <%Page.USER.IDENTITY.Name%>)"
ProviderName="<%$ ConnectionStrings:IM&TSystems on BOHWEB1.ProviderName %>" SelectCommand="SELECT ID, ByFullName, ByPosition, ByInternalTel, ByEmail, ByUsername, NewTitle, NewForename, NewSurname, NewPositionHeld, NewLocation, AccDateOfRequest, AccDateRequired, AccAccountToCopy, NewInternalTel FROM WinUsers">
<InsertParameters>
<asp:Parameter Name="ByFullName" />
<asp:Parameter Name="ByPosition" />
<asp:Parameter Name="ByInternalTel" />
<asp:Parameter Name="ByEmail" />
<asp:Parameter Name="NewTitle" />
<asp:Parameter Name="NewForename" />
<asp:Parameter Name="NewSurname" />
<asp:Parameter Name="NewPositionHeld" />
<asp:Parameter Name="NewLocation" />
<asp:Parameter Name="AccDateRequired" Type="DateTime" />
<asp:Parameter Name="AccAccountToCopy" />
<asp:Parameter Name="NewInternalTel" />
</InsertParameters>
</asp:SqlDataSource>
<asp:SqlDataSource ID="SqlLocations" runat="server" ConnectionString="<%$ ConnectionStrings:IM&TSystems on BOHWEB1 %>"
SelectCommand="SELECT [Location] FROM [Locations] ORDER BY [Location]"></asp:SqlDataSource>
<asp:FormView ID="FormView1" runat="server" DataSourceID="SqlWinUserRequests">
<EditItemTemplate>
<asp:LinkButton ID="NewButton" runat="server" CausesValidation="False" CommandName="New"
Font-Bold="True" Font-Names="Verdana" Font-Size="14pt" ForeColor="#000000" Text="Request a new windows user account"></asp:LinkButton>
</EditItemTemplate>
<EmptyDataTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False" CommandName="New"
Font-Bold="True" Font-Names="Verdana" Font-Size="14pt" ForeColor="#000000" Text="Request a new windows user account"></asp:LinkButton>
</EmptyDataTemplate>
<InsertItemTemplate>
<span style="font-size: 14pt; font-family: Verdana"><strong>Request a new windows user
account</strong></span><br />

<table style="font-size: small; font-family: Verdana" width="750">
<tr>
<td colspan="3" style="height: 21px">
</td>
<td style="height: 21px; width: 10px;">
</td>
<td style="height: 21px">
</td>
</tr>
<tr>
<td colspan="3">
<strong><span style="font-size: 12pt; color: gray">Your Details (Line Managers Only)</span></strong></td>
<td style="width: 10px">
</td>
<td style="height: 21px">
</td>
</tr>
<tr>
<td width="150" style="text-align: right">
Full Name</td>
<td>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="ByFullNameTextBox"
ErrorMessage="Please supply your name">*</asp:RequiredFieldValidator></td>
<td style="width: 244px">
<asp:TextBox ID="ByFullNameTextBox" runat="server" Text='<%# Bind("ByFullName") %>'
Width="235px"></asp:TextBox></td>
<td style="width: 10px">
</td>
<td rowspan="14" valign="top">
<asp:ValidationSummary ID="ValidationSummary1" runat="server" Font-Size="12pt" />
</td>
</tr>
<tr>
<td width="150" style="text-align: right">
Position</td>
<td>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="ByPositionTextBox"
ErrorMessage="Please supply your position">*</asp:RequiredFieldValidator></td>
<td style="width: 244px">
<asp:TextBox ID="ByPositionTextBox" runat="server" Text='<%# Bind("ByPosition") %>'
Width="235px"></asp:TextBox></td>
<td style="width: 10px">
</td>
</tr>
<tr>
<td width="150" style="text-align: right">
Email</td>
<td>
<asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ControlToValidate="ByEmailTextBox"
ErrorMessage="Please supply your email address">*</asp:RequiredFieldValidator></td>
<td style="width: 244px">
<asp:TextBox ID="ByEmailTextBox" runat="server" Text='<%# Bind("ByEmail") %>' Width="235px"></asp:TextBox></td>
<td style="width: 10px">
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ControlToValidate="ByEmailTextBox"
ErrorMessage="Please enter a valid HSSD email address" ValidationExpression="w+([-+.']w+)*@w+([-.]w+)*.gov.gg">*</asp:RegularExpressionValidator></td>
</tr>
<tr>
<td width="150" style="text-align: right; height: 26px;">
Internal Tel</td>
<td style="height: 26px">
<asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server" ControlToValidate="ByInternalTelTextBox"
ErrorMessage="Please supply your internal telephone number">*</asp:RequiredFieldValidator></td>
<td style="width: 244px; height: 26px;">
<asp:TextBox ID="ByInternalTelTextBox" runat="server" Text='<%# Bind("ByInternalTel") %>'
Width="60px"></asp:TextBox></td>
<td style="width: 10px; height: 26px;">
<asp:RegularExpressionValidator ID="RegularExpressionValidator2" runat="server" ControlToValidate="ByInternalTelTextBox"
ErrorMessage="Please enter a valid HSSD internal telephone" ValidationExpression="d{4}">*</asp:RegularExpressionValidator></td>
</tr>
<tr>
<td width="150" style="height: 26px; text-align: right">
Username</td>
<td style="height: 26px">
&nbsp;</td>
<td style="width: 244px; height: 26px">
<asp:Label ID="Label1" runat="server" Text="<%# page.user.identity.name %>"></asp:Label></td>
<td style="width: 10px; height: 26px">
</td>
</tr>
<tr>
<td colspan="3" style="height: 20px">
</td>
<td style="width: 10px; height: 20px;">
&nbsp;</td>
</tr>
<tr>
<td colspan="3">
<span style="font-size: 12pt; color: gray"><strong>New Account Details</strong></span></td>
<td style="width: 10px;">
</td>
</tr>
<tr>
<td style="text-align: right" width="150">
Title</td>
<td style="width: 13px; text-align: right">
</td>
<td style="width: 244px">
<asp:DropDownList ID="DropDownList1" runat="server" SelectedValue='<%# Bind("NewTitle") %>' Width="60px">
<asp:ListItem Value="Mr"></asp:ListItem>
<asp:ListItem Value="Mrs"></asp:ListItem>
<asp:ListItem Value="Miss"></asp:ListItem>
<asp:ListItem Value="Ms"></asp:ListItem>
<asp:ListItem Value="Dr"></asp:ListItem>
<asp:ListItem Value="Sr"></asp:ListItem>
<asp:ListItem></asp:ListItem>
</asp:DropDownList></td>
<td style="width: 10px">
</td>
</tr>
<tr>
<td style="text-align: right" width="150">
Forename</td>
<td style="width: 13px; text-align: right">
<asp:RequiredFieldValidator ID="RequiredFieldValidator6" runat="server" ControlToValidate="NewForenameTextBox"
ErrorMessage="Please supply new user's forename">*</asp:RequiredFieldValidator></td>
<td style="width: 244px">
<asp:TextBox ID="NewForenameTextBox" runat="server" Text='<%# Bind("NewForename") %>'
Width="235px"></asp:TextBox></td>
<td style="width: 10px">
</td>
</tr>
<tr>
<td style="text-align: right" width="150">
Surname</td>
<td style="width: 13px; text-align: right">
<asp:RequiredFieldValidator ID="RequiredFieldValidator7" runat="server" ControlToValidate="NewSurnameTextBox"
ErrorMessage="Please supply new user's surname">*</asp:RequiredFieldValidator></td>
<td style="width: 244px">
<asp:TextBox ID="NewSurnameTextBox" runat="server" Text='<%# Bind("NewSurname") %>'
Width="235px"></asp:TextBox></td>
<td style="width: 10px">
</td>
</tr>
<tr>
<td style="text-align: right" width="150">
Position</td>
<td style="width: 13px; text-align: right">
<asp:RequiredFieldValidator ID="RequiredFieldValidator8" runat="server" ControlToValidate="NewPositionHeldTextBox"
ErrorMessage="Please supply new user's position">*</asp:RequiredFieldValidator></td>
<td style="width: 244px">
<asp:TextBox ID="NewPositionHeldTextBox" runat="server" Text='<%# Bind("NewPositionHeld") %>'
Width="235px"></asp:TextBox></td>
<td style="width: 10px">
</td>
</tr>
<tr>
<td style="text-align: right" width="150">
Location</td>
<td style="width: 13px; text-align: right">
<asp:RequiredFieldValidator ID="RequiredFieldValidator9" runat="server" ControlToValidate="DropDownList2"
ErrorMessage="Please supply new user's location">*</asp:RequiredFieldValidator></td>
<td style="width: 244px">
<asp:DropDownList ID="DropDownList2" runat="server" DataSourceID="SqlLocations" DataTextField="Location"
DataValueField="Location" SelectedValue='<%# Bind("NewLocation") %>' Width="241px">
</asp:DropDownList></td>
<td style="width: 10px">
</td>
</tr>
<tr>
<td style="text-align: right" width="150">
Date
Required</td>
<td style="width: 13px; text-align: right">
</td>
<td style="width: 244px">
<asp:TextBox ID="AccDateRequiredTextBox" runat="server" Text='<%# Bind("AccDateRequired", "{0:d}") %>'
Width="60px"></asp:TextBox></td>
<td style="width: 10px">
</td>
</tr>
<tr>
<td style="text-align: right; height: 26px;" width="150">
Similar Account</td>
<td style="width: 13px; text-align: right; height: 26px;">
<asp:RequiredFieldValidator ID="RequiredFieldValidator10" runat="server" ControlToValidate="AccAccountToCopyTextBox"
ErrorMessage="Please supply the Name of a user with the same account priveledges">*</asp:RequiredFieldValidator></td>
<td style="width: 244px; height: 26px;">
<asp:TextBox ID="AccAccountToCopyTextBox" runat="server" Text='<%# Bind("AccAccountToCopy") %>'
Width="235px"></asp:TextBox></td>
<td style="width: 10px; height: 26px;">
</td>
</tr>
<tr postbackurl="ThankYou.htm">
<td width="150" style="text-align: right">
Contact Tel</td>
<td style="width: 13px">
</td>
<td style="width: 244px; text-align: left">
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("NewInternalTel") %>' Width="100px"></asp:TextBox></td>
<td style="width: 10px">
</td>
<td>
</td>
</tr>
<tr>
<td width="150" style="height: 26px">
</td>
<td style="width: 13px; height: 26px;">
</td>
<td style="width: 244px; text-align: right; height: 26px;">
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click"
Text="Send Request" />&nbsp;
</td>
<td style="width: 10px; height: 26px;">
</td>
<td style="height: 26px">
</td>
</tr>
</table>
</InsertItemTemplate>
<ItemTemplate>
<asp:LinkButton ID="NewButton" runat="server" CausesValidation="False" CommandName="New"
Font-Bold="True" Font-Names="Verdana" Font-Size="11pt" ForeColor="#000000" Text="Request a new Windows user account including MS Office, email and Internet access"></asp:LinkButton>
</ItemTemplate>
<EmptyDataRowStyle BackColor="#F3F5FA" />
</asp:FormView>
&nbsp;<span style="font-size: 10pt; font-family: Verdana">Please note that this form may only
be completed by a line manager from the applicant's department.</span>&nbsp;&nbsp;</div>
</form>
</body>
</html>
 
=================end aspx code=============
=================code behind==============
Partial Class _Default
Inherits System.Web.UI.Page
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
FormView1.InsertItem(True)
End Sub
Protected Sub FormView1_ItemInserted(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.FormViewInsertedEventArgs) Handles FormView1.ItemInserted
Dim Message As String
Message = ", your request has been recieved by IM&T."
System.Web.HttpContext.Current.Response.Write("<SCRIPT LANGUAGE=""JavaScript"">" & vbCrLf)
System.Web.HttpContext.Current.Response.Write("alert (""" & Page.User.Identity.Name & Message & """)" & vbCrLf)
System.Web.HttpContext.Current.Response.Write("</SCRIPT>")
End Sub
End Class
 
=================end code behind==========

View 3 Replies View Related

Need Help Inserting Data Into Table With Sql Insert Into Using Textbox Values

Oct 6, 2007

the error message I get is
{"Object reference not set to an instance of an object."}
and it points to <  Tickr As String = CType(FindControl("TickerTextbx"), TextBox).Text >   
 this is my code":
 Protected Sub TickMastBtn_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles TickMastBtn.Click
REM Collect variablesDim Tickr As String = CType(FindControl("TickerTextbx"), TextBox).Text
Dim Comp As String = CType(FindControl("CoTextbx"), TextBox).TextDim Exch As String = CType(FindControl("ExchTextbx"), TextBox).Text
REM Create connection and command objectsDim cn As New SqlConnection("Data Source=.SQLEXPRESS;AttachDbFilename=C:Program FilesMicrosoft SQL ServerMSSQL.1MSSQLDataVTRADE.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True")Dim cmd As New SqlCommand
cmd.Connection = cn
REM Build our parameterized insert statementDim sql As New StringBuilder
sql.Append("INSERT INTO TickerMaster ")sql.Append("(Ticker,Company,Exchange,) ")sql.Append("VALUES (@Tickr,@Comp,@Exch,)")
cmd.CommandText = sql.ToString
REM Add parameter values to command
REM Parameters used to protect DB from SQL injection attacksWith cmd.Parameters
.Add("Tickr", SqlDbType.Int).Value = Tickr.Add("Comp", SqlDbType.VarChar).Value = Comp
.Add("Exch", SqlDbType.VarChar).Value = Exch
End With
REM Now execute the statement
cn.Open()
cmd.ExecuteNonQuery()
cn.Close()
End Sub

View 3 Replies View Related

Skip Field Terminator While Inserting Data To A Table-Bulk Insert

Oct 10, 2007

Hi,
I have a data file which consists of data as below,
4
PPU_FFA7485E0D||
T_GLR_DET_11||

While iam inserting into table using bulk insert, this pipe(||) is also getting inserted into the table,
here is my query iam using to insert the data using bulk insert.

BULK INSERT TABLE_NAME FROM FILE_PATH
WITH (FIELDTERMINATOR = ''||'''+',KEEPNULLS,FIRSTROW=2,ROWTERMINATOR = '''')




Can any one help on this.

Thanks,
-Badri

View 7 Replies View Related

Stored Procedure Not Inserting Into Linking Table Properly - Two Tables - Two Insert Statements

Dec 9, 2007

Hi can anyone help me with the format of my stored procedure below.
I have two tables (Publication and PublicationAuthors). PublicaitonAuthors is the linking table containing foreign keys PublicaitonID and AuthorID. Seeming as one Publication can have many authors associated with it, i need the stored procedure to create the a single row in the publication table and then recognise that multiple authors need to be inserted into the linking table for that single PublicationID. For this i have a listbox with multiple selection =true.
At the moment with the storedprocedure below it is creating two rows in PublicaitonID, and then inserting two rows into PublicationAuthors with only the first selected Author from the listbox??? Can anyone help???ALTER PROCEDURE dbo.StoredProcedureTest2
@publicationID Int=null,@typeID smallint=null,
@title nvarchar(MAX)=null,@authorID smallint=null
AS
BEGIN TRANSACTION
SET NOCOUNT ON
DECLARE @ERROR Int
--Create a new publication entry
INSERT INTO Publication (typeID, title)
VALUES (@typeID, @title)
--Obtain the ID of the created publication
SET @publicationID = @@IDENTITY
SET @ERROR = @@ERROR
--Create new entry in linking table PublicationAuthors
INSERT INTO PublicationAuthors (publicationID, authorID)
VALUES (@publicationID, @authorID)
SET @ERROR = @@ERROR
IF (@ERROR<>0)
ROLLBACK TRANSACTION
ELSE
COMMIT TRANSACTION

View 9 Replies View Related

Stored Procedure Not Inserting Into Linking Table Properly - Two Tables - Two Insert Statements

Dec 9, 2007

Hi can anyone help me with the format of my stored procedure below.
I have two tables (Publication and PublicationAuthors). PublicaitonAuthors is the linking table containing foreign keys PublicaitonID and AuthorID. Seeming as one Publication can have many authors associated with it, i need the stored procedure to create the a single row in the publication table and then recognise that multiple authors need to be inserted into the linking table for that single PublicationID. For this i have a listbox with multiple selection =true.
At the moment with the storedprocedure below it is creating two rows in PublicaitonID, and then inserting two rows into PublicationAuthors with only the first selected Author from the listbox??? Can anyone help???ALTER PROCEDURE dbo.StoredProcedureTest2
@publicationID Int=null,@typeID smallint=null,
@title nvarchar(MAX)=null,@authorID smallint=null
AS
BEGIN TRANSACTION
SET NOCOUNT ON
DECLARE @ERROR Int
--Create a new publication entry
INSERT INTO Publication (typeID, title)
VALUES (@typeID, @title)
--Obtain the ID of the created publication
SET @publicationID = @@IDENTITY
SET @ERROR = @@ERROR
--Create new entry in linking table PublicationAuthors
INSERT INTO PublicationAuthors (publicationID, authorID)
VALUES (@publicationID, @authorID)
SET @ERROR = @@ERROR
IF (@ERROR<>0)
ROLLBACK TRANSACTION
ELSE
COMMIT TRANSACTION

View 12 Replies View Related

I Can't Retrieve Data After Inserting It ?

Mar 1, 2008

Dears,
I'm using FormView to insert and retrieve data from SQL Server Database 2000. I'm using stored procedure to insert and display data by using C#.
Every time I insert the data, I can't retrive it. To retrieve all the inserted data, I have to close my website, and then reopen it again.
I close the connection every time after using the stored procedures, but nothing happened.
What do you think the problem is ??
 

View 3 Replies View Related

Defining Command,commandtype And Connectionstring For SELECT Command Is Not Similar To INSERT And UPDATE

Feb 23, 2007

i am using visual web developer 2005 and SQL 2005 with VB as the code behindi am using INSERT command like this        Dim test As New SqlDataSource()        test.ConnectionString = ConfigurationManager.ConnectionStrings("DatabaseConnectionString1").ToString()        test.InsertCommandType = SqlDataSourceCommandType.Text        test.InsertCommand = "INSERT INTO try (roll,name, age, email) VALUES (@roll,@name, @age, @email) "                  test.InsertParameters.Add("roll", TextBox1.Text)        test.InsertParameters.Add("name", TextBox2.Text)        test.InsertParameters.Add("age", TextBox3.Text)        test.InsertParameters.Add("email", TextBox4.Text)        test.Insert() i am using UPDATE command like this        Dim test As New SqlDataSource()        test.ConnectionString = ConfigurationManager.ConnectionStrings("DatabaseConnectionString").ToString()        test.UpdateCommandType = SqlDataSourceCommandType.Text        test.UpdateCommand = "UPDATE try SET name = '" + myname + "' , age = '" + myage + "' , email = '" + myemail + "' WHERE roll                                                         123 "        test.Update()but i have to use the SELECT command like this which is completely different from INSERT and  UPDATE commands   Dim tblData As New Data.DataTable()         Dim conn As New Data.SqlClient.SqlConnection("Data Source=.SQLEXPRESS;AttachDbFilename=|DataDirectory|Database.mdf;Integrated                                                                                Security=True;User Instance=True")   Dim Command As New Data.SqlClient.SqlCommand("SELECT * FROM try WHERE age = '100' ", conn)   Dim da As New Data.SqlClient.SqlDataAdapter(Command)   da.Fill(tblData)   conn.Close()                   TextBox4.Text = tblData.Rows(1).Item("name").ToString()        TextBox5.Text = tblData.Rows(1).Item("age").ToString()        TextBox6.Text = tblData.Rows(1).Item("email").ToString()       for INSERT and UPDATE commands defining the command,commandtype and connectionstring is samebut for the SELECT command it is completely different. why ?can i define the command,commandtype and connectionstring for SELECT command similar to INSERT and UPDATE ?if its possible how to do ?please help me

View 2 Replies View Related

Retrieve Guid After Inserting Recrod With NEWID()

Mar 3, 2007

Hi There,
I'm having a problem retreiving the auto generated Guid after inserting anew record with NEWID(), my stored proc is as follows:SET @uiTransactionID = NEWID()
INSERT INTO Transactions (uiTransactionID) VALUES (@uiTransactionID)
IF @@ERROR = 0 AND @@ROWCOUNT = 1
BEGIN
SELECT @uiTransactionID AS '@@GUID'
RETURN 0
END
 And the return on my insert statement is:
command.ExecuteNonQuery();m_uiTransactionID = (Guid)command.Parameters["RETURN_VALUE"].Value;
I can never retreive the newly generated Guid, can onyone spot where i'm going wrong?
Many thanks
Ben

View 2 Replies View Related

Inserting Data Into Two Tables (Getting ID From Table 1 And Inserting Into Table 2)

Oct 10, 2007

I am trying to insert data into two different tables. I will insert into Table 2 based on an id I get from the Select Statement from Table1.
 Insert Table1(Title,Description,Link,Whatever)Values(@title,@description,@link,@Whatever)Select WhateverID from Table1 Where Description = @DescriptionInsert into Table2(CategoryID,WhateverID)Values(@CategoryID,@WhateverID)
 This statement is not working. What should I do? Should I use a stored procedure?? I am writing in C#. Can someone please help!!

View 3 Replies View Related

Retrieve ID Of Last Insert (Scope_Identity)

May 23, 2007

(Newbie) Hi, I am trying to create in a session variable, the ID of the last inserted record. My reading suggests I should use Scope_Identity. I'm having trouble with the syntax/code structure. Also, is it good programming practise to directly assign the session variable e.g. "Session[var]=SqlDataSource.Select()"? The error I'm getting from my code below is "No overload for method SELECT takes 0 arguments". Thanks.
Session["snCoDeptRowID"] = SqlDataSource1.Select();
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT Scope_Identity"
</asp:SqlDataSource>

View 4 Replies View Related

Retrieve Identity After Insert

Jun 1, 2006

I am a "newbie" and have been struggling with this for days!  I have users enter their residence information and insert which generates houseid.  I want to use/display that houseid on next page/step.  I am VERY FRUSTRATED and would appreciate any assistance!
<script runat="server">
Protected Sub SqlDataSource1_Inserting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.SqlDataSourceCommandEventArgs) Handles SqlDataSource1.Inserting
e.Command.Parameters("@house").Size = 5
End Sub

Protected Sub SqlDataSource1_Inserted(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.SqlDataSourceStatusEventArgs) Handles SqlDataSource1.Inserted
Dim house = e.Command.Parameters("@house").Value
Response.Write(house)
End Sub
Protected Sub Wizard1_FinishButtonClick(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.WizardNavigationEventArgs)
End Sub
Protected Sub SqlDataSource1_Selecting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.SqlDataSourceSelectingEventArgs)

End Sub
</script>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConflictDetection="CompareAllValues"
ConnectionString="<%$ ConnectionStrings:ic_registerConnectionString %>"
oninserted="SqlDataSource1_Inserted"
oninserting="SqlDataSource1_Inserting"
DeleteCommand="DELETE FROM [household] WHERE [householdid] = @original_householdid AND [housenum] = @original_housenum AND [streeraddr] = @original_streeraddr AND [aptnum] = @original_aptnum AND [city] = @original_city AND [state] = @original_state AND [zipcode] = @original_zipcode AND [HHPhone] = @original_HHPhone AND [timedate] = @original_timedate"
InsertCommand="INSERT INTO [household] ([housenum], [streeraddr], [aptnum], [city], [state], [zipcode], [HHPhone], [timedate]) VALUES (@housenum, @streeraddr, @aptnum, @city, @state, @zipcode, @HHPhone, { fn NOW() }); SELECT @house = SCOPE_IDENTITY()"
OldValuesParameterFormatString="original_{0}" SelectCommand="SELECT * FROM [household]"
UpdateCommand="UPDATE [household] SET [housenum] = @housenum, [streeraddr] = @streeraddr, [aptnum] = @aptnum, [city] = @city, [state] = @state, [zipcode] = @zipcode, [HHPhone] = @HHPhone, [timedate] = @timedate WHERE [householdid] = @original_householdid AND [housenum] = @original_housenum AND [streeraddr] = @original_streeraddr AND [aptnum] = @original_aptnum AND [city] = @original_city AND [state] = @original_state AND [zipcode] = @original_zipcode AND [HHPhone] = @original_HHPhone AND [timedate] = @original_timedate" OnSelecting="SqlDataSource1_Selecting">
<InsertParameters>
<asp:Parameter Name="housenum" Type="String" />
<asp:Parameter Name="streeraddr" Type="String" />
<asp:Parameter Name="aptnum" Type="String" />
<asp:Parameter Name="city" Type="String" />
<asp:Parameter Name="state" Type="String" />
<asp:Parameter Name="zipcode" Type="String" />
<asp:Parameter Name="HHPhone" Type="String" />
<asp:Parameter Type = "String" Name="house" Direction= "Output"/>
</InsertParameters>
Next question is this easier to do using a Wizard Control and DetailsView on a "step" or using seperate pages and FormView? Or does it matter?

View 2 Replies View Related

How To Insert And Retrieve Data From MDF File

Dec 10, 2011

I want to use sql server as a back end for my asp.net shopping cart using vb.net..i have created an "news.mdf" under app_data folder of my website in visual studio2010...but i tried to connect it to database using below command...but showing error...

sqlconnectionstring = "Data Source=.SQLEXPRESS;attachdbfilename=App_Datamyd atabase_data.mdf;Integrated Security=true;User Instance=true"
myconnection.ConnectionString = sqlconnectionstring
insertstring = "insert into News_table values(@N_head,@n_contents); "
mycommand = New SqlCommand(insertstring, myconnection)

[Code] ....

How to fix this error..and how to display this data in my site also

View 1 Replies View Related

Retrieve Identity Column After Doing An Insert

May 14, 2008

I have a table with an Identity column. Is there a way to get the automatically generated primary key after I insert something to the table? If so, what is the syntax?

View 5 Replies View Related

Retrieve Truncated Data From BULK INSERT?

Jan 10, 2007

Hi everyone. Does anyone know if you can retrieve truncated data from a BULK INSERT operation?

We have a file that needs to be inserted into a SQL Server Database. There is a field that has a maximum of 8000 characters, but some times users submit files that have more than that. We need to be able to capture the truncated data. The BULK INSERT operation does not throw an error. The only way I can think of to get the data is if I bulk insert the data into a temporary table with a memo field and then copy it over, but that may really slow down the SP.

Has anyone encountered this situation before? I also have the option of parsing the file in .NET.

Thanks and take care,

Angel

View 9 Replies View Related

How Can You Use A Variable Tablename And Retrieve The Output From The Insert?

Aug 28, 2007

We are trying to create a unique key from a table with indentity set in the table. We will have a number of these tables. Therefore, we will be creating a stored procedure and passing the table as a parameter. In this example we are setting the table.

When we run the the script, the output clause from the insert should give us a unique number from the given table in the temporary table. This example stores the output in a temporary table @tTemp.

How can you use a variable table name and retrieve the output from the Insert?


declare @tTestTable varchar (20)

set @tTestTable = 'mis.test_sequence'


--DECLARE @tTestTable TABLE ( sqVal [int] IDENTITY(1,1) NOT NULL, add_date datetime)
declare @testsql varchar (4000), @testseq int

DECLARE @tTemp table (mainpk int)

set @testsql = 'DECLARE @tTemp table (mainpk int) INSERT ' + @tTestTable + ' OUTPUT INSERTED.sqVal into @tTemp VALUES (getdate() ) SELECT @testseq=mainpk FROM @tTemp'

select @testsql

EXECUTE sp_executesql @testsql, N'@testseq int output,@tTemp table (mainpk int),@tTemp table (mainpk int) ',@tTemp,@tTemp,@testseq output,@tTemp

SELECT * FROM @tTemp



Please help
Thanks Tim.

View 3 Replies View Related

How To Retrieve The GUID Value Of A SQL NewID() Identity Column After An Insert ?

Jan 10, 2006

Hello,

In my table, i've a GUID column type. I insert a new record with NewID() function in Sql request.

Is it possible to retreive the GUID column of this new record (without requerying the table) ?

I'm using EVC, Sql Mobile 3.0 and OLE DB interface.

Thanks in advance.

View 1 Replies View Related

SQL Server Everywhere - Retrieve Identity Column After Insert Record

Jun 23, 2006

Hello

Using Visual Studio 2005 Prof and SQL Server everywhere.

How do get the identity column value after insert record.

With SQL Server 2005, its quite easy to get by creating and insert statement on the tabledapter ( Insert statement followed by a select statement where identitycolumn = scope_identity())



How do this is sql everywhere??



regards

View 1 Replies View Related

Transact SQL :: Retrieve Currently Created Date From Master Table To Load Into Parent And Child Table

May 12, 2015

In Master tabel i have these date datas

2015-05-10

2015-05-11

2015-05-12

SO when i try to load from  Master table to parent and child table i am using using expresssion like 

select B.ID,A.* FROM FLATFILE_INVENTORY AS A JOIN DMS_INVENTORY AS B ON 
A.ACDealerID=B.DMSDEALERID AND A.StockNumber=B.STOCKNUMBER AND 
A.InventoryDate=B.INVENTORYDATE AND A.VehicleVIN=B.VEHICLEVIN
WHERE convert(date,A.[FtpDate]) = convert(date,GETDATE())  and convert(date,B.Ftpdate) = convert(date,getdate()) ;

If i use this Expression i am getting the current system date data's only  from Master table to parent and child tables.

My Problem is If i do this in my local sserver using the above Expression if i loaded today date and if need to load yesterday date i can change my system date to yesterday date and i can run this Expression.so that yeserday date data alone will get loaded from Master to parent and  child tables.

If i run this expression to remote server  i cannot change the system date in server.

while using this Expression for current date its loads perfectly but when i try to load yesterday data it takes current date date only not the yesterday date data.

What is the Expression on which ever  date i am trying load in  the master table  same date need to loaded in Parent and child table without changing the system Date.

View 10 Replies View Related

What's The Accepted Way To Retrieve Records In A SQL Table With Null Values Using A Visual Studio 2005 Table Adapter?

Jan 21, 2008

I'm using an ObjectDataSource in Visual Studio to retrieve records from a SQL Server 2005 database.
 I have a very simple dilemma.  In a table I have fields FirstName, Surname, Address1, Address2, Address3 etc. None of these are mandatory fields.
It is quite common for the user not to enter data in Address2, Address3, so the values are <null> in the SQL table.
In Visual Studio 2005 I have an aspx form where users can pass search parameters to the ObjectDataSource and the results are returned according to the passed in parameters.
The WHERE clause in my Table Adapter is:WHERE (Address1 LIKE @Address1 + '%') AND (Address2 LIKE @Address2 + '%') AND   (Address3 LIKE @Address3 + '%') AND (FirstName LIKE @FirstName + '%') AND (Surname LIKE @Surname + '%')
If, for example, I simply want to search WHERE FirstName LIKE ‘R’, this does not return any results if the value of Address3 is <null>
My query is this: Could someone please show me the best way in Visual Studio 2005 to return records even if one of the Address fields is <null>.
For reference, I have tried: Address3 LIKE @Address3 + '%' OR IS NULLThis does work, however itsimply returns every instance where Address3 is <null>  (accounting for about 95% of the records in the database). Thanks in advance Simon
 

View 9 Replies View Related

SQL INSERT Command

Sep 16, 2006

Hello!I have problems with my SQL insert command..string zdroj = "server=LIBRA; database=ufd; uid=sa; password=555; ";string dotaz = "SELECT heslo FROM tbl_UFD_Uzivatelia WHERE meno='"+meno.Text+"'";SqlConnection conn = new SqlConnection(zdroj);SqlCommand sqlCmd = new SqlCommand(dotaz, conn);conn.Open(); SqlDataReader reader; reader = sqlCmd.ExecuteReader();reader.Read();Does something exist as oposite of DataReader? How can I execute insert command?Hope you will help me, thanx a lot

View 6 Replies View Related

Insert Command

Sep 29, 2006

How to pass insert sqlquery using dataset

View 2 Replies View Related

Help With Insert Into Command...

Jan 10, 2007

Hi guys! I have an INSERT INTO sqlcommand that inserts values into a table from another table. Why do I always get this error?
Violation of PRIMARY KEY constraint 'PK_TE_shounin_zangyou'. Cannot insert duplicate key in object 'dbo.TE_shounin_zangyou'.The statement has been terminated.
Here's the insert command...
      Dim update_phase As New SqlCommand("INSERT INTO TE_shounin_zangyou (syain_No,date_kyou,time_kyou) SELECT syain_No,date_kyou,time_kyou FROM TE_zangyou WHERE [syain_No] = @syain_No", cnn)      
The table where I would want to insert data is empty, but I get this error. What seems to be the problem?
Thanks.
Audrey

View 8 Replies View Related

Insert Command

Jan 28, 2007

i want to include an insert command to enable admin user to insert new record through the grid view but for some reason the insert command doesnt work, and i want the page to just display the record of the restaurant name "Sakura Yeshi" but i cannot do that and i dont know why? Can somebody help me out with this? i know this might be easy but just i dont know how to deal with it. Thanks
My Code:<script runat="server">
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)        Dim resmen As String        Dim connection As SqlConnection = New SqlConnection()        connection.ConnectionString = ConfigurationManager.ConnectionStrings("ConnectionString").ToString()
        resmen = ("SELECT resname,menu,price,date FROM rest_info WHERE resname = 'sakura yeshi'")        Dim myCommand As SqlCommand = New SqlCommand(resmen, connection)
        connection.Open()        Dim dr As SqlDataReader = myCommand.ExecuteReader()               While dr.Read()            admingrid.DataBind()                End While        connection.Close()    End Sub</script>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">    <strong>Sakura Yeshi Admin Page<br />    <asp:GridView ID="admingrid" runat="server" AutoGenerateColumns="False" CaptionAlign="Left" DataSourceID="SqlDataSource1" Style="z-index: 100; left: 163px; position: absolute; top: 182px">         <Columns>               <asp:CommandField ShowdeleteButton="True" ShowEditButton ="True" ShowinsertButton="True" />                <asp:BoundField DataField="resname" HeaderText="resname" ReadOnly="True" SortExpression="resname" />                <asp:BoundField DataField="menu" HeaderText="menu" SortExpression="menu" />                <asp:BoundField DataField="price" HeaderText="price" SortExpression="price" />                <asp:BoundField DataField="date" HeaderText="date" SortExpression="date" />            </Columns>
        </asp:GridView>        <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>"            SelectCommand="SELECT [resname], [menu], [price], [date] FROM [rest_info]"            DeleteCommand="DELETE FROM [rest_info] WHERE [resname] = 'sakura yeshi'"             InsertCommand="INSERT INTO [rest_info] ([resname], [menu], [price], [date]) VALUES (@resname, @menu, @date, @price)"            UpdateCommand="UPDATE [rest_info] SET [resname] = @resname, [menu] = @menu, [price] = @price, [date] = @date WHERE [resname] = 'sakura yeshi'">
<InsertParameters>                <asp:Parameter Name="resname" Type="Char" />                <asp:Parameter Name="menu" Type="char" />                <asp:Parameter Name="price" Type="Decimal" />                <asp:Parameter Name="date" Type="datetime" />            </InsertParameters>            <UpdateParameters>                <asp:Parameter Name="resname" Type="Char" />                <asp:Parameter Name="menu" Type="char" />                <asp:Parameter Name="price" Type="Decimal" />                <asp:Parameter Name="date" Type="datetime" />            </UpdateParameters>            <DeleteParameters>                <asp:Parameter Name="resname" Type="String" />            </DeleteParameters></asp:SqlDataSource></asp:Content>

View 8 Replies View Related

Insert By Command.

Jul 18, 2007

Hi,
I am creating a page which has 5 text boxes.
Firstname, lastname, pass, zip, email
and a command button. now when i click this button i want it to use a stored procedure and insert the values from the text box to db table. i dont know what code to put in the command button.

View 3 Replies View Related

Insert Command

Nov 11, 2005

I have three tables t1, t2, t3. I want to insert a new row in t1. I am using access 2000 with sql commands for the queries. There are 4 colums in t1. I know the values of two of the colums. The remaining two columns values are going to be look up in the other 2 tables, 1 value from t2 table and the other value from t3.. I need this to be in one statement. From what I have seen you can either use insert with values() or you can populate your table with unkown values from another table. But I want to do both, since 2 of my values are known and the other 2 need to come from another table.

I hope that I made it clear enough. Can anyone help me

Thanks

View 4 Replies View Related

Sql Insert Command Help

May 16, 2007

i am completely new to sql commands so i really need the help on this one.



I have three tables and they go like this



--User Table

firstTable->integerID

firstTable->stringName



--Group Table

secondTable->integerID

secondTable->stringName



--User to Groups table

thirdTable->integerFirstID

thirdTable->integerSecondID

thirdTable->stringDescription



the first table is has a user id and name and the second table has a group id and name, the third table keeps track of how many groups the user is assigned to. The problem i am having is writing a sql insert into command to add more entries to the third table from an asp.net 2.0 page, my sql command is incorrect.



The problem i am having i think, is that i am populating a dropdownlist with the names of all of the groups and when i select one that should be the group i am assigning to the user, the problem is, is that i dont know how to associated that dropdownlist string's name with its ID so that it can be passed to my insert command. is there a way to accomplish this all as a sql command? because i have a formview with a multiview and then a gridview under nested under all of that, and it would be a pain to write a event to work with all of the that.



if i do this it works

INSERT INTO ThirdTable (UserID,GroupID,Description) VALUES '318', '2', 'some description')



View 3 Replies View Related

Inserting Values And Get The Last ID Recorded To Use In Another INSERT

Sep 20, 2007

I need to insert some values into a table and after that catch the ID inserted.
I set some input parameters in stored procedure and only one to get the @id defined as output
SqlParameter paramIdPedido = new SqlParameter("@APP_IDPEDIDO", SqlDbType.Int, 4);paramIdPedido.Direction = ParameterDirection.Output;cmd.Parameters.Add(paramIdPedido);
Do I have to run cmd.ExecuteNonQuery(); to record first what I need and afterrun ExecuteReader: something like SqlDataReader dr = cmd.ExecuteReader();while (dr.Read()... to get the ID)
From stored procedure:
INSERT table(fields) VALUES(vars)SELECT TOP 1 @id = id FROM table ORDER BY id DESC
I must do all these steps or maybe is there anything less complex to do?
Thanks!
 
 
 

View 1 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved