newid() inside sql server function

后端 未结 4 2263
旧巷少年郎
旧巷少年郎 2020-11-27 03:24

I have to insert a fake column at the result of a query, which is the return value of a table-value function. This column data type must be unique-identifier. The best way (

相关标签:
4条回答
  • 2020-11-27 04:12

    use it as a default instead

    create table test(id uniqueidentifier default newsequentialid(),id2 int)
    
    insert test(id2) values(1)
    
    select * from test
    

    NB I used newsequentialid() instead of newid() since newid() will cause pagesplits since it is not sequential, see here: Some Simple Code To Show The Difference Between Newid And Newsequentialid

    0 讨论(0)
  • 2020-11-27 04:13

    here's a clever solution:

    create view getNewID as select newid() as new_id
    
    create function myfunction ()
    returns uniqueidentifier
    as begin
       return (select new_id from getNewID)
    end
    

    that i can't take credit for. i found it here: http://omnibuzz-sql.blogspot.com/2006/07/accessing-non-deterministic-functions.html

    -don

    0 讨论(0)
  • 2020-11-27 04:15

    You can pass NEWID() as a parameter to your function.

    CREATE FUNCTION SOMEIDFUNCTION
    (
        @NEWID1 as varchar(36), @NEWID2 as varchar(36)
    )
    RETURNS varchar(18)
    AS
    BEGIN
        -- Do something --
        DECLARE @SFID varchar(18)
        SELECT @SFID = 'DYN0000000' + LOWER(LEFT(@NEWID1,4)) + LEFT(@NEWID2,4) 
        RETURN @SFID
    END
    GO
    

    Call the function like this;

    SELECT dbo.SOMEIDFUNCTION(NewID(),NewID())
    
    0 讨论(0)
  • 2020-11-27 04:15

    You could use ROW_NUMBER function:

    SELECT
    (ROW_NUMBER() OVER (ORDER BY recordID) ) as RowNumber ,
    recordID,
    fieldBla1
    FROM tableName

    Find more information at http://msdn.microsoft.com/pt-br/library/ms186734.aspx

    0 讨论(0)
提交回复
热议问题