Dynamic Sql: Truncate Table: Trap @@ERROR

Jul 23, 2005

Greeting All, I have a stored proc that dynamically truncates all the
tables in my databases. I use a cursor and some dynamic sql for this:


......
create cursor
Loop through sysobjects and get all table names in my database.

....
exec ('truncate table ' + @TableName)

Now, I want to be able to determine if an error occurred or not nad log
that error to a table in another database.

However, when I try to trap the value of @@ERROR after the
exec ('truncate table ' + @TableName) when an actual error occurs it
fails. My error was synthetically created by placing a foreign key on
the table which precludes the option of truncation:

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

The actual relevant code snippet is:

BEGIN
BEGIN
SET @v_RowCount = (
SELECT rowcnt
FROM sysindexes
WHERE id = (
SELECT id
FROM sysobjects
WHERE name = @v_Name
)
AND indid IN (0,1)
)
EXEC('truncate table ' + @v_Name)
-- If there was an error truncating the current table.
-- Write the event to the MessageLog table.
IF (@@ERROR <> 0)
BEGIN
SET @v_OutputMessage = ('There was an error ' + @v_name)
INSERT INTO MessageLog (message) values (@v_outputmessage)
RETURN (-1)
END



Like I was saying, when the error is generated because of the foreign
key the variable @@error is never set to 4712, in fact if I were to put
a "select @@ERRROR" directly below the "exec('tru..')" statement it
would never be executed. The only thing that would show up in
Enterprise Manager would be the:

Server: Msg 4712, Level 16, State 1, Line 1
Cannot truncate table 'MyTable' because it is being referenced by a
FOREIGN KEY constraint.
Any ideas as to what is going on here?

Thanks, TFD.

View 3 Replies


ADVERTISEMENT

Error While Truncate Table In Sql 2005

May 15, 2008

Hi,
I am facing some issue in SQL 2005. There are five tables and tables having foreign check constrainst to child and parent relationship.

Now the issues is that i am able to delete the table in order wise and i am not able to truncate the all the tables in the same order.

Msg 4712, Level 16, State 1, Line 1
Cannot truncate table 'dbo.Tb_to_Markets' because it is being referenced by a FOREIGN KEY constraint.
But the same table i am delete it.

what can be cause for this error.

Thanks,

View 2 Replies View Related

Trap Sqladatasource Error

Mar 26, 2008

Hi,
I have a page with only a Datasource and a Gridview that allows Delete.  In the database there is a referential integrity (RI) to the one of the columns.  When a user tries to delete the row, the RI stops the delete and throws an error message the way it should.  But it also create a hard failure on the page.
How do I trap the error message so I can display a message "Referential Integrity denied deletion of this record." rather than having it fail ?

View 4 Replies View Related

Error Codes And How To Trap Certain Ones

Apr 10, 2006

I have a system using asp pages & ADO & SQL Server 2000, which processes files, builds a SQL insert statement from the file content and then executes it.

If the insert SQL fails, I need to know whether there was something wrong with the insert SQL, or something wrong with the database (e.g. SQL Server times out), and handle those differently,

Questions
=======
1. Is there an easy way to do this without checking against a list of error codes?
2. Can anyone point me to a list of errorcodes? Can't find this anywhere

thank you

View 6 Replies View Related

ODBC Call Failed, How To Trap Error?

Feb 9, 2006

Hi All,

I have a database with primary and Unique key contraints on SQL Server 2000. I'm front ending it with Access 2k.

I want to trap the error when the Unique key constraint is hit, but i can't capture the error number. All attempts return error 0.

The error i get is
[Microsoft][ODBC SQL Server Driver][SQL Server]Violation of UNIQUE KEY constraint 'IX_lut_Referral_Source'. Cannot insert duplicate key in object 'lut_Referral_Source'. (#2627)[Microsoft][ODBC SQL Server Driver][SQL Server]The statement has been terminated. (#3621)

I've tried the soultion given here http://support.microsoft.com/kb/q185384 but now get a Type mismatch error on errStored

SaveRecODBCErr:
' The function failed because of an ODBC error.
' Below are a list of some of the known error numbers.
' If you are not receiving an error in this list,
' add that error to the Select Case statement.
For Each errStored In DBEngine.Errors

Thanks for your help

View 1 Replies View Related

I'm Sure This Is An Easy One...Error Trap To Skip Over A Bad Object.

Mar 30, 2006

Hello, I have the following code to iterate through each view in a SQLServer and call the "sp_refreshview" command against it. It worksgreat until it finds a view that is damaged, or otherwise cannot berefreshed. Then the whole routine stops working.Can someone please help me re-write this code so that any views thatfail the "sp_refreshview" command get skipped. I'm sure it's just amatter of putting some basic error trapping into the loop, but I've hada few goes at it and failed.Many thanks.DECLARE @DatabaseObject varchar(255)DECLARE ObjectCursor CURSORFOR SELECT table_name FROM information_schema.tables WHERE table_type ='view'OPEN ObjectCursorFETCH NEXT FROM ObjectCursor INTO @DatabaseObjectWHILE @@FETCH_STATUS = 0BEGINEXEC sp_refreshview @DatabaseObjectPrint @DatabaseObject + ' was successfully refreshed.'FETCH NEXT FROM ObjectCursor INTO @DatabaseObjectENDCLOSE ObjectCursorDEALLOCATE ObjectCursorGO

View 5 Replies View Related

How To Handle This Linked Server Error Trap In SQL2K?

Jul 23, 2005

Below is the script. The problem is when I simulated the Oracle linkdrop, my SQL2K never have to a chance to head to the GOTO section as itdies with this error msg and exit. Any idea on a workround? Thanks.Server: Msg 7399, Level 16, State 1, Procedure USP_Link_Check, Line 8OLE DB provider 'MSDAORA' reported an error.[OLE/DB provider returned message: ORA-12154: TNS:could not resolveservice name]OLE DB error trace [OLE/DB Provider 'MSDAORA' IDBInitialize::Initializereturned 0x80004005: ].----------------------------------------------ALTER PROCEDURE [USP_Link_Check] ASDECLARE @myERROR int -- Local @@ERROR, @myRowCount int -- Local @@ROWCOUNT--- Verify network connectionsselect *from openquery(OraLink,'select count(*) from Oracle.table')IF @myERROR != 0 GOTO HANDLE_ERRORHANDLE_ERROR:Print ' Error in Oracle Link'RETURN @myERROR---------------------------------------------

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

Cannot Truncate Table 'Database.dbo.Table' Because It Is Being Referenced By A FOREIGN KEY Constraint..

Aug 23, 2006

Here is my issue I am new to 2005 sql server, and am trying to take my old data which is exported to a txt file and import it to tables in sql. The older database is non relational, and I had made several exports for the way I want to build my tables. I built my packages fine and everything is working until I start building relationships. I remove my foreign key and the table with the primary key will get updated for the package again. I need to update the data daily into sql, and once in it will only be update from the package until the database is moved over.

It will run and update with a primary key until I add a foreign key to another database.

Here is my error when running the package when table 2 has a foreign key.

[Execute SQL Task] Error: Executing the query "TRUNCATE TABLE [consumer].[dbo].[Client] " failed with the following error: "Cannot truncate table 'consumer.dbo.Client' because it is being referenced by a FOREIGN KEY constraint.". Possible failure reasons: Problems with the query, "ResultSet" property not set correctly, parameters not set correctly, or connection not established correctly.

View 3 Replies View Related

Truncate Table

Jul 4, 2007

i did a Stored Procedure to truncate a table. it contains lots of crap from testing the site. just a simple 1 ALTER PROCEDURE dbo.TruncateUploads

AS
TRUNCATE TABLE Uploads but it says "Cannot truncate table 'Uploads' because it is being referenced by a FOREIGN KEY constraint." then i make NULL all foreign keys and try still cannot. then i did it manually deleting all records then can! but why can't i truncate it? isn't it the same as removing all values plus having the primary keys to start from 0? 

View 5 Replies View Related

How Can I TRUNCATE My Table?

Oct 27, 2007

How can i TRUNCATE my table (removes rows that were produced at testing), so that in the actual running the automated IDNumber for my table start with 1.

View 6 Replies View Related

Truncate Table

Nov 1, 2000

hi, I have two tables members table and orders table.
I have 2 records in members table and zero records in order table.
When I try to truncate members table I get an error message.
cannot truncate table members,because it is being referenced by a FOREIGN KEY constraint.

this what blows my head, There is no records in orders table. so why would the constraint enforced when there is no data in the order table. I created same table in access and I was able to delete a member from the members table. any comments.

thanks
Ahmed

View 4 Replies View Related

Truncate Table

Feb 1, 2005

I have several very large tables and sometimes I need to clean them.
It's known that TRUNCATE TABLE works much faster than DELETE, but impossible to use TRUNCATE TABLE on a table referenced by a FOREIGN KEY constraint... Is it possible temporary disable (not delete) constraints and after complition of TRUNCATE enable them ?

View 14 Replies View Related

TRUNCATE Table

Feb 10, 2005

Hi,

(From Bol)
"You Cannot Use Truncate Table On A Table Referenced By A Foreign Key
Constraint;"

1) States
Statecode TinyintPrimary Key
Statename Varchar(25)

2) Rivers
RivercodeSmallint Primary Key
RivernameVarchar(40)

3) Riverinstates
StatecodeTinyint,
RivercodeSmallint,
Constraint Pkriverinstates Primary Key(Statecode,Rivercode),
Constraint Fkriverinstates
Foreign Key (Statecode) References States(Statecode),
Foreign Key (Rivercode) References Rivers(Rivercode)

after removing all rows from RiverInStates Table using TRUNCATE and the command completed successfully.

when i tried to remove all rows from Rivers table , i got the following error.

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

i thought the error may be due to the "Fkriverinstates" FOREIGN KEY CONSTRAINT. so i DROPped the constraint with
ALTER TABLE RiverinStates DROP CONSTRAINT Fkriverinstates

even after DROPping the constraint, im getting the same error
can any one point out where the problem is?

thanks in advance

View 1 Replies View Related

Truncate Table

May 18, 2004

what is the best way to truncate/delete records from a table at a certain time of the day...... i'm sure this is a simple ?, but i'm still learning sql.


thanks,
eddie

View 4 Replies View Related

Truncate All Table's From A Db

Jan 18, 2007

any idea why this is not wroking ?
------------------------------
declare
@TableName varchar

DECLARE
EmptyTables CURSOR FOR

Select Table_Name From Information_Schema.Tables
Where Table_Type = 'Base Table' Order By Table_Type

open EmptyTables

FETCH NEXT FROM
EmptyTables
into
@TableName


WHILE @@FETCH_STATUS = 0
BEGIN
truncate table @TableName

FETCH NEXT FROM
EmptyTables
into
@TableName

END

close EmptyTables
deallocate EmptyTables

View 11 Replies View Related

Truncate Table

Nov 16, 2006



I have a database of 25 GB. I truncated a table which holds around 5 GB of data.

Even after truncation, I see my database size as 25 GB...

Should I run a shrink database after the truncation?

Thanks

Santhosh

View 3 Replies View Related

String Truncate Error

Jun 1, 2006

Yesterday my program was inserting and loading data in the database just fine, now when i try to do a myriad of things(make a paramatizsed search ad a favorites option) when ever i add data to the database i get a string trucate exception, basically its telling me the data im uploading is too large, problem is the feilds in the databse can take it.Its telling me the column im updating to has a string limit of 255 , but in reality the column its updating to has 2000 chracters available. Could some one please tell me how to fix this, it is quite urgent.

View 15 Replies View Related

Truncate Table Permission

Jul 16, 2001

I have somme users who need to truncate some tables owned by DBO. I know that only table owner or DBO can execute TRUNCATE TABLE but I don't want grant DBO permission to those users. Do you have any suggestion ? Thanks a lot.

View 4 Replies View Related

Truncate Table -- Log Backups

Jul 23, 2001

If I have a truncate table statement in a stored proc, will my log backups be compromised due to the nonlogged operations. If so, what are my alternatives in case that I need to restore? Differential backups?

View 1 Replies View Related

I Am Able To Rollback TRUNCATE TABLE ????

Apr 13, 2000

I am doing the following-

begin transaction
truncate table Acounts
select * from Accounts
rollback
select * from Accounts

The first select is returning 0 rows as expected. But after doing the rollback I expected to yet see 0 rows as truncate is not logged so cannot be rolled back. But to my suprise I see that there are rows.

So the rollback is rolling back the truncate table statement. Can someone please explain this????

View 4 Replies View Related

Truncate Table Permission

Mar 17, 2000

I know that only the owner of a table can truncate it.
I want a user to run a procedure that truncates a table. Both the procedure and the table are owned by dbo, however the system says that the user can't truncate the tables because she doesn't have permission. The user has dataread and datawrite global permissions, and I do not want to give her dbo perimssions.
Is there a solution to this?

View 1 Replies View Related

Possible TRUNCATE / BCP Into A Table In One TRANSACTION?

Aug 12, 1998

Hi all,

Is it possible to TRUNCATE a table and BCP data into the same table in one
TRANSACTION?
My problem is that I want to refresh(delete and via BCP append new data) a
table without disturbing running applications. Can I run BCP from a
SQL-script or a stored procedure?

Thank`s
Jonas Dahlqvist
Alfa Laval Automation AB

View 1 Replies View Related

Truncate Table Permissions

Mar 22, 2006

Does anybody know of a way to allow non-administrators to execute the truncate table statement?

I have developers that from time to time need to move data between their databases usinge the DTS wizard. Most of their tables have identity columns and in order retain the identity seed, they need to click on the option to enable identity insert. This option isn't available to non administrators.

View 4 Replies View Related

ErrorMessage &#34;Cannot TRUNCATE TABLE...&#34; ???

Jul 2, 2002

Error Message "Cannot TRUNCATE TABLE 'HR.dbo.Employee' ".

All of a sudden (!) I began to get this error whle attempting to run a multi-step job: This is during a very simple T-SQL statement.

Executed as user: EPRODSQLAdmin. Cannot TRUNCATE TABLE 'HR.dbo.Employee' because it is being referenced by object 'v_apps_Employee'. [SQLSTATE 42000] (Error 3729). The step failed.


Tables are being referenced by views all the time... Why would I begin to get this message?

The only thing I can think of is that I had just made my first "indexed view" ever, and it is in this database. Could that be related to the new error message?

View 1 Replies View Related

Use Truncate Command On A Table

Jun 3, 2008

hi
Can We Use Truncate Command on a table which is Refernced by Foreign Key?

View 5 Replies View Related

Replication With Truncate Table

Mar 13, 2007

HI,

I am trying to find a replication solution. It does not have to be real-time, but snapshot will not work since the database is too big. I was trying to configure Transactional replication. The replication itself worked good, but the Truncate table is not allowed in the transactional replication and merge replication. We have to use "Truncate table" in another processes during replication. Is there any other option or third party application I can use to do the replication with truncate table working. I tried Replication Exec, but it does not support 64bit system, which we have.

View 11 Replies View Related

Log Invalidated After Truncate Table

Nov 23, 2005

Hi group,In one of the books 'Gurus Guide to Transact SQL' i found this info:------------------------------------------------------------TRUNCATE TABLE empties a table without logging row deletions in thetransaction log. It can't be used withtables referenced by FOREIGN KEY constraints, and it invalidates thetransaction log for the entire database.Once the transaction log has been invalidated, it can't be backed upuntil the next full database backup.------------------------------------------------------------Does it mean that the log backup taken after table truncation is aninvalid backup?Help me! i'm lost....Thanks in advanceRonin*** Sent via Developersdex http://www.developersdex.com ***

View 5 Replies View Related

Truncate Table If Exists

Jan 26, 2006

Hi,I am trying to create a script that deletes transaction tables and leavesmaster data like customer, vendors, inventory items, etc. How can I useTRUNCATE TABLE with an Exists? My problem is I have 200+ tables, if Isimply use a list like:truncate table01truncate table02truncate table03....I get errors if the table does not exist and have to manually run thetruncate statements. Some tables may not exist if that part of the app isnever used. I'm trying to make a list of all tables that could existwithout it erroring out 50+ times.Thanks in advance.

View 2 Replies View Related

TRUNCATE TABLE @table_name

Nov 26, 2007

I have a cursor looping through a list of tables that I want totruncate and then do a bulk insert into, Is this possible in SQLServer 2000 or do script each table individually.Cheers,Adam

View 2 Replies View Related

What Resources Does Truncate Table Use

Jul 20, 2005

Hi,We have a heavily used production server and a table which logs everyhit on a web site. This table has grown large over time and we want toclear it down as efficiently as possible. We would like to issue atruncate table statement, but with millions of rows we are a bit waryof how this will affect server performance. The alternative is todelete is stages using rowcount but of course this will generate alarge amount of logging.Can anyone confirm whether issuing a truncate table will have anyaffect on performance - i.e. does it just clear a header block ordooes it have to do more?CheersMartin

View 3 Replies View Related

Truncate Table Problem

Jun 1, 2007

Hi ,



I truncate and Delete the table. What is the differnce between following :



Trunacate table employee_master

delete from employee_master



I heared that After delete records from table through

"delete from employee_master"

data can be rollback using log file,But How ?



Waiting for response............



Regards



Nikhil Chaturvedi

View 4 Replies View Related

Truncate The Destination Table

Jun 27, 2007

Hi,
I need to truncate the Destination table every time before the data is loaded.
I had checked out in OLE DB Destination properties but couldn€™t find any information on truncate table.

EXP:
In INFORMATICA we have a properties setting for truncating the table every time the data get loaded.
I€™m looking for this option in SSIS can any one guide me on this.
Thank you,

View 6 Replies View Related







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