JOIN SQL not working as it should be - c#

I have tabel for courses(CID,CName) and another table shows majors for each course CourseMajor(CID,MNom).
I have a drop dawn list which has majors numbers. if the user select a major number from the list another list should be filled of courses that are from the selected major.
I have the code below show me all courses not only the courses for the selected major number !
I used LEFT JOIN, RIGHT JOIN, INNER JOIN, FULL OUTER JOIN....and none of them work.
note: I am using C#, asp.net, vs.net...
using (SqlConnection con = new SqlConnection(conStr))
{
using (SqlCommand cmd = new SqlCommand("SELECT * FROM TBCourse FULL JOIN TbCourseMajor ON TBCourse.CId = TbCourseMajor.CId AND TbCourseMajor.MNom = '" + DLMNom.SelectedValue + "' ", con))
{
con.Open();
cmd.ExecuteNonQuery();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
reader.Read();
while (reader.Read())
{
DLCName.Items.Add(new ListItem(reader["CName"].ToString(), reader["CNom"].ToString()));
}
}
else { TxtCRN.Text = "Not worked"; }
}
}
This is some details about tables:
CREATE TABLE [dbo].[TBCourse] (
[CId] INT IDENTITY (1, 1) NOT NULL,
[CNom] INT NOT NULL,
[CName] NVARCHAR (50) NOT NULL,
[Chours] NCHAR (10) NOT NULL,
CONSTRAINT [PK_TBCourse] PRIMARY KEY CLUSTERED ([CId] ASC)
);
CREATE TABLE [dbo].[TbCourseMajor] (
[CId] INT NOT NULL,
[MNom] INT NOT NULL,
PRIMARY KEY CLUSTERED ([CId] ASC),
FOREIGN KEY ([CId]) REFERENCES [dbo].[TBCourse] ([CId]),
FOREIGN KEY ([MNom]) REFERENCES [dbo].[TbMajor] ([MNom])
);

The problem was as devlin carnage said in database (in stored data) , the second table has a problem (not store data) it shows null.. I created another table with the same data and it works perfectly.. Thanks all and sorry for not being able to identify the problem from the beginning.

Related

SQL Server command not showing result

I am trying to create some text but the text is not showing up...
Here is my code:
SqlCommand getLeastId = new SqlCommand("SELECT Id FROM [Chat-main] WHERE Userid LIKE #id AND Sendtoid LIKE #toid", c);
getLeastId.Parameters.AddWithValue("#id", (string)Session["CurentUserid"]);
getLeastId.Parameters.AddWithValue("#toid", (string)Session["contactuserid"]);
c.Open();
SqlDataReader reader = getLeastId.ExecuteReader();
if (reader.HasRows)
while (reader.Read())
CreateDiv((int)reader[0]);
c.Close();
The create div function is working.
Thank you guys for helping
My table structure:
CREATE TABLE [dbo].[Chat-main]
(
[Id] INT IDENTITY (1, 1) NOT NULL,
[tag] VARCHAR(50) NOT NULL,
[commet] VARCHAR(MAX) NOT NULL,
[Userid] VARCHAR(MAX) NOT NULL,
[Sendtoid] VARCHAR(MAX) NOT NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);
There are few issues with your code.
1- LIKE can't be used with integer, it is only meant for string types. If you still want, you can use it by converting INT to VARCHAR like following.
CAST(ID AS VARCHAR(9)) LIKE '%123'
2- LIKE used for Sendtoid is also not correct, it should be like following.
getLeastId.Parameters.AddWithValue("#toid"
, "%" + (string)Session["contactuserid"] + "%");
You can change your code like following.
SqlCommand getLeastId = new SqlCommand("SELECT Id FROM [Chat-main] Where Userid = #id AND Sendtoid like #toid", c);
getLeastId.Parameters.AddWithValue("#id", (string)Session["CurentUserid"]);
getLeastId.Parameters.AddWithValue("#toid", "%" + (string)Session["contactuserid"] + "%");
c.Open();
SqlDataReader reader = getLeastId.ExecuteReader();
if (reader.HasRows)
while (reader.Read())
CreateDiv((int)reader[0]);
c.Close();

Update statement conflicted with foreign key

Here is my tables,i can update ad,soyad and email but when i try to update telefon it conflicts with the foreign key [userFk],i already have foreign key update on cascade so,i can't figure out the issue here.Thanks in advance
CREATE TABLE [dbo].[ogrenci] (
[ogrenciNo] INT NOT NULL,
[ad] NVARCHAR (20) NOT NULL,
[soyad] NVARCHAR (20) NOT NULL,
[email] NVARCHAR (50) NOT NULL,
[fakulte_no] INT NOT NULL,
[bolum_ad] NVARCHAR (30) NOT NULL,
[bolum_no] INT DEFAULT ((1)) NOT NULL,
[telefon] NVARCHAR (50) DEFAULT ((1)) NOT NULL,
PRIMARY KEY CLUSTERED ([ogrenciNo] ASC),
UNIQUE NONCLUSTERED ([ogrenciNo] ASC),
UNIQUE NONCLUSTERED ([email] ASC),
CONSTRAINT [bolumFk] FOREIGN KEY ([bolum_no]) REFERENCES [dbo].[bolum] ([bolumNo]) ON DELETE CASCADE,
CONSTRAINT [fakulteFk1] FOREIGN KEY ([fakulte_no]) REFERENCES [dbo].[fakulte] ([fakulteId]) ON DELETE CASCADE,
CONSTRAINT [userFk] FOREIGN KEY ([telefon]) REFERENCES [dbo].[loginusers] ([upassword]) ON DELETE CASCADE ON UPDATE CASCADE
);
and the second one,
CREATE TABLE [dbo].[loginusers] (
[username] NVARCHAR (50) NOT NULL,
[upassword] NVARCHAR (50) NOT NULL,
PRIMARY KEY CLUSTERED ([upassword] ASC)
);
and here is the update button,
private void btnUpdate_Click(object sender, EventArgs e)
{
try
{
if (txtOgrenciNo.Text.Length != 0 && txtAd.Text.Length != 0 && txtSoyad.Text.Length != 0 && txtEmail.Text.Length != 0 && txtTelefon.Text.Length != 0)
{
string query = "UPDATE ogrenci SET ogrenciNo=#ogrenciNoVal,ad=#adVal,soyad=#soyadVal,email=#emailVal,telefon=#telefonVal WHERE ogrenciNo=#ogrenciNoVal";
string query1 = "UPDATE loginusers SET username=#emailVal,upassword=#telefonVal WHERE username=#telefonVal";
using (connection = new SqlConnection(connectionString))
using (SqlCommand command = new SqlCommand(query, connection))
using (SqlCommand cmd = new SqlCommand(query1, connection))
{
connection.Open();
command.Parameters.AddWithValue("#ogrenciNoVal", txtOgrenciNo.Text);
command.Parameters.AddWithValue("#adVal", txtAd.Text);
command.Parameters.AddWithValue("#soyadVal", txtSoyad.Text);
command.Parameters.AddWithValue("#emailVal", txtEmail.Text);
command.Parameters.AddWithValue("#telefonVal", txtTelefon.Text);
cmd.Parameters.AddWithValue("#emailVal", txtEmail.Text);
cmd.Parameters.AddWithValue("#telefonVal", txtTelefon.Text);
command.ExecuteNonQuery();
cmd.ExecuteNonQuery();
gridDoldur();
}
}
else
{
MessageBox.Show("Öğrenci bilgileri boş girilemez.", "Bilgilendirme", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
As upassword column is primarykey in your loginusers table, if you want to update telefon on ogrenci with update cascade property, so you need to remove ,telefon=#telefonVal code from update ogrenci query, like this
string query = "UPDATE ogrenci SET ogrenciNo=#ogrenciNoVal,ad=#adVal,soyad=#soyadVal,email=#emailVal WHERE ogrenciNo=#ogrenciNoVal";
Your second query will update table ogrenci too
WARNING:
It will not good if some student will think like this - "If my password is my telephone, so lets try login as another student with his/her telephone number as password and do something" :)
EDIT:
Your second query where clause is wrong I think,
string query1 = "UPDATE loginusers SET username=#emailVal,upassword=#telefonVal WHERE username=#telefonVal";
It should change to this
string query1 = "UPDATE loginusers SET username=#emailVal,upassword=#telefonVal WHERE upassword=#oldtelefonVal ";
To resolve your problem you need to insert your row in loginusers (not update) after that you need to update your table ogrenci , in the end you can suppress your loginusers row .

Insert a record in table fails everytime

I have a database connection where i insert data into the table having 2 columns i.e. id,first_name,last_name.
Following is the code:
private void Insert_Click(object sender, EventArgs e)
{
try
{
String query = "INSERT INTO data_table (first_name,last_name) VALUES (#f_name,#l_name)";
using (SqlConnection connection1 = new SqlConnection(
Properties.Settings.Default.DatabaseConnection))
using (SqlCommand insertCommand = new SqlCommand(query, connection1))
{
//a shorter syntax to adding parameters
// insertCommand.Parameters.Add("#id", SqlDbType.Int).Value = 1;
insertCommand.Parameters.Add("#f_name", SqlDbType.NChar).Value = "JAVED";
insertCommand.Parameters.Add("#l_name", SqlDbType.NChar).Value = "GHAMJN";
//make sure you open and close(after executing) the connection
connection1.Open();
insertCommand.ExecuteNonQuery();
connection1.Close();
MessageBox.Show("Record inserted. Please check your table data. :)");
}
}
catch (Exception err)
{
MessageBox.Show(err.Message);
}
}
Following is T-SQL script:
CREATE TABLE [dbo].[data_table] (
[Id] INT NOT NULL IDENTITY,
[first_name] NCHAR (10) NULL,
[last_name] NCHAR (10) NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);
The issue is created by id: I have set it auto-increment.
When i click insert button a MessageBox pops saying:
Cannot insert the value NULL into column 'Id',table 'C:\Users.......\Database1.MDF.dbo.data_table;column doesn't allows null.INSERT fails
Add identity seed and increment values to your table...
CREATE TABLE [dbo].[data_table] (
[Id] INT NOT NULL IDENTITY(1,1),
[first_name] NCHAR (10) NULL,
[last_name] NCHAR (10) NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);
Your Id field should be modified as shown below
Deleting that table alongwith all the old copies of old table and creating a new table with suggested Identity(1,1) resolved the issue
try this. The behaviour of Identity Columns can be selectively enabled or disabled with this statement.
If your Identity Column is configured correctly, then this is the only logical explanation for it not behaving as expected
SET IDENTITY_INSERT [dbo].[data_table] ON;
However, it is more likely that your assertion of correctness is flawed and you have not configured the Identity Column correctly.

Adding to two tables, can't add foreign key to second table

So I have two tables, Employee and Login:
CREATE TABLE [dbo].[Employee] (
[EmpID] INT IDENTITY (1, 1) NOT NULL,
[ManagerID] INT NULL,
[EmpName] VARCHAR (50) NOT NULL,
[EmpRank] VARCHAR (50) NOT NULL,
[EmpDateOfBirth] DATE NOT NULL,
[EmpAddress] VARCHAR (100) NOT NULL,
[DeptID] INT NOT NULL,
[EmpSalary] INT DEFAULT ((0)) NOT NULL,
[EmpGender] VARCHAR (50) NOT NULL,
PRIMARY KEY CLUSTERED ([EmpID] ASC),
CONSTRAINT [FK_Employee_Department] FOREIGN KEY ([DeptID]) REFERENCES [dbo].[Department] ([DeptID])
and
CREATE TABLE [dbo].[Login] (
[Username] VARCHAR (50) NOT NULL,
[Password] VARCHAR (50) NOT NULL,
[EmpID] INT NOT NULL IDENTITY,
PRIMARY KEY CLUSTERED ([Username] ASC),
CONSTRAINT [FK_Login_Employee] FOREIGN KEY ([EmpID]) REFERENCES [dbo].[Employee] ([EmpID])
So I have a page form to create a new Employee, which adds info to both the Employee and Login tables. With the Employee table this works fine, but with the Login table, I get an exception in Visual Studio as EmpID 'cannot be null', even though like in the Employee table it is also set to Identity. The exception occurs even if it's not set to Identity. So I'm wondering what I can do so that I can add a new Employee while keeping the same EmpID for the new record in both tables.
This is what the C# code to add the new info looks like:
SqlCommand sqlc = new SqlCommand("Insert into Employee(EmpName, EmpRank, EmpDateOfBirth, EmpGender, DeptID, EmpSalary, EmpAddress) values (#EmpName, #EmpRank, #EmpDateOfBirth, #EmpGender, #DeptID, #EmpSalary, #EmpAddress)", connect);
sqlc.Parameters.AddWithValue("#EmpName", TextBoxName.Text);
sqlc.Parameters.AddWithValue("#EmpRank", DropDownListRank.Text);
sqlc.Parameters.AddWithValue("#EmpDateOfBirth", TextBoxDateOfBirth.Text);
sqlc.Parameters.AddWithValue("#EmpGender", DropDownListGender.Text);
sqlc.Parameters.AddWithValue("#DeptID", DropDownListDepartment.Text);
sqlc.Parameters.AddWithValue("#EmpSalary", TextBoxSalary.Text);
sqlc.Parameters.AddWithValue("#EmpAddress", TextBoxAddress.Text);
SqlCommand sqlc2 = new SqlCommand("Insert into Login(Username, Password) values (#Username, #Password)", connect);
sqlc2.Parameters.AddWithValue("#Username", TextBoxUsername.Text);
sqlc2.Parameters.AddWithValue("#Password", TextBoxPassword.Text);
connect.Open();
sqlc.ExecuteNonQuery();
sqlc2.ExecuteNonQuery();
connect.Close();
Any help will be greatly appreciated.
Well, the first thing to do is to remove the IDENTITY in the Login table EmpID.
This will be the same ID of the other Employee table, so you don't want the database to generate a possible different ID for the Login table.
Second, you need to retrieve from the Employee table the last id assigned automatically by the database.
This could be achieved appending the SELECT SCOPE_IDENTITY() at the first query and retrieving the value assigned to the Employee identity column calling ExecuteScalar()
// Notice the semicolon at the end of the first query to separate
// the second command text. The result of this second command is returned
// by ExecuteScalar
SqlCommand sqlc = new SqlCommand(#"Insert into Employee(EmpName, EmpRank, EmpDateOfBirth,
EmpGender, DeptID, EmpSalary, EmpAddress)
values (#EmpName, #EmpRank, #EmpDateOfBirth,
#EmpGender, #DeptID, #EmpSalary, #EmpAddress);
SELECT SCOPE_IDENTITY()", connect);
sqlc.Parameters.AddWithValue("#EmpName", TextBoxName.Text);
sqlc.Parameters.AddWithValue("#EmpRank", DropDownListRank.Text);
sqlc.Parameters.AddWithValue("#EmpDateOfBirth", TextBoxDateOfBirth.Text);
sqlc.Parameters.AddWithValue("#EmpGender", DropDownListGender.Text);
sqlc.Parameters.AddWithValue("#DeptID", DropDownListDepartment.Text);
sqlc.Parameters.AddWithValue("#EmpSalary", TextBoxSalary.Text);
sqlc.Parameters.AddWithValue("#EmpAddress", TextBoxAddress.Text);
connect.Open();
int empid = Convert.ToInt32(sqlc.ExecuteScalar());
// Now pass the empid value to the second table
// Remember to remove the IDENTITY flag from Login.EmpID otherwise
// you will get an error.
SqlCommand sqlc2 = new SqlCommand(#"Insert into Login(EmpID, Username, Password)
values (#empid, #Username, #Password)", connect);
sqlc2.Parameters.AddWithValue("#empid", empid);
sqlc2.Parameters.AddWithValue("#Username", TextBoxUsername.Text);
sqlc2.Parameters.AddWithValue("#Password", TextBoxPassword.Text);
sqlc2.ExecuteNonQuery();
connect.Close();

SQLite: Insert Into Identity Column [duplicate]

This question already has answers here:
Is there AUTO INCREMENT in SQLite?
(9 answers)
Closed last month.
I'm new to SQLite and I'm trying to run the following code:
using (var cn = new SQLiteConnection("Data Source=:memory:;Version=3;")) {
cn.Open();
var cmd = cn.CreateCommand();
cmd.CommandText = "CREATE TABLE [ContentItems] ([Id] [int] IDENTITY(1,1) NOT NULL, [Title] [nvarchar](100) NOT NULL, CONSTRAINT [PK_ContentItems] PRIMARY KEY ([Id]))";
cmd.ExecuteNonQuery();
var cmd2 = cn.CreateCommand();
cmd2.CommandText = "INSERT INTO [ContentItems] (Title) VALUES ('Test 1')";
cmd2.ExecuteNonQuery();
}
But this gives the error:
Abort due to constraint violation ContentItems.Id may not be NULL
I've had a look through the documentation but based on my past SQL experience I cannot see why this doesn't work. I'd appreciate the help. Thanks
SQLite creates what you're thinking of as an IDENTITY column using the AUTOINCREMENT keyword. In your example, the ID column is not created with AUTOINCREMENT and, since it is declared NOT NULL, you must supply a value.
The CREATE statement you're after is:
CREATE TABLE [ContentItems] (
[Id] INTEGER AUTOINCREMENT NOT NULL,
[Title] TEXT NOT NULL,
CONSTRAINT [PK_ContentItems] PRIMARY KEY ([Id])
)
Note that SQLite uses the TEXT data type (although it will map anything containing "CHAR" to that datatype) and doesn't need or respect maximum field lengths.

Categories