I'm using SQL Server 2008 R2 and I want to build a web form in ASP.NET that runs a SELECT command on my database and creates a json from it.
This is my code:
using (SqlConnection connection = new SqlConnection(ConnectionString))
{
String query = "SELECT * FROM dbo.apartments FOR JSON";
using (SqlCommand command = new SqlCommand(query, connection))
{
connection.Open();
var jsonResult = new StringBuilder();
var reader = command.ExecuteReader();
if (!reader.HasRows)
{
jsonResult.Append("[]");
}
else
{
while (reader.Read())
{
jsonResult.Append(reader.GetValue(0).ToString());
}
}
connection.Close();
}
}
When I run it, I get this error:
Exception Details: System.Data.SqlClient.SqlException: Incorrect syntax near 'JSON'.