Question: I have a dynamic query which reads like this

```
Alter PROCEDURE dbo.mySP 
    -- Add the parameters for the stored procedure here
    (
        @DBName varchar(50),
        @tblName varchar(50)

    )

AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;

-- Insert statements for procedure here
declare @string as varchar(50)
declare @string1 as varchar(50)

set @string1  = '[' + @DBName + ']' + '.[dbo].' + '[' + @tblName + ']'

set @string = 'select * from ' + @string1   

exec @string

```

END

I am calling like this

```
dbo.mySP 'dbtest1','tblTest'

```

And I am experiencing an error

```
"Msg 203, Level 16, State 2, Procedure mySP, Line 27
The name 'select * from [dbtest1].[dbo].[tblTest]' is not a valid identifier."

```

What is wrong? and How to overcome?

Thanks in advance

Answer: 
It thinks that the contents of `@string` refer to a stored procedure name. You need to put

```
EXEC (@string)

```

or better use the stored procedure `sp_executesql`

You should also set up some guard code to check that the values you are passing in are the names of real tables and databases. You can query the views in the INFORMATION\_SCHEMA to validate the input.

You can read more on [safer dynamic SQL](http://colinmackay.co.uk/blog/2009/09/21/if-you-really-must-do-dynamic-sql/) on my blog.
```
ALTER PROCEDURE test_sp
    -- Add the parameters for the stored procedure here
    (
        @DBName varchar(50),
        @tblName varchar(50)

    )

AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON

-- Insert statements for procedure here
declare @string as varchar(100)
declare @string1 as varchar(50)

set @string1  = '[' + @DBName + ']' + '.[dbo].' + '[' + @tblName + ']'
Print @string1
set @string = 'select * from'  + @string1       
Print @string
exec (@string)
SET NOCOUNT OFF  
END

```