I am trying to get comma separated skills Ids
but getting null when executing query with ado.net
Query works fine when I run it in SQL Server Management Studio, but when I tried to execute it with ado.net, I'm getting no output.
I have 2 tables Employee
and Skills
with following columns :
Employee
: Id, Name, LocationSkills
: Id, Skills
Employee data:
Id Name Location
7 Abc London
8 Xyz London
9 Xyz USA
10 Abc USA
Skills:
Id skills EmployeeId
12 AAA Xyz 7
13 BBB 7
14 CCC 7
15 AAA 8
16 BBB 8
17 CCC 8
18 AAA 9
19 BBB 9
20 CCC 9
21 AAA 10
22 BBB 10
20 CCC 10
My code so far:
string Name = "Abc";
string Location = "London";
string csvSkillsIds = string.Join(",", Skill1, Skill2); //AAA Xyz,BBB
'AAA Xyz','BBB' //Added single quotes to comma separated values
string skillList = string.Join(",", csvSkillsIds.Split(',').Select(x => string.Format("'{0}'", x)).ToList());
using (SqlConnection connection = new SqlConnection(""))
{
string query = "Select Stuff(" +
" (" +
" Select ',' + Convert(Varchar, CD.Id)" +
" From Employee as E" +
" Skills S On S.EmployeeId = E.Id " +
" Where E.Name = @name " +
" And E.Location = @location " +
" And S.Skills In (@skills)" +
" For Xml Path ('')" +
" ), 1, 1, ''" +
" ) As SkillId";
using (SqlCommand cmd = new SqlCommand(query, connection))
{
connection.Open();
cmd.Parameters.AddWithValue("@name", Name);
cmd.Parameters.AddWithValue("@location", Location);
cmd.Parameters.AddWithValue("@skills", skillList);
var data = cmd.ExecuteScalar(); //getting no output not even null
connection.Close();
if (data != null)
return data.ToString();
else
return null;
}
}
This is what I am getting in data:
But when I run below query then I am successfully getting output like: 12, 13
Select Stuff
(
(
Select ',' + Convert(Varchar, S.Id)
From Employee E
Join Skills S On S.EmployeeId = E.Id
Where E.Name = @name
And E.Location = @location
And S.Skills In ('AAA Xyz', 'BBB')
For Xml Path ('')
), 1, 1, ''
) As Skills
So I guess problem is in below line:
And S.Skills In (@skills)
Expected output: 12,13