我有三种不同的类型1、2、3。
类型1与tableA关联 类型2与tableB关联 类型3与tableC相关联
现在,我必须运行以下查询:
Alter procedure TestProc @variableType int
As
begin
if @variableType = 'A' then
-- use tableA else tableB
IF NOT EXISTS (Select field from tableA)
print "hello"
end
已编辑: 更改后的实际查询现在看起来像这样:
if not exists(SELECT a.InstrumentId FROM tblARadiationLicenceRenewal a, tblA WHERE
a.RenewalStatusID <> 790 AND a.InstrumentID = 5051747
AND a.LicenceExpiryDate = tblA.ExpiryDate
union
SELECT a.InstrumentID FROM tblRadiationLicenceRenewal a, tblB WHERE
a.RenewalStatusID <> 790 AND a.InstrumentID = 5051747
AND a.LicenceExpiryDate = tblB.ExpiryDate
union
SELECT a.InstrumentID FROM tblRadiationLicenceRenewal a, tblC WHERE
a.RenewalStatusID <> 790 AND a.InstrumentID = 5051747
AND a.LicenceExpiryDate = tblC.ExpiryDate)
-- PRINT 'HELLO WORLD' (THERE ARE LONG QUERIES AND STORED PROCEDURE RUNNING HERE
如何动态更改表名。
答案 0 :(得分:0)
您只需要替换if,就可以做到,而不必担心动态sql:
Alter procedure TestProc @variableType int
As
if @variableType = 'A' then
begin
-- use tableA
IF NOT EXISTS (Select field from tableA)
print "hello"
end
else if @variableType = 'B' then
begin
-- use tableB
IF NOT EXISTS (Select field from tableB)
print "hello"
end
等等...这是SQL存储过程中条件的基本方法。 您可以在网上找到许多不同的方法。
答案 1 :(得分:0)
过程的语法如下-
CREATE PROCEDURE TestProc @variableType INT
AS
BEGIN
IF @variableType = 1
BEGIN
IF NOT EXISTS ( SELECT Your_Field FROM tableA)
PRINT 'Hello from table A'
END
ELSE IF @variableType = 2
BEGIN
IF NOT EXISTS ( SELECT Your_Field FROM tableB)
PRINT 'Hello from table B'
END
ELSE
BEGIN
IF NOT EXISTS ( SELECT Your_Field FROM tableC)
PRINT 'Hello from table C'
END
END