Again, thank you very much.
Now I don't get the error.
But still do not get the result I am looking for.
That if I don't use WHERE and select all records, I see in the SSMS window an entry for CATEGORY = '1009F'
and many others.
But when I use the SQL Select (as in example below) with the @Category = '1009F', the query has no records.
I am still missing something.
UPDATE. I found what I was doing wrong. Never mind my quesiton.
Thank you.
>The value of @Category needs to be quoted in the WHERE clause. Working with embedded quotes in strings like this can be tricky, one solution is to create a variable named @quote and then use it, like this:
>
>use [FirstSQLDatabase];
>go
>declare @cSecondDb as Varchar(100);
>declare @sql as varchar(max);
>declare @Category as Varchar(25);
>declare @quote = ''''
>set @Category = '1009F';
>set @cSecondDb = 'SecondSQLDatabase';
>set @sql = 'select * from ' + @cSecondDb + '.dbo.mytable where Category = ' + @quote + @Category + @quote;
>exec (@sql);
>
>
>>I know that I am missing something simple. But how do I add a WHERE clause to the dynamic SQL?
>>For example, say I want to add to the SQL Select below:
>>
>>declare @Category as Varchar(25);
>>set @Category = '1009F';
>>' WHERE Category = @Category'
>>
>>I get error no matter what I do with the @Category.
>>
>>>Hi Dmitry,
>>>
>>>Use dynamic SQL, something like this:
>>>
>>>use [FirstSQLDatabase];
>>>go
>>>declare @cSecondDb as Varchar(100);
>>>declare @sql as varchar(max);
>>>set @cSecondDb = 'SecondSQLDatabase';
>>>set @sql = 'select * from ' + @cSecondDb + '.dbo.mytable';
>>>exec (@sql);
>>>
>>>
>>>and replace dbo with the appropriate schema name if it's not dbo.
>>>
>>>
>>>>Hi,
>>>>
>>>>I am testing the SQL Select with a name of the database not current.
>>>>This case works:
>>>>
>>>>use [FirstSQLDatabase]
>>>>go
>>>>select * from SecondSQLDatabase..mytable where 1=1
>>>>
>>>>
>>>>Now I want to put the 'SecondSQLDatabase' into a variable. Here is how I do it:
>>>>
>>>>use [FirstSQLDatabase]
>>>>go
>>>>declare @cSecondDb as Varchar(100)
>>>>set @cSecondDb = 'SecondSQLDatabase'
>>>>select * from @cSecondDb..mytable where 1=1
>>>>
>>>>
>>>>The above produces syntax error.
>>>>
>>>>What am I missing?
>>>>TIA
"The creative process is nothing but a series of crises." Isaac Bashevis Singer
"My experience is that as soon as people are old enough to know better, they don't know anything at all." Oscar Wilde
"If a nation values anything more than freedom, it will lose its freedom; and the irony of it is that if it is comfort or money that it values more, it will lose that too." W.Somerset Maugham