Wednesday, August 14, 2013

Google Data API Setup (2.1.0)

To pull all the profile ids for all the accounts from google analytics, we need to install the following .msi file in our local system or server where we are going to execute the process.

The setup name is: Google_Data_API_Setup_2.1.0.0.msi


Once we install the setup file, go to the following path - C:\Program Files (x86)\Google\Google Data API SDK\Redist and copy the all .dll file and paste/move in to the assembly folder (Type as Run in search option - type as Assembly)


Tuesday, August 13, 2013

How to convert Integer value to Time in sql server

Declare @T int

set @T = 10455836

select (@T / 1000000) % 100 as hour,
       (@T / 10000) % 100 as minute,
       (@T / 100) % 100 as second,
       (@T % 100) * 10 as millisecond

select dateadd(hour, (@T / 1000000) % 100,
       dateadd(minute, (@T / 10000) % 100,
       dateadd(second, (@T / 100) % 100,
       dateadd(millisecond, (@T % 100) * 10, cast('00:00:00' as time(2)))))) 

Monday, May 20, 2013

Script to send e-mail by tracking the package status using the Script Task in SSIS

private void Mailsend()
        {
            string fromID = Dts.Variables["User::MailTo"].Value.ToString();
            string toID = Dts.Variables["User::MailTo"].Value.ToString();
            string subject = Dts.Variables["User::MailSubject"].Value.ToString();
            string messageText = Dts.Variables["User::MailMessage"].Value.ToString();
            string exchangeServerName = Dts.Variables["User::ExchangeServerName"].Value.ToString();
            string packagestatus = Dts.Variables["User::PackageStatus"].Value.ToString();
            string restoredata = Dts.Variables["User::RestoreDatabaseStatus"].Value.ToString();

            string sPackageName = Dts.Variables["User::sPackageName"].Value.ToString();
            string sPackageRunStartDate = Dts.Variables["User::sPackageRunStartDate"].Value.ToString();
            string sPackageRunEndDate = Dts.Variables["User::sPackageRunEndDate"].Value.ToString();
            string sPackageStatus = Dts.Variables["User::sPackageStatus"].Value.ToString();


            string sJobName = Dts.Variables["User::JobName"].Value.ToString();
            string sJobLastRunDate = Dts.Variables["User::JobLastRunDate"].Value.ToString();
            string sJobLastRunTime = Dts.Variables["User::JobLastRunTime"].Value.ToString();
            string sJobLastRunDuration = Dts.Variables["User::JobLastRunDuration"].Value.ToString();

            string senderMailID = fromID;
            MailAddress from = new MailAddress(senderMailID);
            string receiverMailID = toID;
            MailAddress to = new MailAddress(receiverMailID);
            MailMessage msg = new MailMessage(from, to);
            msg.Subject = subject;
            StringBuilder mailString = new StringBuilder();
            // mailString.AppendLine(messageText);
            try
            {
                if ((sJobName == null && sPackageName == null) || (sJobName == "" && sPackageName == "" && sPackageStatus != "Completed") )
                {
                    mailString.Append("<html><body><H3>" + messageText + "</h3>" + "</br>" + "LSDM20BackupRestore Status" + "</br>" + "<table border='1' width='100%'> <tr border=2 bgcolor='gray'><td border=2>PackageName</td><td>LastRunStartDate</td><td>LastRunEndDate</td><td>PackageStaus</td></tr> <tr> <td border=2>" + sPackageName + "</td><td>" + sPackageRunStartDate + "</td><td>" + sPackageRunEndDate + "</td><td>" + sPackageStatus + "</td> </tr> </table></body></html>" + "</br>" + "LoadCultivationTrack Job Status" + "</br>" + "<table border='1' width='100%'> <tr border=2 bgcolor='gray'><td border=2>PackageName</td><td>JobLastRunDate</td><td>JobLastRunTime</td><td>JobLastRunDuration</td></tr> <tr> <td border=2>" + sJobName + "</td><td>" + sJobLastRunDate + "</td><td>" + sJobLastRunTime + "</td><td>" + sJobLastRunDuration + "</td> </tr> </table></body></html>");
                    msg.IsBodyHtml = true;
                    msg.Body = mailString.ToString();
                    SmtpClient smtpClient = new SmtpClient(exchangeServerName);
                    smtpClient.Send(msg);
                }
                else if ((sJobName != null && sPackageName == null) ||  (sJobName != "" && sPackageName == "" ))
                {
                    mailString.Append("<html><body><H3>" + messageText + "</h3>" + "</br>" +  "LoadCultivationTrack Job Status" + "</br>" + "<table border='1' width='100%'> <tr border=2 bgcolor='gray'><td border=2>PackageName</td><td>JobLastRunDate</td><td>JobLastRunTime</td><td>JobLastRunDuration</td></tr> <tr> <td border=2>" + sJobName + "</td><td>" + sJobLastRunDate + "</td><td>" + sJobLastRunTime + "</td><td>" + sJobLastRunDuration + "</td> </tr> </table></body></html>");
                    msg.IsBodyHtml = true;
                    msg.Body = mailString.ToString();
                    SmtpClient smtpClient = new SmtpClient(exchangeServerName);
                    smtpClient.Send(msg);
                }
                else if ((sJobName == null && sPackageName != null) ||  (sJobName == "" && sPackageName != "" ))
                {
                    mailString.Append("<html><body><H3>" + messageText + "</h3>" + "</br>" + "LSDM20BackupRestore Status" + "</br>" + "<table border='1' width='100%'> <tr border=2 bgcolor='gray'><td border=2>PackageName</td><td>LastRunStartDate</td><td>LastRunEndDate</td><td>PackageStaus</td></tr> <tr> <td border=2>" + sPackageName + "</td><td>" + sPackageRunStartDate + "</td><td>" + sPackageRunEndDate + "</td><td>" + sPackageStatus + "</td> </tr> </table></body></html>");
                    msg.IsBodyHtml = true;
                    msg.Body = mailString.ToString();
                    SmtpClient smtpClient = new SmtpClient(exchangeServerName);
                    smtpClient.Send(msg);
                }
                
            }
            catch (Exception)
            {
                //Log.Error(String.Format("Resetpassword.ascx.cs: There was an error during sending mail. Details: {0}.\n{1}", ex.Message, ex.StackTrace), new object());
            }
            finally
            {
                msg.Dispose();
            }
        }

Thursday, May 16, 2013

Entity Relationship Model (Diagram)

An entity-relationship diagram is a data modeling technique that creates a graphical representation of the entities, and the relationships between entities, within an information system.


The three main components of an ERD are:

1. One-to-One
One instance of an entity (A) is associated with one other instance of another entity (B). For example, in a database of employees, each employee name (A) is associated with only one social security number (B).


2. One-to-Many
One instance of an entity (A) is associated with zero, one or many instances of another entity (B), but for one instance of entity B there is only one instance of entity A. For example, for a company with all employees working in one building, the building name (A) is associated with many different employees (B), but those employees all share the same singular association with entity A.


3. Many-to-Many
One instance of an entity (A) is associated with one, zero or many instances of another entity (B), and one instance of entity B is associated with one, zero or many instances of entity A. For example, for a company in which all of its employees work on multiple projects, each instance of an employee (A) is associated with many instances of a project (B), and at the same time, each instance of a project (B) has multiple employees (A) associated with it.




ERD-Visio Reference Site


http://msdn.microsoft.com/en-us/library/office/aa140264(v=office.10).aspx

http://techpanacea.blogspot.in/2008/07/how-to-reverse-engineer-er-diagram-from.html

Script to calculate number sequence and insert into a table


Calculating number sequence

DECLARE @idt bigINT
SET @idt = 0
WHILE (@idt < 1000)
BEGIN
SELECT @idt = @idt + 1
insert into dbo.NumberSequence (number)
values (@idt)
END

Inserting into a table

DECLARE @idt bigINT
SET @idt = 0
WHILE (@idt < 1000)
BEGIN
SELECT @idt = @idt + 1
insert into dbo.NumberSequence (number)
values (@idt)
END

C# code to calculate check digit using DAMM Algorithm

C# code to calculate Damm Algorithm  -- In Script transformation task (in DFT)


public override void Input0_ProcessInputRow(Input0Buffer Row)
    {
        string value = Row.sourcecodeid.ToString();
        Int32 intValue;
      
        if (Int32.TryParse(value, out intValue))
        {
            // mystring is an integer

            int column = 0;
           
            int[] intArray = new int[value.Length];
            for (int i = 0; i < value.Length; i++)
            {
                intArray[i] = int.Parse(value[i].ToString());
            }
            for (int i = 0; i < intArray.Length; i++)
            {

                int row = intArray[i];
                int newvalue = ReturnArrayValue(row, column);
                column = newvalue;
                if (i == intArray.Length - 1)
                    Row.checkdigit = column.ToString();
            }

        }
        else
        {
            Row.checkdigit = value;
        }
    }
    public int ReturnArrayValue(int column, int row)
    {
        int[,] myArray = new int[,] { { 0, 3, 1, 7 ,5, 9 ,8, 6, 4, 2 }, {7, 0, 9 ,2 ,1, 5, 4 ,8 ,6, 3 }, { 4,2,0,6,8,7,1,3,5,9 }, 
            {1,7,5,0,9,8,3,4,2,6},
            {6,1,2,3,0,4,5,9,7,8}, { 3,6,7,4,2,0,9,5,8,1 }, {5,8,6,9,7,2,0,1,3,4}, { 8,9,4,5,3,6,2,0,1,7},
            {9,4,3,8,6,1,7,2,0,5 } ,{ 2,5,8,1,4,3,6,7,9,0} };
        return myArray[row, column];
    }
   
}



C# code to calculate Damm Algorithm  -- In Script  task (in control flow)



public void Main()
{
// TODO: Add your code here


            string value = Dts.Variables["User::NumberSequence"].Value.ToString();
            //checkDigit(val);
            Int32 intValue;
   
            if (Int32.TryParse(value, out intValue))
            {
                // mystring is an integer

                int column = 0;
         
                int[] intArray = new int[value.Length];
                for (int i = 0; i < value.Length; i++)
                {
                    intArray[i] = int.Parse(value[i].ToString());
                }
                for (int i = 0; i < intArray.Length; i++)
                {

                    int row = intArray[i];
                    int newvalue = ReturnArrayValue(row, column);
                    column = newvalue;
                    if (i == intArray.Length - 1)
                        Dts.Variables["User::CheckDigitTest"].Value = column.ToString();
                    

                }

            }
            else
            {
                Dts.Variables["User::CheckDigitTest"].Value = value;
               
            }
  Dts.TaskResult = (int)ScriptResults.Success;
}

public int ReturnArrayValue(int column, int row)
        {
            int[,] myArray = new int[,] { { 0, 3, 1, 7 ,5, 9 ,8, 6, 4, 2 }, {7, 0, 9 ,2 ,1, 5, 4 ,8 ,6, 3 }, { 4,2,0,6,8,7,1,3,5,9 }, 
            {1,7,5,0,9,8,3,4,2,6},
            {6,1,2,3,0,4,5,9,7,8}, { 3,6,7,4,2,0,9,5,8,1 }, {5,8,6,9,7,2,0,1,3,4}, { 8,9,4,5,3,6,2,0,1,7},
            {9,4,3,8,6,1,7,2,0,5 } ,{ 2,5,8,1,4,3,6,7,9,0} };
            return myArray[row, column];
        }


Check Digit Calculation


DECLARE @Temp1 INT
       ,@Temp2 INT
       ,@UPC VARCHAR(20)
       ,@CheckDigit INT;

SET @UPC = 547

SELECT @UPC = rtrim(ltrim(@UPC))
WHILE LEN(@UPC) < 11 SET @UPC = '0' + @UPC

SELECT @Temp1 = 0 +
SUBSTRING(@upc,1,1) +
SUBSTRING(@upc,3,1) +
SUBSTRING(@upc,5,1) +
SUBSTRING(@upc,7,1) +
SUBSTRING(@upc,9,1) +
SUBSTRING(@upc,11,1) 

SELECT @Temp1 = @Temp1 * 3

SELECT @Temp2 = 0 +
SUBSTRING(@upc,2,1) +
SUBSTRING(@upc,4,1) +
SUBSTRING(@upc,6,1) +
SUBSTRING(@upc,8,1) +
SUBSTRING(@upc,10,1) 

SELECT @Temp1 = @Temp1 + @Temp2

SELECT @Temp1 = (10- (@Temp1 % 10)) % 10

SELECT @CheckDigit = @Temp1

SELECT @CheckDigit

To pad zeros in left with the numerical value


SELECT EmpID
,REPLICATE('0',11 - LEN(EmpID))+ CAST(EmpID AS varchar ) AS EmpKey
FROM dbo.DimEmployee

Script to count rows in all tables in a database

SELECT '[' + SCHEMA_NAME(t.schema_id) + '].[' + t.name + ']' AS fulltable_name
     , SCHEMA_NAME(t.schema_id) AS schema_name
     , t.name AS table_name
     , i.rows
FROM sys.tables AS t INNER JOIN
sys.sysindexes AS i 
ON t.object_id = i.id AND i.indid < 2

Monday, April 1, 2013

Script to Create a DataBase


USE [master]
GO

IF NOT EXISTS (SELECT name FROM sys.databases WHERE name = N'TestDB')
BEGIN
CREATE DATABASE TestDB ON  PRIMARY 
( NAME = N'TestDB',
FILENAME = N'G:\MSSQL10.SS2008\MSSQL\Data\TestDB.mdf',
SIZE = 1024 MB,
MAXSIZE = Unlimited,
FILEGROWTH = 10% )
 LOG ON 
( NAME = N'TestDB_Log',
FILENAME = N'H:\MSSQL10.SS2008\MSSQL\Data\TestDB_log.ldf',
SIZE = 1024 MB,
MAXSIZE = 2 TB,
 FILEGROWTH = 10% )
END

GO

ALTER DATABASE TestDB SET COMPATIBILITY_LEVEL = 100
GO

IF (1 = FULLTEXTSERVICEPROPERTY('IsFullTextInstalled'))
begin
EXEC TestDB.[dbo].[sp_fulltext_database] @action = 'enable'
end
GO

ALTER DATABASE TestDB SET ANSI_NULL_DEFAULT OFF 
GO
ALTER DATABASE TestDB SET ANSI_NULLS OFF 
GO
ALTER DATABASE TestDB SET ANSI_PADDING OFF 
GO
ALTER DATABASE TestDB SET ANSI_WARNINGS OFF 
GO
ALTER DATABASE TestDB SET ARITHABORT OFF 
GO
ALTER DATABASE TestDB SET AUTO_CLOSE OFF 
GO
ALTER DATABASE TestDB SET AUTO_CREATE_STATISTICS ON 
GO
ALTER DATABASE TestDB SET AUTO_SHRINK OFF 
GO
ALTER DATABASE TestDB SET AUTO_UPDATE_STATISTICS ON 
GO
ALTER DATABASE TestDB SET CURSOR_CLOSE_ON_COMMIT OFF 
GO
ALTER DATABASE TestDB SET CURSOR_DEFAULT  GLOBAL 
GO
ALTER DATABASE TestDB SET CONCAT_NULL_YIELDS_NULL OFF 
GO
ALTER DATABASE TestDB SET NUMERIC_ROUNDABORT OFF 
GO
ALTER DATABASE TestDB SET QUOTED_IDENTIFIER OFF 
GO
ALTER DATABASE TestDB SET RECURSIVE_TRIGGERS OFF 
GO
ALTER DATABASE TestDB SET AUTO_UPDATE_STATISTICS_ASYNC OFF 
GO
ALTER DATABASE TestDB SET DATE_CORRELATION_OPTIMIZATION OFF 
GO
ALTER DATABASE TestDB SET TRUSTWORTHY OFF 
GO
ALTER DATABASE TestDB SET ALLOW_SNAPSHOT_ISOLATION OFF 
GO
ALTER DATABASE TestDB SET PARAMETERIZATION SIMPLE 
GO
ALTER DATABASE TestDB SET READ_COMMITTED_SNAPSHOT OFF 
GO
ALTER DATABASE TestDB SET HONOR_BROKER_PRIORITY OFF 
GO
ALTER DATABASE TestDB SET  READ_WRITE 
GO
ALTER DATABASE TestDB SET RECOVERY SIMPLE 
GO
ALTER DATABASE TestDB SET  MULTI_USER 
GO
ALTER DATABASE TestDB SET PAGE_VERIFY CHECKSUM  
GO
ALTER DATABASE TestDB SET DB_CHAINING OFF 
GO
/*End Create Database Section */


Use TestDB
GO

/*Create MDR Security*/
IF NOT EXISTS (SELECT * FROM sys.database_principals WHERE name = N'AppSupport' AND type = 'R')
CREATE ROLE [AppSupport] AUTHORIZATION [dbo]
GO

--Create MDR_Designer Role
IF NOT EXISTS (SELECT * FROM sys.database_principals WHERE name = N'Designer' AND type = 'R')
CREATE ROLE [Designer] AUTHORIZATION [dbo]
GO

--Create MDR_Developer Role
IF NOT EXISTS (SELECT * FROM sys.database_principals WHERE name = N'Developer' AND type = 'R')
CREATE ROLE [Developer] AUTHORIZATION [dbo]
GO

--Create MDR_Tester Role
IF NOT EXISTS (SELECT * FROM sys.database_principals WHERE name = N'Tester' AND type = 'R')
CREATE ROLE [Tester] AUTHORIZATION [dbo]
GO

PRINT '**Begin DB User Additions**'
/*=================================================================*/
-- ADD USERS AND ROLES for Database

declare @UserList table 
( ID int IDENTITY(1, 1) NOT NULL,
ServerName varchar(250) NOT NULL, 
DBName varchar(250) NOT NULL, 
LoginName varchar(250) NOT NULL, 
DBRole varchar(250) NOT NULL,
IsNTLogin bit NOT NULL,
SQLPWD varchar(50) NULL
)

/*-------------------- Custom Data Here ---------------------------*/
/*Add Groups*/
insert into @UserList (Servername, DBName, LoginName, DBRole, IsNTLogin)
values ('ddwdb01cs', 'TestDB', 'MIS\gg_AppSupport', 'AppSupport', 1)
insert into @UserList (Servername, DBName, LoginName, DBRole, IsNTLogin)
values ('ddwdb01cs', 'TestDB', 'MIS\gg_Tester', 'Tester', 1)
insert into @UserList (Servername, DBName, LoginName, DBRole, IsNTLogin)
values ('ddwdb01cs', 'TestDB', 'MIS\gg_Developer', 'Developer', 1)
insert into @UserList (Servername, DBName, LoginName, DBRole, IsNTLogin)
values ('ddwdb01cs', 'TestDB', 'MIS\gg_Designer', 'Designer', 1)

/*-----------------------------------------------------------------*/

declare @ID int
declare @ServerName varchar(250)
declare @DBName varchar(250)
declare @LoginName varchar(250)
declare @DBUserName varchar(250)
declare @DBRole varchar(250)
declare @IsNT bit
declare @PrevID int
declare @PWD varchar(50)

Set @ID = 0

WHILE @ID is NOT NULL
BEGIN
SELECT top 1 @ID = ID, @ServerName = ServerName, @DBName = DBName, @LoginName = LoginName, @DBRole = DBRole, @IsNT = IsNTLogin, @PWD = SQLPWD
FROM @UserList
WHERE ServerName = @@SERVERNAME and DB_Name() like DBName and ID > @ID
ORDER BY ID

print @ServerName + ' ' + @DBName + ' ' + @LoginName + ' ' + @DBRole

IF NOT EXISTS (SELECT * FROM master.dbo.syslogins WHERE name = @LoginName)
IF @IsNT = 1
EXEC master.dbo.sp_grantlogin @loginame = @LoginName
ELSE
EXEC master.dbo.sp_addlogin @loginame = @LoginName, @passwd = @PWD

set @DBUserName = (SELECT U.name FROM dbo.sysusers U join master.dbo.syslogins L on L.sid = U.sid WHERE L.loginname = @LoginName)

IF @DBUserName IS NULL BEGIN
EXEC dbo.sp_grantdbaccess @loginame = @LoginName, @name_in_db = @LoginName
SET @DBUserName = @LoginName
END

EXEC dbo.sp_addrolemember @DBRole, @DBUserName

IF @PrevID = @ID
set @ID = NULL
ELSE
set @PrevID = @ID



--Grant MDR Role Permissions
--Grant MDR_Tester Permissions
if @DBRole = N'Tester' Begin
EXEC sp_addrolemember N'db_datareader', N'Tester'
Grant View Definition to MDR_Tester
Grant execute to MDR_Tester
END
--Grant MDR_AppSupport Permissions
if @DBRole = N'AppSupport' Begin
EXEC sp_addrolemember N'db_datareader', N'AppSupport'
Grant View Definition to MDR_AppSupport
Grant execute to MDR_AppSupport
END

--Grant MDR_Developer Permissions
if @DBRole = N'Developer' Begin
EXEC sp_addrolemember N'db_datareader', N'Developer'
Grant View Definition to MDR_Developer
Grant execute to MDR_Developer
END
--Grant MDR_Designer Permissions
if @DBRole = N'Designer' and (@@SERVERNAME = N'DDWDB01CS' or @@SERVERNAME=N'DDWSBDB01CS')  Begin
EXEC sp_addrolemember N'db_owner', N'Designer'
END
ELSE Begin
EXEC sp_addrolemember N'db_datareader', N'Designer'
Grant View Definition to MDR_Designer
Grant execute to MDR_Designer
End 
END

/*server level permissions*/
IF NOT EXISTS (SELECT * FROM sys.server_principals WHERE name = N'MIS\svc_CS_SS2008Agent')
CREATE LOGIN [MIS\svc_CS_SS2008Agent] FROM WINDOWS WITH DEFAULT_DATABASE=[master], DEFAULT_LANGUAGE=[us_english]
GO

/*db level permissions*/
IF NOT EXISTS (SELECT * FROM sys.database_principals WHERE name = N'MIS\svc_CS_SS2008Agent')
CREATE USER [MIS\svc_CS_SS2008Agent] FOR LOGIN [MIS\svc_CS_SS2008Agent] WITH DEFAULT_SCHEMA=[dbo]
GO

/*Apply permissions*/
EXEC sp_addrolemember N'db_owner', N'MIS\svc_CS_SS2008Agent'

/*server level permissions*/
IF NOT EXISTS (SELECT * FROM sys.server_principals WHERE name = N'MIS\svc_CS_SS2008Agent')
CREATE LOGIN [MIS\svc_CS_SS2008Agent] FROM WINDOWS WITH DEFAULT_DATABASE=[master], DEFAULT_LANGUAGE=[us_english]
GO

/*db level permissions*/
IF NOT EXISTS (SELECT * FROM sys.database_principals WHERE name = N'MIS\svc_CS_SS2008Agent')
CREATE USER [MIS\svc_CS_SS2008Agent] FOR LOGIN [MIS\svc_CS_SS2008Agent] WITH DEFAULT_SCHEMA=[dbo]
GO

/*Apply permissions*/
EXEC sp_addrolemember N'db_owner', N'MIS\svc_CS_SS2008Agent'

USE [master]
GO
GRANT VIEW SERVER STATE TO [MIS\gg_AppSupport]
GRANT VIEW SERVER STATE TO [MIS\gg_Designer]
GRANT VIEW SERVER STATE TO [MIS\gg_Developer]
GRANT VIEW SERVER STATE TO [MIS\gg_Tester]
GO

PRINT '**DB User Addition Script complete**'

Script to Shrink TempDatabase

USE tempdb
GO
 
DBCC shrinkfile (tempdev, 1024)
GO

DBCC shrinkfile (templog, 1024)
GO

DBCC shrinkfile (tempdb2, 1024)
GO

DBCC shrinkfile (tempdb3, 1024)
GO

DBCC shrinkfile (tempdb4, 1024)
GO

DBCC shrinkfile (tempdb5, 1024)
GO

DBCC shrinkfile (tempdb6, 1024)
GO

DBCC shrinkfile (tempdb7, 1024)
GO

DBCC shrinkfile (tempdb8, 1024)
GO

Script to Shrink TransactionLog

USE TESTDB  
GO

DBCC SHRINKFILE (N'TESTDB_Log', 0, TRUNCATEONLY)
GO

Wednesday, February 27, 2013

How to Find Tables With Primary and Foreign Key Constraint in Database


Table with ForiegnKey constraint

USE EDW; --Database name
GO
SELECT f.name AS ForeignKey,
OBJECT_NAME(f.parent_object_id) AS TableName,
COL_NAME(fc.parent_object_id,
fc.parent_column_id) AS ColumnName,
OBJECT_NAME (f.referenced_object_id) AS ReferenceTableName,
COL_NAME(fc.referenced_object_id,
fc.referenced_column_id) AS ReferenceColumnName
FROM sys.foreign_keys AS f
INNER JOIN sys.foreign_key_columns AS fc
ON f.OBJECT_ID = fc.constraint_object_id

Table with PrimaryKey constraint


USE EDW;  --Database name
GO
SELECT i.name AS IndexName,
OBJECT_NAME(ic.OBJECT_ID) AS TableName,
COL_NAME(ic.OBJECT_ID,ic.column_id) AS ColumnName
FROM sys.indexes AS i
INNER JOIN sys.index_columns AS ic
ON i.OBJECT_ID = ic.OBJECT_ID
AND i.index_id = ic.index_id
WHERE i.is_primary_key = 1

Find a table in a database

Below is the code to find a table in a database

USE XXXX  --Database name

SELECT * FROM sys.Tables
WHERE name LIKE '%Address%'

Below is the code to find a table in all database with stored procedure


USE Master
GO
CREATE PROCEDURE usp_FindTableNameInAllDatabase
@TableName VARCHAR(256)
AS
DECLARE @DBName VARCHAR(256)
DECLARE @varSQL VARCHAR(512)
DECLARE @getDBName CURSOR
SET @getDBName = CURSOR FOR
SELECT name
FROM sys.databases
CREATE TABLE #TmpTable (DBName VARCHAR(256),
SchemaName VARCHAR(256),
TableName VARCHAR(256))
OPEN @getDBName
FETCH NEXT
FROM @getDBName INTO @DBName
WHILE @@FETCH_STATUS = 0
BEGIN
SET @varSQL = 'USE ' + @DBName + ';
INSERT INTO #TmpTable
SELECT '''+ @DBName + ''' AS DBName,
SCHEMA_NAME(schema_id) AS SchemaName,
name AS TableName
FROM sys.tables
WHERE name LIKE ''%' + @TableName + '%'''
EXEC (@varSQL)
FETCH NEXT
FROM @getDBName INTO @DBName
END
CLOSE @getDBName
DEALLOCATE @getDBName
SELECT *
FROM #TmpTable
DROP TABLE #TmpTable

To run the above store proc:
EXEC usp_FindTableNameInAllDatabase 'xxxTablenamexxx'    --Table name

If Exists Logic

If exists logic for a Database

IF EXISTS(select * from sys.databases where name='yourDBname')

If exists logic for a table

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[DimPACodes]') AND type in (N'U'))

If exists logic for a synonms

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N's_DimPACodes') AND type in (N'SN'))

If exists logic for a View

IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'vw_DimProgram') AND type in (N'V'))

If exists logic for a column

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Dimprogram' and COLUMN_NAME = 'IAPKey')

If exists logic for a Schema


IF NOT EXISTS(SELECT * FROM sys.schemas where name = N'Test')
EXEC ('CREATE SCHEMA [telligent] Authorization [dbo]')
GO

(OR)

IF NOT EXISTS(SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'Test')
EXEC ('CREATE SCHEMA [Test] Authorization [dbo]')
GO



Interpreting type codes in sys.objects in SQL Server

AF = Aggregate function (CLR)
C  = CHECK constraint
D  = DEFAULT (constraint or stand-alone)
F  = FOREIGN KEY constraint
FN = SQL scalar function
FS = Assembly (CLR) scalar-function
FT = Assembly (CLR) table-valued function
IF = SQL inline table-valued function
IT = Internal table
P  = SQL Stored Procedure
PC = Assembly (CLR) stored-procedure
PG = Plan guide
PK = PRIMARY KEY constraint
R  = Rule (old-style, stand-alone)
RF = Replication-filter-procedure
S  = System base table
SN = Synonym
SQ = Service queue
TA = Assembly (CLR) DML trigger
TF = SQL table-valued-function
TR = SQL DML trigger
TT = Table type
U  = Table (user-defined)
UQ = UNIQUE constraint
V  = View
X  = Extended stored procedure

To search a string in every column of every table in a specific database

To search a string in every column of every table in a specific database. Create the stored procedure on the database that you want to search in.


CREATE PROCEDURE FindMyData_String
    @DataToFind NVARCHAR(4000),
    @ExactMatch BIT = 0
AS
SET NOCOUNT ON

DECLARE @Temp TABLE(RowId INT IDENTITY(1,1), SchemaName sysname, TableName sysname, ColumnName SysName, DataType VARCHAR(100), DataFound BIT)

    INSERT  INTO @Temp(TableName,SchemaName, ColumnName, DataType)
    SELECT  C.Table_Name,C.TABLE_SCHEMA, C.Column_Name, C.Data_Type
    FROM    Information_Schema.Columns AS C
            INNER Join Information_Schema.Tables AS T
                ON C.Table_Name = T.Table_Name
        AND C.TABLE_SCHEMA = T.TABLE_SCHEMA
    WHERE   Table_Type = 'Base Table'
            And Data_Type In ('ntext','text','nvarchar','nchar','varchar','char')


DECLARE @i INT
DECLARE @MAX INT
DECLARE @TableName sysname
DECLARE @ColumnName sysname
DECLARE @SchemaName sysname
DECLARE @SQL NVARCHAR(4000)
DECLARE @PARAMETERS NVARCHAR(4000)
DECLARE @DataExists BIT
DECLARE @SQLTemplate NVARCHAR(4000)

SELECT  @SQLTemplate = CASE WHEN @ExactMatch = 1
                            THEN 'If Exists(Select *
                                          From   ReplaceTableName
                                          Where  Convert(nVarChar(4000), [ReplaceColumnName])
                                                       = ''' + @DataToFind + '''
                                          )
                                     Set @DataExists = 1
                                 Else
                                     Set @DataExists = 0'
                            ELSE 'If Exists(Select *
                                          From   ReplaceTableName
                                          Where  Convert(nVarChar(4000), [ReplaceColumnName])
                                                       Like ''%' + @DataToFind + '%''
                                          )
                                     Set @DataExists = 1
                                 Else
                                     Set @DataExists = 0'
                            END,
        @PARAMETERS = '@DataExists Bit OUTPUT',
        @i = 1

SELECT @i = 1, @MAX = MAX(RowId)
FROM   @Temp

WHILE @i <= @MAX
    BEGIN
        SELECT  @SQL = REPLACE(REPLACE(@SQLTemplate, 'ReplaceTableName', QUOTENAME(SchemaName) + '.' + QUOTENAME(TableName)), 'ReplaceColumnName', ColumnName)
        FROM    @Temp
        WHERE   RowId = @i


        PRINT @SQL
        EXEC SP_EXECUTESQL @SQL, @PARAMETERS, @DataExists = @DataExists OUTPUT

        IF @DataExists =1
            UPDATE @Temp SET DataFound = 1 WHERE RowId = @i

        SET @i = @i + 1
    END

SELECT  SchemaName,TableName, ColumnName
FROM    @Temp
WHERE   DataFound = 1
GO

To run it just do this:
exec FindMyData_string 'yahoo', 0     --here yahoo is the string name

Execution of job through command mode

Some times SSIS pacakages run through integration server but fails in Job from SQL Agent

This is the most common issue faced when we deploy packages in 64 bit system. When we create any package with Run64bit set as false, this issue occurs.


In order to overcome the 32\64 bit environment issue, we can execute the Job through command line mode

Apply the below code in job by mentioning the control flow package name

C:\Program Files\Microsoft SQL Server\110\DTS\Binn\dtexec.exe /FILE "\"M:/SSIS/MDR2.0/Imports/Imports20_ControlFlow.dtsx\"" /CHECKPOINTING OFF /REPORTING E

Apply the below code in job by mentioning the particular package name

C:\Program Files\Microsoft SQL Server\110\DTS\Binn\dtexec.exe/FILE "M:/SSIS/MDR2.0/EDW/EDW20_OfferedItemCBD.dtsx" /CHECKPOINTING OFF /REPORTING E

Index optimization command


sqlcmd -E -S $(ESCAPE_SQUOTE(SRVR)) -d master -Q "EXECUTE [dbo].[IndexOptimize] @Databases='ListSelect20',@FragmentationHigh='INDEX_REBUILD_OFFLINE',@FragmentationMedium='INDEX_REBUILD_OFFLINE',@FragmentationLevel1 = 1,@FragmentationLevel2 = 2,@PageCountLevel = 1,@SortInTempdb = 'Y'" -b


Script to check the last run status of job

SQL script to check the last run status of a job. This code will retrieve the last run status.


ECLARE @last_run_outcome INT 
SET @last_run_outcome = ( 
SELECT MAX(sjs.last_run_outcome) 
FROM msdb.dbo.sysjobs_view sjv 
INNER JOIN msdb.dbo.sysjobsteps sjs ON sjs.job_id = sjv.job_id 
WHERE name in ('MDR20') 
AND last_run_outcome = 0) 

--SELECT @last_run_outcome  

IF @last_run_outcome = 0 
EXEC msdb.dbo.sp_stop_job N'MDR20' 

Below is the outcome of the job for the last time ran:

0 = Failed
1 = Succeeded
3 = Canceled
5 = Unknown

Tuesday, February 5, 2013

Database

A database is a collection of information that is organized so that it can easily be accessed, managed, and updated. In one view, databases can be classified according to types of content: bibliographic, full-text, numeric, and images.

In computing, databases are sometimes classified according to their organizational approach. The most prevalent approach is the relational database, a tabular database in which data is defined so that it can be reorganized and accessed in a number of different ways. A distributed database is one that can be dispersed or replicated among different points in a network. An object-oriented programming database is one that is congruent with the data defined in object classes and sub classes.

Computer databases typically contain aggregations of data records or files, such as sales transactions, product catalogs and inventories, and customer profiles. Typically, a database manager provides users the capabilities of controlling read/write access, specifying report generation, and analyzing usage. Databases and database managers are prevalent in large mainframe systems, but are also present in smaller distributed workstation and mid-range systems such as the AS/400 and on personal computers. SQL (Structured Query Language) is a standard language for making interactive queries from and updating a database such as IBM's DB2, Microsoft's SQL Server, and database products from Oracle, Sybase, and Computer Associates.

Relational database

A relational database is a collection of data items organized as a set of formally-described tables from which data can be accessed or reassembled in many different ways without having to reorganize the database tables.

The standard user and application program interface to a relational database is the structured query language (SQL). SQL statements are used both for interactive queries for information from a relational database and for gathering data for reports.

In addition to being relatively easy to create and access, a relational database has the important advantage of being easy to extend. After the original database creation, a new data category can be added without requiring that all existing applications be modified.

A relational database is a set of tables containing data fitted into predefined categories. Each table (which is sometimes called a relation) contains one or more data categories in columns. Each row contains a unique instance of data for the categories defined by the columns. For example, a typical business order entry database would include a table that described a customer with columns for name, address, phone number, and so forth. Another table would describe an order: product, customer, date, sales price, and so forth. A user of the database could obtain a view of the database that fitted the user's needs. For example, a branch office manager might like a view or report on all customers that had bought products after a certain date. A financial services manager in the same company could, from the same tables, obtain a report on accounts that needed to be paid.

When creating a relational database, you can define the domain of possible values in a data column and further constraints that may apply to that data value. For example, a domain of possible customers could allow up to ten possible customer names but be constrained in one table to allowing only three of these customer names to be specifiable.

The definition of a relational database results in a table of metadata or formal descriptions of the tables, columns, domains, and constraints.


Multidimensional database (MDB)
A multidimensional database (MDB) is a type of database that is optimized for data warehouse and online analytical processing (OLAP) applications. Multidimensional databases are frequently created using input from existing relational databases. Whereas a relational database is typically accessed using a Structured Query Language (SQL) query, a multidimensional database allows a user to ask questions like "How many Aptivas have been sold in Nebraska so far this year?" and similar questions related to summarizing business operations and trends. An OLAP application that accesses data from a multidimensional database is known as a MOLAP (multidimensional OLAP) application.
A multidimensional database - or a multidimensional database management system (MDDBMS) - implies the ability to rapidly process the data in the database so that answers can be generated quickly. A number of vendors provide products that use multidimensional databases. Approaches to how data is stored and the user interface vary.

Conceptually, a multidimensional database uses the idea of a data cube to represent the dimensions of data available to a user. For example, "sales" could be viewed in the dimensions of product model, geography, time, or some additional dimension. In this case, "sales" is known as the measure attribute of the data cube and the other dimensions are seen as feature attributes. Additionally, a database creator can define hierarchies and levels within a dimension (for example, state and city levels within a regional hierarchy).

Data Warehouse

Data warehousing is combining data from multiple and usually varied sources into one comprehensive and easily manipulated database. Common accessing systems of data warehousing include queries, analysis and reporting. Because data warehousing creates one database in the end, the number of sources can be anything you want it to be, provided that the system can handle the volume, of course. The final result, however, is homogeneous data, which can be more easily manipulated.

Data warehousing is commonly used by companies to analyze trends over time. In other words, companies may very well use data warehousing to view day-to-day operations, but its primary function is facilitating strategic planning resulting from long-term data overviews. From such overviews, business models, forecasts, and other reports and projections can be made. Routinely, because the data stored in data warehouses is intended to provide more overview-like reporting, the data is read-only. If you want to update the data stored via data warehousing, you'll need to build a new query when you're done.

This is not to say that data warehousing involves data that is never updated. On the contrary, the data stored in data warehouses is updated all the time. It's the reporting and the analysis that take more of a long-term view.

Data warehousing is not the be-all and end-all for storing all of a company's data. Rather, data warehousing is used to house the necessary data for specific analysis. More comprehensive data storage requires different capacities that are more static and less easily manipulated than those used for data warehousing.

Data warehousing is typically used by larger companies analyzing larger sets of data for enterprise purposes. Smaller companies wishing to analyze just one subject, for example, usually access data marts, which are much more specific and targeted in their storage and reporting. Data warehousing often includes smaller amounts of data grouped into data marts. In this way, a larger company might have at its disposal both data warehousing and data marts, allowing users to choose the source and functionality depending on current needs.