Reputation: 1211
I'm trying to get relevant rows into datatable, i want only rows that have column value equal to one of the values in other sql table, that's my code:
try
{
sc.Open();
for (int i = 0; i < queryTokens.Length; i++)
{
cmd = new SqlCommand("INSERT INTO QueryIndex (Term) Values ('" + queryTokens[i] + "')", sc);
cmd.ExecuteNonQuery();
}
cmd = new SqlCommand("SELECT * FROM TermsIndex Where Term EXIST (Select Term From QueryIndex)");
SqlDataAdapter da = neuw SqlDataAdapter(cmd);
da.Fill(tempTable);
da.Dispose();
sc.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
the first part of the insert going well i'm sure, but in the second part, i hope you all understand what i'm trying to do, i know i have syntax errors here so please correct me, and i'm getting this exception message: {"Value cannot be null.\r\nParameter name: dataTable"} Null exception..
this is my sql create table:
CREATE TABLE [dbo].[TermsIndex]
(
[ID] VARCHAR(35) NOT NULL,
[Term] VARCHAR(35) NOT NULL,
[Frequency] int NOT NULL,
[Offset] VARCHAR(MAX) NOT NULL,
)
CREATE TABLE [dbo].[QueryIndex]
(
[Term] VARCHAR(MAX) NOT NULL,
)
so why i'm getting that null error? and anyway i'm creating a table just to be able to compare it's entries with column from the first one, i already had it string array, any chance to be able to compare that column value to changing number of strings (tokens) and return row results if it were equal to one of those strings in sql command? or any more elegance way to get the wanted result?
Upvotes: 0
Views: 3212
Reputation: 33381
I assume you have DataTable tempTable;
in your code. You mast initialize it.
DataTable tempTable = new DataTable();
Upvotes: 1
Reputation: 24526
There are a few ways you can do the query:
SELECT DISTINCT T.* FROM TermsIndex T
INNER JOIN QueryIndex Q ON T.Term = Q.Term;
SELECT T.* FROM TermsIndex T
WHERE T.Term IN (SELECT Q.Term FROM QueryIndex Q);
SELECT T.* FROM TermsIndex T
WHERE EXISTS(SELECT Q.Term FROM QueryIndex Q WHERE Q.Term = T.Term);
SELECT T.* FROM TermsIndex T
WHERE T.Term IN('term1', 'term2', 'term3');
Note: There's no dataTable
in your posted code.
Upvotes: 0