Foreign key referencing a 2 columns primary key in SQL Server

Of course it’s possible to create a foreign key relationship to a compound (more than one column) primary key. You didn’t show us the statement you’re using to try and create that relationship – it should be something like: ALTER TABLE dbo.Content ADD CONSTRAINT FK_Content_Libraries FOREIGN KEY(LibraryID, Application) REFERENCES dbo.Libraries(ID, Application) Is that what you’re … Read more

Database Deployment Strategies (SQL Server)

For this very problem I chose to use a migration tool: Migratordotnet. With migrations (in any tool) you have a simple class used to perform your changes and undo them. Here’s an example: [Migration(62)] public class _62_add_date_created_column : Migration { public void Up() { //add it nullable Database.AddColumn(“Customers”, new Column(“DateCreated”, DateTime) ); //seed it with … Read more

What is the equivalent datatype of SQL Server’s Numeric in C#

There isn’t a direct equivalent, in that there are no built-in .NET types which allow you to specify the precision/scale explicitly as far as I’m aware. There’s no fixed-point type like NUMERIC. decimal and double are the common floating point types in .NET, with decimal implementing decimal floating point (like NUMERIC in T-SQL) and double … Read more

SQL Transaction Error: The current transaction cannot be committed and cannot support operations that write to the log file

You always need to check for XACT_STATE(), irrelevant of the XACT_ABORT setting. I have an example of a template for stored procedures that need to handle transactions in the TRY/CATCH context at Exception handling and nested transactions: create procedure [usp_my_procedure_name] as begin set nocount on; declare @trancount int; set @trancount = @@trancount; begin try if … Read more

SQL Server 2005 – Export table programmatically (run a .sql file to rebuild it)

This functionality is already built in to Sql Server Management Studio 2008. Just download the trial and only install the client tools (which shouldn’t expire). Use Management Studio 2008 to connect to your 2005 database (its backwards compatible). Right click your database Choose Tasks > Generate Scripts Press Next, select your database again On the … Read more

SQL Query to find the last day of the month

Try this one – CREATE FUNCTION [dbo].[udf_GetLastDayOfMonth] ( @Date DATETIME ) RETURNS DATETIME AS BEGIN RETURN DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @Date) + 1, 0)) END Query: DECLARE @date DATETIME SELECT @date=”2013-05-31 15:04:10.027″ SELECT DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @date) + 1, 0)) Output: ———————– 2013-05-31 00:00:00.000