Adding a Computed column with After clause - sql

I am trying to create a computed column after a specified column.
But the SQL gives syntax error for the query below. Please help me with the correct syntax/way to do this.
ALTER TABLE service_ServiceClass
ADD LichenClassName AS ([dbo].[UfnGetServiceClassName]([Id])) AFTER Description

You get an error because "AFTER" is MySQL syntax.
There is no direct way to alter column order in SQL Server currently.
In MS SQL Server Management Studio, you'd have to use the SSMS Table Designer (rightclick yourTable->Design) to arrange your columns, which can then generate a script which drops and recreates the table.

There is no after clause in sql server's alter table statement.
The order of the columns in the table (as well is the order of the rows, btw) is completely insignificant from a user's point of view.
It's significant from the server point of view, as it may effect performance when using clustered indexes.
The only time the order of the columns matters is when you are using select * ..., but you shouldn't use that anyway. Always specify the column names directly.

Related

Rename columns in MS Access using SQL

In MS Access, I have a few tables with some column names having spaces in their column names (e.g. Transaction I).
I need to replace the spaces with underscores (e.g. Transaction_ID) using SQL.
Although I'm somewhat familiar with SQL, however, my exposure was in an Oracle environment and all of those queries and functions don't work in MS Access. I am fairly new to MS Access.
I have tried following codes from the posts that I searched, however, to no avail.
alter table EP sp_rename 'Transaction ID' to Transaction_ID
alter table EP rename column 'Transaction ID' to Transaction_ID
Access does not have a built in command "line" option to re-name a column.
(and your example looks to be for SQL Server, and MORE so it looks to be using a library stored procedure function to do this for you. So, that looks to be SQL Server syntax - not MS Access.
If you going to use DDL in Access to re-name a column? You have to create a new column with the desired name, and then move the data to this new column, and then drop the old column.
The so called sql 'ddl' commands in Access actually do quite much follow the SQL standard.
So, before embarking on this road, I would consider to use the built in GUI + table designer. (It will do the dirty work behind the scenes for you).
So, can you use DDL to rename a column? Yes, but you have to do this in 3 steps.
Create the new column.
Copy data from old column to new column
Delete the old column.
Because of indexing, possible relationships and other issues, then one REALLY does want to use the built in table designer + the GUI here.
But, you can use say a procedure (VBA) in Access to do this:
Say we had a REALLY bad column name for City called [The City].
To re-name to City, then we can go:
Sub MyAlter()
' create the new column
CurrentDb.Execute "ALTER TABLE tblHotels ADD COLUMN City TEXT(50)", dbFailOnError
' copy the data
CurrentDb.Execute "UPDATE tblHotels SET City = [The City]", dbFailOnError
' drop the origonal column
CurrentDb.Execute "ALTER TABLE tblHotels DROP COLUMN [The City]", dbFailOnError
End Sub
Just keep in mind that ANY column in Access with spaces (yuk!!) needs to be surrounded with []. This applies to SQL select queries, update queries, insert queries, and of course DDL commands to modify the table structure.
If a one-time deal, then of course simply use access, open the table(s) in question in design mode, and make the changes.
However, if you do for some reason do need to use a procedure, then the above code in a access code module can be used.
Or you could just fire up the query builder, flip to SQL view mode, and type in the above raw sql that way.
(you have to type in each sql command separately - the Access query builder only allows ONE SQL statement at a time.
So you could type in first above SQL, hit "!" to execute, and then do the two additional SQL statements.
MAKE A BACK-UP!!!
And of course any code, any queries, any reports etc. that used the old column name will break. So changing column names in an existing application is a HIGH RISK adventure (you can and will break tons of code, existing forms, and existing reports, and existing SQL queries you have now).
However, if this is a one-time update? Then I would of course just use the table designer. It allows a re-name without a column drop – and it keeps other field settings such as indexes, format etc.
I which above suggested approach makes the most sense will depend on your particular "use" case.
Last but not least? You can use VBA code and the table objects in that code. This approach is probably the best. It does not use SQL DDL, and you have greater control over a lot of features for a given column (required, allow nulls – the list goes on). Most of these settings CAN be set in DDL - but you spend quite a bit of time searching and looking up those settings.
All in all? I would use the table designer if possible here.

Using SSMA to convert from Access to SQL, scripting the fixes

I am using SSMA to convert from an Access db to a SQL 2019 DB.
There are some things I need to fix in the access DB so I am trying to figure out whether or not these things can be done via a query in access or you have to use the goofy UI and do everything manually.
So I had a couple of questions about queries in Microsoft Access:
Can you modify the 'required' attribute on a column within a table by using a query?
Can you configure Index (dupes) on a column by using a query?
Can you change validation rules using a query?
Can you create/delete relationships using a query?
Can you change the field length of a column by using a query?
Any examples of any of these would be helpful, when I google for ms access related things all of the content is either related to Access 2007/2010 or its very UI heavy rather than Query heavy.
I am trying to script this because I may have to do this migration several times.
Update: I was able to get most of what i needed figured out..
ALTER TABLE Users ALTER COLUMN Type CHECK(In ("I","U","") Or Is Null);
Still havent found a way to change the 'ValidationRule'.. trying to change it to
In ("I","U","") Or Is Null
Look into the Data Definition Language section of the MS Access SQL Reference, specifically the ALTER TABLE statement, which will cover the majority of your questions.
For example, in response to:
Can you change the field length of a column by using a query?
ALTER TABLE Table1 ALTER COLUMN Field1 TEXT(100)
The above will change the data type of the field Field1 within table Table1 to a text field accommodating 100 characters.

string or binary data truncated after server reboot

After rebooting SQL Server 2005 Standard 9.0.3233, we have been experiencing the above error in some of our stored procedures which try to insert into a table variable from a specific column of a table. The base table has the column defined as varchar(10), but the table variable has the column being inserted into defined only as varchar(3). However, the SELECT statement only returns data with 3 or less characters.
We have not changed the data or the code base in any other way, and this is only happening on our production server. If I run the same query on a test server with the same SQL Server 2005 edition installed, but an older backup, the error does not occur. The same data is returned in both queries if the INSERT is removed, or the table variable column is extended to match the base table.
What I have noticed is that the execution plan is different when the same query is run on the two servers. On the server where the query works, there is a computed scalar operation which takes the column and does an implicit conversion to varchar(3), before it is then outputted to the nested loop join operation.
On the server that returns an error, there is a hash join and table scan of the base table instead. I have already tried to rebuild indices and update statistics on all tables involved, including using fullscan, and with the same stat_stream as in the server that works, but I can't get the same plan back.
For now we have fixed the few stored procedures which were broken by modifying the size of the table variable column, but I would like to know if there is a way to get the statistics and indices back so that they produce the same plans as before, in case there is more code out there which just hasn't executed yet.
This is known behavior and probably has nothing to do with your reboot. Effectively what's happening is that the optimizer is re-ordering the logical elements of your query for performance reason, but this is resulting in the truncation-error check being done before the WHERE clause's filtering.
The recommended solution is to wrap the column expression that gets assigned to your VARCHAR(3) in a CASE.. that duplicates the length test in your WHERE clause. I know that sounds illogical, but it usually fixes the problem.

Changing Column Ordinal_position Positions

My scenario:
I can change the ordinal position of a column in a table.Is there a way to change the ordinal position of a column in a table without recreating the table?
No, you have to recreate the table if you wish to achieve this. (SQL SERVER)
Even when you do this in SSMS, you will see that the script that is generated also recreates the table.
Not in SQL Server - Not sure about other RDBMSs.
You can create a View with the desired ordinal positions but the only time I can think that would be useful is if you are using SELECT * which is a practice that should be avoided anyway.
Hi it depends on the database system you use.
For example in some it is possible to remove and add a column and you can do it in a procedure part where you also can refill it.
But in general it shouldn't matter as you can define the returned data order in your select statement. Is not that enough for you?
Without recreating the Table is Not possible. However, if your concern is about loosing the data here is an option provided by SQl Server Management Studio.
Note: I have used Sql Server 2019 Developer Edition.
Right Click on the Table name and Choose Design Option
Using your Cursor Drag the position of your Column to your desired Position
SQlServer Table Design Options
If you want to do it at script level, You can see the idea below provided by SSMS
Enable the "Auto Generate Change Script" Option available in Tools Menu --> Options --> Designers --> Table and Database Designers.
Enabling the Auto Generate Change Script Option
When you drag the Column in SSMS it will automatically creates the Script for you.
The High level Idea in the auto generated Script is,
Creating a Table with Temp_YourTableName with desired Order of Columns
Copying all the Data from the Original Table to new Temp_YourTableName
Drop the Original Table
Renaming the Temp_YourTableName to Original YourTableName
of course doing everything with Transaction scope to avoid any data loss while the script is executing.
I found a good reason why some time we need to do this here. Interestingly, it is based on Context and not to do anything with Technical.
Say for example, Original Address Table Contains, Street Address 1, City, State, Zip and Country columns. If the requirement Changes to include a new Columns like Street Address 2 this would be meaning full.

How do you port a SqlServer database to MySQL?

I have a SqlServer db that I would like to port to MySQL. What's the best way to to this. Things that need to be ported are:
Tables (and data)
FileStream → MySQL equivalent?
Stored Procedures
Functions
Data types are relatively similar.
There is no equivalent to FileStream in MySQL - the files must either be stored as BLOBs, or on the file system while the path is stored in the database.
Migrating away from TSQL means:
There's no WITH clause in MySQL - it will have to converted into a derived table/inline view
There's no TOP syntax - these have to be converted to use LIMIT
There's no ranking/analytic functionality in MySQL - can't use ROW_NUMBER, RANK, DENSE_RANK or NTILE. See this article for alternatives.
MySQL views have notoriously limited functionality:
The SELECT statement cannot contain a subquery in the FROM clause.
The SELECT statement cannot refer to system or user variables.
Within a stored program, the definition cannot refer to program parameters or local variables.
The SELECT statement cannot refer to prepared statement parameters.
Any table or view referred to in the definition must exist. However, after a view has been created, it is possible to drop a table or view that the definition refers to. In this case, use of the view results in an error. To check a view definition for problems of this kind, use the CHECK TABLE statement.
The definition cannot refer to a TEMPORARY table, and you cannot create a TEMPORARY view.
Any tables named in the view definition must exist at definition time.
You cannot associate a trigger with a view.
As of MySQL 5.0.52, aliases for column names in the SELECT statement are checked against the maximum column length of 64 characters (not the maximum alias length of 256 characters).
Dynamic SQL will have to be converted to use MySQL's Prepared Statement syntax
A guide/article with some useful tips is available on the official MySQL dev site.
This is not for the faint of heart. Here is an article that explains what you are in for:
http://searchenterpriselinux.techtarget.com/news/column/0,294698,sid39_gci1187176,00.html