can not get the right number of columns SQL Server - sql

I have imported a table to my database, and to get the number of columns and assign it to a variable I do
SELECT #HowManyColumns = COUNT(COLUMN_NAME)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE (TABLE_NAME = #table_name )
But it keeps telling that the count is 0!
If I do the same for other tables it works!
I have found that the column count of the table that is not working is more than 40 columns, Why is it not working...
The data is this

Since tables w/o columns don't exists, that can only mean that the WHERE clause is not satisfied. In other words, the table named as the value of #table_name does not exists. Since you say 'sometimes it work, and some does not' that would immediately point toward case sensitive deployments. Make sure you always use the correct name for the table, with the proper case, so your code work correctly on servers which are deployed with a case sensitive collation.

Try issuing
SELECT DISTINCT TABLE_NAME
FROM INFORMATION_SCHEMA
and check table name for case.

Try having the table name as a text string instead:
DECLARE
#table_name varchar(50),
#noOfColumns int
SET
#table_name = 'table_name'
SET
#noOfColumns =
(SELECT count(*)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = #table_name)
PRINT #noOfColumns
The answer you get is the number of columns in the #noOfColumns variable

Related

How to show column names in a row

I want to write a SELECT statement to show the list of fields in the table.
COLUMN
column_1
column_2
column_3
You can use the information schema tables, particularly columns:
select column_name
from INFORMATION_SCHEMA.COLUMNS
where table_schema = #schema_name and table_name = #table_name;
Note that this metadata is stored per database. So if you want a table in another database, you need three part naming:
select column_name
from <database>.INFORMATION_SCHEMA.COLUMNS
where table_schema = #schema_name and table_name = #table_name;
Yet one more option: This will return results on any table,ad-hoc query or even a stored procedure.
(using spt_values as a demonstration)
Example
Select column_ordinal
,name
,system_type_name
From sys.dm_exec_describe_first_result_set('Select * From master..spt_values',null,null )
Returns
In SQL Server you can also highlight the tablename in a query then press ALT+F1 to show the highlighted table info.

Test for a column within a Select statement

Is it possible to test for a column before selecting it within a select statement?
This may be rough for me to explain, I have actually had to teach myself dynamic SQL over the past 4 months. I am using a dynamically generated parameter (#TableName) to store individual tables within a loop (apologize for the vagueness, but the details aren't relevant).
I then want to be able to be able to conditionally select a column from the table (I will not know if each table has certain columns). I have figured out how to check for a column outside of a select statement...
SET #SQLQuery2 = 'Select #OPFolderIDColumnCheck = Column_Name From INFORMATION_SCHEMA.COLUMNS Where Table_Name = #TABLENAME And Column_Name = ''OP__FolderID'''
SET #ParameterDefinition2 = N'#TABLENAME VARCHAR(100), #OPFolderIDColumnCheck VARCHAR(100) OUTPUT'
EXECUTE SP_EXECUTESQL #SQLQuery2, #ParameterDefinition2, #TABLENAME, #OPFolderIDColumnCheck OUTPUT
IF #OPFolderIDColumnCheck IS NULL
BEGIN
SET #OP__FOLDERID = NULL
END
ELSE
IF #OPFolderIDColumnCheck IS NOT NULL
BEGIN
...etc
but id like to be able to do it inside of a select statement. Is there a way to check and see if OP__FOLDERID exists in the table?
Id like to be able to do something like this:
SELECT IF 'OP__FOLDERID' EXISTS IN [TABLE] THEN 'OP__FOLDERID' FROM [TABLE]
Thank you for any help or direction you can offer.
I'm afraid there isn't any direct way to do this within a SELECT statement at all. You can determine if a column exists in a table, however, and construct your dynamic SQL accordingly. To do this, use something like this:
IF COL_LENGTH('schemaName.tableName', 'columnName') IS NOT NULL
BEGIN
-- Column Exists
END
You could then set a variable as a flag, and the code to construct the dynamic SQL would construct the expression with/without the column, as desired. Another approach would be to use a string value, and set it to the column name if it is present (perhaps with a prefix or suffix comma, as appropriate to the expression). This would allow you to save writing conditionals in the expression building, and would be particularly helpful where you have more than one or two of these maybe-columns in a dynamic expression.

How to find any lower case data/field in all columns of a table (tsql)

I have a table with about 10 columns and contains about 5000 rows of data. I want to figure out if any field of any column is populated in lower case, then I need to fix it. Because, I need all columns to be in upper case for the ETL process.
I guess if there is a query that turns all alphanumeric columns or any column in upper case should work. But I'm curious to know as well how to find the lower case fields in the whole table for all columns so I know what needs to be changed.
Take this as an example table
Table: Student;
Columns: f_name, l_name, id, address, city, state, zipcode
OP mentioned he wanted to see the changes before changing them. This creates a temporary table which displays the changes and then rolls back the UPDATE query.
BEGIN TRAN
DECLARE #Changes TABLE (
OLD_f_name VARCHAR(MAX)
,NEW_f_name VARCHAR(MAX)
)
UPDATE Student
SET f_name = UPPER(f_name)
OUTPUT deleted.f_name
,inserted.f_name
INTO #Changes(OLD_f_name, NEW_f_name);
SELECT * FROM #Changes
ROLLBACK TRAN
To actually do the update, use COMMIT TRAN instead of ROLLBACK TRAN.
You can do this query for every column you want, I suggest to do them one by one to avoid any unexpected mistake :
UPDATE table_name SET column_name = UPPER(column_name)
Using UPPER function, you can convert a character expression with lowercase character data converted to uppercase. In this case, below SQL should work.
UPDATE Table SET ColumnName = UPPER (ColumnName)
To check, use below SQL:
SELECT * FROM Table WHERE UPPER(ColumnName) != ColumnName
COLLATE Latin1_General_CS_AS

Create a stored procedure to iterate through a list of tables and truncate them in MySQL

I'm debating whether or not to try running through a list of tables and truncating them with a stored procedure. Would it be that easy with MySql and how would I do it?
The main piece of info you need is the list of tables. Most platforms support this:
select table_name from information_schema.tables
However, before you code the sproc, do a select * from information_schema.tables and examine the entries, there may be some you do not expect -- system tables and such, so you may need to craft a filter to get the set you want.
Since I don't do mySQL that much, I can't show you the code, but if you can translate this from MS SQL, and fill in some blanks you can make it work:
declare #table_name varchar(200)
while 1=1 begin
select top 1 #table_name = table_name
from information_schema.tables
where ....possible filter...
if #table_name is null break
-- for this line you may need dynamic sql
truncate table #table_name
end

mysql, iterate through column names

I would like to get all of the column names from a MySQL table, loop through each column name and then run a stored procedure using those column names as a variable. Something to the effect of:
colnames = get column names from table
for each colname
if something changed then
do something
else
do something else
It looks like SHOW COLUMNS FROM myTable will give me the column names, but how would I get the column names into a loop?
I would really like to run all of this in a stored procedure using native SQL. Since I'm still learning the intricacies of MySQL, and this would really help out my project. Thanks for your help.
I think you want something like this:
DECLARE col_names CURSOR FOR
SELECT column_name
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = 'tbl_name'
ORDER BY ordinal_position;
select FOUND_ROWS() into num_rows;
SET i = 1;
the_loop: LOOP
IF i > num_rows THEN
CLOSE col_names;
LEAVE the_loop;
END IF;
FETCH col_names
INTO col_name;
//do whatever else you need to do with the col name
SET i = i + 1;
END LOOP the_loop;
You can write a query against information_schema to get the column names:
SELECT column_name
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = 'tbl_name'
ORDER BY ordinal_position
The column names are then returned just as any data from a table would be.