MSSQL use trim on select - sql-server-2008

So i am trying to do ltrim or rtrim in a sql statement without having to explicitly type all the column names. So basically instead of doing
select ltrim(col1), ltrim(col2)... from table 1
i want to do something like
select ltrim(*) from table1.
I understand that typically it is bad practice to use select * but in this case it makes sense. This is for Sql-server 2008. There are some similar questinos but could not find question for this particular issue. Thanks for help in advance.

you can dynamically create the query or make a stored procedure in which you pass the table name..
DECLARE #colsUnpivot AS NVARCHAR(MAX)
,#tablename as varchar(255)='table1',
#columns as varchar (max),
#SQL VARCHAR(max)
select #colsUnpivot = stuff((select ',LTRIM('+quotename(C.name)+')'
from sys.columns as C
where C.object_id = object_id(#tablename) and
C.is_computed=0
for xml path('')), 1, 1, '')
SET #columns=#colsUnpivot
SET #SQL = '(SELECT '+#columns+' FROM [dbo].['+#tablename+'] )';
EXEC(#SQL)

Related

How find an value in to all table postgress

Suppose to have this word 'student' , I need to return all tables that contains the 'student' word. I need something like this:
select *
from information_schema.tables t
where column ='student';
Anyone can help me?
If you want tables, you would use:
select *
from information_schema.tables t
where table_name like '%student%';
If you want columns, you would use the right metadata table and use:
select *
from information_schema.columns c
where column_name like '%student%';
So you want to find the string 'students' or any version thereof in the database. Well there is no simple query that will give you that. So what you need to to select from the information schema all columns names having a string type definition and with those build a query for every column. The routine to do that is not overly complex or large providing you need only standard columns types. That no user defined types, no JSON(B), XML, or hstore types. You can try:
do $$
declare
k_sql_base constant text = $stmt$
select '%1$s' table_schema,'%2$s' table_name,'%3$s' column_name
from %1$I.%2$I where lower(%3$I) like '%4$s' limit 1;
$stmt$;
k_search_text text = '%students%';
c_text_cols cursor for
select col.table_schema
, col.table_name
, col.column_name
from information_schema.columns col
where col.data_type in ('text', 'character varying')
and col.table_schema not in ('pg_catalog', 'information_schema');
l_table_rec record;
l_search_stmt text;
begin
for l_table_rec in c_text_cols
loop
l_search_stmt = format(k_sql_base
,l_table_rec.table_schema
,l_table_rec.table_name
,l_table_rec.column_name
,k_search_text
) ;
execute l_search_stmt into l_table_rec;
if l_table_rec.table_schema is not null then
raise notice 'Found in: %.%.%',l_table_rec.table_schema
,l_table_rec.table_name
,l_table_rec.column_name;
end if;
end loop;
end;
$$;

StoredprocedureinMSSQLtoMySQL

I have a stored procedure in MSSQl, i would like to write it int My sql,
Any help or sugegstions please.I can not get to use XML function in Mysql.
stored proc:
ALTER PROCEDURE uspGetProductDetailsCSV (
#sku NVARCHAR(MAX)
)
AS
BEGIN
-
SELECT T.C.value('.', 'NVARCHAR(100)') AS [SKU]
INTO #tblPersons
FROM (SELECT CAST ('<Name>' + REPLACE (#sku, ',', '</Name><Name>')
+ '</Name>' AS XML) AS [Products]) AS A
CROSS APPLY Products.nodes('/Name') as T(C)
SELECT *
FROM ProductInformation Pr
WHERE EXISTS (SELECT Name FROM #tblPersons tmp WHERE tmp.SKU
= case when len(tmp.SKU) = 11 then Product_No+Colour_Code+Size_Code
when len(tmp.SKU) = 8 then Product_No+Colour_Code
when len(tmp.sku) = 6 then Product_No end)
DROP TABLE #tblPersons
END
Edit: I could not write XML part of stored proc, as i have pasted same code in Mysql, it doesnt create stored proc
Error: >can not cast as XML<
I dont believe XML is a valid type in MySql. Try just leaving it as a VARCHAR.
So, just remove the cast...I also think you will have to use CONCAT instead of + and change the [] around columns to ticks.
So Instead of:
FROM (SELECT CAST ('<Name>' + REPLACE (#sku, ',', '</Name><Name>')
+ '</Name>' AS XML) AS [Products]) AS A
TRY:
FROM (SELECT CONCAT('<Name>' , REPLACE(#sku, ',', '</Name><Name>'),
'</Name>') AS `Products`) AS A

Is it possible that I could find a row contains a string? Assume that I do not know which columns contain a string

I know that there are several ways to find which row's column contains a string, like using [column name] regexp ' ' or [column name] like ' '
while currently what I need some help is I have a table with several columns, all of there are varchar or text and I am not sure which column contains a certain string. Just say that I want to search a "xxx from a table. Several different columns could contain this string or not. Is there a way that I could find which column contains this string?
I have a thinking and the solution could be
select * from [table name] where [column1] regexp 'xxx' or
[column2] regexp 'xxx' or ...... [column39] regexp 'xxx' or .....
[colum60] regexp 'xxx' or ... or [column 80] regexp 'xxx';
I do not want the query like this. Is there another effective way?
To give a better example, say that we are searching for a table that belongs to a blog.
We have title, URL, content, key words, tag, comment and so on. Now we just say, if any blog article is related to "database-normalization", this word may appear in the title, URL or content or anywhere, and I do not want to write it one by one like
where title regexp 'database-normalization' or content regexp 'database-normalization' or url regexp 'database-normalization'......
as when there are hundreds columns, I need to write a hundred, or in this case is there an effective way instead of write hundred or statement? Like using if-else or collections or some others to build the query.
If you want a pure dynamic way, you can try this. I've tried it long back on sql-server and hope it may help you.
#TMP_TABLE -- a temporary table
- PK, IDENTITY
- TABLE_NAME
- COLUMN_NAME
- IS_EXIST
INSERT INTO #TMP_TABLE (TABLE_NAME,COLUMN_NAME)
SELECT C.TABLE_NAME, COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS C
WHERE C.TABLE_NAME = <your-table> AND C.DATA_TYPE = 'varchar'; -- you can modify it to handle multiple table at once.
-- boundaries
SET #MINID = (SELECT ISNULL(MIN(<PK>),0) FROM #TMP_TABLE );
SET #MAXID = (SELECT ISNULL(MAX(<PK>),0) FROM #TMP_TABLE );
WHILE ((#MINID<=#MAXID) AND (#MINID<>0))
BEGIN
SELECT #TABLE_NAME = TABLE_NAME,#COLUMN_NAME = COLUMN_NAME
FROM #TMP_TABLE
WHERE <PK> = #MINID;
SET #sqlString = ' UPDATE #TMP_TABLE
SET IS_EXIST = 1
WHERE EXIST (SELECT 1 FROM '+ #TABLE_NAME+' WHERE '+ #COLUMN_NAME +' = ''demo.webstater.com'') AND <PK> = '+ #MINID;
EXEC(#sql) ;
SET #MINID = (SELECT MIN(<PK>) FROM #TMP_TABLE WHERE <PK> > #MINID );
END
SELECT * FROM #TMP_TABLE WHERE IS_EXIST = 1 ; -- will give you matched results.
If you know the columns in advance, what you proposed is probably the most effective way (if a little verbose).
Otherwise, you could get the column names from INFORMATION_SCHEMA.COLUMNS and construct dynamic SQL based on that.
His question is not to query specific columns with like clause. He has been asking to apply same pattern across columns dynamically.
Example: Table having 3 columns - FirstName, LastName, Address and pattern matching is "starts with A" then resulting query should be:
Select * From Customer where FirstName like 'A%" or LastName like 'A%" or Address like 'A%'
If you want to build query in business layer, this could easily be done with reflection along with EF.
If you are motivated to do in database then you can achieve by building query dynamically and then execute through sp_executesql.
Try this (Just pass tablename and the string to be find)-:
create proc usp_findString
#tablename varchar(500),
#string varchar(max)
as
Begin
Declare #sql2 varchar(max),#sql nvarchar(max)
SELECT #sql2=
STUFF((SELECT ', case when '+QUOTENAME(NAME)+'='''+#string+''' then 1 else 0 end as '+NAME
FROM (select a.name from sys.columns a join sys.tables b on a.[object_id]=b.[object_id] where b.name=#tablename) T1
--WHERE T1.ID=T2.ID
FOR XML PATH('')),1,1,'')
--print #string
set #sql='select '+#sql2+' from '+#tablename
print #sql
EXEC sp_executesql #sql
End
SQL Server 2014
One way is to use CASE to check the substring existence with LOCATE in mysql and return the column but all you have to check in every column of the table as below:
CREATE TABLE test(col1 VARCHAR(1000), col2 VARCHAR(1000), col3 VARCHAR(1000))
INSERT INTO test VALUES
('while currently what I need some help is I have a table with 10 columns',
'contains a certain string. Just say that I want to search a table',
'contains a certain string demo.webstater.com')
SELECT (CASE WHEN LOCATE('demo.webstater.com', col1, 1) > 0 THEN 'col1'
WHEN LOCATE('demo.webstater.com', col2, 1) > 0 THEN 'col2'
WHEN LOCATE('demo.webstater.com', col3, 1) > 0 THEN 'col3'
END) whichColumn
FROM test
OUTPUT:
whichColumn
col3
There are many ways in which you can do your analysis. You can use "LIKE A%%" if it starts from A in SQL, "REGEX" LibrarY for multiple checks.

How to pass list of items as parameter to a stored procedure

I have a stored procedure
create PROCEDURE [dbo].[SP]
(
#OrderList varchar(500)
)
AS
Begin
select *
from table
where id in ('+ #OrderList +')
Here I am passing orderlist....
When I execute like this
exec sp 'iss005,iss006'
I am not getting data
but when I hardcode in sp like this ...
select * from table where id in ('iss005','iss006')
then am getting data...
Thank you
Unfortunately it won't work that way. If you change your procedure to something like the following, this will work:
Create Procedure dbo.SP
#OrderList varchar(500)
AS
Declare #SQL VarChar(1000)
Select #SQL = 'SELECT * FROM table '
Select #SQL = #SQL + 'WHERE id in (' + #OrderList +')'
Exec ( #SQL)
GO
Looking more into your query, your ID's value varchar, so the procedure will fail as you'll still be getting :
WHERE id in (iss005,iss006)
when you want :
WHERE id in ('iss005','iss006')
You would need to either pass in the quote values, e.g. :
#OrderList = 'iss005','iss006'
Or work out some SQL to split the #OrderList by comma and use the QUOTENAME() function to add the quotes to the new variable.
I strongly recommend in this case the use of XML parameters, will give you a lot of flexibility.
Your XML might be something like
<ids>
<id>iss006</id>
<id>iss005</id>
</ids>
Your procedure should be something like this:
create PROCEDURE [dbo].[SP]
(
#OrderList XML
)
AS
Begin
select * from table
where id in (
select ParamValues.ID.value('.','VARCHAR(50)')
FROM #OrderList.nodes('/ids/id') as ParamValues(id)
)
Besides the use of store procedures outputs I also would recommend the use of functions but that is up to you.
Regards.
I had the same kind of requirement. i was getting list of user in a int list variable and i need to get all the order of those user. I have use a very simple trick which had solve my issue. please find the code.
public DataTable GetAllOrderData(List<int> UserID)
{
try
{
string listofuser = String.Join(",", UserID.ToArray());
SqlParameter[] parameters = new SqlParameter[]
{
new SqlParameter("#USERID", listofuser)
};
return SqlDBHelper.ExecuteParamerizedSelectCommand("GetOrderByUserID", System.Data.CommandType.StoredProcedure, parameters);
}
finally { UserID = null; }
}
And this is the stored procedure
CREATE PROCEDURE [dbo].[GetOrderByUserID] (#USERID varchar(700))
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
Declare #SQL VarChar(1000)
Select #SQL = 'SELECT *,ORM.OrganisationName FROM OrderTransaction ORT LEFT JOIN OrganisationMaster ORM ON (ORT.OrganisationID=ORM.OrganisationID) '
Select #SQL = #SQL + 'WHERE ORT.CreatedBy IN (' + #USERID +')'
Exec ( #SQL)
END

EXECUTESQL error

Here is the following piece of code that I am trying to execute on SQL Server.
DECLARE #string NVARCHAR(MAX) = '
CREATE PROC [dbo].[Trend]
#slsID NVARCHAR(20)
AS
BEGIN
SET NOCOUNT ON
DECLARE #BeginningRange varchar(20),
#EndingRange varchar(20)
SET #EndingRange = ''12*13''
SET #BeginningRange = ''12*02''
;WITH CTE1 AS(
SELECT
dbo.Field1,dbo.Field2,dbo.Field3
FROM dbo.Table1 join dbo.Table2 where...conditions
weekNum BETWEEN (#BeginningRange) AND (#EndingRange)
)
SELECT * FROM CTE1
UNPIVOT
( numbers for type in (Field1, Field2, Field3, Field4)
) as p PIVOT
(
Sum(numbers) for
WeekNum in ([12*02],[12*03],[12*04],[12*05],[12*06],[12*07],[12*08],[12*09],[12*10], [12*11],[12*12],[12*13])
) as q
END
'
EXECUTE SP_EXECUTESQL #STRING
When I try to run this, it errors out saying that
"Incorrect syntax near the keywor 'as'"
I took this code out and executed it separately and it didn't error out. Am I missing something here?
Look like missing parentheses around the parameter to the procedure.
One trick you can use is the print out the sql statement and then try to run that - the error message might give you more info
print #STRING
PIVOT and UNPIVOT clauses each require two closing parentheses.
UNPIVOT (... FOR ... IN (...) ) AS ...
PIVOT (... FOR ... IN (...) ) AS ...
where...conditions
This won't pass a syntax check. If you have removed the actual conditions it may be that this is where your error is. And:
dbo.Table1 join dbo.Table2
has no ON clause
I saw both of these by doing a syntax check on the results of print #string which is the first step you should have taken to find the issue. I still say that based on what you gave us there is no reason at all to use dynamic SQl and it is a poor practice to use dynamic SQL if you don't need it.