Inserting A Record For Each Separate Aggregate (solved)
Jul 23, 2005
Hi,
As I wrote my message the solution came to me, so I thought I would
post anyway for others to see in case it was useful:
Here is some sample DDL for this question:
CREATE TABLE Source (
my_value INT NOT NULL )
GO
INSERT INTO Source VALUES (1)
INSERT INTO Source VALUES (2)
INSERT INTO Source VALUES (3)
GO
CREATE TABLE Destination (
value_type VARCHAR(10) NOT NULL,
value INT )
GO
I would like to fill the destination with a row for the COUNT, SUM,
MIN, and MAX. My own problem is of course much more complex than this,
but this is the basic stumbling block for me now. So, the rows that I
would expect to see in Destination are:
value_type value
---------- -----
COUNT 3
SUM 6
MIN 1
MAX 3
The solution that I came up with was to add a Value_Types table:
CREATE TABLE Value_Types (
value_type VARCHAR(10) NOT NULL )
GO
INSERT INTO Value_Types VALUES ('COUNT')
INSERT INTO Value_Types VALUES ('SUM')
INSERT INTO Value_Types VALUES ('MAX')
INSERT INTO Value_Types VALUES ('MIN')
GO
Now the SQL is pretty simple:
SELECT V.value_type,
CASE V.value_type
WHEN 'COUNT' THEN COUNT(*)
WHEN 'SUM' THEN SUM(S.my_value)
WHEN 'MAX' THEN MAX(S.my_value)
WHEN 'MIN' THEN MIN(S.my_value)
END
FROM Source S
INNER JOIN Value_Types V ON 1=1
-Tom.
P.S. - I know that I did not include primary or foreign keys in my DDL.
I'll leave it as an excercise to the reader to figure those out. I
think the code adequately explains the concept.
I am trying to tie together tables that show quantities of a product committed to an order and quantities on hand by a location.
My end result should look like the below example.
Item Location QtyOnHandByLocation SumQtyCommitTotal Prod1 NJ 10 10 Prod1 NY 10 0 Prod1 FL 0 0 Prod1 PA 0 0
So I can see I have 10 items in NJ On Hand and Committed to an order. 10 available in NY but not on an order. Then the other two locations have no quantities.
Below is the CTE but it produces inaccurate results. I've tried running it several different ways by playing with the grouping but have no luck thus far.
--create the temp table Create table #SalesLine ( Novarchar (50) not null , LocationCodevarchar (50) not null , QtyCommitint not null ) create table #ItemLedgerEntry
[code]....
I am close to the desired results but can't find a way.
Is that possible to restrict inserting the record if record already exist in the table.
Scenario: query should be
We are inserting a bulk information of data, it should not insert the row if it already exist in the table. excluding that it should insert the other rows.
Hello, I am working with a database that among other things uses multipart keys as the unique indexes which are not consistent from say one table where a parent record resides to another table which contains related child records. For example I am working with two tables right now, one that contains content that I'll call Contents and the other which contains Usage information about the contents (number of view, a rating and comments give by a customer) which I'll call ContentsUsage. The system that manages the data for the tables has a versioning system by which, whn a content item is added (first time) a "unique" id (guid) and a version number of 1 is created along with the rest of data items in the Contents table and likewise in the ContentsUsage table (essentially a one to one mapping) on the like named fields in that table. Now, each time a given record in the Contents table is updated a new version, with the same guid is created in the Contents and ContentsUsage table. So one side I have:ContentGUID > AAAAVersion > 1ContentGUID > AAAAVersion > 2And the other table (ContentsUsage)ContentGUID > AAAAVersion > 1ContentGUID > AAAAVersion > 2 While both of these tables have a quasi-unique record (row_id) of type char and stored as a guid neither obviously are the same in the two tables and having reviewed the database columns for these tables I find that the official unique key's for these tables are different (table 1, Contents combines the ContentGUID and Version) as the composite / mutli-key index, while table ContentsUsage uses the RowGUID as it's unique index. Contents RowGUID (unique key)ContentGUIDVersionViewsRatingComments................RowGUID ContentGUID (unique key)Version (unique key)Description..... Bearing this in mind I am unable of course to link directly the two tables by using the just the ContentGUID and have to combine the additional Version to I believe obtain the actual "unique" record in question. The question is in terms of writing queries, what would the most efficient query be? What would be the best way to join the two in a query? And are there any pitfalls with the current design that you can see with the way this database (or specifically these tables are defined)? It's something I inherited, so fire away at will on the critique. Having my druthers I would have designed these tables using a unique key of type int that was autogenerated by the database. Any advice, thoughts or comments would be helpful. Thanks,P.
I would like to 'one table' record to separate 'two or three tables' . I just know use the DTS , try to import and export again and agian. So trouble.
Could you give me some suggestions for me? For example , 'Cursor' write in new table . But I try to SQL Server Books Online which is not suitable for me solving problems. One table separate two or three tables. Can you wirte the detail example for me? Thx a lot.
Hey gang, I've got a query and I'm really not sure how to get what I need. I've got a unix datasource that I've setup a linked server for on my SQL database so I'm using Select * From OpenQuery(DataSource, 'Query') I am able to select all of the records from the first two tables that I need. The problem I'm having is the last step. I need a field in the select statement that is going to be a simple yes or no based off of if a customer number is present in a different table. The table that I need to look into can have up to 99 instances of the customer number. It's a "Note" table that stores a string, the customer number and the sequence number of the note. Obviously I don't want to do a straight join and query because I don't want to get 99 duplicates records in the query I'm already pulling. Here's my current Query this works fine: Select *From OpenQuery(UnixData, 'Select CPAREC.CustomerNo, CPBASC_All.CustorCompName, CPAREC.DateAdded, CPAREC.Terms, CPAREC.CreditLimit, CPAREC.PowerNum From CPAREC Inner Join CPBASC_All on CPAREC.CustomerNo = CPBASC_All.CustomerNo Where DateAdded >= #12/01/07# and DateAdded <= #12/31/07#') What I need to add is one more column to the results of this query that will let me know if the Customer number is found in a "Notes" table. This table has 3 fields CustomerNo, SequenceNo, Note. I don't want to join and select on customer number as the customer number maybe repeated as much as 99 times in the Notes table. I just need to know if a single instance of the customer number was found in that table so I can set a column in my select statement as NotesExist (Yes or No) Any advice would be greatly appreciated.
I have sql code that returns the correct number of record when run without an aggregate function like count(myfield) and group by myfield. It always returns 86 row which is correct when Select DISTINCT is used. As, expected when DISTINCT is not used I get double the number if rows or 172. But when I count(myfield) and group by myfield the count is 172 and not 86. The strangest thing about this is that when I am grouping a set of items
Group 1
Group 2
Group 3
The other group sum up correctly while others don't. What can explain this? Here is the code.
Select DISTINCT ws.p4Districtnumber, ws.cycle, ws.worksetid, count(msi.MeterSessionInputKey) as ASND from fcs.dbo.WorkSet as ws left outer join fcs.dbo.WorkAssignment as wa on ws.WorkSetID = wa.WorkSetID left outer join fcs.dbo.MeterSessionInput as msi on wa.worksetkey = msi.worksetkey
I'm working on a database for a financial client and part of what i need to do is calculate a value from two separate rows in the same table and insert the result in the same table as a new row. I have a way of doing so but i consider it to be extremely inelegant and i'm hoping there's a better way of doing it. A description of the existing database schema (which i have control over) will help in explaining the problem:
id metric_id metric_type_id metric_name 1 80 2 Fiscal Enterprise Value Historic Year 1 2 81 2 Fiscal Enterprise Value Current Fiscal Year 3 82 2 Fiscal Enterprise value Forward Fiscal year 1 4 83 2 Fiscal Enterprise Value Forward Fiscal Year 2 5 101 3 Calendar Enterprise value Historic Year 1 6 102 3 Calendar Enterprise Value Current Fiscal Year 5 103 3 Calendar Enterprise value Forward Year 1 6 104 3 Calendar Enterprise Value Forward Year 2
Table Name: metric_type_details
id metric_type_id metric_type_name 1 1 Raw 2 2 Fiscal 3 3 Calendar 4 4 Calculated
The problem scenario is the following: Because a certain number of the securities have a fiscal year end that is different to the calendar end in addition to having fiscal data (such as fiscal enterprise value and fiscal earnings etc...) for each security i also need to store calendarised data. What this means is that if security with security_id = 3 has a fiscal year end of October then using rows with ids = 1, 2, 3 and 4 from the metrics_ladder table i need to calculate metrics with metric_id = 83, 84, 85 and 86 (as described in the metric_details table) and insert the following 4 new records into metrics_ladder:
Metric with metric_id = 101 (Calendar Enterprise value Historic Year 1) will be calculated by taking 10/12 of the value for metric_id 80 plus 2/12 of the value for metric_id 81.
Similarly, metric_id 102 will be equal to 10/12 of the value for metric_id 81 plus 2/12 of the value for metric_id 82,
metric_id 103 will be equal to 10/12 of the value for metric_id 82 plus 2/12 of the value for metric_id 83 and finally
metric_id 104 will be NULL (determined by business requirements as there is no data for forward year 3 to use).
As i could think of no better way of doing this (and hence the reason for this thread) I am currently achieving this by pivoting the relevant data from the metrics_ladder so that the required data for each security is in one row, storing the result in a new column then unpivoting again to store the result in the metrics_ladder table. So the above data in nmetrics_ladder becomes:
-- Dummy year variable to make it easier to use MONTH() function -- to convert 3 letter month to number. i.e. JAN -> 1, DEC -> 12 etc... DECLARE @DUMMY_YEAR VARCHAR(4) SET @DUMMY_YEAR = 1900;
with temp(security_id, metric_id, value) as ( select ml.security_id, ml.metric_id, ml.value from metrics_ladder ml where ml.metric_id in (80,81,82,83,84,85,86,87,88,etc...) -- only consider securities with fiscal year end not equal to december and ml.security_id in (select security_id from company_details where fiscal_year_end <> 'dec') ) insert into @calendar_averages select temppivot.security_id -- Net Income ,(CONVERT(DECIMAL, MONTH(cd.fiscal_year_end + @DUMMY_YEAR))/12*[80]) +((12 - CONVERT(DECIMAL, MONTH(cd.fiscal_year_end + @DUMMY_YEAR)))/12*[81]) as [101] ,(CONVERT(DECIMAL, MONTH(cd.fiscal_year_end + @DUMMY_YEAR))/12*[81]) +((12 - CONVERT(DECIMAL, MONTH(cd.fiscal_year_end + @DUMMY_YEAR)))/12*[82]) as [102] ,(CONVERT(DECIMAL, MONTH(cd.fiscal_year_end + @DUMMY_YEAR))/12*[82]) +((12 - CONVERT(DECIMAL, MONTH(cd.fiscal_year_end + @DUMMY_YEAR)))/12*[83]) as [103] ,NULL as [104] -- Share Holders Equity ,(CONVERT(DECIMAL, MONTH(cd.fiscal_year_end + @DUMMY_YEAR))/12*[84]) +((12 - CONVERT(DECIMAL, MONTH(cd.fiscal_year_end + @DUMMY_YEAR)))/12*[85]) as [105] ,(CONVERT(DECIMAL, MONTH(cd.fiscal_year_end + @DUMMY_YEAR))/12*[85]) +((12 - CONVERT(DECIMAL, MONTH(cd.fiscal_year_end + @DUMMY_YEAR)))/12*[86]) as [106] ,(CONVERT(DECIMAL, MONTH(cd.fiscal_year_end + @DUMMY_YEAR))/12*[86]) +((12 - CONVERT(DECIMAL, MONTH(cd.fiscal_year_end + @DUMMY_YEAR)))/12*[87]) as [107] ,NULL as [108] -- Capex -- Sales -- Accounts payable etc... .. .. from temp pivot ( sum(value) for metric_id in ([80],[81],[82],[83],[84],[85],[86],[87],[88],etc...) ) as temppivot inner join company_details cd on temppivot.security_id = cd.security_id
********* END SQL *********
The result then needs to be unpivoted and stored in metrics_ladder.
And FINALLY, the question! Is there a more elegant way of achieving this??? I have complete control over the database schema so if creating mapping tables or anything along those lines would help it is possible. Also, is SQL not really suited for such operations and would it therefore be better done in C#/VB.NET.
I want to insert a new record into my db in asp.net. Im programming in vb and using an sql server database. i know this is a begginers question but that's exactly what i am. Thanks in advance
hey everyone,I have created two tables in an sql server database. I have a check box in the table 1, and when it is checked, I want to insert that particular record into table 2. (By the way I am using a datagrid) The problem is when I click the check on the particular record I want inserted, and click update, the system copies the record twice instead of once. When I look into table 2, I end up having two of the same records. Can anyone help me.
I am simply trying to use SQLCommand in .net to insert a record into a SQL Server 2005 table. There are 2 fields being pulled from a user input for that could have no values selected. In this case I want to insert a null value into the record. I get an error that Null is no longer supported and that I should use System.DBNull, but that can't be used as an expression. How do I do this? Thank you in advance.
Hi All, i am new to programming, in my application i want to insert a record in sql server database using Ado.net for that i used SqlConnection cn=new SqlConnection(ConfigurationManager.ConnectionStrings["constring"].ConnectionString); SqlCommand cmd; protected void btnInsert_Click(object sender, EventArgs e) { try { cmd = new SqlCommand("Insert into DeptInfo(deptid,deptname)values(" + TextBox1.Text + ",'" + TextBox2.Text + "')", cn); SqlDataAdapter da = new SqlDataAdapter(cmd); cn.Open(); cmd.ExecuteNonQuery(); cn.Close(); TextBox1.Text = ""; TextBox2.Text = ""; } catch(Exception ex) { }} But my requirement is when ever the Insert command is successfull it has to display some alert message(using java script) saying "RECORD INSERTED SUCCESSFULLY" if Record insertion fails it should display some alert message "INSERTING NEW RECORD FAILED" . Any help will be greatly appreciated Thanks,Vision.
i am running a query from one of my asp.net pages. I then want the results which will be around 20 - 30 records to be inserted to a new table. How do I do this?
I get the records from my query but how would i insert more than one record to a new table?
Is it possible to have sql server automatically record date and time (in a designated field)when a record is created in the db? This may seam basic but it has caused me a lot of grief.
I can't seem to get this work. I'm using SQL2005 I want to check if a record exists before entering it. I just can't figure out how to check it before hand. Thanks in advance. Protected Sub BTNCreateProdIDandName_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles BTNCreateProdIDandName.Click ' Define data objects Dim conn As SqlConnection Dim comm As SqlCommand
' Reads the connection string from Web.config Dim connectionString As String = ConfigurationManager.ConnectionStrings("HbAdminMaintenance").ConnectionString ' Initialize connection conn = New SqlConnection(connectionString)
' Check to see if the record exists If comm = New SqlCommand("EXISTS (SELECT (BuilderID, OptionNO FROM optionlist WHERE (BuilderID = @BuilderID) AND (OptionNO = @OptionNO)", conn)
Then 'if the record is exists display this message. LBerror.Text = "This item already exists in your Option List." Else
'If the record does not exist, add it. FYI - This part works fine by itself. comm = New SqlCommand("INSERT INTO [OptionList] ([BuilderID], [OptionNO], [OptionName]) VALUES (@BuilderID, @OptionNO, @OptionName)", conn)
I am trying to insert a record into a sql server table from a textbox in a form but am getting this error The name "textbox1value" is not permitted in this context. Valid expressions are constants, constant expressions, and (in some contexts) variables. Column names are not permitted. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.Data.SqlClient.SqlException: The name "textbox1value" is not permitted in this context. Valid expressions are constants, constant expressions, and (in some contexts) variables. Column names are not permitted.Source Error:
Line 33: dim command1 as sqlcommand=new sqlcommand(q1,connection1) Line 34: command1.connection.open() Line 35: command1.executenonquery() Line 36: command1.connection.close() Line 37: end sub This code is right below. The sub called a() is the one with the problem. <html> <head> <title> </title> <script language="vb" runat="server"> sub page_load(sender as object, e as eventargs) if not page.ispostback then binddata1() end if end sub sub binddata1() dim connection1 as new sqlconnection("server=111.111.11.11;uid=aa;pwd=bb;database=cc") const q as string="select dxid,code from tbltest where date_del is null order by code" dim command1 as new sqlcommand(q,connection1) dim dataadapter1 as new sqldataadapter() dataadapter1.selectcommand=command1 dim dataset1 as new dataset() dataadapter1.fill(dataset1) grid1.datasource=dataset1 grid1.databind() end sub sub a(sender as object,e as eventargs)' response.write(textbox1.text) dim textbox1value as string textbox1value=textbox1.text dim connection1 as sqlconnection=new sqlconnection("server=111.111.11.11;uid=aa;pwd=bb;database=cc") const q1 as string="insert into tbltest(code,descriptor) values (textbox1value,'test')" dim command1 as sqlcommand=new sqlcommand(q1,connection1) command1.connection.open() command1.executenonquery() command1.connection.close() end sub </script> </head> <body> <form runat="server"> <asp:textbox id="textbox1" runat="server" /> <asp:button id="button1" text="click" onclick="a" runat="server" /> <asp:datagrid id="grid1" runat="server" /> </form> </body></html> What am I doing wrong? How can I get the insert query to put the value of textbox1.text into the column called code? Sorry if I am not explaining things clearly. This is like a foreign language to me.
Hi, Can someone please tell me the best practices for checking the primary key field before inserting a record into my database? As an example I have created an asp.net page using VB with an SQL server database. The web page will just insert two fields into a table (Name & Surname into the Names table). The primary key or the Names table is "Name". When I click the Submit button I would like to check to ensure there is not a duplicate primary key. If there is return a user friendly message i.e. A record already exisits, if there no duplicate, add the record. I guess I could use try, catch within the .APSX page or would a stored procedure be better? Thanks Brett
Is there a way to test the integrity of a record which is about to be inserted in a database before doing so? The goal is to prevent all kinds of runtime errors that will occur after the insertion, if the record breaks any of the database rules. The solution should apply to a VBScript used inside a DTS package.
SELECTIndustry, 100.0 * SUM(CASE when ceoischairman = 'yes' then 1 else 0 end) / COUNT(DISTINCT CompID) AS [YesPercent], 100.0 * SUM(CASE when ceoischairman = 'no' then 1 else 0 end) / COUNT(DISTINCT CompID) AS [NoPercent] FROMTCompanies GROUP BYIndustry ORDER BYIndustry
This code above is working as I need it but I need to insert some additional functionality. Thanks
I need to add something like this:
IF YesPercent > NoPercent UPDATE tableX SET CEOIsChairman='Yes' WHERE Industry='<the industry value being evaluated>' Else If NoPercent > YesPercent UPDATE tableX SET CEOIsChairman='No' WHERE Industry='<the industry value being evaluated>' Else UPDATE tableX SET CEOIsChairman='Equal' WHERE Industry='<the industry value being evaluated>' End
I'm using Microsoft SQL Server Management Studio with SQL Server 2005 (SP2).
I have not had much experience with t-SQL and iterative logic implementation through SQL, therefore I think my problem is fairly basic for most of the pros here.
Here it goes...
I have two tables at hand, TestTab1 and TestTab2.
TestTab1 contains two attributes (columns) namely account_name (nvarchar(50)) and entry_count (int). For all rows in TestTab1, account_name is unique, i.e. for each account_name there is only 1 row in TestTab1. This is my source table.
TestTab2 contains one attribute namely account_name (nvarchar(50)). This table is empty and is my destination table.
I need to insert X entries (rows) for each account_name into TestTab2 where X is the int value in entry_count againt each account_name in TestTab1.
In other words, I need to insert account_name into TestTab2 as many times as the number in entry_count indicates.
I tried reading through the documentation but the help was not friendly enough for me to understand how to implement this.
How do i insert a carriage return at the end of an record that's being sent to a flat file? Currently, I get one long string, and would like for SSIS to put carriage returns at the end of each line.
hii I have to insert some data into a table from the webpage. For that I need to know the last occurred value in the primary key and increment this by one and then insert the new record into the table. I am working with SQL Server 2005. I am coding in VB and ASP.NET 2.0. How will I go about this?? Is there some easy way for me to knw the last value of the primary key n then insert the record. It would be great if I get the idea more clear with the help of some code... Thanks
Im trying to add a new rcord to my db on a button click usign the following code
'data adapter Dim dAdapt1 As New SqlClient.SqlDataAdapter 'create a command object Dim objCommand As New SqlClient.SqlCommand 'command builder Dim builderT As SqlClient.SqlCommandBuilder 'connection string Dim cnStr As String = "Data Source=ELEARN-FRM-BETA;Initial Catalog=StudentPlayGround;Integrated Security=True" 'dataset Dim dsT As DataSet Private Sub connect() 'connection objCommand.Connection = New SqlClient.SqlConnection(cnStr) 'associating the builder with the data adapter builderT = New SqlClient.SqlCommandBuilder(dAdapt1) 'opening the connection objCommand.Connection.Open() 'query string Dim query As String = "SELECT * from StudentPlayground..Employees" 'setting the select command dAdapt1.SelectCommand = New SqlClient.SqlCommand(query, objCommand.Connection) 'dataset dsT = New DataSet("Trainee Listings") dAdapt1.Fill(dsT, "Employees") End Sub Private Sub BindData() connect() DataBind() End Sub Protected Sub submitButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles submitButton.Click Dim empID As Integer = CType(FindControl("TextBox8"), TextBox).Text BindData() Dim firstName As String = CType(FindControl("TextBox1"), TextBox).Text BindData() Dim lastName As String = CType(FindControl("TextBox2"), TextBox).Text BindData() Dim location As String = CType(FindControl("TextBox3"), TextBox).Text BindData() Dim termDate As Date = CType(FindControl("TextBox4"), TextBox).Text BindData() Dim hireDate As Date = CType(FindControl("TextBox7"), TextBox).Text BindData() Dim dept As String = CType(FindControl("TextBox5"), TextBox).Text BindData() Dim super As String = CType(FindControl("TextBox6"), TextBox).Text BindData() Dim newRow As DataRow = dsT.Tables("Employees").NewRow newRow.BeginEdit() newRow.Item(0) = empID newRow.Item(1) = firstName newRow.Item(2) = lastName newRow.Item(3) = location newRow.Item(4) = hireDate newRow.Item(5) = termDate newRow.Item(6) = dept newRow.Item(7) = super newRow.EndEdit()
'do the update Dim insertStr As String = "INSERT INTO Employees" + _ "(EmployeeID,FirstName,LatName,Location,HireDate,TerminationDate,Supervisor)" + _ "VALUES (empID,firstName,lastName,location,hireDate,termDate,dept,super)" Dim insertCmd As SqlClient.SqlCommand = New SqlClient.SqlCommand(insertStr, objCommand.Connection) dAdapt1.InsertCommand() = insertCmd
dAdapt1.Update(dsT, "Employees") 'Dim insertCmd As new SqlClient.SqlCommand = (builderT.GetInsertCommand()).ToString()) 'dAdapt1.InsertCommand = New SqlClient.SqlCommand(insertCmd.ToString(), objCommand.Connection) BindData() objCommand.Connection.Close() objCommand.Connection.Dispose() End Sub
im not sure wats going wrong because the record is not being added. Please help!!
Hello, I'm trying to accomplish 3 things with one stored procedure.I'm trying to search for a record in table X, use the outcome of thatsearch to insert another record in table Y and then exec another storedprocedure and use the outcome of that stored procedure to update therecord in table Y.I have this stored procedure (stA)CREATE PROCEDURE procstA (@SSNum varchar(9) = NULL)ASSET NOCOUNT ONSELECT OType, Status, SSN, FName, LNameFROM CustomersWHERE (OType = 'D') AND (Status = 'Completed') AND (SSN = @SSNum)GO.Then, I need to create a new record in another table (Y) using the SSN,FName and Lname fields from this stored procedure.After doing so, I need to run the second stored procedure (stB) Here itis:CREATE PROCEDURE procstB( @SSNum varchar(9) = NULL)ASSET NOCOUNT ON-- select the recordSELECT OrderID, OrderDate, SSNFROM OrdersGROUP BY OrderID, OrderDate, SSNHAVING (ProductType = 'VVSS') AND (MIN(SSN) = @SSNum)GO.After running this, I need to update the record I created a moment agoin table Y with the OrderDate and OrderID from the second storedprocedure.Do you guys think that it can be done within a single stored procedure?Like for example, at the end of store procedure A creating an insertstatement for the new record, and then placing something like execprocstB 'SSN value'? to run stored procedure B and then having aupdate statement to update that new record?Thanks for all your help.
A user inadvertantly deleted a record in a table that maintains an identity seed. I attempted to insert the record using SET IDENTITY_INSERT ON, but forgot that this table is an article in merge replication. I am attempting the insert on the publisher and I get the following message:
Msg 548, Level 16, State 2, Line 2
The insert failed. It conflicted with an identity range check constraint in database 'cad', replicated table 'dbo.emmain', column 'empl_id'. If the identity column is automatically managed by replication, update the range as follows: for the Publisher, execute sp_adjustpublisheridentityrange; for the Subscriber, run the Distribution Agent or the Merge Agent.
The statement has been terminated.
How can I re-insert this record??Thanks in advance for any help
I am duplicating a record from my asp.net page in to the database. When i click on save I am getting the following error message Violation of PRIMARY KEY constraint 'PK_clientinfo'. Cannot insert duplicate key in object 'clientinfo'. The statement has been terminated. The above message i am getting since i have tried to duplicate the clientname field of my table which is set as the primary key. What i want is instead of this message in the browser i need to display an alert saying "the clientname entered already exists" by checking the value from the database. Here is my code. pls modify it to achieve the said problem if(Page.IsValid==true) { conn.Open(); SqlCommand cmd = new SqlCommand("insert into clientinfo (client_name, address) values ('"+txtclientname.Text+"', '"+txtaddress.Text+"')", conn); cmd.ExecuteNonQuery(); conn.Close(); BindData(); txtclear(); System.Web.HttpContext.Current.Response.Write("<script>alert('New Record Added!');</script>"); Response.Redirect("Clientinfo.aspx"); }
i currently have more tha 3 million of records in my table in sql 7. i am getting timeout error in my web application when i try to insert a record in that table
what could be rhe reason for this? how to avoid this type of problem?
Hi, All:Please help. I use sql server as back end and Access 2003 as front end(everything is DAO).A table on SQL server has an identity column as the key.We have trouble on adding records to this table using the following SQL.strSQL = "INSERT INTO myTableOnSQLServer (A, B, C, D, E) SELECT A, B, C, D,E FROM myTableonAccessLocal"db.execute strSQLThe schema of the table "myTableOnSQLServer" and the schema of the table"myTableonAccessLocal" are all the same except that the "myTableOnSQLServer"has an identity column (ID). The key of the "myTableOnSQLServer" is "ID" andthe table "myTableonAccessLocal" does not have a key.When we try to run the query, it gives errors indicating the key is violatedor missing.Should I figure out the autonumber for it first and then add to the SQLserver table?Many thanks,HS
Inside a single transaction I'm inserting/updating multiple records into multiple tables, in this order: table 1 record 1 table 2 record 1 table 3 record 1 table 1 record 2 table 2 record 1 table 1 record 3 table 2 record 3 table 3 record 3
Now I'm getting an unspecified error on a certain table:
Indicates a data modification, such as an insert, an update, or a deletion. Ensures that multiple updates cannot be made to the same resource at the same time. (I assume that multiple updates within the SAME transaction can be made, only multiple updates from different transaction cannot be made, right?) I cannot find any reference to this error message and don't know what the numbers mean. Maybe it relates to data that can be found in the sys.lock_information table like explained here, http://technet.microsoft.com/en-us/library/ms172932.aspx, but I'm not sure.
Furthermore, the sys.lock_information table is empty. I haven't been able to reproduce the problem myself. I only received an error log and the database to investigate it.
So, does anybody have an idea what this error message means and what I can do to troubleshoot this?