January 18, 2022 at 7:10 pm
Hi all,
I have a variable to declare, and this works:
Declare @CopyFromUser Varchar(10) =
(Select Top 1 Op_Ref From [MyServername].[TemperTest_BATON].[dbo].Op Where Op_Forename+' '+Op_Surname = @CopyFromUserFull)
However, the Op_Ref could be in any combination of 5 databases with thankfully identical schema, so I need to select against them, the following is as far as I've got but is still erroring out, could use a hand 🙂
Declare @CopyFromUser Varchar(10) = (Select Top 1 * from
(Select Op_Ref From [MyServername].[TemperTest_BATON].[dbo].Op Where Op_Forename = 'Alice'
And Op_Surname = 'Cooper'
Union
Select Op_Ref From [MyServername].[TemperTest_SERGEI].[dbo].Op Where Op_Forename = 'Alice'
And Op_Surname = 'Cooper'
Union
Select Op_Ref From [MyServername].[TemperTest_PRO].[dbo].Op Where Op_Forename = 'Alice'
And Op_Surname = 'Cooper'
Union
Select Op_Ref From [MyServername].[TemperTest_C30].[dbo].Op Where Op_Forename = 'Alice'
And Op_Surname = 'Cooper'
Union
Select Op_Ref From [MyServername].[TemperTest_ROp].[dbo].Op Where Op_Forename = 'Alice'
And Op_Surname = 'Cooper'))
TIA
January 18, 2022 at 8:10 pm
You will need an alias for the derived table containing the unions.
Just add "AS a" after the final close bracket/parenthesis. (Ironically the TIA from your message would probably have sufficed).
Without an alias, you will see this error message "Incorrect syntax near ')'."
January 18, 2022 at 8:33 pm
What is the error?
I'd guess it's related to not having aliased the subquery -- e.g.,
Declare @CopyFromUser Varchar(10) = (Select Top 1 * from
(Select Op_Ref From [MyServername].[TemperTest_BATON].[dbo].Op Where Op_Forename = 'Alice'
And Op_Surname = 'Cooper'
Union
Select Op_Ref From [MyServername].[TemperTest_SERGEI].[dbo].Op Where Op_Forename = 'Alice'
And Op_Surname = 'Cooper'
Union
Select Op_Ref From [MyServername].[TemperTest_PRO].[dbo].Op Where Op_Forename = 'Alice'
And Op_Surname = 'Cooper'
Union
Select Op_Ref From [MyServername].[TemperTest_C30].[dbo].Op Where Op_Forename = 'Alice'
And Op_Surname = 'Cooper'
Union
Select Op_Ref From [MyServername].[TemperTest_ROp].[dbo].Op Where Op_Forename = 'Alice'
And Op_Surname = 'Cooper') Ops
)
January 18, 2022 at 9:48 pm
The alias indeed, but after the penultimate closing bracket 🙂
Cheers fellas
January 19, 2022 at 6:21 am
Without an order by, are you sure you are getting the proper value? This looks like a bug waiting to happen.
Can more than one of the 5 selects return a value? If so, how are you determining the correct one to return?
Michael L John
If you assassinate a DBA, would you pull a trigger?
To properly post on a forum:
http://www.sqlservercentral.com/articles/61537/
Viewing 6 posts - 1 through 5 (of 5 total)
You must be logged in to reply to this topic. Login to reply