I have a stored procedure like this.
ALTER PROCEDURE [dbo].[storedProc_dataPull]
@serverName nvarchar(30),
@dbName nvarchar(30),
@tblName nvarchar(30),
@schemaName nvarchar (30),
@userID nvarchar (30),
@password nvarchar (30),
@sampleTbl nvarchar (30)
AS
BEGIN
DECLARE @schemaAndTbl nvarchar (39)
SET @schemaAndTbl = @dbName + '.' + @schemaName + '.' +@tblName
EXEC('INSERT INTO @sampleTbl
([ID]
,[ActivityDefinitionID]
,[ParentID]
,[Caption]
,[Description]
,[ShortDescription]
,[Name]
,[Order]
,[ReferenceNumber]
,[ShowOnNavigation]
,[Status]
,[InUseBy]
,[ExpectedStartDate]
,[ActualStartDate]
,[ExpectedEndDate]
SELECT *
FROM OPENDATASOURCE(''SQLOLEDB'',''Data Source=' + @serverName+ ';User ID='+@userID+';Password=' +@password+''').'+@schemaAndTbl+' sdb1')
UPDATE @sampleTbl
SET ServerName = ''+@serverName+'', DBName = ''+@dbName+''
WHERE ServerName IS NULL AND DBName IS NULL
END
When I'm trying to execute, I always get an error:
Must declare the table variable
My next problem is to pass column name as parameter as well.
Is it possible with SQL Server? I just want to make a dynamic stored procedure for my application.
The sample table
@sampleTbl
is a parameter in your stored procedure. Also this is with typenvarchar (30)
. This is not correct. I don't understand why you want to pass the table here as a parameter. If you want to pass table as a parameter, then you should declare it as a TYPE and the table should be passed as READONLY. You will not be able to write values in that table. Remove it from the parameter and modify the query as mentioned in the above answers. It will work..Happy Coding:)