Solved

SQL - Cast fields to data types

Posted on 2012-03-26
6
326 Views
Last Modified: 2012-03-26
Hello Experts,

I need to convert fields in a query to particular datatypes.  But there's a lemon twist here ... the data types are part of the actual data.  That's confusing, so let me show you an example of the query results.

Data_Field      |      Data_Type
-------------------------------------------------------------
City                          varchar(25)
State                        varhcar(2)
Zip                           numeric
Date                        datetime

One field has the data, the other field has the expected data type.
So in my query, I need to do something like this.

SELECT CAST(Data_Field as Data_Type) as 'Data_Field'

But SQL doesn't like this.  Can anyone help me with syntax to make this work?

Many thanks,
Moe
0
Comment
Question by:mauricerichard
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 2
6 Comments
 
LVL 18

Expert Comment

by:Cluskitt
ID: 37766776
SELECT CAST([Date] as datetime) AS 'Date'
You should always avoid naming your fields/tables the same as SQL functions/special words, though
0
 
LVL 18

Expert Comment

by:Cluskitt
ID: 37766796
You can also use MyTableName.MyFieldName nomenclature to avoid these situations. However, this won't avoid other issues. One I've seen recently was some here on EE that had a table with a field named Day. He then had a syntax error trying to perform a DateAdd(day,...,...) because SQL interpreted day as the field and not as the DateAdd argument.
0
 
LVL 18

Accepted Solution

by:
lludden earned 400 total points
ID: 37766854
You need to use dynamic SQL.

DECLARE @Sql VARCHAR(MAX)
DECLARE @T1 TABLE (Data_field VARCHAR(20), Data_Type VARCHAR(20))
INSERT INTO @T1 SELECT 'City','varchar(25)' UNION SELECT 'State','varchar(2)' UNION SELECT 'Zip','Numeric' UNION SELECT 'Date','datetime'
SELECT @SQL =
  COALESCE(
    @SQL + ',Cast([' + t1.Data_Field + '] AS ' + t1.Data_type + ') AS [' + t1.Data_Field + ']',
    'SELECT Cast([' + t1.Data_Field + '] AS ' + t1.Data_type + ') AS [' + t1.Data_Field + ']'
  )
FROM @T1 T1
SET @Sql = @Sql + ' FROM MyTable'

EXECUTE (@Sql)
--Print @SQL
0
Ransomware: The New Cyber Threat & How to Stop It

This infographic explains ransomware, type of malware that blocks access to your files or your systems and holds them hostage until a ransom is paid. It also examines the different types of ransomware and explains what you can do to thwart this sinister online threat.  

 
LVL 1

Author Comment

by:mauricerichard
ID: 37767041
Hi Cluskitt,

Sorry, this is very hard to explain.  Point taken with the naming conventions, but lets not worry about that for now.  Let me try to re-explain this.

The table has 2 fields: 1) Data_Field  2) Data_Type

Imagine you just created a table called Addresses with two fields, Data_Field & Data_Type

Now imagine you ran this statement for this table:
INSERT INTO Addresses(Data_Field, Data_Type) VALUES('City', 'varchar(25)')
INSERT INTO Addresses(Data_Field, Data_Type) VALUES('State', 'varchar(2)')
INSERT INTO Addresses(Data_Field, Data_Type) VALUES('Zipcode', 'numeric')
INSERT INTO Addresses(Data_Field, Data_Type) VALUES('Date', 'datetime')

You'd now have data that looked like I explained in my question.  But it's just data, the data_Type field isn't a SQL datatype ... it's a string of data.

So what I'd like do to is convert the Data_field to whatever Data_Type we entered for it.  So in the example above, when 'City' loads, I want it to be converted to varchar(25) ... when 'Date' loads up I want to convert it to datetime.

So my first thought was: SELECT CAST(Data_Field as Data_Type) as 'Data_Field'
But I get the message: Type c.Data_Type is not a defined system type.
0
 
LVL 18

Assisted Solution

by:Cluskitt
Cluskitt earned 100 total points
ID: 37767093
I understand now. You have to use dynamic SQL as lludden posted, or some similar variations (like using Quotename functions). The way I handled a similar situation was to create a stored procedure that had @Field and @Type as arguments. You then create your query much like the example posted above (if you use Quotename, it surrounds the string with [])
0
 
LVL 1

Author Closing Comment

by:mauricerichard
ID: 37767392
Great, thanks for all the help!
0

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Nowadays, some of developer are too much worried about data. Who is using data, who is updating it etc. etc. Because, data is more costlier in term of money and information. So security of data is focusing concern in days. Lets' understand the Au…
Everyone has problem when going to load data into Data warehouse (EDW). They all need to confirm that data quality is good but they don't no how to proceed. Microsoft has provided new task within SSIS 2008 called "Data Profiler Task". It solve th…
This video shows, step by step, how to configure Oracle Heterogeneous Services via the Generic Gateway Agent in order to make a connection from an Oracle session and access a remote SQL Server database table.
Via a live example combined with referencing Books Online, show some of the information that can be extracted from the Catalog Views in SQL Server.

740 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question