Cyclical Reference Problem With 2 On Delete Cascades Pointing To Same Table.

Apr 13, 2007

I am not sure if this is necessarily a simple question, but I'm somewhat new to SQL so I thought maybe there's an obvious answer I just don't know about.

The problem is that I have one "master" table, and a child table that has two foreign key references back to that master table. Both of these foreign key constraints are marked as "on delete cascade" with the intention that should a row from the master table be deleted, any rows that reference that object in EITHER foreign key field should be deleted.

I am wondering why this causes a cycle. It seems logical enough to me, it just involves two passes of the table, one for each affected column.

Thanks,
Logan

View 4 Replies


ADVERTISEMENT

Cyclical Reference Error With Foreign Keys

Oct 26, 2007

The following SQL statements give me an error on the last line:

CREATE TABLE Employees (id int PRIMARY KEY NOT NULL, name nvarchar(50));
CREATE TABLE RandomTable (uniq int PRIMARY KEY NOT NULL, empid1 int NOT NULL, empid2 int NOT NULL);
ALTER TABLE RandomTable ADD CONSTRAINT RandomTable_FKey_1 FOREIGN KEY (empid1) REFERENCES Employees (id) ON DELETE CASCADE;
ALTER TABLE RandomTable ADD CONSTRAINT RandomTable_FKey_2 FOREIGN KEY (empid2) REFERENCES Employees (id) ON DELETE CASCADE;

The error is:

"The referential relationship will result in a cyclical reference that is not allowed."

Um...how is this cyclical? Is it because I have multiple cascade paths? If so, how do I go about doing the same thing?

Thanks,
Jeff

View 5 Replies View Related

How To Undo A Delete With Cascades

Aug 30, 2005

Hello,Somebody accidently deleted a record with cascade deletesand took out about 80 records.The database has been used heavily since then.How do I put back the data?I have spent hours researching BOL and all I can findis how to restore the database to a point in time.But that will lose all the work done after the mistake.(We do a full backup every week and log backup every day)Is there a standard way to do this?Morgan

View 2 Replies View Related

Cascading Delete And Finding Table Reference Level

Feb 16, 2008

This function will generate all DELETE statements in correct order to perform a CASCADING delete.
For self-joined tables, it will generate the T-SQL code to "unwind" the table, also in correct order!CREATE FUNCTION dbo.fnCascadingDelete
(
@Schema NVARCHAR(128) = NULL,
@Table NVARCHAR(128) = NULL
)
RETURNS@Return TABLE
(
RowID INT PRIMARY KEY CLUSTERED,
IsSelfJoin TINYINT NOT NULL,
HasPk TINYINT NOT NULL,
[SQL] NVARCHAR(4000) NOT NULL
)
AS
BEGIN
DECLARE@Constraints TABLE
(
RowID INT NOT NULL,
Indent SMALLINT NOT NULL,
[Catalog] NVARCHAR(128) NOT NULL,
[Schema] NVARCHAR(128) NOT NULL,
[Table] NVARCHAR(128) NOT NULL,
[Column] NVARCHAR(128),
pkCatalog NVARCHAR(128),
pkSchema NVARCHAR(128),
pkTable NVARCHAR(128),
pkColumn NVARCHAR(128),
pkType NVARCHAR(128),
pkSize INT,
IsSelfJoin TINYINT NOT NULL,
HasPk TINYINT NOT NULL
)

INSERT@Constraints
(
RowID,
Indent,
[Catalog],
[Schema],
[Table],
[Column],
pkCatalog,
pkSchema,
pkTable,
pkColumn,
pkType,
pkSize,
IsSelfJoin,
HasPk
)
SELECTRowID,
Indent,
[Catalog],
[Schema],
[Table],
[Column],
pkCatalog,
pkSchema,
pkTable,
pkColumn,
pkType,
pkSize,
SelfJoin,
CASE
WHEN [Column] IS NULL THEN 0
ELSE 1
END
FROMdbo.fnTableTree(@Schema, @Table)

IF @@ROWCOUNT = 0
RETURN

DECLARE@SQL TABLE
(
ID INT IDENTITY(1, 1),
RowID INT PRIMARY KEY CLUSTERED,
IsSelfJoin TINYINT NOT NULL,
HasPk TINYINT NOT NULL,
[SQL] NVARCHAR(4000) NOT NULL
)

DECLARE@Indent SMALLINT,
@RowID INT,
@ID INT,
@TSQL NVARCHAR(4000),
@RowSQL NVARCHAR(4000),
@EndSQL NVARCHAR(4000),
@pkColumn NVARCHAR(128),
@IsSelfJoin TINYINT,
@HasPk TINYINT

DECLARE@Unwind TABLE
(
RowID INT NOT NULL,
StepID INT IDENTITY(0, 1) PRIMARY KEY NONCLUSTERED,
[SQL] NVARCHAR(4000)
)

WHILE NOT EXISTS (SELECT * FROM @SQL WHERE RowID = 1)
BEGIN
SELECT TOP 1@RowID = c.RowID,
@ID = c.RowID,
@Indent = c.Indent,
@TSQL = N'',
@EndSQL = N'',
@IsSelfJoin = c.IsSelfjoin,
@HasPk = c.HasPk
FROM@Constraints AS c
LEFT JOIN@SQL AS s ON s.RowID = c.RowID
WHEREs.RowID IS NULL
ORDER BYc.Indent DESC,
c.RowID DESC

WHILE @ID > 0
BEGIN
IF @Indent = 0
SELECT@RowSQL = N'DELETE t' + CAST(@RowID AS NVARCHAR(12)),
@RowSQL = @RowSQL + N' FROM ' + QUOTENAME(c.[Catalog]) + N'.' + QUOTENAME(c.[Schema]) + N'.' + QUOTENAME(c.[Table]) + N' AS t' + CAST(@ID AS NVARCHAR(12)),
@EndSQL = N' WHERE t' + CAST(@ID AS NVARCHAR(12)) + '.' + QUOTENAME(COALESCE(c.[Column], '%0')) + N' = ''%1''',
@IsSelfJoin = @IsSelfJoin | c.IsSelfJoin
FROM@Constraints AS c
WHEREc.RowID = @ID
ELSE
SELECT@RowSQL = N' INNER JOIN ' + QUOTENAME(c.[Catalog]) + N'.' + QUOTENAME(c.[Schema]) + N'.' + QUOTENAME(c.[Table]),
@RowSQL = @RowSQL + N' AS t' + CAST(@ID AS NVARCHAR(12)) + N' ON t' + CAST(@ID AS NVARCHAR(12)) + N'.' + QUOTENAME(c.[Column]),
@pkColumn = QUOTENAME(c.pkColumn),
@IsSelfJoin = @IsSelfJoin | c.IsSelfJoin
FROM@Constraints AS c
WHEREc.RowID = @ID

SELECT TOP 1@ID = c.RowID,
@Indent = c.Indent,
@RowSQL = @RowSQL + N' = t' + CAST(c.RowID AS NVARCHAR(12)) + N'.' + @pkColumn,
@IsSelfJoin = @IsSelfJoin | c.IsSelfJoin
FROM@Constraints AS c
WHEREc.RowID < @ID
AND c.Indent < @Indent
ORDER BYc.Indent DESC,
c.RowID DESC

IF @@ROWCOUNT = 0
SET@ID = 0

SET@TSQL = @RowSQL + @TSQL
END

INSERT@SQL
(
RowID,
IsSelfJoin,
HasPk,
[SQL]
)
VALUES(
@RowID,
@IsSelfJoin,
@HasPk,
@TSQL + @EndSQL
)

IF @IsSelfJoin = 1
BEGIN
DECLARE@Yak NVARCHAR(160),
@Catalog NVARCHAR(128),
@Column NVARCHAR(128)

SELECT@Yak = pkType + COALESCE('(' + CAST(pkSize AS NVARCHAR(12)) + ')', ''),
@Catalog = [Catalog],
@Schema = [Schema],
@Table = [Table],
@Column = [Column],
@Catalog = [Catalog],
@Table = [Table],
@pkColumn = pkColumn
FROM@Constraints
WHERERowID = @RowID

SET@RowSQL = 'DECLARE@Lvl INT
SET@Lvl = 0
DECLARE@Stage TABLE (RowID INT IDENTITY(0, 1), Lvl INT, RowKey ' + @Yak + ')
INSERT @Stage (Lvl, RowKey) '
+ REPLACE(@TSQL + @EndSQL, 'DELETE t' + CAST(@RowID AS NVARCHAR(12)) + '', 'SELECT 0, t' + CAST(@RowID AS NVARCHAR(12)) + '.' + QUOTENAME(@Column) + '')
+ ' WHILE @@ROWCOUNT > 0
BEGIN
SET@Lvl = @Lvl + 1

INSERT@Stage (Lvl, RowKey)
SELECT@Lvl,
t.' + QUOTENAME(@pkColumn) + '
FROM' + QUOTENAME(@Catalog) + '.' + QUOTENAME(@Schema) + '.' + QUOTENAME(@Table) + ' AS t
INNER JOIN@Stage AS s ON s.RowKey = t.' + QUOTENAME(@Column) + '
AND s.Lvl = @Lvl - 1
LEFT JOIN@Stage AS cr ON cr.RowKey = t.' + QUOTENAME(@pkColumn) + '
WHEREcr.RowKey IS NULL
END
SELECT ''DELETE FROM ' + QUOTENAME(@Catalog) + '.' + QUOTENAME(@Schema) + '.' + QUOTENAME(@Table) + ' WHERE ' + QUOTENAME(@pkColumn) + ' = '' + QUOTENAME(RowKey, '''''''')
FROM @Stage
WHERE RowID > 0
ORDER BY RowID DESC'

INSERT@Unwind
(
RowID,
[SQL]
)
VALUES(
@RowID,
@RowSQL
)
END
END

INSERT@Return
(
RowID,
IsSelfJoin,
HasPk,
[SQL]
)
SELECTs.ID,
s.IsSelfJoin,
s.HasPk,
CASE
WHEN u.RowID IS NULL THEN s.[SQL]
ELSE u.[SQL]
END
FROM@SQL AS s
LEFT JOIN@Unwind AS u ON u.RowID = s.RowID
ORDER BYs.ID,
u.StepID

RETURN
ENDE 12°55'05.25"
N 56°04'39.16"

View 16 Replies View Related

Need To Delete A Table Which Has A Reference To Another Table

Dec 12, 2007

Hi Friends...

In general we cannot delete a table if it refers another table. But in the process of backup and restore, we need to delete all the tables, so we have return an asp.net function...

Dim Datatable As String
Dim ds As New DataSet
ds = gDatabase.ExecuteQuery(" select Table_Name from Information_schema.Tables where Table_type='TABLE'")
If ds.Tables.Count > 0 Then
If ds.Tables(0).Rows.Count > 0 Then
Dim dr As DataRow
Dim da As SqlCeDataAdapter
Dim Cmd As String
For Each dr In ds.Tables(0).Rows
Datatable = dr.Item("Table_name")
Cmd = "Delete from [" & Datatable & "]"
gDatabase.ExecuteNonQuery(Cmd)
Next
End If
End If

we got an error like

"Msg 4712, Level 16, State 1, Line 1
Cannot truncate table 'Electricalworks' because it is being referenced by a FOREIGN KEY constraint.
"

how to override these errors, if we have to delete all the tables. We have about 200 tables.

View 7 Replies View Related

Cyclical Forwarding

Apr 17, 2008

I have been triyng to find an explanation for this error everywhere, but so far have been unsuccessful:

Cyclical forwarding detected for event 17806: Event source was 'SP-MINCL-WDB04' which matches the current forwarding server. The event was not forwarded.

Does anyone know what this means?



Thanks!

View 9 Replies View Related

The DELETE Statement Conflicted With The REFERENCE Constraint FK__aspnet_Me__UserI__15502E78.

Nov 22, 2007

 Hello,         I try to delete a user from the Membership table but I receive this error. "The DELETE statement conflicted with the REFERENCE constraint "FK__aspnet_Me__UserI__15502E78". The conflict occurred in database "E:INETPUBWEBSITE4APP_DATAASPNETDB.MDF", table "dbo.aspnet_Membership", column 'UserId'.The statement has been terminated."...<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">    <asp:GridView ID="GridView1" runat="server" AllowPaging="True" AutoGenerateColumns="False"        DataKeyNames="UserId" DataSourceID="SqlDataSource1" EmptyDataText="There are no data records to display.">        <Columns>            <asp:CommandField ShowDeleteButton="True" />            <asp:BoundField DataField="UserId" HeaderText="UserId" SortExpression="UserId" />            <asp:BoundField DataField="UserName" HeaderText="UserName" SortExpression="UserName" />            <asp:BoundField DataField="LastActivityDate" HeaderText="LastActivityDate" SortExpression="LastActivityDate" />        </Columns>    </asp:GridView>    <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ASPNETDBConnectionString1 %>"        DeleteCommand="DELETE FROM [aspnet_Users] WHERE [UserId] = @UserId" InsertCommand="INSERT INTO [aspnet_Users] ([ApplicationId], [UserId], [UserName], [LoweredUserName], [MobileAlias], [IsAnonymous], [LastActivityDate]) VALUES (@ApplicationId, @UserId, @UserName, @LoweredUserName, @MobileAlias, @IsAnonymous, @LastActivityDate)"        ProviderName="<%$ ConnectionStrings:ASPNETDBConnectionString2.ProviderName %>"        SelectCommand="SELECT [ApplicationId], [UserId], [UserName], [LoweredUserName], [MobileAlias], [IsAnonymous], [LastActivityDate] FROM [aspnet_Users]"        UpdateCommand="UPDATE [aspnet_Users] SET [ApplicationId] = @ApplicationId, [UserName] = @UserName, [LoweredUserName] = @LoweredUserName, [MobileAlias] = @MobileAlias, [IsAnonymous] = @IsAnonymous, [LastActivityDate] = @LastActivityDate WHERE [UserId] = @UserId">        <InsertParameters>            <asp:Parameter Name="ApplicationId" Type="Object" />            <asp:Parameter Name="UserId" Type="Object" />            <asp:Parameter Name="UserName" Type="String" />            <asp:Parameter Name="LoweredUserName" Type="String" />            <asp:Parameter Name="MobileAlias" Type="String" />            <asp:Parameter Name="IsAnonymous" Type="Boolean" />            <asp:Parameter Name="LastActivityDate" Type="DateTime" />        </InsertParameters>        <UpdateParameters>            <asp:Parameter Name="ApplicationId" Type="Object" />            <asp:Parameter Name="UserName" Type="String" />            <asp:Parameter Name="LoweredUserName" Type="String" />            <asp:Parameter Name="MobileAlias" Type="String" />            <asp:Parameter Name="IsAnonymous" Type="Boolean" />            <asp:Parameter Name="LastActivityDate" Type="DateTime" />            <asp:Parameter Name="UserId" Type="Object" />        </UpdateParameters>        <DeleteParameters>            <asp:Parameter Name="UserId" Type="Object" />        </DeleteParameters>    </asp:SqlDataSource></Content> ...  cheers,imperialx   

View 1 Replies View Related

Whaaat? No Cascading Cascades??

Jan 27, 2004

I may have misinterpreted the error I just got...but.. is it impossible in SQL Server to have a cascade delete FK constraint that leads to a table which has another cascade delete FK?? What's a workaround? Triggers?

View 5 Replies View Related

Getting An Error The DELETE Statement Conflicted With The REFERENCE Constraint FK_Detail_Header

May 14, 2008

Hello All, i have 2 files in excel which i am uploading them to a folder which is located in the root directory. then i am importing these two files into a sqldatabase. i needed some help in importing them and i got it from my previous post at http://forums.asp.net/t/1261155.aspx but now i have a problem. the import works perfectly first time but when i do it the second time i am getting an error on of the file (header). to explain clearly, what i am doing is , every time i upload a new file , i am deleting the data from the tables, so the new data can be inserted (  basically trying to achieve overwirting the existing data). now this technique works fine with the Detail table but not with the Header table. i think the reason is the header table has a primary key on OrderID and a relationship does exists between the Header and Detail. now how would i overcome this error. can some one please guide me. I really appreciate it.here is my code:  // connection for header file
protected OleDbCommand headExcelConnection() { // Connect to the Excel Spreadsheet
string headConnStr = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + Server.MapPath("~/imports/headerorder.xls") + ";" + "Extended Properties=Excel 8.0;"; // create your excel connection object using the connection string
OleDbConnection headXConn = new OleDbConnection(headConnStr); headXConn.Open(); // use a SQL Select command to retrieve the data from the Excel Spreadsheet // the "table name" is the name of the worksheet within the spreadsheet // in this case, the worksheet name is "Sheet1" and is expressed as: [Sheet1$]

OleDbCommand headCommand = new OleDbCommand("SELECT * FROM [Sheet1$]", headXConn); return headCommand; } // importing header information


protected void BtnImpHeader_Click(object sender, EventArgs e) { PanelUpload.Visible = false; PanelView.Visible = false; PanelImport.Visible = true; LabelImport.Text = ""; // reset to blank // Create a new Adapter
OleDbDataAdapter objDataAdapter = new OleDbDataAdapter(); // retrieve the Select command for the Spreadsheet
objDataAdapter.SelectCommand = headExcelConnection();

// Create a DataSet
DataSet objDataSet = new DataSet(); // Populate the DataSet with the spreadsheet worksheet data
objDataAdapter.Fill(objDataSet);

// deleting the exisitng table before copy
SqlConnection mycon = new SqlConnection(ConfigurationManager.ConnectionStrings["ImportexcelConnectionString"].ConnectionString); SqlCommand SqlCmd = null; mycon.Open(); SqlCmd = mycon.CreateCommand(); SqlCmd.CommandText = "DELETE FROM Header"; ---- showing error over on second time SqlCmd.ExecuteNonQuery(); mycon.Close(); // entering the newer header information

SqlConnection mysqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["ImportexcelConnectionString"].ConnectionString); mysqlcon.Open(); foreach (DataRow dr in objDataSet.Tables[0].Rows) { String sqlinsert = "insert into Header values(@param1,@param2,@param3,@param4,@param5,@param6,@param7,@param8,@param9,@param10,@param11,@param12,@param13,@param14,@param15,@param16,@param17,@param18,@param19,@param20,@param21,@param22,@param23,@param24,@param25,@param26,@param27,@param28,@param29,@param30,@param31,@param32)"; SqlCommand cmd = new SqlCommand(sqlinsert, mysqlcon); cmd.Parameters.AddWithValue("@param1", dr[0].ToString()); cmd.Parameters.AddWithValue("@param2", dr[1].ToString()); cmd.Parameters.AddWithValue("@param3", dr[2].ToString()); cmd.Parameters.AddWithValue("@param4", dr[3].ToString()); cmd.Parameters.AddWithValue("@param5", dr[4].ToString()); cmd.Parameters.AddWithValue("@param6", dr[5].ToString()); cmd.Parameters.AddWithValue("@param7", dr[6].ToString()); cmd.Parameters.AddWithValue("@param8", dr[7].ToString()); cmd.Parameters.AddWithValue("@param9", dr[8].ToString()); cmd.Parameters.AddWithValue("@param10", dr[9].ToString()); cmd.Parameters.AddWithValue("@param11", dr[10].ToString()); cmd.Parameters.AddWithValue("@param12", dr[11].ToString()); cmd.Parameters.AddWithValue("@param13", dr[12].ToString()); cmd.Parameters.AddWithValue("@param14", dr[13].ToString()); cmd.Parameters.AddWithValue("@param15", dr[14].ToString()); cmd.Parameters.AddWithValue("@param16", dr[15].ToString()); cmd.Parameters.AddWithValue("@param17", dr[16].ToString()); cmd.Parameters.AddWithValue("@param18", dr[17].ToString()); cmd.Parameters.AddWithValue("@param19", dr[18].ToString()); cmd.Parameters.AddWithValue("@param20", dr[19].ToString()); cmd.Parameters.AddWithValue("@param21", dr[20].ToString()); cmd.Parameters.AddWithValue("@param22", dr[21].ToString()); cmd.Parameters.AddWithValue("@param23", dr[22].ToString()); cmd.Parameters.AddWithValue("@param24", dr[23].ToString()); cmd.Parameters.AddWithValue("@param25", dr[24].ToString()); cmd.Parameters.AddWithValue("@param26", dr[25].ToString()); cmd.Parameters.AddWithValue("@param27", Convert.ToDecimal(dr[26].ToString())); cmd.Parameters.AddWithValue("@param28", Convert.ToDecimal(dr[27].ToString())); cmd.Parameters.AddWithValue("@param29", Convert.ToDecimal(dr[28].ToString())); cmd.Parameters.AddWithValue("@param30", Convert.ToDecimal(dr[29].ToString())); cmd.Parameters.AddWithValue("@param31", Convert.ToDecimal(dr[30].ToString())); cmd.Parameters.AddWithValue("@param32", dr[31].ToString()); cmd.ExecuteNonQuery(); // new SqlCommand (stmt, mysqlcon).ExecuteNonQuery();
LabelImport.Text = "Rows Inserted"; } mysqlcon.Close(); }// connection for detail file

protected OleDbCommand detExcelConnection() { // Connect to the Excel Spreadsheet
string detConnStr = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + Server.MapPath("~/imports/detailorder.xls") + ";" + "Extended Properties=Excel 8.0;"; // create your excel connection object using the connection string
OleDbConnection detXConn = new OleDbConnection(detConnStr); detXConn.Open(); // create your excel connection object using the connection string // use a SQL Select command to retrieve the data from the Excel Spreadsheet // the "table name" is the name of the worksheet within the spreadsheet // in this case, the worksheet name is "Sheet1" and is expressed as: [Sheet1$]
OleDbCommand detCommand = new OleDbCommand("SELECT * FROM [Sheet1$]", detXConn); return detCommand; }// importing detail information

protected void ButtonImport_Click(object sender, EventArgs e) { PanelUpload.Visible = false; PanelView.Visible = false; PanelImport.Visible = true; LabelImport.Text = ""; // reset to blank // Create a new Adapter
OleDbDataAdapter objDataAdapter = new OleDbDataAdapter(); // retrieve the Select command for the Spreadsheet
objDataAdapter.SelectCommand = detExcelConnection();

// Create a DataSet
DataSet objDataSet = new DataSet(); // Populate the DataSet with the spreadsheet worksheet data
objDataAdapter.Fill(objDataSet);

// deleting the exisitng table before copy
SqlConnection mycon = new SqlConnection(ConfigurationManager.ConnectionStrings["ImportexcelConnectionString"].ConnectionString); SqlCommand SqlCmd = null; mycon.Open(); SqlCmd = mycon.CreateCommand(); SqlCmd.CommandText = "DELETE FROM Detail"; SqlCmd.ExecuteNonQuery(); mycon.Close(); // entering newer detail information
SqlConnection mysqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["ImportexcelConnectionString"].ConnectionString); mysqlcon.Open(); foreach (DataRow dr1 in objDataSet.Tables[0].Rows) { String sqlinsert = "insert into Detail values(@param1,@param2,@param3,@param4,@param5,@param6,@param7,@param8,@param9,@param10,@param11,@param12,@param13)"; SqlCommand cmd = new SqlCommand(sqlinsert, mysqlcon); cmd.Parameters.AddWithValue("@param1", dr1[0].ToString()); cmd.Parameters.AddWithValue("@param2", dr1[1].ToString()); cmd.Parameters.AddWithValue("@param3", dr1[2].ToString()); cmd.Parameters.AddWithValue("@param4", dr1[3].ToString()); cmd.Parameters.AddWithValue("@param5", dr1[4].ToString()); cmd.Parameters.AddWithValue("@param6", dr1[5].ToString()); cmd.Parameters.AddWithValue("@param7", dr1[6].ToString()); cmd.Parameters.AddWithValue("@param8", Convert.ToDecimal(dr1[7].ToString())); cmd.Parameters.AddWithValue("@param9", Convert.ToDecimal(dr1[8].ToString())); cmd.Parameters.AddWithValue("@param10", dr1[9].ToString()); cmd.Parameters.AddWithValue("@param11", dr1[10].ToString()); cmd.Parameters.AddWithValue("@param12", dr1[11].ToString()); cmd.Parameters.AddWithValue("@param13", dr1[12].ToString()); cmd.ExecuteNonQuery(); LabelImport.Text = "Rows Inserted"; } mysqlcon.Close(); } the error is as follows:
Server Error in '/WebSite6' Application.


The DELETE statement conflicted with the REFERENCE constraint
"FK_Detail_Header". The conflict occurred in database "C:DOCUMENTS AND
SETTINGSMEMY DOCUMENTSVISUAL STUDIO
2005WEBSITESWEBSITE6APP_DATADATABASE.MDF", table "dbo.Detail", column
'OrderID'.The statement has been terminated. 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 DELETE statement conflicted with the
REFERENCE constraint "FK_Detail_Header". The conflict occurred in database
"C:DOCUMENTS AND SETTINGSMEMY DOCUMENTSVISUAL STUDIO
2005WEBSITESWEBSITE6APP_DATADATABASE.MDF", table "dbo.Detail", column
'OrderID'.The statement has been terminated.Source Error:




Line 176: SqlCmd = mycon.CreateCommand();Line 177: SqlCmd.CommandText = "DELETE FROM Header";Line 178: SqlCmd.ExecuteNonQuery();Line 179: mycon.Close();Line 180:  again i really appreciate.Thanks 

View 1 Replies View Related

How To Trap DELETE Statement Conflicted With COLUMN REFERENCE Constraint Error

Oct 26, 2004

Hi,

On my aspx Web page, I want to delete a member from database table 'tblMember', but if this MemberID is used as FK in another table, I want to display a user friendlier message like "You cannot delete this member, ....." I am using Try, Catch blocks in my Web Page.

Currently it display this message:
"DELETE statement conflicted with COLUMN REFERENCE constraint 'FK_..._....' The conflict occurred in database '...', table 'tblMembers', column 'MemberID'. The statement has been terminated. "

So how should I precisely trap this error? Does anybody know what Exception is it? or what error number in SQL server?


Thanks

View 2 Replies View Related

Soft Delete In Table, Why Merge Agent Report Hards Delete On Table ?

Feb 1, 2007

Hi seniors

there are two tables involve in replication let say table1 and replicated table is also rep.table1.

we are not deleting records physically in table1 so only a bit in table1 has true when u want to delete a record but the strange thing is that replication agaent report that this is hard delete operation on table1 so download and report hard delete operation and delete the record in replicated table which is very crucial.

plz let me know where am i wrong and how i put it into right way.

there is no triggers on published tables and noother trigger is created on published table.

regards

Ahmad Drshen

View 6 Replies View Related

Delete SQL Script As400 Throwing Object Reference Not Set To An Instance Of An Object

Apr 2, 2008

I am trying to send some data back to our as/400 from SQL server. Before I do so I need to delete entries from the table. I have an odbc connection set up and have used it sucessfully in a datareader compoenent but but when I try to use it for a delete SQL task it give me the followign error. what am I doing wrong? I even tried hardcoding in the system name/library name.

Here is my delete sql script
DELETE FROM DSSCNTL Where Companycode = 10


TITLE: SQL Task
------------------------------
Object reference not set to an instance of an object.
------------------------------
BUTTONS:
OK
------------------------------

View 7 Replies View Related

Copy And Delete Table With Foreign Key References(...,...) On Delete Cascade?

Oct 23, 2004

Hello:
Need some serious help with this one...

Background:
Am working on completing an ORM that can not only handles CRUD actions -- but that can also updates the structure of a table transparently when the class defs change. Reason for this is that I can't get the SQL scripts that would work for updating a software on SqlServer to be portable to other DBMS systems. Doing it by code, rather than SQL batch has a chance of making cross-platform, updateable, software...

Anyway, because it needs to be cross-DBMS capable, the constraints are that the system used must work for the lowest common denominator....ie, a 'recipe' of steps that will work on all DBMS's.

The Problem:
There might be simpler ways to do this with SqlServer (all ears :-) - just in case I can't make it cross platform right now) but, with simplistic DBMS's (SqlLite, etc) there is no way to ALTER table once formed: one has to COPY the Table to a new TMP name, adding a Column in the process, then delete the original, then rename the TMP to the original name.

This appears possible in SqlServer too --...as long as there are no CASCADE operations.
Truncate table doesn't seem to be the solution, nor drop, as they all seem to trigger a Cascade delete in the Foreign Table.

So -- please correct me if I am wrong here -- it appears that the operations would be
along the lines of:
a) Remove the Foreign Key references
b) Copy the table structure, and make a new temp table, adding the column
c) Copy the data over
d) Add the FK relations, that used to be in the first table, to the new table
e) Delete the original
f) Done?

The questions are:
a) How does one alter a table to REMOVE the Foreign Key References part, if it has no 'name'.
b) Anyone know of a good clean way to get, and save these constraints to reapply them to the new table. Hopefully with some cross platform ADO.NET solution? GetSchema etc appears to me to be very dbms dependant?
c) ANY and all tips on things I might run into later that I have not mentioned, are also greatly appreciated.

Thanks!
Sky

View 1 Replies View Related

Delete Syntax To Delete A Record From One Table If A Matching Value Isn't Found In Another

Nov 17, 2006

I'm trying to clean up a database design and I'm in a situation to where two tables need a FK but since it didn't exist before there are orphaned records.

Tables are:

Brokers and it's PK is BID

The 2nd table is Broker_Rates which also has a BID table.

I'm trying to figure out a t-sql statement that will parse through all the recrods in the Broker_Rates table and delete the record if there isn't a match for the BID record in the brokers table.

I know this isn't correct syntax but should hopefully clear up what I'm asking

DELETE FROM Broker_Rates

WHERE (Broker_Rates.BID <> Broker.BID)

Thanks

View 6 Replies View Related

DB Design :: Table Partitioning Using Reference Table Data Column

Oct 7, 2015

I have a requirement of table partitioning. we have 10 years of data on a table which is 30 billion up rows on 2005 server we are upgrading it to 2014. we have to keep 7 years of data. there is no keys on table or date column. since its a huge amount of data and many users its slow down the process speed. we are thinking to do partition on 7 years for Quarterly based. but as i said there is no date column on table we have to use reference table to get date. is there a way i can do the partitioning with out adding date column on table? also does partition will make query faster? 

I have think three ways to do it.
1. leave as it is.
2. 7 years partition on one server
3. 3 years partition on server1 and 4 years partition on server2 (for 4 years is snapshot better?)

View 3 Replies View Related

Multiple Columns In Table That Reference 1 Lookup Table

May 4, 2006

Hello,I have a query that I need help with.there are two tables...Product- ProductId- Property1- Property2- Property3PropertyType- PropertyTypeId- PropertyTypeThere many columns in (Product) that reverence 1 lookup table (PropertyType)In the table Product, the columns Property1, Property2, Property3 all contain a numerical value that references PropertyType.PropertyTypeIdHow do I select a Product so I get all rows from Product and also the PropertyType that corresponds to the Product.Property1, Product.Property2, and Product.Property3ProductId  |  Property1  |  Property2  |  Property3  | PropertyType1  | PropertyType2  |  PropertyType3 PropertyType(1) = PropertyType for Property1PropertyType(2) = PropertyType for Property2PropertyType(3) = PropertyType for Property3I hope this makes sence.Thanks in advance.

View 3 Replies View Related

Allow Single Row Delete From A Table But Not Bulk Delete

Sep 16, 2013

The requirement is: I should allow single row delete from a table but not bulk delete. An audit table should get updated if there is any single delete or single update. So I wrote the triggers as follows: for single and bulk delete

ALTER TRIGGER [dbo].[TRG_Delete_Bulk_tbl_attendance]
ON [dbo].[tbl_attendance]
AFTER DELETE
AS

[code]...

When I try to run the website, the database error I am getting is:Transaction count after EXECUTE indicates that a COMMIT or ROLLBACK TRANSACTION statement is missing. Previous count = 0, current count = 1.

View 3 Replies View Related

POINTING TO SERVER

Sep 8, 2006

datasource jdbc in UAT Server has been modified to use ms sql driver & point to the UAT sql server .
I Really not understand what is exactly meaning of modified and pointing (but i know theory any application need to get access that should point to server )or otherwords we say application is pointig to database, to point one server to other what we do get that . could any one give detail idea really i am missing some basics drivers and application pointing . may i know any book or link to study more about this kind of sutuation

View 1 Replies View Related

Help With Pointing To An Image!

Mar 29, 2006

I am new to SQL and I am trying to have a column in my table that points to images I have stored in a directory on my system. I cannot seem to get it to work correctly and I am wondering if someone might be able to help. I want to use this image for each record with the other information on my windows form but I cannot seem to get the file pointer right. Any help would be appreciated. Thanks.

View 4 Replies View Related

Foreign Key Pointing To Two Tables. Is This Possible?

Jan 4, 2008

Hi guys, i have a little question, i hope you can back me up please.

I have this tables:


Code:

TV
IdTV - autoincremental int, Primary key
IdCamera - int, foreign key
DeviceType int



Code:


DayLightCamera
IdDayLightCamera - autoincremental int, Primary key
DayLightCameraName - varchar(30)




Code:

InfraredCamera
IdInfraredCamera - autoincremental int, Primary key
InfraredCameraName - varchar(30)




now, when in insert a row in "TV" the foreign key "IdCamera" will relate to a row in either "InfraredCamera" or in "DaylightCamera" depending on the "DeviceType" value.

in other words, if i insert a row with DeviceType=0, then IdCamera will have to point to a row in the "InfraredCamera" table. And if i insert a row with DeviceType=1, then IdCamera will have to point to a row in the "DaylightCamera" table.

so, my question is, how can i make the constraints relationship so that the idCamera relates to a row in DaylightCamera or in InfraredCamera depending on the value of DeviceType? should i make 2 foreign keys with allow null? or should i place both relationships to the same foreign key? im not sure what to do


Thanks guys for your help. it is really appreciated!

View 3 Replies View Related

Views Pointing To Sybase

Dec 13, 2004

Hi all,

I am new to this so take it slow. I want to build views on SQL Server that points to a db on Sybase. Is this possible? Pro and cons?

View 1 Replies View Related

Re-pointing Stored Procedures

Jan 19, 2005

How do I "point" a set of stored procedures to operate on different linked servers?

In other words, I have the following linked servers:

DatabaseA
DatabaseB
DatabaseC
DatabaseD
...and in the future, there may be added additional linked servers.

All the linked servers have identical schema, but they contain unique data--each linked server represents a company.

I have a database which will contain stored procedures which I will want to operate against these linked servers. How can I "redirect" my stored procedures to operate against a chosen linked server?

If these were not linked servers, but SQL Server databases, I'd be able to replicate the same stored procedures in each database. Then, when I called a stored procedure, it would act against the data in that database. But these aren't SQL Server databases, so that idea is out.

Unfortunately, the USE command cannot be used within a stored procedure, and even if you could, I can't get it to respond to a database name given as a variable. That idea is out.

The only alternative I have left is to use the string catenation facility of the EXECUTE command. Unfortunately, with 100s of complex queries, setting that up is going to be a nightmare.

Does anyone have any ideas?

View 7 Replies View Related

Pointing My New .ADP File To My New SQL Server DB

Oct 25, 2005

I hope this question belongs in this forum.

I have a .ADP application (access 2000 front end, SQL Server 2000 back end)
I basically want to create a new .ADP file and point it to a different SQL Server 2000 Database.

I've copied the current SQL Server DB and recreated it. Same for the .ADP file, but it is currently pointing to the old Db, where do I go to have it point to the new SQL Server DB?

Thanks

View 2 Replies View Related

SQL 2012 :: DTSX Giving Errors - Object Reference Not Set To Instance Reference

Sep 10, 2014

I am using vs 2010 to write my dtsx import scripts.I use a script component as a source to create a flat file destination file.Everything have been working fine,but then my development machine crashed and we have to install everything again.Now when i use the execute package utility to test my scripts i get the following error:

Error system.NullReferenceException: Object refrence not set to an instance reference.

In PreExecute section
TextReader = new system.io.streamreader(" file name")
In the CreateNewOutputRows:
dim nextLine as string
nextLine = textReader.ReadLine

[code]...

is there something which i did not install or what can be the error?

View 0 Replies View Related

UDT - Get Reference To Table

Jan 12, 2007

Hello everyone !

Given a UDT, is there any way to get a reference to the table where the specific instance is running ?

IE: Let's suppose we have defined a UDT named UDTPoint; now we define two tables: ATable & BTable, wich both have one column that is defined as UDTPoint.

When an insert/update/delete operation on ATable or BTable occurs, the UDTPoint class needs to verify in which context it is running (ATable or BTable) before doing operations on data.

Is there any way to achieve that ?

Thanks



Giovanni

View 1 Replies View Related

Pointing Server Name / Instance Name At AG Listener?

Jul 3, 2015

I've started working at an organization that has a sql 2005 cluster with a named instances on it, lets call it Instance1. What they done is to create a dns alias for servername that is the same as the instance name, so when you connect to the sql server you connect "Instance1Instance1".

We want to move to SQL 2014 cluster with AlwaysOn Availability Groups doing the HA/DR, the question is if I create a listener name called "Listener1" is there a way to using DNS or anything else to point "Instance1Instance1" to "Listener1"

View 1 Replies View Related

Best Way To Reference A Table With A Composite Key?

Nov 24, 2006

The table above is my users table. It allows for a user to be at multiple sites or multiple locations within a single site or multiple sites. Would it be wise to use a auto incrementing primary key instead of the 3 column composite key? The reason I ask is because if I am referencing this SU table (which I will be a lot), a lot more data would be replicated to the tables which have the foreign key to this table, right? But if I used a single incrementing column as the primary key, only a small integer would be used as the foreign key, saving space?Does this make sense?   

View 1 Replies View Related

How To Reference A Table In A Different Database?

Apr 5, 2006

I have 2 databases in sql server. let us say database1 = db1 and database2 = db2
Now both the databases have a same table called table1 with the same fields.

IF data in db1.table1 is updated then data in db2.table2 should be updated automatically.

There are many ways we can do this. one way is to create a INSERT trigger on db1.table1.

But i would like to avoid trigger
Is there something in SQL server where I can just link table1 of db1 to db2 and delete the table1 in db2. That means db2 is using the same table that of db1.

Thanks

View 2 Replies View Related

Command To Reference Another Table

Mar 27, 2006

Hi all,

I am new to this site and I hope anyone out there can help me. I was tasked to change the constraints of my existing table. Lets call it table1. This table has an attribute that needs to take the value of another attribute of another table ( let's call it tables2) and that attribute must satisfy a certain expression ( I suppose I can isolate it by using the select statement ).

Anyone know how to get this done.

Please advice.

Thanks and appreciated.

View 4 Replies View Related

Table Reference To Another DB Instance?

Apr 13, 2008

Hello everyone,

this would be my first posting.

I would like to know if it's possible in MS SQL to redirect a table into another DB instance? I have no access into the source code and I have been wondering if it is possible to make a redirection/hard link in MS SQL side.

I would have a table in my base DB and when a query is made into this table, the MS SQL would redirect it to another DB or table. Is this possible in MS SQL ? Something along the lines of a hard-link in linux.
Thank you very much.

View 3 Replies View Related

Using The 'Like' Statement To Reference Another Table

Nov 4, 2007

Hi

Is it possible to to create a 'Like' statement that refernces all the data in a column from another table?
Thanks

View 1 Replies View Related

SQL Server Admin 2014 :: DNS Pointing To A Listener

Jun 25, 2014

In our environment applications are using a DNS name which points to the physical server ip address. Now we are planning to move to 2014. We are planning to have servers in different subnets so we will be having two ip adresses for listener. How we can point the DNS to the listener ips? If failover happens can the DNS point to the exact ip address of the listener where it's primary node?

View 1 Replies View Related

WMI Event Watcher - Pointing Directly To A Machine Name

Nov 27, 2006

Hi,

I am using a WMI Event Watcher task to watch for files dropped into a directory over a network drive.

It seems to work fine when it is pointed to a physical drive name, but not when I use a machine name.

I.e.

This works -
SELECT * FROM __InstanceCreationEvent WITHIN 10 WHERE TargetInstance ISA "CIM_DirectoryContainsFile" and TargetInstance.GroupComponent= "Win32_Directory.Name="C:\\temp\\folder1\\folder2\folder3""

This fails -
SELECT * FROM __InstanceCreationEvent WITHIN 10 WHERE TargetInstance ISA "CIM_DirectoryContainsFile" and TargetInstance.GroupComponent= "Win32_Directory.Name=\\\\machineName\\folder1\\folder2\\folder3"

The failing code does not throw any errors (i.e. SSIS thinks the WQL syntax is correct), but it doesn't pick up any dropped files.

Am I doing something incorrect with the syntax, or must I use a physically mapped drive letter?

Thanks
H

View 11 Replies View Related







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