Showing posts with label SQL Server. Show all posts
Showing posts with label SQL Server. Show all posts

25 February, 2014

Generate class from database table in C#


Using SQL Query:
DECLARE @TableName VARCHAR(MAX) = 'Users'
DECLARE @TableSchema VARCHAR(MAX) = 'dbo'
DECLARE @result varchar(max) = ''
 
SET @result = @result + 'using System;' + CHAR(13) + CHAR(13) 
 
IF (@TableSchema IS NOT NULL) 
BEGIN
    SET @result = @result + 'namespace ' + @TableSchema  + CHAR(13) + '{' + CHAR(13) 
END
 
SET @result = @result + '    public class ' + @TableName + CHAR(13) + '    {' + CHAR(13) 
 
SET @result = @result + '        #region Instance Properties' + CHAR(13)  
 
SELECT @result = @result + CHAR(13) 
    + '        public ' + ColumnType + ' ' + ColumnName + ' { get; set; } ' + CHAR(13) 
FROM
(
    SELECT  c.COLUMN_NAME   AS ColumnName 
        , CASE c.DATA_TYPE   
            WHEN 'bigint' THEN
                CASE C.IS_NULLABLE
                    WHEN 'YES' THEN 'Int64?' ELSE 'Int64' END
            WHEN 'binary' THEN 'Byte[]'
            WHEN 'bit' THEN 
                CASE C.IS_NULLABLE
                    WHEN 'YES' THEN 'Boolean?' ELSE 'Boolean' END            
            WHEN 'char' THEN 'String'
            WHEN 'date' THEN
                CASE C.IS_NULLABLE
                    WHEN 'YES' THEN 'DateTime?' ELSE 'DateTime' END                        
            WHEN 'datetime' THEN
                CASE C.IS_NULLABLE
                    WHEN 'YES' THEN 'DateTime?' ELSE 'DateTime' END                        
            WHEN 'datetime2' THEN  
                CASE C.IS_NULLABLE
                    WHEN 'YES' THEN 'DateTime?' ELSE 'DateTime' END                        
            WHEN 'datetimeoffset' THEN 
                CASE C.IS_NULLABLE
                    WHEN 'YES' THEN 'DateTimeOffset?' ELSE 'DateTimeOffset' END                                    
            WHEN 'decimal' THEN  
                CASE C.IS_NULLABLE
                    WHEN 'YES' THEN 'Decimal?' ELSE 'Decimal' END                                    
            WHEN 'float' THEN 
                CASE C.IS_NULLABLE
                    WHEN 'YES' THEN 'Single?' ELSE 'Single' END                                    
            WHEN 'image' THEN 'Byte[]'
            WHEN 'int' THEN  
                CASE C.IS_NULLABLE
                    WHEN 'YES' THEN 'Int32?' ELSE 'Int32' END
            WHEN 'money' THEN
                CASE C.IS_NULLABLE
                    WHEN 'YES' THEN 'Decimal?' ELSE 'Decimal' END                                                
            WHEN 'nchar' THEN 'String'
            WHEN 'ntext' THEN 'String'
            WHEN 'numeric' THEN
                CASE C.IS_NULLABLE
                    WHEN 'YES' THEN 'Decimal?' ELSE 'Decimal' END                                                            
            WHEN 'nvarchar' THEN 'String'
            WHEN 'real' THEN 
                CASE C.IS_NULLABLE
                    WHEN 'YES' THEN 'Double?' ELSE 'Double' END                                                                        
            WHEN 'smalldatetime' THEN 
                CASE C.IS_NULLABLE
                    WHEN 'YES' THEN 'DateTime?' ELSE 'DateTime' END                                    
            WHEN 'smallint' THEN 
                CASE C.IS_NULLABLE
                    WHEN 'YES' THEN 'Int16?' ELSE 'Int16'END            
            WHEN 'smallmoney' THEN  
                CASE C.IS_NULLABLE
                    WHEN 'YES' THEN 'Decimal?' ELSE 'Decimal' END                                                                        
            WHEN 'text' THEN 'String'
            WHEN 'time' THEN 
                CASE C.IS_NULLABLE
                    WHEN 'YES' THEN 'TimeSpan?' ELSE 'TimeSpan' END                                                                                    
            WHEN 'timestamp' THEN 
                CASE C.IS_NULLABLE
                    WHEN 'YES' THEN 'DateTime?' ELSE 'DateTime' END                                    
            WHEN 'tinyint' THEN 
                CASE C.IS_NULLABLE
                    WHEN 'YES' THEN 'Byte?' ELSE 'Byte' END                                                
            WHEN 'uniqueidentifier' THEN 'Guid'
            WHEN 'varbinary' THEN 'Byte[]'
            WHEN 'varchar' THEN 'String'
            ELSE 'Object'
        END AS ColumnType
        , c.ORDINAL_POSITION 
FROM    INFORMATION_SCHEMA.COLUMNS c
WHERE   c.TABLE_NAME = @TableName and ISNULL(@TableSchema, c.TABLE_SCHEMA) = c.TABLE_SCHEMA  
) t
ORDER BY t.ORDINAL_POSITION
 
SET @result = @result + CHAR(13) + '        #endregion Instance Properties' + CHAR(13)  
 
SET @result = @result  + '    }' + CHAR(13)
 
IF (@TableSchema IS NOT NULL) 
BEGIN
    SET @result = @result + '}' 
END
 
PRINT @result


Output:
using System;

namespace dbo
{
    public class Users
    {
        #region Instance Properties

        public Int32 SysID { getset; } 

        public String UserID { getset; } 

        public String UserName { getset; } 

        public String Password { getset; } 

        public String emailID { getset; } 

        public Boolean IsActive { getset; } 

        public DateTime CreatedWhenDtm { getset; } 

        public String CreatedBy { getset; } 

        public DateTime UpdatedWhenDtm { getset; } 

        public String UpdatedBy { getset; } 

        #endregion Instance Properties
    }
}

29 October, 2013

How to get the row count of all tables in a SQL SERVER

1) Using  sp_MSForEachTable SP
sp_MSForEachTable 'DECLARE @t AS VARCHAR(MAX); 
SELECT @t = CAST(COUNT(1) as VARCHAR(MAX)) 
+ CHAR(9) + CHAR(9) + ''?'' FROM ? ; PRINT @t';
Output:  
 
 
 






2) Using System Table.
 
SELECT 
    sc.name +'.'+ ta.name TableName, SUM(pa.rows) RowCnt
FROM 
    sys.tables ta
INNER JOIN sys.partitions pa
    ON pa.OBJECT_ID = ta.OBJECT_ID
INNER JOIN sys.schemas sc
    ON ta.schema_id = sc.schema_id
WHERE 
 ta.is_ms_shipped = 0 AND pa.index_id IN (1,0)
GROUP BY 
 sc.name,ta.name
ORDER BY 
 SUM(pa.rows) DESC
 
Output:  








 

02 April, 2013

Cannot login to network server in sql server

GO to "Sql Server Configuration Manager"

Select Sql server Services

Check following service are running
- Sql Server(Instance Name)
- Sql Server Browser

Go to "Sql Server Network Configuration"
- Select Protocol for <Instance Name>

 Now check TCP/IP and Named Pipes is Enable.

and make sure Your system Firewall should not block SQL Server port. SQL SERVER port is by Default 1433

27 February, 2013

Removing a Server name from MS SQL Server Management Studio 2008 'Connect to Server' Drop-down list


Download utility from http://ssmsmru.codeplex.com/

OR

Rename Or Delete following file.

In Windows 7, it's in the following:

SQL 2005:
C:\Users\<USER>\AppData\Roaming\Microsoft\Microsoft SQL Server\90\Tools\Shell\mru.dat

SQL 2008:
C:\Users\<USER>\AppData\Roaming\Microsoft\Microsoft SQL Server\100\Tools\Shell\SqlStudio.bin


In Windows XP, it's in the following:

SQL 2005:
C:\Users\<USER>\AppData\Roaming\Microsoft\Microsoft SQL Server\90\Tools\Shell\mru.dat

SQL 2008:
C:\Users\<USER>\AppData\Roaming\Microsoft\Microsoft SQL Server\100\Tools\Shell\SqlStudio.bin

25 December, 2012

Maximum characters of varchar max in sql server

Maximum 2^31-1 byte (2GB).

[2,147,483,647] Character

1 character = 1 byte


Variable-length, non-Unicode string data. n defines the string length and can be a value from 1 through 8,000. max indicates that the maximum storage size is 2^31-1 bytes (2 GB). The storage size, in bytes, is the value of the actual data entered + 2 bytes. The ISO synonyms for varchar are char varying or character varying.

Ref:

30 June, 2011

New Date and Time Functions in SQL Server 2008

Introduction

SQL Server 2008 introduces five new date and time functions namely SYSDATETIME, SYSDATETIMEOFFSET, SYSUTCDATETIME, SWITCHOFFSET and TODATETIMEOFFSET.

In this article described new functions in detail.


1) SYSDATETIME

The SYSDATETIME function basically returns the current system timestamp without the time zone information.


SELECT SYSDATETIME()

GO


SYSDATETIME

------------------------

2011-06-27 16:06:15.9409129


2) SYSDATETIMEOFFSET

The SYSDATETIMEOFFSET function is much similar to SYSDATETIME function; however it will also get you the time zone information.


SELECT SYSDATETIMEOFFSET()

GO


SYSDATETIMEOFFSET

-------------------------------

2011-06-27 16:07:01.8205935 +05:30


3) SYSUTCDATETIME

The SYSUTCDATETIME function returns the Greenwich Mean Time (GMT) or the Coordinated Universal Time (UTC). This time is derived from the current local system time and the time zone settings of the server where SQL Server 2008 is running.


SELECT SYSUTCDATETIME()

GO


SYSUTCDATETIME

------------------------

2011-06-27 10:38:25.6239407


4) SWITCHOFFSET

The SWITCHOFFSET function returns a DATETIMEOFFSET value that is changed from the stored time zone offset to a specified new time zone offset.


SELECT SYSDATETIMEOFFSET(),

SWITCHOFFSET (SYSDATETIMEOFFSET(), '+00:00')

GO


SYSDATETIMEOFFSET SWITCHOFFSET

------------------------------- -------------------------------------

2011-06-27 16:30:55.7127120 +05:30 2011-06-27 11:00:55.7127120 +00:00


5) TODATETIMEOFFSET

The TODATETIMEOFFSET function returns a DATETIMEOFFSET value that is translated from a DATETIME2 expression.


SELECT TODATETIMEOFFSET (GETDATE(),'+05:30')

GO


TODATETIMEOFFSET

---------------------------------

2011-06-27 16:26:56.340 +05:30



New DATETIME Data Types in SQL Server 2008


Introduction
From the beginning, Microsoft SQL Server DBAs have longed for two different data types, where you could store time and date separately. The long wait is over. In all of the older versions, we had only one data type that could store Datetime data type, and it stored both the value of the date and the value of the time.

Finally, in Microsoft SQL Server 2008, Microsoft is introducing a set of new data types for storing date, time and both date and time together. The new data types store more data as well, which means you can store dates anywhere from 01-01-01 to 9999-12-31 and also store time up to the fraction of 9999999.

There are four DATETIME data types newly introduced in SQL Server 2008. 
They are

DATE,
TIME,
DATETIMEOFFSET and 
DATETIME2.

1) DATE Data Type

The DATE data type stores only the date value.
The DATE data type returns data in the form of year, Month and Day. However, the format in which the date is returned is determined by the current language setting in SQL Server.
The range for the DATE data type is from 0001-01-01 through 9999-12-31.

When you specify a datetime value, SQL Server automatically converts that value into the DATE data type, which means that only the date portion is stored.

Example:

DECLARE @Date_Type DATE
SET @Date_Type = '2011-05-17 05:29:15.1234567'

SELECT @Date_Type

Result:
  2011-05-17

2) TIME Data type

The TIME data type stores only the time value. 
The TIME data type returns data in the form of hour, minute, second and fractional second.

The fractional part of the seconds can support up to 7 decimal places.
The precision of the TIME data type supports a range of 00:00:00.0000000 through 23:59:59.9999999.

When you specify the TIME datatype in a Transact-SQL statement, you can specify the precision of the stored values by including the appropriate number within parentheses.

For example, to specify a precision of 7, you would specify TIME(7).
For a precision of 5, you would specify TIME(5), and so on.

If you do not specify the precision, 7 are assumed.

Example:

DECLARE @Time_Type TIME
SET @Time_Type = '2011-05-17 05:29:15.1234567'

SELECT @Time_Type

Result:
  05:29:15.1234567

You can also specify a different precision when converting the data

DECLARE @DateTimeOffset_Type TIME
DECLARE @Time_Type TIME

SET @DateTimeOffset_Type = '2011-05-17 05:29:15.1234567'
SET @Time_Type = CAST(@DateTimeOffset_Type AS TIME(5))

SELECT @Time_Type

Result:
  05:29:15.1234600

Notice that the fractional seconds have been rounded up.
The original fractional seconds were .1234567. However, if you specify a precision of 5, SQL Server will round up the "67" fractional part, returning .1234600 in the results, rather than .1234500.

When inserting data into a TIME column, you can specify a time value or a datetime value as shown in the following INSERT statements:

INSERT INTO TableName (ID, Time_DataType)
VALUES ('1004, 05:23:10.1234567');    --Only Time
INSERT INTO TableName (ID, Time_DataType)
VALUES (1005, '2011-05-17 05:23:10.1234567');  --Date & Time

In both cases, only the time is inserted into the Time_DataType column.


3) DATETIME2 Data Type

The DATETIME2 data type stores the both date and time value.
The data type DATETIME2 is the combination of the data type DATE and TIME.
DATETIME2 is used to store both a date value ranging from 01-01-01 to 9999-12-31 as well as a time value 00:00:00.0000000 to 23:59:59.9999999.

Example:

DECLARE @DateTime2_Type DATETIME2
SET @DateTime2_Type = CONVERT(DATETIME2,'01/01/0001 16:14:00.1234567')

SELECT @DateTime2_Type

Result:
  0001-01-01 16:14:00.1234567 


We could limit the precision like (Precision value range 0-7),
DECLARE @DateTime2_Type DATETIME2(4)
SET @DateTime2_Type = CONVERT(DATETIME2,'01/01/0001 16:14:00.1234567')

SELECT @DateTime2_Type

Result:
  0001-01-01 16:14:00.1235

Notice that the fractional seconds have been rounded up.

4) DATETIMEOFFSET Data type

The DATETIMEOFFSET data type stores the date, time and time-zone offset value.
The DATETIMEOFFSET data type is nearly identical to the DATETIME2 data type, except that a DATETIMEOFFSET value includes one important addition that is a time-zone offset value.
The offset value represents the number of hours and minutes before or after Coordinated Universal Time (UTC).
positive number indicates the amount of time to add to the UTC to determine the local time. (+05:30).
negative number indicates the amount of time to subtract from the UTC to determine the local time. (-05:30)

The Date range is between 0001-01-01 and 9999-12-31.
The Time Range is between 00:00:00 and 23:59:59.9999999.
The Offset range is between -14:00 through +14:00.

Example:

DECLARE @DateTimeOffset_Type DATETIMEOFFSET
SET @DateTimeOffset_Type = CONVERT(DATETIMEOFFSET,'01/01/0001 16:14:00.1234567 +5:30')

SELECT @DateTimeOffset_Type

Result:
  0001-01-01 16:14:00.1234567 +05:30

You can also set the precision of the data type, like

DECLARE @DateTimeOffset_Type DATETIMEOFFSET(4)
SET @DateTimeOffset_Type = CONVERT(DATETIMEOFFSET,'01/01/0001 16:14:00.1234567 +5:30')

SELECT @DateTimeOffset_Type

Result:
  0001-01-01 16:14:00.1235 +05:30





Summary:

Data type
Format
Range
Accuracy
Storage size (bytes)
User-defined fractional second precision
Time zone offset
TIME
hh:mm:ss[.nnnnnnn]
00:00:00.0000000 to 23:59:59.9999999
100 nanoseconds
3 to 5
Yes
No
DATE
YYYY-MM-DD
00001-01-01 to 9999-12-31
1 day
3
No
No
SMALLDATETIME
YYYY-MM-DDhh:mm:ss
1900-01-01 to 2079-06-06
1 minute
4
No
No
DATETIME
YYYY-MM-DDhh:mm:ss[.nnn]
1753-01-01 to 9999-12-31
0.333 second
8
No
No
DATETIME2
YYYY-MM-DDhh:mm:ss[.nnnnnnn]
0001-01-01 00:00:00.0000000 to 9999-12-31 23:59:59.9999999
100 nanoseconds
6 to 8
Yes
No
DATETIMEOFFSET
YYYY-MM-DDhh:mm:ss[.nnnnnnn] [+|-]hh:mm
00001-01-01 00:00:00.0000000 to 9999-12-31 23:59:59.9999999 (in UTC)
100 nanoseconds
8 to 10
Yes
Yes