Tell me more ×
Geographic Information Systems Stack Exchange is a question and answer site for cartographers, geographers and GIS professionals. It's 100% free, no registration required.

I am new to SQL and am having some difficulty manipulating date/time fields using sql. I have two columns: One is date/time formatted (2010-02-16 06:56:00.000) and the other is a text ID. I would like to make a new primary key field (text field) that is a combination of the ID & the date. Ideally I would like this in the following format: ID_dd/mm/yyyy hh:mm:ss (24hr).

I don't seem to see an style option for this time of date-time conversion. Does anyone know of a way to get this data into that format? Not sure if it's possible.

share|improve this question
I could offer you ideas for a PHP solution, if that is acceptable. – L_Holcombe Feb 4 at 19:39
Not really the best question for this site, belongs on stackoverflow.com – Nathan W Feb 4 at 23:21

closed as off topic by Nathan W, Mike Toews, R.K., Devdatta Tengshe, blah238 Feb 5 at 3:52

Questions on Geographic Information Systems Stack Exchange are expected to relate to geographic information systems within the scope defined in the FAQ. Consider editing the question or leaving comments for improvement if you believe the question can be reworded to fit within the scope. Read more about closed questions here.

2 Answers

use string concatenation like if you have date and id columns:

SELECT id||CAST(date AS text) from your_table;
share|improve this answer
the || does not apply in Sql Server – Kelso Feb 4 at 23:29
is valid SQL according to ANSI Standards ... except this is Microsoft – Mike Toews Feb 4 at 23:47

In Sql Server use

select 
CONVERT(varchar(6), Id) + '_' + 
CONVERT(varchar(10), your_datetime,103) + ' ' + 
CONVERT(varchar(10), your_datetime, 108)
from your_table

As an aside, creating a primary key based on this field calculated field seems a little odd, especially since you already have a (presumably) unique Id integer field, which for most cases, makes a good primary key. It's certainly not odd to create a normal (not primary) index on this calculated column for querying purposes.

share|improve this answer
Thank you for your help. This seems like it will do the trick just fine! Yes, the primary key would seem strange, but I will have many unique ID's collected on the same dates, so this seems to be a good solution for matching data in different GIS datasets. – user10723 Feb 6 at 17:46

Not the answer you're looking for? Browse other questions tagged or ask your own question.