I need to take this kind of String and create a new table with one value per row. The string comes from a C# array that values are essentially comma-separated but the string array includes random comments (eg //AB
)
{
//AB "AB:ABLOC", "AB:ABCOM", "AB:ABSTD_DC", "AB:CMTRT" //VAF "VAF:VALAT", "VAF:FCSTATSP", "VAF:STATSP"
}
This is the desired output table:
**Column:**
AB:ABLOC
AB:ABCOM
.
.
.
VAF:STATSP
I don't have access to create stored procedures, tables etc, I'm just running my SQL on the client (SQL Server). Is there any sensible way I can do this?
If I understand your need -create tables with AB
and VAF
name and some columns- I can suggest you a solution like running this query:
DECLARE @ColSptr varchar(3) = '//';
DECLARE @Sql varchar(max) = '';
WITH CTE(strTemp) AS(
SELECT SUBSTRING(@str, CHARINDEX(@ColSptr, @str, 1) + LEN(@ColSptr), LEN(@str))
UNION ALL
SELECT SUBSTRING(strTemp, CHARINDEX(@ColSptr, strTemp, 1) + LEN(@ColSptr), LEN(strTemp))
FROM CTE
WHERE CHARINDEX(@ColSptr, strTemp, 1) > 0
), colData AS (
SELECT
RTRIM(LTRIM(LEFT(strTemp, CHARINDEX(' ', strTemp + ' ', 1)))) AS TableName,
RTRIM(LTRIM(SUBSTRING(strTemp + @ColSptr, CHARINDEX(' ', strTemp + ' ', 1), CHARINDEX(@ColSptr, strTemp + @ColSptr, 1) - CHARINDEX(' ', strTemp + ' ', 1)))) AS ColumnNames
FROM
CTE
), finalColData AS (
SELECT
TableName,
REPLACE(REPLACE(ColumnNames, TableName + ':', ''), '"', '') AS ColumnNames
FROM
colData
)
SELECT
@sql = @sql + CASE WHEN @Sql <> '' THEN CHAR(13) + CHAR(10) ELSE '' END +
'CREATE TABLE ' + TableName + '(' +
'[' +REPLACE(ColumnNames , ', ', '] [varchar](10), [') + '] [varchar](10)) ON [PRIMARY]'
FROM
finalColData;
EXEC(@sql);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.