创建获取状态代码函数

时间:2017-04-28 17:27:09

标签: sql sql-server

我真的很擅长创建功能,而且似乎无法在网上找到类似的内容。我不知道为什么当我这样做时,我会回到空白处?我通过使用Select dbo.UDF_StateCode([State])FROM ...语句来调用它。

CREATE FUNCTION [dbo].[UDF_StateCode] (@State NVARCHAR)
RETURNS NVARCHAR
AS
BEGIN
DECLARE @StateCode NVARCHAR
SET @StateCode =
CASE 
WHEN @State = 'ALASKA' THEN 'AK'
WHEN @State = 'ALABAMA' THEN 'AL'
WHEN @State = 'ARKANSAS' THEN 'AR'
WHEN @State = 'AMERICAN SAMOA' THEN 'AS'
WHEN @State = 'ARIZONA' THEN 'AZ'
WHEN @State = 'CALIFORNIA' THEN 'CA'
WHEN @State = 'COLORADO' THEN 'CO'
WHEN @State = 'CONNECTICUT' THEN 'CT'
WHEN @State = 'DISTRICT OF COLUMBIA' THEN 'DC'
WHEN @State = 'DELAWARE'THEN 'DE' 
WHEN @State = 'FLORIDA' THEN 'FL'
WHEN @State = 'FEDERATED STATES OF MICRONESIA' THEN 'FM'
WHEN @State = 'GEORGIA' THEN 'GA'
WHEN @State = 'GUAM' THEN 'GU'
WHEN @State = 'HAWAII' THEN 'HI' 
WHEN @State = 'IOWA' THEN 'IA'
WHEN @State = 'IDAHO' THEN 'ID'
WHEN @State = 'ILLINOIS' THEN 'IL'
WHEN @State = 'INDIANA' THEN 'IN'
WHEN @State = 'KANSAS' THEN 'KS' 
WHEN @State = 'KENTUCKY' THEN 'KY'
WHEN @State = 'LOUISIANA' THEN 'LA'
WHEN @State = 'MASSACHUSETTS' THEN 'MA'
WHEN @State = 'MARYLAND' THEN 'MD' 
WHEN @State = 'MAINE' THEN 'ME'
WHEN @State = 'MARSHALL ISLANDS' THEN 'MH' 
WHEN @State = 'MICHIGAN' THEN 'MI'
WHEN @State = 'MINNESOTA' THEN 'MN'
WHEN @State = 'MISSOURI' THEN 'MO'
WHEN @State = 'NORTHERN MARIANA ISLANDS' THEN 'MP'
WHEN @State = 'MISSISSIPPI' THEN 'MS'
WHEN @State = 'MONTANA' THEN 'MT'
WHEN @State = 'NORTH CAROLINA' THEN 'NC'
WHEN @State = 'NORTH DAKOTA' THEN 'ND'
WHEN @State = 'NEBRASKA' THEN 'NE'
WHEN @State = 'NEW HAMPSHIRE' THEN 'NH' 
WHEN @State = 'NEW JERSEY' THEN 'NJ' 
WHEN @State = 'NEW MEXICO' THEN 'NM'
WHEN @State = 'NEVADA' THEN 'NV'
WHEN @State = 'NEW YORK' THEN 'NY'
WHEN @State = 'OHIO' THEN 'OH'
WHEN @State = 'OKLAHOMA' THEN 'OK'
WHEN @State = 'OREGON' THEN 'OR'
WHEN @State = 'PENNSYLVANIA' THEN 'PA'
WHEN @State = 'PUERTO RICO'THEN 'PR' 
WHEN @State = 'RHODE ISLAND' THEN 'RI'
WHEN @State = 'SOUTH CAROLINA' THEN 'SC'
WHEN @State = 'SOUTH DAKOTA' THEN 'SD'
WHEN @State = 'TENNESSEE' THEN 'TN'
WHEN @State = 'TEXAS' THEN 'TX'
WHEN @State = 'UTAH' THEN 'UT'
WHEN @State = 'VIRGINIA ' THEN 'VA'
WHEN @State = 'VIRGIN ISLANDS' THEN 'VI' 
WHEN @State = 'VERMONT' THEN 'VT'
WHEN @State = 'WASHINGTON' THEN 'WA'
WHEN @State = 'WISCONSIN' THEN 'WI'
WHEN @State = 'WEST VIRGINIA' THEN 'WV'
WHEN @State = 'WYOMING' THEN 'WY'
ELSE ''
END
RETURN @StateCode
END;

非常感谢任何帮助。谢谢!

1 个答案:

答案 0 :(得分:2)

您必须声明nvarchar()的长度。它的默认值为1。

试试这个:

CREATE FUNCTION [dbo].[UDF_StateCode] (@State NVARCHAR(64)) 
RETURNS NVARCHAR(2)
AS
BEGIN
DECLARE @StateCode NVARCHAR(2) ...

Bad habits to kick : declaring varchar without (length) - Aaron Bertrand - 您应该始终为所有varcharnvarchar变量/参数提供长度。

您可以简化返回nchar(2)而不是可变长度输出。

您还可以通过将此函数编写为内联表值函数而不是标量函数来提高性能。

通常这种东西是表而不是函数,你可以根据需要加入表。但是为了学习如何编写函数,我想这是一个合理的例子。

关于功能表现的一些好文章: