SQL: 如何将多个参数声明为一个参数?

SQL: How Do you Declare multiple paramaters as one?

I am attempting to do the following


 1. Link two tables via a join on the same database
 2. Take a column that exists in both FK_APPLICATIONID(with a slight difference, 
    where one = +1 of the other I.e. Column 1 =1375 and column 2 = 1376
 3. In one of the tables exist a reference number (QREF1234) and the other
       contains 11 phonenumbers
 4. I want to be able to enter the Reference number, and it returns all 11
       phonenumbers as a single declarable value.
 5. use "Select * from TableD where phonenum in (@Declared variable)

这是我目前的情况,

Use Database 1

DECLARE @Result INT;

SELECT @Result = D.PhoneNum1, 

FROM Table1 

JOIN  TABLE2 D on D.FK_ApplicationID= D.FK_ApplicationID

where TABLE1.FK_ApplicationID = D.FK_ApplicationID + 1 
and QREF = 'Q045569/2'
Use Database2

Select * from Table3 where PhoneNum = '@result'

我向不理解我试图实现的目标的下面的人道歉,我希望这能解决问题。

谢谢

有几个选项,但最佳答案取决于您真正想要实现的目标。

有一个 SQL 技巧,您可以将值连接到一个变量中,例如;

create table dbo.t (i int, s varchar(10))
insert dbo.t values (1, 'one')
insert dbo.t values (2, 'two')
insert dbo.t values (3, 'three')
go

declare @s varchar(255)

select @s = isnull(@s + ', ', '') + s from t order by i
select @s

set @s = null
select @s = isnull(@s + ', ', '') + s from t order by i desc
select @s

或者,如果您只想要一个值,那么您可以使用 TOP 关键字,例如;

select top 1 @s = s from t order by i 
select @s

select top 1 @s = s from t order by i desc
select @s

或者,您可以使用三部分命名并跨数据库连接,例如;

SELECT T.*
FROM   DB1.dbo.Table1
       JOIN DB1.dbo.Table2 D
         ON D.FK_ApplicationID = D.FK_ApplicationID
       JOIN DB2.dbo.Table T
         ON T.PhoneNum = RIGHT(D.PhoneNum1, 11)
WHERE  DB1.dbo.FK_ApplicationID = D.dbo.FK_ApplicationID + 1
       AND Hidden = 'VALUE'

希望这对您有所帮助,

里斯