Is it possible to alter a SQL Server table column datatype from bigint to varchar after it has been populated? - sql-server

I have a SQL Server 2008 table which contains an external user reference currently stored as a bigint - the userid from the external table. I want to extend this to allow email address, open ID etc to be used as the external identifier. Is it possible to alter the column datatype from bigint to varchar without affecting any of the existing data?

Yes, that should be possible, no problem - as long as you make your VARCHAR field big enough to hold you BIGINT values :-)
You'd have to use something like this T-SQL:
ALTER TABLE dbo.YourTable
ALTER COLUMN YourColumnName VARCHAR(50) -- or whatever you want
and that should be it! Since all BIGINT values can be converted into a string, that command should work just fine and without any danger of losing data.

Related

At a Format Constraint to A Create Table Statement

I am creating a table in SQL Server for one of my customers that is needing an Access DB converted to SQL Server. ON the tables Access has masked a column a certain way. They have a number lets say TP001111 and when I pull the value into SQL Server I get 1111. I have a table called VendorNumber and I need to format this number.
CREATE TABLE VendorNumber
(
V_ID NVARCHAR(8) NOT NULL PRIMARY KEY,
V_Name NVARCHAR(30) NOT NULL
)
I have tried researching how to do this and I can't find a good example. What is the best way to have this value formatted when it is inserted into the table. I need to have it inserted as TP001111. The current code I have to format the column is:
UPDATE VendorNumber
SET V_ID = 'TP' + RIGHT((REPLICATE('0',6) + TPPRM_ID),6)

Add a column in MS SQL Server table

I wanted to add a column in MS SQL Server. Will it affect any existing stored procedures or triggers or dbms jobs etc? AFAIK, in Oracle once you add a new column to an existing table, you need to recompile any invalid objects. How bout in MS SQL Server?
Adding a column to an existing table, in theory and best practices world is easy, but in reality it is not always as easy as ALTER TABLE ADD COLUMN.
The risk is that any procedure, view or application code that uses a “Select *” or an “Insert Values <…>” (without column names explicitly stated) may not function, or may not function correctly, with an additional column added to the table.
Also note there could be temp tables, table variables and table value parameters built off the table that an additional column affects as well. Best practices and my database development guidelines says not to use the “Select *” or the “Insert Values <…>”.
For example, if you have a table with ID, Name, and Status columns in your table
DECLARE #Table TABLE (id INT, name VARCHAR(20), Status INT)
INSERT INTO #Table VALUES (1,'Name')
It will throw error Column name or number of supplied values does not match table definition. Because in this query, inserting only first two column values and Status is missing. If you add Status column value will not throw any error.
So you need to always mention column names in your INSERT query wherever used
DECLARE #Table TABLE (id INT, name VARCHAR(20), Status INT)
INSERT INTO #Table (id, name) VALUES (1,'Name')
If you didn't specify the column names in INSERT query and add new column to the table will affect that query. Please make sure whether you specified the column names.

Alter Column: option to specify conversion function?

I have a column of type float that contains phone numbers - I'm aware that this is bad, so I want to convert the column from float to nvarchar(max), converting the data appropriately so as not to lose data.
The conversion can apparently be handled correctly using the STR function (suggested here), but I'm not sure how to go about changing the column type and performing the conversion without creating a temporary column. I don't want to use a temporary column because we are doing this automatically a bunch of times in future and don't want to encounter performance impact from page splits (suggested here)
In Postgres you can add a "USING" option to your ALTER COLUMN statement that specifies how to convert the existing data. I can't find anything like this for TSQL. Is there a way I can do this in place?
Postgres example:
...ALTER COLUMN <column> TYPE <type> USING <func>(<column>);
Rather than use a temporary column in your table, use a (temporary) column in a temporary table. In short:
Create temp table with PK of your table + column you want to change (in the correct data type, of course)
select data into temp table using your conversion method
Change data type in actual table
Update actual table from temp table values
If the table is large, I'd suggest doing this in batches. Of course, if the table isn't large, worrying about page splits is premature optimization since doing a complete rebuild of the table and its indexes after the conversion would be cheap. Another question is: why nvarchar(max)? The data is phone numbers. Last time I checked, phone numbers were fairly short (certainly less than the 2 Gb that nvarchar(max) can hold) and non-unicode. Do some domain modeling to figure out the appropriate data size and you'll thank me later. Lastly, why would you do this "automatically a bunch of times in future"? Why not have the correct data type and insert the right values?
In sqlSever:
CREATE TABLE dbo.Employee
(
EmployeeID INT IDENTITY (1,1) NOT NULL
,FirstName VARCHAR(50) NULL
,MiddleName VARCHAR(50) NULL
,LastName VARCHAR(50) NULL
,DateHired datetime NOT NULL
)
-- Change the datatype to support 100 characters and make NOT NULL
ALTER TABLE dbo.Employee
ALTER COLUMN FirstName VARCHAR(100) NOT NULL
-- Change datatype and allow NULLs for DateHired
ALTER TABLE dbo.Employee
ALTER COLUMN DateHired SMALLDATETIME NULL
-- Set SPARSE columns for Middle Name (sql server 2008 only)
ALTER TABLE dbo.Employee
ALTER COLUMN MiddleName VARCHAR(100) SPARSE NULL
http://sqlserverplanet.com/ddl/alter-table-alter-column

Convert char columns to nvarchar, in order to change the codepage (language encoding) for data already in the table?

I have a table that was imported from another source as a column with the char datatype, but the field has international characters. I would like to use nvarcvhar in my table. How can I achieve this?
I already tried updating the columns (using an alter table statement, or "cast as") but the info stored did not get converted.
Thanks
like this
ALTER TABLE TableName ALTER COLUMN ColumnName NVARCHAR(size)
example
CREATE TABLE test (bla VARCHAR(50))
GO
ALTER TABLE test ALTER COLUMN bla NVARCHAR(50)
Make sure that you prefix the string with N when doing the insert
INSERT test VALUES (N'漢語')
SELECT * FROM test
output
bla
--------------------------------------------------
漢語
(1 row(s) affected)
Whatever you do, don't use the SSMS designer/wizard, it will recreate the whole table, see here for example When changing column data types use ALTER TABLE TableName ALTER Column syntax, don't drop and recreate column
alter table your_table alter column your_column nvarchar(length)
SQLFiddle example
Your data is currently in EUC-CN, masquerading as CP1252. It is not lost.
You have several approaches available for conversion to Unicode (look at Converting SQL databases section for overview). In case of SQL Server, you can create extended stored procedures for conversion from EUC-CN to Unicode. This will work but it is not exactly easy (in this case use code page 51936 for your data).
With some luck, depending on what particular characters occur in your data, and what language packs you have installed, you might be able to convert as if from code page 936 like this:
ALTER DATABASE mydatabasename COLLATE Chinese_PRC
If this succeeds, do the same for every column you are going to convert:
ALTER TABLE mytablename ALTER COLUMN mycolumnname
varchar(4000) COLLATE Chinese_PRC NOT NULL
And only then convert them to NVARCHAR.

Correct SQL to convert mySQL tables to SQL Server tables

I have a number of tables I need to convert from mySQL to SQL Server.
An Example of a mySQL Table is
CREATE TABLE `required_items` (
`id` INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY COMMENT 'Unique Barcode ID',
`fk_load_id` INT( 11 ) NOT NULL COMMENT 'Load ID',
`barcode` VARCHAR( 255 ) NOT NULL COMMENT 'Barcode Value',
`description` VARCHAR( 255 ) NULL DEFAULT NULL COMMENT 'Barcode Description',
`created` TIMESTAMP NULL DEFAULT NULL COMMENT 'Creation Timestamp',
`modified` TIMESTAMP ON UPDATE CURRENT_TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'Modified Timestamp',
FOREIGN KEY (`fk_load_id`) REFERENCES `loads`(`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE = InnoDB CHARACTER SET ascii COLLATE ascii_general_ci COMMENT = 'Contains Required Items for the Load';
And a trigger to update the created date
CREATE TRIGGER required_items_before_insert_created_date BEFORE INSERT ON `required_items`
FOR EACH ROW
BEGIN
SET NEW.created = CURRENT_TIMESTAMP;
END
Now I need to create tables similar to this in SQL Server. There seems to be a lot of different data types available so I am unsure which to use.
What data type should I use to the primary key column
(uniqueidentifier, bigint, int)?
What should I use for the timestamps
(timestamp, datatime, datetime2(7))?
How should I enforce the created
and modified timestamps (currently I am using triggers)?
How can I enforce foreign key constraints.
Should I be using Varchar(255) in SQL Server? (Maybe Text, Varchar(MAX) is better)
I am using Visual Studio 2010 to create the tables.
First of all, you can probably use PHPMyAdmin (or something similar) to script out the table creation process to SQL Server. You can take a look at what is automatically created for you to get an idea of what you should be using. After that, you should take a look at SSMS (SQL Server Management Studio) over Visual Studio 2010. Tweaking the tables that your script will create will be easier in SSMS - in fact, most database development tasks will be easier in SSMS.
What data type should I use to the primary key column (uniqueidentifier, bigint, int)?
Depending on how many records you plan to have in your table, use int, or bigint. There are problems with uniqueidentfiers that you will probably want to avoid. INT vs Unique-Identifier for ID field in database
What should I use for the timestamps (timestamp, datatime, datetime2(7))?
timestamps are different in SQL Server than in MySQL. Despite the name, a timestamp is an incrementing number that is used as a mechanism to version rows. http://msdn.microsoft.com/en-us/library/ms182776%28v=sql.90%29.aspx . In short though, datetime is probably your best bet for compatibility purposes.
How should I enforce the created and modified timestamps (currently I am using triggers)?
See above. Also, the SQL Server version of a "Timestamp" is automatically updated by the DBMS. If you need a timestamp similar to your MySQL version, you can use a trigger to do that (but that is generally frowned upon...kind of dogmatic really).
How can I enforce foreign key constraints.
You should treat them as you would using innoDB. See this article for examples of creating foreign key constraints http://blog.sqlauthority.com/2008/09/08/sql-server-%E2%80%93-2008-creating-primary-key-foreign-key-and-default-constraint/
Should I be using Varchar(255) in SQL Server? (Maybe Text, Varchar(MAX) is better)
That depends on the data you plan to store in the field. Varchar max is equivalent to varchar(8000) and if you don't need varchar(255), you can always set it to a lower value like varchar(50). Using a field size that is too large has performance implications. One thing to note is that if you plan to support unicode (multilingual) data in your field, use nvarchar or nchar.

Resources