Inline SQL Cutting Off

I am trying to run the below statement, which if I print the statement it shows the full on statement, but when I use the Exec command it throws an error?

Declare @sql varchar(4000), @FQN varchar(4000)
Create Table #b
(
	acaca varchar(20)
	,ramalad varchar(4000)
)
Insert Into #b Values ('23', 'server.database.dbo.table'), ('44', 'server.database.dbo.table')

Set @FQN = (Select ramalad from #b where acaca = '44')
Set @Sql = 'Select * from '+@FQN+' '
Print @SQL
Exec @Sql

Printing my statement gives me Select * from server.database.dbo.table

However when it reaches the Exec statement it gives me an error of belwo.  Yes this is a linked server, but if I run the select statement direct it produces the results error free.  Why does the inline present an issue?

Msg 7202, Level 11, State 2, Line 7
Could not find server 'Select * from server' in sys.servers. Verify that the correct server name was specified. If necessary, execute the stored procedure sp_addlinkedserver to add the server to sys.servers.


August 19th, 2015 2:11pm

Change your last statement to be

exec (@SQL)

Also, do you have a linked server named 'server'? What will happen if you omit 'server' p

Free Windows Admin Tool Kit Click here and download it now
August 19th, 2015 2:13pm

In addition Naomi's post, what is happening is that SQL Server attempts to run the stored procedure by the name contained in the variable @Sql. Since the name includes three dots, it takes this to be a procedure on a linked server, and you get this funny message.

August 19th, 2015 5:52pm

More addtion, to execute a string, use the sp_executesql stored procedure instead of the EXECUTE statement. sp_executesql is more versatile and efficient.

If you have any question, feel free to let me know.
Free Windows Admin Tool Kit Click here and download it now
August 19th, 2015 11:03pm

This topic is archived. No further replies will be accepted.

Other recent topics Other recent topics