Solved

SQL create table using stored procedure

Posted on 2012-03-22
2
412 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:
ScottPletcher 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:ScottPletcher
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

Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

Join & Write a Comment

Everyone has problem when going to load data into Data warehouse (EDW). They all need to confirm that data quality is good but they don't no how to proceed. Microsoft has provided new task within SSIS 2008 called "Data Profiler Task". It solve th…
For both online and offline retail, the cross-channel business is the most recent pattern in the B2C trade space.
Via a live example, show how to backup a database, simulate a failure backup the tail of the database transaction log and perform the restore.
Via a live example, show how to set up a backup for SQL Server using a Maintenance Plan and how to schedule the job into SQL Server Agent.

747 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

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now