Solved

SQL create table using stored procedure

Posted on 2012-03-22
2
414 Views
Last Modified: 2012-03-23
I am wondering if it is possible to run a stored procedure that will create a table based on the following example.  I want to create the table below called LinkTable (either scenario) from CompanyTable.  If this is possible would it matter if CompanyTable is an sql view instead of a table?

CompanyTable
CompanyID      ContactID
100            1
100            2
100            3
200            4
200            5
300            6
300            7
300            8

LinkTable
CompanyID      ContactID
100            1,2,3
200            4,5
300            6,7,8

OR

LinkTable
CompanyID      ID1      ID2      ID3
100            1      2      3
200            4      5
300            6      7      8
0
Comment
Question by:schwientekd
  • 2
2 Comments
 
LVL 69

Accepted Solution

by:
Scott Pletcher earned 500 total points
ID: 37754670
SELECT CompanyID, LEFT(ContactID, LEN(ContactID) - 1) AS ContactID
FROM (
SELECT
    CompanyID, CAST(
    (SELECT TOP 100 PERCENT CAST(ct2.ContactID AS varchar(10)) + ','
     FROM dbo.CompanyTable ct2
     WHERE ct2.CompanyID = ct1.CompanyID
     ORDER BY ct2.ContactID
     FOR XML PATH('')
    )
    AS varchar(max)) AS ContactID
FROM (
    SELECT DISTINCT CompanyID
    FROM dbo.CompanyTable
) AS ct1
) AS derived
0
 
LVL 69

Expert Comment

by:Scott Pletcher
ID: 37754675
Once you confirm that's working the way you want it, just add this in front of the entire SELECT above:

INSERT INTO LinkTable ( CompanyID, ContactID )
SELECT ...
0

Featured Post

Microsoft Certification Exam 74-409

Veeam® is happy to provide the Microsoft community with a study guide prepared by MVP and MCT, Orin Thomas. This guide will take you through each of the exam objectives, helping you to prepare for and pass the examination.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Let's review the features of new SQL Server 2012 (Denali CTP3). It listed as below: PERCENT_RANK(): PERCENT_RANK() function will returns the percentage value of rank of the values among its group. PERCENT_RANK() function value always in be…
This article shows gives you an overview on SQL Server 2016 row level security. You will also get to know the usages of row-level-security and how it works
This video shows how to set up a shell script to accept a positional parameter when called, pass that to a SQL script, accept the output from the statement back and then manipulate it in the Shell.
This videos aims to give the viewer a basic demonstration of how a user can query current session information by using the SYS_CONTEXT function

776 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question