I tried to drop a table in Teradata database with C# if the table exist.
cmd.CommandText = string.Format("IF EXISTS
(SELECT * FROM sysobjects WHERE type = 'U' AND name = '{0}')
BEGIN DROP TABLE '{0}' END", Customer.TableName);
cmd.ExecuteNonQuery();
But the above always failed with :
{"[Teradata Database] [3706] Syntax error: expected something between the beginning of the request and the 'IF' keyword."}
Second code i tried, the code below works !!!
cmd.CommandText = "select count (*) from Customer.TableName";
reader = cmd.ExecuteReader();
if (reader.FieldCount > 0)
{
reader.Close();
cmd.CommandText = "Drop table Customer.TableName";
reader = cmd.ExecuteReader();
}
However, it works only when got table exist. If the table Customer.TableName does not exist, then it will failed when undergo this
"select count (*) from Customer.TableName";
reader = cmd.ExecuteReader();
You can try
IF EXISTS(SELECT 1 FROM dbc.tables WHERE databasename = db_name
AND tablename = table_name) THEN DROP TABLE table_name
First Try this in editor and then place in your .net c# code.
This will ensure existence of the table and if it exists it will delete it.
Got it working with
"select count(*) from DBC.TABLES WHERE TABLENAME ='" + table.Split('.')[1] + "' and DatabaseName = '" + databasename+ "'"
Related
I am working in ASP.NET using C# and I am struggling to finish the piece of code.
A dropdownlist is displayed on my page on which the user can give a rating for a book on the page.
First, I want to check if the user already gave a rating or not (if the rating column has a value).
If it doesn't have a value, the user can then do the rating by selecting from the dropwdownlist.
Here is my code so far. I am unsure what to write within the if()
// CRUD statement
SqlCommand cmdCheck = ratingconn.CreateCommand();
cmdCheck.CommandText = "SELECT bookRating FROM tbl_ratingInfo WHERE userID = '" + Session["userID"] + "'";
if()
{
// reading the information from the database
SqlDataReader reader = cmdCheck.ExecuteReader();
if (reader.Read())
{
// setting the label text values
ddl_BookName.Text = reader.GetInt32(0).ToString();
}
}
else
{
// creating CRUD statement
SqlCommand cmdRating = ratingconn.CreateCommand();
cmdRating.CommandText = "INSERT INTO tbl_ratingInfo (bookRating) VALUES('"
+ ddl_Rating.Text + "') WHERE userID = " + Session["userID"] + "' ";
}
Here is my database. This table is an intersection table in SQL code.
-- Create the rating info table
CREATE TABLE tbl_ratingInfo
(
-- Add Foreign Keys from members and class tables
bookTitle VARCHAR (100) NOT NULL REFERENCES tbl_bookInfo(bookTitle),
userID INT NOT NULL REFERENCES tbl_userInfo(userID),
bookRating INT NOT NULL DEFAULT 5 CHECK (bookRating <= 5),
-- Composite Primary Key
PRIMARY KEY (bookTitle, userID)
)
GO
Inline query is not good practice. Please use stored procedure instead.
You can use SqlDataReader's HasRows in your if condition:
SqlCommand cmdCheck = ratingconn.CreateCommand();
cmdCheck.CommandText = "SELECT bookRating FROM tbl_ratingInfo WHERE userID = '" + Session['userID'] + "'";
//reading the information from the database
SqlDataReader reader = cmdCheck.ExecuteReader();
if (reader.HasRows) // true if the SqlDataReader contains one or more rows otherwise false.
{
if (reader.Read())
{
// setting the label text values
ddl_BookName.Text = reader.GetInt32(0).ToString();
}
}
else
{
// creating CRUD statement
SqlCommand cmdRating = ratingconn.CreateCommand();
cmdRating.CommandText = "INSERT INTO tbl_ratingInfo (bookRating) VALUES('"
+ ddl_Rating.Text + "') WHERE userID = " + Session["userID"] + "' ";
}
In my application I am getting one row from table1 displaying it in the view and then after reply I am inserting the reply into table 2 and deleting the the entry from table 1 and getting the next question from table1.
I am getting the error:
String or binary data would be truncated. The statement has been terminated
in the httppost method. I have checked the values of the tempdata in the post method by applying a breakpoint and there is no problem with it.
The values in the database are of type nvarchar except the id which is of int type.
I am not able to find why I still get the error. The error shows in the execute method but I am not able to find the reason behind it.
The things that I am inserting are mostly strings and some may contain special character in the string like * , \ etc and up to 700 characters.
PS: Presently I have ignored SQL injection threat
[HttpGet]
public ActionResult Index()
{ string connstr = "Here is the connection string";
SqlConnection conn = new SqlConnection(connstr);
conn.Open();
SqlCommand cmd = new SqlCommand(" Select top(1) Id , Body , Email_subject , Queue , Intent , Tagging FROM
table1 ");
cmd.CommandType = System.Data.CommandType.Text;
cmd.Connection = conn;
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
var Did = reader["Id"].ToString();
TempData["id "] = Int64.Parse(Did);
TempData["subject "] = reader["Email_subject"].ToString();
TempData["body"] = reader["Body"].ToString();
TempData["intent"] = reader["Intent"].ToString();
TempData["queue"] = reader["Queue"].ToString();
TempData["tagging"] = reader["Tagging"].ToString();
}
conn.Close();
TempData.Keep();
return View();
}
[HttpPost]
public ActionResult Index(string Correctornot)
{ TempData.Keep();
string connstr = My connection String;
SqlConnection conn = new SqlConnection(connstr);
conn.Open();
SqlCommand cmd = new SqlCommand("SET IDENTITY_INSERT table2 ON ; INSERT INTO table2 ( Id ,Body, Response ,Queue , Intent , Tagging , Email_subject) VALUES ( '" + TempData["id"] + "' , '" + TempData["body"] + "'
, '" + Correctornot + "' , '" + TempData["Queue"] + "' , '" + TempData["intent"] + "' , '" + TempData["tagging"] + "' , '" + TempData["subject"] + "');DELETE FROM table1 where Id = '" + TempData["id"] + "' ;");
cmd.CommandType = System.Data.CommandType.Text;
cmd.Connection = conn;
SqlDataReader reader2 = cmd.ExecuteReader();
SqlCommand cmd2 = new SqlCommand(" Select top(1) Id , Body , Email_subject , Queue , Intent , Tagging FROM table1");
cmd2.CommandType = System.Data.CommandType.Text;
cmd2.Connection = conn;
SqlDataReader reader3 = cmd2.ExecuteReader();
while (reader3.Read())
{
var Did = reader3["Id"].ToString();
TempData["id "] = Int64.Parse(Did);
TempData["subject "] = reader3["Email_subject"].ToString();
TempData["body"] = reader3["Body"].ToString();
TempData["intent"] = reader3["Intent"].ToString();
TempData["queue"] = reader3["Queue"].ToString();
TempData["tagging"] = reader3["Tagging"].ToString(); }
conn.Close();
TempData.Keep();
return View(); }
Solution:
I was able to solve the problem but I still don't know the reason behind it.
The problem was due to the value returned by clicking the button. Though the value was not too large ( it was just "correct " and "not correct") , when i tried to insert it into the database it gave me the error .
I solved it by using a switch statement instead of directly adding it to the insert statement.
i.e
switch (Correctornot)
{
case "Correct":
sql = "Insert INTO [dbo].[Labeler_Email_For_confirmation_Agents](Body , Response , Queue , Intent , Tagging , Email_subject ) Values ( '" + TempData["body"].ToString() + "' , 'yes' , '" + TempData["queue"].ToString() + "' , '" + TempData["intent"].ToString() + "' , '" + TempData["tagging"].ToString() + "' , '" + TempData["email_subject"].ToString() + "');";
break;
case "Not Correct":
sql = "Insert INTO [dbo].[Labeler_Email_For_confirmation_Agents](Body , Response , Queue , Intent , Tagging , Email_subject ) Values ( '" + TempData["body"].ToString() + "' , 'no' , '" + TempData["queue"].ToString() + "' , '" + TempData["intent"].ToString() + "' , '" + TempData["tagging"].ToString() + "' , '" + TempData["email_subject"].ToString() + "');";
break;
}
SQL Server 2016 SP2 CU6 and SQL Server 2017 CU12
introduced trace flag 460 in order to return the details of truncation warnings.
You can enable it at the query level or at the server level.
Query level
INSERT INTO dbo.TEST (ColumnTest)
VALUES (‘Test truncation warnings’)
OPTION (QUERYTRACEON 460);
GO
Server Level
DBCC TRACEON(460, -1);
GO
From SQL Server 2019 you can enable it at database level:
ALTER DATABASE database_name
SET COMPATIBILITY_LEVEL = 150
ALTER DATABASE SCOPED CONFIGURATION
SET VERBOSE_TRUNCATION_WARNINGS = ON;
The old output message is:
Msg 8152, Level 16, State 30, Line 13
String or binary data would be truncated.
The statement has been terminated.
The new output message is:
Msg 2628, Level 16, State 1, Line 30
String or binary data would be truncated in table 'DbTest.dbo.TEST', column 'ColumnTest'. Truncated value: ‘Test truncation warnings‘'.
In a future SQL Server 2019 release, message 2628 will replace message 8152 by default.
"String or binary data would be truncated. The statement has been terminated" is reporting that one of the values you are trying to insert is too large for the SQL Column. For example, you'll see this error if you try insert "Hello, World" into a SQL Column that can only hold 4 characters. Truncate the value before inserting, or change the datatype of the SQL Column.
I need to insert 388 datas per minute to local Database.
At first when the table is Empty, I only need 5 second to Insert to database.
But when the table gets larger, the program efficacy slow down to more than one minute when the amount of rows comes to 1,026,558.
And the useage of CPU is 100%. It's unusual.
here is my code:
public static void dataToDB(String[] routeIDArray,String[] levelArray,String[] valueArray,String[] travelTimeArray, int amountOfData)
{
MySqlConnection con = new MySqlConnection(connStr);
MySqlCommand cmd = null;
MySqlDataReader rdr = null;
String sqlCmd, updateSqlCmd = "UPDATE `datetimetable` SET ";
for(int counter = 0; counter < amountOfData; counter++)
{
sqlCmd = "ALTER TABLE `datetimetable` ADD COLUMN IF NOT EXISTS `" + routeIDArray[counter] + "` INT NULL;"
+ "INSERT INTO `roadvalue`.`data` (`level`,`value`,`traveltime`) VALUES ("
+ levelArray[counter] + ","
+ valueArray[counter] + ","
+ travelTimeArray[counter] + ");"
+ "SELECT LAST_INSERT_ID() FROM `data`;";
cmd = new MySqlCommand(sqlCmd, con);
con.Open();
rdr = cmd.ExecuteReader();
rdr.Read();
updateSqlCmd += "`" + routeIDArray[counter] + "` = " + rdr[0] + ",";
rdr.Close();
}
updateSqlCmd = updateSqlCmd.TrimEnd(',');
updateSqlCmd += " WHERE EXISTS (SELECT * WHERE dateTime = '" + dateTime.ToString("yyyy-MM-dd HH:mm:00") + "');";
cmd = new MySqlCommand(updateSqlCmd, con);//update data key to datetimetable
cmd.ExecuteNonQuery();
Console.WriteLine("Done.");
con.Close();
}
public static void checkDateTimeExisted()
{
MySqlConnection con = new MySqlConnection(connStr);
MySqlCommand cmd;
String sqlCmd;
sqlCmd = "INSERT INTO `datetimetable` (`dateTime`) SELECT * FROM (SELECT '" + dateTime.ToString("yyyy-MM-dd HH:mm:00")
+ "') AS tmp WHERE NOT EXISTS(SELECT `dateTime` FROM `datetimetable` WHERE `dateTime` = '" + dateTime.ToString("yyyy-MM-dd HH:mm:00") + "') LIMIT 1; ";
con.Open();
cmd = new MySqlCommand(sqlCmd, con);
cmd.ExecuteNonQuery();
con.Close();
}
And Mysql Engine is InooDB, table "data" has one Auto_Increment Primary key, table "datetimetable" has an Auto_Increment Primary key and a not duplicate datetime as index.
What have I done wrong?
I find the answer, the command "SELECT LAST_INSERT_ID() FROM data;" should add LIMIT 1 or it will get all the ID kill the performance.
Do not use ALTER TABLE in a loop -- Plan ahead and provide all the columns before starting.
Do not use multiple statements in a single string. This has security implications, etc.
Do not use WHERE EXISTS... when (I think) a simple WHERE would work.
If there is UNIQUE(datetime), then the final INSERT can be simply
INSERT IGNORE INTO datetimetable
(datetime)
VALUE
('...');
Do batch inserts unless you need the LAST_INSERT_ID(). LIMIT 1 should not be necessary.
Do not 'Normalize' datetime values; it only slows things down. Just put the datetime as is in the main table.
Im creating columns using mysql dynamically if column doesnt exist.. I got the code which works in mysql console but when it comes to c# its giving me "Fatal encountered during command execution"
SET #preparedStatement = (SELECT IF(
(SELECT COUNT(*)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = 'tableName'
AND table_schema = DATABASE()
AND column_name = 'colName'
) > 0,
"SELECT 1",
"ALTER TABLE `tableName` ADD `colName` TINYINT(1) NULL DEFAULT '0';"
));
PREPARE alterIfNotExists FROM #preparedStatement;
EXECUTE alterIfNotExists;
DEALLOCATE PREPARE alterIfNotExists;
above code i converted into c# string as
string qry = "SET #preparedStatement = ( SELECT IF( (SELECT count(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = 'attendance' AND TABLE_NAME = '" + tname + "' AND COLUMN_NAME = '" + code + "_C' ) > 0, \"SELECT 1', \"ALTER TABLE " + tname + " ADD " + code + "_C int(3) NOT NULL default '0'; \" )); PREPARE alterIfNotExists FROM #preparedStatement; EXECUTE alterIfNotExists; DEALLOCATE PREPARE alterIfNotExists;";
what's the error getting?
Execution Code:
private void columnCreate_Load(object sender, EventArgs e)
{
string tname = "bca_i"; //for temprory
string code = "BCAXX";//for temprory
string qry = #"SET #preparedStatement = ( SELECT IF( (SELECT count(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = 'attendance' AND TABLE_NAME = '" + tname + "' AND COLUMN_NAME = '" + code + "_C' ) > 0, \"SELECT 1', \"ALTER TABLE " + tname + " ADD " + code + "_C int(3) NOT NULL default '0'; \" )); PREPARE alterIfNotExists FROM #preparedStatement; EXECUTE alterIfNotExists; DEALLOCATE PREPARE alterIfNotExists;";
try
{
using (MySqlConnection conn = new MySqlConnection(ConStr))
{
conn.Open();
using (MySqlCommand cmd = new MySqlCommand(qry, conn))
{
cmd.ExecuteNonQuery();
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
The part
\"SELECT 1', \"A
does not match your original query at
"SELECT 1",
"A
Do you spot it? You replaced the " after 1 by an '.
I just figured other way for checking column exist.. Just used below query and checked if the column exists iterating through the loop of columns
string last_col = "SELECT COLUMN_NAME FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = 'attendance' AND TABLE_NAME ='" + subCodeText.Text + "'";
where attendance is database and subCodeText.Text is my table name.
I have different tables in my database. I want to write a single query to handle all tables like:
comm.CommandText = "Select * from table1 where UserId='" + 1 + "'";
comm.CommandText = "Select * from table2 where UserId='" + 1 + "'";
It is same query but different table name.
Is there any possible way to write both query with one query?
Thanks.
try using this:
string query = string.Format("Select * from {0} where UserId={1}", tableName, userID);
You can try with this code - string.Format
var input = "table 1";
var query = string.Format("Select * from {0} where UserId= 1 ",input);
comm.CommandText = query;