2

I'm trying to append table name dynamically to SQL Server stored procedure, but I get an error:

couldn't find the stored procedure 's'

Code:

SET ANSI_NULLS ON
GO    
SET QUOTED_IDENTIFIER ON    
GO     

ALTER PROCEDURE [dbo].[atest_demo_sp]    
    @name varchar(10)     
AS     
BEGIN     
    Declare @tname nvarchar    
    Declare @sql nvarchar    

    set @tname = @name           
    Set @sql = 'select * from ' + convert(varchar(10), @tname)    

    -- select @sql     
    execute sp_executesql @sql     
END
2
  • 1
    What's the command you used to call atest_demo_sp? Commented Mar 24, 2016 at 5:53
  • error message you posted ,doesn't relate to the code you are showing. Commented Mar 24, 2016 at 5:58

2 Answers 2

2

You need to explicitly define a length for your string variables!

SET ANSI_NULLS ON
GO    
SET QUOTED_IDENTIFIER ON    
GO     

ALTER PROCEDURE [dbo].[atest_demo_sp]    
    @name varchar(10)     
AS     
BEGIN     
    Declare @tname nvarchar(200)    -- DEFINE A LENGTH HERE !!!
    Declare @sql nvarchar(200)      -- DEFINE A LENGTH HERE !!!

    set @tname = @name           
    Set @sql = N'select * from ' + convert(nvarchar(10), @tname)    

    -- select @sql     
    execute sp_executesql @sql     
END

Otherwise, your variables @tname and @sql will be exactly 1 character long! Probably not what you want!

See this blog post for more details: Bad habits to kick : declaring VARCHAR without (length)

Also, as a side note: either pick varchar (non-Unicode), or use nvarchar (Unicode) - but don't mix the two. And if you use nvarchar, you should always use the N'...' notation for assigning string literals.

Sign up to request clarification or add additional context in comments.

Comments

1

The issue with the set @tname = @name, no need to assign the varchar to nvarchar here. Avoid the @tname variable and directly use @name in the SET statement since it is already varchar.

Hope the @name's first character only assigning to @tname. Also need to define the @sql to some length.

Use the below statement, it will work:

Declare @sql varchar(100);
Set @sql = 'select * from ' + @name

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.