0
IF NOT EXISTS (SELECT TOP 1 CityName FROM dbo.City WHERE [Name] = 'Default City')
BEGIN
INSERT dbo.City ( CityName, Status,CityCategoryId) VALUES  
(N'Default City', 0, (SELECT CityCategoryId FROM dbo.CityCategory WHERE [CityCategoryName] = N'Default City Category'))
END
GO

i have the the above query which runs fine in SQL server 2012 but fails in SQL Server 2005 with the below error message.

Subqueries are not allowed in this context. Only scalar expressions are allowed.

2
  • if N'Default City', 0 are hardcoded values use it in the select statement itself bu removing the keyword VALUES Commented Nov 17, 2014 at 6:42
  • This feature was introduced in SQL Server 2008. Hence, in the version below than this you need to declare variable and assign the value to variable and use it in INSERT statement. Commented Nov 17, 2014 at 6:50

3 Answers 3

1

Change your insert like this.

INSERT dbo.City
       (CityName,Status,CityCategoryId)
SELECT N'Default City',0,CityCategoryId
FROM   dbo.CityCategory
WHERE  [CityCategoryName] = N'Default City Category' 
Sign up to request clarification or add additional context in comments.

1 Comment

If there is no CityCategoryId for the select query. Then the values N'Default City',0 won't get inserted.
1

Try using variable @CityCategoryId. I don't know the type of @CityCategoryId. You can use datatype that you want.

IF NOT EXISTS (SELECT TOP 1 CityName FROM dbo.City WHERE [Name] = 'Default City')
BEGIN
    Declare @CityCategoryId AS NVARCHAR(100)
    SELECT @CityCategoryId = CityCategoryId FROM dbo.CityCategory 
           WHERE [CityCategoryName] = N'Default City Category'

    INSERT dbo.City( CityName, Status, CityCategoryId) 
    VALUES  
        (N'Default City', 0, @CityCategoryId)
END
GO

Comments

0

Try like this. Am not sure...

IF NOT EXISTS (SELECT TOP 1 CityName FROM dbo.City WHERE [Name] = 'Default City')
BEGIN
INSERT dbo.City ( CityName, Status,CityCategoryId)  
SELECT 'Default City',0, CityCategoryId FROM dbo.CityCategory WHERE [CityCategoryName] = N'Default City Category'
END
GO

2 Comments

If there is no CityCategoryId for the select query. Then the values N'Default City',0 won't get inserted.
Yea that's true.. Good find Bro.. I didn't noticed that

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.