I have to put a result of a query (single column and value is being pulled) into a variable. I'm trying to use a cursor however I choose the database to query based on a variable here is my query
SELECT productName, price FROM @ShopName.dbo.Products WHERE ProductName = @ProductName
@ShopName variable is being pulled from the database first and assigned to the variable using a cursor. @ProductName variable is being populated by an input parameter coming from API. I have to get ProductName from a specific database (there are multiple databases with products), but the query above throws syntax errors. Additionally when I tried ad hoc query assigned to a variable:
SET @Sql = N'SELECT productName, price FROM ' + QUOTENAME(@ShopName) + '.dbo.Products WHERE ProductName = ' + @ProductName
It doesn't allow to use it in
DECLARE cursorT CURSOR
FOR
@Sql
This throws Incorrect syntax near '@Sql', Expecting '(', SELECT, or WITH
Is there any way to make it possible to use that query in cursor while using the variable with database name in it?
...FROM @ShopName...unless@ShopNameis a table variable? Please provide us with the complete code and not partial code?