Deleting Dups

Jul 3, 2002

I need to delete duplicate records from a SQL table where only the key field is not a duplicate. I'm not having any luck with my script. Does anyone have a scrip that might work? Thanks

View 2 Replies


ADVERTISEMENT

Deleting Dups And Keeping Only 1 Row In A Batch

Sep 20, 2006

I have asked this question before and got some great answers, I just wanted to ask this again. I can detect dups easily, is there a way to get a total number of all dups so that I can delete a certain number at a time, then check the total again for verification that that specific number of dups are gone? I'm still using 2000. If I delete dups, won't it delete the 1 row I want to keep? And I do have a unique identity column.

thx,

Kat

View 3 Replies View Related

Dealing With Dups And A Lot More!

Mar 14, 2008

Ok, I have a table with about 47000 records in it. I have the following query for that table:Select ReportType =
Case
When ReportType = 1 Then 'Uniquery Report'
When ReportType = 2 Then 'SABRE Report'
When ReportType = 3 Then 'Menu Report'
Else Null
End,
ReportNameTo_,
Frequency.Frequency as Frequency,
ReportDate,
ReportDescription
From Report
Inner Join Frequency on ( Report.ReportFrequency = Frequency.FID )
Where ( Active = 1 )
And ReportDate = ( Select Max ( ReportDate ) From Report Where ( Active = 1 ) )
And ReportID = ( Select Max ( ReportID ) From Report Where ( Active = 1 ) )  
The idea is that i need to get only the last report based off of unique reportname. I added a computer column to the table to give me the ReportNameTo_, since my deliminator is the _. Now my issue is that I have 1 records showing (the last record added to the table), which is right for the query that is written, but wrong for what I want. I need to only return the last record for each unique ReportNameTo_. So as an example, my table has the following ID, ReportNameTo_, Date fields the data looks something like this:
1, 123_, 1/1/20082, 123_, 1/1/20083, 124_, 1/1/20084, 124_, 1/1/20085, 125_, 1/1/20086, 125_, 1/1/20087, 126_, 1/1/20088, 126_, 1/1/2008
I only want to return the following:
2, 123_, 1/1/20084, 124_, 1/1/20086, 125_, 1/1/20088, 126_, 1/1/2008
Hope someone out there can let me know how to do this... I am almost there, just not all the way.

View 2 Replies View Related

Select One Recort From Dups

Oct 27, 2003

Hi all,

I have a table with multiple rows for the same member. For example:

Member1:

Id First_name Last_name
11111 John Joe
11111 John Joe
11111 John Joe
11111 Linda smith

Member2

Id First_name Last_name
22222 Jackie Smith
22222 Jackie Smith
22222 John Smith
22222 Aron Smith

I need to eliminate dups and
my result table should have two rows only:

Id First_name Last_name

11111 John Joe
22222 Jackie Smith

How am I going to do this?? Any ideas...
please.

Thanks,

View 4 Replies View Related

Detect And Or Delete Dups

Oct 30, 2002

Hassle free locating / reporting or deletion of duplicate rows in a SQL table based on the uniqueness of a column or columns that the user provides with a few nifty hands off features. Keywords: delete unique column record records

(This code may also be viewed at http://www.planet-source-code.com/vb/scripts/ShowCode.asp?txtCodeId=576&lngWId=5


/*Description: UTILITY - Locate in MASTER


Syntax: EXEC sp_RemoveDups TableName, DupQualifierFieldNameList, DeleteDups, UniqueColName, CreateIdentColIfNeeded, StoredProcedureResult
Only the first two arguments are required
For HELP, enter the stored procedures name without any arguments or see the PRINT statements below
NO DELETION WILL OCCUR by default - only duplicate recordset returned. To delete records, pass in a 0 for the DeleteDups argument.

Example: EXEC sp_RemoveDups 'MyTable','LastName,FirstName,HomePhone'

Purpose: Allow removal of duplicate rows where
1. We define what fields qualify the duplicate
2. We select the unique rowid or it is detected automatically else no action takes place

Method:Delete by RowID all duplicate rows except the highest RowID (in alpha-sort sequence)
of each group of duplicates.

DATEBYCHANGE
09-23-2002FrankOriginal v1.0
09-23-2002FrankChanged the name from sp_RemoveDupsByRowID to sp_RemoveDups
10-8-2002Sean P. O. MacCath-MoranMade @UniqueColName optional
Added logic to auto-detect RowGUID and Identity columns
Added logic to check for unique value column if no RowGUID or Identity column exists
Added logic to create a temporary ID field as a last resort if no unique column could be located
Added HELP

*/

CREATE PROCEDURE sp_RemoveDups
@TableName as varchar(50) = NULL,
@DupQualifierFieldNameList as varchar(200) = NULL,
@DeleteDups as bit = NULL,
@UniqueColName as varchar(50) = NULL,
@CreateIdentColIfNeeded as bit = NULL,
@StoredProcedureResult int = NULL OUTPUT

AS
SET NOCOUNT ON

DECLARE @SQL nvarchar(2000)
DECLARE @SQL_DetermineUniqueTemplate nvarchar(2000)
DECLARE @TempIdentColName varchar(20)
DECLARE @HostName varchar(50)
DECLARE @ActionText varchar(10)

DECLARE @SUM int
DECLARE @COUNT int
DECLARE @NextColumn varchar(50)


/*==================================================================================*/
/*========================VARIABLE INITIALIZATION AND SETUP========================*/
/*=================================================================================*/
/*If no unique column is located then a temporary Identity column will be created useing the name specified in this TempIdentColName string*/
SET @TempIdentColName = 'TempIdentityColXY123'

SET @SQL_DetermineUniqueTemplate = 'SELECT @COUNT = COUNT(Count), @SUM = sum(Count) from '
SET @SQL_DetermineUniqueTemplate = @SQL_DetermineUniqueTemplate + CHAR(13) + '(SELECT TOP 100 PERCENT <COLUMN_NAME>, COUNT(*) as Count FROM ' + @TableName
SET @SQL_DetermineUniqueTemplate = @SQL_DetermineUniqueTemplate + CHAR(13) + ' GROUP BY <COLUMN_NAME> ORDER BY <COLUMN_NAME>) a'

/*Retrieve the Host Name. This will be used later in this SP as a test to determine if the user is making this call from within SQL Query Analyzer*/
SELECT @HostName = hostname FROM master..sysprocesses WHERE spid = @@SPID AND program_name = 'SQL Query Analyzer'


/*Set ActionText to be used in message output*/
IF (@DeleteDups IS NULL) OR (@DeleteDups = 1)
SET @ActionText = 'Selection'
ELSE
SET @ActionText = 'Deletion'

/*If a value is specified for use by UniqueColName it cannot exist in the columns from the DupQualifierFieldNameList*/
IF CHARINDEX(@UniqueColName, @DupQualifierFieldNameList) > 0
BEGIN
/*The value in UniqueColName was detected in DupQualifierFieldNameList.*/
IF NOT (@HostName IS NULL) PRINT 'The UniqueColName provided (' + @UniqueColName + ') must not exist in DupQualifierFieldNameList (' + @DupQualifierFieldNameList + '). Other solutions will be sought automatically.'
SET @UniqueColName = NULL
END


/*If UniqueColName is provided then perform check to ensure that all the values in that column are, in fact, unique.*/
IF NOT (@UniqueColName IS NULL)
BEGIN
SET @SQL = REPLACE(@SQL_DetermineUniqueTemplate,'<COLUMN_NAME>', @UniqueColName)
/*Perform a check of this column to determine if all of it's values are unique*/
EXEC sp_executesql @SQL, N'@SUM as int OUTPUT,@COUNT as int OUTPUT',@SUM OUTPUT,@COUNT OUTPUT
/*Test to determine if this column contains unique values*/
If @SUM <> @COUNT
BEGIN
/*The column specified by UniqueColName does not contain unique values.*/
IF NOT (@HostName IS NULL) PRINT 'The UniqueColName provided (' + @UniqueColName + ') does not contain unique values. Other solutions will be sought automatically.'
SET @UniqueColName = NULL
END
END


/*==============================================================*/
/*======================HELP OUTPUT TEXT======================*/
/*==============================================================*/
IF (@TableName IS NULL) OR (@TableName = '/?') OR (@TableName = '?') OR (@DupQualifierFieldNameList IS NULL) OR (@DupQualifierFieldNameList = '/?') OR (@DupQualifierFieldNameList = '?')
BEGIN
IF NOT (@HostName IS NULL)
BEGIN
PRINT 'sp_RemoveDups ''TableName'', ''DupQualifierFieldNameList'', [''DeleteDups''], [''UniqueColName''], [''CreateIdentColIfNeeded''], <''StoredProcedureResult''>'
PRINT '====================================================================================================================================================================='
PRINT 'TableName: Required - String - Name of the table to detect duplicate records in.'
PRINT 'DupQualifierFieldNameList: Required - String - Comma seperated list of columns that make up the unique record within TableName.'
PRINT 'DeleteDups: Optional - Bit, Set to 0 to delete duplicate records. A value of NULL or 1 will return the duplicate records to be deleted.'
PRINT 'UniqueColName: Optional - Bit - A table must have a unique column value in it to perform the deletion logic. If no UniqueColName is provided then an attemp will be made to locate the RowGUID column. If that fails then an attempt will be made to locate the Identity column. If that fails then all of the columns of the table will be examined and the first one with all unique values will be selected.'
PRINT 'CreateIdentColIfNeeded: Optional - Bit - By default this SP will create an identity column if no unique column can be located. Pass in a 1 here to run this feature off.'
PRINT 'StoredProcedureResult: Optional - OUTPUT - Int - Returns a 3 if an error occured, otherwise returns a 0.'
END
SET @StoredProcedureResult = 3
RETURN
END


/*========================================================================*/
/*======================DETECT USABLE UniqueColName======================*/
/*========================================================================*/
IF @UniqueColName IS NULL
BEGIN
/*Check for a RowGUID or Identity column in this table. If one exists, then utilze it as the unique value for the purposes of this deletion*/
IF EXISTS(SELECT * FROM SysColumns WHERE ID = Object_ID(@TableName) and ColumnProperty(ID,Name,'IsRowGUIDCol') = 1) SET @UniqueColName = 'RowGUIDCol'
IF EXISTS(SELECT * FROM SysColumns WHERE ID = Object_ID(@TableName) and ColumnProperty(ID,Name,'IsIdentity') = 1) SET @UniqueColName = 'IdentityCol'

IF @UniqueColName IS NULL
/*If no RowGUID or Identity column was found then check all of the columns in this table to see if one of them can be utilized as a unique value column*/
BEGIN
/*Select all of the columns from the table in question...*/
DECLARE MyCursor CURSOR LOCAL SCROLL STATIC FOR SELECT name FROM syscolumns WHERE OBJECT_ID(@TableName)=ID

OPEN MyCursor
FETCH NEXT FROM MyCursor INTO @NextColumn
WHILE @@fetch_status = 0
BEGIN
/*Create SQL string with correct column name in place.*/
SET @SQL = REPLACE(@SQL_DetermineUniqueTemplate,'<COLUMN_NAME>', @NextColumn)
/*Perform a check of this column to determine if all of it's values are unique*/
EXEC sp_executesql @SQL, N'@SUM as int OUTPUT,@COUNT as int OUTPUT',@SUM OUTPUT,@COUNT OUTPUT
/*Test to determine if this column contains unique values*/
If @SUM = @COUNT
BEGIN
/*A unique values column is detected. Use it and break out of the loop UNLESS column is specified in DupQualifierFieldNameList*/
IF CHARINDEX(@NextColumn, @DupQualifierFieldNameList) = 0
BEGIN
/*NextColumn was NOT detected in DupQualifierFieldNameList, so this is the column we will use.*/
SET @UniqueColName = @NextColumn
BREAK
END
END
ELSE
FETCH NEXT FROM MyCursor INTO @NextColumn
END
CLOSE MyCursor
DEALLOCATE MyCursor

END
END

/*If no UniqueColName has been found then create one UNLESS @CreateIdentColIfNeeded = 1*/
IF (@UniqueColName IS NULL) AND ( (@CreateIdentColIfNeeded IS NULL) OR (@CreateIdentColIfNeeded = 0) )
BEGIN
/*Add a sequence column to the table...*/
IF NOT (@HostName IS NULL) PRINT 'Creating temporary identity column in the ' + @TableName + ' table named ' + @TempIdentColName + ' for use in this ' + LOWER(@ActionText) + ' process...'
EXEC('ALTER TABLE ' + @TableName + ' ADD ' + @TempIdentColName + ' [int] IDENTITY (1, 1)')
SET @UniqueColName = @TempIdentColName
END


/*============================================================================*/
/*======================EXECUTE DELETION OR SELECTION======================*/
/*===========================================================================*/
IF @UniqueColName IS NULL
BEGIN
/*No UniqueColName was provided by the user and none were detected by the script. This deletion algorythm cannot run.*/
IF NOT (@HostName IS NULL) PRINT 'Could not perform ' + LOWER(@ActionText) + ' process. No unique columns were located and the UniqueColName flag is set to 1 (False).'
SET @StoredProcedureResult = 3
RETURN
END
ELSE
BEGIN
IF NOT (@HostName IS NULL) PRINT 'Performing ' + LOWER(@ActionText) + ' utilizing the unique values in the ' + @UniqueColName + ' column as a reference...'
/*
Create and execute an SQL statement in the form of:

SELECT * (or DELETE)
FROM TableName WHERE UniqueColName IN
(
SELECT UniqueColName FROM TableName WHERE UniqueColName NOT IN
(
SELECT MAX(Cast(UniqueColName AS varchar(36))) FROM TableName GROUP BY DupQualifierFieldNameList, DupQualifierFieldNameList, etc
)
)
*/
/*Delete all duplicate records useing @UniqueColName as a unique ID column */
IF (@DeleteDups IS NULL) OR (@DeleteDups = 1)
SET @SQL = 'SELECT * '
ELSE
SET @SQL = 'DELETE '

SET @SQL = @SQL + 'FROM ' + @TableName + ' WHERE ' + @UniqueColName + ' IN '
SET @SQL = @SQL + CHAR(13) + CHAR(9) + '(' + CHAR(13) + CHAR(9)
SET @SQL = @SQL + 'SELECT ' + @UniqueColName + ' FROM ' + @TableName + ' WHERE ' + @UniqueColName + ' NOT IN '
SET @SQL = @SQL + CHAR(13) + CHAR(9) + CHAR(9) + '(' + CHAR(13) + CHAR(9)+CHAR(9)
SET @SQL = @SQL + 'SELECT MAX(Cast(' + @UniqueColName + ' AS varchar(36))) FROM '
SET @SQL = @SQL + @TableName + ' GROUP BY ' + @DupQualifierFieldNameList
SET @SQL = @SQL + CHAR(13) + CHAR(9) + CHAR(9) + ')' + CHAR(13) + CHAR(9) + ')'

EXEC (@SQL)
IF @@ERROR <> 0
BEGIN
IF NOT (@HostName IS NULL) PRINT @ActionText + ' process failed.'
SET @StoredProcedureResult = 3
END
ELSE
BEGIN
IF NOT (@HostName IS NULL) PRINT @ActionText + ' completed successfully with this SQL: ' + CHAR(13) + @SQL
SET @StoredProcedureResult = 0
END
END


IF (@UniqueColName = @TempIdentColName) AND ( (@CreateIdentColIfNeeded IS NULL) OR (@CreateIdentColIfNeeded = 0) )
BEGIN
/*Remove the sequence column from the table...*/
IF NOT (@HostName IS NULL) PRINT 'Removing temporary identity column named ' + @TempIdentColName + ' from the ' + @TableName + ' table...'
EXEC('ALTER TABLE ' + @TableName + ' DROP COLUMN ' + @TempIdentColName)
END
GO







Edited by - emanaton on 10/30/2002 11:28:34

View 11 Replies View Related

No Unique Key / Avoid Dups

Oct 16, 2007

I have a table that I cannot create a unique key for because there is nothing unique and I can concatenate anything together to create one. I am looking for a way to import the data daily and have it only import what is not already in the table like a unique index would normally do. I don't want a sequencial number because that would do me any good. I need the record only in there once but I want to get all of the records in the new table. I have a date field with this if that at all helps. I am wondering if I could create a couple of feeder table to make this work but i am stuck. Any ideas on what to do? Thanks!!!

View 6 Replies View Related

Deleting The Master Table Withour Deleting The Child Tables

Aug 9, 2007

Hi
i have to delete the master table data without deleting the child table records,is there any solution for this,  parent table has relation with the child table.
regards
vinod.t.v

View 9 Replies View Related

T-SQL (SS2K8) :: Deleting Only 1 Row At A Time Instead Of Using Condition And Deleting Many Rows?

Jul 18, 2014

/****** Object: StoredProcedure [dbo].[dbo.ServiceLog] Script Date: 07/18/2014 14:30:59 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER proc [dbo].[ServiceLogPurge]

-- Purge records dbo.ServiceLog older than 3 months:
-- Purge records in small portions to avoid locking production tables
-- for a long time. The process takes longer, but can co-exist with
-- normal usage of the tables.

[Code] ...

*** Getting this error below when executing the code ***

Msg 102, Level 15, State 1, Procedure ServiceLogPurge, Line 45
Incorrect syntax near 'Failed:'.

View 9 Replies View Related

Need Help On Deleting

Dec 12, 2001

Please HELP!!

I need a query to DELETE the first few records in a table. For example: something like .....delete top 1000 from tablename. I figured that TOP dosent work with the DELETE. It only works with SELECT and UPDATE statments.


I cannot hardcode any values in the WHERE clause due to certain constraints in my application.

KINDLY HELP, THIS IS URGENT.

View 2 Replies View Related

Deleting Data From DB

Nov 23, 2006

I have edited the aspnet_Users_CreateUser stored procedure so that the UserId that is created when a new user is created is copied to a UserId field in another table. However, when I use the website administration tool to delete users that have been created, it gives me an error saying the delete statement conflicted with the reference constraint. I then added the following code in the aspnet_Users_DeleteUser procedure....
IF ((@TablesToDeleteFrom & 16) <> 0 AND
(EXISTS (SELECT name FROM sysobjects WHERE (name = N'vw_tt') AND (type = 'V'))))
BEGIN
DELETE FROM dbo.userclassset WHERE @UserId = UserId
SELECT @ErrorCode = @@ERROR,
@RowCount = @@ROWCOUNT
IF( @ErrorCode <> 0 )
GOTO Cleanup
IF (@RowCount <> 0)
SELECT @NumTablesDeletedFrom = @NumTablesDeletedFrom + 1    hdhd
END
This code was then added to the function at the end which deletes the data from the aspnet_Users table when everything else has been removed
(@TablesToDeleteFrom & 16) <> 0 AND
Now when I delete a user in the website admin tool, it "deletes" (with no error) the user from the list but doesnt actually physically delete it from the database.
Any ideas?
 

View 1 Replies View Related

Deleting From Sql Question.

Jan 2, 2007

I have a data source which I created a custom statement for which I need to delete from.  I created the folowing selecct statement
 SELECT [CompId], [Description], [CompName], [OS], [UserName], [DriverEntryId] FROM [SrcComputer] WHERE ([UserName] = @UserName)
I wrote the following DELETE statement
 DELETE FROM SrcComputer WHERE (CompId = @CompId)
I have tested it in SQL server management and it does what I want it to do, but I don't know how to use it in my code.  I put it inside of the DELETE tab inside of my custome statement and added a delete button inside of the gridview which utializes my data source, but it's not working.  I don't know how to set the CompId variable?  I want the statement to delete the row that the user clicks on.  Can anyone give me some advice?

View 6 Replies View Related

Deleting A Record

Oct 9, 2007

I have three tables
1. membership table(aspnet_membership table)
2. User Contacts table
3. Address table
These three table have relation ship with one another through a UserId field. 
How will you set up cascaded delete on these tables, Like if I delete a user in the membership table I want the related records in the other tables to be deleted as well. Cascaded delete is it something done through code, or is it definde when the tables are created.
Please advice. 
 

View 1 Replies View Related

Deleting Problems..

Apr 2, 2008

here i a again.. because im really having problems in deleting rows from a gridview... here is my code
SelectCommand="SELECT UserId, First, Last, Email, CreateDate, LastLoginDate, IsApproved, IsLockedOut FROM aspnet_Membership"
DeleteCommand="DELETE FROM aspnet_Membership WHERE [UserId] = @UserId"
ConnectionString="<%$ ConnectionStrings:ConnectionString2 %>" >
<DeleteParameters>
<asp:Parameter Name="UserId" Type="Int32"/>
</DeleteParameters>
 
It is working but when i click the delete button.. this appears
Must declare the scalar variable "@UserId".
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: Must declare the scalar variable "@UserId".Source Error:



An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below. Stack Trace:



[SqlException (0x80131904): Must declare the scalar variable "@UserId".]
System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection) +95
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) +82
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj) +346
System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) +3430
System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean async) +271
System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(DbAsyncResult result, String methodName, Boolean sendToPipe) +367
System.Data.SqlClient.SqlCommand.ExecuteNonQuery() +149
System.Web.UI.WebControls.SqlDataSourceView.ExecuteDbCommand(DbCommand command, DataSourceOperation operation) +492
System.Web.UI.WebControls.SqlDataSourceView.ExecuteDelete(IDictionary keys, IDictionary oldValues) +919
System.Web.UI.DataSourceView.Delete(IDictionary keys, IDictionary oldValues, DataSourceViewOperationCallback callback) +176
System.Web.UI.WebControls.GridView.HandleDelete(GridViewRow row, Int32 rowIndex) +911
System.Web.UI.WebControls.GridView.HandleEvent(EventArgs e, Boolean causesValidation, String validationGroup) +1067
System.Web.UI.WebControls.GridView.RaisePostBackEvent(String eventArgument) +214
System.Web.UI.WebControls.GridView.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +31
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +32
System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +242
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3839
need help asap.. pls THANK YOU VERY MUCH!!!

View 1 Replies View Related

Deleting All But Top Record.

Jun 23, 2005

Hey Guys,I have Performance Monitor running and storing the network usage to my MsSQL database, and this is done a few times a minute. I have a page that then shows show much of my bandwidth is being used. As you can gather, the database quickly starts filling up with hundrreds of records so I could do with a script that delete these records. I cant simply delete all records because that would cause my webpage to fail so I need a way to delete all records apart from the latest one. Wondering if anyone would know how I could do this?

View 3 Replies View Related

Deleting From 2 Tables?

Jul 21, 2005

Hi, I am pretty new to SQL and know that I am probably going around this the wrong way.

I want to make a stored proc that deletes rows from table 1 and delete rows from table 2 where the common link is the id.

Any help would be greatly appreciated!

Many thanks

moop

View 5 Replies View Related

Deleting Old Backups

Apr 17, 2001

I am new to SQL backups but what I have done is created a script sp_BackupProcessor that is used to determine which backup type is run (Full,Differential,Transaction). I am backing up to the local drive and then our tape backup system backs up the files on our local system to tape. I only want to keep 3 days worth of backups on our local machine since the same information is stored on tape. What is the best way to handle this? Any help or ideas would be appreciated. I have included my script for reference.

Thanks,

Tim

CREATE PROCEDURE sp_BackupProcessor
@Help BIT = 0,
@Database VARCHAR(30) = NULL,
@BackupName VARCHAR(50) = NULL,
@BackupType VARCHAR(4) = NULL,
@Filename VARCHAR(255) = NULL,
@Description VARCHAR(255) = NULL
AS

Parameters:
@Database = ''master''
-- Default = ''master''
-- Specifies the database to backup.
@BackupName = ''masterLOG''
-- Default = ''masterLOG''
-- Specifies a name for the backup.
@BackupType = [''FULL'' | ''DIFF'' | ''LOG''],
-- Default = ''LOG''
-- ''FULL'' = Full database backup
-- ''DIFF'' = Differential database backup
-- ''LOG'' = Transaction Log Backup
@Filename = ''C:empmasterLOG.TRN''
-- Defualt = ''C:empmasterLOG.TRN''
-- Specifies the file to use for the backup.
-- Provide full path and filename.
@Description = ''255 cahr max''
-- Default = ''
-- Specifies a description to attach to the bakup.
Usage:
sp_BackupProcessor
@Database = ''Database'',
@BackupName = ''BackupName'',
@BackupType = [''FULL'' | ''DIFF'' | ''LOG''],
@Filename = ''FullPathLocalFile'',
@Description = ''Backup Description (255 max)''
'
RETURN 1
END

DECLARE @BackupStmt VARCHAR(500)
SELECT @BackupStmt =
CASE @BackupType
WHEN 'FULL' THEN
'BACKUP DATABASE ' + @Database + ' ' +
'TO DISK = ''' + @Filename + ''' ' +

'WITH RETAINDAYS = 2,' +
'INIT' + ', ' +
'NAME = ''' + @BackupName + ''', ' +
'NOSKIP' + ', ' +
'DESCRIPTION = ''' + @Description + ''', ' +
'NOFORMAT'
WHEN 'DIFF' THEN
'BACKUP DATABASE ' + @Database + ' ' +
'TO DISK = ''' + @Filename + ''' ' +
'WITH DIFFERENTIAL' + ', ' +
'NAME = ''' + @BackupName + ''', ' +
'NOSKIP' + ', ' +
'DESCRIPTION = ''' + @Description + ''', ' +
'NOFORMAT'
WHEN 'LOG' THEN
'BACKUP LOG ' + @Database + ' ' +
'TO DISK = ''' + @Filename + ''' ' +
'WITH NOINIT' + ', ' +
'NAME = ''' + @BackupName + ''', ' +
'NOSKIP' + ', ' +
'DESCRIPTION = ''' + @Description + ''', ' +
'NOFORMAT'
END
EXECUTE(@BackupStmt)
GO

View 1 Replies View Related

Deleting Duplicates

Apr 17, 2001

Hi,

does anyone out there know how to delete dulicate records in a table? I've looked in BOL and I can't seem to find it. Please advise.

thanks, mark

View 2 Replies View Related

Deleting Datbase

Apr 23, 2001

how do i delete an entire database when it keeps saying that the database is currently in use?

View 3 Replies View Related

Deleting Tables

Feb 21, 2001

hi,
How can I delete two tables with a WHERE condition.
That is I can't do this -What can be an alternate of this statement -

Delete from Tab1,Tab2,Tab3
where
Tab1.name = Tab2.Name and
Tab2.name = Tab3.name

TIA

View 1 Replies View Related

Deleting A Log File

Mar 5, 2001

How can you delete a log file.
Say I have backed up a transaction log at some drive say G:.
Now I want to delete this log file and want to define it in a job.
What is the syntax -
delete G:Test_log.bak ????
What is a proper syntax??
Thanks!

View 1 Replies View Related

Deleting Tables

Aug 24, 2005

Does anyone know why it takes a long time (Approx 10 minutes) to delete a DB. I have 2 identical environments for test and prod. I can delete DBs from my test environment quickly but it takes forever to delete a DB from the production environment. I am running SQL2000 SP3a. There are about 25 DBs in the environment with their sized ranging from 100meg to 2 gig. The only differnece in the environments is all test DBs are simple recovery mode and modt prod DBs are full.

Thanks,
Ken

View 5 Replies View Related

Deleting A Device

Dec 1, 1998

I am trying to drop a device that as no associated file in Windows NT Explorer(.dat) that shows up in my Server Manager Windows

How can I delete them?

Thanks

View 2 Replies View Related

Deleting Odd And Even Numbers

Aug 8, 2002

I have two identical databases. I need to delete the even customer numbers from the first database and the odd numbers from the other database. I know I can do this writing a delete statement for each table. However there are a total of 54 tables.

Does anyone know a faster way to write the script without writing 54 scripts?

I would appreciate your help.

As always you guys are the greatest.

Dianne

View 1 Replies View Related

Deleting A Table

Nov 9, 1998

i have a table that i think is bad -
how do i delete the table?
also i want to copy this same table from another database -
can i use enterprise manager to copy the same table in place of the deleted table?

View 1 Replies View Related

Deleting Duplicates

Sep 21, 2004

Hey all.

I have a table with 100,000 plus records in it, and some are duplicates. Is there any way to delete one of them and not the other. For instance, if I duplicate the table I could run this query.
<cfquery name="query1" datasource="datasource">
DELETE DISTINCT
FROM tablename
WHERE FirstName in ( SELECT FirstName from tablename1 where tablename1.FirstName = tablename.FIRST_NAME AND tablename1.LastName = tablename.LAST_NAME AND tablename1.State = tablename.STATE)
</cfquery>

However, it doesn't work. I know the distinct is not correct. But does anyone know how to achieve this, I have looked all over, and everything I try deletes both records. I was thinking of using some kindof count statement, but it still deletes both of them. Please help. Thanks

View 1 Replies View Related

Deleting Duplications Of A Db

Aug 13, 2004

I am joining two databases and the result has many duplications in it. Using SQL, how do I delete the duplications.

Thanks

View 1 Replies View Related

Deleting Records That Get Too Old

Jul 12, 2004

I must admit I dont know all that much about SQL, which is why I hope someone can show me the light. I have a script almost finished, however I have no idea how to have it trim database entries that are older than, say, 90 days. Any ideas?

View 10 Replies View Related

Deleting Rows

Nov 26, 2004

I have a table with approx 5 million rows and 36 columns. It takes approx
4 minutes to delete 1 row. The table has 3 indexes in addition to it's primary key and has twelve foreign key constraints. We are still using sequel 7.
There is a backup run every night as part of the nightly maintenence that
reorg/reindexes and checks the database integrity. Any thoughts?

Thanks

View 8 Replies View Related

Deleting Records

Feb 25, 2005

I have a table with a load of orphaned records (I know... poor design)
I'm trying to get rid of them, but I'm having a brain cramp.

I need to delete all the records from the table "Floor_Stock" that
would be returned by this select statement:


SELECT FLOOR_STOCK.PRODUCT, FLOOR_STOCK.SITE
FROM PRODUCT_MASTER INNER JOIN
FLOOR_STOCK ON PRODUCT_MASTER.PRODUCT =
FLOOR_STOCK.PRODUCT LEFT OUTER JOIN
BOD_HEADER ON FLOOR_STOCK.PRODUCT =
BOD_HEADER.PRODUCT AND FLOOR_STOCK.SITE =
BOD_HEADER.SITE
WHERE (BOD_HEADER.BOD_INDEX IS NULL) AND
(PRODUCT_MASTER.PROD_TYPE IN ('f', 'n', 'k', 'b', 'l', 's'))


I was thinking along the lines of:


DELETE FROM FLOOR_STOCK INNER JOIN
(SELECT FLOOR_STOCK. PRODUCT, FLOOR_STOCK.SITE
FROM PRODUCT_MASTER INNER JOIN
FLOOR_STOCK ON PRODUCT_MASTER. PRODUCT =
FLOOR_STOCK.PRODUCT
LEFT OUTER JOIN BOD_HEADER ON FLOOR_STOCK. PRODUCT =
BOD_HEADER. PRODUCT AND FLOOR_STOCK.SITE = BOD_HEADER.SITE
WHERE (BOD_HEADER.BOD_INDEX IS NULL) AND
(PRODUCT_MASTER.PROD_TYPE IN ('f', 'n', 'k', 'b', 'l', 's'))) F ON
FLOOR_STOCK. PRODUCT = F. PRODUCT
AND FLOOR_STOCK.SITE = F.SITE


... but Sql Server just laughs at me: "Incorrect Syntax near the keyword INNER"

View 14 Replies View Related

Deleting TRN Files

May 26, 2006

I have a database and I see that I have a lot of TRN files behind it taking up more than 82GB disk space.I have a TRN file from Jan until today. I plan to delete every one of them until April to recover 59 GB of disk space. Would that be OK?

View 4 Replies View Related

Deleting Without Locking?

Feb 26, 2004

Hi All,

Yes, It can be a stupid question but I was trying to understand if it is really impossible!
I have a big table (around 200 millions of records) and I have to delete the old record. I read about the hints and ROWLOCK seems to be perfect. I don't want to have pages locked at all.

However, when I am deleting this table using rowlock I got the following locks
mode - key , type U (Update) and
mode - tab, type X (Exclusive).

I have tried a SELECT on new records but got to wait.

Is there a chance to lock only the records to be deleted?

Thanks a lot,
Felicia Schimidt

View 3 Replies View Related

Deleting Records

Mar 3, 2004

How do I delete one record from one table and cascade down all related tables?


Mike B

View 14 Replies View Related

Error When Deleting

Apr 12, 2004

I have a msde back end for my application.
I also have an Access data file with linked tables to the SQL one.
My app accesses the data through the Access one through ODBC.

I have a data control and when try to delete a record as so:
DataControl.Recordset.Delete
I get a 'ODBC Call Failed' error.

Any ideas why?
The recordset's updateable property is true.

Thanks,

View 8 Replies View Related







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