Diwakar's Blog

http://diwakarko.blogspot.com (दिवाकरको ब्लग)

Introduction to LINQ

No comments
Language-Integrated Query (LINQ) is an innovation introduced in Visual Studio 2008 and .NET Framework version 3.5 that bridges the gap between the world of objects and the world of data.
Traditionally, queries against data are expressed as simple strings without type checking at compile time or IntelliSense support. Furthermore, you have to learn a different query language for each type of data source: SQL databases, XML documents, various Web services, and so on. LINQ makes a query a first-class language construct in C# and Visual Basic. You write queries against strongly typed collections of objects by using language keywords and familiar operators. The following illustration shows a partially-completed LINQ query against a SQL Server database in C# with full type checking and IntelliSense support.
LINQ query with Intellisense In Visual Studio you can write LINQ queries in Visual Basic or C# with SQL Server databases, XML documents, ADO.NET Datasets, and any collection of objects that supports IEnumerable or the generic IEnumerable<T> interface. LINQ support for the ADO.NET Entity Framework is also planned, and LINQ providers are being written by third parties for many Web services and other database implementations.
You can use LINQ queries in new projects, or alongside non-LINQ queries in existing projects. The only requirement is that the project target .NET Framework 3.5 or later.

No comments :

Post a Comment

Introduction to Generic Classes and Inheritance

No comments
Consider the following geometric figures:
Square Rectangle Trapezoid Parallelogram
Square Rectangle Trapezoid Parallelogram
Notice that these are geometric figures with each having four sides. From what we know so far, we can create a base class to prepare it for inheritance. If the class is very general, we can make it a generic one. We can set a data type as an unknown type, anticipating that the dimensions of the figure can be considered as integer or double-precision types. Here is an example:
using System;

public class Quadrilateral
{
        protected T _base;
        protected T _height;
        protected string _name;

        public virtual T Base
        {
            get { return _base; }
            set { _base = value; }
        }

        public virtual T Height
        {
            get { return _height; }
            set { _height = value; }
        }

        public virtual string Name
        {
            get { return _name; }
            set { _name = value; }
        }

        public Quadrilateral(string name = "Quadrilateral")
        {
            _name = name;
        }

        public Quadrilateral(T bs, T height)
        {
            _name = "Quadrilateral";
            _base = bs;
            _height = height;
        }

        public Quadrilateral(string name, T bs, T height)
        {
            _name = name;
            _base = bs;
            _height = height;
        }


        public virtual string Describe()
        {
            return "A quadrilateral is a geometric figure with four sides";
        }

        public virtual void ShowCharacteristics()
        {
            Console.WriteLine("Geometric Figure: {0}", Name);
            Console.WriteLine("Description:      {0}", Describe());
            Console.WriteLine("Base:             {0}", Base);
            Console.WriteLine("Height:           {0}", Height);
        }
}

public class Exercise
{
    static int Main()
    {
        // Trapezoid with equal sides
        var Kite = new Quadrilateral("Beach Kite", 18.64, 18.64);
        Kite.ShowCharacteristics();
        Console.WriteLine();

        // Rectangle, in meters
        var BasketballStadium = new Quadrilateral();
        BasketballStadium.Name = "Basketball Stadium";
        BasketballStadium.Base = 15;
        BasketballStadium.Height = 28;
        BasketballStadium.ShowCharacteristics();
        Console.WriteLine();

        return 0;
    }
}
This would produce:
Geometric Figure: Beach Kite
Description:      A quadrilateral is a geometric figure with four sides
Base:             18.64
Height:           18.64

Geometric Figure: Basketball Stadium
Description:      A quadrilateral is a geometric figure with four sides
Base:             15
Height:           28

Press any key to continue . . .
If you have a generic class that can serve as a foundation for another class, you can derive a class from the generic one. To do this, use the formula we apply when deriving a class but follow the name of each class with <>. Inside of the <> operator, enter the same identifier to indicate that the class is a generic type that is based on another generic class. Here is an example:
public class Square : Quadrilateral
{
}
In the body of the new class, you can use the parameter type as you see fit. For example, you can declare some member variables of that type. You can create methods that return the parameter type or you can pass arguments of the parameter type. When implementing the methods of the new class, use the member variables of the parameter and the argument(s) based on the parameter type as you see fit. You can then declare a variable of the class and use it as we done so far for other generic classes. Here is an example:
using System;

public class Quadrilateral
{
        protected T _base;
        protected T _height;
        protected string _name;

        public virtual T Base
        {
            get { return _base; }
            set { _base = value; }
        }

        public virtual T Height
        {
            get { return _height; }
            set { _height = value; }
        }

        public virtual string Name
        {
            get { return _name; }
            set { _name = value; }
        }

        public Quadrilateral(string name = "Quadrilateral")
        {
            _name = name;
        }

        public Quadrilateral(T bs, T height)
        {
            _name = "Quadrilateral";
            _base = bs;
            _height = height;
        }

        public Quadrilateral(string name, T bs, T height)
        {
            _name = name;
            _base = bs;
            _height = height;
        }


        public virtual string Describe()
        {
            return "A quadrilateral is a geometric figure with four sides";
        }

        public virtual void ShowCharacteristics()
        {
            Console.WriteLine("Geometric Figure: {0}", Name);
            Console.WriteLine("Description:      {0}", Describe());
            Console.WriteLine("Base:             {0}", Base);
            Console.WriteLine("Height:           {0}", Height);
        }
}

public class Square : Quadrilateral
{
        public Square()
        {
            _name = "Square";
        }
        public Square(string name)
        {
            _name = "Square";
        }
        public Square(T side)
        {
            _name = "Square";
            _base = side;
            _height = side;
        }
        public Square(string name, T side)
        {
            _name = name;
            _base = side;
            _height = side;
        }
        public override string Describe()
        {
            return "A square is a quadrilateral with four equal sides";
        }
        public override void ShowCharacteristics()
        {
            Console.WriteLine("Geometric Figure: {0}", Name);
            Console.WriteLine("Description:      {0}", Describe());
            Console.WriteLine("                  {0}", Describe());
            Console.WriteLine("Side:             {0}", Base);
        }
}

public class Exercise
{
    static int Main()
    {
        // Rectangle, in meters
        var plate = new Square();

        plate.Name   = "Plate";
 plate.Base   = 15;
        plate.Height = 28;
 plate.ShowCharacteristics();

        Console.WriteLine();
        return 0;
    }
}
This would produce:
Geometric Figure: Plate
Description:      A quadrilateral is a geometric figure with four sides
                  A square is a quadrilateral with four equal sides
Side:             15

Press any key to continue . . .

No comments :

Post a Comment

5 Different Ways to Declare Functions in jQuery

No comments

From jQuery4u

Introduction

Choosing which way to declare a JavaScript function can be confusing for beginners as there are several different ways to declare functions using JavaScript/jQuery. I’ll try to explain the benefits of each one and how and why you might use them when writing your awesome jQuery code.

1. The basic JavaScript function

This is the simplest way to declare a function in JavaScript. Say for example, we want to write a simple function called multiply(x,y) which simply takes in two parameters x and y, does a simple x times y and returns the value. Here are a few ways you might go about doing exactly this.

function multiply(x,y) {
     return (x * y);
}
console.log(multiply(2,2));
//output: 4
If you wanted a quick function to test something then maybe that’s the only occasion you would use this. It’s not good coding and doesn’t promote code reuse.

2. JavaScript functions for get/set

If you need a private utility for getting/setting/deleting model values then you can declare a function as a variable like this. This could be useful for assigning a variable upon declaration calculated by a function.

var multiply = function(x,y) {
     return (x * y);
}
console.log(multiply(2,2));
//output: 4

//The same function but with a self execution to set the value of the variable:
var multiply = function(x,y) {
     return (x * y);
}(2,2);
console.log(multiply);
//output: 4

3. Create your own jQuery function

This is an awesome way to declare functions that can be used just like your regular jQuery functions, on your DOM elements! Rememeber jQuery.fn is just an alias for jQuery.prototype (which just saves us time when coding such jQuery.fn.init.prototype = jQuery.fn = $.fn as such).

jQuery.fn.extend({
    zigzag: function () {
        var text = $(this).text();
        var zigzagText = '';
        var toggle = true; //lower/uppper toggle
            $.each(text, function(i, nome) {
                zigzagText += (toggle) ? nome.toUpperCase() : nome.toLowerCase();
                toggle = (toggle) ? false : true;
            });
    return zigzagText;
    }
});

console.log($('#tagline').zigzag());
//output: #1 jQuErY BlOg fOr yOuR DaIlY NeWs, PlUgInS, tUtS/TiPs & cOdE SnIpPeTs.

//chained example
console.log($('#tagline').zigzag().toLowerCase());
//output: #1 jquery blog for your daily news, plugins, tuts/tips & code snippets.
Don’t forget to return the element so that you can chain jQuery functions together.

4. Extend Existing jQuery Functions

(or which either extend existing jQuery functions with extra functionality or creating your own functions that can be called using the jQuery namespace (usually, we use the $ sign to represent the jQuery namespace). In this example the $.fn.each function has been modified with custom behaviour.

(function($){

// maintain a to the existing function
var oldEachFn = $.fn.each;

$.fn.each = function() {

    // original behavior - use function.apply to preserve context
    var ret = oldEachFn.apply(this, arguments);
   
    // add custom behaviour
    try {
        // change background colour
        $(this).css({'background-color':'orange'});
       
        // add a message
        var msg = 'Danger high voltage!';
        $(this).prepend(msg);
    }
    catch(e)
    {
        console.log(e);
    }
   
    // preserve return value (probably the jQuery object...)
    return ret;
}

// run the $.fn.each function as normal
$('p').each(function(i,v)
{
    console.log(i,v);
});
//output: all paragrahs on page now appear with orange background and high voltage!

})(jQuery);

5. Functions in custom namespaces

If your writing functions in a custom namespace you must declare them in this way. Extra functions can be added to the namespace you just need to add a comma after each one (except the last one!). If your unsure about namespacing see jQuery Function Namespacing in Plain English

JQUERY4U = {
    multiply: function(x,y) {
        return (x * y);
    }
}
//function call
JQUERY4U.multiply(2,2);

Conclusion

Knowing when and how to declare different types of JavaScript/jQuery functions is definitely something any good js developer should know inside out.

No comments :

Post a Comment

An Introduction to Stored Procedures in MySQL 5

No comments

Introduction

“ A stored routine is a set of SQL statements that can be stored in the server.”
A stored procedure is a method to encapsulate repetitive tasks. They allow for variable declarations, flow control and other useful programming techniques.
The “academic” position on this is quite clear and supports the extensive use of stored procedures. On the other hand, when you consider the opinions of those who work with them day in, day out, you’ll notice that reactions vary from complete, unwavering support to utter hate. Keep these in mind.

Pros

  • Share logic with other applications. Stored procedures encapsulate functionality; this ensures that data access and manipulation are coherent between different applications.
  • Isolate users from data tables. This gives you the ability to grant access to the stored procedures that manipulate the data but not directly to the tables.
  • Provide a security mechanism. Considering the prior item, if you can only access the data using the stored procedures defined, no one else can execute a DELETE SQL statement and erase your data.
  • To improve performance because it reduces network traffic. With a stored procedure, multiple calls can be melded into one.

Cons

  • Increased load on the database server — most of the work is done on the server side, and less on the client side.
  • There’s a decent learning curve. You’ll need to learn the syntax of MySQL statements in order to write stored procedures.
  • You are repeating the logic of your application in two different places: your server code and the stored procedures code, making things a bit more difficult to maintain.
  • Migrating to a different database management system (DB2, SQL Server, etc) may potentially be more difficult.
The tool that I am working with in this tutorial, MySQL Query Browser, is pretty standard for database interactions. The MySQL command line tool is another excellent choice. I make note of this because the popular phpMyAdmin doesn’t support stored procedure execution.
Additionally, I’ll be using very rudimentary table structures, strictly to ease the explanation. I’m showing off stored procedures, and they’re complex enough without worrying about big tables.

Step 1 – Picking a Delimiter

The delimiter is the character or string of characters that you’ll use to tell the mySQL client that you’ve finished typing in an SQL statement. For ages, the delimiter has always been a semicolon. That, however, causes problems, because, in a stored procedure, one can have many statements, and each must end with a semicolon. In this tutorial I will use “//”

Step 2 – How to Work with a Stored Procedure

Creating a Stored Procedure

  1. DELIMITER //  
  2.   
  3. CREATE PROCEDURE `p2` ()  
  4. LANGUAGE SQL  
  5. DETERMINISTIC  
  6. SQL SECURITY DEFINER  
  7. COMMENT 'A procedure'  
  8. BEGIN  
  9.     SELECT 'Hello World !';  
  10. END//  
The first part of the statement creates the procedure. The next clauses defines the optional characteristics of the procedure. Then you have the name and finally the body or routine code.
Stored procedure names are case insensitive, and you cannot create procedures with the same name. Inside a procedure body, you can’t put database-manipulation statements.
The four characteristics of a procedure are:
  • Language : For portability purposes; the default value is SQL.
  • Deterministic : If the procedure always returns the same results, given the same input. This is for replication and logging purposes. The default value is NOT DETERMINISTIC.
  • SQL Security : At call time, check privileges of the user. INVOKER is the user who calls the procedure. DEFINER is the creator of the procedure. The default value is DEFINER.
  • Comment : For documentation purposes; the default value is ""

Calling a Stored Procedure

To call a procedure, you only need to enter the word CALL, followed by the name of the procedure, and then the parentheses, including all the parameters between them (variables or values). Parentheses are compulsory.
  1. CALL stored_procedure_name (param1, param2, ....)  
  2.   
  3. CALL procedure1(10 , 'string parameter' , @parameter_var);  

Modify a Stored Procedure

MySQL provides an ALTER PROCEDURE statement to modify a routine, but only allows for the ability to change certain characteristics. If you need to alter the body or the parameters, you must drop and recreate the procedure.

Delete a Stored Procedure

  1. DROP PROCEDURE IF EXISTS p2;  
This is a simple command. The IF EXISTS clause prevents an error in case the procedure does not exist.

Step 3 – Parameters

Let’s examine how you can define parameters within a stored procedure.
  • CREATE PROCEDURE proc1 () : Parameter list is empty
  • CREATE PROCEDURE proc1 (IN varname DATA-TYPE) : One input parameter. The word IN is optional because parameters are IN (input) by default.
  • CREATE PROCEDURE proc1 (OUT varname DATA-TYPE) : One output parameter.
  • CREATE PROCEDURE proc1 (INOUT varname DATA-TYPE) : One parameter which is both input and output.
Of course, you can define multiple parameters defined with different types.

IN example

  1.    DELIMITER //  
  2.   
  3. CREATE PROCEDURE `proc_IN` (IN var1 INT)  
  4. BEGIN  
  5.     SELECT var1 + 2 AS result;  
  6. END//  

OUT example

  1. DELIMITER //  
  2.   
  3. CREATE PROCEDURE `proc_OUT` (OUT var1 VARCHAR(100))  
  4. BEGIN  
  5.     SET var1 = 'This is a test';  
  6. END //  

INOUT example

  1. DELIMITER //  
  2.   
  3. CREATE PROCEDURE `proc_INOUT` (OUT var1 INT)  
  4. BEGIN  
  5.     SET var1 = var1 * 2;  
  6. END //  

Step 4 – Variables

The following step will teach you how to define variables, and store values inside a procedure. You must declare them explicitly at the start of the BEGIN/END block, along with their data types. Once you’ve declared a variable, you can use it anywhere that you could use a session variable, or literal, or column name.
Declare a variable using the following syntax:
  1. DECLARE varname DATA-TYPE DEFAULT defaultvalue;   
Let’s declare a few variables:
  1. DECLARE a, b INT DEFAULT 5;  
  2.   
  3. DECLARE str VARCHAR(50);  
  4.   
  5. DECLARE today TIMESTAMP DEFAULT CURRENT_DATE;  
  6.   
  7. DECLARE v1, v2, v3 TINYINT;  

Working with variables

Once the variables have been declared, you can assign them values using the SET or SELECT command:
  1. DELIMITER //  
  2.   
  3. CREATE PROCEDURE `var_proc` (IN paramstr VARCHAR(20))  
  4. BEGIN  
  5.     DECLARE a, b INT DEFAULT 5;  
  6.     DECLARE str VARCHAR(50);  
  7.     DECLARE today TIMESTAMP DEFAULT CURRENT_DATE;  
  8.     DECLARE v1, v2, v3 TINYINT;      
  9.   
  10.     INSERT INTO table1 VALUES (a);  
  11.     SET str = 'I am a string';  
  12.     SELECT CONCAT(str,paramstr), today FROM table2 WHERE b >=5;   
  13. END //  

Step 5 – Flow Control Structures

MySQL supports the IF, CASE, ITERATE, LEAVE LOOP, WHILE and REPEAT constructs for flow control within stored programs. We’re going to review how to use IF, CASE and WHILE specifically, since they happen to be the most commonly used statements in routines.

IF statement

With the IF statement, we can handle tasks which involves conditions:
  1. DELIMITER //  
  2.   
  3. CREATE PROCEDURE `proc_IF` (IN param1 INT)  
  4. BEGIN  
  5.     DECLARE variable1 INT;  
  6.     SET variable1 = param1 + 1;  
  7.       
  8.     IF variable1 = 0 THEN  
  9.         SELECT variable1;  
  10.     END IF;  
  11.   
  12.     IF param1 = 0 THEN  
  13.         SELECT 'Parameter value = 0';  
  14.     ELSE  
  15.         SELECT 'Parameter value <> 0';  
  16.     END IF;  
  17. END //  

CASE statement

The CASE statement is another way to check conditions and take the appropriate path. It’s an excellent way to replace multiple IF statements. The statement can be written in two different ways, providing great flexibility to handle multiple conditions.
  1. DELIMITER //  
  2.   
  3. CREATE PROCEDURE `proc_CASE` (IN param1 INT)  
  4. BEGIN  
  5.     DECLARE variable1 INT;  
  6.     SET variable1 = param1 + 1;  
  7.       
  8.     CASE variable1  
  9.         WHEN 0 THEN  
  10.             INSERT INTO table1 VALUES (param1);  
  11.         WHEN 1 THEN  
  12.             INSERT INTO table1 VALUES (variable1);   
  13.         ELSE  
  14.             INSERT INTO table1 VALUES (99);  
  15.     END CASE;  
  16.   
  17. END //  
or:
  1. DELIMITER //  
  2.   
  3. CREATE PROCEDURE `proc_CASE` (IN param1 INT)  
  4. BEGIN  
  5.     DECLARE variable1 INT;  
  6.     SET variable1 = param1 + 1;  
  7.       
  8.     CASE   
  9.         WHEN variable1 = 0 THEN  
  10.             INSERT INTO table1 VALUES (param1);  
  11.         WHEN variable1 = 1 THEN  
  12.             INSERT INTO table1 VALUES (variable1);   
  13.         ELSE  
  14.             INSERT INTO table1 VALUES (99);  
  15.     END CASE;  
  16.   
  17. END //  

WHILE statement

There are technically three standard loops: WHILE loops, LOOP loops, and REPEAT loops. You also have the option of creating a loop using the “Darth Vader” of programming techniques: the GOTO statement. Check out this example of a loop in action:
  1. DELIMITER //  
  2.   
  3. CREATE PROCEDURE `proc_WHILE` (IN param1 INT)  
  4. BEGIN  
  5.     DECLARE variable1, variable2 INT;  
  6.     SET variable1 = 0;  
  7.       
  8.     WHILE variable1 < param1 DO  
  9.         INSERT INTO table1 VALUES (param1);  
  10.         SELECT COUNT(*) INTO variable2 FROM table1;  
  11.         SET variable1 = variable1 + 1;  
  12.     END WHILE;  
  13. END //  

Step 6 - Cursors

Cursor is used to iterate through a set of rows returned by a query and process each row.
MySQL supports cursor in stored procedures. Here's a summary of the essential syntax to create and use a cursor.
  1. DECLARE cursor-name CURSOR FOR SELECT ...;       /*Declare and populate the cursor with a SELECT statement */  
  2. DECLARE  CONTINUE HANDLER FOR NOT FOUND          /*Specify what to do when no more records found*/  
  3. OPEN cursor-name;                                /*Open cursor for use*/  
  4. FETCH cursor-name INTO variable [, variable];    /*Assign variables with the current column values*/  
  5. CLOSE cursor-name;                               /*Close cursor after use*/  
In this example, we'll perform some simple operations using a cursor:
  1. DELIMITER //  
  2.   
  3. CREATE PROCEDURE `proc_CURSOR` (OUT param1 INT)  
  4. BEGIN  
  5.     DECLARE a, b, c INT;  
  6.     DECLARE cur1 CURSOR FOR SELECT col1 FROM table1;  
  7.     DECLARE CONTINUE HANDLER FOR NOT FOUND SET b = 1;  
  8.     OPEN cur1;  
  9.   
  10.     SET b = 0;  
  11.     SET c = 0;  
  12.      
  13.     WHILE b = 0 DO  
  14.         FETCH cur1 INTO a;  
  15.         IF b = 0 THEN  
  16.             SET c = c + a;  
  17.     END IF;    
  18.     END WHILE;  
  19.   
  20.     CLOSE cur1;  
  21.     SET param1 = c;  
  22.   
  23. END //  
Cursor has three important properties that you need to be familiar with in order to avoid unexpected results:
  • Asensitive : Once open, the cursor will not reflect changes in its source tables. In fact, MySQL does not guarantee the cursor will be updated, so you can't rely on it.
  • Read Only : Cursors are not updatable.
  • Not Scrollable : Cursors can be traversed only in one direction, forward, and you can't skip records from fetching.

Conclusion

In this lesson, we covered the fundamentals of stored procedures and some specific properties pertaining to them. Of course, you should continue your studies in areas like security, SQL statements, and performance before you can master MySQL routines.
You have to evaluate the advantages that stored procedures can potentially bring to your applications, and then make a reasonable implementation that fits your requirements. I generally use procedures; their benefits in terms of security, code maintenance and software design make them worthy of use, in my opinion. Additionally, remember that procedures in MySQL are still a work in progress. You should fully expect improvements, in terms of functionality and performance in the future. Please don't hesitate to comment and share your ideas and opinions.

No comments :

Post a Comment

SQL SERVER – Create Script to Copy Database Schema and All The Objects – Data, Schema, Stored Procedure, Functions, Triggers, Tables, Views, Constraints and All Other Database Objects

No comments
After the script is generated, the next challenge often users face is how to execute this large script as SQL Server Management Studio does not open the file. One can use SQLCMD for the same. See that in the last image of this post.
Pay attention to the option Types of data to script – select option ‘Schema and data’
As the file with data will be very large, use SQLCMD to execute the large script which will create database with schema & data.

No comments :

Post a Comment

Creating a SQL Server Database Project in Visual Studio 2012

No comments

Conditional Creation of Tables and Columns (The Old Way)

If your application has numerous deployment versions and you want your script to adapt and be able to either install in a fresh database or into a prior version of the schema, then you have lots of work to do.  First you create the latest version of the table, if it does not exist.  If it does already exist, then you check for the missing columns added since your initial deployment and add them as needed.  You may also need to drop columns that have been removed over time.  Here is an example of an old script where I have done this.
Please excuse the name prefixes. I used to prefix table and stored procedure names with a prefix indicating a kind of namespace. I’ve since changed over to using different schemas. This script also checks for an existing table with sysobjects since this was written for SQL Server 2000 and then updated to use SQL server 2005. It has since been replaced, however sysobjects still works for backwards compatibility. I discourage you from using this in any current or future projects.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
if not exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[XQSXG_MMS_MailMessage]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
 BEGIN
CREATE TABLE [dbo].[XQSXG_MMS_MailMessage](
    [MailMessageID] [int] IDENTITY(1,1) NOT NULL,
    [MailMessageTypeID] [int] NULL,
    [ToAddress] [nvarchar](256) NOT NULL,
    [ToUser] uniqueidentifier NULL,
    [Priority] [int] NOT NULL CONSTRAINT [DF_XQSXG_MMS_MailMessage_Priority]  DEFAULT ((0)),
    [Subject] [nvarchar](512) NOT NULL,
    [Format] [int] NOT NULL CONSTRAINT [DF_XQSXG_MMS_MailMessage_Format]  DEFAULT ((0)),
    [Body] nvarchar(max) NULL, /*SQL Server 2005+, prior used NText*/
    [CreatedDate] [datetime] NOT NULL CONSTRAINT [DF_XQSXG_MMS_MailMessage_CreatedDate]  DEFAULT (getutcdate()),
    [Attempts] [int] NOT NULL CONSTRAINT [DF_XQSXG_MMS_MailMessage_Attempts]  DEFAULT ((0)),
    [LastAttemptDate] [datetime] NULL,
    [CompletedDate] [datetime] NULL
)
 END
GO
 
if not exists(select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'XQSXG_MMS_MailMessage' and COLUMN_NAME = 'MailMessageTypeID')
BEGIN
    ALTER TABLE dbo.XQSXG_MMS_MailMessage ADD
    MailMessageTypeID int NULL
END
GO
if not exists(select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'XQSXG_MMS_MailMessage' and COLUMN_NAME = 'ToUser')
BEGIN
    ALTER TABLE dbo.XQSXG_MMS_MailMessage ADD
    ToUser uniqueidentifier NULL
END
GO
if exists(select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'XQSXG_MMS_MailMessage' and COLUMN_NAME = 'FromAddress')
BEGIN
    ALTER TABLE dbo.XQSXG_MMS_MailMessage Drop Column FromAddress
END
GO
if exists(select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'XQSXG_MMS_MailMessage' and COLUMN_NAME = 'CCAddress')
BEGIN
    ALTER TABLE dbo.XQSXG_MMS_MailMessage Drop Column CCAddress
END
GO
if exists(select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'XQSXG_MMS_MailMessage' and COLUMN_NAME = 'BCCAddress')
BEGIN
    ALTER TABLE dbo.XQSXG_MMS_MailMessage Drop Column BCCAddress
END
GO
 
if not exists
(   select * from dbo.sysobjects where id = object_id(N'[dbo].[PK_XQSXG_MMS_MailMessage]') and parent_obj =
    (select id from dbo.sysobjects where id = object_id(N'[dbo].[XQSXG_MMS_MailMessage]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
)
BEGIN
    ALTER TABLE [dbo].[XQSXG_MMS_MailMessage] ADD CONSTRAINT [PK_XQSXG_MMS_MailMessage] PRIMARY KEY  CLUSTERED
    (
        [MailMessageID]
    )
END
GO

Creating a Database Project in Visual Studio 2012 (The New Way)

You can reverse engineer a database project from an existing database, or create a new project from scratch.  This article will focus on how to create one from scratch.  Open Visual Studio and either create a new solution or open an existing one to which this new database should be a part of.

Adding the Project to a Solution

Select the Other Languages, SQL Server template group on the left.  Then choose the SQL Server Database Project type.  Enter a project name and press OK.  I usually pick a project name matching the class library that will contain the business layer or data layer that will interact with this database, and then append Database to the end of that name.  It may make more sense to also put SQL in the name; just in case you use another type of database in the future.
CreateDBProj-01-AddProjectDialog

Update the Project Properties

You should check out the project properties and see what options are available.  On the main Project Settings tab page, there is a ‘Database Settings’ button that lets you specify any metadata to be applied to the database as a whole.  The defaults have worked for me, but if you need a specific database collation, file group, or need certain flags like ANSI_PADDING then check that out.
I tend to override the default output type, by checking the ‘Create script (.sql file)” option as shown here.  I do not change the default schema from ‘dbo’; even knowing that below I want most of my tables, functions, and procedures in a specific schema.
CreateDBProj-02-ChangeOutputType

Import a Database (Optional)

If you already have a database to start with; you can import from the current schema.  Then you can follow the other sections below for making changes and publishing those changes.  To import a schema, just right click on the project node in solution explorer and select menu “Import” -> “Database”.  Then configure the database connection and pick the options for things you want to import.
ImportDBProj-01-ImportDialog
I prefer the Folder structure of “Schema\Object Type”.  This is what I will assume for the following sections; It is also the default selection for the Import dialog.   I don’t normally change any of the import setting defaults.  If you need permissions of any specific database settings from your existing database then select those import options.  You can modify the database settings in the project properties as noted in the previous section.

Creating a Schema

Before I create any tables, I usually define a schema in which I will place all my database objects for this project.  This allows you to have simpler names for your tables, since the schema scopes them similar to a namespace in .Net code.
It may not really matter where you put the schema file, however I follow the convention used when reverse engineering a database.  Create a folder in the database project of the same name that you will name your schema.  Then add the schema file to that folder using that same name.
CreateDBProj-03-AddSchema
This seems so much better to me than the old way above where I showed a prefix on a table name to facilitate grouping of related tables.  Having different schemas for loosely coupled or unrelated sets of tables also helps me think of ways tables could be segmented into different database shards.  You can either go the route of one database project per schema, or one database project for all your schemas.  I usually make that decision based on how I want to deploy the database.  One database project equals a deployment to one database instance.

Add a Table

When reverse engineering a database into a database project it creates folders under the schema folder for Tables, Functions, and Stored Procedures.  I follow the same convention when creating these items manually.  I just create a table by right clicking on the Tables folder under the schema and selecting the ‘Add Table’ menu item.
CreateDBProj-04-AddTable
The New Item dialog with table selected.
CreateDBProj-04B-SolutionExplorer
Solution Explorer after adding a schema file and tables

Table Designer Overview

The table designer gives you options as to how you want to design your table.  It has a design pane which has a columns grid and keys overview with right click support for adding new keys.  It also has a raw text pane with the sql required to create the table as defined in the design pane.  As you type in the raw text pane the changes appear in the design pane; and as you change details on the design pane it updates the raw text pane.  On my 5 year old laptop, I have not experienced any performance issues either to open the file or in having updates sync between the panes.
CreateDBProj-05-TableDesign
As you use this designer all the keys and constraints are added in the table definition sql file.

Deploying the Database – Publish

Publishing the database changes is very simple.  Just right click on the database project in solution explorer, and select “Publish”.  A dialog appears for connection details.
CreateDBProj-07-DeployDBCon
Assuming you followed the steps above during project setup, this will just generate a script file.  I prefer script files so that I have them ready for promotion to the next environment.  If your project properties default to do an automatic publish instead of generating a script, you can override this by just pressing the ‘Generate Script’ button.
CreateDBProj-08-DeployPublish

Deploying the Database – Schema Compare

You can also create a deployment script with the schema compare command.  This is also available as a right click menu item on the database project node in solution explorer.  This gives you more flexibility.  You pick the database target to compare the database project to and it tells you what is changed.  Then you can choose which items are included in the generated script.  If you leave all changes selected, then this generates the same script as if you followed the ‘Publish’ option in the previous section.
CreateDBProj-09-SchemaCompare
This comparison shows everything as a difference since the schema has not been deployed yet.
To begin a comparison to a database, pick in the ‘Select Target’ dropdown to select a database connection.  In the screenshot above that dropdown has my connection name “.\SQLExpress.CandorMail”.  Then press the Compare button (Or use shortcut Shift-Alt-C) to see the changes.  If you have changes, then press the “generate script button” (Or use shortcut Shift-Alt-G).
If you actually want to deploy these changes to the target database now, then press the ‘Update Target” button (next to generate script).  This has no shortcut, thankfully.  I personally wouldn’t want a possible accidental key press of the wrong combination to publish a database change to a production database.

Build Errors

One of the great advantages of a database project is the continuous ‘compilation’ of the database project objects.  If you have invalid definitions or reference other objects that do not exist, then you will see compilation errors.  This is a great development enhancement over parsing scripts and manually running them against a local database instance on a regular basis.
As you type you will see problem areas highlighted in the raw text pane as shown here.  If you hover over it, you’ll see the error message.
CreateDBProj-06-InlineBuildError
Also if you view the errors list the detail will be shown.  If you double click on the error it will navigate you to the table designer where the error is located.
CreateDBProj-07-BuildErrorView
This error shows that the column name referenced by the foreign key is incorrect. It has a missing ‘s’ in the name.

Database References

You may have multiple database projects in your solution that have some level of dependency.  Maybe one of the projects is a set of customizations to a base database product defined in another project.  Or maybe you just want each schema defined in a separate project.
Without a reference the project that depends on external database objects will not compile (generate a script) if it cannot find the referenced database object.  To fix this you can create a reference to the other database project.  Just right click on the ‘references’ node of the database project and select “Add Database Reference”.  Then you can pick another database project in the solution, or a system database, or a dacpac file exported from another database.

Requirements

This works on my machine.  I didn’t research if it works with less features installed than I have, but it probably does.  I have the following Microsoft development tools installed.
  1. Visual Studio 2012 Professional with update 1 (Full Install , lots of ‘features’.  Not all are listed below)
    • Now includes: SQL Server Data Tools 11.1.20627.00 (separate install for VS 2010)
    • Now includes: Microsoft SQL Server Data Tools (yes, this is different from the previous item)
  2. SQL Server 2012 Express with all features including SQL Server Management Studio (ENU\x64\SQLEXPRWT_x64_ENU.exe, 669.9 MB).  Obviously pick the 32 bit version instead if your OS is 32 bit.  http://www.microsoft.com/en-us/download/details.aspx?id=29062

No comments :

Post a Comment

How to: Create a Stored Procedure (SQL Server Management Studio)

No comments
This topic describes how to create a Transact-SQL stored procedure by using Object Explorer in SQL Server Management Studio and provides an example that creates a simple stored procedure in the AdventureWorks database.
To create a stored procedure


In Object Explorer, connect to an instance of Database Engine and then expand that instance.


Expand Databases, expand the database in which the stored procedure belongs, and then expand Programmability.


Right-click Stored Procedures, and then click New Stored Procedure.


On the Query menu, click Specify Values for Template Parameters.


In the Specify Values for Template Parameters dialog box, the Value column contains suggested values for the parameters. Accept the values or replace them with new values, and then click OK.


In the query editor, replace the SELECT statement with the statements for your procedure.


To test the syntax, on the Query menu, click Parse.


To create the stored procedure, on the Query menu, click Execute.


To save the script, on the File menu, click Save. Accept the file name or replace it with a new name, and then click Save.
To create a stored procedure example


In Object Explorer, connect to an instance of Database Engine and then expand that instance.


Expand Databases, expand the AdventureWorks database, and then expand Programmability.


Right-click Stored Procedures, and then click New Stored Procedure.


On the Query menu, click Specify Values for Template Parameters.


In the Specify Values for Template Parameters dialog box, enter the following values for the parameters shown.
Parameter
Value

Author
Your name

Create Date
Today's date

Description
Returns employee data.

Procedure_name
HumanResources.uspGetEmployees

@Param1
@LastName

@Datatype_For_Param1
nvarchar(50)

Default_Value_For_Param1
NULL

@Param2
@FirstName

@Datatype_For_Param2
nvarchar(50)

Default_Value_For_Param2
NULL



Click OK.


In the query editor, replace the SELECT statement with the following statement:
SELECT FirstName, LastName, JobTitle, Department
FROM HumanResources.vEmployeeDepartment
WHERE FirstName = @FirstName AND LastName = @LastName;


To test the syntax, on the Query menu, click Parse. If an error message is returned, compare the statements with the information above and correct as needed.


To create the stored procedure, on the Query menu, click Execute.


To save the script, on the File menu, click Save. Enter a new file name, and then click Save.


To run the stored procedure, on the toolbar, click New Query.


In the query window, enter the following statements:
USE AdventureWorks;
GO
EXECUTE HumanResources.uspGetEmployees @FirstName = N'Diane', @LastName = N'Margheim';
GO


On the Query menu, click Execute.

No comments :

Post a Comment