tSQL检查输入ID是否有效以及日期是否在当前年份

时间:2016-05-06 10:20:05

标签: sql sql-server tsql

我正在进行tSQL分配,其中一项要求是检查输入的charity ID是否存在,如果没有返回错误,那么我必须检查Tax Date该慈善机构是在今年。这就是我试过的

IF NOT EXISTS (SELECT CharityID FROM CharityTbl WHERE [CharityID] = '@CharityID')
begin
  raiserror ('Sorry Invalid Charity ID', 16,1)
  return 99 
end
--if the TaxNoDateOfIssue for the charitytbl is not in the current year raise an error
IF NOT Exists (Select TaxNoDateOfIssue FROM CharityTbl WHERE YEAR(TaxNoDateOfIssue) = YEAR(getdate())

我不确定如何编写第二个if语句,以便提供任何帮助

2 个答案:

答案 0 :(得分:2)

您只需在同一查询中附加where子句即可。见下面的查询。

IF NOT EXISTS (SELECT CharityID FROM CharityTbl WHERE [CharityID] = '@CharityID' or YEAR(TaxNoDateOfIssue) = YEAR(getdate())
begin
 raiserror ('Sorry Invalid Charity ID', 16,1)
 return 99 
end

答案 1 :(得分:2)

我希望这是你期待的事情。

IF EXISTS (SELECT CharityID FROM CharityTbl WHERE [CharityID] = '@CharityID') --  fist condition
BEGIN
IF NOT Exists (Select TaxNoDateOfIssue FROM CharityTbl WHERE YEAR(TaxNoDateOfIssue) = YEAR(getdate()) -- second condition if 1st success
BEGIN
RAISERROR('Sorry Invalid Tax Year', 16,1)
RETURN 99
END
END
ELSE
BEGIN
RAISERROR('Sorry Invalid Charity ID', 16,1) --  if 1st fails
RETURN 99 
END