1

I'm looking for some views on how to go about resolving this challenge. I have a variable say @Var1 which holds a SQL statement within it.

Example

@Var1 = `SELECT * from another_table WHERE City IS NOT NULL AND Address IS NOT NULL` 

When I execute this variable

EXECUTE sp_executesql @Var1 

I get the desired result, City and Address excluding NULL values.

I am hoping to update a existing table (tbl1) based on execution result of @Var1:

Something like:

UPDATE TABLE tbl1 AS (EXECUTE sp_executesql @Var1) 

Is something like this even possible? Or what approach can I take to get the result of @Var1 into tbl1?

Thanks in advance.

6
  • "update a existing table based on execution result" what do you mean with this statement? You need joins to update against another result set. Commented Jun 14, 2018 at 11:23
  • as @EzLo writes. Then you need to join you result from var1 to your update table otherwise it makes no sense. Commented Jun 14, 2018 at 11:36
  • I am hoping to update an existing table example:(tbl1) based on execution result of @Var1 as explained in my question. Commented Jun 14, 2018 at 11:36
  • @Gary you are basically saying "I want to update [Table A] based on [Table B]". That is not enough information. Commented Jun 14, 2018 at 12:24
  • @JasonGeiger What ever data I retrieve by executing Var1, I am hoping to store that into exiting table "tbl1" . Just wondering if this is a possibility or not possible within SQL? Commented Jun 14, 2018 at 12:49

2 Answers 2

1

My apologies for including links for each step but they deserve the credit.

There are 2 steps. Insert into a temp-table then merge the data from that temp-table into your final table.

You will have to insert into a Temp Table first. INSERT INTO @TABLE EXEC @query with SQL Server 2000

Then you have to merge that data into you main table. SQL MERGE statement to update data

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for providing the answer, I would adapt this approach.
0

try This

UPDATE tbl1 SET Column1= b.Column1, SET Column2= b.Column2, SET Column3= b.Column3, FROM tbl1 a INNER JOIN ( SELECT Column1,Column2,Column3 FROM another_table WHERE City IS NOT NULL AND Address IS NOT NULL ) b ON a.city_Id = b.city_Id 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.