Sunday, April 21, 2019

Mac & Linux
npm ERR! stack Error: EACCES: permission denied, mkdir


sudo npm install --unsafe-perm=true --allow-root
npm config set unsafe-perm true
npm config set allow-root true

Sunday, April 7, 2019

pip3 list -o --format columns|  cut -d' ' -f1|xargs -n1 pip install -U

Monday, November 12, 2018

certutil -hashfile gpg4win-3.1.4.exe sha256

Sunday, March 25, 2018

Extract text from a PDF


java -jar ./tabula-1.0.1-jar-with-dependencies.jar --pages all file.pdf

Thursday, September 28, 2017

Get the schema for a result set from a query or sproc


https://docs.microsoft.com/en-us/sql/relational-databases/system-stored-procedures/sp-describe-first-result-set-transact-sql

https://docs.microsoft.com/en-us/sql/relational-databases/system-dynamic-management-views/sys-dm-exec-describe-first-result-set-transact-sql

EXEC sp_describe_first_result_set @tsql = N'exec sys.sp_who'
GO
SELECT * FROM sys.dm_exec_describe_first_result_set( N'exec sys.sp_who', null, 0)
go

Thursday, March 3, 2016

Delete washes in accounting data

--******************************************************************
--******************************************************************
--******************************************************************
--******************************************************************
-- Algorithm by Carlos Klapp
--******************************************************************
--******************************************************************
--******************************************************************
--******************************************************************
/*

This algorithm splits the data into positive and negative values. 
    It then finds the rows in the same position and flags them as a 
    wash. If the row does not have a matching pair then it is a
    unique transaction and is NOT a wash.

|             Positive values         |             |             Negative values         |
| AccountId | TransactionDate | Value |             | AccountId | TransactionDate | Value |
|         1 |      2016/01/01 |    $7 |     <->     |         1 |      2016/01/01 |   -$7 | <- can be deleted
|         1 |      2016/02/01 |    $7 |     <->     |         1 |      2016/06/01 |   -$7 | <- can be deleted
|         1 |      2016/04/01 |    $7 |     <->     |         1 |      2016/07/01 |   -$7 | <- can be deleted
|           |                 |       |             |         1 |      2016/09/01 |   -$7 | <- keep this row
|         2 |      2016/05/01 |    $8 |     <->     |         2 |      2016/11/01 |   -$8 | <- can be deleted
|           |                 |       |             |         2 |      2016/12/01 |   -$8 | <- keep this row


*/





--******************************************************************
--******************************************************************
-- Build a tally table
--******************************************************************
--******************************************************************
IF OBJECT_ID('dbo.Numbers') IS NOT NULL
    DROP TABLE dbo.Numbers
    
SELECT TOP 10000 N=IDENTITY(INT, 1, 1)
INTO dbo.Numbers
FROM master.dbo.syscolumns a CROSS JOIN master.dbo.syscolumns  b;

ALTER TABLE dbo.Numbers ADD CONSTRAINT NBR_pk PRIMARY KEY(N);


--******************************************************************
--******************************************************************
-- Create the table that will hold our test data
--******************************************************************
--******************************************************************
IF OBJECT_ID('dbo.WashValues') IS NOT NULL
    DROP TABLE dbo.WashValues

CREATE TABLE dbo.WashValues(
    RowId int IDENTITY(1,1) PRIMARY KEY
    ,AccountId INT NOT NULL
    ,TransactionDate datetime NOT NULL
    ,Value MONEY NOT NULL
    ,AbsValue AS CAST(ISNULL(abs(Value), 0) AS MONEY) PERSISTED
    ,IsWash BIT NOT NULL DEFAULT(0)
)


--******************************************************************
--******************************************************************
-- Create our sample data
--******************************************************************
--******************************************************************
INSERT INTO dbo.WashValues(AccountId, TransactionDate, Value)
SELECT
    CAST(CRYPT_GEN_RANDOM(1) AS INT) % 10 + 1 AS AccountId
    ,DATEADD(DAY, n.N, GETDATE()) AS TransactionDate
    ,CAST(CRYPT_GEN_RANDOM(1) AS INT) % 10 * IIF(CAST(CRYPT_GEN_RANDOM(1) AS INT) % 2 = 0, 1, -1) AS Value
FROM
    dbo.Numbers n
WHERE
    n.N BETWEEN 1 AND 10000


--******************************************************************
-- Insert unique case: single positive row without a wash
--******************************************************************
INSERT INTO dbo.WashValues(AccountId, TransactionDate, Value)
SELECT
    999 AS AccountId
    ,GETDATE() AS TransactionDate
    ,999 AS Value


--******************************************************************
-- Insert unique case: single negative row without a wash
--******************************************************************
INSERT INTO dbo.WashValues(AccountId, TransactionDate, Value)
SELECT
    888 AS AccountId
    ,GETDATE() AS TransactionDate
    ,-888 AS Value



--******************************************************************
-- Delete the zero money rows. They sum to zero, so we can ignore them.
--******************************************************************
DELETE from dbo.WashValues WHERE AbsValue = 0


--******************************************************************
--******************************************************************
--******************************************************************
--******************************************************************
-- Split the data into a positive and negative list. In this
--  example we order the lists by the TransactionDate in ascending
--  order. This essentially gives us a FIFO (First In First Out)
--  list.
--******************************************************************
--******************************************************************
--******************************************************************
--******************************************************************

--******************************************************************
-- Build negative list
--******************************************************************
IF OBJECT_ID('dbo.WashValues_Negative') IS NOT NULL
    DROP TABLE dbo.WashValues_Negative

SELECT
    RowId
    ,AccountId
    ,AbsValue
    ,ROW_NUMBER() OVER(PARTITION BY AccountId, Value ORDER BY TransactionDate) AS SequenceId
INTO dbo.WashValues_Negative
FROM 
    dbo.WashValues
WHERE
    Value < 0

    
--******************************************************************
-- Build negative list
--******************************************************************
IF OBJECT_ID('dbo.WashValues_Positive') IS NOT NULL
    DROP TABLE dbo.WashValues_Positive

SELECT
    RowId
    ,AccountId
    ,AbsValue
    ,ROW_NUMBER() OVER(PARTITION BY AccountId, Value ORDER BY TransactionDate) AS SequenceId
INTO dbo.WashValues_Positive
FROM 
    dbo.WashValues
WHERE
    Value > 0



--******************************************************************
--******************************************************************
-- Locate the equivalent rows and mark them as a wash.
--******************************************************************
--******************************************************************
UPDATE w
SET
    w.IsWash = 1
FROM
    dbo.WashValues w
    JOIN (
        SELECT 
            p.RowId AS n_RowId
            ,n.RowId AS p_RowId
        FROM 
            dbo.WashValues_Positive p
            JOIN dbo.WashValues_Negative n
                ON p.AccountId = n.AccountId
                    AND n.AbsValue = p.AbsValue
                    AND n.SequenceId = p.SequenceId
    ) q
        ON w.RowId IN (q.n_RowId, q.p_RowId)



--******************************************************************
--******************************************************************
-- Debug: Inspect the data and make sure the rows are
--  correctly paired.
--******************************************************************
--******************************************************************
SELECT 
    pw.RowId
   ,pw.AccountId
   ,pw.TransactionDate
   ,pw.Value
   ,pw.AbsValue
   ,pw.IsWash
   ,p.SequenceId
   ,nw.RowId
   ,nw.AccountId
   ,nw.TransactionDate
   ,nw.Value
   ,nw.AbsValue
   ,nw.IsWash
   ,n.SequenceId
FROM 
    dbo.WashValues_Positive p
    JOIN dbo.WashValues_Negative n
        ON p.AccountId = n.AccountId
            AND n.AbsValue = p.AbsValue
            AND n.SequenceId = p.SequenceId
    JOIN dbo.WashValues pw
        ON pw.RowId = p.RowId
    JOIN dbo.WashValues nw
        ON nw.RowId = n.RowId
GROUP BY
    pw.RowId
   ,pw.AccountId
   ,pw.TransactionDate
   ,pw.Value
   ,pw.AbsValue
   ,pw.IsWash
   ,p.SequenceId
   ,nw.RowId
   ,nw.AccountId
   ,nw.TransactionDate
   ,nw.Value
   ,nw.AbsValue
   ,nw.IsWash
   ,n.SequenceId
ORDER BY
    pw.AccountId
    ,pw.AbsValue
    ,p.SequenceId

    


--******************************************************************
--******************************************************************
-- Unit Test: The grand total by AccountId must always be the same.
--******************************************************************
--******************************************************************
IF EXISTS(
        SELECT
            *
        FROM
            (
                SELECT
                    AccountId
                    ,SUM(Value) AS Total
                    ,COUNT(*) AS NumRows
                FROM
                    dbo.WashValues
                WHERE
                    IsWash = 0
                GROUP BY
                    AccountId
            ) q1
            FULL OUTER JOIN (
                SELECT
                    AccountId
                    ,SUM(Value) AS Total
                    ,COUNT(*) AS NumRows
                FROM
                    dbo.WashValues
                GROUP BY
                    AccountId
            ) q2
                ON q2.AccountId = q1.AccountId
                    AND q2.Total = q1.Total
        where  
            q1.AccountId IS NULL
            OR q2.AccountId IS null
    )
BEGIN
    RAISERROR('Bug in code. Total do not match', 18, 0)
end

Wednesday, December 3, 2014

SSAS MDX EXCEL: Memory error: While attempting to store a string, a string was found that was larger than the page size selected. The operation cannot be completed.


Adding ";Optimize Response=3" to your connection is one viable workaround.

The original solution is posted here: https://connect.microsoft.com/SQLServer/feedback/details/779232/excel-pivottable-error-while-attempting-to-store-a-string-a-string-was-found-that-was-larger-than-the-page-size-selected

Seems the problem is caused by the OleDB driver. Adding this to SSMS connection string as an additional parameter did not fix the issue.

Another work around is to issue the MDX statement using SQL and a linked server.





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


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

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

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

Thursday, March 21, 2013

Selecting Rows Randomly from a Large Table

http://msdn.microsoft.com/en-us/library/cc441928.aspx

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 for the license text.

*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=
*/

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%'''