Showing posts with label sql server. Show all posts
Showing posts with label sql server. Show all posts

TSQL: Rename Tables or Columns

To rename a table:
EXEC sp_rename @objname='{TableName}', @newname='{NewTableName}', @objtype='TABLE'

To rename a column:
EXEC sp_rename @objname='{TableName}.{ColumnName}', @newname='{NewColumnName}', @objtype='COLUMN'

Note: you may refrain from specifying the Stored Procedure's parameters (@objname, @newname, @objtype) if you will specify the input in the proper order as specified above. Thus:

To rename a table:
EXEC sp_rename '{TableName}', '{NewTableName}', 'TABLE'

To rename a column:
EXEC sp_rename '{TableName}.{ColumnName}', '{NewColumnName}', 'COLUMN'

T-SQL SELECT Random Rows in UNION

To Select random rows from a Table, use the ORDER BY NEWID()

SELECT * FROM Table ORDER BY NEWID();

SELECT TOP 10 PERCENT * FROM Table ORDER BY NEWID();

SELECT TOP 10 * FROM Table ORDER BY NEWID();
To Select random rows from a Table UNION Table, then do:

SELECT * FROM (SELECT TOP 10 Column1, Column2, Column 3 FROM Table1 ORDER BY NEWID()) TableA
UNION
SELECT * FROM (SELECT TOP 10 Column1, Column2, Column3 FROM Table2 ORDER BY NEWID()) TableB;

Create Stored Procedure IF NOT EXISTS (SQL Server)

This is especially useful if you're writing update scripts like I am.

IF NOT EXISTS(Select * from sysobjects where name = 'usp_UserSproc')
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE usp_UserSproc
(
@ID int = NULL --nullable input
)

AS
BEGIN
SET NOCOUNT ON;
IF @ID IS NOT NULL
SELECT * FROM My_Table WHERE ID=@ID;
ELSE
SELECT * FROM My_Table WHERE ID=1;
END';
END