Alter table add if not exists Cassandra - c#

I have an update script I created and run before.
ALTER TABLE "facilities" ADD "tariff_id" text
GO
I want to run this query again without deleting it from the script. If exists did not work with alter. How can I do it?
I have a this exception:
Cassandra.InvalidQueryException: 'Invalid column name tariff_id
because it conflicts with an existing column'

In your script, you can verify if the column exists querying the system_schema in cassandra. Is very simple in your case will be like this:
select * from system_schema.columns where keyspace_name = 'YOUR_KEYSPACE' and table_name = 'facilities' and column_name = 'tariff_id';
If return no lines mean that your column doesn't exists.
Reference:
https://docs.datastax.com/en/dse/5.1/cql/cql/cql_using/useQuerySystemTable.html

I could not find an answer to this problem. The best solution was to ignore that exception code. My solution:
try
{
DB.Instance.Execute(script);
script = "";
}
catch (Exception e)
{
//It helps to pass the lines that already exist. Alter table add etc.
if ( HResult == (-2146233088))
script = "";
else
throw e;
}

Related

What is wrong with my CREATE TABLE MySQL syntax?

I am having some trouble with the CREATE IF NOT EXISTS clause.
I am using a C# application to create a MySQL table, the connection to DB has been established so it's not a problem.
The error I am getting is an exception when I try to execute the query, I get the message:
MySql.Data.MySqlClient.MySqlException (0x80004005): You have an error
in your SQL syntax; check the manual that corresponds to your MySQL
server version for the right syntax to use near 'IF NOT EXISTS(price
VARCHAR, time VARCHAR)' at line 1
In debug mode, the immediate window shows my command string as:
CREATE TABLE ticks_14_11_2016 IF NOT EXISTS(price VARCHAR, time
VARCHAR)
From the examples I have seen, this should be the proper syntax. I am not worried about constraints and keys for the time being, I just need the query to execute...
Also, here is the C# code which I use to build the string and execute query:
string tableName = "ticks_" + getTodayString();
if (databaseClient.IsConnect()) {
string tableString = "CREATE TABLE " + tableName +
" IF NOT EXISTS" +
"(price VARCHAR, " +
"time VARCHAR)";
try
{
var command = databaseClient.Connection.CreateCommand();
command.CommandText = tableString;
command.ExecuteNonQuery();
} catch (Exception e)
{
Console.WriteLine(e);
}
}
The variable databaseClient has a member that is the MySQLConnection object
Also, my server version is: 5.6.28-76.1
You have the if not exists in the wrong place, and also, the varchar type needs a mandatory length argument.
A corrected version should be:
CREATE TABLE IF NOT EXISTS ticks_XXXXX (price VARCHAR(10), time VARCHAR(10));
Change the length to whatever is appropriate for you.
For more information see the reference manual.
You have other ways also to check whether table exists in database or not.
IF OBJECT_ID(N'dbo.ticks_14_11_2016', N'U') IS NOT NULL
BEGIN
------Exists
END
IF EXISTS(SELECT 1 FROM sys.Objects WHERE Object_id =
OBJECT_ID(N'dbo.ticks_14_11_2016') AND Type = N'U')
BEGIN
------Exists
END
IF EXISTS(SELECT 1 FROM sys.Tables WHERE Name = N'ticks_14_11_2016 ' AND Type = N'U')
BEGIN
----Exists
END
IF OBJECT_ID('ticks_14_11_2016') IS NOT NULL
BEGIN
-----Exists
END
Use your logic accordingly

Add statements to existing StoredProcedure in mssql2008

what is the best way to alter a stored procedure from C#(2010) Application code itself at installation time of an add-on.
That means there are existing SP's and different add-on's... So that I have to check the SP. is there a easy way of doing this? or do I have to read this with sp_helptext sp.... add or Change My sentence with reader/writer/string... and execute this?
Regards Oliver
This can be achieved in two ways.
Run the attached query in "Reports to File" option selected in SSMS or press ctrl+Shift+F. In the output, replace an existing column (I assume a column exists in all the Procedures and you wanted to add a new column to the Procedure) with "that column name" + "new column name". For example, if you wanted to add "coly" to the existing procedure and "colx" exists in all the procedure then do "Find and Replace" "colx" with "colx, coly". You need to make sure "colx" is not used anywhere in the condition. You should pick the column which exists only in the select clause.
Pass those two values as parameters to this script and the script does the job and produces the output.
DECLARE #to_Be_Replaced_Value nvarchar(130) = ''
DECLARE #replacing_Value nvarchar(130) = ''
SELECT REPLACE(M.DEFINITION,#to_Be_Replaced_Value,#replacing_Value) DEFINITION
FROM SYS.sql_modules M
INNER JOIN SYS.objects O ON M.object_id = O.object_id
WHERE O.type = 'P'
This may not work for you if my assumption is not met.
so I try to run a different way... but I do have some issues.
Server srv = new Server(#"server\instance");
ServerConnection conContext = new ServerConnection();
conContext = srv.ConnectionContext;
conContext.LoginSecure = false;
conContext.Login = "user";
conContext.Password = "passw";
Server srv2 = new Server(conContext);
Database db;
db = srv2.Databases["mydb"];
StoredProcedure sp = db.StoredProcedures["spMySP"];
sp.TextMode = false;
sp.AnsiNullsStatus = true;
sp.QuotedIdentifierStatus = true;
sp.TextBody = SPBody;
try
{
sp.Alter();
}
catch (SqlServerManagementException ex)
{
}
The String has something like 6000 characters and I only want to change the Body text not the keys itself. The solution postet in the first answer won't work according to the things that I have to many exeptions.. to Declaration etc...
Here I don't want to update the header of the SP, just right after as Begin... but from where I have to use the Body? without the last End?
ALTER proc [dbo].[spMySP]
#Object nvarchar(20), -- comments
#Type nchar(1), -- comments
#num_of_cols_in_key int,
#listCols nvarchar(255),
#ListColdel nvarchar(255)
AS
begin
-- Return values
.... (some Values here)...
---#mybegin#---
....
---#myend#---
the rest
end
I don't know from where I have to pick this.
OK it's done.
I used the sp.bodytext for scratching... find my part that has to be updated and store this back to sp.bodytext... starting from begin up to the last end and this will work as expected.
thanks for help

How to return auto generated id in insert query in postgres sql

I have a table.this is the script for my table:-
CREATE TABLE news
(
news_id bigint NOT NULL DEFAULT nextval('news_seq'::regclass),
title character varying(1024),
description character varying(2024),
CONSTRAINT pk_news_newsid PRIMARY KEY (news_id)
)
WITH (
OIDS=FALSE
);
ALTER TABLE news OWNER TO viewer;
Now I want to get the auto generated news_id on insert the new record in the table.
This is C# function for insert the news:-
public Int64 AddNews(News newNews)
{
string query = string.Empty;
try
{
string dateFormat = ConfigurationManager.AppSettings["DateFormat"];
NpgsqlParameter[] parm = new NpgsqlParameter[2];
parm[0] = new NpgsqlParameter("title", newNews.NewsTitle);
parm[1] = new NpgsqlParameter("des", newNews.NewsDescription);
query = #" INSERT INTO news(title, description)
VALUES (:title, :des)
Returning news_id";
int id=NpgSqlHelper.ExecuteNonQuery(connectionString, CommandType.Text, query, parm);
return id;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
On executing this function I always get the -1 value
Thanks in advance
While executing the following query on pgAdmin gives correct result:
INSERT INTO news(title, description)
VALUES ('title','description')
Returning news_id
Have you tried NpgsqlCommand.ExecuteScalar or the equivalent for the API you are using?
Two possibilities I see:
1) the -1 value indicates you are hitting a rollback situation. When you execute the function, check the table: did the record successfully insert or did some other situation cause a rollback? If so, find what is causing the rollback (see #2).
2) the -1 value also can be returned if you are running a non-insert statement. I realize you ARE running an insert, but what about any TRIGGERS on this table? Are you doing any Select statements in the trigger?
Hope this helps.

Catching specific exception while inserting data in acces database

I am inserting data into access databse and if the data is already present i.e. duplicate enty found then just need to update that enty.
public bool InsertInToTooltip()
{
InitializeSettingsDatabase();
OleDbCommand command;
command = new OleDbCommand(//Query, settingsDbConn);
try
{
command.ExecuteNonQuery();
}
catch (Exception e)
{
UpdateTable();
}
CloseDatabase();
return true;
}
Is there any specific exception thrown in case of inserting duplicate entries in acces database?
You should check if the record exists and the issue an insert or update rather than using an exception for this. You could wrap that logic in a stored procedure or do a select the an additional query.
All in one
IF EXIST (select true from table where id = #id)
Update table set x = y
Else
Insert into table (x, y) values ('x', 'y')
Try using a DataAdapter if you are using controls such as DataGridViews, ComboBoxes etc... This will automatically do all the handling for you as long as you link it to a database source and control. Otherwise i would rather do an extra sql statement that will check if the data is available in the database e.g.
SELECT * FROM TABLE WHERE COLUMN = _VAR
Based on what it returns you can either INSERT or Update. I hope this helps.

How to check for the existence of a DB?

I am wondering if there is an elegant way to check for the existence of a DB? In brief, how do test the connection of a db connection string?
Thanks
Set the Initial Catalog=master in the connection string and execute:
select count(*) from sysdatabases where name = #name
with #name set to the name of the database.
If you want to check the connection string as a whole (and not existence of an independent database), try connecting to it in a try/catch block.
To cover the range of possibilities (server doesn't exist, database doesn't exist, no login, no permissions, server down, etc) - the simplest idea is simply to try to connect as normal, and perform something trivial - SELECT GETDATE() for example. If you get an exception, there is a problem!
There are times (especially when dealing with out-of-process systems) when try/catch is the most pragmatic option.
You could just try connecting to it. If it throws an exception, then the connection string is bad in some way, either the database doesn't exist, the password is wrong, or something else.
DbConnection db = new SqlConnection(connection_string);
try
{
db.Open();
}
catch ( SqlException e )
{
// Cannot connect to database
}
Just try a DBConnection.Open() wrapped in a try block catching DBException.
About as elegant a solution as you are going to find.
try
IF NOT EXISTS(SELECT * FROM sys.databases WHERE [name] = #name)
CREATE DATABASE #name;
GO
or
IF db_id(#name) IS NOT NULL
CREATE DATABASE #name;
GO
or SqlConnection.ChangeDatabase(String). I think it could use less sql server resources then new connection attempt.
If you're using Entity Framework or have it available to you, you can simply call Database.Exists():
if (Database.Exists(connectionString))
{
// do something
}
else
{
// do something else
}
This is what worked for me to verify the existence of any Postgres database with C#:
private bool chkDBExists(string connectionStr, string dbname)
{
using (NpgsqlConnection conn = new NpgsqlConnection(connectionStr))
{
using (NpgsqlCommand command = new NpgsqlCommand
($"SELECT DATNAME FROM pg_catalog.pg_database WHERE DATNAME = '{dbname}'", conn))
{
try
{
conn.Open();
var i = command.ExecuteScalar();
conn.Close();
if (i.ToString().Equals(dbname)) //always 'true' (if it exists) or 'null' (if it doesn't)
return true;
else return false;
}
catch (Exception e) { return false; }
}
}
}
** The if used in the try-catch statement could simply check if the return of the ExecuteScalar is null for non-existent DB and not-null if it exists.
you can get list of Database with below and check your db name:
USE master
GO
SELECT name, database_id, create_date
FROM sys.databases ;
GO

Categories