Need Help On How To Do A Simple Insert SQL Script That Is Related??
Mar 28, 2008
I am trying to figure out what SQL script on how can I do this........I want to insert a record in a table by using the text fieds instead of using a primary key to recognize where it relates to. Fro example, I have two tables:
table Make
---------------
Make ID- Interger (PK) 1
description - text Honda
table model
----------------
Model ID - integer (PK) 1
desc.--text Accord
Make ID - interger (FK) 1
I am trying to figure out A way to do something like this......... INSERT into model (Model ID which is an auto #, description, Make ID) VALUES (txtmodelID.text, txtdescripton.text, instead of doing MakeID here; I want to use the descripton from the Make table to insert thiis MakeID field) I badly need some help with this logic or syntax as it relates to most of the way I need to insert through out my site. Thanks in advance.
In other words I want the user to select a Make from a drop down list not a Make ID# such as Honda that will insert under that Make ID number related to that description..... such as a type of car ; Accord's description into the model table.
I have what should be simple question about related tables in a dataset and using those fields in a report. Here is my simple design.
Order Header -> Line Item -> Line Discount -> Discount Table
Now when designing this report I cannot seem to access the related discount records for the line item. (as more than one can be applied) Every time I try to drag an field from one of the tables in the dataset to my report it automatically adds "First()" onto the field value expression. This seems to work fine for the order header, but doen't even come close to getting the right discount on the line item? I basically need to pass through the Line Discount table to get to the discount name field to put on the same line as my line item data on the report.
I have looked and googled for for an example on this, but have come up short. Can anyone point me in the right direction?
I have a For Each Loop container, and inside the container, I have a SQL Execute task, which runs first, and then I need to kick off 5 Data Flow Tasks. Do I need to connect the 5 DFTs to each other using the Green(Pipelines). How would you usually do this? Thx.
Hi, I have 3 tables: Employees with the fields:idEmployee and employeeName Roles with the fields:idRole and roleName. An employee can have one or many roles. I created the table EmployeeRoles with the fields: id,idEmployee,idRole. idEmployee and idRole are foreign keys. I want to insert a new employee into Employees table, but I have to insert idEmployee field into EmployeeRoles table.
I have two tables. When my user completes an insert of data in table (1), I would like the second "related" table (2) to be automatically populated with defaults. Is this possible? My logical approach to this is: 1. Build a handler for the OnInsert event of the first table 2. In the handler, call the Insert Command on the SQLDataSource for the second table with the defaults specified in the DataSource. What I'm not sure how to do is Step 2 or whats the best way. How do I call the Insertcommand programmatically for a DataSource? Or, is there a better way such as some kind of traditional hardwired SQL insert statement like in classical ASP? Or is there a way to programmatically call a stored procedure and if so is the 3rd approach the best way?
How exactly would someone do this best? It seems this would be a rather common thing someone might need to do.
I would like to update/insert data into a Orderhearder Table along with the related details into the corrosponding OrderDetails Tables. Can this be done using a single stored procedure or do we have to make one call to the UpdateOrderHeader Stored Procedure and loop thru all the details and call the UpdateOrderDetails Stored Procedure. How do we handle the Transactions in such a case ?
Hi, how do I perform a simple insert command? I dont need the SQL syntax, just how do i do it using VS2005. using SqlDataSource, for some reason, after writing the insert sentence, the "next" button remains gray. i am using VS2005 and sql server.
I am trying to do a simple insert 3 items into 3 colms the table has 4 the 4th is an identity with a seed of 1
I am getting this error that i need an explicit val for the key
TABLE SCRIPT :
GO /****** Object: Table [dbo].[Company] Script Date: 03/30/2006 17:48:22 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO SET ANSI_PADDING ON GO CREATE TABLE [dbo].[Company]( [idCompany] [int] IDENTITY(1,1) NOT NULL, [CompanyName] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL, [Abreviation] [nchar](10) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL, [Sol] [varchar](10) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL, CONSTRAINT [PK_Company] PRIMARY KEY CLUSTERED ( [idCompany] ASC )WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY] ) ON [PRIMARY]
GO SET ANSI_PADDING OFF --SHOULDNT NEED THIS : --SET IDENTITY_INSERT dbo.Company ON
INSERT INTO COMPANY VALUES('AmericanExpressCheck','Amex','ax')
Msg 545, Level 16, State 1, Line 2 Explicit value must be specified for identity column in table 'Company' either when IDENTITY_INSERT is set to ON or when a replication user is inserting into a NOT FOR REPLICATION identity column.
INSERT INTO archivetitles (title_id, title, type, pub_id) SELECT title_id, title, type, pub_id FROM titles WHERE (pub_id = '0766')
How would I modify this if the table archivetitles had columns: titleid, title, newcolumn, type, pub_id and I wanted the newcolumn value to be null, but I still wanted to select the values from titles?
Hello,I just started with ms sql. I need to insert data from some textboxes into ms sql 2000 database.I can't get it work.I'm trying this:"INSERT INTO tblUplate (ID_Uplata, JMB, IDOsnovaUplate, Iznos, Datum) Values('', ' + txtJMBUplate.Text + ', ' + ddVrstaPrihoda.SelectedItem + ', ' + txtIznos.Text + ', ' + DateTimePicker1.Value + ')"Is this wrong? Should I use + or & (like I used to use with MS Access)?Thanks
I have a textbox with the id of txtName it is a name text box. and I have a submit button. How do i get the value of the text in the text box to popluate a new row of data in my Sql Server database.
------------------------------- Events ------------------------------- ID | E_EventName -------------------------------
------------------------------- Photos ------------------------------- ID | P_EventID | P_Filename -------------------------------
Given an event like "2005 cookout", and a file like "bob.jpg", I'd like to insert the event id based on the event name and the filename into Photos. How can I do that?
Ive added a primary key called ID to my table, now my insert stored procedure dont no longer work.
i want an unique identifier for each row.
heres my stored procedure:
CREATE PROCEDURE composeMessage -- Add the parameters for the stored procedure here @username varchar(24), @sender varchar(24), @date dateTime, @subject varchar(255), @message varchar(2500)
AS BEGIN
insert into Messages( "Username", "Sender", "Date", "Subject", "Message" ) values ( @username, @sender, @date, @subject, @message ) END GO
heres my sqlcreate table:
USE [Messenger] GO /****** Object: Table [dbo].[Messages] Script Date: 09/12/2006 15:13:52 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO SET ANSI_PADDING ON GO CREATE TABLE [dbo].[Messages]( [Username] [varchar](24) COLLATE Latin1_General_CI_AS NOT NULL, [Sender] [varchar](24) COLLATE Latin1_General_CI_AS NOT NULL, [Subject] [varchar](255) COLLATE Latin1_General_CI_AS NOT NULL, [Message] [varchar](2500) COLLATE Latin1_General_CI_AS NOT NULL, [Date] [datetime] NOT NULL, [ID] [int] NOT NULL, CONSTRAINT [PK_Messages] PRIMARY KEY CLUSTERED ( [ID] ASC )WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY] ) ON [PRIMARY] GO SET ANSI_PADDING OFF
As primary keycan't be null, what do i put for primary key for my insert to work?
I'm trying to wrap my head around inserting values into a table w/ SQLDataSource. What I'm trying to do is have a form where users can submit their feedback and their responses would get put into a table on the backend. It would store not only their comments, but their userid, the url that they were on last, and which area they're from. The trouble is, I have no idea if I'm coding this correctly. On the submit Here is the form: <form id="form1" runat="server"> <asp:SqlDataSource runat="server" ID="feedbackSQL" InsertCommand="insertfeedback_sp" InsertCommandType="StoredProcedure" connectionstring="<%$ ConnectionStrings:Test%>"> <InsertParameters> <asp:Parameter Name="ID" Type="Int16" /> <asp:Parameter Name="Region" Type="String" /> <asp:Parameter Name="Querystring" Type="String" /> <asp:FormParameter Name="Comments" FormField="Comment" /> </InsertParameters> </asp:SqlDataSource> <div> <asp:TextBox ID="Comment" runat="server" Height="200px" Width="350px"></asp:TextBox><br /> <asp:Button ID="Submit" OnClientClick="btn_Submit" runat="server" BackColor="White" Font-Names="Arial" Font-Size="X-Small" Text="Submit" /> <asp:Button ID="Cancel" runat="server" BackColor="White" Font-Names="Arial" Font-Size="X-Small" Text="Cancel" OnClientClick='javascript: window.close()' /> <asp:Button ID="Clear" runat="server" BackColor="White" Font-Names="Arial" Font-Size="X-Small" Text="Clear" OnClientClick='javascript: ClearBox(Comment)' /> </div> </form>Here is the backend: protected void btn_Submit(object sender, EventArgs e) { feedbackSQL.InsertParameters["ID"].DefaultValue = UserId ; feedbackSQL.InsertParameters["Region"].DefaultValue = Region; feedbackSQL.InsertParameters["Comments"].DefaultValue = Comment.Text.ToString(); feedbackSQL.InsertParameters["Querystring"].DefaultValue = URL.ToString(); }When I test it out. Nothing shows up in my database table. I also have another problem, ID is stored in my table as an int, but when I try to set it's value in btn_Submit and try to compile it, I get a "cannont convert 'int' to 'string'" error. Am I missing something here? Any help would be much appreciated, thanks :)
Hi all, I really can't figure out what i'm doing wrong here, and I'd appreciate some help if possible please! SqlDataSource5.InsertParameters("ntuser").DefaultValue = ntuser SqlDataSource5.InsertParameters("datetime").DefaultValue = DateTime.Now SqlDataSource5.Insert()Above is my code to insert into my SQL database a varchar NT user name, and the current date. The Parameters are defined in the HTML as : <asp:SqlDataSource ID="SqlDataSource5" runat="server" ConnectionString="<%$ ConnectionStrings:Test EnvironmentConnectionString %>" InsertCommand="usp_insert_hit" InsertCommandType="StoredProcedure" SelectCommand="usp_select_hits" SelectCommandType="StoredProcedure" UpdateCommand="usp_insert_hit" UpdateCommandType="StoredProcedure"> <InsertParameters> <asp:Parameter Name="ntuser" Type="String" /> <asp:Parameter Name="datetime" Type="DateTime" /> </InsertParameters></asp:SqlDataSource> My SQL Database is set up to have a table called "Hits" which has three colums, a hit_id (Autocounter, primary key), ntuser (varchar), datetime (datetime) When the application runs it stops at runtime and highlights the SQLDataSource5.Insert() line, and I can't figure out why - can anyone else tell why please? thanks.
I've got 2 servers, with sql server 2000 sp3 and ms windows 2003 server. I've written a very simple stored procedure to insert 20,000 rows into a very simple table TEST (id int, msg varchar_50)
On the first server (P-IV 2 GHz), it takes 700 ms / 1000 insertions and on the second (2x Xeon 2,6 GHz), it takes 13 s / 1000 insertions...
(insertion is : INSERT INTO TEST (id, msg) VALUES (@id, 'dummy text'))
...
SQL Server was installed exactly in the same way...
what could I do see where the problem is ? With profiler, I see no difference while logging all events....
I have just one table but need to create a trigger that takes place after an update on the Orders table. I need it to multiply two columns and populate the 3rd column (total cost) with the result as so:
1. Let's say I have a SqlDataSource named Fred. Say I have a string variable, call it Barney. If I call Fred.Insert(Barney) HOW Does the insert command GET the Barney value and pass it to the SQL Insers string? 2. Lets say also in this same insert, I want the user Lets say Batty, who is logged in, to have her username automatically inserted into the table along with her Barney value. What is the method to get a hold of user name that is magically floating around in the session somewhere? All said and done, I'd love for it to work like this: "INSERT INTO [BedRock] ([UserName], [Character] ) VALUES (SomethingThatResolvesToSignedInUserName, SomehtingThatResolvesToStringValueofVariable) Table BedrockUserName CharacterBettyRubble 'Bam-Bam' THANKS inadvance fro ANY HelpDan-Simple and sleepless-Harper
I am using a simple stored proc shown below which inserts a record and updates the same record field called SortID with the Primary Key Column data of the same record.Everything was working fine until few days back. The site has been deployed 2 years back and was LIVE ever since. We have got thousands of records in this Credits table. The table field called SortID is used for moving the credits up and down. My problem is now after 2 years of deploying the table has got duplicate records, suprisingly a same credit is appearing under different MemberID and with the same SortID. How are these duplicate records inserted with a simple insert statement & update ?? Is this a Locking problem or Transaction problem I have no idea. Any ideas will be of great help Thanks in Advance Stored Procedure Used
CREATE PROC SP_SC_INSERT (@memberID int,@title varchar(30),@dir varchar(30),@desc varchar(20))ASINSERT INTO [dbo].[Credits]([MemberID],[Title],[Director], [Description], )VALUES(@memberID,@title,@dir, @desc, )UPDATE Credits Set SortID = @@IDENTITY WHERE CreditID = @@IDENTITYGO
This is simple enough and I'm stumped. Why doesn't this work?
Code Snippet use w go -- Create image warehouse create table dbo.ImageWarehouse ( [ImageWarehouseID] int identity(1,1) primary key, [ImageName] varchar(100), Photo varbinary(max)) Go -- Import image Insert into dbo.ImageWarehouse ([ImageName]) values ('testingimage.gif') update dbo.ImageWarehouse set Photo = (SELECT * FROM OPENROWSET(BULK 'c: estingimage.gif', SINGLE_BLOB)AS x ) WHERE [ImageName]='testingimage.jpg' go -- Check population --delete from dbo.ImageWarehouse select * from dbo.ImageWarehouse go -- Export image declare @SQLcommand nvarchar(4000) set @SQLcommand = 'bcp "SELECT top 1 Photo FROM w.dbo.ImageWarehouse WHERE ImageName = ''testingimage.gif''" queryout "c: estingimage_out.gif" -T -N -S [my server name]' exec xp_cmdshell @SQLcommand go
But testingimage_out.gif is unreadable. It's the same size (28k) as the original trestingimage.gif. Same result with a .jpg file. Try to open the file and it's just red X.
No SQL errors. Just result error. What am I overlooking?
I have installed VS 2008 Beta 2 which includes SQL CE 3.5, (I have VS 2005 installed too).
I can not get any INSERT command to work!
First i have tried the VS wizard for a new connection and a dataset. but after inserting a row into one of the dataset tables and then updating it to SQL CE with tha data adapter, nothing happens! NO ERROR and NO inserted row in the database file! so the identity of the inserted row in dataset table doesnt get updated.
Then i tried a simple code without any dataset in a clean solution:
Code Snippet
Dim con As New SqlCeConnection("Data Source=|DataDirectory|MyDatabase#1.sdf") Dim cmd As New SqlCeCommand("INSERT INTO [Table1](Name) VALUES('TestValue')", con) Try con.Open() cmd.ExecuteNonQuery() Catch ex As SqlCeException MessageBox.Show(ex.Message) Finally con.Close() End Try NO ERROR! NO INSERTED ROW! Nothing happen!
I have a master securities table which has 7 fields. As a part of the daily process I am uploading flat files into database tables. The flat files contains the master(static) security data as well as the analytics(transaction) data. I need to
1) separate the master (static) data from the flat files,
2) check whether that data is present in the master table, if not then insert that data into the master table
3) If data present then move that existing record to an history table and then update the main master table.
All the 7 fields need to be checked to uniquely identify a single record in the master table.
How can this be done? Whether we can us a combination of data flow items or write a sql procedure to do all this.
--Table 1 "Employee" CREATE TABLE [MyCompany].[Employee]( [EmployeeGID] [int] IDENTITY(1,1) NOT NULL, [BranchFID] [int] NOT NULL, [FirstName] [varchar](50) NOT NULL, [MiddleName] [varchar](50) NOT NULL, [LastName] [varchar](50) NOT NULL, CONSTRAINT [PK_Employee] PRIMARY KEY CLUSTERED ( [EmployeeGID] ) GO ALTER TABLE [MyCompany].[Employee] WITH CHECK ADD CONSTRAINT [FK_Employee_BranchFID] FOREIGN KEY([BranchFID]) REFERENCES [myCompany].[Branch] ([BranchGID]) GO ALTER TABLE [MyCompany].[Employee] CHECK CONSTRAINT [FK_Employee_BranchFID]
-- Table 2 "Branch" CREATE TABLE [Mycompany].[Branch]( [BranchGID] [int] IDENTITY(1,1) NOT NULL, [BranchName] [varchar](50) NOT NULL, [City] [varchar](50) NOT NULL, [ManagerFID] [int] NOT NULL, CONSTRAINT [PK_Branch] PRIMARY KEY CLUSTERED ( [BranchGID] ) GO ALTER TABLE [MyCompany].[Branch] WITH CHECK ADD CONSTRAINT [FK_Branch_ManagerFID] FOREIGN KEY([ManagerFID]) REFERENCES [MyCompany].[Employee] ([EmployeeGID]) GO ALTER TABLE [MyCompany].[Branch] CHECK CONSTRAINT [FK_Branch_ManagerFID]
--Foreign IDs = FID --generated IDs = GID Then I try a simple single row DELETE
DELETE FROM MyCompany.Employee WHERE EmployeeGID= 39
Well this might look like a very basic error: I get this Error after trying to delete something from Table €œEmployee€?
The DELETE statement conflicted with the REFERENCE constraint "FK_Branch_ManagerFID". The conflict occurred in database "MyDatabase", table "myCompany.Branch", column 'ManagerFID'.
Yes what I€™ve been doing is to deactivate the foreign key constraint, in both tables when performing these kinds of operations, same thing if I try to delete a €œBranch€? entry, basically each entry in €œbranch€? and €œEmployee€? is child of each other which makes things more complicated.
My question is, is there a simple way to overcome this obstacle without having to deactivate the foreign key constraints every time or a good way to prevent this from happening in the first place? Is this when I have to use €œON DELETE CASCADE€? or something?
Is there a format function in MDX which will help me solve the following scenario:
One of my measures is Net Sales and I have tried all different formats in Analysis Services so that it shows without the decimal places i.e. instead of showing the Net Sales for any selected combination of Dimensions as 123,456.04, I want to show it as 123,456
When I browse the cube (in Analysis Services), I can meet my requirement. However, in my front-end (Microsoft Data Analyzer), I am still getting it as 123,456.04 (even when the same in Analysis services, i.e. when I browse the cube, is being shown as 123,456).
I do not have much choice at the moment and am stuck with Microsoft Data Analyzer and unfortunately have not been able to solve this :(
Can someone think of a solution/workaround/use of MDX which will help me get the results being displayed without the decimal. Is there a format function that I can use in MDX and how to use it???
Hello,What is uniqueidentifier as a data type?Also what is the data type for setting unique STRINGS ((nchar,nvarchar), for example to be used for emails and user names in a userregistration system).SQL Server does not allow me set primary keys for columns where datatypes are not INT.Thanks in advance.
I've been working on a performance review web application (i.e., employee's annual reviews done via the web). In the process of creating the application I've been teaching myself .NET - maybe not the best way to do it but I've been learning a lot. However, I still feel like I'm not doing something right.On each Page_Load I'm doing database work with a data reader: Reading the data in, displaying it, letting the user add, edit, or delete it, etc. So every Page_Load code behind looks like this: string sql = "SELECT UserID, Passwd, RecID, Name FROM UserList";
SqlConnection myConn = new SqlConnection("Server=BART; Database=WSSD; User ID=sa; Password=wss1231"); SqlCommand cmd = new SqlCommand(sql, myConn); SqlDataReader dr;
myConn.Open(); dr = cmd.ExecuteReader(); And so forth and so on. Now since I re-use this code again and again - I imagine it's a good idea to implement my connection code in a class that I can re-use easily. But I have no idea where to start on something like that. What can I say? I'm a newb. A push in the right direction would be great.