我在变量中声明了一个select查询。现在我想检查查询是否返回0行,然后我必须使用其他条件。我正在使用SQL SERVER 2012.如果变量包含0行,如何检查变量。请建议
set @sql = 'select tsf.StaffId,tsf.FullName,tsf.[Address],tsf.PhoneNo,tsf.Email,tsf.Gender,tsf.MobileNo1,tsf.MobileNo2, tsf.Post, tsf.Salary,ts.AdvanceSalary,ts.[Description],ts.[Month] from Tbl_Salary ts
JOIN Tbl_Staff tsf on ts.StaffId = tsf.StaffId'
If @CategoryId is not null
set @sql = @sql + ' where tsf.StaffId='''+cast(@CategoryId as varchar(10))+''''
If @MonthName is not null
set @sql = @sql +' and ts.Month='''+cast(@MonthName as varchar(50))+''''
If @Year is not null
set @sql = @sql +' and ts.Year='''+cast(@Year as varchar(50))+''''
exec(@sql)
答案 0 :(得分:2)
您只需将查询更改为
即可select COUNT(*)
from Tbl_Machine where MachineId = @MachineId
如果您只对计数感兴趣,则无需传输所有这些数据行。
此外,几乎所有数据库库在执行查询时都会返回一个包含行数的属性 - 您可能希望查看您正在使用的任何库。
查看您的更新,这里绝对不需要动态SQL - 使用它会破坏您的性能。你只需要一些条件逻辑
select tsf.StaffId,tsf.FullName,tsf. [Address],tsf.PhoneNo,tsf.Email,tsf.Gender,tsf.MobileNo1,tsf.MobileNo2, tsf.Post, tsf.Salary,ts.AdvanceSalary,ts.[Description],ts.[Month]
from Tbl_Salary ts
JOIN Tbl_Staff tsf on ts.StaffId = tsf.StaffId
WHERE (@CategoryId IS NULL OR tsf.StaffId=@CategoryID)
AND (@MonthName IS NULL OR ts.Month=@MonthName)
AND (@Year IS NULL OR and ts.Year=@Year)
答案 1 :(得分:1)
您还应该检查@@rowcount
,
返回受最后一个语句影响的行数。
因此,在您的查询后添加
IF @@ROWCOUNT =0
BEGIN
--do something
END
答案 2 :(得分:0)
if not exists
(select MachineId, MachineName, PurchasedDate, CompanyName, ModelNo, Amount, InsuranceCom,
MnthlyInstallAmt, TotalPaid, MnthlyInstallDate from Tbl_Machine
where MachineId = @MachineId)
begin
--returned 0 rows
--go with other conditions
end
答案 3 :(得分:0)
set @sql = "select count(temp_all.MachineId) AS 'Total_count' from
(select MachineId, MachineName, PurchasedDate, CompanyName, ModelNo,
Amount, InsuranceCom, MnthlyInstallAmt, TotalPaid, MnthlyInstallDate
from Tbl_Machine where MachineId = @MachineId) AS temp_all"