SQL 两个表中的重复条件
SQL Repeated Condition in Two Tables
我是 SQL 的初学者,我很难摆脱重复的代码。我有一个条件 "AccountId=20",我在 SQL 查询中使用了两次。 SQL 看起来像:
DELETE FROM Table_A WHERE FunctionId IN (Select FunctionId FROM Table_B WHERE AccountId=20);
DELETE FROM Table_B WHERE AccountId=20;
当我更改条件时,我必须更改代码中的两行。
我想清理重复的代码。我试过类似的东西:
DECLARE @condition datatypeForConditions = AccountId=20;
DELETE FROM Table_A WHERE FunctionId IN (Select FunctionId FROM Table_B WHERE @condition);
DELETE FROM Table_B WHERE @condition;
SQL 似乎没有条件数据类型,所以我不能声明这个变量。我什至可以为条件设置变量吗?我怎样才能避免在两个地方改变条件?
你可以这样实现
DECLARE @AccountId int;
@AccountID=20;
DELETE FROM Table_A WHERE FunctionId IN (Select FunctionId FROM Table_B WHERE AccountID=@AccountId);
DELETE FROM Table_B WHERE AccountID=@AccountId;
我是 SQL 的初学者,我很难摆脱重复的代码。我有一个条件 "AccountId=20",我在 SQL 查询中使用了两次。 SQL 看起来像:
DELETE FROM Table_A WHERE FunctionId IN (Select FunctionId FROM Table_B WHERE AccountId=20);
DELETE FROM Table_B WHERE AccountId=20;
当我更改条件时,我必须更改代码中的两行。
我想清理重复的代码。我试过类似的东西:
DECLARE @condition datatypeForConditions = AccountId=20;
DELETE FROM Table_A WHERE FunctionId IN (Select FunctionId FROM Table_B WHERE @condition);
DELETE FROM Table_B WHERE @condition;
SQL 似乎没有条件数据类型,所以我不能声明这个变量。我什至可以为条件设置变量吗?我怎样才能避免在两个地方改变条件?
你可以这样实现
DECLARE @AccountId int;
@AccountID=20;
DELETE FROM Table_A WHERE FunctionId IN (Select FunctionId FROM Table_B WHERE AccountID=@AccountId);
DELETE FROM Table_B WHERE AccountID=@AccountId;