Looking for solution in case statement in SQL Server - sql-server-2008

I am trying to write this below statements in case statements. Trying to update a value in one different TableB for a particular column.
After I do
Update a
set DISMMR =
then trying to check this below condition in case statements
'H01' Is not NULL
and
('H02','H03','HR04','S07','S08','S09') Is NULL
Then 'Unknown'
Here this values are from table name : TableA and column name is Code.
This particular column is designed to be NOT NULL
Here where I say Is NULL means I am trying to say that, this particular value ('H02','H03','HR04','S07','S08','S09') don't exist or present in TableA.
When I say this particular value H01 in TableA for column Code ---- Is not NULL -- means this particular value of column Code exist/present in a column from TableA.
I need to do this one in case statements because once I am done checking this condition , I am writing other case statements started with WHEN to check another condition and update with different value
I am using SQL Server 2008 R2. Now I wrote the below query. It runs fine in SSMS but when i use this Store procedure in SSIS package. My package fails with error.
[Execute SQL Task] Error: Executing the query "execute [dbo].[usp_GetMRF_CHP] ?,?,?" failed with the following error: "Only one expression can be specified in the select list when the subquery is not introduced with EXISTS.". Possible failure reasons: Problems with the query, "ResultSet" property not set correctly, parameters not set correctly
CASE WHEN EXISTS(SELECT 1 FROM dbo.TableA WHERE Code = 'H01')
AND NOT EXISTS(SELECT 1 FROM dbo.TableA
WHERE Code IN ('H02','H03','HR04','S07','S08','S09')
)
THEN 'Unknown'
when ---- I have another case here.
Any help will be very much appreciated. Thanks in advance

If I understand you correct you want to know if a record with Code = 'H01' exists while no record with the other codes exist. The case statement for that would look like this:
CASE WHEN EXISTS(SELECT 1 FROM dbo.TableA WHERE Code = 'H01')
AND NOT EXISTS(SELECT 1 FROM dbo.TableA
WHERE Code IN ('H02','H03','HR04','S07','S08','S09')
)
THEN 'Unknown'
END

Related

A variable is cut in a wrong way but now sure why?

I'm writing a script that locates all branches of a specific repo that haven't received any commits for more than 6 months and deletes them (after notifying committers).
This script will run from Jenkins every week, will store all these branches in some MySQL database and then in the next run (after 1 week), will pull the relevant branch names from the database and will delete them.
I want to make sure that if for some reason the script is run twice on the same day, relevant branches will not get added again to the database, so I check it using a SQL query:
def insert_data(branch_name):
try:
connection = mysql.connector.connect(user=db_user,
host=db_host,
database=db_name,
passwd=db_pass)
cursor = connection.cursor(buffered=True)
insert_query = """insert into {0}
(
branch_name
)
VALUES
(
\"{1}\"
) where not exists (select 1 from {0} where branch_name = \"{1}\" and deletion_date is NULL) ;""".format(
db_table,
branch_name
)
cursor.execute(insert_query, multi=True)
connection.commit()
except Exception as ex:
print(ex)
finally:
cursor.close()
connection.close()
When I run the script, for some reason, the branch_name variable is cut in the middle and then the query that checks if the branch name already exists in the database fails:
1064 (42000): 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 'where not exists (select 1 from branches_to_delete where branch_name = `AUT-1868' at line 8
So instead of checking for 'AUT-18681_designer_create_new_name_if_illegal_char_exist' it checks for 'AUT-1868' which doesn't exist in the database.
I've tried the following:
'{1}'
"{1}"
{1}
But to no avail.
What am I doing wrong?
Using WHERE statement in INSERT INTO query is illegal:
INSERT INTO `some_table`(`some_column`)
VALUES ('some_value') WHERE [some_condition]
So, the above example is not valid MySQL query. For prevent duplication of branch_name you should add unique index on your table like:
ALTER TABLE `table` ADD UNIQUE INDEX `unique_branch_name` (`branch_name`);
And after this you can use next query:
INSERT INTO `table` (`branch_name`) VALUES ('branch_name_1')
ON DUPLICATE KEY UPDATE `branch_name` = `branch_name`;
Pay attention: If your table have auto-increment id, it will be incremented on each insert attempt
Since MySQL 8.0 you can use JASON_TABLE function for generate pseudo table from your values filter it from already exists values and use it fro insert. Look here for example
I don't see anything wrong assuming the source of the branch_name is safe (you are not open to SQL Injection attacks), but as an experiment you might try:
insert_query = f"""insert into {db_table}(branch_name) VALUES(%s) where not exists
(select 1 from {db_table} where branch_name = %s and deletion_date is NULL)"""
cursor.execute(insert_query, (branch_name, branch_name))
I am using a prepared statement (which is also SQL Injection-attack safe) and thus passing the branch_name as a parameters to the execute method and have also removed the multi=True parameter.
Update
I feel like a bit of a dummy for missing what is clearly an illegal WHERE clause. Nevertheless, the rest of the answer suggesting the use of a prepared statement is advice worth following, so I will keep this posted.

mysql case statement fails to create a new column

Sorry about asking the basics. I am trying to make a new column named new_column as in the code below while keeping the old_column as well. When I run the below query, I do get the results printed out fine on the console, but failed to insert the results to the new_column.
I tried both ways, first creating a column named new_column (empty) and then run the query, and secondly just running the query as below. Both didn't return new_column inserted with integer values. What am I missing?
SELECT old_column CASE
WHEN 'A' THEN 1
WHEN 'B' THEN 2
WHEN 'C' THEN 3
ELSE 0
END AS new_column
FROM table_name
Your syntax is wrong, and doesn't produce anything except an error message as you've written it here.
If I understand your question correctly, this should produce the output you want:
SELECT
old_column,
CASE old_column
WHEN 'A' THEN 1
WHEN 'B' THEN 2
WHEN 'C' THEN 3
ELSE 0
END AS new_column
FROM
table_name
A SELECT does exactly what it says it does - it selects the data, but doesn't actually alter it's content.
To permanently add a new column and populate it, you'll need to first ALTER TABLE to add the new column, and then UPDATE that new column's content.
ALTER TABLE table_name ADD COLUMN newcolumn integer;
UPDATE
table_name
SET newcolumn = CASE oldcolumn
WHEN 'A' THEN 1
WHEN 'B' THEN 2
WHEN 'C' THEN 3
ELSE 0
END;
For future reference: If you want help with your SQL syntax, include the actual code you've tried that isn't working, instead of inventing something as you go or re-typing. With SQL-related questions, it's almost always a good idea to post some sample data and the output you'd like to obtain from that data, along with your actual SQL code trying to produce that output. It makes it much easier to help you when we can understand what you're trying to do and have samples to use.

MySQL syntax error regarding WHERE NOT EXISTS

I have a Chef recipe for creating Unix user IDs and deploying them across multiple nodes, to guarantee uniqueness and prevent devs from having to track them themselves. They merely name the application and it is granted a unique ID if an ID for that application doesn't already exist. If one does, it is simply returned to the script and user accounts are created on the webservers with the appropriate value.
I have a mysql database with a single table, called application_id_table which has two columns, id and application_name. id is autoincrementing and application name cannot be null (and must be unique).
Removing the Ruby from my script and making a couple of substitutions, my sql looks like this:
INSERT INTO application_id_table(application_name) VALUES('andy_test')
WHERE NOT EXISTS (select 1 from application_id_table WHERE
application_name = 'andy_test');
when run, I receive the syntax parsing error:
ERROR 1064 (42000): 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 'WHERE NOT EXISTS (select 1 from
application_id_table WHERE application_name = 'a'
I recall seeing that the values statement does not allow a where clause but I don't wish to use a select statement to populate the values as I'm populating them from variables supplied from within Ruby/Chef. Anyone have an idea how to accomplish this?
You want to use insert . . . select:
INSERT INTO application_id_table(application_name)
SELECT aname
FROM (SELECT 'andy_test' as aname) t
WHERE NOT EXISTS (select 1 from application_id_table ait WHERE ait.application_name = t.aname);
You should be able to plug your variable directly into the select statement, the same you would would with the VALUES statement.
Try this:
INSERT INTO application_id_table(application_name)
select 'andy_test'
WHERE NOT EXISTS (select 1 from application_id_table WHERE application_name = 'andy_test');

How to neglect "Invalid column name" error in SQL Server 2008 R2

I am using SQL Server 2008 R2. I have created some SQL statements for some migration:
IF EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='TableA' AND COLUMN_NAME='Status')
BEGIN
UPDATE TableA
SET Status = 'Active'
WHERE Status IS NULL
END
Now, I have dropped the column Status from database table TableA.
Again when I am executing the above block, and although I have placed a check whether that column exists, only then it should execute the UPDATE statement, it gives me error
Invalid column name 'Status'
How to get rid of this error?
Thanks
You need to put the code to run in a separate scope/batch:
IF EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME='TableA' AND COLUMN_NAME='Status')
BEGIN
EXEC('UPDATE TableA SET Status=''Active'' WHERE Status IS NULL')
END
The problem you currently have is that the system wants to compile your batch of code before it executes any part of it. It can't compile the UPDATE statement since there's a column missing, so it never even has a chance to start executing the code and considering whether the EXISTS predicate returns true or false.
Your current SQL Block might fail some times because Information_schema is view and not a table. Also, according to MSDN
Some changes have been made to the information schema views that break backward compatibility.
Hence we can't rely on information schema views.
Instead use sys.tables
IF EXISTS(SELECT 1 FROM SYS.COLUMNS
WHERE NAME = N'Status' AND OBJECT_ID = OBJECT_ID(N'TableA'))
BEGIN
UPDATE TableA SET Status='Active' WHERE Status IS NULL
END

UPDATE OPENQUERY failure

I'm getting an error in the following OPENQUERY statement that I'm trying to execute against a MySql database from SQL Server.
UPDATE OPENQUERY(MYWPDB, 'SELECT total FROM wp_tt WHERE id = 112121') SET total = 1
The error is "Key column information is insufficient or incorrect. Too many rows were affected by update".
The statement should be updating the 'total' field to the value of '1'. It's an integer field and 'id' is the primary key on the table. I'm using SQL Server 2000.
I had the same issue with an openquery that updates iSeries. My openquery is within a cursor also.
The fix is to include the key columns in the select.
So in your case it would be something like this:
UPDATE OPENQUERY(MYWPDB, 'SELECT key1, key2, total FROM wp_tt WHERE id = 112121') SET total = 1
Turns out there's nothing wrong with the query. I was trying to execute the statement inside a cursor operation inside a stored procedure. I tested it outside the cursor operation and it processed fine.
However, since I still needed it to work within the cursor, I had to keep digging, and finally found the four-part syntax would do the trick. So the query instead became:
UPDATE MYWPDB...wp_tt SET total = 1 WHERE id = 112121