I have to pass data in some structured format which is at the code side in a List of an anonymous type to the SQL which is then converted into a Temp table and therefore used in further joins. Currently, I am looping through the data and creating a string using StringBuilder which is actually CREATE temp table and INSERT INTO statements.
Below is my code
StringBuilder sql = new StringBuilder();
sql.Append(@"
IF OBJECT_ID('tempdb..#Student') IS NOT NULL
DROP TABLE #Student
IF OBJECT_ID('tempdb..#Temp') IS NOT NULL
DROP TABLE #Temp
CREATE TABLE #Student (StudentId int,StudentName varchar(500),Marks int, DepartmentId int);");
foreach (var item in studentData)
{
sql.AppendLine();
sql.AppendLine("INSERT INTO #Student (");
StringBuilder values = new StringBuilder("VALUES (");
bool isFirstColumn = true;
Type type = item.GetType();
PropertyInfo[] propertyInfo = type.GetProperties();
foreach (PropertyInfo property in propertyInfo)
{
string columnName = property.Name;
object columnValue = property.GetValue(item);
if (isFirstColumn)
isFirstColumn = false;
else
{
sql.Append(", ");
values.Append(", ");
}
sql.Append(columnName);
values.Append(columnValue);
}
sql.Append(") ");
sql.AppendLine();
sql.Append(values.ToString());
sql.Append(")");
}
sql.AppendLine();
sql.Append(@"SELECT *
INTO #Temp
FROM
(
SELECT *
FROM #Student s
JOIN Department d ON s.DepartmentId = d.DepartmentId
) as t");
I dont have the option of using Stored Proc. Is there any better option to create Temp table than using StringBuilder which will be then inserted in SQL query?
Can we convert the data in the List into XML and then add the data in XML format in the string SQL query?
Any help or suggestions for a better code than this?
Thanks
Since you are using ADO.NET, you can use Table-Valued Parameters and pass the Table-Valued Type to a parameterized SQL statement. I'd opt for using a stored procedure, but both will work.
modified example usage from MS Docs (not tested)
using (connection)
{
// Create a DataTable with the modified rows.
DataTable addedStudents = StudentsDataTable.GetChanges(DataRowState.Added);
// Define the INSERT-SELECT statement.
string sqlInsert =
"INSERT INTO dbo.Students (xxx, yyy)"
+ " SELECT s.xxx, s.yyy"
+ " FROM @tvpStudents AS s;"
// Configure the command and parameter.
SqlCommand insertCommand = new SqlCommand(sqlInsert, connection);
SqlParameter tvpParam = insertCommand.Parameters.AddWithValue("@tvpStudents", addedStudents);
tvpParam.SqlDbType = SqlDbType.Structured;
tvpParam.TypeName = "dbo.StudentTableType";
// Execute the command.
insertCommand.ExecuteNonQuery();
}
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.