jose 的个人资料SQL Server 2005 blogs日志列表 工具 帮助

日志


9月23日

Loading XML to SQL SERVER 2005

Bulk importing XML as a binary byte stream

When bulk loading XML from a file that contains an encoding declaration that you want to apply, specify the SINGLE_BLOB in OPENROWSET. This option ensures that the XML parser in SQL Server imports the data according to the encoding scheme specified in the XML declaration. For example, the following INSERT statement inserts an XML instance in a single column table.
 
USE tempdb
CREATE TABLE T (IntCol int, XmlCol xml)
GO
INSERT INTO T(XmlCol)
SELECT * FROM OPENROWSET(
   BULK 'c:\SampleFolder\SampleData3.txt',
   SINGLE_BLOB) AS x
 
To run this bulk load, create a utf-8 encoded file (c:\SampleFolder\SampleData3.txt) with the following sample instance that specifies the UTF-8 encoding scheme and then execute the INSERT statement.
 
<?xml version="1.0" encoding="UTF-8"?>
<Root>
          <ProductDescription ProductModelID="5">
             <Summary>Some Text</Summary>
          </ProductDescription>
</Root>
 
By using SINGLE_BLOB in this way, you can avoid a mismatch between the encoding of the XML document (as specified by the XML encoding declaration) and the string codepage implied by the server.
9月19日

XML DATATYPE (series 1)

New to SQL Server 2005, is The XML data type, which  lets you store XML documents and fragments in a SQL Server database. An XML fragment is an XML instance that is missing a single top-level element. You can create columns and variables of the XML type and store XML instances in them. Note that the stored representation of XML data type instances cannot exceed 2 GB.

Where can you use the XML data type
a. Table
b. Variable
c. Parameters
d. Return of a function
 
To do: Store XML to a table

a. Create a Table with XML data type
CREATE TABLE ProductDocs (ID INT IDENTITY PRIMARY KEY,
ProductDoc XML NOT NULL)
GO
 
b. Store XML data  Into the table
INSERT INTO ProductDocs VALUES('
<Product>
<ProductID>1</ProductID>
<ProductName>Chai</ProductName>
<SupplierID>1</SupplierID>
<CategoryID>1</CategoryID>
<QuantityPerUnit>10 boxes x 20   bags</QuantityPerUnit>
<UnitPrice>18.0000</UnitPrice>
<UnitsInStock>39</UnitsInStock>
<UnitsOnOrder>0</UnitsOnOrder>
<ReorderLevel>10</ReorderLevel>
<Discontinued>0</Discontinued>
</Product>
')

c. Retrieve XMLdoc
Select product from productdocs

D. create an XML Schema
CREATE XML SCHEMA COLLECTION ProductSchema AS '
<xs:schema xmlns:xs="
http://www.w3.org/2001/XMLSchema"
targetNamespace="
http://www.microsoft.com/schemas/adventureworks/
products"
xmlns:prod="
http://www.microsoft.com/schemas/adventureworks/
products">
<xs:element name="Product">
<xs:complexType>
<xs:sequence>
<xs:element ref="prod:ProductID" />
<xs:element ref="prod:ProductName" />
<xs:element ref="prod:SupplierID" />
<xs:element ref="prod:CategoryID" />
<xs:element ref="prod:QuantityPerUnit" />
<xs:element ref="prod:UnitPrice" />
<xs:element ref="prod:UnitsInStock" />
<xs:element ref="prod:UnitsOnOrder" />
<xs:element ref="prod:ReorderLevel" />
<xs:element ref="prod:Discontinued" />
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="ProductID" type="xs:integer" />
<xs:element name="ProductName" type="xs:string" />
<xs:element name="SupplierID" type="xs:integer" />
<xs:element name="CategoryID" type="xs:integer" />
<xs:element name="QuantityPerUnit" type="xs:string" />
<xs:element name="UnitPrice" type="xs:double" />
<xs:element name="UnitsInStock" type="xs:integer" />
<xs:element name="UnitsOnOrder" type="xs:integer" />
<xs:element name="ReorderLevel" type="xs:integer" />
<xs:element name="Discontinued" type="xs:boolean" />
</xs:schema> '
 
E. retrieve Schemas
SELECT * FROM sys.xml_schema_collections
Schemas are stored in Sys.xml_schema_collections
8月25日

Database Snapshot

    
     A database snapshot is a read-only, static view of a database (called the source database). Each database snapshot is transactionally consistent with the source database at the moment of the snapshot's creation. When you create a database snapshot, the source database will typically have open transactions. Before the snapshot becomes available, the open transactions are rolled back to make the database snapshot transactionally consistent.
 
How to ?
 
Run the following Sql codes to create the snapshot
CREATE DATABASE AdventureWorks_dbss1800 ON
( NAME = AdventureWorks_Data, FILENAME =
'C:\central data\central data\snapshots\data_1800.ss' )
AS SNAPSHOT OF AdventureWorks;
 
Why do the snapshot?
 
1. can be used to maintain historical data
how does the data look like at  a particular point in time such as the end of every quarter or month which can be used for historical reporting.
2. It serves a read-only mirror of the data
You can offload your reporting task to the snapshot as an availability manuever and free up the main database from intensive read only query
3. safe guard data from administrative error
database can be reverted from snapshot in case of administrative error schema changes, bulk insert and the likes. aside from that you can't delete, drop or detach the
source database without first deleting its snapshots
4. Safe guard data from user error
You can easily recover unwanted user error from the snapshot such as deletion and dropeed tables. Snapshot provides faster recovery as compared from recovering from the backup
Limitations
1. It should exist on the same server as the source database
2. contains only commited transaction at the point of which it was taken. Uncommited chages are rollback
3. It is read only
4. You cannot drop files from a snapshot.
5. You cannot back up or restore snapshots.
6. You cannot attach or detach snapshots.
7. You cannot create snapshots on FAT32 file system or RAW partitions.
8. Full-text indexing is not supported on database snapshots, and full-text catalogs are not propagated from the source database.
9. A database snapshot inherits the security constraints of its source database at the time of snapshot creation. Because snapshots are read-only, inherited permissions cannot be changed and permission changes made to the source will not be reflected in existing snapshots.
10. A snapshot always reflects the state of filegroups at the time of snapshot creation: online filegroups remain online, and offline filegroups remain offline. For more information, see "Database Snapshots with Offline Filegroups" later in this topic.
11. If a source database becomes RECOVERY_PENDING, its database snapshots may become inaccessible. After the issue on the source database is resolved, however, its snapshots should become available again.
12. Reverting is unsupported for read-only filegroups as well as compressed filegroups. Attempts to revert to either of these types of filegroups fail
 
7月26日

The SQL SERVER 2005 Try Catch Block

 
 
SYNTAX
BEGIN TRY
    <SQL Statements>
END TRY
BEGIN CATCH TRAN_ABORT
    <SQL Statements>
END CATCH
OVERVIEW
Prior to sql server 2005 error handling is done by querying @@error after every line of execution. In sql server 2005, try catch block provides a new structure way of handling error similar to those of many development language such as VB, Java and C#

One of  the advantage of try catch block over  its old friend @@error is that it enables transaction abort errors to be captured with no loss of the transaction context
EXAMPLES

a. constraint violation


USE AdventureWorks

    BEGIN TRY
      UPDATE HumanResources.Employee
      SET Gender = 'X'
      WHERE EmployeeID = 1;
    END TRY
    BEGIN CATCH
      SELECT ERROR_NUMBER(  ) ErrorNumber,
      ERROR_STATE(  ) ErrorState,
      ERROR_SEVERITY(  ) ErrorSeverity,
      ERROR_MESSAGE(  ) ErrorMessage;
    END CATCH

 

b. selecting from non existing table

USE AdventureWorks;
GO
BEGIN TRY
    -- Table does not exist; object name resolution
    -- error not caught.
    SELECT * FROM NonexistentTable;
END TRY
BEGIN CATCH
    SELECT
        ERROR_NUMBER() as ErrorNumber,
        ERROR_MESSAGE() as ErrorMessage;
END CATCH
 
c. erroneous sp

-- Verify that the stored procedure does not exist.
IF OBJECT_ID ( N'usp_ExampleProc', N'P' ) IS NOT NULL
    DROP PROCEDURE usp_ExampleProc;
GO
-- Create a stored procedure that will cause an
-- object resolution error.
CREATE PROCEDURE usp_ExampleProc
AS
    SELECT * FROM NonexistentTable;
GO
BEGIN TRY
    EXECUTE usp_ExampleProc
END TRY
BEGIN CATCH
    SELECT
        ERROR_NUMBER() as ErrorNumber,
        ERROR_MESSAGE() as ErrorMessage;
END CATCH;
D. division  by zero

USE AdventureWorks;
GO
BEGIN TRY
    -- Generate a divide-by-zero error.
    SELECT 1/0;
END TRY
BEGIN CATCH
    SELECT
        ERROR_NUMBER() AS ErrorNumber,
        ERROR_SEVERITY() AS ErrorSeverity,
        ERROR_STATE() AS ErrorState,
        ERROR_PROCEDURE() AS ErrorProcedure,
        ERROR_LINE() AS ErrorLine,
        ERROR_MESSAGE() AS ErrorMessage;
END CATCH;
GO
 
d. try catch with transaction
USE AdventureWorks;
GO
BEGIN TRANSACTION;
BEGIN TRY
    -- Generate a constraint violation error.
    DELETE FROM Production.Product
        WHERE ProductID = 980;
END TRY
BEGIN CATCH
    SELECT
        ERROR_NUMBER() AS ErrorNumber,
        ERROR_SEVERITY() AS ErrorSeverity,
        ERROR_STATE() as ErrorState,
        ERROR_PROCEDURE() as ErrorProcedure,
        ERROR_LINE() as ErrorLine,
        ERROR_MESSAGE() as ErrorMessage;
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION;
END CATCH;
IF @@TRANCOUNT > 0
    COMMIT TRANSACTION;
GO
 
e. try catch with xact- state
USE AdventureWorks;
GO
-- Check to see if this stored procedure exists.
IF OBJECT_ID (N'usp_GetErrorInfo', N'P') IS NOT NULL
    DROP PROCEDURE usp_GetErrorInfo;
GO
-- Create procedure to retrieve error information.
CREATE PROCEDURE usp_GetErrorInfo
AS
    SELECT
        ERROR_NUMBER() AS ErrorNumber,
        ERROR_SEVERITY() AS ErrorSeverity,
        ERROR_STATE() as ErrorState,
        ERROR_LINE () as ErrorLine,
        ERROR_PROCEDURE() as ErrorProcedure,
        ERROR_MESSAGE() as ErrorMessage;
GO
-- SET XACT_ABORT ON will render the transaction uncommittable
-- when the constraint violation occurs.
SET XACT_ABORT ON;
BEGIN TRY
    BEGIN TRANSACTION;
        -- A foreign key constrain exists on this table. This
        -- statement will generate a constraint violation error.
        DELETE FROM Production.Product
            WHERE ProductID = 980;
    -- If the DELETE statement succeeds, commit the transaction.
    COMMIT TRANSACTION;
END TRY
BEGIN CATCH
    -- Execute error retrieval routine.
    EXECUTE usp_GetErrorInfo;
    -- Test XACT_STATE:
        -- If 1, the transaction is committable.
        -- If -1, the transaction is uncommittable and should
        --     be rolled back.
        -- XACT_STATE = 0 means that there is no transaction and
        --     a COMMIT or ROLLBACK would generate an error.
    -- Test if the transaction is uncommittable.
    IF (XACT_STATE()) = -1
    BEGIN
        PRINT
            N'The transaction is in an uncommittable state.' +
            'Rolling back transaction.'
        ROLLBACK TRANSACTION;
    END;
    -- Test if the transaction is committable
    IF (XACT_STATE()) = 1
    BEGIN
        PRINT
            N'The transaction is committable.' +
            'Committing transaction.'
        COMMIT TRANSACTION;  
    END;
END CATCH;
GO
 
REMARKS
1.  Try catch block can be nested
2.  Only one block is allowed per batch
3.  Catches all execution errors with severity greater than 10 that do not terminate the database connection
4.  A TRY block must be followed immediately by an associated CATCH block. Placing any other statements 
      between the END TRY and BEGIN CATCH statements generates a syntax error.
5.  GOTO statements cannot be used to enter a TRY or CATCH block. GOTO statements can be used to jump to a label within the same TRY or CATCH block or to leave a TRY or CATCH block.
There is no finally block
 
7月18日

Sampling SQL Data with TABLESAMPLE

Sampling  Data with TABLESAMPLE

Sampling, in demography and statistics, is the process of selecting units (e.g., people, organizations) from a population of interest so that by studying the sample we may fairly generalize our results back to the population from which they were chosen.
 
SQL Server 2005  introduce  TABLESAMPLE  function to sample data from a table. With the advent of very large database, such those of the datawarehouse, sampling maybe of great use  to developers and data professional alike who may need only a random sample of the data.

Syntax
 TABLESAMPLE [SYSTEM] (sample_number [ PERCENT | ROWS ] ) 
 [ REPEATABLE (repeat_seed) ]
 

Sample TSQL codes:


USE AdventureWorks ;
GO
SELECT *
FROM Sales.Customer TABLESAMPLE SYSTEM (10 PERCENT) ;

 

Syntax explanation
TABLESAMPLE SYSTEM returns an approximate percentage of rows. It generates a random value for each physical 8 KB page in the table. Based on the random value for a page and the percentage specified in the query, a page is included in the sample or excluded. Each page that is included returns all rows in the sample result set. For example, when specifying TABLESAMPLE SYSTEM 10 PERCENT, SQL Server returns all the rows on approximately 10 percent of the specified table's data pages. If the rows are evenly distributed on the pages of the table, and if there is a sufficient number of pages in the table, the number of rows returned should approximate the sample size requested. However, as the random value generated for each page is independent of the values generated for any other page, it is possible that a larger, or smaller, percentage of pages than requested are returned. The TOP(n) operator can be used to limit the number of rows to a given maximum
 
REPEATABLE indicates that a selected sample should be returned again. When specified with the same repeat_seed value, SQL Server returns the same subset of rows as long as no changes have been made to the table. When specified with a different repeat_seed value, SQL Server will likely return a different sample of the rows in the table. The following actions to the table are considered changes: insert, update, delete, index rebuild, index defragmentation, database restore, and database attach.
 
NOTES ON TABLESAMPLE:
 
1. TABLESAMPLE cannot be used with views.
2. cannot be used with derived tables, tables from linked servers, and tables derived from table-valued functions, rowset functions, or OPENXML
3. compatibility level of 9.0 is a must
7月6日

Using SQL SERVER 2005 Synonyms

Synonyms

 

Synonyms are words with the same meaning. In SQL server 2005 synonyms works like a permanent alias.

 

Microsoft SQL Server 2005 introduces the concept of a synonym. A synonym is an alternative name for a schema-scoped object. Client applications can use a single-part name to reference a base object by using a synonym instead of using a two-part, three-part, or four-part name to reference the base object.

A synonym is a database object that serves the following purposes:

  • It provides an alternative name for another database object, referred to as the base object, that can exist on a local or remote server.
  • It provides a layer of abstraction that protects a client application from changes made to the name or location of the base object.

Something to do:

 

1.  Create a table with a very long name

CREATE TABLE [dbo].[myverylonglonglonglongtablename](

                [id] [int] IDENTITY(1,1) NOT NULL,

                [field1] [nchar](10) COLLATE Latin1_General_CI_AS NULL,

 CONSTRAINT [PK_myverylonglonglonglongtablename] PRIMARY KEY CLUSTERED

(

                [id] ASC

)WITH (PAD_INDEX  = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY]

) ON [PRIMARY]

2. insert some thing in the table

declare @x int

select @x=0

while @x<>10

begin

select @x=@x+1

INSERT INTO [AdventureWorks].[dbo].[myverylonglonglonglongtablename]

           ([field1])

     VALUES

           ('hellox')

end

 

3.  Use select statement on the table with the long name

 

                Select * from [dbo].[myverylonglonglonglongtablename]

 

4.  create and use the synonyms

 

-- Create a synonym for the Product table in myverylonglonglonglongtablename

CREATE SYNONYM shortname

FOR [dbo].[myverylonglonglonglongtablename]

GO

 

-- Query the  table by using the synonym.

 

select * from shortname

6月18日

Restoring Selected tables from a full database backup

SQL server does not have any feature to achieve a solution to a scenario where only some of the database tables needs to be restored from a full database backup. The only avaialble solution is placing the selected tables on different filegroups then restoring the filegorups.

 

These problems can be solve however by thinking out of the box. It can be achieved by   restoring the full backup to a different database and then copying the desired tables through bulk copy, DTS, or SSIS

6月17日

Something is new on Top

One of the new cool enhancements in SQL2k5 is the new syntax and feauture of the TOP clause.
Top clause now supports the TOP N feature where N is a variable. See the example below.
 
 
USE AdventureWorks ;
GO
DECLARE @p AS int
SET @p='10'
SELECT TOP(@p)*
FROM HumanResources.Employee;
GO

 
 
Other cool feature of the TOP clause is that it now supports and can now be used with  insert, update and delete statement
 
3月17日

SQL Server 2005 Common Table Expression (CTE)

SQL Server 2005 Common Table Expression (CTE)   

 

 

CTE’s are similar to SQL Server 2000 implementations of  derived tables and temporary tables in the sense that it creates a temporary resultset on the fly. It also works like a temporary view defined within the scope of an executing statement.

 

 

Benefits of SQL server CTE’s

-          Can be used for recursive Query

-          Meets the ANSI SQL standard

-          It is much easier to code

-          Substitute for a view when the general use of a view is not required; that is, you do not have to store the definition in metadata.

-          Enable grouping by a column that is derived from a scalar subselect, or a function that is either not deterministic or has external access

-          Reference the resulting table multiple times in the same statement.

 

 

A look back on temporary tables and derived tables

 

An example of a Derived Table

 

use adventureworks

Select b.* from

(

   SELECT ListPrice, ListPrice * .95 as markedup

   FROM Production.Product

) as b

 

 

An example of Temporary tables

 CREATE TABLE #MyCTE

(

  ListPrice money,

  SellPrice money

)

INSERT INTO #MyCTE

            (ListPrice, SellPrice)

            SELECT ListPrice, ListPrice * .95

            FROM Production.Product 

 

Limitations of derived tables and temporary tables

 

-          Derived tables cannot be referenced or used more than once

-          Temporary tables cannot reference it self thought it can be used or referenced

more than once.

 

 

 

 

 

A look at some of CTE’s feature

 

A Simple CTE – more looks like a derived table

 

USE AdventureWorks;

GO

WITH DirReps(ManagerID, DirectReports) AS

(

    SELECT ManagerID, COUNT(*)

    FROM HumanResources.Employee AS e

    WHERE ManagerID IS NOT NULL

    GROUP BY ManagerID

)

SELECT ManagerID, DirectReports

FROM DirReps

ORDER BY ManagerID;

GO

 

Using a common table expression to limit counts and report averages

 

WITH DirReps (Manager, DirectReports) AS

(

    SELECT ManagerID, COUNT(*) AS DirectReports

    FROM HumanResources.Employee

    GROUP BY ManagerID

)

SELECT AVG(DirectReports) AS [Average Number of Direct Reports]

FROM DirReps

WHERE DirectReports>= 2 ;

GO

 

Referencing a common table expression more than one time
            USE AdventureWorks;

GO

WITH Sales_CTE (SalesPersonID, NumberOfOrders, MaxDate)

AS

(

    SELECT SalesPersonID, COUNT(*), MAX(OrderDate)

    FROM Sales.SalesOrderHeader

    GROUP BY SalesPersonID

)

SELECT E.EmployeeID, OS.NumberOfOrders, OS.MaxDate,

    E.ManagerID, OM.NumberOfOrders, OM.MaxDate

FROM HumanResources.Employee AS E

    JOIN Sales_CTE AS OS

    ON E.EmployeeID = OS.SalesPersonID

    LEFT OUTER JOIN Sales_CTE AS OM

    ON E.ManagerID = OM.SalesPersonID

ORDER BY E.EmployeeID;

GO

 

Using a recursive common table expression to display multiple levels of recursion

 

 

USE AdventureWorks;

GO

WITH DirectReports(ManagerID, EmployeeID, EmployeeLevel) AS

(

    SELECT ManagerID, EmployeeID, 0 AS EmployeeLevel

    FROM HumanResources.Employee

    WHERE ManagerID IS NULL

    UNION ALL

    SELECT e.ManagerID, e.EmployeeID, EmployeeLevel + 1

    FROM HumanResources.Employee e

        INNER JOIN DirectReports d

        ON e.ManagerID = d.EmployeeID

)

SELECT ManagerID, EmployeeID, EmployeeLevel

FROM DirectReports ;

GO

 

 

 

Using a recursive common table expression to display two levels of recursion

 

 

USE AdventureWorks;

GO

WITH DirectReports(ManagerID, EmployeeID, EmployeeLevel) AS

(

    SELECT ManagerID, EmployeeID, 0 AS EmployeeLevel

    FROM HumanResources.Employee

    WHERE ManagerID IS NULL

    UNION ALL

    SELECT e.ManagerID, e.EmployeeID, EmployeeLevel + 1

    FROM HumanResources.Employee e

        INNER JOIN DirectReports d

        ON e.ManagerID = d.EmployeeID

)

SELECT ManagerID, EmployeeID, EmployeeLevel

FROM DirectReports

WHERE EmployeeLevel <= 2 ;

GO

 

 

 

3月9日

DDL trigger

DDL trigger


 DDL trigger is a new feature of Sql server 2005.  This feauture can be use to audit DDL statement executions on the server. DDL stands for Data definition language which are composed of alter, create and drop statements.

 

 Thus DDL trigger as opposed to DML (insert,update,delete) trigger responds only to DDL statement  (e.g  create, alter and drop )

To do:


1. Open Sql serve management studio
2. Connect to your Sql server 2005 database
3. Use the adventurework database and
4. Type and run the following scripts


Use Adventureworks
CREATE TRIGGER safety
ON DATABASE
FOR CREATE_TABLE, DROP_TABLE, ALTER_TABLE
AS
   PRINT 'You must disable Trigger "safety" to drop, create or alter tables!'
   ROLLBACK ;


5. Test the trigger by running this scripts


create table myContact_table
(
lastname varchar(200),
firstname varchar(200),
middlename varchar(200)
 )

6. Notice that the system relpies with

 You must disable Trigger "safety" to drop, create or alter tables!'


Notes on DDL trigger:

1.  there is no "instead of" DDL trigger
2. DDL triggers fire only in response to DDL events specified by Transact-SQL DDL syntax. System stored procedures that perform DDL-like operations are not supported.
3. DDL triggers can fire in response to a Transact-SQL event processed in the current database, or on the current server. The scope of the trigger depends on the event.
4. DDL triggers do not create the inserted and deleted tables

2月28日

Introduction to Table Partitioning

Introduction to Table Partitioning

In SQL Server 2005

Table partitioning is one of Scalability and maintainability features of SQL Server 2005. With these feature a table can be spread across multiple filegroups. It also allows maintenance (such backup and restore) operations to be performed only on subsets of data (partition) rather than the whole table.

Some partitions in a table can be mapped to a read-only filegroup while other partitions can be mapped to a read/write enabled filegroups.These feature can be used as security implementation to protect subset of sensitive data residing in the same table. Consider a case of a Sales transaction table which contains sales transaction from the present and previous years. Those transactions from the previous years (partition) can be mapped to a readonly filegroup while the present sales transaction can be mapped on a read/write filegroups thereby protecting previous records from being altered irregardless of whoever has logged-in to the system provided he/she did not modify the filegroups readonly attribute

Although the data can be spread across multiple files and filegroups it is still treated as a single table in the datbase

 

Requirements for table partitioning:

1. A partition function - which defines how the rows of a table or index are mapped to a set of partitions based on the values of certain columns, called partitioning columns.

2. A partition scheme which maps each partition specified by the partition function to a filegroup.

These are the required  steps for creating a partitioned table or partitioned index:

1. Create a partition function to specify how a table or index that uses the function can be partitioned.

2. Create a partition scheme to specify the placement of the partitions of a partition function on filegroups.

 

3. Create a table or index using the partition scheme.

To do:

A. Creating a partition function

1. Create a new database

a. Open SQL server 2005 management studio

b. Connect to your SQL server 2005 database engine

c. Right click database > new database > enter "mytest" as the new database name. Click ok.

2. Create the new partition

a. Click on "new query" on the sql server 2005 management studio. Connect to the database engine and

b. Type the following

Use mytestdb

CREATE PARTITION FUNCTION myRangePF1 (int)

AS RANGE LEFT FOR VALUES (1, 100, 1000);

A table that uses this partition function on partitioning column col1 would be partitioned as follows

A. col1 <= 1

B. col1 > 1 and <=100

C. col1 > 100 and <=1000

D. col1 => 1000

Notes:

a. The partition is stored in the database located in the "storage>partition functions" tabs

b. The scope of a partition function is limited to the database that it is created in. Within the database, partition functions reside in a separate namespace from the other functions.

c. Any rows whose partitioning column has null values are placed in the left-most partition, unless NULL is specified as a boundary value and RIGHT is indicated. In this case, the left-most partition is an empty partition, and NULL values are placed in the following partition.

B. Creating A partition scheme

The partition function above partitions a table bind to it in to 4 partitions as stated above. So a partition scheme for this partition function can be mapped into four different filegroups. For more information about files and filesgroups kindly consult your books online.

Heres a sample TSQL statement for creating a partition scheme

CREATE PARTITION SCHEME myRangePS1

AS PARTITION myRangePF1 TO (test1fg, test2fg, test3fg, test4fg) <-- these are the filegroups

In this exercise since we created a database with only one file group which is the "primary" filegroup  We will be using the this scripts.

CREATE PARTITION SCHEME myRangePS1

AS PARTITION myRangePF1 TO (

primary, primary, primary, primary)

To do:

1. Open SQL Server 2005 management studio

2. Connect to SQL server 2005 database engine

3. Be sure to use

"mytest" database from the previous exrcise

4. click on the new query paste the scripts above and press F5 to execute

You have just created a new partitioning scheme.

5. Drop the partition scheme and recreate it by using the following scripts below. Notice that there is an excess filegroup in the filegroup names

Create PARTITION SCHEME myRangePS1

AS PARTITION myRangePF1 TO (

primary, primary, primary, primary, primary)

6. SQL server creates the partition scheme and returns the following message:

Partition scheme 'myRangePS1' has been created successfully. 'PRIMARY' is marked as the next used filegroup in partition scheme 'myRangePS1'.

As you can see the excess filegroup has been mark for use should a new partition would be created in the future

C. Create a table that uses the partition

Use the following scripts to create a partion table

CREATE TABLE PartitionTable (col1 int, col2 char(10))

ON myRangePS1 (col1) ;

1月11日

SQL Server 2005 Schemas

SQL Server 2005 Schemas

 

           

            Schemas  are used to organize database objects into namespaces. In the new SQL server 2005 security architecture, schemas are securable  that contains database objects. A user can be granted access to a schema thereby allowing him to inherit the permissions on database objects inside the schema except for objects where he is explicitly denied.

 

            When a SQL server user is created he can be assigned a default schema. If no default schema is assigned the user is assigned “DBO schema” as its default schema. When a user is assigned a default schema all unqualified data base objects are resolved first to his default schema. When an object is not found in the default schema it then falls back to the “DBO schema”.  If the object in question is still not found in the “DBO schema “, an exemption is thrown

 

            Unlike sql server 2000, schemas are no longer tied to SQL server user which is now better known as the “Users-Schemas separation”. A schema can exist by itself and that means a user can be dropped without dropping the schema
1月6日

Keeping Things Organized

Keeping Things Organized  with
SQL Server 2005 Management Studio
Solutions
 
 
One of the new enhancements of the SQL Server Management Studio is the ability to keep things organized into a solution or a project. Equipped with the solution explorer, very similar to Microsoft Visual Studio it allows you easily navigate through your project. It makes life of DA and DBAs easier by providing the following features:

1. Save connection information with each script.
2. Maintain version control on scripts.
3. Store results options with scripts.
4. Organize related scripts into a single script project.
 
Something to try:
 
1. Open SQL Server 2005 Management Studio
2. In the connect to Server dialog click “Cancel”
3. Click on file > new > create  project
4. In the new project dialog click on “SQL Server Scripts”
5. In the name field of the new project dialog type “my adventure at work”
6. Click ok to create the project
7. In the solution explorer, Right click connection and click on new connection
8. Create a connection to your server but entering necessary data to the connect to server dialog.
9. A new connection appears in the connections folder of the solution explorer
10. Right click the newly create connection and click on new query
11. Type the following scripts:
Use adventureworks
select * from Person.Contact
 
12. run and save the scripts
13. close and reopen the project
12月28日

How does SQL server Updates a record

How Does SQL  Server Updates a Record?
 

1. Client send a request to update record
2. SQL Server receives the request
3. SQL server checks if  the records exist in the data page cache
4. If not SQL server load the pages from hard disk to page cache in memory
5. SQL Server place the following  locks:

a. shared database lock
b. Intent locks on the table
c. Intent lock on the page
d. Update lock  on the rows

6. SQL Server “exclusive lock”  on the  rows to be updated
7. Updates happens in the data page cache in memory
8. SQL server logs the changes to log pages in memory
9. SQL server writes the log pages in memory  to transaction log on disk
10. SQL server release the locks and tell the user that update has completed
11. SQL server write to the logs which is called the “write ahead log”
12. SQL server updates the records in the data file at every checkpoint.

 
notes:
1.  Page cache are reused many times
2.  Currency and consistency are maintained by using locks
3.  What is written in the transaction logs are log pages from memory
4.  Checkpoint writes what is in the transaction log to the data file

 
12月20日

SQL CLR Integration

            One of the new feature of SQL server 2005 is the CLR integration.  This feature allows the use .NET base classes such as the use of arrays  to expand SQL Server functionality. This feature is somewhat similar to extended stored procedures in earlier SQL Server versions.

 

            This feature is supported even by the express edition. To make use of this feature you must first enable it using the SQL server surface area configuration by clicking on start>programs>Microsoft SQL Server 2005>configuration tools>SQL server configuration manager> “Surface area configuration for features”; choose the database server you want to configure;  choose CLR integration feature and checking the checkbox to enable this feature.

 

SQL-CLR Integration Exercise

    

     In this exercise you shall be able to create a simple assembly and deploy it to SQL server database.

Software requirements:

1. For advance users you need SQL server 2005 express
2. For beginners, SQL server 2005 enterprise or developer edition
3. .Net framework version 2

Steps

1. Open notepad. And type the following codes

Imports System
Imports System.Data
Imports Microsoft.SqlServer.Server
Imports System.Data.SqlTypes
 
Public Class HelloWorldProc
    <Microsoft.SqlServer.Server.SqlProcedure> _
    Public Shared  Sub HelloWorld()
        SqlContext.Pipe.Send("Hello world!")
    End Sub
End Class

2. Create a CLR folder on drive c: and save the file you create in step 1 as “clrtest.vb”

3. Locate your Visual basic compiler(VBC) compiler which is deployed together with the .net framework.  It is commonly located in  “windows” or “winnt” folder

4. Add the path to your environment in the control panel>system>system properties>advance>environment variables. Click new and type “path” on the “variable name” textbox and type the path to the compiler in the  “variable value” in my case its “C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727”
5. Click start > run > type “cmd”
6. Compile the codes to an assemble using the “/target” switch
7. type vbc /target:library c:/clr/clrtest.vb
8. Its going to create a dll file called “clrtest.dll”
9. Run the following T-SQL statement. Be sure that you are running on a Sql server 2005 database.

CREATE ASSEMBLY testclr  from 'c:\clr\clrtest.dll' WITH PERMISSION_SET = SAFE

This will load the assembly into the database

10. Create a stored procedure that uses the assembly

CREATE PROCEDURE hello
AS
EXTERNAL NAME testclr.HelloWorldProc.HelloWorld

11. Execute the stored proc

Exec hello

12. It should return


“Hello World!”

 

When and when not to use CLR integration

 

When to use CLR
 Use SQL-CLR integration for:
 1.  Computationally intensive functions
 2.  Complex logic
 3.  Data structures not supported in T-Sql (e.g. arrays)
 4.  Accessing  functionality in the base class library
 5.  SQL reader is faster than TSQL cursor for forward only read only navigation
6.  string handling, regular expression validation, file access, general   cryptography, replacing external procedures

When not to SQL-CLR

 Do not use CRL integration when/for
 1.  Basic data access operations
 2.  Procedures with little or no procedural logic

Security

SQL-CLR integration is off by default

Three levels of security  for assemblies specified during create assembly refer to step 9 of the exercise.


1.  Safe (default)
2.  External Access(registry, files,environment)
3.  Unsafe (unrestricted)

 

12月19日

My sql server blogs

These are my official Sql server 2005 blogs.
These are created for the purpose of rapidly learning
Sql server 2005.
 
thank you for navigating to this site