Search code examples
sqlsql-serverstored-proceduresdynamic-queries

how to add hyphen in dynamic sql query


I have a table with columns A,B,C,D (type of varchar).

From a stored procedure i am fetching data from the same table.I am created a dynamic sql query inside the stored procedure for fetching data from the table.

what i want is that,

need to combine column B and C together with a symbol(hyphen or colon) and display it as a single section.

DECLARE @sSQL nvarchar(100);
DECLARE @symbol nvarchar(100);
SET @symbol='-'
SELECT @sSQL = N'SELECT [A], ([B], '+@symbol+', [C]) as Status FROM Table';
EXEC sp_executesql @sSQL

above query is not working for me.I need following query as a dynamic query.

SELECT A,B+'-'+C as Status FROM Table

Please help.


Solution

  • You do need commas there. Here is the correct syntax:

    SELECT @sSQL = N'SELECT [A], ([B] + '''+@symbol+''' + [C]) as Status FROM Table';