我正在尝试做一些我以前从未做过的事情。我有以下SQL查询:
SELECT a.UserID, u.Initials, u.Surname, u.Email, u.CountryID
FROM [dbo].[App] a
INNER JOIN [dbo].[User] u ON a.UserID = u.ID
WHERE a.ID = 46451
此查询返回以下信息:
UserID:51637
缩写:T
姓:测试员
电子邮件:petercash@live.co.za
CountryID:203
现在我想返回返回的CountryID,它是203并检查它是否存在于sadc表中,如果存在,则使用它从成本表中检索数据
IF ((SELECT COUNT(*) AS counted FROM [dbo].[Sadc] WHERE CountryID = 203) > 0)
SELECT Cost FROM [dbo].[Cost] WHERE ID = 4
第一个SQL Query中的a.ID
(在WHERE子句中)作为参数(因为值每次都会改变)。
然后获取CountryID
的值并将其传递给第二个查询并从Cost表中返回cost
答案 0 :(得分:2)
你几乎在你的问题中输入了最好的方法。
SELECT Cost
FROM [dbo].[Cost]
WHERE ID = 4
AND EXISTS (SELECT * FROM [dbo].[Sadc] WHERE CountryID = 203)
答案 1 :(得分:2)
您可以设置一个变量来保存该值,并使用EXISTS
语句检查它是否在表中:
-- variable to hold the value
DECLARE @CountryId INT
-- this set's the value of @CountryId
SELECT @CountryId = u.CountryID
FROM [dbo].[App] a
INNER JOIN [dbo].[User] u ON a.UserID = u.ID
WHERE a.ID = 46451
-- check if it exists in [Sadc]
IF EXISTS(SELECT 1 FROM [dbo].[Sadc] WHERE CountryID = @CountryId)
BEGIN
-- run your code if it exists
SELECT Cost FROM [dbo].[Cost] WHERE ID = 4
END