I'm trying to write a Stored Proc to Insert records into a table in SQL Server 2000. The fields in the records to be inserted are from another table and from Parameters. I can't seem to figure out the syntax for this.
I created a test in MS Access and it loooks like this:
INSERT INTO PatientTripRegionCountry_Temp ( CountryID, RegionID, Country, PatientTripID ) SELECT Country.CountryID, Country.RegionID, Country.Country, 2 AS PatientTripID FROM Country
This works great in Access but not in SQL Server. In SQL Server 2 = @PatientTripID
i am trying to insert one column of data from another table and then load the rest of the columns with the data that is in the quotes. i am using ms access to test my script and of course access doesn't like my script. this data has to inputted at the same time due to the required fields in the table. any help will be much appreciative and of course i am on a tight deadline.
INSERT INTO NUMBER_PORTABILITY_AVAIL_ASSOC [ACAT_ID, NPT_TYPE, UPD_CNT, LAST_CHG_OPER, LAST_CHG_DATETIME, ACCESS_LEVEL] VALUES (SELECT ID FROM PTDSP0_AVAILABILITY_CATALOG WHERE CSC_SERVICE_CODE='#Y'), 'LNP', '1', 'CSG&TICKET', SYSDATE, 'NONE';
Hi, I've got a table with trialsubscriptions. When someone orders a trialsubscription he has to fill in a form. With the values in the form I like to fill a database with some extra fields from the trialsubscription table. I get those extra fields with a datareader. But when I insert I can't use the same datareader (its an insert), I can't make two datareaders because I have to close the first one etc. Does someone had the same problem and has some example code (or make some :-)) Some keywords are also possible! Thanks! Roel
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.
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 + ' ')
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
I have a stored procedure that selects the unique Name of an item from one table.
SELECT DISTINCT ChainName from Chains
For each ChainName, there exists 0 or more StoreNames in the Stores. I want to return the result of this select as the second field in each row of the result set.
SELECT DISTINCT StoreName FROM Stores WHERE Stores.ChainName = ChainName
Each row of the result set returned by the stored procedure would contain:
ChainName, Array of StoreNames (or comma separated strings or whatever)
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"> 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" /> <br /> set lable =><asp:Label ID="Label1" runat="server" Text="Label" Width="135px" Visible="False"></asp:Label><br /> Lable 2 => <asp:Label ID="Label2" runat="server" Text="Label"></asp:Label><br /> Usernmae=><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> <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>
Hi,I have a query like this :SELECTx1,x2,( SELECT ... FROM ... WHERE ...UNIONSELECT ... FROM ... WHERE ...) as x3FROM ...WHERE ...The problem is that I don't want to return the results where x3 isNULL.Writing :SELECTx1,x2,( SELECT ... FROM ... WHERE ...UNIONSELECT ... FROM ... WHERE ...) as x3FROM ...WHERE ... AND x3 IS NOT NULLdoesn't work.The only solution I found is to write :SELECT * FROM((SELECTx1,x2,( SELECT ... FROM ... WHERE ...UNIONSELECT ... FROM ... WHERE ...) as x3FROM ...WHERE ...) AS R1)WHERE R1.x3 IS NOT NULLIs there a better solution? Can I use an EXISTS clause somewhere totest if x3 is null without having to have a 3rd SELECT statement?There's probably a very simple solution to do this, but I didn't findit.Thanks
I'm doing a INSERT...SELECT where I'm dependent on the records SELECT:ed to be in a certain order. This order is enforced through a clustered index on that table - I can see that they are in the proper order by doing just the SELECT part.
However, when I do the INSERT, it doesn't work (nothing is inserted) - can the order of the records from the SELECT part be changed internally on their way to the INSERT part, so to speak?
Actually - it is a view that I'm inserting into, and there's an instead-of-insert trigger on it that does the actual insertions into the base table. I've added a "PRINT" statement to the trigger code and there's just ONE record printed (there should be millions).
I want to add the content of a table into anotherI tried to copy all fields, except the primary key:INSERT INTO table2(field2, field3, field4, ...)SELECT field2, field3, field4, ...FROM anotherDB.dbo.table1gives the following error:Violation of UNIQUE KEY constraint...Cannot insert duplicate key...Why?I didn't ask him to copy the key column; Isn't the SQL Server supposedto know how to increment the key ?
Here is the situation i am stuck with, see the example first and below explained the problem:
-- 'SESSION A
create table foo (
id integer,
pid integer,
data varchar(10)
);
begin transaction
insert into foo values ( 1, 1, 'foo' )
insert into foo values ( 2, 1, 'bar' )
insert into foo values ( 3, 1, 'bozo' )
insert into foo values ( 4, 2, 'snafu' )
insert into foo values ( 5, 2, 'rimrom' )
insert into foo values ( 6, 2, 'blark' )
insert into foo values ( 7, 3, 'smeg' )
commit transaction
create index foo_id_idx on foo ( id )
create index foo_pid_idx on foo ( pid )
begin transaction
insert into foo values ( 9, 3, 'blamo' )
-- 'SESSION B
begin transaction
select id, data from foo with ( updlock, rowlock ) where id = 5;
-- Problem:
-- Uncommitted transaction in session A, with insert into table FOO, aquires lock on index foo_pid_idx which BLOCKS select with ( updlock, rowlock ) in session B.
-- Insert should aquire only exclusive rowlock. Why does insert block select with ( updlock, rowlock )?
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')
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
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?
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
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)
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>
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.
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
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')
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
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.
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
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.
create proc dbo.usp_CatchAddressException @tableName varchar(500) as -- alter proc dbo.usp_CatchAddressException @tableName varchar(500) as
begin set nocount on declare @sql varchar(700)
-- truncate table tempException set @sql = 'insert hava_dcde.dbo.STREET_EXCEPTION (id_town, id_voter, pre_value, nbr_exception, date_stamp) select a.id_town, a.id_voter, substring(a.ad_str1, 1, len(a.ad_str1) - charindex('' '', reverse(a.ad_str1))), ''20'', getdate() from HAVA_DCDE.dbo.' + quoteName(@tableName)+ ' a where substring(a.ad_str1, 1, len(a.ad_str1) - charindex('' '', reverse(a.ad_str1))+1) not in (select nm_street from HAVA_DCDE.dbo.state_streets ss)' -- and a.id_town = + @tableName -- print(@sql)
exec(@sql) set nocount off end ---------------------------------------------------
when i run this SP 2 times, it will insert the values 2 times. what should i do if i don't want to insert the same values 2 times? I'm confussed, Should i use update? any input will be appreciated.