SQL Server command not showing result - c#

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();

Related

How to fix FK Constraint insert Exception

According to my question with weird problem specified here how to fix
System.Data.SqlClient.SqlException: String or binary data would be truncated in table
My problem is, that if I am saving new problem into the database, its ID is always set to 0 (I checked this out in debugging), which then throws
System.Data.SqlClient.SqlException: The INSERT statement conflicted with the FOREIGN KEY constraint "FK__Alert__Problem_I__17F790F9". The conflict occurred in database "SmartOne", table "dbo.Problem", column 'id'
But in SQL Server Management Studio, the ID is set correctly (ID is defined as an Identity column).
Where both I am using is in my question mentioned below. Thanks for any ideas or advice.
Method that saves Problem:
public void Save(Problem element)
{
using (SqlConnection conn = new SqlConnection(DatabaseSingleton.connString))
{
conn.Open();
using (SqlCommand command = new SqlCommand("INSERT INTO Problem VALUES " +
"(#nameOfAlert, #value, #result, #message_ID) ", conn))
{
command.Parameters.Add(new SqlParameter("#nameOfAlert", element.NameOfAlert));
command.Parameters.Add(new SqlParameter("#value", (int)element.Value));
command.Parameters.Add(new SqlParameter("#result", (int)element.Result));
command.Parameters.Add(new SqlParameter("#message_ID", element.Message_Id));
command.ExecuteNonQuery();
command.CommandText = "Select ##Identity";
}
conn.Close();
}
}
Method that saves an Alert:
public void Save(Alert element)
{
using (SqlConnection conn = new SqlConnection(DatabaseSingleton.connString))
{
conn.Open();
using (SqlCommand command = new SqlCommand("INSERT INTO [Alert] VALUES (#message_ID, #date, #email, #AMUser_ID, #Problem_ID) ", conn))
{
command.Parameters.Add(new SqlParameter("#message_ID", element.Id_MimeMessage));
command.Parameters.Add(new SqlParameter("#date", element.Date));
command.Parameters.Add(new SqlParameter("#email", element.Email));
command.Parameters.Add(new SqlParameter("#AMUser_ID", element.User_ID));
command.Parameters.Add(new SqlParameter("#Problem_ID", element.Problem_ID));
command.ExecuteNonQuery();
command.CommandText = "Select ##Identity";
}
conn.Close();
}
}
SQL Scheme
CREATE TABLE [dbo].[Alert](
[id] [int] IDENTITY(1,1) NOT NULL,
[message_ID] [varchar](100) NOT NULL,
[date] [datetime] NOT NULL,
[email] [varchar](50) NOT NULL,
[AMUser_ID] [int] NOT NULL,
[Problem_ID] [int] NOT NULL);
//Where is ID, it means FK ID
CREATE TABLE [dbo].[Problem](
[id] [int] IDENTITY(1,1) NOT NULL,
[nameOfAlert] [varchar](50) NOT NULL,
[Value_ID] [int] NOT NULL,
[Result_ID] [int] NOT NULL,
[message_ID] [varchar](100) NOT NULL);
One problem might be that you're never actually getting back the inserted IDENTITY value from your first insert - thus you aren't using any valid ProblemId value for your second insert.
Try something like this:
public void Save(Problem element)
{
using (SqlConnection conn = new SqlConnection(DatabaseSingleton.connString))
{
conn.Open();
// define INSERT query - I'd *strongly* recommend specifying all
// columns you're inserting into!
// Also: run the "SELECT SCOPE_IDENTITY()" right after the INSERT
string insertQry = "INSERT INTO dbo.Problem(NameOfAlert, Value, Result, MessageId) " +
"VALUES (#nameOfAlert, #value, #result, #message_ID); " +
"SELECT SCOPE_IDENTITY();";
using (SqlCommand command = new SqlCommand(insertQry, conn))
{
// also here: define the *datatype* of the parameter, and use
// .Value = to set the value.
// Since you haven't shown what the table looks like, I'm just
// **guessing** the datatype and max length for the string parameters - adapt as needed!
command.Parameters.Add("#nameOfAlert", SqlDbType.VarChar, 100).Value = element.NameOfAlert;
command.Parameters.Add("#value", SqlDbType.Int).Value = (int)element.Value;
command.Parameters.Add("#result", SqlDbType.Int).Value = (int)element.Result;
command.Parameters.Add("#message_ID", SqlDbType.VarChar, 100).Value = element.Message_Id;
// since your statement now returns the ID value - use "ExecuteScalar"
var returnedValue = command.ExecuteScalar();
if (returnedValue != null)
{
// if a value was returned - convert to INT
int problemId = Convert.ToInt32(returnedValue);
}
}
conn.Close();
}
}
Now, in case the INSERT works, you get back the ProblemId value from the identity column, and you can now use this in your second insert as value for the #ProblemId parameter.
For saving the id into other table, you have to complete the insertion first. if the insertion is not completed then you can not get the problem id (if it is the primary key, which is supposed to be returned by saving the datas). Only after saving the data to the table, you are going to have the problem id then you can use it as FK in the same method.
if i say, there is two table and you are going to use the first table primary key in the second table as FK. Then you need to complete the first table row insertion. after excuting the query for the first table, you will get the primary key of that row and you can use easily in the second table as FK.

SQLCommand, create table

I want to create table in my database after button click. In Button_Click function I have a code
SqlConnection conn = new SqlConnection(#"MyConnectionString");
conn.Open();
SqlCommand cmd = new SqlCommand("CREATE TABLE '" + tableName+ "' (IdPy INT IDENTITY(1,1), Question NVARCHAR (MAX) NOT NULL, IsChecked BIT NOT NULL, CONSTRAINTPK_'" + tableName+ "' PRIMARY KEY(Id) )", conn);
cmd.ExecuteNonQuery();
conn.Close();
tableName is my String variable (its value 2018-04-18 asd - yes, I want the table with such a name). And I have an error after button click:
System.Data.SqlClient.SqlException: 'Incorrect syntax near '2018-04-18 asd'.'
I think that the problem is in my SqlCommand. I would be gratefull if you could help me solve that problem.
It looks like the tableName variable is 2018-04-18 asd. If that really is the correct table name, you need to escape it (and the constraint) in square brackets:
SqlCommand cmd = new SqlCommand("CREATE TABLE [" + tableName + "] (IdPy INT IDENTITY(1,1), Question NVARCHAR (MAX) NOT NULL, IsChecked BIT NOT NULL, CONSTRAINT [CONSTRAINTPK_" + tableName+ "] PRIMARY KEY(Id) )", conn);
You should escape ([...] in case of MS SQL) table and constraint names:
//DONE: wrap IDisposable into using
using(SqlConnection conn = new SqlConnection(#"MyConnectionString")) {
conn.Open();
//DONE: Make sql readable. Can you see that you've skipped CONSTRAINT keyword?
string sql =
$#"CREATE TABLE [{tableName}] (
-- Fields
IdPy INT IDENTITY(1,1),
Question NVARCHAR (MAX) NOT NULL,
IsChecked BIT NOT NULL,
-- Constraints
--DONE: Constraint key word (optional in some RDBMS) added
CONSTRAINT [CONSTRAINTPK_{tableName}] PRIMARY KEY(Id)
)";
//DONE: wrap IDisposable into using
using (qlCommand cmd = new SqlCommand(sql, conn)) {
cmd.ExecuteNonQuery();
}
}
It might be easier to identify issues with your SQLCommand by using a string variable and parameterised string formatting. An example:
string query = "CREATE TABLE #tablename (IdPy INT IDENTITY(1,1),
Question NVARCHAR (MAX) NOT NULL, IsChecked BIT NOT NULL,
CONSTRAINTPK_#tablename PRIMARY KEY(Id) )";
string param = new {#tablename = txttable.txt(example)};
SqlCommand cmd = new SqlCommand(query, param, conn);
This might help step through to make sure that the variable you have to inspect more concise.

JOIN SQL not working as it should be

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.

I want to update a row if Ptnt_id already exists if not add new one

I want to update a row if Ptnt_id already exists if not add new one
IF EXISTS (select * from `tbl_medicalhistory` where `Ptnt_id` =0) THEN
update `tbl_medicalhistory` set `txt_tongue`= 'UPDATED' where `Ptnt_id` = 0;
ELSE
INSERT INTO `tbl_medicalhistory`(`idMed`, `Ptnt_id`, `txt_tongue`, `txt_palate`, `txt_tonsil`, `txt_lips`, `txt_floorOfMouth`, `txt_cheeks`, `txt_allergy`, `txt_HeartDisease`, `txt_BloodDyscracia`, `txt_Diabetes`, `txt_kidney`, `txt_liver`, `txt_hygiene`, `txt_others`) VALUES (20],20,"This","New","Table","","","","","","","","","","","OTHERS");
idMed will be the primary key and Ptnt_id will be foreign key so if Ptnt_id already exist it will just update the entire row otherwise it will add another row with a new idMed and Ptnt_id
Can someone please help me to write that QUERY/PROCEDURE?
You can use the INSERT ... ON DUPLICATE KEY UPDATE syntax.
A simplified version of the query above would look like this:
INSERT INTO `tbl_medicalhistory`(`idMed`, `Ptnt_id`, `txt_tongue`)
VALUES (20,20,"This")
ON DUPLICATE KEY UPDATE `txt_tongue`="That";
Given that Ptnt_id is a UNIQUE or PRIMARY index, a row will be inserted of one not exists with Ptnt_id=20, otherwise if the row exists, its txt_tongue column will be updated.
Documentation
CREATE PROCEDURE [dbo].[PROCEDURE_NAME]
(
#Ptnt_id int
)
BEGIN
IF EXISTS (SELECT * FROM [dbo].[tbl_medicalhistory] WHERE Ptnt_id=#Ptnt_id)
BEGIN
UPDATE [dbo].[tbl_medicalhistory]
SET txt_tongue= 'UPDATED'
WHERE Ptnt_id=#Ptnt_id
END
ELSE
BEGIN
INSERT INTO [dbo].tbl_medicalhistory(idMed, Ptnt_id, txt_tongue, txt_palate, txt_tonsil, txt_lips, txt_floorOfMouth, txt_cheeks, txt_allergy, txt_HeartDisease, txt_BloodDyscracia, txt_Diabetes, txt_kidney, txt_liver, txt_hygiene, txt_others) VALUES (20,#Ptnt_id,"This","New","Table","","","","","","","","","","","OTHERS")
END
END
If you want to write c# coding this may help you
patient_id="123";
string str1="";
SqlConnection con=new SqlConnection(constr);
con.Open();
SqlCommand cmd=new SqlCommand("SELECT ptnt_id FROM TABLE ", con);
SqlDataReader dr=cmd.ExecuteReader();
while(dr.Read())
{
string pid=dr[0].toString();
if(patient_id == pid)
{
str1="true";
}
}
if(str1 == true)
{
con.close();
con.open();
SqlCommand cmd1=new SqlCommand("UPDATE TABLE SET ..... WHERE ptnt_id='"+pid+"' ",con);
cmd.executeNonQuery();
}
else
{
con.close();
con.open();
SqlCommand cmd1=new SqlCommand("INSERT INTO TABLE VALUES .... ",con);
cmd.executeNonQuery();
}
Change the variable datatype depends on your requirement
CREATE PROCEDURE [dbo].[PROCEDURE_NAME] (
#Ptnt_id INT
,#idMed INT
,#Ptnt_id INT
,#txt_tongue NVARCHAR(50)
,#txt_palate NVARCHAR(50)
,#txt_tonsil NVARCHAR(50)
,#txt_lips NVARCHAR(50)
,#txt_floorOfMouth NVARCHAR(50)
,#txt_cheeks NVARCHAR(50)
,#txt_allergy NVARCHAR(50)
,#txt_HeartDisease NVARCHAR(50)
,#txt_BloodDyscracia NVARCHAR(50)
,#txt_Diabetes NVARCHAR(50)
,#txt_kidney NVARCHAR(50)
,#txt_liver NVARCHAR(50)
,#txt_hygiene NVARCHAR(50)
,#txt_others NVARCHAR(50)
)
BEGIN
IF EXISTS (
SELECT 1
FROM [dbo].[tbl_medicalhistory]
WHERE Ptnt_id = #Ptnt_id
)
BEGIN
UPDATE [dbo].[tbl_medicalhistory]
SET txt_tongue = 'UPDATED'
WHERE Ptnt_id = #Ptnt_id
END
ELSE
BEGIN
INSERT INTO [dbo].tbl_medicalhistory (
idMed
,Ptnt_id
,txt_tongue
,txt_palate
,txt_tonsil
,txt_lips
,txt_floorOfMouth
,txt_cheeks
,txt_allergy
,txt_HeartDisease
,txt_BloodDyscracia
,txt_Diabetes
,txt_kidney
,txt_liver
,txt_hygiene
,txt_others
)
VALUES (
20
,#Ptnt_id
,#idMed
,#Ptnt_id
,#txt_tongue
,#txt_palate
,#txt_tonsil
,#txt_lips
,#txt_floorOfMouth
,#txt_cheeks
,#txt_allergy
,#txt_HeartDisease
,#txt_BloodDyscracia
,#txt_Diabetes
,#txt_kidney
,#txt_liver
,#txt_hygiene
,#txt_others
)
END
END

C# database Column name or number of supplied values does not match table definition

Have just started working with C# and sql and have been trying to use a database to store information, but not 100% on the syntax of it all and have been piecing it together, but have not been able to get past this error, any help would be appreciated, it is probably only something simple i have looked over.
here is the C# code i am using to try and access the database
SqlConnection myConnection = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=""F:\Bar admin\Bar admin\Database.mdf"";Integrated Security=True");
SqlCommand DatabaseNew = new SqlCommand("insert into Events Values(#Name, #Date, #Price, #Tickets, #Descrip)");
myConnection.Open();
// adds the event information to the database
DatabaseNew.Parameters.AddWithValue("#Name", TxtName.Text);
DatabaseNew.Parameters.AddWithValue("#Date", dateTimePicker1.Value);
DatabaseNew.Parameters.AddWithValue("#Price", TxtName.Text);
DatabaseNew.Parameters.AddWithValue("#Tickets", Convert.ToInt16(TxtTicketNum.Text));
DatabaseNew.Parameters.AddWithValue("#Descrip", TxtDesc.Text);
DatabaseNew.Connection = myConnection;
int n = DatabaseNew.ExecuteNonQuery();
if (n>0)
{
MessageBox.Show("Event" + TxtName.Text + "Added");
}
myConnection.Close();
and the sql code
CREATE TABLE [dbo].[Events] (
[Id] INT NOT NULL,
[Name] NCHAR (10) NULL,
[Date] DATETIME NULL,
[Price] NCHAR(10) NULL,
[Tickets] INT NULL,
[TicketsSold] INT NULL,
[Descrip] NVARCHAR(50) NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);
Again any help would be much apreaciated, thank you.
It is expecting all fields with exact order. So Id and TicketsSold are missing and causing error. You should change to:
SqlCommand DatabaseNew = new SqlCommand("insert into Events
(Name,Date,Price,Tickets,Decrip) Values(#Name, #Date, #Price, #Tickets, #Descrip)");
You are not passing ID and it doesn't appear that your ID is set to Auto increment.

Categories