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.
You have not declared
@sampleTblin your dynamic Query.And Table Variables scope is limited to the batch of execution. And the
Execstatement will execute the statements in a batch. Hence that Declaring, Inserting, Selecting & Updating of Table variables must and should be in the same batch. Means It should contain inside ofEXECStatement.2nd Question:My next problem is to pass column name as parameter as well.
Yes it is possible with
sp_executesqlHave a look at sp_executesql (Transact-SQL) for the same.