Sql server select - varchar containing column name and value - c#

I need to add a bunch of c# code to test values against a table. Connecting directly to the data source is out of the question (this needs to be static code).
The output is
X.AddColumn("ColumnName",ColumnValue);
I would like to get a SQL statement that, for a table returns the above pattern, listing each column of a row, iterating through every row in the table.
I was hoping for a select statement in the db that I could copy and paste result set of, ideally one that went through columns dynamically to save me doing something like below for each table I wish to output.
SELECT 'X.AddColumn("ColumnName1", ' + CONVERT(VARCHAR, ColumnName1, 100) +');' AS Col1
...
'X.AddColumn("ColumnNameN", ' + CONVERT(VARCHAR, ColumnNameN, 100) +');' AS ColN
FROM
Schema.Table1

Of the top of my head, this is a 2 step process:
Run the statement below. It will create a query for each of the columns of your table (something like select 'x.AddColumn("Column1", ' + Convert(varchar, Column1, 100) +' )' from dbo.Table1)
SELECT 'select ''x.AddColumn("' + c.column_name
+ '", ''+ Convert(varchar, ' + c.column_name
+ ',100)+'' )'' from ' + c.table_schema + '.'
+ c.table_name
FROM information_schema.columns c
WHERE c.table_name = 'Table1'
AND c.table_schema = 'dbo'
Copy the output of the statement above and run it. It should give you the desired output.

Related

Is it possible to update bunch of different Tables in DB with the same modification to all?

I want to duplicate all my tables in SQL Server, all table names would have had "temp" added at the beginning. And all of them would have had added an extra column (the same to all). I don't need whole code, just general idea how to do it.
A straightforward way to go:
You need to fetch the table names from your database (probably using INFORMATION_SCHEMA.TABLES).
For each of those tables from step 1, you need to generate a corresponding SELECT ... INTO statement.
You need to execute each generated SQL statement from step 2.
You already have a solution with a cursor. This is one without a cursor:
DECLARE #script VARCHAR(MAX) = '';
SELECT #script = #script + 'SELECT * INTO [temp'+ TABLE_NAME +'] FROM [' + TABLE_NAME + '];' + CHAR(13) + CHAR(10) FROM INFORMATION_SCHEMA.TABLES
EXEC (#script);
Remark: The CHAR(13) + CHAR(10) is not necessary; just added for readability if you want to check the script first (using PRINT instead EXEC).
Edit:
An additional question in the comments to add a checksum value in the resulting tables could be done as follows:
DECLARE #script VARCHAR(MAX) = '';
SELECT #script = #script + 'SELECT CHECKSUM(*) AS [__checksum], * INTO [temp'+ TABLE_NAME +'] FROM [' + TABLE_NAME + '];' + CHAR(13) + CHAR(10) FROM INFORMATION_SCHEMA.TABLES
EXEC (#script);
Using HASHBYTES instead of CHECKSUM is probably better, but it accepts only two parameters: the hash algorithm and a single value to hash. So in that case, you probably need to pass a string value by manually concatenating all the fields of your tables, and that may be somewhat troublesome to add in a dynamic query like mine. It would probably result in something more complex than just three lines...
Well, something like this, actually:
DECLARE #script NVARCHAR(MAX) = N'';
WITH
[Columns] AS
(
SELECT
TABLE_NAME AS [TableName],
COLUMN_NAME AS [ColumnName],
ROW_NUMBER() OVER (PARTITION BY TABLE_NAME ORDER BY ORDINAL_POSITION) AS [ColSeq]
FROM
INFORMATION_SCHEMA.COLUMNS
),
[Tables] AS
(
SELECT
[TableName],
CAST(N'[' + [ColumnName] + N']' AS NVARCHAR(MAX)) AS [ColumnList],
[ColSeq]
FROM
[Columns] AS C
WHERE
[ColSeq] = (SELECT MAX([ColSeq])
FROM [Columns]
WHERE [TableName] = C.[TableName])
UNION ALL
SELECT T.[TableName], N'[' + C.[ColumnName] + N'], ' + T.[ColumnList], C.[ColSeq]
FROM
[Tables] AS T
INNER JOIN [Columns] AS C ON C.[TableName] = T.[TableName] AND C.[ColSeq] = T.[ColSeq] - 1
)
SELECT #script = #script + N'SELECT HASHBYTES(''md5'', CONCAT(N'''', ' + [ColumnList] + N')) AS [__checksum], * INTO [temp' + [TableName] + N'] FROM [' + [TableName] + N'];' + NCHAR(13) + NCHAR(10)
FROM [Tables]
WHERE [ColSeq] = 1;
EXEC (#script);
Remarks:
In the recursive CTE [Tables], which is used for concatenating the column names of each table in a comma-separated string value, I started at the last column and moved backwards to ease the filter condition in my main query.
I added an additional first parameter N'' to the CONCAT calls in the resulting #script contents, since the CONCAT function requires at least 2 arguments, which would be troublesome in this case when processing tables with just one column.
In this case, despite the somewhat worse performance, it might be clearer and easier to fall back to using a cursor, like #HasanMahmood suggested in his answer...
try this code:
get all the table name form information schema and run a dynamic sql to create tables
DECLARE #script varchar(max)
DECLARE db_cursor CURSOR FOR
SELECT script = 'Select * Into [temp'+ TABLE_NAME +'] From ' + QUOTENAME(TABLE_NAME) FROM INFORMATION_SCHEMA.TABLES
OPEN db_cursor
FETCH NEXT FROM db_cursor INTO #script
WHILE ##FETCH_STATUS = 0
BEGIN
EXEC(#script)
--PRINT #script
FETCH NEXT FROM db_cursor INTO #script
END
CLOSE db_cursor
DEALLOCATE db_cursor

Joining across several tables - then applying a PIVOT to display the data differently

I am trying to figure a way to execute a seemingly complex join scenario, and am unsure as to how to go about it.
Some Background info:
-I have a 'ProjectCategory' table, which contains a foreign key 'ProjectID' and 'CategoryID' to the Project and Category tables respectively. One project could have as many assigned categories to it as there are existing (up to 10)
-I have a 'Budget' table and a 'Sponsor' Table.
-My 'Project' table is related to my 'Budget' Table in that all Projects have an associated BudgetID
-My 'Budget' Table is related to my 'Sponser' table in that all Budgets have an associated SponsorID.
-'Project' table and 'Sponsor' table are not directly related.
An example of the result set that I am trying to get is firstly:
SponsorName(Field in sponsor table) - ProjectName - Category
___________________________________ ___________ ________
A ABC categoryA
A ABC categoryB
A DEF categoryX
A DEF categoryZ
I would then like to use a PIVOT to show the data like:
SponsorName - ProjectName -categoryA - categoryB -categoryC - categoryD ...
___________ ___________ _________ _________ _________ _________
A ABC X X
A DEF X X
B EFG X X
Where the Xs mark which categories are associated with each project/sponsor combination. The filling in of the Xs is maybe something I will do in the codebehind or using other stored procedures, but this is the basic idea of what I am trying to do.
I am having trouble even figuring out how to write a query to get back the first set before I even implement a pivot to show it as the second set, so I am a bit intimidated by this task. Any help greatly appreciated, and please let me know if you need any more information
Assuming SQL Server, I use a stored procedure for the bulk of Dynamic PIVOTS. (Listed Below)
The source could be a table, #temp or even SQL
Exec [prc-Pivot] '#Temp','Category','max(''X'')[]','SponsorName,ProjectName',null
Returns
SponsorName ProjectName categoryA categoryB categoryD categoryX categoryZ
A ABC X X NULL NULL NULL
A DEF NULL NULL NULL X X
B EFG X NULL X NULL NULL
The Stored Procedure
CREATE PROCEDURE [dbo].[prc-Pivot] (
#Source varchar(1000), -- Any Table or Select Statement
#PvotCol varchar(250), -- Field name or expression ie. Month(Date)
#Summaries varchar(250), -- aggfunction(aggValue)[optionalTitle]
#GroupBy varchar(250), -- Optional additional Group By
#OtherCols varchar(500) ) -- Optional Group By or aggregates
AS
--Exec [prc-Pivot] 'Select Year=Year(TR_Date),* From [Chinrus-Series].[dbo].[DS_Treasury_Rates]','''Q''+DateName(QQ,TR_Date)','avg(TR_Y10)[-Avg]','Year','count(*)[Records],min(TR_Y10)[Min],max(TR_Y10)[Max],Avg(TR_Y10)[Avg]'
Set NoCount On
Set Ansi_Warnings Off
Declare #Vals varchar(max),#SQL varchar(max);
Set #Vals = ''
Set #OtherCols= IsNull(', ' + #OtherCols,'')
Set #Source = case when #Source Like 'Select%' then #Source else 'Select * From '+#Source end
Create Table #TempPvot (Pvot varchar(100))
Insert Into #TempPvot
Exec ('Select Distinct Convert(varchar(100),' + #PvotCol + ') as Pvot FROM (' + #Source + ') A')
Select #Vals = #Vals + ', isnull(' + Replace(Replace(#Summaries,'(','(CASE WHEN ' + #PvotCol + '=''' + Pvot + ''' THEN '),')[', ' END),NULL) As [' + Pvot ) From #TempPvot Order by Pvot
Drop Table #TempPvot
Set #SQL = Replace('Select ' + Isnull(#GroupBy,'') + #OtherCols + #Vals + ' From (' + #Source + ') PvtFinal ' + case when Isnull(#GroupBy,'')<>'' then 'Group By ' + #GroupBy + ' Order by ' + #GroupBy else '' end,'Select , ','Select ')
--Print #SQL
Exec (#SQL)
Set NoCount Off
Set Ansi_Warnings on

Many SQL rows into one

I've got a stored procedure which joins a number of tables to produce a large resultset which is then returned to my application. The application in turn loops through the results and combines rows on a particular ID and chooses data per row to include in a new object. This is perhaps easiest to explain using an example:
Inspection, Desc, Value
1, Description1, 3
1, Description2, 2
1, Description3, 5
This is in code turned into
Inspection, Description1, Description2, Description3
1, 3, 2, 5
The point of this is to have one row per inspection item with item description as headers and value as the cell value for inspection row and header. This is then exported to Excel.
The question is: how do I do this in SQL Server, as in expanding my SP to return a lot fewer but "wider" rows with a lot more columns?
Another complication is that one inspection may have rows which another one lacks, in that case the solution is to add an empty value or a '-'.
P.S. This is using Sql Server 2012.
If you are using mssql 2005+. You can use a pivot like this:
Test data
DECLARE #tbl TABLE(Inspection INT, [Desc] VARCHAR(100),Value INT)
INSERT INTO #tbl
VALUES
(1,'Description1', 3),
(1,'Description2', 2),
(1,'Description3', 5)
Query
SELECT
*
FROM
(
SELECT
tbl.Inspection,
tbl.[Desc],
tbl.Value
FROM
#tbl AS tbl
) AS tbl
PIVOT
(
SUM(Value)
FOR [Desc] IN ([Description1],[Description2],[Description3])
)AS pvt
Result:
Inspection, Description1, Description2, Description3
1 3 2 5
Edit
As juharr said in the comment:
The resulting column names (values in the table) are when building the query. Which might require another initial query to get
Edit 2
If you are not using mssql 2005+. Or want to have and alternitive explanation. Please see the following query:
SELECT
tbl.Inspection,
SUM(CASE WHEN [Desc]='Description1' THEN tbl.Value ELSE 0 END) AS Description1,
SUM(CASE WHEN [Desc]='Description2' THEN tbl.Value ELSE 0 END) AS Description2,
SUM(CASE WHEN [Desc]='Description3' THEN tbl.Value ELSE 0 END) AS Description3
FROM
#tbl AS tbl
GROUP BY
tbl.Inspection
This do not requiere a pivot and can be use on most of RDMS out there
You should use Sql Server Pivot. It converts rows into columns. You can have an easiest start by this example.
If you'd like to do this dynamically, without having to know what all of the Desc values are, you can build your pivot query and use Exec() or Execute sp_executesql
DECLARE #Columns NVARCHAR(MAX),
#Sql NVARCHAR(MAX)
--Build your column headers based on Distinct Desc values
SELECT #Columns = COALESCE(#Columns + ',', '') + QUOTENAME([Desc])
FROM (SELECT DISTINCT [Desc] FROM tbl) t
ORDER BY [Desc]
--Build your pivot query
SET #Sql = '
SELECT
*
FROM
tbl
PIVOT
(
MAX([Value])
FOR [Desc] IN (' + #Columns + ')
) p
'
EXEC(#Sql)
If you want - for null values, you'll need to create another variable to hold the conversion scripts for the Select part of your sql.
DECLARE #Columns NVARCHAR(MAX),
#Sql NVARCHAR(MAX),
#ColumnAliases NVARCHAR(MAX)
--Build your pivot columns based on Distinct Desc values
SELECT #Columns = COALESCE(#Columns + ',', '') + QUOTENAME([Desc])
FROM (SELECT DISTINCT [Desc] FROM tbl) t
ORDER BY [Desc]
--Build your column headers, replacing NULL with -
SELECT #ColumnAliases = COALESCE(#ColumnAliases + ',', '')
+ 'COALESCE(CONVERT(VARCHAR,' + QUOTENAME([Desc]) + '),''-'') AS ' + QUOTENAME([Desc])
FROM (SELECT DISTINCT [Desc] FROM tbl) t
ORDER BY [Desc]
--Build your pivot query
SET #Sql = '
SELECT
Inspection,'
+ #ColumnAliases + '
FROM
tbl
PIVOT
(
MAX([Value])
FOR [Desc] IN (' + #Columns + ')
) p
'
EXEC(#Sql)

What is the best way to loop through sql (SQL or Asp.net C#)?

I am creating a list to send an e-mail to. The individual who is logged in has a field in the database of who they report to (unless there is an error or they report to no one).
So for instance if I am logged in and clicked the submit button in SQL it would say I report to 'John Doe'
I then need to grab who 'John Doe' reports to and add that to the list. I need to keep climbing the list until we reach the top of the company (the GID will be blank or null).
Using me as an example, I report to 'John Doe' who reports to 'Tom Doe'. Tom reports to no-one his usrReportsTo field is like this '00000000-0000-0000-0000-000000000000'.
If the usrReportsTo field is "" or NULL or '00000000-0000-0000-0000-000000000000' the loop should terminate.
Here is the sql I used.
What is the cleanest/neatest/most effecient way to perform this loop and is it better to do it in SQL or ASP.net C#?
select usrReportsTo from dbo.CVT_Users_usr, usrEmailAddress
WHERE RTRIM(usrFirstName) + ' ' + RTRIM(usrLastName) = 'James Wilson'
-- Returns 'James Wilson' + email
SELECT RTRIM(usrFirstName) + ' ' + RTRIM(usrLastName) as Name, usrEmailAddress, usrReportsTo from dbo.CVT_Users_usr
WHERE usrGID = '38922F83-4B6E-499E-BF4F-EF0B094F47F7'
-- Returns 'John Doe' + email + reportsTo
SELECT RTRIM(usrFirstName) + ' ' + RTRIM(usrLastName) as Name, usrEmailAddress, usrReportsTo from dbo.CVT_Users_usr
WHERE usrGID = 'FB8F4939-3956-4834-9D89-D72AFB8BF3E0'
-- Returns 'Tom Doe' + email + reportsTo
Edit #3
Working copy of SQL just doesn't return 100% true data.
with cte
AS
(
select usrGID, RTRIM(usrFirstName) + ' ' + RTRIM(usrLastName) as Name, usrEmailAddress, usrReportsTo from dbo.CVT_Users_usr
union all
select u.usrGID, RTRIM(u.usrFirstName) + ' ' + RTRIM(u.usrLastName), cte.usrEmailAddress, cte.usrReportsTo from dbo.CVT_Users_usr u
inner join cte on u.usrReportsTo = cte.usrGID
)
select * from cte
where Name = 'James Wilson'
-- Returns
usrGID Name usrEmailAddress usrReportsTo
E1DAFC11-BE35-4730-9961-68EEF8D85DE4 James Wilson 38922F83-4B6E-499E-BF4F-EF0B094F47F7
E1DAFC11-BE35-4730-9961-68EEF8D85DE4 James Wilson john#1234.com FB8F4939-3956-4834-9D89-D72AFB8BF3E0
E1DAFC11-BE35-4730-9961-68EEF8D85DE4 James Wilson tom#1234.com 00000000-0000-0000-0000-000000000000
Shouldn't the usrGID and name match the same way usrEmailAddress and usrReportsTo does? I tried chaanging the sql to be cte.USRGID and cte.Name but it gave the max recursion error.
Any ideas?
Using a common table expression you can generate the complete result set in one SQL statement (via a recursive join), thus avoiding any looping at all.
A basic example with the key fields
create table #CVT_Users_usr (usrGid uniqueidentifier, usrEmailAddress varchar(50), usrFirstName varchar(20), usrLastName varchar(20), usrReportsTo uniqueidentifier)
insert #CVT_Users_usr values
('38922F83-4B6E-499E-BF4F-EF0B094F47F7' , 'james#wilson.com','james','wilson', 'E1DAFC11-BE35-4730-9961-68EEF8D85DE4'),
('E1DAFC11-BE35-4730-9961-68EEF8D85DE4', 'john#doe.com','john','doe', 'FB8F4939-3956-4834-9D89-D72AFB8BF3E0'),
('FB8F4939-3956-4834-9D89-D72AFB8BF3E0', 'tom#doe.com','tom','doe' ,'00000000-0000-0000-0000-000000000000'),
('FE6899A5-63BA-42B7-A70E-011711A5FAC6', 'ken#ken.com','ken', 'kenneths', 'FB8F4939-3956-4834-9D89-D72AFB8BF3E0')
declare #id uniqueidentifier
select #id = usrGid from #CVT_Users_usr where usrFirstName='james' and usrLastName='wilson'
;with cte as
(
select usrGid, usrEmailAddress, usrFirstName, usrLastName, usrReportsTo from #CVT_Users_usr
union all
select u.usrGid, cte.usrEmailAddress, cte.usrFirstName, cte.usrLastName, cte.usrReportsTo
from #CVT_Users_usr u
inner join cte on u.usrReportsTo= cte.usrGid
)
select usrFirstName + ' ' + usrLastName, usrEmailAddress from cte
where usrGid=#id
drop table #CVT_Users_usr

SQL Server - PIVOT

We are working on a C# application, we've been using Linq to SQL or standard ADO (when performance needed) to work with SQL Server.
We have a table layed out like so:
Customer ID, Year/Month, Product Name, Quantity
Each customer has additional columns per product.
We need display this information in a data grid like so:
Customer, Year/Month, Product A Quantity, Product B Quantity, Product C Quantity, etc.
What query could give us these results? And how could it be dynamic no matter what products are added and removed? We will be using a ListView in WPF for displaying the data.
We would just store the information differently, but they can add/remove products all the time.
Will PIVOT work?
(PS - the product names are really in another table for normalization, I changed it a little for simplicity for you guys)
The sql pivot command can be used but it requires the columns to be hard-coded. You could either hard-code them, use dynamic sql to generate the columns, or only get the raw data from sql without a pivot and do the data massaging in c#.
You can use pivot with dynamic SQL. Following T-SQL code is taken from this article on sqlteam.com. I've tried to modify the sample for your needs. Also beware of dangers using dynamic SQL, it might lead to SQL Injection if a product name contains apostrophe.
Create a stored proc first;
CREATE PROCEDURE crosstab
#select varchar(8000),
#sumfunc varchar(100),
#pivot varchar(100),
#table varchar(100)
AS
DECLARE #sql varchar(8000), #delim varchar(1)
SET NOCOUNT ON
SET ANSI_WARNINGS OFF
EXEC ('SELECT ' + #pivot + ' AS pivot INTO ##pivot FROM ' + #table + ' WHERE 1=2')
EXEC ('INSERT INTO ##pivot SELECT DISTINCT ' + #pivot + ' FROM ' + #table + ' WHERE '
+ #pivot + ' Is Not Null')
SELECT #sql='', #sumfunc=stuff(#sumfunc, len(#sumfunc), 1, ' END)' )
SELECT #delim=CASE Sign( CharIndex('char', data_type)+CharIndex('date', data_type) )
WHEN 0 THEN '' ELSE '''' END
FROM tempdb.information_schema.columns
WHERE table_name='##pivot' AND column_name='pivot'
SELECT #sql=#sql + '''' + convert(varchar(100), pivot) + ''' = ' +
stuff(#sumfunc,charindex( '(', #sumfunc )+1, 0, ' CASE ' + #pivot + ' WHEN '
+ #delim + convert(varchar(100), pivot) + #delim + ' THEN ' ) + ', ' FROM ##pivot
DROP TABLE ##pivot
SELECT #sql=left(#sql, len(#sql)-1)
SELECT #select=stuff(#select, charindex(' FROM ', #select)+1, 0, ', ' + #sql + ' ')
EXEC (#select)
SET ANSI_WARNINGS ON
Then try the following (I haven't test it, you might need to add qty to select statement)
EXECUTE crosstab 'select ProductID,CustomerID, YearMonth from sales group by ProductId', 'sum(qty)','ProductId','sales'
If you want to try a method that doesn't involve dynamic SQL, you could go through C#.
This guy ran a test comparing the two: http://weblogs.sqlteam.com/jeffs/jeffs/archive/2005/05/12/5127.aspx

Categories

Resources