using EXEC on SQL statements

RoyB09 306 Reputation points
2020-09-08T21:17:27.797+00:00

qryS
Select avg(len(Question)) FROM dbo.Student_Question
Select avg(len(Answer)) FROM dbo.Student_Question
Select avg(len(Learner_Id)) FROM dbo.Student_Question

I’ve got a table with the following column (it also has other columns). I want to select all the columns, but execute the queries in Column qryS. I’ve mostly achieved it in the Cursor below, but am having issues putting the EXEC ( @strqry) result into a variable

Much appreciation if someone could point out where I’m going wrong.

DECLARE c1 Cursor
FOR

select
d.SchemaName, d.Table_Name, d.Column_Name, d.Column_Position, d.DataType, d.max_length, d.qryS
from dbo.Test2020 d
Open c1

DECLARE @strSchema VARCHAR(50);
DECLARE @strTable VARCHAR(50);
DECLARE @strColumn VARCHAR(50);
DECLARE @ColPos int;
DECLARE @strDataType VARCHAR(50);
DECLARE @MaxLen int;
DECLARE @strqry VARCHAR(MAX);

Fetch NEXT FROM c1 INTO @strSchema
,@strTable
,@strColumn
,@ColPos
,@strDataType
,@MaxLen
,@strqry

While (@@Fetch _STATUS <> -1)
BEGIN
IF (@@Fetch _STATUS <> -2)

Declare @x int
Set @x=EXEC ( @strqry )

--EXEC @x=YourStoredProcedure 1,null, @OutputParameter OUTPUT

insert into dbo.Test2020_a (SchemaName, Table_Name, Column_Name, Column_Position, DataType, max_length, qryResult )
values( @strTable ,@strColumn ,@ColPos ,@strDataType ,@MaxLen , @x )

FETCH NEXT FROM c1 INTO @strSchema,@strTable ,@strColumn ,@ColPos ,@strDataType ,@MaxLen ,@strqry
END
CLOSE c1
DEALLOCATE c1

GO

Thanks in advance (it’s been a long day)
Roy

SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
12,951 questions
0 comments No comments
{count} votes

1 additional answer

Sort by: Most helpful
  1. RoyB09 306 Reputation points
    2020-09-08T22:35:05.783+00:00

    Thanks Erland. I've figured a work arount, but will definitely read the article ...

    0 comments No comments