C# 用一列表示该表 数据表my_表; my_表=新数据表(“类别”); my_Table.Columns.Add(“CategoryId”,typeof(string)); //向表中添加数据 对于(int my_Cnt=50;my_Cnt
下面是C#console应用程序正确输出的快照 谢谢你的提问强> 我已经有一段时间没有用C语言编写代码了。但就像一辆自行车,不需要很长时间就能骑上。T-SQL示例使用SSMS 2012完成,C#程序使用VS 2013完成。最新和最伟大的C# 用一列表示该表 数据表my_表; my_表=新数据表(“类别”); my_Table.Columns.Add(“CategoryId”,typeof(string)); //向表中添加数据 对于(int my_Cnt=50;my_Cnt,c#,sql,sql-server,sql-server-2008,stored-procedures,C#,Sql,Sql Server,Sql Server 2008,Stored Procedures,下面是C#console应用程序正确输出的快照 谢谢你的提问 我已经有一段时间没有用C语言编写代码了。但就像一辆自行车,不需要很长时间就能骑上。T-SQL示例使用SSMS 2012完成,C#程序使用VS 2013完成。最新和最伟大的 晚安 在SQL server management studio中检查用户是否将默认数据库设置为您尝试访问的数据库。我也犯了同样的错误,被困了好几天。最后发现用户已将Master设置为其“默认数据库”。旧式连接让我痛苦地流泪。@Hogan-过去是,现在仍然是最糟糕
晚安 在SQL server management studio中检查用户是否将默认数据库设置为您尝试访问的数据库。我也犯了同样的错误,被困了好几天。最后发现用户已将
Master
设置为其“默认数据库”。旧式连接让我痛苦地流泪。@Hogan-过去是,现在仍然是最糟糕的情况的绝对缩影。@Hogan我如何才能将旧式连接转换为更高效的连接join@HotCoolStud-对效率或正确性不作任何要求——但要有可读性语法请看我的答案。可以这样写,但问题仍然没有解决。@hotcoolstub-您是否尝试过[DB\u user1212].[dbo].[CategoryIdArray]
?你到底给它起了什么名字?这只是一个命名/命名空间问题。我以与上面所述相同的方式命名了它,当我尝试[DB_user1212].[dbo].[CategoryIdArray]时,错误出现在类型名“DB_user1212.dbo.CategoryIdArray”包含的前缀数超过了最大值。最大值为1。@HotCoolStud-您检查了调用SP的用户的权限了吗?该用户有自定义类型的权限吗?如何检查它。很好的地方--此行也必须更改:dt_Categories.Columns.Add(“Category”,typeof(String))代码>非常好的解决方案,但没有人关注。哈哈努力。
CREATE TYPE [dbo].[CategoryIdArray] AS TABLE(
[CategoryId] [bigint] NULL
)
GO
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
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;
}
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'
workRow["Category"] = cat;
workRow["CategoryId"] = cat;
...
and c.[Category Id] in (
select CategoryId from @dt -- select from the actual parameter, not its TYPE
)
...
--
-- 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
--
-- 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
--
-- 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
//
// 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();
}
}
}