Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
How-To’s
5) How to get the Rowcount as well as Error at the same time ...................... 5
Mango
Banana
Peach
Grapes
Strawberry
To write a string (like comments, etc.) you can use this code :-
Go
You can raise this message from your code like this :-
IF @@Error <> 0
RAISERROR
4
Begin Transaction
Update Orders
Set OrderDate = GetDate()
Where CustomerId = @CustomerId
IF @@Error <> 0
Begin
Raiserror('Failed
to update Orders',16,1)
Rollback
Transaction
End
Commit Transaction
But what if you also want to get the number of records which
were effected by this query? If you do a @@Rowcount after your
Error checking statement then you are going to get 0 as the
value of @@Recordcount would have been reset. And if you place
@@Recordcount before the error-checking statement then your
@@Error would get reset. So what's the solution to get both of
them at the same time ? Save both the values in a local variable
and then check that local variable. Here's how it can be done.
SET @Rcount = 0
SET @ErrNum = 0
5
Begin Transaction
Update Orders
Set OrderDate = GetDate()
Where CustomerId = @CustomerId
Commit Transaction
The syntax :-
EXECUTE sp_executesql
@SQLString,
@ParmDefinition,
@parm=@parmIN,
@parm1OUT=@parmRET1 OUTPUT,@parm2OUT=@parmRET2 OUTPUT
Example :-
DECLARE @IntVariable INT
DECLARE @SQLString nVARCHAR(500)
DECLARE @ParmDefinition nVARCHAR(500)
DECLARE @Lastlname nVARCHAR(30)
a) Using sp_rename
» Make sure that no user is using the database.
» Make the database in the single user mode. You can do this
by using sp_dboption.
sp_dboption 'Pubs', 'single user', true
» sp_rename Pubs, Library, Database
Note : For renaming the database, you can also use sp_renamedb.
sp_renamedb Pubs, Library
» Bring back the database in multiuser mode
sp_dboption 'Library', 'single user', false
b) Using Detach & Attach
sp_detach_db @dbname = N'Pubs'
10
11
IF @@Error <> 0
Raiserror('Failed to rename Table Sales to Orders',16,1)
ELSE
Print 'Table Sales Renamed to Orders'
END
12
IF @@Error <> 0
Raiserror('Failed to rename column Qty to Quantity',16,1)
ELSE
Print 'Column Qty Renamed to Quantity'
END
ELSE
Print 'Column Quantity already exists'
GO
IF @@Error <> 0
Raiserror('Failed to rename PK UPKCL_sales to PK_Orders',16,1)
ELSE
Print 'PK UPKCL_sales Renamed to PK_Orders'
END
ELSE
Print 'PK UPKCL_sales does not exist'
GO
IF @@Error <> 0
Raiserror('Failed to rename FK FK__Titleauth__au_id__164452b1 to
FK_Titleauthor_Author_auid',16,1)
ELSE
Print 'FK FK__Titleauth__au_id__164452b1 Renamed to
FK_Titleauthor_Author_auid'
END
ELSE
Print 'FK FK__Titleauth__au_id__164452b1 does not exist'
GO
IF @@Error <> 0
Raiserror('Failed to rename Default DF_Orders to
DF_Orders_Ord_Date',16,1)
ELSE
Print 'Default DF_Orders Renamed to DF_Orders_Ord_Date'
END
ELSE
Print 'Default DF_Orders does not exist'
GO
14