Is there any way to access the variables in a dynamic sql which is declared outside the dynamic sql.
I need to do the following:
- Query the information schema to get the parameter names to an sp SELECT PARAMETER_NAME, DATA_TYPE from information_schema.parameters where specific_name=@SPName
- Create a dynamic query using this names like select @param1+","+@param2 in a function.Which accepts @SPName as the parameter
- call this function in my sps to get the dynamic sql
- Execute this sql in my procedure and get the param 1 and param 2 value (param 1 +param2)
- Update this value in my spcallTracking Table SpCallDetails field
I have tried this method ,but getting error like Must declare the scalar variable (param 1) and the reason i Guess is Dynamic sql runs in a different session and therefore variables defined outside the dynamic query will not be available to the dynamic query
https://stackoverflow.com/questions/14960777/must-declare-the-scalar-variable-error-sql
1. Table-
CREATE TABLE [dbo].[Single](
[ID] [uniqueidentifier] NOT NULL,
[Name] [nvarchar](50) NOT NULL,
[Age] [nvarchar](50) NOT NULL,
CONSTRAINT [PK_Parent] PRIMARY KEY CLUSTERED
(
[ID] ASC,
[Name] ASC,
[Age] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY];
2. Function-
CREATE FUNCTION [dbo].[udf_getSPName]
(
@SPName nvarchar(100)
)
RETURNS nvarchar(4000)
AS
BEGIN
DECLARE @ReturnString nvarchar(4000)='SELECT '
DECLARE @tmpParameterDetails table (ParamName varchar(200),DataType varchar(200))
INSERT @tmpParameterDetails
SELECT PARAMETER_NAME, DATA_TYPE from information_schema.parameters
where specific_name=@SPName
SET @ReturnString=@ReturnString+
(SELECT STUFF(
(SELECT ','+ParamName
FROM
@tmpParameterDetails
FOR XML PATH (''))
,1, 1, ''))
Return @ReturnString
RETURN @ReturnString
END
3. Procedure-
CREATE PROCEDURE [dbo].[usp_Single_insert]
@Name nvarchar(50),
@Age int
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
DECLARE @ReturnString as nvarchar(max)
INSERT INTO [Single]
([ID]
,[Name]
,[Age])
VALUES
(NEWID(),
@Name,
@Age)
DECLARE @CreatedBy as nvarchar(100)='test'
DECLARE @CreatedOn as datetime=getdate()
DECLARE @ColV nvarchar(max)
DECLARE @ParmDefinition nvarchar(500);
SET @ReturnString=[dbo].[udf_getSPName]('usp_Single_insert')
EXECUTE sp_executesql @ReturnString
END