Error in T-SQL trigger being ignored in .NET application - c#

I've got a TableAdapter and I'm calling the Update(DataSet dataset) function of the adapter. There is a trigger on the underlying table that is throwing an error but this error is not causing an exception in the application after the select statement but it IS causing an exception if I just raise it at the beginning of the trigger. Any ideas?
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TRIGGER [dbo].[trigger1]
ON [dbo].[table1]
AFTER INSERT, UPDATE
AS
SET NOCOUNT ON;
SELECT a.description
FROM table1 a
INNER JOIN table2 b ON b.b_id = a.b_id
INNER JOIN inserted i ON i.b_id = a.b_id AND i.a_id = a.a_id
WHERE a.code = i.code
AND b.b_id <> i.b_id
AND a.description <> i.description
AND b.code IN (SELECT code FROM b WHERE b_id = i.b_id)
IF (##ROWCOUNT > 0)
BEGIN
RAISERROR ('ERROR', 16, 1)
ROLLBACK TRAN
RETURN
END
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO

It appears that you are examining ##ROW_COUNT to test for the existence of conflicting rows. Perhaps an EXISTS query would meet your needs:
IF EXISTS (
SELECT a.description
FROM table1 a
INNER JOIN table2 b ON b.b_id = a.b_id
INNER JOIN inserted i ON i.b_id = a.b_id AND i.a_id = a.a_id
WHERE a.code = i.code
AND b.b_id <> i.b_id
AND a.description <> i.description
AND b.code IN (SELECT code FROM b WHERE b_id = i.b_id)
)
BEGIN
RAISERROR ('ERROR', 16, 1)
ROLLBACK TRAN
RETURN
END
If the error still is not raised, then the business logic deserves a closer look.

Related

Dynamic SQL Pivot parameters query Entity Framework

I have a query which is working great when I used it in SQL Server Management Studio. It is worth to mention here that in PIVOT [MedicalInformation.MedicalInformationForm.Name.firstName] and [MedicalInformation.MedicalInformationForm.Name.lastName] are NOT static and can vary a.k.a they can be change during run time with different columns
WITH pivot_data AS
(
SELECT
[p].RecordId, -- Grouping Column
[Key], -- Spreading Column
[Value] -- Aggregate Column
FROM
[RecordDatas] AS [p]
INNER JOIN
(SELECT [p0].*
FROM [Records] AS [p0]
WHERE [p0].[IsDeleted] = 0) AS [t] ON [p].[RecordId] = [t].[ID]
WHERE
[p].DatasetId = 1386
AND [p].[IsDeleted] = 0
AND ([t].[ProjectID] = 191)
AND [Key] IN ('MedicalInformation.MedicalInformationForm.Name.firstName',
'MedicalInformation.MedicalInformationForm.Name.lastName')
)
SELECT
RecordId,
[MedicalInformation.MedicalInformationForm.Name.firstName],
[MedicalInformation.MedicalInformationForm.Name.lastName]
FROM
pivot_data
PIVOT
(MAX([Value])
FOR [Key] IN ([MedicalInformation.MedicalInformationForm.Name.firstName],
[MedicalInformation.MedicalInformationForm.Name.lastName])) AS p
The problem occurs when I'm trying to build the same query dynamic from C#:
var sql1 = #"
WITH pivot_data AS
(
SELECT [p].RecordId, -- Grouping Column
[Key], -- Spreading Column
[Value] -- Aggregate Column
FROM [RecordDatas] AS [p]
INNER JOIN (
SELECT [p0].*
FROM [Records] AS [p0]
WHERE [p0].[IsDeleted] = 0
) AS [t] ON [p].[RecordId] = [t].[ID]
where [p].DatasetId = 1386
AND [p].[IsDeleted] = 0
AND ([t].[ProjectID] = 191)
AND [Key] IN( {0} , {1}))
SELECT RecordId, {2},{3}
FROM pivot_data
PIVOT (max([Value]) FOR [Key] IN ({2},{3})) AS p;";
await repositoryMapper.Repository.Context.Database.ExecuteSqlCommandAsync(sql1,
"MedicalInformation.MedicalInformationForm.Name.firstName",
"MedicalInformation.MedicalInformationForm.Name.lastName",
"[MedicalInformation.MedicalInformationForm.Name.firstName]",
"[MedicalInformation.MedicalInformationForm.Name.lastName]");
And here is coming my problem - when query is generated with ExecuteSqlCommandAsync and adding parameters for the PIVOT columns ([MedicalInformation.MedicalInformationForm.Name.firstName] and [MedicalInformation.MedicalInformationForm.Name.lastName]) there is something wrong with syntax. I'm getting an error:
Incorrect syntax near '#p2'.
I have tried to get the generated query which Entity Framework is doing and it looks like this :
exec sp_executesql N'
WITH pivot_data AS
(
SELECT [p].RecordId, -- Grouping Column
[Key], -- Spreading Column
[Value] -- Aggregate Column
FROM [RecordDatas] AS [p]
INNER JOIN (
SELECT [p0].*
FROM [Records] AS [p0]
WHERE [p0].[IsDeleted] = 0
) AS [t] ON [p].[RecordId] = [t].[ID]
where [p].DatasetId = 1386
AND [p].[IsDeleted] = 0
AND ([t].[ProjectID] = 191)
AND [Key] IN( #p0 , #p1))
SELECT RecordId, #p2,#p3
FROM pivot_data
PIVOT (max([Value]) FOR [Key] IN (#p2,#p3)) AS p;
',N'#p0 nvarchar(4000),
#p1 nvarchar(4000),
#p2 nvarchar(4000),
#p3 nvarchar(4000)',
#p0=N'MedicalInformation.MedicalInformationForm.Name.firstName',
#p1=N'MedicalInfo rmation.MedicalInformationForm.Name.lastName',
#p2=N'[MedicalInformation.MedicalInformationForm.Name.firstName]',
#p3=N'[MedicalInformation.MedicalInformationForm.Name.lastName]'
Please help me I'm not sure what is the problem here
The problem is that a line like this:
SELECT RecordId, #p2,#p3
is not valid. Statements are precompiled and you can not change field names in parameters - field names for a statement are static.
You have to go into dynamic SQL, which EntityFramework does not support (outside of the functions allowing you to submit whatever SQL you want). Basically you must create the valid statement in a way that is NOT using parameters are field names.
This does NOT mean you can not use placeholders and - in C# - run a replace operation on the string, but it means that the replacement has to be finished when you THEN submit the changed script to the database.
Limitation of SQL Server.
You can not assign value of these #p2,#p3 in SELECT RecordId, #p2,#p3 from parameter. You need to set these statement before running query as follow:
var sql1 = #"
WITH pivot_data AS
(
SELECT [p].RecordId, -- Grouping Column
[Key], -- Spreading Column
[Value] -- Aggregate Column
FROM [RecordDatas] AS [p]
INNER JOIN (
SELECT [p0].*
FROM [Records] AS [p0]
WHERE [p0].[IsDeleted] = 0
) AS [t] ON [p].[RecordId] = [t].[ID]
where [p].DatasetId = 1386
AND [p].[IsDeleted] = 0
AND ([t].[ProjectID] = 191)
AND [Key] IN( {0} , {1}))
SELECT RecordId, [MedicalInformation.MedicalInformationForm.Name.lastName],[MedicalInformation.MedicalInformationForm.Name.lastName]
FROM pivot_data
PIVOT (max([Value]) FOR [Key] IN ({2},{3})) AS p;";
await repositoryMapper.Repository.Context.Database.ExecuteSqlCommandAsync(sql1,
"MedicalInformation.MedicalInformationForm.Name.firstName",
"MedicalInformation.MedicalInformationForm.Name.lastName",
"[MedicalInformation.MedicalInformationForm.Name.firstName]",
"[MedicalInformation.MedicalInformationForm.Name.lastName]");

Sql execption: Maximum stored procedure..level exceeded

This is the first time im using caches. I set my local cache to true in my webconfig.When i try to run my login page is gives the following error
System.Data.SqlClient.SqlException occurred
HResult=0x80131904
Message=Maximum stored procedure, function, trigger, or view nesting level exceeded (limit 32).
Source=.Net SqlClient Data Provider
StackTrace:
it throws the error on the following code
lock (lastlevelLock)
{
DataSet retval = new DataSet();
if (UseLocalCache)
{
retval =Data.DataRepository.Provider.GetDetailsAll(); // this is where the error comes in
if (retval == null)
retval = new DataSet();
}
else
what am i doing wrong? because the exact same code and db works fine on other machines.I did look at the other similar errors mention on stackflow but nothing helped.
--WITH ENCRYPTION
AS
BEGIN
;WITH cte AS (
SELECT //do selection
FROM Table g WITH(NOLOCK)
)
SELECT //do selection
INTO #cte
FROM cte c
INNER JOIN list.Type gt WITH(NOLOCK) ON c.TypeId = gt.TypeID
INNER JOIN table.crumb br WITH(NOLOCK) ON c.ID = br.ID
ORDER BY Lev
SELECT
// select columns
NULL AS ResultExpected
INTO #TempGame
FROM #cte tg
JOIN list.Type gt WITH(NOLOCK) ON tg.TypeID = gt.TypeID
WHERE tg.ID IN (
SELECT ID FROM table2 WITH(NOLOCK)
WHERE ID = tg.ID
)
SELECT
//select columns
INTO #Temp2
FROM tanbe2 m WITH(NOLOCK)
INNER JOIN table g WITH(NOLOCK) ON m.ID = g.ID
//perform all joins
WHERE m.ID IN (SELECT ID FROM #Temp)
GETDATE() < ISNULL(m.ResultDateTime, m.ResultExpected)
SELECT * FROM #Temp
SELECT * FROM #Temp2
ORDER BY ResultExpected
DROP TABLE #cte
DROP TABLE #Temp
DROP TABLE #Temp2
END
GO
After searching and trying different solutions for multiple hours,i finally just restored the db AGAIN and it seemed to work.

Invalid object using WITH common table expression

I am trying to use With in stored procedure
USE [BusOprtn]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[AddRepairedStock]
#RepairedItems [dbo].[RepairedItems] readonly
AS
BEGIN
declare #productNo bigint,#productManufacturer bigint
SET NOCOUNT ON;
begin try
begin transaction
UPDATE [BusOprtn].[dbo].[RepairItem] SET [ReturnedQuantity] = rdi.ReturnedQuantity,[AmountPaid] = rdi.AmountPaid,[ReturnDate] = rdi.ReturnDate from [BusOprtn].[dbo].[RepairItem] as ri inner join #RepairedItems as rdi on ri.id=rdi.id;
;with y as (
select [PartUsedId],rdi.[ReturnedQuantity] from [BusOprtn].[dbo].[RepairItem] as ri inner join #RepairedItems as rdi on ri.Id=rdi.id
), x as (
SELECT [PartNo] ,[ManufacturerId],[ReturnedQuantity] FROM [BusOprtn].[dbo].[PartUsed] as p inner join y
on p.id = y.PartUsedId
)
UPDATE [BusOprtn].[dbo].[ProductMaster] SET [RepairedStock] =( [RepairedStock]+x.[ReturnedQuantity]) from [BusOprtn].[dbo].[ProductMaster] as pm inner join x on x.[PartNo]=pm.Id;
UPDATE [BusOprtn].[dbo].[ProductStockManufacturer] SET [RepairedCurrentStock] = ([RepairedCurrentStock]+x.[ReturnedQuantity]) from [BusOprtn].[dbo].[ProductStockManufacturer] as pm inner join x on x.[PartNo]=pm.[ProductNo] and x.[ManufacturerId]= pm.[ManufacturerId];
commit transaction
end try
BEGIN CATCH
declare #ErrorMessage nvarchar(max), #ErrorSeverity
int, #ErrorState int;
select #ErrorMessage = ERROR_MESSAGE() + ' Line ' + cast
(ERROR_LINE() as nvarchar(5)), #ErrorSeverity = ERROR_SEVERITY(),
#ErrorState = ERROR_STATE();
rollback transaction;
raiserror (#ErrorMessage, #ErrorSeverity, #ErrorState);
END CATCH
END
When i execute above command it executes successfully. But when i try to call stored procedure at runtime it gives error
`Invalid object name 'x'.
Transaction count after EXECUTE indicates a mismatching number of BEGIN and COMMIT statements. Previous count = 0, current count = 1.`
Earlier problem was with sub query as it not allowed with "WITH" so tried using another temp table y but error continued. I refereed Allowed Items for allowed items in WITH.
The error comes from the second update statement where you are using the CTE x
The scope for a CTE is one statement so x is only visible for the first update.
To fix this you can either duplicate the code for the CTE before the second update or you can use a temp table (or table variable) to capture the output from x and use the temp table in both your update statements instead of the CTE.
With a different formatting of the code this is easy to see.
First update statement:
with y as
(
select [PartUsedId],
rdi.[ReturnedQuantity]
from [BusOprtn].[dbo].[RepairItem] as ri
inner join #RepairedItems as rdi
on ri.Id=rdi.id
), x as
(
SELECT [PartNo],
[ManufacturerId],
[ReturnedQuantity]
FROM [BusOprtn].[dbo].[PartUsed] as p
inner join y
on p.id = y.PartUsedId
)
UPDATE [BusOprtn].[dbo].[ProductMaster]
SET [RepairedStock] = ([RepairedStock]+x.[ReturnedQuantity])
from [BusOprtn].[dbo].[ProductMaster] as pm
inner join x
on x.[PartNo]=pm.Id;
Second update statement:
UPDATE [BusOprtn].[dbo].[ProductStockManufacturer]
SET [RepairedCurrentStock] = ([RepairedCurrentStock]+x.[ReturnedQuantity])
from [BusOprtn].[dbo].[ProductStockManufacturer] as pm
inner join x
on x.[PartNo]=pm.[ProductNo] and x.[ManufacturerId]= pm.[ManufacturerId];
You can try to use SQL Server Profiler (Service menu in MSSMS). There you can find what query exactly received. Maybe something is different.
Hope it will help.

Retrieve multiple data from stored procedure using Linq-to-SQL

I am using Silverlight and Linq-to-SQL to communicate with the database.
I have a stored procedure which receives 2 parameters (PFOID and Quantity) and Userid and returns a product name.
If we send multiple values like multiple pfoid's and quantity's it will return multiple product names shown as below
The stored procedure looks like this..
ALTER PROCEDURE [PFO].[PFOValidateUpdateData]
#PfoIDs xml, -- list of PFO ID's
#UserID uniqueidentifier --The Identity of the User making the call.
AS
BEGIN
-- SET DEFAULT BEHAVIOR
SET NOCOUNT ON -- Performance: stops rows affected messages
SET DEADLOCK_PRIORITY LOW -- This SP to be the Deadlock victim
-- Initialise Lock-Timeout and Deadlock vars for Insert
DECLARE #iLockTimeoutRetries as int
DECLARE #iDeadLockRetries as int
DECLARE #dtLockTimeoutSleepInterval as datetime
DECLARE #dtDeadlockSleepInterval as datetime
DECLARE #iErrorNumber as int
SET #iLockTimeoutRetries = 0
SET #iDeadLockRetries = 0
SET #dtLockTimeoutSleepInterval = sCommon.fnLockTimeoutSleepInterval()
SET #dtDeadlockSleepInterval= sCommon.fnDeadlockSleepInterval()
SET #iErrorNumber = 0
-- procedure specific
DECLARE #idoc as int
DECLARE #IsBrightstarUser as bit
RETRY:
BEGIN TRY
--Create Temp table to store stores!
CREATE TABLE [#PFOList]
(
[PFOId] nvarchar(50),
[Quantity] INT
)
--Create Temp table to store User stores!
CREATE TABLE [#UserStoreList]
(
[StoreID_XRef] nvarchar(50)
)
print CONVERT(varchar(1000), #PfoIDs)
--Create Document
EXEC sp_xml_preparedocument #idoc OUTPUT, #PfoIDs
-- Append to new list of Store records
INSERT INTO [#PFOList] (
[PFOId],
[Quantity]
)
SELECT [PFOID],[Quantity]
FROM OPENXML (#idoc, 'ArrayOfString/string',2)
WITH( [PFOID] nvarchar(50),[Quantity] [INT]) Stores
--WHERE [PFOId] Is Not NULL
-- Clean UP
exec sp_xml_removedocument #iDoc
-- are we dealing with a brightstar user?
SET #IsBrightstarUser = CASE WHEN exists
(SELECT *
FROM dbo.aspnet_UsersInRoles AS uir inner join
dbo.aspnet_Roles AS roles ON uir.RoleId = roles.roleid
WHERE roles.rolename = 'Brightstar Employee' and uir.userid = #userid)
THEN 1 ELSE 0 END
--Get User Storelist
INSERT INTO [#UserStoreList] (
[StoreID_XRef]
)
SELECT s.StoreId_XRef
FROM PFO.UserStoreLink us(nolock)
INNER JOIN PFO.Store s(nolock)
ON us.StoreId=s.StoreId
where UserId=#UserID
--Select * from [#PFOList]
--SELECT #IsBrightstarUser AS ISBrightstaruser
--SELECT * from [#UserStoreList]
--If BrightstarCustomer Update all the Quantities.
IF #IsBrightstarUser=1
BEGIN
UPDATE
PFO.PFO
SET
IsBrightstarReviewComplete = 1
,[ModifyingUsersID] = #UserID
,[ModifiedDate] = getdate()
,[PlannedQty] = pfol.[Quantity]
,[BrightstarReviewedQty]=pfol.[Quantity]
FROM
PFO.PFO as pfo
INNER JOIN [#UserStoreList] as stores on pfo.StoreId_XRef=stores.StoreID_XRef
INNER JOIN [#PFOList] as pfol on pfo.PFOId = pfol.PFOId
WHERE #IsBrightstarUser = 1
END
ELSE BEGIN
--Update Non Contrained Orders
UPDATE
PFO.PFO
SET
[ModifyingUsersID] = #UserID
,[ModifiedDate] = getdate()
,[PlannedQty] = pfol.[Quantity]
FROM
PFO.PFO (nolock) as pfo
INNER JOIN [#UserStoreList] as stores on pfo.StoreId_XRef=stores.StoreID_XRef
INNER JOIN [#PFOList] as pfol on pfo.PFOId = pfol.PFOId
WHERE pfo.IsBrightstarReviewComplete=1 AND IsConstraint=0
--SELECT * from PFO.PFO (nolock) where PFOId='04676723-2afb-49ff-9fa1-0131cabb407c'
--Update Contrained Orders
--Get Existing quantities for the User
CREATE TABLE #ExistingProductQuantity
(
[PfoID] nvarchar(100)
,[Product] nvarchar(255)
,[PlannedQty] INT
,[BrightstarReviewedQty] INT
)
CREATE TABLE #CustProductQuantity
(
[Product] nvarchar(255)
,[IsUpdatable] BIT
)
INSERT INTO #ExistingProductQuantity
( [PfoID],[Product],[PlannedQty],[BrightstarReviewedQty])
SELECT PFOId,InventoryId,PlannedQty,BrightstarReviewedQty
FROM PFO.PFO as pfo
INNER JOIN [#UserStoreList] as stores on pfo.StoreId_XRef=stores.StoreID_XRef
WHERE pfo.IsBrightstarReviewComplete=1 AND IsConstraint=1
UPDATE
#ExistingProductQuantity
SET [PlannedQty]=pfol.[Quantity]
FROM #ExistingProductQuantity eoq
INNER JOIN [#PFOList] as pfol on eoq.PFOId = pfol.PFOId
INSERT INTO #CustProductQuantity
( [Product],[IsUpdatable] )
SELECT
[Product],
CASE WHEN SUM(PlannedQty)<=SUM(BrightstarReviewedQty) THEN 1 ELSE 0 END
FROM #ExistingProductQuantity
GROUP BY [Product]
--SELECT * from #ExistingProductQuantity
--SELECT * from #CustProductQuantity
--Update the products that can be updatable
UPDATE
PFO.PFO
SET
[ModifyingUsersID] = #UserID
,[ModifiedDate] = getdate()
,[PlannedQty] = pfol.[Quantity]
FROM
PFO.PFO as pfo
INNER JOIN #UserStoreList as stores on pfo.StoreId_XRef=stores.StoreID_XRef
INNER JOIN #PFOList as pfol on pfo.PFOId = pfol.PFOId
INNER JOIN #CustProductQuantity as pr on pr.Product=pfo.InventoryId
WHERE pfo.IsBrightstarReviewComplete=1 AND pr.IsUpdatable=1 AND IsConstraint=1
--Return the products that are not updatabele
select [Product]
FROM #CustProductQuantity
where [IsUpdatable]=0
END
END TRY
BEGIN CATCH
-- Get the ErrorNumber
Set #iErrorNumber = ERROR_NUMBER()
--Handle Deadlock situation (Deletes, Inserts & Updates)
IF #iErrorNumber = 1205
BEGIN
-- If we have not made enough attempts to break the lock
IF #iDeadLockRetries < sCommon.fnMaxDeadlockRetries()
BEGIN
-- Increment the Attempt count
SET #iDeadLockRetries = #iDeadLockRetries + 1
-- Pause to allow the deadlock contention to clear
WAITFOR DELAY #dtDeadlockSleepInterval
GOTO RETRY
END
END
-- Handle Lock Timeout situation (Deletes, Inserts & Updates)
IF #iErrorNumber = 1222
BEGIN
-- If we have not made enough attempts to break the Deadlock
IF #iLockTimeoutRetries < sCommon.fnMaxLockTimeoutRetries()
BEGIN
-- Increment the Attempt count
SET #iLockTimeoutRetries = #iLockTimeoutRetries + 1
-- Pause to allow the lock contention to clear
WAITFOR DELAY #dtLockTimeoutSleepInterval
GOTO RETRY
END
END
exec Common.RethrowError
END CATCH
END
The result is as follows..
Product
6435LVWK-360-CD819E3
NSCHI535C1097I360-4C
NSCHU485C1819I360-0C
Return Value
0
My Linq-to-SQL connection is like this
[global::System.Data.Linq.Mapping.FunctionAttribute(Name="PFO.PFOValidateUpdateData")]
public int PFOValidateUpdateData([global::System.Data.Linq.Mapping.ParameterAttribute(Name = "PfoIDs", DbType = "Xml")] System.Xml.Linq.XElement pfoIDs, [global::System.Data.Linq.Mapping.ParameterAttribute(Name = "UserID", DbType = "UniqueIdentifier")] System.Nullable<System.Guid> userID)
{
IExecuteResult result = this.ExecuteMethodCall(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())), pfoIDs, userID);
return ((int)(result.ReturnValue));
}
I am trying to retrieve all the data from the stored procedure but the when I debugging it the return value is "o"..
I would be grateful to you if you could help me retrieve all the data returned by the stored procedure... thank you very much...
If your stored procedure returns a collection of nvarchar's, then the signature of your Linq2Sql method is not correct. It should not return an int, but an ISingleResult.
So the correct signature will be:
public ISingleResult<string> PFOValidateUpdateData(...)
{
IExecuteResult result = this....;
return (ISingleResult<string>)result.ReturnValue;
}
var products = PFOValidateUpdateData(...).ToList();
If you want to return the results from multiple SELECT's in your stored procedure, you'll have to use IMultipleResults.
Well I know this is not the right way...for time being,its working for me...
I created an other table with two columns one ProductId and ID, I am inserting the values returned by the stored procedure,
in the designer.cs I am returning the table,
[global::System.Data.Linq.Mapping.FunctionAttribute(Name="PFO.PFOValidateUpdateData")]
public ISingleResult<PFOValidData> PFOValidateUpdateData([global::System.Data.Linq.Mapping.ParameterAttribute(Name = "PfoIDs", DbType = "Xml")] System.Xml.Linq.XElement pfoIDs, [global::System.Data.Linq.Mapping.ParameterAttribute(Name = "UserID", DbType = "UniqueIdentifier")] System.Nullable<System.Guid> userID)
{
IExecuteResult result = this.ExecuteMethodCall(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())), pfoIDs, userID);
return ((ISingleResult<PFOValidData>)(result.ReturnValue));
}
And in the Domainservice
List<string> PFOValidateUpdateData(string pfoIds, Guid userID)
{
List<string> productIdList = new List<string>();
// Acquire the int
result = this.DataContext.PFOValidateUpdateData(element, userID);
foreach (var item in result)
{
productIdList.Add(item.ProductID);
}
return productIdList;
To get the multiple values returned by the stored procedure....
Please let me know if there is a better way to solve this... thank you

SQL Server: Check if Child Rows Exist

I am working on a web application where there are many tables but two will suffice to illustrate my problem:
User
Order
Let us say that the User table has a primary key "UserID", which is a foreign key in the Order table called "CreatedBy_UserID".
Before deleting a User, I would like to check if the Order table has a record created by the soon-to-be deleted user.
I know that a SqlException occurs if I try to delete the user but let us say that I want to check beforehand that the Order table does not have any records created by this user? Is there any SQL code which I could run which will check all foreign keys of a table if that row is being referenced?
This for me is generally useful code as I could remove the option for deletion altogether if it can be detected that the user exists in these other tables.
I don't want a simple query (SELECT COUNT(*) FROM Order WHERE CreatedBy_UserID == #userID) because this will not work if I create another foreign key to the Order table. Instead I want something that will traverse all foreign keys.
Can this be done?
Below is code for an sp that I've used in the past to perform this task (please excuse the indenting):
create proc dbo.usp_ForeignKeyCheck(
#tableName varchar(100),
#columnName varchar(100),
#idValue int
) as begin
set nocount on
declare fksCursor cursor fast_forward for
select tc.table_name, ccu.column_name
from
information_schema.table_constraints tc join
information_schema.constraint_column_usage ccu on tc.constraint_name = ccu.constraint_name join
information_schema.referential_constraints rc on tc.constraint_name = rc.constraint_name join
information_schema.table_constraints tc2 on rc.unique_constraint_name = tc2.constraint_name join
information_schema.constraint_column_usage ccu2 on tc2.constraint_name = ccu2.constraint_name
where tc.constraint_type = 'Foreign Key' and tc2.table_name = #tableName and ccu2.column_name = #columnName
order by tc.table_name
declare
#fkTableName varchar(100),
#fkColumnName varchar(100),
#fkFound bit,
#params nvarchar(100),
#sql nvarchar(500)
open fksCursor
fetch next from fksCursor
into #fkTableName, #fkColumnName
set #fkFound = 0
set #params=N'#fkFound bit output'
while ##fetch_status = 0 and coalesce(#fkFound,0) <> 1 begin
select #sql = 'set #fkFound = (select top 1 1 from [' + #fkTableName + '] where [' + #fkColumnName + '] = ' + cast(#idValue as varchar(10)) + ')'
print #sql
exec sp_executesql #sql,#params,#fkFound output
fetch next from fksCursor
into #fkTableName, #fkColumnName
end
close fksCursor
deallocate fksCursor
select coalesce(#fkFound,0)
return 0
end
This will select a value of 1 if a row has any foreign key references.
The call you would need would be:
exec usp_ForeignKeyCheck('User','UserID',23)
There is no clean way to iterate through all FK columns where multiple exist. You'd have to build some dynamic SQL to query the system tables and test each in turn.
Personally, I wouldn't do this. I know what FKs I have: I'll test each in turn
...
IF EXISTS (SELECT * FROM Order WHERE CreatedBy_UserID == #userID)
RAISERROR ('User created Orders ', 16, 1)
IF EXISTS (SELECT * FROM Order WHERE PackedBy_UserID == #userID)
RAISERROR ('User packed Orders', 16, 1)
...
You wouldn't dynamically iterate through each property of some user object and generically test each one would you? You'd have code for each property
This code will give you a list of the foreign keys which are defined for a specifit table:
select distinct name from sys.objects
where object_id in ( select constraint_object_id from sys.foreign_key_columns as fk
where fk.Parent_object_id = (select object_id from sys.tables
where name = 'tablename') )
You can use transaction to check it.
I know it seems like stone ax, but it working fast and stable.
private bool TestUser(string connectionString, int userID)
{
var result = true;
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
var command = connection.CreateCommand();
var transaction = connection.BeginTransaction();
command.Connection = connection;
command.Transaction = transaction;
try
{
command.CommandText = "DELETE User WHERE UserID = " + userID.ToString();
command.ExecuteNonQuery();
transaction.Rollback();
}
catch
{
result = false;
}
}
return result;
}

Categories