Saturday, October 12, 2013
Truncate logs on all databases with recovery mode of simple
declare @tblSqlCode dbo.ExecSqlStatementsTableType
insert into @tblSqlCode(SqlCode)
SELECT
'use ' + d.name + ';' + CHAR(10)
+ 'Checkpoint;' + CHAR(10)
+ 'DBCC SHRINKFILE([' + mf.name + ']);' + CHAR(10)
FROM
[sys].[databases] d
JOIN [sys].[master_files] mf
ON d.database_id = mf.database_id
WHERE
d.recovery_model = 3 -- simple
AND d.[state] = 0 -- online
AND mf.state = 0 -- online
AND mf.type = 1 -- log
AND d.is_read_only = 0
AND d.name NOT IN ('master', 'tempdb', 'model', 'msdb')
--SELECT * FROM @tblSqlCode
exec dbo.usp_ExecSqlStatements @TableSqlCode=@tblSqlCode, @UseTransactions=0
Saturday, October 5, 2013
Execute a series of SQL statements
GO
/****** Object: StoredProcedure [dbo].[usp_ExecSqlStatements] Script Date: 10/4/2013 8:03:28 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TYPE [dbo].[ExecSqlStatementsTableType] AS TABLE(
[RowId] [int] IDENTITY(1,1) NOT NULL,
[SqlCode] [nvarchar](max) NOT NULL
)
GO
/*
declare @tblSqlCode dbo.ExecSqlStatementsTableType
insert into @tblSqlCode(SqlCode)
values('print ''task 1'''), ('print ''task 2''')
exec dbo.usp_ExecSqlStatements @TableSqlCode=@tblSqlCode
*/
ALTER proc [dbo].[usp_ExecSqlStatements](
@TableSqlCode dbo.ExecSqlStatementsTableType READONLY
,@verbose bit = 0
,@ExecSql bit = 1
,@UseTransactions BIT = 1
)
as
-- ************************************************************************************************
-- ************************************************************************************************
set nocount on
SET XACT_ABORT ON
-- ************************************************************************************************
-- ************************************************************************************************
-- ************************************************************************************************
declare @MaxRows int
declare @row int
declare @sql nvarchar(max)
DECLARE @ErrorMessage NVARCHAR(max);
DECLARE @ErrorSeverity INT;
DECLARE @ErrorState INT;
-- ************************************************************************************************
-- ************************************************************************************************
-- ************************************************************************************************
select
@row = min(RowId)
,@MaxRows = max(RowId)
from
@TableSqlCode
-- ************************************************************************************************
while @row <= @MaxRows
begin
select
@sql = SqlCode
from
@TableSqlCode
where
RowId = @row
if @sql is not null
begin
if @verbose=1
begin
print @sql
end
if @ExecSql=1
BEGIN
BEGIN TRY
IF @UseTransactions = 1
BEGIN TRAN
exec sp_executesql @sql
IF @UseTransactions = 1
COMMIT tran
END TRY
BEGIN CATCH
SET @ErrorMessage = 'ErrorMessage=[' + ERROR_MESSAGE() + ']' + CHAR(10)
+ 'ErrorSeverity=[' + CAST(ERROR_SEVERITY() AS NVARCHAR(MAX)) +']' + NCHAR(10)
+ 'ErrorState=[' + CAST(ERROR_STATE() AS NVARCHAR(MAX)) + ']' + NCHAR(10)
+ 'SqlCode=' + NCHAR(10)
+ @sql
IF @@TRANCOUNT > 0 AND @UseTransactions = 1
begin
ROLLBACK TRAN
end
RAISERROR(@ErrorMessage, 9, 1)
END CATCH
end
end
set @row = @row +1
end
/****** Object: StoredProcedure [dbo].[usp_ExecSqlStatements] Script Date: 10/4/2013 8:03:28 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TYPE [dbo].[ExecSqlStatementsTableType] AS TABLE(
[RowId] [int] IDENTITY(1,1) NOT NULL,
[SqlCode] [nvarchar](max) NOT NULL
)
GO
/*
declare @tblSqlCode dbo.ExecSqlStatementsTableType
insert into @tblSqlCode(SqlCode)
values('print ''task 1'''), ('print ''task 2''')
exec dbo.usp_ExecSqlStatements @TableSqlCode=@tblSqlCode
*/
ALTER proc [dbo].[usp_ExecSqlStatements](
@TableSqlCode dbo.ExecSqlStatementsTableType READONLY
,@verbose bit = 0
,@ExecSql bit = 1
,@UseTransactions BIT = 1
)
as
-- ************************************************************************************************
-- ************************************************************************************************
set nocount on
SET XACT_ABORT ON
-- ************************************************************************************************
-- ************************************************************************************************
-- ************************************************************************************************
declare @MaxRows int
declare @row int
declare @sql nvarchar(max)
DECLARE @ErrorMessage NVARCHAR(max);
DECLARE @ErrorSeverity INT;
DECLARE @ErrorState INT;
-- ************************************************************************************************
-- ************************************************************************************************
-- ************************************************************************************************
select
@row = min(RowId)
,@MaxRows = max(RowId)
from
@TableSqlCode
-- ************************************************************************************************
while @row <= @MaxRows
begin
select
@sql = SqlCode
from
@TableSqlCode
where
RowId = @row
if @sql is not null
begin
if @verbose=1
begin
print @sql
end
if @ExecSql=1
BEGIN
BEGIN TRY
IF @UseTransactions = 1
BEGIN TRAN
exec sp_executesql @sql
IF @UseTransactions = 1
COMMIT tran
END TRY
BEGIN CATCH
SET @ErrorMessage = 'ErrorMessage=[' + ERROR_MESSAGE() + ']' + CHAR(10)
+ 'ErrorSeverity=[' + CAST(ERROR_SEVERITY() AS NVARCHAR(MAX)) +']' + NCHAR(10)
+ 'ErrorState=[' + CAST(ERROR_STATE() AS NVARCHAR(MAX)) + ']' + NCHAR(10)
+ 'SqlCode=' + NCHAR(10)
+ @sql
IF @@TRANCOUNT > 0 AND @UseTransactions = 1
begin
ROLLBACK TRAN
end
RAISERROR(@ErrorMessage, 9, 1)
END CATCH
end
end
set @row = @row +1
end
Monday, September 30, 2013
Using DMX to flatten MDX result sets
http://blogs.msdn.com/b/jamiemac/archive/2008/03/10/unwinding-mdx-flattening-semantics-with-dmx.aspx
SELECT t.* FROM [Customer Tree]
NATURAL PREDICTION JOIN
(SELECT {Measures.[Measures].[Reseller Sales Amount] *
[Product].[Category].MEMBERS} ON COLUMNS,
{[Date].[Month]} ON ROWS
FROM [Adventure Works]) AS t
SELECT t.* FROM [Customer Tree]
NATURAL PREDICTION JOIN
(SELECT {Measures.[Measures].[Reseller Sales Amount] *
[Product].[Category].MEMBERS} ON COLUMNS,
{[Date].[Month]} ON ROWS
FROM [Adventure Works]) AS t
Tuesday, August 20, 2013
Copy latest file in folder
FOR /F %%I IN ('DIR *.bak /B /O:-D') DO COPY %%I \\server\SqlBackup\Foo.bak & EXIT
Friday, July 19, 2013
MDX query to list all dimension attributes
/*
http://msdn.microsoft.com/en-us/library/ms126309.aspx
http://ssas-wiki.com/w/Articles#DMV_.28Dynamic_Management_View.29
http://dwbi1.wordpress.com/2010/01/01/ssas-dmv-dynamic-management-view/
http://www.ssas-info.com/analysis-services-faq/80-ssas-2008-dmvs/1342-analysis-services-2008-systemmdschema-dmvs-
*/
select
Property_Name
,Property_Caption
,*
from
$SYSTEM.MDSCHEMA_PROPERTIES
where
Property_Type = 1
and Cube_Name = 'The name of your cube'
http://msdn.microsoft.com/en-us/library/ms126309.aspx
http://ssas-wiki.com/w/Articles#DMV_.28Dynamic_Management_View.29
http://dwbi1.wordpress.com/2010/01/01/ssas-dmv-dynamic-management-view/
http://www.ssas-info.com/analysis-services-faq/80-ssas-2008-dmvs/1342-analysis-services-2008-systemmdschema-dmvs-
*/
select
Property_Name
,Property_Caption
,*
from
$SYSTEM.MDSCHEMA_PROPERTIES
where
Property_Type = 1
and Cube_Name = 'The name of your cube'
Saturday, April 27, 2013
drop empty table
EXEC sp_msforeachtable 'IF NOT EXISTS(SELECT TOP 1 1 FROM ?) BEGIN PRINT ''drop table ?'' end'
Friday, April 26, 2013
Execute a series of SQL commands
CREATE TYPE [dbo].[ExecSqlStatementsTableType] AS TABLE(
[RowId] [int] IDENTITY(1,1) NOT NULL,
[SqlCode] [nvarchar](max) NOT NULL
)
go
/*
declare @tblSqlCode dbo.ExecSqlStatementsTableType
insert into @tblSqlCode(SqlCode)
values('print ''task 1'''), ('print ''task 2''')
exec util.usp_ExecSqlStatements @TableSqlCode=@tblSqlCode
*/
CREATE proc [util].[usp_ExecSqlStatements](
@TableSqlCode dbo.ExecSqlStatementsTableType READONLY
,@verbose bit = 0
,@ExecSql bit = 1
)
as
-- ************************************************************************************************
-- ************************************************************************************************
set nocount on
-- ************************************************************************************************
-- ************************************************************************************************
-- ************************************************************************************************
declare @MaxRows int
declare @row int
declare @sql nvarchar(max)
-- ************************************************************************************************
-- ************************************************************************************************
-- ************************************************************************************************
select
@row = min(RowId)
,@MaxRows = max(RowId)
from
@TableSqlCode
-- ************************************************************************************************
while @row <= @MaxRows
begin
select
@sql = SqlCode
from
@TableSqlCode
where
RowId = @row
if @sql is not null
begin
if @verbose=1
begin
print @sql
end
if @ExecSql=1
begin
exec sp_executesql @sql
end
end
set @row = @row +1
end
Friday, March 29, 2013
Thursday, March 21, 2013
Friday, March 8, 2013
split strings into rows of characters
ALTER FUNCTION [dbo].[fn_CharSplit4K](
@pString NVARCHAR(4000)
)
--WARNING!!! DO NOT USE MAX DATA-TYPES HERE! IT WILL KILL PERFORMANCE!
-- From the article: http://www.sqlservercentral.com/articles/Tally+Table/72993/
RETURNS TABLE WITH SCHEMABINDING AS
RETURN
select
row_number() over(order by tl.N) as ItemNumber
,substring(@pString, tl.N, 1) as Item
from
dbo.TallyLarge tl with(nolock)
where
tl.N <= len(@pString)
SQL abbreviated name from camel casing
/*
-- returns 'mtc' since the uppercase letters are M, T, C
select misc.fn_AbrvNameFromCamelCasing('MyTestCase')
*/
alter function misc.fn_AbrvNameFromCamelCasing(
@pString NVARCHAR(4000)
)
returns NVARCHAR(max)
as
begin
return (
SELECT
lower((
SELECT [text()]= ISNULL(q.Item, '')
FROM
(
select
cs.Item
from
dbo.fn_CharSplit4K(@pString) cs
where
cs.Item = upper(cs.Item) Collate SQL_Latin1_General_CP1_CS_AS
) q
FOR XML PATH('')
)) AS AbrvName
)
end
Friday, March 1, 2013
Foreign Keys without Indexes
http://www.sqlservercentral.com/scripts/Administration/68357/
/*
*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=
Util_FKsWithoutIndexes
By Jesse Roberge - YeshuaAgapao@Yahoo.com
Searches for foreign key constraints that don't have fully matching indexes.
The best partial matching indexes are outputted with MatchCounts and column comparisons
Generates a CREATE INDEX template for each foreign-key with no matching index or a partial-matching index.
Customize as needed (add includes, if you want it clustered, or if it should be a part of the primary key, or if you want to merge with another index)
FKs missing full matching indexes can severely hurt the performance of DELETES on the referenced table due to table-scans for checking referential integrity,
as well as SELECTS on the referencing tables where the foreign-key column(s) are in the WHERE or JOIN predicates (This will affect you whether a constraint exists or not).
This only checks the first N columns of the index where N is the number of columns in the foreign key constraint.
Index column order is not verified beyond this (A two-col FK that has 1 matching column in the 2nd col of a 3-col index will be outputted as a partial match)
If your database has no foreign key constraints, then this tool will be worthless to you.
Many databases have partial foreign key constraint coverage. This only works on related tables where constraints are declared.
Required Input Parameters:
None
Optional Input Parameters:
@Delimiter VarChar(1)=’,’
Usage:
EXECUTE dbo.Util_FKsWithoutIndexes
Copyright:
Licensed under the L-GPL - a weak copyleft license - you are permitted to use this as a component of a proprietary database and call this from proprietary software.
Copyleft lets you do anything you want except plagiarize, conceal the source, or prohibit copying & re-distribution of this script/proc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
see
*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=
*/
ALTER PROCEDURE [dbo].[Util_FKsWithoutIndexes]
@Delimiter VarChar(1)=','
AS
SELECT
-- parentschemas.schema_id AS ReferencingSchemaID
--, parentschemas.name AS ReferencingSchemaName
--, parentobjects.object_id AS ReferencingTableID
parentobjects.name AS ReferencingTableName
--, referencedschemas.schema_id AS ReferencedSchemaID
--, referencedschemas.name AS ReferencedSchemaName
--, referencedobjects.object_id AS ReferencedTableID
, referencedobjects.name AS ReferencedTableName
, objects.object_id AS FKConstraintID
, objects.name AS FKConstraintName
, FKTotal.FKColumnCount
, FKMatch.index_id AS PartialMatchIndexID
, indexes.name AS PartialMatchIndexName
, FKMatch.IndexColumnMatchCount
, foreign_key_columns.foreign_key_columns
, index_columns.index_columns_key
, index_columns.index_columns_include
, 'CREATE NONCLUSTERED INDEX IX_' + parentobjects.name + '_' + REPLACE(foreign_key_columns.foreign_key_columns, ', ', '_') + ' ON ' + parentschemas.name + '.' + parentobjects.name + ' (' + foreign_key_columns.foreign_key_columns + ')' AS FKIndexCreate
-- 'CREATE NONCLUSTERED INDEX IX__' + parentschemas.name + '_' + parentobjects.name + '__' + REPLACE(foreign_key_columns.foreign_key_columns, ', ', '_') + ' ON ' + parentschemas.name + '.' + parentobjects.name + ' (' + foreign_key_columns.foreign_key_columns + ')' AS FKIndexCreate
FROM
(
SELECT foreign_key_columns.constraint_object_id, MAX(referenced_object_id) AS referenced_object_id, COUNT(*) AS FKColumnCount
FROM sys.foreign_key_columns
GROUP BY foreign_key_columns.constraint_object_id
) AS FKTotal
JOIN sys.objects ON FKTotal.constraint_object_id=objects.object_id
JOIN sys.objects AS parentobjects ON objects.parent_object_id=ParentObjects.object_id
JOIN sys.schemas AS parentschemas ON parentobjects.schema_id=parentschemas.schema_id
JOIN sys.objects AS referencedobjects ON FKTotal.referenced_object_id=referencedObjects.object_id
JOIN sys.schemas AS referencedschemas ON referencedobjects.schema_id=referencedschemas.schema_id
OUTER APPLY (
SELECT constraint_object_id, index_id, index_object_id, IndexColumnMatchCount
FROM
(
SELECT
foreign_key_columns.constraint_object_id, index_columns.index_id, MAX(index_columns.object_id) AS index_object_id,
COUNT(*) AS IndexColumnMatchCount,
ROW_NUMBER() OVER (PARTITION BY foreign_key_columns.constraint_object_id ORDER BY COUNT(*) DESC) AS IndexColumnMatchCountRowNumber
FROM
sys.foreign_key_columns
JOIN sys.index_columns ON
index_columns.object_id=foreign_key_columns.parent_object_id
AND index_columns.column_id=foreign_key_columns.parent_column_id
WHERE
index_columns.is_included_column=0
AND index_columns.key_ordinal<=FKTotal.FKColumnCount
AND FKTotal.constraint_object_id=foreign_key_columns.constraint_object_id
GROUP BY foreign_key_columns.constraint_object_id, index_columns.index_id
) AS FKMatch
WHERE IndexColumnMatchCountRowNumber=1
) AS FKMatch
LEFT OUTER JOIN sys.indexes ON FKMatch.index_object_id=indexes.object_id AND FKMatch.index_id=indexes.index_id
CROSS APPLY (
SELECT
LEFT(index_columns_key, LEN(index_columns_key)-1) AS foreign_key_columns
FROM
(
SELECT
(
SELECT columns.name + @Delimiter + ' '
FROM
sys.foreign_key_columns
JOIN sys.columns ON
foreign_key_columns.parent_column_id=columns.column_id
AND foreign_key_columns.parent_object_id=columns.object_id
WHERE
FKTotal.constraint_object_id=foreign_key_columns.constraint_object_id
ORDER BY constraint_column_id
FOR XML PATH('')
) AS index_columns_key
) AS Index_Columns
) AS foreign_key_columns
CROSS APPLY (
SELECT
LEFT(index_columns_key, LEN(index_columns_key)-1) AS index_columns_key,
LEFT(index_columns_include, LEN(index_columns_include)-1) AS index_columns_include
FROM
(
SELECT
(
SELECT columns.name + @Delimiter + ' '
FROM
sys.index_columns
JOIN sys.columns ON
index_columns.column_id=columns.column_id
AND index_columns.object_id=columns.object_id
WHERE
index_columns.is_included_column=0
AND FKMatch.index_object_id=index_columns.object_id
AND FKMatch.index_id=index_columns.index_id
ORDER BY key_ordinal
FOR XML PATH('')
) AS index_columns_key,
(
SELECT sys.columns.name + @Delimiter + ' '
FROM
sys.index_columns
JOIN sys.columns ON
sys.index_columns.column_id=sys.columns.column_id
AND sys.index_columns.object_id=sys.columns.object_id
WHERE
sys.index_columns.is_included_column=1
AND sys.indexes.object_id=sys.index_columns.object_id
AND sys.indexes.index_id=sys.index_columns.index_id
ORDER BY index_column_id
FOR XML PATH('')
) AS index_columns_include
) AS Index_Columns
) AS Index_Columns
WHERE FKMatch.IndexColumnMatchCount IS NULL OR FKTotal.FKColumnCount<>FKMatch.IndexColumnMatchCount
ORDER BY
IndexColumnMatchCount DESC, FKColumnCount DESC,
parentobjects.name, objects.name
Wednesday, February 20, 2013
Locating users within a DB
exec sp_MSforeachdb 'select ''?'' as Db, * from ?.sys.sysusers where name like ''%SomeUser%'''
Friday, February 15, 2013
Delete duplicates
delete from a
from
dbo.tableWithDupes a
join (
select
ColPrimaryKey
,row_number() over(
partition by AccountId, Col2, Col3 -- these are the unique columns
order by AccountId -- use this to give one record priority over another
) DupeCount
from
dbo.tableWithDupes
) q
on a.ColPrimaryKey = q.ColPrimaryKey
where
q.DupeCount > 1
Tuesday, February 12, 2013
Tuesday, January 8, 2013
List all identity columns
SELECT
c.TABLE_CATALOG
,c.TABLE_SCHEMA
,t.TABLE_NAME
,c.COLUMN_NAME
FROM
INFORMATION_SCHEMA.COLUMNS AS c JOIN
INFORMATION_SCHEMA.TABLES AS t
ON t.TABLE_NAME = c.TABLE_NAME
WHERE
COLUMNPROPERTY(OBJECT_ID(c.TABLE_NAME), c.COLUMN_NAME, 'IsIdentity') = 1 AND
t.TABLE_TYPE = 'Base Table' AND
t.TABLE_NAME NOT LIKE 'dt%' AND
t.TABLE_NAME NOT LIKE 'MS%' AND
t.TABLE_NAME NOT LIKE 'syncobj_%'
Subscribe to:
Posts (Atom)