Replacing null values automatically for a specific set of tables in SQL Server - sql

I would like to write a query that can update all values on any given table to this -- given that I have many columns across multiple tables the function needs to be universal meaning i can run it without specifying column names, for it simply to identify null values and update them with my value of -- I'm not sure the best way to accomplish this and wrap it into a function I can call when someone INSERTS into any of the tables affected.
I've looked at COALESE as a possible option but any examples would be appreciated.
My table looks like: (I have over 30 tables with 100+ fields so writing out Updates for each field individually sounds like a nightmare, there must be a better way)
ID Name Email Phone
1 John john#aol.com 234-234-2344
2 Mary mary#test.com 332-134-5424
3 Simon null null
4 Kevin null 345-453-2135
5 Kelly kelly#msn.com null
I'd like to replace all nulls with -- permanantly in my table probably using an UPDATE statement.
Any ideas appreciated.

Following SQL will help you to list down all the tables and column names. And you can build a dynamic SQL thingy around this result set to achieve what you want.
SELECT DISTINCT
--SCHEMA_NAME(schema_id) AS schema_name,
t.name AS TableName,
c.name AS ColumnName
FROM sys.tables AS t
INNER JOIN sys.columns c ON t.OBJECT_ID = c.OBJECT_ID
ORDER BY 1,2;
EDIT:
Otherwise, the following link got a solution to your problem.
SQL Server Find and Replace Values in All Tables and All Text Columns

Umm, you are really overcomplicating this. I would suggest instead:
alter table t
alter column phone not null default '--';
Before doing this, update the column so there are no NULL values:
update t
set phone = '--'
where phone is null;
And, I should throw in that I think this is a bad idea. You are confusing "data" with "representation". In an application, you want to show -- for a NULL value. But I think NULL is the best way to represent the missing value in a database.
(And, of course, you need to do the above for each column you care about.)

Related

Create column name based on value without execute

I need to create a column name based on the value of other columns. I need to return a value from a column, but the specific name depends on the value insert on other table.
From intance:
Table A
Column1 | Column2
1 2
Base on that values I need to go to the table B to the column "VE12".
I need this dynamiclly, so the execute(#query) is my last option and I would like to avoid CASE WHEN statments because I have more than 50 options.
My query will be something like:
select case when fn.tab=8 and fo.pais=3 then cp.ve83 end
FROM fn
INNER JOIN fo ON fo.stamp = fn.stamp
INNER JOIN cp
If the value in the column tab is 8 and the value in column pais is 3 I should return the value in column ve83.
Thanks for all the help!
The only sensible option is to go back to the business meaning of the data and redesign the database according to that, instead of according to "technique-oriented abstractions" such as these that SQL was never intended to support.
The main reason for this is that SQL was founded on FIRST order logic, and this precludes supporting stuff like varying domains. Which you are doing (or at least seeking to do) because ve12 could be a DATETIME and ve83 could be a VARCHAR and ve56 coulb be a BLOB etc. etc. So there is just no way for you [or anyone else] to determine the data type of the results in your query, and it is even more impossible to attach meaning to what comes out of your desired query precisely because of this varying-domain and varying-source characteristic.

Mysql Query data filled check

I had created the table with 200 columns and i had inserted data
Now i need to check that specific 100 columns in one row are filled or not,how can we check this using mysql query .the primary key is defined .please help me out how to resolve this.
select * from tablename where column1 != null or column2 != null ......
That is a lot of columns so at the risk of being mysql server version specific you can use the information schema to get the column names and then write a SQL procedure or something in your chosen shell / language that iterates over them performing a test.
select distinct COLUMN_NAME as 'Field', IS_NULLABLE from information_schema.columns where TABLE_SCHEMA="YourDatabase" and TABLE_NAME="YourTableName" and TABLE_NAME not like "%view%" escape '!' ;
The example above will tell you the column name as "Field" and tell you if it can hold a NULL. Having the field name may give you a better way of automating a field name specific test.

Row with unknown values to column SQL Server 2005

I'm new to SQL Server programming, so this may or may not be a stupid question.
So, first I do not know what my input table is (my task is supposed to work with ANY table).
Second, I get the column names using sp_help and then I select only that column into another table. Now I need the rows from COLUMN_NAME to be the names of god knows how many columns into some new table.
I tried something using PIVOT, but I can't seem to make it work.
It sounds like you want to access the metadata tables. Something like this may put you in the right direction:
insert into column_name(name)
select column_name
from information_schema.columns
where table_name = XXX <----- YOUR TABLE GOES HERE

SQL Question checking nulls

I'm very new to sql. I am on this project where I have to check if something is null and if it is I have to change it to zero but there are many tables that I would have to do this and many columns. I was wondering if there was a way that I can check the whole table for nulls instead of checking every column of every table.
Michelle, no you need to check every column for NULLS. The bigger question is why are NULLS being allowed? While I'm not an advocate for never having NULLS in a database (I believe that they have their purpose), an excessive number of NULL values in a table is a good indicator that the database is not normalized properly or has other architectural issues.
It does depend on the platform, but in some cases you can use the system table information to get a list of all of the columns, and utilise this to generate queries to verify every column in every table.
However, that would be quite a hack. The real questions are a) why are there so many nulls ( there might be good reasons, but it does suggest that the structure is wrong, as per Wil ) and b) why is there a sudden need to change then all to zeros? Does this only apply to numeric fields? There are so many other questions that you need to ask before a clear solution becomes clear.
You say you have to change any NULL values to 0, so perhaps the easiest way would be to use COALESCE(value, 0).
COALESCE(value, value2, value3) is a shortcut to a CASE statement like
CASE
WHEN value1 IS NOT NULL THEN value1
WHEN value2 IS NOT NULL THEN value2
...
END
Edit:
If you actually want to update all NULLS to 0 on the table, you could do the following SQL statement:
SELECT 'UPDATE '
+ OBJECT_NAME(OBJECT_ID)
+ ' SET '
+ sc.name
+ ' = 0 WHERE '
+ sc.name
+ ' IS NULL'
FROM sys.columns sc
INNER JOIN sys.types st ON st.system_type_id = sc.system_type_id
WHERE st.name IN ('bigint', 'int', 'smallint')
AND OBJECT_NAME(OBJECT_ID) = 'YourTable'
Which will product a text string that you should be able to copy and paste and run, or run programatically in a loop. It depends on your columns having a number data type, and could be dangerous if you have any such columns whose NULLs you actually want to stay as null. You could take out that last part of the WHERE clause to run it for all tables, but you may want to test and validate beforehand.
I don't have a SQL Server instance at the ready to test on, so this comes with the generic "use at your own risk" disclaimer. :-)
Select nvl(col,'0') from table ;
NVL will work fine in oracle.
NVL will check if col is null, if it is null it will change it to zero.

How can I turn a column name into a result value in SQL Server?

I have a table which has essentially boolean values in a legacy database. The column names are stored as string values in another table so I need to match the column names of one table to a string value in another table. I know there has to be a way to do this directly with SQL in SQL Server but it is beyond me.
My initial thought was to use PIVOT but it is not enabled by default and enabling it would likely be a difficult process with pushing that change to the Production database. I would prefer to use what is enabled by default.
I am considering using COALESCE to translate the boolean value to the string that value that I need. This will be a manual process.
I think I will also use a table variable to insert the results of the first query into that variable and use those results to do the second query. I still have the problem that the columns are on a single row so I wish I could easily pivot the values to put the column names in the result set as strings. But if I could easily do that I could easily write the query with a sub-select.
Any tips are welcome.
Checkout Sysobjects and SysColumns in SQL Server. They are 2 SQL tables that gives you the names of the tables in your DB and the names of the columns that go with that table.
The system view INFORMATION_SCHEMA.COLUMNS will also give you what you want.
You can build a SQL string and then execute that string as a query. Not the prettiest by any means but I think it would work the way you want it to. You would just use a cursor or while loop to build the string.
If you're comfortable with .Net you could just write your own stored proc in your language of choice and manipulate the data in code instead.
Heres a link to get started
CLR Stored Procedures
I'm not quite sure I understand how your design is currently put together (could you post an example?), but the information_schema.columns view will give you a table containing all the column names as string values. If you join your second table against that I think you'll probably get what you need.
For Example, i have a table STATEtbl having 3 columns and i want to get all the column names of this table as ROW values... i use the below query
Select SC.name as Columns from Syscolumns SC
Join Sysobjects SO On SC.id = SO.Id
where Object_name(SO.Id) = 'STATEtbl'
Result of the query:
Columns
--------
State
StateCode
StateFullName