Not able to update column which was set as null using 'select into' statement in sybase - sql

I am creating a temp table in sybase like below
select col1 = null, col2 =2 into #myTable
Here when I try to update col1
update #myTable set col1 = 'test'
I get error - "[Error Code: 257, SQL State: 42000] Implicit conversion from datatype 'VARCHAR' to 'INT' is not allowed. Use the CONVERT function to run this query."
Can anyone please help me fix it?

Assuming this is Sybase ASE (257 is a standard ASE system error number) ...
col1=null doesn't tell the database what the datatype of col1 should be so the database defaults the column's datatype to int.
When creating a table via select/into you need to insure each column is created with the desired datatype. For this particular instance try:
select col1=convert(varchar(10),null), col2=convert(tinyint,2) into #myTable
NOTES:
modify the convert() calls to reference the desired datatypes
when the new column is populated from another table's column(s) the source column(s) datatypes will be used in determing the datatype of the new column
Also keep in mind the following:
select col1='test' into #otherTable
The datatype for col1 will be determined from the initial data value; in this case the value 'test' tells the database you need to store 4 characters so the database will default the column's datatype to varchar(4). This should be fine as long as you never intend to insert anything longer than varchar(4) otherwise you'll need to provide a convert() with the initial select/into to explicitly state the column's datatype, eg:
select col1=convert(varchar(35),'test') into #otherTable
Assuming you get past the Implicit conversion from datatype 'VARCHAR' to 'INT' is not allowed. error message your next bump-in-the road may occur if you try something like:
update #myTable set col2 = NULL
With the result being that you're presented with an error message similar to column does not allow nulls.
As with datatype determination, Sybase (ASE) will try to determine a column's NULLability in a few different ways:
if column is assigned a 'value' of NULL (as in the example: col1 = null) then ASE will configure the column to allow NULLs
if the column's value is being copied from another table then the source column's NULLability will be used in determining the new column's NULLability
if the query explicitly defines the column as NULLable (see example - below) then the column will be configured to allow NULLs
if the database option allow nulls by default is false (ASE default setting) then the column's NULLability will be set to 'not NULL'
when all else fails ...
if the database option allow nulls by default is true then the column's NULLability will be set to 'NULL'(able)
An example of explicitly defining the column to allow NULLs:
select col1 = convert(varchar(35) null,'test') into #otherTable

Related

Does altering column type corrupt the column's existing data?

I am trying to change a column's datatype. The column of type VARCHAR has thousands of GUID values like look those shown below:
b1f4ff32-48d4-494e-a32c-044014cea9
bc5a1158-b310-49ff-a1f3-09d4f8707f69
4b7ebc9d-9fa1-42d9-811e-0b7b4b7297a
fc7ba848-98ea-4bc6-add7-11f0ee9c6917a21
485741ff-2ab2-4705-91b3-136389948b7c
I need to convert the column type to unqiqueidentifier using the script below. Can I do that safely without corrupting the column data?
alter table MyTable
alter column guidColumn uniqueidentifier not null
If you change the data type SQL Server will first check if all the values in the columns can be implicitly converted to the new data type; if they cannot then the ALTER will fail. If they can, then they will be implicitly converted and the ALTER will be successful (assuming no dependencies of course).
For a uniqueidentifier then either it's a valid value or it's not, so either the data will all convert or the ALTER won't take place. For something like a date and time data type, however, you could very easily end up with incorrect data if the data is stored in an ambiguous format like dd/MM/yyyy. This could mean a value like '12/05/2022' ends up being stored as the date value 2022-12-05 rather than 2022-05-12. For such scenarios you would therefore want to UPDATE the data to an unambiguous format first, and then ALTER the data type of the column.
The uniqueidentifier type is considered a character type for the purposes of conversion from a character expression, and therefore is subject to the truncation rules for converting to a character type.
Also there are limitations, uniqueidentifier type is limited to 36 char
So if you decide to truncate the table like in this example:
DECLARE #ID NVARCHAR(max) = N'0E984725-C51C-4BF4-9960-E1C80E27ABA0wrong';
SELECT #ID, CONVERT(uniqueidentifier, #ID) AS TruncatedValue;
This will be the result:
String
Truncated Value
0E984725-C51C-4BF4-9960-E1C80E27ABA0wrong
0E984725-C51C-4BF4-9960-E1C80E27ABA0
So, if your string is more or less than 36 it will not truncate correctly.
For more information check Microsoft documentation:
https://learn.microsoft.com/en-us/sql/t-sql/data-types/uniqueidentifier-transact-sql?view=sql-server-ver15

SQL statement to change the value of a column with that same column in the where clause

I have a SQL Server database and I've changed my mind and instead of a column in my table being set as an int, I want to change it to a varchar. So I changed the type to varchar(8), and saved my changes in SQL Server Management Studio tool (V17.0).
It looks like the tool converted the int values to varchars when I saved the changes. I want to change the value of '1' to 'External', '2' to 'SPTR' and '3' to 'Other'. I was going to do one value at a time.
This is the simple SQL statement I tried:
UPDATE mytable
SET mycolumn = 'External'
WHERE mycolumn = '1'
The error message I get from SSMS is
Conversion failed when converting the varchar value 'External' to data type int"
It's as if the database thinks the type is int, but it's not, it's varchar(8).
Sounds like you really haven't changed the data type. This should resolve the problem.
ALTER TABLE mytable ALTER COLUMN mycolumn varchar(8);
GO
UPDATE mytable
SET mycolumn = CASE mycolumn WHEN '1' THEN 'External'
WHEN '2' THEN 'SPTR'
ELSE 'OTHER'
END;
Note, as well, you can update every value at the same time by using a CASE expression. Likely far easier than 3 UPDATE statements.
ALTER TABLE mytable ALTER COLUMN mycolumn varchar(50);
SELECT DATALENGTH ('External')
returns 8
As long as I know varchar does not use all 50 bytes, it only uses 8 in your case to store "External" field, why don't you try to change table size.
If you have changed mycolumn to a string, then the following should work:
UPDATE mytable
SET mycolumn = 'External'
WHERE mycolumn = '1';
If you are getting a type conversion error, then I assume you have a trigger on the table that is causing the problem. You might be wrong in saying that the type has changed. But even if you are correct, a trigger could still generate this issue.

Trigger to convert empty string to 'null' before it posts in SQL Server decimal column

I've got a front table that essentially matches our SSMS database table t_myTable. Some columns I'm having problems with are those with numeric data types in the db. They are set to allow null, but from the front end when the user deletes the numeric value and tries to send a blank value, it's not posting to the database. I suspect because this value is sent back as an empty string "" which does not translate to the null allowable data type.
Is there a trigger I can create to convert these empty strings into null on insert and update to the database? Or, perhaps a trigger would already happen too late in the process and I need to handle this on the front end or API portion instead?
We'll call my table t_myTable and the column myNumericColumn.
I could also be wrong and perhaps this 'empty string' issue is not the source of my problem. But I suspect that it is.
As #DaleBurrell noted, the proper place to handle data validation is in the application layer. You can wrap each of the potentially problematic values in a NULLIF function, which will convert the value to a NULL if an empty string is passed to it.
The syntax would be along these lines:
SELECT
...
,NULLIF(ColumnName, '') AS ColumnName
select nullif(Column1, '') from tablename
SQL Server doesn't allow to convert an empty string to the numeric data type. Hence the trigger is useless in this case, even INSTEAD OF one: SQL Server will check the conversion before inserting.
SELECT CAST('' AS numeric(18,2)) -- Error converting data type varchar to numeric
CREATE TABLE tab1 (col1 numeric(18,2) NULL);
INSERT INTO tab1 (col1) VALUES(''); -- Error converting data type varchar to numeric
As you didn't mention this error, the client should pass something other than ''. The problem can be found with SQL Profiler: you need to run it and see what exact SQL statement is executing to insert data into the table.

Set a field to the value of another field [duplicate]

Is it possible to copy data from column A to column B for all records in a table in SQL?
How about this
UPDATE table SET columnB = columnA;
This will update every row.
UPDATE table_name SET
destination_column_name=orig_column_name
WHERE condition_if_necessary
This will update all the rows in that columns if safe mode is not enabled.
UPDATE table SET columnB = columnA;
If safe mode is enabled then you will need to use a where clause.
I use primary key as greater than 0 basically all will be updated
UPDATE table SET columnB = columnA where table.column>0;
If you want to copy a column to another column with a different data type in PostgresSQL, you must cast/convert to the data type first, otherwise it will return
Query 1 ERROR: ERROR: column "test_date" is of type timestamp without
time zone but expression is of type character varying LINE 1: update
table_name set test_date = date_string_col
^ HINT: You will need to rewrite or cast the expression.
An example of converting varchar to timestamp:
update table_name set timestamp_col = date_string_col::TIMESTAMP;
An example of converting varchar to int:
update table_name set int_column = string_col::INTEGER;
but any column type(except file or the similar) can be copied to string(character varying) without cast the type.

SQL : The name false is not permitted in this context

On executing the following SQL query
alter table tablename add columnname boolean not null default false;
I got the following error message:
The name "false" is not permitted in this context. Valid expressions are constants, constant expressions, and (in some contexts) variables. Column names are not permitted.
How should I fix this? Suggestions?
The column type should be a bit field.
In SQL you use 0 and 1 to set a bit field. The values are displayed in SQL Server Management Studio as false or true, corresponding to 0 and 1.
alter table tablename add columnname bit not null default 0;
There is no boolean data type. Use the bit data type.
The false value for a bit is 0.
alter table tablename add columnname bit not null default 0