Error converting a character string to a date and/or time

JESUS EDUARDO CHAVARIN ROCHA 81 Reputation points
2022-08-24T21:53:55.6+00:00

Hello, in this code I want to select only the data that matches the number that is stored in my database as nvarchar which is in the NoSem column, but I get an error, does anyone know why?

---

DECLARE @YA AS DATETIME = GETDATE()
SELECT DATEPART(ISO_WEEK, @YA)

SELECT * FROM Datos.dbo.HorasTrabajadas
WHERE @YA = NoSem
ORDER BY Fecha ASC

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,249 questions
Transact-SQL
Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
4,552 questions
0 comments No comments
{count} votes

Accepted answer
  1. CosmogHong-MSFT 22,941 Reputation points Microsoft Vendor
    2022-08-25T02:00:42.367+00:00

    Hi @JESUS EDUARDO CHAVARIN ROCHA
    Because you Declare the parameter @YA AS DATETIME, while the datatype of column NoSem is nvarchar. You cannot compare values with two different datatypes.
    Here are two solutions:
    1)Modify the Declare statement, like this:

    DECLARE @YA AS nvarchar(10) = DATEPART(ISO_WEEK, GETDATE())  
    SELECT @YA  
      
    SELECT * FROM Datos.dbo.HorasTrabajadas  
    WHERE @YA = NoSem  
    ORDER BY Fecha ASC  
    

    2)Modify the WHERE clause, like this:

    DECLARE @YA AS DATETIME = GETDATE()  
    SELECT DATEPART(ISO_WEEK, @YA)  
      
    SELECT * FROM Datos.dbo.HorasTrabajadas  
    WHERE DATEPART(ISO_WEEK, @YA) = NoSem  
    ORDER BY Fecha ASC  
    

    Best regards,
    LiHong


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our Documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

0 additional answers

Sort by: Most helpful