2

I have an insert statement in MSSQL as follows:

INSERT INTO A(KeyId, KeyName, Name)
SELECT ('?','?',BName)FROM B

The value of KeyId and KeyName are retreived from another table D

Table B- Table C mapping is BName= XName Table C- Table D mapping is Xname = XName There are like 1000 records from B which need to be inserted into A. how can i write an SP for the same?

Table A Columns - KeyId,KeyName,Name Table B Columns - Id,BName Table C Columns - XName Table D Columns - KeyId,KeyName, XName

2
  • what is the mapping between table B and C? Commented Dec 17, 2014 at 11:14
  • You write "SELECT KeyId,KeyName FROM C WHERE Name = 'SomeNameFromTableB'", but there's no NAME column in C... Commented Dec 17, 2014 at 11:23

2 Answers 2

2

In SQL Server 2005 and later you can use outer apply:

insert into A(KeyId, KeyName, Name)
select 
    CALC.KeyId,
    CALC.KeyName,
    B.Name
from B
   outer apply (select KeyId,KeyName from C where C.Name = 'SomeNameFromTableB') as CALC

For prior versions you can declare variables, fill it with values and use that variables:

declare @KeyId bigint, @KeyName nvarchar(max)
select @KeyId = KeyId, @KeyName = KeyName FROM C WHERE Name = 'SomeNameFromTableB'

insert into A(KeyId, KeyName, Name)
select 
    @KeyId,
    @KeyName,
    B.Name
from B

UPDATE As from OP's comment:

The value of Name='SomeNamefromTableB' is actually the value i am inserting i.e. B.Name

So, in this case you just can use join:

insert into A(KeyId, KeyName, Name)
select 
    C.KeyId,
    C.KeyName,
    B.BName
from B
   left outer join C on C.XName = B.BName
Sign up to request clarification or add additional context in comments.

6 Comments

Hi The value of Name='SomeNamefromTableB' is actually the value i am inserting i.e. B.Name. Will it work if i replace it?
2nd option can have problem if there are more then one rows returned by select from C. one more thing : as per question Name column is not in table C but used in where clause.
Updated the question. The column in C is XName. It contains some value from BName in table B
@Eve in this case you just can use join. I've updated the answer.
@AndyKorneyev i cannot use a simple join. Its a little more complex than that. I have elaborated the table structure . Updated the question
|
0

try this :

INSERT INTO A(KeyId,KeyName,Name)
SELECT c.KeyId,
       c.KeyName,
       c.XName
FROM   C
       JOIN B
         ON c.XName = b.Name 

This will insert those rows from C where c.XName is present in b.Name.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.