Data types for SQL Server

March 18, 2013 at 11:15 PMMeherunnessa Mitu

Following are the various data types of SQL Server - 

Character strings:

Data typeDescriptionStorage
char(n) Fixed-length character string. Maximum 8,000 characters n
varchar(n) Variable-length character string. Maximum 8,000 characters  
varchar(max) Variable-length character string. Maximum 1,073,741,824 characters  
text Variable-length character string. Maximum 2GB of text data  

Unicode strings:

Data typeDescriptionStorage
nchar(n) Fixed-length Unicode data. Maximum 4,000 characters  
nvarchar(n) Variable-length Unicode data. Maximum 4,000 characters  
nvarchar(max) Variable-length Unicode data. Maximum 536,870,912 characters  
ntext Variable-length Unicode data. Maximum 2GB of text data  

Binary types:

Data typeDescriptionStorage
bit Allows 0, 1, or NULL  
binary(n) Fixed-length binary data. Maximum 8,000 bytes  
varbinary(n) Variable-length binary data. Maximum 8,000 bytes  
varbinary(max) Variable-length binary data. Maximum 2GB  
image Variable-length binary data. Maximum 2GB  

Number types:

Data typeDescriptionStorage
tinyint Allows whole numbers from 0 to 255 1 byte
smallint Allows whole numbers between -32,768 and 32,767 2 bytes
int Allows whole numbers between -2,147,483,648 and 2,147,483,647 4 bytes
bigint Allows whole numbers between -9,223,372,036,854,775,808 and 9,223,372,036,854,775,807 8 bytes
decimal(p,s) Fixed precision and scale numbers.

Allows numbers from -10^38 +1 to 10^38 –1.

The p parameter indicates the maximum total number of digits that can be stored (both to the left and to the right of the decimal point). p must be a value from 1 to 38. Default is 18.

The s parameter indicates the maximum number of digits stored to the right of the decimal point. s must be a value from 0 to p. Default value is 0

5-17 bytes
numeric(p,s) Fixed precision and scale numbers.

Allows numbers from -10^38 +1 to 10^38 –1.

The p parameter indicates the maximum total number of digits that can be stored (both to the left and to the right of the decimal point). p must be a value from 1 to 38. Default is 18.

The s parameter indicates the maximum number of digits stored to the right of the decimal point. s must be a value from 0 to p. Default value is 0

5-17 bytes
smallmoney Monetary data from -214,748.3648 to 214,748.3647 4 bytes
money Monetary data from -922,337,203,685,477.5808 to 922,337,203,685,477.5807 8 bytes
float(n) Floating precision number data from -1.79E + 308 to 1.79E + 308.

The n parameter indicates whether the field should hold 4 or 8 bytes. float(24) holds a 4-byte field and float(53) holds an 8-byte field. Default value of n is 53.

4 or 8 bytes
real Floating precision number data from -3.40E + 38 to 3.40E + 38 4 bytes

Date types:

Data typeDescriptionStorage
datetime From January 1, 1753 to December 31, 9999 with an accuracy of 3.33 milliseconds 8 bytes
datetime2 From January 1, 0001 to December 31, 9999 with an accuracy of 100 nanoseconds 6-8 bytes
smalldatetime From January 1, 1900 to June 6, 2079 with an accuracy of 1 minute 4 bytes
date Store a date only. From January 1, 0001 to December 31, 9999 3 bytes
time Store a time only to an accuracy of 100 nanoseconds 3-5 bytes
datetimeoffset The same as datetime2 with the addition of a time zone offset 8-10 bytes
timestamp Stores a unique number that gets updated every time a row gets created or modified. The timestamp value is based upon an internal clock and does not correspond to real time. Each table may have only one timestamp variable  

Other data types:

Data typeDescription
sql_variant Stores up to 8,000 bytes of data of various data types, except text, ntext, and timestamp
uniqueidentifier Stores a globally unique identifier (GUID)
xml Stores XML formatted data. Maximum 2GB
cursor Stores a reference to a cursor used for database operations
table Stores a result-set for later processing

 

 

 

Reference: w3schools.com

Posted in: SQL Server

Tags: , ,

SQL Server: Restrict Login from Valid Machine IPs Only (Using Logon Trigger)

March 18, 2013 at 10:10 PMMehedi Hasan

Create a table and put the IP’s to be blocked in that table, while checking the IP we can get the data from this table and we can decide whether to block it or allow it. So the entire process will be like below.

 

 

Creating a table and storing IP address

I’m going to create a table in master database and store the IPs.

CREATE TABLE master.dbo.IPBLock (ipaddress VARCHAR(15))


 

 

Create a DDL Logon trigger

 

This trigger will block all the connections from the IP address however you can add some more filters in the trigger to allow admin connections, or system admin etc

 

 

 

 

 

CREATE TRIGGER block_ipaddress

ON ALL SERVER

FOR LOGON

AS

BEGIN

            DECLARE @capturedip NVARCHAR(15);

            SET @capturedip = (SELECT EVENTDATA().value('(/EVENT_INSTANCE/ClientHost)[1]', 'NVARCHAR(15)'));

            IF EXISTS(SELECT ipaddress FROM master.dbo.IPBLock WHERE ipaddress = @capturedip)

            BEGIN

                        Print 'Your IP Address is blocked, Contact Administrator'

                        ROLLBACK

            END

            ELSE

            BEGIN

                        DECLARE @IPRange VARCHAR(15)

                        SELECT @IPRange= SUBSTRING(@capturedip,1,LEN(@capturedip)-CHARINDEX('.',REVERSE(@capturedip)))+'.*'

                        IF EXISTS(SELECT ipaddress FROM master.dbo.IPBLock WHERE ipaddress = @IPRange)

                        BEGIN

                            Print 'Your IP Address Range is blocked, Contact Administrator'

                            ROLLBACK

                        END

            END

END

GO 

 


Testing the Trigger

To test this trigger, I’m going to insert some IP address into the table to block their connection. You can also insert IP range in to the table.


INSERT INTO IPBLock VALUES('192.168.1.3')

INSERT INTO IPBLock VALUES('192.168.1.4')

INSERT INTO IPBLock VALUES('10.100.25.*')


 

Posted in: SQL | SQL Server

Tags:

How to Restore SQL Server 2005 Suspect Database

February 17, 2013 at 6:58 PMMehedi Hasan

If you find your database in Suspect mode, then please keep your nerve strong. Just proceed step by step what I am written below. I think you will get out of this trouble. SQL Server 2005 introduced a new DB Status called Emergency. This mode can change the DB from Suspect mode to Emergency mode, so that you can retrieve the data in read only mode. The steps are... After executing the script given below, you will get back your database in operational mode. Actually I have tried with two of my existing live systems and found no data loss.

 

 

EXEC sp_resetstatus 'yourDBname';

ALTER DATABASE yourDBname SET EMERGENCY

DBCC checkdb('yourDBname')

ALTER DATABASE yourDBname SET SINGLE_USER WITH ROLLBACK IMMEDIATE

DBCC CheckDB ('yourDBname', REPAIR_ALLOW_DATA_LOSS)

ALTER DATABASE yourDBname SET MULTI_USER

 

 

 

Posted in: SQL Server

Tags:

C# Virtual

November 10, 2012 at 6:21 AMMehedi Hasan

 

What is the virtual keyword used for?

 

Virtual - If a base class method is to be overriden, it is defined using the keyword virtual (otherwise the sealed keyword is used to prevent overriding).

Note that the class member method may be overriden even if the virtual keyword is not used, but its usage makes the code more transparent & meaningful. In VB.NET, we may use the overridable keyword for this purpose.

 

When the override keyword is used to override the virtual method, in a scenario where the base class method is required in a child class along with the overriden method, then the base keyword may be used to access the parent class member. The following code example will make the usage more clear.


Code Example : 


 

public class Employee

{

  public virtual void SetBasic(float money) //This method may be overriden

  { Basic += money; }

}

 


public class Manager : Employee

{

  public override void SetBasic(float money) //This method is being overriden

  {

   float managerIncentive = 10000;

   base.SetSalary(money + managerIncentive); //Calling base class method

  }

}

 



 

Posted in: C Sharp

Tags:

C# ReadLine

June 11, 2012 at 11:55 PMMehedi Hasan

ReadLine is a StreamReader method. It returns the next text line from the file. By processing each line separately, we can apply logic to test the lines for validity or reject them. This avoids unnecessary complexity dealing with these lines later on.

 

Code Example : 

 

using System;

using System.Collections.Generic;

using System.IO;

 

class Program

{

    static void Main()

    {

const string f = "TextFile1.txt";

 

 

// Declare new List.

List<string> lines = new List<string>();

 

// Use using StreamReader for disposing.

using (StreamReader r = new StreamReader(f))

{

   // Use while != null pattern for loop

   string line;

   while ((line = r.ReadLine()) != null)

   {

lines.Add(line);

   }

}

 

// Print out all the lines.

foreach (string s in lines)

{

   Console.WriteLine(s);

}

    }

}

 

Output

 

Sample Text File Content

 

Posted in: C Sharp

Tags:

C# Dictionary

May 11, 2012 at 12:44 PMMehedi Hasan

The Dictionary type in the base class library is one of the most important ones. It is an implementation of a hashtable, which is an extremely efficient way to store keys for lookup. The Dictionary in .NET is well-designed.

 

Code Example :

 

using System;

using System.Collections.Generic;

 

class Program

{

    static void Main()

    {

// Use the dictionary.

Dictionary<int , string> dict = new Dictionary<int , string>();

dict.Add(1 , "riaz");

dict.Add(2 , "mishu");

dict.Add(3 , "mitu");

dict.Add(4 , "rabbi");

 

Console.WriteLine(dict[1]);

Console.WriteLine(dict[2]);

Console.WriteLine(dict[3]);

Console.WriteLine(dict[4]);

    }

}

 

Output

 

riaz

mishu

mitu

rabb

Posted in: C Sharp

Tags:

C# Interfaces- Why We Use Interface

April 1, 2012 at 8:06 PMMehedi Hasan

Interfaces in C # provide a way to achieve runtime polymorphism. Using interfaces we can invoke functions from different classes through the same Interface reference, whereas using virtual functions we can invoke functions from different classes in the same inheritance hierarchy through the same reference. Before things start getting difficult let me start using simple and short examples to explain the concept of interfaces.

Why We use Interface

So if an interface implements no functionality then why should we use them?Using interface based design concept provides loose coupling, component-based programming, easier maintainability, makes your code base more scalable and makes code reuse much more accessible because implementation is separated from the interface. Interfaces add a plug and play like architecture into your applications. Interfaces help define a contract (agreement or blueprint, however you chose to define it), between your application and other objects. This indicates what sort of methods, properties and events are exposed by an object.


For example let's take a vehicle. All vehicles have similar items, but are different enough that we could design an interface that holds all the common items of a vehicle. Some vehicles have 2 wheels, some have 4 wheels and can even have 1 wheel, though these are differences they have something in common, they're all movable, they all have some sort of engine, they all have doors, but each of these items may vary. So we can create an interface of a vehicle that has these properties, then we inherit from that interface to implement it.

While wheels, doors and engines are different they all rely on the same interface (I sure hope this is making sense). Interfaces allow us to create nice layouts for what a class is going to implement. Because of the guarantee the interface gives us, when many components use the same interface it allows us to easily interchange one component for another which is using the same interface. Dynamic programs begin to form easily from this. An interface is a contract that defines the signature of some piece of functionality.

So here's a simple example of an interface and implementing it. From the above example we're created a IVehicle interface that looks like this

namespace InterfaceExample
{
    public interface IVehicle
    {
        int Doors { get; set; }
        int Wheels { get; set; }
        Color VehicleColor { get; set; }
        int TopSpeed { get; set; }
        int Cylinders { get; set; }
        int CurrentSpeed { get; }
 
        string DisplayTopSpeed();
        void Accelerate(int step);
    }
}

Now we have our vehicle blueprint, and all classes that implement it must implement the items in our interface, whether it be a motorcycle, car, or truck class we know that all will contain the same functionality. Now for a sample implementation, in this example we'll create a motorcycle class that implements our IVehicle class. This class will contains everything we have defined in our interface,

namespace InterfaceExample
{
    public class Motorcycle : IVehicle
    {
        private int _currentSpeed = 0;

        public int Doors { get; set; }

        public int Wheels { get; set; }

        public Color VehicleColor { get; set; }

        public int TopSpeed { get; set; }

        public int HorsePower { get; set; }

        public int Cylinders { get; set; }

        public int CurrentSpeed
        {
            get { return _currentSpeed; }
        }


        public Motorcycle(int doors, int wheels, Color color, int topSpeed, int horsePower, int cylinders, int currentSpeed)
        {
            this.Doors = doors;
            this.Wheels = wheels;
            this.VehicleColor = color;
            this.TopSpeed = topSpeed;
            this.HorsePower = horsePower;
            this.Cylinders = cylinders;
            this._currentSpeed = currentSpeed;
        }

        public string DisplayTopSpeed()
        {
            return "Top speed is: " + this.TopSpeed;
        }

        public void Accelerate(int step)
        {
            this._currentSpeed += step;
        }
    }
}

Now in the same application we could interchange our Motorcycle class with a Truck class or a Car class and they will all have the same base functionality, that of a IVehicle.

So as you can see interface based development can make a developers life much easier, and our applications much cleaner, maintainable and extensible.




Article Source : http://dotnet.dzone.com/articles/c-interfaces-what-are-they-and

Posted in: C Sharp

Tags:

C# List

March 11, 2012 at 5:37 PMMehedi Hasan

First, the List type provides you with an efficient and dynamically-allocated array. It does not provide fast lookup in the general case, which you will want to use Dictionary for. It is excellent when used in loops.

 

Code Example :

using System;

using System.Collections.Generic;

 

class Program

{

    static void Main()

    {

// Use the List type.

List<string> list = new List<string>();

list.Add("rabbi");

list.Add("shahin");

list.Add("junnun");

 

foreach (string element in list)

{

   Console.WriteLine(element);

}

    }

}

 

Output

 

rabbi

shahin

junnun

 

Posted in: C Sharp

Tags:

C# Array

February 17, 2012 at 8:32 PMMehedi Hasan

In computer memory every byte is an array element. Abstractions translate these bytes into objects and give them meaning. Arrays in the .NET Framework are a foundational type. They are the basis of more usable collections such as List and Dictionary. They use a special syntax form.


Example

 

As an introduction to the C# array type, let's look at a simple example program that allocates and initializes an integer array of three elements. Please notice how the elements can be assigned to or read from using the same syntax (values[int]). The array is zero-based.

 


Code Snipet


using System; 
class Program 
static void Main() 
// Use an array. 
int[] values = new int[3]; 
values[0] = 5; 
values[1] = values[0] * 2;
values[2] = values[1] * 2;
foreach (int value in values)
{
Console.WriteLine(value);
}
} 

Output 
5 
1
0
20

Posted in: C Sharp

Tags:

Fade out the bottom of the page using CSS

January 17, 2012 at 3:40 AMMeherunnessa Mitu

CSS can be used to fade out the bottom of the page just creating a fixed-position div with a transparent image and using z-index property with high value. The z-index property specifies the stack order of an element. An element with greater stack order is always in front of an element with a lower stack order.

Here is the CSS code for fade out bottom -
body
{
    font-family: "Lucida Grande", Georgia, sans-serif;
    font-size: 15px;
}

p
{
    font-size: 14px;
    line-height: 1.5em;
}

#page_wrap
{
    width: 600px;
    z-index: 1;
    margin: 2px auto;
}

#bottom_fade
{
    width: 600px;
    height: 180px;
     z-index: 120;
     position: fixed;
    bottom: 0px;
    background: url('images/bottom-fade.png') bottom center no-repeat;   
}

Put the reference of your style sheet, then create two divs as shown below -
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Fade out bottom of the page using CSS</title>
    <link href="App_Themes/Theme1/FadeOutBottom.css" rel="stylesheet" type="text/css" />
</head>
<body>
    <form id="form1" runat="server">
    <div id="textdiv">
    <h1>Fade out bottom</h1><br />
    <p>
    Completely revolutionize high-quality niches after mission-critical expertise. Professionally deploy standardized total linkage before interoperable architectures. Quickly formulate future-proof meta-services through cross functional portals. Holisticly procrastinate timely results vis-a-vis principle-centered human capital. Distinctively incubate emerging systems and collaborative best practices. Compellingly exploit next-generation technology via web-enabled results.<br />

Professionally disintermediate 24/365 web services via intermandated technologies. Holisticly disseminate flexible web services through professional results. Enthusiastically empower integrated channels and standards compliant channels. Proactively brand end-to-end process improvements rather than resource sucking results. <br />

Credibly aggregate dynamic synergy and one-to-one testing procedures. Credibly synergize out-of-the-box growth strategies via timely mindshare. Synergistically embrace extensive schemas and multidisciplinary processes. Monotonectally synergize 2.0 sources before resource-leveling sources. Professionally grow value-added results before client-based internal or "organic" sources. <br />

Quickly fabricate out-of-the-box relationships via top-line e-services. Uniquely restore market positioning synergy rather than long-term high-impact manufactured products. Monotonectally plagiarize high-payoff interfaces rather than business internal or "organic" sources. Credibly synergize plug-and-play interfaces rather than intuitive results. Compellingly expedite fully tested outsourcing vis-a-vis impactful synergy. <br />


Distinctively re-engineer impactful architectures and resource sucking niches. Authoritatively envisioneer leveraged total linkage whereas vertical value. Phosfluorescently iterate dynamic opportunities through multimedia based systems. Uniquely e-enable frictionless paradigms after B2C initiatives. Credibly deliver go forward methods of empowerment via professional total linkage. Dramatically deliver client-based portals whereas collaborative innovation. <br />
    </p>
    <div id="bottom_fade">
    </div>
    </div>
    </form>
</body>
</html>

That's it.

Source: http://css-tricks.com/examples/FadeOutBottom

Posted in: CSS

Tags: ,