diff --git a/1244.html b/1244.html new file mode 100644 index 0000000..a59ef80 --- /dev/null +++ b/1244.html @@ -0,0 +1,14 @@ +Chapter 1: Being a DBA
+Chapter 2: SQL Server Installation
+Chapter 3: Creating a Database
+Chapter 4: DML and Querying
+Chapter 5: Basic Management Tasks
+Chapter 6: Security
+Chapter 7: Connectivity
+Chapter 8: Backup and Recovery
+Chapter 9: Replication
+Chapter 10: Development with Transact-SQL
+Chapter 11: Data Warehousing and Analysis
+Chapter 12: Data Transformation Services
+Chapter 13: Monitor, Profile, and Tune
+Chapter 14: Keeping the Plates Spinning \ No newline at end of file diff --git a/1450.pdf b/1450.pdf new file mode 100644 index 0000000..dbf4bdd Binary files /dev/null and b/1450.pdf differ diff --git a/1451.pdf b/1451.pdf new file mode 100644 index 0000000..dd2a8e4 Binary files /dev/null and b/1451.pdf differ diff --git a/293x_CODE/Chap03code/Thumbs.db b/293x_CODE/Chap03code/Thumbs.db new file mode 100644 index 0000000..387afe3 Binary files /dev/null and b/293x_CODE/Chap03code/Thumbs.db differ diff --git a/293x_CODE/Chap03code/alter_constraints.sql b/293x_CODE/Chap03code/alter_constraints.sql new file mode 100644 index 0000000..e1ee92e --- /dev/null +++ b/293x_CODE/Chap03code/alter_constraints.sql @@ -0,0 +1,6 @@ +USE TestDB1 + +ALTER TABLE Table2 +ADD CONSTRAINT fk_table2_table1_idcol FOREIGN KEY (Table1_IDCol) + REFERENCES Table1(IDCol) +GO diff --git a/293x_CODE/Chap03code/create_database.sql b/293x_CODE/Chap03code/create_database.sql new file mode 100644 index 0000000..1b9e862 --- /dev/null +++ b/293x_CODE/Chap03code/create_database.sql @@ -0,0 +1,24 @@ +CREATE DATABASE Test3 +ON PRIMARY + (NAME = test3_primary_data1, + FILENAME = 'd:\sqldata\test3_primary_data1.mdf', + SIZE = 1MB, + MAXSIZE = 200MB, + FILEGROWTH = 10%), + (NAME = test3_primary_data2, + FILENAME = 'd:\sqldata\test3_primary_data2.ndf', + SIZE = 1MB, + MAXSIZE = 200MB, + FILEGROWTH = 10%), +FILEGROUP FG2 + (NAME = test3_fg2_data1, + FILENAME = 'd:\sqldata\test3_fg2_data1.ndf', + SIZE = 1MB, + MAXSIZE = 200MB, + FILEGROWTH = 10%) + +LOG ON (NAME = test3_log1, + FILENAME = 'd:\sqldata\test3_log1.ldf', + SIZE = 51MB, + MAXSIZE = 200MB, + FILEGROWTH = 10%) diff --git a/293x_CODE/Chap03code/create_table.sql b/293x_CODE/Chap03code/create_table.sql new file mode 100644 index 0000000..56a1cb6 --- /dev/null +++ b/293x_CODE/Chap03code/create_table.sql @@ -0,0 +1,28 @@ +use Test3 + +CREATE TABLE Table2 +( + IDCol int identity(1,1) PRIMARY KEY, + Table1_IDCol int NULL, + VarCharCol varchar(255) NOT NULL, +) +GO + + +CREATE DATABASE TestDB1 +CREATE TABLE Table1 +( + IDCol int identity(1,1) PRIMARY KEY, + Table1_IDCol int NULL, + VarCharCol varchar(255) NOT NULL, + DateCol datetime NOT NULL, + MoneyCol money NULL +) + +CREATE TABLE Table2 +( + IDCol int identity(1,1) PRIMARY KEY, + Table1_IDCol int NULL, + VarCharCol varchar(255) NOT NULL +) +GO \ No newline at end of file diff --git a/293x_CODE/Chap04code/create_example_tables.sql b/293x_CODE/Chap04code/create_example_tables.sql new file mode 100644 index 0000000..94adcd4 --- /dev/null +++ b/293x_CODE/Chap04code/create_example_tables.sql @@ -0,0 +1,13 @@ +USE Northwind + +CREATE TABLE Food_Table +( + Food_ID INT PRIMARY KEY, + Food_Name VARCHAR(255) +) + +CREATE TABLE Group_Table +( + Group_ID INT PRIMARY KEY, + Group_Name VARCHAR(255) +) diff --git a/293x_CODE/Chap04code/create_full_text_index.sql b/293x_CODE/Chap04code/create_full_text_index.sql new file mode 100644 index 0000000..3481cc7 --- /dev/null +++ b/293x_CODE/Chap04code/create_full_text_index.sql @@ -0,0 +1,20 @@ +USE Northwind + +EXEC sp_fulltext_database 'enable' +GO + + +USE Northwind +EXEC sp_fulltext_catalog 'NorthFTCatalog', 'create' +GO + + +USE Northwind +EXEC sp_fulltext_table 'dbo.Products', + 'Create', 'NorthFTCatalog', 'PK_Products' +GO + + +USE Northwind +EXEC sp_fulltext_column 'dbo.Products', 'ProductName', 'add' +GO \ No newline at end of file diff --git a/293x_CODE/Chap04code/cross_join.sql b/293x_CODE/Chap04code/cross_join.sql new file mode 100644 index 0000000..0749ad5 --- /dev/null +++ b/293x_CODE/Chap04code/cross_join.sql @@ -0,0 +1 @@ +SELECT * FROM Food_Table CROSS JOIN Group_Table \ No newline at end of file diff --git a/293x_CODE/Chap04code/deleting_data.sql b/293x_CODE/Chap04code/deleting_data.sql new file mode 100644 index 0000000..a3db583 --- /dev/null +++ b/293x_CODE/Chap04code/deleting_data.sql @@ -0,0 +1,9 @@ +USE Northwind + +SELECT Food_ID, Food_Name FROM Food_Table + +DELETE Food_Table WHERE Food_Name='Steak' + +SELECT Food_ID, Food_Name FROM Food_Table + +INSERT Food_Table(Food_ID, Food_Name) VALUES(2, 'Steak') \ No newline at end of file diff --git a/293x_CODE/Chap04code/full_text_population.sql b/293x_CODE/Chap04code/full_text_population.sql new file mode 100644 index 0000000..4058258 --- /dev/null +++ b/293x_CODE/Chap04code/full_text_population.sql @@ -0,0 +1,23 @@ +--full population +EXEC sp_fulltext_catalog 'NorthFTCatalog', 'start_full' + +EXEC sp_fulltext_table 'dbo.Products', 'start_full' + + +/* +--incremental population +USE Northwind + +ALTER TABLE Products +ADD TimeStampCol timestamp + +EXEC sp_fulltext_table 'dbo.Products', 'start_full' + +UPDATE Products +SET ProductName='Marmite Spread' WHERE ProductID=63 + +UPDATE Products +SET ProductName='Canterbury Beer' WHERE ProductID=60 + +EXEC sp_fulltext_table 'dbo.Products','start_incremental' +*/ \ No newline at end of file diff --git a/293x_CODE/Chap04code/inner_join.sql b/293x_CODE/Chap04code/inner_join.sql new file mode 100644 index 0000000..cbbc19f --- /dev/null +++ b/293x_CODE/Chap04code/inner_join.sql @@ -0,0 +1,3 @@ +SELECT * FROM Food_Table + INNER JOIN Group_Table ON Food_Table.Food_ID = + Group_Table.Group_ID diff --git a/293x_CODE/Chap04code/multiple_predicates.sql b/293x_CODE/Chap04code/multiple_predicates.sql new file mode 100644 index 0000000..e26bcfa --- /dev/null +++ b/293x_CODE/Chap04code/multiple_predicates.sql @@ -0,0 +1,10 @@ +USE Northwind + +SELECT Food_ID, Food_Name FROM Food_Table + WHERE Food_ID>1 AND (Food_Name='Steak' OR Food_Name='Milk') + +/* +SELECT CustomerID, ContactName, City, PostalCode, Country + FROM Customers + WHERE City='London' OR (Country='Germany' AND PostalCode='80805') +*/ \ No newline at end of file diff --git a/293x_CODE/Chap04code/ordering_data.sql b/293x_CODE/Chap04code/ordering_data.sql new file mode 100644 index 0000000..9c9ea10 --- /dev/null +++ b/293x_CODE/Chap04code/ordering_data.sql @@ -0,0 +1,3 @@ +USE Northwind + +SELECT Food_ID, Food_Name FROM Food_Table ORDER BY Food_Name diff --git a/293x_CODE/Chap04code/outer_join.sql b/293x_CODE/Chap04code/outer_join.sql new file mode 100644 index 0000000..65a035d --- /dev/null +++ b/293x_CODE/Chap04code/outer_join.sql @@ -0,0 +1,19 @@ +--left outer join +SELECT * FROM Food_Table LEFT OUTER JOIN Group_Table ON + Food_Table.Food_ID = Group_Table.Group_ID + + +/* +--right outer join +SELECT * FROM + Food_Table RIGHT OUTER JOIN Group_Table ON + Food_Table.Food_ID = Group_Table.Group_ID +*/ + + +/* +--full outer join +SELECT *FROM + Food_Table FULL OUTER JOIN Group_Table ON + Food_Table.Food_ID = Group_Table.Group_ID +*/ \ No newline at end of file diff --git a/293x_CODE/Chap04code/querying_full_text.sql b/293x_CODE/Chap04code/querying_full_text.sql new file mode 100644 index 0000000..33bc42c --- /dev/null +++ b/293x_CODE/Chap04code/querying_full_text.sql @@ -0,0 +1,15 @@ +--full-text query +SELECT * FROM Products + WHERE CONTAINS(ProductName, '"Syrup" OR "Cran*"') + +--full-text query returned in a table +SELECT * FROM Products + WHERE CONTAINSTABLE(ProductName, '"Syrup" OR "Cran*"') + +--freetext +SELECT * FROM Products + WHERE FREETEXT(ProductName,'Syrup Sauce') + +--freetext table +SELECT * FROM Products + WHERE FREETEXTTABLE(ProductName,'Syrup Sauce') \ No newline at end of file diff --git a/293x_CODE/Chap04code/simple_insert.sql b/293x_CODE/Chap04code/simple_insert.sql new file mode 100644 index 0000000..f4e81f7 --- /dev/null +++ b/293x_CODE/Chap04code/simple_insert.sql @@ -0,0 +1,19 @@ +USE Northwind + +INSERT Food_Table(Food_ID, Food_Name) VALUES(1, 'Bread') + +INSERT Food_Table(Food_ID, Food_Name) VALUES(2, 'Steak') + +INSERT Food_Table(Food_Id, Food_Name) VALUES(3, 'Milk') +GO + + + +USE Northwind + +INSERT Group_Table(Group_ID, Group_Name) VALUES(1, 'Grains') + +INSERT Group_Table(Group_ID, Group_Name) VALUES(5, 'Meat') + +INSERT Group_Table(Group_ID, Group_Name) VALUES(3, 'Dairy') +GO \ No newline at end of file diff --git a/293x_CODE/Chap04code/update.sql b/293x_CODE/Chap04code/update.sql new file mode 100644 index 0000000..c647810 --- /dev/null +++ b/293x_CODE/Chap04code/update.sql @@ -0,0 +1,6 @@ +SELECT ContactName FROM Customers WHERE CustomerID='FRANR' + +UPDATE Customers SET ContactName='Linda Glucina' + WHERE CustomerID='FRANR' + +SELECT ContactName FROM Customers WHERE CustomerID='FRANR' diff --git a/293x_CODE/Chap04code/using_an_index.sql b/293x_CODE/Chap04code/using_an_index.sql new file mode 100644 index 0000000..b79115d --- /dev/null +++ b/293x_CODE/Chap04code/using_an_index.sql @@ -0,0 +1,17 @@ +SELECT UnitPrice, Quantity FROM [Order Details] + WHERE Quantity BETWEEN 10 AND 11 AND UnitPrice > 50 + +/* +CREATE NONCLUSTERED INDEX ix_orderdetails_productid + ON [Order Details](UnitPrice, Quantity) +*/ + + +/* +SELECT UnitPrice, Quantity FROM [Order Details] + WHERE Quantity BETWEEN 10 AND 11 AND UnitPrice > 50 +*/ + +/* +DROP INDEX [Order Details].ix_orderdetails_productid +*/ \ No newline at end of file diff --git a/293x_CODE/Chap04code/using_wildcard.sql b/293x_CODE/Chap04code/using_wildcard.sql new file mode 100644 index 0000000..962fed4 --- /dev/null +++ b/293x_CODE/Chap04code/using_wildcard.sql @@ -0,0 +1,30 @@ +USE Northwind + +SELECT CustomerID, ContactName, City, PostalCode, Country + FROM Customers WHERE City LIKE 'L%' + +/* +SELECT CustomerID, ContactName, City, PostalCode, Country + FROM Customers WHERE City LIKE '[ABC]%' +*/ + + +/* +SELECT CustomerID, ContactName, City, PostalCode, Country + FROM Customers WHERE City LIKE '[A-C]%' + +*/ + + +/* +SELECT CustomerID, ContactName, City, PostalCode, Country + FROM Customers WHERE City LIKE '[^ABC]%' + +*/ + + +/* +SELECT CustomerID, ContactName, City, PostalCode, Country + FROM Customers WHERE City LIKE '_[a]%' + +*/ \ No newline at end of file diff --git a/293x_CODE/Chap05code/add_alert.sql b/293x_CODE/Chap05code/add_alert.sql new file mode 100644 index 0000000..83e0506 --- /dev/null +++ b/293x_CODE/Chap05code/add_alert.sql @@ -0,0 +1,8 @@ +EXEC msdb..sp_add_alert @name = 'Alert: Object not found', + @severity = 11 + +/* +EXEC msdb..sp_add_notification 'Alert: Object not found', + 'SuperDBA', 1 + +*/ diff --git a/293x_CODE/Chap05code/add_job.sql b/293x_CODE/Chap05code/add_job.sql new file mode 100644 index 0000000..e435260 --- /dev/null +++ b/293x_CODE/Chap05code/add_job.sql @@ -0,0 +1,41 @@ +DECLARE @JobID BINARY(16) + +EXEC msdb.dbo.sp_add_job @job_id = @JobID OUTPUT , + @job_name = 'Run DBCC on Northwind', + @enabled = 1, -- Active + @owner_login_name = 'sa', + @notify_level_eventlog = 2, + @notify_level_email = 2, + @notify_email_operator_name = 'SuperDBA' + +SELECT @JobID + +GO + + + +EXEC msdb.dbo.sp_add_jobstep @job_name = 'Run DBCC on + Northwind', + @step_name = 'Run DBCC CheckDB on + Northwind', + @command = 'DBCC CheckDB + (''Northwind'')', + @subsystem = 'TSQL', + @output_file_name = 'C: \ + DBCCResult.txt' + + +GO + + + +EXEC msdb.dbo.sp_add_jobschedule @job_name = 'Run DBCC on + Northwind', + @name = 'Run DBCC Weekly', + @freq_type = 8, -- Weekly + @freq_interval = 2, -- Monday + @active_start_time = 40000, + @freq_recurrence_factor = 1 + -- Every week + +GO \ No newline at end of file diff --git a/293x_CODE/Chap05code/add_operator.sql b/293x_CODE/Chap05code/add_operator.sql new file mode 100644 index 0000000..a8017bd --- /dev/null +++ b/293x_CODE/Chap05code/add_operator.sql @@ -0,0 +1 @@ +EXEC msdb..sp_add_operator @name = 'SuperDBA', @email_address = 'superdba@mycompanyname.xyz' diff --git a/293x_CODE/Chap05code/db_restore.sql b/293x_CODE/Chap05code/db_restore.sql new file mode 100644 index 0000000..050ea84 --- /dev/null +++ b/293x_CODE/Chap05code/db_restore.sql @@ -0,0 +1,8 @@ +RESTORE DATABASE Northwind2 +FROM DISK = 'C:\Program Files\Microsoft SQL Server + \MSSQL\BACKUP\Northwind.bak' +WITH + MOVE 'Northwind_log' TO 'C:\Program Files\ + Microsoft SQL Server\MSSQL\data\Northwind2_log.ldf', + MOVE 'Northwind' TO 'C:\Program Files\ + Microsoft SQL Server\MSSQL\data\Northwind2.mdf' diff --git a/293x_CODE/Chap05code/when_db_backedup.sql b/293x_CODE/Chap05code/when_db_backedup.sql new file mode 100644 index 0000000..f25ffab --- /dev/null +++ b/293x_CODE/Chap05code/when_db_backedup.sql @@ -0,0 +1,3 @@ +SELECT MAX(backup_finish_date) +FROM msdb..backupset +WHERE type = 'D' AND database_name = 'Northwind' diff --git a/293x_CODE/Chap07code/7053_07_51.bmp b/293x_CODE/Chap07code/7053_07_51.bmp new file mode 100644 index 0000000..2ffb4fc Binary files /dev/null and b/293x_CODE/Chap07code/7053_07_51.bmp differ diff --git a/293x_CODE/Chap07code/CreateADONetConnection/AssemblyInfo.vb b/293x_CODE/Chap07code/CreateADONetConnection/AssemblyInfo.vb new file mode 100644 index 0000000..00fbd89 --- /dev/null +++ b/293x_CODE/Chap07code/CreateADONetConnection/AssemblyInfo.vb @@ -0,0 +1,31 @@ +Imports System.Reflection +Imports System.Runtime.InteropServices + +' General Information about an assembly is controlled through the following +' set of attributes. Change these attribute values to modify the information +' associated with an assembly. + +' Review the values of the assembly attributes + + + + + + + + + +'The following GUID is for the ID of the typelib if this project is exposed to COM + + +' Version information for an assembly consists of the following four values: +' +' Major Version +' Minor Version +' Build Number +' Revision +' +' You can specify all the values or you can default the Build and Revision Numbers +' by using the '*' as shown below: + + diff --git a/293x_CODE/Chap07code/CreateADONetConnection/CreateADONetConnection.sln b/293x_CODE/Chap07code/CreateADONetConnection/CreateADONetConnection.sln new file mode 100644 index 0000000..a75167c --- /dev/null +++ b/293x_CODE/Chap07code/CreateADONetConnection/CreateADONetConnection.sln @@ -0,0 +1,21 @@ +Microsoft Visual Studio Solution File, Format Version 7.00 +Project("{F184B08F-C81C-45F6-A57F-5ABD9991F28F}") = "CreateADONetConnection", "CreateADONetConnection.vbproj", "{B0DD5415-57C0-419F-A952-A45E895B15A6}" +EndProject +Global + GlobalSection(SolutionConfiguration) = preSolution + ConfigName.0 = Debug + ConfigName.1 = Release + EndGlobalSection + GlobalSection(ProjectDependencies) = postSolution + EndGlobalSection + GlobalSection(ProjectConfiguration) = postSolution + {B0DD5415-57C0-419F-A952-A45E895B15A6}.Debug.ActiveCfg = Debug|.NET + {B0DD5415-57C0-419F-A952-A45E895B15A6}.Debug.Build.0 = Debug|.NET + {B0DD5415-57C0-419F-A952-A45E895B15A6}.Release.ActiveCfg = Release|.NET + {B0DD5415-57C0-419F-A952-A45E895B15A6}.Release.Build.0 = Release|.NET + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + EndGlobalSection + GlobalSection(ExtensibilityAddIns) = postSolution + EndGlobalSection +EndGlobal diff --git a/293x_CODE/Chap07code/CreateADONetConnection/CreateADONetConnection.suo b/293x_CODE/Chap07code/CreateADONetConnection/CreateADONetConnection.suo new file mode 100644 index 0000000..4538af4 Binary files /dev/null and b/293x_CODE/Chap07code/CreateADONetConnection/CreateADONetConnection.suo differ diff --git a/293x_CODE/Chap07code/CreateADONetConnection/CreateADONetConnection.vb b/293x_CODE/Chap07code/CreateADONetConnection/CreateADONetConnection.vb new file mode 100644 index 0000000..96b47c1 --- /dev/null +++ b/293x_CODE/Chap07code/CreateADONetConnection/CreateADONetConnection.vb @@ -0,0 +1,37 @@ +Imports System.Data.SqlClient + +Module Module1 + + Sub Main() + Try + ' ADO.NET SQL Server-optimized connection object + Dim conn As New SqlConnection("Initial Catalog=pubs;" _ + & "Data Source =(local);Integrated Security=SSPI") + conn.Open() + + ' Command object + Dim command As New SqlCommand("SELECT au_id,au_lname,au_fname" _ + & " FROM authors", conn) + ' Datareader object + Dim reader As SqlDataReader = _ + command.ExecuteReader(CommandBehavior.CloseConnection) + + ' Output datareader values + While reader.Read() + Console.WriteLine(reader.GetSqlValue(1)) + End While + + ' Tidy & pause + conn.Close() + Console.ReadLine() + + ' Catch any errors + Catch ex As Exception + Console.WriteLine("Exception: " & ex.Message) + Console.WriteLine(ex.ToString) + Console.ReadLine() + End Try + + End Sub + +End Module diff --git a/293x_CODE/Chap07code/CreateADONetConnection/CreateADONetConnection.vbproj b/293x_CODE/Chap07code/CreateADONetConnection/CreateADONetConnection.vbproj new file mode 100644 index 0000000..5b4ad57 --- /dev/null +++ b/293x_CODE/Chap07code/CreateADONetConnection/CreateADONetConnection.vbproj @@ -0,0 +1,97 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/293x_CODE/Chap07code/CreateADONetConnection/CreateADONetConnection.vbproj.user b/293x_CODE/Chap07code/CreateADONetConnection/CreateADONetConnection.vbproj.user new file mode 100644 index 0000000..447fdc6 --- /dev/null +++ b/293x_CODE/Chap07code/CreateADONetConnection/CreateADONetConnection.vbproj.user @@ -0,0 +1,48 @@ + + + + + + + + + + + + diff --git a/293x_CODE/Chap07code/CreateADONetConnection/bin/CreateADONetConnection.exe b/293x_CODE/Chap07code/CreateADONetConnection/bin/CreateADONetConnection.exe new file mode 100644 index 0000000..22e61fa Binary files /dev/null and b/293x_CODE/Chap07code/CreateADONetConnection/bin/CreateADONetConnection.exe differ diff --git a/293x_CODE/Chap07code/CreateADONetConnection/bin/CreateADONetConnection.pdb b/293x_CODE/Chap07code/CreateADONetConnection/bin/CreateADONetConnection.pdb new file mode 100644 index 0000000..b507986 Binary files /dev/null and b/293x_CODE/Chap07code/CreateADONetConnection/bin/CreateADONetConnection.pdb differ diff --git a/293x_CODE/Chap07code/CreateADONetConnection/obj/Debug/CreateADONetConnection.exe b/293x_CODE/Chap07code/CreateADONetConnection/obj/Debug/CreateADONetConnection.exe new file mode 100644 index 0000000..22e61fa Binary files /dev/null and b/293x_CODE/Chap07code/CreateADONetConnection/obj/Debug/CreateADONetConnection.exe differ diff --git a/293x_CODE/Chap07code/CreateADONetConnection/obj/Debug/CreateADONetConnection.pdb b/293x_CODE/Chap07code/CreateADONetConnection/obj/Debug/CreateADONetConnection.pdb new file mode 100644 index 0000000..b507986 Binary files /dev/null and b/293x_CODE/Chap07code/CreateADONetConnection/obj/Debug/CreateADONetConnection.pdb differ diff --git a/293x_CODE/Chap07code/Thumbs.db b/293x_CODE/Chap07code/Thumbs.db new file mode 100644 index 0000000..0abc0d0 Binary files /dev/null and b/293x_CODE/Chap07code/Thumbs.db differ diff --git a/293x_CODE/Chap07code/Wspcfg.ini b/293x_CODE/Chap07code/Wspcfg.ini new file mode 100644 index 0000000..e45a9b6 --- /dev/null +++ b/293x_CODE/Chap07code/Wspcfg.ini @@ -0,0 +1,4 @@ +[sqlservr] + ServerBindTCPPorts=1433 + Persistent=1 + KillOldSession=1 diff --git a/293x_CODE/Chap07code/autohierarch.xml b/293x_CODE/Chap07code/autohierarch.xml new file mode 100644 index 0000000..40685a2 --- /dev/null +++ b/293x_CODE/Chap07code/autohierarch.xml @@ -0,0 +1,9 @@ + + + SELECT Customers.CustomerID, OrderID + FROM Customers + LEFT OUTER JOIN Orders ON Customers.CustomerID = Orders.CustomerID + ORDER BY Customers.CustomerID + FOR XML AUTO + + diff --git a/293x_CODE/Chap07code/createODBCconnection.asp b/293x_CODE/Chap07code/createODBCconnection.asp new file mode 100644 index 0000000..b941326 --- /dev/null +++ b/293x_CODE/Chap07code/createODBCconnection.asp @@ -0,0 +1,25 @@ +<% +'Declare variables +Dim rs +Dim conn +'handle errors +On Error Resume next +'Set Object reference +Set rs = CreateObject("ADODB.Recordset") + +'Open the database and query records +conn = "DSN=LOCAL_PUBS_TEST" +rs.Open "SELECT au_id,au_lname,au_fname FROM authors", conn + +Select CASE Err.Number + CASE 0 + Response.Write "ODBC Connection succeded." + CASE Else + Response.Write "ODBC Connection failed : " & _ + Err.Number & " - " & Err.Description +End Select + +'clean up +rs.Close +Set rs = Nothing +%> diff --git a/293x_CODE/Chap07code/nwind.xdr b/293x_CODE/Chap07code/nwind.xdr new file mode 100644 index 0000000..bbf5ced --- /dev/null +++ b/293x_CODE/Chap07code/nwind.xdr @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + + + + diff --git a/293x_CODE/Chap07code/rawhierarch.xml b/293x_CODE/Chap07code/rawhierarch.xml new file mode 100644 index 0000000..36b9694 --- /dev/null +++ b/293x_CODE/Chap07code/rawhierarch.xml @@ -0,0 +1,8 @@ + + + SELECT Customers.CustomerID, OrderID + FROM Customers + LEFT OUTER JOIN Orders ON Customers.CustomerID = Orders.CustomerID + FOR XML RAW + + diff --git a/293x_CODE/Chap07code/siblings.xml b/293x_CODE/Chap07code/siblings.xml new file mode 100644 index 0000000..6eaac87 --- /dev/null +++ b/293x_CODE/Chap07code/siblings.xml @@ -0,0 +1,32 @@ + + + SELECT 1 as TAG, + NULL as Parent, + CustomerID as [Customer!1!CustomerID], + NULL as [Order!2!OrderID], + NULL as [Employee!3!LastName] + FROM Customers + + UNION ALL + SELECT 2, + 1, + Customers.CustomerID, + Orders.OrderID, + NULL + FROM Orders + JOIN Customers ON Orders.CustomerID = Customers.CustomerID + + UNION ALL + SELECT DISTINCT 3, + 1, + Customers.CustomerID, + NULL, + Employees.LastName + FROM Customers + JOIN Orders ON Customers.CustomerID = Orders.CustomerID + JOIN Employees ON Orders.EmployeeID = Employees.EmployeeID + + ORDER BY [Customer!1!CustomerID],[Employee!3!LastName],[Order!2!OrderID] + FOR XML EXPLICIT + + diff --git a/293x_CODE/Chap08code/backup.sql b/293x_CODE/Chap08code/backup.sql new file mode 100644 index 0000000..ef2b865 --- /dev/null +++ b/293x_CODE/Chap08code/backup.sql @@ -0,0 +1,3 @@ +BACKUP DATABASE Northwind +TO DISK='C:\Program Files\Microsoft SQL Server\MSSQL\Backup\Northwind backup.bak' +WITH INIT diff --git a/293x_CODE/Chap08code/create_simulatefailure.sql b/293x_CODE/Chap08code/create_simulatefailure.sql new file mode 100644 index 0000000..60ce424 --- /dev/null +++ b/293x_CODE/Chap08code/create_simulatefailure.sql @@ -0,0 +1,50 @@ +CREATE DATABASE SimulateDataFailure + +ALTER DATABASE SimulateDataFailure SET RECOVERY FULL +GO + + +USE SimulateDataFailure +GO +CREATE TABLE SimulateDataFailure +( + IdCol INT PRIMARY KEY, + DateCol DATETIME DEFAULT(GETDATE()) +) +GO + +INSERT SimulateDataFailure(IdCol) VALUES(1) +INSERT SimulateDataFailure(IdCol) VALUES(2) +INSERT SimulateDataFailure(IdCol) VALUES(3) +GO + + +BACKUP DATABASE SimulateDataFailure +TO DISK='C:\SimulateDataFailure.BAK' +WITH INIT +GO + + +INSERT SimulateDataFailure(IdCol) VALUES(4) +INSERT SimulateDataFailure(IdCol) VALUES(5) +INSERT SimulateDataFailure(IdCol) VALUES(6) +GO + +BACKUP LOG SimulateDataFailure +TO DISK='C:\SimulateDataFailure.BAK' +WITH NOINIT +GO + + +INSERT SimulateDataFailure(IdCol) VALUES(7) +INSERT SimulateDataFailure(IdCol) VALUES(8) +INSERT SimulateDataFailure(IdCol) VALUES(9) +GO + +BACKUP LOG SimulateDataFailure +TO DISK='C:\SimulateDataFailure.BAK' +WITH NOINIT, NO_TRUNCATE +GO + +DROP DATABASE SimulateDataFailure +GO \ No newline at end of file diff --git a/293x_CODE/Chap08code/differential_backup.sql b/293x_CODE/Chap08code/differential_backup.sql new file mode 100644 index 0000000..9457fa4 --- /dev/null +++ b/293x_CODE/Chap08code/differential_backup.sql @@ -0,0 +1,3 @@ +BACKUP DATABASE Northwind +TO DISK='C:\Program Files\Microsoft SQL Server\MSSQL\Backup\Northwind backup.bak' +WITH DIFFERENTIAL, NOINIT diff --git a/293x_CODE/Chap08code/differential_restore.sql b/293x_CODE/Chap08code/differential_restore.sql new file mode 100644 index 0000000..f1e956d --- /dev/null +++ b/293x_CODE/Chap08code/differential_restore.sql @@ -0,0 +1,18 @@ +--restores initial DB +RESTORE DATABASE Northwind FROM +DISK='C:\Program Files\Microsoft SQL Server\MSSQL\Backup\Northwind backup.bak' +WITH NORECOVERY, REPLACE, FILE=1 +GO + +--restores differential +RESTORE DATABASE Northwind FROM +DISK='C:\Program Files\Microsoft SQL Server\MSSQL\Backup\Northwind backup.bak' +WITH RECOVERY, FILE=4 +GO + +--checks the data +USE Northwind +GO +SELECT CustomerID, CompanyName, ContactName +FROM Customers +WHERE CustomerID LIKE 'TBA%' diff --git a/293x_CODE/Chap08code/restore.sql b/293x_CODE/Chap08code/restore.sql new file mode 100644 index 0000000..8a04404 --- /dev/null +++ b/293x_CODE/Chap08code/restore.sql @@ -0,0 +1,3 @@ +RESTORE DATABASE Northwind FROM +DISK='C:\Program Files\Microsoft SQL Server\MSSQL\Backup\Northwind backup.bak' +WITH NORECOVERY, REPLACE, FILE=1 diff --git a/293x_CODE/Chap08code/restore_simulatefailure.sql b/293x_CODE/Chap08code/restore_simulatefailure.sql new file mode 100644 index 0000000..dbcd527 --- /dev/null +++ b/293x_CODE/Chap08code/restore_simulatefailure.sql @@ -0,0 +1,19 @@ +RESTORE DATABASE SimulateDataFailure +FROM DISK='C:\SimulateDataFailure.BAK' +WITH FILE=1, NORECOVERY +GO + +RESTORE LOG SimulateDataFailure +FROM DISK='C:\SimulateDataFailure.BAK' +WITH FILE=2, NORECOVERY +GO + +RESTORE LOG SimulateDataFailure +FROM DISK='C:\SimulateDataFailure.BAK' +WITH FILE=3, RECOVERY +GO + +USE SimulateDataFailure +GO +SELECT * FROM SimulateDataFailure +GO \ No newline at end of file diff --git a/293x_CODE/Chap08code/restore_southwind.sql b/293x_CODE/Chap08code/restore_southwind.sql new file mode 100644 index 0000000..d69db2e --- /dev/null +++ b/293x_CODE/Chap08code/restore_southwind.sql @@ -0,0 +1,15 @@ +CREATE DATABASE Southwind +GO + +RESTORE FILELISTONLY +FROM DISK='C:\Program Files\Microsoft SQL Server\MSSQL\BACKUP\Northwind backup.bak' +GO + +RESTORE DATABASE Southwind +FROM DISK='C:\Program Files\Microsoft SQL Server\MSSQL\BACKUP\Northwind backup.bak' +WITH MOVE 'Northwind' + TO 'C:\Program Files\Microsoft SQL Server\MSSQL\data\Southwind.mdf', +MOVE 'Northwind_log' + TO 'C:\Program Files\Microsoft SQL Server\MSSQL\data\Southwind.ldf', +REPLACE +GO \ No newline at end of file diff --git a/293x_CODE/Chap08code/transaction_log_backup.sql b/293x_CODE/Chap08code/transaction_log_backup.sql new file mode 100644 index 0000000..d0963d6 --- /dev/null +++ b/293x_CODE/Chap08code/transaction_log_backup.sql @@ -0,0 +1,18 @@ +USE Northwind +GO + +INSERT dbo.Customers(CustomerID, CompanyName, + ContactName, City, Country) +VALUES('TBASB','Tony Bain & Associates', + 'Stephanie Bain','Christchurch', 'New Zealand') + +INSERT dbo.Customers(CustomerID, CompanyName, + ContactName, City, Country) +VALUES('TBAWB','Tony Bain & Associates', + 'William Bain', 'Christchurch', 'New Zealand') +GO + + +BACKUP LOG Northwind +TO DISK='C:\Program Files\Microsoft SQL Server\MSSQL\Backup\Northwind backup.bak' +WITH NOINIT diff --git a/293x_CODE/Chap08code/transaction_log_restore.sql b/293x_CODE/Chap08code/transaction_log_restore.sql new file mode 100644 index 0000000..6659dbe --- /dev/null +++ b/293x_CODE/Chap08code/transaction_log_restore.sql @@ -0,0 +1,11 @@ +RESTORE LOG Northwind FROM +DISK='C:\Program Files\Microsoft SQL Server\MSSQL\Backup\Northwind backup.bak' +WITH RECOVERY, FILE=3 +GO + + +USE Northwind +GO +SELECT CustomerID, CompanyName, ContactName +FROM Customers +WHERE CustomerID LIKE 'TBA%' diff --git a/293x_CODE/Chap10Code/ALTER.sql b/293x_CODE/Chap10Code/ALTER.sql new file mode 100644 index 0000000..6111745 --- /dev/null +++ b/293x_CODE/Chap10Code/ALTER.sql @@ -0,0 +1,26 @@ +--alter Employee table +USE Southwind +GO + +ALTER TABLE dbo.Employee + ADD StartDate DATETIME NULL +GO + + + +--alter view +ALTER VIEW dbo.vEmployee +AS +SELECT EmployeeID, EmployeeName, StartDate FROM dbo.Employee +GO + + + + +--alter sproc +ALTER PROCEDURE dbo.GetEmployees +AS +BEGIN + SELECT EmployeeID, [Group], EmployeeName, StartDate FROM dbo.Employee +END +GO diff --git a/293x_CODE/Chap10Code/ArchiveSalesTable.sql b/293x_CODE/Chap10Code/ArchiveSalesTable.sql new file mode 100644 index 0000000..cac2723 --- /dev/null +++ b/293x_CODE/Chap10Code/ArchiveSalesTable.sql @@ -0,0 +1,64 @@ +/* create the history table */ +CREATE TABLE sales_history ( +stor_id INT, +ord_num VARCHAR(15), +ord_date SMALLDATETIME, +qty INT, +payterms VARCHAR(20), +title_id VARCHAR(10) +) + +GO + +/* enclose all data modification statements in a transaction +** just in case we encounter errors +*/ + +BEGIN TRANSACTION + +/* populate history table first: */ + + INSERT sales_history ( + stor_id, + ord_num, + ord_date, + qty, + payterms, + title_id + ) + + SELECT + stor_id, + ord_num, + ord_date, + qty, + payterms, + title_id + FROM sales + WHERE + DATEDIFF(YEAR, ord_date, GETDATE()) > = 2 + +/* handle any errors: */ +IF @@ERROR <> 0 + BEGIN + RAISERROR('error while populating history table', 16, 1) + ROLLBACK TRANSACTION + RETURN + END + +/* now that we have a copy +** get rid of the old records: +*/ + +DELETE sales + WHERE DATEDIFF(YEAR, ord_date, GETDATE()) > = 2 + +IF @@ERROR <> 0 + BEGIN + RAISERROR('error while deleting old records', 16, 1) + ROLLBACK TRANSACTION + RETURN + END + +/* commit transaction if no errors: */ +COMMIT TRANSACTION diff --git a/293x_CODE/Chap10Code/CONDITIONAL.sql b/293x_CODE/Chap10Code/CONDITIONAL.sql new file mode 100644 index 0000000..170bd06 --- /dev/null +++ b/293x_CODE/Chap10Code/CONDITIONAL.sql @@ -0,0 +1,84 @@ +-- declare local variable +-- to determine weekday number: +DECLARE @day INT + +SELECT @day = DATEPART(DAY, GETDATE()) + +IF @day = 1 + BEGIN + SELECT * FROM authors WHERE state = 'ca' + END +ELSE + BEGIN + -- nested IF logic: + IF @day = 2 + BEGIN + SELECT * FROM authors WHERE state = 'tn' + END + ELSE + BEGIN + SELECT * FROM authors WHERE state = 'or' + END + END + + +-- As above, but using CASE: +-- delcare local variable +-- to determine weekday number: +DECLARE @day INT + +SELECT @day = DATEPART(DAY, GETDATE()) + +SELECT * FROM authors +WHERE + state = CASE + WHEN @day = 1 THEN 'ca' + WHEN @day = 2 THEN 'tn' + ELSE 'or' + END + + + +-- checking for authors from Texas: +IF NOT ((SELECT COUNT(*) FROM authors WHERE state = 'tx') > 0) + BEGIN + PRINT 'There are no authors from Texas' + END + +-- similar to above, using EXISTS: +IF EXISTS (SELECT * FROM authors WHERE state = 'tx') + BEGIN + PRINT 'There ARE authors from Texas' + END + + +-- Using CASE to replace results with custom data: +SELECT DISTINCT state = CASE + WHEN state = 'ca' THEN 'California' + WHEN state = 'tn' THEN 'Tennessee' + WHEN state = 'or' THEN 'Oregon' + ELSE state + END +FROM authors + + + + +-- Using CASE to customize return result based on day of the week: +SELECT greeting = + CASE WHEN DATEPART(HOUR, GETDATE()) < 12 + THEN 'Good ' + DATENAME(WEEKDAY, GETDATE()) + +' Morning!' + WHEN DATEPART(HOUR, GETDATE()) BETWEEN 12 AND 17 + THEN 'Good ' + DATENAME(WEEKDAY, GETDATE()) + +' Afternoon!' + WHEN DATEPART(HOUR, GETDATE()) BETWEEN 18 AND 22 + THEN 'Good ' + DATENAME(WEEKDAY, GETDATE()) + +' Evening!' + ELSE + 'Good ' + DATENAME(WEEKDAY, GETDATE()) + ' Night!' + END + + + + diff --git a/293x_CODE/Chap10Code/CREATE.sql b/293x_CODE/Chap10Code/CREATE.sql new file mode 100644 index 0000000..8a957ec --- /dev/null +++ b/293x_CODE/Chap10Code/CREATE.sql @@ -0,0 +1,77 @@ +USE master +GO +CREATE DATABASE Southwind +GO + +--create table +USE Southwind +GO + +CREATE TABLE dbo.Employee ( + EmployeeID INT NOT NULL IDENTITY(1, 1) PRIMARY KEY, + [Group] VARCHAR(50) NULL, + EmployeeName VARCHAR(50) NULL +) +GO + + +--create view +USE Southwind +GO + +CREATE VIEW dbo.vEmployee AS + SELECT EmployeeID, EmployeeName FROM dbo.Employee +GO + + + +--create sproc +USE Southwind +GO + + +CREATE PROCEDURE dbo.GetEmployees (@EName CHAR(1)) AS +BEGIN + SELECT EmployeeID, [Group], EmployeeName FROM dbo.Employee + WHERE EmployeeName LIKE @EName + '%' +END +GO + +EXECUTE dbo.GetEmployees 'D' +GO +--We can still get all employees with a clever tactic +EXECUTE dbo.GetEmployees '%' + + + +--create scalar UDF +USE Southwind +GO + +CREATE FUNCTION dbo.fnConvertDateToISOStd(@DateToUse DATETIME) +RETURNS CHAR(8) +AS +BEGIN + RETURN CONVERT(CHAR(8), @DateToUse, 112) +END +GO + + + +--create table UDF +USE Southwind +GO + +CREATE FUNCTION dbo.fnTest2() +RETURNS TABLE +AS + RETURN SELECT EmployeeID, [Group], EmployeeName FROM dbo.Employee +GO + + + + + + + + diff --git a/293x_CODE/Chap10Code/CURSOR.sql b/293x_CODE/Chap10Code/CURSOR.sql new file mode 100644 index 0000000..ca9af10 --- /dev/null +++ b/293x_CODE/Chap10Code/CURSOR.sql @@ -0,0 +1,29 @@ +/* turn off messages of how many rows are returned */ +SET NOCOUNT ON + +-- declare local variables for further processing: +DECLARE @last_name VARCHAR(40), + @first_name VARCHAR(40) + +--declare the cursor with a SELECT statement +DECLARE author_cursor CURSOR FOR + SELECT au_lname, au_fname FROM authors + +-- open cursor +OPEN author_cursor +-- attempt to fetch a row from a cursor +FETCH NEXT FROM author_cursor INTO @last_name, @first_name + +/* initialize a WHILE loop for successful fetches*/ +WHILE @@FETCH_STATUS = 0 +BEGIN + -- do some processing: + SELECT 'Current author is ' + @first_name + ' ' + @last_name + + -- go to the next row: + FETCH NEXT FROM author_cursor INTO @last_name, @first_name +END + +-- close and deallocate the cursor +CLOSE author_cursor +DEALLOCATE author_cursor diff --git a/293x_CODE/Chap10Code/DROP.sql b/293x_CODE/Chap10Code/DROP.sql new file mode 100644 index 0000000..1e5fdbd --- /dev/null +++ b/293x_CODE/Chap10Code/DROP.sql @@ -0,0 +1,25 @@ +--drop sproc +USE Southwind +GO + +DROP PROCEDURE dbo.GetEmployees + + + +--Multiple objects of same type can be dropped using the following syntax: +DROP PROCEDURE sp1, sp2, sp3 + + +--drop view, table, & database +--dropping does not have to be done in reverse order of creation, +--but it is recommended as this helps avoid orphaned objects. +DROP VIEW dbo.vEmployee + +DROP TABLE dbo.Employee + +--note - we must leave the context of the Southwind DB before we can drop it. +USE master +GO + +DROP DATABASE Southwind +GO diff --git a/293x_CODE/Chap10Code/ERRORS.sql b/293x_CODE/Chap10Code/ERRORS.sql new file mode 100644 index 0000000..9799dae --- /dev/null +++ b/293x_CODE/Chap10Code/ERRORS.sql @@ -0,0 +1,18 @@ +-- an example of error handling in action: +SELECT CAST('23/34/20' AS SMALLDATETIME) + +IF @@ERROR <> 0 + BEGIN + RAISERROR('An error occurred', 16, 1) + END + + +-- Logging an entry in the error log using xp_logevent: +RAISERROR('ouch', 16, 1) WITH SETERROR + +IF @@ERROR <> 0 + BEGIN + EXEC master..xp_logevent 50002, + 'An error of type warning has been encountered', + WARNING + END diff --git a/293x_CODE/Chap10Code/FUNCTIONS.sql b/293x_CODE/Chap10Code/FUNCTIONS.sql new file mode 100644 index 0000000..1a2be95 --- /dev/null +++ b/293x_CODE/Chap10Code/FUNCTIONS.sql @@ -0,0 +1,131 @@ +-- using the AVG function +USE Northwind +GO + +SELECT STR(AVG(OD.Quantity * OD.UnitPrice), 6, 2) FROM Orders O + INNER JOIN [Order Details] OD ON O.OrderID = OD.OrderID +WHERE DATEPART(YY, O.OrderDate) = '1997' +GO + + +-- Creating globally unique values +CREATE TABLE dbo.VIP( +VIPID UNIQUEIDENTIFIER NOT NULL CONSTRAINT DF_VIP_VIPID DEFAULT(NEWID()), +VIPName VARCHAR(50) +) +GO + +INSERT INTO dbo.VIP(VIPName) +SELECT 'Melinda' UNION ALL +SELECT 'Letha' UNION ALL +SELECT 'Autrey' UNION ALL +SELECT 'Scott' UNION ALL +SELECT 'Craig' UNION ALL +SELECT 'Shabbir' +GO + + + +-- a scalar UDF +USE Northwind +GO + +CREATE FUNCTION dbo.fnConvertToJulianDate( + @inDate AS DATETIME +) +RETURNS VARCHAR(7) +AS +BEGIN + RETURN CAST(DATEPART(YY, @inDate) AS CHAR(4)) + + RIGHT('00' + CAST(DATEPART(DY, @inDate) AS VARCHAR(3)), 3) +END +GO + + +-- using the scalar UDF +SELECT TOP 5 + O.OrderID, O.CustomerID, + dbo.fnConvertToJulianDate(O.OrderDate) AS OrderDate, + dbo.fnConvertToJulianDate(O.RequiredDate) AS RequiredDate, + dbo.fnConvertToJulianDate(O.ShippedDate) AS ShippedDate, + STR(SUM(OD.UnitPrice * OD.Quantity), 8, 2) AS Amount +FROM Orders O + INNER JOIN [Order Details] OD ON O.OrderID = OD.OrderID +GROUP BY O.ORDERID, O.CustomerID, O.OrderDate, O.RequiredDate, + O.ShippedDate +ORDER BY Amount DESC + + + +-- an in-line UDF +Use Northwind +GO + +CREATE FUNCTION dbo.fnGetCustInfoByAmount ( + @StartDate DATETIME, + @EndDate DATETIME +) +RETURNS TABLE +AS +RETURN SELECT + O.OrderID, O.CustomerID, CONVERT(VARCHAR(12), O.OrderDate, + 101) +AS + OrderDate, + CONVERT(VARCHAR(12), O.RequiredDate, 101) AS RequiredDate, + CONVERT(VARCHAR(12), O.ShippedDate, 101) AS ShippedDate, + STR(SUM(OD.UnitPrice * OD.Quantity), 8, 2) AS Amount +FROM Orders O + INNER JOIN [Order Details] OD ON O.OrderID = OD.OrderID +WHERE OrderDate BETWEEN @StartDate AND @EndDate +GROUP BY O.ORDERID, O.CustomerID, O.OrderDate, O.RequiredDate, + O.ShippedDate +GO + +-- the associated SELECT query +SELECT * FROM dbo.fnGetCustInfoByAmount ('9/30/1997', + '10/02/1997') +GO + + + +-- a table UDF +CREATE FUNCTION dbo.fnGetCustInfoByAmount2 ( + @StartDate DATETIME, + @EndDate DATETIME +) +RETURNS @JustForShow TABLE ( + OrderID INT NOT NULL, + CustomerID NCHAR(5) NULL, + OrderDate VARCHAR(12) NULL, + RequiredDate VARCHAR(12) NULL, + ShippedDate VARCHAR(12) NULL, + Amount VARCHAR(8) NULL) +AS + BEGIN + INSERT INTO @JustForShow ( + OrderID, CustomerID, + OrderDate, RequiredDate, ShippedDate, Amount) + SELECT O.OrderID, O.CustomerID, + CONVERT(VARCHAR(12), O.OrderDate, 101) AS OrderDate, + CONVERT(VARCHAR(12), O.RequiredDate, 101) + AS RequiredDate, + CONVERT(VARCHAR(12), O.ShippedDate, 101) + AS ShippedDate, + STR(SUM(OD.UnitPrice * OD.Quantity), 8, 2) AS Amount + FROM Orders O + INNER JOIN [Order Details] OD ON O.OrderID = OD.OrderID + WHERE OrderDate BETWEEN @StartDate AND @EndDate + GROUP BY O.ORDERID, O.CustomerID, O.OrderDate, + O.RequiredDate, O.ShippedDate + + RETURN + END +GO + +--the associated SELECT query +SELECT * FROM dbo.fnGetCustInfoByAmount2 ('9/30/1997', + '10/02/1997') + +GO + diff --git a/293x_CODE/Chap10Code/INSERT.sql b/293x_CODE/Chap10Code/INSERT.sql new file mode 100644 index 0000000..c280f63 --- /dev/null +++ b/293x_CODE/Chap10Code/INSERT.sql @@ -0,0 +1,57 @@ +--insert data from other tables +INSERT sales ( +stor_id, +ord_num, +ord_date, +qty, +payterms, +title_id) + +SELECT stores.stor_id, + 'neworder', + GETDATE(), + 55, + 'net 439', + titles.title_id +FROM stores, titles + WHERE stores.stor_name = 'news & brews' + AND + titles.title = 'you can combat computer stress!' + + + + + + +--insert using a sproc: here is the sproc +CREATE PROCEDURE dbo.author_name_city(@state CHAR(2)) + +AS + +SELECT au_lname, au_fname, city FROM authors +WHERE state = @state + + +--and here is the INSERT statement +CREATE TABLE #author ( +au_lname VARCHAR(50), +au_fname VARCHAR(50), +city VARCHAR(50) +) + +GO + +INSERT #author EXEC author_name_city @state = 'ca' + + +--inserting dynamic SQL +DECLARE @sql VARCHAR(600) +SELECT @sql = 'DECLARE @state CHAR(2)' +SELECT @sql = @sql + 'SET @state = ''ca''' +SELECT @sql = @sql + 'SELECT au_lname, au_fname FROM authors +WHERE state = @state ' + +INSERT #author (au_lname, au_fname) + +EXEC (@sql) + diff --git a/293x_CODE/Chap10Code/LOOPS.sql b/293x_CODE/Chap10Code/LOOPS.sql new file mode 100644 index 0000000..243794a --- /dev/null +++ b/293x_CODE/Chap10Code/LOOPS.sql @@ -0,0 +1,118 @@ +--Running a WHILE loop +SET NOCOUNT ON +DECLARE @counter TINYINT + +SET @counter = 0 + +WHILE @counter < 10 + BEGIN + SELECT TOP 1 au_lname FROM authors + WHERE au_id LIKE '%' + CAST(@counter AS VARCHAR) + '%' + SET @counter = @counter + 1 + END + + +-- same as above, but with a BREAK +SET NOCOUNT ON +DECLARE @counter TINYINT + +SET @counter = 0 + +WHILE @counter < 10 + BEGIN + SELECT TOP 1 au_lname FROM authors + WHERE au_id LIKE '%' + CAST(@counter AS VARCHAR) + '%' + + SET @counter = @counter + 1 + + IF @counter > 2 + BEGIN + BREAK + END + END + + + +--Nested WHILE loop +SET NOCOUNT ON +DECLARE @counter TINYINT + +SET @counter = 0 + +WHILE @counter < 10 + BEGIN + SELECT TOP 1 au_lname FROM authors + WHERE au_id LIKE '%' + CAST(@counter AS VARCHAR) + '%' + SET @counter = @counter + 1 + + WHILE @counter = 2 + BEGIN + PRINT 'now breaking!' + BREAK + END + + IF @counter = 2 + BEGIN + PRINT 'now continuing!' + CONTINUE + END + END + + + +-- Using a GOTO +DECLARE @counter TINYINT + +SET @counter = 0 + +WHILE @counter < 10 + BEGIN + SELECT TOP 1 au_lname FROM authors + WHERE au_id LIKE '%' + CAST(@counter AS VARCHAR) + '%' + SET @counter = @counter + 1 + WHILE @counter > 2 + BEGIN + BREAK + END + + IF @counter > 1 + BEGIN + GOTO my_label + END + END + +my_label: + +SELECT 'The processing continues here!' + + + + +-- Using GOTO to centralize error handling: +BEGIN TRANSACTION + +UPDATE authors SET au_lname = 'Ringer' +WHERE au_lname = 'Whiter' + +IF @@ERROR <> 0 + BEGIN + GOTO error_handler + END + +UPDATE titles SET title = 'new title' +WHERE title = 'old title' + +IF @@ERROR <> 0 + BEGIN + GOTO error_handler + END + +COMMIT TRANSACTION + +error_handler: +IF @@ERROR <>0 + BEGIN + RAISERROR('An error occurred, rolling back', 16, 1) + ROLLBACK TRANSACTION + END + diff --git a/293x_CODE/Chap10Code/SELECT.sql b/293x_CODE/Chap10Code/SELECT.sql new file mode 100644 index 0000000..573ed0b --- /dev/null +++ b/293x_CODE/Chap10Code/SELECT.sql @@ -0,0 +1,47 @@ +--using JOIN +SELECT authors.au_lname, authors.au_fname, titles.title, +titles.price +FROM dbo.authors + INNER JOIN dbo.titleauthor ON authors.au_id = +titleauthor.au_id + INNER JOIN dbo.titles ON titleauthor.title_id = +titles.title_id +ORDER BY authors.au_lname, authors.au_fname + + + +--as above but using aliases +SELECT a.au_lname, a.au_fname, t.title, t.price +FROM dbo.authors a + INNER JOIN dbo.titleauthor ta on a.au_id = ta.au_id + INNER JOIN dbo.titles t on ta.title_id = t.title_id +ORDER BY a.au_lname, a.au_fname + + + +--GROUP BY +SELECT a.au_lname, a.au_fname, SUM(t.price) AS TotalPrice +FROM dbo.authors a + INNER JOIN dbo.titleauthor ta on a.au_id = ta.au_id + INNER JOIN dbo.titles t on ta.title_id = t.title_id +GROUP BY a.au_lname, a.au_fname +ORDER BY a.au_lname, a.au_fname + + + +--Ordering authors by title price +SELECT a.au_lname, a.au_fname, t.title, t.price +FROM dbo.authors a + INNER JOIN dbo.titleauthor ta on a.au_id = ta.au_id + INNER JOIN dbo.titles t on ta.title_id = t.title_id +ORDER BY t.price DESC + + +--As above but using TOP statement +SELECT TOP 10 a.au_lname, a.au_fname, t.title, t.price +FROM dbo.authors a + INNER JOIN dbo.titleauthor ta on a.au_id = ta.au_id + INNER JOIN dbo.titles t on ta.title_id = t.title_id +ORDER BY t.price DESC + + diff --git a/293x_CODE/Chap10Code/SQLXML.sql b/293x_CODE/Chap10Code/SQLXML.sql new file mode 100644 index 0000000..b946410 --- /dev/null +++ b/293x_CODE/Chap10Code/SQLXML.sql @@ -0,0 +1,124 @@ +--Using the FOR AUTO XML mode: +SELECT TOP 2 * FROM customers FOR XML AUTO, ELEMENTS + + +--AUTO and a multi-table query: +SELECT TOP 2 + Orders.OrderDate, + Orders.ShipCity, + Customers.CompanyName, + Customers.Country +FROM orders INNER JOIN customers ON + orders.customerid = customers.customerid +FOR XML AUTO + + + +--Changing the nesting in a multi-table query: +SELECT TOP 2 + Customers.CompanyName, + Customers.Country, + Orders.OrderDate, + Orders.ShipCity +FROM Orders INNER JOIN Customers ON + orders.customerid = customers.customerid +FOR XML AUTO + + + + +--Using FOR XML RAW: +SELECT TOP 2 + Customers.CompanyName, + Customers.Country, + Orders.OrderDate, + Orders.ShipCity +FROM Orders INNER JOIN Customers ON + orders.customerid = customers.customerid +FOR XML RAW + + + +--Using FOR XML EXPLICIT: +USE pubs + +SELECT 1 AS TAG, NULL AS PARENT, +authors.au_fname AS [author!1!au_fname], +authors.au_lname AS [author!1!au_lname], +NULL AS [titleauthor!2!royaltyper], +NULL AS [titles!3!title] +FROM +authors WHERE au_lname = 'green' + +UNION ALL + +SELECT 2 AS TAG, 1 AS PARENT, +au_fname, +au_lname, +royaltyper, +NULL +FROM authors INNER JOIN titleauthor ON +authors.au_id= titleauthor.au_id +WHERE au_lname ='green' + +UNION ALL + +SELECT 3 AS TAG, 2 AS PARENT, +au_fname, +au_lname, +royaltyper, +title +FROM authors INNER JOIN titleauthor ON authors.au_id = + titleauthor.au_id +INNER JOIN titles ON titles.title_id = titleauthor.title_id +WHERE au_lname ='green' +ORDER BY [author!1!au_fname], [author!1!au_lname], + [titleauthor!2!royaltyper] +FOR XML EXPLICIT + + + + +--Using OPENXML: +USE PUBS +DECLARE @xml_text VARCHAR(4000), @i INT + +SELECT @xml_text = ' + + + +' + +EXEC sp_xml_preparedocument @i OUTPUT, @xml_text + +SELECT * FROM + OPENXML(@i, '/root/authors') +WITH ( + au_id VARCHAR(11), + au_lname VARCHAR(20), + au_fname VARCHAR(30), + phone VARCHAR(12), + address VARCHAR(50), + city VARCHAR(20), + state CHAR(2), + zip CHAR(5), + contract BIT) + +EXEC sp_xml_removedocument @i + diff --git a/293x_CODE/Chap10Code/TEMP_TABLES.sql b/293x_CODE/Chap10Code/TEMP_TABLES.sql new file mode 100644 index 0000000..58398eb --- /dev/null +++ b/293x_CODE/Chap10Code/TEMP_TABLES.sql @@ -0,0 +1,23 @@ +CREATE TABLE #temp_table ( +last_name VARCHAR(40), +first_name VARCHAR(40) +) + +DECLARE @table_variable TABLE ( +last_name VARCHAR(40), +first_name VARCHAR(40) +) + +INSERT #temp_table + SELECT TOP 3 au_lname, au_fname FROM authors + ORDER BY au_lname + +INSERT @table_variable + SELECT TOP 3 au_lname, au_fname FROM authors + ORDER BY au_lname + +SELECT * FROM #temp_table +SELECT * FROM @table_variable + +--must explicitly drop the temp table: +DROP TABLE #temp_table diff --git a/293x_CODE/Chap10Code/TRANSACTIONS.sql b/293x_CODE/Chap10Code/TRANSACTIONS.sql new file mode 100644 index 0000000..92d3d75 --- /dev/null +++ b/293x_CODE/Chap10Code/TRANSACTIONS.sql @@ -0,0 +1,22 @@ + +-- Example showing a transaction in action: +Use Northwind + +BEGIN TRANSACTION + +SELECT UnitPrice, * FROM Products WHERE ProductID = 3 + +UPDATE Products SET UnitPrice = UnitPrice * 1.05 WHERE ProductID = 3 + +SELECT UnitPrice, * FROM Products WHERE ProductID = 3 + +ROLLBACK TRANSACTION + +SELECT UnitPrice, * FROM Products WHERE ProductID = 3 + + + + + + + diff --git a/293x_CODE/Chap10Code/TRIGGERS.sql b/293x_CODE/Chap10Code/TRIGGERS.sql new file mode 100644 index 0000000..6ee71f1 --- /dev/null +++ b/293x_CODE/Chap10Code/TRIGGERS.sql @@ -0,0 +1,43 @@ +--create an audit table to track when some territories are inserted or deleted: +CREATE TABLE triggertest( +TestID INT NOT NULL IDENTITY(1, 1) Primary Key, +TestDate DATETIME NOT NULL DEFAULT(GETDATE()), +TestData VARCHAR(256) NOT NULL +) +GO + +--then create the INSERT trigger: +CREATE TRIGGER trInsTerritories ON dbo.Territories +FOR INSERT +AS +INSERT INTO dbo.triggertest(TestData) +SELECT 'New Territory added: ' + TerritoryDescription +FROM INSERTED +GO + +--and then the DELETE trigger: +CREATE TRIGGER trDelTerritories ON dbo.Territories +FOR DELETE +AS +INSERT INTO dbo.triggertest(TestData) +SELECT 'New Territory removed: ' + TerritoryDescription +FROM DELETED +GO + +--now, we'll INSERT a few territories: +INSERT INTO Territories(TerritoryID, TerritoryDescription, + RegionID) +VALUES(11111, 'TestTerritory1', 4) +INSERT INTO Territories(TerritoryID, TerritoryDescription, + RegionID) +VALUES(22222, 'TestTerritory2', 4) +GO + +--and then DELETE them: +DELETE FROM Territories +WHERE TerritoryDescription LIKE 'TestTerritory%' +GO + +--now, let's look at our triggertest table: +SELECT * FROM triggertest +GO \ No newline at end of file diff --git a/293x_CODE/Chap10Code/Thumbs.db b/293x_CODE/Chap10Code/Thumbs.db new file mode 100644 index 0000000..559140b Binary files /dev/null and b/293x_CODE/Chap10Code/Thumbs.db differ diff --git a/293x_CODE/Chap10Code/UPDATE_CASE.sql b/293x_CODE/Chap10Code/UPDATE_CASE.sql new file mode 100644 index 0000000..9bb5fc4 --- /dev/null +++ b/293x_CODE/Chap10Code/UPDATE_CASE.sql @@ -0,0 +1,39 @@ +--RUN this query: +SELECT sales.* +FROM sales INNER JOIN titles ON sales.title_id = + titles.title_id +WHERE titles.type = 'business' + + + +--Then run this update, and try the query above again: +UPDATE sales SET payterms = 'COD' +FROM sales INNER JOIN titles ON sales.title_id = + titles.title_id +WHERE titles.type = 'business' + + + + +--Next, update payterms column using the CASE statement: +UPDATE sales +SET +payterms = CASE WHEN titles.type = 'business' THEN 'cod' + WHEN titles.type = 'mod_cook' THEN 'net 30' + WHEN titles.type = 'popular_comp' THEN 'net 40' + WHEN titles.type = 'trad_cook' THEN 'net 35' + WHEN titles.type = 'psychology' THEN 'net 0' + ELSE 'CASH' + END +FROM sales + INNER JOIN titles ON sales.title_id = titles.title_id + + +--This UPDATE adds a running total of titles sold so far column +ALTER TABLE sales ADD sold_so_far INT NULL +GO + +UPDATE sales +SET sold_so_far = ( + SELECT COUNT(*) FROM sales s2 WHERE s2.title_id = + sales.title_id) diff --git a/293x_CODE/Chap11Code/PopulateTables.sql b/293x_CODE/Chap11Code/PopulateTables.sql new file mode 100644 index 0000000..81adede --- /dev/null +++ b/293x_CODE/Chap11Code/PopulateTables.sql @@ -0,0 +1,371 @@ +SET NOCOUNT ON + +INSERT customer (customer_name) +SELECT 'john doe' + +INSERT customer (customer_name) +SELECT 'jane doe' + +INSERT customer (customer_name) +SELECT 'bubba smith' + +INSERT customer (customer_name) +SELECT 'john smith' + +INSERT customer (customer_name) +SELECT 'tabiry karesi' + +INSERT store (store_name_and_address) +SELECT 'store 1 on Wilson street' + +INSERT store (store_name_and_address) +SELECT 'store 2 on Market street' + +INSERT store (store_name_and_address) +SELECT 'store 3 on East Main street' + +INSERT store (store_name_and_address) +SELECT 'store 4 on Belmont Avenue' + +INSERT zip_code +SELECT '37013' + +INSERT zip_code +SELECT '42101' + +INSERT zip_code +SELECT '53516' + +INSERT zip_code +SELECT '25135' + +INSERT product +SELECT 'chocolate' + +INSERT product +SELECT 'cranberry sause' + +INSERT product +SELECT 'turkey' + +INSERT product +SELECT 'pumkin pie' + +INSERT age_range +SELECT '20 - 25' + +INSERT age_range +SELECT '26 - 35' + +INSERT age_range +SELECT '36 - 45' + +INSERT age_range +SELECT '46 - 55' + + +DECLARE @time SMALLDATETIME + +SELECT @time = '1/1/2002' + +WHILE @time < = '1/1/2003' +BEGIN + +INSERT time (date_and_time) +SELECT @time + +SELECT @time = DATEADD(DAY, 1, @time) + +END + +DECLARE + @customer_key INT, + @age_range_key INT, + @product_key INT, + @zip_code_key INT, + @store_key INT, + @time_key INT, + @sales_amount INT + + SELECT @customer_key= 1, + @age_range_key = 1, + @zip_code_key = 1, + @sales_amount = 2 + + + DECLARE store_cursor CURSOR FOR + SELECT TOP 2 store_key FROM store + + + OPEN store_cursor + FETCH NEXT FROM store_cursor INTO @store_key + + WHILE @@FETCH_STATUS = 0 + + BEGIN + + DECLARE product_cursor CURSOR + FOR SELECT product_key FROM product + + OPEN product_cursor + FETCH NEXT FROM product_cursor INTO @product_key + + WHILE @@FETCH_STATUS = 0 + BEGIN + + + DECLARE time_cursor CURSOR FOR + SELECT TOP 50 time_key FROM time ORDER BY time_key DESC + OPEN time_cursor + + FETCH NEXT FROM time_cursor INTO @time_key + + WHILE @@FETCH_STATUS = 0 + + BEGIN + + INSERT sales_fact ( + customer_key, + age_range_key, + product_key, + zip_code_key, + store_key, + time_key, + sales_amount) + + SELECT + @customer_key, + @age_range_key, + @product_key, + @zip_code_key, + @store_key, + @time_key, + @sales_amount +SELECT @sales_amount = @sales_amount + 1 + FETCH NEXT FROM time_cursor INTO @time_key + END + CLOSE time_cursor + DEALLOCATE time_cursor + + FETCH NEXT FROM product_cursor INTO @product_key + END + CLOSE product_cursor + DEALLOCATE product_cursor + + FETCH NEXT FROM store_cursor INTO @store_key + END + CLOSE store_cursor + DEALLOCATE store_cursor + + + SELECT @customer_key= 2, + @age_range_key = 2, + @zip_code_key = 2, + @sales_amount = 25 + + + DECLARE store_cursor CURSOR FOR + SELECT TOP 2 store_key FROM store ORDER BY store_key DESC + + + OPEN store_cursor + FETCH NEXT FROM store_cursor INTO @store_key + + WHILE @@FETCH_STATUS = 0 + + BEGIN + + DECLARE product_cursor CURSOR + FOR SELECT product_key FROM product + + OPEN product_cursor + FETCH NEXT FROM product_cursor INTO @product_key + + WHILE @@FETCH_STATUS = 0 + BEGIN + + + DECLARE time_cursor CURSOR FOR + SELECT TOP 50 time_key FROM time ORDER BY time_key DESC + OPEN time_cursor + + FETCH NEXT FROM time_cursor INTO @time_key + + WHILE @@FETCH_STATUS = 0 + + BEGIN + + INSERT sales_fact ( + customer_key, + age_range_key, + product_key, + zip_code_key, + store_key, + time_key, + sales_amount) + + SELECT + @customer_key, + @age_range_key, + @product_key, + @zip_code_key, + @store_key, + @time_key, + @sales_amount +SELECT @sales_amount = @sales_amount + 1 + FETCH NEXT FROM time_cursor INTO @time_key + END + CLOSE time_cursor + DEALLOCATE time_cursor + + FETCH NEXT FROM product_cursor INTO @product_key + END + CLOSE product_cursor + DEALLOCATE product_cursor + + FETCH NEXT FROM store_cursor INTO @store_key + END + CLOSE store_cursor + DEALLOCATE store_cursor + + + SELECT @customer_key= 3, + @age_range_key = 3, + @zip_code_key = 3, + @sales_amount = 15 + + + DECLARE store_cursor CURSOR FOR + SELECT TOP 1 store_key FROM store + + + OPEN store_cursor + FETCH NEXT FROM store_cursor INTO @store_key + + WHILE @@FETCH_STATUS = 0 + + BEGIN + + DECLARE product_cursor CURSOR + FOR SELECT product_key FROM product + + OPEN product_cursor + FETCH NEXT FROM product_cursor INTO @product_key + + WHILE @@FETCH_STATUS = 0 + BEGIN + + + DECLARE time_cursor CURSOR FOR + SELECT TOP 50 time_key FROM time ORDER BY time_key DESC + OPEN time_cursor + + FETCH NEXT FROM time_cursor INTO @time_key + + WHILE @@FETCH_STATUS = 0 + + BEGIN + + INSERT sales_fact ( + customer_key, + age_range_key, + product_key, + zip_code_key, + store_key, + time_key, + sales_amount) + + SELECT + @customer_key, + @age_range_key, + @product_key, + @zip_code_key, + @store_key, + @time_key, + @sales_amount +SELECT @sales_amount = @sales_amount + 1 + FETCH NEXT FROM time_cursor INTO @time_key + END + CLOSE time_cursor + DEALLOCATE time_cursor + + FETCH NEXT FROM product_cursor INTO @product_key + END + CLOSE product_cursor + DEALLOCATE product_cursor + + FETCH NEXT FROM store_cursor INTO @store_key + END + CLOSE store_cursor + DEALLOCATE store_cursor + + + SELECT @customer_key= 4, + @age_range_key = 4, + @zip_code_key = 4, + @sales_amount = 5 + + + DECLARE store_cursor CURSOR FOR + SELECT store_key FROM store + + + OPEN store_cursor + FETCH NEXT FROM store_cursor INTO @store_key + + WHILE @@FETCH_STATUS = 0 + + BEGIN + + DECLARE product_cursor CURSOR + FOR SELECT product_key FROM product + + OPEN product_cursor + FETCH NEXT FROM product_cursor INTO @product_key + + WHILE @@FETCH_STATUS = 0 + BEGIN + + + DECLARE time_cursor CURSOR FOR + SELECT TOP 50 time_key FROM time ORDER BY time_key DESC + OPEN time_cursor + + FETCH NEXT FROM time_cursor INTO @time_key + + WHILE @@FETCH_STATUS = 0 + + BEGIN + + INSERT sales_fact ( + customer_key, + age_range_key, + product_key, + zip_code_key, + store_key, + time_key, + sales_amount) + + SELECT + @customer_key, + @age_range_key, + @product_key, + @zip_code_key, + @store_key, + @time_key, + @sales_amount +SELECT @sales_amount = @sales_amount + 1 + FETCH NEXT FROM time_cursor INTO @time_key + END + CLOSE time_cursor + DEALLOCATE time_cursor + + FETCH NEXT FROM product_cursor INTO @product_key + END + CLOSE product_cursor + DEALLOCATE product_cursor + + FETCH NEXT FROM store_cursor INTO @store_key + END + CLOSE store_cursor + DEALLOCATE store_cursor diff --git a/293x_CODE/Chap11Code/createTablesAndConstraints.sql b/293x_CODE/Chap11Code/createTablesAndConstraints.sql new file mode 100644 index 0000000..6d2d726 --- /dev/null +++ b/293x_CODE/Chap11Code/createTablesAndConstraints.sql @@ -0,0 +1,192 @@ +if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FK_sales_fact_age_range]') and OBJECTPROPERTY(id, N'IsForeignKey') = 1) +ALTER TABLE [dbo].[sales_fact] DROP CONSTRAINT FK_sales_fact_age_range +GO + +if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FK_sales_fact_customer]') and OBJECTPROPERTY(id, N'IsForeignKey') = 1) +ALTER TABLE [dbo].[sales_fact] DROP CONSTRAINT FK_sales_fact_customer +GO + +if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FK_sales_fact_product]') and OBJECTPROPERTY(id, N'IsForeignKey') = 1) +ALTER TABLE [dbo].[sales_fact] DROP CONSTRAINT FK_sales_fact_product +GO + +if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FK_sales_fact_store]') and OBJECTPROPERTY(id, N'IsForeignKey') = 1) +ALTER TABLE [dbo].[sales_fact] DROP CONSTRAINT FK_sales_fact_store +GO + +if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FK_sales_fact_time]') and OBJECTPROPERTY(id, N'IsForeignKey') = 1) +ALTER TABLE [dbo].[sales_fact] DROP CONSTRAINT FK_sales_fact_time +GO + +if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FK_sales_fact_zip_code]') and OBJECTPROPERTY(id, N'IsForeignKey') = 1) +ALTER TABLE [dbo].[sales_fact] DROP CONSTRAINT FK_sales_fact_zip_code +GO + +if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[age_range]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) +drop table [dbo].[age_range] +GO + +if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[customer]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) +drop table [dbo].[customer] +GO + +if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[product]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) +drop table [dbo].[product] +GO + +if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sales_fact]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) +drop table [dbo].[sales_fact] +GO + +if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[store]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) +drop table [dbo].[store] +GO + +if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[time]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) +drop table [dbo].[time] +GO + +if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[zip_code]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) +drop table [dbo].[zip_code] +GO + +CREATE TABLE [dbo].[age_range] ( + [age_range_key] [int] IDENTITY (1, 1) NOT NULL , + [age_range] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL +) ON [PRIMARY] +GO + +CREATE TABLE [dbo].[customer] ( + [customer_key] [int] IDENTITY (1, 1) NOT NULL , + [customer_name] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL +) ON [PRIMARY] +GO + +CREATE TABLE [dbo].[product] ( + [product_key] [int] IDENTITY (1, 1) NOT NULL , + [product_description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL +) ON [PRIMARY] +GO + +CREATE TABLE [dbo].[sales_fact] ( + [customer_key] [int] NOT NULL , + [age_range_key] [int] NOT NULL , + [product_key] [int] NOT NULL , + [zip_code_key] [int] NOT NULL , + [store_key] [int] NOT NULL , + [time_key] [int] NOT NULL , + [sales_amount] [smallmoney] NULL +) ON [PRIMARY] +GO + +CREATE TABLE [dbo].[store] ( + [store_key] [int] IDENTITY (1, 1) NOT NULL , + [store_name_and_address] [varchar] (75) COLLATE SQL_Latin1_General_CP1_CI_AS NULL +) ON [PRIMARY] +GO + +CREATE TABLE [dbo].[time] ( + [time_key] [int] IDENTITY (1, 1) NOT NULL , + [date_and_time] [smalldatetime] NULL +) ON [PRIMARY] +GO + +CREATE TABLE [dbo].[zip_code] ( + [zip_code_key] [int] IDENTITY (1, 1) NOT NULL , + [zip_code] [varchar] (15) COLLATE SQL_Latin1_General_CP1_CI_AS NULL +) ON [PRIMARY] +GO + +ALTER TABLE [dbo].[age_range] WITH NOCHECK ADD + CONSTRAINT [PK_age_range] PRIMARY KEY CLUSTERED + ( + [age_range_key] + ) ON [PRIMARY] +GO + +ALTER TABLE [dbo].[customer] WITH NOCHECK ADD + CONSTRAINT [PK_customer1] PRIMARY KEY CLUSTERED + ( + [customer_key] + ) ON [PRIMARY] +GO + +ALTER TABLE [dbo].[product] WITH NOCHECK ADD + CONSTRAINT [PK_product] PRIMARY KEY CLUSTERED + ( + [product_key] + ) ON [PRIMARY] +GO + +ALTER TABLE [dbo].[sales_fact] WITH NOCHECK ADD + CONSTRAINT [PK_sales_fact] PRIMARY KEY CLUSTERED + ( + [customer_key], + [age_range_key], + [product_key], + [zip_code_key], + [store_key], + [time_key] + ) ON [PRIMARY] +GO + +ALTER TABLE [dbo].[store] WITH NOCHECK ADD + CONSTRAINT [PK_store] PRIMARY KEY CLUSTERED + ( + [store_key] + ) ON [PRIMARY] +GO + +ALTER TABLE [dbo].[time] WITH NOCHECK ADD + CONSTRAINT [PK_time] PRIMARY KEY CLUSTERED + ( + [time_key] + ) ON [PRIMARY] +GO + +ALTER TABLE [dbo].[zip_code] WITH NOCHECK ADD + CONSTRAINT [PK_demographic] PRIMARY KEY CLUSTERED + ( + [zip_code_key] + ) ON [PRIMARY] +GO + +ALTER TABLE [dbo].[sales_fact] ADD + CONSTRAINT [FK_sales_fact_age_range] FOREIGN KEY + ( + [age_range_key] + ) REFERENCES [dbo].[age_range] ( + [age_range_key] + ), + CONSTRAINT [FK_sales_fact_customer] FOREIGN KEY + ( + [customer_key] + ) REFERENCES [dbo].[customer] ( + [customer_key] + ), + CONSTRAINT [FK_sales_fact_product] FOREIGN KEY + ( + [product_key] + ) REFERENCES [dbo].[product] ( + [product_key] + ), + CONSTRAINT [FK_sales_fact_store] FOREIGN KEY + ( + [store_key] + ) REFERENCES [dbo].[store] ( + [store_key] + ), + CONSTRAINT [FK_sales_fact_time] FOREIGN KEY + ( + [time_key] + ) REFERENCES [dbo].[time] ( + [time_key] + ), + CONSTRAINT [FK_sales_fact_zip_code] FOREIGN KEY + ( + [zip_code_key] + ) REFERENCES [dbo].[zip_code] ( + [zip_code_key] + ) +GO + diff --git a/293x_CODE/Chap12code/MergeNameFields.vbs b/293x_CODE/Chap12code/MergeNameFields.vbs new file mode 100644 index 0000000..7597b8f --- /dev/null +++ b/293x_CODE/Chap12code/MergeNameFields.vbs @@ -0,0 +1,20 @@ +'******************************************** +' Visual Basic Transformation Script +'******************************************** + +' Copy each source column to the destination column +Function Main() + if ISNULL(DTSSource("minit")) then + DTSDestination("FullName") = DTSSource("fname") _ + & " " & DTSSource("lname") + elseif Len(trim(DTSSource("minit"))) = 0 then + DTSDestination("FullName") = DTSSource("fname") _ + & " " & DTSSource("lname") + else + DTSDestination("FullName") = DTSSource("fname") _ + & " " & DTSSource("minit") _ + & ". " & DTSSource("lname") + end if + Main = DTSTransformStat_OK +End Function + diff --git a/293x_CODE/Chap12code/create_employee_table.sql b/293x_CODE/Chap12code/create_employee_table.sql new file mode 100644 index 0000000..ca2928d --- /dev/null +++ b/293x_CODE/Chap12code/create_employee_table.sql @@ -0,0 +1,8 @@ +CREATE TABLE [employee] ( +[emp_id] char (9) NOT NULL +PRIMARY KEY, +[FullName] varchar (60) NOT NULL, +[job_id] smallint NOT NULL, +[job_lvl] tinyint NULL, +[pub_id] char (4) NOT NULL, +[hire_date] datetime NOT NULL ) \ No newline at end of file diff --git a/9781590592939.jpg b/9781590592939.jpg new file mode 100644 index 0000000..b21c287 Binary files /dev/null and b/9781590592939.jpg differ diff --git a/LICENSE.txt b/LICENSE.txt new file mode 100644 index 0000000..c99cda6 --- /dev/null +++ b/LICENSE.txt @@ -0,0 +1,27 @@ +Freeware License, some rights reserved + +Copyright (c) 2004 Baya Pavliashvili, Michael Benkovich, Tony Bain, Brian Freeman, and Joseph Sack + +Permission is hereby granted, free of charge, to anyone obtaining a copy +of this software and associated documentation files (the "Software"), +to work with the Software within the limits of freeware distribution and fair use. +This includes the rights to use, copy, and modify the Software for personal use. +Users are also allowed and encouraged to submit corrections and modifications +to the Software for the benefit of other users. + +It is not allowed to reuse, modify, or redistribute the Software for +commercial use in any way, or for a user’s educational materials such as books +or blog articles without prior permission from the copyright holder. + +The above copyright notice and this permission notice need to be included +in all copies or substantial portions of the software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS OR APRESS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + diff --git a/README.md b/README.md new file mode 100644 index 0000000..df445ed --- /dev/null +++ b/README.md @@ -0,0 +1,15 @@ +#Apress Source Code + +This repository accompanies [*Beginning SQL Server 2000 DBA*](http://www.apress.com/9781590592939) by Baya Pavliashvili, Michael Benkovich, Tony Bain, Brian Freeman, and Joseph Sack (Apress, 2004). + +![Cover image](9781590592939.jpg) + +Download the files as a zip using the green button, or clone the repository to your machine using Git. + +##Releases + +Release v1.0 corresponds to the code in the published book, without corrections or updates. + +##Contributions + +See the file Contributing.md for more information on how you can contribute to this repository. diff --git a/contributing.md b/contributing.md new file mode 100644 index 0000000..f6005ad --- /dev/null +++ b/contributing.md @@ -0,0 +1,14 @@ +# Contributing to Apress Source Code + +Copyright for Apress source code belongs to the author(s). However, under fair use you are encouraged to fork and contribute minor corrections and updates for the benefit of the author(s) and other readers. + +## How to Contribute + +1. Make sure you have a GitHub account. +2. Fork the repository for the relevant book. +3. Create a new branch on which to make your change, e.g. +`git checkout -b my_code_contribution` +4. Commit your change. Include a commit message describing the correction. Please note that if your commit message is not clear, the correction will not be accepted. +5. Submit a pull request. + +Thank you for your contribution! \ No newline at end of file