插入一个表值进行查询

时间:2013-10-29 07:56:18

标签: sql sql-server stored-procedures

使用值

myTbl
ID  Number
1    12458
2    45896  
3    12458
4    87456

具有以下查询:

SELECT TOP 1 n.abonent_name , ad.address
FROM dbo.names n 
INNER JOIN dbo.addresses ad on n.address_id = ad.id
WHERE n.number = (every number from myTbl)

希望在myTbl中插入查询 Where子句每个数字,然后将每个数字的响应插入虚拟表 #tbl ,例如插入#tbl abonent_name和地址number = 12458 ,在此插入之后,在where子句中写入另一个数字45896然后插入#tbl等等。

CREATE TABLE #tbl
(
   id identity(1,1),
   abonent_name varchar(20),
   address varchar(50)
)

想要在没有光标的情况下编写

2 个答案:

答案 0 :(得分:1)

SELECT TOP 1 n.abonent_name , ad.address
FROM dbo.names n 
INNER JOIN dbo.addresses ad on n.address_id = ad.id
WHERE n.number IN (SELECT number from myTbl)

尝试上面。但是你可以通过以下方式一举两得:

SELECT  ROW_NUMBER() OVER (order by n.abonent_name) AS ID, n.abonent_name , ad.address
INTO #tbl
FROM dbo.names n 
INNER JOIN dbo.addresses ad on n.address_id = ad.id
WHERE n.number IN (SELECT number from myTbl)

答案 1 :(得分:0)

您不需要使用光标。 如果addresses表中每个名称可以有多于1行,则可以使用以下模式:

INSERT INTO #tbl (abonent_name, address)
SELECT x.abonent_name, x.address
from
(
    SELECT
      ROW_NUMBER() OVER (PARTITION BY n.abonent_name
                         ORDER BY n.abonent_name, x.address) AS RowNumber,
      n.abonent_name,
      ad.address
    FROM dbo.names n 
    INNER JOIN myTbl tbl on n.number = tbl.number
    INNER JOIN dbo.addresses ad on n.address_id = ad.id
) x
where x.RowNumber = 1
order by x.RowNumber;

此代码将在 #tbl 表中插入 myTbl 表中存在的每个名称的第一个(字母)地址。名称将按字母顺序升序排序。条件x.RowNumber=1将在多个匹配的情况下过滤第一个地址。