这是我上一个问题的延续 sql update for dynamic row number
这次我有更新的要求。 我有两张桌子 CraftTypes &的 EmployeeCraftTypes
我需要更新 CraftType 表中的多行 我能够根据TheGameiswar
提供的答案更新它现在需求有一个修改。
在 CraftTypes 表格中, CraftTypeKey 列有一个外键引用,表格为 EmployeeCraftsTypes
如果 EmployeeCrafttypes 表中存在 CraftTypeKey 的条目,则不应更新该行。 此外,必须获取其行值未更新的 CraftTypeKey ,以便返回行的FK_restriction状态。
这是我正在使用的SQL查询。
CREATE TYPE [DBO].[DEPARTMENTTABLETYPE] AS TABLE
( DepartmentTypeKey SMALLINT, DepartmentTypeName VARCHAR(50),DepartmentTypeCode VARCHAR(10) , DepartmentTypeDescription VARCHAR(128) )
ALTER PROCEDURE [dbo].[usp_UpdateDepartmentType]
@DEPARTMENTDETAILS [DBO].[DEPARTMENTTABLETYPE] READONLY
AS
BEGIN
SET NOCOUNT ON;
DECLARE @rowcount1 INT
BEGIN
BEGIN TRY
BEGIN TRANSACTION
UPDATE D1
SET
D1.[DepartmentTypeName]=D2.DepartmentTypeName
,D1.[DepartmentTypeCode]=D2.DepartmentTypeCode
,D1.[DepartmentTypeDescription]=D2.DepartmentTypeDescription
FROM
[dbo].[DepartmentTypes] D1
INNER JOIN
@DEPARTMENTDETAILS D2
ON
D1.DepartmentTypeKey=D2.DepartmentTypeKey
WHERE
D2.[DepartmentTypeKey] not in (select 1 from [dbo].[EmployeeDepartment] where [DepartmentTypeKey]=D2.DepartmentTypeKey)
SET @ROWCOUNT1=@@ROWCOUNT
COMMIT
END TRY
BEGIN CATCH
SET @ROWCOUNT1=0
ROLLBACK TRAN
END CATCH
IF @rowcount1 =0
SELECT -174;
ELSE
SELECT 100;
END
END
请帮助 并提前致谢
答案 0 :(得分:0)
确定
我想我这次想办法了。我不确定这是正确的方法,但它足以让我满足要求。
我选择了来自 EmployeeCraftsTypes 表的FK引用的不同行作为第二个选择查询。
现在我可以获得由于FK约束而未更新的Row值。
这是我用过的SQL查询
ALTER PROCEDURE [dbo].[usp_UpdateCraftType]
@CRAFTDETAILS [DBO].[CRAFTTABLETYPE] READONLY
AS
BEGIN
SET NOCOUNT ON;
DECLARE @STATUSKEY TINYINT = (SELECT DBO.GETSTATUSKEY('ACTIVE'))
DECLARE @ROWCOUNT1 INT
BEGIN
BEGIN TRY
BEGIN TRANSACTION
UPDATE C1
SET
[C1].[CraftTypeName]=C2.CRAFTTYPENAME
,[C1].[CRAFTTYPEDESCRIPTION]=C2.CRAFTTYPEDESCRIPTION
,[C1].[StatusKey]=C2.[StatusKey]
FROM
[dbo].[CRAFTTYPES] C1
INNER JOIN
@CRAFTDETAILS C2
ON
C1.CRAFTTYPEKEY=C2.CRAFTTYPEKEY
WHERE
C2.[CRAFTTYPEKEY] NOT IN (SELECT EC.[CRAFTTYPEKEY] from [dbo].[EmployeeCrafts] EC where EC.[CRAFTTYPEKEY]=C2.[CRAFTTYPEKEY])
SET @ROWCOUNT1=@@ROWCOUNT
COMMIT
END TRY
BEGIN CATCH
SET @ROWCOUNT1=0
ROLLBACK TRAN
END CATCH
--SET @ROWCOUNT1 = @@ROWCOUNT
IF @ROWCOUNT1 =0
SELECT -172;
ELSE
BEGIN
SELECT 100;
SELECT DISTINCT EC.[CRAFTTYPEKEY],'Value Already Assigned' as Reason
FROM [DBO].[EmployeeCrafts] EC
JOIN @CRAFTDETAILS C3
on C3.[CRAFTTYPEKEY]=EC.[CRAFTTYPEKEY]
WHERE EC.[CRAFTTYPEKEY]=C3.[CRAFTTYPEKEY]
END
END
END
现在在Web API方面,我可以通过检查第二个表的rowcount来检查是否有任何更新失败。 如果行计数大于0,则可以生成更新错误消息
希望它会对某人有所帮助....