Showing posts with label t-sql. Show all posts
Showing posts with label t-sql. Show all posts

Monday, December 21, 2015

Mejoras de T-SQL en SQL Server 2016 - DROP IF EXISTS

Mirando algunas de las mejoras introducidas con SQL Server 2016 encontré una que es realmente muy interesante y útil. Se ha introducido en T-SQL un constructor que se ha estado solicitando hace mucho tiempo.

Generalmente cuando empezamos con un script, particularmente cuando queremos hacer una demo, lo que hacemos es chequear si los objectos existen para luego borrarlos y finalmente crearlos nuevamente

-- Casos tipicos
IF OBJECT_ID('[dbo].[MiTabla]', 'U') IS NOT NULL
       DROP TABLE [dbo].[MiTabla];
-- Otra opción
IF EXISTS (SELECT * FROM sys.procedures WHERE name = 'SP_DBA_MyStoreProc')

       DROP PROCEDURE SP_DBA_MyStoreProc

Ahora con SQL Server 2016 podemos hacer lo siguiente

DROP TABLE IF EXISTS [dbo].[MiTabla];
DROP PROCEDURE IF EXISTS [SP_DBA_MyStoreProc];

La parte interesante es que si el objecto no existe no mostrará ningún mensaje de error

Seguramente lo van a empezar a utilizar a la brevedad porque es un constructor muy útil

El mismo constructor esta disponible para otros objectos

  • AGGREGATE
  • PROCEDURE
  • TABLE
  • ASSEMBLY
  • ROLE
  • TRIGGER
  • VIEW
  • RULE
  • DATABASE
  • SCHEMA_USER
  • DEFAULT
  • SECURITY POLICY
  • FUNCTION
  • SEQUENCE
  • INDEX
  • TYPE
  • SYNONYM

También se puede utilizar para columnas y/o contraints

ALTER TABLE [dbo].[MiTabla] DROP CONSTRAINT IF EXISTS MT_column_pk;
ALTER TABLE [dbo].[MiTabla] DROP COLUMN IF EXISTS ID;


Thursday, February 14, 2013

Monitoring Disk space using T-SQL and Powershell

UPDATE: New version with bug fixes. Now works on named instances !! (2014-10-14)

Hello everybody,

Here is a handy script that allows you to get disks information using T-SQL and Powershell. It is useful to monitor the free space on each disk so we can create a sql job to run it periodically and send out a notification when space is getting low

Here is the script


USE master
GO
SET NOCOUNT ON
declare @svrName varchar(255)
declare @sql varchar(400)
--by default it will take the current server name, we can the set the server name as well
set @svrName = cast(SERVERPROPERTY ('ComputerNamePhysicalNetBIOS') as varchar(255))
set @sql = 'powershell.exe -c "Get-WmiObject -ComputerName ' + QUOTENAME(@svrName,'''') + ' -Class Win32_Volume -Filter ''DriveType = 3'' | select name,capacity,freespace,Label | foreach{$_.name+''|''+$_.capacity/1048576+''%''+$_.freespace/1048576+''&''+$_.label+''*''}"'
--creating a temporary table
DECLARE @output TABLE
(line varchar(255))
--inserting disk name, total space and free space value in to temporary table
insert @output
EXEC xp_cmdshell @sql

DECLARE @DISKS TABLE(
id int identity
,[DiskName] varchar(10)
,[Capacity(MB)] bigint
,[FreeSpace(MB)] bigint
,[Label] varchar(200)
)

INSERT INTO @DISKS
select rtrim(ltrim(SUBSTRING(line,1,CHARINDEX('|',line) -1))) as drivename
      ,round(cast(rtrim(ltrim(SUBSTRING(line,CHARINDEX('|',line)+1,      (CHARINDEX('%',line) -1)-CHARINDEX('|',line)) )) as Float),0) as 'capacity(MB)'
      ,round(cast(rtrim(ltrim(SUBSTRING(line,CHARINDEX('%',line)+1,      (CHARINDEX('&',line) -1)-CHARINDEX('%',line)) )) as Float),0) as 'freespace(MB)'
      ,rtrim(ltrim(SUBSTRING(line,CHARINDEX('&',line)+1,      (CHARINDEX('*',line) -1)-CHARINDEX('&',line)) )) as 'Label'
from @output
where line like '[A-Z][:]%'
order by drivename


select *
,[Capacity(MB)]/1024 as [Capacity(GB)],[FreeSpace(MB)]/1024 as [FreeSpace(GB)]

,round( [FreeSpace(MB)]*100/[Capacity(MB)],2) as [% Free]