Safely query SQL table with variable table name - c#

I'm trying to make some common code for retrieving identities from tables and that involves making an unsafe query string to inject the table name.
I read everywhere that I cannot safely inject the table name. So I want to query if the table exists, then based on the result, perform a real or dummy query.
var unsafeTableQuery = "SELECT [Id] FROM [dbo].[" + tableName + "] WHERE [BulkInsertSessionID] = #bulkInsertSessionId";
var guardQuery =
"DECLARE #Exists BIT = ( SELECT CAST( COUNT(1) AS BIT ) FROM sys.tables WHERE name = #TableName AND type = 'U' );" +
"IF (#Exists = 0) SELECT TOP 0 NULL 'Id'" +
"ELSE " + unsafeTableQuery;
var cmd = new SqlCommand(guardQuery, conn, tran);
cmd.Parameters.Add(new SqlParameter("#TableName", tableName));
cmd.Parameters.Add(new SqlParameter("#bulkInsertSessionId", bulkInsertSessionId));
using (SqlDataReader reader = cmd.ExecuteReader())
{
int index = 0;
while (reader.Read())
{
int id = (int)reader[0];
entities[index++].Id = id;
}
}
Even though I have an unsafe concatenation, I'm first querying the table name against the sys.tables by a parameter. And if it doesn't exist, the IF..ELSE block will never step into the unsafe query.
For easier readability I'm expecting to run the following query:
DECLARE #Exists BIT = ( SELECT CAST( COUNT(1) AS BIT ) FROM sys.tables WHERE name = #TableName AND type = 'U' );
IF(#Exists = 0)
SELECT TOP 0 NULL 'Id'
ELSE
SELECT [Id] from <InjectedTableName> where BulkInsertSessionID = #bulkSessionId
Am I correct in my assumption that this is safe?

Suppose your users have an access to change the variable tableName. I suppose some user types it on some form. Suppose he types this:
Users]; DROP TABLE Users;--
Then your whole command will be:
DECLARE #Exists BIT = ( SELECT CAST( COUNT(1) AS BIT ) FROM sys.tables WHERE name = #TableName AND type = 'U' );
IF(#Exists = 0)
SELECT TOP 0 NULL 'Id'
ELSE
SELECT [Id] from [Users]; DROP TABLE Users;-- where BulkInsertSessionID = #bulkSessionId
This will do its IF ELSE part and then will go to next statement which is:
DROP TABLE Users;
Note that drop statement will execute in any case even if ELSE part is not executed, because you don't have BEGIN END. Note that the rest is commented out... This is most basic injection method...

Related

SQL update query in C# foreach loop

I want to run an UPDATE SQL query within a C# foreach loop, such as:
var alterQuery = $#"
IF NOT EXISTS(SELECT 1 FROM sys.columns WHERE Name = 'MyColumn' AND Object_ID = Object_ID('MyTable'))
ALTER TABLE MyTable
ADD [MyColumn] nvarchar(255)
";
using (var connection = myConnection)
{
connection.Execute(alterQuery);
foreach (var obj in myObjects)
{
var query = $#"UPDATE [MyTable]
SET [MyColumn] = '{obj.Val}'
WHERE [ID] = '{obj.ID}'
";
// note: my Execute method uses ExecuteNonQuery() behind the scenes
connection.Execute(query);
}
}
But, I receive the following SQL Exception. I receive it when there are two or more values in myObjects but not when there is only one:
Additional information: Column names in each table must be unique. Column name MyColumn in table MyTable is specified more than once.
I believe it may be due to the queries running simultaneously and trying to access the same column (MyColumn). Should I be running my queries in such a way that each must wait until the previous completes?
How can I successfully run these queries?
I solved this issue by adding BEGIN and END around my ALTER TABLE query.
Does not work:
IF NOT EXISTS(SELECT 1 FROM sys.columns WHERE Name = 'MyColumn' AND
Object_ID = Object_ID('MyTable'))
ALTER TABLE MyTable
ADD [MyColumn] nvarchar(255)
Works:
IF NOT EXISTS(SELECT 1 FROM sys.columns WHERE Name = 'MyColumn' AND
Object_ID = Object_ID('MyTable'))
BEGIN
ALTER TABLE MyTable
ADD [MyColumn] nvarchar(255)
END
I find it weird that in the non-working case, the only line that the IF NOT EXISTScheck controls is the ALTER TABLE MyTable line, rather than both the ALTER TABLE MyTable and the ADD [MyColumn] nvarchar(255) lines, which should be interpreted as one statement.

Unable to create dynamic sql query in asp.net C#

I am keep getting
Conversion failed when converting the varchar value '46434,15864' to data type int.
I have this texbox which accepts numeric and commas. I need to create query with emp_num in (46434,15864) like syntax.
The query generated from codebehind is this, which runs fine manually in sql server:
SELECT * -- column names
FROM [DBO].[tablename] LPR
WHERE LPR.[EMPLOYEE_NUMBER] in (46434,15864)
code:
if (txtEmpNum.Text.Trim() != "")
{
////sb.Append(" and LPR.[EMPLOYEE_NUMBER] like '%'+ #empnumber + '%' ");
sb.Append(" and LPR.[EMPLOYEE_NUMBER] in (#empnumber) ");
cmd.Parameters.Add("#empnumber", SqlDbType.VarChar).Value = txtEmpNum.Text.Trim(); //.Replace("," , "','");
}
cmd.CommandText = sb.ToString();
DataTable dt = GetData(cmd);
gvdetails.DataSource = dt;
gvdetails.DataBind();
Table:
You will have to parametrize every value. This way you'll have dynamically created query, but NOT prone to SQL Inject
Here's code:
//where IN part of your query
string inClause = "and LPR.[EMPLOYEE_NUMBER] in ({0})";
// string arrays for values and variables of your query
string[] paramValues = txtEmpNum.Text.Trim().Split(',');
string[] paramVars = paramValues.Select((s, i) => "#empNo" + i.ToString()).ToArray();
//create query, ie. and LPR.[EMPLOYEE_NUMBER] in (#empNo0, #empNo1...)
inClause = string.Format(inClause, string.Join(", ", paramVars));
//add vars and values to command
for (int i = 0; i < paramVars.Length; i++)
{
cmd.Parameters.Add(paramVars[i], SqlDbType.Int).Value = paramValues[i];
}
You need a split function to create a list from an string. You can create that function running this script once :
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[fnSplitString]
(
#string NVARCHAR(MAX),
#delimiter CHAR(1)
)
RETURNS #output TABLE(splitdata NVARCHAR(MAX)
)
BEGIN
set #delimiter = coalesce(#delimiter, dbo.cSeparador());
DECLARE #start INT, #end INT
SELECT #start = 1, #end = CHARINDEX(#delimiter, #string)
WHILE #start < LEN(#string) + 1 BEGIN
IF #end = 0
SET #end = LEN(#string) + 1
INSERT INTO #output (splitdata)
VALUES(SUBSTRING(#string, #start, #end - #start))
SET #start = #end + 1
SET #end = CHARINDEX(#delimiter, #string, #start)
END
RETURN
END
Now your query will be :
SELECT *
FROM [DBO].[tablename] LPR
WHERE LPR.[EMPLOYEE_NUMBER] in (select * from fnSplitString(#empnumber, ','))
You can call it from C# exactly the same way you called your original code.
Basically the error is saying that your variable #empnumber is varchar and LPR.[EMPLOYEE_NUMBER] is integer
You can just append the value of your textbox to your query.
Edit: As others have suggested, this would be prone to SQL Injection. Marc Guillot and Nino solutions are better.

C# ADO.net query runs slow

I have a query that .net builds and executes via ADO to Sql Server 2012. If ADO executes the query it times out waiting for the database to return but if I copy and past it into SQL Management studio and execute it against the same database it returns in less then a second.
I found that wrapping the query that ADO generates in ' storing it in a SQL variable and using SP_EXECUTESQL makes it run nice and fast. Why would there be a difference? I have not changed the query in any way.
Here is one of the queries it builds and executes (I left out all the code that dynamically builds the string that CommandText gets set to).
using(SqlConnection conn = ConnectionStringHelper.GetOpenConnection)
using(SqlCommand cmd = conn.CreateCommand)
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("agencyID", broadcastAgencyID);
cmd.Parameters.AddWithValue("tableName", mapping.TableName);
cmd.Parameters.AddWithValue("schemaName", mapping.SchemaName);
cmd.Parameters.AddWithValue("broadcastEntityMappingID", mapping.BroadcastEntityMappingID);
cmd.CommandText = #"SET NOCOUNT ON;
DECLARE #currentAgencyID NVARCHAR(MAX)
DECLARE #currentFacilityID NVARCHAR(MAX)
DECLARE #currentAgencyEntityBroadcastID INT
SELECT broadcastEntity.AgencyID, broadcastEntity.FacilityID
INTO #missingBroadcasts
FROM [Resource].[AgencyFacility] broadcastEntity
LEFT JOIN(
SELECT keys.AgencyID, keys.FacilityID
, record.BroadcastAgencyID
, record.AgencyEntityBroadcastID
FROM [Propagation].[AgencyEntityBroadcast] record
INNER JOIN (
SELECT AgencyEntityBroadcastID
,[AgencyID], [FacilityID]
FROM (
SELECT AgencyEntityBroadcastID
,ColumnName AS [PropagationColumnName]
,ColumnValue AS [PropagationColumnValue]
FROM Propagation.AgencyEntityBroadcastKeys
) Keys
PIVOT(MAX(PropagationColumnValue) FOR PropagationColumnName IN (
[AgencyID], [FacilityID]
)) pivoted
) keys ON keys.AgencyEntityBroadcastID = record.AgencyEntityBroadcastID
WHERE record.BroadcastAgencyID = #agencyID
AND record.BroadcastEntityMappingID = #broadcastEntityMappingID
) keys ON keys.BroadcastAgencyID = broadcastEntity.AgencyID
AND keys.AgencyID = broadcastEntity.AgencyID
AND keys.FacilityID = broadcastEntity.FacilityID
WHERE broadcastEntity.AgencyID = #agencyID
AND keys.AgencyEntityBroadcastID IS NULL
DECLARE entity_cursor CURSOR FOR
SELECT * FROM #missingBroadcasts
OPEN entity_cursor
FETCH NEXT FROM entity_cursor
INTO #currentAgencyID, #currentFacilityID
WHILE ##FETCH_STATUS = 0
BEGIN
INSERT INTO Propagation.AgencyEntityBroadcast(
BroadcastAgencyID,
BroadcastEntityMappingID,
BroadcastTypeID,
CreatedOn,
ModifiedOn
)
VALUES(
#agencyID,
#broadcastEntityMappingID,
1,
GETUTCDATE(),
GETUTCDATE()
)
SET #currentAgencyEntityBroadcastID = (SELECT SCOPE_IDENTITY())
INSERT INTO Propagation.AgencyEntityBroadcastKeys(
AgencyEntityBroadcastID,
ColumnName,
ColumnValue
) VALUES (
#currentAgencyEntityBroadcastID,
'AgencyID',
#currentAgencyID
)
INSERT INTO Propagation.AgencyEntityBroadcastKeys(
AgencyEntityBroadcastID,
ColumnName,
ColumnValue
) VALUES (
#currentAgencyEntityBroadcastID,
'FacilityID',
#currentFacilityID
)
FETCH NEXT FROM entity_cursor INTO #currentAgencyID, #currentFacilityID
END
CLOSE entity_cursor
DEALLOCATE entity_cursor
DROP TABLE #missingBroadcasts
SET NOCOUNT OFF;";
cmd.ExecuteNonQuery();
}
This kind of behaviour is usually caused by parameter sniffing problems. You can try with option recompile or optimize for unknown .
Option recompile
....
WHERE broadcastEntity.AgencyID = #agencyID
AND keys.AgencyEntityBroadcastID IS NULL
OPTION (RECOMPILE)
Optimize for unknown
.....
WHERE broadcastEntity.AgencyID = #agencyID
AND keys.AgencyEntityBroadcastID IS NULL
OPTION (OPTIMIZE FOR (#agencyID UNKNOWN, #broadcastEntityMappingID UNKNOWN))

Invalid object name 'dbo.CategoryIdArray'

My Motive is to pass long array of ID as parameter to stored procedure and select data on the basis of ID. So i created Type in SQL Server
CREATE TYPE [dbo].[CategoryIdArray] AS TABLE(
[CategoryId] [bigint] NULL
)
GO
and stored procedure
ALTER PROCEDURE [dbo].[GetNewestArticleByCatsPageWise]
#dt as [dbo].[CategoryIdArray] READONLY,
#PageIndex INT = 1
,#PageSize INT = 10
,#PageCount INT OUTPUT
AS
BEGIN
SET NOCOUNT ON;
SELECT ROW_NUMBER() OVER
(
ORDER BY [dateadded]
)AS RowNumber,[desid]
INTO #Results
FROM [DB_user1212].[dbo].[discussions] as d , [DB_user1212].[dbo].[CategoryMap] as c where d.desid=c.[Topic Id] and c.[Category Id] in (select CategoryId from [dbo].[CategoryIdArray]) and [TopicType]='1' order by [dateadded]
DECLARE #RecordCount INT
SELECT #RecordCount = COUNT(*) FROM #Results
SET #PageCount = CEILING(CAST(#RecordCount AS DECIMAL(10, 2)) / CAST(#PageSize AS DECIMAL(10, 2)))
PRINT #PageCount
SELECT * FROM #Results
WHERE RowNumber BETWEEN(#PageIndex -1) * #PageSize + 1 AND(((#PageIndex -1) * #PageSize + 1) + #PageSize) - 1
DROP TABLE #Results
END
Tried to use above stored procedure by Code below
public List<String> getNewestArticleByCategoryPageWise( long[] categoryId)
{
List<string> topicId= new List<string>();
try
{
DataTable dt_Categories = new DataTable();
dt_Categories.Columns.Add("Category", typeof(String));
DataRow workRow;
foreach(long cat in categoryId)
{
workRow = dt_Categories.NewRow();
workRow["Category"] = cat;
dt_Categories.Rows.Add(workRow);
}
int pageIndex = 1;
SqlCommand cmd = new SqlCommand("dbo.GetNewestArticleByCatsPageWise", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#PageIndex", pageIndex);
cmd.Parameters.AddWithValue("#PageSize", 10);
cmd.Parameters.Add("#PageCount", SqlDbType.Int, 4).Direction = ParameterDirection.Output;
SqlParameter tvparam = cmd.Parameters.AddWithValue("#dt", dt_Categories);
tvparam.SqlDbType = SqlDbType.Structured;
con.Open();
sdr= cmd.ExecuteReader();
while(sdr.Read())
{
topicId.Add(sdr.GetString(0));
}
con.Close();
}
catch(Exception ex)
{
con.Close();
throw ex;
}
return topicId;
}
When i run above function exception is thrown Invalid object name 'dbo.CategoryIdArray'. But i created it as type. Help me out what i missed out. I refferred this.
Problem is with this line in stored procedure is with this line
select CategoryId from [dbo].[CategoryIdArray] .
We can not select from type like this, we should use
select CategoryId from #dt
The first thing that I do when I get these questions is to create a sample database. The code below creates the following.
1 - database named [test]
2 - table named [Discussions]
3 - table named [CategoryMap]
4 - user defined table type named [CategoryIdArray]
5 - load the tables with 100 records of data
--
-- Create a test db
--
USE [master];
go
CREATE DATABASE [Test];
GO
--
-- Create the user defined type
--
USE [Test];
go
CREATE TYPE [CategoryIdArray] AS
TABLE
(
[CategoryId] [bigint] NULL
);
--
-- Create skelton tables
--
create table Discussions
(
dis_id int identity (1,1),
dis_name varchar(64),
dis_added_dte datetime default getdate()
);
go
create table CategoryMap
(
cat_id int identity(1,1),
cat_topic_id int,
cat_topic_type char(1)
);
go
-- clear tables
truncate table Discussions;
truncate table CategoryMap;
go
--
-- Create 100 rows of dummy data
--
declare #cnt int = 0;
while #cnt < 100
begin
insert into Discussions (dis_name)
values ('sample discussion record # ' + str(#cnt, 2, 0));
insert into CategoryMap (cat_topic_id, cat_topic_type)
values (#cnt+1, '1')
set #cnt = #cnt + 1;
end;
go
--
-- Show the sample data
--
select * from Discussions;
go
select * from CategoryMap;
go
The second step is to re-write the stored procedure. If you are using below 2012, go with a window function rownumber(). In 2012, the offset and fetch clauses of the order by were included for paging.
http://technet.microsoft.com/en-us/library/ms188385(v=sql.110).aspx
--
-- Create my procedure
--
create procedure [GetArticlesByPage]
#Tvp as [CategoryIdArray] READONLY,
#PageIndex INT = 1,
#PageSize INT = 10,
#PageCount INT OUTPUT
AS
BEGIN
-- Declare variables
DECLARE #var_recs int = 0;
DECLARE #var_offset int = 0;
-- Do not count the records
SET NOCOUNT ON;
-- Start of paging
SET #var_offset = #var_offset + ((#PageIndex - 1) * #PageSize);
-- Set page count variable
SELECT #var_recs = count(*)
FROM
[dbo].[Discussions] as d
JOIN
[dbo].[CategoryMap] as c
ON
d.dis_id = c.cat_topic_id
JOIN
#TVP a
ON
c.cat_id = a.CategoryId
WHERE
cat_topic_type = '1';
set #PageCount = ceiling(cast(#var_recs as real) / cast(#PageSize as real));
--
-- Return the record set
--
SELECT
dis_id
FROM
[dbo].[Discussions] as d
JOIN
[dbo].[CategoryMap] as c
ON
d.dis_id = c.cat_topic_id
JOIN
#TVP a
ON
c.cat_id = a.CategoryId
WHERE
cat_topic_type = '1'
ORDER BY
dis_added_dte
OFFSET #var_offset ROWS
FETCH NEXT #PageSize ROWS ONLY;
END;
GO
I did leave the page count in place; However, I do not think it is needed since you can repeat the call until the result set is empty.
Please do not dump the record set into a temporary table since it could be quite large if you were return all the columns to display. I choose two separate calls. One for a total count. One for a single page.
The last TSQL part is to test the stored procedure from SSMS.
--
-- Call the stored procedure
--
-- instantiate tvp
DECLARE #my_tvp as [CategoryIdArray];
DECLARE #my_page_cnt as int;
-- add 25 entries
declare #cnt int = 25;
while #cnt < 50
begin
insert into #my_tvp (CategoryId)
values (#cnt + 1);
set #cnt = #cnt + 1;
end;
-- show the data in the tvp
select * from #my_tvp
-- call the function
exec [GetArticlesByPage] #my_tvp, 1, 10, #PageCount = #my_page_cnt OUTPUT;
-- show the data in the output
select #my_page_cnt as 'my_pages';
go
In my test example, I wanted rows 26 to 50 paged as 10 rows. Result 1 is the 25 rows, Result 2 is the 10 rows that were paged, and Result 3 is how many pages. Therefore, the TSQL part of the solution is sound.
Stay tuned for a C# program debug session later tonight.
http://www.mssqltips.com/sqlservertip/2112/table-value-parameters-in-sql-server-2008-and-net-c/
Take a look at this post. It is doing exactly what you are trying to do.
Here are some ideas to try.
1 - Make sure the connection properties, login's default database is [Test] for my example.
2 - Is the type defined in the [Test] database? Please double check this.
3 - Is this correct? The column name is [CategoryId] in the database type. You have the following - [Category]. Try changing the name in the C# code.
dt_Categories.Columns.Add("Category", typeof(String));
4 - Remove the [dbo]. from the type in the SP. It is not in the example from MS SQL Tips. Might be confusing the issue. SQL server will resolve the name.
5 - I noticed the type is defined as big int but the id in the tables is int? Make sure the data types are consistent.
Please try these suggestions. Get back to me on how you make out.
Can you get me a detailed call stack trace and error message if this is still an issue??
So here is a C# console application that I promised.
It works as expected.
You were mixing up some ideas that are the foundation of ADO.NET and data tables. You should get used to looking at the immediate window and local variables. This will help you track down issues.
Here is my sample call to the Stored Procedure.
1 - Setup data table (50 to 74)
2 - Page the data by 5's
3 - Look at second page
//
// Good Ref. - http://msdn.microsoft.com/en-us/library/ms254937(v=vs.110).aspx
//
// Basic stuff from C# console app
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
// Required for data table
using System.Data;
using System.Data.SqlClient;
// Standard stuff ...
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
// Debug info
Console.WriteLine("Test - Start");
// Create the table with one column
DataTable my_Table;
my_Table = new DataTable("Category");
my_Table.Columns.Add("CategoryId", typeof(string));
// Add data to table
for (int my_Cnt = 50; my_Cnt < 75; my_Cnt++)
{
DataRow my_Row = my_Table.NewRow();
my_Row["CategoryId"] = my_Cnt.ToString();
my_Table.Rows.Add(my_Row);
}
// Debug info
Console.WriteLine("Test - created data set");
// Create a connection
SqlConnection my_Conn;
string str_Conn = "Server=localhost;Database=Test;Trusted_Connection=True;";
my_Conn = new SqlConnection(str_Conn);
// Debug info
Console.WriteLine("Test - create connection");
// Create the command and set its properties.
SqlCommand my_Cmd = new SqlCommand();
my_Cmd.Connection = my_Conn;
my_Cmd.CommandText = "dbo.GetArticlesByPage";
my_Cmd.CommandType = CommandType.StoredProcedure;
// Add parameter 0
SqlParameter my_Parm0 = new SqlParameter();
my_Parm0.ParameterName = "#Tvp";
my_Parm0.SqlDbType = SqlDbType.Structured;
my_Parm0.Direction = ParameterDirection.Input;
my_Parm0.Value = my_Table;
my_Cmd.Parameters.Add(my_Parm0);
// Add parameter 1
SqlParameter my_Parm1 = new SqlParameter();
my_Parm1.ParameterName = "#PageIndex";
my_Parm1.SqlDbType = SqlDbType.Int;
my_Parm1.Direction = ParameterDirection.Input;
my_Parm1.Value = 2;
my_Cmd.Parameters.Add(my_Parm1);
// Add parameter 2
SqlParameter my_Parm2 = new SqlParameter();
my_Parm2.ParameterName = "#PageSize";
my_Parm2.SqlDbType = SqlDbType.Int;
my_Parm2.Direction = ParameterDirection.Input;
my_Parm2.Value = 5;
my_Cmd.Parameters.Add(my_Parm2);
// Add parameter 3
SqlParameter my_Parm3 = new SqlParameter();
my_Parm3.ParameterName = "#PageCount";
my_Parm3.SqlDbType = SqlDbType.Int;
my_Parm3.Direction = ParameterDirection.Output;
my_Parm3.Value = 5;
my_Cmd.Parameters.Add(my_Parm3);
// Open the connection
my_Conn.Open();
// Debug info
Console.WriteLine("Test - execute reader");
// Execute the reader
SqlDataReader my_Reader = my_Cmd.ExecuteReader();
if (my_Reader.HasRows)
{
while (my_Reader.Read())
{
Console.WriteLine("{0}", my_Reader[0].ToString());
}
}
else
{
Console.WriteLine("No rows found.");
}
// Close the reader
my_Reader.Close();
// Number of pages (output after reader - order is important)
Console.WriteLine("Pages = ");
Console.WriteLine(my_Cmd.Parameters["#PageCount"].Value.ToString());
// Close the connection
my_Conn.Close();
// Debug info
Console.WriteLine("Test - close connection");
// Debug info
Console.WriteLine("Test - End");
// Pause to view output
Console.Read();
}
}
}
Here is a snapshot of the correct output from the C# console application.
I have to thank you for your question!
It has been a while since I coded in C#. But like a bike, does not take long to get back on it. The T-SQL examples were done with SSMS 2012 and the C# program was done with VS 2013. The latest and greatest.
Good nite!
I make no claim about efficient or correct -- but readable modern syntax your base query can be written like this:
SELECT ROW_NUMBER() OVER (ORDER BY [dateadded]) AS RowNumber,[desid]
INTO #Results
FROM [DB_user1212].[dbo].[discussions] as d
JOIN [DB_user1212].[dbo].[CategoryMap] as c ON d.desid=c.[Topic Id]
JOIN [dbo].[CategoryIdArray] arr ON c.[Category Id] = arr.CategoryID
WHERE [TopicType]='1'
Here is your solution:
In your stored procedure, in your WHERE statement, you are selecting * from a "TYPE" rather than the actual parameter object being passed in. It is like doing "SELECT * FROM VARCHAR", which makes no sense. Try this:
...
and c.[Category Id] in (
select CategoryId from #dt -- select from the actual parameter, not its TYPE
)
...
Instead of:
workRow["Category"] = cat;
use
workRow["CategoryId"] = cat;
Check in the SQL server management studio if the user has default database set to the database you're trying to access. I had the same type of error and got stuck for days. Finally found out the user had Master set as its' default DB.

Update a table from two comma separated parameter as input

I have a Gridview in front end where Grid have two columns : ID and Order like this:
ID Order
1 1
2 2
3 3
4 4
Now user can update the order like in front end Gridview:
ID Order
1 2
2 4
3 1
4 3
Now if the user click the save button the ID and order data is being sent to Stored Procedure as #sID = (1,2,3,4) and #sOrder = (2,4,1,3)
Now if I want to update the order and make save I want to store it into database. Through Stored procedure how can update into the table so that the table is updated and while select it gives me the results like:
ID Order
1 2
2 4
3 1
4 3
There is no built in function to parse these comma separated string. However, yo can use the XML function in SQL Server to do this. Something like:
DECLARE #sID VARCHAR(100) = '1,2,3,4';
DECLARE #sOrder VARCHAR(10) = '2,4,1,3';
DECLARE #sIDASXml xml = CONVERT(xml,
'<root><s>' +
REPLACE(#sID, ',', '</s><s>') +
'</s></root>');
DECLARE #sOrderASXml xml = CONVERT(xml,
'<root><s>' +
REPLACE(#sOrder, ',', '</s><s>') +
'</s></root>');
;WITH ParsedIDs
AS
(
SELECT ID = T.c.value('.','varchar(20)'),
ROW_NUMBER() OVER(ORDER BY (SELECT 1)) AS RowNumber
FROM #sIDASXml.nodes('/root/s') T(c)
), ParsedOrders
AS
(
SELECT "Order" = T.c.value('.','varchar(20)'),
ROW_NUMBER() OVER(ORDER BY (SELECT 1)) AS RowNumber
FROM #sOrderASXml.nodes('/root/s') T(c)
)
UPDATE t
SET t."Order" = p."Order"
FROM #tableName AS t
INNER JOIN
(
SELECT i.ID, p."Order"
FROM ParsedOrders p
INNER JOIN ParsedIDs i ON p.RowNumber = i.RowNumber
) AS p ON t.ID = p.ID;
Live Demo
Then you can put this inside a stored procedure or whatever.
Note that: You didn't need to do all of this manually, it should be some way to make this gridview update the underlying data table automatically through data binding. You should search for something like this instead of all this pain.
You could use a table valued parameter to avoid sending delimiter-separated values or even XML to the database. To do this you need to:
Declare a parameter type in the database, like this:
CREATE TYPE UpdateOrderType TABLE (ID int, Order int)
After that you can define the procedure to use the parameter as
CREATE PROCEDURE UpdateOrder (#UpdateOrderValues UpdateOrderType readonly)
AS
BEGIN
UPDATE t
SET OrderID = tvp.Order
FROM <YourTable> t
INNER JOIN #UpdateOrderValues tvp ON t.ID=tvp.ID
END
As you can see, the SQL is trivial compared to parsing XML or delimited strings.
Use the parameter from C#:
using (SqlCommand command = connection.CreateCommand()) {
command.CommandText = "dbo.UpdateOrder";
command.CommandType = CommandType.StoredProcedure;
//create a table from your gridview data
DataTable paramValue = CreateDataTable(orderedData)
SqlParameter parameter = command.Parameters
.AddWithValue("#UpdateOrderValues", paramValue );
parameter.SqlDbType = SqlDbType.Structured;
parameter.TypeName = "dbo.UpdateOrderType";
command.ExecuteNonQuery();
}
where CreateDataTable is something like:
//assuming the source data has ID and Order properties
private static DataTable CreateDataTable(IEnumerable<OrderData> source) {
DataTable table = new DataTable();
table.Columns.Add("ID", typeof(int));
table.Columns.Add("Order", typeof(int));
foreach (OrderData data in source) {
table.Rows.Add(data.ID, data.Order);
}
return table;
}
(code lifted from this question)
As you can see this approach (specific to SQL-Server 2008 and up) makes it easier and more formal to pass in structured data as a parameter to a procedure. What's more, you're working with type safety all the way, so much of the parsing errors that tend to crop up in string/xml manipulation are not an issue.
You can use charindex like
DECLARE #id VARCHAR(MAX)
DECLARE #order VARCHAR(MAX)
SET #id='1,2,3,4,'
SET #order='2,4,1,3,'
WHILE CHARINDEX(',',#id) > 0
BEGIN
DECLARE #tmpid VARCHAR(50)
SET #tmpid=SUBSTRING(#id,1,(charindex(',',#id)-1))
DECLARE #tmporder VARCHAR(50)
SET #tmporder=SUBSTRING(#order,1,(charindex(',',#order)-1))
UPDATE dbo.Test SET
[Order]=#tmporder
WHERE ID=convert(int,#tmpid)
SET #id = SUBSTRING(#id,charindex(',',#id)+1,len(#id))
SET #order=SUBSTRING(#order,charindex(',',#order)+1,len(#order))
END

Categories

Resources