Adding conditions in where statement - c#

I have this Linq query:
IQueryable<SPR> query = db.SPRs;
if (!string.IsNullOrEmpty(search.accountNumber))
{
query = query.Where(b => b.CustomerAccountNumber.Contains(search.accountNumber));
}
if (!string.IsNullOrEmpty(search.accountName))
{
query = query.Where(b => b.CustomerNumber.Contains(search.accountName));
}
if (!string.IsNullOrEmpty(search.submittedBy))
{
query = query.Where(b => b.SubmittedBy.Contains(search.submittedBy));
}
if (!string.IsNullOrEmpty(search.smName))
{
query = query.Where(b => b.SMUserName == search.smName);
}
var result = query.ToList();
I am just appending the where clause if conditions are true. The issue is that it is not just adding a And in the generated SQL where clause like I want it to.
Here is the generated SQL if I have the SubmittedBy and SMUserName filled with data.
SELECT
[Extent1].[Id] AS [Id],
[Extent1].[CustomerNumber] AS [CustomerNumber],
[Extent1].[CustomerAccountNumber] AS [CustomerAccountNumber],
[Extent1].[SMUserName] AS [SMUserName],
[Extent1].[SubmittedBy] AS [SubmittedBy],
[Extent1].[Notes] AS [Notes]
FROM
[dbo].[SPRs] AS [Extent1]
WHERE
([Extent1].[SubmittedBy] LIKE #p__linq__0 ESCAPE N'~')
AND (([Extent1].[SMUserName] = #p__linq__1) OR (([Extent1].[SMUserName] IS NULL)
AND (#p__linq__1 IS NULL)))
Not sure how this last line OR (([Extent1].[SMUserName] IS NULL) AND (#p__linq__1 IS NULL))) is getting added which is messing the query up.
Can someone please tell me how I can have just AND in the eventual query when the if conditions are satisfied?

Since you are working with sql server a more performance efficient and sleek way would be to handle the optional parameters inside a stored procedure and make use of Dynamic sql with sp_executesql to benefit from Parameterised Execution Plans.
CREATE PROCEDURE getSPR
#SubmittedBy Varchar(100) = NULL --<--- Use appropriate datatypes
,#CustomerAccountNumber Varchar(100) = NULL
,#CustomerNumber Varchar(100) = NULL
,#SMUserName Varchar(100) = NULL
AS
BEGIN
SET NOCOUNT ON;
Declare #Sql Nvarchar(max);
SET #Sql = N'SELECT [Id]
,[CustomerNumber]
,[CustomerAccountNumber]
,[SMUserName]
,[SubmittedBy]
,[Notes]
FROM [dbo].[SPRs]
WHERE 1 = 1 '
+ CASE WHEN #SubmittedBy IS NOT NULL THEN
N' AND [SubmittedBy] LIKE ''%'' + #SubmittedBy + ''%''' ELSE N' ' END
+ CASE WHEN #CustomerAccountNumber IS NOT NULL THEN
N' AND [CustomerAccountNumber] LIKE ''%'' + #CustomerAccountNumber + ''%''' ELSE N' ' END
+ CASE WHEN #CustomerNumber IS NOT NULL THEN
N' AND [CustomerNumber] LIKE ''%'' + #CustomerNumber + ''%''' ELSE N' ' END
+ CASE WHEN #SMUserName IS NOT NULL THEN
N' AND [SMUserName] = #SMUserName ' ELSE N' ' END
Exec sp_executesql #sql
,N' #SubmittedBy Varchar(100),#CustomerAccountNumber Varchar(100)
,#CustomerNumber Varchar(100), #SMUserName Varchar(100)'
,#SubmittedBy
,#CustomerAccountNumber
,#CustomerNumber
,#SMUserName
END

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

Best way to write Combination logic in SQL or MVC for multiple select options

I, want to write the best combination login either SQL store procedure or ASP.net for the following combination diagram.
Each field in the diagram has 4 combinations. So, total it will be 20 combinations. I, don't want to write 20 if else statement in SQL server or c#.
Here is the UI for the logic.
The user can either select Quotation no or combination of 20 etc. I, don't want to write 20 if else statement.
Is their any better way to write a statement in SQL or C# to make it better.
For example
the user can select from either Quotation no or agency name or start date or end date or combination of two or more field.
What is the best way to write the algorithm?
Here is the combination
1- Search By only Quotation No
2- Search By only Agency No
3- Search By only Start Date
4- Search By only End Date
5- Search By only contract No
6 - Quotation No + Agency No
7 - Quotation No + Start Date
8 - Quotation No + End Date
9 - Select by All fields
I stumbled upon a similar problem some time ago while trying to perform a search using many filters. The best solution I found was to use a dynamic SQL query, in which the statement is built based on the parameters.
The select clause of the sql statement is static but the from clause and the where clause is based on the parameters.
CREATE PROCEDURE dbo.SearchQuotation
(
#QuotationNo INT,
#AgencyName VARCHAR(50),
#StartDate DATETIME,
#EndDate DATETIME,
#Term INT
)
AS
BEGIN
DECLARE #SQL NVARCHAR(4000)
SELECT #SQL = N'SELECT * FROM Quotations WHERE 1 = 1'
DECLARE #ParametersDefinition NVARCHAR(4000)
SELECT #ParametersDefinition = N'#QuotationNoParameter INT,
#AgencyNameParameter VARCHAR(50),
#StartDateParameter DATETIME,
#EndDateParameter DATETIME,
#TermParameter INT'
IF #QuotationNo IS NOT NULL
SELECT #SQL = #SQL + N' AND QuotationNo = #QuotationNoParameter '
IF #AgencyName IS NOT NULL
SELECT #SQL = #SQL + N' AND AgencyName = #AgencyNameParameter '
IF #StartDate IS NOT NULL
SELECT #SQL = #SQL + N' AND StartDate = #StartDateParameter '
IF #EndDate IS NOT NULL
SELECT #SQL = #SQL + N' AND EndDate = #EndDateParameter '
IF #Term IS NOT NULL
SELECT #SQL = #SQL + N' AND Term = #TermParameter '
EXECUTE sp_executesql
#SQL,
#ParametersDefinition,
#QuotationNoParameter = #QuotationNo,
#AgencyNameParameter = #AgencyName,
#StartDateParameter = #StartDate,
#EndDateParameter = #EndDate,
#TermParameter = #Term
END
From the SQL side you can achieve by this way:
SELECT * FROM Qoutes AS q
WHERE (q.QoutationNo = #QoutationNo OR #QoutationNo IS NULL)
AND (q.AgencyName = #AgencyName OR #AgencyName IS NULL)
AND (q.StartDate = #StartDate OR #StartDate IS NULL)
AND (q.EndDate = #EndDate OR #EndDate IS NULL)
AND (q.Term = #Term OR #Term IS NULL)
Pass NULL value if it is not selected from the web page.

prevent sql injection in proc in linq c#

I have a search form with 3 textboxes (stud_name, stud_city, stud_state). When I enter this vaue ' drop table users in the name textbox, it will drop the table successfully. Here is my c# code for calling stored procedure. How to prevent this type of injection using linq in c#
using (iDataContext db = new iDataContext(connectionString))
{
var statusList = db.SP_Student_LOOKUP(name, city, state);
return statusList.ToList<SP_Student_LOOKUPResult>();
}
here is my sp
CREATE proc SP_Student_LOOKUP #name varchar(50),
#city varchar(50),
#state varchar(2)
as
declare #sql varchar(2048)
begin
set #sql = 'select * from student where ';
if (((#name is not null)) and (len(#name) > 0))
set #sql = #sql + ' studentname like ''%'+#name+'%'' and '
if (((#city is not null)) and (len(#city) > 0))
set #sql = #sql + ' studentcity like ''%'+#city+'%'' and '
if (((#state is not null)) and (len(#state) > 0))
set #sql = #sql + ' studentstate like ''%'+#state+'%'' and '
print #sql
exec( #sql )
Your stored proc is susceptible to sql injection because you're (needlessly) using dynamic sql to build up your query. Don't do this.
Your stored procedure should be
CREATE proc SP_Student_LOOKUP
#name varchar(50),
#city varchar(50),
#state varchar(2)
as
select * from student
where
(#name is null or len(#name) = 0 or studentname LIKE #name)
and (#city is null or len(#city) = 0 or studentcity like #city)
and (#state is null or len(#state) = 0 or studentstate like #state)
This has the same behaviour as your dynamic sql, with 1 caveat - to fully stop the sql injection vulnerability you need to wrap % and % around your inputs - by doing this inside the stored proc you will re-introoduce the same problem
If you're using Entity Framework, as I'm guessing, you shouldn't be using stored procedures to retrieve data, unless your query is really beyond the capabilities of LINQ (and it isn't). You should build your query in LINQ, like that:
using (iDataContext db = new iDataContext(connectionString))
{
var statusList = from s in db.Set<student>()
select s;
if (!String.IsNullOrEmpty(name))
{
statusList = statusList.Where(s => s.studentname.Contains(name));
}
if (!String.IsNullOrEmpty(city))
{
studentList = studentList.Where(s => s.studentcity.Contains(city));
}
if (!String.IsNullOrEmpty(state))
{
studentList = studentList.Where(s => s.studentstate.Contains(state));
}
return statusList.ToList();
}
and if you're really using the old DataContext object, please read a more recent EF tutorial. This has been superceeded by DbContext (where you will find the .Set<>() method I used).
I agree with #TsahiAsher and #Jamiec
but clearly you are adamant to stick to the dynamic sql,
Given the constraints, I'd suggest that you parameterize your dynamic sql and execute it with the parameters you got.
(note i've also changed the position of "And" statements because if all 3 parameters are empty, you'd get an incomplete sql statement)
db fiddle Here
-- If I recall correct, it has to be NVARCHAR
declare #sql nvarchar(2048)
set #sql = 'select * from student where 1=1 ';
if ((#name is not null) and (len(#name) > 0))
set #sql = #sql + 'AND studentname like ''%''+#name+''%'' '
if ((#city is not null) and (len(#city) > 0))
set #sql = #sql + 'AND studentcity like ''%''+#city+''%'' '
if ((#state is not null) and (len(#state) > 0))
set #sql = #sql + 'AND studentstate like ''%''+#state+''%'' '
print (#sql)
exec sp_executesql #sql, N'#name VARCHAR(50),#city VARCHAR(50),#state VARCHAR(2)', #name = #name, #city = #city, #state=#state
Sanitize the input strings by escaping single quotes within it:
using (iDataContext db = new iDataContext(connectionString))
{
var statusList = db.SP_Student_LOOKUP(name.Replace("'", #"\'"), city.Replace("'", #"\'"), state.Replace("'", #"\'")
return statusList.ToList<SP_Student_LOOKUPResult>();
}

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

Cannot update SQL table using variable for the table name? [duplicate]

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

Categories

Resources