DBA Diaries

Thoughts and experiences of a DBA working with SQL Server and MySQL

How to Rename a SQL Server Column or Table Using T-SQL

Posted on November 20, 2013 Written by Andy Hayes Leave a Comment

I would typically use Management Studio to rename columns or tables in SQL Server. Afterall, it is an easy thing to do to open up the GUI make your changes and then save them back to the SQL Server.

Have you ever been in a situation where you wanted to make a number of such changes and then later on you needed to repeat those changes on another system?

I was in such a situation recently where due to some application changes, many columns had to be renamed, the application tested and then I had to repeat the procedure on production.

I did not want to have to open up every table in Management Studio and click the save button each time all over again!

I needed something that I could execute quickly, so I prepared a file of T-SQL commands to make my changes in one swift stroke. I achieved it all using sp_rename

T-SQL example – renaming columns and tables

So here we have an example for renaming a column:

EXEC sp_rename 'Table.[OldColumnName]', '[NewColumnName]', '[COLUMN]';

If we wanted to rename a table then we can use:

EXEC sp_rename '[OldTableName]', '[NewTableName]';

Note that the square brackets are not mandatory but are necessary when you have silly database designers who have put such things as hyphens or spaces in their field names. Makes me cringe just thinking about it! 😐

Permissions needed for sp_rename

You need ALTER permission if you want to rename tables or columns.

One final note

You can use sp_rename for renaming other objects besides tables. It can also be used for renaming indexes, constraints, types databases and statistics. More more information on this useful little proc, visit this link

Filed Under: All Articles, SQL Tips and Tricks Tagged With: sql server, t-sql

Differences Between TRUNCATE TABLE and DELETE

Posted on May 19, 2013 Written by Andy Hayes 3 Comments

If you want to remove data from a table, you can do this in a couple of ways using TRUNCATE TABLE or DELETE. A common approach is to use DELETE to remove all rows in the table but TRUNCATE TABLE offers an alternative and I will list what the differences between the two are.

DELETE

--Delete rows with filter
DELETE FROM SchemaName.Table WHERE...

--Delete all rows
DELETE SchemaName.Table

--Delete all rows
DELETE FROM SchemaName.Table

--Delete using JOINS
DELETE T1
FROM SchemaName.Table1 AS T1
JOIN SchemaName.Table2 AS T2 ON T1.Column1 = T2.Column1

--Delete using IN
DELETE FROM SchemaName.Table1
WHERE Column1 IN (SELECT Column1 FROM SchemaName.Table2)

--Delete using EXISTS
DELETE T1
FROM SchemaName.Table1 AS T1
WHERE EXISTS
(SELECT *
FROM SchemaName.Table2 AS T2
WHERE T1.Column1 = T2.Column1)

  • Provides more control over what data is and can be deleted.
  • Will not reseed the identity value on an identity column
  • Can be used where the DELETE operation does not violate foreign key constraint
  • Can be a slow operation if the table is large
  • Locking can be an issue if the operation is removing many rows
  • Will fire triggers
  • Transactions can be rolled back as LSN (log sequence number) is maintained in the transaction log
  • Data pages consumed may need to be reclaimed using a DBCC SHRINKDATABASE operation
  • DELETE will typically consume more transaction log space because of extra logging

TRUNCATE TABLE

TRUNCATE TABLE Schema.TableName;

  • WHERE clause is not optional – it will remove all data from your table
  • Reseeds the identify value of an identity column
  • Cannot be used on a table which is referenced by a foreign key constraint
  • Can be considerably quicker than DELETE due to deallocation of data pages and minimal logging
  • Cannot be used in replication or log shipping
  • Will not fire triggers
  • Cannot be used on tables which are part of an indexed view
  • Who has permission: table owner, sysadmin, db_owner, db_ddladmin or any user with ALTER permission on the table

I wanted to expand on the differences in speed between the two operations.

When TRUNCATE TABLE is issued against a table, all the data pages are deallocated which are used to store the tables data. Compared with a DELETE, this is significantly faster as each DELETE operation is logged in the transaction log but only the deallocations are logged in the transaction log for a TRUNCATE operation.

The DELETE operation will consume database resource and locks and can therefore be considerably slower and have greater impact on your system in comparison to TRUNCATE TABLE. See this post on reducing overhead for large delete operations.

As each DELETE operation is logged inside of the transaction log, it is possible to rollback to a point in time but with TRUNCATE TABLE it is not possible to have this level of precision. In a rollback scenario, only a complete rollback could be performed.

As with a DELETE it is also possible to rollback a TRUNCATE if it has not yet been committed. You can do this by using transactions like in this very simple example:

BEGIN TRAN
TRUNCATE TABLE SchemaName.Table
--test success here
ROLLBACK TRAN
ELSE
COMMIT TRAN

Time to wrap this up..

So there are a number of differences between the two. Both operations have their pros and cons and provide you with a choice over how you want to remove your data.

 

Filed Under: All Articles, SQL Tips and Tricks Tagged With: sql server, t-sql

New T-SQL features in SQL Server 2012 – THROW

Posted on May 6, 2012 Written by Andy Hayes Leave a Comment

sql server 2012 throwNew in SQL Server 2012 as part of exception handling in T-SQL is THROW

Exception handling in previous versions of SQL Server

THROW will raise an exception inside of the catch block and there are already ways to do this in previous versions of SQL Server but where this is an improvement over previous methods is that it simplifies writing the code to raise them.

So lets compare the old and the new.

Here is the T-SQL:

SQL Server 2005/SQL2008

BEGIN TRY
DECLARE @VarToTest INT
SET @VarToTest = 'C'
END TRY
BEGIN CATCH
DECLARE
@ErrorMessage nvarchar(4000)
, @ErrorSeverity int

SET @ErrorMessage = ERROR_MESSAGE()
SET @ErrorSeverity = ERROR_SEVERITY()

RAISERROR (@ErrorMessage, @ErrorSeverity, 1 )
END CATCH

SQL Server 2012

BEGIN TRY
DECLARE @VarToTest INT
SET @VarToTest = 'C'
END TRY
BEGIN CATCH
THROW
END CATCH

Msg 245, Level 16, State 1, Line 4 Conversion failed when converting the varchar value ‘C’ to data type int.

For more information see this link from books online – SQL Server 2012 THROW

Filed Under: All Articles, SQL Tips and Tricks Tagged With: sql server, t-sql

New T-SQL features in SQL Server 2012 – WITH RESULT SETS

Posted on April 21, 2012 Written by Andy Hayes Leave a Comment

sql server 2012 with result setsNew in SQL Server 2012 comes an extension to EXECUTE in the form of WITH RESULT SETS.

WITH RESULT SETS allows column names and their data types to be changed in the result set of a stored procedure.

My first thought with this improvement is that it could be very useful to have when building SSIS packages which read from a stored procedure as a data source. We’ll take a look at that in a future post but in addition to that, it helps to replace some of the following…

Before Server 2012 WITH RESULT SETS you had to…

If you wanted to change the column names and their data types after executing a stored procedure, then in previous versions there were a few things to try.

  1. Create a copy of the stored procedure and change it to return different column names or data types.
  2. Execute the stored procedure and insert the results into a temporary table, then read from the temporary table.
  3. Edit the same stored procedure and change its output.
  4. Create a UDF and select from that.

Oh dear, not good. 😐

Some of the issues which spring to mind with those points are code duplication, sub-optimal performance because of the use of temp tables and just hassle in writing lengthy code. I’m going to try and look at some of these in a future post.

So lets check WITH RESULT SETS syntax

To get it working you supply WITH RESULT SETS and parentheses followed by the column names and data types as follows:

EXEC Your_Stored_Procedure
WITH RESULT SETS
(
(Col1_Renamed INT,
Col2_Renamed VARCHAR(50))
)

If your stored procedure is returning multiple result sets then it is possible to manipulate all of them. For example:

EXEC Your_Other_Stored_Procedure
WITH RESULT SETS
(
(Col1_Renamed INT,
Col2_Renamed VARCHAR(50)),
(Col3_Renamed TINYINT,
Col4_Renamed NVARCHAR(100))
)

Please note that the number of columns being returned in the result set cannot be changed.

Lets look at a demo of it in action against the AdventureWorks2012 database. First, I will create a new stored procedure…

CREATE PROCEDURE GetCustomerOrders @CustomerID INT
AS

SELECT
SalesOrderID
, OrderDate
FROM Sales.SalesOrderHeader
WHERE CustomerID = @CustomerID

Now, I’m going to execute it and use the WITH RESULT SETS to change the output.

EXEC GetCustomerOrders @CustomerID = 11000
WITH RESULT SETS
(
(OrderID INT,
DateOfOrder VARCHAR(20))
)

Which returns…

OrderID     DateOfOrder
----------- --------------------
43793       Jul 22 2005 12:00AM
51522       Jul 22 2007 12:00AM
57418       Nov  4 2007 12:00AM

(3 row(s) affected)

Without the WITH RESULT SETS it looks like this

SalesOrderID OrderDate
------------ -----------------------
43793        2005-07-22 00:00:00.000
51522        2007-07-22 00:00:00.000
57418        2007-11-04 00:00:00.000

(3 row(s) affected)

WITH RESULT SETS conclusion

Another nice addition to the T-SQL features in SQL Server 2012 which helps to streamline code when formatting result sets produced by stored procedures.

Anything which makes life more simple is always welcome 🙂

If you want more information click this link on SQL Server 2012 WITH RESULT SETS

Filed Under: All Articles, SQL Tips and Tricks Tagged With: sql server 2012, t-sql

  • « Previous Page
  • 1
  • 2
  • 3
  • 4
  • 5
  • Next Page »

Categories

  • All Articles (82)
  • Career Development (8)
  • MySQL Administration (18)
  • MySQL Performance (2)
  • SQL Server Administration (24)
  • SQL Server News (3)
  • SQL Server Performance (14)
  • SQL Server Security (3)
  • SQL Tips and Tricks (19)

Top 10 Popular Posts

  • Using sp_change_users_login to fix SQL Server orphaned users
  • How to shrink tempdb
  • MySQL SHOW USERS? – How to List All MySQL Users and Privileges
  • How to Transfer Logins to Another SQL Server or Instance
  • How to Delete Millions of Rows using T-SQL with Reduced Impact
  • T-SQL – How to Select Top N Rows for Each Group Using ROW_NUMBER()
  • New T-SQL features in SQL Server 2012 – OFFSET and FETCH
  • How to Kill All MySQL Processes For a Specific User
  • Using exec sp_who2 to help with SQL Server troubleshooting
  • How to move tempdb

Recent Posts

  • How to Setup MySQL Master Master Replication
  • How To Use SQL to Convert a STRING to an INT
  • How to set up MySQL Replication Tutorial
  • How to Use SQL CASE for Conditional Logic in Your SQL Queries
  • Using ISNULL in SQL Server to Replace NULL Values

Search

Connect

  • Twitter
  • Facebook
  • Google+
  • RSS

About

  • Cookie Policy
  • Disclaimer
  • About
Copyright © ‘2021’ DBA Diaries built on the Genesis Framework

This site uses cookies. We assume you are happy with cookies but click the link if you are not. Close