0

I have a parameter with the available values as column names and a I am using that parameter in the sql query

 WHERE ((@ColumnName) BETWEEN (@StartDate) AND (@EndDate)) 
AND (schema.table.column_name LIKE (@Number))

When i try to run the report i get a cannot convert date/time from characters

enter image description here

If i remove the @ColumnName parameter the report runs fine but i want the ability to choose a column to search the date against.

3
  • 1
    You can't use a variable (@ColumnName) to represent a column name. SQL appears to be interpreting it as a "string" literal in this case (whatever data type the variable is). You'll need to use dynamic tsql.
    – Dave Mason
    Jul 17, 2014 at 13:52
  • Indeed that is happening but looking to see what the best practice for using dynamic on this. Jul 17, 2014 at 13:54
  • There are two common server-side options for creating and executing dynamic tsql strings: EXECUTE and sp_executesql.
    – Dave Mason
    Jul 17, 2014 at 13:58

1 Answer 1

1

If you want pass Column name dynamically you will need to use a stored procedure to do this using dynamic sql something like this....

CREATE PROCEDURE Get_Data
  @ColumnName1  SYSNAME,
  @ColumnName2  SYSNAME,
  @StartDate    DATETIME,
  @EndDate      DATETIME,
  @Number       VARCHAR(100)
AS
BEGIN
  SET NOCOUNT ON;

  DECLARE @SQL NVARCHAR(MAX);

SET @SQL = N'SELECT * FROM TableName'
         + N'WHERE ' + QUOTENAME(@ColumnName1) + N' BETWEEN @StartDate AND @EndDate '
         + N' AND ' + QUOTENAME(@ColumnName2) + N' LIKE ''@Number'' '

 EXECUTE sp_executesql @SQL 
                      ,N'@StartDate DATETIME, @EndDate DATETIME, @Number VARCHAR(100)'
                      ,@StartDate
                      ,@EndDate
                      ,@Number

END

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.