Results 1 to 7 of 7

Thread: Dynamic SQL and Exec returning a value

  1. #1

    Thread Starter
    Hyperactive Member
    Join Date
    Apr 2001
    Location
    N42 29.340 W71 53.215
    Posts
    422

    Question Dynamic SQL and Exec returning a value

    Is it possible to Exec a dsql statement and return a simple value to a local var? e.g

    Set @RecCnt = Exec('Select Count(ID) from tblContacts Where FirstName=''David''')

    This doesn't work, and note, I need to use DSQL here because I'm actually building up that Select statement each time.

    Right now I do this:

    Declare @RecCnt Int
    Create Table #tmp1 ( RecCnt Int )
    Insert into #tmp1 Exec('Select Count(ID) from tblContacts Where FirstName=''David''')
    Select @RecCnt = RecCnt From #tmp1
    Print @RecCnt
    Drop table #tmp1

    But, I'd rather not have to deal with the temp table.

    Thanks, DaveBo
    "The wise man doesn't know all the answers, but he knows where to find them."
    VBForums is one place, but for the really important stuff ... here's a clue 1Tim3:15

  2. #2
    Frenzied Member
    Join Date
    Feb 2003
    Location
    Argentina
    Posts
    1,950

    Re: Dynamic SQL and Exec returning a value

    Not familiar w/T-SQL syntax, but why can't you just SELECT the Count into a recordset that will only have one record? No temp table.
    In DAO (stop booing! It's what I'm stuck with at work!):
    vb Code:
    1. Dim db As DAO.Database
    2. Dim rs As DAO.Recordset
    3. Set db = CurrentDB
    4. Set rs = db.OpenRecordset("SELECT Count(ID) from tblContacts Where FirstName='David'")
    5. MsgBox rs.Fields("ID")
    I think, but not sure, that in VB.Net you also have an option to return a scalar value, which with the same caveat, think only returns one value. Been a few years since I coded in .Net, so can't be sure there.
    Tengo mas preguntas que contestas

  3. #3
    Frenzied Member MaximilianMayrhofer's Avatar
    Join Date
    Aug 2007
    Location
    IM IN YR LOOP
    Posts
    2,001

    Re: Dynamic SQL and Exec returning a value

    You could also do the same thing with ADO using the following:

    vb.net Code:
    1. Public Class YourForm
    2.  
    3.     Dim ds As New DataSet()
    4.     Dim da As New OleDb.OleDbDataAdapter()
    5.     Dim conn As New OleDb.OleDbConnection()
    6.  
    7.     Private Sub Form_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    8.         conn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=YourPath\Yourfilename.mdb; User Id=admin;Password=;"
    9.        
    10.         da.SelectCommand = New OleDb.OleDbCommand("SELECT Count(ID) from tblContacts Where FirstName='David'")
    11.         da.SelectCommand.Connection = conn
    12.         conn.Open()
    13.         da.Fill(ds)
    14.  
    15.         MsgBox(ds.Tables(0).Rows(0).Item("ID").ToString)
    16.  
    17.         conn.close()
    18.  
    19.     End Sub
    20.  
    21. End Class

  4. #4
    PowerPoster
    Join Date
    Oct 2002
    Location
    British Columbia
    Posts
    9,758

    Re: Dynamic SQL and Exec returning a value

    Is it possible to Exec a dsql statement and return a simple value to a local var? e.g
    Using Temp tables is the only way. The dynamic statement is "Executed" in a separate batch and batches cannot access each other's local variables.

    Edit: Temp tables is not the only way. Apparently you can accomplish this using sp_ExecuteSQL and Exec.

    Code:
    DECLARE @SQLString nvarchar(500);
    DECLARE @ParmDefinition nvarchar(500);
    DECLARE @MaxCustomer varchar(30);
    
    SET @SQLString = N'SELECT @Output = Max(CustomerId) FROM Customers'
    SET @ParmDefinition = N'@Output varchar(30) OUTPUT'
    
    EXECUTE sp_executesql @SQLString, @ParmDefinition, @Output = @MaxCustomer OUTPUT
    
    SELECT @MaxCustomer
    Last edited by brucevde; Nov 22nd, 2007 at 11:18 AM.

  5. #5
    MS SQL Powerposter szlamany's Avatar
    Join Date
    Mar 2004
    Location
    Connecticut
    Posts
    18,263

    Re: Dynamic SQL and Exec returning a value

    @brucevde - nice find!

    I'm sure it's just a wrapper for doing it the old fashion way - but it certainly does make it look neater.

    After looking into the MASTER DB I found that it's an EXTENDED SP - probably meaning it's written in a higher level language - compiled down to a DLL - and made to look like a normal T-SQL sproc.

    I would imagine - and I've not tested this - that it might be slower.

    *** Read the sticky in the DB forum about how to get your question answered quickly!! ***

    Please remember to rate posts! Rate any post you find helpful - even in old threads! Use the link to the left - "Rate this Post".

    Some Informative Links:
    [ SQL Rules to Live By ] [ Reserved SQL keywords ] [ When to use INDEX HINTS! ] [ Passing Multi-item Parameters to STORED PROCEDURES ]
    [ Solution to non-domain Windows Authentication ] [ Crazy things we do to shrink log files ] [ SQL 2005 Features ] [ Loading Pictures from DB ]

    MS MVP 2006, 2007, 2008

  6. #6
    MS SQL Powerposter szlamany's Avatar
    Join Date
    Mar 2004
    Location
    Connecticut
    Posts
    18,263

    Re: Dynamic SQL and Exec returning a value

    Actually the sp_executesql is incredibly faster.

    I did this as a test

    Code:
    set nocount on
    create table #result (val int)
    declare @i int
    declare @val int
    set @i=1
    While @i<25000
    Begin
    	insert into #result exec('select 1')
    	set @val=(select val from #result)
    	truncate table #result
    	Set @i=@i+1
    End
    drop table #result
    That 25000 iterations took 4 seconds.

    I tried this - it was so fast I had to change the iterations to 250,000!

    Code:
    set nocount on
    
    declare @i int
    declare @val int
    
    DECLARE @SQLString nvarchar(500);
    DECLARE @ParmDefinition nvarchar(500);
    SET @SQLString = N'SELECT @Output = 1'
    SET @ParmDefinition = N'@Output int OUTPUT'
    
    set @i=1
    While @i<250000
    Begin
    	EXECUTE sp_executesql @SQLString, @ParmDefinition, @Output = @Val OUTPUT
    	
    	Set @i=@i+1
    End
    The 250,000 took 4 seconds!

    New respect for extended stored procedures!

    *** Read the sticky in the DB forum about how to get your question answered quickly!! ***

    Please remember to rate posts! Rate any post you find helpful - even in old threads! Use the link to the left - "Rate this Post".

    Some Informative Links:
    [ SQL Rules to Live By ] [ Reserved SQL keywords ] [ When to use INDEX HINTS! ] [ Passing Multi-item Parameters to STORED PROCEDURES ]
    [ Solution to non-domain Windows Authentication ] [ Crazy things we do to shrink log files ] [ SQL 2005 Features ] [ Loading Pictures from DB ]

    MS MVP 2006, 2007, 2008

  7. #7

    Thread Starter
    Hyperactive Member
    Join Date
    Apr 2001
    Location
    N42 29.340 W71 53.215
    Posts
    422

    Re: Dynamic SQL and Exec returning a value

    Brucevde, excellent. Just what I always wanted (sort of)

    I'm going to have some fun, and maybe even do something useful, with this.

    Thanks, DaveBo
    "The wise man doesn't know all the answers, but he knows where to find them."
    VBForums is one place, but for the really important stuff ... here's a clue 1Tim3:15

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width