0

I'm trying to write an insert statement which would get data from an array.

I have two variables, one is BusinessID and one is BusinessType. A business can have multiple types. For example BusinessType = (1,2,3,4,5), however BusinessID would only ever be a single number e.g. BusinessID = 1

Is there a function in mssql to be able to do something like;

for BusinessType in BusinessType
   insert into Business 
   Values(BusinessID,BusinessType)

This would ideally give me the result

BusinessID BusinessType
     1          1
     1          2
     1          3
     1          4
     1          5
5
  • 2
    Normally it's the responsibility of the application layer to translate that comma-separated list into a series of INSERT statements. Commented Oct 17, 2017 at 17:50
  • What is the SQL datatype of "BusinessType"? Commented Oct 17, 2017 at 17:51
  • BusinessType is an int currently, but it can be something else if needed. Commented Oct 17, 2017 at 17:53
  • 1
    You could look into user defined table types and pass in a table valued parameter, or you can split the string (which is not good for performance), or you can generate multiple insert statements (also not good for performance). Commented Oct 17, 2017 at 17:54
  • A table called Business should contain records where each record represents a "business" (whatever this is in your context). If that table Business has a column called BusinessID, then this should be the ID to identify one record (or one "business"). It doesn't seem to make sense to have multiple records in Business that have the same BusinessID. It seems you are trying to build a kind of bridge table combining "businesses" with "business types". You should think over your database design or at least your naming pattern. Commented Oct 17, 2017 at 18:02

1 Answer 1

1

If not 2016, here is an inline approach to split your string

Uncomment the Insert line if satisfied with the results.

Example

Declare @BusinessID int = 1
Declare @Type varchar(max) = '1,2,3,4,5'  -- notice no ()'s

--Insert Into Business (BusinessID,BusinessType) 
Select BusinessID = @BusinessID
      ,BusinessType = B.i.value('(./text())[1]', 'int')
 From  (Select x = Cast('<x>' + replace(@Type,',','</x><x>')+'</x>' as xml).query('.')) as A 
 Cross Apply x.nodes('x') AS B(i)

Returns

BusinessID  BusinessType
1           1
1           2
1           3
1           4
1           5
Sign up to request clarification or add additional context in comments.

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.