SQL insert row data, trough nulls are not allowed - sql

I created a simple database in sql 2012 where I didnt allow to store null data, I checked out my program and I see that it still save empty row :( Is there option that can help me prevent save null in db (and why turning off "allow null" didnt stop it?) ?

You want a CHECK Constraint. This will throw an error when a statement attempts to put data in a field that doesn't match the criteria.
ALTER TABLE UserInfo ADD CONSTRAINT CK_UserInfo_Login CHECK (Login <> '')

Related

Sybase ASE: Add NOT NULL column without a DEFAULT fails. Why?

Consider the following empty (as in without rows) table:
CREATE TABLE my_table(
my_column CHAR(10) NOT NULL
);
Trying to add a NOT NULL column without a DEFAULT will fail:
ALTER TABLE my_table ADD my_new_column CHAR(10) NOT NULL;
Error:
*[Code: 4997, SQL State: S1000]
ALTER TABLE my_table failed.
Default clause is required in order to add non-NULL column 'my_new_column'.
But adding the column as NULL and then change it to be NOT NULL will work:
ALTER TABLE my_table ADD my_new_column CHAR(10) NULL;
ALTER TABLE my_table MODIFY my_new_column CHAR(10) NOT NULL;
Setting a default and then removing the default will work too:
ALTER TABLE my_table ADD my_new_column CHAR(10) DEFAULT '' NOT NULL;
ALTER TABLE my_table REPLACE my_new_column DEFAULT NULL;
What's the justification for this behavior? What is the database trying to do internally that adding the column directly fails? I have a feeling that it might have something to do with internal versioning but I can't find anything in this regard.
This is speculation. I am guessing that Sybase is being overly conservative. In general, you cannot add a new not null column with no default value to a table that has rows. This is true in all databases, because there is no way to populate the existing rows for the new column.
I am guessing that Sybase simply doesn't check if the table has rows, only if it exists. Clearly it is not doing the check for the alter.
This is only speculation, but I suspect it has to do the combination of needing to both acquire a lock on the whole table to guarantee continued compliance with the schema, and re-allocate space for the records.
Allowing a direct add of a NOT NULL column would compromise any existing records if there's no default value. Yes, we know the table is empty. And the database can (eventually) know the table is empty at execution time... but it can't really know the table is empty at execution plan compile time, because a row could be added while the execution plan is determined.
This means the database would need to generate the worst-possible execution plan, involving a lock on the entire table, for the query to run in a transactionally-safe way. Additionally, adding (or removing) a column causes extra work for the database because it needs to re-allocate any pages and rebuild indexes in order to account for the changed size of individual records.
Put the two together, and it becomes difficult to just rollback a failed query, because you may have actual pages in different states. For whatever reason, the developers chose not to allow this.
The other options allow you to simply fail the query if a bad row gets in the way and would violate the schema, because you're not re-sizing records within pages. It might even allow you to get away with some page and row locks, rather than full table locks.

Syntax Error or Access Violation comes up when logging into the program

our program connects to a db and when you sign into the program, it's throwing this error: "Syntax error or access violation" along with "Cannot insert the value NULL into column 'ID', table 'CADDB.dbo.AuditTrail'; column does not allow nulls. INSERT fails"
I've tried Microsoft's Fix to Use ANSI Nulls, Padding and Warnings in the ODBC connections, but it still occurs.
Can someone point me where to look? I believe it's corrupt data in the db... but not 100% sure. I will attach the error that gets logged with that message if you need me to.
The exception showed you the root cause that your app is trying to insert NULL value into column ID, a column not allowing NULL. If this is caused by your application's bug and you also want to insert a NULL value into ID column. Then you may change the table to allow NULL for column ID or use a special value representing NULL (not recommended) for the insertion.
Otherwise, it is more likely to be your application's issue.
You need to make sure the column from CADDB.dbo.AuditTrail allow nulls,check your table schema for that, or you could try insert into the column ISNULL(value,'NULL'), which is the string null not actual NULL.
ANSI_NULL query option only be took into effect when doing the value comparison. which is IS NULL/IS NOT NULL when it is set to ON or using =/!=/<> when set to OFF.
Use the ISNULL() function. Example ISNULL(column Name, '')
I'm not sure if you're using T-SQL script in your code to access the table, or you can alter the column to allow nulls.
Thank you everybody! The issue was the db was corrupt. I got a working backup of the same db and it works fine without any errors.

Editing Record issues in Access / SQL (Write Conflict)

a problem has come up after a SQL DB I used was migrated to a new server. Now when trying to edit a record in Access (form or table), it says: WRITE CONFLICT: This record has been changed by another user since you started editing it...
Are there any non obvious reasons for this. There is noone else using the server, I've disabled any triggers on the Table. I've just found that it is something to do with NULLs as records that have none are ok, but some rows which have NULLs are not. Could it be to do with indexes? If it is relevant, I have recently started BULK uploading daily, rather than doing it one at a time using INSERT INTO from Access.
Possible problems:
1 Concurrent edits
A reason might be that the record in question has been opened in a form that you are editing. If you change the record programmatically during your editing session and then try to close the form (and thus try to save the record), access says that the record has been changed by someone else (of course it's you, but Access doesn't know).
Save the form before changing the record programmatically.
In the form:
'This saves the form's current record
Me.Dirty = False
'Now, make changes to the record programmatically
2 Missing primary key or timestamp
Make sure the SQL-Server table has a primary key as well as a timestamp (= rowversion) column.
The timestamp column helps Access to determine if the record has been edited since it was last selected. Access does this by inspecting all fields, if no timestamp is available. Maybe this does not work well with null entries if there is no timestamp column (see 3 Null bits issue).
The timestamp actually stores a row version number and not a time.
Don't forget to refresh the table link in access after adding a timestamp column, otherwise Access won't see it. (Note: Microsoft's Upsizing Wizard creates timestamp columns when converting Access tables to SQL-Server tables.)
3 Null bits issue
According to #AlbertD.Kallal this could be a null bits issue described here: KB280730 (last snapshot on WayBackMachine, the original article was deleted). If you are using bit fields, set their default value to 0 and replace any NULLs entered before by 0. I usually use a BIT DEFAULT 0 NOT NULL for Boolean fields as it most closely matches the idea of a Boolean.
The KB article says to use an *.adp instead of a *.mdb; however, Microsoft discontinued the support for Access Data Projects (ADP) in Access 2013.
Had this problem, same as the original poster. Even on edit directly using no form. The problem is on bit fields, If your field is Null, it converts Null to 0 when you access the record, then you make changes which this time is the 2nd change. So the 2 changes conflicts. I followed Olivier's suggestion:
"Make sure the table has a primary key as well as a timestamp column."
And it solved the problem.
I have seen a similar situation with MS Access 2003 (and prior) when linked to MS SQL Sever 2000 (and prior). In my case I found that the issue to be the bit fields in MS SQL Server database tables - bit fields do not allow null values. When I would add a record to a table linked via the MS Access 2003 the database window an error would be returned unless I specifically set the bit field to True or False. To remedy, I changed any MS SQL Server datatables so that any bit field defaulted to either 0 value or 1. Once I did that I was able to add/edit data to the linked table via MS Access.
I found the problem due to the conflict between Jet/Access boolean and SQL Server bit fields.
Described here under pitfall #4
https://blogs.office.com/2012/02/17/five-common-pitfalls-when-upgrading-access-to-sql-server/
I wrote an SQL script to alter all bit fields to NOT NULL and provide a default - zero in my case.
Just execute this in SQL Server Management Studio and paste the results into a fresh query window and run them - its hardly worth putting this in a cursor and executing it.
SELECT
'UPDATE [' + o.name + '] SET [' + c.name + '] = ISNULL([' + c.name + '], 0);' +
'ALTER TABLE [' + o.name + '] ALTER COLUMN [' + c.name + '] BIT NOT NULL;' +
'ALTER TABLE [' + o.name + '] ADD CONSTRAINT [DF_' + o.name + '_' + c.name + '] DEFAULT ((0)) FOR [' + c.name + ']'
FROM
sys.columns c
INNER JOIN sys.objects o
ON o.object_id = c.object_id
WHERE
c.system_type_id = 104
AND o.is_ms_shipped = 0;
This is a bug with Microsoft
To work around this problem, use one of the following methods:
Update the form that is based on the multi-table view
On the first occurrence of the error message that is mentioned in the "Symptoms" section, you must click either Copy to Clipboard or
Drop Changes in the Write Conflict dialog box. To avoid the repeated
occurrence of the error message that is mentioned in the "Symptoms"
section, you must update the recordset in the form before you edit
the same record again.
Notes
To update the form in Access 2003 or in Access 2002, click Refresh on the Records menu.
To update the form in Access 2007, click Refresh All in the Records group on the Home tab.
Use a main form with a linked subform
To avoid the repeated occurrence of the error message that is mentioned in the "Symptoms" section, you can use a main form with a
linked subform to enter data in the related tables. You can enter
records in both tables from one location without using a form that is
based on the multi-table view.
To create a main form with a linked subform, follow these steps:
Create a new form that is based on the related (child) table that is used in the multi-table view. Include the required fields
on the form.
Save the form, and then close the form.
Create a new form that is based on the primary table that is used in the multi-table view. Include the required fields on the
form.
In the Database window, add the form that you saved in step 2 to the main form.
This creates a subform.
Set the Link Child Fields property and the Link Master Fields property of the subform to the name of the field or fields that are
used to link the tables.
Methods from work around taken from microsoft support
I have experienced both of the causes detailed above: Directly changing data in a table that is currently bound to a form AND having a 'bit' type field in SQL Server that does not have the Default Value set to '0' (zero).
The only way I have been able to get around the latter issue is to add the default value of zero to the bit field AND run an update query to set all current values to zero.
In order to get around the former error, I have had to be inventive. Sometimes I can change the order of the VBA statements and move Refresh or Requery to a different location, thus preventing the error message. In most cases, however, what I do is DIM a String variable in the Subroutine where I call the direct table update. BEFORE I call the update, I set this String variable to the value of the Recordsource behind the bound form, thus capturing the exact SQL statement being used at the time. Then, I set the form's Recordsource to an empty string ("") in order to disconnect it from the data. Then, I perform the data update. Then, I set the form's Recordsource back to the value saved in the String variable, reestablishing the binding and allowing it to pick up the new value(s) in the table. If there is one or more subforms contained within this form, then the "Link" fields need to handled in a similar manner as the Recordsource. When the Recordsource is set to an empty string, you may see #Name in the now-unbound fields. What I do is simply set the Visible property to False at the highest possible level (Detail section, Subform, etc.) during the time when the Recordsource is empty, hiding the #Name values from the user. Setting the Recordsource to an empty string is my go-to solution when a coding change can't be found. I am wondering, though, if my design skills are lacking and there is a way to completely avoid the issue altogether?
One final thought on addressing the error message: Instead of calling a routine to directly update the data in the table table, I find a way to update the data via the form instead, by adding a bound control to the form and updating the data in that so that the form data and the table data do not become out of sync.
In order to get over this problem. I created VBA to change another field in the same row. So I created a separate field which adds 1 to the contents when I try to close the form. This solved the issue.
I've dealt with this issue with MS Access tables linked to MS SQL tables multiple times. The original poster's response was extremly helpful and was indeed the source of much of my issues.
I also ran into this issue when i accidently added a bit field with a space in the fieldname... yeah....
I had run alter table tablename add [fieldname ] bit default 0. i solution i found was to drop that field and not have a space in the name.
I had this issue and realized it was caused by adding a new bit field to an existing table. I deleted the new field and everything went back to working fine.
If you are using linked tables, ensure you have updated these and retry before doing anything else.
I thought I had updated them but hadn't, turns out someone had updated the form validation and SQL tables to allow 150 chars, but hadn't refreshed the linked table hence access only saw 50 char allowed - Boom Write conflict
Not sure this is the most appropriate error for the scenario, but hey, most of the interesting issues are never flagged appropriately in any microsoft software!
I´m using this workaround and it has worked for me:
Front end: Ms Access
Backend: Mysql
On the Before update event of a given field:
Private Sub tbl_comuna_id_comuna_BeforeUpdate(Cancel As Integer)
If Me.tbl_comuna_id_comuna.OldValue = Me.tbl_comuna_id_comuna.Value Then
Cancel = True
Undo
End If
End Sub
I just had very havy write-conflict problems (Acc2013 32bit, SQL Srv2017 expr) with a rather "heavy loaded" Split-Form.
For me - at last - was the solution to get rid of the write-conflict problems to simply
SET THE AcSplitFormDatasheet to READ-ONLY !!! (I haven't a clue why it was read-write anyway i must have set it by fault...)
It did nearly cost me a whole week to find that out.
I was having this problem and saving the record, marking Dirty to false, etc. did not work. It ended up that adding a timestamp column to the SQL table is what avoided/fixed the issue.
When last time I got this error, it was bit field having NULL value issue.
But this time, it was different text size of source table field vs linked table field.
I checked all my bit fields in various tables but didn't find any issue. All of them had default value, so there were no NULL values for bit fields. I observed that a text field with nvarchar(500) was giving this error. The linked table was using old field size 50 instead of recently changed 500. Relink of tables solved the problem.
So another finding is if the data type is changed for a linked table, you need to relink the table.
Just had this issue on MS Access 365 connected to PostgreSQL server. The error only occurred when trying to edit the first row.
I manually deleted the first row in pgAdmin 4, and then manually added it again. This solved the issue.
I was receiving the same error message.
Id Column in database table was set to BigInt, changing it to Int resolved the issue.

Delete from sql server 2000?

I want to delete all rows from table in sql server 2000 but whenever I want to delete manually or with query it shows error. In help tab it shows ODBC error: <0s>.
My table contains some '0' values but its datatype is String. Is that's the reason for this
error.
code is:
stat2=conn.createStatement();
stat2.executeUpdate("Delete * from pat.dbo.PHPL");
"Key column information is insufficient or incorrect. Too many rows were affected by update" that's warning and when click help it shows: ODBC error: <0s>. An ODBC error has been generated. You might have deleted a record that has a foreign key value related to it, or you might have violated a check constraint. For details, refer to your ODBC documentation.
Use
Truncate Table PHPL
I think you have duplicate identities, check you are not allowing duplicates on this column.

Avoid duplicate rows in phonegap database

I have a database with a single column and create it like this
function populateDB(tx){
tx.executeSql('CREATE TABLE IF NOT EXISTS RESULT(result, UNIQUE(result))');
}
however, when I want to write objects into the table, I get the error:
could not execute statement (19 constraint failed)
The error only appears when I add the NOT NULL and PRIMARY KEY to the set-Up. Without it, it keeps writing duplicates in my database (I fill the database with data from a webservice on startup of a phonegap iOS application, so I want to catch duplicate rows on database level)
At first I had only "PRIMARY KEY" in it, and because the error says something about constraints, I was assuming the primary key has to be "NOT NULL", adding it to the code, I still got the same error.
how can I solve this. thanks in advance
edit: Maybe it´s important for you to know that I write stringyfied JSON Objects into the results column.
edit: I insert the object in this function. Basically I do it one by one:
this.save = function(){
db.transaction (function(transaction){
object = $.toJSON(self);
object = encodeURI(object);
transaction.executeSql('INSERT INTO RESULT (result) VALUES ("'+object+'")');
},
errorCB,
successCB
);
}
edit: I updated my set up table code. The error doesnt occur on every row, but the objects are actually unique.
"IF NOT EXISTS" is the catch here. You get constraint failed when you use conditions like "IF NOT EXISTS" or "REPLACE", "IGNORE" etc in SQLite queries.
Suppose, you're trying to create a table that already exists, then the constraint (here not creating the table again if it already exist) fails and hence the query fails (which you actually want - you dont want to duplicate the tables right?) and gives you the error constraint failed.
You may get a similar error on INSERT or REPLACE, INSERT or IGNORE, etc...