Created
June 28, 2019 14:10
-
-
Save karenpayneoregon/42b9f859b89758db60fca33f0ec5b880 to your computer and use it in GitHub Desktop.
Rough example of creating a list of DataTable using TSQL OFFSET and FETCH NEXT
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Data; | |
using System.Data.SqlClient; | |
using System.Linq; | |
using System.Text; | |
using System.Threading.Tasks; | |
using BaseConnectionLibrary.ConnectionClasses; | |
namespace SQL_SplittingTable | |
{ | |
public class DataOperations : SqlServerConnection | |
{ | |
public DataOperations() | |
{ | |
DatabaseServer = ".\\SQLEXPRESS"; | |
DefaultCatalog = "NorthWindAzureForInserts"; | |
} | |
public List<DataTable> GetDataSet() | |
{ | |
var dataTables = new List<DataTable>(); | |
var totalRecords = 0; | |
var tableIndex = 1; | |
using (var cn = new SqlConnection {ConnectionString = ConnectionString}) | |
{ | |
using (var cmd = new SqlCommand {Connection = cn}) | |
{ | |
var selectStatement = | |
@"SELECT Cust.CustomerIdentifier, | |
Cust.CompanyName, | |
Cust.ContactName, | |
C.[Name] AS Country | |
FROM dbo.Customers AS Cust | |
INNER JOIN dbo.Countries AS C | |
ON Cust.CountryIdentifier = C.CountryIdentifier | |
ORDER BY Cust.CustomerIdentifier | |
OFFSET @Offset ROWS | |
FETCH NEXT 25 ROWS ONLY;"; | |
var countStatement = "SELECT COUNT(Cust.CustomerIdentifier) FROM dbo.Customers AS Cust"; | |
cmd.CommandText = countStatement; | |
cn.Open(); | |
totalRecords = Convert.ToInt32(cmd.ExecuteScalar()); | |
cmd.CommandText = selectStatement; | |
cmd.Parameters.Add("@OffSet", SqlDbType.Int); | |
for (var index = 0; index < totalRecords; index++) | |
{ | |
if (index % 25 == 0) | |
{ | |
cmd.Parameters["@OffSet"].Value = index; | |
var dt = new DataTable() {TableName = $"Table{tableIndex}"}; | |
dt.Load(cmd.ExecuteReader()); | |
dataTables.Add(dt); | |
tableIndex += 1; | |
} | |
} | |
} | |
} | |
return dataTables; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment