INSERT From Different Tables And Values

Oct 18, 2006

Hello

for MS SQL 2000

I am having MyTable with 7 columns : A,B,C,D,E,F,G

i want to

INSERT INTO myTable
SELECT A,B,C,D FROM FirstTable WHERE FirstTable.ID > 100

and the columns E,F,G :
E = 1
F = SELECT Max(ID) AS F FROM SecondTable
G = 0

how can i do it ?
i would like to create a stored procedure

thank you

View 2 Replies


ADVERTISEMENT

Insert With Max Values From Multiple Tables

Dec 20, 2007

I am trying to add records to 2 separate tables and each table has a unique ID from the other table. I need to find the highest number ID from both tables (and add 1) and add a record with both new values to both tables.

I have tried the following, but it is not working. Any help would be appreciated, Thanks (my tables are MEMOS and PDSMSGC)


INSERT INTO MEMOS (MemoID, ParentID, FieldName, MemoText)
SELECT MAX(MemoID) + 1 FROM "MEMOS", MAX(MessageID) +1 FROM "PDSMSGC", 'pmc:MemoID', 'Hi my name is bob'
INSERT INTO PDSMSGC (MessageID, MemoID) SELECT MAX(MessageID) + 1 FROM "PDSMSGC", MAX(MemoID) FROM "MEMOS"

View 5 Replies View Related

Insert Values To Two Tables (Buy And Product) Simu

Jun 25, 2007

Hello!

I wonder if anybody can help me with the following problem.

I want to insert values to two tables (Buy and Product) simultainasly ie i want the foreign key in Product to have the same value the primary key have in Buy.

Regards KE





KE

View 8 Replies View Related

Stored Procedure To Split Values And Insert Into Tables

Oct 19, 2012

I have an empty employee table and employee_details table. The temp table which i created say it has 10 columns of which 6 are from employees and 4 from employee_details. I have loaded some data into temp table say 10 rows.

Now the stored procedure using cursor should be created such that, it should fetch the rows one by one from temp table and insert the values into employee table(6 columns) and the rest in employee_details table(4 columns).
This is the scenario.

Here is the column names of my temp table

CREATE TABLE [dbo].[temp](
[employee_id] [char](7) NOT NULL,
[first_name] [char](50) NOT NULL,
[middle_name] [char](50) NOT NULL,
[last_name] [char](50) NOT NULL,
[title] [char](5) NOT NULL,

[Code] ....

Here the last 4 columns belong to the employee_details table. The stored procedure should fetch record by record from temp split and insert into employee and employee_details table.

View 1 Replies View Related

Insert Multiple Rows To Table Based On Values From Other 2 Tables.

Nov 21, 2007

I have a form to assign JOB SITES to previously created PROJECT.  The  JOB SITES appear in the DataList as it varies based on customer. It can be 3 to 50 JOB SITES per PROJECT.
I have "PROJECT" table with all necessary fields for project information and "JOBSITES" table for job sites. I also created a new table called "PROJECTSITES"  which has only 2 columns:  "ProjectId" and "SiteId".
What I am trying to do is to insert multiple rows into that "PROJECTSITES" table based on which checkbox was checked.  The checkbox is located next to each site and I want to be able to select only the ones I need. Btw the Datalist is located inside of a formview and has it's own datasource which already distincts which JOBSITES to display.
Sample:
ProjectId    -    SiteId
1   -   5
1    -   9
1    -   16
1    -   18
1    -   20
1    -   27
1    -   31
ProjectId stays the same, only values for SiteId are being different.
I hope I explaining it right. Do I have to use some sort of loop to go through the automatically populated DataList records and how do I make a multiple inserts to database table? We use SQL Server 2005 and VB for code behind. Please ask if I missed on some information. Thank you in advance.

View 10 Replies View Related

Comparing Values In Two Tables In Order To Do Insert -- Comparision Is Not Working!!

Jul 23, 2005

I have the following insert statement in place:Insert WPHPayments(constituentID, constituentName, campaignYear, fundID, fundDescription, dateAndTimeEntered, amount)Select gt.constituentID, gt.constituentName, gt.campaignYear, gt.fundID, gt.fundDescription, gt.dateAndTimeEntered, gt.amountFrom GTPROCENTERFUNDPAYMENTEXTRACT gt, WPHExtractWhere gt.constituentID = WPHExtract.wph_constIDI want to insert all of the values that are in the GTPROCENTERFUNDPAYMENTEXTRACT table that have the same constituentID that as the records in the WPHExtract table.  Am I just missing something becasue the syntax is showing that everytihing is correct however there is nothing comming back in the result set.  Thanks in advance everyone.  Regards,RB

View 1 Replies View Related

T-SQL (SS2K8) :: Stored Procedure To Truncate And Insert Values In Table 1 And Update And Insert Values In Table 2

Apr 30, 2015

table2 is intially populated (basically this will serve as historical table for view); temptable and table2 will are similar except that table2 has two extra columns which are insertdt and updatedt

process:
1. get data from an existing view and insert in temptable
2. truncate/delete contents of table1
3. insert data in table1 by comparing temptable vs table2 (values that exists in temptable but not in table2 will be inserted)
4. insert data in table2 which are not yet present (comparing ID in t2 and temptable)
5. UPDATE table2 whose field/column VALUE is not equal with temptable. (meaning UNMATCHED VALUE)

* for #5 if a value from table2 (historical table) has changed compared to temptable (new result of view) this must be updated as well as the updateddt field value.

View 2 Replies View Related

OPENROWSET (INSERT) Insert Error: Column Name Or Number Of Supplied Values Does Not Match Table Definition.

Mar 24, 2008

Is there a way to avoid entering column names in the excel template for me to create an excel file froma  dynamic excel using openrowset.
I have teh following code but it works fien when column names are given ahead of time.
If I remove the column names from the template and just to Select * from the table and Select * from sheet1 then it tells me that column names donot match.
 Server: Msg 213, Level 16, State 5, Line 1Insert Error: Column name or number of supplied values does not match table definition.
here is my code...
SET @sql1='select * from table1'SET @sql2='select * from table2'  
IF @File_Name = ''      Select @fn = 'C:Test1.xls'     ELSE      Select @fn = 'C:' + @File_Name + '.xls'        -- FileCopy command string formation     SELECT @Cmd = 'Copy C:TestTemplate1.xls ' + @fn     
-- FielCopy command execution through Shell Command     EXEC MASTER..XP_CMDSHELL @cmd, NO_OUTPUT        -- Mentioning the OLEDB Rpovider and excel destination filename     set @provider = 'Microsoft.Jet.OLEDB.4.0'     set @ExcelString = 'Excel 8.0;HDR=yes;Database=' + @fn   
exec('insert into OPENrowset(''' + @provider + ''',''' + @ExcelString + ''',''SELECT *     FROM [Sheet1$]'')      '+ @sql1 + '')         exec('insert into OPENrowset(''' + @provider + ''',''' + @ExcelString + ''',''SELECT *     FROM [Sheet2$]'')      '+ @sql2 + ' ')   
 
 

View 4 Replies View Related

How Can I Insert Date Values From Char Values

Jan 4, 1999

My process return a date in char format like "3/12/1998",
How could I put this data ( in char ) directly to date ISQ Server field ?

Thank's

View 1 Replies View Related

'Insert Into' For Multiple Values Given A Table Into Which The Values Need To Go

Sep 1, 2007

Please be easy on me...I haven't touched SQL for a year. Why given;



Code Snippet
USE [Patients]
GO
/****** Object: Table [dbo].[Patients] Script Date: 08/31/2007 22:09:29 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Patients](
[PID] [int] IDENTITY(1,1) NOT NULL,
[ID] [varchar](50) NULL,
[FirstName] [nvarchar](50) NULL,
[LastName] [nvarchar](50) NULL,
[DOB] [datetime] NULL,
CONSTRAINT [PK_Patients] PRIMARY KEY CLUSTERED
(
[PID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF


do I get

Msg 102, Level 15, State 1, Line 3

Incorrect syntax near ','.
for the following;




Code Snippet
INSERT INTO Patients
(ID, FirstName,LastName,DOB) VALUES
( '1234-12', 'Joe','Smith','3/1/1960'),
( '5432-30','Bob','Jones','3/1/1960');


Thank you,
hazz

View 3 Replies View Related

How To Insert Values Without Duplicate Values?

Apr 8, 2008

Hi,
 
I want to insert data into table without duplicate values ..
 
how to do?

View 5 Replies View Related

Cannot INSERT Data To 3 Tables Linked With Relationship (INSERT Statement Conflicted With The FOREIGN KEY Constraint Error)

Apr 9, 2007

Hello
 I have a problem with setting relations properly when inserting data using adonet. Already have searched for a solutions, still not finding a mistake...
Here's the sql management studio diagram :

 and here goes the  code1 DataSet ds = new DataSet();
2
3 SqlDataAdapter myCommand1 = new SqlDataAdapter("select * from SurveyTemplate", myConnection);
4 SqlCommandBuilder cb = new SqlCommandBuilder(myCommand1);
5 myCommand1.FillSchema(ds, SchemaType.Source);
6 DataTable pTable = ds.Tables["Table"];
7 pTable.TableName = "SurveyTemplate";
8 myCommand1.InsertCommand = cb.GetInsertCommand();
9 myCommand1.InsertCommand.Connection = myConnection;
10
11 SqlDataAdapter myCommand2 = new SqlDataAdapter("select * from Question", myConnection);
12 cb = new SqlCommandBuilder(myCommand2);
13 myCommand2.FillSchema(ds, SchemaType.Source);
14 pTable = ds.Tables["Table"];
15 pTable.TableName = "Question";
16 myCommand2.InsertCommand = cb.GetInsertCommand();
17 myCommand2.InsertCommand.Connection = myConnection;
18
19 SqlDataAdapter myCommand3 = new SqlDataAdapter("select * from Possible_Answer", myConnection);
20 cb = new SqlCommandBuilder(myCommand3);
21 myCommand3.FillSchema(ds, SchemaType.Source);
22 pTable = ds.Tables["Table"];
23 pTable.TableName = "Possible_Answer";
24 myCommand3.InsertCommand = cb.GetInsertCommand();
25 myCommand3.InsertCommand.Connection = myConnection;
26
27 ds.Relations.Add(new DataRelation("FK_Question_SurveyTemplate", ds.Tables["SurveyTemplate"].Columns["id"], ds.Tables["Question"].Columns["surveyTemplateID"]));
28 ds.Relations.Add(new DataRelation("FK_Possible_Answer_Question", ds.Tables["Question"].Columns["id"], ds.Tables["Possible_Answer"].Columns["questionID"]));
29
30 DataRow dr = ds.Tables["SurveyTemplate"].NewRow();
31 dr["name"] = o[0];
32 dr["description"] = o[1];
33 dr["active"] = 1;
34 ds.Tables["SurveyTemplate"].Rows.Add(dr);
35
36 DataRow dr1 = ds.Tables["Question"].NewRow();
37 dr1["questionIndex"] = 1;
38 dr1["questionContent"] = "q1";
39 dr1.SetParentRow(dr);
40 ds.Tables["Question"].Rows.Add(dr1);
41
42 DataRow dr2 = ds.Tables["Possible_Answer"].NewRow();
43 dr2["answerIndex"] = 1;
44 dr2["answerContent"] = "a11";
45 dr2.SetParentRow(dr1);
46 ds.Tables["Possible_Answer"].Rows.Add(dr2);
47
48 dr1 = ds.Tables["Question"].NewRow();
49 dr1["questionIndex"] = 2;
50 dr1["questionContent"] = "q2";
51 dr1.SetParentRow(dr);
52 ds.Tables["Question"].Rows.Add(dr1);
53
54 dr2 = ds.Tables["Possible_Answer"].NewRow();
55 dr2["answerIndex"] = 1;
56 dr2["answerContent"] = "a21";
57 dr2.SetParentRow(dr1);
58 ds.Tables["Possible_Answer"].Rows.Add(dr2);
59
60 dr2 = ds.Tables["Possible_Answer"].NewRow();
61 dr2["answerIndex"] = 2;
62 dr2["answerContent"] = "a22";
63 dr2.SetParentRow(dr1);
64 ds.Tables["Possible_Answer"].Rows.Add(dr2);
65
66 myCommand1.Update(ds,"SurveyTemplate");
67 myCommand2.Update(ds, "Question");
68 myCommand3.Update(ds, "Possible_Answer");
69 ds.AcceptChanges();
70

and that causes (at line 67):"The INSERT statement conflicted with the FOREIGN KEY constraint
"FK_Question_SurveyTemplate". The conflict occurred in database
"ankietyzacja", table "dbo.SurveyTemplate", column
'id'.
The statement has been terminated.
at System.Data.Common.DbDataAdapter.UpdatedRowStatusErrors(RowUpdatedEventArgs rowUpdatedEvent, BatchCommandInfo[] batchCommands, Int32 commandCount)
at System.Data.Common.DbDataAdapter.UpdatedRowStatus(RowUpdatedEventArgs rowUpdatedEvent, BatchCommandInfo[] batchCommands, Int32 commandCount)
at System.Data.Common.DbDataAdapter.Update(DataRow[] dataRows, DataTableMapping tableMapping)
at System.Data.Common.DbDataAdapter.UpdateFromDataTable(DataTable dataTable, DataTableMapping tableMapping)
at System.Data.Common.DbDataAdapter.Update(DataSet dataSet, String srcTable)
at AnkietyzacjaWebService.Service1.createSurveyTemplate(Object[] o) in J:\PL\PAI\AnkietyzacjaWebService\AnkietyzacjaWebServicece\Service1.asmx.cs:line 397"


Could You please tell me what am I missing here ?
Thanks a lot.
 

View 5 Replies View Related

Insert Records From Foxpro Tables To SQL Server Tables

Apr 22, 2004

Hi,

Currently, I'm using the following steps to migrate millions of records from Foxpro tables to SQL Server tables:

1. Transfer Foxpro records to .dat files and then bcp to SQL Server tables in a dummy database. All the SQL tables have the same columns as the Foxpro tables.
2. Manipulate the data in the SQL tables of the dummy database and save the manipulated data into the SQL tables of the real database where the tables may have different structure from the corresponding Foxpro tables.

I only know the following ways to import Foxpro data into SQL Server:

#1. Transfer Foxpro records to .dat files and then bcp to SQL Server tables
#2. Transfer Foxpro records to .dat files and then Bulk Insert to SQL Server tables
#3. DTS Foxpro records directly to SQL Server tables

I'm thinking whether the following choices will be better than the current way:

1st choice: Change step 1 to use #2 instead of #1
2nd choice: Change step 1 to use #3 instead of #1
3rd choice: Use #3 plus manipulating in DTS to replace step 1 and step 2

Thank you for any suggestion.

View 2 Replies View Related

Variable Insert To SQL Server Insert Satement Setting Values For The @variable INSIDE Sql

Apr 29, 2007

ok, I am on Day 2 of being brain dead.I have a database with a table with 2 varchar(25) columns I have a btton click event that gets the value of the userName,  and a text box.I NEED to insert a new row in a sql database, with the 2 variables.Ive used a sqldatasource object, and tried to midify the insert parameters, tried to set it at the button click event, and NOTHING is working. Anyone have a good source for sql 101/ASP.Net/Braindead where I can find this out, or better yet, give me an example.  this is what I got <%@ Page Language="C#" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><script runat="server">     protected void runit_Click(object sender, EventArgs e)    {       //SqlDataSource ID = "InsertExtraInfo".Insert();      //SqlDataSource1.Insert();    }      protected void Button1_Click1(object sender, EventArgs e)    {        SqlDataSource newsql;                newsql.InsertParameters.Add("@name", "Dan");        newsql.InsertParameters.Add("@color", "rose");        String t_c = "purple";        string tempname = Page.User.Identity.Name;        Label1.Text = tempname;        Label2.Text = t_c;        newsql.Insert();    }</script><html xmlns="http://www.w3.org/1999/xhtml" ><head runat="server">    <title>mini update</title></head><body>    <form id="form1" runat="server">        &nbsp;name<asp:TextBox ID="name" runat="server" OnTextChanged="TextBox2_TextChanged"></asp:TextBox><br />        color        <asp:TextBox ID="color" runat="server"></asp:TextBox><br />        <br />        <asp:Button ID="Button1" runat="server" OnClick="Button1_Click1" Text="Button" />        &nbsp;<br />        set lable =&gt;<asp:Label ID="Label1" runat="server" Text="Label" Width="135px" Visible="False"></asp:Label><br />        Lable 2 =&gt;        <asp:Label ID="Label2" runat="server" Text="Label"></asp:Label><br />        Usernmae=&gt;<asp:LoginName ID="LoginName1" runat="server" />        <br />        <br />        <br />        <br />        <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConflictDetection="CompareAllValues"            ConnectionString="<%$ ConnectionStrings:newstring %>" DeleteCommand="DELETE FROM [favcolor] WHERE [name] = @original_name AND [color] = @original_color"            InsertCommand="INSERT INTO [favcolor] ([name], [color]) VALUES (@name, @color)"            OldValuesParameterFormatString="original_{0}" SelectCommand="SELECT [name], [color] FROM [favcolor]"            UpdateCommand="UPDATE [favcolor] SET [color] = @color WHERE [name] = @original_name AND [color] = @original_color">            <DeleteParameters>                <asp:Parameter Name="original_name" Type="String" />                <asp:Parameter Name="original_color" Type="String" />            </DeleteParameters>            <UpdateParameters>                <asp:Parameter Name="color" Type="String" />                <asp:Parameter Name="original_name" Type="String" />                <asp:Parameter Name="original_color" Type="String" />            </UpdateParameters>            <InsertParameters>        <asp:InsertParameter("@name", "Dan", Type="String" />        <asp:InsertParameter("@color", "rose") Type="String"/>                                       </InsertParameters>        </asp:SqlDataSource>        &nbsp;        <asp:GridView ID="GridView1" runat="server" AllowPaging="True" AllowSorting="True"            AutoGenerateColumns="False" DataKeyNames="name" DataSourceID="SqlDataSource1">            <Columns>                <asp:CommandField ShowDeleteButton="True" ShowEditButton="True" ShowSelectButton="True" />                                <asp:BoundField DataField="color" HeaderText="color" SortExpression="color" />                <asp:BoundField DataField="name" HeaderText="name" ReadOnly="True" SortExpression="name" />            </Columns>        </asp:GridView>           </form></body></html>  

View 1 Replies View Related

How Do You Insert Into Two Tables From One Insert? Or Even How Would You Using Two Inserts?

Mar 18, 2007

I currently insert into one table with:                 SqlCommand comm = new SqlCommand("INSERT INTO UsersTable (UserName, Password, Email) VALUES (@person, @pass, @email)", sqlConnection);                comm.Parameters.AddWithValue("@person", usrnmeLbl.Text);                comm.Parameters.AddWithValue("@pass", hiddenpassLbl.Text);                comm.Parameters.AddWithValue("@email", hemailLbl.Text);but I realized that there's another table related to this table and I need to have something go in it so that the users data will be recorded at the same pace. So I tried:                 SqlCommand comm = new SqlCommand("INSERT INTO UsersTable, FatherHistTable (UserName, Password, Email), (Father) VALUES (@person, @pass, @email), (@father)", sqlConnection);                comm.Parameters.AddWithValue("@person", usrnmeLbl.Text);                comm.Parameters.AddWithValue("@pass", hiddenpassLbl.Text);                comm.Parameters.AddWithValue("@email", hemailLbl.Text);                comm.Parameters.AddWithValue("@father", fthrsNmeLbl.Text);Not working, so I am thinking I must do two inserts:                  SqlCommand comm = new SqlCommand("INSERT INTO
UsersTable (UserName, Password, Email) VALUES (@person, @pass,
@email)", sqlConnection);
                comm.Parameters.AddWithValue("@person", usrnmeLbl.Text);
                comm.Parameters.AddWithValue("@pass", hiddenpassLbl.Text);
                comm.Parameters.AddWithValue("@email", hemailLbl.Text);                 SqlCommand comm2 = new SqlCommand("INSERT INTO
FatherHistTable (Father) VALUES (@father)", sqlConnection);
                comm2.Parameters.AddWithValue("@father", fthrsNmeLbl.Text); Is that the only way to go about it then? Thanks in advance for any explanations. 

View 26 Replies View Related

Getting Values From Other Tables

Sep 22, 2004

Howdy all. I've tried to figure this out on my own, but alas!, I keep hitting a brick wall.
I'm making a game score "keep-tracker" (very technical jargon, I know...) and so I've set up 3 tables:

Table 1: Players
Columns: PlayerID, PlayerName, Paid

Table 2: Contestants
Columns: ContestantID, ContestantName, Eliminated

Table 3: Picks
Columns: PlayerID, Pick1, Pick2, Pick3, etc...

For Players and Contestants tables, the IDs are int, the names are nvarhars, and Paid/Eliminated is boolean (bit).

Now, I'm trying to display in a datagrid using ASP.NET 1.1, the PlayerName along with the Picks that they have chosen.

I've created a stored proc as follows:

CREATE PROCEDURE GetPicks AS
SELECT
Players.PlayerName,
Picks.Pick1,
Picks.Pick2,
Picks.Pick3,
Picks.Pick4
FROM
Picks, Players, Contestants
WHERE
Picks.PlayerID = Players.PlayerID AND Picks.Pick1 = Contestants.ContestantID
ORDER BY
PlayerName
GO



The result I'm getting is:

PlayerName Pick1 Pick2 Pick3 Pick4
Bob 1 3 5 12
Charlie 1 3 16 17
Wilma 4 7 9 14


The PlayerName appears, rather than PlayerID, which is good to see, but my question is: how can I get the ContestantName to appear as Pick1, Pick2, etc., instead of the integer?

I've tinkered around with JOINs, but I'm a beginner and I'm finding JOINs a bit confusing...
Help would be appreciated! Thanks for your help in advance...

JP

View 3 Replies View Related

Values In Tables

Feb 22, 2001

In the web pages like everbody I'm adding values like "all selections" or "no selection" for select boxes manually. After this manual addition I add the database results within a loop like States.

Is it OK to add manual selection entires to database with a ID value of 0 like below;
StateID State
------- -----
0 Not Selected
1 NY
....

and then using in web page without any manual entries. Also is this kind of entry can be better for indexing and Foreign Key usages.

Thanks in advance.

View 2 Replies View Related

&&<&&> Values From Two Tables

Mar 27, 2008

I have two tables, A & B I need to compare 4 columns in table B with one column in table A. The data returned should only be the values which are not equal values in a column in table A

For example:
row 1 of columns 1, 2, 3, 4 in table B have values 1001, 1001, 1002, 1003
row 2 of columns 1, 2, 3, 4 in table B have values 1001, 1008, 1009, 1007
Table A has a column 1 which has many rows which may contain the values 1001, 1002 etc... but does not have the value 1008. It would then return row 2 as the value in column 2 of table B does not exist in table A column 1.

Any help would be much appreciated

View 7 Replies View Related

Insert Multiple Row Values

Oct 25, 2007

hi everyone
how do i insert multiple rows in a database ?
i came up with something like this after googling but it does not work
INSERT INTO tblSold (LID, BuyerID,Date)select ('759','2106','2441') UNION ALLselect ('0','0','0') UNION ALLselect ('10/25/2007','10/25/2007','10/25/2007')

View 8 Replies View Related

Insert Values From 2 Different Sources

Jan 12, 2008

Hi,I have a button that that executes insertion of data into a database. For the data it inserts into one column, the data is located in another database table.As well as this being inserted, I would like more data to be inserted in the same column, which comes from textboxes which are located on the same page as the button that executes the insertion..For example: someone types in information into textboxes, then presses the button. The code behind then inserts the data from the textboxes plus the data from the other table (for which the coding is already done).Here is my current code:     public bool [snip](int ProductId)    {[snip]        command.CommandText = "INSERT INTO Messages (sendername,recievername,message,senddate,subject) VALUES (@sendername,@recievername,@message,@date,@subject)";        command.Parameters.AddWithValue("@sendername", System.Web.HttpContext.Current.User.Identity.Name);        DataView dv = SqlDataSource2.Select(DataSourceSelectArguments.Empty) as DataView;        string receivername = " " + dv[0]["Usersname"].ToString() + " ";        command.Parameters.AddWithValue("@recievername", receivername);        DataView dv2 = SqlDataSource3.Select(DataSourceSelectArguments.Empty) as DataView;        string message = dv2[0]["paymentinstructions"].ToString();        command.Parameters.AddWithValue("@message", message);        command.Parameters.AddWithValue("@subject", TextBox1.Text);        command.Parameters.AddWithValue("@date", DateTime.Now);        command.ExecuteNonQuery();        con.Close();        command.Dispose();        return true;    }  So along with "paymentinstructions" being inserted into 'message', I would also like the values from TextBox4, TextBox5 and TextBox6 to be inserted... It would also be good if text could be inserted infront of the values of these textboxes - e.g.    Price: "TextBox4's value"Does anyone have any ideas? Reply if it needs further explanation.Thanks,Jon 

View 14 Replies View Related

Select Some Values From A Row And Insert On Another Row

Feb 12, 2008

I have a table wih multiple records and some has common values.
For example, new child row need to inherit some of parent's data.
Here is how I want to do:
Select [parent data1], [parent data2] from [TABEL] where id = parent
Insert INTO [TABLE]  ([child id], [child data1], [child data2] ) VALUES [child  id] [parent id] [parent id]...........
I was thinking about using Selected and Inserting events but not sure how.
Please help?
 Thanks,

View 1 Replies View Related

How To Insert One Of Two Values Into Column?

May 9, 2008

I have a form with a few panels on it, and the visibility of the panels is determined by a radiobutton selection.  Once a user selects a radio button item, the appropriate panels visibility changes to true.  On two of the panels, there is a drop down list with a list of clients, and the dropdownlists are named Client1 and Client2 (Client 1 is included in panel 1 and client 2 is in panel 2)
How do I insert the values for client1 or client2 (depending upon which is visible) into the same sql column via a stored procedure?   The database field is called client.  How do I get the value from my vb.net form into the stored procedure? 

View 2 Replies View Related

Insert Values Error

Oct 19, 2004

Hey Guys:

I am trying to create a form, and then insert the values entered by a user into a sql database, I have enclosed the page code below. Everything works except the data is not being inserted into the database, and i keep getting the default message in my error message section. I took this right from the quick start tutorial and started working with it, and keep getting an error.

I believe the error is located in the INSERT statement


<%@ Page Language="vb" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>


<html>

<script language="VB" runat="server">

Dim MyConnection As SqlConnection

Sub Page_Load(Sender As Object, E As EventArgs)

MyConnection = New SqlConnection("server=localhost;database=planetauction;uid=planetauction;pwd=bean13")

If Not (IsPostBack)
BindGrid()
Page.DataBind()
End If
End Sub

Sub AddAuthor_Click(Sender As Object, E As EventArgs)
Page.Validate()
If Not Page.IsValid
Return
End If

Dim DS As DataSet
Dim MyCommand As SqlCommand

If txtLastName.Value = ""
Message.InnerHtml = "ERROR: Null values not allowed for Author ID, " & _
"Name or Phone"
Message.Style("color") = "red"
BindGrid()
Return
End If

Dim InsertCmd As String = "insert into users (txtLastName) values (@lastname)"

MyCommand = New SqlCommand(InsertCmd, MyConnection)

MyCommand.Parameters.Add(New SqlParameter("@lastname", SqlDbType.NVarChar, 50))
MyCommand.Parameters("@lastname").Value = txtLastName.Value

MyCommand.Connection.Open()

Try
MyCommand.ExecuteNonQuery()
Message.InnerHtml = "Record Added<br>" & InsertCmd.ToString()

Catch Exp As SQLException
If Exp.Number = 2627
Message.InnerHtml = "ERROR: A record already exists with the " & _
"same primary key"
Else
Message.InnerHtml = "ERROR: Could not add record, please ensure " & _
"the fields are correctly filled out"
End If
Message.Style("color") = "red"

End Try

MyCommand.Connection.Close()

BindGrid()
End Sub

Sub BindGrid()

Dim MyCommand As SqlDataAdapter = new SqlDataAdapter( _
"select * from users", MyConnection)

Dim DS As DataSet = new DataSet()
MyCommand.Fill(DS, "Users")

MyDataGrid.DataSource=DS.Tables("Users").DefaultView
MyDataGrid.DataBind()
End Sub

</script>

<body style="font: 10pt verdana">

<form runat="server" ID="Form1">

<h3><font face="Verdana">Inserting a Row of Data</font></h3>

<table width="95%">
<tr>
<td valign="top">

<ASP:DataGrid id="MyDataGrid" runat="server"
Width="700"
BackColor="#ccccff"
BorderColor="black"
ShowFooter="false"
CellPadding=3
CellSpacing="0"
Font-Name="Verdana"
Font-Size="8pt"
HeaderStyle-BackColor="#aaaadd"
EnableViewState="false"
/>

</td>
<td valign="top">

<table style="font: 8pt verdana">
<tr>
<td colspan="2" bgcolor="#aaaadd" style="font:10pt verdana">Add a New Author:</td>
</tr>
<tr>
<td nowrap>Last Name: </td>
<td>
<input type="text" id="txtLastName" runat="server" NAME="txtLastName"><br>

</td>
</tr>
<tr>
<td></td>
<td style="padding-top:15">
<input type="submit" OnServerClick="AddAuthor_Click" value="Add Author" runat="server" ID="Submit1" NAME="Submit1">
</td>
</tr>
<tr>
<td colspan="2" style="padding-top:15" align="center">
<span id="Message" EnableViewState="false" style="font: arial 11pt;" runat="server"/>
</td>
</tr>
</table>

</td>
</tr>
</table>

</form>

</body>
</html>

View 3 Replies View Related

Insert Null Values

Jan 28, 2005

Hi all

Iam having some problems with null values

try
{
cmd.Parameters["@fmv"].Value = Convert.ToDecimal(TextBox13.Text);
}
catch
{
cmd.Parameters["@fmv"].Value =System.Data.SqlTypes.SqlDecimal.Null;
}

for Empty Textbox values
i am getting the following error,

System.Data.SqlTypes.SqlNullValueException: Data is Null. This method or property cannot be called on Null values.

My Database is allowed to accept null values.

System.Data.SqlType.SqlDatetime.Null works but SqlDecimal.Null does not work.

Could any one help me with this?

Thanks

Raj

View 2 Replies View Related

How To Insert The Values In A COLUMN?

Jul 10, 2001

I have two tables.

S

SNO CHAR(5)
SNAME CHAR(20)


S1
SNo CHAR(5)
SNAME CHAR(20)


The structure is same but S(SNAME) does not contain data. If I use the following command of SQL then It appends the rows in table. I want that the values should be inserted from TOP to BOTTOM.

INSERT INTO S (SNAME)
Select sname from s1

Could anybody solve this probelm?

Thanks

View 2 Replies View Related

Insert Triggers And Max Values

Nov 20, 2000

I have a situation where I need to create an insert trigger on table a which will create a corresponding record in table b. However before I insert the record i must obtain the max value for the record in table b and increment it by one. I have all this working. My question is if I just put a begin and commit with this statement is there a chance that when 2 users insert at the same time the max value may be incorrect say for instance

CREATE TRIGGER tr_cms_prov_ins ON provider
FOR INSERT
as
declare @ndentPrid char(3),
@nxtgenPrid char(7),
@fname varchar(40),
@lname varchar(40)
begin tran
select @ndentPrid = max(provider_id) from providerdnt
if @ndentPrid is null
set @ndentPrid = 1
else set @ndentPrid = @ndentPrid + 1

insert into dental..provider (provider_id, first_name, last_name, collections_go_to)
select @ndentPrid, first_name, last_name','YYYYYYYYYYYYYYYNNNNN' from inserted
commit tran

Will this do it or do I need to enforce some type of locking to handle the max value. There are no inserts into
table b directly only by the trigger insert on table a

View 1 Replies View Related

Insert Multiple Values

Jan 5, 2000

i have about 2,000 record and i need to insert them in my table.
how do i insert these informations using this syntax??
au_id au_name au_fname
1003 vivian latin
1005 cecy mani
1004 bili david

insert into autors (au_id, au_name,au_fname)
Values ('1101', 'Rabit','jesicca')


thanks for your time and help.

View 1 Replies View Related

How To Insert Identity Values

Oct 3, 2005

hi to the group,
i am small problem,
i am having two columns 1 is col1 which is a primary key and col2 any think .now i want to insert the data into second column at that time the first column must get the values in identity (like 1,2,3,4 etc)
with out using identity(sql server)/generated always(db2)
can any one knows please explain it

View 3 Replies View Related

How To Insert Multiple Values

Apr 14, 2014

this is my data

AM1WSJZ1241
AM1WLSU7162
AM1SXBI5100
AM1TWXX0477
AM1MSMQ6167
AM1WRQP1810
AM1HNME1411

i want a query to insert a data in table

View 1 Replies View Related

Insert A Row With Default Values

Aug 12, 2014

I need to insert a record in a table which has about 90 columns.

My first column is a CustCode that would be supplied by parameter all other columns should be set to 0

Is there a quick way of doing this?

View 5 Replies View Related

Insert New Values Every Day To New Table?

Sep 24, 2014

I have a table as dbo.Bewegungen and it will be updated every day with new dates

I inserted once the values of this table to another table with group by. I want to know how should i insert the new values every day to the new table? i don't want to insert the previous values again.

it has 5 columns as primary key and one of them is Date.

View 2 Replies View Related

How To Insert Into Identity Values

Oct 3, 2005

hi to the group,
i am small problem,
i am having two columns 1 is col1 which is a primary key and col2 any think .now i want to insert the data into second column at that time the first column must get the values in identity (like 1,2,3,4 etc)
with out using identity(sql server)/generated always(db2)
can any one knows please explain it
bye

View 1 Replies View Related

INSERT SELECTed Values And Other..

Dec 28, 2005

Hi,

Wondering if anyone can help with this..

I want to INSERT some data already SELECTED in a query and also some other variables.. Will the **dodgy code** make it easier to understand I wonder..

** DODGY CODE **

INSERT INTO tblTableOne(Column1, Column2, Column3, Column4)
VALUES( ( SELECT Column1, Column2 FROM tblTableTwo ), "Text for Column3", "And text for column4")

** END OF DODGY CODE **

I understand it may have something to do with TEMP TABLES perhaps??

Any help greatly appreciated..

KingRoon

Chaotician Man,
Slice the lines of virgin pathways.
Harmony Hero.

View 4 Replies View Related







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