Stored Procedure giving different result on same database with same argument - c#

I have a stored procedure which gives different result in only a specific case.
When I call it from SQL Server Management Studio 2008 R2, it gives me 0 as output.
When I call it from C# class file. It gives me 1 as output.
I am using edmx file, and it is updated for sure.
The call is something like below from SSMS [SQL Server Management Studio]
exec proc_GetPrimaryKeyUsageCount 62, 'tblFormula'
This gives output as 0
The same stored procedure is called from C# file is like below
_db.GetPrimaryKeyUsageCount(62, "tblFormula");
This gives output as 1
The stored procedure is
CREATE PROCEDURE proc_GetPrimaryKeyUsageCount (
#PrimaryKeyColumnId INT
,#PrimaryKeyTable NVARCHAR(max)
--,#Response INT OUTPUT
)
AS
BEGIN
DECLARE #counter INT
DECLARE #sqlCommand NVARCHAR(max)
DECLARE #ForeignKey TABLE (
child_table VARCHAR(max)
,child_fk_column VARCHAR(max)
)
DECLARE #child_table VARCHAR(max)
DECLARE #child_fk_column VARCHAR(max)
SET #counter = 0
INSERT INTO #ForeignKey
SELECT child_table = c.TABLE_NAME
,child_fk_column = c.COLUMN_NAME
FROM INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE p
INNER JOIN INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS pc ON pc.UNIQUE_CONSTRAINT_SCHEMA = p.CONSTRAINT_SCHEMA
AND pc.UNIQUE_CONSTRAINT_NAME = p.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE c ON c.CONSTRAINT_SCHEMA = pc.CONSTRAINT_SCHEMA
AND c.CONSTRAINT_NAME = pc.CONSTRAINT_NAME
WHERE EXISTS (
SELECT 1
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME = 'IsDeleted'
AND TABLE_SCHEMA = p.TABLE_SCHEMA
AND TABLE_NAME = p.TABLE_NAME
AND p.TABLE_NAME = #PrimaryKeyTable
)
DECLARE db_cursor CURSOR
FOR
SELECT child_table
,child_fk_column
FROM #ForeignKey
OPEN db_cursor
FETCH NEXT
FROM db_cursor
INTO #child_table
,#child_fk_column
WHILE ##FETCH_STATUS = 0
BEGIN
PRINT 'select count(*) from ' + CAST(#child_table AS VARCHAR) + ' where ' + CAST(#child_fk_column AS VARCHAR) + ' = ' + CAST(#PrimaryKeyColumnId AS VARCHAR)
SET #sqlCommand = 'select #cnt=count(*) from ' + CAST(#child_table AS VARCHAR) + ' where ' + CAST(#child_fk_column AS VARCHAR) + ' = ' + CAST(#PrimaryKeyColumnId AS VARCHAR)
EXEC sp_executesql #sqlCommand
,N'#cnt int OUTPUT'
,#cnt = #counter OUTPUT
IF #counter > 0
BREAK
FETCH NEXT
FROM db_cursor
INTO #child_table
,#child_fk_column
END
SELECT #counter AS [PrimaryKeyUsageCount]
END
1st argument is Id of the primary key and 2nd argument is the name of the table having that primary key.
The Procedure returns the count of the usage of primary key in other tables in same database. If it finds even 1 occurrence, it will return that count otherwise 0.
If anything extra is needed please do let me know.

There are couple of mistakes, which could cause the problem.
The INSERT should be like that:
INSERT INTO #ForeignKey
SELECT c.TABLE_NAME,c.COLUMN_NAME
FROM INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE p
INNER JOIN INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS pc ON pc.UNIQUE_CONSTRAINT_SCHEMA = p.CONSTRAINT_SCHEMA
AND pc.UNIQUE_CONSTRAINT_NAME = p.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE c ON c.CONSTRAINT_SCHEMA = pc.CONSTRAINT_SCHEMA
AND c.CONSTRAINT_NAME = pc.CONSTRAINT_NAME
WHERE EXISTS (
SELECT *
FROM INFORMATION_SCHEMA.COLUMNS AS isc
WHERE isc.COLUMN_NAME = 'IsDeleted'
AND isc.TABLE_SCHEMA = p.TABLE_SCHEMA
AND isc.TABLE_NAME = p.TABLE_NAME
AND p.TABLE_NAME = #PrimaryKeyTable
)
After cursor loop shoud be:
CLOSE db_cursor
DEALLOCATE db_cursor

Related

SqlCommand Parameters.AddWithValue return # instead of variable [duplicate]

I am trying to execute this query:
declare #tablename varchar(50)
set #tablename = 'test'
select * from #tablename
This produces the following error:
Msg 1087, Level 16, State 1, Line 5
Must declare the table variable "#tablename".
What's the right way to have the table name populated dynamically?
For static queries, like the one in your question, table names and column names need to be static.
For dynamic queries, you should generate the full SQL dynamically, and use sp_executesql to execute it.
Here is an example of a script used to compare data between the same tables of different databases:
Static query:
SELECT * FROM [DB_ONE].[dbo].[ACTY]
EXCEPT
SELECT * FROM [DB_TWO].[dbo].[ACTY]
Since I want to easily change the name of table and schema, I have created this dynamic query:
declare #schema sysname;
declare #table sysname;
declare #query nvarchar(max);
set #schema = 'dbo'
set #table = 'ACTY'
set #query = '
SELECT * FROM [DB_ONE].' + QUOTENAME(#schema) + '.' + QUOTENAME(#table) + '
EXCEPT
SELECT * FROM [DB_TWO].' + QUOTENAME(#schema) + '.' + QUOTENAME(#table);
EXEC sp_executesql #query
Since dynamic queries have many details that need to be considered and they are hard to maintain, I recommend that you read: The curse and blessings of dynamic SQL
Change your last statement to this:
EXEC('SELECT * FROM ' + #tablename)
This is how I do mine in a stored procedure. The first block will declare the variable, and set the table name based on the current year and month name, in this case TEST_2012OCTOBER. I then check if it exists in the database already, and remove if it does. Then the next block will use a SELECT INTO statement to create the table and populate it with records from another table with parameters.
--DECLARE TABLE NAME VARIABLE DYNAMICALLY
DECLARE #table_name varchar(max)
SET #table_name =
(SELECT 'TEST_'
+ DATENAME(YEAR,GETDATE())
+ UPPER(DATENAME(MONTH,GETDATE())) )
--DROP THE TABLE IF IT ALREADY EXISTS
IF EXISTS(SELECT name
FROM sysobjects
WHERE name = #table_name AND xtype = 'U')
BEGIN
EXEC('drop table ' + #table_name)
END
--CREATES TABLE FROM DYNAMIC VARIABLE AND INSERTS ROWS FROM ANOTHER TABLE
EXEC('SELECT * INTO ' + #table_name + ' FROM dbo.MASTER WHERE STATUS_CD = ''A''')
Use:
CREATE PROCEDURE [dbo].[GetByName]
#TableName NVARCHAR(100)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
DECLARE #sSQL nvarchar(500);
SELECT #sSQL = N'SELECT * FROM' + QUOTENAME(#TableName);
EXEC sp_executesql #sSQL
END
You can't use a table name for a variable. You'd have to do this instead:
DECLARE #sqlCommand varchar(1000)
SET #sqlCommand = 'SELECT * from yourtable'
EXEC (#sqlCommand)
You'll need to generate the SQL content dynamically:
declare #tablename varchar(50)
set #tablename = 'test'
declare #sql varchar(500)
set #sql = 'select * from ' + #tablename
exec (#sql)
Use sp_executesql to execute any SQL, e.g.
DECLARE #tbl sysname,
#sql nvarchar(4000),
#params nvarchar(4000),
#count int
DECLARE tblcur CURSOR STATIC LOCAL FOR
SELECT object_name(id) FROM syscolumns WHERE name = 'LastUpdated'
ORDER BY 1
OPEN tblcur
WHILE 1 = 1
BEGIN
FETCH tblcur INTO #tbl
IF ##fetch_status <> 0
BREAK
SELECT #sql =
N' SELECT #cnt = COUNT(*) FROM dbo.' + quotename(#tbl) +
N' WHERE LastUpdated BETWEEN #fromdate AND ' +
N' coalesce(#todate, ''99991231'')'
SELECT #params = N'#fromdate datetime, ' +
N'#todate datetime = NULL, ' +
N'#cnt int OUTPUT'
EXEC sp_executesql #sql, #params, '20060101', #cnt = #count OUTPUT
PRINT #tbl + ': ' + convert(varchar(10), #count) + ' modified rows.'
END
DEALLOCATE tblcur
You need to use the SQL Server dynamic SQL:
DECLARE #table NVARCHAR(128),
#sql NVARCHAR(MAX);
SET #table = N'tableName';
SET #sql = N'SELECT * FROM ' + #table;
Use EXEC to execute any SQL:
EXEC (#sql)
Use EXEC sp_executesql to execute any SQL:
EXEC sp_executesql #sql;
Use EXECUTE sp_executesql to execute any SQL:
EXECUTE sp_executesql #sql
Declare #tablename varchar(50)
set #tablename = 'Your table Name'
EXEC('select * from ' + #tablename)
Also, you can use this...
DECLARE #SeqID varchar(150);
DECLARE #TableName varchar(150);
SET #TableName = (Select TableName from Table);
SET #SeqID = 'SELECT NEXT VALUE FOR ' + #TableName + '_Data'
exec (#SeqID)
Declare #fs_e int, #C_Tables CURSOR, #Table varchar(50)
SET #C_Tables = CURSOR FOR
select name from sysobjects where OBJECTPROPERTY(id, N'IsUserTable') = 1 AND name like 'TR_%'
OPEN #C_Tables
FETCH #C_Tables INTO #Table
SELECT #fs_e = sdec.fetch_Status FROM sys.dm_exec_cursors(0) as sdec where sdec.name = '#C_Tables'
WHILE ( #fs_e <> -1)
BEGIN
exec('Select * from ' + #Table)
FETCH #C_Tables INTO #Table
SELECT #fs_e = sdec.fetch_Status FROM sys.dm_exec_cursors(0) as sdec where sdec.name = '#C_Tables'
END

SQL Geo-Spatial Linked Server Query

I have one question on the TSQL Linked Server Query. Linked Server is GIS enforced so we pass the coordinates to that server which it returns the data from the Linked Server. Please find the below-working query.
DECLARE #input varchar(max), #sql varchar(max);
SET #input = N'((-119.470830216356 46.2642458295079,-119.470722927989 46.2642050348762,-119.470076515615 46.2647075484513,-119.470240130371 46.2647075484512,-119.470830216356 46.2642458295079))'
BEGIN
SELECT #sql = 'select * from openquery([LinkedServerName],''DECLARE #b geometry;
SET #b = geometry::STGeomFromText(''''POLYGON '+ #input + ' '''', 4326);
SET #b = #b.MakeValid();
SELECT * from [Database].[Table] AS b
where b.Shape.STIntersects(#b.STCentroid()) = 1'')'
END
EXEC(#sql)
But the issue is sometimes we have to pass more than 8000 characters to the input parameter #input since it is varchar(max) and EXEC command both have an 8000 character limitation. So we are trying to get rid of Dynamic SQL so that we can pass the input using 2 input variables (We have implemented splitting the input into subsets each of 8000 characters in our C# code and sending them as 2 different inputs to the SQL Query). We have tried the below query in the Actual Server (Linked Server) which is working fine.
DECLARE #b geometry
SET #input = N'((-119.470830216356 46.2642458295079,-119.470722927989 46.2642050348762,'
SET #input2 = N'-119.470076515615 46.2647075484513,-119.470240130371 46.2647075484512,-119.470830216356 46.2642458295079))'
SELECT #b = geometry::STGeomFromText('POLYGON ' + #input + #input2 + '', 4326)
SELECT #b = #b.MakeValid()
SELECT * FROM [Database].[TableName] AS b
WHERE b.Shape.STIntersects(#b.STCentroid()) = 1
We tried below SQL Linked query in our local server but it is throwing below error
DECLARE #input varchar(max), #input2 varchar(max);
SET #input = N'((-119.470830216356 46.2642458295079,-119.470722927989 46.2642050348762,'
SET #input2 = N'-119.470076515615 46.2647075484513,-119.470240130371 46.2647075484512,-119.470830216356 46.2642458295079))'
SELECT * FROM OPENQUERY([LinkedServerName],
'DECLARE #b geometry;
SELECT #b = geometry::STGeomFromText(''''POLYGON ' + #input + #input2 + '' ', 4326);
SELECT #b = #b.MakeValid();
SELECT * FROM [DatabaseName].[TableName] AS b
where b.Shape.STIntersects(#b.STCentroid()) = 1') AS AD
In the above query, an issue has been highlighted in the attached image.
Help is really appreciated.

Return value from one stored procedure to another

I want to use the return value from one stored procedure to another stored procedure. I was searching on the internet and try several solutions, but all of them are not working, I don't know what the mistake I make.
The stored procedure that I want to use its return value is:
CREATE PROCEDURE dbo.pro_ForeignKeyCheck
(#tableName VARCHAR(100),
#columnName VARCHAR(100),
#idValue INT)
AS BEGIN
SET NOCOUNT ON
DECLARE fksCursor CURSOR FAST_FORWARD FOR
SELECT
tc.table_name, ccu.column_name
FROM
information_schema.table_constraints tc
JOIN
information_schema.constraint_column_usage ccu ON tc.constraint_name = ccu.constraint_name
JOIN
information_schema.referential_constraints rc ON tc.constraint_name = rc.constraint_name
JOIN
information_schema.table_constraints tc2 ON rc.unique_constraint_name = tc2.constraint_name
JOIN
information_schema.constraint_column_usage ccu2 ON tc2.constraint_name = ccu2.constraint_name
WHERE
tc.constraint_type = 'Foreign Key'
AND tc2.table_name = #tableName
AND ccu2.column_name = #columnName
ORDER BY
tc.table_name
DECLARE #fkTableName VARCHAR(100),
#fkColumnName VARCHAR(100),
#fkFound BIT,
#params NVARCHAR(100),
#sql NVARCHAR(500)
OPEN fksCursor
FETCH NEXT FROM fksCursor INTO #fkTableName, #fkColumnName
SET #fkFound = 0
SET #params = N'#fkFound BIT OUTPUT'
WHILE ##fetch_status = 0 AND COALESCE(#fkFound, 0) <> 1
BEGIN
SELECT #sql = 'set #fkFound = (select top 1 1 from [' + #fkTableName + '] where [' + #fkColumnName + '] = ' + cast(#idValue as varchar(10)) + ')'
PRINT #sql
EXEC sp_executesql #sql, #params, #fkFound OUTPUT
FETCH NEXT FROM fksCursor INTO #fkTableName, #fkColumnName
END
CLOSE fksCursor
DEALLOCATE fksCursor
SELECT COALESCE(#fkFound, 0)
RETURN 0
END
and this use to check if the primary key value used in all child tables, we call it like this
EXECUTE pro_ForeignKeyCheck 'tablename','columnName', 1
or
EXECUTE pro_ForeignKeyCheck #tablename = 'tablename', #columnName = 'columnName', #idValue = 1
and it will work, but I cannot use the return value in other stored procedure
CREATE PROCEDURE [dbo].[pro_Delete_acount]
#UserID int,
#Action NVARCHAR(10)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #count int , #ErrNo int , #ErrMsg varchar(2000), #exit int
set #exit=0
if #Action ='ADMIN'
begin
/*---------Call Store Procedure pro_ForeignKeyCheck to check if there is value are exit in child table*/
--EXEC #exit = pro_ForeignKeyCheck1 #tablename='tb_M_admin',#columnName='admin_id',#idValue= #UserID
--select #exit
--EXEC #exit = pro_ForeignKeyCheck #tablename='tb_M_admin',#columnName='admin_id',#idValue= 1
EXEC #exit = pro_ForeignKeyCheck 'tb_M_admin','admin_id', 0
--select #exit
select -2[Ret_Status],#exit[ErrNo],0[ErrMsg] -- test
end
end
Could anyone help me with that?
Thanks all
Add
#Status int OUTPUT
in the pro_ForeignKeyCheck so it starts with
CREATE PROCEDURE dbo.pro_ForeignKeyCheck1
#tableName VARCHAR(100),
#columnName VARCHAR(100),
#idValue int,
#Status int OUTPUT
and at the end of it did as follow
--select coalesce(#fkFound,0)
select #Status = coalesce(#fkFound,0)
--return 0
stop the last to line and add new one
In the other stored procedure, call it as follows
EXEC pro_ForeignKeyCheck1 'tb_M_admin','admin_id', 0 ,#exit output
select #exit
and now the return value will be used.
Thanks to all
EXEC #exit = pro_ForeignKeyCheck 'tb_M_admin','admin_id', 0
---
select coalesce(#fkFound,0)
return 0 --< this will be assigned to #exit
replace this code with
return IsNull(#fkFound, 0)
You may leave select for other purposes but it cannot affect RETURN value. So you may remove it either.
This is oversimplified example of call of one SP from another. I hope it will give you some ideas.
create procedure dbo.first_proc
#bd datetime,
#d int output
as
select #d= DATEDIFF(day,#bd,getdate())
go
create procedure dbo.sec_proc
#birthday datetime
as
declare #days int
exec dbo.first_proc #birthday, #days output
select 'you live '+cast(#days as varchar) + ' days' result
go
exec dbo.sec_proc '1959-09-17'

Entity Framework Conditional Left Join and Custom Column Select

I have a stored procedure which results in lots of data. and also want to convert this to EF
unable to figure out how to join to the relavent tables when an attribute is present for the system. and also the column selection is very dynamic in nature,
I could take this sql and execute this directly and get things sorted that way but would miss but the grid in the front end wont be able to handle 600mb of data thrown from the database.
so need paging thought can do this better with EF.
for reference purpose I have the following sql below.
Declare #SQL varchar(max);
Declare #SelectColumns VARCHAR(MAX)
SELECT DISTINCT #SelectColumns= STUFF((SELECT ',''' + [PrimaryDataSource] + ''' Golden'
+ ISNULL(CASE WHEN System1 IS NOT NULL THEN ', System1.' + QUOTENAME([System1]) + ' System1' END, '')
+ ISNULL(CASE WHEN System2 IS NOT NULL THEN ', System2.' + QUOTENAME([System2]) + ' System2' END, '')
+ ISNULL(CASE WHEN [System3] IS NOT NULL THEN ', System3.' + QUOTENAME([System3])+ ' System3' END, '')
+ ISNULL(CASE WHEN System4 IS NOT NULL THEN ', System4.' + QUOTENAME(System4)+ ' System4' END, '')
+ ISNULL(CASE WHEN System5 IS NOT NULL THEN ', System5.' + QUOTENAME(System5)+ ' System5' END, '')
+ ISNULL(CASE WHEN System6 IS NOT NULL THEN ', System6.' + QUOTENAME(System6)+ ' System6' END, '')
FROM [dbo].[TBL_Mapping]
where Attribute =#attributeName
FOR XML PATH(''), TYPE
).value('.', 'VARCHAR(MAX)')
,1,1,'')
SET #SQL = '
SELECT distinct
m.ID MappingID,
m.KeyValueUniqueKey,
m.ValueKeyUniqueKey,
' + #SelectColumns + '
FROM [dbo].[TBL_Mapping] M '
IF CHARINDEX('System1.',#SelectColumns) > 0
BEGIN
SET #SQL = #SQL +
'
LEFT OUTER JOIN dbo.VW_System1_ALL System1 ON
System1.System1ID=M.System1ID '
END
IF CHARINDEX('System2.',#SelectColumns) > 0
BEGIN
SET #SQL = #SQL +
'
LEFT OUTER JOIN dbo.TBL_System2 System2 ON
M.System2ID= System2.System2ID '
END
IF CHARINDEX('System4.',#SelectColumns) > 0
BEGIN
SET #SQL = #SQL + '
LEFT OUTER JOIN DBO.tbl_System4 System4 ON
System4.Key1 = M.KeyValueUniqueKey AND
System4.Value1 = ValueKeyUniqueKey '
END
IF CHARINDEX('System5.',#SelectColumns) > 0
BEGIN
SET #SQL = #SQL + '
LEFT OUTER JOIN DBO.tbl_System5 System5 ON
System5.System5Id = M.System5Id'
END
IF CHARINDEX('System6.',#SelectColumns) > 0
BEGIN
SET #SQL = #SQL + '
LEFT OUTER JOIN dbo.tbl_system6 System6 ON
System6.System6Id = M.System6Id'
END
IF CHARINDEX('System3.',#SelectColumns) > 0
BEGIN
SET #SQL = #SQL + '
LEFT OUTER JOIN [dbo].[TBL_System3] System3 ON
System3.System3Id = M.System3Id'
END
SET #SQL = #SQL + '
WHERE m.version=0 and isActive=1
ORDER by m.ID'
print #SQL
exec (#SQL)
I have looked at the Leftjoin2 extn method but that is not helping much.
What is the best possible action to get this on to EF.
or EF itself is a wrong choise for this sort of problems?
You can do dynamic query generating and then in the end do Skip().Take().
Your model for custom object may look like this:
class MappingData
{
//not sure what the data types are.
int MappingId;
int KeyValueUniqueKey;
int ValueKeyUniqueKey;
string System1;
string System2;
...
string System6;
}
Then in the get method map data,
IQueryable<MappingData> sql = db.TBL_Mapping
.Select(m => new MappingData {
MappingId = ID,
KeyValueUniqueKey = KeyValueUniqueKey,
ValueKeyUniqueKey = ValueKeyUniqueKey,
//leave other columns out
//they will be filled in
//dynamically
})
.Distinct();//get distinct
//--------------------
//REPEAT START
bool HasSystem1 = db.TBL_Mapping.Any(m => m.System1 != null);
//left outer join with System1 if it has it in the TBL_Mapping
if (HasSystem1)
{
sql =
from m in sql
join s1 in db.VW_System1_ALL
on m.System1ID equals s1.System1ID into stemp
from st in stemp.DefaultIfEmpty()
select new { MappingId = st.Id,
KeyValueUniqueKey = st.KeyValueUniqueKey,
ValueKeyUniqueKey = st.ValueKeyUniqueKey,
System1 = st.System1 }; //SystemX column.
}
//REPEAT END
//--------------------
// repeat the above for System2 thru System6
//And in the end do paging.
var result = sql
.Skip(currentPageNumber * numberOfObjectsInPage)
.Take(numberOfObjectsInPage);
This is a bad fit for EF. If all you are only trying to add paging -- add your own paging functionality to the stored proc. You can do this by using ROW_NUMBER OVER what every you are sorting by, then use an an outer query to return the page of data you want, for example...
CREATE PROCEDURE [dbo].[PagedSomething]
#pageSize int,
#pageNum int -- assume pages are 0-based
AS
BEGIN
-- outer query does the paging in its where clause,
-- returning the selected "pages" from the raw results of the inner query
SELECT RawResults.SomethingId
FROM
-- inner query where you make your basic data
(SELECT
s.SomethingId
, ROW_NUMBER() OVER(ORDER BY s.SomethingId) RowID
FROM Somethings s) RawResults
WHERE RowID >= #pageNum * #pageSize + 1
AND RowID < (#pageNum + 1) * #pageSize + 1
END

Using ExecuteNonQuery to run a Stored Procedure isn't creating my table, but the table is created when executing the sp in SSMS

Some notes:
ExecuteNonQuery returns -1
ExecuteNonQuery will drop the table (#droptable), but it will not create the new table (#code)
the length of the #code query is 10265 characters
The stored procedure runs perfectly fine in SSMS and returns 22 rows in the table
Are there any ideas as to why C#'s ExecuteNonQuery function doesn't seem to be executing the 'exec(#code)' portion of the stored procedure?
ALTER procedure [dbo].[sp_create_EditControlResultsPivot]
as
begin
declare #t nvarchar (250);
set #t = 'editControlResults'
declare #newtable nvarchar(250);
set #newtable = 'dbo.' + #t + 'Pivot'
declare #nonPivotColumn1 nvarchar(250);
set #nonPivotColumn1 = 'num'
declare #nonPivotColumn2 nvarchar(25);
set #nonPivotColumn2 = 'File_Name'
declare #droptable nvarchar(max);
set #droptable =
'if EXISTS (select * from sys.objects where object_id = object_id(N''' + #newtable + '''))
begin drop table ' + #newtable + ' end
'
declare #i int
set #i = 1;
declare #itemList nvarchar(max);
declare #code nvarchar(max);
while #i <= (
select COUNT(*)
from sys.columns c
left join sys.tables t on c.object_id = t.object_id
where 1=1
and c.name not like #nonPivotColumn1
and c.name not like #nonPivotColumn2
and t.name = #t
)
begin
set #itemList = #itemList + ', ' +
(
select col from
(
select c.name as col, ROW_NUMBER () over (order by c.name) as num from
sys.columns c left join sys.tables t on c.object_id = t.object_id
where 1=1
and c.name not like #nonPivotColumn1
and c.name not like #nonPivotColumn2
and t.name = #t
) sub where num = #i
)
set #i = #i + 1
end
set #itemList = (select substring(#itemList, 2, LEN(#itemList)))
set #code = '
SELECT ' + #nonpivotcolumn2 + ', Item
into ' + #newtable + '
FROM
(SELECT ' + #nonpivotcolumn2 + ', ' + #itemList + '
FROM ' + #t + ') sub
UNPIVOT
(Value FOR Item IN (' + #itemList + ')
) AS sub
where Value = ''true''
'
exec(#droptable)
exec(#code);
--print(len(#code))
END
--exec sp_create_EditControlResultsPivot
The ExecuteNonQuery Method returns the number of rows affected use the ExecuteReader method instead.
SqlCommand.ExecuteReader Method
The only way to return data from ExecuteNonQuery would be via an Output parameter.
I suspect your comment #3. the length of the #code query is 10265 characters...could be an issue...I think the call from C# is chopping it to only 4000 or 8000 chars...
Since you are not expecting a resultset, ExecuteNonQuery is good.
Things to try:
Try inserting the content of the #code variable (inside the procedure) in a table and see if you are getting the correct sql...both when executed from SSMS and from C# call
If you get a valid sql query in step 1 (which I doubt)...try executing that query in SSMS to see if it really works...

Categories

Resources