Showing posts with label procedure. Show all posts
Showing posts with label procedure. Show all posts

Thursday, March 29, 2012

Deleting stored procedures through query analyzer

Hi All!

I know this must be a very silly question but, what is the PLSQL string I have to use to delete a stored procedure in a database? Essentially I have to remove a stored procedure that comes from a database backup every night because it belongs to a user and that user has to be recreated in the new SQL Server 2000. Simply put:

1. Production database comes into test database
2. Remove copy of stored procedure since it can not be set to dbo user because there is another copy with the same name that belongs to dbo.
3. Remove user
4. Add user (this one brings login name since the restored one didn't)
5. Have a nice day

I've got everything except removing the stored procedure so I will really appreciate the help.

Thank you all!

Rijckewaert wrote:

Hi All!

I know this must be a very silly question but, what is the PLSQL string I have to use to delete a stored procedure in a database?

Transact-SQL ... here Oracle is notwelcome

the actual traditional code is

IF OBJECT_ID('[schema/owner].[object]') IS NOT NULL

DROP PROCEDURE [schema/owner].[object];

Essentially I have to remove a stored procedure that comes from a database backup every night because it belongs to a user and that user has to be recreated in the new SQL Server 2000. Simply put:

1. Production database comes into test database
2. Remove copy of stored procedure since it can not be set to dbo user because there is another copy with the same name that belongs to dbo.
3. Remove user
4. Add user (this one brings login name since the restored one didn't)
5. Have a nice day

I've got everything except removing the stored procedure so I will really appreciate the help.

Thank you all!

this "design" is not clear to me... why would you always drop an object to be recreated (if the inner code remains the same)?

is this becouse of the well known "orphaned users" problem?
this problem (perhaps the problem you are experimenting) is involved when a "restored" database user(s) is no longer mapped to a corresponding server's standard SQL Server login..
in SQL Server 2000 this means the relationship between master.dbo.syslogins is broken with database.dbo.sysusers...
actually the JOIN on master.dbo.syslogins.sid ~ database.dbo.sysusers.sid

if this is the case, you do not need to delete the object and the user... you just need to resync it/them, via the sp_change_users_logins system stored procedure http://msdn2.microsoft.com/en-us/library/ms174378.aspx ... please have a look at http://msdn2.microsoft.com/en-us/library/ms175475.aspx as well..

if this is not the case... please expand

regards

Tuesday, March 27, 2012

Deleting more duplicates

Hello,
I have a stored procedure that deletes duplicates
in one table:

....
AS
BEGIN
DELETE FROM mytable
WHERE Id IN(
SELECT Max(id)
from mytable
group by date, idsens
having count(*) >1
)
END

sometimes it happens that I have >2 rows with duplicated values.
How can I write a new stored procedure that delete all rows with
duplicated infomrations (leaving only one row with those values)?

Thanks
M.A.On Tue, 25 Jul 2006 10:36:10 GMT, Maury wrote:

Quote:

Originally Posted by

>Hello,
>I have a stored procedure that deletes duplicates
>in one table:
>
>...
>AS
>BEGIN
>DELETE FROM mytable
>WHERE Id IN(
>SELECT Max(id)
>from mytable
>group by date, idsens
>having count(*) >1
>)
>END
>
>sometimes it happens that I have >2 rows with duplicated values.
>How can I write a new stored procedure that delete all rows with
>duplicated infomrations (leaving only one row with those values)?


Hi Maury,

For SQL Server 2005:

WITH DeDupe (Id, rn)
AS (SELECT Id, ROW_NUMBER() OVER (PARTITION BY date, idsens ORDER BY Id)
FROM mytable)
DELETE DeDupe
WHERE rn 1;

For all versions of SQL Server:

DELETE FROM mytable
WHERE EXISTS
(SELECT *
FROM mytable AS m2
WHERE m2.date = mytable.date
AND m2.idsens = mytable.idsens
AND m2.Id < mytable.Id);

--
Hugo Kornelis, SQL Server MVP|||Hugo Kornelis ha scritto:

Quote:

Originally Posted by

WITH DeDupe (Id, rn)
AS (SELECT Id, ROW_NUMBER() OVER (PARTITION BY date, idsens ORDER BY Id)
FROM mytable)
DELETE DeDupe
WHERE rn 1;


This is very very interesting (I didn't know these commands)
I have to search a good reference
or stored procedure language manual
for sql server 2005
some hints?
thanks!!!!
M.A.|||Maury (maurizio.alberti_TOGLI_@.gmail.com) writes:

Quote:

Originally Posted by

This is very very interesting (I didn't know these commands)
I have to search a good reference
or stored procedure language manual
for sql server 2005
some hints?


Books Online. Ships with SQL Server. Update available from the link below.

--
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pr...oads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodin...ions/books.mspx

Sunday, March 25, 2012

Deleting Log file

Hello
Is there any time / way /procedure to delte the log file and let SQL
recreate it without losing any data. In other words - at what point in time
can one be safely assured that all data in the log file is committed to the
database.
reason - have 1.2gb database and 9gb logfile - caused by duplicating
another database ( importing thru ODBC ) each night and would like to kill
the log file each morning after the transfer - the SQL database is only
used for reporting as the other package has lots of limitations - yep - we
are working on converting it all to SQL so this replication doesn't have to
happen but that is still a fair way off
TIA
PeteIf your recovery plan is to restore from your last full database backup (or
rerun your import), you can set the database recovery model to SIMPLE so
that committed transactions are automatically removed from the log.
You can run DBCC SHRINKFILE to release unused log space back to the OS. The
log will still need to be large enough to accommodate your largest
transaction so you probably don't want to do this routinely.
--
Hope this helps.
Dan Guzman
SQL Server MVP
"Pete" <p0911@.hotmail.com> wrote in message
news:eAMZK0PSEHA.1568@.TK2MSFTNGP11.phx.gbl...
> Hello
> Is there any time / way /procedure to delte the log file and let SQL
> recreate it without losing any data. In other words - at what point in
time
> can one be safely assured that all data in the log file is committed to
the
> database.
> reason - have 1.2gb database and 9gb logfile - caused by duplicating
> another database ( importing thru ODBC ) each night and would like to kill
> the log file each morning after the transfer - the SQL database is only
> used for reporting as the other package has lots of limitations - yep - we
> are working on converting it all to SQL so this replication doesn't have
to
> happen but that is still a fair way off
> TIA
> Pete
>sql

Deleting Log file

Hello
Is there any time / way /procedure to delte the log file and let SQL
recreate it without losing any data. In other words - at what point in time
can one be safely assured that all data in the log file is committed to the
database.
reason - have 1.2gb database and 9gb logfile - caused by duplicating
another database ( importing thru ODBC ) each night and would like to kill
the log file each morning after the transfer - the SQL database is only
used for reporting as the other package has lots of limitations - yep - we
are working on converting it all to SQL so this replication doesn't have to
happen but that is still a fair way off
TIA
Pete
If your recovery plan is to restore from your last full database backup (or
rerun your import), you can set the database recovery model to SIMPLE so
that committed transactions are automatically removed from the log.
You can run DBCC SHRINKFILE to release unused log space back to the OS. The
log will still need to be large enough to accommodate your largest
transaction so you probably don't want to do this routinely.
Hope this helps.
Dan Guzman
SQL Server MVP
"Pete" <p0911@.hotmail.com> wrote in message
news:eAMZK0PSEHA.1568@.TK2MSFTNGP11.phx.gbl...
> Hello
> Is there any time / way /procedure to delte the log file and let SQL
> recreate it without losing any data. In other words - at what point in
time
> can one be safely assured that all data in the log file is committed to
the
> database.
> reason - have 1.2gb database and 9gb logfile - caused by duplicating
> another database ( importing thru ODBC ) each night and would like to kill
> the log file each morning after the transfer - the SQL database is only
> used for reporting as the other package has lots of limitations - yep - we
> are working on converting it all to SQL so this replication doesn't have
to
> happen but that is still a fair way off
> TIA
> Pete
>

Deleting Log file

Hello
Is there any time / way /procedure to delte the log file and let SQL
recreate it without losing any data. In other words - at what point in time
can one be safely assured that all data in the log file is committed to the
database.
reason - have 1.2gb database and 9gb logfile - caused by duplicating
another database ( importing thru ODBC ) each night and would like to kill
the log file each morning after the transfer - the SQL database is only
used for reporting as the other package has lots of limitations - yep - we
are working on converting it all to SQL so this replication doesn't have to
happen but that is still a fair way off
TIA
PeteIf your recovery plan is to restore from your last full database backup (or
rerun your import), you can set the database recovery model to SIMPLE so
that committed transactions are automatically removed from the log.
You can run DBCC SHRINKFILE to release unused log space back to the OS. The
log will still need to be large enough to accommodate your largest
transaction so you probably don't want to do this routinely.
Hope this helps.
Dan Guzman
SQL Server MVP
"Pete" <p0911@.hotmail.com> wrote in message
news:eAMZK0PSEHA.1568@.TK2MSFTNGP11.phx.gbl...
> Hello
> Is there any time / way /procedure to delte the log file and let SQL
> recreate it without losing any data. In other words - at what point in
time
> can one be safely assured that all data in the log file is committed to
the
> database.
> reason - have 1.2gb database and 9gb logfile - caused by duplicating
> another database ( importing thru ODBC ) each night and would like to kill
> the log file each morning after the transfer - the SQL database is only
> used for reporting as the other package has lots of limitations - yep - we
> are working on converting it all to SQL so this replication doesn't have
to
> happen but that is still a fair way off
> TIA
> Pete
>

Deleting from Stored Procedures

I am trying to write a stored procedure to delete something from a table but I keep getting sytax error.

This is the code I am using:

DELETE [tablename].[tablerow], [tablename].[tablerow]
FROM [tablename]
WHERE (((tablename.tablerow)="void"));

This works as an Access query but not as a stored procedure.DELETE
FROM [tablename]
WHERE tablename.tablerow)='void'
GO

Wednesday, March 21, 2012

Deleting Data From DB

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) <> 0AND

(

EXISTS(SELECT name FROMsysobjectsWHERE(name= N'vw_tt')AND(type ='V'))))BEGINDELETE FROMdbo.userclasssetWHERE@.UserId = UserIdSELECT@.ErrorCode = @.@.ERROR,

@.RowCount = @.@.ROWCOUNT

IF( @.ErrorCode <> 0 )GOTOCleanupIF(@.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?

Problem fixed. The following code seemed to do the trick. I just needed to place it in the right point in the code which was just before the deletion of the UserId information in the membership table. Sorry to waste peoples time!

DELETE FROM dbo.userclassset WHERE @.UserId = UserId

Deleting data by calling the stored procedure in the .NET

Hi, does anyone know how to delete data from the SQL database bycalling the stored procedure in the Visual Basic.NET? Because I did theDelete hyperlink bounded inside a datagrid. I have already displayedthe appointment date, time in the datagrid so I do not have to inputany values inside it. These are my stored procedures code for deleting:
ALTER PROCEDURE spCancelReservation(@.AppDate DATETIME, @.AppTime CHAR(4), @.MemNRIC CHAR(9))
AS
BEGIN
IF NOT EXISTS
(SELECT MemNRIC, AppDate, AppTime
FROM DasAppointment
WHERE (MemNRIC = @.MemNRIC) AND (AppDate = @.AppDate) AND (AppTime = @.AppTime))
RETURN -400
ELSE IF EXISTS
(SELECT MemNRIC
FROM DasAppointment
WHERE (DATEDIFF(DAY, GETDATE(), @.AppDate) < 10))
RETURN -401
ELSE
DELETE FROM DasAppointment
WHERE MemNRIC = @.MemNRIC
END
IF @.@.ERROR <> 0
RETURN @.@.ERROR
RETURN
DECLARE @.status int
EXEC @.status = spCancelReservation '2005-08-16', '1900', 'S1256755J'
SELECT 'Status' = @.status
Can someone pls help? Thanks!
So what is the problem? Is the stored proc not running or are you having trouble calling the stored proc from .NET ?|||Ya, I am having trouble calling from the .NET. The stored procedure itself can work in the SQL Server database.|||The call from ASP.NET should be essentially the same as the code you had posted in this thread:http://forums.asp.net/1004793/ShowPost.aspx. Please try to get the code working and post exact problems and exact error messages.
|||Hi, these are my codes for the .NET.
Dim connStr As String = System.Configuration.ConfigurationSettings.AppSettings("SqlConnection.connectionString")
Dim dbConn As New SqlConnection
Dim dr As SqlDataReader
dbConn.ConnectionString = connStr
Try
dbConn.Open()
Dim dbCmd As New SqlCommand
dbCmd.Connection = dbConn
dbCmd.CommandType = CommandType.StoredProcedure
dbCmd.CommandText = "spCancelReservation"
Dim dbParam As SqlParameter
dbParam = dbCmd.Parameters.Add("@.AppDate", SqlDbType.DateTime)
dbParam.Direction = ParameterDirection.Input
dbParam.Value = Session("AppDate")

dbParam = dbCmd.Parameters.Add("@.AppTime", SqlDbType.Char, 4)
dbParam.Direction = ParameterDirection.Input
dbParam.Value = Session("AppTime")

dbParam = dbCmd.Parameters.Add("@.MemNRIC", SqlDbType.Char, 9)
dbParam.Direction = ParameterDirection.Input
dbParam.Value = Session("NRIC")
dr = dbCmd.ExecuteReader()
Finally
'Re-direct to View page for display of reservation
Server.Transfer("View.aspx")
End Try

End Sub
For the part on red: it is supposed to be already displayed in the datagrid. So can i used a session to store it?
For the part on green: it is supposed to just go into viewing theappointments after one has already logged in. So he is entited to viewhis own appt without having to input his NRIC no again.
For the part on blue: I am supposed to delete the appt but this line ofcode is to add into the database right? So should I changed to dbCmd.Parameters.Clear()? If yes, how do I write?
All the above are written inside the page_load event and all the dataare being displayed as a datagrid. I created this page to do the behindscene of deleting without the user actually seeing it. So for thebinding of the datagrid, wad should I typed for the URL and the URLfield in the property builder as i used a hyperlink column to deletethe appt?
When the page is runned, the following occurred:A field or property with the name 'Cancel.aspx' was not found on the selected datasource.
|||Dim connStr As String = System.Configuration.ConfigurationSettings.AppSettings("SqlConnection.connectionString")
Dim dbConn As New SqlConnection
Dim dr As SqlDataReader
dbConn.ConnectionString = connStr
Try

Dim dbCmd As New SqlCommand
dbCmd.Connection = dbConn
dbCmd.CommandType = CommandType.StoredProcedure
dbCmd.CommandText = "spCancelReservation"
Response.write("Appdate=" & Session("AppDate") & ", AppTime=" & Session("AppTime") & ", NRIC=" & Session("NRIC"))
dbCmd.Parameters.Add(New SQL Parameter("@.AppDate", SqlDbType.DateTime)))
dbParam.Value = Session("AppDate")

dbParam = dbCmd.Parameters.Add(New SQL Parameter("@.AppTime", SqlDbType.Char, 4))
dbParam.Value = Session("AppTime")
dbParam = dbCmd.Parameters.Add(New SQL Parameter("@.MemNRIC", SqlDbType.Char, 9))
dbParam.Value = Session("NRIC")
dbConn.Open()'open the connection as late as you can and close it immediately when you are done.
dr = dbCmd.ExecuteReader()
Finally
dbConn.Close'<---- This Is very important
'Re-direct to View page for display of reservation
Server.Transfer("View.aspx")
End Try

End Sub

I have simplified your code a little bit. I added a response.write statement so you can check what values you ae trying to pass. IF they are NULL's you need to accomodate for that. To check the values you could comment the line : dr = dbCmd.ExecuteReader()and run the page.|||I tried your codes, but I end up getting this error:
A field or property with the name 'Cancel.aspx' was not found on the selected datasource.
I think this error is due to the URL field or URL format string neededin the datagrid under Properties Builder. But I do not know what URLlinks to specify..
So I tried another cancel function, this time I tried a simpler deleteby using another stored procedure to view the existing appointment on awebform with a "Delete" button to delete the existing appointment. Butnow, the date, time can be shown, but when the "Delete" button isclicked, there is no deletion of data.
These codes are written in the button click event:
If Not Page.IsPostBack Then
Dim nric As String
nric = Session("NRIC")
lblMNRIC.Text = nric
DimconnStr As String =System.Configuration.ConfigurationSettings.AppSettings("SqlConnection.connectionString")
Dim dbConn As New SqlConnection
dbConn.ConnectionString = connStr
Dim dr As SqlDataReader
Try
dbConn.Open()
Dim dbCmd As New SqlCommand
dbCmd.Connection = dbConn
dbCmd.CommandType = CommandType.StoredProcedure
dbCmd.CommandText = "spCancelReservation"
Dim dbParam As SqlParameter
dbParam = dbCmd.Parameters.Add("@.return", SqlDbType.Int)
dbParam.Direction = ParameterDirection.ReturnValue
dbParam = dbCmd.Parameters.Add("@.MemNRIC", SqlDbType.Char, 9)
dbParam.Direction = ParameterDirection.Input
dbParam.Value = lblMNRIC.Text
dr = dbCmd.ExecuteReader()
Dim status As Integer
status = dbCmd.Parameters("@.return").Value
If status = -401 Then
lblError.Visible = True
lblError.Text = "You must cancel at least 10 days in advance!"
Else
lblDate.Visible = False
lblTime.Visible = False
lblADate.Visible = False
lblATime.Visible = False
lblError.Text = "You do not have any appointment!"
Response.Redirect("View.aspx")
End If
Catch ex As SqlException
lblError.Text = ex.Message
Catch ex As Exception
lblError.Text = ex.message
Finally
dbConn.Close()
End Try
End If
End Sub
|||can you check to see if the values in the textboxes are right? I have not used ReturnValue before. I have used OUTPUT parameters and it is slightly different. I am used to defining the parameter the way I showed in my code. I dont know what else to help you with - your code looks ok since there seem to be no syntax errors. Does the stored proc work from query analyzer?|||Ya, the values in the textboxes are right. The stored procedure works from the query analyzer. It can delete perfectly there. But in the .NET, the page will be refreshed but the data will not be deleted.|||For one thing, you should be using ExecuteNonQuery, not ExecuteReader.|||Ya, it should be ExecuteNonQuery.. Thanks.. Now it works.. but what isthe difference between NonQuery and ExecuteReader? I thought whendeleting, it should read the data from the database?
|||ExecuteNonQuery does not return any records. It will only return the number of rows affected kind alike your @.@.rowcount.
ExecuteReader returns the result set of a SELECT statement.


I thought when deleting, it should read the data from the database?


Nope. When deleting you are only deleting the records. Unless you have a SELECT statement you would not get any recordset back.

Monday, March 19, 2012

Deleting a row using a Stored Procedure from a GridView

I am trying to do something that I would think is simple. I have a stored procedure used for deleting a record, and I want to call it from the "Delete" command of a Delete button on a GridView. This incredible simple SP accepts one value, the unique record ID to delete the record like this:

CREATE PROCEDURE usp_DeleteBox/* ******************************************* Delete a record using the Passed ID.********************************************** */(@.pIDas int =Null)ASDELETE FROM [Boxes]WHERE ID = @.pID

When I configured the data source for the GridView, I selected the "Delete" tab and selected my Stored Procedure from the list. As mentioned on another post I saw here, I set the "DataKeyNames" property of the GridView to my id field (called "ID", naturally).

When I click the Delete button on a row, I get this error message: "Procedure or function usp_DeleteBox has too many arguments specified." If I leave the "DataKeyNames" property empty, it does nothing when I click delete.

Can someone tell me the correct way to configure this? I am sure I am missing something obvious, and I would appreciate any suggestions. Thank you!

Do you have any other columns in the DataKeyNames field? Any DeleteParameters on the DataSource? Can you show the GridView and DataSource code ?

|||

Thanks for your quick reply! I have no other colums in the DataKeyNames field. Here is the code you mentioned:

<asp:GridView ID="GridView1" runat="server" AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False" CellPadding="4" DataSourceID="SqlDataSource_Boxes" Font-Names="Arial" ForeColor="#333333" GridLines="None"> <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" /> <Columns> <asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False" ReadOnly="True" SortExpression="ID" /> <asp:BoundField DataField="BoxNumber" HeaderText="BoxNumber" SortExpression="BoxNumber" /> <asp:BoundField DataField="PalletNumber" HeaderText="PalletNumber" SortExpression="PalletNumber" /> <asp:BoundField DataField="DestName" HeaderText="DestName" SortExpression="DestName" /> <asp:BoundField DataField="DestCode" HeaderText="DestCode" SortExpression="DestCode" /> <asp:CommandField ButtonType="Button" ShowDeleteButton="True" /> </Columns> <RowStyle BackColor="#F7F6F3" ForeColor="#333333" /> <EditRowStyle BackColor="#999999" /> <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" /> <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" /> <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" /> <AlternatingRowStyle BackColor="White" ForeColor="#284775" /> </asp:GridView>
 <asp:SqlDataSource ID="SqlDataSource_Boxes" runat="server" ConnectionString="<%$ ConnectionStrings:BoxTrackSite.My.MySettings.ShippingConnStr%>" SelectCommand="SELECT dbo.Boxes.ID, dbo.Boxes.BoxNumber, dbo.Pallets.PalletNumber, dbo.Destinations.DestName, dbo.Destinations.DestCode FROM dbo.Boxes INNER JOIN dbo.Pallets ON dbo.Boxes.PalletID = dbo.Pallets.ID INNER JOIN dbo.Destinations ON dbo.Boxes.DestID = dbo.Destinations.ID" DeleteCommand="usp_DeleteBox" DeleteCommandType="StoredProcedure"> <DeleteParameters> <asp:Parameter Name="pID" Type="Int32" /> </DeleteParameters> </asp:SqlDataSource>
I know the SqlDataSource has a DeleteParameter (I don't know how that got there). If I removed that, it does nothing. Any further suggestions? Thanks again for your help.|||

I found a solution, but it wasn't as clean as I would have liked. Following the details inthis post, I found that I was indeed passing two parameters "pID" & "ID" when the SqlDataSource.Deleting event fired. So, as the other people mentioned, I changed my SP variable to be the same name as the identity column in my database ("ID") - and this worked.

It's frustrating that this is the behaviour. The controls should support methods for doing things as I was trying to do it originally. Some developers do not have the "luxury" (or permission) to modify existing SP's.

Deleting a Bunch of Reports

I need to delete a bunch of reports out of a folder in my reporting site. I can delete them one at a time, but it takes forever. I found a procedure in the database called 'DeleteObject.' It appears that this will do it for me. I just feed it the path of each report I want to delete. I tried it and it fails at the last statement in the proc. What am I doing wrong. Is it possible to do this?
Thanks.Probably not an answer to your question but just curious..


I just feed it the path of each report I want to delete.


Path of each report ? Arent you better off deleting them directly from the folder if you have to manually give the path of each report ?|||It would be if it didn't take forever to go through them all. Clicking is the easy, quick part. The problem is that you click on the report, you then have to click on the Properties tab, then click 'Delete' and then wait several seconds for the delete to take place. If the report has no parameters, it starts to generate automatically when you click on it, and (I believe) that once the report is processing, it can't be deleted until it's done. At least my experience with it leads me to believe that. So, it would take a heck of a lot less time to concatenate a statement together from a select of the path and run each one from query analyzer.
Thanks for the reply, though.

Friday, March 9, 2012

Deleted Stored Procedure Caused Backup Job to Failed

Hello,

I created a test stored procedure in MS SQL 2000. When the problem in my app was fixed, I deleted this test stored procedure. But the backup job thinks this procedure still exist and so backup job would failed. How can I fix this problem?

Thank in advance for your assistance.

Correct the 'backup job' so that it doesn't reference the deleted stored procedure.

I don't think that a database backup would fail because of the inclusion or deletion of a particular object, especially a stored procedure -unless that stored procedure is running the process.

|||

Arnie Rowland wrote:

I don't think that a database backup would fail because of the inclusion or deletion of a particular object, especially a stored procedure -unless that stored procedure is running the process.

Correct, a database backup doesn't care about the objects within the database.

Deleted Stored Procedure Caused Backup Job to Failed

Hello,

I created a test stored procedure in MS SQL 2000. When the problem in my app was fixed, I deleted this test stored procedure. But the backup job thinks this procedure still exist and so backup job would failed. How can I fix this problem?

Thank in advance for your assistance.

What kind of procedure it is?

I don't think procedure is anything to do database backup. Database backup is the complete copy of the database not the one by one object copy...

Can you post the error what you are getting when you are running the backup and how you are running the backup?

Deleted Records space

Am new to SQL2000, but have worked with other RDBMS's.
I am wondering what the procedure is to recover the space taken up in a
database by records marked for deletion?
Is this something automatically done as part of the shrink database procedure?
Kind Regards,
Naj
Hi
As soon as a row is deleted, it's space can be occupied by other data. It is
best to re-index the clustered keys as this will re-organize the DB to it's
original fill factor again. Shrink DB will not help you in this case.
Regards
Mike Epprecht, Microsoft SQL Server MVP
Zurich, Switzerland
IM: mike@.epprecht.net
MVP Program: http://www.microsoft.com/mvp
Blog: http://www.msmvps.com/epprecht/
"Naj Parandah" <Naj Parandah@.discussions.microsoft.com> wrote in message
news:B09A1600-7354-4D70-B5EB-3B41B4E9F1BD@.microsoft.com...
> Am new to SQL2000, but have worked with other RDBMS's.
> I am wondering what the procedure is to recover the space taken up in a
> database by records marked for deletion?
> Is this something automatically done as part of the shrink database
> procedure?
> Kind Regards,
> Naj
|||Thanks very much for the information Mike!
"Mike Epprecht (SQL MVP)" wrote:

> Hi
> As soon as a row is deleted, it's space can be occupied by other data. It is
> best to re-index the clustered keys as this will re-organize the DB to it's
> original fill factor again. Shrink DB will not help you in this case.
> Regards
> --
> Mike Epprecht, Microsoft SQL Server MVP
> Zurich, Switzerland
> IM: mike@.epprecht.net
> MVP Program: http://www.microsoft.com/mvp
> Blog: http://www.msmvps.com/epprecht/
> "Naj Parandah" <Naj Parandah@.discussions.microsoft.com> wrote in message
> news:B09A1600-7354-4D70-B5EB-3B41B4E9F1BD@.microsoft.com...
>
>

Deleted Records space

Am new to SQL2000, but have worked with other RDBMS's.
I am wondering what the procedure is to recover the space taken up in a
database by records marked for deletion?
Is this something automatically done as part of the shrink database procedure?
Kind Regards,
NajHi
As soon as a row is deleted, it's space can be occupied by other data. It is
best to re-index the clustered keys as this will re-organize the DB to it's
original fill factor again. Shrink DB will not help you in this case.
Regards
--
Mike Epprecht, Microsoft SQL Server MVP
Zurich, Switzerland
IM: mike@.epprecht.net
MVP Program: http://www.microsoft.com/mvp
Blog: http://www.msmvps.com/epprecht/
"Naj Parandah" <Naj Parandah@.discussions.microsoft.com> wrote in message
news:B09A1600-7354-4D70-B5EB-3B41B4E9F1BD@.microsoft.com...
> Am new to SQL2000, but have worked with other RDBMS's.
> I am wondering what the procedure is to recover the space taken up in a
> database by records marked for deletion?
> Is this something automatically done as part of the shrink database
> procedure?
> Kind Regards,
> Naj|||Thanks very much for the information Mike!
"Mike Epprecht (SQL MVP)" wrote:
> Hi
> As soon as a row is deleted, it's space can be occupied by other data. It is
> best to re-index the clustered keys as this will re-organize the DB to it's
> original fill factor again. Shrink DB will not help you in this case.
> Regards
> --
> Mike Epprecht, Microsoft SQL Server MVP
> Zurich, Switzerland
> IM: mike@.epprecht.net
> MVP Program: http://www.microsoft.com/mvp
> Blog: http://www.msmvps.com/epprecht/
> "Naj Parandah" <Naj Parandah@.discussions.microsoft.com> wrote in message
> news:B09A1600-7354-4D70-B5EB-3B41B4E9F1BD@.microsoft.com...
> > Am new to SQL2000, but have worked with other RDBMS's.
> > I am wondering what the procedure is to recover the space taken up in a
> > database by records marked for deletion?
> >
> > Is this something automatically done as part of the shrink database
> > procedure?
> >
> > Kind Regards,
> > Naj
>
>

Deleted Records space

Am new to SQL2000, but have worked with other RDBMS's.
I am wondering what the procedure is to recover the space taken up in a
database by records marked for deletion?
Is this something automatically done as part of the shrink database procedur
e?
Kind Regards,
NajHi
As soon as a row is deleted, it's space can be occupied by other data. It is
best to re-index the clustered keys as this will re-organize the DB to it's
original fill factor again. Shrink DB will not help you in this case.
Regards
--
Mike Epprecht, Microsoft SQL Server MVP
Zurich, Switzerland
IM: mike@.epprecht.net
MVP Program: http://www.microsoft.com/mvp
Blog: http://www.msmvps.com/epprecht/
"Naj Parandah" <Naj Parandah@.discussions.microsoft.com> wrote in message
news:B09A1600-7354-4D70-B5EB-3B41B4E9F1BD@.microsoft.com...
> Am new to SQL2000, but have worked with other RDBMS's.
> I am wondering what the procedure is to recover the space taken up in a
> database by records marked for deletion?
> Is this something automatically done as part of the shrink database
> procedure?
> Kind Regards,
> Naj|||Thanks very much for the information Mike!
"Mike Epprecht (SQL MVP)" wrote:

> Hi
> As soon as a row is deleted, it's space can be occupied by other data. It
is
> best to re-index the clustered keys as this will re-organize the DB to it'
s
> original fill factor again. Shrink DB will not help you in this case.
> Regards
> --
> Mike Epprecht, Microsoft SQL Server MVP
> Zurich, Switzerland
> IM: mike@.epprecht.net
> MVP Program: http://www.microsoft.com/mvp
> Blog: http://www.msmvps.com/epprecht/
> "Naj Parandah" <Naj Parandah@.discussions.microsoft.com> wrote in message
> news:B09A1600-7354-4D70-B5EB-3B41B4E9F1BD@.microsoft.com...
>
>

Saturday, February 25, 2012

DELETE transaction with SNAPSHOT isolation level - conflicts another table

Hi,

we are executing the following query in a stored procedure using snapshot isolation level:

DELETE FROM tBackgroundProcessProgressReport
FROM tBackgroundProcessProgressReport LEFT OUTER JOIN
tBackgroundProcess ON
tBackgroundProcess.BackgroundProcessProgressReportID =tBackgroundProcessProgressReport.BackgroundProcessProgressReportID LEFTOUTER JOIN
tBackgroundProcessProgressReportItem ON
tBackgroundProcessProgressReport.BackgroundProcessProgressReportID =tBackgroundProcessProgressReportItem.BackgroundProcessProgressReportID
WHERE (tBackgroundProcess.BackgroundProcessID IS NULL) AND
(tBackgroundProcessProgressReportItem.BackgroundProcessProgressReportItemID IS NULL)

The query should delete records from tBackgroundProcessProgressReport which are not connected with the other two tables.
However, for some reasone we get the following exception:

System.Data.SqlClient.SqlException:Snapshot isolation transaction aborted due to update conflict. Youcannot use snapshot isolation to access table 'dbo.tBackgroundProcess'directly or indirectly in database 'RHSS_PRD_PT_Engine' to update,delete, or insert the row that has been modified or deleted by anothertransaction. Retry the transaction or change the isolation level forthe update/delete statement.

The exception specifies that we arenot allowed to update/delete/insert records in tBackgroundProcess, butthe query indeed deletes records from tBackgroundProcessProgressReport,not from the table in the exception.
Is the exception raised because of the join?

Has someone encountered this issue before?

Thanks,

Yani

Hi,

it looks like this forum is not the best place to ask, since it's dedicated to asp.net

So anybody with idea where i could ask for a solution for my problem?

Thanks in advance!

Friday, February 17, 2012

DELETE Procedure. How to return a value?

Hello,

I created a DELETE Stored Procedure in SQL 2005.
When calling this procedure from my server code (VB.NET in my case) I
need to know if the record was deleted or not.

How should I do this?

Should I make the procedure to return True or False? If yes, how can I
do this?

My Stored Procedure is as follows (I think it is ok):

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE [dbo].[Content_DeleteContent]

-- Define the procedure parameters
@.ContentName NVARCHAR(100),
@.ContentCulture NVARCHAR(5)

AS

-- Prevent extra result sets from interfering with SELECT statements.
SET NOCOUNT ON;

-- Declare and define ContentId
DECLARE @.ContentId UNIQUEIDENTIFIER;
SELECT @.ContentId = ContentId FROM dbo.Content WHERE ContentName =
@.ContentName

-- Check if ContentId is Not Null
IF @.ContentId IS NOT NULL
BEGIN

-- Check if ContentId is Null
IF @.ContentCulture IS NULL
BEGIN

-- Delete all localized contents from dbo.ContentLocalized
DELETE
FROM dbo.ContentLocalized
WHERE ContentId = @.ContentId

-- Delete content from dbo.Content
DELETE
FROM dbo.Content
WHERE ContentName = @.ContentName;

END
ELSE

-- Delete localized content from dbo.ContentLocalized
DELETE
FROM dbo.ContentLocalized
WHERE (ContentID = @.ContentID AND ContentCulture = @.ContentCulture)

END

GO

Thanks,
Miguel

hi miguel.

below is the sp i modified. i've added an output parameter, which will be null if record(s) are deleted properly. so you can check in your code using output parameter.

SET ANSI_NULLSON
GO
SET QUOTED_IDENTIFIERON
GO

ALTER PROCEDURE [dbo].[Content_DeleteContent]

-- Define the procedure parameters
@.ContentNameNVARCHAR(100),
@.ContentCultureNVARCHAR(5) ,
@.nFlag tinyint output

AS

-- Prevent extra result sets from interfering with SELECT statements.
SET NOCOUNT ON;

-- Declare and define ContentId
DECLARE @.ContentIdUNIQUEIDENTIFIER;
SELECT @.ContentId = ContentIdFROM dbo.ContentWHERE ContentName =
@.ContentName

-- Check if ContentId is Not Null
IF @.ContentIdISNOT NULL
BEGIN

-- Check if ContentId is Null
IF @.ContentCultureISNULL
BEGIN

-- Delete all localized contents from dbo.ContentLocalized
DELETE
FROM dbo.ContentLocalized
WHERE ContentId = @.ContentId

-- Delete content from dbo.Content
DELETE
FROM dbo.Content
WHERE ContentName = @.ContentName;

Select @.nFlag = ContentIDfrom dbo.ContentLocalized
WHERE ContentId = @.ContentId
if @.nFlagisnull
Begin
Select @.nFlag = 1FROM dbo.Content
WHERE ContentName = @.ContentName;
End

END
ELSE

BEGIN
-- Delete localized content from dbo.ContentLocalized
DELETE
FROM dbo.ContentLocalized
WHERE (ContentID = @.ContentID AND ContentCulture = @.ContentCulture)

Select @.nFlage = ContentIDFROM dbo.ContentLocalized
WHERE (ContentID = @.ContentID AND ContentCulture = @.ContentCulture)


END

END

hope it helps.

regards,

satish.|||Rather than do SELECT's after the DELETE's checking for @.@.ROWCOUNT works faster since the number of records deleted is already stored in the function. You could just check if @.@.ROWCOUNT >0 and set your flag to 1 or 0 appropriately.|||

Hi Dinakar

miguel has usedSET NOCOUNT ON.

thanks,

satish.

|||

Hello,

I defined "Set NoCount On" because this is done by default in SQL Server 2005 Management Studio and because this is how I see in most code examples.

I am just starting with SQL. Should I change it?

Could somebody give me some info on this?

Thanks,

Miguel

|||

hi miguel,

sorry i m not aware of default in sql 2k5

set nocount on --in case you update/insert/delete record on a table it wont return number of affected records

set nocount off --in case you update/insert/delete record on a table it will return number of affected records

hope it clarifies

now if you set it to off in your sp then after delete you can check

if @.@.ROWCOUNT > 0

begin

end

@.@.ROWCOUNT contains no.of records affected due to preceeding operation.

regards,

satish.

|||

SET NOCOUNT will only suppress messages from being printed in the Messages tab which are returned to the calling application. It does not have any effect on @.@.ROWCOUNT. You can still do your T-SQL Queries and have the results of rows affected in @.@.ROWCOUNT, get the value into variable and return it via OUTPUT parameters. Having the SET NOCOUNT ON is a good thing, generally. It prevents unnecessary messages from being passed across to the application.

Satish,

You are probably checking the Messages tab by running a T-SQL statement between SET NOCOUNT commands.

Try this:

SET NOCOUNT ON

SELECT TOP 10 * FROM anyTable

SELECT @.@.ROWCOUNT as RowsAffected

SET NOCOUNT OFF

|||

errrrr silly of me.

thanks dinakar you removed my misunderstanding about @.@.ROWCOUNT and SET NOCOUNT

cheers,

satish.

DELETE Procedure. How to do this?

Hello,

I created a delete procedure which is working but I still have a
problem.

When I delete a localized content from dbo.by27_ContentLocalized given
a ContentName and ContentCulture I want to check if this is the only
record in ContentLocalized for that ContentName.

If it is then I also want to delete the record in dbo.by27_Content
which has that ContentName.

How can I do this?

Thanks,
Miguel

Here is my DELETE procedure:

-- Define the procedure parameters
@.ContentCulture NVARCHAR(5),
@.ContentName NVARCHAR(100)

AS

-- Allows @.@.ROWCOUNT and the return of number of records when
ExecuteNonQuery is used
SET NOCOUNT OFF;

-- Declare and define ContentId
DECLARE @.ContentId UNIQUEIDENTIFIER;
SELECT @.ContentId = ContentId FROM dbo.by27_Content WHERE ContentName =
@.ContentName

-- Check if ContentId is Not Null
IF @.ContentId IS NOT NULL
BEGIN

-- Check if ContentId is Null
IF @.ContentCulture IS NULL
BEGIN

-- Delete all localized contents from dbo.by27_ContentLocalized
DELETE
FROM dbo.by27_ContentLocalized
WHERE ContentId = @.ContentId

-- Delete content from dbo.by27_Content
DELETE
FROM dbo.by27_Content
WHERE ContentName = @.ContentName;

END
ELSE

-- Delete localized content from dbo.by27_ContentLocalized
DELETE
FROM dbo.by27_ContentLocalized
WHERE (ContentID = @.ContentID AND ContentCulture = @.ContentCulture)

END

shapper:

When I delete a localized content from dbo.by27_ContentLocalized given
a ContentName and ContentCulture I want to check if this is the only
record in ContentLocalized for that ContentName.

Can you explain what you mean by "only record in ContentLocalized for that ContentName". Do you mean check if there is only 1 record and delete it? or something else?

|||

I mean that when a record in by27_ContentLocalized is deleted it checks if it is the only one which is related with its parent in by27_Content.

If it is then it deletes also its parent in by27_Content, see?

Thanks,

Miguel

|||

How about adding something like this to the end of the procedure...

IF NOT EXISTS(SELECT * FROM by27_ContentLocalized WHERE ContentId = @.ContentID)
BEGIN
DELETE FROM by27_Content WHERE ContentID = @.ContentID
END

I hope this helps,

Steve

|||You can create a DELETE trigger on dbo.by27_ContentLocalized table, which will check to see whether the deleted row is the only record in ContentLocalized for that ContentName. For example:

CREATE?TRIGGER trg_CheckDeleteCL ON dbo.by27_ContentLocalized AFTER DELETE
AS
SELECT 1 FROM dbo.by27_ContentLocalized b,deleted d
WHERE b.ContentName=d.ContentName
IF(@.@.ROWCOUNT=0)
BEGIN
DECLARE @.msg NVARCHAR(2000)
DELETE dbo.by27_Content FROM dbo.by27_Content c, deleted d
WHERE c.ContentName=d.ContentName
SELECT @.msg='The record with ContentName='''+ContentName+'''deleted from dbo.by27_Content'
FROM deleted
PRINT @.msg
END
go

Delete problem-too many parameters

I have a dataview control with the delete method pointing to a logical delete stored procedure in SQL SERVER Express. I am getting an error message saying too many parameters provided. I've check and there is one parameter expected and one passed in. This is my SP, the html, and the debug infor I'm looking at. Any ideas?

PROCEDUREdbo.usp_Drivers_Delete

@.mintDriver_IDint

AS

UPDATEtblDrivers

SETActive= 0

WHEREDriver_ID=@.mintDriver_ID

html:

<DeleteParameters>

<asp:ControlParameterControlID="GridView1"Name="mintDriver_ID"PropertyName="SelectedValue"

Type="Int32"/>

</DeleteParameters>

Debug:

?SqlDataSourceDrivers.DeleteParameters(0)

{System.Web.UI.WebControls.ControlParameter}

System.Web.UI.WebControls.ControlParameter: {System.Web.UI.WebControls.ControlParameter}

ConvertEmptyStringToNull: True

DefaultValue: Nothing

Direction: Input {1}

Name: "mintDriver_ID"

Size: 0

Type: Int32 {9}

?SqlDataSourceDrivers.DeleteParameters.Count

1

Error:

Exception Details:System.Data.SqlClient.SqlException: Procedure or function usp_Drivers_Delete has too many arguments specified.

Perhaps I'm missing something, but you don't really have a delete. You have an update that sets a status column (Active) to 0. I think if you try changing the <DeleteParameters> to <UpdateParameters> you should be fine.

Deb

delete problem

hi all,
can any one tell me why only 906 rows from the temp table are deleted by this sp:??

create PROCEDURE usp_DelAllPersonalContacts11

AS
begin
declare @.contactid int ,@.tempid int ,@.b int
create table #temp (tempid int identity(1,1),contactid int)

set @.b=2000
while @.b>0
begin
insert into #temp (contactid)
values (@.b)
set @.b=@.b-1

end
select * from #temp
declare user_cursor cursor for (select tempid,contactid from #temp )
open user_cursor

fetch next from user_cursor
into @.tempid,@.contactid

while @.@.fetch_status=0
begin
delete from #temp where contactid=@.contactid
print @.contactid
fetch next from user_Cursor
into @.tempid,@.contactid
end
close user_cursor
deallocate user_cursor

select * from #temp

drop table #temp
endWhen I change it into:

delete from #temp where contactid <= @.contactid
if @.@.rowcount <> 1
begin
select 'RC: ', @.@.rowcount
print @.contactid
end

All rows are deleted, @.@.rowcount <> 1 fires once on @.contactid 2000.

But: my guess is that since the cursor has no order by clause it somewhat randomly puts a hold on a next row (whatever that means):

declare user_cursor cursor for
select tempid,contactid
from #temp
order by tempid

works for me with the contactid = @.contactid