This is my stored procedure which take input from listbox and display records related to selected item. but if i do not select anything from listbox then it need to display all records which is no happened.
This is my Stored Procedure
USE [MyDb]
GO
/****** Object: StoredProcedure [dbo].[usp_SearchCAMAFunctionalObsolescence] Script Date: 10/18/2016 12:30:08 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[usp_SearchCAMAFunctionalObsolescence]
#section as nvarchar(max),
#quality as nvarchar(max),
#style as nvarchar(max)
As
Begin
set nocount on;
Declare #Where as varchar(max)
Declare #Select as varchar(max)
Set #Select = ' Distinct vi.struct_no as structure,a.assesmt_no as assessment,a.parcel_no as parcel, o.own_last+'' , ''+o.own_first as taxpayer, id.year_built as built, id.effect_age as age, id.mkt_adj as fo, vi.aprais_val as mktvalue
From assessments a
inner join parcel p on a.parcel_no = p.parcel_no
inner join valueimp vi on vi.assesmt_no = a.assesmt_no
inner join owner o on o.id = a.owner_id
inner join imp_details id on id.improvementId = vi.id and (id.isdeleted is null or id.isdeleted = 0)
inner join quality_details qd on qd.quality_id = id.quality_id
inner join section_details sd on sd.section_id = id.section_id
inner join style_details stdl on stdl.style_id = id.style_id'
Set #Where = ' where (' + #section + ' is null or sd.section_id = ' + #section + ') and (' + #quality + ' is null or qd.quality_id = ' + #quality + ') and (' + #style + ' is null or stdl.style_id = ' + #style + ')'
DECLARE #QUERY NVARCHAR(MAX)
SET #QUERY= 'Select '+ #SELECT + #WHERE
print #QUERY
EXEC sp_executesql #QUERY , N'#section as int ,#quality as int,#style as int' ,#section ,#quality,#style
END
if i execute stored procedure in this way
// EXEC usp_SearchCAMAFunctionalObsolescence 'null','null','null'
it display all records.
but i need to execute stored procedure in this way
// EXEC usp_SearchCAMAFunctionalObsolescence null,null,null
and it not display anything
You don't need a dynamic sql for this purpose. Use IFNULL in the WHERE statements,if you are using mysql.(for SQL Server use ISNULL and for oracle use NVL instead.)
If the input variable is null,then the script will return the actual column value.
USE [MyDb]
GO
/****** Object: StoredProcedure [dbo].[usp_SearchCAMAFunctionalObsolescence] Script Date: 10/18/2016 12:30:08 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[usp_SearchCAMAFunctionalObsolescence]
#section as nvarchar(max),
#quality as nvarchar(max),
#style as nvarchar(max)
As
Begin
set nocount on;
SELECT Distinct vi.struct_no as structure,a.assesmt_no as assessment,a.parcel_no as parcel, o.own_last+'' , ''+o.own_first as taxpayer, id.year_built as built, id.effect_age as age, id.mkt_adj as fo, vi.aprais_val as mktvalue
From assessments a
inner join parcel p on a.parcel_no = p.parcel_no
inner join valueimp vi on vi.assesmt_no = a.assesmt_no
inner join owner o on o.id = a.owner_id
inner join imp_details id on id.improvementId = vi.id and (id.isdeleted is null or id.isdeleted = 0)
inner join quality_details qd on qd.quality_id = id.quality_id
inner join section_details sd on sd.section_id = id.section_id
inner join style_details stdl on stdl.style_id = id.style_id
WHERE sd.section_id =IFNULL(#section,sd.section_id)
AND qd.quality_id = IFNULL(#quality,qd.quality_id)
AND stdl.style_id = IFNULL(#style,stdl.style_id )
END
Why not create a Stored Proc that returns unfiltered results and then call that in your code when no selection is made?
CREATE PROCEDURE [dbo].[usp_SearchCAMAFunctionalObsolescenceUnfiltered]
As
Begin
set nocount on;
SELEcT Distinct vi.struct_no as structure,a.assesmt_no as assessment,a.parcel_no as parcel, o.own_last+'' , ''+o.own_first as taxpayer, id.year_built as built, id.effect_age as age, id.mkt_adj as fo, vi.aprais_val as mktvalue
From assessments a
inner join parcel p on a.parcel_no = p.parcel_no
inner join valueimp vi on vi.assesmt_no = a.assesmt_no
inner join owner o on o.id = a.owner_id
inner join imp_details id on id.improvementId = vi.id and (id.isdeleted is null or id.isdeleted = 0)
inner join quality_details qd on qd.quality_id = id.quality_id
inner join section_details sd on sd.section_id = id.section_id
inner join style_details stdl on stdl.style_id = id.style_id
END
Related
ALTER PROCEDURE [dbo].[ListaUnidadAlumnos]
#MateriaId INT,
#UnidadId INT,
#Columnas AS NVARCHAR(MAX) = Null,
#Query AS NVARCHAR(MAX) = Null
AS
BEGIN
SET NOCOUNT ON;
SELECT
#Columnas = STUFF((SELECT ',' + QUOTENAME(convert(char(10), L.Fecha, 120))
FROM (SELECT DISTINCT(A.Fecha)
FROM Asistencias A
INNER JOIN AspNetUsers U ON A.AlumnoId = U.Id
INNER JOIN Unidades UN ON UN.UnidadId = A.UnidadId
INNER JOIN Materias M ON UN.MateriaId = M.MateriaId
WHERE UN.MateriaId = #MateriaId
AND UN.UnidadId = #UnidadId) L
GROUP BY L.Fecha
ORDER BY L.Fecha asc
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '')
SET #Query = 'SELECT AlumnoId, ' + #Columnas + ' from
(
SELECT A.AlumnoId, A.Fecha, A.Valor
FROM Asistencias A
INNER JOIN AspNetUsers U ON A.AlumnoId = U.Id
) x
pivot
(
max(Valor)
for Fecha in (' + #Columnas + ')
) p '
EXECUTE(#query)
This stored procedure returns:
The dates are dynamic, depending on the assistance of the class
I am not using entity framework, I execute the procedures in the following way
public async Task ObtenerListaMateria(int materiaId)
{
var pMateriaId = new SqlParameter("#MateriaId", materiaId);
ListaAlumnosIdMateria = await _context.ListaAlumnosIdMateria
.FromSql("EXEC ObtenerListaAlumnosIdMateria #MateriaId", pMateriaId)
.ToListAsync();
ViewData["NumeroAlumnos"] = ListaAlumnosIdMateria.Count();
ViewData["Contador"] = 0;
}
If I execute the procedures in this way, first I have to create the model with the data that they see in the procedure
My question is, how do you call the procedure if the query will always give me a different number of dates, can I create a generic model?
I have a stored procedure that is called from C#:
CREATE PROCEDURE [MySP]
#ID int,
#Exists bit OUTPUT
AS
BEGIN
SET NOCOUNT ON;
SET #Exists = 0
SELECT TOP 1 ID
FROM MyTable
WHERE ID = #ID
IF ##ROWCOUNT = 0
BEGIN
SELECT b.*
FROM AnotherTable b
INNER JOIN AnotherTable2 c ON b.ID = c.ID
WHERE b.ID = #ID
END
ELSE
BEGIN
SET #Exists = 1
SELECT TOP 0 NULL
END
END
IF #ID does not exist in table MyTable, then I return the SELECT b.*, otherwise if #ID exists in the table, then I return no rows
The problem is that when #ID exists in the table, the stored procedure returns two tables as a result to C#, the one from SELECT TOP 1 and the one from SELECT b.* and I only want to return SELECT b.* so how can I do this?
Just replace all the logic with:
SELECT b.*
From AnotherTable b INNER JOIN
AnotherTable2 c
ON b.ID = c.ID
WHERE b.ID = #ID AND
NOT EXISTS (SELECT 1 FROM MyTable WHERE ID = #ID);
And, if you don't want duplicates, you might as well do:
SELECT b.*
From AnotherTable b
WHERE b.ID = #ID AND
EXISTS (SELECT 1 FROM AnotherTable2 c WHERE b.ID = c.ID) AND
NOT EXISTS (SELECT 1 FROM MyTable WHERE ID = #ID);
Then, learn about table valued functions. If you want to return a table, then the best approach -- if it is feasible -- is a function, not a stored procedure.
(Functions are more limited in their functionality, so this is not always possible.)
Use exists for this:
CREATE PROCEDURE [MySP]
#ID int,
#Exists bit OUTPUT
AS
BEGIN
SET NOCOUNT ON;
SET #Exists = 0
IF EXISTS(SELECT TOP 1 ID FROM MyTable WHERE ID = #ID)
BEGIN
SELECT b.*
From AnotherTable b
INNER JOIN AnotherTable2 c on b.ID = c.ID
Where b.ID = #ID
END
ELSE
BEGIN
SET #Exists = 1
SELECT TOP 0 NULL
END
END
The second result that you are getting is from the statement select top 0 null
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...
We're looking to do an update in several SQL Server databases to change all NULL values in a certain table to be empty strings instead of NULL. We're potentially going to be doing this across hundreds of databases. The table name will always be the same, but the column names are variable based on how the front-end application is configured (don't judge... I didn't create this system).
Is there a way to do an update on all of these columns without knowing the column names ahead of time?
You can pass the name of the column in dynamic sql:
declare #sql nvarchar (1000);
set #sql = N'update table set ' + #column_name + '= ''''';
exec sp_executesql #sql;
You can look in the sys.columns table and join on the table name or object_id.
DECLARE #OBJ_ID INT
SELECT #OBJ_ID = OBJECT_ID
FROM SYS.tables
WHERE name = 'YOURTABLE'
SELECT * FROM SYS.columns
WHERE OBJECT_ID = #OBJ_ID
You could use the name field from the sys.columns query as a basis to perform the update on.
Assuming you want all columns of varchar/char types only (or change the type filter to whatever you need):
DECLARE #tableName varchar(10)
SET #tableName = 'yourtablenamehere'
DECLARE #sql VARCHAR(MAX)
SET #sql = ''
SELECT #sql = #sql + 'UPDATE ' + #tableName + ' SET ' + c.name + ' = '''' WHERE ' + c.name + ' IS NULL ;'
FROM sys.columns c
INNER JOIN sys.tables t ON c.object_id = t.object_id
INNER JOIN sys.types y ON c.system_type_id = y.system_type_id
WHERE t.name = #tableName AND y.name IN ('varchar', 'nvarchar', 'char', 'nchar')
EXEC (#sql)
This can be achieved with cursors. You first select the column names like #Darren mentioned, then you Set a Cursor with those values and loop:
Open oColumnsCursor
Fetch Next From oColumnscursor
Into #ColumnName
While ##FETCH_STATUS=0
Begin
Set #oQuery = 'Update [DB]..[Table] Set [' + #ColumnName + '] = ''NewValue'' Where [' + #ColumnName + '] = ''OldValue'''
Execute(#oQuery)
Fetch Next From oColumnscursor Into #ColumnName
Set #oCount = #oCount + 1
End
Close oColumnsCursor;
Deallocate oColumnsCursor;
This will work when you know the Table Name:
DECLARE #tableName varchar(10)
SET #tableName = 'Customers'
DECLARE #sql VARCHAR(MAX)
SET #sql = ''
SELECT #sql = #sql + 'UPDATE ' + #tableName + ' SET ' + c.name + ' = ISNULL('+ c.name +','''');'
FROM sys.columns c
INNER JOIN sys.tables t ON c.object_id = t.object_id
INNER JOIN sys.types y ON c.system_type_id = y.system_type_id
WHERE y.name IN ('varchar', 'nvarchar', 'char', 'nchar')
AND t.name = #tableName;
EXEC(#sql);
And this will iterate all Tables and all Columns in a Db:
DECLARE #sql VARCHAR(MAX)
SET #sql = ''
SELECT #sql = #sql + 'UPDATE ' + t.name + ' SET ' + c.name + ' = ISNULL('+ c.name +','''');'
FROM sys.columns c
INNER JOIN sys.tables t ON c.object_id = t.object_id
INNER JOIN sys.types y ON c.system_type_id = y.system_type_id
WHERE y.name IN ('varchar', 'nvarchar', 'char', 'nchar');
EXEC(#sql);
Below is the procedure.
ALTER PROCEDURE [dbo].[util_db_updateRow]
#colval_name NVARCHAR (30), -- column and values e.g. tax='5.50'
#idf_name NVARCHAR (300), -- column name
#idn_name NVARCHAR (300), -- column value
#tbl_name NVARCHAR (100) -- table name
AS
BEGIN
SET NOCOUNT ON;
DECLARE #sql NVARCHAR(MAX)
-- construct SQL
SET #sql = 'UPDATE ' + #tbl_name + ' SET ' + #colval_name +
' WHERE ' + #idf_name + '=' + #idn_name;
-- execute the SQL
EXEC sp_executesql #sql
SET NOCOUNT OFF
RETURN
END
Below is the stored procedure where you can pass Schema Name, Table Name and list of column names separted by comma.It works only in Sql Server 2016 or higher.
CREATE OR ALTER PROCEDURE UpdateData
(#SchemaName NVARCHAR(Max),#TableName NVARCHAR(MAX),#ColumnNames NVARCHAR(MAX))
AS
BEGIN
DECLARE #DynamicSql NVARCHAR(MAX);
SET #DynamicSql = 'UPDATE ' +'[' +#SchemaName+'].' + '[' +#TableName+']' +' SET ' + STUFF((SELECT ', [' + C.name + '] = ' + '''NEW_VALUE'''
FROM sys.columns C
INNER JOIN sys.tables T ON T.object_id = C.object_id
INNER JOIN sys.schemas S ON T.schema_id = S.schema_id
WHERE
T.name = #TableName
AND S.Name = #SchemaName
AND [C].[name] in (SELECT VALUE FROM string_split(#ColumnNames,','))
FOR XML PATH('')), 1,1, '')
print #DynamicSql;
EXEC (#DynamicSql);
END
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