我在mysql中定义了以下函数,并尝试将其转换为MSSQL。 MSSQL(2012)的等价物是什么?
DELIMETER $$
CREATE FUNCTION get_random_state() RETURNS VARCHAR(500) DETERMINISTIC
BEGIN
set @state := ELT(1 + FLOOR(RAND() * 6),'AZ','RI','VA','PA','LA','CA');
RETURN @state;
END $$
DELIMETER ;
答案 0 :(得分:3)
它有一个小问题....在SQL Server中你不能使用RAND(),NEWID()它会抛出一个错误抱怨有一些幻灯片效果功能bla bla ..
但是有一种方法可以创建一个调用RAND()函数的View,然后在Function定义中使用该视图。
CREATE VIEW vw_Rand_Value
AS
SELECT RAND() Rnd_Value
GO
CREATE FUNCTION get_random_state()
RETURNS VARCHAR(2)
BEGIN
DECLARE @Table TABLE(States VARCHAR(2), OrderID FLOAT)
INSERT INTO @Table (States,OrderID)
VALUES ('AZ', (SELECT * FROM vw_Rand_Value))
,('RI', (SELECT * FROM vw_Rand_Value))
,('VA', (SELECT * FROM vw_Rand_Value))
,('PA', (SELECT * FROM vw_Rand_Value))
,('LA', (SELECT * FROM vw_Rand_Value))
,('CA', (SELECT * FROM vw_Rand_Value))
DECLARE @Random_State VARCHAR(2);
SELECT TOP 1 @Random_State = States
FROM @Table
ORDER BY OrderID;
RETURN @Random_State;
END
CREATE FUNCTION get_random_state()
RETURNS VARCHAR(2)
BEGIN
DECLARE @rand int;
DECLARE @Random_State VARCHAR(2);
SELECT @rand = 1 + FLOOR(Rnd_Value * 6) FROM vw_Rand_Value
SET @Random_State = CHOOSE(@rand,'AZ','RI','VA','PA','LA','CA');
RETURN @Random_State;
END
SELECT dbo.get_random_state()