Thursday, September 18, 2014

AES algorith is stronger algorthm than 3DES/Triple-DES

AES is an algorithm adopted as a Federal U.S. government standard in 2002 and approved
by the NSA. It is a stronger algorithm than Triple-DES. When you choose the algorithm,
you need to balance between security and performances. AES_128 is gradually becoming
more vulnerable as new attacks are discovered but it is still considered reasonably safe. If your database contains classified
information, you should go for a bigger key, which is harder to crack. But the bigger the
key, the higher the performance impact will be. This being said, the performance impact
of TDE is relatively low.


Reference: Microsoft SQL Server 2012 Security Cookbook

List of services started automatically by Windows that you could consider stopping

# DHCP Client: On most servers, IP addresses are fixed and DHCP is not needed.

#DNS Client: This caches DNS names locally.

#Network Location Awareness: This collects and stores the configuration information
for the network and notifies the programs when this information is modified. You can't
disable it unless you use the Windows 2008 Advanced Firewall.

#Print Spooler: This loads the files to the memory for printing later. It can be disabled
if you don't print from the server.

#Windows Error Reporting Service: This allows errors to be reported when programs
stop working or responding, and allows existing solutions to be delivered. It can safely
be disabled.

#Windows Firewall: You can disable this service, if you are using a network firewall.

#Shell Hardware Detection: This activates AutoPlay for removable devices.
On Windows Server 2008 R2, this service stops when nobody is logged in,

to minimize risks. You can disable it.

Reference: Microsoft SQL Server 2012 Security
Cookbook

Ports and Protocols Used by Microsoft SQL Server

Service / PurposeProtocolPort
Analysis Services connections via HTTP (default)TCP80
Analysis Services connections via HTTPS (default)TCP443
ClusteringUDP135
ClusteringTCP135 (RPC) / 3343 (Cluster Network Driver) / 445 SMB / 139 NetBIOS / 5000-5099 (RPC) / 8011-8031 (RPC)
Database MirroringTCPThere is no default port for this service. Use the following T-SQL statements to identify which ports are in use: SELECT name, port FROM sys.tcp_endpoints.
Dedicated Administrator ConnectionTCP1434 by default (local port). But this port is assigned dynamically by SQL Server during startup.
FilestreamTCP139 y 445.
Microsoft Distributed Transaction Coordinator (MS DTC)TCP135
Reporting services Web ServicesTCP80
Reporting Services configured for use through HTTPSTCP1433
Service BrokerTCP4022
SQL Server 2008 Analysis ServicesTCP2382 (SQL Server Browser Services for SSAS port)
2383 (Clusters will listen only on this port)
SQL Server Browser Service (Database Engine)UDP1434. Might be required when using named instances.
SQL Server Browser ServiceTCP2382
SQL Server default instance running over an HTTPS endpoint.TCP443
SQL Server Instance (Database Engine) running over an HTTP endpoint.TCP80 y 443 (SSL).
SQL Server Integration ServicesTCP135 (DCOM).
SQL over TCP (default instance)TCP1433
Transact-SQL DebuggerTCP135
Windows Management InstrumentationTCP135 (DCOM)



References:


Configuring the Windows Firewall to Allow SQL Server Access.
http://msdn.microsoft.com/en-us/library/cc646023.aspx 

Enable a network for cluster use.
http://technet.microsoft.com/en-us/library/cc728293(WS.10).aspx


Friday, September 12, 2014

Script to list data types of all columns in a Database in SQL Server

SQL Server tables displays the data type of
each column inside the table. You can do this dozens of ways, but a popular method shown in
the following example joins the sys.objects table with the sys.columns table. There are two
functions that you may not be familiar with in the following code. The TYPE_NAME() function
translates the data type id into its proper name. To go the opposite direction, you could use the
TYPE_ID() function. The other function of note is SCHEMA_ID(), which is used to return the
identity value for the schema. This is useful primarily when you want to write reports against the
SQL Server metadata.


USE AdventureWorks
GO

SELECT o.NAME AS ObjectName
 ,c.NAME AS ColumnName
 ,TYPE_NAME(c.user_type_id) AS DataType
FROM sys.objects o
INNER JOIN sys.columns c ON o.object_id = c.object_id
WHERE o.NAME = 'Department'
 AND o.Schema_ID = SCHEMA_ID('HumanResources')

Tuesday, June 10, 2014

Script to automatically create insert statements for table data in SQL Server

CREATE procedure  [dbo].[INS]                             
(                                                         
   @Query  Varchar(MAX)                                                         
)                             
AS                            
   Set nocount ON                 
DEclare @WithStrINdex as INT                           
DEclare @WhereStrINdex as INT                           
DEclare @INDExtouse as INT                            
Declare @SchemaAndTAble VArchar(270)                           
Declare @Schema_name  varchar(30)                           
Declare @Table_name  varchar(240)                           
declare @Condition  Varchar(MAX)                             
SET @WithStrINdex=0                           
SELECT @WithStrINdex=CHARINDEX('With',@Query )                           
, @WhereStrINdex=CHARINDEX('WHERE', @Query)                           
IF(@WithStrINdex!=0)                           
Select @INDExtouse=@WithStrINdex                           
ELSE                           
Select @INDExtouse=@WhereStrINdex                           
Select @SchemaAndTAble=Left (@Query,@INDExtouse-1)                                                     
select @SchemaAndTAble=Ltrim (Rtrim( @SchemaAndTAble))                           
Select @Schema_name= Left (@SchemaAndTAble, CharIndex('.',@SchemaAndTAble )-1)                           
,      @Table_name = SUBSTRING(  @SchemaAndTAble , CharIndex('.',@SchemaAndTAble )+1,LEN(@SchemaAndTAble) )                           
,      @CONDITION=SUBSTRING(@Query,@WhereStrINdex+6,LEN(@Query))--27+6                           
Declare   @COLUMNS  table (Row_number SmallINT , Column_Name VArchar(Max) )                             
Declare @CONDITIONS as varchar(MAX)                             
Declare @Total_Rows as SmallINT                             
Declare @Counter as SmallINT             
declare @ComaCol as varchar(max)           
select @ComaCol=''                  
Set @Counter=1                             
set @CONDITIONS=''                             
INsert INTO @COLUMNS                             
Select  Row_number()Over (Order by ORDINAL_POSITION ) [Count] ,Column_Name FRom INformation_schema.columns Where Table_schema=@Schema_name                             
And table_name=@Table_name        
and Column_Name not in ('SyncDestination','PendingSyncDestination' ,'SkuID','SaleCreditedto')                  
select @Total_Rows= Count(1) FRom  @COLUMNS                             
             Select @Table_name= '['+@Table_name+']'                     
             Select @Schema_name='['+@Schema_name+']'                     
While (@Counter<=@Total_Rows )                             
begin                              
--PRINT @Counter                             
    select @ComaCol= @ComaCol+'['+Column_Name+'],'           
    FROM @COLUMNS                             
Where [Row_number]=@Counter                         
select @CONDITIONS=@CONDITIONS+ ' +Case When ['+Column_Name+'] is null then ''Null'' Else ''''''''+                             
 Replace( Convert(varchar(Max),['+Column_Name+']  ) ,'''''''',''''  )                             
  +'''''''' end+'+''','''                             
FROM @COLUMNS                             
Where [Row_number]=@Counter                             
SET @Counter=@Counter+1                              
End                             
select @CONDITIONS=Right(@CONDITIONS,LEN(@CONDITIONS)-2)                             
select @CONDITIONS=LEFT(@CONDITIONS,LEN(@CONDITIONS)-4)             
select @ComaCol= substring (@ComaCol,0,  len(@ComaCol) )                           
select @CONDITIONS= '''INSERT INTO '+@Schema_name+'.'+@Table_name+ '('+@ComaCol+')' +' Values( '+'''' + '+'+@CONDITIONS                             
select @CONDITIONS=@CONDITIONS+'+'+ ''')'''                             
Select @CONDITIONS= 'Select  '+@CONDITIONS +'FRom  ' +@Schema_name+'.'+@Table_name+' With(NOLOCK) ' + ' Where '+@Condition                             
print(@CONDITIONS)                             
Exec(@CONDITIONS) 
Exec [dbo].[INS]  'Person.PersonPhone where 1=1'

Thursday, October 24, 2013

Script to rename all tables Starting with "wd_" with script in SQL Server


-- using my tempdb as a sandbox...
USE tempdb
GO
CREATE TABLE wd_table01(x int)
CREATE TABLE wd_table02(x int)
CREATE TABLE wd_table03(x int)
GO
IF OBJECT_ID('tempdb..#tables') IS NOT NULL DROP TABLE #tables;
SELECT TABLE_NAME AS tbl
INTO #tables
FROM INFORMATION_SCHEMA.TABLES
WHERE table_name LIKE 'wd_%'
DECLARE @sql varchar(8000);
SELECT @sql=
(       SELECT 'exec sp_rename '''+tbl+''', '''+REPLACE(tbl,'wd_','')+''';'+CHAR(10)
        FROM #tables
        FOR XML PATH(''));
EXEC(@sql);

Wednesday, October 2, 2013

How do I create foreign Keyrelationship with a table in a different database?

You would need to manage the referential constraint across databases using a Trigger.
Basically you create an insert, update trigger to verify the existence of the Key in the Primary key table. If the key does not exist then revert the insert or update and then handle the exception.
Example:
Create Trigger dbo.MyTableTrigger ON dbo.MyTable, After Insert, Update
As
Begin

   If NOT Exists(select PK from OtherDB.dbo.TableName where PK in (Select FK from inserted) BEGIN
      -- Handle the Referential Error Here
   END

END

Edited: Just to clarify. This is not the best approach with enforcing referential integrity. Ideally you would want both tables in the same db but if that is not possible. Then the above is a potential work around for you.

Credits:John Hartsock