SQL Format() 函数不起作用?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6469683/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Format() function doesn't work?
提问by
I am trying to execute following built-in function in sql but it gives me error that this function doesn't exist
我试图在 sql 中执行以下内置函数,但它给了我这个函数不存在的错误
my query:
我的查询:
select EmpId, EmpName, format(EmpJoinDate, "YYYY-DD-MM") as date from Employee
Error i am getting:
我得到的错误:
'format' is not a recognized built-in function name
What may be the problem, or what am i doing wrong?
可能是什么问题,或者我做错了什么?
Thanks!
谢谢!
采纳答案by Kirill Polishchuk
回答by Tom H
That's because FORMAT()
is not a built-in function in SQL 2005. You need to use the CONVERT()
function:
那是因为FORMAT()
它不是 SQL 2005 中的内置函数。您需要使用该CONVERT()
函数:
SELECT
EmpId,
EmpName,
REPLACE(CONVERT(VARCHAR(10), EmpJoinDate, 102), '.', '-') AS date
FROM
Employee
A few caveats though... "date" is a reserved word I believe, so I wouldn't suggest using that, even as a column alias. Also, the above actually gives YYYY-MM-DD. YYYY-DD-MM is pretty rare I believe. If you truly want that you'll need to either concatenate things together yourself with the DATEPART
and CAST
functions or concatenate things using SUBSTRING
with CONVERT
.
但是有一些警告......我相信“日期”是一个保留词,所以我不建议使用它,即使作为列别名也是如此。此外,上面实际上给出了 YYYY-MM-DD。我相信 YYYY-DD-MM 非常罕见。如果你真的想要,你需要自己用DATEPART
and将事物连接在一起,CAST
或者使用SUBSTRING
with将事物连接在一起CONVERT
。
Do a search on CONVERT
and you should be able to find all of the various formats supported. The one that I used above (102) is for YYYY.MM.DD, so I did a replace to give the hyphens instead.
进行搜索CONVERT
,您应该能够找到所有支持的各种格式。我上面使用的那个 (102) 是用于 YYYY.MM.DD,所以我做了一个替换来代替连字符。
回答by RW5207
According to MSDN documentation, http://msdn.microsoft.com/en-us/library/hh213505(SQL.110).aspx, it is a built-in function. I am assuming it has not been implemented.
根据 MSDN 文档http://msdn.microsoft.com/en-us/library/hh213505(SQL.110).aspx,它是一个内置函数。我假设它尚未实施。
回答by T_D
The other answers will work but use some hacky string replace and concats. Although you could set date_style
to 23 to convert straight to "YYYY-DD-MM" format:
其他答案将起作用,但使用一些 hacky 字符串替换和连接。虽然您可以设置date_style
为 23 以直接转换为“YYYY-DD-MM”格式:
convert(varchar(10), EmpJoinDate, 23)
For a complete list of formats I'd like to refer to this awesome SO-answer: https://stackoverflow.com/a/19537658/2140636
有关格式的完整列表,我想参考这个很棒的 SO-answer:https: //stackoverflow.com/a/19537658/2140636