An IF inside a check constraint SQL - sql-server

I have this table..
CREATE TABLE [dbo].[Tipo_Servicios_Info](
[TSI_TS_Id] [int] NOT NULL,
[TS_Tar_Id] [int] NOT NULL,
[TS_PDI_Id] [int] NOT NULL,
[TSI_Descripcion] varchar(100),
[TSI_FechaIni] date not null,
[TSI_FechaFin] date not null,
[TSI_HoraMin] time,
[TSI_HoraMax] time,
[TSI_Duracion] varchar(50) not null,
[TSI_Unidad] varchar(50) not null,
[TSI_Cantidad] int not null,
CONSTRAINT [PK_TIPO_SERVICIOS_INFO] PRIMARY KEY CLUSTERED
(
[TSI_TS_Id] ASC,
[TS_Tar_Id] ASC,
[TS_PDI_Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF,
ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
With some checks..
ALTER TABLE Dbo.Tipo_Servicios_Info
ADD CONSTRAINT Ck_Valores_Unidad CHECK(Tsi_Unidad IN('Dia', 'Hora'));
GO
ALTER TABLE Dbo.Tipo_Servicios_Info
ADD CONSTRAINT Df_Tipo_Servicios_Info_Tsi_Unidad DEFAULT 'Dia' FOR Tsi_Unidad;
GO
In this two above I set as default value of the TSI_Unidad to 'Dia', but this field only can contain Dia or Hora by the second constraint.
But i have a problem, I must define TSI_HoraMin and TSI_HoraMax that can be null(if TSI_Unidad is Dia, they have to be nullable), but if TSI_Unidad is Hora, [TSI_HoraMin] and [TSI_HoraMax] cant be null.
I want to create a new constraint but i dont know how can i do it..
This would be the idea..
ALTER TABLE [dbo].[Tipo_Servicios_Info]
ADD CONSTRAINT CK_HorasMin CHECK([TSI_HoraMin] is not null if [TSI_Unidad] = 'Hora')
GO
But this constraint, obviously, isnt well defined.

From what I gather you are trying to not allow a null value for TSI_HoraMin if TSI_Unidad = 'Hora`. In which case you could use:
ALTER TABLE [dbo].[Tipo_Servicios_Info]
ADD CONSTRAINT CK_HorasMin
CHECK(NOT([TSI_HoraMin] IS NULL AND [TSI_Unidad] = 'Hora'));

Related

MSSQL: How to join only if its children not exist

I want to left join but only if it does not have the specific child.
Here is my current query:
SELECT "chatRoom"."id" as id,
"chatRoom"."name" as name,
"chatRoom"."type" as type,
"chatRoom"."description" as description,
"chatRoom"."thumbnail" as thumbnail,
"chatRoom"."status" as status,
chats.[unreadCount] as unreadCount
FROM "chat_room" "chatRoom"
LEFT JOIN "chat_room_participant" "participants" ON "participants"."chatRoomId"="chatRoom"."id"
LEFT JOIN (
SELECT "chatRoom"."id" AS "chatRoomId", COUNT(readBy.id) AS "unreadCount"
FROM "chat" "chat"
LEFT JOIN "chat_room" "chatRoom" ON "chatRoom"."id"="chat"."chatRoomId"
LEFT JOIN "chat_read_by_chat_room_participant" "chat_readBy" ON "chat_readBy"."chatId"="chat"."id"
LEFT JOIN "chat_room_participant" "readBy" ON "readBy"."id"="chat_readBy"."chatRoomParticipantId"
WHERE NOT(readBy.UserId IN ('ca774a5f-a04d-ec11-ae58-74d83e04f9d3'))
OR "readBy"."id" IS NULL
GROUP BY "chatRoom"."id"
) "chats" ON chats.chatRoomId = "chatRoom"."id"
WHERE ('ALL' = 'ALL' OR "chatRoom"."status" = 'ALL')
AND "chatRoom"."applicationId" = '4ac752e9-004c-ec11-ae53-74d83e04f9d3'
AND "participants"."userId" = 'A97D66C4-014C-EC11-AE53-74D83E04F9D3'
ORDER BY "chatRoom"."lastUpdate" DESC
In this query, it returns the correct value only if the readBy is null or contains 1 entry which equals to the given userId.
So here I have the userId. I want to get all the unread chats count from each chatRoom that has the user as a participant.
The schema is like this:
chatRoom has many chats
chatRoom has many participants
chats has many to many `readBy` (participants)
So there is a column automatically created for the many-to-many relation:
column: chat_read_by_chat_room_participant
Contains:
|chatId|chatRoomParticipantId|
In my query above, the left join will get any readBy from another user:
WHERE NOT(readBy.UserId IN ('ca774a5f-a04d-ec11-ae58-74d83e04f9d3')) OR "readBy"."id" IS NULL GROUP BY "chatRoom"."id") "chats" ON chats.chatRoomId = "chatRoom"."id"
which I do not want. This will return the entry if the user already read the chat, but another users have read as well. I want to return the entry only if the user has not read the chat.
How can I do this?
CREATION QUERY
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[chat](
[id] [uniqueidentifier] NOT NULL,
[sentAt] [bigint] NOT NULL,
[type] [nvarchar](255) NOT NULL,
[status] [nvarchar](255) NOT NULL,
[message] [nvarchar](max) NOT NULL,
[filePath] [nvarchar](max) NULL,
[chatRoomId] [uniqueidentifier] NOT NULL,
[senderId] [nvarchar](255) NOT NULL,
[userId] [uniqueidentifier] NULL,
CONSTRAINT [PK_9d0b2ba74336710fd31154738a5] PRIMARY KEY CLUSTERED
(
[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
ALTER TABLE [dbo].[chat] ADD CONSTRAINT [DF_9d0b2ba74336710fd31154738a5] DEFAULT (newsequentialid()) FOR [id]
GO
ALTER TABLE [dbo].[chat] WITH CHECK ADD CONSTRAINT [FK_52af74c7484586ef4bdfd8e4dbb] FOREIGN KEY([userId])
REFERENCES [dbo].[chat_room_participant] ([id])
GO
ALTER TABLE [dbo].[chat] CHECK CONSTRAINT [FK_52af74c7484586ef4bdfd8e4dbb]
GO
ALTER TABLE [dbo].[chat] WITH CHECK ADD CONSTRAINT [FK_e49029a11d5d42ae8a5dd9919a2] FOREIGN KEY([chatRoomId])
REFERENCES [dbo].[chat_room] ([id])
GO
ALTER TABLE [dbo].[chat] CHECK CONSTRAINT [FK_e49029a11d5d42ae8a5dd9919a2]
GO
CREATE TABLE [dbo].[chat_read_by_chat_room_participant](
[chatId] [uniqueidentifier] NOT NULL,
[chatRoomParticipantId] [uniqueidentifier] NOT NULL,
CONSTRAINT [PK_f3dd24628d4644dd6e79bcd03d1] PRIMARY KEY CLUSTERED
(
[chatId] ASC,
[chatRoomParticipantId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[chat_read_by_chat_room_participant] WITH CHECK ADD CONSTRAINT [FK_011624ccd7e7b0281ef629f2930] FOREIGN KEY([chatId])
REFERENCES [dbo].[chat] ([id])
ON UPDATE CASCADE
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[chat_read_by_chat_room_participant] CHECK CONSTRAINT [FK_011624ccd7e7b0281ef629f2930]
GO
ALTER TABLE [dbo].[chat_read_by_chat_room_participant] WITH CHECK ADD CONSTRAINT [FK_2e33e3de9d7c91d426c09a24810] FOREIGN KEY([chatRoomParticipantId])
REFERENCES [dbo].[chat_room_participant] ([id])
ON UPDATE CASCADE
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[chat_read_by_chat_room_participant] CHECK CONSTRAINT [FK_2e33e3de9d7c91d426c09a24810]
GO
CREATE TABLE [dbo].[chat_room](
[id] [uniqueidentifier] NOT NULL,
[name] [nvarchar](255) NULL,
[type] [nvarchar](255) NOT NULL,
[thumbnail] [nvarchar](max) NULL,
[description] [nvarchar](max) NULL,
[status] [nvarchar](255) NOT NULL,
[applicationId] [uniqueidentifier] NOT NULL,
[lastUpdate] [bigint] NULL,
CONSTRAINT [PK_8aa3a52cf74c96469f0ef9fbe3e] PRIMARY KEY CLUSTERED
(
[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
ALTER TABLE [dbo].[chat_room] ADD CONSTRAINT [DF_8aa3a52cf74c96469f0ef9fbe3e] DEFAULT (newsequentialid()) FOR [id]
GO
ALTER TABLE [dbo].[chat_room] WITH CHECK ADD CONSTRAINT [FK_2226638e6b7665ec0259d246b2b] FOREIGN KEY([applicationId])
REFERENCES [dbo].[application] ([id])
GO
ALTER TABLE [dbo].[chat_room] CHECK CONSTRAINT [FK_2226638e6b7665ec0259d246b2b]
GO
CREATE TABLE [dbo].[chat_room_participant](
[id] [uniqueidentifier] NOT NULL,
[joinedAt] [bigint] NOT NULL,
[privilege] [nvarchar](255) NOT NULL,
[chatRoomId] [uniqueidentifier] NOT NULL,
[userId] [uniqueidentifier] NOT NULL,
CONSTRAINT [PK_15913cf37a762fce4c8d6a32a42] PRIMARY KEY CLUSTERED
(
[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY],
CONSTRAINT [UQ_ae9630d66f6c5d12afd1a991fec] UNIQUE NONCLUSTERED
(
[chatRoomId] ASC,
[userId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[chat_room_participant] ADD CONSTRAINT [DF_15913cf37a762fce4c8d6a32a42] DEFAULT (newsequentialid()) FOR [id]
GO
ALTER TABLE [dbo].[chat_room_participant] WITH CHECK ADD CONSTRAINT [FK_9f718459ea81b5130f81980ca08] FOREIGN KEY([userId])
REFERENCES [dbo].[user] ([id])
GO
ALTER TABLE [dbo].[chat_room_participant] CHECK CONSTRAINT [FK_9f718459ea81b5130f81980ca08]
GO
ALTER TABLE [dbo].[chat_room_participant] WITH CHECK ADD CONSTRAINT [FK_fb664f48a4ec615ec5cce90a25d] FOREIGN KEY([chatRoomId])
REFERENCES [dbo].[chat_room] ([id])
GO
ALTER TABLE [dbo].[chat_room_participant] CHECK CONSTRAINT [FK_fb664f48a4ec615ec5cce90a25d]
GO
It looks like you just need a WHERE NOT EXISTS correlated subquery.
Don't be tempted to just use LEFT JOIN IS NULL syntax, it is generally less efficient, as it hides from the optimizer that you are doing an anti-join. Occasionally it can be useful though.
Further notes:
Don't quote column and table names unless you have to. And generally avoid names that need quoting.
Don't alias columns that don't need aliasing.
Choose short meaningful table aliases.
Basic formatting and good use of whitespace helps readability
Your LEFT JOIN chat_room_participant logically becomes an INNER JOIN because of the WHERE.
You don't need to re-join chat_room in the grouped subquery, you can just group by the join column.
You may want to use a grouped OUTER APPLY instead of that subquery. It is unlikely to get a different query plan, but it can be easier to read.
COUNT(SomeNotNullValue) is the same as COUNT(*)
('ALL' = 'ALL' OR cr.status = 'ALL') only makes sense if cr.Status is nullable, otherwise you would just use cr.status = 'ALL'. Even if it is nullable, you may as well use (cr.Status IS NULL OR cr.status = 'ALL')
SELECT
cr.id,
cr.name,
cr.type,
cr.description,
cr.thumbnail,
cr.status,
c.unreadCount
FROM chat_room cr
JOIN chat_room_participant p ON p.chatRoomId = cr.id
LEFT JOIN (
SELECT
c.chatRoomId AS chatRoomId,
COUNT(*) AS unreadCount
FROM chat c
WHERE NOT EXISTS (SELECT 1
FROM chat_read_by_chat_room_participant chat_readBy
JOIN chat_room_participant readBy ON readBy.id = chat_readBy.chatRoomParticipantId
WHERE chat_readBy.chatId = c.id
AND readBy.UserId IN ('ca774a5f-a04d-ec11-ae58-74d83e04f9d3')
)
GROUP BY c.chatRoomId
) c ON c.chatRoomId = cr.id
WHERE (cr.Status IS NULL OR cr.status = 'ALL')
AND cr.applicationId = '4ac752e9-004c-ec11-ae53-74d83e04f9d3'
AND p.userId = 'A97D66C4-014C-EC11-AE53-74D83E04F9D3'
ORDER BY
cr.lastUpdate DESC;
It seems that what you want is an anti-semi join. That is, a join to demonstrate that a row does not exist.
The two typical methods are...
main_table AS m
LEFT JOIN
other_table AS o
ON o.m_id = m.id
AND o.user = 'xyz'
WHERE
o.id IS NULL
Or...
main_table AS m
WHERE
NOT EXISTS (
SELECT *
FROM other_table AS o
WHERE o.m_id = m.id
AND o.user = 'xyz'
)
Exactly how to apply this to your example is unclear as you have cluttered your question with too many other details. (It is not a Minimal Verifiable Example.)

How to limit the value range that can be placed in a column?

I am a beginner in SQL,
I have a table with GroupRole column and Age column.
CREATE TABLE [Persons](
[PersonID] [int] IDENTITY(1,1) NOT NULL,
[FullName] [varchar](70) NULL,
[Age] [int] NULL,
[GroupRole ] [varchar](30) NULL
CONSTRAINT [PK_Persons] PRIMARY KEY CLUSTERED
(
[PersonID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
I want to limit the value range that can be placed in an age column lower 30
and GroupRole column equal 'Admin'.
I do not want to do this in the c# code.
How can I do it?
this have easy way:
ALTER TABLE Persons
ADD CONSTRAINT CHK_PersonAge CHECK (Age>=30 AND GroupRole ='Admin');
You need to use Check Constraints. They are part of your table's metadata and define conditions to be checked every time, when the data is modified or inserted in the table. If these conditions are not met, the DML operation will fail with an error.
You need to modify your CREATE TABLE statement as follows:
CREATE TABLE [Persons](
[PersonID] [int] IDENTITY(1,1) NOT NULL,
[FullName] [varchar](70) NULL,
[Age] [int] NULL CONSTRAINT CHK_Age CHECK ([Age] < 30),
[GroupRole] [varchar](30) NULL CONSTRAINT CHK_GroupRole CHECK ([GroupRole] in ('Admin'))
CONSTRAINT [PK_Persons] PRIMARY KEY CLUSTERED
(
[PersonID] ASC
) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF,
ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO

Cannot insert duplicate key row in object 'dbo.CFD' with unique index

I am running into an error on the insertion of a single row into a table, dbo.CFD. The complete error states:
Cannot insert duplicate key row in object 'dbo.CFD' with unique index 'IX_CFD_NRSC_FXTR_N'. The duplicate key value is (BP2001, 1990, CHK, 01, 3456).
Looking at the index in question, IX_CFD_NRSC_FXTR_N, it is a non-unique, non-clustered index on a single column (The column with BP2001 in the error).
Looking at the data, there are many records with the values of BP2001, CHK, 01, and 3456, however none with 1990 (but various other values), so it doesn't seem I am conflicting with a unique constraint.
I also verified that all foreign key constraints are being met and the primary key constraint is not being violated.
How can I figure out what exactly is causing this issue? Every example I can find results in there being duplicate data being inserted, but I don't think that is the issue here. Thanks!
Edit----------
The table create script:
CREATE TABLE [dbo].[CFD](
[PRPSL_I] [int] NOT NULL,
[FILE_TYPE_C] [char](3) NOT NULL,
[CAD_FLR_C] [char](2) NOT NULL,
[FXTR_SERL_I] [int] NOT NULL,
[ADJC_I] [int] NULL,
[CMP_I] [int] NULL,
[VER_I] [int] NULL,
[NRSC_FXTR_N] [varchar](15) NULL,
[MDSE_SPCE_HT_I] [int] NULL,
[MDSE_SPCE_LGTH_I] [int] NULL,
[MDSE_SPCE_DPT_I] [int] NULL,
[NRSC_FXTR_SIDE_I] [int] NULL,
[NRSC_FXTR_SECT_I] [int] NULL,
[BOFM_INCL_F] [bit] NOT NULL,
[DIVI_I] [int] NULL,
[PRTY_I] [int] NULL,
[REUSE_I] [int] NULL,
[FXTR_ISTL_LOC_N] [varchar](6) NULL,
[PHYS_SECT_NUM_I] [int] NULL,
[SAFL_LOC_N] [varchar](4) NULL,
[SEQ_I] [int] NULL,
[SIDE_ASLE_I] [int] NULL,
[LDIN_I] [int] NULL,
[LDIN_STAT_I] [int] NULL,
CONSTRAINT [PK_CFD] PRIMARY KEY CLUSTERED
(
[PRPSL_I] ASC,
[FILE_TYPE_C] ASC,
[CAD_FLR_C] ASC,
[FXTR_SERL_I] ASC
)WITH (PAD_INDEX = ON, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 80) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
ALTER TABLE [dbo].[CFD] ADD CONSTRAINT [DF_CFD_BOFM_INCL_F] DEFAULT ((0)) FOR [BOFM_INCL_F]
GO
ALTER TABLE [dbo].[CFD] WITH CHECK ADD CONSTRAINT [FK1_CFD] FOREIGN KEY([PRPSL_I], [FILE_TYPE_C], [CAD_FLR_C])
REFERENCES [dbo].[CAD_FILE] ([PRPSL_I], [FILE_TYPE_C], [CAD_FLR_C])
GO
ALTER TABLE [dbo].[CFD] CHECK CONSTRAINT [FK1_CFD]
GO
ALTER TABLE [dbo].[CFD] WITH CHECK ADD CONSTRAINT [FK2_CFD] FOREIGN KEY([CMP_I])
REFERENCES [dbo].[CMP] ([CMP_I])
GO
ALTER TABLE [dbo].[CFD] CHECK CONSTRAINT [FK2_CFD]
GO
ALTER TABLE [dbo].[CFD] WITH CHECK ADD CONSTRAINT [FK3_CFD] FOREIGN KEY([ADJC_I])
REFERENCES [dbo].[ADJC_E] ([ADJC_I])
GO
ALTER TABLE [dbo].[CFD] CHECK CONSTRAINT [FK3_CFD]
GO
ALTER TABLE [dbo].[CFD] WITH CHECK ADD CONSTRAINT [CK_CFD] CHECK (([FILE_TYPE_C]<>'SFP'))
GO
ALTER TABLE [dbo].[CFD] CHECK CONSTRAINT [CK_CFD]
GO
CREATE NONCLUSTERED INDEX [IX_CFD_NRSC_FXTR_N] ON [dbo].[CFD]
(
[NRSC_FXTR_N] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO

Scalar_Variable Function with Multiple AND statements returning "NULL"

Im writing Scalar-Variable function in sql to return a strName mapped by an integer. The following is my script:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER FUNCTION [dbo].[Lookup_BSource_Value]
(
-- Add the parameters for the function here
#AVal nvarchar(100)
)
RETURNS nvarchar(100)
AS
BEGIN
-- Declare the return variable here
DECLARE #Val nvarchar(100)
SELECT #Val = Val
FROM SMBase
WHERE AName = 'a_source'
AND (OTypeCode = 1084)
AND (AVal = (#AVal))
RETURN #Val
END
I should be getting the result of "BA" but am receiving a "NULL". Is my syntax correct for the multiple AND statements?
EDIT*
Before use the function in my SSIS package I am just doing a simple
SELECT dbo.Lookup_BSource_Value(XXXXXXXXX)
This gives me the null.
The following is the logical schema of the table I am querying:
USE [MSCRM_M_RC]
GO
/****** Object: Table [dbo].[SMBase] Script Date: 1/21/2014 6:29:48 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[SMBase](
[OTypeCode] [int] NOT NULL,
[AName] [nvarchar](100) NOT NULL,
[AVal] [int] NOT NULL,
[LaId] [int] NOT NULL,
[OrgId] [uniqueidentifier] NOT NULL,
[Val] [nvarchar](4000) NULL,
[DOrder] [int] NULL,
[VNumber] [timestamp] NULL,
[SMId] [uniqueidentifier] NOT NULL,
CONSTRAINT [cndx_PrimaryKey_SMap] PRIMARY KEY CLUSTERED
(
[SMId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 80) ON [PRIMARY],
CONSTRAINT [UQ_SMap] UNIQUE NONCLUSTERED
(
[OTCode] ASC,
[AName] ASC,
[AValue] ASC,
[LaId] ASC,
[OrgId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 80) ON [PRIMARY]
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[SMBase] ADD CONSTRAINT [DF_SMa_SMId] DEFAULT (newid()) FOR [SMId]
GO
*EDIT**
The following is my logical schema of my StringMapTable:
StringMap(SMID pk, OTypeCode,AName, AVal, LaID, OrgID fk, Val, DOrder, VNumber)
The following is my logical schema of my TPTRepair Table:
TPTRepair(TPTRepairID pk, Name, Source, TT, LTHrs, CustID fk, PID fk)
The problem is the following:
The "Source" field is an integer in TPTRepair. I'm writing the following scalar-function to reference StringMap to return the string value from Value column in StringMap. I have to have a couple ands because AName hase to = 'a_source' and OTypeCode has to = 1084.
My scalar-function results in a NULL and shouldn't be. Is my syntax correct from the multiple AND statement in my scalar-function above?
So Im apparently an idiot. It was the most simplest thing. OTypeCode was to = '10084' rather than '1084'. Im an intern. Please forgive me ;) This was the answer.

LINQ query issue: returning multiple records

I have 2 tables. Problem is I always get multiple records no matter what I do.
Pages
SubMenus
Relation is 1 to 1 (each submenu has a page)
SubMenus sample data:
submenu_id parentmenu_id display_name url_name
----------------------------------------------------
1 1 Home home
2 1 Contact contact
Pages table data:
page_id submenu_id page_title url_name
---------------------------------------------------------
1 1 Home Page home
2 1 Contact Page null
I want to retrieve single value from there JOIN where SubMenu.UrlName == Home
(from s in SubMenus
join p in Pages on s.Id equals p.SubMenuId
where s.UrlName == "home"
select new
{
s.Id, s.UrlName,
PageId = p.Id, p.Title, p.Html,
p.MetaAuthor, p.MetaKeywords, p.MetaDescription
}).FirstOrDefault();
But if I check the SQL and run it. I get single record without any problem. Below is what SQL generated
SELECT TOP (1)
[Extent1].[submenu_id] AS [submenu_id],
[Extent1].[url_name] AS [url_name],
[Extent2].[page_id] AS [page_id],
[Extent2].[page_title] AS [page_title],
[Extent2].[page_html] AS [page_html],
[Extent2].[meta_author] AS [meta_author],
[Extent2].[meta_keywords] AS [meta_keywords],
[Extent2].[meta_description] AS [meta_description]
FROM
[dbo].[SubMenu] AS [Extent1]
INNER JOIN
[dbo].[Pages] AS [Extent2] ON [Extent1].[submenu_id] = [Extent2].[submenu_id]
WHERE
N'home' = [Extent1].[url_name]
Table structure:
CREATE TABLE [dbo].[ParentMenu]
(
[parentmenu_id] [int] IDENTITY(1,1) NOT NULL,
[group_name] [nvarchar](50) NULL,
[title] [nvarchar](100) NULL,
[active] [bit] NOT NULL,
[index_order] [int] NULL,
CONSTRAINT [PK_ParentMenu]
PRIMARY KEY CLUSTERED ([parentmenu_id] ASC)
WITH (PAD_INDEX = OFF, STATISTICS NORECOMPUTE = OFF,
IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON,
ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[ParentMenu]
ADD CONSTRAINT [DF_ParentMenu_active] DEFAULT ((1)) FOR [active]
GO
ALTER TABLE [dbo].[ParentMenu]
ADD CONSTRAINT [DF_ParentMenu_index_order] DEFAULT ((0)) FOR [index_order]
GO
CREATE TABLE [dbo].[SubMenu]
(
[submenu_id] [int] IDENTITY(1,1) NOT NULL,
[parentmenu_id] [int] NOT NULL,
[display_name] [nvarchar](100) NULL,
[url_name] [nvarchar](100) NULL,
[index_order] [int] NULL,
[active] [bit] NOT NULL,
CONSTRAINT [PK_SubMenu]
PRIMARY KEY CLUSTERED ([submenu_id] ASC)
WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF,
IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON,
ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
CONSTRAINT [IX_SubMenu_1]
UNIQUE NONCLUSTERED ([url_name] ASC)
WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF,
IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON,
ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[SubMenu] WITH CHECK
ADD CONSTRAINT [FK_SubMenu_ParentMenu]
FOREIGN KEY([parentmenu_id]) REFERENCES [dbo].[ParentMenu] ([parentmenu_id])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[SubMenu] CHECK CONSTRAINT [FK_SubMenu_ParentMenu]
GO
ALTER TABLE [dbo].[SubMenu]
ADD CONSTRAINT [DF_SubMenu_index_order] DEFAULT ((0)) FOR [index_order]
GO
ALTER TABLE [dbo].[SubMenu]
ADD CONSTRAINT [DF_SubMenu_active] DEFAULT ((1)) FOR [active]
GO
CREATE TABLE [dbo].[Pages]
(
[page_id] [int] IDENTITY(1,1) NOT NULL,
[submenu_id] [int] NOT NULL,
[page_title] [nvarchar](200) NULL,
[url_name] [nvarchar](100) NULL,
[page_html] [nvarchar](max) NULL,
[meta_author] [nvarchar](300) NULL,
[meta_keywords] [nvarchar](max) NULL,
[meta_description] [nvarchar](max) NULL,
[active] [bit] NOT NULL,
[creation_date] [date] NULL,
CONSTRAINT [PK_Pages]
PRIMARY KEY CLUSTERED ([page_id] ASC)
WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF,
IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON,
ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[Pages] WITH CHECK
ADD CONSTRAINT [FK_Pages_SubMenu]
FOREIGN KEY([submenu_id]) REFERENCES [dbo].[SubMenu] ([submenu_id])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[Pages] CHECK CONSTRAINT [FK_Pages_SubMenu]
GO
ALTER TABLE [dbo].[Pages]
ADD CONSTRAINT [DF_Pages_active] DEFAULT ((1)) FOR [active]
GO
You are saying that Problem is I always get multiple records no matter what I do.
The query that you show has top 1 in the very first line, it will always return just one row.
What's wrong with it?
From what I see your SQL query matches what your LINQ query does.
In this case LINQ query cannot possible return more rows than SQL returns.

Resources