SQL Server - Cursor Syntax

by Administrator 1. February 2010 21:54

 -- Variables to hold the data


 DECLARE @Var1 int
 DECLARE @Var2 datetime

 -- CURSOR


 DECLARE db_cursor CURSOR FOR 
 SELECT  Col1,
Col2
 FROM Table1

 OPEN db_cursor  
 FETCH NEXT FROM db_cursor INTO @Var1 , @Var2

 WHILE @@FETCH_STATUS = 0  
 BEGIN   
  -- DO STUFF HERE

  
  FETCH NEXT FROM db_cursor INTO @Var1 , @Var2 
 END  

 CLOSE db_cursor  
 DEALLOCATE db_cursor

 

 

 

 

 

SQL Server - Add multiple email addresses for an operator

by Administrator 10. November 2009 00:00

SQLServer Agent Jobs can only have one operator defined under the notifications section so what do you do if you want to send notification emails to more than one person? You could set up a distribution list within your email system but a simpler approach is simply to semi-colon separate the list of email addresses. 

Its as simple as that ! Just make sure you have enabled your alerting for the SQL Server Agent and configured database correctly and away you go

 

 

SQL Server - Try Catch Statement Syntax

by Administrator 8. October 2009 21:39

I'm sure there are more complexities to this - but this seems to work well in most applications

BEGIN TRY


 BEGIN TRANSACTION
 
 -- Do whatever you need to do
 

 COMMIT TRANSACTION


END TRY


BEGIN CATCH


 -- Rollback if in a transaction


 IF @@TRANCOUNT > 0 ROLLBACK TRANSACTION
 
 -- Do whatever error logging you need to do


END CATCH

 

SQL Server - Send Email Using Database Mail From TSQL or Stored Procedure

by Administrator 8. October 2009 18:28

Pretty simple stuff. This assumes that a valid database account etc. is set up and Database Mail is configured correctly

EXECUTE msdb.dbo.sp_send_dbmail @recipients='to@xxx.com',
@subject = 'Test email',
@body = 'Test email body',
@reply_to='from@yyy.com'

SQL Server - Check if variable or column is numeric

by Administrator 7. October 2009 18:39

The simplest way to check if a value is numeric is to use the 'ISNUMERIC' function

-- This returns 1

select ISNUMERIC('1.1')

-- This returns 1

select ISNUMERIC('12')

-- This returns 0

select ISNUMERIC('aaaa')

SQL Server - Force Database Log File Shrink

by Administrator 6. October 2009 20:51

 

USE DATABASENAME
GO
DBCC SHRINKFILE(LOGNAME, 1)
BACKUP LOG DATABASENAME WITH TRUNCATE_ONLY
DBCC SHRINKFILE(LOGNAME, 1)

SQL Server - Change Table Collation

by Administrator 5. October 2009 20:50

Handy script to change the collation of all tables within a database. 

  • Change the database collation itself via the management console
  • Note that you'll need to drop any indexes on the columns you are changing. I normally just script the indexes out, run this script and recreate the indexes

-- =============================================
-- Script to reset COLLATE to database default
-- =============================================


declare @to_collation nvarchar(255)
select  @to_collation = 'Latin1_General_CI_AI'

declare @dbname nvarchar(255)
set @dbname=db_name()
PRINT('ALTERING DATABASE ' + @dbname + ' TO COLLATION '+ @to_collation)

DECLARE COL_CURSOR CURSOR READ_ONLY FOR
select table_schema, table_name, column_name,
column_default, is_Nullable, Data_type,
character_maximum_length, collation_name
from information_schema.columns
INNER JOIN
(SELECT TABLE_NAME TN FROM
information_schema.tables where TABLE_TYPE='BASE TABLE' ) IT ON (TABLE_NAME=TN)
where (Data_type LIKE  '%char%' OR Data_type LIKE '%text%')
AND collation_name <> @to_collation

DECLARE @table_schema varchar(10), @table_name varchar(100), @column_name varchar(100),
@column_default varchar(100), @is_Nullable varchar(5), @Data_type varchar(100),
@character_maximum_length varchar(10), @columncollation varchar(200)

DECLARE @Execstr VARCHAR(2000)
OPEN COL_CURSOR
FETCH NEXT FROM COL_CURSOR INTO @table_schema, @table_name, @column_name,
@column_default, @is_Nullable, @Data_type,
@character_maximum_length, @columncollation
WHILE (@@fetch_status <> -1)
BEGIN
 IF (@@fetch_status <> -2)
 BEGIN
  SET @Execstr = 'ALTER TABLE ' + @table_schema + '.' + @table_name
    + ' ALTER COLUMN [' + @column_name  + '] ' + @Data_type
    
  IF @Data_type <> 'ntext' and @Data_type <> 'text' BEGIN  
   SET @Execstr = @Execstr + ' ('
    +  case when @character_maximum_length = -1 then 'MAX' else @character_maximum_length end
    + ') '
  END
  
  SET @Execstr = @Execstr + ' COLLATE ' + @to_collation
        + CASE WHEN @is_Nullable='no'  THEN  ' NOT NULL' ELSE ' NULL ' END  
    
  
  EXEC (@Execstr)

  PRINT ('Executing -->' + @Execstr )
  PRINT ('--Orig COLLATION WAS -->' + @columncollation )

 END
 FETCH NEXT FROM COL_CURSOR INTO @table_schema, @table_name, @column_name,
 @column_default, @is_Nullable, @Data_type,
 @character_maximum_length, @columncollation
END
CLOSE COL_CURSOR
DEALLOCATE COL_CURSOR
GO

 

 

 

SQL Server - Get table storage and row count for all tables

by Administrator 24. September 2009 21:59

This simple script returns a list of tables, their row counts and storage usage

DECLARE @Table VARCHAR(255)   
CREATE TABLE #Results
(
    [Table Name] varchar(100),
    [Number of Rows] varchar(100),
    [Size Reserved] varchar(50),
    [Size Data] varchar(50),
    [Size Indexes] varchar(50),
    [Size Unused] varchar(50)
)

 

-- Get all user tables

DECLARE cursorTableList CURSOR
FOR SELECT [name]
 FROM dbo.[sysobjects]
 WHERE  OBJECTPROPERTY(id, N'IsUserTable') = 1
FOR READ ONLY


OPEN cursorTableList
FETCH NEXT FROM cursorTableList INTO @Table

WHILE (@@Fetch_Status >= 0)
BEGIN
    INSERT  #Results EXEC sp_spaceused @Table
    FETCH NEXT FROM cursorTableList INTO @Table
END

CLOSE cursorTableList
DEALLOCATE cursorTableList

-- RETURN RESULTS

SELECT * FROM #Results
DROP TABLE #Results

GO

 

 

 

SQL Server - Move tables between schemas

by Administrator 23. September 2009 22:45

Ever needed to move or transfer tables or stored procedures (and presumably other database objects) from one schema to another? Then this is the command you need.

ALTER SCHEMA DestinationSchema TRANSFER SourceSchema.ObjectToMove