Thursday, July 05, 2012

Execute a command for a batch in Windows 2008 Server


ForFiles

This is a command in windows 20008 for applying specified command on each file for a batch. 
For example if want to delete files older than a specified time period then this command will help me accomplishing this task. 
This is a very useful and easy to understand command. 
Command for an example is given below : 

The mentioned below command will delete files older than 15 days in the folder "D:\YOURFOLDERNAME" and any sub directories in it. 


forfiles /p d:\yourfoldername /s /m *.txt /c "cmd /c del @file" /d -15


forfiles --command name
/p -- specifies that next argument is path 
/s -- specifies that sub directories should be scanned
/m -- file type or search criteria 
/c -- actual command which will be executed for each file
"cmd /c" and "@file" are default values for the argument /c
"cmd /c  yourcommand @file"
/d --specifies number of days 


Further details can referenced on mentioned below technet link. 

Thanks to TechNet.





Monday, June 11, 2012

Atlantis Schema Inspector - by "Atlantis Interactive"


Another handy tool to compare schema in SQL Server.

SQL Server Schema Comparison and Scripting Tool.

Atlantis Schema Inspector is an incredibly fast, flexible and complete (and free) SQL Server synchronization and SQL Script tool - use it to get your deployments right first time, every time.

Schema Inspector offers an easy and fast way to compare and synchronize schema elements of SQL Server databases whether live, test, snapshots or partial databases. Any changes can be checked speedily and easily without errors. It can save your development team lots of time and help you achieve your project delivery accurately and on time. Schema Inspector works in tandem with our Data Inspector and both combine with our SQL Everywhere to make a uniquely integrated “one stop” solution for all SQL developers and administrators alike.

You can confidently use Schema Inspector and Data Inspector to save hours of development time whether developing new SQL Server databases or migrating old systems over to new. The savings in development time will make a significant contribution to the ensuring your project will deliver solutions to your users on-time and on-budget. SQL Script can be a notoriously difficult way in which to perform SQL Server synchronization - Schema Inspector relieves the difficulties associated with your deployments.

Thanks to Atlantis Interactive UK Ltd.
Download from the link mentioned below : -

Please consider donating them. 

SQL Load Generator by CodePlex

A very handy tool to generate a good load, a must have tool. 

SQL Load Generator is used to run multiple concurrent queries against SQL Server. The user can choose the number of concurrent queries to run, provide different queries, choose SQL or domain accounts, and provide application name settings. SLG was developed using C# 3.5.

Here’s a summary of the features:


Runs multiple queries against SQL Server. You can add as many as you like.
Each query can be either a SQL User or Domain User.
You can specify an Application name for the connection.
You can specify the new of concurrent threads to use for each query.
You can start all queries, stop all queries, remove all queries.
There is logging (you can toggle on and off… it isn’t precisely thread safe, and can cause crashes when there are lots of failures on multiple threads) for failed queries.
You can set all the defaults on a per user basis, and persist them.
Each query has a # of Runs and a # of Fails counter. You can use the ‘Reset Counters’ feature to reset the total counts (not the per query counts).

You can save your settings via the ‘Options’ menu. You can add default items to the different dropdowns, provide default query settings, change the log locations, etc. You can also modify the stock connection string… though keep in mind some of the settings (particularly ‘pooling=false’ will affect the way the application works… namely, the connections to SQL Server won’t be closed). 



Download from the link mentioned below :  




Thanks to Pinal Dev who tweeted this. 



Wednesday, November 23, 2011

Calculate difference of Time only between two dates while discarding difference of dates in SQL Server/ extract time and calculate difference between two dates in SQL Server


DECLARE @DateTimeOne DATETIME
DECLARE @DateTimeTwo DATETIME

SET @DateTimeOne = '1900-01-01 10:41:09.250'
SET @DateTimeTwo = GETDATE()


--hour = hh
--minute = mi, n
--second = ss, s
--millisecond = ms


SELECT  DATEDIFF(mi,SUBSTRING(CONVERT(VARCHAR,@DateTimeOne, 121), 12, 12)
,SUBSTRING(CONVERT(VARCHAR,@DateTimeTwo, 121), 12, 12) ) MinuteDifferenceinDate

Friday, June 24, 2011

Working with Email Address in SQL Server ( Validate Email Address )

at times working with email addresses in sql server becomes difficult so
here is a UDF you can use to validate the email address

It will validate mentioned below list

No Spaces are allowed
email cant start with '@'
email cant end at '.'
@must be in email and only once
domain name should be at the end and must be at least two characters
email cant habe patterns like '..' or '.@'








CREATE FUNCTION [dbo].[validateEmailAddress]
(
@EmailAddress nVARCHAR(4000)
)
RETURNS TINYINT AS
BEGIN


DECLARE @Result TINYINT
SELECT @Result =
CASE WHEN
CHARINDEX(' ',LTRIM(RTRIM(@EmailAddress))) = 0
AND LEFT(LTRIM(@EmailAddress),1) <> '@'
AND RIGHT(RTRIM(@EmailAddress),1) <> '.'
AND CHARINDEX('.',@EmailAddress,CHARINDEX('@',@EmailAddress)) - CHARINDEX('@',@EmailAddress) > 1
AND LEN(LTRIM(RTRIM(@EmailAddress))) - LEN(REPLACE(LTRIM(RTRIM(@EmailAddress)),'@','')) = 1
AND CHARINDEX('.',REVERSE(LTRIM(RTRIM(@EmailAddress)))) >= 3
AND (CHARINDEX('.@',@EmailAddress) = 0 AND CHARINDEX('..',@EmailAddress) = 0)
THEN 1 ELSE  0 END

RETURN @Result

END



Example:- 

it will return 1 for correct email address and 0 for incorrect 
:
SELECT  dbo.validateEmailAddress('myemail@mydomain.com')  -- Correct

SELECT  dbo.validateEmailAddress('@myemail@m  domain.com')  -- Incorrect 


Tuesday, January 11, 2011

Best Practices for using DATETIME column in sql server 2005 and 2008

Best Practices for using DATETIME column in sql server 2005 and 2008

In production environment we have seen that there are certain times when you make a good query by applying best practices but you don’t get good results at the time of sorting.
This might happen because of DATETIME columns which are mostly used for sorting purpose and indexes for these columns do not give you appropriate results.
Mentioned below is tip for using DATETIME column which can enhance the speed of your query while maintaining same number of indexes.
This technique requires mentioned below changes in your table: - 
  1. One Persisted Computed Column (BIGINT) which will store DATETIME in integer format by removing special symbols from DATETIME
  2. This computed column will be added in the covering index
  3. Query will use this column instead of DATETIME column



Example :
/* Create Sample Table */
CREATE TABLE [dbo].[MyTable](
      [C1] [int] IDENTITY(1,1) NOT NULL,
      [C2] [DATETIME] NULL,
 CONSTRAINT [PK_MyTable] PRIMARY KEY CLUSTERED
(
      [C1] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO

/* Data Insert */
SET IDENTITY_INSERT [dbo].[MyTable] ON
INSERT [dbo].[MyTable] ([C1], [C2]) VALUES (1, CAST(0x00009E5E00000000 AS DATETIME))
INSERT [dbo].[MyTable] ([C1], [C2]) VALUES (2, CAST(0x00009E5F00000000 AS DATETIME))
INSERT [dbo].[MyTable] ([C1], [C2]) VALUES (3, CAST(0x00009E6000000000 AS DATETIME))
INSERT [dbo].[MyTable] ([C1], [C2]) VALUES (4, CAST(0x00009E6100000000 AS DATETIME))
INSERT [dbo].[MyTable] ([C1], [C2]) VALUES (5, CAST(0x00009E7D00000000 AS DATETIME))
INSERT [dbo].[MyTable] ([C1], [C2]) VALUES (6, CAST(0x00009E7E00000000 AS DATETIME))
SET IDENTITY_INSERT [dbo].[MyTable] OFF

/* Query */
DECLARE @D1 DATETIME
DECLARE @D2 DATETIME
SET         @D1 = GETDATE()-10
SET         @D2 = GETDATE()
SELECT      C1
            ,C2
FROM  MyTable
WHERE C2 BETWEEN @D1 AND @D2

/* Change in Table Add New Column that will store DATETIME in Integer Format */
ALTER TABLE MyTable
ADD [C3]  AS (CONVERT([bigint],CONVERT([varchar],[C2],(112))+replace(CONVERT([varchar],[C2],(114)),':',''),0)) PERSISTED

/* Existing Index for query */
CREATE NONCLUSTERED INDEX [Index_For_C2] ON MyTable
(
      [C2] ASC,
      [C1] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF,
 IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
GO

/* Add New Column to Existing Index for query */
CREATE NONCLUSTERED INDEX [Index_For_C2] ON MyTable
(
      [C3] ASC,
      [C2] ASC,
      [C1] ASC
)WITH (STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF,
DROP_EXISTING = ON, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
GO

/*Updated Query using Integer Column instead of DATETIME having same result set*/
DECLARE @D1 BIGINT
DECLARE @D2 BIGINT
SET         @D1 = (CONVERT([bigint],CONVERT([varchar],GETDATE()-10,(112))+replace(CONVERT([varchar],GETDATE()-10,(114)),':',''),0))
SET         @D2 = (CONVERT([bigint],CONVERT([varchar],GETDATE(),(112))+replace(CONVERT([varchar],GETDATE(),(114)),':',''),0))
SELECT      C1
            ,C2
FROM  MyTable
WHERE C3 BETWEEN @D1 AND @D2


The above query will now use the new updated index and will be much faster as it will get records by using an integer column instead of DATETIME column. 

Wednesday, November 03, 2010

SQL Server to MySQL Conversion using MySQL Migration Toolkit.

A simple and powerful tool for migrating data from SQL Server to MySQL.

It can import/export your data directly to database server and you can also generate Create and Insert scripts.

A useful tool by MySQL team.

You can download the tool by signing up on mentioned below site and download this tool

Sunday, December 27, 2009

winupdate86.exe is2010.exe Internet Security 2010 its a fake antivirus and how to remove it

Type gpedit.msc in RUN

Goto=> User Configurations
Goto=> Administrative Templates
Goto=> System
Goto=> Ctrl+Alt+Del Options
Double Click Remove Task Bar Manager
Click on DISABLE
Press OK

Your Task bar will be enables
now look for mentioned below exes and KILL process tree

Thursday, November 26, 2009

Export Microsoft SQL Server data to SQLITE

At time you need to interact with SQLITE and normally there are tools which are not free but i have found a tool which is very useful when you need to export data from Microsoft SQL Server to SQLITE.

You need to have a login for the mentioned below site, signup and download the utility.

This tool was made by Liron Levi.

Thursday, September 10, 2009

Import MYSQL Data to Microsoft SQL Server 2005

At times you my need to interact with mysql database and the method given below is very easy for Microsoft SQL Server guys to do stuff with mysql database.

1) You need to have a mysql instance configured.
2) Install the MySQL ODBC Driver for Microsoft SQL Server
3) Add MySQL Instance as a linked server to Microsoft SQL Server by issuing the mentioned below command.
4) Access and Import you MySQL Data right from Microsoft SQL Server Management Studio

Tuesday, July 28, 2009

Claim Unused space from table after Deletion of rows of after droppping columns

If you deleted rows and space used is same as previous then first thing you need to do is Rebuild Clustered Index.
It will release most of the unused space.

Secondly if you have dropped any variable length column then you can run the mentioned below command.
DBCC CLEANTABLE (AdventureWorks,"Production.Document", 0)

Wednesday, May 27, 2009

Search Suffix using Full Text Search in SQL Server 2005

A solution to search Suffix is given below as its a limitation in FTS that FTS cannot search suffix.

Its not recommended and not efficient as it requires another column but its a solution which can help you out in some cases.


1. Add a column in your table which stores the reverse of the string
like
SET NewColumnName = REVERSE(ColumnName)

Tuesday, May 05, 2009

Identify missing indexes in sql server 2005

SELECT DISTINCT DB_NAME(Database_ID) [Database]
,OBJECT_NAME(Object_ID) [Table]
,Equality_Columns
,Included_Columns
FROM sys.dm_db_missing_index_details mid
WHERE Database_ID = DB_ID()
ORDER BY 2

Monday, April 06, 2009

Computed Columns in SQL Server 2005

A computed column is computed from an expression that can use other columns in the same table. The expression can be a noncomputed column name, constant, function, variable, and any combination of these connected by one or more operators. The expression cannot be a subquery.

For example, in the AdventureWorks sample database, the TotalDue column of the Sales.SalesOrderHeader table has the definition: TotalDue AS Subtotal + TaxAmt + Freight.

Friday, March 27, 2009

Users get blocked when access same table while getting Unique IDs

--Table which will have the Unique IDs
CREATE TABLE dbo.CounterTable
(
Counter int IDENTITY(1,1) NOT NULL
)
GO
--Procedure which Inserts unique IDs in table and returns the New ID

Wednesday, March 18, 2009

Simple cursor Example in Microsoft SQL Server

DECLARE @String nVARCHAR(MAX)
DECLARE @getInputBuffer CURSOR
SET @getInputBuffer = CURSOR FOR
SELECT Text FROM Table

OPEN @getInputBuffer

FETCH NEXT
FROM @getInputBuffer INTO @String

WHILE @@FETCH_STATUS = 0

Get foreign keys of a table in SQL Server

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
WHERE OBJECT_NAME (f.referenced_object_id)   = 'TableName'
ORDER BY 2

Find /Remove New Line or Carriage Return Character in String or Text in SQL Server

1)

DECLARE @NewLine char(2)
SET @NewLine=char(13)+char(10)

SELECT *
FROM TABLENAME
WHERE CHARINDEX(@NewLine,ColumnName) > 0


2)

DECLARE @NewLine char(2)
SET @NewLine=char(13)

SELECT *
FROM TABLENAME
WHERE CHARINDEX(@NewLine,ColumnName) > 0



3)

DECLARE @NewLine char(2)
SET @NewLine=char(10)

SELECT *
FROM TABLENAME
WHERE CHARINDEX(@NewLine,ColumnName) > 0

Delete Duplicate Records Using Common Tabel Expression


there are many ways to delete the duplicates in a table but sometimes the group by doesnt seem to work so you can try out the new feature of Microsoft SQL Server "Common Table Expression"

With Dups as 
(
SELECT  row_number() over (
partition by ColumnName 
order by  ColumnName ) as RowNum
FROM Table
)
DELETE 
FROM Dups 
WHERE rownum > 1



Tuesday, January 13, 2009

Solution for Large volume of backup storage on tape with high performance and security

Linear Tape-Open (or LTO) is a magnetic tape data storage technology originally developed in the late 1990s as an open standards alternative to the proprietary magnetic tape formats that were available at the time. Seagate, Hewlett-Packard, and IBM initiated the LTO Consortium, which directs development and manages licensing and certification of media and mechanism manufacturers. The standard form-factor of LTO technology goes by the name "Ultrium", the original version of which was released in 2000 and could hold 100 GB of data in a single cartridge. The most recent version was released in 2007 and can hold 800 GB in the same size cartridge

http://h10010.www1.hp.com/wwpc/us/en/en/WF05a/12169-304612-3446236-3446236-3446236-3454484.html

http://en.wikipedia.org/wiki/Linear_Tape-Open