From query analyzer how can I change the field datatype from money to varchar?
Alter table tablenaame alter column columnname varchar(30)--Is not working.Can you describe "not working" in a bit more detail? Does the command appear to run, but the column datatype doesn't change? Does it give an error message? Does your server crash and spit blue smoke?
-PatP|||You cannot change the datatype to money from (n)varchar, because this conversion cannot be done implicitly. You'll have to create a new table with desired datatype (money), use CONVERT/CAST function to insert the data into it, then drop the original table, create a new table with the same name, and insert the data back in.
Showing posts with label alter. Show all posts
Showing posts with label alter. Show all posts
Monday, February 20, 2012
Money to Varchar
Money to Varchar
How can I alter a field datatype from money to varchar?To change the column type you will have to create a new table and copy the data over using the convert function, example below.
--create table x
--(a int null,
--b money null)
CREATE TABLE dbo.Tmp_x
(
a int NULL,
b nvarchar(50) NULL
) ON [PRIMARY]
GO
IF EXISTS(SELECT * FROM dbo.x)
EXEC('INSERT INTO dbo.Tmp_x (a, b)
SELECT a, CONVERT(nvarchar(50), b) FROM dbo.x')
GO
DROP TABLE dbo.x
GO
EXECUTE sp_rename N'dbo.Tmp_x', N'x', 'OBJECT'
GO|||You can also add a temporary column to your table of the varchar type and fill it with the data from the money column to see if all values can be converted. If so, empty the money column, change the datatype of the money column to varchar and fill it with the data of the temporary column. Finally delete the temporary column.
To add a column:
alter table owner.your_table
add temp_column varchar(10)
To modify a column datatype:
alter table owner.your_table
alter column your_column varchar(10)
To drop a column:
alter table owner.your_table
drop column temp_column
--create table x
--(a int null,
--b money null)
CREATE TABLE dbo.Tmp_x
(
a int NULL,
b nvarchar(50) NULL
) ON [PRIMARY]
GO
IF EXISTS(SELECT * FROM dbo.x)
EXEC('INSERT INTO dbo.Tmp_x (a, b)
SELECT a, CONVERT(nvarchar(50), b) FROM dbo.x')
GO
DROP TABLE dbo.x
GO
EXECUTE sp_rename N'dbo.Tmp_x', N'x', 'OBJECT'
GO|||You can also add a temporary column to your table of the varchar type and fill it with the data from the money column to see if all values can be converted. If so, empty the money column, change the datatype of the money column to varchar and fill it with the data of the temporary column. Finally delete the temporary column.
To add a column:
alter table owner.your_table
add temp_column varchar(10)
To modify a column datatype:
alter table owner.your_table
alter column your_column varchar(10)
To drop a column:
alter table owner.your_table
drop column temp_column
Subscribe to:
Posts (Atom)