Wednesday, 6 August 2014


Crate Insert Script using Sql Procedure:

CREATE procedure  [dbo].[GenerateInsertScript]                            
(                                                        
   @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)

Steps to use it

1. exec GenerateInsertScript 'dbo.Table where 1=1'
2 Exec GenerateInsertScript  'Dbo.test where name =''neeraj''' * for string




Friday, 4 July 2014

How to configure SQL Server Session State with Custom Database

There are two steps got to follow to enable the SQL Server Session state to work

1. Configuring the database to support the SQL Server Session state.
2. Configuring your application to use SQL Server Session state.

1. Configuring the database to support the SQL Server Session state.
.Net framework has a tool aspnet_regsql which you can use to add the table and stored procedure to support SQL Server Session state. You can find this tool in the following folder.
C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\ aspnet_regsql.exe
You can run this exe from window command prompt or you can directly run from SDK Command prompt.
Executing the following command enables SQL Server Session state for a database server named local and store it in a custom database called CustomSessionDB.
aspnet_regsql -C "Data Source=local;User Id=sa; Password=Sql2005" -ssadd -sstype c -d CustomSessionDB
Executing this command creates a new database named CustomSessionDB that contains both the tables and stored procedures for storing Session state.

2. Configuring your application to use SQL Server Session state.
To Configuring your application to use SQL Server Session state change the session state session as follows:
<sessionState mode=" SQLServer" sqlConnectionString="data source=local;user id=sa;password=Sql2005;database=CustomSessionDB" timeout="30" allowCustomSqlDatabase ="true" />


Thursday, 3 July 2014

Memory Measurements in Computer

Bit 1 or 0
1 Byte 8 bits
1 Kilobyte 1024 bytes
1 Megabyte 1024 kilobytes
1 Gigabyte 1024 Megabyte
1 Terabyte 1024 Gigabytes
1 Petabyte 1024 Terabytes
1 Exabyte 1024 Petabytes
1 Zettabyte 1024 Exabytes
1 Yottabyte 1024 Zettabytes

Time Calculation

What is a millisecond (ms)?

A millisecond is a unit of time. The symbol for millisecond is ms. There are 1,000 milliseconds in a second.

What is a minute (min)?

A minute is a unit of time. The symbol for minute is min. There are 60 minutes in an hour and 60 seconds in a minute.

Definitions

Below are definitions relating to these conversion formulas:
Unit Symbol Description
nanosecond ns
microsecond μs 1 microsecond = 1,000 nanoseconds
millisecond ms 1 millisecond = 1,000 microseconds
second (base unit of Time) sec or s 1 second = 1,000 milliseconds
minute min 1 minute = 60 seconds
hour hr 1 hours = 60 minutes
day d 1 day = 24 hours
week wk 1 week = 7 days
fortnight 4tnite 1 4tnite = 2 weeks or 14 days

Create Dynamic Code using Sql procedure in C#

We can create the dynamic codes using sql as follows(This is contribution by Santh Soft System)

Create PROCEDURE usp_getCode
(
@objName nvarchar(100)
)
AS
SET NOCOUNT ON
DECLARE @parameterCount int
DECLARE @errMsg varchar(100)
DECLARE @parameterAt varchar(1)
DECLARE @connName varchar(100)
DECLARE @outputValues varchar(100)
--Change the following variable to the name of your connection instance
SET @connName='conn.Connection'
SET @parameterAt=''
SET @outputValues=''
SELECT
dbo.sysobjects.name AS ObjName,
dbo.sysobjects.xtype AS ObjType,
dbo.syscolumns.name AS ColName,
dbo.syscolumns.colorder AS ColOrder,
dbo.syscolumns.length AS ColLen,
dbo.syscolumns.colstat AS ColKey,
dbo.syscolumns.isoutparam AS ColIsOut,
dbo.systypes.xtype
INTO #t_obj
FROM
dbo.syscolumns INNER JOIN
dbo.sysobjects ON dbo.syscolumns.id = dbo.sysobjects.id INNER JOIN
dbo.systypes ON dbo.syscolumns.xtype = dbo.systypes.xtype
WHERE
(dbo.sysobjects.name = @objName)
AND
(dbo.systypes.status <> 1)
ORDER BY
dbo.sysobjects.name,
dbo.syscolumns.colorder

SET @parameterCount=(SELECT count(*) FROM #t_obj)
IF(@parameterCount<1) SET @errMsg='No Parameters/Fields found for ' + @objName
IF(@errMsg is null)
BEGIN
PRINT 'try'
PRINT ' {'
PRINT ' SqlParameter[] paramsToStore = new SqlParameter[' + cast(@parameterCount as varchar) + '];'
PRINT ''

DECLARE @source_name nvarchar,@source_type varchar,
@col_name nvarchar(100),@col_order int,@col_type varchar(20),
@col_len int,@col_key int,@col_xtype int,@col_redef varchar(20), @col_isout tinyint

DECLARE cur CURSOR FOR
SELECT * FROM #t_obj
OPEN cur
-- Perform the first fetch.
FETCH NEXT FROM cur INTO @source_name,@source_type,@col_name,@col_order,@col_len,@col_key,@col_isout,@col_xtype

if(@source_type=N'U') SET @parameterAt='@'
-- Check @@FETCH_STATUS to see if there are any more rows to fetch.
WHILE @@FETCH_STATUS = 0
BEGIN
SET @col_redef=(SELECT CASE @col_xtype
WHEN 34 THEN 'Image'
WHEN 35 THEN 'Text'
WHEN 36 THEN 'UniqueIdentifier'
WHEN 48 THEN 'TinyInt'
WHEN 52 THEN 'SmallInt'
WHEN 56 THEN 'Int'
WHEN 58 THEN 'SmallDateTime'
WHEN 59 THEN 'Real'
WHEN 60 THEN 'Money'
WHEN 61 THEN 'DateTime'
WHEN 62 THEN 'Float'
WHEN 99 THEN 'NText'
WHEN 104 THEN 'Bit'
WHEN 106 THEN 'Decimal'
WHEN 122 THEN 'SmallMoney'
WHEN 127 THEN 'BigInt'
WHEN 165 THEN 'VarBinary'
WHEN 167 THEN 'VarChar'
WHEN 173 THEN 'Binary'
WHEN 175 THEN 'Char'
WHEN 231 THEN 'NVarChar'
WHEN 239 THEN 'NChar'
ELSE '!MISSING'
END AS C)

--Write out the parameter
PRINT ' paramsToStore[' + cast(@col_order-1 as varchar)
+ '] = new SqlParameter(''' + @parameterAt + @col_name
+ ''', SqlDbType.' + @col_redef
+ ');'

--Write out the parameter direction it is output
IF(@col_isout=1)
BEGIN
PRINT ' paramsToStore['+ cast(@col_order-1 as varchar) +'].Direction=ParameterDirection.Output;'
SET @outputValues=@outputValues+' ' +REPLACE(@col_name,'@','') +'=paramsToStore['+ cast(@col_order-1 as varchar) +'].Value;'
END
ELSE
BEGIN
--Write out the parameter value line
PRINT ' paramsToStore['+ cast(@col_order-1 as varchar) + '].Value = '+ REPLACE(@col_name,'@','') +';'
END
--If the type is a string then output the size declaration
-- IF(@col_xtype=231)OR(@col_xtype=167)OR(@col_xtype=175)OR(@col_xtype=99)OR(@col_xtype=35)
-- BEGIN
-- PRINT ' paramsToStore[' + cast(@col_order-1 as varchar) + '].Size=' + cast(@col_len as varchar) + ';'
-- END

-- This is executed as long as the previous fetch succeeds.
FETCH NEXT FROM cur INTO @source_name,@source_type,@col_name,@col_order, @col_len,@col_key,@col_isout,@col_xtype
END
PRINT ''
PRINT ' SqlHelper.ExecuteNonQuery(' + @connName + ', CommandType.StoredProcedure,''' + @objName + ''', paramsToStore);'
PRINT @outputValues
PRINT ' }'
PRINT 'catch(Exception excp)'
PRINT ' {'
PRINT ' }'
PRINT 'finally'
PRINT ' {'
PRINT ' ' + @connName + '.Dispose();'
PRINT ' ' + @connName + '.Close();'
PRINT ' }'
CLOSE cur
DEALLOCATE cur
END
if(LEN(@errMsg)>0) PRINT @errMsg
DROP TABLE #t_obj
SET NOCOUNT ON