我在SQL中有一个简单的表(MyEmail),其中包含一些需要发送的电子邮件,例如:
ID Email
1 name@yahoo.com
2 something2@yahoo.com
3 name3@google.com
4 something4@yahoo.com
我制作了一个存储过程(GetAddress)来收集它们,以便以后可以将它们存储到变量中:
SELECT Email
FROM dbo.MyEmai
我需要代码的C#部分的帮助:
SqlCommand cmdMyEmails = new SqlCommand("GetAddress", connection);
cmdMyEmails.CommandType = CommandType.StoredProcedure;
var MyEmails = (string)cmdMyEmails.ExecuteScalar();
此代码仅返回一行,我需要从表中选择所有行并将其存储到MyEmails变量中。
我尝试了类似的方法,但是还是没有运气:
var MyEmails = (cmdMyEmails.ExecuteReader()).ToString();
有人可以帮我吗? 我需要选择所有行并将其存储到MyEmails变量中。
谢谢!
答案 0 :(得分:2)
如您在此msdn tutorial
中所见 The present element is 0
The previous list is [0]
The present element is 1
The previous list is [0, 1]
The present element is 2
The previous list is [0, 1, 2]
The present element is 3
The previous list is [0, 1, 2, 3]
The present element is 4
The previous list is [0, 1, 2, 3, 4]
The present element is 5
The previous list is [1, 2, 3, 4, 5]
您可能想使用these methods中的任何一个:
var MyEmails= new List<Email>(); //I suposse MyEmails is a List of Email as an example
SqlCommand command = new SqlCommand(queryString, connection);
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
MyEmails.Add(new Email(){email=reader[0].ToString()}); // as an example
}
//如果知道列0是包含电子邮件的列。reader[0].ToString();
//电子邮件是查询结果的列名称答案 1 :(得分:1)
只需在其中使用datatable填充数据并执行ExecuteReader()
DataTableresult = new DataTable();
SqlCommand cmdMyEmails = new SqlCommand("GetAddress", connection);
cmdMyEmails.CommandType = CommandType.StoredProcedure;
result.Load(cmd.ExecuteReader());
已更新
u可以使用SqlDataAdapter填充数据集
DataSet ds = new DataSet();
SqlCommand cmdMyEmails = new SqlCommand("GetAddress", connection);
cmdMyEmails.CommandType = CommandType.StoredProcedure;
SqlDataAdapter sda = new SqlDataAdapter()
sda.SelectCommand = cmd;
sda.Fill(ds);
或使用阅读器获取数据
SqlCommand cmdMyEmails = new SqlCommand("GetAddress", connection);
cmdMyEmails.CommandType = CommandType.StoredProcedure;
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
string Emailid = reader["Email"].ToString();
}
答案 2 :(得分:0)
只需使用此语句更改您的SQL语句,您就已经将所有地址作为单个值获取,并以';'分隔,因此您无需更改C#代码的一行:
void pop()
如果您使用的SQL版本早于SQL Server 2017,则string_agg函数不可用,因此您需要使用此技巧(使用XML内置函数):
template <typename Traversal, typename T, typename Container>
struct GraphNeighbors;
template<typename T, typename Container=std::deque<T>>
struct GraphNeighbors<class FIFO, T, Container>
{
private:
std::queue<T, Container> nodes;
public:
T pop()
{
T elem = std::move(nodes.front());
nodes.pop();
return elem;
}
void push(const T & elem)
{
nodes.push(elem);
}
void push(T&& elem)
nodes.emplace(std::move(elem));
}
};
template<typename T, typename Container=std::deque<T>>
struct GraphNeighbors<class LIFO, T, Container>
{
private:
std::stack<T, Container> nodes;
public:
T pop()
{
T elem = std::move(nodes.top());
nodes.pop();
return elem;
}
void push(const T & elem)
{
nodes.push(elem);
}
void push(T&& elem)
nodes.emplace(std::move(elem));
}
};