Question

In SQL Server, I have a stored procedure that accepts a date parameter. That date paramater is then passed along to another stored procedure. However, the 2nd stored procedure parameter is named as the first parameter. and then I need to I have 2 different scalar variables:

DECLARE @date date, @sql varchar(100);

SET @date = '2012-07-01';
SELECT @sql = ('EXEC pStoredprocedure @date = '''+@date+'''')

I need the @sql scalar to contain this text so the stored procedure can call the other stored procedure:

EXEC pStoredprocedure @date = '2012-07-01'

But, when I run my code above, I get this error:

Msg 402, Level 16, State 1, Line 4 The data types varchar and date are incompatible in the add operator.

It's almost like I need to escape the @date operator. Can this be done?

Side note: Yes, I'm trying to dynamically pass along some variables. I understand the dangers of doing so, but doing it this way is much simpler...

Was it helpful?

Solution

The date variable is being used in string concatenation, so it should be treated as a string, either through its declaration, a convert function, or a cast. I tried this:

 DECLARE @date varchar(20), @sql varchar(100);
SET @date = '2012-07-01';
SELECT @sql = ('EXEC pStoredprocedure @date = ''' + @date + '''')

 PRINT @sql

and got this:

 EXEC pStoredprocedure @date = '2012-07-01'

I am stuck on 2005, so I don't have the date datatype, but when I tried to use datetime, I got this error:

Msg 241, Level 16, State 1, Line 4 Conversion failed when converting datetime from character string.

You can also try

 DECLARE @date datetime, @sql varchar(100);
SET @date = '2012-07-01';
SELECT @sql = ('EXEC pStoredprocedure @date = ''' + CONVERT(varchar(20), @date, 102) + '''')
 PRINT @SQL;

and get

 EXEC pStoredprocedure @date = '2012.07.01'
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top