I am trying to write a view and retrieve data from that view, I have done this :
string command = "if OBJECT_ID('try1') IS NOT NULL Drop view try1" +"\n"+"go"+"\n";
command = command + "Create view try1 as select WBSCode,Description,TerritoryCode,AmountReleased,convert(varchar(25),CreatedOn,106) as CreatedOn,IsEnable from WBS where WBSCode like '%" + msrch + "%'";
command = command +"\n"+"go"+"\n"+"select WBSCode,Description,TerritoryCode,AmountReleased,convert(varchar(25),CreatedOn,106) as CreatedOn,IsEnable from try1 where TerritoryCode in (select TerritoryCode from Territory where StateCode='" + mbcode + "')";
SqlCommand cmdd = new SqlCommand(command);
cmdd.Connection = con;
SqlDataAdapter da = new SqlDataAdapter(cmdd);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
mngwbsGV1.DataSource = dt;
mngwbsGV1.DataBind();
}
but the issue is i am getting an error in da.Fill(dt) that:
Incorrect syntax near ‘go’.
‘CREATE VIEW’ must be the first statement in a query batch.
Incorrect syntax near ‘go’.
But when I am running this in my SQL Server 2008 it’s running but not retrieving the data
What should I do?
You should be creating your view separately, e.g. during installation or version upgrade – using regular SQL scripts.
If you must do this in code – you need to do it this way:
and then you can select from it using this (use a parametrized query instead of concatenating together your SQL command to avoid SQL injection attacks and to improve performance!):
But then again: if you have such a simple select – what do you need a view for in the first place, especially if you just want to create it, select from it, and drop it again right away. Doesn’t make any sense at all ….