Showing posts with label SQL. Show all posts
Showing posts with label SQL. Show all posts

Tuesday, June 28, 2011

Digital Signing Demo

This post demonstrates the use of a digital signing function to ensure data within a table is unaltered outside a given set of stored procs. To understand how these and other crytographic functions can be employed to improve the security of database applications, please review this post.

The first step in the demonstration is to create an empty database within which sensitive data will be housed:

USE master;
GO

IF EXISTS (SELECT * FROM sys.databases WHERE name = ‘SigningFunctionDemo’)
   DROP DATABASE SigningFunctionDemo;
GO
CREATE DATABASE SigningFunctionDemo;
GO

Next, a table will be created to house some sensitive data.  It’s important to note that for this demonstration, the data is not being encrypted but it could be to make unauthorized access and modifications more challenging:

USE SigningFunctionDemo;
GO

CREATE TABLE dbo.MySensitiveData (
   Id INT NOT NULL IDENTITY(1,1),
   MyData NVARCHAR(25) NOT NULL,
   MySignature VARBINARY(256) NOT NULL
   );
GO

To support signing, an asymmetric key will be created along with two stored procedures making the signing and verification calls on behalf of the application:

CREATE ASYMMETRIC KEY MySigningKey
    WITH ALGORITHM = RSA_2048
    ENCRYPTION BY PASSWORD = N’asd!i36oheQ#wr8iW#%qwei4!orqhq9w7as’;
GO

CREATE PROC dbo.spPutData @MyData NVARCHAR(25)
AS
   INSERT INTO dbo.MySensitiveData (MyData, MySignature)
   SELECT
    @MyData,
    SIGNBYASYMKEY(
         ASYMKEY_ID(‘MySigningKey’),
         @MyData,
         N’asd!i36oheQ#wr8iW#%qwei4!orqhq9w7as’
         );
GO

CREATE PROC dbo.spGetData @Id int
AS
 SELECT
    MyData,
    VERIFYSIGNEDBYASYMKEY(
  ASYMKEY_ID(‘MySigningKey’),
  MyData,
  MySignature
  ) AS IsValid
 FROM dbo.MySensitiveData
 WHERE  Id = @Id;
GO

With this in place, data can now be placed into the database along with a signature:

EXEC dbo.spPutData N’This is my sensitive data’
GO

Accessing the table directly, the data and its signature can be seen:

SELECT * FROM dbo.MySensitiveData
GO

Read more: MSDN Blogs

Monday, June 27, 2011

Detailed steps for configuring TeamCity to use MySQL as repository database on Windows

Introduction
I started recently setting up a TeamCity 6.5 server on a Windows 2008 R2 machine. The install was straight forward, but unfortunately TeamCity doesn’t use a mainstream database server out of the box. The good news is that you can configure TeamCity to use a different database server to run the TeamCity repository. I decided to use MySQL. This blog post has detailed steps for switching TeamCity to MySQL.

Why would someone want to switch to MySQL?

Performance
The most important reason is performance. Moving to a database server that is enterprise grade and located on a separate machine is boosting TeamCity response times significantly.

Integration
The second reason is integration. I am working on a prototype of a WordPress plug-in called LabPress that needs to be able to access TeamCity tables directly.

Step by step
Before we start here is a link to the TeamCity Documentation for switching the database engine.
Important Note: The following steps assume that you start from a clean TeamCity 6.5 system or you don’t need to migrate existing build configurations and projects to the new database.

Step 0
Install TeamCity 6.5 and MySQL, and optionally phpMyAdmin to administer MySQL via a web browser. The TeamCity install is straight forward. MySQL can be installed conveniently via the Microsoft Web Platform Installer.

Read more: Tellingmachine

Sunday, June 26, 2011

Encrypt the Data

SQL Server supports the encryption of data through a number of mechanisms.  These include:
   Cryptographic functions for the encryption and signing of individual values,
   The Transparent Data Encryption (TDE) feature through which the data and log files associated with a database are encrypted, and
   Support for SSL and IPSec to encrypt data as it is transmitted between the server and clients.

In addition, SQL Server supports an internally managed cryptographic key infrastructure but may also integrate with an externally managed infrastructure through its Extensible Key Management (EKM) interface.

To get a more in-depth and complete overview of the SQL Server cryptographic capabilities, please refere to this white paper.


Cryptographic Functions
With SQL Server 2005, a collection of cryptographic functions were introduced into the database product for the encryption and signing of individual values. Prior to the 2005 release, applications could store encrypted values and signatures within the database but relied on external functions to perform the encryption and signing work.  By moving the functions into the database engine, SQL Server provides greater and more consistent access to cryptographic functionality and allows an application to more easily leverage a centrally managed encryption key infrastructure.


The Encryption Functions
The encryption functions support encryption using either symmetric or asymmetric keys.  Symmetric key encryption has less  performance overhead while asymmetric key encryption provides stronger protection.

To perform symmetric key encryption, SQL Server provides two functions: EncryptByKey() and EncryptByPassPhrase().  The EncryptByKey() function leverages a symmetric key registered in advance with SQL Server.  With the EncryptByPassPhrase() function, a temporary symmetric key is generated using a passphrase supplied with the function. The choice of which function to employ comes down to the needs of the application and the availability of key management support within the organization.

Read more: MSDN Blogs

Thursday, June 23, 2011

Build Secure Database Applications with Microsoft SQL Server Series To Be - Post 0 of X

  • Databases are prime targets because they are foundational to many applications and are the principle stores of sensitive data.
  • Responsibility for the protection of our databases is distributed between multiple groups. While an optimist might see this as providing multiple layers of protection, I'm concerned that without one group or individual having overarching responsibility, there tend to be significant gaps in security policies and procedures.
With this in mind, I am speaking with folks about ways they can improve the security of their database applications built upon Microsoft SQL Server. My objectives are to:
  • Improve awareness of features and practices that can be used to make SQL Server databases tougher targets, and
  • Encourage folks to engage in dialogs within their organizations about database security to ensure gaps are identified and addressed.
In order to engage a broader audience, I am providing much of this information here as a series of blog posts organized around the high-level practices that should be employed. As entries are posted, I'll convert each of these practices into links to make accessing of this information a bit easier:
  • Harden the database server
  • Control network communications
  • Limit access to database services
  • Assign minimal permissions
  • Encrypt your data
  • Defend against common exploits
  • Monitor and enforce policies

Secure the Authentication Process

SQL Server supports two authentication mechanisms: Windows authentication and SQL Server (SQL) authentication.  With Windows authentication, SQL Server simply validates a user’s Windows identity with an identity management solution such as Active Directory.  With SQL authentication, SQL Server generates, stores, and manages instance-specific user name and password information.  While SQL Server can be configured to employ SQL authentication in addition to the Windows authentication default, it is strongly discouraged as SQL authentication is vulnerable to brute-force attacks. That’s not to say that Windows authentication is invulnerable to attack. In fact a new feature, Extended Protection, was introduced with SQL Server 2008 R2 to thwart one such attack.
Extended Protection
The man-in-the-middle (MITM) attack is executed by a malicious application which impersonates the SQL Server service to a client and the client to the service.  In doing so, the malicious application places itself in the middle of the communications channel between the client and server and from this vantage point can intercept messages transmitted between the two. (This attack is also referred to as authentication relay.)
To thwart this attack, SQL Server registers its identity as a Service Principle Name (SPN) with Active Directory (typically at the time of installation).  The client obtains the SPN as part of the connection process and validates this against the SPN held by SQL Server.  If the malicious application does not have access to the SPN, the connection is not completed.
This process is referred to as service binding and it protects against scenarios where the malicious application lures the client to it.  If the client voluntarily connects to the malicious application (usually due to spoofing), then channel binding can be employed to block the MITM attack.
With channel binding, the SQL Server service sends the connecting client the public key associated with a private key it maintains.  The client generates a value known as the Client Binding Token (CBT), encrypts it with the service’s public key, and transmits the encrypted CBT to SQL Server. Using its private key, SQL Server decrypts the CBT and then uses the CBT to encrypt the channel between it and the client.  Without the private key, the malicious application cannot decrypt the CBT and therefore cannot access the data passed between the client and server.
Read more: Data Otaku

Thursday, June 16, 2011

Creating a Windows Sidebar gadget for a SQL Server Reporting Services Report walkthrough

untitled%25255B3%25255D.png?imgmax=800


By default, after installing Window7 operation, there are many powerful and handy little tools in Sidebar Gadget, you can also download some customized Sidebar Gadget, such as: MSDN forum helper. Currently, we have some stock reports to show the real-time status of stock market, we also want to integrate SQL Reporting Services - stock report into window7’s Sidebar Gadget rather than open the IE all the time.
This article will walk you through the processes of integrating SQL Server Reporting Services into Windows 7 Sidebar Gadget.


SQL Server: Shortcuts for TSQL Code in SSMS

For a developer or DBA it’s common to start their day with “SELECT * FROM” and in a daily routine work we type same lines of script many times. If you are a lazy developer or DBA like me then sometime it feels boring to type same code again and again. Intellisence in SQL Server 2008, saved lot of time but still it lacks few features, which other third party tools were offering before SQL Server 2008. Through such tools like SQL PROMPT, we have ability to type shortcuts in editor which after pressing Enter or Tab turn into a predefined code block. Like I will just type * and it will convert it to “SELECT * FROM”.
If you don’t like to purchase these tools but still want to make your life easy then you need SSMS Tools by Mladen Prajdić, totally free and you can download from here. Beside other good tools it has an option of SQL Snippets. Although it already have a good list of shortcuts but still you can add of your choice.

SQL+Snippet+2.gif

Read more: Connect SQL

Wednesday, June 15, 2011

How to Implement HADR (a high-availability and disaster recovery solution) in SQL Server ? Step by Step Guide with screenshots

SQL Server Denali (2011) would introduce a new feather named HADR (a high-availability and disaster recovery solution). The new feather is using a multi data mirror technology, thats provides high-availability and disaster recovery solution.
I found an excellent article on this topic, that can accessed by using the link: Implement HADR (a high-availability and disaster recovery solution) in SQL Server ? Step by Step Guide with screenshots
The autor of the article above, DBATAG (virtual preferred name) owns the website http://www.sqlserver-training.com/, that provides an excellent How to’s, writing blog, articles and tutorials.

Read more: yuval14

Tuesday, June 14, 2011

מרכז הפתרונות של SQL Server

שלום רב,
לטובת מנהלי בסיסי הנתונים מייקרוסופט העלתה את מרכז הפתרונות של SQL Server.
מטרת המרכז לרכז במקום אחד את כל הקישורים הדרושים לנו ביום יום.
המרכז מחולק למספר קטגוריות:
1. משאבים חדשים
2. שדרוג והעברה
3.כלים
4. בינה עסקית
5. קהילה
6. אפשרויות תמיכה
7. מחזור חיי תמיכה
מרכז הפתרונות רלוונטי לגירסאות הבאות של SQL Server ‏:2008 R2, 2008, 2005, 2000, 7.0

SQL CASE statement examples

It is quite difficult to write a stored procedure or a function if you do not know or understand the SQL conditional processing statements. From an interview perspective, you should familiarize yourself with the conditional processing as well as the flow control statements.

The CASE expression is used to evaluate several conditions and return a single value for each condition. For example, it allows an alternative value to be displayed depending on the value of a column. A common use of the CASE expression is to replace codes or abbreviations with more readable values. This is also known as a Simple CASE expression.

Question: For a given product and category abbreviation, show the full category name using a CASE expression.

SELECT   ProductNumber, Category =
      CASE ProductLine
         WHEN 'R' THEN 'Road'
         WHEN 'M' THEN 'Mountain'
         WHEN 'T' THEN 'Touring'
         WHEN 'S' THEN 'Other sale items'
         ELSE 'Not for sale'
      END,
   Name
FROM Product
ORDER BY ProductNumber;

Another use of CASE is to categorize data.

Question: Based on an item list price, show the price range for the item. The example below shows a searched CASE expression which evaluates a set of Boolean expressions to determine the result.

SELECT   ProductNumber, Name, 'Price Range' = 
      CASE 
         WHEN ListPrice =  0 THEN 'Mfg item - not for resale'
         WHEN ListPrice < 50 THEN 'Under $50'
         WHEN ListPrice >= 50 and ListPrice < 250 THEN 'Under $250'
         WHEN ListPrice >= 250 and ListPrice < 1000 THEN 'Under $1000'
         ELSE 'Over $1000'
      END
FROM Production.Product
ORDER BY ProductNumber ;

Monday, June 13, 2011

Temporary and Global Temporary Table in SQL Server 2008

TemporaryTable:

Temporary tables are tables that are available only to the session that created them. 
These tables are automatically destroyed at the termination of the procedure or session that created them.
Use of temporary tables in MS SQL Server is more developer friendly and they are widely used in development. Local temporary tables are visible only in the current session.
Temporary tables are created using the same syntax as a CREATE TABLE except the table name starts with a '#' sign. When the table consists of a single '#' sign, it is defined as a local temporary table and it's scope is limited to the session it is created in.

Global TemporaryTable:

Global Temporary tables are visible to or available across all sessions. And all users.
Global Temporary tables are created using the same syntax as a CREATE TABLE except the table name starts with "##" (two '#' signs). When the table is only "##", it is defined as a local global temporary table and it's scope is not limited to the session it is created in.

A Global Temporary table is dropped automatically when the last session using the temporary table has completed.

Both the local temporary tables and global temporary tables are physical.

Uses of Temporary Tables:
A Temporary Table variable can be very useful when used with stored procedures to pass input/output parameters or to store the result of a table valued function.
Now to create the Temporary table the query will be:

CREATE TABLE #TEMPTABLE
(
Id INT,
Name VARCHAR(30),
Date DATETIME DEFAULT GETDATE()
)
Run the query. After that the "TEMPTABLE" will be created.
Now we are going to insert some values into the TempTable.
INSERT INTO #TEMPTABLE(Id, Name) VALUES(1,'shirsendu');
INSERT INTO #TEMPTABLE(Id, Name) VALUES(2,'Sarnali');
INSERT INTO #TEMPTABLE(Id, Name) VALUES(3,'Mrinal');
Execute the Query
Now to see the values inserted into the temp table execute the following query:
select * from  #TEMPTABLE

The result will look like

Read more: C# Corner

SELECT 101 FAQ's FROM SQL Server Community INSERT INTO Free eBook (185 pages, PDF)

Our SQL Server Forum Support Team authored, collected and consolidated those common asked questions in SQL Server MSDN and TechNet forums into this ebook so as to provide an offline reading and learning experience for IT professionals and people who are interested in SQL Server. In this ebook, there are totally about 101 items covering database administration, SSAS, SSIS and SSRS which are good references for you to handle common SQL Server problems.
...
Part I Database Administration 
1. Why did a T-SQL script fail to run a job when it could successfully run in SQL Server Management Studio ? 6 
2. How can I degrade a SQL Server database from a higher version to a lower one? 8 
3. How can I create a linked server to the Access or Excel data source from the 64-bit version of SQL Server 2005/2008? 9 
4. Why is all of the memory allocated for SQL Server not shown in Windows Task Manager? 11 
5. How do I configure SQL Server to use larger memory space over 2GB on a 32-bit server? 13 
6. How do I rename my SQL Server instance? 15 
7. How do I store data in multiple languages within one database? 16 
8. How do I calculate the space a nullable column takes in SQL Server 2008? 17 
9. Why can't I view the list of databases, tables, views and etc. in the SQL ServerManagement Studio Object Explorer? 18 
10. Why can't I by pass the "Restart computer" rule when installing SQL Server 2008? 19 
11. Can SQL Server Enterprise Edition be installed on client operating systems? 20 
12. How do I troubleshoot SQL Server connectivity issues? 21 
13. Why can’t I track data changes even though I already enabled the database audit on my database? 22 
14. How do I use Powershell script to read the information of any database on a server? 23 
15. Why can't I log on to SQL Server using Windows Authentication in SQL Server Management Studio? 24 
16. What permission(s) do I need to execute a stored procedure (sp)? 25 
17. How do I troubleshoot SQL Server 2008 installation issues? 27 
18. How do I configure SQL Server to enable distributed transactions via Linked Server? 28 
19. How do I find the correct "server" or "data source" value for an SQL Server instance in a connection string? 29 
20. How do I configure Windows Firewall to allow remote connections using TCP/IP protocol for SQL Server? 30 
21. Could SQL Server 2008 Express edition and SQL Server 2008 R2 Express edition be installed side by side with SQL Server 2005 Express? 32 
22. How do I apply a service pack for an instance of SQL Server 2005 Express Edition or SQL Server 2008 Express Edition? 33 
23. How do I resolve ‘SQL Server Setup cannot valid the service accounts’ error message during the setup? 34 
24. Why do I get ‘Rule “Existing clustered or clustered-prepared instance” failed’ error while adding new features to an existing instance of SQL Server Failover Cluster? 35
Part II Analysis Services 
25. How do I clear the warm cache of a cube? 38 
26. How do I exclude data members or create non-aggregatable values in parent-child dimensions? 39 
27. How do I specify a calculated member as the default member of an attribute? 41 
28. How do I create AVG measure in my cube? 42 
29. How do I implement dynamic security for the users? 43


Thursday, May 26, 2011

SQL CLR Stored Procedure using Visual Studio 2010

In this post, we will see how to use SQL CLR functionality for defining Stored Procedure using C# in VS 2010. We will also see how to enable CLR under SQL Server.
T-SQL is designed for direct access of data and for manipulation of that data. But T-SQL does not contain arrays, classes, collections, For-Each loop functionalities. However using SQL CLR, we can achieve all of this. With the integration of CLR in SQL Server, we can write managed code to define –
  • Stored Procedures.
  • User Defined Functions.
  • Triggers.
  • User Defined Type.
  • User Defined Aggregate.
The decision to use CLR functionality under SQL server needs to be implemented when you are performing –
  • CPU intensive operations.
  • Procedures that perform complex logic.
  • When you want to use BCL (Base class libraries) of .NET framework.
By default the CLR is not enabled under SQL Server. To enable CLR under SQL Server, execute the following command –

SP_CONFIGURE 'clr enabled',1
RECONFIGURE

Read more: SQL Server curry

Tuesday, May 24, 2011

How to extract day/month/year from a DateTime column – TSQL

You can do this using two different ways. First is to us DAY(), MONTH() an YEAR() TSQL functions. These functions return an integer representing a day/month or year respectively.
These can be used as:

– © 2011 – Vishal (http://SqlAndMe.com)
SELECT      DAY  ( GETDATE() ) AS 'Day',
            MONTH( GETDATE() ) AS 'Month',
            YEAR ( GETDATE() ) AS 'Year'
Result Set:
Day         Month       Year
———– ———– ———–
19          5           2011
(1 row(s) affected)
Another way is to use DATEPART() TSQL function. The DATEPART() function can also extract week, hour, minute, second in addition to day, month and year. For a full list of parts that can be extracted using DATEPART() refer BOL.
We can use DATEPART() to extract parts as below:

– © 2011 – Vishal (http://SqlAndMe.com)
SELECT      DATEPART(DAY,   GETDATE()) AS 'Day',
            DATEPART(MONTH, GETDATE()) AS 'Month',
            DATEPART(YEAR,  GETDATE()) AS 'Year',
            DATEPART(HOUR,   GETDATE()) AS 'Hour',
            DATEPART(MINUTE, GETDATE()) AS 'Minute',
            DATEPART(SECOND, GETDATE()) AS 'Second'
Result Set:
Day         Month       Year        Hour        Minute      Second
———– ———– ———– ———– ———– ———–
19          5           2011        21          6           5
(1 row(s) affected)

Read more: SqlServerPedia

SQL Server: How to Remove Extra Spaces From String Value

xtra spaces between characters of a string value is a common problem and if you’re a developer then you must have faced the problem. On request of a blog reader here is a script from my query bank which I like to use to remove such extra spaces.

--Create a temp table for testing our query
CREATE TABLE #ExtraSpaces ( MyVal VARCHAR(8000))

--Insert some value to test
INSERT  INTO #ExtraSpaces
SELECT  'This     is my                         message.               '
UNION ALL
SELECT 'This      message   contains            tabs and    extra       spaces'

-- Lets remove extra spaces and tabs
WHILE 1 = 1
    BEGIN
        UPDATE  #ExtraSpaces
        SET    MyVal = REPLACE(
SUBSTRING(MyVal, 1,
CHARINDEX('  ', MyVal, 1) - 1) + ' '
                + LTRIM(
SUBSTRING(MyVal,
CHARINDEX('  ', MyVal, 1), 8000)),'  ',' ')
        WHERE   CHARINDEX('  ', MyVal, 1) > 0

Read more: Connect SQL

How to get difference between two dates – TSQL

o calculate the difference between two dates, you can use DATEDIFF() function. The DATEDIFF() function returns the number of days/month/years and time between two dates.
Syntax:

DATEDIFF (date part, start date, end date)
For example, to calculate time left till Independence Day, you can use:
– © 2011 – Vishal (http://SqlAndMe.com)
DECLARE     @Today      DATETIME = GETDATE()
DECLARE     @IDay       DATETIME = '2011-08-15 08:30:00'
SELECT DATEDIFF(DAY, @Today, @IDay),      'Days Left'
UNION ALL
SELECT DATEDIFF(MONTH, @Today, @IDay),    'Months Left'
UNION ALL
SELECT DATEDIFF(YEAR, @Today, @IDay),     'Years Left'
UNION ALL
SELECT DATEDIFF(QUARTER, @Today, @IDay),  'Quarters Left'
UNION ALL
SELECT DATEDIFF(HOUR, @Today, @IDay),     'Hours Left'
UNION ALL
SELECT DATEDIFF(MINUTE, @Today, @IDay),   'Minutes Left'
UNION ALL
SELECT DATEDIFF(SECOND, @Today, @IDay),   'Seconds Left'
Result Set:
———– ————-
86          Days Left
3           Months Left

Read more: SQLServerPedia

SQLSPIDAnalyzer.sql - My way of monitoring a particular request in SQL Server

Since a long time I wanted to leverage the details from the DMV dm_tran_database_transactions into my regular SPID monitoring script. I just tried it today and looks to be useful. Any feedbacks/bugs/thoughts, let me know.
I'm combining sys.dm_os_workers, sys.dm_os_threads, sys.dm_exec_requests optionally  sys.dm_exec_query_plan, sys.dm_tran_locks to give a complete picture about a session currently running in SQL Server. To get details about a particular column, refere Books Online.
I'm also attaching .sql file for easier download.

/* ------------------------------------------------------------------------------ 
SQLSPIDAnalyzer.sql - Script to analyze the status of a particular SPID 
Author: SQLSakthi 
Input: Session ID or SPID 
---------------------------------------------------------------------------------- 
THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND 
---------------------------------------------------------------------------------*/
DECLARE @spid int
SELECT @spid = NULL   --<<<< Specify the Session ID to be tracked here
IF @spid IS NULL SELECT 'Please specify a Session ID (SPID) to track' AS 'Error'
SELECT f.session_id spid
,[state]
,f.start_time [req_start_time], f.cpu_time, f.logical_reads,f.writes
,f.command cmd, DB_NAME(f.database_id) db
,f.blocking_session_id blkng_spid
,f.wait_type ,f.wait_time ,f.wait_resource ,a.[last_wait_type]
,suspended_ms =
  CASE a.wait_started_ms_ticks
    WHEN 0 THEN 0
    ELSE c.ms_ticks - a.wait_started_ms_ticks
  END
,runnable_ms =
  CASE a.wait_resumed_ms_ticks
    WHEN 0 THEN 0
    ELSE c.ms_ticks - a.wait_resumed_ms_ticks
  END
--,g.resource_type,g.resource_description,request_mode,request_type,request_status,request_lifetime -- For Lock info
,database_transaction_begin_time xsn_begin
,CASE database_transaction_type
WHEN 1 THEN 'Read/Write'
WHEN 2 THEN 'Read-only'

Android SQLite Viewer

sqliteviewer_2.png


Choosing the database file is done with an external file manager or with agraham's FileDialog.
After choosing a database file, you will see a list with the database tables. Choosing a table will open the second activity which shows the table fields types and the table contents.
BLOB columns will display: "click to see image".
When you click on such a cell the program will try to convert the BLOB data to an image and show it.

Read more: Anywhere Software

Sunday, May 22, 2011

NHibernate one-to-one mapping, non-primary keys

Can't get NHibernate to generate the correct query. It keeps using the primary keys of the two tables I'm joining for the one-to-one relationship, and I can't figure out how to specify the foreign key in one of the tables.

tableA      tableB
{ aID,      { bID,
  bID,        z,
  c,          y,
  d }         x }

so the tableA should join to tableB using tableA.bID = tableB.bID. How can I specify this in the mapping for tableA? I'm using the tableA class to retrieve a row from tableA and a row from tableB, as it is a real one to one relationship.

NHibernate generates the sql to join the tables using tableA.aID = tableB.bID, which is wrong.
This does not work:

<class name="tableA" table="tableA">
  <id name="aID" column="aID" />
  <property name="bID" column="bID" />
  <property name="c" column="c" />
  <property name="d" column="d" />
  <one-to-one name="otherThing" class="tableB" foreign-key="bID" />
</class>
<class name="tableB" table="tableB">
  <id name="bID" column="bID" />
  <property name="z" column="z" />
  <property name="y" column="y" />
  <property name="x" column="x" />
</class>
Answer:
This is the correct way to map it:
<class name="tableA" table="tableA">
  ...
  <many-to-one name="otherThing" class="tableB" column="bID" unique="true" />
</class>

Read more: Satackoverflow

Wednesday, May 18, 2011

Why is my SQL Server being slow... Top 10 PerfMon Counters for SQL Server Performance Monitoring

Do you have a list of SQL Server Counters you review when monitoring your SQL Server environment? Counters allow you a method to measure current performance, as well as performance over time. Identifying the metrics you like to use to measure SQL Server performance and collecting them over time gives you a quick and easy way to identify SQL Server problems, as well as graph your performance trend over time.

Below is my top 10 list of SQL Server counters in no particular order. For each counter I have described what it is, and in some cases I have described the ideal value of these counters. This list should give you a starting point for developing the metrics you want to use to measure database performance in your SQL Server environment.