Computer
Microsoft Sql Server
search
Microsoft Sql Server
, MS-SQL
See Also
Microsoft Windows Server
Microsoft Windows Run Command
Microsoft Internet Information Services
Windows Powershell
Microsoft Windows
Microsoft Asp.Net
Microsoft Sql Server
Technique
Select
Select
Select isnull( title, firstname) + ' ' + lastName as customerName from databaseTable
Select with cast and convert
Select LastName, CompanyName + CAST(id as nvarchar) as employeeId from databaseTable
Select convert( date, orderDate, 102) as orderDate from databaseTable
Select with case when
Select case when completedDate is NULL then 'completed' else 'processing' end as status from databaseTable
Select where
Select * where id=1
Select * where id is not null
Select Color from databaseTable where Color in ('black', 'red','white')
Select Code from databaseTable where Code like 'SM-%'
% functions as wildcard
Select Code from databaseTable where Code like 'SM-[^Z]%-%'
Uses regular expression ([^Z] is any character other than 'Z')
Ordering
Select name from databaseTable order by name desc
Offset and fetch
Select name from databaseTable offset 5 rows fetch next 15 rows only
Grouping
SELECT aField, count(*) FROM [dbTableName] GROUP BY aField
SELECT aField, count(*) FROM [dbTableName] GROUP BY aField HAVING count(*)>50
Aggregates
Aggregate functions: Count, Max, Min, Avg, StDev, Sum, Var
SELECT COUNT(*) FROM [dbTableName]
Examples
Select customer, Rank() over (order by totalSale desc) as RankByTotalSale from invoices
Select inv.cust, sum(line.total) as total from invoice as inv join lines as line on inv.id = line.invId, group by inv.cust
Select count(productId) as nIds, count(quantity) as nQuantities, sum(unitPrice) as sumPrices from orderDetails
Functions
Select upper(Name), round (Weight, 0) as approxWeight from wrestlers
Select year(tripDate) as year, DateName(month, tripDate) as month from trips
Select left(ProductId,3) as model from products
Technique
Operations on Table
Insert
INSERT INTO [dbTableName] (field1, field2, field3) VALUES ('data1', 'data2', 'data3')
INSERT INTO [dbTableName1] (field1, field2, field3) VALUES (SELECT f1, f2, f3 FROM [dbTableName2])
Update
Update databaseTable set survey = true where CustomerID % 9 = 1
Delete
DELETE FROM [dbTableName] where aField='test'
Delete All Table Rows
DELETE FROM [dbTableName]
TRUNCATE TABLE [dbTableName]
Truncate is faster, but cannot be rolled back
Maintenance Queries
SQL Server Version
SELECT @@VERSION
Technique
Joins
Inner Join
Default, can be abbreviated as Join
Represented by (A n B), or A intersect B
All rows in which the field criteria match will be shown
Criteria must be present in each table
Examples (inner join is often written as join)
Select * from tabA as A join tabB as B on A.id = B.id
Select * customer as c join custAddress as ca on c.custId = ca.custId and ca.type = 'Main'
Left Outer Join
Represented by (A ? (A n B))
All rows from the left-sided (first) table (regardless of match) AND
Any matching from the right table
Examples
Select * from tabA as A left outer join tabB as B on A.id = B.id
Right Outer Join
Identical to a Left Outer Join except the right-sided (second) table is the priority
Represented by (B ? (A n B))
All rows from the right-sided (second) table (regardless of match) AND
Any matching from the left table
Full Outer Join
Represented by (A ? B ? (A n B))
All rows from both tables regardless of matches in one or the other
Technique
Unions/intersect/Except
Union
Example: Obtain all contacts for both staff and customers
select fname, lname, phone from staff UNION fname, lname, phone from customer
Intersect
Example: Obtain all staff who are ALSO customers
select fname, lname, phone from staff INTERSECT fname, lname, phone from customer
Except
Example: Obtain all staff who are NOT customers
select fname, lname, phone from staff INTERSECT fname, lname, phone from customer
Management
Windows Server set-up
Update the system
Run Windows Update
Apply Bios and firmare patches
Update device drivers (e.g. drives)
Set power options (esp. for dedicated database server)
Set Windows Power Options to "High Performance"
Set Bios Power Management to disabled or OS Control
Set-up Windows server user account for each Database service
User Account Examples: SqlAdmin, SqlAdminAgent, SqlBrowser
Do not set-up accounts as administrator
Set-up as password never expires and user cannot change password
Have accounts ready for MS-SQL installation and have ready at install time
Grant specific access
Use Local Group Policy Editor (gpedit.msc, computer-Windows-Security-Local-User)
Grant "Perform volume maintenance tasks"
Grant "Lock pages in memory" (and set a max memory for MS-SQL usage)
Management
SQL Server Installation
Choose a version of SQL Server
Versions: Enterprise, Business, Standard, Express
Lice
nsing: Per core or per client (CAL)
Enterprise is full featured, but astronomically priced
Business is $5000+
Standard is $3000 + CAL but has limitations and licensing is confusing
Express is free, but has significant limitations
No sqlAgent, <1 GB memory, <10 GB per database
Can limit database size by using Filestream Data (saves blob data to file system)
Can connect remotely with Sql Management Studio using SqlBrowser
http://blog.citrix24.com/configure-sql-express-to-accept-remote-connections/
Install only features needed currently
Less exposure for attacks
Faster to patch
Less resource utilization
Install Options
Choose sql server stand-alone install or update from older version
Sql Server Feature Installation (barebones options selected initially)
Database Engine Services
Management Tools
Documentation Components
Default or Named Instance
Choose default on a production server with only one sql server version
I chose Named Instance for SqlExpress
Server Configuration
Assign windows server accounts as created above (one for each service)
Set Database Engine and SqlAgent both to Automatic startup
Windows Authentication or Mixed Mode
Many applications require mixed mode
For mixed mode, enter a secure password for SA account
Add Active Directory accounts you plan to use to SQL Server administrator list
Data Directories
Set database directory, log directory, temp DB directory, Backup directory
Even using only a C-Drive, consider changing to shorter names in less deep dirs
Filestream
Enable to allow SQL Server to save blob data to file system outside the database
SQL Express 10 GB limit does not include Filestream Data
Management
SQL Server Configuration and Maintenance
Configuration via SQL Server Management Studio
Right click on the SQL Server instance in the top left column (above the database list)
Select Properties
Memory Page
Set maximum server memory (to less than the full amount)
Database Settings Page
Check "Compress Backup"
Change Database locations
Avoid changing Processors Page
When making changes, consider "Use Script" button, which displays the T-SQL
Configuration via SQL Server Configuration Manager
SQL Server Services (e.g. SQL Server, SQL Server Browser, SQL Server Agent)
View Service Properties
Preferred interface for maximal functionality (e.g. Change logon account)
Task manager, services applet are incomplete
Manage Service
Stop, Start, Restart a service
Pause and resume a service
Enabling a disabled service, requires using windows services to enable
Task manager will not allow enabling (must be enabled via Services applet)
SQL Server Network Configuration
Shared Memory (enabled by default)
TCP/IP (enabled by default)
Named Pipes (older protocol, rarely used now)
Maintenance
Keep the system updated (patches, cummulative updates, service packs)
Set-up Database mail (with SMTP) and SQL Server agent alerts
Test database connectivity with a blank UDL file
Create a blank file and change its extension to "UDL" (MS Data Link File)
Opening the file will bring up a Data Link properties dialog
Start on the Provider Tab and then move to the Connection Tab
Type in DB Server, integrated security or SA/Password, database
Click Test Connection
References
Berry (2012) SQL Server 2012: Installation and Configuration, Pluralsight
Gennick (2004) SQL Pocket Guide, O'Reilly, Sebastopol
Type your search phrase here