Array comparison using SQL 2005. Error converting
Ok, no idea why a multi-billion dollar company skimps on array functions for their flagship SQL servers This is why people use MySQL Server. Ok, enough ranting. Using SQL 2005.
Let's say i received an array via checkbox from another page using the querystring method:
intTask = request.querystring("task")
For this example, intTask = "1,3,5"
Then I used the query
SELECT user.Task FROM user WHERE (user.Task in (" & intTask & "))
This gives an error of:
Conversion failed when converting the nvarchar value '1, 2' to data type int
The array in the User.task column here = 1,2. NVARCHAR is the data type. intTask is a string. No idea why SQL is trying to convert the column to integers when its suppose to be a string comparison. I already know about the SQL injection vulnerability, that taken care of with another script for the page.
OK. Well how does one compare arrays using SQl Server 2005 ? I can't seem to find any SQL functions that will iterate through 2 strings and compare for all matching values.
For example
intTask = 1,2
user.task = 3,5,7,2,9
Because of the 2's, I should get a recordset because the 2's exist in both arrays
UPDATE
Is there an SQL function that will handle two arrays and iterate through the arrays to find matching items. Somethi开发者_StackOverflowng like:
intTask = "1,3,5"
user("task") = "3,5,2"
ARR1 = split(intTask,",")
ARR2 = split(user("task"),",")
for i=0 to UBound(arr1)
for j=0 to UBound(arr2)
if(arr1(i) = arr2(j)) then
common_found = true
end if
Next
Next
Thanks in advance
The array in the User.task column here = 1,2. NVARCHAR is the data type.
because 1,2 are 2 integers and your column is a nvarchar, use '1','2', you might need to prefix win N
take a look at Arrays and Lists in SQL Server 2005 and Beyond
Here is a code example
create table #test (id nvarchar(20))
insert #test values('1,2')
insert #test values('2,3')
go
works
select * from #test
where id in (N'1,2')
will fail
select * from #test
where id in (1,2)
Msg 245, Level 16, State 1, Line 1
Conversion failed when converting the nvarchar value '1,2,3' to data type int.
If you are only using integers then use varchar, not nvarchar, nvarchar uses double the storage of varchar...of course if you properly normlized the Db you would not have these problems
精彩评论