写一个function自动返回类型。
-- ================================================
-- Template generated from Template Explorer using:
-- Create Scalar Function (New Menu).SQL
--
-- Use the Specify Values for Template Parameters 
-- command (Ctrl-Shift-M) to fill in the parameter 
-- values below.
--
-- This block of comments will not be included in
-- the definition of the function.
-- ================================================
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: Alex
-- Create date: 
-- Description:
-- =============================================
CREATE FUNCTION GetType 
(
-- Add the parameters for the function here
@p1 int
)
RETURNS int
AS
BEGIN
-- Declare the return variable here
DECLARE @Result int -- Add the T-SQL statements to compute the return value here
SELECT @Result = ID
FROM T2
Where @p1 between minVol and maxVol -- Return the result of the function
RETURN @ResultEND
GO表结构如下:create table t1
(id int identity(1,1) not null primary key,
Vol int,
type int)
gocreate table t2
(id int identity(1,1) not null primary key,
minvol int,
maxvol int)
goinsert t1 values(5, '')
insert t1 values(10, '')
insert t1 values(14, '')
insert t1 values(17, '')insert t2 values(0, 10)
insert t2 values(11, 15)
insert t2 values(16, 25)--select * from t1
--select * from t2update t1
set type = dbo.GetType(Vol)select * from t1

解决方案 »

  1.   

    update t1
    set type = dbo.GetType(Vol)
    上面用于调用function,并更t1。
    下面是结果。id          Vol         type
    ----------- ----------- -----------
    1           5           1
    2           10          1
    3           14          2
    4           17          3(4 row(s) affected)
      

  2.   

    谢谢jobine,这个其实跟将select语句直接写到update里一样的.
      

  3.   


    drop table t1
    drop table t2
    create table t1
    (id int identity(1,1) not null primary key,
    Vol int,
    type int)
    gocreate table t2
    (id int identity(1,1) not null primary key,
    minvol int,
    maxvol int)
    goinsert t1 values(5, '')
    insert t1 values(10, '')
    insert t1 values(14, '')
    insert t1 values(17, '')insert t2 values(0, 10)
    insert t2 values(11, 15)
    insert t2 values(16, 25)
    select t1.* ,t2.id as type from t1 t1, t2 t2 where t1.Vol between t2.minvol and t2.maxvol
      

  4.   


    /*
    id          Vol         type        type
    ----------- ----------- ----------- -----------
    1           5           0           1
    2           10          0           1
    3           14          0           2
    4           17          0           3(4 row(s) affected)*/