June 2006 Entries
Security.sql in SQL Server 2005- All others SQL Server 2005 Script have moved to Article under SQL Server

 

-------------------------

-- *** Windows Logins ***

-- **********************

-- This code assumes that JoeAppdev and JaneAppdev already exist as a Windows login

-- Add a Windows login to SQL Server

-- Note that the brackets are required for a Windows login

CREATE

LOGIN [APPDEV\JaneAppDev] FROM WINDOWS;

GO

USE

GO

CREATE

WITH DEFAULT_SCHEMA = Production

GO

-- Or, rename the user in the database

DROP

GO

CREATE

GO

-- Alter the login to add a default schema

ALTER

WITH DEFAULT_SCHEMA = Production

GO

-- Add one of the built-in Windows groups

CREATE

LOGIN [BUILTIN\Users] FROM WINDOWS;

GO

-- *** SQL Server Logins ***

-- *************************

CREATE

LOGIN Topaz WITH PASSWORD = 'Bo3EXNWJ#N6ndg5';

GO

USE

GO

CREATE

WITH DEFAULT_SCHEMA = HumanResources

GO

-- Or, rename the user in the database

DROP

GO

CREATE

WITH DEFAULT_SCHEMA = HumanResources

GO

-- *** Password Policies ***

-- *************************

-- Requires that SQL Server be running on Windows Server 2003 or later

-- and that password policies be enabled in Local Security Settings.

USE

GO

CREATE

LOGIN SIMPLEPWD WITH PASSWORD = 'SIMPLEPWD'

GO

ALTER

LOGIN Topaz WITH PASSWORD = 'Bo3EXNWJ#N6ndg5',

CHECK_EXPIRATION = OFF, CHECK_POLICY = OFF

ALTER

-- *** Authorization ***

==

*********************

-- *** Server Roles

-- Add login Topaz to the sysadmin role

sp_addsrvrolemember

'Topaz', 'sysadmin'

-- Get a list of all server roles

EXEC

sp_helpsrvrole

-- Get the description of a single server role

EXEC

-- Get list of members of the diskadmin role

EXEC

-- *** Database roles

 

 

 

 

 

/*** Execution Context

**********************/

-- Execution Context Sample

-- *** Create the database for this demo ***

USE

GO

CREATE

LOGIN UserProc WITH password = 'Y&2!@37z#F!l1zB'

CREATE

LOGIN UserTable WITH password = 'Y&2!@37z#F!l1zB'

CREATE

LOGIN RealUser WITH password = 'Y&2!@37z#F!l1zB'

GO

CREATE

GO

USE

GO

-- Create the users

CREATE

CREATE

CREATE

GO

-- Create the schemas

CREATE

GO

CREATE

GO

-- Create a table and a proc in different schemas to ensure that

-- there is no ownerhship chaining.

CREATE

TABLE SchemaUserTable.Vendor (ID int, name varchar(50), state char(2), phno char(12))

GO

INSERT

INTO SchemaUserTable.Vendor VALUES (1,'Vendor1','AK','123-345-1232')

INSERT

INTO SchemaUserTable.Vendor VALUES (2,'Vendor2','WA','454-765-3233')

INSERT

INTO SchemaUserTable.Vendor VALUES (3,'Vendor3','OR','345-776-3433')

INSERT

INTO SchemaUserTable.Vendor VALUES (4,'Vendor4','AK','232-454-5654')

INSERT

INTO SchemaUserTable.Vendor VALUES (5,'Vendor5','OR','454-545-5654')

INSERT

INTO SchemaUserTable.Vendor VALUES (6,'Vendor6','HI','232-655-1232')

INSERT

INTO SchemaUserTable.Vendor VALUES (7,'Vendor7','HI','453-454-1232')

INSERT

INTO SchemaUserTable.Vendor VALUES (8,'Vendor8','WA','555-654-1232')

INSERT

INTO SchemaUserTable.Vendor VALUES (9,'Vendor9','AK','555-345-1232')

GO

-- Create the stored procedure in SchemaUserProc

CREATE

PROC SchemaUserProc.VendorAccessProc @state char(2)

AS

SELECT * FROM SchemaUserTable.Vendor WHERE state = @state

GO

-- Grant permissions on the stored procedure

GRANT

GO

-- *** Ready to test execution context ***

-- Now try and access the proc as RealUser

EXECUTE

AS user = 'RealUser'

EXEC

SchemaUserProc.VendorAccessProc 'AK'

-- The permission is denied on the underlying table.

-- But do not want to have to grant permissions to all callers on the underlying table.

-- Instead have the proc run as UserTable, which has SELECT permissions on the table,

-- since that user owns the schema it is in.

REVERT

-- Alter the procedure with UserTable as the execution context

-- ALTER preserves the permissions on the object

ALTER

PROC SchemaUserProc.VendorAccessProc @state char(2)

WITH

EXECUTE AS 'UserTable'

AS

SELECT * FROM SchemaUserTable.Vendor WHERE state = @state

GO

-- Now try and execute the proc as RealUser

EXECUTE

AS user = 'RealUser'

EXEC

SchemaUserProc.VendorAccessProc 'AK'

REVERT

-- Clean up

USE

GO

DROP

DROP

DROP

DROP

 

 

 

/*** Metadata Security

**********************/

USE

CREATE

LOGIN User1 WITH password = 'mC%929N*!LkDvuJ'

-- Use the database of your choice

USE

CREATE

EXECUTE

AS LOGIN = 'User1'

SELECT

-- Because the user has no permissions in the database, no rows are returned

* FROM sys.objects

REVERT

-- Give User1 rights to a table and stored procedure

GRANT

GRANT

-- Execute again as User1

EXECUTE

AS LOGIN = 'User1'

SELECT

 -- Attempt to drop a table in the database

-- Throws an error that doesn't confirm the existence of the table

* FROM sys.objects

DROP

REVERT

-- Clean up

DROP

GO

USE

DROP

LOGIN User1
master
USER User1
TABLE Production.Product
EXECUTE ON dbo.uspGetBillOfMaterials TO User1
SELECT ON Person.Contact TO User1
USER User1
AdventureWorks
master
DATABASE ExecuteContextDB
LOGIN RealUser
LOGIN UserTable
LOGIN UserProc
master
EXECUTE ON SchemaUserProc.VendorAccessProc TO RealUser
SCHEMA SchemaUserTable AUTHORIZATION UserTable
SCHEMA SchemaUserProc AUTHORIZATION UserProc
USER RealUser
USER UserTable
USER UserProc
ExecuteContextDB
DATABASE ExecuteContextDB
master
sp_helpsrvrolemember securityadmin
sp_helpsrvrole securityadmin
LOGIN Topaz WITH PASSWORD = 'Bo3EXNWJ#N6ndg5' UNLOCK

 

-- Unlock after too many unsuccessful login attempts

master
USER TopazD FOR LOGIN Topaz
USER Topaz
USER Topaz FOR LOGIN Topaz
AdventureWorks
USER Jane
USER Jane FOR LOGIN [Home\Mhn002AppDev]
USER [Home\Mhn002AppDev]
USER [Home\Mhn002AppDev] FOR LOGIN [Home\Mhn002AppDev]
AdventureWorks
Encryption.sql in SQL Server 2005

 

Set up sample encryption database

USE

-- Set up three logins

CREATE

LOGIN User1 WITH password = '3f@$fWDY3QvP&K0'

GO

CREATE

GO

USE

CREATE

CREATE

TABLE Customer (

CustId int,

Name nvarchar(30),

City varchar(20),

CreditCardType varbinary(1000),

CreditCardNumber varbinary(1000),

Notes varbinary(4000))

GO

-- Grant access to user

GRANT

-- **************************************************************************

-- DATABASE MASTER KEY

-- **************************************************************************

USE

-- Databases do not have a master key by default, so you must create it

-- before you can use it:

CREATE

MASTER KEY ENCRYPTION BY PASSWORD = 'gK#3hbQKDFQY0oF'

-- Create an asymmetric key to protect the new symmetric key

CREATE

AUTHORIZATION User1

WITH ALGORITHM = RSA_2048

-- **************************************************************************

-- SYMMETRIC KEYS

-- **************************************************************************

CREATE

WITH ALGORITHM = RC4

ENCRYPTION BY ASYMMETRIC KEY User1AsymmetricKey

-- List the symmetric keys in the database

SELECT

-- Insert data, using various asymmetric keys. If the symmetric key isn't

-- open, no error and no data inserted.

* FROM sys.symmetric_keys

OPEN

DECRYPTION BY ASYMMETRIC KEY User1AsymmetricKey

INSERT

INTO Customer VALUES (1, 'Sally Roe', 'Chatinika',

EncryptByKey(Key_GUID('User1SymmetricKey'), 'Visa'),

EncryptByKey(Key_GUID('User1SymmetricKey'), '1234-5678-9009-8765'),

EncryptByKey(Key_GUID('User1SymmetricKey'),

'One of our best customers. Treat like royalty.'))

CLOSE

-- View the new data entered using symmetric keys.

SELECT

-- View the data. Note that you don't have to specify which symmectric key

-- to use to decrypt data, even though multiple symmetric keys can be open.

OPEN

DECRYPTION BY ASYMMETRIC KEY User1AsymmetricKey

SELECT

CustID, Name, City,

CONVERT(VARCHAR, DecryptByKey(CreditCardType)) AS CardType,

CONVERT(VARCHAR, DecryptByKey(CreditCardNumber)) AS CardNumber,

CONVERT(VARCHAR, DecryptByKey(Notes)) AS Notes

FROM

CLOSE

-- **************************************************************************

-- Encryption Catalog Views

-- **************************************************************************

-- Existing keys

SELECT

* FROM sys.certificates

SELECT

* FROM sys.asymmetric_keys

SELECT

* FROM sys.symmetric_keys

SELECT

* FROM sys.database_principals

SELECT

* FROM sys.key_encryptions

SELECT

-- Information about keys

-- "Returns a row for each symmetric key encryption specified using the

-- ENCRYPTION BY clause of the CREATE SYMMETRIC KEY statement."

* FROM sys.crypt_properties

SELECT

-- "Returns one row for each cryptographic property associated with a securable"

-- None in this database

* FROM sys.key_encryptions

SELECT

-- **************************************************************************

-- Clean Up Samples

-- **************************************************************************

* FROM sys.crypt_properties

USE

GO

DROP

DROP

LOGIN User1
DATABASE EncryptionDB
master
SYMMETRIC KEY User1SymmetricKey
Customer

SYMMETRIC KEY User1SymmetricKey
* FROM Customer
SYMMETRIC KEY User1SymmetricKey
SYMMETRIC KEY User1SymmetricKey
SYMMETRIC KEY User1SymmetricKey
ASYMMETRIC KEY User1AsymmetricKey
EncryptionDB
SELECT,INSERT on Customer to User1
USER User1 FOR LOGIN User1 EncryptionDB DATABASE EncryptionDB master
Transaction.sql in SQL Server 2005

 

 

 

 

USE

Northwind;

GO

-- Execute these statements in Connection1:

BEGIN

TRAN

UPDATE dbo.Categories

SET CategoryName = 'Drinks'

WHERE CategoryID = 1;

-- Open a new connection and execute this statement

SELECT

CategoryName from dbo.Categories WHERE CategoryID = 1;

-- Create a table to demonstrate compile errors

CREATE

(ID INT PRIMARY KEY,

ColValue CHAR(4));

GO

-- Create the batch

INSERT

INTO dbo.CompileErrors VALUES (1, 'aaaa');

INSERT

INTO dbo.CompileErrors VALUES (2, 'bbbb');

INSERT

INTO dbo.CompileErrors VALUSE (3, 'cccc');

GO

SELECT

* FROM CompileErrors;

GO

INSERT

INTO dbo.CompileErrors VALUES (1, 'aaaa');

GO

INSERT

INTO dbo.CompileErrors VALUES (2, 'bbbb');

GO

INSERT

INTO dbo.CompileErrors VALUSE (3, 'cccc');

GO

-- Insert new rows with PK violation

INSERT

INTO dbo.CompileErrors VALUES (11, 'aaaa');

INSERT

INTO dbo.CompileErrors VALUES (12, 'bbbb');

INSERT

INTO dbo.CompileErrors VALUES (11, 'cccc');

GO

-- Insert new rows with a non-existent table name

INSERT

INTO dbo.CompileErrors VALUES (111, 'aaaa');

INSERT

INTO dbo.CompileErrors VALUES (112, 'bbbb');

INSERT

INTO dbo.CompileErrrs VALUES (113, 'cccc');

GO

-- DROP TABLE CompileErrors;

-- Use @@TRANCOUNT

BEGIN

TRANSACTION;

UPDATE dbo.Employees

SET LastName = 'Da Volio'

WHERE LastName = 'Davolio';

IF @@TRANCOUNT > 0

BEGIN

PRINT N'The transaction is active.';

ROLLBACK TRANSACTION;

PRINT N'The transaction has been rolled back.';

END

GO

SELECT

LastName FROM dbo.Employees;

-- Use @@ERROR

SELECT

message_id, text from sys.messages;

-- Simple error handling

DECLARE

BEGIN

@err int TRANSACTION;

INSERT INTO dbo.Customers (CustomerID, CompanyName)

VALUES ('ALFKI', 'New ALFKI');

SET @Err = @@ERROR

IF @Err = 0

BEGIN

PRINT 'Commit transaction.';

COMMIT

END

ELSE

BEGIN

PRINT 'Error = ' + CAST(@Err AS varchar(10));

ROLLBACK

END

GO

-- Transactions in Stored Procedures

-- Traditional error handling with @@ERROR

CREATE

@CategoryName nvarchar(15) = NULL,

@CategoryID int = NULL OUTPUT,

@ReturnCode int = NULL OUTPUT,

@ReturnMessage nvarchar(255) = NULL OUTPUT

AS

SET

NOCOUNT ON

-- Declare some working variables

DECLARE @Err int;

DECLARE @Rows int;

DECLARE @identity int;

 

IF @CategoryName IS NULL

BEGIN

SELECT @ReturnCode = 515,

@ReturnMessage = 'Null CategoryName not allowed.'

RETURN

END

 

SELECT

@ReturnCode AS ReturnCode,

@ReturnMessage AS ReturnMessage;

GO

-- Using RAISERROR

IF

WHERE CategoryName='Seafood')

BEGIN

RAISERROR ('Duplicate CategoryName detected.', 16, 1);

END

GO

-- Creating a user-defined error.

EXECUTE

N'Session ID %d caused an error in %s.';

GO

-- Raise the custom error:

DECLARE

@spid INT;

SET

@spid = @@SPID;

DECLARE

@name NVARCHAR(128);

SET

@name = DB_NAME();

RAISERROR

(50003, 10, 1, @spid, @name)

GO

--EXECUTE sp_dropmessage 50003;

-- TRY/CATCH

BEGIN

TRY

BEGIN TRANSACTION;

INSERT INTO dbo.Customers (CustomerID, CompanyName)

VALUES ('ALFKI', 'New ALFKI');

COMMIT

PRINT 'Transaction committed.'; TRY CATCH

 

ROLLBACK

PRINT 'Transaction rolled back.'; CATCH

 

GO

-- Display detailed error information

BEGIN

TRY

BEGIN TRANSACTION;

INSERT INTO dbo.Customers (CustomerID, CompanyName)

VALUES ('ALFKI', 'New ALFKI');

COMMIT

PRINT 'Transaction committed.'; TRY CATCH

 

ROLLBACK

SELECT

ERROR_NUMBER() AS Number,

ERROR_SEVERITY() AS Severity,

ERROR_STATE() AS State,

ERROR_PROCEDURE() AS procedureName,

ERROR_LINE() AS Line,

ERROR_MESSAGE() AS messageText;

PRINT 'Transaction rolled back.'; CATCH

 

GO

-- Use RAISERROR in a TRY/CATCH

BEGIN

TRY

RAISERROR ('Error severity 9', 9, 1);

RAISERROR ('Error severity 16', 16, 1); TRY CATCH

 

DECLARE @ErrorMessage NVARCHAR(4000);

DECLARE @ErrorSeverity INT;

SELECT

@ErrorMessage = ('In CATCH block: ' + ERROR_MESSAGE()),

@ErrorSeverity = ERROR_SEVERITY();

RAISERROR (@ErrorMessage,

@ErrorSeverity, 1); CATCH;

 

GO

-- Create a stored procedure using TRY/CATCH

-- and RAISERROR

CREATE

@CategoryName nvarchar(15) = NULL,

@CategoryID int = NULL OUTPUT,

@ReturnCode int = NULL OUTPUT,

@ReturnMessage nvarchar(255) = NULL OUTPUT

AS

SET

BEGIN

NOCOUNT ON TRY

-- Test if CategoryName null.

IF @CategoryName IS NULL

RAISERROR ('Validation failed: Null CategoryName.', 16, 1);

-- Test if CategoryName already exists.

IF EXISTS (SELECT CategoryName FROM dbo.Categories

WHERE CategoryName=@CategoryName)

RAISERROR ('Validation failed: Duplicate CategoryName.', 16, 1);

-- Begin the transaction.

BEGIN TRANSACTION

INSERT INTO dbo.Categories (CategoryName)

VALUES (@CategoryName);

COMMIT

SET @CategoryID=SCOPE_IDENTITY();

SELECT @ReturnCode=0,

@ReturnMessage='Success! ' + @CategoryName + ' added.'; TRY CATCH

 

-- Test to see if we're in a transaction.

IF @@TRANCOUNT > 0

ROLLBACK

-- Return error information to client.

SELECT @ReturnCode = ERROR_NUMBER();

SELECT @ReturnMessage = ERROR_MESSAGE() +

' Severity=' + CAST(ERROR_SEVERITY() AS nvarchar(2)) +

'; State=' + CAST(ERROR_STATE() AS nvarchar(2)) +

'; Proc=' + CAST(ERROR_PROCEDURE() AS nvarchar(50)) +

'; Line=' + CAST(ERROR_LINE() AS nvarchar(10)); CATCH

 

GO

-- Execute the Stored Procedure

DECLARE

@CategoryName nvarchar(15)

DECLARE

DECLARE

DECLARE

@CategoryID int @ReturnCode int @ReturnMessage nvarchar(255)

SET

@CategoryName = 'Seafood'

EXECUTE

@CategoryName,

@CategoryID OUTPUT,

@ReturnCode OUTPUT,

@ReturnMessage OUTPUT;

 

END

IF

WHERE CategoryName=@CategoryName)

BEGIN

SELECT @ReturnCode = 2601,

@ReturnMessage = 'Name already exists.'

RETURN

END TRANSACTION

 

 

INSERT INTO dbo.Categories (CategoryName)

VALUES (@CategoryName);

-- Pick up @@ERROR and @@ROWCOUNT

SELECT @Err = @@ERROR, @Rows = @@ROWCOUNT

-- If there's an error, rollback.

IF @Err <> 0

BEGIN

SELECT @ReturnCode=@Err,

@ReturnMessage= 'Transaction rolled back.'

ROLLBACK

RETURN

END

-- If no rows inserted, rollback.

IF @Rows = 0

BEGIN

SELECT @ReturnCode=2601,

@ReturnMessage='Insert failed.'

ROLLBACK

RETURN

END

-- Success! Commit the transaction.

ELSE

BEGIN

COMMIT

SET @identity=SCOPE_IDENTITY();

SELECT @ReturnCode=0, @CategoryID=@identity,

@ReturnMessage='Transaction succeeded, row added.'

RETURN

END

GO

-- Execute the Stored Procedure

DECLARE

@CategoryName nvarchar(15)

DECLARE

DECLARE

DECLARE

@CategoryID int @ReturnCode int @ReturnMessage nvarchar(255)

SET

@CategoryName = 'Seafood1'

EXECUTE

@CategoryName,

@CategoryID OUTPUT,

@ReturnCode OUTPUT,

@ReturnMessage OUTPUT;

 

BEGIN

 

SELECT

@ReturnCode AS ReturnCode,

@ReturnMessage AS ReturnMessage;

GO

-- Use XACT_STATE

SET

XACT_ABORT ON;

BEGIN

TRY

BEGIN TRANSACTION;

-- Generate a constraint violation error.

DELETE FROM dbo.Categories WHERE CategoryID=1;

COMMIT TRANSACTION;

PRINT 'Transaction Committed.' TRY CATCH

 

IF (XACT_STATE()) = -1

BEGIN

DECLARE @category nvarchar(50)

SELECT @Category =

(SELECT CategoryName FROM dbo.Categories WHERE CategoryID=1)

ROLLBACK

PRINT 'The ' + @category + ' category cannot be deleted.';

END CATCH

GO

--CLEANUP

DROP

DROP

PROC dbo.InsertCategoryTransaction;

DROP

PROC dbo.InsertCategoryTryCatch;

EXECUTE

sp_dropmessage 50003;
TABLE dbo.CompileErrors;

END

BEGIN

END

END

BEGIN

END

END

BEGIN

END

END

BEGIN

END

END

BEGIN

-- Perform the transaction

 

-- Exit if CategoryName already exists.

-- Exit if CategoryName is null.

 

@CategoryID AS CategoryId, dbo.InsertCategoryTryCatch PROCEDURE dbo.InsertCategoryTryCatch sp_addmessage 50003, 16, EXISTS (SELECT CategoryName FROM dbo.Categories @CategoryID AS CategoryId, dbo.InsertCategoryTransaction EXISTS (SELECT CategoryName FROM dbo.Categories PROCEDURE dbo.InsertCategoryTransaction TABLE dbo.CompileErrors

-- Don't execute this yet!!

ROLLBACK

Functions.sql in SQL Server 2005

 

 

USE

Northwind;

--------------------------------------------

-- Scalar Functions

--------------------------------------------

CREATE

RETURNS int

BEGIN

DECLARE @Total AS int;

SELECT @Total = SUM(Quantity)

FROM dbo.[Order Details];

RETURN @Total;

END

GO

SELECT

dbo.fnProductsSold();

GO

SELECT

dbo.fnProductsSold() AS TotalSold

FROM

 

Products;

-- Scalar function with parameter

CREATE

(@ProductID int = null)

RETURNS int

WITH RETURNS NULL ON NULL INPUT

AS

BEGIN

DECLARE @total int;

SELECT @Total = SUM(Quantity)

FROM dbo.[Order Details]

WHERE ProductID = @ProductID;

RETURN @Total;

END

GO

SELECT

dbo.fnProductsSoldByProduct(NULL);

SELECT

dbo.fnProductsSoldByProduct(DEFAULT);

SELECT

dbo.fnProductsSoldByProduct(3);

GO

--------------------------------------------

-- Inline Table Valued Functions

--------------------------------------------

CREATE

RETURNS

AS

RETURN

SELECT

dbo.fnProductsSold() AS UnitsSold,

SUM(UnitPrice * Quantity) AS TotalSales,

AVG(UnitPrice) AS AveragePrice,

COUNT(*) AS LineItems

FROM dbo.[Order Details];

-- returns an error

SELECT

dbo.fnProductSelectStatistics();

-- correct calling syntax

SELECT

* FROM dbo.fnProductStatistics();

SELECT

FROM

dbo.fnProductStatistics();

-- Inline function with parameter

CREATE

(@ProductID int = NULL)

RETURNS

AS

RETURN

SELECT

dbo.fnProductsSoldByProduct(@ProductID)

AS UnitsSold,

SUM(UnitPrice * Quantity) AS TotalSales,

COUNT(*) AS LineItems

FROM dbo.[Order Details]

WHERE ProductID = @ProductID;

-- execute the function

SELECT

FROM fnStatisticsByProduct(4);

SELECT

* FROM dbo.fnStatisticsByProduct(DEFAULT);

SELECT

* FROM dbo.fnStatisticsByProduct(NULL);

-- Update from inline function

CREATE

(@ProductID int)

RETURNS

AS

RETURN

SELECT ProductID, ProductName, UnitPrice, UnitsInStock

FROM dbo.Products

WHERE ProductID = @ProductID

AND Discontinued = 0;

-- Execute as SELECT

SELECT

* FROM dbo.fnProductByID(3);

-- Update

UPDATE

dbo.fnProductByID(3)

SET

UnitsInStock = 63;

-- Display modified data

SELECT

FROM

dbo.fnProductByID(3);

--------------------------------------------

-- Multi-Statement Table Valued Functions

--------------------------------------------

-- get orders by employee or country

CREATE

(

@EmployeeID int = NULL,

@ShipCountry nvarchar(15) = NULL

RETURNS

(

ShipCountry nvarchar(15) NOT NULL,

CustomerID nchar(5) NOT NULL,

OrderID int NOT NULL,

EmployeeID int NOT NULL

AS

BEGIN

-- If all inputs null, return all rows.

-- Sort by ShipCountry, CustomerID, OrderID, EmployeeID

IF @EmployeeID IS NULL AND @ShipCountry IS NULL

INSERT @Order

SELECT ShipCountry, CustomerID, OrderID, EmployeeID

FROM dbo.Orders

ORDER BY ShipCountry, CustomerID, OrderID, EmployeeID;

ELSE IF @EmployeeID IS NULL AND @ShipCountry IS NOT NULL

-- Filter by ShipCountry.

-- Sort by EmployeeID, CustomerID, OrderID

INSERT @Order

SELECT ShipCountry, CustomerID, OrderID, EmployeeID

FROM dbo.Orders

WHERE ShipCountry=@ShipCountry

ORDER BY EmployeeID, CustomerID, OrderID;

ELSE IF @EmployeeID IS NOT NULL AND @ShipCountry IS NULL

-- Filter by EmployeeID.

-- Sort by ShipCountry, CustomerID, OrderID

INSERT @Order

SELECT ShipCountry, CustomerID, OrderID, EmployeeID

FROM dbo.Orders

WHERE EmployeeID=@EmployeeID

ORDER BY ShipCountry, CustomerID, OrderID;

ELSE IF @EmployeeID IS NOT NULL AND @ShipCountry IS NOT NULL

-- Filter by ShipCountry and EmployeeID.

-- Sort by ShipCountry, CustomerID, OrderID, EmployeeID

INSERT @Order

SELECT ShipCountry, CustomerID, OrderID, EmployeeID

FROM dbo.Orders

WHERE ShipCountry=@ShipCountry AND EmployeeID=@EmployeeID

ORDER BY ShipCountry, CustomerID, OrderID, EmployeeID;

RETURN

END

;

GO

-- Execute the function

DECLARE

@EmployeeID nchar(5);

DECLARE

@ShipCountry nvarchar(15)

SET

@EmployeeID = NULL

SET

@ShipCountry = NULL

SELECT

FROM

dbo.fnOrdersByEmplyee_Country(@EmployeeID, @ShipCountry)

GO

-- Filter on employee

SELECT

FROM

dbo.fnOrdersByEmplyee_Country(6, NULL);

GO

-- Rearrange column and sort orders

SELECT

FROM

dbo.fnOrdersByEmplyee_Country(NULL, 'Spain')

ORDER

BY CustomerID, EmployeeID, OrderID;

GO

-- List distinct countries

SELECT

FROM

dbo.fnOrdersByEmplyee_Country(6, NULL);

GO

-- Joining functions to tables

SELECT

FROM

INNER

ON

O.EmployeeID = E.EmployeeID

ORDER

BY E.LastName;

---------------------------------------------------

-- Using Functions

---------------------------------------------------

-- Create a scalar function to calculate a discount

CREATE

(

@price money,

@discount int

)

RETURNS money

WITH RETURNS NULL ON NULL INPUT

AS

BEGIN

DECLARE @work money

SELECT @work = @price - (@price * (@discount * .01))

RETURN @work

END

 

;

-- Execute the function against the Products table

SELECT

dbo.fnCalcDiscountPrice(UnitPrice,5) AS [5% Off],

dbo.fnCalcDiscountPrice(UnitPrice,3) AS [3% Off]

FROM

ORDER

 

BY UnitPrice DESC;

-- Using Table-Valued Functions in a subquery

-- Compute order total

IF

Object_id('dbo.fnOrderTotal') IS NOT NULL

DROP FUNCTION dbo.fnOrderTotal;

GO

CREATE

FUNCTION dbo.fnOrderTotal()

RETURNS

AS

RETURN SELECT

OrderID, SUM(UnitPrice*Quantity) AS Total

FROM dbo.[Order Details]

GROUP BY OrderID

GO

-- Using functions in subqueries

SELECT

FROM

INNER

ON

WHERE

T.Total >

(SELECT AVG(Total) FROM dbo.fnOrderTotal())

ORDER

BY CustomerID, Total DESC;

-- Cleanup

IF

Object_id('dbo.fnProductsSold') IS NOT NULL

DROP FUNCTION dbo.fnProductsSold;

IF

Object_id('dbo.fnProductsSoldByProduct') IS NOT NULL

DROP FUNCTION dbo.fnProductsSoldByProduct;

IF

Object_id('dbo.fnProductStatistics') IS NOT NULL

DROP FUNCTION dbo.fnProductStatistics;

IF

Object_id('dbo.fnStatisticsByProduct') IS NOT NULL

DROP FUNCTION dbo.fnStatisticsByProduct;

IF

Object_id('dbo.fnProductByID') IS NOT NULL

DROP FUNCTION dbo.fnProductByID;

IF

OBJECT_ID (N'dbo.fnOrdersByEmplyee_Country') IS NOT NULL

DROP FUNCTION dbo.fnOrdersByEmplyee_Country;

IF

Object_id('dbo.fnCalcDiscountPrice') IS NOT NULL

DROP FUNCTION dbo.fnCalcDiscountPrice;

IF

Object_id('dbo.fnOrderTotal') IS NOT NULL

DROP FUNCTION dbo.fnOrderTotal;

O.OrderID = T.OrderID
JOIN dbo.fnOrderTotal() AS T
dbo.fnOrdersByEmplyee_Country(NULL, 'USA') AS O
O.CustomerID, O.OrderID, T.Total
TABLE
dbo.Products
ProductID, ProductName, UnitPrice,
FUNCTION dbo.fnCalcDiscountPrice
JOIN dbo.Employees AS E dbo.fnOrdersByEmplyee_Country(NULL, 'Italy') AS O E.LastName, E.FirstName, O.CustomerID, O.OrderID DISTINCT ShipCountry CustomerID, EmployeeID, OrderID ShipCountry, CustomerID, OrderID ShipCountry, CustomerID, OrderID, EmployeeID

)

@Order TABLE

)

FUNCTION dbo.fnOrdersByEmplyee_Country ProductID, UnitsInStock

 

TABLE FUNCTION fnProductByID UnitsSold, TotalSales, LineItems TABLE FUNCTION dbo.fnStatisticsByProduct UnitsSold, TotalSales, AveragePrice, LineItems TABLE FUNCTION dbo.fnProductStatistics() FUNCTION dbo.fnProductsSoldByProduct AVG(UnitPrice) AS AvgPrice,

AS

FUNCTION dbo.fnProductsSold()
My Computer Crashed?. As a result I lost all the .NET Applications that has been saved. I have recovered all the files from hardware failures(06/25/06)
 
       
       
My desktop computer crashed and died today, and I though, “oh well what the hey“.  Now I have to clearn my house and see if I still have my hubby.   However it started out with a weird frustrations combined with mild hard palpitations, and then I blamed everyone that I communicated last night.   Some of them could hack my computer.   Hence I was wrong again(?).


I wired in front panel buttons (Power, restart, an IDE LED, and a Power LED). I took these front panel buttons and LEDs from an old computer. Needless to say, it didn't work out the way i planned. I had to re-wire it to work with my computer. During this process, i restarted, shutdown, cut power to my computer quite a few times.

Thinking back i realised i should have at least unplugged the harddrive during all this.

Now when i start the computer, it goes all the way to the windows XP loading screen, then halfway through it restarts, and this is an endless process. I'm beginning to think the harddrive has crashed. Can anyone help me confirm this?

I'd rather not re-format the computer, unless i absolutly have to, as i have filess on the computer i'd like to save.
 
The main reason of my computer crashed was my hard drive failure is very upsetting because your hard drive holds all your valuable data files. I needed to repair my hard drive This takes time and can be expensive. Also there is no guarantee that your hard drive data will be recovered.  Well, I'll asked my hubby to fix it for me.   Please forgive me from blamed everything on you for the crashed.  
 
My desktop computer have recovered all my files.   Thanks to my disk back up from (Giga Bank  software installation 8G.B) a few weeks ago, and I  have forgot all about it.  I just remembered about the backupdisk this morning(06/25/06).  THANKS GOD.... 

 
 
use byval for object in method signature

     

 

 

This was a question in one of my interview with American Express, and this was how I understand the question:

 that I  In VB.NET, I found there are a lots methods passing object parameter by value. For example,

Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click

It's impossible in vb6.In vb6, the object is always passed by reference.
How come we can pass object byval in .NET?

An object in both VB6 & VB.NET is a Reference Type!

ByVal & ByRef Parameters are independent of Reference & Value Types. All
parameters in VB.NET by default are passed ByVal, you should only pass a
parameter ByRef when you have to, which is when you need to modify the
callers variable.

A Reference Type is an object that exists on the heap. If I have a variable
that is a reference type and assign the variable to another variable. Both
variables will be pointing to the same object on the heap.

Dim x As Person
x = New Person()
Dim y As Person
y = x

Both x & y are the exact same Person object on the heap.

A Value Type does not live on the Heap. If I have a value type variable and
I assign it to another variable, a copy of the value is made.

Dim x As Integer
x = 100
Dim y As Integer
y = x

Although both x & y have the value 100, they are physically different values
as a copy was made.

Now when you pass a variable to a ByVal parameter a copy of the variable is
made. So for a Reference Type a copy of the reference is made, which means
there is still only one object on the heap & two references to that object.
For a Value Type a copy of the value is made.

When you pass a variable to a ByRef parameter a reference to that variable
is made. So for a Reference Type you have a reference to a reference to the
object, for a Value Type you have a reference to the value.

Remember ByVal & ByRef are how parameters are passed. Reference & Value
Types are how quantities are stored.


Themes (skin & css files) in ASP.NET 2.0

 

Posted on Friday, June 02, 2006 7:29 PM

 

     

 

I created http://maisworkandfriends.com on Themes (skin & css files) in ASP.NET 2.0.  Still trying to decide when it's best to use skin files over css files.  Already figured out that an object property should not belong to both.  Tested some, and haven't been able to receive consistent results.  Is it because...

Caching - How does the ASP.NET Developer server work?
When using multiple CSS / skin file- Are they always applied in the same sequence
Who knows????

I seem to experience the most inconsistencies when changing the document.Theme or document.StyleSheetTheme properties AFTER I have started using them, i.e. switching back and forth between document.Theme and document.StyleSheetTheme to test the differences between the two properties, I have noticed that the @Page directive was not always updated to reflect changes made in Design View.  Not sure what's going on there - need to do some more testing with a better attitude.

Design view displays form with skins applied when using document.StyleSheetTheme but NOT when using document.Theme

 

404 Error -- File Not Found

     

404 Error -- File Not Found
The page you are looking for (http://vijay.8k.com/index.html) is not here.
Possible Reasons:
  • You may have spelled the URL incorrectly.
  • This site may have been removed due to a violation of the FreeServers "Acceptable Use Policy".
  • This site may have been moved to a different server
MaiJohnsworkandfamilyGallery

 
   
I went fishing /ComputerConference CA/my first sport car/KeyWest2001/ Winter in Rochester!
 
More pictures in pictures gallaries section...
Many psychics’ stopped me
 

Many psychics’ stopped me in the malls, restaurant, drug stores, bookstores, department stores...etc, and told me about my past love life, and future career, family love life.  All of them made me believed that some evils have came into my life from the past has had harm my life for a long time.   I needed them to unharm all my bad luck so this will help me be lucky again :)

 

The first few times, I believed in some of them, because they with children, or older folks.   For examples:

 

“You are thinking of your soul mate but not your husband, you meant to be with him.  You two met from the past life and thing didn’t work…etc.  You are will be together this life, because he loves you, just because evil has stopped us to be together.  I can help you two got back together“.  “Give me $200, $300, $900…etc“.   None of them got any dimes from me.

 

“Some others told me liked you are always wanted children, and you can't have them  Or “you've always abused and mistreated by your family...etc“.   Does my face look like I was abused and mistreated? Or because I looked stupid enough to get them stop me then see if I have money for them to steal :)?

 

I am very sick of the psychics’.   They are a whole Gang of evils people.   They will make up the story, made you believed that something wrong with you from your past and now but they are all lie just to get your money.

 

I will report to the police next time any of them stop me, and I advice you to do the same,

 

 

 

Creating a Windows Forms Application

 

Developers will create Windows Forms applications much like they do Visual Basic-based forms today (although with Windows Forms, they get the same level of productivity in all of the languages in Visual Studio, not just Visual Basic). In the following image, you can see that a design surface is used to visually lay out the form with rich controls. To edit source code, developers simply double-click a control and the source editor will appear, enabling quick access to the full event model for the control and form.

Building Windows Forms

Figure 1. Building Windows Forms

Visual Inheritance

Visual inheritance is one of the key new features available in Windows Forms that will enhance developer productivity and facilitate code reuse. For example, an organization could define a standard base form that contains items such as the corporate logo and perhaps a common toolbar. This form can be used by developers through inheritance and extended to meet the requirements of specific applications while promoting a common user interface across the organization. The creator of the base form can specify which elements can be extended and which must be used as is, ensuring that the form is reused appropriately

Precision Form Design

Developers will have an unprecedented level of control and productivity when designing the look and feel of their Windows Forms applications. Features such as the In-Place Menu Editor, Control Anchoring, Control Docking, and many new controls enable a higher level of power and precision for developers building rich Windows-based user interfaces.

With the In-Place Menu Editor, developers can quickly and easily add menus to a form, modify them, and view how they look without having to run the application. Controls on the form are more effective with Control Anchoring, enabling a form to automatically resize controls as a user resizes the form. With Control Docking, controls can be docked on any side of a form, providing greater flexibility in layout.

In-place Menu Editor

Figure 2. In-place Menu Editor

Existing ActiveX® controls can be leveraged and run on any form as well, preserving investments in existing technologies.

New controls-including Link Label, Tray Icon, and Print Preview-provide additional common functionality for developers. Link Label provides HTML-like linking to a specified URL. Text displayed using this control will appear underlined and the cursor will change to a hand as the mouse moves over it, firing an actionable event when clicked. Tray Icon enables developers to create applications that run in the Windows tray similar to the Microsoft SQL Server™ Service Manager. Windows Forms offers a printing framework that makes printing simple, including a Print Preview window with the Print Preview control.

Developers can build applications that support the broadest audience of users with Windows Forms. Windows Forms controls implement Microsoft Active Accessibility® programming interfaces, making it straightforward to build applications that support accessibility aids such as screen readers.

Sometimes your mind is clear and sharp

 

     

Sometimes your mind is clear and sharp, but every once in a while, you get lost in a dream world and can't seem to find your way back to reality. Don't pressure yourself to step down to reality at this time. Instead, you should take this time to dream

First SharePoint at Devry University in Miramar

   

 

I attended the first SharePoint (Session #1 - Level 100 - June 3rd, 2006) at Devry University in Miramar, Room #240, from 2:00 pm to 5:00 pm this weekend. 

 

I am very impress with  the SharePoint  class today, and  from  Duray Akar's  lecture and I have learned more about:

 

 

1. List items in calendar

 

2. Automatically convert Office documents in SharePoint repository, such as World and Excel to Adobe ® allow distribution of read-only, non-editable copies

 

3. Establish a referential integrity relationship between two SharePoint lists using this web part.

 

4. Simultaneously create SharePoint and Active Directory Users! Allows third party editors, such as Adobe FrameMaker and Autodesk AutoCAD to easily browse the SharePoint repository for viewing.

 

5. Editing, check in/out, and uploading.

 

6. SharePoint list items from multiple areas and web sites into a single view with the ability to display, filter, and sort relevant information

 

7. List Alert Web Part gives users a more flexible way to receive alerts from SharePoint list, such as when tasks are due or when an issue’s status field changes from “Open” to “Fixed”. 

 

Hoped I captured everything... :).

 

Thank you Florida.NET: Dave Noderer, Duray Akar, and Stacy Draper for made this happened.

I should doing this...

 

 

        

But instead me and my computer right now...

South Florida Code Camp Feb 2, 2006

       
 

I attended my 1st Code Camp– 2006 South Florida Code Camp, Feb 2, 2006.  Not only did I learn a lot, I had a great time.  I learned which of the presentations I should goto...( I have seen David Silverlight, Alex Funhouse, and Russ Fustino’s presentations many times during the year).

 

I think that I should attend new presenters that I have never seen before, and I did.  I also learned from every session I attended, and from the many conversations I had with other speakers and attendees.  I could easily turn into a Code Camp evangelist (Joe Healy,  and Dave Noderer). 

 

I think it is one of the best ideas in a long time for training and networking within the Microsoft developer community.  I'll give a quick 10 great things about Code Camps (I know I could list many more), but these are the ones that personally benefit me. 

 

Unfortunately, I wasn’t feeling well, I went home early and I knew I missed all others fun in the afternoon, and the Microsoft's Party at night.

 

1.  Free knowledge from folks actually using the product.

2. Choices - I get to choose what topics (and often levels of difficulty) to attend.

3. Opportunity to listened to a friendly group of IT professionals

4. Learn from questions and feedback from the attendees

5. Meeting new friends and peers - I've made new contacts at the Code Camp I have attended

6. Hooking up with old friends - keeping in touch with those I familiar face that I met at the day before prior to last year Code Camps

7. User Group networking - I have found that user groups help other user groups and they really enjoy helping other user groups

8. In Fort Lauderdale Florida the top prize seemed to be popular this year is “Communities Credits Awards” “marketing material(?)”.

9. Great food (of course)

10. A LOT OF FUN!

 

Geekette maisblogette

 

 

For those of you keeping up with my Geekette maisblogette, I am between jobs again.  No, I didn't get fired; I completed working for SunCruzCasino, Inc.  So what does a geekette do with the time off liked this?  Well, among other things (yeah yeah...geeky things), I decided to catch up on some entertainment.

 

I started with Showtime than HBO.  I have been interested in the show for some times.  Nevertheless, I head on down to the local video rental store (which is not so local, if you take my meaning) and pick up a few episodes.   I have no patient to watch re-run each night.

 

What a cool show!  It is somewhat esoteric but not so much that it's annoying.  It's very strange, but not so strange that it can't be understood.  It's an excellent blend of very vivid characters and extremely well-written dialogue with a stark yet somehow rich backdrop of interweaving tales.  The acting is very good, sometimes even great.  Remember “Sex in the City“? Provides the best performances followed VERY good stars liked ” Sarah Jessica Parker as Carrie Bradshaw, Kim Cattrall as Samantha Jones, Kristin Davis as Charlotte York, and Cynthia Nixon as Miranda Hobbes.

 

One of the key interests I had was Sarah Jessica Parker as Carrie Bradshaw.  I think Sarah Jessica Parker is a very versatile actor and I really enjoy watching her work.  For interestingly enough, however, my favorite character is Charlotte York played by Kristin Davis.   Thought,  I liked the show and I have begun understand how single people.  Dating games liked,  I won't ever want to be part of these games.

 

All in all, I recommend, if not highly, that you see the show.  If nothing else, checks it out on IMDB and HBO.  I am 8 episodes into season one and hope to finish the season over the weekend.  As always, your thoughts on the show are appreciated!