无法在SQL中显示表格

时间:2014-09-08 21:15:32

标签: sql sql-server tsql

我创建了一个表,其中一个列名是用户定义的函数。我已成功将数据插入表中,但我无法选择并查看整个表格。

CREATE TABLE Member_Profile(
Gender          CHAR(1),
Name            VARCHAR(50),
D_O_B           DATE,
Weight          DECIMAL(10,2),
Height          DECIMAL(10,2),
Smoker          CHAR(1),
Salary          INT,
MemberID        INT,
Cupid_Score AS  [dbo].[Q3CupidUDF](Gender,Name,D_O_B,Weight,Height,Smoker,Salary),
PRIMARY KEY(MemberID)
)

INSERT INTO Member_Profile VALUES('M', 'Tim', '01-01-82', 97.0, 1.88, 'N', 65000, 1)
SELECT * FROM Member_Profile

这是表格的UDF ----

CREATE FUNCTION [dbo].[Q3CupidUDF]
(
@Gender         CHAR(1),
@Name           VARCHAR(15),
@DOB            DATE,
@Weight         DECIMAL(10,2),
@Height         DECIMAL(10,2),
@Smoker         CHAR(1),
@Salary         INT
)
RETURNS INT
AS
BEGIN
DECLARE @CupidScore INT
DECLARE @Age INT
SELECT @Age = DATEDIFF(YEAR, @DOB, GETDATE())

SELECT @CupidScore = CASE   
    WHEN @Age between 20 and 30 THEN 5
    WHEN @Age between 31 and 40 THEN 4
    WHEN @Age between 41 and 50 THEN 3
    WHEN @Age > 50 THEN 2
    ELSE 0
END

DECLARE @WtHt DECIMAL(2,1)
SET @WtHt = @Weight/(@Height*@Height)

SET @CupidScore = @CupidScore + CASE
    WHEN @WtHt between 20 and 25 THEN 1
    WHEN @WtHt between 25 and 30 THEN 3                     
    WHEN @WtHt between 30 and 35 THEN 4
    WHEN @WtHt between 35 and 40 THEN 2
    ELSE 0
END

IF @Smoker = 'Y' SET @CupidScore = @CupidScore + 2

SET @CupidScore = @CupidScore + CASE
    WHEN @Salary < 50000 THEN 1
    WHEN @Salary between 50001 and 60000 THEN 2
    WHEN @Salary between 60001 and 70000 THEN 3
    WHEN @Salary > 70000 THEN 4
END

RETURN @CupidScore
END

2 个答案:

答案 0 :(得分:1)

您的问题是由于UDF内部的数据截断造成的。问题是你正在进行的计算返回一个十进制值,其中的位数比你在变量中声明的要多得多。

DECLARE @WtHt DECIMAL(2,1)

应声明为:

DECLARE @WtHt decimal(10,7)

这是因为以下计算返回如下值:27.444545043006

SET @WtHt = @Weight/(@Height*@Height)

以下是一个工作示例:http://sqlfiddle.com/#!3/a874f/1/0

答案 1 :(得分:0)

我还没有在我面前安装SQL服务器,但您是否尝试将@wtht更改为十进制(10,2)?