Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

(TSQL) stored procedure- add single quotes?

Status
Not open for further replies.

MrPeds

Programmer
Jan 7, 2003
219
GB
Hi,

I am working on a simple stored procedure that takes in a string argument , which is the name of a person e.g. Bob.

I would like to know if it is possible to set the name as 'Bob' instead of Bob, at the moment i have:

CREATE PROCEDURE myProc
@myname nvarchar(20)

DECLARE @cmdSQL nvarchar(1000)

SET @cmdSQL = 'SELECT col1, col2, col3,
(SELECT col4 WHERE name = ' + @myname + ')....etc

EXECUTE(@cmdSQL)

at the moment I am getting the subquery as
(SELECT col4 WHERE name = Bob) but I actually want
(SELECT col4 WHERE name = 'Bob')

How do i insert the '' ?

Thanks in advance,

MrPeds
 
SET @cmdSQL = 'SELECT col1, col2, col3,
(SELECT col4 WHERE name = ''' + @myname + ''')'


--Angel [rainbow]
-----------------------------------
Every time I lose my mind, I wonder
if it's really worth finding.
 
Hi Angel,

Try something like this:

SET @cmdSQL = "SELECT col1, col2, col3, col4 WHERE name = '" + @myname + "'"

Using double quotes to enclose the single quotes, and make them part of the actual string you're building.

Hope that helps,
Phillip
 
If you use double quotes, then you'll have to deal with the QUOTED_IDENTIFIER settings. It is safer to stick with single quotes to define character strings.

--Angel [rainbow]
-----------------------------------
Every time I lose my mind, I wonder
if it's really worth finding.
 
The solution offered by AngelWPB works exactly as i need it!

Thank you!
 
Just another point, you should avoid using dynamic sql wherever possible. In your example you are using the variable in place of an expression so you don't actually need to use it:

Code:
CREATE PROCEDURE myProc
  @myname nvarchar(20)
AS

SELECT col1, col2, col3,
  (SELECT col4 FROM t2 WHERE name = @myname)
FROM t1
...

--James
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top