SQL cmd.command include an OR statement

41 Views Asked by At

Below is my SQL cmd.CommandText query:

cmd.CommandText = "SELECT CONVERT(date, [DateTime]) 'Date of Download', ActionBy AS 'User Full Name', COUNT(DISTINCT CAST(Identifier AS NVARCHAR(10)) + Remarks + Link) 'Number of Document Downloads' " + 
    " FROM [dbo].[AuditLog] "+
    " WHERE ActionTaken = 'Clicked' "+
    " and Type = 'Attachment Link'" +
    " and CONVERT(date, [DateTime]) BETWEEN CONVERT(date,'" + scanStartDate.ToString("yyyy-MM-dd HH:mm:ss.fff") + "') and CONVERT(date,'" + scanEndDate.ToString("yyyy-MM-dd HH:mm:ss.fff") + "') "+
    " GROUP BY CONVERT(date, [DateTime]), ActionBy "+
    " HAVING COUNT(DISTINCT Identifier) > " + limit + 
    " ORDER BY COUNT(DISTINCT Identifier) DESC";

I would like to include an extra parameter OR for Type, like as follows:

" and Type = 'Attachment Link' OR 'Attachment Link - Search'" +

May I know how can it be done?

Thank you.

Edit: Apologies, did not add in the error message, as follow.

An expression of non-boolean type specified in a context where a condition is expected, near 'and'.

2

There are 2 best solutions below

3
kjmerf On BEST ANSWER

I assume I am over-simplifying but do you mean:

cmd.CommandText = "SELECT CONVERT(date, [DateTime]) 'Date of Download', ActionBy AS 'User Full Name', COUNT(DISTINCT CAST(Identifier AS NVARCHAR(10)) + Remarks + Link) 'Number of Document Downloads' " + 
    " FROM [dbo].[AuditLog] "+
    " WHERE ActionTaken = 'Clicked' "+
    " and (Type = 'Attachment Link' OR Type = 'Attachment Link - Search') " +
    " and CONVERT(date, [DateTime]) BETWEEN CONVERT(date,'" + scanStartDate.ToString("yyyy-MM-dd HH:mm:ss.fff") + "') and CONVERT(date,'" + scanEndDate.ToString("yyyy-MM-dd HH:mm:ss.fff") + "') "+
    " GROUP BY CONVERT(date, [DateTime]), ActionBy "+
    " HAVING COUNT(DISTINCT Identifier) > " + limit + 
    " ORDER BY COUNT(DISTINCT Identifier) DESC";

You might need ( ) for order of operations and I think you mean "=" instead of "-".

0
Ed Bangga On

specify the column after your OR operator

cmd.CommandText = "SELECT CONVERT(date, [DateTime]) 'Date of Download', ActionBy AS 'User Full Name', COUNT(DISTINCT CAST(Identifier AS NVARCHAR(10)) + Remarks + Link) 'Number of Document Downloads' " + 
        " FROM [dbo].[AuditLog] "+
        " WHERE ActionTaken = 'Clicked' "+
        " and (Type = 'Attachment Link' OR Type = 'Attachment Link - Search') " +
        " and CONVERT(date, [DateTime]) BETWEEN CONVERT(date,'" + scanStartDate.ToString("yyyy-MM-dd HH:mm:ss.fff") + "') and CONVERT(date,'" + scanEndDate.ToString("yyyy-MM-dd HH:mm:ss.fff") + "') "+
        " GROUP BY CONVERT(date, [DateTime]), ActionBy "+
        " HAVING COUNT(DISTINCT Identifier) > " + limit + 
        " ORDER BY COUNT(DISTINCT Identifier) DESC";