Table Name Variable in SQL used in an If..else

  • You can use code like this to return a variable from sp_executesql.

    declare @strstor_id int

    set @strstor_id = 6380

    declare @strDatabaseName varchar(10)

    set @strDatabaseName = 'pubs'

    declare @cnt int

    Select @cnt=Count(*) from pubs.dbo.stores v WHERE v.stor_ID = 6380

    print @cnt

    set @cnt = 99

    declare @cmd nvarchar(1000)

    set @cmd = 'Select @cnt=Count(*) from ' + rtrim(@strDatabaseName) + '.dbo.stores v WHERE v.stor_ID = ' + cast(@strstor_ID as char(10))

    print @cmd

    print @cnt

    exec sp_executesql @cmd,N'@cnt int out',@cnt out

    print @cnt

    Gregory Larsen, DBA

    If you looking for SQL Server Examples check out my website at http://www.geocities.com/sqlserverexamples

    Gregory A. Larsen, MVP

Viewing post 1 (of 2 total)

You must be logged in to reply to this topic. Login to reply