ruemichael
asked on
Microsoft Query on SQL varchar field
I have created an Excel sheet with a Microsoft Query to a MSSQL database. I'm having issues querying a date range on a field being used for date but configured as a varchar data type. Changing the data type tinternally to SQL is not an option.
ASKER
Actually the field in question is being populated through another automated process so data integrity isn't much of a question; always being m/d/yy. My current query is below. My challenge is to perform the same query on a date range rather than the static date. The DRAWING_ID (no idea how they came up with that) is data type varchar.
SELECT CUST_ORDER_LINE.DRAWING_ID , CUST_ORDER_LINE.ORDER_QTY, CUST_ORDER_LINE.TOTAL_USR_ SHIP_QTY, PART.ID
FROM VEPMW.dbo.CUST_ORDER_LINE CUST_ORDER_LINE, VEPMW.dbo.CUSTOMER CUSTOMER, VEPMW.dbo.CUSTOMER_ORDER CUSTOMER_ORDER, VEPMW.dbo.PART PART
WHERE CUSTOMER_ORDER.ID = CUST_ORDER_LINE.CUST_ORDER _ID AND CUSTOMER_ORDER.CUSTOMER_ID = CUSTOMER.ID AND CUST_ORDER_LINE.PART_ID = PART.ID AND ((CUST_ORDER_LINE.DRAWING_ ID='9/20/0 7') AND (CUSTOMER_ORDER.STATUS='R' ) AND (PART.ID=?))
SELECT CUST_ORDER_LINE.DRAWING_ID
FROM VEPMW.dbo.CUST_ORDER_LINE CUST_ORDER_LINE, VEPMW.dbo.CUSTOMER CUSTOMER, VEPMW.dbo.CUSTOMER_ORDER CUSTOMER_ORDER, VEPMW.dbo.PART PART
WHERE CUSTOMER_ORDER.ID = CUST_ORDER_LINE.CUST_ORDER
ASKER CERTIFIED SOLUTION
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
dbbishop is correct. Moreover, to prevent possible conversion errors, add a check to make sure it is a valid date before CASTing it to datetime:
((CASE WHEN ISDATE(CUST_ORDER_LINE.DRA WING_ID) = 1 THEN
CAST(CUST_ORDER_LINE.DRAWI NG_ID AS DATETIME) ELSE '19000101' END BETWEEN @date1 ...
((CASE WHEN ISDATE(CUST_ORDER_LINE.DRA
CAST(CUST_ORDER_LINE.DRAWI
Just noticed an error in my code. Change:
((CAST(CUST_ORDER_LINE.DRA WING_ID='9 /20/07' AS DATETIME)
to:
((CAST(CUST_ORDER_LINE.DRA WING_ID AS DATETIME)
((CAST(CUST_ORDER_LINE.DRA
to:
((CAST(CUST_ORDER_LINE.DRA
Forced accept.
Computer101
EE Admin
Computer101
EE Admin
SELECT <Fields>
FROM YourTable
WHERE YourDateField = CONVERT(DATETIME,<yourvarc
However because your source field is varchar, I expect a lot of data in there will be invalid, so the CONVERT function will fail a lot of the time.