1

I need a SQL guru, this is driving me crazy... I'm getting an error when executing dynamic SQL with a user-defined Table Type:

Error: Operand type clash: VariableTableType is incompatible with VariableTableType

Problem: It doesn’t seem to really declare the VariableTableType in the [Database1] database even though the Use [Database1] is right above it. The XT function has to run in the [Database1] database for it to work.

If I run the exec with the dbname, it works- ex: exec database1.dbo.sp_executesql @cmdTest – but I have many client databases that have the same database structure (different data) where I have to pass in the client database name so I can’t hardcode it that way. If I make @dbname=’MainDatabase’ it will run – just doesn’t run against the right database.

[MainDatabase] Contains main stored proc that has the dynamic SQL: @dbname=’Database1’

      DECLARE @cmdTEST NVARCHAR(MAX)=N'USE '+@dbname +'
      DECLARE @t as dbo.VariableTableType
      INSERT @t
      SELECT VariableName,[Value],InstanceID FROM #tVarTble
      SELECT dbo.XT(''Test string'',7153,45,@t)RtnValue
      '
      exec sp_executesql @cmdTEST

Also tried passing in the VariableTableType and put the declaration outside of the dynamic sql. --exec sp_executesql @cmdTEST,N'@t VariableTableType READONLY',t=@t

[Database1] (this function also exists in the [MainDatabase]

      ALTER FUNCTION [dbo].[XT] 
      (
        @text nvarchar(max),
        @instanceID INT,
        @storeID INT,
        @vt dbo.VariableTableType READONLY
      )
      RETURNS nvarchar(max)
      AS BEGIN
      … code here
       RETURN @return
      END

VariableTableType exists in the [MainDatabase] and [Database1]

      CREATE TYPE [dbo].[VariableTableType] AS TABLE(
        [VariableName] [NVARCHAR](50) NULL,
        [Value] [NVARCHAR](50) NULL,
        [InstanceID] [INT] NULL
      )
wp78de
  • 18,207
  • 7
  • 43
  • 71
grc
  • 19
  • 2
  • Its actually 2014. When I tried the 3 names it worked with the exec database1.dbo.sp_executesql ... but I have to pass in the database name and can't just hardcode it. – grc Feb 05 '20 at 18:43
  • You should be able to concat the DB name to use it in your dynamic SQL in the three-part form. – wp78de Feb 05 '20 at 18:57
  • I can't use it on the VariableValueTable user-defined table type because it won't allow you to. I have it dynamically putting Use [Database1] but the VariableValueTable acts like it doesn't see it. Hence the error. – grc Feb 05 '20 at 19:01
  • If I change the Select dbo.XT( function to just be SELECT * from @t - it works. So it is something to do with the function call. I tried it with database1.dbo.XT( and it doesn't work. – grc Feb 06 '20 at 13:15
  • And it works if I just run it on Database1 (without dynamic SQL) – grc Feb 06 '20 at 13:38
  • I have upvoted. Maybe somebody else can help. – wp78de Feb 06 '20 at 15:13

0 Answers0