How do I programmatically access data about my database? - c#

I'd like to access the list of tables and for each table report number of rows, disk space used, etc. It would be nice to get these details at the database level, too.
How do I do this programmatically?

Jason's answer above is good, but more generally. you're looking at Information Schema. Also Wikipedia's entry:
http://en.wikipedia.org/wiki/Information_schema

You can just open a connection and query the database:
using(var connection = new SqlConnection(connectionString)) {
connection.Open();
using(var command = connection.CreateCommand()) {
command.CommandText = "SELECT * FROM SYS.TABLES";
using(var reader = command.ExecuteReader()) {
while(reader.Read()) {
Console.WriteLine(reader["name"]);
}
}
}
}
You can Google for the query strings for the other information that you want.

Create a SqlConnection to your database and open the connection.
SqlConnection conn = new SqlConnection("Data Source=Servername;Initial Catalog=Marketing;Integrated Security=SSPI");
conn.Open();
Create a SqlCommand and assign the CommandText to the value of SQL you require.
SqlCommand cmd = new SqlCommand("PLACE SQL HERE", conn);
Tables and number of rows:
SELECT
[TableName] = so.name,
[RowCount] = MAX(si.rows)
FROM
sysobjects so,
sysindexes si
WHERE
so.xtype = 'U'
AND
si.id = OBJECT_ID(so.name)
GROUP BY
so.name
ORDER BY
2 DESC
Space used:
EXEC sp_spaceused 'tablename'

This script doesn't include schema names but gets you most of the information you want for the current database. I'm sure you can adapt it into a stored procedure.
SET NOCOUNT ON
GO
DECLARE #tblSpaceUsed TABLE
(
[name] sysname NOT NULL,
[rows] int NOT NULL,
[reserved] nvarchar(50) NOT NULL,
[reservedKB] int NULL,
[data] nvarchar(50) NOT NULL,
[dataKB] int NULL,
[index] nvarchar(50) NOT NULL,
[indexKB] int NULL,
[unused] nvarchar(50) NOT NULL,
[unusedKB] int NULL
)
DECLARE #tableName sysname
DECLARE #tableNames CURSOR
SET #tableNames = CURSOR
FAST_FORWARD
FOR
SELECT DISTINCT
ss.name + '.' + st.name
FROM
sys.tables st
INNER JOIN
sys.schemas ss
ON st.schema_id = ss.schema_id
OPEN #tableNames
FETCH NEXT FROM #tableNames INTO #tableName
WHILE ##FETCH_STATUS = 0
BEGIN
INSERT INTO #tblSpaceUsed ([name], [rows], [reserved], [data], [index], [unused]) EXEC sp_spaceused #tableName
FETCH NEXT FROM #tableNames INTO #tableName
END
CLOSE #tableNames
UPDATE
#tblSpaceUsed
SET
[reservedKB] = CONVERT(int, LEFT([reserved], LEN([reserved]) - 3)),
[dataKB] = CONVERT(int, LEFT([data], LEN([data]) - 3)),
[indexKB] = CONVERT(int, LEFT([index], LEN([index]) - 3)),
[unusedKB] = CONVERT(int, LEFT([unused], LEN([unused]) - 3))
SELECT
*
FROM
#tblSpaceUsed

Related

Return value from stored procedure to C# function

I am trying to count how many users is updated and how many users are inserted after I run my stored procedure.
CREATE PROCEDURE [dbo].[ADProcTemp]
#Username varchar(250),
#DisplayName varchar(70),
#isEnabled tinyint,
#PassNevExp tinyint,
#addedUser int OUTPUT,
#updatedUser int OUTPUT
AS
BEGIN
SET #addedUser = 0
SET #updatedUser = 0
IF NOT EXISTS (SELECT TOP 1 PrezimeIme FROM [dbo].[tblZaposleni_AD] WITH (NOLOCK)
WHERE NetworkLogin = #Username)
BEGIN
IF(#isEnabled = 1 OR #PassNevExp = 1)
INSERT INTO [dbo].[tblZaposleni_AD](NetworkLogin, PrezimeIme, Status, PassNevExp)
VALUES (#Username, #DisplayName, #isEnabled, #PassNevExp)
SET #addedUser = #addedUser + ##ROWCOUNT;
SELECT #addedUser As UkupnoDodanihKorisnika
END
ELSE
BEGIN
UPDATE [dbo].[tblZaposleni_AD]
SET Status = #isEnabled,
PassNevExp = #PassNevExp
WHERE NetworkLogin = #Username
AND (Status <> #isEnabled) OR (PassNevExp <>#PassNevExp)
SET #updatedUser = #updatedUser + ##ROWCOUNT;
SELECT #updatedUser As UkupnoIzmjenjenihKorisnika
END
END
Here is my stored procedure and right now I want in my C# code display #addedUser and #updatedUser variable from stored procedure.
So far I create this
public void ExcStrPrc(string Username, string DisplayName, bool isEnable, bool PassNevExp)
{
SqlConnection conn = new SqlConnection(#"Data Source=(LocalDb)\MSSQLLocalDB;Initial Catalog=DesignSaoOsig1;Integrated Security=True");
SqlCommand cmd = new SqlCommand("ADProcTemp", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Username", Username.ToString().Trim());
cmd.Parameters.AddWithValue("#DisplayName", DisplayName.ToString().Trim());
cmd.Parameters.AddWithValue("#isEnabled", Convert.ToInt32(isEnable));
cmd.Parameters.AddWithValue("#PassNevExp", Convert.ToInt32(PassNevExp));
cmd.Parameters.Add("#addedUser", SqlDbType.Int).Direction = ParameterDirection.Output;
cmd.Parameters.Add("#updatedUser", SqlDbType.Int).Direction = ParameterDirection.Output;
conn.Open();
int k = cmd.ExecuteNonQuery();
if (k != 0)
{
Console.WriteLine("Uspjesno izvrseno !");
}
Console.WriteLine("Ukupno novih korisnika {0}");
conn.Close();
}
Any idea how to display counter from stored procedure to C# function? I added inside my function and right now I didn't get any data in output...
TBH was a long time ago since I messed around with output parameters, but you add output parameters, but you never check those. The values you require should be in those parameters.
I suggest you try to get those values like (after the execution of course):
var addedUserCount = (int)cmd.Parameters["#addedUser"].Value;
Or something similar

Building a dynamic where clause in a stored procedure command

I have a stored procedure where the arguments looks like this
Create Procedure [dbo].[myStoredProcedure]
#TaskId int = 0
, #FileName varchar(200) =''
, #DataDtFrom smalldatetime = '01/01/1900'
, #DataDtTo smalldatetime = '01/01/1900'
, #OFFSET INT = 0
, #FETCH INT = 2000
, #WhereClauseString varchar(5000) = ''
SELECT
DataDt
,EffDt
,LoanNumber
,UploadDate
,UploadedFileName
FROM dbo.myFileTable u
WHERE
(#DataDtTo = '01/01/1900' or DataDt between #DataDtFrom and #DataDtTo)
and (#TaskId = 0 or TaskId = #TaskId)
and (#FileName = '' or UploadedFileName like '%' + #FileName + '%')
**Where ??? = #WhereClauseString**
ORDER BY u.UploadDate
OFFSET #OFFSET ROWS
FETCH NEXT #FETCH ROWS ONLY
I initialize this in C#
var whereClauseString = "LoanNum in(111,222,444) and TaskId in (123,456,789)";
using (var conn = new MyEntities().Database.Connection)
{
conn.Open();
var cmd = conn.CreateCommand();
cmd.CommandTimeout = 1800;
cmd.CommandText = model.UploadStoredProcedure;
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.Add(new System.Data.SqlClient.SqlParameter("#TaskId", Convert.ToInt64(model.TaskId)));
cmd.Parameters.Add(new System.Data.SqlClient.SqlParameter("#FileName", model.FileName ?? string.Empty));
cmd.Parameters.Add(new System.Data.SqlClient.SqlParameter("#DataDtFrom", DateTime.Parse(model.adjFromDataDt.ToShortDateString()) <= DateTime.Parse(basicDate.ToShortDateString()) ? basicDate : model.adjFromDataDt.Date));
cmd.Parameters.Add(new System.Data.SqlClient.SqlParameter("#DataDtTo", DateTime.Parse(model.adjToDataDt.ToShortDateString()) <= DateTime.Parse(basicDate.ToShortDateString()) ? basicDate : model.adjToDataDt.Date));
cmd.Parameters.Add(new System.Data.SqlClient.SqlParameter("#OFFSET", model.Page));
cmd.Parameters.Add(new System.Data.SqlClient.SqlParameter("#FETCH", model.PageSize));
**Dynamic Where clause** -->> System.Data.SqlClient.SqlParameter("#WhereClause", whereClauseString));
var da = new System.Data.SqlClient.SqlDataAdapter((System.Data.SqlClient.SqlCommand)cmd);
da.Fill(ds);
}
My question is it possible to build a dynamic where clause and pass it to the stored procedure and sort on the columns that are being referenced in the where clause?
How would I know which columns I need in the stored procedure that are being referenced in the where clause?
Would such a thing be possible with this stored Procedure and Entity Framework?
Anyway, if your DB is far from external attacks with SQL Injection you still can think in an easy solution based in Dinamic SQL, very often this way can solve quickly very complex problems otherwise:
CREATE Procedure [dbo].[myStoredProcedure]
#TaskId int = 0
, #FileName varchar(200) =''
, #DataDtFrom smalldatetime = '01/01/1900'
, #DataDtTo smalldatetime = '01/01/1900'
, #OFFSET INT = 0
, #FETCH INT = 2000
, #WhereClauseString varchar(5000) = ''
AS
BEGIN
DECLARE #SQL AS NVARCHAR(MAX);
SELECT #SQL = '
SELECT
DataDt
,EffDt
,LoanNumber
,UploadDate
,UploadedFileName
FROM dbo.myFileTable u
WHERE
('''+CONVERT(CHAR(10), #DataDtTo, 112)+''' = ''01/01/1900'' or DataDt between '''+CONVERT(CHAR(10), #DataDtFrom, 112)+''' and '''+CONVERT(CHAR(10), #DataDtTo, 112)+''')
and ('+CONVERT(CHAR(10), #TaskId)+' = 0 or TaskId = '+CONVERT(CHAR(10), #TaskId)+')
and ('+RTRIM(CONVERT(CHAR(100), #FileName))+' = '''' or UploadedFileName like ''%'+RTRIM(CONVERT(CHAR(100), #FileName))+'%'')
' +CONVERT(CHAR(100), #WhereClauseString)+'
ORDER BY u.UploadDate
OFFSET '+CONVERT(CHAR(10), #OFFSET)+' ROWS
FETCH NEXT '+CONVERT(CHAR(10), #FETCH)+' ROWS ONLY;
'
PRINT #SQL;
EXEC sp_ExecuteSQL #SQL;
END;

Search through all Database - Tables - Column Text for a string

Issue
We are in the process of changing a database name on our server, but the database is huge and we want to create a small application that will loop through all databases, and then all the tables in the databases and then all the columns in the tables for text that matches "LIVE".
Code
I started creating code but i feel like this way in clunky and is returning an error.
using (SqlConnection connection = new SqlConnection(#"data source="SERVER NAME";integrated security=false;uid="USER";password="PASSWORD";"))
{
connection.Open();
SqlCommand command = new SqlCommand(#"SELECT * FROM sys.databases", connection);
SqlDataReader reader = command.ExecuteReader();
try
{
while (reader.Read())
{
_databases.Add(string.Format("{0}", reader["name"]));
}
}
finally
{
reader.Close();
}
foreach (var database in _databases)
{
using (SqlConnection tableconnection = new SqlConnection(string.Format(#"data source="SERVER NAME";initial catalog=" + database + ";integrated security=false;uid="USERNAME";password="PASSWORD";")))
{
tableconnection.Open();
SqlCommand tablecommand = new SqlCommand(#"SELECT * FROM information_schema.tables", tableconnection);
SqlDataReader readertable = tablecommand.ExecuteReader();
try
{
while (readertable.Read())
{
_tables.Add(string.Format("{0}", readertable["TABLE_NAME"]));
}
}
finally
{
readertable.Close();
}
foreach (var tables in _tables)
{
SqlCommand columncommand = new SqlCommand(string.Format(#"SELECT * FROM INFORMATION_SCHEMA.COLUMNS where TABLE_Name=" + tables, tableconnection));
SqlDataReader readercolumn = columncommand.ExecuteReader();
try
{
while (readercolumn.Read())
{
_columns.Add(string.Format("{0}", readercolumn["COLUMN_NAME"]));
}
}
finally
{
readercolumn.Close();
}
}
}
}
}
As you can see I am unsure if this is the best way to do it. The code errors on:
SqlDataReader readercolumn = columncommand.ExecuteReader();
and the error is:
Additional information: ExecuteReader: Connection property has not been initialized.
Does anyone know what is going wrong or a simple way to do this?
You can use this for your problem :). :
CREATE PROCEDURE dbo.SearchAllDatabases
#SearchTerm NVARCHAR(255) = NULL
AS
BEGIN
SET NOCOUNT ON;
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
IF #SearchTerm IS NULL OR #SearchTerm NOT LIKE N'%[^%^_]%'
BEGIN
RAISERROR(N'Please enter a valid search term.', 11, 1);
RETURN;
END
CREATE TABLE #results
(
[database] SYSNAME,
[schema] SYSNAME,
[table] SYSNAME,
[column] SYSNAME,
ExampleValue NVARCHAR(1000)
);
DECLARE
#DatabaseCommands NVARCHAR(MAX) = N'',
#ColumnCommands NVARCHAR(MAX) = N'';
SELECT #DatabaseCommands = #DatabaseCommands + N'
EXEC ' + QUOTENAME(name) + '.sys.sp_executesql
#ColumnCommands, N''#SearchTerm NVARCHAR(MAX)'', #SearchTerm;'
FROM sys.databases
WHERE database_id > 4 -- non-system databases
AND[state] = 0-- online
AND user_access = 0; -- multi-user
SET #ColumnCommands = N'DECLARE #q NCHAR(1),
#SearchCommands NVARCHAR(MAX);
SELECT #q = NCHAR(39),
#SearchCommands = N''DECLARE #VSearchTerm VARCHAR(255) = #SearchTerm;'';
SELECT #SearchCommands = #SearchCommands + CHAR(10) + N''
SELECT TOP(1)
[db] = DB_NAME(),
[schema] = N'' + #q + s.name + #q + '',
[table] = N'' + #q + t.name + #q + '',
[column] = N'' + #q + c.name + #q + '',
ExampleValue = LEFT('' + QUOTENAME(c.name) + '', 1000)
FROM '' + QUOTENAME(s.name) + ''.'' + QUOTENAME(t.name) + ''
WHERE '' + QUOTENAME(c.name) + N'' LIKE #'' + CASE
WHEN c.system_type_id IN(35, 167, 175) THEN ''V''
ELSE '''' END + ''SearchTerm;''
FROM sys.schemas AS s
INNER JOIN sys.tables AS t
ON s.[schema_id] = t.[schema_id]
INNER JOIN sys.columns AS c
ON t.[object_id] = c.[object_id]
WHERE c.system_type_id IN (35, 99, 167, 175, 231, 239)
AND c.max_length >= LEN(#SearchTerm);
PRINT #SearchCommands;
EXEC sys.sp_executesql #SearchCommands,
N''#SearchTerm NVARCHAR(255)'', #SearchTerm;';
INSERT #Results
(
[database],
[schema],
[table],
[column],
ExampleValue
)
EXEC[master].sys.sp_executesql #DatabaseCommands,
N'#ColumnCommands NVARCHAR(MAX), #SearchTerm NVARCHAR(255)',
#ColumnCommands, #SearchTerm;
SELECT[Searched for] = #SearchTerm;
SELECT[database],[schema],[table],[column],ExampleValue
FROM #Results
ORDER BY[database],[schema],[table],[column];
END
GO
And use it like this :
exec SearchAllDatabases #SearchTerm = '%value%'
Or execute this stored procedure from your code.
using (SqlConnection connection = new SqlConnection(#"data source="SERVER NAME";integrated security=false;uid="USER";password="PASSWORD";"))
{
conn.Open();
// 1. create a command object identifying the stored procedure
SqlCommand cmd = new SqlCommand("SearchAllDatabases", conn);
// 2. set the command object so it knows to execute a stored procedure
cmd.CommandType = CommandType.StoredProcedure;
// 3. add parameter to command, which will be passed to the stored procedure
cmd.Parameters.Add(new SqlParameter("#SearchTerm", value));
cmd.ExecuteNonQuery();
}
Your code
SqlCommand columncommand = new SqlCommand(string.Format(#"SELECT * FROM INFORMATION_SCHEMA.COLUMNS where TABLE_Name=" + tables, tableconnection));
The end of the statement has )), putting table connection as a parameter for string.Format, which you dont use, so either, move it or...
You should have:
SqlCommand columncommand = new SqlCommand(#"SELECT * FROM INFORMATION_SCHEMA.COLUMNS where TABLE_Name=" + tables, tableconnection);

Insert, Update error: Subquery returned more than 1 row in C#

I have written a SQL script in stored procedure and query by C#.
But it throws an error:
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
As I know the problem is that the subquery is returning more than one row to the main query. May I know how to solve it? Thank you.
public void insertData(string TransID, string Item, string FromLocation, string Qty, string Requestor, string RefNum, string Remark, string ReasonID, string ReasonRemark, string CreateDate, string CreateUser, string ToLocation)
{
string constr = ConfigurationManager.ConnectionStrings["CIMProRPT01ConnectionString"].ConnectionString;
using (SqlConnection _cn = new SqlConnection(constr))
{
using (SqlCommand _cmd = new SqlCommand("MMSIssue_InsertOrUpdate", _cn))
{
using (SqlDataAdapter da = new SqlDataAdapter(_cmd))
{
_cn.Open();
_cmd.CommandType = CommandType.StoredProcedure;
_cmd.Parameters.AddWithValue("#INV_TRANS_ID", TransID);
_cmd.Parameters.AddWithValue("#INV_ID", Item);
_cmd.Parameters.AddWithValue("#INV_LOCATION", FromLocation);
_cmd.Parameters.AddWithValue("#INV_QTY", Qty);
_cmd.Parameters.AddWithValue("#INV_TRANS_REQUESTOR", Requestor);
_cmd.Parameters.AddWithValue("#INV_TRANS_REFNO", RefNum);
_cmd.Parameters.AddWithValue("#INV_TRANS_REMARK", Remark);
_cmd.Parameters.AddWithValue("#INV_REASON_ID", ReasonID);
_cmd.Parameters.AddWithValue("#INV_REASON_REMARK", ReasonRemark);
_cmd.Parameters.AddWithValue("#INV_CREATE_DATE", CreateDate);
_cmd.Parameters.AddWithValue("#INV_CREATE_USER", CreateUser);
_cmd.Parameters.AddWithValue("#INV_FROMLOC", ToLocation);
_cmd.Parameters.Add("#RecordFound", SqlDbType.Int, 0);
_cmd.Parameters["#RecordFound"].Direction = ParameterDirection.Output;
_cmd.ExecuteNonQuery();
string DeleteWMMRSQL = "DELETE FROM [CIMProRPT01].[dbo].[OTH_INV_QTY_LOC] WHERE INV_QTY = 0 OR INV_QTY is null OR INV_QTY <= '-1'";
SqlCommand cmd3 = new SqlCommand(DeleteWMMRSQL, _cn);
cmd3.ExecuteNonQuery();
_cn.Close();
float INV_QTY = Convert.ToInt32(_cmd.Parameters["#RecordFound"].Value.ToString());
if (INV_QTY == 2)
{
//QTY is more Than existing QTY !!");
Response.Write("QTY is more Than existing QTY !!");
Response.Redirect("MMS_LocationTrans.aspx");
}
else
{
//QTY not able to key in 0
Response.Write("QTY not able to key in 0!!");
}
}
}
}
}
Stored procedure:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[MMSIssue_InsertOrUpdate]
#INV_TRANS_ID VARCHAR(40),
#INV_ID VARCHAR(40),
#INV_LOCATION VARCHAR(40),
#INV_QTY FLOAT,
#INV_TRANS_REQUESTOR VARCHAR(40),
#INV_TRANS_REFNO VARCHAR(40),
#INV_TRANS_REMARK VARCHAR(255),
#INV_REASON_ID VARCHAR(40),
#INV_REASON_REMARK VARCHAR(255),
#INV_CREATE_DATE DATETIME,
#INV_CREATE_USER VARCHAR (255),
#INV_FROMLOC VARCHAR (40),
#RecordFound INT OUTPUT
AS
BEGIN
SET NOCOUNT ON;
IF EXISTS(SELECT * FROM OTH_INV_QTY_LOC
WHERE INV_ID = #INV_ID AND INV_LOCATION = #INV_LOCATION)
BEGIN
UPDATE OTH_INV_QTY_LOC
SET [INV_ID] = #INV_ID,
INV_LOCATION = #INV_LOCATION,
INV_QTY = INV_QTY - #INV_QTY
WHERE INV_ID = #INV_ID
AND INV_LOCATION = #INV_LOCATION
INSERT INTO OTH_INV_TRANSACTION (INV_TRANS_ID, INV_ID, INV_TRANS_LOCATION, INV_TRANS_QTY, INV_TRANS_REQUESTOR, INV_TRANS_REFNO, INV_TRANS_REMARK, INV_REASON_ID, INV_REASON_REMARK, INV_CREATE_DATE, INV_CREATE_USER, INV_FROMLOC)
VALUES (#INV_TRANS_ID, #INV_ID, #INV_LOCATION, #INV_QTY, #INV_TRANS_REQUESTOR, #INV_TRANS_REFNO, #INV_TRANS_REMARK, #INV_REASON_ID, #INV_REASON_REMARK, #INV_CREATE_DATE, #INV_CREATE_USER, #INV_FROMLOC)
DECLARE #InvFindQTY FLOAT
SET #InvFindQTY = (SELECT INV_QTY FROM OTH_INV_QTY_LOC)
IF #InvFindQTY >= #INV_QTY
BEGIN
SELECT #RecordFound = 2
END
ELSE
BEGIN
SELECT #RecordFound = 1
END
END
ELSE
BEGIN
SELECT #RecordFound = 0
END
END
The issue is with this line in the stored procedure:
DECLARE #InvFindQTY FLOAT
SET #InvFindQTY = ( SELECT INV_QTY FROM OTH_INV_QTY_LOC)
If you have more than one record in OTH_INV_QTY_LOC, you will receive this error.
It looks like you should be able to fix the problem by adding
WHERE INV_ID = #INV_ID
to ensure that only a single record is selected, i.e.:
SET #InvFindQTY = ( SELECT INV_QTY FROM OTH_INV_QTY_LOC WHERE INV_ID = #INV_ID)

How to get SQL String Result from Stored Procedure and save it in C# Windows Application string variable

I have the following Stored Procedure :
ALTER PROCEDURE [dbo].[ProcedureName]
#date NVARCHAR(50)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #result nvarchar(500) -- this one should return string.
DECLARE #variable1 NVARCHAR(50)
set #variable1 = (SELECT COUNT(*) FROM dbo.Table1 WHERE column1 not in (select column1 from dbo.Table2))
DECLARE #variable2 NVARCHAR(50)
update dbo.Table1 set columnX = 1 where column1 not in (select column1 from dbo.Table2)
set #variable2 = ##ROWCOUNT
and so on... it continues like 200 rows of script with at least 10-12 variables
after that I want to get result like this
'Hello,' +
'Some Text here' +
#date +': ' +
'Explaining text for variable1- ' + #variable1 +
'Updated rows from variable2 - ' + #variable2 +
'some other select count - ' + #variable3 +
'some other update rowcount - '+ #variable4
......
till now i was able to get this with PRINT Statement, but can't take it to variable in my C# code which goes like this:
public void Execute_Click(object sender, EventArgs e)
{
if (MessageBox.Show("Are you sure you want to execute the program?", "Confirm Start", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.No)
{
string connectionString = GetConnectionString(usernamePicker.Text, passwordPicker.Text);
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand("dbo.ProcedureName", connection))
{
connection.Open();
cmd.CommandText = "dbo.ProcedureName";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#date", SqlDbType.VarChar).Value = dateTimePicker1.Text;
SqlParameter result = cmd.Parameters.Add("#result", SqlDbType.VarChar);
result.Direction = ParameterDirection.ReturnValue;
cmd.ExecuteScalar();
var resultout = (string)cmd.Parameters["#result"].Value;
connection.Close();
TextMessage.Text = dateTimePicker1.Text;
}
}
}
}
all i get for result is 0 or NULL or etc.
i tried to return value from SQL with PRINT, RETURN, SET, OUTPUT ....... but nothing seems to work. However fetching variable from C# to SQL seems like child-work. Any ideas?
If you want to return the concatenate string as output then at the end of the procedure just write select #result. Make sure that you have concatenated it before this statement.
This will return you the string which you can use in your c# code as a string.
Change your stored procedure to this:
ALTER PROCEDURE [dbo].[ProcedureName]
#date NVARCHAR(50),
#variable1 NVARCHAR(50) output,
#variable2 NVARCHAR(50) output
AS
BEGIN
SET NOCOUNT ON;
DECLARE #result nvarchar(500) -- this one should return string.
set #variable1 = (SELECT COUNT(*) FROM dbo.Table1 WHERE column1 not in (select column1 from dbo.Table2))
update dbo.Table1 set columnX = 1 where column1 not in (select column1 from dbo.Table2)
set #variable2 = ##ROWCOUNT
and modify your code like this:
SqlParameter result1 = cmd.Parameters.Add("#variable1", SqlDbType.VarChar);
result1.Direction = ParameterDirection.ReturnValue;
SqlParameter result2 = cmd.Parameters.Add("#variable2", SqlDbType.VarChar);
result2.Direction = ParameterDirection.ReturnValue;
ok lets say I did this procedure
ALTER PROCEDURE [dbo].[ProcedureName]
#date NVARCHAR(50),
#result nvarchar(500) output
AS
BEGIN
SET NOCOUNT ON;
DECLARE #variable1 NVARCHAR(50)
set #variable1 = (SELECT COUNT(*) FROM dbo.Table1 WHERE column1 not in (select column1 from Table2))
set #result = #variable1 + ' some text '
i want "#result" to be output text from procedure and get it with C#

Categories

Resources