Friday, November 23, 2012

SQL Server Function - SP_RENAME and NEWID

Today, we will have an overview of two SQL Server functions

  • SP_RENAME
  • NEWID

SP_RENAME is used to rename table name or rename any column of the table.
NEWID is used to extract random records from table.

Renaming of Column in Table


Syntax
sp_RENAME 'Tablename.ColumnName','NewColumnName','Column'

I had a table named as Employee_Salary in my SQL Server 2012 under Northwind database. It has four columns ID (Primary Key), Employee_Name,Salary and Sal_Month.
I want to rename column named as 'Employee_Name' to 'Employees_Name'

So, below is the command that needs to be executed

sp_RENAME 'Employee_Salary.Employee_Name','Employees_Name','Column'

Once done, you will see that column name would be updated.


Renaming of Table


We can rename the table with sp_RENAME function provided in SQL Server.
Syntax
sp_RENAME 'TableName' , 'TableNewName'

Below is the command executed

sp_RENAME 'Employee_Salary','Employees_Salary'


NEWID


As told, NEWID() is used to extract random records from the table.
We had table named as Employees_Salary containing employees salary for all the months. Below are the records present in the table

















Below is the query to extract random records


select top 2 * from Employees_Salary order by NEWID()

Below is the data extracted when executed the query













If we execute the above query again below is the data returned












So, you have seen every time we execute the same query we are getting different records from table.

Hope with this article of mine, you have become familiar with very little but important functions of SQL Server.

No comments:

Post a Comment