简体   繁体   中英

SQL Sub-Select using primary Key

I'm looking to retrieve values from a sub-select query on a rowset where I only want values from the current row of the main query (SQL Server versions 2005-2012 have shown this same behavior). I've written a sub-select query which is returning multiple rows ( HOW , I'm matching on the primary KEY?!)

The following example code illustrates what I'm trying to accomplish:

CREATE TABLE [dbo].[TestTable]
(
    [TestID] [int] IDENTITY(1,1) NOT NULL,
    [TestValue] [nvarchar](255) NULL,
    [TestValue2] [nvarchar](255) NULL,
    [TestValue3] [nvarchar](255) NULL,
    [TestValue4] [nvarchar](255) NULL,

    PRIMARY KEY CLUSTERED ([TestID] ASC)
         WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, 
               ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO

INSERT INTO [TESTDB].[dbo].[TestTable] ([TestValue], [TestValue2], [TestValue3],[TestValue4])
VALUES('01234', '56789', '98765', '43210')
GO

INSERT INTO [TESTDB].[dbo].[TestTable] ([TestValue], [TestValue2], [TestValue3],[TestValue4])
VALUES('01234', '98765', '56789', '43210')
GO

INSERT INTO [TESTDB].[dbo].[TestTable] ([TestValue], [TestValue2], [TestValue3],[TestValue4])
VALUES('01234', '43210', '56789' ,'98765')
GO

INSERT INTO [TESTDB].[dbo].[TestTable] ([TestValue], [TestValue2], [TestValue3],[TestValue4])
VALUES('01234', '98765', '43210', '56789')
GO

SELECT TOP 1000 
     [TestID]
    ,[TestValue]
    ,[TestValue2]
    ,[TestValue3]
    ,(SELECT TestValue + TestValue2 AS CompositeValue 
      FROM [TESTDB].[dbo].TestTable AS foo 
      WHERE foo.TestID = TestID)
FROM 
    [TESTDB].[dbo].[TestTable]

Error being returned is:

Msg 512, Level 16, State 1, Line 2
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.

If you can offer an alternate way of performing this query - ie using ROW_NUMBER or some other method (without performing a select into a temporary table, and without declaring individual variables).

Thanks in advance!

Try to alias the base table

SELECT TOP 1000 [TestID]
,[TestValue]
,[TestValue2]
,[TestValue3]
,(SELECT foo.TestValue + foo.TestValue2 FROM [TESTDB].[dbo].TestTable AS foo WHERE     foo.TestID=B.TestID) AS CompositeValue
FROM [TESTDB].[dbo].[TestTable] AS B

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM