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

SQL:如何将多个参数声明为一个?,sql,sql-server,variables,declare,Sql,Sql Server,Variables,Declare,这是我到目前为止得到的 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 =

这是我到目前为止得到的

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)
我向下面的人道歉,他们不理解我试图实现的目标,我希望这能澄清这一点


谢谢

有一些选择,但最好的答案取决于你真正想要实现的目标

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

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'
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关键字,例如

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'
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
或者,您可以使用三部分命名,只需跨数据库连接,例如

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
希望这有帮助


Rhys

您在D.FK_ApplicationID=D.FK_ApplicationID上的行JOIN DB1.table2d是错误的。连接的两边都是一样的。你的代码毫无意义。它使用未定义的别名(如db1)和非感官比较(如D.FK_ApplicationID=D.FK_ApplicationID)。修正你的疑问。另外,添加示例数据和所需结果。为什么不在一个查询中引用表呢?语法类似于从MyDB1.dbo.table中选择*,其中从MyDB2.dbo.table中选择PhoneNumber1中的PhoneNumber1。因此,您的表结构有字段Phonenum1、Phonenum2、Phonenum3、…、Phonenum11,您想将电话号码与这些字段中的任何一个匹配吗?我根本不理解您的最终目标语句。老实说,我不知所措,我不明白这对我有什么帮助,我道歉。@Denslat-你试过运行我的第三个例子吗?您将需要更改对象名称以反映它们的真实情况,但它应该为您提供所需的内容。如果它不起作用,为什么不呢?