| jose 的个人资料SQL Server 2005 blogs日志列表 | 帮助 |
SQL Server 2005 blogsLearning the First Few Steps 9月23日 Loading XML to SQL SERVER 2005Bulk 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.
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.
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.
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=" 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 ?
Why do the snapshot?
Limitations
7月26日 The SQL SERVER 2005 Try Catch BlockSYNTAX
OVERVIEW
EXAMPLES
REMARKS
7月18日 Sampling SQL Data with TABLESAMPLESampling 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
Sample TSQL codes:
Syntax explanation
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 SynonymsSynonyms
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:
Something to do:
1. Create a table with a very long name
2. insert some thing in the table
3. Use select statement on the table with the long name
Select * from [dbo].[myverylonglonglonglongtablename]
4. create and use the synonyms
6月18日 Restoring Selected tables from a full database backupSQL 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 TopOne 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.
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 tablesCREATE 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 triggerDDL trigger
Thus DDL trigger as opposed to DML (insert,update,delete) trigger responds only to DDL statement (e.g create, alter and drop )
6. Notice that the system relpies with You must disable Trigger "safety" to drop, create or alter tables!'
2月28日 Introduction to Table PartitioningIntroduction 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:
These are the required steps for creating a partitioned table or partitioned index:
To do: A. Creating a partition function 1. Create a new database
2. Create the new 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. Here’s a sample TSQL statement for creating a partition scheme
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.
AS PARTITION myRangePF1 TO ( ‘primary’, ‘primary’, ‘primary’, ‘primary’)To do: "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
ON myRangePS1 (col1) ; 1月11日 SQL Server 2005 SchemasSQL 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 OrganizedKeeping 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:
12. run and save the scripts 13. close and reopen the project 12月28日 How does SQL server Updates a recordHow Does SQL Server Updates a Record?
1. Client send a request to update record
6. SQL Server “exclusive lock” on the rows to be updated 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 IntegrationOne 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 Steps 1. Open notepad. And type the following codes
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”
This will load the assembly into the database 10. Create a stored procedure that uses the assembly
11. Execute the stored proc
12. It should return
When and when not to use CLR integration
Security SQL-CLR integration is off by default
12月19日 My sql server blogsThese 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 |
||||||
|
|